nemo_automodel.components.models.qwen3_8_flash_next.qsa
nemo_automodel.components.models.qwen3_8_flash_next.qsa
Qwen3.8-Flash-Next QSA routing, FlexAttention sparse GQA, and its PyTorch oracle.
The supplied Qwen3.8-Flash-Next reference is an inference implementation: its indexer returns integer top-k IDs and defines neither an auxiliary indexer loss nor a straight-through gradient. This module therefore freezes the indexer weights explicitly. Routing is still recomputed from the current hidden states on every forward, while gradients flow through the main attention Q/K/V path.
Module Contents
Classes
Functions
Data
_PYTORCH_ORACLE_QUERY_CHUNK_SIZE
API
Bases: Module
Frozen, hookable Qwen3.8-Flash-Next compressed-block indexer.
forward has no cache or mutable routing state and returns the complete
logical-ID tensor [B, S, indexer_budget + compress_ratio - 1]. A normal
PyTorch forward hook can therefore capture the exact routing artifact used
by the subsequent sparse attention.
The fused projection produces raw query/key layout
[B, S, (H_index + 1) * D_index]. Queries become
[B, S, H_index, D_index]. Raw keys become [B, S, 1, D_index] and
complete consecutive groups are averaged in FP32 into
[B, floor(S / c), 1, D_index] before K RMSNorm and group-start RoPE.
Select document-confined routes for one packed THD row.
Each document is unpacked into its own right-padded pseudo-batch row so the per-row selection runs unchanged: compression groups restart at every document start and visibility is bounded by the document length. Local per-document IDs are then offset by the document start and packed back into the flattened layout.
Parameters:
Packed decoder block input [1, T, hidden_size].
Document-relative rotary values [1, T, D_rope].
Strictly increasing boundaries [num_docs + 1]
starting at zero and ending at T.
Returns: torch.Tensor
int32 global flattened IDs “[1, T, token_budget +
Select document-confined routes for one rank’s packed query shard.
The frozen indexer needs no gradients, so raw index keys and rotary
values are gathered globally with plain collectives and every document
is compressed identically on all ranks. Documents intersecting the
local shard are scored one at a time with the existing per-row
selection; queries in the CP padding tail (beyond the final document
boundary) keep all -1 routes.
Parameters:
Local packed shard [1, S_local, hidden_size].
Local document-relative rotary values [1, S_local, D_rope].
Validated global boundaries [num_docs + 1].
Contiguous CP metadata for the packed global row.
Returns: torch.Tensor
int32 global flattened IDs “[1, S_local, token_budget +
Return selected logical token IDs for every physical query row.
Parameters:
Decoder block input [B, S, hidden_size].
Composed Qwen3.8-Flash-Next rotary values [B, S, D_rope] stored
as concatenated cosine/sine halves.
Optional binary right-tail mask [B, S].
Optional contiguous CP metadata. When present,
hidden_states and freqs_cis contain the local query
shard while raw logical lengths and selected IDs use global
sequence coordinates.
Optional packed-document boundaries [num_docs + 1]
for a THD batch of one row. Routes then stay confined to each
query’s document and use global flattened token IDs.
Returns: torch.Tensor
int32 logical IDs [B, S, token_budget + compress_ratio - 1].
Initialize frozen indexer parameters for scratch-model construction.
Evaluate one bounded-workspace chunk of the PyTorch QSA oracle.
grouped_query uses [B, Q, Hkv, G, D]; K/V remain
[B, S_global, Hkv, D] and IDs use [B, Q, K].
Parameters:
Local grouped queries [B, Q, Hkv, G, D].
Global keys [B, S_global, Hkv, D].
Global values [B, S_global, Hkv, D].
Global logical IDs [B, Q, K]; -1 marks
invalid fixed-width slots.
Score multiplier.
Returns: torch.Tensor
Chunk output [B, Q, Hq, D] in the query dtype.
Apply the Qwen3.8-Flash-Next attention RoPE to indexer states.
Parameters:
Index query or compressed-key states [B, N, H, D_index].
Model-composed rotary values [B, N, D_rope] laid out as
cat(cos[..., D_rope/2], sin[..., D_rope/2]). D_rope may be
smaller than D_index; the remaining index dimensions pass
through unchanged.
Returns: torch.Tensor
Rotated states in the same [B, N, H, D_index] layout and dtype.
Run the differentiable PyTorch QSA oracle without expanding K/V heads.
This implementation is retained for CPU execution and numerical parity.
CUDA training with backend.attn='flex' dispatches to FlexAttention
instead. The oracle uses a private fixed query chunk solely to bound
temporary gathered K/V storage; it has no public model configuration.
Parameters:
Main normalized/rotated local queries [B, S_query, Hq, D].
Main normalized/rotated global keys [B, S_global, Hkv, D].
Main global values [B, S_global, Hkv, D].
Indexer output [B, S_query, K]. IDs are global
logical positions in the same batch row; -1 marks fixed-width
padding.
Score multiplier, defaulting to 1 / sqrt(D).
Returns: torch.Tensor
Sparse attention output [B, S_query, Hq, D]. Rows with no selected
Dispatch QSA to FlexAttention on CUDA or the PyTorch oracle elsewhere.
CPU execution always uses the oracle so model construction, checkpoint inspection, and distributed CPU parity tests need no compiled kernels. CUDA execution is strict: unsupported backends or dtypes are reported rather than silently falling back to the gathered implementation.
Validate a non-packed right-tail mask and return logical lengths.
Parameters:
None or a binary tensor [B, S]. Each row must
be exactly 1 ** L + 0 ** (S - L); left/interior padding and
packed document-ID masks are rejected.
Expected batch dimension B.
Expected physical sequence dimension S.
Device on which to return the lengths.
Returns: torch.Tensor
Logical sequence lengths as int64 [B].
Score compressed blocks and expand gold QSA top-k IDs.
For query position t, only floor((t + 1) / compress_ratio) complete
blocks are visible. Each block score is
sum_h(relu(dot(q[t,h], k[block,0]))) / sqrt(D). The best
token_budget / compress_ratio blocks are expanded to token IDs, then
the 0—compress_ratio - 1 tokens in the current incomplete causal tail
are appended. Invalid slots are -1.
Parameters:
Normalized and rotated local index queries
[B, S_query, H_index, D_index].
FP32-mean-pooled, normalized, rotated index keys
[B, floor(S_global / compress_ratio), 1, D_index].
Right-padded logical lengths [B].
Maximum number of tokens contributed by complete blocks.
Number of consecutive tokens represented by one block.
Query rows scored together. This bounds the temporary FP32 score tensor without changing top-k semantics.
Global position represented by local query row
zero. It is zero without CP and cp_rank * S_query for the
contiguous CP layout.
Padded global physical sequence length. It defaults to the local query length for the non-CP path.
Returns: torch.Tensor
Global logical token IDs “[B, S_query, token_budget +