NVIDIA-NeMo/Speech · #16434
feat(asr): sequence-packed teacher forcing in the Transformer decoder
docs/source/asr/api.rst49 + / 0 −
@@ -92,6 +92,55 @@ Modules :members: +.. _sequence-packed-teacher-forcing:++Sequence-packed teacher forcing+~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~++``TransformerDecoderNM.forward_packed`` (``nemo.collections.asr.modules.transformer.transformer``) runs the Transformer decoder in teacher forcing over token-flat inputs:+the target ids of all sequences in one row, the encoder states of all sequences in one row, and the sequence boundaries as explicit metadata instead of masks.+No padded position is computed, so a batch of mixed lengths costs its valid tokens only.+The result equals the rows of the padded ``forward`` at the valid positions, in batch order.++.. code-block:: python++ import torch++ from nemo.collections.asr.parts.packed_sequence import pack_encoder_output+ from nemo.collections.asr.parts.submodules.packed_attention import PackedAttentionContext++ # encoder_states: (B, T, D) with encoder_lengths: (B,), for example from ConformerEncoder.forward;+ # ConformerEncoder.forward_sequence_packed returns the PackedEncoderActivations directly+ packed_encoder = pack_encoder_output(encoder_states, encoder_lengths)+ encoder_context = PackedAttentionContext(packed_encoder)++ # input_ids: (B, U) with input_lengths: (B,); the valid ids of all sequences, in batch order+ valid = torch.arange(input_ids.shape[1], device=input_ids.device)[None, :] < input_lengths[:, None]+ decoder_context = PackedAttentionContext.from_lengths(input_lengths)++ with torch.autocast("cuda", dtype=torch.bfloat16):+ hidden = decoder.forward_packed(input_ids[valid], decoder_context, packed_encoder.data, encoder_context)+ # hidden: (sum(input_lengths), D); the log probabilities follow as in the padded path++The attention of the packed path runs variable-length FlashAttention, which sets the requirements on CUDA:++* float16 or bfloat16 inputs, in training through ``torch.autocast``;+* a head width (``hidden_size / num_attention_heads``) of at most 256 and divisible by 8;+* a GPU of compute capability 8.0 (Ampere) or newer.++Other CUDA inputs, float32 among them, raise ``NotImplementedError`` instead of falling back to a slower path.+On the CPU the sequences are attended one at a time with dense attention in any dtype, which is the reference of the unit tests.++The packed path covers the training forward and backward and leaves out what the padded ``forward`` does beyond that:++* no incremental decoding: ``return_mems`` raises, the decoder memories of the generators are not formed;+* no attention scores: the ``return_xatt_scores`` output of the cross-attention sublayers is empty, the fused kernels do not form the weights;+* no adapters: a decoder block with an enabled adapter raises;+* the causal mask is the standard one, a ``diagonal`` other than 0 raises;+* learned positional encodings bound the sequence length by ``max_sequence_length`` as in the padded path;+* a sequence without encoder states gets a zero cross-attention context, where the padded ``forward`` attends uniformly over its masked frames.++ .. _rnn-encoder-api: .. autoclass:: nemo.collections.asr.modules.RNNEncodernemo/collections/asr/modules/transformer/transformer.py33 + / 0 −
@@ -25,6 +25,7 @@ from nemo.collections.asr.modules.transformer.transformer_encoders import TransformerEncoder from nemo.collections.asr.modules.transformer.transformer_modules import TransformerEmbedding from nemo.collections.asr.parts.submodules.multi_head_attention import RotaryPositionalEncoding+from nemo.collections.asr.parts.submodules.packed_attention import PackedAttentionContext from nemo.collections.asr.parts.utils import adapter_utils from nemo.collections.common.parts.utils import ModuleBlock, build_module from nemo.core.classes.common import typecheck@@ -288,6 +289,38 @@ def forward( decoder_hidden_states = torch.transpose(decoder_hidden_states, 0, 1) return decoder_hidden_states + def forward_packed(+ self,+ input_ids: torch.Tensor,+ decoder_context: PackedAttentionContext,+ encoder_states: torch.Tensor,+ encoder_context: PackedAttentionContext,+ ) -> torch.Tensor:+ """Decoder hidden states for token-flat input ids, see ``TransformerDecoder.forward_packed``.++ Args:+ input_ids: token ids of all sequences, shape ``(U_total,)``.+ decoder_context: boundaries and positions of the ids.+ encoder_states: packed encoder output, shape ``(T_total, hidden_size)``.+ encoder_context: boundaries of the encoder output.++ Returns:+ The decoder hidden states, shape ``(U_total, hidden_size)``.+ """+ if self.return_mems:+ raise NotImplementedError("forward_packed does not return the decoder memories of incremental decoding.")+ if (+ isinstance(self._embedding, TransformerEmbedding)+ and self._embedding.learn_positional_encodings+ and decoder_context.max_seqlen > self._embedding.max_sequence_length+ ):+ raise ValueError(+ f"Input sequence is longer than maximum allowed sequence length for positional encoding. "+ f"Got {decoder_context.max_seqlen} and {self._embedding.max_sequence_length}"+ )+ decoder_embeddings = self._embedding.forward_packed(input_ids, decoder_context.position_ids)+ return self._decoder.forward_packed(decoder_embeddings, decoder_context, encoder_states, encoder_context)+ @property def hidden_size(self): return self._hidden_sizenemo/collections/asr/modules/transformer/transformer_decoders.py91 + / 0 −
@@ -22,6 +22,7 @@ from nemo.collections.asr.modules.transformer.transformer_modules import MultiHeadAttention, PositionWiseFF from nemo.collections.asr.parts.submodules.adapters.attention_adapter_mixin import AttentionAdapterModuleMixin+from nemo.collections.asr.parts.submodules.packed_attention import PackedAttentionContext from nemo.collections.asr.parts.utils import adapter_utils from nemo.collections.common.parts import form_attention_mask from nemo.collections.common.parts.utils import ModuleBlock, build_module@@ -187,6 +188,61 @@ def forward(self, decoder_query, decoder_mask, decoder_keys, encoder_states, enc else: return self.forward_postln(decoder_query, decoder_mask, decoder_keys, encoder_states, encoder_mask) + def forward_packed(+ self,+ decoder_states: torch.Tensor,+ decoder_context: PackedAttentionContext,+ encoder_states: torch.Tensor,+ encoder_context: PackedAttentionContext,+ ) -> torch.Tensor:+ """The block over token-flat decoder states attending token-flat encoder states.++ See ``TransformerDecoder.forward_packed`` for the contract.++ Args:+ decoder_states: shape ``(U_total, hidden_size)``.+ decoder_context: boundaries and positions of the decoder tokens.+ encoder_states: shape ``(T_total, hidden_size)``, in the same sequence order.+ encoder_context: boundaries of the encoder tokens.++ Returns:+ The output states, shape ``(U_total, hidden_size)``.+ """+ if self.get_enabled_adapters():+ raise NotImplementedError("Enabled adapters are not supported in the sequence-packed decoder block.")+ # the residual adds are in place like in the padded blocks, which keeps the residual stream in the+ # autocast dtype from the first block on+ if self.pre_ln:+ residual = decoder_states+ normed = self.layer_norm_1(decoder_states)+ attended, _ = self.first_sub_layer.forward_packed(+ normed, normed, normed, decoder_context, decoder_context, causal=True+ )+ attended += residual+ residual = attended+ normed = self.layer_norm_2(attended)+ attended, _ = self.second_sub_layer.forward_packed(+ normed, encoder_states, encoder_states, decoder_context, encoder_context+ )+ attended += residual+ output_states = self.third_sub_layer(self.layer_norm_3(attended))+ output_states += attended+ return output_states++ attended, _ = self.first_sub_layer.forward_packed(+ decoder_states, decoder_states, decoder_states, decoder_context, decoder_context, causal=True+ )+ attended += decoder_states+ decoder_states = self.layer_norm_1(attended)+ attended, _ = self.second_sub_layer.forward_packed(+ decoder_states, encoder_states, encoder_states, decoder_context, encoder_context+ )+ attended += decoder_states+ decoder_states = self.layer_norm_2(attended)+ output_states = self.third_sub_layer(decoder_states)+ output_states += decoder_states+ return self.layer_norm_3(output_states)+ def get_accepted_adapter_types(self) -> Set[type]: types = super().get_accepted_adapter_types() @@ -336,6 +392,41 @@ def forward( else: return memory_states, xatt_scores_list + def forward_packed(+ self,+ decoder_states: torch.Tensor,+ decoder_context: PackedAttentionContext,+ encoder_states: torch.Tensor,+ encoder_context: PackedAttentionContext,+ ) -> torch.Tensor:+ """Teacher-forced decoding over sequence-packed inputs, the training-time counterpart of ``forward``.++ The decoder and encoder masks of ``forward`` are replaced by the two packings:+ no padded position is computed,+ self-attention is causal within every sequence (the mask of diagonal 0)+ and the cross-attention of a sequence sees only its own encoder states;+ a sequence without encoder states gets a zero cross-attention context,+ where ``forward`` attends uniformly over its masked frames.+ The cached memory lists of incremental decoding, the cross-attention scores and adapters+ are not provided in this form.++ Args:+ decoder_states: embedded decoder inputs of all sequences, shape ``(U_total, hidden_size)``.+ decoder_context: boundaries and positions of the decoder tokens.+ encoder_states: encoder outputs of all sequences, shape ``(T_total, hidden_size)``, in the same order.+ encoder_context: boundaries of the encoder tokens.++ Returns:+ The decoder hidden states, shape ``(U_total, hidden_size)``, after the final norm when configured.+ """+ if self.diagonal != 0:+ raise NotImplementedError("forward_packed implements the causal mask of diagonal 0.")+ for layer in self.layers:+ decoder_states = layer.forward_packed(decoder_states, decoder_context, encoder_states, encoder_context)+ if self.final_layer_norm is not None:+ decoder_states = self.final_layer_norm(decoder_states)+ return decoder_states+ def input_example(self, max_batch=1, max_dim=256): """ Generates input examples for tracing etc.nemo/collections/asr/modules/transformer/transformer_modules.py67 + / 0 −
@@ -21,7 +21,9 @@ import torch from torch import nn +from nemo.collections.asr.modules.transformer_encoder_utils import _apply_packed_rope from nemo.collections.asr.parts.submodules.multi_head_attention import RotaryPositionalEncoding+from nemo.collections.asr.parts.submodules.packed_attention import PackedAttentionContext, packed_cross_attention from nemo.collections.common.parts import form_attention_mask from nemo.collections.common.parts.utils import build_activation @@ -201,6 +203,24 @@ def forward(self, input_ids, token_type_ids=None, start_pos=0): return embeddings + def forward_packed(self, input_ids: torch.Tensor, position_ids: torch.Tensor) -> torch.Tensor:+ """Embed token-flat ids with explicit positions.++ Args:+ input_ids: ids of all sequences, shape ``(U_total,)``.+ position_ids: position of every id within its sequence, shape ``(U_total,)``.++ Returns:+ The embeddings, shape ``(U_total, hidden_size)``.+ """+ token_embeddings = self.token_embedding(input_ids)+ if self.embedding_scale is not None:+ token_embeddings = token_embeddings * self.embedding_scale+ embeddings = token_embeddings + self.position_embedding(position_ids)+ if self.layer_norm is not None:+ embeddings = self.layer_norm(embeddings)+ return self.dropout(embeddings)+ class MultiHeadAttention(nn.Module): """@@ -297,6 +317,53 @@ def forward(self, queries, keys, values, attention_mask): return output_states, extra_output + def forward_packed(+ self,+ queries: torch.Tensor,+ keys: torch.Tensor,+ values: torch.Tensor,+ query_context: PackedAttentionContext,+ key_context: PackedAttentionContext,+ *,+ causal: bool = False,+ ) -> tuple[torch.Tensor, dict]:+ """Attention over token-flat queries and keys with explicit sequence boundaries instead of masks.++ Args:+ queries: shape ``(Q_total, hidden_size)``.+ keys: shape ``(K_total, hidden_size)``, packed in the same sequence order as the queries.+ values: shape ``(K_total, hidden_size)``.+ query_context: boundaries and positions of the queries.+ key_context: boundaries and positions of the keys; self-attention passes the ``query_context`` object+ itself, which the rotary position embedding requires.+ causal: let every query see only the keys at its position or before (self-attention).++ Returns:+ The output states, shape ``(Q_total, hidden_size)``, and an empty ``extra_output``:+ the attention weights that the padded forward returns with ``return_xatt_scores``+ are not formed by the fused kernels.+ """+ heads, head_size = self.num_attention_heads, self.attn_head_size+ query = self.query_net(queries).view(-1, heads, head_size)+ key = self.key_net(keys).view(-1, heads, head_size)+ value = self.value_net(values).view(-1, heads, head_size)+ if self.rotary_pos_enc is not None:+ if query_context is not key_context:+ raise NotImplementedError("The rotary position embedding applies to self-attention only.")+ self.rotary_pos_enc.extend_pe(query_context.max_seqlen, key.device, key.dtype)+ query, key = _apply_packed_rope(self.rotary_pos_enc, query, key, query_context.position_ids)+ context = packed_cross_attention(+ query,+ key,+ value,+ query_context,+ key_context,+ causal=causal,+ dropout_p=self.attn_dropout.p if self.training else 0.0,+ )+ output_states = self.out_projection(context.reshape(-1, heads * head_size))+ return self.layer_dropout(output_states), {}+ class PositionWiseFF(nn.Module): """nemo/collections/asr/parts/submodules/packed_attention.py129 + / 2 −
@@ -13,7 +13,7 @@ # See the License for the specific language governing permissions and # limitations under the License. -"""Self-attention over sequence-packed activations with explicit per-utterance boundaries."""+"""Self- and cross-attention over sequence-packed activations with explicit per-sequence boundaries.""" import functools import math@@ -31,7 +31,13 @@ packed_sequence_ids, ) -__all__ = ["PackedAttentionContext", "document_block_mask", "packed_attention", "packed_attention_supports_dropout"]+__all__ = [+ "PackedAttentionContext",+ "document_block_mask",+ "packed_attention",+ "packed_attention_supports_dropout",+ "packed_cross_attention",+] # the sparse block size of FlexAttention; the document block mask is built at this granularity BLOCK_SIZE = 128@@ -275,6 +281,90 @@ def packed_attention_supports_dropout(device: torch.device, dtype: torch.dtype, return _get_flash_attention_varlen_for_device(device) is not None +def packed_cross_attention(+ q: Tensor,+ k: Tensor,+ v: Tensor,+ query_context: PackedAttentionContext,+ key_context: PackedAttentionContext,+ *,+ causal: bool = False,+ dropout_p: float = 0.0,+ scale: float | None = None,+) -> Tensor:+ """Attend from token-flat queries to the token-flat keys of the same sequence, without a position bias.++ On CUDA this runs variable-length FlashAttention and raises when that does not apply+ (float32, a head width above 256 or not divisible by 8, a GPU before Ampere):+ the dense attention below would be several times slower than the padded attention.+ On the CPU the sequences are attended one at a time with dense attention,+ which is also the reference of the unit tests.++ Args:+ q: queries, shape ``(Q_total, H, d_k)``.+ k: keys, shape ``(K_total, H, d_k)``, packed in the same sequence order as the queries.+ v: values, shape ``(K_total, H, d_k)``.+ query_context: packing metadata of the queries.+ key_context: packing metadata of the keys; the same object as ``query_context`` in self-attention.+ causal: let every query see only the keys at its position or before; needs equal query and key lengths.+ dropout_p: dropout on the attention weights, in ``[0, 1)``.+ scale: positive score scale, ``1 / sqrt(d_k)`` by default.++ Returns:+ Context vectors of shape ``(Q_total, H, d_k)``.++ Raises:+ ValueError: for inputs that do not match their contexts and for scalars outside their ranges,+ checked before the dispatch so that every backend rejects the same calls.+ NotImplementedError: on CUDA when variable-length FlashAttention does not apply.+ """+ if scale is None:+ scale = 1.0 / math.sqrt(q.shape[-1])+ if not 0.0 <= dropout_p < 1.0:+ raise ValueError(f"dropout_p must be in [0, 1), got {dropout_p}.")+ if not (math.isfinite(scale) and scale > 0.0):+ raise ValueError(f"scale must be positive, got {scale}.")+ if query_context.lengths.numel() != key_context.lengths.numel():+ raise ValueError("query_context and key_context must describe the same number of sequences.")+ if q.shape[0] != query_context.total_tokens:+ raise ValueError(f"q has {q.shape[0]} rows, query_context describes {query_context.total_tokens} tokens.")+ if k.shape[0] != key_context.total_tokens or v.shape[0] != key_context.total_tokens:+ raise ValueError(+ f"k and v have {k.shape[0]} and {v.shape[0]} rows, key_context describes {key_context.total_tokens} tokens."+ )+ if causal and query_context is not key_context and not torch.equal(query_context.lengths, key_context.lengths):+ raise ValueError("causal packed attention needs equal query and key lengths per sequence.")+ if query_context.total_tokens == 0 or key_context.total_tokens == 0:+ # empty-slice sums keep the gradient edges to q, k and v without summing the inputs,+ # which overflows in float16 and turns the zero anchor into NaN+ anchor = q[:0].sum() + k[:0].sum() + v[:0].sum()+ return q.new_zeros(q.shape) + anchor.to(q.dtype)+ if q.is_cuda:+ flash = _flash_attention_varlen(q)+ if flash is None:+ raise NotImplementedError(+ "packed cross attention on CUDA runs variable-length FlashAttention only, which needs float16 or "+ "bfloat16 (train under autocast), a head width of at most 256 and divisible by 8, and a GPU of "+ f"compute capability 8.0 or newer; got {q.dtype} with head width {q.shape[-1]} on "+ f"{torch.cuda.get_device_name(q.device)}."+ )+ return flash(+ q.contiguous(),+ k.contiguous(),+ v.contiguous(),+ query_context.cu_seqlens,+ key_context.cu_seqlens,+ query_context.max_seqlen,+ key_context.max_seqlen,+ dropout_p=dropout_p,+ softmax_scale=scale,+ causal=causal,+ )+ return _reference_packed_cross_attention(+ q, k, v, query_context, key_context, causal=causal, dropout_p=dropout_p, scale=scale+ )++ def _padded_size(value: int, floor: int) -> int: """Round ``value`` up to a power of two, at least ``floor`` (a power of two itself).""" return max(floor, 1 << max(value - 1, 0).bit_length())@@ -393,3 +483,40 @@ def _reference_packed_attention( weights = torch.nn.functional.dropout(weights, p=dropout_p, training=True) outputs.append(torch.matmul(weights, vi).transpose(0, 1)) return torch.cat(outputs, dim=0)+++def _reference_packed_cross_attention(+ q: Tensor,+ k: Tensor,+ v: Tensor,+ query_context: PackedAttentionContext,+ key_context: PackedAttentionContext,+ *,+ causal: bool,+ dropout_p: float,+ scale: float,+) -> Tensor:+ """Dense attention one sequence at a time from its queries to its keys."""+ outputs = []+ for (q_start, q_end), (k_start, k_end) in zip(query_context.sequence_slices, key_context.sequence_slices):+ if q_end == q_start:+ continue+ if k_end == k_start:+ # a zero context that keeps the gradient edges to q, k and v, like the empty-batch case+ anchor = q[:0].sum() + k[:0].sum() + v[:0].sum()+ outputs.append(q.new_zeros((q_end - q_start,) + tuple(q.shape[1:])) + anchor)+ continue+ qi = q[q_start:q_end].transpose(0, 1)+ ki = k[k_start:k_end].transpose(0, 1)+ vi = v[k_start:k_end].transpose(0, 1)+ # scaled before the product like the padded attention, so that half-precision scores stay finite+ root = math.sqrt(scale)+ scores = torch.matmul(qi * root, (ki * root).transpose(-2, -1))+ if causal:+ visible = torch.ones(q_end - q_start, k_end - k_start, dtype=torch.bool, device=q.device).tril()+ scores = scores.masked_fill(~visible, float("-inf"))+ weights = torch.softmax(scores, dim=-1)+ if dropout_p > 0.0:+ weights = torch.nn.functional.dropout(weights, p=dropout_p, training=True)+ outputs.append(torch.matmul(weights, vi).transpose(0, 1))+ return torch.cat(outputs, dim=0)tests/collections/asr/test_packed_attention.py158 + / 0 −
@@ -30,6 +30,7 @@ PackedAttentionContext, document_block_mask, packed_attention,+ packed_cross_attention, ) @@ -277,6 +278,163 @@ def test_flex_attention_matches_reference_on_cuda(self, lengths, head_dim): torch.testing.assert_close(grad, t.grad, atol=1e-3, rtol=1e-3) +def _cuda_param():+ """The CUDA case of a device parametrization, marked as a GPU test and skipped without a GPU."""+ return pytest.param(+ "cuda",+ marks=[pytest.mark.gpu, pytest.mark.skipif(not torch.cuda.is_available(), reason="requires CUDA")],+ )+++class TestPackedCrossAttention:+ """Attention from token-flat queries to the keys of their own sequence, through FlashAttention and the reference."""++ @pytest.mark.unit+ def test_rejects_inputs_that_do_not_match_their_contexts(self):+ queries = PackedAttentionContext.from_lengths(torch.tensor([3, 4]))+ keys = PackedAttentionContext.from_lengths(torch.tensor([5, 4]))+ q, k, v = torch.randn(7, 2, 8), torch.randn(9, 2, 8), torch.randn(9, 2, 8)+ with pytest.raises(ValueError, match="equal query and key lengths"):+ packed_cross_attention(q, k, v, queries, keys, causal=True)+ with pytest.raises(ValueError, match="rows"):+ packed_cross_attention(q[:5], k, v, queries, keys)+ with pytest.raises(ValueError, match="rows"):+ packed_cross_attention(q, k[:8], v, queries, keys)+ with pytest.raises(ValueError, match="number of sequences"):+ packed_cross_attention(q, k, v, queries, PackedAttentionContext.from_lengths(torch.tensor([9])))++ @pytest.mark.unit+ def test_half_precision_scores_stay_finite_on_the_dense_path(self):+ """Unscaled products of 64 times 40 squared overflow float16; the scaling happens before the product."""+ context = PackedAttentionContext.from_lengths(torch.tensor([2]))+ x = torch.full((2, 1, 64), 40.0, dtype=torch.float16)+ out = packed_cross_attention(x, x, x, context, context)+ assert torch.isfinite(out).all()+ torch.testing.assert_close(out, x)++ @pytest.mark.unit+ def test_queries_without_keys_keep_gradient_edges(self):+ """A sequence with queries and no keys gets a zero context that still connects q, k and v."""+ cases = [([1, 0], [0, 1], (1, 1, 8)), ([1, 1], [0, 0], (2, 1, 8)), ([0, 0], [1, 1], (0, 1, 8))]+ for query_lengths, key_lengths, out_shape in cases:+ query_context = PackedAttentionContext.from_lengths(torch.tensor(query_lengths))+ key_context = PackedAttentionContext.from_lengths(torch.tensor(key_lengths))+ q = torch.randn(query_context.total_tokens, 1, 8, requires_grad=True)+ k, v = (torch.randn(key_context.total_tokens, 1, 8, requires_grad=True) for _ in range(2))+ out = packed_cross_attention(q, k, v, query_context, key_context)+ assert out.shape == out_shape and not out.any()+ out.sum().backward()+ for tensor in (q, k, v):+ assert tensor.grad is not None and not tensor.grad.any()++ @pytest.mark.unit+ @pytest.mark.parametrize("device", ["cpu", _cuda_param()])+ def test_queries_without_keys_stay_finite_in_float16(self, device):+ """The sum of 2048 rows of ones overflows float16; the zero context must not become NaN through it."""+ query_context = PackedAttentionContext.from_lengths(torch.tensor([2048], device=device))+ key_context = PackedAttentionContext.from_lengths(torch.tensor([0], device=device))+ q = torch.ones((2048, 2, 64), dtype=torch.float16, device=device, requires_grad=True)+ k, v = (torch.zeros((0, 2, 64), dtype=torch.float16, device=device, requires_grad=True) for _ in range(2))+ out = packed_cross_attention(q, k, v, query_context, key_context)+ assert out.shape == q.shape and torch.isfinite(out).all() and not out.any()+ out.sum().backward()+ for tensor in (q, k, v):+ assert tensor.grad is not None and not tensor.grad.any()++ @pytest.mark.unit+ @pytest.mark.parametrize("device", ["cpu", _cuda_param()])+ def test_scalar_arguments_are_checked_before_the_dispatch(self, device):+ """The same ranges on both backends: dropout in [0, 1), a positive finite scale; the boundaries run."""+ dtype = torch.bfloat16 if device == "cuda" else torch.float32+ context = PackedAttentionContext.from_lengths(torch.tensor([5, 3], device=device))+ x = torch.randn(8, 2, 64, device=device, dtype=dtype)+ for dropout_p in (1.0, -0.1, float("nan")):+ with pytest.raises(ValueError, match="dropout_p"):+ packed_cross_attention(x, x, x, context, context, dropout_p=dropout_p)+ for scale in (-0.125, 0.0, float("nan"), float("inf")):+ with pytest.raises(ValueError, match="scale"):+ packed_cross_attention(x, x, x, context, context, scale=scale)+ if device == "cuda":+ self._skip_without_flash_attention(dtype)+ out = packed_cross_attention(x, x, x, context, context, dropout_p=0.0, scale=0.5)+ reference = packed_attention_module._reference_packed_cross_attention(+ x.float(), x.float(), x.float(), context, context, causal=False, dropout_p=0.0, scale=0.5+ )+ torch.testing.assert_close(out.float(), reference, atol=5e-2, rtol=5e-2)+ almost_all_dropped = packed_cross_attention(x, x, x, context, context, dropout_p=0.999)+ assert almost_all_dropped.shape == x.shape and torch.isfinite(almost_all_dropped).all()++ @pytest.mark.unit+ @pytest.mark.gpu+ @pytest.mark.skipif(not torch.cuda.is_available(), reason="requires CUDA")+ def test_rejects_cuda_inputs_outside_flash_attention(self):+ """No silent fall-back to the dense per-sequence attention on CUDA: float32 and an odd head width."""+ context = PackedAttentionContext.from_lengths(torch.tensor([3, 2], device="cuda"))+ x = torch.randn(context.total_tokens, 2, 64, device="cuda")+ with pytest.raises(NotImplementedError, match="FlashAttention only"):+ packed_cross_attention(x, x, x, context, context)+ narrow = torch.randn(context.total_tokens, 2, 12, device="cuda", dtype=torch.bfloat16)+ with pytest.raises(NotImplementedError, match="FlashAttention only"):+ packed_cross_attention(narrow, narrow, narrow, context, context)++ @staticmethod+ def _skip_without_flash_attention(dtype):+ if packed_attention_module._flash_attention_varlen(torch.empty(1, 1, 8, device="cuda", dtype=dtype)) is None:+ pytest.skip("requires a variable-length FlashAttention provider")++ @pytest.mark.unit+ @pytest.mark.gpu+ @pytest.mark.skipif(not torch.cuda.is_available(), reason="requires CUDA")+ @pytest.mark.parametrize(+ "dtype, tolerance",+ [(torch.float16, 1e-2), (torch.bfloat16, 5e-2)],+ ids=["fp16", "bf16"],+ )+ @pytest.mark.parametrize("causal", [False, True], ids=["cross", "causal"])+ def test_flash_matches_the_dense_reference(self, dtype, tolerance, causal):+ """Outputs and input gradients against the float32 reference; the lengths hold empty sequences."""+ self._skip_without_flash_attention(dtype)+ torch.manual_seed(0)+ query_context = PackedAttentionContext.from_lengths(torch.tensor([5, 0, 130, 3], device="cuda"))+ key_lengths = torch.tensor([9, 4, 0, 300], device="cuda")+ key_context = query_context if causal else PackedAttentionContext.from_lengths(key_lengths)+ heads, head_dim = 2, 64+ q = torch.randn(query_context.total_tokens, heads, head_dim, device="cuda", dtype=dtype)+ k, v = (torch.randn(key_context.total_tokens, heads, head_dim, device="cuda", dtype=dtype) for _ in range(2))+ upstream = torch.randn_like(q)++ def run(tensors, attention, **options):+ inputs = [t.detach().clone().requires_grad_() for t in tensors]+ out = attention(*inputs, query_context, key_context, causal=causal, **options)+ out.backward(upstream.to(out.dtype))+ return out.float(), [t.grad.float() for t in inputs]++ out, grads = run((q, k, v), packed_cross_attention)+ reference, reference_grads = run(+ (q.float(), k.float(), v.float()),+ packed_attention_module._reference_packed_cross_attention,+ dropout_p=0.0,+ scale=head_dim**-0.5,+ )+ torch.testing.assert_close(out, reference, atol=tolerance, rtol=tolerance)+ for grad, reference_grad in zip(grads, reference_grads):+ torch.testing.assert_close(grad, reference_grad, atol=tolerance, rtol=tolerance)++ @pytest.mark.unit+ @pytest.mark.gpu+ @pytest.mark.skipif(not torch.cuda.is_available(), reason="requires CUDA")+ def test_dropout_reaches_the_kernel(self):+ self._skip_without_flash_attention(torch.bfloat16)+ torch.manual_seed(0)+ context = PackedAttentionContext.from_lengths(torch.tensor([40, 25], device="cuda"))+ q, k, v = (torch.randn(context.total_tokens, 2, 64, device="cuda", dtype=torch.bfloat16) for _ in range(3))+ without = [packed_cross_attention(q, k, v, context, context) for _ in range(2)]+ with_dropout = [packed_cross_attention(q, k, v, context, context, dropout_p=0.5) for _ in range(2)]+ torch.testing.assert_close(without[0], without[1])+ assert not torch.allclose(with_dropout[0], with_dropout[1])+ assert not torch.allclose(with_dropout[0], without[0])++ @pytest.mark.gpu @pytest.mark.skipif(not torch.cuda.is_available(), reason="requires CUDA") class TestPackedAttentionBackends:tests/collections/asr/test_transformer_decoder.py163 + / 0 −
@@ -32,6 +32,8 @@ TransformerEmbedding, ) from nemo.collections.asr.modules.transformer.transformer_utils import get_nemo_transformer+from nemo.collections.asr.parts.packed_sequence import pack_encoder_output+from nemo.collections.asr.parts.submodules.packed_attention import PackedAttentionContext def _composed_decoder(**overrides):@@ -246,3 +248,164 @@ def test_defaults_unchanged(self): isinstance(decoder.embedding.layer_norm, torch.nn.LayerNorm) and decoder.embedding.embedding_scale is None ) assert decoder.decoder.final_layer_norm is None+++def _packed_inputs(input_ids, input_lengths, encoder_states, encoder_lengths):+ """Token-flat ids and encoder states with their packing metadata, in batch order."""+ valid = torch.arange(input_ids.shape[1], device=input_ids.device)[None, :] < input_lengths[:, None]+ packed_encoder = pack_encoder_output(encoder_states, encoder_lengths)+ return (+ input_ids[valid],+ PackedAttentionContext.from_lengths(input_lengths),+ packed_encoder.data,+ PackedAttentionContext(packed_encoder),+ )+++def _valid_rows(padded, lengths):+ return padded[torch.arange(padded.shape[1], device=padded.device)[None, :] < lengths[:, None]]+++class TestPackedTransformerDecoder:+ """Sequence-packed teacher forcing against the padded forward: outputs at valid positions and gradients."""++ @pytest.mark.unit+ @pytest.mark.parametrize("pre_ln", [True, False])+ def test_matches_padded_forward(self, pre_ln):+ torch.manual_seed(0)+ if pre_ln:+ decoder = _composed_decoder().double()+ else:+ options = dict(vocab_size=11, hidden_size=16, num_layers=2, inner_size=24, num_attention_heads=2)+ decoder = TransformerDecoderNM(num_token_types=0, **options).double().eval()+ for parameter in decoder.parameters():+ parameter.data.normal_(0, 0.3)+ input_ids = torch.tensor([[10, 1, 5, 7, 2], [10, 3, 4, 0, 0], [10, 6, 0, 0, 0]])+ input_lengths = torch.tensor([5, 3, 2])+ encoder_lengths = torch.tensor([9, 4, 7])+ encoder_states = torch.randn(3, 9, 16, dtype=torch.float64, requires_grad=True)+ decoder_mask = (torch.arange(5)[None, :] < input_lengths[:, None]).to(torch.int64)+ encoder_mask = (torch.arange(9)[None, :] < encoder_lengths[:, None]).to(torch.int64)++ padded = decoder(+ input_ids=input_ids,+ decoder_mask=decoder_mask,+ encoder_embeddings=encoder_states,+ encoder_mask=encoder_mask,+ )+ packed_encoder_states = encoder_states.detach().clone().requires_grad_()+ ids, decoder_context, states, encoder_context = _packed_inputs(+ input_ids, input_lengths, packed_encoder_states, encoder_lengths+ )+ packed = decoder.forward_packed(ids, decoder_context, states, encoder_context)++ torch.testing.assert_close(packed, _valid_rows(padded, input_lengths))+ _valid_rows(padded, input_lengths).square().sum().backward()+ reference_grads = {name: p.grad.clone() for name, p in decoder.named_parameters() if p.grad is not None}+ decoder.zero_grad()+ packed.square().sum().backward()+ torch.testing.assert_close(+ _valid_rows(packed_encoder_states.grad, encoder_lengths), _valid_rows(encoder_states.grad, encoder_lengths)+ )+ for name, parameter in decoder.named_parameters():+ if name in reference_grads:+ torch.testing.assert_close(parameter.grad, reference_grads[name], msg=name)++ @pytest.mark.unit+ def test_half_precision_attention_matches_padded_on_cpu(self):+ """Rows of 40 through identity projections: the padded attention pre-scales, the packed one must stay finite too."""+ attention = MultiHeadAttention(64, 1, use_bias=False).half().eval()+ for net in (attention.query_net, attention.key_net, attention.value_net, attention.out_projection):+ net.weight.data.copy_(torch.eye(64, dtype=torch.float16))+ x = torch.full((1, 2, 64), 40.0, dtype=torch.float16)+ padded, _ = attention(x, x, x, None)+ context = PackedAttentionContext.from_lengths(torch.tensor([2]))+ packed, _ = attention.forward_packed(x[0], x[0], x[0], context, context)+ assert torch.isfinite(packed).all()+ torch.testing.assert_close(packed, padded[0])++ @pytest.mark.unit+ def test_rejects_sequences_beyond_the_learned_positions(self):+ decoder = _composed_decoder(max_sequence_length=4, learn_positional_encodings=True)+ ids, decoder_context, states, encoder_context = _packed_inputs(+ torch.tensor([[10, 1, 5, 7, 2]]), torch.tensor([5]), torch.randn(1, 3, 16), torch.tensor([3])+ )+ with pytest.raises(ValueError, match="longer than maximum"):+ decoder.forward_packed(ids, decoder_context, states, encoder_context)++ @pytest.mark.unit+ def test_rejects_other_diagonals_and_memories(self):+ decoder = _composed_decoder()+ ids, decoder_context, states, encoder_context = _packed_inputs(+ torch.tensor([[10, 1]]), torch.tensor([2]), torch.randn(1, 3, 16), torch.tensor([3])+ )+ decoder.decoder.diagonal = 1+ with pytest.raises(NotImplementedError, match="diagonal"):+ decoder.forward_packed(ids, decoder_context, states, encoder_context)+ decoder.decoder.diagonal = 0+ decoder.return_mems = True+ with pytest.raises(NotImplementedError, match="memories"):+ decoder.forward_packed(ids, decoder_context, states, encoder_context)++ @pytest.mark.unit+ @pytest.mark.gpu+ @pytest.mark.skipif(not torch.cuda.is_available(), reason="requires CUDA")+ @pytest.mark.parametrize("pre_ln", [True, False])+ def test_bf16_training_step_matches_padded_on_cuda(self, pre_ln):+ """Forward and backward under bfloat16 autocast through the projections, residual adds and norms.++ Both paths run in eval mode, so that dropout does not separate them, with a shared random upstream gradient.+ Gradients are compared by L2 norm: a relative part for the bfloat16 noise of two kernel orders and an absolute+ floor from the largest parameter gradient, since a key bias cancels in the softmax and its gradient is noise+ around zero on both paths.+ """+ torch.manual_seed(1)+ sizes = dict(vocab_size=11, hidden_size=64, num_layers=2, inner_size=96, num_attention_heads=2)+ if pre_ln:+ decoder = _composed_decoder(**sizes).cuda()+ else:+ decoder = TransformerDecoderNM(num_token_types=0, **sizes).cuda().eval()+ for parameter in decoder.parameters():+ parameter.data.normal_(0, 0.1)+ input_ids = torch.randint(1, 11, (3, 30), device="cuda")+ input_lengths = torch.tensor([30, 17, 2], device="cuda")+ encoder_lengths = torch.tensor([200, 45, 130], device="cuda")+ encoder_states = torch.randn(3, 200, 64, device="cuda", requires_grad=True)+ decoder_mask = (torch.arange(30, device="cuda")[None, :] < input_lengths[:, None]).to(torch.int64)+ encoder_mask = (torch.arange(200, device="cuda")[None, :] < encoder_lengths[:, None]).to(torch.int64)+ upstream = torch.randn(int(input_lengths.sum()), 64, device="cuda")++ with torch.autocast("cuda", dtype=torch.bfloat16):+ padded = decoder(+ input_ids=input_ids,+ decoder_mask=decoder_mask,+ encoder_embeddings=encoder_states,+ encoder_mask=encoder_mask,+ )+ padded = _valid_rows(padded, input_lengths)+ (padded.float() * upstream).sum().backward()+ reference_grads = {name: p.grad.clone() for name, p in decoder.named_parameters() if p.grad is not None}+ reference_encoder_grad = _valid_rows(encoder_states.grad, encoder_lengths).clone()+ decoder.zero_grad()+ encoder_states.grad = None++ with torch.autocast("cuda", dtype=torch.bfloat16):+ packed = decoder.forward_packed(*_packed_inputs(input_ids, input_lengths, encoder_states, encoder_lengths))+ (packed.float() * upstream).sum().backward()++ torch.testing.assert_close(packed.float(), padded.float(), atol=5e-2, rtol=5e-2)+ encoder_grad = _valid_rows(encoder_states.grad, encoder_lengths)+ assert (encoder_grad - reference_encoder_grad).norm() <= 5e-2 * reference_encoder_grad.norm()+ largest = max(grad.norm() for grad in reference_grads.values())+ for name, parameter in decoder.named_parameters():+ if name not in reference_grads:+ continue+ assert parameter.grad is not None, name+ reference = reference_grads[name]+ difference = (parameter.grad.float() - reference.float()).norm()+ assert difference <= 0.15 * reference.norm() + 0.02 * largest, (+ name,+ difference,+ reference.norm(),+ largest,+ )