@margoengine/compute 0.0.0-stage → 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (71) hide show
  1. package/LICENSE +201 -0
  2. package/NOTICE +4 -0
  3. package/README.md +736 -3
  4. package/dist/array-DbI848Wf.js +166 -0
  5. package/dist/array.d.ts +109 -0
  6. package/dist/autodiff.d.ts +22 -0
  7. package/dist/autodiff.js +143 -0
  8. package/dist/autotune.d.ts +100 -0
  9. package/dist/autotune.js +179 -0
  10. package/dist/compat-YK57ZCbA.js +4 -0
  11. package/dist/compat.d.ts +2 -0
  12. package/dist/context-C75sQQra.js +2470 -0
  13. package/dist/context.d.ts +368 -0
  14. package/dist/cpu-CdVdqP4I.js +871 -0
  15. package/dist/cpu-kernel.wasm +0 -0
  16. package/dist/cpu-load-aTmfphVu.js +5 -0
  17. package/dist/cpu-load.d.ts +3 -0
  18. package/dist/cpu-runtime.d.ts +8 -0
  19. package/dist/cpu-wasm.d.ts +42 -0
  20. package/dist/cpu-wasm.js +161 -0
  21. package/dist/cpu.d.ts +138 -0
  22. package/dist/decomp-kernel.wasm +0 -0
  23. package/dist/decomp.d.ts +42 -0
  24. package/dist/decomp.js +158 -0
  25. package/dist/distance.d.ts +85 -0
  26. package/dist/distance.js +256 -0
  27. package/dist/dtype.d.ts +36 -0
  28. package/dist/errors-CDgOgzCd.js +7 -0
  29. package/dist/expr-DwFen60A.js +995 -0
  30. package/dist/expr.d.ts +196 -0
  31. package/dist/fft.d.ts +33 -0
  32. package/dist/fft.js +168 -0
  33. package/dist/frame.d.ts +63 -0
  34. package/dist/frame.js +82 -0
  35. package/dist/graph.d.ts +75 -0
  36. package/dist/graph.js +174 -0
  37. package/dist/histogram.d.ts +17 -0
  38. package/dist/index.d.ts +17 -0
  39. package/dist/index.js +4 -0
  40. package/dist/kernel.d.ts +65 -0
  41. package/dist/linalg.d.ts +21 -0
  42. package/dist/linalg.js +149 -0
  43. package/dist/nn-extra.d.ts +130 -0
  44. package/dist/nn-extra.js +322 -0
  45. package/dist/nn.d.ts +385 -0
  46. package/dist/nn.js +704 -0
  47. package/dist/onnx-kernel.wasm +0 -0
  48. package/dist/onnx.d.ts +164 -0
  49. package/dist/onnx.js +817 -0
  50. package/dist/quant.d.ts +59 -0
  51. package/dist/quant.js +242 -0
  52. package/dist/random.d.ts +64 -0
  53. package/dist/random.js +150 -0
  54. package/dist/reduce.d.ts +34 -0
  55. package/dist/scan.d.ts +26 -0
  56. package/dist/select.d.ts +38 -0
  57. package/dist/shaders.d.ts +80 -0
  58. package/dist/shape.d.ts +23 -0
  59. package/dist/shape.js +134 -0
  60. package/dist/signal.d.ts +29 -0
  61. package/dist/signal.js +178 -0
  62. package/dist/sort.d.ts +38 -0
  63. package/dist/sparse.d.ts +136 -0
  64. package/dist/sparse.js +273 -0
  65. package/dist/stream.d.ts +39 -0
  66. package/dist/stream.js +100 -0
  67. package/dist/subgroups.d.ts +27 -0
  68. package/dist/subgroups.js +191 -0
  69. package/dist/usingCtx-igdMnAhr.js +57 -0
  70. package/dist/wgsl.d.ts +68 -0
  71. package/package.json +144 -6
