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