@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
Binary file
@@ -0,0 +1,5 @@
1
+ import { t as e } from "./cpu-CdVdqP4I.js";
2
+ //#region src/cpu-load.ts
3
+ var t = () => new e();
4
+ //#endregion
5
+ export { t as cpuContext };
@@ -0,0 +1,3 @@
1
+ import type { ComputeContext } from './context.js';
2
+ /** Makes the CPU context (createCompute's fallback). */
3
+ export declare const cpuContext: () => ComputeContext;
@@ -0,0 +1,8 @@
1
+ import type { Operand } from './expr.js';
2
+ /** @internal Optional execution engine. Host storage and validation stay in CpuContext. */
3
+ export interface CpuRuntime {
4
+ values(operand: Operand): Float64Array;
5
+ run(name: string, inputs: readonly ArrayLike<number>[], params?: readonly number[]): Float64Array[];
6
+ kernel(label: string, resources: Readonly<Record<string, unknown>>): void;
7
+ dispose(): void;
8
+ }
@@ -0,0 +1,42 @@
1
+ /// <reference lib="esnext.disposable" preserve="true" />
2
+ import { CpuContext } from './cpu.js';
3
+ import { type WaitOptions } from './context.js';
4
+ import type { Operand } from './expr.js';
5
+ import type { CpuRuntime } from './cpu-runtime.js';
6
+ interface Kernel {
7
+ memory: WebAssembly.Memory;
8
+ reserve(n: number): number;
9
+ run(op: number): number;
10
+ output(i: number): number;
11
+ length(i: number): number;
12
+ groups(): number;
13
+ release(): void;
14
+ }
15
+ /** Execution counters count bridge calls and SIMD lane groups, never elapsed time. */
16
+ export interface CpuWasmWork {
17
+ /** Number of completed Wasm dispatches. */
18
+ readonly calls: number;
19
+ /** Actual pairs of lanes executed by SIMD arithmetic. */
20
+ readonly simdGroups: number;
21
+ }
22
+ declare class Runtime implements CpuRuntime {
23
+ #private;
24
+ calls: number;
25
+ simdGroups: number;
26
+ constructor(kernel: Kernel);
27
+ run(name: string, inputs: readonly ArrayLike<number>[], params?: readonly number[]): Float64Array[];
28
+ values(operand: Operand): Float64Array;
29
+ kernel(label: string, r: Readonly<Record<string, unknown>>): void;
30
+ dispose(): void;
31
+ }
32
+ /** CPU context backed by its own lazy Rust SIMD instance. Arrays remain ordinary owned host buffers. */
33
+ export declare class CpuWasmContext extends CpuContext {
34
+ #private;
35
+ /** @internal Use createCpuWasm. */
36
+ constructor(runtime: Runtime);
37
+ /** Deterministic work since creation. */
38
+ get work(): CpuWasmWork;
39
+ }
40
+ /** Loads one private SIMD instance. No fetch, compilation or global changes occur on import. */
41
+ export declare function createCpuWasm(options?: WaitOptions): Promise<CpuWasmContext>;
42
+ export {};
@@ -0,0 +1,161 @@
1
+ import { n as e, r as t, t as n } from "./errors-CDgOgzCd.js";
2
+ import { n as r } from "./context-C75sQQra.js";
3
+ import { m as i } from "./expr-DwFen60A.js";
4
+ import { i as a, n as o, r as s, t as c } from "./cpu-CdVdqP4I.js";
5
+ //#region src/cpu-wasm.ts
6
+ var l = /* @__PURE__ */ "add.sub.mul.div.floorDiv.mod.pow.minimum.maximum.clip.atan2.hypot.neg.abs.sign.square.sqrt.exp.exp2.log.log2.sin.cos.tan.asin.acos.atan.sinh.cosh.tanh.degrees.radians.rsqrt.reciprocal.log1p.expm1.floor.ceil.trunc.round.lt.le.gt.ge.eq.ne.and.or.xor.not.isnan.isinf.isfinite.bitAnd.bitOr.bitXor.bitNot.shiftLeft.shiftRight.popcount.bitcast.astype.where".split("."), u = [
7
+ "leaf",
8
+ "scalar",
9
+ "index",
10
+ "expr",
11
+ "reduce",
12
+ "arg",
13
+ "scan",
14
+ "segmented",
15
+ "group",
16
+ "order",
17
+ "gather",
18
+ "quantile",
19
+ "unique",
20
+ "take",
21
+ "scatter",
22
+ "compact",
23
+ "histogram",
24
+ "matmul",
25
+ "fft.stockham",
26
+ "convolve",
27
+ "convolve2d",
28
+ "sparse.spmv",
29
+ "sparse.diagonal",
30
+ "random"
31
+ ], d = (e) => e === "i32" ? 1 : e === "u32" ? 2 : 0, f = class {
32
+ #e;
33
+ constructor(e) {
34
+ this.calls = 0, this.simdGroups = 0, this.#e = e;
35
+ }
36
+ run(t, r, i = []) {
37
+ let a = u.indexOf(t), o = this.#e;
38
+ if (!o) throw n("disposed", "CPU Wasm runtime is disposed", "compute");
39
+ if (a < 0) throw n("unsupported", `CPU Wasm does not support ${t}`, "compute");
40
+ let s = [i, ...r], c = 1 + s.reduce((e, t) => e + 1 + t.length, 0);
41
+ if (c > 8388608) throw e("CPU Wasm packet exceeds 8,388,608 f64 words; process smaller chunks", "compute");
42
+ let l = o.reserve(c), d = new Float64Array(o.memory.buffer, l, c);
43
+ d[0] = s.length;
44
+ let f = 1;
45
+ for (let e of s) d[f++] = e.length, d.set(e, f), f += e.length;
46
+ this.calls++;
47
+ let p = o.run(a);
48
+ return this.simdGroups += o.groups(), Array.from({ length: p }, (e, t) => new Float64Array(o.memory.buffer, o.output(t), o.length(t)).slice());
49
+ }
50
+ values(e) {
51
+ e.context.check();
52
+ let n = e.shape, r = e.size, o = (s) => {
53
+ if (s.kind === "leaf") {
54
+ let t = s.array;
55
+ t.check(e.context);
56
+ let i = n.map((e, r) => {
57
+ let i = r - n.length + t.ndim;
58
+ return i < 0 || t.shape[i] === 1 ? 0 : t.strides[i];
59
+ });
60
+ return this.run("leaf", [
61
+ a(t),
62
+ n,
63
+ i
64
+ ], [r, t.offset])[0];
65
+ }
66
+ if (s.kind === "scalar") return this.run("scalar", [], [
67
+ r,
68
+ s.value,
69
+ d(s.dtype)
70
+ ])[0];
71
+ if (s.kind === "index") return this.run("index", [], [r])[0];
72
+ let c = s.args.map((e) => e.kind === "leaf" ? e.array.dtype : e.dtype), u = c.reduce(i), f = l.indexOf(s.op);
73
+ if (f < 0) throw t(`Unknown element-wise operation ${s.op}`, "compute");
74
+ return this.run("expr", s.args.map(o), [
75
+ f,
76
+ d(u),
77
+ d(s.dtype),
78
+ ...c.map(d)
79
+ ])[0];
80
+ };
81
+ return r ? o(e.node()) : /* @__PURE__ */ new Float64Array();
82
+ }
83
+ kernel(e, t) {
84
+ let r = (e) => {
85
+ let n = o(t[e]);
86
+ return Float64Array.from(n.data.subarray(n.offset));
87
+ }, i = (e, n) => {
88
+ let r = o(t[e]);
89
+ r.data.set(n, r.offset);
90
+ }, a = (e, n) => {
91
+ let r = s(t[e]);
92
+ return Array.from({ length: n }, (e, t) => r.getUint32(t * 4, !0));
93
+ };
94
+ if (e === "matmul") {
95
+ let n = Array.from(t.shape.subarray(0, 12));
96
+ n.push(d(t.product.dtype), t.product.size), i("product", this.run(e, [r("left"), r("right")], n)[0]);
97
+ } else if (e === "fft.stockham") {
98
+ let t = this.run(e, [
99
+ r("reIn"),
100
+ r("imIn"),
101
+ r("twiddle")
102
+ ], a("pass_", 4));
103
+ i("reOut", t[0]), i("imOut", t[1]);
104
+ } else if (e === "convolve" || e === "convolve2d") i("out", this.run(e, [r(e === "convolve" ? "signal" : "image"), r("taps")], a("conv", e === "convolve" ? 5 : 9))[0]);
105
+ else if (e === "sparse.spmv" || e === "sparse.diagonal") {
106
+ let t = [
107
+ "rowPtr",
108
+ "colIdx",
109
+ "values",
110
+ ...e === "sparse.spmv" ? ["x"] : []
111
+ ].map(r);
112
+ i(e === "sparse.spmv" ? "y" : "d", this.run(e, t, a("shape", 1))[0]);
113
+ } else if (e === "random") {
114
+ let n = s(t.draw), r = a("draw", 8);
115
+ r.push(n.getFloat32(32, !0), n.getFloat32(36, !0), n.getInt32(40, !0)), i("out", this.run(e, [], r)[0]);
116
+ } else throw n("unsupported", `The ${e} pass runs WGSL and needs a GPU`, "compute");
117
+ }
118
+ dispose() {
119
+ this.#e?.release(), this.#e = void 0;
120
+ }
121
+ }, p = class extends c {
122
+ #e;
123
+ constructor(e) {
124
+ super(e), this.#e = e;
125
+ }
126
+ get work() {
127
+ return {
128
+ calls: this.#e.calls,
129
+ simdGroups: this.#e.simdGroups
130
+ };
131
+ }
132
+ };
133
+ async function m(e = {}) {
134
+ r(e.signal);
135
+ let t = new URL("./cpu-kernel.wasm?no-inline",
136
+ import.meta.url
137
+ );
138
+ try {
139
+ let i;
140
+ if (t.protocol === "file:") t.search = "", i = await (await import(
141
+ /* @vite-ignore */
142
+ /* webpackIgnore: true */
143
+ "node:fs/promises"
144
+ )).readFile(t, { signal: e.signal });
145
+ else {
146
+ let r = await fetch(t, { signal: e.signal });
147
+ if (!r.ok) throw n("failed", `CPU Wasm load failed: HTTP ${r.status}`, "compute");
148
+ i = new Uint8Array(await r.arrayBuffer());
149
+ }
150
+ r(e.signal);
151
+ let { instance: a } = await WebAssembly.instantiate(i, { host: { math: (e, t, n) => {
152
+ let r = l[e];
153
+ return r === "exp2" ? 2 ** t : r === "rsqrt" ? 1 / Math.sqrt(t) : r === "reciprocal" ? 1 / t : Math[r](t, n);
154
+ } } }), o = new f(a.exports);
155
+ return e.signal?.aborted && (o.dispose(), r(e.signal)), new p(o);
156
+ } catch (t) {
157
+ throw r(e.signal), n("failed", `CPU Wasm initialization failed: ${t instanceof Error ? t.message : String(t)}`, "compute");
158
+ }
159
+ }
160
+ //#endregion
161
+ export { p as CpuWasmContext, m as createCpuWasm };
package/dist/cpu.d.ts ADDED
@@ -0,0 +1,138 @@
1
+ /// <reference lib="esnext.disposable" preserve="true" />
2
+ import { GpuArray } from './array.js';
3
+ import { type DType } from './dtype.js';
4
+ import { Operand, type AxisOptions, type OperandLike } from './expr.js';
5
+ import { ComputeContext, type Copy, type Pass, type PassTiming, type Program, type WaitOptions } from './context.js';
6
+ import type { CpuRuntime } from './cpu-runtime.js';
7
+ import type { Kernel } from './kernel.js';
8
+ import type { Operator } from './shaders.js';
9
+ import type { ScanOptions } from './scan.js';
10
+ import type { SortOptions } from './sort.js';
11
+ import type { TakeOptions } from './select.js';
12
+ import type { Histogram, HistogramOptions } from './histogram.js';
13
+ type Typed = Float32Array | Int32Array | Uint32Array;
14
+ /** The whole host buffer of an array, typed by its element type (index it from `array.offset`). */
15
+ export declare const cpuView: (array: GpuArray) => Typed;
16
+ /** A binding as host values: a GpuArray from its offset, a `{ buffer }` binding whole, or uniform bytes. */
17
+ export declare function cpuBound(resource: unknown): {
18
+ data: Typed;
19
+ offset: number;
20
+ };
21
+ export declare const cpuUniform: (resource: unknown) => DataView<ArrayBufferLike>;
22
+ /**
23
+ * A compute context that runs on the CPU (see {@link createCompute}'s `backend`). Same API as the WebGPU context;
24
+ * your own WGSL (`kernel`, `map`, custom reduce and scan operators) throws a MargoError (`unsupported`).
25
+ */
26
+ export declare class CpuContext extends ComputeContext {
27
+ #private;
28
+ /** @internal Use `createCompute({ backend: 'cpu' })`. */
29
+ constructor(runtime?: CpuRuntime);
30
+ dispose(): void;
31
+ /** `'cpu'`: work runs in JavaScript on the calling thread. */
32
+ get backend(): 'webgpu' | 'cpu';
33
+ /** @internal */
34
+ allocate(size: number, _usage: number, dtype: DType): GPUBuffer;
35
+ /** @internal Programs are not compiled on the CPU: the label picks a host kernel. */
36
+ program(code: string, entryPoint?: string, label?: string): Program;
37
+ /** @internal Runs each pass's host kernel, then the copies. */
38
+ submit(passes: readonly Pass[], copies?: readonly Copy[]): void;
39
+ /** @internal */
40
+ readBytes(buffer: GPUBuffer, offset: number, size: number, signal?: AbortSignal): Promise<ArrayBuffer>;
41
+ /** Resolves at once: CPU work is done when the call returns. */
42
+ done(options?: WaitOptions): Promise<void>;
43
+ /** Runs `work` and resolves an empty list: there are no GPU passes to time. */
44
+ profile(work: () => unknown, options?: WaitOptions): Promise<PassTiming[]>;
45
+ /** Throws a MargoError (`unsupported`): WGSL kernels need a GPU. */
46
+ kernel(_code: string, _options?: {
47
+ readonly entryPoint?: string;
48
+ readonly label?: string;
49
+ }): Kernel;
50
+ /** Throws a MargoError (`unsupported`): `map` runs a WGSL expression; use the element-wise methods. */
51
+ map<T extends DType = DType>(_inputs: Operand | Readonly<Record<string, Operand>>, _expression: string, _options?: {
52
+ readonly dtype?: T;
53
+ readonly label?: string;
54
+ }): GpuArray<T>;
55
+ /** A u32 array of three workgroup counts (only meaningful to WGSL kernels, which need a GPU). */
56
+ indirectArgs(workgroups?: readonly [number, number, number]): GpuArray<'u32'>;
57
+ /** An array (drawing from it needs an engine, which needs a GPU). */
58
+ drawable<T extends DType = 'f32'>(shape: number | readonly number[], dtype?: T): GpuArray<T>;
59
+ /** @internal Interprets the expression into a new contiguous array. */
60
+ evaluate(operand: Operand): GpuArray;
61
+ reduce(input: Operand, op?: Operator, options?: AxisOptions): GpuArray;
62
+ sum(input: Operand, options?: AxisOptions): GpuArray;
63
+ prod(input: Operand, options?: AxisOptions): GpuArray;
64
+ min(input: Operand, options?: AxisOptions): GpuArray;
65
+ max(input: Operand, options?: AxisOptions): GpuArray;
66
+ mean(input: Operand, options?: AxisOptions): GpuArray;
67
+ var(input: Operand, options?: AxisOptions & {
68
+ readonly ddof?: number;
69
+ }): GpuArray;
70
+ std(input: Operand, options?: AxisOptions & {
71
+ readonly ddof?: number;
72
+ }): GpuArray;
73
+ argmin(input: Operand, options?: {
74
+ readonly axis?: number;
75
+ readonly keepdims?: boolean;
76
+ }): GpuArray<'u32'>;
77
+ argmax(input: Operand, options?: {
78
+ readonly axis?: number;
79
+ readonly keepdims?: boolean;
80
+ }): GpuArray<'u32'>;
81
+ all(input: Operand, options?: AxisOptions): GpuArray;
82
+ any(input: Operand, options?: AxisOptions): GpuArray;
83
+ countNonzero(input: Operand, options?: AxisOptions): GpuArray;
84
+ nansum(input: Operand, options?: AxisOptions): GpuArray;
85
+ nanmin(input: Operand, options?: AxisOptions): GpuArray;
86
+ nanmax(input: Operand, options?: AxisOptions): GpuArray;
87
+ nanmean(input: Operand, options?: AxisOptions): GpuArray;
88
+ scan(input: Operand, options?: ScanOptions): GpuArray;
89
+ cumsum(input: Operand, options?: {
90
+ readonly axis?: number;
91
+ }): GpuArray;
92
+ cumprod(input: Operand, options?: {
93
+ readonly axis?: number;
94
+ }): GpuArray;
95
+ segmentedScan(values_: Operand, flags: Operand, options?: Omit<ScanOptions, 'axis'>): GpuArray;
96
+ reduceByKey(keys: Operand, values_: Operand, options?: {
97
+ readonly op?: Operator;
98
+ } & WaitOptions): Promise<{
99
+ keys: GpuArray;
100
+ values: GpuArray;
101
+ }>;
102
+ sort(input: Operand, options?: SortOptions): GpuArray;
103
+ argsort(input: Operand, options?: SortOptions): GpuArray<'u32'>;
104
+ sortByKey(keys: Operand, values_: Operand, options?: SortOptions): {
105
+ readonly keys: GpuArray;
106
+ readonly values: GpuArray;
107
+ };
108
+ topk(input: Operand, k: number, options?: {
109
+ readonly largest?: boolean;
110
+ }): {
111
+ readonly values: GpuArray;
112
+ readonly indices: GpuArray<'u32'>;
113
+ };
114
+ quantile(input: Operand, q: number | readonly number[]): GpuArray<'f32'>;
115
+ median(input: Operand): GpuArray<'f32'>;
116
+ unique(input: Operand, options?: {
117
+ readonly counts?: boolean;
118
+ } & WaitOptions): Promise<{
119
+ values: GpuArray;
120
+ counts?: GpuArray<'u32'>;
121
+ }>;
122
+ take(input: Operand, indices: Operand, options?: TakeOptions): GpuArray;
123
+ scatter<T extends DType>(target: GpuArray<T>, indices: Operand, values_: OperandLike, options?: {
124
+ readonly op?: 'set' | 'add' | 'min' | 'max';
125
+ }): GpuArray<T>;
126
+ bincount(input: Operand, options: {
127
+ readonly weights?: Operand;
128
+ readonly length: number;
129
+ }): GpuArray;
130
+ compact(input: Operand, mask: Operand): {
131
+ readonly values: GpuArray;
132
+ readonly count: GpuArray<'u32'>;
133
+ };
134
+ filter(input: Operand, mask: Operand, options?: WaitOptions): Promise<GpuArray>;
135
+ nonzero(input: Operand, options?: WaitOptions): Promise<GpuArray<'u32'>>;
136
+ histogram(input: Operand, options?: HistogramOptions): Histogram;
137
+ }
138
+ export {};
Binary file
@@ -0,0 +1,42 @@
1
+ import { Operand } from './expr.js';
2
+ import type { GpuArray } from './array.js';
3
+ import { type WaitOptions } from './context.js';
4
+ /** Dense decomposition options. Every wait observes signal. */
5
+ export interface DecompOptions extends WaitOptions {
6
+ /** Full orthogonal factors for QR/SVD. Default false (reduced factors). */
7
+ readonly fullMatrices?: boolean;
8
+ /** Maximum cyclic Jacobi sweeps for SVD/eigh. Default 100; range 1..1000. */
9
+ readonly maxSweeps?: number;
10
+ }
11
+ /** A = Q R. Q has orthonormal columns; R is upper trapezoidal. */
12
+ export interface QRResult {
13
+ readonly q: GpuArray<'f32'>;
14
+ readonly r: GpuArray<'f32'>;
15
+ }
16
+ /** A = U diag(s) Vh. Singular values are nonnegative and descending. */
17
+ export interface SVDResult {
18
+ readonly u: GpuArray<'f32'>;
19
+ readonly s: GpuArray<'f32'>;
20
+ readonly vh: GpuArray<'f32'>;
21
+ }
22
+ /** A V = V diag(values). Eigenvalues ascend; vectors are columns. */
23
+ export interface EigenResult {
24
+ readonly values: GpuArray<'f32'>;
25
+ readonly vectors: GpuArray<'f32'>;
26
+ }
27
+ /** Solve A X = b with partial-pivoted LU; leading matrix dimensions broadcast. 1-D b is a vector. */
28
+ export declare function solve(a: Operand, b: Operand, options?: DecompOptions): Promise<GpuArray<'f32'>>;
29
+ /** Inverse of every square matrix, using partial-pivoted LU. Singular matrices reject. */
30
+ export declare function inv(a: Operand, options?: DecompOptions): Promise<GpuArray<'f32'>>;
31
+ /** Determinant per square matrix. Singular matrices return zero; det(0x0) is one. */
32
+ export declare function det(a: Operand, options?: DecompOptions): Promise<GpuArray<'f32'>>;
33
+ /** Lower triangular L with A = L L^T. A must be real symmetric and positive definite. */
34
+ export declare function cholesky(a: Operand, options?: DecompOptions): Promise<GpuArray<'f32'>>;
35
+ /** Householder QR for square, tall, wide, rank-deficient and empty matrices. */
36
+ export declare function qr(a: Operand, options?: DecompOptions): Promise<QRResult>;
37
+ /** One-sided Jacobi SVD without forming A^T A. Reduced by default, full factors optional. */
38
+ export declare function svd(a: Operand, options?: DecompOptions): Promise<SVDResult>;
39
+ /** Symmetric Jacobi eigenvalues and orthonormal eigenvectors, sorted ascending. */
40
+ export declare function eigh(a: Operand, options?: DecompOptions): Promise<EigenResult>;
41
+ /** Symmetric eigenvalues sorted ascending. */
42
+ export declare function eigvalsh(a: Operand, options?: DecompOptions): Promise<GpuArray<'f32'>>;
package/dist/decomp.js ADDED
@@ -0,0 +1,158 @@
1
+ import { n as e, r as t, t as n } from "./errors-CDgOgzCd.js";
2
+ import { n as r } from "./context-C75sQQra.js";
3
+ import { n as i, r as a } from "./expr-DwFen60A.js";
4
+ //#region src/decomp.ts
5
+ async function o(e) {
6
+ r(e);
7
+ let t = new URL("./decomp-kernel.wasm?no-inline",
8
+ import.meta.url
9
+ );
10
+ try {
11
+ let n;
12
+ if (t.protocol === "file:") t.search = "", n = await (await import(
13
+ /* @vite-ignore */
14
+ /* webpackIgnore: true */
15
+ "node:fs/promises"
16
+ )).readFile(t, { signal: e });
17
+ else {
18
+ let r = await fetch(t, { signal: e });
19
+ if (!r.ok) throw s(`HTTP ${r.status}`);
20
+ n = new Uint8Array(await r.arrayBuffer());
21
+ }
22
+ r(e);
23
+ let { instance: i } = await WebAssembly.instantiate(n);
24
+ return r(e), i.exports;
25
+ } catch (t) {
26
+ throw r(e), t instanceof Error && t.name === "MargoError" ? t : s(t instanceof Error ? t.message : String(t), t);
27
+ }
28
+ }
29
+ function s(e, t) {
30
+ let r = n("failed", `Decomposition Wasm load failed: ${e}; serve decomp-kernel.wasm beside decomp.js and allow WebAssembly compilation (CSP 'wasm-unsafe-eval')`, "compute");
31
+ return t !== void 0 && Object.defineProperty(r, "cause", {
32
+ value: t,
33
+ configurable: !0,
34
+ writable: !0
35
+ }), r;
36
+ }
37
+ var c = (e) => e.reduce((e, t) => e * t, 1);
38
+ function l(n) {
39
+ if (!(n instanceof i) || n.ndim < 2) throw t("decomp needs an array [..., rows, columns]", "compute");
40
+ if (n.context.check(), n.shape.at(-1) > 4096 || n.shape.at(-2) > 4096) throw e("decomp matrix dimensions are limited to 4096", "compute");
41
+ }
42
+ function u(e, t, n) {
43
+ let r = 0, i = 1;
44
+ for (let a = t.length - 1; a >= 0; a--) {
45
+ let o = e % t[a];
46
+ e = Math.floor(e / t[a]);
47
+ let s = n[a - t.length + n.length] ?? 1;
48
+ s !== 1 && (r += o * i), i *= s;
49
+ }
50
+ return r;
51
+ }
52
+ async function d(s, d, f, p) {
53
+ if (r(f.signal), l(s), d === 0 && !(p instanceof i)) throw t("solve needs a compute array or expression as its RHS", "compute");
54
+ let m = s.context, h = s.shape.at(-2), g = s.shape.at(-1), _ = Math.min(h, g);
55
+ if ((d <= 3 || d === 6) && h !== g) throw e("solve, inv, det, cholesky and eigh need square matrices", "compute");
56
+ let v = f.fullMatrices ?? !1, y = f.maxSweeps ?? 100;
57
+ if (typeof v != "boolean" || !Number.isInteger(y) || y < 1 || y > 1e3) throw e("fullMatrices must be boolean; maxSweeps must be an integer in 1..1000", "compute");
58
+ let b = [...s.shape.slice(0, -2)], x = 0, S = !1;
59
+ if (p) {
60
+ if (!(p instanceof i) || p.context !== m || p.ndim === 0) throw t("solve operands must share a context; b needs at least one dimension", "compute");
61
+ if (S = p.ndim === 1, x = S ? 1 : p.shape.at(-1), (S ? p.shape[0] : p.shape.at(-2)) !== g) throw e("solve RHS rows must match A", "compute");
62
+ b = a(b, S ? [] : p.shape.slice(0, -2));
63
+ }
64
+ let C = v ? h : _, w = d === 0 ? [S ? [g] : [g, x]] : d === 1 || d === 3 ? [[g, g]] : d === 2 ? [[]] : d === 4 ? [[h, C], [C, g]] : d === 5 ? [
65
+ [h, v ? h : _],
66
+ [_],
67
+ [v ? g : _, g]
68
+ ] : [[g], [g, g]], T = w.map(c), E = T.reduce((e, t) => e + t, 0), D = c(b);
69
+ if (x > 4096 || h * g * 8 + h * h * 2 + g * g * 2 + g * x * 2 > 16777216 || D * E > 16777216) throw e("decomp exceeds its 16,777,216-element workspace/output limit (8mn + 2m^2 + 2n^2 + 2n rhs per matrix: square matrices up to 1182); use smaller blocks or the sparse solvers in @margoengine/compute/sparse", "compute");
70
+ let [O, k, A] = await Promise.all([
71
+ s.read({ signal: f.signal }),
72
+ p?.read({ signal: f.signal }),
73
+ o(f.signal)
74
+ ]), j = Float64Array.from(O), M = k ? Float64Array.from(k) : void 0, N = T.map((e) => new Float32Array(D * e));
75
+ try {
76
+ for (let t = 0; t < D && E > 0; t++) {
77
+ t > 0 && t % 16 == 0 && await new Promise((e) => setTimeout(e, 0)), r(f.signal), m.check();
78
+ let i = h * g, a = d === 0 ? g * x : 0, o = A.reserve(i + a + E);
79
+ if (!o) throw e("decomp workspace allocation rejected", "compute");
80
+ let c = new Float64Array(A.memory.buffer, o, i + a + E), l = u(t, b, s.shape.slice(0, -2)) * i;
81
+ if (c.set(j.subarray(l, l + i)), M && p) {
82
+ let e = u(t, b, S ? [] : p.shape.slice(0, -2)) * a;
83
+ c.set(M.subarray(e, e + a), i);
84
+ }
85
+ let _ = A.run(d, h, g, x, Number(v), y);
86
+ if (_) throw n("failed", `Dense decomposition failed in batch ${t}: ${[
87
+ "",
88
+ "workspace limit",
89
+ "nonfinite input",
90
+ "matrix must be symmetric",
91
+ "singular matrix",
92
+ "matrix is not positive definite",
93
+ "Jacobi iteration did not converge",
94
+ "result overflow"
95
+ ][_] ?? _}`, "compute");
96
+ c = new Float64Array(A.memory.buffer, o, i + a + E);
97
+ let C = i + a;
98
+ T.forEach((e, r) => {
99
+ if (N[r].set(c.subarray(C, C + e), t * e), N[r].subarray(t * e, (t + 1) * e).some((e) => !Number.isFinite(e))) throw n("failed", "Dense decomposition result exceeds f32 range", "compute");
100
+ C += e;
101
+ });
102
+ }
103
+ r(f.signal), m.check();
104
+ let t = [];
105
+ try {
106
+ for (let e = 0; e < N.length; e++) t.push(m.array(N[e], {
107
+ shape: [...b, ...w[e]],
108
+ dtype: "f32"
109
+ }));
110
+ return t;
111
+ } catch (e) {
112
+ for (let e of t) e.dispose();
113
+ throw e;
114
+ }
115
+ } finally {
116
+ A.release();
117
+ }
118
+ }
119
+ async function f(e, t, n = {}) {
120
+ return (await d(e, 0, n, t))[0];
121
+ }
122
+ async function p(e, t = {}) {
123
+ return (await d(e, 1, t))[0];
124
+ }
125
+ async function m(e, t = {}) {
126
+ return (await d(e, 2, t))[0];
127
+ }
128
+ async function h(e, t = {}) {
129
+ return (await d(e, 3, t))[0];
130
+ }
131
+ async function g(e, t = {}) {
132
+ let [n, r] = await d(e, 4, t);
133
+ return {
134
+ q: n,
135
+ r
136
+ };
137
+ }
138
+ async function _(e, t = {}) {
139
+ let [n, r, i] = await d(e, 5, t);
140
+ return {
141
+ u: n,
142
+ s: r,
143
+ vh: i
144
+ };
145
+ }
146
+ async function v(e, t = {}) {
147
+ let [n, r] = await d(e, 6, t);
148
+ return {
149
+ values: n,
150
+ vectors: r
151
+ };
152
+ }
153
+ async function y(e, t = {}) {
154
+ let { values: n, vectors: r } = await v(e, t);
155
+ return r.dispose(), n;
156
+ }
157
+ //#endregion
158
+ export { h as cholesky, m as det, v as eigh, y as eigvalsh, p as inv, g as qr, f as solve, _ as svd };
@@ -0,0 +1,85 @@
1
+ /// <reference lib="esnext.disposable" preserve="true" />
2
+ import type { GpuArray } from './array.js';
3
+ import { Operand } from './expr.js';
4
+ import type { ComputeContext } from './context.js';
5
+ /** The nearest-seed value of a cell no seed reached (no seeds at all). */
6
+ export declare const NO_SEED = 4294967295;
7
+ /** The distance of a cell with no known seed: the largest finite f32, 3.4028234663852886e38. */
8
+ export declare const NO_DISTANCE = 3.4028234663852886e+38;
9
+ /** The pass lists of the jump flooding variants. `jfa+1` (the default) has the fewest errors per pass spent. */
10
+ export type FloodVariant = 'jfa' | '1+jfa' | 'jfa+1' | 'jfa+2';
11
+ /** Options for the flood functions. */
12
+ export interface FloodOptions {
13
+ /** Pass list: 'jfa' (log2 n passes, the most errors), 'jfa+1' (default), '1+jfa' or 'jfa+2'. */
14
+ readonly variant?: FloodVariant;
15
+ /** Cell size: distances are cell counts times this. Default 1. */
16
+ readonly spacing?: number;
17
+ /** Rejects with the signal's reason before the work is submitted (and, on the CPU backend, while it is read). */
18
+ readonly signal?: AbortSignal;
19
+ }
20
+ /** Options for `signedDistance`. */
21
+ export interface SignedOptions extends FloodOptions {
22
+ /** Where the zero set lies, in cells from a cell centre toward the other side. Default 0.5 (halfway between an inside and an outside cell); 0 measures centre to centre. */
23
+ readonly edge?: number;
24
+ }
25
+ /** A flooded field: nearest seed and distance per cell. Dispose both arrays (`using` does). */
26
+ export interface Flood {
27
+ /** Row-major index of each cell's nearest seed, or NO_SEED. */
28
+ readonly nearest: GpuArray<'u32'>;
29
+ /** Distance to that seed in cells times `spacing`, or NO_DISTANCE. */
30
+ readonly distance: GpuArray<'f32'>;
31
+ /** Number of flood passes run (the seeding and distance passes are not counted). */
32
+ readonly passes: number;
33
+ dispose(): void;
34
+ [Symbol.dispose](): void;
35
+ }
36
+ /**
37
+ * The step sizes of a variant for an area whose longest side is `longest` cells: n/2, ..., 1 where n is the next power
38
+ * of two, with a 1 first ('1+jfa'), a 1 last ('jfa+1') or a 2 and a 1 last ('jfa+2').
39
+ * @example jumpFloodSteps(8, 'jfa+1') // [4, 2, 1, 1]
40
+ */
41
+ export declare function jumpFloodSteps(longest: number, variant?: FloodVariant): number[];
42
+ /**
43
+ * Floods the nearest seed to every cell of a 2D (up to 4096 x 4096) or 3D (up to 512 per side, and as many cells as the
44
+ * device's storage binding allows) mask in log2(longest side) + 1 passes. A cell is a seed when its mask value is not
45
+ * 0. The result holds the row-major index of each cell's nearest seed and the distance to it.
46
+ * @example using f = await jumpFlood(mask); // f.distance is an f32 array shaped like the mask
47
+ */
48
+ export declare function jumpFlood(seeds: Operand, options?: FloodOptions): Promise<Flood>;
49
+ /** Distance from every cell to the nearest seed cell (nonzero mask value), in cells times `spacing`. */
50
+ export declare function distanceTransform(seeds: Operand, options?: FloodOptions): Promise<GpuArray<'f32'>>;
51
+ /**
52
+ * Signed distance of a mask: negative inside (nonzero cells), positive outside, the zero set `edge` (default half a
53
+ * cell) from the cell centres. Two floods, one from the inside cells and one from the outside cells.
54
+ */
55
+ export declare function signedDistance(mask: Operand, options?: SignedOptions): Promise<GpuArray<'f32'>>;
56
+ /** A Voronoi map: the nearest site of every cell, and the distance to it. */
57
+ export interface VoronoiMap {
58
+ /** Index of each cell's nearest site (its position in the `sites` list), or NO_SEED. */
59
+ readonly id: GpuArray<'u32'>;
60
+ /** Distance to that site's cell in cells times `spacing`, or NO_DISTANCE. */
61
+ readonly distance: GpuArray<'f32'>;
62
+ /** Flood passes run. */
63
+ readonly passes: number;
64
+ }
65
+ /**
66
+ * Voronoi map of point sites on a 2D or 3D grid of `shape` cells. Sites are flat cell coordinates `[x, y, x, y, ...]`
67
+ * (or x, y, z), rounded to the nearest cell; when two sites share a cell the lower index wins.
68
+ */
69
+ export declare function voronoiMap(ctx: ComputeContext, sites: ArrayLike<number>, shape: readonly number[], options?: FloodOptions): Promise<VoronoiMap>;
70
+ /** Options for `distanceTransformExact`. */
71
+ export interface ExactOptions {
72
+ /** Cell size. Default 1. */
73
+ readonly spacing?: number;
74
+ /** Signed: negative inside (nonzero cells), with the zero set `edge` cells from the centres. Default false. */
75
+ readonly signed?: boolean;
76
+ /** As `SignedOptions.edge`. Default 0.5. */
77
+ readonly edge?: number;
78
+ }
79
+ /**
80
+ * The exact distance transform on the CPU (Felzenszwalb and Huttenlocher, linear time per axis): distance from every cell
81
+ * of a row-major 2D or 3D `mask` (`shape` is [width, height] or [width, height, depth]; nonzero = seed) to the nearest
82
+ * seed. The oracle the flooded results are tested against, and the right tool below a few thousand cells.
83
+ * @example distanceTransformExact(new Uint8Array([1, 0, 0, 0, 0, 0]), [3, 2]) // [0, 1, 2, 1, 1.414, 2.236]
84
+ */
85
+ export declare function distanceTransformExact(mask: ArrayLike<number>, shape: readonly number[], options?: ExactOptions): Float32Array;