@jax-js/jax 0.0.1 → 0.0.2

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/dist/index.d.cts CHANGED
@@ -1,24 +1,28 @@
1
- /**
2
- * @file Lazy shape tracking for multidimensional tensors.
3
- *
4
- * This module provides an immutable `View` class that can be used to calculate
5
- * shapes of arrays as operations are applied to them, lazily.
6
- *
7
- * Some operations like reshape() may not be representable with a single view,
8
- * for instance, because composing reshape() with shrink() leads to a
9
- * non-contiguous range of memory locations. This is why `ShapeTracker` is a
10
- * list of views.
11
- *
12
- * Indexing into a `ShapeTracker` or `View` can be folded into shader code.
13
- *
14
- * Originally based on tinygrad's implementation of shape tracking in the
15
- * `tinygrad.shape` module. But this version is simplified a bit. I'm not really
16
- * trying to innovate on shape tracking in this library, so if I have doubts on
17
- * something, it'll just be copied from tinygrad (with comments).
18
- *
19
- * This file is a bit longer than the original, since Python is more concise.
20
- */
1
+ import "node:module";
21
2
 
3
+ //#region rolldown:runtime
4
+ //#endregion
5
+ //#region src/pprint.d.ts
6
+ /** General class for pretty-printing expressions with indentation. */
7
+ declare class PPrint {
8
+ readonly indents: number[];
9
+ readonly lines: string[];
10
+ constructor(indents: number[], lines: string[]);
11
+ /** Add a fixed amount of indentation to each line. */
12
+ indent(spaces: number): PPrint;
13
+ /** Concatenate pretty-printed expressions with newlines. */
14
+ concat(...items: PPrint[]): PPrint;
15
+ /** Stack one block to the right of another one, sharing 1 common line. */
16
+ stack(other: PPrint): PPrint;
17
+ /** Combine this block of lines into a formatted string. */
18
+ toString(): string;
19
+ static pp(s: Stringable): PPrint;
20
+ }
21
+ interface Stringable {
22
+ toString(): string;
23
+ }
24
+ //#endregion
25
+ //#region src/shape.d.ts
22
26
  type Pair = [number, number];
23
27
  /**
24
28
  * A multidimensional view into memory. An array can be thought of as the
@@ -30,49 +34,54 @@ type Pair = [number, number];
30
34
  * 2. Otherwise, look at this memory address: offset + ∑(strides[i] * dim[i]).
31
35
  */
32
36
  declare class View {
33
- #private;
34
- /** The shape of the view (size of each dimension). */
35
- readonly shape: number[];
36
- /** How many indices to move in buffer for each hop in one dimension. */
37
- readonly strides: number[];
38
- /** Offset from the start of the buffer. */
39
- readonly offset: number;
40
- /** Masked out subarray where data is read. All other data is zeroed. */
41
- readonly mask: Pair[] | null;
42
- private constructor();
43
- static create(shape: number[], strides?: number[], offset?: number, mask?: Pair[] | null): View;
44
- get ndim(): number;
45
- get size(): number;
46
- /** Whether this is a default, contiguous, unaltered view of the data (identity). */
47
- get contiguous(): boolean;
48
- /** Produce an AluExp for evaluating this view at an index. */
49
- toAluExp(idxs: AluExp[]): [AluExp, AluExp];
50
- /**
51
- * Try to compose this view with another one. `this` view is applied first,
52
- * followed by the argument. If this is not possible for the specific views,
53
- * return `null` instead.
54
- *
55
- * If composable, return a combined view with the same shape as `v1`.
56
- *
57
- * This is very tricky. The shapes of v1 and v2 may be different, and in that
58
- * case, we do some math to figure out whether they're compatible.
59
- */
60
- compose(v1: View): View | null;
61
- /** Attempt to simplify this view into a smaller reshaped form. */
62
- minify(): View;
63
- /** Pad the view with zeros on each dimension. */
64
- pad(arg: Pair[]): View;
65
- /** Shrink the view by taking a subarray. */
66
- shrink(arg: Pair[]): View;
67
- /** Expand one or more axes with length "1" by repeating the data. */
68
- expand(newShape: number[]): View;
69
- /** Permute the axes of an array. */
70
- permute(axis: number[]): View;
71
- /** Flip (reverse) one or more axes of the view. */
72
- flip(arg: boolean[]): View;
73
- /** Reshape the view into a new shape. */
74
- reshape(newShape: number[]): View | null;
37
+ #private;
38
+ /** The shape of the view (size of each dimension). */
39
+ readonly shape: number[];
40
+ /** How many indices to move in buffer for each hop in one dimension. */
41
+ readonly strides: number[];
42
+ /** Offset from the start of the buffer. */
43
+ readonly offset: number;
44
+ /** Masked out subarray where data is read. All other data is zeroed. */
45
+ readonly mask: Pair[] | null;
46
+ private constructor();
47
+ static create(shape: number[], strides?: number[], offset?: number, mask?: Pair[] | null): View;
48
+ get ndim(): number;
49
+ get size(): number;
50
+ /** Whether this is a default, contiguous, unaltered view of the data (identity). */
51
+ get contiguous(): boolean;
52
+ /** Produce an AluExp for evaluating this view at an index. */
53
+ toAluExp(idxs: AluExp[]): [AluExp, AluExp];
54
+ /**
55
+ * Try to compose this view with another one. `this` view is applied first,
56
+ * followed by the argument. If this is not possible for the specific views,
57
+ * return `null` instead.
58
+ *
59
+ * If composable, return a combined view with the same shape as `v1`.
60
+ *
61
+ * This is very tricky. The shapes of v1 and v2 may be different, and in that
62
+ * case, we do some math to figure out whether they're compatible.
63
+ */
64
+ compose(v1: View): View | null;
65
+ /** Attempt to simplify this view into a smaller reshaped form. */
66
+ minify(): View;
67
+ /** Pad the view with zeros on each dimension. */
68
+ pad(arg: Pair[]): View;
69
+ /** Shrink the view by taking a subarray. */
70
+ shrink(arg: Pair[]): View;
71
+ /** Expand one or more axes with length "1" by repeating the data. */
72
+ expand(newShape: number[]): View;
73
+ /** Permute the axes of an array. */
74
+ permute(axis: number[]): View;
75
+ /** Flip (reverse) one or more axes of the view. */
76
+ flip(arg: boolean[]): View;
77
+ /** Reshape the view into a new shape. */
78
+ reshape(newShape: number[]): View | null;
75
79
  }
80
+ /**
81
+ * Find position of `offset` in each dimension within an existing shape. Like
82
+ * `numpy.unravel_index` in behavior.
83
+ */
84
+
76
85
  /**
77
86
  * Array shape after applying movement operations, as a series of views.
78
87
  *
@@ -80,31 +89,33 @@ declare class View {
80
89
  * shape, then used as the virtual buffer for the next view.
81
90
  */
82
91
  declare class ShapeTracker {
83
- readonly views: View[];
84
- constructor(views: View[]);
85
- /** Compose this shape tracker with another, applying after. */
86
- compose(other: ShapeTracker): ShapeTracker;
87
- static fromShape(shape: number[]): ShapeTracker;
88
- get contiguous(): boolean;
89
- get consecutive(): boolean;
90
- get lastStrides(): number[];
91
- get shape(): number[];
92
- get size(): number;
93
- toAluExp(idxs: AluExp[]): [AluExp, AluExp];
94
- simplify(): ShapeTracker;
95
- pad(arg: Pair[]): ShapeTracker;
96
- shrink(arg: Pair[]): ShapeTracker;
97
- expand(newShape: number[]): ShapeTracker;
98
- permute(axis: number[]): ShapeTracker;
99
- flip(arg: boolean[]): ShapeTracker;
100
- reshape(newShape: number[]): ShapeTracker;
101
- /** Broadcast along the given new axes, then expand the shape. */
102
- broadcast(newShape: number[], axis: number[]): ShapeTracker;
92
+ readonly views: View[];
93
+ constructor(views: View[]);
94
+ /** Compose this shape tracker with another, applying it after this one. */
95
+ compose(other: ShapeTracker): ShapeTracker;
96
+ static fromShape(shape: number[]): ShapeTracker;
97
+ get contiguous(): boolean;
98
+ get consecutive(): boolean;
99
+ get lastStrides(): number[];
100
+ get shape(): number[];
101
+ get size(): number;
102
+ toAluExp(idxs: AluExp[]): [AluExp, AluExp];
103
+ simplify(): ShapeTracker;
104
+ pad(arg: Pair[]): ShapeTracker;
105
+ shrink(arg: Pair[]): ShapeTracker;
106
+ expand(newShape: number[]): ShapeTracker;
107
+ permute(axis: number[]): ShapeTracker;
108
+ flip(arg: boolean[]): ShapeTracker;
109
+ reshape(newShape: number[]): ShapeTracker;
110
+ /** Broadcast along the given new axes, then expand the shape. */
111
+ broadcast(newShape: number[], axis: number[]): ShapeTracker;
103
112
  }
104
-
113
+ //#endregion
114
+ //#region src/utils.d.ts
115
+ /** @inline */
105
116
  type RecursiveArray<T> = T | RecursiveArray<T>[];
106
117
  interface FpHashable {
107
- hash(state: FpHash): void;
118
+ hash(state: FpHash): void;
108
119
  }
109
120
  /**
110
121
  * Polynomial hashes modulo p are good at avoiding collisions in expectation.
@@ -114,17 +125,20 @@ interface FpHashable {
114
125
  * See https://en.wikipedia.org/wiki/Lagrange%27s_theorem_(number_theory)
115
126
  */
116
127
  declare class FpHash {
117
- #private;
118
- value: bigint;
119
- update(...values: (string | boolean | number | bigint | null | undefined | FpHashable)[]): this;
120
- static hash(...values: (string | boolean | number | bigint | null | undefined | FpHashable)[]): bigint;
128
+ #private;
129
+ value: bigint;
130
+ update(...values: (string | boolean | number | bigint | null | undefined | FpHashable)[]): this;
131
+ static hash(...values: (string | boolean | number | bigint | null | undefined | FpHashable)[]): bigint;
121
132
  }
122
-
133
+ /** Run a function while caching it inline inside a `Map`. */
134
+ //#endregion
135
+ //#region src/alu.d.ts
123
136
  declare enum DType {
124
- Float32 = "float32",
125
- Int32 = "int32",
126
- Bool = "bool",
127
- Complex64 = "complex64"
137
+ Float32 = "float32",
138
+ Int32 = "int32",
139
+ Uint32 = "uint32",
140
+ Bool = "bool",
141
+ Complex64 = "complex64",
128
142
  }
129
143
  /**
130
144
  * Mathematical expression on scalar values.
@@ -134,94 +148,105 @@ declare enum DType {
134
148
  * graph rewrite engine.
135
149
  */
