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 optional_enum_state( name: str, enum_values: Sequence[str], default: str | None, help: str, *, update_global_hook: Callable[[str | None], None] | None = None, update_thread_local_hook: Callable[[str | None], None] | None = None, include_in_jit_key: bool = False, ) -> State[str | None...
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...
optional_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
def int_state( name: str, default: int, help: str, *, update_global_hook: Callable[[int], None] | None = None, update_thread_local_hook: Callable[[int | None], None] | None = None, include_in_jit_key: bool = False, validator: Callable[[Any], None] | None = None, ) -> State[int]: """Set...
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. defa...
int_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 float_state( name: str, default: float, help: str, *, update_global_hook: Callable[[float], None] | None = None, update_thread_local_hook: Callable[[float | None], None] | None = None, ) -> State[float]: """Set up thread-local state and return a contextmanager for managing it. See docst...
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. defa...
float_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 string_state( name: str, default: str, help: str, *, update_global_hook: Callable[[str], None] | None = None, update_thread_local_hook: Callable[[str | None], None] | None = None, ) -> State[str]: """Set up thread-local state and return a contextmanager for managing it. See docstring fo...
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. defa...
string_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 optional_string_state( name: str, default: str | None, help: str, *, update_global_hook: Callable[[str], None] | None = None, update_thread_local_hook: Callable[[str | None], None] | None = None, ) -> State[str | None]: """Set up thread-local state and return a contextmanager for managing ...
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. defa...
optional_string_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 string_or_object_state( name: str, default: Any, help: str, *, update_global_hook: Callable[[Any], None] | None = None, update_thread_local_hook: Callable[[Any], None] | None = None, validator: Callable[[Any], None] | None = None, ) -> State[Any]: """Set up thread-local state and retur...
Set up thread-local state and return a contextmanager for managing it. Similar to ``string_state``, except the context manager will accept any object, not just a string. Any value passed via command line flag or environment variable will be treated as a string. Args: name: string, converted to lowercase t...
string_or_object_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 explicit_device_put_scope() -> Iterator[None]: """Indicates that the current context is an explicit device_put*() call.""" state = guard_lib.thread_local_state() prev = state.explicit_device_put state.explicit_device_put = True try: yield finally: state.explicit_device_put = prev
Indicates that the current context is an explicit device_put*() call.
explicit_device_put_scope
python
jax-ml/jax
jax/_src/config.py
https://github.com/jax-ml/jax/blob/master/jax/_src/config.py
Apache-2.0
def explicit_device_get_scope() -> Iterator[None]: """Indicates that the current context is an explicit device_get() call.""" state = guard_lib.thread_local_state() prev = state.explicit_device_get state.explicit_device_get = True try: yield finally: state.explicit_device_get = prev
Indicates that the current context is an explicit device_get() call.
explicit_device_get_scope
python
jax-ml/jax
jax/_src/config.py
https://github.com/jax-ml/jax/blob/master/jax/_src/config.py
Apache-2.0
def _update_transfer_guard(state, key, val): """Applies the transfer guard level within guard_lib.""" if val is None: setattr(state, key, None) elif val == 'allow': setattr(state, key, guard_lib.TransferGuardLevel.ALLOW) elif val == 'log': setattr(state, key, guard_lib.TransferGuardLevel.LOG) elif...
Applies the transfer guard level within guard_lib.
_update_transfer_guard
python
jax-ml/jax
jax/_src/config.py
https://github.com/jax-ml/jax/blob/master/jax/_src/config.py
Apache-2.0
def transfer_guard(new_val: str) -> Iterator[None]: """A contextmanager to control the transfer guard level for all transfers. For more information, see https://docs.jax.dev/en/latest/transfer_guard.html Args: new_val: The new thread-local transfer guard level for all transfers. Yields: None. """...
A contextmanager to control the transfer guard level for all transfers. For more information, see https://docs.jax.dev/en/latest/transfer_guard.html Args: new_val: The new thread-local transfer guard level for all transfers. Yields: None.
transfer_guard
python
jax-ml/jax
jax/_src/config.py
https://github.com/jax-ml/jax/blob/master/jax/_src/config.py
Apache-2.0
def __init__(self, constvars: Sequence[Var], invars: Sequence[Var], outvars: Sequence[Atom], eqns: Sequence[JaxprEqn], effects: Effects = no_effects, # We want all calls to pass a DebugInfo object, but for backwards # compatibility we have to allow calls when ...
Args: constvars: list of variables introduced for constants. Array constants are replaced with such variables while scalar constants are kept inline. invars: list of input variables. Together, `constvars` and `invars` are the inputs to the Jaxpr. outvars: list of output atoms. ...
__init__
python
jax-ml/jax
jax/_src/core.py
https://github.com/jax-ml/jax/blob/master/jax/_src/core.py
Apache-2.0
def subjaxprs(jaxpr: Jaxpr) -> Iterator[Jaxpr]: """Generator for all subjaxprs found in the params of jaxpr.eqns. Does not descend recursively into the found subjaxprs. """ for eqn in jaxpr.eqns: yield from jaxprs_in_params(eqn.params)
Generator for all subjaxprs found in the params of jaxpr.eqns. Does not descend recursively into the found subjaxprs.
subjaxprs
python
jax-ml/jax
jax/_src/core.py
https://github.com/jax-ml/jax/blob/master/jax/_src/core.py
Apache-2.0
def traverse_jaxpr_params(f, params): """Applies f to each jaxpr parameter and returns a tuple of returned values.""" return {name: f(p) for name, param in params.items() for p in (param if isinstance(param, (tuple, list)) else [param]) if type(p) in (Jaxpr, ClosedJaxpr)}
Applies f to each jaxpr parameter and returns a tuple of returned values.
traverse_jaxpr_params
python
jax-ml/jax
jax/_src/core.py
https://github.com/jax-ml/jax/blob/master/jax/_src/core.py
Apache-2.0
def reset_trace_state() -> bool: """Resets the global trace state and returns True if it was already clean.""" if not trace_ctx.is_top_level(): trace_ctx.reset() trace_ctx.update_thread_local_jit_state() return False else: return True
Resets the global trace state and returns True if it was already clean.
reset_trace_state
python
jax-ml/jax
jax/_src/core.py
https://github.com/jax-ml/jax/blob/master/jax/_src/core.py
Apache-2.0
def maybe_find_leaked_tracers(trace: Trace) -> list[Tracer]: """Find the leaked tracers holding a reference to the Trace """ if not getattr(threading.current_thread(), 'pydev_do_not_trace', True): warnings.warn(TRACER_LEAK_DEBUGGER_WARNING) # Trigger garbage collection to filter out unreachable objects that...
Find the leaked tracers holding a reference to the Trace
maybe_find_leaked_tracers
python
jax-ml/jax
jax/_src/core.py
https://github.com/jax-ml/jax/blob/master/jax/_src/core.py
Apache-2.0
def concrete_or_error(force: Any, val: Any, context=""): """Like force(val), but gives the context in the error message.""" if force is None: force = lambda x: x if isinstance(val, Tracer): maybe_concrete = val.to_concrete_value() if maybe_concrete is None: raise ConcretizationTypeError(val, con...
Like force(val), but gives the context in the error message.
concrete_or_error
python
jax-ml/jax
jax/_src/core.py
https://github.com/jax-ml/jax/blob/master/jax/_src/core.py
Apache-2.0
def concrete_dim_or_error(val: Any, context=""): """Like concrete_or_error(operator.index), allowing symbolic dimensions.""" if is_symbolic_dim(val): return val else: return concrete_or_error(operator.index, val, context=context)
Like concrete_or_error(operator.index), allowing symbolic dimensions.
concrete_dim_or_error
python
jax-ml/jax
jax/_src/core.py
https://github.com/jax-ml/jax/blob/master/jax/_src/core.py
Apache-2.0
def canonicalize_shape(shape: Shape, context: str="") -> tuple[Any, ...]: """Canonicalizes and checks for errors in a user-provided shape value. Args: shape: a Python value that represents a shape. Returns: A tuple of canonical dimension values. """ if isinstance(shape, int): shape = shape, tr...
Canonicalizes and checks for errors in a user-provided shape value. Args: shape: a Python value that represents a shape. Returns: A tuple of canonical dimension values.
canonicalize_shape
python
jax-ml/jax
jax/_src/core.py
https://github.com/jax-ml/jax/blob/master/jax/_src/core.py
Apache-2.0
def get_sharding(sharding, shape): """Modifies and checks the sharding. Some modifications/checks include: * Making the length of specs the same as ndim * If a mesh axis is mentioned in pspec is Auto/Manual, replace it with None * Checking for len(spec)-ndim match * Checking if the mesh is an Abstr...
Modifies and checks the sharding. Some modifications/checks include: * Making the length of specs the same as ndim * If a mesh axis is mentioned in pspec is Auto/Manual, replace it with None * Checking for len(spec)-ndim match * Checking if the mesh is an AbstractMesh.
get_sharding
python
jax-ml/jax
jax/_src/core.py
https://github.com/jax-ml/jax/blob/master/jax/_src/core.py
Apache-2.0
def definitely_equal_shape(s1: Shape, s2: Shape) -> bool: """Check that two shapes are guaranteed to be element-wise equal. In presence of dynamic shapes may return False even when the shapes may be equal at runtime. """ return (len(s1) == len(s2) and all(unsafe_map(definitely_equal, s1, s2)))
Check that two shapes are guaranteed to be element-wise equal. In presence of dynamic shapes may return False even when the shapes may be equal at runtime.
definitely_equal_shape
python
jax-ml/jax
jax/_src/core.py
https://github.com/jax-ml/jax/blob/master/jax/_src/core.py
Apache-2.0
def divide_shape_sizes(s1: Shape, s2: Shape) -> DimSize: """Returns an integer "i" s.t., i * size(s2) == size(s1). Raises InconclusiveDimensionOperation if there is no such integer.""" sz1 = math.prod(s1) sz2 = math.prod(s2) if definitely_equal(sz1, sz2): # Takes care of sz1 and sz2 being 0 return 1 q,...
Returns an integer "i" s.t., i * size(s2) == size(s1). Raises InconclusiveDimensionOperation if there is no such integer.
divide_shape_sizes
python
jax-ml/jax
jax/_src/core.py
https://github.com/jax-ml/jax/blob/master/jax/_src/core.py
Apache-2.0
def stride_dim(d: DimSize, window_size: DimSize, window_stride: DimSize) -> DimSize: """max(0, (d - window_size) // window_stride + 1) If d < window_size, returns 0. We assume window_size >= 1 and window_stride >= 1. """ # If d < window_size then (d - window_size) // window_stride < 0 return max_dim((d - w...
max(0, (d - window_size) // window_stride + 1) If d < window_size, returns 0. We assume window_size >= 1 and window_stride >= 1.
stride_dim
python
jax-ml/jax
jax/_src/core.py
https://github.com/jax-ml/jax/blob/master/jax/_src/core.py
Apache-2.0
def min_dim(d1: DimSize, d2: DimSize) -> DimSize: """Like min(d1, d2) but for both constant and symbolic dimensions.""" d1_is_constant = is_constant_dim(d1) if d1_is_constant and is_constant_dim(d2): return min(d1, d2) d1 = concrete_dim_or_error(d1, "argument `d1` of `core.min_dim`") d2 = concrete_dim_or_...
Like min(d1, d2) but for both constant and symbolic dimensions.
min_dim
python
jax-ml/jax
jax/_src/core.py
https://github.com/jax-ml/jax/blob/master/jax/_src/core.py
Apache-2.0
def max_dim(d1: DimSize, d2: DimSize) -> DimSize: """Like max(d1, d2) but for both constant and symbolic dimensions.""" d1_is_constant = is_constant_dim(d1) if d1_is_constant and is_constant_dim(d2): return max(d1, d2) d1 = concrete_dim_or_error(d1, "argument `d1` of `core.max_dim`") d2 = concrete_dim_o...
Like max(d1, d2) but for both constant and symbolic dimensions.
max_dim
python
jax-ml/jax
jax/_src/core.py
https://github.com/jax-ml/jax/blob/master/jax/_src/core.py
Apache-2.0
def dimension_as_value(d: DimSize): """Turns a dimension size into a JAX array. This is the identity function for constant dimensions. Has the same abstract value as Python constants. """ if isinstance(d, (int, Tracer, np.int32, np.int64)): return d # For shape_poly._DimPolynomial if hasattr(d, ...
Turns a dimension size into a JAX array. This is the identity function for constant dimensions. Has the same abstract value as Python constants.
dimension_as_value
python
jax-ml/jax
jax/_src/core.py
https://github.com/jax-ml/jax/blob/master/jax/_src/core.py
Apache-2.0
def canonicalize_slice( s: slice, axis_size: DimSize ) -> tuple[DimSize, DimSize, DimSize]: """Computes the start index, step, and size of the slice `x[s]`. This is similar to `s.indices(axis_size)`, except that it returns `(start, step, size)`, and it works when the slice and/or the `axis_size` are ...
Computes the start index, step, and size of the slice `x[s]`. This is similar to `s.indices(axis_size)`, except that it returns `(start, step, size)`, and it works when the slice and/or the `axis_size` are symbolic. See https://numpy.org/doc/stable/user/basics.indexing.html#slicing-and-striding
canonicalize_slice
python
jax-ml/jax
jax/_src/core.py
https://github.com/jax-ml/jax/blob/master/jax/_src/core.py
Apache-2.0
def evaluate_shape(shape: Shape, dim_vars: Sequence[str], *dim_values: Array) -> Sequence[Array]: """Evaluates a shape possibly containing non-constants. Args: shape: the shape to evaluate. dim_vars: the dimension variables names that may appear in `shape`. dim_values: the dimension ...
Evaluates a shape possibly containing non-constants. Args: shape: the shape to evaluate. dim_vars: the dimension variables names that may appear in `shape`. dim_values: the dimension values corresponding to `dim_vars`. Returns: a tuple of JAX values corresponding to `shape`, of type `dim_val...
evaluate_shape
python
jax-ml/jax
jax/_src/core.py
https://github.com/jax-ml/jax/blob/master/jax/_src/core.py
Apache-2.0
def typecompat(aval_ref: AbstractValue, aval: AbstractValue) -> bool: """Determine whether `aval` conforms to `aval_ref`. Ignores weak_type.""" try: return typematch(aval_ref, aval) except TypeError: return False
Determine whether `aval` conforms to `aval_ref`. Ignores weak_type.
typecompat
python
jax-ml/jax
jax/_src/core.py
https://github.com/jax-ml/jax/blob/master/jax/_src/core.py
Apache-2.0
def typematch(t1: AbstractValue, t2: AbstractValue) -> bool: """Determine whether `t1` and `t2` are equivalent. Ignores weak_type.""" t1 = t1.normalize() t2 = t2.normalize() if t1 == t2: return True elif (isinstance(t1, (ShapedArray, DShapedArray)) and isinstance(t2, (ShapedArray, DShapedArray))):...
Determine whether `t1` and `t2` are equivalent. Ignores weak_type.
typematch
python
jax-ml/jax
jax/_src/core.py
https://github.com/jax-ml/jax/blob/master/jax/_src/core.py
Apache-2.0
def check_jaxpr(jaxpr: Jaxpr): """Checks well-formedness of a jaxpr. Specifically, check that: - variables that are read are bound beforehand - variables are typed equally throughout a jaxpr - variable type annotations are compatible with their binding expression Raises `JaxprTypeError` if `jaxpr` is dete...
Checks well-formedness of a jaxpr. Specifically, check that: - variables that are read are bound beforehand - variables are typed equally throughout a jaxpr - variable type annotations are compatible with their binding expression Raises `JaxprTypeError` if `jaxpr` is determined invalid. Returns `None` oth...
check_jaxpr
python
jax-ml/jax
jax/_src/core.py
https://github.com/jax-ml/jax/blob/master/jax/_src/core.py
Apache-2.0
def suggest_same_var_names(self, for_vars: Sequence[Atom], like_vars: Sequence[Atom]) -> None: """Suggests the names for `for_vars` to match those of `like_vars`. `for_vars` are distinct Vars, and are aliased with `like_vars`. """ used_like_vars...
Suggests the names for `for_vars` to match those of `like_vars`. `for_vars` are distinct Vars, and are aliased with `like_vars`.
suggest_same_var_names
python
jax-ml/jax
jax/_src/core.py
https://github.com/jax-ml/jax/blob/master/jax/_src/core.py
Apache-2.0
def str_eqn_compact(primitive: Primitive, params: dict[Any, Any]) -> str: "Compact equation to string conversion used in HLO metadata." if primitive in custom_str_eqn_compact_rules: return custom_str_eqn_compact_rules[primitive](primitive, params) primitive_name = primitive.name kvs = " ".join(f"{k}={v}" fo...
Compact equation to string conversion used in HLO metadata.
str_eqn_compact
python
jax-ml/jax
jax/_src/core.py
https://github.com/jax-ml/jax/blob/master/jax/_src/core.py
Apache-2.0
def last_used(jaxpr: Jaxpr) -> dict[Var, JaxprEqn | None]: """Returns a mapping from every var in jaxpr to what equation uses it last.""" last_used: dict[Var, JaxprEqn | None] = { v: None for v in jaxpr.outvars if not isinstance(v, Literal)} for eqn in reversed(jaxpr.eqns): for v in eqn.invars: if...
Returns a mapping from every var in jaxpr to what equation uses it last.
last_used
python
jax-ml/jax
jax/_src/core.py
https://github.com/jax-ml/jax/blob/master/jax/_src/core.py
Apache-2.0
def clean_up_dead_vars(eqn: JaxprEqn, env: dict[Var, Any], last_used: dict[Var, JaxprEqn | None]): """Remove all eqn.invars from env if eqn is the last time they were used.""" for v in {v for v in eqn.invars if not isinstance(v, Literal)}: if last_used[v] is eqn: # Delete ref to var...
Remove all eqn.invars from env if eqn is the last time they were used.
clean_up_dead_vars
python
jax-ml/jax
jax/_src/core.py
https://github.com/jax-ml/jax/blob/master/jax/_src/core.py
Apache-2.0
def def_vmap( self, vmap_rule: Callable[..., tuple[Any, Any]], ) -> Callable[..., tuple[Any, Any]]: """Define the vmap rule for this custom_vmap function. Args: vmap_rule: A function that implements the vmap rule. This function should accept the following arguments: (1) an integer `...
Define the vmap rule for this custom_vmap function. Args: vmap_rule: A function that implements the vmap rule. This function should accept the following arguments: (1) an integer ``axis_size`` as its first argument, (2) a pytree of booleans with the same structure as the inputs to the...
def_vmap
python
jax-ml/jax
jax/_src/custom_batching.py
https://github.com/jax-ml/jax/blob/master/jax/_src/custom_batching.py
Apache-2.0
def sequential_vmap(f): """A special case of ``custom_vmap`` that uses a loop. A function decorated with ``sequential_vmap`` will be called sequentially within a loop when batched. This is useful for functions that don't natively support batch dimensions. For example: >>> @jax.custom_batching.sequentia...
A special case of ``custom_vmap`` that uses a loop. A function decorated with ``sequential_vmap`` will be called sequentially within a loop when batched. This is useful for functions that don't natively support batch dimensions. For example: >>> @jax.custom_batching.sequential_vmap ... def f(x): ...
sequential_vmap
python
jax-ml/jax
jax/_src/custom_batching.py
https://github.com/jax-ml/jax/blob/master/jax/_src/custom_batching.py
Apache-2.0
def def_dce( self, dce_rule: Callable[..., Any], ) -> Callable[..., Any]: """Define a custom DCE rule for this function. Args: dce_rule: A function that takes (a) any arguments indicated as static using ``static_argnums``, (b) a Pytree of ``bool`` values (``used_outs``) indi...
Define a custom DCE rule for this function. Args: dce_rule: A function that takes (a) any arguments indicated as static using ``static_argnums``, (b) a Pytree of ``bool`` values (``used_outs``) indicating which outputs should be computed, and (c) the rest of the (non-static) arguments...
def_dce
python
jax-ml/jax
jax/_src/custom_dce.py
https://github.com/jax-ml/jax/blob/master/jax/_src/custom_dce.py
Apache-2.0
def defjvp(self, jvp: Callable[..., tuple[ReturnValue, ReturnValue]], symbolic_zeros: bool = False, ) -> Callable[..., tuple[ReturnValue, ReturnValue]]: """Define a custom JVP rule for the function represented by this instance. Args: jvp: a Python callable represent...
Define a custom JVP rule for the function represented by this instance. Args: jvp: a Python callable representing the custom JVP rule. When there are no ``nondiff_argnums``, the ``jvp`` function should accept two arguments, where the first is a tuple of primal inputs and the second is a tuple...
defjvp
python
jax-ml/jax
jax/_src/custom_derivatives.py
https://github.com/jax-ml/jax/blob/master/jax/_src/custom_derivatives.py
Apache-2.0
def defjvps(self, *jvps: Callable[..., ReturnValue] | None) -> None: """Convenience wrapper for defining JVPs for each argument separately. This convenience wrapper cannot be used together with ``nondiff_argnums``. Args: *jvps: a sequence of functions, one for each positional argument of the ...
Convenience wrapper for defining JVPs for each argument separately. This convenience wrapper cannot be used together with ``nondiff_argnums``. Args: *jvps: a sequence of functions, one for each positional argument of the :class:`~jax.custom_jvp` function. Each function takes as arguments ...
defjvps
python
jax-ml/jax
jax/_src/custom_derivatives.py
https://github.com/jax-ml/jax/blob/master/jax/_src/custom_derivatives.py
Apache-2.0
def defvjp(self, fwd: Callable[..., tuple[ReturnValue, Any]], bwd: Callable[..., tuple[Any, ...]], symbolic_zeros: bool = False, optimize_remat: bool = False, ) -> None: """Define a custom VJP rule for the function represented by this instance. A...
Define a custom VJP rule for the function represented by this instance. Args: fwd: a Python callable representing the forward pass of the custom VJP rule. When there are no ``nondiff_argnums``, the ``fwd`` function has the same input signature as the underlying primal function. It should ...
defvjp
python
jax-ml/jax
jax/_src/custom_derivatives.py
https://github.com/jax-ml/jax/blob/master/jax/_src/custom_derivatives.py
Apache-2.0
def custom_vjp_primal_tree_values(tree): """Strips away perturbation information from forward rule arguments. This is a helper function for user with the ``symbolic_zeros`` option to the ``defvjp`` method of a ``custom_vjp``-decorated function. In ``symbolic_zeros`` mode, the custom forward rule receives argu...
Strips away perturbation information from forward rule arguments. This is a helper function for user with the ``symbolic_zeros`` option to the ``defvjp`` method of a ``custom_vjp``-decorated function. In ``symbolic_zeros`` mode, the custom forward rule receives arguments whose pytree leaves are records with a...
custom_vjp_primal_tree_values
python
jax-ml/jax
jax/_src/custom_derivatives.py
https://github.com/jax-ml/jax/blob/master/jax/_src/custom_derivatives.py
Apache-2.0
def custom_gradient(fun): """Convenience function for defining custom VJP rules (aka custom gradients). While the canonical way to define custom VJP rules is via ``jax.custom_vjp``, the ``custom_gradient`` convenience wrapper follows TensorFlow's ``tf.custom_gradient`` API. The difference here is that ``custom...
Convenience function for defining custom VJP rules (aka custom gradients). While the canonical way to define custom VJP rules is via ``jax.custom_vjp``, the ``custom_gradient`` convenience wrapper follows TensorFlow's ``tf.custom_gradient`` API. The difference here is that ``custom_gradient`` can be used as a ...
custom_gradient
python
jax-ml/jax
jax/_src/custom_derivatives.py
https://github.com/jax-ml/jax/blob/master/jax/_src/custom_derivatives.py
Apache-2.0
def closure_convert(fun: Callable, *example_args) -> tuple[Callable, list[Any]]: """Closure conversion utility, for use with higher-order custom derivatives. To define custom derivatives such as with ``jax.custom_vjp(f)``, the target function ``f`` must take, as formal arguments, all values involved in differe...
Closure conversion utility, for use with higher-order custom derivatives. To define custom derivatives such as with ``jax.custom_vjp(f)``, the target function ``f`` must take, as formal arguments, all values involved in differentiation. If ``f`` is a higher-order function, in that it accepts as an argument a P...
closure_convert
python
jax-ml/jax
jax/_src/custom_derivatives.py
https://github.com/jax-ml/jax/blob/master/jax/_src/custom_derivatives.py
Apache-2.0
def unreachable(*args, out_avals=None, exc_type=TypeError, message='unreachable'): """Fail when evaluated concretely (but allow for staging). This function allows one to assert an impossibility of evaluation. It can be used to guarantee that evaluation does not "reach" a certain point in the se...
Fail when evaluated concretely (but allow for staging). This function allows one to assert an impossibility of evaluation. It can be used to guarantee that evaluation does not "reach" a certain point in the sense that it does not execute, but it can nonetheless be staged out by JAX without error. Args: ...
unreachable
python
jax-ml/jax
jax/_src/custom_derivatives.py
https://github.com/jax-ml/jax/blob/master/jax/_src/custom_derivatives.py
Apache-2.0
def _check_factor(factor:str): """Validates a factor. A factor is a string starting with a letter and containing only letters, digits, or underscores. """ if not factor[0].isalpha(): raise ValueError(f"Factor names have to start with a letter, but got '{factor[0]}'") for char in factor[1:]: if char...
Validates a factor. A factor is a string starting with a letter and containing only letters, digits, or underscores.
_check_factor
python
jax-ml/jax
jax/_src/custom_partitioning_sharding_rule.py
https://github.com/jax-ml/jax/blob/master/jax/_src/custom_partitioning_sharding_rule.py
Apache-2.0
def _is_batching(factor: str) -> bool: """Checks if a factor is a representation for leading batching dimensions. Leading batching dimensions is represented by a factor containing ... and optionally followed by a digit, and ... is equivalent to ...0. """ if len(factor) < 1 or factor[0] != BATCHING: re...
Checks if a factor is a representation for leading batching dimensions. Leading batching dimensions is represented by a factor containing ... and optionally followed by a digit, and ... is equivalent to ...0.
_is_batching
python
jax-ml/jax
jax/_src/custom_partitioning_sharding_rule.py
https://github.com/jax-ml/jax/blob/master/jax/_src/custom_partitioning_sharding_rule.py
Apache-2.0
def _parse_values( rule: str, ) -> tuple[ArrayMapping, ...]: """Parses the LHS or RHS of an Einsum notation like string. Converts each operand or result in the Einsum notation like string to a tuple of ArrayMapping. This very closely follows how einops parses their rules in einops/parsing.py. Args: ...
Parses the LHS or RHS of an Einsum notation like string. Converts each operand or result in the Einsum notation like string to a tuple of ArrayMapping. This very closely follows how einops parses their rules in einops/parsing.py. Args: rule: The Einsum notation for the operands or results of an operation....
_parse_values
python
jax-ml/jax
jax/_src/custom_partitioning_sharding_rule.py
https://github.com/jax-ml/jax/blob/master/jax/_src/custom_partitioning_sharding_rule.py
Apache-2.0
def str_to_sdy_sharding_rule(rule: str, **factor_sizes) -> SdyShardingRule: """Constructs a SdyShardingRule object from the Einsum notation like string. This is done by verifying that the input Einsum notation like string and with optional factor sizes represents a valid sharding rule and converting it to an i...
Constructs a SdyShardingRule object from the Einsum notation like string. This is done by verifying that the input Einsum notation like string and with optional factor sizes represents a valid sharding rule and converting it to an internal representation. Args: rule: The Einsum notation like string for an...
str_to_sdy_sharding_rule
python
jax-ml/jax
jax/_src/custom_partitioning_sharding_rule.py
https://github.com/jax-ml/jax/blob/master/jax/_src/custom_partitioning_sharding_rule.py
Apache-2.0
def sdy_sharding_rule_to_mlir( rule: SdyShardingRule, operand_types: list[IrTypes], result_types: list[IrTypes],) -> ir.Attribute: """Builds the MLIR representation for the sharding rule. This is done by verifying that the rule is consistent with the types of the operation and converting the Einsum notatio...
Builds the MLIR representation for the sharding rule. This is done by verifying that the rule is consistent with the types of the operation and converting the Einsum notation like string to OpShardingRuleAttr.
sdy_sharding_rule_to_mlir
python
jax-ml/jax
jax/_src/custom_partitioning_sharding_rule.py
https://github.com/jax-ml/jax/blob/master/jax/_src/custom_partitioning_sharding_rule.py
Apache-2.0
def add_factor(factor, size): """Adds a factor to factors_to_indices_sizes. `size` may be a dimensions size, a user specified factor size, or UNKNOWN if a factor is first used as in a compound factor and then used for a whole dimension. """ factor_index, factor_size = factors_to_indices_sizes.g...
Adds a factor to factors_to_indices_sizes. `size` may be a dimensions size, a user specified factor size, or UNKNOWN if a factor is first used as in a compound factor and then used for a whole dimension.
add_factor
python
jax-ml/jax
jax/_src/custom_partitioning_sharding_rule.py
https://github.com/jax-ml/jax/blob/master/jax/_src/custom_partitioning_sharding_rule.py
Apache-2.0
def debug_callback_batching_rule(args, dims, **params): """Unrolls the debug callback across the mapped axis.""" axis_size = next(x.shape[i] for x, i in zip(args, dims) if i is not None) # TODO(sharadmv): implement in terms of rolled loop unstead of # unrolled. def get_arg_at_dim(i, dim, ar...
Unrolls the debug callback across the mapped axis.
debug_callback_batching_rule
python
jax-ml/jax
jax/_src/debugging.py
https://github.com/jax-ml/jax/blob/master/jax/_src/debugging.py
Apache-2.0
def debug_print( fmt: str, *args, ordered: bool = False, partitioned: bool = False, **kwargs ) -> None: """Prints values and works in staged out JAX functions. This function does *not* work with f-strings because formatting is delayed. So instead of ``jax.debug.print(f"hello {bar}")``, write ``jax.debug.pr...
Prints values and works in staged out JAX functions. This function does *not* work with f-strings because formatting is delayed. So instead of ``jax.debug.print(f"hello {bar}")``, write ``jax.debug.print("hello {bar}", bar=bar)``. This function is a thin convenience wrapper around :func:`jax.debug.callback`. ...
debug_print
python
jax-ml/jax
jax/_src/debugging.py
https://github.com/jax-ml/jax/blob/master/jax/_src/debugging.py
Apache-2.0
def inspect_array_sharding(value, *, callback: Callable[[Sharding], None]): """Enables inspecting array sharding inside JIT-ted functions. This function, when provided with a Pytree of arrays, calls back with each of their shardings and works in ``pjit``-ted computations, enabling inspecting the chosen interme...
Enables inspecting array sharding inside JIT-ted functions. This function, when provided with a Pytree of arrays, calls back with each of their shardings and works in ``pjit``-ted computations, enabling inspecting the chosen intermediate shardings. The policy for when ``callback`` is called is *as early as po...
inspect_array_sharding
python
jax-ml/jax
jax/_src/debugging.py
https://github.com/jax-ml/jax/blob/master/jax/_src/debugging.py
Apache-2.0
def accelerate_getattr_deprecation(module: ModuleType, name: str) -> None: """Accelerate the deprecation of a module-level attribute. Raises an AttributeError instead of a DeprecationWarning upon attribute access. Used in Google-internal code to implement faster deprecation. """ message, _ = module._deprecat...
Accelerate the deprecation of a module-level attribute. Raises an AttributeError instead of a DeprecationWarning upon attribute access. Used in Google-internal code to implement faster deprecation.
accelerate_getattr_deprecation
python
jax-ml/jax
jax/_src/deprecations.py
https://github.com/jax-ml/jax/blob/master/jax/_src/deprecations.py
Apache-2.0
def warn(deprecation_id: str, message: str, stacklevel: int) -> None: """Warns about a deprecation, or errors if the deprecation is accelerated.""" if is_accelerated(deprecation_id): raise ValueError(message) else: warnings.warn(message, category=DeprecationWarning, stacklevel=stacklevel...
Warns about a deprecation, or errors if the deprecation is accelerated.
warn
python
jax-ml/jax
jax/_src/deprecations.py
https://github.com/jax-ml/jax/blob/master/jax/_src/deprecations.py
Apache-2.0
def _reorder_shards(x, new_s, copy_semantics: CopySemantics): """Reorders array shards to match the order indicated by the new sharding.""" xc_copy_semantics = pxla.to_xc_copy_semantics([copy_semantics])[0] return xc.reorder_shards(x, new_s, xc_copy_semantics) # type: ignore
Reorders array shards to match the order indicated by the new sharding.
_reorder_shards
python
jax-ml/jax
jax/_src/dispatch.py
https://github.com/jax-ml/jax/blob/master/jax/_src/dispatch.py
Apache-2.0
def _is_supported_cross_host_transfer(ndim, src_sharding, dst_sharding): """Returns True if src->dst is a supported cross-host transfer.""" backend = xla_bridge.get_backend() # There is experimental support for cross-host device transfers on TFRT TPU # backends only. if (xla_bridge.process_count() == 1 or bac...
Returns True if src->dst is a supported cross-host transfer.
_is_supported_cross_host_transfer
python
jax-ml/jax
jax/_src/dispatch.py
https://github.com/jax-ml/jax/blob/master/jax/_src/dispatch.py
Apache-2.0
def to_dlpack(x: Array, stream: int | Any | None = None, src_device: xla_client.Device | None = None, dl_device: tuple[DLDeviceType, int] | None = None, max_version: tuple[int, int] | None = None, copy : bool | None = None): """Returns a DLPack tensor that encap...
Returns a DLPack tensor that encapsulates a :class:`~jax.Array` ``x``. Args: x: a :class:`~jax.Array`, on either CPU or GPU. stream: optional platform-dependent stream to wait on until the buffer is ready. This corresponds to the `stream` argument to ``__dlpack__`` documented in https://dmlc.gith...
to_dlpack
python
jax-ml/jax
jax/_src/dlpack.py
https://github.com/jax-ml/jax/blob/master/jax/_src/dlpack.py
Apache-2.0
def supports_inf(dtype: DTypeLike) -> bool: """Return true if the dtype supports infinity, else return False.""" typ = np.dtype(dtype).type if typ in {float8_e4m3b11fnuz, float8_e4m3fn, float8_e4m3fnuz, float8_e5m2fnuz}: return False return issubdtype(dtype, np.inexact)
Return true if the dtype supports infinity, else return False.
supports_inf
python
jax-ml/jax
jax/_src/dtypes.py
https://github.com/jax-ml/jax/blob/master/jax/_src/dtypes.py
Apache-2.0
def jax_dtype(obj: DTypeLike | None, *, align: bool = False, copy: bool = False) -> DType: """Cast an object to a dtype, respecting JAX dtype defaults. Arguments mirror those of :func:`numpy.dtype`. """ if obj is None: obj = float_ elif issubdtype(obj, extended): return obj # type: ign...
Cast an object to a dtype, respecting JAX dtype defaults. Arguments mirror those of :func:`numpy.dtype`.
jax_dtype
python
jax-ml/jax
jax/_src/dtypes.py
https://github.com/jax-ml/jax/blob/master/jax/_src/dtypes.py
Apache-2.0
def bit_width(dtype: DTypeLike) -> int: """Number of bits per element for the dtype.""" # Note: we cannot use dtype.itemsize here because this is # incorrect for sub-byte integer types. if dtype == np.dtype(bool): return 8 # physical bit layout for boolean dtype elif issubdtype(dtype, np.integer): re...
Number of bits per element for the dtype.
bit_width
python
jax-ml/jax
jax/_src/dtypes.py
https://github.com/jax-ml/jax/blob/master/jax/_src/dtypes.py
Apache-2.0
def to_numeric_dtype(dtype: DTypeLike) -> DType: """Promotes a dtype into an numeric dtype, if it is not already one.""" dtype_ = np.dtype(dtype) return np.dtype('int32') if dtype_ == np.dtype('bool') else dtype_
Promotes a dtype into an numeric dtype, if it is not already one.
to_numeric_dtype
python
jax-ml/jax
jax/_src/dtypes.py
https://github.com/jax-ml/jax/blob/master/jax/_src/dtypes.py
Apache-2.0
def to_inexact_dtype(dtype: DTypeLike) -> DType: """Promotes a dtype into an inexact dtype, if it is not already one.""" dtype_ = np.dtype(dtype) return _dtype_to_inexact.get(dtype_, dtype_)
Promotes a dtype into an inexact dtype, if it is not already one.
to_inexact_dtype
python
jax-ml/jax
jax/_src/dtypes.py
https://github.com/jax-ml/jax/blob/master/jax/_src/dtypes.py
Apache-2.0
def to_floating_dtype(dtype: DTypeLike) -> DType: """Promotes a dtype to a non-complex floating dtype.""" dtype_ = np.dtype(dtype) return finfo(_dtype_to_inexact.get(dtype_, dtype_)).dtype
Promotes a dtype to a non-complex floating dtype.
to_floating_dtype
python
jax-ml/jax
jax/_src/dtypes.py
https://github.com/jax-ml/jax/blob/master/jax/_src/dtypes.py
Apache-2.0
def scalar_type_of(x: Any) -> type: """Return the scalar type associated with a JAX value.""" typ = dtype(x) if typ in _custom_float_dtypes: return float elif typ in _intn_dtypes: return int elif np.issubdtype(typ, np.bool_): return bool elif np.issubdtype(typ, np.integer): return int elif...
Return the scalar type associated with a JAX value.
scalar_type_of
python
jax-ml/jax
jax/_src/dtypes.py
https://github.com/jax-ml/jax/blob/master/jax/_src/dtypes.py
Apache-2.0
def _scalar_type_to_dtype(typ: type, value: Any = None) -> DType: """Return the numpy dtype for the given scalar type. Raises ------ OverflowError: if `typ` is `int` and the value is too large for int64. Examples -------- >>> _scalar_type_to_dtype(int) dtype('int32') >>> _scalar_type_to_dtype(float)...
Return the numpy dtype for the given scalar type. Raises ------ OverflowError: if `typ` is `int` and the value is too large for int64. Examples -------- >>> _scalar_type_to_dtype(int) dtype('int32') >>> _scalar_type_to_dtype(float) dtype('float32') >>> _scalar_type_to_dtype(complex) dtype('compl...
_scalar_type_to_dtype
python
jax-ml/jax
jax/_src/dtypes.py
https://github.com/jax-ml/jax/blob/master/jax/_src/dtypes.py
Apache-2.0
def coerce_to_array(x: Any, dtype: DTypeLike | None = None) -> np.ndarray: """Coerces a scalar or NumPy array to an np.array. Handles Python scalar type promotion according to JAX's rules, not NumPy's rules. """ if dtype is None and type(x) in python_scalar_dtypes: dtype = _scalar_type_to_dtype(type(x), ...
Coerces a scalar or NumPy array to an np.array. Handles Python scalar type promotion according to JAX's rules, not NumPy's rules.
coerce_to_array
python
jax-ml/jax
jax/_src/dtypes.py
https://github.com/jax-ml/jax/blob/master/jax/_src/dtypes.py
Apache-2.0
def _issubclass(a: Any, b: Any) -> bool: """Determines if ``a`` is a subclass of ``b``. Similar to issubclass, but returns False instead of an exception if `a` is not a class. """ try: return issubclass(a, b) except TypeError: return False
Determines if ``a`` is a subclass of ``b``. Similar to issubclass, but returns False instead of an exception if `a` is not a class.
_issubclass
python
jax-ml/jax
jax/_src/dtypes.py
https://github.com/jax-ml/jax/blob/master/jax/_src/dtypes.py
Apache-2.0
def issubdtype(a: DTypeLike | ExtendedDType | None, b: DTypeLike | ExtendedDType | None) -> bool: """Returns True if first argument is a typecode lower/equal in type hierarchy. This is like :func:`numpy.issubdtype`, but can handle dtype extensions such as :obj:`jax.dtypes.bfloat16` and `jax.dtypes...
Returns True if first argument is a typecode lower/equal in type hierarchy. This is like :func:`numpy.issubdtype`, but can handle dtype extensions such as :obj:`jax.dtypes.bfloat16` and `jax.dtypes.prng_key`.
issubdtype
python
jax-ml/jax
jax/_src/dtypes.py
https://github.com/jax-ml/jax/blob/master/jax/_src/dtypes.py
Apache-2.0
def isdtype(dtype: DTypeLike, kind: str | DTypeLike | tuple[str | DTypeLike, ...]) -> bool: """Returns a boolean indicating whether a provided dtype is of a specified kind. Args: dtype : the input dtype kind : the data type kind. If ``kind`` is dtype-like, return ``dtype = kind``. If ``kind`` i...
Returns a boolean indicating whether a provided dtype is of a specified kind. Args: dtype : the input dtype kind : the data type kind. If ``kind`` is dtype-like, return ``dtype = kind``. If ``kind`` is a string, then return True if the dtype is in the specified category: - ``'bool'``: ``{b...
isdtype
python
jax-ml/jax
jax/_src/dtypes.py
https://github.com/jax-ml/jax/blob/master/jax/_src/dtypes.py
Apache-2.0
def _jax_type(dtype: DType, weak_type: bool) -> JAXType: """Return the jax type for a dtype and weak type.""" if weak_type: if dtype == bool: return dtype if dtype in _custom_float_dtypes: return float return type(dtype.type(0).item()) return dtype
Return the jax type for a dtype and weak type.
_jax_type
python
jax-ml/jax
jax/_src/dtypes.py
https://github.com/jax-ml/jax/blob/master/jax/_src/dtypes.py
Apache-2.0
def _type_promotion_lattice(jax_numpy_dtype_promotion: str) -> dict[JAXType, list[JAXType]]: """ Return the type promotion lattice in the form of a DAG. This DAG maps each type to its immediately higher type on the lattice. """ b1, = _bool_types uint2, uint4, u1, u2, u4, u8, int2, int4, i1, i2, i4, i8 = _in...
Return the type promotion lattice in the form of a DAG. This DAG maps each type to its immediately higher type on the lattice.
_type_promotion_lattice
python
jax-ml/jax
jax/_src/dtypes.py
https://github.com/jax-ml/jax/blob/master/jax/_src/dtypes.py
Apache-2.0
def promote_types(a: DTypeLike, b: DTypeLike) -> DType: """Returns the type to which a binary operation should cast its arguments. JAX implementation of :func:`numpy.promote_types`. For details of JAX's type promotion semantics, see :ref:`type-promotion`. Args: a: a :class:`numpy.dtype` or a dtype specifi...
Returns the type to which a binary operation should cast its arguments. JAX implementation of :func:`numpy.promote_types`. For details of JAX's type promotion semantics, see :ref:`type-promotion`. Args: a: a :class:`numpy.dtype` or a dtype specifier. b: a :class:`numpy.dtype` or a dtype specifier. Re...
promote_types
python
jax-ml/jax
jax/_src/dtypes.py
https://github.com/jax-ml/jax/blob/master/jax/_src/dtypes.py
Apache-2.0
def dtype(x: Any, *, canonicalize: bool = False) -> DType: """Return the dtype object for a value or type, optionally canonicalized based on X64 mode.""" if x is None: raise ValueError(f"Invalid argument to dtype: {x}.") is_type = isinstance(x, type) if is_type and x in python_scalar_dtypes: dt = python...
Return the dtype object for a value or type, optionally canonicalized based on X64 mode.
dtype
python
jax-ml/jax
jax/_src/dtypes.py
https://github.com/jax-ml/jax/blob/master/jax/_src/dtypes.py
Apache-2.0
def result_type(*args: Any, return_weak_type_flag: bool = False) -> DType | tuple[DType, bool]: """Convenience function to apply JAX argument dtype promotion. Args: return_weak_type_flag : if True, then return a ``(dtype, weak_type)`` tuple. If False, just return `dtype` Returns: dtype or (dtype, ...
Convenience function to apply JAX argument dtype promotion. Args: return_weak_type_flag : if True, then return a ``(dtype, weak_type)`` tuple. If False, just return `dtype` Returns: dtype or (dtype, weak_type) depending on the value of the ``return_weak_type`` argument.
result_type
python
jax-ml/jax
jax/_src/dtypes.py
https://github.com/jax-ml/jax/blob/master/jax/_src/dtypes.py
Apache-2.0
def safe_to_cast(input_dtype_or_value: Any, output_dtype_or_value: Any) -> bool: """Check if a dtype/value is safe to cast to another dtype/value Args: input_dtype_or_value: a dtype or value (to be passed to result_type) representing the source dtype. output_dtype_or_value: a dtype o...
Check if a dtype/value is safe to cast to another dtype/value Args: input_dtype_or_value: a dtype or value (to be passed to result_type) representing the source dtype. output_dtype_or_value: a dtype or value (to be passed to result_type) representing the target dtype. Returns: boolean repr...
safe_to_cast
python
jax-ml/jax
jax/_src/dtypes.py
https://github.com/jax-ml/jax/blob/master/jax/_src/dtypes.py
Apache-2.0
def print_environment_info(return_string: bool = False) -> str | None: """Returns a string containing local environment & JAX installation information. This is useful information to include when asking a question or filing a bug. Args: return_string (bool) : if True, return the string rather than printing to ...
Returns a string containing local environment & JAX installation information. This is useful information to include when asking a question or filing a bug. Args: return_string (bool) : if True, return the string rather than printing to stdout.
print_environment_info
python
jax-ml/jax
jax/_src/environment_info.py
https://github.com/jax-ml/jax/blob/master/jax/_src/environment_info.py
Apache-2.0
def _initialize_error_code_ref() -> None: """Initialize the error code ref in the current thread. The shape and size of the error code array depend on the mesh in the context. In single-device environments, the array is a scalar. In multi-device environments, its shape and size match those of the mesh. """ ...
Initialize the error code ref in the current thread. The shape and size of the error code array depend on the mesh in the context. In single-device environments, the array is a scalar. In multi-device environments, its shape and size match those of the mesh.
_initialize_error_code_ref
python
jax-ml/jax
jax/_src/error_check.py
https://github.com/jax-ml/jax/blob/master/jax/_src/error_check.py
Apache-2.0
def set_error_if(pred: jax.Array, /, msg: str) -> None: """Set the internal error state if any element of `pred` is `True`. This function is used inside JAX computations to detect runtime errors without immediately halting execution. When this function is traced (e.g., inside :func:`jax.jit`), the correspondin...
Set the internal error state if any element of `pred` is `True`. This function is used inside JAX computations to detect runtime errors without immediately halting execution. When this function is traced (e.g., inside :func:`jax.jit`), the corresponding error message and its traceback are recorded. At executio...
set_error_if
python
jax-ml/jax
jax/_src/error_check.py
https://github.com/jax-ml/jax/blob/master/jax/_src/error_check.py
Apache-2.0
def raise_if_error() -> None: """Raise an exception if the internal error state is set. This function should be called after a computation completes to check for any errors that were marked during execution via `set_error_if()`. If an error exists, it raises a `JaxValueError` with the corresponding error messa...
Raise an exception if the internal error state is set. This function should be called after a computation completes to check for any errors that were marked during execution via `set_error_if()`. If an error exists, it raises a `JaxValueError` with the corresponding error message. This function should not be ...
raise_if_error
python
jax-ml/jax
jax/_src/error_check.py
https://github.com/jax-ml/jax/blob/master/jax/_src/error_check.py
Apache-2.0
def wrap_for_export(f): """Wrap a function with error checking to make it compatible with AOT mode. Error checking relies on global state, which cannot be serialized across processes. This wrapper ensures that the error state remains within the function scope, making it possible to export the function and late...
Wrap a function with error checking to make it compatible with AOT mode. Error checking relies on global state, which cannot be serialized across processes. This wrapper ensures that the error state remains within the function scope, making it possible to export the function and later import in other processes...
wrap_for_export
python
jax-ml/jax
jax/_src/error_check.py
https://github.com/jax-ml/jax/blob/master/jax/_src/error_check.py
Apache-2.0
def unwrap_from_import(f): """Unwrap a function after AOT import to restore error checking. When an AOT-exported function is imported in a new process, its error state is separate from the global error state of the current process. This wrapper ensures that errors detected during execution are correctly integr...
Unwrap a function after AOT import to restore error checking. When an AOT-exported function is imported in a new process, its error state is separate from the global error state of the current process. This wrapper ensures that errors detected during execution are correctly integrated into the global error che...
unwrap_from_import
python
jax-ml/jax
jax/_src/error_check.py
https://github.com/jax-ml/jax/blob/master/jax/_src/error_check.py
Apache-2.0
def register_ffi_target( name: str, fn: Any, platform: str = "cpu", api_version: int = 1, **kwargs: Any, ) -> None: """Registers a foreign function target. Args: name: the name of the target. fn: a ``PyCapsule`` object containing the function pointer, or a ``dict`` where the keys ...
Registers a foreign function target. Args: name: the name of the target. fn: a ``PyCapsule`` object containing the function pointer, or a ``dict`` where the keys are FFI stage names (e.g. `"execute"`) and the values are ``PyCapsule`` objects containing a pointer to the handler for that stage. ...
register_ffi_target
python
jax-ml/jax
jax/_src/ffi.py
https://github.com/jax-ml/jax/blob/master/jax/_src/ffi.py
Apache-2.0
def register_ffi_type_id( name: str, obj: Any, platform: str = "cpu", ) -> None: """Registers a custom type ID for a FFI target. Args: name: the name of the type ID. This name must be unique within the process. obj: a ``PyCapsule`` object encapsulating a pointer to the type ID. platform: th...
Registers a custom type ID for a FFI target. Args: name: the name of the type ID. This name must be unique within the process. obj: a ``PyCapsule`` object encapsulating a pointer to the type ID. platform: the target platform.
register_ffi_type_id
python
jax-ml/jax
jax/_src/ffi.py
https://github.com/jax-ml/jax/blob/master/jax/_src/ffi.py
Apache-2.0
def register_ffi_target_as_batch_partitionable(name: str) -> None: """Registers an FFI target as batch partitionable. Args: name: the name of the target. """ xla_client.register_custom_call_as_batch_partitionable(name) xla_bridge.register_plugin_callbacks( functools.partial(xla_client.register_cust...
Registers an FFI target as batch partitionable. Args: name: the name of the target.
register_ffi_target_as_batch_partitionable
python
jax-ml/jax
jax/_src/ffi.py
https://github.com/jax-ml/jax/blob/master/jax/_src/ffi.py
Apache-2.0
def pycapsule(funcptr): """Wrap a ctypes function pointer in a PyCapsule. The primary use of this function, and the reason why it lives with in the ``jax.ffi`` submodule, is to wrap function calls from external compiled libraries to be registered as XLA custom calls. Example usage:: import ctypes i...
Wrap a ctypes function pointer in a PyCapsule. The primary use of this function, and the reason why it lives with in the ``jax.ffi`` submodule, is to wrap function calls from external compiled libraries to be registered as XLA custom calls. Example usage:: import ctypes import jax from jax.lib im...
pycapsule
python
jax-ml/jax
jax/_src/ffi.py
https://github.com/jax-ml/jax/blob/master/jax/_src/ffi.py
Apache-2.0
def include_dir() -> str: """Get the path to the directory containing header files bundled with jaxlib""" jaxlib_dir = os.path.dirname(os.path.abspath(jaxlib.__file__)) return os.path.join(jaxlib_dir, "include")
Get the path to the directory containing header files bundled with jaxlib
include_dir
python
jax-ml/jax
jax/_src/ffi.py
https://github.com/jax-ml/jax/blob/master/jax/_src/ffi.py
Apache-2.0
def _convert_layout_for_lowering( aval: core.AbstractValue, layout: FfiLayoutOptions = None) -> Sequence[int]: """Convert a layout to the minor-to-major order used by the custom call API.""" if layout is None: return tuple(reversed(range(len(_aval_shape(aval))))) elif isinstance(layout, DeviceLocalLayout)...
Convert a layout to the minor-to-major order used by the custom call API.
_convert_layout_for_lowering
python
jax-ml/jax
jax/_src/ffi.py
https://github.com/jax-ml/jax/blob/master/jax/_src/ffi.py
Apache-2.0
def build_ffi_lowering_function( call_target_name: str, *, operand_layouts: Sequence[FfiLayoutOptions] | None = None, result_layouts: Sequence[FfiLayoutOptions] | None = None, backend_config: Mapping[str, ir.Attribute] | str | None = None, **lowering_args: Any, ) -> Callable[..., ir.Operation]: ...
Build a lowering op for an foreign function interface (FFI) target. By default, this lowering rule can use the input and output abstract values to compute the input and output types and shapes for the custom call, assuming row-major layouts. Note that layouts passed to this function as tuples should be in m...
build_ffi_lowering_function
python
jax-ml/jax
jax/_src/ffi.py
https://github.com/jax-ml/jax/blob/master/jax/_src/ffi.py
Apache-2.0
def ffi_lowering( call_target_name: str, *, operand_layouts: Sequence[FfiLayoutOptions] | None = None, result_layouts: Sequence[FfiLayoutOptions] | None = None, backend_config: Mapping[str, ir.Attribute] | str | None = None, **lowering_args: Any ) -> mlir.LoweringRule: """Build a lowering rule...
Build a lowering rule for an foreign function interface (FFI) target. By default, this lowering rule can use the input and output abstract values to compute the input and output types and shapes for the custom call, assuming row-major layouts. Note that layouts passed to this function as tuples should be in ...
ffi_lowering
python
jax-ml/jax
jax/_src/ffi.py
https://github.com/jax-ml/jax/blob/master/jax/_src/ffi.py
Apache-2.0
def ffi_call( target_name: str, result_shape_dtypes: ResultMetadata | Sequence[ResultMetadata], *, has_side_effect: bool = False, vmap_method: str | None = None, input_layouts: Sequence[FfiLayoutOptions] | None = None, output_layouts: FfiLayoutOptions | Sequence[FfiLayoutOptions] | None = No...
Call a foreign function interface (FFI) target. See the :ref:`ffi-tutorial` tutorial for more information. Like :func:`~jax.pure_callback`, the behavior of ``ffi_call`` under :func:`~jax.vmap` depends on the value of ``vmap_method``. See the :func:`~jax.pure_callback` documentation for more details about the ...
ffi_call
python
jax-ml/jax
jax/_src/ffi.py
https://github.com/jax-ml/jax/blob/master/jax/_src/ffi.py
Apache-2.0
def ravel_pytree(pytree): """Ravel (flatten) a pytree of arrays down to a 1D array. Args: pytree: a pytree of arrays and scalars to ravel. Returns: A pair where the first element is a 1D array representing the flattened and concatenated leaf values, with dtype determined by promoting the dtypes of ...
Ravel (flatten) a pytree of arrays down to a 1D array. Args: pytree: a pytree of arrays and scalars to ravel. Returns: A pair where the first element is a 1D array representing the flattened and concatenated leaf values, with dtype determined by promoting the dtypes of leaf values, and the second ...
ravel_pytree
python
jax-ml/jax
jax/_src/flatten_util.py
https://github.com/jax-ml/jax/blob/master/jax/_src/flatten_util.py
Apache-2.0
def num_available_tpu_chips_and_device_id(): """Returns the device id and number of TPU chips attached through PCI.""" num_chips = 0 tpu_version = None for vendor_path in glob.glob('/sys/bus/pci/devices/*/vendor'): vendor_id = pathlib.Path(vendor_path).read_text().strip() if vendor_id != _GOOGLE_PCI_VEN...
Returns the device id and number of TPU chips attached through PCI.
num_available_tpu_chips_and_device_id
python
jax-ml/jax
jax/_src/hardware_utils.py
https://github.com/jax-ml/jax/blob/master/jax/_src/hardware_utils.py
Apache-2.0
def pprof_equation_profile(jaxpr: core.Jaxpr) -> bytes: """Generates a pprof profile that maps jaxpr equations to Python stack traces. By visualizing the profile using pprof, one can identify Python code that is responsible for yielding large numbers of jaxpr equations. Args: jaxpr: a Jaxpr. Returns: ...
Generates a pprof profile that maps jaxpr equations to Python stack traces. By visualizing the profile using pprof, one can identify Python code that is responsible for yielding large numbers of jaxpr equations. Args: jaxpr: a Jaxpr. Returns: A gzip-compressed pprof Profile protocol buffer, suitable ...
pprof_equation_profile
python
jax-ml/jax
jax/_src/jaxpr_util.py
https://github.com/jax-ml/jax/blob/master/jax/_src/jaxpr_util.py
Apache-2.0
def eqns_using_var_with_invar_index(jaxpr: core.Jaxpr, invar: core.Var) -> Iterator[tuple[core.JaxprEqn, int]]: """Find all the equations which use invar and the positional index of its binder""" for eqn in jaxpr.eqns: for invar_index, eqn_var in enumerate(eqn.invars): if eqn_var == invar: yield e...
Find all the equations which use invar and the positional index of its binder
eqns_using_var_with_invar_index
python
jax-ml/jax
jax/_src/jaxpr_util.py
https://github.com/jax-ml/jax/blob/master/jax/_src/jaxpr_util.py
Apache-2.0
def eqns_using_var(jaxpr: core.Jaxpr, invar: core.Var) -> Iterator[core.JaxprEqn]: """Find the leaf equations using a variable""" # The complexity of this call is because the invar might originate from a nested jaxpr for eqn, invar_index in eqns_using_var_with_invar_index(jaxpr, invar): if (child_jaxprs_and_v...
Find the leaf equations using a variable
eqns_using_var
python
jax-ml/jax
jax/_src/jaxpr_util.py
https://github.com/jax-ml/jax/blob/master/jax/_src/jaxpr_util.py
Apache-2.0
def _conv_view(lhs, rhs_shape, window_strides, pads, pad_value): """Compute the view (and its axes) of a convolution or window reduction.""" if (_min(lhs.ndim, len(rhs_shape)) < 2 or lhs.ndim != len(rhs_shape) or lhs.shape[1] != rhs_shape[1]): raise ValueError('Dimension mismatch') if len(window_strides...
Compute the view (and its axes) of a convolution or window reduction.
_conv_view
python
jax-ml/jax
jax/_src/lax_reference.py
https://github.com/jax-ml/jax/blob/master/jax/_src/lax_reference.py
Apache-2.0
def _make_reducer(py_binop, init_val): """Make a reducer function given a Python binop and an initial value.""" # It's tempting to use np.ufunc.reduce (even with a ufunc generated by # np.frompyfunc(py_binop)), but this may not agree with custom init_val. # We make an attempt to uncover an underlying numpy ufun...
Make a reducer function given a Python binop and an initial value.
_make_reducer
python
jax-ml/jax
jax/_src/lax_reference.py
https://github.com/jax-ml/jax/blob/master/jax/_src/lax_reference.py
Apache-2.0
def attach(package_name: str, submodules: Sequence[str]) -> tuple[ Callable[[str], Any], Callable[[], list[str]], list[str], ]: """Lazily loads submodules of a package. Returns: A tuple of ``__getattr__``, ``__dir__`` function and ``__all__`` -- a list of available global names, which can be us...
Lazily loads submodules of a package. Returns: A tuple of ``__getattr__``, ``__dir__`` function and ``__all__`` -- a list of available global names, which can be used to replace the corresponding definitions in the package. Raises: RuntimeError: If the ``__name__`` of the caller cannot be determin...
attach
python
jax-ml/jax
jax/_src/lazy_loader.py
https://github.com/jax-ml/jax/blob/master/jax/_src/lazy_loader.py
Apache-2.0
def wrap(self, gen, gen_static_args, out_store: Store | EqualStore | None) -> WrappedFun: """Add another transform and its store.""" if out_store is None: return WrappedFun(self.f, partial(gen, self.f_transformed, *gen_static_args), ((gen, gen_static_args),) + self.trans...
Add another transform and its store.
wrap
python
jax-ml/jax
jax/_src/linear_util.py
https://github.com/jax-ml/jax/blob/master/jax/_src/linear_util.py
Apache-2.0