@margoengine/compute 0.0.0-stage → 1.0.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE +201 -0
- package/NOTICE +4 -0
- package/README.md +804 -2
- package/dist/array-C29noZq7.js +166 -0
- package/dist/array.d.ts +109 -0
- package/dist/autodiff.d.ts +22 -0
- package/dist/autodiff.js +143 -0
- package/dist/autotune.d.ts +100 -0
- package/dist/autotune.js +179 -0
- package/dist/compat-YK57ZCbA.js +4 -0
- package/dist/compat.d.ts +2 -0
- package/dist/context-CCvs3wkC.js +2479 -0
- package/dist/context.d.ts +376 -0
- package/dist/cpu-D4UQwJ9L.js +871 -0
- package/dist/cpu-kernel.wasm +0 -0
- package/dist/cpu-load-XFcM1TXj.js +5 -0
- package/dist/cpu-load.d.ts +3 -0
- package/dist/cpu-runtime.d.ts +8 -0
- package/dist/cpu-wasm.d.ts +42 -0
- package/dist/cpu-wasm.js +161 -0
- package/dist/cpu.d.ts +138 -0
- package/dist/decomp-kernel.wasm +0 -0
- package/dist/decomp.d.ts +42 -0
- package/dist/decomp.js +158 -0
- package/dist/distance.d.ts +85 -0
- package/dist/distance.js +256 -0
- package/dist/dtype.d.ts +36 -0
- package/dist/errors-CDgOgzCd.js +7 -0
- package/dist/expr-t3jm8acM.js +996 -0
- package/dist/expr.d.ts +196 -0
- package/dist/fft.d.ts +33 -0
- package/dist/fft.js +168 -0
- package/dist/frame.d.ts +76 -0
- package/dist/frame.js +85 -0
- package/dist/graph.d.ts +75 -0
- package/dist/graph.js +174 -0
- package/dist/histogram.d.ts +17 -0
- package/dist/index.d.ts +17 -0
- package/dist/index.js +4 -0
- package/dist/kernel.d.ts +65 -0
- package/dist/linalg.d.ts +21 -0
- package/dist/linalg.js +149 -0
- package/dist/nn-extra.d.ts +130 -0
- package/dist/nn-extra.js +322 -0
- package/dist/nn.d.ts +385 -0
- package/dist/nn.js +704 -0
- package/dist/onnx-image-D2qfYsXf.js +66 -0
- package/dist/onnx-image.d.ts +10 -0
- package/dist/onnx-kernel.wasm +0 -0
- package/dist/onnx-regex-DaesIdrm.js +331 -0
- package/dist/onnx-regex.d.ts +2 -0
- package/dist/onnx.d.ts +167 -0
- package/dist/onnx.js +885 -0
- package/dist/quant.d.ts +59 -0
- package/dist/quant.js +242 -0
- package/dist/random.d.ts +64 -0
- package/dist/random.js +150 -0
- package/dist/reduce.d.ts +34 -0
- package/dist/scan.d.ts +26 -0
- package/dist/select.d.ts +38 -0
- package/dist/shaders.d.ts +80 -0
- package/dist/shape.d.ts +23 -0
- package/dist/shape.js +134 -0
- package/dist/signal.d.ts +29 -0
- package/dist/signal.js +178 -0
- package/dist/sort.d.ts +38 -0
- package/dist/sparse.d.ts +136 -0
- package/dist/sparse.js +273 -0
- package/dist/stream.d.ts +39 -0
- package/dist/stream.js +100 -0
- package/dist/subgroups.d.ts +27 -0
- package/dist/subgroups.js +191 -0
- package/dist/usingCtx-igdMnAhr.js +57 -0
- package/dist/wgsl.d.ts +68 -0
- package/package.json +146 -4
package/dist/graph.js
ADDED
|
@@ -0,0 +1,174 @@
|
|
|
1
|
+
import { n as e, r as t } from "./errors-CDgOgzCd.js";
|
|
2
|
+
import { n } from "./context-CCvs3wkC.js";
|
|
3
|
+
import { a as r } from "./expr-t3jm8acM.js";
|
|
4
|
+
import { CsrMatrix as i, coo as a } from "./sparse.js";
|
|
5
|
+
import { t as o } from "./usingCtx-igdMnAhr.js";
|
|
6
|
+
//#region src/graph.ts
|
|
7
|
+
var s = 1 << 30;
|
|
8
|
+
function c(t, n) {
|
|
9
|
+
let { vertices: r, sources: i, targets: o, weights: c } = n, l = i?.length;
|
|
10
|
+
if (!Number.isInteger(r) || r < 0 || r >= s) throw e(`graph vertices must be a whole number below ${s}, got ${r}`, "compute");
|
|
11
|
+
if (o?.length !== l || c && c.length !== l) throw e(`graph needs sources, targets and weights of one length, got ${l}, ${o?.length}, ${c?.length}`, "compute");
|
|
12
|
+
let u = [], d = [], f = [];
|
|
13
|
+
for (let t = 0; t < l; t++) {
|
|
14
|
+
let a = i[t], s = o[t], l = c ? c[t] : 1;
|
|
15
|
+
if (!Number.isInteger(a) || a < 0 || a >= r || !Number.isInteger(s) || s < 0 || s >= r) throw e(`graph edge ${t} from ${a} to ${s} is outside the ${r} vertices`, "compute");
|
|
16
|
+
if (Number.isNaN(l)) throw e(`graph edge ${t} has a NaN weight`, "compute");
|
|
17
|
+
u.push(a), d.push(s), f.push(l), n.directed === !1 && (u.push(s), d.push(a), f.push(l));
|
|
18
|
+
}
|
|
19
|
+
let p = Array.from(u, (e, t) => t).sort((e, t) => u[e] - u[t] || d[e] - d[t] || f[e] - f[t]), m = [], h = [], g = [];
|
|
20
|
+
for (let e of p) {
|
|
21
|
+
let t = m.length - 1;
|
|
22
|
+
t >= 0 && m[t] === u[e] && h[t] === d[e] || (m.push(u[e]), h.push(d[e]), g.push(f[e]));
|
|
23
|
+
}
|
|
24
|
+
return a(t, {
|
|
25
|
+
rows: m,
|
|
26
|
+
cols: h,
|
|
27
|
+
values: g,
|
|
28
|
+
shape: [r, r]
|
|
29
|
+
});
|
|
30
|
+
}
|
|
31
|
+
function l(n) {
|
|
32
|
+
if (!(n instanceof i)) throw t("Graph algorithms take a CsrMatrix; make one with graph()", "compute");
|
|
33
|
+
if (n.shape[0] !== n.shape[1]) throw e(`A graph's matrix is square, got ${n.shape[0]} x ${n.shape[1]}`, "compute");
|
|
34
|
+
let r = n.rowIdx.astype("i32").eval(), a = n.colIdx.astype("i32").eval();
|
|
35
|
+
return {
|
|
36
|
+
from: r,
|
|
37
|
+
to: a,
|
|
38
|
+
dispose() {
|
|
39
|
+
r.dispose(), a.dispose();
|
|
40
|
+
}
|
|
41
|
+
};
|
|
42
|
+
}
|
|
43
|
+
var u = (t, n) => {
|
|
44
|
+
let r = typeof n == "number" ? [n] : n, i = t.shape[0];
|
|
45
|
+
if (!r?.length) throw e("Give at least one source vertex", "compute");
|
|
46
|
+
for (let t of r) if (!Number.isInteger(t) || t < 0 || t >= i) throw e(`Source vertex ${t} is outside the ${i} vertices`, "compute");
|
|
47
|
+
return r;
|
|
48
|
+
}, d = (t) => {
|
|
49
|
+
let n = t.checkEvery ?? 8;
|
|
50
|
+
if (!Number.isInteger(n) || n < 1) throw e(`checkEvery must be a whole number from 1, got ${n}`, "compute");
|
|
51
|
+
return n;
|
|
52
|
+
};
|
|
53
|
+
async function f(e, t, r, i) {
|
|
54
|
+
let a = d(i), s = 0;
|
|
55
|
+
for (; s < r;) try {
|
|
56
|
+
var c = o();
|
|
57
|
+
n(i.signal);
|
|
58
|
+
let l = c.u(e().eval());
|
|
59
|
+
for (let e = 0; e < a && s < r; e++, s++) t();
|
|
60
|
+
if (!await c.u(e().ne(l).sum()).item(i)) return {
|
|
61
|
+
rounds: s,
|
|
62
|
+
settled: !0
|
|
63
|
+
};
|
|
64
|
+
} catch (e) {
|
|
65
|
+
c.e = e;
|
|
66
|
+
} finally {
|
|
67
|
+
c.d();
|
|
68
|
+
}
|
|
69
|
+
return {
|
|
70
|
+
rounds: s,
|
|
71
|
+
settled: !1
|
|
72
|
+
};
|
|
73
|
+
}
|
|
74
|
+
function p(e, t, n, i, a, o) {
|
|
75
|
+
let c = e.array(new Int32Array(a).fill(s));
|
|
76
|
+
e.scatter(c, n, r(i, t, s), { op: "min" });
|
|
77
|
+
let l = r(c.eq(s), -1, c).eval();
|
|
78
|
+
c.dispose();
|
|
79
|
+
for (let e of o) l.write([-1], e);
|
|
80
|
+
return l;
|
|
81
|
+
}
|
|
82
|
+
async function m(e, t, n = {}) {
|
|
83
|
+
let i = l(e), { from: a, to: o } = i, c = e.context, d = e.shape[0], m = u(e, t), h = new Int32Array(d).fill(s);
|
|
84
|
+
for (let e of m) h[e] = 0;
|
|
85
|
+
let g = c.array(h), _ = () => {
|
|
86
|
+
let e = c.take(g, a);
|
|
87
|
+
c.scatter(g, o, e.add(1).minimum(s), { op: "min" }), e.dispose();
|
|
88
|
+
};
|
|
89
|
+
try {
|
|
90
|
+
let { rounds: t } = e.nnz ? await f(() => g, _, d, n) : { rounds: 0 }, i = c.take(g, a), l = c.take(g, o), u = i.lt(s).and(i.add(1).eq(l)).eval(), h = p(c, a, o, u, d, m), v = r(g.eq(s), -1, g).eval();
|
|
91
|
+
for (let e of [
|
|
92
|
+
i,
|
|
93
|
+
l,
|
|
94
|
+
u
|
|
95
|
+
]) e.dispose();
|
|
96
|
+
return {
|
|
97
|
+
distances: v,
|
|
98
|
+
predecessors: h,
|
|
99
|
+
iterations: t
|
|
100
|
+
};
|
|
101
|
+
} finally {
|
|
102
|
+
g.dispose(), i.dispose();
|
|
103
|
+
}
|
|
104
|
+
}
|
|
105
|
+
async function h(e, t, n = {}) {
|
|
106
|
+
let i = l(e), { from: a, to: o } = i, s = e.context, c = e.shape[0], d = u(e, t), m = new Float32Array(c).fill(Infinity);
|
|
107
|
+
for (let e of d) m[e] = 0;
|
|
108
|
+
let h = s.array(m), g = () => {
|
|
109
|
+
let t = s.take(h, a);
|
|
110
|
+
s.scatter(h, o, r(t.isfinite(), t.add(e.values), t), { op: "min" }), t.dispose();
|
|
111
|
+
};
|
|
112
|
+
try {
|
|
113
|
+
let t = 0, r = !1;
|
|
114
|
+
if (e.nnz) {
|
|
115
|
+
let e = await f(() => h, g, c, n);
|
|
116
|
+
if (t = e.rounds, !e.settled) {
|
|
117
|
+
let e = await f(() => h, g, 1, {
|
|
118
|
+
...n,
|
|
119
|
+
checkEvery: 1
|
|
120
|
+
});
|
|
121
|
+
t += e.rounds, r = !e.settled;
|
|
122
|
+
}
|
|
123
|
+
}
|
|
124
|
+
let i = s.take(h, a), l = s.take(h, o), u = i.isfinite().and(i.add(e.values).eq(l)).eval(), m = p(s, a, o, u, c, d);
|
|
125
|
+
for (let e of [
|
|
126
|
+
i,
|
|
127
|
+
l,
|
|
128
|
+
u
|
|
129
|
+
]) e.dispose();
|
|
130
|
+
return {
|
|
131
|
+
distances: h.eval(),
|
|
132
|
+
predecessors: m,
|
|
133
|
+
iterations: t,
|
|
134
|
+
negativeCycle: r
|
|
135
|
+
};
|
|
136
|
+
} finally {
|
|
137
|
+
h.dispose(), i.dispose();
|
|
138
|
+
}
|
|
139
|
+
}
|
|
140
|
+
async function g(e, t = {}) {
|
|
141
|
+
let n = l(e), { from: r, to: i } = n, a = e.context, s = e.shape[0];
|
|
142
|
+
if (!s) return n.dispose(), {
|
|
143
|
+
labels: a.zeros(0, "i32"),
|
|
144
|
+
count: 0,
|
|
145
|
+
iterations: 0
|
|
146
|
+
};
|
|
147
|
+
let c = a.arange(0, s, 1, "i32"), u = () => {
|
|
148
|
+
let e = a.take(c, r), t = a.take(c, i);
|
|
149
|
+
a.scatter(c, e, t, { op: "min" }), a.scatter(c, t, e, { op: "min" }), e.dispose(), t.dispose();
|
|
150
|
+
let n = a.take(c, c);
|
|
151
|
+
c.dispose(), c = n;
|
|
152
|
+
};
|
|
153
|
+
try {
|
|
154
|
+
try {
|
|
155
|
+
var d = o();
|
|
156
|
+
let n = 0;
|
|
157
|
+
e.nnz && ({rounds: n} = await f(() => c, u, Infinity, t));
|
|
158
|
+
let r = d.u(a.arange(0, s, 1, "i32")), i = d.u(c.eq(r).astype("i32").eval()), l = d.u(a.cumsum(i)), p = d.u(a.take(l, c)), m = await d.u(i.sum()).item(t);
|
|
159
|
+
return {
|
|
160
|
+
labels: p.sub(1).eval(),
|
|
161
|
+
count: m,
|
|
162
|
+
iterations: n
|
|
163
|
+
};
|
|
164
|
+
} catch (e) {
|
|
165
|
+
d.e = e;
|
|
166
|
+
} finally {
|
|
167
|
+
d.d();
|
|
168
|
+
}
|
|
169
|
+
} finally {
|
|
170
|
+
c.dispose(), n.dispose();
|
|
171
|
+
}
|
|
172
|
+
}
|
|
173
|
+
//#endregion
|
|
174
|
+
export { m as bfs, g as connectedComponents, c as graph, h as shortestPaths };
|
|
@@ -0,0 +1,17 @@
|
|
|
1
|
+
import type { GpuArray } from './array.js';
|
|
2
|
+
import { Operand } from './expr.js';
|
|
3
|
+
import type { ComputeContext } from './context.js';
|
|
4
|
+
/** Options for histograms. */
|
|
5
|
+
export interface HistogramOptions {
|
|
6
|
+
/** Number of equal bins. Default 64. */
|
|
7
|
+
readonly bins?: number;
|
|
8
|
+
/** Range [min, max] the bins cover; values outside are not counted. Default the data's own min and max. */
|
|
9
|
+
readonly range?: readonly [number, number];
|
|
10
|
+
}
|
|
11
|
+
/** A histogram: per-bin counts and the `bins + 1` bin edges, both on the GPU. */
|
|
12
|
+
export interface Histogram {
|
|
13
|
+
readonly counts: GpuArray<'u32'>;
|
|
14
|
+
readonly edges: GpuArray<'f32'>;
|
|
15
|
+
}
|
|
16
|
+
/** NumPy-style histogram (see ComputeContext.histogram). */
|
|
17
|
+
export declare function histogram(ctx: ComputeContext, input: Operand, options?: HistogramOptions): Histogram;
|
package/dist/index.d.ts
ADDED
|
@@ -0,0 +1,17 @@
|
|
|
1
|
+
/// <reference lib="esnext.disposable" preserve="true" />
|
|
2
|
+
export { createCompute, ComputeContext } from './context.js';
|
|
3
|
+
export type { ArrayOptions, BindingResource, ComputeTuning, CreateComputeOptions, PassTiming, WaitOptions, } from './context.js';
|
|
4
|
+
export { GpuArray } from './array.js';
|
|
5
|
+
export type { ReadOptions, SliceSpec } from './array.js';
|
|
6
|
+
export { Expr, Operand, where, broadcastShapes } from './expr.js';
|
|
7
|
+
export type { AxisOptions, OperandLike } from './expr.js';
|
|
8
|
+
export { Kernel, BoundKernel } from './kernel.js';
|
|
9
|
+
export type { RunOptions } from './kernel.js';
|
|
10
|
+
export type { DType, TypedArrayFor, Float16ArrayLike } from './dtype.js';
|
|
11
|
+
export type { ScanOptions } from './scan.js';
|
|
12
|
+
export type { SortOptions } from './sort.js';
|
|
13
|
+
export type { TakeOptions } from './select.js';
|
|
14
|
+
export type { Histogram, HistogramOptions } from './histogram.js';
|
|
15
|
+
export type { Operator } from './shaders.js';
|
|
16
|
+
export { reflectWGSL, encode } from './wgsl.js';
|
|
17
|
+
export type { BindingInfo, EntryPointInfo, HostValue, ModuleInfo, TypeLayout } from './wgsl.js';
|
package/dist/index.js
ADDED
|
@@ -0,0 +1,4 @@
|
|
|
1
|
+
import { a as e, d as t, i as n, r, t as i, u as a } from "./context-CCvs3wkC.js";
|
|
2
|
+
import { a as o, n as s, r as c, t as l } from "./expr-t3jm8acM.js";
|
|
3
|
+
import { t as u } from "./array-C29noZq7.js";
|
|
4
|
+
export { n as BoundKernel, i as ComputeContext, l as Expr, u as GpuArray, e as Kernel, s as Operand, c as broadcastShapes, r as createCompute, a as encode, t as reflectWGSL, o as where };
|
package/dist/kernel.d.ts
ADDED
|
@@ -0,0 +1,65 @@
|
|
|
1
|
+
import { GpuArray } from './array.js';
|
|
2
|
+
import type { BindingInfo } from './wgsl.js';
|
|
3
|
+
import type { BindingResource, ComputeContext, Program } from './context.js';
|
|
4
|
+
/** How many threads (`count`), workgroups, or an indirect argument buffer a kernel run dispatches. */
|
|
5
|
+
export interface RunOptions {
|
|
6
|
+
/** Threads to cover, up to three dimensions; rounded up to whole workgroups of the entry point's `@workgroup_size`. */
|
|
7
|
+
readonly count?: number | readonly [number, number?, number?];
|
|
8
|
+
/** Workgroups to dispatch, as `dispatchWorkgroups` takes them. */
|
|
9
|
+
readonly workgroups?: number | readonly [number, number?, number?];
|
|
10
|
+
/**
|
|
11
|
+
* Workgroup counts read on the GPU from three u32 at element `indirectOffset` of this array (an array with INDIRECT
|
|
12
|
+
* usage: create it with `kernel.indirectArgs()`), so a previous pass (a compaction, a culling count) sizes this one.
|
|
13
|
+
*/
|
|
14
|
+
readonly indirect?: GpuArray<'u32'> | GPUBuffer;
|
|
15
|
+
/** Element offset of the three counts in `indirect`. Default 0. */
|
|
16
|
+
readonly indirectOffset?: number;
|
|
17
|
+
}
|
|
18
|
+
/** A compiled WGSL compute kernel whose resources are bound by name. Create it with `gpu.kernel(code)`. */
|
|
19
|
+
export declare class Kernel {
|
|
20
|
+
#private;
|
|
21
|
+
/** The kernel's `@group @binding` resources, read from its source. */
|
|
22
|
+
readonly bindings: readonly BindingInfo[];
|
|
23
|
+
/** The entry point it runs. */
|
|
24
|
+
readonly entryPoint: string;
|
|
25
|
+
/** The entry point's `@workgroup_size`. */
|
|
26
|
+
readonly workgroupSize: readonly [number, number, number];
|
|
27
|
+
/** @internal Use `gpu.kernel(code)`. */
|
|
28
|
+
constructor(context: ComputeContext, program: Program);
|
|
29
|
+
/**
|
|
30
|
+
* Queues one dispatch. `resources` maps binding names to GpuArrays, GPU buffers, textures, samplers, bytes, or plain
|
|
31
|
+
* values for uniform structs (laid out from the WGSL declaration). Returns the kernel, so runs chain.
|
|
32
|
+
* @example kernel.run({ src, dst, params: { scale: 2, count: n } }, { count: n });
|
|
33
|
+
*/
|
|
34
|
+
run(resources: Readonly<Record<string, BindingResource>>, options: RunOptions): this;
|
|
35
|
+
/**
|
|
36
|
+
* Binds resources once for repeated runs: the bind groups and the buffers holding plain uniform values are kept, so
|
|
37
|
+
* each `run` (or `encode` into your own command encoder) is one dispatch. Change a uniform with `set`.
|
|
38
|
+
*/
|
|
39
|
+
bind(resources: Readonly<Record<string, BindingResource>>): BoundKernel;
|
|
40
|
+
/** A u32 array of `[x, y, z]` workgroup counts with INDIRECT usage, for `run({ indirect })`. */
|
|
41
|
+
indirectArgs(workgroups?: readonly [number, number, number]): GpuArray<'u32'>;
|
|
42
|
+
/** Releases the kernel. Running it afterwards throws a MargoError (`disposed`). */
|
|
43
|
+
dispose(): void;
|
|
44
|
+
/** Same as `dispose()`, for `using`. */
|
|
45
|
+
[Symbol.dispose](): void;
|
|
46
|
+
}
|
|
47
|
+
/** A kernel with its resources bound, for runs every frame. Create it with `kernel.bind(resources)`. */
|
|
48
|
+
export declare class BoundKernel {
|
|
49
|
+
#private;
|
|
50
|
+
/** @internal Use `kernel.bind(resources)`. */
|
|
51
|
+
constructor(context: ComputeContext, program: Program, resources: Readonly<Record<string, BindingResource>>);
|
|
52
|
+
/**
|
|
53
|
+
* Changes one binding. A plain uniform value of the same size is written into the existing buffer (no new bind
|
|
54
|
+
* group); anything else rebinds.
|
|
55
|
+
*/
|
|
56
|
+
set(name: string, value: BindingResource): this;
|
|
57
|
+
/** Records the dispatch into `encoder` (an engine frame's encoder, or your own). */
|
|
58
|
+
encode(encoder: GPUCommandEncoder | GPUComputePassEncoder, options: RunOptions): void;
|
|
59
|
+
/** Submits one dispatch. Returns this binding, so runs chain. */
|
|
60
|
+
run(options: RunOptions): this;
|
|
61
|
+
/** Frees the buffers holding plain values. */
|
|
62
|
+
dispose(): void;
|
|
63
|
+
/** Same as `dispose()`, for `using`. */
|
|
64
|
+
[Symbol.dispose](): void;
|
|
65
|
+
}
|
package/dist/linalg.d.ts
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
import { GpuArray } from './array.js';
|
|
2
|
+
import { type DType } from './dtype.js';
|
|
3
|
+
import { Operand, type Expr } from './expr.js';
|
|
4
|
+
/** WGSL for one batched tiled matrix product: c = a @ b with strided operands. */
|
|
5
|
+
export declare function matmulShader(a: DType, b: DType, out: DType): string;
|
|
6
|
+
/**
|
|
7
|
+
* Matrix product `a @ b` with NumPy's `matmul` rules: the last two dimensions multiply ([.., m, k] @ [.., k, n] gives
|
|
8
|
+
* [.., m, n]), leading dimensions broadcast as a batch, and a 1-D operand acts as a row (left) or column (right) whose
|
|
9
|
+
* dimension is dropped from the result. Floats accumulate in f32, integers in their own type.
|
|
10
|
+
* @example const c = matmul(a, b); const batched = matmul(stackOf10, w); const xtx = matmul(x.T, x);
|
|
11
|
+
*/
|
|
12
|
+
export declare function matmul(a: Operand, b: Operand): GpuArray;
|
|
13
|
+
/** Dot product of two 1-D arrays (shape `[]`), or `matmul` for higher dimensions. */
|
|
14
|
+
export declare function dot(a: Operand, b: Operand): GpuArray;
|
|
15
|
+
/** Outer product of two 1-D arrays: a lazy expression of shape [a.size, b.size]. */
|
|
16
|
+
export declare function outer(a: GpuArray, b: GpuArray): Expr;
|
|
17
|
+
/** Euclidean (L2) norm of every element, or along `axis`, in f32. */
|
|
18
|
+
export declare function norm(x: Operand, options?: {
|
|
19
|
+
readonly axis?: number | readonly number[];
|
|
20
|
+
readonly keepdims?: boolean;
|
|
21
|
+
}): GpuArray;
|
package/dist/linalg.js
ADDED
|
@@ -0,0 +1,149 @@
|
|
|
1
|
+
import { n as e, r as t } from "./errors-CDgOgzCd.js";
|
|
2
|
+
import { m as n, n as r, p as i, r as a } from "./expr-t3jm8acM.js";
|
|
3
|
+
import { t as o } from "./array-C29noZq7.js";
|
|
4
|
+
//#region src/linalg.ts
|
|
5
|
+
var s = 64;
|
|
6
|
+
function c(e, t, n) {
|
|
7
|
+
let r = i(n) ? "f32" : n;
|
|
8
|
+
return `${e === "f16" || t === "f16" || n === "f16" ? "enable f16;\n" : ""}struct Shape { m: u32, n: u32, k: u32, pad: u32, aOffset: u32, aBatch: u32, aRow: u32, aCol: u32, bOffset: u32, bBatch: u32, bRow: u32, bCol: u32 }
|
|
9
|
+
@group(0) @binding(0) var<storage, read> left: array<${e}>;
|
|
10
|
+
@group(0) @binding(1) var<storage, read> right: array<${t}>;
|
|
11
|
+
@group(0) @binding(2) var<storage, read_write> product: array<${n}>;
|
|
12
|
+
@group(0) @binding(3) var<uniform> shape: Shape;
|
|
13
|
+
var<workgroup> tileA: array<array<${r}, 64>, 16>;
|
|
14
|
+
var<workgroup> tileB: array<array<${r}, 64>, 16>;
|
|
15
|
+
@compute @workgroup_size(16, 16)
|
|
16
|
+
fn main(@builtin(workgroup_id) wid: vec3u, @builtin(local_invocation_id) lid: vec3u) {
|
|
17
|
+
let batch = wid.z;
|
|
18
|
+
let row0 = wid.y * 64u;
|
|
19
|
+
let col0 = wid.x * 64u;
|
|
20
|
+
let thread = lid.y * 16u + lid.x;
|
|
21
|
+
var acc: array<${r}, 16>;
|
|
22
|
+
for (var k0 = 0u; k0 < shape.k; k0 += 16u) {
|
|
23
|
+
for (var l = 0u; l < 4u; l++) {
|
|
24
|
+
let e = thread + l * 256u;
|
|
25
|
+
let am = e / 16u;
|
|
26
|
+
let ak = e % 16u;
|
|
27
|
+
var va: ${r} = ${r}(0);
|
|
28
|
+
if (row0 + am < shape.m && k0 + ak < shape.k) {
|
|
29
|
+
va = ${r}(left[shape.aOffset + batch * shape.aBatch + (row0 + am) * shape.aRow + (k0 + ak) * shape.aCol]);
|
|
30
|
+
}
|
|
31
|
+
tileA[ak][am] = va;
|
|
32
|
+
let bk = e / 64u;
|
|
33
|
+
let bn = e % 64u;
|
|
34
|
+
var vb: ${r} = ${r}(0);
|
|
35
|
+
if (k0 + bk < shape.k && col0 + bn < shape.n) {
|
|
36
|
+
vb = ${r}(right[shape.bOffset + batch * shape.bBatch + (k0 + bk) * shape.bRow + (col0 + bn) * shape.bCol]);
|
|
37
|
+
}
|
|
38
|
+
tileB[bk][bn] = vb;
|
|
39
|
+
}
|
|
40
|
+
workgroupBarrier();
|
|
41
|
+
for (var kk = 0u; kk < 16u; kk++) {
|
|
42
|
+
var ra: array<${r}, 4>;
|
|
43
|
+
var rb: array<${r}, 4>;
|
|
44
|
+
for (var i = 0u; i < 4u; i++) { ra[i] = tileA[kk][lid.y * 4u + i]; rb[i] = tileB[kk][lid.x * 4u + i]; }
|
|
45
|
+
for (var i = 0u; i < 4u; i++) {
|
|
46
|
+
for (var j = 0u; j < 4u; j++) { acc[i * 4u + j] += ra[i] * rb[j]; }
|
|
47
|
+
}
|
|
48
|
+
}
|
|
49
|
+
workgroupBarrier();
|
|
50
|
+
}
|
|
51
|
+
for (var i = 0u; i < 4u; i++) {
|
|
52
|
+
let r = row0 + lid.y * 4u + i;
|
|
53
|
+
for (var j = 0u; j < 4u; j++) {
|
|
54
|
+
let c = col0 + lid.x * 4u + j;
|
|
55
|
+
if (r < shape.m && c < shape.n) { product[(batch * shape.m + r) * shape.n + c] = ${n}(acc[i * 4u + j]); }
|
|
56
|
+
}
|
|
57
|
+
}
|
|
58
|
+
}`;
|
|
59
|
+
}
|
|
60
|
+
function l(e, t) {
|
|
61
|
+
let n = t.length, r = e.ndim - 2, i = [];
|
|
62
|
+
for (let t = 0; t < n; t++) {
|
|
63
|
+
let a = t - (n - r);
|
|
64
|
+
i.push(a < 0 || e.shape[a] === 1 ? 0 : e.strides[a]);
|
|
65
|
+
}
|
|
66
|
+
if (i.every((e) => e === 0)) return 0;
|
|
67
|
+
for (let e = 0; e < n - 1; e++) if (i[e] !== i[e + 1] * t[e + 1]) return;
|
|
68
|
+
return i[n - 1] ?? 0;
|
|
69
|
+
}
|
|
70
|
+
function u(i, u) {
|
|
71
|
+
if (!(i instanceof r) || !(u instanceof r)) throw t("matmul takes two GpuArrays or Exprs", "compute");
|
|
72
|
+
if (i.context !== u.context) throw t("matmul operands belong to different compute contexts", "compute");
|
|
73
|
+
if (i.ndim === 0 || u.ndim === 0) throw e("matmul needs arrays of at least one dimension; use mul for scalars", "compute");
|
|
74
|
+
let d = i.context;
|
|
75
|
+
d.check();
|
|
76
|
+
let f = [], p = (e) => {
|
|
77
|
+
if (e instanceof o) return e;
|
|
78
|
+
let t = e.eval();
|
|
79
|
+
return f.push(t), t;
|
|
80
|
+
}, m = p(i), h = p(u), g = m.ndim === 1, _ = h.ndim === 1;
|
|
81
|
+
g && (m = m.reshape(1, m.size)), _ && (h = h.reshape(h.size, 1));
|
|
82
|
+
let [v, y] = m.shape.slice(-2), [b, x] = h.shape.slice(-2);
|
|
83
|
+
if (y !== b) throw e(`matmul shapes [${i.shape.join(", ")}] and [${u.shape.join(", ")}] differ in the inner dimension (${y} vs ${b})`, "compute");
|
|
84
|
+
let S = a(m.shape.slice(0, -2), h.shape.slice(0, -2)), C = S.reduce((e, t) => e * t, 1), w = l(m, S), T = l(h, S);
|
|
85
|
+
w === void 0 && (m = m.broadcastTo([
|
|
86
|
+
...S,
|
|
87
|
+
v,
|
|
88
|
+
y
|
|
89
|
+
]).eval(), f.push(m), w = v * y), T === void 0 && (h = h.broadcastTo([
|
|
90
|
+
...S,
|
|
91
|
+
y,
|
|
92
|
+
x
|
|
93
|
+
]).eval(), f.push(h), T = y * x);
|
|
94
|
+
let E = n(m.dtype, h.dtype), D = [
|
|
95
|
+
...S,
|
|
96
|
+
...g ? [] : [v],
|
|
97
|
+
..._ ? [] : [x]
|
|
98
|
+
], O = d.empty(D, E);
|
|
99
|
+
if (C > d.device.limits.maxComputeWorkgroupsPerDimension) throw e(`matmul batch of ${C} is over the device's ${d.device.limits.maxComputeWorkgroupsPerDimension}; split the batch`, "compute");
|
|
100
|
+
if (O.size > 0) {
|
|
101
|
+
m.check(d), h.check(d);
|
|
102
|
+
let e = m.ndim, t = h.ndim;
|
|
103
|
+
d.submit([{
|
|
104
|
+
program: d.program(c(m.dtype, h.dtype, E), void 0, "matmul"),
|
|
105
|
+
resources: {
|
|
106
|
+
left: { buffer: m.buffer },
|
|
107
|
+
right: { buffer: h.buffer },
|
|
108
|
+
product: O,
|
|
109
|
+
shape: new Uint32Array([
|
|
110
|
+
v,
|
|
111
|
+
x,
|
|
112
|
+
y,
|
|
113
|
+
0,
|
|
114
|
+
m.offset,
|
|
115
|
+
w,
|
|
116
|
+
m.strides[e - 2],
|
|
117
|
+
m.strides[e - 1],
|
|
118
|
+
h.offset,
|
|
119
|
+
T,
|
|
120
|
+
h.strides[t - 2],
|
|
121
|
+
h.strides[t - 1]
|
|
122
|
+
])
|
|
123
|
+
},
|
|
124
|
+
workgroups: [
|
|
125
|
+
Math.ceil(x / s),
|
|
126
|
+
Math.ceil(v / s),
|
|
127
|
+
C
|
|
128
|
+
]
|
|
129
|
+
}]);
|
|
130
|
+
}
|
|
131
|
+
for (let e of f) e.dispose();
|
|
132
|
+
return O;
|
|
133
|
+
}
|
|
134
|
+
function d(t, n) {
|
|
135
|
+
if (t.ndim === 1 && n.ndim === 1) {
|
|
136
|
+
if (t.size !== n.size) throw e(`dot of vectors of ${t.size} and ${n.size} elements`, "compute");
|
|
137
|
+
return t.mul(n).sum();
|
|
138
|
+
}
|
|
139
|
+
return u(t, n);
|
|
140
|
+
}
|
|
141
|
+
function f(e, t) {
|
|
142
|
+
return e.reshape(e.size, 1).mul(t.reshape(1, t.size));
|
|
143
|
+
}
|
|
144
|
+
function p(e, t = {}) {
|
|
145
|
+
let n = e.astype("f32").square().sum(t), r = n.sqrt().eval();
|
|
146
|
+
return n.dispose(), r;
|
|
147
|
+
}
|
|
148
|
+
//#endregion
|
|
149
|
+
export { d as dot, u as matmul, c as matmulShader, p as norm, f as outer };
|
|
@@ -0,0 +1,130 @@
|
|
|
1
|
+
/// <reference lib="esnext.disposable" preserve="true" />
|
|
2
|
+
import { Tensor, Module, type InitOptions } from './nn.js';
|
|
3
|
+
import { Random } from './random.js';
|
|
4
|
+
import type { GpuArray } from './array.js';
|
|
5
|
+
import type { ComputeContext, WaitOptions } from './context.js';
|
|
6
|
+
type Pair = readonly [number, number];
|
|
7
|
+
/** Channel normalization options; affine defaults true and eps defaults 1e-5. */
|
|
8
|
+
export interface NormOptions {
|
|
9
|
+
/** Numerical stabilizer. Default 1e-5; positive and finite. */
|
|
10
|
+
readonly eps?: number;
|
|
11
|
+
/** Learn channel scale and shift. Default true. */
|
|
12
|
+
readonly affine?: boolean;
|
|
13
|
+
}
|
|
14
|
+
/** Batch normalization options. */
|
|
15
|
+
export interface BatchNormOptions extends NormOptions {
|
|
16
|
+
/** Contribution of a new batch. Default 0.1; null uses a cumulative average. */
|
|
17
|
+
readonly momentum?: number | null;
|
|
18
|
+
/** Track buffers for inference. Default true. */
|
|
19
|
+
readonly trackRunningStats?: boolean;
|
|
20
|
+
/** Channel axis. Default 1 (NCHW); accepts negative axes. */
|
|
21
|
+
readonly axis?: number;
|
|
22
|
+
}
|
|
23
|
+
/** Batch normalization of rank >=2, with differentiable batch statistics and unbiased running variance. */
|
|
24
|
+
export declare class BatchNorm extends Module {
|
|
25
|
+
#private;
|
|
26
|
+
/** Learned [channels] scale, initially one, when affine is enabled. */
|
|
27
|
+
readonly weight: Tensor | undefined;
|
|
28
|
+
/** Learned [channels] shift, initially zero, when affine is enabled. */
|
|
29
|
+
readonly bias: Tensor | undefined;
|
|
30
|
+
/** Inference mean, initially zero. */
|
|
31
|
+
readonly runningMean: GpuArray;
|
|
32
|
+
/** Inference variance, initially one. */
|
|
33
|
+
readonly runningVar: GpuArray;
|
|
34
|
+
/** Number of batches incorporated into running statistics. */
|
|
35
|
+
batchesTracked: number;
|
|
36
|
+
constructor(c: ComputeContext, channels: number, options?: BatchNormOptions);
|
|
37
|
+
forward(x: Tensor): Tensor;
|
|
38
|
+
stateDict(options?: WaitOptions): Promise<Record<string, Float32Array>>;
|
|
39
|
+
loadStateDict(state: Readonly<Record<string, ArrayLike<number>>>): void;
|
|
40
|
+
release(): void;
|
|
41
|
+
}
|
|
42
|
+
/** Per-sample group normalization of [batch, channels, ...spatial], with train/eval equivalence. */
|
|
43
|
+
export declare class GroupNorm extends Module {
|
|
44
|
+
#private;
|
|
45
|
+
/** Learned channel scale, initially one. */
|
|
46
|
+
readonly weight: Tensor | undefined;
|
|
47
|
+
/** Learned channel shift, initially zero. */
|
|
48
|
+
readonly bias: Tensor | undefined;
|
|
49
|
+
constructor(c: ComputeContext, groups: number, channels: number, options?: NormOptions);
|
|
50
|
+
forward(x: Tensor): Tensor;
|
|
51
|
+
}
|
|
52
|
+
/** Transposed 2D convolution options, with NCHW input and [in, out/groups, kh, kw] weights. */
|
|
53
|
+
export interface ConvTransposeOptions extends InitOptions {
|
|
54
|
+
/** Spatial stride. Default 1. */ readonly stride?: number | Pair;
|
|
55
|
+
/** Symmetric spatial padding. Default 0. */ readonly padding?: number | Pair;
|
|
56
|
+
/** Spacing between kernel taps. Default 1. */ readonly dilation?: number | Pair;
|
|
57
|
+
/** Additional high-side output pixels. Default 0, less than stride or dilation. */ readonly outputPadding?: number | Pair;
|
|
58
|
+
/** Independent channel groups. Default 1. */ readonly groups?: number;
|
|
59
|
+
/** Learn a bias. Default true. */ readonly bias?: boolean;
|
|
60
|
+
}
|
|
61
|
+
/** Differentiable grouped/dilated transposed convolution, including explicit output size. */
|
|
62
|
+
export declare class ConvTranspose2d extends Module {
|
|
63
|
+
#private;
|
|
64
|
+
/** [inChannels, outChannels/groups, kh, kw] parameters. */ readonly weight: Tensor;
|
|
65
|
+
/** Optional [outChannels] learned bias. */ readonly bias: Tensor | undefined;
|
|
66
|
+
constructor(c: ComputeContext, inChannels: number, outChannels: number, kernelSize: number | Pair, options?: ConvTransposeOptions);
|
|
67
|
+
forward(x: Tensor): Tensor;
|
|
68
|
+
/** Chooses a valid spatial output size instead of the configured output padding. */
|
|
69
|
+
withOutputSize(x: Tensor, outputSize?: Pair): Tensor;
|
|
70
|
+
}
|
|
71
|
+
/** Interpolation of one, two or three spatial axes after [batch, channels]. */
|
|
72
|
+
export interface UpsampleOptions {
|
|
73
|
+
/** Explicit spatial output dimensions, exclusive with scaleFactor. */ readonly size?: number | readonly number[];
|
|
74
|
+
/** Positive spatial scale factors. Default 2, exclusive with size. */ readonly scaleFactor?: number | readonly number[];
|
|
75
|
+
/** nearest, linear (1D/2D/3D), or bicubic (2D). Default nearest. */ readonly mode?: 'nearest' | 'linear' | 'bilinear' | 'trilinear' | 'bicubic';
|
|
76
|
+
/** Align the first and last pixel centers for linear/cubic interpolation. Default false. */ readonly alignCorners?: boolean;
|
|
77
|
+
}
|
|
78
|
+
/** Differentiable upsampling, including edge replication and half-pixel linear/cubic coordinates. */
|
|
79
|
+
export declare function upsample(x: Tensor, options?: UpsampleOptions): Tensor;
|
|
80
|
+
/** A reusable differentiable interpolation module. Options default to 2x nearest. */
|
|
81
|
+
export declare class Upsample extends Module {
|
|
82
|
+
#private;
|
|
83
|
+
constructor(options?: UpsampleOptions);
|
|
84
|
+
forward(x: Tensor): Tensor;
|
|
85
|
+
}
|
|
86
|
+
/** Recurrent layer options. */
|
|
87
|
+
export interface RecurrentOptions extends InitOptions {
|
|
88
|
+
/** Stacked recurrent layers. Default 1. */ readonly numLayers?: number;
|
|
89
|
+
/** Two directions with output channels concatenated. Default false. */ readonly bidirectional?: boolean;
|
|
90
|
+
/** [batch, time, features] input/output, rather than [time, batch, features]. Default false. */ readonly batchFirst?: boolean;
|
|
91
|
+
/** Learned input and recurrent biases. Default true. */ readonly bias?: boolean;
|
|
92
|
+
/** Dropout between stacked layers only. Default 0. */ readonly dropout?: number;
|
|
93
|
+
}
|
|
94
|
+
/** Optional recurrent state and padded-sequence lengths. */
|
|
95
|
+
export interface RecurrentState {
|
|
96
|
+
/** [layers * directions, batch, hidden]. Default zeros. */ readonly h?: Tensor;
|
|
97
|
+
/** LSTM cell state with the same shape. Default zeros. */ readonly c?: Tensor;
|
|
98
|
+
/** One integer length in [0,time] per batch item. Default full length. */ readonly lengths?: readonly number[];
|
|
99
|
+
}
|
|
100
|
+
/** Recurrent sequence and final states. Output order always matches input time order. */
|
|
101
|
+
export interface RecurrentResult {
|
|
102
|
+
/** [time,batch,directions*hidden], or batch-first when configured. */ readonly output: Tensor;
|
|
103
|
+
/** Final state [layers*directions,batch,hidden]. */ readonly h: Tensor;
|
|
104
|
+
/** Final LSTM cell state; undefined for GRU. */ readonly c?: Tensor;
|
|
105
|
+
}
|
|
106
|
+
declare class Cell extends Module {
|
|
107
|
+
readonly weightIH: Tensor;
|
|
108
|
+
readonly weightHH: Tensor;
|
|
109
|
+
readonly biasIH: Tensor | undefined;
|
|
110
|
+
readonly biasHH: Tensor | undefined;
|
|
111
|
+
constructor(ctx: ComputeContext, input: number, hidden: number, gates: number, bias: boolean, rng: Random);
|
|
112
|
+
forward(x: Tensor): Tensor;
|
|
113
|
+
}
|
|
114
|
+
declare abstract class Recurrent extends Module {
|
|
115
|
+
#private;
|
|
116
|
+
/** Per-layer/per-direction input, recurrent and bias parameters, in layer-major order. */ readonly cells: Cell[];
|
|
117
|
+
constructor(ctx: ComputeContext, inputSize: number, hiddenSize: number, options: RecurrentOptions, lstm: boolean);
|
|
118
|
+
forward(x: Tensor): Tensor;
|
|
119
|
+
/** Runs a complete sequence and exposes final states, without retaining mutable hidden state in the module. */
|
|
120
|
+
run(input: Tensor, state?: RecurrentState): RecurrentResult;
|
|
121
|
+
}
|
|
122
|
+
/** Stacked/bidirectional LSTM with i,f,g,o gates, trainable biases and full backpropagation through time. */
|
|
123
|
+
export declare class LSTM extends Recurrent {
|
|
124
|
+
constructor(c: ComputeContext, inputSize: number, hiddenSize: number, options?: RecurrentOptions);
|
|
125
|
+
}
|
|
126
|
+
/** Stacked/bidirectional GRU with r,z,n gates and reset applied after recurrent candidate projection. */
|
|
127
|
+
export declare class GRU extends Recurrent {
|
|
128
|
+
constructor(c: ComputeContext, inputSize: number, hiddenSize: number, options?: RecurrentOptions);
|
|
129
|
+
}
|
|
130
|
+
export {};
|