@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.
Files changed (75) hide show
  1. package/LICENSE +201 -0
  2. package/NOTICE +4 -0
  3. package/README.md +804 -2
  4. package/dist/array-C29noZq7.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-CCvs3wkC.js +2479 -0
  13. package/dist/context.d.ts +376 -0
  14. package/dist/cpu-D4UQwJ9L.js +871 -0
  15. package/dist/cpu-kernel.wasm +0 -0
  16. package/dist/cpu-load-XFcM1TXj.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-t3jm8acM.js +996 -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 +76 -0
  34. package/dist/frame.js +85 -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-image-D2qfYsXf.js +66 -0
  48. package/dist/onnx-image.d.ts +10 -0
  49. package/dist/onnx-kernel.wasm +0 -0
  50. package/dist/onnx-regex-DaesIdrm.js +331 -0
  51. package/dist/onnx-regex.d.ts +2 -0
  52. package/dist/onnx.d.ts +167 -0
  53. package/dist/onnx.js +885 -0
  54. package/dist/quant.d.ts +59 -0
  55. package/dist/quant.js +242 -0
  56. package/dist/random.d.ts +64 -0
  57. package/dist/random.js +150 -0
  58. package/dist/reduce.d.ts +34 -0
  59. package/dist/scan.d.ts +26 -0
  60. package/dist/select.d.ts +38 -0
  61. package/dist/shaders.d.ts +80 -0
  62. package/dist/shape.d.ts +23 -0
  63. package/dist/shape.js +134 -0
  64. package/dist/signal.d.ts +29 -0
  65. package/dist/signal.js +178 -0
  66. package/dist/sort.d.ts +38 -0
  67. package/dist/sparse.d.ts +136 -0
  68. package/dist/sparse.js +273 -0
  69. package/dist/stream.d.ts +39 -0
  70. package/dist/stream.js +100 -0
  71. package/dist/subgroups.d.ts +27 -0
  72. package/dist/subgroups.js +191 -0
  73. package/dist/usingCtx-igdMnAhr.js +57 -0
  74. package/dist/wgsl.d.ts +68 -0
  75. package/package.json +146 -4
