@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
|
@@ -0,0 +1,166 @@
|
|
|
1
|
+
import { n as e, r as t, t as n } from "./errors-CDgOgzCd.js";
|
|
2
|
+
import { c as r, h as i, n as a, u as o } from "./expr-t3jm8acM.js";
|
|
3
|
+
//#region src/array.ts
|
|
4
|
+
function s(e) {
|
|
5
|
+
let t = Array(e.length), n = 1;
|
|
6
|
+
for (let r = e.length - 1; r >= 0; r--) t[r] = n, n *= e[r];
|
|
7
|
+
return t;
|
|
8
|
+
}
|
|
9
|
+
function c(t, n = "Shape") {
|
|
10
|
+
if (!Array.isArray(t) || t.some((e) => !Number.isInteger(e) || e < 0)) throw e(`${n} must be whole numbers of at least 0, got [${String(t)}]`, "compute");
|
|
11
|
+
return [...t];
|
|
12
|
+
}
|
|
13
|
+
function l(t, n) {
|
|
14
|
+
if (!Number.isInteger(t) || t < -n || t >= Math.max(n, 1)) throw e(`Axis ${t} is out of range for ${n} dimensions`, "compute");
|
|
15
|
+
return t < 0 ? t + n : t;
|
|
16
|
+
}
|
|
17
|
+
var u = class u extends a {
|
|
18
|
+
#e = !1;
|
|
19
|
+
#t;
|
|
20
|
+
constructor(t, n, r, i, a = 0) {
|
|
21
|
+
if (super(), this.context = t, this.dtype = n, this.shape = Object.freeze(c(r)), i) {
|
|
22
|
+
this.storage = i.storage, this.strides = Object.freeze([...i.strides]), this.offset = i.offset, this.#t = !!i.owner;
|
|
23
|
+
return;
|
|
24
|
+
}
|
|
25
|
+
let l = this.size, u = l * o(n), d = t.device.limits.maxStorageBufferBindingSize;
|
|
26
|
+
if (u > d) throw e(`GpuArray of ${l} ${n} elements needs ${u} bytes, over this device's ${d}-byte storage binding limit; split the data or stream it`, "compute");
|
|
27
|
+
this.storage = {
|
|
28
|
+
buffer: t.allocate(Math.max(16, Math.ceil(u / 16) * 16), a, n),
|
|
29
|
+
dtype: n,
|
|
30
|
+
disposed: !1
|
|
31
|
+
}, this.strides = Object.freeze(s(this.shape)), this.offset = 0, this.#t = !0;
|
|
32
|
+
}
|
|
33
|
+
get buffer() {
|
|
34
|
+
return this.storage.buffer;
|
|
35
|
+
}
|
|
36
|
+
get byteLength() {
|
|
37
|
+
return this.size * o(this.dtype);
|
|
38
|
+
}
|
|
39
|
+
get contiguous() {
|
|
40
|
+
let e = s(this.shape);
|
|
41
|
+
return this.shape.every((t, n) => t === 1 || this.strides[n] === e[n]);
|
|
42
|
+
}
|
|
43
|
+
get disposed() {
|
|
44
|
+
return this.#e || this.storage.disposed;
|
|
45
|
+
}
|
|
46
|
+
get owner() {
|
|
47
|
+
return this.#t;
|
|
48
|
+
}
|
|
49
|
+
node() {
|
|
50
|
+
return {
|
|
51
|
+
kind: "leaf",
|
|
52
|
+
array: this
|
|
53
|
+
};
|
|
54
|
+
}
|
|
55
|
+
check(e) {
|
|
56
|
+
if (this.disposed) throw n("disposed", "GpuArray disposed; create a new array with gpu.array()", "compute");
|
|
57
|
+
if (e !== this.context) throw n("state", "GpuArray belongs to another compute context; create it with this context", "compute");
|
|
58
|
+
}
|
|
59
|
+
#n(e, t, n) {
|
|
60
|
+
return this.check(this.context), new u(this.context, this.dtype, e, {
|
|
61
|
+
storage: this.storage,
|
|
62
|
+
strides: t,
|
|
63
|
+
offset: n
|
|
64
|
+
});
|
|
65
|
+
}
|
|
66
|
+
reshape(...t) {
|
|
67
|
+
let n = t.length === 1 && Array.isArray(t[0]) ? t[0] : t, r = n.filter((e) => e !== -1).reduce((e, t) => e * t, 1);
|
|
68
|
+
if (n.filter((e) => e === -1).length > 1) throw e("reshape takes at most one -1 dimension", "compute");
|
|
69
|
+
let i = n.map((e) => e === -1 ? r ? this.size / r : 0 : e);
|
|
70
|
+
if (c(i), i.reduce((e, t) => e * t, 1) !== this.size) throw e(`Cannot reshape ${this.size} elements [${this.shape.join(", ")}] into [${n.join(", ")}]`, "compute");
|
|
71
|
+
let a = this.contiguous ? this : this.eval();
|
|
72
|
+
return a.#n(i, s(i), a.offset);
|
|
73
|
+
}
|
|
74
|
+
flatten() {
|
|
75
|
+
return this.reshape(this.size);
|
|
76
|
+
}
|
|
77
|
+
transpose(...t) {
|
|
78
|
+
let n = t.length ? t.map((e) => l(e, this.ndim)) : this.shape.map((e, t) => this.ndim - 1 - t);
|
|
79
|
+
if (n.length !== this.ndim || new Set(n).size !== this.ndim) throw e(`transpose needs a permutation of ${this.ndim} axes, got [${t.join(", ")}]`, "compute");
|
|
80
|
+
return this.#n(n.map((e) => this.shape[e]), n.map((e) => this.strides[e]), this.offset);
|
|
81
|
+
}
|
|
82
|
+
get T() {
|
|
83
|
+
return this.transpose();
|
|
84
|
+
}
|
|
85
|
+
slice(...t) {
|
|
86
|
+
if (t.length > this.ndim) throw e(`slice got ${t.length} specs for ${this.ndim} dimensions`, "compute");
|
|
87
|
+
let n = this.offset, r = [], i = [];
|
|
88
|
+
return this.shape.forEach((a, o) => {
|
|
89
|
+
let s = t[o] ?? null;
|
|
90
|
+
if (typeof s == "number") {
|
|
91
|
+
let t = s < 0 ? s + a : s;
|
|
92
|
+
if (!Number.isInteger(s) || t < 0 || t >= a) throw e(`Index ${s} is out of range for dimension ${o} of length ${a}`, "compute");
|
|
93
|
+
n += t * this.strides[o];
|
|
94
|
+
return;
|
|
95
|
+
}
|
|
96
|
+
let [c, l, u] = s ?? [], d = u ?? 1;
|
|
97
|
+
if (!Number.isInteger(d) || d === 0) throw e(`Slice step must be a non-zero integer, got ${d}`, "compute");
|
|
98
|
+
let f = (e, t) => {
|
|
99
|
+
if (e == null) return t;
|
|
100
|
+
let n = e < 0 ? e + a : e;
|
|
101
|
+
return d > 0 ? Math.min(Math.max(n, 0), a) : Math.min(Math.max(n, -1), a - 1);
|
|
102
|
+
}, p = f(c, d > 0 ? 0 : a - 1), m = f(l, d > 0 ? a : -1), h = Math.max(0, Math.ceil((m - p) / d));
|
|
103
|
+
h && (n += p * this.strides[o]), r.push(h), i.push(this.strides[o] * d);
|
|
104
|
+
}), this.#n(r, i, n);
|
|
105
|
+
}
|
|
106
|
+
expandDims(t) {
|
|
107
|
+
let n = t < 0 ? t + this.ndim + 1 : t;
|
|
108
|
+
if (!Number.isInteger(n) || n < 0 || n > this.ndim) throw e(`expandDims axis ${t} is out of range`, "compute");
|
|
109
|
+
let r = [...this.shape], i = [...this.strides];
|
|
110
|
+
return r.splice(n, 0, 1), i.splice(n, 0, 0), this.#n(r, i, this.offset);
|
|
111
|
+
}
|
|
112
|
+
squeeze(t) {
|
|
113
|
+
let n = t === void 0 ? this.shape.map((e) => e === 1) : this.shape.map((e, n) => n === l(t, this.ndim));
|
|
114
|
+
if (t !== void 0 && this.shape[l(t, this.ndim)] !== 1) throw e(`squeeze axis ${t} has length ${this.shape[l(t, this.ndim)]}, not 1`, "compute");
|
|
115
|
+
return this.#n(this.shape.filter((e, t) => !n[t]), this.strides.filter((e, t) => !n[t]), this.offset);
|
|
116
|
+
}
|
|
117
|
+
broadcastTo(t) {
|
|
118
|
+
c(t);
|
|
119
|
+
let n = t.length;
|
|
120
|
+
if (n < this.ndim) throw e(`Cannot broadcast [${this.shape.join(", ")}] to fewer dimensions`, "compute");
|
|
121
|
+
let r = t.map((r, i) => {
|
|
122
|
+
let a = i - (n - this.ndim);
|
|
123
|
+
if (a < 0) return 0;
|
|
124
|
+
if (this.shape[a] === r) return this.strides[a];
|
|
125
|
+
if (this.shape[a] === 1) return 0;
|
|
126
|
+
throw e(`Cannot broadcast [${this.shape.join(", ")}] to [${t.join(", ")}]`, "compute");
|
|
127
|
+
});
|
|
128
|
+
return this.#n(t, r, this.offset);
|
|
129
|
+
}
|
|
130
|
+
ascontiguous() {
|
|
131
|
+
return this.check(this.context), this.contiguous && this.offset === 0 ? this : this.eval();
|
|
132
|
+
}
|
|
133
|
+
transfer(t) {
|
|
134
|
+
if (!this.#t || !this.contiguous || this.offset) throw n("state", "Only a contiguous owning array can transfer its buffer", "compute");
|
|
135
|
+
if (c(t).reduce((e, t) => e * t, 1) !== this.size) throw e(`Cannot give ${this.size} elements the shape [${t.join(", ")}]`, "compute");
|
|
136
|
+
let r = new u(this.context, this.dtype, t, {
|
|
137
|
+
storage: this.storage,
|
|
138
|
+
strides: s(t),
|
|
139
|
+
offset: 0,
|
|
140
|
+
owner: !0
|
|
141
|
+
});
|
|
142
|
+
return this.#t = !1, this.#e = !0, this.context.forget(this), this.context.track(r), r;
|
|
143
|
+
}
|
|
144
|
+
write(n, r = 0) {
|
|
145
|
+
if (this.check(this.context), !this.contiguous) throw t("write needs a contiguous array; write to the array the view came from", "compute");
|
|
146
|
+
if (!Number.isInteger(r) || r < 0 || r + n.length > this.size) throw e(`GpuArray write of ${n.length} elements at ${r} does not fit ${this.size} elements`, "compute");
|
|
147
|
+
if (!n.length) return this;
|
|
148
|
+
let a = i(n, this.dtype), s = o(this.dtype), c = (this.offset + r) * s;
|
|
149
|
+
return c % 4 || a.byteLength % 4 ? this.context.writeUnaligned(this.storage.buffer, c, new Uint8Array(a.buffer, a.byteOffset, a.byteLength)) : this.context.device.queue.writeBuffer(this.storage.buffer, c, a), this;
|
|
150
|
+
}
|
|
151
|
+
async read(t = {}) {
|
|
152
|
+
if (this.check(this.context), !this.contiguous) return await super.read(t);
|
|
153
|
+
let n = t.offset ?? 0, i = t.length ?? this.size - n;
|
|
154
|
+
if (!Number.isInteger(n) || !Number.isInteger(i) || n < 0 || i < 0 || n + i > this.size) throw e(`GpuArray read of ${i} elements at ${n} is outside ${this.size} elements`, "compute");
|
|
155
|
+
let a = o(this.dtype), s = await this.context.readBytes(this.storage.buffer, (this.offset + n) * a, i * a, t.signal);
|
|
156
|
+
return new (r(this.dtype))(s);
|
|
157
|
+
}
|
|
158
|
+
dispose() {
|
|
159
|
+
this.#e || (this.#e = !0, this.#t && (this.storage.disposed = !0, this.storage.buffer.destroy(), this.context.forget(this)));
|
|
160
|
+
}
|
|
161
|
+
[Symbol.dispose]() {
|
|
162
|
+
this.dispose();
|
|
163
|
+
}
|
|
164
|
+
};
|
|
165
|
+
//#endregion
|
|
166
|
+
export { l as n, c as r, u as t };
|
package/dist/array.d.ts
ADDED
|
@@ -0,0 +1,109 @@
|
|
|
1
|
+
import { type DType, type TypedArrayFor } from './dtype.js';
|
|
2
|
+
import { Operand, type Node, type Storage } from './expr.js';
|
|
3
|
+
import type { ComputeContext } from './context.js';
|
|
4
|
+
/** Options for reading results back. */
|
|
5
|
+
export interface ReadOptions {
|
|
6
|
+
/** Abandons the read: the promise rejects with the signal's reason. */
|
|
7
|
+
readonly signal?: AbortSignal;
|
|
8
|
+
/** First element to read (C order). Default 0. */
|
|
9
|
+
readonly offset?: number;
|
|
10
|
+
/** Elements to read. Default the rest. */
|
|
11
|
+
readonly length?: number;
|
|
12
|
+
}
|
|
13
|
+
/** A slice of one dimension: an index (drops the dimension), `[start, stop, step?]` (negatives count from the end), or `null` for all. */
|
|
14
|
+
export type SliceSpec = number | null | readonly [number | null, (number | null)?, (number | null)?];
|
|
15
|
+
/** Checks a shape and returns it as a plain array. */
|
|
16
|
+
export declare function checkShape(shape: readonly number[], what?: string): number[];
|
|
17
|
+
/** Normalizes a possibly negative axis. */
|
|
18
|
+
export declare function axisOf(axis: number, ndim: number): number;
|
|
19
|
+
/**
|
|
20
|
+
* An N-dimensional typed array in GPU memory (`f32`, `f16`, `i32` or `u32`), NumPy style: a shape, strides and an
|
|
21
|
+
* offset into a buffer that views share. `reshape`, `transpose`, `slice` and `broadcastTo` return views without
|
|
22
|
+
* copying; element-wise methods (`add`, `mul`, `sqrt`, ...) return lazy expressions that run fused in one kernel;
|
|
23
|
+
* reductions (`sum`, `mean`, `argmax`, ...) run on the GPU and return arrays. `read()` brings values back.
|
|
24
|
+
*/
|
|
25
|
+
export declare class GpuArray<T extends DType = DType> extends Operand {
|
|
26
|
+
#private;
|
|
27
|
+
/** The context that owns this array. */
|
|
28
|
+
readonly context: ComputeContext;
|
|
29
|
+
/** Element type. */
|
|
30
|
+
readonly dtype: T;
|
|
31
|
+
/** The shared GPU memory. @internal */
|
|
32
|
+
readonly storage: Storage;
|
|
33
|
+
/** Dimensions, outermost first. */
|
|
34
|
+
readonly shape: readonly number[];
|
|
35
|
+
/** Element step per dimension (0 for a broadcast dimension). */
|
|
36
|
+
readonly strides: readonly number[];
|
|
37
|
+
/** First element's index in the buffer. */
|
|
38
|
+
readonly offset: number;
|
|
39
|
+
/** @internal Use `gpu.array()`, `gpu.zeros()` and friends. */
|
|
40
|
+
constructor(
|
|
41
|
+
/** The context that owns this array. */
|
|
42
|
+
context: ComputeContext,
|
|
43
|
+
/** Element type. */
|
|
44
|
+
dtype: T, shape: readonly number[], view?: {
|
|
45
|
+
storage: Storage;
|
|
46
|
+
strides: readonly number[];
|
|
47
|
+
offset: number;
|
|
48
|
+
owner?: boolean;
|
|
49
|
+
},
|
|
50
|
+
/** @internal Extra buffer usage flags (INDIRECT for dispatch arguments, VERTEX to draw from). */
|
|
51
|
+
usage?: number);
|
|
52
|
+
/** The GPU buffer holding the elements (STORAGE, COPY_SRC and COPY_DST usage), for binding in your own passes. */
|
|
53
|
+
get buffer(): GPUBuffer;
|
|
54
|
+
/** Size of the elements in bytes. */
|
|
55
|
+
get byteLength(): number;
|
|
56
|
+
/** True when the elements are packed in C order from `offset`. */
|
|
57
|
+
get contiguous(): boolean;
|
|
58
|
+
/** True after `dispose()`, the context's disposal or, for a view, the owning array's disposal. */
|
|
59
|
+
get disposed(): boolean;
|
|
60
|
+
/** True when this array owns its buffer (not a view). */
|
|
61
|
+
get owner(): boolean;
|
|
62
|
+
/** @internal */
|
|
63
|
+
node(): Node;
|
|
64
|
+
/** @internal Throws when this array cannot be used in `context`. */
|
|
65
|
+
check(context: ComputeContext): void;
|
|
66
|
+
/**
|
|
67
|
+
* The same elements with a new shape (one dimension may be -1 and is inferred). A view when the array is
|
|
68
|
+
* contiguous; otherwise the elements are copied first.
|
|
69
|
+
*/
|
|
70
|
+
reshape(...shape: (number | readonly number[])[]): GpuArray<T>;
|
|
71
|
+
/** A flat view (or copy, when not contiguous) of every element. */
|
|
72
|
+
flatten(): GpuArray<T>;
|
|
73
|
+
/** The dimensions permuted (default reversed): a view, no copy. */
|
|
74
|
+
transpose(...axes: number[]): GpuArray<T>;
|
|
75
|
+
/** The transpose (reversed dimensions), as NumPy's `.T`. */
|
|
76
|
+
get T(): GpuArray<T>;
|
|
77
|
+
/**
|
|
78
|
+
* A view of part of the array, one spec per leading dimension: an index (drops the dimension), `[start, stop,
|
|
79
|
+
* step]` with negatives counting from the end, or `null` for the whole dimension.
|
|
80
|
+
* @example m.slice(0) // first row
|
|
81
|
+
* @example m.slice(null, [0, 3]) // first three columns
|
|
82
|
+
* @example v.slice([null, null, -1]) // reversed
|
|
83
|
+
*/
|
|
84
|
+
slice(...specs: SliceSpec[]): GpuArray<T>;
|
|
85
|
+
/** A view with a length-1 dimension inserted at `axis`. */
|
|
86
|
+
expandDims(axis: number): GpuArray<T>;
|
|
87
|
+
/** A view without length-1 dimensions (or only `axis`). */
|
|
88
|
+
squeeze(axis?: number): GpuArray<T>;
|
|
89
|
+
/** A view broadcast to `shape` (NumPy rules): repeated dimensions read the same elements. */
|
|
90
|
+
broadcastTo(shape: readonly number[]): GpuArray<T>;
|
|
91
|
+
/** A contiguous array with these elements: this array when it already is, else a copy. */
|
|
92
|
+
ascontiguous(): GpuArray<T>;
|
|
93
|
+
/**
|
|
94
|
+
* @internal Moves this array's buffer to a new owning array of `shape` (same size, C order); this array is left
|
|
95
|
+
* disposed. Used to give results their final shape without a copy.
|
|
96
|
+
*/
|
|
97
|
+
transfer<S extends readonly number[]>(shape: S): GpuArray<T>;
|
|
98
|
+
/** Writes `data` (converted to this array's type) starting at flat element `offset`. Needs a contiguous array. */
|
|
99
|
+
write(data: ArrayLike<number>, offset?: number): this;
|
|
100
|
+
/**
|
|
101
|
+
* Copies the elements (C order) back to the CPU once every queued GPU operation is done. Rejects with a MargoError
|
|
102
|
+
* (`failed`) when queued work failed on the GPU, and with the signal's reason when aborted.
|
|
103
|
+
*/
|
|
104
|
+
read(options?: ReadOptions): Promise<TypedArrayFor[T]>;
|
|
105
|
+
/** Frees the GPU buffer (for a view, only the view). Using it afterwards throws a MargoError (`disposed`). */
|
|
106
|
+
dispose(): void;
|
|
107
|
+
/** Same as `dispose()`, for `using`. */
|
|
108
|
+
[Symbol.dispose](): void;
|
|
109
|
+
}
|
|
@@ -0,0 +1,22 @@
|
|
|
1
|
+
import { GpuArray } from './array.js';
|
|
2
|
+
import { Operand, type OperandLike } from './expr.js';
|
|
3
|
+
/** Options for {@link grad}. */
|
|
4
|
+
export interface GradOptions {
|
|
5
|
+
/** Weights of the output's elements (broadcast to its shape): the gradient is of sum(output * seed). Default 1. */
|
|
6
|
+
readonly seed?: OperandLike;
|
|
7
|
+
}
|
|
8
|
+
/**
|
|
9
|
+
* Gradients of sum(output * seed) with respect to each array in `wrt`, as f32 arrays of their shapes (zeros for an
|
|
10
|
+
* array the output does not read). `output` is an element-wise expression; the gradient flows through its
|
|
11
|
+
* arithmetic, maths and selections, through broadcasting and through views of the arrays. Rounding, comparisons and
|
|
12
|
+
* bit operations have no gradient.
|
|
13
|
+
* @example
|
|
14
|
+
* const loss = w.mul(x).add(b).sub(y).square(); // per sample
|
|
15
|
+
* const [dw, db] = grad(loss, [w, b]); // d(sum loss)/dw, d(sum loss)/db
|
|
16
|
+
*/
|
|
17
|
+
export declare function grad(output: Operand, wrt: readonly GpuArray[], options?: GradOptions): GpuArray<'f32'>[];
|
|
18
|
+
/** The value sum(output * seed) (shape []) and its gradients with respect to `wrt` (see {@link grad}). */
|
|
19
|
+
export declare function valueAndGrad(output: Operand, wrt: readonly GpuArray[], options?: GradOptions): {
|
|
20
|
+
value: GpuArray;
|
|
21
|
+
grads: GpuArray<'f32'>[];
|
|
22
|
+
};
|
package/dist/autodiff.js
ADDED
|
@@ -0,0 +1,143 @@
|
|
|
1
|
+
import { n as e, r as t } from "./errors-CDgOgzCd.js";
|
|
2
|
+
import { a as n, n as r, p as i, t as a } from "./expr-t3jm8acM.js";
|
|
3
|
+
import { t as o } from "./array-C29noZq7.js";
|
|
4
|
+
//#region src/autodiff.ts
|
|
5
|
+
var s = (e) => e.kind === "leaf" ? e.array.shape : e.kind === "scalar" ? [] : e.shape, c = (e) => e.kind === "leaf" ? e.array.dtype : e.dtype, l = (e, t) => typeof e == "number" ? typeof t == "number" ? e * t : e === 1 ? t : t.mul(e) : typeof t == "number" && t === 1 ? e : e.mul(t), u = (e) => typeof e == "number" ? -e : e.neg(), d = (e, t) => e === void 0 ? t : typeof e == "number" && typeof t == "number" ? e + t : typeof e == "number" ? t.add(e) : e.add(t), f = (e, t, r) => r ? n(e, 0, t) : n(e, t, 0);
|
|
6
|
+
function p(e, t) {
|
|
7
|
+
return t.kind === "leaf" ? t.array : t.kind === "scalar" ? t.value : new a(e, t);
|
|
8
|
+
}
|
|
9
|
+
function m(e, t, r) {
|
|
10
|
+
let o = t.args.map((t) => p(e, t)), s = o[0], [, d, m] = o, h = new a(e, t), g = (e) => typeof e == "number" ? e * e : e.square();
|
|
11
|
+
switch (t.op) {
|
|
12
|
+
case "add": return [r, r];
|
|
13
|
+
case "sub": return [r, u(r)];
|
|
14
|
+
case "mul": return [l(r, d), l(r, s)];
|
|
15
|
+
case "div": return [l(r, typeof d == "number" ? 1 / d : d.reciprocal()), l(u(r), h.div(d))];
|
|
16
|
+
case "pow": return [l(r, s.pow(typeof d == "number" ? d - 1 : d.sub(1)).mul(d)), l(r, n(s.gt(0), h.mul(s.log()), 0))];
|
|
17
|
+
case "minimum": return [f(s.le(d), r, !1), f(s.le(d), r, !0)];
|
|
18
|
+
case "maximum": return [f(s.ge(d), r, !1), f(s.ge(d), r, !0)];
|
|
19
|
+
case "clip": return [
|
|
20
|
+
f(s.ge(d).and(s.le(m)), r, !1),
|
|
21
|
+
f(s.lt(d), r, !1),
|
|
22
|
+
f(s.gt(m), r, !1)
|
|
23
|
+
];
|
|
24
|
+
case "atan2": {
|
|
25
|
+
let e = s.square().add(g(d));
|
|
26
|
+
return [l(r, e.reciprocal().mul(d)), l(u(r), s.div(e))];
|
|
27
|
+
}
|
|
28
|
+
case "hypot": return [l(r, n(h.eq(0), 0, s.div(h))), l(r, n(h.eq(0), 0, h.reciprocal().mul(d)))];
|
|
29
|
+
case "neg": return [u(r)];
|
|
30
|
+
case "abs": return [l(r, s.sign())];
|
|
31
|
+
case "square": return [l(r, s.mul(2))];
|
|
32
|
+
case "sqrt": return [l(r, h.reciprocal().mul(.5))];
|
|
33
|
+
case "rsqrt": return [l(r, h.mul(h).mul(h).mul(-.5))];
|
|
34
|
+
case "reciprocal": return [l(u(r), h.square())];
|
|
35
|
+
case "exp": return [l(r, h)];
|
|
36
|
+
case "exp2": return [l(r, h.mul(Math.LN2))];
|
|
37
|
+
case "expm1": return [l(r, h.add(1))];
|
|
38
|
+
case "log": return [l(r, s.reciprocal())];
|
|
39
|
+
case "log2": return [l(r, s.mul(Math.LN2).reciprocal())];
|
|
40
|
+
case "log1p": return [l(r, s.add(1).reciprocal())];
|
|
41
|
+
case "sin": return [l(r, s.cos())];
|
|
42
|
+
case "cos": return [l(u(r), s.sin())];
|
|
43
|
+
case "tan": return [l(r, h.square().add(1))];
|
|
44
|
+
case "asin": return [l(r, s.square().neg().add(1).rsqrt())];
|
|
45
|
+
case "acos": return [l(u(r), s.square().neg().add(1).rsqrt())];
|
|
46
|
+
case "atan": return [l(r, s.square().add(1).reciprocal())];
|
|
47
|
+
case "sinh": return [l(r, s.cosh())];
|
|
48
|
+
case "cosh": return [l(r, s.sinh())];
|
|
49
|
+
case "tanh": return [l(r, h.square().neg().add(1))];
|
|
50
|
+
case "degrees": return [l(r, 180 / Math.PI)];
|
|
51
|
+
case "radians": return [l(r, Math.PI / 180)];
|
|
52
|
+
case "astype": return [i(t.dtype) && i(c(t.args[0])) ? r : void 0];
|
|
53
|
+
case "where": return [
|
|
54
|
+
void 0,
|
|
55
|
+
f(s, r, !1),
|
|
56
|
+
f(s, r, !0)
|
|
57
|
+
];
|
|
58
|
+
default: return t.args.map(() => void 0);
|
|
59
|
+
}
|
|
60
|
+
}
|
|
61
|
+
var h = (e, t) => e.length === t.length && e.every((e, n) => e === t[n]);
|
|
62
|
+
function g(e, t, n, r, i) {
|
|
63
|
+
let a = typeof t == "number" ? [] : t.shape;
|
|
64
|
+
if (h(n, r) && (typeof t == "number" || h(a, r))) return t;
|
|
65
|
+
let o;
|
|
66
|
+
if (typeof t != "number" && h(a, n)) o = t;
|
|
67
|
+
else {
|
|
68
|
+
let r = e.zeros(n);
|
|
69
|
+
i.push(r), o = r.add(t);
|
|
70
|
+
}
|
|
71
|
+
if (h(n, r)) return o;
|
|
72
|
+
let s = n.length - r.length, c = n.map((e, t) => t).filter((e) => e < s || r[e - s] === 1 && n[e] !== 1), l = c.length ? o.sum({
|
|
73
|
+
axis: c,
|
|
74
|
+
keepdims: !0
|
|
75
|
+
}) : o.eval();
|
|
76
|
+
return i.push(l), l.reshape(r.length ? [...r] : []);
|
|
77
|
+
}
|
|
78
|
+
function _(e, n, a = {}) {
|
|
79
|
+
if (!(e instanceof r)) throw t("grad takes an output GpuArray or Expr", "compute");
|
|
80
|
+
if (!Array.isArray(n) || n.some((e) => !(e instanceof o))) throw t("grad takes the arrays to differentiate by as a list of GpuArrays", "compute");
|
|
81
|
+
let c = e.context;
|
|
82
|
+
c.check();
|
|
83
|
+
for (let e of n) if (e.check(c), !i(e.dtype)) throw t(`grad by an integer array (${e.dtype}) has no meaning; use f32`, "compute");
|
|
84
|
+
let l = a.seed ?? 1;
|
|
85
|
+
if (l instanceof r && l.context !== c) throw t("grad seed belongs to another compute context", "compute");
|
|
86
|
+
if (typeof l != "number" && !(l instanceof r)) throw t("grad seed must be a number, a GpuArray or an Expr", "compute");
|
|
87
|
+
let u = [], f = /* @__PURE__ */ new Set(), p = (e) => {
|
|
88
|
+
if (!f.has(e)) {
|
|
89
|
+
if (f.add(e), e.kind === "op") for (let t of e.args) p(t);
|
|
90
|
+
u.push(e);
|
|
91
|
+
}
|
|
92
|
+
}, h = e.node();
|
|
93
|
+
p(h);
|
|
94
|
+
let _ = /* @__PURE__ */ new Map([[h, l instanceof r ? l.astype("f32") : l]]), b = [], x = [];
|
|
95
|
+
h.kind === "leaf" && x.push({
|
|
96
|
+
array: h.array,
|
|
97
|
+
g: _.get(h),
|
|
98
|
+
from: e.shape
|
|
99
|
+
});
|
|
100
|
+
for (let e = u.length - 1; e >= 0; e--) {
|
|
101
|
+
let t = u[e], n = _.get(t);
|
|
102
|
+
n !== void 0 && t.kind === "op" && i(t.dtype) && m(c, t, n).forEach((e, n) => {
|
|
103
|
+
if (e === void 0) return;
|
|
104
|
+
let r = t.args[n];
|
|
105
|
+
r.kind === "leaf" ? x.push({
|
|
106
|
+
array: r.array,
|
|
107
|
+
g: e,
|
|
108
|
+
from: t.shape
|
|
109
|
+
}) : r.kind === "op" && _.set(r, d(_.get(r), g(c, e, t.shape, s(r), b)));
|
|
110
|
+
});
|
|
111
|
+
}
|
|
112
|
+
let S = n.map((e) => {
|
|
113
|
+
let t;
|
|
114
|
+
for (let { array: n, g: r, from: a } of x) {
|
|
115
|
+
if (n !== e && n.storage !== e.storage || !i(n.dtype)) continue;
|
|
116
|
+
let o = g(c, r, a, n.shape, b), s = n === e ? typeof o == "number" ? c.full(e.shape, o) : o.astype("f32").eval() : y(c, o, n, e);
|
|
117
|
+
t = t ? v(t, s) : s;
|
|
118
|
+
}
|
|
119
|
+
return t ?? c.zeros(e.shape);
|
|
120
|
+
});
|
|
121
|
+
for (let e of b) e.dispose();
|
|
122
|
+
return S;
|
|
123
|
+
}
|
|
124
|
+
var v = (e, t) => {
|
|
125
|
+
let n = e.add(t).eval();
|
|
126
|
+
return e.dispose(), t.dispose(), n;
|
|
127
|
+
};
|
|
128
|
+
function y(t, n, r, i) {
|
|
129
|
+
if (!i.contiguous || i.offset !== 0) throw e("grad by a view is not supported; pass the array the views came from", "compute");
|
|
130
|
+
let a = t.arange(0, r.size, 1, "i32"), o = r.shape, s = a.mul(0).add(r.offset), c = 1;
|
|
131
|
+
for (let e = o.length - 1; e >= 0; e--) o[e] > 1 && r.strides[e] !== 0 && (s = s.add(a.floorDiv(c).mod(o[e]).mul(r.strides[e]))), c *= o[e];
|
|
132
|
+
let l = typeof n == "number" ? void 0 : n.astype("f32").eval(), u = t.zeros([i.size]);
|
|
133
|
+
return t.scatter(u, s, l ? l.reshape(r.size) : n, { op: "add" }), l?.dispose(), a.dispose(), u.transfer([...i.shape]);
|
|
134
|
+
}
|
|
135
|
+
function b(e, t, n = {}) {
|
|
136
|
+
let r = n.seed ?? 1;
|
|
137
|
+
return {
|
|
138
|
+
value: (typeof r == "number" && r === 1 ? e : e.mul(r)).sum(),
|
|
139
|
+
grads: _(e, t, n)
|
|
140
|
+
};
|
|
141
|
+
}
|
|
142
|
+
//#endregion
|
|
143
|
+
export { _ as grad, b as valueAndGrad };
|
|
@@ -0,0 +1,100 @@
|
|
|
1
|
+
import { type ComputeContext, type ComputeTuning, type WaitOptions } from './context.js';
|
|
2
|
+
import type { Kernel } from './kernel.js';
|
|
3
|
+
/** A workgroup size as WGSL declares it: x, y, z. In a template string it reads `64,1,1`. */
|
|
4
|
+
export type WorkgroupSize = readonly [number, number, number];
|
|
5
|
+
/** Remembers results across sessions: `localStorage` fits, and so does anything with these two methods, async or not. */
|
|
6
|
+
export interface AutotuneStore {
|
|
7
|
+
/** The value stored under `key`, or null. */
|
|
8
|
+
getItem(key: string): string | null | undefined | Promise<string | null | undefined>;
|
|
9
|
+
/** Stores `value` under `key`. */
|
|
10
|
+
setItem(key: string, value: string): unknown;
|
|
11
|
+
}
|
|
12
|
+
/** What {@link autotune} measures. */
|
|
13
|
+
export interface AutotuneOptions extends WaitOptions {
|
|
14
|
+
/** Names the kernel in the cache. */
|
|
15
|
+
readonly name: string;
|
|
16
|
+
/** The kernel's WGSL at a size: put `@workgroup_size(${size})` in it. */
|
|
17
|
+
readonly source: (size: WorkgroupSize) => string;
|
|
18
|
+
/** Runs the kernel once as the real work would; make the inputs the size the real work has. */
|
|
19
|
+
readonly run: (kernel: Kernel, size: WorkgroupSize) => unknown;
|
|
20
|
+
/**
|
|
21
|
+
* Sizes to try, numbers for one dimension; on a tie the earlier wins. Those this device cannot run are dropped.
|
|
22
|
+
* Default 256, 128, 64, 32, 512, 1024.
|
|
23
|
+
*/
|
|
24
|
+
readonly candidates?: readonly (number | readonly number[])[];
|
|
25
|
+
/** What the best size depends on besides the adapter and the source, such as the element count. Default ''. */
|
|
26
|
+
readonly signature?: string;
|
|
27
|
+
/** Timed runs of each size, of which the median counts. Default 7. */
|
|
28
|
+
readonly trials?: number;
|
|
29
|
+
/** Untimed runs of each size first, which also build its pipeline. Default 2. */
|
|
30
|
+
readonly warmup?: number;
|
|
31
|
+
/** Remembers results across sessions. Default none: they last as long as the context. */
|
|
32
|
+
readonly store?: AutotuneStore;
|
|
33
|
+
/** Measures again even if a result is known. Default false. */
|
|
34
|
+
readonly refresh?: boolean;
|
|
35
|
+
/** Entry point, when the source has several. */
|
|
36
|
+
readonly entryPoint?: string;
|
|
37
|
+
}
|
|
38
|
+
/** The median time of one candidate. */
|
|
39
|
+
export interface AutotuneTiming {
|
|
40
|
+
/** The size measured. */
|
|
41
|
+
readonly workgroupSize: WorkgroupSize;
|
|
42
|
+
/** Median milliseconds of one run: GPU time from timestamp queries, else wall clock up to `gpu.done()`. */
|
|
43
|
+
readonly ms: number;
|
|
44
|
+
}
|
|
45
|
+
/** What {@link autotune} resolves. */
|
|
46
|
+
export interface AutotuneResult {
|
|
47
|
+
/** The fastest size. */
|
|
48
|
+
readonly workgroupSize: WorkgroupSize;
|
|
49
|
+
/** The kernel compiled at that size. */
|
|
50
|
+
readonly kernel: Kernel;
|
|
51
|
+
/** Every candidate's time, in the order given; empty when the result was known. */
|
|
52
|
+
readonly timings: readonly AutotuneTiming[];
|
|
53
|
+
/** True when the result came from the cache and nothing ran. */
|
|
54
|
+
readonly cached: boolean;
|
|
55
|
+
}
|
|
56
|
+
type Measuring = Pick<AutotuneOptions, 'trials' | 'warmup' | 'signal'>;
|
|
57
|
+
/**
|
|
58
|
+
* Measures a kernel at each candidate workgroup size and resolves the fastest, compiled. Known results are reused without
|
|
59
|
+
* running anything. Needs a GPU: the CPU backend throws a MargoError (`unsupported`), as for any WGSL kernel.
|
|
60
|
+
* @example
|
|
61
|
+
* const { kernel } = await autotune(gpu, {
|
|
62
|
+
* name: 'saxpy',
|
|
63
|
+
* signature: String(n),
|
|
64
|
+
* source: (size) => `... @compute @workgroup_size(${size}) fn main ...`,
|
|
65
|
+
* run: (kernel) => kernel.run({ x, y }, { count: n }),
|
|
66
|
+
* });
|
|
67
|
+
*/
|
|
68
|
+
export declare function autotune(gpu: ComputeContext, options: AutotuneOptions): Promise<AutotuneResult>;
|
|
69
|
+
/** What {@link tuneCompute} measures. */
|
|
70
|
+
export interface TuneComputeOptions extends WaitOptions, Measuring {
|
|
71
|
+
/** Elements in the arrays measured: make it the size the real work has. Default 4,194,304. */
|
|
72
|
+
readonly count?: number;
|
|
73
|
+
/** Remembers results across sessions. Default none: they last as long as the context. */
|
|
74
|
+
readonly store?: AutotuneStore;
|
|
75
|
+
/** Measures again even if a result is known. Default false. */
|
|
76
|
+
readonly refresh?: boolean;
|
|
77
|
+
}
|
|
78
|
+
/** What {@link tuneCompute} resolves. */
|
|
79
|
+
export interface TuneComputeResult {
|
|
80
|
+
/** The fastest size of each kernel. Pass it to `createCompute({ tuned })` to skip measuring next time. */
|
|
81
|
+
readonly tuned: Required<ComputeTuning>;
|
|
82
|
+
/** Every size's time for each kernel measured; a kernel whose result was known has none. */
|
|
83
|
+
readonly timings: {
|
|
84
|
+
readonly [K in keyof ComputeTuning]-?: readonly AutotuneTiming[];
|
|
85
|
+
};
|
|
86
|
+
/** True when every result came from the cache and nothing ran. */
|
|
87
|
+
readonly cached: boolean;
|
|
88
|
+
}
|
|
89
|
+
/**
|
|
90
|
+
* Measures the context's own reduce, scan and sort kernels at each workgroup size this device allows, and uses the
|
|
91
|
+
* fastest from then on. Integer results and sort orders stay the same; float sums round in another order. Call it before
|
|
92
|
+
* `useSubgroups`, whose kernels replace these. Known results are reused without running anything. Needs a GPU: the CPU
|
|
93
|
+
* backend throws a MargoError (`unsupported`), and so do subgroup kernels already in use.
|
|
94
|
+
* @example
|
|
95
|
+
* using gpu = await createCompute();
|
|
96
|
+
* const { tuned } = await tuneCompute(gpu, { store: localStorage });
|
|
97
|
+
* console.log(tuned); // { reduce: 128, scan: 256, sort: 256 } on one GPU
|
|
98
|
+
*/
|
|
99
|
+
export declare function tuneCompute(gpu: ComputeContext, options?: TuneComputeOptions): Promise<TuneComputeResult>;
|
|
100
|
+
export {};
|