@jax-js/jax 0.1.0 → 0.1.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.d.ts CHANGED
@@ -165,9 +165,10 @@ declare enum DType {
165
165
  Uint32 = "uint32",
166
166
  Bool = "bool",
167
167
  Float16 = "float16",
168
+ Float64 = "float64",
168
169
  }
169
170
  /** @inline */
170
- type DataArray = Float32Array<ArrayBuffer> | Int32Array<ArrayBuffer> | Uint32Array<ArrayBuffer> | Float16Array<ArrayBuffer>;
171
+ type DataArray = Float32Array<ArrayBuffer> | Int32Array<ArrayBuffer> | Uint32Array<ArrayBuffer> | Float16Array<ArrayBuffer> | Float64Array<ArrayBuffer>;
171
172
  /**
172
173
  * Promote two dtypes to their join according to the type lattice.
173
174
  *
@@ -177,7 +178,7 @@ type DataArray = Float32Array<ArrayBuffer> | Int32Array<ArrayBuffer> | Uint32Arr
177
178
  *
178
179
  * **Type lattice:**
179
180
  * ```text
180
- * bool -> uint32 -> int32 -> float16 -> float32
181
+ * bool -> uint32 -> int32 -> float16 -> float32 -> float64
181
182
  * weakType --^
182
183
  * ```
183
184
  *
@@ -223,6 +224,8 @@ declare class AluExp implements FpHashable {
223
224
  static erf(a: AluExp): AluExp;
224
225
  static erfc(a: AluExp): AluExp;
225
226
  static sqrt(a: AluExp): AluExp;
227
+ static floor(a: AluExp): AluExp;
228
+ static ceil(a: AluExp): AluExp;
226
229
  static reciprocal(a: AluExp): AluExp;
227
230
  static cast(dtype: DType, a: AluExp): AluExp;
228
231
  static bitcast(dtype: DType, a: AluExp): AluExp;
@@ -240,6 +243,7 @@ declare class AluExp implements FpHashable {
240
243
  static u32(value: number): AluExp;
241
244
  static bool(value: boolean): AluExp;
242
245
  static f16(value: number): AluExp;
246
+ static f64(value: number): AluExp;
243
247
  not(): AluExp;
244
248
  /** Compute a reasonable expression hash with low collision rate. */
245
249
  getHash(): bigint;
