@jax-js/jax 0.0.1 → 0.0.3

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,24 +1,26 @@
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
 
23
+ /** @inline */
22
24
  type Pair = [number, number];
23
25
  /**
24
26
  * A multidimensional view into memory. An array can be thought of as the
@@ -30,49 +32,56 @@ type Pair = [number, number];
30
32
  * 2. Otherwise, look at this memory address: offset + ∑(strides[i] * dim[i]).
31
33
  */
32
34
  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;
35
+ #private;
36
+ /** The shape of the view (size of each dimension). */
37
+ readonly shape: number[];
38
+ /** How many indices to move in buffer for each hop in one dimension. */
39
+ readonly strides: number[];
40
+ /** Offset from the start of the buffer. */
41
+ readonly offset: number;
42
+ /** Masked out subarray where data is read. All other data is zeroed. */
43
+ readonly mask: Pair[] | null;
44
+ private constructor();
45
+ static create(shape: number[], strides?: number[], offset?: number, mask?: Pair[] | null): View;
46
+ get ndim(): number;
47
+ get size(): number;
48
+ /** Whether this is a default, contiguous, unaltered view of the data (identity). */
49
+ get contiguous(): boolean;
50
+ /** Return the range of data being indexed in this view, or [0, 0] if none. */
51
+ dataRange(): [number, number];
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,44 @@ 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;
112
+ /**
113
+ * Repeat data in each axis by a positive number of repetitions.
114
+ *
115
+ * - If `tile` is true (default): [1, 2, 3] -> [1, 2, 3, 1, 2, 3].
116
+ * - If `tile` is false: [1, 2, 3] -> [1, 1, 2, 2, 3, 3].
117
+ */
118
+ repeat(reps: number[], tile?: boolean): ShapeTracker;
119
+ /** Move axis i to axis j. */
120
+ moveaxis(i: number, j: number): ShapeTracker;
121
+ /** Like pad(), but allows for negative values. */
122
+ padOrShrink(arg: Pair[]): ShapeTracker;
103
123
  }
104
-
124
+ //#endregion
125
+ //#region src/utils.d.ts
126
+ /** @inline */
105
127
  type RecursiveArray<T> = T | RecursiveArray<T>[];
106
128
  interface FpHashable {
107
- hash(state: FpHash): void;
129
+ hash(state: FpHash): void;
108
130
  }
109
131
  /**
110
132
  * Polynomial hashes modulo p are good at avoiding collisions in expectation.
@@ -114,18 +136,24 @@ interface FpHashable {
114
136
  * See https://en.wikipedia.org/wiki/Lagrange%27s_theorem_(number_theory)
115
137
  */
116
138
  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;
139
+ #private;
140
+ value: bigint;
141
+ update(...values: (string | boolean | number | bigint | null | undefined | FpHashable)[]): this;
142
+ static hash(...values: (string | boolean | number | bigint | null | undefined | FpHashable)[]): bigint;
121
143
  }
122
-
144
+ /** Run a function while caching it inline inside a `Map`. */
145
+ //#endregion
146
+ //#region src/alu.d.ts
147
+ /** A numerical data type for array contents. */
123
148
  declare enum DType {
124
- Float32 = "float32",
125
- Int32 = "int32",
126
- Bool = "bool",
127
- Complex64 = "complex64"
149
+ Float32 = "float32",
150
+ Int32 = "int32",
151
+ Uint32 = "uint32",
152
+ Bool = "bool",
153
+ Float16 = "float16",
128
154
  }
155
+ /** @inline */
156
+ type DataArray = Float32Array<ArrayBuffer> | Int32Array<ArrayBuffer> | Uint32Array<ArrayBuffer> | Float16Array<ArrayBuffer>;
129
157
  /**
130
158
  * Mathematical expression on scalar values.
131
159
  *
@@ -134,94 +162,127 @@ declare enum DType {
134
162
  * graph rewrite engine.
135
163
  */
136
164
  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[];
165
+ #private;
166
+ readonly op: AluOp;
167
+ readonly dtype: DType;
168
+ readonly src: AluExp[];
169
+ readonly arg: any;
170
+ constructor(op: AluOp, dtype: DType, src: AluExp[], arg?: any);
171
+ static add(a: AluExp, b: AluExp): AluExp;
172
+ static sub(a: AluExp, b: AluExp): AluExp;
173
+ static mul(a: AluExp, b: AluExp): AluExp;
174
+ static idiv(a: AluExp, b: AluExp): AluExp;
175
+ static mod(a: AluExp, b: AluExp): AluExp;
176
+ static min(a: AluExp, b: AluExp): AluExp;
177
+ static max(a: AluExp, b: AluExp): AluExp;
178
+ static sin(a: AluExp): AluExp;
179
+ static cos(a: AluExp): AluExp;
180
+ static exp(a: AluExp): AluExp;
181
+ static log(a: AluExp): AluExp;
182
+ static sqrt(a: AluExp): AluExp;
183
+ static reciprocal(a: AluExp): AluExp;
184
+ static cast(dtype: DType, a: AluExp): AluExp;
185
+ static bitcast(dtype: DType, a: AluExp): AluExp;
186
+ static threefry2x32(k0: AluExp, k1: AluExp, c0: AluExp, c1: AluExp, mode?: "xor" | 0 | 1): AluExp;
187
+ static cmplt(a: AluExp, b: AluExp): AluExp;
188
+ static cmpne(a: AluExp, b: AluExp): AluExp;
189
+ static where(cond: AluExp, a: AluExp, b: AluExp): AluExp;
190
+ static const(dtype: DType, value: any): AluExp;
191
+ static special(dtype: DType, name: string, n: number): AluExp;
192
+ static variable(dtype: DType, name: string): AluExp;
193
+ static globalIndex(dtype: DType, gid: number, len: number, bufidx: AluExp): AluExp;
194
+ static globalView(dtype: DType, gid: number, st: ShapeTracker, indices: AluExp[]): AluExp;
195
+ static f32(value: number): AluExp;
196
+ static i32(value: number): AluExp;
197
+ static u32(value: number): AluExp;
198
+ static bool(value: boolean): AluExp;
199
+ static f16(value: number): AluExp;
200
+ not(): AluExp;
201
+ /** Compute a reasonable expression hash with low collision rate. */
202
+ getHash(): bigint;
203
+ hash(state: FpHash): void;
204
+ /** Substitute variables in this AluExp to values. */
205
+ substitute(variables: Record<string, AluExp>): AluExp;
206
+ /** Reindex gid values in this expression as needed. */
207
+ reindexGids(gidMap: Map<number, number>): AluExp;
208
+ get min(): number;
209
+ get max(): number;
210
+ /** Largest known integer that divides self. */
211
+ constFactor(): number;
212
+ /**
213
+ * Checks if divisible by an integer v and returns the quotient if it is, or
214
+ * `null` if it's not divisible.
215
+ */
216
+ divides(v: number): AluExp | null;
217
+ /**
218
+ * Get all expressions by deeply matching an operation.
219
+ *
220
+ * For example: `((2+(3*5))+4).splitOp(+) -> [2,(3*5),4]`.
221
+ */
222
+ splitOp(sep: AluOp): IterableIterator<AluExp>;
223
+ /**
224
+ * Simplify the expression by replacing any known patterns and deduping
225
+ * identical subexpressions.
226
+ */
227
+ simplify(cache?: Map<bigint, AluExp>): AluExp;
228
+ /** Resolve this to a value, or `undefined` if not possible. */
229
+ resolve(): any | undefined;
230
+ /**
231
+ * Evaluate the expression on CPU, returning the result.
232
+ *
233
+ * Typically you would compile the AluExp as a representation to a lower-level
234
+ * language. This is just to define the semantics and help debug.
235
+ *
236
+ * Note that the representation of Bool is as a number (0 or 1) here.
237
+ */
238
+ evaluate(context: Record<string, any>, globals?: (gid: number, bufidx: number) => any): number;
239
+ /** Get this expression in debug format as a string. */
240
+ toString(): string;
241
+ /** Generic fold() operation with a reducer over the expression tree. */
242
+ fold<T = void>(reducer: (exp: AluExp, mappedSrc: T[]) => T): T;
243
+ /** Check if any expression in the tree satisfies a predicate. */
244
+ some(predicate: (exp: AluExp) => boolean): boolean;
245
+ /** Rewrite the expression recursively using a visitor. */
246
+ rewrite(visitor: (exp: AluExp) => AluExp | undefined | null): AluExp;
247
+ /** Collect all nodes that satisfy a predicate. */
248
+ collect(predicate: (exp: AluExp) => boolean): AluExp[];
249
+ /** Produce a list of all distinct AluOp in this expression. */
250
+ distinctOps(): Set<AluOp>;
251
+ /** Rewrite GlobalView operations to GlobalIndex operations. */
252
+ rewriteGlobalViews(): AluExp;
201
253
  }
