@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.d.ts ADDED
@@ -0,0 +1,385 @@
1
+ /// <reference lib="esnext.disposable" preserve="true" />
2
+ import { GpuArray, type ReadOptions } from './array.js';
3
+ import { type ComputeContext, type WaitOptions } from './context.js';
4
+ import { type Operand } from './expr.js';
5
+ import { Random } from './random.js';
6
+ /** Runs `work` without recording gradients: tensors made inside have `requiresGrad` false. */
7
+ export declare function noGrad<T>(work: () => T): T;
8
+ /** Options of the reducing methods of {@link Tensor}. */
9
+ export interface TensorAxisOptions {
10
+ /** Axis or axes to reduce. Default every axis. */
11
+ readonly axis?: number | readonly number[];
12
+ /** Keep reduced axes as size 1. Default false. */
13
+ readonly keepdims?: boolean;
14
+ }
15
+ type Other = Tensor | GpuArray | number;
16
+ /**
17
+ * A value on the tape: a GpuArray, its gradient once `backward` has run, and how it was made. Methods return new
18
+ * tensors. `loss.backward()` queues the whole backward pass; `loss.dispose()` (or `using`) frees everything the
19
+ * forward and backward passes made, and leaves parameters, their gradients and your own input arrays alone.
20
+ */
21
+ export declare class Tensor {
22
+ #private;
23
+ /** The values. Evaluated: reading it needs no further work. */
24
+ readonly value: GpuArray;
25
+ /** The gradient of the last `backward`, summed over calls until `zeroGrad`. Kept on leaves only. */
26
+ grad: GpuArray | undefined;
27
+ /** True when gradients flow to or through this tensor. */
28
+ readonly requiresGrad: boolean;
29
+ /** @internal Use {@link tensor}, {@link parameter} or the methods. */
30
+ constructor(value: GpuArray, requiresGrad: boolean, leaf: boolean, parents?: readonly Tensor[], send?: (g: GpuArray) => void, owned?: readonly GpuArray[]);
31
+ /** Dimensions of the value. */
32
+ get shape(): readonly number[];
33
+ /** Number of dimensions. */
34
+ get ndim(): number;
35
+ /** The compute context of the value. */
36
+ get context(): ComputeContext;
37
+ /** The values as a TypedArray, in C order. `signal`, `offset` and `length` work as on `GpuArray.read`. */
38
+ read(options?: ReadOptions): ReturnType<GpuArray['read']>;
39
+ /** The one value of a single-element tensor. */
40
+ item(): Promise<number>;
41
+ /** @internal Adds an array this call now owns to the gradient. */
42
+ accumulate(g: GpuArray): void;
43
+ /**
44
+ * Queues the backward pass from this tensor: the gradient of its value (of `sum(value * seed)` with `seed`) lands in
45
+ * `grad` of every leaf that requires one. Without `seed` the tensor must hold a single element.
46
+ */
47
+ backward(seed?: GpuArray): void;
48
+ /** Clears this tensor's gradient. */
49
+ zeroGrad(): void;
50
+ /** Frees what made this tensor, back to the leaves. Parameters, their gradients and input arrays stay. */
51
+ dispose(): void;
52
+ /** Same as `dispose()`, for `using`. */
53
+ [Symbol.dispose](): void;
54
+ /** @internal Lets the free functions of this module build tape nodes. */
55
+ static made(from: Tensor, value: GpuArray, parents: readonly Tensor[], send: (g: GpuArray) => void, owned?: GpuArray[]): Tensor;
56
+ /** @internal */
57
+ static take(to: Tensor, g: Operand): void;
58
+ /** @internal */
59
+ static give(to: Tensor, g: GpuArray): void;
60
+ /** Element-wise sum, with NumPy's broadcasting. */
61
+ add(other: Other): Tensor;
62
+ /** Element-wise difference. */
63
+ sub(other: Other): Tensor;
64
+ /** Element-wise product. */
65
+ mul(other: Other): Tensor;
66
+ /** Element-wise quotient. */
67
+ div(other: Other): Tensor;
68
+ /** Matrix product over the last two dimensions; leading dimensions broadcast as a batch. Both need two or more. */
69
+ matmul(other: Tensor | GpuArray): Tensor;
70
+ /** Sum over `axis` (default every axis). */
71
+ sum(options?: TensorAxisOptions): Tensor;
72
+ /** Mean over `axis` (default every axis). */
73
+ mean(options?: TensorAxisOptions): Tensor;
74
+ /** Maximum over one axis; the gradient goes to the first maximum of each line. */
75
+ max(options: {
76
+ readonly axis: number;
77
+ readonly keepdims?: boolean;
78
+ }): Tensor;
79
+ /** The same elements in another shape (one dimension may be -1). */
80
+ reshape(...shape: number[]): Tensor;
81
+ /** The dimensions in the order `axes`, as a view. */
82
+ permute(...axes: number[]): Tensor;
83
+ /** e to the power of each element. */
84
+ exp(): Tensor;
85
+ /** Natural logarithm. */
86
+ log(): Tensor;
87
+ /** 1 over the square root. */
88
+ rsqrt(): Tensor;
89
+ /** max(x, 0). */
90
+ relu(): Tensor;
91
+ /** x above 0, `slope` times x below. */
92
+ leakyRelu(slope?: number): Tensor;
93
+ /** The logistic function. */
94
+ sigmoid(): Tensor;
95
+ /** Hyperbolic tangent. */
96
+ tanh(): Tensor;
97
+ /** x times its sigmoid (also called swish). */
98
+ silu(): Tensor;
99
+ /** GELU in its tanh form. */
100
+ gelu(): Tensor;
101
+ /** Softmax along `axis` (default the last). */
102
+ softmax(axis?: number): Tensor;
103
+ /** Log of the softmax along `axis` (default the last), without its overflow. */
104
+ logSoftmax(axis?: number): Tensor;
105
+ }
106
+ /** A leaf tensor over `array`, which stays yours. With `requiresGrad`, `backward` fills its `grad`. */
107
+ export declare function tensor(array: GpuArray, options?: {
108
+ readonly requiresGrad?: boolean;
109
+ }): Tensor;
110
+ /** A leaf tensor to train: it requires a gradient, and optimizers update its array in place. */
111
+ export declare function parameter(array: GpuArray): Tensor;
112
+ /** Mean squared error between `prediction` and `target`. */
113
+ export declare function mseLoss(prediction: Tensor, target: Tensor | GpuArray): Tensor;
114
+ /**
115
+ * Softmax cross-entropy between `logits` ([..., classes]) and integer class `labels` (one per row), averaged over the
116
+ * rows. Takes logits, as PyTorch's `cross_entropy` does: do not apply softmax first.
117
+ */
118
+ export declare function crossEntropy(logits: Tensor, labels: GpuArray): Tensor;
119
+ /** Zeroes each element with probability `p` and scales the rest by 1 / (1 - p). */
120
+ export declare function dropout(x: Tensor, p: number, rng: Random): Tensor;
121
+ type Pair = readonly [number, number];
122
+ /** Scaled dot-product attention options. */
123
+ export interface AttentionOptions {
124
+ /** Each position attends only to itself and earlier ones. Default false. */
125
+ readonly causal?: boolean;
126
+ }
127
+ /**
128
+ * softmax(q k^T / sqrt(d)) v over the last two dimensions: q is [..., t, d], k and v [..., s, d]. The score matrix
129
+ * [..., t, s] is held in memory, so memory grows with t times s.
130
+ */
131
+ export declare function scaledDotProductAttention(q: Tensor, k: Tensor, v: Tensor, options?: AttentionOptions): Tensor;
132
+ /** A part of a network. Subclasses set layers and parameters as plain properties and define `forward`. */
133
+ export declare abstract class Module {
134
+ #private;
135
+ /** True while training (the default): dropout is on. */
136
+ training: boolean;
137
+ /** Runs the layer. */
138
+ abstract forward(x: Tensor, ...rest: Tensor[]): Tensor;
139
+ /** Every parameter with its dotted name, in property order. */
140
+ namedParameters(prefix?: string): [string, Tensor][];
141
+ /** Every parameter. */
142
+ parameters(): Tensor[];
143
+ /** Switches this module and those inside it to training (or, with false, to evaluation). Returns this. */
144
+ train(mode?: boolean): this;
145
+ /** Switches to evaluation: dropout is off. Returns this. */
146
+ eval(): this;
147
+ /** Inference on an array: no gradients, evaluation mode, and only the result stays allocated. */
148
+ predict(input: GpuArray): GpuArray;
149
+ /** The parameters and each child module's saved state, by dotted name. `signal` cancels every nested read. */
150
+ stateDict(options?: WaitOptions): Promise<Record<string, Float32Array>>;
151
+ /** Writes saved values into the parameters. Every parameter must be present, in its size. */
152
+ loadStateDict(state: Readonly<Record<string, ArrayLike<number>>>): void;
153
+ /** Frees the parameters, their gradients and the layer's tables. */
154
+ dispose(): void;
155
+ /** @internal Frees what a layer holds besides parameters. */
156
+ release(): void;
157
+ /** Same as `dispose()`, for `using`. */
158
+ [Symbol.dispose](): void;
159
+ }
160
+ /** Options for layers with random starting weights. */
161
+ export interface InitOptions {
162
+ /** Generator for the starting weights, to make them repeat. Default a new, randomly seeded one. */
163
+ readonly rng?: Random;
164
+ }
165
+ /** y = x W^T + b over the last dimension. W is [outFeatures, inFeatures]. */
166
+ export declare class Linear extends Module {
167
+ /** [outFeatures, inFeatures]. */
168
+ readonly weight: Tensor;
169
+ /** [outFeatures], unless made with `bias: false`. */
170
+ readonly bias: Tensor | undefined;
171
+ constructor(gpu: ComputeContext, inFeatures: number, outFeatures: number, options?: InitOptions & {
172
+ readonly bias?: boolean;
173
+ });
174
+ forward(x: Tensor): Tensor;
175
+ }
176
+ /** Geometry of a convolution. */
177
+ export interface ConvOptions extends InitOptions {
178
+ /** Step between windows. Default 1. */
179
+ readonly stride?: number | Pair;
180
+ /** Zeros added on each side. Default 0. */
181
+ readonly padding?: number | Pair;
182
+ /** Spacing between kernel taps. Default 1. */
183
+ readonly dilation?: number | Pair;
184
+ /** Add a learned bias per output channel. Default true. */
185
+ readonly bias?: boolean;
186
+ }
187
+ /** 2D convolution (cross-correlation, as in every deep learning library) of [n, channels, h, w] input. */
188
+ export declare class Conv2d extends Module {
189
+ #private;
190
+ /** [outChannels, inChannels, kh, kw]. */
191
+ readonly weight: Tensor;
192
+ /** [outChannels], unless made with `bias: false`. */
193
+ readonly bias: Tensor | undefined;
194
+ constructor(gpu: ComputeContext, inChannels: number, outChannels: number, kernelSize: number | Pair, options?: ConvOptions);
195
+ forward(x: Tensor): Tensor;
196
+ release(): void;
197
+ }
198
+ /** 1D convolution of [n, channels, length] input. Weights are [outChannels, inChannels, 1, kernelSize]. */
199
+ export declare class Conv1d extends Module {
200
+ /** The 2D convolution this layer runs on a height of 1. */
201
+ readonly conv: Conv2d;
202
+ constructor(gpu: ComputeContext, inChannels: number, outChannels: number, kernelSize: number, options?: Omit<ConvOptions, 'stride' | 'padding' | 'dilation'> & {
203
+ readonly stride?: number;
204
+ readonly padding?: number;
205
+ readonly dilation?: number;
206
+ });
207
+ forward(x: Tensor): Tensor;
208
+ }
209
+ /** Geometry of a pooling layer. */
210
+ export interface PoolOptions {
211
+ /** Step between windows. Default the kernel size. */
212
+ readonly stride?: number | Pair;
213
+ /** Added on each side, at most half the kernel. Default 0. */
214
+ readonly padding?: number | Pair;
215
+ }
216
+ declare abstract class Pool2d extends Module {
217
+ #private;
218
+ constructor(kernelSize: number | Pair, options?: PoolOptions);
219
+ protected abstract fold(windows: Tensor): Tensor;
220
+ protected abstract readonly edge: number;
221
+ forward(x: Tensor): Tensor;
222
+ release(): void;
223
+ }
224
+ /** Largest value of each window of [n, channels, h, w] input. */
225
+ export declare class MaxPool2d extends Pool2d {
226
+ protected readonly edge: number;
227
+ protected fold(windows: Tensor): Tensor;
228
+ }
229
+ /** Mean of each window of [n, channels, h, w] input. Padding counts as zeros in the mean. */
230
+ export declare class AvgPool2d extends Pool2d {
231
+ protected readonly edge = 0;
232
+ protected fold(windows: Tensor): Tensor;
233
+ }
234
+ /** Keeps the first dimension and flattens the rest. */
235
+ export declare class Flatten extends Module {
236
+ forward(x: Tensor): Tensor;
237
+ }
238
+ /** Runs layers in order. */
239
+ export declare class Sequential extends Module {
240
+ /** The layers. */
241
+ readonly layers: readonly Module[];
242
+ constructor(...layers: Module[]);
243
+ forward(x: Tensor): Tensor;
244
+ }
245
+ /** See {@link Tensor.relu}. */
246
+ export declare class ReLU extends Module {
247
+ forward(x: Tensor): Tensor;
248
+ }
249
+ /** See {@link Tensor.leakyRelu}. */
250
+ export declare class LeakyReLU extends Module {
251
+ readonly slope: number;
252
+ constructor(slope?: number);
253
+ forward(x: Tensor): Tensor;
254
+ }
255
+ /** See {@link Tensor.gelu}. */
256
+ export declare class GELU extends Module {
257
+ forward(x: Tensor): Tensor;
258
+ }
259
+ /** See {@link Tensor.silu}. */
260
+ export declare class SiLU extends Module {
261
+ forward(x: Tensor): Tensor;
262
+ }
263
+ /** See {@link Tensor.sigmoid}. */
264
+ export declare class Sigmoid extends Module {
265
+ forward(x: Tensor): Tensor;
266
+ }
267
+ /** See {@link Tensor.tanh}. */
268
+ export declare class Tanh extends Module {
269
+ forward(x: Tensor): Tensor;
270
+ }
271
+ /** See {@link Tensor.softmax}. */
272
+ export declare class Softmax extends Module {
273
+ readonly axis: number;
274
+ constructor(axis?: number);
275
+ forward(x: Tensor): Tensor;
276
+ }
277
+ /** See {@link dropout}. Off in evaluation mode. */
278
+ export declare class Dropout extends Module {
279
+ #private;
280
+ readonly p: number;
281
+ constructor(p?: number, options?: InitOptions);
282
+ forward(x: Tensor): Tensor;
283
+ }
284
+ /** Normalizes the last dimension to mean 0 and variance 1, then scales and shifts it by learned values. */
285
+ export declare class LayerNorm extends Module {
286
+ #private;
287
+ /** Scale, [features], starting at 1. */
288
+ readonly weight: Tensor;
289
+ /** Shift, [features], starting at 0. */
290
+ readonly bias: Tensor;
291
+ constructor(gpu: ComputeContext, features: number, options?: {
292
+ readonly eps?: number;
293
+ });
294
+ forward(x: Tensor): Tensor;
295
+ }
296
+ /** Rows of a learned table, looked up by integer ids of any shape. */
297
+ export declare class Embedding extends Module {
298
+ /** [count, dim]. */
299
+ readonly weight: Tensor;
300
+ constructor(gpu: ComputeContext, count: number, dim: number, options?: InitOptions);
301
+ forward(ids: Tensor): Tensor;
302
+ }
303
+ /** Multi-head attention: self-attention with one argument, or query, key and value. Input is [batch, length, dim]. */
304
+ export declare class MultiHeadAttention extends Module {
305
+ #private;
306
+ /** Query projection. */
307
+ readonly query: Linear;
308
+ /** Key projection. */
309
+ readonly key: Linear;
310
+ /** Value projection. */
311
+ readonly value: Linear;
312
+ /** Output projection. */
313
+ readonly output: Linear;
314
+ constructor(gpu: ComputeContext, dim: number, heads: number, options?: InitOptions & AttentionOptions & {
315
+ readonly bias?: boolean;
316
+ });
317
+ forward(query: Tensor, key?: Tensor, value?: Tensor): Tensor;
318
+ }
319
+ /** What every optimizer shares. */
320
+ export declare abstract class Optimizer {
321
+ /** The parameters it updates. */
322
+ readonly parameters: readonly Tensor[];
323
+ /** Learning rate; change it between steps to schedule it. */
324
+ lr: number;
325
+ constructor(parameters: readonly Tensor[], lr: number);
326
+ /** Clears every parameter's gradient; call it before each `backward`. */
327
+ zeroGrad(): void;
328
+ /** Updates each parameter that has a gradient. */
329
+ abstract step(): void;
330
+ /** Frees the optimizer's state. */
331
+ abstract dispose(): void;
332
+ /** Same as `dispose()`, for `using`. */
333
+ [Symbol.dispose](): void;
334
+ }
335
+ /** Options of {@link SGD}. */
336
+ export interface SGDOptions {
337
+ /** Learning rate. Default 0.01. */
338
+ readonly lr?: number;
339
+ /** Momentum. Default 0. */
340
+ readonly momentum?: number;
341
+ /** L2 penalty added to the gradient. Default 0. */
342
+ readonly weightDecay?: number;
343
+ }
344
+ /** Stochastic gradient descent with optional momentum. */
345
+ export declare class SGD extends Optimizer {
346
+ #private;
347
+ constructor(parameters: readonly Tensor[], options?: SGDOptions);
348
+ step(): void;
349
+ dispose(): void;
350
+ }
351
+ /** Options of {@link Adam} and {@link AdamW}. */
352
+ export interface AdamOptions {
353
+ /** Learning rate. Default 0.001. */
354
+ readonly lr?: number;
355
+ /** Decay of the two moving averages. Default [0.9, 0.999]. */
356
+ readonly betas?: readonly [number, number];
357
+ /** Added to the denominator. Default 1e-8. */
358
+ readonly eps?: number;
359
+ /** Adam: L2 penalty added to the gradient, default 0. AdamW: decay applied to the weights, default 0.01. */
360
+ readonly weightDecay?: number;
361
+ }
362
+ /** Adam: steps scaled by running averages of the gradient and its square. */
363
+ export declare class Adam extends Optimizer {
364
+ #private;
365
+ /** @internal */
366
+ protected readonly decay: number;
367
+ constructor(parameters: readonly Tensor[], options?: AdamOptions, decay?: number);
368
+ /** @internal The gradient the moments see. */
369
+ protected gradient(p: Tensor, g: GpuArray): Operand;
370
+ /** @internal The value the update starts from. */
371
+ protected start(p: Tensor): Operand;
372
+ step(): void;
373
+ dispose(): void;
374
+ }
375
+ /**
376
+ * Adam with weight decay applied to the weights directly instead of through the gradient. Each step multiplies the
377
+ * weights by `1 - lr * weightDecay` (the PyTorch convention). Loshchilov and Hutter's Algorithm 2 subtracts
378
+ * eta_t * lambda * theta, which the learning rate does not scale: their lambda is `lr * weightDecay` here.
379
+ */
380
+ export declare class AdamW extends Adam {
381
+ constructor(parameters: readonly Tensor[], options?: AdamOptions);
382
+ protected gradient(_p: Tensor, g: GpuArray): Operand;
383
+ protected start(p: Tensor): Operand;
384
+ }
385
+ export {};