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.
Inspect Architecture: DeepSeek-V3 and R1 reasoning MoE1. 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.
2. The math
3. How it works
4. The code (python)
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
In the catalog
Finished this chapter?
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.