202
254
  /** Symbolic form for each mathematical operation. */
203
255
  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"
256
+ Add = "Add",
257
+ Sub = "Sub",
258
+ Mul = "Mul",
259
+ Idiv = "Idiv",
260
+ Mod = "Mod",
261
+ Min = "Min",
262
+ Max = "Max",
263
+ Sin = "Sin",
264
+ Cos = "Cos",
265
+ Exp = "Exp",
266
+ Log = "Log",
267
+ Sqrt = "Sqrt",
268
+ Reciprocal = "Reciprocal",
269
+ Cast = "Cast",
270
+ Bitcast = "Bitcast",
271
+ Cmplt = "Cmplt",
272
+ Cmpne = "Cmpne",
273
+ Where = "Where",
274
+ // Ternary operator: `cond ? a : b`
275
+ Threefry2x32 = "Threefry2x32",
276
+ // PRNG operation, arg = 'xor' | 0 | 1
277
+ Const = "Const",
278
+ // arg = value
279
+ Special = "Special",
280
+ // arg = [variable, n]
281
+ Variable = "Variable",
282
+ // arg = variable
283
+ GlobalIndex = "GlobalIndex",
284
+ // arg = [gid, len]; src = [bufidx]
285
+ GlobalView = "GlobalView",
225
286
  }
226
287
  /**
227
288
  * Description of a kernel to be compiled.
@@ -231,24 +292,26 @@ declare enum AluOp {
231
292
  * indexing into a buffer.
232
293
  */
233
294
  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;
295
+ /** Number of global arguments / arrays. */
296
+ readonly nargs: number;
297
+ /** Size of the result array in element count. */
298
+ readonly size: number;
299
+ /** Expression to be evaluated. */
300
+ readonly exp: AluExp;
301
+ /** Optional reduction to be performed. */
302
+ readonly reduction?: Reduction | undefined;
303
+ constructor(/** Number of global arguments / arrays. */
304
+ nargs: number, /** Size of the result array in element count. */
305
+ size: number, /** Expression to be evaluated. */
306
+ exp: AluExp, /** Optional reduction to be performed. */
307
+ reduction?: Reduction | undefined);
308
+ hash(state: FpHash): void;
309
+ pprint(): PPrint;
310
+ toString(): string;
311
+ /** The dtype of the values output by this kernel. */
312
+ get dtype(): DType;
313
+ /** The number of bytes in the output array when evaluating this kernel. */
314
+ get bytes(): number;
252
315
  }
253
316
  /**
254
317
  * Description of a reduction.
@@ -266,42 +329,30 @@ declare class Kernel implements FpHashable {
266
329
  * at this level since they depend on GPU, versus CPU or Wasm.
267
330
  */
268
331
  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;
332
+ /** Data type of the values being reduced over. */
333
+ readonly dtype: DType;
334
+ /** Operation to perform. Only ops in `AluGroup.Reduce` are supported. */
335
+ readonly op: AluOp;
336
+ /** Size of the reduction axis. */
337
+ readonly size: number;
338
+ /** Follow-up expression defined with the "acc" variable, defaults to identity. */
339
+ readonly epilogue: AluExp;
340
+ constructor(/** Data type of the values being reduced over. */
341
+ dtype: DType, /** Operation to perform. Only ops in `AluGroup.Reduce` are supported. */
342
+ op: AluOp, /** Size of the reduction axis. */
343
+ size: number, /** Follow-up expression defined with the "acc" variable, defaults to identity. */
344
+ epilogue?: AluExp);
345
+ hash(state: FpHash): void;
346
+ toString(): string;
347
+ /** Get the identity for this reduction operation. */
348
+ get identity(): any;
349
+ /** Evaluate this operation on CPU. */
350
+ evaluate(...values: any): any;
291
351
  }
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
-
304
- type Device = "cpu" | "webgpu";
352
+ /** Expression for accessing `indices` in input array with the given shape. */
353
+ //#endregion
354
+ //#region src/backend.d.ts
355
+ type Device = "cpu" | "wasm" | "webgpu";
305
356
  declare const devices: Device[];
306
357
  /** Set the default device backend (must be initialized). */
307
358
  declare function setDevice(device: Device): void;
@@ -313,75 +364,78 @@ declare function setDevice(device: Device): void;
313
364
  * available backends.
314
365
  */
315
366
  declare function init(...devicesToInit: Device[]): Promise<Device[]>;
367
+ /** Retrieve a backend that has been initialized. */
368
+
316
369
  /** Unique identifier for an allocated, on-device buffer. */
317
370
  type Slot = number;
318
371
  /** A device backend. */
319
372
  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;
373
+ /** The name of the backend as a string. */
374
+ readonly type: Device;
375
+ /** Maximum number of arguments per dispatched kernel. */
376
+ readonly maxArgs: number;
377
+ /** Allocate a new slot with reference count 1. */
378
+ malloc(size: number, initialData?: Uint8Array): Slot;
379
+ /** Increment the reference count of the slot. */
380
+ incRef(slot: Slot): void;
381
+ /**
382
+ * Decrement the reference count of the slot. If the reference count reaches
383
+ * zero, it is freed. This should throw if the slot was already freed.
384
+ */
385
+ decRef(slot: Slot): void;
386
+ /** Read a range of bytes from a buffer. */
387
+ read(slot: Slot, start?: number, count?: number): Promise<Uint8Array<ArrayBuffer>>;
388
+ /** Read a range of bytes from a buffer, blocking variant. */
389
+ readSync(slot: Slot, start?: number, count?: number): Uint8Array<ArrayBuffer>;
390
+ /** Prepare an expression to be executed later. */
391
+ prepare(kernel: Kernel): Promise<Executable>;
392
+ /** Prepare an expression to be executed later, blocking variant. */
393
+ prepareSync(kernel: Kernel): Executable;
394
+ /**
395
+ * Run a backend operation that was previously prepared.
396
+ *
397
+ * The operation may not run immediately, but operations are guaranteed to run
398
+ * in the dispatch order. Also, `read()` will wait for all pending operations
399
+ * on that slot to finish.
400
+ */
401
+ dispatch(exe: Executable, inputs: Slot[], outputs: Slot[]): void;
349
402
  }
350
403
  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);
404
+ readonly kernel: Kernel;
405
+ /** Extra data specific to the backend running this kernel. */
406
+ readonly data: T;
407
+ constructor(kernel: Kernel, /** Extra data specific to the backend running this kernel. */
408
+ data: T);
409
+ }
410
+ declare namespace tree_d_exports {
411
+ export { JsTree, JsTreeDef, MapJsTree, NodeType, dispose, flatten, leaves, map, ref, structure, unflatten };
357
412
  }
358
-
359
- /** @file Utilities for working with tree-like container data structures ("pytrees"). */
360
413
  declare enum NodeType {
361
- Array = "Array",
362
- Object = "Object",
363
- Leaf = "Leaf"
414
+ Array = "Array",
415
+ Object = "Object",
416
+ Leaf = "Leaf",
364
417
  }
418
+ /** Analog to the JAX "pytree" object, but for JavaScript. */
365
419
  type JsTree<T> = T | JsTree<T>[] | {
366
- [key: string]: JsTree<T>;
420
+ [key: string]: JsTree<T>;
367
421
  };
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>;
372
- };
373
- /** Analog to the JAX "pytree" object, but for JavaScript. */
422
+ type Same<X, Y> = (<T>() => T extends X ? 1 : 2) extends (<T>() => T extends Y ? 1 : 2) ? true : false;
423
+ type MappedJsTree<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> };
424
+ /** @ignore Convert a subtype of JsTree<A> into a JsTree<B>, with the same structure. */
425
+ type MapJsTree<T, A, B> = Same<A, B> extends true ? T : MappedJsTree<T, A, B>;
426
+ /** Represents the structure of a JsTree. */
374
427
  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;
428
+ readonly nodeType: NodeType;
429
+ readonly nodeMetadata: any;
430
+ readonly childTreedefs: JsTreeDef[];
431
+ static leaf: JsTreeDef;
432
+ constructor(nodeType: NodeType, nodeMetadata: any,
433
+ // Must be comparable with deepEqual.
434
+ childTreedefs: JsTreeDef[]);
435
+ /** Returns a string representation of this tree definition. */
436
+ toString(root?: boolean): string;
437
+ /** Compare this tree definition with another. */
438
+ equals(other: JsTreeDef): boolean;
385
439
  }
