nemo_automodel.components.models.qwen3_8_flash_next.layers
nemo_automodel.components.models.qwen3_8_flash_next.layers
Qwen3.8-Flash-Next model-local layers.
The HyperConnection equations in this module follow the Qwen3.8-Flash-Next reference implementation. They are intentionally not shared with DeepSeek-V4: that model uses a different Sinkhorn-based HyperConnection parameterization.
Module Contents
Classes
Functions
Data
_grouped_rms_norm_fp32_compiled
API
Bases: Module
One Qwen3.8-Flash-Next decoder layer with two learned HyperConnections.
Tensor layout
The first layer accepts token embeddings [batch, sequence, hidden]
and expands them to flattened HC state
[batch, sequence, hc_count * hidden]. Every layer returns that
flattened HC layout.
Parameters:
Zero-based decoder index.
Qwen3.8-Flash-Next text configuration.
Native MoE configuration.
Attention, linear, and expert backend configuration.
Optional Engram-derived PLE module. The checkpoint installs it only on decoder index 1.
Expand a one-stream decoder input into the persistent HC layout.
Parameters:
Tensor of shape [batch, sequence, hidden_size]
or [batch, sequence, hc_count * hidden_size].
Returns: torch.Tensor
Tensor of shape
Return packed segment IDs for PLE, or None for an unpacked batch.
Parameters:
Local raw IDs of shape [batch, sequence].
Optional contiguous CP metadata. Its global_cu_seqlens
bound the full, unsharded packed row.
Non-CP boundaries [segments + 1] of the local packed row,
built from the loader seq_lens, if any.
Returns: torch.Tensor | None
Segment IDs [1, sequence], or [1, global_sequence] under CP: one per
Run PLE, attention/GDN, and top-10 MoE updates.
Parameters:
One-stream input [batch, sequence, hidden] on
the first layer, otherwise flattened HC streams
[batch, sequence, hc_count * hidden].
Raw tokenizer IDs of shape [batch, sequence] used by
the PLE hash path.
Composed rotary values [batch, sequence, rotary_dim]
whose final axis stores concatenated cosine and sine values.
Optional token mask of shape [batch, sequence]
or backend-specific causal attention mask.
Optional [batch, sequence] mask where True
marks padding for MoE dispatch.
Optional positions of shape [batch, sequence] or
[axes, batch, sequence].
Optional contiguous CP metadata. Tensor-bearing fields
contain replicated global raw IDs/padding of shape [batch, global_sequence] and identify this rank’s local interval.
Attention backend metadata.
Returns: torch.Tensor
Flattened HC streams of shape
Initialize this decoder layer for training from scratch.
Parameters:
Device used by attention/MoE initializers.
Standard deviation for dense projection weights.
Extend the activation-checkpoint contexts of this block with QSA route replay.
The MoE parallelizer calls this model-owned hook when it wraps the block in a checkpoint wrapper. QSA layers record the frozen indexer’s routes during the checkpoint forward and replay them during recompute; GatedDeltaNet layers, or a config that disables reuse, return the incoming contexts unchanged.
Parameters:
The parallelizer’s torch.utils.checkpoint context factory, or
None.
Returns: Callable[[], tuple[AbstractContextManager, AbstractContextManager]] | None
The (possibly wrapped) context factory.
Bases: CPAwareGatedDeltaNet
CP-aware GatedDeltaNet with Qwen3.8-Flash-Next’s sigmoid output gate.
Run the inherited FLA CP core in explicit contiguous sequence order.
Parameters:
Local contiguous states of shape [batch, local_sequence, hidden]. Rank r owns global positions
[r * local_sequence, (r + 1) * local_sequence).
Local global positions of shape [batch, local_sequence] or repeated text-RoPE axes of shape [axes, batch, local_sequence].
Optional local positions of shape [local_sequence]
or [batch, local_sequence]; ignored because Qwen3.8-Flash-Next’s
model-owned layout is always contiguous.
External packed CP metadata. Qwen3.8-Flash-Next builds its own state and rejects an externally supplied one.
Returns: torch.Tensor
Local GDN output of shape [batch, local_sequence, hidden] in
Route packed boundaries around the inherited non-CP varlen path.
Without CP, cu_seqlens flows to the inherited FLA varlen forward
unchanged. With an active CP mesh the boundaries describe the global
packed row, so they are stashed for _forward_with_cp and the
inherited dispatcher sees no cu_seqlens.
Parameters:
Tensor of shape [batch, sequence, hidden]. Packed non-CP inputs have one physical row; a padded tail must be its own segment.
Arguments with the tensor layouts documented by
CPAwareGatedDeltaNet.forward. cu_seqlens contains
document boundaries of shape [documents + 1], global under CP;
attention_mask has shape [batch, sequence], with document-ID
change points matching cu_seqlens. IDs and indices are
normalized to consecutive documents covering the full row.
Returns: torch.Tensor
Tensor of shape [batch, sequence, hidden].
Raises:
ValueError: If non-CP boundaries do not strictly partition one row or the supplied document mask disagrees with those boundaries.
Bases: Module
Gemma-style RMS normalization over fixed-width HyperConnection branches.
Tensor layout
Input and output have shape [..., hidden_size]. The learned weight
has shape [hidden_size] and is applied as 1 + weight.
Parameters:
Flattened feature width.
Number of features normalized together. A flattened input
of shape [..., hidden_size] is viewed as
[..., hidden_size // group_size, group_size].
Variance epsilon.
Normalize each branch independently.
Parameters:
Flattened branch states of shape
[..., hidden_size].
Returns: torch.Tensor
Normalized states of shape [..., hidden_size].
Reset the additive Gemma-style scale to zero.
Bases: Module
Qwen3.8-Flash-Next gated HyperConnection read/write transform.
A read normalizes hc_count streams independently, predicts a feature
gate, and averages the gated streams to one block input. A write predicts
one injection gate per stream and adds the block output back to every
stream. The final decoder mixer uses only the read side.
Tensor layout
Reads [..., hc_count * hidden_size] and returns
[..., hidden_size]. Writes a block tensor [..., hidden_size]
back to a residual tensor [..., hc_count * hidden_size].
Parameters:
Width of one HC stream.
Number of streams.
Bottleneck width used to predict read gates.
Variance epsilon for branch normalization.
Linear backend configuration.
Whether to instantiate the write-side injection weight.
Parameter dtype override. If omitted, the backend model dtype is resolved by the caller and should be passed explicitly.
Inject one block output into every HC stream.
Parameters:
Attention or MoE output of shape
[..., hidden_size].
Flattened pre-block streams and their normalized values,
each shaped [..., hc_count * hidden_size].
Returns: torch.Tensor
Updated flattened streams of shape
Initialize HC weights for training from scratch.
Parameters:
Standard deviation for all HC linear weights.
Collapse HC streams to the input of an attention or MoE block.
Parameters:
Flattened HC streams of shape
[..., hc_count * hidden_size].
Returns: torch.Tensor
A pair containing the mixed block input of shape
Residual tensors retained between a HyperConnection read and write.
Flattened HC streams of shape [..., hc_count * hidden_size].
Branch-normalized streams with the same shape.
Bases: Qwen3NextAttention
Qwen3.8-Flash-Next gated attention with compressed-block QSA routing.
The main query/key/value, output gate, and output projection retain the Qwen3-Next equations. A separate frozen indexer returns logical token IDs, then the model-owned QSA dispatcher evaluates only those IDs. CUDA BF16 training selects FlexAttention or SM90 CuTe through backend.attn; CPU and explicit reference backends use the PyTorch oracle. Main Q/K/V remain differentiable.
Run the frozen indexer, or replay its recorded routes during checkpoint recompute.
Parameters:
Block input of shape [batch, sequence, hidden_size].
Rotary values [batch, sequence, rotary_dim].
Optional binary right-tail mask [batch, sequence]; ignored
for packed rows.
Optional contiguous CP metadata.
Optional packed-document boundaries [num_docs + 1].
Returns: QSARouteSelection
The route IDs [batch, sequence, attention_width] and, on the CUDA flex path,
Select compressed blocks and run model-owned sparse GQA.
Parameters:
Block input of shape [batch, sequence, hidden_size].
Rotary values [batch, sequence, rotary_dim] whose
final axis stores concatenated cosine and sine values.
Optional token mask of shape [batch, sequence]
or backend-specific causal attention mask.
Optional contiguous CP metadata. When present, x
contains local queries while compressed/main K/V are gathered
to global rank order.
Backend attention metadata. Packed layouts provide
global document boundaries through cu_seqlens or
cp_context.
Returns: torch.Tensor
Attention output with the same shape as x.
Initialize attention and indexer weights.
Parameters:
Device retained for the common attention initializer contract.
Projection initialization standard deviation.
Install the contiguous CP mesh used for QSA K/V exchange.
Bases: Module
Qwen3.8-Flash-Next GDN output normalization with its checkpoint-selected gate.
Transformers’ Qwen3.5 GatedDeltaNet hard-codes a SiLU output gate. Qwen3.8-Flash-Next
keeps the same projections and delta-rule core but sets
output_gate_type='sigmoid'. Keeping this model-local module avoids
changing the shared Qwen3.5 execution contract.
Normalize in fp32, then apply the configured gate in fp32.
Parameters:
Tensor of shape [..., hidden_size] containing
GatedDeltaNet values.
Tensor of shape [..., hidden_size] containing the
elementwise output-gate logits.
Returns: torch.Tensor
Tensor of shape [..., hidden_size] in the input dtype.
Match the multiplicative RMSNorm checkpoint convention.
FP32 grouped RMSNorm as one fusable elementwise chain.
Bound the QSA route width and name the physical K/V extent for one forward.
Valid route IDs are contiguous and a causal row can never see more than the longest document (packed) or the whole sequence (dense), so the indexer’s fixed-width output can be trimmed without changing attention. Routes are global K/V coordinates: under CP the keys are all-gathered to the global length, so the mask extent follows the CP context whether or not the row is packed.
Parameters:
Number of query positions on this rank.
Optional packed-document boundaries [num_docs + 1].
Optional contiguous CP metadata.
Returns: int
(max_visible_tokens, kv_length): the route-width bound and the number of
FP32 RMSNorm + output gate as one fusable elementwise chain.