Learn machine learning from scratch

Start at chapter 1 and build up: what a model is, how it measures its own mistakes, and how it learns. Everything is worked out in plain Python, with the maths shown rather than assumed. Two shorter tracks hold reference notes on the maths and on modern architectures.

Track Progress: 0 Completed
0%
Modern ArchitecturesLEVEL 3 · ADVANCEDChapter 4

Mixture of Experts (MoE) & Multi-Head Latent Attention (MLA)

DeepSeek-V3 architecture: Top-2 gating routing, auxiliary-loss-free balancing, and 93% KV cache compression.

Reference notes. Condensed summaries of each topic, not step-by-step lessons. The Core Course is the one to work through.

7 min Prerequisites: Modern LLM Blocks, Softmax & Matrix factorizations
Inspect Architecture: DeepSeek-V3 and R1 reasoning MoE

1. The idea

Frontier reasoning architectures like DeepSeek-V3 scale model capacity while keeping inference FLOPs constant using Sparse Mixture-of-Experts (MoE) and Multi-Head Latent Attention (MLA). MLA compresses keys and values into a shared low-rank latent representation.

Two diagrams. Mixture of Experts, drawn for E = 8 experts and k = 2: a token x goes to the router, s = softmax of x W_g plus b_g, which sends it to only two experts, E2 and E6, with weights s2 and s6; the other six sit idle. The output is y = the sum of s_i E_i(x) over the top k. Multi-Head Latent Attention: x_t is projected by W_DKV to a small latent vector c_t^KV of size d_c, which is what gets cached. W_UK and W_UV rebuild the keys and values for every head from it on the fly, and d_c is much smaller than n_h times d_h.Two diagrams. Mixture of Experts, drawn for E = 8 experts and k = 2: a token x goes to the router, s = softmax of x W_g plus b_g, which sends it to only two experts, E2 and E6, with weights s2 and s6; the other six sit idle. The output is y = the sum of s_i E_i(x) over the top k. Multi-Head Latent Attention: x_t is projected by W_DKV to a small latent vector c_t^KV of size d_c, which is what gets cached. W_UK and W_UV rebuild the keys and values for every head from it on the fly, and d_c is much smaller than n_h times d_h.
Two ways to scale without paying for it on every token: run only k experts, and cache one small latent instead of full keys and values.

2. The math

MoE Top-k Softmax Routing
y=∑i∈Top-k(s)siEi(x)s=softmax(xWg+bg)y = \sum_{i \in \text{Top-}k(s)} s_i E_i(x) \qquad s = \text{softmax}(x W_g + b_g)
Tokens route dynamically to k of E experts with weighted combination.
Multi-Head Latent Attention (MLA) Low-Rank Compression
ctKV=WDKVxt∈RdcktC=WUKctKV,  vtC=WUVctKV(dc≪nhdh)c_t^{KV} = W_{DKV} x_t \in \mathbb{R}^{d_c} \qquad k_t^C = W_{UK} c_t^{KV}, \; v_t^C = W_{UV} c_t^{KV} \qquad (d_c \ll n_h d_h)
Compresses key-value cache by up to 93% using low-rank latent vector c_t^{KV}.

3. How it works

1
Router Gating Score
Compute token affinity scores s = Softmax(x W_g) across E available expert networks.
2
Top-k Selection
Select indices of k highest affinity experts (e.g. Top-2 or Top-8) and normalize routing weights.
3
Expert Dispatch & Accumulation
Execute selected expert FFNs and compute weighted sum sum s_i E_i(x).
4
MLA Latent Decompression
Project compressed latent vector c_t^{KV} into multi-head keys and values on the fly.

4. The code (python)

moe_mla.py
import torch
import torch.nn as nn
import torch.nn.functional as F

class SparseMoELayer(nn.Module):
    """Top-2 Sparse Mixture-of-Experts Layer with Gating in PyTorch."""
    def __init__(self, dim: int, hidden_dim: int, num_experts: int = 8, top_k: int = 2):
        super().__init__()
        self.num_experts = num_experts
        self.top_k = top_k
        self.router = nn.Linear(dim, num_experts, bias=False)
        self.experts = nn.ModuleList([
            nn.Sequential(
                nn.Linear(dim, hidden_dim),
                nn.SiLU(),
                nn.Linear(hidden_dim, dim)
            ) for _ in range(num_experts)
        ])

    def forward(self, x: torch.Tensor) -> torch.Tensor:
        B, T, D = x.shape
        x_flat = x.view(-1, D)

        router_logits = self.router(x_flat)
        top_k_logits, top_k_indices = torch.topk(router_logits, self.top_k, dim=-1)
        top_k_weights = F.softmax(top_k_logits, dim=-1)

        out = torch.zeros_like(x_flat)

        for expert_idx in range(self.num_experts):
            mask = (top_k_indices == expert_idx)
            if not mask.any(): continue

            token_indices, k_positions = torch.where(mask)
            expert_inputs = x_flat[token_indices]
            expert_outputs = self.experts[expert_idx](expert_inputs)

            weights = top_k_weights[token_indices, k_positions].unsqueeze(-1)
            out.index_add_(0, token_indices, expert_outputs * weights)

        return out.view(B, T, D)

5. Check yourself

Answer all 1 questions correctly to complete the chapter · 0 / 1 done
Q1/1 What is the key advantage of a 671B parameter MoE model that activates 37B parameters per token over a dense 671B model?

Finished this chapter?

Weekly newsletter

The Epoch Zero newsletter

What changed in ML architectures this week: new models worth knowing, benchmark moves, and one architecture explained in plain words. Free, once a week, unsubscribe anytime.