136
150
  declare class AluExp implements FpHashable {
137
- #private;
138
- readonly op: AluOp;
139
- readonly dtype: DType;
140
- readonly src: AluExp[];
141
- readonly arg: any;
142
- constructor(op: AluOp, dtype: DType, src: AluExp[], arg?: any);
143
- static add(a: AluExp, b: AluExp): AluExp;
144
- static sub(a: AluExp, b: AluExp): AluExp;
145
- static mul(a: AluExp, b: AluExp): AluExp;
146
- static idiv(a: AluExp, b: AluExp): AluExp;
147
- static mod(a: AluExp, b: AluExp): AluExp;
148
- static min(a: AluExp, b: AluExp): AluExp;
149
- static max(a: AluExp, b: AluExp): AluExp;
150
- static sin(a: AluExp): AluExp;
151
- static cos(a: AluExp): AluExp;
152
- static exp(a: AluExp): AluExp;
153
- static log(a: AluExp): AluExp;
154
- static reciprocal(a: AluExp): AluExp;
155
- static cast(dtype: DType, a: AluExp): AluExp;
156
- static cmplt(a: AluExp, b: AluExp): AluExp;
157
- static cmpne(a: AluExp, b: AluExp): AluExp;
158
- static where(cond: AluExp, a: AluExp, b: AluExp): AluExp;
159
- static const(dtype: DType, value: any): AluExp;
160
- static special(dtype: DType, name: string, n: number): AluExp;
161
- static variable(dtype: DType, name: string): AluExp;
162
- static globalIndex(dtype: DType, gid: number, bufidx: AluExp): AluExp;
163
- static globalView(dtype: DType, gid: number, st: ShapeTracker, indices: AluExp[]): AluExp;
164
- static i32(value: number): AluExp;
165
- static f32(value: number): AluExp;
166
- static bool(value: boolean): AluExp;
167
- not(): AluExp;
168
- /** Compute a reasonable expression hash with low collision rate. */
169
- getHash(): bigint;
170
- hash(state: FpHash): void;
171
- /** Substitute variables in this AluExp to values. */
172
- substitute(variables: Record<string, AluExp>): AluExp;
173
- /** Reindex gid values in this expression as needed. */
174
- reindexGids(gidMap: Map<number, number>): AluExp;
175
- get min(): number;
176
- get max(): number;
177
- /**
178
- * Simplify the expression by replacing any known patterns and deduping
179
- * identical subexpressions.
180
- */
181
- simplify(cache?: Map<bigint, AluExp>): AluExp;
182
- /** Resolve this to a value, or `undefined` if not possible. */
183
- resolve(): any | undefined;
184
- /**
185
- * Evaluate the expression on CPU, returning the result.
186
- *
187
- * Typically you would compile the AluExp as a representation to a lower-level
188
- * language. This is just to define the semantics and help debug.
189
- *
190
- * Note that the representation of Bool is as a number (0 or 1) here.
191
- */
192
- evaluate(context: Record<string, any>, globals?: (gid: number, bufidx: number) => any): any;
193
- /** Get this expression in debug format as a string. */
194
- toString(): string;
195
- /** Generic fold() operation with a reducer over the expression tree. */
196
- fold<T = void>(reducer: (exp: AluExp, mappedSrc: T[]) => T): T;
197
- /** Rewrite the expression recursively using a visitor. */
198
- rewrite(visitor: (exp: AluExp) => AluExp | undefined | null): AluExp;
199
- /** Collect all nodes that satisfy a predicate. */
200
- collect(predicate: (exp: AluExp) => boolean): AluExp[];
151
+ #private;
152
+ readonly op: AluOp;
153
+ readonly dtype: DType;
154
+ readonly src: AluExp[];
155
+ readonly arg: any;
156
+ constructor(op: AluOp, dtype: DType, src: AluExp[], arg?: any);
157
+ static add(a: AluExp, b: AluExp): AluExp;
158
+ static sub(a: AluExp, b: AluExp): AluExp;
159
+ static mul(a: AluExp, b: AluExp): AluExp;
160
+ static idiv(a: AluExp, b: AluExp): AluExp;
161
+ static mod(a: AluExp, b: AluExp): AluExp;
162
+ static min(a: AluExp, b: AluExp): AluExp;
163
+ static max(a: AluExp, b: AluExp): AluExp;
164
+ static sin(a: AluExp): AluExp;
165
+ static cos(a: AluExp): AluExp;
166
+ static exp(a: AluExp): AluExp;
167
+ static log(a: AluExp): AluExp;
168
+ static reciprocal(a: AluExp): AluExp;
169
+ static cast(dtype: DType, a: AluExp): AluExp;
170
+ static bitcast(dtype: DType, a: AluExp): AluExp;
171
+ static threefry2x32(k0: AluExp, k1: AluExp, c0: AluExp, c1: AluExp, mode?: "xor" | 0 | 1): AluExp;
172
+ static cmplt(a: AluExp, b: AluExp): AluExp;
173
+ static cmpne(a: AluExp, b: AluExp): AluExp;
174
+ static where(cond: AluExp, a: AluExp, b: AluExp): AluExp;
175
+ static const(dtype: DType, value: any): AluExp;
176
+ static special(dtype: DType, name: string, n: number): AluExp;
177
+ static variable(dtype: DType, name: string): AluExp;
178
+ static globalIndex(dtype: DType, gid: number, bufidx: AluExp): AluExp;
179
+ static globalView(dtype: DType, gid: number, st: ShapeTracker, indices: AluExp[]): AluExp;
180
+ static i32(value: number): AluExp;
181
+ static u32(value: number): AluExp;
182
+ static f32(value: number): AluExp;
183
+ static bool(value: boolean): AluExp;
184
+ not(): AluExp;
185
+ /** Compute a reasonable expression hash with low collision rate. */
186
+ getHash(): bigint;
187
+ hash(state: FpHash): void;
188
+ /** Substitute variables in this AluExp to values. */
189
+ substitute(variables: Record<string, AluExp>): AluExp;
190
+ /** Reindex gid values in this expression as needed. */
191
+ reindexGids(gidMap: Map<number, number>): AluExp;
192
+ get min(): number;
193
+ get max(): number;
194
+ /**
195
+ * Simplify the expression by replacing any known patterns and deduping
196
+ * identical subexpressions.
197
+ */
198
+ simplify(cache?: Map<bigint, AluExp>): AluExp;
199
+ /** Resolve this to a value, or `undefined` if not possible. */
200
+ resolve(): any | undefined;
201
+ /**
202
+ * Evaluate the expression on CPU, returning the result.
203
+ *
204
+ * Typically you would compile the AluExp as a representation to a lower-level
205
+ * language. This is just to define the semantics and help debug.
206
+ *
207
+ * Note that the representation of Bool is as a number (0 or 1) here.
208
+ */
209
+ evaluate(context: Record<string, any>, globals?: (gid: number, bufidx: number) => any): number;
210
+ /** Get this expression in debug format as a string. */
211
+ toString(): string;
212
+ /** Generic fold() operation with a reducer over the expression tree. */
213
+ fold<T = void>(reducer: (exp: AluExp, mappedSrc: T[]) => T): T;
214
+ /** Rewrite the expression recursively using a visitor. */
215
+ rewrite(visitor: (exp: AluExp) => AluExp | undefined | null): AluExp;
216
+ /** Collect all nodes that satisfy a predicate. */
217
+ collect(predicate: (exp: AluExp) => boolean): AluExp[];
201
218
  }
202
219
  /** Symbolic form for each mathematical operation. */
203
220
  declare enum AluOp {
204
- Add = "Add",
205
- Sub = "Sub",
206
- Mul = "Mul",
207
- Idiv = "Idiv",
208
- Mod = "Mod",
209
- Min = "Min",
210
- Max = "Max",
211
- Sin = "Sin",
212
- Cos = "Cos",
213
- Exp = "Exp",
214
- Log = "Log",
215
- Reciprocal = "Reciprocal",
216
- Cast = "Cast",
217
- Cmplt = "Cmplt",
218
- Cmpne = "Cmpne",
219
- Where = "Where",// Ternary operator: `cond ? a : b`
220
- Const = "Const",// arg = value
221
- Special = "Special",// arg = [variable, n]
222
- Variable = "Variable",// arg = variable
223
- GlobalIndex = "GlobalIndex",// arg = gid; src = [bufidx]
224
- GlobalView = "GlobalView"
221
+ Add = "Add",
222
+ Sub = "Sub",
223
+ Mul = "Mul",
224
+ Idiv = "Idiv",
225
+ Mod = "Mod",
226
+ Min = "Min",
227
+ Max = "Max",
228
+ Sin = "Sin",
229
+ Cos = "Cos",
230
+ Exp = "Exp",
231
+ Log = "Log",
232
+ Reciprocal = "Reciprocal",
233
+ Cast = "Cast",
234
+ Bitcast = "Bitcast",
235
+ Cmplt = "Cmplt",
236
+ Cmpne = "Cmpne",
237
+ Where = "Where",
238
+ // Ternary operator: `cond ? a : b`
239
+ Threefry2x32 = "Threefry2x32",
240
+ // PRNG operation, arg = 'xor' | 0 | 1
241
+ Const = "Const",
242
+ // arg = value
243
+ Special = "Special",
244
+ // arg = [variable, n]
245
+ Variable = "Variable",
246
+ // arg = variable
247
+ GlobalIndex = "GlobalIndex",
248
+ // arg = gid; src = [bufidx]
249
+ GlobalView = "GlobalView",
225
250
  }
226
251
  /**
227
252
  * Description of a kernel to be compiled.
@@ -231,24 +256,26 @@ declare enum AluOp {
231
256
  * indexing into a buffer.
232
257
  */
233
258
  declare class Kernel implements FpHashable {
234
- /** Number of global arguments / arrays. */
235
- readonly nargs: number;
236
- /** Size of the result array in element count. */
237
- readonly size: number;
238
- /** Expression to be evaluated. */
239
- readonly exp: AluExp;
240
- /** Optional reduction to be performed. */
241
- readonly reduction?: Reduction | undefined;
242
- constructor(
243
- /** Number of global arguments / arrays. */
244
- nargs: number,
245
- /** Size of the result array in element count. */
246
- size: number,
247
- /** Expression to be evaluated. */
248
- exp: AluExp,
249
- /** Optional reduction to be performed. */
250
- reduction?: Reduction | undefined);
251
- hash(state: FpHash): void;
259
+ /** Number of global arguments / arrays. */
260
+ readonly nargs: number;
261
+ /** Size of the result array in element count. */
262
+ readonly size: number;
263
+ /** Expression to be evaluated. */
264
+ readonly exp: AluExp;
265
+ /** Optional reduction to be performed. */
266
+ readonly reduction?: Reduction | undefined;
267
+ constructor(/** Number of global arguments / arrays. */
268
+ nargs: number, /** Size of the result array in element count. */
269
+ size: number, /** Expression to be evaluated. */
270
+ exp: AluExp, /** Optional reduction to be performed. */
271
+ reduction?: Reduction | undefined);
272
+ hash(state: FpHash): void;
273
+ pprint(): PPrint;
274
+ toString(): string;
275
+ /** The dtype of the values output by this kernel. */
276
+ get dtype(): DType;
277
+ /** The number of bytes in the output array when evaluating this kernel. */
278
+ get bytes(): number;
252
279
  }