386
440
  /** Flatten a structured object, returning the tree definition. */
387
441
  declare function flatten<T>(tree: JsTree<T>): [T[], JsTreeDef];
@@ -391,151 +445,324 @@ declare function leaves<T>(tree: JsTree<T>): T[];
391
445
  declare function structure<T>(tree: JsTree<T>): JsTreeDef;
392
446
  /** Reconstruct a structured object from the flattened representation. */
393
447
  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 };
448
+ /** Maps a multi-input function over pytree args to produce a new pytree. */
449
+ declare function map<T, U, Tree extends JsTree<T>>(fn: (...args: T[]) => U, tree: Tree, ...rest: Tree[]): MapJsTree<Tree, T, U>;
450
+ /** Take a reference of every array in a tree. */
451
+ declare function ref<Tree extends JsTree<Array>>(tree: Tree): Tree;
452
+ /** Dispose every array in a tree. */
453
+ declare function dispose<Tree extends JsTree<Array>>(tree: Tree | null | undefined): void;
454
+ //#endregion
455
+ //#region src/frontend/convolution.d.ts
456
+ /** Definition of a general dilated convolution. Should be valid on creation. */
457
+ interface ConvParams {
458
+ strides: number[];
459
+ padding: [number, number][];
460
+ lhsDilation: number[];
461
+ rhsDilation: number[];
407
462
  }
463
+ /**
464
+ * Check that the shapes and parameters passed to convolution are valid.
465
+ *
466
+ * If the check succeeds, returns the output shape.
467
+ */
408
468
 
409
- /** @file Core library internals and interpreter stack, based on Autodidax. */
410
-
469
+ //#endregion
470
+ //#region src/frontend/core.d.ts
471
+ /**
472
+ * Frontend primitive operations, which are lowered into Kernel objects before
473
+ * being dispatched to the backend.
474
+ *
475
+ * Any operation between arrays can be described in these parts. This is also
476
+ * the set of primitives that can occur in Jaxpr programs, and the level at
477
+ * which transformations like vmap, grad, and jvp occur. They are loosely based
478
+ * on [XLA](https://openxla.org/xla/operation_semantics).
479
+ *
480
+ * All n-ary operations support broadcasting, with NumPy semantics.
481
+ */
411
482
  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"
483
+ Add = "add",
484
+ Mul = "mul",
485
+ Idiv = "idiv",
486
+ Neg = "neg",
487
+ Reciprocal = "reciprocal",
488
+ StopGradient = "stop_gradient",
489
+ Cast = "cast",
490
+ Bitcast = "bitcast",
491
+ RandomBits = "random_bits",
492
+ Sin = "sin",
493
+ Cos = "cos",
494
+ Exp = "exp",
495
+ Log = "log",
496
+ Sqrt = "sqrt",
497
+ Min = "min",
498
+ Max = "max",
499
+ Reduce = "reduce",
500
+ Dot = "dot",
501
+ // sum(x*y, axis=-1)
502
+ Conv = "conv",
503
+ // see lax.conv_general_dilated
504
+ Pool = "pool",
505
+ PoolTranspose = "pool_transpose",
506
+ Compare = "compare",
507
+ Where = "where",
508
+ Transpose = "transpose",
509
+ Broadcast = "broadcast",
510
+ Reshape = "reshape",
511
+ Flip = "flip",
512
+ Shrink = "shrink",
513
+ Pad = "pad",
514
+ Gather = "gather",
515
+ JitCall = "jit_call",
431
516
  }
517
+ interface PrimitiveParamsImpl extends Record<Primitive, Record<string, any>> {
518
+ [Primitive.Cast]: {
519
+ dtype: DType;
520
+ };
521
+ [Primitive.Bitcast]: {
522
+ dtype: DType;
523
+ };
524
+ [Primitive.Reduce]: {
525
+ op: AluOp;
526
+ axis: number[];
527
+ };
528
+ [Primitive.Conv]: ConvParams;
529
+ [Primitive.Pool]: {
530
+ window: number[];
531
+ strides: number[];
532
+ };
533
+ [Primitive.PoolTranspose]: {
534
+ inShape: number[];
535
+ window: number[];
536
+ strides: number[];
537
+ };
538
+ [Primitive.Compare]: {
539
+ op: CompareOp;
540
+ };
541
+ [Primitive.Transpose]: {
542
+ perm: number[];
543
+ };
544
+ [Primitive.Broadcast]: {
545
+ shape: number[];
546
+ axis: number[];
547
+ };
548
+ [Primitive.RandomBits]: {
549
+ shape: number[];
550
+ mode: "xor" | 0 | 1;
551
+ };
552
+ [Primitive.Reshape]: {
553
+ shape: number[];
554
+ };
555
+ [Primitive.Flip]: {
556
+ axis: number[];
557
+ };
558
+ [Primitive.Shrink]: {
559
+ slice: Pair[];
560
+ };
561
+ [Primitive.Pad]: {
562
+ width: Pair[];
563
+ };
564
+ [Primitive.Gather]: {
565
+ axis: number[];
566
+ outDim: number;
567
+ };
568
+ [Primitive.JitCall]: {
569
+ jaxpr: Jaxpr;
570
+ numConsts: number;
571
+ };
572
+ }
573
+ /** Type of parameters taken by each primitive. */
574
+ type PrimitiveParams<T extends Primitive> = T extends keyof PrimitiveParamsImpl ? PrimitiveParamsImpl[T] : Record<string, never>;
575
+ declare enum CompareOp {
576
+ Greater = "greater",
577
+ Less = "less",
578
+ Equal = "equal",
579
+ NotEqual = "not_equal",
580
+ GreaterEqual = "greater_equal",
581
+ LessEqual = "less_equal",
582
+ }
583
+ /** @inline */
584
+ type ReduceOpts = {
585
+ keepDims?: boolean;
586
+ };
432
587
  type MainTrace = {
433
- level: number;
434
- traceType: new (main: MainTrace) => Trace;
435
- globalData: any | null;
588
+ level: number;
589
+ traceType: new (main: MainTrace) => Trace;
590
+ globalData: any | null;
436
591
  };
592
+ /**
593
+ * Push an interpreter onto the trace stack. Use this like:
594
+ * `using main = newMain(...);`
595
+ */
596
+
437
597
  type TracerValue = Tracer | number | boolean;
438
598
  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[];
599
+ readonly main: MainTrace;
600
+ constructor(main: MainTrace);
601
+ abstract pure(val: TracerValue): Tracer;
602
+ abstract lift(val: Tracer): Tracer;
603
+ abstract processPrimitive<P extends Primitive>(primitive: P, tracers: Tracer[], params: PrimitiveParams<P>): Tracer[];
444
604
  }
445
605
  interface AbstractValue {
446
- shape: number[];
447
- dtype: DType;
606
+ shape: number[];
607
+ dtype: DType;
448
608
  }
449
609
  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;
