nemo_automodel.components.models.deepseek_v4.model
nemo_automodel.components.models.deepseek_v4.model
DeepSeek V4 Model.
Key architectural points (from official inference/model.py):
HC (Hyper-Connections): Every transformer block maintains hc_mult=4 copies of the hidden state. The embedding output is expanded: [B,S,dim] -> [B,S,hc_mult,dim]. hc_pre reduces [B,S,hc_mult,dim] -> [B,S,dim] before attn/ffn. hc_post expands [B,S,dim] -> [B,S,hc_mult,dim] after attn/ffn. Full HC requires the hc_split_sinkhorn CUDA kernel. Current fallback: mean-pooling for hc_pre, broadcast add for hc_post.
HC parameters (ALL layers, stored in float32): hc_attn_fn : [mix_hc, hc_mult*dim] where mix_hc = (2+hc_mult)hc_mult = 24 hc_attn_base : [mix_hc] hc_attn_scale : [3] hc_ffn_fn : [mix_hc, hc_multdim] hc_ffn_base : [mix_hc] hc_ffn_scale : [3]
Gate hash layers (layer_idx < num_hash_layers): Instead of score-based routing, the gate uses a fixed token-id -> expert-id lookup table (tid2eid: [vocab_size, n_activated_experts]).
All layers use MoE FFN (no dense layers). Compress-ratio sliding-window attention is not yet implemented.
Module Contents
Classes
Functions
Data
API
Bases: Module
Single transformer block for DeepSeek V4.
Uses HuggingFace transformers PR 45616’s HyperConnection decoder-layer
pattern: two DeepseekV4HyperConnection modules own the collapse /
expand mixer weights at the attention and FFN sites respectively.
Checkpoint’s flat hc_attn_* / hc_ffn_* keys are routed into
attn_hc.* / ffn_hc.* by the state-dict adapter.
Transform one HC block.
Parameters:
HC streams with layout [batch, sequence, hc_mult, hidden].
Main RoPE tensors with layout compatible with
[batch, sequence, qk_rope_head_dim].
Token positions with layout [batch, sequence].
Optional compressor RoPE tensors.
Optional compressor rotary module.
Additive attention mask with layout
[batch, 1, sequence, sequence].
Boolean padding mask with layout [batch, sequence].
Token IDs with layout [batch, sequence].
Visual pseudo-token types with layout
[batch, sequence] and -1 at text positions.
Returns: torch.Tensor
HC streams with layout [batch, sequence, hc_mult, hidden].
Bases: CausalLMOutputWithPast
Output of DeepseekV4ForCausalLM.forward.
Subclasses transformers.modeling_outputs.CausalLMOutputWithPast so the
standard logits / hidden_states fields are present (the recipe’s
fused cross-entropy path requires "hidden_states" in out and reads the
final hidden states off the output) while the DSV4-specific MTP fields are
carried as declared dataclass fields. As required by ModelOutput, every
field after the first declares a None default.
Bases: HFCheckpointingMixin, Module, MoEFSDPSyncMixin
Keep DSV4 non-layer PP dependencies with the stages that need them.
Run causal language modeling with optional DSV4 visual inputs.
Parameters:
Token IDs with layout [batch, sequence].
Optional PP-propagated MTP embeddings, each with
layout [batch, sequence, hidden].
Position IDs with layout [batch, sequence].
Valid-token mask with layout [batch, sequence].
Padding mask with layout [batch, sequence].
Concatenated patches with layout
[all_patches, 3, patch_size, patch_size].
ViT grids with layout [all_images, 2].
Image counts with layout [batch].
Visual types with layout [batch, sequence]
and -1 for text.
Number or positions of logits to retain.
Whether to expose final states.
Returns: 'DeepseekV4CausalLMOutput' | tuple[torch.Tensor, ...] | torch.Tensor
DeepseekV4CausalLMOutput outside PP, or the PP stage tensor
Return PP input/output meta tensors for DSV4’s HC and MTP contract.
Model-owned context-parallel batch prep (Miles-style contiguous shard).
Returns a ContextParallelSharder (under the "cp_sharder" batch key) so
the CP dispatch delegates CP sharding back to this
model, with the config-derived per-rank shard multiple bound. DSV4
embeds internally, so (unlike VLM models) this does not pre-embed —
it leaves input_ids for the sharding callable.
Bases: Module
Hash gate for first num_hash_layers: routes tokens via a fixed lookup table.
Instead of computing routing scores, the gate uses tid2eid[token_id] to pre-assign expert indices. The routing weight is still computed from the gate weight but the selection is deterministic per token id.
tid2eid shape: [vocab_size, n_activated_experts] (int64 runtime, non-trainable)
Signature matches components.moe.layers.Gate — forward(x, token_mask, cp_mesh) returning (weights, indices, aux_loss) — so the generic MoE
module can call it interchangeably. The per-forward input_ids needed
for the tid2eid lookup is stashed on the module by the enclosing Block via
:meth:set_input_ids immediately before the MoE call.
Initialize the trainable gate and a valid deterministic hash table.
Parameters:
Standard deviation for the routing weight initialization.
Stash the current batch’s input_ids for the next forward call.
No-op for compat with callers that walk MoE gates and call update_bias.
Bases: Module
Encode one image from ViT patches into LLM-width grid features.
Parameters:
Image patches with layout
[n_vit_h * n_vit_w, 3, patch_size, patch_size].
Number of patch rows.
Number of patch columns.
Returns: torch.Tensor
Aligned features with layout
Run the DSV4 text backbone with an optional image embedding bridge.
Parameters:
Token IDs with layout [batch, sequence] on the first
PP stage, or HC activations on later stages.
Optional embeddings with layout
[batch, sequence, hidden].
Positions with layout [batch, sequence].
Valid-token mask with layout [batch, sequence].
Padding mask with layout [batch, sequence].
Concatenated image patches with layout
[all_patches, 3, patch_size, patch_size].
Patch grids with layout [all_images, 2].
Image counts with layout [batch].
Pseudo-token types with layout
[batch, sequence] and -1 at text positions.
Whether to also return the uncollapsed HC stream.
Returns: torch.Tensor | tuple[torch.Tensor, torch.Tensor]
Hidden states with layout [batch, sequence, hidden] and,
Replace pseudo-token embeddings with encoded images and sentinels.
Parameters:
Text embeddings with layout [batch, sequence, hidden].
Concatenated patches with layout
[all_patches, 3, patch_size, patch_size].
ViT grid sizes with layout [all_images, 2].
Pseudo-token types with layout
[batch, sequence] and -1 for text.
Optional counts with layout [batch].
Returns: torch.Tensor
Embeddings with the same layout as inputs_embeds.
Bases: Gate
DSV4 gate with separate visual bias and optional text hash routing.
The released vision checkpoint routes visual pseudo tokens by score in all
layers. In the first hash layers only text tokens use tid2eid; visual
tokens use scores + bias_vl. Later layers select text experts with the
normal correction bias and visual experts with bias_vl.
Return a local [experts] tensor from a tensor or DTensor.
Select experts from router logits of layout [tokens, experts].
Initialize visual bias and a deterministic checkpoint-free hash map.
Set token metadata consumed by the next gate call.
Parameters:
Token IDs with layout [batch, sequence].
Visual types with layout [batch, sequence]
and -1 for text tokens.
Accept standard THD offsets at the DSV4 model boundary.
DSV4 internally uses seq_lens to build document-aware masks. Packed
callers commonly provide the equivalent cu_seqlens representation, so
normalize it here when context parallelism has not already produced native
padded-BSHD lengths.
Convert standard THD cumulative offsets to DSV4’s per-row lengths.
Make every token inside an image span mutually visible.
Parameters:
Additive causal/sliding mask with layout
[batch, 1, sequence, sequence].
Pseudo-token types with layout [batch, sequence]
and -1 at text positions.
Returns: torch.Tensor
Additive mask with the same layout as attention_mask. Text