@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/dist/sparse.js ADDED
@@ -0,0 +1,273 @@
1
+ import { n as e, r as t, t as n } from "./errors-CDgOgzCd.js";
2
+ import { n as r } from "./context-C75sQQra.js";
3
+ import { n as i } from "./expr-DwFen60A.js";
4
+ import { t as a } from "./array-DbI848Wf.js";
5
+ //#region src/sparse.ts
6
+ var o = "struct Shape { rows: u32, pad0: u32, pad1: u32, pad2: u32 }\n@group(0) @binding(0) var<storage, read> rowPtr: array<u32>;\n@group(0) @binding(1) var<storage, read> colIdx: array<u32>;\n@group(0) @binding(2) var<storage, read> values: array<f32>;\n@group(0) @binding(3) var<storage, read> x: array<f32>;\n@group(0) @binding(4) var<storage, read_write> y: array<f32>;\n@group(0) @binding(5) var<uniform> shape: Shape;\n@compute @workgroup_size(256)\nfn main(@builtin(workgroup_id) wid: vec3u, @builtin(num_workgroups) nwg: vec3u, @builtin(local_invocation_index) lid: u32) {\n let r = (wid.x + wid.y * nwg.x) * 256u + lid;\n if (r >= shape.rows) { return; }\n var sum = 0.0;\n for (var k = rowPtr[r]; k < rowPtr[r + 1u]; k++) { sum += values[k] * x[colIdx[k]]; }\n y[r] = sum;\n}", s = "struct Shape { rows: u32, pad0: u32, pad1: u32, pad2: u32 }\n@group(0) @binding(0) var<storage, read> rowPtr: array<u32>;\n@group(0) @binding(1) var<storage, read> colIdx: array<u32>;\n@group(0) @binding(2) var<storage, read> values: array<f32>;\n@group(0) @binding(3) var<storage, read_write> d: array<f32>;\n@group(0) @binding(4) var<uniform> shape: Shape;\n@compute @workgroup_size(256)\nfn main(@builtin(workgroup_id) wid: vec3u, @builtin(num_workgroups) nwg: vec3u, @builtin(local_invocation_index) lid: u32) {\n let r = (wid.x + wid.y * nwg.x) * 256u + lid;\n if (r >= shape.rows) { return; }\n var v = 0.0;\n for (var k = rowPtr[r]; k < rowPtr[r + 1u]; k++) { if (colIdx[k] == r) { v += values[k]; } }\n d[r] = v;\n}", c = (e) => e instanceof a && e.dtype === "f32" && e.contiguous && e.offset === 0 ? {
7
+ array: e,
8
+ owned: !1
9
+ } : {
10
+ array: e.astype("f32").eval(),
11
+ owned: !0
12
+ }, l = class r {
13
+ #e = !1;
14
+ constructor(e, t, n, r, i, a) {
15
+ this.context = e, this.rowPtr = n, this.colIdx = r, this.rowIdx = i, this.values = a, this.shape = Object.freeze([t[0], t[1]]), this.nnz = a.size;
16
+ }
17
+ get disposed() {
18
+ return this.#e;
19
+ }
20
+ #t() {
21
+ if (this.#e) throw n("disposed", "CsrMatrix disposed; create a new one with csr() or coo()", "compute");
22
+ }
23
+ matvec(n) {
24
+ this.#t();
25
+ let r = this.context, [a, s] = this.shape;
26
+ if (!(n instanceof i)) throw t("matvec takes a GpuArray or an Expr", "compute");
27
+ if (n.size !== s) throw e(`matvec of a ${a} x ${s} matrix needs ${s} elements, got ${n.size}`, "compute");
28
+ let l = c(n), u = r.empty([a], "f32");
29
+ return a > 0 && r.submit([{
30
+ program: r.program(o, void 0, "sparse.spmv"),
31
+ resources: {
32
+ rowPtr: this.rowPtr,
33
+ colIdx: this.colIdx,
34
+ values: this.values,
35
+ x: l.array,
36
+ y: u,
37
+ shape: new Uint32Array([
38
+ a,
39
+ 0,
40
+ 0,
41
+ 0
42
+ ])
43
+ },
44
+ workgroups: r.grid(Math.ceil(a / 256))
45
+ }]), l.owned && l.array.dispose(), u;
46
+ }
47
+ diagonal() {
48
+ this.#t();
49
+ let e = this.context, t = Math.min(...this.shape), n = e.empty([t], "f32");
50
+ return t > 0 && e.submit([{
51
+ program: e.program(s, void 0, "sparse.diagonal"),
52
+ resources: {
53
+ rowPtr: this.rowPtr,
54
+ colIdx: this.colIdx,
55
+ values: this.values,
56
+ d: n,
57
+ shape: new Uint32Array([
58
+ t,
59
+ 0,
60
+ 0,
61
+ 0
62
+ ])
63
+ },
64
+ workgroups: e.grid(Math.ceil(t / 256))
65
+ }]), n;
66
+ }
67
+ transpose() {
68
+ this.#t();
69
+ let e = this.context, [t, n] = this.shape, i = e.argsort(this.colIdx, { bits: Math.max(1, Math.ceil(Math.log2(n + 1))) }), a = e.take(this.rowIdx, i), o = e.take(this.colIdx, i), s = e.take(this.values, i);
70
+ return i.dispose(), new r(e, [n, t], u(e, o, n), a, o, s);
71
+ }
72
+ toDense() {
73
+ this.#t();
74
+ let e = this.context, [t, n] = this.shape, r = e.zeros([t * n]), i = this.rowIdx.astype("i32").mul(n).add(this.colIdx.astype("i32"));
75
+ return e.scatter(r, i, this.values, { op: "add" }), r.reshape(t, n);
76
+ }
77
+ dispose() {
78
+ if (!this.#e) {
79
+ this.#e = !0;
80
+ for (let e of [
81
+ this.rowPtr,
82
+ this.colIdx,
83
+ this.rowIdx,
84
+ this.values
85
+ ]) e.dispose();
86
+ }
87
+ }
88
+ [Symbol.dispose]() {
89
+ this.dispose();
90
+ }
91
+ };
92
+ function u(e, t, n) {
93
+ let r = e.bincount(t, { length: n }), i = e.cumsum(r), a = e.zeros([n + 1], "u32");
94
+ return n > 0 && e.scatter(a, e.arange(1, n + 1, 1, "i32"), i), r.dispose(), i.dispose(), a;
95
+ }
96
+ var d = (t, n) => {
97
+ if (!Number.isInteger(t) || t < 0) throw e(`${n} must be a whole number of at least 0, got ${t}`, "compute");
98
+ return t;
99
+ }, f = (t) => {
100
+ if (!t || t.length !== 2) throw e("A sparse matrix needs shape: [rows, cols]", "compute");
101
+ return [d(t[0], "rows"), d(t[1], "cols")];
102
+ };
103
+ function p(t, n) {
104
+ t.check();
105
+ let [r, i] = f(n?.shape), { rows: a, cols: o, values: s } = n, c = s?.length;
106
+ if (a?.length !== c || o?.length !== c) throw e(`coo needs rows, cols and values of one length, got ${a?.length}, ${o?.length}, ${c}`, "compute");
107
+ let u = Array.from({ length: c }, (e, t) => t);
108
+ for (let t = 0; t < c; t++) if (!Number.isInteger(a[t]) || a[t] < 0 || a[t] >= r || !Number.isInteger(o[t]) || o[t] < 0 || o[t] >= i) throw e(`coo entry ${t} at (${a[t]}, ${o[t]}) is outside the ${r} x ${i} matrix`, "compute");
109
+ u.sort((e, t) => a[e] - a[t] || o[e] - o[t] || e - t);
110
+ let d = [], p = [], m = [];
111
+ for (let e of u) {
112
+ let t = m.length - 1;
113
+ t >= 0 && d[t] === a[e] && p[t] === o[e] ? m[t] += s[e] : (d.push(a[e]), p.push(o[e]), m.push(s[e]));
114
+ }
115
+ let h = new Uint32Array(r + 1);
116
+ for (let e of d) h[e + 1]++;
117
+ for (let e = 0; e < r; e++) h[e + 1] += h[e];
118
+ return new l(t, [r, i], t.array(h, "u32"), t.array(p, "u32"), t.array(d, "u32"), t.array(m, "f32"));
119
+ }
120
+ function m(t, n) {
121
+ let [r] = f(n?.shape), { rowPtr: i, colIdx: a, values: o } = n;
122
+ if (i?.length !== r + 1 || i[0] !== 0 || i[r] !== o?.length) throw e(`csr rowPtr needs ${r + 1} offsets from 0 to the ${o?.length} values, got ${i?.length}`, "compute");
123
+ let s = Array(o.length);
124
+ for (let t = 0; t < r; t++) {
125
+ if (!(i[t + 1] >= i[t])) throw e(`csr rowPtr decreases at row ${t}`, "compute");
126
+ for (let e = i[t]; e < i[t + 1]; e++) s[e] = t;
127
+ }
128
+ return p(t, {
129
+ rows: s,
130
+ cols: a,
131
+ values: o,
132
+ shape: n.shape
133
+ });
134
+ }
135
+ function h(t, n, r, i) {
136
+ let [a, o] = f(i);
137
+ if (n.length !== r.length) throw e(`diags needs one value per offset, got ${n.length} and ${r.length}`, "compute");
138
+ let s = [], c = [], l = [];
139
+ return r.forEach((t, r) => {
140
+ if (!Number.isInteger(t)) throw e(`diags offsets must be integers, got ${t}`, "compute");
141
+ for (let e = Math.max(0, -t); e < a && e + t < o; e++) s.push(e), c.push(e + t), l.push(n[r]);
142
+ }), p(t, {
143
+ rows: s,
144
+ cols: c,
145
+ values: l,
146
+ shape: [a, o]
147
+ });
148
+ }
149
+ function g(e, n) {
150
+ if (!(e instanceof l)) throw t("spmv takes a CsrMatrix; make one with csr() or coo()", "compute");
151
+ return e.matvec(n);
152
+ }
153
+ function _(n, r, a, o) {
154
+ if (!(r instanceof l)) throw t(`${n} takes a CsrMatrix; make one with csr() or coo()`, "compute");
155
+ if (!(a instanceof i)) throw t(`${n} takes b as a GpuArray or an Expr`, "compute");
156
+ let [s, c] = r.shape;
157
+ if (s !== c) throw e(`${n} needs a square matrix, got ${s} x ${c}`, "compute");
158
+ if (a.size !== s) throw e(`${n}: b has ${a.size} elements, the matrix ${s} rows`, "compute");
159
+ let u = o.tol ?? 1e-5, d = o.atol ?? 0, f = o.maxIterations ?? 10 * s, p = o.checkEvery ?? 32, m = o.preconditioner ?? "jacobi";
160
+ if (!(u >= 0) || !(d >= 0)) throw e(`${n} tol and atol must be at least 0`, "compute");
161
+ if (!Number.isInteger(f) || f < 0) throw e(`${n} maxIterations must be a whole number, got ${f}`, "compute");
162
+ if (!Number.isInteger(p) || p < 1) throw e(`${n} checkEvery must be a whole number of at least 1, got ${p}`, "compute");
163
+ if (m !== "jacobi" && m !== "none") throw t(`${n} preconditioner must be 'jacobi' or 'none', got ${String(m)}`, "compute");
164
+ if (o.x0 && o.x0.size !== s) throw e(`${n}: x0 has ${o.x0.size} elements, the matrix ${s} rows`, "compute");
165
+ let h = r.context, g = a.astype("f32").eval(), _ = o.x0 ? o.x0.astype("f32").eval() : h.zeros([s]), v;
166
+ if (m === "jacobi") {
167
+ let e = r.diagonal();
168
+ v = h.where(e.eq(0), 1, e.reciprocal()).eval(), e.dispose();
169
+ }
170
+ return {
171
+ ctx: h,
172
+ n: s,
173
+ b: g,
174
+ x: _,
175
+ inverse: v,
176
+ tol: u,
177
+ atol: d,
178
+ maxIterations: f,
179
+ checkEvery: p
180
+ };
181
+ }
182
+ var v = (e, t) => (e?.dispose(), t), y = (e, t) => e.mul(t).sum();
183
+ async function b(e, t) {
184
+ try {
185
+ return await e.item({ signal: t });
186
+ } finally {
187
+ e.dispose();
188
+ }
189
+ }
190
+ async function x(e, t, n, r, i) {
191
+ let a = t.matvec(n), [o, s] = await Promise.all([b(e.b.sub(a).square().sum(), i), b(y(e.b, e.b), i)]);
192
+ a.dispose(), e.b.dispose(), e.inverse?.dispose();
193
+ let c = Math.sqrt(o);
194
+ return {
195
+ x: n,
196
+ iterations: r,
197
+ residual: c,
198
+ converged: c <= Math.max(e.tol * Math.sqrt(s), e.atol)
199
+ };
200
+ }
201
+ async function S(e, t, n = {}) {
202
+ let i = _("cg", e, t, n), { ctx: a, inverse: o, checkEvery: s, maxIterations: c } = i, l = n.signal;
203
+ r(l);
204
+ let u = await b(y(i.b, i.b), l), d = Math.max(i.tol * Math.sqrt(u), i.atol) ** 2, f = i.x, p = e.matvec(f), m = i.b.sub(p).eval();
205
+ p.dispose();
206
+ let h = o ? m.mul(o).eval() : m, g = h.add(0).eval(), S = y(m, h), C = 0, w = f.add(0).eval();
207
+ if (await b(y(m, m), l) > d) for (; C < c;) {
208
+ let t = e.matvec(g), n = y(g, t), r = a.where(S.eq(0), 0, S.div(n)).eval();
209
+ if (n.dispose(), f = v(f, f.add(g.mul(r)).eval()), m = v(m, m.sub(t.mul(r)).eval()), t.dispose(), r.dispose(), C++, C % s === 0 || C === c) {
210
+ let e = await b(y(m, m), l);
211
+ if (!Number.isFinite(e)) {
212
+ f = v(f, w);
213
+ break;
214
+ }
215
+ if (w = v(w, f.add(0).eval()), e <= d) break;
216
+ }
217
+ let i = o ? m.mul(o).eval() : m, u = y(m, i), p = a.where(u.eq(0), 0, u.div(S)).eval();
218
+ g = v(g, i.add(g.mul(p)).eval()), o && h.dispose(), h = i, S.dispose(), p.dispose(), S = u;
219
+ }
220
+ o && h.dispose();
221
+ for (let e of [
222
+ m,
223
+ g,
224
+ S
225
+ ]) e.dispose();
226
+ return w !== f && w.dispose(), x(i, e, f, C, l);
227
+ }
228
+ async function C(e, t, n = {}) {
229
+ let i = _("bicgstab", e, t, n), { ctx: a, inverse: o, checkEvery: s, maxIterations: c } = i, l = n.signal;
230
+ r(l);
231
+ let u = await b(y(i.b, i.b), l), d = Math.max(i.tol * Math.sqrt(u), i.atol) ** 2, f = (e) => o ? e.mul(o).eval() : e.add(0).eval(), p = i.x, m = e.matvec(p), h = i.b.sub(m).eval();
232
+ m.dispose();
233
+ let g = h.add(0).eval(), S = a.zeros([i.n]), C = a.zeros([i.n]), w = a.ones([]), T = a.ones([]), E = a.ones([]), D = 0, O = p.add(0).eval();
234
+ if (await b(y(h, h), l) > d) for (; D < c;) {
235
+ let t = y(g, h), n = y(h, h).eq(0).eval(), r = a.where(n, 0, t.div(w).mul(T.div(E))).eval();
236
+ S = v(S, h.add(S.sub(C.mul(E)).mul(r)).eval());
237
+ let i = f(S);
238
+ C = v(C, e.matvec(i));
239
+ let o = y(g, C);
240
+ T = v(T, a.where(n, 0, t.div(o)).eval()), o.dispose();
241
+ let u = h.sub(C.mul(T)).eval(), m = f(u), _ = e.matvec(m), x = y(_, _), k = y(_, u);
242
+ E = v(E, a.where(x.eq(0), 0, k.div(x)).eval()), k.dispose(), p = v(p, p.add(i.mul(T)).add(m.mul(E)).eval()), h = v(h, u.sub(_.mul(E)).eval());
243
+ for (let e of [
244
+ i,
245
+ u,
246
+ m,
247
+ _,
248
+ x,
249
+ r,
250
+ n
251
+ ]) e.dispose();
252
+ if (w = v(w, t), D++, D % s === 0 || D === c) {
253
+ let [e, t] = await Promise.all([b(y(h, h), l), E.item({ signal: l })]);
254
+ if (!Number.isFinite(e) || !Number.isFinite(t)) {
255
+ p = v(p, O);
256
+ break;
257
+ }
258
+ if (O = v(O, p.add(0).eval()), e <= d) break;
259
+ }
260
+ }
261
+ for (let e of [
262
+ h,
263
+ g,
264
+ S,
265
+ C,
266
+ w,
267
+ T,
268
+ E
269
+ ]) e.dispose();
270
+ return O !== p && O.dispose(), x(i, e, p, D, l);
271
+ }
272
+ //#endregion
273
+ export { l as CsrMatrix, C as bicgstab, S as cg, p as coo, m as csr, s as diagonalShader, h as diags, g as spmv, o as spmvShader };
@@ -0,0 +1,39 @@
1
+ import type { GpuArray } from './array.js';
2
+ import type { DType } from './dtype.js';
3
+ import { type ComputeContext, type WaitOptions } from './context.js';
4
+ /** Where chunks come from: an iterable or async iterable of TypedArrays (or number arrays). */
5
+ export type ChunkSource = Iterable<ArrayLike<number>> | AsyncIterable<ArrayLike<number>>;
6
+ /** Options for streaming. */
7
+ export interface StreamOptions extends WaitOptions {
8
+ /** Element type of the uploaded chunks. Default from each chunk's TypedArray. */
9
+ readonly dtype?: DType;
10
+ }
11
+ /** Splits an array into chunks of `size` elements (subarray views of a TypedArray, no copies). */
12
+ export declare function chunks<T extends ArrayLike<number>>(data: T, size: number): Generator<T>;
13
+ /**
14
+ * Runs `work` on each chunk as a GpuArray and yields its results in order. The chunk array is freed after `work`'s
15
+ * result settles; the next chunk is read from the source meanwhile.
16
+ * @example for await (const sum of stream(gpu, chunks(bigData, 1 << 24), (c) => c.sum().item())) total += sum;
17
+ */
18
+ export declare function stream<R>(gpu: ComputeContext, source: ChunkSource, work: (chunk: GpuArray, index: number) => R | Promise<R>, options?: StreamOptions): AsyncGenerator<Awaited<R>>;
19
+ /** Folds every chunk with `op` and resolves the result (combined in double precision across chunks). */
20
+ export declare function reduceStream(gpu: ComputeContext, source: ChunkSource, op?: 'sum' | 'product' | 'min' | 'max', options?: StreamOptions): Promise<number>;
21
+ /** Summary statistics of a stream. */
22
+ export interface StreamStats {
23
+ readonly count: number;
24
+ readonly mean: number;
25
+ /** Population variance (divide by count); multiply by count / (count - 1) for the sample variance. */
26
+ readonly variance: number;
27
+ readonly min: number;
28
+ readonly max: number;
29
+ }
30
+ /** Count, mean, variance, min and max of every value in a stream, in one pass over the data. */
31
+ export declare function statsStream(gpu: ComputeContext, source: ChunkSource, options?: StreamOptions): Promise<StreamStats>;
32
+ /** A histogram over a fixed range accumulated chunk by chunk on the GPU (counts and edges as `histogram` gives them). */
33
+ export declare function histogramStream(gpu: ComputeContext, source: ChunkSource, histogramOptions: {
34
+ readonly bins?: number;
35
+ readonly range: readonly [number, number];
36
+ }, options?: StreamOptions): Promise<{
37
+ counts: GpuArray<'u32'>;
38
+ edges: GpuArray<'f32'>;
39
+ }>;
package/dist/stream.js ADDED
@@ -0,0 +1,100 @@
1
+ import { n as e, r as t } from "./errors-CDgOgzCd.js";
2
+ import { n } from "./context-C75sQQra.js";
3
+ //#region src/stream.ts
4
+ function* r(t, n) {
5
+ if (!Number.isInteger(n) || n < 1) throw e(`Chunk size must be a whole number of at least 1, got ${n}`, "compute");
6
+ let r = t.subarray;
7
+ for (let e = 0; e < t.length; e += n) yield r ? r.call(t, e, Math.min(e + n, t.length)) : Array.prototype.slice.call(t, e, e + n);
8
+ }
9
+ async function* i(e) {
10
+ if (e && typeof e[Symbol.asyncIterator] == "function") yield* e;
11
+ else if (e && typeof e[Symbol.iterator] == "function") yield* e;
12
+ else throw t("stream takes an iterable or async iterable of TypedArrays", "compute");
13
+ }
14
+ async function* a(e, r, a, o = {}) {
15
+ if (typeof a != "function") throw t("stream needs a function to run on each chunk", "compute");
16
+ let s = i(r), c = s.next(), l = 0;
17
+ for (;;) {
18
+ n(o.signal);
19
+ let t = await c;
20
+ if (t.done) return;
21
+ let r = o.dtype ? e.array(t.value, o.dtype) : e.array(t.value);
22
+ c = s.next();
23
+ try {
24
+ yield await a(r, l++);
25
+ } finally {
26
+ r.dispose();
27
+ }
28
+ }
29
+ }
30
+ async function o(e, n, r = "sum", i = {}) {
31
+ let o = {
32
+ sum: (e, t) => e + t,
33
+ product: (e, t) => e * t,
34
+ min: Math.min,
35
+ max: Math.max
36
+ }[r];
37
+ if (!o) throw t(`reduceStream op must be sum, product, min or max, got ${r}`, "compute");
38
+ let s = {
39
+ sum: 0,
40
+ product: 1,
41
+ min: Infinity,
42
+ max: -Infinity
43
+ }[r];
44
+ for await (let t of a(e, n, (t) => e.reduce(t, r).item(i), i)) s = o(s, t);
45
+ return s;
46
+ }
47
+ async function s(e, t, n = {}) {
48
+ let r = 0, i = 0, o = 0, s = Infinity, c = -Infinity, l = a(e, t, async (e) => {
49
+ let t = e.mean(), r = e.var(), i = e.min(), a = e.max(), o = await Promise.all([
50
+ t,
51
+ r,
52
+ i,
53
+ a
54
+ ].map((e) => e.item(n)));
55
+ for (let e of [
56
+ t,
57
+ r,
58
+ i,
59
+ a
60
+ ]) e.dispose();
61
+ return {
62
+ n: e.size,
63
+ values: o
64
+ };
65
+ }, n);
66
+ for await (let { n: e, values: t } of l) {
67
+ if (!e) continue;
68
+ let [n, a, l, u] = t, d = r + e, f = n - i;
69
+ o += a * e + f * f * (r * e / d), i += e / d * f, r = d, s = Math.min(s, l), c = Math.max(c, u);
70
+ }
71
+ return {
72
+ count: r,
73
+ mean: r ? i : NaN,
74
+ variance: r ? o / r : NaN,
75
+ min: s,
76
+ max: c
77
+ };
78
+ }
79
+ async function c(t, n, r, i = {}) {
80
+ if (!r?.range) throw e("histogramStream needs a fixed range so chunks share bins", "compute");
81
+ let o, s;
82
+ for await (let e of a(t, n, (e) => t.histogram(e, r), i)) {
83
+ if (!o) {
84
+ o = e.counts, s = e.edges;
85
+ continue;
86
+ }
87
+ let t = o.add(e.counts).eval();
88
+ o.dispose(), e.counts.dispose(), e.edges.dispose(), o = t;
89
+ }
90
+ if (!o) {
91
+ let e = t.zeros(0), n = t.histogram(e, r);
92
+ return e.dispose(), n;
93
+ }
94
+ return {
95
+ counts: o,
96
+ edges: s
97
+ };
98
+ }
99
+ //#endregion
100
+ export { r as chunks, c as histogramStream, o as reduceStream, s as statsStream, a as stream };
@@ -0,0 +1,27 @@
1
+ import type { ComputeContext } from './context.js';
2
+ import type { Fused } from './expr.js';
3
+ /** WGSL for one tree level over 1,024-element blocks, with the bindings of the default level kernel. */
4
+ export declare function subgroupLevelShader(src: Fused, combine: string, identity: string): string;
5
+ /** WGSL folding one axis with a workgroup per output, with the bindings of the default kernel. */
6
+ export declare function subgroupAxisShader(src: Fused, combine: string, identity: string): string;
7
+ /** WGSL for one scan level over 1,024 values, with the bindings of the default scan kernel. */
8
+ export declare function subgroupScanShader(src: Fused, combine: string, identity: string): string;
9
+ /**
10
+ * The radix sort's local pass with the bindings and outputs of the default one: each 256-key block sorted on the 4-bit
11
+ * digit at `shift`, its digit counts and starts. Four ballots give every key the mask of the keys in its subgroup with
12
+ * the same digit, so its rank is a population count, and one exchange through workgroup memory replaces four one-bit
13
+ * splits. Slots past `n` hold 0xffffffff keys: digit 15, and last in it, since they have the highest lanes.
14
+ */
15
+ export declare const subgroupRadixLocalShader: string;
16
+ /**
17
+ * Runs the context's reductions, flat scans and radix sorts on subgroups when its device has them. `gpu.sum`,
18
+ * `gpu.cumsum`, `gpu.sort` and all that is built on them keep their API. Returns true when the subgroup kernels are in
19
+ * use, false when the device lacks the `subgroups` feature (the CPU backend, the WebGL2 layer,
20
+ * or a shared device made without it), in which case nothing changes. Integer results, orders and sorts stay exactly
21
+ * the same; float sums round in another order, and that order depends on the GPU's subgroup size.
22
+ * @example
23
+ * using gpu = await createCompute();
24
+ * useSubgroups(gpu); // true on most current GPUs
25
+ * const total = await gpu.array(new Float32Array(1 << 20).fill(1)).sum().item();
26
+ */
27
+ export declare function useSubgroups(gpu: ComputeContext): boolean;
@@ -0,0 +1,191 @@
1
+ //#region src/subgroups.ts
2
+ var e = "fn blockIndex(wid: vec3u, nwg: vec3u) -> u32 { return wid.x + wid.y * nwg.x; }", t = "@compute @workgroup_size(256)\nfn main(@builtin(workgroup_id) wid: vec3u, @builtin(num_workgroups) nwg: vec3u, @builtin(subgroup_invocation_id) rank: u32)", n = "let size = subgroupAdd(1u);\n var taken = 0u;\n if (subgroupElect()) { taken = atomicAdd(&seats, size | 0x10000u); }\n taken = subgroupBroadcastFirst(taken);\n let lane = (taken & 0xffffu) + rank;\n let slot = taken >> 16u;", r = {
3
+ "a + b": "subgroupAdd",
4
+ "a * b": "subgroupMul",
5
+ "min(a, b)": "subgroupMin",
6
+ "max(a, b)": "subgroupMax"
7
+ }, i = (e) => {
8
+ let t = r[e];
9
+ return t ? `let folded = ${t}(acc);` : "var folded = acc;\n for (var offset = 1u; offset < 128u; offset <<= 1u) {\n let other = subgroupShuffleDown(folded, offset);\n if (rank + offset < size) { folded = combine(folded, other); }\n }";
10
+ }, a = (e) => `if (rank == 0u) { partial[slot] = folded; }
11
+ workgroupBarrier();
12
+ if (lane == 0u) {
13
+ var total = partial[0];
14
+ let slots = atomicLoad(&seats) >> 16u;
15
+ for (var s = 1u; s < slots; s++) { total = combine(total, partial[s]); }
16
+ ${e} = total;
17
+ }`, o = (t, n) => `enable subgroups;
18
+ ${t.enables}${t.declarations}struct Params { n: u32, inf: u32, len: u32, inner: u32 }
19
+ ${e}
20
+ @group(0) @binding(${t.next}) var<storage, read_write> dst: array<${t.dtype}>;
21
+ @group(0) @binding(${t.next + 1}) var<uniform> params: Params;
22
+ var<workgroup> partial: array<${t.dtype}, 256>;
23
+ var<workgroup> seats: atomic<u32>;
24
+ ${t.fn}
25
+ fn combine(a: ${t.dtype}, b: ${t.dtype}) -> ${t.dtype} { return ${n}; }`;
26
+ function s(e, s, c) {
27
+ let l = r[s] ? "k * 256u + lane" : "lane * 4u + k";
28
+ return `${o(e, s)}
29
+ ${t} {
30
+ let g = blockIndex(wid, nwg);
31
+ if (g * 1024u >= params.n) { return; }
32
+ ${n}
33
+ var acc: ${e.dtype} = ${c};
34
+ for (var k = 0u; k < 4u; k++) {
35
+ let i = g * 1024u + ${l};
36
+ if (i < params.n) { acc = combine(acc, value(i)); }
37
+ }
38
+ ${i(s)}
39
+ ${a("dst[g]")}
40
+ }`;
41
+ }
42
+ function c(e, r, s) {
43
+ return `${o(e, r)}
44
+ fn at(o: u32, k: u32) -> u32 { return ((o / params.inner) * params.len + k) * params.inner + o % params.inner; }
45
+ ${t} {
46
+ let o = blockIndex(wid, nwg);
47
+ if (o >= params.n) { return; }
48
+ ${n}
49
+ let run = (params.len + 255u) / 256u;
50
+ var acc: ${e.dtype} = ${s};
51
+ for (var k = lane * run; k < min(params.len, lane * run + run); k++) { acc = combine(acc, value(at(o, k))); }
52
+ ${i(r)}
53
+ ${a("dst[o]")}
54
+ }`;
55
+ }
56
+ function l(r, i, a) {
57
+ let o = r.dtype;
58
+ return `enable subgroups;
59
+ ${r.enables}${r.declarations}struct Params { n: u32, inf: u32, a: u32, b: u32 }
60
+ ${e}
61
+ @group(0) @binding(${r.next}) var<storage, read_write> dst: array<${o}>;
62
+ @group(0) @binding(${r.next + 1}) var<storage, read_write> sums: array<${o}>;
63
+ @group(0) @binding(${r.next + 2}) var<uniform> params: Params;
64
+ var<workgroup> partial: array<${o}, 256>;
65
+ var<workgroup> seats: atomic<u32>;
66
+ ${r.fn}
67
+ fn combine(a: ${o}, b: ${o}) -> ${o} { return ${i}; }
68
+ ${t} {
69
+ let g = blockIndex(wid, nwg);
70
+ if (g * 1024u >= params.n) { return; }
71
+ ${n}
72
+ let base = g * 1024u + lane * 4u;
73
+ var item: array<${o}, 4>;
74
+ var acc: ${o} = ${a};
75
+ for (var k = 0u; k < 4u; k++) {
76
+ var v: ${o} = ${a};
77
+ if (base + k < params.n) { v = value(base + k); }
78
+ acc = combine(acc, v);
79
+ item[k] = acc;
80
+ }
81
+ var running = acc;
82
+ for (var offset = 1u; offset < 128u; offset <<= 1u) {
83
+ let other = subgroupShuffleUp(running, offset);
84
+ if (rank >= offset) { running = combine(other, running); }
85
+ }
86
+ if (rank + 1u == size) { partial[slot] = running; }
87
+ workgroupBarrier();
88
+ var before: ${o} = ${a};
89
+ for (var s = 0u; s < slot; s++) { before = combine(before, partial[s]); }
90
+ let left = subgroupShuffleUp(running, 1u);
91
+ if (rank > 0u) { before = combine(before, left); }
92
+ for (var k = 0u; k < 4u; k++) {
93
+ if (base + k < params.n) {
94
+ if (params.a == 1u) {
95
+ var previous = before;
96
+ if (k > 0u) { previous = combine(before, item[k - 1u]); }
97
+ dst[base + k] = previous;
98
+ } else {
99
+ dst[base + k] = combine(before, item[k]);
100
+ }
101
+ }
102
+ }
103
+ if (lane == 255u) { sums[g] = combine(before, acc); }
104
+ }`;
105
+ }
106
+ var u = `enable subgroups;
107
+ struct Radix { n: u32, shift: u32, blocks: u32, values: u32 }
108
+ ${e}
109
+ @group(0) @binding(0) var<storage, read> keysIn: array<u32>;
110
+ @group(0) @binding(1) var<storage, read> valuesIn: array<u32>;
111
+ @group(0) @binding(2) var<storage, read_write> keysLocal: array<u32>;
112
+ @group(0) @binding(3) var<storage, read_write> valuesLocal: array<u32>;
113
+ @group(0) @binding(4) var<storage, read_write> counts: array<u32>;
114
+ @group(0) @binding(5) var<storage, read_write> starts: array<u32>;
115
+ @group(0) @binding(6) var<uniform> radix: Radix;
116
+ var<workgroup> sharedKeys: array<u32, 256>;
117
+ var<workgroup> sharedValues: array<u32, 256>;
118
+ var<workgroup> seats: atomic<u32>;
119
+ var<workgroup> tally: array<u32, 1024>;
120
+ var<workgroup> totals: array<u32, 16>;
121
+ var<workgroup> digitStarts: array<u32, 16>;
122
+ fn lanesBelow(rank: u32) -> vec4u {
123
+ var mask = vec4u(0u);
124
+ for (var w = 0u; w < 4u; w++) {
125
+ let bits = rank - min(rank, w * 32u);
126
+ mask[w] = select((1u << bits) - 1u, 0xffffffffu, bits >= 32u);
127
+ }
128
+ return mask;
129
+ }
130
+ ${t.replace("@builtin(subgroup_invocation_id) rank: u32", "@builtin(subgroup_invocation_id) rank: u32, @builtin(local_invocation_index) lid: u32")} {
131
+ let g = blockIndex(wid, nwg);
132
+ if (g >= radix.blocks) { return; }
133
+ ${n}
134
+ let i = g * 256u + lane;
135
+ var key = 0xffffffffu;
136
+ var value = 0u;
137
+ if (i < radix.n) {
138
+ key = keysIn[i];
139
+ if (radix.values == 1u) { value = valuesIn[i]; }
140
+ }
141
+ let digit = (key >> radix.shift) & 15u;
142
+ var same = subgroupBallot(true);
143
+ for (var b = 0u; b < 4u; b++) {
144
+ let high = ((digit >> b) & 1u) == 1u;
145
+ let ballot = subgroupBallot(high);
146
+ same &= select(~ballot, ballot, high);
147
+ }
148
+ let lower = countOneBits(same & lanesBelow(rank));
149
+ let rankInDigit = lower.x + lower.y + lower.z + lower.w;
150
+ let peers = countOneBits(same);
151
+ if (rankInDigit == 0u) { tally[digit * 64u + slot] = peers.x + peers.y + peers.z + peers.w; }
152
+ workgroupBarrier();
153
+ let slots = atomicLoad(&seats) >> 16u;
154
+ if (lid < 16u) {
155
+ var sum = 0u;
156
+ for (var s = 0u; s < slots; s++) {
157
+ let c = tally[lid * 64u + s];
158
+ tally[lid * 64u + s] = sum;
159
+ sum += c;
160
+ }
161
+ totals[lid] = sum;
162
+ }
163
+ workgroupBarrier();
164
+ if (lid < 16u) {
165
+ var start = 0u;
166
+ for (var d = 0u; d < lid; d++) { start += totals[d]; }
167
+ digitStarts[lid] = start;
168
+ }
169
+ workgroupBarrier();
170
+ let dest = digitStarts[digit] + tally[digit * 64u + slot] + rankInDigit;
171
+ sharedKeys[dest] = key;
172
+ if (radix.values == 1u) { sharedValues[dest] = value; }
173
+ workgroupBarrier();
174
+ keysLocal[g * 256u + lid] = sharedKeys[lid];
175
+ if (radix.values == 1u) { valuesLocal[g * 256u + lid] = sharedValues[lid]; }
176
+ if (lid < 16u) {
177
+ let padding = 256u - min(256u, radix.n - g * 256u);
178
+ counts[lid * radix.blocks + g] = totals[lid] - select(0u, padding, lid == 15u);
179
+ starts[g * 16u + lid] = digitStarts[lid];
180
+ }
181
+ }`, d = (e) => (t, ...n) => t.dtype === "f16" ? void 0 : e(t, ...n), f = {
182
+ level: d(s),
183
+ axis: d(c),
184
+ scan: d(l),
185
+ radixLocal: u
186
+ };
187
+ function p(e) {
188
+ return e.check(), e.subgroups ? (e.kernelRoute = f, !0) : !1;
189
+ }
190
+ //#endregion
191
+ export { c as subgroupAxisShader, s as subgroupLevelShader, u as subgroupRadixLocalShader, l as subgroupScanShader, p as useSubgroups };
@@ -0,0 +1,57 @@
1
+ //#region \0@oxc-project+runtime@0.153.0/helpers/esm/usingCtx.js
2
+ function e() {
3
+ var e = typeof SuppressedError == "function" ? SuppressedError : function(e, t) {
4
+ var n = Error();
5
+ return n.name = "SuppressedError", n.error = e, n.suppressed = t, n;
6
+ }, t = {}, n = [];
7
+ function r(e, t) {
8
+ if (t != null) {
9
+ if (Object(t) !== t) throw TypeError("using declarations can only be used with objects, functions, null, or undefined.");
10
+ if (e) var r = t[Symbol.asyncDispose || Symbol.for("Symbol.asyncDispose")];
11
+ if (r === void 0 && (r = t[Symbol.dispose || Symbol.for("Symbol.dispose")], e)) var i = r;
12
+ if (typeof r != "function") throw TypeError("Object is not disposable.");
13
+ i && (r = function() {
14
+ try {
15
+ i.call(t);
16
+ } catch (e) {
17
+ return Promise.reject(e);
18
+ }
19
+ }), n.push({
20
+ v: t,
21
+ d: r,
22
+ a: e
23
+ });
24
+ } else e && n.push({
25
+ d: t,
26
+ a: e
27
+ });
28
+ return t;
29
+ }
30
+ return {
31
+ e: t,
32
+ u: r.bind(null, !1),
33
+ a: r.bind(null, !0),
34
+ d: function() {
35
+ var r, i = this.e, a = 0;
36
+ function o() {
37
+ for (; r = n.pop();) try {
38
+ if (!r.a && a === 1) return a = 0, n.push(r), Promise.resolve().then(o);
39
+ if (r.d) {
40
+ var e = r.d.call(r.v);
41
+ if (r.a) return a |= 2, Promise.resolve(e).then(o, s);
42
+ } else a |= 1;
43
+ } catch (e) {
44
+ return s(e);
45
+ }
46
+ if (a === 1) return i === t ? Promise.resolve() : Promise.reject(i);
47
+ if (i !== t) throw i;
48
+ }
49
+ function s(n) {
50
+ return i = i === t ? n : new e(n, i), o();
51
+ }
52
+ return o();
53
+ }
54
+ };
55
+ }
56
+ //#endregion
57
+ export { e as t };