2 * A .m model, compiled and running on the GPU.
3 *
4 * A model file is ordinary MATLAB: it defines an `init` function that builds the
5 * initial spectral state and a `step` function that advances it one timestep.
6 * Each is specialized for the current grid and compiled into a ModelPlan, and
7 * both operate on the same state buffers (see HostBuffers).
8 *
9 * Both functions return the new state followed by the grid fields the app
10 * renders, so their signatures say exactly what they produce:
11 *
12 * function [U, V, u, v] = init(noise, a, b)
13 * function [U, V, u, v] = step(U, V, lam, a, b, D1, D2, dt)
14 *
15 * The host supplies the things that are precomputation rather than algorithm:
16 * the grid, the Laplace-Beltrami eigenvalues, the seeded initial noise, and the
17 * parameter values. Each argument is matched to the .m's declared parameter
18 * name, so the file documents its own interface.
19 */
20import { ShtPlan } from '../sht/sht.ts';
8144287WIP: added code for Laplace-Beltrami operator evaluation on smooth genus-0 surfaceOwen Melia 21import type { DerivPlan } from '../sht/deriv.ts';
0af3386Reaction-diffusion on spherical-harmonic surfacesJeremy Magland 22import { lmIndex, type ShtConfig } from '../sht/layout.ts';
23import { HostBuffers, ModelPlan } from './plan.ts';
24import { inFunction, inFunctionAsync, inModel } from './errors.ts';
25import { CompiledModel, type Binding } from './compile.ts';
27export interface ModelParams {
28 [key: string]: number;
29}
31export interface GpuModelOptions {
32 device: GPUDevice;
33 sht: ShtPlan;
34 cfg: ShtConfig;
35 /** Model source (.m text). */
36 source: string;
37 /** Parameter names the .m may take as arguments. */
38 paramNames: string[];
39 /** Spectral state names, in order (e.g. ['U', 'V']). */
40 state: string[];
41 /** Grid fields to render, in order (e.g. ['u', 'v']). */
42 view: string[];
43 /**
44 * The surface, as the .m may ask for it: `gx`, `gy`, `gz` are the embedding's
45 * Cartesian coordinates on the grid, and `Gx`, `Gy`, `Gz` the spherical-
46 * harmonic coefficients they were synthesized from. Omitted for a bare unit
47 * sphere, where the .m has no geometry to take.
48 */
49 geometry?: GeometryBuffers;
8144287WIP: added code for Laplace-Beltrami operator evaluation on smooth genus-0 surfaceOwen Melia 50 /** Computes `dtheta`/`dphi` for the .m's surface Laplace-Beltrami
51 * correction. Omitted for a bare unit sphere, same as `geometry`. */
52 deriv?: DerivPlan;
54 * Iterations of the implicit solve the .m's `for` loop runs. A fixed scalar
55 * rather than a tunable one: the loop is unrolled into the op sequence, so
56 * the count is part of what compiles and changing it recompiles.
57 */
58 niter?: number;
59}
61/** Host-supplied surface fields, in the layout the .m sees them. */
62export interface GeometryBuffers {
63 /** Grid coordinates, npts each. */
64 x: Float32Array;
65 y: Float32Array;
66 z: Float32Array;
67 /** Their spherical-harmonic coefficients, 2 x nlm each. */
68 X: Float32Array;
69 Y: Float32Array;
70 Z: Float32Array;
591a4f5Reduce the Laplace-Beltrami matvec to 6 transforms per species per iterationDan Fortunato 71 /** Inverse metric quantities (src/geom/metric.ts), grid space, npts each —
72 * the Algorithm-4 (12-transform) Laplace-Beltrami path. */
8144287WIP: added code for Laplace-Beltrami operator evaluation on smooth genus-0 surfaceOwen Melia 73 Vtx: Float32Array;
74 Vty: Float32Array;
75 Vtz: Float32Array;
76 Vpx: Float32Array;
77 Vpy: Float32Array;
78 Vpz: Float32Array;
591a4f5Reduce the Laplace-Beltrami matvec to 6 transforms per species per iterationDan Fortunato 79 /** Flux-form metric weights (src/geom/metric.ts computeFluxMetric), grid
80 * space, npts each — the six-transform Laplace-Beltrami scheme of
81 * docs/reduced-transforms.md. */
82 p1: Float32Array;
83 p2: Float32Array;
84 q2: Float32Array;
85 r: Float32Array;
e4d6a3bPrecondition with the operator's symbol; project the correction onto the bandDan Fortunato 86 /** Mean-J preconditioner scale (Geometry.Jhat): folded into every
87 * setParams upload as the 'jhat' uniform, so a .m that takes jhat is
88 * never left with the zero a missing parameter would default to. An
89 * explicit jhat in the params wins (jhat: 1 pins the plain round-sphere
90 * preconditioner, for A/B). */
91 Jhat: number;
94/** Names the .m may take for the grid coordinates and for their coefficients. */
95export const GEOMETRY_GRID_NAMES = ['gx', 'gy', 'gz'] as const;
96export const GEOMETRY_SPECTRAL_NAMES = ['Gx', 'Gy', 'Gz'] as const;
591a4f5Reduce the Laplace-Beltrami matvec to 6 transforms per species per iterationDan Fortunato 97/** Names the .m may take for the inverse metric quantities (Algorithm 4). */
8144287WIP: added code for Laplace-Beltrami operator evaluation on smooth genus-0 surfaceOwen Melia 98export const METRIC_GRID_NAMES = ['Vtx', 'Vty', 'Vtz', 'Vpx', 'Vpy', 'Vpz'] as const;
591a4f5Reduce the Laplace-Beltrami matvec to 6 transforms per species per iterationDan Fortunato 99/** Names the .m may take for the flux-form metric weights (six-transform
100 * scheme). A model asks for whichever set its loop uses; both are uploaded. */
101export const FLUX_METRIC_GRID_NAMES = ['p1', 'p2', 'q2', 'r'] as const;
0af3386Reaction-diffusion on spherical-harmonic surfacesJeremy Magland 102
103/** Laplace-Beltrami eigenvalues l(l+1), duplicated across re/im so the array
104 * matches the 2 x nlm spectral layout element for element. */
105export function eigenvalues(cfg: ShtConfig, nlm: number): Float32Array {
106 const lam = new Float32Array(2 * nlm);
107 for (let m = 0; m <= cfg.mmax; m++) {
108 for (let l = m; l <= cfg.lmax; l++) {
109 const i = lmIndex(cfg.lmax, l, m);
110 lam[2 * i] = l * (l + 1);
111 lam[2 * i + 1] = l * (l + 1);
112 }
113 }
114 return lam;
115}
8144287WIP: added code for Laplace-Beltrami operator evaluation on smooth genus-0 surfaceOwen Melia 117/**
118 * 1 where l < lmax-2, else 0, duplicated across re/im like `lam`. The
119 * theta/phi derivative recurrences (src/sht/derivCoeffs.ts) cannot exactly
120 * represent a derivative at the top two degrees of the band limit, so the
121 * surface Laplace-Beltrami correction filters them out wherever it
122 * re-differentiates a field (evolving_surface/notes/algos.tex Sec 6,
123 * "Miscellaneous implementation details").
124 */
125export function filterMask(cfg: ShtConfig, nlm: number): Float32Array {
126 const filt = new Float32Array(2 * nlm);
127 for (let m = 0; m <= cfg.mmax; m++) {
128 for (let l = m; l <= cfg.lmax; l++) {
129 const i = lmIndex(cfg.lmax, l, m);
130 const keep = l < cfg.lmax - 2 ? 1 : 0;
131 filt[2 * i] = keep;
132 filt[2 * i + 1] = keep;
133 }
134 }
135 return filt;
136}
139 readonly paramNames: string[];
140 readonly state: string[];
141 readonly view: string[];
142 readonly npts: number;
143 readonly nlm: number;
145 #device: GPUDevice;
146 #host: HostBuffers;
147 #initPlan: ModelPlan;
148 #stepPlan: ModelPlan;
e4d6a3bPrecondition with the operator's symbol; project the correction onto the bandDan Fortunato 149 /** Current geometry's mean-J scale; 1 with no geometry (the sphere). */
150 #jhat = 1;
152 /** Scratch holding a copy of the whole spectral state; see snapshotState. */
153 #stash: GPUBuffer;
154 /** Which function wrote the state most recently; see `read`. */
155 #lastRan: 'init' | 'step' = 'init';
156 #stashedRan: 'init' | 'step' = 'init';
157 #destroyed = false;
159 private constructor(init: {
160 device: GPUDevice;
161 host: HostBuffers;
162 initPlan: ModelPlan;
163 stepPlan: ModelPlan;
164 readback: GPUBuffer;
165 stash: GPUBuffer;
166 paramNames: string[];
167 state: string[];
168 view: string[];
169 npts: number;
170 nlm: number;
171 }) {
172 this.#device = init.device;
173 this.#host = init.host;
174 this.#initPlan = init.initPlan;
175 this.#stepPlan = init.stepPlan;
176 this.#readback = init.readback;
177 this.#stash = init.stash;
178 this.paramNames = init.paramNames;
179 this.state = init.state;
180 this.view = init.view;
181 this.npts = init.npts;
182 this.nlm = init.nlm;
183 }
185 static async create(opts: GpuModelOptions): Promise<GpuModel> {
8144287WIP: added code for Laplace-Beltrami operator evaluation on smooth genus-0 surfaceOwen Melia 186 const { device, sht, cfg, source, paramNames, state, view, geometry, deriv } = opts;
0af3386Reaction-diffusion on spherical-harmonic surfacesJeremy Magland 187 const npts = cfg.nlat * cfg.nphi;
188 const nlm = sht.nlm;
189 const niter = opts.niter ?? 0;
8144287WIP: added code for Laplace-Beltrami operator evaluation on smooth genus-0 surfaceOwen Melia 191 // What the .m may ask for by parameter name. Spectral state, the
192 // eigenvalues and the top-mode filter are 2 x nlm; the seeded
193 // perturbation is a grid field.
0af3386Reaction-diffusion on spherical-harmonic surfacesJeremy Magland 194 const bindings: Record<string, Binding> = {
195 lam: { kind: 'tensor', shape: [2, nlm] },
8144287WIP: added code for Laplace-Beltrami operator evaluation on smooth genus-0 surfaceOwen Melia 196 filt: { kind: 'tensor', shape: [2, nlm] },
0af3386Reaction-diffusion on spherical-harmonic surfacesJeremy Magland 197 noise: { kind: 'tensor', shape: [npts, 1] },
198 npts: { kind: 'const', value: npts },
199 nlm: { kind: 'const', value: nlm },
200 niter: { kind: 'const', value: niter },
201 };
202 if (geometry) {
203 for (const g of GEOMETRY_GRID_NAMES) bindings[g] = { kind: 'tensor', shape: [npts, 1] };
204 for (const g of GEOMETRY_SPECTRAL_NAMES) bindings[g] = { kind: 'tensor', shape: [2, nlm] };
8144287WIP: added code for Laplace-Beltrami operator evaluation on smooth genus-0 surfaceOwen Melia 205 for (const g of METRIC_GRID_NAMES) bindings[g] = { kind: 'tensor', shape: [npts, 1] };
591a4f5Reduce the Laplace-Beltrami matvec to 6 transforms per species per iterationDan Fortunato 206 for (const g of FLUX_METRIC_GRID_NAMES) bindings[g] = { kind: 'tensor', shape: [npts, 1] };
e4d6a3bPrecondition with the operator's symbol; project the correction onto the bandDan Fortunato 207 // Mean-J preconditioner scale (Geometry.Jhat): a uniform, not a const,
208 // so swapping the surface updates it with no recompile. The session
209 // folds the current geometry's value into every setParams call.
210 bindings['jhat'] = { kind: 'param' };
212 for (const s of state) bindings[s] = { kind: 'tensor', shape: [2, nlm] };
213 for (const p of paramNames) bindings[p] = { kind: 'param' };
215 // Parsing belongs to the file, not to either function.
216 const compiled = inModel(() => new CompiledModel(source, bindings, { npts, nlm }));
217 // Both functions return the new state first, then the rendered grid fields.
218 const nargout = state.length + view.length;
219 const initFn = inFunction('init', () => compiled.specialize('init', nargout));
220 const stepFn = inFunction('step', () => compiled.specialize('step', nargout));
221 compiled.finish();
223 // Only the state outputs feed back into the argument buffers; the grid
224 // fields are read for display and then overwritten next call.
225 const feedback = [...state, ...view.map(() => null)];
227 const host = new HostBuffers(device);
228 // The host owns the state and the inputs it uploads, whether or not a given
229 // function happens to take them as arguments — `init` does not read `U`, but
230 // it writes it, and `step` reads it back.
231 for (const s of state) host.ensure(s, 2 * nlm);
232 host.ensure('lam', 2 * nlm);
8144287WIP: added code for Laplace-Beltrami operator evaluation on smooth genus-0 surfaceOwen Melia 233 host.ensure('filt', 2 * nlm);
0af3386Reaction-diffusion on spherical-harmonic surfacesJeremy Magland 234 host.ensure('noise', npts);
235 if (geometry) {
236 for (const g of GEOMETRY_GRID_NAMES) host.ensure(g, npts);
237 for (const g of GEOMETRY_SPECTRAL_NAMES) host.ensure(g, 2 * nlm);
8144287WIP: added code for Laplace-Beltrami operator evaluation on smooth genus-0 surfaceOwen Melia 238 for (const g of METRIC_GRID_NAMES) host.ensure(g, npts);
591a4f5Reduce the Laplace-Beltrami matvec to 6 transforms per species per iterationDan Fortunato 239 for (const g of FLUX_METRIC_GRID_NAMES) host.ensure(g, npts);
242 const initPlan = await inFunctionAsync('init', () =>
8144287WIP: added code for Laplace-Beltrami operator evaluation on smooth genus-0 surfaceOwen Melia 243 ModelPlan.create(device, sht, { fn: initFn, feedback }, host, deriv),
245 const stepPlan = await inFunctionAsync('step', () =>
8144287WIP: added code for Laplace-Beltrami operator evaluation on smooth genus-0 surfaceOwen Melia 246 ModelPlan.create(device, sht, { fn: stepFn, feedback }, host, deriv),
249 host.upload('lam', eigenvalues(cfg, nlm));
8144287WIP: added code for Laplace-Beltrami operator evaluation on smooth genus-0 surfaceOwen Melia 250 host.upload('filt', filterMask(cfg, nlm));
252 host.upload('gx', geometry.x);
253 host.upload('gy', geometry.y);
254 host.upload('gz', geometry.z);
255 host.upload('Gx', geometry.X);
256 host.upload('Gy', geometry.Y);
257 host.upload('Gz', geometry.Z);
8144287WIP: added code for Laplace-Beltrami operator evaluation on smooth genus-0 surfaceOwen Melia 258 host.upload('Vtx', geometry.Vtx);
259 host.upload('Vty', geometry.Vty);
260 host.upload('Vtz', geometry.Vtz);
261 host.upload('Vpx', geometry.Vpx);
262 host.upload('Vpy', geometry.Vpy);
263 host.upload('Vpz', geometry.Vpz);
591a4f5Reduce the Laplace-Beltrami matvec to 6 transforms per species per iterationDan Fortunato 264 host.upload('p1', geometry.p1);
265 host.upload('p2', geometry.p2);
266 host.upload('q2', geometry.q2);
267 host.upload('r', geometry.r);
270 const readback = device.createBuffer({
271 label: 'mgpu-readback',
272 size: 4 * Math.max(npts, 2 * nlm),
273 usage: GPUBufferUsage.MAP_READ | GPUBufferUsage.COPY_DST,
274 });
275 const stash = device.createBuffer({
276 label: 'mgpu-state-stash',
277 size: 4 * state.length * 2 * nlm,
278 usage: GPUBufferUsage.COPY_SRC | GPUBufferUsage.COPY_DST,
279 });
e4d6a3bPrecondition with the operator's symbol; project the correction onto the bandDan Fortunato 281 const gpu = new GpuModel({
0af3386Reaction-diffusion on spherical-harmonic surfacesJeremy Magland 282 device, host, initPlan, stepPlan, readback, stash,
283 paramNames, state, view, npts, nlm,
284 });
e4d6a3bPrecondition with the operator's symbol; project the correction onto the bandDan Fortunato 285 if (geometry) gpu.#jhat = geometry.Jhat;
286 return gpu;
289 setParams(params: ModelParams): void {
e4d6a3bPrecondition with the operator's symbol; project the correction onto the bandDan Fortunato 290 const merged = { jhat: this.#jhat, ...params };
291 this.#initPlan.setParams(merged);
292 this.#stepPlan.setParams(merged);
295 /**
296 * Write a host-owned value directly — the spectral state, or one of the input
297 * fields. Lets a test set up an exact initial condition (a single spherical-
298 * harmonic mode, say) instead of going through `init`.
299 */
300 upload(name: string, data: Float32Array): void {
301 this.#host.upload(name, data);
302 }
304 /**
305 * Swap the surface under a running model. The geometry is data, not code —
306 * its shape in the bindings depends only on the grid — so changing it is six
307 * buffer writes and needs no recompile, and the simulation carries straight
308 * on. Only meaningful if the .m took the geometry as an argument.
309 */
310 uploadGeometry(geometry: GeometryBuffers): void {
311 const fields: [string, Float32Array][] = [
312 ['gx', geometry.x], ['gy', geometry.y], ['gz', geometry.z],
313 ['Gx', geometry.X], ['Gy', geometry.Y], ['Gz', geometry.Z],
8144287WIP: added code for Laplace-Beltrami operator evaluation on smooth genus-0 surfaceOwen Melia 314 ['Vtx', geometry.Vtx], ['Vty', geometry.Vty], ['Vtz', geometry.Vtz],
315 ['Vpx', geometry.Vpx], ['Vpy', geometry.Vpy], ['Vpz', geometry.Vpz],
591a4f5Reduce the Laplace-Beltrami matvec to 6 transforms per species per iterationDan Fortunato 316 ['p1', geometry.p1], ['p2', geometry.p2],
317 ['q2', geometry.q2], ['r', geometry.r],
319 for (const [name, data] of fields) {
320 if (this.#host.get(name)) this.#host.upload(name, data);
321 }
e4d6a3bPrecondition with the operator's symbol; project the correction onto the bandDan Fortunato 322 // The new surface's preconditioner scale takes effect on the next
323 // setParams (the session re-applies its params after a swap).
324 this.#jhat = geometry.Jhat;
327 /** Upload the seeded perturbation and run `init`. */
328 init(noise: Float32Array): void {
329 this.#host.upload('noise', noise);
330 const enc = this.#device.createCommandEncoder({ label: 'mgpu-init' });
331 this.#initPlan.encodeSteps(enc, 1);
332 this.#device.queue.submit([enc.finish()]);
333 this.#lastRan = 'init';
334 }
336 /**
337 * Copy the spectral state aside, so a batch of steps can run — to be timed —
338 * and then be undone with restoreState, leaving the simulation exactly where
339 * it was. Only the state is stashed: the grid view fields keep whatever the
340 * batch last wrote until a subsequent step recomputes them, so step before
341 * reading a view after a restore.
342 */
343 snapshotState(): void {
344 this.#stashedRan = this.#lastRan;
345 this.#copyState('save');
346 }
348 restoreState(): void {
349 this.#copyState('restore');
350 this.#lastRan = this.#stashedRan;
351 }
353 #copyState(dir: 'save' | 'restore'): void {
354 // A restore can land after a rebuild destroyed the buffers mid-await;
355 // there is nothing left to protect, so do not submit into destroyed state.
356 if (this.#destroyed) return;
357 const enc = this.#device.createCommandEncoder({ label: `mgpu-state-${dir}` });
358 let offset = 0;
359 for (const name of this.state) {
360 const slot = this.#host.get(name);
361 if (!slot) throw new Error(`state '${name}' has no host buffer`);
362 const bytes = 4 * slot.count;
363 if (dir === 'save') {
364 enc.copyBufferToBuffer(slot.buffer, 0, this.#stash, offset, bytes);
365 } else {
366 enc.copyBufferToBuffer(this.#stash, offset, slot.buffer, 0, bytes);
367 }
368 offset += bytes;
369 }
370 this.#device.queue.submit([enc.finish()]);
371 }
373 /**
374 * Advance `steps` timesteps. Synchronous — this only records commands and
375 * submits them; nothing is read back and nothing is awaited.
376 */
377 step(steps = 1): void {
378 const enc = this.#device.createCommandEncoder({ label: 'mgpu-step' });
379 this.#stepPlan.encodeSteps(enc, steps);
380 this.#device.queue.submit([enc.finish()]);
381 this.#lastRan = 'step';
382 }
384 /**
385 * The buffer currently holding a named value. Grid fields like `u` are
386 * produced by both functions, into separate buffers (only the spectral state
387 * is shared), so this resolves to whichever function ran most recently —
388 * which is what makes the first frame show the initial state rather than an
389 * unwritten buffer.
390 */
391 #locate(name: string): { buffer: GPUBuffer; count: number } | null {
392 const [first, second] =
393 this.#lastRan === 'init'
394 ? [this.#initPlan, this.#stepPlan]
395 : [this.#stepPlan, this.#initPlan];
396 const buffer = first.buffer(name) ?? second.buffer(name);
397 const count = first.elementCount(name) ?? second.elementCount(name);
398 if (!buffer || count === undefined) return null;
399 return { buffer, count };
400 }
402 /** The GPU buffer a named value would be read from right now — for encoding
403 * further GPU work against it (e.g. a display-grid synthesis of the state)
404 * without a CPU round trip. */
405 valueBuffer(name: string): GPUBuffer | null {
406 return this.#locate(name)?.buffer ?? null;
407 }
409 /** Read a named value back to the CPU. The only await in the whole loop. */
410 async read(name: string): Promise<Float32Array> {
411 const located = this.#locate(name);
412 if (!located) {
413 throw new Error(`read: the model has no value named '${name}'`);
414 }
415 const { buffer, count } = located;
416 const enc = this.#device.createCommandEncoder({ label: `mgpu-read-${name}` });
417 enc.copyBufferToBuffer(buffer, 0, this.#readback, 0, 4 * count);
418 this.#device.queue.submit([enc.finish()]);
419 await this.#readback.mapAsync(GPUMapMode.READ, 0, 4 * count);
420 const out = new Float32Array(this.#readback.getMappedRange(0, 4 * count).slice(0));
421 this.#readback.unmap();
422 return out;
423 }
425 /** What the .m compiled to, for display. */
426 describe(): { init: string[]; step: string[] } {
427 return { init: this.#initPlan.describe(), step: this.#stepPlan.describe() };
428 }
430 destroy(): void {
431 this.#destroyed = true;
432 this.#initPlan.destroy();
433 this.#stepPlan.destroy();
434 this.#host.destroy();
435 this.#readback.destroy();
436 this.#stash.destroy();
437 }
438}