610
+ /** @ignore */
611
+ readonly _trace: Trace;
612
+ constructor(trace: Trace);
613
+ abstract get aval(): AbstractValue;
614
+ abstract toString(): string;
615
+ /**
616
+ * Access an array by reference, incrementing the reference count.
617
+ *
618
+ * jax-js handles freeing arrays by using "move" semantics, like in Rust/C++.
619
+ * Whenever you pass an array into a function, that function should consume
620
+ * the array, and it will no longer be usable. For example, if you had:
621
+ *
622
+ * ```
623
+ * const x = np.array([1, 2, 3]);
624
+ * const y = np.add(x, x);
625
+ * ```
626
+ *
627
+ * The second line does not work because the first parameter consumes `x`, and
628
+ * then the second parameter will already have been freed / disposed.
629
+ *
630
+ * To fix this, you can write:
631
+ *
632
+ * ```
633
+ * const y = np.add(x.ref, x);
634
+ * ```
635
+ *
636
+ * Under the hood, every access to `.ref` increments the internal reference
637
+ * count of the array. The reference count starts at 1. When it hits 0, the
638
+ * memory behind the array is freed.
639
+ */
640
+ abstract get ref(): this;
641
+ /**
642
+ * Manually decrement the reference count of the array.
643
+ *
644
+ * Arrays are created with reference count 1. Whenever it is used as argument
645
+ * to a function or other operation, it is disposed (i.e., reference count
646
+ * decreases by 1) automatically. Whenever a `.ref` is created, the reference
647
+ * count increases.
648
+ *
649
+ * You generally don't need to call this function directly since arrays are
650
+ * automatically disposed after being passed into an operation. One common
651
+ * exception is when writing a function and ignoring one of its arguments. In
652
+ * that case, by convention you should dispose of that argument manually.
653
+ *
654
+ * ```
655
+ * function myCustomOperation(a: np.Array, b: np.Array) {
656
+ * b.dispose(); // Needed to satisfy "move" rules.
657
+ * return a.add(1);
658
+ * }
659
+ * ```
660
+ */
661
+ abstract dispose(): void;
662
+ get shape(): number[];
663
+ get size(): number;
664
+ get dtype(): DType;
665
+ get ndim(): number;
666
+ /** @ignore */
667
+ fullLower(): Tracer;
668
+ neg(): this;
669
+ add(other: this | TracerValue): this;
670
+ mul(other: this | TracerValue): this;
671
+ greater(other: this | TracerValue): this;
672
+ less(other: this | TracerValue): this;
673
+ equal(other: this | TracerValue): this;
674
+ notEqual(other: this | TracerValue): this;
675
+ greaterEqual(other: this | TracerValue): this;
676
+ lessEqual(other: this | TracerValue): this;
677
+ /** Sum of the elements of the array over a given axis, or axes. */
678
+ sum(axis?: number | number[], opts?: ReduceOpts): this;
679
+ /** Product of the array elements over a given axis. */
680
+ prod(axis?: number | number[], opts?: ReduceOpts): this;
681
+ /** Compute the average of the array elements along the specified axis. */
682
+ mean(axis?: number | number[], opts?: ReduceOpts): this;
683
+ /** Permute the dimensions of an array. Defaults to reversing the axis order. */
684
+ transpose(perm?: number[]): this;
685
+ /**
686
+ * Give a new shape to an array without changing its data.
687
+ *
688
+ * One shape dimension can be -1. In this case, the value is inferred from the
689
+ * length of the array and remaining dimensions.
690
+ */
691
+ reshape(shape: number | number[]): this;
692
+ /** Copy the array and cast to a specified dtype. */
693
+ astype(dtype: DType): this;
694
+ /** Subtract an array from this one. */
695
+ sub(other: this | TracerValue): this;
696
+ /** Divide an array by this one. */
697
+ div(other: this | TracerValue): this;
698
+ /** Return specified diagonals. See `numpy.diagonal` for full docs. */
699
+ diagonal(offset?: number, axis1?: number, axis2?: number): this;
700
+ /** Flatten the array without changing its data. */
701
+ flatten(): this;
702
+ /** Flatten the array without changing its data. */
703
+ ravel(): this;
704
+ /**
705
+ * Iterate over the first dimension of this array, returning slices.
706
+ *
707
+ * This can be used to destructure arrays. For example:
708
+ *
709
+ * ```js
710
+ * let x = np.array([[1, 2], [3, 4]]);
711
+ * let [a, b] = x;
712
+ * console.log(a.js()); // [1, 2]
713
+ * console.log(b.js()); // [3, 4]
714
+ * ```
715
+ */
716
+ [Symbol.iterator](): IterableIterator<this>;
717
+ /**
718
+ * Slice an array along one or more axes.
719
+ *
720
+ * This is the equivalent of slicing in Python, e.g. `x[1:3, 2, :, None]`. To
721
+ * mimic this in JavaScript, we would write:
722
+ *
723
+ * ```js
724
+ * x.slice([1, 3], 2, [], null);
725
+ * ```
726
+ *
727
+ * The `slice` method accepts a variable number of arguments, each of which
728
+ * can be a number, an empty array, a single-element array, a two-element
729
+ * array, or `null`. The arguments are interpreted as follows:
730
+ *
731
+ * - A number `n` means to access the `n`-th element along that axis, removing
732
+ * that axis from the resulting shape.
733
+ * - An empty array `[]` means to keep that axis as-is, like `:` in Python.
734
+ * - A single-element array `[i]` means to start slicing from index `i`
735
+ * (inclusive) to the end of the axis, like `x[i:]`.
736
+ * - A two-element array `[i, j]` means to slice from index `i` (inclusive)
737
+ * to index `j` (exclusive), like `x[i:j]`.
738
+ * - `null` means to add a new axis at that position, like `np.newaxis`.
739
+ *
740
+ * Like in Python, negative indices are supported, which count from the end of
741
+ * the axis. For example, `-1` means the last element.
742
+ *
743
+ * Strided slices are not yet implemented, so you cannot write `x[::2]` or
744
+ * similar.
745
+ *
746
+ * Advanced indexing by integer arrays is also supported. This translates to
747
+ * the "gather" primitive, and it allows you to access specific elements of
748
+ * the array by integer indices stored in another array.
749
+ */
750
+ slice(...index: (number | [] | [number] | Pair | null | Tracer)[]): this;
527
751
  }
528
752
  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;
753
+ readonly shape: number[];
754
+ readonly dtype: DType;
755
+ constructor(shape: number[], dtype: DType);
756
+ static fromAval(aval: AbstractValue): ShapedArray;
757
+ get ndim(): number;
758
+ toString(): string;
759
+ equals(other: ShapedArray): boolean;
536
760
  }
537
-
761
+ //#endregion
762
+ //#region src/frontend/array.d.ts
538
763
  type ArrayLike = Array | number | boolean;
764
+ /** Version of pureArray with fudged types. */
765
+
539
766
  /**
540
767
  * An executable operation that will be dispatched to the backend.
541
768
  *
@@ -543,22 +770,23 @@ type ArrayLike = Array | number | boolean;
543
770
  * operation is dispatched, the references should be released.
544
771
  */
545
772
  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;
773
+ #private;
774
+ readonly backend: Backend;
775
+ readonly kernel: Kernel;
776
+ readonly inputs: Slot[];
777
+ readonly outputs: Slot[];
778
+ prepared: Executable | null;
779
+ submitted: boolean;
780
+ constructor(backend: Backend, kernel: Kernel, inputs: Slot[], outputs: Slot[]);
781
+ updateRc(delta: number): void;
782
+ prepare(): Promise<void>;
783
+ prepareSync(): void;
784
+ submit(): void;
558
785
  }
786
+ /** @inline */
559
787
  type DTypeAndDevice = {
560
- dtype?: DType;
561
- device?: Device;
788
+ dtype?: DType;
789
+ device?: Device;
562
790
  };
563
791
  /**
564
792
  * A multidimensional numeric array with data stored on CPU or GPU.
@@ -571,64 +799,120 @@ type DTypeAndDevice = {
571
799
  * "Array" type by name.
572
800
  */
573
801
  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;
802
+ #private;
803
+ id: number;
804
+ /**
805
+ * @ignore
806
+ * Constructs an array from source, shape and backend. Note that if the source
807
+ * is a backend `Slot`, this constructor _takes ownership_ of the slot. It
808
+ * will be freed when the array is disposed.
809
+ */
810
+ constructor(source: AluExp | Slot, st: ShapeTracker, dtype: DType, backend: Backend, pending?: Iterable<PendingExecute> | null);
811
+ /** @ignore */
812
+ get aval(): ShapedArray;
813
+ /** Return a simple string representation of the array's dimensions. */
814
+ toString(): string;
815
+ get device(): Device;
816
+ get ref(): this;
817
+ dispose(): void;
818
+ /**
819
+ * Convert this array into a primitive value.
820
+ *
821
+ * This only works for scalars (0-dimensional arrays). It lets you get values
822
+ * "out" of the JAX system. For instance, if `x = np.array(5)`, then you can
823
+ * evaluate `x + 1` and `x ** 2` to get `6` and `25`, respectively.
824
+ *
825
+ * This method is also called for `==` equality.
826
+ */
827
+ [Symbol.toPrimitive](): any;
828
+ /** Realize the array and return it as data. */
829
+ data(): Promise<DataArray>;
830
+ /**
831
+ * Wait for this array to finish evaluation.
832
+ *
833
+ * Operations and data loading in jax-js are lazy, so this function ensures
834
+ * that pending operations are dispatched and fully executed before it
835
+ * returns.
836
+ *
837
+ * If you are mapping from `data()` or `dataSync()`, it will also trigger
838
+ * dispatch of operations as well.
839
+ */
840
+ wait(): Promise<Array>;
841
+ /**
842
+ * Realize the array and return it as data. This is a sync variant and not
843
+ * recommended for performance reasons, as it will block rendering.
844
+ */
845
+ dataSync(): DataArray;
846
+ /**
847
+ * Convert this array into a JavaScript object.
848
+ *
849
+ * This is a blocking operation that will compile all of the shaders and wait
850
+ * for execution to complete, synchronously. No other JavaScript code on the
851
+ * site will be run during shader execution.
852
+ *
853
+ * To avoid blocking, prefer `jsAsync()` when possible.
854
+ */
855
+ js(): any;
856
+ /** Convert this array into a JavaScript object, asynchronously. */
857
+ jsAsync(): Promise<any>;
858
+ /**
859
+ * Copy an element of an array to a numeric scalar and return it.
860
+ *
861
+ * Throws an error if the array does not have a single element. The array must
862
+ * either be rank-0, or all dimensions of the shape are 1.
863
+ */
864
+ item(): number;
865
+ /** @private Internal plumbing method for Array / Tracer ops. */
866
+ static _implRules(): typeof implRules;
867
+ _realizeSource(): number;
609
868
  }
