@margoengine/compute 0.0.0-stage → 1.0.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.
- package/LICENSE +201 -0
- package/NOTICE +4 -0
- package/README.md +804 -2
- package/dist/array-C29noZq7.js +166 -0
- package/dist/array.d.ts +109 -0
- package/dist/autodiff.d.ts +22 -0
- package/dist/autodiff.js +143 -0
- package/dist/autotune.d.ts +100 -0
- package/dist/autotune.js +179 -0
- package/dist/compat-YK57ZCbA.js +4 -0
- package/dist/compat.d.ts +2 -0
- package/dist/context-CCvs3wkC.js +2479 -0
- package/dist/context.d.ts +376 -0
- package/dist/cpu-D4UQwJ9L.js +871 -0
- package/dist/cpu-kernel.wasm +0 -0
- package/dist/cpu-load-XFcM1TXj.js +5 -0
- package/dist/cpu-load.d.ts +3 -0
- package/dist/cpu-runtime.d.ts +8 -0
- package/dist/cpu-wasm.d.ts +42 -0
- package/dist/cpu-wasm.js +161 -0
- package/dist/cpu.d.ts +138 -0
- package/dist/decomp-kernel.wasm +0 -0
- package/dist/decomp.d.ts +42 -0
- package/dist/decomp.js +158 -0
- package/dist/distance.d.ts +85 -0
- package/dist/distance.js +256 -0
- package/dist/dtype.d.ts +36 -0
- package/dist/errors-CDgOgzCd.js +7 -0
- package/dist/expr-t3jm8acM.js +996 -0
- package/dist/expr.d.ts +196 -0
- package/dist/fft.d.ts +33 -0
- package/dist/fft.js +168 -0
- package/dist/frame.d.ts +76 -0
- package/dist/frame.js +85 -0
- package/dist/graph.d.ts +75 -0
- package/dist/graph.js +174 -0
- package/dist/histogram.d.ts +17 -0
- package/dist/index.d.ts +17 -0
- package/dist/index.js +4 -0
- package/dist/kernel.d.ts +65 -0
- package/dist/linalg.d.ts +21 -0
- package/dist/linalg.js +149 -0
- package/dist/nn-extra.d.ts +130 -0
- package/dist/nn-extra.js +322 -0
- package/dist/nn.d.ts +385 -0
- package/dist/nn.js +704 -0
- package/dist/onnx-image-D2qfYsXf.js +66 -0
- package/dist/onnx-image.d.ts +10 -0
- package/dist/onnx-kernel.wasm +0 -0
- package/dist/onnx-regex-DaesIdrm.js +331 -0
- package/dist/onnx-regex.d.ts +2 -0
- package/dist/onnx.d.ts +167 -0
- package/dist/onnx.js +885 -0
- package/dist/quant.d.ts +59 -0
- package/dist/quant.js +242 -0
- package/dist/random.d.ts +64 -0
- package/dist/random.js +150 -0
- package/dist/reduce.d.ts +34 -0
- package/dist/scan.d.ts +26 -0
- package/dist/select.d.ts +38 -0
- package/dist/shaders.d.ts +80 -0
- package/dist/shape.d.ts +23 -0
- package/dist/shape.js +134 -0
- package/dist/signal.d.ts +29 -0
- package/dist/signal.js +178 -0
- package/dist/sort.d.ts +38 -0
- package/dist/sparse.d.ts +136 -0
- package/dist/sparse.js +273 -0
- package/dist/stream.d.ts +39 -0
- package/dist/stream.js +100 -0
- package/dist/subgroups.d.ts +27 -0
- package/dist/subgroups.js +191 -0
- package/dist/usingCtx-igdMnAhr.js +57 -0
- package/dist/wgsl.d.ts +68 -0
- package/package.json +146 -4
package/README.md
CHANGED
|
@@ -1,3 +1,805 @@
|
|
|
1
|
-
#
|
|
1
|
+
# @margoengine/compute
|
|
2
2
|
|
|
3
|
-
|
|
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
|
+
On the WebGL2 compatibility layer a context loads its sort route (`import()`) when it is made. `createCompute`
|
|
512
|
+
resolves after it, but a `ComputeFrame` makes its context when it attaches, and a sort built on `frame.gpu` before the
|
|
513
|
+
route has loaded keeps the radix passes, which the layer runs on its CPU tier. `frame.ready` (and `gpu.ready`) settles
|
|
514
|
+
once the route is in place; it is already settled on WebGPU. Await it before building kernels on a frame's context:
|
|
515
|
+
|
|
516
|
+
```ts
|
|
517
|
+
import {Engine} from '@margoengine/core';
|
|
518
|
+
import {ComputeFrame} from '@margoengine/compute/frame';
|
|
519
|
+
const engine = await Engine.create(document.querySelector('canvas')!);
|
|
520
|
+
const frame = ComputeFrame.attach(engine);
|
|
521
|
+
await frame.ready;
|
|
522
|
+
const order = frame.gpu.sort(frame.gpu.zeros(1024));
|
|
523
|
+
order.dispose();
|
|
524
|
+
frame.dispose();
|
|
525
|
+
```
|
|
526
|
+
|
|
527
|
+
## Subgroups
|
|
528
|
+
|
|
529
|
+
`@margoengine/compute/subgroups` runs a context's reductions, flat scans and radix sorts on WebGPU subgroups.
|
|
530
|
+
`useSubgroups(gpu)` swaps the kernels; every call keeps its API, and so does what is built on them (`compact`, `filter`,
|
|
531
|
+
`unique`, `topk`, `quantile`).
|
|
532
|
+
|
|
533
|
+
- It returns true when the subgroup kernels are in use. It returns false and changes nothing on a device without the
|
|
534
|
+
`subgroups` feature: the CPU backend, the WebGL2 layer, or a shared device made without it. `gpu.subgroups` says
|
|
535
|
+
which you have. `createCompute()` asks for the feature on a device of its own; a device you pass in must have it.
|
|
536
|
+
- Integers, orders, sorts and stable ties are exactly what the default kernels give. Custom `{ combine, identity }`
|
|
537
|
+
operators keep their left-to-right order.
|
|
538
|
+
- Float sums round in another order, which depends on the GPU's subgroup size. That is why it is a choice: the default
|
|
539
|
+
kernels sum in the same order on every GPU. On one GPU a sum repeats exactly from run to run.
|
|
540
|
+
- It works at every subgroup size WebGPU allows, without assuming which invocations share a subgroup. Checked at 32
|
|
541
|
+
(RTX A6000) and 4 (SwiftShader).
|
|
542
|
+
- Not swapped: `f16` arrays, `argmin` and `argmax`, `segmentedScan` and scans along an axis, and axis reductions with
|
|
543
|
+
one thread per output (many outputs or short lines). Those run the default kernels.
|
|
544
|
+
|
|
545
|
+
Sorts gain the most, since a digit is ranked in one step instead of four. Sums and scans are limited by memory, so they
|
|
546
|
+
gain little on a big GPU: [docs/limits.md](../../docs/limits.md#rendering) has the measured rows.
|
|
547
|
+
|
|
548
|
+
```ts
|
|
549
|
+
import { createCompute } from '@margoengine/compute';
|
|
550
|
+
import { useSubgroups } from '@margoengine/compute/subgroups';
|
|
551
|
+
|
|
552
|
+
using gpu = await createCompute();
|
|
553
|
+
const active = useSubgroups(gpu); // false on the CPU backend, and everything below still works
|
|
554
|
+
const keys = gpu.array(new Uint32Array([5, 3, 9, 1]));
|
|
555
|
+
console.log(active, await gpu.sort(keys).read(), await keys.sum().item()); // [1, 3, 5, 9] 18
|
|
556
|
+
```
|
|
557
|
+
|
|
558
|
+
## Workgroup autotuning
|
|
559
|
+
|
|
560
|
+
`@margoengine/compute/autotune` picks your kernel's workgroup size by timing it on this adapter, because the fastest size
|
|
561
|
+
depends on the GPU and the kernel. Write the kernel as a function of the size. `autotune` runs it at each candidate, resolves
|
|
562
|
+
the fastest `kernel` and `workgroupSize`, and remembers the answer, so later calls run nothing. It needs a GPU: the CPU backend
|
|
563
|
+
rejects with `unsupported`, as any WGSL kernel does.
|
|
564
|
+
|
|
565
|
+
```ts
|
|
566
|
+
import { createCompute } from '@margoengine/compute';
|
|
567
|
+
import { autotune } from '@margoengine/compute/autotune';
|
|
568
|
+
|
|
569
|
+
using gpu = await createCompute();
|
|
570
|
+
const n = 1 << 20;
|
|
571
|
+
const x = gpu.arange(0, n, 1, 'f32');
|
|
572
|
+
const y = gpu.zeros(n);
|
|
573
|
+
const { kernel, workgroupSize, timings, cached } = await autotune(gpu, {
|
|
574
|
+
name: 'saxpy',
|
|
575
|
+
signature: String(n),
|
|
576
|
+
source: (size) => /* wgsl */ `
|
|
577
|
+
@group(0) @binding(0) var<storage, read> x: array<f32>;
|
|
578
|
+
@group(0) @binding(1) var<storage, read_write> y: array<f32>;
|
|
579
|
+
@compute @workgroup_size(${size}) fn main(@builtin(global_invocation_id) id: vec3u) {
|
|
580
|
+
if (id.x < ${n}u) { y[id.x] = 2.0 * x[id.x] + y[id.x]; }
|
|
581
|
+
}`,
|
|
582
|
+
run: (kernel) => kernel.run({ x, y }, { count: n }),
|
|
583
|
+
});
|
|
584
|
+
console.log(workgroupSize, cached, timings); // for example [256, 1, 1] false [{ workgroupSize: [256, 1, 1], ms: 0.2 }, ...]
|
|
585
|
+
y.write(new Float32Array(n)); // the runs above changed y
|
|
586
|
+
kernel.run({ x, y }, { count: n });
|
|
587
|
+
console.log(await y.read({ length: 3 })); // [0, 2, 4]
|
|
588
|
+
```
|
|
589
|
+
|
|
590
|
+
`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
|
|
591
|
+
it depends on in `signature` (default `''`). `run` runs many times, so write it to be repeatable. Options:
|
|
592
|
+
|
|
593
|
+
- `candidates`: sizes to try, numbers or `[x, y, z]`. Default 256, 128, 64, 32, 512, 1024. Those over the device's limits are
|
|
594
|
+
dropped, and on a tie the earlier wins.
|
|
595
|
+
- `trials`: timed runs of each size, of which the median counts. Default 7. Sizes take turns within each round.
|
|
596
|
+
- `warmup`: untimed runs of each size first. Default 2.
|
|
597
|
+
- `store`: keeps results across sessions; `localStorage` fits, or any object with `getItem` and `setItem`, async or not. An
|
|
598
|
+
error from it reaches you. Default none: results last as long as the context.
|
|
599
|
+
- `refresh`: measures again even if a result is known. Default false.
|
|
600
|
+
- `entryPoint` and `signal`.
|
|
601
|
+
|
|
602
|
+
Times are GPU time from timestamp queries, or wall clock up to `gpu.done()` on a device without them. Browsers round GPU
|
|
603
|
+
timestamps (steps of 0.066 ms in the Chrome tested), so sizes of a short kernel can tie: have `run` dispatch it several times.
|
|
604
|
+
Equal medians go to the better mean, then to the earlier candidate. A result is kept per
|
|
605
|
+
adapter, `name`, `signature`, WGSL source and candidate list, so changing any of them measures again.
|
|
606
|
+
|
|
607
|
+
`tuneCompute` does the same for the package's own `reduce`, `scan` and `sort` kernels. It times each at 64 to 1024 threads and
|
|
608
|
+
the context uses the winners from then on. Keep the table and pass it to `createCompute({ tuned })` to skip measuring.
|
|
609
|
+
|
|
610
|
+
```ts
|
|
611
|
+
import { createCompute } from '@margoengine/compute';
|
|
612
|
+
import { tuneCompute } from '@margoengine/compute/autotune';
|
|
613
|
+
|
|
614
|
+
using gpu = await createCompute();
|
|
615
|
+
if (gpu.backend === 'webgpu') {
|
|
616
|
+
const { tuned, timings } = await tuneCompute(gpu, { count: 1 << 20 }); // the array size your work has
|
|
617
|
+
console.log(tuned, timings.sort); // { reduce: 128, scan: 128, sort: 64 } on an Apple M6
|
|
618
|
+
}
|
|
619
|
+
const keys = gpu.array(new Uint32Array([5, 3, 9, 1]));
|
|
620
|
+
console.log(await gpu.sort(keys).read()); // [1, 3, 5, 9]
|
|
621
|
+
```
|
|
622
|
+
|
|
623
|
+
Options are `count` (default 4,194,304), `trials`, `warmup`, `store`, `refresh` and `signal`, as above. `createCompute({ tuned })`
|
|
624
|
+
takes `reduce`, `scan` and `sort`, each 64, 128, 256, 512 or 1024 and within the device's limit, and refuses anything else.
|
|
625
|
+
Default 256 for all three. Integer results and sort orders stay the same; float sums round in another order. Other operations
|
|
626
|
+
keep their fixed sizes: `sum(axis)`, segmented scans, the fused element-wise kernels. The CPU backend, `useSubgroups` and the
|
|
627
|
+
WebGL2 layer's sort use kernels of their own and ignore the table; call `tuneCompute` before `useSubgroups`.
|
|
628
|
+
|
|
629
|
+
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
|
|
630
|
+
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.
|
|
631
|
+
|
|
632
|
+
## CPU fallback
|
|
633
|
+
|
|
634
|
+
`createCompute()` uses WebGPU when the runtime has a usable adapter and otherwise falls back to the CPU, so code
|
|
635
|
+
written for the GPU also runs in Node and on machines without WebGPU. `gpu.backend` says which you got
|
|
636
|
+
(`'webgpu'` or `'cpu'`). `createCompute({ backend: 'cpu' })` always picks the CPU and `{ backend: 'webgpu' }` never
|
|
637
|
+
does (it rejects instead). The CPU code loads with `import()` only when it is used.
|
|
638
|
+
|
|
639
|
+
The CPU backend has the same API and the same results as the GPU path:
|
|
640
|
+
|
|
641
|
+
- Arrays, views, broadcasting and fused expressions run through an interpreter of the same expression tree. Every
|
|
642
|
+
value is rounded to its element type as on the GPU (f32 rounding, 32-bit integer wrap).
|
|
643
|
+
- Reductions, scans and sorts give the same orders, counts and integer results. Float sums are accumulated in double
|
|
644
|
+
precision, so they agree with the GPU to f32 rounding.
|
|
645
|
+
- `/linalg`, `/fft`, `/signal`, `/random` and `/stream` work unchanged. `Random` draws the same Philox stream, word
|
|
646
|
+
for word.
|
|
647
|
+
- What needs a GPU throws a MargoError with code `unsupported`: your own WGSL (`gpu.kernel`, `gpu.map`, custom
|
|
648
|
+
`{ combine, identity }` operators), `f16` arrays and `/frame`.
|
|
649
|
+
|
|
650
|
+
The browser test compares the two backends on the same inputs. The CPU runs on the calling thread and is much slower
|
|
651
|
+
than a GPU: the `compute` benchmark suite times both ([docs/benchmarking.md](../../docs/benchmarking.md#gpu-compute)).
|
|
652
|
+
|
|
653
|
+
On the WebGL2 compatibility layer (`@margoengine/webgl2-compat`), `gpu.backend` is `'webgpu'` and everything runs as
|
|
654
|
+
on WebGPU, with one route of its own: sorts run as a single-invocation radix sort (loaded with `import()` only there),
|
|
655
|
+
since the layer has no workgroup memory. The order is the same stable order.
|
|
656
|
+
|
|
657
|
+
```ts
|
|
658
|
+
import { createCompute } from '@margoengine/compute';
|
|
659
|
+
|
|
660
|
+
using gpu = await createCompute(); // WebGPU when available, otherwise the CPU
|
|
661
|
+
const x = gpu.array(new Float32Array([4, 1, 3, 2]));
|
|
662
|
+
console.log(gpu.backend, await gpu.sort(x).read(), await x.mean().item()); // 'cpu' in Node: [1, 2, 3, 4] 2.5
|
|
663
|
+
```
|
|
664
|
+
|
|
665
|
+
## ONNX models
|
|
666
|
+
|
|
667
|
+
`@margoengine/compute/onnx` runs an ONNX model on the CPU in SIMD Wasm, in Node and in browsers (no GPU inference).
|
|
668
|
+
`loadOnnx` takes a URL or the model's bytes, and `run` takes named `OnnxTensor` inputs and resolves named outputs.
|
|
669
|
+
|
|
670
|
+
```ts
|
|
671
|
+
import { loadOnnx, OnnxTensor } from '@margoengine/compute/onnx';
|
|
672
|
+
|
|
673
|
+
// Normally loadOnnx(new URL('model.onnx', import.meta.url)). These 167 bytes quantize x to uint8 and back.
|
|
674
|
+
const bytes = Uint8Array.from(
|
|
675
|
+
atob(
|
|
676
|
+
'CAo6nAEKHAoBeAoBcwoBehIBcSIOUXVhbnRpemVMaW5lYXIKHgoBcQoBcwoBehIBeSIQRGVxdWFudGl6ZUxpbmVhchISY2xlYW4tcm9vbS1maXh0dXJlKgsQAUIBc0oEAAAAPyoIEAJCAXpKAYBaDwoBeBIKCggIARIECgIIBGIPCgFxEgoKCAgCEgQKAggEYg8KAXkSCgoICAESBAoCCARCBAoAEBU=',
|
|
677
|
+
),
|
|
678
|
+
(c) => c.charCodeAt(0),
|
|
679
|
+
);
|
|
680
|
+
using model = await loadOnnx(bytes);
|
|
681
|
+
const result = await model.run({ x: new OnnxTensor('float32', Float32Array.of(-1, 0.2, 1.3, 100), [4]) });
|
|
682
|
+
const q = result.q as OnnxTensor; // uint8 [126, 128, 131, 255]
|
|
683
|
+
const y = result.y as OnnxTensor; // float32 [-1, 0, 1.5, 63.5]
|
|
684
|
+
console.log(q.data, y.data);
|
|
685
|
+
```
|
|
686
|
+
|
|
687
|
+
Quantized operators follow the ONNX specification: QuantizeLinear and DequantizeLinear (per-tensor, per-axis and
|
|
688
|
+
blocked), DynamicQuantizeLinear, ConvInteger, MatMulInteger, QLinearConv and QLinearMatMul. Every ONNX tensor element
|
|
689
|
+
type through opset 28 loads: the 8-bit, 6-bit and 4-bit floats keep their bits (Cast converts them, with `saturate` and
|
|
690
|
+
`round_mode`), 4-bit and 2-bit values stay packed, and complex tensors are stored and moved but take no arithmetic.
|
|
691
|
+
RegexFullMatch (RE2 syntax, matched without backtracking), TfIdfVectorizer, DeformConv and the sequence-model
|
|
692
|
+
operators (Attention, RotaryEmbedding, TensorScatter, CausalConvWithState, LinearAttention) run too.
|
|
693
|
+
[Limits](../../docs/limits.md#batch-180-job-5-temporal-analysis) lists what is not built.
|
|
694
|
+
|
|
695
|
+
ImageDecoder (opset 20) turns a PNG, JPEG, JPEG 2000, WebP, BMP, TIFF (classic or BigTIFF) or PNM file in a `uint8`
|
|
696
|
+
tensor into `[height, width, channels]` bytes, `RGB` (the default), `BGR` or `Grayscale`, with alpha dropped. It reads
|
|
697
|
+
the files through the optional peer `@margoengine/decoders`: install it beside compute for models that use this
|
|
698
|
+
operator. A stream that cannot be decoded gives the empty matrix `[0, 0, channels]`.
|
|
699
|
+
|
|
700
|
+
```ts
|
|
701
|
+
import {loadOnnx, OnnxTensor} from 'margoengine/compute/onnx';
|
|
702
|
+
|
|
703
|
+
// Normally loadOnnx(new URL('model.onnx', import.meta.url)). These 135 bytes hold one ImageDecoder node, BGR.
|
|
704
|
+
const model135 = Uint8Array.from(
|
|
705
|
+
atob(
|
|
706
|
+
'CAo6fQozCgRmaWxlEgVpbWFnZSIMSW1hZ2VEZWNvZGVyKhYKDHBpeGVsX2Zvcm1hdKABAyIDQkdSEhJjbGVhbi1yb29tLWZpeHR1cmVaEwoEZmlsZRILCgkIAhIFCgMSAW5iHQoFaW1hZ2USFAoSCAISDgoDEgFoCgMSAXcKAggDQgQKABAU',
|
|
707
|
+
),
|
|
708
|
+
(c) => c.charCodeAt(0),
|
|
709
|
+
);
|
|
710
|
+
// A 2 x 1 image as a PPM file: one red pixel and one blue one.
|
|
711
|
+
const file = Uint8Array.from([...new TextEncoder().encode('P6 2 1 255 '), 255, 0, 0, 0, 0, 255]);
|
|
712
|
+
using decoder = await loadOnnx(model135);
|
|
713
|
+
const decoded = await decoder.run({ file: new OnnxTensor('uint8', file, [file.length]) });
|
|
714
|
+
const image = decoded.image as OnnxTensor;
|
|
715
|
+
console.log(image.shape, image.data); // [1, 2, 3] and [0, 0, 255, 255, 0, 0]
|
|
716
|
+
```
|
|
717
|
+
|
|
718
|
+
## Errors, waiting and profiling
|
|
719
|
+
|
|
720
|
+
Operations queue GPU work and return at once. Anything that waits (`read`, `item`, `done`, `profile`, `filter`) takes
|
|
721
|
+
an `AbortSignal`. When queued work failed on the GPU (a WGSL error in a kernel or expression, or out of memory), it
|
|
722
|
+
rejects with a `MargoError` whose `code` is `failed` and whose message includes the GPU's diagnostic (validation,
|
|
723
|
+
out-of-memory and internal errors alike). Argument
|
|
724
|
+
mistakes throw `TypeError` or `RangeError` at once, naming the fix, and every message links to
|
|
725
|
+
[margoengine.com/errors](https://margoengine.com/errors#compute).
|
|
726
|
+
|
|
727
|
+
`await gpu.profile(() => work())` resolves the GPU time of every pass, from timestamp queries.
|
|
728
|
+
|
|
729
|
+
## Options and defaults
|
|
730
|
+
|
|
731
|
+
| Option | Default | Meaning |
|
|
732
|
+
| --- | --- | --- |
|
|
733
|
+
| `createCompute({ engine })` | none | share the engine's WebGPU device |
|
|
734
|
+
| `createCompute({ device })` | none | share a GPUDevice you made |
|
|
735
|
+
| `createCompute({ backend })` | `'auto'` | `'auto'`, `'webgpu'` or `'cpu'` (see [CPU fallback](#cpu-fallback)) |
|
|
736
|
+
| `createCompute({ fastMath })` | `false` | WGSL builtins for the transcendental functions (see [Precision](#precision)) |
|
|
737
|
+
| `createCompute({ powerPreference })` | `'high-performance'` (none on Windows, where browsers ignore it) | adapter choice for a device of its own |
|
|
738
|
+
| `createCompute({ signal })` | none | abandon device creation |
|
|
739
|
+
| `array(data, { dtype })` | from the TypedArray, else `'f32'` | element type |
|
|
740
|
+
| `array(data, { shape })` | `[data.length]` | dimensions |
|
|
741
|
+
| reductions `{ axis, keepdims }` | every axis, `false` | where to reduce |
|
|
742
|
+
| `var` / `std` `{ ddof }` | `0` | delta degrees of freedom |
|
|
743
|
+
| `scan({ op, exclusive, axis })` | `'sum'`, `false`, flat | scan kind |
|
|
744
|
+
| `sort({ descending, bits })` | `false`, `32` | order; low key bits for small u32 keys |
|
|
745
|
+
| `take({ axis, mode })` | flat, `'clip'` | gather axis; out-of-range handling |
|
|
746
|
+
| `scatter({ op })` | `'set'` | `'add'`, `'min'` or `'max'` combine duplicates |
|
|
747
|
+
| `histogram({ bins, range })` | `64`, data range | binning |
|
|
748
|
+
| `convolve({ mode, method })` | `'full'`, `'auto'` | NumPy mode; direct or FFT |
|
|
749
|
+
| `new Random(gpu, { seed, stream })` | random seed, `0` | reproducibility |
|
|
750
|
+
| `ComputeFrame.attach(engine, { order })` | `-1000` | frame-graph order of the jobs |
|
|
751
|
+
|
|
752
|
+
Integer sums wrap at 32 bits. GPU float arithmetic is f32 (f16 for `f16` arrays). Results agree with NumPy's float64
|
|
753
|
+
to f32 rounding, not bit for bit.
|
|
754
|
+
|
|
755
|
+
## Precision
|
|
756
|
+
|
|
757
|
+
The WGSL builtins for `sin`, `exp`, `pow` and the other transcendental functions are only as accurate as the WGSL
|
|
758
|
+
specification asks, and GPUs differ: `sin` and `cos` may be 2^-11 off inside [-pi, pi] and anything outside it, `atan2`
|
|
759
|
+
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
|
|
760
|
+
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
|
|
761
|
+
element-wise functions use precise f32 versions by default, the same on every GPU, within these bounds of the exact
|
|
762
|
+
value (in ulp of the result):
|
|
763
|
+
|
|
764
|
+
| Functions | Bound |
|
|
765
|
+
| --- | --- |
|
|
766
|
+
| `sin`, `cos`, `acos`, `exp`, `exp2`, `log`, `sqrt` | 1 |
|
|
767
|
+
| `asin`, `log2` | 1.5 |
|
|
768
|
+
| `atan`, `atan2`, `expm1`, `log1p`, `sinh`, `cosh`, `tanh` | 2 |
|
|
769
|
+
| `tan` | 2.5 |
|
|
770
|
+
| `pow` | 2 while `|y log2 x| < 16`, 5 up to the ends of the f32 range |
|
|
771
|
+
|
|
772
|
+
The bounds hold on NVIDIA, AMD and Intel GPUs, whose shader compilers reorder floating-point sums as WGSL allows:
|
|
773
|
+
AMD's and Intel's fold `(1 + x) - 1` to `x`, so the precise functions rebuild the operands of each exact step from
|
|
774
|
+
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
|
|
775
|
+
and an integer exponent works as in NumPy (`(-2) ** 3` is -8). Division is the builtin (WGSL allows 2.5 ulp).
|
|
776
|
+
|
|
777
|
+
`createCompute({ fastMath: true })` uses the builtins instead: faster for arithmetic-bound kernels, with the bounds
|
|
778
|
+
above only as good as the GPU's. Measured on an RTX A6000, one call per element over 16,777,216 values: the precise
|
|
779
|
+
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
|
|
780
|
+
way.
|
|
781
|
+
|
|
782
|
+
```ts
|
|
783
|
+
import { createCompute } from '@margoengine/compute';
|
|
784
|
+
|
|
785
|
+
using gpu = await createCompute();
|
|
786
|
+
using fast = await createCompute({ fastMath: true });
|
|
787
|
+
const x = gpu.array([1e6, -2]);
|
|
788
|
+
console.log(await x.sin().read(), await x.pow(3).read()); // the same on every GPU: [-0.34999, -0.90930], [1e18, -8]
|
|
789
|
+
console.log(fast.fastMath, (await fast.array([1.5]).sin().read())[0]); // true, within 2^-11 of 0.99749
|
|
790
|
+
```
|
|
791
|
+
|
|
792
|
+
The browser correctness gate reads the repository's speed phase. During the
|
|
793
|
+
build phase it executes value/error checks and exact candidate-output checks,
|
|
794
|
+
while throughput and hardware winner measurements are explicitly deferred.
|
|
795
|
+
All original measurement scenes remain in the named release speed suite;
|
|
796
|
+
public `autotune` and `tuneCompute` behavior is unchanged.
|
|
797
|
+
|
|
798
|
+
`npm run test:gpu:owners --workspace @margoengine/compute` runs the real
|
|
799
|
+
ComputeFrame ownership regression on native WebGPU and the WebGL2 compatibility
|
|
800
|
+
layer. It is registered in the package GPU plan, including affected merge checks.
|
|
801
|
+
|
|
802
|
+
It checks all 1,024 exact four-dispatch values, direct disposal, the secondary
|
|
803
|
+
scene registration, the default-scene sentinel, and context/array release.
|
|
804
|
+
After building packages, it checks all 1,024 values after each of four exact
|
|
805
|
+
dispatches, then scene detachment and resource release.
|