@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/nn.js ADDED
@@ -0,0 +1,704 @@
1
+ import { n as e, r as t } from "./errors-CDgOgzCd.js";
2
+ import { n } from "./context-C75sQQra.js";
3
+ import { a as r } from "./expr-DwFen60A.js";
4
+ import { t as i } from "./array-DbI848Wf.js";
5
+ import { matmul as a } from "./linalg.js";
6
+ import { Random as o } from "./random.js";
7
+ import { t as s } from "./usingCtx-igdMnAhr.js";
8
+ //#region src/nn.ts
9
+ var c = !0;
10
+ function l(e) {
11
+ let t = c;
12
+ c = !1;
13
+ try {
14
+ return e();
15
+ } finally {
16
+ c = t;
17
+ }
18
+ }
19
+ function u(e, t) {
20
+ let n = e.ndim - t.length, r = [];
21
+ for (let i = 0; i < e.ndim; i++) (i < n || t[i - n] === 1 && e.shape[i] !== 1) && r.push(i);
22
+ return r.length ? e.sum({
23
+ axis: r,
24
+ keepdims: !0
25
+ }).transfer(t) : e.eval();
26
+ }
27
+ var d = (e) => {
28
+ let t = [...e.shape.keys()];
29
+ return [t[e.ndim - 1], t[e.ndim - 2]] = [t[e.ndim - 2], t[e.ndim - 1]], e.transpose(...t);
30
+ }, f = (e, t) => e === void 0 ? [...Array(t).keys()] : (typeof e == "number" ? [e] : [...e]).map((e) => e < 0 ? e + t : e), p = class n {
31
+ #e;
32
+ #t;
33
+ #n;
34
+ #r;
35
+ constructor(e, t, n, r = [], i, a = []) {
36
+ this.value = e, this.requiresGrad = t, this.#r = n, this.#e = r, this.#t = i, this.#n = a;
37
+ }
38
+ get shape() {
39
+ return this.value.shape;
40
+ }
41
+ get ndim() {
42
+ return this.value.ndim;
43
+ }
44
+ get context() {
45
+ return this.value.context;
46
+ }
47
+ read(e = {}) {
48
+ return this.value.read(e);
49
+ }
50
+ item() {
51
+ return this.value.item();
52
+ }
53
+ accumulate(e) {
54
+ if (!this.grad) {
55
+ this.grad = e;
56
+ return;
57
+ }
58
+ let t = this.grad.add(e).eval();
59
+ this.grad.dispose(), e.dispose(), this.grad = t;
60
+ }
61
+ #i(e) {
62
+ this.requiresGrad && this.accumulate(u(e, this.shape));
63
+ }
64
+ #a(e) {
65
+ this.requiresGrad ? e.shape.length === this.ndim && e.shape.every((e, t) => e === this.shape[t]) ? this.accumulate(e) : (this.accumulate(u(e, this.shape)), e.dispose()) : e.dispose();
66
+ }
67
+ backward(n) {
68
+ if (!this.requiresGrad) throw t("backward needs a tensor that depends on a parameter; none of its inputs requires a gradient", "compute");
69
+ if (!n && this.value.size !== 1) throw e(`backward of ${this.value.size} elements needs a seed; reduce to one value first`, "compute");
70
+ let r = [], i = /* @__PURE__ */ new Set(), a = [[this, 0]];
71
+ for (i.add(this); a.length;) {
72
+ let e = a[a.length - 1], t = e[0].#e[e[1]++];
73
+ t ? t.requiresGrad && !i.has(t) && (i.add(t), a.push([t, 0])) : (r.push(e[0]), a.pop());
74
+ }
75
+ this.accumulate(n ? u(n, this.shape) : this.context.ones(this.shape));
76
+ for (let e = r.length - 1; e >= 0; e--) {
77
+ let t = r[e], n = t.grad;
78
+ t.#r || !n || (t.#t?.(n), n.dispose(), t.grad = void 0);
79
+ }
80
+ }
81
+ zeroGrad() {
82
+ this.grad?.dispose(), this.grad = void 0;
83
+ }
84
+ dispose() {
85
+ let e = [this], t = new Set(e);
86
+ for (; e.length;) {
87
+ let n = e.pop();
88
+ if (!n.#r) {
89
+ n.grad?.dispose(), n.grad = void 0, n.value.dispose();
90
+ for (let e of n.#n) e.dispose();
91
+ for (let r of n.#e) t.has(r) || (t.add(r), e.push(r));
92
+ }
93
+ }
94
+ }
95
+ [Symbol.dispose]() {
96
+ this.dispose();
97
+ }
98
+ #o(e, t, r, i) {
99
+ let a = c && t.some((e) => e.requiresGrad);
100
+ return new n(e, a, !1, t, a ? r : void 0, i);
101
+ }
102
+ static made(e, t, n, r, i) {
103
+ return e.#o(t, n, r, i);
104
+ }
105
+ static take(e, t) {
106
+ e.#i(t);
107
+ }
108
+ static give(e, t) {
109
+ e.#a(t);
110
+ }
111
+ add(e) {
112
+ let t = m(this, e);
113
+ return t === void 0 ? this.#s(this.value.add(e).eval(), 1) : this.#o(this.value.add(t.value).eval(), [this, t], (e) => {
114
+ this.#i(e), t.#i(e);
115
+ });
116
+ }
117
+ sub(e) {
118
+ let t = m(this, e);
119
+ return t === void 0 ? this.#s(this.value.sub(e).eval(), 1) : this.#o(this.value.sub(t.value).eval(), [this, t], (e) => {
120
+ this.#i(e), t.#i(e.neg());
121
+ });
122
+ }
123
+ mul(e) {
124
+ let t = m(this, e);
125
+ return t === void 0 ? this.#s(this.value.mul(e).eval(), e) : this.#o(this.value.mul(t.value).eval(), [this, t], (e) => {
126
+ this.#i(e.mul(t.value)), t.#i(e.mul(this.value));
127
+ });
128
+ }
129
+ div(e) {
130
+ let t = m(this, e);
131
+ return t === void 0 ? this.#s(this.value.div(e).eval(), 1 / e) : this.#o(this.value.div(t.value).eval(), [this, t], (e) => {
132
+ this.#i(e.div(t.value)), t.#i(e.mul(this.value).neg().div(t.value.square()));
133
+ });
134
+ }
135
+ #s(e, t) {
136
+ return this.#o(e, [this], (e) => this.#i(t === 1 ? e : e.mul(t)));
137
+ }
138
+ matmul(t) {
139
+ let n = m(this, t);
140
+ if (this.ndim < 2 || n.ndim < 2) throw e(`Tensor matmul needs two or more dimensions, got [${this.shape.join(", ")}] and [${n.shape.join(", ")}]; reshape first`, "compute");
141
+ return this.#o(a(this.value, n.value), [this, n], (e) => {
142
+ this.requiresGrad && this.#a(a(e, d(n.value))), n.requiresGrad && n.#a(a(d(this.value), e));
143
+ });
144
+ }
145
+ sum(e = {}) {
146
+ let t = this.#c(e);
147
+ return this.#o(this.value.sum(e), [this], (e) => {
148
+ this.#a(e.reshape(t).broadcastTo(this.shape).eval());
149
+ });
150
+ }
151
+ mean(e = {}) {
152
+ let t = f(e.axis, this.ndim).reduce((e, t) => e * this.shape[t], 1);
153
+ return this.sum(e).mul(1 / t);
154
+ }
155
+ max(e) {
156
+ let t = this.#c(e), n = f(e.axis, this.ndim)[0], i = this.value.argmax({
157
+ axis: n,
158
+ keepdims: !0
159
+ }), a = this.context.arange(0, this.shape[n], 1, "u32"), o = this.shape.map((e, t) => t === n ? e : 1);
160
+ return this.#o(this.value.max(e), [this], (e) => {
161
+ this.#a(r(a.reshape(o).eq(i), e.reshape(t), 0).eval());
162
+ }, [i, a]);
163
+ }
164
+ #c(e) {
165
+ let t = f(e.axis, this.ndim);
166
+ return this.shape.map((e, n) => t.includes(n) ? 1 : e);
167
+ }
168
+ reshape(...e) {
169
+ let t = this.value.ascontiguous(), n = t !== this.value, r = this.shape;
170
+ return this.#o(t.reshape(...e), [this], (e) => {
171
+ this.#a(e.reshape(...r).eval());
172
+ }, n ? [t] : []);
173
+ }
174
+ permute(...e) {
175
+ let t = e.map((t, n) => e.indexOf(n));
176
+ return this.#o(this.value.transpose(...e), [this], (e) => {
177
+ this.#a(e.transpose(...t).eval());
178
+ });
179
+ }
180
+ #l(e, t) {
181
+ return this.#o(e, [this], (n) => this.#i(t(n, e)));
182
+ }
183
+ exp() {
184
+ return this.#l(this.value.exp().eval(), (e, t) => e.mul(t));
185
+ }
186
+ log() {
187
+ return this.#l(this.value.log().eval(), (e) => e.div(this.value));
188
+ }
189
+ rsqrt() {
190
+ return this.#l(this.value.rsqrt().eval(), (e, t) => e.mul(t).mul(t).mul(t).mul(-.5));
191
+ }
192
+ relu() {
193
+ let e = this.value;
194
+ return this.#l(r(e.gt(0), e, 0).eval(), (t) => r(e.gt(0), t, 0));
195
+ }
196
+ leakyRelu(e = .01) {
197
+ let t = this.value;
198
+ return this.#l(r(t.gt(0), t, t.mul(e)).eval(), (n) => r(t.gt(0), n, n.mul(e)));
199
+ }
200
+ sigmoid() {
201
+ return this.#l(this.value.neg().exp().add(1).reciprocal().eval(), (e, t) => e.mul(t).mul(t.neg().add(1)));
202
+ }
203
+ tanh() {
204
+ return this.#l(this.value.tanh().eval(), (e, t) => e.mul(t.square().neg().add(1)));
205
+ }
206
+ silu() {
207
+ let e = this.value, t = e.neg().exp().add(1).reciprocal();
208
+ return this.#l(e.mul(t).eval(), (n) => n.mul(t.mul(e.mul(t.neg().add(1)).add(1))));
209
+ }
210
+ gelu() {
211
+ let e = this.value, t = Math.sqrt(2 / Math.PI), n = e.add(e.mul(e).mul(e).mul(.044715)).mul(t).tanh();
212
+ return this.#l(e.mul(.5).mul(n.add(1)).eval(), (r) => {
213
+ let i = e.square().mul(.134145).add(1).mul(t);
214
+ return r.mul(n.add(1).mul(.5).add(e.mul(.5).mul(n.square().neg().add(1)).mul(i)));
215
+ });
216
+ }
217
+ softmax(e = -1) {
218
+ let t = {
219
+ axis: e,
220
+ keepdims: !0
221
+ }, n = this.value.max(t), r = this.value.sub(n).exp(), i = r.sum(t), a = r.div(i).eval();
222
+ return n.dispose(), i.dispose(), this.#o(a, [this], (e) => {
223
+ let n = e.mul(a).sum(t);
224
+ this.#i(a.mul(e.sub(n))), n.dispose();
225
+ });
226
+ }
227
+ logSoftmax(e = -1) {
228
+ let t = {
229
+ axis: e,
230
+ keepdims: !0
231
+ }, n = this.value.max(t), r = this.value.sub(n).exp().sum(t), i = this.value.sub(n).sub(r.log()).eval();
232
+ return n.dispose(), r.dispose(), this.#o(i, [this], (e) => {
233
+ let n = e.sum(t);
234
+ this.#i(e.sub(i.exp().mul(n))), n.dispose();
235
+ });
236
+ }
237
+ };
238
+ function m(e, n) {
239
+ if (typeof n != "number") {
240
+ if (n instanceof p) return n;
241
+ if (n instanceof i) return new p(n, !1, !0);
242
+ throw t("Tensor operands are Tensors, GpuArrays or numbers", "compute");
243
+ }
244
+ }
245
+ function h(e, n = {}) {
246
+ if (!(e instanceof i)) throw t("tensor takes a GpuArray; use gpu.array(data) first", "compute");
247
+ return new p(e, !!n.requiresGrad, !0);
248
+ }
249
+ function g(e) {
250
+ return h(e, { requiresGrad: !0 });
251
+ }
252
+ var _ = (e) => new p(e, !1, !1);
253
+ function v(e, t) {
254
+ let n = e.sub(t);
255
+ return n.mul(n).mean();
256
+ }
257
+ function y(t, n) {
258
+ let r = t.shape[t.ndim - 1], i = t.value.size / r;
259
+ if (n.size !== i) throw e(`crossEntropy has ${i} rows of logits but ${n.size} labels`, "compute");
260
+ let a = t.context, o = t.reshape(i, r).logSoftmax(), s = a.arange(0, r, 1, "i32"), c = n.astype("i32").eval(), l = c.reshape(i, 1).eq(s.reshape(1, r)).astype("f32").eval();
261
+ return s.dispose(), c.dispose(), o.mul(_(l)).sum().mul(-1 / i);
262
+ }
263
+ function b(t, n, r) {
264
+ if (!(n >= 0 && n < 1)) throw e(`dropout p must be in [0, 1), got ${n}`, "compute");
265
+ let i = r.uniform(t.shape), a = i.ge(n).astype("f32").mul(1 / (1 - n)).eval();
266
+ return i.dispose(), t.mul(_(a));
267
+ }
268
+ var x = (t, n, r) => {
269
+ let i = typeof t == "number" ? [t, t] : t;
270
+ if (i.length !== 2 || !i.every((e) => Number.isInteger(e) && e >= r)) throw e(`${n} must be a whole number of at least ${r}, or two of them, got ${String(t)}`, "compute");
271
+ return i;
272
+ };
273
+ function S(t, n, r, i, a) {
274
+ let [o, s] = a.kernel, [c, l] = a.stride, [u, d] = a.padding, [f, p] = a.dilation, m = Math.floor((r + 2 * u - f * (o - 1) - 1) / c) + 1, h = Math.floor((i + 2 * d - p * (s - 1) - 1) / l) + 1;
275
+ if (m < 1 || h < 1) throw e(`A ${o} x ${s} window does not fit a ${r} x ${i} input; lower the kernel or add padding`, "compute");
276
+ let g = m * h, _ = n * o * s, v = n * r * i, y = new Int32Array(g * _), b = new Uint32Array(g * _), x = new Uint32Array(v), S = !1;
277
+ for (let e = 0, t = 0; e < m; e++) for (let a = 0; a < h; a++) for (let m = 0; m < n; m++) for (let n = 0; n < o; n++) for (let o = 0; o < s; o++, t++) {
278
+ let s = e * c - u + n * f, h = a * l - d + o * p;
279
+ if (s < 0 || s >= r || h < 0 || h >= i) {
280
+ S = !0;
281
+ continue;
282
+ }
283
+ let g = (m * r + s) * i + h;
284
+ y[t] = g, b[t] = 1, x[g]++;
285
+ }
286
+ let C = Math.max(1, ...x), w = new Int32Array(v * C), T = new Uint32Array(v * C);
287
+ x.fill(0);
288
+ for (let e = 0; e < y.length; e++) if (b[e]) {
289
+ let t = y[e], n = t * C + x[t]++;
290
+ w[n] = e, T[n] = 1;
291
+ }
292
+ return {
293
+ positions: g,
294
+ taps: _,
295
+ outH: m,
296
+ outW: h,
297
+ table: t.array(y, { shape: [g, _] }),
298
+ valid: S ? t.array(b, { shape: [g, _] }) : void 0,
299
+ inverse: t.array(w, { shape: [v, C] }),
300
+ inverseValid: t.array(T, { shape: [v, C] })
301
+ };
302
+ }
303
+ function C(e, t, n) {
304
+ let i = e.context, a = e.shape[0], o = i.take(e.value, t.table, { axis: 1 });
305
+ if (t.valid) {
306
+ let e = r(t.valid, o, n).eval();
307
+ o.dispose(), o = e;
308
+ }
309
+ return p.made(e, o, [e], (n) => {
310
+ let o = n.reshape(a, t.positions * t.taps), s = i.take(o, t.inverse, { axis: 1 });
311
+ p.give(e, r(t.inverseValid, s, 0).sum({ axis: 2 })), s.dispose();
312
+ });
313
+ }
314
+ function w(e, t, n, i = {}) {
315
+ let a = e.shape[e.ndim - 1], o = [...t.shape.keys()], s = [
316
+ ...o.slice(0, -2),
317
+ o[o.length - 1],
318
+ o[o.length - 2]
319
+ ], c = e.matmul(t.permute(...s)).mul(1 / Math.sqrt(a));
320
+ if (i.causal) {
321
+ let n = e.context, i = e.shape[e.ndim - 2], a = t.shape[t.ndim - 2], o = n.arange(0, i, 1, "i32"), s = n.arange(0, a, 1, "i32"), l = r(s.reshape(1, a).gt(o.reshape(i, 1)), -Infinity, 0).eval();
322
+ o.dispose(), s.dispose(), c = c.add(_(l));
323
+ }
324
+ return c.softmax().matmul(n);
325
+ }
326
+ var T = class t {
327
+ constructor() {
328
+ this.training = !0;
329
+ }
330
+ namedParameters(e = "") {
331
+ let n = [], r = (e, i) => {
332
+ i instanceof p ? i.requiresGrad && n.push([e, i]) : i instanceof t ? n.push(...i.namedParameters(`${e}.`)) : Array.isArray(i) && i.forEach((t, n) => r(`${e}.${n}`, t));
333
+ };
334
+ for (let [t, n] of Object.entries(this)) r(`${e}${t}`, n);
335
+ return n;
336
+ }
337
+ parameters() {
338
+ return this.namedParameters().map(([, e]) => e);
339
+ }
340
+ #e(e) {
341
+ e(this);
342
+ let n = (r) => {
343
+ r instanceof t ? r.#e(e) : Array.isArray(r) && r.forEach(n);
344
+ };
345
+ Object.values(this).forEach(n);
346
+ }
347
+ train(e = !0) {
348
+ return this.#e((t) => t.training = e), this;
349
+ }
350
+ eval() {
351
+ return this.train(!1);
352
+ }
353
+ predict(e) {
354
+ let t = this.training;
355
+ this.train(!1);
356
+ try {
357
+ return l(() => {
358
+ try {
359
+ var t = s();
360
+ return t.u(this.forward(h(e))).value.eval();
361
+ } catch (e) {
362
+ t.e = e;
363
+ } finally {
364
+ t.d();
365
+ }
366
+ });
367
+ } finally {
368
+ this.train(t);
369
+ }
370
+ }
371
+ async stateDict(e = {}) {
372
+ n(e.signal);
373
+ let r = { signal: e.signal }, i = {}, a = async (e, n) => {
374
+ if (n instanceof p) n.requiresGrad && (i[e] = await n.value.read(r));
375
+ else if (n instanceof t) for (let [t, a] of Object.entries(await n.stateDict(r))) i[`${e}.${t}`] = a;
376
+ else if (Array.isArray(n)) for (let t = 0; t < n.length; t++) await a(`${e}.${t}`, n[t]);
377
+ };
378
+ for (let [e, t] of Object.entries(this)) await a(e, t);
379
+ return i;
380
+ }
381
+ loadStateDict(n) {
382
+ for (let [t, r] of this.namedParameters()) {
383
+ let i = n[t];
384
+ if (!i) throw e(`State has no parameter ${t}`, "compute");
385
+ if (i.length !== r.value.size) throw e(`State's ${t} has ${i.length} values; the parameter has ${r.value.size}`, "compute");
386
+ }
387
+ let r = (e, i) => {
388
+ if (i instanceof p) i.requiresGrad && i.value.write(n[e]);
389
+ else if (i instanceof t) {
390
+ let t = {};
391
+ for (let [r, i] of Object.entries(n)) r.startsWith(`${e}.`) && (t[r.slice(e.length + 1)] = i);
392
+ i.loadStateDict(t);
393
+ } else Array.isArray(i) && i.forEach((t, n) => r(`${e}.${n}`, t));
394
+ };
395
+ for (let [e, t] of Object.entries(this)) r(e, t);
396
+ }
397
+ dispose() {
398
+ for (let e of this.parameters()) e.zeroGrad(), e.value.dispose();
399
+ this.#e((e) => e.release());
400
+ }
401
+ release() {}
402
+ [Symbol.dispose]() {
403
+ this.dispose();
404
+ }
405
+ }, E = (e, t, n) => g(e.uniform(t, {
406
+ low: -n,
407
+ high: n
408
+ })), D = class extends T {
409
+ constructor(e, t, n, r = {}) {
410
+ super();
411
+ let i = r.rng ?? new o(e), a = 1 / Math.sqrt(t);
412
+ this.weight = E(i, [n, t], a), this.bias = r.bias === !1 ? void 0 : E(i, [n], a);
413
+ }
414
+ forward(e) {
415
+ let t = e.matmul(this.weight.permute(1, 0));
416
+ return this.bias ? t.add(this.bias) : t;
417
+ }
418
+ }, O = class {
419
+ #e = /* @__PURE__ */ new Map();
420
+ of(e, t, n, r, i) {
421
+ let a = `${t},${n},${r}`, o = this.#e.get(a);
422
+ return o || this.#e.set(a, o = S(e, t, n, r, i)), o;
423
+ }
424
+ dispose() {
425
+ for (let e of this.#e.values()) for (let t of [
426
+ e.table,
427
+ e.valid,
428
+ e.inverse,
429
+ e.inverseValid
430
+ ]) t?.dispose();
431
+ this.#e.clear();
432
+ }
433
+ }, k = class extends T {
434
+ #e;
435
+ #t = new O();
436
+ #n;
437
+ constructor(e, t, n, r, i = {}) {
438
+ super();
439
+ let a = x(r, "kernelSize", 1), s = i.rng ?? new o(e), c = 1 / Math.sqrt(t * a[0] * a[1]);
440
+ this.#n = t, this.#e = {
441
+ kernel: a,
442
+ stride: x(i.stride ?? 1, "stride", 1),
443
+ padding: x(i.padding ?? 0, "padding", 0),
444
+ dilation: x(i.dilation ?? 1, "dilation", 1)
445
+ }, this.weight = E(s, [
446
+ n,
447
+ t,
448
+ a[0],
449
+ a[1]
450
+ ], c), this.bias = i.bias === !1 ? void 0 : E(s, [n], c);
451
+ }
452
+ forward(t) {
453
+ if (t.ndim !== 4 || t.shape[1] !== this.#n) throw e(`Conv2d takes [n, ${this.#n}, h, w], got [${t.shape.join(", ")}]`, "compute");
454
+ let [n, r, i, a] = t.shape, o = this.weight.shape[0], s = this.#t.of(t.context, r, i, a, this.#e), c = C(t.reshape(n, r * i * a), s, 0).matmul(this.weight.reshape(o, s.taps).permute(1, 0));
455
+ return this.bias && (c = c.add(this.bias)), c.permute(0, 2, 1).reshape(n, o, s.outH, s.outW);
456
+ }
457
+ release() {
458
+ this.#t.dispose();
459
+ }
460
+ }, A = class extends T {
461
+ constructor(e, t, n, r, i = {}) {
462
+ super(), this.conv = new k(e, t, n, [1, r], {
463
+ ...i,
464
+ stride: [1, i.stride ?? 1],
465
+ padding: [0, i.padding ?? 0],
466
+ dilation: [1, i.dilation ?? 1]
467
+ });
468
+ }
469
+ forward(t) {
470
+ if (t.ndim !== 3) throw e(`Conv1d takes [n, channels, length], got [${t.shape.join(", ")}]`, "compute");
471
+ let [n, r, i] = t.shape, a = this.conv.forward(t.reshape(n, r, 1, i));
472
+ return a.reshape(n, a.shape[1], a.shape[3]);
473
+ }
474
+ }, j = class extends T {
475
+ #e;
476
+ #t = new O();
477
+ constructor(t, n = {}) {
478
+ super();
479
+ let r = x(t, "kernelSize", 1), i = x(n.padding ?? 0, "padding", 0);
480
+ if (i[0] * 2 > r[0] || i[1] * 2 > r[1]) throw e(`Pool padding is at most half the kernel, got ${i} for ${r}`, "compute");
481
+ this.#e = {
482
+ kernel: r,
483
+ stride: x(n.stride ?? r, "stride", 1),
484
+ padding: i,
485
+ dilation: [1, 1]
486
+ };
487
+ }
488
+ forward(t) {
489
+ if (t.ndim !== 4) throw e(`Pooling takes [n, channels, h, w], got [${t.shape.join(", ")}]`, "compute");
490
+ let [n, r, i, a] = t.shape, o = this.#t.of(t.context, 1, i, a, this.#e);
491
+ return this.fold(C(t.reshape(n * r, i * a), o, this.edge)).reshape(n, r, o.outH, o.outW);
492
+ }
493
+ release() {
494
+ this.#t.dispose();
495
+ }
496
+ }, M = class extends j {
497
+ constructor(...e) {
498
+ super(...e), this.edge = -Infinity;
499
+ }
500
+ fold(e) {
501
+ return e.max({ axis: 2 });
502
+ }
503
+ }, N = class extends j {
504
+ constructor(...e) {
505
+ super(...e), this.edge = 0;
506
+ }
507
+ fold(e) {
508
+ return e.mean({ axis: 2 });
509
+ }
510
+ }, P = class extends T {
511
+ forward(e) {
512
+ return e.reshape(e.shape[0], -1);
513
+ }
514
+ }, F = class extends T {
515
+ constructor(...e) {
516
+ super(), this.layers = e;
517
+ }
518
+ forward(e) {
519
+ return this.layers.reduce((e, t) => t.forward(e), e);
520
+ }
521
+ }, I = class extends T {
522
+ forward(e) {
523
+ return e.relu();
524
+ }
525
+ }, L = class extends T {
526
+ constructor(e = .01) {
527
+ super(), this.slope = e;
528
+ }
529
+ forward(e) {
530
+ return e.leakyRelu(this.slope);
531
+ }
532
+ }, R = class extends T {
533
+ forward(e) {
534
+ return e.gelu();
535
+ }
536
+ }, z = class extends T {
537
+ forward(e) {
538
+ return e.silu();
539
+ }
540
+ }, B = class extends T {
541
+ forward(e) {
542
+ return e.sigmoid();
543
+ }
544
+ }, V = class extends T {
545
+ forward(e) {
546
+ return e.tanh();
547
+ }
548
+ }, H = class extends T {
549
+ constructor(e = -1) {
550
+ super(), this.axis = e;
551
+ }
552
+ forward(e) {
553
+ return e.softmax(this.axis);
554
+ }
555
+ }, U = class extends T {
556
+ #e;
557
+ #t;
558
+ constructor(t = .5, n = {}) {
559
+ if (super(), this.p = t, !(t >= 0 && t < 1)) throw e(`Dropout p must be in [0, 1), got ${t}`, "compute");
560
+ this.#e = n.rng;
561
+ }
562
+ forward(e) {
563
+ return !this.training || this.p === 0 ? e : b(e, this.p, this.#e ?? (this.#t ??= new o(e.context)));
564
+ }
565
+ }, W = class extends T {
566
+ #e;
567
+ constructor(e, t, n = {}) {
568
+ super(), this.weight = g(e.ones(t)), this.bias = g(e.zeros(t)), this.#e = n.eps ?? 1e-5;
569
+ }
570
+ forward(e) {
571
+ let t = {
572
+ axis: -1,
573
+ keepdims: !0
574
+ }, n = e.sub(e.mean(t)), r = n.mul(n).mean(t).add(this.#e).rsqrt();
575
+ return n.mul(r).mul(this.weight).add(this.bias);
576
+ }
577
+ }, G = class extends T {
578
+ constructor(e, t, n, r = {}) {
579
+ super(), this.weight = g((r.rng ?? new o(e)).normal([t, n]));
580
+ }
581
+ forward(e) {
582
+ let t = this.weight, n = t.context, r = t.shape[1], i = e.value.reshape(e.value.size), a = n.take(t.value, i, { axis: 0 });
583
+ return p.made(t, a.reshape(...e.shape, r), [t], (e) => {
584
+ let a = n.zeros(t.shape), o = i.astype("i32").eval(), s = n.arange(0, r, 1, "i32"), c = o.reshape(i.size, 1).mul(r).add(s).eval();
585
+ n.scatter(a, c, e, { op: "add" });
586
+ for (let e of [
587
+ o,
588
+ s,
589
+ c
590
+ ]) e.dispose();
591
+ p.give(t, a);
592
+ }, [a]);
593
+ }
594
+ }, K = class extends T {
595
+ #e;
596
+ #t;
597
+ constructor(t, n, r, i = {}) {
598
+ if (super(), !Number.isInteger(r) || r < 1 || n % r) throw e(`MultiHeadAttention dim ${n} must split evenly into ${r} heads`, "compute");
599
+ let a = {
600
+ rng: i.rng ?? new o(t),
601
+ bias: i.bias
602
+ };
603
+ this.query = new D(t, n, n, a), this.key = new D(t, n, n, a), this.value = new D(t, n, n, a), this.output = new D(t, n, n, a), this.#e = r, this.#t = !!i.causal;
604
+ }
605
+ #n(e) {
606
+ let [t, n, r] = e.shape;
607
+ return e.reshape(t, n, this.#e, r / this.#e).permute(0, 2, 1, 3);
608
+ }
609
+ forward(t, n = t, r = n) {
610
+ if (t.ndim !== 3) throw e(`MultiHeadAttention takes [batch, length, dim], got [${t.shape.join(", ")}]`, "compute");
611
+ let [i, a, o] = t.shape, s = w(this.#n(this.query.forward(t)), this.#n(this.key.forward(n)), this.#n(this.value.forward(r)), { causal: this.#t });
612
+ return this.output.forward(s.permute(0, 2, 1, 3).reshape(i, a, o));
613
+ }
614
+ };
615
+ function q(e, t) {
616
+ let n = t.eval();
617
+ e.context.submit([], [[
618
+ n.buffer,
619
+ 0,
620
+ e.buffer,
621
+ e.offset * 4,
622
+ e.byteLength
623
+ ]]), n.dispose();
624
+ }
625
+ var J = class {
626
+ constructor(t, n) {
627
+ if (!t.length) throw e("An optimizer needs at least one parameter", "compute");
628
+ if (!(n > 0)) throw e(`Learning rate must be above 0, got ${n}`, "compute");
629
+ this.parameters = t, this.lr = n;
630
+ }
631
+ zeroGrad() {
632
+ for (let e of this.parameters) e.zeroGrad();
633
+ }
634
+ [Symbol.dispose]() {
635
+ this.dispose();
636
+ }
637
+ }, Y = class extends J {
638
+ #e;
639
+ #t;
640
+ #n = /* @__PURE__ */ new Map();
641
+ constructor(e, t = {}) {
642
+ super(e, t.lr ?? .01), this.#e = t.momentum ?? 0, this.#t = t.weightDecay ?? 0;
643
+ }
644
+ step() {
645
+ for (let e of this.parameters) {
646
+ if (!e.grad) continue;
647
+ let t = this.#t ? e.grad.add(e.value.mul(this.#t)) : e.grad;
648
+ if (!this.#e) {
649
+ q(e.value, e.value.sub(t.mul(this.lr)));
650
+ continue;
651
+ }
652
+ let n = this.#n.get(e);
653
+ n ? q(n, n.mul(this.#e).add(t)) : this.#n.set(e, n = t.eval()), q(e.value, e.value.sub(n.mul(this.lr)));
654
+ }
655
+ }
656
+ dispose() {
657
+ for (let e of this.#n.values()) e.dispose();
658
+ this.#n.clear();
659
+ }
660
+ }, X = class extends J {
661
+ #e;
662
+ #t;
663
+ #n = /* @__PURE__ */ new Map();
664
+ #r = 0;
665
+ constructor(e, t = {}, n = 0) {
666
+ super(e, t.lr ?? .001), this.#e = t.betas ?? [.9, .999], this.#t = t.eps ?? 1e-8, this.decay = t.weightDecay ?? n;
667
+ }
668
+ gradient(e, t) {
669
+ return this.decay ? t.add(e.value.mul(this.decay)) : t;
670
+ }
671
+ start(e) {
672
+ return e.value;
673
+ }
674
+ step() {
675
+ this.#r++;
676
+ let [e, t] = this.#e, n = 1 - e ** this.#r, r = 1 - t ** this.#r;
677
+ for (let i of this.parameters) {
678
+ if (!i.grad) continue;
679
+ let a = this.gradient(i, i.grad), o = this.#n.get(i);
680
+ if (!o) {
681
+ let e = i.context;
682
+ this.#n.set(i, o = [e.zeros(i.shape), e.zeros(i.shape)]);
683
+ }
684
+ let [s, c] = o;
685
+ q(s, s.mul(e).add(a.mul(1 - e))), q(c, c.mul(t).add(a.square().mul(1 - t))), q(i.value, this.start(i).sub(s.mul(this.lr / n).div(c.mul(1 / r).sqrt().add(this.#t))));
686
+ }
687
+ }
688
+ dispose() {
689
+ for (let [e, t] of this.#n.values()) e.dispose(), t.dispose();
690
+ this.#n.clear();
691
+ }
692
+ }, Z = class extends X {
693
+ constructor(e, t = {}) {
694
+ super(e, t, .01);
695
+ }
696
+ gradient(e, t) {
697
+ return t;
698
+ }
699
+ start(e) {
700
+ return this.decay ? e.value.mul(1 - this.lr * this.decay) : e.value;
701
+ }
702
+ };
703
+ //#endregion
704
+ export { X as Adam, Z as AdamW, N as AvgPool2d, A as Conv1d, k as Conv2d, U as Dropout, G as Embedding, P as Flatten, R as GELU, W as LayerNorm, L as LeakyReLU, D as Linear, M as MaxPool2d, T as Module, K as MultiHeadAttention, J as Optimizer, I as ReLU, Y as SGD, F as Sequential, z as SiLU, B as Sigmoid, H as Softmax, V as Tanh, p as Tensor, y as crossEntropy, b as dropout, v as mseLoss, l as noGrad, g as parameter, w as scaledDotProductAttention, h as tensor };
Binary file