253
280
  /**
254
281
  * Description of a reduction.
@@ -266,41 +293,29 @@ declare class Kernel implements FpHashable {
266
293
  * at this level since they depend on GPU, versus CPU or Wasm.
267
294
  */
268
295
  declare class Reduction implements FpHashable {
269
- /** Data type of the values being reduced over. */
270
- readonly dtype: DType;
271
- /** Operation to perform. Only ops in `AluGroup.Reduce` are supported. */
272
- readonly op: AluOp;
273
- /** Size of the reduction axis. */
274
- readonly size: number;
275
- /** Follow-up expression defined with the "acc" variable, defaults to identity. */
276
- readonly fusion: AluExp;
277
- constructor(
278
- /** Data type of the values being reduced over. */
279
- dtype: DType,
280
- /** Operation to perform. Only ops in `AluGroup.Reduce` are supported. */
281
- op: AluOp,
282
- /** Size of the reduction axis. */
283
- size: number,
284
- /** Follow-up expression defined with the "acc" variable, defaults to identity. */
285
- fusion?: AluExp);
286
- hash(state: FpHash): void;
287
- /** Get the identity for this reduction operation. */
288
- get identity(): any;
289
- /** Evaluate this operation on CPU. */
290
- evaluate(...values: any): any;
296
+ /** Data type of the values being reduced over. */
297
+ readonly dtype: DType;
298
+ /** Operation to perform. Only ops in `AluGroup.Reduce` are supported. */
299
+ readonly op: AluOp;
300
+ /** Size of the reduction axis. */
301
+ readonly size: number;
302
+ /** Follow-up expression defined with the "acc" variable, defaults to identity. */
303
+ readonly fusion: AluExp;
304
+ constructor(/** Data type of the values being reduced over. */
305
+ dtype: DType, /** Operation to perform. Only ops in `AluGroup.Reduce` are supported. */
306
+ op: AluOp, /** Size of the reduction axis. */
307
+ size: number, /** Follow-up expression defined with the "acc" variable, defaults to identity. */
308
+ fusion?: AluExp);
309
+ hash(state: FpHash): void;
310
+ toString(): string;
311
+ /** Get the identity for this reduction operation. */
312
+ get identity(): any;
313
+ /** Evaluate this operation on CPU. */
314
+ evaluate(...values: any): any;
291
315
  }
292
-
293
- /**
294
- * @file Shared interfaces and code for the low-level backend API.
295
- *
296
- * Think of each backend as a _connector_ to a specific hardware or software
297
- * implementation of the array API.
298
- *
299
- * Backends do not share any of the built-in operational semantics of the
300
- * library. This is a private API. You must allocate and free buffers manually,
301
- * and dispatch happens on the level of each shader. Buffers are untyped.
302
- */
303
-
316
+ /** Expression for accessing `indices` in input array with the given shape. */
317
+ //#endregion
318
+ //#region src/backend.d.ts
304
319
  type Device = "cpu" | "webgpu";
305
320
  declare const devices: Device[];
306
321
  /** Set the default device backend (must be initialized). */
@@ -313,75 +328,74 @@ declare function setDevice(device: Device): void;
313
328
  * available backends.
314
329
  */
315
330
  declare function init(...devicesToInit: Device[]): Promise<Device[]>;
331
+ /** Retrieve a backend that has been initialized. */
332
+
316
333
  /** Unique identifier for an allocated, on-device buffer. */
317
334
  type Slot = number;
318
335
  /** A device backend. */
319
336
  interface Backend {
320
- /** The name of the backend as a string. */
321
- readonly type: Device;
322
- /** Maximum number of arguments per dispatched kernel. */
323
- readonly maxArgs: number;
324
- /** Allocate a new slot with reference count 1. */
325
- malloc(size: number, initialData?: ArrayBuffer): Slot;
326
- /** Increment the reference count of the slot. */
327
- incRef(slot: Slot): void;
328
- /**
329
- * Decrement the reference count of the slot. If the reference count reaches
330
- * zero, it is freed. This should throw if the slot was already freed.
331
- */
332
- decRef(slot: Slot): void;
333
- /** Read a range of bytes from a buffer. */
334
- read(slot: Slot, start?: number, count?: number): Promise<ArrayBuffer>;
335
- /** Read a range of bytes from a buffer, blocking variant. */
336
- readSync(slot: Slot, start?: number, count?: number): ArrayBuffer;
337
- /** Prepare an expression to be executed later. */
338
- prepare(kernel: Kernel): Promise<Executable>;
339
- /** Prepare an expression to be executed later, blocking variant. */
340
- prepareSync(kernel: Kernel): Executable;
341
- /**
342
- * Run a backend operation that was previously prepared.
343
- *
344
- * The operation may not run immediately, but operations are guaranteed to run
345
- * in the dispatch order. Also, `read()` will wait for all pending operations
346
- * on that slot to finish.
347
- */
348
- dispatch(exe: Executable, inputs: Slot[], outputs: Slot[]): void;
337
+ /** The name of the backend as a string. */
338
+ readonly type: Device;
339
+ /** Maximum number of arguments per dispatched kernel. */
340
+ readonly maxArgs: number;
341
+ /** Allocate a new slot with reference count 1. */
342
+ malloc(size: number, initialData?: ArrayBuffer): Slot;
343
+ /** Increment the reference count of the slot. */
344
+ incRef(slot: Slot): void;
345
+ /**
346
+ * Decrement the reference count of the slot. If the reference count reaches
347
+ * zero, it is freed. This should throw if the slot was already freed.
348
+ */
349
+ decRef(slot: Slot): void;
350
+ /** Read a range of bytes from a buffer. */
351
+ read(slot: Slot, start?: number, count?: number): Promise<ArrayBuffer>;
352
+ /** Read a range of bytes from a buffer, blocking variant. */
353
+ readSync(slot: Slot, start?: number, count?: number): ArrayBuffer;
354
+ /** Prepare an expression to be executed later. */
355
+ prepare(kernel: Kernel): Promise<Executable>;
356
+ /** Prepare an expression to be executed later, blocking variant. */
357
+ prepareSync(kernel: Kernel): Executable;
358
+ /**
359
+ * Run a backend operation that was previously prepared.
360
+ *
361
+ * The operation may not run immediately, but operations are guaranteed to run
362
+ * in the dispatch order. Also, `read()` will wait for all pending operations
363
+ * on that slot to finish.
364
+ */
365
+ dispatch(exe: Executable, inputs: Slot[], outputs: Slot[]): void;
349
366
  }
350
367
  declare class Executable<T = any> {
351
- readonly kernel: Kernel;
352
- /** Extra data specific to the backend running this kernel. */
353
- readonly data: T;
354
- constructor(kernel: Kernel,
355
- /** Extra data specific to the backend running this kernel. */
356
- data: T);
368
+ readonly kernel: Kernel;
369
+ /** Extra data specific to the backend running this kernel. */
370
+ readonly data: T;
371
+ constructor(kernel: Kernel, /** Extra data specific to the backend running this kernel. */
372
+ data: T);
373
+ }
374
+ declare namespace tree_d_exports {
375
+ export { JsTree, JsTreeDef, MapJsTree, NodeType, flatten, leaves, map, ref, structure, unflatten };
357
376
  }
358
-
359
- /** @file Utilities for working with tree-like container data structures ("pytrees"). */
360
377
  declare enum NodeType {
361
- Array = "Array",
362
- Object = "Object",
363
- Leaf = "Leaf"
378
+ Array = "Array",
379
+ Object = "Object",
380
+ Leaf = "Leaf",
364
381
  }
365
382
  type JsTree<T> = T | JsTree<T>[] | {
366
- [key: string]: JsTree<T>;
367
- };
368
- type MapJsTree<T, A, B> = T extends A ? B : T extends globalThis.Array<infer U> ? number extends T["length"] ? MapJsTree<U, A, B>[] : {
369
- [K in keyof T]: MapJsTree<T[K], A, B>;
370
- } : {
371
- [K in keyof T]: MapJsTree<T[K], A, B>;
383
+ [key: string]: JsTree<T>;
372
384
  };
385
+ type MapJsTree<T, A, B> = T extends A ? B : T extends globalThis.Array<infer U> ? number extends T["length"] ? MapJsTree<U, A, B>[] : { [K in keyof T]: MapJsTree<T[K], A, B> } : { [K in keyof T]: MapJsTree<T[K], A, B> };
373
386
  /** Analog to the JAX "pytree" object, but for JavaScript. */
374
387
  declare class JsTreeDef {
375
- readonly nodeType: NodeType;
376
- readonly nodeMetadata: any;
377
- readonly childTreedefs: JsTreeDef[];
378
- static leaf: JsTreeDef;
379
- constructor(nodeType: NodeType, nodeMetadata: any, // Must be comparable with deepEqual.
380
- childTreedefs: JsTreeDef[]);
381
- /** Returns a string representation of this tree definition. */
382
- toString(root?: boolean): string;
383
- /** Compare this tree definition with another. */
384
- equals(other: JsTreeDef): boolean;
388
+ readonly nodeType: NodeType;
389
+ readonly nodeMetadata: any;
390
+ readonly childTreedefs: JsTreeDef[];
391
+ static leaf: JsTreeDef;
392
+ constructor(nodeType: NodeType, nodeMetadata: any,
393
+ // Must be comparable with deepEqual.
394
+ childTreedefs: JsTreeDef[]);
395
+ /** Returns a string representation of this tree definition. */
396
+ toString(root?: boolean): string;
397
+ /** Compare this tree definition with another. */
398
+ equals(other: JsTreeDef): boolean;
385
399
  }
386
400
  /** Flatten a structured object, returning the tree definition. */
387
401
  declare function flatten<T>(tree: JsTree<T>): [T[], JsTreeDef];
@@ -391,151 +405,290 @@ declare function leaves<T>(tree: JsTree<T>): T[];
391
405
  declare function structure<T>(tree: JsTree<T>): JsTreeDef;
392
406
  /** Reconstruct a structured object from the flattened representation. */
393
407
  declare function unflatten<T>(treedef: JsTreeDef, leaves: Iterable<T>): JsTree<T>;
