Input features
×The features entering this shared expert.
- shape
- [B batch, T positions, 4096 d]
Sources
Contextual evidence from MoE RMSNorm
RMSNorm divides by the root mean square plus ε, in float32, and multiplies by a learned gain.
model.py 183–196 ↗ · deepseek-ai/DeepSeek-V4-Flash @ 60d8d70770c6
Excerpt
class RMSNorm(nn.Module):
def __init__(self, dim: int, eps: float = 1e-6):
super().__init__()
self.dim = dim
self.eps = eps
# rmsnorm in the checkpoint is stored in bf16, while the parameter here is stored in fp32 for convenient.
self.weight = nn.Parameter(torch.ones(dim, dtype=torch.float32))
def forward(self, x: torch.Tensor):
dtype = x.dtype
x = x.float()
var = x.square().mean(-1, keepdim=True)
x = x * torch.rsqrt(var + self.eps)
return (self.weight * x).to(dtype)The block runs the two sublayers alike: compute the mixes from the streams, read with them, normalise, apply the sublayer, write the streams.
model.py 688–700 ↗ · deepseek-ai/DeepSeek-V4-Flash @ 60d8d70770c6
Excerpt
def forward(self, x: torch.Tensor, start_pos: int, input_ids: Optional[torch.Tensor]) -> torch.Tensor:
residual = x
x, post, comb = self.hc_pre(x, self.hc_attn_fn, self.hc_attn_scale, self.hc_attn_base)
x = self.attn_norm(x)
x = self.attn(x, start_pos)
x = self.hc_post(x, residual, post, comb)
residual = x
x, post, comb = self.hc_pre(x, self.hc_ffn_fn, self.hc_ffn_scale, self.hc_ffn_base)
x = self.ffn_norm(x)
x = self.ffn(x, input_ids)
x = self.hc_post(x, residual, post, comb)
return xContextual evidence from Router, by token ID
The router: square-root softplus scores from one projection in float32; in the first n_hash_layers layers the experts come from a fixed token-to-expert table and there is no bias; elsewhere the top 6 of the scores plus a selection bias; the weights are the unbiased scores of the chosen experts, divided by their sum and multiplied by 1.5.
model.py 546–584 ↗ · deepseek-ai/DeepSeek-V4-Flash @ 60d8d70770c6
Excerpt
class Gate(nn.Module):
"""MoE gating: computes expert routing scores and selects top-k experts.
Supports hash-based routing (first n_hash_layers) where expert indices are
predetermined per token ID, and score-based routing (remaining layers)."""
def __init__(self, layer_id: int, args: ModelArgs):
super().__init__()
self.dim = args.dim
self.topk = args.n_activated_experts
self.score_func = args.score_func
self.route_scale = args.route_scale
self.hash = layer_id < args.n_hash_layers
self.weight = nn.Parameter(torch.empty(args.n_routed_experts, args.dim))
if self.hash:
self.tid2eid = nn.Parameter(torch.empty(args.vocab_size, args.n_activated_experts, dtype=torch.int32), requires_grad=False)
self.bias = None
else:
self.bias = nn.Parameter(torch.empty(args.n_routed_experts, dtype=torch.float32))
def forward(self, x: torch.Tensor, input_ids: Optional[torch.Tensor] = None) -> Tuple[torch.Tensor, torch.Tensor]:
scores = linear(x.float(), self.weight.float())
if self.score_func == "softmax":
scores = scores.softmax(dim=-1)
elif self.score_func == "sigmoid":
scores = scores.sigmoid()
else:
scores = F.softplus(scores).sqrt()
original_scores = scores
# Bias shifts scores for expert selection (topk) but does not affect routing weights.
if self.bias is not None:
scores = scores + self.bias
if self.hash:
indices = self.tid2eid[input_ids]
else:
indices = scores.topk(self.topk, dim=-1)[1]
weights = original_scores.gather(1, indices)
if self.score_func != "softmax":
weights /= weights.sum(dim=-1, keepdim=True)
weights *= self.route_scale
return weights, indicesThe reference configuration: 43 layers of width 4,096, 64 heads of 512 features with a 64-feature rotary part, a 1,024-feature query latent, a grouped output of 8 groups at rank 1,024, a window of 128, the per-layer compression ratios (0, 0, then 4 and 128 alternating, and 0 for the MTP block; 0 is a layer of window attention only), an indexer of 64 heads of 128 keeping 512, hyper-connections of 4 streams with 20 Sinkhorn iterations, 256 routed experts of 2,048 of which 6 are used with 1 shared, square-root-softplus scores scaled by 1.5, three hash-routed layers, and YaRN over 65,536 positions.
config.json 1–34 ↗ · deepseek-ai/DeepSeek-V4-Flash @ 60d8d70770c6
Excerpt
{
"vocab_size": 129280,
"dim": 4096,
"moe_inter_dim": 2048,
"n_layers": 43,
"n_hash_layers": 3,
"n_heads": 64,
"n_routed_experts": 256,
"n_shared_experts": 1,
"n_activated_experts": 6,
"score_func": "sqrtsoftplus",
"route_scale": 1.5,
"swiglu_limit": 10.0,
"q_lora_rank": 1024,
"head_dim": 512,
"rope_head_dim": 64,
"o_groups": 8,
"o_lora_rank": 1024,
"window_size": 128,
"original_seq_len": 65536,
"rope_theta": 10000,
"rope_factor": 16,
"beta_fast": 32,
"beta_slow": 1,
"index_n_heads": 64,
"index_head_dim": 128,
"index_topk": 512,
"hc_mult": 4,
"hc_sinkhorn_iters": 20,
"dtype": "fp8",
"scale_fmt": "ue8m0",
"expert_dtype": "fp4",
"compress_rope_theta": 160000,
"compress_ratios": [0, 0, 4, 128, 4, 128, 4, 128, 4, 128, 4, 128, 4, 128, 4, 128, 4, 128, 4, 128, 4, 128, 4, 128, 4, 128, 4, 128, 4, 128, 4, 128, 4, 128, 4, 128, 4, 128, 4, 128, 4, 128, 4, 0]Contextual evidence from Routed expert
An expert is a SwiGLU whose gate is clamped above at 10 and whose up branch is clamped to ±10, computed in float32, with the routing weight applied before the down projection.
model.py 587–606 ↗ · deepseek-ai/DeepSeek-V4-Flash @ 60d8d70770c6
Excerpt
class Expert(nn.Module):
"""Single MoE expert: SwiGLU FFN (w1, w2, w3). Computation in float32 for stability."""
def __init__(self, dim: int, inter_dim: int, dtype=None, swiglu_limit=0):
super().__init__()
self.w1 = Linear(dim, inter_dim, dtype=dtype)
self.w2 = Linear(inter_dim, dim, dtype=dtype)
self.w3 = Linear(dim, inter_dim, dtype=dtype)
self.swiglu_limit = swiglu_limit
def forward(self, x: torch.Tensor, weights: Optional[torch.Tensor] = None) -> torch.Tensor:
dtype = x.dtype
gate = self.w1(x).float()
up = self.w3(x).float()
if self.swiglu_limit > 0:
up = torch.clamp(up, min=-self.swiglu_limit, max=self.swiglu_limit)
gate = torch.clamp(gate, max=self.swiglu_limit)
x = F.silu(gate) * up
if weights is not None:
x = weights * x
return self.w2(x.to(dtype))The mixture: route, run each selected expert on its tokens with its weight, add the shared expert’s output; the routed experts are stored in FP4.
model.py 609–644 ↗ · deepseek-ai/DeepSeek-V4-Flash @ 60d8d70770c6
Excerpt
class MoE(nn.Module):
"""Mixture-of-Experts: gate routes each token to top-k routed experts + 1 shared expert.
Experts are sharded across TP ranks; each rank handles n_routed_experts // world_size experts."""
def __init__(self, layer_id: int, args: ModelArgs):
super().__init__()
self.layer_id = layer_id
self.dim = args.dim
assert args.n_routed_experts % world_size == 0, f"Number of experts must be divisible by world size (world_size={world_size})"
self.n_routed_experts = args.n_routed_experts
self.n_local_experts = args.n_routed_experts // world_size
self.n_activated_experts = args.n_activated_experts
self.experts_start_idx = rank * self.n_local_experts
self.experts_end_idx = self.experts_start_idx + self.n_local_experts
self.gate = Gate(layer_id, args)
expert_dtype = torch.float4_e2m1fn_x2 if args.expert_dtype == "fp4" else None
self.experts = nn.ModuleList([Expert(args.dim, args.moe_inter_dim, dtype=expert_dtype, swiglu_limit=args.swiglu_limit) if self.experts_start_idx <= i < self.experts_end_idx else None
for i in range(self.n_routed_experts)])
assert args.n_shared_experts == 1
self.shared_experts = Expert(args.dim, args.moe_inter_dim, swiglu_limit=args.swiglu_limit)
def forward(self, x: torch.Tensor, input_ids: torch.Tensor) -> torch.Tensor:
shape = x.size()
x = x.view(-1, self.dim)
weights, indices = self.gate(x, input_ids.flatten())
y = torch.zeros_like(x, dtype=torch.float32)
counts = torch.bincount(indices.flatten(), minlength=self.n_routed_experts).tolist()
for i in range(self.experts_start_idx, self.experts_end_idx):
if counts[i] == 0:
continue
expert = self.experts[i]
idx, top = torch.where(indices == i)
y[idx] += expert(x[idx], weights[idx, top, None])
if world_size > 1:
dist.all_reduce(y)
y += self.shared_experts(x)
return y.type_as(x).view(shape)