code
stringlengths
66
870k
docstring
stringlengths
19
26.7k
func_name
stringlengths
1
138
language
stringclasses
1 value
repo
stringlengths
7
68
path
stringlengths
5
324
url
stringlengths
46
389
license
stringclasses
7 values
def lt(x: ArrayLike, y: ArrayLike) -> Array: r"""Elementwise less-than: :math:`x < y`. This function lowers directly to the `stablehlo.compare`_ operation with ``comparison_direction=LT`` and ``compare_type`` set according to the input dtype. Args: x, y: Input arrays. Must have matching non-complex dtyp...
Elementwise less-than: :math:`x < y`. This function lowers directly to the `stablehlo.compare`_ operation with ``comparison_direction=LT`` and ``compare_type`` set according to the input dtype. Args: x, y: Input arrays. Must have matching non-complex dtypes. If neither is a scalar, ``x`` and ``y`` m...
lt
python
jax-ml/jax
jax/_src/lax/lax.py
https://github.com/jax-ml/jax/blob/master/jax/_src/lax/lax.py
Apache-2.0
def convert_element_type(operand: ArrayLike, new_dtype: DTypeLike | dtypes.ExtendedDType) -> Array: """Elementwise cast. This function lowers directly to the `stablehlo.convert`_ operation, which performs an elementwise conversion from one type to another, similar to a C++ ``static_cas...
Elementwise cast. This function lowers directly to the `stablehlo.convert`_ operation, which performs an elementwise conversion from one type to another, similar to a C++ ``static_cast``. Args: operand: an array or scalar value to be cast. new_dtype: a dtype-like object (e.g. a :class:`numpy.dtype`, a...
convert_element_type
python
jax-ml/jax
jax/_src/lax/lax.py
https://github.com/jax-ml/jax/blob/master/jax/_src/lax/lax.py
Apache-2.0
def bitcast_convert_type(operand: ArrayLike, new_dtype: DTypeLike) -> Array: """Elementwise bitcast. This function lowers directly to the `stablehlo.bitcast_convert`_ operation. The output shape depends on the size of the input and output dtypes with the following logic:: if new_dtype.itemsize == operand...
Elementwise bitcast. This function lowers directly to the `stablehlo.bitcast_convert`_ operation. The output shape depends on the size of the input and output dtypes with the following logic:: if new_dtype.itemsize == operand.dtype.itemsize: output_shape = operand.shape if new_dtype.itemsize < op...
bitcast_convert_type
python
jax-ml/jax
jax/_src/lax/lax.py
https://github.com/jax-ml/jax/blob/master/jax/_src/lax/lax.py
Apache-2.0
def clamp(min: ArrayLike, x: ArrayLike, max: ArrayLike) -> Array: r"""Elementwise clamp. Returns :math:`\mathrm{clamp}(x) = \begin{cases} \mathit{min} & \text{if } x < \mathit{min},\\ \mathit{max} & \text{if } x > \mathit{max},\\ x & \text{otherwise} \end{cases}`. """ min, x, max = core.standard_insert...
Elementwise clamp. Returns :math:`\mathrm{clamp}(x) = \begin{cases} \mathit{min} & \text{if } x < \mathit{min},\\ \mathit{max} & \text{if } x > \mathit{max},\\ x & \text{otherwise} \end{cases}`.
clamp
python
jax-ml/jax
jax/_src/lax/lax.py
https://github.com/jax-ml/jax/blob/master/jax/_src/lax/lax.py
Apache-2.0
def concatenate(operands: Array | Sequence[ArrayLike], dimension: int) -> Array: """Concatenates a sequence of arrays along `dimension`. Wraps XLA's `Concatenate <https://www.tensorflow.org/xla/operation_semantics#concatenate>`_ operator. Args: operands: a sequence of arrays to concatenate. The arrays m...
Concatenates a sequence of arrays along `dimension`. Wraps XLA's `Concatenate <https://www.tensorflow.org/xla/operation_semantics#concatenate>`_ operator. Args: operands: a sequence of arrays to concatenate. The arrays must have equal shapes, except in the `dimension` axis. dimension: the dimens...
concatenate
python
jax-ml/jax
jax/_src/lax/lax.py
https://github.com/jax-ml/jax/blob/master/jax/_src/lax/lax.py
Apache-2.0
def split(operand: ArrayLike, sizes: Sequence[int], axis: int = 0) -> Sequence[Array]: """Splits an array along ``axis``. Args: operand: an array to split sizes: the sizes of the split arrays. The sum of the sizes must be equal to the size of the ``axis`` dimension of ``operand``. axis:...
Splits an array along ``axis``. Args: operand: an array to split sizes: the sizes of the split arrays. The sum of the sizes must be equal to the size of the ``axis`` dimension of ``operand``. axis: the axis along which to split the array. Returns: A sequence of ``len(sizes)`` arrays. If ``si...
split
python
jax-ml/jax
jax/_src/lax/lax.py
https://github.com/jax-ml/jax/blob/master/jax/_src/lax/lax.py
Apache-2.0
def dot(lhs: Array, rhs: Array, precision: PrecisionLike = None, preferred_element_type: DTypeLike | None = None) -> Array: """Vector/vector, matrix/vector, and matrix/matrix multiplication. Wraps XLA's `Dot <https://www.tensorflow.org/xla/operation_semantics#dot>`_ operator. For more general contract...
Vector/vector, matrix/vector, and matrix/matrix multiplication. Wraps XLA's `Dot <https://www.tensorflow.org/xla/operation_semantics#dot>`_ operator. For more general contraction, see the :func:`jax.lax.dot_general` operator. Args: lhs: an array of dimension 1 or 2. rhs: an array of dimension 1 or 2....
dot
python
jax-ml/jax
jax/_src/lax/lax.py
https://github.com/jax-ml/jax/blob/master/jax/_src/lax/lax.py
Apache-2.0
def dot_general(lhs: ArrayLike, rhs: ArrayLike, dimension_numbers: DotDimensionNumbers, precision: PrecisionLike = None, preferred_element_type: DTypeLike | None = None, *, out_sharding=None) -> Array: """General dot product/contraction operator. Wrap...
General dot product/contraction operator. Wraps XLA's `DotGeneral <https://www.tensorflow.org/xla/operation_semantics#dotgeneral>`_ operator. The semantics of ``dot_general`` are complicated, but most users should not have to use it directly. Instead, you can use higher-level functions like :func:`jax.numpy...
dot_general
python
jax-ml/jax
jax/_src/lax/lax.py
https://github.com/jax-ml/jax/blob/master/jax/_src/lax/lax.py
Apache-2.0
def ragged_dot( lhs: Array, rhs: Array, group_sizes: Array, precision: PrecisionLike = None, preferred_element_type: DTypeLike | None = None, group_offset: Array | None = None, ) -> Array: """Ragged matrix multiplication. Args: lhs: (m, k) shaped array. rhs: (g, k, n) shaped arr...
Ragged matrix multiplication. Args: lhs: (m, k) shaped array. rhs: (g, k, n) shaped array. group_sizes: (g,) shaped array with integer element type, where g denotes number of groups. The ith element indicates the size of ith group. precision: Optional. Consistent with precision argument for :func:`...
ragged_dot
python
jax-ml/jax
jax/_src/lax/lax.py
https://github.com/jax-ml/jax/blob/master/jax/_src/lax/lax.py
Apache-2.0
def ragged_dot_general( lhs: Array, rhs: Array, group_sizes: Array, ragged_dot_dimension_numbers: RaggedDotDimensionNumbers, precision: PrecisionLike = None, preferred_element_type: DTypeLike | None = None, group_offset: Array | None = None, ) -> Array: """Ragged matrix multiplication. ...
Ragged matrix multiplication. Ragged dot takes three arrays---``lhs``, ``rhs``, and ``group_sizes``---and a ``ragged_dot_dimension_numbers`` argument. Like `dot_general`, ``lhs`` and ``rhs`` are allowed arbitrary batch and contracting dimensions. Additionally, ``lhs`` is required to have one ragged dimension, ...
ragged_dot_general
python
jax-ml/jax
jax/_src/lax/lax.py
https://github.com/jax-ml/jax/blob/master/jax/_src/lax/lax.py
Apache-2.0
def broadcast(operand: ArrayLike, sizes: Sequence[int], *, out_sharding=None ) -> Array: """Broadcasts an array, adding new leading dimensions Args: operand: an array sizes: a sequence of integers, giving the sizes of new leading dimensions to add to the front of the array. Returns: ...
Broadcasts an array, adding new leading dimensions Args: operand: an array sizes: a sequence of integers, giving the sizes of new leading dimensions to add to the front of the array. Returns: An array containing the result. See Also: jax.lax.broadcast_in_dim : add new dimensions at any lo...
broadcast
python
jax-ml/jax
jax/_src/lax/lax.py
https://github.com/jax-ml/jax/blob/master/jax/_src/lax/lax.py
Apache-2.0
def broadcast_in_dim(operand: ArrayLike, shape: Shape, broadcast_dimensions: Sequence[int], *, out_sharding=None ) -> Array: """Wraps XLA's `BroadcastInDim <https://www.tensorflow.org/xla/operation_semantics#broadcastindim>`_ operator. Args: operand: an array s...
Wraps XLA's `BroadcastInDim <https://www.tensorflow.org/xla/operation_semantics#broadcastindim>`_ operator. Args: operand: an array shape: the shape of the target array broadcast_dimensions: to which dimension in the target shape each dimension of the operand shape corresponds to. That is, dim...
broadcast_in_dim
python
jax-ml/jax
jax/_src/lax/lax.py
https://github.com/jax-ml/jax/blob/master/jax/_src/lax/lax.py
Apache-2.0
def broadcast_to_rank(x: ArrayLike, rank: int) -> Array: """Adds leading dimensions of ``1`` to give ``x`` rank ``rank``.""" ndim = np.ndim(x) if ndim == rank: return asarray(x) return broadcast(x, (1,) * (rank - ndim))
Adds leading dimensions of ``1`` to give ``x`` rank ``rank``.
broadcast_to_rank
python
jax-ml/jax
jax/_src/lax/lax.py
https://github.com/jax-ml/jax/blob/master/jax/_src/lax/lax.py
Apache-2.0
def reshape(operand: ArrayLike, new_sizes: Shape, dimensions: Sequence[int] | None = None, *, out_sharding: NamedSharding | P | None = None) -> Array: """Wraps XLA's `Reshape <https://www.tensorflow.org/xla/operation_semantics#reshape>`_ operator. For inserting/removing dimensions of si...
Wraps XLA's `Reshape <https://www.tensorflow.org/xla/operation_semantics#reshape>`_ operator. For inserting/removing dimensions of size 1, prefer using ``lax.squeeze`` / ``lax.expand_dims``. These preserve information about axis identity that may be useful for advanced transformation rules. Args: oper...
reshape
python
jax-ml/jax
jax/_src/lax/lax.py
https://github.com/jax-ml/jax/blob/master/jax/_src/lax/lax.py
Apache-2.0
def pad(operand: ArrayLike, padding_value: ArrayLike, padding_config: Sequence[tuple[int, int, int]]) -> Array: """Applies low, high, and/or interior padding to an array. Wraps XLA's `Pad <https://www.tensorflow.org/xla/operation_semantics#pad>`_ operator. Args: operand: an array to be padded. ...
Applies low, high, and/or interior padding to an array. Wraps XLA's `Pad <https://www.tensorflow.org/xla/operation_semantics#pad>`_ operator. Args: operand: an array to be padded. padding_value: the value to be inserted as padding. Must have the same dtype as ``operand``. padding_config: a s...
pad
python
jax-ml/jax
jax/_src/lax/lax.py
https://github.com/jax-ml/jax/blob/master/jax/_src/lax/lax.py
Apache-2.0
def select(pred: ArrayLike, on_true: ArrayLike, on_false: ArrayLike) -> Array: """Selects between two branches based on a boolean predicate. Wraps XLA's `Select <https://www.tensorflow.org/xla/operation_semantics#select>`_ operator. In general :func:`~jax.lax.select` leads to evaluation of both branches, al...
Selects between two branches based on a boolean predicate. Wraps XLA's `Select <https://www.tensorflow.org/xla/operation_semantics#select>`_ operator. In general :func:`~jax.lax.select` leads to evaluation of both branches, although the compiler may elide computations if possible. For a similar function tha...
select
python
jax-ml/jax
jax/_src/lax/lax.py
https://github.com/jax-ml/jax/blob/master/jax/_src/lax/lax.py
Apache-2.0
def select_n(which: ArrayLike, *cases: ArrayLike) -> Array: """Selects array values from multiple cases. Generalizes XLA's `Select <https://www.tensorflow.org/xla/operation_semantics#select>`_ operator. Unlike XLA's version, the operator is variadic and can select from many cases using an integer `pred`. ...
Selects array values from multiple cases. Generalizes XLA's `Select <https://www.tensorflow.org/xla/operation_semantics#select>`_ operator. Unlike XLA's version, the operator is variadic and can select from many cases using an integer `pred`. Args: which: determines which case should be returned. Must b...
select_n
python
jax-ml/jax
jax/_src/lax/lax.py
https://github.com/jax-ml/jax/blob/master/jax/_src/lax/lax.py
Apache-2.0
def transpose(operand: ArrayLike, permutation: Sequence[int] | np.ndarray) -> Array: """Wraps XLA's `Transpose <https://www.tensorflow.org/xla/operation_semantics#transpose>`_ operator. """ permutation = tuple(operator.index(d) for d in permutation) if permutation == tuple(range(np.ndim(operan...
Wraps XLA's `Transpose <https://www.tensorflow.org/xla/operation_semantics#transpose>`_ operator.
transpose
python
jax-ml/jax
jax/_src/lax/lax.py
https://github.com/jax-ml/jax/blob/master/jax/_src/lax/lax.py
Apache-2.0
def argmin(operand: ArrayLike, axis: int, index_dtype: DTypeLike) -> Array: """Computes the index of the minimum element along ``axis``.""" return argmin_p.bind(operand, axes=(axis,), index_dtype=dtypes.canonicalize_dtype(index_dtype))
Computes the index of the minimum element along ``axis``.
argmin
python
jax-ml/jax
jax/_src/lax/lax.py
https://github.com/jax-ml/jax/blob/master/jax/_src/lax/lax.py
Apache-2.0
def argmax(operand: ArrayLike, axis: int, index_dtype: DTypeLike) -> Array: """Computes the index of the maximum element along ``axis``.""" return argmax_p.bind(operand, axes=(axis,), index_dtype=dtypes.canonicalize_dtype(index_dtype))
Computes the index of the maximum element along ``axis``.
argmax
python
jax-ml/jax
jax/_src/lax/lax.py
https://github.com/jax-ml/jax/blob/master/jax/_src/lax/lax.py
Apache-2.0
def reduce(operands: Any, init_values: Any, computation: Callable[[Any, Any], Any], dimensions: Sequence[int]) -> Any: """Wraps XLA's `Reduce <https://www.tensorflow.org/xla/operation_semantics#reduce>`_ operator. ``init_values`` and ``computation`` together must form a `monoid...
Wraps XLA's `Reduce <https://www.tensorflow.org/xla/operation_semantics#reduce>`_ operator. ``init_values`` and ``computation`` together must form a `monoid <https://en.wikipedia.org/wiki/Monoid>`_ for correctness. That is ``init_values`` must be an identity of ``computation``, and ``computation`` must be ...
reduce
python
jax-ml/jax
jax/_src/lax/lax.py
https://github.com/jax-ml/jax/blob/master/jax/_src/lax/lax.py
Apache-2.0
def sort(operand: Array | Sequence[Array], dimension: int = -1, is_stable: bool = True, num_keys: int = 1) -> Array | tuple[Array, ...]: """Wraps XLA's `Sort <https://www.tensorflow.org/xla/operation_semantics#sort>`_ operator. For floating point inputs, -0.0 and 0.0 are treated as equivalent, and NaN v...
Wraps XLA's `Sort <https://www.tensorflow.org/xla/operation_semantics#sort>`_ operator. For floating point inputs, -0.0 and 0.0 are treated as equivalent, and NaN values are sorted to the end of the array. For complex inputs, the sort order is lexicographic over the real and imaginary parts, with the real part...
sort
python
jax-ml/jax
jax/_src/lax/lax.py
https://github.com/jax-ml/jax/blob/master/jax/_src/lax/lax.py
Apache-2.0
def sort_key_val(keys: Array, values: ArrayLike, dimension: int = -1, is_stable: bool = True) -> tuple[Array, Array]: """Sorts ``keys`` along ``dimension`` and applies the same permutation to ``values``.""" dimension = canonicalize_axis(dimension, len(keys.shape)) k, v = sort_p.bind(keys, values,...
Sorts ``keys`` along ``dimension`` and applies the same permutation to ``values``.
sort_key_val
python
jax-ml/jax
jax/_src/lax/lax.py
https://github.com/jax-ml/jax/blob/master/jax/_src/lax/lax.py
Apache-2.0
def top_k(operand: ArrayLike, k: int) -> tuple[Array, Array]: """Returns top ``k`` values and their indices along the last axis of ``operand``. Args: operand: N-dimensional array of non-complex type. k: integer specifying the number of top entries. Returns: A tuple ``(values, indices)`` where -...
Returns top ``k`` values and their indices along the last axis of ``operand``. Args: operand: N-dimensional array of non-complex type. k: integer specifying the number of top entries. Returns: A tuple ``(values, indices)`` where - ``values`` is an array containing the top k values along the last ...
top_k
python
jax-ml/jax
jax/_src/lax/lax.py
https://github.com/jax-ml/jax/blob/master/jax/_src/lax/lax.py
Apache-2.0
def full(shape: Shape, fill_value: ArrayLike, dtype: DTypeLike | None = None, *, sharding: Sharding | None = None) -> Array: """Returns an array of `shape` filled with `fill_value`. Args: shape: sequence of integers, describing the shape of the output array. fill_value: the value to fill the new a...
Returns an array of `shape` filled with `fill_value`. Args: shape: sequence of integers, describing the shape of the output array. fill_value: the value to fill the new array with. dtype: the type of the output array, or `None`. If not `None`, `fill_value` will be cast to `dtype`. sharding: an ...
full
python
jax-ml/jax
jax/_src/lax/lax.py
https://github.com/jax-ml/jax/blob/master/jax/_src/lax/lax.py
Apache-2.0
def _eye(dtype: DTypeLike, shape: Shape, offset: DimSize = 0) -> Array: """Like numpy.eye, create a 2D array with ones on a diagonal.""" offset = _clip_int_to_valid_range(offset, np.int32, "argument `offset` of jax.numpy.eye") dtype = dtypes.canonicalize_dtype(dtype) bool_eye...
Like numpy.eye, create a 2D array with ones on a diagonal.
_eye
python
jax-ml/jax
jax/_src/lax/lax.py
https://github.com/jax-ml/jax/blob/master/jax/_src/lax/lax.py
Apache-2.0
def _delta(dtype: DTypeLike, shape: Shape, axes: Sequence[int]) -> Array: """This utility function exists for creating Kronecker delta arrays.""" axes = map(int, axes) dtype = dtypes.canonicalize_dtype(dtype) base_shape = tuple(np.take(shape, axes)) iotas = [broadcasted_iota(np.uint32, base_shape, i) ...
This utility function exists for creating Kronecker delta arrays.
_delta
python
jax-ml/jax
jax/_src/lax/lax.py
https://github.com/jax-ml/jax/blob/master/jax/_src/lax/lax.py
Apache-2.0
def _tri(dtype: DTypeLike, shape: Shape, offset: DimSize) -> Array: """Like numpy.tri, create a 2D array with ones below a diagonal.""" offset = _clip_int_to_valid_range(offset, np.int32, "argument `offset` of jax.numpy.tri") dtype = dtypes.canonicalize_dtype(dtype) bool_tri ...
Like numpy.tri, create a 2D array with ones below a diagonal.
_tri
python
jax-ml/jax
jax/_src/lax/lax.py
https://github.com/jax-ml/jax/blob/master/jax/_src/lax/lax.py
Apache-2.0
def stop_gradient(x: T) -> T: """Stops gradient computation. Operationally ``stop_gradient`` is the identity function, that is, it returns argument `x` unchanged. However, ``stop_gradient`` prevents the flow of gradients during forward or reverse-mode automatic differentiation. If there are multiple nested g...
Stops gradient computation. Operationally ``stop_gradient`` is the identity function, that is, it returns argument `x` unchanged. However, ``stop_gradient`` prevents the flow of gradients during forward or reverse-mode automatic differentiation. If there are multiple nested gradient computations, ``stop_gradie...
stop_gradient
python
jax-ml/jax
jax/_src/lax/lax.py
https://github.com/jax-ml/jax/blob/master/jax/_src/lax/lax.py
Apache-2.0
def reduce_precision(operand: float | ArrayLike, exponent_bits: int, mantissa_bits: int) -> Array: """Wraps XLA's `ReducePrecision <https://www.tensorflow.org/xla/operation_semantics#reduceprecision>`_ operator. """ exponent_bits = core.concrete_or_error( operator...
Wraps XLA's `ReducePrecision <https://www.tensorflow.org/xla/operation_semantics#reduceprecision>`_ operator.
reduce_precision
python
jax-ml/jax
jax/_src/lax/lax.py
https://github.com/jax-ml/jax/blob/master/jax/_src/lax/lax.py
Apache-2.0
def squeeze(array: ArrayLike, dimensions: Sequence[int]) -> Array: """Squeeze any number of size 1 dimensions from an array.""" ndim = np.ndim(array) dimensions = tuple(sorted(canonicalize_axis(i, ndim) for i in dimensions)) if not dimensions and isinstance(array, Array): return array return squeeze_p.bin...
Squeeze any number of size 1 dimensions from an array.
squeeze
python
jax-ml/jax
jax/_src/lax/lax.py
https://github.com/jax-ml/jax/blob/master/jax/_src/lax/lax.py
Apache-2.0
def expand_dims(array: ArrayLike, dimensions: Sequence[int]) -> Array: """Insert any number of size 1 dimensions into an array.""" if len(set(dimensions)) != len(dimensions): raise ValueError(f'repeated axis in lax.expand_dims: {dimensions}') ndim_out = np.ndim(array) + len(dimensions) dims = [canonicalize_...
Insert any number of size 1 dimensions into an array.
expand_dims
python
jax-ml/jax
jax/_src/lax/lax.py
https://github.com/jax-ml/jax/blob/master/jax/_src/lax/lax.py
Apache-2.0
def collapse(operand: Array, start_dimension: int, stop_dimension: int | None = None) -> Array: """Collapses dimensions of an array into a single dimension. For example, if ``operand`` is an array with shape ``[2, 3, 4]``, ``collapse(operand, 0, 2).shape == [6, 4]``. The elements of the collapsed ...
Collapses dimensions of an array into a single dimension. For example, if ``operand`` is an array with shape ``[2, 3, 4]``, ``collapse(operand, 0, 2).shape == [6, 4]``. The elements of the collapsed dimension are laid out major-to-minor, i.e., with the lowest-numbered dimension as the slowest varying dimension...
collapse
python
jax-ml/jax
jax/_src/lax/lax.py
https://github.com/jax-ml/jax/blob/master/jax/_src/lax/lax.py
Apache-2.0
def broadcast_hlo( aval_out: core.ShapedArray, avals: Sequence[core.ShapedArray], args: Sequence[ir.Value]) -> Sequence[ir.Value]: """Broadcasts HLO values with broadcast-compatible shapes to the same shape. """ out = [] for aval, arg in zip(avals, args): if aval.shape != aval_out.shape: asser...
Broadcasts HLO values with broadcast-compatible shapes to the same shape.
broadcast_hlo
python
jax-ml/jax
jax/_src/lax/lax.py
https://github.com/jax-ml/jax/blob/master/jax/_src/lax/lax.py
Apache-2.0
def _nary_lower_hlo( op: Callable, ctx, *args: ir.Value, accuracy=None, **params ) -> Sequence[ir.Value]: """Lowers an elementwise operator to its MLIR equivalent. """ del params avals_in, (aval_out,) = ctx.avals_in, ctx.avals_out args = mlir.multi_broadcast_in_dim(ctx, args, avals_in, aval_out.shape) a...
Lowers an elementwise operator to its MLIR equivalent.
_nary_lower_hlo
python
jax-ml/jax
jax/_src/lax/lax.py
https://github.com/jax-ml/jax/blob/master/jax/_src/lax/lax.py
Apache-2.0
def shape_as_value(shape: core.Shape): """Converts a shape that may contain Poly values into a JAX value.""" if len(shape) == 0: return full((0,), np.array(0, np.int64)) if core.is_constant_shape(shape): return np.asarray(shape, dtype=np.int64) dims = [ expand_dims(convert_element_type(core.dimens...
Converts a shape that may contain Poly values into a JAX value.
shape_as_value
python
jax-ml/jax
jax/_src/lax/lax.py
https://github.com/jax-ml/jax/blob/master/jax/_src/lax/lax.py
Apache-2.0
def _reduce_tree(*xs, axis=0): """Reduce by repeatedly splitting the array and multiplying.""" while xs[0].shape[axis] > 1: n = xs[0].shape[axis] n1 = (n + 1) // 2 n2 = n - n1 xs1 = [slicing.slice_in_dim(x, 0, n1) for x in xs] xs2 = [slicing.slice_in_dim(x, n1, None) for x in xs] ...
Reduce by repeatedly splitting the array and multiplying.
_reduce_tree
python
jax-ml/jax
jax/_src/lax/lax.py
https://github.com/jax-ml/jax/blob/master/jax/_src/lax/lax.py
Apache-2.0
def infeed(token, shape=None, partitions=None): """Consumes an infeed value of `shape` from the host. Experimental. `token` is used to sequence infeed and outfeed effects. `partitions` may be specified inside a `sharded_jit` function. """ flat_shapes, treedef = tree_util.tree_flatten(shape) for shape in fl...
Consumes an infeed value of `shape` from the host. Experimental. `token` is used to sequence infeed and outfeed effects. `partitions` may be specified inside a `sharded_jit` function.
infeed
python
jax-ml/jax
jax/_src/lax/lax.py
https://github.com/jax-ml/jax/blob/master/jax/_src/lax/lax.py
Apache-2.0
def outfeed(token, xs, partitions = None): """Outfeeds value `xs` to the host. Experimental. `token` is used to sequence infeed and outfeed effects. `partitions` may be specified inside a `sharded_jit` or `pjit` function. """ if partitions is not None: # We specifically use type() to raise an error for P...
Outfeeds value `xs` to the host. Experimental. `token` is used to sequence infeed and outfeed effects. `partitions` may be specified inside a `sharded_jit` or `pjit` function.
outfeed
python
jax-ml/jax
jax/_src/lax/lax.py
https://github.com/jax-ml/jax/blob/master/jax/_src/lax/lax.py
Apache-2.0
def rng_uniform(a, b, shape): """Stateful PRNG generator. Experimental and its use is discouraged. Returns uniformly distributed random numbers in the range [a, b). If b <= a, then the result is undefined, and different implementations may return different results. You should use jax.random for most purpose...
Stateful PRNG generator. Experimental and its use is discouraged. Returns uniformly distributed random numbers in the range [a, b). If b <= a, then the result is undefined, and different implementations may return different results. You should use jax.random for most purposes; this function exists only for ...
rng_uniform
python
jax-ml/jax
jax/_src/lax/lax.py
https://github.com/jax-ml/jax/blob/master/jax/_src/lax/lax.py
Apache-2.0
def _dilate_shape(shape, dilation): """Utility function for computing the shape resulting from a dilation.""" if not np.all(np.greater(dilation, 0)): msg = "All dilations must be positive, got {}." raise TypeError(msg.format(dilation)) dilation = (1,) * (len(shape) - len(dilation)) + tuple(dilation) ret...
Utility function for computing the shape resulting from a dilation.
_dilate_shape
python
jax-ml/jax
jax/_src/lax/lax.py
https://github.com/jax-ml/jax/blob/master/jax/_src/lax/lax.py
Apache-2.0
def padtype_to_pads(in_shape, window_shape, window_strides, padding): """Convert padding string to list of pairs of pad values.""" if isinstance(padding, str): mapping = { 'VALID': PaddingType.VALID, 'SAME': PaddingType.SAME, 'SAME_LOWER': PaddingType.SAME_LOWER, } try: pa...
Convert padding string to list of pairs of pad values.
padtype_to_pads
python
jax-ml/jax
jax/_src/lax/lax.py
https://github.com/jax-ml/jax/blob/master/jax/_src/lax/lax.py
Apache-2.0
def check_same_dtypes(name: str, *avals: core.UnshapedArray) -> None: """Check that dtypes agree, possibly ignoring float precision.""" # the `ignore_fp_precision` flag exists because the XLA shape inference logic # allows mixed floating point precision, but the HLO verifier often rejects it if any(dtypes.issub...
Check that dtypes agree, possibly ignoring float precision.
check_same_dtypes
python
jax-ml/jax
jax/_src/lax/lax.py
https://github.com/jax-ml/jax/blob/master/jax/_src/lax/lax.py
Apache-2.0
def _check_shapelike(fun_name, arg_name, obj, non_zero_shape=False): """Check that `obj` is a shape-like value (e.g. tuple of nonnegative ints).""" if not isinstance(obj, (tuple, list, np.ndarray)): msg = "{} {} must be of type tuple/list/ndarray, got {}." raise TypeError(msg.format(fun_name, arg_name, type...
Check that `obj` is a shape-like value (e.g. tuple of nonnegative ints).
_check_shapelike
python
jax-ml/jax
jax/_src/lax/lax.py
https://github.com/jax-ml/jax/blob/master/jax/_src/lax/lax.py
Apache-2.0
def canonicalize_precision(precision: PrecisionLike) -> CanonicalPrecision: """Turns an API precision specification into a pair of enumeration values. The API can take the precision as a string, or int, and either as a single value to apply to both operands, or as a sequence of two values. """ if precision i...
Turns an API precision specification into a pair of enumeration values. The API can take the precision as a string, or int, and either as a single value to apply to both operands, or as a sequence of two values.
canonicalize_precision
python
jax-ml/jax
jax/_src/lax/lax.py
https://github.com/jax-ml/jax/blob/master/jax/_src/lax/lax.py
Apache-2.0
def optimization_barrier(operand, /): """Prevents the compiler from moving operations across the barrier. Optimization barriers have a number of possible uses: * An optimization barrier ensures that all inputs are evaluated before any operators that depend on the barrier's outputs. This can be used to enfor...
Prevents the compiler from moving operations across the barrier. Optimization barriers have a number of possible uses: * An optimization barrier ensures that all inputs are evaluated before any operators that depend on the barrier's outputs. This can be used to enforce a particular order of operations. ...
optimization_barrier
python
jax-ml/jax
jax/_src/lax/lax.py
https://github.com/jax-ml/jax/blob/master/jax/_src/lax/lax.py
Apache-2.0
def cholesky_update(r_matrix: ArrayLike, w_vector: ArrayLike) -> Array: r"""Cholesky rank-1 update. Given a Cholesky decomposition :math:`A = R.T \, R` and a vector :math:`w`, computes the Cholesky decomposition of :math:`A + w \, w.T` in :math:`O(N^2)` time. Args: r_matrix: An upper-triangular matrix (...
Cholesky rank-1 update. Given a Cholesky decomposition :math:`A = R.T \, R` and a vector :math:`w`, computes the Cholesky decomposition of :math:`A + w \, w.T` in :math:`O(N^2)` time. Args: r_matrix: An upper-triangular matrix (R) such that :math:`A = R^T \, R`. w_vector: A vector :math:`w` for rank-1...
cholesky_update
python
jax-ml/jax
jax/_src/lax/linalg.py
https://github.com/jax-ml/jax/blob/master/jax/_src/lax/linalg.py
Apache-2.0
def eig( x: ArrayLike, *, compute_left_eigenvectors: bool = True, compute_right_eigenvectors: bool = True, use_magma: bool | None = None, ) -> list[Array]: """Eigendecomposition of a general matrix. Nonsymmetric eigendecomposition is only implemented on CPU and GPU. On GPU, the default implem...
Eigendecomposition of a general matrix. Nonsymmetric eigendecomposition is only implemented on CPU and GPU. On GPU, the default implementation calls LAPACK directly on the host CPU, but an experimental GPU implementation using `MAGMA <https://icl.utk.edu/magma/>`_ is also available. The MAGMA implementation is...
eig
python
jax-ml/jax
jax/_src/lax/linalg.py
https://github.com/jax-ml/jax/blob/master/jax/_src/lax/linalg.py
Apache-2.0
def householder_product(a: ArrayLike, taus: ArrayLike) -> Array: """Product of elementary Householder reflectors. Args: a: A matrix with shape ``[..., m, n]``, whose lower triangle contains elementary Householder reflectors. taus: A vector with shape ``[..., k]``, where ``k < min(m, n)``, containing ...
Product of elementary Householder reflectors. Args: a: A matrix with shape ``[..., m, n]``, whose lower triangle contains elementary Householder reflectors. taus: A vector with shape ``[..., k]``, where ``k < min(m, n)``, containing the scalar factors of the elementary Householder reflectors. ...
householder_product
python
jax-ml/jax
jax/_src/lax/linalg.py
https://github.com/jax-ml/jax/blob/master/jax/_src/lax/linalg.py
Apache-2.0
def schur( x: ArrayLike, *, compute_schur_vectors: bool = True, sort_eig_vals: bool = False, select_callable: Callable[..., Any] | None = None, ) -> tuple[Array, Array]: r"""Schur decomposition. Only implemented on CPU. Computes the Schur decomposition: .. math:: A = Q \, U \, Q^{-H} ...
Schur decomposition. Only implemented on CPU. Computes the Schur decomposition: .. math:: A = Q \, U \, Q^{-H} for a square matrix :math:`A`. Args: x: A batch of square matrices with shape ``[..., m, m]``. compute_schur_vectors: If ``True``, compute the Schur vectors ::math:`Q`, otherwi...
schur
python
jax-ml/jax
jax/_src/lax/linalg.py
https://github.com/jax-ml/jax/blob/master/jax/_src/lax/linalg.py
Apache-2.0
def svd( x: ArrayLike, *, full_matrices: bool = True, compute_uv: bool = True, subset_by_index: tuple[int, int] | None = None, algorithm: SvdAlgorithm | None = None, ) -> Array | tuple[Array, Array, Array]: """Singular value decomposition. Computes the singular value decomposition of an inp...
Singular value decomposition. Computes the singular value decomposition of an input matrix. Args: x: A batch of matrices with shape ``[..., m, n]``. full_matrices: Determines if full or reduced matrices are returned. compute_uv: If ``True``, returns the left singular vectors, the singular values...
svd
python
jax-ml/jax
jax/_src/lax/linalg.py
https://github.com/jax-ml/jax/blob/master/jax/_src/lax/linalg.py
Apache-2.0
def symmetric_product( a_matrix: ArrayLike, c_matrix: ArrayLike, *, alpha: float = 1., beta: float = 0., symmetrize_output: bool = False ): r"""Symmetric product. Computes the symmetric product .. math:: \alpha \, A \, A^T + \beta \, C where :math:`A` is a rectangular matrix and :...
Symmetric product. Computes the symmetric product .. math:: \alpha \, A \, A^T + \beta \, C where :math:`A` is a rectangular matrix and :math:`C` is a symmetric matrix. Args: a_matrix: A batch of matrices with shape ``[..., m, n]``. c_matrix: A batch of matrices with shape ``[..., m, m]``. a...
symmetric_product
python
jax-ml/jax
jax/_src/lax/linalg.py
https://github.com/jax-ml/jax/blob/master/jax/_src/lax/linalg.py
Apache-2.0
def triangular_solve( a: ArrayLike, b: ArrayLike, *, left_side: bool = False, lower: bool = False, transpose_a: bool = False, conjugate_a: bool = False, unit_diagonal: bool = False, ) -> Array: r"""Triangular solve. Solves either the matrix equation .. math:: \mathit{op}(A) ....
Triangular solve. Solves either the matrix equation .. math:: \mathit{op}(A) . X = B if ``left_side`` is ``True`` or .. math:: X . \mathit{op}(A) = B if ``left_side`` is ``False``. ``A`` must be a lower or upper triangular square matrix, and where :math:`\mathit{op}(A)` may either transpose ...
triangular_solve
python
jax-ml/jax
jax/_src/lax/linalg.py
https://github.com/jax-ml/jax/blob/master/jax/_src/lax/linalg.py
Apache-2.0
def tridiagonal_solve(dl: Array, d: Array, du: Array, b: Array) -> Array: r"""Computes the solution of a tridiagonal linear system. This function computes the solution of a tridiagonal linear system: .. math:: A \, X = B Args: dl: A batch of vectors with shape ``[..., m]``. The lower diagonal ...
Computes the solution of a tridiagonal linear system. This function computes the solution of a tridiagonal linear system: .. math:: A \, X = B Args: dl: A batch of vectors with shape ``[..., m]``. The lower diagonal of A: ``dl[i] := A[i, i-1]`` for i in ``[0,m)``. Note that ``dl[0] = 0``. ...
tridiagonal_solve
python
jax-ml/jax
jax/_src/lax/linalg.py
https://github.com/jax-ml/jax/blob/master/jax/_src/lax/linalg.py
Apache-2.0
def _drotg(x, y): """Get coefs for Givens rotation in a numerically stable way.""" def _drotg_nonzero(x, y): abs_x = abs(x) abs_y = abs(y) denominator = lax.select(abs_x > abs_y, abs_x, abs_y) x /= denominator y /= denominator rh = 1 / lax.sqrt(x ** 2 + y ** 2) return x...
Get coefs for Givens rotation in a numerically stable way.
_drotg
python
jax-ml/jax
jax/_src/lax/linalg.py
https://github.com/jax-ml/jax/blob/master/jax/_src/lax/linalg.py
Apache-2.0
def eigh_jacobi(x: ArrayLike, *, lower: bool = True, sort_eigenvalues: bool = True) -> tuple[Array, Array]: """Helper Jacobi eigendecomposition implemented by XLA. Used as a subroutine of QDWH-eig on TPU. """ return eigh_jacobi_p.bind(x, lower=lower, sort_eigenvalues=sort_eigenvalues)
Helper Jacobi eigendecomposition implemented by XLA. Used as a subroutine of QDWH-eig on TPU.
eigh_jacobi
python
jax-ml/jax
jax/_src/lax/linalg.py
https://github.com/jax-ml/jax/blob/master/jax/_src/lax/linalg.py
Apache-2.0
def _lu_unblocked(a): """Unblocked LU decomposition, as a rolled loop.""" m, n = a.shape def body(k, state): pivot, perm, a = state m_idx = lax.iota('int32', m) n_idx = lax.iota('int32', n) if dtypes.issubdtype(a.dtype, np.complexfloating): t = a[:, k] magnitude = abs(t.real) + abs(t....
Unblocked LU decomposition, as a rolled loop.
_lu_unblocked
python
jax-ml/jax
jax/_src/lax/linalg.py
https://github.com/jax-ml/jax/blob/master/jax/_src/lax/linalg.py
Apache-2.0
def _lu_blocked(a, block_size=128): """Blocked LU decomposition, as an unrolled loop.""" m, n = a.shape r = min(m, n) pivot = lax.full((r,), 0, dtype=np.int32) perm = lax.iota('int32', m) for k in range(0, r, block_size): b = min(r - k, block_size) block_pivot, block_perm, lu_block = _lu_unblocked(a...
Blocked LU decomposition, as an unrolled loop.
_lu_blocked
python
jax-ml/jax
jax/_src/lax/linalg.py
https://github.com/jax-ml/jax/blob/master/jax/_src/lax/linalg.py
Apache-2.0
def _lu_python(x): """Default LU decomposition in Python, where no better version exists.""" batch_dims = x.shape[:-2] fn = _lu_blocked for _ in range(len(batch_dims)): fn = api.vmap(fn) return fn(x)
Default LU decomposition in Python, where no better version exists.
_lu_python
python
jax-ml/jax
jax/_src/lax/linalg.py
https://github.com/jax-ml/jax/blob/master/jax/_src/lax/linalg.py
Apache-2.0
def _generic_lu_pivots_to_permutation(swaps, permutation_size): """Converts the pivots (row swaps) returned by LU to a permutation. We build a permutation rather than applying `swaps` directly to the rows of a matrix because lax loops aren't differentiable. Args: swaps: an array of shape (..., k) of row s...
Converts the pivots (row swaps) returned by LU to a permutation. We build a permutation rather than applying `swaps` directly to the rows of a matrix because lax loops aren't differentiable. Args: swaps: an array of shape (..., k) of row swaps to perform permutation_size: the size of the output permutat...
_generic_lu_pivots_to_permutation
python
jax-ml/jax
jax/_src/lax/linalg.py
https://github.com/jax-ml/jax/blob/master/jax/_src/lax/linalg.py
Apache-2.0
def geqrf(a: ArrayLike) -> tuple[Array, Array]: """Computes the QR decomposition of a matrix. Args: a: an ``[..., m, n]`` batch of matrices, with floating-point or complex type. Returns: An ``(a, taus)`` pair where ``r`` is in the upper triangle of ``a``, ``q`` is represented in the lower triangle of...
Computes the QR decomposition of a matrix. Args: a: an ``[..., m, n]`` batch of matrices, with floating-point or complex type. Returns: An ``(a, taus)`` pair where ``r`` is in the upper triangle of ``a``, ``q`` is represented in the lower triangle of ``a`` and in ``taus`` as elementary Householder ...
geqrf
python
jax-ml/jax
jax/_src/lax/linalg.py
https://github.com/jax-ml/jax/blob/master/jax/_src/lax/linalg.py
Apache-2.0
def geqp3(a: ArrayLike, jpvt: ArrayLike, *, use_magma: bool | None = None) -> tuple[Array, Array, Array]: """Computes the column-pivoted QR decomposition of a matrix. Args: a: a ``[..., m, n]`` batch of matrices, with floating-point or complex type. jpvt: a ``[..., n]`` batch of column-pivot inde...
Computes the column-pivoted QR decomposition of a matrix. Args: a: a ``[..., m, n]`` batch of matrices, with floating-point or complex type. jpvt: a ``[..., n]`` batch of column-pivot index vectors with integer type, use_magma: Locally override the ``jax_use_magma`` flag. If ``True``, the `geqp3` i...
geqp3
python
jax-ml/jax
jax/_src/lax/linalg.py
https://github.com/jax-ml/jax/blob/master/jax/_src/lax/linalg.py
Apache-2.0
def _extract_diagonal(s: Array) -> Array: """Extract the diagonal from a batched matrix""" i = lax.iota('int32', min(s.shape[-2], s.shape[-1])) return s[..., i, i]
Extract the diagonal from a batched matrix
_extract_diagonal
python
jax-ml/jax
jax/_src/lax/linalg.py
https://github.com/jax-ml/jax/blob/master/jax/_src/lax/linalg.py
Apache-2.0
def _broadcasting_select_hlo(ctx, which, which_aval, x, x_aval, y, y_aval) -> ir.Value: """Wrapper around XLA `Select` that broadcasts its arguments.""" out_shapes = list(lax_internal.broadcast_shapes( tuple(which_aval.shape), tuple(x_aval.shape), tuple(y_aval.shape))) which, x, y = mlir.multi_broadcast_in_...
Wrapper around XLA `Select` that broadcasts its arguments.
_broadcasting_select_hlo
python
jax-ml/jax
jax/_src/lax/linalg.py
https://github.com/jax-ml/jax/blob/master/jax/_src/lax/linalg.py
Apache-2.0
def conv_general_dilated_patches( lhs: ArrayLike, filter_shape: Sequence[int], window_strides: Sequence[int], padding: str | Sequence[tuple[int, int]], lhs_dilation: Sequence[int] | None = None, rhs_dilation: Sequence[int] | None = None, dimension_numbers: convolution.ConvGeneralDilatedDimen...
Extract patches subject to the receptive field of `conv_general_dilated`. Runs the input through a convolution with given parameters. The kernel of the convolution is constructed such that the output channel dimension `"C"` contains flattened image patches, so instead a single `"C"` dimension represents, for e...
conv_general_dilated_patches
python
jax-ml/jax
jax/_src/lax/other.py
https://github.com/jax-ml/jax/blob/master/jax/_src/lax/other.py
Apache-2.0
def conv_general_dilated_local( lhs: ArrayLike, rhs: ArrayLike, window_strides: Sequence[int], padding: str | Sequence[tuple[int, int]], filter_shape: Sequence[int], lhs_dilation: Sequence[int] | None = None, rhs_dilation: Sequence[int] | None = None, dimension_numbers: convolution.ConvG...
General n-dimensional unshared convolution operator with optional dilation. Also known as locally connected layer, the operation is equivalent to convolution with a separate (unshared) `rhs` kernel used at each output spatial location. Docstring below adapted from `jax.lax.conv_general_dilated`. See Also: ...
conv_general_dilated_local
python
jax-ml/jax
jax/_src/lax/other.py
https://github.com/jax-ml/jax/blob/master/jax/_src/lax/other.py
Apache-2.0
def logaddexp(x1: ArrayLike, x2: ArrayLike, /) -> Array: """Compute log(exp(x1) + exp(x2)) avoiding overflow.""" x1_arr = lax.asarray(x1) x2_arr = lax.asarray(x2) assert x1_arr.dtype == x2_arr.dtype amax = lax.max(x1_arr, x2_arr) if dtypes.isdtype(x1_arr.dtype, "real floating"): delta = lax.sub(x1_arr,...
Compute log(exp(x1) + exp(x2)) avoiding overflow.
logaddexp
python
jax-ml/jax
jax/_src/lax/other.py
https://github.com/jax-ml/jax/blob/master/jax/_src/lax/other.py
Apache-2.0
def psum(x, axis_name, *, axis_index_groups=None): """Compute an all-reduce sum on ``x`` over the pmapped axis ``axis_name``. If ``x`` is a pytree then the result is equivalent to mapping this function to each leaf in the tree. Inputs of boolean dtype are converted to integers before the reduction. Args: ...
Compute an all-reduce sum on ``x`` over the pmapped axis ``axis_name``. If ``x`` is a pytree then the result is equivalent to mapping this function to each leaf in the tree. Inputs of boolean dtype are converted to integers before the reduction. Args: x: array(s) with a mapped axis named ``axis_name``. ...
psum
python
jax-ml/jax
jax/_src/lax/parallel.py
https://github.com/jax-ml/jax/blob/master/jax/_src/lax/parallel.py
Apache-2.0
def pmean(x, axis_name, *, axis_index_groups=None): """Compute an all-reduce mean on ``x`` over the pmapped axis ``axis_name``. If ``x`` is a pytree then the result is equivalent to mapping this function to each leaf in the tree. Args: x: array(s) with a mapped axis named ``axis_name``. axis_name: has...
Compute an all-reduce mean on ``x`` over the pmapped axis ``axis_name``. If ``x`` is a pytree then the result is equivalent to mapping this function to each leaf in the tree. Args: x: array(s) with a mapped axis named ``axis_name``. axis_name: hashable Python object used to name a pmapped axis (see the ...
pmean
python
jax-ml/jax
jax/_src/lax/parallel.py
https://github.com/jax-ml/jax/blob/master/jax/_src/lax/parallel.py
Apache-2.0
def pmax(x, axis_name, *, axis_index_groups=None): """Compute an all-reduce max on ``x`` over the pmapped axis ``axis_name``. If ``x`` is a pytree then the result is equivalent to mapping this function to each leaf in the tree. Args: x: array(s) with a mapped axis named ``axis_name``. axis_name: hasha...
Compute an all-reduce max on ``x`` over the pmapped axis ``axis_name``. If ``x`` is a pytree then the result is equivalent to mapping this function to each leaf in the tree. Args: x: array(s) with a mapped axis named ``axis_name``. axis_name: hashable Python object used to name a pmapped axis (see the ...
pmax
python
jax-ml/jax
jax/_src/lax/parallel.py
https://github.com/jax-ml/jax/blob/master/jax/_src/lax/parallel.py
Apache-2.0
def pmin(x, axis_name, *, axis_index_groups=None): """Compute an all-reduce min on ``x`` over the pmapped axis ``axis_name``. If ``x`` is a pytree then the result is equivalent to mapping this function to each leaf in the tree. Args: x: array(s) with a mapped axis named ``axis_name``. axis_name: hasha...
Compute an all-reduce min on ``x`` over the pmapped axis ``axis_name``. If ``x`` is a pytree then the result is equivalent to mapping this function to each leaf in the tree. Args: x: array(s) with a mapped axis named ``axis_name``. axis_name: hashable Python object used to name a pmapped axis (see the ...
pmin
python
jax-ml/jax
jax/_src/lax/parallel.py
https://github.com/jax-ml/jax/blob/master/jax/_src/lax/parallel.py
Apache-2.0
def pbroadcast(x, axis_name, source): """Perform a collective broadcast and replicate from ``source``. This is equivalent to ``` def pbroadcast(x, axis_name, source): masked = jnp.where(axis_index(axis_name) == source, x, zeros_like(x)) return psum(masked, axis_name) ``` but implemented in a hardwa...
Perform a collective broadcast and replicate from ``source``. This is equivalent to ``` def pbroadcast(x, axis_name, source): masked = jnp.where(axis_index(axis_name) == source, x, zeros_like(x)) return psum(masked, axis_name) ``` but implemented in a hardware optimized way. If ``x`` is a pytree t...
pbroadcast
python
jax-ml/jax
jax/_src/lax/parallel.py
https://github.com/jax-ml/jax/blob/master/jax/_src/lax/parallel.py
Apache-2.0
def ppermute(x, axis_name, perm): """Perform a collective permutation according to the permutation ``perm``. If ``x`` is a pytree then the result is equivalent to mapping this function to each leaf in the tree. This function is an analog of the CollectivePermute HLO. Args: x: array(s) with a mapped axi...
Perform a collective permutation according to the permutation ``perm``. If ``x`` is a pytree then the result is equivalent to mapping this function to each leaf in the tree. This function is an analog of the CollectivePermute HLO. Args: x: array(s) with a mapped axis named ``axis_name``. axis_name: h...
ppermute
python
jax-ml/jax
jax/_src/lax/parallel.py
https://github.com/jax-ml/jax/blob/master/jax/_src/lax/parallel.py
Apache-2.0
def pshuffle(x, axis_name, perm): """Convenience wrapper of jax.lax.ppermute with alternate permutation encoding If ``x`` is a pytree then the result is equivalent to mapping this function to each leaf in the tree. Args: x: array(s) with a mapped axis named ``axis_name``. axis_name: hashable Python ob...
Convenience wrapper of jax.lax.ppermute with alternate permutation encoding If ``x`` is a pytree then the result is equivalent to mapping this function to each leaf in the tree. Args: x: array(s) with a mapped axis named ``axis_name``. axis_name: hashable Python object used to name a pmapped axis (see t...
pshuffle
python
jax-ml/jax
jax/_src/lax/parallel.py
https://github.com/jax-ml/jax/blob/master/jax/_src/lax/parallel.py
Apache-2.0
def all_to_all(x, axis_name, split_axis, concat_axis, *, axis_index_groups=None, tiled=False): """Materialize the mapped axis and map a different axis. If ``x`` is a pytree then the result is equivalent to mapping this function to each leaf in the tree. In the output, the input mapped axis ``axis_name`` is ma...
Materialize the mapped axis and map a different axis. If ``x`` is a pytree then the result is equivalent to mapping this function to each leaf in the tree. In the output, the input mapped axis ``axis_name`` is materialized at the logical axis position ``concat_axis``, and the input unmapped axis at position ...
all_to_all
python
jax-ml/jax
jax/_src/lax/parallel.py
https://github.com/jax-ml/jax/blob/master/jax/_src/lax/parallel.py
Apache-2.0
def ragged_all_to_all( operand, output, input_offsets, send_sizes, output_offsets, recv_sizes, *, axis_name, axis_index_groups = None): """Ragged version of :func:`all_to_all` collective. We say data are "ragged" when they can be represented as a list of arrays whose shapes differ only in the size of the...
Ragged version of :func:`all_to_all` collective. We say data are "ragged" when they can be represented as a list of arrays whose shapes differ only in the size of the leading axis. For example, these data are ragged, comprising four component arrays:: ragged_data = [jnp.arange(3), jnp.arange(1), jnp.arange(...
ragged_all_to_all
python
jax-ml/jax
jax/_src/lax/parallel.py
https://github.com/jax-ml/jax/blob/master/jax/_src/lax/parallel.py
Apache-2.0
def axis_index(axis_name: AxisName) -> jax.Array: """Return the index along the mapped axis ``axis_name``. Args: axis_name: hashable Python object used to name the mapped axis. Returns: An integer representing the index. For example, with 8 XLA devices available: >>> from functools import partial ...
Return the index along the mapped axis ``axis_name``. Args: axis_name: hashable Python object used to name the mapped axis. Returns: An integer representing the index. For example, with 8 XLA devices available: >>> from functools import partial >>> @partial(jax.pmap, axis_name='i') ... def f(_):...
axis_index
python
jax-ml/jax
jax/_src/lax/parallel.py
https://github.com/jax-ml/jax/blob/master/jax/_src/lax/parallel.py
Apache-2.0
def pgather(src, idx, axes: int | AxisName): """Uses the last positional axis of idx to index into src's axes.""" if not isinstance(axes, (tuple, list)): axes = (axes,) # TODO: Canonicalize exes! return pgather_p.bind(src, idx, axes=tuple(axes))
Uses the last positional axis of idx to index into src's axes.
pgather
python
jax-ml/jax
jax/_src/lax/parallel.py
https://github.com/jax-ml/jax/blob/master/jax/_src/lax/parallel.py
Apache-2.0
def all_gather(x, axis_name, *, axis_index_groups=None, axis=0, tiled=False): """Gather values of x across all replicas. If ``x`` is a pytree then the result is equivalent to mapping this function to each leaf in the tree. This is equivalent to, but faster than, all_to_all(broadcast(x)). Args: x: array...
Gather values of x across all replicas. If ``x`` is a pytree then the result is equivalent to mapping this function to each leaf in the tree. This is equivalent to, but faster than, all_to_all(broadcast(x)). Args: x: array(s) with a mapped axis named ``axis_name``. axis_name: hashable Python object u...
all_gather
python
jax-ml/jax
jax/_src/lax/parallel.py
https://github.com/jax-ml/jax/blob/master/jax/_src/lax/parallel.py
Apache-2.0
def psum_scatter(x, axis_name, *, scatter_dimension=0, axis_index_groups=None, tiled=False): """ Like ``psum(x, axis_name)`` but each device retains only part of the result. For example, ``psum_scatter(x, axis_name, scatter_dimension=0, tiled=False)`` computes the same value as ``psum(x, axis_...
Like ``psum(x, axis_name)`` but each device retains only part of the result. For example, ``psum_scatter(x, axis_name, scatter_dimension=0, tiled=False)`` computes the same value as ``psum(x, axis_name)[axis_index(axis_name)]``, but it is more efficient. Thus the ``psum`` result is left scattered along the ...
psum_scatter
python
jax-ml/jax
jax/_src/lax/parallel.py
https://github.com/jax-ml/jax/blob/master/jax/_src/lax/parallel.py
Apache-2.0
def _dynamic_concat(a, b, m, axis=0): "Concatenates padded arrays `a` and `b` where the true size of `a` is `m`." if m is None: return jnp.concatenate([a, b], axis=axis) return lax.dynamic_update_slice_in_dim( _pad_in_dim(a, high=b.shape[axis], axis=axis), b, m, axis)
Concatenates padded arrays `a` and `b` where the true size of `a` is `m`.
_dynamic_concat
python
jax-ml/jax
jax/_src/lax/qdwh.py
https://github.com/jax-ml/jax/blob/master/jax/_src/lax/qdwh.py
Apache-2.0
def _use_qr(u, m, n, params): """QDWH iteration using QR decomposition. Args: u: a matrix, with static (padded) shape M x N. m, n: the dynamic shape of the matrix, where m <= M and n <= N. params: the QDWH parameters. """ a_minus_e_by_sqrt_c, sqrt_c, e = params M, N = u.shape y = _dynamic_concat(sqr...
QDWH iteration using QR decomposition. Args: u: a matrix, with static (padded) shape M x N. m, n: the dynamic shape of the matrix, where m <= M and n <= N. params: the QDWH parameters.
_use_qr
python
jax-ml/jax
jax/_src/lax/qdwh.py
https://github.com/jax-ml/jax/blob/master/jax/_src/lax/qdwh.py
Apache-2.0
def _use_cholesky(u, m, n, params): """QDWH iteration using Cholesky decomposition. Args: u: a matrix, with static (padded) shape M x N m, n: the dynamic shape of the matrix, where m <= M and n <= N. params: the QDWH parameters. """ a_minus_e, c, e = params _, N = u.shape x = c * (u.T.conj() @ u) + j...
QDWH iteration using Cholesky decomposition. Args: u: a matrix, with static (padded) shape M x N m, n: the dynamic shape of the matrix, where m <= M and n <= N. params: the QDWH parameters.
_use_cholesky
python
jax-ml/jax
jax/_src/lax/qdwh.py
https://github.com/jax-ml/jax/blob/master/jax/_src/lax/qdwh.py
Apache-2.0
def gather(operand: ArrayLike, start_indices: ArrayLike, dimension_numbers: GatherDimensionNumbers, slice_sizes: Shape, *, unique_indices: bool = False, indices_are_sorted: bool = False, mode: str | GatherScatterMode | None = None, fill_value ...
Gather operator. Wraps `XLA's Gather operator <https://www.tensorflow.org/xla/operation_semantics#gather>`_. :func:`gather` is a low-level operator with complicated semantics, and most JAX users will never need to call it directly. Instead, you should prefer using `Numpy-style indexing`_, and/or :func:`jax....
gather
python
jax-ml/jax
jax/_src/lax/slicing.py
https://github.com/jax-ml/jax/blob/master/jax/_src/lax/slicing.py
Apache-2.0
def scatter_add( operand: ArrayLike, scatter_indices: ArrayLike, updates: ArrayLike, dimension_numbers: ScatterDimensionNumbers, *, indices_are_sorted: bool = False, unique_indices: bool = False, mode: str | GatherScatterMode | None = None) -> Array: """Scatter-add operator. Wraps `XLA's Scatter operator ...
Scatter-add operator. Wraps `XLA's Scatter operator <https://www.tensorflow.org/xla/operation_semantics#scatter>`_, where addition is used to combine updates and values from `operand`. The semantics of scatter are complicated, and its API might change in the future. For most use cases, you should prefer the...
scatter_add
python
jax-ml/jax
jax/_src/lax/slicing.py
https://github.com/jax-ml/jax/blob/master/jax/_src/lax/slicing.py
Apache-2.0
def scatter_sub( operand: ArrayLike, scatter_indices: ArrayLike, updates: ArrayLike, dimension_numbers: ScatterDimensionNumbers, *, indices_are_sorted: bool = False, unique_indices: bool = False, mode: str | GatherScatterMode | None = None, ) -> Array: """Scatter-sub operator. Wraps...
Scatter-sub operator. Wraps `XLA's Scatter operator <https://www.tensorflow.org/xla/operation_semantics#scatter>`_, where subtraction is used to combine updates and values from `operand`. The semantics of scatter are complicated, and its API might change in the future. For most use cases, you should prefer ...
scatter_sub
python
jax-ml/jax
jax/_src/lax/slicing.py
https://github.com/jax-ml/jax/blob/master/jax/_src/lax/slicing.py
Apache-2.0
def scatter_mul( operand: ArrayLike, scatter_indices: ArrayLike, updates: ArrayLike, dimension_numbers: ScatterDimensionNumbers, *, indices_are_sorted: bool = False, unique_indices: bool = False, mode: str | GatherScatterMode | None = None) -> Array: """Scatter-multiply operator. Wraps `XLA's Scatter opera...
Scatter-multiply operator. Wraps `XLA's Scatter operator <https://www.tensorflow.org/xla/operation_semantics#scatter>`_, where multiplication is used to combine updates and values from `operand`. The semantics of scatter are complicated, and its API might change in the future. For most use cases, you should...
scatter_mul
python
jax-ml/jax
jax/_src/lax/slicing.py
https://github.com/jax-ml/jax/blob/master/jax/_src/lax/slicing.py
Apache-2.0
def scatter_min( operand: ArrayLike, scatter_indices: ArrayLike, updates: ArrayLike, dimension_numbers: ScatterDimensionNumbers, *, indices_are_sorted: bool = False, unique_indices: bool = False, mode: str | GatherScatterMode | None = None) -> Array: """Scatter-min operator. Wraps `XLA's Scatter operator ...
Scatter-min operator. Wraps `XLA's Scatter operator <https://www.tensorflow.org/xla/operation_semantics#scatter>`_, where the `min` function is used to combine updates and values from `operand`. The semantics of scatter are complicated, and its API might change in the future. For most use cases, you should ...
scatter_min
python
jax-ml/jax
jax/_src/lax/slicing.py
https://github.com/jax-ml/jax/blob/master/jax/_src/lax/slicing.py
Apache-2.0
def scatter_max( operand: ArrayLike, scatter_indices: ArrayLike, updates: ArrayLike, dimension_numbers: ScatterDimensionNumbers, *, indices_are_sorted: bool = False, unique_indices: bool = False, mode: str | GatherScatterMode | None = None) -> Array: """Scatter-max operator. Wraps `XLA's Scatter operator ...
Scatter-max operator. Wraps `XLA's Scatter operator <https://www.tensorflow.org/xla/operation_semantics#scatter>`_, where the `max` function is used to combine updates and values from `operand`. The semantics of scatter are complicated, and its API might change in the future. For most use cases, you should ...
scatter_max
python
jax-ml/jax
jax/_src/lax/slicing.py
https://github.com/jax-ml/jax/blob/master/jax/_src/lax/slicing.py
Apache-2.0
def scatter_apply( operand: Array, scatter_indices: Array, func: Callable[[Array], Array], dimension_numbers: ScatterDimensionNumbers, *, update_shape: Shape = (), indices_are_sorted: bool = False, unique_indices: bool = False, mode: str | GatherScatterMode | None = None) -> Array: """Scatter-apply operat...
Scatter-apply operator. Wraps `XLA's Scatter operator <https://www.tensorflow.org/xla/operation_semantics#scatter>`_, where values from ``operand`` are replaced with ``func(operand)``, with duplicate indices resulting in multiple applications of ``func``. The semantics of scatter are complicated, and its AP...
scatter_apply
python
jax-ml/jax
jax/_src/lax/slicing.py
https://github.com/jax-ml/jax/blob/master/jax/_src/lax/slicing.py
Apache-2.0
def scatter( operand: ArrayLike, scatter_indices: ArrayLike, updates: ArrayLike, dimension_numbers: ScatterDimensionNumbers, *, indices_are_sorted: bool = False, unique_indices: bool = False, mode: str | GatherScatterMode | None = None) -> Array: """Scatter-update operator. Wraps `XLA's Scatter operator ...
Scatter-update operator. Wraps `XLA's Scatter operator <https://www.tensorflow.org/xla/operation_semantics#scatter>`_, where updates replace values from `operand`. If multiple updates are performed to the same index of operand, they may be applied in any order. :func:`scatter` is a low-level operator wit...
scatter
python
jax-ml/jax
jax/_src/lax/slicing.py
https://github.com/jax-ml/jax/blob/master/jax/_src/lax/slicing.py
Apache-2.0
def index_in_dim(operand: Array | np.ndarray, index: int, axis: int = 0, keepdims: bool = True) -> Array: """Convenience wrapper around :func:`lax.slice` to perform int indexing. This is effectively equivalent to ``operand[..., index]`` with the indexing applied on the specified axis. Args: ...
Convenience wrapper around :func:`lax.slice` to perform int indexing. This is effectively equivalent to ``operand[..., index]`` with the indexing applied on the specified axis. Args: operand: an array to index. index: integer index axis: the axis along which to apply the index (defaults to 0) ke...
index_in_dim
python
jax-ml/jax
jax/_src/lax/slicing.py
https://github.com/jax-ml/jax/blob/master/jax/_src/lax/slicing.py
Apache-2.0
def dynamic_slice_in_dim(operand: Array | np.ndarray, start_index: ArrayLike, slice_size: int, axis: int = 0, *, allow_negative_indices: bool = True) -> Array: """Convenience wrapper around :func:`lax.dynamic_slice` applied to one dimension. ...
Convenience wrapper around :func:`lax.dynamic_slice` applied to one dimension. This is roughly equivalent to the following Python indexing syntax applied along the specified axis: ``operand[..., start_index:start_index + slice_size]``. Args: operand: an array to slice. start_index: the (possibly dynamic...
dynamic_slice_in_dim
python
jax-ml/jax
jax/_src/lax/slicing.py
https://github.com/jax-ml/jax/blob/master/jax/_src/lax/slicing.py
Apache-2.0
def dynamic_index_in_dim(operand: Array | np.ndarray, index: int | Array, axis: int = 0, keepdims: bool = True, *, allow_negative_indices: bool = True) -> Array: """Convenience wrapper around dynamic_slice to perform i...
Convenience wrapper around dynamic_slice to perform int indexing. This is roughly equivalent to the following Python indexing syntax applied along the specified axis: ``operand[..., index]``. Args: operand: an array to slice. index: the (possibly dynamic) start index axis: the axis along which to ap...
dynamic_index_in_dim
python
jax-ml/jax
jax/_src/lax/slicing.py
https://github.com/jax-ml/jax/blob/master/jax/_src/lax/slicing.py
Apache-2.0
def dynamic_update_slice_in_dim(operand: Array | np.ndarray, update: ArrayLike, start_index: ArrayLike, axis: int, *, allow_negative_indices: bool = True) -> Array: """Convenience wrapper ar...
Convenience wrapper around :func:`dynamic_update_slice` to update a slice in a single ``axis``. Args: operand: an array to slice. update: an array containing the new values to write onto `operand`. start_index: a single scalar index axis: the axis of the update. allow_negative_indices: boolean ...
dynamic_update_slice_in_dim
python
jax-ml/jax
jax/_src/lax/slicing.py
https://github.com/jax-ml/jax/blob/master/jax/_src/lax/slicing.py
Apache-2.0
def dynamic_update_index_in_dim(operand: Array | np.ndarray, update: ArrayLike, index: ArrayLike, axis: int, *, allow_negative_indices: bool = True) -> Array: """Convenience wrapper around :func:`dynamic_update_slice` to u...
Convenience wrapper around :func:`dynamic_update_slice` to update a slice of size 1 in a single ``axis``. Args: operand: an array to slice. update: an array containing the new values to write onto `operand`. index: a single scalar index axis: the axis of the update. allow_negative_indices: bool...
dynamic_update_index_in_dim
python
jax-ml/jax
jax/_src/lax/slicing.py
https://github.com/jax-ml/jax/blob/master/jax/_src/lax/slicing.py
Apache-2.0
def _get_sharding_for_varying_out_shape(out_shape, operand, name): """Returns a sharding when out_shape may not be the same as operand shape""" mesh = operand.sharding.mesh for op_sh, out_sh, op_spec in safe_zip( operand.shape, out_shape, operand.sharding.spec): if (op_sh != out_sh and op_spec is not No...
Returns a sharding when out_shape may not be the same as operand shape
_get_sharding_for_varying_out_shape
python
jax-ml/jax
jax/_src/lax/slicing.py
https://github.com/jax-ml/jax/blob/master/jax/_src/lax/slicing.py
Apache-2.0
def _gather_shape_rule(operand, indices, *, dimension_numbers, slice_sizes, unique_indices, indices_are_sorted, mode, fill_value): """Validates the well-formedness of the arguments to Gather. The code implements the checks based on the detailed operation semantics of ...
Validates the well-formedness of the arguments to Gather. The code implements the checks based on the detailed operation semantics of XLA's `Gather <https://www.tensorflow.org/xla/operation_semantics#gather>`_ operator and following the outline of the implementation of ShapeInference::InferGatherShape in Tenso...
_gather_shape_rule
python
jax-ml/jax
jax/_src/lax/slicing.py
https://github.com/jax-ml/jax/blob/master/jax/_src/lax/slicing.py
Apache-2.0
def _gather_fill(operand, indices, *, dimension_numbers, slice_sizes, unique_indices, indices_are_sorted, fill_value, output_shape): """Lowers a FILL_OR_DROP gather as a PROMISE_IN_BOUNDS gather with masking.""" dnums = dimension_numbers intarray = partial(np.array, dtype=np.int6...
Lowers a FILL_OR_DROP gather as a PROMISE_IN_BOUNDS gather with masking.
_gather_fill
python
jax-ml/jax
jax/_src/lax/slicing.py
https://github.com/jax-ml/jax/blob/master/jax/_src/lax/slicing.py
Apache-2.0
def _scatter_shape_rule(operand, indices, updates, *, update_jaxpr, update_consts, dimension_numbers, indices_are_sorted, unique_indices, mode): """Validates the well-formedness of the ``dimension_numbers`` argument to Scatter. The code implements the checks based ...
Validates the well-formedness of the ``dimension_numbers`` argument to Scatter. The code implements the checks based on the detailed operation semantics of XLA's `Scatter <https://www.tensorflow.org/xla/operation_semantics#scatter>`_ operator and following the outline of the implementation of ShapeInference:...
_scatter_shape_rule
python
jax-ml/jax
jax/_src/lax/slicing.py
https://github.com/jax-ml/jax/blob/master/jax/_src/lax/slicing.py
Apache-2.0