1/**
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';
21import type { DerivPlan } from '../sht/deriv.ts';
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;
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;
53 /**
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;
71 /** Inverse metric quantities (src/geom/metric.ts), grid space, npts each. */
72 Vtx: Float32Array;
73 Vty: Float32Array;
74 Vtz: Float32Array;
75 Vpx: Float32Array;
76 Vpy: Float32Array;
77 Vpz: Float32Array;
78}
80/** Names the .m may take for the grid coordinates and for their coefficients. */
81export const GEOMETRY_GRID_NAMES = ['gx', 'gy', 'gz'] as const;
82export const GEOMETRY_SPECTRAL_NAMES = ['Gx', 'Gy', 'Gz'] as const;
83/** Names the .m may take for the inverse metric quantities. */
84export const METRIC_GRID_NAMES = ['Vtx', 'Vty', 'Vtz', 'Vpx', 'Vpy', 'Vpz'] as const;
86/** Laplace-Beltrami eigenvalues l(l+1), duplicated across re/im so the array
87 * matches the 2 x nlm spectral layout element for element. */
88export function eigenvalues(cfg: ShtConfig, nlm: number): Float32Array {
89 const lam = new Float32Array(2 * nlm);
90 for (let m = 0; m <= cfg.mmax; m++) {
91 for (let l = m; l <= cfg.lmax; l++) {
92 const i = lmIndex(cfg.lmax, l, m);
93 lam[2 * i] = l * (l + 1);
94 lam[2 * i + 1] = l * (l + 1);
95 }
96 }
97 return lam;
98}
100/**
101 * 1 where l < lmax-2, else 0, duplicated across re/im like `lam`. The
102 * theta/phi derivative recurrences (src/sht/derivCoeffs.ts) cannot exactly
103 * represent a derivative at the top two degrees of the band limit, so the
104 * surface Laplace-Beltrami correction filters them out wherever it
105 * re-differentiates a field (evolving_surface/notes/algos.tex Sec 6,
106 * "Miscellaneous implementation details").
107 */
108export function filterMask(cfg: ShtConfig, nlm: number): Float32Array {
109 const filt = new Float32Array(2 * nlm);
110 for (let m = 0; m <= cfg.mmax; m++) {
111 for (let l = m; l <= cfg.lmax; l++) {
112 const i = lmIndex(cfg.lmax, l, m);
113 const keep = l < cfg.lmax - 2 ? 1 : 0;
114 filt[2 * i] = keep;
115 filt[2 * i + 1] = keep;
116 }
117 }
118 return filt;
119}
121export class GpuModel {
122 readonly paramNames: string[];
123 readonly state: string[];
124 readonly view: string[];
125 readonly npts: number;
126 readonly nlm: number;
128 #device: GPUDevice;
129 #host: HostBuffers;
130 #initPlan: ModelPlan;
131 #stepPlan: ModelPlan;
132 #readback: GPUBuffer;
133 /** Scratch holding a copy of the whole spectral state; see snapshotState. */
134 #stash: GPUBuffer;
135 /** Which function wrote the state most recently; see `read`. */
136 #lastRan: 'init' | 'step' = 'init';
137 #stashedRan: 'init' | 'step' = 'init';
138 #destroyed = false;
140 private constructor(init: {
141 device: GPUDevice;
142 host: HostBuffers;
143 initPlan: ModelPlan;
144 stepPlan: ModelPlan;
145 readback: GPUBuffer;
146 stash: GPUBuffer;
147 paramNames: string[];
148 state: string[];
149 view: string[];
150 npts: number;
151 nlm: number;
152 }) {
153 this.#device = init.device;
154 this.#host = init.host;
155 this.#initPlan = init.initPlan;
156 this.#stepPlan = init.stepPlan;
157 this.#readback = init.readback;
158 this.#stash = init.stash;
159 this.paramNames = init.paramNames;
160 this.state = init.state;
161 this.view = init.view;
162 this.npts = init.npts;
163 this.nlm = init.nlm;
164 }
166 static async create(opts: GpuModelOptions): Promise<GpuModel> {
167 const { device, sht, cfg, source, paramNames, state, view, geometry, deriv } = opts;
168 const npts = cfg.nlat * cfg.nphi;
169 const nlm = sht.nlm;
170 const niter = opts.niter ?? 0;
172 // What the .m may ask for by parameter name. Spectral state, the
173 // eigenvalues and the top-mode filter are 2 x nlm; the seeded
174 // perturbation is a grid field.
175 const bindings: Record<string, Binding> = {
176 lam: { kind: 'tensor', shape: [2, nlm] },
177 filt: { kind: 'tensor', shape: [2, nlm] },
178 noise: { kind: 'tensor', shape: [npts, 1] },
179 npts: { kind: 'const', value: npts },
180 nlm: { kind: 'const', value: nlm },
181 niter: { kind: 'const', value: niter },
182 };
183 if (geometry) {
184 for (const g of GEOMETRY_GRID_NAMES) bindings[g] = { kind: 'tensor', shape: [npts, 1] };
185 for (const g of GEOMETRY_SPECTRAL_NAMES) bindings[g] = { kind: 'tensor', shape: [2, nlm] };
186 for (const g of METRIC_GRID_NAMES) bindings[g] = { kind: 'tensor', shape: [npts, 1] };
187 }
188 for (const s of state) bindings[s] = { kind: 'tensor', shape: [2, nlm] };
189 for (const p of paramNames) bindings[p] = { kind: 'param' };
191 // Parsing belongs to the file, not to either function.
192 const compiled = inModel(() => new CompiledModel(source, bindings, { npts, nlm }));
193 // Both functions return the new state first, then the rendered grid fields.
194 const nargout = state.length + view.length;
195 const initFn = inFunction('init', () => compiled.specialize('init', nargout));
196 const stepFn = inFunction('step', () => compiled.specialize('step', nargout));
197 compiled.finish();
199 // Only the state outputs feed back into the argument buffers; the grid
200 // fields are read for display and then overwritten next call.
201 const feedback = [...state, ...view.map(() => null)];
203 const host = new HostBuffers(device);
204 // The host owns the state and the inputs it uploads, whether or not a given
205 // function happens to take them as arguments — `init` does not read `U`, but
206 // it writes it, and `step` reads it back.
207 for (const s of state) host.ensure(s, 2 * nlm);
208 host.ensure('lam', 2 * nlm);
209 host.ensure('filt', 2 * nlm);
210 host.ensure('noise', npts);
211 if (geometry) {
212 for (const g of GEOMETRY_GRID_NAMES) host.ensure(g, npts);
213 for (const g of GEOMETRY_SPECTRAL_NAMES) host.ensure(g, 2 * nlm);
214 for (const g of METRIC_GRID_NAMES) host.ensure(g, npts);
215 }
217 const initPlan = await inFunctionAsync('init', () =>
218 ModelPlan.create(device, sht, { fn: initFn, feedback }, host, deriv),
219 );
220 const stepPlan = await inFunctionAsync('step', () =>
221 ModelPlan.create(device, sht, { fn: stepFn, feedback }, host, deriv),
222 );
224 host.upload('lam', eigenvalues(cfg, nlm));
225 host.upload('filt', filterMask(cfg, nlm));
226 if (geometry) {
227 host.upload('gx', geometry.x);
228 host.upload('gy', geometry.y);
229 host.upload('gz', geometry.z);
230 host.upload('Gx', geometry.X);
231 host.upload('Gy', geometry.Y);
232 host.upload('Gz', geometry.Z);
233 host.upload('Vtx', geometry.Vtx);
234 host.upload('Vty', geometry.Vty);
235 host.upload('Vtz', geometry.Vtz);
236 host.upload('Vpx', geometry.Vpx);
237 host.upload('Vpy', geometry.Vpy);
238 host.upload('Vpz', geometry.Vpz);
239 }
241 const readback = device.createBuffer({
242 label: 'mgpu-readback',
243 size: 4 * Math.max(npts, 2 * nlm),
244 usage: GPUBufferUsage.MAP_READ | GPUBufferUsage.COPY_DST,
245 });
246 const stash = device.createBuffer({
247 label: 'mgpu-state-stash',
248 size: 4 * state.length * 2 * nlm,
249 usage: GPUBufferUsage.COPY_SRC | GPUBufferUsage.COPY_DST,
250 });
252 return new GpuModel({
253 device, host, initPlan, stepPlan, readback, stash,
254 paramNames, state, view, npts, nlm,
255 });
256 }
258 setParams(params: ModelParams): void {
259 this.#initPlan.setParams(params);
260 this.#stepPlan.setParams(params);
261 }
263 /**
264 * Write a host-owned value directly — the spectral state, or one of the input
265 * fields. Lets a test set up an exact initial condition (a single spherical-
266 * harmonic mode, say) instead of going through `init`.
267 */
268 upload(name: string, data: Float32Array): void {
269 this.#host.upload(name, data);
270 }
272 /**
273 * Swap the surface under a running model. The geometry is data, not code —
274 * its shape in the bindings depends only on the grid — so changing it is six
275 * buffer writes and needs no recompile, and the simulation carries straight
276 * on. Only meaningful if the .m took the geometry as an argument.
277 */
278 uploadGeometry(geometry: GeometryBuffers): void {
279 const fields: [string, Float32Array][] = [
280 ['gx', geometry.x], ['gy', geometry.y], ['gz', geometry.z],
281 ['Gx', geometry.X], ['Gy', geometry.Y], ['Gz', geometry.Z],
282 ['Vtx', geometry.Vtx], ['Vty', geometry.Vty], ['Vtz', geometry.Vtz],
283 ['Vpx', geometry.Vpx], ['Vpy', geometry.Vpy], ['Vpz', geometry.Vpz],
284 ];
285 for (const [name, data] of fields) {
286 if (this.#host.get(name)) this.#host.upload(name, data);
287 }
288 }
290 /** Upload the seeded perturbation and run `init`. */
291 init(noise: Float32Array): void {
292 this.#host.upload('noise', noise);
293 const enc = this.#device.createCommandEncoder({ label: 'mgpu-init' });
294 this.#initPlan.encodeSteps(enc, 1);
295 this.#device.queue.submit([enc.finish()]);
296 this.#lastRan = 'init';
297 }
299 /**
300 * Copy the spectral state aside, so a batch of steps can run — to be timed —
301 * and then be undone with restoreState, leaving the simulation exactly where
302 * it was. Only the state is stashed: the grid view fields keep whatever the
303 * batch last wrote until a subsequent step recomputes them, so step before
304 * reading a view after a restore.
305 */
306 snapshotState(): void {
307 this.#stashedRan = this.#lastRan;
308 this.#copyState('save');
309 }
311 restoreState(): void {
312 this.#copyState('restore');
313 this.#lastRan = this.#stashedRan;
314 }
316 #copyState(dir: 'save' | 'restore'): void {
317 // A restore can land after a rebuild destroyed the buffers mid-await;
318 // there is nothing left to protect, so do not submit into destroyed state.
319 if (this.#destroyed) return;
320 const enc = this.#device.createCommandEncoder({ label: `mgpu-state-${dir}` });
321 let offset = 0;
322 for (const name of this.state) {
323 const slot = this.#host.get(name);
324 if (!slot) throw new Error(`state '${name}' has no host buffer`);
325 const bytes = 4 * slot.count;
326 if (dir === 'save') {
327 enc.copyBufferToBuffer(slot.buffer, 0, this.#stash, offset, bytes);
328 } else {
329 enc.copyBufferToBuffer(this.#stash, offset, slot.buffer, 0, bytes);
330 }
331 offset += bytes;
332 }
333 this.#device.queue.submit([enc.finish()]);
334 }
336 /**
337 * Advance `steps` timesteps. Synchronous — this only records commands and
338 * submits them; nothing is read back and nothing is awaited.
339 */
340 step(steps = 1): void {
341 const enc = this.#device.createCommandEncoder({ label: 'mgpu-step' });
342 this.#stepPlan.encodeSteps(enc, steps);
343 this.#device.queue.submit([enc.finish()]);
344 this.#lastRan = 'step';
345 }
347 /**
348 * The buffer currently holding a named value. Grid fields like `u` are
349 * produced by both functions, into separate buffers (only the spectral state
350 * is shared), so this resolves to whichever function ran most recently —
351 * which is what makes the first frame show the initial state rather than an
352 * unwritten buffer.
353 */
354 #locate(name: string): { buffer: GPUBuffer; count: number } | null {
355 const [first, second] =
356 this.#lastRan === 'init'
357 ? [this.#initPlan, this.#stepPlan]
358 : [this.#stepPlan, this.#initPlan];
359 const buffer = first.buffer(name) ?? second.buffer(name);
360 const count = first.elementCount(name) ?? second.elementCount(name);
361 if (!buffer || count === undefined) return null;
362 return { buffer, count };
363 }
365 /** The GPU buffer a named value would be read from right now — for encoding
366 * further GPU work against it (e.g. a display-grid synthesis of the state)
367 * without a CPU round trip. */
368 valueBuffer(name: string): GPUBuffer | null {
369 return this.#locate(name)?.buffer ?? null;
370 }
372 /** Read a named value back to the CPU. The only await in the whole loop. */
373 async read(name: string): Promise<Float32Array> {
374 const located = this.#locate(name);
375 if (!located) {
376 throw new Error(`read: the model has no value named '${name}'`);
377 }
378 const { buffer, count } = located;
379 const enc = this.#device.createCommandEncoder({ label: `mgpu-read-${name}` });
380 enc.copyBufferToBuffer(buffer, 0, this.#readback, 0, 4 * count);
381 this.#device.queue.submit([enc.finish()]);
382 await this.#readback.mapAsync(GPUMapMode.READ, 0, 4 * count);
383 const out = new Float32Array(this.#readback.getMappedRange(0, 4 * count).slice(0));
384 this.#readback.unmap();
385 return out;
386 }
388 /** What the .m compiled to, for display. */
389 describe(): { init: string[]; step: string[] } {
390 return { init: this.#initPlan.describe(), step: this.#stepPlan.describe() };
391 }
393 destroy(): void {
394 this.#destroyed = true;
395 this.#initPlan.destroy();
396 this.#stepPlan.destroy();
397 this.#host.destroy();
398 this.#readback.destroy();
399 this.#stash.destroy();
400 }
401}