Mixture of experts

Shared expert

×

The same feed-forward, run for every position.

h=a⊙uˉh=a\odot\bar u
yshared=hW2y^{\mathrm{shared}}=hW_{2}
All 7 steps
g=xffnW1g=x_{\mathrm{ffn}}W_{1}
u=xffnW3u=x_{\mathrm{ffn}}W_{3}
gˉ=min⁡(g, 10)\bar g=\min(g,\,10)
uˉ=clip⁡(u, −10, 10)\bar u=\operatorname{clip}(u,\,-10,\,10)
a=gˉ σ(gˉ)a=\bar g\,\sigma(\bar g)
h=a⊙uˉh=a\odot\bar u
yshared=hW2y^{\mathrm{shared}}=hW_{2}
in
xffnx_{\mathrm{ffn}} [B batch, T positions, 4096 d]
out
ysharedy^{\mathrm{shared}} [B batch, T positions, 4096 d]
Parameters25,165,824 × 2 layers

25,165,824 parameters per instance, across its learned components

ComponentCalculationParameters
Gate projection4,096 × 2,0488,388,608
Up projection4,096 × 2,0488,388,608
Down projection2,048 × 4,0968,388,608
Per-instance total25,165,824

One in each of the 2 layers, each with its own weights.

Explanation

Stored as 8-bit floats (model.py 627).

Sources

In codeself.shared_experts(x) · 643

Open pinned code ↗

Direct evidence

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)