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