@jax-js/jax 0.1.6 → 0.1.8

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
@@ -538,1757 +538,1780 @@ declare class Executable<T = any> {
538
538
  source: Kernel | Routine, /** Extra data specific to the backend running this executable. */
539
539
  data: T);
540
540
  }
541
- declare namespace numpy_fft_d_exports {
542
- export { ComplexPair, fft, ifft };
541
+ declare namespace tree_d_exports {
542
+ export { JsTree, JsTreeDef, MapJsTree, NodeType, dispose, flatten, leaves, map, ref, structure, unflatten };
543
543
  }
544
- /**
545
- * A pair of arrays representing real and imaginary part `a + bj`. Both arrays
546
- * must have the same shape.
547
- */
548
- type ComplexPair = {
549
- real: Array;
550
- imag: Array;
544
+ declare enum NodeType {
545
+ Array = "Array",
546
+ Object = "Object",
547
+ Leaf = "Leaf",
548
+ }
549
+ /** Analog to the JAX "pytree" object, but for JavaScript. */
550
+ type JsTree<T> = T | JsTree<T>[] | {
551
+ [key: string]: JsTree<T>;
551
552
  };
552
- /**
553
- * Compute a one-dimensional discrete Fourier transform.
554
- *
555
- * Currently, the size of the axis must be a power of two.
556
- */
557
- declare function fft(a: ComplexPair, axis?: number): ComplexPair;
558
- /**
559
- * Compute a one-dimensional inverse discrete Fourier transform.
560
- *
561
- * Currently, the size of the axis must be a power of two.
562
- */
563
- declare function ifft(a: ComplexPair, axis?: number): ComplexPair;
564
- declare namespace numpy_linalg_d_exports {
565
- export { cholesky$1 as cholesky, det, diagonal, inv, lstsq, matmul, matrixPower, matrixTranspose, outer, slogdet, solve, tensordot, trace, vecdot };
553
+ type Same<X, Y> = (<T>() => T extends X ? 1 : 2) extends (<T>() => T extends Y ? 1 : 2) ? true : false;
554
+ 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> };
555
+ /** @ignore Convert a subtype of JsTree<A> into a JsTree<B>, with the same structure. */
556
+ type MapJsTree<T, A, B> = Same<A, B> extends true ? T : MappedJsTree<T, A, B>;
557
+ /** Represents the structure of a JsTree. */
558
+ declare class JsTreeDef {
559
+ readonly nodeType: NodeType;
560
+ readonly nodeMetadata: any;
561
+ readonly childTreedefs: JsTreeDef[];
562
+ static leaf: JsTreeDef;
563
+ constructor(nodeType: NodeType, nodeMetadata: any,
564
+ // Must be comparable with deepEqual.
565
+ childTreedefs: JsTreeDef[]);
566
+ /** Get the total number of leaves in the tree. */
567
+ get size(): number;
568
+ /** Returns a string representation of this tree definition. */
569
+ toString(root?: boolean): string;
570
+ /** Compare this tree definition with another. */
571
+ equals(other: JsTreeDef): boolean;
572
+ }
573
+ /** Flatten a structured object, returning the tree definition. */
574
+ declare function flatten<T>(tree: JsTree<T>): [T[], JsTreeDef];
575
+ /** Get the leaves of a tree. */
576
+ declare function leaves<T>(tree: JsTree<T>): T[];
577
+ /** Get the treedef for a tree. */
578
+ declare function structure<T>(tree: JsTree<T>): JsTreeDef;
579
+ /** Reconstruct a structured object from the flattened representation. */
580
+ declare function unflatten<T>(treedef: JsTreeDef, leaves: Iterable<T>): JsTree<T>;
581
+ /** Maps a multi-input function over pytree args to produce a new pytree. */
582
+ declare function map<T, U, Tree extends JsTree<T>>(fn: (...args: T[]) => U, tree: Tree, ...rest: Tree[]): MapJsTree<Tree, T, U>;
583
+ /** Take a reference of every array in a tree. */
584
+ declare function ref<Tree extends JsTree<any>>(tree: Tree): Tree;
585
+ /** Dispose every array in a tree. */
586
+ declare function dispose<Tree extends JsTree<any>>(tree: Tree | null | undefined): void;
587
+ //#endregion
588
+ //#region src/frontend/convolution.d.ts
589
+ /** Definition of a general dilated convolution. Should be valid on creation. */
590
+ interface ConvParams {
591
+ vmapDims: number;
592
+ strides: number[];
593
+ padding: Pair[];
594
+ lhsDilation: number[];
595
+ rhsDilation: number[];
566
596
  }
567
597
  /**
568
- * Compute the Cholesky decomposition of a (batched) positive-definite matrix.
598
+ * Check that the shapes and parameters passed to convolution are valid.
599
+ * Expected shapes of the lhs and rhs of the convolution are:
569
600
  *
570
- * This is like `jax.lax.linalg.cholesky()`, except with an option to symmetrize
571
- * the input matrix, which is on by default.
601
+ * - `lhsShape = [*vmapDims, batchSize, inChannels, spatialDims...]`
602
+ * - `rhsShape = [*vmapDims, outChannels, inChannels, kernelSize...]`
603
+ *
604
+ * If the check succeeds, returns the output shape.
572
605
  */
573
- declare function cholesky$1(a: ArrayLike, {
574
- upper,
575
- symmetrizeInput
576
- }?: {
577
- upper?: boolean;
578
- symmetrizeInput?: boolean;
579
- }): Array;
580
- /** Compute the determinant of a square matrix (batched). */
581
- declare function det(a: ArrayLike): Array;
582
- /** Compute the inverse of a square matrix (batched). */
583
- declare function inv(a: ArrayLike): Array;
606
+ //#endregion
607
+ //#region src/frontend/jaxpr.d.ts
584
608
  /**
585
- * Return the least-squares solution to a linear equation.
586
- *
587
- * For overdetermined systems, this finds the `x` that minimizes `norm(ax - b)`.
588
- * For underdetermined systems, this finds the minimum-norm solution for `x`.
589
- *
590
- * This currently uses Cholesky decomposition to solve the normal equations,
591
- * under the hood. The method is not as robust as QR or SVD.
609
+ * Function callback with an associated dispose() method.
592
610
  *
593
- * @param a coefficient matrix of shape `(M, N)`
594
- * @param b right-hand side of shape `(M,)` or `(M, K)`
595
- * @return least-squares solution of shape `(N,)` or `(N, K)`
611
+ * The dispose() method should be called to clean up any tracer resources needed
612
+ * by the function after the last time it is called.
596
613
  */
597
- declare function lstsq(a: ArrayLike, b: ArrayLike): Array;
598
- /** Raise a square matrix to an integer power, via repeated squarings. */
599
- declare function matrixPower(a: ArrayLike, n: number): Array;
600
- /** Return sign and natural logarithm of the determinant of `a`. */
601
- declare function slogdet(a: ArrayLike): [Array, Array];
614
+ type OwnedFunction<F extends Function> = F & {
615
+ dispose: () => void;
616
+ };
617
+ /** Variable in a Jaxpr expression. */
618
+ declare class Var {
619
+ #private;
620
+ readonly id: number;
621
+ readonly aval: ShapedArray;
622
+ constructor(aval: ShapedArray);
623
+ toString(): string;
624
+ }
625
+ /** Literal in a Jaxpr expression. Currently, only scalars are supported. */
626
+ declare class Lit {
627
+ readonly value: number;
628
+ readonly aval: ShapedArray;
629
+ get dtype(): DType;
630
+ constructor(aval: AbstractValue, value: number);
631
+ }
632
+ type Atom = Var | Lit;
633
+ declare class VarPrinter {
634
+ #private;
635
+ names: Map<Var, string>;
636
+ name(v: Var): string;
637
+ nameType(v: Var): string;
638
+ }
639
+ /** A single statement / binding in a Jaxpr, in ANF form. */
640
+ declare class JaxprEqn {
641
+ readonly primitive: Primitive;
642
+ readonly inputs: Atom[];
643
+ readonly params: Record<string, any>;
644
+ readonly outBinders: Var[];
645
+ constructor(primitive: Primitive, inputs: Atom[], params: Record<string, any>, outBinders: Var[]);
646
+ pprint(usedVars?: Set<Var>, vp?: VarPrinter): PPrint;
647
+ toString(): string;
648
+ }
649
+ /** Typed intermediate representation for traced computations. */
650
+ declare class Jaxpr implements FpHashable {
651
+ #private;
652
+ readonly inBinders: Var[];
653
+ readonly eqns: JaxprEqn[];
654
+ readonly outs: Atom[];
655
+ constructor(inBinders: Var[], eqns: JaxprEqn[], outs: Atom[]);
656
+ pprint(): PPrint;
657
+ toString(): string;
658
+ /**
659
+ * Gets a hash of this Jaxpr.
660
+ *
661
+ * Var identity is not considered in the hash, so two Jaxprs with the same
662
+ * order of assignments and operators but different variable IDs will resolve
663
+ * to the same hash (and toString representation).
664
+ */
665
+ getHash(): bigint;
666
+ hash(state: FpHash): void;
667
+ /**
668
+ * Produce a simplified Jaxpr with basic optimizations applied.
669
+ * - Trim away unused variables.
670
+ * - Fold away *1, *0, or +0 operations against literals.
671
+ * - Remove no-op movement operations.
672
+ */
673
+ simplify(): Jaxpr;
674
+ /** Flattens nested Jit in a Jaxpr. Useful for handling jit-of-jit. */
675
+ flatten(): Jaxpr;
676
+ }
677
+ /** Jaxpr with a collection of associated, traced constants. */
678
+ declare class ClosedJaxpr {
679
+ readonly jaxpr: Jaxpr;
680
+ readonly consts: Tracer[];
681
+ constructor(jaxpr: Jaxpr, consts: Tracer[]);
682
+ /** String representation of this Jaxpr. */
683
+ toString(): string;
684
+ /** Apply a function to the underlying Jaxpr. */
685
+ mapJaxpr(f: (jaxpr: Jaxpr) => Jaxpr): ClosedJaxpr;
686
+ /** Dispose of the constants in this Jaxpr. */
687
+ dispose(): void;
688
+ }
689
+ /** @inline */
690
+ type JitOpts = {
691
+ staticArgnums?: number[];
692
+ };
693
+ //#endregion
694
+ //#region src/frontend/core.d.ts
602
695
  /**
603
- * Solve a linear system of equations.
696
+ * Frontend primitive operations, which are lowered into Kernel objects before
697
+ * being dispatched to the backend.
604
698
  *
605
- * This solves a (batched) linear system of equations `a @ x = b` for `x` given
606
- * `a` and `b`. If `a` is singular, this will return `nan` or `inf` values.
699
+ * Any operation between arrays can be described in these parts. This is also
700
+ * the set of primitives that can occur in Jaxpr programs, and the level at
701
+ * which transformations like vmap, grad, and jvp occur. They are loosely based
702
+ * on [XLA](https://openxla.org/xla/operation_semantics).
607
703
  *
608
- * @param a - Coefficient matrix of shape `(..., N, N)`.
609
- * @param b - Values of shape `(N,)` or `(..., N, M)`.
610
- * @returns Solution `x` of shape `(..., N)` or `(..., N, M)`.
704
+ * All n-ary operations support broadcasting, with NumPy semantics.
611
705
  */
612
- declare function solve(a: ArrayLike, b: ArrayLike): Array;
613
- //#endregion
614
- //#region src/library/numpy/dtype-info.d.ts
615
- /** @inline */
616
- type FInfo = Readonly<{
617
- /** The number of bits occupied by the type. */
618
- bits: number;
619
- /** Returns the _dtype_ for which finfo returns information. */
620
- dtype: DType;
621
- /** The difference between 1.0 and the next smallest representable float larger than 1.0. */
622
- eps: number;
623
- /** The difference between 1.0 and the next largest representable float smaller than 1.0. */
624
- epsneg: number;
625
- /** The exponent that yields `eps`. */
626
- machep: number;
627
- /** The largest representable finite number. */
628
- max: number;
629
- /** The smallest positive power of the base (2) that causes overflow. */
630
- maxexp: number;
631
- /** The smallest representable (most negative) finite number. */
632
- min: number;
633
- /** The largest negative power of the base (2) without leading zeros in mantissa. */
634
- minexp: number;
635
- /** The exponent that yields `epsneg`. */
636
- negep: number;
637
- /** Number of bits in the exponent portion. */
638
- nexp: number;
639
- /** Number of bits in the mantissa portion. */
640
- nmant: number;
641
- /** The approximate number of decimal digits to which this kind of float is precise. */
642
- precision: number;
643
- /** The approximate decimal resolution, i.e., `10 ** -precision`. */
644
- resolution: number;
645
- /** The smallest positive normal number. */
646
- smallestNormal: number;
647
- /** The smallest positive subnormal number. */
648
- smallestSubnormal: number;
649
- }>;
650
- /** Machine limits for floating-point types. */
651
- declare function finfo(dtype: DType): FInfo;
652
- /** @inline */
653
- type IInfo = Readonly<{
654
- /** The number of bits occupied by the type. */
655
- bits: number;
656
- /** Returns the _dtype_ for which iinfo returns information. */
657
- dtype: DType;
658
- /** The largest representable integer. */
659
- max: number;
660
- /** The smallest representable integer. */
661
- min: number;
662
- }>;
663
- /** Machine limits for integer types. */
664
- declare function iinfo(dtype: DType): IInfo;
665
- declare namespace numpy_d_exports {
666
- export { Array, ArrayLike, DType, absolute as abs, absolute, acos, arccosh as acosh, add, all, allclose, any, arange, acos as arccos, arccosh, asin as arcsin, arcsinh, atan as arctan, atan2 as arctan2, arctanh, argmax, argmin, argsort, array, asin, arcsinh as asinh, astype, atan, atan2, arctanh as atanh, bool, broadcastArrays, broadcastShapes, broadcastTo, cbrt, ceil, clip, columnStack, concatenate, convolve, corrcoef, correlate, cos, cosh, cov, cumsum, cumsum as cumulativeSum, deg2rad, degrees, diag, diagonal, trueDivide as divide, divmod, dot$1 as dot, dstack, e, einsum, equal, eulerGamma, exp, exp2, expandDims, expm1, eye, numpy_fft_d_exports as fft, finfo, flip, fliplr, flipud, float16, float32, float64, floor, floorDivide, fmod, frexp, full, fullLike, greater, greaterEqual, hamming, hann, heaviside, hstack, hypot, identity$1 as identity, iinfo, inf, inner, int32, isfinite, isinf, isnan, isneginf, isposinf, ldexp, less, lessEqual, numpy_linalg_d_exports as linalg, linspace, log, log10, log1p, log2, logspace, matmul, matrixTranspose, max, maximum, mean, meshgrid, min, minimum, moveaxis, multiply, nan, ndim, negative, notEqual, ones, onesLike, outer, pad, transpose as permuteDims, pi, positive, power as pow, power, prod, promoteTypes, ptp, rad2deg, radians, ravel, reciprocal, remainder, repeat, reshape, shape$1 as shape, sign, sin, sinc, sinh, size, sort, split$1 as split, sqrt, square, squeeze, stack, std, subtract, sum, swapaxes, take, tan, tanh, tensordot, tile, trace, transpose, tri, tril, triu, trueDivide, trunc, uint32, var_, vdot, vecdot, vstack, where, zeros, zerosLike };
706
+ declare enum Primitive {
707
+ Add = "add",
708
+ Mul = "mul",
709
+ Idiv = "idiv",
710
+ Mod = "mod",
711
+ // uses sign of numerator, C-style, matches JS but not Python
712
+ Min = "min",
713
+ Max = "max",
714
+ Neg = "neg",
715
+ Reciprocal = "reciprocal",
716
+ Floor = "floor",
717
+ Ceil = "ceil",
718
+ StopGradient = "stop_gradient",
719
+ Cast = "cast",
720
+ Bitcast = "bitcast",
721
+ Sin = "sin",
722
+ Cos = "cos",
723
+ Asin = "asin",
724
+ Atan = "atan",
725
+ Exp = "exp",
726
+ Log = "log",
727
+ Erf = "erf",
728
+ Erfc = "erfc",
729
+ Sqrt = "sqrt",
730
+ Reduce = "reduce",
731
+ Dot = "dot",
732
+ // sum(x*y, axis=-1)
733
+ Conv = "conv",
734
+ // see lax.conv_general_dilated
735
+ Pool = "pool",
736
+ PoolTranspose = "pool_transpose",
737
+ Compare = "compare",
738
+ Where = "where",
739
+ Concatenate = "concatenate",
740
+ Split = "split",
741
+ RandomBits = "random_bits",
742
+ Gather = "gather",
743
+ Transpose = "transpose",
744
+ Broadcast = "broadcast",
745
+ Reshape = "reshape",
746
+ Flip = "flip",
747
+ Shrink = "shrink",
748
+ Pad = "pad",
749
+ Sort = "sort",
750
+ // sort(x, axis=-1)
751
+ Argsort = "argsort",
752
+ // argsort(x, axis=-1)
753
+ TriangularSolve = "triangular_solve",
754
+ // A is upper triangular, A @ X.T = B.T
755
+ Cholesky = "cholesky",
756
+ // A is positive-definite, A = L @ L^T
757
+ LU = "lu",
758
+ // LU decomposition with partial pivoting
759
+ Jit = "jit",
667
760
  }
668
- declare const float32 = DType.Float32;
669
- declare const int32 = DType.Int32;
670
- declare const uint32 = DType.Uint32;
671
- declare const bool = DType.Bool;
672
- declare const float16 = DType.Float16;
673
- declare const float64 = DType.Float64;
674
- /** Euler's constant, `e = 2.7182818284590...` */
675
- declare const e: number;
676
- /** Euler-Mascheroni constant, `γ = 0.5772156649...` */
677
- declare const eulerGamma = 0.5772156649015329;
678
- /** Positive infinity. */
679
- declare const inf: number;
680
- /** Floating-point representation of NaN. */
681
- declare const nan: number;
682
- /** This is Pi, `π = 3.14159265358979...` */
683
- declare const pi: number;
684
- /** @function Element-wise addition, with broadcasting. */
685
- declare const add: (x: ArrayLike, y: ArrayLike) => Array;
686
- /** @function Element-wise multiplication, with broadcasting. */
687
- declare const multiply: (x: ArrayLike, y: ArrayLike) => Array;
688
- /** @function Numerical negative of every element of an array. */
689
- declare const negative: (x: ArrayLike) => Array;
690
- /** @function Calculate element-wise reciprocal of the input. This is `1/x`. */
691
- declare const reciprocal: (x: ArrayLike) => Array;
692
- /** @function Round input down to the nearest integer. */
693
- declare const floor: (x: ArrayLike) => Array;
694
- /** @function Round input up to the nearest integer. */
695
- declare const ceil: (x: ArrayLike) => Array;
696
- /** @function Element-wise sine function (takes radians). */
697
- declare const sin: (x: ArrayLike) => Array;
698
- /** @function Element-wise cosine function (takes radians). */
699
- declare const cos: (x: ArrayLike) => Array;
700
- /** @function Element-wise inverse sine function (inverse of sin). */
701
- declare const asin: (x: ArrayLike) => Array;
702
- /** @function Element-wise inverse tangent function (inverse of tan). */
703
- declare const atan: (x: ArrayLike) => Array;
704
- /** @function Calculate the exponential of all elements in the input array. */
705
- declare const exp: (x: ArrayLike) => Array;
706
- /** @function Calculate the natural logarithm of all elements in the input array. */
707
- declare const log: (x: ArrayLike) => Array;
708
- /** @function Calculate the square root of all elements in the input array. */
709
- declare const sqrt: (x: ArrayLike) => Array;
710
- /** @function Return element-wise minimum of the input arrays. */
711
- declare const minimum: (x: ArrayLike, y: ArrayLike) => Array;
712
- /** @function Return element-wise maximum of the input arrays. */
713
- declare const maximum: (x: ArrayLike, y: ArrayLike) => Array;
714
- /** @function Compare two arrays element-wise. */
715
- declare const greater: (x: ArrayLike, y: ArrayLike) => Array;
716
- /** @function Compare two arrays element-wise. */
717
- declare const less: (x: ArrayLike, y: ArrayLike) => Array;
718
- /** @function Compare two arrays element-wise. */
719
- declare const equal: (x: ArrayLike, y: ArrayLike) => Array;
720
- /** @function Compare two arrays element-wise. */
721
- declare const notEqual: (x: ArrayLike, y: ArrayLike) => Array;
722
- /** @function Compare two arrays element-wise. */
723
- declare const greaterEqual: (x: ArrayLike, y: ArrayLike) => Array;
724
- /** @function Compare two arrays element-wise. */
725
- declare const lessEqual: (x: ArrayLike, y: ArrayLike) => Array;
726
- /** @function Element-wise ternary operator, evaluates to `x` if cond else `y`. */
727
- declare const where: (cond: ArrayLike, x: ArrayLike, y: ArrayLike) => Array;
761
+ interface PrimitiveParamsImpl extends Record<Primitive, Record<string, any>> {
762
+ [Primitive.Cast]: {
763
+ dtype: DType;
764
+ };
765
+ [Primitive.Bitcast]: {
766
+ dtype: DType;
767
+ };
768
+ [Primitive.Reduce]: {
769
+ op: AluOp;
770
+ axis: number[];
771
+ };
772
+ [Primitive.Conv]: ConvParams;
773
+ [Primitive.Pool]: {
774
+ window: number[];
775
+ strides: number[];
776
+ };
777
+ [Primitive.PoolTranspose]: {
778
+ inShape: number[];
779
+ window: number[];
780
+ strides: number[];
781
+ };
782
+ [Primitive.Compare]: {
783
+ op: CompareOp;
784
+ };
785
+ [Primitive.Concatenate]: {
786
+ axis: number;
787
+ };
788
+ [Primitive.Split]: {
789
+ axis: number;
790
+ sizes: number[];
791
+ };
792
+ [Primitive.RandomBits]: {
793
+ shape: number[];
794
+ mode: "xor" | 0 | 1;
795
+ };
796
+ [Primitive.Gather]: {
797
+ axis: number[];
798
+ outDim: number;
799
+ };
800
+ [Primitive.Transpose]: {
801
+ perm: number[];
802
+ };
803
+ [Primitive.Broadcast]: {
804
+ shape: number[];
805
+ axis: number[];
806
+ };
807
+ [Primitive.Reshape]: {
808
+ shape: number[];
809
+ };
810
+ [Primitive.Flip]: {
811
+ axis: number[];
812
+ };
813
+ [Primitive.Shrink]: {
814
+ slice: Pair[];
815
+ };
816
+ [Primitive.Pad]: {
817
+ width: Pair[];
818
+ };
819
+ [Primitive.TriangularSolve]: {
820
+ unitDiagonal: boolean;
821
+ };
822
+ [Primitive.Jit]: {
823
+ name: string;
824
+ jaxpr: Jaxpr;
825
+ numConsts: number;
826
+ };
827
+ }
828
+ /** Type of parameters taken by each primitive. */
829
+ type PrimitiveParams<T extends Primitive> = T extends keyof PrimitiveParamsImpl ? PrimitiveParamsImpl[T] : Record<string, never>;
830
+ declare enum CompareOp {
831
+ Less = "less",
832
+ Equal = "equal",
833
+ NotEqual = "not_equal",
834
+ LessEqual = "less_equal",
835
+ }
836
+ /** @inline */
837
+ type Axis = number | number[] | null;
838
+ /** @inline */
839
+ type ReduceOpts = {
840
+ keepdims?: boolean;
841
+ };
842
+ type MainTrace = {
843
+ level: number;
844
+ traceType: new (main: MainTrace) => Trace;
845
+ globalData: any | null;
846
+ };
728
847
  /**
729
- * @function
730
- * Permute the dimensions of an array. Defaults to reversing the axis order.
848
+ * Push an interpreter onto the trace stack. Use this like:
849
+ * `using main = newMain(...);`
731
850
  */
732
- declare const transpose: (x: ArrayLike, perm?: number[]) => Array;
851
+
852
+ type TracerValue = Tracer | number | boolean;
853
+ declare abstract class Trace {
854
+ readonly main: MainTrace;
855
+ constructor(main: MainTrace);
856
+ abstract pure(val: TracerValue): Tracer;
857
+ abstract lift(val: Tracer): Tracer;
858
+ abstract processPrimitive<P extends Primitive>(primitive: P, tracers: Tracer[], params: PrimitiveParams<P>): Tracer[];
859
+ }
860
+ /** Internal representation of an array value. */
861
+ interface AbstractValue {
862
+ /** Shape of the array. Must be a static tuple of non-negative dimensions. */
863
+ shape: number[];
864
+ /** Concrete data type of array elements. */
865
+ dtype: DType;
866
+ /**
867
+ * Arrays created from JavaScript numbers (e.g., `np.array(3)`) are created as
868
+ * _weakly typed_ unless a dtype is explicitly specified.
869
+ *
870
+ * Weakly typed values will automatically cast to the data type of other
871
+ * arrays when used as an operand as an expression. This property only affects
872
+ * how they promote in type casting; their memory layout is still determined
873
+ * by the actual `dtype` field.
874
+ *
875
+ * ```ts
876
+ * const x = np.array(3); // weakType = true, dtype = float32
877
+ * const y = np.array([1, 2], { dtype: np.int32 }); // weakType = false, dtype = int32
878
+ * const z = x.add(y); // z has dtype int32 because x is weakly typed
879
+ * ```
880
+ *
881
+ * Weak types are present in JIT programs in their spec (e.g., Jaxpr inputs
882
+ * and outputs can be weakly typed) form. But they're solely a frontend
883
+ * concept. Backends are not aware of weak types.
884
+ */
885
+ weakType: boolean;
886
+ }
733
887
  /**
734
- * @function
735
- * Give a new shape to an array without changing its data.
888
+ * Broadcast shapes and promote types with casting for two avals.
736
889
  *
737
- * One shape dimension can be -1. In this case, the value is inferred from the
738
- * length of the array and remaining dimensions.
890
+ * This implements the weak type behavior described in `promoteTypes()`, but not
891
+ * implemented in that function as `weakType` is not passed.
739
892
  */
740
- declare const reshape: (x: ArrayLike, shape: number[]) => Array;
741
- /**
742
- * @function
743
- * Move axes of an array to new positions. Other axes retain original order.
744
- */
745
- declare const moveaxis: (x: ArrayLike, src: number, dst: number) => Array;
746
- /**
747
- * @function
748
- * Add padding (zeros) to an array.
749
- *
750
- * The `width` argument is either an integer or pair of integers, in which case
751
- * all axes are padded with the same width. Or if it is an array of pairs, each
752
- * pair specifies the padding for its corresponding axis.
753
- */
754
- declare const pad: (x: ArrayLike, width: number | Pair | Pair[]) => Array;
755
- /**
756
- * @function
757
- * Return the number of dimensions of an array. Does not consume array reference.
758
- */
759
- declare const ndim: (x: ArrayLike) => number;
760
- /** @function Return the shape of an array. Does not consume array reference. */
761
- declare const shape$1: (x: ArrayLike) => number[];
762
- /**
763
- * @function
764
- * Return an array of zeros with the same shape and type as a given array.
765
- */
766
- declare const zerosLike: (a: ArrayLike, dtype?: DType) => Array;
767
- /**
768
- * @function
769
- * Return an array of ones with the same shape and type as a given array.
770
- */
771
- declare const onesLike: (a: ArrayLike, dtype?: DType) => Array;
772
- /**
773
- * @function
774
- * Return a full array with the same shape and type as a given array.
775
- */
776
- declare const fullLike: (a: ArrayLike, fillValue: number | boolean | Array, dtype?: DType) => Array;
777
- /**
778
- * Return the number of elements in an array, optionally along an axis.
779
- * Does not consume array reference.
780
- */
781
- declare function size(a: ArrayLike, axis?: number): number;
782
- /** Convert an array to a specified dtype. */
783
- declare function astype(a: ArrayLike, dtype: DType): Array;
784
- /** Sum of the elements of the array over a given axis, or axes. */
785
- declare function sum(a: ArrayLike, axis?: Axis, opts?: ReduceOpts): Array;
786
- /** Product of the array elements over a given axis. */
787
- declare function prod(a: ArrayLike, axis?: Axis, opts?: ReduceOpts): Array;
788
- /** Return the minimum of array elements along a given axis. */
789
- declare function min(a: ArrayLike, axis?: Axis, opts?: ReduceOpts): Array;
790
- /** Return the maximum of array elements along a given axis. */
791
- declare function max(a: ArrayLike, axis?: Axis, opts?: ReduceOpts): Array;
792
- /**
793
- * Test whether all array elements along a given axis evaluate to True.
794
- *
795
- * Returns a boolean array with the same shape as `a` with the specified axis
796
- * removed. If axis is None, returns a scalar.
797
- */
798
- declare function all(a: ArrayLike, axis?: Axis, opts?: ReduceOpts): Array;
799
- /**
800
- * Test whether any array element along a given axis evaluates to True.
801
- *
802
- * Returns a boolean array with the same shape as `a` with the specified axis
803
- * removed. If axis is None, returns a scalar.
804
- */
805
- declare function any(a: ArrayLike, axis?: Axis, opts?: ReduceOpts): Array;
806
- /** Return the peak-to-peak range along a given axis (`max - min`). */
807
- declare function ptp(a: ArrayLike, axis?: Axis, opts?: ReduceOpts): Array;
808
- /** Compute the average of the array elements along the specified axis. */
809
- declare function mean(a: ArrayLike, axis?: Axis, opts?: ReduceOpts): Array;
810
- /**
811
- * Returns the indices of the minimum values along an axis.
812
- *
813
- * By default, index is into the flatted array, otherwise it is along the
814
- * specified axis.
815
- */
816
- declare function argmin(a: ArrayLike, axis?: number, opts?: ReduceOpts): Array;
817
- /**
818
- * Returns the indices of the maximum values along an axis.
819
- *
820
- * By default, index is into the flatted array, otherwise it is along the
821
- * specified axis.
822
- */
823
- declare function argmax(a: ArrayLike, axis?: number, opts?: ReduceOpts): Array;
824
- /**
825
- * Cumulative sum of elements along an axis.
826
- *
827
- * Currently this function is `O(n^2)`, we'll improve this later on with a
828
- * two-phase parallel reduction algorithm.
829
- */
830
- declare function cumsum(a: ArrayLike, axis?: number): Array;
831
- /** Reverse the elements in an array along the given axes. */
832
- declare function flip(x: ArrayLike, axis?: Axis): Array;
833
- /**
834
- * Split an array into multiple sub-arrays along an axis.
835
- *
836
- * @param a - The input array to split.
837
- * @param indicesOrSections - If an integer, it indicates the number of equal
838
- * sections to create along the specified axis. If a list of integers, it
839
- * specifies the indices at which to split the array.
840
- * @param axis - The axis along which to split the array. Default is 0.
841
- */
842
- declare function split$1(a: ArrayLike, indicesOrSections: number | number[], axis?: number): Array[];
843
- /**
844
- * Join a sequence of arrays along an existing axis.
845
- *
846
- * The arrays must have the same shape, except in the dimension corresponding to
847
- * `axis` (the first, by default).
848
- *
849
- * No scalars can be passed to this function, as the axis is then ambiguous.
850
- */
851
- declare function concatenate(xs: Array[], axis?: number): Array;
852
- /**
853
- * Join a sequence of arrays along a new axis.
854
- *
855
- * The `axis` parameter specifies the index of the new axis in the dimensions of
856
- * the result. For example, if `axis=0` it will be the first dimension and if
857
- * `axis=-1` it will be the last dimension.
858
- *
859
- * All shapes must have the same shape.
860
- */
861
- declare function stack(xs: ArrayLike[], axis?: number): Array;
862
- /**
863
- * Horizontally stack arrays. Inputs are promoted to rank at least 1, then
864
- * concatenated along axis 1 (if rank-2 or higher) or 0 (if rank-1).
865
- */
866
- declare function hstack(xs: ArrayLike[]): Array;
867
- /**
868
- * Vertically stack arrays. Inputs are promoted to rank at least 2, then
869
- * concatenated along axis 0.
870
- */
871
- declare function vstack(xs: ArrayLike[]): Array;
872
- /**
873
- * Stack arrays depth-wise. Inputs are promoted to rank at least 3, then
874
- * concatenated along axis 2.
875
- */
876
- declare function dstack(xs: ArrayLike[]): Array;
877
- /**
878
- * Stack arrays column-wise. Inputs are promoted to rank at least 2, then
879
- * concatenated along axis 1.
880
- */
881
- declare function columnStack(xs: ArrayLike[]): Array;
882
- /** Flip an array vertically (axis=0). */
883
- declare function flipud(x: ArrayLike): Array;
884
- /** Flip an array horizontally (axis=1). */
885
- declare function fliplr(x: ArrayLike): Array;
886
- /** Interchange two axes of an array. */
887
- declare function swapaxes(a: ArrayLike, axis1: number, axis2: number): Array;
888
- /** Transpose the last two dimensions of an array. */
889
- declare function matrixTranspose(a: ArrayLike): Array;
890
- /** Return a 1-D flattened array containing the elements of the input. */
891
- declare function ravel(a: ArrayLike): Array;
892
- /** Remove one or more length-1 axes from an array. */
893
- declare function squeeze(a: ArrayLike, axis?: Axis): Array;
893
+
894
+ declare abstract class Tracer {
895
+ /** @ignore */
896
+ readonly _trace: Trace;
897
+ constructor(trace: Trace);
898
+ abstract get aval(): AbstractValue;
899
+ abstract toString(): string;
900
+ /**
901
+ * Access an array by reference, incrementing the reference count.
902
+ *
903
+ * jax-js handles freeing arrays by using "move" semantics, like in Rust/C++.
904
+ * Whenever you pass an array into a function, that function should consume
905
+ * the array, and it will no longer be usable. For example, if you had:
906
+ *
907
+ * ```
908
+ * const x = np.array([1, 2, 3]);
909
+ * const y = np.add(x, x);
910
+ * ```
911
+ *
912
+ * The second line does not work because the first parameter consumes `x`, and
913
+ * then the second parameter will already have been freed / disposed.
914
+ *
915
+ * To fix this, you can write:
916
+ *
917
+ * ```
918
+ * const y = np.add(x.ref, x);
919
+ * ```
920
+ *
921
+ * Under the hood, every access to `.ref` increments the internal reference
922
+ * count of the array. The reference count starts at 1. When it hits 0, the
923
+ * memory behind the array is freed.
924
+ */
925
+ abstract get ref(): this;
926
+ /**
927
+ * Manually decrement the reference count of the array.
928
+ *
929
+ * Arrays are created with reference count 1. Whenever it is used as argument
930
+ * to a function or other operation, it is disposed (i.e., reference count
931
+ * decreases by 1) automatically. Whenever a `.ref` is created, the reference
932
+ * count increases.
933
+ *
934
+ * You generally don't need to call this function directly since arrays are
935
+ * automatically disposed after being passed into an operation. One common
936
+ * exception is when writing a function and ignoring one of its arguments. In
937
+ * that case, by convention you should dispose of that argument manually.
938
+ *
939
+ * ```
940
+ * function myCustomOperation(a: np.Array, b: np.Array) {
941
+ * b.dispose(); // Needed to satisfy "move" rules.
942
+ * return a.add(1);
943
+ * }
944
+ * ```
945
+ */
946
+ abstract dispose(): void;
947
+ /** The shape of the array. */
948
+ get shape(): number[];
949
+ /** The total number of elements in the array. */
950
+ get size(): number;
951
+ /** The dtype of elements stored in the array. */
952
+ get dtype(): DType;
953
+ /**
954
+ * Whether the array is weakly typed.
955
+ *
956
+ * Weakly typed arrays will cast to the dtype of the other operand. See
957
+ * `promoteTypes()` for details.
958
+ */
959
+ get weakType(): boolean;
960
+ /** The number of dimensions of the array. */
961
+ get ndim(): number;
962
+ /** @ignore */
963
+ fullLower(): Tracer;
964
+ neg(): this;
965
+ add(other: this | TracerValue): this;
966
+ mul(other: this | TracerValue): this;
967
+ mod(other: this | TracerValue): this;
968
+ greater(other: this | TracerValue): this;
969
+ less(other: this | TracerValue): this;
970
+ equal(other: this | TracerValue): this;
971
+ notEqual(other: this | TracerValue): this;
972
+ greaterEqual(other: this | TracerValue): this;
973
+ lessEqual(other: this | TracerValue): this;
974
+ /** Sum of the elements of the array over a given axis, or axes. */
975
+ sum(axis?: Axis, opts?: ReduceOpts): this;
976
+ /** Product of the array elements over a given axis. */
977
+ prod(axis?: Axis, opts?: ReduceOpts): this;
978
+ /** Compute the average of the array elements along the specified axis. */
979
+ mean(axis?: Axis, opts?: ReduceOpts): this;
980
+ /** Minimum of the elements of the array along a given axis. */
981
+ min(axis?: Axis, opts?: ReduceOpts): this;
982
+ /** Maximum of the elements of the array along a given axis. */
983
+ max(axis?: Axis, opts?: ReduceOpts): this;
984
+ /** Test whether all array elements along a given axis evaluate to true. */
985
+ all(axis?: Axis, opts?: ReduceOpts): this;
986
+ /** Test whether any array element along a given axis evaluates to true. */
987
+ any(axis?: Axis, opts?: ReduceOpts): this;
988
+ /** Permute the dimensions of an array. Defaults to reversing the axis order. */
989
+ transpose(perm?: number[]): this;
990
+ /**
991
+ * Give a new shape to an array without changing its data.
992
+ *
993
+ * One shape dimension can be -1. In this case, the value is inferred from the
994
+ * length of the array and remaining dimensions.
995
+ */
996
+ reshape(shape: number | number[]): this;
997
+ /** Copy the array and cast to a specified dtype. */
998
+ astype(dtype: DType): this;
999
+ /** Subtract an array from this one. */
1000
+ sub(other: this | TracerValue): this;
1001
+ /** Divide an array by this one. */
1002
+ div(other: this | TracerValue): this;
1003
+ /** Return specified diagonals. See `jax.numpy.diagonal` for full docs. */
1004
+ diagonal(offset?: number, axis1?: number, axis2?: number): this;
1005
+ /** Flatten the array without changing its data. */
1006
+ flatten(): this;
1007
+ /** Flatten the array without changing its data. */
1008
+ ravel(): this;
1009
+ /**
1010
+ * Iterate over the first dimension of this array, returning slices.
1011
+ *
1012
+ * This can be used to destructure arrays. For example:
1013
+ *
1014
+ * ```js
1015
+ * let x = np.array([[1, 2], [3, 4]]);
1016
+ * let [a, b] = x;
1017
+ * console.log(a.js()); // [1, 2]
1018
+ * console.log(b.js()); // [3, 4]
1019
+ * ```
1020
+ */
1021
+ [Symbol.iterator](): IterableIterator<this>;
1022
+ /**
1023
+ * Return a sorted copy of an array in ascending order.
1024
+ *
1025
+ * See `jax.numpy.sort` for full docs.
1026
+ */
1027
+ sort(axis?: number): this;
1028
+ /**
1029
+ * Return the indices that would sort an array. This may not be a stable
1030
+ * sorting algorithm; it need not preserve order of indices in ties.
1031
+ *
1032
+ * See `jax.numpy.argsort` for full docs.
1033
+ */
1034
+ argsort(axis?: number): this;
1035
+ /**
1036
+ * Slice an array along one or more axes.
1037
+ *
1038
+ * This is the equivalent of slicing in Python, e.g. `x[1:3, 2, :, None]`. To
1039
+ * mimic this in JavaScript, we would write:
1040
+ *
1041
+ * ```js
1042
+ * x.slice([1, 3], 2, [], null);
1043
+ * ```
1044
+ *
1045
+ * The `slice` method accepts a variable number of arguments, each of which
1046
+ * can be a number, an empty array, a single-element array, a two-element
1047
+ * array, or `null`. The arguments are interpreted as follows:
1048
+ *
1049
+ * - A number `n` means to access the `n`-th element along that axis, removing
1050
+ * that axis from the resulting shape.
1051
+ * - An empty array `[]` means to keep that axis as-is, like `:` in Python.
1052
+ * - A single-element array `[i]` means to start slicing from index `i`
1053
+ * (inclusive) to the end of the axis, like `x[i:]`.
1054
+ * - A two-element array `[i, j]` means to slice from index `i` (inclusive)
1055
+ * to index `j` (exclusive), like `x[i:j]`.
1056
+ * - `null` means to add a new axis at that position, like `np.newaxis`.
1057
+ *
1058
+ * Like in Python, negative indices are supported, which count from the end of
1059
+ * the axis. For example, `-1` means the last element.
1060
+ *
1061
+ * Strided slices are not yet implemented, so you cannot write `x[::2]` or
1062
+ * similar.
1063
+ *
1064
+ * Advanced indexing by integer arrays is also supported. This translates to
1065
+ * the "gather" primitive, and it allows you to access specific elements of
1066
+ * the array by integer indices stored in another array.
1067
+ */
1068
+ slice(...index: (number | [] | [number] | Pair | null | Tracer)[]): this;
1069
+ }
1070
+ declare class ShapedArray implements AbstractValue {
1071
+ readonly shape: number[];
1072
+ readonly dtype: DType;
1073
+ readonly weakType: boolean;
1074
+ constructor(shape: number[], dtype: DType, weakType: boolean);
1075
+ static fromAval(aval: AbstractValue): ShapedArray;
1076
+ get ndim(): number;
1077
+ get size(): number;
1078
+ scalar(): ShapedArray;
1079
+ toString(): string;
1080
+ equals(other: ShapedArray): boolean;
1081
+ }
1082
+ //#endregion
1083
+ //#region src/frontend/array.d.ts
1084
+ type ArrayLike = Array | number | boolean;
1085
+ /** Version of pureArray with fudged types. */
1086
+
894
1087
  /**
895
- * Expand the shape of an array by inserting new axes of length 1.
896
- *
897
- * @param a - Input array.
898
- * @param axis - Position(s) in the expanded axes where the new axis (or axes)
899
- * is placed. Can be a single integer or an array of integers.
900
- * @returns Array with the number of dimensions increased.
1088
+ * An executable operation that will be dispatched to the backend.
901
1089
  *
902
- * @example
903
- * ```ts
904
- * const x = np.array([1, 2]);
905
- * np.expandDims(x, 0); // Shape [1, 2]
906
- * np.expandDims(x, 1); // Shape [2, 1]
907
- * np.expandDims(x, [0, 2]); // Shape [1, 2, 1]
908
- * ```
1090
+ * This holds a reference to all input buffers used in the operation. After the
1091
+ * operation is dispatched, the references should be released.
909
1092
  */
910
- declare function expandDims(a: ArrayLike, axis: number | number[]): Array;
1093
+ declare class PendingExecute {
1094
+ #private;
1095
+ readonly backend: Backend;
1096
+ readonly source: Kernel | Routine;
1097
+ readonly inputs: Slot[];
1098
+ readonly outputs: Slot[];
1099
+ prepared: Executable | null;
1100
+ submitted: boolean;
1101
+ constructor(backend: Backend, source: Kernel | Routine, inputs: Slot[], outputs: Slot[]);
1102
+ updateRc(delta: number): void;
1103
+ prepare(): Promise<void>;
1104
+ prepareSync(): void;
1105
+ submit(): void;
1106
+ }
1107
+ /** @inline */
1108
+ type DTypeAndDevice = {
1109
+ dtype?: DType;
1110
+ device?: Device;
1111
+ };
1112
+ type ArrayConstructorArgs = {
1113
+ source: AluExp | Slot;
1114
+ st: ShapeTracker;
1115
+ dtype: DType;
1116
+ weakType: boolean;
1117
+ backend: Backend;
1118
+ committed: boolean;
1119
+ pending?: Iterable<PendingExecute>;
1120
+ };
911
1121
  /**
912
- * Repeat each element of an array after themselves.
1122
+ * A multidimensional numeric array with data stored on CPU or GPU.
913
1123
  *
914
- * If no axis is provided, use the flattened input array, and return a flat
915
- * output array.
916
- */
917
- declare function repeat(a: ArrayLike, repeats: number, axis?: number): Array;
918
- /**
919
- * Construct an array by repeating A the number of times given by reps.
1124
+ * This is the library's core data type. Equivalent to `jax.Array` from JAX, or
1125
+ * `torch.Tensor`.
920
1126
  *
921
- * If `A` is an array of shape `(d1, d2, ..., dn)` and `reps` is a sequence of
922
- * integers, the resulting array will have a shape of `(reps[0] * d1,
923
- * reps[1] * d2, ..., reps[n] * dn)`, with `A` tiled along each dimension.
1127
+ * Not to be confused with the JavaScript "Array" constructor. Avoid importing
1128
+ * this into your code's namespace if you're already using the JavaScript
1129
+ * "Array" type by name.
924
1130
  */
925
- declare function tile(a: ArrayLike, reps: number | number[]): Array;
1131
+ declare class Array extends Tracer {
1132
+ #private;
1133
+ /**
1134
+ * @ignore
1135
+ * Constructs an array from source, shape and backend. Note that if the source
1136
+ * is a backend `Slot`, this constructor _takes ownership_ of the slot. It
1137
+ * will be freed when the array is disposed.
1138
+ */
1139
+ constructor(args: ArrayConstructorArgs);
1140
+ /** @ignore */
1141
+ get aval(): ShapedArray;
1142
+ /** Return a simple string representation of the array's dimensions. */
1143
+ toString(): string;
1144
+ get device(): Device;
1145
+ get ref(): this;
1146
+ /** Get the current reference count (for debugging memory management). */
1147
+ get refCount(): number;
1148
+ dispose(): void;
1149
+ /**
1150
+ * Convert this array into a primitive value.
1151
+ *
1152
+ * This only works for scalars (0-dimensional arrays). It lets you get values
1153
+ * "out" of the JAX system. For instance, if `x = np.array(5)`, then you can
1154
+ * evaluate `x + 1` and `x ** 2` to get `6` and `25`, respectively.
1155
+ *
1156
+ * This method is also called for `==` equality.
1157
+ */
1158
+ [Symbol.toPrimitive](): any;
1159
+ /** Realize the array and return it as data. */
1160
+ data(): Promise<DataArray>;
1161
+ /**
1162
+ * Wait for this array to finish evaluation.
1163
+ *
1164
+ * Operations and data loading in jax-js are lazy, so this function ensures
1165
+ * that pending operations are dispatched and fully executed before it
1166
+ * returns.
1167
+ *
1168
+ * If you are mapping from `data()` or `dataSync()`, it will also trigger
1169
+ * dispatch of operations as well.
1170
+ *
1171
+ * **Note:** `jax.blockUntilReady()` is a higher-level API, it calls this
1172
+ * asynchronously for multiple arrays.
1173
+ */
1174
+ blockUntilReady(): Promise<Array>;
1175
+ /**
1176
+ * Realize the array and return it as data. This is a sync variant and not
1177
+ * recommended for performance reasons, as it will block rendering.
1178
+ */
1179
+ dataSync(): DataArray;
1180
+ /**
1181
+ * Convert this array into a JavaScript object.
1182
+ *
1183
+ * This is a blocking operation that will compile all of the shaders and wait
1184
+ * for execution to complete, synchronously. No other JavaScript code on the
1185
+ * site will be run during shader execution.
1186
+ *
1187
+ * To avoid blocking, prefer `jsAsync()` when possible.
1188
+ */
1189
+ js(): any;
1190
+ /** Convert this array into a JavaScript object, asynchronously. */
1191
+ jsAsync(): Promise<any>;
1192
+ /**
1193
+ * Copy an element of an array to a numeric scalar and return it.
1194
+ *
1195
+ * Throws an error if the array does not have a single element. The array must
1196
+ * either be rank-0, or all dimensions of the shape are 1.
1197
+ */
1198
+ item(): number;
1199
+ /** @private Internal plumbing method for Array / Tracer ops. */
1200
+ static _implRules(): typeof implRules;
1201
+ /** @private */
1202
+ _realizeSource(): number;
1203
+ /** @private Put this array on a new backend, asynchronously. */
1204
+ _put(backend: Backend): Promise<Array>;
1205
+ /** @private Put this array on a new backend, synchronously. */
1206
+ _putSync(backend: Backend): Array;
1207
+ }
1208
+ /** Constructor for creating a new array from data. */
1209
+ declare function array(values: Array | DataArray | RecursiveArray<number> | RecursiveArray<boolean>, {
1210
+ shape,
1211
+ dtype,
1212
+ device
1213
+ }?: {
1214
+ shape?: number[];
1215
+ } & DTypeAndDevice): Array;
1216
+ /** If x is a value, lift it into an array, otherwise leave it be. */
1217
+
1218
+ type ImplRule<P extends Primitive> = (tracers: Array[], params: PrimitiveParams<P>) => Array[];
1219
+ declare const implRules: { [P in Primitive]: ImplRule<P> };
1220
+ /** Return a new array of given shape and type, filled with zeros. */
1221
+ declare function zeros(shape: number[], {
1222
+ dtype,
1223
+ device
1224
+ }?: DTypeAndDevice): Array;
1225
+ /** Return a new array of given shape and type, filled with ones. */
1226
+ declare function ones(shape: number[], {
1227
+ dtype,
1228
+ device
1229
+ }?: DTypeAndDevice): Array;
1230
+ /** Return a new array of given shape and type, filled with `fill_value`. */
1231
+ declare function full(shape: number[], fillValue: number | boolean | Array, {
1232
+ dtype,
1233
+ device
1234
+ }?: DTypeAndDevice): Array;
926
1235
  /**
927
- * Broadcast an array to a shape, with NumPy-style broadcasing rules.
1236
+ * Create an identity matrix.
928
1237
  *
929
- * In other words, this lets you append axes to the left, and/or expand
930
- * dimensions where the shape is 1.
1238
+ * If numCols is not provided, it defaults to numRows, i.e., a square identity
1239
+ * matrix with ones on the diagonal.
931
1240
  */
932
- declare function broadcastTo(a: ArrayLike, shape: number[]): Array;
933
- /** Broadcast input shapes to a common output shape. */
934
- declare function broadcastShapes(...shapes: number[][]): number[];
935
- /** Broadcast arrays to a common shape. */
936
- declare function broadcastArrays(...arrays: ArrayLike[]): Array[];
1241
+ declare function eye(numRows: number, numCols?: number, {
1242
+ dtype,
1243
+ device
1244
+ }?: DTypeAndDevice): Array;
1245
+ /** Return the identity matrix, with ones on the main diagonal. */
1246
+ declare function identity$1(n: number, {
1247
+ dtype,
1248
+ device
1249
+ }?: DTypeAndDevice): Array;
937
1250
  /**
938
- * Return specified diagonals.
1251
+ * Return evenly spaced values within a given interval.
939
1252
  *
940
- * If a is 2D, return the diagonal of the array with the given offset. If a is
941
- * 3D or higher, compute diagonals along the two given axes (default: 0, 1).
1253
+ * This can be called with a varying number of arguments, just like the range()
1254
+ * builtin function in Python.
942
1255
  *
943
- * This returns a view over the existing array. The shape of the resulting array
944
- * is determined by removing the two axes along which the diagonal is taken,
945
- * then appending a new axis to the right with holding the diagonals.
946
- */
947
- declare function diagonal(a: ArrayLike, offset?: number, axis1?: number, axis2?: number): Array;
948
- /**
949
- * Extract a diagonal or construct a diagonal array.
1256
+ * - `arange(stop)` is equivalent to `arange(0, stop, 1)`.
1257
+ * - `arange(start, stop)` is equivalent to `arange(start, stop, 1)`.
1258
+ * - `arange(start, stop, step)` creates an array starting at `start`, ending
1259
+ * before `stop`, with a step size of `step`.
950
1260
  *
951
- * If v is a 2D array, return the k-th diagonal of v (as a view). If v is a 1D
952
- * array, return a 2D array with v on the k-th diagonal.
1261
+ * Defaults to an integer data type. This can produce unintended results when
1262
+ * using a non-integer step, so prefer linspace() in those cases.
953
1263
  */
954
- declare function diag(v: ArrayLike, k?: number): Array;
955
- /** Calculate the sum of the diagonal of an array along the given axes. */
956
- declare function trace(a: ArrayLike, offset?: number, axis1?: number, axis2?: number): Array;
1264
+ declare function arange(start: number, stop?: number, step?: number, {
1265
+ dtype,
1266
+ device
1267
+ }?: DTypeAndDevice): Array;
957
1268
  /**
958
- * Return a sorted copy of an array.
1269
+ * Return an array with ones on and below the diagonal and zeros elsewhere.
959
1270
  *
960
- * The array is sorted along a specified axis (the last by default). This may be
961
- * an unstable sort, and it dispatches to device-specific implementation.
1271
+ * If `k` is provided, it specifies the sub-diagonal on and below which the
1272
+ * array is filled with ones. `k=0` is the main diagonal, `k<0` is below it, and
1273
+ * `k>0` is above it.
962
1274
  */
963
- declare function sort(a: ArrayLike, axis?: number): Array;
1275
+ declare function tri(n: number, m?: number, k?: number, {
1276
+ dtype,
1277
+ device
1278
+ }?: DTypeAndDevice): Array;
1279
+ /** Return the lower triangle of an array. Must be of dimension >= 2. */
1280
+ declare function tril(a: ArrayLike, k?: number): Array;
1281
+ /** Return the upper triangle of an array. Must be of dimension >= 2. */
1282
+ declare function triu(a: ArrayLike, k?: number): Array;
964
1283
  /**
965
- * Return indices that would sort an array. This may be an unstable sorting
966
- * algorithm; it need not preserve order of indices in ties.
1284
+ * Return evenly spaced numbers over a specified interval.
967
1285
  *
968
- * Returns an array of `int32` indices.
1286
+ * Returns _num_ evenly spaced samples, calculated over the interval
1287
+ * [`start`, `stop`]. The endpoint `stop` is included in the result by default,
1288
+ * but this is controlled by the `endpoint` parameter.
969
1289
  *
970
- * The array is sorted along a specified axis (the last by default).
1290
+ * The default data type is Float32. Use arange() for integer steps.
971
1291
  */
972
- declare function argsort(a: ArrayLike, axis?: number): Array;
1292
+ declare function linspace(start: number, stop: number, num?: number, endpoint?: boolean, {
1293
+ dtype,
1294
+ device
1295
+ }?: DTypeAndDevice): Array;
973
1296
  /**
974
- * Take elements from an array along an axis.
1297
+ * Return numbers spaced evenly on a log scale.
975
1298
  *
976
- * This is equivalent to advanced indexing with integer indices over that
977
- * numbered axis. By default, the flattened array is used.
978
- */
979
- declare function take(a: ArrayLike, indices: ArrayLike, axis?: number | null): Array;
980
- /** Return if two arrays are element-wise equal within a tolerance. */
981
- declare function allclose(actual: Parameters<typeof array>[0], expected: Parameters<typeof array>[0], options?: {
982
- rtol?: number;
983
- atol?: number;
984
- }): boolean;
985
- /** Matrix product of two arrays. */
986
- declare function matmul(x: ArrayLike, y: ArrayLike): Array;
987
- /** Dot product of two arrays. */
988
- declare function dot$1(x: ArrayLike, y: ArrayLike): Array;
989
- /**
990
- * Compute the tensor dot product of two N-dimensional arrays.
1299
+ * In linear space, the sequence starts at `base ** start` and ends at
1300
+ * `base ** stop` (see `endpoint` below).
991
1301
  *
992
- * The behavior is determined by `axes`. If an integer `k`, sum over the last
993
- * `k` axes of x and the first `k` axes of y. If a tuple, then the first array
994
- * corresponds to the axes of x and the second to the axes of y.
1302
+ * @param start - `base ** start` is the starting value of the sequence.
1303
+ * @param stop - `base ** stop` is the final value of the sequence, unless `endpoint` is false.
1304
+ * @param num - Number of samples to generate. Default is 50.
1305
+ * @param endpoint - If true, `stop` is the last sample. Otherwise, it is not included. Default is true.
1306
+ * @param base - The base of the log space. Default is 10.
1307
+ * @returns Array of evenly spaced values on a log scale.
995
1308
  */
996
- declare function tensordot(x: ArrayLike, y: ArrayLike, axes?: number | [number[], number[]]): Array;
1309
+ declare function logspace(start: number, stop: number, num?: number, endpoint?: boolean, base?: number, {
1310
+ dtype,
1311
+ device
1312
+ }?: DTypeAndDevice): Array;
1313
+ //#endregion
1314
+ //#region src/frontend/linearize.d.ts
1315
+ /** @inline */
1316
+ type GradOpts = {
1317
+ /**
1318
+ * Integer or sequence of integers. Specifies which positional argument(s) to
1319
+ * differentiate with respect to.
1320
+ *
1321
+ * Defaults to `0` (the first argument).
1322
+ */
1323
+ argnums?: number | number[];
1324
+ /**
1325
+ * The input function returns a pair of `[out, aux]` including an auxiliary
1326
+ * value. This `aux` is not differentiated, but is returned alongside the
1327
+ * gradient when evaluating the function.
1328
+ */
1329
+ hasAux?: boolean;
1330
+ };
1331
+ declare namespace lax_linalg_d_exports {
1332
+ export { cholesky$1 as cholesky, lu, triangularSolve };
1333
+ }
997
1334
  /**
998
- * Einstein summation with string subscripts.
1335
+ * Compute the Cholesky decomposition of a symmetric positive-definite matrix.
1336
+ *
1337
+ * The Cholesky decomposition of a matrix `A` is:
1338
+ *
1339
+ * - A = L @ L^T (for upper=false, default)
1340
+ * - A = U^T @ U (for upper=true)
1341
+ *
1342
+ * where `L` is a lower-triangular matrix and `U` is an upper-triangular matrix.
1343
+ * The input matrix must be symmetric and positive-definite.
999
1344
  *
1000
1345
  * @example
1001
1346
  * ```ts
1002
- * import { numpy as np } from "@jax-js/jax";
1347
+ * import { lax, numpy as np } from "@jax-js/jax";
1003
1348
  *
1004
- * const a = np.ones([2, 3]);
1005
- * const b = np.ones([3]);
1006
- * np.einsum("ij,j", a, b); // Shape [2]
1349
+ * const x = np.array([[2., 1.], [1., 2.]]);
1350
+ *
1351
+ * // Lower Cholesky factorization (default):
1352
+ * const L = lax.linalg.cholesky(x);
1353
+ * // L ≈ [[1.4142135, 0], [0.70710677, 1.2247449]]
1354
+ *
1355
+ * // Upper Cholesky factorization:
1356
+ * const U = lax.linalg.cholesky(x, { upper: true });
1357
+ * // U ≈ [[1.4142135, 0.70710677], [0, 1.2247449]]
1007
1358
  * ```
1008
1359
  */
1009
- declare function einsum(subscripts: string, ...operands: ArrayLike[]): Array;
1360
+ declare function cholesky$1(a: ArrayLike, {
1361
+ upper
1362
+ }?: {
1363
+ upper?: boolean;
1364
+ }): Array;
1010
1365
  /**
1011
- * Einstein summation alternating between arrays and numeric indices.
1366
+ * LU decomposition with partial pivoting.
1367
+ *
1368
+ * Computes the matrix decomposition: `P @ A = L @ U`, where `P` is a
1369
+ * permutation of the rows of `A`, `L` is lower-triangular with unit diagonal,
1370
+ * and `U` is upper-triangular.
1371
+ *
1372
+ * @param x - A batch of matrices with shape `[..., m, n]`.
1373
+ *
1374
+ * @returns A tuple `(lu, pivots, permutation)` where:
1375
+ * - `lu`: combined lower and upper triangular matrices.
1376
+ * - `pivots`: an array of pivot indices with shape `[..., min(m, n)]`.
1377
+ * - `permutation`: the permutation generated by pivots with shape `[..., m]`.
1012
1378
  *
1013
1379
  * @example
1014
1380
  * ```ts
1015
- * import { numpy as np } from "@jax-js/jax";
1381
+ * import { lax, numpy as np } from "@jax-js/jax";
1016
1382
  *
1017
- * const a = np.ones([2, 3]);
1018
- * const b = np.ones([3]);
1019
- * np.einsum(a, [0, 1], b, [1]); // Shape [2]
1383
+ * const A = np.array([[4., 3.], [6., 3.]]);
1384
+ * const [lu, pivots, permutation] = lax.linalg.lu(A);
1385
+ * // lu ≈ [[6., 3.], [0.6666667, 1.0]]
1386
+ * // pivots = [1, 1]
1387
+ * // permutation = [1, 0]
1020
1388
  * ```
1021
1389
  */
1022
- declare function einsum(...args: (ArrayLike | number[])[]): Array;
1390
+ declare function lu(x: ArrayLike): [Array, Array, Array];
1023
1391
  /**
1024
- * Compute the inner product of two arrays.
1392
+ * Solve a triangular linear system.
1025
1393
  *
1026
- * Unlike `jax.numpy.matmul()` or `jax.numpy.dot()`, this always performs a
1027
- * contraction on the last axis.
1394
+ * Solves `a @ x = b` (if leftSide=true) or `x @ a = b` (if leftSide=false)
1395
+ * where `a` is a triangular matrix.
1028
1396
  *
1029
- * Returned array has shape `[...x.shape[:-1], ...y.shape[:-1]]`.
1030
- */
1031
- declare function inner(x: ArrayLike, y: ArrayLike): Array;
1032
- /**
1033
- * Compute the outer product of two arrays.
1397
+ * @example
1398
+ * ```ts
1399
+ * import { lax, numpy as np } from "@jax-js/jax";
1034
1400
  *
1035
- * If the input arrays are not 1D, they will be flattened. Returned array will
1036
- * be of shape `[x.size, y.size]`.
1401
+ * const L = np.array([[2., 0.], [1., 3.]]);
1402
+ * const b = np.array([4., 7.]).reshape([2, 1]);
1403
+ *
1404
+ * // Solve L @ x = b
1405
+ * const x = lax.linalg.triangularSolve(L, b, { leftSide: true, lower: true });
1406
+ * // x = [[2.], [5./3.]]
1407
+ * ```
1037
1408
  */
1038
- declare function outer(x: ArrayLike, y: ArrayLike): Array;
1039
- /** Vector dot product of two arrays along a given axis. */
1040
- declare function vecdot(x: ArrayLike, y: ArrayLike, {
1041
- axis
1409
+ declare function triangularSolve(a: ArrayLike, b: ArrayLike, {
1410
+ leftSide,
1411
+ lower,
1412
+ transposeA,
1413
+ unitDiagonal
1042
1414
  }?: {
1043
- axis?: number;
1415
+ leftSide?: boolean;
1416
+ lower?: boolean;
1417
+ transposeA?: boolean;
1418
+ unitDiagonal?: boolean;
1044
1419
  }): Array;
1420
+ declare namespace lax_d_exports {
1421
+ export { DotDimensionNumbers, PaddingType, conv, convGeneralDilated, convTranspose, convWithGeneralPadding, dot$1 as dot, erf, erfc, lax_linalg_d_exports as linalg, reduceWindow, stopGradient };
1422
+ }
1045
1423
  /**
1046
- * Return the dot product of two vectors.
1424
+ * Dimension numbers for general `dot()` primitive.
1047
1425
  *
1048
- * Like vecdot() but flattens the arguments first into vectors.
1426
+ * Contracting dimensions act as a tensor contraction (reduction) along the
1427
+ * given axis. They must be the same size in both operands. Batch dimensions
1428
+ * are treated as vectorized, leading batch dimensions.
1429
+ *
1430
+ * The return value has a shape where the first dimensions are shared batch
1431
+ * dimensions, followed by `lhs` non-contracting dimensions, followed by
1432
+ * `rhs` non-contracting dimensions.
1049
1433
  */
1050
- declare function vdot(x: ArrayLike, y: ArrayLike): Array;
1051
- /** Convolution of two one-dimensional arrays. */
1052
- declare function convolve(x: Array, y: Array, mode?: "full" | "same" | "valid"): Array;
1053
- /** Correlation of two one dimensional arrays. */
1054
- declare function correlate(x: Array, y: Array, mode?: "full" | "same" | "valid"): Array;
1434
+ type DotDimensionNumbers = {
1435
+ lhsContractingDims?: number[];
1436
+ rhsContractingDims?: number[];
1437
+ lhsBatchDims?: number[];
1438
+ rhsBatchDims?: number[];
1439
+ };
1440
+ /**
1441
+ * General dot product/contraction operator.
1442
+ *
1443
+ * Prefer higher-level functions like `jax.numpy.dot()`, `jax.numpy.matmul()`,
1444
+ * `jax.numpy.tensordot(), and `jax.numpy.einsum()` where possible.
1445
+ */
1446
+ declare function dot$1(lhs: Array, rhs: Array, {
1447
+ lhsContractingDims: lc,
1448
+ rhsContractingDims: rc,
1449
+ lhsBatchDims: lb,
1450
+ rhsBatchDims: rb
1451
+ }?: DotDimensionNumbers): Array;
1452
+ type PaddingType = "VALID" | "SAME" | "SAME_LOWER" | Pair[];
1055
1453
  /**
1056
- * Return a tuple of coordinate matrices from coordinate vectors.
1454
+ * General n-dimensional convolution operator, with optional dilation.
1057
1455
  *
1058
- * Make N-D coordinate arrays for vectorized evaluations of N-D scalar/vector
1059
- * fields over N-D grids, given one-dimensional coordinate arrays x1, x2,…, xn.
1456
+ * The semantics of this operation mimic the `jax.lax.conv_general_dilated`
1457
+ * function in JAX, which wraps XLA's general convolution operator.
1458
+ *
1459
+ * @param lhs - Input tensor; shape `[N, C_in, ...xs]`
1460
+ * @param rhs - Convolution kernel; shape `[C_out, C_in / G, ...ks]`
1461
+ * @param windowStrides - Strides for each spatial dimension
1462
+ * @param padding - Padding for each spatial dimension, or a string
1463
+ * (`"VALID"`, `"SAME"`, or `"SAME_LOWER"`)
1060
1464
  */
1061
- declare function meshgrid(xs: Array[], {
1062
- indexing
1465
+ declare function convGeneralDilated(lhs: Array, rhs: Array, windowStrides: number[], padding: PaddingType, {
1466
+ lhsDilation,
1467
+ rhsDilation,
1468
+ featureGroupCount
1063
1469
  }?: {
1064
- indexing?: "xy" | "ij";
1065
- }): Array[];
1470
+ lhsDilation?: number[];
1471
+ rhsDilation?: number[];
1472
+ featureGroupCount?: number;
1473
+ }): Array;
1474
+ /** Convenience wrapper around `convGeneralDilated`. */
1475
+ declare function convWithGeneralPadding(lhs: Array, rhs: Array, windowStrides: number[], padding: PaddingType, lhsDilation?: number[], rhsDilation?: number[]): Array;
1476
+ /** Convenience wrapper around `convGeneralDilated`. */
1477
+ declare function conv(lhs: Array, rhs: Array, windowStrides: number[], padding: PaddingType): Array;
1066
1478
  /**
1067
- * Clip (limit) the values in an array.
1479
+ * Convenience wrapper for calculating the N-d convolution "transpose".
1068
1480
  *
1069
- * Given an interval, values outside the interval are clipped to the interval
1070
- * edges. For example, if an interval of [0, 1] is specified, values smaller
1071
- * than 0 become 0, and values larger than 1 become 1.
1481
+ * This function directly calculates a fractionally strided conv rather than
1482
+ * indirectly calculating the gradient (transpose) of a forward convolution.
1483
+ * It is equivalent to the JAX version, except:
1072
1484
  *
1073
- * If either bound is undefined, it is ignored.
1074
- */
1075
- declare function clip(a: ArrayLike, min?: ArrayLike, max?: ArrayLike): Array;
1076
- /**
1077
- * Calculate the absolute value element-wise.
1485
+ * - The `use_consistent_padding` option is not available. We only have the
1486
+ * consistent padding case (JAX version >0.8.4).
1487
+ * - The order of dimensions matches `lax.conv_general_dilated`.
1078
1488
  *
1079
- * This is the same function as `jax.numpy.abs()`.
1489
+ * Unlike PyTorch/TensorFlow, by default we don't reverse the kernel's spatial
1490
+ * dimensions or the `(C_out, C_in)` axis order. To get this behavior, set
1491
+ * `transposeKernel` to true.
1492
+ *
1493
+ * @param lhs - Input tensor; shape `[N, C_in, ...xs]`
1494
+ * @param rhs - Convolution kernel; shape `[C_out, C_in, ...ks]`
1495
+ * @param strides - Sequence of n integers, sets fractional stride
1496
+ * @param padding - Apply padding of `dilation * (kernel_size - 1) - padding` to
1497
+ * each side of the input, so it acts like gradient of `conv()`
1498
+ * @param rhsDilation - Atrous dilation for the kernel
1499
+ * @param transposeKernel - Flip spatial axes and swap the input/output channels
1500
+ * of the kernel; its shape should be `[C_in, C_out, ...ks]`
1080
1501
  */
1081
- declare function absolute(x: ArrayLike): Array;
1082
- /** Return an element-wise indication of sign of the input. */
1083
- declare function sign(x: ArrayLike): Array;
1084
- /** @function Return element-wise positive values of the input (no-op). */
1085
- declare const positive: (x: ArrayLike) => Array;
1502
+ declare function convTranspose(lhs: Array, rhs: Array, strides: number[], padding: PaddingType, {
1503
+ rhsDilation,
1504
+ transposeKernel
1505
+ }?: {
1506
+ rhsDilation?: number[];
1507
+ transposeKernel?: boolean;
1508
+ }): Array;
1509
+ /** Reduce a computation over padded windows. */
1510
+ declare function reduceWindow(operand: Array, computation: (x: Array) => Array, windowDimensions: number[], windowStrides?: number[]): Array;
1511
+ /** The error function: `erf(x) = 2/sqrt(pi) * int[0..x] exp(-t^2) dt`. */
1512
+ declare function erf(x: ArrayLike): Array;
1086
1513
  /**
1087
- * Return the Hamming window of size M, a taper with a weighted cosine bell.
1514
+ * The complementary error function: `erfc(x) = 1 - erf(x)`.
1088
1515
  *
1089
- * `w(n) = 0.54 - 0.46 * cos(2πn/(M-1))` for `0 <= n <= M-1`.
1516
+ * This function is more accurate than `1 - erf(x)` for large values of `x`,
1517
+ * where `erf(x)` is very close to 1.
1090
1518
  */
1091
- declare function hamming(M: number): Array;
1519
+ declare function erfc(x: ArrayLike): Array;
1092
1520
  /**
1093
- * Return the Hann window of size M, a taper with a weighted cosine bell.
1521
+ * Stops gradient computation.
1094
1522
  *
1095
- * `w(n) = 0.5 - 0.5 * cos(2πn/(M-1))` for `0 <= n <= M-1`.
1523
+ * Behaves as the identity function but prevents the flow of gradients during
1524
+ * forward or reverse-mode automatic differentiation.
1096
1525
  */
1097
- declare function hann(M: number): Array;
1526
+ declare function stopGradient(x: ArrayLike): Array;
1527
+ declare namespace numpy_fft_d_exports {
1528
+ export { ComplexPair, fft, ifft };
1529
+ }
1098
1530
  /**
1099
- * @function
1100
- * Compute the Heaviside step function. It is defined piecewise:
1101
- * - `heaviside(x1, x2) = 0` for `x1 < 0`,
1102
- * - `heaviside(x1, x2) = x2` for `x1 == 0`,
1103
- * - `heaviside(x1, x2) = 1` for `x1 > 0`.
1531
+ * A pair of arrays representing real and imaginary part `a + bj`. Both arrays
1532
+ * must have the same shape.
1104
1533
  */
1105
- declare const heaviside: OwnedFunction<(x1: ArrayLike, x2: ArrayLike) => Array>;
1106
- /** Calculate element-wise square of the input array. */
1107
- declare function square(x: ArrayLike): Array;
1108
- /** Element-wise tangent function (takes radians). */
1109
- declare function tan(x: ArrayLike): Array;
1534
+ type ComplexPair = {
1535
+ real: Array;
1536
+ imag: Array;
1537
+ };
1110
1538
  /**
1111
- * @function
1112
- * Return the normalized sinc function.
1539
+ * Compute a one-dimensional discrete Fourier transform.
1113
1540
  *
1114
- * The sinc function is defined as `sin(πx) / (πx)` for `x != 0`, and `1` for `x = 0`.
1115
- * This is the normalized sinc function commonly used in signal processing.
1541
+ * Currently, the size of the axis must be a power of two.
1542
+ */
1543
+ declare function fft(a: ComplexPair, axis?: number): ComplexPair;
1544
+ /**
1545
+ * Compute a one-dimensional inverse discrete Fourier transform.
1116
1546
  *
1117
- * **Note:** JVP is not supported at x=0 due to discontinuous derivative. This
1118
- * requires a custom JVP rule to handle properly (see JAX implementation).
1547
+ * Currently, the size of the axis must be a power of two.
1119
1548
  */
1120
- declare const sinc: OwnedFunction<(x: ArrayLike) => Array>;
1121
- /** Element-wise inverse cosine function (inverse of cos). */
1122
- declare function acos(x: ArrayLike): Array;
1549
+ declare function ifft(a: ComplexPair, axis?: number): ComplexPair;
1550
+ declare namespace numpy_linalg_d_exports {
1551
+ export { cholesky, det, diagonal, inv, lstsq, matmul, matrixPower, matrixTranspose, outer, slogdet, solve, tensordot, trace, vecdot };
1552
+ }
1123
1553
  /**
1124
- * @function
1125
- * Return element-wise hypotenuse for the given legs of a right triangle.
1554
+ * Compute the Cholesky decomposition of a (batched) positive-definite matrix.
1126
1555
  *
1127
- * In the original NumPy/JAX implementation, this function is more numerically
1128
- * stable than `sqrt(x1**2 + x2**2)`. We don't currently implement those
1129
- * stability improvements.
1556
+ * This is like `jax.lax.linalg.cholesky()`, except with an option to symmetrize
1557
+ * the input matrix, which is on by default.
1130
1558
  */
1131
- declare const hypot: OwnedFunction<(x1: ArrayLike, x2: ArrayLike) => Array>;
1559
+ declare function cholesky(a: ArrayLike, {
1560
+ upper,
1561
+ symmetrizeInput
1562
+ }?: {
1563
+ upper?: boolean;
1564
+ symmetrizeInput?: boolean;
1565
+ }): Array;
1566
+ /** Compute the determinant of a square matrix (batched). */
1567
+ declare function det(a: ArrayLike): Array;
1568
+ /** Compute the inverse of a square matrix (batched). */
1569
+ declare function inv(a: ArrayLike): Array;
1132
1570
  /**
1133
- * @function
1134
- * Element-wise arc tangent of y/x with correct quadrant.
1571
+ * Return the least-squares solution to a linear equation.
1135
1572
  *
1136
- * Returns the angle in radians between the positive x-axis and the point (x, y).
1137
- * The result is in the range [-π, π].
1573
+ * For overdetermined systems, this finds the `x` that minimizes `norm(ax - b)`.
1574
+ * For underdetermined systems, this finds the minimum-norm solution for `x`.
1138
1575
  *
1139
- * Uses numerically stable formulas:
1140
- * - When x >= 0: atan2(y, x) = 2 * atan(y / (sqrt(x^2 + y^2) + x))
1141
- * - When x < 0: atan2(y, x) = 2 * atan((sqrt(x^2 + y^2) - x) / y)
1576
+ * This currently uses Cholesky decomposition to solve the normal equations,
1577
+ * under the hood. The method is not as robust as QR or SVD.
1142
1578
  *
1143
- * The output is ill-defined when both x and y are zero.
1579
+ * @param a coefficient matrix of shape `(M, N)`
1580
+ * @param b right-hand side of shape `(M,)` or `(M, K)`
1581
+ * @return least-squares solution of shape `(N,)` or `(N, K)`
1144
1582
  */
1145
- declare const atan2: OwnedFunction<(y: ArrayLike, x: ArrayLike) => Array>;
1146
- /** Element-wise subtraction, with broadcasting. */
1147
- declare function subtract(x: ArrayLike, y: ArrayLike): Array;
1148
- /** Calculates the floating-point division of x by y element-wise. */
1149
- declare function trueDivide(x: ArrayLike, y: ArrayLike): Array;
1583
+ declare function lstsq(a: ArrayLike, b: ArrayLike): Array;
1584
+ /** Raise a square matrix to an integer power, via repeated squarings. */
1585
+ declare function matrixPower(a: ArrayLike, n: number): Array;
1586
+ /** Return sign and natural logarithm of the determinant of `a`. */
1587
+ declare function slogdet(a: ArrayLike): [Array, Array];
1150
1588
  /**
1151
- * Return the largest integer smaller or equal to the division of the inputs.
1152
- *
1153
- * The result is always rounded towards negative infinity.
1589
+ * Solve a linear system of equations.
1154
1590
  *
1155
- * For floating-point inputs, this is equivalent to `floor(x / y)`.
1156
- * For integer inputs, we use `(x - remainder(x, y)) / y` to handle
1157
- * negative values correctly (note: may overflow near int32 boundaries).
1591
+ * This solves a (batched) linear system of equations `a @ x = b` for `x` given
1592
+ * `a` and `b`. If `a` is singular, this will return `nan` or `inf` values.
1158
1593
  *
1159
- * @param x - Dividend array.
1160
- * @param y - Divisor array.
1161
- * @returns Element-wise floor division of x by y.
1594
+ * @param a - Coefficient matrix of shape `(..., N, N)`.
1595
+ * @param b - Values of shape `(N,)` or `(..., N, M)`.
1596
+ * @returns Solution `x` of shape `(..., N)` or `(..., N, M)`.
1162
1597
  */
1163
- declare function floorDivide(x: ArrayLike, y: ArrayLike): Array;
1598
+ declare function solve(a: ArrayLike, b: ArrayLike): Array;
1599
+ //#endregion
1600
+ //#region src/library/numpy/dtype-info.d.ts
1601
+ /** @inline */
1602
+ type FInfo = Readonly<{
1603
+ /** The number of bits occupied by the type. */
1604
+ bits: number;
1605
+ /** Returns the _dtype_ for which finfo returns information. */
1606
+ dtype: DType;
1607
+ /** The difference between 1.0 and the next smallest representable float larger than 1.0. */
1608
+ eps: number;
1609
+ /** The difference between 1.0 and the next largest representable float smaller than 1.0. */
1610
+ epsneg: number;
1611
+ /** The exponent that yields `eps`. */
1612
+ machep: number;
1613
+ /** The largest representable finite number. */
1614
+ max: number;
1615
+ /** The smallest positive power of the base (2) that causes overflow. */
1616
+ maxexp: number;
1617
+ /** The smallest representable (most negative) finite number. */
1618
+ min: number;
1619
+ /** The largest negative power of the base (2) without leading zeros in mantissa. */
1620
+ minexp: number;
1621
+ /** The exponent that yields `epsneg`. */
1622
+ negep: number;
1623
+ /** Number of bits in the exponent portion. */
1624
+ nexp: number;
1625
+ /** Number of bits in the mantissa portion. */
1626
+ nmant: number;
1627
+ /** The approximate number of decimal digits to which this kind of float is precise. */
1628
+ precision: number;
1629
+ /** The approximate decimal resolution, i.e., `10 ** -precision`. */
1630
+ resolution: number;
1631
+ /** The smallest positive normal number. */
1632
+ smallestNormal: number;
1633
+ /** The smallest positive subnormal number. */
1634
+ smallestSubnormal: number;
1635
+ }>;
1636
+ /** Machine limits for floating-point types. */
1637
+ declare function finfo(dtype: DType): FInfo;
1638
+ /** @inline */
1639
+ type IInfo = Readonly<{
1640
+ /** The number of bits occupied by the type. */
1641
+ bits: number;
1642
+ /** Returns the _dtype_ for which iinfo returns information. */
1643
+ dtype: DType;
1644
+ /** The largest representable integer. */
1645
+ max: number;
1646
+ /** The smallest representable integer. */
1647
+ min: number;
1648
+ }>;
1649
+ /** Machine limits for integer types. */
1650
+ declare function iinfo(dtype: DType): IInfo;
1651
+ declare namespace numpy_d_exports {
1652
+ export { Array, ArrayLike, DType, absolute as abs, absolute, acos, arccosh as acosh, add, all, allclose, any, arange, acos as arccos, arccosh, asin as arcsin, arcsinh, atan as arctan, atan2 as arctan2, arctanh, argmax, argmin, argsort, array, asin, arcsinh as asinh, astype, atan, atan2, arctanh as atanh, bool, broadcastArrays, broadcastShapes, broadcastTo, cbrt, ceil, clip, columnStack, concatenate, convolve, corrcoef, correlate, cos, cosh, cov, cumsum, cumsum as cumulativeSum, deg2rad, degrees, diag, diagonal, trueDivide as divide, divmod, dot, dstack, e, einsum, equal, eulerGamma, exp, exp2, expandDims, expm1, eye, numpy_fft_d_exports as fft, finfo, flip, fliplr, flipud, float16, float32, float64, floor, floorDivide, fmod, frexp, full, fullLike, greater, greaterEqual, hamming, hann, heaviside, hstack, hypot, identity$1 as identity, iinfo, inf, inner, int32, isfinite, isinf, isnan, isneginf, isposinf, ldexp, less, lessEqual, numpy_linalg_d_exports as linalg, linspace, log, log10, log1p, log2, logspace, matmul, matrixTranspose, max, maximum, mean, meshgrid, min, minimum, moveaxis, multiply, nan, nanToNum, ndim, negative, notEqual, ones, onesLike, outer, pad, transpose as permuteDims, pi, positive, power as pow, power, prod, promoteTypes, ptp, rad2deg, radians, ravel, reciprocal, remainder, repeat, reshape, shape$1 as shape, sign, sin, sinc, sinh, size, sort, split$1 as split, sqrt, square, squeeze, stack, std, subtract, sum, swapaxes, take, tan, tanh, tensordot, tile, trace, transpose, tri, tril, triu, trueDivide, trunc, uint32, var_, vdot, vecdot, vstack, where, zeros, zerosLike };
1653
+ }
1654
+ declare const float32 = DType.Float32;
1655
+ declare const int32 = DType.Int32;
1656
+ declare const uint32 = DType.Uint32;
1657
+ declare const bool = DType.Bool;
1658
+ declare const float16 = DType.Float16;
1659
+ declare const float64 = DType.Float64;
1660
+ /** Euler's constant, `e = 2.7182818284590...` */
1661
+ declare const e: number;
1662
+ /** Euler-Mascheroni constant, `γ = 0.5772156649...` */
1663
+ declare const eulerGamma = 0.5772156649015329;
1664
+ /** Positive infinity. */
1665
+ declare const inf: number;
1666
+ /** Floating-point representation of NaN. */
1667
+ declare const nan: number;
1668
+ /** This is Pi, `π = 3.14159265358979...` */
1669
+ declare const pi: number;
1670
+ /** @function Element-wise addition, with broadcasting. */
1671
+ declare const add: (x: ArrayLike, y: ArrayLike) => Array;
1672
+ /** @function Element-wise multiplication, with broadcasting. */
1673
+ declare const multiply: (x: ArrayLike, y: ArrayLike) => Array;
1674
+ /** @function Numerical negative of every element of an array. */
1675
+ declare const negative: (x: ArrayLike) => Array;
1676
+ /** @function Calculate element-wise reciprocal of the input. This is `1/x`. */
1677
+ declare const reciprocal: (x: ArrayLike) => Array;
1678
+ /** @function Round input down to the nearest integer. */
1679
+ declare const floor: (x: ArrayLike) => Array;
1680
+ /** @function Round input up to the nearest integer. */
1681
+ declare const ceil: (x: ArrayLike) => Array;
1682
+ /** @function Element-wise sine function (takes radians). */
1683
+ declare const sin: (x: ArrayLike) => Array;
1684
+ /** @function Element-wise cosine function (takes radians). */
1685
+ declare const cos: (x: ArrayLike) => Array;
1686
+ /** @function Element-wise inverse sine function (inverse of sin). */
1687
+ declare const asin: (x: ArrayLike) => Array;
1688
+ /** @function Element-wise inverse tangent function (inverse of tan). */
1689
+ declare const atan: (x: ArrayLike) => Array;
1690
+ /** @function Calculate the exponential of all elements in the input array. */
1691
+ declare const exp: (x: ArrayLike) => Array;
1692
+ /** @function Calculate the natural logarithm of all elements in the input array. */
1693
+ declare const log: (x: ArrayLike) => Array;
1694
+ /** @function Calculate the square root of all elements in the input array. */
1695
+ declare const sqrt: (x: ArrayLike) => Array;
1696
+ /** @function Return element-wise minimum of the input arrays. */
1697
+ declare const minimum: (x: ArrayLike, y: ArrayLike) => Array;
1698
+ /** @function Return element-wise maximum of the input arrays. */
1699
+ declare const maximum: (x: ArrayLike, y: ArrayLike) => Array;
1700
+ /** @function Compare two arrays element-wise. */
1701
+ declare const greater: (x: ArrayLike, y: ArrayLike) => Array;
1702
+ /** @function Compare two arrays element-wise. */
1703
+ declare const less: (x: ArrayLike, y: ArrayLike) => Array;
1704
+ /** @function Compare two arrays element-wise. */
1705
+ declare const equal: (x: ArrayLike, y: ArrayLike) => Array;
1706
+ /** @function Compare two arrays element-wise. */
1707
+ declare const notEqual: (x: ArrayLike, y: ArrayLike) => Array;
1708
+ /** @function Compare two arrays element-wise. */
1709
+ declare const greaterEqual: (x: ArrayLike, y: ArrayLike) => Array;
1710
+ /** @function Compare two arrays element-wise. */
1711
+ declare const lessEqual: (x: ArrayLike, y: ArrayLike) => Array;
1712
+ /** @function Element-wise ternary operator, evaluates to `x` if cond else `y`. */
1713
+ declare const where: (cond: ArrayLike, x: ArrayLike, y: ArrayLike) => Array;
1164
1714
  /**
1165
1715
  * @function
1166
- * Calculate element-wise floating-point modulo operation.
1716
+ * Permute the dimensions of an array. Defaults to reversing the axis order.
1167
1717
  */
1168
- declare const fmod: OwnedFunction<(x: ArrayLike, y: ArrayLike) => Array>;
1718
+ declare const transpose: (x: ArrayLike, perm?: number[]) => Array;
1169
1719
  /**
1170
1720
  * @function
1171
- * Calculate element-wise remainder of the division (matches sign of y).
1172
- */
1173
- declare const remainder: OwnedFunction<(x: ArrayLike, y: ArrayLike) => Array>;
1174
- /**
1175
- * Return element-wise quotient and remainder simultaneously.
1176
- *
1177
- * Equivalent to `[floorDivide(x, y), remainder(x, y)]`.
1178
- *
1179
- * @param x - Dividend array.
1180
- * @param y - Divisor array.
1181
- * @returns Tuple of [quotient, remainder].
1182
- */
1183
- declare function divmod(x: ArrayLike, y: ArrayLike): [Array, Array];
1184
- /** Round input to the nearest integer towards zero. */
1185
- declare function trunc(x: ArrayLike): Array;
1186
- /**
1187
- * Compute `x1 * 2 ** x2` as a standard multiplication and exponentiation.
1188
- *
1189
- * This is the inverse of `frexp()`.
1190
- */
1191
- declare function ldexp(x1: ArrayLike, x2: ArrayLike): Array;
1192
- /**
1193
- * Decompose floating-point values into mantissa and two's exponent.
1721
+ * Give a new shape to an array without changing its data.
1194
1722
  *
1195
- * The mantissa is returned in the range `(-1, 1)` with magnitude `>= 0.5` if
1196
- * `x != 0`, and the exponent is an integer such that
1197
- * `x = mantissa * 2**exponent`.
1198
- */
1199
- declare function frexp(x: ArrayLike): [Array, Array];
1200
- /** Calculate `2**p` for all p in the input array. */
1201
- declare function exp2(p: ArrayLike): Array;
1202
- /** Return the base-2 logarithm of x, element-wise. */
1203
- declare function log2(x: ArrayLike): Array;
1204
- /** Return the base-10 logarithm of x, element-wise. */
1205
- declare function log10(x: ArrayLike): Array;
1206
- /** Calculate `exp(x) - 1` element-wise. */
1207
- declare function expm1(x: ArrayLike): Array;
1208
- /** Calculate the natural logarithm of `1 + x` element-wise. */
1209
- declare function log1p(x: ArrayLike): Array;
1210
- /** Convert angles from degrees to radians. */
1211
- declare function deg2rad(x: ArrayLike): Array;
1212
- /** @function Alias of `jax.numpy.deg2rad()`. */
1213
- declare const radians: typeof deg2rad;
1214
- /** Convert angles from radians to degrees. */
1215
- declare function rad2deg(x: ArrayLike): Array;
1216
- /** @function Alias of `jax.numpy.rad2deg()`. */
1217
- declare const degrees: typeof rad2deg;
1218
- /**
1219
- * @function
1220
- * Computes first array raised to power of second array, element-wise.
1723
+ * One shape dimension can be -1. In this case, the value is inferred from the
1724
+ * length of the array and remaining dimensions.
1221
1725
  */
1222
- declare const power: OwnedFunction<(x1: ArrayLike, x2: ArrayLike) => Array>;
1223
- /** @function Calculate the element-wise cube root of the input array. */
1224
- declare const cbrt: OwnedFunction<(x: ArrayLike) => Array>;
1726
+ declare const reshape: (x: ArrayLike, shape: number[]) => Array;
1225
1727
  /**
1226
1728
  * @function
1227
- * Calculate element-wise hyperbolic sine of input.
1228
- *
1229
- * `sinh(x) = (exp(x) - exp(-x)) / 2`
1729
+ * Move axes of an array to new positions. Other axes retain original order.
1230
1730
  */
1231
- declare const sinh: OwnedFunction<(x: ArrayLike) => Array>;
1731
+ declare const moveaxis: (x: ArrayLike, src: number, dst: number) => Array;
1232
1732
  /**
1233
1733
  * @function
1234
- * Calculate element-wise hyperbolic cosine of input.
1734
+ * Add padding (zeros) to an array.
1235
1735
  *
1236
- * `cosh(x) = (exp(x) + exp(-x)) / 2`
1736
+ * The `width` argument is either an integer or pair of integers, in which case
1737
+ * all axes are padded with the same width. Or if it is an array of pairs, each
1738
+ * pair specifies the padding for its corresponding axis.
1237
1739
  */
1238
- declare const cosh: OwnedFunction<(x: ArrayLike) => Array>;
1740
+ declare const pad: (x: ArrayLike, width: number | Pair | Pair[] | Record<number, Pair>) => Array;
1239
1741
  /**
1240
1742
  * @function
1241
- * Calculate element-wise hyperbolic tangent of input.
1242
- *
1243
- * `tanh(x) = sinh(x)/cosh(x) = (exp(x) - exp(-x)) / (exp(x) + exp(-x))`
1743
+ * Return the number of dimensions of an array. Does not consume array reference.
1244
1744
  */
1245
- declare const tanh: OwnedFunction<(x: ArrayLike) => Array>;
1745
+ declare const ndim: (x: ArrayLike) => number;
1746
+ /** @function Return the shape of an array. Does not consume array reference. */
1747
+ declare const shape$1: (x: ArrayLike) => number[];
1246
1748
  /**
1247
1749
  * @function
1248
- * Calculate element-wise inverse hyperbolic sine of input.
1249
- *
1250
- * `arcsinh(x) = ln(x + sqrt(x^2 + 1))`
1750
+ * Return an array of zeros with the same shape and type as a given array.
1251
1751
  */
1252
- declare const arcsinh: OwnedFunction<(x: ArrayLike) => Array>;
1752
+ declare const zerosLike: (a: ArrayLike, dtype?: DType) => Array;
1253
1753
  /**
1254
1754
  * @function
1255
- * Calculate element-wise inverse hyperbolic cosine of input.
1256
- *
1257
- * `arccosh(x) = ln(x + sqrt(x^2 - 1))`
1755
+ * Return an array of ones with the same shape and type as a given array.
1258
1756
  */
1259
- declare const arccosh: OwnedFunction<(x: ArrayLike) => Array>;
1757
+ declare const onesLike: (a: ArrayLike, dtype?: DType) => Array;
1260
1758
  /**
1261
1759
  * @function
1262
- * Calculate element-wise inverse hyperbolic tangent of input.
1263
- *
1264
- * `arctanh(x) = 0.5 * ln((1 + x) / (1 - x))`
1265
- */
1266
- declare const arctanh: OwnedFunction<(x: ArrayLike) => Array>;
1267
- /**
1268
- * Compute the variance of an array.
1269
- *
1270
- * The variance is computed for the flattened array by default, otherwise over
1271
- * the specified axis.
1272
- *
1273
- * If `correction` is provided, the divisor in calculation is `N - correction`,
1274
- * where `N` represents the number of elements (e.g., for Bessel's correction).
1275
- */
1276
- declare function var_(x: ArrayLike, axis?: Axis, opts?: {
1277
- mean?: ArrayLike;
1278
- correction?: number;
1279
- } & ReduceOpts): Array;
1280
- /**
1281
- * Compute the standard deviation of an array.
1282
- *
1283
- * The standard deviation is computed for the flattened array by default,
1284
- * otherwise over the specified axis.
1285
- *
1286
- * If `correction` is provided, the divisor in calculation is `N - correction`,
1287
- * where `N` represents the number of elements (e.g., for Bessel's correction).
1760
+ * Return a full array with the same shape and type as a given array.
1288
1761
  */
1289
- declare function std(x: ArrayLike, axis?: Axis, opts?: {
1290
- mean?: ArrayLike;
1291
- correction?: number;
1292
- } & ReduceOpts): Array;
1293
- /** Estimate the sample covariance of a set of variables. */
1294
- declare function cov(x: ArrayLike, y?: ArrayLike | null, {
1295
- rowvar
1296
- }?: {
1297
- rowvar?: boolean;
1298
- }): Array;
1299
- /** Compute the Pearson correlation coefficients (in range `[-1, 1]`). */
1300
- declare function corrcoef(x: ArrayLike, y?: ArrayLike): Array;
1301
- /** Test element-wise for positive or negative infinity, return bool array. */
1302
- declare function isinf(x: ArrayLike): Array;
1303
- /** Test element-wise for NaN (Not a Number). */
1304
- declare function isnan(x: ArrayLike): Array;
1305
- /** Test element-wise for negative infinity, return bool array. */
1306
- declare function isneginf(x: ArrayLike): Array;
1307
- /** Test element-wise for positive infinity, return bool array. */
1308
- declare function isposinf(x: ArrayLike): Array;
1762
+ declare const fullLike: (a: ArrayLike, fillValue: number | boolean | Array, dtype?: DType) => Array;
1309
1763
  /**
1310
- * @function
1311
- * Test element-wise for finite values (not infinity or NaN).
1764
+ * Return the number of elements in an array, optionally along an axis.
1765
+ * Does not consume array reference.
1312
1766
  */
1313
- declare const isfinite: OwnedFunction<(x: ArrayLike) => Array>;
1314
- declare namespace tree_d_exports {
1315
- export { JsTree, JsTreeDef, MapJsTree, NodeType, dispose, flatten, leaves, map, ref, structure, unflatten };
1316
- }
1317
- declare enum NodeType {
1318
- Array = "Array",
1319
- Object = "Object",
1320
- Leaf = "Leaf",
1321
- }
1322
- /** Analog to the JAX "pytree" object, but for JavaScript. */
1323
- type JsTree<T> = T | JsTree<T>[] | {
1324
- [key: string]: JsTree<T>;
1325
- };
1326
- type Same<X, Y> = (<T>() => T extends X ? 1 : 2) extends (<T>() => T extends Y ? 1 : 2) ? true : false;
1327
- 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> };
1328
- /** @ignore Convert a subtype of JsTree<A> into a JsTree<B>, with the same structure. */
1329
- type MapJsTree<T, A, B> = Same<A, B> extends true ? T : MappedJsTree<T, A, B>;
1330
- /** Represents the structure of a JsTree. */
1331
- declare class JsTreeDef {
1332
- readonly nodeType: NodeType;
1333
- readonly nodeMetadata: any;
1334
- readonly childTreedefs: JsTreeDef[];
1335
- static leaf: JsTreeDef;
1336
- constructor(nodeType: NodeType, nodeMetadata: any,
1337
- // Must be comparable with deepEqual.
1338
- childTreedefs: JsTreeDef[]);
1339
- /** Get the total number of leaves in the tree. */
1340
- get size(): number;
1341
- /** Returns a string representation of this tree definition. */
1342
- toString(root?: boolean): string;
1343
- /** Compare this tree definition with another. */
1344
- equals(other: JsTreeDef): boolean;
1345
- }
1346
- /** Flatten a structured object, returning the tree definition. */
1347
- declare function flatten<T>(tree: JsTree<T>): [T[], JsTreeDef];
1348
- /** Get the leaves of a tree. */
1349
- declare function leaves<T>(tree: JsTree<T>): T[];
1350
- /** Get the treedef for a tree. */
1351
- declare function structure<T>(tree: JsTree<T>): JsTreeDef;
1352
- /** Reconstruct a structured object from the flattened representation. */
1353
- declare function unflatten<T>(treedef: JsTreeDef, leaves: Iterable<T>): JsTree<T>;
1354
- /** Maps a multi-input function over pytree args to produce a new pytree. */
1355
- declare function map<T, U, Tree extends JsTree<T>>(fn: (...args: T[]) => U, tree: Tree, ...rest: Tree[]): MapJsTree<Tree, T, U>;
1356
- /** Take a reference of every array in a tree. */
1357
- declare function ref<Tree extends JsTree<Array>>(tree: Tree): Tree;
1358
- /** Dispose every array in a tree. */
1359
- declare function dispose<Tree extends JsTree<Array>>(tree: Tree | null | undefined): void;
1360
- //#endregion
1361
- //#region src/frontend/convolution.d.ts
1362
- /** Definition of a general dilated convolution. Should be valid on creation. */
1363
- interface ConvParams {
1364
- vmapDims: number;
1365
- strides: number[];
1366
- padding: Pair[];
1367
- lhsDilation: number[];
1368
- rhsDilation: number[];
1369
- }
1767
+ declare function size(a: ArrayLike, axis?: number): number;
1768
+ /** Convert an array to a specified dtype. */
1769
+ declare function astype(a: ArrayLike, dtype: DType): Array;
1770
+ /** Sum of the elements of the array over a given axis, or axes. */
1771
+ declare function sum(a: ArrayLike, axis?: Axis, opts?: ReduceOpts): Array;
1772
+ /** Product of the array elements over a given axis. */
1773
+ declare function prod(a: ArrayLike, axis?: Axis, opts?: ReduceOpts): Array;
1774
+ /** Return the minimum of array elements along a given axis. */
1775
+ declare function min(a: ArrayLike, axis?: Axis, opts?: ReduceOpts): Array;
1776
+ /** Return the maximum of array elements along a given axis. */
1777
+ declare function max(a: ArrayLike, axis?: Axis, opts?: ReduceOpts): Array;
1370
1778
  /**
1371
- * Check that the shapes and parameters passed to convolution are valid.
1372
- * Expected shapes of the lhs and rhs of the convolution are:
1373
- *
1374
- * - `lhsShape = [*vmapDims, batchSize, inChannels, spatialDims...]`
1375
- * - `rhsShape = [*vmapDims, outChannels, inChannels, kernelSize...]`
1779
+ * Test whether any array element along a given axis evaluates to True.
1376
1780
  *
1377
- * If the check succeeds, returns the output shape.
1781
+ * Returns a boolean array with the same shape as `a` with the specified axis
1782
+ * removed. If axis is None, returns a scalar.
1378
1783
  */
1379
- //#endregion
1380
- //#region src/frontend/jaxpr.d.ts
1784
+ declare function any(a: ArrayLike, axis?: Axis, opts?: ReduceOpts): Array;
1381
1785
  /**
1382
- * Function callback with an associated dispose() method.
1786
+ * Test whether all array elements along a given axis evaluate to True.
1383
1787
  *
1384
- * The dispose() method should be called to clean up any tracer resources needed
1385
- * by the function after the last time it is called.
1788
+ * Returns a boolean array with the same shape as `a` with the specified axis
1789
+ * removed. If axis is None, returns a scalar.
1386
1790
  */
1387
- type OwnedFunction<F extends Function> = F & {
1388
- dispose: () => void;
1389
- };
1390
- /** Variable in a Jaxpr expression. */
1391
- declare class Var {
1392
- #private;
1393
- readonly id: number;
1394
- readonly aval: ShapedArray;
1395
- constructor(aval: ShapedArray);
1396
- toString(): string;
1397
- }
1398
- /** Literal in a Jaxpr expression. Currently, only scalars are supported. */
1399
- declare class Lit {
1400
- readonly value: number;
1401
- readonly aval: ShapedArray;
1402
- get dtype(): DType;
1403
- constructor(aval: AbstractValue, value: number);
1404
- }
1405
- type Atom = Var | Lit;
1406
- declare class VarPrinter {
1407
- #private;
1408
- names: Map<Var, string>;
1409
- name(v: Var): string;
1410
- nameType(v: Var): string;
1411
- }
1412
- /** A single statement / binding in a Jaxpr, in ANF form. */
1413
- declare class JaxprEqn {
1414
- readonly primitive: Primitive;
1415
- readonly inputs: Atom[];
1416
- readonly params: Record<string, any>;
1417
- readonly outBinders: Var[];
1418
- constructor(primitive: Primitive, inputs: Atom[], params: Record<string, any>, outBinders: Var[]);
1419
- pprint(usedVars?: Set<Var>, vp?: VarPrinter): PPrint;
1420
- toString(): string;
1421
- }
1422
- /** Typed intermediate representation for traced computations. */
1423
- declare class Jaxpr implements FpHashable {
1424
- #private;
1425
- readonly inBinders: Var[];
1426
- readonly eqns: JaxprEqn[];
1427
- readonly outs: Atom[];
1428
- constructor(inBinders: Var[], eqns: JaxprEqn[], outs: Atom[]);
1429
- pprint(): PPrint;
1430
- toString(): string;
1431
- /**
1432
- * Gets a hash of this Jaxpr.
1433
- *
1434
- * Var identity is not considered in the hash, so two Jaxprs with the same
1435
- * order of assignments and operators but different variable IDs will resolve
1436
- * to the same hash (and toString representation).
1437
- */
1438
- getHash(): bigint;
1439
- hash(state: FpHash): void;
1440
- /**
1441
- * Produce a simplified Jaxpr with basic optimizations applied.
1442
- * - Trim away unused variables.
1443
- * - Fold away *1, *0, or +0 operations against literals.
1444
- * - Remove no-op movement operations.
1445
- */
1446
- simplify(): Jaxpr;
1447
- /** Flattens nested Jit in a Jaxpr. Useful for handling jit-of-jit. */
1448
- flatten(): Jaxpr;
1449
- }
1450
- /** Jaxpr with a collection of associated, traced constants. */
1451
- declare class ClosedJaxpr {
1452
- readonly jaxpr: Jaxpr;
1453
- readonly consts: Tracer[];
1454
- constructor(jaxpr: Jaxpr, consts: Tracer[]);
1455
- /** String representation of this Jaxpr. */
1456
- toString(): string;
1457
- /** Apply a function to the underlying Jaxpr. */
1458
- mapJaxpr(f: (jaxpr: Jaxpr) => Jaxpr): ClosedJaxpr;
1459
- /** Dispose of the constants in this Jaxpr. */
1460
- dispose(): void;
1461
- }
1462
- /** @inline */
1463
- type JitOpts = {
1464
- staticArgnums?: number[];
1465
- };
1466
- //#endregion
1467
- //#region src/frontend/core.d.ts
1791
+ declare function all(a: ArrayLike, axis?: Axis, opts?: ReduceOpts): Array;
1792
+ /** Return the peak-to-peak range along a given axis (`max - min`). */
1793
+ declare function ptp(a: ArrayLike, axis?: Axis, opts?: ReduceOpts): Array;
1794
+ /** Compute the average of the array elements along the specified axis. */
1795
+ declare function mean(a: ArrayLike, axis?: Axis, opts?: ReduceOpts): Array;
1468
1796
  /**
1469
- * Frontend primitive operations, which are lowered into Kernel objects before
1470
- * being dispatched to the backend.
1471
- *
1472
- * Any operation between arrays can be described in these parts. This is also
1473
- * the set of primitives that can occur in Jaxpr programs, and the level at
1474
- * which transformations like vmap, grad, and jvp occur. They are loosely based
1475
- * on [XLA](https://openxla.org/xla/operation_semantics).
1476
- *
1477
- * All n-ary operations support broadcasting, with NumPy semantics.
1478
- */
1479
- declare enum Primitive {
1480
- Add = "add",
1481
- Mul = "mul",
1482
- Idiv = "idiv",
1483
- Mod = "mod",
1484
- // uses sign of numerator, C-style, matches JS but not Python
1485
- Min = "min",
1486
- Max = "max",
1487
- Neg = "neg",
1488
- Reciprocal = "reciprocal",
1489
- Floor = "floor",
1490
- Ceil = "ceil",
1491
- StopGradient = "stop_gradient",
1492
- Cast = "cast",
1493
- Bitcast = "bitcast",
1494
- Sin = "sin",
1495
- Cos = "cos",
1496
- Asin = "asin",
1497
- Atan = "atan",
1498
- Exp = "exp",
1499
- Log = "log",
1500
- Erf = "erf",
1501
- Erfc = "erfc",
1502
- Sqrt = "sqrt",
1503
- Reduce = "reduce",
1504
- Dot = "dot",
1505
- // sum(x*y, axis=-1)
1506
- Conv = "conv",
1507
- // see lax.conv_general_dilated
1508
- Pool = "pool",
1509
- PoolTranspose = "pool_transpose",
1510
- Compare = "compare",
1511
- Where = "where",
1512
- Concatenate = "concatenate",
1513
- Split = "split",
1514
- RandomBits = "random_bits",
1515
- Gather = "gather",
1516
- Transpose = "transpose",
1517
- Broadcast = "broadcast",
1518
- Reshape = "reshape",
1519
- Flip = "flip",
1520
- Shrink = "shrink",
1521
- Pad = "pad",
1522
- Sort = "sort",
1523
- // sort(x, axis=-1)
1524
- Argsort = "argsort",
1525
- // argsort(x, axis=-1)
1526
- TriangularSolve = "triangular_solve",
1527
- // A is upper triangular, A @ X.T = B.T
1528
- Cholesky = "cholesky",
1529
- // A is positive-definite, A = L @ L^T
1530
- LU = "lu",
1531
- // LU decomposition with partial pivoting
1532
- Jit = "jit",
1533
- }
1534
- interface PrimitiveParamsImpl extends Record<Primitive, Record<string, any>> {
1535
- [Primitive.Cast]: {
1536
- dtype: DType;
1537
- };
1538
- [Primitive.Bitcast]: {
1539
- dtype: DType;
1540
- };
1541
- [Primitive.Reduce]: {
1542
- op: AluOp;
1543
- axis: number[];
1544
- };
1545
- [Primitive.Conv]: ConvParams;
1546
- [Primitive.Pool]: {
1547
- window: number[];
1548
- strides: number[];
1549
- };
1550
- [Primitive.PoolTranspose]: {
1551
- inShape: number[];
1552
- window: number[];
1553
- strides: number[];
1554
- };
1555
- [Primitive.Compare]: {
1556
- op: CompareOp;
1557
- };
1558
- [Primitive.Concatenate]: {
1559
- axis: number;
1560
- };
1561
- [Primitive.Split]: {
1562
- axis: number;
1563
- sizes: number[];
1564
- };
1565
- [Primitive.RandomBits]: {
1566
- shape: number[];
1567
- mode: "xor" | 0 | 1;
1568
- };
1569
- [Primitive.Gather]: {
1570
- axis: number[];
1571
- outDim: number;
1572
- };
1573
- [Primitive.Transpose]: {
1574
- perm: number[];
1575
- };
1576
- [Primitive.Broadcast]: {
1577
- shape: number[];
1578
- axis: number[];
1579
- };
1580
- [Primitive.Reshape]: {
1581
- shape: number[];
1582
- };
1583
- [Primitive.Flip]: {
1584
- axis: number[];
1585
- };
1586
- [Primitive.Shrink]: {
1587
- slice: Pair[];
1588
- };
1589
- [Primitive.Pad]: {
1590
- width: Pair[];
1591
- };
1592
- [Primitive.TriangularSolve]: {
1593
- unitDiagonal: boolean;
1594
- };
1595
- [Primitive.Jit]: {
1596
- name: string;
1597
- jaxpr: Jaxpr;
1598
- numConsts: number;
1599
- };
1600
- }
1601
- /** Type of parameters taken by each primitive. */
1602
- type PrimitiveParams<T extends Primitive> = T extends keyof PrimitiveParamsImpl ? PrimitiveParamsImpl[T] : Record<string, never>;
1603
- declare enum CompareOp {
1604
- Less = "less",
1605
- Equal = "equal",
1606
- NotEqual = "not_equal",
1607
- LessEqual = "less_equal",
1608
- }
1609
- /** @inline */
1610
- type Axis = number | number[] | null;
1611
- /** @inline */
1612
- type ReduceOpts = {
1613
- keepdims?: boolean;
1614
- };
1615
- type MainTrace = {
1616
- level: number;
1617
- traceType: new (main: MainTrace) => Trace;
1618
- globalData: any | null;
1619
- };
1797
+ * Returns the indices of the minimum values along an axis.
1798
+ *
1799
+ * By default, index is into the flatted array, otherwise it is along the
1800
+ * specified axis.
1801
+ */
1802
+ declare function argmin(a: ArrayLike, axis?: number, opts?: ReduceOpts): Array;
1620
1803
  /**
1621
- * Push an interpreter onto the trace stack. Use this like:
1622
- * `using main = newMain(...);`
1804
+ * Returns the indices of the maximum values along an axis.
1805
+ *
1806
+ * By default, index is into the flatted array, otherwise it is along the
1807
+ * specified axis.
1623
1808
  */
1624
-
1625
- type TracerValue = Tracer | number | boolean;
1626
- declare abstract class Trace {
1627
- readonly main: MainTrace;
1628
- constructor(main: MainTrace);
1629
- abstract pure(val: TracerValue): Tracer;
1630
- abstract lift(val: Tracer): Tracer;
1631
- abstract processPrimitive<P extends Primitive>(primitive: P, tracers: Tracer[], params: PrimitiveParams<P>): Tracer[];
1632
- }
1633
- /** Internal representation of an array value. */
1634
- interface AbstractValue {
1635
- /** Shape of the array. Must be a static tuple of non-negative dimensions. */
1636
- shape: number[];
1637
- /** Concrete data type of array elements. */
1638
- dtype: DType;
1639
- /**
1640
- * Arrays created from JavaScript numbers (e.g., `np.array(3)`) are created as
1641
- * _weakly typed_ unless a dtype is explicitly specified.
1642
- *
1643
- * Weakly typed values will automatically cast to the data type of other
1644
- * arrays when used as an operand as an expression. This property only affects
1645
- * how they promote in type casting; their memory layout is still determined
1646
- * by the actual `dtype` field.
1647
- *
1648
- * ```ts
1649
- * const x = np.array(3); // weakType = true, dtype = float32
1650
- * const y = np.array([1, 2], { dtype: np.int32 }); // weakType = false, dtype = int32
1651
- * const z = x.add(y); // z has dtype int32 because x is weakly typed
1652
- * ```
1653
- *
1654
- * Weak types are present in JIT programs in their spec (e.g., Jaxpr inputs
1655
- * and outputs can be weakly typed) form. But they're solely a frontend
1656
- * concept. Backends are not aware of weak types.
1657
- */
1658
- weakType: boolean;
1659
- }
1809
+ declare function argmax(a: ArrayLike, axis?: number, opts?: ReduceOpts): Array;
1660
1810
  /**
1661
- * Broadcast shapes and promote types with casting for two avals.
1811
+ * Cumulative sum of elements along an axis.
1662
1812
  *
1663
- * This implements the weak type behavior described in `promoteTypes()`, but not
1664
- * implemented in that function as `weakType` is not passed.
1813
+ * Currently this function is `O(n^2)`, we'll improve this later on with a
1814
+ * two-phase parallel reduction algorithm.
1665
1815
  */
1666
-
1667
- declare abstract class Tracer {
1668
- /** @ignore */
1669
- readonly _trace: Trace;
1670
- constructor(trace: Trace);
1671
- abstract get aval(): AbstractValue;
1672
- abstract toString(): string;
1673
- /**
1674
- * Access an array by reference, incrementing the reference count.
1675
- *
1676
- * jax-js handles freeing arrays by using "move" semantics, like in Rust/C++.
1677
- * Whenever you pass an array into a function, that function should consume
1678
- * the array, and it will no longer be usable. For example, if you had:
1679
- *
1680
- * ```
1681
- * const x = np.array([1, 2, 3]);
1682
- * const y = np.add(x, x);
1683
- * ```
1684
- *
1685
- * The second line does not work because the first parameter consumes `x`, and
1686
- * then the second parameter will already have been freed / disposed.
1687
- *
1688
- * To fix this, you can write:
1689
- *
1690
- * ```
1691
- * const y = np.add(x.ref, x);
1692
- * ```
1693
- *
1694
- * Under the hood, every access to `.ref` increments the internal reference
1695
- * count of the array. The reference count starts at 1. When it hits 0, the
1696
- * memory behind the array is freed.
1697
- */
1698
- abstract get ref(): this;
1699
- /**
1700
- * Manually decrement the reference count of the array.
1701
- *
1702
- * Arrays are created with reference count 1. Whenever it is used as argument
1703
- * to a function or other operation, it is disposed (i.e., reference count
1704
- * decreases by 1) automatically. Whenever a `.ref` is created, the reference
1705
- * count increases.
1706
- *
1707
- * You generally don't need to call this function directly since arrays are
1708
- * automatically disposed after being passed into an operation. One common
1709
- * exception is when writing a function and ignoring one of its arguments. In
1710
- * that case, by convention you should dispose of that argument manually.
1711
- *
1712
- * ```
1713
- * function myCustomOperation(a: np.Array, b: np.Array) {
1714
- * b.dispose(); // Needed to satisfy "move" rules.
1715
- * return a.add(1);
1716
- * }
1717
- * ```
1718
- */
1719
- abstract dispose(): void;
1720
- /** The shape of the array. */
1721
- get shape(): number[];
1722
- /** The total number of elements in the array. */
1723
- get size(): number;
1724
- /** The dtype of elements stored in the array. */
1725
- get dtype(): DType;
1726
- /**
1727
- * Whether the array is weakly typed.
1728
- *
1729
- * Weakly typed arrays will cast to the dtype of the other operand. See
1730
- * `promoteTypes()` for details.
1731
- */
1732
- get weakType(): boolean;
1733
- /** The number of dimensions of the array. */
1734
- get ndim(): number;
1735
- /** @ignore */
1736
- fullLower(): Tracer;
1737
- neg(): this;
1738
- add(other: this | TracerValue): this;
1739
- mul(other: this | TracerValue): this;
1740
- mod(other: this | TracerValue): this;
1741
- greater(other: this | TracerValue): this;
1742
- less(other: this | TracerValue): this;
1743
- equal(other: this | TracerValue): this;
1744
- notEqual(other: this | TracerValue): this;
1745
- greaterEqual(other: this | TracerValue): this;
1746
- lessEqual(other: this | TracerValue): this;
1747
- /** Sum of the elements of the array over a given axis, or axes. */
1748
- sum(axis?: Axis, opts?: ReduceOpts): this;
1749
- /** Product of the array elements over a given axis. */
1750
- prod(axis?: Axis, opts?: ReduceOpts): this;
1751
- /** Compute the average of the array elements along the specified axis. */
1752
- mean(axis?: Axis, opts?: ReduceOpts): this;
1753
- /** Permute the dimensions of an array. Defaults to reversing the axis order. */
1754
- transpose(perm?: number[]): this;
1755
- /**
1756
- * Give a new shape to an array without changing its data.
1757
- *
1758
- * One shape dimension can be -1. In this case, the value is inferred from the
1759
- * length of the array and remaining dimensions.
1760
- */
1761
- reshape(shape: number | number[]): this;
1762
- /** Copy the array and cast to a specified dtype. */
1763
- astype(dtype: DType): this;
1764
- /** Subtract an array from this one. */
1765
- sub(other: this | TracerValue): this;
1766
- /** Divide an array by this one. */
1767
- div(other: this | TracerValue): this;
1768
- /** Return specified diagonals. See `jax.numpy.diagonal` for full docs. */
1769
- diagonal(offset?: number, axis1?: number, axis2?: number): this;
1770
- /** Flatten the array without changing its data. */
1771
- flatten(): this;
1772
- /** Flatten the array without changing its data. */
1773
- ravel(): this;
1774
- /**
1775
- * Iterate over the first dimension of this array, returning slices.
1776
- *
1777
- * This can be used to destructure arrays. For example:
1778
- *
1779
- * ```js
1780
- * let x = np.array([[1, 2], [3, 4]]);
1781
- * let [a, b] = x;
1782
- * console.log(a.js()); // [1, 2]
1783
- * console.log(b.js()); // [3, 4]
1784
- * ```
1785
- */
1786
- [Symbol.iterator](): IterableIterator<this>;
1787
- /**
1788
- * Return a sorted copy of an array in ascending order.
1789
- *
1790
- * See `jax.numpy.sort` for full docs.
1791
- */
1792
- sort(axis?: number): this;
1793
- /**
1794
- * Return the indices that would sort an array. This may not be a stable
1795
- * sorting algorithm; it need not preserve order of indices in ties.
1796
- *
1797
- * See `jax.numpy.argsort` for full docs.
1798
- */
1799
- argsort(axis?: number): this;
1800
- /**
1801
- * Slice an array along one or more axes.
1802
- *
1803
- * This is the equivalent of slicing in Python, e.g. `x[1:3, 2, :, None]`. To
1804
- * mimic this in JavaScript, we would write:
1805
- *
1806
- * ```js
1807
- * x.slice([1, 3], 2, [], null);
1808
- * ```
1809
- *
1810
- * The `slice` method accepts a variable number of arguments, each of which
1811
- * can be a number, an empty array, a single-element array, a two-element
1812
- * array, or `null`. The arguments are interpreted as follows:
1813
- *
1814
- * - A number `n` means to access the `n`-th element along that axis, removing
1815
- * that axis from the resulting shape.
1816
- * - An empty array `[]` means to keep that axis as-is, like `:` in Python.
1817
- * - A single-element array `[i]` means to start slicing from index `i`
1818
- * (inclusive) to the end of the axis, like `x[i:]`.
1819
- * - A two-element array `[i, j]` means to slice from index `i` (inclusive)
1820
- * to index `j` (exclusive), like `x[i:j]`.
1821
- * - `null` means to add a new axis at that position, like `np.newaxis`.
1822
- *
1823
- * Like in Python, negative indices are supported, which count from the end of
1824
- * the axis. For example, `-1` means the last element.
1825
- *
1826
- * Strided slices are not yet implemented, so you cannot write `x[::2]` or
1827
- * similar.
1828
- *
1829
- * Advanced indexing by integer arrays is also supported. This translates to
1830
- * the "gather" primitive, and it allows you to access specific elements of
1831
- * the array by integer indices stored in another array.
1832
- */
1833
- slice(...index: (number | [] | [number] | Pair | null | Tracer)[]): this;
1834
- }
1835
- declare class ShapedArray implements AbstractValue {
1836
- readonly shape: number[];
1837
- readonly dtype: DType;
1838
- readonly weakType: boolean;
1839
- constructor(shape: number[], dtype: DType, weakType: boolean);
1840
- static fromAval(aval: AbstractValue): ShapedArray;
1841
- get ndim(): number;
1842
- get size(): number;
1843
- scalar(): ShapedArray;
1844
- toString(): string;
1845
- equals(other: ShapedArray): boolean;
1846
- }
1847
- //#endregion
1848
- //#region src/frontend/array.d.ts
1849
- type ArrayLike = Array | number | boolean;
1850
- /** Version of pureArray with fudged types. */
1851
-
1816
+ declare function cumsum(a: ArrayLike, axis?: number): Array;
1817
+ /** Reverse the elements in an array along the given axes. */
1818
+ declare function flip(x: ArrayLike, axis?: Axis): Array;
1819
+ /**
1820
+ * Split an array into multiple sub-arrays along an axis.
1821
+ *
1822
+ * @param a - The input array to split.
1823
+ * @param indicesOrSections - If an integer, it indicates the number of equal
1824
+ * sections to create along the specified axis. If a list of integers, it
1825
+ * specifies the indices at which to split the array.
1826
+ * @param axis - The axis along which to split the array. Default is 0.
1827
+ */
1828
+ declare function split$1(a: ArrayLike, indicesOrSections: number | number[], axis?: number): Array[];
1829
+ /**
1830
+ * Join a sequence of arrays along an existing axis.
1831
+ *
1832
+ * The arrays must have the same shape, except in the dimension corresponding to
1833
+ * `axis` (the first, by default).
1834
+ *
1835
+ * No scalars can be passed to this function, as the axis is then ambiguous.
1836
+ */
1837
+ declare function concatenate(xs: Array[], axis?: number): Array;
1852
1838
  /**
1853
- * An executable operation that will be dispatched to the backend.
1839
+ * Join a sequence of arrays along a new axis.
1854
1840
  *
1855
- * This holds a reference to all input buffers used in the operation. After the
1856
- * operation is dispatched, the references should be released.
1841
+ * The `axis` parameter specifies the index of the new axis in the dimensions of
1842
+ * the result. For example, if `axis=0` it will be the first dimension and if
1843
+ * `axis=-1` it will be the last dimension.
1844
+ *
1845
+ * All shapes must have the same shape.
1857
1846
  */
1858
- declare class PendingExecute {
1859
- #private;
1860
- readonly backend: Backend;
1861
- readonly source: Kernel | Routine;
1862
- readonly inputs: Slot[];
1863
- readonly outputs: Slot[];
1864
- prepared: Executable | null;
1865
- submitted: boolean;
1866
- constructor(backend: Backend, source: Kernel | Routine, inputs: Slot[], outputs: Slot[]);
1867
- updateRc(delta: number): void;
1868
- prepare(): Promise<void>;
1869
- prepareSync(): void;
1870
- submit(): void;
1871
- }
1872
- /** @inline */
1873
- type DTypeAndDevice = {
1874
- dtype?: DType;
1875
- device?: Device;
1876
- };
1877
- type ArrayConstructorArgs = {
1878
- source: AluExp | Slot;
1879
- st: ShapeTracker;
1880
- dtype: DType;
1881
- weakType: boolean;
1882
- backend: Backend;
1883
- committed: boolean;
1884
- pending?: Iterable<PendingExecute>;
1885
- };
1847
+ declare function stack(xs: ArrayLike[], axis?: number): Array;
1886
1848
  /**
1887
- * A multidimensional numeric array with data stored on CPU or GPU.
1849
+ * Horizontally stack arrays. Inputs are promoted to rank at least 1, then
1850
+ * concatenated along axis 1 (if rank-2 or higher) or 0 (if rank-1).
1851
+ */
1852
+ declare function hstack(xs: ArrayLike[]): Array;
1853
+ /**
1854
+ * Vertically stack arrays. Inputs are promoted to rank at least 2, then
1855
+ * concatenated along axis 0.
1856
+ */
1857
+ declare function vstack(xs: ArrayLike[]): Array;
1858
+ /**
1859
+ * Stack arrays depth-wise. Inputs are promoted to rank at least 3, then
1860
+ * concatenated along axis 2.
1861
+ */
1862
+ declare function dstack(xs: ArrayLike[]): Array;
1863
+ /**
1864
+ * Stack arrays column-wise. Inputs are promoted to rank at least 2, then
1865
+ * concatenated along axis 1.
1866
+ */
1867
+ declare function columnStack(xs: ArrayLike[]): Array;
1868
+ /** Flip an array vertically (axis=0). */
1869
+ declare function flipud(x: ArrayLike): Array;
1870
+ /** Flip an array horizontally (axis=1). */
1871
+ declare function fliplr(x: ArrayLike): Array;
1872
+ /** Interchange two axes of an array. */
1873
+ declare function swapaxes(a: ArrayLike, axis1: number, axis2: number): Array;
1874
+ /** Transpose the last two dimensions of an array. */
1875
+ declare function matrixTranspose(a: ArrayLike): Array;
1876
+ /** Return a 1-D flattened array containing the elements of the input. */
1877
+ declare function ravel(a: ArrayLike): Array;
1878
+ /** Remove one or more length-1 axes from an array. */
1879
+ declare function squeeze(a: ArrayLike, axis?: Axis): Array;
1880
+ /**
1881
+ * Expand the shape of an array by inserting new axes of length 1.
1888
1882
  *
1889
- * This is the library's core data type. Equivalent to `jax.Array` from JAX, or
1890
- * `torch.Tensor`.
1883
+ * @param a - Input array.
1884
+ * @param axis - Position(s) in the expanded axes where the new axis (or axes)
1885
+ * is placed. Can be a single integer or an array of integers.
1886
+ * @returns Array with the number of dimensions increased.
1891
1887
  *
1892
- * Not to be confused with the JavaScript "Array" constructor. Avoid importing
1893
- * this into your code's namespace if you're already using the JavaScript
1894
- * "Array" type by name.
1888
+ * @example
1889
+ * ```ts
1890
+ * const x = np.array([1, 2]);
1891
+ * np.expandDims(x, 0); // Shape [1, 2]
1892
+ * np.expandDims(x, 1); // Shape [2, 1]
1893
+ * np.expandDims(x, [0, 2]); // Shape [1, 2, 1]
1894
+ * ```
1895
1895
  */
1896
- declare class Array extends Tracer {
1897
- #private;
1898
- /**
1899
- * @ignore
1900
- * Constructs an array from source, shape and backend. Note that if the source
1901
- * is a backend `Slot`, this constructor _takes ownership_ of the slot. It
1902
- * will be freed when the array is disposed.
1903
- */
1904
- constructor(args: ArrayConstructorArgs);
1905
- /** @ignore */
1906
- get aval(): ShapedArray;
1907
- /** Return a simple string representation of the array's dimensions. */
1908
- toString(): string;
1909
- get device(): Device;
1910
- get ref(): this;
1911
- /** Get the current reference count (for debugging memory management). */
1912
- get refCount(): number;
1913
- dispose(): void;
1914
- /**
1915
- * Convert this array into a primitive value.
1916
- *
1917
- * This only works for scalars (0-dimensional arrays). It lets you get values
1918
- * "out" of the JAX system. For instance, if `x = np.array(5)`, then you can
1919
- * evaluate `x + 1` and `x ** 2` to get `6` and `25`, respectively.
1920
- *
1921
- * This method is also called for `==` equality.
1922
- */
1923
- [Symbol.toPrimitive](): any;
1924
- /** Realize the array and return it as data. */
1925
- data(): Promise<DataArray>;
1926
- /**
1927
- * Wait for this array to finish evaluation.
1928
- *
1929
- * Operations and data loading in jax-js are lazy, so this function ensures
1930
- * that pending operations are dispatched and fully executed before it
1931
- * returns.
1932
- *
1933
- * If you are mapping from `data()` or `dataSync()`, it will also trigger
1934
- * dispatch of operations as well.
1935
- *
1936
- * **Note:** `jax.blockUntilReady()` is a higher-level API, it calls this
1937
- * asynchronously for multiple arrays.
1938
- */
1939
- blockUntilReady(): Promise<Array>;
1940
- /**
1941
- * Realize the array and return it as data. This is a sync variant and not
1942
- * recommended for performance reasons, as it will block rendering.
1943
- */
1944
- dataSync(): DataArray;
1945
- /**
1946
- * Convert this array into a JavaScript object.
1947
- *
1948
- * This is a blocking operation that will compile all of the shaders and wait
1949
- * for execution to complete, synchronously. No other JavaScript code on the
1950
- * site will be run during shader execution.
1951
- *
1952
- * To avoid blocking, prefer `jsAsync()` when possible.
1953
- */
1954
- js(): any;
1955
- /** Convert this array into a JavaScript object, asynchronously. */
1956
- jsAsync(): Promise<any>;
1957
- /**
1958
- * Copy an element of an array to a numeric scalar and return it.
1959
- *
1960
- * Throws an error if the array does not have a single element. The array must
1961
- * either be rank-0, or all dimensions of the shape are 1.
1962
- */
1963
- item(): number;
1964
- /** @private Internal plumbing method for Array / Tracer ops. */
1965
- static _implRules(): typeof implRules;
1966
- /** @private */
1967
- _realizeSource(): number;
1968
- /** @private Put this array on a new backend, asynchronously. */
1969
- _put(backend: Backend): Promise<Array>;
1970
- /** @private Put this array on a new backend, synchronously. */
1971
- _putSync(backend: Backend): Array;
1972
- }
1973
- /** Constructor for creating a new array from data. */
1974
- declare function array(values: Array | DataArray | RecursiveArray<number> | RecursiveArray<boolean>, {
1975
- shape,
1976
- dtype,
1977
- device
1978
- }?: {
1979
- shape?: number[];
1980
- } & DTypeAndDevice): Array;
1981
- /** If x is a value, lift it into an array, otherwise leave it be. */
1982
-
1983
- type ImplRule<P extends Primitive> = (tracers: Array[], params: PrimitiveParams<P>) => Array[];
1984
- declare const implRules: { [P in Primitive]: ImplRule<P> };
1985
- /** Return a new array of given shape and type, filled with zeros. */
1986
- declare function zeros(shape: number[], {
1987
- dtype,
1988
- device
1989
- }?: DTypeAndDevice): Array;
1990
- /** Return a new array of given shape and type, filled with ones. */
1991
- declare function ones(shape: number[], {
1992
- dtype,
1993
- device
1994
- }?: DTypeAndDevice): Array;
1995
- /** Return a new array of given shape and type, filled with `fill_value`. */
1996
- declare function full(shape: number[], fillValue: number | boolean | Array, {
1997
- dtype,
1998
- device
1999
- }?: DTypeAndDevice): Array;
1896
+ declare function expandDims(a: ArrayLike, axis: number | number[]): Array;
1897
+ /**
1898
+ * Repeat each element of an array after themselves.
1899
+ *
1900
+ * If no axis is provided, use the flattened input array, and return a flat
1901
+ * output array.
1902
+ */
1903
+ declare function repeat(a: ArrayLike, repeats: number, axis?: number): Array;
1904
+ /**
1905
+ * Construct an array by repeating A the number of times given by reps.
1906
+ *
1907
+ * If `A` is an array of shape `(d1, d2, ..., dn)` and `reps` is a sequence of
1908
+ * integers, the resulting array will have a shape of `(reps[0] * d1,
1909
+ * reps[1] * d2, ..., reps[n] * dn)`, with `A` tiled along each dimension.
1910
+ */
1911
+ declare function tile(a: ArrayLike, reps: number | number[]): Array;
1912
+ /**
1913
+ * Broadcast an array to a shape, with NumPy-style broadcasing rules.
1914
+ *
1915
+ * In other words, this lets you append axes to the left, and/or expand
1916
+ * dimensions where the shape is 1.
1917
+ */
1918
+ declare function broadcastTo(a: ArrayLike, shape: number[]): Array;
1919
+ /** Broadcast input shapes to a common output shape. */
1920
+ declare function broadcastShapes(...shapes: number[][]): number[];
1921
+ /** Broadcast arrays to a common shape. */
1922
+ declare function broadcastArrays(...arrays: ArrayLike[]): Array[];
1923
+ /**
1924
+ * Return specified diagonals.
1925
+ *
1926
+ * If a is 2D, return the diagonal of the array with the given offset. If a is
1927
+ * 3D or higher, compute diagonals along the two given axes (default: 0, 1).
1928
+ *
1929
+ * This returns a view over the existing array. The shape of the resulting array
1930
+ * is determined by removing the two axes along which the diagonal is taken,
1931
+ * then appending a new axis to the right with holding the diagonals.
1932
+ */
1933
+ declare function diagonal(a: ArrayLike, offset?: number, axis1?: number, axis2?: number): Array;
1934
+ /**
1935
+ * Extract a diagonal or construct a diagonal array.
1936
+ *
1937
+ * If v is a 2D array, return the k-th diagonal of v (as a view). If v is a 1D
1938
+ * array, return a 2D array with v on the k-th diagonal.
1939
+ */
1940
+ declare function diag(v: ArrayLike, k?: number): Array;
1941
+ /** Calculate the sum of the diagonal of an array along the given axes. */
1942
+ declare function trace(a: ArrayLike, offset?: number, axis1?: number, axis2?: number): Array;
1943
+ /**
1944
+ * Return a sorted copy of an array.
1945
+ *
1946
+ * The array is sorted along a specified axis (the last by default). This may be
1947
+ * an unstable sort, and it dispatches to device-specific implementation.
1948
+ */
1949
+ declare function sort(a: ArrayLike, axis?: number): Array;
1950
+ /**
1951
+ * Return indices that would sort an array. This may be an unstable sorting
1952
+ * algorithm; it need not preserve order of indices in ties.
1953
+ *
1954
+ * Returns an array of `int32` indices.
1955
+ *
1956
+ * The array is sorted along a specified axis (the last by default).
1957
+ */
1958
+ declare function argsort(a: ArrayLike, axis?: number): Array;
2000
1959
  /**
2001
- * Create an identity matrix.
1960
+ * Take elements from an array along an axis.
2002
1961
  *
2003
- * If numCols is not provided, it defaults to numRows, i.e., a square identity
2004
- * matrix with ones on the diagonal.
1962
+ * This is equivalent to advanced indexing with integer indices over that
1963
+ * numbered axis. By default, the flattened array is used.
2005
1964
  */
2006
- declare function eye(numRows: number, numCols?: number, {
2007
- dtype,
2008
- device
2009
- }?: DTypeAndDevice): Array;
2010
- /** Return the identity matrix, with ones on the main diagonal. */
2011
- declare function identity$1(n: number, {
2012
- dtype,
2013
- device
2014
- }?: DTypeAndDevice): Array;
1965
+ declare function take(a: ArrayLike, indices: ArrayLike, axis?: number | null): Array;
1966
+ /** Return if two arrays are element-wise equal within a tolerance. */
1967
+ declare function allclose(actual: Parameters<typeof array>[0], expected: Parameters<typeof array>[0], options?: {
1968
+ rtol?: number;
1969
+ atol?: number;
1970
+ }): boolean;
1971
+ /** Matrix product of two arrays. */
1972
+ declare function matmul(x: ArrayLike, y: ArrayLike): Array;
1973
+ /** Dot product of two arrays. */
1974
+ declare function dot(x: ArrayLike, y: ArrayLike): Array;
2015
1975
  /**
2016
- * Return evenly spaced values within a given interval.
1976
+ * Compute the tensor dot product of two N-dimensional arrays.
2017
1977
  *
2018
- * This can be called with a varying number of arguments, just like the range()
2019
- * builtin function in Python.
1978
+ * The behavior is determined by `axes`. If an integer `k`, sum over the last
1979
+ * `k` axes of x and the first `k` axes of y. If a tuple, then the first array
1980
+ * corresponds to the axes of x and the second to the axes of y.
1981
+ */
1982
+ declare function tensordot(x: ArrayLike, y: ArrayLike, axes?: number | [number[], number[]]): Array;
1983
+ /**
1984
+ * Einstein summation with string subscripts.
2020
1985
  *
2021
- * - `arange(stop)` is equivalent to `arange(0, stop, 1)`.
2022
- * - `arange(start, stop)` is equivalent to `arange(start, stop, 1)`.
2023
- * - `arange(start, stop, step)` creates an array starting at `start`, ending
2024
- * before `stop`, with a step size of `step`.
1986
+ * @example
1987
+ * ```ts
1988
+ * import { numpy as np } from "@jax-js/jax";
2025
1989
  *
2026
- * Defaults to an integer data type. This can produce unintended results when
2027
- * using a non-integer step, so prefer linspace() in those cases.
1990
+ * const a = np.ones([2, 3]);
1991
+ * const b = np.ones([3]);
1992
+ * np.einsum("ij,j", a, b); // Shape [2]
1993
+ * ```
2028
1994
  */
2029
- declare function arange(start: number, stop?: number, step?: number, {
2030
- dtype,
2031
- device
2032
- }?: DTypeAndDevice): Array;
1995
+ declare function einsum(subscripts: string, ...operands: ArrayLike[]): Array;
2033
1996
  /**
2034
- * Return an array with ones on and below the diagonal and zeros elsewhere.
1997
+ * Einstein summation alternating between arrays and numeric indices.
2035
1998
  *
2036
- * If `k` is provided, it specifies the sub-diagonal on and below which the
2037
- * array is filled with ones. `k=0` is the main diagonal, `k<0` is below it, and
2038
- * `k>0` is above it.
1999
+ * @example
2000
+ * ```ts
2001
+ * import { numpy as np } from "@jax-js/jax";
2002
+ *
2003
+ * const a = np.ones([2, 3]);
2004
+ * const b = np.ones([3]);
2005
+ * np.einsum(a, [0, 1], b, [1]); // Shape [2]
2006
+ * ```
2039
2007
  */
2040
- declare function tri(n: number, m?: number, k?: number, {
2041
- dtype,
2042
- device
2043
- }?: DTypeAndDevice): Array;
2044
- /** Return the lower triangle of an array. Must be of dimension >= 2. */
2045
- declare function tril(a: ArrayLike, k?: number): Array;
2046
- /** Return the upper triangle of an array. Must be of dimension >= 2. */
2047
- declare function triu(a: ArrayLike, k?: number): Array;
2008
+ declare function einsum(...args: (ArrayLike | number[])[]): Array;
2048
2009
  /**
2049
- * Return evenly spaced numbers over a specified interval.
2010
+ * Compute the inner product of two arrays.
2050
2011
  *
2051
- * Returns _num_ evenly spaced samples, calculated over the interval
2052
- * [`start`, `stop`]. The endpoint `stop` is included in the result by default,
2053
- * but this is controlled by the `endpoint` parameter.
2012
+ * Unlike `jax.numpy.matmul()` or `jax.numpy.dot()`, this always performs a
2013
+ * contraction on the last axis.
2054
2014
  *
2055
- * The default data type is Float32. Use arange() for integer steps.
2015
+ * Returned array has shape `[...x.shape[:-1], ...y.shape[:-1]]`.
2056
2016
  */
2057
- declare function linspace(start: number, stop: number, num?: number, endpoint?: boolean, {
2058
- dtype,
2059
- device
2060
- }?: DTypeAndDevice): Array;
2017
+ declare function inner(x: ArrayLike, y: ArrayLike): Array;
2061
2018
  /**
2062
- * Return numbers spaced evenly on a log scale.
2019
+ * Compute the outer product of two arrays.
2063
2020
  *
2064
- * In linear space, the sequence starts at `base ** start` and ends at
2065
- * `base ** stop` (see `endpoint` below).
2021
+ * If the input arrays are not 1D, they will be flattened. Returned array will
2022
+ * be of shape `[x.size, y.size]`.
2023
+ */
2024
+ declare function outer(x: ArrayLike, y: ArrayLike): Array;
2025
+ /** Vector dot product of two arrays along a given axis. */
2026
+ declare function vecdot(x: ArrayLike, y: ArrayLike, {
2027
+ axis
2028
+ }?: {
2029
+ axis?: number;
2030
+ }): Array;
2031
+ /**
2032
+ * Return the dot product of two vectors.
2066
2033
  *
2067
- * @param start - `base ** start` is the starting value of the sequence.
2068
- * @param stop - `base ** stop` is the final value of the sequence, unless `endpoint` is false.
2069
- * @param num - Number of samples to generate. Default is 50.
2070
- * @param endpoint - If true, `stop` is the last sample. Otherwise, it is not included. Default is true.
2071
- * @param base - The base of the log space. Default is 10.
2072
- * @returns Array of evenly spaced values on a log scale.
2034
+ * Like vecdot() but flattens the arguments first into vectors.
2073
2035
  */
2074
- declare function logspace(start: number, stop: number, num?: number, endpoint?: boolean, base?: number, {
2075
- dtype,
2076
- device
2077
- }?: DTypeAndDevice): Array;
2078
- //#endregion
2079
- //#region src/frontend/linearize.d.ts
2080
- /** @inline */
2081
- type GradOpts = {
2082
- /**
2083
- * Integer or sequence of integers. Specifies which positional argument(s) to
2084
- * differentiate with respect to.
2085
- *
2086
- * Defaults to `0` (the first argument).
2087
- */
2088
- argnums?: number | number[];
2089
- /**
2090
- * The input function returns a pair of `[out, aux]` including an auxiliary
2091
- * value. This `aux` is not differentiated, but is returned alongside the
2092
- * gradient when evaluating the function.
2093
- */
2094
- hasAux?: boolean;
2095
- };
2096
- declare namespace lax_linalg_d_exports {
2097
- export { cholesky, lu, triangularSolve };
2098
- }
2036
+ declare function vdot(x: ArrayLike, y: ArrayLike): Array;
2037
+ /** Convolution of two one-dimensional arrays. */
2038
+ declare function convolve(x: Array, y: Array, mode?: "full" | "same" | "valid"): Array;
2039
+ /** Correlation of two one dimensional arrays. */
2040
+ declare function correlate(x: Array, y: Array, mode?: "full" | "same" | "valid"): Array;
2099
2041
  /**
2100
- * Compute the Cholesky decomposition of a symmetric positive-definite matrix.
2042
+ * Return a tuple of coordinate matrices from coordinate vectors.
2101
2043
  *
2102
- * The Cholesky decomposition of a matrix `A` is:
2044
+ * Make N-D coordinate arrays for vectorized evaluations of N-D scalar/vector
2045
+ * fields over N-D grids, given one-dimensional coordinate arrays x1, x2,…, xn.
2046
+ */
2047
+ declare function meshgrid(xs: Array[], {
2048
+ indexing
2049
+ }?: {
2050
+ indexing?: "xy" | "ij";
2051
+ }): Array[];
2052
+ /**
2053
+ * Clip (limit) the values in an array.
2103
2054
  *
2104
- * - A = L @ L^T (for upper=false, default)
2105
- * - A = U^T @ U (for upper=true)
2055
+ * Given an interval, values outside the interval are clipped to the interval
2056
+ * edges. For example, if an interval of [0, 1] is specified, values smaller
2057
+ * than 0 become 0, and values larger than 1 become 1.
2106
2058
  *
2107
- * where `L` is a lower-triangular matrix and `U` is an upper-triangular matrix.
2108
- * The input matrix must be symmetric and positive-definite.
2059
+ * If either bound is undefined, it is ignored.
2060
+ */
2061
+ declare function clip(a: ArrayLike, min?: ArrayLike, max?: ArrayLike): Array;
2062
+ /**
2063
+ * Calculate the absolute value element-wise.
2109
2064
  *
2110
- * @example
2111
- * ```ts
2112
- * import { lax, numpy as np } from "@jax-js/jax";
2065
+ * This is the same function as `jax.numpy.abs()`.
2066
+ */
2067
+ declare function absolute(x: ArrayLike): Array;
2068
+ /** Return an element-wise indication of sign of the input. */
2069
+ declare function sign(x: ArrayLike): Array;
2070
+ /** @function Return element-wise positive values of the input (no-op). */
2071
+ declare const positive: (x: ArrayLike) => Array;
2072
+ /**
2073
+ * Return the Hamming window of size M, a taper with a weighted cosine bell.
2113
2074
  *
2114
- * const x = np.array([[2., 1.], [1., 2.]]);
2075
+ * `w(n) = 0.54 - 0.46 * cos(2πn/(M-1))` for `0 <= n <= M-1`.
2076
+ */
2077
+ declare function hamming(M: number): Array;
2078
+ /**
2079
+ * Return the Hann window of size M, a taper with a weighted cosine bell.
2115
2080
  *
2116
- * // Lower Cholesky factorization (default):
2117
- * const L = lax.linalg.cholesky(x);
2118
- * // L ≈ [[1.4142135, 0], [0.70710677, 1.2247449]]
2081
+ * `w(n) = 0.5 - 0.5 * cos(2πn/(M-1))` for `0 <= n <= M-1`.
2082
+ */
2083
+ declare function hann(M: number): Array;
2084
+ /**
2085
+ * @function
2086
+ * Compute the Heaviside step function. It is defined piecewise:
2087
+ * - `heaviside(x1, x2) = 0` for `x1 < 0`,
2088
+ * - `heaviside(x1, x2) = x2` for `x1 == 0`,
2089
+ * - `heaviside(x1, x2) = 1` for `x1 > 0`.
2090
+ */
2091
+ declare const heaviside: OwnedFunction<(x1: ArrayLike, x2: ArrayLike) => Array>;
2092
+ /** Calculate element-wise square of the input array. */
2093
+ declare function square(x: ArrayLike): Array;
2094
+ /** Element-wise tangent function (takes radians). */
2095
+ declare function tan(x: ArrayLike): Array;
2096
+ /**
2097
+ * @function
2098
+ * Return the normalized sinc function.
2119
2099
  *
2120
- * // Upper Cholesky factorization:
2121
- * const U = lax.linalg.cholesky(x, { upper: true });
2122
- * // U ≈ [[1.4142135, 0.70710677], [0, 1.2247449]]
2123
- * ```
2100
+ * The sinc function is defined as `sin(πx) / (πx)` for `x != 0`, and `1` for `x = 0`.
2101
+ * This is the normalized sinc function commonly used in signal processing.
2102
+ *
2103
+ * **Note:** JVP is not supported at x=0 due to discontinuous derivative. This
2104
+ * requires a custom JVP rule to handle properly (see JAX implementation).
2124
2105
  */
2125
- declare function cholesky(a: ArrayLike, {
2126
- upper
2127
- }?: {
2128
- upper?: boolean;
2129
- }): Array;
2106
+ declare const sinc: OwnedFunction<(x: ArrayLike) => Array>;
2107
+ /** Element-wise inverse cosine function (inverse of cos). */
2108
+ declare function acos(x: ArrayLike): Array;
2130
2109
  /**
2131
- * LU decomposition with partial pivoting.
2110
+ * @function
2111
+ * Return element-wise hypotenuse for the given legs of a right triangle.
2112
+ *
2113
+ * In the original NumPy/JAX implementation, this function is more numerically
2114
+ * stable than `sqrt(x1**2 + x2**2)`. We don't currently implement those
2115
+ * stability improvements.
2116
+ */
2117
+ declare const hypot: OwnedFunction<(x1: ArrayLike, x2: ArrayLike) => Array>;
2118
+ /**
2119
+ * @function
2120
+ * Element-wise arc tangent of y/x with correct quadrant.
2121
+ *
2122
+ * Returns the angle in radians between the positive x-axis and the point (x, y).
2123
+ * The result is in the range [-π, π].
2124
+ *
2125
+ * Uses numerically stable formulas:
2126
+ * - When x >= 0: atan2(y, x) = 2 * atan(y / (sqrt(x^2 + y^2) + x))
2127
+ * - When x < 0: atan2(y, x) = 2 * atan((sqrt(x^2 + y^2) - x) / y)
2128
+ *
2129
+ * The output is ill-defined when both x and y are zero.
2130
+ */
2131
+ declare const atan2: OwnedFunction<(y: ArrayLike, x: ArrayLike) => Array>;
2132
+ /** Element-wise subtraction, with broadcasting. */
2133
+ declare function subtract(x: ArrayLike, y: ArrayLike): Array;
2134
+ /** Calculates the floating-point division of x by y element-wise. */
2135
+ declare function trueDivide(x: ArrayLike, y: ArrayLike): Array;
2136
+ /**
2137
+ * Return the largest integer smaller or equal to the division of the inputs.
2132
2138
  *
2133
- * Computes the matrix decomposition: `P @ A = L @ U`, where `P` is a
2134
- * permutation of the rows of `A`, `L` is lower-triangular with unit diagonal,
2135
- * and `U` is upper-triangular.
2139
+ * The result is always rounded towards negative infinity.
2136
2140
  *
2137
- * @param x - A batch of matrices with shape `[..., m, n]`.
2141
+ * For floating-point inputs, this is equivalent to `floor(x / y)`.
2142
+ * For integer inputs, we use `(x - remainder(x, y)) / y` to handle
2143
+ * negative values correctly (note: may overflow near int32 boundaries).
2138
2144
  *
2139
- * @returns A tuple `(lu, pivots, permutation)` where:
2140
- * - `lu`: combined lower and upper triangular matrices.
2141
- * - `pivots`: an array of pivot indices with shape `[..., min(m, n)]`.
2142
- * - `permutation`: the permutation generated by pivots with shape `[..., m]`.
2145
+ * @param x - Dividend array.
2146
+ * @param y - Divisor array.
2147
+ * @returns Element-wise floor division of x by y.
2148
+ */
2149
+ declare function floorDivide(x: ArrayLike, y: ArrayLike): Array;
2150
+ /**
2151
+ * @function
2152
+ * Calculate element-wise floating-point modulo operation.
2153
+ */
2154
+ declare const fmod: OwnedFunction<(x: ArrayLike, y: ArrayLike) => Array>;
2155
+ /**
2156
+ * @function
2157
+ * Calculate element-wise remainder of the division (matches sign of y).
2158
+ */
2159
+ declare const remainder: OwnedFunction<(x: ArrayLike, y: ArrayLike) => Array>;
2160
+ /**
2161
+ * Return element-wise quotient and remainder simultaneously.
2143
2162
  *
2144
- * @example
2145
- * ```ts
2146
- * import { lax, numpy as np } from "@jax-js/jax";
2163
+ * Equivalent to `[floorDivide(x, y), remainder(x, y)]`.
2147
2164
  *
2148
- * const A = np.array([[4., 3.], [6., 3.]]);
2149
- * const [lu, pivots, permutation] = lax.linalg.lu(A);
2150
- * // lu [[6., 3.], [0.6666667, 1.0]]
2151
- * // pivots = [1, 1]
2152
- * // permutation = [1, 0]
2153
- * ```
2165
+ * @param x - Dividend array.
2166
+ * @param y - Divisor array.
2167
+ * @returns Tuple of [quotient, remainder].
2154
2168
  */
2155
- declare function lu(x: ArrayLike): [Array, Array, Array];
2169
+ declare function divmod(x: ArrayLike, y: ArrayLike): [Array, Array];
2170
+ /** Round input to the nearest integer towards zero. */
2171
+ declare function trunc(x: ArrayLike): Array;
2156
2172
  /**
2157
- * Solve a triangular linear system.
2158
- *
2159
- * Solves `a @ x = b` (if leftSide=true) or `x @ a = b` (if leftSide=false)
2160
- * where `a` is a triangular matrix.
2173
+ * Compute `x1 * 2 ** x2` as a standard multiplication and exponentiation.
2161
2174
  *
2162
- * @example
2163
- * ```ts
2164
- * import { lax, numpy as np } from "@jax-js/jax";
2175
+ * This is the inverse of `frexp()`.
2176
+ */
2177
+ declare function ldexp(x1: ArrayLike, x2: ArrayLike): Array;
2178
+ /**
2179
+ * Decompose floating-point values into mantissa and two's exponent.
2165
2180
  *
2166
- * const L = np.array([[2., 0.], [1., 3.]]);
2167
- * const b = np.array([4., 7.]).reshape([2, 1]);
2181
+ * The mantissa is returned in the range `(-1, 1)` with magnitude `>= 0.5` if
2182
+ * `x != 0`, and the exponent is an integer such that
2183
+ * `x = mantissa * 2**exponent`.
2184
+ */
2185
+ declare function frexp(x: ArrayLike): [Array, Array];
2186
+ /** Calculate `2**p` for all p in the input array. */
2187
+ declare function exp2(p: ArrayLike): Array;
2188
+ /** Return the base-2 logarithm of x, element-wise. */
2189
+ declare function log2(x: ArrayLike): Array;
2190
+ /** Return the base-10 logarithm of x, element-wise. */
2191
+ declare function log10(x: ArrayLike): Array;
2192
+ /** Calculate `exp(x) - 1` element-wise. */
2193
+ declare function expm1(x: ArrayLike): Array;
2194
+ /** Calculate the natural logarithm of `1 + x` element-wise. */
2195
+ declare function log1p(x: ArrayLike): Array;
2196
+ /** Convert angles from degrees to radians. */
2197
+ declare function deg2rad(x: ArrayLike): Array;
2198
+ /** @function Alias of `jax.numpy.deg2rad()`. */
2199
+ declare const radians: typeof deg2rad;
2200
+ /** Convert angles from radians to degrees. */
2201
+ declare function rad2deg(x: ArrayLike): Array;
2202
+ /** @function Alias of `jax.numpy.rad2deg()`. */
2203
+ declare const degrees: typeof rad2deg;
2204
+ /**
2205
+ * @function
2206
+ * Computes first array raised to power of second array, element-wise.
2207
+ */
2208
+ declare const power: OwnedFunction<(x1: ArrayLike, x2: ArrayLike) => Array>;
2209
+ /** @function Calculate the element-wise cube root of the input array. */
2210
+ declare const cbrt: OwnedFunction<(x: ArrayLike) => Array>;
2211
+ /**
2212
+ * @function
2213
+ * Calculate element-wise hyperbolic sine of input.
2168
2214
  *
2169
- * // Solve L @ x = b
2170
- * const x = lax.linalg.triangularSolve(L, b, { leftSide: true, lower: true });
2171
- * // x = [[2.], [5./3.]]
2172
- * ```
2215
+ * `sinh(x) = (exp(x) - exp(-x)) / 2`
2173
2216
  */
2174
- declare function triangularSolve(a: ArrayLike, b: ArrayLike, {
2175
- leftSide,
2176
- lower,
2177
- transposeA,
2178
- unitDiagonal
2179
- }?: {
2180
- leftSide?: boolean;
2181
- lower?: boolean;
2182
- transposeA?: boolean;
2183
- unitDiagonal?: boolean;
2184
- }): Array;
2185
- declare namespace lax_d_exports {
2186
- export { DotDimensionNumbers, PaddingType, conv, convGeneralDilated, convTranspose, convWithGeneralPadding, dot, erf, erfc, lax_linalg_d_exports as linalg, reduceWindow, stopGradient };
2187
- }
2217
+ declare const sinh: OwnedFunction<(x: ArrayLike) => Array>;
2188
2218
  /**
2189
- * Dimension numbers for general `dot()` primitive.
2219
+ * @function
2220
+ * Calculate element-wise hyperbolic cosine of input.
2190
2221
  *
2191
- * Contracting dimensions act as a tensor contraction (reduction) along the
2192
- * given axis. They must be the same size in both operands. Batch dimensions
2193
- * are treated as vectorized, leading batch dimensions.
2222
+ * `cosh(x) = (exp(x) + exp(-x)) / 2`
2223
+ */
2224
+ declare const cosh: OwnedFunction<(x: ArrayLike) => Array>;
2225
+ /**
2226
+ * @function
2227
+ * Calculate element-wise hyperbolic tangent of input.
2194
2228
  *
2195
- * The return value has a shape where the first dimensions are shared batch
2196
- * dimensions, followed by `lhs` non-contracting dimensions, followed by
2197
- * `rhs` non-contracting dimensions.
2229
+ * `tanh(x) = sinh(x)/cosh(x) = (exp(x) - exp(-x)) / (exp(x) + exp(-x))`
2198
2230
  */
2199
- type DotDimensionNumbers = {
2200
- lhsContractingDims?: number[];
2201
- rhsContractingDims?: number[];
2202
- lhsBatchDims?: number[];
2203
- rhsBatchDims?: number[];
2204
- };
2231
+ declare const tanh: OwnedFunction<(x: ArrayLike) => Array>;
2205
2232
  /**
2206
- * General dot product/contraction operator.
2233
+ * @function
2234
+ * Calculate element-wise inverse hyperbolic sine of input.
2207
2235
  *
2208
- * Prefer higher-level functions like `jax.numpy.dot()`, `jax.numpy.matmul()`,
2209
- * `jax.numpy.tensordot(), and `jax.numpy.einsum()` where possible.
2236
+ * `arcsinh(x) = ln(x + sqrt(x^2 + 1))`
2210
2237
  */
2211
- declare function dot(lhs: Array, rhs: Array, {
2212
- lhsContractingDims: lc,
2213
- rhsContractingDims: rc,
2214
- lhsBatchDims: lb,
2215
- rhsBatchDims: rb
2216
- }?: DotDimensionNumbers): Array;
2217
- type PaddingType = "VALID" | "SAME" | "SAME_LOWER" | Pair[];
2238
+ declare const arcsinh: OwnedFunction<(x: ArrayLike) => Array>;
2218
2239
  /**
2219
- * General n-dimensional convolution operator, with optional dilation.
2240
+ * @function
2241
+ * Calculate element-wise inverse hyperbolic cosine of input.
2220
2242
  *
2221
- * The semantics of this operation mimic the `jax.lax.conv_general_dilated`
2222
- * function in JAX, which wraps XLA's general convolution operator.
2243
+ * `arccosh(x) = ln(x + sqrt(x^2 - 1))`
2244
+ */
2245
+ declare const arccosh: OwnedFunction<(x: ArrayLike) => Array>;
2246
+ /**
2247
+ * @function
2248
+ * Calculate element-wise inverse hyperbolic tangent of input.
2223
2249
  *
2224
- * @param lhs - Input tensor; shape `[N, C_in, ...xs]`
2225
- * @param rhs - Convolution kernel; shape `[C_out, C_in / G, ...ks]`
2226
- * @param windowStrides - Strides for each spatial dimension
2227
- * @param padding - Padding for each spatial dimension, or a string
2228
- * (`"VALID"`, `"SAME"`, or `"SAME_LOWER"`)
2250
+ * `arctanh(x) = 0.5 * ln((1 + x) / (1 - x))`
2229
2251
  */
2230
- declare function convGeneralDilated(lhs: Array, rhs: Array, windowStrides: number[], padding: PaddingType, {
2231
- lhsDilation,
2232
- rhsDilation,
2233
- featureGroupCount
2234
- }?: {
2235
- lhsDilation?: number[];
2236
- rhsDilation?: number[];
2237
- featureGroupCount?: number;
2238
- }): Array;
2239
- /** Convenience wrapper around `convGeneralDilated`. */
2240
- declare function convWithGeneralPadding(lhs: Array, rhs: Array, windowStrides: number[], padding: PaddingType, lhsDilation?: number[], rhsDilation?: number[]): Array;
2241
- /** Convenience wrapper around `convGeneralDilated`. */
2242
- declare function conv(lhs: Array, rhs: Array, windowStrides: number[], padding: PaddingType): Array;
2252
+ declare const arctanh: OwnedFunction<(x: ArrayLike) => Array>;
2243
2253
  /**
2244
- * Convenience wrapper for calculating the N-d convolution "transpose".
2254
+ * Compute the variance of an array.
2245
2255
  *
2246
- * This function directly calculates a fractionally strided conv rather than
2247
- * indirectly calculating the gradient (transpose) of a forward convolution.
2248
- * It is equivalent to the JAX version, except:
2256
+ * The variance is computed for the flattened array by default, otherwise over
2257
+ * the specified axis.
2249
2258
  *
2250
- * - The `use_consistent_padding` option is not available. We only have the
2251
- * consistent padding case (JAX version >0.8.4).
2252
- * - The order of dimensions matches `lax.conv_general_dilated`.
2259
+ * If `correction` is provided, the divisor in calculation is `N - correction`,
2260
+ * where `N` represents the number of elements (e.g., for Bessel's correction).
2261
+ */
2262
+ declare function var_(x: ArrayLike, axis?: Axis, opts?: {
2263
+ mean?: ArrayLike;
2264
+ correction?: number;
2265
+ } & ReduceOpts): Array;
2266
+ /**
2267
+ * Compute the standard deviation of an array.
2253
2268
  *
2254
- * Unlike PyTorch/TensorFlow, by default we don't reverse the kernel's spatial
2255
- * dimensions or the `(C_out, C_in)` axis order. To get this behavior, set
2256
- * `transposeKernel` to true.
2269
+ * The standard deviation is computed for the flattened array by default,
2270
+ * otherwise over the specified axis.
2257
2271
  *
2258
- * @param lhs - Input tensor; shape `[N, C_in, ...xs]`
2259
- * @param rhs - Convolution kernel; shape `[C_out, C_in, ...ks]`
2260
- * @param strides - Sequence of n integers, sets fractional stride
2261
- * @param padding - Apply padding of `dilation * (kernel_size - 1) - padding` to
2262
- * each side of the input, so it acts like gradient of `conv()`
2263
- * @param rhsDilation - Atrous dilation for the kernel
2264
- * @param transposeKernel - Flip spatial axes and swap the input/output channels
2265
- * of the kernel; its shape should be `[C_in, C_out, ...ks]`
2272
+ * If `correction` is provided, the divisor in calculation is `N - correction`,
2273
+ * where `N` represents the number of elements (e.g., for Bessel's correction).
2266
2274
  */
2267
- declare function convTranspose(lhs: Array, rhs: Array, strides: number[], padding: PaddingType, {
2268
- rhsDilation,
2269
- transposeKernel
2275
+ declare function std(x: ArrayLike, axis?: Axis, opts?: {
2276
+ mean?: ArrayLike;
2277
+ correction?: number;
2278
+ } & ReduceOpts): Array;
2279
+ /** Estimate the sample covariance of a set of variables. */
2280
+ declare function cov(x: ArrayLike, y?: ArrayLike | null, {
2281
+ rowvar
2270
2282
  }?: {
2271
- rhsDilation?: number[];
2272
- transposeKernel?: boolean;
2283
+ rowvar?: boolean;
2273
2284
  }): Array;
2274
- /** Reduce a computation over padded windows. */
2275
- declare function reduceWindow(operand: Array, computation: (x: Array) => Array, windowDimensions: number[], windowStrides?: number[]): Array;
2276
- /** The error function: `erf(x) = 2/sqrt(pi) * int[0..x] exp(-t^2) dt`. */
2277
- declare function erf(x: ArrayLike): Array;
2285
+ /** Compute the Pearson correlation coefficients (in range `[-1, 1]`). */
2286
+ declare function corrcoef(x: ArrayLike, y?: ArrayLike): Array;
2287
+ /** Test element-wise for positive or negative infinity, return bool array. */
2288
+ declare function isinf(x: ArrayLike): Array;
2289
+ /** Test element-wise for NaN (Not a Number). */
2290
+ declare function isnan(x: ArrayLike): Array;
2291
+ /** Test element-wise for negative infinity, return bool array. */
2292
+ declare function isneginf(x: ArrayLike): Array;
2293
+ /** Test element-wise for positive infinity, return bool array. */
2294
+ declare function isposinf(x: ArrayLike): Array;
2278
2295
  /**
2279
- * The complementary error function: `erfc(x) = 1 - erf(x)`.
2296
+ * Replace NaN and infinite entries in an array.
2280
2297
  *
2281
- * This function is more accurate than `1 - erf(x)` for large values of `x`,
2282
- * where `erf(x)` is very close to 1.
2298
+ * By default, NaNs are replaced with `0.0`, and infinities are are substituted
2299
+ * with the corresponding maximum or minimum finite values.
2283
2300
  */
2284
- declare function erfc(x: ArrayLike): Array;
2301
+ declare function nanToNum(x: ArrayLike, {
2302
+ nan,
2303
+ posinf,
2304
+ neginf
2305
+ }?: {
2306
+ nan?: ArrayLike;
2307
+ posinf?: ArrayLike | null;
2308
+ neginf?: ArrayLike | null;
2309
+ }): Array;
2285
2310
  /**
2286
- * Stops gradient computation.
2287
- *
2288
- * Behaves as the identity function but prevents the flow of gradients during
2289
- * forward or reverse-mode automatic differentiation.
2311
+ * @function
2312
+ * Test element-wise for finite values (not infinity or NaN).
2290
2313
  */
2291
- declare function stopGradient(x: ArrayLike): Array;
2314
+ declare const isfinite: OwnedFunction<(x: ArrayLike) => Array>;
2292
2315
  declare namespace nn_d_exports {
2293
2316
  export { celu, dotProductAttention, elu, gelu, glu, hardSigmoid, hardSilu, hardSilu as hardSwish, hardTanh, identity, leakyRelu, logSigmoid, logSoftmax, logmeanexp, logsumexp, mish, oneHot, relu, relu6, selu, sigmoid, silu, softSign, softmax, softplus, sparsePlus, sparseSigmoid, squareplus, standardize, silu as swish };
2294
2317
  }