package/README.md CHANGED
@@ -1,3 +1,736 @@
1
- # Temporary Holding Version
2
-
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
1
+ # @margoengine/compute
2
+
3
+ Import `margoengine/compute` from the `margoengine` package, or `@margoengine/compute` from this package alone; the two are the same module. Neither is on npm yet: the [Install](../../README.md#install) section lists the two routes that work today (run in a clone, or install local tarballs).
4
+
5
+ GPU compute without the WebGPU boilerplate, for data science and for engine work. It feels like NumPy: N-dimensional
6
+ typed arrays with views and broadcasting, element-wise expressions that fuse into a single kernel, reductions and
7
+ statistics along axes, scans, sorting, selection and histograms. It also runs your own WGSL kernels, with bindings
8
+ read from the source. Optional entries add matrix products (`/linalg`), Fourier transforms (`/fft`), convolution
9
+ (`/signal`), reproducible random numbers (`/random`), sparse matrices and solvers (`/sparse`), gradients
10
+ (`/autodiff`), data larger than GPU memory (`/stream`), kernels inside an engine's frame (`/frame`), subgroup
11
+ kernels for reductions, scans and sorts (`/subgroups`), neural networks (`/nn`), graph algorithms (`/graph`) and workgroup sizes measured per adapter (`/autotune`).
12
+
13
+ The package is optional and tree-shakable, adds nothing to core, and needs no engine: without one it opens a
14
+ headless device of its own. Without WebGPU (Node, an older browser, a blocklisted GPU) the same code runs on the CPU.
15
+
16
+
17
+ ```ts
18
+ import { createCompute } from '@margoengine/compute';
19
+
20
+ using gpu = await createCompute(); // disposed (arrays and device freed) at the end of the block
21
+ const x = gpu.array(new Float32Array([3, 1, 4, 1, 5, 9, 2, 6]));
22
+ const sorted = await gpu.sort(x).read(); // Float32Array [1, 1, 2, 3, 4, 5, 6, 9]
23
+ const mean = await x.mean().item(); // 3.875
24
+ const z = x.sub(x.mean()).div(x.std()); // one fused kernel; nothing runs until it is read
25
+ console.log(sorted, mean, await z.read());
26
+ ```
27
+
28
+ ## Arrays
29
+
30
+ `gpu.array(data, { dtype, shape })` uploads a TypedArray or a plain array. The dtype comes from the TypedArray:
31
+ floats give `f32` (Float64Array is converted), signed integers give `i32`, unsigned integers give `u32`, and
32
+ Float16Array gives `f16` on GPUs with `shader-f16` (check `gpu.f16`). Plain arrays default to `f32`. The second
33
+ argument may be just the dtype. Creation helpers: `zeros`, `ones`, `full`, `arange`, `linspace`, `eye`.
34
+
35
+ `read()` resolves the elements in C order (`{ offset, length, signal }` reads part of them), and `item()` resolves the
36
+ one value of a single-element array. Disposing an array frees its GPU memory; disposing the context frees every array
37
+ it made.
38
+
39
+ ```ts
40
+ import { createCompute } from '@margoengine/compute';
41
+
42
+ using gpu = await createCompute();
43
+ const m = gpu.array([1, 2, 3, 4, 5, 6], { shape: [2, 3] });
44
+ const counts = gpu.zeros(10, 'u32');
45
+ const steps = gpu.arange(0, 1, 0.25); // f32 [0, 0.25, 0.5, 0.75]
46
+ console.log(m.shape, counts.size, await steps.read());
47
+ ```
48
+
49
+ Views cost no copy: `reshape(2, -1)`, `transpose()` or `.T`, `slice(...)` (an index, `[start, stop, step]` with
50
+ negative steps, or `null` for a whole dimension), `expandDims`, `squeeze` and `broadcastTo`. A view reads through
51
+ its strides, inside the same fused kernel.
52
+
53
+ ```ts
54
+ import { createCompute } from '@margoengine/compute';
55
+
56
+ using gpu = await createCompute();
57
+ const m = gpu.array(Float32Array.from({ length: 12 }, (_, k) => k), { shape: [3, 4] });
58
+ console.log(await m.T.read()); // the transpose, read in its own C order
59
+ console.log(await m.slice(null, [1, 3]).read()); // columns 1 and 2: [1, 2, 5, 6, 9, 10]
60
+ console.log(await m.slice([null, null, -1]).read()); // the rows reversed
61
+ ```
62
+
63
+ ## Fused expressions
64
+
65
+ Element-wise methods return lazy `Expr`essions, which follow NumPy's broadcasting and type promotion. Nothing runs
66
+ until you `read()` or `eval()` the expression or hand it to a reduction, and then the whole tree compiles into one
67
+ kernel, so no intermediate array is ever written. Constants travel in a uniform, so changing one does not recompile.
68
+
69
+ The element-wise methods:
70
+
71
+ - **Arithmetic:** `add`, `sub`, `mul`, `div` (true division; integers give f32), `floorDiv`, `mod` (NumPy sign
72
+ rules), `pow`, `minimum`, `maximum`, `clip`, `abs`, `neg`, `sign`, `square`.
73
+ - **Maths:** `sqrt`, `rsqrt`, `reciprocal`, `exp`, `exp2`, `expm1`, `log`, `log2`, `log1p`, the trigonometric and
74
+ hyperbolic functions, `atan2`, `hypot`, `degrees`, `radians`.
75
+ - **Rounding:** `floor`, `ceil`, `round` (ties to even), `trunc`.
76
+ - **Comparison and logic** (all give u32 0/1): `lt`, `le`, `gt`, `ge`, `eq`, `ne`, `and`, `or`, `xor`, `not`,
77
+ `isnan`, `isinf`, `isfinite`.
78
+ - **Integer bits:** `bitAnd`, `bitOr`, `bitXor`, `bitNot`, `shiftLeft`, `shiftRight`, `popcount`.
79
+ - **Conversion:** `astype(dtype)`, `bitcast(dtype)`.
80
+
81
+ `gpu.where(cond, a, b)` selects element-wise. `gpu.map(x, 'WGSL expression')` covers anything the methods do not.
82
+
83
+ ```ts
84
+ import { createCompute } from '@margoengine/compute';
85
+
86
+ using gpu = await createCompute();
87
+ const x = gpu.array(new Float32Array([-2, -1, 0, 1, 2]));
88
+ const relu = gpu.where(x.gt(0), x, 0); // [0, 0, 0, 1, 2]
89
+ const table = gpu.arange(1, 4, 1, 'f32').reshape(3, 1).mul(gpu.arange(1, 4, 1, 'f32')); // 3 x 3 broadcast
90
+ const custom = gpu.map(x, 'x * x * sign(x)');
91
+ console.log(await relu.read(), await table.read(), await custom.read());
92
+ ```
93
+
94
+ ## Reductions and statistics
95
+
96
+ The reductions are `sum`, `prod`, `min`, `max`, `mean`, `var` and `std` (both take `ddof`), `argmin`, `argmax`, `all`,
97
+ `any`, `countNonzero`, and the NaN-ignoring `nansum`, `nanmean`, `nanmin` and `nanmax`. Each runs over every element,
98
+ or along `axis` (a number or a list), with `keepdims`. Each is available as a method or on the context. Results are
99
+ arrays: shape `[]` for a full reduction, read with `item()`. The first pass reads the expression it is given, so
100
+ `x.sub(m).square().sum()` is one pass over `x`. `gpu.reduce(x, { combine: 'max(a, b)', identity: '0u' })` takes
101
+ any associative WGSL operator.
102
+
103
+ ```ts
104
+ import { createCompute } from '@margoengine/compute';
105
+
106
+ using gpu = await createCompute();
107
+ const data = gpu.array(new Float32Array([1, 9, 3, 7, 2, 8]), { shape: [2, 3] });
108
+ console.log(await data.sum({ axis: 0 }).read()); // [3, 17, 11]
109
+ console.log(await data.argmax({ axis: 1 }).read()); // [1, 2]
110
+ console.log(await data.std({ ddof: 1 }).item());
111
+ console.log(await gpu.nanmean(gpu.array([1, NaN, 3])).item()); // 2
112
+ ```
113
+
114
+ ## Scan, sort and selection
115
+
116
+ | Call | What it does |
117
+ | --- | --- |
118
+ | `gpu.cumsum(x, { axis })`, `cumprod`, `scan(x, { op, exclusive, axis })` | prefix scans, flat or along an axis |
119
+ | `gpu.segmentedScan(values, flags)` | a scan that restarts where a flag is set |
120
+ | `await gpu.reduceByKey(keys, values, { op })` | group-by over runs of equal keys |
121
+ | `gpu.sort(x, { descending, bits })`, `argsort`, `sortByKey(keys, values)` | stable GPU radix sort of any type |
122
+ | `gpu.topk(x, k)`, `quantile(x, q)`, `median(x)`, `await gpu.unique(x, { counts })` | order statistics |
123
+ | `gpu.take(x, indices, { axis, mode })` | gather (NumPy `take`; negative indices count from the end) |
124
+ | `gpu.scatter(target, indices, values, { op })` | write in place; `add`, `min`, `max` combine duplicates atomically, f32 included |
125
+ | `gpu.bincount(indices, { length, weights })` | counts or weight sums per value |
126
+ | `gpu.compact(x, mask)` | packed survivors plus a GPU-side count, with no readback |
127
+ | `await gpu.filter(x, mask)`, `await gpu.nonzero(mask)` | exactly sized results |
128
+ | `gpu.histogram(x, { bins, range })` | NumPy bins; the range is found on the GPU when not given |
129
+
130
+ ```ts
131
+ import { createCompute } from '@margoengine/compute';
132
+
133
+ using gpu = await createCompute();
134
+ const scores = gpu.array(new Float32Array([0.2, 0.9, 0.4, 0.7]));
135
+ const order = gpu.argsort(scores, { descending: true }); // [1, 3, 2, 0]
136
+ const best = gpu.topk(scores, 2); // values [0.9, 0.7], indices [1, 3]
137
+ const passed = await gpu.filter(scores, scores.gt(0.5)); // [0.9, 0.7]
138
+ const hist = gpu.histogram(scores, { bins: 4, range: [0, 1] });
139
+ console.log(await order.read(), await best.indices.read(), await passed.read(), await hist.counts.read());
140
+ ```
141
+
142
+ ## Your own kernels
143
+
144
+ `gpu.kernel(wgsl)` reads the module's `@group @binding` declarations. `run` then binds resources by name: GpuArrays,
145
+ GPU buffers, textures, samplers, or plain objects for uniform structs, laid out by WGSL's alignment rules. `count`
146
+ threads round up to whole workgroups; `workgroups` or `indirect` (a GPU array of counts) dispatch directly.
147
+ `kernel.bind(resources)` keeps the bind groups for runs every frame: `set(name, value)` rewrites a uniform in place.
148
+
149
+ ```ts
150
+ import { createCompute } from '@margoengine/compute';
151
+
152
+ using gpu = await createCompute();
153
+ const n = 1024;
154
+ const src = gpu.arange(0, n, 1, 'f32');
155
+ const dst = gpu.zeros(n);
156
+ const saxpy = gpu.kernel(/* wgsl */ `
157
+ struct Params { a: f32, count: u32 }
158
+ @group(0) @binding(0) var<storage, read> x: array<f32>;
159
+ @group(0) @binding(1) var<storage, read_write> y: array<f32>;
160
+ @group(0) @binding(2) var<uniform> params: Params;
161
+ @compute @workgroup_size(64) fn main(@builtin(global_invocation_id) id: vec3u) {
162
+ if (id.x < params.count) { y[id.x] = params.a * x[id.x] + y[id.x]; }
163
+ }`);
164
+ saxpy.run({ x: src, y: dst, params: { a: 2, count: n } }, { count: n });
165
+ console.log(await dst.read({ length: 4 })); // [0, 2, 4, 6]
166
+ ```
167
+
168
+ ## Linear algebra, FFT, convolution and random numbers
169
+
170
+ `@margoengine/compute/linalg` provides:
171
+
172
+ - `matmul(a, b)` with NumPy's rules (batched, broadcasting; transposed views are read without copies);
173
+ - `dot`, `outer` and `norm`.
174
+
175
+ `@margoengine/compute/fft` provides:
176
+
177
+ - `fft` and `ifft` for any length (Stockham for powers of two, Bluestein otherwise), along any axis, on
178
+ `{ re, im }` arrays;
179
+ - `fft2`, `ifft2` and `fftfreq`.
180
+
181
+ `@margoengine/compute/signal` provides:
182
+
183
+ - `convolve` and `correlate` with NumPy's modes;
184
+ - `convolve2d` with SciPy's zero fill.
185
+
186
+ Each picks the direct or the FFT method by kernel size.
187
+
188
+ `@margoengine/compute/random` provides `new Random(gpu, { seed, stream })`, a Philox4x32-10 generator with
189
+ `uniform`, `normal`, `integers`, `bits`, `permutation` and `choice`. Every draw except `normal` is bit-identical on
190
+ every device and on the CPU backend; `normal` uses the precise functions ([Precision](#precision)), so it agrees with
191
+ the CPU backend to a few ulp on every GPU. Uniforms carry 24 random bits, so `normal` (Box-Muller) never goes past
192
+ 5.77 standard deviations. `integers` maps a 32-bit word by multiply and shift without rejection: some values are more
193
+ likely by at most `(high - low) / 2^32` (Lemire 2019). `permutation` sorts random 32-bit keys; a tie, probability under
194
+ `n (n - 1) / 2^33`, keeps index order.
195
+
196
+ ```ts
197
+ import { createCompute } from '@margoengine/compute';
198
+ import { matmul } from '@margoengine/compute/linalg';
199
+ import { fft } from '@margoengine/compute/fft';
200
+ import { convolve } from '@margoengine/compute/signal';
201
+ import { Random } from '@margoengine/compute/random';
202
+
203
+ using gpu = await createCompute();
204
+ const rng = new Random(gpu, { seed: 42 });
205
+ const x = rng.normal([256, 64]);
206
+ const gram = matmul(x.T, x); // 64 x 64
207
+ const { re, im } = fft(rng.uniform(1000)); // any length
208
+ const power = re.square().add(im.square());
209
+ const smooth = convolve(rng.normal(10000), gpu.array([0.25, 0.5, 0.25]), { mode: 'same' });
210
+ console.log(gram.shape, await power.max().item(), smooth.size);
211
+ ```
212
+
213
+ ## Dense decompositions
214
+
215
+ `@margoengine/compute/decomp` provides `solve`, `inv`, `det`, `cholesky`, `qr`, `svd`, `eigh` and `eigvalsh` on stacks of
216
+ matrices, NumPy style. They run in one lazily loaded SIMD Wasm module in f64 on every backend and return f32 arrays:
217
+ partially pivoted LU, lower Cholesky, Householder QR, one-sided cyclic Jacobi SVD (Demmel and Veselic 1992; it never
218
+ forms A^T A) and two-sided Jacobi for symmetric eigenpairs. Options: `fullMatrices` (default `false`, reduced Q and U)
219
+ and `maxSweeps` (default 100, 1 to 1000; a Jacobi method that has not converged by then rejects). An SVD column whose
220
+ singular value is below 2^-150, which rounds to 0 in f32, is set to exactly zero and its singular vector completed
221
+ orthogonally, so rank-deficient inputs such as many repeated columns converge (512 by 512 in under 20 sweeps) while
222
+ every representable small singular value keeps Jacobi's relative accuracy. A missing, blocked or corrupt
223
+ `decomp-kernel.wasm` rejects with a `failed` MargoError that keeps the read or compile error as `cause`. Each matrix must keep
224
+ `8 m n + 2 m^2 + 2 n^2` (plus `2 n k` for a solve with k right-hand sides) at or under 16,777,216 elements, so square
225
+ matrices go up to 1182 (1094 for `solve` with as many columns); larger problems belong to the sparse solvers below.
226
+
227
+ ## Distance fields
228
+
229
+ `@margoengine/compute/distance` turns a mask into distances by jump flooding (Rong and Tan, I3D 2006; the 1+JFA, JFA+1
230
+ and JFA+2 variants, ISVD 2007), in log2 of the longest side passes plus one:
231
+
232
+ - `distanceTransform(mask)`: distance from every cell to the nearest seed (a nonzero mask value), in cells times `spacing`;
233
+ - `signedDistance(mask)`: negative inside, positive outside, zero half a cell from the cell centres (`edge` moves it);
234
+ - `jumpFlood(mask)`: the same with the nearest seed's row-major index per cell (`NO_SEED` when none);
235
+ - `voronoiMap(gpu, sites, shape)`: each cell's nearest site index and distance;
236
+ - `distanceTransformExact(mask, shape)`: the exact CPU transform (Felzenszwalb and Huttenlocher 2012) that the flooded
237
+ results are tested against, right for small inputs.
238
+
239
+ Masks are 2D (2 to 4096 per side) or 3D (2 to 512 per side, and as many cells as the device's storage binding allows,
240
+ 128 MiB per buffer on the WebGL2 layer). A mask is a u32 or i32 array, or any array or expression compared with 0. The
241
+ `variant` option picks the pass list: `'jfa+1'` (default) is wrong at under 0.01 percent of cells in the measured cases
242
+ and never more than 1 cell too far in 2D (2 cells in 3D); plain `'jfa'` is wrong at under 0.02 percent with up to 2.4
243
+ cells of excess. Squared distances are exact integers and ties go to the lower index, so the nearest-seed buffer is
244
+ identical on WebGPU, the WebGL2 layer and the CPU backend. The functions return promises because the CPU backend reads
245
+ its input; on the GPU nothing waits.
246
+
247
+ ```ts
248
+ import { createCompute } from '@margoengine/compute';
249
+ import { distanceTransform, signedDistance } from '@margoengine/compute/distance';
250
+
251
+ using gpu = await createCompute();
252
+ const size = 256;
253
+ const disc = gpu.array(Uint32Array.from({ length: size * size }, (_, i) =>
254
+ Math.hypot((i % size) - 128, Math.floor(i / size) - 128) < 40 ? 1 : 0), { shape: [size, size] });
255
+ using distance = await distanceTransform(disc); // 0 inside the disc, cells to the disc outside
256
+ using signed = await signedDistance(disc); // negative inside
257
+ // Outline 3 cells wide, and a glow that fades over 24 cells.
258
+ const outline = signed.abs().lt(1.5).astype('f32');
259
+ const glow = distance.mul(-1 / 24).add(1).clip(0, 1);
260
+ console.log(await outline.sum().item(), await glow.max().item(), await signed.min().item());
261
+ ```
262
+
263
+ ## Sparse matrices and solvers
264
+
265
+ `@margoengine/compute/sparse` holds sparse matrices in compressed sparse row (CSR) form on the GPU, as SciPy does:
266
+
267
+ - `coo(gpu, { rows, cols, values, shape })` from coordinates in any order (duplicates are summed);
268
+ - `csr(gpu, { rowPtr, colIdx, values, shape })` from CSR arrays;
269
+ - `diags(gpu, values, offsets, shape)` for constant diagonals;
270
+ - `A.matvec(x)` or `spmv(A, x)`, `A.transpose()`, `A.diagonal()`, `A.toDense()`.
271
+
272
+ `cg(A, b)` (conjugate gradient, for symmetric positive definite A) and `bicgstab(A, b)` (any square A) solve A x = b
273
+ on the GPU. Their scalars stay in GPU memory between iterations, so the only read-back is the residual every
274
+ `checkEvery` iterations, so a converged solve reports a multiple of `checkEvery` iterations (or `maxIterations`).
275
+ Both resolve `{ x, iterations, residual, converged }` and do not reject when they run out of iterations. Arithmetic
276
+ is f32: a badly conditioned system may stop short of `tol` (`converged: false`), and a breakdown returns the last x
277
+ whose residual was finite.
278
+
279
+ | Option | Default | Meaning |
280
+ | --- | --- | --- |
281
+ | `tol` | `1e-5` | stop when the residual is at most `tol` times the norm of b (f32 arithmetic) |
282
+ | `atol` | `0` | or at most `atol` |
283
+ | `maxIterations` | 10 times the rows | most iterations |
284
+ | `preconditioner` | `'jacobi'` | `'jacobi'` (divide by the diagonal) or `'none'` |
285
+ | `checkEvery` | `32` | iterations between residual read-backs |
286
+ | `x0` | zeros | starting guess |
287
+ | `signal` | none | abandon the solve |
288
+
289
+ ```ts
290
+ import { createCompute } from '@margoengine/compute';
291
+ import { cg, diags } from '@margoengine/compute/sparse';
292
+
293
+ using gpu = await createCompute();
294
+ const n = 1000;
295
+ using A = diags(gpu, [-1, 4, -1], [-1, 0, 1], [n, n]); // a diagonally dominant tridiagonal system
296
+ const b = gpu.ones(n);
297
+ const { x, iterations, converged } = await cg(A, b, { tol: 1e-6 });
298
+ console.log(converged, iterations, await x.max().item());
299
+ ```
300
+
301
+ ## Gradients
302
+
303
+ `@margoengine/compute/autodiff` differentiates element-wise expressions in reverse mode. `grad(output, [a, b])`
304
+ returns the gradient of `sum(output)` with respect to each array, with the arrays' shapes. `valueAndGrad` also
305
+ returns the sum. `{ seed }` weights the elements, giving `sum(output * seed)`.
306
+
307
+ - Gradients are lazy expressions over the same tree. Each one runs as one fused kernel that recomputes the forward
308
+ values it needs.
309
+ - They flow through arithmetic, maths functions, `where`, `minimum`, `maximum` and `clip`, and through broadcasting
310
+ (summed over the broadcast axes).
311
+ - They flow through views: a transpose or slice adds into the array it reads.
312
+ - Rounding, comparisons and bit operations have no gradient. `grad` by an integer array throws a TypeError.
313
+ - Matrix products and reductions inside the expression are not differentiated: they are already arrays when the
314
+ expression reads them.
315
+
316
+ ```ts
317
+ import { createCompute } from '@margoengine/compute';
318
+ import { valueAndGrad } from '@margoengine/compute/autodiff';
319
+
320
+ using gpu = await createCompute();
321
+ const x = gpu.array([0, 1, 2, 3]),
322
+ y = gpu.array([1, 3, 5, 7]);
323
+ const w = gpu.array([0], { shape: [] }),
324
+ b = gpu.array([0], { shape: [] });
325
+ for (let step = 0; step < 200; step++) {
326
+ const { value, grads } = valueAndGrad(w.mul(x).add(b).sub(y).square(), [w, b]);
327
+ // Gradient descent step: w -= 0.02 * dw (written back into w's buffer).
328
+ w.write(await w.sub(grads[0].mul(0.02)).read());
329
+ b.write(await b.sub(grads[1].mul(0.02)).read());
330
+ for (const a of [value, ...grads]) a.dispose();
331
+ }
332
+ console.log(await w.item(), await b.item()); // close to 2 and 1
333
+ ```
334
+
335
+ ## Neural networks
336
+
337
+ `@margoengine/compute/nn` trains and runs neural networks, with names and shapes that follow PyTorch. It is built from the
338
+ package's own arrays, so a network runs unchanged on WebGPU and on the CPU backend.
339
+
340
+ - **Layers:** `Linear`, `Conv1d`, `Conv2d` (stride, padding, dilation), `MaxPool2d`, `AvgPool2d`, `Flatten`, `Dropout`,
341
+ `LayerNorm`, `Embedding`, `MultiHeadAttention` (`causal`; self or cross attention), `Sequential`. Subclass `Module` for your
342
+ own: parameters and layers kept as plain properties are found by `parameters()`.
343
+ - **Activations**, as layers and as `Tensor` methods: `ReLU`, `LeakyReLU`, `GELU` (the tanh form), `SiLU`, `Sigmoid`, `Tanh`,
344
+ `Softmax`. `Tensor` also has `logSoftmax`, `exp`, `log` and `rsqrt`.
345
+ - **Losses:** `crossEntropy(logits, labels)` (it takes logits, not probabilities) and `mseLoss(prediction, target)`.
346
+ - **Optimizers:** `SGD` (`momentum`, `weightDecay`), `Adam` and `AdamW`. AdamW scales its decay by the learning rate as
347
+ PyTorch does (`weights *= 1 - lr * weightDecay`); the paper's lambda is `lr * weightDecay`. Change `opt.lr` between steps to schedule it.
348
+ - **Functions:** `scaledDotProductAttention(q, k, v, { causal })`, `dropout`, `noGrad(work)`.
349
+
350
+ A `Tensor` holds a GpuArray and how it was made. `tensor(array)` wraps your input, `parameter(array)` makes one to train, and
351
+ `loss.backward()` fills `grad` on the parameters. Disposing a result (`using` does it for you) frees everything its forward and
352
+ backward passes made; parameters, their gradients and your input arrays stay. `model.predict(array)` runs inference and keeps
353
+ only the result. `await model.stateDict()` and `model.loadStateDict(state)` save and restore weights;
354
+ `model.stateDict({ signal })` and `tensor.read({ signal })` cancel a large readback. Pass one
355
+ `rng: new Random(gpu, { seed })` to the layers to make starting weights repeat.
356
+
357
+ ```ts
358
+ import { createCompute } from '@margoengine/compute';
359
+ import { Random } from '@margoengine/compute/random';
360
+ import { AdamW, Conv2d, Flatten, Linear, MaxPool2d, ReLU, Sequential, crossEntropy, tensor } from '@margoengine/compute/nn';
361
+
362
+ using gpu = await createCompute();
363
+ const rng = new Random(gpu, { seed: 1 });
364
+ using model = new Sequential(
365
+ new Conv2d(gpu, 1, 8, 3, { padding: 1, rng }),
366
+ new ReLU(),
367
+ new MaxPool2d(2),
368
+ new Flatten(),
369
+ new Linear(gpu, 8 * 14 * 14, 10, { rng }),
370
+ );
371
+ using opt = new AdamW(model.parameters(), { lr: 1e-3 });
372
+ const images = rng.uniform([32, 1, 28, 28]);
373
+ const labels = rng.integers(0, 10, 32);
374
+ for (let step = 0; step < 10; step++) {
375
+ opt.zeroGrad();
376
+ using loss = crossEntropy(model.forward(tensor(images)), labels);
377
+ loss.backward();
378
+ opt.step();
379
+ if (step === 9) console.log(await loss.item());
380
+ }
381
+ console.log((await model.predict(images).read()).length); // 320: 10 logits per image
382
+ ```
383
+
384
+ ```ts
385
+ import { createCompute } from '@margoengine/compute';
386
+ import { LayerNorm, MultiHeadAttention, tensor } from '@margoengine/compute/nn';
387
+
388
+ using gpu = await createCompute();
389
+ using attention = new MultiHeadAttention(gpu, 64, 8, { causal: true });
390
+ using norm = new LayerNorm(gpu, 64);
391
+ const x = tensor(gpu.zeros([2, 16, 64])); // batch, length, features
392
+ using y = norm.forward(attention.forward(x));
393
+ console.log(y.shape); // [2, 16, 64]
394
+ ```
395
+
396
+ Gradients of convolutions and pooling repeat exactly from run to run. `Embedding` gradients add repeated ids atomically, so
397
+ their rounding may vary on a GPU. [docs/limits.md](../../docs/limits.md#rendering) has what is left out and what memory it takes.
398
+
399
+ ## Graphs
400
+
401
+ `@margoengine/compute/graph` runs breadth-first search, shortest paths and connected components on sparse graphs, on WebGPU
402
+ and on the CPU backend. A graph is a `CsrMatrix` from `/sparse`, where row `r` lists the edges out of vertex `r` and each
403
+ value is that edge's weight, so one matrix serves the solvers and these. `graph(gpu, { vertices, sources, targets })` builds one
404
+ from edge lists: `weights` default to 1, `directed: false` makes every edge run both ways, and repeated edges keep the
405
+ smallest weight (`coo` would add them).
406
+
407
+ - **`bfs(g, sources)`** resolves `distances` (i32, edges from the nearest source, -1 where no path leads), `predecessors`
408
+ and `iterations`. It ignores weights and follows edges forward.
409
+ - **`shortestPaths(g, sources)`** (Bellman-Ford) resolves `distances` (f32, Infinity where no path leads), `predecessors`,
410
+ `iterations` and `negativeCycle`. Weights may be negative. `negativeCycle: true` means a cycle of negative total weight can
411
+ be reached from a source: no shortest path exists then and the other results mean nothing.
412
+ - **`connectedComponents(g)`** resolves `labels` (i32, numbered from 0 by each component's smallest vertex), `count` and
413
+ `iterations`. Every edge counts both ways, so a directed graph gives its weakly connected components.
414
+
415
+ `sources` is one vertex or a list; distances are then to the nearest. `predecessors` (i32) holds the vertex before each one on
416
+ a shortest path, the smallest if several tie, and -1 at sources and unreached vertices. Zero-weight cycles can make
417
+ `shortestPaths` predecessors tie into a loop; `distances` still hold. The results belong to you: dispose them. Every algorithm
418
+ takes `checkEvery` (rounds between read-backs of whether anything changed, default 8) and `signal`.
419
+
420
+ ```ts
421
+ import { createCompute } from '@margoengine/compute';
422
+ import { bfs, connectedComponents, graph, shortestPaths } from '@margoengine/compute/graph';
423
+
424
+ using gpu = await createCompute();
425
+ using g = graph(gpu, {
426
+ vertices: 5,
427
+ sources: [0, 0, 1, 2],
428
+ targets: [1, 2, 3, 3],
429
+ weights: [4, 1, 1, 1],
430
+ });
431
+ console.log(await (await bfs(g, 0)).distances.read()); // [0, 1, 1, 2, -1]
432
+ const { distances, predecessors } = await shortestPaths(g, 0);
433
+ console.log(await distances.read()); // [0, 4, 1, 2, Infinity]
434
+ console.log(await predecessors.read()); // [-1, 0, 0, 2, -1]
435
+ const { labels, count } = await connectedComponents(g);
436
+ console.log(count, await labels.read()); // 2 [0, 0, 0, 0, 1]
437
+ ```
438
+
439
+ Every round visits every edge, so a run costs edges x rounds and a long thin graph (a road network) takes as many rounds as
440
+ its longest shortest path. [docs/limits.md](../../docs/limits.md#rendering) has the numbers.
441
+
442
+ ## Streams and frames
443
+
444
+ `@margoengine/compute/stream` works through data larger than GPU memory, chunk by chunk. It reads the next chunk
445
+ while the GPU works on the current one. It provides:
446
+
447
+ - `stream(gpu, source, work)`;
448
+ - `reduceStream`;
449
+ - `statsStream` (count, mean, variance, min and max in one pass);
450
+ - `histogramStream`;
451
+ - `chunks(array, size)`.
452
+
453
+ A source is any iterable or async iterable of TypedArrays.
454
+
455
+ `@margoengine/compute/frame` runs kernels every frame inside an engine's frame graph:
456
+
457
+ - `ComputeFrame.attach(engine)` attaches it; `frame.gpu` is a context on the engine's device;
458
+ - `frame.add(bound, run)` adds a job;
459
+ - jobs encode into the frame's own command encoder before the scene draws, so their buffers feed the same frame;
460
+ - `gpu.drawable(shape)` makes arrays the engine can draw from;
461
+ - `gpu.indirectArgs()` makes arrays that GPU culling can size dispatches with.
462
+
463
+ ```ts
464
+ import { createCompute } from '@margoengine/compute';
465
+ import { chunks, statsStream } from '@margoengine/compute/stream';
466
+
467
+ using gpu = await createCompute();
468
+ const big = new Float32Array(10_000_000).map(() => Math.random());
469
+ const stats = await statsStream(gpu, chunks(big, 1 << 22));
470
+ console.log(stats.count, stats.mean, stats.variance);
471
+ ```
472
+
473
+ ```ts
474
+ import { Engine } from '@margoengine/core';
475
+ import { ComputeFrame } from '@margoengine/compute/frame';
476
+
477
+ const canvas = document.querySelector('canvas')!;
478
+ const engine = await Engine.create(canvas);
479
+ const frame = ComputeFrame.attach(engine);
480
+ const positions = frame.gpu.drawable(4096 * 4);
481
+ const step = frame.gpu
482
+ .kernel(/* wgsl */ `
483
+ struct P { dt: f32 }
484
+ @group(0) @binding(0) var<storage, read_write> positions: array<vec4f>;
485
+ @group(0) @binding(1) var<uniform> p: P;
486
+ @compute @workgroup_size(64) fn main(@builtin(global_invocation_id) id: vec3u) {
487
+ if (id.x < arrayLength(&positions)) { positions[id.x].y += p.dt; }
488
+ }`)
489
+ .bind({ positions, p: { dt: 0 } });
490
+ frame.add(step, (dt) => (step.set('p', { dt }), { count: 4096 }));
491
+ engine.start();
492
+ ```
493
+
494
+ `ComputeFrame` can also be registered in a secondary scene. Disposal removes
495
+ that registration, releases its context and arrays, and preserves the engine's
496
+ device and any same-name plugin in another scene. Device restoration replaces
497
+ the context and clears jobs while retaining registration.
498
+
499
+ ```ts
500
+ import {Engine} from '@margoengine/core';
501
+ import {ComputeFrame} from '@margoengine/compute/frame';
502
+ const engine = await Engine.create(document.querySelector('canvas')!);
503
+ const product = engine.createScene('product');
504
+ const frame = new ComputeFrame();
505
+ product.use(frame);
506
+ const data = frame.gpu.zeros(4);
507
+ frame.dispose();
508
+ console.assert(engine.sceneOf(frame) === undefined && data.disposed);
509
+ ```
510
+
511
+ ## Subgroups
512
+
513
+ `@margoengine/compute/subgroups` runs a context's reductions, flat scans and radix sorts on WebGPU subgroups.
514
+ `useSubgroups(gpu)` swaps the kernels; every call keeps its API, and so does what is built on them (`compact`, `filter`,
515
+ `unique`, `topk`, `quantile`).
516
+
517
+ - It returns true when the subgroup kernels are in use. It returns false and changes nothing on a device without the
518
+ `subgroups` feature: the CPU backend, the WebGL2 layer, or a shared device made without it. `gpu.subgroups` says
519
+ which you have. `createCompute()` asks for the feature on a device of its own; a device you pass in must have it.
520
+ - Integers, orders, sorts and stable ties are exactly what the default kernels give. Custom `{ combine, identity }`
521
+ operators keep their left-to-right order.
522
+ - Float sums round in another order, which depends on the GPU's subgroup size. That is why it is a choice: the default
523
+ kernels sum in the same order on every GPU. On one GPU a sum repeats exactly from run to run.
524
+ - It works at every subgroup size WebGPU allows, without assuming which invocations share a subgroup. Checked at 32
525
+ (RTX A6000) and 4 (SwiftShader).
526
+ - Not swapped: `f16` arrays, `argmin` and `argmax`, `segmentedScan` and scans along an axis, and axis reductions with
527
+ one thread per output (many outputs or short lines). Those run the default kernels.
528
+
529
+ Sorts gain the most, since a digit is ranked in one step instead of four. Sums and scans are limited by memory, so they
530
+ gain little on a big GPU: [docs/limits.md](../../docs/limits.md#rendering) has the measured rows.
531
+
532
+ ```ts
533
+ import { createCompute } from '@margoengine/compute';
534
+ import { useSubgroups } from '@margoengine/compute/subgroups';
535
+
536
+ using gpu = await createCompute();
537
+ const active = useSubgroups(gpu); // false on the CPU backend, and everything below still works
538
+ const keys = gpu.array(new Uint32Array([5, 3, 9, 1]));
539
+ console.log(active, await gpu.sort(keys).read(), await keys.sum().item()); // [1, 3, 5, 9] 18
540
+ ```
541
+
542
+ ## Workgroup autotuning
543
+
544
+ `@margoengine/compute/autotune` picks your kernel's workgroup size by timing it on this adapter, because the fastest size
545
+ depends on the GPU and the kernel. Write the kernel as a function of the size. `autotune` runs it at each candidate, resolves
546
+ the fastest `kernel` and `workgroupSize`, and remembers the answer, so later calls run nothing. It needs a GPU: the CPU backend
547
+ rejects with `unsupported`, as any WGSL kernel does.
548
+
549
+ ```ts
550
+ import { createCompute } from '@margoengine/compute';
551
+ import { autotune } from '@margoengine/compute/autotune';
552
+
553
+ using gpu = await createCompute();
554
+ const n = 1 << 20;
555
+ const x = gpu.arange(0, n, 1, 'f32');
556
+ const y = gpu.zeros(n);
557
+ const { kernel, workgroupSize, timings, cached } = await autotune(gpu, {
558
+ name: 'saxpy',
559
+ signature: String(n),
560
+ source: (size) => /* wgsl */ `
561
+ @group(0) @binding(0) var<storage, read> x: array<f32>;
562
+ @group(0) @binding(1) var<storage, read_write> y: array<f32>;
563
+ @compute @workgroup_size(${size}) fn main(@builtin(global_invocation_id) id: vec3u) {
564
+ if (id.x < ${n}u) { y[id.x] = 2.0 * x[id.x] + y[id.x]; }
565
+ }`,
566
+ run: (kernel) => kernel.run({ x, y }, { count: n }),
567
+ });
568
+ console.log(workgroupSize, cached, timings); // for example [256, 1, 1] false [{ workgroupSize: [256, 1, 1], ms: 0.2 }, ...]
569
+ y.write(new Float32Array(n)); // the runs above changed y
570
+ kernel.run({ x, y }, { count: n });
571
+ console.log(await y.read({ length: 3 })); // [0, 2, 4]
572
+ ```
573
+
574
+ `run` must do what the real work does, at the real size: a size that wins on a small input can lose on a large one. Say what
575
+ it depends on in `signature` (default `''`). `run` runs many times, so write it to be repeatable. Options:
576
+
577
+ - `candidates`: sizes to try, numbers or `[x, y, z]`. Default 256, 128, 64, 32, 512, 1024. Those over the device's limits are
578
+ dropped, and on a tie the earlier wins.
579
+ - `trials`: timed runs of each size, of which the median counts. Default 7. Sizes take turns within each round.
580
+ - `warmup`: untimed runs of each size first. Default 2.
581
+ - `store`: keeps results across sessions; `localStorage` fits, or any object with `getItem` and `setItem`, async or not. An
582
+ error from it reaches you. Default none: results last as long as the context.
583
+ - `refresh`: measures again even if a result is known. Default false.
584
+ - `entryPoint` and `signal`.
585
+
586
+ Times are GPU time from timestamp queries, or wall clock up to `gpu.done()` on a device without them. Browsers round GPU
587
+ timestamps (steps of 0.066 ms in the Chrome tested), so sizes of a short kernel can tie: have `run` dispatch it several times.
588
+ Equal medians go to the better mean, then to the earlier candidate. A result is kept per
589
+ adapter, `name`, `signature`, WGSL source and candidate list, so changing any of them measures again.
590
+
591
+ `tuneCompute` does the same for the package's own `reduce`, `scan` and `sort` kernels. It times each at 64 to 1024 threads and
592
+ the context uses the winners from then on. Keep the table and pass it to `createCompute({ tuned })` to skip measuring.
593
+
594
+ ```ts
595
+ import { createCompute } from '@margoengine/compute';
596
+ import { tuneCompute } from '@margoengine/compute/autotune';
597
+
598
+ using gpu = await createCompute();
599
+ if (gpu.backend === 'webgpu') {
600
+ const { tuned, timings } = await tuneCompute(gpu, { count: 1 << 20 }); // the array size your work has
601
+ console.log(tuned, timings.sort); // { reduce: 128, scan: 128, sort: 64 } on an Apple M6
602
+ }
603
+ const keys = gpu.array(new Uint32Array([5, 3, 9, 1]));
604
+ console.log(await gpu.sort(keys).read()); // [1, 3, 5, 9]
605
+ ```
606
+
607
+ Options are `count` (default 4,194,304), `trials`, `warmup`, `store`, `refresh` and `signal`, as above. `createCompute({ tuned })`
608
+ takes `reduce`, `scan` and `sort`, each 64, 128, 256, 512 or 1024 and within the device's limit, and refuses anything else.
609
+ Default 256 for all three. Integer results and sort orders stay the same; float sums round in another order. Other operations
610
+ keep their fixed sizes: `sum(axis)`, segmented scans, the fused element-wise kernels. The CPU backend, `useSubgroups` and the
611
+ WebGL2 layer's sort use kernels of their own and ignore the table; call `tuneCompute` before `useSubgroups`.
612
+
613
+ The gain depends on the GPU. On an Apple M6 a million-key sort went from 3.55 ms at the default 256 to 3.09 ms at 64, and 16.8
614
+ million keys from 60.2 to 55.6 ms at 128. On an RTX A6000 256 was already the best for all three, so tuning changes nothing there.
615
+
616
+ ## CPU fallback
617
+
618
+ `createCompute()` uses WebGPU when the runtime has a usable adapter and otherwise falls back to the CPU, so code
619
+ written for the GPU also runs in Node and on machines without WebGPU. `gpu.backend` says which you got
620
+ (`'webgpu'` or `'cpu'`). `createCompute({ backend: 'cpu' })` always picks the CPU and `{ backend: 'webgpu' }` never
621
+ does (it rejects instead). The CPU code loads with `import()` only when it is used.
622
+
623
+ The CPU backend has the same API and the same results as the GPU path:
624
+
625
+ - Arrays, views, broadcasting and fused expressions run through an interpreter of the same expression tree. Every
626
+ value is rounded to its element type as on the GPU (f32 rounding, 32-bit integer wrap).
627
+ - Reductions, scans and sorts give the same orders, counts and integer results. Float sums are accumulated in double
628
+ precision, so they agree with the GPU to f32 rounding.
629
+ - `/linalg`, `/fft`, `/signal`, `/random` and `/stream` work unchanged. `Random` draws the same Philox stream, word
630
+ for word.
631
+ - What needs a GPU throws a MargoError with code `unsupported`: your own WGSL (`gpu.kernel`, `gpu.map`, custom
632
+ `{ combine, identity }` operators), `f16` arrays and `/frame`.
633
+
634
+ The browser test compares the two backends on the same inputs. The CPU runs on the calling thread and is much slower
635
+ than a GPU: the `compute` benchmark suite times both ([docs/benchmarking.md](../../docs/benchmarking.md#gpu-compute)).
636
+
637
+ On the WebGL2 compatibility layer (`@margoengine/webgl2-compat`), `gpu.backend` is `'webgpu'` and everything runs as
638
+ on WebGPU, with one route of its own: sorts run as a single-invocation radix sort (loaded with `import()` only there),
639
+ since the layer has no workgroup memory. The order is the same stable order.
640
+
641
+ ```ts
642
+ import { createCompute } from '@margoengine/compute';
643
+
644
+ using gpu = await createCompute(); // WebGPU when available, otherwise the CPU
645
+ const x = gpu.array(new Float32Array([4, 1, 3, 2]));
646
+ console.log(gpu.backend, await gpu.sort(x).read(), await x.mean().item()); // 'cpu' in Node: [1, 2, 3, 4] 2.5
647
+ ```
648
+
649
+ ## Errors, waiting and profiling
650
+
651
+ Operations queue GPU work and return at once. Anything that waits (`read`, `item`, `done`, `profile`, `filter`) takes
652
+ an `AbortSignal`. When queued work failed on the GPU (a WGSL error in a kernel or expression, or out of memory), it
653
+ rejects with a `MargoError` whose `code` is `failed` and whose message includes the GPU's diagnostic (validation,
654
+ out-of-memory and internal errors alike). Argument
655
+ mistakes throw `TypeError` or `RangeError` at once, naming the fix, and every message links to
656
+ [margoengine.com/errors](https://margoengine.com/errors#compute).
657
+
658
+ `await gpu.profile(() => work())` resolves the GPU time of every pass, from timestamp queries.
659
+
660
+ ## Options and defaults
661
+
662
+ | Option | Default | Meaning |
663
+ | --- | --- | --- |
664
+ | `createCompute({ engine })` | none | share the engine's WebGPU device |
665
+ | `createCompute({ device })` | none | share a GPUDevice you made |
666
+ | `createCompute({ backend })` | `'auto'` | `'auto'`, `'webgpu'` or `'cpu'` (see [CPU fallback](#cpu-fallback)) |
667
+ | `createCompute({ fastMath })` | `false` | WGSL builtins for the transcendental functions (see [Precision](#precision)) |
668
+ | `createCompute({ powerPreference })` | `'high-performance'` (none on Windows, where browsers ignore it) | adapter choice for a device of its own |
669
+ | `createCompute({ signal })` | none | abandon device creation |
670
+ | `array(data, { dtype })` | from the TypedArray, else `'f32'` | element type |
671
+ | `array(data, { shape })` | `[data.length]` | dimensions |
672
+ | reductions `{ axis, keepdims }` | every axis, `false` | where to reduce |
673
+ | `var` / `std` `{ ddof }` | `0` | delta degrees of freedom |
674
+ | `scan({ op, exclusive, axis })` | `'sum'`, `false`, flat | scan kind |
675
+ | `sort({ descending, bits })` | `false`, `32` | order; low key bits for small u32 keys |
676
+ | `take({ axis, mode })` | flat, `'clip'` | gather axis; out-of-range handling |
677
+ | `scatter({ op })` | `'set'` | `'add'`, `'min'` or `'max'` combine duplicates |
678
+ | `histogram({ bins, range })` | `64`, data range | binning |
679
+ | `convolve({ mode, method })` | `'full'`, `'auto'` | NumPy mode; direct or FFT |
680
+ | `new Random(gpu, { seed, stream })` | random seed, `0` | reproducibility |
681
+ | `ComputeFrame.attach(engine, { order })` | `-1000` | frame-graph order of the jobs |
682
+
683
+ Integer sums wrap at 32 bits. GPU float arithmetic is f32 (f16 for `f16` arrays). Results agree with NumPy's float64
684
+ to f32 rounding, not bit for bit.
685
+
686
+ ## Precision
687
+
688
+ The WGSL builtins for `sin`, `exp`, `pow` and the other transcendental functions are only as accurate as the WGSL
689
+ specification asks, and GPUs differ: `sin` and `cos` may be 2^-11 off inside [-pi, pi] and anything outside it, `atan2`
690
+ 4096 ulp, `asin` 6.8e-5, `log` 2^-21 near 1, and `pow` is undefined for a negative base. An Intel Arc 140V is 1.1e-5
691
+ off for `sin` near 1.5 where an RTX A6000 is within 3e-7; the A6000's `tanh` is 133 ulp off and its `pow` 114. So
692
+ element-wise functions use precise f32 versions by default, the same on every GPU, within these bounds of the exact
693
+ value (in ulp of the result):
694
+
695
+ | Functions | Bound |
696
+ | --- | --- |
697
+ | `sin`, `cos`, `acos`, `exp`, `exp2`, `log`, `sqrt` | 1 |
698
+ | `asin`, `log2` | 1.5 |
699
+ | `atan`, `atan2`, `expm1`, `log1p`, `sinh`, `cosh`, `tanh` | 2 |
700
+ | `tan` | 2.5 |
701
+ | `pow` | 2 while `|y log2 x| < 16`, 5 up to the ends of the f32 range |
702
+
703
+ The bounds hold on NVIDIA, AMD and Intel GPUs, whose shader compilers reorder floating-point sums as WGSL allows:
704
+ AMD's and Intel's fold `(1 + x) - 1` to `x`, so the precise functions rebuild the operands of each exact step from
705
+ their bits, where the compiler cannot rearrange them. `sin`, `cos` and `tan` reduce any argument exactly, so `sin(1e6)` is as accurate as `sin(1)`. `pow` of a negative base
706
+ and an integer exponent works as in NumPy (`(-2) ** 3` is -8). Division is the builtin (WGSL allows 2.5 ulp).
707
+
708
+ `createCompute({ fastMath: true })` uses the builtins instead: faster for arithmetic-bound kernels, with the bounds
709
+ above only as good as the GPU's. Measured on an RTX A6000, one call per element over 16,777,216 values: the precise
710
+ functions take 1.0 to 1.8 times the builtins, `tan` 2.3 times and `pow` 3 times. The CPU backend computes every function in double precision and rounds to f32 either
711
+ way.
712
+
713
+ ```ts
714
+ import { createCompute } from '@margoengine/compute';
715
+
716
+ using gpu = await createCompute();
717
+ using fast = await createCompute({ fastMath: true });
718
+ const x = gpu.array([1e6, -2]);
719
+ console.log(await x.sin().read(), await x.pow(3).read()); // the same on every GPU: [-0.34999, -0.90930], [1e18, -8]
720
+ console.log(fast.fastMath, (await fast.array([1.5]).sin().read())[0]); // true, within 2^-11 of 0.99749
721
+ ```
722
+
723
+ The browser correctness gate reads the repository's speed phase. During the
724
+ build phase it executes value/error checks and exact candidate-output checks,
725
+ while throughput and hardware winner measurements are explicitly deferred.
726
+ All original measurement scenes remain in the named release speed suite;
727
+ public `autotune` and `tuneCompute` behavior is unchanged.
728
+
729
+ `npm run test:gpu:owners --workspace @margoengine/compute` runs the real
730
+ ComputeFrame ownership regression on native WebGPU and the WebGL2 compatibility
731
+ layer. It is registered in the package GPU plan, including affected merge checks.
732
+
733
+ It checks all 1,024 exact four-dispatch values, direct disposal, the secondary
734
+ scene registration, the default-scene sentinel, and context/array release.
735
+ After building packages, it checks all 1,024 values after each of four exact
736
+ dispatches, then scene detachment and resource release.