610
869
  /** Construct an array from a single scalar constant. */
611
- declare function scalar(value: number | boolean, { dtype, device }?: DTypeAndDevice): Array;
870
+ declare function scalar(value: number | boolean, {
871
+ dtype,
872
+ device
873
+ }?: DTypeAndDevice): Array;
612
874
  /** 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[];
875
+ declare function array(values: Array | Float16Array<ArrayBuffer> | Float32Array<ArrayBuffer> | Int32Array<ArrayBuffer> | Uint32Array<ArrayBuffer> | RecursiveArray<number> | RecursiveArray<boolean>, {
876
+ shape,
877
+ dtype,
878
+ device
879
+ }?: {
880
+ shape?: number[];
615
881
  } & DTypeAndDevice): Array;
616
- type ImplRule = (tracers: Array[], params: any) => Array[];
882
+ /** If x is a value, lift it into an array, otherwise leave it be. */
883
+
884
+ type ImplRule<P extends Primitive> = (tracers: Array[], params: PrimitiveParams<P>) => Array[];
885
+ declare const implRules: { [P in Primitive]: ImplRule<P> };
617
886
  /** Return a new array of given shape and type, filled with zeros. */
618
- declare function zeros(shape: number[], { dtype, device }?: DTypeAndDevice): Array;
887
+ declare function zeros(shape: number[], {
888
+ dtype,
889
+ device
890
+ }?: DTypeAndDevice): Array;
619
891
  /** Return a new array of given shape and type, filled with ones. */
620
- declare function ones(shape: number[], { dtype, device }?: DTypeAndDevice): Array;
892
+ declare function ones(shape: number[], {
893
+ dtype,
894
+ device
895
+ }?: DTypeAndDevice): Array;
621
896
  /** 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;
897
+ declare function full(shape: number[], fillValue: number | boolean | Array, {
898
+ dtype,
899
+ device
900
+ }?: DTypeAndDevice): Array;
623
901
  /**
624
902
  * Create an identity matrix.
625
903
  *
626
904
  * If numCols is not provided, it defaults to numRows, i.e., a square identity
627
905
  * matrix with ones on the diagonal.
628
906
  */
629
- declare function eye(numRows: number, numCols?: number, { dtype, device }?: DTypeAndDevice): Array;
907
+ declare function eye(numRows: number, numCols?: number, {
908
+ dtype,
909
+ device
910
+ }?: DTypeAndDevice): Array;
630
911
  /** Return the identity array, with ones on the main diagonal. */
631
- declare function identity$1(n: number, { dtype, device }?: DTypeAndDevice): Array;
912
+ declare function identity$1(n: number, {
913
+ dtype,
914
+ device
915
+ }?: DTypeAndDevice): Array;
632
916
  /**
633
917
  * Return evenly spaced values within a given interval.
634
918
  *
@@ -643,7 +927,10 @@ declare function identity$1(n: number, { dtype, device }?: DTypeAndDevice): Arra
643
927
  * Defaults to an integer data type. This can produce unintended results when
644
928
  * using a non-integer step, so prefer linspace() in those cases.
645
929
  */
646
- declare function arange(start: number, stop?: number, step?: number, { dtype, device }?: DTypeAndDevice): Array;
930
+ declare function arange(start: number, stop?: number, step?: number, {
931
+ dtype,
932
+ device
933
+ }?: DTypeAndDevice): Array;
647
934
  /**
648
935
  * Return evenly spaced numbers over a specified interval.
649
936
  *
@@ -653,12 +940,18 @@ declare function arange(start: number, stop?: number, step?: number, { dtype, de
653
940
  *
654
941
  * The default data type is Float32. Use arange() for integer steps.
655
942
  */
656
- declare function linspace(start: number, stop: number, num?: number, endpoint?: boolean, { dtype, device }?: DTypeAndDevice): Array;
657
-
943
+ declare function linspace(start: number, stop: number, num?: number, endpoint?: boolean, {
944
+ dtype,
945
+ device
946
+ }?: DTypeAndDevice): Array;
947
+ declare namespace numpy_d_exports {
948
+ export { Array, ArrayLike, DType, abs, absolute, add, allclose, arange, argmax, argmin, array, astype, bool, clip, columnStack, concatenate, cos, cosh, diag, diagonal, divide, dot, dstack, e, equal, eulerGamma, exp, exp2, eye, flip, fliplr, flipud, float16, float32, full, fullLike, 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, onesLike, pad, permuteDims, pi, prod, ravel, reciprocal, reshape, scalar, shape$1 as shape, sin, sinh, size, sqrt, square, stack, sum, tan, tanh, transpose, trueDivide, trunc, uint32, vdot, vecdot, vstack, where, zeros, zerosLike };
949
+ }
658
950
  declare const float32 = DType.Float32;
659
951
  declare const int32 = DType.Int32;
952
+ declare const uint32 = DType.Uint32;
660
953
  declare const bool = DType.Bool;
661
- declare const complex64 = DType.Complex64;
954
+ declare const float16 = DType.Float16;
662
955
  /** Euler's constant, `e = 2.7182818284590...` */
663
956
  declare const e: number;
664
957
  /** Euler-Mascheroni constant, `γ = 0.5772156649...` */
@@ -685,6 +978,8 @@ declare const cos: (x: ArrayLike) => Array;
685
978
  declare const exp: (x: ArrayLike) => Array;
686
979
  /** Calculate the natural logarithm of all elements in the input array. */
687
980
  declare const log: (x: ArrayLike) => Array;
981
+ /** Calculate the square root of all elements in the input array. */
982
+ declare const sqrt: (x: ArrayLike) => Array;
688
983
  /** Return element-wise minimum of the input arrays. */
689
984
  declare const minimum: (x: ArrayLike, y: ArrayLike) => Array;
690
985
  /** Return element-wise maximum of the input arrays. */
@@ -712,16 +1007,98 @@ declare const transpose: (x: ArrayLike, perm?: number[]) => Array;
712
1007
  * length of the array and remaining dimensions.
713
1008
  */
714
1009
  declare const reshape: (x: ArrayLike, shape: number[]) => Array;
715
- declare const sum: (x: ArrayLike, axis?: number | number[]) => Array;
1010
+ /** Move axes of an array to new positions. Other axes retain original order. */
716
1011
  declare const moveaxis: (x: ArrayLike, src: number, dst: number) => Array;
717
- /** Return the number of dimensions of an array. */
1012
+ /**
1013
+ * Add padding (zeros) to an array.
1014
+ *
1015
+ * The `width` argument is either an integer or pair of integers, in which case
1016
+ * all axes are padded with the same width. Or if it is an array of pairs, each
1017
+ * pair specifies the padding for its corresponding axis.
1018
+ */
1019
+ declare const pad: (x: ArrayLike, width: number | [number, number] | [number, number][]) => Array;
1020
+ /** Return the number of dimensions of an array. Does not consume array reference. */
718
1021
  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. */
1022
+ /** Return the shape of an array. Does not consume array reference. */
1023
+ declare const shape$1: (x: ArrayLike) => number[];
1024
+ /** Return an array of zeros with the same shape and type as a given array. */
1025
+ declare const zerosLike: (a: ArrayLike, dtype?: DType) => Array;
1026
+ /** Return an array of ones with the same shape and type as a given array. */
1027
+ declare const onesLike: (a: ArrayLike, dtype?: DType) => Array;
1028
+ /** Return a full array with the same shape and type as a given array. */
1029
+ declare const fullLike: (a: ArrayLike, fillValue: number | boolean | Array, dtype?: DType) => Array;
1030
+ /**
1031
+ * Return the number of elements in an array, optionally along an axis.
1032
+ * Does not consume array reference.
1033
+ */
722
1034
  declare function size(a: ArrayLike, axis?: number): number;
