@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/expr.d.ts ADDED
@@ -0,0 +1,196 @@
1
+ import { type DType } from './dtype.js';
2
+ import type { ComputeContext, WaitOptions } from './context.js';
3
+ import type { GpuArray, ReadOptions } from './array.js';
4
+ /** The GPU memory behind an array and its views. */
5
+ export interface Storage {
6
+ readonly buffer: GPUBuffer;
7
+ readonly dtype: DType;
8
+ disposed: boolean;
9
+ }
10
+ /** @internal An expression tree node. */
11
+ export type Node = {
12
+ readonly kind: 'leaf';
13
+ readonly array: GpuArray;
14
+ } | {
15
+ readonly kind: 'scalar';
16
+ readonly value: number;
17
+ readonly dtype: DType;
18
+ } | {
19
+ readonly kind: 'index';
20
+ readonly dtype: 'u32';
21
+ readonly shape: readonly number[];
22
+ } | {
23
+ readonly kind: 'op';
24
+ readonly op: string;
25
+ readonly args: readonly Node[];
26
+ readonly dtype: DType;
27
+ readonly shape: readonly number[];
28
+ };
29
+ /** Something element-wise operations take: an array, an expression, or a plain number (broadcast everywhere). */
30
+ export type OperandLike = Operand | number;
31
+ /** An axis or axes to reduce along, and whether to keep them as length-1 dimensions. */
32
+ export interface AxisOptions {
33
+ /** Axis (negative counts from the end) or axes. Default every axis. */
34
+ readonly axis?: number | readonly number[];
35
+ /** Keep reduced axes as length 1, so the result broadcasts against the input. Default false. */
36
+ readonly keepdims?: boolean;
37
+ }
38
+ /** Shape of the NumPy broadcast of `a` and `b`; throws a RangeError naming both when they do not broadcast. */
39
+ export declare function broadcastShapes(a: readonly number[], b: readonly number[]): number[];
40
+ /**
41
+ * Element-wise operations, conversions and reductions shared by {@link GpuArray} and lazy {@link Expr}essions. Every
42
+ * element-wise method returns an `Expr` (nothing runs yet); `eval()`, `read()` or a reduction runs the fused kernel.
43
+ */
44
+ export declare abstract class Operand {
45
+ /** Element type. */
46
+ abstract readonly dtype: DType;
47
+ /** Dimensions, outermost first (C order). `[]` for a single value. */
48
+ abstract readonly shape: readonly number[];
49
+ /** The compute context. */
50
+ abstract readonly context: ComputeContext;
51
+ /** @internal The expression node. */
52
+ abstract node(): Node;
53
+ /** Number of elements. */
54
+ get size(): number;
55
+ /** Number of dimensions. */
56
+ get ndim(): number;
57
+ /** @internal Builds an element-wise op node. */
58
+ protected op(op: string, args: readonly OperandLike[], dtype?: DType): Expr;
59
+ /** `this + b`. */ add(b: OperandLike): Expr;
60
+ /** `this - b`. */ sub(b: OperandLike): Expr;
61
+ /** `this * b`. */ mul(b: OperandLike): Expr;
62
+ /** True division `this / b` (integers divide as f32, as NumPy's `/`). */ div(b: OperandLike): Expr;
63
+ /** Floor division (NumPy `//`); integer division by zero gives 0. */ floorDiv(b: OperandLike): Expr;
64
+ /** Remainder with the sign of `b` (NumPy `%`). */ mod(b: OperandLike): Expr;
65
+ /** `this ** b` (as f32). */ pow(b: OperandLike): Expr;
66
+ /** Element-wise minimum (NumPy `minimum`). */ minimum(b: OperandLike): Expr;
67
+ /** Element-wise maximum (NumPy `maximum`). */ maximum(b: OperandLike): Expr;
68
+ /** Limits values to [lo, hi] (NumPy `clip`). */ clip(lo: OperandLike, hi: OperandLike): Expr;
69
+ /** Two-argument arctangent `atan2(this, x)` in radians. */ atan2(x: OperandLike): Expr;
70
+ /** `sqrt(this² + b²)`. */ hypot(b: OperandLike): Expr;
71
+ /** `-this`. */ neg(): Expr;
72
+ /** Absolute value. */ abs(): Expr;
73
+ /** -1, 0 or 1. */ sign(): Expr;
74
+ /** `this * this`. */ square(): Expr;
75
+ /** Square root. */ sqrt(): Expr;
76
+ /** `1 / sqrt(this)`. */ rsqrt(): Expr;
77
+ /** `1 / this`. */ reciprocal(): Expr;
78
+ /** e to the power of each element. */ exp(): Expr;
79
+ /** 2 to the power of each element. */ exp2(): Expr;
80
+ /** `exp(this) - 1`, accurate near 0. */ expm1(): Expr;
81
+ /** Natural logarithm. */ log(): Expr;
82
+ /** Base-2 logarithm. */ log2(): Expr;
83
+ /** `log(1 + this)`, accurate near 0. */ log1p(): Expr;
84
+ /** Sine (radians). */ sin(): Expr;
85
+ /** Cosine (radians). */ cos(): Expr;
86
+ /** Tangent (radians). */ tan(): Expr;
87
+ /** Arcsine. */ asin(): Expr;
88
+ /** Arccosine. */ acos(): Expr;
89
+ /** Arctangent. */ atan(): Expr;
90
+ /** Hyperbolic sine. */ sinh(): Expr;
91
+ /** Hyperbolic cosine. */ cosh(): Expr;
92
+ /** Hyperbolic tangent. */ tanh(): Expr;
93
+ /** Radians to degrees. */ degrees(): Expr;
94
+ /** Degrees to radians. */ radians(): Expr;
95
+ /** Rounds down. */ floor(): Expr;
96
+ /** Rounds up. */ ceil(): Expr;
97
+ /** Rounds to nearest, ties to even (as NumPy). */ round(): Expr;
98
+ /** Rounds toward zero. */ trunc(): Expr;
99
+ /** 1 where `this < b`, else 0 (u32). */ lt(b: OperandLike): Expr;
100
+ /** 1 where `this <= b`, else 0 (u32). */ le(b: OperandLike): Expr;
101
+ /** 1 where `this > b`, else 0 (u32). */ gt(b: OperandLike): Expr;
102
+ /** 1 where `this >= b`, else 0 (u32). */ ge(b: OperandLike): Expr;
103
+ /** 1 where `this == b`, else 0 (u32). */ eq(b: OperandLike): Expr;
104
+ /** 1 where `this != b`, else 0 (u32). */ ne(b: OperandLike): Expr;
105
+ /** Logical and of truthiness (non-zero), as u32 0 or 1. */ and(b: OperandLike): Expr;
106
+ /** Logical or of truthiness, as u32 0 or 1. */ or(b: OperandLike): Expr;
107
+ /** Logical exclusive or of truthiness, as u32 0 or 1. */ xor(b: OperandLike): Expr;
108
+ /** Logical not: 1 where zero, else 0 (u32). */ not(): Expr;
109
+ /** 1 where NaN (u32). */ isnan(): Expr;
110
+ /** 1 where +-Infinity (u32). */ isinf(): Expr;
111
+ /** 1 where neither NaN nor infinite (u32). */ isfinite(): Expr;
112
+ /** Bitwise and (integers). */ bitAnd(b: OperandLike): Expr;
113
+ /** Bitwise or (integers). */ bitOr(b: OperandLike): Expr;
114
+ /** Bitwise exclusive or (integers). */ bitXor(b: OperandLike): Expr;
115
+ /** Bitwise not (integers). */ bitNot(): Expr;
116
+ /** Shift left by `b` bits (integers). */ shiftLeft(b: OperandLike): Expr;
117
+ /** Shift right by `b` bits, arithmetic for i32 (integers). */ shiftRight(b: OperandLike): Expr;
118
+ /** Number of set bits (integers). */ popcount(): Expr;
119
+ /** Reinterprets the 32-bit pattern as another 32-bit type (f32, i32, u32). */
120
+ bitcast(dtype: Exclude<DType, 'f16'>): Expr;
121
+ /** Converts to `dtype` (floats to integers truncate toward zero and saturate). */
122
+ astype(dtype: DType): Expr;
123
+ /** Runs the expression into a new array (a GpuArray evaluates to a contiguous copy of itself). */
124
+ eval(): GpuArray;
125
+ /** Evaluates and copies the elements back to the CPU in C order. */
126
+ read(options?: ReadOptions): Promise<ArrayBufferView<ArrayBuffer> & ArrayLike<number>>;
127
+ /** The single value of a one-element expression or array, read back. */
128
+ item(options?: WaitOptions): Promise<number>;
129
+ /** Sum (along `axis`). */ sum(options?: AxisOptions): GpuArray;
130
+ /** Product (along `axis`). */ prod(options?: AxisOptions): GpuArray;
131
+ /** Minimum (along `axis`). */ min(options?: AxisOptions): GpuArray;
132
+ /** Maximum (along `axis`). */ max(options?: AxisOptions): GpuArray;
133
+ /** Arithmetic mean (along `axis`), in f32. */ mean(options?: AxisOptions): GpuArray;
134
+ /** Variance (along `axis`) with `ddof` delta degrees of freedom (default 0), in f32. */
135
+ var(options?: AxisOptions & {
136
+ readonly ddof?: number;
137
+ }): GpuArray;
138
+ /** Standard deviation (along `axis`), in f32. */
139
+ std(options?: AxisOptions & {
140
+ readonly ddof?: number;
141
+ }): GpuArray;
142
+ /** Index of the minimum (along one axis; flat index without one), first on ties. */
143
+ argmin(options?: {
144
+ readonly axis?: number;
145
+ readonly keepdims?: boolean;
146
+ }): GpuArray<'u32'>;
147
+ /** Index of the maximum (along one axis; flat index without one), first on ties. */
148
+ argmax(options?: {
149
+ readonly axis?: number;
150
+ readonly keepdims?: boolean;
151
+ }): GpuArray<'u32'>;
152
+ /** 1 when every element (along `axis`) is non-zero (u32). */ all(options?: AxisOptions): GpuArray;
153
+ /** 1 when any element (along `axis`) is non-zero (u32). */ any(options?: AxisOptions): GpuArray;
154
+ }
155
+ /** A lazy element-wise expression. Nothing runs until `eval()`, `read()` or a reduction takes it. */
156
+ export declare class Expr extends Operand {
157
+ #private;
158
+ /** The compute context. */
159
+ readonly context: ComputeContext;
160
+ /** @internal */
161
+ constructor(context: ComputeContext, node: Node & {
162
+ kind: 'op' | 'index';
163
+ });
164
+ /** Element type of the result. */
165
+ get dtype(): DType;
166
+ /** Shape of the result (the broadcast of the inputs). */
167
+ get shape(): readonly number[];
168
+ /** @internal */
169
+ node(): Node;
170
+ }
171
+ /** WGSL for a fused expression: storage declarations, the element function and the resources to bind. */
172
+ export interface Fused {
173
+ /** `enable f16;` when any value is f16. */
174
+ readonly enables: string;
175
+ /** Storage and uniform declarations, bound from `binding` up. */
176
+ readonly declarations: string;
177
+ /** `fn value(i: u32) -> T` returning element i (C order) of the expression. */
178
+ readonly fn: string;
179
+ /** Binding name to array (and `fused` to the constants), for the context's `submit`. */
180
+ readonly resources: Record<string, GPUBufferBinding | Uint32Array<ArrayBuffer>>;
181
+ /** Next free binding index. */
182
+ readonly next: number;
183
+ /** Result type and shape. */
184
+ readonly dtype: DType;
185
+ readonly shape: readonly number[];
186
+ /** A key for the program cache: the source without constants. */
187
+ readonly key: string;
188
+ }
189
+ /**
190
+ * Compiles `operand` into WGSL that computes any element by index. `binding` is the first binding index to use;
191
+ * leaves become read-only storage bindings `src0`, `src1`, ... (one per distinct buffer) and constants a uniform
192
+ * `fused`. `maxStorage` caps the storage bindings; past it, the deepest subtrees are evaluated first.
193
+ */
194
+ export declare function fuse(operand: Operand, binding: number, maxStorage: number, temporaries: GpuArray[]): Fused;
195
+ /** NumPy-style `where(condition, a, b)`: `a` where the condition is non-zero, else `b`, broadcast together. */
196
+ export declare function where(condition: Operand, a: OperandLike, b: OperandLike): Expr;
package/dist/fft.d.ts ADDED
@@ -0,0 +1,33 @@
1
+ import { GpuArray } from './array.js';
2
+ import { Operand } from './expr.js';
3
+ import type { ComputeContext } from './context.js';
4
+ /** A complex array as separate real and imaginary parts (f32, same shape). */
5
+ export interface Complex {
6
+ readonly re: GpuArray<'f32'>;
7
+ readonly im: GpuArray<'f32'>;
8
+ }
9
+ /** Options for transforms. */
10
+ export interface FFTOptions {
11
+ /** Axis to transform along. Default the last. */
12
+ readonly axis?: number;
13
+ }
14
+ /**
15
+ * WGSL for one radix-2 Stockham pass over `lines` lines of length `n`; `l` is the current sub-transform length.
16
+ * `twiddle` holds exp(-2 pi i k / n) for k < n/2, computed in double precision on the host and rounded to f32
17
+ * (`twiddleTable`): WGSL lets `sin` and `cos` be off by up to 2^-11, and GPUs differ (about 3e-7 on an NVIDIA
18
+ * Ampere, enough on an Intel Arc 140V to put an n = 1024 round trip 1.4e-5 off), so no transcendental runs here.
19
+ */
20
+ export declare const stockhamShader = "struct Pass { n: u32, l: u32, lines: u32, inverse: u32 }\n@group(0) @binding(0) var<storage, read> reIn: array<f32>;\n@group(0) @binding(1) var<storage, read> imIn: array<f32>;\n@group(0) @binding(2) var<storage, read_write> reOut: array<f32>;\n@group(0) @binding(3) var<storage, read_write> imOut: array<f32>;\n@group(0) @binding(4) var<uniform> pass_: Pass;\n@group(0) @binding(5) var<storage, read> twiddle: array<vec2f>;\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 t = (wid.x + wid.y * nwg.x) * 256u + lid;\n let half = pass_.n / 2u;\n if (t >= half * pass_.lines) { return; }\n let line = t / half;\n let j = t % half;\n let base = line * pass_.n;\n let k = j % pass_.l;\n\n var w = twiddle[k * (half / pass_.l)];\n if (pass_.inverse == 1u) { w.y = -w.y; }\n let a = vec2f(reIn[base + j], imIn[base + j]);\n let b0 = vec2f(reIn[base + j + half], imIn[base + j + half]);\n let b = vec2f(w.x * b0.x - w.y * b0.y, w.x * b0.y + w.y * b0.x);\n let dest = base + 2u * j - k;\n reOut[dest] = a.x + b.x;\n imOut[dest] = a.y + b.y;\n reOut[dest + pass_.l] = a.x - b.x;\n imOut[dest + pass_.l] = a.y - b.y;\n}";
21
+ /**
22
+ * Forward discrete Fourier transform along `axis` (default the last), of a real array or `{ re, im }`. Any length.
23
+ * @example const { re, im } = fft(signal); const power = re.square().add(im.square());
24
+ */
25
+ export declare function fft(input: Operand | Complex, options?: FFTOptions): Complex;
26
+ /** Inverse transform along `axis`, scaled by 1/n (NumPy's default), so `ifft(fft(x)).re` is x. */
27
+ export declare function ifft(input: Operand | Complex, options?: FFTOptions): Complex;
28
+ /** Two-dimensional transform over the last two axes. */
29
+ export declare function fft2(input: Operand | Complex): Complex;
30
+ /** Inverse two-dimensional transform over the last two axes. */
31
+ export declare function ifft2(input: Operand | Complex): Complex;
32
+ /** Sample frequencies of an n-point transform with sample spacing `d` (NumPy `fftfreq`), f32. */
33
+ export declare function fftfreq(ctx: ComputeContext, n: number, d?: number): GpuArray<'f32'>;
package/dist/fft.js ADDED
@@ -0,0 +1,168 @@
1
+ import { n as e, r as t } from "./errors-CDgOgzCd.js";
2
+ import { n } from "./expr-DwFen60A.js";
3
+ import { n as r, t as i } from "./array-DbI848Wf.js";
4
+ //#region src/fft.ts
5
+ var a = "struct Pass { n: u32, l: u32, lines: u32, inverse: u32 }\n@group(0) @binding(0) var<storage, read> reIn: array<f32>;\n@group(0) @binding(1) var<storage, read> imIn: array<f32>;\n@group(0) @binding(2) var<storage, read_write> reOut: array<f32>;\n@group(0) @binding(3) var<storage, read_write> imOut: array<f32>;\n@group(0) @binding(4) var<uniform> pass_: Pass;\n@group(0) @binding(5) var<storage, read> twiddle: array<vec2f>;\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 t = (wid.x + wid.y * nwg.x) * 256u + lid;\n let half = pass_.n / 2u;\n if (t >= half * pass_.lines) { return; }\n let line = t / half;\n let j = t % half;\n let base = line * pass_.n;\n let k = j % pass_.l;\n\n var w = twiddle[k * (half / pass_.l)];\n if (pass_.inverse == 1u) { w.y = -w.y; }\n let a = vec2f(reIn[base + j], imIn[base + j]);\n let b0 = vec2f(reIn[base + j + half], imIn[base + j + half]);\n let b = vec2f(w.x * b0.x - w.y * b0.y, w.x * b0.y + w.y * b0.x);\n let dest = base + 2u * j - k;\n reOut[dest] = a.x + b.x;\n imOut[dest] = a.y + b.y;\n reOut[dest + pass_.l] = a.x - b.x;\n imOut[dest + pass_.l] = a.y - b.y;\n}", o = (e) => e > 0 && !(e & e - 1);
6
+ function s(t) {
7
+ if (!o(t) || t < 2) throw e(`twiddleTable needs a power of two of at least 2, got ${t}`, "compute");
8
+ let n = t / 2, r = new Float32Array(t);
9
+ for (let e = 0; e < n; e++) {
10
+ let n = 2 * Math.PI * e / t, i = 4 * e === t;
11
+ r[2 * e] = i ? 0 : Math.cos(n), r[2 * e + 1] = i ? -1 : -Math.sin(n);
12
+ }
13
+ return r;
14
+ }
15
+ var c = 8, l = /* @__PURE__ */ new WeakMap();
16
+ function u(e, t) {
17
+ let n = l.get(e);
18
+ n || l.set(e, n = /* @__PURE__ */ new Map());
19
+ let r = n.get(t);
20
+ if (r && !r.disposed ? n.delete(t) : r = e.array(s(t)), n.set(t, r), n.size > c) {
21
+ let [e, t] = n.entries().next().value;
22
+ n.delete(e), t.dispose();
23
+ }
24
+ return r;
25
+ }
26
+ function d(e, t, n, r, i, o) {
27
+ let s = t, c = n, l = [], d = e.program(a, void 0, "fft.stockham"), f = [], p = r * i, m = e.empty([p], "f32"), h = e.empty([p], "f32"), g = r > 2 ? e.empty([p], "f32") : m, _ = r > 2 ? e.empty([p], "f32") : h;
28
+ if (r === 1) return e.submit([], [[
29
+ t.buffer,
30
+ t.offset * 4,
31
+ m.buffer,
32
+ 0,
33
+ p * 4
34
+ ], [
35
+ n.buffer,
36
+ n.offset * 4,
37
+ h.buffer,
38
+ 0,
39
+ p * 4
40
+ ]]), {
41
+ re: m,
42
+ im: h
43
+ };
44
+ let v = u(e, r), y = 0;
45
+ for (let t = 1; t < r; t *= 2) {
46
+ let [n, a] = y === 0 ? [m, h] : [g, _];
47
+ f.push({
48
+ program: d,
49
+ resources: {
50
+ reIn: s,
51
+ imIn: c,
52
+ reOut: n,
53
+ imOut: a,
54
+ pass_: new Uint32Array([
55
+ r,
56
+ t,
57
+ i,
58
+ +!!o
59
+ ]),
60
+ twiddle: v
61
+ },
62
+ workgroups: e.grid(Math.ceil(p / 2 / 256))
63
+ }), s = n, c = a, y ^= 1;
64
+ }
65
+ if (e.submit(f), r > 2) for (let e of s === m ? [g, _] : [m, h]) l.push(e);
66
+ for (let e of l) e.dispose();
67
+ return {
68
+ re: s,
69
+ im: c
70
+ };
71
+ }
72
+ var f = (e, t, n, r) => ({
73
+ re: e.mul(n).sub(t.mul(r)),
74
+ im: e.mul(r).add(t.mul(n))
75
+ });
76
+ function p(e, t, n, r, i, a) {
77
+ let o = 1;
78
+ for (; o < 2 * r - 1;) o *= 2;
79
+ let s = a ? 1 : -1, c = new Float32Array(r), l = new Float32Array(r);
80
+ for (let e = 0; e < r; e++) {
81
+ let t = s * Math.PI * (e * e % (2 * r)) / r;
82
+ c[e] = Math.cos(t), l[e] = Math.sin(t);
83
+ }
84
+ let u = new Float32Array(o), p = new Float32Array(o);
85
+ for (let e = 0; e < r; e++) u[e] = c[e], p[e] = -l[e], e && (u[o - e] = c[e], p[o - e] = -l[e]);
86
+ let m = e.array(c, { shape: [1, r] }), h = e.array(l, { shape: [1, r] }), g = e.array(u), _ = e.array(p), v = d(e, g, _, o, 1, !1), y = f(t.reshape(i, r), n.reshape(i, r), m, h), b = e.zeros([i, o]), x = e.zeros([i, o]), S = y.re.eval(), C = y.im.eval(), w = [];
87
+ for (let e = 0; e < i; e++) w.push([
88
+ S.buffer,
89
+ e * r * 4,
90
+ b.buffer,
91
+ e * o * 4,
92
+ r * 4
93
+ ]), w.push([
94
+ C.buffer,
95
+ e * r * 4,
96
+ x.buffer,
97
+ e * o * 4,
98
+ r * 4
99
+ ]);
100
+ e.submit([], w);
101
+ let T = d(e, b, x, o, i, !1), E = v.re.reshape(1, o), D = v.im.reshape(1, o), O = f(T.re.reshape(i, o), T.im.reshape(i, o), E, D), k = O.re.eval(), A = O.im.eval(), j = d(e, k, A, o, i, !0), M = f(j.re.reshape(i, o).slice(null, [0, r]), j.im.reshape(i, o).slice(null, [0, r]), m, h), N = {
102
+ re: M.re.mul(1 / o).eval().transfer([i * r]),
103
+ im: M.im.mul(1 / o).eval().transfer([i * r])
104
+ };
105
+ for (let e of [
106
+ m,
107
+ h,
108
+ g,
109
+ _,
110
+ v.re,
111
+ v.im,
112
+ b,
113
+ x,
114
+ S,
115
+ C,
116
+ T.re,
117
+ T.im,
118
+ k,
119
+ A,
120
+ j.re,
121
+ j.im
122
+ ]) e.dispose();
123
+ return N;
124
+ }
125
+ function m(a, s, c) {
126
+ let l = a instanceof n ? a : a.re, u = a instanceof n ? void 0 : a.im;
127
+ if (!(l instanceof n)) throw t("fft takes a real array or { re, im } arrays", "compute");
128
+ if (u && (u.ndim !== l.ndim || u.shape.some((e, t) => e !== l.shape[t]))) throw e("fft re and im must have one shape", "compute");
129
+ let f = l.context;
130
+ if (f.check(), l.ndim === 0) throw e("fft needs at least one dimension", "compute");
131
+ let m = r(s.axis ?? -1, l.ndim), h = l.shape[m], g = l.shape, _ = [...g.keys()].filter((e) => e !== m).concat(m), v = _.map((e, t) => _.indexOf(t)), y = (e) => {
132
+ let t = e instanceof i ? e : e.eval(), n = t.transpose(..._).astype("f32").eval();
133
+ return t !== e && t.dispose(), n;
134
+ }, b = y(l), x = u ? y(u) : f.zeros(b.shape), S = h ? b.size / h : 0, C;
135
+ C = b.size === 0 ? {
136
+ re: f.zeros(b.shape),
137
+ im: f.zeros(b.shape)
138
+ } : o(h) ? d(f, b.reshape(b.size), x.reshape(x.size), h, S, c) : p(f, b, x, h, S, c), b.dispose(), x.dispose();
139
+ let w = _.map((e) => g[e]), T = (e) => {
140
+ let t = e.reshape(...w).transpose(...v), n = (c ? t.mul(1 / h) : t).eval();
141
+ return e.dispose(), n;
142
+ };
143
+ return {
144
+ re: T(C.re),
145
+ im: T(C.im)
146
+ };
147
+ }
148
+ function h(e, t = {}) {
149
+ return m(e, t, !1);
150
+ }
151
+ function g(e, t = {}) {
152
+ return m(e, t, !0);
153
+ }
154
+ function _(e) {
155
+ let t = h(e, { axis: -1 }), n = h(t, { axis: -2 });
156
+ return t.re.dispose(), t.im.dispose(), n;
157
+ }
158
+ function v(e) {
159
+ let t = g(e, { axis: -1 }), n = g(t, { axis: -2 });
160
+ return t.re.dispose(), t.im.dispose(), n;
161
+ }
162
+ function y(t, n, r = 1) {
163
+ if (!Number.isInteger(n) || n < 1) throw e(`fftfreq n must be a whole number of at least 1, got ${n}`, "compute");
164
+ let i = t.arange(0, n, 1, "i32"), a = t.where(i.lt(Math.ceil(n / 2)), i, i.sub(n)).astype("f32").mul(1 / (n * r)).eval();
165
+ return i.dispose(), a;
166
+ }
167
+ //#endregion
168
+ export { h as fft, _ as fft2, y as fftfreq, g as ifft, v as ifft2, a as stockhamShader };
@@ -0,0 +1,63 @@
1
+ // @ts-ignore optional peer: its types apply when it is installed
2
+ import type { Engine, EnginePlugin, FrameGraph } from '@margoengine/core/extension';
3
+ // @ts-ignore optional peer: its types apply when it is installed
4
+ import type { EngineKernel } from '@margoengine/core';
5
+ import { ComputeContext } from './context.js';
6
+ import { BoundKernel, type RunOptions } from './kernel.js';
7
+ /** A per-frame job: a bound kernel, its dispatch (or a function giving it each frame), and its order among jobs. */
8
+ export interface FrameJob {
9
+ readonly kernel: BoundKernel;
10
+ readonly run: RunOptions | ((delta: number) => RunOptions | null);
11
+ readonly order: number;
12
+ }
13
+ /** Options for {@link ComputeFrame.attach}. */
14
+ export interface ComputeFrameOptions {
15
+ /**
16
+ * Frame-graph order of the compute pass. Default -1000: before the main scene pass (order 0) and before effects that
17
+ * run ahead of it.
18
+ */
19
+ readonly order?: number;
20
+ /** Called after the GPU device is restored (a lost device's buffers are gone): rebuild arrays and jobs on `frame.gpu`. */
21
+ readonly onRestored?: (frame: ComputeFrame) => void;
22
+ }
23
+ /**
24
+ * Runs compute kernels every frame inside an engine's frame graph. `frame.gpu` is a compute context on the engine's
25
+ * device; bind kernels there and `add` them as jobs. A job's `run` may be a function of the frame delta (return null
26
+ * to skip that frame), so uniforms can change every frame with `bound.set(...)` inside it.
27
+ * @example
28
+ * const frame = ComputeFrame.attach(engine);
29
+ * const step = frame.gpu.kernel(simulateWGSL).bind({ particles, params: { dt: 0 } });
30
+ * frame.add(step, (dt) => (step.set('params', { dt }), { count: particles.size / 4 }));
31
+ */
32
+ export declare class ComputeFrame implements EnginePlugin {
33
+ #private;
34
+ /** Plugin name, unique per frame instance. */
35
+ readonly name: string;
36
+ /** Creates the frame and attaches it to `engine` (WebGPU backend). */
37
+ static attach(engine: EngineKernel, options?: ComputeFrameOptions): ComputeFrame;
38
+ /** @param options Pass order and the device-restore callback. Attach with `engine.use(frame)`, or use {@link ComputeFrame.attach}. */
39
+ constructor(options?: ComputeFrameOptions);
40
+ /** The compute context on the engine's device. */
41
+ get gpu(): ComputeContext;
42
+ /** The jobs, in run order. */
43
+ get jobs(): readonly FrameJob[];
44
+ /** @internal EnginePlugin hook. */
45
+ setup(engine: Engine): void;
46
+ /** @internal EnginePlugin hook. */
47
+ onPreUpdate(delta: number): void;
48
+ /** @internal EnginePlugin hook. */
49
+ registerPasses(graph: FrameGraph): void;
50
+ /** @internal EnginePlugin hook: the old device's buffers are gone, so jobs are dropped and a new context made. */
51
+ onDeviceRestored(engine: Engine): void;
52
+ /**
53
+ * Adds a job run every frame, in ascending `order` (default: after the jobs already added). Returns a function that
54
+ * removes it.
55
+ */
56
+ add(kernel: BoundKernel, run: FrameJob['run'], options?: {
57
+ readonly order?: number;
58
+ }): () => void;
59
+ /** Removes the plugin from the engine and frees the context's arrays (the engine's device stays). */
60
+ dispose(): void;
61
+ /** Same as `dispose()`, for `using`. */
62
+ [Symbol.dispose](): void;
63
+ }
package/dist/frame.js ADDED
@@ -0,0 +1,82 @@
1
+ // @margo/core-built 0.1.0
2
+ import {coreRequirement as __margoCoreRequirement,assertCore as __margoAssertCore} from '@margoengine/core/extension';
3
+
4
+ import { n as e, r as t, t as n } from "./errors-CDgOgzCd.js";
5
+ import { i as r, t as i } from "./context-C75sQQra.js";
6
+ //#region src/frame.ts
7
+ var a = 0, o = class o {coreRequirement=__margoCoreRequirement("0.1.0",import.meta.url);
8
+ #e;
9
+ #t;
10
+ #n;
11
+ #r;
12
+ #i;
13
+ #a;
14
+ #o;
15
+ static attach(e, t = {}) {__margoAssertCore(e,__margoCoreRequirement("0.1.0",import.meta.url));
16
+ let n = new o(t);
17
+ return e.use(n), n;
18
+ }
19
+ constructor(t = {}) {
20
+ this.name = `compute-frame:${a++}`, this.#n = [], this.#a = 0, this.#o = !1;
21
+ let n = t.order ?? -1e3;
22
+ if (!Number.isFinite(n)) throw e(`ComputeFrame order must be a finite number, got ${n}`, "compute");
23
+ this.#e = n, this.#t = t.onRestored;
24
+ }
25
+ get gpu() {
26
+ if (this.#o) throw n("disposed", "ComputeFrame disposed; attach a new one", "compute");
27
+ if (!this.#r) throw n("state", "ComputeFrame is not attached; call ComputeFrame.attach(engine)", "compute");
28
+ return this.#r;
29
+ }
30
+ get jobs() {
31
+ return this.#n;
32
+ }
33
+ setup(e) {
34
+ let t = e.gpu;
35
+ if (!t) throw n("unsupported", "ComputeFrame needs the WebGPU backend; the engine runs WebGL2", "compute");
36
+ this.#i = e, this.#r = new i(t, !1);
37
+ }
38
+ onPreUpdate(e) {
39
+ this.#a = e;
40
+ }
41
+ registerPasses(e) {
42
+ e.add({
43
+ name: `${this.name}:jobs`,
44
+ order: this.#e,
45
+ execute: (e) => this.#s(e)
46
+ });
47
+ }
48
+ #s(e) {
49
+ if (!(e.backend !== "webgpu" || e.view && e.view.index > 0 || !this.#n.length)) for (let t of this.#n) {
50
+ let n = typeof t.run == "function" ? t.run(this.#a) : t.run;
51
+ n && t.kernel.encode(e.encoder, n);
52
+ }
53
+ }
54
+ onDeviceRestored(e) {
55
+ this.#n.length = 0, this.#r?.dispose(), this.#r = e.gpu ? new i(e.gpu, !1) : void 0, this.#t?.(this);
56
+ }
57
+ add(e, i, a = {}) {
58
+ if (this.#o) throw n("disposed", "ComputeFrame disposed; attach a new one", "compute");
59
+ if (!(e instanceof r)) throw t("ComputeFrame.add takes a bound kernel: gpu.kernel(code).bind(resources)", "compute");
60
+ if (typeof i != "function" && (typeof i != "object" || !i)) throw t("ComputeFrame.add needs run options ({ count }, { workgroups } or { indirect }) or a function returning them", "compute");
61
+ let o = {
62
+ kernel: e,
63
+ run: i,
64
+ order: a.order ?? (this.#n.at(-1)?.order ?? 0) + 1
65
+ };
66
+ return this.#n.push(o), this.#n.sort((e, t) => e.order - t.order), () => {
67
+ let e = this.#n.indexOf(o);
68
+ e >= 0 && this.#n.splice(e, 1);
69
+ };
70
+ }
71
+ dispose() {
72
+ if (this.#o) return;
73
+ this.#o = !0, this.#n.length = 0, this.#r?.dispose(), this.#r = void 0;
74
+ let e = this.#i;
75
+ this.#i = void 0, e?.sceneOf(this)?.removePlugin(this.name);
76
+ }
77
+ [Symbol.dispose]() {
78
+ this.dispose();
79
+ }
80
+ };
81
+ //#endregion
82
+ export { o as ComputeFrame };
@@ -0,0 +1,75 @@
1
+ /// <reference lib="esnext.disposable" preserve="true" />
2
+ import type { GpuArray } from './array.js';
3
+ import { type ComputeContext, type WaitOptions } from './context.js';
4
+ import { CsrMatrix } from './sparse.js';
5
+ /** Options of every algorithm here. */
6
+ export interface GraphOptions extends WaitOptions {
7
+ /** Rounds between read-backs of whether anything changed. Default 8. */
8
+ readonly checkEvery?: number;
9
+ }
10
+ /** Edges of a graph by their ends. */
11
+ export interface GraphData {
12
+ /** Number of vertices. */
13
+ readonly vertices: number;
14
+ /** Source vertex of each edge. */
15
+ readonly sources: ArrayLike<number>;
16
+ /** Target vertex of each edge. */
17
+ readonly targets: ArrayLike<number>;
18
+ /** Weight of each edge. Default 1 each. */
19
+ readonly weights?: ArrayLike<number>;
20
+ /** Edges run one way. With false, each also runs back. Default true. */
21
+ readonly directed?: boolean;
22
+ }
23
+ /**
24
+ * A graph as a CsrMatrix, built on the CPU from your arrays and uploaded. Edges between the same two vertices keep the
25
+ * smallest weight, as a shortest path would. Dispose it when done.
26
+ * @example const g = graph(gpu, { vertices: 3, sources: [0, 1], targets: [1, 2], directed: false });
27
+ */
28
+ export declare function graph(gpu: ComputeContext, data: GraphData): CsrMatrix;
29
+ /** What {@link bfs} resolves. */
30
+ export interface BfsResult {
31
+ /** Edges from the nearest source to each vertex (i32); -1 where no path leads. */
32
+ readonly distances: GpuArray<'i32'>;
33
+ /** The vertex before each one on a shortest path (i32), the smallest if several; -1 at sources and unreached ones. */
34
+ readonly predecessors: GpuArray<'i32'>;
35
+ /** Rounds run. */
36
+ readonly iterations: number;
37
+ }
38
+ /**
39
+ * Breadth-first search from one source or several, following edges forward and ignoring weights.
40
+ * @example const { distances } = await bfs(g, 0); await distances.read();
41
+ */
42
+ export declare function bfs(A: CsrMatrix, sources: number | readonly number[], options?: GraphOptions): Promise<BfsResult>;
43
+ /** What {@link shortestPaths} resolves. */
44
+ export interface ShortestPathsResult {
45
+ /** Summed weight from the nearest source to each vertex (f32); Infinity where no path leads. */
46
+ readonly distances: GpuArray<'f32'>;
47
+ /**
48
+ * The vertex before each one on a shortest path (i32), the smallest if several; -1 at sources and unreached ones.
49
+ * Edges of weight 0 can tie into a loop here; `distances` still holds.
50
+ */
51
+ readonly predecessors: GpuArray<'i32'>;
52
+ /** Rounds run. */
53
+ readonly iterations: number;
54
+ /** True when a cycle of negative total weight can be reached: then no shortest path exists and `distances` mean nothing. */
55
+ readonly negativeCycle: boolean;
56
+ }
57
+ /**
58
+ * Shortest paths from one source or several by edge weights, which may be negative. Sums are f32.
59
+ * @example const { distances, predecessors } = await shortestPaths(g, 0);
60
+ */
61
+ export declare function shortestPaths(A: CsrMatrix, sources: number | readonly number[], options?: GraphOptions): Promise<ShortestPathsResult>;
62
+ /** What {@link connectedComponents} resolves. */
63
+ export interface ComponentsResult {
64
+ /** Each vertex's component (i32), numbered from 0 in the order of each component's smallest vertex. */
65
+ readonly labels: GpuArray<'i32'>;
66
+ /** How many components there are. */
67
+ readonly count: number;
68
+ /** Rounds run. */
69
+ readonly iterations: number;
70
+ }
71
+ /**
72
+ * Connected components, taking every edge as running both ways (weakly connected components of a directed graph).
73
+ * @example const { labels, count } = await connectedComponents(g);
74
+ */
75
+ export declare function connectedComponents(A: CsrMatrix, options?: GraphOptions): Promise<ComponentsResult>;