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