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 frexp(x: ArrayLike, /) -> tuple[Array, Array]:
"""Split floating point values into mantissa and twos exponent.
JAX implementation of :func:`numpy.frexp`.
Args:
x: real-valued array
Returns:
A tuple ``(mantissa, exponent)`` where ``mantissa`` is a floating point
value between -1 and 1, and ``e... | Split floating point values into mantissa and twos exponent.
JAX implementation of :func:`numpy.frexp`.
Args:
x: real-valued array
Returns:
A tuple ``(mantissa, exponent)`` where ``mantissa`` is a floating point
value between -1 and 1, and ``exponent`` is an integer such that
``x == mantissa * ... | frexp | python | jax-ml/jax | jax/_src/numpy/ufuncs.py | https://github.com/jax-ml/jax/blob/master/jax/_src/numpy/ufuncs.py | Apache-2.0 |
def remainder(x1: ArrayLike, x2: ArrayLike, /) -> Array:
"""Returns element-wise remainder of the division.
JAX implementation of :obj:`numpy.remainder`.
Args:
x1: scalar or array. Specifies the dividend.
x2: scalar or array. Specifies the divisor. ``x1`` and ``x2`` should either
have same shape o... | Returns element-wise remainder of the division.
JAX implementation of :obj:`numpy.remainder`.
Args:
x1: scalar or array. Specifies the dividend.
x2: scalar or array. Specifies the divisor. ``x1`` and ``x2`` should either
have same shape or be broadcast compatible.
Returns:
An array containing... | remainder | python | jax-ml/jax | jax/_src/numpy/ufuncs.py | https://github.com/jax-ml/jax/blob/master/jax/_src/numpy/ufuncs.py | Apache-2.0 |
def fmod(x1: ArrayLike, x2: ArrayLike, /) -> Array:
"""Calculate element-wise floating-point modulo operation.
JAX implementation of :obj:`numpy.fmod`.
Args:
x1: scalar or array. Specifies the dividend.
x2: scalar or array. Specifies the divisor. ``x1`` and ``x2`` should either
have same shape or... | Calculate element-wise floating-point modulo operation.
JAX implementation of :obj:`numpy.fmod`.
Args:
x1: scalar or array. Specifies the dividend.
x2: scalar or array. Specifies the divisor. ``x1`` and ``x2`` should either
have same shape or be broadcast compatible.
Returns:
An array contai... | fmod | python | jax-ml/jax | jax/_src/numpy/ufuncs.py | https://github.com/jax-ml/jax/blob/master/jax/_src/numpy/ufuncs.py | Apache-2.0 |
def square(x: ArrayLike, /) -> Array:
"""Calculate element-wise square of the input array.
JAX implementation of :obj:`numpy.square`.
Args:
x: input array or scalar.
Returns:
An array containing the square of the elements of ``x``.
Note:
``jnp.square`` is equivalent to computing ``jnp.power(x,... | Calculate element-wise square of the input array.
JAX implementation of :obj:`numpy.square`.
Args:
x: input array or scalar.
Returns:
An array containing the square of the elements of ``x``.
Note:
``jnp.square`` is equivalent to computing ``jnp.power(x, 2)``.
See also:
- :func:`jax.numpy.... | square | python | jax-ml/jax | jax/_src/numpy/ufuncs.py | https://github.com/jax-ml/jax/blob/master/jax/_src/numpy/ufuncs.py | Apache-2.0 |
def deg2rad(x: ArrayLike, /) -> Array:
r"""Convert angles from degrees to radians.
JAX implementation of :obj:`numpy.deg2rad`.
The angle in degrees is converted to radians by:
.. math::
deg2rad(x) = x * \frac{pi}{180}
Args:
x: scalar or array. Specifies the angle in degrees.
Returns:
An a... | Convert angles from degrees to radians.
JAX implementation of :obj:`numpy.deg2rad`.
The angle in degrees is converted to radians by:
.. math::
deg2rad(x) = x * \frac{pi}{180}
Args:
x: scalar or array. Specifies the angle in degrees.
Returns:
An array containing the angles in radians.
See... | deg2rad | python | jax-ml/jax | jax/_src/numpy/ufuncs.py | https://github.com/jax-ml/jax/blob/master/jax/_src/numpy/ufuncs.py | Apache-2.0 |
def rad2deg(x: ArrayLike, /) -> Array:
r"""Convert angles from radians to degrees.
JAX implementation of :obj:`numpy.rad2deg`.
The angle in radians is converted to degrees by:
.. math::
rad2deg(x) = x * \frac{180}{pi}
Args:
x: scalar or array. Specifies the angle in radians.
Returns:
An a... | Convert angles from radians to degrees.
JAX implementation of :obj:`numpy.rad2deg`.
The angle in radians is converted to degrees by:
.. math::
rad2deg(x) = x * \frac{180}{pi}
Args:
x: scalar or array. Specifies the angle in radians.
Returns:
An array containing the angles in degrees.
See... | rad2deg | python | jax-ml/jax | jax/_src/numpy/ufuncs.py | https://github.com/jax-ml/jax/blob/master/jax/_src/numpy/ufuncs.py | Apache-2.0 |
def conjugate(x: ArrayLike, /) -> Array:
"""Return element-wise complex-conjugate of the input.
JAX implementation of :obj:`numpy.conjugate`.
Args:
x: inpuat array or scalar.
Returns:
An array containing the complex-conjugate of ``x``.
See also:
- :func:`jax.numpy.real`: Returns the element-wi... | Return element-wise complex-conjugate of the input.
JAX implementation of :obj:`numpy.conjugate`.
Args:
x: inpuat array or scalar.
Returns:
An array containing the complex-conjugate of ``x``.
See also:
- :func:`jax.numpy.real`: Returns the element-wise real part of the complex
argument.
... | conjugate | python | jax-ml/jax | jax/_src/numpy/ufuncs.py | https://github.com/jax-ml/jax/blob/master/jax/_src/numpy/ufuncs.py | Apache-2.0 |
def imag(val: ArrayLike, /) -> Array:
"""Return element-wise imaginary of part of the complex argument.
JAX implementation of :obj:`numpy.imag`.
Args:
val: input array or scalar.
Returns:
An array containing the imaginary part of the elements of ``val``.
See also:
- :func:`jax.numpy.conjugate`... | Return element-wise imaginary of part of the complex argument.
JAX implementation of :obj:`numpy.imag`.
Args:
val: input array or scalar.
Returns:
An array containing the imaginary part of the elements of ``val``.
See also:
- :func:`jax.numpy.conjugate` and :func:`jax.numpy.conj`: Returns the el... | imag | python | jax-ml/jax | jax/_src/numpy/ufuncs.py | https://github.com/jax-ml/jax/blob/master/jax/_src/numpy/ufuncs.py | Apache-2.0 |
def real(val: ArrayLike, /) -> Array:
"""Return element-wise real part of the complex argument.
JAX implementation of :obj:`numpy.real`.
Args:
val: input array or scalar.
Returns:
An array containing the real part of the elements of ``val``.
See also:
- :func:`jax.numpy.conjugate` and :func:`j... | Return element-wise real part of the complex argument.
JAX implementation of :obj:`numpy.real`.
Args:
val: input array or scalar.
Returns:
An array containing the real part of the elements of ``val``.
See also:
- :func:`jax.numpy.conjugate` and :func:`jax.numpy.conj`: Returns the element-wise
... | real | python | jax-ml/jax | jax/_src/numpy/ufuncs.py | https://github.com/jax-ml/jax/blob/master/jax/_src/numpy/ufuncs.py | Apache-2.0 |
def modf(x: ArrayLike, /, out=None) -> tuple[Array, Array]:
"""Return element-wise fractional and integral parts of the input array.
JAX implementation of :obj:`numpy.modf`.
Args:
x: input array or scalar.
out: Not used by JAX.
Returns:
An array containing the fractional and integral parts of the... | Return element-wise fractional and integral parts of the input array.
JAX implementation of :obj:`numpy.modf`.
Args:
x: input array or scalar.
out: Not used by JAX.
Returns:
An array containing the fractional and integral parts of the elements of ``x``,
promoting dtypes inexact.
See also:
... | modf | python | jax-ml/jax | jax/_src/numpy/ufuncs.py | https://github.com/jax-ml/jax/blob/master/jax/_src/numpy/ufuncs.py | Apache-2.0 |
def isfinite(x: ArrayLike, /) -> Array:
"""Return a boolean array indicating whether each element of input is finite.
JAX implementation of :obj:`numpy.isfinite`.
Args:
x: input array or scalar.
Returns:
A boolean array of same shape as ``x`` containing ``True`` where ``x`` is
not ``inf``, ``-inf... | Return a boolean array indicating whether each element of input is finite.
JAX implementation of :obj:`numpy.isfinite`.
Args:
x: input array or scalar.
Returns:
A boolean array of same shape as ``x`` containing ``True`` where ``x`` is
not ``inf``, ``-inf``, or ``NaN``, and ``False`` otherwise.
S... | isfinite | python | jax-ml/jax | jax/_src/numpy/ufuncs.py | https://github.com/jax-ml/jax/blob/master/jax/_src/numpy/ufuncs.py | Apache-2.0 |
def isinf(x: ArrayLike, /) -> Array:
"""Return a boolean array indicating whether each element of input is infinite.
JAX implementation of :obj:`numpy.isinf`.
Args:
x: input array or scalar.
Returns:
A boolean array of same shape as ``x`` containing ``True`` where ``x`` is
``inf`` or ``-inf``, an... | Return a boolean array indicating whether each element of input is infinite.
JAX implementation of :obj:`numpy.isinf`.
Args:
x: input array or scalar.
Returns:
A boolean array of same shape as ``x`` containing ``True`` where ``x`` is
``inf`` or ``-inf``, and ``False`` otherwise.
See also:
- ... | isinf | python | jax-ml/jax | jax/_src/numpy/ufuncs.py | https://github.com/jax-ml/jax/blob/master/jax/_src/numpy/ufuncs.py | Apache-2.0 |
def isposinf(x, /, out=None):
"""
Return boolean array indicating whether each element of input is positive infinite.
JAX implementation of :obj:`numpy.isposinf`.
Args:
x: input array or scalar. ``complex`` dtype are not supported.
Returns:
A boolean array of same shape as ``x`` containing ``True``... |
Return boolean array indicating whether each element of input is positive infinite.
JAX implementation of :obj:`numpy.isposinf`.
Args:
x: input array or scalar. ``complex`` dtype are not supported.
Returns:
A boolean array of same shape as ``x`` containing ``True`` where ``x`` is
``inf``, and ``... | isposinf | python | jax-ml/jax | jax/_src/numpy/ufuncs.py | https://github.com/jax-ml/jax/blob/master/jax/_src/numpy/ufuncs.py | Apache-2.0 |
def isneginf(x, /, out=None):
"""
Return boolean array indicating whether each element of input is negative infinite.
JAX implementation of :obj:`numpy.isneginf`.
Args:
x: input array or scalar. ``complex`` dtype are not supported.
Returns:
A boolean array of same shape as ``x`` containing ``True``... |
Return boolean array indicating whether each element of input is negative infinite.
JAX implementation of :obj:`numpy.isneginf`.
Args:
x: input array or scalar. ``complex`` dtype are not supported.
Returns:
A boolean array of same shape as ``x`` containing ``True`` where ``x`` is
``-inf``, and `... | isneginf | python | jax-ml/jax | jax/_src/numpy/ufuncs.py | https://github.com/jax-ml/jax/blob/master/jax/_src/numpy/ufuncs.py | Apache-2.0 |
def isnan(x: ArrayLike, /) -> Array:
"""Returns a boolean array indicating whether each element of input is ``NaN``.
JAX implementation of :obj:`numpy.isnan`.
Args:
x: input array or scalar.
Returns:
A boolean array of same shape as ``x`` containing ``True`` where ``x`` is
not a number (i.e. ``Na... | Returns a boolean array indicating whether each element of input is ``NaN``.
JAX implementation of :obj:`numpy.isnan`.
Args:
x: input array or scalar.
Returns:
A boolean array of same shape as ``x`` containing ``True`` where ``x`` is
not a number (i.e. ``NaN``) and ``False`` otherwise.
See also:... | isnan | python | jax-ml/jax | jax/_src/numpy/ufuncs.py | https://github.com/jax-ml/jax/blob/master/jax/_src/numpy/ufuncs.py | Apache-2.0 |
def heaviside(x1: ArrayLike, x2: ArrayLike, /) -> Array:
r"""Compute the heaviside step function.
JAX implementation of :obj:`numpy.heaviside`.
The heaviside step function is defined by:
.. math::
\mathrm{heaviside}(x1, x2) = \begin{cases}
0, & x1 < 0\\
x2, & x1 = 0\\
1, & x1 > 0.
... | Compute the heaviside step function.
JAX implementation of :obj:`numpy.heaviside`.
The heaviside step function is defined by:
.. math::
\mathrm{heaviside}(x1, x2) = \begin{cases}
0, & x1 < 0\\
x2, & x1 = 0\\
1, & x1 > 0.
\end{cases}
Args:
x1: input array or scalar. ``complex... | heaviside | python | jax-ml/jax | jax/_src/numpy/ufuncs.py | https://github.com/jax-ml/jax/blob/master/jax/_src/numpy/ufuncs.py | Apache-2.0 |
def hypot(x1: ArrayLike, x2: ArrayLike, /) -> Array:
r"""
Return element-wise hypotenuse for the given legs of a right angle triangle.
JAX implementation of :obj:`numpy.hypot`.
Args:
x1: scalar or array. Specifies one of the legs of right angle triangle.
``complex`` dtype are not supported.
x2: ... |
Return element-wise hypotenuse for the given legs of a right angle triangle.
JAX implementation of :obj:`numpy.hypot`.
Args:
x1: scalar or array. Specifies one of the legs of right angle triangle.
``complex`` dtype are not supported.
x2: scalar or array. Specifies the other leg of right angle tri... | hypot | python | jax-ml/jax | jax/_src/numpy/ufuncs.py | https://github.com/jax-ml/jax/blob/master/jax/_src/numpy/ufuncs.py | Apache-2.0 |
def reciprocal(x: ArrayLike, /) -> Array:
"""Calculate element-wise reciprocal of the input.
JAX implementation of :obj:`numpy.reciprocal`.
The reciprocal is calculated by ``1/x``.
Args:
x: input array or scalar.
Returns:
An array of same shape as ``x`` containing the reciprocal of each element of... | Calculate element-wise reciprocal of the input.
JAX implementation of :obj:`numpy.reciprocal`.
The reciprocal is calculated by ``1/x``.
Args:
x: input array or scalar.
Returns:
An array of same shape as ``x`` containing the reciprocal of each element of
``x``.
Note:
For integer inputs, ``... | reciprocal | python | jax-ml/jax | jax/_src/numpy/ufuncs.py | https://github.com/jax-ml/jax/blob/master/jax/_src/numpy/ufuncs.py | Apache-2.0 |
def reduce(self, a: ArrayLike, axis: int | None = 0,
dtype: DTypeLike | None = None,
out: None = None, keepdims: bool = False, initial: ArrayLike | None = None,
where: ArrayLike | None = None) -> Array:
"""Reduction operation derived from a binary function.
JAX implementa... | Reduction operation derived from a binary function.
JAX implementation of :meth:`numpy.ufunc.reduce`.
Args:
a: Input array.
axis: integer specifying the axis over which to reduce. default=0
dtype: optionally specify the type of the output array.
out: Unused by JAX
keepdims: If Tr... | reduce | python | jax-ml/jax | jax/_src/numpy/ufunc_api.py | https://github.com/jax-ml/jax/blob/master/jax/_src/numpy/ufunc_api.py | Apache-2.0 |
def accumulate(self, a: ArrayLike, axis: int = 0, dtype: DTypeLike | None = None,
out: None = None) -> Array:
"""Accumulate operation derived from binary ufunc.
JAX implementation of :func:`numpy.ufunc.accumulate`.
Args:
a: N-dimensional array over which to accumulate.
axis: i... | Accumulate operation derived from binary ufunc.
JAX implementation of :func:`numpy.ufunc.accumulate`.
Args:
a: N-dimensional array over which to accumulate.
axis: integer axis over which accumulation will be performed (default = 0)
dtype: optionally specify the type of the output array.
... | accumulate | python | jax-ml/jax | jax/_src/numpy/ufunc_api.py | https://github.com/jax-ml/jax/blob/master/jax/_src/numpy/ufunc_api.py | Apache-2.0 |
def at(self, a: ArrayLike, indices: Any, b: ArrayLike | None = None, /, *,
inplace: bool = True) -> Array:
"""Update elements of an array via the specified unary or binary ufunc.
JAX implementation of :func:`numpy.ufunc.at`.
Note:
:meth:`numpy.ufunc.at` mutates arrays in-place. JAX arrays a... | Update elements of an array via the specified unary or binary ufunc.
JAX implementation of :func:`numpy.ufunc.at`.
Note:
:meth:`numpy.ufunc.at` mutates arrays in-place. JAX arrays are immutable,
so :meth:`jax.numpy.ufunc.at` cannot replicate these semantics. Instead, JAX
will return the upda... | at | python | jax-ml/jax | jax/_src/numpy/ufunc_api.py | https://github.com/jax-ml/jax/blob/master/jax/_src/numpy/ufunc_api.py | Apache-2.0 |
def reduceat(self, a: ArrayLike, indices: Any, axis: int = 0,
dtype: DTypeLike | None = None, out: None = None) -> Array:
"""Reduce an array between specified indices via a binary ufunc.
JAX implementation of :meth:`numpy.ufunc.reduceat`
Args:
a: N-dimensional array to reduce
in... | Reduce an array between specified indices via a binary ufunc.
JAX implementation of :meth:`numpy.ufunc.reduceat`
Args:
a: N-dimensional array to reduce
indices: a 1-dimensional array of increasing integer values which encodes
segments of the array to be reduced.
axis: integer specify... | reduceat | python | jax-ml/jax | jax/_src/numpy/ufunc_api.py | https://github.com/jax-ml/jax/blob/master/jax/_src/numpy/ufunc_api.py | Apache-2.0 |
def outer(self, A: ArrayLike, B: ArrayLike, /) -> Array:
"""Apply the function to all pairs of values in ``A`` and ``B``.
JAX implementation of :meth:`numpy.ufunc.outer`.
Args:
A: N-dimensional array
B: N-dimensional array
Returns:
An array of shape `tuple(*A.shape, *B.shape)`
... | Apply the function to all pairs of values in ``A`` and ``B``.
JAX implementation of :meth:`numpy.ufunc.outer`.
Args:
A: N-dimensional array
B: N-dimensional array
Returns:
An array of shape `tuple(*A.shape, *B.shape)`
Examples:
A times-table for integers 1...10 created via
... | outer | python | jax-ml/jax | jax/_src/numpy/ufunc_api.py | https://github.com/jax-ml/jax/blob/master/jax/_src/numpy/ufunc_api.py | Apache-2.0 |
def frompyfunc(func: Callable[..., Any], /, nin: int, nout: int,
*, identity: Any = None) -> ufunc:
"""Create a JAX ufunc from an arbitrary JAX-compatible scalar function.
Args:
func : a callable that takes `nin` scalar arguments and returns `nout` outputs.
nin: integer specifying the number... | Create a JAX ufunc from an arbitrary JAX-compatible scalar function.
Args:
func : a callable that takes `nin` scalar arguments and returns `nout` outputs.
nin: integer specifying the number of scalar inputs
nout: integer specifying the number of scalar outputs
identity: (optional) a scalar specifying... | frompyfunc | python | jax-ml/jax | jax/_src/numpy/ufunc_api.py | https://github.com/jax-ml/jax/blob/master/jax/_src/numpy/ufunc_api.py | Apache-2.0 |
def promote_shapes(fun_name: str, *args: ArrayLike) -> list[Array]:
"""Apply NumPy-style broadcasting, making args shape-compatible for lax.py."""
if len(args) < 2:
return [lax.asarray(arg) for arg in args]
else:
shapes = [np.shape(arg) for arg in args]
if config.dynamic_shapes.value:
# With dyn... | Apply NumPy-style broadcasting, making args shape-compatible for lax.py. | promote_shapes | python | jax-ml/jax | jax/_src/numpy/util.py | https://github.com/jax-ml/jax/blob/master/jax/_src/numpy/util.py | Apache-2.0 |
def promote_dtypes(*args: ArrayLike) -> list[Array]:
"""Convenience function to apply Numpy argument dtype promotion."""
# TODO(dougalm,mattjj): This is a performance bottleneck. Consider memoizing.
if len(args) < 2:
return [lax.asarray(arg) for arg in args]
else:
to_dtype, weak_type = dtypes._lattice_r... | Convenience function to apply Numpy argument dtype promotion. | promote_dtypes | python | jax-ml/jax | jax/_src/numpy/util.py | https://github.com/jax-ml/jax/blob/master/jax/_src/numpy/util.py | Apache-2.0 |
def promote_dtypes_inexact(*args: ArrayLike) -> list[Array]:
"""Convenience function to apply Numpy argument dtype promotion.
Promotes arguments to an inexact type."""
to_dtype, weak_type = dtypes._lattice_result_type(*args)
to_dtype = dtypes.canonicalize_dtype(to_dtype, allow_extended_dtype=True)
to_dtype_i... | Convenience function to apply Numpy argument dtype promotion.
Promotes arguments to an inexact type. | promote_dtypes_inexact | python | jax-ml/jax | jax/_src/numpy/util.py | https://github.com/jax-ml/jax/blob/master/jax/_src/numpy/util.py | Apache-2.0 |
def promote_dtypes_numeric(*args: ArrayLike) -> list[Array]:
"""Convenience function to apply Numpy argument dtype promotion.
Promotes arguments to a numeric (non-bool) type."""
to_dtype, weak_type = dtypes._lattice_result_type(*args)
to_dtype = dtypes.canonicalize_dtype(to_dtype)
to_dtype_numeric = dtypes.t... | Convenience function to apply Numpy argument dtype promotion.
Promotes arguments to a numeric (non-bool) type. | promote_dtypes_numeric | python | jax-ml/jax | jax/_src/numpy/util.py | https://github.com/jax-ml/jax/blob/master/jax/_src/numpy/util.py | Apache-2.0 |
def promote_dtypes_complex(*args: ArrayLike) -> list[Array]:
"""Convenience function to apply Numpy argument dtype promotion.
Promotes arguments to a complex type."""
to_dtype, weak_type = dtypes._lattice_result_type(*args)
to_dtype = dtypes.canonicalize_dtype(to_dtype)
to_dtype_complex = dtypes.to_complex_d... | Convenience function to apply Numpy argument dtype promotion.
Promotes arguments to a complex type. | promote_dtypes_complex | python | jax-ml/jax | jax/_src/numpy/util.py | https://github.com/jax-ml/jax/blob/master/jax/_src/numpy/util.py | Apache-2.0 |
def _arraylike_asarray(x: Any) -> Array:
"""Convert an array-like object to an array."""
if hasattr(x, '__jax_array__'):
x = x.__jax_array__()
return lax.asarray(x) | Convert an array-like object to an array. | _arraylike_asarray | python | jax-ml/jax | jax/_src/numpy/util.py | https://github.com/jax-ml/jax/blob/master/jax/_src/numpy/util.py | Apache-2.0 |
def ensure_arraylike(fun_name: str, /, *args: Any) -> Array | tuple[Array, ...]:
"""Check that arguments are arraylike and convert them to arrays."""
check_arraylike(fun_name, *args)
if len(args) == 1:
return _arraylike_asarray(args[0]) # pytype: disable=bad-return-type
return tuple(_arraylike_asarray(arg)... | Check that arguments are arraylike and convert them to arrays. | ensure_arraylike | python | jax-ml/jax | jax/_src/numpy/util.py | https://github.com/jax-ml/jax/blob/master/jax/_src/numpy/util.py | Apache-2.0 |
def ensure_arraylike_tuple(fun_name: str, tup: Sequence[Any]) -> tuple[Array, ...]:
"""Check that argument elements are arraylike and convert to a tuple of arrays.
This is useful because ensure_arraylike with a single argument returns a single array.
"""
check_arraylike(fun_name, *tup)
return tuple(_arraylik... | Check that argument elements are arraylike and convert to a tuple of arrays.
This is useful because ensure_arraylike with a single argument returns a single array.
| ensure_arraylike_tuple | python | jax-ml/jax | jax/_src/numpy/util.py | https://github.com/jax-ml/jax/blob/master/jax/_src/numpy/util.py | Apache-2.0 |
def check_arraylike(fun_name: str, *args: Any, emit_warning=False, stacklevel=3):
"""Check if all args fit JAX's definition of arraylike."""
assert isinstance(fun_name, str), f"fun_name must be a string. Got {fun_name}"
if any(not _arraylike(arg) for arg in args):
pos, arg = next((i, arg) for i, arg in enumer... | Check if all args fit JAX's definition of arraylike. | check_arraylike | python | jax-ml/jax | jax/_src/numpy/util.py | https://github.com/jax-ml/jax/blob/master/jax/_src/numpy/util.py | Apache-2.0 |
def check_no_float0s(fun_name: str, *args: Any):
"""Check if none of the args have dtype float0."""
if any(dtypes.dtype(arg) == dtypes.float0 for arg in args):
raise TypeError(
f"Called {fun_name} with a float0 array. "
"float0s do not support any operations by design because they "
"are... | Check if none of the args have dtype float0. | check_no_float0s | python | jax-ml/jax | jax/_src/numpy/util.py | https://github.com/jax-ml/jax/blob/master/jax/_src/numpy/util.py | Apache-2.0 |
def check_for_prngkeys(fun_name: str, *args: Any):
"""Check if args don't match and none of the args have typed prng dtype"""
arg_dtypes = [dtypes.dtype(arg) for arg in args]
if len(set(arg_dtypes)) < 2:
return # Will be caught by extended dtype impl rules.
if any(dtypes.issubdtype(dt, dtypes.prng_key) for... | Check if args don't match and none of the args have typed prng dtype | check_for_prngkeys | python | jax-ml/jax | jax/_src/numpy/util.py | https://github.com/jax-ml/jax/blob/master/jax/_src/numpy/util.py | Apache-2.0 |
def promote_args(fun_name: str, *args: ArrayLike) -> list[Array]:
"""Convenience function to apply Numpy argument shape and dtype promotion."""
check_arraylike(fun_name, *args)
args = tuple(_check_jax_array_protocol(arg) for arg in args)
_check_no_float0s(fun_name, *args)
check_for_prngkeys(fun_name, *args)
... | Convenience function to apply Numpy argument shape and dtype promotion. | promote_args | python | jax-ml/jax | jax/_src/numpy/util.py | https://github.com/jax-ml/jax/blob/master/jax/_src/numpy/util.py | Apache-2.0 |
def promote_args_inexact(fun_name: str, *args: ArrayLike) -> list[Array]:
"""Convenience function to apply Numpy argument shape and dtype promotion.
Promotes non-inexact types to an inexact type."""
check_arraylike(fun_name, *args)
args = tuple(_check_jax_array_protocol(arg) for arg in args)
_check_no_float0... | Convenience function to apply Numpy argument shape and dtype promotion.
Promotes non-inexact types to an inexact type. | promote_args_inexact | python | jax-ml/jax | jax/_src/numpy/util.py | https://github.com/jax-ml/jax/blob/master/jax/_src/numpy/util.py | Apache-2.0 |
def _broadcast_arrays(*args: ArrayLike) -> list[Array]:
"""Like Numpy's broadcast_arrays but doesn't return views."""
avals = [core.shaped_abstractify(arg) for arg in args]
shapes = [a.shape for a in avals]
if not shapes or all(core.definitely_equal_shape(shapes[0], s) for s in shapes):
return [lax.asarray(... | Like Numpy's broadcast_arrays but doesn't return views. | _broadcast_arrays | python | jax-ml/jax | jax/_src/numpy/util.py | https://github.com/jax-ml/jax/blob/master/jax/_src/numpy/util.py | Apache-2.0 |
def ndim(a: ArrayLike | SupportsNdim) -> int:
"""Return the number of dimensions of an array.
JAX implementation of :func:`numpy.ndim`. Unlike ``np.ndim``, this function
raises a :class:`TypeError` if the input is a collection such as a list or
tuple.
Args:
a: array-like object, or any object with an ``... | Return the number of dimensions of an array.
JAX implementation of :func:`numpy.ndim`. Unlike ``np.ndim``, this function
raises a :class:`TypeError` if the input is a collection such as a list or
tuple.
Args:
a: array-like object, or any object with an ``ndim`` attribute.
Returns:
An integer specif... | ndim | python | jax-ml/jax | jax/_src/numpy/util.py | https://github.com/jax-ml/jax/blob/master/jax/_src/numpy/util.py | Apache-2.0 |
def shape(a: ArrayLike | SupportsShape) -> tuple[int, ...]:
"""Return the shape an array.
JAX implementation of :func:`numpy.shape`. Unlike ``np.shape``, this function
raises a :class:`TypeError` if the input is a collection such as a list or
tuple.
Args:
a: array-like object, or any object with a ``sha... | Return the shape an array.
JAX implementation of :func:`numpy.shape`. Unlike ``np.shape``, this function
raises a :class:`TypeError` if the input is a collection such as a list or
tuple.
Args:
a: array-like object, or any object with a ``shape`` attribute.
Returns:
An tuple of integers representing... | shape | python | jax-ml/jax | jax/_src/numpy/util.py | https://github.com/jax-ml/jax/blob/master/jax/_src/numpy/util.py | Apache-2.0 |
def size(a: ArrayLike | SupportsSize | SupportsShape, axis: int | None = None) -> int:
"""Return number of elements along a given axis.
JAX implementation of :func:`numpy.size`. Unlike ``np.size``, this function
raises a :class:`TypeError` if the input is a collection such as a list or
tuple.
Args:
a: a... | Return number of elements along a given axis.
JAX implementation of :func:`numpy.size`. Unlike ``np.size``, this function
raises a :class:`TypeError` if the input is a collection such as a list or
tuple.
Args:
a: array-like object, or any object with a ``size`` attribute when ``axis`` is not
specifi... | size | python | jax-ml/jax | jax/_src/numpy/util.py | https://github.com/jax-ml/jax/blob/master/jax/_src/numpy/util.py | Apache-2.0 |
def _parse_gufunc_signature(
signature: str,
) -> tuple[list[CoreDims], list[CoreDims]]:
"""Parse string signatures for a generalized universal function.
Args:
signature: generalized universal function signature, e.g.,
``(m,n),(n,p)->(m,p)`` for ``jnp.matmul``.
Returns:
Input and output core d... | Parse string signatures for a generalized universal function.
Args:
signature: generalized universal function signature, e.g.,
``(m,n),(n,p)->(m,p)`` for ``jnp.matmul``.
Returns:
Input and output core dimensions parsed from the signature.
| _parse_gufunc_signature | python | jax-ml/jax | jax/_src/numpy/vectorize.py | https://github.com/jax-ml/jax/blob/master/jax/_src/numpy/vectorize.py | Apache-2.0 |
def _update_dim_sizes(
dim_sizes: dict[str, int],
shape: tuple[int, ...],
core_dims: CoreDims,
error_context: str = "",
*,
is_input: bool):
"""Incrementally check and update core dimension sizes for a single argument.
Args:
dim_sizes: sizes of existing core dimensions. Will be updated i... | Incrementally check and update core dimension sizes for a single argument.
Args:
dim_sizes: sizes of existing core dimensions. Will be updated in-place.
shape: shape of this argument.
core_dims: core dimensions for this argument.
error_context: string context for error messages.
is_input: are we ... | _update_dim_sizes | python | jax-ml/jax | jax/_src/numpy/vectorize.py | https://github.com/jax-ml/jax/blob/master/jax/_src/numpy/vectorize.py | Apache-2.0 |
def _parse_input_dimensions(
args: tuple[NDArray, ...],
input_core_dims: list[CoreDims],
error_context: str = "",
) -> tuple[tuple[int, ...], dict[str, int]]:
"""Parse broadcast and core dimensions for vectorize with a signature.
Args:
args: tuple of input arguments to examine.
input_core_dims:... | Parse broadcast and core dimensions for vectorize with a signature.
Args:
args: tuple of input arguments to examine.
input_core_dims: list of core dimensions corresponding to each input.
error_context: string context for error messages.
Returns:
broadcast_shape: common shape to broadcast all non-c... | _parse_input_dimensions | python | jax-ml/jax | jax/_src/numpy/vectorize.py | https://github.com/jax-ml/jax/blob/master/jax/_src/numpy/vectorize.py | Apache-2.0 |
def _check_output_dims(
func: Callable,
dim_sizes: dict[str, int],
expected_output_core_dims: list[CoreDims],
error_context: str = "",
) -> Callable:
"""Check that output core dimensions match the signature."""
def wrapped(*args):
out = func(*args)
out_shapes = map(np.shape, out if isinstanc... | Check that output core dimensions match the signature. | _check_output_dims | python | jax-ml/jax | jax/_src/numpy/vectorize.py | https://github.com/jax-ml/jax/blob/master/jax/_src/numpy/vectorize.py | Apache-2.0 |
def _apply_excluded(func: Callable[..., Any],
excluded: Collection[int | str],
args: Sequence[Any],
kwargs: dict[str, Any]) -> tuple[Callable[..., Any], Sequence[Any], dict[str, Any]]:
"""Partially apply positional arguments in `excluded` to a function."""
... | Partially apply positional arguments in `excluded` to a function. | _apply_excluded | python | jax-ml/jax | jax/_src/numpy/vectorize.py | https://github.com/jax-ml/jax/blob/master/jax/_src/numpy/vectorize.py | Apache-2.0 |
def vectorize(pyfunc, *, excluded=frozenset(), signature=None):
"""Define a vectorized function with broadcasting.
:func:`vectorize` is a convenience wrapper for defining vectorized
functions with broadcasting, in the style of NumPy's
`generalized universal functions <https://numpy.org/doc/stable/reference/c-a... | Define a vectorized function with broadcasting.
:func:`vectorize` is a convenience wrapper for defining vectorized
functions with broadcasting, in the style of NumPy's
`generalized universal functions <https://numpy.org/doc/stable/reference/c-api/generalized-ufuncs.html>`_.
It allows for defining functions tha... | vectorize | python | jax-ml/jax | jax/_src/numpy/vectorize.py | https://github.com/jax-ml/jax/blob/master/jax/_src/numpy/vectorize.py | Apache-2.0 |
def blackman(M: int) -> Array:
"""Return a Blackman window of size M.
JAX implementation of :func:`numpy.blackman`.
Args:
M: The window size.
Returns:
An array of size M containing the Blackman window.
Examples:
>>> with jnp.printoptions(precision=2, suppress=True):
... print(jnp.blackma... | Return a Blackman window of size M.
JAX implementation of :func:`numpy.blackman`.
Args:
M: The window size.
Returns:
An array of size M containing the Blackman window.
Examples:
>>> with jnp.printoptions(precision=2, suppress=True):
... print(jnp.blackman(4))
[-0. 0.63 0.63 -0. ]
... | blackman | python | jax-ml/jax | jax/_src/numpy/window_functions.py | https://github.com/jax-ml/jax/blob/master/jax/_src/numpy/window_functions.py | Apache-2.0 |
def bartlett(M: int) -> Array:
"""Return a Bartlett window of size M.
JAX implementation of :func:`numpy.bartlett`.
Args:
M: The window size.
Returns:
An array of size M containing the Bartlett window.
Examples:
>>> with jnp.printoptions(precision=2, suppress=True):
... print(jnp.bartlet... | Return a Bartlett window of size M.
JAX implementation of :func:`numpy.bartlett`.
Args:
M: The window size.
Returns:
An array of size M containing the Bartlett window.
Examples:
>>> with jnp.printoptions(precision=2, suppress=True):
... print(jnp.bartlett(4))
[0. 0.67 0.67 0. ]
S... | bartlett | python | jax-ml/jax | jax/_src/numpy/window_functions.py | https://github.com/jax-ml/jax/blob/master/jax/_src/numpy/window_functions.py | Apache-2.0 |
def hamming(M: int) -> Array:
"""Return a Hamming window of size M.
JAX implementation of :func:`numpy.hamming`.
Args:
M: The window size.
Returns:
An array of size M containing the Hamming window.
Examples:
>>> with jnp.printoptions(precision=2, suppress=True):
... print(jnp.hamming(4))... | Return a Hamming window of size M.
JAX implementation of :func:`numpy.hamming`.
Args:
M: The window size.
Returns:
An array of size M containing the Hamming window.
Examples:
>>> with jnp.printoptions(precision=2, suppress=True):
... print(jnp.hamming(4))
[0.08 0.77 0.77 0.08]
See a... | hamming | python | jax-ml/jax | jax/_src/numpy/window_functions.py | https://github.com/jax-ml/jax/blob/master/jax/_src/numpy/window_functions.py | Apache-2.0 |
def hanning(M: int) -> Array:
"""Return a Hanning window of size M.
JAX implementation of :func:`numpy.hanning`.
Args:
M: The window size.
Returns:
An array of size M containing the Hanning window.
Examples:
>>> with jnp.printoptions(precision=2, suppress=True):
... print(jnp.hanning(4))... | Return a Hanning window of size M.
JAX implementation of :func:`numpy.hanning`.
Args:
M: The window size.
Returns:
An array of size M containing the Hanning window.
Examples:
>>> with jnp.printoptions(precision=2, suppress=True):
... print(jnp.hanning(4))
[0. 0.75 0.75 0. ]
See a... | hanning | python | jax-ml/jax | jax/_src/numpy/window_functions.py | https://github.com/jax-ml/jax/blob/master/jax/_src/numpy/window_functions.py | Apache-2.0 |
def kaiser(M: int, beta: ArrayLike) -> Array:
"""Return a Kaiser window of size M.
JAX implementation of :func:`numpy.kaiser`.
Args:
M: The window size.
beta: The Kaiser window parameter.
Returns:
An array of size M containing the Kaiser window.
Examples:
>>> with jnp.printoptions(precisio... | Return a Kaiser window of size M.
JAX implementation of :func:`numpy.kaiser`.
Args:
M: The window size.
beta: The Kaiser window parameter.
Returns:
An array of size M containing the Kaiser window.
Examples:
>>> with jnp.printoptions(precision=2, suppress=True):
... print(jnp.kaiser(4, ... | kaiser | python | jax-ml/jax | jax/_src/numpy/window_functions.py | https://github.com/jax-ml/jax/blob/master/jax/_src/numpy/window_functions.py | Apache-2.0 |
def _scatter_update(x: ArrayLike, idx: Index, y: ArrayLike, scatter_op: Callable[..., Array],
indices_are_sorted: bool, unique_indices: bool,
mode: lax.GatherScatterMode | str | None = None, normalize_indices: bool = True,
out_sharding: sharding.Sharding | Non... | Helper for indexed updates.
Computes the value of x that would result from computing::
x[idx] op= y
except in a pure functional way, with no in-place updating.
Args:
x: ndarray to be updated.
idx: None, an integer, a slice, an ellipsis, an ndarray with integer dtype,
or a tuple of those indica... | _scatter_update | python | jax-ml/jax | jax/_src/ops/scatter.py | https://github.com/jax-ml/jax/blob/master/jax/_src/ops/scatter.py | Apache-2.0 |
def _get_identity(op, dtype):
"""Get an appropriate identity for a given operation in a given dtype."""
if op is lax.scatter_add:
return 0
elif op is lax.scatter_mul:
return 1
elif op is lax.scatter_min:
if dtype == dtypes.bool_:
return True
elif dtypes.issubdtype(dtype, np.integer):
... | Get an appropriate identity for a given operation in a given dtype. | _get_identity | python | jax-ml/jax | jax/_src/ops/scatter.py | https://github.com/jax-ml/jax/blob/master/jax/_src/ops/scatter.py | Apache-2.0 |
def segment_sum(data: ArrayLike,
segment_ids: ArrayLike,
num_segments: int | None = None,
indices_are_sorted: bool = False,
unique_indices: bool = False,
bucket_size: int | None = None,
mode: lax.GatherScatterMode | str | No... | Computes the sum within segments of an array.
Similar to TensorFlow's `segment_sum
<https://www.tensorflow.org/api_docs/python/tf/math/segment_sum>`_
Args:
data: an array with the values to be summed.
segment_ids: an array with integer dtype that indicates the segments of
`data` (along its leading... | segment_sum | python | jax-ml/jax | jax/_src/ops/scatter.py | https://github.com/jax-ml/jax/blob/master/jax/_src/ops/scatter.py | Apache-2.0 |
def segment_prod(data: ArrayLike,
segment_ids: ArrayLike,
num_segments: int | None = None,
indices_are_sorted: bool = False,
unique_indices: bool = False,
bucket_size: int | None = None,
mode: lax.GatherScatterMode | s... | Computes the product within segments of an array.
Similar to TensorFlow's `segment_prod
<https://www.tensorflow.org/api_docs/python/tf/math/segment_prod>`_
Args:
data: an array with the values to be reduced.
segment_ids: an array with integer dtype that indicates the segments of
`data` (along its ... | segment_prod | python | jax-ml/jax | jax/_src/ops/scatter.py | https://github.com/jax-ml/jax/blob/master/jax/_src/ops/scatter.py | Apache-2.0 |
def segment_max(data: ArrayLike,
segment_ids: ArrayLike,
num_segments: int | None = None,
indices_are_sorted: bool = False,
unique_indices: bool = False,
bucket_size: int | None = None,
mode: lax.GatherScatterMode | str | No... | Computes the maximum within segments of an array.
Similar to TensorFlow's `segment_max
<https://www.tensorflow.org/api_docs/python/tf/math/segment_max>`_
Args:
data: an array with the values to be reduced.
segment_ids: an array with integer dtype that indicates the segments of
`data` (along its le... | segment_max | python | jax-ml/jax | jax/_src/ops/scatter.py | https://github.com/jax-ml/jax/blob/master/jax/_src/ops/scatter.py | Apache-2.0 |
def segment_min(data: ArrayLike,
segment_ids: ArrayLike,
num_segments: int | None = None,
indices_are_sorted: bool = False,
unique_indices: bool = False,
bucket_size: int | None = None,
mode: lax.GatherScatterMode | str | No... | Computes the minimum within segments of an array.
Similar to TensorFlow's `segment_min
<https://www.tensorflow.org/api_docs/python/tf/math/segment_min>`_
Args:
data: an array with the values to be reduced.
segment_ids: an array with integer dtype that indicates the segments of
`data` (along its le... | segment_min | python | jax-ml/jax | jax/_src/ops/scatter.py | https://github.com/jax-ml/jax/blob/master/jax/_src/ops/scatter.py | Apache-2.0 |
def logsumexp(a: ArrayLike, axis: Axis = None, b: ArrayLike | None = None,
keepdims: bool = False, return_sign: bool = False, where: ArrayLike | None = None) -> Array | tuple[Array, Array]:
r"""Log-sum-exp reduction.
JAX implementation of :func:`scipy.special.logsumexp`.
.. math::
\operatornam... | Log-sum-exp reduction.
JAX implementation of :func:`scipy.special.logsumexp`.
.. math::
\operatorname{logsumexp} a = \log \sum_i b_i \exp a_i
where the :math:`i` indices range over one or more dimensions to be reduced.
Args:
a: the input array
axis: int or sequence of ints, default=None. Axis al... | logsumexp | python | jax-ml/jax | jax/_src/ops/special.py | https://github.com/jax-ml/jax/blob/master/jax/_src/ops/special.py | Apache-2.0 |
def ref_aval(self) -> AbstractMemoryRef | TransformedRef:
"""Returns the abstract value of the Ref after transformations."""
if not self.transforms:
return self.transformed_block_aval
ref = TransformedRef(self.transformed_block_aval, ())
for transform in reversed(self.transforms):
ref = tran... | Returns the abstract value of the Ref after transformations. | ref_aval | python | jax-ml/jax | jax/_src/pallas/core.py | https://github.com/jax-ml/jax/blob/master/jax/_src/pallas/core.py | Apache-2.0 |
def has_trivial_window(self):
"""If block shape is same as the array shape and index_map returns 0s."""
for b, s in zip(self.block_shape, self.array_shape_dtype.shape):
if _get_block_dim_size(b) != s:
return False
for atom in self.index_map_jaxpr.jaxpr.outvars:
if not (isinstance(atom, j... | If block shape is same as the array shape and index_map returns 0s. | has_trivial_window | python | jax-ml/jax | jax/_src/pallas/core.py | https://github.com/jax-ml/jax/blob/master/jax/_src/pallas/core.py | Apache-2.0 |
def slice_block_ops(self):
"""Returns a slice to select the block operands to a kernel.
The block operands are: *ins, *outs, the same for which we
have `self.block_mappings`.
This works on a sequence that contains *index, *ins, *outs, *scratch.
"""
return slice(self.num_index_operands,
... | Returns a slice to select the block operands to a kernel.
The block operands are: *ins, *outs, the same for which we
have `self.block_mappings`.
This works on a sequence that contains *index, *ins, *outs, *scratch.
| slice_block_ops | python | jax-ml/jax | jax/_src/pallas/core.py | https://github.com/jax-ml/jax/blob/master/jax/_src/pallas/core.py | Apache-2.0 |
def slice_scratch_ops(self):
"""Returns a slice object to select the scratch operands to a kernel.
This works on a sequence that contains *index, *ins, *outs, *scratch.
"""
if self.num_scratch_operands:
return slice(-self.num_scratch_operands, None)
else:
return slice(0, 0) | Returns a slice object to select the scratch operands to a kernel.
This works on a sequence that contains *index, *ins, *outs, *scratch.
| slice_scratch_ops | python | jax-ml/jax | jax/_src/pallas/core.py | https://github.com/jax-ml/jax/blob/master/jax/_src/pallas/core.py | Apache-2.0 |
def core_map(
mesh,
*,
compiler_params: Any | None = None,
interpret: bool = False,
debug: bool = False,
cost_estimate: CostEstimate | None = None,
name: str | None = None,
):
"""Runs a function on a mesh, mapping it over the devices in the mesh.
The function should be stateful in that ... | Runs a function on a mesh, mapping it over the devices in the mesh.
The function should be stateful in that it takes in no inputs and returns
no outputs but can mutate closed-over Refs, for example.
Args:
mesh: The mesh to run the function on.
compiler_params: The compiler parameters to pass to the back... | core_map | python | jax-ml/jax | jax/_src/pallas/core.py | https://github.com/jax-ml/jax/blob/master/jax/_src/pallas/core.py | Apache-2.0 |
def cost_estimate_jaxpr(
jaxpr: jax_core.ClosedJaxpr,
) -> pallas_core.CostEstimate:
"""Returns the cost estimate for the given Jaxpr."""
jaxpr, _ = jaxpr.jaxpr, jaxpr.consts
total_cost = CostEstimate(flops=0, transcendentals=0, bytes_accessed=0)
for eqn in jaxpr.eqns:
rule = _cost_rules.get(eqn.primit... | Returns the cost estimate for the given Jaxpr. | cost_estimate_jaxpr | python | jax-ml/jax | jax/_src/pallas/cost_estimate.py | https://github.com/jax-ml/jax/blob/master/jax/_src/pallas/cost_estimate.py | Apache-2.0 |
def estimate_cost(fun, *args, **kwargs) -> pallas_core.CostEstimate:
"""Computes a cost estimate for the given function.
Args:
fun: The function to compute the cost estimate for.
*args: The arguments to the function. Can be jax.ShapeDtypeStruct or
jax.Array.
**kwargs: The keyword arguments to the... | Computes a cost estimate for the given function.
Args:
fun: The function to compute the cost estimate for.
*args: The arguments to the function. Can be jax.ShapeDtypeStruct or
jax.Array.
**kwargs: The keyword arguments to the function.
Returns:
A pallas_core.CostEstimate object containing th... | estimate_cost | python | jax-ml/jax | jax/_src/pallas/cost_estimate.py | https://github.com/jax-ml/jax/blob/master/jax/_src/pallas/cost_estimate.py | Apache-2.0 |
def _logical_to_interpret_mode_dtype(dtype):
"""Converts logical dtypes into JAX dtypes for interpret mode.
Logical types are dtypes that exist as part of the Pallas API but
do not have an corresponding backing type in HLO (for example,
a Semaphore dtype).
This function maps a logical dtype to a valid HLO d... | Converts logical dtypes into JAX dtypes for interpret mode.
Logical types are dtypes that exist as part of the Pallas API but
do not have an corresponding backing type in HLO (for example,
a Semaphore dtype).
This function maps a logical dtype to a valid HLO dtype that can be
used to emulate the behavior of... | _logical_to_interpret_mode_dtype | python | jax-ml/jax | jax/_src/pallas/hlo_interpreter.py | https://github.com/jax-ml/jax/blob/master/jax/_src/pallas/hlo_interpreter.py | Apache-2.0 |
def _pad_to_block_dimension(value, block_shape: tuple[int, ...]):
"""Pads values so the shape evenly divides into block dimensions.
For example, if values has a shape of (33, 2, 5) with a block_shape of
(32, 2, 4), this function will pad the value of shape to (64, 2, 8).
Args:
value: Array to be padded.
... | Pads values so the shape evenly divides into block dimensions.
For example, if values has a shape of (33, 2, 5) with a block_shape of
(32, 2, 4), this function will pad the value of shape to (64, 2, 8).
Args:
value: Array to be padded.
block_shape: Block shapes to use for padding.
Returns:
A padd... | _pad_to_block_dimension | python | jax-ml/jax | jax/_src/pallas/hlo_interpreter.py | https://github.com/jax-ml/jax/blob/master/jax/_src/pallas/hlo_interpreter.py | Apache-2.0 |
def kernel_to_hlo_jaxpr(jaxpr: jax_core.Jaxpr,
consts: Sequence[Any],
grid_mapping: GridMapping,
backend: str | None,
) -> tuple[jax_core.Jaxpr, Sequence[Any], Sequence[Any]]:
"""Converts a Pallas kernel jaxpr to a valid HLO jaxpr."""
del b... | Converts a Pallas kernel jaxpr to a valid HLO jaxpr. | kernel_to_hlo_jaxpr | python | jax-ml/jax | jax/_src/pallas/hlo_interpreter.py | https://github.com/jax-ml/jax/blob/master/jax/_src/pallas/hlo_interpreter.py | Apache-2.0 |
def _broadcast_input_output_aliases(
args: Sequence[jax.Array],
dims: Sequence[int | batching.NotMapped],
*,
input_output_aliases: tuple[tuple[int, int], ...],
axis_size: int,
) -> tuple[tuple[jax.Array, ...], tuple[int | batching.NotMapped, ...]]:
"""Broadcast input/output operands.
When we ha... | Broadcast input/output operands.
When we have input/output aliasing, since the output will be mapped, we need
to make sure to broadcast the input across that dimension if it is not
mapped. If the input is mapped, but on a different axis, we transpose the input
to match the output.
| _broadcast_input_output_aliases | python | jax-ml/jax | jax/_src/pallas/pallas_call.py | https://github.com/jax-ml/jax/blob/master/jax/_src/pallas/pallas_call.py | Apache-2.0 |
def _batch_with_explicit_loop(
args: Sequence[jax.Array],
dims: Sequence[int | batching.NotMapped],
*,
jaxpr: jax_core.Jaxpr,
grid_mapping: GridMapping,
mesh: pallas_core.Mesh | None,
input_output_aliases: tuple[tuple[int, int], ...],
debug: bool,
interpret: Any,
compiler_params:... | Batch the pallas_call by calling it in loop over the batch size.
This function provides a fallback implementation of batching a pallas_call
for the cases in which adding a batch dimension to the pallas grid is not
supported. This is currently the case when the batched dimension corresponds
to a dynamic axis or... | _batch_with_explicit_loop | python | jax-ml/jax | jax/_src/pallas/pallas_call.py | https://github.com/jax-ml/jax/blob/master/jax/_src/pallas/pallas_call.py | Apache-2.0 |
def atomic_xchg(x_ref_or_view, idx, val, *, mask: Any | None = None):
"""Atomically exchanges the given value with the value at the given index.
Args:
x_ref_or_view: The ref to operate on.
idx: The indexer to use.
mask: TO BE DOCUMENTED.
Returns:
The value at the given index prior to the aupdate... | Atomically exchanges the given value with the value at the given index.
Args:
x_ref_or_view: The ref to operate on.
idx: The indexer to use.
mask: TO BE DOCUMENTED.
Returns:
The value at the given index prior to the aupdate.
| atomic_xchg | python | jax-ml/jax | jax/_src/pallas/primitives.py | https://github.com/jax-ml/jax/blob/master/jax/_src/pallas/primitives.py | Apache-2.0 |
def atomic_add(x_ref_or_view, idx, val, *, mask: Any | None = None):
"""Atomically computes ``x_ref_or_view[idx] += val``.
Args:
x_ref_or_view: The ref to operate on.
idx: The indexer to use.
mask: TO BE DOCUMENTED.
Returns:
The value at the given index prior to the atomic operation.
"""
ret... | Atomically computes ``x_ref_or_view[idx] += val``.
Args:
x_ref_or_view: The ref to operate on.
idx: The indexer to use.
mask: TO BE DOCUMENTED.
Returns:
The value at the given index prior to the atomic operation.
| atomic_add | python | jax-ml/jax | jax/_src/pallas/primitives.py | https://github.com/jax-ml/jax/blob/master/jax/_src/pallas/primitives.py | Apache-2.0 |
def atomic_max(x_ref_or_view, idx, val, *, mask: Any | None = None):
"""Atomically computes ``x_ref_or_view[idx] = max(x_ref_or_view[idx], val)``.
Args:
x_ref_or_view: The ref to operate on.
idx: The indexer to use.
mask: TO BE DOCUMENTED.
Returns:
The value at the given index prior to the atomi... | Atomically computes ``x_ref_or_view[idx] = max(x_ref_or_view[idx], val)``.
Args:
x_ref_or_view: The ref to operate on.
idx: The indexer to use.
mask: TO BE DOCUMENTED.
Returns:
The value at the given index prior to the atomic operation.
| atomic_max | python | jax-ml/jax | jax/_src/pallas/primitives.py | https://github.com/jax-ml/jax/blob/master/jax/_src/pallas/primitives.py | Apache-2.0 |
def atomic_min(x_ref_or_view, idx, val, *, mask: Any | None = None):
"""Atomically computes ``x_ref_or_view[idx] = min(x_ref_or_view[idx], val)``.
Args:
x_ref_or_view: The ref to operate on.
idx: The indexer to use.
mask: TO BE DOCUMENTED.
Returns:
The value at the given index prior to the atomi... | Atomically computes ``x_ref_or_view[idx] = min(x_ref_or_view[idx], val)``.
Args:
x_ref_or_view: The ref to operate on.
idx: The indexer to use.
mask: TO BE DOCUMENTED.
Returns:
The value at the given index prior to the atomic operation.
| atomic_min | python | jax-ml/jax | jax/_src/pallas/primitives.py | https://github.com/jax-ml/jax/blob/master/jax/_src/pallas/primitives.py | Apache-2.0 |
def atomic_and(x_ref_or_view, idx, val, *, mask: Any | None = None):
"""Atomically computes ``x_ref_or_view[idx] &= val``.
Args:
x_ref_or_view: The ref to operate on.
idx: The indexer to use.
mask: TO BE DOCUMENTED.
Returns:
The value at the given index prior to the atomic operation.
"""
ret... | Atomically computes ``x_ref_or_view[idx] &= val``.
Args:
x_ref_or_view: The ref to operate on.
idx: The indexer to use.
mask: TO BE DOCUMENTED.
Returns:
The value at the given index prior to the atomic operation.
| atomic_and | python | jax-ml/jax | jax/_src/pallas/primitives.py | https://github.com/jax-ml/jax/blob/master/jax/_src/pallas/primitives.py | Apache-2.0 |
def atomic_or(x_ref_or_view, idx, val, *, mask: Any | None = None):
"""Atomically computes ``x_ref_or_view[idx] |= val``.
Args:
x_ref_or_view: The ref to operate on.
idx: The indexer to use.
mask: TO BE DOCUMENTED.
Returns:
The value at the given index prior to the atomic operation.
"""
retu... | Atomically computes ``x_ref_or_view[idx] |= val``.
Args:
x_ref_or_view: The ref to operate on.
idx: The indexer to use.
mask: TO BE DOCUMENTED.
Returns:
The value at the given index prior to the atomic operation.
| atomic_or | python | jax-ml/jax | jax/_src/pallas/primitives.py | https://github.com/jax-ml/jax/blob/master/jax/_src/pallas/primitives.py | Apache-2.0 |
def atomic_xor(x_ref_or_view, idx, val, *, mask: Any | None = None):
"""Atomically computes ``x_ref_or_view[idx] ^= val``.
Args:
x_ref_or_view: The ref to operate on.
idx: The indexer to use.
mask: TO BE DOCUMENTED.
Returns:
The value at the given index prior to the atomic operation.
"""
ret... | Atomically computes ``x_ref_or_view[idx] ^= val``.
Args:
x_ref_or_view: The ref to operate on.
idx: The indexer to use.
mask: TO BE DOCUMENTED.
Returns:
The value at the given index prior to the atomic operation.
| atomic_xor | python | jax-ml/jax | jax/_src/pallas/primitives.py | https://github.com/jax-ml/jax/blob/master/jax/_src/pallas/primitives.py | Apache-2.0 |
def _pad_values_to_avoid_dynamic_slice_oob_shift(value,
slice_sizes, unpad=False):
"""
DynamicSlice and DynamicUpdateSlice adjust the start index in cases where the
requested slice overruns the bounds of the array. This pads the array with
uninitialised values such that the re... |
DynamicSlice and DynamicUpdateSlice adjust the start index in cases where the
requested slice overruns the bounds of the array. This pads the array with
uninitialised values such that the requested slice will never overrun.
For example, if arr is [1.,2.,3.,4.] and a slice of size 4, start index 2 is
request... | _pad_values_to_avoid_dynamic_slice_oob_shift | python | jax-ml/jax | jax/_src/pallas/primitives.py | https://github.com/jax-ml/jax/blob/master/jax/_src/pallas/primitives.py | Apache-2.0 |
def load(x_ref_or_view, idx, *, mask=None, other=None, cache_modifier=None,
eviction_policy=None, volatile=False) -> jax.Array:
"""Returns an array loaded from the given index.
If neither ``mask`` nor ``other`` is specified, this function has the same
semantics as ``x_ref_or_view[idx]`` in JAX.
Args:... | Returns an array loaded from the given index.
If neither ``mask`` nor ``other`` is specified, this function has the same
semantics as ``x_ref_or_view[idx]`` in JAX.
Args:
x_ref_or_view: The ref to load from.
idx: The indexer to use.
mask: An optional boolean mask specifying which indices to load.
... | load | python | jax-ml/jax | jax/_src/pallas/primitives.py | https://github.com/jax-ml/jax/blob/master/jax/_src/pallas/primitives.py | Apache-2.0 |
def swap(x_ref_or_view, idx, val, *, mask=None, eviction_policy=None,
_function_name="swap") -> jax.Array:
"""Swaps the value at the given index and returns the old value.
See :func:`~jax.experimental.pallas.load` for the meaning of the arguments.
Returns:
The value stored in the ref prior to the s... | Swaps the value at the given index and returns the old value.
See :func:`~jax.experimental.pallas.load` for the meaning of the arguments.
Returns:
The value stored in the ref prior to the swap.
| swap | python | jax-ml/jax | jax/_src/pallas/primitives.py | https://github.com/jax-ml/jax/blob/master/jax/_src/pallas/primitives.py | Apache-2.0 |
def _handle_f8(dtype: jax.typing.DTypeLike):
"""Ugly workaround to support float8_e4m3b11fnuz in dot."""
if dtype == jnp.float8_e4m3b11fnuz:
return jnp.bfloat16
return dtype | Ugly workaround to support float8_e4m3b11fnuz in dot. | _handle_f8 | python | jax-ml/jax | jax/_src/pallas/primitives.py | https://github.com/jax-ml/jax/blob/master/jax/_src/pallas/primitives.py | Apache-2.0 |
def debug_print(fmt: str, *args: jax.typing.ArrayLike):
"""Prints values from inside a Pallas kernel.
Args:
fmt: A format string to be included in the output. The restrictions on the
format string depend on the backend:
* On GPU, when using Triton, ``fmt`` must not contain any placeholders
... | Prints values from inside a Pallas kernel.
Args:
fmt: A format string to be included in the output. The restrictions on the
format string depend on the backend:
* On GPU, when using Triton, ``fmt`` must not contain any placeholders
(``{...}``), since it is always printed before any of the va... | debug_print | python | jax-ml/jax | jax/_src/pallas/primitives.py | https://github.com/jax-ml/jax/blob/master/jax/_src/pallas/primitives.py | Apache-2.0 |
def run_scoped(
f: Callable[..., Any],
*types: Any,
collective_axes: Hashable | tuple[Hashable, ...] = (),
**kw_types: Any,
) -> Any:
"""Calls the function with allocated references and returns the result.
The positional and keyword arguments describe which reference types
to allocate for each ar... | Calls the function with allocated references and returns the result.
The positional and keyword arguments describe which reference types
to allocate for each argument. Each backend has its own set of reference
types in addition to :class:`jax.experimental.pallas.MemoryRef`.
When `collective_axes` is specified... | run_scoped | python | jax-ml/jax | jax/_src/pallas/primitives.py | https://github.com/jax-ml/jax/blob/master/jax/_src/pallas/primitives.py | Apache-2.0 |
def _transform_semaphore(ref_value, transforms, ref_aval):
"""Helper function for indexing into a semaphore during state_discharge."""
if ref_value.shape == ref_aval.shape:
return state_discharge.transform_array(ref_value, transforms)
elif len(ref_value.shape) == 0:
return ref_value
else:
raise Valu... | Helper function for indexing into a semaphore during state_discharge. | _transform_semaphore | python | jax-ml/jax | jax/_src/pallas/primitives.py | https://github.com/jax-ml/jax/blob/master/jax/_src/pallas/primitives.py | Apache-2.0 |
def next_power_of_2(x: int) -> int:
"""Returns the next power of two greater than or equal to `x`."""
if x < 0:
raise ValueError("`next_power_of_2` requires a non-negative integer.")
return 1 if x == 0 else 2 ** (x - 1).bit_length() | Returns the next power of two greater than or equal to `x`. | next_power_of_2 | python | jax-ml/jax | jax/_src/pallas/utils.py | https://github.com/jax-ml/jax/blob/master/jax/_src/pallas/utils.py | Apache-2.0 |
def physicalize(f):
"""Runs a function that contains fusible extended dtypes."""
def wrapper(*args, **kwargs):
if kwargs:
raise NotImplementedError()
flattened_args, treedef = jax.tree.flatten(args)
debug_info = api_util.debug_info("physicalize", f, args, kwargs)
wrapped_fun, out_tree_thunk =... | Runs a function that contains fusible extended dtypes. | physicalize | python | jax-ml/jax | jax/_src/pallas/fuser/fusible_dtype.py | https://github.com/jax-ml/jax/blob/master/jax/_src/pallas/fuser/fusible_dtype.py | Apache-2.0 |
def physicalize_closed_jaxpr(jaxpr: core.ClosedJaxpr) -> core.ClosedJaxpr:
"""Replaces all extended dtypes with physical types in a jaxpr."""
fun = functools.partial(physicalize_interp, jaxpr.jaxpr, jaxpr.consts)
in_avals = [_physical_aval(aval) for aval in jaxpr.in_avals]
flat_avals, treedef = tree_util.tree_f... | Replaces all extended dtypes with physical types in a jaxpr. | physicalize_closed_jaxpr | python | jax-ml/jax | jax/_src/pallas/fuser/fusible_dtype.py | https://github.com/jax-ml/jax/blob/master/jax/_src/pallas/fuser/fusible_dtype.py | Apache-2.0 |
def physicalize_interp(
jaxpr: core.Jaxpr, consts: Sequence[core.Value], *args: core.Value
):
"""Physicalizes a jaxpr by replacing fusible dtypes with physical types."""
# TODO: Merge into JAX core.
env: dict[core.Var, Any] = {}
def read_env(var: core.Atom):
if isinstance(var, core.Literal):
retu... | Physicalizes a jaxpr by replacing fusible dtypes with physical types. | physicalize_interp | python | jax-ml/jax | jax/_src/pallas/fuser/fusible_dtype.py | https://github.com/jax-ml/jax/blob/master/jax/_src/pallas/fuser/fusible_dtype.py | Apache-2.0 |
def fuse(f=None, *, resolve_fusion_dtypes: bool = True, debug: bool = False):
"""Fuses a function into a single fusible.
Args:
f: The function to fuse.
resolve_fusion_dtypes: (experimental) whether or not to resolve fusion
dtypes (which don't correspond to physical dtypes)
debug: Whether to print... | Fuses a function into a single fusible.
Args:
f: The function to fuse.
resolve_fusion_dtypes: (experimental) whether or not to resolve fusion
dtypes (which don't correspond to physical dtypes)
debug: Whether to print debug information.
There should be a single call to a `fusible` inside the body... | fuse | python | jax-ml/jax | jax/_src/pallas/fuser/jaxpr_fusion.py | https://github.com/jax-ml/jax/blob/master/jax/_src/pallas/fuser/jaxpr_fusion.py | Apache-2.0 |
def _handle_xla_runtime_error(
base_err: xla_client.XlaRuntimeError,
) -> MosaicError | None:
"""Reformats XLARuntimeError to include a Python traceback."""
if 'Mosaic' not in str(base_err):
return None
try:
_, frames = parse_location_string(str(base_err))
except ValueError:
# If no location str... | Reformats XLARuntimeError to include a Python traceback. | _handle_xla_runtime_error | python | jax-ml/jax | jax/_src/pallas/mosaic/error_handling.py | https://github.com/jax-ml/jax/blob/master/jax/_src/pallas/mosaic/error_handling.py | Apache-2.0 |
def mlir_error_to_verification_error(
base_err: ir.MLIRError) -> VerificationError:
"""Reformats MLIRError to include a Python traceback."""
diagnostic = base_err.error_diagnostics[0] # pytype: disable=attribute-error
def _get_diagnostic_message(diagnostic) -> str:
current_msg = diagnostic.message
fo... | Reformats MLIRError to include a Python traceback. | mlir_error_to_verification_error | python | jax-ml/jax | jax/_src/pallas/mosaic/error_handling.py | https://github.com/jax-ml/jax/blob/master/jax/_src/pallas/mosaic/error_handling.py | Apache-2.0 |
def redact_locations(err_msg: str) -> str:
"""Removes location strings from an error message."""
for mat in re.finditer(LOCATION_PATTERN, err_msg):
start, end = mat.span('location')
# Remove the entire line containing the location.
line_start = err_msg.rfind('\n', 0, end)
line_start = line_start if ... | Removes location strings from an error message. | redact_locations | python | jax-ml/jax | jax/_src/pallas/mosaic/error_handling.py | https://github.com/jax-ml/jax/blob/master/jax/_src/pallas/mosaic/error_handling.py | Apache-2.0 |
def parse_location_string(location_string: str) -> tuple[str, list[RawFrame]]:
"""Parses a serialized MLIR location.
Locations strings have the format:
`loc("location_name"(<callsite>))`
Where <callsite> is a nested callsite string representing the entire
call stack:
`callsite("fn_name"("filename":lineno:... | Parses a serialized MLIR location.
Locations strings have the format:
`loc("location_name"(<callsite>))`
Where <callsite> is a nested callsite string representing the entire
call stack:
`callsite("fn_name"("filename":lineno:colno) at callsite(...))`
Args:
location_string: A string serialization of an... | parse_location_string | python | jax-ml/jax | jax/_src/pallas/mosaic/error_handling.py | https://github.com/jax-ml/jax/blob/master/jax/_src/pallas/mosaic/error_handling.py | Apache-2.0 |
def traceback_from_raw_frames(frames: list[RawFrame]) -> types.TracebackType:
"""Constructs a traceback from a list of RawFrame objects."""
xla_frames = [
xla_client.Frame(frame.filename, frame.func_name, -1, frame.lineno)
for frame in frames
]
return xla_client.Traceback.traceback_from_frames(xla_frame... | Constructs a traceback from a list of RawFrame objects. | traceback_from_raw_frames | python | jax-ml/jax | jax/_src/pallas/mosaic/error_handling.py | https://github.com/jax-ml/jax/blob/master/jax/_src/pallas/mosaic/error_handling.py | Apache-2.0 |
def sync_copy(src_ref, dst_ref):
"""Copies a PyTree of Refs to another PyTree of Refs.
Args:
src_ref: A Pytree of source Refs/TransformedRefs.
dst_ref: A Pytree of destination Refs/TransformedRefs.
"""
if not jax.tree.leaves(src_ref):
# No buffers to copy so skip the function.
return
@functo... | Copies a PyTree of Refs to another PyTree of Refs.
Args:
src_ref: A Pytree of source Refs/TransformedRefs.
dst_ref: A Pytree of destination Refs/TransformedRefs.
| sync_copy | python | jax-ml/jax | jax/_src/pallas/mosaic/helpers.py | https://github.com/jax-ml/jax/blob/master/jax/_src/pallas/mosaic/helpers.py | Apache-2.0 |
def run_on_first_core(core_axis_name: str):
"""Runs a function on the first core in a given axis."""
num_cores = jax.lax.axis_size(core_axis_name)
if num_cores == 1:
return lambda f: f()
def wrapped(f):
core_id = jax.lax.axis_index(core_axis_name)
@pl_helpers.when(core_id == 0)
@functools.wrap... | Runs a function on the first core in a given axis. | run_on_first_core | python | jax-ml/jax | jax/_src/pallas/mosaic/helpers.py | https://github.com/jax-ml/jax/blob/master/jax/_src/pallas/mosaic/helpers.py | Apache-2.0 |
def core_barrier(sem, *, core_axis_name: str):
"""Synchronizes all cores in a given axis."""
num_cores = jax.lax.axis_size(core_axis_name)
core_id = jax.lax.axis_index(core_axis_name)
@pl_helpers.when(num_cores > 1)
def _():
with jax.named_scope("sync_cores"):
def signal_core(i):
# Don't s... | Synchronizes all cores in a given axis. | core_barrier | python | jax-ml/jax | jax/_src/pallas/mosaic/helpers.py | https://github.com/jax-ml/jax/blob/master/jax/_src/pallas/mosaic/helpers.py | Apache-2.0 |
def _get_global_core_id(device_id, local_core_id):
"""Computes the global core ID from the given device and local core ID."""
device_id = int(device_id)
local_core_id = int(local_core_id)
return device_id * _get_shared_memory().num_cores_per_device + local_core_id | Computes the global core ID from the given device and local core ID. | _get_global_core_id | python | jax-ml/jax | jax/_src/pallas/mosaic/interpret.py | https://github.com/jax-ml/jax/blob/master/jax/_src/pallas/mosaic/interpret.py | Apache-2.0 |
def signal(self, inc, global_core_id, clock):
"""Signal the semaphore on `(device_id, core_id)` by `inc`.
Args:
inc: A positive integer. The amount by which to increment the semaphore
on the target device.
global_core_id: The ID of the target core.
clock: The vector clock of the sign... | Signal the semaphore on `(device_id, core_id)` by `inc`.
Args:
inc: A positive integer. The amount by which to increment the semaphore
on the target device.
global_core_id: The ID of the target core.
clock: The vector clock of the signaling device at the time of the signal.
| signal | python | jax-ml/jax | jax/_src/pallas/mosaic/interpret.py | https://github.com/jax-ml/jax/blob/master/jax/_src/pallas/mosaic/interpret.py | Apache-2.0 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.