394
-
395
- type tree_JsTree<T> = JsTree<T>;
396
- type tree_JsTreeDef = JsTreeDef;
397
- declare const tree_JsTreeDef: typeof JsTreeDef;
398
- type tree_MapJsTree<T, A, B> = MapJsTree<T, A, B>;
399
- type tree_NodeType = NodeType;
400
- declare const tree_NodeType: typeof NodeType;
401
- declare const tree_flatten: typeof flatten;
402
- declare const tree_leaves: typeof leaves;
403
- declare const tree_structure: typeof structure;
404
- declare const tree_unflatten: typeof unflatten;
405
- declare namespace tree {
406
- export { type tree_JsTree as JsTree, tree_JsTreeDef as JsTreeDef, type tree_MapJsTree as MapJsTree, tree_NodeType as NodeType, tree_flatten as flatten, tree_leaves as leaves, tree_structure as structure, tree_unflatten as unflatten };
407
- }
408
-
409
- /** @file Core library internals and interpreter stack, based on Autodidax. */
410
-
408
+ /** Maps a multi-input function over pytree args to produce a new pytree. */
409
+ declare function map<T, U, Tree extends JsTree<T>>(fn: (...args: T[]) => U, tree: Tree, ...rest: Tree[]): MapJsTree<Tree, T, U>;
410
+ /** Take a reference of every array in a tree. */
411
+ declare function ref<Tree extends JsTree<Array>>(tree: Tree): Tree;
412
+ //#endregion
413
+ //#region src/frontend/core.d.ts
414
+ /**
415
+ * Frontend primitive operations, which are lowered into Kernel objects before
416
+ * being dispatched to the backend.
417
+ *
418
+ * Any operation between arrays can be described in these parts. This is also
419
+ * the set of primitives that can occur in Jaxpr programs, and the level at
420
+ * which transformations like vmap, grad, and jvp occur. They are loosely based
421
+ * on [XLA](https://openxla.org/xla/operation_semantics).
422
+ *
423
+ * All n-ary operations support broadcasting, with NumPy semantics.
424
+ */
411
425
  declare enum Primitive {
412
- Add = "add",
413
- Mul = "mul",
414
- Idiv = "idiv",
415
- Neg = "neg",
416
- Reciprocal = "reciprocal",
417
- Sin = "sin",
418
- Cos = "cos",
419
- Exp = "exp",
420
- Log = "log",
421
- Min = "min",
422
- Max = "max",
423
- ReduceSum = "reduce_sum",
424
- Compare = "compare",
425
- Where = "where",
426
- Transpose = "transpose",
427
- Broadcast = "broadcast",
428
- Reshape = "reshape",
429
- Flip = "flip",
430
- JitCall = "jit_call"
426
+ Add = "add",
427
+ Mul = "mul",
428
+ Idiv = "idiv",
429
+ Neg = "neg",
430
+ Reciprocal = "reciprocal",
431
+ StopGradient = "stop_gradient",
432
+ Cast = "cast",
433
+ Bitcast = "bitcast",
434
+ RandomBits = "random_bits",
435
+ Sin = "sin",
436
+ Cos = "cos",
437
+ Exp = "exp",
438
+ Log = "log",
439
+ Min = "min",
440
+ Max = "max",
441
+ Reduce = "reduce",
442
+ Dot = "dot",
443
+ Compare = "compare",
444
+ Where = "where",
445
+ Transpose = "transpose",
446
+ Broadcast = "broadcast",
447
+ Reshape = "reshape",
448
+ Flip = "flip",
449
+ Shrink = "shrink",
450
+ Pad = "pad",
451
+ Gather = "gather",
452
+ JitCall = "jit_call",
453
+ }
454
+ interface PrimitiveParamsImpl extends Record<Primitive, Record<string, unknown>> {
455
+ [Primitive.Cast]: {
456
+ dtype: DType;
457
+ };
458
+ [Primitive.Bitcast]: {
459
+ dtype: DType;
460
+ };
461
+ [Primitive.Reduce]: {
462
+ op: AluOp;
463
+ axis: number[];
464
+ };
465
+ [Primitive.Compare]: {
466
+ op: CompareOp;
467
+ };
468
+ [Primitive.Transpose]: {
469
+ perm: number[];
470
+ };
471
+ [Primitive.Broadcast]: {
472
+ shape: number[];
473
+ axis: number[];
474
+ };
475
+ [Primitive.RandomBits]: {
476
+ shape: number[];
477
+ mode: "xor" | 0 | 1;
478
+ };
479
+ [Primitive.Reshape]: {
480
+ shape: number[];
481
+ };
482
+ [Primitive.Flip]: {
483
+ axis: number[];
484
+ };
485
+ [Primitive.Shrink]: {
486
+ slice: [number, number][];
487
+ };
488
+ [Primitive.Pad]: {
489
+ width: [number, number][];
490
+ };
491
+ [Primitive.Gather]: {
492
+ axis: number[];
493
+ outDim: number;
494
+ };
495
+ [Primitive.JitCall]: {
496
+ jaxpr: Jaxpr;
497
+ numConsts: number;
498
+ };
499
+ }
500
+ /** Type of parameters taken by each primitive. */
501
+ type PrimitiveParams<T extends Primitive> = T extends keyof PrimitiveParamsImpl ? PrimitiveParamsImpl[T] : Record<string, never>;
502
+ declare enum CompareOp {
503
+ Greater = "greater",
504
+ Less = "less",
505
+ Equal = "equal",
506
+ NotEqual = "not_equal",
507
+ GreaterEqual = "greater_equal",
508
+ LessEqual = "less_equal",
431
509
  }
510
+ /** @inline */
511
+ type ReduceOpts = {
512
+ keepDims?: boolean;
513
+ };
432
514
  type MainTrace = {
433
- level: number;
434
- traceType: new (main: MainTrace) => Trace;
435
- globalData: any | null;
515
+ level: number;
516
+ traceType: new (main: MainTrace) => Trace;
517
+ globalData: any | null;
436
518
  };
519
+ /**
520
+ * Push an interpreter onto the trace stack. Use this like:
521
+ * `using main = newMain(...);`
522
+ */
523
+
437
524
  type TracerValue = Tracer | number | boolean;
438
525
  declare abstract class Trace {
439
- readonly main: MainTrace;
440
- constructor(main: MainTrace);
441
- abstract pure(val: TracerValue): Tracer;
442
- abstract lift(val: Tracer): Tracer;
443
- abstract processPrimitive(primitive: Primitive, tracers: Tracer[], params: Record<string, any>): Tracer[];
526
+ readonly main: MainTrace;
527
+ constructor(main: MainTrace);
528
+ abstract pure(val: TracerValue): Tracer;
529
+ abstract lift(val: Tracer): Tracer;
530
+ abstract processPrimitive<P extends Primitive>(primitive: P, tracers: Tracer[], params: PrimitiveParams<P>): Tracer[];
444
531
  }
445
532
  interface AbstractValue {
446
- shape: number[];
447
- dtype: DType;
533
+ shape: number[];
534
+ dtype: DType;
448
535
  }
449
536
  declare abstract class Tracer {
450
- readonly _trace: Trace;
451
- constructor(trace: Trace);
452
- abstract get aval(): AbstractValue;
453
- abstract toString(): string;
454
- /**
455
- * Access an array by reference, incrementing the reference count.
456
- *
457
- * jax-js handles freeing arrays by using "move" semantics, like in Rust/C++.
458
- * Whenever you pass an array into a function, that function should consume
459
- * the array, and it will no longer be usable. For example, if you had:
460
- *
461
- * ```
462
- * const x = np.array([1, 2, 3]);
463
- * const y = np.add(x, x);
464
- * ```
465
- *
466
- * The second line does not work because the first parameter consumes `x`, and
467
- * then the second parameter will already have been freed / disposed.
468
- *
469
- * To fix this, you can write:
470
- *
471
- * ```
472
- * const y = np.add(x.ref, x);
473
- * ```
474
- *
475
- * Under the hood, every access to `.ref` increments the internal reference
476
- * count of the array. The reference count starts at 1. When it hits 0, the
477
- * memory behind the array is freed.
478
- */
479
- abstract get ref(): this;
480
- /**
481
- * Manually decrement the reference count of the array.
482
- *
483
- * Arrays are created with reference count 1. Whenever it is used as argument
484
- * to a function or other operation, it is disposed (i.e., reference count
485
- * decreases by 1) automatically. Whenever a `.ref` is created, the reference
486
- * count increases.
487
- *
488
- * You generally don't need to call this function directly since arrays are
489
- * automatically disposed after being passed into an operation. One common
490
- * exception is when writing a function and ignoring one of its arguments. In
491
- * that case, by convention you should dispose of that argument manually.
492
- *
493
- * ```
494
- * function myCustomOperation(a: np.Array, b: np.Array) {
495
- * b.dispose(); // Needed to satisfy "move" rules.
496
- * return a.add(1);
497
- * }
498
- * ```
499
- */
500
- abstract dispose(): void;
501
- get shape(): number[];
502
- get dtype(): DType;
503
- get ndim(): number;
504
- fullLower(): Tracer;
505
- neg(): this;
506
- add(other: this | TracerValue): this;
507
- mul(other: this | TracerValue): this;
508
- greater(other: this | TracerValue): this;
509
- less(other: this | TracerValue): this;
510
- equal(other: this | TracerValue): this;
511
- notEqual(other: this | TracerValue): this;
512
- greaterEqual(other: this | TracerValue): this;
513
- lessEqual(other: this | TracerValue): this;
514
- sum(axis?: number | number[]): this;
515
- transpose(perm?: number[]): this;
516
- reshape(shape: number | number[]): this;
517
- /** Subtract an array from this one. */
518
- sub(other: this | TracerValue): this;
519
- /** Divide an array by this one. */
520
- div(other: this | TracerValue): this;
521
- /** Return specified diagonals. See `numpy.diagonal` for full docs. */
522
- diagonal(offset?: number, axis1?: number, axis2?: number): this;
523
- /** Flatten the array without changing its data. */
524
- flatten(): this;
525
- /** Flatten the array without changing its data. */
526
- ravel(): this;
537
+ /** @ignore */
538
+ readonly _trace: Trace;
539
+ constructor(trace: Trace);
540
+ abstract get aval(): AbstractValue;
541
+ abstract toString(): string;
542
+ /**
543
+ * Access an array by reference, incrementing the reference count.
544
+ *
545
+ * jax-js handles freeing arrays by using "move" semantics, like in Rust/C++.
546
+ * Whenever you pass an array into a function, that function should consume
547
+ * the array, and it will no longer be usable. For example, if you had:
548
+ *
549
+ * ```
550
+ * const x = np.array([1, 2, 3]);
551
+ * const y = np.add(x, x);
552
+ * ```
553
+ *
554
+ * The second line does not work because the first parameter consumes `x`, and
555
+ * then the second parameter will already have been freed / disposed.
556
+ *
557
+ * To fix this, you can write:
558
+ *
559
+ * ```
560
+ * const y = np.add(x.ref, x);
561
+ * ```
562
+ *
563
+ * Under the hood, every access to `.ref` increments the internal reference
564
+ * count of the array. The reference count starts at 1. When it hits 0, the
565
+ * memory behind the array is freed.
566
+ */
567
+ abstract get ref(): this;
568
+ /**
569
+ * Manually decrement the reference count of the array.
570
+ *
571
+ * Arrays are created with reference count 1. Whenever it is used as argument
572
+ * to a function or other operation, it is disposed (i.e., reference count
573
+ * decreases by 1) automatically. Whenever a `.ref` is created, the reference
574
+ * count increases.
575
+ *
576
+ * You generally don't need to call this function directly since arrays are
577
+ * automatically disposed after being passed into an operation. One common
578
+ * exception is when writing a function and ignoring one of its arguments. In
579
+ * that case, by convention you should dispose of that argument manually.
580
+ *
581
+ * ```
582
+ * function myCustomOperation(a: np.Array, b: np.Array) {
583
+ * b.dispose(); // Needed to satisfy "move" rules.
584
+ * return a.add(1);
585
+ * }
586
+ * ```
587
+ */
588
+ abstract dispose(): void;
589
+ get shape(): number[];
590
+ get dtype(): DType;
591
+ get ndim(): number;
592
+ /** @ignore */
593
+ fullLower(): Tracer;
594
+ neg(): this;
595
+ add(other: this | TracerValue): this;
596
+ mul(other: this | TracerValue): this;
597
+ greater(other: this | TracerValue): this;
598
+ less(other: this | TracerValue): this;
599
+ equal(other: this | TracerValue): this;
600
+ notEqual(other: this | TracerValue): this;
601
+ greaterEqual(other: this | TracerValue): this;
602
+ lessEqual(other: this | TracerValue): this;
603
+ /** Sum of the elements of the array over a given axis, or axes. */
604
+ sum(axis?: number | number[], opts?: ReduceOpts): this;
605
+ /** Product of the array elements over a given axis. */
606
+ prod(axis?: number | number[], opts?: ReduceOpts): this;
607
+ /** Compute the average of the array elements along the specified axis. */
608
+ mean(axis?: number | number[], opts?: ReduceOpts): this;
609
+ /** Permute the dimensions of an array. Defaults to reversing the axis order. */
610
+ transpose(perm?: number[]): this;
611
+ /**
612
+ * Give a new shape to an array without changing its data.
613
+ *
614
+ * One shape dimension can be -1. In this case, the value is inferred from the
615
+ * length of the array and remaining dimensions.
616
+ */
617
+ reshape(shape: number | number[]): this;
618
+ /** Copy the array and cast to a specified dtype. */
619
+ astype(dtype: DType): this;
620
+ /** Subtract an array from this one. */
621
+ sub(other: this | TracerValue): this;
622
+ /** Divide an array by this one. */
623
+ div(other: this | TracerValue): this;
624
+ /** Return specified diagonals. See `numpy.diagonal` for full docs. */
625
+ diagonal(offset?: number, axis1?: number, axis2?: number): this;
626
+ /** Flatten the array without changing its data. */
627
+ flatten(): this;
628
+ /** Flatten the array without changing its data. */
629
+ ravel(): this;
630
+ /**
631
+ * Iterate over the first dimension of this array, returning slices.
632
+ *
633
+ * This can be used to destructure arrays. For example:
634
+ *
635
+ * ```js
636
+ * let x = np.array([[1, 2], [3, 4]]);
637
+ * let [a, b] = x;
638
+ * console.log(a.js()); // [1, 2]
639
+ * console.log(b.js()); // [3, 4]
640
+ * ```
641
+ */
642
+ [Symbol.iterator](): IterableIterator<this>;
643
+ /**
644
+ * Slice an array along one or more axes.
645
+ *
646
+ * This is the equivalent of slicing in Python, e.g. `x[1:3, 2, :, None]`. To
647
+ * mimic this in JavaScript, we would write:
648
+ *
649
+ * ```js
650
+ * x.slice([1, 3], 2, [], null);
651
+ * ```
652
+ *
653
+ * The `slice` method accepts a variable number of arguments, each of which
654
+ * can be a number, an empty array, a single-element array, a two-element
655
+ * array, or `null`. The arguments are interpreted as follows:
656
+ *
657
+ * - A number `n` means to access the `n`-th element along that axis, removing
658
+ * that axis from the resulting shape.
659
+ * - An empty array `[]` means to keep that axis as-is, like `:` in Python.
660
+ * - A single-element array `[i]` means to start slicing from index `i`
661
+ * (inclusive) to the end of the axis, like `x[i:]`.
662
+ * - A two-element array `[i, j]` means to slice from index `i` (inclusive)
663
+ * to index `j` (exclusive), like `x[i:j]`.
664
+ * - `null` means to add a new axis at that position, like `np.newaxis`.
665
+ *
666
+ * Like in Python, negative indices are supported, which count from the end of
667
+ * the axis. For example, `-1` means the last element.
668
+ *
669
+ * Strided slices are not yet implemented, so you cannot write `x[::2]` or
670
+ * similar.
671
+ *
672
+ * Advanced indexing by integer arrays is also supported. This translates to
673
+ * the "gather" primitive, and it allows you to access specific elements of
674
+ * the array by integer indices stored in another array.
675
+ */
676
+ slice(...index: (number | [] | [number] | [number, number] | null | Tracer)[]): this;
527
677
  }