@@ -0,0 +1,59 @@
1
+ /// <reference lib="esnext.disposable" preserve="true" />
2
+ import type { ComputeContext } from './context.js';
3
+ import type { GpuArray } from './array.js';
4
+ /** Affine signed int8 parameters: real = scale * (q - zeroPoint). */
5
+ export interface Quantization {
6
+ /** Positive finite f32 scale, or one scale per axis coordinate. */
7
+ readonly scale: number | readonly number[];
8
+ /** Signed int8 zero point(s), same cardinality as scale. Default zero. */
9
+ readonly zeroPoint?: number | readonly number[];
10
+ /** Axis for vector parameters, negative axes allowed. Omit for per-tensor. */
11
+ readonly axis?: number;
12
+ }
13
+ /** Inference output quantization, accumulator bias and cancellation. */
14
+ export interface QuantOptions {
15
+ /** Per-tensor output scale and zero point; choose to avoid clipping. */
16
+ readonly output: Quantization;
17
+ /** Int32 bias per output channel, in input-scale times weight-scale units. Default none. */
18
+ readonly bias?: Int32Array;
19
+ /** Cancels CPU reads or submission before GPU dispatch. */
20
+ readonly signal?: AbortSignal;
21
+ }
22
+ /** NCHW convolution with [outChannels, inChannels/groups, kh, kw] weights. */
23
+ export interface QuantConvOptions extends QuantOptions {
24
+ /** Spatial stride. Default 1. */ readonly stride?: number | readonly [number, number];
25
+ /** Tap dilation. Default 1. */ readonly dilation?: number | readonly [number, number];
26
+ /** 0, symmetric [h,w], [top,left,bottom,right], valid, same or same-lower. Default 0. */
27
+ readonly padding?: number | readonly number[] | 'valid' | 'same' | 'same-lower';
28
+ /** Independent channel groups, including depthwise. Default 1. */ readonly groups?: number;
29
+ }
30
+ /** Owned packed int8 tensor. Four signed bytes per u32 on either backend, with no float mirror. */
31
+ export declare class QuantizedTensor {
32
+ /** Logical C-order dimensions. */ readonly shape: readonly number[];
33
+ /** Canonical f32 scales. */ readonly scales: readonly number[];
34
+ /** Canonical int8 zero points. */ readonly zeroPoints: readonly number[];
35
+ /** Per-channel axis, or undefined for per-tensor. */ readonly axis: number | undefined;
36
+ /** Logical element count. */ readonly size: number;
37
+ /** @internal Packed storage, not an expanded i32 tensor. */ readonly packed: GpuArray<'u32'>;
38
+ /** @internal Use quantize or quantizedTensor. */
39
+ constructor(packed: GpuArray<'u32'>, shape: readonly number[], q: Quantization);
40
+ /** Context owning this tensor. */ get context(): ComputeContext;
41
+ /** Read signed bytes, with optional cancellation. */
42
+ read(options?: {
43
+ readonly signal?: AbortSignal;
44
+ }): Promise<Int8Array>;
45
+ /** Read reconstructed real values. */
46
+ dequantize(options?: {
47
+ readonly signal?: AbortSignal;
48
+ }): Promise<Float32Array>;
49
+ /** Release packed storage; safe to repeat. */ dispose(): void;
50
+ /** Explicit resource management. */ [Symbol.dispose](): void;
51
+ }
52
+ /** Upload already quantized signed bytes. Inputs and parameter arrays are copied. */
53
+ export declare function quantizedTensor(c: ComputeContext, data: Int8Array, shape: readonly number[], q: Quantization): QuantizedTensor;
54
+ /** Quantize finite real values with nearest-even rounding and int8 saturation. */
55
+ export declare function quantize(c: ComputeContext, data: ArrayLike<number>, shape: readonly number[], q: Quantization): QuantizedTensor;
56
+ /** Batched broadcast matmul, including vector promotion. Integer MACs, f32 nearest-even requantization. */
57
+ export declare function quantizedMatmul(a: QuantizedTensor, b: QuantizedTensor, o: QuantOptions): Promise<QuantizedTensor>;
58
+ /** Grouped/depthwise dilated 2D convolution. Padding contributes real zero, including asymmetric zero points. */
59
+ export declare function quantizedConv2d(a: QuantizedTensor, b: QuantizedTensor, o: QuantConvOptions): Promise<QuantizedTensor>;
package/dist/quant.js ADDED
@@ -0,0 +1,242 @@
1
+ import { n as e, r as t } from "./errors-CDgOgzCd.js";
2
+ //#region src/quant.ts
3
+ var n = (t) => {
4
+ throw e(`${t}; supply valid int8 quantization or dimensions`, "compute");
5
+ }, r = (e) => e.reduce((e, t) => e * t, 1), i = (e) => typeof e == "number" ? [e] : [...e], a = (e) => {
6
+ let t = Math.floor(e), n = e - t;
7
+ return n < .5 ? t : n > .5 ? t + 1 : t + (t % 2 == 0 ? 0 : 1);
8
+ }, o = (e) => Math.max(-128, Math.min(127, e)), s = Math.fround;
9
+ function c(e, t) {
10
+ let r = i(e.scale).map(s), a = e.zeroPoint === void 0 ? r.map(() => 0) : i(e.zeroPoint), o = e.axis === void 0 ? void 0 : e.axis < 0 ? e.axis + t.length : e.axis;
11
+ return o !== void 0 && (!Number.isInteger(o) || o < 0 || o >= t.length) && n("Quantization axis is out of range"), (r.length !== (o === void 0 ? 1 : t[o]) || a.length !== r.length || r.some((e) => !(e > 0 && Number.isFinite(e))) || a.some((e) => !Number.isInteger(e) || e < -128 || e > 127)) && n("Scales and zero points must match the quantization axis"), {
12
+ scale: Object.freeze(r),
13
+ zero: Object.freeze(a),
14
+ axis: o
15
+ };
16
+ }
17
+ function l(e) {
18
+ let t = new Uint32Array(Math.ceil(e.length / 4));
19
+ for (let n = 0; n < e.length; n++) t[n >>> 2] |= (e[n] & 255) << (n & 3) * 8;
20
+ return t;
21
+ }
22
+ function u(e, t) {
23
+ return Int8Array.from({ length: t }, (t, n) => e[n >>> 2] >>> (n & 3) * 8 & 255);
24
+ }
25
+ var d = class {
26
+ constructor(e, t, n) {
27
+ this.shape = Object.freeze([...t]), this.size = r(t);
28
+ let i = c(n, t);
29
+ this.scales = i.scale, this.zeroPoints = i.zero, this.axis = i.axis, this.packed = e;
30
+ }
31
+ get context() {
32
+ return this.packed.context;
33
+ }
34
+ async read(e = {}) {
35
+ return u(await this.packed.read(e), this.size);
36
+ }
37
+ async dequantize(e = {}) {
38
+ let t = await this.read(e), n = this.axis === void 0 ? 1 : r(this.shape.slice(this.axis + 1));
39
+ return Float32Array.from(t, (e, t) => {
40
+ let r = this.axis === void 0 ? 0 : Math.floor(t / n) % this.shape[this.axis];
41
+ return (e - this.zeroPoints[r]) * this.scales[r];
42
+ });
43
+ }
44
+ dispose() {
45
+ this.packed.dispose();
46
+ }
47
+ [Symbol.dispose]() {
48
+ this.dispose();
49
+ }
50
+ };
51
+ function f(e, t) {
52
+ (!Array.isArray(e) || e.some((e) => !Number.isSafeInteger(e) || e < 0) || !Number.isSafeInteger(r(e)) || r(e) !== t || t > 2147483647) && n("Shape must hold the input and fit signed 32-bit indexing");
53
+ }
54
+ function p(e, n, r, i) {
55
+ if (e.check(), !(n instanceof Int8Array)) throw t("Use Int8Array for signed quantized input", "compute");
56
+ return f(r, n.length), c(i, r), new d(e.array(l(n)), r, i);
57
+ }
58
+ function m(e, t, i, s) {
59
+ f(i, t.length);
60
+ let l = c(s, i), u = l.axis === void 0 ? 1 : r(i.slice(l.axis + 1));
61
+ return p(e, Int8Array.from(t, (e, t) => {
62
+ Number.isFinite(e) || n("Quantization input must be finite");
63
+ let r = l.axis === void 0 ? 0 : Math.floor(t / u) % i[l.axis];
64
+ return o(a(e / l.scale[r]) + l.zero[r]);
65
+ }), i, s);
66
+ }
67
+ var h = "fn av(i:u32)->i32 { let v=(a[i/4u] >> ((i%4u)*8u)) & 255u; return (i32(v)^128)-128; }\nfn bv(i:u32)->i32 { let v=(b[i/4u] >> ((i%4u)*8u)) & 255u; return (i32(v)^128)-128; }\nfn nearest(v:f32)->f32 { let n=floor(v); let r=v-n; if(r<0.5){return n;} if(r>0.5){return n+1.0;} return n+f32(i32(n)%2!=0); }";
68
+ async function g(e, t, i, l) {
69
+ i.signal?.throwIfAborted(), e.packed.check(e.context), t.packed.check(e.context), (e.axis !== void 0 && e.axis !== l.aAxis || t.axis !== void 0 && t.axis !== l.bAxis) && n("Quantized axes must be output rows or weight output channels");
70
+ let u = c(i.output, l.shape);
71
+ u.axis !== void 0 && n("Output quantization must be per tensor"), i.bias !== void 0 && (!(i.bias instanceof Int32Array) || i.bias.length !== l.channels) && n("Bias must have one int32 per output channel");
72
+ let m = i.bias ? new Int32Array(i.bias) : new Int32Array(l.channels), g = {
73
+ scale: u.scale[0],
74
+ zeroPoint: u.zero[0]
75
+ }, _ = e.zeroPoints.reduce((e, t) => Math.max(e, 128 + t, 127 - t), 0), v = t.zeroPoints.reduce((e, t) => Math.max(e, 128 + t, 127 - t), 0);
76
+ l.taps * _ * v + m.reduce((e, t) => Math.max(e, Math.abs(t)), 0) > 2147483647 && n("Int32 accumulator could overflow"), f(l.shape, r(l.shape));
77
+ for (let r of e.scales) for (let e of t.scales) {
78
+ let t = s(s(r * e) / u.scale[0]);
79
+ t > 0 && Number.isFinite(t) || n("Rescale multiplier must be representable in f32");
80
+ }
81
+ if (e.context.backend === "cpu") {
82
+ let [n, c] = await Promise.all([e.read({ signal: i.signal }), t.read({ signal: i.signal })]), d = new Int8Array(r(l.shape));
83
+ for (let r = 0; r < d.length; r++) {
84
+ let [i, f, p] = l.channel(r), h = e.axis === void 0 ? 0 : i, g = t.axis === void 0 ? 0 : f, _ = m[p];
85
+ for (let i = 0; i < l.taps; i++) {
86
+ let [a, o] = l.indices(r, i);
87
+ a >= 0 && (_ += (n[a] - e.zeroPoints[h]) * (c[o] - t.zeroPoints[g]));
88
+ }
89
+ let v = s(s(e.scales[h] * t.scales[g]) / u.scale[0]);
90
+ d[r] = o(a(s(s(_) * v)) + u.zero[0]);
91
+ }
92
+ return i.signal?.throwIfAborted(), p(e.context, d, l.shape, g);
93
+ }
94
+ let y = r(l.shape), b = Math.ceil(y / 4), x = e.context, S = Math.ceil(b / 64), C = x.device.limits.maxComputeWorkgroupsPerDimension;
95
+ S > C * C && n("Output exceeds two-dimensional dispatch capacity");
96
+ let w = x.empty([b], "u32");
97
+ try {
98
+ if (y) {
99
+ let n = (e) => Float32Array.from(e.scales.flatMap((t, n) => [t, e.zeroPoints[n]])), [r, i] = l.code.split("//INDICES"), a = `@group(0) @binding(0) var<storage,read> a:array<u32>;
100
+ @group(0) @binding(1) var<storage,read> b:array<u32>;
101
+ @group(0) @binding(2) var<storage,read_write> out:array<u32>;
102
+ @group(0) @binding(3) var<storage,read> qa:array<vec2<f32>>;
103
+ @group(0) @binding(4) var<storage,read> qb:array<vec2<f32>>;
104
+ @group(0) @binding(5) var<storage,read> bias:array<i32>;
105
+ ${h}
106
+ @compute @workgroup_size(64) fn main(@builtin(global_invocation_id) gid:vec3<u32>) {
107
+ let word=gid.x+gid.y*${Math.min(S, C) * 64}u; if(word>=${b}u){return;}
108
+ var packed=0u;
109
+ for(var lane=0u;lane<4u;lane++){ let i=word*4u+lane; if(i>=${y}u){break;}
110
+ ${r}
111
+ let ac=${e.axis === void 0 ? "0u" : "row"}; let bc=${t.axis === void 0 ? "0u" : "channel"};
112
+ var acc=bias[channel];
113
+ for(var k=0u;k<${l.taps}u;k++){ ${i}
114
+ if(ai>=0){acc+=(av(u32(ai))-i32(qa[ac].y))*(bv(bi)-i32(qb[bc].y));}}
115
+ let multiplier=(qa[ac].x*qb[bc].x)/${u.scale[0]}f;
116
+ let value=i32(clamp(nearest(clamp(f32(acc)*multiplier,-512.0,512.0))+${u.zero[0]}.0,-128.0,127.0));
117
+ packed=packed|((u32(value)&255u)<<(lane*8u)); }
118
+ out[word]=packed; }`;
119
+ x.submit([{
120
+ program: x.program(a, void 0, "quant-int8"),
121
+ resources: {
122
+ a: e.packed,
123
+ b: t.packed,
124
+ out: w,
125
+ qa: n(e),
126
+ qb: n(t),
127
+ bias: m
128
+ },
129
+ workgroups: [
130
+ Math.min(S, C),
131
+ Math.ceil(S / C),
132
+ 1
133
+ ]
134
+ }]);
135
+ }
136
+ return new d(w, l.shape, g);
137
+ } catch (e) {
138
+ throw w.dispose(), e;
139
+ }
140
+ }
141
+ async function _(e, t, i) {
142
+ (!e.shape.length || !t.shape.length) && n("Matmul requires rank at least one");
143
+ let a = e.shape.length === 1, o = t.shape.length === 1, s = a ? [1, ...e.shape] : [...e.shape], c = o ? [...t.shape, 1] : [...t.shape], l = s.at(-2), u = s.at(-1), d = c.at(-1);
144
+ u !== c.at(-2) && n("Matmul inner dimensions must match");
145
+ let f = Math.max(s.length, c.length) - 2, p = Array(f).fill(1);
146
+ for (; s.length < f + 2;) s.unshift(1);
147
+ for (; c.length < f + 2;) c.unshift(1);
148
+ for (let e = 0; e < f; e++) s[e] !== c[e] && s[e] !== 1 && c[e] !== 1 && n("Matmul batch dimensions must broadcast"), p[e] = s[e] === 1 ? c[e] : s[e];
149
+ let m = (e, t) => {
150
+ let n = 0;
151
+ for (let i = 0; i < f; i++) n += (e[i] === 1 ? 0 : Math.floor(t / r(p.slice(i + 1))) % p[i]) * r(e.slice(i + 1));
152
+ return n;
153
+ }, h = (e) => e.slice(0, f).map((t, n) => t === 1 ? "0u" : `((batch/${r(p.slice(n + 1))}u)%${p[n]}u)*${r(e.slice(n + 1))}u`).join("+") || "0u";
154
+ return g(e, t, i, {
155
+ shape: [
156
+ ...p,
157
+ ...a ? [] : [l],
158
+ ...o ? [] : [d]
159
+ ],
160
+ taps: u,
161
+ channels: d,
162
+ aAxis: a ? void 0 : e.shape.length - 2,
163
+ bAxis: o ? void 0 : t.shape.length - 1,
164
+ channel: (e) => [
165
+ Math.floor(e / d) % l,
166
+ e % d,
167
+ e % d
168
+ ],
169
+ indices: (e, t) => {
170
+ let n = Math.floor(e / (l * d));
171
+ return [m(s, n) + Math.floor(e / d) % l * u + t, m(c, n) + t * d + e % d];
172
+ },
173
+ code: `let row=(i/${d || 1}u)%${l || 1}u; let channel=i%${d || 1}u; let batch=i/${l * d || 1}u;
174
+ //INDICES
175
+ let ai=i32(${h(s)}+row*${u}u+k); let bi=${h(c)}+k*${d}u+channel;`
176
+ });
177
+ }
178
+ var v = (e, t) => {
179
+ let r = typeof e == "number" ? [e, e] : [...e];
180
+ return (r.length !== 2 || r.some((e) => !Number.isSafeInteger(e) || e < t || e > 2147483647)) && n("Spatial options need two bounded integers"), r;
181
+ };
182
+ async function y(e, t, r) {
183
+ (e.shape.length !== 4 || t.shape.length !== 4) && n("Conv2d requires NCHW and OIHW ranks");
184
+ let [i, a, o, s] = e.shape, [c, l, u, d] = t.shape, f = r.groups ?? 1, [p, m] = v(r.stride ?? 1, 1), [h, _] = v(r.dilation ?? 1, 1);
185
+ (!Number.isSafeInteger(f) || f < 1 || a !== l * f || c % f || !a || !c || !u || !d || !o || !s) && n("Convolution channels, groups and kernels must agree");
186
+ let y;
187
+ if (typeof r.padding == "string") {
188
+ [
189
+ "valid",
190
+ "same",
191
+ "same-lower"
192
+ ].includes(r.padding) || n("Choose valid, same or same-lower padding");
193
+ let e = r.padding === "valid" ? 0 : Math.max(0, (Math.ceil(o / p) - 1) * p + h * (u - 1) + 1 - o), t = r.padding === "valid" ? 0 : Math.max(0, (Math.ceil(s / m) - 1) * m + _ * (d - 1) + 1 - s), i = r.padding === "same-lower" ? Math.ceil : Math.floor;
194
+ y = [
195
+ i(e / 2),
196
+ i(t / 2),
197
+ e - i(e / 2),
198
+ t - i(t / 2)
199
+ ];
200
+ } else {
201
+ let e = r.padding ?? 0;
202
+ y = typeof e != "number" && e.length === 4 ? [...e] : [...v(e, 0), ...v(e, 0)], y.some((e) => !Number.isSafeInteger(e) || e < 0 || e > 2147483647) && n("Padding must be nonnegative bounded integers");
203
+ }
204
+ let [b, x, S, C] = y, w = Math.floor((o + b + S - h * (u - 1) - 1) / p) + 1, T = Math.floor((s + x + C - _ * (d - 1) - 1) / m) + 1;
205
+ (w < 0 || T < 0 || [
206
+ o + b + S,
207
+ s + x + C,
208
+ h * u,
209
+ _ * d
210
+ ].some((e) => e > 2147483647)) && n("Convolution geometry exceeds indexing range");
211
+ let E = w * T, D = l * u * d;
212
+ return g(e, t, r, {
213
+ shape: [
214
+ i,
215
+ c,
216
+ w,
217
+ T
218
+ ],
219
+ taps: D,
220
+ channels: c,
221
+ bAxis: 0,
222
+ channel: (e) => [
223
+ 0,
224
+ Math.floor(e / E) % c,
225
+ Math.floor(e / E) % c
226
+ ],
227
+ indices: (e, t) => {
228
+ let n = Math.floor(e / E) % c, r = Math.floor(e % E / T) * p - b + Math.floor(t % (u * d) / d) * h, i = e % T * m - x + t % d * _, g = Math.floor(n / (c / f)) * l + Math.floor(t / (u * d));
229
+ return [r < 0 || i < 0 || r >= o || i >= s ? -1 : ((Math.floor(e / (c * E)) * a + g) * o + r) * s + i, n * D + t];
230
+ },
231
+ code: `let channel=(i/${E || 1}u)%${c}u; let batch=i/${c * E || 1}u;
232
+ let oy=(i%${E || 1}u)/${T || 1}u; let ox=i%${T || 1}u;
233
+ //INDICES
234
+ let y=i32(oy*${p}u+(k%${u * d}u)/${d}u*${h}u)-${b};
235
+ let x=i32(ox*${m}u+(k%${d}u)*${_}u)-${x};
236
+ let c=(channel/${c / f}u)*${l}u+k/${u * d}u;
237
+ var ai=-1; if(y>=0 && x>=0 && y<${o} && x<${s}){ai=i32((batch*${a}u+c)*${o * s}u)+y*${s}+x;}
238
+ let bi=channel*${D}u+k;`
239
+ });
240
+ }
241
+ //#endregion
242
+ export { d as QuantizedTensor, m as quantize, y as quantizedConv2d, _ as quantizedMatmul, p as quantizedTensor };
@@ -0,0 +1,64 @@
1
+ import { type GpuArray } from './array.js';
2
+ import type { DType } from './dtype.js';
3
+ import type { ComputeContext } from './context.js';
4
+ /** Philox4x32 multipliers and Weyl key increments (Salmon et al. 2011, table 2). */
5
+ export declare const PHILOX: {
6
+ readonly M0: 3528531795;
7
+ readonly M1: 3449720151;
8
+ readonly W0: 2654435769;
9
+ readonly W1: 3144134277;
10
+ };
11
+ /** Philox4x32-10 on the CPU: the four 32-bit outputs for `counter` (4 words) and `key` (2 words). */
12
+ export declare function philox4x32(counter: readonly number[], key: readonly number[]): Uint32Array;
13
+ /**
14
+ * WGSL that fills `out` with one distribution: element i takes word i % 4 of the Philox block for counter
15
+ * (offset + i / 4, offsetHigh, stream, 0). `kind` 0 raw u32, 1 uniform [low, high), 2 normal (mean, std),
16
+ * 3 integers in [low, high) (the high word of word * range: D. Lemire, "Fast random integer generation in an interval",
17
+ * ACM TOMACS 29(1), 2019, without the rejection step, so the bias is below range / 2^32).
18
+ */
19
+ export declare function randomShader(dtype: DType): string;
20
+ /** Options for creating a generator. */
21
+ export interface RandomOptions {
22
+ /** Seed (an integer up to 2^53). Default: one from `crypto.getRandomValues`. */
23
+ readonly seed?: number;
24
+ /** Independent stream number for the same seed (parallel workers). Default 0. */
25
+ readonly stream?: number;
26
+ }
27
+ /**
28
+ * A reproducible GPU random number generator (Philox4x32-10). The same seed and stream give the same numbers on every
29
+ * device; each draw continues where the last stopped.
30
+ * @example const rng = new Random(gpu, { seed: 42 }); const noise = rng.normal([1024, 1024]);
31
+ */
32
+ export declare class Random {
33
+ #private;
34
+ /** The seed. */
35
+ readonly seed: number;
36
+ /** The stream number. */
37
+ readonly stream: number;
38
+ constructor(ctx: ComputeContext, options?: RandomOptions);
39
+ /** Blocks of four words drawn so far (the counter). */
40
+ get counter(): bigint;
41
+ /** Raw 32-bit words. */
42
+ bits(shape: number | readonly number[]): GpuArray<'u32'>;
43
+ /** Uniform floats in [low, high) (default [0, 1)), 24 bits of randomness each, f32. */
44
+ uniform(shape: number | readonly number[], options?: {
45
+ readonly low?: number;
46
+ readonly high?: number;
47
+ }): GpuArray<'f32'>;
48
+ /** Normally distributed floats with `mean` (default 0) and `std` (default 1), f32. */
49
+ normal(shape: number | readonly number[], options?: {
50
+ readonly mean?: number;
51
+ readonly std?: number;
52
+ }): GpuArray<'f32'>;
53
+ /** Integers in [low, high) (i32). The bias toward some values is below (high - low) / 2^32. */
54
+ integers(low: number, high: number, shape: number | readonly number[]): GpuArray<'i32'>;
55
+ /**
56
+ * A random permutation of 0..n-1 (u32): the stable argsort of random 32-bit keys. Equal keys keep index order, so it
57
+ * departs from uniform only when two keys tie, which happens with probability below n (n - 1) / 2^33.
58
+ */
59
+ permutation(n: number): GpuArray<'u32'>;
60
+ /** `size` elements of `input` chosen uniformly with replacement (or without, via a permutation). */
61
+ choice(input: GpuArray, size: number, options?: {
62
+ readonly replace?: boolean;
63
+ }): GpuArray;
64
+ }
package/dist/random.js ADDED
@@ -0,0 +1,150 @@
1
+ import { n as e, r as t } from "./errors-CDgOgzCd.js";
2
+ import { o as n } from "./expr-t3jm8acM.js";
3
+ import { r } from "./array-C29noZq7.js";
4
+ //#region src/random.ts
5
+ var i = {
6
+ M0: 3528531795,
7
+ M1: 3449720151,
8
+ W0: 2654435769,
9
+ W1: 3144134277
10
+ };
11
+ function a(e, t) {
12
+ let [n, r, a, o] = e.map((e) => e >>> 0), [s, c] = t.map((e) => e >>> 0);
13
+ for (let e = 0; e < 10; e++) {
14
+ let e = BigInt(i.M0) * BigInt(n), t = BigInt(i.M1) * BigInt(a), l = Number(e >> 32n), u = Number(e & 4294967295n), d = Number(t >> 32n), f = Number(t & 4294967295n);
15
+ [n, r, a, o] = [
16
+ (d ^ r ^ s) >>> 0,
17
+ f,
18
+ (l ^ o ^ c) >>> 0,
19
+ u
20
+ ], s = s + i.W0 >>> 0, c = c + i.W1 >>> 0;
21
+ }
22
+ return new Uint32Array([
23
+ n,
24
+ r,
25
+ a,
26
+ o
27
+ ]);
28
+ }
29
+ var o = "\nfn mulhilo(a: u32, b: u32) -> vec2u {\n let a0 = a & 0xffffu; let a1 = a >> 16u;\n let b0 = b & 0xffffu; let b1 = b >> 16u;\n let p00 = a0 * b0; let p01 = a0 * b1; let p10 = a1 * b0; let p11 = a1 * b1;\n let mid = (p00 >> 16u) + (p01 & 0xffffu) + (p10 & 0xffffu);\n let hi = p11 + (p01 >> 16u) + (p10 >> 16u) + (mid >> 16u);\n let lo = (mid << 16u) | (p00 & 0xffffu);\n return vec2u(hi, lo);\n}\nfn philox(counter: vec4u, key: vec2u) -> vec4u {\n var c = counter;\n var k = key;\n for (var iteration = 0u; iteration < 10u; iteration++) {\n let m0 = mulhilo(0xd2511f53u, c.x);\n let m1 = mulhilo(0xcd9e8d57u, c.z);\n c = vec4u(m1.x ^ c.y ^ k.x, m1.y, m0.x ^ c.w ^ k.y, m0.y);\n k = k + vec2u(0x9e3779b9u, 0xbb67ae85u);\n }\n return c;\n}";
30
+ function s(e) {
31
+ return `${e === "f16" ? "enable f16;\n" : ""}struct Draw { n: u32, offset: u32, offsetHigh: u32, kind: u32, key0: u32, key1: u32, stream: u32, range: u32, a: f32, b: f32, base: i32, pad: u32 }
32
+ @group(0) @binding(0) var<storage, read_write> out: array<${e}>;
33
+ @group(0) @binding(1) var<uniform> draw: Draw;
34
+ ${o}
35
+ ${n([
36
+ "preciseSqrt",
37
+ "preciseLog",
38
+ "preciseSin",
39
+ "preciseCos"
40
+ ])}
41
+ fn unit(x: u32) -> f32 { return f32(x >> 8u) * 5.9604644775390625e-8; }
42
+ @compute @workgroup_size(256)
43
+ fn main(@builtin(workgroup_id) wid: vec3u, @builtin(num_workgroups) nwg: vec3u, @builtin(local_invocation_index) lid: u32) {
44
+ let i = (wid.x + wid.y * nwg.x) * 256u + lid;
45
+ if (i >= draw.n) { return; }
46
+ let block = i / 4u;
47
+ let low = draw.offset + block;
48
+ let high = draw.offsetHigh + select(0u, 1u, low < draw.offset);
49
+ let r = philox(vec4u(low, high, draw.stream, 0u), vec2u(draw.key0, draw.key1));
50
+ let lane = i % 4u;
51
+ let word = r[lane];
52
+ if (draw.kind == 1u) {
53
+
54
+
55
+ out[i] = ${e}(draw.a + pmHide((draw.b - draw.a) * unit(word)));
56
+ } else if (draw.kind == 2u) {
57
+
58
+ let pair = lane & 2u;
59
+ let u1 = f32((r[pair] >> 8u) + 1u) * 5.9604644775390625e-8;
60
+ let u2 = unit(r[pair + 1u]);
61
+
62
+ let radius = preciseSqrt(-2.0 * preciseLog(u1));
63
+ let angle = 6.283185307179586 * u2;
64
+ let z = select(radius * preciseCos(angle), radius * preciseSin(angle), (lane & 1u) == 1u);
65
+ out[i] = ${e}(draw.a + draw.b * z);
66
+ } else if (draw.kind == 3u) {
67
+ let m = mulhilo(word, draw.range);
68
+ out[i] = ${e}(draw.base + bitcast<i32>(m.x));
69
+ } else {
70
+ out[i] = ${e === "u32" ? "word" : `${e}(word)`};
71
+ }
72
+ }`;
73
+ }
74
+ var c = class {
75
+ #e;
76
+ #t;
77
+ #n = 0n;
78
+ constructor(t, n = {}) {
79
+ this.#e = t;
80
+ let r = n.seed;
81
+ if (r === void 0) {
82
+ let e = /* @__PURE__ */ new Uint32Array(2);
83
+ globalThis.crypto.getRandomValues(e), r = e[0] + (e[1] & 2097151) * 2 ** 32;
84
+ }
85
+ if (!Number.isSafeInteger(r) || r < 0) throw e(`Random seed must be a whole number from 0 to 2^53, got ${r}`, "compute");
86
+ let i = n.stream ?? 0;
87
+ if (!Number.isInteger(i) || i < 0 || i > 4294967295) throw e(`Random stream must be a u32, got ${i}`, "compute");
88
+ this.seed = r, this.stream = i, this.#t = [r % 2 ** 32 >>> 0, Math.floor(r / 2 ** 32) >>> 0];
89
+ }
90
+ get counter() {
91
+ return this.#n;
92
+ }
93
+ #r(e, t, n, i = 0, a = 0, o = 0, c = 0) {
94
+ let l = r(typeof e == "number" ? [e] : e), u = this.#e.empty(l, t), d = u.size;
95
+ if (d === 0) return u;
96
+ let f = /* @__PURE__ */ new DataView(/* @__PURE__ */ new ArrayBuffer(48));
97
+ return [
98
+ d,
99
+ Number(this.#n & 4294967295n),
100
+ Number(this.#n >> 32n & 4294967295n),
101
+ n,
102
+ this.#t[0],
103
+ this.#t[1],
104
+ this.stream,
105
+ c
106
+ ].forEach((e, t) => f.setUint32(t * 4, e >>> 0, !0)), f.setFloat32(32, i, !0), f.setFloat32(36, a, !0), f.setInt32(40, o, !0), this.#e.submit([{
107
+ program: this.#e.program(s(t), void 0, "random"),
108
+ resources: {
109
+ out: u,
110
+ draw: new Uint8Array(f.buffer)
111
+ },
112
+ workgroups: this.#e.grid(Math.ceil(d / 256))
113
+ }]), this.#n += BigInt(Math.ceil(d / 4)), u;
114
+ }
115
+ bits(e) {
116
+ return this.#r(e, "u32", 0);
117
+ }
118
+ uniform(t, n = {}) {
119
+ let r = n.low ?? 0, i = n.high ?? 1;
120
+ if (!Number.isFinite(r) || !Number.isFinite(i) || !(i > r)) throw e(`uniform needs finite low < high, got ${r}, ${i}`, "compute");
121
+ return this.#r(t, "f32", 1, r, i);
122
+ }
123
+ normal(t, n = {}) {
124
+ let r = n.mean ?? 0, i = n.std ?? 1;
125
+ if (!Number.isFinite(r) || !(i >= 0)) throw e(`normal needs a finite mean and std >= 0, got ${r}, ${i}`, "compute");
126
+ return this.#r(t, "f32", 2, r, i);
127
+ }
128
+ integers(t, n, r) {
129
+ if (!Number.isInteger(t) || !Number.isInteger(n) || n <= t || n - t > 4294967295 || t < -(2 ** 31) || n > 2 ** 31) throw e(`integers needs whole numbers low < high within i32, got ${t}, ${n}`, "compute");
130
+ return this.#r(r, "i32", 3, 0, 0, t, n - t);
131
+ }
132
+ permutation(t) {
133
+ if (!Number.isInteger(t) || t < 0) throw e(`permutation n must be a whole number, got ${t}`, "compute");
134
+ let n = this.bits(t), r = this.#e.argsort(n);
135
+ return n.dispose(), r;
136
+ }
137
+ choice(n, r, i = {}) {
138
+ if (!(n && typeof n == "object" && "storage" in n)) throw t("choice takes a GpuArray", "compute");
139
+ if (!Number.isInteger(r) || r < 0) throw e(`choice size must be a whole number, got ${r}`, "compute");
140
+ if (i.replace === !1) {
141
+ if (r > n.size) throw e(`choice without replacement of ${r} from ${n.size} elements`, "compute");
142
+ let t = this.permutation(n.size), i = t.slice([0, r]), a = this.#e.take(n, i);
143
+ return t.dispose(), a;
144
+ }
145
+ let a = this.integers(0, n.size, r), o = this.#e.take(n, a);
146
+ return a.dispose(), o;
147
+ }
148
+ };
149
+ //#endregion
150
+ export { i as PHILOX, c as Random, a as philox4x32, s as randomShader };
@@ -0,0 +1,34 @@
1
+ import { type GpuArray } from './array.js';
2
+ import { Operand, type AxisOptions, type Fused } from './expr.js';
3
+ import { type Operator } from './shaders.js';
4
+ import type { ComputeContext } from './context.js';
5
+ /** The axes to reduce, ascending and unique; every axis when `axis` is undefined. */
6
+ export declare function axesOf(axis: number | readonly number[] | undefined, ndim: number): number[];
7
+ /** WGSL for one tree level over 1,024-element blocks of `src`'s values. */
8
+ export declare function levelShader(src: Fused, combine: string, identity: string, threads?: number): string;
9
+ /**
10
+ * WGSL folding one axis: output o = (outer, j) folds `len` values at (outer * len + k) * inner + j. `perThread`
11
+ * gives each output a thread; otherwise a workgroup whose threads each fold a consecutive run of k.
12
+ */
13
+ export declare function axisShader(src: Fused, combine: string, identity: string, perThread: boolean): string;
14
+ /** Full or per-axis reduction of `input` with `op` (see ComputeContext.reduce). */
15
+ export declare function reduce(ctx: ComputeContext, input: Operand, op: Operator, options?: AxisOptions): GpuArray;
16
+ /** Mean in f32 (see ComputeContext.mean). */
17
+ export declare function mean(ctx: ComputeContext, input: Operand, options?: AxisOptions): GpuArray;
18
+ /** Variance in f32 with `ddof` (see ComputeContext.var). */
19
+ export declare function variance(ctx: ComputeContext, input: Operand, options?: AxisOptions & {
20
+ readonly ddof?: number;
21
+ }): GpuArray;
22
+ /** Standard deviation in f32 (see ComputeContext.std). */
23
+ export declare function std(ctx: ComputeContext, input: Operand, options?: AxisOptions & {
24
+ readonly ddof?: number;
25
+ }): GpuArray;
26
+ /** Mean ignoring NaN, in f32. */
27
+ export declare function nanmean(ctx: ComputeContext, input: Operand, options?: AxisOptions): GpuArray;
28
+ /** WGSL for argmin/argmax: pairs of (value, index), first index on ties. */
29
+ export declare function argShader(src: Fused, which: 'min' | 'max', mode: 'flat' | 'level' | 'thread' | 'group'): string;
30
+ /** argmin / argmax (see ComputeContext.argmin). */
31
+ export declare function arg(ctx: ComputeContext, input: Operand, which: 'min' | 'max', options?: {
32
+ readonly axis?: number;
33
+ readonly keepdims?: boolean;
34
+ }): GpuArray<'u32'>;
package/dist/scan.d.ts ADDED
@@ -0,0 +1,26 @@
1
+ import { type GpuArray } from './array.js';
2
+ import { Operand } from './expr.js';
3
+ import { type Operator } from './shaders.js';
4
+ import type { ComputeContext, Pass, WaitOptions } from './context.js';
5
+ /** Options for scans. */
6
+ export interface ScanOptions {
7
+ /** Operator. Default `'sum'`. */
8
+ readonly op?: Operator;
9
+ /** Exclusive scan (element i combines elements before it, starting from the identity). Default false. */
10
+ readonly exclusive?: boolean;
11
+ /** Scan each line along this axis on its own. Default: the flat array. */
12
+ readonly axis?: number;
13
+ }
14
+ /** @internal Queues an exclusive sum scan of `source` (u32 counts) into `dst`. */
15
+ export declare function exclusiveSumPasses(ctx: ComputeContext, source: Operand, dst: GpuArray, n: number, passes: Pass[], temporary: GpuArray[]): void;
16
+ /** Flat or per-axis scan (see ComputeContext.scan). */
17
+ export declare function scan(ctx: ComputeContext, input: Operand, options?: ScanOptions): GpuArray;
18
+ /** Scan restarting at non-zero flags (see ComputeContext.segmentedScan). */
19
+ export declare function segmented(ctx: ComputeContext, values: Operand, flags: Operand, options?: Omit<ScanOptions, 'axis'>): GpuArray;
20
+ /** Group-by on runs of equal keys (see ComputeContext.reduceByKey). */
21
+ export declare function reduceByKey(ctx: ComputeContext, keys: Operand, values: Operand, options?: {
22
+ readonly op?: Operator;
23
+ } & WaitOptions): Promise<{
24
+ keys: GpuArray;
25
+ values: GpuArray;
26
+ }>;
@@ -0,0 +1,38 @@
1
+ import { GpuArray } from './array.js';
2
+ import { type DType } from './dtype.js';
3
+ import { Operand, type OperandLike } from './expr.js';
4
+ import type { ComputeContext, WaitOptions } from './context.js';
5
+ /** Options for `take`. */
6
+ export interface TakeOptions {
7
+ /** Axis to take along. Default: the flattened input. */
8
+ readonly axis?: number;
9
+ /** Out-of-range indices: `'clip'` to the nearest end (default) or `'wrap'` around. Negative indices count from the end. */
10
+ readonly mode?: 'clip' | 'wrap';
11
+ }
12
+ /** Elements at indices (see ComputeContext.take). */
13
+ export declare function take(ctx: ComputeContext, input: Operand, indices: Operand, options?: TakeOptions): GpuArray;
14
+ /** Writes values at indices, in place (see ComputeContext.scatter). */
15
+ export declare function scatter<T extends DType>(ctx: ComputeContext, target: GpuArray<T>, indices: Operand, values: OperandLike, options?: {
16
+ readonly op?: 'set' | 'add' | 'min' | 'max';
17
+ }): GpuArray<T>;
18
+ /** Counts (or weight sums) per value (see ComputeContext.bincount). */
19
+ export declare function bincount(ctx: ComputeContext, input: Operand, options: {
20
+ readonly weights?: Operand;
21
+ readonly length: number;
22
+ }): GpuArray;
23
+ /** @internal Compaction into a full-size array plus a count, without reading back. */
24
+ export declare function compactInto(ctx: ComputeContext, input: Operand, mask: Operand): {
25
+ values: GpuArray;
26
+ count: GpuArray<'u32'>;
27
+ };
28
+ /** Compaction without reading back (see ComputeContext.compact). */
29
+ export declare function compact(ctx: ComputeContext, input: Operand, mask: Operand): {
30
+ values: GpuArray;
31
+ count: GpuArray<'u32'>;
32
+ };
33
+ /** @internal Reads a one-element u32 count. */
34
+ export declare function readCount(ctx: ComputeContext, count: GpuArray<'u32'>, signal?: AbortSignal): Promise<number>;
35
+ /** Exactly sized compaction (see ComputeContext.filter). */
36
+ export declare function filter(ctx: ComputeContext, input: Operand, mask: Operand, options?: WaitOptions): Promise<GpuArray>;
37
+ /** Flat indices of non-zero elements (see ComputeContext.nonzero). */
38
+ export declare function nonzero(ctx: ComputeContext, input: Operand, options?: WaitOptions): Promise<GpuArray<'u32'>>;