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