Skip to navigation

nemo_automodel.components.models.deepseek_v41.dfly2

View as MarkdownOpen in Claude

DFly2 draft for DeepSeek-V4.1-Flash (arXiv:2611.34776).

Each draft layer is a V4.1 block (latent MQA with an attention sink, routed MoE and single-pass mHC) paired with one of the target’s ratio-1 sparse-attention layers. It owns no context projection: its queries read the keys that target layer attends over, its own sliding-window latents followed by the shared 1:1 global latents, at the slots that layer attends from the row before the anchor (the last 128 tokens plus the indexer’s top-512 picks), together with the draft keys of its own block. The released checkpoint pairs layers 28, 32 and 36.

Around the backbone, the target’s final hidden state at the row before the anchor is fused into the anchor slot (MTP fusion), and a teacher-forced hidden correction, a SwiGLU plus an attentive correction over the last layer’s context and the block’s own prefix, adjusts every slot before the frozen LM head. Slot 0 holds the anchor and is not supervised, so a block of block_size slots drafts block_size - 1 tokens.

Module Contents

Classes

NameDescription
DeepseekV41DFly2ConfigValidated declarative configuration of the V4.1 DFly2 draft.
DeepseekV41DFly2ModelModel-owned DFly2 draft emitting the shared DSpark loss inputs over its drafted slots.
_DeepseekV41DFly2AttentionLatent MQA over a paired target layer’s keys and the draft’s own block.
_DeepseekV41DFly2AttentiveCorrectionPer-slot latent MQA over the last draft layer’s context plus a gated read of the block prefix.
_DeepseekV41DFly2BlockOne draft layer: latent MQA, routed MoE and single-pass mHC, as in the target’s blocks.
_DeepseekV41DFly2ConfidenceHeadFP32 acceptance head on the drafted slots’ final-normalized states (absent from the released draft).
_DeepseekV41DFly2HiddenCorrectionTeacher-forced residual from each slot’s hidden state and the token before it.
_DeepseekV41DFly2MTPFusionFuse the target’s last hidden state into the anchor slot, as the target’s MTP layer opens.

Functions

NameDescription
_listed_latent_attentionAttend every query over its listed keys, one shared latent serving as key and value.
default_dfly2_backendReturn the draft’s kernel selection.

Data

MAX_BLOCK_SLOTS

_SPARSE_BACKENDS

API

class nemo_automodel.components.models.deepseek_v41.dfly2.DeepseekV41DFly2Config(
target_layer_ids: tuple[int, ...],
block_size: int,
num_anchors: int,
mask_token_id: int,
enable_confidence_head: bool = False,
confidence_head_stop_gradient: bool = True,
n_routed_experts: int = 128,
num_experts_per_tok: int = 3
)
Dataclass

Validated declarative configuration of the V4.1 DFly2 draft.

block_size
int

Draft slots per block, the anchor slot included.

confidence_head_stop_gradient
bool = True

Feed the acceptance head detached states, so its loss trains only the head.

enable_confidence_head
bool = False

Build the acceptance head, absent from the released draft.

mask_token_id
int

Token filling the non-anchor slots.

n_routed_experts
int = 128

Routed experts per draft layer.

num_anchors
int

Blocks sampled per sequence.

num_experts_per_tok
int = 3

Experts each token is routed to.

target_layer_ids
tuple[int, ...]

Target layers paired with the draft layers, in draft-layer order. Each must be a ratio-1 sparse-attention layer, whose context rows are raw tokens.

text_config
DeepseekV41TextConfig

Target text configuration; the draft reuses its attention, mHC and MoE shapes and its compressed-layer rotary embedding.

