/ concept-collection / turing-sphere-2
Sign in
concept-collection / turing-sphere-2
turing-sphere-2 / scripts / bench.ts
271 lines · 8.7 KBBlameHistoryRaw
1/**
2 * Command-line benchmark: run exactly the simulation the browser app is
3 * running — same solver, same transforms, same parameters — on desktop WebGPU
4 * (Google Dawn, via the optional `webgpu` package) or on the f64 CPU
5 * reference, and report ms/step. The app prints the matching command under
6 * its stats line; copy it and run it here for an apples-to-apples comparison.
7 *
8 * node scripts/bench.mjs --preset schnak-spots --lmax 63 --backend webgpu \
9 * --steps 2000 --seed 1 --a 0.1 --b 0.9 --D1 0.0004 --D2 0.008 --dt 0.05
10 *
11 * The only thing missing here is the rendering: this is the solver alone.
12 * Entry point is scripts/bench.mjs, which copes with older Node versions.
13 */
14import {
15 GpuBackend,
16 CpuBackend,
17 requestShtDevice,
18 describeAdapter,
19 type ShtBackend,
20} from '../src/solver/backend.ts';
21import { Simulation } from '../src/solver/simulation.ts';
22import { presets } from '../src/solver/models.ts';
23import {
24 parseArgs,
25 modelForSpec,
26 configForSpec,
27 resolvePreset,
28 formatCommand,
29 BENCH_COMMAND,
30 DEFAULT_LMAX,
31 DEFAULT_SEED,
32 DEFAULT_STEPS,
33 DEFAULT_WARMUP,
34 DEFAULT_BACKEND,
35 type RunSpec,
36} from '../src/bench/runSpec.ts';
38const USAGE = `usage: ${BENCH_COMMAND} [options]
40 --preset <key> ${presets.map((p) => p.key).join(' | ')}
41 (default ${presets[0].key})
42 --lmax <n> spherical harmonic truncation (default ${DEFAULT_LMAX})
43 --backend <kind> webgpu | cpu (default ${DEFAULT_BACKEND})
44 --steps <n> timed steps (default ${DEFAULT_STEPS})
45 --warmup <n> untimed steps first (default ${DEFAULT_WARMUP})
46 --seed <n> initial-noise seed (default ${DEFAULT_SEED})
47 --<param> <v> any parameter of the preset's model, e.g. --dt 0.05
48 --json machine-readable output
49 --help
51The browser app shows the command for whatever it is currently simulating;
52copy it from under the stats line to compare the same run here.`;
54function fail(msg: string, code = 1): never {
55 console.error(`bench: ${msg}`);
56 process.exit(code);
58const errMsg = (e: unknown): string => (e instanceof Error ? e.message : String(e));
60// ---------------------------------------------------------------- arguments
61const argv = process.argv.slice(2);
62if (argv.includes('--help') || argv.includes('-h')) {
63 console.log(USAGE);
64 process.exit(0);
66const wantJson = argv.includes('--json');
67let spec: RunSpec;
68try {
69 spec = parseArgs(argv.filter((a) => a !== '--json'));
70} catch (e) {
71 fail(`${errMsg(e)}\n\n${USAGE}`, 2);
74// ---------------------------------------------------------------- WebGPU
75/**
76 * Install Dawn under the globals the transform code expects (navigator.gpu,
77 * GPUBufferUsage, ...), so src/ runs here unchanged — including
78 * requestShtDevice(), which is the same device request the browser makes.
79 * The specifier is indirect so that typechecking does not require the
80 * optional package to be installed.
81 */
82async function installWebGpu(): Promise<string> {
83 const specifier = 'webgpu';
84 let mod: {
85 create: (flags: string[]) => GPU;
86 globals: Record<string, unknown>;
87 };
88 try {
89 mod = await import(specifier);
90 } catch {
91 throw new Error(
92 'desktop WebGPU needs the optional `webgpu` package (prebuilt Google Dawn):\n' +
93 ' npm install webgpu\n' +
94 'or run with --backend cpu.',
95 );
96 }
97 Object.assign(globalThis, mod.globals);
98 // DAWN_FLAGS is ';'-separated because individual Dawn options take
99 // comma-separated lists, e.g. 'enable-dawn-features=allow_unsafe_apis,timestamp_quantization'
100 const dawnFlags = process.env.DAWN_FLAGS?.split(';').filter(Boolean) ?? [];
101 Object.defineProperty(globalThis, 'navigator', {
102 value: { gpu: mod.create(dawnFlags) },
103 configurable: true,
104 writable: true,
105 });
106 const { version } = await import(`${specifier}/package.json`, {
107 with: { type: 'json' },
108 }).then(
109 (m) => m.default as { version: string },
110 () => ({ version: '?' }),
111 );
112 return `node-webgpu ${version} (Google Dawn)`;
115// ---------------------------------------------------------------- statistics
116interface Timing {
117 meanMs: number;
118 medianMs: number;
119 p05Ms: number;
120 p95Ms: number;
121 minMs: number;
122 totalMs: number;
123 stepsPerSec: number;
126function timing(samples: Float64Array): Timing {
127 const sorted = Float64Array.from(samples).sort();
128 const q = (p: number): number =>
129 sorted[Math.min(sorted.length - 1, Math.floor(p * sorted.length))];
130 let total = 0;
131 for (const v of samples) total += v;
132 const mean = total / samples.length;
133 return {
134 meanMs: mean,
135 medianMs: q(0.5),
136 p05Ms: q(0.05),
137 p95Ms: q(0.95),
138 minMs: sorted[0],
139 totalMs: total,
140 stepsPerSec: 1000 / mean,
141 };
144function fieldRange(v: ArrayLike<number>): { min: number; max: number } {
145 let min = Infinity;
146 let max = -Infinity;
147 for (let i = 0; i < v.length; i++) {
148 if (v[i] < min) min = v[i];
149 if (v[i] > max) max = v[i];
150 }
151 return { min, max };
154// ---------------------------------------------------------------- run
155const model = modelForSpec(spec);
156const { preset } = resolvePreset(spec.preset);
157const cfg = configForSpec(spec);
159let device: GPUDevice | null = null;
160let backend: ShtBackend | null = null;
161let runtime = 'CPU (direct summation, f64)';
162let adapter = '';
164try {
165 if (spec.backend === 'webgpu') {
166 runtime = await installWebGpu();
167 device = await requestShtDevice();
168 adapter = await describeAdapter(device);
169 backend = await GpuBackend.create(device, cfg);
170 } else {
171 backend = new CpuBackend(cfg);
172 }
174 const sim = new Simulation(backend, model, spec.params);
175 await sim.init(spec.seed);
177 if (!wantJson) {
178 const kind =
179 spec.backend === 'webgpu'
180 ? `WebGPU fp32${adapter ? ` — ${adapter}` : ''}`
181 : 'CPU f64';
182 console.log(`turing-sphere bench — solver only, no rendering\n`);
183 console.log(` preset ${preset.label} (model ${model.key}: ${model.species.join(', ')})`);
184 console.log(
185 ` params ${model.params.map((p) => `${p.key}=${spec.params[p.key]}`).join(' ')}`,
186 );
187 console.log(
188 ` grid lmax ${cfg.lmax} · ${cfg.nlat}×${cfg.nphi} · nlm ${backend.nlm.toLocaleString()}`,
189 );
190 console.log(` backend ${kind}\n ${runtime}`);
191 console.log(` run ${spec.warmup} warmup + ${spec.steps} timed steps, seed ${spec.seed}\n`);
192 }
194 for (let s = 0; s < spec.warmup; s++) await sim.step();
196 const samples = new Float64Array(spec.steps);
197 const progress = !wantJson && process.stderr.isTTY;
198 let lastReport = performance.now();
199 let running = 0;
200 for (let s = 0; s < spec.steps; s++) {
201 const t0 = performance.now();
202 await sim.step();
203 samples[s] = performance.now() - t0;
204 running += samples[s];
205 if (progress && performance.now() - lastReport > 1000) {
206 process.stderr.write(
207 `\r\x1b[K ${s + 1}/${spec.steps} steps · ${(running / (s + 1)).toFixed(2)} ms/step`,
208 );
209 lastReport = performance.now();
210 }
211 }
212 if (progress) process.stderr.write('\r\x1b[K');
214 const t = timing(samples);
215 const range = fieldRange(sim.V[0]);
216 let finite = true;
217 for (const v of sim.V[0]) if (!Number.isFinite(v)) finite = false;
219 if (wantJson) {
220 console.log(
221 JSON.stringify(
222 {
223 command: formatCommand(spec),
224 spec,
225 model: model.key,
226 backend: { kind: spec.backend, adapter, runtime },
227 grid: { lmax: cfg.lmax, nlat: cfg.nlat, nphi: cfg.nphi, nlm: backend.nlm },
228 timing: t,
229 state: {
230 t: sim.t,
231 steps: sim.stepCount,
232 species: model.species[0],
233 min: range.min,
234 max: range.max,
235 contrast: range.max - range.min,
236 finite,
237 },
238 },
239 null,
240 2,
241 ),
242 );
243 } else {
244 console.log(
245 ` ${t.meanMs.toFixed(2)} ms/step ${t.stepsPerSec.toFixed(1)} steps/s ` +
246 `${(spec.params.dt * t.stepsPerSec).toFixed(2)} model time/s`,
247 );
248 console.log(
249 ` median ${t.medianMs.toFixed(2)} · p05 ${t.p05Ms.toFixed(2)} · ` +
250 `p95 ${t.p95Ms.toFixed(2)} · min ${t.minMs.toFixed(2)} ms ` +
251 `(${(t.totalMs / 1000).toFixed(1)} s total)`,
252 );
253 console.log(
254 ` after ${sim.stepCount} steps: t = ${sim.t.toFixed(2)}, ` +
255 `${model.species[0]} ∈ [${range.min.toFixed(4)}, ${range.max.toFixed(4)}] ` +
256 `(contrast ${(range.max - range.min).toFixed(4)})${finite ? '' : ' — NOT FINITE'}`,
257 );
258 console.log(
259 `\n Compare with the ms/step in the app's stats line. That one is also the\n` +
260 ` solver alone, but measured while the page renders the spheres.`,
261 );
262 }
264 backend.destroy();
265 device?.destroy();
266 process.exit(finite ? 0 : 1);
267} catch (e) {
268 backend?.destroy();
269 device?.destroy();
270 fail(errMsg(e));
moveopenescclose