528
678
  declare class ShapedArray implements AbstractValue {
529
- readonly shape: number[];
530
- readonly dtype: DType;
531
- constructor(shape: number[], dtype: DType);
532
- static fromAval(aval: AbstractValue): ShapedArray;
533
- get ndim(): number;
534
- strShort(): string;
535
- equals(other: ShapedArray): boolean;
679
+ readonly shape: number[];
680
+ readonly dtype: DType;
681
+ constructor(shape: number[], dtype: DType);
682
+ static fromAval(aval: AbstractValue): ShapedArray;
683
+ get ndim(): number;
684
+ strShort(): string;
685
+ equals(other: ShapedArray): boolean;
536
686
  }
537
-
687
+ //#endregion
688
+ //#region src/frontend/array.d.ts
538
689
  type ArrayLike = Array | number | boolean;
690
+ /** Version of pureArray with fudged types. */
691
+
539
692
  /**
540
693
  * An executable operation that will be dispatched to the backend.
541
694
  *
@@ -543,22 +696,23 @@ type ArrayLike = Array | number | boolean;
543
696
  * operation is dispatched, the references should be released.
544
697
  */
545
698
  declare class PendingExecute {
546
- #private;
547
- readonly backend: Backend;
548
- readonly kernel: Kernel;
549
- readonly inputs: Slot[];
550
- readonly outputs: Slot[];
551
- prepared: Executable | null;
552
- submitted: boolean;
553
- constructor(backend: Backend, kernel: Kernel, inputs: Slot[], outputs: Slot[]);
554
- updateRc(delta: number): void;
555
- prepare(): Promise<void>;
556
- prepareSync(): void;
557
- submit(): void;
699
+ #private;
700
+ readonly backend: Backend;
701
+ readonly kernel: Kernel;
702
+ readonly inputs: Slot[];
703
+ readonly outputs: Slot[];
704
+ prepared: Executable | null;
705
+ submitted: boolean;
706
+ constructor(backend: Backend, kernel: Kernel, inputs: Slot[], outputs: Slot[]);
707
+ updateRc(delta: number): void;
708
+ prepare(): Promise<void>;
709
+ prepareSync(): void;
710
+ submit(): void;
558
711
  }
712
+ /** @inline */
559
713
  type DTypeAndDevice = {
560
- dtype?: DType;
561
- device?: Device;
714
+ dtype?: DType;
715
+ device?: Device;
562
716
  };
563
717
  /**
564
718
  * A multidimensional numeric array with data stored on CPU or GPU.
@@ -571,64 +725,104 @@ type DTypeAndDevice = {
571
725
  * "Array" type by name.
572
726
  */
573
727
  declare class Array extends Tracer {
574
- #private;
575
- id: number;
576
- constructor(source: AluExp | Slot, st: ShapeTracker, dtype: DType, backend: Backend, pending?: Iterable<PendingExecute> | null);
577
- get aval(): ShapedArray;
578
- /** Return a simple string representation of the array's dimensions. */
579
- toString(): string;
580
- get device(): Device;
581
- get ref(): this;
582
- dispose(): void;
583
- /**
584
- * Convert this array into a primitive value.
585
- *
586
- * This only works for scalars (0-dimensional arrays). It lets you get values
587
- * "out" of the JAX system. For instance, if `x = np.array(5)`, then you can
588
- * evaluate `x + 1` and `x ** 2` to get `6` and `25`, respectively.
589
- *
590
- * This method is also called for `==` equality.
591
- */
592
- [Symbol.toPrimitive](): any;
593
- /** Realize the array and return it as data. */
594
- data(): Promise<Float32Array | Int32Array>;
595
- /** Wait for this array to be placed on the backend, if needed. */
596
- wait(): Promise<void>;
597
- /**
598
- * Realize the array and return it as data. This is a sync variant and not
599
- * recommended for performance reasons, as it will block rendering.
600
- */
601
- dataSync(): Float32Array | Int32Array;
602
- /** Convert this array into a JavaScript object (blocking). */
603
- js(): RecursiveArray<number> | RecursiveArray<boolean>;
604
- /** Convert this array into a JavaScript object, asynchronously. */
605
- jsAsync(): Promise<RecursiveArray<number> | RecursiveArray<boolean>>;
606
- /** @private Internal plumbing method for Array / Tracer ops. */
607
- static _implRules(): Record<Primitive, ImplRule>;
608
- _realizeSource(): number;
728
+ #private;
729
+ id: number;
730
+ /**
731
+ * @ignore
732
+ * Constructs an array from source, shape and backend. Note that if the source
733
+ * is a backend `Slot`, this constructor _takes ownership_ of the slot. It
734
+ * will be freed when the array is disposed.
735
+ */
736
+ constructor(source: AluExp | Slot, st: ShapeTracker, dtype: DType, backend: Backend, pending?: Iterable<PendingExecute> | null);
737
+ /** @ignore */
738
+ get aval(): ShapedArray;
739
+ /** Return a simple string representation of the array's dimensions. */
740
+ toString(): string;
741
+ get device(): Device;
742
+ get ref(): this;
743
+ dispose(): void;
744
+ /**
745
+ * Convert this array into a primitive value.
746
+ *
747
+ * This only works for scalars (0-dimensional arrays). It lets you get values
748
+ * "out" of the JAX system. For instance, if `x = np.array(5)`, then you can
749
+ * evaluate `x + 1` and `x ** 2` to get `6` and `25`, respectively.
750
+ *
751
+ * This method is also called for `==` equality.
752
+ */
753
+ [Symbol.toPrimitive](): any;
754
+ /** Realize the array and return it as data. */
755
+ data(): Promise<Float32Array | Int32Array | Uint32Array>;
756
+ /** Wait for this array to be placed on the backend, if needed. */
757
+ wait(): Promise<void>;
758
+ /**
759
+ * Realize the array and return it as data. This is a sync variant and not
760
+ * recommended for performance reasons, as it will block rendering.
761
+ */
762
+ dataSync(): Float32Array | Int32Array | Uint32Array;
763
+ /**
764
+ * Convert this array into a JavaScript object.
765
+ *
766
+ * This is a blocking operation that will compile all of the shaders and wait
767
+ * for execution to complete, synchronously. No other JavaScript code on the
768
+ * site will be run during shader execution.
769
+ *
770
+ * To avoid blocking, prefer `jsAsync()` when possible.
771
+ */
772
+ js(): any;
773
+ /** Convert this array into a JavaScript object, asynchronously. */
774
+ jsAsync(): Promise<any>;
775
+ /** @private Internal plumbing method for Array / Tracer ops. */
776
+ static _implRules(): typeof implRules;
777
+ _realizeSource(): number;
609
778
  }
