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 tf_hlo(self, f_tf, args_tf: Sequence[Any]) -> str: """Get the unoptimized HLO from TF""" f_tf_fun = tf.function(f_tf, autograph=False, jit_compile=True) logging.info("[%s] Got TF graph %s", self._testMethodName, f_tf_fun.get_concrete_function(*args_tf).graph.as_graph_de...
Get the unoptimized HLO from TF
tf_hlo
python
jax-ml/jax
jax/experimental/jax2tf/tests/sharding_test.py
https://github.com/jax-ml/jax/blob/master/jax/experimental/jax2tf/tests/sharding_test.py
Apache-2.0
def check_sharding(self, f_tf, args_tf: Sequence[Any], *, checks=()): """Check the sharding in TF. Args: f_tf: the TF callable args_tf: the TF args checks: a list of tuples. The first element is a regular expression, the second element is an integer representing t...
Check the sharding in TF. Args: f_tf: the TF callable args_tf: the TF args checks: a list of tuples. The first element is a regular expression, the second element is an integer representing the expected number of occurrences of the regular expression in the TF HLO. As a special ca...
check_sharding
python
jax-ml/jax
jax/experimental/jax2tf/tests/sharding_test.py
https://github.com/jax-ml/jax/blob/master/jax/experimental/jax2tf/tests/sharding_test.py
Apache-2.0
def assertDtypesMatch(self, x, y, *, canonicalize_dtypes=True): """Compares dtypes across JAX and TF dtypes. Overrides super method.""" def to_numpy_dtype(dt): return dt if isinstance(dt, np.dtype) else dt.as_numpy_dtype if not config.enable_x64.value and canonicalize_dtypes: self.assertEqual(...
Compares dtypes across JAX and TF dtypes. Overrides super method.
assertDtypesMatch
python
jax-ml/jax
jax/experimental/jax2tf/tests/tf_test_util.py
https://github.com/jax-ml/jax/blob/master/jax/experimental/jax2tf/tests/tf_test_util.py
Apache-2.0
def TransformConvertAndCompare(self, func: Callable, arg, transform: str | None): """Like ConvertAndCompare but first applies a transformation. `func` must be a function from one argument to one result. `arg` is the argument before the transformation. `transform` can b...
Like ConvertAndCompare but first applies a transformation. `func` must be a function from one argument to one result. `arg` is the argument before the transformation. `transform` can be None, "jit", "jvp", "grad", "vmap", "jvp_vmap", "grad_vmap"
TransformConvertAndCompare
python
jax-ml/jax
jax/experimental/jax2tf/tests/tf_test_util.py
https://github.com/jax-ml/jax/blob/master/jax/experimental/jax2tf/tests/tf_test_util.py
Apache-2.0
def CheckOpMetadata(self, jax_fun, x, expected: Sequence[OpMetadataGraph], include_xla_op_metadata=True): """Checks that the tf.Graph obtained by converting `jax_fun` for argument `x` contains all the given OpMetadata. If `not include_xla_op_metadata` then disabl...
Checks that the tf.Graph obtained by converting `jax_fun` for argument `x` contains all the given OpMetadata. If `not include_xla_op_metadata` then disable the generation of the OpMetadata attributes, and check that we don't find any ops with metadata.
CheckOpMetadata
python
jax-ml/jax
jax/experimental/jax2tf/tests/tf_test_util.py
https://github.com/jax-ml/jax/blob/master/jax/experimental/jax2tf/tests/tf_test_util.py
Apache-2.0
def __call__(self, x): """Define the convolutional network architecture. Architecture originates from "Human-level control through deep reinforcement learning.", Nature 518, no. 7540 (2015): 529-533. Note that this is different than the one from "Playing atari with deep reinforcement learning." ar...
Define the convolutional network architecture. Architecture originates from "Human-level control through deep reinforcement learning.", Nature 518, no. 7540 (2015): 529-533. Note that this is different than the one from "Playing atari with deep reinforcement learning." arxiv.org/abs/1312.5602 (2013) ...
__call__
python
jax-ml/jax
jax/experimental/jax2tf/tests/flax_models/actor_critic.py
https://github.com/jax-ml/jax/blob/master/jax/experimental/jax2tf/tests/flax_models/actor_critic.py
Apache-2.0
def flip_sequences(inputs: Array, lengths: Array) -> Array: """Flips a sequence of inputs along the time dimension. This function can be used to prepare inputs for the reverse direction of a bidirectional LSTM. It solves the issue that, when naively flipping multiple padded sequences stored in a matrix, the fi...
Flips a sequence of inputs along the time dimension. This function can be used to prepare inputs for the reverse direction of a bidirectional LSTM. It solves the issue that, when naively flipping multiple padded sequences stored in a matrix, the first elements would be padding values for those sequences that w...
flip_sequences
python
jax-ml/jax
jax/experimental/jax2tf/tests/flax_models/bilstm_classifier.py
https://github.com/jax-ml/jax/blob/master/jax/experimental/jax2tf/tests/flax_models/bilstm_classifier.py
Apache-2.0
def __call__(self, inputs: Array, deterministic: bool | None = None) -> Array: """Embeds the input sequences and applies word dropout and dropout. Args: inputs: Batch of input token ID sequences <int64>[batch_size, seq_length]. deterministic: Disables dropout when set to True. R...
Embeds the input sequences and applies word dropout and dropout. Args: inputs: Batch of input token ID sequences <int64>[batch_size, seq_length]. deterministic: Disables dropout when set to True. Returns: The embedded inputs, shape: <float32>[batch_size, seq_length, embedding_size]. ...
__call__
python
jax-ml/jax
jax/experimental/jax2tf/tests/flax_models/bilstm_classifier.py
https://github.com/jax-ml/jax/blob/master/jax/experimental/jax2tf/tests/flax_models/bilstm_classifier.py
Apache-2.0
def __call__(self, inputs: Array, deterministic: bool | None = None): """Applies the MLP to the last dimension of the inputs. Args: inputs: <float32>[batch_size, ..., input_features]. deterministic: Disables dropout when set to True. Returns: The MLP output <float32>[batch_size, ..., out...
Applies the MLP to the last dimension of the inputs. Args: inputs: <float32>[batch_size, ..., input_features]. deterministic: Disables dropout when set to True. Returns: The MLP output <float32>[batch_size, ..., output_size]
__call__
python
jax-ml/jax
jax/experimental/jax2tf/tests/flax_models/bilstm_classifier.py
https://github.com/jax-ml/jax/blob/master/jax/experimental/jax2tf/tests/flax_models/bilstm_classifier.py
Apache-2.0
def __call__(self, keys: Array, mask: Array) -> Array: """Applies model to the input keys and mask. Args: keys: The inputs for which to compute an attention score. Shape: <float32>[batch_size, seq_length, embeddings_size]. mask: A mask that determinines which values in `keys` are valid. On...
Applies model to the input keys and mask. Args: keys: The inputs for which to compute an attention score. Shape: <float32>[batch_size, seq_length, embeddings_size]. mask: A mask that determinines which values in `keys` are valid. Only values for which the mask is True will get non-zero...
__call__
python
jax-ml/jax
jax/experimental/jax2tf/tests/flax_models/bilstm_classifier.py
https://github.com/jax-ml/jax/blob/master/jax/experimental/jax2tf/tests/flax_models/bilstm_classifier.py
Apache-2.0
def __call__(self, encoded_inputs: Array, lengths: Array, deterministic: bool | None = None) -> Array: """Applies model to the encoded inputs. Args: encoded_inputs: The inputs (e.g., sentences) that have already been encoded by some encoder, e.g., an LSTM. <float32>[batch_size, ...
Applies model to the encoded inputs. Args: encoded_inputs: The inputs (e.g., sentences) that have already been encoded by some encoder, e.g., an LSTM. <float32>[batch_size, seq_length, encoded_inputs_size]. lengths: The lengths of the inputs. <int64>[batch_size]. deterministic: Di...
__call__
python
jax-ml/jax
jax/experimental/jax2tf/tests/flax_models/bilstm_classifier.py
https://github.com/jax-ml/jax/blob/master/jax/experimental/jax2tf/tests/flax_models/bilstm_classifier.py
Apache-2.0
def __call__(self, token_ids: Array, lengths: Array, deterministic: bool | None = None) -> Array: """Embeds the token IDs, encodes them, and classifies with attention.""" embedded_inputs = self.embed_token_ids( token_ids, deterministic=deterministic) logits = self.logits_from_embedded...
Embeds the token IDs, encodes them, and classifies with attention.
__call__
python
jax-ml/jax
jax/experimental/jax2tf/tests/flax_models/bilstm_classifier.py
https://github.com/jax-ml/jax/blob/master/jax/experimental/jax2tf/tests/flax_models/bilstm_classifier.py
Apache-2.0
def add_graphs_tuples(graphs: jraph.GraphsTuple, other_graphs: jraph.GraphsTuple) -> jraph.GraphsTuple: """Adds the nodes, edges and global features from other_graphs to graphs.""" return graphs._replace( nodes=graphs.nodes + other_graphs.nodes, edges=graphs.edges + other_graphs.ed...
Adds the nodes, edges and global features from other_graphs to graphs.
add_graphs_tuples
python
jax-ml/jax
jax/experimental/jax2tf/tests/flax_models/gnn.py
https://github.com/jax-ml/jax/blob/master/jax/experimental/jax2tf/tests/flax_models/gnn.py
Apache-2.0
def __call__(self, inputs: Array) -> tuple[Array, Array]: """Applies the decoder model. Args: inputs: [batch_size, max_output_len-1, vocab_size] Contains the inputs to the decoder at each time step (only used when not using teacher forcing). Since each token at position i is fed as input ...
Applies the decoder model. Args: inputs: [batch_size, max_output_len-1, vocab_size] Contains the inputs to the decoder at each time step (only used when not using teacher forcing). Since each token at position i is fed as input to the decoder at position i+1, the last token is not pro...
__call__
python
jax-ml/jax
jax/experimental/jax2tf/tests/flax_models/seq2seq_lstm.py
https://github.com/jax-ml/jax/blob/master/jax/experimental/jax2tf/tests/flax_models/seq2seq_lstm.py
Apache-2.0
def __call__(self, encoder_inputs: Array, decoder_inputs: Array) -> tuple[Array, Array]: """Applies the seq2seq model. Args: encoder_inputs: [batch_size, max_input_length, vocab_size]. padded batch of input sequences to encode. decoder_inputs: [batch_size, max_output_length, ...
Applies the seq2seq model. Args: encoder_inputs: [batch_size, max_input_length, vocab_size]. padded batch of input sequences to encode. decoder_inputs: [batch_size, max_output_length, vocab_size]. padded batch of expected decoded sequences for teacher forcing. When sampling (i.e...
__call__
python
jax-ml/jax
jax/experimental/jax2tf/tests/flax_models/seq2seq_lstm.py
https://github.com/jax-ml/jax/blob/master/jax/experimental/jax2tf/tests/flax_models/seq2seq_lstm.py
Apache-2.0
def shift_inputs(x, segment_ids=None, axis=1): """Shift inputs and replace EOS by 0 for packed inputs.""" shifted = shift_right(x, axis=axis) # For packed targets, the first shifted token of a new sequence is made # 0, rather than being the EOS token for the last sequence. if segment_ids is not None: shif...
Shift inputs and replace EOS by 0 for packed inputs.
shift_inputs
python
jax-ml/jax
jax/experimental/jax2tf/tests/flax_models/transformer_lm1b.py
https://github.com/jax-ml/jax/blob/master/jax/experimental/jax2tf/tests/flax_models/transformer_lm1b.py
Apache-2.0
def __call__(self, inputs, decoder_mask=None, encoder_decoder_mask=None): """Applies EncoderDecoder1DBlock module. Args: inputs: input data for decoder decoder_mask: decoder self-attention mask. encoder_decoder_mask: encoder-decoder attention mask....
Applies EncoderDecoder1DBlock module. Args: inputs: input data for decoder decoder_mask: decoder self-attention mask. encoder_decoder_mask: encoder-decoder attention mask. Returns: output after transformer encoder-decoder block.
__call__
python
jax-ml/jax
jax/experimental/jax2tf/tests/flax_models/transformer_lm1b.py
https://github.com/jax-ml/jax/blob/master/jax/experimental/jax2tf/tests/flax_models/transformer_lm1b.py
Apache-2.0
def __call__(self, inputs, inputs_positions=None, inputs_segmentation=None, decoder_mask=None, encoder_decoder_mask=None): """Applies Transformer model on the inputs. Args: encoded: encoded input data from encoder. inputs: i...
Applies Transformer model on the inputs. Args: encoded: encoded input data from encoder. inputs: input data. inputs_positions: input subsequence positions for packed examples. inputs_segmentation: input segmentation info for packed examples. decoder_mask: decoder self-attention mask. ...
__call__
python
jax-ml/jax
jax/experimental/jax2tf/tests/flax_models/transformer_lm1b.py
https://github.com/jax-ml/jax/blob/master/jax/experimental/jax2tf/tests/flax_models/transformer_lm1b.py
Apache-2.0
def __call__(self, inputs, inputs_positions=None, inputs_segmentation=None): """Applies TransformerLM on the inputs. Args: inputs: target data. inputs_positions: input subsequence positions for packed examples. inputs_segmentation: input segmentati...
Applies TransformerLM on the inputs. Args: inputs: target data. inputs_positions: input subsequence positions for packed examples. inputs_segmentation: input segmentation info for packed examples. Returns: logits array from transformer decoder.
__call__
python
jax-ml/jax
jax/experimental/jax2tf/tests/flax_models/transformer_lm1b.py
https://github.com/jax-ml/jax/blob/master/jax/experimental/jax2tf/tests/flax_models/transformer_lm1b.py
Apache-2.0
def sinusoidal_init(max_len=2048): """1D Sinusoidal Position Embedding Initializer. Args: max_len: maximum possible length for the input Returns: output: init function returning `(1, max_len, d_feature)` """ def init(key, shape, dtype=np.float32): """Sinusoidal init.""" del key, dtype ...
1D Sinusoidal Position Embedding Initializer. Args: max_len: maximum possible length for the input Returns: output: init function returning `(1, max_len, d_feature)`
sinusoidal_init
python
jax-ml/jax
jax/experimental/jax2tf/tests/flax_models/transformer_nlp_seq.py
https://github.com/jax-ml/jax/blob/master/jax/experimental/jax2tf/tests/flax_models/transformer_nlp_seq.py
Apache-2.0
def __call__(self, inputs): """Applies AddPositionEmbs module. By default this layer uses a fixed sinusoidal embedding table. If a learned position embedding is desired, pass an initializer to posemb_init in the configuration. Args: inputs: input data. Returns: output: `(bs, times...
Applies AddPositionEmbs module. By default this layer uses a fixed sinusoidal embedding table. If a learned position embedding is desired, pass an initializer to posemb_init in the configuration. Args: inputs: input data. Returns: output: `(bs, timesteps, in_dim)`
__call__
python
jax-ml/jax
jax/experimental/jax2tf/tests/flax_models/transformer_nlp_seq.py
https://github.com/jax-ml/jax/blob/master/jax/experimental/jax2tf/tests/flax_models/transformer_nlp_seq.py
Apache-2.0
def __call__(self, inputs, deterministic): """Applies Encoder1DBlock module. Args: inputs: input data. deterministic: if true dropout is applied otherwise not. Returns: output after transformer encoder block. """ config = self.config # Attention block. assert inputs.ndim...
Applies Encoder1DBlock module. Args: inputs: input data. deterministic: if true dropout is applied otherwise not. Returns: output after transformer encoder block.
__call__
python
jax-ml/jax
jax/experimental/jax2tf/tests/flax_models/transformer_nlp_seq.py
https://github.com/jax-ml/jax/blob/master/jax/experimental/jax2tf/tests/flax_models/transformer_nlp_seq.py
Apache-2.0
def __call__(self, inputs, *, train): """Applies Transformer model on the inputs. Args: inputs: input data train: if it is training. Returns: output of a transformer encoder. """ assert inputs.ndim == 2 # (batch, len) config = self.config x = inputs.astype('int32') ...
Applies Transformer model on the inputs. Args: inputs: input data train: if it is training. Returns: output of a transformer encoder.
__call__
python
jax-ml/jax
jax/experimental/jax2tf/tests/flax_models/transformer_nlp_seq.py
https://github.com/jax-ml/jax/blob/master/jax/experimental/jax2tf/tests/flax_models/transformer_nlp_seq.py
Apache-2.0
def shift_right(x, axis=1): """Shift the input to the right by padding on axis 1.""" pad_widths = [(0, 0)] * len(x.shape) pad_widths[axis] = (1, 0) padded = jnp.pad( x, pad_widths, mode='constant', constant_values=x.dtype.type(0)) return padded[:, :-1]
Shift the input to the right by padding on axis 1.
shift_right
python
jax-ml/jax
jax/experimental/jax2tf/tests/flax_models/transformer_wmt.py
https://github.com/jax-ml/jax/blob/master/jax/experimental/jax2tf/tests/flax_models/transformer_wmt.py
Apache-2.0
def __call__(self, inputs, encoder_mask=None): """Applies Encoder1DBlock module. Args: inputs: input data. encoder_mask: encoder self-attention mask. Returns: output after transformer encoder block. """ config = self.config # Attention block. ...
Applies Encoder1DBlock module. Args: inputs: input data. encoder_mask: encoder self-attention mask. Returns: output after transformer encoder block.
__call__
python
jax-ml/jax
jax/experimental/jax2tf/tests/flax_models/transformer_wmt.py
https://github.com/jax-ml/jax/blob/master/jax/experimental/jax2tf/tests/flax_models/transformer_wmt.py
Apache-2.0
def __call__(self, targets, encoded, decoder_mask=None, encoder_decoder_mask=None): """Applies EncoderDecoder1DBlock module. Args: targets: input data for decoder encoded: input data from encoder decoder_mask: decoder self-attention ...
Applies EncoderDecoder1DBlock module. Args: targets: input data for decoder encoded: input data from encoder decoder_mask: decoder self-attention mask. encoder_decoder_mask: encoder-decoder attention mask. Returns: output after transformer encoder-decoder block.
__call__
python
jax-ml/jax
jax/experimental/jax2tf/tests/flax_models/transformer_wmt.py
https://github.com/jax-ml/jax/blob/master/jax/experimental/jax2tf/tests/flax_models/transformer_wmt.py
Apache-2.0
def __call__(self, inputs, inputs_positions=None, encoder_mask=None): """Applies Transformer model on the inputs. Args: inputs: input data inputs_positions: input subsequence positions for packed examples. encoder_mask: decoder self-attention mask....
Applies Transformer model on the inputs. Args: inputs: input data inputs_positions: input subsequence positions for packed examples. encoder_mask: decoder self-attention mask. Returns: output of a transformer encoder.
__call__
python
jax-ml/jax
jax/experimental/jax2tf/tests/flax_models/transformer_wmt.py
https://github.com/jax-ml/jax/blob/master/jax/experimental/jax2tf/tests/flax_models/transformer_wmt.py
Apache-2.0
def __call__(self, encoded, targets, targets_positions=None, decoder_mask=None, encoder_decoder_mask=None): """Applies Transformer model on the inputs. Args: encoded: encoded input data from encoder. targets: target inputs. ...
Applies Transformer model on the inputs. Args: encoded: encoded input data from encoder. targets: target inputs. targets_positions: input subsequence positions for packed examples. decoder_mask: decoder self-attention mask. encoder_decoder_mask: encoder-decoder attention mask. Re...
__call__
python
jax-ml/jax
jax/experimental/jax2tf/tests/flax_models/transformer_wmt.py
https://github.com/jax-ml/jax/blob/master/jax/experimental/jax2tf/tests/flax_models/transformer_wmt.py
Apache-2.0
def encode(self, inputs, inputs_positions=None, inputs_segmentation=None): """Applies Transformer encoder-branch on the inputs. Args: inputs: input data. inputs_positions: input subsequence positions for packed examples. inputs_segmentation: input segmen...
Applies Transformer encoder-branch on the inputs. Args: inputs: input data. inputs_positions: input subsequence positions for packed examples. inputs_segmentation: input segmentation info for packed examples. Returns: encoded feature array from the transformer encoder.
encode
python
jax-ml/jax
jax/experimental/jax2tf/tests/flax_models/transformer_wmt.py
https://github.com/jax-ml/jax/blob/master/jax/experimental/jax2tf/tests/flax_models/transformer_wmt.py
Apache-2.0
def decode(self, encoded, inputs, # only needed for masks targets, targets_positions=None, inputs_segmentation=None, targets_segmentation=None): """Applies Transformer decoder-branch on encoded-input and target. Args: encoded:...
Applies Transformer decoder-branch on encoded-input and target. Args: encoded: encoded input data from encoder. inputs: input data (only needed for masking). targets: target data. targets_positions: target subsequence positions for packed examples. inputs_segmentation: input segmentat...
decode
python
jax-ml/jax
jax/experimental/jax2tf/tests/flax_models/transformer_wmt.py
https://github.com/jax-ml/jax/blob/master/jax/experimental/jax2tf/tests/flax_models/transformer_wmt.py
Apache-2.0
def __call__(self, inputs, targets, inputs_positions=None, targets_positions=None, inputs_segmentation=None, targets_segmentation=None): """Applies Transformer model on the inputs. Args: inputs: input data. ta...
Applies Transformer model on the inputs. Args: inputs: input data. targets: target data. inputs_positions: input subsequence positions for packed examples. targets_positions: target subsequence positions for packed examples. inputs_segmentation: input segmentation info for packed exam...
__call__
python
jax-ml/jax
jax/experimental/jax2tf/tests/flax_models/transformer_wmt.py
https://github.com/jax-ml/jax/blob/master/jax/experimental/jax2tf/tests/flax_models/transformer_wmt.py
Apache-2.0
def jaxpr_type_signature(jaxpr: core.Jaxpr) -> KeyReuseSignature: """Parse the jaxpr to determine key reuse signature""" consumed: dict[core.Atom, bool | np.ndarray] = {} forwards: dict[core.Atom, core.Atom] = {} # map forwarded outputs to inputs. def resolve_forwards(var: core.Atom) -> core.Atom: if not ...
Parse the jaxpr to determine key reuse signature
jaxpr_type_signature
python
jax-ml/jax
jax/experimental/key_reuse/_core.py
https://github.com/jax-ml/jax/blob/master/jax/experimental/key_reuse/_core.py
Apache-2.0
def _declare_runtime_functions(): """Declares the runtime functions that can be used by the generated code.""" ptr_ty = ir.Type.parse("!llvm.ptr") i64 = ir.IntegerType.get_signless(64) arg_tys = [ptr_ty, ptr_ty, i64, i64, ptr_ty, ptr_ty, i64, ptr_ty] init_tma_desc_type = ir.FunctionType.get(arg_tys, []) fun...
Declares the runtime functions that can be used by the generated code.
_declare_runtime_functions
python
jax-ml/jax
jax/experimental/mosaic/gpu/core.py
https://github.com/jax-ml/jax/blob/master/jax/experimental/mosaic/gpu/core.py
Apache-2.0
def _check_transforms_and_swizzle_are_supported( ref_ty: ir.MemRefType, transforms: Sequence[launch_context.MemRefTransform], swizzle: mgpu.SwizzlingMode, minimum_swizzle: mgpu.SwizzlingMode = mgpu.SwizzlingMode.kNoSwizzle, ): """Checks that the list of provided transforms and swizzle are supported. ...
Checks that the list of provided transforms and swizzle are supported. Currently, we allow the following: - any swizzle that is larger than or equal to `minimum_swizzle`; - optionally, a single tile transform (with rank equal to the rank of the memref being annotated); - optionally, a single transp...
_check_transforms_and_swizzle_are_supported
python
jax-ml/jax
jax/experimental/mosaic/gpu/dialect_lowering.py
https://github.com/jax-ml/jax/blob/master/jax/experimental/mosaic/gpu/dialect_lowering.py
Apache-2.0
def swizzle_and_transforms_from_transforms_attr( transforms: ir.ArrayAttr, ) -> tuple[mgpu.SwizzlingMode, tuple[launch_context.MemRefTransform, ...]]: """Returns the swizzle and MemrefTransforms for the given transforms. Args: transforms: a list of transform attributes. Returns: A tuple containing t...
Returns the swizzle and MemrefTransforms for the given transforms. Args: transforms: a list of transform attributes. Returns: A tuple containing the swizzle mode and MemRefTransforms corresponding to the parameter transforms. If `transforms` is empty, or does not contain any swizzling transform, t...
swizzle_and_transforms_from_transforms_attr
python
jax-ml/jax
jax/experimental/mosaic/gpu/dialect_lowering.py
https://github.com/jax-ml/jax/blob/master/jax/experimental/mosaic/gpu/dialect_lowering.py
Apache-2.0
def _transformed_smem_ref_type( ref_ty: ir.MemRefType, transforms: tuple[launch_context.MemRefTransform, ...], ) -> ir.MemRefType: """Returns the transformed ref type for the given logical ref and transforms. """ transposed = _is_memref_transposed(ref_ty) if not transforms and not transposed: return...
Returns the transformed ref type for the given logical ref and transforms.
_transformed_smem_ref_type
python
jax-ml/jax
jax/experimental/mosaic/gpu/dialect_lowering.py
https://github.com/jax-ml/jax/blob/master/jax/experimental/mosaic/gpu/dialect_lowering.py
Apache-2.0
def reinterpret_smem_ref( ref: ir.Value, transforms: tuple[launch_context.MemRefTransform, ...], ) -> ir.Value: """Applies transforms on the ref, and makes sure that their effect is propagated appropriately on the strides. This function is used any time we lower from a dialect SMEM ref (2D for wgmma) w...
Applies transforms on the ref, and makes sure that their effect is propagated appropriately on the strides. This function is used any time we lower from a dialect SMEM ref (2D for wgmma) with given transforms to a "physical" SMEM ref (4D for wgmma) that is fully transformed and transposed as needed.
reinterpret_smem_ref
python
jax-ml/jax
jax/experimental/mosaic/gpu/dialect_lowering.py
https://github.com/jax-ml/jax/blob/master/jax/experimental/mosaic/gpu/dialect_lowering.py
Apache-2.0
def _flatten_ir_values( values: Sequence[ir.Value], fa_layouts: Iterable[ir.Attribute] ) -> tuple[Sequence[ir.Value], Sequence[_VectorTemplate | None]]: """Flattens a sequence of values. Non-vector values are preserved as is. Vectors are mapped to fragmented arrays and then flattened into per-register values...
Flattens a sequence of values. Non-vector values are preserved as is. Vectors are mapped to fragmented arrays and then flattened into per-register values. Args: values: The sequence of values to flatten. fa_layouts: The layouts of vectors in ``values``. Returns: A tuple of (flattened values, temp...
_flatten_ir_values
python
jax-ml/jax
jax/experimental/mosaic/gpu/dialect_lowering.py
https://github.com/jax-ml/jax/blob/master/jax/experimental/mosaic/gpu/dialect_lowering.py
Apache-2.0
def _move_scf_block_to_block_with_flattened_arguments( ctx: LoweringContext, old_block: ir.Block, new_block: ir.Block, last_op_type: type[ir.OpView], args_template: Sequence[_VectorTemplate | None], *new_leading_args: Sequence[ir.Value], ) -> Sequence[_VectorTemplate | None]: """Moves the oper...
Moves the operations from `old_block` to `new_block`. The input arguments to the block, if any, are flattened using the provided `args_template`, except for any new_leading_args which are simply prepended to the flattened arguments and must be part of the template. The last operation of the old block must be ...
_move_scf_block_to_block_with_flattened_arguments
python
jax-ml/jax
jax/experimental/mosaic/gpu/dialect_lowering.py
https://github.com/jax-ml/jax/blob/master/jax/experimental/mosaic/gpu/dialect_lowering.py
Apache-2.0
def single_thread_predicates(module: ir.Module) -> tuple[ir.Value, ir.Value]: """Returns a single thread predicate per block and one per warpgroup.""" block_predicate = warpgroup_predicate = None for op in module.body.operations: for region in op.operation.regions: for block in region.blocks: fo...
Returns a single thread predicate per block and one per warpgroup.
single_thread_predicates
python
jax-ml/jax
jax/experimental/mosaic/gpu/dialect_lowering.py
https://github.com/jax-ml/jax/blob/master/jax/experimental/mosaic/gpu/dialect_lowering.py
Apache-2.0
def _should_lower(op: ir.OpView) -> bool: """Returns 'true' if the operation should be lowered.""" return ( op.OPERATION_NAME.startswith("mosaic_gpu.") # pytype: disable=attribute-error or inference_utils.should_have_layout(op) or any(bool(b) for r in op.regions for b in r) # Does it have subblo...
Returns 'true' if the operation should be lowered.
_should_lower
python
jax-ml/jax
jax/experimental/mosaic/gpu/dialect_lowering.py
https://github.com/jax-ml/jax/blob/master/jax/experimental/mosaic/gpu/dialect_lowering.py
Apache-2.0
def tile_shape(self, shape: tuple[int, ...]) -> tuple[int, ...]: """Computes the shape of an array after tiling.""" def fail(): raise ValueError(f"Tiling {self.tiles} does not apply to shape {shape}") for tile in self.tiles: if len(tile) > len(shape): fail() untiled_dims, tiled_dim...
Computes the shape of an array after tiling.
tile_shape
python
jax-ml/jax
jax/experimental/mosaic/gpu/fragmented_array.py
https://github.com/jax-ml/jax/blob/master/jax/experimental/mosaic/gpu/fragmented_array.py
Apache-2.0
def untile_shape(self, shape: tuple[int, ...]) -> tuple[int, ...]: """Computes the shape of an array before tiling from its tiled shape.""" def fail(): raise ValueError( f"shape {shape} is not a valid result of applying tiling {self}." ) for tile in reversed(self.tiles): if len(t...
Computes the shape of an array before tiling from its tiled shape.
untile_shape
python
jax-ml/jax
jax/experimental/mosaic/gpu/fragmented_array.py
https://github.com/jax-ml/jax/blob/master/jax/experimental/mosaic/gpu/fragmented_array.py
Apache-2.0
def tile_strides(self, strides: tuple[int, ...]) -> tuple[int, ...]: """Computes the strides of an array after tiling.""" for tile in self.tiles: untiled, tiled = strides[:-len(tile)], strides[-len(tile):] strides = (*untiled, *(s * t for s, t in zip(tiled, tile)), *tiled) return strides
Computes the strides of an array after tiling.
tile_strides
python
jax-ml/jax
jax/experimental/mosaic/gpu/fragmented_array.py
https://github.com/jax-ml/jax/blob/master/jax/experimental/mosaic/gpu/fragmented_array.py
Apache-2.0
def tile_dimension(self, dim: int) -> tuple[bool, ...]: """Result is True whenever the tiled dim originated from the given input dim.""" tiling_rank = len(self.tiles[0]) if dim < 0 or dim >= tiling_rank: raise ValueError(f"Invalid dimension {dim} for tiling {self}") strides = [1] * tiling_rank ...
Result is True whenever the tiled dim originated from the given input dim.
tile_dimension
python
jax-ml/jax
jax/experimental/mosaic/gpu/fragmented_array.py
https://github.com/jax-ml/jax/blob/master/jax/experimental/mosaic/gpu/fragmented_array.py
Apache-2.0
def remove_dimension(self, dim: int) -> "Tiling": """Returns a tiling with the given dimension removed.""" tiling_rank = len(self.tiles[0]) if dim < 0 or dim >= tiling_rank: raise ValueError(f"Invalid dimension {dim} for tiling {self}") dim_in_tile = dim tiles = [] last_tile_rank = len(sel...
Returns a tiling with the given dimension removed.
remove_dimension
python
jax-ml/jax
jax/experimental/mosaic/gpu/fragmented_array.py
https://github.com/jax-ml/jax/blob/master/jax/experimental/mosaic/gpu/fragmented_array.py
Apache-2.0
def tile_nested_shape_strides( self, shape: tuple[tuple[int, ...], ...], strides: tuple[tuple[int, ...], ...], ) -> tuple[tuple[tuple[int, ...], ...], tuple[tuple[int, ...], ...]]: """A fused version of `tile_shape` and `tile_strides` for nested shapes. By nested shape we mean that each log...
A fused version of `tile_shape` and `tile_strides` for nested shapes. By nested shape we mean that each logical dimension (i.e. each element of shape/strides) is actually composed out of multiple physical dimensions. For example, a row-major array of logical shape (128, 128) that is tiled into (64, 64)...
tile_nested_shape_strides
python
jax-ml/jax
jax/experimental/mosaic/gpu/fragmented_array.py
https://github.com/jax-ml/jax/blob/master/jax/experimental/mosaic/gpu/fragmented_array.py
Apache-2.0
def enumerate_negative(elems: Sequence[T]) -> Iterable[tuple[int, T]]: """Like built-in enumerate, but returns negative indices into the sequence.""" offset = len(elems) for i, e in enumerate(elems): yield i - offset, e
Like built-in enumerate, but returns negative indices into the sequence.
enumerate_negative
python
jax-ml/jax
jax/experimental/mosaic/gpu/fragmented_array.py
https://github.com/jax-ml/jax/blob/master/jax/experimental/mosaic/gpu/fragmented_array.py
Apache-2.0
def registers_shape(self, shape: tuple[int, ...]) -> tuple[int, ...]: """Returns the shape of the register array needed to represent an array of the given logical shape.""" tiled_shape = list(self.tiling.tile_shape(shape)) if not isinstance(self.warp_dim, Replicated): tiled_shape[self.warp_dim] = 1 ...
Returns the shape of the register array needed to represent an array of the given logical shape.
registers_shape
python
jax-ml/jax
jax/experimental/mosaic/gpu/fragmented_array.py
https://github.com/jax-ml/jax/blob/master/jax/experimental/mosaic/gpu/fragmented_array.py
Apache-2.0
def shape_from_registers_shape(self, shape: tuple[int, ...]) -> tuple[int, ...]: """Returns the logical shape of an array given its register array shape. Inverse to `registers_shape`. """ tiled_tiling = self.tiled_tiling_shape shape = list(shape) if not isinstance(self.warp_dim, Replicated): ...
Returns the logical shape of an array given its register array shape. Inverse to `registers_shape`.
shape_from_registers_shape
python
jax-ml/jax
jax/experimental/mosaic/gpu/fragmented_array.py
https://github.com/jax-ml/jax/blob/master/jax/experimental/mosaic/gpu/fragmented_array.py
Apache-2.0
def _tiled_wgmma_layout(shape: tuple[int, ...]): """Returns the tiled layout relevant for WGMMA operations. The tiled layout is equivalent to one described here in PTX documentation: https://docs.nvidia.com/cuda/parallel-thread-execution/#wgmma-64n16-d """ if len(shape) != 2: raise ValueError(f"Shape {sh...
Returns the tiled layout relevant for WGMMA operations. The tiled layout is equivalent to one described here in PTX documentation: https://docs.nvidia.com/cuda/parallel-thread-execution/#wgmma-64n16-d
_tiled_wgmma_layout
python
jax-ml/jax
jax/experimental/mosaic/gpu/fragmented_array.py
https://github.com/jax-ml/jax/blob/master/jax/experimental/mosaic/gpu/fragmented_array.py
Apache-2.0
def linear_thread_idxs(self): """The indexes to be used for vector load/store WGStridedFragLayout. Yields: The indices of the vector that correspond to the current thread. """ index = ir.IndexType.get() cardinality = np.prod(self.shape) assert cardinality % (WARPGROUP_SIZE * self.vec_size...
The indexes to be used for vector load/store WGStridedFragLayout. Yields: The indices of the vector that correspond to the current thread.
linear_thread_idxs
python
jax-ml/jax
jax/experimental/mosaic/gpu/fragmented_array.py
https://github.com/jax-ml/jax/blob/master/jax/experimental/mosaic/gpu/fragmented_array.py
Apache-2.0
def __init__( self, *, _registers: np.ndarray, _layout: FragmentedLayout, _is_signed: bool | None, ): """Initializes a fragmented array. This is a low-level API. Prefer using classmethods to construct fragmented arrays instead. """ # We need to use ``object.__setattr...
Initializes a fragmented array. This is a low-level API. Prefer using classmethods to construct fragmented arrays instead.
__init__
python
jax-ml/jax
jax/experimental/mosaic/gpu/fragmented_array.py
https://github.com/jax-ml/jax/blob/master/jax/experimental/mosaic/gpu/fragmented_array.py
Apache-2.0
def to_layout(self, new_layout: FragmentedLayout): """Converts the fragmented array to the given layout. At the moment, only conversions from ``WGSplatFragLayout`` are supported. """ i32 = ir.IntegerType.get_signless(32) c = lambda x: arith.constant(i32, x) if self.layout == new_layout: r...
Converts the fragmented array to the given layout. At the moment, only conversions from ``WGSplatFragLayout`` are supported.
to_layout
python
jax-ml/jax
jax/experimental/mosaic/gpu/fragmented_array.py
https://github.com/jax-ml/jax/blob/master/jax/experimental/mosaic/gpu/fragmented_array.py
Apache-2.0
def foreach( self, fn: Callable[[ir.Value, tuple[ir.Value, ...]], ir.Value | None], *, create_array=False, is_signed=None, ): """Call a function for each value and index.""" index = ir.IndexType.get() new_regs = None orig_fn = fn def fn(*args): nonlocal new_regs...
Call a function for each value and index.
foreach
python
jax-ml/jax
jax/experimental/mosaic/gpu/fragmented_array.py
https://github.com/jax-ml/jax/blob/master/jax/experimental/mosaic/gpu/fragmented_array.py
Apache-2.0
def transfer_tiled2( ref: ir.Value, swizzle: int | None, layout: TiledLayout, shape: tuple[int, ...], optimized: bool = True, ): """Generate a transfer schedule for a tiled layout. Given a ref with one level tiling applied to it (we assume all dimensions have been tiled), th...
Generate a transfer schedule for a tiled layout. Given a ref with one level tiling applied to it (we assume all dimensions have been tiled), this function generates an iterable describing a good schedule for swizzled SMEM loads/stores. At each step, the iterable yields a tuple of three values: * a...
transfer_tiled2
python
jax-ml/jax
jax/experimental/mosaic/gpu/fragmented_array.py
https://github.com/jax-ml/jax/blob/master/jax/experimental/mosaic/gpu/fragmented_array.py
Apache-2.0
def optimization_barrier(*arrays: mgpu.FragmentedArray): """Acts as an optimization barrier for LLVM. Passing arrays through this function will make sure that they are computed before any side-effecting operations that follow this barrier. """ index = ir.IndexType.get() i32 = ir.IntegerType.get_signless(32...
Acts as an optimization barrier for LLVM. Passing arrays through this function will make sure that they are computed before any side-effecting operations that follow this barrier.
optimization_barrier
python
jax-ml/jax
jax/experimental/mosaic/gpu/fragmented_array.py
https://github.com/jax-ml/jax/blob/master/jax/experimental/mosaic/gpu/fragmented_array.py
Apache-2.0
def in_layouts(op: MlirOperation) -> Sequence[ir.Attribute]: """Returns the in_layouts attribute of the given operation. Raises: ValueError: If the operation does not have an in_layouts attribute. """ if "in_layouts" not in op.attributes: raise ValueError(f"{op} does not have an in_layouts attribute.")...
Returns the in_layouts attribute of the given operation. Raises: ValueError: If the operation does not have an in_layouts attribute.
in_layouts
python
jax-ml/jax
jax/experimental/mosaic/gpu/inference_utils.py
https://github.com/jax-ml/jax/blob/master/jax/experimental/mosaic/gpu/inference_utils.py
Apache-2.0
def out_layouts(op: MlirOperation) -> Sequence[ir.Attribute]: """Returns the out_layouts attribute of the given operation. Raises: ValueError: If the operation does not have an out_layouts attribute. """ if "out_layouts" not in op.attributes: raise ValueError(f"{op} does not have an out_layouts attribu...
Returns the out_layouts attribute of the given operation. Raises: ValueError: If the operation does not have an out_layouts attribute.
out_layouts
python
jax-ml/jax
jax/experimental/mosaic/gpu/inference_utils.py
https://github.com/jax-ml/jax/blob/master/jax/experimental/mosaic/gpu/inference_utils.py
Apache-2.0
def in_transforms(op: MlirOperation) -> Sequence[ir.Attribute]: """Returns the in_transforms attribute of the given operation. Raises: ValueError: If the operation does not have an in_transforms attribute. """ if "in_transforms" not in op.attributes: raise ValueError(f"{op} does not have an in_transfor...
Returns the in_transforms attribute of the given operation. Raises: ValueError: If the operation does not have an in_transforms attribute.
in_transforms
python
jax-ml/jax
jax/experimental/mosaic/gpu/inference_utils.py
https://github.com/jax-ml/jax/blob/master/jax/experimental/mosaic/gpu/inference_utils.py
Apache-2.0
def out_transforms(op: MlirOperation) -> Sequence[ir.Attribute]: """Returns the out_transforms attribute of the given operation. Raises: ValueError: If the operation does not have an out_transforms attribute. """ if "out_transforms" not in op.attributes: raise ValueError(f"{op} does not have an out_tra...
Returns the out_transforms attribute of the given operation. Raises: ValueError: If the operation does not have an out_transforms attribute.
out_transforms
python
jax-ml/jax
jax/experimental/mosaic/gpu/inference_utils.py
https://github.com/jax-ml/jax/blob/master/jax/experimental/mosaic/gpu/inference_utils.py
Apache-2.0
def should_have_layout(op: MlirOperation) -> bool: """Returns 'true' if the operation should be assigned a layout.""" is_array = lambda v: ir.VectorType.isinstance(v.type) return any(map(is_array, itertools.chain(op.operands, op.results))) # type: ignore
Returns 'true' if the operation should be assigned a layout.
should_have_layout
python
jax-ml/jax
jax/experimental/mosaic/gpu/inference_utils.py
https://github.com/jax-ml/jax/blob/master/jax/experimental/mosaic/gpu/inference_utils.py
Apache-2.0
def attr_element( attr_name: str, op: MlirOperation, index: int ) -> ir.Attribute | None: """Returns `op.attributes[attr_name][index]` if it exists, otherwise None. If `op.attributes[attr_name]` exists, then `index` must be a valid index into the attribute array. """ if attr_name not in op.attributes: ...
Returns `op.attributes[attr_name][index]` if it exists, otherwise None. If `op.attributes[attr_name]` exists, then `index` must be a valid index into the attribute array.
attr_element
python
jax-ml/jax
jax/experimental/mosaic/gpu/inference_utils.py
https://github.com/jax-ml/jax/blob/master/jax/experimental/mosaic/gpu/inference_utils.py
Apache-2.0
def should_have_transforms(op: ir.OpView) -> bool: """Returns 'True' if the operation should be assigned in/out transforms.""" return any( map( is_transformable_smem_memref, itertools.chain(op.operands, op.results), ) )
Returns 'True' if the operation should be assigned in/out transforms.
should_have_transforms
python
jax-ml/jax
jax/experimental/mosaic/gpu/inference_utils.py
https://github.com/jax-ml/jax/blob/master/jax/experimental/mosaic/gpu/inference_utils.py
Apache-2.0
def is_transformable_smem_memref(v: ir.Value) -> bool: """Whether the value is a memref in SMEM on which transforms should be applied.""" barrier_ty = ir.Type.parse("!mosaic_gpu.barrier") smem = ir.Attribute.parse("#gpu.address_space<workgroup>") return ( ir.MemRefType.isinstance(v.type) # barriers ...
Whether the value is a memref in SMEM on which transforms should be applied.
is_transformable_smem_memref
python
jax-ml/jax
jax/experimental/mosaic/gpu/inference_utils.py
https://github.com/jax-ml/jax/blob/master/jax/experimental/mosaic/gpu/inference_utils.py
Apache-2.0
def value_layout(value: ir.Value) -> ir.Attribute | None: """Returns the layout for a given value as defined by its owner. Raises: ValueError: If `result` is not a Vector. """ if not ir.VectorType.isinstance(value.type): raise ValueError(f"{value} is not a vector.") return _value_attr(value, "layout...
Returns the layout for a given value as defined by its owner. Raises: ValueError: If `result` is not a Vector.
value_layout
python
jax-ml/jax
jax/experimental/mosaic/gpu/inference_utils.py
https://github.com/jax-ml/jax/blob/master/jax/experimental/mosaic/gpu/inference_utils.py
Apache-2.0
def value_transforms(value: ir.Value) -> ir.Attribute | None: """Returns the transforms for a given value as defined by its owner. Raises: ValueError: If `result` is not a memref. """ if not ir.MemRefType.isinstance(value.type): raise ValueError(f"{value} is not a memref.") return _value_attr(value,...
Returns the transforms for a given value as defined by its owner. Raises: ValueError: If `result` is not a memref.
value_transforms
python
jax-ml/jax
jax/experimental/mosaic/gpu/inference_utils.py
https://github.com/jax-ml/jax/blob/master/jax/experimental/mosaic/gpu/inference_utils.py
Apache-2.0
def traverse_op( op: ir.OpView, callback: Callable[[ir.OpView], None], traversal_order: TraversalOrder = TraversalOrder.FORWARD, ): """Traverses the operation and applies the callback in the given order.""" for region in op.operation.regions: for block in region: if traversal_order == Traversa...
Traverses the operation and applies the callback in the given order.
traverse_op
python
jax-ml/jax
jax/experimental/mosaic/gpu/inference_utils.py
https://github.com/jax-ml/jax/blob/master/jax/experimental/mosaic/gpu/inference_utils.py
Apache-2.0
def finalize_size(self): """ Allocates and initializes the host buffer. This needs to be done after lowering, i.e. after all TMA descriptors have been recorded. Only then we know what the scratch contains. """ if self.next_offset == 0: return assert self._alloc_op is not None with ...
Allocates and initializes the host buffer. This needs to be done after lowering, i.e. after all TMA descriptors have been recorded. Only then we know what the scratch contains.
finalize_size
python
jax-ml/jax
jax/experimental/mosaic/gpu/launch_context.py
https://github.com/jax-ml/jax/blob/master/jax/experimental/mosaic/gpu/launch_context.py
Apache-2.0
def cluster_idx( self, dim: gpu.Dimension | Sequence[gpu.Dimension] | None = None ) -> ir.Value: """Returns the index of a block within a subset of the cluster spanned by the given dimensions.""" if dim is None: dim = gpu.Dimension elif isinstance(dim, gpu.Dimension): dim = (dim,) in...
Returns the index of a block within a subset of the cluster spanned by the given dimensions.
cluster_idx
python
jax-ml/jax
jax/experimental/mosaic/gpu/launch_context.py
https://github.com/jax-ml/jax/blob/master/jax/experimental/mosaic/gpu/launch_context.py
Apache-2.0
def _alloc_scratch( self, size: int, alignment: int | None = None, host_init: Callable[[ir.Value], None] = lambda _: None, device_init: Callable[[ir.Value], Any] = lambda x: x, ) -> ir.Value: """Allocates a GMEM scratch buffer. The buffer is initialized on the host and then copi...
Allocates a GMEM scratch buffer. The buffer is initialized on the host and then copied to GMEM before the kernel launch.
_alloc_scratch
python
jax-ml/jax
jax/experimental/mosaic/gpu/launch_context.py
https://github.com/jax-ml/jax/blob/master/jax/experimental/mosaic/gpu/launch_context.py
Apache-2.0
def async_copy( self, *, src_ref, dst_ref, gmem_slice: Any = (), gmem_transform: MemRefTransform | tuple[MemRefTransform, ...] = (), gmem_peer_id: int | ir.Value | None = None, barrier: utils.BarrierRef | None = None, swizzle: int | None = None, arrive: bool |...
Initiates an async copy between GMEM and SMEM. Exactly one of `src_ref` and `dst_ref` must be in GMEM and in SMEM, and the SMEM reference must be contiguous. The GMEM window that is read or written to is specified by the `gmem_slice`. The copy can change the order in which the data appears in the windo...
async_copy
python
jax-ml/jax
jax/experimental/mosaic/gpu/launch_context.py
https://github.com/jax-ml/jax/blob/master/jax/experimental/mosaic/gpu/launch_context.py
Apache-2.0
def from_splat_fragmented_layout_attr(attr: ir.Attribute) -> fa.WGSplatFragLayout: """Constructs a WGSplatFragLayout from a #mosaic_gpu.WGSplatFragLayout attribute. Raises: ValueError: If the attribute is not a #mosaic_gpu.WGSplatFragLayout attribute. """ match = _splat_fragmented_layout_attr_pattern...
Constructs a WGSplatFragLayout from a #mosaic_gpu.WGSplatFragLayout attribute. Raises: ValueError: If the attribute is not a #mosaic_gpu.WGSplatFragLayout attribute.
from_splat_fragmented_layout_attr
python
jax-ml/jax
jax/experimental/mosaic/gpu/layouts.py
https://github.com/jax-ml/jax/blob/master/jax/experimental/mosaic/gpu/layouts.py
Apache-2.0
def from_strided_fragmented_layout_attr( attr: ir.Attribute, ) -> fa.WGStridedFragLayout: """Constructs a WGStridedFragLayout from a #mosaic_gpu.WGStridedFragLayout attribute. Raises: ValueError: If the attribute is not a #mosaic_gpu.WGStridedFragLayout attribute. """ match = _strided_fragmented_...
Constructs a WGStridedFragLayout from a #mosaic_gpu.WGStridedFragLayout attribute. Raises: ValueError: If the attribute is not a #mosaic_gpu.WGStridedFragLayout attribute.
from_strided_fragmented_layout_attr
python
jax-ml/jax
jax/experimental/mosaic/gpu/layouts.py
https://github.com/jax-ml/jax/blob/master/jax/experimental/mosaic/gpu/layouts.py
Apache-2.0
def from_tiled_layout_attr( attr: ir.Attribute, ) -> fa.TiledLayout: """Constructs a TiledLayout from a #mosaic_gpu.TiledLayout attribute. Raises: ValueError: If the attribute is not a #mosaic_gpu.TiledLayout attribute. """ match = _tiled_layout_attr_pattern.fullmatch(str(attr)) if not match: ...
Constructs a TiledLayout from a #mosaic_gpu.TiledLayout attribute. Raises: ValueError: If the attribute is not a #mosaic_gpu.TiledLayout attribute.
from_tiled_layout_attr
python
jax-ml/jax
jax/experimental/mosaic/gpu/layouts.py
https://github.com/jax-ml/jax/blob/master/jax/experimental/mosaic/gpu/layouts.py
Apache-2.0
def to_layout_attr( layout: ( fa.WGSplatFragLayout | fa.WGStridedFragLayout | fa.TiledLayout ), ) -> ir.Attribute: """Constructs an MLIR attribute that corresponds to the given layout.""" match layout: case fa.WGSplatFragLayout(): return to_splat_fragmented_layout_attr(layo...
Constructs an MLIR attribute that corresponds to the given layout.
to_layout_attr
python
jax-ml/jax
jax/experimental/mosaic/gpu/layouts.py
https://github.com/jax-ml/jax/blob/master/jax/experimental/mosaic/gpu/layouts.py
Apache-2.0
def from_layout_attr( attr: ir.Attribute, ) -> ( fa.WGSplatFragLayout | fa.WGStridedFragLayout | fa.TiledLayout ): """Constructs a layout from an MLIR attribute.""" if is_splat_fragmented_layout(attr): return from_splat_fragmented_layout_attr(attr) elif is_strided_fragmented_layout(attr): ...
Constructs a layout from an MLIR attribute.
from_layout_attr
python
jax-ml/jax
jax/experimental/mosaic/gpu/layouts.py
https://github.com/jax-ml/jax/blob/master/jax/experimental/mosaic/gpu/layouts.py
Apache-2.0
def _choose_representative_layout( layouts: set[ir.Attribute], ) -> ir.Attribute | None: """Chooses an appropriate layout from a given set of possible layouts. Given the input set of possible layouts, this function extracts a single representative layout. Currently, this function only works with strided, s...
Chooses an appropriate layout from a given set of possible layouts. Given the input set of possible layouts, this function extracts a single representative layout. Currently, this function only works with strided, splat, and tiled layouts. Returns: A single layout that can be used to annotate the operatio...
_choose_representative_layout
python
jax-ml/jax
jax/experimental/mosaic/gpu/layout_inference.py
https://github.com/jax-ml/jax/blob/master/jax/experimental/mosaic/gpu/layout_inference.py
Apache-2.0
def tiled_memref_shape(ref: ir.Value): """Returns the 2D untiled shape and element type of a tiled 4D memref.""" ref_ty = ir.MemRefType(ref.type) if ref_ty.rank != 4: raise ValueError(f"Expected a 4D memref, got: {ref_ty}") logical_shape = ( ref_ty.shape[0] * ref_ty.shape[2], ref_ty.shape[1] * ref_ty....
Returns the 2D untiled shape and element type of a tiled 4D memref.
tiled_memref_shape
python
jax-ml/jax
jax/experimental/mosaic/gpu/mma_utils.py
https://github.com/jax-ml/jax/blob/master/jax/experimental/mosaic/gpu/mma_utils.py
Apache-2.0
def measure( f: Callable[P, T], *, mode: str = "events", aggregate: bool = True ) -> Callable[P, tuple[T, Timings]]: """Sets up a function ``f`` for profiling on GPU. ``measure`` is a higher-order function that augments the argument ``f`` to return GPU runtime in milliseconds, in addition to its proper outpu...
Sets up a function ``f`` for profiling on GPU. ``measure`` is a higher-order function that augments the argument ``f`` to return GPU runtime in milliseconds, in addition to its proper outputs. Args: f: The function to measure. It must accept at least one argument and return at least one output to be m...
measure
python
jax-ml/jax
jax/experimental/mosaic/gpu/profiler.py
https://github.com/jax-ml/jax/blob/master/jax/experimental/mosaic/gpu/profiler.py
Apache-2.0
def _transfer_32xcols( base_addr: ir.Value, cols: int, atom_shape: tuple[int, int], tmem_packing: int, reg_packing: int, ): """Generates a sequence of parameters for a given TMEM read or write. Arguments: base_addr: The base address of the TMEM region. cols: The number of logical column...
Generates a sequence of parameters for a given TMEM read or write. Arguments: base_addr: The base address of the TMEM region. cols: The number of logical columns to transfer. atom_shape: The logical shape of the tile written by the warp in a single TMEM transfer. tmem_packing: Packing degree in...
_transfer_32xcols
python
jax-ml/jax
jax/experimental/mosaic/gpu/tcgen05.py
https://github.com/jax-ml/jax/blob/master/jax/experimental/mosaic/gpu/tcgen05.py
Apache-2.0
def _resolve_transforms( transforms: ir.ArrayAttr | None, other_transforms: ir.ArrayAttr | None, ) -> ir.ArrayAttr | None: """Resolves two sets of competing transforms to a single compatible set. Args: transforms: one optional set of transforms. other_transforms: another optional set of transforms....
Resolves two sets of competing transforms to a single compatible set. Args: transforms: one optional set of transforms. other_transforms: another optional set of transforms. Returns: A single set of transforms that is compatible with both `transforms` and `other_transforms`, or `None` if both tran...
_resolve_transforms
python
jax-ml/jax
jax/experimental/mosaic/gpu/transform_inference.py
https://github.com/jax-ml/jax/blob/master/jax/experimental/mosaic/gpu/transform_inference.py
Apache-2.0
def infer_transforms(module: ir.Module): """Infers transforms for the given module. Transforms are to memrefs what layouts are to vectors. More specifically, transforms describe mappings between SMEM refs and GMEM refs, and are determined based on how SMEM refs are used. For that reason, we always annotate a...
Infers transforms for the given module. Transforms are to memrefs what layouts are to vectors. More specifically, transforms describe mappings between SMEM refs and GMEM refs, and are determined based on how SMEM refs are used. For that reason, we always annotate and apply memrefs on SMEM refs. The pass is ...
infer_transforms
python
jax-ml/jax
jax/experimental/mosaic/gpu/transform_inference.py
https://github.com/jax-ml/jax/blob/master/jax/experimental/mosaic/gpu/transform_inference.py
Apache-2.0
def single_thread_predicate(scope: ThreadSubset = ThreadSubset.BLOCK): """Returns a predicate that selects a single thread. Args: scope: What level of the thread hierarchy to select a thread from. For example, if the scope is BLOCK, only one thread per block will be selected. """ elected = nvvm...
Returns a predicate that selects a single thread. Args: scope: What level of the thread hierarchy to select a thread from. For example, if the scope is BLOCK, only one thread per block will be selected.
single_thread_predicate
python
jax-ml/jax
jax/experimental/mosaic/gpu/utils.py
https://github.com/jax-ml/jax/blob/master/jax/experimental/mosaic/gpu/utils.py
Apache-2.0
def single_thread(scope: ThreadSubset = ThreadSubset.BLOCK): """Runs the context only from a single thread. Args: scope: What level of the thread hierarchy to select a thread from. For example, if the scope is BLOCK, only one thread per block will be selected. """ global _ONCE_PER # If we're ...
Runs the context only from a single thread. Args: scope: What level of the thread hierarchy to select a thread from. For example, if the scope is BLOCK, only one thread per block will be selected.
single_thread
python
jax-ml/jax
jax/experimental/mosaic/gpu/utils.py
https://github.com/jax-ml/jax/blob/master/jax/experimental/mosaic/gpu/utils.py
Apache-2.0
def _reshape(ref: ir.Value, sh0: list[int], sh1: list[int]): """Reshapes using only "parallel" folds/unfolds. This function uses folds/unfolds that are "parallel" in that they only act on original dimensions, i.e. they won't fold into an intermediate dimension that they will then unfold. """ i0, i1 = 0, 0...
Reshapes using only "parallel" folds/unfolds. This function uses folds/unfolds that are "parallel" in that they only act on original dimensions, i.e. they won't fold into an intermediate dimension that they will then unfold.
_reshape
python
jax-ml/jax
jax/experimental/mosaic/gpu/utils.py
https://github.com/jax-ml/jax/blob/master/jax/experimental/mosaic/gpu/utils.py
Apache-2.0
def memref_reshape(ref: ir.Value, shape: tuple[int, ...]) -> ir.Value: """Reshape by means of folding and unfolding. The use of memref fold/unfold may avoid some possible issues with strided memrefs. """ ref_ty = ir.MemRefType(ref.type) if math.prod(ref_ty.shape) != math.prod(shape): raise ValueError(...
Reshape by means of folding and unfolding. The use of memref fold/unfold may avoid some possible issues with strided memrefs.
memref_reshape
python
jax-ml/jax
jax/experimental/mosaic/gpu/utils.py
https://github.com/jax-ml/jax/blob/master/jax/experimental/mosaic/gpu/utils.py
Apache-2.0
def memref_unfold(ref: ir.Value, dim, factors) -> ir.Value: """Unfolds dim into two dimensions, the size of leading one given be major_factor.""" ref_ty = ir.MemRefType(ref.type) new_shape = list(ref_ty.shape) if sum(f is None for f in factors) > 1: raise ValueError("Can only infer one dimension") known_f...
Unfolds dim into two dimensions, the size of leading one given be major_factor.
memref_unfold
python
jax-ml/jax
jax/experimental/mosaic/gpu/utils.py
https://github.com/jax-ml/jax/blob/master/jax/experimental/mosaic/gpu/utils.py
Apache-2.0
def from_barrier_memref(cls, barrier: ir.Value): """Creates a DialectBarrierRef from a memref of a dialect barrier.""" memref_type = ir.MemRefType(barrier.type) if memref_type.rank > 1 or memref_type.element_type != ir.Type.parse( "!mosaic_gpu.barrier" ): raise ValueError( "Expec...
Creates a DialectBarrierRef from a memref of a dialect barrier.
from_barrier_memref
python
jax-ml/jax
jax/experimental/mosaic/gpu/utils.py
https://github.com/jax-ml/jax/blob/master/jax/experimental/mosaic/gpu/utils.py
Apache-2.0
def arrive(self, for_tensor_core: bool = False): """Arrives on a barrier in all blocks that share at least one of the coordinates along the collective dimensions. Note that unlike in arrive, each warpgroup arrives once. """ if for_tensor_core: llvm.inline_asm( ir.Type.parse("!llvm.void"...
Arrives on a barrier in all blocks that share at least one of the coordinates along the collective dimensions. Note that unlike in arrive, each warpgroup arrives once.
arrive
python
jax-ml/jax
jax/experimental/mosaic/gpu/utils.py
https://github.com/jax-ml/jax/blob/master/jax/experimental/mosaic/gpu/utils.py
Apache-2.0
def wgmma( acc: WGMMAAccumulator, a: fa.FragmentedArray | ir.Value, b: ir.Value, *, swizzle: int = 128, ): """Perform acc += a @ b using the WGMMA instruction. The expected memref shapes are: a: (m, k, 64, S) b: (k, n, S, S) where S = swizzle // bytewidth(element_type). The refs m...
Perform acc += a @ b using the WGMMA instruction. The expected memref shapes are: a: (m, k, 64, S) b: (k, n, S, S) where S = swizzle // bytewidth(element_type). The refs must be contiguous or be contiguous except for having their two minor dimensions swapped.
wgmma
python
jax-ml/jax
jax/experimental/mosaic/gpu/wgmma.py
https://github.com/jax-ml/jax/blob/master/jax/experimental/mosaic/gpu/wgmma.py
Apache-2.0
def wgmma_fence(array: fa.FragmentedArray): """Fences the array construction from WGMMA instructions. LLVM treats in-register computation as pure and can move it after the fence, which is explicitly disallowed by the PTX programming model. For that reason, we insert an LLVM optimization barrier before the fenc...
Fences the array construction from WGMMA instructions. LLVM treats in-register computation as pure and can move it after the fence, which is explicitly disallowed by the PTX programming model. For that reason, we insert an LLVM optimization barrier before the fence.
wgmma_fence
python
jax-ml/jax
jax/experimental/mosaic/gpu/wgmma.py
https://github.com/jax-ml/jax/blob/master/jax/experimental/mosaic/gpu/wgmma.py
Apache-2.0
def wgmma( smem_scratch: Any, # pylint: disable=unused-argument acc: WGMMAAccumulator, a_slice: SmemRef, b_slice: SmemRef, swizzle: int, ) -> dict[str, WGMMAAccumulator]: """Perform a matrix multiplication. This function must guarantee that all WGMMA operations queued before it...
Perform a matrix multiplication. This function must guarantee that all WGMMA operations queued before it was called have completed before returning.
wgmma
python
jax-ml/jax
jax/experimental/mosaic/gpu/examples/matmul.py
https://github.com/jax-ml/jax/blob/master/jax/experimental/mosaic/gpu/examples/matmul.py
Apache-2.0
def compute_output(block_m_start, n_start, call_counter): """Compute and store a single output tile. call_counter should be 0 the first time this function is called and incremented by 1 before each subsequent call. """ acc_slot = arith.remui(call_counter, c(2, index)) acc_slice = ac...
Compute and store a single output tile. call_counter should be 0 the first time this function is called and incremented by 1 before each subsequent call.
compute_output
python
jax-ml/jax
jax/experimental/mosaic/gpu/examples/matmul_blackwell.py
https://github.com/jax-ml/jax/blob/master/jax/experimental/mosaic/gpu/examples/matmul_blackwell.py
Apache-2.0
def has_backward_blocks(self) -> bool: """Returns True if all backward blocks are specified for the fused dq and dk/dv backwards pass. """ backward_blocks = [ self.block_q_dkv, self.block_kv_dkv, self.block_q_dq, self.block_kv_dq, ] return all(b is not None for ...
Returns True if all backward blocks are specified for the fused dq and dk/dv backwards pass.
has_backward_blocks
python
jax-ml/jax
jax/experimental/pallas/ops/gpu/attention.py
https://github.com/jax-ml/jax/blob/master/jax/experimental/pallas/ops/gpu/attention.py
Apache-2.0
def _find_swizzle(dim_size_bits: int): """Finds the largest swizzle that fits the dimension size.""" for swizzle_bytes in (128, 64, 32, 16): if dim_size_bits % (swizzle_bytes * 8) == 0: return swizzle_bytes raise ValueError( f"Dimension size has {dim_size_bits} bits, which is not a multiple of 128...
Finds the largest swizzle that fits the dimension size.
_find_swizzle
python
jax-ml/jax
jax/experimental/pallas/ops/gpu/blackwell_matmul_mgpu.py
https://github.com/jax-ml/jax/blob/master/jax/experimental/pallas/ops/gpu/blackwell_matmul_mgpu.py
Apache-2.0
def paged_attention( q: jax.Array, k_pages: jax.Array, v_pages: jax.Array, block_tables: jax.Array, lengths: jax.Array | None, *, block_h: int = 16, pages_per_compute_block: int = 8, k_splits: int = 16, num_warps: int = 8, num_stages: int = 2, interpret: bool = False, ...
Paged grouped query attention. Args: q: A [batch_size, num_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. block_tables: A i32[batch_size, pages_per_sequence] jax.Array. E...
paged_attention
python
jax-ml/jax
jax/experimental/pallas/ops/gpu/paged_attention.py
https://github.com/jax-ml/jax/blob/master/jax/experimental/pallas/ops/gpu/paged_attention.py
Apache-2.0
def paged_attention_reference( q: jax.Array, k: jax.Array, v: jax.Array, lengths: jax.Array, *, mask_value: float = DEFAULT_MASK_VALUE, attn_logits_soft_cap: float | None = None, ) -> jax.Array: """Grouped query attention reference implementation. Args: q: A [batch_size, num_heads, ...
Grouped query attention reference implementation. Args: q: A [batch_size, num_heads, head_dim] jax.Array. k: A [batch_size, kv_seq_len, num_kv_heads, head_dim] jax.Array. v: A [batch_size, kv_seq_len, num_kv_heads, head_dim] jax.Array. lengths: A i32[batch_size] jax.Array the length of each example. ...
paged_attention_reference
python
jax-ml/jax
jax/experimental/pallas/ops/gpu/paged_attention.py
https://github.com/jax-ml/jax/blob/master/jax/experimental/pallas/ops/gpu/paged_attention.py
Apache-2.0
def create(cls, group_lengths, tile, tid): """Get the group info for the current block.""" tile = jnp.int32(tile) group_boundaries = [group_lengths[i] for i in range(group_lengths.shape[0])] # We usually only have very few groups, so we unroll the loop processing # them. Normally we'd break out of...
Get the group info for the current block.
create
python
jax-ml/jax
jax/experimental/pallas/ops/gpu/ragged_dot_mgpu.py
https://github.com/jax-ml/jax/blob/master/jax/experimental/pallas/ops/gpu/ragged_dot_mgpu.py
Apache-2.0
def softmax( x: jax.Array, *, axis: int = -1, num_warps: int = 4, interpret: bool = False, debug: bool = False ) -> jax.Array: """Computes the softmax of the input array along the specified axis. Args: x: input array axis: the axis along which to perform the computation num_warps: the number of...
Computes the softmax of the input array along the specified axis. Args: x: input array axis: the axis along which to perform the computation num_warps: the number of warps to use for executing the Triton kernel interpret: whether to interpret the kernel using pallas debug: whether to use pallas i...
softmax
python
jax-ml/jax
jax/experimental/pallas/ops/gpu/softmax.py
https://github.com/jax-ml/jax/blob/master/jax/experimental/pallas/ops/gpu/softmax.py
Apache-2.0