nemo_automodel.components.models.hy_v4_flash.attention
nemo_automodel.components.models.hy_v4_flash.attention
Gated MLA with learnable sinks for Hy4-flash: sliding-window and compressed-indexer sparse layers.
Both layer types run the same absorbed latent attention: the per-head key up-projection is folded into the query,
every head attends over one shared [kv_lora_rank + rope] latent per token, and the value up-projection is
applied to the output. This equals the reference’s expanded attention and is what the shared sparse kernel
(models/common/cudnn_sparse_attention) consumes, with per-document index lists:
sliding_attention: the lastsliding_windowtokens of the query’s document.indexed_attention: dense causal attention while a document is not longer thanindex_topk; otherwise theindex_topk // index_kpool - 1best-scoring complete groups plus the query’s own group.
Indices only ever point into the query’s own document, and groups are document-local.
Module Contents
Classes
Functions
API
Bases: Module
Gated MLA of one decoder layer (attention_type selects heads, indices and rotary theta).
Per-head key / value up-projections of kv_b_proj as [heads, dim, latent] tensors.
Evaluating the module on an identity keeps the result differentiable through LoRA adapters and valid
when FSDP shards kv_b_proj (a direct .weight read would see the sharded DTensor).
Raises:
RuntimeError: Ifkv_b_projcarries a LoRA adapter with active training dropout. One absorbed weight cannot represent per-token dropout.
Run the sparse latent attention kernel (or its PyTorch twin).
Parameters:
Tensor of shape [queries, heads, kv_lora_rank + rope_dim].
Tensor of shape [keys, kv_lora_rank + rope_dim].
Key lists of the queries (indices [queries, width] into kv rows, lengths [queries]).
fp32 tensor of shape [heads], the learned sink logits.
Supplies the padding-row metadata the kernel’s backward needs.
Returns: torch.Tensor
Tensor of shape [queries, heads, kv_lora_rank]; zero for queries without keys.
Return the latent keys (and index token keys) over the global sequence.
Under context parallelism only the latent keys kv_local [local_tokens, kv_lora_rank + rope_dim]
(differentiable: backward reduce-scatters their gradients to the owning rank) and the index token_keys
[local_tokens, index_head_dim] (no gradient) travel, not the hidden states.
Key lists of a sparse layer: dense for short documents, the indexer’s selection for long ones.
q_resid [local_tokens, q_lora_rank] and hidden_states [local_tokens, hidden] are this rank’s queries;
token_keys [global_tokens, index_head_dim] are the normalized index keys. The plan holds global key rows.
Attend within documents.
hidden_states [1, local_tokens, hidden] is the local interval of the packed row; rope holds this layer
type’s tables over the global sequence. The result has the same shape; positions outside every document are
zero.
Initialize as the reference does: normal projections, constant sinks, unit norm weights, then the indexer.
Accept the context-parallel mesh from the shared parallelizer without storing it.
The parallelizer offers the mesh to sliding-window blocks only, so a group stored here would be missing on
the sparse layers. Every layer instead reads the group from the forward’s HYV4FlashDocLayout.cp_group
(keys are gathered over it, queries stay local).
Bases: Module
Group-pooled lightning indexer. Selection is discrete, so the indexer receives no loss gradient.
Token keys are pooled index_kpool at a time through a softmax over fp32 value / gate projections
(key_value_projection / key_gate_projection biased by intra_group_ape), normalized, and rotated
with the sparse layer’s RoPE at the first token of each group. Queries come from the attention’s
q_a_layernorm output.
Enter the fp32 pooling modules once with an empty input.
Pooling runs only for documents longer than index_topk, so how often (and whether) a rank calls these
modules depends on its data. Under FSDP each call of a sharded unit is a collective (all-gather), and ranks
that issue different collective sequences deadlock. Entering the units here, unconditionally and in the same
order on every rank, makes that sequence data independent; later calls find the parameters unsharded.
Parameters:
Any tensor on the compute device (its values are unused).
Pool one document’s token keys into complete-group keys.
Parameters:
Tensor of shape [document_tokens, index_head_dim].
Returns: torch.Tensor
Tensor of shape [document_tokens // index_kpool, index_head_dim] (a trailing partial group has no key).
Initialize as the reference does: normal projections and pooling bias, unit norm weights.
Select the document-local tokens every query of one contiguous query interval attends to.
A query recalls the index_topk // index_kpool - 1 best-scoring groups that closed before its own group
(ties towards the earlier group), plus its own group up to itself. The fp32 [queries, heads, groups]
scores are materialized a chunk of queries at a time, within score_block_bytes.
Parameters:
Tensor of shape [queries, q_lora_rank]; consecutive tokens of one document.
Tensor of shape [queries, hidden].
Tables of shape [queries, rope_dim // 2] at the queries’ positions.
Tensor of shape [groups, index_head_dim], unrotated pooled keys of the document’s leading complete groups; must cover every group that closes before the last query’s group.
Tables of shape [groups, rope_dim // 2] at the first token of each group.
Document-local token index of the first query.
Returns: HYV4FlashSparsePlan
Plan with indices [queries, index_topk] of document-local token indices and lengths [queries].
Normalized per-token index keys.
Parameters:
Tensor of shape [tokens, hidden].
Returns: torch.Tensor
Tensor of shape [tokens, index_head_dim].
Document boundaries and layer-independent key lists of one packed row, built once per forward pass.
Whether this rank holds no padding token (every query has at least its own key).
Context-parallel group whose ranks hold the consecutive shards of the global sequence, or None
when this rank holds all of it. Every layer gathers its keys over this group.
Key lists of every sparse layer before selection (width index_topk): exact for documents
not longer than index_topk; rows of longer documents are replaced by the indexer’s selection.
(start, end) token intervals of the real documents in the global sequence
(end exclusive); padding is not listed.
One past the last global token held by this rank.
First global token held by this rank (0 without context parallelism).
Int64 tensor of shape [valid_local_tokens] of the non-padding local queries, or None when
all_rows_nonempty.
Key lists of every sliding-window layer (width sliding_window).
Interleaved M-RoPE tables of one attention type over the global sequence.
Tensor of shape [global_tokens, rope_dim // 2].
Tensor of shape [global_tokens, rope_dim // 2].
Kernel-ready key lists of this rank’s queries.
Int32 tensor of shape [local_tokens, width] of global key rows: an ascending valid prefix followed
by -1.
Int32 tensor of shape [local_tokens], the valid-prefix length of each query (0 for padding).
Keys of the last width tokens (including the query) of each query, inside its document.
This is the whole key list of a sliding-window layer (width = sliding_window) and of a sparse layer for
documents not longer than index_topk (width = index_topk, i.e. dense causal attention).
Parameters:
Integer tensor of shape [queries], global token index of each query.
Integer tensor of shape [queries], global index of each query’s document start
(position + 1 for padding, which leaves the query without keys).
Maximum number of keys per query.
Returns: HYV4FlashSparsePlan
The plan, with indices of shape [queries, width] and lengths of shape [queries].
PyTorch implementation of the shared sparse latent attention kernel (CPU/CUDA, any dtype).
Parameters:
Tensor of shape [queries, heads, latent_dim + rope_dim].
Tensor of shape [keys, latent_dim + rope_dim], shared by all heads.
Integer tensor of shape [queries, width] into kv rows, -1 marking unused slots.
fp32 tensor of shape [heads], learned sink logits (scaled-logit space).
Softmax scale applied to q . k.
Leading channels of kv used as the value (the latent width).
Queries processed at a time.
Returns: torch.Tensor
Tensor of shape [queries, heads, value_dim] in the dtype of q.