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 is_equivalent_to(self: Sharding, other: Sharding, ndim: int) -> bool: """Returns ``True`` if two shardings are equivalent. Two shardings are equivalent if they place the same logical array shards on the same devices. """ try: return (are_op_shardings_equal(self._to_xla_hlo_sharding(ndim),...
Returns ``True`` if two shardings are equivalent. Two shardings are equivalent if they place the same logical array shards on the same devices.
is_equivalent_to
python
jax-ml/jax
jax/_src/sharding.py
https://github.com/jax-ml/jax/blob/master/jax/_src/sharding.py
Apache-2.0
def unflatten_array(named_sizes, assignment): """Recovers the ordering of axis names based on a device assignment. The device assignments that this function can convert into axis orders are of the form:: np.arange(np.prod(named_sizes.values())).transpose(...).flatten() for some transposition ``...``. Thi...
Recovers the ordering of axis names based on a device assignment. The device assignments that this function can convert into axis orders are of the form:: np.arange(np.prod(named_sizes.values())).transpose(...).flatten() for some transposition ``...``. This is satisfied by all OpSharding assignments gene...
unflatten_array
python
jax-ml/jax
jax/_src/sharding_impls.py
https://github.com/jax-ml/jax/blob/master/jax/_src/sharding_impls.py
Apache-2.0
def unflatten_superdims(assignment): """Unflatten a list of dimension sizes and their strides that generates assignment. If this function succeeds for a given ``assignment``, then the following property should be satisfied:: dims_with_strides = unflatten_superdims(assignment) base_array = np.arange(map(...
Unflatten a list of dimension sizes and their strides that generates assignment. If this function succeeds for a given ``assignment``, then the following property should be satisfied:: dims_with_strides = unflatten_superdims(assignment) base_array = np.arange(map(fst, sorted(dims_with_strides, key=snd, re...
unflatten_superdims
python
jax-ml/jax
jax/_src/sharding_impls.py
https://github.com/jax-ml/jax/blob/master/jax/_src/sharding_impls.py
Apache-2.0
def explode_superdims(sizes, dims): """Explode superdims to fit a known shape. The unflattening process might mistakenly generate too few too large dimensions. For example, ``unflatten_superdims(np.arange(n))`` always returns ``[(n, 1)]``. This function takes a list of such contiguous super-dimensions and spli...
Explode superdims to fit a known shape. The unflattening process might mistakenly generate too few too large dimensions. For example, ``unflatten_superdims(np.arange(n))`` always returns ``[(n, 1)]``. This function takes a list of such contiguous super-dimensions and splits them into smaller dimensions such th...
explode_superdims
python
jax-ml/jax
jax/_src/sharding_impls.py
https://github.com/jax-ml/jax/blob/master/jax/_src/sharding_impls.py
Apache-2.0
def get_process_index_and_count( tensor_sharding: jsharding.Sharding, dim: int, ndims: int) -> tuple[int, int]: """Get current process index and number of unique processes for given dimension. This function facilitates mapping of process-level data to individual devices. Each process can use its index to obt...
Get current process index and number of unique processes for given dimension. This function facilitates mapping of process-level data to individual devices. Each process can use its index to obtain the data corresponding to that index. If process level data is sharded on multiple dimensions this function can b...
get_process_index_and_count
python
jax-ml/jax
jax/_src/sharding_impls.py
https://github.com/jax-ml/jax/blob/master/jax/_src/sharding_impls.py
Apache-2.0
def local_to_global_shape( sharding: jsharding.Sharding, local_shape: Shape) -> tuple[int | None, ...]: """Computes the global shape given the per process if possible. The returned shape will have the size of the global tensor in that dimension or None, if it is not computable. The latter can happen when sha...
Computes the global shape given the per process if possible. The returned shape will have the size of the global tensor in that dimension or None, if it is not computable. The latter can happen when sharding is not uniform along that dimension, e.g. different hosts require different shapes, or if different pro...
local_to_global_shape
python
jax-ml/jax
jax/_src/sharding_impls.py
https://github.com/jax-ml/jax/blob/master/jax/_src/sharding_impls.py
Apache-2.0
def num_addressable_indices( tensor_sharding: jsharding.Sharding, dim: int, global_shape: Shape) -> int: """Returns the number of indices for given dimension this host has access to. Each host can have multiple number of devices that are spanning possibly discontiguous slices of data. This function computes ...
Returns the number of indices for given dimension this host has access to. Each host can have multiple number of devices that are spanning possibly discontiguous slices of data. This function computes the total number of unique indices for dimension `dim` that any of its addressable devices hold. In most ca...
num_addressable_indices
python
jax-ml/jax
jax/_src/sharding_impls.py
https://github.com/jax-ml/jax/blob/master/jax/_src/sharding_impls.py
Apache-2.0
def make_mesh(axis_shapes: Sequence[int], axis_names: Sequence[str], *, devices: Sequence[xc.Device] | None = None, axis_types: tuple[mesh_lib.AxisType, ...] | None = None ) -> mesh_lib.Mesh: """Creates an efficient mesh with the shape and axis names specified. This functi...
Creates an efficient mesh with the shape and axis names specified. This function attempts to automatically compute a good mapping from a set of logical axes to a physical mesh. For example, on a TPU v3 with 8 devices: >>> mesh = jax.make_mesh((8,), ('x')) # doctest: +SKIP >>> [d.id for d in mesh.devices.flat...
make_mesh
python
jax-ml/jax
jax/_src/sharding_impls.py
https://github.com/jax-ml/jax/blob/master/jax/_src/sharding_impls.py
Apache-2.0
def set_mesh(mesh: mesh_lib.Mesh | None) -> mesh_lib.Mesh | None: """Sets the given concrete mesh globally and returns the previous concrete mesh.""" if mesh is not None and not isinstance(mesh, mesh_lib.Mesh): raise ValueError( f"Expected mesh of type `jax.sharding.Mesh`. Got {type(mesh)}") asse...
Sets the given concrete mesh globally and returns the previous concrete mesh.
set_mesh
python
jax-ml/jax
jax/_src/sharding_impls.py
https://github.com/jax-ml/jax/blob/master/jax/_src/sharding_impls.py
Apache-2.0
def _sharding_spec_indices(self, shape: tuple[int, ...]) -> np.ndarray: """Returns NumPy-style indices corresponding to a sharding spec. Args: shape: The shape of the logical array being sharded. Returns: An ndarray with the same shape as the logical mesh (as derived form `mesh_mapping`). Each entry...
Returns NumPy-style indices corresponding to a sharding spec. Args: shape: The shape of the logical array being sharded. Returns: An ndarray with the same shape as the logical mesh (as derived form `mesh_mapping`). Each entry is a NumPy-style index selecting the subset of the data array to be plac...
_sharding_spec_indices
python
jax-ml/jax
jax/_src/sharding_specs.py
https://github.com/jax-ml/jax/blob/master/jax/_src/sharding_specs.py
Apache-2.0
def spec_to_indices(shape: Sequence[int], spec: ShardingSpec) -> tuple[Index, ...]: """Returns numpy-style indices corresponding to a sharding spec. Each index describes a shard of the array. The order of the indices is the same as the device_buffers of a Array sharded using PmapSharding (i.e...
Returns numpy-style indices corresponding to a sharding spec. Each index describes a shard of the array. The order of the indices is the same as the device_buffers of a Array sharded using PmapSharding (i.e. the data is laid out row-major). Args: shape: The shape of the logical array being sharded. sp...
spec_to_indices
python
jax-ml/jax
jax/_src/sharding_specs.py
https://github.com/jax-ml/jax/blob/master/jax/_src/sharding_specs.py
Apache-2.0
def pmap_sharding_spec(nrep, axis_size, sharded_shape: Sequence[int], map_axis: int | None) -> ShardingSpec: """Sharding spec for arguments or results of a pmap. Args: nrep: number of local XLA replicas (product of local axis sizes) axis_size: local axis size for outer pmap sharde...
Sharding spec for arguments or results of a pmap. Args: nrep: number of local XLA replicas (product of local axis sizes) axis_size: local axis size for outer pmap sharded_aval: the aval of the value inside the outer pmap, an instance of a ShapedArray. map_axis: the axis along which the value is ...
pmap_sharding_spec
python
jax-ml/jax
jax/_src/sharding_specs.py
https://github.com/jax-ml/jax/blob/master/jax/_src/sharding_specs.py
Apache-2.0
def shard_map(f=None, /, *, out_specs: Specs, axis_names: Set[AxisName] = set(), in_specs: Specs | None = None, mesh: Mesh | AbstractMesh | None = None, check_vma: bool = True): """Map a function over shards of data using a mesh of devices. See the docs at https://docs.jax.dev/en/latest...
Map a function over shards of data using a mesh of devices. See the docs at https://docs.jax.dev/en/latest/notebooks/shard_map.html. Args: f: callable to be mapped. Each application of ``f``, or "instance" of ``f``, takes as input a shard of the mapped-over arguments and produces a shard of the ou...
shard_map
python
jax-ml/jax
jax/_src/shard_map.py
https://github.com/jax-ml/jax/blob/master/jax/_src/shard_map.py
Apache-2.0
def decode_vlq(enc: Iterable[int]) -> int: """Decode a Base-64-VLQ into an integer.""" enc_iter = iter(enc) d = VLQ_DECODE_TABLE[next(enc_iter)] sign = bool(d & VLQ_SIGN_MASK) value = (d & VLQ_VALUE_MASK) >> 1 # Compensate for first quantum containing sign as LSB: shift = -1 while d & VLQ_MORE_MASK: ...
Decode a Base-64-VLQ into an integer.
decode_vlq
python
jax-ml/jax
jax/_src/sourcemap.py
https://github.com/jax-ml/jax/blob/master/jax/_src/sourcemap.py
Apache-2.0
def encode_vlq(value: int) -> bytes: """Encode an integer into a Base-64-VLQ.""" # Move sign to LSB value = ((-value) << 1 | 1) if value < 0 else value << 1 buf = [] while True: d = value & VLQ_VALUE_MASK value >>= VLQ_VALUE_BITWIDTH more = value > 0 if more: d |= VLQ_MORE_MASK buf....
Encode an integer into a Base-64-VLQ.
encode_vlq
python
jax-ml/jax
jax/_src/sourcemap.py
https://github.com/jax-ml/jax/blob/master/jax/_src/sourcemap.py
Apache-2.0
def decode_segment(enc: Iterable[int]) -> Segment: """Decode a sequence of VLQs into a segment.""" enc_iter = iter(enc) col = decode_vlq(enc_iter) try: source = decode_vlq(enc_iter) except StopIteration: # Stopping here is fine (1-segment). return (col,) source_line = decode_vlq(enc_iter) sour...
Decode a sequence of VLQs into a segment.
decode_segment
python
jax-ml/jax
jax/_src/sourcemap.py
https://github.com/jax-ml/jax/blob/master/jax/_src/sourcemap.py
Apache-2.0
def serialize_mappings(mappings: Mappings) -> str: """Encode mappings into a string of TC39 mapping data.""" enc = b";".join( b",".join(encode_segment(seg) for seg in segs) for segs in mappings ) return enc.decode("ascii")
Encode mappings into a string of TC39 mapping data.
serialize_mappings
python
jax-ml/jax
jax/_src/sourcemap.py
https://github.com/jax-ml/jax/blob/master/jax/_src/sourcemap.py
Apache-2.0
def new_segment(self, *seg): """Start a new source mapping segment in the current group. Args: *seg: A segment as in TC39, but all indices are absolute. See https://tc39.es/source-map/#mappings-structure for details. Raises: RuntimeError: If no current group exists. """ assert ...
Start a new source mapping segment in the current group. Args: *seg: A segment as in TC39, but all indices are absolute. See https://tc39.es/source-map/#mappings-structure for details. Raises: RuntimeError: If no current group exists.
new_segment
python
jax-ml/jax
jax/_src/sourcemap.py
https://github.com/jax-ml/jax/blob/master/jax/_src/sourcemap.py
Apache-2.0
def is_user_filename(filename: str) -> bool: """Heuristic that guesses the identity of the user's code in a stack trace.""" return (_include_path_regex().search(filename) is not None or _exclude_path_regex().search(filename) is None)
Heuristic that guesses the identity of the user's code in a stack trace.
is_user_filename
python
jax-ml/jax
jax/_src/source_info_util.py
https://github.com/jax-ml/jax/blob/master/jax/_src/source_info_util.py
Apache-2.0
def user_frames(source_info: SourceInfo) -> Iterator[Frame]: """Iterator over the user's frames, filtering jax-internal frames.""" # Guess the user's frame is the innermost frame not in the jax source tree or # Python stdlib. We don't use traceback_util.path_starts_with because that # incurs filesystem access, ...
Iterator over the user's frames, filtering jax-internal frames.
user_frames
python
jax-ml/jax
jax/_src/source_info_util.py
https://github.com/jax-ml/jax/blob/master/jax/_src/source_info_util.py
Apache-2.0
def input_shardings(self) -> Sequence[sharding_lib.Sharding]: """Flat sequence of input shardings. May raise ``NotImplementedError`` if unavailable, e.g. based on backend, compiler, or runtime. """ raise NotImplementedError( "compiled executable carries no input sharding information")
Flat sequence of input shardings. May raise ``NotImplementedError`` if unavailable, e.g. based on backend, compiler, or runtime.
input_shardings
python
jax-ml/jax
jax/_src/stages.py
https://github.com/jax-ml/jax/blob/master/jax/_src/stages.py
Apache-2.0
def output_shardings(self) -> Sequence[sharding_lib.Sharding]: """Flat sequence of output shardings. May raise ``NotImplementedError`` if unavailable, e.g. based on backend, compiler, or runtime. """ raise NotImplementedError( "compiled executable carries no output sharding information")
Flat sequence of output shardings. May raise ``NotImplementedError`` if unavailable, e.g. based on backend, compiler, or runtime.
output_shardings
python
jax-ml/jax
jax/_src/stages.py
https://github.com/jax-ml/jax/blob/master/jax/_src/stages.py
Apache-2.0
def as_text(self) -> str: """A human-readable text representation of this executable. Intended for visualization and debugging purposes. This need not be a valid nor reliable serialization. It is relayed directly to external callers. May raise ``NotImplementedError`` if unavailable, e.g. based on back...
A human-readable text representation of this executable. Intended for visualization and debugging purposes. This need not be a valid nor reliable serialization. It is relayed directly to external callers. May raise ``NotImplementedError`` if unavailable, e.g. based on backend, compiler, or runtime. ...
as_text
python
jax-ml/jax
jax/_src/stages.py
https://github.com/jax-ml/jax/blob/master/jax/_src/stages.py
Apache-2.0
def cost_analysis(self) -> Any: """A summary of execution cost estimates. Intended for visualization and debugging purposes. The object output by this is some simple data structure that can easily be printed or serialized (e.g. nested dicts, lists, and tuples with numeric leaves). However, its stru...
A summary of execution cost estimates. Intended for visualization and debugging purposes. The object output by this is some simple data structure that can easily be printed or serialized (e.g. nested dicts, lists, and tuples with numeric leaves). However, its structure can be arbitrary: it need not be ...
cost_analysis
python
jax-ml/jax
jax/_src/stages.py
https://github.com/jax-ml/jax/blob/master/jax/_src/stages.py
Apache-2.0
def memory_analysis(self) -> Any: """A summary of estimated memory requirements. Intended for visualization and debugging purposes. The object output by this is some simple data structure that can easily be printed or serialized (e.g. nested dicts, lists, and tuples with numeric leaves). However, its ...
A summary of estimated memory requirements. Intended for visualization and debugging purposes. The object output by this is some simple data structure that can easily be printed or serialized (e.g. nested dicts, lists, and tuples with numeric leaves). However, its structure can be arbitrary: it need no...
memory_analysis
python
jax-ml/jax
jax/_src/stages.py
https://github.com/jax-ml/jax/blob/master/jax/_src/stages.py
Apache-2.0
def hlo(self) -> xc.XlaComputation: """Return an HLO representation of this computation.""" hlo = self.stablehlo() m: str | bytes m = mlir.module_to_bytecode(hlo) return _jax.mlir.mlir_module_to_xla_computation( m, use_tuple_args=self.compile_args["tuple_args"])
Return an HLO representation of this computation.
hlo
python
jax-ml/jax
jax/_src/stages.py
https://github.com/jax-ml/jax/blob/master/jax/_src/stages.py
Apache-2.0
def stablehlo(self) -> ir.Module: """Return a StableHLO representation of this computation.""" raise NotImplementedError( f"cost analysis unsupported on XLA computation: {type(self)}")
Return a StableHLO representation of this computation.
stablehlo
python
jax-ml/jax
jax/_src/stages.py
https://github.com/jax-ml/jax/blob/master/jax/_src/stages.py
Apache-2.0
def as_text(self, dialect: str | None = None, *, debug_info: bool = False) -> str: """A human-readable text representation of this lowering. Intended for visualization and debugging purposes. This need not be a valid nor reliable serialization. It is relayed directly to external...
A human-readable text representation of this lowering. Intended for visualization and debugging purposes. This need not be a valid nor reliable serialization. It is relayed directly to external callers.
as_text
python
jax-ml/jax
jax/_src/stages.py
https://github.com/jax-ml/jax/blob/master/jax/_src/stages.py
Apache-2.0
def compiler_ir(self, dialect: str | None = None) -> Any: """An arbitrary object representation of this lowering. Intended for debugging purposes. This need not be a valid nor reliable serialization. It is relayed directly to external callers, with no guarantee on type, structure, or consistency across...
An arbitrary object representation of this lowering. Intended for debugging purposes. This need not be a valid nor reliable serialization. It is relayed directly to external callers, with no guarantee on type, structure, or consistency across invocations. May raise ``NotImplementedError`` if unavailab...
compiler_ir
python
jax-ml/jax
jax/_src/stages.py
https://github.com/jax-ml/jax/blob/master/jax/_src/stages.py
Apache-2.0
def cost_analysis(self) -> Any: """A summary of execution cost estimates. Intended for visualization and debugging purposes. The object output by this is some simple data structure that can easily be printed or serialized (e.g. nested dicts, lists, and tuples with numeric leaves). However, its stru...
A summary of execution cost estimates. Intended for visualization and debugging purposes. The object output by this is some simple data structure that can easily be printed or serialized (e.g. nested dicts, lists, and tuples with numeric leaves). However, its structure can be arbitrary: it need not be ...
cost_analysis
python
jax-ml/jax
jax/_src/stages.py
https://github.com/jax-ml/jax/blob/master/jax/_src/stages.py
Apache-2.0
def donate_argnums(self): """Flat tuple of donated argument indices.""" return tuple( i for i, x in enumerate(tree_util.tree_leaves(self.args_info)) if x.donated)
Flat tuple of donated argument indices.
donate_argnums
python
jax-ml/jax
jax/_src/stages.py
https://github.com/jax-ml/jax/blob/master/jax/_src/stages.py
Apache-2.0
def as_text(self) -> str | None: """A human-readable text representation of this executable. Intended for visualization and debugging purposes. This is not a valid nor reliable serialization. Returns ``None`` if unavailable, e.g. based on backend, compiler, or runtime. """ try: retur...
A human-readable text representation of this executable. Intended for visualization and debugging purposes. This is not a valid nor reliable serialization. Returns ``None`` if unavailable, e.g. based on backend, compiler, or runtime.
as_text
python
jax-ml/jax
jax/_src/stages.py
https://github.com/jax-ml/jax/blob/master/jax/_src/stages.py
Apache-2.0
def cost_analysis(self) -> Any | None: """A summary of execution cost estimates. Intended for visualization and debugging purposes. The object output by this is some simple data structure that can easily be printed or serialized (e.g. nested dicts, lists, and tuples with numeric leaves). However, its ...
A summary of execution cost estimates. Intended for visualization and debugging purposes. The object output by this is some simple data structure that can easily be printed or serialized (e.g. nested dicts, lists, and tuples with numeric leaves). However, its structure can be arbitrary: it may be incon...
cost_analysis
python
jax-ml/jax
jax/_src/stages.py
https://github.com/jax-ml/jax/blob/master/jax/_src/stages.py
Apache-2.0
def memory_analysis(self) -> Any | None: """A summary of estimated memory requirements. Intended for visualization and debugging purposes. The object output by this is some simple data structure that can easily be printed or serialized (e.g. nested dicts, lists, and tuples with numeric leaves). However...
A summary of estimated memory requirements. Intended for visualization and debugging purposes. The object output by this is some simple data structure that can easily be printed or serialized (e.g. nested dicts, lists, and tuples with numeric leaves). However, its structure can be arbitrary: it may be ...
memory_analysis
python
jax-ml/jax
jax/_src/stages.py
https://github.com/jax-ml/jax/blob/master/jax/_src/stages.py
Apache-2.0
def from_flat_info(cls, lowering: Lowering, in_tree: tree_util.PyTreeDef, in_avals, donate_argnums: tuple[int, ...], out_tree: tree_util.PyTreeDef, no_kwargs: bool = False): """Initialize fr...
Initialize from flat info (``in_avals`` etc.) and an input PyTreeDef. Args: in_tree: The ``PyTreeDef`` of (args, kwargs). out_tree: The ``PyTreeDef`` of the outputs. no_kwargs: If ``True`` the transformation, and the ``Compiled`` returned from this object will not support keyword ...
from_flat_info
python
jax-ml/jax
jax/_src/stages.py
https://github.com/jax-ml/jax/blob/master/jax/_src/stages.py
Apache-2.0
def as_text(self, dialect: str | None = None, *, debug_info: bool = False) -> str: """A human-readable text representation of this lowering. Intended for visualization and debugging purposes. This need not be a valid nor reliable serialization. Use `jax.export` if you want reliable and po...
A human-readable text representation of this lowering. Intended for visualization and debugging purposes. This need not be a valid nor reliable serialization. Use `jax.export` if you want reliable and portable serialization. Args: dialect: Optional string specifying a lowering dialect (e.g. "sta...
as_text
python
jax-ml/jax
jax/_src/stages.py
https://github.com/jax-ml/jax/blob/master/jax/_src/stages.py
Apache-2.0
def compiler_ir(self, dialect: str | None = None) -> Any | None: """An arbitrary object representation of this lowering. Intended for debugging purposes. This is not a valid nor reliable serialization. The output has no guarantee of consistency across invocations. Use `jax.export` if you want relia...
An arbitrary object representation of this lowering. Intended for debugging purposes. This is not a valid nor reliable serialization. The output has no guarantee of consistency across invocations. Use `jax.export` if you want reliable and portable serialization. Returns ``None`` if unavailable, e....
compiler_ir
python
jax-ml/jax
jax/_src/stages.py
https://github.com/jax-ml/jax/blob/master/jax/_src/stages.py
Apache-2.0
def lower(self, *, lowering_platforms: tuple[str, ...] | None = None, _private_parameters: mlir.LoweringParameters | None = None): """Lower to compiler input, returning a ``Lowered`` instance.""" if _private_parameters is None: _private_parameters = mlir.LoweringParameters() new_callable =...
Lower to compiler input, returning a ``Lowered`` instance.
lower
python
jax-ml/jax
jax/_src/stages.py
https://github.com/jax-ml/jax/blob/master/jax/_src/stages.py
Apache-2.0
def thread_unsafe_test(): """Decorator for tests that are not thread-safe. Note: this decorator (naturally) only applies to what it wraps, not to, say, code in separate setUp() or tearDown() methods. """ if TEST_NUM_THREADS.value <= 0: yield return _test_rwlock.assert_reader_held() _test_rwlock....
Decorator for tests that are not thread-safe. Note: this decorator (naturally) only applies to what it wraps, not to, say, code in separate setUp() or tearDown() methods.
thread_unsafe_test
python
jax-ml/jax
jax/_src/test_loader.py
https://github.com/jax-ml/jax/blob/master/jax/_src/test_loader.py
Apache-2.0
def thread_unsafe_test_class(): """Decorator that marks a TestCase class as thread-hostile.""" def f(klass): assert issubclass(klass, unittest.TestCase), type(klass) klass.thread_hostile = True return klass return f
Decorator that marks a TestCase class as thread-hostile.
thread_unsafe_test_class
python
jax-ml/jax
jax/_src/test_loader.py
https://github.com/jax-ml/jax/blob/master/jax/_src/test_loader.py
Apache-2.0
def run_test(test): """Recursively runs tests in a test suite or test case.""" if isinstance(test, unittest.TestSuite): for subtest in test: run_test(subtest) else: test_result = ThreadSafeTestResult(lock, result) futures.append(executor.submit(_run_one_test, test, te...
Recursively runs tests in a test suite or test case.
run_test
python
jax-ml/jax
jax/_src/test_loader.py
https://github.com/jax-ml/jax/blob/master/jax/_src/test_loader.py
Apache-2.0
def to_default_dtype(arr: ArrayLike) -> np.ndarray: """Convert a value to an array with JAX's default dtype. This is generally used for type conversions of values returned by numpy functions, to make their dtypes take into account the state of the ``jax_enable_x64`` and ``jax_default_dtype_bits`` flags. """ ...
Convert a value to an array with JAX's default dtype. This is generally used for type conversions of values returned by numpy functions, to make their dtypes take into account the state of the ``jax_enable_x64`` and ``jax_default_dtype_bits`` flags.
to_default_dtype
python
jax-ml/jax
jax/_src/test_util.py
https://github.com/jax-ml/jax/blob/master/jax/_src/test_util.py
Apache-2.0
def with_jax_dtype_defaults(func: Callable[..., Any], use_defaults: bool = True): """Return a version of a function with outputs that match JAX's default dtypes. This is generally used to wrap numpy functions within tests, in order to make their default output dtypes match those of corresponding JAX functions, t...
Return a version of a function with outputs that match JAX's default dtypes. This is generally used to wrap numpy functions within tests, in order to make their default output dtypes match those of corresponding JAX functions, taking into account the state of the ``jax_enable_x64`` and ``jax_default_dtype_bits``...
with_jax_dtype_defaults
python
jax-ml/jax
jax/_src/test_util.py
https://github.com/jax-ml/jax/blob/master/jax/_src/test_util.py
Apache-2.0
def _capture_output(fp: TextIO) -> Generator[Callable[[], str], None, None]: """Context manager to capture all output written to a given file object. Unlike ``contextlib.redirect_stdout``, this context manager works for any file object and also for both pure Python and native code. Example:: with capture...
Context manager to capture all output written to a given file object. Unlike ``contextlib.redirect_stdout``, this context manager works for any file object and also for both pure Python and native code. Example:: with capture_output(sys.stdout) as get_output: print(42) print("Captured": get_outpu...
_capture_output
python
jax-ml/jax
jax/_src/test_util.py
https://github.com/jax-ml/jax/blob/master/jax/_src/test_util.py
Apache-2.0
def count_events(event): "Returns a context-manager that yields a function that counts a test event." @contextmanager def count_event(): before = thread_local_state.counts.get(event, 0) yield lambda: thread_local_state.counts.get(event, 0) - before return count_event
Returns a context-manager that yields a function that counts a test event.
count_events
python
jax-ml/jax
jax/_src/test_util.py
https://github.com/jax-ml/jax/blob/master/jax/_src/test_util.py
Apache-2.0
def collect_lowered_jaxprs() -> Generator[Sequence[tuple[core.ClosedJaxpr, mlir.ir.Module]]]: """ Collects all the pairs of (jaxpr, mlir_module) that are lowered. """ assert thread_local_state.collect_lowered_jaxprs is None collection: list[tuple[core.C...
Collects all the pairs of (jaxpr, mlir_module) that are lowered.
collect_lowered_jaxprs
python
jax-ml/jax
jax/_src/test_util.py
https://github.com/jax-ml/jax/blob/master/jax/_src/test_util.py
Apache-2.0
def _get_device_tags(): """returns a set of tags defined for the device under test""" if is_device_rocm(): device_tags = {device_under_test(), "rocm"} elif is_device_cuda(): device_tags = {device_under_test(), "cuda"} elif device_under_test() == "METAL": device_tags = {device_under_test(), "gpu"} ...
returns a set of tags defined for the device under test
_get_device_tags
python
jax-ml/jax
jax/_src/test_util.py
https://github.com/jax-ml/jax/blob/master/jax/_src/test_util.py
Apache-2.0
def device_supports_buffer_donation(): """A decorator for test methods to run the test only on devices that support buffer donation.""" return _device_filter( lambda: test_device_matches(mlir._platforms_with_donation) )
A decorator for test methods to run the test only on devices that support buffer donation.
device_supports_buffer_donation
python
jax-ml/jax
jax/_src/test_util.py
https://github.com/jax-ml/jax/blob/master/jax/_src/test_util.py
Apache-2.0
def request_cpu_devices(nr_devices: int): """Requests at least `nr_devices` CPU devices. request_cpu_devices should be called at the top-level of a test module before main() runs. It is not guaranteed that the number of CPU devices will be exactly `nr_devices`: it may be more or less, depending on how exact...
Requests at least `nr_devices` CPU devices. request_cpu_devices should be called at the top-level of a test module before main() runs. It is not guaranteed that the number of CPU devices will be exactly `nr_devices`: it may be more or less, depending on how exactly the test is invoked. Test cases that requi...
request_cpu_devices
python
jax-ml/jax
jax/_src/test_util.py
https://github.com/jax-ml/jax/blob/master/jax/_src/test_util.py
Apache-2.0
def pytest_mark_if_available(marker: str): """A decorator for test classes or methods to pytest.mark if installed.""" def wrap(func_or_class): try: import pytest except ImportError: return func_or_class return getattr(pytest.mark, marker)(func_or_class) return wrap
A decorator for test classes or methods to pytest.mark if installed.
pytest_mark_if_available
python
jax-ml/jax
jax/_src/test_util.py
https://github.com/jax-ml/jax/blob/master/jax/_src/test_util.py
Apache-2.0
def skip_under_pytest(reason: str): """A decorator for test methods to skip the test when run under pytest.""" reason = "Running under pytest: " + reason def skip(test_method): return unittest.skipIf(is_running_under_pytest(), reason)(test_method) return skip
A decorator for test methods to skip the test when run under pytest.
skip_under_pytest
python
jax-ml/jax
jax/_src/test_util.py
https://github.com/jax-ml/jax/blob/master/jax/_src/test_util.py
Apache-2.0
def _rand_dtype(rand, shape, dtype, scale=1., post=lambda x: x): """Produce random values given shape, dtype, scale, and post-processor. Args: rand: a function for producing random values of a given shape, e.g. a bound version of either np.RandomState.randn or np.RandomState.rand. shape: a shape valu...
Produce random values given shape, dtype, scale, and post-processor. Args: rand: a function for producing random values of a given shape, e.g. a bound version of either np.RandomState.randn or np.RandomState.rand. shape: a shape value as a tuple of positive integers. dtype: a numpy dtype. scale...
_rand_dtype
python
jax-ml/jax
jax/_src/test_util.py
https://github.com/jax-ml/jax/blob/master/jax/_src/test_util.py
Apache-2.0
def rand_fullrange(rng, standardize_nans=False): """Random numbers that span the full range of available bits.""" def gen(shape, dtype, post=lambda x: x): dtype = np.dtype(dtype) size = dtype.itemsize * math.prod(_dims_of_shape(shape)) vals = rng.randint(0, np.iinfo(np.uint8).max, size=size, dtype=np.ui...
Random numbers that span the full range of available bits.
rand_fullrange
python
jax-ml/jax
jax/_src/test_util.py
https://github.com/jax-ml/jax/blob/master/jax/_src/test_util.py
Apache-2.0
def rand_indices_unique_along_axis(rng): """Sample an array of given shape containing indices up to dim (exclusive), such that the indices are unique along the given axis. Optionally, convert some of the resulting indices to negative indices.""" def fn(dim, shape, axis, allow_negative=True): batch_size = ma...
Sample an array of given shape containing indices up to dim (exclusive), such that the indices are unique along the given axis. Optionally, convert some of the resulting indices to negative indices.
rand_indices_unique_along_axis
python
jax-ml/jax
jax/_src/test_util.py
https://github.com/jax-ml/jax/blob/master/jax/_src/test_util.py
Apache-2.0
def with_config(**kwds): """Test case decorator for subclasses of JaxTestCase""" def decorator(cls): assert inspect.isclass(cls) and issubclass(cls, JaxTestCase), "@with_config can only wrap JaxTestCase class definitions." cls._default_thread_local_config = {} for b in cls.__bases__: cls._default_...
Test case decorator for subclasses of JaxTestCase
with_config
python
jax-ml/jax
jax/_src/test_util.py
https://github.com/jax-ml/jax/blob/master/jax/_src/test_util.py
Apache-2.0
def promote_like_jnp(fun, inexact=False): """Decorator that promotes the arguments of `fun` to `jnp.result_type(*args)`. jnp and np have different type promotion semantics; this decorator allows tests make an np reference implementation act more like a jnp implementation. """ _promote = promote_dtypes_inex...
Decorator that promotes the arguments of `fun` to `jnp.result_type(*args)`. jnp and np have different type promotion semantics; this decorator allows tests make an np reference implementation act more like a jnp implementation.
promote_like_jnp
python
jax-ml/jax
jax/_src/test_util.py
https://github.com/jax-ml/jax/blob/master/jax/_src/test_util.py
Apache-2.0
def assertDeprecationWarnsOrRaises(self, deprecation_id: str, message: str): """Assert warning or error, depending on deprecation state. For use with functions that call :func:`jax._src.deprecations.warn`. """ if deprecations.is_accelerated(deprecation_id): return self.assertRaisesRegex(ValueErro...
Assert warning or error, depending on deprecation state. For use with functions that call :func:`jax._src.deprecations.warn`.
assertDeprecationWarnsOrRaises
python
jax-ml/jax
jax/_src/test_util.py
https://github.com/jax-ml/jax/blob/master/jax/_src/test_util.py
Apache-2.0
def assertArraysAllClose(self, actual, desired, *, check_dtypes=True, atol=None, rtol=None, err_msg=''): """Assert that actual and desired are close (up to numerical tolerances).""" self.assertEqual(actual.shape, desired.shape) atol = max(tolerance(_dtype(actual), atol), tolerance...
Assert that actual and desired are close (up to numerical tolerances).
assertArraysAllClose
python
jax-ml/jax
jax/_src/test_util.py
https://github.com/jax-ml/jax/blob/master/jax/_src/test_util.py
Apache-2.0
def assertAllClose(self, actual, desired, *, check_dtypes=True, atol=None, rtol=None, canonicalize_dtypes=True, err_msg=''): """Assert that actual and desired, either arrays or nested tuples/lists, are close.""" if isinstance(actual, dict): self.assertIsInstance(desired, dict) s...
Assert that actual and desired, either arrays or nested tuples/lists, are close.
assertAllClose
python
jax-ml/jax
jax/_src/test_util.py
https://github.com/jax-ml/jax/blob/master/jax/_src/test_util.py
Apache-2.0
def assertMultiLineStrippedEqual(self, expected, what): """Asserts two strings are equal, after dedenting and stripping each line.""" expected = textwrap.dedent(expected) what = textwrap.dedent(what) ignore_space_re = re.compile(r'\s*\n\s*') expected_clean = re.sub(ignore_space_re, '\n', expected.st...
Asserts two strings are equal, after dedenting and stripping each line.
assertMultiLineStrippedEqual
python
jax-ml/jax
jax/_src/test_util.py
https://github.com/jax-ml/jax/blob/master/jax/_src/test_util.py
Apache-2.0
def _CompileAndCheck(self, fun, args_maker, *, check_dtypes=True, tol=None, rtol=None, atol=None, check_cache_misses=True): """Helper method for running JAX compilation and allclose assertions.""" args = args_maker() def wrapped_fun(*args): self.assertTrue(python_should_be_exec...
Helper method for running JAX compilation and allclose assertions.
_CompileAndCheck
python
jax-ml/jax
jax/_src/test_util.py
https://github.com/jax-ml/jax/blob/master/jax/_src/test_util.py
Apache-2.0
def strict_promotion_if_dtypes_match(dtypes): """ Context manager to enable strict promotion if all dtypes match, and enable standard dtype promotion otherwise. """ if all(dtype == dtypes[0] for dtype in dtypes): return jax.numpy_dtype_promotion('strict') return jax.numpy_dtype_promotion('standard')
Context manager to enable strict promotion if all dtypes match, and enable standard dtype promotion otherwise.
strict_promotion_if_dtypes_match
python
jax-ml/jax
jax/_src/test_util.py
https://github.com/jax-ml/jax/blob/master/jax/_src/test_util.py
Apache-2.0
def parameterized_filterable(*, kwargs: Sequence[dict[str, Any]], testcase_name: Callable[[dict[str, Any]], str] | None = None, one_containing: str | None = None, ): """Decorator for named parameterized tests, with filtering support. Works like ``parameterized.named_parameters``, except that it sanitiz...
Decorator for named parameterized tests, with filtering support. Works like ``parameterized.named_parameters``, except that it sanitizes the test names so that we can use ``pytest -k`` and ``python test.py -k`` test filtering. This means, e.g., that many special characters are replaced with `_`. It also suppor...
parameterized_filterable
python
jax-ml/jax
jax/_src/test_util.py
https://github.com/jax-ml/jax/blob/master/jax/_src/test_util.py
Apache-2.0
def register_event_duration_listener(callback): """Manages registering/unregistering an event duration listener callback.""" try: monitoring.register_event_duration_secs_listener(callback) yield finally: monitoring._unregister_event_duration_listener_by_callback(callback)
Manages registering/unregistering an event duration listener callback.
register_event_duration_listener
python
jax-ml/jax
jax/_src/test_util.py
https://github.com/jax-ml/jax/blob/master/jax/_src/test_util.py
Apache-2.0
def set_env(**kwargs): """Context manager to temporarily set/unset one or more environment variables. Caution: setting environment variables is not thread-safe. If you use this utility, you must annotate your test using, e.g., @thread_unsafe_test() or @thread_unsafe_test_class(). Examples: >>> import o...
Context manager to temporarily set/unset one or more environment variables. Caution: setting environment variables is not thread-safe. If you use this utility, you must annotate your test using, e.g., @thread_unsafe_test() or @thread_unsafe_test_class(). Examples: >>> import os >>> os.environ['my_var...
set_env
python
jax-ml/jax
jax/_src/test_util.py
https://github.com/jax-ml/jax/blob/master/jax/_src/test_util.py
Apache-2.0
def numpy_vecdot(x, y, axis): """Implementation of numpy.vecdot for testing on numpy < 2.0.0""" if numpy_version() >= (2, 0, 0): raise ValueError("should be calling vecdot directly on numpy 2.0.0") x = np.moveaxis(x, axis, -1) y = np.moveaxis(y, axis, -1) x, y = np.broadcast_arrays(x, y) return np.matmu...
Implementation of numpy.vecdot for testing on numpy < 2.0.0
numpy_vecdot
python
jax-ml/jax
jax/_src/test_util.py
https://github.com/jax-ml/jax/blob/master/jax/_src/test_util.py
Apache-2.0
def complex_plane_sample(dtype, size_re=10, size_im=None): """Return a 2-D array of complex numbers that covers the complex plane with a grid of samples. The size of the grid is (3 + 2 * size_im) x (3 + 2 * size_re) that includes infinity points, extreme finite points, and the specified number of...
Return a 2-D array of complex numbers that covers the complex plane with a grid of samples. The size of the grid is (3 + 2 * size_im) x (3 + 2 * size_re) that includes infinity points, extreme finite points, and the specified number of points from real and imaginary axis. For example: >...
complex_plane_sample
python
jax-ml/jax
jax/_src/test_util.py
https://github.com/jax-ml/jax/blob/master/jax/_src/test_util.py
Apache-2.0
def nptomp(self, x): """Convert numpy array/scalar to an array/instance of mpmath number type. """ if isinstance(x, np.ndarray): return np.fromiter(map(self.nptomp, x.flatten()), dtype=object).reshape(x.shape) elif isinstance(x, np.floating): mpmath = self.mpmath ctx = self.get_context...
Convert numpy array/scalar to an array/instance of mpmath number type.
nptomp
python
jax-ml/jax
jax/_src/test_util.py
https://github.com/jax-ml/jax/blob/master/jax/_src/test_util.py
Apache-2.0
def mptonp(self, x): """Convert mpmath instance to numpy array/scalar type. """ if isinstance(x, np.ndarray) and x.dtype.kind == 'O': x_flat = x.flatten() item = x_flat[0] ctx = item.context fp_format = self.contexts_inv[ctx] if isinstance(item, ctx.mpc): dtype = getatt...
Convert mpmath instance to numpy array/scalar type.
mptonp
python
jax-ml/jax
jax/_src/test_util.py
https://github.com/jax-ml/jax/blob/master/jax/_src/test_util.py
Apache-2.0
def normalize(self, exact, reference, value): """Normalize reference and value using precision defined by the difference of exact and reference. """ def worker(ctx, s, e, r, v): ss, sm, se, sbc = s._mpf_ es, em, ee, ebc = e._mpf_ rs, rm, re, rbc = r._mpf_ vs, vm, ve, vbc = v._mpf...
Normalize reference and value using precision defined by the difference of exact and reference.
normalize
python
jax-ml/jax
jax/_src/test_util.py
https://github.com/jax-ml/jax/blob/master/jax/_src/test_util.py
Apache-2.0
def setup_hypothesis(max_examples=30) -> None: """Sets up the hypothesis profiles. Sets up the hypothesis testing profiles, and selects the one specified by the ``JAX_HYPOTHESIS_PROFILE`` environment variable (or the ``--jax_hypothesis_profile`` configuration. Args: max_examples: the maximum number of h...
Sets up the hypothesis profiles. Sets up the hypothesis testing profiles, and selects the one specified by the ``JAX_HYPOTHESIS_PROFILE`` environment variable (or the ``--jax_hypothesis_profile`` configuration. Args: max_examples: the maximum number of hypothesis examples to try, when using the defa...
setup_hypothesis
python
jax-ml/jax
jax/_src/test_util.py
https://github.com/jax-ml/jax/blob/master/jax/_src/test_util.py
Apache-2.0
def raise_on_warnings(): "Context manager that raises an exception if a warning is raised." if warnings.showwarning is not _showwarning: with warnings.catch_warnings(): warnings.simplefilter("error") yield return def handler(message, category, filename, lineno, file=None, line=None): rais...
Context manager that raises an exception if a warning is raised.
raise_on_warnings
python
jax-ml/jax
jax/_src/test_warning_util.py
https://github.com/jax-ml/jax/blob/master/jax/_src/test_warning_util.py
Apache-2.0
def record_warnings(): "Context manager that yields a list of warnings that are raised." if warnings.showwarning is not _showwarning: with warnings.catch_warnings(record=True) as w: warnings.simplefilter("always") yield w return log = [] def handler(message, category, filename, lineno, fil...
Context manager that yields a list of warnings that are raised.
record_warnings
python
jax-ml/jax
jax/_src/test_warning_util.py
https://github.com/jax-ml/jax/blob/master/jax/_src/test_warning_util.py
Apache-2.0
def ignore_warning(*, message: str | None = None, category: type = Warning): "Context manager that ignores any matching warnings." if warnings.showwarning is not _showwarning: with warnings.catch_warnings(): warnings.filterwarnings( "ignore", message="" if message is None else message, category=ca...
Context manager that ignores any matching warnings.
ignore_warning
python
jax-ml/jax
jax/_src/test_warning_util.py
https://github.com/jax-ml/jax/blob/master/jax/_src/test_warning_util.py
Apache-2.0
def to_json(self) -> bytes: """Serializes the backend config into JSON.""" # We format the JSON ourselves, because json.dumps seems to be overly slow. config = io.BytesIO() config.write(b'{"custom_call_config": {"body": "') config.write(base64.b64encode(self.lowered_module_asm)) config.write(b'"...
Serializes the backend config into JSON.
to_json
python
jax-ml/jax
jax/_src/tpu_custom_call.py
https://github.com/jax-ml/jax/blob/master/jax/_src/tpu_custom_call.py
Apache-2.0
def _get_device_type(module: ir.Module) -> str | None: """Determines the device type based on the core_type annotations.""" sparsecore_func_found = False tensorcore_func_found = False def assign_device_type_based_on_core_type(op: ir.Operation) -> ir.WalkResult: nonlocal sparsecore_func_found nonlocal t...
Determines the device type based on the core_type annotations.
_get_device_type
python
jax-ml/jax
jax/_src/tpu_custom_call.py
https://github.com/jax-ml/jax/blob/master/jax/_src/tpu_custom_call.py
Apache-2.0
def as_tpu_kernel( module: ir.Module, out_type: Any, *, cost_estimate: CostEstimate | None = None, backend: str | xla_client.Client = "tpu", kernel_name: str | None = None, vmem_limit_bytes: int | None = None, flags: dict[str, bool | int | float] | None = None, allow_input_fusion: Se...
Turns an MLIR Mosaic kernel into a JAX-compatible function.
as_tpu_kernel
python
jax-ml/jax
jax/_src/tpu_custom_call.py
https://github.com/jax-ml/jax/blob/master/jax/_src/tpu_custom_call.py
Apache-2.0
def _running_under_ipython() -> bool: """Returns true if we appear to be in an IPython session.""" try: get_ipython() # type: ignore return True except NameError: return False
Returns true if we appear to be in an IPython session.
_running_under_ipython
python
jax-ml/jax
jax/_src/traceback_util.py
https://github.com/jax-ml/jax/blob/master/jax/_src/traceback_util.py
Apache-2.0
def _ipython_supports_tracebackhide() -> bool: """Returns true if the IPython version supports __tracebackhide__.""" import IPython # pytype: disable=import-error return IPython.version_info[:2] >= (7, 17)
Returns true if the IPython version supports __tracebackhide__.
_ipython_supports_tracebackhide
python
jax-ml/jax
jax/_src/traceback_util.py
https://github.com/jax-ml/jax/blob/master/jax/_src/traceback_util.py
Apache-2.0
def flatten(tree: Any, is_leaf: Callable[[Any], bool] | None = None ) -> tuple[list[tree_util.Leaf], tree_util.PyTreeDef]: """Flattens a pytree. The flattening order (i.e. the order of elements in the output list) is deterministic, corresponding to a left-to-right depth-first tree trave...
Flattens a pytree. The flattening order (i.e. the order of elements in the output list) is deterministic, corresponding to a left-to-right depth-first tree traversal. Args: tree: a pytree to flatten. is_leaf: an optionally specified function that will be called at each flattening step. It should...
flatten
python
jax-ml/jax
jax/_src/tree.py
https://github.com/jax-ml/jax/blob/master/jax/_src/tree.py
Apache-2.0
def leaves(tree: Any, is_leaf: Callable[[Any], bool] | None = None ) -> list[tree_util.Leaf]: """Gets the leaves of a pytree. Args: tree: the pytree for which to get the leaves is_leaf : an optionally specified function that will be called at each flattening step. It should retu...
Gets the leaves of a pytree. Args: tree: the pytree for which to get the leaves is_leaf : an optionally specified function that will be called at each flattening step. It should return a boolean, which indicates whether the flattening should traverse the current object, or if it should be stopped...
leaves
python
jax-ml/jax
jax/_src/tree.py
https://github.com/jax-ml/jax/blob/master/jax/_src/tree.py
Apache-2.0
def map(f: Callable[..., Any], tree: Any, *rest: Any, is_leaf: Callable[[Any], bool] | None = None) -> Any: """Maps a multi-input function over pytree args to produce a new pytree. Args: f: function that takes ``1 + len(rest)`` arguments, to be applied at the corresponding leaves ...
Maps a multi-input function over pytree args to produce a new pytree. Args: f: function that takes ``1 + len(rest)`` arguments, to be applied at the corresponding leaves of the pytrees. tree: a pytree to be mapped over, with each leaf providing the first positional argument to ``f``. rest: a ...
map
python
jax-ml/jax
jax/_src/tree.py
https://github.com/jax-ml/jax/blob/master/jax/_src/tree.py
Apache-2.0
def reduce(function: Callable[[T, Any], T], tree: Any, initializer: Any = tree_util.no_initializer, is_leaf: Callable[[Any], bool] | None = None) -> T: """Call reduce() over the leaves of a tree. Args: function: the reduction function tree: the pytree to reduce over ini...
Call reduce() over the leaves of a tree. Args: function: the reduction function tree: the pytree to reduce over initializer: the optional initial value is_leaf : an optionally specified function that will be called at each flattening step. It should return a boolean, which indicates whether the...
reduce
python
jax-ml/jax
jax/_src/tree.py
https://github.com/jax-ml/jax/blob/master/jax/_src/tree.py
Apache-2.0
def structure(tree: Any, is_leaf: None | (Callable[[Any], bool]) = None) -> tree_util.PyTreeDef: """Gets the treedef for a pytree. Args: tree: the pytree for which to get the leaves is_leaf : an optionally specified function that will be called at each flattening step. It should return ...
Gets the treedef for a pytree. Args: tree: the pytree for which to get the leaves is_leaf : an optionally specified function that will be called at each flattening step. It should return a boolean, which indicates whether the flattening should traverse the current object, or if it should be stopp...
structure
python
jax-ml/jax
jax/_src/tree.py
https://github.com/jax-ml/jax/blob/master/jax/_src/tree.py
Apache-2.0
def transpose(outer_treedef: tree_util.PyTreeDef, inner_treedef: tree_util.PyTreeDef | None, pytree_to_transpose: Any) -> Any: """Transform a tree having tree structure (outer, inner) into one having structure (inner, outer). Args: outer_treedef: PyTreeDef representing the outer tre...
Transform a tree having tree structure (outer, inner) into one having structure (inner, outer). Args: outer_treedef: PyTreeDef representing the outer tree. inner_treedef: PyTreeDef representing the inner tree. If None, then it will be inferred from outer_treedef and the structure of pytree_to_tra...
transpose
python
jax-ml/jax
jax/_src/tree.py
https://github.com/jax-ml/jax/blob/master/jax/_src/tree.py
Apache-2.0
def unflatten(treedef: tree_util.PyTreeDef, leaves: Iterable[tree_util.Leaf]) -> Any: """Reconstructs a pytree from the treedef and the leaves. The inverse of :func:`tree_flatten`. Args: treedef: the treedef to reconstruct leaves: the iterable of leaves to use for reconstruction. The itera...
Reconstructs a pytree from the treedef and the leaves. The inverse of :func:`tree_flatten`. Args: treedef: the treedef to reconstruct leaves: the iterable of leaves to use for reconstruction. The iterable must match the leaves of the treedef. Returns: The reconstructed pytree, containing the ...
unflatten
python
jax-ml/jax
jax/_src/tree.py
https://github.com/jax-ml/jax/blob/master/jax/_src/tree.py
Apache-2.0
def flatten_with_path( tree: Any, is_leaf: Callable[..., bool] | None = None, is_leaf_takes_path: bool = False, ) -> tuple[list[tuple[tree_util.KeyPath, Any]], tree_util.PyTreeDef]: """Flattens a pytree like ``tree_flatten``, but also returns each leaf's key path. Args: tree: a pytree to flatten. If it...
Flattens a pytree like ``tree_flatten``, but also returns each leaf's key path. Args: tree: a pytree to flatten. If it contains a custom type, it is recommended to be registered with ``register_pytree_with_keys``. Returns: A pair which the first element is a list of key-leaf pairs, each of which...
flatten_with_path
python
jax-ml/jax
jax/_src/tree.py
https://github.com/jax-ml/jax/blob/master/jax/_src/tree.py
Apache-2.0
def leaves_with_path( tree: Any, is_leaf: Callable[..., bool] | None = None, is_leaf_takes_path: bool = False, ) -> list[tuple[tree_util.KeyPath, Any]]: """Gets the leaves of a pytree like ``tree_leaves`` and returns each leaf's key path. Args: tree: a pytree. If it contains a custom type, it is recomm...
Gets the leaves of a pytree like ``tree_leaves`` and returns each leaf's key path. Args: tree: a pytree. If it contains a custom type, it is recommended to be registered with ``register_pytree_with_keys``. Returns: A list of key-leaf pairs, each of which contains a leaf and its key path. Examples...
leaves_with_path
python
jax-ml/jax
jax/_src/tree.py
https://github.com/jax-ml/jax/blob/master/jax/_src/tree.py
Apache-2.0
def map_with_path( f: Callable[..., Any], tree: Any, *rest: Any, is_leaf: Callable[..., bool] | None = None, is_leaf_takes_path: bool = False, ) -> Any: """Maps a multi-input function over pytree key path and args to produce a new pytree. This is a more powerful alternative of ``tree_map`` that...
Maps a multi-input function over pytree key path and args to produce a new pytree. This is a more powerful alternative of ``tree_map`` that can take the key path of each leaf as input argument as well. Args: f: function that takes ``2 + len(rest)`` arguments, aka. the key path and each corresponding l...
map_with_path
python
jax-ml/jax
jax/_src/tree.py
https://github.com/jax-ml/jax/blob/master/jax/_src/tree.py
Apache-2.0
def broadcast(prefix_tree: Any, full_tree: Any, is_leaf: Callable[[Any], bool] | None = None ) -> list[Any]: """Broadcasts a tree prefix into the full structure of a given tree. Args: prefix_tree: a pytree that is a tree prefix of full_tree. full_tree: a pytree with the st...
Broadcasts a tree prefix into the full structure of a given 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 flattening st...
broadcast
python
jax-ml/jax
jax/_src/tree.py
https://github.com/jax-ml/jax/blob/master/jax/_src/tree.py
Apache-2.0
def tree_flatten(tree: Any, is_leaf: Callable[[Any], bool] | None = None ) -> tuple[list[Leaf], PyTreeDef]: """Alias of :func:`jax.tree.flatten`.""" return default_registry.flatten(tree, is_leaf)
Alias of :func:`jax.tree.flatten`.
tree_flatten
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 tree_leaves(tree: Any, is_leaf: Callable[[Any], bool] | None = None ) -> list[Leaf]: """Alias of :func:`jax.tree.leaves`.""" return default_registry.flatten(tree, is_leaf)[0]
Alias of :func:`jax.tree.leaves`.
tree_leaves
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 tree_structure(tree: Any, is_leaf: None | (Callable[[Any], bool]) = None) -> PyTreeDef: """Alias of :func:`jax.tree.structure`.""" return default_registry.flatten(tree, is_leaf)[1]
Alias of :func:`jax.tree.structure`.
tree_structure
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 all_leaves(iterable: Iterable[Any], is_leaf: Callable[[Any], bool] | None = None) -> bool: """Tests whether all elements in the given iterable are all leaves. This function is useful in advanced cases, for example if a library allows arbitrary map operations on a flat iterable of leaves it may...
Tests whether all elements in the given iterable are all leaves. This function is useful in advanced cases, for example if a library allows arbitrary map operations on a flat iterable of leaves it may want to check if the result is still a flat iterable of leaves. Args: iterable: Iterable of leaves. Re...
all_leaves
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_node( nodetype: type[T], flatten_func: Callable[[T], tuple[_Children, _AuxData]], unflatten_func: Callable[[_AuxData, _Children], T], flatten_with_keys_func: ( Callable[[T], tuple[KeyLeafPairs, _AuxData]] | None ) = None, ) -> None: """Extends the set of types that are ...
Extends the set of types that are considered internal nodes in pytrees. See :ref:`example usage <pytrees>`. Args: nodetype: a Python type to register as a pytree. flatten_func: a function to be used during flattening, taking a value of type ``nodetype`` and returning a pair, with (1) an iterable for...
register_pytree_node
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 tree_map(f: Callable[..., Any], tree: Any, *rest: Any, is_leaf: Callable[[Any], bool] | None = None) -> Any: """Alias of :func:`jax.tree.map`.""" leaves, treedef = tree_flatten(tree, is_leaf) all_leaves = [leaves] + [treedef.flatten_up_to(r) for r in rest] return treed...
Alias of :func:`jax.tree.map`.
tree_map
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 tree_transpose(outer_treedef: PyTreeDef, inner_treedef: PyTreeDef | None, pytree_to_transpose: Any) -> Any: """Alias of :func:`jax.tree.transpose`.""" flat, treedef = tree_flatten(pytree_to_transpose) if inner_treedef is None: inner_treedef = tree_structure(outer_treedef.flatten_up_to(p...
Alias of :func:`jax.tree.transpose`.
tree_transpose
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 _replace_nones(sentinel, tree): """Replaces ``None`` in ``tree`` with ``sentinel``.""" leaves, treedef = none_leaf_registry.flatten(tree) leaves = map(lambda x: sentinel if x is None else x, leaves) return treedef.unflatten(leaves)
Replaces ``None`` in ``tree`` with ``sentinel``.
_replace_nones
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 tree_reduce(function: Callable[[T, Any], T], tree: Any, initializer: Any = no_initializer, is_leaf: Callable[[Any], bool] | None = None) -> T: """Alias of :func:`jax.tree.reduce`.""" if initializer is no_initializer: return functools.reduce(function, tree_leav...
Alias of :func:`jax.tree.reduce`.
tree_reduce
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 tree_broadcast(prefix_tree: Any, full_tree: Any, is_leaf: Callable[[Any], bool] | None = None ) -> list[Any]: """Alias of :func:`jax.tree.broadcast`.""" broadcast_leaves = broadcast_prefix(prefix_tree, full_tree, is_leaf=is_leaf) return tree_structure(full_tree).unflatten(...
Alias of :func:`jax.tree.broadcast`.
tree_broadcast
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