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