/ concept-collection / turing-surface
concept-collection / turing-surface
232 lines · 8.0 KBBlameHistoryRaw
1/**
2 * Browser validation, in the environment the demo actually ships to.
3 *
4 * Runs the same four check modules as `npm run test:node` — so both GPU stacks
5 * (Dawn on the desktop, the browser's own here) get the same guarantees — plus a
6 * long soak that only makes sense in a page.
7 *
8 * Results are posted to window.__RESULTS__ for the headless runner.
9 */
10import { requestShtDevice, describeAdapter } from '../src/sht/sht.ts';
11import { ModelSession } from '../src/mgpu/session.ts';
12import { mModels, defaultParams } from '../src/mgpu/registry.ts';
13import { digestOf, formatDigest, type StateDigest } from '../src/mgpu/digest.ts';
14import {
15 parseArgs,
16 modelForSpec,
17 geometryForSpec,
18 formatCommand,
19 DEFAULT_NITER,
20} from '../src/bench/runSpec.ts';
21import {
22 mGeometryByKey,
23 defaultGeometryParams,
24 DEFAULT_GEOMETRY_KEY,
25} from '../src/geom/registry.ts';
26import { transformChecks } from './transformChecks.ts';
27import { analyticChecks } from './analyticChecks.ts';
28import { modelChecks } from './modelChecks.ts';
29import { geometryChecks } from './geometryChecks.ts';
30import { fluxChecks } from './fluxChecks.ts';
32declare global {
33 interface Window {
34 __RESULTS__?: { ok: boolean; fatal?: string; lines: string[] };
35 /** Set by the ?state= mode, for scripts/compare-env.mjs. */
36 __STATE__?: { digest: StateDigest; state: number[] };
37 /** Set by the ?soak= mode, for scripts/compare-perf.mjs. */
38 __SOAK__?: {
39 lmax: number;
40 steps: number;
41 batch: number;
42 solverMsPerStep: number;
43 encodeMsPerStep: number;
44 adapter: string;
45 fourier: 'fft' | 'dft';
46 };
47 }
50const logEl = document.getElementById('log')!;
51const lines: string[] = [];
52let failures = 0;
54function log(s: string): void {
55 lines.push(s);
56 logEl.textContent = lines.join('\n');
57 console.log(s);
60function check(name: string, ok: boolean, detail: string): void {
61 log(`${ok ? 'PASS' : 'FAIL'} ${name} ${detail}`);
62 if (!ok) failures++;
65/**
66 * Solver-only soak, selected with ?soak=<steps>&lmax=<n>.
67 *
68 * No three.js at all, so this is the browser's honest solver rate: the same
69 * batched, no-readback measurement the desktop benchmark reports. If this number
70 * matches the benchmark's but the app's frame cost does not, the difference is
71 * the readback and competing with the renderer for the GPU, not the computation.
72 */
73async function soak(steps: number, lmax: number): Promise<void> {
74 const device = await requestShtDevice();
75 const model = mModels[0];
76 // The desktop benchmark this is compared against resolves its geometry and
77 // iteration count from the same two constants. They have to agree: the
78 // iteration count is unrolled into the step, so a mismatch would compare
79 // two different amounts of work and call the difference "the browser".
80 const geometry = mGeometryByKey(DEFAULT_GEOMETRY_KEY)!;
81 const session = await ModelSession.create({
82 device,
83 model,
84 params: defaultParams(model),
85 lmax,
86 geometry,
87 geometryParams: defaultGeometryParams(geometry),
88 niter: DEFAULT_NITER,
89 });
90 session.seed(5);
91 log(
92 `soak: ${steps} steps at lmax ${lmax} ` +
93 `(grid ${session.cfg.nlat}x${session.cfg.nphi}, ${geometry.key}, ` +
94 `${DEFAULT_NITER} solve iter, ${session.describe().step.length} ops/step), solver only`,
95 );
97 const BATCH = 25;
98 // Timed separately from the sampling: `solverMs` counts only submitted steps
99 // waited for, never read back, so it is comparable to `npm run bench`.
100 let solverMs = 0;
101 let solverSteps = 0;
102 let encodeMs = 0;
103 const t0 = performance.now();
104 for (let s = 0; s < steps; s += BATCH) {
105 const n = Math.min(BATCH, steps - s);
106 const b0 = performance.now();
107 session.step(n);
108 // CPU-side command encoding, separated from GPU execution: in a browser each
109 // WebGPU call crosses Blink's bindings and Dawn's validation, so on a fast
110 // GPU the encoding can be what actually limits the step rate.
111 const b1 = performance.now();
112 encodeMs += b1 - b0;
113 await session.sync();
114 solverMs += performance.now() - b0;
115 solverSteps += n;
116 const u = await session.read(model.species[0]);
117 let lo = Infinity;
118 let hi = -Infinity;
119 for (const v of u) {
120 if (v < lo) lo = v;
121 if (v > hi) hi = v;
122 }
123 if ((s + BATCH) % 100 === 0) {
124 const mem = (performance as Performance & { memory?: { usedJSHeapSize: number } })
125 .memory;
126 log(
127 ` step ${session.steps} u in [${lo.toFixed(4)}, ${hi.toFixed(4)}]` +
128 (mem ? ` heap ${(mem.usedJSHeapSize / 1048576).toFixed(1)} MB` : ''),
129 );
130 // yield so the page stays responsive and the runner can poll
131 await new Promise((r) => setTimeout(r, 0));
132 }
133 }
134 const ms = (performance.now() - t0) / steps;
136 const final = await session.read(model.species[0]);
137 let finite = true;
138 for (const v of final) if (!Number.isFinite(v)) finite = false;
139 const solverPerStep = solverMs / solverSteps;
140 const encodePerStep = encodeMs / solverSteps;
141 check(
142 `soak: ${steps} steps survived`,
143 finite,
144 `solver ${solverPerStep.toFixed(2)} ms/step (batches of ${BATCH}, no readback), ` +
145 `of which ${encodePerStep.toFixed(3)} ms/step CPU encoding, ` +
146 `${ms.toFixed(2)} ms/step incl. sampling readback`,
147 );
148 log(
149 ` compare 'solver' with the ms/step from \`npm run bench -- --lmax ${lmax}\`:\n` +
150 ` same .m, same kernels, no rendering on either side.`,
151 );
153 window.__SOAK__ = {
154 lmax,
155 steps,
156 batch: BATCH,
157 solverMsPerStep: solverPerStep,
158 encodeMsPerStep: encodePerStep,
159 adapter: await describeAdapter(device),
160 fourier: session.sht.fourierMode,
161 };
162 session.destroy();
163 window.__RESULTS__ = { ok: failures === 0, lines };
164 log(failures === 0 ? 'ALL PASS' : `${failures} FAILURE(S)`);
167/**
168 * Run one exact spec and post its final state, for scripts/compare-env.mjs to
169 * compare against the same spec run on the desktop. Query parameters map
170 * straight onto the benchmark's flags — `?state=1&lmax=31&steps=200` — and go
171 * through the same parseArgs, so neither side can quietly use different
172 * defaults.
173 */
174async function dumpState(q: URLSearchParams): Promise<void> {
175 const argv: string[] = [];
176 for (const [k, v] of q) {
177 if (k === 'state') continue;
178 argv.push(`--${k}`, v);
179 }
180 const spec = parseArgs(argv);
181 const model = modelForSpec(spec);
183 const device = await requestShtDevice();
184 const adapter = await describeAdapter(device);
185 const session = await ModelSession.create({
186 device,
187 model,
188 params: spec.params,
189 lmax: spec.lmax,
190 geometry: geometryForSpec(spec),
191 geometryParams: spec.geometryParams,
192 niter: spec.niter,
193 });
194 session.seed(spec.seed);
195 session.step(spec.steps);
196 await session.sync();
197 const state = await session.read(model.state[0]);
198 const digest = digestOf(state, session.sht.fourierMode, adapter);
200 log(`${formatCommand(spec)}\n`);
201 log(`state after ${spec.steps} steps from seed ${spec.seed}:`);
202 log(` ${formatDigest(digest)}`);
203 log(` adapter: ${adapter}`);
204 window.__STATE__ = { digest, state: [...state] };
205 session.destroy();
208async function main(): Promise<void> {
209 const q = new URLSearchParams(location.search);
210 if (q.has('state')) return dumpState(q);
211 if (q.has('soak')) {
212 return soak(Number(q.get('soak')) || 500, Number(q.get('lmax')) || 63);
213 }
214 const device = await requestShtDevice();
216 await transformChecks(device, check, log);
217 await analyticChecks(device, check, log);
218 await modelChecks(device, check, log);
219 // The sweep is opt-in here (?sweep=1): it is a few seconds on desktop Dawn
220 // but minutes in a browser, where each session recompiles its unrolled step.
221 await geometryChecks(device, check, log, { sweep: q.has('sweep') });
222 await fluxChecks(device, check, log, { ab: q.has('sweep') });
224 window.__RESULTS__ = { ok: failures === 0, lines };
225 log(failures === 0 ? 'ALL PASS' : `${failures} FAILURE(S)`);
228main().catch((e) => {
229 const msg = e instanceof Error ? `${e.message}\n${e.stack ?? ''}` : String(e);
230 log(`fatal: ${msg}`);
231 window.__RESULTS__ = { ok: false, fatal: msg, lines };
232});