nemo_automodel.components.models.deepseek_v41.attention
nemo_automodel.components.models.deepseek_v41.attention
Differentiable CSA2 attention from the official DeepSeek V4.1 inference model.
Full layers publish compressed KV, index keys, and selected positions. Reindex layers replace only the selection; Reuse layers consume it unchanged. Immutable per-forward state keeps source gradients intact through activation recomputation. Weights are dequantized for training while the released FP8 window KV and FP4 compressed KV/indexer representations retain their quantize/dequantize boundaries. The released indexer weights are frozen because the hard top-k operation provides no language-model gradient and the inference release does not implement indexer distillation.
Module Contents
Classes
Functions
API
Bases: Module
Full-sequence CSA2 with local KV, shared compressed KV, and an attention sink.
The training implementation supports eager, SDPA and TileLang attention with torch linear layers and eager FP32 or TE RMSNorm. Left padding, KV-cache decoding and tensor sharding remain unsupported. Context parallelism keeps contiguous local queries and exchanges window KV and shared compressed KV. Every local sequence must contain complete compression groups.
Return the checkpoint’s per-head FP32 attention sink parameter.
Undo RoPE on [batch, sequence, heads, head_dim] and project to hidden width.
angles has shape [batch, sequence, rotary_pairs]; valid_tokens
is boolean [batch, sequence]. Return [batch, sequence, hidden] with
padded queries zeroed, preserving the attention output dtype.
Apply attention and publish immutable state for the next layer.
Parameters:
Tensor of shape [batch, sequence, hidden].
Integer tensor of shape [batch, sequence] or [1, sequence], containing contiguous global positions for unpacked input and document-local positions for packed input.
Optional document IDs [batch, local_sequence], zero for padding. Document starts must be aligned to compression-group boundaries.
Per-forward tensors documented in DeepseekV41AttentionState. Consumers must receive the state from their preceding layer.
Optional binary right-padding mask of shape [batch, local_sequence], with one for tokens and zero for padding.
Optional CP group, overriding setup_cp_attention. Hidden states and positions are local shards; shared KV state is global.
Returns: DeepseekV41AttentionOutput
Output with hidden_states [batch, sequence, hidden] and the new state,
Initialize every attention parameter after construction or meta materialization.
Parameters:
Standard deviation of projection weights.
Configure the model-owned KV transport through the shared CP hook.
Attention result and the shared state for the next layer.
CSA2 state owned by one full-sequence model forward.
Under CP, compressed and index-key axes span the global sequence while sequence axes in topk_indices and candidates contain only local queries.
Tensor fields retain autograd history and are never modified by consumers. A model creates an empty state for every forward, including every microbatch.
Bases: Module
Non-overlapping channelwise softmax pooling; ratio one is a projection.
Return complete compressed groups before rotary embedding.
Parameters:
Tensor of shape [batch, sequence, hidden].
Returns: torch.Tensor
Tensor of shape [batch, floor(sequence / ratio), head_dim] in the
Bases: Linear
Keep pooling weights in FP32 while selecting compute from the input dtype.
Project […, input] into […, output] with the input’s compute dtype.
Bases: Module
Frozen released CSA2 indexer with shared keys and hierarchical selection.
Run selection on each document’s own key interval.
topk tie-breaking depends on the physical row width. Selecting over an entire pack, even with other documents masked out, can therefore change a document’s attention. Local intervals also reset candidate blocks at document boundaries.
Parameters:
Causal, document-masked scores [batch, local_sequence, global_compressed].
Document IDs [batch, local_sequence], zero for padding.
Global compressed metadata and keys described by DeepseekV41AttentionState.
Returns: DeepseekV41AttentionState
Immutable state with global-key topk indices [batch, local_sequence, topk]
Produce index keys when owned, then replace the current selection.
Parameters:
Tensor of shape [batch, sequence, hidden].
Tensor of shape [batch, sequence, q_lora_rank].
Optional unrotated KV of shape [batch, compressed, head_dim].
FP32 rotary angles of shape [batch, sequence, rotary_pairs].
FP32 angles of shape [batch, compressed, rotary_pairs].
Shared tensors with layouts in DeepseekV41AttentionState.
Optional physical global positions [batch, local_sequence].
Optional document IDs [batch, local_sequence], zero for padding.
Optional CP group; latent and compressed_angles contain local complete groups, while state index keys span all ranks.
Returns: DeepseekV41AttentionState
New state with index_keys [batch, compressed, index_head_dim],
Bases: Module
Adjacent-pair RoPE with the official frequency-only YaRN adjustment.
Construct FP32 phase angles without a cast-sensitive frequency buffer.
Parameters:
Integer tensor of shape [batch, sequence].
Returns: torch.Tensor
FP32 angles of shape [batch, sequence, rotary_pairs], where
Rotate the final channels without changing the input storage.
Parameters:
Tensor of shape [batch, sequence, channels] or [batch, sequence, heads, channels].
FP32 tensor of shape [batch, sequence, rotary_pairs]. The last 2 * rotary_pairs channels of values use adjacent-pair rotation.
Conjugate the rotation for the attention output.
Returns: torch.Tensor
Tensor with the shape and dtype of values, in independent storage.
Keep high-scoring blocks and always retain the latest visible block.
Parameters:
Causally masked scores of shape [batch, sequence, compressed].
Integer tensor of shape [batch, sequence, 1] counting visible compressed positions for each query.
Maximum retained blocks per query.
Compressed positions per block.
Returns: torch.Tensor
Boolean candidate mask of shape [batch, sequence, compressed].