@@ -312,6 +316,8 @@ declare enum AluOp {
312
316
  Erf = "Erf",
313
317
  Erfc = "Erfc",
314
318
  Sqrt = "Sqrt",
319
+ Floor = "Floor",
320
+ Ceil = "Ceil",
315
321
  Reciprocal = "Reciprocal",
316
322
  Cast = "Cast",
317
323
  Bitcast = "Bitcast",
@@ -454,680 +460,85 @@ declare class Executable<T = any> {
454
460
  constructor(kernel: Kernel, /** Extra data specific to the backend running this kernel. */
455
461
  data: T);
456
462
  }
457
- declare namespace tree_d_exports {
458
- export { JsTree, JsTreeDef, MapJsTree, NodeType, dispose, flatten, leaves, map, ref, structure, unflatten };
459
- }
460
- declare enum NodeType {
461
- Array = "Array",
462
- Object = "Object",
463
- Leaf = "Leaf",
464
- }
465
- /** Analog to the JAX "pytree" object, but for JavaScript. */
466
- type JsTree<T> = T | JsTree<T>[] | {
467
- [key: string]: JsTree<T>;
468
- };
469
- type Same<X, Y> = (<T>() => T extends X ? 1 : 2) extends (<T>() => T extends Y ? 1 : 2) ? true : false;
470
- type MappedJsTree<T, A, B> = T extends A ? B : T extends Array ? T : 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> };
471
- /** @ignore Convert a subtype of JsTree<A> into a JsTree<B>, with the same structure. */
472
- type MapJsTree<T, A, B> = Same<A, B> extends true ? T : MappedJsTree<T, A, B>;
473
- /** Represents the structure of a JsTree. */
474
- declare class JsTreeDef {
475
- readonly nodeType: NodeType;
476
- readonly nodeMetadata: any;
477
- readonly childTreedefs: JsTreeDef[];
478
- static leaf: JsTreeDef;
479
- constructor(nodeType: NodeType, nodeMetadata: any,
480
- // Must be comparable with deepEqual.
481
- childTreedefs: JsTreeDef[]);
482
- /** Get the total number of leaves in the tree. */
483
- get size(): number;
484
- /** Returns a string representation of this tree definition. */
485
- toString(root?: boolean): string;
486
- /** Compare this tree definition with another. */
487
- equals(other: JsTreeDef): boolean;
488
- }
489
- /** Flatten a structured object, returning the tree definition. */
490
- declare function flatten<T>(tree: JsTree<T>): [T[], JsTreeDef];
491
- /** Get the leaves of a tree. */
492
- declare function leaves<T>(tree: JsTree<T>): T[];
493
- /** Get the treedef for a tree. */
494
- declare function structure<T>(tree: JsTree<T>): JsTreeDef;
495
- /** Reconstruct a structured object from the flattened representation. */
496
- declare function unflatten<T>(treedef: JsTreeDef, leaves: Iterable<T>): JsTree<T>;
497
- /** Maps a multi-input function over pytree args to produce a new pytree. */
498
- declare function map<T, U, Tree extends JsTree<T>>(fn: (...args: T[]) => U, tree: Tree, ...rest: Tree[]): MapJsTree<Tree, T, U>;
499
- /** Take a reference of every array in a tree. */
500
- declare function ref<Tree extends JsTree<Array>>(tree: Tree): Tree;
501
- /** Dispose every array in a tree. */
502
- declare function dispose<Tree extends JsTree<Array>>(tree: Tree | null | undefined): void;
503
- //#endregion
504
- //#region src/frontend/convolution.d.ts
505
- /** Definition of a general dilated convolution. Should be valid on creation. */
506
- interface ConvParams {
507
- strides: number[];
508
- padding: [number, number][];
509
- lhsDilation: number[];
510
- rhsDilation: number[];
463
+ declare namespace numpy_d_exports {
464
+ export { Array, ArrayLike, DType, abs, absolute, acos, acosh, add, allclose, arange, arccos, arccosh, arcsinh, arctan, arctan2, arctanh, argmax, argmin, array, asin, asinh, astype, atan, atan2, atanh, bool, broadcastArrays, broadcastShapes, broadcastTo, cbrt, ceil, clip, columnStack, concatenate, cos, cosh, deg2rad, degrees, diag, diagonal, divide, dot$1 as dot, dstack, e, einsum, equal, eulerGamma, exp, exp2, expm1, eye, flip, fliplr, flipud, float16, float32, float64, floor, fmod, frexp, full, fullLike, greater, greaterEqual, hamming, hann, heaviside, hstack, hypot, identity$1 as identity, inf, inner, int32, isfinite, isinf, isnan, isneginf, isposinf, ldexp, less, lessEqual, linspace, log, log10, log1p, log2, matmul, max, maximum, mean, meshgrid, min, minimum, moveaxis, multiply, nan, ndim, negative, notEqual, ones, onesLike, outer, pad, permuteDims, pi, positive, pow, power, prod, promoteTypes, ptp, rad2deg, radians, ravel, reciprocal, remainder, repeat, reshape, shape$1 as shape, sign, sin, sinh, size, sqrt, square, squeeze, stack, std, subtract, sum, tan, tanh, tensordot, tile, trace, transpose, tri, tril, triu, trueDivide, trunc, uint32, var_, vdot, vecdot, vstack, where, zeros, zerosLike };
511
465
  }
466
+ declare const float32 = DType.Float32;
467
+ declare const int32 = DType.Int32;
468
+ declare const uint32 = DType.Uint32;
469
+ declare const bool = DType.Bool;
470
+ declare const float16 = DType.Float16;
471
+ declare const float64 = DType.Float64;
472
+ /** Euler's constant, `e = 2.7182818284590...` */
473
+ declare const e: number;
474
+ /** Euler-Mascheroni constant, `γ = 0.5772156649...` */
475
+ declare const eulerGamma = 0.5772156649015329;
476
+ /** Positive infinity. */
477
+ declare const inf: number;
478
+ /** Floating-point representation of NaN. */
479
+ declare const nan: number;
480
+ /** This is Pi, `π = 3.14159265358979...` */
481
+ declare const pi: number;
482
+ /** @function Element-wise addition, with broadcasting. */
483
+ declare const add: (x: ArrayLike, y: ArrayLike) => Array;
484
+ /** @function Element-wise multiplication, with broadcasting. */
485
+ declare const multiply: (x: ArrayLike, y: ArrayLike) => Array;
486
+ /** @function Numerical negative of every element of an array. */
487
+ declare const negative: (x: ArrayLike) => Array;
488
+ /** @function Calculate element-wise reciprocal of the input. This is `1/x`. */
489
+ declare const reciprocal: (x: ArrayLike) => Array;
490
+ /** @function Round input down to the nearest integer. */
491
+ declare const floor: (x: ArrayLike) => Array;
492
+ /** @function Round input up to the nearest integer. */
493
+ declare const ceil: (x: ArrayLike) => Array;
494
+ /** @function Element-wise sine function (takes radians). */
495
+ declare const sin: (x: ArrayLike) => Array;
496
+ /** @function Element-wise cosine function (takes radians). */
497
+ declare const cos: (x: ArrayLike) => Array;
498
+ /** @function Element-wise inverse sine function (inverse of sin). */
499
+ declare const asin: (x: ArrayLike) => Array;
500
+ /** @function Element-wise inverse tangent function (inverse of tan). */
501
+ declare const atan: (x: ArrayLike) => Array;
502
+ /** @function Calculate the exponential of all elements in the input array. */
503
+ declare const exp: (x: ArrayLike) => Array;
504
+ /** @function Calculate the natural logarithm of all elements in the input array. */
505
+ declare const log: (x: ArrayLike) => Array;
506
+ /** @function Calculate the square root of all elements in the input array. */
507
+ declare const sqrt: (x: ArrayLike) => Array;
508
+ /** @function Return element-wise minimum of the input arrays. */
509
+ declare const minimum: (x: ArrayLike, y: ArrayLike) => Array;
510
+ /** @function Return element-wise maximum of the input arrays. */
511
+ declare const maximum: (x: ArrayLike, y: ArrayLike) => Array;
512
+ /** @function Compare two arrays element-wise. */
513
+ declare const greater: (x: ArrayLike, y: ArrayLike) => Array;
514
+ /** @function Compare two arrays element-wise. */
515
+ declare const less: (x: ArrayLike, y: ArrayLike) => Array;
516
+ /** @function Compare two arrays element-wise. */
517
+ declare const equal: (x: ArrayLike, y: ArrayLike) => Array;
518
+ /** @function Compare two arrays element-wise. */
519
+ declare const notEqual: (x: ArrayLike, y: ArrayLike) => Array;
520
+ /** @function Compare two arrays element-wise. */
521
+ declare const greaterEqual: (x: ArrayLike, y: ArrayLike) => Array;
522
+ /** @function Compare two arrays element-wise. */
523
+ declare const lessEqual: (x: ArrayLike, y: ArrayLike) => Array;
524
+ /** @function Element-wise ternary operator, evaluates to `x` if cond else `y`. */
525
+ declare const where: (cond: ArrayLike, x: ArrayLike, y: ArrayLike) => Array;
512
526
  /**
513
- * Check that the shapes and parameters passed to convolution are valid.
514
- *
515
- * If the check succeeds, returns the output shape.
527
+ * @function
528
+ * Permute the dimensions of an array. Defaults to reversing the axis order.
516
529
  */
517
-
518
- //#endregion
519
- //#region src/frontend/core.d.ts
530
+ declare const transpose: (x: ArrayLike, perm?: number[]) => Array;
520
531
  /**
521
- * Frontend primitive operations, which are lowered into Kernel objects before
522
- * being dispatched to the backend.
523
- *
524
- * Any operation between arrays can be described in these parts. This is also
525
- * the set of primitives that can occur in Jaxpr programs, and the level at
526
- * which transformations like vmap, grad, and jvp occur. They are loosely based
527
- * on [XLA](https://openxla.org/xla/operation_semantics).
532
+ * @function
533
+ * Give a new shape to an array without changing its data.
528
534
  *
529
- * All n-ary operations support broadcasting, with NumPy semantics.
535
+ * One shape dimension can be -1. In this case, the value is inferred from the
536
+ * length of the array and remaining dimensions.
530
537
  */
531
- declare enum Primitive {
532
- Add = "add",
533
- Mul = "mul",
534
- Idiv = "idiv",
535
- Neg = "neg",
536
- Reciprocal = "reciprocal",
537
- StopGradient = "stop_gradient",
538
- Cast = "cast",
539
- Bitcast = "bitcast",
540
- RandomBits = "random_bits",
541
- Sin = "sin",
542
- Cos = "cos",
543
- Asin = "asin",
544
- Atan = "atan",
545
- Exp = "exp",
546
- Log = "log",
547
- Erf = "erf",
548
- Erfc = "erfc",
549
- Sqrt = "sqrt",
550
- Min = "min",
551
- Max = "max",
552
- Reduce = "reduce",
553
- Dot = "dot",
554
- // sum(x*y, axis=-1)
555
- Conv = "conv",
556
- // see lax.conv_general_dilated
557
- Pool = "pool",
558
- PoolTranspose = "pool_transpose",
559
- Compare = "compare",
560
- Where = "where",
561
- Transpose = "transpose",
562
- Broadcast = "broadcast",
563
- Reshape = "reshape",
564
- Flip = "flip",
565
- Shrink = "shrink",
566
- Pad = "pad",
567
- Gather = "gather",
568
- JitCall = "jit_call",
569
- }
570
- interface PrimitiveParamsImpl extends Record<Primitive, Record<string, any>> {
571
- [Primitive.Cast]: {
572
- dtype: DType;
573
- };
574
- [Primitive.Bitcast]: {
575
- dtype: DType;
576
- };
577
- [Primitive.Reduce]: {
578
- op: AluOp;
579
- axis: number[];
580
- };
581
- [Primitive.Conv]: ConvParams;
582
- [Primitive.Pool]: {
583
- window: number[];
584
- strides: number[];
585
- };
586
- [Primitive.PoolTranspose]: {
587
- inShape: number[];
588
- window: number[];
589
- strides: number[];
590
- };
591
- [Primitive.Compare]: {
592
- op: CompareOp;
593
- };
594
- [Primitive.Transpose]: {
595
- perm: number[];
596
- };
597
- [Primitive.Broadcast]: {
598
- shape: number[];
599
- axis: number[];
600
- };
601
- [Primitive.RandomBits]: {
602
- shape: number[];
603
- mode: "xor" | 0 | 1;
604
- };
605
- [Primitive.Reshape]: {
606
- shape: number[];
607
- };
608
- [Primitive.Flip]: {
609
- axis: number[];
610
- };
611
- [Primitive.Shrink]: {
612
- slice: Pair[];
613
- };
614
- [Primitive.Pad]: {
615
- width: Pair[];
616
- };
617
- [Primitive.Gather]: {
618
- axis: number[];
619
- outDim: number;
620
- };
621
- [Primitive.JitCall]: {
622
- name: string;
623
- jaxpr: Jaxpr;
624
- numConsts: number;
625
- };
626
- }
627
- /** Type of parameters taken by each primitive. */
628
- type PrimitiveParams<T extends Primitive> = T extends keyof PrimitiveParamsImpl ? PrimitiveParamsImpl[T] : Record<string, never>;
629
- declare enum CompareOp {
630
- Greater = "greater",
631
- Less = "less",
632
- Equal = "equal",
633
- NotEqual = "not_equal",
634
- GreaterEqual = "greater_equal",
635
- LessEqual = "less_equal",
636
- }
637
- /** @inline */
638
- type Axis = number | number[] | null;
639
- /** @inline */
640
- type ReduceOpts = {
641
- keepdims?: boolean;
642
- };
643
- type MainTrace = {
644
- level: number;
645
- traceType: new (main: MainTrace) => Trace;
646
- globalData: any | null;
647
- };
538
+ declare const reshape: (x: ArrayLike, shape: number[]) => Array;
648
539
  /**
649
- * Push an interpreter onto the trace stack. Use this like:
650
- * `using main = newMain(...);`
651
- */
652
-
653
- type TracerValue = Tracer | number | boolean;
654
- declare abstract class Trace {
655
- readonly main: MainTrace;
656
- constructor(main: MainTrace);
657
- abstract pure(val: TracerValue): Tracer;
658
- abstract lift(val: Tracer): Tracer;
659
- abstract processPrimitive<P extends Primitive>(primitive: P, tracers: Tracer[], params: PrimitiveParams<P>): Tracer[];
660
- }
661
- /** Internal representation of an array value. */
662
- interface AbstractValue {
663
- /** Shape of the array. Must be a static tuple of non-negative dimensions. */
664
- shape: number[];
665
- /** Concrete data type of array elements. */
666
- dtype: DType;
667
- /**
668
- * Arrays created from JavaScript numbers (e.g., `np.array(3)`) are created as
669
- * _weakly typed_ unless a dtype is explicitly specified.
670
- *
671
- * Weakly typed values will automatically cast to the data type of other
672
- * arrays when used as an operand as an expression. This property only affects
673
- * how they promote in type casting; their memory layout is still determined
674
- * by the actual `dtype` field.
675
- *
676
- * ```ts
677
- * const x = np.array(3); // weakType = true, dtype = float32
678
- * const y = np.array([1, 2], { dtype: np.int32 }); // weakType = false, dtype = int32
679
- * const z = x.add(y); // z has dtype int32 because x is weakly typed
680
- * ```
681
- *
682
- * Weak types are present in JIT programs in their spec (e.g., Jaxpr inputs
683
- * and outputs can be weakly typed) form. But they're solely a frontend
684
- * concept. Backends are not aware of weak types.
685
- */
686
- weakType: boolean;
687
- }
688
- /**
689
- * Broadcast shapes and promote types with casting for two avals.
690
- *
691
- * This implements the weak type behavior described in `promoteTypes()`, but not
692
- * implemented in that function as `weakType` is not passed.
693
- */
694
-
695
- declare abstract class Tracer {
696
- /** @ignore */
697
- readonly _trace: Trace;
698
- constructor(trace: Trace);
699
- abstract get aval(): AbstractValue;
700
- abstract toString(): string;
701
- /**
702
- * Access an array by reference, incrementing the reference count.
703
- *
704
- * jax-js handles freeing arrays by using "move" semantics, like in Rust/C++.
705
- * Whenever you pass an array into a function, that function should consume
706
- * the array, and it will no longer be usable. For example, if you had:
707
- *
708
- * ```
709
- * const x = np.array([1, 2, 3]);
710
- * const y = np.add(x, x);
711
- * ```
712
- *
713
- * The second line does not work because the first parameter consumes `x`, and
714
- * then the second parameter will already have been freed / disposed.
715
- *
716
- * To fix this, you can write:
717
- *
718
- * ```
719
- * const y = np.add(x.ref, x);
720
- * ```
721
- *
722
- * Under the hood, every access to `.ref` increments the internal reference
723
- * count of the array. The reference count starts at 1. When it hits 0, the
724
- * memory behind the array is freed.
725
- */
726
- abstract get ref(): this;
727
- /**
728
- * Manually decrement the reference count of the array.
729
- *
730
- * Arrays are created with reference count 1. Whenever it is used as argument
731
- * to a function or other operation, it is disposed (i.e., reference count
732
- * decreases by 1) automatically. Whenever a `.ref` is created, the reference
733
- * count increases.
734
- *
735
- * You generally don't need to call this function directly since arrays are
736
- * automatically disposed after being passed into an operation. One common
737
- * exception is when writing a function and ignoring one of its arguments. In
738
- * that case, by convention you should dispose of that argument manually.
739
- *
740
- * ```
741
- * function myCustomOperation(a: np.Array, b: np.Array) {
742
- * b.dispose(); // Needed to satisfy "move" rules.
743
- * return a.add(1);
744
- * }
745
- * ```
746
- */
747
- abstract dispose(): void;
748
- /** The shape of the array. */
749
- get shape(): number[];
750
- /** The total number of elements in the array. */
751
- get size(): number;
752
- /** The dtype of elements stored in the array. */
753
- get dtype(): DType;
754
- /**
755
- * Whether the array is weakly typed.
756
- *
757
- * Weakly typed arrays will cast to the dtype of the other operand. See
758
- * `promoteTypes()` for details.
759
- */
760
- get weakType(): boolean;
761
- /** The number of dimensions of the array. */
762
- get ndim(): number;
763
- /** @ignore */
764
- fullLower(): Tracer;
765
- neg(): this;
766
- add(other: this | TracerValue): this;
767
- mul(other: this | TracerValue): this;
768
- greater(other: this | TracerValue): this;
769
- less(other: this | TracerValue): this;
770
- equal(other: this | TracerValue): this;
771
- notEqual(other: this | TracerValue): this;
772
- greaterEqual(other: this | TracerValue): this;
773
- lessEqual(other: this | TracerValue): this;
774
- /** Sum of the elements of the array over a given axis, or axes. */
775
- sum(axis?: Axis, opts?: ReduceOpts): this;
776
- /** Product of the array elements over a given axis. */
777
- prod(axis?: Axis, opts?: ReduceOpts): this;
778
- /** Compute the average of the array elements along the specified axis. */
779
- mean(axis?: Axis, opts?: ReduceOpts): this;
780
- /** Permute the dimensions of an array. Defaults to reversing the axis order. */
781
- transpose(perm?: number[]): this;
782
- /**
783
- * Give a new shape to an array without changing its data.
784
- *
785
- * One shape dimension can be -1. In this case, the value is inferred from the
786
- * length of the array and remaining dimensions.
787
- */
788
- reshape(shape: number | number[]): this;
789
- /** Copy the array and cast to a specified dtype. */
790
- astype(dtype: DType): this;
791
- /** Subtract an array from this one. */
792
- sub(other: this | TracerValue): this;
793
- /** Divide an array by this one. */
794
- div(other: this | TracerValue): this;
795
- /** Return specified diagonals. See `numpy.diagonal` for full docs. */
796
- diagonal(offset?: number, axis1?: number, axis2?: number): this;
797
- /** Flatten the array without changing its data. */
798
- flatten(): this;
799
- /** Flatten the array without changing its data. */
800
- ravel(): this;
801
- /**
802
- * Iterate over the first dimension of this array, returning slices.
803
- *
804
- * This can be used to destructure arrays. For example:
805
- *
806
- * ```js
807
- * let x = np.array([[1, 2], [3, 4]]);
808
- * let [a, b] = x;
809
- * console.log(a.js()); // [1, 2]
810
- * console.log(b.js()); // [3, 4]
811
- * ```
812
- */
813
- [Symbol.iterator](): IterableIterator<this>;
814
- /**
815
- * Slice an array along one or more axes.
816
- *
817
- * This is the equivalent of slicing in Python, e.g. `x[1:3, 2, :, None]`. To
818
- * mimic this in JavaScript, we would write:
819
- *
820
- * ```js
821
- * x.slice([1, 3], 2, [], null);
822
- * ```
823
- *
824
- * The `slice` method accepts a variable number of arguments, each of which
825
- * can be a number, an empty array, a single-element array, a two-element
826
- * array, or `null`. The arguments are interpreted as follows:
827
- *
828
- * - A number `n` means to access the `n`-th element along that axis, removing
829
- * that axis from the resulting shape.
830
- * - An empty array `[]` means to keep that axis as-is, like `:` in Python.
831
- * - A single-element array `[i]` means to start slicing from index `i`
832
- * (inclusive) to the end of the axis, like `x[i:]`.
833
- * - A two-element array `[i, j]` means to slice from index `i` (inclusive)
834
- * to index `j` (exclusive), like `x[i:j]`.
835
- * - `null` means to add a new axis at that position, like `np.newaxis`.
836
- *
837
- * Like in Python, negative indices are supported, which count from the end of
838
- * the axis. For example, `-1` means the last element.
839
- *
840
- * Strided slices are not yet implemented, so you cannot write `x[::2]` or
841
- * similar.
842
- *
843
- * Advanced indexing by integer arrays is also supported. This translates to
844
- * the "gather" primitive, and it allows you to access specific elements of
845
- * the array by integer indices stored in another array.
846
- */
847
- slice(...index: (number | [] | [number] | Pair | null | Tracer)[]): this;
848
- }
849
- declare class ShapedArray implements AbstractValue {
850
- readonly shape: number[];
851
- readonly dtype: DType;
852
- readonly weakType: boolean;
853
- constructor(shape: number[], dtype: DType, weakType: boolean);
854
- static fromAval(aval: AbstractValue): ShapedArray;
855
- get ndim(): number;
856
- toString(): string;
857
- equals(other: ShapedArray): boolean;
858
- }
859
- //#endregion
860
- //#region src/frontend/array.d.ts
861
- type ArrayLike = Array | number | boolean;
862
- /** Version of pureArray with fudged types. */
863
-
864
- /**
865
- * An executable operation that will be dispatched to the backend.
866
- *
867
- * This holds a reference to all input buffers used in the operation. After the
868
- * operation is dispatched, the references should be released.
869
- */
870
- declare class PendingExecute {
871
- #private;
872
- readonly backend: Backend;
873
- readonly kernel: Kernel;
874
- readonly inputs: Slot[];
875
- readonly outputs: Slot[];
876
- prepared: Executable | null;
877
- submitted: boolean;
878
- constructor(backend: Backend, kernel: Kernel, inputs: Slot[], outputs: Slot[]);
879
- updateRc(delta: number): void;
880
- prepare(): Promise<void>;
881
- prepareSync(): void;
882
- submit(): void;
883
- }
884
- /** @inline */
885
- type DTypeAndDevice = {
886
- dtype?: DType;
887
- device?: Device;
888
- };
889
- type ArrayConstructorArgs = {
890
- source: AluExp | Slot;
891
- st: ShapeTracker;
892
- dtype: DType;
893
- weakType: boolean;
894
- backend: Backend;
895
- committed: boolean;
896
- pending?: Iterable<PendingExecute>;
897
- };
898
- /**
899
- * A multidimensional numeric array with data stored on CPU or GPU.
900
- *
901
- * This is the library's core data type. Equivalent to `jax.Array` from JAX, or
902
- * `torch.Tensor`.
903
- *
904
- * Not to be confused with the JavaScript "Array" constructor. Avoid importing
905
- * this into your code's namespace if you're already using the JavaScript
906
- * "Array" type by name.
907
- */
908
- declare class Array extends Tracer {
909
- #private;
910
- id: number;
911
- /**
912
- * @ignore
913
- * Constructs an array from source, shape and backend. Note that if the source
914
- * is a backend `Slot`, this constructor _takes ownership_ of the slot. It
915
- * will be freed when the array is disposed.
916
- */
917
- constructor(args: ArrayConstructorArgs);
918
- /** @ignore */
919
- get aval(): ShapedArray;
920
- /** Return a simple string representation of the array's dimensions. */
921
- toString(): string;
922
- get device(): Device;
923
- get ref(): this;
924
- dispose(): void;
925
- /**
926
- * Convert this array into a primitive value.
927
- *
928
- * This only works for scalars (0-dimensional arrays). It lets you get values
929
- * "out" of the JAX system. For instance, if `x = np.array(5)`, then you can
930
- * evaluate `x + 1` and `x ** 2` to get `6` and `25`, respectively.
931
- *
932
- * This method is also called for `==` equality.
933
- */
934
- [Symbol.toPrimitive](): any;
935
- /** Realize the array and return it as data. */
936
- data(): Promise<DataArray>;
937
- /**
938
- * Wait for this array to finish evaluation.
939
- *
940
- * Operations and data loading in jax-js are lazy, so this function ensures
941
- * that pending operations are dispatched and fully executed before it
942
- * returns.
943
- *
944
- * If you are mapping from `data()` or `dataSync()`, it will also trigger
945
- * dispatch of operations as well.
946
- *
947
- * **Note:** `jax.blockUntilReady()` is a higher-level API, it calls this
948
- * asynchronously for multiple arrays.
949
- */
950
- blockUntilReady(): Promise<Array>;
951
- /**
952
- * Realize the array and return it as data. This is a sync variant and not
953
- * recommended for performance reasons, as it will block rendering.
954
- */
955
- dataSync(): DataArray;
956
- /**
957
- * Convert this array into a JavaScript object.
958
- *
959
- * This is a blocking operation that will compile all of the shaders and wait
960
- * for execution to complete, synchronously. No other JavaScript code on the
961
- * site will be run during shader execution.
962
- *
963
- * To avoid blocking, prefer `jsAsync()` when possible.
964
- */
965
- js(): any;
966
- /** Convert this array into a JavaScript object, asynchronously. */
967
- jsAsync(): Promise<any>;
968
- /**
969
- * Copy an element of an array to a numeric scalar and return it.
970
- *
971
- * Throws an error if the array does not have a single element. The array must
972
- * either be rank-0, or all dimensions of the shape are 1.
973
- */
974
- item(): number;
975
- /** @private Internal plumbing method for Array / Tracer ops. */
976
- static _implRules(): typeof implRules;
977
- /** @private */
978
- _realizeSource(): number;
979
- /** @private Put this array on a new backend, asynchronously. */
980
- _put(backend: Backend): Promise<Array>;
981
- /** @private Put this array on a new backend, synchronously. */
982
- _putSync(backend: Backend): Array;
983
- }
984
- /** Constructor for creating a new array from data. */
985
- declare function array(values: Array | Float16Array<ArrayBuffer> | Float32Array<ArrayBuffer> | Int32Array<ArrayBuffer> | Uint32Array<ArrayBuffer> | RecursiveArray<number> | RecursiveArray<boolean>, {
986
- shape,
987
- dtype,
988
- device
989
- }?: {
990
- shape?: number[];
991
- } & DTypeAndDevice): Array;
992
- /** If x is a value, lift it into an array, otherwise leave it be. */
993
-
994
- type ImplRule<P extends Primitive> = (tracers: Array[], params: PrimitiveParams<P>) => Array[];
995
- declare const implRules: { [P in Primitive]: ImplRule<P> };
996
- /** Return a new array of given shape and type, filled with zeros. */
997
- declare function zeros(shape: number[], {
998
- dtype,
999
- device
1000
- }?: DTypeAndDevice): Array;
1001
- /** Return a new array of given shape and type, filled with ones. */
1002
- declare function ones(shape: number[], {
1003
- dtype,
1004
- device
1005
- }?: DTypeAndDevice): Array;
1006
- /** Return a new array of given shape and type, filled with `fill_value`. */
1007
- declare function full(shape: number[], fillValue: number | boolean | Array, {
1008
- dtype,
1009
- device
1010
- }?: DTypeAndDevice): Array;
1011
- /**
1012
- * Create an identity matrix.
1013
- *
1014
- * If numCols is not provided, it defaults to numRows, i.e., a square identity
1015
- * matrix with ones on the diagonal.
1016
- */
1017
- declare function eye(numRows: number, numCols?: number, {
1018
- dtype,
1019
- device
1020
- }?: DTypeAndDevice): Array;
1021
- /** Return the identity matrix, with ones on the main diagonal. */
1022
- declare function identity$1(n: number, {
1023
- dtype,
1024
- device
1025
- }?: DTypeAndDevice): Array;
1026
- /**
1027
- * Return evenly spaced values within a given interval.
1028
- *
1029
- * This can be called with a varying number of arguments, just like the range()
1030
- * builtin function in Python.
1031
- *
1032
- * - `arange(stop)` is equivalent to `arange(0, stop, 1)`.
1033
- * - `arange(start, stop)` is equivalent to `arange(start, stop, 1)`.
1034
- * - `arange(start, stop, step)` creates an array starting at `start`, ending
1035
- * before `stop`, with a step size of `step`.
1036
- *
1037
- * Defaults to an integer data type. This can produce unintended results when
1038
- * using a non-integer step, so prefer linspace() in those cases.
1039
- */
1040
- declare function arange(start: number, stop?: number, step?: number, {
1041
- dtype,
1042
- device
1043
- }?: DTypeAndDevice): Array;
1044
- /**
1045
- * Return evenly spaced numbers over a specified interval.
1046
- *
1047
- * Returns _num_ evenly spaced samples, calculated over the interval
1048
- * [`start`, `stop`]. The endpoint `stop` is included in the result by default,
1049
- * but this is controlled by the `endpoint` parameter.
1050
- *
1051
- * The default data type is Float32. Use arange() for integer steps.
1052
- */
1053
- declare function linspace(start: number, stop: number, num?: number, endpoint?: boolean, {
1054
- dtype,
1055
- device
1056
- }?: DTypeAndDevice): Array;
1057
- declare namespace numpy_d_exports {
1058
- export { Array, ArrayLike, DType, abs, absolute, acos, acosh, add, allclose, arange, arccos, arccosh, arcsinh, arctan, arctan2, arctanh, argmax, argmin, array, asin, asinh, astype, atan, atan2, atanh, bool, broadcastArrays, broadcastShapes, broadcastTo, cbrt, clip, columnStack, concatenate, cos, cosh, deg2rad, degrees, diag, diagonal, divide, dot, dstack, e, equal, eulerGamma, exp, exp2, expm1, eye, flip, fliplr, flipud, float16, float32, full, fullLike, greater, greaterEqual, hamming, hann, heaviside, hstack, hypot, identity$1 as identity, inf, inner, int32, less, lessEqual, linspace, log, log10, log1p, log2, matmul, max, maximum, mean, meshgrid, min, minimum, moveaxis, multiply, nan, ndim, negative, notEqual, ones, onesLike, outer, pad, permuteDims, pi, pow, power, prod, promoteTypes, rad2deg, radians, ravel, reciprocal, repeat, reshape, shape$1 as shape, sign, sin, sinh, size, sqrt, square, stack, std, subtract, sum, tan, tanh, tile, transpose, tri, tril, triu, trueDivide, trunc, uint32, var_, vdot, vecdot, vstack, where, zeros, zerosLike };
1059
- }
1060
- declare const float32 = DType.Float32;
1061
- declare const int32 = DType.Int32;
1062
- declare const uint32 = DType.Uint32;
1063
- declare const bool = DType.Bool;
1064
- declare const float16 = DType.Float16;
1065
- /** Euler's constant, `e = 2.7182818284590...` */
1066
- declare const e: number;
1067
- /** Euler-Mascheroni constant, `γ = 0.5772156649...` */
1068
- declare const eulerGamma = 0.5772156649015329;
1069
- /** Positive infinity. */
1070
- declare const inf: number;
1071
- /** Floating-point representation of NaN. */
1072
- declare const nan: number;
1073
- /** This is Pi, `π = 3.14159265358979...` */
1074
- declare const pi: number;
1075
- /** @function Element-wise addition, with broadcasting. */
1076
- declare const add: (x: ArrayLike, y: ArrayLike) => Array;
1077
- /** @function Element-wise multiplication, with broadcasting. */
1078
- declare const multiply: (x: ArrayLike, y: ArrayLike) => Array;
1079
- /** @function Numerical negative of every element of an array. */
1080
- declare const negative: (x: ArrayLike) => Array;
1081
- /** @function Calculate element-wise reciprocal of the input. This is `1/x`. */
1082
- declare const reciprocal: (x: ArrayLike) => Array;
1083
- /** @function Element-wise sine function (takes radians). */
1084
- declare const sin: (x: ArrayLike) => Array;
1085
- /** @function Element-wise cosine function (takes radians). */
1086
- declare const cos: (x: ArrayLike) => Array;
1087
- /** @function Element-wise inverse sine function (inverse of sin). */
1088
- declare const asin: (x: ArrayLike) => Array;
1089
- /** @function Element-wise inverse tangent function (inverse of tan). */
1090
- declare const atan: (x: ArrayLike) => Array;
1091
- /** @function Calculate the exponential of all elements in the input array. */
1092
- declare const exp: (x: ArrayLike) => Array;
1093
- /** @function Calculate the natural logarithm of all elements in the input array. */
1094
- declare const log: (x: ArrayLike) => Array;
1095
- /** @function Calculate the square root of all elements in the input array. */
1096
- declare const sqrt: (x: ArrayLike) => Array;
1097
- /** @function Return element-wise minimum of the input arrays. */
1098
- declare const minimum: (x: ArrayLike, y: ArrayLike) => Array;
1099
- /** @function Return element-wise maximum of the input arrays. */
1100
- declare const maximum: (x: ArrayLike, y: ArrayLike) => Array;
1101
- /** @function Compare two arrays element-wise. */
1102
- declare const greater: (x: ArrayLike, y: ArrayLike) => Array;
1103
- /** @function Compare two arrays element-wise. */
1104
- declare const less: (x: ArrayLike, y: ArrayLike) => Array;
1105
- /** @function Compare two arrays element-wise. */
1106
- declare const equal: (x: ArrayLike, y: ArrayLike) => Array;
1107
- /** @function Compare two arrays element-wise. */
1108
- declare const notEqual: (x: ArrayLike, y: ArrayLike) => Array;
1109
- /** @function Compare two arrays element-wise. */
1110
- declare const greaterEqual: (x: ArrayLike, y: ArrayLike) => Array;
1111
- /** @function Compare two arrays element-wise. */
1112
- declare const lessEqual: (x: ArrayLike, y: ArrayLike) => Array;
1113
- /** @function Element-wise ternary operator, evaluates to `x` if cond else `y`. */
1114
- declare const where: (cond: ArrayLike, x: ArrayLike, y: ArrayLike) => Array;
1115
- /**
1116
- * @function
1117
- * Permute the dimensions of an array. Defaults to reversing the axis order.
1118
- */
1119
- declare const transpose: (x: ArrayLike, perm?: number[]) => Array;
1120
- /**
1121
- * @function
1122
- * Give a new shape to an array without changing its data.
1123
- *
1124
- * One shape dimension can be -1. In this case, the value is inferred from the
1125
- * length of the array and remaining dimensions.
1126
- */
1127
- declare const reshape: (x: ArrayLike, shape: number[]) => Array;
1128
- /**
1129
- * @function
1130
- * Move axes of an array to new positions. Other axes retain original order.
540
+ * @function
541
+ * Move axes of an array to new positions. Other axes retain original order.
1131
542
  */
1132
543
  declare const moveaxis: (x: ArrayLike, src: number, dst: number) => Array;
1133
544
  /**
@@ -1176,6 +587,8 @@ declare function prod(a: ArrayLike, axis?: Axis, opts?: ReduceOpts): Array;
1176
587
  declare function min(a: ArrayLike, axis?: Axis, opts?: ReduceOpts): Array;
1177
588
  /** Return the maximum of array elements along a given axis. */
1178
589
  declare function max(a: ArrayLike, axis?: Axis, opts?: ReduceOpts): Array;
590
+ /** Return the peak-to-peak range along a given axis (`max - min`). */
591
+ declare function ptp(a: ArrayLike, axis?: Axis, opts?: ReduceOpts): Array;
1179
592
  /** Compute the average of the array elements along the specified axis. */
1180
593
  declare function mean(a: ArrayLike, axis?: Axis, opts?: ReduceOpts): Array;
1181
594
  /**
@@ -1241,6 +654,8 @@ declare function fliplr(x: ArrayLike): Array;
1241
654
  declare const permuteDims: (x: ArrayLike, perm?: number[]) => Array;
1242
655
  /** Return a 1-D flattened array containing the elements of the input. */
1243
656
  declare function ravel(a: ArrayLike): Array;
657
+ /** Remove one or more length-1 axes from an array. */
658
+ declare function squeeze(a: ArrayLike, axis?: Axis): Array;
1244
659
  /**
1245
660
  * Repeat each element of an array after themselves.
1246
661
  *
@@ -1285,6 +700,8 @@ declare function diagonal(a: ArrayLike, offset?: number, axis1?: number, axis2?:
1285
700
  * array, return a 2D array with v on the k-th diagonal.
1286
701
  */
1287
702
  declare function diag(v: ArrayLike, k?: number): Array;
703
+ /** Calculate the sum of the diagonal of an array along the given axes. */
704
+ declare function trace(a: ArrayLike, offset?: number, axis1?: number, axis2?: number): Array;
1288
705
  /** Return if two arrays are element-wise equal within a tolerance. */
1289
706
  declare function allclose(actual: Parameters<typeof array>[0], expected: Parameters<typeof array>[0], options?: {
1290
707
  rtol?: number;
@@ -1293,7 +710,41 @@ declare function allclose(actual: Parameters<typeof array>[0], expected: Paramet
1293
710
  /** Matrix product of two arrays. */
1294
711
  declare function matmul(x: ArrayLike, y: ArrayLike): Array;
1295
712
  /** Dot product of two arrays. */
1296
- declare function dot(x: ArrayLike, y: ArrayLike): Array;
713
+ declare function dot$1(x: ArrayLike, y: ArrayLike): Array;
714
+ /**
715
+ * Compute the tensor dot product of two N-dimensional arrays.
716
+ *
717
+ * The behavior is determined by `axes`. If an integer `k`, sum over the last
718
+ * `k` axes of x and the first `k` axes of y. If a tuple, then the first array
719
+ * corresponds to the axes of x and the second to the axes of y.
720
+ */
721
+ declare function tensordot(x: ArrayLike, y: ArrayLike, axes?: number | [number[], number[]]): Array;
722
+ /**
723
+ * Einstein summation with string subscripts.
724
+ *
725
+ * @example
726
+ * ```ts
727
+ * import { numpy as np } from "@jax-js/jax";
728
+ *
729
+ * const a = np.ones([2, 3]);
730
+ * const b = np.ones([3]);
731
+ * np.einsum("ij,j", a, b); // Shape [2]
732
+ * ```
733
+ */
734
+ declare function einsum(subscripts: string, ...operands: ArrayLike[]): Array;
735
+ /**
736
+ * Einstein summation alternating between arrays and numeric indices.
737
+ *
738
+ * @example
739
+ * ```ts
740
+ * import { numpy as np } from "@jax-js/jax";
741
+ *
742
+ * const a = np.ones([2, 3]);
743
+ * const b = np.ones([3]);
744
+ * np.einsum(a, [0, 1], b, [1]); // Shape [2]
745
+ * ```
746
+ */
747
+ declare function einsum(...args: (ArrayLike | number[])[]): Array;
1297
748
  /**
1298
749
  * Compute the inner product of two arrays.
1299
750
  *
@@ -1368,6 +819,8 @@ declare function absolute(x: ArrayLike): Array;
1368
819
  declare const abs: typeof absolute;
1369
820
  /** Return an element-wise indication of sign of the input. */
1370
821
  declare function sign(x: ArrayLike): Array;
822
+ /** @function Return element-wise positive values of the input (no-op). */
823
+ declare const positive: (x: ArrayLike) => Array;
1371
824
  /**
1372
825
  * Return the Hamming window of size M, a taper with a weighted cosine bell.
1373
826
  *
@@ -1404,213 +857,880 @@ declare function acos(x: ArrayLike): Array;
1404
857
  */
1405
858
  declare const hypot: OwnedFunction<(x1: ArrayLike, x2: ArrayLike) => Array>;
1406
859
  /**
1407
- * @function
1408
- * Element-wise arc tangent of y/x with correct quadrant.
1409
- *
1410
- * Returns the angle in radians between the positive x-axis and the point (x, y).
1411
- * The result is in the range [-π, π].
1412
- *
1413
- * Uses numerically stable formulas:
1414
- * - When x >= 0: atan2(y, x) = 2 * atan(y / (sqrt(x^2 + y^2) + x))
1415
- * - When x < 0: atan2(y, x) = 2 * atan((sqrt(x^2 + y^2) - x) / y)
860
+ * @function
861
+ * Element-wise arc tangent of y/x with correct quadrant.
862
+ *
863
+ * Returns the angle in radians between the positive x-axis and the point (x, y).
864
+ * The result is in the range [-π, π].
865
+ *
866
+ * Uses numerically stable formulas:
867
+ * - When x >= 0: atan2(y, x) = 2 * atan(y / (sqrt(x^2 + y^2) + x))
868
+ * - When x < 0: atan2(y, x) = 2 * atan((sqrt(x^2 + y^2) - x) / y)
869
+ *
870
+ * The output is ill-defined when both x and y are zero.
871
+ */
872
+ declare const atan2: OwnedFunction<(y: ArrayLike, x: ArrayLike) => Array>;
873
+ /** @function Alias of `jax.numpy.acos()`. */
874
+ declare const arccos: typeof acos;
875
+ /** @function Alias of `jax.numpy.atan()`. */
876
+ declare const arctan: (x: ArrayLike) => Array;
877
+ /** @function Alias of `jax.numpy.atan2()`. */
878
+ declare const arctan2: OwnedFunction<(y: ArrayLike, x: ArrayLike) => Array>;
879
+ /** Element-wise subtraction, with broadcasting. */
880
+ declare function subtract(x: ArrayLike, y: ArrayLike): Array;
881
+ /** Calculates the floating-point division of x by y element-wise. */
882
+ declare function trueDivide(x: ArrayLike, y: ArrayLike): Array;
883
+ /**
884
+ * @function
885
+ * Calculate element-wise floating-point modulo operation.
886
+ */
887
+ declare const fmod: OwnedFunction<(x: ArrayLike, y: ArrayLike) => Array>;
888
+ /**
889
+ * @function
890
+ * Calculate element-wise remainder of the division (matches sign of y).
891
+ */
892
+ declare const remainder: OwnedFunction<(x: ArrayLike, y: ArrayLike) => Array>;
893
+ /** @function Alias of `jax.numpy.trueDivide()`. */
894
+ declare const divide: typeof trueDivide;
895
+ /** Round input to the nearest integer towards zero. */
896
+ declare function trunc(x: ArrayLike): Array;
897
+ /**
898
+ * Compute `x1 * 2 ** x2` as a standard multiplication and exponentiation.
899
+ *
900
+ * This is the inverse of `frexp()`.
901
+ */
902
+ declare function ldexp(x1: ArrayLike, x2: ArrayLike): Array;
903
+ /**
904
+ * Decompose floating-point values into mantissa and two's exponent.
905
+ *
906
+ * The mantissa is returned in the range `(-1, 1)` with magnitude `>= 0.5` if
907
+ * `x != 0`, and the exponent is an integer such that
908
+ * `x = mantissa * 2**exponent`.
909
+ */
910
+ declare function frexp(x: ArrayLike): [Array, Array];
911
+ /** Calculate `2**p` for all p in the input array. */
912
+ declare function exp2(p: ArrayLike): Array;
913
+ /** Return the base-2 logarithm of x, element-wise. */
914
+ declare function log2(x: ArrayLike): Array;
915
+ /** Return the base-10 logarithm of x, element-wise. */
916
+ declare function log10(x: ArrayLike): Array;
917
+ /** Calculate `exp(x) - 1` element-wise. */
918
+ declare function expm1(x: ArrayLike): Array;
919
+ /** Calculate the natural logarithm of `1 + x` element-wise. */
920
+ declare function log1p(x: ArrayLike): Array;
921
+ /** Convert angles from degrees to radians. */
922
+ declare function deg2rad(x: ArrayLike): Array;
923
+ /** @function Alias of `jax.numpy.deg2rad()`. */
924
+ declare const radians: typeof deg2rad;
925
+ /** Convert angles from radians to degrees. */
926
+ declare function rad2deg(x: ArrayLike): Array;
927
+ /** @function Alias of `jax.numpy.rad2deg()`. */
928
+ declare const degrees: typeof rad2deg;
929
+ /**
930
+ * @function
931
+ * Computes first array raised to power of second array, element-wise.
932
+ */
933
+ declare const power: OwnedFunction<(x1: ArrayLike, x2: ArrayLike) => Array>;
934
+ /** @function Alias of `jax.numpy.power()`. */
935
+ declare const pow: OwnedFunction<(x1: ArrayLike, x2: ArrayLike) => Array>;
936
+ /** @function Calculate the element-wise cube root of the input array. */
937
+ declare const cbrt: OwnedFunction<(x: ArrayLike) => Array>;
938
+ /**
939
+ * @function
940
+ * Calculate element-wise hyperbolic sine of input.
941
+ *
942
+ * `sinh(x) = (exp(x) - exp(-x)) / 2`
943
+ */
944
+ declare const sinh: OwnedFunction<(x: ArrayLike) => Array>;
945
+ /**
946
+ * @function
947
+ * Calculate element-wise hyperbolic cosine of input.
948
+ *
949
+ * `cosh(x) = (exp(x) + exp(-x)) / 2`
950
+ */
951
+ declare const cosh: OwnedFunction<(x: ArrayLike) => Array>;
952
+ /**
953
+ * @function
954
+ * Calculate element-wise hyperbolic tangent of input.
955
+ *
956
+ * `tanh(x) = sinh(x)/cosh(x) = (exp(x) - exp(-x)) / (exp(x) + exp(-x))`
957
+ */
958
+ declare const tanh: OwnedFunction<(x: ArrayLike) => Array>;
959
+ /**
960
+ * @function
961
+ * Calculate element-wise inverse hyperbolic sine of input.
962
+ *
963
+ * `arcsinh(x) = ln(x + sqrt(x^2 + 1))`
964
+ */
965
+ declare const arcsinh: OwnedFunction<(x: ArrayLike) => Array>;
966
+ /**
967
+ * @function
968
+ * Calculate element-wise inverse hyperbolic cosine of input.
969
+ *
970
+ * `arccosh(x) = ln(x + sqrt(x^2 - 1))`
971
+ */
972
+ declare const arccosh: OwnedFunction<(x: ArrayLike) => Array>;
973
+ /**
974
+ * @function
975
+ * Calculate element-wise inverse hyperbolic tangent of input.
976
+ *
977
+ * `arctanh(x) = 0.5 * ln((1 + x) / (1 - x))`
978
+ */
979
+ declare const arctanh: OwnedFunction<(x: ArrayLike) => Array>;
980
+ /** @function Alias of `jax.numpy.arcsinh()`. */
981
+ declare const asinh: OwnedFunction<(x: ArrayLike) => Array>;
982
+ /** @function Alias of `jax.numpy.arccosh()`. */
983
+ declare const acosh: OwnedFunction<(x: ArrayLike) => Array>;
984
+ /** @function Alias of `jax.numpy.arctanh()`. */
985
+ declare const atanh: OwnedFunction<(x: ArrayLike) => Array>;
986
+ /**
987
+ * Compute the variance of an array.
988
+ *
989
+ * The variance is computed for the flattened array by default, otherwise over
990
+ * the specified axis.
991
+ *
992
+ * If `correction` is provided, the divisor in calculation is `N - correction`,
993
+ * where `N` represents the number of elements (e.g., for Bessel's correction).
994
+ */
995
+ declare function var_(x: ArrayLike, axis?: Axis, opts?: {
996
+ mean?: ArrayLike;
997
+ correction?: number;
998
+ } & ReduceOpts): Array;
999
+ /**
1000
+ * Compute the standard deviation of an array.
1001
+ *
1002
+ * The standard deviation is computed for the flattened array by default,
1003
+ * otherwise over the specified axis.
1004
+ *
1005
+ * If `correction` is provided, the divisor in calculation is `N - correction`,
1006
+ * where `N` represents the number of elements (e.g., for Bessel's correction).
1007
+ */
1008
+ declare function std(x: ArrayLike, axis?: Axis, opts?: {
1009
+ mean?: ArrayLike;
1010
+ correction?: number;
1011
+ } & ReduceOpts): Array;
1012
+ /** Test element-wise for positive or negative infinity, return bool array. */
1013
+ declare function isinf(x: ArrayLike): Array;
1014
+ /** Test element-wise for NaN (Not a Number). */
1015
+ declare function isnan(x: ArrayLike): Array;
1016
+ /** Test element-wise for negative infinity, return bool array. */
1017
+ declare function isneginf(x: ArrayLike): Array;
1018
+ /** Test element-wise for positive infinity, return bool array. */
1019
+ declare function isposinf(x: ArrayLike): Array;
1020
+ /**
1021
+ * @function
1022
+ * Test element-wise for finite values (not infinity or NaN).
1023
+ */
1024
+ declare const isfinite: OwnedFunction<(x: ArrayLike) => Array>;
1025
+ //# sourceMappingURL=numpy.d.ts.map
1026
+ declare namespace tree_d_exports {
1027
+ export { JsTree, JsTreeDef, MapJsTree, NodeType, dispose, flatten, leaves, map, ref, structure, unflatten };
1028
+ }
1029
+ declare enum NodeType {
1030
+ Array = "Array",
1031
+ Object = "Object",
1032
+ Leaf = "Leaf",
1033
+ }
1034
+ /** Analog to the JAX "pytree" object, but for JavaScript. */
1035
+ type JsTree<T> = T | JsTree<T>[] | {
1036
+ [key: string]: JsTree<T>;
1037
+ };
1038
+ type Same<X, Y> = (<T>() => T extends X ? 1 : 2) extends (<T>() => T extends Y ? 1 : 2) ? true : false;
1039
+ type MappedJsTree<T, A, B> = T extends A ? B : T extends Array ? T : 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> };
1040
+ /** @ignore Convert a subtype of JsTree<A> into a JsTree<B>, with the same structure. */
1041
+ type MapJsTree<T, A, B> = Same<A, B> extends true ? T : MappedJsTree<T, A, B>;
1042
+ /** Represents the structure of a JsTree. */
1043
+ declare class JsTreeDef {
1044
+ readonly nodeType: NodeType;
1045
+ readonly nodeMetadata: any;
1046
+ readonly childTreedefs: JsTreeDef[];
1047
+ static leaf: JsTreeDef;
1048
+ constructor(nodeType: NodeType, nodeMetadata: any,
1049
+ // Must be comparable with deepEqual.
1050
+ childTreedefs: JsTreeDef[]);
1051
+ /** Get the total number of leaves in the tree. */
1052
+ get size(): number;
1053
+ /** Returns a string representation of this tree definition. */
1054
+ toString(root?: boolean): string;
1055
+ /** Compare this tree definition with another. */
1056
+ equals(other: JsTreeDef): boolean;
1057
+ }
1058
+ /** Flatten a structured object, returning the tree definition. */
1059
+ declare function flatten<T>(tree: JsTree<T>): [T[], JsTreeDef];
1060
+ /** Get the leaves of a tree. */
1061
+ declare function leaves<T>(tree: JsTree<T>): T[];
1062
+ /** Get the treedef for a tree. */
1063
+ declare function structure<T>(tree: JsTree<T>): JsTreeDef;
1064
+ /** Reconstruct a structured object from the flattened representation. */
1065
+ declare function unflatten<T>(treedef: JsTreeDef, leaves: Iterable<T>): JsTree<T>;
1066
+ /** Maps a multi-input function over pytree args to produce a new pytree. */
1067
+ declare function map<T, U, Tree extends JsTree<T>>(fn: (...args: T[]) => U, tree: Tree, ...rest: Tree[]): MapJsTree<Tree, T, U>;
1068
+ /** Take a reference of every array in a tree. */
1069
+ declare function ref<Tree extends JsTree<Array>>(tree: Tree): Tree;
1070
+ /** Dispose every array in a tree. */
1071
+ declare function dispose<Tree extends JsTree<Array>>(tree: Tree | null | undefined): void;
1072
+ //#endregion
1073
+ //#region src/frontend/convolution.d.ts
1074
+ /** Definition of a general dilated convolution. Should be valid on creation. */
1075
+ interface ConvParams {
1076
+ strides: number[];
1077
+ padding: [number, number][];
1078
+ lhsDilation: number[];
1079
+ rhsDilation: number[];
1080
+ }
1081
+ /**
1082
+ * Check that the shapes and parameters passed to convolution are valid.
1416
1083
  *
1417
- * The output is ill-defined when both x and y are zero.
1084
+ * If the check succeeds, returns the output shape.
1418
1085
  */
1419
- declare const atan2: OwnedFunction<(y: ArrayLike, x: ArrayLike) => Array>;
1420
- /** @function Alias of `jax.numpy.acos()`. */
1421
- declare const arccos: typeof acos;
1422
- /** @function Alias of `jax.numpy.atan()`. */
1423
- declare const arctan: (x: ArrayLike) => Array;
1424
- /** @function Alias of `jax.numpy.atan2()`. */
1425
- declare const arctan2: OwnedFunction<(y: ArrayLike, x: ArrayLike) => Array>;
1426
- /** Element-wise subtraction, with broadcasting. */
1427
- declare function subtract(x: ArrayLike, y: ArrayLike): Array;
1428
- /** Calculates the floating-point division of x by y element-wise. */
1429
- declare function trueDivide(x: ArrayLike, y: ArrayLike): Array;
1430
- /** @function Alias of `jax.numpy.trueDivide()`. */
1431
- declare const divide: typeof trueDivide;
1432
- /** Round input to the nearest integer towards zero. */
1433
- declare function trunc(x: ArrayLike): Array;
1434
- /** Calculate `2**p` for all p in the input array. */
1435
- declare function exp2(p: ArrayLike): Array;
1436
- /** Return the base-2 logarithm of x, element-wise. */
1437
- declare function log2(x: ArrayLike): Array;
1438
- /** Return the base-10 logarithm of x, element-wise. */
1439
- declare function log10(x: ArrayLike): Array;
1440
- /** Calculate `exp(x) - 1` element-wise. */
1441
- declare function expm1(x: ArrayLike): Array;
1442
- /** Calculate the natural logarithm of `1 + x` element-wise. */
1443
- declare function log1p(x: ArrayLike): Array;
1444
- /** Convert angles from degrees to radians. */
1445
- declare function deg2rad(x: ArrayLike): Array;
1446
- /** @function Alias of `jax.numpy.deg2rad()`. */
1447
- declare const radians: typeof deg2rad;
1448
- /** Convert angles from radians to degrees. */
1449
- declare function rad2deg(x: ArrayLike): Array;
1450
- /** @function Alias of `jax.numpy.rad2deg()`. */
1451
- declare const degrees: typeof rad2deg;
1086
+ //#endregion
1087
+ //#region src/frontend/jaxpr.d.ts
1452
1088
  /**
1453
- * @function
1454
- * Computes first array raised to power of second array, element-wise.
1089
+ * Function callback with an associated dispose() method.
1090
+ *
1091
+ * The dispose() method should be called to clean up any tracer resources needed
1092
+ * by the function after the last time it is called.
1455
1093
  */
1456
- declare const power: OwnedFunction<(x1: ArrayLike, x2: ArrayLike) => Array>;
1457
- /** @function Alias of `jax.numpy.power()`. */
1458
- declare const pow: OwnedFunction<(x1: ArrayLike, x2: ArrayLike) => Array>;
1459
- /** @function Calculate the element-wise cube root of the input array. */
1460
- declare const cbrt: OwnedFunction<(x: ArrayLike) => Array>;
1094
+ type OwnedFunction<F extends Function> = F & {
1095
+ dispose: () => void;
1096
+ };
1097
+ /** Variable in a Jaxpr expression. */
1098
+ declare class Var {
1099
+ #private;
1100
+ readonly id: number;
1101
+ readonly aval: ShapedArray;
1102
+ constructor(aval: ShapedArray);
1103
+ toString(): string;
1104
+ }
1105
+ /** Literal in a Jaxpr expression. Currently, only scalars are supported. */
1106
+ declare class Lit {
1107
+ readonly value: number;
1108
+ readonly aval: ShapedArray;
1109
+ get dtype(): DType;
1110
+ constructor(aval: AbstractValue, value: number);
1111
+ }
1112
+ type Atom = Var | Lit;
1113
+ declare class VarPrinter {
1114
+ #private;
1115
+ names: Map<Var, string>;
1116
+ name(v: Var): string;
1117
+ nameType(v: Var): string;
1118
+ }
1119
+ /** A single statement / binding in a Jaxpr, in ANF form. */
1120
+ declare class JaxprEqn {
1121
+ readonly primitive: Primitive;
1122
+ readonly inputs: Atom[];
1123
+ readonly params: Record<string, any>;
1124
+ readonly outBinders: Var[];
1125
+ constructor(primitive: Primitive, inputs: Atom[], params: Record<string, any>, outBinders: Var[]);
1126
+ pprint(usedVars?: Set<Var>, vp?: VarPrinter): PPrint;
1127
+ toString(): string;
1128
+ }
1129
+ /** Typed intermediate representation for traced computations. */
1130
+ declare class Jaxpr implements FpHashable {
1131
+ #private;
1132
+ readonly inBinders: Var[];
1133
+ readonly eqns: JaxprEqn[];
1134
+ readonly outs: Atom[];
1135
+ constructor(inBinders: Var[], eqns: JaxprEqn[], outs: Atom[]);
1136
+ pprint(): PPrint;
1137
+ toString(): string;
1138
+ /**
1139
+ * Gets a hash of this Jaxpr.
1140
+ *
1141
+ * Var identity is not considered in the hash, so two Jaxprs with the same
1142
+ * order of assignments and operators but different variable IDs will resolve
1143
+ * to the same hash (and toString representation).
1144
+ */
1145
+ getHash(): bigint;
1146
+ hash(state: FpHash): void;
1147
+ /**
1148
+ * Produce a simplified Jaxpr with basic optimizations applied.
1149
+ * - Trim away unused variables.
1150
+ * - Fold away *1, *0, or +0 operations against literals.
1151
+ * - Remove no-op movement operations.
1152
+ */
1153
+ simplify(): Jaxpr;
1154
+ /** Flattens nested JitCall in a Jaxpr. Useful for handling jit-of-jit. */
1155
+ flatten(): Jaxpr;
1156
+ }
1157
+ /** @inline */
1158
+ type JitOpts = {
1159
+ staticArgnums?: number[];
1160
+ };
1161
+ //#endregion
1162
+ //#region src/frontend/core.d.ts
1461
1163
  /**
1462
- * @function
1463
- * Calculate element-wise hyperbolic sine of input.
1164
+ * Frontend primitive operations, which are lowered into Kernel objects before
1165
+ * being dispatched to the backend.
1464
1166
  *
1465
- * `sinh(x) = (exp(x) - exp(-x)) / 2`
1167
+ * Any operation between arrays can be described in these parts. This is also
1168
+ * the set of primitives that can occur in Jaxpr programs, and the level at
1169
+ * which transformations like vmap, grad, and jvp occur. They are loosely based
1170
+ * on [XLA](https://openxla.org/xla/operation_semantics).
1171
+ *
1172
+ * All n-ary operations support broadcasting, with NumPy semantics.
1173
+ */
1174
+ declare enum Primitive {
1175
+ Add = "add",
1176
+ Mul = "mul",
1177
+ Idiv = "idiv",
1178
+ Mod = "mod",
1179
+ // uses sign of dividend, C-style, matches JS but not Python
1180
+ Neg = "neg",
1181
+ Reciprocal = "reciprocal",
1182
+ Floor = "floor",
1183
+ Ceil = "ceil",
1184
+ StopGradient = "stop_gradient",
1185
+ Cast = "cast",
1186
+ Bitcast = "bitcast",
1187
+ RandomBits = "random_bits",
1188
+ Sin = "sin",
1189
+ Cos = "cos",
1190
+ Asin = "asin",
1191
+ Atan = "atan",
1192
+ Exp = "exp",
1193
+ Log = "log",
1194
+ Erf = "erf",
1195
+ Erfc = "erfc",
1196
+ Sqrt = "sqrt",
1197
+ Min = "min",
1198
+ Max = "max",
1199
+ Reduce = "reduce",
1200
+ Dot = "dot",
1201
+ // sum(x*y, axis=-1)
1202
+ Conv = "conv",
1203
+ // see lax.conv_general_dilated
1204
+ Pool = "pool",
1205
+ PoolTranspose = "pool_transpose",
1206
+ Compare = "compare",
1207
+ Where = "where",
1208
+ Transpose = "transpose",
1209
+ Broadcast = "broadcast",
1210
+ Reshape = "reshape",
1211
+ Flip = "flip",
1212
+ Shrink = "shrink",
1213
+ Pad = "pad",
1214
+ Gather = "gather",
1215
+ JitCall = "jit_call",
1216
+ }
1217
+ interface PrimitiveParamsImpl extends Record<Primitive, Record<string, any>> {
1218
+ [Primitive.Cast]: {
1219
+ dtype: DType;
1220
+ };
1221
+ [Primitive.Bitcast]: {
1222
+ dtype: DType;
1223
+ };
1224
+ [Primitive.Reduce]: {
1225
+ op: AluOp;
1226
+ axis: number[];
1227
+ };
1228
+ [Primitive.Conv]: ConvParams;
1229
+ [Primitive.Pool]: {
1230
+ window: number[];
1231
+ strides: number[];
1232
+ };
1233
+ [Primitive.PoolTranspose]: {
1234
+ inShape: number[];
1235
+ window: number[];
1236
+ strides: number[];
1237
+ };
1238
+ [Primitive.Compare]: {
1239
+ op: CompareOp;
1240
+ };
1241
+ [Primitive.Transpose]: {
1242
+ perm: number[];
1243
+ };
1244
+ [Primitive.Broadcast]: {
1245
+ shape: number[];
1246
+ axis: number[];
1247
+ };
1248
+ [Primitive.RandomBits]: {
1249
+ shape: number[];
1250
+ mode: "xor" | 0 | 1;
1251
+ };
1252
+ [Primitive.Reshape]: {
1253
+ shape: number[];
1254
+ };
1255
+ [Primitive.Flip]: {
1256
+ axis: number[];
1257
+ };
1258
+ [Primitive.Shrink]: {
1259
+ slice: Pair[];
1260
+ };
1261
+ [Primitive.Pad]: {
1262
+ width: Pair[];
1263
+ };
1264
+ [Primitive.Gather]: {
1265
+ axis: number[];
1266
+ outDim: number;
1267
+ };
1268
+ [Primitive.JitCall]: {
1269
+ name: string;
1270
+ jaxpr: Jaxpr;
1271
+ numConsts: number;
1272
+ };
1273
+ }
1274
+ /** Type of parameters taken by each primitive. */
1275
+ type PrimitiveParams<T extends Primitive> = T extends keyof PrimitiveParamsImpl ? PrimitiveParamsImpl[T] : Record<string, never>;
1276
+ declare enum CompareOp {
1277
+ Less = "less",
1278
+ Equal = "equal",
1279
+ NotEqual = "not_equal",
1280
+ LessEqual = "less_equal",
1281
+ }
1282
+ /** @inline */
1283
+ type Axis = number | number[] | null;
1284
+ /** @inline */
1285
+ type ReduceOpts = {
1286
+ keepdims?: boolean;
1287
+ };
1288
+ type MainTrace = {
1289
+ level: number;
1290
+ traceType: new (main: MainTrace) => Trace;
1291
+ globalData: any | null;
1292
+ };
1293
+ /**
1294
+ * Push an interpreter onto the trace stack. Use this like:
1295
+ * `using main = newMain(...);`
1466
1296
  */
1467
- declare const sinh: OwnedFunction<(x: ArrayLike) => Array>;
1297
+
1298
+ type TracerValue = Tracer | number | boolean;
1299
+ declare abstract class Trace {
1300
+ readonly main: MainTrace;
1301
+ constructor(main: MainTrace);
1302
+ abstract pure(val: TracerValue): Tracer;
1303
+ abstract lift(val: Tracer): Tracer;
1304
+ abstract processPrimitive<P extends Primitive>(primitive: P, tracers: Tracer[], params: PrimitiveParams<P>): Tracer[];
1305
+ }
1306
+ /** Internal representation of an array value. */
1307
+ interface AbstractValue {
1308
+ /** Shape of the array. Must be a static tuple of non-negative dimensions. */
1309
+ shape: number[];
1310
+ /** Concrete data type of array elements. */
1311
+ dtype: DType;
1312
+ /**
1313
+ * Arrays created from JavaScript numbers (e.g., `np.array(3)`) are created as
1314
+ * _weakly typed_ unless a dtype is explicitly specified.
1315
+ *
1316
+ * Weakly typed values will automatically cast to the data type of other
1317
+ * arrays when used as an operand as an expression. This property only affects
1318
+ * how they promote in type casting; their memory layout is still determined
1319
+ * by the actual `dtype` field.
1320
+ *
1321
+ * ```ts
1322
+ * const x = np.array(3); // weakType = true, dtype = float32
1323
+ * const y = np.array([1, 2], { dtype: np.int32 }); // weakType = false, dtype = int32
1324
+ * const z = x.add(y); // z has dtype int32 because x is weakly typed
1325
+ * ```
1326
+ *
1327
+ * Weak types are present in JIT programs in their spec (e.g., Jaxpr inputs
1328
+ * and outputs can be weakly typed) form. But they're solely a frontend
1329
+ * concept. Backends are not aware of weak types.
1330
+ */
1331
+ weakType: boolean;
1332
+ }
1468
1333
  /**
1469
- * @function
1470
- * Calculate element-wise hyperbolic cosine of input.
1334
+ * Broadcast shapes and promote types with casting for two avals.
1471
1335
  *
1472
- * `cosh(x) = (exp(x) + exp(-x)) / 2`
1336
+ * This implements the weak type behavior described in `promoteTypes()`, but not
1337
+ * implemented in that function as `weakType` is not passed.
1473
1338
  */
1474
- declare const cosh: OwnedFunction<(x: ArrayLike) => Array>;
1339
+
1340
+ declare abstract class Tracer {
1341
+ /** @ignore */
1342
+ readonly _trace: Trace;
1343
+ constructor(trace: Trace);
1344
+ abstract get aval(): AbstractValue;
1345
+ abstract toString(): string;
1346
+ /**
1347
+ * Access an array by reference, incrementing the reference count.
1348
+ *
1349
+ * jax-js handles freeing arrays by using "move" semantics, like in Rust/C++.
1350
+ * Whenever you pass an array into a function, that function should consume
1351
+ * the array, and it will no longer be usable. For example, if you had:
1352
+ *
1353
+ * ```
1354
+ * const x = np.array([1, 2, 3]);
1355
+ * const y = np.add(x, x);
1356
+ * ```
1357
+ *
1358
+ * The second line does not work because the first parameter consumes `x`, and
1359
+ * then the second parameter will already have been freed / disposed.
1360
+ *
1361
+ * To fix this, you can write:
1362
+ *
1363
+ * ```
1364
+ * const y = np.add(x.ref, x);
1365
+ * ```
1366
+ *
1367
+ * Under the hood, every access to `.ref` increments the internal reference
1368
+ * count of the array. The reference count starts at 1. When it hits 0, the
1369
+ * memory behind the array is freed.
1370
+ */
1371
+ abstract get ref(): this;
1372
+ /**
1373
+ * Manually decrement the reference count of the array.
1374
+ *
1375
+ * Arrays are created with reference count 1. Whenever it is used as argument
1376
+ * to a function or other operation, it is disposed (i.e., reference count
1377
+ * decreases by 1) automatically. Whenever a `.ref` is created, the reference
1378
+ * count increases.
1379
+ *
1380
+ * You generally don't need to call this function directly since arrays are
1381
+ * automatically disposed after being passed into an operation. One common
1382
+ * exception is when writing a function and ignoring one of its arguments. In
1383
+ * that case, by convention you should dispose of that argument manually.
1384
+ *
1385
+ * ```
1386
+ * function myCustomOperation(a: np.Array, b: np.Array) {
1387
+ * b.dispose(); // Needed to satisfy "move" rules.
1388
+ * return a.add(1);
1389
+ * }
1390
+ * ```
1391
+ */
1392
+ abstract dispose(): void;
1393
+ /** The shape of the array. */
1394
+ get shape(): number[];
1395
+ /** The total number of elements in the array. */
1396
+ get size(): number;
1397
+ /** The dtype of elements stored in the array. */
1398
+ get dtype(): DType;
1399
+ /**
1400
+ * Whether the array is weakly typed.
1401
+ *
1402
+ * Weakly typed arrays will cast to the dtype of the other operand. See
1403
+ * `promoteTypes()` for details.
1404
+ */
1405
+ get weakType(): boolean;
1406
+ /** The number of dimensions of the array. */
1407
+ get ndim(): number;
1408
+ /** @ignore */
1409
+ fullLower(): Tracer;
1410
+ neg(): this;
1411
+ add(other: this | TracerValue): this;
1412
+ mul(other: this | TracerValue): this;
1413
+ greater(other: this | TracerValue): this;
1414
+ less(other: this | TracerValue): this;
1415
+ equal(other: this | TracerValue): this;
1416
+ notEqual(other: this | TracerValue): this;
1417
+ greaterEqual(other: this | TracerValue): this;
1418
+ lessEqual(other: this | TracerValue): this;
1419
+ /** Sum of the elements of the array over a given axis, or axes. */
1420
+ sum(axis?: Axis, opts?: ReduceOpts): this;
1421
+ /** Product of the array elements over a given axis. */
1422
+ prod(axis?: Axis, opts?: ReduceOpts): this;
1423
+ /** Compute the average of the array elements along the specified axis. */
1424
+ mean(axis?: Axis, opts?: ReduceOpts): this;
1425
+ /** Permute the dimensions of an array. Defaults to reversing the axis order. */
1426
+ transpose(perm?: number[]): this;
1427
+ /**
1428
+ * Give a new shape to an array without changing its data.
1429
+ *
1430
+ * One shape dimension can be -1. In this case, the value is inferred from the
1431
+ * length of the array and remaining dimensions.
1432
+ */
1433
+ reshape(shape: number | number[]): this;
1434
+ /** Copy the array and cast to a specified dtype. */
1435
+ astype(dtype: DType): this;
1436
+ /** Subtract an array from this one. */
1437
+ sub(other: this | TracerValue): this;
1438
+ /** Divide an array by this one. */
1439
+ div(other: this | TracerValue): this;
1440
+ /** Return specified diagonals. See `numpy.diagonal` for full docs. */
1441
+ diagonal(offset?: number, axis1?: number, axis2?: number): this;
1442
+ /** Flatten the array without changing its data. */
1443
+ flatten(): this;
1444
+ /** Flatten the array without changing its data. */
1445
+ ravel(): this;
1446
+ /**
1447
+ * Iterate over the first dimension of this array, returning slices.
1448
+ *
1449
+ * This can be used to destructure arrays. For example:
1450
+ *
1451
+ * ```js
1452
+ * let x = np.array([[1, 2], [3, 4]]);
1453
+ * let [a, b] = x;
1454
+ * console.log(a.js()); // [1, 2]
1455
+ * console.log(b.js()); // [3, 4]
1456
+ * ```
1457
+ */
1458
+ [Symbol.iterator](): IterableIterator<this>;
1459
+ /**
1460
+ * Slice an array along one or more axes.
1461
+ *
1462
+ * This is the equivalent of slicing in Python, e.g. `x[1:3, 2, :, None]`. To
1463
+ * mimic this in JavaScript, we would write:
1464
+ *
1465
+ * ```js
1466
+ * x.slice([1, 3], 2, [], null);
1467
+ * ```
1468
+ *
1469
+ * The `slice` method accepts a variable number of arguments, each of which
1470
+ * can be a number, an empty array, a single-element array, a two-element
1471
+ * array, or `null`. The arguments are interpreted as follows:
1472
+ *
1473
+ * - A number `n` means to access the `n`-th element along that axis, removing
1474
+ * that axis from the resulting shape.
1475
+ * - An empty array `[]` means to keep that axis as-is, like `:` in Python.
1476
+ * - A single-element array `[i]` means to start slicing from index `i`
1477
+ * (inclusive) to the end of the axis, like `x[i:]`.
1478
+ * - A two-element array `[i, j]` means to slice from index `i` (inclusive)
1479
+ * to index `j` (exclusive), like `x[i:j]`.
1480
+ * - `null` means to add a new axis at that position, like `np.newaxis`.
1481
+ *
1482
+ * Like in Python, negative indices are supported, which count from the end of
1483
+ * the axis. For example, `-1` means the last element.
1484
+ *
1485
+ * Strided slices are not yet implemented, so you cannot write `x[::2]` or
1486
+ * similar.
1487
+ *
1488
+ * Advanced indexing by integer arrays is also supported. This translates to
1489
+ * the "gather" primitive, and it allows you to access specific elements of
1490
+ * the array by integer indices stored in another array.
1491
+ */
1492
+ slice(...index: (number | [] | [number] | Pair | null | Tracer)[]): this;
1493
+ }
1494
+ declare class ShapedArray implements AbstractValue {
1495
+ readonly shape: number[];
1496
+ readonly dtype: DType;
1497
+ readonly weakType: boolean;
1498
+ constructor(shape: number[], dtype: DType, weakType: boolean);
1499
+ static fromAval(aval: AbstractValue): ShapedArray;
1500
+ get ndim(): number;
1501
+ toString(): string;
1502
+ equals(other: ShapedArray): boolean;
1503
+ }
1504
+ //#endregion
1505
+ //#region src/frontend/array.d.ts
1506
+ type ArrayLike = Array | number | boolean;
1507
+ /** Version of pureArray with fudged types. */
1508
+
1475
1509
  /**
1476
- * @function
1477
- * Calculate element-wise hyperbolic tangent of input.
1510
+ * An executable operation that will be dispatched to the backend.
1478
1511
  *
1479
- * `tanh(x) = sinh(x)/cosh(x) = (exp(x) - exp(-x)) / (exp(x) + exp(-x))`
1512
+ * This holds a reference to all input buffers used in the operation. After the
1513
+ * operation is dispatched, the references should be released.
1480
1514
  */
1481
- declare const tanh: OwnedFunction<(x: ArrayLike) => Array>;
1515
+ declare class PendingExecute {
1516
+ #private;
1517
+ readonly backend: Backend;
1518
+ readonly kernel: Kernel;
1519
+ readonly inputs: Slot[];
1520
+ readonly outputs: Slot[];
1521
+ prepared: Executable | null;
1522
+ submitted: boolean;
1523
+ constructor(backend: Backend, kernel: Kernel, inputs: Slot[], outputs: Slot[]);
1524
+ updateRc(delta: number): void;
1525
+ prepare(): Promise<void>;
1526
+ prepareSync(): void;
1527
+ submit(): void;
1528
+ }
1529
+ /** @inline */
1530
+ type DTypeAndDevice = {
1531
+ dtype?: DType;
1532
+ device?: Device;
1533
+ };
1534
+ type ArrayConstructorArgs = {
1535
+ source: AluExp | Slot;
1536
+ st: ShapeTracker;
1537
+ dtype: DType;
1538
+ weakType: boolean;
1539
+ backend: Backend;
1540
+ committed: boolean;
1541
+ pending?: Iterable<PendingExecute>;
1542
+ };
1482
1543
  /**
1483
- * @function
1484
- * Calculate element-wise inverse hyperbolic sine of input.
1544
+ * A multidimensional numeric array with data stored on CPU or GPU.
1485
1545
  *
1486
- * `arcsinh(x) = ln(x + sqrt(x^2 + 1))`
1546
+ * This is the library's core data type. Equivalent to `jax.Array` from JAX, or
1547
+ * `torch.Tensor`.
1548
+ *
1549
+ * Not to be confused with the JavaScript "Array" constructor. Avoid importing
1550
+ * this into your code's namespace if you're already using the JavaScript
1551
+ * "Array" type by name.
1487
1552
  */
1488
- declare const arcsinh: OwnedFunction<(x: ArrayLike) => Array>;
1553
+ declare class Array extends Tracer {
1554
+ #private;
1555
+ id: number;
1556
+ /**
1557
+ * @ignore
1558
+ * Constructs an array from source, shape and backend. Note that if the source
1559
+ * is a backend `Slot`, this constructor _takes ownership_ of the slot. It
1560
+ * will be freed when the array is disposed.
1561
+ */
1562
+ constructor(args: ArrayConstructorArgs);
1563
+ /** @ignore */
1564
+ get aval(): ShapedArray;
1565
+ /** Return a simple string representation of the array's dimensions. */
1566
+ toString(): string;
1567
+ get device(): Device;
1568
+ get ref(): this;
1569
+ dispose(): void;
1570
+ /**
1571
+ * Convert this array into a primitive value.
1572
+ *
1573
+ * This only works for scalars (0-dimensional arrays). It lets you get values
1574
+ * "out" of the JAX system. For instance, if `x = np.array(5)`, then you can
1575
+ * evaluate `x + 1` and `x ** 2` to get `6` and `25`, respectively.
1576
+ *
1577
+ * This method is also called for `==` equality.
1578
+ */
1579
+ [Symbol.toPrimitive](): any;
1580
+ /** Realize the array and return it as data. */
1581
+ data(): Promise<DataArray>;
1582
+ /**
1583
+ * Wait for this array to finish evaluation.
1584
+ *
1585
+ * Operations and data loading in jax-js are lazy, so this function ensures
1586
+ * that pending operations are dispatched and fully executed before it
1587
+ * returns.
1588
+ *
1589
+ * If you are mapping from `data()` or `dataSync()`, it will also trigger
1590
+ * dispatch of operations as well.
1591
+ *
1592
+ * **Note:** `jax.blockUntilReady()` is a higher-level API, it calls this
1593
+ * asynchronously for multiple arrays.
1594
+ */
1595
+ blockUntilReady(): Promise<Array>;
1596
+ /**
1597
+ * Realize the array and return it as data. This is a sync variant and not
1598
+ * recommended for performance reasons, as it will block rendering.
1599
+ */
1600
+ dataSync(): DataArray;
1601
+ /**
1602
+ * Convert this array into a JavaScript object.
1603
+ *
1604
+ * This is a blocking operation that will compile all of the shaders and wait
1605
+ * for execution to complete, synchronously. No other JavaScript code on the
1606
+ * site will be run during shader execution.
1607
+ *
1608
+ * To avoid blocking, prefer `jsAsync()` when possible.
1609
+ */
1610
+ js(): any;
1611
+ /** Convert this array into a JavaScript object, asynchronously. */
1612
+ jsAsync(): Promise<any>;
1613
+ /**
1614
+ * Copy an element of an array to a numeric scalar and return it.
1615
+ *
1616
+ * Throws an error if the array does not have a single element. The array must
1617
+ * either be rank-0, or all dimensions of the shape are 1.
1618
+ */
1619
+ item(): number;
1620
+ /** @private Internal plumbing method for Array / Tracer ops. */
1621
+ static _implRules(): typeof implRules;
1622
+ /** @private */
1623
+ _realizeSource(): number;
1624
+ /** @private Put this array on a new backend, asynchronously. */
1625
+ _put(backend: Backend): Promise<Array>;
1626
+ /** @private Put this array on a new backend, synchronously. */
1627
+ _putSync(backend: Backend): Array;
1628
+ }
1629
+ /** Constructor for creating a new array from data. */
1630
+ declare function array(values: Array | DataArray | RecursiveArray<number> | RecursiveArray<boolean>, {
1631
+ shape,
1632
+ dtype,
1633
+ device
1634
+ }?: {
1635
+ shape?: number[];
1636
+ } & DTypeAndDevice): Array;
1637
+ /** If x is a value, lift it into an array, otherwise leave it be. */
1638
+
1639
+ type ImplRule<P extends Primitive> = (tracers: Array[], params: PrimitiveParams<P>) => Array[];
1640
+ declare const implRules: { [P in Primitive]: ImplRule<P> };
1641
+ /** Return a new array of given shape and type, filled with zeros. */
1642
+ declare function zeros(shape: number[], {
1643
+ dtype,
1644
+ device
1645
+ }?: DTypeAndDevice): Array;
1646
+ /** Return a new array of given shape and type, filled with ones. */
1647
+ declare function ones(shape: number[], {
1648
+ dtype,
1649
+ device
1650
+ }?: DTypeAndDevice): Array;
1651
+ /** Return a new array of given shape and type, filled with `fill_value`. */
1652
+ declare function full(shape: number[], fillValue: number | boolean | Array, {
1653
+ dtype,
1654
+ device
1655
+ }?: DTypeAndDevice): Array;
1489
1656
  /**
1490
- * @function
1491
- * Calculate element-wise inverse hyperbolic cosine of input.
1657
+ * Create an identity matrix.
1492
1658
  *
1493
- * `arccosh(x) = ln(x + sqrt(x^2 - 1))`
1659
+ * If numCols is not provided, it defaults to numRows, i.e., a square identity
1660
+ * matrix with ones on the diagonal.
1494
1661
  */
1495
- declare const arccosh: OwnedFunction<(x: ArrayLike) => Array>;
1662
+ declare function eye(numRows: number, numCols?: number, {
1663
+ dtype,
1664
+ device
1665
+ }?: DTypeAndDevice): Array;
1666
+ /** Return the identity matrix, with ones on the main diagonal. */
1667
+ declare function identity$1(n: number, {
1668
+ dtype,
1669
+ device
1670
+ }?: DTypeAndDevice): Array;
1496
1671
  /**
1497
- * @function
1498
- * Calculate element-wise inverse hyperbolic tangent of input.
1672
+ * Return evenly spaced values within a given interval.
1499
1673
  *
1500
- * `arctanh(x) = 0.5 * ln((1 + x) / (1 - x))`
1674
+ * This can be called with a varying number of arguments, just like the range()
1675
+ * builtin function in Python.
1676
+ *
1677
+ * - `arange(stop)` is equivalent to `arange(0, stop, 1)`.
1678
+ * - `arange(start, stop)` is equivalent to `arange(start, stop, 1)`.
1679
+ * - `arange(start, stop, step)` creates an array starting at `start`, ending
1680
+ * before `stop`, with a step size of `step`.
1681
+ *
1682
+ * Defaults to an integer data type. This can produce unintended results when
1683
+ * using a non-integer step, so prefer linspace() in those cases.
1501
1684
  */
1502
- declare const arctanh: OwnedFunction<(x: ArrayLike) => Array>;
1503
- /** @function Alias of `jax.numpy.arcsinh()`. */
1504
- declare const asinh: OwnedFunction<(x: ArrayLike) => Array>;
1505
- /** @function Alias of `jax.numpy.arccosh()`. */
1506
- declare const acosh: OwnedFunction<(x: ArrayLike) => Array>;
1507
- /** @function Alias of `jax.numpy.arctanh()`. */
1508
- declare const atanh: OwnedFunction<(x: ArrayLike) => Array>;
1685
+ declare function arange(start: number, stop?: number, step?: number, {
1686
+ dtype,
1687
+ device
1688
+ }?: DTypeAndDevice): Array;
1509
1689
  /**
1510
- * Compute the variance of an array.
1690
+ * Return evenly spaced numbers over a specified interval.
1511
1691
  *
1512
- * The variance is computed for the flattened array by default, otherwise over
1513
- * the specified axis.
1692
+ * Returns _num_ evenly spaced samples, calculated over the interval
1693
+ * [`start`, `stop`]. The endpoint `stop` is included in the result by default,
1694
+ * but this is controlled by the `endpoint` parameter.
1514
1695
  *
1515
- * If `correction` is provided, the divisor in calculation is `N - correction`,
1516
- * where `N` represents the number of elements (e.g., for Bessel's correction).
1696
+ * The default data type is Float32. Use arange() for integer steps.
1517
1697
  */
1518
- declare function var_(x: ArrayLike, axis?: Axis, opts?: {
1519
- mean?: ArrayLike;
1520
- correction?: number;
1521
- } & ReduceOpts): Array;
1698
+ declare function linspace(start: number, stop: number, num?: number, endpoint?: boolean, {
1699
+ dtype,
1700
+ device
1701
+ }?: DTypeAndDevice): Array;
1702
+ declare namespace lax_d_exports {
1703
+ export { DotDimensionNumbers, PaddingType, conv, convGeneralDilated, convWithGeneralPadding, dot, erf, erfc, reduceWindow, stopGradient };
1704
+ }
1522
1705
  /**
1523
- * Compute the standard deviation of an array.
1706
+ * Dimension numbers for general `dot()` primitive.
1524
1707
  *
1525
- * The standard deviation is computed for the flattened array by default,
1526
- * otherwise over the specified axis.
1708
+ * Contracting dimensions act as a tensor contraction (reduction) along the
1709
+ * given axis. They must be the same size in both operands. Batch dimensions
1710
+ * are treated as vectorized, leading batch dimensions.
1527
1711
  *
1528
- * If `correction` is provided, the divisor in calculation is `N - correction`,
1529
- * where `N` represents the number of elements (e.g., for Bessel's correction).
1712
+ * The return value has a shape where the first dimensions are shared batch
1713
+ * dimensions, followed by `lhs` non-contracting dimensions, followed by
1714
+ * `rhs` non-contracting dimensions.
1530
1715
  */
1531
- declare function std(x: ArrayLike, axis?: Axis, opts?: {
1532
- mean?: ArrayLike;
1533
- correction?: number;
1534
- } & ReduceOpts): Array;
1535
- //# sourceMappingURL=numpy.d.ts.map
1536
- //#endregion
1537
- //#region src/frontend/jaxpr.d.ts
1716
+ type DotDimensionNumbers = {
1717
+ lhsContractingDims?: number[];
1718
+ rhsContractingDims?: number[];
1719
+ lhsBatchDims?: number[];
1720
+ rhsBatchDims?: number[];
1721
+ };
1538
1722
  /**
1539
- * Function callback with an associated dispose() method.
1723
+ * General dot product/contraction operator.
1540
1724
  *
1541
- * The dispose() method should be called to clean up any tracer resources needed
1542
- * by the function after the last time it is called.
1725
+ * Prefer higher-level functions like `jax.numpy.dot()`, `jax.numpy.matmul()`,
1726
+ * `jax.numpy.tensordot(), and `jax.numpy.einsum()` where possible.
1543
1727
  */
1544
- type OwnedFunction<F extends Function> = F & {
1545
- dispose: () => void;
1546
- };
1547
- /** Variable in a Jaxpr expression. */
1548
- declare class Var {
1549
- #private;
1550
- readonly id: number;
1551
- readonly aval: ShapedArray;
1552
- constructor(aval: ShapedArray);
1553
- toString(): string;
1554
- }
1555
- /** Literal in a Jaxpr expression. Currently, only scalars are supported. */
1556
- declare class Lit {
1557
- readonly value: number;
1558
- readonly aval: ShapedArray;
1559
- get dtype(): DType;
1560
- constructor(aval: AbstractValue, value: number);
1561
- }
1562
- type Atom = Var | Lit;
1563
- declare class VarPrinter {
1564
- #private;
1565
- names: Map<Var, string>;
1566
- name(v: Var): string;
1567
- nameType(v: Var): string;
1568
- }
1569
- /** A single statement / binding in a Jaxpr, in ANF form. */
1570
- declare class JaxprEqn {
1571
- readonly primitive: Primitive;
1572
- readonly inputs: Atom[];
1573
- readonly params: Record<string, any>;
1574
- readonly outBinders: Var[];
1575
- constructor(primitive: Primitive, inputs: Atom[], params: Record<string, any>, outBinders: Var[]);
1576
- pprint(usedVars?: Set<Var>, vp?: VarPrinter): PPrint;
1577
- toString(): string;
1578
- }
1579
- /** Typed intermediate representation for traced computations. */
1580
- declare class Jaxpr implements FpHashable {
1581
- #private;
1582
- readonly inBinders: Var[];
1583
- readonly eqns: JaxprEqn[];
1584
- readonly outs: Atom[];
1585
- constructor(inBinders: Var[], eqns: JaxprEqn[], outs: Atom[]);
1586
- pprint(): PPrint;
1587
- toString(): string;
1588
- /**
1589
- * Gets a hash of this Jaxpr.
1590
- *
1591
- * Var identity is not considered in the hash, so two Jaxprs with the same
1592
- * order of assignments and operators but different variable IDs will resolve
1593
- * to the same hash (and toString representation).
1594
- */
1595
- getHash(): bigint;
1596
- hash(state: FpHash): void;
1597
- /**
1598
- * Produce a simplified Jaxpr with basic optimizations applied.
1599
- * - Trim away unused variables.
1600
- * - Fold away *1, *0, or +0 operations against literals.
1601
- * - Remove no-op movement operations.
1602
- */
1603
- simplify(): Jaxpr;
1604
- /** Flattens nested JitCall in a Jaxpr. Useful for handling jit-of-jit. */
1605
- flatten(): Jaxpr;
1606
- }
1607
- /** @inline */
1608
- type JitOpts = {
1609
- staticArgnums?: number[];
1610
- };
1611
- declare namespace lax_d_exports {
1612
- export { PaddingType, conv, convGeneralDilated, convWithGeneralPadding, erf, erfc, reduceWindow, stopGradient };
1613
- }
1728
+ declare function dot(lhs: Array, rhs: Array, {
1729
+ lhsContractingDims: lc,
1730
+ rhsContractingDims: rc,
1731
+ lhsBatchDims: lb,
1732
+ rhsBatchDims: rb
1733
+ }?: DotDimensionNumbers): Array;
1614
1734
  type PaddingType = "VALID" | "SAME" | "SAME_LOWER" | [number, number][];
1615
1735
  /**
1616
1736
  * General n-dimensional convolution operator, with optional dilation.