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 get_neighbor( idx: jax.Array, mesh: jax.sharding.Mesh, axis_name: str, *, direction: str ) -> tuple[jax.Array, ...]: """Helper function that computes the mesh indices of a neighbor.""" axis_names = mesh.axis_names which_axis = axis_names.index(axis_name) mesh_index = [ idx if i == which_axis else ...
Helper function that computes the mesh indices of a neighbor.
get_neighbor
python
jax-ml/jax
jax/experimental/pallas/ops/tpu/all_gather.py
https://github.com/jax-ml/jax/blob/master/jax/experimental/pallas/ops/tpu/all_gather.py
Apache-2.0
def gmm( lhs: jnp.ndarray, rhs: jnp.ndarray, group_sizes: jnp.ndarray, preferred_element_type: jnp.dtype = jnp.float32, tiling: tuple[int, int, int] | LutFn | None = (128, 128, 128), group_offset: jnp.ndarray | None = None, existing_out: jnp.ndarray | None = None, transpose_rhs: bool = F...
Compute lhs[sizes[i-1]:sizes[i], :] @ rhs for each group 'i'. Args: lhs: A 2d, jnp.ndarray with shape [m, k]. rhs: A 3d, jnp.ndarray with shape [num_groups, k, n]. group_sizes: A 1d, jnp.ndarray with shape [num_groups] and jnp.int32 dtype. preferred_element_type: jnp.dtype, the element type for the o...
gmm
python
jax-ml/jax
jax/experimental/pallas/ops/tpu/megablox/gmm.py
https://github.com/jax-ml/jax/blob/master/jax/experimental/pallas/ops/tpu/megablox/gmm.py
Apache-2.0
def wait_and_get_loaded(self) -> jax.Array: """Wait async copies and gets the loaded buffer as a jax.Array.""" for async_copy in self._async_copies: async_copy.wait() head_dim = self._vmem_buffer.shape[-1] jax_array = self._vmem_buffer[...].astype(jnp.float32) if self._scales_vmem_buffer is no...
Wait async copies and gets the loaded buffer as a jax.Array.
wait_and_get_loaded
python
jax-ml/jax
jax/experimental/pallas/ops/tpu/paged_attention/paged_attention_kernel.py
https://github.com/jax-ml/jax/blob/master/jax/experimental/pallas/ops/tpu/paged_attention/paged_attention_kernel.py
Apache-2.0
def paged_attention( q: jax.Array, k_pages: jax.Array | quantization_utils.QuantizedTensor, v_pages: jax.Array | quantization_utils.QuantizedTensor, lengths: jax.Array, page_indices: jax.Array, *, mask_value: float = DEFAULT_MASK_VALUE, attn_logits_soft_cap: float | None = None, page...
Paged grouped query attention. Args: q: A [batch_size, num_q_heads, head_dim] jax.Array. k_pages: A [num_kv_heads, total_num_pages, page_size, head_dim] jax.Array. v_pages: A [num_kv_heads, total_num_pages, page_size, head_dim] jax.Array. lengths: A i32[batch_size] jax.Array the length of each exampl...
paged_attention
python
jax-ml/jax
jax/experimental/pallas/ops/tpu/paged_attention/paged_attention_kernel.py
https://github.com/jax-ml/jax/blob/master/jax/experimental/pallas/ops/tpu/paged_attention/paged_attention_kernel.py
Apache-2.0
def from_int8( x: jnp.ndarray, h: jnp.ndarray, dtype: jnp.dtype = jnp.bfloat16 ) -> jnp.ndarray: """Converts an int8 array to a float array with a scale. Args: x: Int8 array. h: Quantization scale. dtype: Float dtype to convert to. Returns: Float array. """ return x.astype(dtype) * h / M...
Converts an int8 array to a float array with a scale. Args: x: Int8 array. h: Quantization scale. dtype: Float dtype to convert to. Returns: Float array.
from_int8
python
jax-ml/jax
jax/experimental/pallas/ops/tpu/paged_attention/quantization_utils.py
https://github.com/jax-ml/jax/blob/master/jax/experimental/pallas/ops/tpu/paged_attention/quantization_utils.py
Apache-2.0
def quantize_to_int8( x: jnp.ndarray, ) -> QuantizedTensor: """Quantizes a float array to an int8 QuantizedTensor. Args: x: Float array to quantize. Returns: Int8 QuantizedTensor. """ x_scales = get_quantization_scales(x) return QuantizedTensor(weight=to_int8(x, x_scales), scales=x_scales)
Quantizes a float array to an int8 QuantizedTensor. Args: x: Float array to quantize. Returns: Int8 QuantizedTensor.
quantize_to_int8
python
jax-ml/jax
jax/experimental/pallas/ops/tpu/paged_attention/quantization_utils.py
https://github.com/jax-ml/jax/blob/master/jax/experimental/pallas/ops/tpu/paged_attention/quantization_utils.py
Apache-2.0
def unquantize_from_int8( x: QuantizedTensor, dtype: jnp.dtype = jnp.bfloat16, ) -> jnp.ndarray: """Unquantizes an int8 QuantizedTensor to a float array. Args: x: Int8 QuantizedTensor to unquantize. dtype: Float dtype to unquantize to. Returns: Float array. """ return from_int8(x.weight,...
Unquantizes an int8 QuantizedTensor to a float array. Args: x: Int8 QuantizedTensor to unquantize. dtype: Float dtype to unquantize to. Returns: Float array.
unquantize_from_int8
python
jax-ml/jax
jax/experimental/pallas/ops/tpu/paged_attention/quantization_utils.py
https://github.com/jax-ml/jax/blob/master/jax/experimental/pallas/ops/tpu/paged_attention/quantization_utils.py
Apache-2.0
def grouped_query_attention_reference( queries: jax.Array, # [batch_size, num_q_heads, head_dim] k_pages: jax.Array, # [batch_size, num_kv_heads, max_seq_len, head_dim] v_pages: jax.Array, # [batch_size, num_kv_heads, max_seq_len, head_dim] seq_lens: jax.Array, # i32[batch_size] soft_cap: float ...
Grouped query attention with a single query per request.
grouped_query_attention_reference
python
jax-ml/jax
jax/experimental/pallas/ops/tpu/paged_attention/util.py
https://github.com/jax-ml/jax/blob/master/jax/experimental/pallas/ops/tpu/paged_attention/util.py
Apache-2.0
def next_power_of_2(x: int): """Finds the smallest power of 2 >= x using bit manipulation. Args: x: The input number (should be an integer). Returns: The smallest integer power of 2 that is >= x. """ assert x > 0 if x == 1: return 1 return 1 << (x - 1).bit_length()
Finds the smallest power of 2 >= x using bit manipulation. Args: x: The input number (should be an integer). Returns: The smallest integer power of 2 that is >= x.
next_power_of_2
python
jax-ml/jax
jax/experimental/pallas/ops/tpu/ragged_paged_attention/tuned_block_sizes.py
https://github.com/jax-ml/jax/blob/master/jax/experimental/pallas/ops/tpu/ragged_paged_attention/tuned_block_sizes.py
Apache-2.0
def simplify_key(key): """Simplify the key to reduce the number of combinations.""" ( q_dtype, kv_dtype, num_q_heads_per_blk, num_kv_heads_per_blk, head_dim, page_size, max_num_batched_tokens, pages_per_seq, ) = key return ( jnp.dtype(q_dtype).name, jn...
Simplify the key to reduce the number of combinations.
simplify_key
python
jax-ml/jax
jax/experimental/pallas/ops/tpu/ragged_paged_attention/tuned_block_sizes.py
https://github.com/jax-ml/jax/blob/master/jax/experimental/pallas/ops/tpu/ragged_paged_attention/tuned_block_sizes.py
Apache-2.0
def get_tpu_version() -> int: """Returns the numeric version of the TPU, or -1 if not on TPU.""" kind = jax.devices()[0].device_kind if 'TPU' not in kind: return -1 if kind.endswith(' lite'): kind = kind[: -len(' lite')] assert kind[:-1] == 'TPU v', kind return int(kind[-1])
Returns the numeric version of the TPU, or -1 if not on TPU.
get_tpu_version
python
jax-ml/jax
jax/experimental/pallas/ops/tpu/ragged_paged_attention/tuned_block_sizes.py
https://github.com/jax-ml/jax/blob/master/jax/experimental/pallas/ops/tpu/ragged_paged_attention/tuned_block_sizes.py
Apache-2.0
def get_tuned_block_sizes( q_dtype, kv_dtype, num_q_heads_per_blk, num_kv_heads_per_blk, head_dim, page_size, max_num_batched_tokens, pages_per_seq, ) -> tuple[int, int]: """Look up for the best (num_kv_pages_per_blk, num_queries_per_blk) from auto-tuned table.""" tpu_version = get_t...
Look up for the best (num_kv_pages_per_blk, num_queries_per_blk) from auto-tuned table.
get_tuned_block_sizes
python
jax-ml/jax
jax/experimental/pallas/ops/tpu/ragged_paged_attention/tuned_block_sizes.py
https://github.com/jax-ml/jax/blob/master/jax/experimental/pallas/ops/tpu/ragged_paged_attention/tuned_block_sizes.py
Apache-2.0
def mul32_hi_lo(x: jax.Array, y: jax.Array) -> tuple[jax.Array, jax.Array]: """Multiplies 2 32-bit values and returns the hi+low bits of the result.""" xhi = x >> 16 yhi = y >> 16 xlo = x & 0xffff ylo = y & 0xffff xy_hi = xhi * yhi xy_lo = xlo * ylo cross_xy = xhi * ylo cross_yx = xlo * yhi carry =...
Multiplies 2 32-bit values and returns the hi+low bits of the result.
mul32_hi_lo
python
jax-ml/jax
jax/experimental/pallas/ops/tpu/random/philox.py
https://github.com/jax-ml/jax/blob/master/jax/experimental/pallas/ops/tpu/random/philox.py
Apache-2.0
def philox_4x32_kernel(key, shape: Shape, unpadded_shape: Shape, block_size: tuple[int, int], offset: typing.ArrayLike = 0, fuse_output: bool = True): """Generates random bits using the Philox keyed hash func...
Generates random bits using the Philox keyed hash function. Args: key: A Philox key of shape (2,). shape: The shape of the output. Must be divisible by `block_size`. unpadded_shape: If `shape` is padded, then this is the shape of the output tensor if it were not padded. This is important for indexi...
philox_4x32_kernel
python
jax-ml/jax
jax/experimental/pallas/ops/tpu/random/philox.py
https://github.com/jax-ml/jax/blob/master/jax/experimental/pallas/ops/tpu/random/philox.py
Apache-2.0
def philox_4x32_count(key, shape: Shape, offset: typing.ArrayLike = 0, fuse_output: bool = True): """Convenience function to call philox_4x32_kernel with padded shapes.""" if len(shape) == 0: return philox_4x32_count( key, (1, 1), offset=...
Convenience function to call philox_4x32_kernel with padded shapes.
philox_4x32_count
python
jax-ml/jax
jax/experimental/pallas/ops/tpu/random/philox.py
https://github.com/jax-ml/jax/blob/master/jax/experimental/pallas/ops/tpu/random/philox.py
Apache-2.0
def philox_split(key, shape: Shape): """Splits the key into two keys of the same shape.""" bits1, bits2 = philox_4x32_count(key, shape, fuse_output=False) return jnp.stack([bits1, bits2], axis=bits1.ndim)
Splits the key into two keys of the same shape.
philox_split
python
jax-ml/jax
jax/experimental/pallas/ops/tpu/random/philox.py
https://github.com/jax-ml/jax/blob/master/jax/experimental/pallas/ops/tpu/random/philox.py
Apache-2.0
def blocked_iota(block_shape: Shape, total_shape: Shape): """Computes a sub-block of a larger shaped iota. Args: block_shape: The output block shape of the iota. total_shape: The total shape of the input tensor. Returns: Result of the blocked iota. """ iota_data = jnp.zeros(block...
Computes a sub-block of a larger shaped iota. Args: block_shape: The output block shape of the iota. total_shape: The total shape of the input tensor. Returns: Result of the blocked iota.
blocked_iota
python
jax-ml/jax
jax/experimental/pallas/ops/tpu/random/prng_utils.py
https://github.com/jax-ml/jax/blob/master/jax/experimental/pallas/ops/tpu/random/prng_utils.py
Apache-2.0
def threefry_2x32_count(key, shape: Shape, unpadded_shape: Shape, block_size: tuple[int, int]): """Generates random bits using the Threefry hash function. This function is a fusion of prng.shaped_iota and prng.threefry_2x32 from the JAX core library. Args: ...
Generates random bits using the Threefry hash function. This function is a fusion of prng.shaped_iota and prng.threefry_2x32 from the JAX core library. Args: key: A threefry key of shape (2,). shape: The shape of the output. Must be divisible by `block_size`. unpadded_shape: If `shape` is padded, th...
threefry_2x32_count
python
jax-ml/jax
jax/experimental/pallas/ops/tpu/random/threefry.py
https://github.com/jax-ml/jax/blob/master/jax/experimental/pallas/ops/tpu/random/threefry.py
Apache-2.0
def get_kernel_name( block_metadata: Mapping[str, Any], is_mqa: bool, save_residuals: bool, is_segmented: bool, phase: str, ) -> str: """Returns a unique name for all SplashAttention kernel variants.""" assert phase == "dq" or phase == "dkv" or phase == "fwd" # Saving residuals is supported on...
Returns a unique name for all SplashAttention kernel variants.
get_kernel_name
python
jax-ml/jax
jax/experimental/pallas/ops/tpu/splash_attention/splash_attention_kernel.py
https://github.com/jax-ml/jax/blob/master/jax/experimental/pallas/ops/tpu/splash_attention/splash_attention_kernel.py
Apache-2.0
def _splash_attention( fwd_mask_info: mask_info_lib.MaskInfo, dq_mask_info: mask_info_lib.MaskInfo | None, dkv_mask_info: mask_info_lib.MaskInfo | None, q: jax.Array, k: jax.Array, v: jax.Array, segment_ids: SegmentIds | None = None, *, is_mqa: bool, block_sizes: BlockSizes | Non...
For dynamic masks, `partial_mask_blocks` has shape (head_count, q_blocks, kv_blocks, block_q, block_kv). This shape allows sharding across both head count and query sequence dimensions. Note: The leading dimensions (head_count, q_blocks, kv_blocks) must be collapsed into a single dimension before being passed...
_splash_attention
python
jax-ml/jax
jax/experimental/pallas/ops/tpu/splash_attention/splash_attention_kernel.py
https://github.com/jax-ml/jax/blob/master/jax/experimental/pallas/ops/tpu/splash_attention/splash_attention_kernel.py
Apache-2.0
def manual_sharding_spec(self, sharding: jax.sharding.NamedSharding): """Returns a value that can be used as a shard_map partition spec for the kernel.""" if self.fwd_mask_info.data_next is not None: block_mask_shape = self.fwd_mask_info.data_next.shape try: shard_shape = sharding.shard_shap...
Returns a value that can be used as a shard_map partition spec for the kernel.
manual_sharding_spec
python
jax-ml/jax
jax/experimental/pallas/ops/tpu/splash_attention/splash_attention_kernel.py
https://github.com/jax-ml/jax/blob/master/jax/experimental/pallas/ops/tpu/splash_attention/splash_attention_kernel.py
Apache-2.0
def make_causal_mask(shape: tuple[int, int], offset: int = 0) -> np.ndarray: """Makes a causal attention mask. Args: shape: Shape of the 2-dim mask: (q_seq_len, kv_seq_len). offset: Offset of q start wrt kv. A positive offset shifts the bottom triangle upward, a negative one shifts it downward. A neg...
Makes a causal attention mask. Args: shape: Shape of the 2-dim mask: (q_seq_len, kv_seq_len). offset: Offset of q start wrt kv. A positive offset shifts the bottom triangle upward, a negative one shifts it downward. A negative offset makes the first 'offset' rows of the attention matrix all 0s wh...
make_causal_mask
python
jax-ml/jax
jax/experimental/pallas/ops/tpu/splash_attention/splash_attention_mask.py
https://github.com/jax-ml/jax/blob/master/jax/experimental/pallas/ops/tpu/splash_attention/splash_attention_mask.py
Apache-2.0
def make_chunk_attention_mask( shape: tuple[int, int], chunk_size: int ) -> np.ndarray: """Makes a chunked causal attention mask. Args: shape: The desired shape of the mask (q_seq_len, kv_seq_len). chunk_size: The size of the attention chunks. Returns: A boolean mask of shape `mask_shape` where ...
Makes a chunked causal attention mask. Args: shape: The desired shape of the mask (q_seq_len, kv_seq_len). chunk_size: The size of the attention chunks. Returns: A boolean mask of shape `mask_shape` where True indicates attention is allowed according to chunked causal rules, and False otherwise. ...
make_chunk_attention_mask
python
jax-ml/jax
jax/experimental/pallas/ops/tpu/splash_attention/splash_attention_mask.py
https://github.com/jax-ml/jax/blob/master/jax/experimental/pallas/ops/tpu/splash_attention/splash_attention_mask.py
Apache-2.0
def local_mask_function(q_ids, kv_ids): """Computes the local attention mask for the given slice indices.""" left_size, right_size = self.window_size assert q_ids.ndim == 2 assert kv_ids.ndim == 2 if left_size is None and right_size is None: return np.ones((q_ids.shape[0], kv_ids...
Computes the local attention mask for the given slice indices.
local_mask_function
python
jax-ml/jax
jax/experimental/pallas/ops/tpu/splash_attention/splash_attention_mask.py
https://github.com/jax-ml/jax/blob/master/jax/experimental/pallas/ops/tpu/splash_attention/splash_attention_mask.py
Apache-2.0
def _downcast_to_small_type(array: np.ndarray) -> np.ndarray: """Downcast numpy array. If possible, downcast the data-type of the input array to the smallest numpy type (among np.int16 and np.int8) that fits the content of the array. Args: array: the array to downcast Returns: The downcasted array....
Downcast numpy array. If possible, downcast the data-type of the input array to the smallest numpy type (among np.int16 and np.int8) that fits the content of the array. Args: array: the array to downcast Returns: The downcasted array. Raises: ValueError: if the input array is not np.int32 or i...
_downcast_to_small_type
python
jax-ml/jax
jax/experimental/pallas/ops/tpu/splash_attention/splash_attention_mask_info.py
https://github.com/jax-ml/jax/blob/master/jax/experimental/pallas/ops/tpu/splash_attention/splash_attention_mask_info.py
Apache-2.0
def _check_mask(mask: mask_lib.Mask) -> None: """Check that the given mask is valid. A row of all zeros along the kv dimension would result in a division by zero when computing the softmax. This function is meant to protect against that case. Args: mask: the mask to check. Raises: ValueError: the...
Check that the given mask is valid. A row of all zeros along the kv dimension would result in a division by zero when computing the softmax. This function is meant to protect against that case. Args: mask: the mask to check. Raises: ValueError: the mask is invalid.
_check_mask
python
jax-ml/jax
jax/experimental/pallas/ops/tpu/splash_attention/splash_attention_mask_info.py
https://github.com/jax-ml/jax/blob/master/jax/experimental/pallas/ops/tpu/splash_attention/splash_attention_mask_info.py
Apache-2.0
def _get_mask_info_for_shard( output_shape: tuple[int, int, int], has_mask_next: bool, mask: mask_lib.MultiHeadMask | jax.Array, block_shape: tuple[int, int], coords_to_partial_mask_block_index: dict[tuple[int, int, int], int], masks_per_head_shard: int, head_start: int, num_heads: int, ...
Process a slice of the mask to compute data_next and mask_next. Args: output_shape: The shape of the data_next and mask_next to return has_mask_next: Whether mask_next should be constructed. If False None is returned for mask_next. mask: The full mask to be sliced according to the head and sequence...
_get_mask_info_for_shard
python
jax-ml/jax
jax/experimental/pallas/ops/tpu/splash_attention/splash_attention_mask_info.py
https://github.com/jax-ml/jax/blob/master/jax/experimental/pallas/ops/tpu/splash_attention/splash_attention_mask_info.py
Apache-2.0
def _process_dynamic_mask( mask: jax.Array, block_shape: tuple[int, int], is_dkv: bool, *, downcast_smem_data: bool = True, head_shards: int = 1, q_seq_shards: int = 1, shrink_grid: bool = True, ) -> tuple[MaskInfo, None]: """Similar to `_process_mask` but the mask must be a dynamic ar...
Similar to `_process_mask` but the mask must be a dynamic array. Since the mask is dynamic, we can't know the exact number of partial mask blocks at trace time. Therefore, the entire mask is materialized in `partial_mask_blocks`. Note that we can still populate MaskInfo to skip fully-masked blocks. Args: ...
_process_dynamic_mask
python
jax-ml/jax
jax/experimental/pallas/ops/tpu/splash_attention/splash_attention_mask_info.py
https://github.com/jax-ml/jax/blob/master/jax/experimental/pallas/ops/tpu/splash_attention/splash_attention_mask_info.py
Apache-2.0
def _process_mask( mask: mask_lib.MultiHeadMask, # [num_heads, q_seq_len, kv_seq_len] block_shape: tuple[int, int], is_dkv: bool, *, downcast_smem_data: bool = True, head_shards: int = 1, q_seq_shards: int = 1, shrink_grid: bool = True, ) -> tuple[MaskInfo, jax_util.HashableFunction | N...
Transform a dense mask into a sparse representation. The number of head and Q sequence shards are needed to create a MaskInfo object that is partitionable (with shmap or PartIR) along these two dimension. In particular for dKV MaskInfo, for each shard the indices of in the data_next array are relative to the c...
_process_mask
python
jax-ml/jax
jax/experimental/pallas/ops/tpu/splash_attention/splash_attention_mask_info.py
https://github.com/jax-ml/jax/blob/master/jax/experimental/pallas/ops/tpu/splash_attention/splash_attention_mask_info.py
Apache-2.0
def _get_spatial_valid_position_count( dnums: convolution.ConvDimensionNumbers, lhs: roofline.RooflineShape, rhs: roofline.RooflineShape, out: roofline.RooflineShape, window_strides: Sequence[int], padding: Sequence[tuple[int, int]], lhs_dilation: Sequence[int], rhs_dilation: Sequence[in...
Gets the number of valid spatial positions for conv_general_dilated. Args: dnums: The dimension numbers for the convolution. lhs: The shape of the left-hand side of the convolution. rhs: The shape of the right-hand side of the convolution. out: The shape of the output of the convolution. window_s...
_get_spatial_valid_position_count
python
jax-ml/jax
jax/experimental/roofline/rooflines.py
https://github.com/jax-ml/jax/blob/master/jax/experimental/roofline/rooflines.py
Apache-2.0
def filter_passes(regex: str) -> Sequence[Pass]: """Gets all registered passes whose display name matches the given regex.""" return [ pass_ for pass_ in _pass_registry.values() if re.match(regex, pass_.name) ]
Gets all registered passes whose display name matches the given regex.
filter_passes
python
jax-ml/jax
jax/experimental/source_mapper/common.py
https://github.com/jax-ml/jax/blob/master/jax/experimental/source_mapper/common.py
Apache-2.0
def flag_env(**kwargs): """A context manager for setting and restoring flags.""" old_flags = {kwarg: getattr(flags.FLAGS, kwarg) for kwarg in kwargs} for kwarg, new_value in kwargs.items(): setattr(flags.FLAGS, kwarg, new_value) try: yield finally: for kwarg, old_value in old_flags.items(): ...
A context manager for setting and restoring flags.
flag_env
python
jax-ml/jax
jax/experimental/source_mapper/common.py
https://github.com/jax-ml/jax/blob/master/jax/experimental/source_mapper/common.py
Apache-2.0
def generate_sourcemaps( f, passes: Sequence[common.Pass], **pass_kwargs ) -> SourceMapGeneratorFn: """Generates a SourceMapBundle for the specified compiler passes. Args: f: The function to compile. passes: Which compiler passes to generate sourcemaps for. **pass_kwargs: Keyword arguments ...
Generates a SourceMapBundle for the specified compiler passes. Args: f: The function to compile. passes: Which compiler passes to generate sourcemaps for. **pass_kwargs: Keyword arguments for individual passes.
generate_sourcemaps
python
jax-ml/jax
jax/experimental/source_mapper/generate_map.py
https://github.com/jax-ml/jax/blob/master/jax/experimental/source_mapper/generate_map.py
Apache-2.0
def value_and_grad(fun: Callable, argnums: int | Sequence[int] = 0, has_aux=False, **kwargs) -> Callable[..., tuple[Any, Any]]: """Sparse-aware version of :func:`jax.value_and_grad` Arguments and return values are the same as :func:`jax.value_and_grad`, but when taking the gradient with respec...
Sparse-aware version of :func:`jax.value_and_grad` Arguments and return values are the same as :func:`jax.value_and_grad`, but when taking the gradient with respect to a :class:`jax.experimental.sparse` array, the gradient is computed in the subspace defined by the array's sparsity pattern. Examples: >>>...
value_and_grad
python
jax-ml/jax
jax/experimental/sparse/ad.py
https://github.com/jax-ml/jax/blob/master/jax/experimental/sparse/ad.py
Apache-2.0
def grad(fun: Callable, argnums: int | Sequence[int] = 0, has_aux=False, **kwargs) -> Callable: """Sparse-aware version of :func:`jax.grad` Arguments and return values are the same as :func:`jax.grad`, but when taking the gradient with respect to a :class:`jax.experimental.sparse` array, the gradient ...
Sparse-aware version of :func:`jax.grad` Arguments and return values are the same as :func:`jax.grad`, but when taking the gradient with respect to a :class:`jax.experimental.sparse` array, the gradient is computed in the subspace defined by the array's sparsity pattern. Examples: >>> from jax.experiment...
grad
python
jax-ml/jax
jax/experimental/sparse/ad.py
https://github.com/jax-ml/jax/blob/master/jax/experimental/sparse/ad.py
Apache-2.0
def jacfwd(fun: Callable, argnums: int | Sequence[int] = 0, has_aux: bool = False, **kwargs) -> Callable: """Sparse-aware version of :func:`jax.jacfwd` Arguments and return values are the same as :func:`jax.jacfwd`, but when taking the gradient with respect to a :class:`jax.experimental.sparse` array,...
Sparse-aware version of :func:`jax.jacfwd` Arguments and return values are the same as :func:`jax.jacfwd`, but when taking the gradient with respect to a :class:`jax.experimental.sparse` array, the gradient is computed in the subspace defined by the array's sparsity pattern. Currently this is only implemented ...
jacfwd
python
jax-ml/jax
jax/experimental/sparse/ad.py
https://github.com/jax-ml/jax/blob/master/jax/experimental/sparse/ad.py
Apache-2.0
def jacrev(fun: Callable, argnums: int | Sequence[int] = 0, has_aux: bool = False, **kwargs) -> Callable: """Sparse-aware version of :func:`jax.jacrev` Arguments and return values are the same as :func:`jax.jacrev`, but when taking the gradient with respect to a :class:`jax.experimental.sparse` array,...
Sparse-aware version of :func:`jax.jacrev` Arguments and return values are the same as :func:`jax.jacrev`, but when taking the gradient with respect to a :class:`jax.experimental.sparse` array, the gradient is computed in the subspace defined by the array's sparsity pattern. Currently this is only implemented ...
jacrev
python
jax-ml/jax
jax/experimental/sparse/ad.py
https://github.com/jax-ml/jax/blob/master/jax/experimental/sparse/ad.py
Apache-2.0
def todense(arr: JAXSparse | Array) -> Array: """Convert input to a dense matrix. If input is already dense, pass through.""" bufs, tree = tree_util.tree_flatten(arr) return todense_p.bind(*bufs, tree=tree)
Convert input to a dense matrix. If input is already dense, pass through.
todense
python
jax-ml/jax
jax/experimental/sparse/api.py
https://github.com/jax-ml/jax/blob/master/jax/experimental/sparse/api.py
Apache-2.0
def empty(shape: Shape, dtype: DTypeLike | None=None, index_dtype: DTypeLike = 'int32', sparse_format: str = 'bcoo', **kwds) -> JAXSparse: """Create an empty sparse array. Args: shape: sequence of integers giving the array shape. dtype: (optional) dtype of the array. index_dtype: (optional) d...
Create an empty sparse array. Args: shape: sequence of integers giving the array shape. dtype: (optional) dtype of the array. index_dtype: (optional) dtype of the index arrays. format: string specifying the matrix format (e.g. ['bcoo']). **kwds: additional keywords passed to the format-specific _...
empty
python
jax-ml/jax
jax/experimental/sparse/api.py
https://github.com/jax-ml/jax/blob/master/jax/experimental/sparse/api.py
Apache-2.0
def eye(N: int, M: int | None = None, k: int = 0, dtype: DTypeLike | None = None, index_dtype: DTypeLike = 'int32', sparse_format: str = 'bcoo', **kwds) -> JAXSparse: """Create 2D sparse identity matrix. Args: N: int. Number of rows in the output. M: int, optional. Number of columns in the output. ...
Create 2D sparse identity matrix. Args: N: int. Number of rows in the output. M: int, optional. Number of columns in the output. If None, defaults to `N`. k: int, optional. Index of the diagonal: 0 (the default) refers to the main diagonal, a positive value refers to an upper diagonal, and a negat...
eye
python
jax-ml/jax
jax/experimental/sparse/api.py
https://github.com/jax-ml/jax/blob/master/jax/experimental/sparse/api.py
Apache-2.0
def _bcoo_set_nse(mat: BCOO, nse: int) -> BCOO: """Return a copy of `mat` with the specified nse. Note that if nse < mat.nse, this will potentially discard data. """ nse = operator.index(nse) assert nse >= 0 if mat.nse == nse: return mat if nse <= mat.nse: data = mat.data[(*(slice(None) for i in r...
Return a copy of `mat` with the specified nse. Note that if nse < mat.nse, this will potentially discard data.
_bcoo_set_nse
python
jax-ml/jax
jax/experimental/sparse/bcoo.py
https://github.com/jax-ml/jax/blob/master/jax/experimental/sparse/bcoo.py
Apache-2.0
def _bcoo_todense(data: Array, indices: Array, *, spinfo: SparseInfo ) -> Array: """Convert batched sparse matrix to a dense matrix. Args: data : array of shape ``batch_dims + (nse,) + block_dims``. indices : array of shape ``batch_dims + (n_sparse, nse)`` spinfo : SparseInfo. In part...
Convert batched sparse matrix to a dense matrix. Args: data : array of shape ``batch_dims + (nse,) + block_dims``. indices : array of shape ``batch_dims + (n_sparse, nse)`` spinfo : SparseInfo. In particular, this includes the shape of the matrix, which is equal to ``batch_dims + sparse_dims + bloc...
_bcoo_todense
python
jax-ml/jax
jax/experimental/sparse/bcoo.py
https://github.com/jax-ml/jax/blob/master/jax/experimental/sparse/bcoo.py
Apache-2.0
def bcoo_fromdense(mat: Array, *, nse: int | None = None, n_batch: int = 0, n_dense: int = 0, index_dtype: DTypeLike = jnp.int32) -> BCOO: """Create BCOO-format sparse matrix from a dense matrix. Args: mat : array to be converted to BCOO. nse : number of specified elements in each batch ...
Create BCOO-format sparse matrix from a dense matrix. Args: mat : array to be converted to BCOO. nse : number of specified elements in each batch n_batch : number of batch dimensions (default: 0) n_dense : number of block_dimensions (default: 0) index_dtype : dtype of sparse indices (default: int...
bcoo_fromdense
python
jax-ml/jax
jax/experimental/sparse/bcoo.py
https://github.com/jax-ml/jax/blob/master/jax/experimental/sparse/bcoo.py
Apache-2.0
def _bcoo_fromdense(mat: Array, *, nse: int, n_batch: int = 0, n_dense: int = 0, index_dtype: DTypeLike = jnp.int32) -> tuple[Array, Array]: """Create BCOO-format sparse matrix from a dense matrix. Args: mat : array to be converted to BCOO, with ``ndim = n_batch + n_sparse + n_dense``. ...
Create BCOO-format sparse matrix from a dense matrix. Args: mat : array to be converted to BCOO, with ``ndim = n_batch + n_sparse + n_dense``. nse : number of specified elements in each batch n_batch : number of batch dimensions (default: 0) n_dense : number of block_dimensions (default: 0) index...
_bcoo_fromdense
python
jax-ml/jax
jax/experimental/sparse/bcoo.py
https://github.com/jax-ml/jax/blob/master/jax/experimental/sparse/bcoo.py
Apache-2.0
def bcoo_extract(sparr: BCOO, arr: ArrayLike, *, assume_unique: bool | None = None) -> BCOO: """Extract values from a dense array according to the sparse array's indices. Args: sparr : BCOO array whose indices will be used for the output. arr : ArrayLike with shape equal to self.shape assume_unique : b...
Extract values from a dense array according to the sparse array's indices. Args: sparr : BCOO array whose indices will be used for the output. arr : ArrayLike with shape equal to self.shape assume_unique : bool, defaults to sparr.unique_indices If True, extract values for every index, even if index...
bcoo_extract
python
jax-ml/jax
jax/experimental/sparse/bcoo.py
https://github.com/jax-ml/jax/blob/master/jax/experimental/sparse/bcoo.py
Apache-2.0
def bcoo_dot_general(lhs: BCOO | Array, rhs: BCOO | Array, *, dimension_numbers: DotDimensionNumbers, precision: None = None, preferred_element_type: None = None, out_sharding=None) -> BCOO | Array: """A general contraction operation....
A general contraction operation. Args: lhs: An ndarray or BCOO-format sparse array. rhs: An ndarray or BCOO-format sparse array.. dimension_numbers: a tuple of tuples of the form `((lhs_contracting_dims, rhs_contracting_dims), (lhs_batch_dims, rhs_batch_dims))`. precision: unused pref...
bcoo_dot_general
python
jax-ml/jax
jax/experimental/sparse/bcoo.py
https://github.com/jax-ml/jax/blob/master/jax/experimental/sparse/bcoo.py
Apache-2.0
def bcoo_dot_general_sampled(A: Array, B: Array, indices: Array, *, dimension_numbers: DotDimensionNumbers) -> Array: """A contraction operation with output computed at given sparse indices. Args: lhs: An ndarray. rhs: An ndarray. indices: BCOO indices. dimension_numbers: a tuple of tuples of the f...
A contraction operation with output computed at given sparse indices. Args: lhs: An ndarray. rhs: An ndarray. indices: BCOO indices. dimension_numbers: a tuple of tuples of the form `((lhs_contracting_dims, rhs_contracting_dims), (lhs_batch_dims, rhs_batch_dims))`. Returns: BCOO da...
bcoo_dot_general_sampled
python
jax-ml/jax
jax/experimental/sparse/bcoo.py
https://github.com/jax-ml/jax/blob/master/jax/experimental/sparse/bcoo.py
Apache-2.0
def bcoo_sort_indices(mat: BCOO) -> BCOO: """Sort indices of a BCOO array. Args: mat : BCOO array Returns: mat_out : BCOO array with sorted indices. """ data, indices = bcoo_sort_indices_p.bind(*mat._bufs, spinfo=mat._info) return BCOO((data, indices), shape=mat.shape, indices_sorted=True, ...
Sort indices of a BCOO array. Args: mat : BCOO array Returns: mat_out : BCOO array with sorted indices.
bcoo_sort_indices
python
jax-ml/jax
jax/experimental/sparse/bcoo.py
https://github.com/jax-ml/jax/blob/master/jax/experimental/sparse/bcoo.py
Apache-2.0
def bcoo_sum_duplicates(mat: BCOO, nse: int | None = None) -> BCOO: """Sums duplicate indices within a BCOO array, returning an array with sorted indices. Args: mat : BCOO array nse : integer (optional). The number of specified elements in the output matrix. This must be specified for bcoo_sum_duplic...
Sums duplicate indices within a BCOO array, returning an array with sorted indices. Args: mat : BCOO array nse : integer (optional). The number of specified elements in the output matrix. This must be specified for bcoo_sum_duplicates to be compatible with JIT and other JAX transformations. If no...
bcoo_sum_duplicates
python
jax-ml/jax
jax/experimental/sparse/bcoo.py
https://github.com/jax-ml/jax/blob/master/jax/experimental/sparse/bcoo.py
Apache-2.0
def bcoo_update_layout(mat: BCOO, *, n_batch: int | None = None, n_dense: int | None = None, on_inefficient: str | None = 'error') -> BCOO: """Update the storage layout (i.e. n_batch & n_dense) of a BCOO matrix. In many cases this can be done without introducing undue storage overhead. Howev...
Update the storage layout (i.e. n_batch & n_dense) of a BCOO matrix. In many cases this can be done without introducing undue storage overhead. However, increasing ``mat.n_batch`` or ``mat.n_dense`` will lead to very inefficient storage, with many explicitly-stored zeros, unless the new batch or dense dimensions...
bcoo_update_layout
python
jax-ml/jax
jax/experimental/sparse/bcoo.py
https://github.com/jax-ml/jax/blob/master/jax/experimental/sparse/bcoo.py
Apache-2.0
def bcoo_broadcast_in_dim(mat: BCOO, *, shape: Shape, broadcast_dimensions: Sequence[int], sharding=None) -> BCOO: """Expand the size and rank of a BCOO array by duplicating the data. A BCOO equivalence to jax.lax.broadcast_in_dim. Args: mat: A BCOO-format array. shape: The sha...
Expand the size and rank of a BCOO array by duplicating the data. A BCOO equivalence to jax.lax.broadcast_in_dim. Args: mat: A BCOO-format array. shape: The shape of the target array. broadcast_dimensions: The dimension in the shape of the target array which each dimension of the operand (``mat`...
bcoo_broadcast_in_dim
python
jax-ml/jax
jax/experimental/sparse/bcoo.py
https://github.com/jax-ml/jax/blob/master/jax/experimental/sparse/bcoo.py
Apache-2.0
def bcoo_concatenate(operands: Sequence[BCOO], *, dimension: int) -> BCOO: """Sparse implementation of :func:`jax.lax.concatenate` Args: operands : Sequence of BCOO arrays to concatenate. The arrays must have equal shapes, except in the `dimension` axis. Additionally, the arrays must have have equi...
Sparse implementation of :func:`jax.lax.concatenate` Args: operands : Sequence of BCOO arrays to concatenate. The arrays must have equal shapes, except in the `dimension` axis. Additionally, the arrays must have have equivalent batch, sparse, and dense dimensions. dimension : Positive integer spe...
bcoo_concatenate
python
jax-ml/jax
jax/experimental/sparse/bcoo.py
https://github.com/jax-ml/jax/blob/master/jax/experimental/sparse/bcoo.py
Apache-2.0
def bcoo_reshape(mat: BCOO, *, new_sizes: Sequence[int], dimensions: Sequence[int] | None = None, sharding=None) -> BCOO: """Sparse implementation of {func}`jax.lax.reshape`. Args: operand: BCOO array to be reshaped. new_sizes: sequence of integers specifying the resulting...
Sparse implementation of {func}`jax.lax.reshape`. Args: operand: BCOO array to be reshaped. new_sizes: sequence of integers specifying the resulting shape. The size of the final array must match the size of the input. This must be specified such that batch, sparse, and dense dimensions do not mix...
bcoo_reshape
python
jax-ml/jax
jax/experimental/sparse/bcoo.py
https://github.com/jax-ml/jax/blob/master/jax/experimental/sparse/bcoo.py
Apache-2.0
def bcoo_rev(operand, dimensions): """Sparse implementation of {func}`jax.lax.rev`""" # Check validity of dimensions via original implementation. _ = jax.jit(lax.rev, static_argnames=("dimensions",)).eval_shape( jax.ShapeDtypeStruct(operand.shape, operand.dtype), dimensions=dimensions) batch...
Sparse implementation of {func}`jax.lax.rev`
bcoo_rev
python
jax-ml/jax
jax/experimental/sparse/bcoo.py
https://github.com/jax-ml/jax/blob/master/jax/experimental/sparse/bcoo.py
Apache-2.0
def bcoo_squeeze(arr: BCOO, *, dimensions: Sequence[int]) -> BCOO: """Sparse implementation of {func}`jax.lax.squeeze`. Squeeze any number of size 1 dimensions from an array. Args: arr: BCOO array to be reshaped. dimensions: sequence of integers specifying dimensions to squeeze. Returns: out: res...
Sparse implementation of {func}`jax.lax.squeeze`. Squeeze any number of size 1 dimensions from an array. Args: arr: BCOO array to be reshaped. dimensions: sequence of integers specifying dimensions to squeeze. Returns: out: reshaped array.
bcoo_squeeze
python
jax-ml/jax
jax/experimental/sparse/bcoo.py
https://github.com/jax-ml/jax/blob/master/jax/experimental/sparse/bcoo.py
Apache-2.0
def bcoo_dynamic_slice(mat: BCOO, start_indices: Sequence[Any], slice_sizes: Sequence[int]) -> BCOO: """Sparse implementation of {func}`jax.lax.dynamic_slice`. Args: mat: BCOO array to slice. start_indices: a list of scalar indices, one per dimension. These values may be dynamic. slice_sizes: the...
Sparse implementation of {func}`jax.lax.dynamic_slice`. Args: mat: BCOO array to slice. start_indices: a list of scalar indices, one per dimension. These values may be dynamic. slice_sizes: the size of the slice. Must be a sequence of non-negative integers with length equal to `ndim(operand)`...
bcoo_dynamic_slice
python
jax-ml/jax
jax/experimental/sparse/bcoo.py
https://github.com/jax-ml/jax/blob/master/jax/experimental/sparse/bcoo.py
Apache-2.0
def bcoo_reduce_sum(mat: BCOO, *, axes: Sequence[int]) -> BCOO: """Sum array element over given axes. Args: mat: A BCOO-format array. shape: The shape of the target array. axes: A tuple or list or ndarray which contains axes of ``mat`` over which sum is performed. Returns: A BCOO-format a...
Sum array element over given axes. Args: mat: A BCOO-format array. shape: The shape of the target array. axes: A tuple or list or ndarray which contains axes of ``mat`` over which sum is performed. Returns: A BCOO-format array containing the result.
bcoo_reduce_sum
python
jax-ml/jax
jax/experimental/sparse/bcoo.py
https://github.com/jax-ml/jax/blob/master/jax/experimental/sparse/bcoo.py
Apache-2.0
def bcoo_multiply_sparse(lhs: BCOO, rhs: BCOO) -> BCOO: """An element-wise multiplication of two sparse arrays. Args: lhs: A BCOO-format array. rhs: A BCOO-format array. Returns: An BCOO-format array containing the result. """ out_data, out_indices, out_shape = _bcoo_multiply_sparse( lhs.d...
An element-wise multiplication of two sparse arrays. Args: lhs: A BCOO-format array. rhs: A BCOO-format array. Returns: An BCOO-format array containing the result.
bcoo_multiply_sparse
python
jax-ml/jax
jax/experimental/sparse/bcoo.py
https://github.com/jax-ml/jax/blob/master/jax/experimental/sparse/bcoo.py
Apache-2.0
def _bcoo_multiply_dense(data: Array, indices: Array, v: Array, *, spinfo: SparseInfo) -> Array: """Broadcasted elementwise multiplication between a BCOO array and a dense array.""" # TODO(jakevdp): the logic here is similar to bcoo_extract... can we reuse that? shape = spinfo.shape if v.ndim == 0: return l...
Broadcasted elementwise multiplication between a BCOO array and a dense array.
_bcoo_multiply_dense
python
jax-ml/jax
jax/experimental/sparse/bcoo.py
https://github.com/jax-ml/jax/blob/master/jax/experimental/sparse/bcoo.py
Apache-2.0
def fromdense(cls, mat: Array, *, nse: int | None = None, index_dtype: DTypeLike = np.int32, n_dense: int = 0, n_batch: int = 0) -> BCOO: """Create a BCOO array from a (dense) :class:`~jax.Array`.""" return bcoo_fromdense( mat, nse=nse, index_dtype=index_dtype, n_dense=n_dense, n_batch=n_b...
Create a BCOO array from a (dense) :class:`~jax.Array`.
fromdense
python
jax-ml/jax
jax/experimental/sparse/bcoo.py
https://github.com/jax-ml/jax/blob/master/jax/experimental/sparse/bcoo.py
Apache-2.0
def from_scipy_sparse(cls, mat, *, index_dtype: DTypeLike | None=None, n_dense: int = 0, n_batch: int = 0) -> BCOO: """Create a BCOO array from a :mod:`scipy.sparse` array.""" if n_dense != 0 or n_batch != 0: raise NotImplementedError("BCOO.fromscipy with nonzero n_dense/n_batch") ...
Create a BCOO array from a :mod:`scipy.sparse` array.
from_scipy_sparse
python
jax-ml/jax
jax/experimental/sparse/bcoo.py
https://github.com/jax-ml/jax/blob/master/jax/experimental/sparse/bcoo.py
Apache-2.0
def _empty(cls, shape: Shape, *, dtype: DTypeLike | None = None, index_dtype: DTypeLike = 'int32', n_dense: int = 0, n_batch: int = 0, nse: int = 0) -> BCOO: """Create an empty BCOO instance. Public method is sparse.empty().""" shape = tuple(shape) n_sparse = len(shape) - n_dense - n_batch ...
Create an empty BCOO instance. Public method is sparse.empty().
_empty
python
jax-ml/jax
jax/experimental/sparse/bcoo.py
https://github.com/jax-ml/jax/blob/master/jax/experimental/sparse/bcoo.py
Apache-2.0
def update_layout(self, *, n_batch: int | None = None, n_dense: int | None = None, on_inefficient: str = 'error') -> BCOO: """Update the storage layout (i.e. n_batch & n_dense) of a BCOO matrix. In many cases this can be done without introducing undue storage overhead. However, increasi...
Update the storage layout (i.e. n_batch & n_dense) of a BCOO matrix. In many cases this can be done without introducing undue storage overhead. However, increasing ``mat.n_batch`` or ``mat.n_dense`` will lead to very inefficient storage, with many explicitly-stored zeros, unless the new batch or dense dime...
update_layout
python
jax-ml/jax
jax/experimental/sparse/bcoo.py
https://github.com/jax-ml/jax/blob/master/jax/experimental/sparse/bcoo.py
Apache-2.0
def sum_duplicates(self, nse: int | None = None, remove_zeros: bool = True) -> BCOO: """Return a copy of the array with duplicate indices summed. Additionally, this operation will result in explicit zero entries removed, and indices being sorted in lexicographic order. Because the size of the resultin...
Return a copy of the array with duplicate indices summed. Additionally, this operation will result in explicit zero entries removed, and indices being sorted in lexicographic order. Because the size of the resulting representation depends on the values in the arrays, this operation is not compatible w...
sum_duplicates
python
jax-ml/jax
jax/experimental/sparse/bcoo.py
https://github.com/jax-ml/jax/blob/master/jax/experimental/sparse/bcoo.py
Apache-2.0
def transpose(self, axes: Sequence[int] | None = None) -> BCOO: """Create a new array containing the transpose.""" perm: list[int] = list(range(self.ndim)[::-1] if axes is None else axes) mat_T = bcoo_transpose(self, permutation=perm) shape_T = tuple(self.shape[i] for i in perm) sparse_perm = [p - s...
Create a new array containing the transpose.
transpose
python
jax-ml/jax
jax/experimental/sparse/bcoo.py
https://github.com/jax-ml/jax/blob/master/jax/experimental/sparse/bcoo.py
Apache-2.0
def _bcsr_to_bcoo(indices: jax.Array, indptr: jax.Array, *, shape: Sequence[int]) -> jax.Array: """Given BCSR (indices, indptr), return BCOO (indices).""" n_batch, _, _ = _validate_bcsr_indices(indices, indptr, shape) csr_to_coo = nfold_vmap(_csr_to_coo, n_batch) return jnp.stack(csr_to_coo(in...
Given BCSR (indices, indptr), return BCOO (indices).
_bcsr_to_bcoo
python
jax-ml/jax
jax/experimental/sparse/bcsr.py
https://github.com/jax-ml/jax/blob/master/jax/experimental/sparse/bcsr.py
Apache-2.0
def _bcoo_to_bcsr(indices: Array, *, shape: Sequence[int], index_dtype: DTypeLike) -> tuple[Array, Array]: """Given BCOO (indices), return BCSR (indices, indptr). Note: this assumes that ``indices`` are lexicographically sorted within each batch. """ n_batch, n_sparse, _, _ = bcoo._validate_b...
Given BCOO (indices), return BCSR (indices, indptr). Note: this assumes that ``indices`` are lexicographically sorted within each batch.
_bcoo_to_bcsr
python
jax-ml/jax
jax/experimental/sparse/bcsr.py
https://github.com/jax-ml/jax/blob/master/jax/experimental/sparse/bcsr.py
Apache-2.0
def bcsr_fromdense(mat: ArrayLike, *, nse: int | None = None, n_batch: int = 0, n_dense:int = 0, index_dtype: DTypeLike = jnp.int32) -> BCSR: """Create BCSR-format sparse matrix from a dense matrix. Args: mat : array to be converted to BCOO. nse : number of stored elements in each batch ...
Create BCSR-format sparse matrix from a dense matrix. Args: mat : array to be converted to BCOO. nse : number of stored elements in each batch n_batch : number of batch dimensions (default: 0) n_dense : number of dense dimensions (default: 0) index_dtype : dtype of sparse indices (default: int32)...
bcsr_fromdense
python
jax-ml/jax
jax/experimental/sparse/bcsr.py
https://github.com/jax-ml/jax/blob/master/jax/experimental/sparse/bcsr.py
Apache-2.0
def _bcsr_fromdense(mat: ArrayLike, *, nse: int, n_batch: int = 0, n_dense: int = 0, index_dtype: DTypeLike = jnp.int32) -> tuple[Array, Array, Array]: """Create BCSR-format sparse matrix from a dense matrix. Args: mat : array to be converted to BCSR, with ``ndim = n_batch + n_sparse ...
Create BCSR-format sparse matrix from a dense matrix. Args: mat : array to be converted to BCSR, with ``ndim = n_batch + n_sparse + n_dense``. nse : number of stored elements in each batch. n_batch : number of batch dimensions (default: 0) n_dense : number of dense dimensions (default: 0) i...
_bcsr_fromdense
python
jax-ml/jax
jax/experimental/sparse/bcsr.py
https://github.com/jax-ml/jax/blob/master/jax/experimental/sparse/bcsr.py
Apache-2.0
def _bcsr_todense(data: ArrayLike, indices: ArrayLike, indptr: ArrayLike, *, spinfo: SparseInfo) -> Array: """Convert batched sparse matrix to a dense matrix. Args: data : array of shape ``batch_dims + (nse,) + dense_dims``. indices : array of shape ``batch_dims + (nse,)``. indptr : a...
Convert batched sparse matrix to a dense matrix. Args: data : array of shape ``batch_dims + (nse,) + dense_dims``. indices : array of shape ``batch_dims + (nse,)``. indptr : array of shape ``batch_dims + (shape[len(batch_dims)] + 1,). spinfo : SparseInfo. In particular, this includes the shape ...
_bcsr_todense
python
jax-ml/jax
jax/experimental/sparse/bcsr.py
https://github.com/jax-ml/jax/blob/master/jax/experimental/sparse/bcsr.py
Apache-2.0
def bcsr_dot_general(lhs: BCSR | Array, rhs: Array, *, dimension_numbers: DotDimensionNumbers, precision: None = None, preferred_element_type: None = None, out_sharding=None) -> Array: """A general contraction operation. Args: ...
A general contraction operation. Args: lhs: An ndarray or BCSR-format sparse array. rhs: An ndarray or BCSR-format sparse array.. dimension_numbers: a tuple of tuples of the form `((lhs_contracting_dims, rhs_contracting_dims), (lhs_batch_dims, rhs_batch_dims))`. precision: unused pref...
bcsr_dot_general
python
jax-ml/jax
jax/experimental/sparse/bcsr.py
https://github.com/jax-ml/jax/blob/master/jax/experimental/sparse/bcsr.py
Apache-2.0
def bcsr_concatenate(operands: Sequence[BCSR], *, dimension: int) -> BCSR: """Sparse implementation of :func:`jax.lax.concatenate` Args: operands : Sequence of BCSR arrays to concatenate. The arrays must have equal shapes, except in the `dimension` axis. Additionally, the arrays must have have equi...
Sparse implementation of :func:`jax.lax.concatenate` Args: operands : Sequence of BCSR arrays to concatenate. The arrays must have equal shapes, except in the `dimension` axis. Additionally, the arrays must have have equivalent batch, sparse, and dense dimensions. dimension : Positive integer spe...
bcsr_concatenate
python
jax-ml/jax
jax/experimental/sparse/bcsr.py
https://github.com/jax-ml/jax/blob/master/jax/experimental/sparse/bcsr.py
Apache-2.0
def _empty(cls, shape, *, dtype=None, index_dtype='int32', n_dense=0, n_batch=0, nse=0): """Create an empty BCSR instance. Public method is sparse.empty().""" shape = tuple(shape) if n_dense < 0 or n_batch < 0 or nse < 0: raise ValueError(f"Invalid inputs: {shape=}, {n_dense=}, {n_batch=}...
Create an empty BCSR instance. Public method is sparse.empty().
_empty
python
jax-ml/jax
jax/experimental/sparse/bcsr.py
https://github.com/jax-ml/jax/blob/master/jax/experimental/sparse/bcsr.py
Apache-2.0
def fromdense(cls, mat, *, nse=None, index_dtype=np.int32, n_dense=0, n_batch=0): """Create a BCSR array from a (dense) :class:`Array`.""" return bcsr_fromdense(mat, nse=nse, index_dtype=index_dtype, n_dense=n_dense, n_batch=n_batch)
Create a BCSR array from a (dense) :class:`Array`.
fromdense
python
jax-ml/jax
jax/experimental/sparse/bcsr.py
https://github.com/jax-ml/jax/blob/master/jax/experimental/sparse/bcsr.py
Apache-2.0
def from_scipy_sparse(cls, mat, *, index_dtype=None, n_dense=0, n_batch=0): """Create a BCSR array from a :mod:`scipy.sparse` array.""" if n_dense != 0 or n_batch != 0: raise NotImplementedError("BCSR from_scipy_sparse with nonzero n_dense/n_batch.") if mat.ndim != 2: raise ValueError(f"BCSR fr...
Create a BCSR array from a :mod:`scipy.sparse` array.
from_scipy_sparse
python
jax-ml/jax
jax/experimental/sparse/bcsr.py
https://github.com/jax-ml/jax/blob/master/jax/experimental/sparse/bcsr.py
Apache-2.0
def _sort_indices(self) -> COO: """Return a copy of the COO matrix with sorted indices. The matrix is sorted by row indices and column indices per row. If self._rows_sorted is True, this returns ``self`` without a copy. """ # TODO(jakevdp): would be benefit from lowering this to cusparse sort_rows ...
Return a copy of the COO matrix with sorted indices. The matrix is sorted by row indices and column indices per row. If self._rows_sorted is True, this returns ``self`` without a copy.
_sort_indices
python
jax-ml/jax
jax/experimental/sparse/coo.py
https://github.com/jax-ml/jax/blob/master/jax/experimental/sparse/coo.py
Apache-2.0
def _empty(cls, shape: Sequence[int], *, dtype: DTypeLike | None = None, index_dtype: DTypeLike = 'int32') -> COO: """Create an empty COO instance. Public method is sparse.empty().""" shape = tuple(shape) if len(shape) != 2: raise ValueError(f"COO must have ndim=2; got {shape=}") data...
Create an empty COO instance. Public method is sparse.empty().
_empty
python
jax-ml/jax
jax/experimental/sparse/coo.py
https://github.com/jax-ml/jax/blob/master/jax/experimental/sparse/coo.py
Apache-2.0
def coo_fromdense(mat: Array, *, nse: int | None = None, index_dtype: DTypeLike = jnp.int32) -> COO: """Create a COO-format sparse matrix from a dense matrix. Args: mat : array to be converted to COO. nse : number of specified entries in ``mat``. If not specified, it will be computed from the input m...
Create a COO-format sparse matrix from a dense matrix. Args: mat : array to be converted to COO. nse : number of specified entries in ``mat``. If not specified, it will be computed from the input matrix. index_dtype : dtype of sparse indices Returns: mat_coo : COO representation of the matri...
coo_fromdense
python
jax-ml/jax
jax/experimental/sparse/coo.py
https://github.com/jax-ml/jax/blob/master/jax/experimental/sparse/coo.py
Apache-2.0
def _coo_fromdense(mat: Array, *, nse: int, index_dtype: DTypeLike = jnp.int32) -> tuple[Array, Array, Array]: """Create COO-format sparse matrix from a dense matrix. Args: mat : array to be converted to COO. nse : number of specified entries in ``mat`` index_dtype : dtype of sparse indices Returns:...
Create COO-format sparse matrix from a dense matrix. Args: mat : array to be converted to COO. nse : number of specified entries in ``mat`` index_dtype : dtype of sparse indices Returns: data : array of shape ``(nse,)`` and dtype ``mat.dtype`` row : array of shape ``(nse,)`` and dtype ``index_...
_coo_fromdense
python
jax-ml/jax
jax/experimental/sparse/coo.py
https://github.com/jax-ml/jax/blob/master/jax/experimental/sparse/coo.py
Apache-2.0
def coo_matvec(mat: COO, v: Array, transpose: bool = False) -> Array: """Product of COO sparse matrix and a dense vector. Args: mat : COO matrix v : one-dimensional array of size ``(shape[0] if transpose else shape[1],)`` and dtype ``mat.dtype`` transpose : boolean specifying whether to transpose...
Product of COO sparse matrix and a dense vector. Args: mat : COO matrix v : one-dimensional array of size ``(shape[0] if transpose else shape[1],)`` and dtype ``mat.dtype`` transpose : boolean specifying whether to transpose the sparse matrix before computing. Returns: y : array of sha...
coo_matvec
python
jax-ml/jax
jax/experimental/sparse/coo.py
https://github.com/jax-ml/jax/blob/master/jax/experimental/sparse/coo.py
Apache-2.0
def coo_matmat(mat: COO, B: Array, *, transpose: bool = False) -> Array: """Product of COO sparse matrix and a dense matrix. Args: mat : COO matrix B : array of shape ``(mat.shape[0] if transpose else mat.shape[1], cols)`` and dtype ``mat.dtype`` transpose : boolean specifying whether to transpos...
Product of COO sparse matrix and a dense matrix. Args: mat : COO matrix B : array of shape ``(mat.shape[0] if transpose else mat.shape[1], cols)`` and dtype ``mat.dtype`` transpose : boolean specifying whether to transpose the sparse matrix before computing. Returns: C : array of shape...
coo_matmat
python
jax-ml/jax
jax/experimental/sparse/coo.py
https://github.com/jax-ml/jax/blob/master/jax/experimental/sparse/coo.py
Apache-2.0
def _empty(cls, shape, *, dtype=None, index_dtype='int32'): """Create an empty CSR instance. Public method is sparse.empty().""" shape = tuple(shape) if len(shape) != 2: raise ValueError(f"CSR must have ndim=2; got {shape=}") data = jnp.empty(0, dtype) indices = jnp.empty(0, index_dtype) i...
Create an empty CSR instance. Public method is sparse.empty().
_empty
python
jax-ml/jax
jax/experimental/sparse/csr.py
https://github.com/jax-ml/jax/blob/master/jax/experimental/sparse/csr.py
Apache-2.0
def _empty(cls, shape, *, dtype=None, index_dtype='int32'): """Create an empty CSC instance. Public method is sparse.empty().""" shape = tuple(shape) if len(shape) != 2: raise ValueError(f"CSC must have ndim=2; got {shape=}") data = jnp.empty(0, dtype) indices = jnp.empty(0, index_dtype) i...
Create an empty CSC instance. Public method is sparse.empty().
_empty
python
jax-ml/jax
jax/experimental/sparse/csr.py
https://github.com/jax-ml/jax/blob/master/jax/experimental/sparse/csr.py
Apache-2.0
def csr_fromdense(mat: Array, *, nse: int | None = None, index_dtype: DTypeLike = np.int32) -> CSR: """Create a CSR-format sparse matrix from a dense matrix. Args: mat : array to be converted to CSR. nse : number of specified entries in ``mat``. If not specified, it will be computed from the input ma...
Create a CSR-format sparse matrix from a dense matrix. Args: mat : array to be converted to CSR. nse : number of specified entries in ``mat``. If not specified, it will be computed from the input matrix. index_dtype : dtype of sparse indices Returns: mat_coo : CSR representation of the matri...
csr_fromdense
python
jax-ml/jax
jax/experimental/sparse/csr.py
https://github.com/jax-ml/jax/blob/master/jax/experimental/sparse/csr.py
Apache-2.0
def _csr_fromdense(mat: Array, *, nse: int, index_dtype: DTypeLike = np.int32) -> tuple[Array, Array, Array]: """Create CSR-format sparse matrix from a dense matrix. Args: mat : array to be converted to CSR. nse : number of specified entries in ``mat`` index_dtype : dtype of sparse indices Returns: ...
Create CSR-format sparse matrix from a dense matrix. Args: mat : array to be converted to CSR. nse : number of specified entries in ``mat`` index_dtype : dtype of sparse indices Returns: data : array of shape ``(nse,)`` and dtype ``mat.dtype``. indices : array of shape ``(nse,)`` and dtype ``i...
_csr_fromdense
python
jax-ml/jax
jax/experimental/sparse/csr.py
https://github.com/jax-ml/jax/blob/master/jax/experimental/sparse/csr.py
Apache-2.0
def csr_matvec(mat: CSR, v: Array, transpose: bool = False) -> Array: """Product of CSR sparse matrix and a dense vector. Args: mat : CSR matrix v : one-dimensional array of size ``(shape[0] if transpose else shape[1],)`` and dtype ``mat.dtype`` transpose : boolean specifying whether to transpose...
Product of CSR sparse matrix and a dense vector. Args: mat : CSR matrix v : one-dimensional array of size ``(shape[0] if transpose else shape[1],)`` and dtype ``mat.dtype`` transpose : boolean specifying whether to transpose the sparse matrix before computing. Returns: y : array of sha...
csr_matvec
python
jax-ml/jax
jax/experimental/sparse/csr.py
https://github.com/jax-ml/jax/blob/master/jax/experimental/sparse/csr.py
Apache-2.0
def csr_matmat(mat: CSR, B: Array, *, transpose: bool = False) -> Array: """Product of CSR sparse matrix and a dense matrix. Args: mat : CSR matrix B : array of shape ``(mat.shape[0] if transpose else mat.shape[1], cols)`` and dtype ``mat.dtype`` transpose : boolean specifying whether to transpos...
Product of CSR sparse matrix and a dense matrix. Args: mat : CSR matrix B : array of shape ``(mat.shape[0] if transpose else mat.shape[1], cols)`` and dtype ``mat.dtype`` transpose : boolean specifying whether to transpose the sparse matrix before computing. Returns: C : array of shape...
csr_matmat
python
jax-ml/jax
jax/experimental/sparse/csr.py
https://github.com/jax-ml/jax/blob/master/jax/experimental/sparse/csr.py
Apache-2.0
def _csr_matmat(data: Array, indices: Array, indptr: Array, B: Array, *, shape: Shape, transpose: bool = False) -> Array: """Product of CSR sparse matrix and a dense matrix. Args: data : array of shape ``(nse,)``. indices : array of shape ``(nse,)`` indptr : array of shape ``(shape[0] +...
Product of CSR sparse matrix and a dense matrix. Args: data : array of shape ``(nse,)``. indices : array of shape ``(nse,)`` indptr : array of shape ``(shape[0] + 1,)`` and dtype ``indices.dtype`` B : array of shape ``(shape[0] if transpose else shape[1], cols)`` and dtype ``data.dtype`` sh...
_csr_matmat
python
jax-ml/jax
jax/experimental/sparse/csr.py
https://github.com/jax-ml/jax/blob/master/jax/experimental/sparse/csr.py
Apache-2.0
def _svqb(X): """Derives a truncated orthonormal basis for `X`. SVQB [1] is an accelerator-friendly orthonormalization procedure, which squares the matrix `C = X.T @ X` and computes an eigenbasis for a smaller `(k, k)` system; this offloads most of the work in orthonormalization to the first multiply when `n...
Derives a truncated orthonormal basis for `X`. SVQB [1] is an accelerator-friendly orthonormalization procedure, which squares the matrix `C = X.T @ X` and computes an eigenbasis for a smaller `(k, k)` system; this offloads most of the work in orthonormalization to the first multiply when `n` is large. Impo...
_svqb
python
jax-ml/jax
jax/experimental/sparse/linalg.py
https://github.com/jax-ml/jax/blob/master/jax/experimental/sparse/linalg.py
Apache-2.0
def _project_out(basis, U): """Derives component of U in the orthogonal complement of basis. This method iteratively subtracts out the basis component and orthonormalizes the remainder. To an extent, these two operations can oppose each other when the remainder norm is near-zero (since normalization enlarges a...
Derives component of U in the orthogonal complement of basis. This method iteratively subtracts out the basis component and orthonormalizes the remainder. To an extent, these two operations can oppose each other when the remainder norm is near-zero (since normalization enlarges a vector which may possibly lie ...
_project_out
python
jax-ml/jax
jax/experimental/sparse/linalg.py
https://github.com/jax-ml/jax/blob/master/jax/experimental/sparse/linalg.py
Apache-2.0
def _rayleigh_ritz_orth(A, S): """Solve the Rayleigh-Ritz problem for `A` projected to `S`. Solves the local eigenproblem for `A` within the subspace `S`, which is assumed to be orthonormal (with zero columns allowed), identifying `w, V` satisfying (1) `S.T A S V ~= diag(w) V` (2) `V` is standard orthonor...
Solve the Rayleigh-Ritz problem for `A` projected to `S`. Solves the local eigenproblem for `A` within the subspace `S`, which is assumed to be orthonormal (with zero columns allowed), identifying `w, V` satisfying (1) `S.T A S V ~= diag(w) V` (2) `V` is standard orthonormal Note that (2) is simplified t...
_rayleigh_ritz_orth
python
jax-ml/jax
jax/experimental/sparse/linalg.py
https://github.com/jax-ml/jax/blob/master/jax/experimental/sparse/linalg.py
Apache-2.0
def _extend_basis(X, m): """Extend the basis of `X` with `m` addition dimensions. Given an orthonormal `X` of dimension `k`, a typical strategy for deriving an extended basis is to generate a random one and project it out. We instead generate a basis using block householder reflectors [1] [2] to leverage th...
Extend the basis of `X` with `m` addition dimensions. Given an orthonormal `X` of dimension `k`, a typical strategy for deriving an extended basis is to generate a random one and project it out. We instead generate a basis using block householder reflectors [1] [2] to leverage the favorable properties of dete...
_extend_basis
python
jax-ml/jax
jax/experimental/sparse/linalg.py
https://github.com/jax-ml/jax/blob/master/jax/experimental/sparse/linalg.py
Apache-2.0
def nm_spmm( lhs: Array, rhs: Array, metadata: Array, dimension_numbers: DotDimensionNumbers = (((1,), (0,)), (tuple(), tuple())), sparse_operand_idx: int = 0, output_dtype: DTypeLike = jnp.bfloat16, ) -> Array: """Dot operation where one of the operands has N:M sparsity. Args: lhs: An ...
Dot operation where one of the operands has N:M sparsity. Args: lhs: An ndarray (first dot operand). rhs: An ndarray (second dot operand). metadata: An ndarray with structured sparsity metadata for the contracting dimension. For 2:4 sparsity it should contain (N=2) two-bit index values for ea...
nm_spmm
python
jax-ml/jax
jax/experimental/sparse/nm.py
https://github.com/jax-ml/jax/blob/master/jax/experimental/sparse/nm.py
Apache-2.0
def random_bcoo(key, shape, *, dtype=jnp.float_, indices_dtype=None, nse=0.2, n_batch=0, n_dense=0, unique_indices=True, sorted_indices=False, generator=random.uniform, **kwds): """Generate a random BCOO matrix. Args: key : PRNG key to be passed to ``generator`` function. sh...
Generate a random BCOO matrix. Args: key : PRNG key to be passed to ``generator`` function. shape : tuple specifying the shape of the array to be generated. dtype : dtype of the array to be generated. indices_dtype: dtype of the BCOO indices. nse : number of specified elements in the matrix, or i...
random_bcoo
python
jax-ml/jax
jax/experimental/sparse/random.py
https://github.com/jax-ml/jax/blob/master/jax/experimental/sparse/random.py
Apache-2.0
def _CheckAgainstDense(self, dense_op, sparse_op, args_maker, check_jit=True, check_dtypes=True, tol=None, atol=None, rtol=None, canonicalize_dtypes=True): """Check an operation against a dense equivalent""" sparse_args = args_maker() dense_args = tree_util....
Check an operation against a dense equivalent
_CheckAgainstDense
python
jax-ml/jax
jax/experimental/sparse/test_util.py
https://github.com/jax-ml/jax/blob/master/jax/experimental/sparse/test_util.py
Apache-2.0
def iter_subsets(s: Sequence) -> Iterable[tuple]: """Return an iterator over all subsets of a sequence s""" return itertools.chain.from_iterable( itertools.combinations(s, n) for n in range(len(s) + 1) )
Return an iterator over all subsets of a sequence s
iter_subsets
python
jax-ml/jax
jax/experimental/sparse/test_util.py
https://github.com/jax-ml/jax/blob/master/jax/experimental/sparse/test_util.py
Apache-2.0
def data(self, spvalue: SparsifyValue) -> Array: """Get the data buffer associated with a SparsifyValue.""" if spvalue.data_ref is None: raise RuntimeError("Internal: requested data from spvalue with data_ref=None") return self._buffers[spvalue.data_ref]
Get the data buffer associated with a SparsifyValue.
data
python
jax-ml/jax
jax/experimental/sparse/transform.py
https://github.com/jax-ml/jax/blob/master/jax/experimental/sparse/transform.py
Apache-2.0
def indices(self, spvalue: SparsifyValue) -> Array: """Get the indices buffer associated with a SparsifyValue.""" if spvalue.indices_ref is None: raise RuntimeError("Internal: requested indices from spvalue with indices_ref=None") return self._buffers[spvalue.indices_ref]
Get the indices buffer associated with a SparsifyValue.
indices
python
jax-ml/jax
jax/experimental/sparse/transform.py
https://github.com/jax-ml/jax/blob/master/jax/experimental/sparse/transform.py
Apache-2.0
def indptr(self, spvalue: SparsifyValue) -> Array: """Get the BCSR indptr buffer associated with a SparsifyValue.""" if spvalue.indptr_ref is None: raise RuntimeError("Internal: requested indices from spvalue with indptr_ref=None") return self._buffers[spvalue.indptr_ref]
Get the BCSR indptr buffer associated with a SparsifyValue.
indptr
python
jax-ml/jax
jax/experimental/sparse/transform.py
https://github.com/jax-ml/jax/blob/master/jax/experimental/sparse/transform.py
Apache-2.0
def sparse(self, shape, data=None, indices=None, indptr=None, *, data_ref=None, indices_ref=None, indptr_ref=None, indices_sorted=False, unique_indices=False): """Add a new sparse array to the sparsify environment.""" if data is not None: assert data_ref is None data_ref = ...
Add a new sparse array to the sparsify environment.
sparse
python
jax-ml/jax
jax/experimental/sparse/transform.py
https://github.com/jax-ml/jax/blob/master/jax/experimental/sparse/transform.py
Apache-2.0