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 _update_clocks(low_global_core_id, high_global_core_id): """Synchronizes the vector clocks for the cores with ids in the range between the two arguments.""" shared_memory = _get_shared_memory() # Despite only updating the vector clocks for some cores, we still need to # hold the global lock to ensure that n...
Synchronizes the vector clocks for the cores with ids in the range between the two arguments.
_update_clocks
python
jax-ml/jax
jax/_src/pallas/mosaic/interpret.py
https://github.com/jax-ml/jax/blob/master/jax/_src/pallas/mosaic/interpret.py
Apache-2.0
def _update_clocks_for_device_barrier(device_id): """Synchronizes the vector clocks for the cores on the given device.""" shared_memory = _get_shared_memory() low_core_id = device_id * shared_memory.num_cores_per_device high_core_id = (device_id + 1) * shared_memory.num_cores_per_device _update_clocks(low_cor...
Synchronizes the vector clocks for the cores on the given device.
_update_clocks_for_device_barrier
python
jax-ml/jax
jax/_src/pallas/mosaic/interpret.py
https://github.com/jax-ml/jax/blob/master/jax/_src/pallas/mosaic/interpret.py
Apache-2.0
def _allocate_buffer( device_id: Array, local_core_id: Array | None, memory_space: Array, val: Array, ): """Allocates a memory buffer on the device with id `device_id` and core with id `local_core_id`. Args: device_id: Singleton array holding the device id where the buffer will be allocat...
Allocates a memory buffer on the device with id `device_id` and core with id `local_core_id`. Args: device_id: Singleton array holding the device id where the buffer will be allocated. local_core_id: None or singleton array holding the core id where the buffer will be allocated. If None, a buffer...
_allocate_buffer
python
jax-ml/jax
jax/_src/pallas/mosaic/interpret.py
https://github.com/jax-ml/jax/blob/master/jax/_src/pallas/mosaic/interpret.py
Apache-2.0
def _allocate_semaphores( device_id: Array, local_core_id: Array | None, shape: Array ): """Allocates semaphores on the device with id `device_id` and core with id `local_core_id`. The number of semaphores allocated is given by the product of the entries in `shape`. Since for each semaphore id there is re...
Allocates semaphores on the device with id `device_id` and core with id `local_core_id`. The number of semaphores allocated is given by the product of the entries in `shape`. Since for each semaphore id there is really only one global `Semaphore` object, 'allocation' of semaphores per device and core here mea...
_allocate_semaphores
python
jax-ml/jax
jax/_src/pallas/mosaic/interpret.py
https://github.com/jax-ml/jax/blob/master/jax/_src/pallas/mosaic/interpret.py
Apache-2.0
def _to_int(x : int | Array | None) -> int | None: """Converts a value to an integer, or returns None if the value is None.""" if x is None: return None return int(x)
Converts a value to an integer, or returns None if the value is None.
_to_int
python
jax-ml/jax
jax/_src/pallas/mosaic/interpret.py
https://github.com/jax-ml/jax/blob/master/jax/_src/pallas/mosaic/interpret.py
Apache-2.0
def _get_parallel_dim_semantics( compiler_params: dict[str, Any], num_dimensions_in_grid: int, ) -> tuple[bool, ...]: """Returns a tuple indicating which grid dimensions have parallel semantics. Args: compiler_params: Representation of a `mosaic_core.CompilerParams` object as a dictionary. num_di...
Returns a tuple indicating which grid dimensions have parallel semantics. Args: compiler_params: Representation of a `mosaic_core.CompilerParams` object as a dictionary. num_dimensions_in_grid: The number of dimensions in the grid. Returns: A tuple of booleans where the entry at index `i` is `Tr...
_get_parallel_dim_semantics
python
jax-ml/jax
jax/_src/pallas/mosaic/interpret.py
https://github.com/jax-ml/jax/blob/master/jax/_src/pallas/mosaic/interpret.py
Apache-2.0
def _get_parallel_subgrid_size( parallel_semantics_per_dim: tuple[bool, ...], grid: tuple[int, ...] ) -> int: """Returns the size of the subgrid along the parallel dimensions.""" return functools.reduce( lambda x, y: x * y, ( dim_size if parallel_dim else 1 for dim_size, parallel...
Returns the size of the subgrid along the parallel dimensions.
_get_parallel_subgrid_size
python
jax-ml/jax
jax/_src/pallas/mosaic/interpret.py
https://github.com/jax-ml/jax/blob/master/jax/_src/pallas/mosaic/interpret.py
Apache-2.0
def _get_randomized_grid_coordinates( grid: tuple[int, ...], compiler_params: dict[str, Any], random_seed: int | None, ) -> _GridPointCoordinatesPerDim: """Returns a tuple of randomized coordinates for each 'parallel' dimension in `grid`. For a dimension with 'parallel' semantics at position `d` in the...
Returns a tuple of randomized coordinates for each 'parallel' dimension in `grid`. For a dimension with 'parallel' semantics at position `d` in the grid, the returned tuple contains a random permutation of the sequence `[0,..., grid[d] - 1]` at index `d`. For each dimension with 'arbitrary' semantics, the resu...
_get_randomized_grid_coordinates
python
jax-ml/jax
jax/_src/pallas/mosaic/interpret.py
https://github.com/jax-ml/jax/blob/master/jax/_src/pallas/mosaic/interpret.py
Apache-2.0
def _get_grid_point( loop_indices: tuple[Array, ...], grid_point_coordinates: _GridPointCoordinatesPerDim, ) -> Array: """Indexes each entry in `grid_point_coordinates` with the corresponding entry in `loop_indices`. If an entry in `grid_point_coordinates` is an empty array, the corresponding entry in th...
Indexes each entry in `grid_point_coordinates` with the corresponding entry in `loop_indices`. If an entry in `grid_point_coordinates` is an empty array, the corresponding entry in the returned array is the corresponding entry in `loop_indices`. Otherwise, the returned array contains the entry in `grid_point_coo...
_get_grid_point
python
jax-ml/jax
jax/_src/pallas/mosaic/interpret.py
https://github.com/jax-ml/jax/blob/master/jax/_src/pallas/mosaic/interpret.py
Apache-2.0
def _pad_to_block_dimension(value, block_shape, interpret_params): """Pads values so the shape evenly divides into block dimensions. For example, if values has a shape of (33, 2, 5) with a block_shape of (32, 2, 4), this function will pad the value of shape to (64, 2, 8). Args: value: Array to be padded. ...
Pads values so the shape evenly divides into block dimensions. For example, if values has a shape of (33, 2, 5) with a block_shape of (32, 2, 4), this function will pad the value of shape to (64, 2, 8). Args: value: Array to be padded. block_shape: Block shapes to use for padding. If None, no padding wi...
_pad_to_block_dimension
python
jax-ml/jax
jax/_src/pallas/mosaic/interpret.py
https://github.com/jax-ml/jax/blob/master/jax/_src/pallas/mosaic/interpret.py
Apache-2.0
def _body( carry: tuple[ jnp.int32, tuple[jnp.int32, ...], jnp.ndarray, list[jnp.ndarray], list[jnp.ndarray], ], ) -> tuple[ jnp.int32, tuple[jnp.int32, ...], jnp.ndarray, list[jnp.ndarray], list[jnp....
Performs one execution of the kernel body. Execution of `jaxpr` is preceded by reading kernel input buffers and followed by writing kernel output buffers. Args: carry: (iteration_idx, loop_idx, grid_point, prev_start_indices, cur_start_indices). - iteration_idx: the...
_body
python
jax-ml/jax
jax/_src/pallas/mosaic/interpret.py
https://github.com/jax-ml/jax/blob/master/jax/_src/pallas/mosaic/interpret.py
Apache-2.0
def _compute_name_stack_updates( old_name_stack: list[str], new_name_stack: list[str] ) -> tuple[list[str], list[str]]: """Computes the popped/pushed items to the name stack after an update. Args: old_name_stack: The name stack prior to the update. new_name_stack: The name stack after the update. ...
Computes the popped/pushed items to the name stack after an update. Args: old_name_stack: The name stack prior to the update. new_name_stack: The name stack after the update. Returns: popped: A list of names popped from the name stack as part of the update. pushed: A list of names pushed to the na...
_compute_name_stack_updates
python
jax-ml/jax
jax/_src/pallas/mosaic/lowering.py
https://github.com/jax-ml/jax/blob/master/jax/_src/pallas/mosaic/lowering.py
Apache-2.0
def _prng_key_load_lowering_rule(ctx: LoweringRuleContext, *args_flat, args_tree) -> KeyScalarBundle: """Lowering rule for loading PRNG keys from SMEM. PRNG key loads are currently lowered as a list of scalar loads from SMEM, rather than a single vector load. We store these scalars in a bundle type called KeyS...
Lowering rule for loading PRNG keys from SMEM. PRNG key loads are currently lowered as a list of scalar loads from SMEM, rather than a single vector load. We store these scalars in a bundle type called KeyScalarBundle, which has special case handling for functions that consume the key such as set_seed.
_prng_key_load_lowering_rule
python
jax-ml/jax
jax/_src/pallas/mosaic/lowering.py
https://github.com/jax-ml/jax/blob/master/jax/_src/pallas/mosaic/lowering.py
Apache-2.0
def _maybe_cast_load_to_bool( ctx, out_aval, val: ir.Value ) -> tuple[ir.Value, jnp.dtype]: """Casts a memref load value to bool if the requested value is a bool. Mosaic does not support boolean-type memrefs, since booleans typically live in mask registers. We instead load booleans as integers from memrefs...
Casts a memref load value to bool if the requested value is a bool. Mosaic does not support boolean-type memrefs, since booleans typically live in mask registers. We instead load booleans as integers from memrefs and move them to mask registers on load using this function. Args: out_aval: The output aval ...
_maybe_cast_load_to_bool
python
jax-ml/jax
jax/_src/pallas/mosaic/lowering.py
https://github.com/jax-ml/jax/blob/master/jax/_src/pallas/mosaic/lowering.py
Apache-2.0
def _maybe_cast_store_to_memref_type( ctx: LoweringRuleContext, expected_aval, val: ir.Value ) -> ir.Value: """Casts a boolean value back to an integer for storing in a memref.""" if expected_aval.dtype != jnp.bool_: return val int_out_type = aval_to_ir_type( ctx.lowering_context.dynamic_shape_repla...
Casts a boolean value back to an integer for storing in a memref.
_maybe_cast_store_to_memref_type
python
jax-ml/jax
jax/_src/pallas/mosaic/lowering.py
https://github.com/jax-ml/jax/blob/master/jax/_src/pallas/mosaic/lowering.py
Apache-2.0
def jax_dot_dims_to_tpu_dot_dot_dims(dimension_numbers, lhs_shape, rhs_shape): """Converts a jax dot dimension numbers to a tpu dot dimension numbers. Jax dot dimension numbers are given as a tuple of tuples of sequences of ints of the form ((lhs_contracting_dims, rhs_contracting_dims), (lhs_batch_dims, rhs_ba...
Converts a jax dot dimension numbers to a tpu dot dimension numbers. Jax dot dimension numbers are given as a tuple of tuples of sequences of ints of the form ((lhs_contracting_dims, rhs_contracting_dims), (lhs_batch_dims, rhs_batch_dims)). TPU dot dimension numbers are given as an MLIR definition of the form...
jax_dot_dims_to_tpu_dot_dot_dims
python
jax-ml/jax
jax/_src/pallas/mosaic/lowering.py
https://github.com/jax-ml/jax/blob/master/jax/_src/pallas/mosaic/lowering.py
Apache-2.0
def _maybe_cast_to_int(x: jax.Array | jax_core.AbstractValue): """Casts boolean values to integers. We perform this cast because Mosaic does not directly support bool values for Memrefs. Instead, we load bools as integers and cast them to bools after loading from a memref inside of the kernel. """ assert i...
Casts boolean values to integers. We perform this cast because Mosaic does not directly support bool values for Memrefs. Instead, we load bools as integers and cast them to bools after loading from a memref inside of the kernel.
_maybe_cast_to_int
python
jax-ml/jax
jax/_src/pallas/mosaic/pallas_call_registration.py
https://github.com/jax-ml/jax/blob/master/jax/_src/pallas/mosaic/pallas_call_registration.py
Apache-2.0
def pallas_call_tpu_lowering_rule( ctx: mlir.LoweringRuleContext, *in_nodes, jaxpr: jax_core.Jaxpr, grid_mapping: pallas_core.GridMapping, mesh: pallas_core.Mesh | None, input_output_aliases: tuple[tuple[int, int], ...], debug: bool, interpret: bool, compiler_params: dict[str, pallas...
Lowers a pallas_call to a Mosaic TPU custom call.
pallas_call_tpu_lowering_rule
python
jax-ml/jax
jax/_src/pallas/mosaic/pallas_call_registration.py
https://github.com/jax-ml/jax/blob/master/jax/_src/pallas/mosaic/pallas_call_registration.py
Apache-2.0
def _broadcast_pytree_to(from_pytree, to_pytree): """Broadcast a prefix pytree to a given full tree.""" proxy = object() treedef = tree_util.tree_structure(to_pytree) broadcast_leaves = [] def add_leaves(i, x): broadcast_leaves.extend( [i] * tree_util.tree_structure(x).num_leaves) try: tree_...
Broadcast a prefix pytree to a given full tree.
_broadcast_pytree_to
python
jax-ml/jax
jax/_src/pallas/mosaic/pipeline.py
https://github.com/jax-ml/jax/blob/master/jax/_src/pallas/mosaic/pipeline.py
Apache-2.0
def _make_block_ds( idx: jax.Array | int, size: jax.Array | int ) -> pl.Slice: """Make a DMA slice with mosaic size hints.""" out = pl.ds(idx * size, size) assert isinstance(out, pl.Slice) return out
Make a DMA slice with mosaic size hints.
_make_block_ds
python
jax-ml/jax
jax/_src/pallas/mosaic/pipeline.py
https://github.com/jax-ml/jax/blob/master/jax/_src/pallas/mosaic/pipeline.py
Apache-2.0
def _get_block_shape(spec: pl.BlockSpec) -> tuple[int, ...]: """Get the block shape for a given block spec.""" def _get_dim_size(bd): match bd: case pl.Blocked(block_size): return block_size case pl.Element(block_size): return block_size case pl.BoundedSlice(block_size): ...
Get the block shape for a given block spec.
_get_block_shape
python
jax-ml/jax
jax/_src/pallas/mosaic/pipeline.py
https://github.com/jax-ml/jax/blob/master/jax/_src/pallas/mosaic/pipeline.py
Apache-2.0
def create(cls, spec: pl.BlockSpec, dtype, buffer_type, needs_swap_ref=True ) -> BufferedRef: """Create a BufferedRef. Args: spec: pallas blockspec. dtype: dtype for buffers. buffer_type: enum indicating whether this is an input, output, or in/out accumulator buffered refe...
Create a BufferedRef. Args: spec: pallas blockspec. dtype: dtype for buffers. buffer_type: enum indicating whether this is an input, output, or in/out accumulator buffered reference. needs_swap_ref: whether a swap slots tracker needs to be allocated. Returns: Initialized ...
create
python
jax-ml/jax
jax/_src/pallas/mosaic/pipeline.py
https://github.com/jax-ml/jax/blob/master/jax/_src/pallas/mosaic/pipeline.py
Apache-2.0
def with_slot_index( self, slot_index: int | jax.Array | None ) -> "BufferedRef": """Returns a new BufferedRef with the given slot index.""" return dataclasses.replace(self, _current_slot_reg=slot_index)
Returns a new BufferedRef with the given slot index.
with_slot_index
python
jax-ml/jax
jax/_src/pallas/mosaic/pipeline.py
https://github.com/jax-ml/jax/blob/master/jax/_src/pallas/mosaic/pipeline.py
Apache-2.0
def bind_existing_ref(self, window_ref, indices): """For handling VMEM references, the pipeline aliases the existing ref.""" if self.memory_space == VMEM: return dataclasses.replace( self, window_ref=window_ref.at[self.compute_slice(indices)] ) return self
For handling VMEM references, the pipeline aliases the existing ref.
bind_existing_ref
python
jax-ml/jax
jax/_src/pallas/mosaic/pipeline.py
https://github.com/jax-ml/jax/blob/master/jax/_src/pallas/mosaic/pipeline.py
Apache-2.0
def compute_slice(self, grid_indices): """Compute DMA slice from grid indices.""" indices = self.compute_index(*grid_indices) assert len(self.block_shape) == len(indices) indexer = [] for bd, idx in zip(self.block_shape, indices, strict=True): match bd: case None | pl.Squeezed(): ...
Compute DMA slice from grid indices.
compute_slice
python
jax-ml/jax
jax/_src/pallas/mosaic/pipeline.py
https://github.com/jax-ml/jax/blob/master/jax/_src/pallas/mosaic/pipeline.py
Apache-2.0
def copy_in(self, src_ref, grid_indices): """Starts copy of HBM dma slice into the current slot.""" assert self.is_input if self.memory_space == VMEM: return assert not (self.window_ref is None or isinstance(self.window_ref, REF)) assert self.sem_recvs is not None if self.swap is not None: ...
Starts copy of HBM dma slice into the current slot.
copy_in
python
jax-ml/jax
jax/_src/pallas/mosaic/pipeline.py
https://github.com/jax-ml/jax/blob/master/jax/_src/pallas/mosaic/pipeline.py
Apache-2.0
def copy_out(self, dst_ref, grid_indices): """Starts copy of HBM dma slice from the current slot.""" assert self.is_output if self.memory_space == VMEM: return assert not (self.window_ref is None or isinstance(self.window_ref, REF)) assert self.sem_sends is not None if self.swap is not None: ...
Starts copy of HBM dma slice from the current slot.
copy_out
python
jax-ml/jax
jax/_src/pallas/mosaic/pipeline.py
https://github.com/jax-ml/jax/blob/master/jax/_src/pallas/mosaic/pipeline.py
Apache-2.0
def wait_in(self, src_ref, grid_indices): """Waits for input copy to finish.""" assert self.is_input if self.memory_space == VMEM: return assert not (self.window_ref is None or isinstance(self.window_ref, REF)) assert self.sem_recvs is not None src_slice = self.get_dma_slice(src_ref.shape, src_r...
Waits for input copy to finish.
wait_in
python
jax-ml/jax
jax/_src/pallas/mosaic/pipeline.py
https://github.com/jax-ml/jax/blob/master/jax/_src/pallas/mosaic/pipeline.py
Apache-2.0
def wait_out(self, dst_ref, grid_indices): """Waits for output copy to finish.""" assert self.is_output if self.memory_space == VMEM: return assert not (self.window_ref is None or isinstance(self.window_ref, REF)) assert self.sem_sends is not None # In a double buffer, previous slot is the same ...
Waits for output copy to finish.
wait_out
python
jax-ml/jax
jax/_src/pallas/mosaic/pipeline.py
https://github.com/jax-ml/jax/blob/master/jax/_src/pallas/mosaic/pipeline.py
Apache-2.0
def set_accumulator(self, init=False): """Set accumulator or zero it out to initialize.""" assert self.is_accumulator if self.accum_ref is not None: accum_dtype = self.accum_ref.dtype def _init(): self.accum_ref[...] = jnp.zeros_like(self.accum_ref[...]) def _set(): self.ac...
Set accumulator or zero it out to initialize.
set_accumulator
python
jax-ml/jax
jax/_src/pallas/mosaic/pipeline.py
https://github.com/jax-ml/jax/blob/master/jax/_src/pallas/mosaic/pipeline.py
Apache-2.0
def __init__( self, step: jax.Array, indices: tuple[int | jax.Array, ...], grid: tuple[int | jax.Array, ...], grid_offsets: tuple[int | jax.Array, ...], first_cycle=None, last_cycle=None, init_accumulators=None, trace_scopes=True, ): """Initializes scheduler. ...
Initializes scheduler. Args: step: inner step number. indices: current grid indices. grid: pallas grid for BufferedRefs. grid_offsets: offsets for grid indices (used for megacore). first_cycle: whether this is the first invocation of the pipeline. last_cycle: whether this is the...
__init__
python
jax-ml/jax
jax/_src/pallas/mosaic/pipeline.py
https://github.com/jax-ml/jax/blob/master/jax/_src/pallas/mosaic/pipeline.py
Apache-2.0
def skip_input_copies_when_init_accumulators(schedule) -> Any: """Skip input copies in schedule when init_accumulators is True.""" new_schedule = {**schedule} for k in ["prologue_copy_in", "wait_in", "copy_in"]: def new_pred(original_pred_fn, *a): pred = original_pred_fn(*a) if a[1].is_accumulato...
Skip input copies in schedule when init_accumulators is True.
skip_input_copies_when_init_accumulators
python
jax-ml/jax
jax/_src/pallas/mosaic/pipeline.py
https://github.com/jax-ml/jax/blob/master/jax/_src/pallas/mosaic/pipeline.py
Apache-2.0
def get_pipeline_schedule(schedule) -> Any: """Retrieve a named pipeline schedule or pass through fully specified one.""" predefined_schedules = { 'default': _default_schedule, 'fixed': _fixed_schedule } if isinstance(schedule, str): return predefined_schedules[schedule].copy() return schedule
Retrieve a named pipeline schedule or pass through fully specified one.
get_pipeline_schedule
python
jax-ml/jax
jax/_src/pallas/mosaic/pipeline.py
https://github.com/jax-ml/jax/blob/master/jax/_src/pallas/mosaic/pipeline.py
Apache-2.0
def make_pipeline_allocations( *refs, in_specs=None, out_specs=None, should_accumulate_out=False, needs_swap_ref=True, ): """Create BufferedRefs for the pipeline. This function creates buffered refs for an inner pipeline that can be created at the top-level of a pallas call such that they may...
Create BufferedRefs for the pipeline. This function creates buffered refs for an inner pipeline that can be created at the top-level of a pallas call such that they may be reused across multiple invocations of the inner pipeline. Args: in_specs: input pallas block specs out_specs: output pallas block ...
make_pipeline_allocations
python
jax-ml/jax
jax/_src/pallas/mosaic/pipeline.py
https://github.com/jax-ml/jax/blob/master/jax/_src/pallas/mosaic/pipeline.py
Apache-2.0
def pipeline( *refs: Any, scratches=None, allocations=None, first_cycle: CondVal = True, last_cycle: CondVal = True, init_accumulators: CondVal = False, prefetch=None, postyeet=None, schedule=None, body_prologue=None, ): """ Run the pipeline. Args: *ref_args:...
Run the pipeline. Args: *ref_args: a list of pallas refs (or more generally a list of pytrees of pallas refs) scratches: scratch buffers for the inner kernel allocations: a list of BufferedRefs, one corresponding to each ref first_cycle: boolean indicating if this is the first ...
pipeline
python
jax-ml/jax
jax/_src/pallas/mosaic/pipeline.py
https://github.com/jax-ml/jax/blob/master/jax/_src/pallas/mosaic/pipeline.py
Apache-2.0
def make_async_remote_copy(src_ref, dst_ref, send_sem, recv_sem, device_id, device_id_type: primitives.DeviceIdType = primitives.DeviceIdType.MESH): """Creates a description of a remote copy operation. Copies data from src_ref on the current device to dst_ref on the device specified by...
Creates a description of a remote copy operation. Copies data from src_ref on the current device to dst_ref on the device specified by device_id. Both semaphores should be waited on using the descriptor on both source and target devices. Note that device_id can also refer to the current device. Args: s...
make_async_remote_copy
python
jax-ml/jax
jax/_src/pallas/mosaic/primitives.py
https://github.com/jax-ml/jax/blob/master/jax/_src/pallas/mosaic/primitives.py
Apache-2.0
def wrap_pallas_seed(*seeds, impl): """Joins scalar into a single PRNG key.""" impl = jax_random.resolve_prng_impl(impl) return join_key_p.bind(*seeds, impl=impl)
Joins scalar into a single PRNG key.
wrap_pallas_seed
python
jax-ml/jax
jax/_src/pallas/mosaic/primitives.py
https://github.com/jax-ml/jax/blob/master/jax/_src/pallas/mosaic/primitives.py
Apache-2.0
def to_pallas_key(key: jax.Array) -> jax.Array: """Helper function for converting non-Pallas PRNG keys into Pallas keys.""" # Handle new-style typed PRNG keys. generate_key = functools.partial( jax.random.bits, shape=tpu_key_impl.key_shape, dtype=jnp.uint32 ) vmapped_key = False if jnp.issubdtype(key....
Helper function for converting non-Pallas PRNG keys into Pallas keys.
to_pallas_key
python
jax-ml/jax
jax/_src/pallas/mosaic/random.py
https://github.com/jax-ml/jax/blob/master/jax/_src/pallas/mosaic/random.py
Apache-2.0
def _make_stateful_sampler(sampler: SampleFnType) -> KeylessSampleFnType: """Converts a jax.random sampling function to a stateful version. Args: sampler: A sampling function that consumes a key and returns random samples. Returns: A stateful sampling function with the key argument removed. """ ...
Converts a jax.random sampling function to a stateful version. Args: sampler: A sampling function that consumes a key and returns random samples. Returns: A stateful sampling function with the key argument removed.
_make_stateful_sampler
python
jax-ml/jax
jax/_src/pallas/mosaic/random.py
https://github.com/jax-ml/jax/blob/master/jax/_src/pallas/mosaic/random.py
Apache-2.0
def sample_block(sampler_fn: SampleFnType, global_key: jax.Array, block_size: Shape, tile_size: Shape, total_size: Shape, block_index: tuple[typing.ArrayLike, ...] | None = None, **kwargs) -> jax.Array: """Samples a ...
Samples a block of random values with invariance guarantees. `sample_block` allows the sampling of identical blocks of random values across kernels with different block shapes and iteration orders. Each call to `sample_block` returns a `block_size`-shaped array of random samples corresponding to the `block_ind...
sample_block
python
jax-ml/jax
jax/_src/pallas/mosaic/random.py
https://github.com/jax-ml/jax/blob/master/jax/_src/pallas/mosaic/random.py
Apache-2.0
def skip(f): """Skips the verification of the given function.""" def wrapper(*args, **kwargs): is_not_verifying = assume(normally=1, when_verifying=0) lax.cond(is_not_verifying)(lambda: f(*args, **kwargs)) return wrapper
Skips the verification of the given function.
skip
python
jax-ml/jax
jax/_src/pallas/mosaic/verification.py
https://github.com/jax-ml/jax/blob/master/jax/_src/pallas/mosaic/verification.py
Apache-2.0
def define_model(model): """Replaces a function with its simplified model during verification.""" def decorator(f): def wrapper(*args, **kwargs): lax.cond( assume(normally=1, when_verifying=0), lambda: f(*args, **kwargs), lambda: model(*args, **kwargs), ) return wra...
Replaces a function with its simplified model during verification.
define_model
python
jax-ml/jax
jax/_src/pallas/mosaic/verification.py
https://github.com/jax-ml/jax/blob/master/jax/_src/pallas/mosaic/verification.py
Apache-2.0
def is_trivial_index(idx, shape) -> bool: """Checks if the index selects the entire shape.""" # Slices that select the entire dimension. def _slices(d): slices = [slice(b, e, s) for b, e, s in it.product([0, None], [d, None], [1, None])] return [indexing.Slice(0, d, 1), *slices] if isinstance(idx, tup...
Checks if the index selects the entire shape.
is_trivial_index
python
jax-ml/jax
jax/_src/pallas/mosaic_gpu/core.py
https://github.com/jax-ml/jax/blob/master/jax/_src/pallas/mosaic_gpu/core.py
Apache-2.0
def _is_known_divisible(value, divisor, fuel=10) -> bool: """Returns True if the value is statically known to be divisible by the divisor.""" if divisor == 1: return True if fuel < 0: return False if not isinstance(value.owner, ir.Operation): return False def_op = value.owner.opview match def_op...
Returns True if the value is statically known to be divisible by the divisor.
_is_known_divisible
python
jax-ml/jax
jax/_src/pallas/mosaic_gpu/core.py
https://github.com/jax-ml/jax/blob/master/jax/_src/pallas/mosaic_gpu/core.py
Apache-2.0
def flatten_ref_union(ref_union: AbstractRefUnion) -> tuple[_Ref, ...]: """Flattens a union of trees of references into a tuple of references. This is the moral equivalent of `jax.tree.leaves` for aliased references. """ flat_refs = [] union_bytes = 0 for ref_group in ref_union.refs: byte_offset = 0 ...
Flattens a union of trees of references into a tuple of references. This is the moral equivalent of `jax.tree.leaves` for aliased references.
flatten_ref_union
python
jax-ml/jax
jax/_src/pallas/mosaic_gpu/core.py
https://github.com/jax-ml/jax/blob/master/jax/_src/pallas/mosaic_gpu/core.py
Apache-2.0
def remote_ref( ref: _Ref, device_id: jax.typing.ArrayLike, device_id_type: pallas_primitives.DeviceIdType = pallas_primitives.DeviceIdType.MESH, ) -> pallas_core.TransformedRef: """Translate memref to a symmetric memref on a peer device.""" if not isinstance(ref, pallas_core.TransformedRef): if not...
Translate memref to a symmetric memref on a peer device.
remote_ref
python
jax-ml/jax
jax/_src/pallas/mosaic_gpu/core.py
https://github.com/jax-ml/jax/blob/master/jax/_src/pallas/mosaic_gpu/core.py
Apache-2.0
def nd_loop( grid: Sequence[int], *, collective_axes: Sequence[Hashable] | Hashable, ) -> Callable[[Callable[[Sequence[jax.Array]], None]], None]: """A loop over a multi-dimensional grid partitioned along the given axes. For example, if ``collective_axes`` is ``"x"`` with :func:`lax.axis_size` equal ...
A loop over a multi-dimensional grid partitioned along the given axes. For example, if ``collective_axes`` is ``"x"`` with :func:`lax.axis_size` equal to 4 and the grid is (2, 3), the implementation would produce the following iteration order loop step index axis index 0 (0, 0) ...
nd_loop
python
jax-ml/jax
jax/_src/pallas/mosaic_gpu/helpers.py
https://github.com/jax-ml/jax/blob/master/jax/_src/pallas/mosaic_gpu/helpers.py
Apache-2.0
def _estimate_resources( ctx: ResourceEstimatorContext, jaxpr: jax_core.Jaxpr ) -> Resources: """Estimates the resources required by the kernel.""" rs = Resources(smem_scratch_bytes=0) for eqn in jaxpr.eqns: # TODO(slebedev): Add support for other primitives, notably control flow. if rule := _resource...
Estimates the resources required by the kernel.
_estimate_resources
python
jax-ml/jax
jax/_src/pallas/mosaic_gpu/lowering.py
https://github.com/jax-ml/jax/blob/master/jax/_src/pallas/mosaic_gpu/lowering.py
Apache-2.0
def single_lane_predicate(self) -> ir.Value: """Returns a predicate that is True for a single lane within the current thread semantics. """ assert self.lowering_semantics == mgpu.LoweringSemantics.Lane match self.primitive_semantics: case gpu_core.PrimitiveSemantics.Warpgroup: return s...
Returns a predicate that is True for a single lane within the current thread semantics.
single_lane_predicate
python
jax-ml/jax
jax/_src/pallas/mosaic_gpu/lowering.py
https://github.com/jax-ml/jax/blob/master/jax/_src/pallas/mosaic_gpu/lowering.py
Apache-2.0
def reserve_barrier( self, barrier: mgpu.Barrier ) -> mgpu.BarrierRef | mgpu.DialectBarrierRef | mgpu.CollectiveBarrierRef: """Reserves a barrier. Raises: RuntimeError: If the barrier is already reserved. """ available = self.runtime_barriers.get(barrier, []) if not available: r...
Reserves a barrier. Raises: RuntimeError: If the barrier is already reserved.
reserve_barrier
python
jax-ml/jax
jax/_src/pallas/mosaic_gpu/lowering.py
https://github.com/jax-ml/jax/blob/master/jax/_src/pallas/mosaic_gpu/lowering.py
Apache-2.0
def scratch_view( self, structs: Sequence[jax.ShapeDtypeStruct] ) -> Sequence[ir.Value]: """Creates a view into the runtime scratch buffer for each struct. This is a low-level API. Use it only if you know what you are doing. The function allocates bytes at the top of a stack, which need to be ...
Creates a view into the runtime scratch buffer for each struct. This is a low-level API. Use it only if you know what you are doing. The function allocates bytes at the top of a stack, which need to be deallocated in a FIFO fashion with :meth:`ModuleContext.stack_free_smem`. After deallocation, the vi...
scratch_view
python
jax-ml/jax
jax/_src/pallas/mosaic_gpu/lowering.py
https://github.com/jax-ml/jax/blob/master/jax/_src/pallas/mosaic_gpu/lowering.py
Apache-2.0
def _unravel_program_id( block_id: ir.Value, axis: int, dimensions: tuple[int, ...], row_major: bool = False ) -> ir.Value: """Computes the program ID for axes compressed into one block dimension.""" if row_major: div_value = math.prod(dimensions[axis+1:]) else: div_value = math.prod(dimen...
Computes the program ID for axes compressed into one block dimension.
_unravel_program_id
python
jax-ml/jax
jax/_src/pallas/mosaic_gpu/lowering.py
https://github.com/jax-ml/jax/blob/master/jax/_src/pallas/mosaic_gpu/lowering.py
Apache-2.0
def _handle_dtype_bitcast( ref: ir.Value, src_dtype: ir.Type, dst_dtype: ir.Type ) -> ir.Value: """Allows bitcasting a SMEM ref from one element type to another. Args: ref: the reference to bitcast. src_dtype: the source element type. dst_dtype: the destination element type. Returns: A bitca...
Allows bitcasting a SMEM ref from one element type to another. Args: ref: the reference to bitcast. src_dtype: the source element type. dst_dtype: the destination element type. Returns: A bitcasted version of `ref` with element type `dst_dtype`. Raises: ValueError: if the source ref is not ...
_handle_dtype_bitcast
python
jax-ml/jax
jax/_src/pallas/mosaic_gpu/lowering.py
https://github.com/jax-ml/jax/blob/master/jax/_src/pallas/mosaic_gpu/lowering.py
Apache-2.0
def _transform_dtype( dtype: dtypes.DType, transforms: Sequence[state_types.Transform], ) -> dtypes.DType: """Applies `t.transform_dtype` for `t` in `transforms` sequentially on `dtype`.""" for transform in transforms: dtype = transform.transform_dtype(dtype) return dtype
Applies `t.transform_dtype` for `t` in `transforms` sequentially on `dtype`.
_transform_dtype
python
jax-ml/jax
jax/_src/pallas/mosaic_gpu/lowering.py
https://github.com/jax-ml/jax/blob/master/jax/_src/pallas/mosaic_gpu/lowering.py
Apache-2.0
def _bcast_wg( x: object, y: object, x_aval: jax_core.ShapedArray, y_aval: jax_core.ShapedArray, out_aval: jax_core.ShapedArray, ) -> tuple[ir.Value, ir.Value]: """Ensures that ``x`` and ``y`` have the expected shapes and dtypes. More specifically, the inputs are converted to vectors of the sam...
Ensures that ``x`` and ``y`` have the expected shapes and dtypes. More specifically, the inputs are converted to vectors of the same dtype as ``x_aval`` and ``y_aval``, and broadcasted to the output shape if necessary.
_bcast_wg
python
jax-ml/jax
jax/_src/pallas/mosaic_gpu/lowering.py
https://github.com/jax-ml/jax/blob/master/jax/_src/pallas/mosaic_gpu/lowering.py
Apache-2.0
def merge_indexers( indexers: Sequence[indexing.NDIndexer]) -> indexing.NDIndexer: """Merges multiple indexers into a single indexer. This function computes a new indexer such that applying the new indexer produces the same result as applying the sequence of input indexers in order from first-to-last. ""...
Merges multiple indexers into a single indexer. This function computes a new indexer such that applying the new indexer produces the same result as applying the sequence of input indexers in order from first-to-last.
merge_indexers
python
jax-ml/jax
jax/_src/pallas/mosaic_gpu/lowering.py
https://github.com/jax-ml/jax/blob/master/jax/_src/pallas/mosaic_gpu/lowering.py
Apache-2.0
def _get_slot(step, has_seq_dim): """Returns the buffer slot given the pipeline step.""" if has_seq_dim: return step else: return 0
Returns the buffer slot given the pipeline step.
_get_slot
python
jax-ml/jax
jax/_src/pallas/mosaic_gpu/pipeline.py
https://github.com/jax-ml/jax/blob/master/jax/_src/pallas/mosaic_gpu/pipeline.py
Apache-2.0
def _compute_registers( memory_registers: int, num_compute_wgs: int, ) -> int: """Returns the max number of registers to use in compute threads. We start with the theoretical max registers per thread if one wargroup (128 threads) used the entire SM's 64k register file (64k / 128 = 512). Then reserve `m...
Returns the max number of registers to use in compute threads. We start with the theoretical max registers per thread if one wargroup (128 threads) used the entire SM's 64k register file (64k / 128 = 512). Then reserve `memory_registers` for the producer warpgroup and distribute the remaining registers evenly ...
_compute_registers
python
jax-ml/jax
jax/_src/pallas/mosaic_gpu/pipeline.py
https://github.com/jax-ml/jax/blob/master/jax/_src/pallas/mosaic_gpu/pipeline.py
Apache-2.0
def load( src: _Ref, idx, *, layout: Layout | ParameterizedLayout | None = None, optimized: bool = True, ) -> jax.Array: """Loads from a reference into an array with the specified layout. Args: src: The reference to load from. Can be either in SMEM or GMEM. idx: The index to load from. ...
Loads from a reference into an array with the specified layout. Args: src: The reference to load from. Can be either in SMEM or GMEM. idx: The index to load from. layout: The optional layout to use for the resulting array. optimized: If True, a compilation error will be raised if no optimized i...
load
python
jax-ml/jax
jax/_src/pallas/mosaic_gpu/primitives.py
https://github.com/jax-ml/jax/blob/master/jax/_src/pallas/mosaic_gpu/primitives.py
Apache-2.0
def copy_gmem_to_smem( src: _Ref, dst: _Ref, barrier: _Ref, *, collective_axes: str | tuple[str, ...] | None = None, partitioned_axis: int | None = None, ) -> None: """Asynchronously copies a GMEM reference to a SMEM reference. If collective_axes is specified, this performs a multicast copy...
Asynchronously copies a GMEM reference to a SMEM reference. If collective_axes is specified, this performs a multicast copy where all CUDA blocks that share the same index along the collective axis receive a copy of the same block of data loaded from `dst` to `src`. If both collective_axes and partitioned_axi...
copy_gmem_to_smem
python
jax-ml/jax
jax/_src/pallas/mosaic_gpu/primitives.py
https://github.com/jax-ml/jax/blob/master/jax/_src/pallas/mosaic_gpu/primitives.py
Apache-2.0
def wgmma(acc: gpu_core.WGMMAAbstractAccumulatorRef, a, b) -> None: """Performs an asynchronous warp group matmul-accumulate on the given references. Conceptually, this is equivalent to doing ``acc[...] += a[...] @ b[...]``, except that the computation is performed asynchronously. Args: acc: The accumulat...
Performs an asynchronous warp group matmul-accumulate on the given references. Conceptually, this is equivalent to doing ``acc[...] += a[...] @ b[...]``, except that the computation is performed asynchronously. Args: acc: The accumulator reference. Needs to be allocated via :func:`jax.experimental.pal...
wgmma
python
jax-ml/jax
jax/_src/pallas/mosaic_gpu/primitives.py
https://github.com/jax-ml/jax/blob/master/jax/_src/pallas/mosaic_gpu/primitives.py
Apache-2.0
def tcgen05_mma(acc: _Ref, a: _Ref, b: _Ref, barrier: _Ref, accumulate: bool | jax.Array = True, collective_axis: str | None = None): """Asynchronous matrix-multiply accumulate for TensorCore gen 5 (Blackwell). If run in collective mod...
Asynchronous matrix-multiply accumulate for TensorCore gen 5 (Blackwell). If run in collective mode, `acc`, `a` (LHS), and `b` (RHS) should correspond to half of the total inputs to the MMA, where `acc` and `a` (LHS) are split in half along the rows and `b` (RHS) is split along the columns like so: ---------...
tcgen05_mma
python
jax-ml/jax
jax/_src/pallas/mosaic_gpu/primitives.py
https://github.com/jax-ml/jax/blob/master/jax/_src/pallas/mosaic_gpu/primitives.py
Apache-2.0
def _undo_transforms( raw_ref: pallas_core.AbstractMemoryRef, memory_transforms: Sequence[gpu_core.MemoryRefTransform], ): """Extract the `Transform`s that reverse the `MemoryRefTransform`s""" tmp_ref = state_types.TransformedRef(raw_ref, transforms=()) tmp_ref = functools.reduce(lambda r, t: t.undo(r), r...
Extract the `Transform`s that reverse the `MemoryRefTransform`s
_undo_transforms
python
jax-ml/jax
jax/_src/pallas/mosaic_gpu/primitives.py
https://github.com/jax-ml/jax/blob/master/jax/_src/pallas/mosaic_gpu/primitives.py
Apache-2.0
def inline_mgpu(*, arg_types=(), return_type=None): r"""Returns a decorator that inlines Mosaic GPU code. This allows using lower-level Mosaic GPU abstractions and operations, which are otherwise not directly exposed in Pallas. Example:: layout = plgpu.Layout.WG_STRIDED(x_ref.shape, vec_size=4) ...
Returns a decorator that inlines Mosaic GPU code. This allows using lower-level Mosaic GPU abstractions and operations, which are otherwise not directly exposed in Pallas. Example:: layout = plgpu.Layout.WG_STRIDED(x_ref.shape, vec_size=4) @plgpu.inline_mgpu( arg_types=(plgpu.RefType(),)...
inline_mgpu
python
jax-ml/jax
jax/_src/pallas/mosaic_gpu/primitives.py
https://github.com/jax-ml/jax/blob/master/jax/_src/pallas/mosaic_gpu/primitives.py
Apache-2.0
def _is_contiguous_int4(block_info: BlockInfo, nd_indexer: NDIndexer) -> bool: """Returns True if the block is contiguous in the last dimension.""" # In order to loaded as `uint8` the index must be an aligned slice. return ( block_info.full_shape_dtype.dtype in (jnp.int4, jnp.uint4) and block_info.sta...
Returns True if the block is contiguous in the last dimension.
_is_contiguous_int4
python
jax-ml/jax
jax/_src/pallas/triton/lowering.py
https://github.com/jax-ml/jax/blob/master/jax/_src/pallas/triton/lowering.py
Apache-2.0
def _reinterpret_int4_as_uint8( block_info: BlockInfo, nd_indexer: NDIndexer ) -> tuple[BlockInfo, NDIndexer]: """Returns a new block info and indexer that reads `int4` as `uint8`.""" last_idx = nd_indexer.indices[-1] new_last_idx = indexing.Slice(last_idx.start // 2, last_idx.size // 2) new_indices = (*nd_...
Returns a new block info and indexer that reads `int4` as `uint8`.
_reinterpret_int4_as_uint8
python
jax-ml/jax
jax/_src/pallas/triton/lowering.py
https://github.com/jax-ml/jax/blob/master/jax/_src/pallas/triton/lowering.py
Apache-2.0
def approx_tanh(x: jax.Array) -> jax.Array: r"""Elementwise approximate hyperbolic tangent: :math:`\mathrm{tanh}(x)`. See https://docs.nvidia.com/cuda/parallel-thread-execution/index.html#floating-point-instructions-tanh. """ if x.dtype == jnp.float16: asm = "tanh.approx.f16 $0, $1;" constraint = "h"...
Elementwise approximate hyperbolic tangent: :math:`\mathrm{tanh}(x)`. See https://docs.nvidia.com/cuda/parallel-thread-execution/index.html#floating-point-instructions-tanh.
approx_tanh
python
jax-ml/jax
jax/_src/pallas/triton/primitives.py
https://github.com/jax-ml/jax/blob/master/jax/_src/pallas/triton/primitives.py
Apache-2.0
def elementwise_inline_asm( asm: str, *, args: Sequence[jax.Array], constraints: str, pack: int, result_shape_dtypes: Sequence[jax.ShapeDtypeStruct], ) -> Sequence[jax.Array]: """Inline assembly applying an elementwise operation. Args: asm: The assembly code to run. args: The argume...
Inline assembly applying an elementwise operation. Args: asm: The assembly code to run. args: The arguments to pass to the assembly code. constraints: LLVM inline assembly `constraints <https://llvm.org/docs/LangRef.html#inline-asm-constraint-string>`_. pack: The number of elements from each ar...
elementwise_inline_asm
python
jax-ml/jax
jax/_src/pallas/triton/primitives.py
https://github.com/jax-ml/jax/blob/master/jax/_src/pallas/triton/primitives.py
Apache-2.0
def dct(x: Array, type: int = 2, n: int | None = None, axis: int = -1, norm: str | None = None) -> Array: """Computes the discrete cosine transform of the input JAX implementation of :func:`scipy.fft.dct`. Args: x: array type: integer, default = 2. Currently only type 2 is supported. n: inte...
Computes the discrete cosine transform of the input JAX implementation of :func:`scipy.fft.dct`. Args: x: array type: integer, default = 2. Currently only type 2 is supported. n: integer, default = x.shape[axis]. The length of the transform. If larger than ``x.shape[axis]``, the input will be ze...
dct
python
jax-ml/jax
jax/_src/scipy/fft.py
https://github.com/jax-ml/jax/blob/master/jax/_src/scipy/fft.py
Apache-2.0
def dctn(x: Array, type: int = 2, s: Sequence[int] | None=None, axes: Sequence[int] | None = None, norm: str | None = None) -> Array: """Computes the multidimensional discrete cosine transform of the input JAX implementation of :func:`scipy.fft.dctn`. Args: x: array type: inte...
Computes the multidimensional discrete cosine transform of the input JAX implementation of :func:`scipy.fft.dctn`. Args: x: array type: integer, default = 2. Currently only type 2 is supported. s: integer or sequence of integers. Specifies the shape of the result. If not specified, it will defau...
dctn
python
jax-ml/jax
jax/_src/scipy/fft.py
https://github.com/jax-ml/jax/blob/master/jax/_src/scipy/fft.py
Apache-2.0
def idct(x: Array, type: int = 2, n: int | None = None, axis: int = -1, norm: str | None = None) -> Array: """Computes the inverse discrete cosine transform of the input JAX implementation of :func:`scipy.fft.idct`. Args: x: array type: integer, default = 2. Currently only type 2 is supported. ...
Computes the inverse discrete cosine transform of the input JAX implementation of :func:`scipy.fft.idct`. Args: x: array type: integer, default = 2. Currently only type 2 is supported. n: integer, default = x.shape[axis]. The length of the transform. If larger than ``x.shape[axis]``, the input w...
idct
python
jax-ml/jax
jax/_src/scipy/fft.py
https://github.com/jax-ml/jax/blob/master/jax/_src/scipy/fft.py
Apache-2.0
def idctn(x: Array, type: int = 2, s: Sequence[int] | None=None, axes: Sequence[int] | None = None, norm: str | None = None) -> Array: """Computes the multidimensional inverse discrete cosine transform of the input JAX implementation of :func:`scipy.fft.idctn`. Args: x: array ...
Computes the multidimensional inverse discrete cosine transform of the input JAX implementation of :func:`scipy.fft.idctn`. Args: x: array type: integer, default = 2. Currently only type 2 is supported. s: integer or sequence of integers. Specifies the shape of the result. If not specified, it w...
idctn
python
jax-ml/jax
jax/_src/scipy/fft.py
https://github.com/jax-ml/jax/blob/master/jax/_src/scipy/fft.py
Apache-2.0
def trapezoid(y: ArrayLike, x: ArrayLike | None = None, dx: ArrayLike = 1.0, axis: int = -1) -> Array: r""" Integrate along the given axis using the composite trapezoidal rule. JAX implementation of :func:`scipy.integrate.trapezoid` The trapezoidal rule approximates the integral under a curve by...
Integrate along the given axis using the composite trapezoidal rule. JAX implementation of :func:`scipy.integrate.trapezoid` The trapezoidal rule approximates the integral under a curve by summing the areas of trapezoids formed between adjacent data points. Args: y: array of data to integrate. x: ...
trapezoid
python
jax-ml/jax
jax/_src/scipy/integrate.py
https://github.com/jax-ml/jax/blob/master/jax/_src/scipy/integrate.py
Apache-2.0
def svd(a: ArrayLike, full_matrices: bool = True, compute_uv: bool = True, overwrite_a: bool = False, check_finite: bool = True, lapack_driver: str = 'gesdd') -> Array | tuple[Array, Array, Array]: r"""Compute the singular value decomposition. JAX implementation of :func:`scipy.linalg.svd`. The ...
Compute the singular value decomposition. JAX implementation of :func:`scipy.linalg.svd`. The SVD of a matrix `A` is given by .. math:: A = U\Sigma V^H - :math:`U` contains the left singular vectors and satisfies :math:`U^HU=I` - :math:`V` contains the right singular vectors and satisfies :math:`V^H...
svd
python
jax-ml/jax
jax/_src/scipy/linalg.py
https://github.com/jax-ml/jax/blob/master/jax/_src/scipy/linalg.py
Apache-2.0
def schur(a: ArrayLike, output: str = 'real') -> tuple[Array, Array]: """Compute the Schur decomposition Only implemented on CPU. JAX implementation of :func:`scipy.linalg.schur`. The Schur form `T` of a matrix `A` satisfies: .. math:: A = Z T Z^H where `Z` is unitary, and `T` is upper-triangular...
Compute the Schur decomposition Only implemented on CPU. JAX implementation of :func:`scipy.linalg.schur`. The Schur form `T` of a matrix `A` satisfies: .. math:: A = Z T Z^H where `Z` is unitary, and `T` is upper-triangular for the complex-valued Schur decomposition (i.e. ``output="complex"``) a...
schur
python
jax-ml/jax
jax/_src/scipy/linalg.py
https://github.com/jax-ml/jax/blob/master/jax/_src/scipy/linalg.py
Apache-2.0
def lu_factor(a: ArrayLike, overwrite_a: bool = False, check_finite: bool = True) -> tuple[Array, Array]: """Factorization for LU-based linear solves JAX implementation of :func:`scipy.linalg.lu_factor`. This function returns a result suitable for use with :func:`jax.scipy.linalg.lu_solve`. For direct LU deco...
Factorization for LU-based linear solves JAX implementation of :func:`scipy.linalg.lu_factor`. This function returns a result suitable for use with :func:`jax.scipy.linalg.lu_solve`. For direct LU decompositions, prefer :func:`jax.scipy.linalg.lu`. Args: a: input array of shape ``(..., M, N)``. overw...
lu_factor
python
jax-ml/jax
jax/_src/scipy/linalg.py
https://github.com/jax-ml/jax/blob/master/jax/_src/scipy/linalg.py
Apache-2.0
def lu_solve(lu_and_piv: tuple[Array, ArrayLike], b: ArrayLike, trans: int = 0, overwrite_b: bool = False, check_finite: bool = True) -> Array: """Solve a linear system using an LU factorization JAX implementation of :func:`scipy.linalg.lu_solve`. Uses the output of :func:`jax.scipy.linalg.lu_factor...
Solve a linear system using an LU factorization JAX implementation of :func:`scipy.linalg.lu_solve`. Uses the output of :func:`jax.scipy.linalg.lu_factor`. Args: lu_and_piv: ``(lu, piv)``, output of :func:`~jax.scipy.linalg.lu_factor`. ``lu`` is an array of shape ``(..., M, N)``, containing ``L`` in i...
lu_solve
python
jax-ml/jax
jax/_src/scipy/linalg.py
https://github.com/jax-ml/jax/blob/master/jax/_src/scipy/linalg.py
Apache-2.0
def lu(a: ArrayLike, permute_l: bool = False, overwrite_a: bool = False, check_finite: bool = True) -> tuple[Array, Array] | tuple[Array, Array, Array]: """Compute the LU decomposition JAX implementation of :func:`scipy.linalg.lu`. The LU decomposition of a matrix `A` is: .. math:: A = P L U ...
Compute the LU decomposition JAX implementation of :func:`scipy.linalg.lu`. The LU decomposition of a matrix `A` is: .. math:: A = P L U where `P` is a permutation matrix, `L` is lower-triangular and `U` is upper-triangular. Args: a: array of shape ``(..., M, N)`` to decompose. permute_l: i...
lu
python
jax-ml/jax
jax/_src/scipy/linalg.py
https://github.com/jax-ml/jax/blob/master/jax/_src/scipy/linalg.py
Apache-2.0
def qr(a: ArrayLike, overwrite_a: bool = False, lwork: Any = None, mode: str = "full", pivoting: bool = False, check_finite: bool = True ) -> tuple[Array] | tuple[Array, Array] | tuple[Array, Array, Array]: """Compute the QR decomposition of an array JAX implementation of :func:`scipy.linalg.qr`. T...
Compute the QR decomposition of an array JAX implementation of :func:`scipy.linalg.qr`. The QR decomposition of a matrix `A` is given by .. math:: A = QR Where `Q` is a unitary matrix (i.e. :math:`Q^HQ=I`) and `R` is an upper-triangular matrix. Args: a: array of shape (..., M, N) mode: Co...
qr
python
jax-ml/jax
jax/_src/scipy/linalg.py
https://github.com/jax-ml/jax/blob/master/jax/_src/scipy/linalg.py
Apache-2.0
def solve_triangular(a: ArrayLike, b: ArrayLike, trans: int | str = 0, lower: bool = False, unit_diagonal: bool = False, overwrite_b: bool = False, debug: Any = None, check_finite: bool = True) -> Array: """Solve a triangular linear system of equations JAX implementation o...
Solve a triangular linear system of equations JAX implementation of :func:`scipy.linalg.solve_triangular`. This solves a (batched) linear system of equations ``a @ x = b`` for ``x`` given a triangular matrix ``a`` and a vector or matrix ``b``. Args: a: array of shape ``(..., N, N)``. Only part of the arr...
solve_triangular
python
jax-ml/jax
jax/_src/scipy/linalg.py
https://github.com/jax-ml/jax/blob/master/jax/_src/scipy/linalg.py
Apache-2.0
def expm(A: ArrayLike, *, upper_triangular: bool = False, max_squarings: int = 16) -> Array: """Compute the matrix exponential JAX implementation of :func:`scipy.linalg.expm`. Args: A: array of shape ``(..., N, N)`` upper_triangular: if True, then assume that ``A`` is upper-triangular. Default=False. ...
Compute the matrix exponential JAX implementation of :func:`scipy.linalg.expm`. Args: A: array of shape ``(..., N, N)`` upper_triangular: if True, then assume that ``A`` is upper-triangular. Default=False. max_squarings: The number of squarings in the scaling-and-squaring approximation method (de...
expm
python
jax-ml/jax
jax/_src/scipy/linalg.py
https://github.com/jax-ml/jax/blob/master/jax/_src/scipy/linalg.py
Apache-2.0
def expm_frechet(A: ArrayLike, E: ArrayLike, *, method: str | None = None, compute_expm: bool = True) -> Array | tuple[Array, Array]: """Compute the Frechet derivative of the matrix exponential. JAX implementation of :func:`scipy.linalg.expm_frechet` Args: A: array of shape ``(..., N, N)`` ...
Compute the Frechet derivative of the matrix exponential. JAX implementation of :func:`scipy.linalg.expm_frechet` Args: A: array of shape ``(..., N, N)`` E: array of shape ``(..., N, N)``; specifies the direction of the derivative. compute_expm: if True (default) then compute and return ``expm(A)``. ...
expm_frechet
python
jax-ml/jax
jax/_src/scipy/linalg.py
https://github.com/jax-ml/jax/blob/master/jax/_src/scipy/linalg.py
Apache-2.0
def block_diag(*arrs: ArrayLike) -> Array: """Create a block diagonal matrix from input arrays. JAX implementation of :func:`scipy.linalg.block_diag`. Args: *arrs: arrays of at most two dimensions Returns: 2D block-diagonal array constructed by placing the input arrays along the diagonal. Exam...
Create a block diagonal matrix from input arrays. JAX implementation of :func:`scipy.linalg.block_diag`. Args: *arrs: arrays of at most two dimensions Returns: 2D block-diagonal array constructed by placing the input arrays along the diagonal. Examples: >>> A = jnp.ones((1, 1)) >>> B = j...
block_diag
python
jax-ml/jax
jax/_src/scipy/linalg.py
https://github.com/jax-ml/jax/blob/master/jax/_src/scipy/linalg.py
Apache-2.0
def rsf2csf(T: ArrayLike, Z: ArrayLike, check_finite: bool = True) -> tuple[Array, Array]: """Convert real Schur form to complex Schur form. JAX implementation of :func:`scipy.linalg.rsf2csf`. Args: T: array of shape ``(..., N, N)`` containing the real Schur form of the input. Z: array of shape ``(..., ...
Convert real Schur form to complex Schur form. JAX implementation of :func:`scipy.linalg.rsf2csf`. Args: T: array of shape ``(..., N, N)`` containing the real Schur form of the input. Z: array of shape ``(..., N, N)`` containing the corresponding Schur transformation matrix. check_finite: unused...
rsf2csf
python
jax-ml/jax
jax/_src/scipy/linalg.py
https://github.com/jax-ml/jax/blob/master/jax/_src/scipy/linalg.py
Apache-2.0
def hessenberg(a: ArrayLike, *, calc_q: bool = False, overwrite_a: bool = False, check_finite: bool = True) -> Array | tuple[Array, Array]: """Compute the Hessenberg form of the matrix JAX implementation of :func:`scipy.linalg.hessenberg`. The Hessenberg form `H` of a matrix `A` satisfies: .. ...
Compute the Hessenberg form of the matrix JAX implementation of :func:`scipy.linalg.hessenberg`. The Hessenberg form `H` of a matrix `A` satisfies: .. math:: A = Q H Q^H where `Q` is unitary and `H` is zero below the first subdiagonal. Args: a : array of shape ``(..., N, N)`` calc_q: if Tru...
hessenberg
python
jax-ml/jax
jax/_src/scipy/linalg.py
https://github.com/jax-ml/jax/blob/master/jax/_src/scipy/linalg.py
Apache-2.0
def hilbert(n: int) -> Array: r"""Create a Hilbert matrix of order n. JAX implementation of :func:`scipy.linalg.hilbert`. The Hilbert matrix is defined by: .. math:: H_{ij} = \frac{1}{i + j + 1} for :math:`1 \le i \le n` and :math:`1 \le j \le n`. Args: n: the size of the matrix to create. ...
Create a Hilbert matrix of order n. JAX implementation of :func:`scipy.linalg.hilbert`. The Hilbert matrix is defined by: .. math:: H_{ij} = \frac{1}{i + j + 1} for :math:`1 \le i \le n` and :math:`1 \le j \le n`. Args: n: the size of the matrix to create. Returns: A Hilbert matrix of sh...
hilbert
python
jax-ml/jax
jax/_src/scipy/linalg.py
https://github.com/jax-ml/jax/blob/master/jax/_src/scipy/linalg.py
Apache-2.0
def pascal(n: int, kind: str | None = None) -> Array: r"""Create a Pascal matrix approximation of order n. JAX implementation of :func:`scipy.linalg.pascal`. The elements of the Pascal matrix approximate the binomial coefficients. This implementation is not exact as JAX does not support exact factorials. A...
Create a Pascal matrix approximation of order n. JAX implementation of :func:`scipy.linalg.pascal`. The elements of the Pascal matrix approximate the binomial coefficients. This implementation is not exact as JAX does not support exact factorials. Args: n: the size of the matrix to create. kind: (opt...
pascal
python
jax-ml/jax
jax/_src/scipy/linalg.py
https://github.com/jax-ml/jax/blob/master/jax/_src/scipy/linalg.py
Apache-2.0
def map_coordinates( input: ArrayLike, coordinates: Sequence[ArrayLike], order: int, mode: str = 'constant', cval: ArrayLike = 0.0, ): """ Map the input array to new coordinates using interpolation. JAX implementation of :func:`scipy.ndimage.map_coordinates` Given an input array and a set of coordinat...
Map the input array to new coordinates using interpolation. JAX implementation of :func:`scipy.ndimage.map_coordinates` Given an input array and a set of coordinates, this function returns the interpolated values of the input array at those coordinates. Args: input: N-dimensional input array from whic...
map_coordinates
python
jax-ml/jax
jax/_src/scipy/ndimage.py
https://github.com/jax-ml/jax/blob/master/jax/_src/scipy/ndimage.py
Apache-2.0
def fftconvolve(in1: ArrayLike, in2: ArrayLike, mode: str = "full", axes: Sequence[int] | None = None) -> Array: """ Convolve two N-dimensional arrays using Fast Fourier Transform (FFT). JAX implementation of :func:`scipy.signal.fftconvolve`. Args: in1: left-hand input to the convolution. ...
Convolve two N-dimensional arrays using Fast Fourier Transform (FFT). JAX implementation of :func:`scipy.signal.fftconvolve`. Args: in1: left-hand input to the convolution. in2: right-hand input to the convolution. Must have ``in1.ndim == in2.ndim``. mode: controls the size of the output. Available...
fftconvolve
python
jax-ml/jax
jax/_src/scipy/signal.py
https://github.com/jax-ml/jax/blob/master/jax/_src/scipy/signal.py
Apache-2.0
def convolve(in1: Array, in2: Array, mode: str = 'full', method: str = 'auto', precision: PrecisionLike = None) -> Array: """Convolution of two N-dimensional arrays. JAX implementation of :func:`scipy.signal.convolve`. Args: in1: left-hand input to the convolution. in2: right-hand input to ...
Convolution of two N-dimensional arrays. JAX implementation of :func:`scipy.signal.convolve`. Args: in1: left-hand input to the convolution. in2: right-hand input to the convolution. Must have ``in1.ndim == in2.ndim``. mode: controls the size of the output. Available operations are: * ``"full"`...
convolve
python
jax-ml/jax
jax/_src/scipy/signal.py
https://github.com/jax-ml/jax/blob/master/jax/_src/scipy/signal.py
Apache-2.0
def convolve2d(in1: Array, in2: Array, mode: str = 'full', boundary: str = 'fill', fillvalue: float = 0, precision: PrecisionLike = None) -> Array: """Convolution of two 2-dimensional arrays. JAX implementation of :func:`scipy.signal.convolve2d`. Args: in1: left-hand input to the convolution....
Convolution of two 2-dimensional arrays. JAX implementation of :func:`scipy.signal.convolve2d`. Args: in1: left-hand input to the convolution. Must have ``in1.ndim == 2``. in2: right-hand input to the convolution. Must have ``in2.ndim == 2``. mode: controls the size of the output. Available operations...
convolve2d
python
jax-ml/jax
jax/_src/scipy/signal.py
https://github.com/jax-ml/jax/blob/master/jax/_src/scipy/signal.py
Apache-2.0
def correlate(in1: Array, in2: Array, mode: str = 'full', method: str = 'auto', precision: PrecisionLike = None) -> Array: """Cross-correlation of two N-dimensional arrays. JAX implementation of :func:`scipy.signal.correlate`. Args: in1: left-hand input to the cross-correlation. in2: right...
Cross-correlation of two N-dimensional arrays. JAX implementation of :func:`scipy.signal.correlate`. Args: in1: left-hand input to the cross-correlation. in2: right-hand input to the cross-correlation. Must have ``in1.ndim == in2.ndim``. mode: controls the size of the output. Available operations are:...
correlate
python
jax-ml/jax
jax/_src/scipy/signal.py
https://github.com/jax-ml/jax/blob/master/jax/_src/scipy/signal.py
Apache-2.0
def correlate2d(in1: Array, in2: Array, mode: str = 'full', boundary: str = 'fill', fillvalue: float = 0, precision: PrecisionLike = None) -> Array: """Cross-correlation of two 2-dimensional arrays. JAX implementation of :func:`scipy.signal.correlate2d`. Args: in1: left-hand input to the cro...
Cross-correlation of two 2-dimensional arrays. JAX implementation of :func:`scipy.signal.correlate2d`. Args: in1: left-hand input to the cross-correlation. Must have ``in1.ndim == 2``. in2: right-hand input to the cross-correlation. Must have ``in2.ndim == 2``. mode: controls the size of the output. A...
correlate2d
python
jax-ml/jax
jax/_src/scipy/signal.py
https://github.com/jax-ml/jax/blob/master/jax/_src/scipy/signal.py
Apache-2.0
def detrend(data: ArrayLike, axis: int = -1, type: str = 'linear', bp: int = 0, overwrite_data: None = None) -> Array: """ Remove linear or piecewise linear trends from data. JAX implementation of :func:`scipy.signal.detrend`. Args: data: The input array containing the data to detrend. axi...
Remove linear or piecewise linear trends from data. JAX implementation of :func:`scipy.signal.detrend`. Args: data: The input array containing the data to detrend. axis: The axis along which to detrend. Default is -1 (the last axis). type: The type of detrending. Can be: * ``'linear'``: Fit ...
detrend
python
jax-ml/jax
jax/_src/scipy/signal.py
https://github.com/jax-ml/jax/blob/master/jax/_src/scipy/signal.py
Apache-2.0
def _fft_helper(x: Array, win: Array, detrend_func: Callable[[Array], Array], nperseg: int, noverlap: int, nfft: int | None, sides: str) -> Array: """Calculate windowed FFT in the same way the original SciPy does. """ if x.dtype.kind == 'i': x = x.astype(win.dtype) *batch_shape, signal_leng...
Calculate windowed FFT in the same way the original SciPy does.
_fft_helper
python
jax-ml/jax
jax/_src/scipy/signal.py
https://github.com/jax-ml/jax/blob/master/jax/_src/scipy/signal.py
Apache-2.0
def odd_ext(x: Array, n: int, axis: int = -1) -> Array: """Extends `x` along with `axis` by odd-extension. This function was previously a part of "scipy.signal.signaltools" but is no longer exposed. Args: x : input array n : the number of points to be added to the both end axis: the axis to be ext...
Extends `x` along with `axis` by odd-extension. This function was previously a part of "scipy.signal.signaltools" but is no longer exposed. Args: x : input array n : the number of points to be added to the both end axis: the axis to be extended
odd_ext
python
jax-ml/jax
jax/_src/scipy/signal.py
https://github.com/jax-ml/jax/blob/master/jax/_src/scipy/signal.py
Apache-2.0
def _spectral_helper(x: Array, y: ArrayLike | None, fs: ArrayLike = 1.0, window: str = 'hann', nperseg: int | None = None, noverlap: int | None = None, nfft: int | None = None, detrend_type: bool | str | Callable[[Array], Array] = 'constant', ...
LAX-backend implementation of `scipy.signal._spectral_helper`. Unlike the original helper function, `y` can be None for explicitly indicating auto-spectral (non cross-spectral) computation. In addition to this, `detrend` argument is renamed to `detrend_type` for avoiding internal name overlap.
_spectral_helper
python
jax-ml/jax
jax/_src/scipy/signal.py
https://github.com/jax-ml/jax/blob/master/jax/_src/scipy/signal.py
Apache-2.0
def stft(x: Array, fs: ArrayLike = 1.0, window: str = 'hann', nperseg: int = 256, noverlap: int | None = None, nfft: int | None = None, detrend: bool = False, return_onesided: bool = True, boundary: str | None = 'zeros', padded: bool = True, axis: int = -1) -> tuple[Array, Array, Array]: ""...
Compute the short-time Fourier transform (STFT). JAX implementation of :func:`scipy.signal.stft`. Args: x: Array representing a time series of input values. fs: Sampling frequency of the time series (default: 1.0). window: Data tapering window to apply to each segment. Can be a window function name...
stft
python
jax-ml/jax
jax/_src/scipy/signal.py
https://github.com/jax-ml/jax/blob/master/jax/_src/scipy/signal.py
Apache-2.0
def csd(x: Array, y: ArrayLike | None, fs: ArrayLike = 1.0, window: str = 'hann', nperseg: int | None = None, noverlap: int | None = None, nfft: int | None = None, detrend: str = 'constant', return_onesided: bool = True, scaling: str = 'density', axis: int = -1, average: str = 'mean') ->...
Estimate cross power spectral density (CSD) using Welch's method. This is a JAX implementation of :func:`scipy.signal.csd`. It is similar to :func:`jax.scipy.signal.welch`, but it operates on two input signals and estimates their cross-spectral density instead of the power spectral density (PSD). Args: ...
csd
python
jax-ml/jax
jax/_src/scipy/signal.py
https://github.com/jax-ml/jax/blob/master/jax/_src/scipy/signal.py
Apache-2.0
def welch(x: Array, fs: ArrayLike = 1.0, window: str = 'hann', nperseg: int | None = None, noverlap: int | None = None, nfft: int | None = None, detrend: str = 'constant', return_onesided: bool = True, scaling: str = 'density', axis: int = -1, average: str = 'mean') -> tuple[Arra...
Estimate power spectral density (PSD) using Welch's method. This is a JAX implementation of :func:`scipy.signal.welch`. It divides the input signal into overlapping segments, computes the modified periodogram for each segment, and averages the results to obtain a smoother estimate of the PSD. Args: x: ...
welch
python
jax-ml/jax
jax/_src/scipy/signal.py
https://github.com/jax-ml/jax/blob/master/jax/_src/scipy/signal.py
Apache-2.0