1035
+ /** Convert an array to a specified dtype. */
1036
+ declare function astype(a: ArrayLike, dtype: DType): Array;
1037
+ /** Sum of the elements of the array over a given axis, or axes. */
1038
+ declare function sum(a: ArrayLike, axis?: number | number[], opts?: ReduceOpts): Array;
1039
+ /** Product of the array elements over a given axis. */
1040
+ declare function prod(a: ArrayLike, axis?: number | number[], opts?: ReduceOpts): Array;
1041
+ /** Return the minimum of array elements along a given axis. */
1042
+ declare function min(a: ArrayLike, axis?: number | number[], opts?: ReduceOpts): Array;
1043
+ /** Return the maximum of array elements along a given axis. */
1044
+ declare function max(a: ArrayLike, axis?: number | number[], opts?: ReduceOpts): Array;
1045
+ /** Compute the average of the array elements along the specified axis. */
1046
+ declare function mean(a: ArrayLike, axis?: number | number[], opts?: ReduceOpts): Array;
1047
+ /**
1048
+ * Returns the indices of the minimum values along an axis.
1049
+ *
1050
+ * By default, index is into the flatted array, otherwise it is along the
1051
+ * specified axis.
1052
+ */
1053
+ declare function argmin(a: ArrayLike, axis?: number, opts?: ReduceOpts): Array;
1054
+ /**
1055
+ * Returns the indices of the maximum values along an axis.
1056
+ *
1057
+ * By default, index is into the flatted array, otherwise it is along the
1058
+ * specified axis.
1059
+ */
1060
+ declare function argmax(a: ArrayLike, axis?: number, opts?: ReduceOpts): Array;
723
1061
  /** Reverse the elements in an array along the given axes. */
724
1062
  declare function flip(x: ArrayLike, axis?: number | number[]): Array;
1063
+ /**
1064
+ * Join a sequence of arrays along an existing axis.
1065
+ *
1066
+ * The arrays must have the same shape, except in the dimension corresponding to
1067
+ * `axis` (the first, by default).
1068
+ *
1069
+ * No scalars can be passed to this function, as the axis is then ambiguous.
1070
+ */
1071
+ declare function concatenate(xs: Array[], axis?: number): Array;
1072
+ /**
1073
+ * Join a sequence of arrays along a new axis.
1074
+ *
1075
+ * The `axis` parameter specifies the index of the new axis in the dimensions of
1076
+ * the result. For example, if `axis=0` it will be the first dimension and if
1077
+ * `axis=-1` it will be the last dimension.
1078
+ *
1079
+ * All shapes must have the same shape.
1080
+ */
1081
+ declare function stack(xs: ArrayLike[], axis?: number): Array;
1082
+ /**
1083
+ * Horizontally stack arrays. Inputs are promoted to rank at least 1, then
1084
+ * concatenated along axis 1 (if rank-2 or higher) or 0 (if rank-1).
1085
+ */
1086
+ declare function hstack(xs: ArrayLike[]): Array;
1087
+ /**
1088
+ * Vertically stack arrays. Inputs are promoted to rank at least 2, then
1089
+ * concatenated along axis 0.
1090
+ */
1091
+ declare function vstack(xs: ArrayLike[]): Array;
1092
+ /**
1093
+ * Stack arrays depth-wise. Inputs are promoted to rank at least 3, then
1094
+ * concatenated along axis 2.
1095
+ */
1096
+ declare function dstack(xs: ArrayLike[]): Array;
1097
+ /**
1098
+ * Stack arrays column-wise. Inputs are promoted to rank at least 2, then
1099
+ * concatenated along axis 1.
1100
+ */
1101
+ declare function columnStack(xs: ArrayLike[]): Array;
725
1102
  /** Flip an array vertically (axis=0). */
726
1103
  declare function flipud(x: ArrayLike): Array;
727
1104
  /** Flip an array horizontally (axis=1). */
@@ -733,13 +1110,13 @@ declare function ravel(a: ArrayLike): Array;
733
1110
  * Return specified diagonals.
734
1111
  *
735
1112
  * If a is 2D, return the diagonal of the array with the given offset. If a is
736
- * 3D or higher, compute diagonals along the two given axes.
1113
+ * 3D or higher, compute diagonals along the two given axes (default: 0, 1).
737
1114
  *
738
- * This returns a view over the existing array.
1115
+ * This returns a view over the existing array. The shape of the resulting array
1116
+ * is determined by removing the two axes along which the diagonal is taken,
1117
+ * then appending a new axis to the right with holding the diagonals.
739
1118
  */
740
1119
  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
1120
  /**
744
1121
  * Extract a diagonal or construct a diagonal array.
745
1122
  *
@@ -749,15 +1126,15 @@ declare function matrixTranspose(x: ArrayLike): Array;
749
1126
  declare function diag(v: ArrayLike, k?: number): Array;
750
1127
  /** Return if two arrays are element-wise equal within a tolerance. */
751
1128
  declare function allclose(actual: Parameters<typeof array>[0], expected: Parameters<typeof array>[0], options?: {
752
- rtol?: number;
753
- atol?: number;
1129
+ rtol?: number;
1130
+ atol?: number;
754
1131
  }): boolean;
755
1132
  /** Matrix product of two arrays. */
756
- declare const matmul: (x: ArrayLike, y: ArrayLike) => Array;
1133
+ declare function matmul(x: ArrayLike, y: ArrayLike): Array;
757
1134
  /** Dot product of two arrays. */
758
- declare const dot: (x: ArrayLike, y: ArrayLike) => Array;
1135
+ declare function dot(x: ArrayLike, y: ArrayLike): Array;
759
1136
  /** Vector dot product of two arrays. */
760
- declare const vecdot: (x: ArrayLike, y: ArrayLike) => Array;
1137
+ declare function vecdot(x: ArrayLike, y: ArrayLike): Array;
761
1138
  /**
762
1139
  * Return the dot product of two vectors.
763
1140
  *
@@ -770,8 +1147,10 @@ declare function vdot(x: ArrayLike, y: ArrayLike): Array;
770
1147
  * Make N-D coordinate arrays for vectorized evaluations of N-D scalar/vector
771
1148
  * fields over N-D grids, given one-dimensional coordinate arrays x1, x2,…, xn.
772
1149
  */