nemo_automodel.components.models.deepseek_v41.dfly2.DeepseekV41DFly2Config.build(

Validate the target pairing and build a freshly initialized draft.

Parameters:

backend
BackendConfig | NoneDefaults to None

Kernel selection for the draft; defaults to default_dfly2_backend.

Returns: DeepseekV41DFly2Model

The draft, ready for device placement.

Raises:

  • ValueError: A paired layer is not a ratio-1 target layer, or a size is invalid.
class nemo_automodel.components.models.deepseek_v41.dfly2.DeepseekV41DFly2Model(
)

Bases: Module

Model-owned DFly2 draft emitting the shared DSpark loss inputs over its drafted slots.

_fsdp_shard_across_blocks
= ['attn.sinks_param']
_keep_in_fp32_modules_strict
_no_split_modules
= ['_DeepseekV41DFly2Block']
_pre_shard_hf_state_dict_keys
confidence_head
config
= copy.deepcopy(text)
embed_tokens
final_norm
hidden_correction
layers
lm_head
moe_config
mtp_fusion
= _DeepseekV41DFly2MTPFusion(text, dtype)
state_dict_adapter
nemo_automodel.components.models.deepseek_v41.dfly2.DeepseekV41DFly2Model._backbone(
noise_embeddings: torch.Tensor,
context_keys: collections.abc.Sequence[torch.Tensor],
key_indices: collections.abc.Sequence[torch.Tensor],
position_ids: torch.Tensor
) -> torch.Tensor

Run the draft layers on the block inputs.

Parameters:

noise_embeddings
torch.Tensor

Tensor of shape [batch, draft_sequence, hidden].

context_keys
Sequence[torch.Tensor]

One tensor of shape [batch, context_keys, head_dim] per layer.

key_indices
Sequence[torch.Tensor]

One integer tensor of shape [batch, draft_sequence, slots] per layer.

position_ids
torch.Tensor

Integer tensor of shape [batch, draft_sequence].

Returns: torch.Tensor

The collapsed, not yet normalized output of shape [batch, draft_sequence, hidden].

nemo_automodel.components.models.deepseek_v41.dfly2.DeepseekV41DFly2Model.compute_logits(
hidden_states: torch.Tensor
) -> torch.Tensor

Project hidden states through the frozen vocabulary head in FP32.

Parameters:

hidden_states
torch.Tensor

Tensor of shape […, hidden], with arbitrary leading dimensions.

Returns: torch.Tensor

FP32 tensor of shape […, vocab].

nemo_automodel.components.models.deepseek_v41.dfly2.DeepseekV41DFly2Model.forward(
input_ids: torch.Tensor,
loss_mask: torch.Tensor,
context_keys: collections.abc.Sequence[torch.Tensor],
context_indices: collections.abc.Sequence[torch.Tensor],
target_last_hidden_states: torch.Tensor

Run DFly2 training for sampled anchors.

Slot k of the block at anchor a predicts token a + k; slot 0 holds the anchor and is dropped from the outputs, so every output tensor covers the block_size - 1 drafted slots and its teacher is the target’s distribution at the token before the label.

Parameters:

input_ids
torch.Tensor

Target-token tensor of shape [batch, sequence].

loss_mask
torch.Tensor

Supervision tensor of shape [batch, sequence].

context_keys
Sequence[torch.Tensor]

One tensor per draft layer of shape [batch, context_keys, head_dim], as in DFly2TargetFeatures.

context_indices
Sequence[torch.Tensor]

One integer tensor per draft layer of shape [batch, sequence, slots], as in DFly2TargetFeatures.

target_last_hidden_states
torch.Tensor

Frozen target tensor of shape [batch, sequence, hidden], the input of the target’s LM head.

Returns: DSparkForwardOutput

Shared DSpark loss inputs. Draft and teacher logits have shape [batch,

nemo_automodel.components.models.deepseek_v41.dfly2.DeepseekV41DFly2Model.initialize_attentive_correction() -> None

Start the attentive correction from the last draft layer’s attention, with its output closed.

Its query and key input projections read [hidden; previous embedding]: the hidden columns take the layer’s wq_a / wkv and the embedding columns start at zero. The norms, wq_b, wo_a and both sinks take the layer’s values; wo_b, the gate and the per-slot biases start at zero, so the correction contributes nothing until trained.

nemo_automodel.components.models.deepseek_v41.dfly2.DeepseekV41DFly2Model.initialize_embeddings_and_head(
embed_tokens: torch.nn.Module,
lm_head: torch.nn.Module,
freeze: bool = True
) -> None

Copy the target’s embedding and vocabulary projection.

Parameters:

embed_tokens
nn.Module

Target embedding with weight of shape [vocab, hidden].

lm_head
nn.Module

Target output projection with weight of shape [vocab, hidden].

freeze
boolDefaults to True

Must be true: the draft shares the target’s frozen embedding and head.

nemo_automodel.components.models.deepseek_v41.dfly2.DeepseekV41DFly2Model.initialize_from_target(
target: torch.nn.Module
) -> None

Start every draft layer’s attention, norms, mHC mixes and shared expert from its paired target layer.

Collective when the target is sharded: every rank must call it, in the same order. The routed experts and the router keep their fresh initialization; warm-start them from an existing draft through draft_weights_path instead.

Parameters:

target
nn.Module

The frozen target DeepseekV41ForCausalLM; its parameters may be DTensors, which are gathered one at a time.

nemo_automodel.components.models.deepseek_v41.dfly2.DeepseekV41DFly2Model.initialize_weights(
buffer_device: torch.device | None = None
) -> None

Initialize every draft parameter for checkpoint-free training.

The fusion gate, the hidden correction’s down projection and the attentive correction’s output start at zero, so a fresh draft is its backbone alone.

Parameters:

buffer_device
torch.device | NoneDefaults to None

Device used by grouped expert initialization. Defaults to the first attention projection’s device.

class nemo_automodel.components.models.deepseek_v41.dfly2._DeepseekV41DFly2Attention(
layer_idx: int,
)

Bases: DeepseekV41Attention

Latent MQA over a paired target layer’s keys and the draft’s own block.

rotary_emb
= _RotaryEmbedding(config, compressed=True)
nemo_automodel.components.models.deepseek_v41.dfly2._DeepseekV41DFly2Attention.forward(
hidden_states: torch.Tensor,
context_keys: torch.Tensor,
key_indices: torch.Tensor,
position_ids: torch.Tensor
) -> torch.Tensor

Attend draft queries to their listed target keys and their own block.

Parameters:

hidden_states
torch.Tensor

Normalized draft tensor of shape [batch, draft_sequence, hidden].

context_keys
torch.Tensor

Paired target layer’s keys of shape [batch, context_keys, head_dim].

key_indices
torch.Tensor

Integer tensor of shape [batch, draft_sequence, slots] of rows of cat(context_keys, draft_keys), -1 unused.

position_ids
torch.Tensor

Integer tensor of shape [batch, draft_sequence].

Returns: torch.Tensor

Tensor of shape [batch, draft_sequence, hidden]. Inputs are not mutated.

class nemo_automodel.components.models.deepseek_v41.dfly2._DeepseekV41DFly2AttentiveCorrection(
dtype: torch.dtype
)

Bases: Module

Per-slot latent MQA over the last draft layer’s context plus a gated read of the block prefix.

The query comes from the slot’s normalized hidden state and the normalized embedding of the token before it. Slot k reads the context keys the last draft layer read, then, in a softmax of its own with a sink and a learned bias by distance, the keys of slots 0..k of its block, added through a per-head tanh gate. wo_b and the gate start at zero, so a fresh correction is an exact no-op.

attn_sink
block_gate
block_gate_bias
block_rel_bias
block_sink
head_dim
= config.head_dim
kv_in
kv_norm
num_groups
= config.o_groups
num_heads
= config.num_attention_heads
q_in
q_norm
rotary_emb
= _RotaryEmbedding(config, compressed=True)
wo_a
wo_b
wq_b
nemo_automodel.components.models.deepseek_v41.dfly2._DeepseekV41DFly2AttentiveCorrection._prefix_read(
query: torch.Tensor,
keys: torch.Tensor,
inputs: torch.Tensor,
block_size: int
) -> torch.Tensor

Gated read of each slot’s own block prefix (slots 0..k for slot k).

The prefix has a softmax of its own: a per-head learned bias indexed by how many slots back the key is, plus the block_sink logit in the denominator as an extra column. Each head scales its read by tanh of a gate computed from the slot’s inputs.

Parameters:

query
torch.Tensor

Tensor of shape [batch, slots, heads, head_dim], whole blocks of block_size.

keys
torch.Tensor

Tensor of shape [batch, slots, head_dim], each slot’s key, also its value.

inputs
torch.Tensor

Tensor of shape [batch, slots, 2 * hidden], the query inputs.

block_size
int

Slots per block.

Returns: torch.Tensor

FP32 tensor of shape [batch, slots, heads, head_dim].

nemo_automodel.components.models.deepseek_v41.dfly2._DeepseekV41DFly2AttentiveCorrection.forward(
inputs: torch.Tensor,
context_keys: torch.Tensor,
context_indices: torch.Tensor,
position_ids: torch.Tensor,
block_size: int
) -> torch.Tensor

Compute the correction of every slot.

Parameters:

inputs
torch.Tensor

Tensor of shape [batch, slots, 2 * hidden], the concatenated normalized hidden state and previous-token embedding of each slot; whole blocks.

context_keys
torch.Tensor

Last draft layer’s context keys of shape [batch, context_keys, head_dim].

context_indices
torch.Tensor

Integer tensor of shape [batch, slots, key_slots] of context_keys rows, -1 unused.

position_ids
torch.Tensor

Integer tensor of shape [batch, slots].

block_size
int

Slots per block.

Returns: torch.Tensor

Tensor of shape [batch, slots, hidden].

class nemo_automodel.components.models.deepseek_v41.dfly2._DeepseekV41DFly2Block(
layer_idx: int,
)

Bases: Module

One draft layer: latent MQA, routed MoE and single-pass mHC, as in the target’s blocks.

attn
attn_hc
attn_norm
ffn
= MoE(moe_config, backend)
ffn_hc
ffn_norm
mlp
MoE

Expose the shared parallelizer’s MoE interface without duplicate registration.

nemo_automodel.components.models.deepseek_v41.dfly2._DeepseekV41DFly2Block.forward(
hidden_states: torch.Tensor,
pre_mix: torch.Tensor,
context_keys: torch.Tensor,
key_indices: torch.Tensor,
position_ids: torch.Tensor
) -> tuple[torch.Tensor, torch.Tensor]

Apply one draft layer.

The attention input collapses the streams with the previous layer’s FFN pre-mix and the FFN input with this layer’s attention pre-mix, as the target’s blocks do.

Parameters:

hidden_states
torch.Tensor

Tensor of shape [batch, draft_sequence, streams, hidden].

pre_mix
torch.Tensor

FP32 tensor of shape [batch, draft_sequence, streams].

context_keys
torch.Tensor

Tensor of shape [batch, context_keys, head_dim].

key_indices
torch.Tensor

Integer tensor of shape [batch, draft_sequence, slots].

position_ids
torch.Tensor

Integer tensor of shape [batch, draft_sequence].

Returns: torch.Tensor

Updated streams of shape [batch, draft_sequence, streams, hidden] and the FP32

class nemo_automodel.components.models.deepseek_v41.dfly2._DeepseekV41DFly2ConfidenceHead(
hidden_size: int
)

Bases: Module

FP32 acceptance head on the drafted slots’ final-normalized states (absent from the released draft).

confidence_proj
= nn.Linear(hidden_size, 1, dtype=(torch.float32))
nemo_automodel.components.models.deepseek_v41.dfly2._DeepseekV41DFly2ConfidenceHead.forward(
hidden_states: torch.Tensor
) -> torch.Tensor

Predict an acceptance logit per slot.

Parameters:

hidden_states
torch.Tensor

Tensor of shape […, hidden], with arbitrary leading dimensions.

Returns: torch.Tensor

FP32 tensor of shape […].

class nemo_automodel.components.models.deepseek_v41.dfly2._DeepseekV41DFly2HiddenCorrection(
intermediate_size: int,
dtype: torch.dtype
)

Bases: Module

Teacher-forced residual from each slot’s hidden state and the token before it.

attention
down_proj
embed_norm
gate_proj
hidden_norm
up_proj
nemo_automodel.components.models.deepseek_v41.dfly2._DeepseekV41DFly2HiddenCorrection.forward(
hidden_states: torch.Tensor,
previous_embeddings: torch.Tensor,
context_keys: torch.Tensor,
context_indices: torch.Tensor,
position_ids: torch.Tensor,
block_size: int
) -> torch.Tensor

Return the corrected hidden states.

Parameters:

hidden_states
torch.Tensor

Final-normalized draft tensor of shape [batch, slots, hidden].

previous_embeddings
torch.Tensor

Tensor of shape [batch, slots, hidden], the embedding of the token before each slot (the anchor for slots 0 and 1).

context_keys
torch.Tensor

Tensor of shape [batch, context_keys, head_dim].

context_indices
torch.Tensor

Integer tensor of shape [batch, slots, key_slots].

position_ids
torch.Tensor

Integer tensor of shape [batch, slots].

block_size
int

Slots per block.

Returns: torch.Tensor

Tensor of shape [batch, slots, hidden].

class nemo_automodel.components.models.deepseek_v41.dfly2._DeepseekV41DFly2MTPFusion(
dtype: torch.dtype
)

Bases: Module

Fuse the target’s last hidden state into the anchor slot, as the target’s MTP layer opens.

eh_proj
enorm
gate
hnorm
nemo_automodel.components.models.deepseek_v41.dfly2._DeepseekV41DFly2MTPFusion.forward(
anchor_embeddings: torch.Tensor,
target_hidden_states: torch.Tensor
) -> torch.Tensor

Compute the residual added to every anchor slot.

Parameters:

anchor_embeddings
torch.Tensor

Tensor of shape [batch, num_anchors, hidden], the anchor tokens’ embeddings.

target_hidden_states
torch.Tensor

Tensor of shape [batch, num_anchors, hidden], the target’s final normalized hidden state at the row before each anchor.

Returns: torch.Tensor

Tensor of shape [batch, num_anchors, hidden].

nemo_automodel.components.models.deepseek_v41.dfly2._listed_latent_attention(
query: torch.Tensor,
kv: torch.Tensor,
indices: torch.Tensor,
sinks: torch.Tensor,
scale: float,
backend: str
) -> torch.Tensor

Attend every query over its listed keys, one shared latent serving as key and value.

Parameters:

query
torch.Tensor

Tensor of shape [batch, queries, heads, head_dim].

kv
torch.Tensor

Tensor of shape [batch, keys, head_dim].

indices
torch.Tensor

Integer tensor of shape [batch, queries, slots] of kv rows, -1 unused. The listed keys of a row must be distinct.

sinks
torch.Tensor

FP32 tensor of shape [heads], learned logits added to every softmax denominator only.

scale
float

Query/key score multiplier.

backend
str

"tilelang" or "cudnn" run the shared sparse kernel; "sdpa" and "eager" scatter the lists into a dense mask.

Returns: torch.Tensor

Tensor of shape [batch, queries, heads, head_dim] in the dtype of query; zero

nemo_automodel.components.models.deepseek_v41.dfly2.default_dfly2_backend(
attn: str = 'sdpa'

Return the draft’s kernel selection.

Parameters:

attn
strDefaults to 'sdpa'

"sdpa" or "eager" scatter the key lists into a dense mask, which suits short rows; "tilelang" or "cudnn" run the shared sparse kernel, which long rows need.

Returns: BackendConfig

Backend with torch linears and FP32 RMSNorm. Like BackendConfig’s own default, the

nemo_automodel.components.models.deepseek_v41.dfly2.MAX_BLOCK_SLOTS = 16
nemo_automodel.components.models.deepseek_v41.dfly2._SPARSE_BACKENDS = ('tilelang', 'cudnn')