2dedc35turing-sphere: reaction-diffusion on the sphere, spectral solver on WebGPUJeremy Magland 1# turing-sphere
3Reaction–diffusion systems (Turing patterns) solved **live in the browser on the
4surface of a sphere**, using a spectral spherical-harmonic method with the
5transforms running on the GPU via WebGPU.
61e12f1Write the solver in MATLAB and compile it to WebGPUJeremy Magland 7The solver itself is **MATLAB**. The `.m` files under [`models/`](models/) are the
8algorithm — [numbl](https://numbl.org) parses and lowers them in the browser, and
9each element-wise line becomes a WebGPU compute kernel. You can edit the MATLAB
10on the page and watch the pattern change.
c47b479Point the demo link back at the original repo's Pages siteJeremy Magland 12**Live demo:** <https://concept-collection.github.io/turing-sphere/>
14## What it does
16It solves the N-species system
18```
19d(u_k)/dt = D_k*lap_s(u_k) + f_k(t, x, y, z, u_1, ..., u_N), k = 1, ..., N
20```
22on the unit sphere, where `lap_s` is the Laplace–Beltrami operator. Diffusion is
23treated implicitly in spherical-harmonic coefficient space, where `lap_s` is
24diagonal with eigenvalues `-l(l+1)`; reaction is treated explicitly on the grid.
25The two are combined with a first-order IMEX Euler step — the entire time loop is
27```
28V_k = synth(U_k) # spectral -> grid
29R_k = analys(f_k(t, x, y, z, V_1..V_N)) # reaction on grid -> spectral
30U_k = (U_k + dt*R_k) / (1 + dt*D_k*l(l+1))
31```
33You watch the patterns emerge in real time on orbitable 3D spheres (one per
34species, cameras synced), with pause/resume, re-seeding, live parameter editing,
163ec45Render on demand, display oversampling, and jump-free solver timingJeremy Magland 35and colormap selection. The display can oversample the solver — the state is
36spectral, so evaluating it on a finer grid for rendering is exact
37interpolation, not smoothing. This never touches the solver or its grid; by
38default it turns on only when the solver grid is coarse.
61e12f1Write the solver in MATLAB and compile it to WebGPUJeremy Magland 40Three models are included, one `.m` file each:
42- **[Schnakenberg](models/schnakenberg.m)** — Turing spots (unstable band
43 14 ≤ l ≤ 40, peak l = 24)
44- **[Brusselator](models/brusselator.m)** — stripes and spots from a stiffer reaction
45- **[Allen–Cahn](models/allencahn.m)** — a single species whose interfaces form
46 and coarsen
48## MATLAB, compiled to WebGPU
61e12f1Write the solver in MATLAB and compile it to WebGPUJeremy Magland 50A model file is ordinary MATLAB defining two functions — `init` builds the initial
51spectral state, `step` advances it one timestep:
53```matlab
54function [Un, Vn, u, v] = step(U, V, lam, a, b, D1, D2, dt)
55 u = synth(U);
56 v = synth(V);
57 uuv = u .* u .* v;
58 Un = (U + dt * analys(a - u + uuv)) ./ (1 + (dt * D1) * lam);
59 Vn = (V + dt * analys(b - uuv)) ./ (1 + (dt * D2) * lam);
60end
61```
63Getting from there to the GPU uses numbl for everything up to the IR, and this
64repo only for the backend:
661. **numbl parses and lowers.** Each function is specialized for the concrete
67 argument types of the current grid, via the same `specializeUserFunction`
68 entry point numbl's own JIT uses. Types and array shapes are fixed at this
69 point, so the backend never has to re-decide what an operation means.
702. **numbl's inline pass fuses.** Lowering emits one statement per *operator*
71 (ANF); `inlinePass` folds single-use temps back into their consumer, so one
72 line of MATLAB becomes one expression tree. `uuv = u .* u .* v` arrives as a
73 single statement, not three.
743. **This repo emits WGSL** ([`src/mgpu/wgsl.ts`](src/mgpu/wgsl.ts)). Each
75 element-wise statement becomes one compute kernel that computes one output
76 element per invocation — the WebGPU counterpart of numbl's own C-side fused
77 emitter. Anything it cannot express is refused at compile time with a source
78 position, never silently mis-compiled.
794. **`synth` / `analys` are external operations.** numbl learns their type rules
80 from a `.mtoc2.js` workspace file — its sanctioned extension point for a
81 JS-defined builtin — and the backend maps each call onto the existing
82 spherical-harmonic compute pipelines.
84The Schnakenberg step above compiles to 11 GPU operations: 4 transforms, 5
85generated kernels, and 2 buffer copies feeding the new state back.
87Two consequences worth noting:
89- **The step is synchronous.** WebGPU's encode path (`writeBuffer`, dispatch,
90 `submit`) is all synchronous; only readback and pipeline creation are async, and
91 every pipeline is built once at compile time. So a timestep is pure command
92 recording — the whole batch goes out in one submit, and the only `await` in the
93 loop is the single readback per rendered frame. numbl's own execution being
94 synchronous is therefore not an obstacle: nothing about the algorithm needs to
95 block.
96- **Parameters are uniforms, not constants.** Tunable scalars are deliberately
97 lowered without exact values, so moving a slider rewrites a small buffer
98 instead of triggering a recompile. Editing the MATLAB recompiles; changing `dt`
99 does not.
101## Provenance
103This is the browser port of a MATLAB reference implementation
104(`SphericalReactionDiffusion.m`, "websph"), which defines the solver through a
105four-member porting boundary: `coeffs2vals`, `vals2coeffs`, `grid.lat`,
106`grid.lon`. Profiling of the MATLAB version shows the transforms are ~96% of
107compute, so this port swaps in:
109- **Transforms:** [shtns-webgpu](https://github.com/concept-collection/shtns-webgpu) —
110 fp32 spherical harmonic transforms in WGSL compute shaders, modeled on
111 [SHTNS](https://nschaeff.bitbucket.io/shtns/). Its source is vendored under
112 [`src/sht/`](src/sht/) (CECILL-2.1), including the f64 CPU reference
b689087Benchmark the WGSL transforms against upstream SHTNSJeremy Magland 113 transform used for testing. [`bench/shtns/`](bench/shtns/) builds the real
114 SHTNS and measures ours against it — see
115 [Against upstream SHTNS](#against-upstream-shtns).
2dedc35turing-sphere: reaction-diffusion on the sphere, spectral solver on WebGPUJeremy Magland 116- **Rendering:** three.js spheres with per-vertex colormaps, adapted from the
117 `SphereEmbedding` view in
118 [figpack](https://github.com/flatironinstitute/figpack)'s experimental
119 extension package ([`src/render/`](src/render/)).
61e12f1Write the solver in MATLAB and compile it to WebGPUJeremy Magland 120- **Solver:** the MATLAB stayed MATLAB. [`models/`](models/) holds the IMEX loop
35d91faDelete the TypeScript solver; the .m models are the only implementationJeremy Magland 121 as `.m` files, executed on the GPU by [`src/mgpu/`](src/mgpu/). There is no
122 second implementation: the app, the desktop benchmark and the tests all compile
123 and run the same `.m`.
35d91faDelete the TypeScript solver; the .m models are the only implementationJeremy Magland 125An earlier version of this repo carried a TypeScript port of the loop alongside
126the `.m`, and used it as the test oracle. That is gone. Two implementations
127agreeing only shows they share assumptions, so the `.m` path is now checked
128against closed-form answers instead — see [Tests](#tests). The one place a second
129implementation is still the right oracle is the transforms themselves, where
130[`src/sht/reference.ts`](src/sht/reference.ts) is shtns-webgpu's own f64
131direct-summation twin.
35d91faDelete the TypeScript solver; the .m models are the only implementationJeremy Magland 133Because the algorithm is compiled to compute shaders, **WebGPU is required** —
134there is no CPU fallback (the f64 CPU transform remains, for tests).
136## Numerics
138- Grid: Gauss–Legendre × equispaced-phi, dealiased for the cubic reactions with
139 the `(pdeg+1)` rule from the reference implementation:
140 `nlat ≥ ((pdeg+1)·lmax+1)/2`, `nphi ≥ (pdeg+1)·lmax+1` (rounded up to a power
141 of two for the GPU FFT path). At the default lmax 63 that is a 128×256 grid.
142- Spectral layout: SHTNS conventions — orthonormal + Condon–Shortley, complex
143 coefficients for m ≥ 0, m-major ordering.
144- fp32 transforms introduce ~1e-6 relative error per step (verified against the
145 f64 CPU path); for pattern formation from 1e-2 seeded noise this is
146 inconsequential.
15a77e2Add a desktop WebGPU benchmark and show its command in the appJeremy Magland 148## Desktop vs browser
150How much does running this in a browser cost? [`scripts/bench.ts`](scripts/bench.ts)
35d91faDelete the TypeScript solver; the .m models are the only implementationJeremy Magland 151runs the *same* thing — same `.m`, lowered by numbl into the same WGSL kernels,
152over the same transforms — from Node on desktop WebGPU (Google Dawn), and the app
153prints the command line that reproduces whatever it is currently simulating:
155```
35d91faDelete the TypeScript solver; the .m models are the only implementationJeremy Magland 156npm run bench -- --preset schnak-spots --lmax 63 --steps 2000 \
15a77e2Add a desktop WebGPU benchmark and show its command in the appJeremy Magland 157 --seed 1 --a 0.1 --b 0.9 --D1 0.0004 --D2 0.008 --dt 0.05
158```
160Copy it from under the stats line, run it, and compare the `ms/step` it reports
161with the app's. Both sides go through the one shared
162[`src/bench/runSpec.ts`](src/bench/runSpec.ts) — the app formats a run into that
163command, the benchmark parses it back — so there is no second copy of the
35d91faDelete the TypeScript solver; the .m models are the only implementationJeremy Magland 164defaults for the two runs to drift apart on. Both then go through the same
165[`ModelSession`](src/mgpu/session.ts), down to the device request in
166`requestShtDevice()` (Dawn is installed under `navigator.gpu` and the WebGPU
167globals, and the rest runs unchanged).
169The benchmark runs under `vite-node`, which is what resolves numbl's compiler
170sources and the `?raw` model imports — plain Node cannot (see
171[The numbl dependency](#the-numbl-dependency)).
173It reports two numbers, because they answer different questions:
175```
176 0.54 ms/step 1857.5 steps/s 92.87 model time/s (batches of 16)
177 one step per submit: 0.74 ms mean · median 0.60 · p05 0.51 · p95 1.29 · min 0.50
178```
180The first is throughput: a batch of steps submitted together and awaited once,
181which is how the app runs and what keeping the state in GPU buffers is for. The
182second is per-step latency, one submit each — comparable to a design that
183synchronises every step, and the only way to get a distribution.
185**What the GPU-resident design is worth.** At lmax 31 on an Intel Xe (Mesa, via
186Dawn) this path runs at **0.25 ms/step**, against **3.01 ms/step** for the
187TypeScript solver this repo used to carry — same machine, same transforms, same
188parameters. A **~12x** difference, and almost all of it is the four per-step
189buffer readbacks that version paid and this one does not. Note that CI, which
190only has a software rasterizer, shows no such gap: there the transforms dominate
191and both designs land within ~10% of each other. The saving is real but it is a
192saving on driver round-trips, so it only appears once the GPU is fast.
e5b7827Fix CI: do not omit optional dependenciesJeremy Magland 194Desktop WebGPU comes from the `webgpu` package (prebuilt Dawn, ~70 MB), listed
195as an optional dependency so that a platform it has no binaries for fails the
196install of that package alone rather than the whole tree. `npm install` picks it
35d91faDelete the TypeScript solver; the .m models are the only implementationJeremy Magland 197up; without it there is no desktop GPU to run on and the benchmark says so.
198Those binaries need glibc 2.29+, which rules out older cluster images
199(RHEL/Rocky 8 is 2.28) unless you run inside a container with a newer base. Other
200flags: `--steps`, `--warmup`, `--batch`, `--json`, `--help`;
201`DAWN_FLAGS='backend=vulkan'` (`;`-separated) passes Dawn options through, e.g. to
202pick a backend or to compare against Dawn's own software adapter.
0f3abbdSeparate solver time from frame time, and add a cross-environment checkJeremy Magland 204### Comparing the two honestly
0f3abbdSeparate solver time from frame time, and add a cross-environment checkJeremy Magland 206The app reports **two** numbers, and only the first is comparable to the
207benchmark:
209```
210solver 0.58 ms/step (1724 steps/s) · 12.4 ms/frame incl. readback + render
211```
213`solver` is the batch of steps alone, waited for but not read back — the same
214thing the benchmark's throughput number measures. `ms/frame` additionally carries
215a GPU→CPU readback **per species**, the colormapping, and the vertex upload.
217Those per-frame costs are fixed: they do not shrink when the GPU gets faster. So
218the faster your GPU, the larger the ratio between them — on a quick discrete GPU
219it is easy for a frame to cost ten times the four steps inside it, purely because
220a `mapAsync` round trip in a browser has to drain the queue and cross into the GPU
221process. **That is expected, and it is not the solver being slower in the
222browser.** Compare `solver` with the benchmark's throughput line; comparing
223`ms/frame` against it measures the readback, not the computation.
225Other things the comparison does not control for:
227- the browser's renderer→GPU-process boundary on every submit, where Dawn in Node
228 is in-process; and, for a page that is not cross-origin isolated, coarser
229 `performance.now()`.
35d91faDelete the TypeScript solver; the .m models are the only implementationJeremy Magland 230- both sides are fp32 throughout, on the same generated kernels, so nothing here
231 is a numerics comparison — only a cost one.
cde22eaStop the per-frame sync from inflating the app's solver numberJeremy Magland 233### Why the browser is slower, and how to find out by how much
235Some gap is real and some is measurement. Four numbers, in increasing order of
236what they include — walk down them and the gap attributes itself:
239node scripts/compare-perf.mjs [--lmax 63] [--steps 300]
240```
242measures the same solver work in both — batched, nothing read back, no rendering
243on either side — and reports each with its CPU-encoding share, the Fourier stage,
244and the adapter. It stops you first if the two are not even the same device: a
245browser quietly falling back to a software adapter is a common cause of "the
246browser is much slower", and then the ratio compares different hardware and means
247nothing.
3221abdAdd a Benchmark button that measures the solver and the GPU's clock rampJeremy Magland 249Or press **Benchmark** in the app: it pauses rendering and runs batches
250continuously for two seconds, reporting the same measurement the terminal makes,
251plus the **ramp** — the first third of the run against the last. GPUs downclock
252when idle and an animation-paced loop leaves them idle most of every frame, so a
253large ramp means the steady-state number is limited by clocks rather than by the
254work.
256By hand, five numbers, in increasing order of what they include:
cde22eaStop the per-frame sync from inflating the app's solver numberJeremy Magland 258| number | includes |
259|---|---|
260| `npm run bench -- --lmax 63` | desktop solver: batched steps, one sync per batch, in-process Dawn |
3221abdAdd a Benchmark button that measures the solver and the GPU's clock rampJeremy Magland 261| the app's **Benchmark** button | browser solver, sustained, no rendering, no pacing |
262| `test.html?soak=2000&lmax=63` → `solver` | the same, without the page around it |
263| the app's `solver` | browser solver, one batch of 32 every two seconds |
cde22eaStop the per-frame sync from inflating the app's solver numberJeremy Magland 264| the app's `ms/frame` | four steps **plus** a readback per species, colormapping and the vertex upload |
266If the soak matches the benchmark, the solver is fine in the browser and
267everything above it is readback and rendering. If the soak is itself slower, the
268remaining suspects are:
270- **the GPU-process boundary.** Every submit and every sync is IPC out of the
271 renderer; Dawn in Node is in-process. This is a fixed per-batch cost, so it hurts
272 most when the GPU is fast. `npm run bench -- --batch 4` makes the desktop pay a
273 sync as often as the app's frame loop does, which shows how much of the gap is
274 just amortization.
17db8f1Add scripts/compare-perf.mjs, and rule out CPU command encodingJeremy Magland 275- **not CPU command encoding**, which is worth ruling out explicitly because it is
276 the obvious suspect: a step is ~47 WebGPU calls, and 32 of them per burst is a
277 lot of JS→GPU traffic. Measured, it goes the other way — 0.009 ms/step in Chrome
278 against 0.062 ms/step under node-webgpu, because Chrome defers commands to the
279 GPU process while node-webgpu validates them inline. Encoding is *cheaper* in
280 the browser. Both `compare-perf.mjs` and the benchmark print it.
cde22eaStop the per-frame sync from inflating the app's solver numberJeremy Magland 281- **competing with the renderer.** The page draws two spheres through WebGL on the
282 same GPU, in its own animation loop. The soak has no renderer, so comparing the
283 soak against the app's `solver` separates contention from everything else.
284- **clocks.** An animation-paced loop leaves the GPU idle for most of each 16 ms
285 frame, so it may never leave its low-power state, while the benchmark hammers it
286 continuously and boosts. On a thermally managed laptop this alone can be worth a
3221abdAdd a Benchmark button that measures the solver and the GPU's clock rampJeremy Magland 287 factor of two, and it is not something the code can fix. The **Benchmark**
288 button's ramp figure measures it directly.
289- **anything else using the GPU.** Another process competing for it changes
290 whichever run overlaps it, which makes a comparison across two separate
291 invocations meaningless. `compare-perf.mjs` runs both sides back to back in one
292 invocation partly for this reason.
293- **not buffer robustness**, another plausible suspect: WebGPU clamps every array
294 access for safety, which could cost real time in the transform kernels' inner
295 loops. Measured with Dawn's `disable_robustness` toggle
296 (`DAWN_FLAGS='enable-dawn-features=disable_robustness' npm run bench`), it makes
297 no difference here at all — 0.59 ms/step either way.
cde22eaStop the per-frame sync from inflating the app's solver numberJeremy Magland 298- **which browser.** WebGPU implementations differ substantially in maturity;
299 Chrome and Safari are not interchangeable for this.
301None of these change *what* is computed — see below for how to confirm that
302independently.
0f3abbdSeparate solver time from frame time, and add a cross-environment checkJeremy Magland 304### Is it really the same computation?
306```
307node scripts/compare-env.mjs [--lmax 31] [--steps 200] [--preset schnak-spots]
308```
310runs one identical spec on the desktop and in a real browser and compares the
311final spectral state. The pipeline is deterministic given (model source,
312parameters, lmax, seed, steps) — a seeded PRNG, then fixed arithmetic — so the two
313should agree to fp32 round-off. Both sides build their spec through the same
314`parseArgs`, so neither can quietly use a different default.
316They will *not* agree bit for bit; GPUs differ in fused-multiply-add and other
317latitude fp32 allows. Between Intel Xe (via Dawn) and SwiftShader — about as
318different as two implementations get — 200 steps at lmax 31 agree to a relative
319L2 of **2e-6**.
321It also reports which **Fourier stage** each side chose. `ShtPlan` picks FFT or
322DFT from the device's workgroup-storage and invocation limits, and those are
323genuinely different algorithms that round differently, so a mismatch there
324explains a difference in the values rather than being a symptom of one. The app's
325stats line and the benchmark both print the chosen stage for the same reason.
b689087Benchmark the WGSL transforms against upstream SHTNSJeremy Magland 327## Against upstream SHTNS
329The transforms are a WGSL translation of
330[SHTNS](https://nschaeff.bitbucket.io/shtns/), and the tests check them against
331their own f64 CPU twin — which shows they are self-consistent, not how they
332compare with the library they are modeled on. SHTNS itself runs on the CPU with
333hand-tuned SIMD codelets, and on Nvidia GPUs with its own CUDA kernels, including
334a single-precision mode. That is a direct comparison, and
335[`bench/shtns/`](bench/shtns/) makes it:
337```
338cd bench/shtns && ./bootstrap.sh && make # clone SHTns at a pinned commit, build
339node scripts/compare-native.mjs --check # then, from the repo root
340```
342`bootstrap.sh` adds CUDA support when `nvcc` is on `PATH`, so the same tree gives
343you the CPU comparison anywhere and the GPU one on a machine with an Nvidia card.
344`compare-native.mjs` runs every implementation present, back to back in one
345invocation so a second process competing for the GPU affects both sides rather
4166b48Tidy up after the SHTNS comparisonJeremy Magland 346than one, and prints them in one table. On an RTX PRO 6000 Blackwell, at the
347app's default lmax:
349```
350 grid lmax 63 · 128×256 · nlm 2,080 (one synthesis + one analysis per round trip)
4166b48Tidy up after the SHTNS comparisonJeremy Magland 352 webgpu 0.084 ms/round trip 11848/s (baseline) fp32
353 NVIDIA (blackwell), via Dawn · CPU-side launching 0.012 ms/step
354 shtns cuda 0.021 ms/round trip 48009/s 0.25x webgpu fp32
355 NVIDIA RTX PRO 6000 (sm_120, 188 SMs) · CPU-side launching 0.018 ms/step
356 shtns cpu 0.072 ms/round trip 13982/s 0.85x webgpu fp64
358```
4166b48Tidy up after the SHTNS comparisonJeremy Magland 360Read that carefully rather than as "4x". The two GPU rows are limited by different
361things: the WGSL row spends 14% of its time on the CPU and is genuinely GPU-bound,
362while SHTNS spends **86%** — 0.018 ms of 0.021 — queueing its six-or-so kernels, so
363its number is close to what it costs to *submit* a round trip on that host and its
364actual GPU time is below that and unresolved. The 4x is a lower bound on the gap in
365GPU work, not a measurement of it. `compare-native.mjs` flags any row above 50%
366for this reason.
368The other number worth noticing is the third row: one CPU core in fp64 is about
369level with the WGSL transforms on a 188-SM datacentre GPU. At lmax 63 there are
3702,080 coefficients on a 128×256 grid — far too little work to occupy that card, so
371this says more about occupancy than about the shaders. Sweep lmax before drawing
372conclusions, and stop at 511: above that `16*nphi` exceeds the workgroup-storage
373limit, the FFT stage falls back to the O(nphi·mmax) DFT, and the comparison stops
374being about the FFT.
b689087Benchmark the WGSL transforms against upstream SHTNSJeremy Magland 376Two things are measured, because they answer different questions:
378- **transforms** (`npm run bench:sht` here, `--mode transform` there) — one
379 spectral → grid → spectral round trip and nothing else. This is the
380 library-against-library number, and since the transforms are ~96% of the
381 solver's compute it is what decides how fast the solver can be.
382- **solver** (`npm run bench` here, `--mode solver` there) — a whole IMEX Euler
383 timestep, which is what the app's `solver` line reports.
385`--check` diffs the final spectral state across implementations, which is what
386makes the timing mean anything: two numbers are only comparable if they are the
387cost of the same computation. That check is possible at all because the spectral
388layout and normalization are SHTNS's own — orthonormal with Condon–Shortley,
389coefficients grouped by `m`, `LM(l,m)` agreeing index for index — so a state can
390be diffed element by element with no reindexing. Over 20 steps, fp32 WGSL against
391fp64 SHTNS agrees to **~1e-6** relative L2, for every model.
393It is also the check on the one second implementation this repo has. The native
394solver cannot run `models/<key>.m` — C has no numbl — so `bench/shtns/spec.h`
395restates the same arithmetic, one line per line of MATLAB. `--check` is what
396keeps that transcription honest, and `compare-native.mjs` refuses to compare two
397runs whose resolved grid or parameters disagree, which is the other way the two
398sides could drift.
400[`bench/shtns/README.md`](bench/shtns/README.md) lists what is *not* identical and
401should be kept in mind when reading the ratio — SHTNS runs its Legendre
402recurrence in fp64 even in fp32 mode for `lmax <= 128` (WebGPU has no fp64 at
403all), the Fourier stages are cuFFT/VkFFT/FFTW against a WGSL FFT, and SHTNS'
404polar optimization is off by default here because we have none.
4166b48Tidy up after the SHTNS comparisonJeremy Magland 406How much the grid size matters is easiest to see on a weak GPU, where there is no
407launch-overhead floor to hide behind. On an Intel Xe iGPU against one core of the
b689087Benchmark the WGSL transforms against upstream SHTNSJeremy Magland 408same laptop, one round trip costs:
410| lmax | grid | WGSL (fp32) | SHTNS, 1 CPU core (fp64) |
411|---|---|---|---|
412| 31 | 64×128 | 0.183 ms | 0.017 ms |
413| 63 | 128×256 | 0.250 ms | 0.110 ms |
414| 127 | 256×512 | 0.733 ms | 0.602 ms |
41610x behind at lmax 31, 1.2x at lmax 127 — the same comparison, on the same two
417chips. Whatever a single number says, it is saying it about one grid size.
2dedc35turing-sphere: reaction-diffusion on the sphere, spectral solver on WebGPUJeremy Magland 419## Tests
35d91faDelete the TypeScript solver; the .m models are the only implementationJeremy Magland 421There is no second implementation of the solver to diff against, so the `.m` path
422is checked against **closed-form answers**. Each case is one whose evolution is
423known exactly, run through the whole real pipeline — MATLAB source, numbl
424lowering, generated WGSL, GPU transforms — and compared with arithmetic
425([`test/analyticChecks.ts`](test/analyticChecks.ts)):
427- **A** — a linear reaction `f(u) = c*u` leaves every spherical-harmonic mode
428 independent, growing by exactly `(1 + dt*c) / (1 + dt*D*l(l+1))` per step. This
429 pins the transform round-trip, the eigenvalue mapping, the IMEX update and the
430 state feedback at once, and checks that nothing leaks between modes. Agrees to
431 ~2e-7 over 20 steps.
432- **B** — a nonlinear reaction on a *uniform* field stays uniform and diffusion
433 cannot touch it, so each step is exactly the scalar ODE map. Agrees to 1.5e-8
434 over 25 steps. Checks that a generated kernel evaluates a nonlinear reaction.
435- **C** — a 1e-6 perturbation of the Schnakenberg fixed point follows the
436 linearized 2x2 IMEX recurrence, and the `(l=24, m=7)` mode is confirmed
437 unstable. Looser (~2e-3) because fp32 keeps only about four digits of a
438 perturbation that small.
440Two test models exist only for this: [`test/models/linear.m`](test/models/linear.m)
441and [`test/models/logistic.m`](test/models/logistic.m).
443Alongside those, [`test/modelChecks.ts`](test/modelChecks.ts) compiles every model
444the app offers and asserts **how many kernels it compiles to**. That is a fusion
445guard: numbl's lowering emits one statement per *operator* and its inline pass
446folds them back into per-line expression trees, and if that stops happening the
447results stay correct while every operator becomes its own dispatch. It is
448invisible in the numbers, so it is asserted directly. (It has already caught one
449regression.)
451[`test/transformChecks.ts`](test/transformChecks.ts) is the one remaining
b689087Benchmark the WGSL transforms against upstream SHTNSJeremy Magland 452implementation-vs-implementation check inside the suite, comparing the WGSL
453transforms against shtns-webgpu's f64 CPU twin. Comparing them against *upstream*
454SHTNS is a separate, opt-in step, because it needs a native toolchain — see
455[Against upstream SHTNS](#against-upstream-shtns).
457All three modules run in **both** environments, so the two GPU stacks get the same
458guarantees:
460- `npm run test:node` — under Dawn on the desktop, via `vite-node`. Needs a GPU;
461 pass `--skip-without-gpu` to let a machine without one say so and move on
462 (which is what CI does, since the browser suite covers the same modules).
463- `npm run test:gpu` — builds and drives headless Chrome, on SwiftShader in CI.
464 Also runs the soak.
466Other commands:
468- `npm run bench -- --help` — the desktop benchmark (see
15a77e2Add a desktop WebGPU benchmark and show its command in the appJeremy Magland 469 [Desktop vs browser](#desktop-vs-browser)).
b689087Benchmark the WGSL transforms against upstream SHTNSJeremy Magland 470- `npm run bench:sht -- --help` — the transforms alone, with no solver around
471 them, for comparing against upstream SHTNS.
30ed90fAdd scripts/diagnose-sht.ts: which stage of the transform is wrong?Jeremy Magland 472- `npx vite-node scripts/diagnose-sht.ts` — when the transform tests fail on a GPU,
473 say *which* stage is wrong. It reads the intermediate `fm` back out and scores
474 the Legendre and Fourier stages of each direction separately against the f64
475 reference, then breaks the error down by order `m` and by latitude.
4166b48Tidy up after the SHTNS comparisonJeremy Magland 476- `npx vite-node scripts/diagnose-leg.ts [--m 0]` — the follow-up to that: read the
477 Legendre recurrence out of the production shader term by term, by synthesizing a
478 spectrum that is 1 at a single coefficient, and compare each `ỹ_l^m` with the f64
479 reference. The first term that disagrees names the culprit.
35d91faDelete the TypeScript solver; the .m models are the only implementationJeremy Magland 480- `npx vite-node scripts/longrun-node.ts [lmax]` — run to t = 100 and confirm the
481 pattern saturates into O(1)-contrast spots rather than decaying or diverging.
482- `node scripts/soak.mjs [steps] [lmax]` — drive the demo for many steps,
483 sampling JS heap and catching crashes.
484- `node scripts/screenshot.mjs out.png [light|dark] [minSteps]` — screenshot the
485 demo after a number of steps.
e7bcd70Add soak, live-check and solver-only soak toolingJeremy Magland 486- `node scripts/check-live.mjs [url]` — smoke-check a deployed URL in a real
487 browser: load, press Run, confirm the solver advances.
0f3abbdSeparate solver time from frame time, and add a cross-environment checkJeremy Magland 488- `node scripts/compare-env.mjs` — run one identical spec on the desktop and in a
489 browser and compare the final state (see
490 [Is it really the same computation?](#is-it-really-the-same-computation)).
17db8f1Add scripts/compare-perf.mjs, and rule out CPU command encodingJeremy Magland 491- `node scripts/compare-perf.mjs` — measure the same solver work in both and split
492 the difference (see
493 [Why the browser is slower](#why-the-browser-is-slower-and-how-to-find-out-by-how-much)).
b689087Benchmark the WGSL transforms against upstream SHTNSJeremy Magland 494- `node scripts/compare-native.mjs` — run one spec through the WGSL transforms and
495 through upstream SHTNS, and line the numbers up (see
496 [Against upstream SHTNS](#against-upstream-shtns)). Needs
497 [`bench/shtns/`](bench/shtns/) built first.
e7bcd70Add soak, live-check and solver-only soak toolingJeremy Magland 498- `test.html?soak=<steps>&lmax=<n>` — solver-only soak with no rendering.
500### A note on canvas resizing
502Early long runs killed the browser after ~700–800 steps. The cause was the
503colorbar's min/max labels changing width as their digit count changed, which
504reflowed the panel, fired the `ResizeObserver`, and called
505`renderer.setSize()` — reallocating the WebGL drawing buffer. Assigning
506`canvas.width` also blanks the canvas even when the value is unchanged, so the
507same bug caused visible flicker. Fixed by giving the colorbar column a fixed
508width and making `SphereScene.resize()` return early on no-op resizes.
4166b48Tidy up after the SHTNS comparisonJeremy Magland 510### A note on the Legendre recurrence on Blackwell
512The first run on an Nvidia GPU — an RTX PRO 6000, driver 590.48, reached through
513Dawn's Vulkan backend — failed 11 of the tests. `synth` was off by 5.5e+3 while
514`analys` was accurate to 7.3e-7, and the solver produced NaN within 40 steps.
516The two diagnostic scripts above were written for it and localized it in two
517steps: `leg_synth` was the only wrong shader, and within it the recurrence was
518right at `l = m` and `l = m+1` and then returned *exactly zero* at `l = m+2`, at
519every latitude. That is not a precision failure. It is
521```wgsl
522let c0 = ab[base + (l + 2u - m)];
523y0 = c0.x * ct * y1 + c0.y * y0; // c0 reads as (0, 0) on the first iteration
524```
526with the `ab` read two lines later working fine. The buffer was not at fault:
527`leg_analys` reads the same array correctly on the same device, and `m = 62, 63`
528— the only orders whose loop breaks before that line — were the only correct
529ones. Nothing about that WGSL is invalid, so it was a miscompiled load.
531Fixed by giving the advance the shape `leg_analys` already used, which that
532driver compiles correctly: both coefficients fetched unconditionally, and the new
533`y0` carried in a temporary rather than assigned and then read back by the `y1`
534update. Two shaders doing the same recurrence should have agreed on form anyway.
536Worth knowing for what it says about the transforms in general: nothing had
537exercised them on Nvidia hardware before, and the existing test caught it
538immediately — it just could not say where. That is what the diagnostics are for.
2dedc35turing-sphere: reaction-diffusion on the sphere, spectral solver on WebGPUJeremy Magland 540## Development
542```
543npm install
544npm run dev # local dev server
545npm run build # type-check + production build to dist/
546```
61e12f1Write the solver in MATLAB and compile it to WebGPUJeremy Magland 548### The numbl dependency
550numbl is a local `file:../../numbl` dependency, so a sibling checkout of
551[numbl](https://github.com/flatironinstitute/numbl) is required. We use its
552compiler internals — parser, lowerer, IR, inline pass — which its package
553`exports` map does not publish, so they are reached through the `numbl-src` path
554alias in [`vite.config.ts`](vite.config.ts).
556The exact surface we depend on is written down in
557[`src/mgpu/numbl.d.ts`](src/mgpu/numbl.d.ts) and TypeScript checks against
558*that*, not against numbl's sources. This keeps this project's compiler settings
559independent of numbl's (its sources do not type-check under the stricter options
560used here), and means a change to one of those shapes upstream breaks the build
561here with a clear diff rather than deep inside numbl's tree.
563The compiler is ~395 kB gzipped and lands in its own chunk. That is the cost of
564compiling MATLAB in the page; a build-time lowering step could remove it at the
565price of no longer being editable live.
567CI clones numbl to the sibling path that `file:` dependency expects, pinned to a
568commit. Two details make that work, both verified by building against a checkout
569that had none of numbl's own dependencies installed:
571- **numbl's `node_modules` are not needed.** The slice we import — parser,
572 lowering, IR, inline pass — is self-contained TypeScript. (Other parts of numbl
573 do import `three`, `react` and `fflate`; we never reach them.)
574- **the install must pass `--ignore-scripts`.** npm runs a linked package's
575 `prepare` script, and numbl's is `husky`, which is not installed in CI.
35d91faDelete the TypeScript solver; the .m models are the only implementationJeremy Magland 577The `scripts/*.ts` entry points that touch the compiler (the benchmark, the node
578tests, the long run) go through `vite-node`, so they resolve imports exactly as the
579browser build does — the `numbl-src` alias and the `?raw` model imports included.
580Plain `node` cannot: numbl's sources import each other as `./foo.js` while the
581files are `.ts`, which needs a bundler's resolution. Scripts that do not touch the
582compiler (`soak.mjs`, `screenshot.mjs`, `check-live.mjs`, `test-gpu.mjs`) are plain
583`.mjs` and run under `node` directly.
2dedc35turing-sphere: reaction-diffusion on the sphere, spectral solver on WebGPUJeremy Magland 585Deployed to GitHub Pages by `.github/workflows/deploy.yml` on push to `main`.
587## License
589CECILL-2.1 (inherited from SHTNS via shtns-webgpu, whose sources are vendored).