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 _clamp_scatter_indices(operand, indices, updates, *, dnums):
"""Clamps `indices` to be in-range for a scatter."""
slice_sizes = []
pos = 0
for i in range(len(operand.shape)):
if i in dnums.inserted_window_dims or i in dnums.operand_batching_dims:
slice_sizes.append(1)
else:
slice_sizes.a... | Clamps `indices` to be in-range for a scatter. | _clamp_scatter_indices | 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 igammac(a: ArrayLike, x: ArrayLike) -> Array:
r"""Elementwise complementary regularized incomplete gamma function."""
a, x = core.standard_insert_pvary(a, x)
return igammac_p.bind(a, x) | Elementwise complementary regularized incomplete gamma function. | igammac | python | jax-ml/jax | jax/_src/lax/special.py | https://github.com/jax-ml/jax/blob/master/jax/_src/lax/special.py | Apache-2.0 |
def igamma_grad_a(a: ArrayLike, x: ArrayLike) -> Array:
r"""Elementwise derivative of the regularized incomplete gamma function."""
a, x = core.standard_insert_pvary(a, x)
return igamma_grad_a_p.bind(a, x) | Elementwise derivative of the regularized incomplete gamma function. | igamma_grad_a | python | jax-ml/jax | jax/_src/lax/special.py | https://github.com/jax-ml/jax/blob/master/jax/_src/lax/special.py | Apache-2.0 |
def random_gamma_grad(a: ArrayLike, x: ArrayLike, *, dtype) -> Array:
r"""Elementwise derivative of samples from `Gamma(a, 1)`."""
a, x = core.standard_insert_pvary(a, x)
return random_gamma_grad_impl(a, x, dtype=dtype) | Elementwise derivative of samples from `Gamma(a, 1)`. | random_gamma_grad | python | jax-ml/jax | jax/_src/lax/special.py | https://github.com/jax-ml/jax/blob/master/jax/_src/lax/special.py | Apache-2.0 |
def zeta(x: ArrayLike, q: ArrayLike) -> Array:
r"""Elementwise Hurwitz zeta function: :math:`\zeta(x, q)`"""
x, q = core.standard_insert_pvary(x, q)
return zeta_p.bind(x, q) | Elementwise Hurwitz zeta function: :math:`\zeta(x, q)` | zeta | python | jax-ml/jax | jax/_src/lax/special.py | https://github.com/jax-ml/jax/blob/master/jax/_src/lax/special.py | Apache-2.0 |
def nth_partial_betainc_numerator(iteration, a, b, x):
"""
The partial numerator for the incomplete beta function is given
here: http://dlmf.nist.gov/8.17.E23 Note that there is a special
case: the partial numerator for the first iteration is one.
"""
iteration_bcast = broadcast_in_dim(iteration... |
The partial numerator for the incomplete beta function is given
here: http://dlmf.nist.gov/8.17.E23 Note that there is a special
case: the partial numerator for the first iteration is one.
| nth_partial_betainc_numerator | python | jax-ml/jax | jax/_src/lax/special.py | https://github.com/jax-ml/jax/blob/master/jax/_src/lax/special.py | Apache-2.0 |
def _i0e_impl32(x):
"""
Computes an approximation to the modified Bessel function of the first kind,
zeroth order. The following implementation follows Cephes' F32 and F64
implementation of i0e.
"""
i0e_coeffs_a = np.array(
[-1.30002500998624804212E-8, 6.04699502254191894932E-8,
-2.6707938539406117... |
Computes an approximation to the modified Bessel function of the first kind,
zeroth order. The following implementation follows Cephes' F32 and F64
implementation of i0e.
| _i0e_impl32 | python | jax-ml/jax | jax/_src/lax/special.py | https://github.com/jax-ml/jax/blob/master/jax/_src/lax/special.py | Apache-2.0 |
def create(capacity: int, prototype: Any) -> Stack:
"""Creates a stack with size `capacity` with elements like `prototype`.
`prototype` can be any JAX pytree. This function looks only at its
structure; the specific values are ignored.
"""
return Stack(
jnp.array(0, jnp.int32),
jax.tree_... | Creates a stack with size `capacity` with elements like `prototype`.
`prototype` can be any JAX pytree. This function looks only at its
structure; the specific values are ignored.
| create | python | jax-ml/jax | jax/_src/lax/stack.py | https://github.com/jax-ml/jax/blob/master/jax/_src/lax/stack.py | Apache-2.0 |
def push(self, elem: Any) -> Stack:
"""Pushes `elem` onto the stack, returning the updated stack."""
return Stack(
self._size + 1,
jax.tree_util.tree_map(
lambda x, y: lax.dynamic_update_index_in_dim(x, y, self._size, 0),
self._data, elem)) | Pushes `elem` onto the stack, returning the updated stack. | push | python | jax-ml/jax | jax/_src/lax/stack.py | https://github.com/jax-ml/jax/blob/master/jax/_src/lax/stack.py | Apache-2.0 |
def pop(self) -> tuple[Any, Stack]:
"""Pops from the stack, returning an (elem, updated stack) pair."""
elem = jax.tree_util.tree_map(
lambda x: lax.dynamic_index_in_dim(x, self._size - 1, 0, keepdims=False),
self._data)
return elem, Stack(self._size - 1, self._data) | Pops from the stack, returning an (elem, updated stack) pair. | pop | python | jax-ml/jax | jax/_src/lax/stack.py | https://github.com/jax-ml/jax/blob/master/jax/_src/lax/stack.py | Apache-2.0 |
def reduce_window(
operand,
init_value,
computation: Callable,
window_dimensions: core.Shape,
window_strides: Sequence[int],
padding: str | Sequence[tuple[int, int]],
base_dilation: Sequence[int] | None = None,
window_dilation: Sequence[int] | None = None,
) -> Array:
"""Wraps XLA's `R... | Wraps XLA's `ReduceWindowWithGeneralPadding
<https://www.tensorflow.org/xla/operation_semantics#reducewindow>`_
operator.
| reduce_window | python | jax-ml/jax | jax/_src/lax/windowed_reductions.py | https://github.com/jax-ml/jax/blob/master/jax/_src/lax/windowed_reductions.py | Apache-2.0 |
def _select_and_gather_add(tangents: Array, operand: Array,
select_prim: core.Primitive,
window_dimensions: core.Shape,
window_strides: Sequence[int],
padding: Sequence[tuple[int, int]],
... | Extracts the tangent corresponding to the minimum or maximum element in
each window of the `operand` array.
Wraps XLA's `ReduceWindow
<https://www.tensorflow.org/xla/operation_semantics#reducewindow>`_
operator, which applies a reduction function to all elements in each window of
the input multi-dimensional ... | _select_and_gather_add | python | jax-ml/jax | jax/_src/lax/windowed_reductions.py | https://github.com/jax-ml/jax/blob/master/jax/_src/lax/windowed_reductions.py | Apache-2.0 |
def _check_tree_and_avals(what1, tree1, avals1, what2, tree2, avals2):
"""Raises TypeError if (tree1, avals1) does not match (tree2, avals2).
Corresponding `tree` and `avals` must match in the sense that the number of
leaves in `tree` must be equal to the length of `avals`. `what1` and
`what2` describe what th... | Raises TypeError if (tree1, avals1) does not match (tree2, avals2).
Corresponding `tree` and `avals` must match in the sense that the number of
leaves in `tree` must be equal to the length of `avals`. `what1` and
`what2` describe what the `tree1` and `tree2` represent.
| _check_tree_and_avals | python | jax-ml/jax | jax/_src/lax/control_flow/common.py | https://github.com/jax-ml/jax/blob/master/jax/_src/lax/control_flow/common.py | Apache-2.0 |
def switch(index, branches: Sequence[Callable], *operands,
operand=_no_operand_sentinel):
"""Apply exactly one of the ``branches`` given by ``index``.
If ``index`` is out of bounds, it is clamped to within bounds.
Has the semantics of the following Python::
def switch(index, branches, *operands)... | Apply exactly one of the ``branches`` given by ``index``.
If ``index`` is out of bounds, it is clamped to within bounds.
Has the semantics of the following Python::
def switch(index, branches, *operands):
index = clamp(0, index, len(branches) - 1)
return branches[index](*operands)
Internally t... | switch | python | jax-ml/jax | jax/_src/lax/control_flow/conditionals.py | https://github.com/jax-ml/jax/blob/master/jax/_src/lax/control_flow/conditionals.py | Apache-2.0 |
def _cond(pred, true_fun: Callable, false_fun: Callable, *operands,
operand=_no_operand_sentinel):
"""Conditionally apply ``true_fun`` or ``false_fun``.
Wraps XLA's `Conditional
<https://www.tensorflow.org/xla/operation_semantics#conditional>`_
operator.
Provided arguments are correctly typed, ``c... | Conditionally apply ``true_fun`` or ``false_fun``.
Wraps XLA's `Conditional
<https://www.tensorflow.org/xla/operation_semantics#conditional>`_
operator.
Provided arguments are correctly typed, ``cond()`` has equivalent
semantics to this Python implementation, where ``pred`` must be a
scalar type::
de... | _cond | python | jax-ml/jax | jax/_src/lax/control_flow/conditionals.py | https://github.com/jax-ml/jax/blob/master/jax/_src/lax/control_flow/conditionals.py | Apache-2.0 |
def _cond_with_per_branch_args(pred,
true_operand, true_fun: Callable,
false_operand, false_fun: Callable):
"""Conditionally apply ``true_fun`` or ``false_fun``.
Has equivalent semantics to this Python implementation::
def cond(pred, true_operand, ... | Conditionally apply ``true_fun`` or ``false_fun``.
Has equivalent semantics to this Python implementation::
def cond(pred, true_operand, true_fun, false_operand, false_fun):
if pred:
return true_fun(true_operand)
else:
return false_fun(false_operand)
Pred has to be a scalar type, ... | _cond_with_per_branch_args | python | jax-ml/jax | jax/_src/lax/control_flow/conditionals.py | https://github.com/jax-ml/jax/blob/master/jax/_src/lax/control_flow/conditionals.py | Apache-2.0 |
def platform_dependent(*args: Any,
default: Callable[..., _T] | None = None,
**per_platform: Callable[..., _T]):
"""Stages out platform-specific code.
In JAX the actual platform on which a computation is run is determined
very late, e.g., based on where the data is l... | Stages out platform-specific code.
In JAX the actual platform on which a computation is run is determined
very late, e.g., based on where the data is located. When using AOT
lowering or serialization, the computation may be compiled and executed
on a different machine, or even on a platform that is not availab... | platform_dependent | python | jax-ml/jax | jax/_src/lax/control_flow/conditionals.py | https://github.com/jax-ml/jax/blob/master/jax/_src/lax/control_flow/conditionals.py | Apache-2.0 |
def discharged_for_loop(nsteps, body, init_state, *, reverse: bool = False):
"""A `for_loop` implementation that discharges its body right away.
Potentially useful for testing and benchmarking.
"""
flat_state, state_tree = tree_flatten(init_state)
state_avals = map(state_utils.val_to_ref_aval, flat_state)
... | A `for_loop` implementation that discharges its body right away.
Potentially useful for testing and benchmarking.
| discharged_for_loop | python | jax-ml/jax | jax/_src/lax/control_flow/for_loop.py | https://github.com/jax-ml/jax/blob/master/jax/_src/lax/control_flow/for_loop.py | Apache-2.0 |
def _promote_weak_typed_inputs(in_vals, in_avals, out_avals):
"""Promote weakly-typed in_vals to be compatible with out_avals.
Args:
in_vals : flattened list of input values.
in_avals : corresponding list of avals.
out_avals : list of target output avals.
Returns:
in_vals_new : flattened list of ... | Promote weakly-typed in_vals to be compatible with out_avals.
Args:
in_vals : flattened list of input values.
in_avals : corresponding list of avals.
out_avals : list of target output avals.
Returns:
in_vals_new : flattened list of modified in_vals with no weak types.
changed : bool; true if in... | _promote_weak_typed_inputs | python | jax-ml/jax | jax/_src/lax/control_flow/loops.py | https://github.com/jax-ml/jax/blob/master/jax/_src/lax/control_flow/loops.py | Apache-2.0 |
def fori_loop(lower, upper, body_fun, init_val,
*, unroll: int | bool | None = None):
"""Loop from ``lower`` to ``upper`` by reduction to :func:`jax.lax.while_loop`.
The `Haskell-like type signature`_ in brief is
.. code-block:: haskell
fori_loop :: Int -> Int -> ((Int, a) -> a) -> a -> a
... | Loop from ``lower`` to ``upper`` by reduction to :func:`jax.lax.while_loop`.
The `Haskell-like type signature`_ in brief is
.. code-block:: haskell
fori_loop :: Int -> Int -> ((Int, a) -> a) -> a -> a
The semantics of ``fori_loop`` are given by this Python implementation::
def fori_loop(lower, upper,... | fori_loop | python | jax-ml/jax | jax/_src/lax/control_flow/loops.py | https://github.com/jax-ml/jax/blob/master/jax/_src/lax/control_flow/loops.py | Apache-2.0 |
def associative_scan(fn: Callable, elems, reverse: bool = False, axis: int = 0):
"""Performs a scan with an associative binary operation, in parallel.
For an introduction to associative scans, see [BLE1990]_.
Args:
fn: A Python callable implementing an associative binary operation with
signature ``r =... | Performs a scan with an associative binary operation, in parallel.
For an introduction to associative scans, see [BLE1990]_.
Args:
fn: A Python callable implementing an associative binary operation with
signature ``r = fn(a, b)``. Function `fn` must be associative, i.e., it
must satisfy the equati... | associative_scan | python | jax-ml/jax | jax/_src/lax/control_flow/loops.py | https://github.com/jax-ml/jax/blob/master/jax/_src/lax/control_flow/loops.py | Apache-2.0 |
def _interleave(a, b, axis):
"""Given two Tensors of static shape, interleave them along the first axis."""
assert a.shape[axis] == b.shape[axis] or a.shape[axis] == b.shape[axis] + 1
a_pad = [(0, 0, 0)] * a.ndim
b_pad = [(0, 0, 0)] * b.ndim
a_pad[axis] = (0, 1 if a.shape[axis] == b.shape[axis] else 0, 1)
b... | Given two Tensors of static shape, interleave them along the first axis. | _interleave | python | jax-ml/jax | jax/_src/lax/control_flow/loops.py | https://github.com/jax-ml/jax/blob/master/jax/_src/lax/control_flow/loops.py | Apache-2.0 |
def custom_root(f: Callable,
initial_guess: Any,
solve: Callable[[Callable, Any], Any],
tangent_solve: Callable[[Callable, Any], Any],
has_aux=False):
"""Differentiably solve for the roots of a function.
This is a low-level routine, mostly intended fo... | Differentiably solve for the roots of a function.
This is a low-level routine, mostly intended for internal use in JAX.
Gradients of custom_root() are defined with respect to closed-over variables
from the provided function ``f`` via the implicit function theorem:
https://en.wikipedia.org/wiki/Implicit_functio... | custom_root | python | jax-ml/jax | jax/_src/lax/control_flow/solves.py | https://github.com/jax-ml/jax/blob/master/jax/_src/lax/control_flow/solves.py | Apache-2.0 |
def custom_linear_solve(
matvec: Callable,
b: Any,
solve: Callable[[Callable, Any], Any],
transpose_solve: Callable[[Callable, Any], Any] | None = None,
symmetric=False, has_aux=False):
"""Perform a matrix-free linear solve with implicitly defined gradients.
This function allows for overriding ... | Perform a matrix-free linear solve with implicitly defined gradients.
This function allows for overriding or defining gradients for a linear
solve directly via implicit differentiation at the solution, rather than by
differentiating *through* the solve operation. This can sometimes be much faster
or more numer... | custom_linear_solve | python | jax-ml/jax | jax/_src/lax/control_flow/solves.py | https://github.com/jax-ml/jax/blob/master/jax/_src/lax/control_flow/solves.py | Apache-2.0 |
def _try_cuda_nvcc_import() -> str | None:
"""Try to import `cuda_nvcc` and get its path directly.
If the pip package `nvidia-cuda-nvcc-cu11` is installed, it should have
both of the things XLA looks for in the cuda path, namely `bin/ptxas` and
`nvvm/libdevice/libdevice.10.bc`.
"""
try:
f... | Try to import `cuda_nvcc` and get its path directly.
If the pip package `nvidia-cuda-nvcc-cu11` is installed, it should have
both of the things XLA looks for in the cuda path, namely `bin/ptxas` and
`nvvm/libdevice/libdevice.10.bc`.
| _try_cuda_nvcc_import | python | jax-ml/jax | jax/_src/lib/__init__.py | https://github.com/jax-ml/jax/blob/master/jax/_src/lib/__init__.py | Apache-2.0 |
def squareplus(x: ArrayLike, b: ArrayLike = 4) -> Array:
r"""Squareplus activation function.
Computes the element-wise function
.. math::
\mathrm{squareplus}(x) = \frac{x + \sqrt{x^2 + b}}{2}
as described in https://arxiv.org/abs/2112.11687.
Args:
x : input array
b : smoothness parameter
"""... | Squareplus activation function.
Computes the element-wise function
.. math::
\mathrm{squareplus}(x) = \frac{x + \sqrt{x^2 + b}}{2}
as described in https://arxiv.org/abs/2112.11687.
Args:
x : input array
b : smoothness parameter
| squareplus | python | jax-ml/jax | jax/_src/nn/functions.py | https://github.com/jax-ml/jax/blob/master/jax/_src/nn/functions.py | Apache-2.0 |
def sparse_plus(x: ArrayLike) -> Array:
r"""Sparse plus function.
Computes the function:
.. math::
\mathrm{sparse\_plus}(x) = \begin{cases}
0, & x \leq -1\\
\frac{1}{4}(x+1)^2, & -1 < x < 1 \\
x, & 1 \leq x
\end{cases}
This is the twin function of the softplus activation ensuring a... | Sparse plus function.
Computes the function:
.. math::
\mathrm{sparse\_plus}(x) = \begin{cases}
0, & x \leq -1\\
\frac{1}{4}(x+1)^2, & -1 < x < 1 \\
x, & 1 \leq x
\end{cases}
This is the twin function of the softplus activation ensuring a zero output
for inputs less than -1 and a l... | sparse_plus | python | jax-ml/jax | jax/_src/nn/functions.py | https://github.com/jax-ml/jax/blob/master/jax/_src/nn/functions.py | Apache-2.0 |
def soft_sign(x: ArrayLike) -> Array:
r"""Soft-sign activation function.
Computes the element-wise function
.. math::
\mathrm{soft\_sign}(x) = \frac{x}{|x| + 1}
Args:
x : input array
"""
numpy_util.check_arraylike("soft_sign", x)
x_arr = jnp.asarray(x)
return x_arr / (jnp.abs(x_arr) + 1) | Soft-sign activation function.
Computes the element-wise function
.. math::
\mathrm{soft\_sign}(x) = \frac{x}{|x| + 1}
Args:
x : input array
| soft_sign | python | jax-ml/jax | jax/_src/nn/functions.py | https://github.com/jax-ml/jax/blob/master/jax/_src/nn/functions.py | Apache-2.0 |
def silu(x: ArrayLike) -> Array:
r"""SiLU (aka swish) activation function.
Computes the element-wise function:
.. math::
\mathrm{silu}(x) = x \cdot \mathrm{sigmoid}(x) = \frac{x}{1 + e^{-x}}
:func:`swish` and :func:`silu` are both aliases for the same function.
Args:
x : input array
Returns:
... | SiLU (aka swish) activation function.
Computes the element-wise function:
.. math::
\mathrm{silu}(x) = x \cdot \mathrm{sigmoid}(x) = \frac{x}{1 + e^{-x}}
:func:`swish` and :func:`silu` are both aliases for the same function.
Args:
x : input array
Returns:
An array.
See also:
:func:`sig... | silu | python | jax-ml/jax | jax/_src/nn/functions.py | https://github.com/jax-ml/jax/blob/master/jax/_src/nn/functions.py | Apache-2.0 |
def mish(x: ArrayLike) -> Array:
r"""Mish activation function.
Computes the element-wise function:
.. math::
\mathrm{mish}(x) = x \cdot \mathrm{tanh}(\mathrm{softplus}(x))
For more information, see
`Mish: A Self Regularized Non-Monotonic Activation Function
<https://arxiv.org/abs/1908.08681>`_.
Ar... | Mish activation function.
Computes the element-wise function:
.. math::
\mathrm{mish}(x) = x \cdot \mathrm{tanh}(\mathrm{softplus}(x))
For more information, see
`Mish: A Self Regularized Non-Monotonic Activation Function
<https://arxiv.org/abs/1908.08681>`_.
Args:
x : input array
Returns:
... | mish | python | jax-ml/jax | jax/_src/nn/functions.py | https://github.com/jax-ml/jax/blob/master/jax/_src/nn/functions.py | Apache-2.0 |
def log_sigmoid(x: ArrayLike) -> Array:
r"""Log-sigmoid activation function.
Computes the element-wise function:
.. math::
\mathrm{log\_sigmoid}(x) = \log(\mathrm{sigmoid}(x)) = -\log(1 + e^{-x})
Args:
x : input array
Returns:
An array.
See also:
:func:`sigmoid`
"""
numpy_util.check... | Log-sigmoid activation function.
Computes the element-wise function:
.. math::
\mathrm{log\_sigmoid}(x) = \log(\mathrm{sigmoid}(x)) = -\log(1 + e^{-x})
Args:
x : input array
Returns:
An array.
See also:
:func:`sigmoid`
| log_sigmoid | python | jax-ml/jax | jax/_src/nn/functions.py | https://github.com/jax-ml/jax/blob/master/jax/_src/nn/functions.py | Apache-2.0 |
def elu(x: ArrayLike, alpha: ArrayLike = 1.0) -> Array:
r"""Exponential linear unit activation function.
Computes the element-wise function:
.. math::
\mathrm{elu}(x) = \begin{cases}
x, & x > 0\\
\alpha \left(\exp(x) - 1\right), & x \le 0
\end{cases}
Args:
x : input array
alpha : ... | Exponential linear unit activation function.
Computes the element-wise function:
.. math::
\mathrm{elu}(x) = \begin{cases}
x, & x > 0\\
\alpha \left(\exp(x) - 1\right), & x \le 0
\end{cases}
Args:
x : input array
alpha : scalar or array of alpha values (default: 1.0)
Returns:
... | elu | python | jax-ml/jax | jax/_src/nn/functions.py | https://github.com/jax-ml/jax/blob/master/jax/_src/nn/functions.py | Apache-2.0 |
def leaky_relu(x: ArrayLike, negative_slope: ArrayLike = 1e-2) -> Array:
r"""Leaky rectified linear unit activation function.
Computes the element-wise function:
.. math::
\mathrm{leaky\_relu}(x) = \begin{cases}
x, & x \ge 0\\
\alpha x, & x < 0
\end{cases}
where :math:`\alpha` = :code:`ne... | Leaky rectified linear unit activation function.
Computes the element-wise function:
.. math::
\mathrm{leaky\_relu}(x) = \begin{cases}
x, & x \ge 0\\
\alpha x, & x < 0
\end{cases}
where :math:`\alpha` = :code:`negative_slope`.
Args:
x : input array
negative_slope : array or scala... | leaky_relu | python | jax-ml/jax | jax/_src/nn/functions.py | https://github.com/jax-ml/jax/blob/master/jax/_src/nn/functions.py | Apache-2.0 |
def hard_tanh(x: ArrayLike) -> Array:
r"""Hard :math:`\mathrm{tanh}` activation function.
Computes the element-wise function:
.. math::
\mathrm{hard\_tanh}(x) = \begin{cases}
-1, & x < -1\\
x, & -1 \le x \le 1\\
1, & 1 < x
\end{cases}
Args:
x : input array
Returns:
An arr... | Hard :math:`\mathrm{tanh}` activation function.
Computes the element-wise function:
.. math::
\mathrm{hard\_tanh}(x) = \begin{cases}
-1, & x < -1\\
x, & -1 \le x \le 1\\
1, & 1 < x
\end{cases}
Args:
x : input array
Returns:
An array.
| hard_tanh | python | jax-ml/jax | jax/_src/nn/functions.py | https://github.com/jax-ml/jax/blob/master/jax/_src/nn/functions.py | Apache-2.0 |
def selu(x: ArrayLike) -> Array:
r"""Scaled exponential linear unit activation.
Computes the element-wise function:
.. math::
\mathrm{selu}(x) = \lambda \begin{cases}
x, & x > 0\\
\alpha e^x - \alpha, & x \le 0
\end{cases}
where :math:`\lambda = 1.0507009873554804934193349852946` and
:m... | Scaled exponential linear unit activation.
Computes the element-wise function:
.. math::
\mathrm{selu}(x) = \lambda \begin{cases}
x, & x > 0\\
\alpha e^x - \alpha, & x \le 0
\end{cases}
where :math:`\lambda = 1.0507009873554804934193349852946` and
:math:`\alpha = 1.67326324235437728481704... | selu | python | jax-ml/jax | jax/_src/nn/functions.py | https://github.com/jax-ml/jax/blob/master/jax/_src/nn/functions.py | Apache-2.0 |
def gelu(x: ArrayLike, approximate: bool = True) -> Array:
r"""Gaussian error linear unit activation function.
If ``approximate=False``, computes the element-wise function:
.. math::
\mathrm{gelu}(x) = \frac{x}{2} \left(\mathrm{erfc} \left(
\frac{-x}{\sqrt{2}} \right) \right)
If ``approximate=True`... | Gaussian error linear unit activation function.
If ``approximate=False``, computes the element-wise function:
.. math::
\mathrm{gelu}(x) = \frac{x}{2} \left(\mathrm{erfc} \left(
\frac{-x}{\sqrt{2}} \right) \right)
If ``approximate=True``, uses the approximate formulation of GELU:
.. math::
\ma... | gelu | python | jax-ml/jax | jax/_src/nn/functions.py | https://github.com/jax-ml/jax/blob/master/jax/_src/nn/functions.py | Apache-2.0 |
def glu(x: ArrayLike, axis: int = -1) -> Array:
r"""Gated linear unit activation function.
Computes the function:
.. math::
\mathrm{glu}(x) = x\left[\ldots, 0:\frac{n}{2}, \ldots\right] \cdot
\mathrm{sigmoid} \left( x\left[\ldots, \frac{n}{2}:n, \ldots\right]
\right)
where the array is spl... | Gated linear unit activation function.
Computes the function:
.. math::
\mathrm{glu}(x) = x\left[\ldots, 0:\frac{n}{2}, \ldots\right] \cdot
\mathrm{sigmoid} \left( x\left[\ldots, \frac{n}{2}:n, \ldots\right]
\right)
where the array is split into two along ``axis``. The size of the ``axis``
... | glu | python | jax-ml/jax | jax/_src/nn/functions.py | https://github.com/jax-ml/jax/blob/master/jax/_src/nn/functions.py | Apache-2.0 |
def log_softmax(x: ArrayLike,
axis: int | tuple[int, ...] | None = -1,
where: ArrayLike | None = None) -> Array:
r"""Log-Softmax function.
Computes the logarithm of the :code:`softmax` function, which rescales
elements to the range :math:`[-\infty, 0)`.
.. math ::
\mathrm{l... | Log-Softmax function.
Computes the logarithm of the :code:`softmax` function, which rescales
elements to the range :math:`[-\infty, 0)`.
.. math ::
\mathrm{log\_softmax}(x)_i = \log \left( \frac{\exp(x_i)}{\sum_j \exp(x_j)}
\right)
Args:
x : input array
axis: the axis or axes along which the ... | log_softmax | python | jax-ml/jax | jax/_src/nn/functions.py | https://github.com/jax-ml/jax/blob/master/jax/_src/nn/functions.py | Apache-2.0 |
def softmax(x: ArrayLike,
axis: int | tuple[int, ...] | None = -1,
where: ArrayLike | None = None) -> Array:
r"""Softmax function.
Computes the function which rescales elements to the range :math:`[0, 1]`
such that the elements along :code:`axis` sum to :math:`1`.
.. math ::
\mathr... | Softmax function.
Computes the function which rescales elements to the range :math:`[0, 1]`
such that the elements along :code:`axis` sum to :math:`1`.
.. math ::
\mathrm{softmax}(x) = \frac{\exp(x_i)}{\sum_j \exp(x_j)}
Args:
x : input array
axis: the axis or axes along which the softmax should b... | softmax | python | jax-ml/jax | jax/_src/nn/functions.py | https://github.com/jax-ml/jax/blob/master/jax/_src/nn/functions.py | Apache-2.0 |
def standardize(x: ArrayLike,
axis: int | tuple[int, ...] | None = -1,
mean: ArrayLike | None = None,
variance: ArrayLike | None = None,
epsilon: ArrayLike = 1e-5,
where: ArrayLike | None = None) -> Array:
r"""Standardizes input to zero m... | Standardizes input to zero mean and unit variance.
The standardization is given by:
.. math::
x_{std} = \frac{x - \langle x\rangle}{\sqrt{\langle(x - \langle x\rangle)^2\rangle + \epsilon}}
where :math:`\langle x\rangle` indicates the mean of :math:`x`, and :math:`\epsilon` is
a small correction factor... | standardize | python | jax-ml/jax | jax/_src/nn/functions.py | https://github.com/jax-ml/jax/blob/master/jax/_src/nn/functions.py | Apache-2.0 |
def one_hot(x: Any, num_classes: int, *,
dtype: Any = jnp.float_, axis: int | AxisName = -1) -> Array:
"""One-hot encodes the given indices.
Each index in the input ``x`` is encoded as a vector of zeros of length
``num_classes`` with the element at ``index`` set to one::
>>> jax.nn.one_hot(jnp.a... | One-hot encodes the given indices.
Each index in the input ``x`` is encoded as a vector of zeros of length
``num_classes`` with the element at ``index`` set to one::
>>> jax.nn.one_hot(jnp.array([0, 1, 2]), 3)
Array([[1., 0., 0.],
[0., 1., 0.],
[0., 0., 1.]], dtype=float32)
Indice... | one_hot | python | jax-ml/jax | jax/_src/nn/functions.py | https://github.com/jax-ml/jax/blob/master/jax/_src/nn/functions.py | Apache-2.0 |
def hard_silu(x: ArrayLike) -> Array:
r"""Hard SiLU (swish) activation function
Computes the element-wise function
.. math::
\mathrm{hard\_silu}(x) = x \cdot \mathrm{hard\_sigmoid}(x)
Both :func:`hard_silu` and :func:`hard_swish` are aliases for the same
function.
Args:
x : input array
Return... | Hard SiLU (swish) activation function
Computes the element-wise function
.. math::
\mathrm{hard\_silu}(x) = x \cdot \mathrm{hard\_sigmoid}(x)
Both :func:`hard_silu` and :func:`hard_swish` are aliases for the same
function.
Args:
x : input array
Returns:
An array.
See also:
:func:`har... | hard_silu | python | jax-ml/jax | jax/_src/nn/functions.py | https://github.com/jax-ml/jax/blob/master/jax/_src/nn/functions.py | Apache-2.0 |
def dot_product_attention(
query: ArrayLike,
key: ArrayLike,
value: ArrayLike,
bias: ArrayLike | None = None,
mask: ArrayLike | None = None,
*,
scale: float | None = None,
is_causal: bool = False,
query_seq_lengths: ArrayLike | None = None,
key_value_seq_lengths: ArrayLike | None... | Scaled dot product attention function.
Computes the attention function on Query, Key, and Value tensors:
.. math::
\mathrm{Attention}(Q, K, V)=\mathrm{softmax}(\frac{QK^T}{\sqrt{d_k}})V
If we define :code:`logits` as the output of :math:`QK^T` and the
:code:`probs` as the output of :math:`softmax`.
T... | dot_product_attention | python | jax-ml/jax | jax/_src/nn/functions.py | https://github.com/jax-ml/jax/blob/master/jax/_src/nn/functions.py | Apache-2.0 |
def scaled_matmul(
lhs: Array,
rhs: Array,
lhs_scales: Array,
rhs_scales: Array,
preferred_element_type: DTypeLike = jnp.float32,
) -> Array:
r"""Scaled matrix multiplication function.
Performs block-scaled matmul of `a` and `b` using `a_scales` and `b_scales`.
The last dim is the contr... | Scaled matrix multiplication function.
Performs block-scaled matmul of `a` and `b` using `a_scales` and `b_scales`.
The last dim is the contracting dim, and block size is inferred.
Mathematically, this operation is equivalent to::
a_block_size = a.shape[-1] // a_scales.shape[-1]
b_block_size ... | scaled_matmul | python | jax-ml/jax | jax/_src/nn/functions.py | https://github.com/jax-ml/jax/blob/master/jax/_src/nn/functions.py | Apache-2.0 |
def get_scaled_dot_general_config(mode: Literal['nvfp4', 'mxfp8'],
global_scale: Array | None = None):
r"""Get quantization configs for scaled_dot_general.
Create quantization configs for the `jax.nn.scaled_dot_general`.
See Also:
- :func:`jax.nn.scaled_dot_general`... | Get quantization configs for scaled_dot_general.
Create quantization configs for the `jax.nn.scaled_dot_general`.
See Also:
- :func:`jax.nn.scaled_dot_general`: Scaled dot general function.
| get_scaled_dot_general_config | python | jax-ml/jax | jax/_src/nn/functions.py | https://github.com/jax-ml/jax/blob/master/jax/_src/nn/functions.py | Apache-2.0 |
def scaled_dot_general(
lhs, rhs,
dimension_numbers,
preferred_element_type=jnp.float32,
configs: List[BlockScaleConfig] | None = None,
implementation: Literal['cudnn'] | None = None,
):
r"""Scaled dot general operation.
Performs a generalized dot product with block-scaled quantization on the... | Scaled dot general operation.
Performs a generalized dot product with block-scaled quantization on the
lhs and rhs inputs. This operation extends `lax.dot_general` to support
user-defined scaling configurations.
Essentially, the operation follows::
a, a_scales = quantize(lhs, configs[0])
b, b_sca... | scaled_dot_general | python | jax-ml/jax | jax/_src/nn/functions.py | https://github.com/jax-ml/jax/blob/master/jax/_src/nn/functions.py | Apache-2.0 |
def zeros(key: Array,
shape: core.Shape,
dtype: DTypeLikeInexact = jnp.float_) -> Array:
"""An initializer that returns a constant array full of zeros.
The ``key`` argument is ignored.
>>> import jax, jax.numpy as jnp
>>> jax.nn.initializers.zeros(jax.random.key(42), (2, 3), jnp.float32)
... | An initializer that returns a constant array full of zeros.
The ``key`` argument is ignored.
>>> import jax, jax.numpy as jnp
>>> jax.nn.initializers.zeros(jax.random.key(42), (2, 3), jnp.float32)
Array([[0., 0., 0.],
[0., 0., 0.]], dtype=float32)
| zeros | python | jax-ml/jax | jax/_src/nn/initializers.py | https://github.com/jax-ml/jax/blob/master/jax/_src/nn/initializers.py | Apache-2.0 |
def ones(key: Array,
shape: core.Shape,
dtype: DTypeLikeInexact = jnp.float_) -> Array:
"""An initializer that returns a constant array full of ones.
The ``key`` argument is ignored.
>>> import jax, jax.numpy as jnp
>>> jax.nn.initializers.ones(jax.random.key(42), (3, 2), jnp.float32)
Arra... | An initializer that returns a constant array full of ones.
The ``key`` argument is ignored.
>>> import jax, jax.numpy as jnp
>>> jax.nn.initializers.ones(jax.random.key(42), (3, 2), jnp.float32)
Array([[1., 1.],
[1., 1.],
[1., 1.]], dtype=float32)
| ones | python | jax-ml/jax | jax/_src/nn/initializers.py | https://github.com/jax-ml/jax/blob/master/jax/_src/nn/initializers.py | Apache-2.0 |
def constant(value: ArrayLike,
dtype: DTypeLikeInexact = jnp.float_
) -> Initializer:
"""Builds an initializer that returns arrays full of a constant ``value``.
Args:
value: the constant value with which to fill the initializer.
dtype: optional; the initializer's default dtype.
... | Builds an initializer that returns arrays full of a constant ``value``.
Args:
value: the constant value with which to fill the initializer.
dtype: optional; the initializer's default dtype.
>>> import jax, jax.numpy as jnp
>>> initializer = jax.nn.initializers.constant(-7)
>>> initializer(jax.random.k... | constant | python | jax-ml/jax | jax/_src/nn/initializers.py | https://github.com/jax-ml/jax/blob/master/jax/_src/nn/initializers.py | Apache-2.0 |
def uniform(scale: RealNumeric = 1e-2,
dtype: DTypeLikeInexact = jnp.float_) -> Initializer:
"""Builds an initializer that returns real uniformly-distributed random arrays.
Args:
scale: optional; the upper bound of the random distribution.
dtype: optional; the initializer's default dtype.
Re... | Builds an initializer that returns real uniformly-distributed random arrays.
Args:
scale: optional; the upper bound of the random distribution.
dtype: optional; the initializer's default dtype.
Returns:
An initializer that returns arrays whose values are uniformly distributed in
the range ``[0, sc... | uniform | python | jax-ml/jax | jax/_src/nn/initializers.py | https://github.com/jax-ml/jax/blob/master/jax/_src/nn/initializers.py | Apache-2.0 |
def normal(stddev: RealNumeric = 1e-2,
dtype: DTypeLikeInexact = jnp.float_) -> Initializer:
"""Builds an initializer that returns real normally-distributed random arrays.
Args:
stddev: optional; the standard deviation of the distribution.
dtype: optional; the initializer's default dtype.
Ret... | Builds an initializer that returns real normally-distributed random arrays.
Args:
stddev: optional; the standard deviation of the distribution.
dtype: optional; the initializer's default dtype.
Returns:
An initializer that returns arrays whose values are normally distributed
with mean ``0`` and st... | normal | python | jax-ml/jax | jax/_src/nn/initializers.py | https://github.com/jax-ml/jax/blob/master/jax/_src/nn/initializers.py | Apache-2.0 |
def truncated_normal(stddev: RealNumeric = 1e-2,
dtype: DTypeLikeInexact = jnp.float_,
lower: RealNumeric = -2.0,
upper: RealNumeric = 2.0) -> Initializer:
r"""Builds an initializer that returns truncated-normal random arrays.
Args:
stddev: optiona... | Builds an initializer that returns truncated-normal random arrays.
Args:
stddev: optional; the standard deviation of the untruncated distribution.
Note that this function does not apply the stddev correction as is done in
the variancescaling initializers, and users are expected to apply this
co... | truncated_normal | python | jax-ml/jax | jax/_src/nn/initializers.py | https://github.com/jax-ml/jax/blob/master/jax/_src/nn/initializers.py | Apache-2.0 |
def _compute_fans(shape: Sequence[int],
in_axis: int | Sequence[int] = -2,
out_axis: int | Sequence[int] = -1,
batch_axis: int | Sequence[int] = ()
) -> tuple[float, float]:
"""
Compute effective input and output sizes for a linear or convoluti... |
Compute effective input and output sizes for a linear or convolutional layer.
Axes not in in_axis, out_axis, or batch_axis are assumed to constitute the
"receptive field" of a convolution (kernel spatial dimensions).
| _compute_fans | python | jax-ml/jax | jax/_src/nn/initializers.py | https://github.com/jax-ml/jax/blob/master/jax/_src/nn/initializers.py | Apache-2.0 |
def _complex_uniform(key: Array,
shape: Sequence[int],
dtype: DTypeLikeInexact) -> Array:
"""
Sample uniform random values within a disk on the complex plane,
with zero mean and unit variance.
"""
key_r, key_theta = random.split(key)
real_dtype = np.array(0, dtype).... |
Sample uniform random values within a disk on the complex plane,
with zero mean and unit variance.
| _complex_uniform | python | jax-ml/jax | jax/_src/nn/initializers.py | https://github.com/jax-ml/jax/blob/master/jax/_src/nn/initializers.py | Apache-2.0 |
def _complex_truncated_normal(key: Array, upper: ArrayLike,
shape: Sequence[int],
dtype: DTypeLikeInexact) -> Array:
"""
Sample random values from a centered normal distribution on the complex plane,
whose modulus is truncated to `upper`, and the varianc... |
Sample random values from a centered normal distribution on the complex plane,
whose modulus is truncated to `upper`, and the variance before the truncation
is one.
| _complex_truncated_normal | python | jax-ml/jax | jax/_src/nn/initializers.py | https://github.com/jax-ml/jax/blob/master/jax/_src/nn/initializers.py | Apache-2.0 |
def variance_scaling(
scale: RealNumeric,
mode: Literal["fan_in"] | Literal["fan_out"] | Literal["fan_avg"] | Literal["fan_geo_avg"],
distribution: (Literal["truncated_normal"] | Literal["normal"] |
Literal["uniform"]),
in_axis: int | Sequence[int] = -2,
out_axis: int | Sequence[int] = -... |
Initializer that adapts its scale to the shape of the weights tensor.
With ``distribution="truncated_normal"`` or ``distribution="normal"``, samples
are drawn from a (truncated) normal distribution with a mean of zero
and a standard deviation (after truncation, if applicable) of
:math:`\sqrt{\frac{scale}{n}... | variance_scaling | python | jax-ml/jax | jax/_src/nn/initializers.py | https://github.com/jax-ml/jax/blob/master/jax/_src/nn/initializers.py | Apache-2.0 |
def glorot_uniform(in_axis: int | Sequence[int] = -2,
out_axis: int | Sequence[int] = -1,
batch_axis: int | Sequence[int] = (),
dtype: DTypeLikeInexact = jnp.float_) -> Initializer:
"""Builds a Glorot uniform initializer (aka Xavier uniform initializer).
A `... | Builds a Glorot uniform initializer (aka Xavier uniform initializer).
A `Glorot uniform initializer`_ is a specialization of
:func:`jax.nn.initializers.variance_scaling` where ``scale = 1.0``,
``mode="fan_avg"``, and ``distribution="uniform"``.
Args:
in_axis: axis or sequence of axes of the input dimensio... | glorot_uniform | python | jax-ml/jax | jax/_src/nn/initializers.py | https://github.com/jax-ml/jax/blob/master/jax/_src/nn/initializers.py | Apache-2.0 |
def glorot_normal(in_axis: int | Sequence[int] = -2,
out_axis: int | Sequence[int] = -1,
batch_axis: int | Sequence[int] = (),
dtype: DTypeLikeInexact = jnp.float_) -> Initializer:
"""Builds a Glorot normal initializer (aka Xavier normal initializer).
A `Glorot... | Builds a Glorot normal initializer (aka Xavier normal initializer).
A `Glorot normal initializer`_ is a specialization of
:func:`jax.nn.initializers.variance_scaling` where ``scale = 1.0``,
``mode="fan_avg"``, and ``distribution="truncated_normal"``.
Args:
in_axis: axis or sequence of axes of the input di... | glorot_normal | python | jax-ml/jax | jax/_src/nn/initializers.py | https://github.com/jax-ml/jax/blob/master/jax/_src/nn/initializers.py | Apache-2.0 |
def lecun_uniform(in_axis: int | Sequence[int] = -2,
out_axis: int | Sequence[int] = -1,
batch_axis: int | Sequence[int] = (),
dtype: DTypeLikeInexact = jnp.float_) -> Initializer:
"""Builds a Lecun uniform initializer.
A `Lecun uniform initializer`_ is a speci... | Builds a Lecun uniform initializer.
A `Lecun uniform initializer`_ is a specialization of
:func:`jax.nn.initializers.variance_scaling` where ``scale = 1.0``,
``mode="fan_in"``, and ``distribution="uniform"``.
Args:
in_axis: axis or sequence of axes of the input dimension in the weights
array.
ou... | lecun_uniform | python | jax-ml/jax | jax/_src/nn/initializers.py | https://github.com/jax-ml/jax/blob/master/jax/_src/nn/initializers.py | Apache-2.0 |
def lecun_normal(in_axis: int | Sequence[int] = -2,
out_axis: int | Sequence[int] = -1,
batch_axis: int | Sequence[int] = (),
dtype: DTypeLikeInexact = jnp.float_) -> Initializer:
"""Builds a Lecun normal initializer.
A `Lecun normal initializer`_ is a specializat... | Builds a Lecun normal initializer.
A `Lecun normal initializer`_ is a specialization of
:func:`jax.nn.initializers.variance_scaling` where ``scale = 1.0``,
``mode="fan_in"``, and ``distribution="truncated_normal"``.
Args:
in_axis: axis or sequence of axes of the input dimension in the weights
array.... | lecun_normal | python | jax-ml/jax | jax/_src/nn/initializers.py | https://github.com/jax-ml/jax/blob/master/jax/_src/nn/initializers.py | Apache-2.0 |
def he_uniform(in_axis: int | Sequence[int] = -2,
out_axis: int | Sequence[int] = -1,
batch_axis: int | Sequence[int] = (),
dtype: DTypeLikeInexact = jnp.float_) -> Initializer:
"""Builds a He uniform initializer (aka Kaiming uniform initializer).
A `He uniform initiali... | Builds a He uniform initializer (aka Kaiming uniform initializer).
A `He uniform initializer`_ is a specialization of
:func:`jax.nn.initializers.variance_scaling` where ``scale = 2.0``,
``mode="fan_in"``, and ``distribution="uniform"``.
Args:
in_axis: axis or sequence of axes of the input dimension in the... | he_uniform | python | jax-ml/jax | jax/_src/nn/initializers.py | https://github.com/jax-ml/jax/blob/master/jax/_src/nn/initializers.py | Apache-2.0 |
def he_normal(in_axis: int | Sequence[int] = -2,
out_axis: int | Sequence[int] = -1,
batch_axis: int | Sequence[int] = (),
dtype: DTypeLikeInexact = jnp.float_) -> Initializer:
"""Builds a He normal initializer (aka Kaiming normal initializer).
A `He normal initializer`_ i... | Builds a He normal initializer (aka Kaiming normal initializer).
A `He normal initializer`_ is a specialization of
:func:`jax.nn.initializers.variance_scaling` where ``scale = 2.0``,
``mode="fan_in"``, and ``distribution="truncated_normal"``.
Args:
in_axis: axis or sequence of axes of the input dimension ... | he_normal | python | jax-ml/jax | jax/_src/nn/initializers.py | https://github.com/jax-ml/jax/blob/master/jax/_src/nn/initializers.py | Apache-2.0 |
def orthogonal(scale: RealNumeric = 1.0,
column_axis: int = -1,
dtype: DTypeLikeInexact = jnp.float_) -> Initializer:
"""
Builds an initializer that returns uniformly distributed orthogonal matrices.
If the shape is not square, the matrices will have orthonormal rows or columns
de... |
Builds an initializer that returns uniformly distributed orthogonal matrices.
If the shape is not square, the matrices will have orthonormal rows or columns
depending on which side is smaller.
Args:
scale: the upper bound of the uniform distribution.
column_axis: the axis that contains the columns th... | orthogonal | python | jax-ml/jax | jax/_src/nn/initializers.py | https://github.com/jax-ml/jax/blob/master/jax/_src/nn/initializers.py | Apache-2.0 |
def delta_orthogonal(
scale: RealNumeric = 1.0,
column_axis: int = -1,
dtype: DTypeLikeInexact = jnp.float_) -> Initializer:
"""
Builds an initializer for delta orthogonal kernels.
Args:
scale: the upper bound of the uniform distribution.
column_axis: the axis that contains the columns that should ... |
Builds an initializer for delta orthogonal kernels.
Args:
scale: the upper bound of the uniform distribution.
column_axis: the axis that contains the columns that should be orthogonal.
dtype: the default dtype of the weights.
Returns:
A `delta orthogonal initializer`_. The shape passed to the i... | delta_orthogonal | python | jax-ml/jax | jax/_src/nn/initializers.py | https://github.com/jax-ml/jax/blob/master/jax/_src/nn/initializers.py | Apache-2.0 |
def _get_platform(
device_or_sharding: xc.Device | Sharding | None | str) -> str:
"""Get device_or_sharding platform or look up config.default_device.value."""
if isinstance(device_or_sharding, xc.Device):
return device_or_sharding.platform
elif isinstance(device_or_sharding, Sharding):
return list(de... | Get device_or_sharding platform or look up config.default_device.value. | _get_platform | python | jax-ml/jax | jax/_src/numpy/array.py | https://github.com/jax-ml/jax/blob/master/jax/_src/numpy/array.py | Apache-2.0 |
def __array_namespace__(self, *, api_version: None | str = None) -> ModuleType:
"""Return the `Python array API`_ namespace for JAX.
.. _Python array API: https://data-apis.org/array-api/
"""
if api_version is not None and api_version != __array_api_version__:
raise ValueError(f"{api_version=!r} is not ava... | Return the `Python array API`_ namespace for JAX.
.. _Python array API: https://data-apis.org/array-api/
| __array_namespace__ | python | jax-ml/jax | jax/_src/numpy/array_api_metadata.py | https://github.com/jax-ml/jax/blob/master/jax/_src/numpy/array_api_metadata.py | Apache-2.0 |
def _linspace(start: ArrayLike, stop: ArrayLike, num: int = 50,
endpoint: bool = True, retstep: bool = False,
dtype: DTypeLike | None = None,
axis: int = 0,
*, device: xc.Device | Sharding | None = None) -> Array | tuple[Array, Array]:
"""Implementation of linsp... | Implementation of linspace differentiable in start and stop args. | _linspace | python | jax-ml/jax | jax/_src/numpy/array_creation.py | https://github.com/jax-ml/jax/blob/master/jax/_src/numpy/array_creation.py | Apache-2.0 |
def logspace(start: ArrayLike, stop: ArrayLike, num: int = 50,
endpoint: bool = True, base: ArrayLike = 10.0,
dtype: DTypeLike | None = None, axis: int = 0) -> Array:
"""Generate logarithmically-spaced values.
JAX implementation of :func:`numpy.logspace`.
Args:
start: scalar or arr... | Generate logarithmically-spaced values.
JAX implementation of :func:`numpy.logspace`.
Args:
start: scalar or array. Used to specify the start value. The start value is
``base ** start``.
stop: scalar or array. Used to specify the stop value. The end value is
``base ** stop``.
num: int, opt... | logspace | python | jax-ml/jax | jax/_src/numpy/array_creation.py | https://github.com/jax-ml/jax/blob/master/jax/_src/numpy/array_creation.py | Apache-2.0 |
def _logspace(start: ArrayLike, stop: ArrayLike, num: int = 50,
endpoint: bool = True, base: ArrayLike = 10.0,
dtype: DTypeLike | None = None, axis: int = 0) -> Array:
"""Implementation of logspace differentiable in start and stop args."""
dtypes.check_user_dtype_supported(dtype, "logspa... | Implementation of logspace differentiable in start and stop args. | _logspace | python | jax-ml/jax | jax/_src/numpy/array_creation.py | https://github.com/jax-ml/jax/blob/master/jax/_src/numpy/array_creation.py | Apache-2.0 |
def geomspace(start: ArrayLike, stop: ArrayLike, num: int = 50, endpoint: bool = True,
dtype: DTypeLike | None = None, axis: int = 0) -> Array:
"""Generate geometrically-spaced values.
JAX implementation of :func:`numpy.geomspace`.
Args:
start: scalar or array. Specifies the starting values.
... | Generate geometrically-spaced values.
JAX implementation of :func:`numpy.geomspace`.
Args:
start: scalar or array. Specifies the starting values.
stop: scalar or array. Specifies the stop values.
num: int, optional, default=50. Number of values to generate.
endpoint: bool, optional, default=True. ... | geomspace | python | jax-ml/jax | jax/_src/numpy/array_creation.py | https://github.com/jax-ml/jax/blob/master/jax/_src/numpy/array_creation.py | Apache-2.0 |
def _geomspace(start: ArrayLike, stop: ArrayLike, num: int = 50, endpoint: bool = True,
dtype: DTypeLike | None = None, axis: int = 0) -> Array:
"""Implementation of geomspace differentiable in start and stop args."""
dtypes.check_user_dtype_supported(dtype, "geomspace")
if dtype is None:
dtype... | Implementation of geomspace differentiable in start and stop args. | _geomspace | python | jax-ml/jax | jax/_src/numpy/array_creation.py | https://github.com/jax-ml/jax/blob/master/jax/_src/numpy/array_creation.py | Apache-2.0 |
def _all(self: Array, axis: reductions.Axis = None, out: None = None,
keepdims: bool = False, *, where: ArrayLike | None = None) -> Array:
"""Test whether all array elements along a given axis evaluate to True.
Refer to :func:`jax.numpy.all` for the full documentation.
"""
return reductions.all(self, ... | Test whether all array elements along a given axis evaluate to True.
Refer to :func:`jax.numpy.all` for the full documentation.
| _all | python | jax-ml/jax | jax/_src/numpy/array_methods.py | https://github.com/jax-ml/jax/blob/master/jax/_src/numpy/array_methods.py | Apache-2.0 |
def _any(self: Array, axis: reductions.Axis = None, out: None = None,
keepdims: bool = False, *, where: ArrayLike | None = None) -> Array:
"""Test whether any array elements along a given axis evaluate to True.
Refer to :func:`jax.numpy.any` for the full documentation.
"""
return reductions.any(self, ... | Test whether any array elements along a given axis evaluate to True.
Refer to :func:`jax.numpy.any` for the full documentation.
| _any | python | jax-ml/jax | jax/_src/numpy/array_methods.py | https://github.com/jax-ml/jax/blob/master/jax/_src/numpy/array_methods.py | Apache-2.0 |
def _argmax(self: Array, axis: int | None = None, out: None = None,
keepdims: bool | None = None) -> Array:
"""Return the index of the maximum value.
Refer to :func:`jax.numpy.argmax` for the full documentation.
"""
return lax_numpy.argmax(self, axis=axis, out=out, keepdims=keepdims) | Return the index of the maximum value.
Refer to :func:`jax.numpy.argmax` for the full documentation.
| _argmax | python | jax-ml/jax | jax/_src/numpy/array_methods.py | https://github.com/jax-ml/jax/blob/master/jax/_src/numpy/array_methods.py | Apache-2.0 |
def _argmin(self: Array, axis: int | None = None, out: None = None,
keepdims: bool | None = None) -> Array:
"""Return the index of the minimum value.
Refer to :func:`jax.numpy.argmin` for the full documentation.
"""
return lax_numpy.argmin(self, axis=axis, out=out, keepdims=keepdims) | Return the index of the minimum value.
Refer to :func:`jax.numpy.argmin` for the full documentation.
| _argmin | python | jax-ml/jax | jax/_src/numpy/array_methods.py | https://github.com/jax-ml/jax/blob/master/jax/_src/numpy/array_methods.py | Apache-2.0 |
def _argsort(self: Array, axis: int | None = -1, *, kind: None = None, order: None = None,
stable: bool = True, descending: bool = False) -> Array:
"""Return the indices that sort the array.
Refer to :func:`jax.numpy.argsort` for the full documentation.
"""
return lax_numpy.argsort(self, axis=axis... | Return the indices that sort the array.
Refer to :func:`jax.numpy.argsort` for the full documentation.
| _argsort | python | jax-ml/jax | jax/_src/numpy/array_methods.py | https://github.com/jax-ml/jax/blob/master/jax/_src/numpy/array_methods.py | Apache-2.0 |
def _astype(self: Array, dtype: DTypeLike | None, copy: bool = False,
device: xc.Device | Sharding | None = None) -> Array:
"""Copy the array and cast to a specified dtype.
This is implemented via :func:`jax.lax.convert_element_type`, which may
have slightly different behavior than :meth:`numpy.ndarr... | Copy the array and cast to a specified dtype.
This is implemented via :func:`jax.lax.convert_element_type`, which may
have slightly different behavior than :meth:`numpy.ndarray.astype` in
some cases. In particular, the details of float-to-int and int-to-float
casts are implementation dependent.
| _astype | python | jax-ml/jax | jax/_src/numpy/array_methods.py | https://github.com/jax-ml/jax/blob/master/jax/_src/numpy/array_methods.py | Apache-2.0 |
def _compress(self: Array, condition: ArrayLike,
axis: int | None = None, *, out: None = None,
size: int | None = None, fill_value: ArrayLike = 0) -> Array:
"""Return selected slices of this array along given axis.
Refer to :func:`jax.numpy.compress` for full documentation.
"""
retu... | Return selected slices of this array along given axis.
Refer to :func:`jax.numpy.compress` for full documentation.
| _compress | python | jax-ml/jax | jax/_src/numpy/array_methods.py | https://github.com/jax-ml/jax/blob/master/jax/_src/numpy/array_methods.py | Apache-2.0 |
def _cumprod(self: Array, axis: reductions.Axis = None, dtype: DTypeLike | None = None,
out: None = None) -> Array:
"""Return the cumulative product of the array.
Refer to :func:`jax.numpy.cumprod` for the full documentation.
"""
return reductions.cumprod(self, axis=axis, dtype=dtype, out=out) | Return the cumulative product of the array.
Refer to :func:`jax.numpy.cumprod` for the full documentation.
| _cumprod | python | jax-ml/jax | jax/_src/numpy/array_methods.py | https://github.com/jax-ml/jax/blob/master/jax/_src/numpy/array_methods.py | Apache-2.0 |
def _cumsum(self: Array, axis: reductions.Axis = None, dtype: DTypeLike | None = None,
out: None = None) -> Array:
"""Return the cumulative sum of the array.
Refer to :func:`jax.numpy.cumsum` for the full documentation.
"""
return reductions.cumsum(self, axis=axis, dtype=dtype, out=out) | Return the cumulative sum of the array.
Refer to :func:`jax.numpy.cumsum` for the full documentation.
| _cumsum | python | jax-ml/jax | jax/_src/numpy/array_methods.py | https://github.com/jax-ml/jax/blob/master/jax/_src/numpy/array_methods.py | Apache-2.0 |
def _dot(self: Array, b: ArrayLike, *, precision: lax_internal.PrecisionLike = None,
preferred_element_type: DTypeLike | None = None) -> Array:
"""Compute the dot product of two arrays.
Refer to :func:`jax.numpy.dot` for the full documentation.
"""
return tensor_contractions.dot(self, b, precision=pre... | Compute the dot product of two arrays.
Refer to :func:`jax.numpy.dot` for the full documentation.
| _dot | python | jax-ml/jax | jax/_src/numpy/array_methods.py | https://github.com/jax-ml/jax/blob/master/jax/_src/numpy/array_methods.py | Apache-2.0 |
def _item(self: Array, *args: int) -> bool | int | float | complex:
"""Copy an element of an array to a standard Python scalar and return it."""
arr = core.concrete_or_error(np.asarray, self, context="This occurred in the item() method of jax.Array")
if dtypes.issubdtype(self.dtype, dtypes.extended):
raise Ty... | Copy an element of an array to a standard Python scalar and return it. | _item | python | jax-ml/jax | jax/_src/numpy/array_methods.py | https://github.com/jax-ml/jax/blob/master/jax/_src/numpy/array_methods.py | Apache-2.0 |
def _max(self: Array, axis: reductions.Axis = None, out: None = None,
keepdims: bool = False, initial: ArrayLike | None = None,
where: ArrayLike | None = None) -> Array:
"""Return the maximum of array elements along a given axis.
Refer to :func:`jax.numpy.max` for the full documentation.
"""
... | Return the maximum of array elements along a given axis.
Refer to :func:`jax.numpy.max` for the full documentation.
| _max | python | jax-ml/jax | jax/_src/numpy/array_methods.py | https://github.com/jax-ml/jax/blob/master/jax/_src/numpy/array_methods.py | Apache-2.0 |
def _mean(self: Array, axis: reductions.Axis = None, dtype: DTypeLike | None = None,
out: None = None, keepdims: bool = False, *,
where: ArrayLike | None = None) -> Array:
"""Return the mean of array elements along a given axis.
Refer to :func:`jax.numpy.mean` for the full documentation.
"""
... | Return the mean of array elements along a given axis.
Refer to :func:`jax.numpy.mean` for the full documentation.
| _mean | python | jax-ml/jax | jax/_src/numpy/array_methods.py | https://github.com/jax-ml/jax/blob/master/jax/_src/numpy/array_methods.py | Apache-2.0 |
def _min(self: Array, axis: reductions.Axis = None, out: None = None,
keepdims: bool = False, initial: ArrayLike | None = None,
where: ArrayLike | None = None) -> Array:
"""Return the minimum of array elements along a given axis.
Refer to :func:`jax.numpy.min` for the full documentation.
"""
... | Return the minimum of array elements along a given axis.
Refer to :func:`jax.numpy.min` for the full documentation.
| _min | python | jax-ml/jax | jax/_src/numpy/array_methods.py | https://github.com/jax-ml/jax/blob/master/jax/_src/numpy/array_methods.py | Apache-2.0 |
def _nonzero(self: Array, *, fill_value: None | ArrayLike | tuple[ArrayLike, ...] = None,
size: int | None = None) -> tuple[Array, ...]:
"""Return indices of nonzero elements of an array.
Refer to :func:`jax.numpy.nonzero` for the full documentation.
"""
return lax_numpy.nonzero(self, size=size, f... | Return indices of nonzero elements of an array.
Refer to :func:`jax.numpy.nonzero` for the full documentation.
| _nonzero | python | jax-ml/jax | jax/_src/numpy/array_methods.py | https://github.com/jax-ml/jax/blob/master/jax/_src/numpy/array_methods.py | Apache-2.0 |
def _prod(self: Array, axis: reductions.Axis = None, dtype: DTypeLike | None = None,
out: None = None, keepdims: bool = False,
initial: ArrayLike | None = None, where: ArrayLike | None = None,
promote_integers: bool = True) -> Array:
"""Return product of the array elements over a given a... | Return product of the array elements over a given axis.
Refer to :func:`jax.numpy.prod` for the full documentation.
| _prod | python | jax-ml/jax | jax/_src/numpy/array_methods.py | https://github.com/jax-ml/jax/blob/master/jax/_src/numpy/array_methods.py | Apache-2.0 |
def _ptp(self: Array, axis: reductions.Axis = None, out: None = None,
keepdims: bool = False) -> Array:
"""Return the peak-to-peak range along a given axis.
Refer to :func:`jax.numpy.ptp` for the full documentation.
"""
return reductions.ptp(self, axis=axis, out=out, keepdims=keepdims) | Return the peak-to-peak range along a given axis.
Refer to :func:`jax.numpy.ptp` for the full documentation.
| _ptp | python | jax-ml/jax | jax/_src/numpy/array_methods.py | https://github.com/jax-ml/jax/blob/master/jax/_src/numpy/array_methods.py | Apache-2.0 |
def _repeat(self: Array, repeats: ArrayLike, axis: int | None = None, *,
total_repeat_length: int | None = None,
out_sharding: NamedSharding | PartitionSpec | None = None) -> Array:
"""Construct an array from repeated elements.
Refer to :func:`jax.numpy.repeat` for the full documentation.
... | Construct an array from repeated elements.
Refer to :func:`jax.numpy.repeat` for the full documentation.
| _repeat | python | jax-ml/jax | jax/_src/numpy/array_methods.py | https://github.com/jax-ml/jax/blob/master/jax/_src/numpy/array_methods.py | Apache-2.0 |
def _reshape(self: Array, *args: Any, order: str = "C", out_sharding=None
) -> Array:
"""Returns an array containing the same data with a new shape.
Refer to :func:`jax.numpy.reshape` for full documentation.
"""
__tracebackhide__ = True
newshape = _compute_newshape(self, args[0] if len(args) == ... | Returns an array containing the same data with a new shape.
Refer to :func:`jax.numpy.reshape` for full documentation.
| _reshape | python | jax-ml/jax | jax/_src/numpy/array_methods.py | https://github.com/jax-ml/jax/blob/master/jax/_src/numpy/array_methods.py | Apache-2.0 |
def _searchsorted(self: Array, v: ArrayLike, side: str = 'left',
sorter: ArrayLike | None = None, *, method: str = 'scan') -> Array:
"""Perform a binary search within a sorted array.
Refer to :func:`jax.numpy.searchsorted` for full documentation."""
return lax_numpy.searchsorted(self, v, side=s... | Perform a binary search within a sorted array.
Refer to :func:`jax.numpy.searchsorted` for full documentation. | _searchsorted | python | jax-ml/jax | jax/_src/numpy/array_methods.py | https://github.com/jax-ml/jax/blob/master/jax/_src/numpy/array_methods.py | Apache-2.0 |
def _sort(self: Array, axis: int | None = -1, *, kind: None = None,
order: None = None, stable: bool = True, descending: bool = False) -> Array:
"""Return a sorted copy of an array.
Refer to :func:`jax.numpy.sort` for full documentation.
"""
return lax_numpy.sort(self, axis=axis, kind=kind, order=ord... | Return a sorted copy of an array.
Refer to :func:`jax.numpy.sort` for full documentation.
| _sort | python | jax-ml/jax | jax/_src/numpy/array_methods.py | https://github.com/jax-ml/jax/blob/master/jax/_src/numpy/array_methods.py | Apache-2.0 |
def _std(self: Array, axis: reductions.Axis = None, dtype: DTypeLike | None = None,
out: None = None, ddof: int = 0, keepdims: bool = False, *,
where: ArrayLike | None = None, correction: int | float | None = None) -> Array:
"""Compute the standard deviation along a given axis.
Refer to :func:`ja... | Compute the standard deviation along a given axis.
Refer to :func:`jax.numpy.std` for full documentation.
| _std | python | jax-ml/jax | jax/_src/numpy/array_methods.py | https://github.com/jax-ml/jax/blob/master/jax/_src/numpy/array_methods.py | Apache-2.0 |
def _sum(self: Array, axis: reductions.Axis = None, dtype: DTypeLike | None = None,
out: None = None, keepdims: bool = False, initial: ArrayLike | None = None,
where: ArrayLike | None = None, promote_integers: bool = True) -> Array:
"""Sum of the elements of the array over a given axis.
Refer to ... | Sum of the elements of the array over a given axis.
Refer to :func:`jax.numpy.sum` for full documentation.
| _sum | python | jax-ml/jax | jax/_src/numpy/array_methods.py | https://github.com/jax-ml/jax/blob/master/jax/_src/numpy/array_methods.py | Apache-2.0 |
def _take(self: Array, indices: ArrayLike, axis: int | None = None, out: None = None,
mode: str | None = None, unique_indices: bool = False, indices_are_sorted: bool = False,
fill_value: StaticScalar | None = None) -> Array:
"""Take elements from an array.
Refer to :func:`jax.numpy.take` for fu... | Take elements from an array.
Refer to :func:`jax.numpy.take` for full documentation.
| _take | python | jax-ml/jax | jax/_src/numpy/array_methods.py | https://github.com/jax-ml/jax/blob/master/jax/_src/numpy/array_methods.py | Apache-2.0 |
def _trace(self: Array, offset: int | ArrayLike = 0, axis1: int = 0, axis2: int = 1,
dtype: DTypeLike | None = None, out: None = None) -> Array:
"""Return the sum along the diagonal.
Refer to :func:`jax.numpy.trace` for full documentation.
"""
return lax_numpy.trace(self, offset=offset, axis1=axis1,... | Return the sum along the diagonal.
Refer to :func:`jax.numpy.trace` for full documentation.
| _trace | python | jax-ml/jax | jax/_src/numpy/array_methods.py | https://github.com/jax-ml/jax/blob/master/jax/_src/numpy/array_methods.py | Apache-2.0 |
def _transpose(self: Array, *args: Any) -> Array:
"""Returns a copy of the array with axes transposed.
Refer to :func:`jax.numpy.transpose` for full documentation.
"""
if not args:
axis = None
elif len(args) == 1:
axis = args[0] if args[0] is None else _ensure_index_tuple(args[0])
else:
axis = ... | Returns a copy of the array with axes transposed.
Refer to :func:`jax.numpy.transpose` for full documentation.
| _transpose | python | jax-ml/jax | jax/_src/numpy/array_methods.py | https://github.com/jax-ml/jax/blob/master/jax/_src/numpy/array_methods.py | Apache-2.0 |
def _var(self: Array, axis: reductions.Axis = None, dtype: DTypeLike | None = None,
out: None = None, ddof: int = 0, keepdims: bool = False, *,
where: ArrayLike | None = None, correction: int | float | None = None) -> Array:
"""Compute the variance along a given axis.
Refer to :func:`jax.numpy.va... | Compute the variance along a given axis.
Refer to :func:`jax.numpy.var` for full documentation.
| _var | python | jax-ml/jax | jax/_src/numpy/array_methods.py | https://github.com/jax-ml/jax/blob/master/jax/_src/numpy/array_methods.py | Apache-2.0 |
def _compute_newshape(arr: Array, newshape: DimSize | Shape) -> Shape:
"""Fixes a -1 value in newshape, if present."""
orig_newshape = newshape # for error messages
try:
iter(newshape) # type: ignore[arg-type]
except:
newshape = [newshape]
newshape = core.canonicalize_shape(newshape) # type: ignore... | Fixes a -1 value in newshape, if present. | _compute_newshape | python | jax-ml/jax | jax/_src/numpy/array_methods.py | https://github.com/jax-ml/jax/blob/master/jax/_src/numpy/array_methods.py | Apache-2.0 |
def _view(self: Array, dtype: DTypeLike | None = None, type: None = None) -> Array:
"""Return a bitwise copy of the array, viewed as a new dtype.
This is fuller-featured wrapper around :func:`jax.lax.bitcast_convert_type`.
If the source and target dtype have the same bitwidth, the result has the same
shape as... | Return a bitwise copy of the array, viewed as a new dtype.
This is fuller-featured wrapper around :func:`jax.lax.bitcast_convert_type`.
If the source and target dtype have the same bitwidth, the result has the same
shape as the input array. If the bitwidth of the target dtype is different
from the source, the... | _view | python | jax-ml/jax | jax/_src/numpy/array_methods.py | https://github.com/jax-ml/jax/blob/master/jax/_src/numpy/array_methods.py | Apache-2.0 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.