NVIDIA-NeMo/Speech · #16567
feat(asr): Triton kernel for the sequence-packed relative-position attention
docs/source/speechlm2/configs.rst55 + / 1 −
@@ -276,6 +276,57 @@ Padding overhead drops from ``O(B * (T_max - T_avg))`` to ``O(per-utt rounding to 2*cp_size)``. Throughput improvement scales with the variance of utterance lengths in your bucketing. +**Packed encoder sequences:**++.. code-block:: yaml++ model:+ packed_encoder_sequences: true # default false (padded encoder batches)++With ``packed_encoder_sequences`` a ``ParallelExpertEncoder`` runs its ASR and+diarization branches over the utterances of a batch token-flat, without padding+between them, and ``encoder_chunk_size_seconds`` chunks both branches after+feature stacking (see above). The attention over the packed batch picks its+backend per branch, device and precision:++* ``rel_pos`` attention (FastConformer, Sortformer) runs a fused Triton kernel on+ CUDA in float32, bfloat16 and float16, with attention dropout (``dropout_att``,+ any value up to ``1.0``). Without Triton it runs FlexAttention, which computes in+ float32 and has no attention dropout.+* ``abs_pos`` and ``rope`` attention (Transformer) run variable-length+ FlashAttention in float16 or bfloat16, with attention dropout; otherwise+ FlexAttention, without it.+* ``packed_rel_pos_attention: flex`` on a ``ConformerEncoder`` (the+ ``asr_encoder_cfg``, or the ``encoder`` of the ``diarization_model_cfg``) selects+ FlexAttention for ``rel_pos`` attention, the backend of packed runs before the+ kernel, which reproduces their outputs; it has no attention dropout. Keep it for a+ run that thresholds the diarization probabilities of a frozen Sortformer and has+ not been validated on the kernel. For an encoder mounted from a bundle+ (``pe_encoder_path``) the switch of the diarization branch is the override+ ``diar_packed_rel_pos_attention``, which leaves the bundle's architecture and+ weights as they are:++ .. code-block:: yaml++ model:+ pe_encoder_path: /path/to/parallel_expert_encoder.nemo+ pe_encoder_overrides:+ diar_packed_rel_pos_attention: flex++* A branch whose configuration has no packed form in training mode (attention+ dropout on a backend without it, among the cases+ ``ConformerEncoder.sequence_packed_unsupported_reason`` names) runs padded and+ is re-packed, so the step completes either way, with one exception: when+ ``encoder_chunk_size_seconds`` requires splitting an utterance of the batch into+ independent chunks, which has no padded form, the step raises ``TypeError`` with+ the reason instead. Independent post-stacking chunks also need+ ``subsampling: feature_stacking`` on the branch; a ``ConvSubsampling`` front end+ raises ``TypeError`` when such a split is needed, in training and in evaluation.+ Evaluation mode lifts the dropout condition only: every branch runs packed, and+ the other packed-mode restrictions (the reasons+ ``sequence_packed_unsupported_reason`` names, the chunking front end) hold in+ both modes.+ DuplexS2SModel Configuration ----------------------------- @@ -459,7 +510,10 @@ Model Parameters ``lr = optimizer.lr * multiplier``; the first matching pattern wins and unmatched parameters keep the base learning rate. - **pe_encoder_path**: Path to a standalone ParallelExpertEncoder ``.nemo`` bundle (or a pretrained model- id) to mount as the perception encoder. Optional **pe_encoder_overrides** adjust the bundle's config.+ id) to mount as the perception encoder. Optional **pe_encoder_overrides** adjust the bundle's runtime+ settings, not its architecture: the speaker-feature contract, normalization, chunking, and+ ``diar_packed_rel_pos_attention``, the packed attention backend of the diarization branch (see+ "Packed encoder sequences" above). - **pe_encoder_config**: Inline ParallelExpertEncoder config, as embedded in consolidated checkpoints. It constructs only the encoder architecture: the weights must come from the checkpoint loaded afterwards (e.g. via ``init_from_checkpoint``), otherwise the encoder keeps its random initialization.nemo/collections/asr/modules/conformer_encoder.py42 + / 17 −
@@ -101,6 +101,11 @@ class ConformerEncoder(NeuralModule, StreamingEncoder, Exportable, AccessMixin): use_triton (bool, Optional): use the fused Triton subsampling kernels, for CUDA input with 'dw_striding' subsampling. Defaults to None, enabling them whenever Triton is installed. Export always uses the PyTorch path.+ packed_rel_pos_attention (str): the backend of 'rel_pos' attention over packed sequences+ (``forward_sequence_packed``) on CUDA: 'triton', the fused attention kernel with attention+ dropout wherever Triton is installed (FlexAttention otherwise), or 'flex', FlexAttention always,+ the backend before the kernel, which computes in float32 and has no attention dropout.+ Keyword-only; defaults to 'triton'. In float64 both run the dense reference attention. reduction (str, Optional): the method of reduction, choices=['pooling', 'striding']. If no value is passed, then no reduction is performed and the models runs with the original 4x subsampling. reduction_position (int, Optional): the index of the layer to apply reduction. If -1, apply reduction@@ -384,6 +389,8 @@ def __init__( conv: ModuleBlock | None = None, self_attn: ModuleBlock | None = None, norm: ModuleBlock | None = None,+ *,+ packed_rel_pos_attention: str = 'triton', ): super().__init__() d_ff = d_model * ff_expansion_factor@@ -395,6 +402,9 @@ def __init__( self.subsampling_conv_chunking_factor = subsampling_conv_chunking_factor self.self_attention_model = self_attention_model+ if packed_rel_pos_attention not in ('triton', 'flex'):+ raise ValueError(f"packed_rel_pos_attention must be 'triton' or 'flex', got {packed_rel_pos_attention!r}.")+ self.packed_rel_pos_attention = packed_rel_pos_attention self.global_tokens = global_tokens self.global_attn_separate = global_attn_separate self.global_tokens_spacing = global_tokens_spacing@@ -933,9 +943,10 @@ def forward_sequence_packed( else: packed = _forward_packed_module(self.pre_encode, packed) - attention_context = PackedAttentionContext(packed)- # the relative-position table covers the padded length the attention kernels see- self.update_max_seq_length(seq_length=attention_context.padded_max_seqlen, device=packed.data.device)+ attention_context = PackedAttentionContext(packed, rel_pos_kernel=self.packed_rel_pos_attention == 'triton')+ # the relative-position table covers the length the attention backend reads:+ # the longest utterance for the Triton kernel, the rounded kernel shape for FlexAttention+ self.update_max_seq_length(seq_length=attention_context.rel_pos_max_seqlen, device=packed.data.device) x = packed.data if self.self_attention_model == 'rope': if self.xscale:@@ -954,10 +965,10 @@ def forward_sequence_packed( if self.pos_enc.xscale: x = x * self.pos_enc.xscale x = self.pos_enc.dropout(x)- # the relative positions L - 1 down to -(L - 1) for the padded length L, as RelPositionalEncoding.forward+ # the relative positions L - 1 down to -(L - 1) for the table length L, as RelPositionalEncoding.forward center_pos = self.pos_enc.pe.size(1) // 2 + 1- padded_len = attention_context.padded_max_seqlen- pos_emb = self.pos_enc.pe[:, center_pos - padded_len : center_pos + padded_len - 1]+ table_len = attention_context.rel_pos_max_seqlen+ pos_emb = self.pos_enc.pe[:, center_pos - table_len : center_pos + table_len - 1] if self.pos_enc.dropout_emb: pos_emb = self.pos_enc.dropout_emb(pos_emb) @@ -1002,9 +1013,11 @@ def sequence_packed_unsupported_reason(self) -> str | None: intermediate layer captures (InterCTC and ``save_encoder_tensors``, whose consumers expect padded tensors), frontends other than a linear layer or a non-causal ``striding`` or ``dw_striding`` ``ConvSubsampling``, and instance or group normalization in the convolution modules.- Attention dropout in training mode on CUDA: FlexAttention has no dropout, so ``rel_pos`` attention,- which carries its position bias through FlexAttention, needs ``dropout_att: 0``,- and ``abs_pos`` and ``rope`` attention keep their dropout only where variable-length FlashAttention runs,+ Attention dropout in training mode on CUDA: FlexAttention has no dropout, so ``rel_pos`` attention+ keeps its dropout only through its Triton kernel+ (``packed_rel_pos_attention: triton``, Triton installed, float32, bfloat16 or float16)+ or in float64, which runs the dense reference attention on every backend,+ and ``abs_pos`` and ``rope`` attention only where variable-length FlashAttention runs, in float16 or bfloat16 (autocast counts) with a head width that is a multiple of 8 up to 256; see ``packed_attention_supports_dropout``. Off CUDA the dense reference attention applies the dropout. """@@ -1045,16 +1058,28 @@ def sequence_packed_unsupported_reason(self) -> str | None: and parameter.device.type == 'cuda' and any(layer.self_attn.dropout_rate > 0 for layer in layers) ):- # off CUDA the dense per-utterance reference path applies the dropout, with or without a position bias- if self.self_attention_model == 'rel_pos':- return (- "FlexAttention has no dropout on the attention weights: set dropout_att: 0 on the encoder "- "for rel_pos attention over packed sequences; abs_pos and rope attention keep their dropout "- "through variable-length FlashAttention, which runs in float16 or bfloat16 (autocast) only."- )+ # off CUDA the dense per-utterance reference path applies the dropout, with or without a position term autocast = torch.is_autocast_enabled('cuda') dtype = torch.get_autocast_dtype('cuda') if autocast else parameter.dtype- if not packed_attention_supports_dropout(parameter.device, dtype, layers[0].self_attn.d_k):+ head_dim = layers[0].self_attn.d_k+ if self.self_attention_model == 'rel_pos':+ # the same rule as the dispatch of packed_attention: the kernel where it is selected and runs,+ # the dense reference in float64, FlexAttention otherwise+ if not packed_attention_supports_dropout(+ parameter.device,+ dtype,+ head_dim,+ rel_pos=True,+ rel_pos_kernel=self.packed_rel_pos_attention == 'triton',+ ):+ return (+ "rel_pos attention over packed sequences keeps its dropout through its Triton kernel "+ "(packed_rel_pos_attention: triton; Triton installed; float32, bfloat16 or float16) "+ "or in float64 (the dense reference attention), "+ "and FlexAttention, the path otherwise, has no dropout on the attention weights: "+ "set dropout_att: 0 on the encoder or select the kernel."+ )+ elif not packed_attention_supports_dropout(parameter.device, dtype, head_dim): return ( "Attention dropout over packed sequences runs through variable-length FlashAttention, which " "needs float16 or bfloat16 (autocast), a head width that is a multiple of 8 up to 256, and a CUDA "nemo/collections/asr/modules/parallel_expert_encoder.py30 + / 4 −
@@ -40,7 +40,7 @@ import torch.distributed as dist import yaml from lightning.pytorch import Trainer-from omegaconf import DictConfig, OmegaConf+from omegaconf import DictConfig, OmegaConf, open_dict from torch import nn from tqdm import tqdm @@ -107,6 +107,7 @@ class CTCTimestampInputs: "asr_normalize_type", "chunk_size_seconds", "diar_normalize_type",+ "diar_packed_rel_pos_attention", "frame_shift_seconds", "max_speaker_count", "missing_rttm_target",@@ -416,6 +417,7 @@ def __init__(self, cfg: DictConfig, trainer: Optional[Trainer] = None): chunk_size_seconds=self._cfg.get("chunk_size_seconds", None), sync_max_audio_length=self._cfg.get("sync_max_audio_length", False), max_speaker_count=self._cfg.get("max_speaker_count", 8),+ diar_packed_rel_pos_attention=self._cfg.get("diar_packed_rel_pos_attention", None), # Timestamp artifacts are deployment inputs, not portable PEE architecture. ctc_timestamp_model_path=None, )@@ -516,8 +518,10 @@ def load_from_nemo( Load a PE bundle and return its inner encoder. Local ``.nemo`` paths are read directly and their ``encoder.*`` tensors are loaded into a fresh shell; other identifiers go through :meth:`from_pretrained`. ``config_overrides`` is restricted- to runtime-semantic fields so it resolves legacy bundle ambiguity without allowing a recipe to- replace the saved encoder architecture accidentally, and it requires a local path.+ to runtime-semantic fields (the speaker-feature contract, normalization, chunking, the packed+ attention backend of the diarization branch, ``diar_packed_rel_pos_attention``) so it resolves legacy+ bundle ambiguity without allowing a recipe to replace the saved encoder architecture accidentally,+ and it requires a local path. Args: model_path_or_name (str): Local ``.nemo`` path or pretrained model name.@@ -704,6 +708,7 @@ def __init__( max_speaker_count: int = 8, ctc_timestamp_model_path: Optional[str] = None, ctc_timestamp_alignment: Optional[Dict[str, Any]] = None,+ diar_packed_rel_pos_attention: Optional[str] = None, ): """ Initialize the ASR and diarization experts and their fusion layers.@@ -735,6 +740,12 @@ def __init__( max_speaker_count (int): Fixed speaker dimension retained for boolean diarization timestamps. ctc_timestamp_model_path (Optional[str]): Runtime-only lightweight CTC timestamp artifact path. ctc_timestamp_alignment (Optional[Dict[str, Any]]): Timestamp aligner options, including backend selection.+ diar_packed_rel_pos_attention (Optional[str]): Backend of the diarization encoder's ``rel_pos``+ attention over packed sequences, ``'triton'`` or ``'flex'``, replacing the+ ``packed_rel_pos_attention`` of its config; a runtime override of a bundle+ (``config_overrides`` of :meth:`ParallelExpertEncoderPT.load_from_nemo`, the+ ``pe_encoder_overrides`` of a SALM recipe), which leaves the saved architecture and weights+ as they are. ``None`` keeps the config's backend. """ super().__init__() @@ -759,6 +770,20 @@ def __init__( self._feat_in = self.asr_encoder._feat_in diarization_model_cfg = _clone_config(diarization_model_cfg)+ self.diar_packed_rel_pos_attention = diar_packed_rel_pos_attention+ if diar_packed_rel_pos_attention is not None:+ if diar_packed_rel_pos_attention not in ("triton", "flex"):+ raise ValueError(+ f"diar_packed_rel_pos_attention must be 'triton' or 'flex', got {diar_packed_rel_pos_attention!r}."+ )+ diar_encoder_target = str(diarization_model_cfg.encoder.get("_target_", ""))+ if not diar_encoder_target.endswith("ConformerEncoder"):+ raise ValueError(+ "diar_packed_rel_pos_attention selects the packed rel_pos attention backend of a ConformerEncoder "+ f"diarization branch; the diarization encoder is {diar_encoder_target or 'unnamed'}."+ )+ with open_dict(diarization_model_cfg.encoder):+ diarization_model_cfg.encoder.packed_rel_pos_attention = diar_packed_rel_pos_attention if diar_normalize_type is None: diar_normalize_type = diarization_model_cfg.get("preprocessor", {}).get("normalize", None) self.diar_normalize_type = diar_normalize_type@@ -1019,7 +1044,8 @@ def _forward_packed_branch( Run an encoder token-flat, optionally splitting after feature stacking. Encoders without ``forward_sequence_packed``, or whose ``supports_sequence_packed_output`` denies it for their configuration (a ``ConformerEncoder`` training with attention dropout- over ``rel_pos`` attention, for one), fall back to a padded forward and are re-packed.+ on a packed attention backend without it, FlexAttention, for one;+ its ``sequence_packed_unsupported_reason`` lists them), fall back to a padded forward and are re-packed. When a chunk size is set and an utterance exceeds it, feature stacking runs once over each full utterance, and the encoder layers then see each chunk as an independent sequence. Chunking requires ``subsampling='feature_stacking'``.nemo/collections/asr/parts/submodules/multi_head_attention.py14 + / 13 −
@@ -223,7 +223,7 @@ def forward_packed( Args: x: layer input of all utterances, shape ``(T_total, n_feat)``. context: packing metadata of the batch.- pos_emb: relative positional embedding ``(1, 2 * max_seqlen - 1, n_feat)``,+ pos_emb: relative positional embedding ``(1, 2 * context.rel_pos_max_seqlen - 1, n_feat)``, used by the Transformer-XL subclass only. Returns:@@ -237,13 +237,14 @@ def forward_packed( k = self.linear_k(x).view(-1, self.h, self.d_k) v = self.linear_v(x).view(-1, self.h, self.d_k) q, k = self._apply_packed_pos_emb(q, k, context)- q, rel_pos_bias = self._packed_rel_pos_terms(q, pos_emb)+ q, pos_query, pos_emb = self._packed_rel_pos_terms(q, pos_emb) out = packed_attention( q, k, v, context,- rel_pos_bias=rel_pos_bias,+ pos_query=pos_query,+ pos_emb=pos_emb, dropout_p=self.dropout_rate if self.training else 0.0, ) return self.linear_out(out.reshape(-1, self.h * self.d_k))@@ -256,9 +257,9 @@ def _apply_packed_pos_emb( def _packed_rel_pos_terms( self, q: torch.Tensor, pos_emb: torch.Tensor | None- ) -> tuple[torch.Tensor, torch.Tensor | None]:- """Hook for the Transformer-XL subclass: the query with its content bias and the position bias, or None."""- return q, None+ ) -> tuple[torch.Tensor, torch.Tensor | None, torch.Tensor | None]:+ """Hook for the Transformer-XL subclass: the query with its content bias and the two position-term factors."""+ return q, None, None def update_cache(self, key, value, query, cache): if cache is not None:@@ -418,20 +419,20 @@ def forward(self, query, key, value, mask, pos_emb, cache=None): def _packed_rel_pos_terms( self, q: torch.Tensor, pos_emb: torch.Tensor | None- ) -> tuple[torch.Tensor, torch.Tensor | None]:- """Matrix (c) folded into the query and matrices (b) + (d) as a bias over relative positions.+ ) -> tuple[torch.Tensor, torch.Tensor | None, torch.Tensor | None]:+ """Matrix (c) folded into the query, and the factors of matrices (b) + (d). - The bias has shape (T_total, head, 2 * max_seqlen - 1);- entry ``max_seqlen - 1 - (i - j)`` of the last axis is the term of query position i and key position j,+ The position query ``(T_total, head, d_k)`` and the projected embedding ``(R, head, d_k)`` form the bias+ over relative positions inside the attention kernel;+ its entry ``(R - 1) / 2 - (i - j)`` is the term of query position i and key position j, which is what ``rel_shift`` selects in the padded forward. """ if pos_emb is None: raise ValueError("Transformer-XL attention over packed sequences needs pos_emb.")- p = self.linear_pos(pos_emb).view(-1, self.h, self.d_k) # (2 * max_seqlen - 1, head, d_k)+ p = self.linear_pos(pos_emb).view(-1, self.h, self.d_k) # (R, head, d_k) bias_u = self.pos_bias_u.to(q.dtype) bias_v = self.pos_bias_v.to(q.dtype)- rel_pos_bias = torch.einsum('thd,phd->thp', q + bias_v, p)- return q + bias_u, rel_pos_bias+ return q + bias_u, q + bias_v, p class RelPositionMultiHeadAttentionLongformer(RelPositionMultiHeadAttention):nemo/collections/asr/parts/submodules/packed_attention.py130 + / 32 −
@@ -30,6 +30,13 @@ packed_encoder_position_ids, packed_sequence_ids, )+from nemo.core.utils.optional_libs import TRITON_AVAILABLE++if TRITON_AVAILABLE:+ from nemo.collections.asr.parts.triton.rel_pos_attention import (+ PACKED_REL_POS_ATTENTION_DTYPES,+ packed_rel_pos_attention,+ ) __all__ = [ "PackedAttentionContext",@@ -47,8 +54,11 @@ # are keyed by the powers of two 64, 128 and 256: any other width falls to a generic configuration # whose shared memory exceeds the 101 KB of consumer Blackwell GPUs (torch 2.12, width 44, the FastConformer Small head). FLEX_MIN_HEAD_DIM = 16-# The FlexAttention kernels are compiled statically per shape (a fully dynamic compile cannot trace the computed-# gather of the relative-position bias; only the bias's token axis is marked dynamic, see _flex_packed_attention).+# FlexAttention is the relative-position path without Triton+# (with it, nemo.collections.asr.parts.triton.rel_pos_attention runs; float64 takes the reference path).+# Its kernels are compiled statically per shape+# (a fully dynamic compile cannot trace the computed gather of the relative-position bias;+# only the bias's token axis is marked dynamic, see _flex_packed_attention). # The token axis and the relative-position width the kernels see are rounded up to powers of two # from these floors, so the kernels of a run are bounded by the logarithms of the two ranges, # not by the number of distinct batches, and the recompile limit below leaves room for them.@@ -62,33 +72,43 @@ class PackedAttentionContext: """Packing metadata of one batch, shared by all attention layers of a packed forward. - The FlexAttention block mask is derived from the utterance boundaries,+ On CUDA with Triton the relative-position attention runs the kernel of+ :mod:`nemo.collections.asr.parts.triton.rel_pos_attention` over the utterance boundaries as they are.+ Without it, or with ``rel_pos_kernel`` off, FlexAttention runs with a block mask derived from the boundaries, without evaluating a mask over the dense token grid: a key block is complete for a query block when both lie inside the same utterance, partial when it intersects an utterance that the query block touches, and skipped otherwise. Args: packed: the packed activations entering the encoder layers; only their sequence metadata is used.+ rel_pos_kernel: whether relative-position attention runs the Triton kernel where it can (the default),+ or FlexAttention on CUDA whatever the dtype, the backend before the kernel,+ which computes in float32 and has no dropout on the attention weights. """ - def __init__(self, packed: PackedEncoderActivations):+ def __init__(self, packed: PackedEncoderActivations, *, rel_pos_kernel: bool = True): self.lengths = packed.lengths self.cu_seqlens = packed.cu_seqlens self.max_seqlen = packed.max_seqlen self.total_tokens = packed.total_tokens self.device = packed.data.device self.sequence_ids = packed_sequence_ids(packed) self.position_ids = packed_encoder_position_ids(packed)- # the shapes the compiled attention kernels see, see TOKEN_PADDING and LENGTH_PADDING+ # the shapes the compiled FlexAttention kernels see, see TOKEN_PADDING and LENGTH_PADDING self.padded_total_tokens = _padded_size(self.total_tokens, TOKEN_PADDING) self.padded_max_seqlen = _padded_size(self.max_seqlen, LENGTH_PADDING)+ # the Triton kernel reads the relative-position table of the longest utterance (at least one row),+ # FlexAttention one of its rounded length+ self.rel_pos_kernel = rel_pos_kernel and TRITON_AVAILABLE and self.device.type == "cuda"+ self.rel_pos_max_seqlen = max(self.max_seqlen, 1) if self.rel_pos_kernel else self.padded_max_seqlen self._block_mask = None self._bias_rows = None self._sequence_slices = None+ self._seq_lens = None @classmethod- def from_lengths(cls, lengths: Tensor) -> "PackedAttentionContext":+ def from_lengths(cls, lengths: Tensor, *, rel_pos_kernel: bool = True) -> "PackedAttentionContext": """Metadata for token-flat ids or states whose sequences have these lengths, in packing order.""" lengths = lengths.to(torch.int64) total_tokens = int(lengths.sum().item())@@ -97,7 +117,7 @@ def from_lengths(cls, lengths: Tensor) -> "PackedAttentionContext": packed = PackedEncoderActivations.from_validated( placeholder, lengths, lengths_to_cu_seqlens(lengths), max_seqlen )- return cls(packed)+ return cls(packed, rel_pos_kernel=rel_pos_kernel) @property def sequence_slices(self) -> tuple[tuple[int, int], ...]:@@ -107,6 +127,18 @@ def sequence_slices(self) -> tuple[tuple[int, int], ...]: self._sequence_slices = tuple(zip(offsets[:-1], offsets[1:])) return self._sequence_slices + @property+ def seq_starts(self) -> Tensor:+ """First token of every utterance, shape ``(B,)`` int32, for the Triton kernel."""+ return self.cu_seqlens[:-1]++ @property+ def seq_lens(self) -> Tensor:+ """Tokens of every utterance, shape ``(B,)`` int32, for the Triton kernel."""+ if self._seq_lens is None:+ self._seq_lens = self.lengths.to(torch.int32)+ return self._seq_lens+ def block_mask(self) -> BlockMask: """The document block mask over the padded token axis, built once per batch.""" if self._block_mask is None:@@ -199,44 +231,64 @@ def packed_attention( v: Tensor, context: PackedAttentionContext, *,+ pos_query: Tensor | None = None,+ pos_emb: Tensor | None = None, rel_pos_bias: Tensor | None = None, dropout_p: float = 0.0, scale: float | None = None, ) -> Tensor: """Attend within utterances over token-flat queries, keys and values. - On CUDA, attention without a position bias runs variable-length FlashAttention in half precision when available,- and everything else runs FlexAttention with the document block mask of the context.- Elsewhere the utterances are attended one at a time with dense attention,+ On CUDA, attention without a position term runs variable-length FlashAttention in half precision when available,+ and attention with the Transformer-XL position term given by its factors runs the Triton kernel+ of :mod:`nemo.collections.asr.parts.triton.rel_pos_attention` (float32, bfloat16 and float16, with dropout)+ where the context selects it (``context.rel_pos_kernel``);+ everything else, the materialized ``rel_pos_bias`` included, runs FlexAttention+ with the document block mask of the context.+ Elsewhere, and for float64 (FlexAttention's kernels compute in float32 at most),+ the utterances are attended one at a time with dense attention, which is also the reference of the unit tests. Args: q: queries, shape ``(T_total, H, d_k)``. k: keys, shape ``(T_total, H, d_k)``. v: values, shape ``(T_total, H, d_k)``. context: packing metadata of the batch.- rel_pos_bias: optional Transformer-XL position bias, shape ``(T_total, H, 2 * max_seqlen - 1)``,- whose last axis is indexed by ``max_seqlen - 1 - (query position - key position)``;- it is scaled like the content scores and added to them.- dropout_p: dropout on the attention weights,- supported by the variable-length FlashAttention path and the reference path but not by FlexAttention+ pos_query: queries with their position bias added, shape ``(T_total, H, d_k)``;+ with ``pos_emb`` the Transformer-XL position term ``pos_query[i] . pos_emb[c - (i - j)]``+ of query position ``i`` and key position ``j`` is scaled like the content scores and added to them;+ both or neither.+ pos_emb: projected relative position embedding, shape ``(R, H, d_k)`` with odd ``R``,+ whose row ``c = (R - 1) / 2`` is the relative position zero;+ it covers at least ``context.rel_pos_max_seqlen - 1`` positions each way.+ rel_pos_bias: the position term materialized over the relative positions instead of its factors,+ shape ``(T_total, H, R)`` with odd ``R`` and the row convention of ``pos_emb``+ (``R = 2 * max_seqlen - 1`` indexes it by ``max_seqlen - 1 - (i - j)``);+ the form of the FlexAttention and reference paths, which it keeps on.+ dropout_p: dropout on the attention weights, supported by every path but FlexAttention (see ``packed_attention_supports_dropout``). scale: score scale, ``1 / sqrt(d_k)`` by default. Returns: Context vectors of shape ``(T_total, H, d_k)``. """+ if (pos_query is None) != (pos_emb is None):+ raise ValueError("pos_query and pos_emb come together: give both or neither.")+ if rel_pos_bias is not None and pos_query is not None:+ raise ValueError("The position term comes either as rel_pos_bias or as pos_query and pos_emb, not both.") if scale is None: scale = 1.0 / math.sqrt(q.shape[-1]) if context.total_tokens == 0: # keep every projection in the autograd graph when a rank holds no valid token, # so distributed gradient reductions see the same parameters on all ranks anchor = q.sum() + k.sum()+ if pos_query is not None:+ anchor = anchor + pos_query.sum() + pos_emb.sum() if rel_pos_bias is not None: anchor = anchor + rel_pos_bias.sum() return v + 0.0 * anchor.to(v.dtype)- if q.is_cuda:- if rel_pos_bias is None:+ if q.is_cuda and q.dtype != torch.float64:+ if pos_query is None and rel_pos_bias is None: flash = _flash_attention_varlen(q) if flash is not None: q, k, v = q.contiguous(), k.contiguous(), v.contiguous()@@ -252,27 +304,60 @@ def packed_attention( softmax_scale=scale, causal=False, )+ elif pos_query is not None and context.rel_pos_kernel and q.dtype in PACKED_REL_POS_ATTENTION_DTYPES:+ # the context's lengths and max_seqlen agree by construction: no device read for the check+ return packed_rel_pos_attention(+ q,+ k,+ v,+ pos_query,+ pos_emb,+ context.seq_starts,+ context.seq_lens,+ context.max_seqlen,+ dropout_p=dropout_p,+ scale=scale,+ check_lengths=False,+ ) if dropout_p > 0.0: raise NotImplementedError(- "FlexAttention has no dropout on the attention weights: "- "set dropout_att: 0 on the encoder for rel_pos attention over packed sequences; "- "abs_pos and rope attention keep their dropout through variable-length FlashAttention, "- "which runs in float16 or bfloat16 (autocast) only."+ "FlexAttention has no dropout on the attention weights. "+ "rel_pos attention keeps its dropout through its Triton kernel "+ "(Triton installed, float32, bfloat16 or float16), "+ "abs_pos and rope attention through variable-length FlashAttention in float16 or bfloat16 (autocast); "+ "otherwise set dropout_att: 0 on the encoder for packed sequences." )- return _flex_packed_attention(q, k, v, context, rel_pos_bias=rel_pos_bias, scale=scale)- return _reference_packed_attention(q, k, v, context, rel_pos_bias=rel_pos_bias, dropout_p=dropout_p, scale=scale)+ return _flex_packed_attention(+ q, k, v, context, rel_pos_bias=_materialized(pos_query, pos_emb, rel_pos_bias), scale=scale+ )+ return _reference_packed_attention(+ q,+ k,+ v,+ context,+ rel_pos_bias=_materialized(pos_query, pos_emb, rel_pos_bias),+ dropout_p=dropout_p,+ scale=scale,+ ) -def packed_attention_supports_dropout(device: torch.device, dtype: torch.dtype, head_dim: int) -> bool:- """Whether ``packed_attention`` without a position bias applies dropout on this device, dtype and head width.+def packed_attention_supports_dropout(+ device: torch.device, dtype: torch.dtype, head_dim: int, *, rel_pos: bool = False, rel_pos_kernel: bool = True+) -> bool:+ """Whether ``packed_attention`` applies dropout on this device, dtype and head width: the dispatch rule. - Off CUDA it always does (the dense reference path); on CUDA only where variable-length FlashAttention runs:- float16 or bfloat16, a head width that is a multiple of 8 up to 256, compute capability 8 or newer,- since FlexAttention has no dropout.- Attention with a position bias (``rel_pos``) runs FlexAttention on CUDA whatever the dtype.+ Off CUDA, and on CUDA in float64, it always does (the dense reference path).+ On CUDA without a position term, only where variable-length FlashAttention runs:+ float16 or bfloat16, a head width that is a multiple of 8 up to 256, compute capability 8 or newer.+ With the Transformer-XL position term (``rel_pos``), only where its Triton kernel runs:+ selected (``rel_pos_kernel``, the switch of the ``PackedAttentionContext``), Triton installed,+ in float32, bfloat16 or float16.+ FlexAttention, the path otherwise, has no dropout. """- if device.type != 'cuda':+ if device.type != 'cuda' or dtype == torch.float64: return True+ if rel_pos:+ return rel_pos_kernel and TRITON_AVAILABLE and dtype in PACKED_REL_POS_ATTENTION_DTYPES if dtype not in (torch.float16, torch.bfloat16) or head_dim > 256 or head_dim % 8 != 0: return False # a function-level import: the modules package initializes the encoders, which import this module@@ -407,8 +492,21 @@ def _flash_attention_varlen(q: Tensor) -> Callable | None: return _select_flash_attention_varlen(q, static_eligible=head_dim <= 256 and head_dim % 8 == 0) +def _materialized(pos_query: Tensor | None, pos_emb: Tensor | None, rel_pos_bias: Tensor | None) -> Tensor | None:+ """The unscaled position term over all relative positions, shape ``(T_total, H, R)``, from either form."""+ if pos_query is None:+ return rel_pos_bias+ return torch.einsum("thd,rhd->thr", pos_query, pos_emb)++ def _flex_packed_attention(- q: Tensor, k: Tensor, v: Tensor, context: PackedAttentionContext, *, rel_pos_bias: Tensor | None, scale: float+ q: Tensor,+ k: Tensor,+ v: Tensor,+ context: PackedAttentionContext,+ *,+ rel_pos_bias: Tensor | None,+ scale: float, ) -> Tensor: total_tokens = context.total_tokens padded_total = context.padded_total_tokens@@ -461,7 +559,7 @@ def _reference_packed_attention( dropout_p: float, scale: float, ) -> Tensor:- """Dense attention one utterance at a time, with the same bias convention as the kernels."""+ """Dense attention one utterance at a time, with the same position-term convention as the kernels.""" outputs = [] center = (rel_pos_bias.shape[-1] - 1) // 2 if rel_pos_bias is not None else 0 for start, end in context.sequence_slices:nemo/collections/asr/parts/triton/rel_pos_attention.pyadded914 + / 0 −
@@ -0,0 +1,914 @@+# SPDX-FileCopyrightText: Copyright (c) 2026, NVIDIA CORPORATION & AFFILIATES. All rights reserved.+# SPDX-License-Identifier: Apache-2.0+#+# Licensed under the Apache License, Version 2.0 (the "License");+# you may not use this file except in compliance with the License.+# You may obtain a copy of the License at+#+# http://www.apache.org/licenses/LICENSE-2.0+#+# Unless required by applicable law or agreed to in writing, software+# distributed under the License is distributed on an "AS IS" BASIS,+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.+# See the License for the specific language governing permissions and+# limitations under the License.++"""Transformer-XL self-attention over sequence-packed activations, with dropout on the attention weights.++The utterances of a batch are concatenated along the token axis;+``seq_starts`` and ``seq_lens`` say where each one lies, so gaps between them are allowed,+and a program of the kernels never reads or writes a row outside its utterance.+Queries, keys and values have shape ``(T_total, H, D)``.+The score of query position ``i`` and key position ``j`` of one utterance is+``scale * q_i . k_j + scale * pos_query_i . pos_emb[c - (i - j)]`` with ``c = max_seqlen - 1``,+the convention of ``RelPositionMultiHeadAttention`` (``rel_shift`` selects the same entries in the padded forward).++The position term ``(T_total, H, 2 * max_seqlen - 1)`` is computed from ``pos_query`` and ``pos_emb``+inside the custom ops, in the forward and again in the backward,+so it is never saved for the backward and no layer retains one;+the kernels read it through 64-bit offsets,+since ``H * T_total * (2 * max_seqlen - 1)`` passes 2**31 at large packed batches.+Its buffer is ``(H, T_total, R)`` with ``R`` rounded up to a multiple of eight,+because an odd leading dimension sends the GEMMs to slow unaligned kernels;+the kernels take the strides of the ``(T_total, H, R)`` view.++Dropout on the attention weights is a Philox hash of the global query row and the local key column,+with the head mixed into the seed, so the backward recomputes the mask instead of storing it.+The seed is a one-element device tensor read inside the kernels:+drawn on the device for every call, so a CUDA-graph replay draws a fresh mask,+or given by the caller for a reproducible run.+The gradient of the position term is row-owned (every query row writes its own row), without atomics,+so the backward is deterministic.++One head dimension serves queries, keys, values and the position embedding, as in RETURNN's kernel+(``returnn/torch/util/rel_pos_att_triton.py`` of https://github.com/rwth-i6/returnn), which this follows.+The backward recomputes ``delta = sum_j p_ij dp_ij`` in a pass of its own+instead of the flash-attention shortcut ``rowsum(out * d_out)``, which holds only for an exactly accumulated ``out``;+with bf16 storage the shortcut's rounding error enters the position-term gradient as a per-row bias.++The tiles of the four kernels are tuned on a GB300 (228 KB of shared memory per block).+A GPU with less shared memory refuses the first configuration at its first launch (Triton's ``OutOfResources``);+the launch then steps down a ladder of smaller tiles, once per kernel, device, dtype and head width,+so the kernels run on workstation and consumer GPUs as well, at a lower speed.+"""++import math+from typing import Callable++import torch+import triton+import triton.language as tl+from torch import Tensor+from triton.runtime.errors import OutOfResources++__all__ = ["PACKED_REL_POS_ATTENTION_DTYPES", "packed_rel_pos_attention"]++# the dtypes the kernels read and write; the softmax and the accumulations run in float32 either way+PACKED_REL_POS_ATTENTION_DTYPES = (torch.float32, torch.bfloat16, torch.float16)++# Tiles (BLOCK_M, BLOCK_N, warps, pipeline stages);+# the first entry of each ladder is the configuration tuned on a GB300, the later ones need less shared memory.+# The forward: 64 x 128 tiles with eight warps and two stages (tuned at D = 128; 148 KB in float32).+FORWARD_TILES = ((64, 128, 8, 2), (64, 64, 8, 2), (64, 64, 4, 1), (32, 64, 4, 1), (32, 32, 4, 1))+# The backward kernels: 64 x 64 tiles up to D = 64, 32 x 32 above.+BACKWARD_TILES = ((64, 64, 4, 3), (32, 32, 4, 3), (32, 32, 4, 1), (16, 32, 4, 1))+BACKWARD_TILES_WIDE = BACKWARD_TILES[1:]+# the head enters the dropout seed through this stride+DROPOUT_HEAD_SEED_STRIDE = tl.constexpr(1000003)+++def packed_rel_pos_attention(+ q: Tensor,+ k: Tensor,+ v: Tensor,+ pos_query: Tensor,+ pos_emb: Tensor,+ seq_starts: Tensor,+ seq_lens: Tensor,+ max_seqlen: int,+ *,+ dropout_p: float = 0.0,+ dropout_seed: Tensor | None = None,+ scale: float | None = None,+ check_lengths: bool = True,+) -> Tensor:+ """Attend within utterances over token-flat queries, keys and values with the Transformer-XL position term.++ Args:+ q: queries with the content bias added, shape ``(T_total, H, D)``; float32, bfloat16 or float16.+ k: keys, shape ``(T_total, H, D)``, dtype of ``q``.+ v: values, shape ``(T_total, H, D)``, dtype of ``q``.+ pos_query: queries with the position bias added, shape ``(T_total, H, D)``, dtype of ``q``.+ pos_emb: projected relative position embedding, shape ``(R, H, D)`` with odd ``R``, dtype of ``q``;+ row ``(R - 1) / 2 - d`` holds the relative position ``d``,+ so the table must cover at least ``max_seqlen - 1`` positions each way (``R >= 2 * max_seqlen - 1``).+ seq_starts: first row of every utterance, shape ``(B,)``, integer.+ seq_lens: rows of every utterance, shape ``(B,)``, integer; the rows between the utterances are never read.+ max_seqlen: longest utterance, a host integer, which sizes the launch grid and the table the kernels read;+ a length beyond it is rejected (``check_lengths``).+ dropout_p: dropout probability on the attention weights, up to one;+ at one every weight is dropped and the output is zero, as ``nn.Dropout(1.0)`` on the weights.+ dropout_seed: one-element integer tensor with the Philox seed for a reproducible mask;+ drawn on the device of ``q`` by default, which gives a fresh mask on every CUDA-graph replay.+ scale: factor of both score terms, ``1 / sqrt(D)`` by default.+ check_lengths: read the lengths from the device once and reject one beyond ``max_seqlen``,+ which would otherwise leave the query rows past the launched tiles zero+ and send the position lookups past the table. The read is impossible in compiled code and under+ CUDA-graph capture, so a compiled or captured call with the check on is refused:+ such a caller validates the lengths against ``max_seqlen`` itself, outside the compiled region,+ and passes ``False``, as the ``PackedAttentionContext`` of the encoders does for metadata whose+ bound holds by construction, which keeps the launch free of device reads.++ Returns:+ Context vectors of shape ``(T_total, H, D)`` and the dtype of ``q``; rows outside every utterance are zero.+ """+ if q.ndim != 3:+ raise ValueError(f"q must have shape (T_total, H, D), got {tuple(q.shape)}.")+ if not q.is_cuda:+ raise RuntimeError("The packed relative-position attention kernel requires CUDA tensors.")+ if q.dtype not in PACKED_REL_POS_ATTENTION_DTYPES:+ raise TypeError(f"q must be float32, bfloat16 or float16, got {q.dtype}.")+ for name, tensor in (("k", k), ("v", v), ("pos_query", pos_query)):+ if tensor.shape != q.shape:+ raise ValueError(f"{name} must have the shape of q {tuple(q.shape)}, got {tuple(tensor.shape)}.")+ for name, tensor in (("k", k), ("v", v), ("pos_query", pos_query), ("pos_emb", pos_emb)):+ if tensor.dtype != q.dtype or tensor.device != q.device:+ raise TypeError(f"{name} must be {q.dtype} on {q.device}, got {tensor.dtype} on {tensor.device}.")+ total, heads, head_dim = q.shape+ if pos_emb.ndim != 3 or pos_emb.shape[1:] != (heads, head_dim):+ raise ValueError(f"pos_emb must have shape (R, {heads}, {head_dim}), got {tuple(pos_emb.shape)}.")+ width = pos_emb.shape[0]+ if width % 2 == 0:+ raise ValueError(f"pos_emb must have an odd number of rows, got {width}.")+ if max_seqlen < 0 or width < 2 * max_seqlen - 1:+ raise ValueError(f"pos_emb with {width} rows covers no utterance of max_seqlen {max_seqlen} frames.")+ if seq_starts.shape != seq_lens.shape or seq_starts.ndim != 1:+ raise ValueError(+ f"seq_starts and seq_lens must have shape (B,), got {tuple(seq_starts.shape)} and {tuple(seq_lens.shape)}."+ )+ for name, tensor in (("seq_starts", seq_starts), ("seq_lens", seq_lens)):+ if tensor.dtype not in (torch.int32, torch.int64) or tensor.device != q.device:+ raise TypeError(f"{name} must be int32 or int64 on {q.device}, got {tensor.dtype} on {tensor.device}.")+ if not 0.0 <= dropout_p <= 1.0:+ raise ValueError(f"dropout_p must be in [0, 1], got {dropout_p}.")+ if total * heads * head_dim >= 2**31:+ raise ValueError(+ f"q with {total} x {heads} x {head_dim} elements exceeds the 32-bit row offsets of the kernels."+ )+ if scale is None:+ scale = 1.0 / math.sqrt(head_dim)+ if check_lengths:+ _check_lengths(seq_lens, max_seqlen)+ if total == 0 or max_seqlen == 0 or dropout_p == 1.0:+ # nothing to attend, or every weight dropped: zeros, with a zero gradient edge to every input+ return _zeros_with_gradient_edges(q, k, v, pos_query, pos_emb)+ if width > 2 * max_seqlen - 1:+ center = (width - 1) // 2+ pos_emb = pos_emb[center - (max_seqlen - 1) : center + max_seqlen]+ if dropout_seed is not None and (+ dropout_seed.numel() != 1 or dropout_seed.dtype not in (torch.int32, torch.int64)+ ):+ raise ValueError(+ f"dropout_seed must be one integer, got {dropout_seed.dtype} of shape {tuple(dropout_seed.shape)}."+ )+ if dropout_seed is not None:+ dropout_seed = dropout_seed.to(device=q.device, dtype=torch.int32)+ elif dropout_p > 0.0:+ dropout_seed = torch.randint(0, 2**31 - 1, (1,), dtype=torch.int32, device=q.device)+ else:+ dropout_seed = torch.zeros((1,), dtype=torch.int32, device=q.device)+ out, _ = torch.ops.nemo_asr.packed_rel_pos_attention_fwd(+ q.contiguous(),+ k.contiguous(),+ v.contiguous(),+ pos_query.contiguous(),+ pos_emb.contiguous(),+ seq_starts.to(torch.int32),+ seq_lens.to(torch.int32),+ max_seqlen,+ dropout_p,+ dropout_seed,+ scale,+ )+ return out+++@torch.library.custom_op("nemo_asr::packed_rel_pos_attention_fwd", mutates_args=(), device_types="cuda")+def _attention_fwd(+ q: Tensor,+ k: Tensor,+ v: Tensor,+ pos_query: Tensor,+ pos_emb: Tensor,+ seq_starts: Tensor,+ seq_lens: Tensor,+ max_seqlen: int,+ dropout_p: float,+ dropout_seed: Tensor,+ scale: float,+) -> tuple[Tensor, Tensor]:+ # the inputs are made contiguous here as well: a compiled graph may feed the op any layout,+ # and the kernels read the starts and lengths with unit stride+ q, k, v = q.contiguous(), k.contiguous(), v.contiguous()+ seq_starts, seq_lens = seq_starts.contiguous(), seq_lens.contiguous()+ pos_emb = _padded_rows(pos_emb.contiguous())+ position_term = _position_term(pos_query.contiguous(), pos_emb, scale)+ out, lse = _forward(+ q, k, v, _term_view(position_term), seq_starts, seq_lens, max_seqlen, dropout_p, dropout_seed, scale+ )+ return out, lse+++@_attention_fwd.register_fake+def _attention_fwd_fake(+ q: Tensor,+ k: Tensor,+ v: Tensor,+ pos_query: Tensor,+ pos_emb: Tensor,+ seq_starts: Tensor,+ seq_lens: Tensor,+ max_seqlen: int,+ dropout_p: float,+ dropout_seed: Tensor,+ scale: float,+) -> tuple[Tensor, Tensor]:+ del k, v, pos_query, pos_emb, seq_starts, seq_lens, max_seqlen, dropout_p, dropout_seed, scale+ # new_empty, not empty_like: the outputs are contiguous whatever the traced input layout+ return q.new_empty(tuple(q.shape)), q.new_empty(tuple(q.shape[:2]), dtype=torch.float32)+++@torch.library.custom_op("nemo_asr::packed_rel_pos_attention_bwd", mutates_args=(), device_types="cuda")+def _attention_bwd(+ q: Tensor,+ k: Tensor,+ v: Tensor,+ pos_query: Tensor,+ pos_emb: Tensor,+ seq_starts: Tensor,+ seq_lens: Tensor,+ max_seqlen: int,+ lse: Tensor,+ d_out: Tensor,+ dropout_p: float,+ dropout_seed: Tensor,+ scale: float,+) -> tuple[Tensor, Tensor, Tensor, Tensor, Tensor]:+ q, k, v, pos_query = q.contiguous(), k.contiguous(), v.contiguous(), pos_query.contiguous()+ seq_starts, seq_lens = seq_starts.contiguous(), seq_lens.contiguous()+ total, heads, head_dim = q.shape+ width = pos_emb.shape[0]+ pos_emb = _padded_rows(pos_emb.contiguous())+ position_term = _position_term(pos_query, pos_emb, scale)+ # the position-term gradient takes the layout of the term; zeroed as a whole, the padding columns stay zero+ d_position_term = torch.zeros_like(position_term, dtype=torch.float32)+ dq, dk, dv = _backward(+ q,+ k,+ v,+ _term_view(position_term),+ seq_starts,+ seq_lens,+ max_seqlen,+ lse,+ d_out.contiguous(),+ dropout_p,+ dropout_seed,+ scale,+ _term_view(d_position_term),+ )+ del position_term+ # the chain rule through the position term, GEMMs in the io dtype on the row-padded buffers+ # (the zero padding columns contribute nothing); the scale is applied in float32 before the cast,+ # as the kernels do for the content gradients, since the unscaled term can exceed the float16 range+ d_position_term = d_position_term.mul_(scale).to(q.dtype)+ d_pos_query = torch.empty((heads, total, head_dim), dtype=q.dtype, device=q.device)+ torch.baddbmm(d_pos_query, d_position_term, pos_emb.transpose(0, 1), beta=0.0, out=d_pos_query)+ # rows outside every utterance have a zero gradient row, but their position queries may hold anything,+ # and zero times a non-finite payload is NaN: they are zeroed for this GEMM+ pos_query = torch.where(_utterance_rows(seq_starts, seq_lens, total)[:, None, None], pos_query, 0.0)+ d_pos_emb = torch.empty((heads, pos_emb.shape[0], head_dim), dtype=q.dtype, device=q.device)+ torch.baddbmm(d_pos_emb, d_position_term.transpose(1, 2), pos_query.transpose(0, 1), beta=0.0, out=d_pos_emb)+ return (+ dq.to(q.dtype),+ dk.to(q.dtype),+ dv.to(q.dtype),+ d_pos_query.permute(1, 0, 2).contiguous(),+ d_pos_emb[:, :width].permute(1, 0, 2).contiguous(),+ )+++@_attention_bwd.register_fake+def _attention_bwd_fake(+ q: Tensor,+ k: Tensor,+ v: Tensor,+ pos_query: Tensor,+ pos_emb: Tensor,+ seq_starts: Tensor,+ seq_lens: Tensor,+ max_seqlen: int,+ lse: Tensor,+ d_out: Tensor,+ dropout_p: float,+ dropout_seed: Tensor,+ scale: float,+) -> tuple[Tensor, Tensor, Tensor, Tensor, Tensor]:+ del seq_starts, seq_lens, max_seqlen, lse, d_out, dropout_p, dropout_seed, scale+ return (+ q.new_empty(tuple(q.shape)),+ k.new_empty(tuple(k.shape)),+ v.new_empty(tuple(v.shape)),+ pos_query.new_empty(tuple(pos_query.shape)),+ pos_emb.new_empty(tuple(pos_emb.shape)),+ )+++def _setup_context(ctx, inputs, output):+ q, k, v, pos_query, pos_emb, seq_starts, seq_lens, max_seqlen, dropout_p, dropout_seed, scale = inputs+ _, lse = output+ ctx.save_for_backward(q, k, v, pos_query, pos_emb, seq_starts, seq_lens, lse, dropout_seed)+ ctx.max_seqlen, ctx.dropout_p, ctx.scale = max_seqlen, dropout_p, scale+++def _autograd_backward(ctx, d_out, d_lse):+ del d_lse # the log-sum-exp is an internal output of the forward+ q, k, v, pos_query, pos_emb, seq_starts, seq_lens, lse, dropout_seed = ctx.saved_tensors+ dq, dk, dv, d_pos_query, d_pos_emb = torch.ops.nemo_asr.packed_rel_pos_attention_bwd(+ q,+ k,+ v,+ pos_query,+ pos_emb,+ seq_starts,+ seq_lens,+ ctx.max_seqlen,+ lse,+ d_out,+ ctx.dropout_p,+ dropout_seed,+ ctx.scale,+ )+ return dq, dk, dv, d_pos_query, d_pos_emb, None, None, None, None, None, None+++torch.library.register_autograd(+ "nemo_asr::packed_rel_pos_attention_fwd", _autograd_backward, setup_context=_setup_context+)+++def _padded_rows(pos_emb: Tensor) -> Tensor:+ """``(R, H, D)`` to ``(R rounded up to a multiple of eight, H, D)`` with zero rows appended."""+ width = pos_emb.shape[0]+ padded = pos_emb.new_zeros((-(-width // 8) * 8,) + tuple(pos_emb.shape[1:]))+ padded[:width] = pos_emb+ return padded+++def _position_term(pos_query: Tensor, pos_emb: Tensor, scale: float) -> Tensor:+ """The scaled position term as an ``(H, T_total, R)`` buffer from ``(T_total, H, D)`` and ``(R, H, D)`` factors."""+ total, heads, _ = pos_query.shape+ buffer = torch.empty((heads, total, pos_emb.shape[0]), dtype=pos_query.dtype, device=pos_query.device)+ # beta 0: the uninitialized buffer is not read+ torch.baddbmm(buffer, pos_query.transpose(0, 1), pos_emb.permute(1, 2, 0), beta=0.0, alpha=scale, out=buffer)+ return buffer+++def _term_view(buffer: Tensor) -> Tensor:+ """The ``(T_total, H, R)`` view the kernels index, of an ``(H, T_total, R)`` buffer."""+ return buffer.permute(1, 0, 2)+++def _utterance_rows(seq_starts: Tensor, seq_lens: Tensor, total: int) -> Tensor:+ """Boolean mask of the rows inside an utterance, from the starts and lengths on the device (no host read)."""+ marks = torch.zeros(total + 1, dtype=torch.int32, device=seq_starts.device)+ marks.scatter_add_(0, seq_starts.long(), torch.ones_like(seq_starts))+ marks.scatter_add_(0, (seq_starts + seq_lens).long(), -torch.ones_like(seq_starts))+ return torch.cumsum(marks[:-1], 0) > 0+++def _check_lengths(seq_lens: Tensor, max_seqlen: int) -> None:+ """Reject a length beyond ``max_seqlen`` with one device read; refuse the call where no read is possible."""+ if seq_lens.numel() == 0:+ return+ if torch.compiler.is_compiling():+ raise RuntimeError(_NO_DEVICE_READ.format(where="in compiled code"))+ with torch.cuda.device(seq_lens.device):+ if torch.cuda.is_current_stream_capturing():+ raise RuntimeError(_NO_DEVICE_READ.format(where="during CUDA-graph capture"))+ longest = int(seq_lens.max())+ if longest > max_seqlen:+ raise ValueError(+ f"max_seqlen {max_seqlen} is below the longest utterance of {longest} rows: "+ "its rows past the launched tiles would stay zero and its position lookups would pass the table."+ )+++_NO_DEVICE_READ = (+ "packed_rel_pos_attention(check_lengths=True) reads the lengths from the device, which is impossible {where}: "+ "validate the lengths against max_seqlen outside the compiled or captured region and pass check_lengths=False."+)+++def _zeros_with_gradient_edges(q: Tensor, *inputs: Tensor) -> Tensor:+ """Zeros of the shape and dtype of ``q`` with a zero gradient edge to ``q`` and every input.++ ``torch.where`` with a false condition selects nothing from a tensor and sends it a zero gradient,+ so a non-finite payload (in a gap row, say) reaches neither the output nor a gradient,+ which ``0.0 * tensor`` would not guarantee.+ """+ nothing = torch.zeros((), dtype=torch.bool, device=q.device)+ out = q.new_zeros(tuple(q.shape))+ for tensor in (q, *inputs):+ out = torch.where(nothing, tensor.sum(), out)+ return out+++def _forward(+ q: Tensor,+ k: Tensor,+ v: Tensor,+ position_term: Tensor,+ seq_starts: Tensor,+ seq_lens: Tensor,+ max_seqlen: int,+ dropout_p: float,+ dropout_seed: Tensor,+ scale: float,+) -> tuple[Tensor, Tensor]:+ total, heads, head_dim = q.shape+ # zeros, not empty: the kernels write the rows of the utterances only+ out = torch.zeros_like(q)+ lse = torch.empty((total, heads), dtype=torch.float32, device=q.device)+ n_batch = seq_starts.numel()+ if n_batch and max_seqlen:+ head_dim_block = _head_dim_block(head_dim)+ _launch(+ _forward_kernel,+ FORWARD_TILES,+ q.device,+ ("forward", q.device.index, q.dtype, head_dim_block),+ lambda block_m, block_n: (n_batch * heads, triton.cdiv(max_seqlen, block_m)),+ (+ q,+ k,+ v,+ position_term,+ out,+ lse,+ seq_starts,+ seq_lens,+ dropout_seed,+ dropout_p,+ scale,+ q.stride(0),+ q.stride(1),+ position_term.stride(0),+ position_term.stride(1),+ 2 * max_seqlen - 1,+ max_seqlen - 1,+ max_seqlen,+ ),+ dict(H=heads, D=head_dim, D_PAD=head_dim_block, DROPOUT=dropout_p > 0.0, FP32=q.dtype == torch.float32),+ )+ return out, lse+++def _backward(+ q: Tensor,+ k: Tensor,+ v: Tensor,+ position_term: Tensor,+ seq_starts: Tensor,+ seq_lens: Tensor,+ max_seqlen: int,+ lse: Tensor,+ d_out: Tensor,+ dropout_p: float,+ dropout_seed: Tensor,+ scale: float,+ d_position_term: Tensor,+) -> tuple[Tensor, Tensor, Tensor]:+ total, heads, head_dim = q.shape+ delta = torch.zeros((total, heads), dtype=torch.float32, device=q.device)+ dq = torch.zeros_like(q, dtype=torch.float32)+ dk = torch.zeros_like(k, dtype=torch.float32)+ dv = torch.zeros_like(v, dtype=torch.float32)+ n_batch = seq_starts.numel()+ if n_batch and max_seqlen:+ head_dim_block = _head_dim_block(head_dim)+ ladder = BACKWARD_TILES if head_dim_block <= 64 else BACKWARD_TILES_WIDE+ common = dict(+ H=heads, D=head_dim, D_PAD=head_dim_block, DROPOUT=dropout_p > 0.0, FP32=q.dtype == torch.float32+ )+ strides = (q.stride(0), q.stride(1), position_term.stride(0), position_term.stride(1))+ inputs = (q, k, v, position_term, d_out, lse)+ widths = (2 * max_seqlen - 1, max_seqlen - 1, max_seqlen)++ def key(name):+ return (name, q.device.index, q.dtype, head_dim_block)++ def rows(block_m, block_n):+ return n_batch * heads, triton.cdiv(max_seqlen, block_m)++ def columns(block_m, block_n):+ return n_batch * heads, triton.cdiv(max_seqlen, block_n)++ bounds = (seq_starts, seq_lens, dropout_seed, dropout_p, scale, *strides)+ _launch(_delta_kernel, ladder, q.device, key("delta"), rows, (*inputs, delta, *bounds, *widths), common)+ _launch(_dkv_kernel, ladder, q.device, key("dkv"), columns, (*inputs, delta, dk, dv, *bounds, *widths), common)+ _launch(+ _dq_kernel,+ ladder,+ q.device,+ key("dq"),+ rows,+ (+ *inputs,+ delta,+ dq,+ d_position_term,+ *bounds,+ d_position_term.stride(0),+ d_position_term.stride(1),+ *widths,+ ),+ common,+ )+ return dq, dk, dv+++def _head_dim_block(head_dim: int) -> int:+ return max(16, triton.next_power_of_2(head_dim))+++# the ladder entry in use per (kernel, device, dtype, head width)+_tiles_in_use: dict[tuple[str, int, torch.dtype, int], int] = {}+++def _launch(+ kernel: triton.JITFunction,+ ladder: tuple[tuple[int, int, int, int], ...],+ device: torch.device,+ key: tuple[str, int, torch.dtype, int],+ grid: Callable[[int, int], tuple[int, int]],+ args: tuple,+ constexprs: dict[str, object],+) -> None:+ """Launch ``kernel`` on ``device`` with the first entry of ``ladder`` that its shared memory takes.++ Triton launches in the current CUDA context, not on the tensors' device, so the device is pinned for the launch.+ Triton refuses a configuration beyond the device's shared memory at its first launch (``OutOfResources``);+ the next entry is tried, and the one that runs is remembered under ``key``.+ ``grid`` maps the tile sizes (BLOCK_M, BLOCK_N) to the launch grid.+ """+ error = None+ for index in range(_tiles_in_use.get(key, 0), len(ladder)):+ block_m, block_n, num_warps, num_stages = ladder[index]+ try:+ with torch.cuda.device(device):+ kernel[grid(block_m, block_n)](+ *args, BLOCK_M=block_m, BLOCK_N=block_n, num_warps=num_warps, num_stages=num_stages, **constexprs+ )+ except OutOfResources as exc:+ error = exc+ continue+ _tiles_in_use[key] = index+ return+ raise error+++@triton.jit+def _load_rows(ptr, rows, h, stride_t, stride_h, offs_d, row_mask, D: tl.constexpr, D_PAD: tl.constexpr):+ """A ``(rows, D_PAD)`` tile of a ``(T_total, H, D)`` tensor at head ``h``, zero outside the rows and past ``D``."""+ ptrs = ptr + rows[:, None] * stride_t + h * stride_h + offs_d[None, :]+ if D_PAD == D:+ mask = row_mask[:, None]+ else:+ mask = row_mask[:, None] & (offs_d < D)[None, :]+ return tl.load(ptrs, mask=mask, other=0.0)+++@triton.jit+def _store_rows(ptr, rows, h, stride_t, stride_h, offs_d, row_mask, tile, D: tl.constexpr, D_PAD: tl.constexpr):+ ptrs = ptr + rows[:, None] * stride_t + h * stride_h + offs_d[None, :]+ if D_PAD == D:+ mask = row_mask[:, None]+ else:+ mask = row_mask[:, None] & (offs_d < D)[None, :]+ tl.store(ptrs, tile, mask=mask)+++@triton.jit+def _dot(a, b, FP32: tl.constexpr):+ # float32 dots as three TF32 products: the accuracy of float32 on the tensor cores,+ # where plain float32 dots run on the FMA units at several times the time+ if FP32:+ product = tl.dot(a, b, input_precision="tf32x3")+ else:+ product = tl.dot(a, b)+ return product+++@triton.jit+def _term_offsets(q_rows, h, rel, stride_bt, stride_bh):+ """64-bit offsets into the position term, whose extent passes 2**31 at large packed batches."""+ return q_rows[:, None].to(tl.int64) * stride_bt + h.to(tl.int64) * stride_bh + rel+++@triton.jit+def _keep(dropout_seed, h, q_rows, offs_n, drop_stride, dropout_p):+ """Which (global query row, local key column) pairs keep their weight: a Philox hash with the head in the seed."""+ offsets = q_rows[:, None].to(tl.int64) * drop_stride + offs_n[None, :]+ return tl.rand(tl.load(dropout_seed) + h * DROPOUT_HEAD_SEED_STRIDE, offsets) >= dropout_p+++@triton.jit+def _forward_kernel(+ Q,+ K,+ V,+ BD,+ Out,+ Lse,+ SeqStarts,+ SeqLens,+ Seed,+ dropout_p,+ scale,+ stride_qt,+ stride_qh,+ stride_bt,+ stride_bh,+ R,+ center,+ drop_stride,+ H: tl.constexpr,+ D: tl.constexpr,+ D_PAD: tl.constexpr,+ BLOCK_M: tl.constexpr,+ BLOCK_N: tl.constexpr,+ DROPOUT: tl.constexpr,+ FP32: tl.constexpr,+):+ pid_bh = tl.program_id(0)+ pid_m = tl.program_id(1)+ b = pid_bh // H+ h = pid_bh % H+ seq_start = tl.load(SeqStarts + b)+ seq_len = tl.load(SeqLens + b)+ if pid_m * BLOCK_M >= seq_len:+ return+ offs_m = pid_m * BLOCK_M + tl.arange(0, BLOCK_M)+ offs_d = tl.arange(0, D_PAD)+ q_rows = seq_start + offs_m+ q_mask = offs_m < seq_len+ q = _load_rows(Q, q_rows, h, stride_qt, stride_qh, offs_d, q_mask, D, D_PAD)+ m_i = tl.full([BLOCK_M], float("-inf"), dtype=tl.float32)+ l_i = tl.zeros([BLOCK_M], dtype=tl.float32)+ acc = tl.zeros([BLOCK_M, D_PAD], dtype=tl.float32)+ for start_n in range(0, seq_len, BLOCK_N):+ offs_n = start_n + tl.arange(0, BLOCK_N)+ n_mask = offs_n < seq_len+ k_rows = seq_start + offs_n+ k = _load_rows(K, k_rows, h, stride_qt, stride_qh, offs_d, n_mask, D, D_PAD)+ s = _dot(q, tl.trans(k), FP32) * scale+ rel = center + offs_n[None, :] - offs_m[:, None]+ valid = q_mask[:, None] & n_mask[None, :] & (rel >= 0) & (rel < R)+ bd = tl.load(BD + _term_offsets(q_rows, h, rel, stride_bt, stride_bh), mask=valid, other=0.0)+ s = tl.where(valid, s + bd, float("-inf"))+ m_new = tl.maximum(m_i, tl.max(s, 1))+ # a row without a valid score yet has m_new = -inf; exp(-inf - -inf) would be NaN+ m_safe = tl.where(m_new == float("-inf"), 0.0, m_new)+ p = tl.exp(s - m_safe[:, None])+ alpha = tl.exp(m_i - m_safe)+ l_i = l_i * alpha + tl.sum(p, 1)+ acc = acc * alpha[:, None]+ if DROPOUT:+ keep = _keep(Seed, h, q_rows, offs_n, drop_stride, dropout_p)+ p_use = tl.where(keep, p / (1.0 - dropout_p), 0.0)+ else:+ p_use = p+ v_tile = _load_rows(V, k_rows, h, stride_qt, stride_qh, offs_d, n_mask, D, D_PAD)+ acc += _dot(p_use.to(v_tile.dtype), v_tile, FP32)+ m_i = m_new+ out = acc / l_i[:, None]+ _store_rows(Out, q_rows, h, stride_qt, stride_qh, offs_d, q_mask, out, D, D_PAD)+ tl.store(Lse + q_rows * H + h, m_i + tl.log(l_i), mask=q_mask)+++@triton.jit+def _delta_kernel(+ Q,+ K,+ V,+ BD,+ DO,+ Lse,+ Delta,+ SeqStarts,+ SeqLens,+ Seed,+ dropout_p,+ scale,+ stride_qt,+ stride_qh,+ stride_bt,+ stride_bh,+ R,+ center,+ drop_stride,+ H: tl.constexpr,+ D: tl.constexpr,+ D_PAD: tl.constexpr,+ BLOCK_M: tl.constexpr,+ BLOCK_N: tl.constexpr,+ DROPOUT: tl.constexpr,+ FP32: tl.constexpr,+):+ # delta_i = sum_j p_ij dp_ij from the recomputed weights, see the module docstring+ pid_bh = tl.program_id(0)+ pid_m = tl.program_id(1)+ b = pid_bh // H+ h = pid_bh % H+ seq_start = tl.load(SeqStarts + b)+ seq_len = tl.load(SeqLens + b)+ if pid_m * BLOCK_M >= seq_len:+ return+ offs_m = pid_m * BLOCK_M + tl.arange(0, BLOCK_M)+ offs_d = tl.arange(0, D_PAD)+ m_mask = offs_m < seq_len+ q_rows = seq_start + offs_m+ q = _load_rows(Q, q_rows, h, stride_qt, stride_qh, offs_d, m_mask, D, D_PAD)+ do = _load_rows(DO, q_rows, h, stride_qt, stride_qh, offs_d, m_mask, D, D_PAD)+ lse = tl.load(Lse + q_rows * H + h, mask=m_mask, other=0.0)+ delta = tl.zeros([BLOCK_M], dtype=tl.float32)+ for start_n in range(0, seq_len, BLOCK_N):+ offs_n = start_n + tl.arange(0, BLOCK_N)+ n_mask = offs_n < seq_len+ k_rows = seq_start + offs_n+ k = _load_rows(K, k_rows, h, stride_qt, stride_qh, offs_d, n_mask, D, D_PAD)+ v = _load_rows(V, k_rows, h, stride_qt, stride_qh, offs_d, n_mask, D, D_PAD)+ s = _dot(q, tl.trans(k), FP32) * scale+ dp = _dot(do, tl.trans(v), FP32)+ rel = center + offs_n[None, :] - offs_m[:, None]+ valid = m_mask[:, None] & n_mask[None, :] & (rel >= 0) & (rel < R)+ bd = tl.load(BD + _term_offsets(q_rows, h, rel, stride_bt, stride_bh), mask=valid, other=0.0)+ s = tl.where(valid, s + bd, float("-inf"))+ p = tl.exp(s - lse[:, None])+ if DROPOUT:+ keep = _keep(Seed, h, q_rows, offs_n, drop_stride, dropout_p)+ dp = tl.where(keep, dp / (1.0 - dropout_p), 0.0)+ delta += tl.sum(tl.where(valid, p * dp, 0.0), 1)+ tl.store(Delta + q_rows * H + h, delta, mask=m_mask)+++@triton.jit+def _dkv_kernel(+ Q,+ K,+ V,+ BD,+ DO,+ Lse,+ Delta,+ DK,+ DV,+ SeqStarts,+ SeqLens,+ Seed,+ dropout_p,+ scale,+ stride_qt,+ stride_qh,+ stride_bt,+ stride_bh,+ R,+ center,+ drop_stride,+ H: tl.constexpr,+ D: tl.constexpr,+ D_PAD: tl.constexpr,+ BLOCK_M: tl.constexpr,+ BLOCK_N: tl.constexpr,+ DROPOUT: tl.constexpr,+ FP32: tl.constexpr,+):+ pid_bh = tl.program_id(0)+ pid_n = tl.program_id(1)+ b = pid_bh // H+ h = pid_bh % H+ seq_start = tl.load(SeqStarts + b)+ seq_len = tl.load(SeqLens + b)+ if pid_n * BLOCK_N >= seq_len:+ return+ offs_n = pid_n * BLOCK_N + tl.arange(0, BLOCK_N)+ offs_d = tl.arange(0, D_PAD)+ n_mask = offs_n < seq_len+ k_rows = seq_start + offs_n+ k = _load_rows(K, k_rows, h, stride_qt, stride_qh, offs_d, n_mask, D, D_PAD)+ v = _load_rows(V, k_rows, h, stride_qt, stride_qh, offs_d, n_mask, D, D_PAD)+ dk = tl.zeros([BLOCK_N, D_PAD], dtype=tl.float32)+ dv = tl.zeros([BLOCK_N, D_PAD], dtype=tl.float32)+ for start_m in range(0, seq_len, BLOCK_M):+ offs_m = start_m + tl.arange(0, BLOCK_M)+ m_mask = offs_m < seq_len+ q_rows = seq_start + offs_m+ q = _load_rows(Q, q_rows, h, stride_qt, stride_qh, offs_d, m_mask, D, D_PAD)+ do = _load_rows(DO, q_rows, h, stride_qt, stride_qh, offs_d, m_mask, D, D_PAD)+ lse = tl.load(Lse + q_rows * H + h, mask=m_mask, other=0.0)+ delta = tl.load(Delta + q_rows * H + h, mask=m_mask, other=0.0)+ s = _dot(q, tl.trans(k), FP32) * scale+ rel = center + offs_n[None, :] - offs_m[:, None]+ valid = m_mask[:, None] & n_mask[None, :] & (rel >= 0) & (rel < R)+ bd = tl.load(BD + _term_offsets(q_rows, h, rel, stride_bt, stride_bh), mask=valid, other=0.0)+ s = tl.where(valid, s + bd, float("-inf"))+ p = tl.exp(s - lse[:, None])+ if DROPOUT:+ keep = _keep(Seed, h, q_rows, offs_n, drop_stride, dropout_p)+ p_use = tl.where(keep, p / (1.0 - dropout_p), 0.0)+ else:+ p_use = p+ dv += _dot(tl.trans(p_use.to(do.dtype)), do, FP32)+ dp = _dot(do, tl.trans(v), FP32)+ if DROPOUT:+ dp = tl.where(keep, dp / (1.0 - dropout_p), 0.0)+ # the scale is folded into ds before the dot, as in the flash-attention backward;+ # the scaled dot (dot(trans(ds), q) * scale) miscompiles on Blackwell in bf16 and fp16 (triton-lang/triton#12757)+ ds = tl.where(valid, p * (dp - delta[:, None]) * scale, 0.0)+ dk += _dot(tl.trans(ds.to(q.dtype)), q, FP32)+ _store_rows(DK, k_rows, h, stride_qt, stride_qh, offs_d, n_mask, dk, D, D_PAD)+ _store_rows(DV, k_rows, h, stride_qt, stride_qh, offs_d, n_mask, dv, D, D_PAD)+++@triton.jit+def _dq_kernel(+ Q,+ K,+ V,+ BD,+ DO,+ Lse,+ Delta,+ DQ,+ DBD,+ SeqStarts,+ SeqLens,+ Seed,+ dropout_p,+ scale,+ stride_qt,+ stride_qh,+ stride_bt,+ stride_bh,+ stride_dbt,+ stride_dbh,+ R,+ center,+ drop_stride,+ H: tl.constexpr,+ D: tl.constexpr,+ D_PAD: tl.constexpr,+ BLOCK_M: tl.constexpr,+ BLOCK_N: tl.constexpr,+ DROPOUT: tl.constexpr,+ FP32: tl.constexpr,+):+ pid_bh = tl.program_id(0)+ pid_m = tl.program_id(1)+ b = pid_bh // H+ h = pid_bh % H+ seq_start = tl.load(SeqStarts + b)+ seq_len = tl.load(SeqLens + b)+ if pid_m * BLOCK_M >= seq_len:+ return+ offs_m = pid_m * BLOCK_M + tl.arange(0, BLOCK_M)+ offs_d = tl.arange(0, D_PAD)+ m_mask = offs_m < seq_len+ q_rows = seq_start + offs_m+ q = _load_rows(Q, q_rows, h, stride_qt, stride_qh, offs_d, m_mask, D, D_PAD)+ do = _load_rows(DO, q_rows, h, stride_qt, stride_qh, offs_d, m_mask, D, D_PAD)+ lse = tl.load(Lse + q_rows * H + h, mask=m_mask, other=0.0)+ delta = tl.load(Delta + q_rows * H + h, mask=m_mask, other=0.0)+ dq = tl.zeros([BLOCK_M, D_PAD], dtype=tl.float32)+ for start_n in range(0, seq_len, BLOCK_N):+ offs_n = start_n + tl.arange(0, BLOCK_N)+ n_mask = offs_n < seq_len+ k_rows = seq_start + offs_n+ k = _load_rows(K, k_rows, h, stride_qt, stride_qh, offs_d, n_mask, D, D_PAD)+ v = _load_rows(V, k_rows, h, stride_qt, stride_qh, offs_d, n_mask, D, D_PAD)+ s = _dot(q, tl.trans(k), FP32) * scale+ rel = center + offs_n[None, :] - offs_m[:, None]+ valid = m_mask[:, None] & n_mask[None, :] & (rel >= 0) & (rel < R)+ bd = tl.load(BD + _term_offsets(q_rows, h, rel, stride_bt, stride_bh), mask=valid, other=0.0)+ s = tl.where(valid, s + bd, float("-inf"))+ p = tl.exp(s - lse[:, None])+ dp = _dot(do, tl.trans(v), FP32)+ if DROPOUT:+ keep = _keep(Seed, h, q_rows, offs_n, drop_stride, dropout_p)+ dp = tl.where(keep, dp / (1.0 - dropout_p), 0.0)+ ds = tl.where(valid, p * (dp - delta[:, None]), 0.0)+ dq += _dot((ds * scale).to(k.dtype), k, FP32)+ # the position-term gradient is ds itself, row-owned: every (i, j) of a row has its own entry+ tl.store(DBD + _term_offsets(q_rows, h, rel, stride_dbt, stride_dbh), ds, mask=valid)+ _store_rows(DQ, q_rows, h, stride_qt, stride_qh, offs_d, m_mask, dq, D, D_PAD)tests/collections/asr/test_conformer_encoder.py105 + / 4 −
@@ -14,6 +14,7 @@ # limitations under the License. import copy import functools+import inspect import os import numpy as np@@ -42,6 +43,7 @@ ) from nemo.collections.asr.parts.submodules.subsampling import ConvSubsampling from nemo.collections.asr.parts.utils.streaming_utils import CacheAwareStreamingAudioBuffer+from nemo.core.utils.optional_libs import TRITON_AVAILABLE class TestStochasticDepth:@@ -900,6 +902,22 @@ def test_state_dict_unchanged(self): assert sorted(encoder.state_dict()) == sorted(keys) assert "layers.0.self_attn.linear_pos.weight" in _packed_encoder().state_dict() + @pytest.mark.unit+ def test_block_arguments_keep_their_positions(self):+ """``packed_rel_pos_attention`` is keyword-only, after the block arguments: a positional ``None`` after+ ``use_triton`` still binds to ``pre_encode``, as it did before the option existed."""+ parameters = list(inspect.signature(ConformerEncoder.__init__).parameters.values())[1:]+ names = [parameter.name for parameter in parameters]+ assert names.index("pre_encode") == names.index("use_triton") + 1+ option = inspect.signature(ConformerEncoder.__init__).parameters["packed_rel_pos_attention"]+ assert option.kind is inspect.Parameter.KEYWORD_ONLY and option.default == "triton"+ sizes = {"feat_in": 8, "n_layers": 1, "d_model": 16}+ positional = [+ sizes.get(parameter.name, parameter.default) for parameter in parameters[: names.index("pre_encode")]+ ]+ encoder = ConformerEncoder(*positional, None)+ assert isinstance(encoder.pre_encode, ConvSubsampling) and encoder.packed_rel_pos_attention == "triton"+ @pytest.mark.gpu @pytest.mark.skipif(not torch.cuda.is_available(), reason="requires CUDA")@@ -930,7 +948,7 @@ def _half_precision_flash_attention_available(): @pytest.mark.unit @pytest.mark.parametrize("self_attention_model", ["rel_pos", "abs_pos", "rope"]) def test_bf16_autocast_matches_padded_outputs_and_gradients(self, self_attention_model):- """rel_pos runs FlexAttention with the position bias; abs_pos and rope run variable-length FlashAttention."""+ """rel_pos runs the Triton kernel with the position term; abs_pos and rope run variable-length FlashAttention.""" if self_attention_model != "rel_pos" and not self._half_precision_flash_attention_available(): pytest.skip("requires a variable-length FlashAttention provider") torch.manual_seed(9)@@ -969,6 +987,86 @@ def test_attention_dropout_runs_through_flash_attention_in_bf16(self, self_atten assert encoder.layers[0].self_attn.linear_q.weight.grad is not None @pytest.mark.unit+ @pytest.mark.skipif(not TRITON_AVAILABLE, reason="requires Triton")+ def test_rel_pos_attention_dropout_runs_through_the_kernel(self, monkeypatch):+ """Attention dropout with rel_pos trains packed, in float32 and under bf16 autocast, without FlexAttention."""++ def no_flex_attention(*args, **kwargs):+ raise AssertionError("FlexAttention must not run")++ monkeypatch.setattr(packed_attention_module, "_flex_packed_attention", no_flex_attention)+ torch.manual_seed(11)+ encoder = _packed_encoder(self_attention_model="rel_pos", dropout_att=0.1, d_model=32, n_heads=2)+ encoder = encoder.cuda().train()+ lengths = torch.tensor([300, 7, 150], device="cuda")+ features = _packed_test_features(lengths, dtype=torch.float32, device="cuda")+ for autocast in (False, True):+ with torch.autocast("cuda", dtype=torch.bfloat16, enabled=autocast):+ packed = encoder.forward_sequence_packed(features, lengths)+ again = encoder.forward_sequence_packed(features, lengths)+ assert packed.data.shape == (int(packed.lengths.sum()), 32) and torch.isfinite(packed.data).all()+ # the dropout draws a fresh mask per call+ assert not torch.equal(packed.data, again.data)+ encoder.zero_grad()+ packed.data.float().square().mean().backward()+ assert encoder.layers[0].self_attn.linear_pos.weight.grad is not None+ assert encoder.layers[0].self_attn.pos_bias_v.grad.abs().sum() > 0++ @pytest.mark.unit+ @pytest.mark.skipif(not TRITON_AVAILABLE, reason="requires Triton")+ def test_flex_attention_stays_selectable_for_rel_pos(self, monkeypatch):+ """``packed_rel_pos_attention: flex`` keeps the backend before the kernel: FlexAttention over the rounded+ table, which has no dropout, so attention dropout in training mode is refused as before."""+ with pytest.raises(ValueError, match="packed_rel_pos_attention"):+ _packed_encoder(packed_rel_pos_attention="cuda")+ torch.manual_seed(8)+ encoder = _packed_encoder(self_attention_model="rel_pos", dropout_att=0.1, packed_rel_pos_attention="flex")+ encoder = encoder.cuda().train()+ reason = encoder.sequence_packed_unsupported_reason()+ assert reason is not None and "FlexAttention" in reason+ encoder.eval()+ assert encoder.sequence_packed_unsupported_reason() is None++ def no_kernel(*args, **kwargs):+ raise AssertionError("the Triton kernel must not run")++ monkeypatch.setattr(packed_attention_module, "packed_rel_pos_attention", no_kernel)+ lengths = torch.tensor([300, 7, 150], device="cuda")+ features = _packed_test_features(lengths, dtype=torch.float32, device="cuda")+ padded_out, padded_lengths = encoder(audio_signal=features, length=lengths)+ packed = encoder.forward_sequence_packed(features, lengths)+ torch.testing.assert_close(packed.data, _valid_frames(padded_out, padded_lengths), atol=1e-4, rtol=1e-4)++ @pytest.mark.unit+ @pytest.mark.parametrize("backend", ["flex", "triton"])+ def test_float64_attention_dropout_runs_the_reference_on_either_backend(self, monkeypatch, backend):+ """In float64 ``packed_attention`` runs the dense reference attention, with dropout, whichever backend the+ encoder selects, and the capability check at the encoder entry point follows that dispatch rule."""++ def no_flex_attention(*args, **kwargs):+ raise AssertionError("FlexAttention must not run")++ def no_kernel(*args, **kwargs):+ raise AssertionError("the Triton kernel must not run")++ monkeypatch.setattr(packed_attention_module, "_flex_packed_attention", no_flex_attention)+ monkeypatch.setattr(packed_attention_module, "packed_rel_pos_attention", no_kernel, raising=False)+ torch.manual_seed(5)+ encoder = _packed_encoder(+ self_attention_model="rel_pos", dropout_att=0.1, d_model=32, n_heads=2, packed_rel_pos_attention=backend+ )+ encoder = encoder.cuda().double().train()+ assert encoder.sequence_packed_unsupported_reason() is None+ lengths = torch.tensor([40, 7, 25], device="cuda")+ features = _packed_test_features(lengths, dtype=torch.float64, device="cuda")+ packed = encoder.forward_sequence_packed(features, lengths)+ again = encoder.forward_sequence_packed(features, lengths)+ assert packed.data.dtype == torch.float64 and torch.isfinite(packed.data).all()+ # the dropout draws a fresh mask per call+ assert not torch.equal(packed.data, again.data)+ packed.data.square().mean().backward()+ assert encoder.layers[0].self_attn.linear_pos.weight.grad is not None+ @pytest.mark.parametrize("self_attention_model", ["abs_pos", "rope"]) def test_flash_and_flex_backends_match_padded_in_bf16(self, self_attention_model): """The same weights and inputs through both CUDA attention backends, each against the padded forward.@@ -1018,12 +1116,15 @@ def run(backend): assert (grad - flex[3][name]).norm() <= 0.05 * flex[3][name].norm() + 1e-5, name @pytest.mark.unit- def test_attention_dropout_without_flash_attention_is_rejected(self):- """FlexAttention has no dropout: rel_pos attention, and abs_pos attention in float32, refuse dropout_att.+ def test_attention_dropout_without_flash_attention_is_rejected(self, monkeypatch):+ """FlexAttention has no dropout: rel_pos attention without its Triton kernel, and abs_pos attention+ in float32, refuse dropout_att. The refusal comes from the support check that ``supports_sequence_packed_output`` shares,- so packed perception modules keep their padded path for these configurations instead.+ so packed perception modules keep their padded path for these configurations instead;+ the kernel is switched off here, since with it rel_pos attention keeps its dropout. """+ monkeypatch.setattr(packed_attention_module, "TRITON_AVAILABLE", False) lengths = torch.tensor([30, 7], device="cuda") features = _packed_test_features(lengths, dtype=torch.float32, device="cuda") for self_attention_model in ("rel_pos", "abs_pos"):tests/collections/asr/test_packed_attention.py799 + / 49 −
@@ -13,7 +13,7 @@ # See the License for the specific language governing permissions and # limitations under the License. -"""Attention over packed sequences: the document block mask and the Transformer-XL attention against padded."""+"""Attention over packed sequences: the document block mask, the Triton kernel and the Transformer-XL attention.""" import pytest import torch@@ -32,6 +32,47 @@ packed_attention, packed_cross_attention, )+from nemo.core.utils.optional_libs import TRITON_AVAILABLE++if TRITON_AVAILABLE:+ import triton+ import triton.language as tl++ from nemo.collections.asr.parts.triton import rel_pos_attention as kernel_module+ from nemo.collections.asr.parts.triton.rel_pos_attention import _keep as _kernel_keep++ @triton.jit+ def _keep_mask_kernel(+ Mask, Seed, dropout_p, total, max_seqlen, stride_mt, stride_mh, BLOCK_M: tl.constexpr, BLOCK_N: tl.constexpr+ ):+ rows = tl.program_id(0) * BLOCK_M + tl.arange(0, BLOCK_M)+ h = tl.program_id(1)+ offs_n = tl.arange(0, BLOCK_N)+ keep = _kernel_keep(Seed, h, rows, offs_n, max_seqlen, dropout_p)+ ptrs = Mask + rows[:, None] * stride_mt + h * stride_mh + offs_n[None, :]+ tl.store(ptrs, keep.to(tl.int8), mask=(rows < total)[:, None] & (offs_n < max_seqlen)[None, :])+++requires_kernel = pytest.mark.skipif(+ not (torch.cuda.is_available() and TRITON_AVAILABLE), reason="requires CUDA and Triton"+)+++def _keep_mask(total, heads, max_seqlen, *, dropout_p, dropout_seed):+ """The (T_total, H, max_seqlen) mask of attention weights the kernels keep under dropout, from the kernels' hash."""+ mask = torch.zeros((total, heads, max_seqlen), dtype=torch.int8, device="cuda")+ _keep_mask_kernel[(triton.cdiv(total, 32), heads)](+ mask,+ dropout_seed,+ dropout_p,+ total,+ max_seqlen,+ mask.stride(0),+ mask.stride(1),+ BLOCK_M=32,+ BLOCK_N=triton.next_power_of_2(max_seqlen),+ )+ return mask.bool() def _valid_frames(padded, lengths):@@ -52,6 +93,22 @@ def reset_dynamo_after_each_test(): torch._dynamo.reset() +@pytest.fixture+def flex_attention_only(monkeypatch):+ """Route rel_pos attention to FlexAttention, the path without the Triton kernel."""+ monkeypatch.setattr(packed_attention_module, "TRITON_AVAILABLE", False)+++def _rel_pos_inputs(context, heads, head_dim, device="cuda", dtype=torch.float32, pos_scale=1.0):+ """Random q, k, v, pos_query and pos_emb for the context, as leaves."""+ total, max_len = context.total_tokens, context.rel_pos_max_seqlen+ q, k, v, pos_query = (+ torch.randn(total, heads, head_dim, device=device, dtype=dtype, requires_grad=True) for _ in range(4)+ )+ pos_emb = (torch.randn(2 * max_len - 1, heads, head_dim, device=device, dtype=dtype) * pos_scale).requires_grad_()+ return q, k, v, pos_query, pos_emb++ class TestDocumentBlockMask: @pytest.mark.unit @pytest.mark.parametrize("lengths", [[5, 3, 7], [300, 1, 129, 128, 40], [257]])@@ -101,10 +158,12 @@ def test_context_from_lengths(self): assert context.cu_seqlens.tolist() == [0, 3, 3, 5] assert context.position_ids.tolist() == [0, 1, 2, 0, 1] assert context.sequence_slices == ((0, 3), (3, 3), (3, 5))+ assert context.seq_starts.tolist() == [0, 3, 3] and context.seq_lens.tolist() == [3, 0, 2]+ assert context.seq_starts.dtype == torch.int32 and context.seq_lens.dtype == torch.int32 class TestPackedAttentionKernelShapes:- """The shapes the compiled kernels see: powers of two from the padding floors, few per run."""+ """The shapes the compiled FlexAttention kernels see: powers of two from the padding floors, few per run.""" @pytest.mark.unit def test_padded_sizes_are_powers_of_two_from_the_floors(self):@@ -115,6 +174,24 @@ def test_padded_sizes_are_powers_of_two_from_the_floors(self): context = PackedAttentionContext.from_lengths(torch.tensor([300, 7])) assert context.bias_rows().tolist() == list(range(307)) + [306] * (4096 - 307) + @pytest.mark.unit+ @pytest.mark.gpu+ def test_rel_pos_table_length_follows_the_backend(self, monkeypatch):+ """FlexAttention needs the rounded length, the Triton kernel the longest utterance; the CPU runs neither."""+ context = PackedAttentionContext.from_lengths(torch.tensor([300, 7]))+ assert not context.rel_pos_kernel and context.rel_pos_max_seqlen == 512+ if torch.cuda.is_available():+ context = PackedAttentionContext.from_lengths(torch.tensor([300, 7], device="cuda"))+ assert context.rel_pos_kernel == TRITON_AVAILABLE+ assert context.rel_pos_max_seqlen == (300 if TRITON_AVAILABLE else 512)+ monkeypatch.setattr(packed_attention_module, "TRITON_AVAILABLE", False)+ context = PackedAttentionContext.from_lengths(torch.tensor([300, 7], device="cuda"))+ assert not context.rel_pos_kernel and context.rel_pos_max_seqlen == 512+ # an empty batch keeps a one-row table for the kernel+ monkeypatch.setattr(packed_attention_module, "TRITON_AVAILABLE", True)+ context = PackedAttentionContext.from_lengths(torch.tensor([0, 0], device="cuda"))+ assert context.rel_pos_kernel and context.rel_pos_max_seqlen == 1+ @pytest.mark.unit def test_kernel_shapes_of_a_run_stay_below_the_recompile_limit(self): """Batches of any size up to 150,000 tokens with utterances up to 100,000 frames share few shapes."""@@ -125,71 +202,57 @@ def test_kernel_shapes_of_a_run_stay_below_the_recompile_limit(self): shapes.add((context.padded_total_tokens, context.padded_max_seqlen)) assert len(shapes) < packed_attention_module.RECOMPILE_LIMIT // 2 + @staticmethod+ def _attend_with_flex(lengths):+ context = PackedAttentionContext.from_lengths(torch.tensor(lengths, device="cuda"))+ assert not context.rel_pos_kernel+ q, k, v, pos_query, pos_emb = _rel_pos_inputs(context, heads=2, head_dim=16)+ return packed_attention(q, k, v, context, pos_query=pos_query, pos_emb=pos_emb)+ # Dynamo settings are changed through the config module's own `patch`, not through monkeypatch: # pytest's undo deletes the entry from torch's config module (torch 2.12 and 2.14), # and every later lookup of `recompile_limit` in the process fails. @pytest.mark.unit @pytest.mark.gpu @pytest.mark.skipif(not torch.cuda.is_available(), reason="requires CUDA FlexAttention")- def test_recompile_limit_miss_raises_instead_of_running_eagerly(self, monkeypatch):+ def test_recompile_limit_miss_raises_instead_of_running_eagerly(self, monkeypatch, flex_attention_only): """Past its recompile limit Dynamo would run flex_attention eagerly over dense scores; the miss must fail.""" monkeypatch.setattr(packed_attention_module, "RECOMPILE_LIMIT", 1) limit_name = "recompile_limit" if hasattr(torch._dynamo.config, "recompile_limit") else "cache_size_limit" torch._dynamo.reset()-- def attend(lengths):- context = PackedAttentionContext.from_lengths(torch.tensor(lengths, device="cuda"))- q, k, v = (torch.randn(context.total_tokens, 2, 16, device="cuda") for _ in range(3))- bias = torch.randn(context.total_tokens, 2, 2 * context.padded_max_seqlen - 1, device="cuda")- return packed_attention(q, k, v, context, rel_pos_bias=bias)- with torch._dynamo.config.patch(**{limit_name: 1}):- attend([40, 30])+ self._attend_with_flex([40, 30]) with pytest.raises(torch._dynamo.exc.FailOnRecompileLimitHit):- attend([5000, 30])+ self._attend_with_flex([5000, 30]) @pytest.mark.unit @pytest.mark.gpu @pytest.mark.skipif(not torch.cuda.is_available(), reason="requires CUDA FlexAttention")- def test_token_total_does_not_recompile(self):+ def test_token_total_does_not_recompile(self, flex_attention_only): """Batches with equal padded shapes but different token totals share one kernel. The relative-position bias enters the kernel with its unpadded token axis; without the dynamic mark on that axis the static compile specializes on every distinct total. """ torch._dynamo.reset()-- def attend(lengths):- context = PackedAttentionContext.from_lengths(torch.tensor(lengths, device="cuda"))- q, k, v = (torch.randn(context.total_tokens, 2, 16, device="cuda") for _ in range(3))- bias = torch.randn(context.total_tokens, 2, 2 * context.padded_max_seqlen - 1, device="cuda")- return packed_attention(q, k, v, context, rel_pos_bias=bias)-- attend([40, 30])+ self._attend_with_flex([40, 30]) with torch._dynamo.config.patch(error_on_recompile=True):- attend([40, 35])- attend([45, 35, 20])+ self._attend_with_flex([40, 35])+ self._attend_with_flex([45, 35, 20]) @pytest.mark.unit @pytest.mark.gpu @pytest.mark.skipif(not torch.cuda.is_available(), reason="requires CUDA FlexAttention")- def test_kernels_have_a_dynamo_cache_of_their_own(self):+ def test_kernels_have_a_dynamo_cache_of_their_own(self, flex_attention_only): """The packed kernels leave the code object of flex_attention itself alone. The Transformer encoders compile flex_attention itself with dynamic shapes; entries of the packed kernels on that code object would count against that compile's recompile limit. """ torch._dynamo.reset()-- def attend(lengths):- context = PackedAttentionContext.from_lengths(torch.tensor(lengths, device="cuda"))- q, k, v = (torch.randn(context.total_tokens, 2, 16, device="cuda") for _ in range(3))- bias = torch.randn(context.total_tokens, 2, 2 * context.padded_max_seqlen - 1, device="cuda")- return packed_attention(q, k, v, context, rel_pos_bias=bias)-- attend([40, 30])- attend([5000, 30]) # a second kernel shape, a second cache entry+ self._attend_with_flex([40, 30])+ self._attend_with_flex([5000, 30]) # a second kernel shape, a second cache entry limit_name = "recompile_limit" if hasattr(torch._dynamo.config, "recompile_limit") else "cache_size_limit" # with a shared cache the two entries above would already be over the limit of this compile with torch._dynamo.config.patch(**{limit_name: 1, "fail_on_recompile_limit_hit": True}):@@ -233,11 +296,39 @@ def test_matches_padded(self): @pytest.mark.unit def test_empty_batch_keeps_gradients(self): q = torch.randn(0, 2, 4, requires_grad=True)- bias = torch.randn(0, 2, 1, requires_grad=True)+ pos_emb = torch.randn(1, 2, 4, requires_grad=True) context = PackedAttentionContext.from_lengths(torch.tensor([0, 0]))- out = packed_attention(q, q, q, context, rel_pos_bias=bias)+ out = packed_attention(q, q, q, context, pos_query=q, pos_emb=pos_emb) out.sum().backward()- assert out.shape == (0, 2, 4) and q.grad is not None and bias.grad is not None+ assert out.shape == (0, 2, 4) and q.grad is not None and pos_emb.grad is not None++ @pytest.mark.unit+ def test_position_factors_come_together(self):+ q = torch.randn(5, 2, 4)+ context = PackedAttentionContext.from_lengths(torch.tensor([5]))+ with pytest.raises(ValueError, match="both or neither"):+ packed_attention(q, q, q, context, pos_query=q)++ @pytest.mark.unit+ def test_rel_pos_bias_keyword_matches_the_factors(self):+ """The materialized position term of the earlier interface runs and trains like its factors."""+ torch.manual_seed(5)+ context = PackedAttentionContext.from_lengths(torch.tensor([7, 3, 11]))+ q, k, v, pos_query, pos_emb = _rel_pos_inputs(context, heads=2, head_dim=8, device="cpu", dtype=torch.float64)+ bias = torch.einsum("thd,rhd->thr", pos_query, pos_emb).detach().requires_grad_()+ from_factors = packed_attention(q, k, v, context, pos_query=pos_query, pos_emb=pos_emb)+ from_bias = packed_attention(q, k, v, context, rel_pos_bias=bias)+ torch.testing.assert_close(from_bias, from_factors)+ from_factors.square().sum().backward()+ from_bias.square().sum().backward()+ assert bias.grad is not None and torch.isfinite(bias.grad).all()+ # the chain rule through the factors: the gradient of pos_query is that of the bias times pos_emb+ torch.testing.assert_close(torch.einsum("thr,rhd->thd", bias.grad, pos_emb.detach()), pos_query.grad)+ with pytest.raises(ValueError, match="not both"):+ packed_attention(q, k, v, context, pos_query=pos_query, pos_emb=pos_emb, rel_pos_bias=bias)+ empty = PackedAttentionContext.from_lengths(torch.tensor([0]))+ out = packed_attention(q[:0], k[:0], v[:0], empty, rel_pos_bias=bias[:0])+ assert out.shape == (0, 2, 8) and out.requires_grad @pytest.mark.unit @pytest.mark.gpu@@ -247,34 +338,31 @@ def test_empty_batch_keeps_gradients(self): [([300, 7, 150, 1, 260], 32), ([1000, 513, 2], 32), ([300, 7, 150], 8), ([300, 7, 150], 44)], ids=["five_utterances", "long_utterances", "head_dim_8", "head_dim_44"], )- def test_flex_attention_matches_reference_on_cuda(self, lengths, head_dim):+ def test_flex_attention_matches_reference_on_cuda(self, lengths, head_dim, flex_attention_only): """Also a head width below the kernel minimum of 16 and a non-power-of-two width, both zero-padded. Width 44 is the head of the released FastConformer Small; without the padding to a power of two it fell to a generic kernel configuration whose shared memory exceeds consumer Blackwell's (torch 2.12). """ torch.manual_seed(0)- lengths = torch.tensor(lengths, device="cuda")- heads = 4- states = torch.randn(len(lengths), int(lengths.max()), heads * head_dim, device="cuda")- packed = pack_encoder_output(states, lengths)- context = PackedAttentionContext(packed)- total, max_len = packed.total_tokens, packed.max_seqlen- q, k, v = (torch.randn(total, heads, head_dim, device="cuda", requires_grad=True) for _ in range(3))- bias = torch.randn(total, heads, 2 * max_len - 1, device="cuda", requires_grad=True)+ context = PackedAttentionContext.from_lengths(torch.tensor(lengths, device="cuda"))+ assert not context.rel_pos_kernel+ q, k, v, pos_query, pos_emb = _rel_pos_inputs(context, heads=4, head_dim=head_dim)+ leaves = (q, k, v, pos_query, pos_emb) - out = packed_attention(q, k, v, context, rel_pos_bias=bias)+ out = packed_attention(q, k, v, context, pos_query=pos_query, pos_emb=pos_emb) out.square().sum().backward()- grads = [t.grad.clone() for t in (q, k, v, bias)]- for t in (q, k, v, bias):+ grads = [t.grad.clone() for t in leaves]+ for t in leaves: t.grad = None+ bias = torch.einsum("thd,rhd->thr", pos_query, pos_emb) reference = packed_attention_module._reference_packed_attention( q, k, v, context, rel_pos_bias=bias, dropout_p=0.0, scale=head_dim**-0.5 ) reference.square().sum().backward() torch.testing.assert_close(out, reference, atol=1e-4, rtol=1e-4)- for grad, t in zip(grads, (q, k, v, bias)):+ for grad, t in zip(grads, leaves): torch.testing.assert_close(grad, t.grad, atol=1e-3, rtol=1e-3) @@ -504,3 +592,665 @@ def select_provider(queries): torch.testing.assert_close(flash_value, reference_value, atol=tolerance, rtol=tolerance, msg=name) torch.testing.assert_close(flex_value, reference_value, atol=tolerance, rtol=tolerance, msg=name) torch.testing.assert_close(flash_value, flex_value, atol=tolerance, rtol=tolerance, msg=name)+++def _dense_reference(q, k, v, pos_query, pos_emb, starts, lens, scale, keep=None, dropout_p=0.0):+ """Dense attention one utterance at a time in the dtype of the inputs, for any packed layout.++ ``keep`` is the kept-weight mask ``(T_total, H, max_seqlen)`` of the kernel's dropout, if any.+ """+ out = torch.zeros_like(q)+ heads = q.shape[1]+ center = (pos_emb.shape[0] - 1) // 2+ for start, length in zip(starts, lens):+ if length == 0:+ continue+ rows = slice(start, start + length)+ scores = torch.einsum("ihd,jhd->hij", q[rows], k[rows]) * scale+ positions = torch.arange(length, device=q.device)+ relative = center + positions[None, :] - positions[:, None]+ bias = torch.einsum("ihd,rhd->hir", pos_query[rows], pos_emb)+ scores = scores + bias.gather(2, relative.expand(heads, -1, -1)) * scale+ weights = torch.softmax(scores, dim=-1)+ if keep is not None:+ weights = weights * keep[rows, :, :length].permute(1, 0, 2).to(weights.dtype) / (1.0 - dropout_p)+ out[rows] = torch.einsum("hij,jhd->ihd", weights, v[rows])+ return out+++def _lengths_starts(lengths):+ """Starts of a dense packing of these lengths."""+ return [sum(lengths[:i]) for i in range(len(lengths))]+++def _max_relative_error(actual, reference):+ """Largest absolute difference relative to the largest magnitude of the reference, in float64."""+ reference = reference.double()+ return float((actual.double() - reference).abs().max() / reference.abs().max().clamp_min(1e-12))+++def _relative_norm_error(actual, reference):+ reference = reference.double()+ return float((actual.double() - reference).norm() / reference.norm().clamp_min(1e-12))+++@pytest.mark.gpu+@requires_kernel+class TestPackedRelPosAttentionKernel:+ """The Triton kernel against the dense per-utterance reference in float64, on the kernel's own layout."""++ @staticmethod+ def _run(q, k, v, pos_query, pos_emb, starts, lens, max_seqlen, scale, *, dropout_p=0.0, seed=None):+ """Forward and the five gradients of the kernel, for a random upstream gradient of fixed seed."""+ leaves = (q, k, v, pos_query, pos_emb)+ out = kernel_module.packed_rel_pos_attention(+ q, k, v, pos_query, pos_emb, starts, lens, max_seqlen, dropout_p=dropout_p, dropout_seed=seed, scale=scale+ )+ d_out = torch.randn(out.shape, generator=torch.Generator(device="cuda").manual_seed(99), device="cuda")+ d_out = d_out.to(out.dtype)+ grads = torch.autograd.grad(out, leaves, d_out)+ return out, grads, d_out++ @staticmethod+ def _reference(q, k, v, pos_query, pos_emb, starts, lens, scale, d_out, *, keep=None, dropout_p=0.0):+ """The float64 reference outputs and gradients for the same (rounded) inputs."""+ leaves = [t.detach().double().requires_grad_() for t in (q, k, v, pos_query, pos_emb)]+ out = _dense_reference(*leaves, starts, lens, scale, keep=keep, dropout_p=dropout_p)+ grads = torch.autograd.grad(out, leaves, d_out.double())+ return out, grads++ @staticmethod+ def _check(kernel, reference, tolerance, norm=False):+ names = ("out", "d_q", "d_k", "d_v", "d_pos_query", "d_pos_emb")+ for name, actual, expected in zip(names, (kernel[0], *kernel[1]), (reference[0], *reference[1])):+ assert torch.isfinite(actual).all(), name+ error = _relative_norm_error(actual, expected) if norm else _max_relative_error(actual, expected)+ assert error <= tolerance, (name, error)++ @pytest.mark.unit+ @pytest.mark.parametrize(+ "lengths, head_dim",+ [([300, 7, 150, 1, 260], 64), ([257, 33], 128), ([5, 0, 1, 3], 64), ([300, 7, 150], 44)],+ ids=["five_utterances", "odd_widths", "empty_and_single_frame", "head_dim_44"],+ )+ def test_matches_float64_reference(self, lengths, head_dim):+ """Outputs and all five gradients in float32, against the reference in float64 and in float32."""+ torch.manual_seed(0)+ context = PackedAttentionContext.from_lengths(torch.tensor(lengths, device="cuda"))+ q, k, v, pos_query, pos_emb = _rel_pos_inputs(context, heads=4, head_dim=head_dim, pos_scale=0.5)+ starts, lens = context.seq_starts, context.seq_lens+ scale = head_dim**-0.5+ kernel = self._run(q, k, v, pos_query, pos_emb, starts, lens, context.max_seqlen, scale)+ reference64 = self._reference(q, k, v, pos_query, pos_emb, _lengths_starts(lengths), lengths, scale, kernel[2])+ self._check(kernel, reference64, tolerance=2e-5)+ # the tolerance is at the float32 level: the float32 reference meets it against the float64 one as well+ reference32 = _dense_reference(+ *(t.detach() for t in (q, k, v, pos_query, pos_emb)), _lengths_starts(lengths), lengths, scale+ )+ assert _max_relative_error(reference32, reference64[0]) <= 2e-5++ @pytest.mark.unit+ @pytest.mark.parametrize("dtype, tolerance", [(torch.bfloat16, 3e-2), (torch.float16, 1e-2)])+ @pytest.mark.parametrize("head_dim", [64, 128])+ def test_matches_float64_reference_in_half_precision(self, dtype, tolerance, head_dim):+ """Outputs and gradients in bfloat16 and float16 against the float64 reference, by relative norm error."""+ torch.manual_seed(1)+ lengths = [300, 7, 150, 1, 260]+ context = PackedAttentionContext.from_lengths(torch.tensor(lengths, device="cuda"))+ q, k, v, pos_query, pos_emb = _rel_pos_inputs(context, heads=4, head_dim=head_dim, dtype=dtype, pos_scale=0.5)+ scale = head_dim**-0.5+ kernel = self._run(+ q, k, v, pos_query, pos_emb, context.seq_starts, context.seq_lens, context.max_seqlen, scale+ )+ reference64 = self._reference(q, k, v, pos_query, pos_emb, _lengths_starts(lengths), lengths, scale, kernel[2])+ assert kernel[0].dtype == dtype and all(grad.dtype == dtype for grad in kernel[1])+ self._check(kernel, reference64, tolerance=tolerance, norm=True)++ @pytest.mark.unit+ def test_tile_ladder_steps_down_where_the_shared_memory_ends(self, monkeypatch):+ """A configuration Triton refuses is skipped once per key and the next one runs; an exhausted ladder raises."""+ torch.manual_seed(12)+ lengths = [300, 7, 150]+ context = PackedAttentionContext.from_lengths(torch.tensor(lengths, device="cuda"))+ q, k, v, pos_query, pos_emb = _rel_pos_inputs(context, heads=2, head_dim=64, pos_scale=0.5)+ starts, lens, max_seqlen, scale = context.seq_starts, context.seq_lens, context.max_seqlen, 64**-0.5+ key = ("forward", q.device.index, q.dtype, 64)+ monkeypatch.setattr(kernel_module, "_tiles_in_use", {})+ self._run(q, k, v, pos_query, pos_emb, starts, lens, max_seqlen, scale)+ entry = kernel_module._tiles_in_use[key] # the entry this GPU runs without interference+ oversized = (64, 128, 8, 64) # 64 pipeline stages of key and value tiles exceed any shared memory+ monkeypatch.setattr(kernel_module, "_tiles_in_use", {})+ monkeypatch.setattr(kernel_module, "FORWARD_TILES", (oversized,) + kernel_module.FORWARD_TILES)+ kernel = self._run(q, k, v, pos_query, pos_emb, starts, lens, max_seqlen, scale)+ reference64 = self._reference(q, k, v, pos_query, pos_emb, _lengths_starts(lengths), lengths, scale, kernel[2])+ self._check(kernel, reference64, tolerance=2e-5)+ assert kernel_module._tiles_in_use[key] == entry + 1+ monkeypatch.setattr(kernel_module, "_tiles_in_use", {})+ monkeypatch.setattr(kernel_module, "FORWARD_TILES", (oversized,))+ with pytest.raises(kernel_module.OutOfResources):+ self._run(q, k, v, pos_query, pos_emb, starts, lens, max_seqlen, scale)++ @pytest.mark.unit+ def test_empty_input_keeps_the_gradient_edges(self):+ heads, head_dim = 2, 32+ leaves = [torch.randn(0, heads, head_dim, device="cuda", requires_grad=True) for _ in range(4)]+ pos_emb = torch.randn(1, heads, head_dim, device="cuda", requires_grad=True)+ starts = torch.zeros(2, dtype=torch.int32, device="cuda")+ out = kernel_module.packed_rel_pos_attention(*leaves, pos_emb, starts, starts, 0)+ assert out.shape == (0, heads, head_dim)+ grads = torch.autograd.grad(out.sum(), (*leaves, pos_emb))+ assert all(grad.shape == leaf.shape and not grad.any() for grad, leaf in zip(grads, (*leaves, pos_emb)))++ @pytest.mark.unit+ def test_all_empty_pack_with_non_finite_payloads_returns_zeros(self):+ """The rows of a pack whose utterances are all empty are gap rows: zeros, whatever their payload."""+ heads, head_dim = 1, 16+ leaves = [torch.full((4, heads, head_dim), float("nan"), device="cuda", requires_grad=True) for _ in range(4)]+ pos_emb = torch.full((1, heads, head_dim), float("nan"), device="cuda", requires_grad=True)+ starts = torch.tensor([0, 2], device="cuda", dtype=torch.int32)+ lens = torch.zeros(2, device="cuda", dtype=torch.int32)+ out = kernel_module.packed_rel_pos_attention(*leaves, pos_emb, starts, lens, 0)+ assert torch.equal(out, torch.zeros_like(out))+ grads = torch.autograd.grad(out.sum(), (*leaves, pos_emb))+ assert all(torch.equal(grad, torch.zeros_like(leaf)) for grad, leaf in zip(grads, (*leaves, pos_emb)))++ @pytest.mark.unit+ def test_full_dropout_zeroes_the_output(self):+ """``dropout_p=1.0`` drops every weight, as ``nn.Dropout(1.0)`` on the attention weights would."""+ context = PackedAttentionContext.from_lengths(torch.tensor([20, 5], device="cuda"))+ q, k, v, pos_query, pos_emb = _rel_pos_inputs(context, heads=2, head_dim=32)+ starts, lens, max_seqlen = context.seq_starts, context.seq_lens, context.max_seqlen+ out = kernel_module.packed_rel_pos_attention(+ q, k, v, pos_query, pos_emb, starts, lens, max_seqlen, dropout_p=1.0+ )+ assert torch.equal(out, torch.zeros_like(q))+ grads = torch.autograd.grad(out.sum(), (q, k, v, pos_query, pos_emb))+ assert all(not grad.any() for grad in grads)+ out = packed_attention(q, k, v, context, pos_query=pos_query, pos_emb=pos_emb, dropout_p=1.0)+ assert torch.equal(out, torch.zeros_like(q))++ @pytest.mark.unit+ def test_length_beyond_max_seqlen_is_rejected(self):+ """A bound below a length would leave query rows zero and send position lookups past the table."""+ heads, head_dim = 1, 16+ q, k, pos_query = (torch.zeros(65, heads, head_dim, device="cuda") for _ in range(3))+ v = torch.ones_like(q)+ starts = torch.zeros(1, device="cuda", dtype=torch.int32)+ lens = torch.full((1,), 65, device="cuda", dtype=torch.int32)+ attend = kernel_module.packed_rel_pos_attention+ with pytest.raises(ValueError, match="longest utterance of 65 rows"):+ attend(q, k, v, pos_query, torch.zeros(1, heads, head_dim, device="cuda"), starts, lens, 1)+ # the correct bound attends every row: uniform weights over the ones of v+ table = torch.zeros(2 * 65 - 1, heads, head_dim, device="cuda")+ out = attend(q, k, v, pos_query, table, starts, lens, 65)+ torch.testing.assert_close(out, torch.ones_like(out))+ # a compiled call cannot read the lengths: with the check on it is refused, never skipped+ compiled = torch.compile(attend, fullgraph=True)+ with pytest.raises(Exception, match="pass check_lengths=False"):+ compiled(q, k, v, pos_query, table, starts, lens, 1)+ with pytest.raises(Exception, match="pass check_lengths=False"):+ compiled(q, k, v, pos_query, table, starts, lens, 65)+ out = compiled(q, k, v, pos_query, table, starts, lens, 65, check_lengths=False)+ torch.testing.assert_close(out, torch.ones_like(out))+ torch._dynamo.reset()++ @pytest.mark.unit+ @pytest.mark.skipif(torch.cuda.device_count() < 2, reason="requires two CUDA devices")+ def test_runs_on_a_device_other_than_the_current(self):+ """The launches pin the input device: tensors on the second device while the first one is current,+ with an update of the input queued on a stream of the second device."""+ torch.manual_seed(3)+ device = torch.device("cuda:1")+ lens = [30, 7, 15]+ context = PackedAttentionContext.from_lengths(torch.tensor(lens, device=device))+ q, k, v, pos_query, pos_emb = _rel_pos_inputs(context, heads=2, head_dim=32, device=device)+ starts_t, lens_t, max_seqlen = context.seq_starts, context.seq_lens, context.max_seqlen+ scale = 32**-0.5+ stream = torch.cuda.Stream(device=device)+ with torch.cuda.stream(stream), torch.cuda.device(0):+ assert torch.cuda.current_device() == 0 and torch.cuda.current_stream(device) == stream+ with torch.no_grad():+ q.add_(0.5)+ out = kernel_module.packed_rel_pos_attention(q, k, v, pos_query, pos_emb, starts_t, lens_t, max_seqlen)+ d_out = torch.randn(out.shape, device=device)+ grads = torch.autograd.grad(out, (q, k, v, pos_query, pos_emb), d_out)+ stream.synchronize()+ starts = [0, 30, 37]+ reference = self._reference(q, k, v, pos_query, pos_emb, starts, lens, scale, d_out)+ self._check((out, grads, d_out), reference, tolerance=2e-5)++ @pytest.mark.unit+ def test_gaps_between_utterances_and_junk_rows(self):+ """Any layout: the rows between the utterances are never read and come back as zeros."""+ torch.manual_seed(2)+ lens = [40, 0, 25, 9]+ starts = [8, 60, 61, 100]+ total, heads, head_dim = 128, 2, 32+ q, k, v, pos_query = (torch.randn(total, heads, head_dim, device="cuda") * 100 for _ in range(4))+ for start, length in zip(starts, lens):+ for tensor in (q, k, v, pos_query):+ tensor[start : start + length] = torch.randn(length, heads, head_dim, device="cuda")+ leaves = [t.requires_grad_() for t in (q, k, v, pos_query)]+ pos_emb = (torch.randn(2 * 40 - 1, heads, head_dim, device="cuda") * 0.5).requires_grad_()+ starts_t = torch.tensor(starts, device="cuda", dtype=torch.int32)+ lens_t = torch.tensor(lens, device="cuda", dtype=torch.int32)+ scale = head_dim**-0.5+ kernel = self._run(*leaves, pos_emb, starts_t, lens_t, 40, scale)+ reference64 = self._reference(*leaves, pos_emb, starts, lens, scale, kernel[2])+ self._check(kernel, reference64, tolerance=2e-5)+ valid = torch.zeros(total, dtype=torch.bool, device="cuda")+ for start, length in zip(starts, lens):+ valid[start : start + length] = True+ assert (kernel[0][~valid] == 0).all()+ for grad in kernel[1][:4]:+ assert (grad[~valid] == 0).all()+ # non-finite payloads in the gap rows change nothing: the kernels never read them,+ # and the position-embedding gradient excludes them+ for tensor in leaves:+ with torch.no_grad():+ tensor[~valid] = float("nan")+ tensor[~valid, :, 0] = float("inf")+ poisoned = self._run(*leaves, pos_emb, starts_t, lens_t, 40, scale)+ for name, before, after in zip(+ ("out", "d_q", "d_k", "d_v", "d_pos_query", "d_pos_emb"),+ (kernel[0], *kernel[1]),+ (poisoned[0], *poisoned[1]),+ ):+ assert torch.equal(before, after), name++ @pytest.mark.unit+ def test_strided_metadata_reads_every_utterance(self):+ """Starts and lengths may arrive as strided views; the kernels read them as laid out."""+ torch.manual_seed(13)+ heads, head_dim = 2, 32+ leaves = [torch.randn(3, heads, head_dim, device="cuda", requires_grad=True) for _ in range(4)]+ pos_emb = torch.randn(1, heads, head_dim, device="cuda", requires_grad=True)+ starts = torch.tensor([0, 0, 2, 0], device="cuda", dtype=torch.int32)[::2]+ lens = torch.tensor([1, 0, 1, 0], device="cuda", dtype=torch.int64)[::2]+ assert not starts.is_contiguous() and not lens.is_contiguous()+ strided = self._run(*leaves, pos_emb, starts, lens, 1, head_dim**-0.5)+ contiguous = self._run(*leaves, pos_emb, starts.contiguous(), lens.contiguous(), 1, head_dim**-0.5)+ torch.testing.assert_close(strided[0][0], leaves[2][0])+ torch.testing.assert_close(strided[0][2], leaves[2][2])+ assert (strided[0][1] == 0).all()+ for before, after in zip((strided[0], *strided[1]), (contiguous[0], *contiguous[1])):+ assert torch.equal(before, after)++ @pytest.mark.unit+ def test_large_upstream_gradient_in_float16_keeps_finite_position_gradients(self):+ """The position-term gradient is scaled in float32 before its float16 cast, so it does not overflow."""+ heads, head_dim = 1, 16+ zeros = [+ torch.zeros(2, heads, head_dim, device="cuda", dtype=torch.float16, requires_grad=True) for _ in range(3)+ ]+ q, k, pos_query = zeros+ v = torch.zeros(2, heads, head_dim, device="cuda", dtype=torch.float16)+ v[:, 0, 0] = torch.tensor([4.0, -4.0])+ v.requires_grad_()+ pos_emb = torch.zeros(3, heads, head_dim, device="cuda", dtype=torch.float16, requires_grad=True)+ starts = torch.tensor([0], device="cuda", dtype=torch.int32)+ lens = torch.tensor([2], device="cuda", dtype=torch.int32)+ for scale in (None, 0.5):+ out = kernel_module.packed_rel_pos_attention(q, k, v, pos_query, pos_emb, starts, lens, 2, scale=scale)+ d_out = torch.zeros_like(out)+ d_out[:, 0, 0] = 60000.0+ grads = torch.autograd.grad(out, (q, k, v, pos_query, pos_emb), d_out)+ assert all(torch.isfinite(grad).all() for grad in grads)+ assert all(not grad.any() for grad in (grads[0], grads[1], grads[3], grads[4]))+ torch.testing.assert_close(+ grads[2][:, 0, 0], torch.full((2,), 60000.0, device="cuda", dtype=torch.float16)+ )++ @pytest.mark.unit+ def test_wider_position_table_is_sliced_to_the_utterances(self):+ """A table beyond the longest utterance adds nothing; its outer rows get no gradient."""+ torch.manual_seed(3)+ lengths = [30, 12]+ context = PackedAttentionContext.from_lengths(torch.tensor(lengths, device="cuda"))+ q, k, v, pos_query, _ = _rel_pos_inputs(context, heads=2, head_dim=32)+ pos_emb = torch.randn(2 * 100 - 1, 2, 32, device="cuda", requires_grad=True)+ scale = 32**-0.5+ kernel = self._run(q, k, v, pos_query, pos_emb, context.seq_starts, context.seq_lens, 30, scale)+ reference64 = self._reference(q, k, v, pos_query, pos_emb, [0, 30], lengths, scale, kernel[2])+ self._check(kernel, reference64, tolerance=2e-5)+ d_pos_emb = kernel[1][4]+ assert (d_pos_emb[:70] == 0).all() and (d_pos_emb[129:] == 0).all() and d_pos_emb[70:129].abs().sum() > 0++ @pytest.mark.unit+ def test_dropout_mask_statistics_and_exact_parity(self):+ """The kept weights follow the probability, and the output equals the reference with the kernel's mask."""+ torch.manual_seed(4)+ lengths = [300, 7, 150, 260]+ context = PackedAttentionContext.from_lengths(torch.tensor(lengths, device="cuda"))+ heads, head_dim, dropout_p = 4, 64, 0.3+ q, k, v, pos_query, pos_emb = _rel_pos_inputs(context, heads=heads, head_dim=head_dim, pos_scale=0.5)+ seed = torch.tensor([12345], dtype=torch.int32, device="cuda")+ keep = _keep_mask(context.total_tokens, heads, context.max_seqlen, dropout_p=dropout_p, dropout_seed=seed)+ assert keep.shape == (context.total_tokens, heads, context.max_seqlen)+ valid_pairs = sum(length * length for length in lengths) * heads+ kept = sum(+ int(keep[start : start + length, :, :length].sum()) for start, length in zip([0, 300, 307, 457], lengths)+ )+ assert abs(kept / valid_pairs - (1.0 - dropout_p)) < 0.01+ scale = head_dim**-0.5+ kernel = self._run(+ q,+ k,+ v,+ pos_query,+ pos_emb,+ context.seq_starts,+ context.seq_lens,+ context.max_seqlen,+ scale,+ dropout_p=dropout_p,+ seed=seed,+ )+ reference64 = self._reference(+ q, k, v, pos_query, pos_emb, [0, 300, 307, 457], lengths, scale, kernel[2], keep=keep, dropout_p=dropout_p+ )+ self._check(kernel, reference64, tolerance=2e-5)++ @pytest.mark.unit+ def test_dropout_seed_determines_the_mask(self):+ torch.manual_seed(5)+ context = PackedAttentionContext.from_lengths(torch.tensor([64, 30], device="cuda"))+ q, k, v, pos_query, pos_emb = _rel_pos_inputs(context, heads=2, head_dim=32)+ args = (q, k, v, pos_query, pos_emb, context.seq_starts, context.seq_lens, context.max_seqlen)++ def attend(seed):+ return kernel_module.packed_rel_pos_attention(*args, dropout_p=0.5, dropout_seed=seed).detach()++ seed_a = torch.tensor([7], dtype=torch.int32, device="cuda")+ torch.testing.assert_close(attend(seed_a), attend(seed_a), atol=0.0, rtol=0.0)+ assert not torch.equal(attend(seed_a), attend(torch.tensor([8], dtype=torch.int32, device="cuda")))+ # without a seed the kernel draws one from the device generator: fresh per call, reproducible per seed+ torch.manual_seed(11)+ first = attend(None)+ second = attend(None)+ assert not torch.equal(first, second)+ torch.manual_seed(11)+ torch.testing.assert_close(attend(None), first, atol=0.0, rtol=0.0)+ without_dropout = kernel_module.packed_rel_pos_attention(*args).detach()+ assert not torch.equal(first, without_dropout)++ @pytest.mark.unit+ def test_cuda_graph_replay_follows_new_contents_and_lengths(self):+ """Forward and backward captured once; replays see new tensors, new lengths within the bound, the seed.+ The capture cannot read the lengths, so the call passes ``check_lengths=False`` and the bound is the+ caller's: every replay stays within it."""+ torch.manual_seed(6)+ heads, head_dim, capacity, bound = 2, 32, 160, 64+ static = {+ name: torch.randn(capacity, heads, head_dim, device="cuda", requires_grad=True)+ for name in ("q", "k", "v", "pos_query")+ }+ static["pos_emb"] = torch.randn(2 * bound - 1, heads, head_dim, device="cuda", requires_grad=True)+ d_out = torch.randn(capacity, heads, head_dim, device="cuda")+ starts = torch.tensor([0, 60, 100], dtype=torch.int32, device="cuda")+ lens = torch.tensor([60, 40, 60], dtype=torch.int32, device="cuda")+ seed = torch.tensor([3], dtype=torch.int32, device="cuda")+ leaves = tuple(static.values())++ def step():+ out = kernel_module.packed_rel_pos_attention(+ *leaves,+ starts,+ lens,+ bound,+ dropout_p=0.2,+ dropout_seed=seed,+ scale=head_dim**-0.5,+ check_lengths=False,+ )+ return (out, *torch.autograd.grad(out, leaves, d_out))++ stream = torch.cuda.Stream()+ stream.wait_stream(torch.cuda.current_stream())+ with torch.cuda.stream(stream):+ for _ in range(3):+ step()+ torch.cuda.current_stream().wait_stream(stream)+ graph = torch.cuda.CUDAGraph()+ with torch.cuda.graph(graph):+ captured = step()++ def eager():+ return [t.detach().clone() for t in step()]++ for new_lens, new_seed in (([30, 0, 55], 21), ([60, 37, 2], 22)):+ for tensor in leaves:+ tensor.data.copy_(torch.randn_like(tensor))+ lens.copy_(torch.tensor(new_lens, dtype=torch.int32, device="cuda"))+ seed.fill_(new_seed)+ graph.replay()+ replayed = [t.clone() for t in captured]+ for actual, expected in zip(replayed, eager()):+ torch.testing.assert_close(actual, expected, atol=1e-6, rtol=1e-6)++ @pytest.mark.unit+ def test_cuda_graph_replays_draw_fresh_dropout_masks(self):+ """Without a given seed the capture holds a device draw, so every replay has another mask."""+ torch.manual_seed(7)+ context = PackedAttentionContext.from_lengths(torch.tensor([64, 30], device="cuda"))+ q, k, v, pos_query, pos_emb = (t.detach() for t in _rel_pos_inputs(context, heads=2, head_dim=32))+ args = (q, k, v, pos_query, pos_emb, context.seq_starts, context.seq_lens, context.max_seqlen)+ stream = torch.cuda.Stream()+ stream.wait_stream(torch.cuda.current_stream())+ with torch.cuda.stream(stream):+ for _ in range(2):+ kernel_module.packed_rel_pos_attention(*args, dropout_p=0.5)+ torch.cuda.current_stream().wait_stream(stream)+ graph = torch.cuda.CUDAGraph()+ with torch.cuda.graph(graph):+ # the capture cannot read the lengths: the context's bound holds by construction+ out = kernel_module.packed_rel_pos_attention(*args, dropout_p=0.5, check_lengths=False)+ graph.replay()+ first = out.clone()+ graph.replay()+ second = out.clone()+ assert torch.isfinite(first).all() and torch.isfinite(second).all()+ assert not torch.equal(first, second)++ @pytest.mark.unit+ def test_production_shape_stays_below_the_int32_bound(self):+ """Eight heads of 128 over a packed batch of the training size: finite, and one call equals two halves.++ The position term is addressed as ``h * T_total * R + i * R + r`` in 64 bits (R padded to eight);+ at this shape the product stays below 2**31, so a 32-bit regression would not show here,+ which test_offsets_beyond_the_int32_bound covers.+ """+ torch.manual_seed(8)+ generator = torch.Generator().manual_seed(8)+ lengths = []+ while sum(lengths) < 83_000:+ lengths.append(int(torch.randint(50, 668, (1,), generator=generator)))+ heads, head_dim = 8, 128+ context = PackedAttentionContext.from_lengths(torch.tensor(lengths, device="cuda"))+ assert heads * context.total_tokens * (2 * context.max_seqlen - 1 + 8) < 2**31+ q, k, v, pos_query, pos_emb = _rel_pos_inputs(context, heads=heads, head_dim=head_dim, dtype=torch.bfloat16)+ self._full_equals_halves(q, k, v, pos_query, pos_emb, lengths, head_dim**-0.5)++ @pytest.mark.unit+ def test_offsets_beyond_the_int32_bound(self):+ """The position term of 96 utterances of 2,000 frames with four heads exceeds 2**31 elements."""+ if torch.cuda.get_device_properties(0).total_memory < 64 * 1024**3:+ pytest.skip("needs a 64 GiB GPU for the position term and its gradient")+ torch.manual_seed(9)+ heads, head_dim, seq_len, n_seqs = 4, 64, 2000, 96+ lengths = [seq_len] * n_seqs+ context = PackedAttentionContext.from_lengths(torch.tensor(lengths, device="cuda"))+ assert heads * context.total_tokens * (2 * seq_len - 1) > 2**31+ q, k, v, pos_query, pos_emb = _rel_pos_inputs(context, heads=heads, head_dim=head_dim, pos_scale=0.1)+ self._full_equals_halves(q, k, v, pos_query, pos_emb, lengths, head_dim**-0.5)++ def _full_equals_halves(self, q, k, v, pos_query, pos_emb, lengths, scale):+ """One call over all utterances against two calls over the halves of the batch, outputs and gradients."""+ max_seqlen = max(lengths)+ starts = _lengths_starts(lengths)+ d_out = torch.randn(q.shape, generator=torch.Generator(device="cuda").manual_seed(99), device="cuda")+ d_out = d_out.to(q.dtype)++ def run(first, last):+ begin, end = starts[first], starts[last - 1] + lengths[last - 1]+ leaves = [t[begin:end].detach().clone().requires_grad_() for t in (q, k, v, pos_query)]+ table = pos_emb.detach().clone().requires_grad_()+ starts_t = torch.tensor([s - begin for s in starts[first:last]], dtype=torch.int32, device="cuda")+ lens_t = torch.tensor(lengths[first:last], dtype=torch.int32, device="cuda")+ out = kernel_module.packed_rel_pos_attention(*leaves, table, starts_t, lens_t, max_seqlen, scale=scale)+ return [out.detach(), *torch.autograd.grad(out, (*leaves, table), d_out[begin:end])]++ half = len(lengths) // 2+ full, first, second = run(0, len(lengths)), run(0, half), run(half, len(lengths))+ tolerance = 1e-2 if q.dtype == torch.bfloat16 else 1e-4+ for name, whole, a, b in zip(("out", "d_q", "d_k", "d_v", "d_pos_query", "d_pos_emb"), full, first, second):+ halves = a + b if name == "d_pos_emb" else torch.cat([a, b])+ assert torch.isfinite(whole).all(), name+ error = _relative_norm_error(whole, halves)+ assert error <= tolerance, (name, error)++ @pytest.mark.unit+ def test_rejects_what_the_kernels_cannot_take(self):+ context = PackedAttentionContext.from_lengths(torch.tensor([20, 5], device="cuda"))+ q, k, v, pos_query, pos_emb = (t.detach() for t in _rel_pos_inputs(context, heads=2, head_dim=32))+ starts, lens, max_seqlen = context.seq_starts, context.seq_lens, context.max_seqlen+ attend = kernel_module.packed_rel_pos_attention+ with pytest.raises(TypeError, match="float32, bfloat16 or float16"):+ attend(q.double(), k.double(), v.double(), pos_query.double(), pos_emb.double(), starts, lens, max_seqlen)+ with pytest.raises(TypeError, match="pos_emb must be"):+ attend(q, k, v, pos_query, pos_emb.half(), starts, lens, max_seqlen)+ with pytest.raises(ValueError, match="odd number of rows"):+ attend(q, k, v, pos_query, pos_emb[1:], starts, lens, max_seqlen)+ with pytest.raises(ValueError, match="covers no utterance"):+ attend(q, k, v, pos_query, pos_emb[2:-2], starts, lens, max_seqlen)+ with pytest.raises(ValueError, match="dropout_p"):+ attend(q, k, v, pos_query, pos_emb, starts, lens, max_seqlen, dropout_p=1.5)+ with pytest.raises(ValueError, match="dropout_seed"):+ attend(q, k, v, pos_query, pos_emb, starts, lens, max_seqlen, dropout_p=0.1, dropout_seed=starts)+ with pytest.raises(ValueError, match="shape of q"):+ attend(q, k[:-1], v, pos_query, pos_emb, starts, lens, max_seqlen)+++@pytest.mark.gpu+@requires_kernel+class TestPackedRelPosAttentionDispatch:+ """What packed_attention routes to the kernel, and what it keeps for FlexAttention and the reference."""++ @pytest.mark.unit+ @pytest.mark.parametrize("dtype", [torch.float32, torch.bfloat16])+ def test_kernel_is_the_default_for_rel_pos_on_cuda(self, monkeypatch, dtype):+ calls = []+ original = packed_attention_module.packed_rel_pos_attention+ monkeypatch.setattr(+ packed_attention_module, "packed_rel_pos_attention", lambda *a, **kw: calls.append(1) or original(*a, **kw)+ )+ monkeypatch.setattr(packed_attention_module, "_flex_packed_attention", _fail)+ context = PackedAttentionContext.from_lengths(torch.tensor([30, 7], device="cuda"))+ q, k, v, pos_query, pos_emb = _rel_pos_inputs(context, heads=2, head_dim=32, dtype=dtype)+ out = packed_attention(q, k, v, context, pos_query=pos_query, pos_emb=pos_emb, dropout_p=0.1)+ assert calls == [1] and out.dtype == dtype and out.shape == q.shape++ @pytest.mark.unit+ def test_float64_runs_the_reference_on_cuda(self, monkeypatch):+ """Neither the kernel nor FlexAttention's Inductor template takes float64; the dense reference does."""+ calls = []+ original = packed_attention_module._reference_packed_attention+ monkeypatch.setattr(+ packed_attention_module,+ "_reference_packed_attention",+ lambda *a, **kw: calls.append(1) or original(*a, **kw),+ )+ monkeypatch.setattr(packed_attention_module, "_flex_packed_attention", _fail)+ context = PackedAttentionContext.from_lengths(torch.tensor([30, 7], device="cuda"))+ q, k, v, pos_query, pos_emb = _rel_pos_inputs(context, heads=2, head_dim=32, dtype=torch.float64)+ out = packed_attention(q, k, v, context, pos_query=pos_query, pos_emb=pos_emb, dropout_p=0.1)+ assert calls == [1] and out.dtype == torch.float64 and out.shape == q.shape+ # the capability query agrees: the reference applies the dropout, with and without a position term+ device = torch.device("cuda")+ assert packed_attention_module.packed_attention_supports_dropout(device, torch.float64, 44)+ assert packed_attention_module.packed_attention_supports_dropout(device, torch.float64, 44, rel_pos=True)+ monkeypatch.setattr(packed_attention_module, "TRITON_AVAILABLE", False)+ assert packed_attention_module.packed_attention_supports_dropout(device, torch.float64, 44, rel_pos=True)+ assert not packed_attention_module.packed_attention_supports_dropout(device, torch.float32, 44, rel_pos=True)++ @pytest.mark.unit+ def test_rel_pos_bias_keyword_runs_flex_attention(self, monkeypatch):+ """The materialized position term keeps the FlexAttention path of the earlier interface, dropout refusal included."""+ monkeypatch.setattr(packed_attention_module, "packed_rel_pos_attention", _fail)+ context = PackedAttentionContext.from_lengths(torch.tensor([30, 7], device="cuda"))+ q, k, v, pos_query, pos_emb = _rel_pos_inputs(context, heads=2, head_dim=32)+ bias = torch.einsum("thd,rhd->thr", pos_query, pos_emb).detach().requires_grad_()+ out = packed_attention(q, k, v, context, rel_pos_bias=bias)+ reference = packed_attention_module._reference_packed_attention(+ q.double(), k.double(), v.double(), context, rel_pos_bias=bias.double(), dropout_p=0.0, scale=32**-0.5+ )+ torch.testing.assert_close(out.double(), reference, atol=1e-4, rtol=1e-4)+ out.square().sum().backward()+ assert bias.grad is not None and torch.isfinite(bias.grad).all() and bias.grad.abs().sum() > 0+ with pytest.raises(NotImplementedError, match="dropout_att"):+ packed_attention(q, k, v, context, rel_pos_bias=bias, dropout_p=0.1)++ @pytest.mark.unit+ def test_flex_attention_is_selectable_per_context(self, monkeypatch):+ """``rel_pos_kernel=False`` keeps the backend before the kernel: FlexAttention over the rounded table."""+ lengths = torch.tensor([30, 7], device="cuda")+ kernel_context = PackedAttentionContext.from_lengths(lengths)+ flex_context = PackedAttentionContext.from_lengths(lengths, rel_pos_kernel=False)+ assert kernel_context.rel_pos_kernel and not flex_context.rel_pos_kernel+ assert flex_context.rel_pos_max_seqlen == flex_context.padded_max_seqlen == 128+ q, k, v, pos_query, pos_emb = _rel_pos_inputs(flex_context, heads=2, head_dim=32)+ kernel = packed_attention(q, k, v, kernel_context, pos_query=pos_query, pos_emb=pos_emb)+ monkeypatch.setattr(packed_attention_module, "packed_rel_pos_attention", _fail)+ flex = packed_attention(q, k, v, flex_context, pos_query=pos_query, pos_emb=pos_emb)+ torch.testing.assert_close(flex, kernel, atol=1e-4, rtol=1e-4)+ with pytest.raises(NotImplementedError, match="dropout_att"):+ packed_attention(q, k, v, flex_context, pos_query=pos_query, pos_emb=pos_emb, dropout_p=0.1)++ @pytest.mark.unit+ def test_dropout_is_refused_only_without_the_kernel(self, flex_attention_only):+ context = PackedAttentionContext.from_lengths(torch.tensor([30, 7], device="cuda"))+ q, k, v, pos_query, pos_emb = _rel_pos_inputs(context, heads=2, head_dim=32)+ with pytest.raises(NotImplementedError, match="dropout_att"):+ packed_attention(q, k, v, context, pos_query=pos_query, pos_emb=pos_emb, dropout_p=0.1)++ @pytest.mark.unit+ def test_rel_position_attention_module_matches_padded_without_a_padded_copy(self, monkeypatch):+ """The Transformer-XL module through the kernel equals its padded forward; no pad and no FlexAttention run."""+ torch.manual_seed(2)+ attention = RelPositionMultiHeadAttention(+ n_head=4, n_feat=256, dropout_rate=0.0, pos_bias_u=None, pos_bias_v=None+ )+ torch.nn.init.normal_(attention.pos_bias_u)+ torch.nn.init.normal_(attention.pos_bias_v)+ attention = attention.cuda()+ pos_enc = RelPositionalEncoding(d_model=256, dropout_rate=0.0, max_len=400).cuda()+ pos_enc.extend_pe(400, "cuda", torch.float32)+ lengths = torch.tensor([300, 7, 150], device="cuda")+ x = torch.randn(3, 300, 256, device="cuda", requires_grad=True)+ _, pos_emb = pos_enc(x)+ pad = torch.arange(300, device="cuda")[None, :] >= lengths[:, None]+ mask = pad[:, None, :] | pad[:, :, None]+ padded_out = attention(query=x, key=x, value=x, mask=mask, pos_emb=pos_emb)+ _valid_frames(padded_out, lengths).square().sum().backward()+ reference_grads = {name: p.grad.clone() for name, p in attention.named_parameters()}+ attention.zero_grad()++ # the padded forward pads inside rel_shift; the packed one must need neither pad nor FlexAttention+ monkeypatch.setattr(packed_attention_module, "_flex_packed_attention", _fail)+ monkeypatch.setattr(torch.nn.functional, "pad", _fail)+ packed_x = x.detach().clone().requires_grad_()+ packed = pack_encoder_output(packed_x, lengths)+ context = PackedAttentionContext(packed)+ assert context.rel_pos_kernel+ packed_out = attention.forward_packed(packed.data, context, pos_emb=pos_emb)+ torch.testing.assert_close(packed_out, _valid_frames(padded_out, lengths), atol=1e-4, rtol=1e-4)+ packed_out.square().sum().backward()+ torch.testing.assert_close(+ _valid_frames(packed_x.grad, lengths), _valid_frames(x.grad, lengths), atol=1e-3, rtol=1e-3+ )+ for name, parameter in attention.named_parameters():+ torch.testing.assert_close(parameter.grad, reference_grads[name], atol=1e-3, rtol=1e-3, msg=name)+++def _fail(*args, **kwargs):+ raise AssertionError("this path must not run")tests/collections/asr/test_parallel_expert_encoder.py117 + / 7 −
@@ -42,6 +42,7 @@ from nemo.collections.asr.modules.transformer_encoder import TransformerEncoder from nemo.collections.asr.parts.packed_sequence import pack_encoder_output, unpack_encoder_output from nemo.collections.asr.parts.preprocessing.features import normalize_batch, normalize_packed_batch+from nemo.collections.asr.parts.submodules import packed_attention as packed_attention_module from nemo.collections.common.parts.optional_cuda_graphs import capture_cuda_graph from nemo.collections.speechlm2.parts import ctc_timestamp_utils from nemo.collections.speechlm2.parts.ctc_timestamp_utils import (@@ -53,6 +54,7 @@ get_ctc_timestamp_aligner, merge_prepared_batches, )+from nemo.core.utils.optional_libs import TRITON_AVAILABLE from tests.collections.asr.ctc_timestamp_test_utils import search_streams # ``@experimental`` wraps the class in a wrapt proxy, so ``__new__`` (used to build@@ -2008,21 +2010,23 @@ def tracked_packed_forward(*args, **kwargs): @pytest.mark.unit @pytest.mark.run_only_on("GPU") @pytest.mark.skipif(not torch.cuda.is_available(), reason="PEE GPU test requires CUDA")-def test_fastconformer_asr_branch_with_attention_dropout_keeps_the_padded_fallback_in_packed_training(monkeypatch):- """rel_pos attention over packed sequences runs FlexAttention on CUDA, which has no dropout.-- A FastConformer branch with ``dropout_att > 0`` therefore has no native packed form in training mode:- its ``supports_sequence_packed_output`` says so, the PEE keeps the padded fallback it ran before the native path- existed, and the step completes forward and backward; in evaluation mode the native path is available again.+def test_fastconformer_asr_branch_with_attention_dropout_in_packed_training(monkeypatch):+ """rel_pos attention over packed sequences keeps its dropout through its Triton kernel;+ without Triton it runs FlexAttention, which has no dropout.++ With Triton the FastConformer branch with ``dropout_att > 0`` runs its native packed path.+ Without it the branch has no native packed form in training mode: its ``supports_sequence_packed_output``+ says so, the PEE keeps the padded fallback it ran before the native path existed, and the step completes+ forward and backward; in evaluation mode the native path is available again. """+ # two heads over the 32-wide toy encoders: head dimension 16 asr_encoder_cfg = toy_asr_encoder_cfg() asr_encoder_cfg.n_heads = 2 asr_encoder_cfg.dropout_att = 0.1 diarization_model_cfg = toy_diarization_model_cfg() diarization_model_cfg.encoder.n_heads = 2 encoder = build_toy_pe_encoder(asr_encoder_cfg=asr_encoder_cfg, diarization_model_cfg=diarization_model_cfg) encoder = encoder.train().cuda()- assert not encoder.asr_encoder.supports_sequence_packed_output native_calls = [] native_forward = encoder.asr_encoder.forward_sequence_packed @@ -2034,6 +2038,20 @@ def tracked_native_forward(*args, **kwargs): lengths = torch.tensor([80, 53], device="cuda") mels = torch.randn(2, _MEL_FEATURES, 80, device="cuda", requires_grad=True) targets = torch.ones(2, 10, _N_SPK, device="cuda") # external speaker targets: Sortformer is skipped+ if TRITON_AVAILABLE:+ assert encoder.asr_encoder.supports_sequence_packed_output+ packed = encoder.forward_sequence_packed(mels, lengths, spk_targets=targets)+ assert native_calls == [1] and torch.isfinite(packed.data).all()+ # the backward through the native path as well+ packed.data.square().mean().backward()+ assert mels.grad is not None and torch.isfinite(mels.grad).all()+ query_grad = encoder.asr_encoder.layers[0].self_attn.linear_q.weight.grad+ assert query_grad is not None and torch.isfinite(query_grad).all()+ mels.grad = None+ encoder.zero_grad()+ native_calls.clear()+ monkeypatch.setattr(packed_attention_module, "TRITON_AVAILABLE", False)+ assert not encoder.asr_encoder.supports_sequence_packed_output packed = encoder.forward_sequence_packed(mels, lengths, spk_targets=targets) assert native_calls == [] and torch.isfinite(packed.data).all() packed.data.square().mean().backward()@@ -2043,6 +2061,44 @@ def tracked_native_forward(*args, **kwargs): assert encoder.asr_encoder.supports_sequence_packed_output +@pytest.mark.unit+@pytest.mark.run_only_on("GPU")+@pytest.mark.skipif(not (torch.cuda.is_available() and TRITON_AVAILABLE), reason="requires CUDA and Triton")+def test_fastconformer_asr_branch_with_full_attention_dropout_trains_packed(monkeypatch):+ """``dropout_att: 1.0`` is a valid ``nn.Dropout`` setting: the native packed path drops every attention weight+ and the step completes forward and backward, as the padded fallback did before the kernel."""+ asr_encoder_cfg = toy_asr_encoder_cfg()+ asr_encoder_cfg.n_heads = 2+ asr_encoder_cfg.dropout_att = 1.0+ diarization_model_cfg = toy_diarization_model_cfg()+ diarization_model_cfg.encoder.n_heads = 2+ encoder = build_toy_pe_encoder(asr_encoder_cfg=asr_encoder_cfg, diarization_model_cfg=diarization_model_cfg)+ encoder = encoder.train().cuda()+ native_calls = []+ native_forward = encoder.asr_encoder.forward_sequence_packed++ def tracked_native_forward(*args, **kwargs):+ native_calls.append(1)+ return native_forward(*args, **kwargs)++ monkeypatch.setattr(encoder.asr_encoder, "forward_sequence_packed", tracked_native_forward)+ assert encoder.asr_encoder.supports_sequence_packed_output+ lengths = torch.tensor([80, 53], device="cuda")+ mels = torch.randn(2, _MEL_FEATURES, 80, device="cuda", requires_grad=True)+ targets = torch.ones(2, 10, _N_SPK, device="cuda")+ for autocast in (False, True):+ with torch.autocast("cuda", dtype=torch.bfloat16, enabled=autocast):+ packed = encoder.forward_sequence_packed(mels, lengths, spk_targets=targets)+ assert torch.isfinite(packed.data).all()+ packed.data.float().square().mean().backward()+ assert mels.grad is not None and torch.isfinite(mels.grad).all()+ for name, parameter in encoder.asr_encoder.named_parameters():+ assert parameter.grad is None or torch.isfinite(parameter.grad).all(), name+ mels.grad = None+ encoder.zero_grad()+ assert native_calls == [1, 1]++ @pytest.mark.unit def test_native_packed_path_normalizes_diar_and_asr_independently_without_unpack( monkeypatch,@@ -2597,6 +2653,60 @@ def test_legacy_canonical_bundle_requires_explicit_speaker_contract(tmp_path): assert restored._bundle_config.sync_max_audio_length is False +@pytest.mark.unit+def test_bundle_override_selects_the_diarization_attention_backend(tmp_path):+ """``diar_packed_rel_pos_attention`` is a runtime override of a bundle: it selects the packed attention backend+ of the diarization ConformerEncoder, leaves the architecture and the strictly loaded weights as they are, and+ is the only accepted way to reach that setting (``diarization_model_cfg`` is not an override key)."""+ source = build_toy_pe_encoder().eval()+ state = {f"encoder.{key}": value for key, value in source.state_dict().items()}+ archive = tmp_path / "diar-backend.nemo"+ write_bundle(archive, bundle_config(), state)++ with pytest.raises(ValueError, match="Unsupported ParallelExpertEncoder config_overrides keys"):+ ParallelExpertEncoderPT.load_from_nemo(+ str(archive),+ strict=True,+ config_overrides={"diarization_model_cfg": {"encoder": {"packed_rel_pos_attention": "flex"}}},+ )+ with pytest.raises(ValueError, match="diar_packed_rel_pos_attention must be 'triton' or 'flex'"):+ ParallelExpertEncoderPT.load_from_nemo(+ str(archive), strict=True, config_overrides={"diar_packed_rel_pos_attention": "cuda"}+ )++ restored = ParallelExpertEncoderPT.load_from_nemo(+ str(archive), strict=True, config_overrides={"diar_packed_rel_pos_attention": "flex"}+ ).eval()+ assert restored.diarization_model.encoder.packed_rel_pos_attention == "flex"+ assert restored.asr_encoder.packed_rel_pos_attention == "triton"+ assert restored.diar_packed_rel_pos_attention == "flex"+ assert restored._bundle_config.diar_packed_rel_pos_attention == "flex"+ assert set(restored.state_dict()) == set(source.state_dict())+ for key, value in source.state_dict().items():+ torch.testing.assert_close(restored.state_dict()[key], value)+ # without the override the bundle keeps its config's backend+ plain = ParallelExpertEncoderPT.load_from_nemo(str(archive), strict=True)+ assert plain.diarization_model.encoder.packed_rel_pos_attention == "triton"+ assert plain.diar_packed_rel_pos_attention is None++ # the override names a ConformerEncoder setting: a Transformer diarization branch has none+ packed_source = build_toy_packed_pe_encoder().eval()+ packed_archive = tmp_path / "transformer-diar.nemo"+ write_bundle(+ packed_archive,+ bundle_config(+ asr_encoder_type="transformer",+ asr_encoder_cfg=toy_transformer_asr_encoder_cfg(),+ diarization_model_cfg=toy_packed_diarization_model_cfg(),+ ),+ {f"encoder.{key}": value for key, value in packed_source.state_dict().items()},+ )+ with pytest.raises(ValueError, match="ConformerEncoder diarization branch"):+ ParallelExpertEncoderPT.load_from_nemo(+ str(packed_archive), strict=True, config_overrides={"diar_packed_rel_pos_attention": "flex"}+ )++ @pytest.mark.unit def test_sync_max_audio_length_is_disabled_by_portable_config(): config = bundle_config(sync_max_audio_length=False)tests/collections/speechlm2/test_independent_dual_encoder.py5 + / 3 −
@@ -18,6 +18,7 @@ from nemo.collections.asr.modules.conformer_encoder import ConformerEncoder from nemo.collections.asr.modules.transformer_encoder import TransformerEncoder from nemo.collections.asr.parts.packed_sequence import pack_encoder_output+from nemo.collections.asr.parts.submodules import packed_attention as packed_attention_module from nemo.collections.speechlm2.modules.perception import IndependentDualEncoder @@ -111,10 +112,11 @@ def make_conformer_encoder(dropout_att: float) -> ConformerEncoder: @pytest.mark.gpu @pytest.mark.skipif(not torch.cuda.is_available(), reason="requires CUDA")-def test_independent_dual_encoder_keeps_the_padded_fallback_for_a_branch_without_native_packed_support():+def test_independent_dual_encoder_keeps_the_padded_fallback_for_a_branch_without_native_packed_support(monkeypatch): """A ConformerEncoder branch training with attention dropout over rel_pos attention has no native packed form- on CUDA (FlexAttention has no dropout): the dual encoder still constructs in training mode, runs that branch- padded and re-packs it, and the step completes forward and backward."""+ on CUDA without the Triton attention kernel (FlexAttention has no dropout): the dual encoder still constructs+ in training mode, runs that branch padded and re-packs it, and the step completes forward and backward."""+ monkeypatch.setattr(packed_attention_module, "TRITON_AVAILABLE", False) torch.manual_seed(7) asr = make_conformer_encoder(dropout_att=0.1) auxiliary = make_encoder(32)tests/collections/speechlm2/test_pretrained.py43 + / 0 −
@@ -21,6 +21,13 @@ from safetensors.torch import save_file from nemo.collections.speechlm2.parts import pretrained+from tests.collections.asr.test_parallel_expert_encoder import (+ _ASR_D_MODEL,+ _MEL_FEATURES,+ build_toy_pe_encoder,+ bundle_config,+ write_bundle,+) def test_setup_speech_encoder_hydrates_missing_config_without_weights():@@ -116,6 +123,42 @@ def test_setup_parallel_expert_encoder_maps_shared_chunk_size(chunk_size_seconds assert model.cfg.perception.preprocessor.normalize is None +def test_setup_parallel_expert_encoder_mounts_a_bundle_with_the_diarization_backend_override(tmp_path):+ """The recipe's ``pe_encoder_overrides.diar_packed_rel_pos_attention`` reaches the diarization encoder of a+ bundle mounted through ``pe_encoder_path``, with the bundle's weights loaded strictly."""+ source = build_toy_pe_encoder().eval()+ archive = tmp_path / "pee.nemo"+ write_bundle(archive, bundle_config(), {f"encoder.{key}": value for key, value in source.state_dict().items()})+ model = SimpleNamespace(+ cfg=DictConfig(+ {+ "pe_encoder_path": str(archive),+ "pe_encoder_overrides": {"diar_packed_rel_pos_attention": "flex"},+ "perception": {+ "preprocessor": {"features": _MEL_FEATURES, "normalize": "per_feature"},+ "modality_adapter": {"d_model": _ASR_D_MODEL},+ },+ }+ ),+ perception=SimpleNamespace(+ encoder=SimpleNamespace(d_model=_ASR_D_MODEL),+ modality_adapter=object(),+ proj=torch.nn.Linear(_ASR_D_MODEL, 8),+ preprocessor=SimpleNamespace(featurizer=SimpleNamespace(normalize="per_feature")),+ ),+ )++ pretrained.setup_parallel_expert_encoder(model)++ mounted = model.perception.encoder+ assert mounted.diarization_model.encoder.packed_rel_pos_attention == "flex"+ assert mounted.asr_encoder.packed_rel_pos_attention == "triton"+ assert set(mounted.state_dict()) == set(source.state_dict())+ for key, value in source.state_dict().items():+ torch.testing.assert_close(mounted.state_dict()[key], value)+ assert model.perception.preprocessor.featurizer.normalize is None++ def test_setup_parallel_expert_encoder_constructs_inline_export_architecture(): inline_config = {"target": "ParallelExpertEncoderPT", "asr_encoder_cfg": {}, "diarization_model_cfg": {}} pe_encoder = SimpleNamespace(tests/collections/speechlm2/test_salm_automodel_pee.py33 + / 0 −
@@ -42,6 +42,7 @@ from nemo.collections.speechlm2.data.salm_dataset import MultiSpeakerConfig, SALMMultiSpeakerProcessor from nemo.collections.speechlm2.models import SALMAutomodel from nemo.collections.speechlm2.modules.perception import AudioPerceptionModule, IdentityConnector+from nemo.core.utils.optional_libs import TRITON_AVAILABLE # Reuse the toy PE encoder (and its dimensions) defined for the standalone # ParallelExpertEncoder tests, so both suites share one dummy bundle definition.@@ -280,6 +281,38 @@ def test_salm_automodel_pee_training_step(model, dataset, prompt_formatter, trai assert results["loss"] > 0 +@requires_cuda+@pytest.mark.gpu+@pytest.mark.skipif(not TRITON_AVAILABLE, reason="the native packed rel_pos path with attention dropout needs Triton")+@pytest.mark.parametrize("dropout_att", [0.1, 1.0], ids=["partial_dropout", "full_dropout"])+def test_salm_automodel_pee_packed_training_step_with_attention_dropout(+ model, dataset, prompt_formatter, training_cutset_batch, monkeypatch, dropout_att+):+ """Packed encoder sequences train through the native packed FastConformer branch with attention dropout,+ at the boundary of the kernel's range as well: ``dropout_att: 1.0``, a valid ``nn.Dropout`` setting,+ drops every attention weight and still completes the loss, the backward and finite ASR gradients."""+ monkeypatch.setitem(model.cfg, "packed_encoder_sequences", True)+ asr_encoder = model.perception.encoder.asr_encoder+ for layer in asr_encoder.layers:+ monkeypatch.setattr(layer.self_attn, "dropout_rate", dropout_att)+ was_training = model.training+ model.train()+ try:+ assert asr_encoder.supports_sequence_packed_output+ training_cutset_batch = training_cutset_batch.map(+ lambda c: c.apply_prompt_format(prompt_formatter), apply_fn=None+ )+ batch = move_data_to_device(dataset[training_cutset_batch], device=model.device)+ results = model._training_step_batch(batch, batch_idx=0)+ assert torch.isfinite(results["loss"]) and results["loss"] > 0+ results["loss"].backward()+ grads = [parameter.grad for parameter in asr_encoder.parameters() if parameter.grad is not None]+ assert grads and all(torch.isfinite(grad).all() for grad in grads)+ finally:+ model.zero_grad(set_to_none=True)+ model.train(was_training)++ @requires_cuda @pytest.mark.gpu def test_salm_automodel_pee_validation_step(model, dataset, prompt_formatter, training_cutset_batch):