773
- declare function meshgrid(xs: Array[], { indexing }?: {
774
- indexing?: "xy" | "ij";
1150
+ declare function meshgrid(xs: Array[], {
1151
+ indexing
1152
+ }?: {
1153
+ indexing?: "xy" | "ij";
775
1154
  }): Array[];
776
1155
  /**
777
1156
  * Clip (limit) the values in an array.
@@ -807,161 +1186,119 @@ declare function exp2(p: ArrayLike): Array;
807
1186
  declare function log2(x: ArrayLike): Array;
808
1187
  /** Return the base-10 logarithm of x, element-wise. */
809
1188
  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
-
1189
+ /**
1190
+ * Calculate element-wise hyperbolic sine of input.
1191
+ *
1192
+ * `sinh(x) = (exp(x) - exp(-x)) / 2`
1193
+ */
1194
+ declare function sinh(x: ArrayLike): Array;
1195
+ /**
1196
+ * Calculate element-wise hyperbolic cosine of input.
1197
+ *
1198
+ * `cosh(x) = (exp(x) + exp(-x)) / 2`
1199
+ */
1200
+ declare function cosh(x: ArrayLike): Array;
1201
+ /**
1202
+ * Calculate element-wise hyperbolic tangent of input.
1203
+ *
1204
+ * `tanh(x) = sinh(x)/cosh(x) = (exp(x) - exp(-x)) / (exp(x) + exp(-x))`
1205
+ */
1206
+ declare function tanh(x: ArrayLike): Array;
1207
+ //#endregion
1208
+ //#region src/frontend/jaxpr.d.ts
905
1209
  /** Variable in a Jaxpr expression. */
906
1210
  declare class Var {
907
- #private;
908
- readonly id: number;
909
- readonly aval: ShapedArray;
910
- constructor(aval: ShapedArray);
911
- toString(): string;
1211
+ #private;
1212
+ readonly id: number;
1213
+ readonly aval: ShapedArray;
1214
+ constructor(aval: ShapedArray);
1215
+ toString(): string;
912
1216
  }
913
1217
  /** Literal in a Jaxpr expression. Currently, only scalars are supported. */
914
1218
  declare class Lit {
915
- readonly dtype: DType;
916
- readonly value: number;
917
- readonly aval: ShapedArray;
918
- constructor(dtype: DType, value: number);
1219
+ readonly dtype: DType;
1220
+ readonly value: number;
1221
+ readonly aval: ShapedArray;
1222
+ constructor(dtype: DType, value: number);
919
1223
  }
920
1224
  type Atom = Var | Lit;
921
1225
  declare class VarPrinter {
922
- #private;
923
- names: Map<Var, string>;
924
- name(v: Var): string;
925
- nameType(v: Var): string;
1226
+ #private;
1227
+ names: Map<Var, string>;
1228
+ name(v: Var): string;
1229
+ nameType(v: Var): string;
926
1230
  }
927
1231
  /** A single statement / binding in a Jaxpr, in ANF form. */
928
1232
  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;
1233
+ readonly primitive: Primitive;
1234
+ readonly inputs: Atom[];
1235
+ readonly params: Record<string, any>;
1236
+ readonly outBinders: Var[];
1237
+ constructor(primitive: Primitive, inputs: Atom[], params: Record<string, any>, outBinders: Var[]);
1238
+ pprint(usedVars?: Set<Var>, vp?: VarPrinter): PPrint;
1239
+ toString(): string;
936
1240
  }
937
1241
  /** Typed intermediate representation for traced computations. */
938
1242
  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;
1243
+ #private;
1244
+ readonly inBinders: Var[];
1245
+ readonly eqns: JaxprEqn[];
1246
+ readonly outs: Atom[];
1247
+ constructor(inBinders: Var[], eqns: JaxprEqn[], outs: Atom[]);
1248
+ pprint(): PPrint;
1249
+ toString(): string;
1250
+ /**
1251
+ * Gets a hash of this Jaxpr.
1252
+ *
1253
+ * Var identity is not considered in the hash, so two Jaxprs with the same
1254
+ * order of assignments and operators but different variable IDs will resolve
1255
+ * to the same hash (and toString representation).
1256
+ */
1257
+ getHash(): bigint;
1258
+ hash(state: FpHash): void;
1259
+ /**
1260
+ * Produce a simplified Jaxpr with basic optimizations applied.
1261
+ * - Trim away unused variables.
1262
+ * - Fold away *1, *0, or +0 operations against literals.
1263
+ * - Remove no-op movement operations.
1264
+ */
1265
+ simplify(): Jaxpr;
1266
+ /** Flattens nested JitCall in a Jaxpr. Useful for handling jit-of-jit. */
1267
+ flatten(): Jaxpr;
1268
+ }
1269
+ /** @inline */
1270
+ type JitOpts = {
1271
+ staticArgnums?: number[];
1272
+ device?: Device;
1273
+ };
1274
+ declare namespace lax_d_exports {
1275
+ export { PaddingType, conv, convGeneralDilated, convWithGeneralPadding, reduceWindow };
1276
+ }
1277
+ type PaddingType = "VALID" | "SAME" | "SAME_LOWER" | [number, number][];
1278
+ /**
1279
+ * General n-dimensional convolution operator, with optional dilation.
1280
+ *
1281
+ * The semantics of this operation mimic the `jax.lax.conv_general_dilated`
1282
+ * function in JAX, which wraps XLA's general convolution operator.
1283
+ *
1284
+ * Grouped convolutions are not supported right now.
1285
+ */
1286
+ declare function convGeneralDilated(lhs: Array, rhs: Array, windowStrides: number[], padding: PaddingType, {
1287
+ lhsDilation,
1288
+ rhsDilation
1289
+ }?: {
1290
+ lhsDilation?: number[];
1291
+ rhsDilation?: number[];
1292
+ }): Array;
1293
+ /** Convenience wrapper around `convGeneralDilated`. */
1294
+ declare function convWithGeneralPadding(lhs: Array, rhs: Array, windowStrides: number[], padding: PaddingType, lhsDilation?: number[], rhsDilation?: number[]): Array;
1295
+ /** Convenience wrapper around `convGeneralDilated`. */
1296
+ declare function conv(lhs: Array, rhs: Array, windowStrides: number[], padding: PaddingType): Array;
1297
+ /** Reduce a computation over padded windows. */
1298
+ declare function reduceWindow(operand: Array, computation: (x: Array) => Array, windowDimensions: number[], windowStrides?: number[]): Array;
1299
+ declare namespace nn_d_exports {
1300
+ export { celu, elu, gelu, glu, identity, leakyRelu, logSigmoid, logSoftmax, logsumexp, mish, oneHot, relu, relu6, sigmoid, silu, softSign, softmax, softplus, swish };
963
1301
  }
964
-
965
1302
  /**
966
1303
  * Rectified Linear Unit (ReLU) activation function:
967
1304
  * `relu(x) = max(x, 0)`.
@@ -1000,7 +1337,7 @@ declare function softSign(x: ArrayLike): Array;
1000
1337
  *
1001
1338
  * Reference: https://en.wikipedia.org/wiki/Swish_function
1002
1339
  */
1003
- declare function silu(x: ArrayLike): Array;
1340
+ declare const silu: (x: ArrayLike) => Array;
1004
1341
  /**
1005
1342
  * Sigmoid-weighted Linear Unit (SiLU) activation function, also known as
1006
1343
  * Swish, computed element-wise:
@@ -1010,7 +1347,7 @@ declare function silu(x: ArrayLike): Array;
1010
1347
  *
1011
1348
  * Reference: https://en.wikipedia.org/wiki/Swish_function
1012
1349
  */
1013
- declare const swish: typeof silu;
1350
+ declare const swish: (x: ArrayLike) => Array;
1014
1351
  /**
1015
1352
  * Log-sigmoid activation function, computed element-wise:
1016
1353
  * `log_sigmoid(x) = log(sigmoid(x)) = -log(1 + exp(-x))`.
@@ -1018,49 +1355,154 @@ declare const swish: typeof silu;
1018
1355
  declare function logSigmoid(x: ArrayLike): Array;
1019
1356
  /** Identity activation function. Returns the argument unmodified. */
1020
1357
  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 };
1358
+ /** Leaky rectified linear (ReLU) activation function */
1359
+ declare function leakyRelu(x: ArrayLike, negativeSlope?: number): Array;
1360
+ /**
1361
+ * Exponential linear unit activation function.
1362
+ *
1363
+ * Computes the element-wise function:
1364
+ * `elu(x) = x > 0 ? x : alpha * (exp(x) - 1)`
1365
+ */
1366
+ declare function elu(x: ArrayLike, alpha?: number): Array;
1367
+ /**
1368
+ * Continuously-differentiable exponential linear unit activation function.
1369
+ *
1370
+ * Computes the element-wise function:
1371
+ * `celu(x) = x > 0 ? x : alpha * (exp(x/alpha) - 1)`
1372
+ */
1373
+ declare function celu(x: ArrayLike, alpha?: number): Array;
1374
+ /**
1375
+ * Gaussion error linear unit (GELU) activation function.
1376
+ *
1377
+ * This is computed element-wise. Currently jax-js does not support the erf() or
1378
+ * gelu() functions exactly as primitives, so an approximation is used:
1379
+ * `gelu(x) ~= x * 0.5 * (1 + tanh(sqrt(2/pi) * (x + 0.044715 * x^3)))`.
1380
+ *
1381
+ * Reference: https://ml-explore.github.io/mlx/build/html/python/nn/_autosummary_functions/mlx.nn.gelu_approx.html
1382
+ *
1383
+ * This will be improved in the future.
1384
+ */
1385
+ declare const gelu: (x: ArrayLike) => Array;
1386
+ /**
1387
+ * Gated linear unit (GLU) activation function.
1388
+ *
1389
+ * Splits the `axis` dimension of the input into two halves, a and b, then
1390
+ * computes `a * sigmoid(b)`.
1391
+ */
1392
+ declare function glu(x: ArrayLike, axis?: number): Array;
1393
+ /**
1394
+ * Mish activation function.
1395
+ *
1396
+ * Computes the element-wise function:
1397
+ * `mish(x) = x * tanh(softplus(x))`
1398
+ */
1399
+ declare function mish(x: ArrayLike): Array;
1400
+ /**
1401
+ * Softmax function. Computes the function which rescales elements to the range
1402
+ * [0, 1] such that the elements along `axis` sum to 1.
1403
+ *
1404
+ * If `axis` is not specified, it defaults to the last axis.
1405
+ *
1406
+ * Reference: https://en.wikipedia.org/wiki/Softmax_function
1407
+ */
1408
+ declare function softmax(x: ArrayLike, axis?: number | number[]): Array;
1409
+ /**
1410
+ * Log-Softmax function.
1411
+ *
1412
+ * Computes the logarithm of the `softmax` function, which rescales elements to
1413
+ * the range [-infinity, 0).
1414
+ *
1415
+ * If `axis` is not specified, it defaults to the last axis.
1416
+ */
1417
+ declare function logSoftmax(x: ArrayLike, axis?: number | number[]): Array;
1418
+ /**
1419
+ * Log-sum-exp reduction. Also a multivariate version of `softplus`.
1420
+ *
1421
+ * If no axis is specified, the reduction is performed over all elements. This
1422
+ * convention differs from `jax.nn.logSoftmax()`.
1423
+ *
1424
+ * Reference: https://en.wikipedia.org/wiki/LogSumExp
1425
+ */
1426
+ declare function logsumexp(x: ArrayLike, axis?: number | number[]): Array;
1427
+ /**
1428
+ * One-hot encodes the given indices.
1429
+ *
1430
+ * Each index in the integer input `x` is encoded as a vector of zeros of length
1431
+ * `numClasses`, with a 1 at the index position specified by its value.
1432
+ *
1433
+ * ```js
1434
+ * import { nn, numpy as np } from '@jax-js/jax';
1435
+ *
1436
+ * nn.oneHot(np.array([1, 1, 2], { dtype: np.int32 }), 3);
1437
+ * // Output:
1438
+ * // [[0, 1, 0],
1439
+ * // [0, 1, 0],
1440
+ * // [0, 0, 1]]
1441
+ * ```
1442
+ */
1443
+ declare function oneHot(x: Array, numClasses: number): Array;
1444
+ declare namespace random_d_exports {
1445
+ export { bits, key, split, uniform };
1033
1446
  }
