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 arrays_to_spvalues( spenv: SparsifyEnv, args: Any ) -> Any: """Convert a pytree of (sparse) arrays to an equivalent pytree of spvalues.""" def array_to_spvalue(arg): if isinstance(arg, BCOO): return spenv.sparse(arg.shape, arg.data, arg.indices, indices_sorted=arg...
Convert a pytree of (sparse) arrays to an equivalent pytree of spvalues.
arrays_to_spvalues
python
jax-ml/jax
jax/experimental/sparse/transform.py
https://github.com/jax-ml/jax/blob/master/jax/experimental/sparse/transform.py
Apache-2.0
def spvalues_to_arrays( spenv: SparsifyEnv, spvalues: Any, ) -> Any: """Convert a pytree of spvalues to an equivalent pytree of (sparse) arrays.""" def spvalue_to_array(spvalue): if spvalue.is_bcoo(): return BCOO((spenv.data(spvalue), spenv.indices(spvalue)), shape=spvalue.sh...
Convert a pytree of spvalues to an equivalent pytree of (sparse) arrays.
spvalues_to_arrays
python
jax-ml/jax
jax/experimental/sparse/transform.py
https://github.com/jax-ml/jax/blob/master/jax/experimental/sparse/transform.py
Apache-2.0
def spvalues_to_avals( spenv: SparsifyEnv, spvalues: Any, ) -> Any: """Convert a pytree of spvalues to an equivalent pytree of abstract values.""" def spvalue_to_aval(spvalue): data = spenv.data(spvalue) return core.ShapedArray(spvalue.shape, data.dtype, data.aval.weak_type) return tree_map(sp...
Convert a pytree of spvalues to an equivalent pytree of abstract values.
spvalues_to_avals
python
jax-ml/jax
jax/experimental/sparse/transform.py
https://github.com/jax-ml/jax/blob/master/jax/experimental/sparse/transform.py
Apache-2.0
def _sparsify_with_interpreter(f): """Implementation of sparsify() using jaxpr interpreter.""" f_raw = sparsify_raw(f) @functools.wraps(f) def wrapped(*args, **params): spenv = SparsifyEnv() spvalues = arrays_to_spvalues(spenv, args) spvalues_out, out_tree = f_raw(spenv, *spvalues, **params) out...
Implementation of sparsify() using jaxpr interpreter.
_sparsify_with_interpreter
python
jax-ml/jax
jax/experimental/sparse/transform.py
https://github.com/jax-ml/jax/blob/master/jax/experimental/sparse/transform.py
Apache-2.0
def sparsify(f, use_tracer=False): """Experimental sparsification transform. Examples: Decorate JAX functions to make them compatible with :class:`jax.experimental.sparse.BCOO` matrices: >>> from jax.experimental import sparse >>> @sparse.sparsify ... def f(M, v): ... return 2 * M.T @ ...
Experimental sparsification transform. Examples: Decorate JAX functions to make them compatible with :class:`jax.experimental.sparse.BCOO` matrices: >>> from jax.experimental import sparse >>> @sparse.sparsify ... def f(M, v): ... return 2 * M.T @ v >>> M = sparse.BCOO.fromdense(jnp...
sparsify
python
jax-ml/jax
jax/experimental/sparse/transform.py
https://github.com/jax-ml/jax/blob/master/jax/experimental/sparse/transform.py
Apache-2.0
def _ensure_unique_indices(spenv, spvalue): """Return an spvalue representation with deduplicated indices.""" if spvalue.is_dense() or spvalue.unique_indices: return spvalue arr = spvalues_to_arrays(spenv, spvalue) arr = arr.sum_duplicates(nse=arr.nse, remove_zeros=False) return arrays_to_spvalues(spenv, ...
Return an spvalue representation with deduplicated indices.
_ensure_unique_indices
python
jax-ml/jax
jax/experimental/sparse/transform.py
https://github.com/jax-ml/jax/blob/master/jax/experimental/sparse/transform.py
Apache-2.0
def nfold_vmap(fun, N, *, broadcasted=True, in_axes=0): """Convenience function to apply (broadcasted) vmap N times.""" _vmap = broadcasting_vmap if broadcasted else vmap for _ in range(N): fun = _vmap(fun, in_axes=in_axes) return fun
Convenience function to apply (broadcasted) vmap N times.
nfold_vmap
python
jax-ml/jax
jax/experimental/sparse/util.py
https://github.com/jax-ml/jax/blob/master/jax/experimental/sparse/util.py
Apache-2.0
def _csr_extract(indices: Array, indptr: Array, mat: Array) -> Array: """Extract values of dense matrix mat at given CSR indices.""" row, col = _csr_to_coo(indices, indptr) return _coo_extract(row, col, mat)
Extract values of dense matrix mat at given CSR indices.
_csr_extract
python
jax-ml/jax
jax/experimental/sparse/util.py
https://github.com/jax-ml/jax/blob/master/jax/experimental/sparse/util.py
Apache-2.0
def _count_stored_elements_per_batch(mat: Array, n_batch: int = 0, n_dense: int = 0) -> Array: """Return per-batch number of stored elements (nse) of a dense matrix.""" mat = jnp.asarray(mat) mask = (mat != 0) if n_dense > 0: mask = mask.any(tuple(-(i + 1) for i in range(n_dense))) mask = mask.sum(tuple(r...
Return per-batch number of stored elements (nse) of a dense matrix.
_count_stored_elements_per_batch
python
jax-ml/jax
jax/experimental/sparse/util.py
https://github.com/jax-ml/jax/blob/master/jax/experimental/sparse/util.py
Apache-2.0
def _dot_general_validated_shape( lhs_shape: tuple[int, ...], rhs_shape: tuple[int, ...], dimension_numbers: DotDimensionNumbers) -> tuple[int, ...]: """Validate the inputs and return the output shape.""" lhs = core.ShapedArray(lhs_shape, np.float32) rhs = core.ShapedArray(rhs_shape, np.float32) return ...
Validate the inputs and return the output shape.
_dot_general_validated_shape
python
jax-ml/jax
jax/experimental/sparse/util.py
https://github.com/jax-ml/jax/blob/master/jax/experimental/sparse/util.py
Apache-2.0
def send_or_recv( x: jax.Array, tgt_sharding: jax.sharding.Sharding, src_sharding: jax.sharding.Sharding | None = None, ): """ When `src_sharding is None` this function corresponds to a send and `x.sharding` must be equal to `tgt_sharding`. When `src_sharding is not None` this function corre...
When `src_sharding is None` this function corresponds to a send and `x.sharding` must be equal to `tgt_sharding`. When `src_sharding is not None` this function corresponds to a receive and `x` will be consumed, i.e. it's unsafe to use `x` after `send_or_recv(x, src_sharding=...)`. `x` can be a "gl...
send_or_recv
python
jax-ml/jax
jax/experimental/_private_mm/mini_dime.py
https://github.com/jax-ml/jax/blob/master/jax/experimental/_private_mm/mini_dime.py
Apache-2.0
def launch_example(num_processes, user_main, num_devices=8): """ A launcher for examples running across multiple processes on a single node. Returns true iff all processes exited successfully. Example code my_example.py: def my_example(num_processes, process_id): # Do some distribut...
A launcher for examples running across multiple processes on a single node. Returns true iff all processes exited successfully. Example code my_example.py: def my_example(num_processes, process_id): # Do some distributed JAX stuff. ... if __name__ == '__main__': ...
launch_example
python
jax-ml/jax
jax/experimental/_private_mm/examples/launch_utils.py
https://github.com/jax-ml/jax/blob/master/jax/experimental/_private_mm/examples/launch_utils.py
Apache-2.0
def setup_tpu(tpu_driver_version=None): """Raises an error. Do not use.""" raise RuntimeError( "jax.tools.colab_tpu.setup_tpu() was required for older JAX versions" " running on older generations of TPUs, and should no longer be used.")
Raises an error. Do not use.
setup_tpu
python
jax-ml/jax
jax/tools/colab_tpu.py
https://github.com/jax-ml/jax/blob/master/jax/tools/colab_tpu.py
Apache-2.0
def jax_to_ir(fn, input_shapes, *, constants=None, format): """Converts a JAX function to a serialized ir and a debug txt dump. Args: fn: Function to convert. input_shapes: List of tuples (arg name, jax.core.ShapedArray), indicating the shapes of the arguments to fn. The order of parameters in ...
Converts a JAX function to a serialized ir and a debug txt dump. Args: fn: Function to convert. input_shapes: List of tuples (arg name, jax.core.ShapedArray), indicating the shapes of the arguments to fn. The order of parameters in the resulting XLA program will match the order in this list. ...
jax_to_ir
python
jax-ml/jax
jax/tools/jax_to_ir.py
https://github.com/jax-ml/jax/blob/master/jax/tools/jax_to_ir.py
Apache-2.0
def save_anything_except_these_names(*names_not_to_save): """Save any values (not just named ones) excluding the names given.""" names_not_to_save = frozenset(names_not_to_save) def policy(prim, *_, **params): if prim is name_p: return params['name'] not in names_not_to_save return True # allow sav...
Save any values (not just named ones) excluding the names given.
save_anything_except_these_names
python
jax-ml/jax
jax/_src/ad_checkpoint.py
https://github.com/jax-ml/jax/blob/master/jax/_src/ad_checkpoint.py
Apache-2.0
def save_any_names_but_these(*names_not_to_save): """Save only named values, excluding the names given.""" names_not_to_save = frozenset(names_not_to_save) def policy(prim, *_, **params): if prim is name_p: return params['name'] not in names_not_to_save return False # only allow saving named values...
Save only named values, excluding the names given.
save_any_names_but_these
python
jax-ml/jax
jax/_src/ad_checkpoint.py
https://github.com/jax-ml/jax/blob/master/jax/_src/ad_checkpoint.py
Apache-2.0
def save_only_these_names(*names_which_can_be_saved): """Save only named values, and only among the names given.""" names_which_can_be_saved = set(names_which_can_be_saved) def policy(prim, *_, **params): if prim is name_p: return params['name'] in names_which_can_be_saved return False # not saveab...
Save only named values, and only among the names given.
save_only_these_names
python
jax-ml/jax
jax/_src/ad_checkpoint.py
https://github.com/jax-ml/jax/blob/master/jax/_src/ad_checkpoint.py
Apache-2.0
def _nan_check_posthook(fun, args, kwargs, output): """Hook function called by the C++ jit/pmap to perform NaN checking.""" buffers = [] for leaf in tree_leaves(output): if hasattr(leaf, "addressable_shards"): buffers.extend([shard.data for shard in leaf.addressable_shards]) try: dispatch.check_s...
Hook function called by the C++ jit/pmap to perform NaN checking.
_nan_check_posthook
python
jax-ml/jax
jax/_src/api.py
https://github.com/jax-ml/jax/blob/master/jax/_src/api.py
Apache-2.0
def _allow_deprecated_jit_signature(f: F) -> F: """Temporary decorator for the jit signature deprecation.""" @wraps(f) def wrapped(*args, **kwargs): if len(args) == 1 or deprecations.is_accelerated('jax-jit-positional-args'): # Fast path for typical usage. return f(*args, **kwargs) if 'fun' in...
Temporary decorator for the jit signature deprecation.
_allow_deprecated_jit_signature
python
jax-ml/jax
jax/_src/api.py
https://github.com/jax-ml/jax/blob/master/jax/_src/api.py
Apache-2.0
def jit( fun: Callable, /, *, in_shardings: Any = sharding_impls.UNSPECIFIED, out_shardings: Any = sharding_impls.UNSPECIFIED, static_argnums: int | Sequence[int] | None = None, static_argnames: str | Iterable[str] | None = None, donate_argnums: int | Sequence[int] | None = None, donate_argnames: str | It...
Sets up ``fun`` for just-in-time compilation with XLA. Args: fun: Function to be jitted. ``fun`` should be a pure function. The arguments and return value of ``fun`` should be arrays, scalar, or (nested) standard Python containers (tuple/list/dict) thereof. Positional arguments indicated by ``...
jit
python
jax-ml/jax
jax/_src/api.py
https://github.com/jax-ml/jax/blob/master/jax/_src/api.py
Apache-2.0
def grad(fun: Callable, argnums: int | Sequence[int] = 0, has_aux: bool = False, holomorphic: bool = False, allow_int: bool = False, reduce_axes: Sequence[AxisName] = ()) -> Callable: """Creates a function that evaluates the gradient of ``fun``. Args: fun: Function to be differentiat...
Creates a function that evaluates the gradient of ``fun``. Args: fun: Function to be differentiated. Its arguments at positions specified by ``argnums`` should be arrays, scalars, or standard Python containers. Argument arrays in the positions specified by ``argnums`` must be of inexact (i.e., ...
grad
python
jax-ml/jax
jax/_src/api.py
https://github.com/jax-ml/jax/blob/master/jax/_src/api.py
Apache-2.0
def value_and_grad(fun: Callable, argnums: int | Sequence[int] = 0, has_aux: bool = False, holomorphic: bool = False, allow_int: bool = False, reduce_axes: Sequence[AxisName] = () ) -> Callable[..., tuple[Any, Any]]: """Create a function that evaluates both ``fun`` and the grad...
Create a function that evaluates both ``fun`` and the gradient of ``fun``. Args: fun: Function to be differentiated. Its arguments at positions specified by ``argnums`` should be arrays, scalars, or standard Python containers. It should return a scalar (which includes arrays with shape ``()`` but not...
value_and_grad
python
jax-ml/jax
jax/_src/api.py
https://github.com/jax-ml/jax/blob/master/jax/_src/api.py
Apache-2.0
def fwd_and_bwd( fun: Callable, argnums: int | Sequence[int], has_aux: bool = False, jitted: bool = True, ) -> tuple[Callable, Callable]: """Creates functions ``fwd`` and ``bwd`` corresponding to the forward and backward pass of a given function ``fun``. The forward function ``fwd(*args)`` functionally be...
Creates functions ``fwd`` and ``bwd`` corresponding to the forward and backward pass of a given function ``fun``. The forward function ``fwd(*args)`` functionally behaves much like ``y, fun_vjp = jax.vjp(fun, *args)``, but allows reuse of the backward function ``bwd`` across multiple iterations, which is useful...
fwd_and_bwd
python
jax-ml/jax
jax/_src/api.py
https://github.com/jax-ml/jax/blob/master/jax/_src/api.py
Apache-2.0
def jacfwd(fun: Callable, argnums: int | Sequence[int] = 0, has_aux: bool = False, holomorphic: bool = False) -> Callable: """Jacobian of ``fun`` evaluated column-by-column using forward-mode AD. Args: fun: Function whose Jacobian is to be computed. argnums: Optional, integer or sequence of inte...
Jacobian of ``fun`` evaluated column-by-column using forward-mode AD. Args: fun: Function whose Jacobian is to be computed. argnums: Optional, integer or sequence of integers. Specifies which positional argument(s) to differentiate with respect to (default ``0``). has_aux: Optional, bool. Indicates...
jacfwd
python
jax-ml/jax
jax/_src/api.py
https://github.com/jax-ml/jax/blob/master/jax/_src/api.py
Apache-2.0
def jacrev(fun: Callable, argnums: int | Sequence[int] = 0, has_aux: bool = False, holomorphic: bool = False, allow_int: bool = False) -> Callable: """Jacobian of ``fun`` evaluated row-by-row using reverse-mode AD. Args: fun: Function whose Jacobian is to be computed. argnums: Optional, integer ...
Jacobian of ``fun`` evaluated row-by-row using reverse-mode AD. Args: fun: Function whose Jacobian is to be computed. argnums: Optional, integer or sequence of integers. Specifies which positional argument(s) to differentiate with respect to (default ``0``). has_aux: Optional, bool. Indicates wheth...
jacrev
python
jax-ml/jax
jax/_src/api.py
https://github.com/jax-ml/jax/blob/master/jax/_src/api.py
Apache-2.0
def hessian(fun: Callable, argnums: int | Sequence[int] = 0, has_aux: bool = False, holomorphic: bool = False) -> Callable: """Hessian of ``fun`` as a dense array. Args: fun: Function whose Hessian is to be computed. Its arguments at positions specified by ``argnums`` should be arrays, scala...
Hessian of ``fun`` as a dense array. Args: fun: Function whose Hessian is to be computed. Its arguments at positions specified by ``argnums`` should be arrays, scalars, or standard Python containers thereof. It should return arrays, scalars, or standard Python containers thereof. argnums: ...
hessian
python
jax-ml/jax
jax/_src/api.py
https://github.com/jax-ml/jax/blob/master/jax/_src/api.py
Apache-2.0
def _unravel_array_into_pytree(pytree, axis, example, arr): """Unravel an array into a PyTree with a given structure. Args: pytree: The pytree that provides the structure. axis: The parameter axis is either -1, 0, or 1. It controls the resulting shapes. example: If specified, cast the com...
Unravel an array into a PyTree with a given structure. Args: pytree: The pytree that provides the structure. axis: The parameter axis is either -1, 0, or 1. It controls the resulting shapes. example: If specified, cast the components to the matching dtype/weak_type, or else use the ...
_unravel_array_into_pytree
python
jax-ml/jax
jax/_src/api.py
https://github.com/jax-ml/jax/blob/master/jax/_src/api.py
Apache-2.0
def vmap(fun: F, in_axes: int | None | Sequence[Any] = 0, out_axes: Any = 0, axis_name: AxisName | None = None, axis_size: int | None = None, spmd_axis_name: AxisName | tuple[AxisName, ...] | None = None) -> F: """Vectorizing map. Creates a function which maps ``fun`` over...
Vectorizing map. Creates a function which maps ``fun`` over argument axes. Args: fun: Function to be mapped over additional axes. in_axes: An integer, None, or sequence of values specifying which input array axes to map over. If each positional argument to ``fun`` is an array, then ``in_axes`` c...
vmap
python
jax-ml/jax
jax/_src/api.py
https://github.com/jax-ml/jax/blob/master/jax/_src/api.py
Apache-2.0
def jvp( fun: Callable, primals, tangents, has_aux: bool = False ) -> tuple[Any, ...]: """Computes a (forward-mode) Jacobian-vector product of ``fun``. Args: fun: Function to be differentiated. Its arguments should be arrays, scalars, or standard Python containers of arrays or scalars. It should re...
Computes a (forward-mode) Jacobian-vector product of ``fun``. Args: fun: Function to be differentiated. Its arguments should be arrays, scalars, or standard Python containers of arrays or scalars. It should return an array, scalar, or standard Python container of arrays or scalars. primals: The p...
jvp
python
jax-ml/jax
jax/_src/api.py
https://github.com/jax-ml/jax/blob/master/jax/_src/api.py
Apache-2.0
def _jvp(fun: lu.WrappedFun, primals, tangents, has_aux=False): """Variant of jvp() that takes an lu.WrappedFun.""" primals_, (), primal_box_data = pjit._flatten_boxes(fun.debug_info, primals, {}) tangents_, (), tangent_box_data = pjit._flatten_boxes(fun.debug_info, tangents, {}) fun = pjit._handle_boxes(fun, f...
Variant of jvp() that takes an lu.WrappedFun.
_jvp
python
jax-ml/jax
jax/_src/api.py
https://github.com/jax-ml/jax/blob/master/jax/_src/api.py
Apache-2.0
def linearize(fun: Callable, *primals, has_aux: bool = False ) -> tuple[Any, Callable] | tuple[Any, Callable, Any]: """Produces a linear approximation to ``fun`` using :py:func:`jvp` and partial eval. Args: fun: Function to be differentiated. Its arguments should be arrays, scalars, or stan...
Produces a linear approximation to ``fun`` using :py:func:`jvp` and partial eval. Args: fun: Function to be differentiated. Its arguments should be arrays, scalars, or standard Python containers of arrays or scalars. It should return an array, scalar, or standard python container of arrays or scalars...
linearize
python
jax-ml/jax
jax/_src/api.py
https://github.com/jax-ml/jax/blob/master/jax/_src/api.py
Apache-2.0
def vjp( fun: Callable, *primals, has_aux: bool = False, reduce_axes=() ) -> tuple[Any, Callable] | tuple[Any, Callable, Any]: """Compute a (reverse-mode) vector-Jacobian product of ``fun``. :py:func:`grad` is implemented as a special case of :py:func:`vjp`. Args: fun: Function to be differentiated. I...
Compute a (reverse-mode) vector-Jacobian product of ``fun``. :py:func:`grad` is implemented as a special case of :py:func:`vjp`. Args: fun: Function to be differentiated. Its arguments should be arrays, scalars, or standard Python containers of arrays or scalars. It should return an array, scalar,...
vjp
python
jax-ml/jax
jax/_src/api.py
https://github.com/jax-ml/jax/blob/master/jax/_src/api.py
Apache-2.0
def _vjp(fun: lu.WrappedFun, *primals, has_aux=False): """Variant of vjp() that takes an lu.WrappedFun.""" primals_flat, in_tree = tree_flatten(primals) for arg in primals_flat: dispatch.check_arg(arg) if not has_aux: flat_fun, out_tree = flatten_fun_nokwargs(fun, in_tree) out_primals, vjp = ad.vjp(flat...
Variant of vjp() that takes an lu.WrappedFun.
_vjp
python
jax-ml/jax
jax/_src/api.py
https://github.com/jax-ml/jax/blob/master/jax/_src/api.py
Apache-2.0
def linear_transpose(fun: Callable, *primals, reduce_axes=()) -> Callable: """Transpose a function that is promised to be linear. For linear functions, this transformation is equivalent to :py:func:`vjp`, but avoids the overhead of computing the forward pass. The outputs of the transposed function will always...
Transpose a function that is promised to be linear. For linear functions, this transformation is equivalent to :py:func:`vjp`, but avoids the overhead of computing the forward pass. The outputs of the transposed function will always have the exact same dtypes as ``primals``, even if some values are truncated ...
linear_transpose
python
jax-ml/jax
jax/_src/api.py
https://github.com/jax-ml/jax/blob/master/jax/_src/api.py
Apache-2.0
def make_jaxpr( fun: Callable, static_argnums: int | Iterable[int] = (), axis_env: Sequence[tuple[AxisName, int]] | None = None, return_shape: bool = False, abstracted_axes: Any | None = None, ) -> Callable[..., core.ClosedJaxpr | tuple[core.ClosedJaxpr, Any]]: """Create a function that returns th...
Create a function that returns the jaxpr of ``fun`` given example args. Args: fun: The function whose ``jaxpr`` is to be computed. Its positional arguments and return value should be arrays, scalars, or standard Python containers (tuple/list/dict) thereof. static_argnums: See the :py:func:`jax.ji...
make_jaxpr
python
jax-ml/jax
jax/_src/api.py
https://github.com/jax-ml/jax/blob/master/jax/_src/api.py
Apache-2.0
def _check_string_compatible_sharding(s): """Checks if target devices are compatible with string arrays.""" if isinstance(s, xc.Device) and s.device_kind == "cpu": return if (isinstance(s, Sharding) and s._internal_device_list[0].device_kind == "cpu"): return raise TypeError( "String arrays ...
Checks if target devices are compatible with string arrays.
_check_string_compatible_sharding
python
jax-ml/jax
jax/_src/api.py
https://github.com/jax-ml/jax/blob/master/jax/_src/api.py
Apache-2.0
def device_put_sharded(shards: Sequence[Any], devices: Sequence[xc.Device]): # noqa: F811 """Transfer array shards to specified devices and form Array(s). Args: shards: A sequence of arrays, scalars, or (nested) standard Python containers thereof representing the shards to be stacked together to form ...
Transfer array shards to specified devices and form Array(s). Args: shards: A sequence of arrays, scalars, or (nested) standard Python containers thereof representing the shards to be stacked together to form the output. The length of ``shards`` must equal the length of ``devices``. devices: A se...
device_put_sharded
python
jax-ml/jax
jax/_src/api.py
https://github.com/jax-ml/jax/blob/master/jax/_src/api.py
Apache-2.0
def device_put_replicated(x: Any, devices: Sequence[xc.Device]): # noqa: F811 """Transfer array(s) to each specified device and form Array(s). Args: x: an array, scalar, or (nested) standard Python container thereof representing the array to be replicated to form the output. devices: A sequence of :...
Transfer array(s) to each specified device and form Array(s). Args: x: an array, scalar, or (nested) standard Python container thereof representing the array to be replicated to form the output. devices: A sequence of :py:class:`Device` instances representing the devices to which ``x`` will be tr...
device_put_replicated
python
jax-ml/jax
jax/_src/api.py
https://github.com/jax-ml/jax/blob/master/jax/_src/api.py
Apache-2.0
def device_get(x: Any): """Transfer ``x`` to host. If ``x`` is a pytree, then the individual buffers are copied in parallel. Args: x: An array, scalar, Array or (nested) standard Python container thereof representing the array to be transferred to host. Returns: An array or (nested) Python cont...
Transfer ``x`` to host. If ``x`` is a pytree, then the individual buffers are copied in parallel. Args: x: An array, scalar, Array or (nested) standard Python container thereof representing the array to be transferred to host. Returns: An array or (nested) Python container thereof representing th...
device_get
python
jax-ml/jax
jax/_src/api.py
https://github.com/jax-ml/jax/blob/master/jax/_src/api.py
Apache-2.0
def eval_shape(fun: Callable, *args, **kwargs): """Compute the shape/dtype of ``fun`` without any FLOPs. This utility function is useful for performing shape inference. Its input/output behavior is defined by:: def eval_shape(fun, *args, **kwargs): out = fun(*args, **kwargs) shape_dtype_struct =...
Compute the shape/dtype of ``fun`` without any FLOPs. This utility function is useful for performing shape inference. Its input/output behavior is defined by:: def eval_shape(fun, *args, **kwargs): out = fun(*args, **kwargs) shape_dtype_struct = lambda x: jax.ShapeDtypeStruct(x.shape, x.dtype) ...
eval_shape
python
jax-ml/jax
jax/_src/api.py
https://github.com/jax-ml/jax/blob/master/jax/_src/api.py
Apache-2.0
def block_until_ready(x): """ Tries to call a ``block_until_ready`` method on pytree leaves. Args: x: a pytree, usually with at least some JAX array instances at its leaves. Returns: A pytree with the same structure and values of the input, where the values of all JAX array leaves are ready. """...
Tries to call a ``block_until_ready`` method on pytree leaves. Args: x: a pytree, usually with at least some JAX array instances at its leaves. Returns: A pytree with the same structure and values of the input, where the values of all JAX array leaves are ready.
block_until_ready
python
jax-ml/jax
jax/_src/api.py
https://github.com/jax-ml/jax/blob/master/jax/_src/api.py
Apache-2.0
def copy_to_host_async(x): """ Tries to call a ``copy_to_host_async`` method on pytree leaves. For each leaf this method will try to call the ``copy_to_host_async`` method on the leaf. If the leaf is not a JAX array, or if the leaf does not have a ``copy_to_host_async`` method, then this method will do nothi...
Tries to call a ``copy_to_host_async`` method on pytree leaves. For each leaf this method will try to call the ``copy_to_host_async`` method on the leaf. If the leaf is not a JAX array, or if the leaf does not have a ``copy_to_host_async`` method, then this method will do nothing to the leaf. Args: x: ...
copy_to_host_async
python
jax-ml/jax
jax/_src/api.py
https://github.com/jax-ml/jax/blob/master/jax/_src/api.py
Apache-2.0
def clear_backends(): """ Clear all backend clients so that new backend clients can be created later. """ xb._clear_backends() xb.local_devices.cache_clear() xb.process_count.cache_clear() dispatch.xla_primitive_callable.cache_clear() util.clear_all_caches() pjit._infer_params_cached.cache_clear() p...
Clear all backend clients so that new backend clients can be created later.
clear_backends
python
jax-ml/jax
jax/_src/api.py
https://github.com/jax-ml/jax/blob/master/jax/_src/api.py
Apache-2.0
def clear_caches(): """Clear all compilation and staging caches. This doesn't clear the persistent cache; to disable it (e.g. for benchmarks), set the jax_enable_compilation_cache config option to False. """ # Clear all lu.cache, util.cache and util.weakref_lru_cache instances # (used for staging and Pytho...
Clear all compilation and staging caches. This doesn't clear the persistent cache; to disable it (e.g. for benchmarks), set the jax_enable_compilation_cache config option to False.
clear_caches
python
jax-ml/jax
jax/_src/api.py
https://github.com/jax-ml/jax/blob/master/jax/_src/api.py
Apache-2.0
def _ensure_index(x: Any) -> int | tuple[int, ...]: """Ensure x is either an index or a tuple of indices.""" x = core.concrete_or_error(None, x, "expected a static index or sequence of indices.") try: return operator.index(x) except TypeError: return tuple(map(operator.index, x))
Ensure x is either an index or a tuple of indices.
_ensure_index
python
jax-ml/jax
jax/_src/api_util.py
https://github.com/jax-ml/jax/blob/master/jax/_src/api_util.py
Apache-2.0
def _validate_argnums(sig: inspect.Signature, argnums: tuple[int, ...], argnums_name: str) -> None: """ Validate that the argnums are sensible for a given function. For functions that accept a variable number of positions arguments (`f(..., *args)`) all positive argnums are considered valid. """ n_pos_args...
Validate that the argnums are sensible for a given function. For functions that accept a variable number of positions arguments (`f(..., *args)`) all positive argnums are considered valid.
_validate_argnums
python
jax-ml/jax
jax/_src/api_util.py
https://github.com/jax-ml/jax/blob/master/jax/_src/api_util.py
Apache-2.0
def _validate_argnames( sig: inspect.Signature, argnames: tuple[str, ...], argnames_name: str ) -> None: """ Validate that the argnames are sensible for a given function. For functions that accept a variable keyword arguments (`f(..., **kwargs)`) all argnames are considered valid except those marked as p...
Validate that the argnames are sensible for a given function. For functions that accept a variable keyword arguments (`f(..., **kwargs)`) all argnames are considered valid except those marked as position-only (`f(pos_only, /, ...)`).
_validate_argnames
python
jax-ml/jax
jax/_src/api_util.py
https://github.com/jax-ml/jax/blob/master/jax/_src/api_util.py
Apache-2.0
def _ensure_inbounds(allow_invalid: bool, num_args: int, argnums: Sequence[int] ) -> tuple[int, ...]: """Ensure argnum is within bounds. Also resolves negative argnums.""" result = [] for i in argnums: if i >= num_args and allow_invalid: continue if not -num_args <= i < num_args: ...
Ensure argnum is within bounds. Also resolves negative argnums.
_ensure_inbounds
python
jax-ml/jax
jax/_src/api_util.py
https://github.com/jax-ml/jax/blob/master/jax/_src/api_util.py
Apache-2.0
def argnums_partial_except(f: lu.WrappedFun, static_argnums: tuple[int, ...], args: tuple[Any, ...], *, allow_invalid: bool): "Version of ``argnums_partial`` that checks hashability of static_argnums." if not static_argnums: return f, args static_argnums = _ensure_inbounds(allow_inv...
Version of ``argnums_partial`` that checks hashability of static_argnums.
argnums_partial_except
python
jax-ml/jax
jax/_src/api_util.py
https://github.com/jax-ml/jax/blob/master/jax/_src/api_util.py
Apache-2.0
def donation_vector(donate_argnums, donate_argnames, in_tree, kws: bool = True) -> tuple[bool, ...]: """Returns a tuple with a boolean value for each leaf in args and kwargs. What if a user specifies donate_argnums but calls the function with kwargs or vice-versa? In that case, in `resolve_ar...
Returns a tuple with a boolean value for each leaf in args and kwargs. What if a user specifies donate_argnums but calls the function with kwargs or vice-versa? In that case, in `resolve_argnums` using the signature of the function, the counterpart (donate_argnames or donate_argnums respectively) is calculated...
donation_vector
python
jax-ml/jax
jax/_src/api_util.py
https://github.com/jax-ml/jax/blob/master/jax/_src/api_util.py
Apache-2.0
def rebase_donate_argnums(donate_argnums, static_argnums) -> tuple[int, ...]: """Shifts donate to account for static. >>> rebase_donate_argnums((3, 4), (0, 1)) (1, 2) Args: donate_argnums: An iterable of ints. static_argnums: An iterable of ints. Returns: A tuple of unique, sorted integer value...
Shifts donate to account for static. >>> rebase_donate_argnums((3, 4), (0, 1)) (1, 2) Args: donate_argnums: An iterable of ints. static_argnums: An iterable of ints. Returns: A tuple of unique, sorted integer values based on donate_argnums with each element offset to account for static_argnum...
rebase_donate_argnums
python
jax-ml/jax
jax/_src/api_util.py
https://github.com/jax-ml/jax/blob/master/jax/_src/api_util.py
Apache-2.0
def infer_argnums_and_argnames( sig: inspect.Signature, argnums: int | Iterable[int] | None, argnames: str | Iterable[str] | None, ) -> tuple[tuple[int, ...], tuple[str, ...]]: """Infer missing argnums and argnames for a function with inspect.""" if argnums is None and argnames is None: return (),...
Infer missing argnums and argnames for a function with inspect.
infer_argnums_and_argnames
python
jax-ml/jax
jax/_src/api_util.py
https://github.com/jax-ml/jax/blob/master/jax/_src/api_util.py
Apache-2.0
def resolve_argnums( fun: Callable, signature: inspect.Signature | None, donate_argnums: int | Sequence[int] | None, donate_argnames: str | Iterable[str] | None, static_argnums: int | Sequence[int] | None, static_argnames: str | Iterable[str] | None, ) -> tuple[tuple[int, ...], tuple[str, ...], ...
Validates and completes the argnum/argname specification for a jit. * fills in any missing pieces (e.g., names given numbers, or vice versa), * validates the argument names/numbers against the function signature, * validates that donated and static arguments don't intersect. * rebases the donated arguments so ...
resolve_argnums
python
jax-ml/jax
jax/_src/api_util.py
https://github.com/jax-ml/jax/blob/master/jax/_src/api_util.py
Apache-2.0
def resolve_kwargs(fun: Callable, args, kwargs) -> tuple[Any, ...]: """Resolve input arguments to positional following a function's signature. This will raise a TypeError if any keyword-only arguments were passed by the caller. """ if isinstance(fun, partial): # functools.partial should have an opaque si...
Resolve input arguments to positional following a function's signature. This will raise a TypeError if any keyword-only arguments were passed by the caller.
resolve_kwargs
python
jax-ml/jax
jax/_src/api_util.py
https://github.com/jax-ml/jax/blob/master/jax/_src/api_util.py
Apache-2.0
def debug_info( traced_for: str, fun: Callable, args: Sequence[Any], kwargs: dict[str, Any], *, static_argnums: Sequence[int] = (), static_argnames: Sequence[str] = (), result_paths_thunk: Callable[[], tuple[str, ...]] | None = None, # TODO(necula): check if we really need this, e.g....
Constructd core.DebugInfo for a function given example args and kwargs. `args` and `kwargs` are example positional and keyword arguments, users with `inspect.Signature` to get the names of arguments. The arguments that are considered static for tracing purposes should be included, and designated using `static_...
debug_info
python
jax-ml/jax
jax/_src/api_util.py
https://github.com/jax-ml/jax/blob/master/jax/_src/api_util.py
Apache-2.0
def _non_static_arg_names(fn_signature: inspect.Signature | None, args: Sequence[Any], kwargs: dict[str, Any], static_argnums: Sequence[int], static_argnames: Sequence[str], ) -> tuple[str, ...]: """Returns the nam...
Returns the names of the non-static arguments. If the `fn_signature` is given then we get from it the names of the top-level arguments. In other cases, including when the `args` and `kwargs` do not match the signature, we use names like `args[0[]`, `args[1]`, etc.
_non_static_arg_names
python
jax-ml/jax
jax/_src/api_util.py
https://github.com/jax-ml/jax/blob/master/jax/_src/api_util.py
Apache-2.0
def _reconstruct_array(fun, args, arr_state, aval_state): """Method to reconstruct a device array from a serialized state.""" np_value = fun(*args) np_value.__setstate__(arr_state) jnp_value = api.device_put(np_value) # TODO(slebedev): Remove this branch after December 10th 2024. if "named_shape" in aval_st...
Method to reconstruct a device array from a serialized state.
_reconstruct_array
python
jax-ml/jax
jax/_src/array.py
https://github.com/jax-ml/jax/blob/master/jax/_src/array.py
Apache-2.0
def _validate_shape_and_dtype_for_per_device_arrays( arrays: Sequence[ArrayImpl | np.ndarray], sharding: Sharding, aval: core.ShapedArray, expected_shape: Shape, ): """Validates that per-device arrays are valid and consistent.""" expected_dtype = aval.dtype for db in arrays: if db.dtype != exp...
Validates that per-device arrays are valid and consistent.
_validate_shape_and_dtype_for_per_device_arrays
python
jax-ml/jax
jax/_src/array.py
https://github.com/jax-ml/jax/blob/master/jax/_src/array.py
Apache-2.0
def on_device_size_in_bytes(self): """Returns the total global on-device size of the array in bytes.""" arr = self._arrays[0] per_shard_size = arr.on_device_size_in_bytes() return per_shard_size * self.sharding.num_devices
Returns the total global on-device size of the array in bytes.
on_device_size_in_bytes
python
jax-ml/jax
jax/_src/array.py
https://github.com/jax-ml/jax/blob/master/jax/_src/array.py
Apache-2.0
def global_shards(self) -> Sequence[Shard]: """Returns list of all `Shard`s of the Array across all devices. The result includes shards that are not addressable by the current process. If a `Shard` is not addressable, then its `data` will be `None`. """ self._check_if_deleted() if self.is_fully...
Returns list of all `Shard`s of the Array across all devices. The result includes shards that are not addressable by the current process. If a `Shard` is not addressable, then its `data` will be `None`.
global_shards
python
jax-ml/jax
jax/_src/array.py
https://github.com/jax-ml/jax/blob/master/jax/_src/array.py
Apache-2.0
def make_array_from_process_local_data( sharding: Sharding, local_data: np.ndarray, global_shape: Shape | None = None, ) -> ArrayImpl: # pyformat: disable """Creates distributed tensor using the data available in process. This function is a common special case of `make_array_from_callback`. It assu...
Creates distributed tensor using the data available in process. This function is a common special case of `make_array_from_callback`. It assumes that the data is available in the process and takes care of the index wrangling. The most common case is when the sharding is sharded across the batch dimension an...
make_array_from_process_local_data
python
jax-ml/jax
jax/_src/array.py
https://github.com/jax-ml/jax/blob/master/jax/_src/array.py
Apache-2.0
def make_array_from_single_device_arrays( shape: Shape, sharding: Sharding, arrays: Sequence[basearray.Array], *, dtype: DTypeLike | None = None, ) -> ArrayImpl: r"""Returns a ``jax.Array`` from a sequence of ``jax.Array``\s each on a single device. Every device in input ``sharding``\'s mesh must have a...
Returns a ``jax.Array`` from a sequence of ``jax.Array``\s each on a single device. Every device in input ``sharding``\'s mesh must have an array in ``arrays``\s. Args: shape : Shape of the output ``jax.Array``. This conveys information already included with ``sharding`` and ``arrays`` and serves as ...
make_array_from_single_device_arrays
python
jax-ml/jax
jax/_src/array.py
https://github.com/jax-ml/jax/blob/master/jax/_src/array.py
Apache-2.0
def blocked_fold_in( global_key: ArrayLike, total_size: Shape, block_size: Shape, tile_size: Shape, block_index: Sequence[ArrayLike], ) -> NdKeyList: """Computes a grid of keys for block-invariant sampling. Suppose we wished to construct a 16x512 array of random numbers, using block sizes of 16x128 a...
Computes a grid of keys for block-invariant sampling. Suppose we wished to construct a 16x512 array of random numbers, using block sizes of 16x128 and 16x256. We could select an tile size of 8x128 (which divides both 16x128 and 16x256) and divide the total array in tiles as: --------------------------------- ...
blocked_fold_in
python
jax-ml/jax
jax/_src/blocked_sampler.py
https://github.com/jax-ml/jax/blob/master/jax/_src/blocked_sampler.py
Apache-2.0
def sample_block( sampler_fn: SampleFn, keys: NdKeyList, block_size: Shape, tile_size: Shape, *args, **kwargs ) -> jax.Array: """Draws random samples for a single block. This function is intended to be used in conjunction with `blocked_fold_in`: ``` key_list = blocked_fold_in(global_k...
Draws random samples for a single block. This function is intended to be used in conjunction with `blocked_fold_in`: ``` key_list = blocked_fold_in(global_key, total_size, block_size, tile_size, block_index) samples = sample_block(jax.random.uniform, key_list, block_size, tile_size...
sample_block
python
jax-ml/jax
jax/_src/blocked_sampler.py
https://github.com/jax-ml/jax/blob/master/jax/_src/blocked_sampler.py
Apache-2.0
def buffer_callback( callback: Callable[..., None], result_shape_dtypes: object, *, has_side_effect: bool = False, vmap_method: str | None = None, input_output_aliases: dict[int, int] | None = None, command_buffer_compatible: bool = False, ): """An experimental callback that operates in pl...
An experimental callback that operates in place on device buffers. Only supported on CPU and GPU backends. Note that the plan is for this to eventually be replaced by a consolidated callback API built using JAX mutable arrays, but for now this provides a mechanism for prototyping computational kernels using o...
buffer_callback
python
jax-ml/jax
jax/_src/buffer_callback.py
https://github.com/jax-ml/jax/blob/master/jax/_src/buffer_callback.py
Apache-2.0
def add_flag_prefixes(flag_prefixes: list[str]) -> None: """Add flag prefixes to include in the cache key. Call prior to get(). """ global _extra_flag_prefixes _extra_flag_prefixes += flag_prefixes
Add flag prefixes to include in the cache key. Call prior to get().
add_flag_prefixes
python
jax-ml/jax
jax/_src/cache_key.py
https://github.com/jax-ml/jax/blob/master/jax/_src/cache_key.py
Apache-2.0
def get( module: ir.Module, devices: np.ndarray, compile_options: xla_client.CompileOptions, backend: xla_client.Client, compression_algorithm: str = "zstandard", ignore_callbacks: IgnoreCallbacks = IgnoreCallbacks.NO, ) -> str: """Creates a hashed string to use as a key to the compilation cac...
Creates a hashed string to use as a key to the compilation cache. Creates a cache key that is a hex-encoded string of a unique hash based on the arguments. The hex-encoded string is 256 characters long. Args: module: the input program devices: an array of accelerator devices that the program will run on...
get
python
jax-ml/jax
jax/_src/cache_key.py
https://github.com/jax-ml/jax/blob/master/jax/_src/cache_key.py
Apache-2.0
def _remove_callbacks(m: ir.Module, ignore_callbacks: IgnoreCallbacks): """Removes callback pointers from precompiled IR. Python function pointers are not deterministic across executions. """ def _update_bc_attribute(op: ir.Operation) -> ir.WalkResult: if op.name == "stablehlo.custom_call" and ( ( ...
Removes callback pointers from precompiled IR. Python function pointers are not deterministic across executions.
_remove_callbacks
python
jax-ml/jax
jax/_src/cache_key.py
https://github.com/jax-ml/jax/blob/master/jax/_src/cache_key.py
Apache-2.0
def pure_callback( callback: Callable[..., Any], result_shape_dtypes: Any, *args: Any, sharding: SingleDeviceSharding | None = None, vectorized: bool | None | DeprecatedArg = DeprecatedArg(), vmap_method: str | None = None, **kwargs: Any, ): """Calls a pure Python callback. Works under :fu...
Calls a pure Python callback. Works under :func:`jit`/:func:`~vmap`/etc. For more explanation, see `External Callbacks`_. ``pure_callback`` enables calling a Python function in JIT-ed JAX functions. The input ``callback`` will be passed JAX arrays placed on a local CPU, and it should also return JAX arrays on...
pure_callback
python
jax-ml/jax
jax/_src/callback.py
https://github.com/jax-ml/jax/blob/master/jax/_src/callback.py
Apache-2.0
def io_callback( callback: Callable[..., Any], result_shape_dtypes: Any, *args: Any, sharding: SingleDeviceSharding | None = None, ordered: bool = False, **kwargs: Any, ): """Calls an impure Python callback. For more explanation, see `External Callbacks`_. Args: callback: function to...
Calls an impure Python callback. For more explanation, see `External Callbacks`_. Args: callback: function to execute on the host. It is assumed to be an impure function. If ``callback`` is pure, using :func:`jax.pure_callback` instead may lead to more efficient execution. result_shape_dtypes:...
io_callback
python
jax-ml/jax
jax/_src/callback.py
https://github.com/jax-ml/jax/blob/master/jax/_src/callback.py
Apache-2.0
def get(self) -> str | None: """Returns error message if error happened, None if no error happened.""" exp = self.get_exception() if exp is not None: return str(exp) return None
Returns error message if error happened, None if no error happened.
get
python
jax-ml/jax
jax/_src/checkify.py
https://github.com/jax-ml/jax/blob/master/jax/_src/checkify.py
Apache-2.0
def get_exception(self) -> JaxException | None: """Returns Python exception if error happened, None if no error happened.""" if any(map(np.shape, self._pred.values())): return self._get_batched_exception() else: min_code = None cur_effect = None for error_effect, code in self._code.i...
Returns Python exception if error happened, None if no error happened.
get_exception
python
jax-ml/jax
jax/_src/checkify.py
https://github.com/jax-ml/jax/blob/master/jax/_src/checkify.py
Apache-2.0
def _add_placeholder_effects(self, effects: set[ErrorEffect]): """Fill out Error with `effects` and np.ones arrays of their payloads.""" new_err = self._pred.copy() new_code = self._code.copy() new_payload = self._payload.copy() for effect in effects: if effect not in self._pred.keys(): ...
Fill out Error with `effects` and np.ones arrays of their payloads.
_add_placeholder_effects
python
jax-ml/jax
jax/_src/checkify.py
https://github.com/jax-ml/jax/blob/master/jax/_src/checkify.py
Apache-2.0
def div_error_check(error, enabled_errors, x, y): """Checks for division by zero and NaN.""" if DivisionByZeroError in enabled_errors: any_zero = jnp.any(jnp.equal(y, 0)) error = assert_func(error, any_zero, DivisionByZeroError(get_traceback())) return nan_error_check(lax.div_p, error, enabled_errors, x, ...
Checks for division by zero and NaN.
div_error_check
python
jax-ml/jax
jax/_src/checkify.py
https://github.com/jax-ml/jax/blob/master/jax/_src/checkify.py
Apache-2.0
def scatter_error_check(prim, error, enabled_errors, operand, indices, updates, *, update_jaxpr, update_consts, dimension_numbers, indices_are_sorted, unique_indices, mode): """Checks if indices are within bounds and update does not generate NaN.""" out = prim.bind( ...
Checks if indices are within bounds and update does not generate NaN.
scatter_error_check
python
jax-ml/jax
jax/_src/checkify.py
https://github.com/jax-ml/jax/blob/master/jax/_src/checkify.py
Apache-2.0
def ignore_error_output_jaxpr(jaxpr, num_error_vals: int): """Constructs a checked jaxpr which does not output its error value.""" consts = jaxpr.consts jaxpr = jaxpr.jaxpr new_jaxpr = jaxpr.replace(outvars=jaxpr.outvars[num_error_vals:]) return core.ClosedJaxpr(new_jaxpr, consts)
Constructs a checked jaxpr which does not output its error value.
ignore_error_output_jaxpr
python
jax-ml/jax
jax/_src/checkify.py
https://github.com/jax-ml/jax/blob/master/jax/_src/checkify.py
Apache-2.0
def check(pred: Bool, msg: str, *fmt_args, debug: bool = False, **fmt_kwargs, ) -> None: """Check a predicate, add an error with msg if predicate is False. This is an effectful operation, and can't be staged (jitted/scanned/...). Before staging a function with checks, :fun...
Check a predicate, add an error with msg if predicate is False. This is an effectful operation, and can't be staged (jitted/scanned/...). Before staging a function with checks, :func:`~checkify` it! Args: pred: if False, a FailedCheckError error is added. msg: error message if error is added. Can be a f...
check
python
jax-ml/jax
jax/_src/checkify.py
https://github.com/jax-ml/jax/blob/master/jax/_src/checkify.py
Apache-2.0
def check_error(error: Error) -> None: """Raise an Exception if ``error`` represents a failure. Functionalized by :func:`~checkify`. The semantics of this function are equivalent to: >>> def check_error(err: Error) -> None: ... err.throw() # can raise ValueError But unlike that implementation, ``check_e...
Raise an Exception if ``error`` represents a failure. Functionalized by :func:`~checkify`. The semantics of this function are equivalent to: >>> def check_error(err: Error) -> None: ... err.throw() # can raise ValueError But unlike that implementation, ``check_error`` can be functionalized using the :fu...
check_error
python
jax-ml/jax
jax/_src/checkify.py
https://github.com/jax-ml/jax/blob/master/jax/_src/checkify.py
Apache-2.0
def cloud_tpu_init() -> None: """Automatically sets Cloud TPU topology and other env vars. **This must be called before the TPU runtime is loaded, which happens as soon as JAX's C++ backend is loaded! I.e. call this before xla_bridge or xla_client is imported.** Safe to call in non-Cloud TPU environments. ...
Automatically sets Cloud TPU topology and other env vars. **This must be called before the TPU runtime is loaded, which happens as soon as JAX's C++ backend is loaded! I.e. call this before xla_bridge or xla_client is imported.** Safe to call in non-Cloud TPU environments. Some of these environment variabl...
cloud_tpu_init
python
jax-ml/jax
jax/_src/cloud_tpu_init.py
https://github.com/jax-ml/jax/blob/master/jax/_src/cloud_tpu_init.py
Apache-2.0
def is_cache_used(backend: xla_client.Client) -> bool: """Check if cache is used and report adoption metrics one-time per task. The cache may be initialized during the first call to this function. """ # Return _cache_used directly if _cache_checked is True. If _cache_checked is # False, set it to True, report...
Check if cache is used and report adoption metrics one-time per task. The cache may be initialized during the first call to this function.
is_cache_used
python
jax-ml/jax
jax/_src/compilation_cache.py
https://github.com/jax-ml/jax/blob/master/jax/_src/compilation_cache.py
Apache-2.0
def get_file_cache(path: str) -> tuple[CacheInterface, str] | None: """Returns the file cache and the path to the cache.""" max_size = config.compilation_cache_max_size.value return LRUCache(path, max_size=max_size), path
Returns the file cache and the path to the cache.
get_file_cache
python
jax-ml/jax
jax/_src/compilation_cache.py
https://github.com/jax-ml/jax/blob/master/jax/_src/compilation_cache.py
Apache-2.0
def initialize_cache(path) -> None: """ This API is deprecated; use set_cache_dir instead. Set the path. To take effect, should be called prior to any calls to get_executable_and_time() and put_executable_and_time(). """ warnings.warn("initialize_cache is deprecated; use set_cache_dir instead", ...
This API is deprecated; use set_cache_dir instead. Set the path. To take effect, should be called prior to any calls to get_executable_and_time() and put_executable_and_time().
initialize_cache
python
jax-ml/jax
jax/_src/compilation_cache.py
https://github.com/jax-ml/jax/blob/master/jax/_src/compilation_cache.py
Apache-2.0
def is_executable_in_cache(backend, cache_key: str) -> bool: """Checks if the executable is in the cache.""" cache = _get_cache(backend) if cache is None: return False # TODO(patrios): add check cache key method to cache interface. executable_and_time = cache.get(cache_key) return executable_and_time i...
Checks if the executable is in the cache.
is_executable_in_cache
python
jax-ml/jax
jax/_src/compilation_cache.py
https://github.com/jax-ml/jax/blob/master/jax/_src/compilation_cache.py
Apache-2.0
def get_executable_and_time( cache_key: str, compile_options, backend, executable_devices ) -> tuple[xla_client.LoadedExecutable | None, int | None]: """Returns the cached executable and its compilation time if present, or None otherwise. """ cache = _get_cache(backend) if cache is None: logger.debug(...
Returns the cached executable and its compilation time if present, or None otherwise.
get_executable_and_time
python
jax-ml/jax
jax/_src/compilation_cache.py
https://github.com/jax-ml/jax/blob/master/jax/_src/compilation_cache.py
Apache-2.0
def put_executable_and_time( cache_key: str, module_name: str, executable: xla_client.LoadedExecutable, backend, compile_time: int ) -> None: """Adds the 'executable' and its compilation time to the cache, possibly evicting older entries. """ log_priority = (logging.WARNING ...
Adds the 'executable' and its compilation time to the cache, possibly evicting older entries.
put_executable_and_time
python
jax-ml/jax
jax/_src/compilation_cache.py
https://github.com/jax-ml/jax/blob/master/jax/_src/compilation_cache.py
Apache-2.0
def is_initialized() -> bool: """ Deprecated. Return whether the cache is enabled. Initialization can be deferred, so initialized status is not checked. The name is retained for backwards compatibility. """ warnings.warn("is_initialized is deprecated; do not use", DeprecationWarning, stac...
Deprecated. Return whether the cache is enabled. Initialization can be deferred, so initialized status is not checked. The name is retained for backwards compatibility.
is_initialized
python
jax-ml/jax
jax/_src/compilation_cache.py
https://github.com/jax-ml/jax/blob/master/jax/_src/compilation_cache.py
Apache-2.0
def reset_cache() -> None: """Get back to pristine, uninitialized state.""" global _cache global _cache_initialized global _cache_checked global _cache_used logger.info("Resetting cache at %s.", _cache._path if _cache is not None else "<empty>") _cache = None with _cache_initialized_mutex...
Get back to pristine, uninitialized state.
reset_cache
python
jax-ml/jax
jax/_src/compilation_cache.py
https://github.com/jax-ml/jax/blob/master/jax/_src/compilation_cache.py
Apache-2.0
def combine_executable_and_time( serialized_executable: bytes, compile_time: int ) -> bytes: """Given the serialized executable and the compilation time, produce a cache entry in the format shown below. The cache entry is of the form: Byte: 0 1 2 3 4 ... Content: compilation time seri...
Given the serialized executable and the compilation time, produce a cache entry in the format shown below. The cache entry is of the form: Byte: 0 1 2 3 4 ... Content: compilation time serialized executable (big-endian int)
combine_executable_and_time
python
jax-ml/jax
jax/_src/compilation_cache.py
https://github.com/jax-ml/jax/blob/master/jax/_src/compilation_cache.py
Apache-2.0
def extract_executable_and_time( executable_and_time: bytes ) -> tuple[bytes, int]: """Given the cache entry in the format shown below, extract the serialized executable and the compilation time. The cache entry 'executable_and_time' is of the form: Byte: 0 1 2 3 4 ... Content: compilati...
Given the cache entry in the format shown below, extract the serialized executable and the compilation time. The cache entry 'executable_and_time' is of the form: Byte: 0 1 2 3 4 ... Content: compilation time serialized executable (big-endian int)
extract_executable_and_time
python
jax-ml/jax
jax/_src/compilation_cache.py
https://github.com/jax-ml/jax/blob/master/jax/_src/compilation_cache.py
Apache-2.0
def use_detailed_logging(module: ir.Module) -> bool: """Returns 'true' if detailed logging should be enabled for 'module'.""" bound = _COMPILER_DETAILED_LOGGING_MIN_OPS.value return _walk_operations(module.operation, bound) < 0
Returns 'true' if detailed logging should be enabled for 'module'.
use_detailed_logging
python
jax-ml/jax
jax/_src/compiler.py
https://github.com/jax-ml/jax/blob/master/jax/_src/compiler.py
Apache-2.0
def get_compile_options( num_replicas: int, num_partitions: int, device_assignment=None, use_spmd_partitioning: bool = True, use_shardy_partitioner: bool = False, use_auto_spmd_partitioning: bool = False, auto_spmd_partitioning_mesh_shape: list[int] | None = None, auto_spmd_partitioning_...
Returns the compile options to use, as derived from flag values. Args: num_replicas: Number of replicas for which to compile. num_partitions: Number of partitions for which to compile. device_assignment: Optional ndarray of jax devices indicating the assignment of logical replicas to physical devic...
get_compile_options
python
jax-ml/jax
jax/_src/compiler.py
https://github.com/jax-ml/jax/blob/master/jax/_src/compiler.py
Apache-2.0
def register_xla_runtime_error_handler( handler_fn: Callable[[xc.XlaRuntimeError], Exception | None], ): """Registers a custom exception handler for XLA runtime errors. Registering a custom handler allows re-raising a more informative exception after encountering an XLARuntimeError. Args: handler_fn: ...
Registers a custom exception handler for XLA runtime errors. Registering a custom handler allows re-raising a more informative exception after encountering an XLARuntimeError. Args: handler_fn: A function which returns a new exception to replace the original XLA runtime error, or None if the original ...
register_xla_runtime_error_handler
python
jax-ml/jax
jax/_src/compiler.py
https://github.com/jax-ml/jax/blob/master/jax/_src/compiler.py
Apache-2.0
def _is_executable_in_cache(backend, cache_key) -> bool: """Checks if executable is presented in cache on a given key """ try: return compilation_cache.is_executable_in_cache(backend, cache_key) except Exception as ex: if config.raise_persistent_cache_errors.value: raise warnings.warn( ...
Checks if executable is presented in cache on a given key
_is_executable_in_cache
python
jax-ml/jax
jax/_src/compiler.py
https://github.com/jax-ml/jax/blob/master/jax/_src/compiler.py
Apache-2.0
def _cache_read( module_name: str, cache_key: str, compile_options: xc.CompileOptions, backend: xc.Client, executable_devices: xc.DeviceList, ) -> tuple[xc.LoadedExecutable | None, int | None]: """Looks up the `computation` and it's compilation time in the persistent compilation cache repository. """ tr...
Looks up the `computation` and it's compilation time in the persistent compilation cache repository.
_cache_read
python
jax-ml/jax
jax/_src/compiler.py
https://github.com/jax-ml/jax/blob/master/jax/_src/compiler.py
Apache-2.0
def _cache_write(cache_key: str, compile_time_secs: float, module_name: str, backend: xc.Client, executable: xc.LoadedExecutable, host_callbacks: Sequence[Any]) -> None: """Writes the `serialized_computation` and its compilation time to the persist...
Writes the `serialized_computation` and its compilation time to the persistent compilation cache repository.
_cache_write
python
jax-ml/jax
jax/_src/compiler.py
https://github.com/jax-ml/jax/blob/master/jax/_src/compiler.py
Apache-2.0
def config_with_absl(self): """Registers absl flags for the JAX configs. E.g., for each JAX config defined using bool_state(), this method registers an absl boolean flag, with the same name. This is the recommended method to call if you use `app.run(main)` and you need JAX flags. Examples: ...
Registers absl flags for the JAX configs. E.g., for each JAX config defined using bool_state(), this method registers an absl boolean flag, with the same name. This is the recommended method to call if you use `app.run(main)` and you need JAX flags. Examples: ```python from absl import a...
config_with_absl
python
jax-ml/jax
jax/_src/config.py
https://github.com/jax-ml/jax/blob/master/jax/_src/config.py
Apache-2.0
def trace_context(): """Returns a tuple of configuration values that affect tracing. These values are included in the cache key for linear_util.cache. Values included in this set should also most likely be included in the C++ JIT state, which is handled separately. """ return (axis_env_state.value, mesh_c...
Returns a tuple of configuration values that affect tracing. These values are included in the cache key for linear_util.cache. Values included in this set should also most likely be included in the C++ JIT state, which is handled separately.
trace_context
python
jax-ml/jax
jax/_src/config.py
https://github.com/jax-ml/jax/blob/master/jax/_src/config.py
Apache-2.0
def _add_hooks(self, update_global_hook, update_thread_local_hook): """Private method that adds hooks to an existing context-manager. Used to avoid cyclic import dependencies.""" self._update_thread_local_hook = update_thread_local_hook self._update_global_hook = update_global_hook update_global_ho...
Private method that adds hooks to an existing context-manager. Used to avoid cyclic import dependencies.
_add_hooks
python
jax-ml/jax
jax/_src/config.py
https://github.com/jax-ml/jax/blob/master/jax/_src/config.py
Apache-2.0
def bool_state( name: str, default: bool, help: str, *, update_global_hook: Callable[[bool], None] | None = None, update_thread_local_hook: Callable[[bool | None], None] | None = None, upgrade: bool = False, extra_description: str = '', include_in_jit_key: bool = False, ) -> State[bo...
Set up thread-local state and return a contextmanager for managing it. This function is a convenience wrapper. It defines a flag, environment variable, and corresponding thread-local state, which can be managed via the contextmanager it returns. The thread-local state value can be read via the ``config.<optio...
bool_state
python
jax-ml/jax
jax/_src/config.py
https://github.com/jax-ml/jax/blob/master/jax/_src/config.py
Apache-2.0
def enum_state( name: str, enum_values: Sequence[str], default: str, help: str, *, update_global_hook: Callable[[str], None] | None = None, update_thread_local_hook: Callable[[str | None], None] | None = None, include_in_jit_key: bool = False, ) -> State[str]: """Set up thread-local st...
Set up thread-local state and return a contextmanager for managing it. See docstring for ``bool_state``. Args: name: string, converted to lowercase to define the name of the config option (and absl flag). It is converted to uppercase to define the corresponding shell environment variable. enum...
enum_state
python
jax-ml/jax
jax/_src/config.py
https://github.com/jax-ml/jax/blob/master/jax/_src/config.py
Apache-2.0