610
779
  /** Construct an array from a single scalar constant. */
611
- declare function scalar(value: number | boolean, { dtype, device }?: DTypeAndDevice): Array;
780
+ declare function scalar(value: number | boolean, {
781
+ dtype,
782
+ device
783
+ }?: DTypeAndDevice): Array;
612
784
  /** Constructor for creating a new array from data. */
613
- declare function array(values: Array | Float32Array | Int32Array | RecursiveArray<number> | RecursiveArray<boolean>, { shape, dtype, device }?: {
614
- shape?: number[];
785
+ declare function array(values: Array | Float32Array | Int32Array | RecursiveArray<number> | RecursiveArray<boolean>, {
786
+ shape,
787
+ dtype,
788
+ device
789
+ }?: {
790
+ shape?: number[];
615
791
  } & DTypeAndDevice): Array;
616
- type ImplRule = (tracers: Array[], params: any) => Array[];
792
+ /** If x is a value, lift it into an array, otherwise leave it be. */
793
+
794
+ type ImplRule<P extends Primitive> = (tracers: Array[], params: PrimitiveParams<P>) => Array[];
795
+ declare const implRules: { [P in Primitive]: ImplRule<P> };
617
796
  /** Return a new array of given shape and type, filled with zeros. */
618
- declare function zeros(shape: number[], { dtype, device }?: DTypeAndDevice): Array;
797
+ declare function zeros(shape: number[], {
798
+ dtype,
799
+ device
800
+ }?: DTypeAndDevice): Array;
619
801
  /** Return a new array of given shape and type, filled with ones. */
620
- declare function ones(shape: number[], { dtype, device }?: DTypeAndDevice): Array;
802
+ declare function ones(shape: number[], {
803
+ dtype,
804
+ device
805
+ }?: DTypeAndDevice): Array;
621
806
  /** Return a new array of given shape and type, filled with `fill_value`. */
622
- declare function full(shape: number[], fillValue: number | boolean | Array, { dtype, device }?: DTypeAndDevice): Array;
807
+ declare function full(shape: number[], fillValue: number | boolean | Array, {
808
+ dtype,
809
+ device
810
+ }?: DTypeAndDevice): Array;
623
811
  /**
624
812
  * Create an identity matrix.
625
813
  *
626
814
  * If numCols is not provided, it defaults to numRows, i.e., a square identity
627
815
  * matrix with ones on the diagonal.
628
816
  */
629
- declare function eye(numRows: number, numCols?: number, { dtype, device }?: DTypeAndDevice): Array;
817
+ declare function eye(numRows: number, numCols?: number, {
818
+ dtype,
819
+ device
820
+ }?: DTypeAndDevice): Array;
630
821
  /** Return the identity array, with ones on the main diagonal. */
631
- declare function identity$1(n: number, { dtype, device }?: DTypeAndDevice): Array;
822
+ declare function identity$1(n: number, {
823
+ dtype,
824
+ device
825
+ }?: DTypeAndDevice): Array;
632
826
  /**
633
827
  * Return evenly spaced values within a given interval.
634
828
  *
@@ -643,7 +837,10 @@ declare function identity$1(n: number, { dtype, device }?: DTypeAndDevice): Arra
643
837
  * Defaults to an integer data type. This can produce unintended results when
644
838
  * using a non-integer step, so prefer linspace() in those cases.
645
839
  */
646
- declare function arange(start: number, stop?: number, step?: number, { dtype, device }?: DTypeAndDevice): Array;
840
+ declare function arange(start: number, stop?: number, step?: number, {
841
+ dtype,
842
+ device
843
+ }?: DTypeAndDevice): Array;
647
844
  /**
648
845
  * Return evenly spaced numbers over a specified interval.
649
846
  *
@@ -653,10 +850,17 @@ declare function arange(start: number, stop?: number, step?: number, { dtype, de
653
850
  *
654
851
  * The default data type is Float32. Use arange() for integer steps.
655
852
  */
656
- declare function linspace(start: number, stop: number, num?: number, endpoint?: boolean, { dtype, device }?: DTypeAndDevice): Array;
657
-
853
+ declare function linspace(start: number, stop: number, num?: number, endpoint?: boolean, {
854
+ dtype,
855
+ device
856
+ }?: DTypeAndDevice): Array;
857
+ /** Translate a `CompareOp` into an `AluExp` on two sub-expressions. */
858
+ declare namespace numpy_d_exports {
859
+ export { Array, ArrayLike, DType, abs, absolute, add, allclose, arange, argmax, argmin, array, astype, bool, clip, columnStack, complex64, concatenate, cos, diag, diagonal, divide, dot, dstack, e, equal, eulerGamma, exp, exp2, eye, flip, fliplr, flipud, float32, full, greater, greaterEqual, hstack, identity$1 as identity, inf, int32, less, lessEqual, linspace, log, log10, log2, matmul, max, maximum, mean, meshgrid, min, minimum, moveaxis, multiply, nan, ndim, negative, notEqual, ones, pad, permuteDims, pi, prod, ravel, reciprocal, reshape, scalar, shape$1 as shape, sin, size, square, stack, sum, tan, transpose, trueDivide, trunc, uint32, vdot, vecdot, vstack, where, zeros };
860
+ }
658
861
  declare const float32 = DType.Float32;
659
862
  declare const int32 = DType.Int32;
863
+ declare const uint32 = DType.Uint32;
660
864
  declare const bool = DType.Bool;
661
865
  declare const complex64 = DType.Complex64;
662
866
  /** Euler's constant, `e = 2.7182818284590...` */
@@ -712,16 +916,92 @@ declare const transpose: (x: ArrayLike, perm?: number[]) => Array;
712
916
  * length of the array and remaining dimensions.
713
917
  */
714
918
  declare const reshape: (x: ArrayLike, shape: number[]) => Array;
715
- declare const sum: (x: ArrayLike, axis?: number | number[]) => Array;
919
+ /** Move axes of an array to new positions. Other axes retain original order. */
716
920
  declare const moveaxis: (x: ArrayLike, src: number, dst: number) => Array;
717
- /** Return the number of dimensions of an array. */
921
+ /**
922
+ * Add padding (zeros) to an array.
923
+ *
924
+ * The `width` argument is either an integer or pair of integers, in which case
925
+ * all axes are padded with the same width. Or if it is an array of pairs, each
926
+ * pair specifies the padding for its corresponding axis.
927
+ */
928
+ declare const pad: (x: ArrayLike, width: number | [number, number] | [number, number][]) => Array;
929
+ /** Return the number of dimensions of an array. Does not consume array reference. */
718
930
  declare const ndim: (x: ArrayLike) => number;
719
- /** Return the shape of an array. */
720
- declare const shape: (x: ArrayLike) => number[];
721
- /** Return the number of elements in an array, optionally along an axis. */
931
+ /** Return the shape of an array. Does not consume array reference. */
932
+ declare const shape$1: (x: ArrayLike) => number[];
933
+ /**
934
+ * Return the number of elements in an array, optionally along an axis.
935
+ * Does not consume array reference.
936
+ */
722
937
  declare function size(a: ArrayLike, axis?: number): number;
938
+ /** Convert an array to a specified dtype. */
939
+ declare function astype(a: ArrayLike, dtype: DType): Array;
940
+ /** Sum of the elements of the array over a given axis, or axes. */
941
+ declare function sum(a: ArrayLike, axis?: number | number[], opts?: ReduceOpts): Array;
942
+ /** Product of the array elements over a given axis. */
943
+ declare function prod(a: ArrayLike, axis?: number | number[], opts?: ReduceOpts): Array;
944
+ /** Return the minimum of array elements along a given axis. */
945
+ declare function min(a: ArrayLike, axis?: number | number[], opts?: ReduceOpts): Array;
946
+ /** Return the maximum of array elements along a given axis. */
947
+ declare function max(a: ArrayLike, axis?: number | number[], opts?: ReduceOpts): Array;
948
+ /** Compute the average of the array elements along the specified axis. */
949
+ declare function mean(a: ArrayLike, axis?: number | number[], opts?: ReduceOpts): Array;
950
+ /**
951
+ * Returns the indices of the minimum values along an axis.
952
+ *
953
+ * By default, index is into the flatted array, otherwise it is along the
954
+ * specified axis.
955
+ */
956
+ declare function argmin(a: ArrayLike, axis?: number, opts?: ReduceOpts): Array;
957
+ /**
958
+ * Returns the indices of the maximum values along an axis.
959
+ *
960
+ * By default, index is into the flatted array, otherwise it is along the
961
+ * specified axis.
962
+ */
963
+ declare function argmax(a: ArrayLike, axis?: number, opts?: ReduceOpts): Array;
723
964
  /** Reverse the elements in an array along the given axes. */
724
965
  declare function flip(x: ArrayLike, axis?: number | number[]): Array;
966
+ /**
967
+ * Join a sequence of arrays along an existing axis.
968
+ *
969
+ * The arrays must have the same shape, except in the dimension corresponding to
970
+ * `axis` (the first, by default).
971
+ *
972
+ * No scalars can be passed to this function, as the axis is then ambiguous.
973
+ */
974
+ declare function concatenate(xs: Array[], axis?: number): Array;
975
+ /**
976
+ * Join a sequence of arrays along a new axis.
977
+ *
978
+ * The `axis` parameter specifies the index of the new axis in the dimensions of
979
+ * the result. For example, if `axis=0` it will be the first dimension and if
980
+ * `axis=-1` it will be the last dimension.
981
+ *
982
+ * All shapes must have the same shape.
983
+ */
984
+ declare function stack(xs: ArrayLike[], axis?: number): Array;
985
+ /**
986
+ * Horizontally stack arrays. Inputs are promoted to rank at least 1, then
987
+ * concatenated along axis 1 (if rank-2 or higher) or 0 (if rank-1).
988
+ */
989
+ declare function hstack(xs: ArrayLike[]): Array;
990
+ /**
991
+ * Vertically stack arrays. Inputs are promoted to rank at least 2, then
992
+ * concatenated along axis 0.
993
+ */
994
+ declare function vstack(xs: ArrayLike[]): Array;
995
+ /**
996
+ * Stack arrays depth-wise. Inputs are promoted to rank at least 3, then
997
+ * concatenated along axis 2.
998
+ */
999
+ declare function dstack(xs: ArrayLike[]): Array;
1000
+ /**
1001
+ * Stack arrays column-wise. Inputs are promoted to rank at least 2, then
1002
+ * concatenated along axis 1.
1003
+ */
1004
+ declare function columnStack(xs: ArrayLike[]): Array;
725
1005
  /** Flip an array vertically (axis=0). */
726
1006
  declare function flipud(x: ArrayLike): Array;
727
1007
  /** Flip an array horizontally (axis=1). */
@@ -738,8 +1018,6 @@ declare function ravel(a: ArrayLike): Array;
738
1018
  * This returns a view over the existing array.
739
1019
  */
740
1020
  declare function diagonal(a: ArrayLike, offset?: number, axis1?: number, axis2?: number): Array;
741
- /** Transposes a matrix or stack of matrices `x` (swap last two axes). */
742
- declare function matrixTranspose(x: ArrayLike): Array;
743
1021
  /**
744
1022
  * Extract a diagonal or construct a diagonal array.
745
1023
  *
@@ -749,15 +1027,15 @@ declare function matrixTranspose(x: ArrayLike): Array;
749
1027
  declare function diag(v: ArrayLike, k?: number): Array;
750
1028
  /** Return if two arrays are element-wise equal within a tolerance. */
751
1029
  declare function allclose(actual: Parameters<typeof array>[0], expected: Parameters<typeof array>[0], options?: {
752
- rtol?: number;
753
- atol?: number;
1030
+ rtol?: number;
1031
+ atol?: number;
754
1032
  }): boolean;
755
1033
  /** Matrix product of two arrays. */
756
- declare const matmul: (x: ArrayLike, y: ArrayLike) => Array;
1034
+ declare function matmul(x: ArrayLike, y: ArrayLike): Array;
757
1035
  /** Dot product of two arrays. */
758
- declare const dot: (x: ArrayLike, y: ArrayLike) => Array;
1036
+ declare function dot(x: ArrayLike, y: ArrayLike): Array;
759
1037
  /** Vector dot product of two arrays. */
760
- declare const vecdot: (x: ArrayLike, y: ArrayLike) => Array;
1038
+ declare function vecdot(x: ArrayLike, y: ArrayLike): Array;
761
1039
  /**
762
1040
  * Return the dot product of two vectors.
763
1041
  *
@@ -770,8 +1048,10 @@ declare function vdot(x: ArrayLike, y: ArrayLike): Array;
770
1048
  * Make N-D coordinate arrays for vectorized evaluations of N-D scalar/vector
771
1049
  * fields over N-D grids, given one-dimensional coordinate arrays x1, x2,…, xn.
772
1050
  */
773
- declare function meshgrid(xs: Array[], { indexing }?: {
774
- indexing?: "xy" | "ij";
1051
+ declare function meshgrid(xs: Array[], {
1052
+ indexing
1053
+ }?: {
1054
+ indexing?: "xy" | "ij";
775
1055
  }): Array[];
776
1056
  /**
777
1057
  * Clip (limit) the values in an array.
@@ -807,161 +1087,71 @@ declare function exp2(p: ArrayLike): Array;
807
1087
  declare function log2(x: ArrayLike): Array;
808
1088
  /** Return the base-10 logarithm of x, element-wise. */
809
1089
  declare function log10(x: ArrayLike): Array;
810
-
811
- type numpy_Array = Array;
812
- declare const numpy_Array: typeof Array;
813
- type numpy_ArrayLike = ArrayLike;
814
- type numpy_DType = DType;
815
- declare const numpy_DType: typeof DType;
816
- declare const numpy_abs: typeof abs;
817
- declare const numpy_absolute: typeof absolute;
818
- declare const numpy_add: typeof add;
819
- declare const numpy_allclose: typeof allclose;
820
- declare const numpy_arange: typeof arange;
821
- declare const numpy_array: typeof array;
822
- declare const numpy_bool: typeof bool;
823
- declare const numpy_clip: typeof clip;
824
- declare const numpy_complex64: typeof complex64;
825
- declare const numpy_cos: typeof cos;
826
- declare const numpy_diag: typeof diag;
827
- declare const numpy_diagonal: typeof diagonal;
828
- declare const numpy_divide: typeof divide;
829
- declare const numpy_dot: typeof dot;
830
- declare const numpy_e: typeof e;
831
- declare const numpy_equal: typeof equal;
832
- declare const numpy_eulerGamma: typeof eulerGamma;
833
- declare const numpy_exp: typeof exp;
834
- declare const numpy_exp2: typeof exp2;
835
- declare const numpy_eye: typeof eye;
836
- declare const numpy_flip: typeof flip;
837
- declare const numpy_fliplr: typeof fliplr;
838
- declare const numpy_flipud: typeof flipud;
839
- declare const numpy_float32: typeof float32;
840
- declare const numpy_full: typeof full;
841
- declare const numpy_greater: typeof greater;
842
- declare const numpy_greaterEqual: typeof greaterEqual;
843
- declare const numpy_inf: typeof inf;
844
- declare const numpy_int32: typeof int32;
845
- declare const numpy_less: typeof less;
846
- declare const numpy_lessEqual: typeof lessEqual;
847
- declare const numpy_linspace: typeof linspace;
848
- declare const numpy_log: typeof log;
849
- declare const numpy_log10: typeof log10;
850
- declare const numpy_log2: typeof log2;
851
- declare const numpy_matmul: typeof matmul;
852
- declare const numpy_matrixTranspose: typeof matrixTranspose;
853
- declare const numpy_maximum: typeof maximum;
854
- declare const numpy_meshgrid: typeof meshgrid;
855
- declare const numpy_minimum: typeof minimum;
856
- declare const numpy_moveaxis: typeof moveaxis;
857
- declare const numpy_multiply: typeof multiply;
858
- declare const numpy_nan: typeof nan;
859
- declare const numpy_ndim: typeof ndim;
860
- declare const numpy_negative: typeof negative;
861
- declare const numpy_notEqual: typeof notEqual;
862
- declare const numpy_ones: typeof ones;
863
- declare const numpy_permuteDims: typeof permuteDims;
864
- declare const numpy_pi: typeof pi;
865
- declare const numpy_ravel: typeof ravel;
866
- declare const numpy_reciprocal: typeof reciprocal;
867
- declare const numpy_reshape: typeof reshape;
868
- declare const numpy_scalar: typeof scalar;
869
- declare const numpy_shape: typeof shape;
870
- declare const numpy_sin: typeof sin;
871
- declare const numpy_size: typeof size;
872
- declare const numpy_square: typeof square;
873
- declare const numpy_sum: typeof sum;
874
- declare const numpy_tan: typeof tan;
875
- declare const numpy_transpose: typeof transpose;
876
- declare const numpy_trueDivide: typeof trueDivide;
877
- declare const numpy_trunc: typeof trunc;
878
- declare const numpy_vdot: typeof vdot;
879
- declare const numpy_vecdot: typeof vecdot;
880
- declare const numpy_where: typeof where;
881
- declare const numpy_zeros: typeof zeros;
882
- declare namespace numpy {
883
- export { numpy_Array as Array, type numpy_ArrayLike as ArrayLike, numpy_DType as DType, numpy_abs as abs, numpy_absolute as absolute, numpy_add as add, numpy_allclose as allclose, numpy_arange as arange, numpy_array as array, numpy_bool as bool, numpy_clip as clip, numpy_complex64 as complex64, numpy_cos as cos, numpy_diag as diag, numpy_diagonal as diagonal, numpy_divide as divide, numpy_dot as dot, numpy_e as e, numpy_equal as equal, numpy_eulerGamma as eulerGamma, numpy_exp as exp, numpy_exp2 as exp2, numpy_eye as eye, numpy_flip as flip, numpy_fliplr as fliplr, numpy_flipud as flipud, numpy_float32 as float32, numpy_full as full, numpy_greater as greater, numpy_greaterEqual as greaterEqual, identity$1 as identity, numpy_inf as inf, numpy_int32 as int32, numpy_less as less, numpy_lessEqual as lessEqual, numpy_linspace as linspace, numpy_log as log, numpy_log10 as log10, numpy_log2 as log2, numpy_matmul as matmul, numpy_matrixTranspose as matrixTranspose, numpy_maximum as maximum, numpy_meshgrid as meshgrid, numpy_minimum as minimum, numpy_moveaxis as moveaxis, numpy_multiply as multiply, numpy_nan as nan, numpy_ndim as ndim, numpy_negative as negative, numpy_notEqual as notEqual, numpy_ones as ones, numpy_permuteDims as permuteDims, numpy_pi as pi, numpy_ravel as ravel, numpy_reciprocal as reciprocal, numpy_reshape as reshape, numpy_scalar as scalar, numpy_shape as shape, numpy_sin as sin, numpy_size as size, numpy_square as square, numpy_sum as sum, numpy_tan as tan, numpy_transpose as transpose, numpy_trueDivide as trueDivide, numpy_trunc as trunc, numpy_vdot as vdot, numpy_vecdot as vecdot, numpy_where as where, numpy_zeros as zeros };
884
- }
885
-
886
- /** General class for pretty-printing expressions with indentation. */
887
- declare class PPrint {
888
- readonly indents: number[];
889
- readonly lines: string[];
890
- constructor(indents: number[], lines: string[]);
891
- /** Add a fixed amount of indentation to each line. */
892
- indent(spaces: number): PPrint;
893
- /** Concatenate two or more pretty-printed expressions. */
894
- concat(...items: PPrint[]): PPrint;
895
- /** Stack one block to the right of another one, sharing 1 common line. */
896
- stack(other: PPrint): PPrint;
897
- /** Combine this block of lines into a formatted string. */
898
- toString(): string;
899
- static pp(s: Stringable): PPrint;
900
- }
901
- interface Stringable {
902
- toString(): string;
903
- }
904
-
1090
+ //#endregion
1091
+ //#region src/frontend/jaxpr.d.ts
905
1092
  /** Variable in a Jaxpr expression. */
906
1093
  declare class Var {
907
- #private;
908
- readonly id: number;
909
- readonly aval: ShapedArray;
910
- constructor(aval: ShapedArray);
911
- toString(): string;
1094
+ #private;
1095
+ readonly id: number;
1096
+ readonly aval: ShapedArray;
1097
+ constructor(aval: ShapedArray);
1098
+ toString(): string;
912
1099
  }
913
1100
  /** Literal in a Jaxpr expression. Currently, only scalars are supported. */
914
1101
  declare class Lit {
915
- readonly dtype: DType;
916
- readonly value: number;
917
- readonly aval: ShapedArray;
918
- constructor(dtype: DType, value: number);
1102
+ readonly dtype: DType;
1103
+ readonly value: number;
1104
+ readonly aval: ShapedArray;
1105
+ constructor(dtype: DType, value: number);
919
1106
  }
920
1107
  type Atom = Var | Lit;
921
1108
  declare class VarPrinter {
922
- #private;
923
- names: Map<Var, string>;
924
- name(v: Var): string;
925
- nameType(v: Var): string;
1109
+ #private;
1110
+ names: Map<Var, string>;
1111
+ name(v: Var): string;
1112
+ nameType(v: Var): string;
926
1113
  }
927
1114
  /** A single statement / binding in a Jaxpr, in ANF form. */
928
1115
  declare class JaxprEqn {
929
- readonly primitive: Primitive;
930
- readonly inputs: Atom[];
931
- readonly params: Record<string, any>;
932
- readonly outBinders: Var[];
933
- constructor(primitive: Primitive, inputs: Atom[], params: Record<string, any>, outBinders: Var[]);
934
- pprint(usedVars?: Set<Var>, vp?: VarPrinter): PPrint;
935
- toString(): string;
1116
+ readonly primitive: Primitive;
1117
+ readonly inputs: Atom[];
1118
+ readonly params: Record<string, any>;
1119
+ readonly outBinders: Var[];
1120
+ constructor(primitive: Primitive, inputs: Atom[], params: Record<string, any>, outBinders: Var[]);
1121
+ pprint(usedVars?: Set<Var>, vp?: VarPrinter): PPrint;
1122
+ toString(): string;
936
1123
  }
937
1124
  /** Typed intermediate representation for traced computations. */
938
1125
  declare class Jaxpr implements FpHashable {
939
- #private;
940
- readonly inBinders: Var[];
941
- readonly eqns: JaxprEqn[];
942
- readonly outs: Atom[];
943
- constructor(inBinders: Var[], eqns: JaxprEqn[], outs: Atom[]);
944
- pprint(): PPrint;
945
- toString(): string;
946
- /**
947
- * Gets a hash of this Jaxpr.
948
- *
949
- * Var identity is not considered in the hash, so two Jaxprs with the same
950
- * order of assignments and operators but different variable IDs will resolve
951
- * to the same hash (and toString representation).
952
- */
953
- getHash(): bigint;
954
- hash(state: FpHash): void;
955
- /**
956
- * Produce a simplified Jaxpr with basic optimizations applied.
957
- * - Trim away unused variables.
958
- * - Fold away *1, *0, or +0 operations against literals.
959
- */
960
- simplify(): Jaxpr;
961
- /** Flattens nested JitCall in a Jaxpr. Useful for handling jit-of-jit. */
962
- flatten(): Jaxpr;
1126
+ #private;
1127
+ readonly inBinders: Var[];
1128
+ readonly eqns: JaxprEqn[];
1129
+ readonly outs: Atom[];
1130
+ constructor(inBinders: Var[], eqns: JaxprEqn[], outs: Atom[]);
1131
+ pprint(): PPrint;
1132
+ toString(): string;
1133
+ /**
1134
+ * Gets a hash of this Jaxpr.
1135
+ *
1136
+ * Var identity is not considered in the hash, so two Jaxprs with the same
1137
+ * order of assignments and operators but different variable IDs will resolve
1138
+ * to the same hash (and toString representation).
1139
+ */
1140
+ getHash(): bigint;
1141
+ hash(state: FpHash): void;
1142
+ /**
1143
+ * Produce a simplified Jaxpr with basic optimizations applied.
1144
+ * - Trim away unused variables.
1145
+ * - Fold away *1, *0, or +0 operations against literals.
1146
+ * - Remove no-op movement operations.
1147
+ */
1148
+ simplify(): Jaxpr;
1149
+ /** Flattens nested JitCall in a Jaxpr. Useful for handling jit-of-jit. */
1150
+ flatten(): Jaxpr;
1151
+ }
1152
+ declare namespace nn_d_exports {
1153
+ export { identity, logSigmoid, logSoftmax, logsumexp, oneHot, relu, relu6, sigmoid, silu, softSign, softmax, softplus, swish };
963
1154
  }
964
-
965
1155
  /**
966
1156
  * Rectified Linear Unit (ReLU) activation function:
967
1157
  * `relu(x) = max(x, 0)`.
@@ -1018,20 +1208,70 @@ declare const swish: typeof silu;
1018
1208
  declare function logSigmoid(x: ArrayLike): Array;
1019
1209
  /** Identity activation function. Returns the argument unmodified. */
1020
1210
  declare const identity: (x: ArrayLike) => Array;
1021
-
1022
- declare const nn_identity: typeof identity;
1023
- declare const nn_logSigmoid: typeof logSigmoid;
1024
- declare const nn_relu: typeof relu;
1025
- declare const nn_relu6: typeof relu6;
1026
- declare const nn_sigmoid: typeof sigmoid;
1027
- declare const nn_silu: typeof silu;
1028
- declare const nn_softSign: typeof softSign;
1029
- declare const nn_softplus: typeof softplus;
1030
- declare const nn_swish: typeof swish;
1031
- declare namespace nn {
1032
- export { nn_identity as identity, nn_logSigmoid as logSigmoid, nn_relu as relu, nn_relu6 as relu6, nn_sigmoid as sigmoid, nn_silu as silu, nn_softSign as softSign, nn_softplus as softplus, nn_swish as swish };
1211
+ /**
1212
+ * Softmax function. Computes the function which rescales elements to the range
1213
+ * [0, 1] such that the elements along `axis` sum to 1.
1214
+ *
1215
+ * If `axis` is not specified, it defaults to the last axis.
1216
+ *
1217
+ * Reference: https://en.wikipedia.org/wiki/Softmax_function
1218
+ */
1219
+ declare function softmax(x: ArrayLike, axis?: number | number[]): Array;
1220
+ /**
1221
+ * Log-Softmax function.
1222
+ *
1223
+ * Computes the logarithm of the `softmax` function, which rescales elements to
1224
+ * the range [-infinity, 0).
1225
+ *
1226
+ * If `axis` is not specified, it defaults to the last axis.
1227
+ */
1228
+ declare function logSoftmax(x: ArrayLike, axis?: number | number[]): Array;
1229
+ /**
1230
+ * Log-sum-exp reduction. Also a multivariate version of `softplus`.
1231
+ *
1232
+ * If no axis is specified, the reduction is performed over all elements. This
1233
+ * convention differs from `jax.nn.logSoftmax()`.
1234
+ *
1235
+ * Reference: https://en.wikipedia.org/wiki/LogSumExp
1236
+ */
1237
+ declare function logsumexp(x: ArrayLike, axis?: number | number[]): Array;
1238
+ /**
1239
+ * One-hot encodes the given indices.
1240
+ *
1241
+ * Each index in the integer input `x` is encoded as a vector of zeros of length
1242
+ * `numClasses`, with a 1 at the index position specified by its value.
1243
+ *
1244
+ * ```js
1245
+ * import { nn, numpy as np } from '@jax-js/jax';
1246
+ *
1247
+ * nn.oneHot(np.array([1, 1, 2], { dtype: np.int32 }), 3);
1248
+ * // Output:
1249
+ * // [[0, 1, 0],
1250
+ * // [0, 1, 0],
1251
+ * // [0, 0, 1]]
1252
+ * ```
1253
+ */
1254
+ declare function oneHot(x: Array, numClasses: number): Array;
1255
+ declare namespace random_d_exports {
1256
+ export { bits, key, split, uniform };
1033
1257
  }
1034
-
1258
+ /** Create a pseudo-random number generator (PRNG) key from 32-bit integer seed. */
1259
+ declare function key(seed: number): Array;
1260
+ /** Splits a PRNG key into `num` new keys by adding a leading axis. */
1261
+ declare function split(key: Array, num?: number | number[]): Array;
1262
+ /** Sample uniform bits in the form of unsigned integers. */
1263
+ declare function bits(key: Array, shape?: number[]): Array;
1264
+ /** Sample uniform random values in [minval, maxval) with given shape. */
1265
+ declare function uniform(key: Array, shape?: number[], {
1266
+ minval,
1267
+ maxval
1268
+ }?: {
1269
+ minval?: number;
1270
+ maxval?: number;
1271
+ }): Array;
1272
+ //#endregion
1273
+ //#region src/index.d.ts
1274
+ /** @inline */
1035
1275
  type WithArgsSubtype<F extends (args: any[]) => any, T> = Parameters<F> extends T ? F : never;
1036
1276
  /** Compute the forward-mode Jacobian-vector product for a function. */
1037
1277
  declare const jvp: <F extends (...args: any[]) => JsTree<Array>>(f: WithArgsSubtype<F, JsTree<ArrayLike>>, primals: MapJsTree<Parameters<F>, ArrayLike, ArrayLike>, tangents: MapJsTree<Parameters<F>, ArrayLike, ArrayLike>) => [ReturnType<F>, ReturnType<F>];
@@ -1041,9 +1281,9 @@ declare const vmap: <F extends (...args: any[]) => JsTree<Array>>(f: WithArgsSub
1041
1281
  declare const jacfwd: <F extends (x: Array) => Array>(f: F) => (...args: MapJsTree<Parameters<F>, ArrayLike, ArrayLike>) => ReturnType<F>;
1042
1282
  /** Construct a Jaxpr by dynamically tracing a function with example inputs. */
1043
1283
  declare const makeJaxpr: <F extends (...args: any[]) => JsTree<Array>>(f: WithArgsSubtype<F, JsTree<ArrayLike>>) => (...args: Parameters<F>) => {
1044
- jaxpr: Jaxpr;
1045
- consts: Array[];
1046
- treedef: JsTreeDef;
1284
+ jaxpr: Jaxpr;
1285
+ consts: Array[];
1286
+ treedef: JsTreeDef;
1047
1287
  };
1048
1288
  declare const jit: <F extends (...args: any[]) => JsTree<Array>>(f: WithArgsSubtype<F, JsTree<ArrayLike>>) => (...args: MapJsTree<Parameters<F>, ArrayLike, ArrayLike>) => ReturnType<F>;
1049
1289
  /**
@@ -1058,9 +1298,11 @@ declare const vjp: <F extends (...args: any[]) => JsTree<Array>>(f: WithArgsSubt
1058
1298
  * first argument.
1059
1299
  */
1060
1300
  declare const grad: <F extends (...args: any[]) => JsTree<Array>>(f: WithArgsSubtype<F, JsTree<ArrayLike>>) => (...primals: MapJsTree<Parameters<F>, ArrayLike, ArrayLike>) => MapJsTree<Parameters<F>[0], ArrayLike, Array>;
1301
+ /** Create a function that evaluates both `f` and the gradient of `f`. */
1302
+ declare const valueAndGrad: <F extends (...args: any[]) => JsTree<Array>>(f: WithArgsSubtype<F, JsTree<ArrayLike>>) => (...primals: MapJsTree<Parameters<F>, ArrayLike, ArrayLike>) => [ReturnType<F>, MapJsTree<Parameters<F>[0], ArrayLike, Array>];
1061
1303
  /** Compute the Jacobian evaluated row-by-row by reverse-mode AD. */
1062
1304
  declare const jacrev: typeof jacfwd;
1063
1305
  /** Compute the Jacobian with reverse-mode AD. Alias for `jacrev()`. */
1064
1306
  declare const jacobian: <F extends (x: Array) => Array>(f: F) => (...args: MapJsTree<Parameters<F>, ArrayLike, ArrayLike>) => ReturnType<F>;
1065
-
1066
- export { type Device, devices, grad, init, jacfwd, jacobian, jacrev, jit, jvp, linearize, makeJaxpr, nn, numpy, setDevice, tree, vjp, vmap };
1307
+ //#endregion
1308
+ export { type Device, devices, grad, init, jacfwd, jacobian, jacrev, jit, jvp, linearize, makeJaxpr, nn_d_exports as nn, numpy_d_exports as numpy, random_d_exports as random, setDevice, tree_d_exports as tree, valueAndGrad, vjp, vmap };