1034
-
1035
- type WithArgsSubtype<F extends (args: any[]) => any, T> = Parameters<F> extends T ? F : never;
1447
+ /** Create a pseudo-random number generator (PRNG) key from 32-bit integer seed. */
1448
+ declare function key(seed: number): Array;
1449
+ /** Splits a PRNG key into `num` new keys by adding a leading axis. */
1450
+ declare function split(key: Array, num?: number | number[]): Array;
1451
+ /** Sample uniform bits in the form of unsigned integers. */
1452
+ declare function bits(key: Array, shape?: number[]): Array;
1453
+ /** Sample uniform random values in [minval, maxval) with given shape. */
1454
+ declare function uniform(key: Array, shape?: number[], {
1455
+ minval,
1456
+ maxval
1457
+ }?: {
1458
+ minval?: number;
1459
+ maxval?: number;
1460
+ }): Array;
1461
+ //#endregion
1462
+ //#region src/index.d.ts
1036
1463
  /** Compute the forward-mode Jacobian-vector product for a function. */
1037
- 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>];
1464
+ declare const jvp: <F extends (...args: any[]) => JsTree<Array>>(f: F, primals: MapJsTree<Parameters<F>, Array, ArrayLike>, tangents: MapJsTree<Parameters<F>, Array, ArrayLike>) => [ReturnType<F>, ReturnType<F>];
1038
1465
  /** Vectorize an operation on a batched axis for one or more inputs. */
1039
- declare const vmap: <F extends (...args: any[]) => JsTree<Array>>(f: WithArgsSubtype<F, JsTree<ArrayLike>>, inAxes?: number | MapJsTree<Parameters<F>, ArrayLike, number | null>) => (...args: MapJsTree<Parameters<F>, ArrayLike, ArrayLike>) => ReturnType<F>;
1466
+ declare const vmap: <F extends (...args: any[]) => JsTree<Array>>(f: F, inAxes?: number | MapJsTree<Parameters<F>, ArrayLike, number | null>) => (...args: MapJsTree<Parameters<F>, Array, ArrayLike>) => ReturnType<F>;
1040
1467
  /** Compute the Jacobian evaluated column-by-column by forward-mode AD. */
1041
- declare const jacfwd: <F extends (x: Array) => Array>(f: F) => (...args: MapJsTree<Parameters<F>, ArrayLike, ArrayLike>) => ReturnType<F>;
1468
+ declare const jacfwd: <F extends (x: Array) => Array>(f: F) => (...args: MapJsTree<Parameters<F>, Array, ArrayLike>) => ReturnType<F>;
1042
1469
  /** Construct a Jaxpr by dynamically tracing a function with example inputs. */
1043
- 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;
1470
+ declare const makeJaxpr: <F extends (...args: any[]) => JsTree<Array>>(f: F) => (...args: Parameters<F>) => {
1471
+ jaxpr: Jaxpr;
1472
+ consts: Array[];
1473
+ treedef: JsTreeDef;
1047
1474
  };
1048
- declare const jit: <F extends (...args: any[]) => JsTree<Array>>(f: WithArgsSubtype<F, JsTree<ArrayLike>>) => (...args: MapJsTree<Parameters<F>, ArrayLike, ArrayLike>) => ReturnType<F>;
1475
+ /**
1476
+ * Mark a function for automatic JIT compilation, with operator fusion.
1477
+ *
1478
+ * The function will be compiled the first time it is called with a set of
1479
+ * argument shapes.
1480
+ *
1481
+ * **Options:**
1482
+ * - `staticArgnums`: An array of argument indices to treat as static
1483
+ * (compile-time constant). These arguments must be hashable, won't be traced,
1484
+ * and different values will trigger recompilation.
1485
+ * - `device`: The device to place the computation on. If not specified, the
1486
+ * computation will be placed on the default device.
1487
+ */
1488
+ declare const jit: <F extends (...args: any[]) => JsTree<Array>>(f: F, opts?: JitOpts) => (...args: MapJsTree<Parameters<F>, Array, ArrayLike>) => ReturnType<F>;
1049
1489
  /**
1050
1490
  * Produce a local linear approximation to a function at a point using jvp() and
1051
1491
  * partial evaluation.
1052
1492
  */
1053
- declare const linearize: <F extends (...args: any[]) => JsTree<Array>>(f: WithArgsSubtype<F, JsTree<ArrayLike>>, ...primals: MapJsTree<Parameters<F>, ArrayLike, ArrayLike>) => [ReturnType<F>, (...tangents: MapJsTree<Parameters<F>, ArrayLike, ArrayLike>) => ReturnType<F>];
1493
+ declare const linearize: <F extends (...args: any[]) => JsTree<Array>>(f: F, ...primals: MapJsTree<Parameters<F>, Array, ArrayLike>) => [ReturnType<F>, (...tangents: MapJsTree<Parameters<F>, Array, ArrayLike>) => ReturnType<F>];
1054
1494
  /** Calculate the reverse-mode vector-Jacobian product for a function. */
1055
- declare const vjp: <F extends (...args: any[]) => JsTree<Array>>(f: WithArgsSubtype<F, JsTree<ArrayLike>>, ...primals: MapJsTree<Parameters<F>, ArrayLike, ArrayLike>) => [ReturnType<F>, (cotangents: MapJsTree<ReturnType<F>, Array, ArrayLike>) => MapJsTree<Parameters<F>, ArrayLike, Array>];
1495
+ declare const vjp: <F extends (...args: any[]) => JsTree<Array>>(f: F, ...primals: MapJsTree<Parameters<F>, Array, ArrayLike>) => [ReturnType<F>, (cotangents: MapJsTree<ReturnType<F>, Array, ArrayLike>) => MapJsTree<Parameters<F>, ArrayLike, Array>];
1056
1496
  /**
1057
1497
  * Compute the gradient of a scalar-valued function `f` with respect to its
1058
1498
  * first argument.
1059
1499
  */
1060
- 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>;
1500
+ declare const grad: <F extends (...args: any[]) => JsTree<Array>>(f: F) => (...primals: MapJsTree<Parameters<F>, Array, ArrayLike>) => MapJsTree<Parameters<F>[0], ArrayLike, Array>;
1501
+ /** Create a function that evaluates both `f` and the gradient of `f`. */
1502
+ declare const valueAndGrad: <F extends (...args: any[]) => JsTree<Array>>(f: F) => (...primals: MapJsTree<Parameters<F>, Array, ArrayLike>) => [ReturnType<F>, MapJsTree<Parameters<F>[0], ArrayLike, Array>];
1061
1503
  /** Compute the Jacobian evaluated row-by-row by reverse-mode AD. */
1062
1504
  declare const jacrev: typeof jacfwd;
1063
1505
  /** Compute the Jacobian with reverse-mode AD. Alias for `jacrev()`. */
1064
- 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 };
1506
+ declare const jacobian: <F extends (x: Array) => Array>(f: F) => (...args: MapJsTree<Parameters<F>, Array, ArrayLike>) => ReturnType<F>;
1507
+ //#endregion
1508
+ export { DType, type Device, type JsTree, type JsTreeDef, devices, grad, init, jacfwd, jacobian, jacrev, jit, jvp, lax_d_exports as lax, 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 };