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