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 broadcast_prefix(prefix_tree: Any, full_tree: Any,
is_leaf: Callable[[Any], bool] | None = None
) -> list[Any]:
"""Broadcasts tree prefix leaves into the full set of leaves for a given full tree.
Args:
prefix_tree: a pytree that is a tree prefix of full_tree.
... | Broadcasts tree prefix leaves into the full set of leaves for a given full tree.
Args:
prefix_tree: a pytree that is a tree prefix of full_tree.
full_tree: a pytree with the structure to broadcast the prefix leaves into.
is_leaf: an optionally specified function that will be called at each
... | broadcast_prefix | python | jax-ml/jax | jax/_src/tree_util.py | https://github.com/jax-ml/jax/blob/master/jax/_src/tree_util.py | Apache-2.0 |
def flatten_one_level(tree: Any) -> tuple[Iterable[Any], Hashable]:
"""Flatten the given pytree node by one level.
Args:
tree: A valid pytree node, either built-in or registered via
:func:`register_pytree_node` or related functions.
Returns:
A pair of the pytrees flattened children and its hashabl... | Flatten the given pytree node by one level.
Args:
tree: A valid pytree node, either built-in or registered via
:func:`register_pytree_node` or related functions.
Returns:
A pair of the pytrees flattened children and its hashable metadata.
Raises:
ValueError: If the given pytree is not a built... | flatten_one_level | python | jax-ml/jax | jax/_src/tree_util.py | https://github.com/jax-ml/jax/blob/master/jax/_src/tree_util.py | Apache-2.0 |
def flatten_one_level_with_keys(
tree: Any,
) -> tuple[Iterable[KeyLeafPair], Hashable]:
"""Flatten the given pytree node by one level, with keys."""
out = default_registry.flatten_one_level_with_keys(tree) # type: ignore
if out is None:
raise ValueError(f"can't tree-flatten type: {type(tree)}")
else:
... | Flatten the given pytree node by one level, with keys. | flatten_one_level_with_keys | python | jax-ml/jax | jax/_src/tree_util.py | https://github.com/jax-ml/jax/blob/master/jax/_src/tree_util.py | Apache-2.0 |
def equality_errors(
tree1: Any, tree2: Any, is_leaf: Callable[[Any], bool] | None = None,
) -> Iterable[tuple[KeyPath, str, str, str]]:
"""Helper to describe structural differences between two pytrees.
Args:
tree1, tree2: pytrees known to have different structure.
Usage:
raise Exception(
"... | Helper to describe structural differences between two pytrees.
Args:
tree1, tree2: pytrees known to have different structure.
Usage:
raise Exception(
"Value 1 and value 2 must have the same pytree structure, but they have "
"the following structural differences:
" +
("
".join(
... | equality_errors | python | jax-ml/jax | jax/_src/tree_util.py | https://github.com/jax-ml/jax/blob/master/jax/_src/tree_util.py | Apache-2.0 |
def keystr(keys: KeyPath, *, simple: bool = False, separator: str = '') -> str:
"""Helper to pretty-print a tuple of keys.
Args:
keys: A tuple of ``KeyEntry`` or any class that can be converted to string.
simple: If True, use a simplified string representation for keys. The
simple representation of k... | Helper to pretty-print a tuple of keys.
Args:
keys: A tuple of ``KeyEntry`` or any class that can be converted to string.
simple: If True, use a simplified string representation for keys. The
simple representation of keys will be more compact than the default, but
is ambiguous in some cases (for ... | keystr | python | jax-ml/jax | jax/_src/tree_util.py | https://github.com/jax-ml/jax/blob/master/jax/_src/tree_util.py | Apache-2.0 |
def register_pytree_with_keys(
nodetype: type[T],
flatten_with_keys: Callable[[T], tuple[Iterable[KeyLeafPair], _AuxData]],
unflatten_func: Callable[[_AuxData, Iterable[Any]], T],
flatten_func: None | (Callable[[T], tuple[Iterable[Any], _AuxData]]) = None,
):
"""Extends the set of types that are consi... | Extends the set of types that are considered internal nodes in pytrees.
This is a more powerful alternative to ``register_pytree_node`` that allows
you to access each pytree leaf's key path when flattening and tree-mapping.
Args:
nodetype: a Python type to treat as an internal pytree node.
flatten_with_... | register_pytree_with_keys | python | jax-ml/jax | jax/_src/tree_util.py | https://github.com/jax-ml/jax/blob/master/jax/_src/tree_util.py | Apache-2.0 |
def register_pytree_with_keys_class(cls: Typ) -> Typ:
"""Extends the set of types that are considered internal nodes in pytrees.
This function is similar to ``register_pytree_node_class``, but requires a
class that defines how it could be flattened with keys.
It is a thin wrapper around ``register_pytree_with... | Extends the set of types that are considered internal nodes in pytrees.
This function is similar to ``register_pytree_node_class``, but requires a
class that defines how it could be flattened with keys.
It is a thin wrapper around ``register_pytree_with_keys``, and
provides a class-oriented interface:
Args... | register_pytree_with_keys_class | python | jax-ml/jax | jax/_src/tree_util.py | https://github.com/jax-ml/jax/blob/master/jax/_src/tree_util.py | Apache-2.0 |
def register_dataclass(
nodetype: Typ,
data_fields: Sequence[str] | None = None,
meta_fields: Sequence[str] | None = None,
drop_fields: Sequence[str] = (),
) -> Typ:
"""Extends the set of types that are considered internal nodes in pytrees.
This differs from ``register_pytree_with_keys_class`` in t... | Extends the set of types that are considered internal nodes in pytrees.
This differs from ``register_pytree_with_keys_class`` in that the C++
registries use the optimized C++ dataclass builtin instead of the argument
functions.
See :ref:`extending-pytrees` for more information about registering pytrees.
Ar... | register_dataclass | python | jax-ml/jax | jax/_src/tree_util.py | https://github.com/jax-ml/jax/blob/master/jax/_src/tree_util.py | Apache-2.0 |
def register_static(cls: type[H]) -> type[H]:
"""Registers `cls` as a pytree with no leaves.
Instances are treated as static by :func:`jax.jit`, :func:`jax.pmap`, etc. This can
be an alternative to labeling inputs as static using ``jit``'s ``static_argnums``
and ``static_argnames`` kwargs, ``pmap``'s ``static_... | Registers `cls` as a pytree with no leaves.
Instances are treated as static by :func:`jax.jit`, :func:`jax.pmap`, etc. This can
be an alternative to labeling inputs as static using ``jit``'s ``static_argnums``
and ``static_argnames`` kwargs, ``pmap``'s ``static_broadcasted_argnums``, etc.
Args:
cls: type ... | register_static | python | jax-ml/jax | jax/_src/tree_util.py | https://github.com/jax-ml/jax/blob/master/jax/_src/tree_util.py | Apache-2.0 |
def safe_zip(*args):
"""
Like builtin :func:`zip`, but with additional safety checks.
The differences from :func:`zip` are:
- :func:`safe_zip` checks that at least one argument is provided.
- :func:`safe_zip` checks that all arguments have the same length.
- :func:`safe_zip` returns an eagerly-evaluated l... |
Like builtin :func:`zip`, but with additional safety checks.
The differences from :func:`zip` are:
- :func:`safe_zip` checks that at least one argument is provided.
- :func:`safe_zip` checks that all arguments have the same length.
- :func:`safe_zip` returns an eagerly-evaluated list instead of a
lazil... | safe_zip | python | jax-ml/jax | jax/_src/util.py | https://github.com/jax-ml/jax/blob/master/jax/_src/util.py | Apache-2.0 |
def unzip2(xys: Iterable[tuple[T1, T2]]
) -> tuple[tuple[T1, ...], tuple[T2, ...]]:
"""Unzip sequence of length-2 tuples into two tuples."""
# Note: we deliberately don't use zip(*xys) because it is lazily evaluated,
# is too permissive about inputs, and does not guarantee a length-2 output.
xs: list[T1] = ... | Unzip sequence of length-2 tuples into two tuples. | unzip2 | python | jax-ml/jax | jax/_src/util.py | https://github.com/jax-ml/jax/blob/master/jax/_src/util.py | Apache-2.0 |
def unzip3(xyzs: Iterable[tuple[T1, T2, T3]]
) -> tuple[tuple[T1, ...], tuple[T2, ...], tuple[T3, ...]]:
"""Unzip sequence of length-3 tuples into three tuples."""
# Note: we deliberately don't use zip(*xyzs) because it is lazily evaluated,
# is too permissive about inputs, and does not guarantee a length-3 o... | Unzip sequence of length-3 tuples into three tuples. | unzip3 | python | jax-ml/jax | jax/_src/util.py | https://github.com/jax-ml/jax/blob/master/jax/_src/util.py | Apache-2.0 |
def split_list(args: Sequence[T], ns: Sequence[int]) -> list[list[T]]:
"""Split list into sublists of the specified sizes."""
args = list(args)
lists = []
for n in ns:
lists.append(args[:n])
args = args[n:]
lists.append(args)
return lists | Split list into sublists of the specified sizes. | split_list | python | jax-ml/jax | jax/_src/util.py | https://github.com/jax-ml/jax/blob/master/jax/_src/util.py | Apache-2.0 |
def partition_list(bs: Sequence[bool], l: Sequence[T]) -> tuple[list[T], list[T]]:
"""Partition a list into two based on a mask."""
assert len(bs) == len(l)
lists: tuple[list[T], list[T]] = ([], [])
for b, x in zip(bs, l):
lists[b].append(x)
return lists | Partition a list into two based on a mask. | partition_list | python | jax-ml/jax | jax/_src/util.py | https://github.com/jax-ml/jax/blob/master/jax/_src/util.py | Apache-2.0 |
def merge_lists(bs: Sequence[bool],
l0: Sequence[T1],
l1: Sequence[T2]
) -> list[T1 | T2]:
"""Merge the elements of two lists based on a mask."""
assert sum(bs) == len(l1) and len(bs) - sum(bs) == len(l0)
i0, i1 = iter(l0), iter(l1)
out: list[T1 | T2] = [next(i1) ... | Merge the elements of two lists based on a mask. | merge_lists | python | jax-ml/jax | jax/_src/util.py | https://github.com/jax-ml/jax/blob/master/jax/_src/util.py | Apache-2.0 |
def unflatten(xs: Iterable[T], ns: Sequence[int]) -> list[list[T]]:
"""Splits `xs` into subsequences of lengths `ns`.
Unlike `split_list`, the `sum(ns)` must be equal to `len(xs)`."""
xs_iter = iter(xs)
unflattened = [[next(xs_iter) for _ in range(n)] for n in ns]
assert next(xs_iter, _unflatten_done) is _un... | Splits `xs` into subsequences of lengths `ns`.
Unlike `split_list`, the `sum(ns)` must be equal to `len(xs)`. | unflatten | python | jax-ml/jax | jax/_src/util.py | https://github.com/jax-ml/jax/blob/master/jax/_src/util.py | Apache-2.0 |
def weakref_lru_cache(call: Callable, maxsize=2048,
trace_context_in_key: bool = True):
"""
Least recently used cache decorator with weakref support.
The cache will take a weakref to the first argument of the wrapped function
and strong refs to all subsequent operations. In all other resp... |
Least recently used cache decorator with weakref support.
The cache will take a weakref to the first argument of the wrapped function
and strong refs to all subsequent operations. In all other respects it should
behave similar to `functools.lru_cache`.
| weakref_lru_cache | python | jax-ml/jax | jax/_src/util.py | https://github.com/jax-ml/jax/blob/master/jax/_src/util.py | Apache-2.0 |
def wraps(
wrapped: Callable,
namestr: str | None = None,
docstr: str | None = None,
**kwargs,
) -> Callable[[T], T]:
"""
Like functools.wraps, but with finer-grained control over the name and docstring
of the resulting function.
"""
def wrapper(fun: T) -> T:
try:
name = fun_name(wra... |
Like functools.wraps, but with finer-grained control over the name and docstring
of the resulting function.
| wraps | python | jax-ml/jax | jax/_src/util.py | https://github.com/jax-ml/jax/blob/master/jax/_src/util.py | Apache-2.0 |
def distributed_debug_log(*pairs):
"""Format and log `pairs` if config.jax_distributed_debug is enabled.
Args:
pairs: A sequence of label/value pairs to log. The first pair is treated as
a heading for subsequent pairs.
"""
if config.distributed_debug.value:
lines = ["\nDISTRIBUTED_DEBUG_BEGIN"]
... | Format and log `pairs` if config.jax_distributed_debug is enabled.
Args:
pairs: A sequence of label/value pairs to log. The first pair is treated as
a heading for subsequent pairs.
| distributed_debug_log | python | jax-ml/jax | jax/_src/util.py | https://github.com/jax-ml/jax/blob/master/jax/_src/util.py | Apache-2.0 |
def use_cpp_class(cpp_cls: type[Any]) -> Callable[[type[T]], type[T]]:
"""A decorator replacing a Python class with its C++ version at runtime."""
def wrapper(cls):
if cpp_cls is None:
return cls
exclude_methods = {'__module__', '__dict__', '__doc__'}
for attr_name, attr in cls.__dict__.items()... | A decorator replacing a Python class with its C++ version at runtime. | use_cpp_class | python | jax-ml/jax | jax/_src/util.py | https://github.com/jax-ml/jax/blob/master/jax/_src/util.py | Apache-2.0 |
def use_cpp_method(is_enabled: bool = True) -> Callable[[T], T]:
"""A decorator excluding methods from the set that are forwarded to C++ class."""
if not isinstance(is_enabled, bool):
raise TypeError("``is_enabled`` must be a bool")
def decorator(f):
if is_enabled:
original_func = _original_func(f)
... | A decorator excluding methods from the set that are forwarded to C++ class. | use_cpp_method | python | jax-ml/jax | jax/_src/util.py | https://github.com/jax-ml/jax/blob/master/jax/_src/util.py | Apache-2.0 |
def make_tpu_client(
library_path: str | None = None, options: _NameValueMapping | None = None
):
"""Returns a TPU client. Defaults to allowing 32 in-flight computations."""
if not _jax.pjrt_plugin_loaded('tpu'):
c_api = xla_client.load_pjrt_plugin_dynamically(
"tpu", library_path or "libtpu.so"
... | Returns a TPU client. Defaults to allowing 32 in-flight computations. | make_tpu_client | python | jax-ml/jax | jax/_src/xla_bridge.py | https://github.com/jax-ml/jax/blob/master/jax/_src/xla_bridge.py | Apache-2.0 |
def make_cpu_client(
collectives: xla_client._xla.CpuCollectives | None = None,
) -> xla_client.Client:
"""Creates a CPU client with the requested collectives implementation.
The implementation of CPU collectives used by the client is determined by the
flag `--jax_cpu_collectives_implementation` - unless `co... | Creates a CPU client with the requested collectives implementation.
The implementation of CPU collectives used by the client is determined by the
flag `--jax_cpu_collectives_implementation` - unless `collectives` is
provided, in which case the flag is overridden and `collectives` is used.
Args:
collective... | make_cpu_client | python | jax-ml/jax | jax/_src/xla_bridge.py | https://github.com/jax-ml/jax/blob/master/jax/_src/xla_bridge.py | Apache-2.0 |
def _get_pjrt_plugin_names_and_library_paths(
plugins_from_env: str,
) -> dict[str, str]:
"""Gets the names and library paths of PJRT plugins to load from env var.
Args:
plugins_from_env: plugin name and paths from env var. It is in the format
of 'name1:path1,name2:path2' ('name1;path1,name2;path2' f... | Gets the names and library paths of PJRT plugins to load from env var.
Args:
plugins_from_env: plugin name and paths from env var. It is in the format
of 'name1:path1,name2:path2' ('name1;path1,name2;path2' for windows).
Returns:
A dict of {plugin_name: library path} for the PJRT plugins to load.
| _get_pjrt_plugin_names_and_library_paths | python | jax-ml/jax | jax/_src/xla_bridge.py | https://github.com/jax-ml/jax/blob/master/jax/_src/xla_bridge.py | Apache-2.0 |
def _get_pjrt_plugin_config(
json_path: str,
) -> tuple[
str, Mapping[str, str | int | list[int] | float | bool] | None
]:
"""Gets PJRT plugin configuration from a json file.
The json file needs to have a "library_path" field for the plugin library
path. It can have an optional "create_option" field for ... | Gets PJRT plugin configuration from a json file.
The json file needs to have a "library_path" field for the plugin library
path. It can have an optional "create_option" field for the options used when
creating a PJRT plugin client. The value of "create_option" is key-value
pairs. Please see xla_client._NameVal... | _get_pjrt_plugin_config | python | jax-ml/jax | jax/_src/xla_bridge.py | https://github.com/jax-ml/jax/blob/master/jax/_src/xla_bridge.py | Apache-2.0 |
def discover_pjrt_plugins() -> None:
"""Discovers plugins in the namespace package `jax_plugins` and import them.
There are two methods used to discover plugin modules. They are intended
to be used together by implementers in order to cover all packaging and
development cases:
1. Define a globally unique mo... | Discovers plugins in the namespace package `jax_plugins` and import them.
There are two methods used to discover plugin modules. They are intended
to be used together by implementers in order to cover all packaging and
development cases:
1. Define a globally unique module under the `jax_plugins` namespace
... | discover_pjrt_plugins | python | jax-ml/jax | jax/_src/xla_bridge.py | https://github.com/jax-ml/jax/blob/master/jax/_src/xla_bridge.py | Apache-2.0 |
def register_plugin(
plugin_name: str,
*,
priority: int = 400,
library_path: str | None = None,
options: OptionsDict | Callable[[], OptionsDict] | None = None,
c_api: Any | None = None,
) -> Any:
"""Registers a backend factory for the PJRT plugin.
Args:
plugin_name: the name of the plug... | Registers a backend factory for the PJRT plugin.
Args:
plugin_name: the name of the plugin.
priority: the priority this plugin should be registered in jax backends.
Default to be 400.
library_path: Optional. The full path to the .so file of the plugin. The
plugin needs to provide either the l... | register_plugin | python | jax-ml/jax | jax/_src/xla_bridge.py | https://github.com/jax-ml/jax/blob/master/jax/_src/xla_bridge.py | Apache-2.0 |
def register_pjrt_plugin_factories_from_env() -> None:
"""Registers backend factories for PJRT plugins.
A backend factory will be registered for every PJRT plugin in the input
string, in the format of 'name1:path1,name2:path2' ('name1;path1,name2;path2'
for windows). The path can be a path to the plugin librar... | Registers backend factories for PJRT plugins.
A backend factory will be registered for every PJRT plugin in the input
string, in the format of 'name1:path1,name2:path2' ('name1;path1,name2;path2'
for windows). The path can be a path to the plugin library or a path to the
plugin configuration json file. The jso... | register_pjrt_plugin_factories_from_env | python | jax-ml/jax | jax/_src/xla_bridge.py | https://github.com/jax-ml/jax/blob/master/jax/_src/xla_bridge.py | Apache-2.0 |
def canonicalize_platform(platform: str) -> str:
"""Replaces platform aliases with their concrete equivalent.
In particular, replaces "gpu" with either "cuda" or "rocm", depending on which
hardware is actually present. We want to distinguish "cuda" and "rocm" for
purposes such as MLIR lowering rules, but in ma... | Replaces platform aliases with their concrete equivalent.
In particular, replaces "gpu" with either "cuda" or "rocm", depending on which
hardware is actually present. We want to distinguish "cuda" and "rocm" for
purposes such as MLIR lowering rules, but in many cases we don't want to
force users to care.
| canonicalize_platform | python | jax-ml/jax | jax/_src/xla_bridge.py | https://github.com/jax-ml/jax/blob/master/jax/_src/xla_bridge.py | Apache-2.0 |
def backends_are_initialized() -> bool:
"Returns true if backends have already been initialized."
with _backend_lock:
return len(_backends) != 0 | Returns true if backends have already been initialized. | backends_are_initialized | python | jax-ml/jax | jax/_src/xla_bridge.py | https://github.com/jax-ml/jax/blob/master/jax/_src/xla_bridge.py | Apache-2.0 |
def register_plugin_callbacks(callback):
"""Registers a callback to be called with c_api after plugins discovery.
The callback will be called on all discovered PJRT C API plugins. If
`register_plugin_callbacks` is called before the plugins are discovered, the
callback will be called right after the plugins are... | Registers a callback to be called with c_api after plugins discovery.
The callback will be called on all discovered PJRT C API plugins. If
`register_plugin_callbacks` is called before the plugins are discovered, the
callback will be called right after the plugins are discovered. Otherwise, the
callback will be... | register_plugin_callbacks | python | jax-ml/jax | jax/_src/xla_bridge.py | https://github.com/jax-ml/jax/blob/master/jax/_src/xla_bridge.py | Apache-2.0 |
def get_device_backend(
device: xla_client.Device | None = None,
) -> xla_client.Client:
"""Returns the Backend associated with `device`, or the default Backend."""
if device is not None:
return device.client
return get_backend() | Returns the Backend associated with `device`, or the default Backend. | get_device_backend | python | jax-ml/jax | jax/_src/xla_bridge.py | https://github.com/jax-ml/jax/blob/master/jax/_src/xla_bridge.py | Apache-2.0 |
def device_count(
backend: str | xla_client.Client | None = None
) -> int:
"""Returns the total number of devices.
On most platforms, this is the same as :py:func:`jax.local_device_count`.
However, on multi-process platforms where different devices are associated
with different processes, this will return ... | Returns the total number of devices.
On most platforms, this is the same as :py:func:`jax.local_device_count`.
However, on multi-process platforms where different devices are associated
with different processes, this will return the total number of devices across
all processes.
Args:
backend: This is an... | device_count | python | jax-ml/jax | jax/_src/xla_bridge.py | https://github.com/jax-ml/jax/blob/master/jax/_src/xla_bridge.py | Apache-2.0 |
def local_device_count(
backend: str | xla_client.Client | None = None
) -> int:
"""Returns the number of devices addressable by this process."""
return int(get_backend(backend).local_device_count()) | Returns the number of devices addressable by this process. | local_device_count | python | jax-ml/jax | jax/_src/xla_bridge.py | https://github.com/jax-ml/jax/blob/master/jax/_src/xla_bridge.py | Apache-2.0 |
def devices(
backend: str | xla_client.Client | None = None
) -> list[xla_client.Device]:
"""Returns a list of all devices for a given backend.
.. currentmodule:: jaxlib._jax
Each device is represented by a subclass of :class:`Device` (e.g.
:class:`CpuDevice`, :class:`GpuDevice`). The length of the return... | Returns a list of all devices for a given backend.
.. currentmodule:: jaxlib._jax
Each device is represented by a subclass of :class:`Device` (e.g.
:class:`CpuDevice`, :class:`GpuDevice`). The length of the returned list is
equal to ``device_count(backend)``. Local devices can be identified by
comparing :at... | devices | python | jax-ml/jax | jax/_src/xla_bridge.py | https://github.com/jax-ml/jax/blob/master/jax/_src/xla_bridge.py | Apache-2.0 |
def backend_pjrt_c_api_version(platform=None) -> tuple[int, int] | None:
"""Returns the PJRT C API version of the backend.
Returns None if the backend does not use PJRT C API.
"""
backend = get_backend(platform)
if hasattr(backend, "pjrt_c_api_major_version") and hasattr(
backend, "pjrt_c_api_minor_ver... | Returns the PJRT C API version of the backend.
Returns None if the backend does not use PJRT C API.
| backend_pjrt_c_api_version | python | jax-ml/jax | jax/_src/xla_bridge.py | https://github.com/jax-ml/jax/blob/master/jax/_src/xla_bridge.py | Apache-2.0 |
def backend_xla_version(platform=None) -> int | None:
"""Returns the XLA version of the backend.
Returns None if the backend does not use PJRT C API or does not have
xla_version in the plugin attributes. This method can be used to skip features
that are not available before certain xla_version if the backend i... | Returns the XLA version of the backend.
Returns None if the backend does not use PJRT C API or does not have
xla_version in the plugin attributes. This method can be used to skip features
that are not available before certain xla_version if the backend is a
plugin and uses xla_version.
| backend_xla_version | python | jax-ml/jax | jax/_src/xla_bridge.py | https://github.com/jax-ml/jax/blob/master/jax/_src/xla_bridge.py | Apache-2.0 |
def backend_stablehlo_version(platform=None) -> Sequence[int] | None:
"""Returns the StableHLO version of the backend.
Returns None if the backend does not use PJRT C API or does not have
stablehlo_current_version in the plugin attributes. This method can be used to
skip features that are not available before ... | Returns the StableHLO version of the backend.
Returns None if the backend does not use PJRT C API or does not have
stablehlo_current_version in the plugin attributes. This method can be used to
skip features that are not available before certain stablehlo_current_version
if the backend is a plugin and uses sta... | backend_stablehlo_version | python | jax-ml/jax | jax/_src/xla_bridge.py | https://github.com/jax-ml/jax/blob/master/jax/_src/xla_bridge.py | Apache-2.0 |
def local_devices(process_index: int | None = None,
backend: str | xla_client.Client | None = None,
host_id: int | None = None) -> list[xla_client.Device]:
"""Like :py:func:`jax.devices`, but only returns devices local to a given process.
If ``process_index`` is ``None``, return... | Like :py:func:`jax.devices`, but only returns devices local to a given process.
If ``process_index`` is ``None``, returns devices local to this process.
Args:
process_index: the integer index of the process. Process indices can be
retrieved via ``len(jax.process_count())``.
backend: This is an exper... | local_devices | python | jax-ml/jax | jax/_src/xla_bridge.py | https://github.com/jax-ml/jax/blob/master/jax/_src/xla_bridge.py | Apache-2.0 |
def process_index(
backend: str | xla_client.Client | None = None
) -> int:
"""Returns the integer process index of this process.
On most platforms, this will always be 0. This will vary on multi-process
platforms though.
Args:
backend: This is an experimental feature and the API is likely to change.
... | Returns the integer process index of this process.
On most platforms, this will always be 0. This will vary on multi-process
platforms though.
Args:
backend: This is an experimental feature and the API is likely to change.
Optional, a string representing the xla backend: ``'cpu'``, ``'gpu'``, or
... | process_index | python | jax-ml/jax | jax/_src/xla_bridge.py | https://github.com/jax-ml/jax/blob/master/jax/_src/xla_bridge.py | Apache-2.0 |
def process_count(
backend: str | xla_client.Client | None = None
) -> int:
"""Returns the number of JAX processes associated with the backend."""
return max(d.process_index for d in devices(backend)) + 1 | Returns the number of JAX processes associated with the backend. | process_count | python | jax-ml/jax | jax/_src/xla_bridge.py | https://github.com/jax-ml/jax/blob/master/jax/_src/xla_bridge.py | Apache-2.0 |
def process_indices(
backend: str | xla_client.Client | None = None
) -> list[int]:
"""Returns the list of all JAX process indices associated with the backend.
Args:
backend: This is an experimental feature and the API is likely to change.
Optional, a string representing the xla backend: ``'cpu'``, `... | Returns the list of all JAX process indices associated with the backend.
Args:
backend: This is an experimental feature and the API is likely to change.
Optional, a string representing the xla backend: ``'cpu'``, ``'gpu'``, or
``'tpu'``.
Returns:
List of integer process indices.
| process_indices | python | jax-ml/jax | jax/_src/xla_bridge.py | https://github.com/jax-ml/jax/blob/master/jax/_src/xla_bridge.py | Apache-2.0 |
def dot_product_attention(
query: Array,
key: Array,
value: Array,
bias: Array | None = None,
mask: Array | None = None,
q_seqlen: Array | None = None,
kv_seqlen: Array | None = None,
q_offsets: Array | None = None,
kv_offsets: Array | None = None,
fp8_params: FP8Params | None = ... | Computes dot-product attention given query (Q), key (K), and value (V).
This function serves as the core operation for applying attention
mechanisms as described in the paper [https://arxiv.org/abs/1706.03762].
Initially, it determines the attention weights by processing Q and K,
subsequently combining the out... | dot_product_attention | python | jax-ml/jax | jax/_src/cudnn/fused_attention_stablehlo.py | https://github.com/jax-ml/jax/blob/master/jax/_src/cudnn/fused_attention_stablehlo.py | Apache-2.0 |
def call_cudnn_fusion(f, *args, **kwargs):
"""Creates a new cudnn_fusion corresponding to calling
the given function f with args and kwargs."""
jaxpr, out_shapes = jax.make_jaxpr(
functools.partial(f, **kwargs), return_shape=True
)(*args)
flat_args = jax.tree.leaves(args)
out_tree = jax.tree.structure(o... | Creates a new cudnn_fusion corresponding to calling
the given function f with args and kwargs. | call_cudnn_fusion | python | jax-ml/jax | jax/_src/cudnn/fusion.py | https://github.com/jax-ml/jax/blob/master/jax/_src/cudnn/fusion.py | Apache-2.0 |
def _cudnn_fusion_stablehlo_lowering(
ctx,
*args,
name,
jaxpr,
):
"""Make cudnn_fusion which calls the implementation function.
Currently this leaks a CallOp since we're using the `core_call_lowering`
function, but this should get cleaned up by DCE easily.
"""
impl = mlir.core_call_lowering(
ctx, ... | Make cudnn_fusion which calls the implementation function.
Currently this leaks a CallOp since we're using the `core_call_lowering`
function, but this should get cleaned up by DCE easily.
| _cudnn_fusion_stablehlo_lowering | python | jax-ml/jax | jax/_src/cudnn/fusion.py | https://github.com/jax-ml/jax/blob/master/jax/_src/cudnn/fusion.py | Apache-2.0 |
def scaled_matmul_wrapper(
lhs: Array,
rhs: Array,
lhs_scales: Array,
rhs_scales: Array,
preferred_element_type: DTypeLike = jnp.float32,
) -> Array:
"""
Performs scaled matrix multiplication between two 3D arrays, with scaling
factors applied to the matrices.
Args:
lhs (Arr... |
Performs scaled matrix multiplication between two 3D arrays, with scaling
factors applied to the matrices.
Args:
lhs (Array): A 3D array of shape (B, M, K).
rhs (Array): A 3D array of shape (B, N, K).
lhs_scales (Array): A 3D array of shape (B, M, K_block).
rhs_scales (Arra... | scaled_matmul_wrapper | python | jax-ml/jax | jax/_src/cudnn/scaled_matmul_stablehlo.py | https://github.com/jax-ml/jax/blob/master/jax/_src/cudnn/scaled_matmul_stablehlo.py | Apache-2.0 |
def shape_normalization(x, dimension_numbers):
"""
Normalizes the shape of the input tensor `x` to `(B, M, K)`.
This function rearranges and reshapes the input tensor `x` such that:
- `B` represents the batch dimensions.
- `M` represents the non-contracting dimensions.
- `K` represents the contracting dime... |
Normalizes the shape of the input tensor `x` to `(B, M, K)`.
This function rearranges and reshapes the input tensor `x` such that:
- `B` represents the batch dimensions.
- `M` represents the non-contracting dimensions.
- `K` represents the contracting dimensions.
The dimensions are reordered and reshaped... | shape_normalization | python | jax-ml/jax | jax/_src/cudnn/scaled_matmul_stablehlo.py | https://github.com/jax-ml/jax/blob/master/jax/_src/cudnn/scaled_matmul_stablehlo.py | Apache-2.0 |
def compute_dot_output_shape(
lhs_shape, rhs_shape, lhs_dimension_numbers, rhs_dimension_numbers
):
"""
Computes the output shape for a `lax.dot_general`-like operation.
"""
lhs_contract, lhs_batch = lhs_dimension_numbers[0], lhs_dimension_numbers[1]
rhs_contract, rhs_batch = rhs_dimension_numbers[0], r... |
Computes the output shape for a `lax.dot_general`-like operation.
| compute_dot_output_shape | python | jax-ml/jax | jax/_src/cudnn/scaled_matmul_stablehlo.py | https://github.com/jax-ml/jax/blob/master/jax/_src/cudnn/scaled_matmul_stablehlo.py | Apache-2.0 |
def do_p(self, arg):
"""p expression
Evaluates and prints the value of an expression
"""
try:
print(repr(self.evaluate(arg)), file=self.stdout)
except:
self._error_message() | p expression
Evaluates and prints the value of an expression
| do_p | python | jax-ml/jax | jax/_src/debugger/cli_debugger.py | https://github.com/jax-ml/jax/blob/master/jax/_src/debugger/cli_debugger.py | Apache-2.0 |
def do_pp(self, arg):
"""pp expression
Evaluates and pretty-prints the value of an expression
"""
try:
print(pprint.pformat(self.evaluate(arg)), file=self.stdout)
except:
self._error_message() | pp expression
Evaluates and pretty-prints the value of an expression
| do_pp | python | jax-ml/jax | jax/_src/debugger/cli_debugger.py | https://github.com/jax-ml/jax/blob/master/jax/_src/debugger/cli_debugger.py | Apache-2.0 |
def update_code(self, code_, highlights, *, linenostart: int = 1):
"""Updates the code viewer to use new code."""
self._code = code_
self._view.clear()
code_, css_ = self._highlight_code(self._code, highlights, linenostart)
uuid_ = uuid.uuid4()
code_div = colab_lib.div(
colab_lib.css(css... | Updates the code viewer to use new code. | update_code | python | jax-ml/jax | jax/_src/debugger/colab_debugger.py | https://github.com/jax-ml/jax/blob/master/jax/_src/debugger/colab_debugger.py | Apache-2.0 |
def update_frame(self, frame):
"""Updates the frame viewer to use a new frame."""
self.frame = frame
lineno = self.frame.lineno or None
filename = self.frame.filename.strip()
if inspect.getmodulename(filename):
if filename not in self._file_cache:
try:
with open(filename) as ... | Updates the frame viewer to use a new frame. | update_frame | python | jax-ml/jax | jax/_src/debugger/colab_debugger.py | https://github.com/jax-ml/jax/blob/master/jax/_src/debugger/colab_debugger.py | Apache-2.0 |
def breakpoint(*, backend: str | None = None, filter_frames: bool = True,
num_frames: int | None = None, ordered: bool = False,
token = None, **kwargs): # pylint: disable=redefined-builtin
"""Enters a breakpoint at a point in a program.
Args:
backend: The debugger backend to use.... | Enters a breakpoint at a point in a program.
Args:
backend: The debugger backend to use. By default, picks the highest priority
debugger and in the absence of other registered debuggers, falls back to
the CLI debugger.
filter_frames: Whether or not to filter out JAX-internal stack frames from
... | breakpoint | python | jax-ml/jax | jax/_src/debugger/core.py | https://github.com/jax-ml/jax/blob/master/jax/_src/debugger/core.py | Apache-2.0 |
def serialize(exp: _export.Exported, vjp_order: int = 0) -> bytearray:
"""Serializes an Exported.
Args:
exp: the Exported to serialize.
vjp_order: The maximum vjp order to include. E.g., the value 2 means that we
serialize the primal functions and two orders of the `vjp` function. This
should a... | Serializes an Exported.
Args:
exp: the Exported to serialize.
vjp_order: The maximum vjp order to include. E.g., the value 2 means that we
serialize the primal functions and two orders of the `vjp` function. This
should allow 2nd order reverse mode differentiation of the deserialized
functi... | serialize | python | jax-ml/jax | jax/_src/export/serialization.py | https://github.com/jax-ml/jax/blob/master/jax/_src/export/serialization.py | Apache-2.0 |
def _syntactic_cmp(self, other: _DimFactor) -> int:
"""Returns -1 if self < other, 0 if self == other, 1 if self > other.
The comparison is done lexicographically (syntactic), to be used for sorting.
The result is not related to the semantic value.
"""
if c := cmp_comparable(self._size, other._size)... | Returns -1 if self < other, 0 if self == other, 1 if self > other.
The comparison is done lexicographically (syntactic), to be used for sorting.
The result is not related to the semantic value.
| _syntactic_cmp | python | jax-ml/jax | jax/_src/export/shape_poly.py | https://github.com/jax-ml/jax/blob/master/jax/_src/export/shape_poly.py | Apache-2.0 |
def to_var(self) -> str | None:
"""Extract the variable name from a term.
Return None if the term is not a single variable."""
a = self.to_factor()
return a.to_var() if a is not None else None | Extract the variable name from a term.
Return None if the term is not a single variable. | to_var | python | jax-ml/jax | jax/_src/export/shape_poly.py | https://github.com/jax-ml/jax/blob/master/jax/_src/export/shape_poly.py | Apache-2.0 |
def to_factor(self) -> _DimFactor | None:
"""Extract the single factor from a term.
Return None if the term is not a single factor."""
if len(self._factors) > 1: return None
(f, f_exp), = self._factors
if f_exp != 1: return None
return f | Extract the single factor from a term.
Return None if the term is not a single factor. | to_factor | python | jax-ml/jax | jax/_src/export/shape_poly.py | https://github.com/jax-ml/jax/blob/master/jax/_src/export/shape_poly.py | Apache-2.0 |
def mul(self, other: _DimTerm) -> _DimTerm:
"""
Returns the product with another term. Example: (n^2*m) * n == n^3 * m.
"""
return _DimTerm(_DimExpr._linear_combination_sorted_pairs(self._factors, 0, 1,
other._factors, 0, 1)) |
Returns the product with another term. Example: (n^2*m) * n == n^3 * m.
| mul | python | jax-ml/jax | jax/_src/export/shape_poly.py | https://github.com/jax-ml/jax/blob/master/jax/_src/export/shape_poly.py | Apache-2.0 |
def divide(self, divisor: _DimTerm) -> _DimTerm:
"""
Divides by another term. Raises a InconclusiveDimensionOperation
if the result is not a term.
For example, (n^3 * m) // n == n^2*m, but n // m fails.
"""
new_factors = _DimExpr._linear_combination_sorted_pairs(self._factors, 0, 1,
... |
Divides by another term. Raises a InconclusiveDimensionOperation
if the result is not a term.
For example, (n^3 * m) // n == n^2*m, but n // m fails.
| divide | python | jax-ml/jax | jax/_src/export/shape_poly.py | https://github.com/jax-ml/jax/blob/master/jax/_src/export/shape_poly.py | Apache-2.0 |
def _to_single_term(self) -> tuple[int, int, _DimTerm] | None:
"""Extracts the single term: k + c * term.
Returns None if the expression is not a single term, or (k, c, term)
"""
n1 = 0
n2 = 0
term = None
for t, t_k in self._sorted_terms:
if t.is_constant:
n1 = t_k
cont... | Extracts the single term: k + c * term.
Returns None if the expression is not a single term, or (k, c, term)
| _to_single_term | python | jax-ml/jax | jax/_src/export/shape_poly.py | https://github.com/jax-ml/jax/blob/master/jax/_src/export/shape_poly.py | Apache-2.0 |
def _normalize_sorted_terms(terms: SortedTerms,
scope: SymbolicScope) -> DimSize:
"""Constructs a _DimExpr in normal form from sorted terms.
Ensures that the symbolic dimension is normalized, e.g., does not
have terms with coefficient 0, it reflects all the scope
normaliza... | Constructs a _DimExpr in normal form from sorted terms.
Ensures that the symbolic dimension is normalized, e.g., does not
have terms with coefficient 0, it reflects all the scope
normalization_rules, and it is represented as a Python integer if it is
known to be a constant.
Does not attempt to nor... | _normalize_sorted_terms | python | jax-ml/jax | jax/_src/export/shape_poly.py | https://github.com/jax-ml/jax/blob/master/jax/_src/export/shape_poly.py | Apache-2.0 |
def _to_term(self) -> _DimTerm | None:
"""Extract the single term from a symbolic expression.
Returns None if the expression is not a single term."""
if len(self._sorted_terms) > 1: return None
(t, t_k), = self._sorted_terms
return t if t_k == 1 else None | Extract the single term from a symbolic expression.
Returns None if the expression is not a single term. | _to_term | python | jax-ml/jax | jax/_src/export/shape_poly.py | https://github.com/jax-ml/jax/blob/master/jax/_src/export/shape_poly.py | Apache-2.0 |
def _to_factor(self) -> _DimFactor | None:
"""Extract the factor from a symbolic expression.
Returns None if the expression is not a single factor."""
t = self._to_term()
return t.to_factor() if t is not None else None | Extract the factor from a symbolic expression.
Returns None if the expression is not a single factor. | _to_factor | python | jax-ml/jax | jax/_src/export/shape_poly.py | https://github.com/jax-ml/jax/blob/master/jax/_src/export/shape_poly.py | Apache-2.0 |
def _to_var(self) -> str | None:
"""Extract the variable name from a symbolic expression.
Returns None if the expression is not a single variable."""
mon = self._to_factor()
return mon.to_var() if mon is not None else None | Extract the variable name from a symbolic expression.
Returns None if the expression is not a single variable. | _to_var | python | jax-ml/jax | jax/_src/export/shape_poly.py | https://github.com/jax-ml/jax/blob/master/jax/_src/export/shape_poly.py | Apache-2.0 |
def _to_constant(e: DimSize) -> int | None:
"""Extract the constant from a symbolic expression.
Returns None if the expression is not a single constant."""
if not isinstance(e, _DimExpr):
return int(e)
m, m_c = e._leading_term
return m_c if m.is_constant else None | Extract the constant from a symbolic expression.
Returns None if the expression is not a single constant. | _to_constant | python | jax-ml/jax | jax/_src/export/shape_poly.py | https://github.com/jax-ml/jax/blob/master/jax/_src/export/shape_poly.py | Apache-2.0 |
def _get_vars(self) -> set[str]:
"""The variables that appear in a symbolic dimension."""
acc = set()
for mon, _ in self._sorted_terms:
acc.update(mon.get_vars())
return acc | The variables that appear in a symbolic dimension. | _get_vars | python | jax-ml/jax | jax/_src/export/shape_poly.py | https://github.com/jax-ml/jax/blob/master/jax/_src/export/shape_poly.py | Apache-2.0 |
def _linear_combination_sorted_pairs(
pairs1, i1, f1,
pairs2, i2, f2):
"""Computes e1[i1:] * f1 + e2[i2:] * f2.
e1, e2, and the result are sorted with largest term first.
This is an optimization for a common operation. The unoptimized code would
compute each subexpression in turn. This work... | Computes e1[i1:] * f1 + e2[i2:] * f2.
e1, e2, and the result are sorted with largest term first.
This is an optimization for a common operation. The unoptimized code would
compute each subexpression in turn. This works for both SortedTerms and SortedFactors.
| _linear_combination_sorted_pairs | python | jax-ml/jax | jax/_src/export/shape_poly.py | https://github.com/jax-ml/jax/blob/master/jax/_src/export/shape_poly.py | Apache-2.0 |
def _divmod(self, divisor: DimSize) -> tuple[DimSize, int]:
"""
Floor division with remainder (divmod) generalized to expressions.
If the `divisor` is not a constant, the remainder must be 0.
If the `divisor` is a constant, the remainder may be non 0, for consistency
with integer divmod.
:retur... |
Floor division with remainder (divmod) generalized to expressions.
If the `divisor` is not a constant, the remainder must be 0.
If the `divisor` is a constant, the remainder may be non 0, for consistency
with integer divmod.
:return: Quotient resulting from polynomial division and integer remainde... | _divmod | python | jax-ml/jax | jax/_src/export/shape_poly.py | https://github.com/jax-ml/jax/blob/master/jax/_src/export/shape_poly.py | Apache-2.0 |
def _geq_decision(e1: DimSize, e2: DimSize, cmp_str: Callable[[], str]) -> bool:
"""Implements `e1 >= e2`.
Args:
e1, e2: the expressions to compare for greater-equal
cmp_str: a callable such that `cmp_str()` describes the comparison
for error messages, e.g., "a <= b". Without this all comparisons wou... | Implements `e1 >= e2`.
Args:
e1, e2: the expressions to compare for greater-equal
cmp_str: a callable such that `cmp_str()` describes the comparison
for error messages, e.g., "a <= b". Without this all comparisons would
be reported as ">=".
Raises InconclusiveDimensionOperation if the result i... | _geq_decision | python | jax-ml/jax | jax/_src/export/shape_poly.py | https://github.com/jax-ml/jax/blob/master/jax/_src/export/shape_poly.py | Apache-2.0 |
def _einsum_contract_path(*operands, **kwargs):
"""Like opt_einsum.contract_path, with support for DimExpr shapes.
We use opt_einsum.contract_path to compute the schedule, using a fixed
constant for all dimension variables. This is safe because we throw an
error if there are more than 1 contractions. Essential... | Like opt_einsum.contract_path, with support for DimExpr shapes.
We use opt_einsum.contract_path to compute the schedule, using a fixed
constant for all dimension variables. This is safe because we throw an
error if there are more than 1 contractions. Essentially, we just use
opt_einsum.contract_path to parse t... | _einsum_contract_path | python | jax-ml/jax | jax/_src/export/shape_poly.py | https://github.com/jax-ml/jax/blob/master/jax/_src/export/shape_poly.py | Apache-2.0 |
def shape_assertion(assert_what: jax.Array,
*error_message_inputs: jax.Array,
error_message: str) -> None:
"""Adds a shape assertion in the code.
Args:
assert_what: a boolean asserted to be true. Must be computed based only
on dimension expressions, so that it can ... | Adds a shape assertion in the code.
Args:
assert_what: a boolean asserted to be true. Must be computed based only
on dimension expressions, so that it can be evaluated after shape
refinement.
error_message_inputs: integers expressions whose values can be referenced
in the `error_message`. M... | shape_assertion | python | jax-ml/jax | jax/_src/export/shape_poly.py | https://github.com/jax-ml/jax/blob/master/jax/_src/export/shape_poly.py | Apache-2.0 |
def symbolic_shape(shape_spec: str | None,
*,
constraints: Sequence[str] = (),
scope: SymbolicScope | None = None,
like: Sequence[int | None] | None = None
) -> Sequence[DimSize]:
"""Constructs a symbolic shape from a strin... | Constructs a symbolic shape from a string representation.
See https://docs.jax.dev/en/latest/export/shape_poly.html for examples.
Args:
shape_spec: a symbolic shape specification. None stands for "...".
A shape specification is the string representation of a tuple (the
parentheses are optional) wi... | symbolic_shape | python | jax-ml/jax | jax/_src/export/shape_poly.py | https://github.com/jax-ml/jax/blob/master/jax/_src/export/shape_poly.py | Apache-2.0 |
def symbolic_args_specs(
args, # pytree of arguments
shapes_specs, # prefix pytree of strings
constraints: Sequence[str] = (),
scope: SymbolicScope | None = None,
):
"""Constructs a pytree of jax.ShapeDtypeSpec arguments specs for `export`.
See the documentation of :func:`jax.export.symbolic_shap... | Constructs a pytree of jax.ShapeDtypeSpec arguments specs for `export`.
See the documentation of :func:`jax.export.symbolic_shape` and
the [shape polymorphism documentation](https://docs.jax.dev/en/latest/export/shape_poly.html) for details.
Args:
args: a pytree of arguments. These can be jax.Array, or jax.... | symbolic_args_specs | python | jax-ml/jax | jax/_src/export/shape_poly.py | https://github.com/jax-ml/jax/blob/master/jax/_src/export/shape_poly.py | Apache-2.0 |
def shape_and_dtype_jax_array(a) -> tuple[Sequence[int | None], DType]:
"""Returns the shape and dtype of a jax.Array or a j"""
if isinstance(a, jax.ShapeDtypeStruct):
return a.shape, a.dtype
aval = core.get_aval(a)
return aval.shape, aval.dtype | Returns the shape and dtype of a jax.Array or a j | shape_and_dtype_jax_array | python | jax-ml/jax | jax/_src/export/shape_poly.py | https://github.com/jax-ml/jax/blob/master/jax/_src/export/shape_poly.py | Apache-2.0 |
def compute(self, eval: ShapeEvaluator) -> jax.Array | None:
"""Computes if the constraint is satisfied.
If the constraint can be resolved statically returns None
or raises ValueError otherwise. If the constraint cannot be
resolved statically, returns a value representing if the
constraint is satis... | Computes if the constraint is satisfied.
If the constraint can be resolved statically returns None
or raises ValueError otherwise. If the constraint cannot be
resolved statically, returns a value representing if the
constraint is satisfied.
| compute | python | jax-ml/jax | jax/_src/export/shape_poly.py | https://github.com/jax-ml/jax/blob/master/jax/_src/export/shape_poly.py | Apache-2.0 |
def shape_assertions(self, eval: ShapeEvaluator) -> None:
"""Computes the shape assertions for the set of constraints.
See jax_export.Exported docstring.
"""
# We want to report the errors in the same order as `check_statically`.
# So, we process them in order, in case some fail statically, and we
... | Computes the shape assertions for the set of constraints.
See jax_export.Exported docstring.
| shape_assertions | python | jax-ml/jax | jax/_src/export/shape_poly.py | https://github.com/jax-ml/jax/blob/master/jax/_src/export/shape_poly.py | Apache-2.0 |
def solve_dim_vars(
args_avals: Sequence[core.ShapedArray],
args_kwargs_tree: tree_util.PyTreeDef,
) -> tuple[DimVarEnv, ShapeConstraints, Sequence[tuple[str, int, int]]]:
"""Solves dimension variables in a called function's avals in terms of actual argument shapes.
For example, given:
args_avals... | Solves dimension variables in a called function's avals in terms of actual argument shapes.
For example, given:
args_avals = [ShapedArray((3, a, a + b), f32)]
we introduce fresh "synthetic" dimension variables to represent the actual
dimension size of actual arguments for each non-constant dimension.
Ea... | solve_dim_vars | python | jax-ml/jax | jax/_src/export/shape_poly.py | https://github.com/jax-ml/jax/blob/master/jax/_src/export/shape_poly.py | Apache-2.0 |
def compute_dim_vars_from_arg_shapes(
args_avals: Sequence[core.ShapedArray],
*actual_args: jax.Array,
args_kwargs_tree: tree_util.PyTreeDef) -> Sequence[jax.Array]:
"""Computes values of dimension variables to unify args_avals with actual arguments.
Like `solve_dim_vars` except that here we express th... | Computes values of dimension variables to unify args_avals with actual arguments.
Like `solve_dim_vars` except that here we express the solution as
JAX arrays that reference the `actual_args`. This function can be used to
generate the code for computing the dimension variables. It also generates
the shape asse... | compute_dim_vars_from_arg_shapes | python | jax-ml/jax | jax/_src/export/shape_poly.py | https://github.com/jax-ml/jax/blob/master/jax/_src/export/shape_poly.py | Apache-2.0 |
def build(scope: SymbolicScope) -> _DecisionByElimination:
"""Builds an initialized DecisionByElimination for a scope.
Caches the initial state of the decision procedure in the scope.
"""
if not scope._initialized or not scope._explicit_constraints:
# We do not cache until the scope is fully init... | Builds an initialized DecisionByElimination for a scope.
Caches the initial state of the decision procedure in the scope.
| build | python | jax-ml/jax | jax/_src/export/shape_poly_decision.py | https://github.com/jax-ml/jax/blob/master/jax/_src/export/shape_poly_decision.py | Apache-2.0 |
def combine_and_add_constraint(self,
cmp: Comparator,
e1: _DimExpr | int | float,
e2: _DimExpr | int | float,
debug_str: str | None = None):
"""Adds a constraint "e1 >= e2" to the inte... | Adds a constraint "e1 >= e2" to the internal state. | combine_and_add_constraint | python | jax-ml/jax | jax/_src/export/shape_poly_decision.py | https://github.com/jax-ml/jax/blob/master/jax/_src/export/shape_poly_decision.py | Apache-2.0 |
def add_to_state(self,
cmp: Comparator,
e: _DimExpr,
debug_str: str | None):
"""Updates the internal state to reflect "e >= 0". """
assert _DimExpr._to_constant(e) is None
if (term_factors := e._to_single_term()) is not None:
n, t_k, t = term_f... | Updates the internal state to reflect "e >= 0". | add_to_state | python | jax-ml/jax | jax/_src/export/shape_poly_decision.py | https://github.com/jax-ml/jax/blob/master/jax/_src/export/shape_poly_decision.py | Apache-2.0 |
def combine_term_with_existing(self, t: _DimTerm, t_k: int, *,
scope: shape_poly.SymbolicScope,
only_smaller_than_t=True,
) -> Sequence[tuple[Comparator,
_DimExpr,
... |
Combine a term with existing constraints.
For input (t, t_k) the tuple (c_eq, c, c_s, t_s) is among the returned
tuples if there exists a constraint `c =[c_eq] 0` that can be combined
with `t*t_k` to eliminate `t`, and:
* `c =[c_eq] 0`
* The term `comb = t*t_k*t_s + c*c_s` does not contain... | combine_term_with_existing | python | jax-ml/jax | jax/_src/export/shape_poly_decision.py | https://github.com/jax-ml/jax/blob/master/jax/_src/export/shape_poly_decision.py | Apache-2.0 |
def bounds(self, e: DimSize,
prec: BoundsPrecision,
add_implicit_constraints: bool = False
) -> tuple[float, float]:
"""Returns the lower and upper bounds, or -+inf.
Args:
e: the expression for which to compute the bounds.
prec: the desired precision. See comm... | Returns the lower and upper bounds, or -+inf.
Args:
e: the expression for which to compute the bounds.
prec: the desired precision. See comments in `BoundsPrecision`.
add_implicit_constraints: if True, then before computing the bounds
add the implicit constraints for the terms inside `e`.... | bounds | python | jax-ml/jax | jax/_src/export/shape_poly_decision.py | https://github.com/jax-ml/jax/blob/master/jax/_src/export/shape_poly_decision.py | Apache-2.0 |
def _bounds_for_sorted_terms(self,
scope: SymbolicScope,
e: Sequence[tuple[_DimTerm, int]],
i: int,
prec: BoundsPrecision) -> tuple[float, float]:
"""The lower and upper bounds of e[i:].
... | The lower and upper bounds of e[i:].
See comments about soundness and `cmp_with` in the `shape_poly.bounds_decision`` method.
Returns (lower-bound, upper-bound)
| _bounds_for_sorted_terms | python | jax-ml/jax | jax/_src/export/shape_poly_decision.py | https://github.com/jax-ml/jax/blob/master/jax/_src/export/shape_poly_decision.py | Apache-2.0 |
def add_implicit_constraints_expr(self, e: _DimExpr):
"""Adds the implicit constraints for the expression `e`"""
for t, _ in e._sorted_terms:
if t.is_constant: continue
self.add_implicit_constraints_term(t) | Adds the implicit constraints for the expression `e` | add_implicit_constraints_expr | python | jax-ml/jax | jax/_src/export/shape_poly_decision.py | https://github.com/jax-ml/jax/blob/master/jax/_src/export/shape_poly_decision.py | Apache-2.0 |
def is_custom_call(self) -> str | None:
"""Returns the custom call target allowed by this directive."""
m = re.match(r'custom_call:(.+)$', self._impl)
return m.group(1) if m else None | Returns the custom call target allowed by this directive. | is_custom_call | python | jax-ml/jax | jax/_src/export/_export.py | https://github.com/jax-ml/jax/blob/master/jax/_src/export/_export.py | Apache-2.0 |
def in_shardings_jax(
self,
mesh: sharding.Mesh) -> Sequence[sharding.Sharding | None]:
"""Creates Shardings corresponding to self.in_shardings_hlo.
The Exported object stores `in_shardings_hlo` as HloShardings, which are
independent of a mesh or set of devices. This method constructs
Sharding ... | Creates Shardings corresponding to self.in_shardings_hlo.
The Exported object stores `in_shardings_hlo` as HloShardings, which are
independent of a mesh or set of devices. This method constructs
Sharding that can be used in JAX APIs such as `jax.jit` or
`jax.device_put`.
Example usage:
>>> ... | in_shardings_jax | python | jax-ml/jax | jax/_src/export/_export.py | https://github.com/jax-ml/jax/blob/master/jax/_src/export/_export.py | Apache-2.0 |
def out_shardings_jax(
self,
mesh: sharding.Mesh) -> Sequence[sharding.Sharding | None]:
"""Creates Shardings corresponding to `self.out_shardings_hlo`.
See documentation for in_shardings_jax.
"""
return tuple(_hlo_sharding_to_named_sharding(s, mesh)
for s in self.out_shard... | Creates Shardings corresponding to `self.out_shardings_hlo`.
See documentation for in_shardings_jax.
| out_shardings_jax | python | jax-ml/jax | jax/_src/export/_export.py | https://github.com/jax-ml/jax/blob/master/jax/_src/export/_export.py | Apache-2.0 |
def vjp(self) -> Exported:
"""Gets the exported VJP.
Returns None if not available, which can happen if the Exported has been
loaded from an external format without a VJP.
"""
if self._get_vjp is None:
raise ValueError("No VJP is available")
return self._get_vjp(self) | Gets the exported VJP.
Returns None if not available, which can happen if the Exported has been
loaded from an external format without a VJP.
| vjp | python | jax-ml/jax | jax/_src/export/_export.py | https://github.com/jax-ml/jax/blob/master/jax/_src/export/_export.py | Apache-2.0 |
def serialize(self,
vjp_order: int = 0) -> bytearray:
"""Serializes an Exported.
Args:
vjp_order: The maximum vjp order to include. E.g., the value 2 means that we
serialize the primal functions and two orders of the `vjp` function. This
should allow 2nd order reverse mode... | Serializes an Exported.
Args:
vjp_order: The maximum vjp order to include. E.g., the value 2 means that we
serialize the primal functions and two orders of the `vjp` function. This
should allow 2nd order reverse mode differentiation of the deserialized
function. i.e., `jax.grad(jax.gr... | serialize | python | jax-ml/jax | jax/_src/export/_export.py | https://github.com/jax-ml/jax/blob/master/jax/_src/export/_export.py | Apache-2.0 |
def deserialize(blob: bytearray) -> Exported:
"""Deserializes an Exported.
Args:
blob: a bytearray obtained from `Exported.serialize`.
"""
# Lazy load the serialization module, since flatbuffers is an optional
# dependency.
from jax._src.export.serialization import deserialize
return deserialize(blob... | Deserializes an Exported.
Args:
blob: a bytearray obtained from `Exported.serialize`.
| deserialize | python | jax-ml/jax | jax/_src/export/_export.py | https://github.com/jax-ml/jax/blob/master/jax/_src/export/_export.py | Apache-2.0 |
def __call__(self, aux_data: PyTreeAuxData) -> bytes:
"""Serializes the PyTree node AuxData.
The AuxData is returned by the `flatten_func` registered by
`tree_util.register_pytree_node`).
""" | Serializes the PyTree node AuxData.
The AuxData is returned by the `flatten_func` registered by
`tree_util.register_pytree_node`).
| __call__ | python | jax-ml/jax | jax/_src/export/_export.py | https://github.com/jax-ml/jax/blob/master/jax/_src/export/_export.py | Apache-2.0 |
def __call__(self, serialized_aux_data: bytes) -> PyTreeAuxData:
"""Deserializes the PyTree node AuxData.
The result will be passed to `_BuildFromChildren`.
""" | Deserializes the PyTree node AuxData.
The result will be passed to `_BuildFromChildren`.
| __call__ | python | jax-ml/jax | jax/_src/export/_export.py | https://github.com/jax-ml/jax/blob/master/jax/_src/export/_export.py | Apache-2.0 |
def __call__(self, aux_data: PyTreeAuxData, children: Sequence[Any]) -> Any:
"""Materializes a T given a deserialized AuxData and children.
This is similar in scope with the `unflatten_func`.
""" | Materializes a T given a deserialized AuxData and children.
This is similar in scope with the `unflatten_func`.
| __call__ | python | jax-ml/jax | jax/_src/export/_export.py | https://github.com/jax-ml/jax/blob/master/jax/_src/export/_export.py | Apache-2.0 |
def register_pytree_node_serialization(
nodetype: type[T],
*,
serialized_name: str,
serialize_auxdata: _SerializeAuxData,
deserialize_auxdata: _DeserializeAuxData,
from_children: _BuildFromChildren | None = None
) -> type[T]:
"""Registers a custom PyTree node for serialization and deserializat... | Registers a custom PyTree node for serialization and deserialization.
You must use this function before you can serialize and deserialize PyTree
nodes for the types not supported natively. We serialize PyTree nodes for
the `in_tree` and `out_tree` fields of `Exported`, which are part of the
exported function's... | register_pytree_node_serialization | python | jax-ml/jax | jax/_src/export/_export.py | https://github.com/jax-ml/jax/blob/master/jax/_src/export/_export.py | Apache-2.0 |
def register_namedtuple_serialization(
nodetype: type[T],
*,
serialized_name: str) -> type[T]:
"""Registers a namedtuple for serialization and deserialization.
JAX has native PyTree support for `collections.namedtuple`, and does not
require a call to `jax.tree_util.register_pytree_node`. However, if ... | Registers a namedtuple for serialization and deserialization.
JAX has native PyTree support for `collections.namedtuple`, and does not
require a call to `jax.tree_util.register_pytree_node`. However, if you
want to serialize functions that have inputs of outputs of a
namedtuple type, you must register that typ... | register_namedtuple_serialization | python | jax-ml/jax | jax/_src/export/_export.py | https://github.com/jax-ml/jax/blob/master/jax/_src/export/_export.py | Apache-2.0 |
def _export_internal(
fun_jit: stages.Wrapped,
*,
platforms: Sequence[str] | None = None,
disabled_checks: Sequence[DisabledSafetyCheck] = (),
_device_assignment_for_internal_jax2tf_use_only=None,
override_lowering_rules=None,
) -> Callable[..., Exported]:
"""Exports native serialization f... | Exports native serialization for a JAX function.
Note: this function exists only for internal usage by jax2tf. Use
`jax.export` instead.
See https://docs.jax.dev/en/latest/export/export.html
See docstring of `export` for more details.
| _export_internal | python | jax-ml/jax | jax/_src/export/_export.py | https://github.com/jax-ml/jax/blob/master/jax/_src/export/_export.py | Apache-2.0 |
def _wrap_main_func(
module: ir.Module,
args_avals_flat: Sequence[core.ShapedArray],
*,
args_kwargs_tree: tree_util.PyTreeDef,
has_platform_index_argument: bool,
module_kept_var_idx: tuple[int, ...],
serialization_version: int
) -> ir.Module:
"""Wraps the lowered module with a new "main" h... | Wraps the lowered module with a new "main" handling dimension arguments.
See calling convention documentation https://docs.jax.dev/en/latest/export/export.html#module-calling-convention.
Args:
module: a copy of HLO module as obtained from lowering.
args_avals_flat: the avals for all the arguments of the l... | _wrap_main_func | python | jax-ml/jax | jax/_src/export/_export.py | https://github.com/jax-ml/jax/blob/master/jax/_src/export/_export.py | Apache-2.0 |
def _check_module(mod: ir.Module, *,
disabled_checks: Sequence[DisabledSafetyCheck],
shardy_enabled: bool) -> bool:
"""Run a number of checks on the module.
Args:
disabled_checks: the safety checks that are disabled.
Returns True if the module uses non-replicated sharding... | Run a number of checks on the module.
Args:
disabled_checks: the safety checks that are disabled.
Returns True if the module uses non-replicated shardings.
| _check_module | python | jax-ml/jax | jax/_src/export/_export.py | https://github.com/jax-ml/jax/blob/master/jax/_src/export/_export.py | Apache-2.0 |
def expand_in_shardings(in_shardings: Sequence[LoweringSharding],
module_kept_var_idx: Sequence[int],
nr_inputs: int) -> Sequence[LoweringSharding]:
"""Expands in_shardings with unspecified shardings for inputs not kept.
Assumes in_shardings corresponds to module_kep... | Expands in_shardings with unspecified shardings for inputs not kept.
Assumes in_shardings corresponds to module_kept_var_idx.
| expand_in_shardings | python | jax-ml/jax | jax/_src/export/_export.py | https://github.com/jax-ml/jax/blob/master/jax/_src/export/_export.py | Apache-2.0 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.