Transformers & LLM Principles
MoE and New Architectures: Sparse Experts, Load Balancing, State Space Models, Linear Attention and Hybrids
Advanced 40 min For: Researchers
Key takeaways
- ▸MoE replaces the feed-forward layer with several experts and a router, and each token passes through only a few experts, decoupling total parameters from compute per token. From the official config.json files, Mixtral 8x7B has 46.7B parameters with 12.9B active per token, Qwen3-235B-A22B has 235B / 22B and DeepSeek-V3 671B / about 37B; experts account for more than 95% of all parameters.
- ▸Load balancing is the central problem in training MoE. Switch Transformer uses the auxiliary loss α·N·Σfᵢ·Pᵢ (α = 0.01) with a capacity factor, skipping tokens that exceed capacity; DeepSeek-V3 instead gives each expert a bias that is used only for selection, not for weighting, and nudges it by 0.001 per step according to load, barely relying on an auxiliary loss and dropping no tokens in training or inference.
- ▸DeepSeekMoE introduced fine-grained and shared experts: experts are cut smaller and more of them are activated, while always-active shared experts hold common knowledge. DeepSeek-V3 has 1 shared and 256 routed experts per layer and picks 8 per token; Qwen3’s MoE models pick 8 of 128 experts and have no shared expert.
- ▸State space models and linear attention replace the KV cache, which grows with length, by a fixed-size recurrent state, so per-step compute and memory at inference do not depend on context length. Mamba makes the SSM parameters input-dependent (selective) and reports 5× the inference throughput of a Transformer of the same size; Gated DeltaNet combines gating with the delta update rule to overwrite memory precisely.
- ▸Large-scale practice is now mostly hybrid: Jamba has one attention layer in every eight and needs 4GB of KV cache for a 256K context against 32GB for Mixtral; Qwen3-Next-80B-A3B uses Gated DeltaNet in three of every four layers and gated attention in the fourth, with 80B parameters in total and 3B active per token.
Overview: the previous lesson, Modern LLM Architectures, kept the overall Transformer structure and changed only normalisation, positional schemes and the organisation of attention heads. This lesson covers two larger changes. The first keeps attention and replaces the feed-forward layer with a mixture of experts (MoE), decoupling total parameters from compute per token; Mixtral, the MoE versions of Qwen3 and DeepSeek-V3 belong here. The second replaces some or all attention layers with state space models (SSMs), linear attention or their variants, swapping the KV cache that grows with context for a fixed-size recurrent state, and has led to hybrid architectures that interleave attention and recurrent layers. The lesson ends with a short look at diffusion language models and looped language models. Figures come from the cited papers, official model cards and config files, or the runnable example at the end.
This lesson belongs to the MoE and New Architectures unit. Its prerequisite is Modern LLM Architectures; the KV cache and inference bandwidth are covered in How LLMs Generate Text. Related algorithm cards: sparsely-gated MoE, GShard, Switch Transformer, Mixtral, DeepSeekMoE, auxiliary-loss-free load balancing, S4, Mamba, Mamba-2, linear attention, RWKV, RetNet, Hyena, xLSTM, Gated DeltaNet, Jamba and hybrids, diffusion language models and looped language models.
The basic structure of MoE
In a dense Transformer every token passes through the same feed-forward layer (FFN). An MoE layer replaces it with N feed-forward networks of the same shape but with separate parameters (the experts), plus a router (also called the gating network). For an input x, the router scores every expert, keeps only the k highest, and the output is the weighted sum of those k experts’ outputs:
Routing probabilities p = softmax(W_r · x); select the k experts with the largest p, forming the set S Output y = Σ_{i∈S} gᵢ · FFNᵢ(x), where gᵢ is pᵢ renormalised over S
Because each token goes through only k experts, compute is about that of k FFNs while the parameter count is that of N FFNs. Shazeer et al. (2017) validated the idea at scale on LSTM language models and machine translation: using noisy top-k gating, with MoE layers of up to 137 billion parameters, they increased model capacity by more than 1000× with only minor losses in computational efficiency.
| Model | Experts / active per token | Shared experts | Total parameters | Active per token | Source |
|---|---|---|---|---|---|
| Switch-C (2021) | 2048 / 1 | none | 1.6T | — | Switch Transformer paper |
| Mixtral 8x7B (2024) | 8 / 2 | none | 46.7B | 12.9B | paper and config.json |
| Qwen3-30B-A3B (2025) | 128 / 8 | none | 30.5B | 3.3B | model card and config.json |
| Qwen3-235B-A22B (2025) | 128 / 8 | none | 235B | 22B | technical report and config.json |
| DeepSeek-V3 (2024) | 256 / 8 | 1 | 671B | 37B | technical report and config.json |
| Qwen3-Next-80B-A3B (2025) | 512 / 10 | 1 | 80B | 3B | model card |
Counting term by term from the official config files (part 1 of the example), Mixtral 8x7B has 46.7B parameters with 12.88B active per token; Qwen3-30B-A3B has 30.5B (29.9B without embedding and output layers), matching the 30.5B and 29.9B on its model card, with 3.35B active (3.3B on the card); DeepSeek-V3 has 671.0B with 37.55B active (671B and 37B in the technical report). In all four, experts hold more than 95% of the parameters, and the active fraction falls from 27.6% for Mixtral to 5.6% for DeepSeek-V3. The “8x7B” in Mixtral’s name does not mean 56B parameters: only the feed-forward layers are replicated eight times, while attention, embeddings and the rest are shared, which gives 46.7B in total.
MoE saves compute, not memory: which expert will be chosen is not known in advance, so all expert weights must be available. MoE therefore pays off most in training and large-batch inference; for single-request inference each step must read the selected experts’ weights, and memory bandwidth remains the main bottleneck. Deployment trade-offs are covered in LLM Serving Engines.
Routing and load balancing
Left unconstrained, the router tends to keep choosing a few experts: those experts train better, get chosen even more, and the rest barely train (routing collapse). With expert parallelism, experts sit on different devices and imbalance also lets the busiest device slow everything down. There are three main remedies.
Auxiliary losses. Shazeer et al. (2017) used two auxiliary losses that push the importance (sum of gate weights) and the load of the experts towards uniform. GShard (Lepikhin et al., 2020) used top-2 gating in the encoder and decoder of a Transformer, adding expert capacity, group-level dispatching, an auxiliary loss and random routing (the token is dispatched to the second expert with a probability proportional to its gate weight), and trained a 600-billion-parameter multilingual translation model on 2048 TPU v3 cores in 4 days. Switch Transformer (Fedus et al., 2021) simplified routing to top-1 and wrote the auxiliary loss as:
Auxiliary loss = α · N · Σᵢ fᵢ · Pᵢ
where fᵢ is the fraction of tokens in the batch dispatched to expert i (not differentiable), Pᵢ is the average router probability for expert i (differentiable) and N is the number of experts. Under uniform routing fᵢ = Pᵢ = 1/N and the loss equals α. The paper swept α from 10⁻¹ to 10⁻⁵ and settled on α = 10⁻². ST-MoE (Zoph et al., 2022) added the router z-loss, which penalises large logits entering the router, to improve training stability.
The capacity factor. To keep computation shapes fixed, GShard and Switch Transformer give each expert a capacity:
Expert capacity = (tokens per batch / number of experts) × capacity factor
Tokens beyond capacity are skipped (dropped) at that layer and pass to the next layer only through the residual connection. A larger capacity factor drops fewer tokens but wastes more compute and communication. Switch Transformer reports drop rates typically below 1% in its setting. Part 2 of the example sets an artificial routing preference towards expert 0: with top-2 routing the busiest expert receives 2.64 times the mean load and the auxiliary loss is 1.650 (1.000 when uniform); with capacity factors of 1.0, 1.25 and 2.0, 29.0%, 22.3% and 8.0% of assignments are dropped. Later implementations such as the dropless MoE in MegaBlocks handle expert batches of unequal size with block-sparse computation and no longer need a capacity factor.
Auxiliary-loss-free balancing. Wang et al. (2024) note that an auxiliary loss introduces gradients that interfere with the main objective: too large a coefficient hurts quality, too small fails to balance. Their method gives each expert i a bias bᵢ used only when selecting the top k:
Selection: pick the k experts with the largest sᵢ + bᵢ; weighting: gate values still use the original score sᵢ Update: after each step, subtract γ from bᵢ for overloaded experts and add γ for underloaded ones
The biases are updated only from the load of previous batches and take no part in back-propagation, so they create no interfering gradients and leak no information about future tokens in the current sequence. DeepSeek-V3 adopts this strategy, with a bias update speed γ of 0.001 for the first 14.3T tokens and 0 for the final 500B; it keeps a sequence-wise balance loss with a coefficient of only 0.0001 to prevent extreme imbalance within a single sequence. The technical report says that thanks to good load balance DeepSeek-V3 drops no tokens in training or inference. Part 3 of the example applies the same rule (γ = 0.001) to the skewed routing above: after 300 steps the busiest expert’s load falls from 2.63 to 1.02 times the mean. Qwen3’s MoE models instead use a global-batch load-balancing loss, measuring load over the whole global batch rather than each micro-batch, which the technical report says encourages expert specialisation.
Fine-grained experts, shared experts and expert parallelism
DeepSeekMoE (Dai et al., 2024) proposed two structural changes:
- Fine-grained expert segmentation: keeping total parameters and compute fixed, each expert’s intermediate dimension is cut down and the number of experts increased, with more experts activated. Splitting each of N experts into m gives mN experts with mK activated per token, greatly increasing the number of possible expert combinations;
- Shared expert isolation: a few shared experts are always active for every token to hold common knowledge, reducing redundancy among routed experts.
The paper reports that DeepSeekMoE 2B matches GShard 2.9B, which has 1.5 times the expert parameters and compute, and that DeepSeekMoE 16B matches LLaMA2 7B with about 40% of the compute. Each MoE layer of DeepSeek-V3 has 1 shared expert and 256 routed experts with an intermediate dimension of 2048, and each token activates 8 routed experts; the first 3 layers remain dense FFNs. Routing scores use a sigmoid and are normalised over the selected experts. Qwen3’s MoE models also use fine-grained experts (8 of 128 active) but have no shared expert.
Expert parallelism places different experts of the same layer on different GPUs: each token is sent to the devices holding its experts and the results are sent back, i.e. two all-to-all exchanges. Traffic grows with the number of active experts and of nodes crossed, so DeepSeek-V3 uses node-limited routing: each layer’s routed experts are spread evenly over 64 GPUs in 8 nodes, and each token goes to at most 4 nodes. The technical report estimates that at the same communication cost the number of experts per token could in principle grow from 8 to 13 (4 nodes × 3.2 experts per node). Other forms of parallelism are covered in Distributed Training and Clusters.
What experts learn. The Mixtral paper analysed expert assignments across subsets of The Pile and found the distributions for ArXiv papers, biomedical abstracts (PubMed) and philosophy papers (PhilPapers) very similar, with no obvious topic specialisation; only the synthetic DM Mathematics set differed slightly. Routing showed more syntactic regularities: self in Python, “Question” in English and code indentation often went to the same expert, and consecutive tokens often shared an expert.
State space models: from S4 to Mamba
Attention compute grows quadratically with sequence length and the KV cache grows linearly at inference. State space models (SSMs), which come from control theory, summarise the history recurrently in a hidden state h:
Continuous form: h′(t) = A·h(t) + B·x(t), y(t) = C·h(t) After discretisation with step Δ: hₜ = Ā·hₜ₋₁ + B̄·xₜ, yₜ = C·hₜ
When A, B and C do not depend on the input (linear time-invariant, LTI), unrolling the recurrence gives yₜ = Σⱼ (C·Āʲ·B̄)·xₜ₋ⱼ: the output is the input convolved with a fixed kernel. Training can therefore compute the whole sequence in parallel as a convolution (via FFT), while inference generates step by step with the recurrence. Part 6 of the example confirms that the two algorithms differ by at most 1.4×10⁻¹⁴.
S4 (Gu et al., 2021) introduced a structured parameterisation of A and an efficient way to compute with it, letting SSMs model very long dependencies stably. The paper reports state-of-the-art results on every Long Range Arena task at the time and was the first model to solve the length-16384 Path-X task (88% accuracy); on image and language modelling it substantially closed the gap to Transformers while generating 60× faster.
Mamba (Gu and Dao, 2023) argues that the weakness of LTI models is that they cannot decide what to remember or ignore based on content, which particularly hurts discrete data such as text. Mamba makes B, C and the step Δ functions of the current input (a selective SSM), so the model can propagate or forget information token by token. The price is that there is no longer a fixed convolution kernel, so the paper designs a hardware-aware parallel scan that runs the recurrence in GPU SRAM. Mamba blocks contain no attention and no separate MLP. The paper reports 5× the inference throughput of a Transformer of the same size, compute linear in sequence length and improving performance on sequences up to a million long; Mamba-3B outperforms Transformers of the same size and matches Transformers twice its size in pre-training and downstream evaluation.
Mamba-2 (Dao and Gu, 2024) introduces the state space duality (SSD) framework: once A is restricted to a scalar times the identity, the selective SSM is equivalent to a linear attention with a structured mask, so it can be computed either recurrently or block-wise with matrix multiplications that make better use of GPU matrix units. The paper reports a core layer 2–8× faster than Mamba’s selective scan.
Linear attention and its refinements
Standard attention computes, for each query, a softmax(q·kⱼ)-weighted average. Linear attention (Katharopoulos et al., 2020) replaces the softmax similarity with an inner product of kernel feature maps φ(q)·φ(k) and uses the associativity of matrix multiplication to change the order of computation:
Output oₜ = φ(qₜ)ᵀ·Sₜ / φ(qₜ)ᵀ·zₜ, where Sₜ = Sₜ₋₁ + φ(kₜ)·vₜᵀ and zₜ = zₜ₋₁ + φ(kₜ)
Causal attention thereby becomes an RNN with the matrix Sₜ as its state, and complexity falls from O(N²) to O(N). The paper reports performance similar to vanilla Transformers and up to 4000× faster autoregressive prediction on very long sequences. Part 5 of the example uses φ(x) = elu(x) + 1 and finds a maximum difference of 8.9×10⁻¹⁶ between the parallel and recurrent forms, with the state fixed at 32×32.
The simplest linear attention only accumulates; it neither forgets nor overwrites, and the state fills up with old information. Later work mainly improves the update rule:
| Method | How the state is updated | Reported |
|---|---|---|
| RWKV (Peng et al., 2023) | linear attention with channel-wise time decay (WKV); parallel like a Transformer in training, recurrent like an RNN at inference | trained up to 14 billion parameters |
| RetNet (Sun et al., 2023) | a “retention” mechanism with exponential decay, computable in parallel, recurrent and chunk-wise recurrent form | O(1) inference memory and latency |
| Hyena (Poli et al., 2023) | no recurrent state; implicitly parameterised long convolutions interleaved with data-controlled gating | Transformer quality with 20% less training compute at length 2K; 100× faster than optimised attention at 64K |
| xLSTM (Beck et al., 2024) | exponential gating; sLSTM with scalar memory, mLSTM with matrix memory and a covariance update, fully parallelisable | — |
| Gated DeltaNet (Yang et al., 2024) | gating (global decay) plus the delta rule (precise overwrite by key) | beats Mamba2 and DeltaNet on language modelling, in-context retrieval, length extrapolation and other benchmarks |
The delta rule comes from the classic learning rule of Widrow et al. (1960): before writing a new key–value pair, read out what the key currently stores and write only the difference, Sₜ = Sₜ₋₁ + βₜ·(vₜ − Sₜ₋₁·kₜ)·kₜᵀ. Writing to the same key again then overwrites the old value instead of adding to it. Part 7 of the example writes v1 and then v2 under the same unit key: the delta-rule read-out is 1.9×10⁻¹⁵ from v2, whereas plain linear attention reads v1 + v2, at a distance of 8.13 from v2. The Gated DeltaNet paper argues that gating allows memory to be erased quickly and the delta rule allows it to be modified precisely, that the two are complementary, and builds hybrids that combine Gated DeltaNet layers with sliding-window attention or Mamba2 layers. Triton implementations of many of these layers are available in flash-linear-attention.
Hybrid architectures
Purely recurrent models compress all history into a fixed-size state, and are weaker than attention at exact retrieval and copying over long distances. Large-scale practice is therefore mostly hybrid: most layers use an SSM or linear attention and a few full-attention layers are kept.
Jamba (Lieber et al., 2024) has 8 layers per Jamba block with an attention-to-Mamba ratio of 1:7, and applies MoE every other layer (2 of 16 experts). The released model has 52B parameters in total and 12B active, fits on a single 80GB GPU and supports a 256K context. The paper’s ablations show virtually no difference between ratios of 1:3 and 1:7, with 1:7 more compute-efficient. Table 1 of the paper gives the KV cache for a 256K context in 16 bits: 128GB for LLaMA-2 6.7B, 32GB for both Mistral 7.2B and Mixtral, and 4GB for Jamba. Part 8 of the example recomputes these from the official Jamba and Mixtral configs and gets the same 4 GiB and 32 GiB.
Qwen3-Next-80B-A3B (2025): its model card gives the layout as 12 groups of “3 × (Gated DeltaNet → MoE) + 1 × (gated attention → MoE)”, 48 layers in all; the MoE part has 512 experts with 10 active per token plus 1 shared expert, 80B parameters in total with 3B active, and a native context of 262,144 tokens. From the config, the KV cache of the 12 attention layers at 256K is 6 GiB, and the recurrent state of the 36 Gated DeltaNet layers totals about 18.9 million elements regardless of context length. The model card says the base model outperforms Qwen3-32B-Base on downstream tasks at about 10% of its training cost, with about 10 times its inference throughput for contexts above 32K.
Main considerations when choosing an architecture:
| Aspect | Dense Transformer | MoE Transformer | SSM / linear attention | Hybrid |
|---|---|---|---|---|
| Compute per token | proportional to parameters | proportional to active parameters only | independent of context length | in between |
| Inference memory | weights + KV cache growing with length | all expert weights + KV cache | weights + fixed state | small KV cache + fixed state |
| Exact retrieval and copying | strong | strong | weaker | handled by the attention layers |
| Engineering ecosystem | most mature | needs expert parallelism and load balancing | needs specialised kernels | must support both kinds of kernel |
Diffusion and looped language models
Diffusion language models do not generate left to right. In LLaDA (Nie et al., 2025) the forward process masks tokens at random in a given proportion and the reverse process uses a Transformer to predict all masked positions at once, training on a bound on the likelihood. The paper trains an 8B LLaDA from scratch and reports in-context learning competitive with LLaMA3 8B, instruction following such as multi-turn dialogue after SFT, and better results than GPT-4o on a reversal poem-completion task, arguing that core LLM abilities do not necessarily depend on autoregressive modelling. The official implementation is ML-GSAI/LLaDA.
Looped language models run the same layers several times, trading “recurrence in depth” for more compute without more parameters. The idea goes back to the Universal Transformer (Dehghani et al., 2018), which applies the same Transformer block recurrently in depth with a dynamic per-position halting mechanism; the paper shows that under certain assumptions it is Turing-complete, and reports a 0.9 BLEU improvement over the Transformer on WMT14 English–German. Like the test-time compute scaling in Reasoning Models, it aims to let a model spend more computation when needed.
Runnable example
The code below was run on PyTorch 2.15 (CPU). It downloads the public config.json of six models from Hugging Face (no weights), takes a few seconds, and its output matches the figures in the text.
import json, math, urllib.request, torch
torch.manual_seed(0); torch.set_num_threads(3)
GiB = 1024**3
def cfg(repo): return json.load(urllib.request.urlopen(f'https://huggingface.co/{repo}/resolve/main/config.json'))
# 1) Total and active parameters from config.json
def gqa_attn(c):
h, H, KV = c['hidden_size'], c['num_attention_heads'], c['num_key_value_heads']
hd = c.get('head_dim') or h // H
return h*H*hd*2 + h*KV*hd*2 + (2*hd if 'Qwen' in c['architectures'][0] else 0)
def report(name, c, attn, n_exp, k, d_exp, n_shared=0, d_shared=0, dense_layers=0, d_dense=0):
h, L, V = c['hidden_size'], c['num_hidden_layers'], c['vocab_size']
expert = 3*h*d_exp # SwiGLU expert: three matrices
moe_tot = n_exp*expert + n_shared*3*h*d_shared + n_exp*h
moe_act = k*expert + n_shared*3*h*d_shared + n_exp*h
base = L*(attn + 2*h) + dense_layers*3*h*d_dense + 2*V*h + h
tot = base + (L-dense_layers)*moe_tot; act = base + (L-dense_layers)*moe_act
print(f'{name}: {tot/1e9:.1f}B total ({(tot-2*V*h)/1e9:.1f}B without embedding and output layers), {act/1e9:.2f}B active per token ({act/tot:.1%}); experts hold {(L-dense_layers)*n_exp*expert/tot:.1%}')
m = cfg('mistralai/Mixtral-8x7B-v0.1')
report('Mixtral 8x7B', m, gqa_attn(m), m['num_local_experts'], m['num_experts_per_tok'], m['intermediate_size'])
for repo in ('Qwen/Qwen3-30B-A3B', 'Qwen/Qwen3-235B-A22B'):
q = cfg(repo); report(repo.split('/')[1], q, gqa_attn(q), q['num_experts'], q['num_experts_per_tok'], q['moe_intermediate_size'])
d = cfg('deepseek-ai/DeepSeek-V3'); h, H = d['hidden_size'], d['num_attention_heads']
mla = (h*d['q_lora_rank'] + d['q_lora_rank'] + d['q_lora_rank']*H*(d['qk_nope_head_dim']+d['qk_rope_head_dim'])
+ h*(d['kv_lora_rank']+d['qk_rope_head_dim']) + d['kv_lora_rank'] + d['kv_lora_rank']*H*(d['qk_nope_head_dim']+d['v_head_dim'])
+ H*d['v_head_dim']*h)
report('DeepSeek-V3', d, mla, d['n_routed_experts'], d['num_experts_per_tok'], d['moe_intermediate_size'],
d['n_shared_experts'], d['moe_intermediate_size'], d['first_k_dense_replace'], d['intermediate_size'])
# 2) Top-k routing, the Switch auxiliary loss and the capacity factor
N, K, T, dm = 8, 2, 4096, 64
x = torch.randn(T, dm)
W = torch.randn(dm, N) * 0.15
skew = torch.tensor([1.5, 0.8, 0.3, 0., 0., -0.3, -0.6, -1.0]) # an artificial routing preference: expert 0 is the most popular
def route(logits, k):
p = logits.softmax(-1); topv, topi = p.topk(k, -1)
return p, topi, topv / topv.sum(-1, keepdim=True)
p, topi, gates = route(x @ W + skew, K)
load = torch.bincount(topi.flatten(), minlength=N).float()
f = torch.bincount(topi[:, 0], minlength=N).float() / T; P = p.mean(0)
print(f'Top-{K} routing ({N} experts, {T} tokens): tokens per expert {load.int().tolist()}, max/mean = {load.max()/load.mean():.2f}')
print(f' Switch auxiliary loss N·Σfᵢ·Pᵢ = {N*(f*P).sum():.3f} (1.000 when perfectly uniform)')
for cf in (1.0, 1.25, 2.0):
cap = math.floor(T*K/N*cf); dropped = (load - cap).clamp(min=0).sum()
print(f' Capacity factor {cf}: capacity {cap} per expert, {int(dropped)} overflowing assignments dropped ({dropped/(T*K):.1%})')
# 3) Auxiliary-loss-free balancing: adjust routing biases only, not the gate weights
b = torch.zeros(N); u = 0.001; s = torch.sigmoid(x @ W + skew)
for step in range(1, 3001):
idx = torch.randint(0, T, (512,)); sc = s[idx]
sel = (sc + b).topk(K, -1).indices
c = torch.bincount(sel.flatten(), minlength=N).float()
b += u * torch.sign(c.mean() - c)
if step in (1, 300, 3000):
sel_all = (s + b).topk(K, -1).indices; la = torch.bincount(sel_all.flatten(), minlength=N).float()
print(f' Bias update step {step:>4}: max/mean load = {la.max()/la.mean():.2f}, bias of expert 0 {b[0]:+.3f}')
# 4) An 8-expert, top-2 MoE feed-forward layer (SwiGLU experts)
class MoE(torch.nn.Module):
def __init__(s, d, dff, n=8, k=2):
super().__init__(); s.k = k; s.router = torch.nn.Linear(d, n, bias=False)
s.w1 = torch.nn.Parameter(torch.randn(n, d, dff)*d**-0.5); s.w3 = torch.nn.Parameter(torch.randn(n, d, dff)*d**-0.5)
s.w2 = torch.nn.Parameter(torch.randn(n, dff, d)*dff**-0.5)
def forward(s, x):
p, idx, g = route(s.router(x), s.k); y = torch.zeros_like(x)
for e in range(s.w1.shape[0]):
tok, slot = (idx == e).nonzero(as_tuple=True)
if len(tok) == 0: continue
xe = x[tok]; he = torch.nn.functional.silu(xe @ s.w1[e]) * (xe @ s.w3[e])
y.index_add_(0, tok, g[tok, slot, None] * (he @ s.w2[e]))
return y
moe = MoE(256, 512); xx = torch.randn(1024, 256); yy = moe(xx)
tot = sum(p.numel() for p in moe.parameters()); act = moe.router.weight.numel() + 2*3*256*512
print(f'MoE layer: output shape {tuple(yy.shape)}, {tot/1e6:.2f}M parameters, {act/1e6:.2f}M active per token (about 2x the compute and 8x the parameters of one dense FFN of the same width)')
# 5) Linear attention: the parallel and recurrent forms agree, and the state has a fixed size
Tn, dk = 512, 32
q, k, v = torch.randn(Tn, dk, dtype=torch.float64), torch.randn(Tn, dk, dtype=torch.float64), torch.randn(Tn, dk, dtype=torch.float64)
phi = lambda z: torch.nn.functional.elu(z) + 1
Q, Kf = phi(q), phi(k)
A = (Q @ Kf.T).tril(); par = (A @ v) / A.sum(-1, keepdim=True)
S = torch.zeros(dk, dk, dtype=torch.float64); z = torch.zeros(dk, dtype=torch.float64); rec = []
for t in range(Tn):
S += torch.outer(Kf[t], v[t]); z += Kf[t]; rec.append((Q[t] @ S) / (Q[t] @ z))
print(f'Linear attention: max difference between parallel and recurrent forms {(par - torch.stack(rec)).abs().max():.1e}; recurrent state {dk}×{dk} elements, independent of sequence length')
# 6) A linear time-invariant SSM: recurrence equals convolution (the starting point of S4)
Ns, Ls = 16, 256
Ad = torch.diag(torch.rand(Ns, dtype=torch.float64) * 0.9); Bv = torch.randn(Ns, 1, dtype=torch.float64); Cv = torch.randn(1, Ns, dtype=torch.float64)
uu = torch.randn(Ls, dtype=torch.float64); hs = torch.zeros(Ns, 1, dtype=torch.float64); yr = []
for t in range(Ls): hs = Ad @ hs + Bv * uu[t]; yr.append((Cv @ hs).item())
Kern = torch.stack([(Cv @ torch.matrix_power(Ad, j) @ Bv).squeeze() for j in range(Ls)])
yc = torch.stack([(Kern[:t+1].flip(0) * uu[:t+1]).sum() for t in range(Ls)])
print(f'SSM: max difference between recurrent and convolutional outputs {(torch.tensor(yr, dtype=torch.float64) - yc).abs().max():.1e}; once Mamba makes B, C and Δ input-dependent there is no fixed kernel, so it uses a parallel scan')
# 7) The delta rule: write the same key twice; linear attention adds up, the delta rule overwrites
dk = 64; kk = torch.nn.functional.normalize(torch.randn(dk, dtype=torch.float64), dim=0)
v1, v2 = torch.randn(dk, dtype=torch.float64), torch.randn(dk, dtype=torch.float64)
S_lin = torch.outer(v1, kk) + torch.outer(v2, kk)
S_del = torch.zeros(dk, dk, dtype=torch.float64)
for vv in (v1, v2): S_del = S_del + torch.outer(vv - S_del @ kk, kk) # delta rule with β = 1
print(f'Delta rule: distance of the read-out from v2 {(S_del @ kk - v2).norm():.1e}; linear attention reads v1+v2, distance from v2 {(S_lin @ kk - v2).norm():.2f}')
# 8) KV cache of hybrid models (BF16, 256K context)
def kv(layers, kvh, hd, T=262144): return 2*layers*kvh*hd*T*2
j = cfg('ai21labs/Jamba-v0.1'); n_attn = j['num_hidden_layers'] // j['attn_layer_period']
print(f'Jamba: {n_attn} attention layers out of {j["num_hidden_layers"]}, KV cache {kv(n_attn, j["num_key_value_heads"], j["hidden_size"]//j["num_attention_heads"])/GiB:.0f} GiB; '
f'Mixtral (attention in all 32 layers) {kv(m["num_hidden_layers"], m["num_key_value_heads"], m["hidden_size"]//m["num_attention_heads"])/GiB:.0f} GiB')
qn = cfg('Qwen/Qwen3-Next-80B-A3B-Instruct'); na = qn['num_hidden_layers'] // qn['full_attention_interval']
st = (qn['num_hidden_layers'] - na) * qn['linear_num_value_heads'] * qn['linear_key_head_dim'] * qn['linear_value_head_dim']
print(f'Qwen3-Next-80B-A3B: {na} gated-attention layers out of {qn["num_hidden_layers"]}, KV cache {kv(na, qn["num_key_value_heads"], qn["head_dim"])/GiB:.0f} GiB; '
f'the recurrent state of the {qn["num_hidden_layers"]-na} Gated DeltaNet layers totals {st/1e6:.1f}M elements, independent of context length')
Output:
Mixtral 8x7B: 46.7B total (46.4B without embedding and output layers), 12.88B active per token (27.6%); experts hold 96.6%
Qwen3-30B-A3B: 30.5B total (29.9B without embedding and output layers), 3.35B active per token (11.0%); experts hold 95.0%
Qwen3-235B-A22B: 235.1B total (233.8B without embedding and output layers), 22.19B active per token (9.4%); experts hold 96.6%
DeepSeek-V3: 671.0B total (669.2B without embedding and output layers), 37.55B active per token (5.6%); experts hold 97.4%
Top-2 routing (8 experts, 4096 tokens): tokens per expert [2703, 1681, 1062, 755, 770, 517, 462, 242], max/mean = 2.64
Switch auxiliary loss N·Σfᵢ·Pᵢ = 1.650 (1.000 when perfectly uniform)
Capacity factor 1.0: capacity 1024 per expert, 2374 overflowing assignments dropped (29.0%)
Capacity factor 1.25: capacity 1280 per expert, 1824 overflowing assignments dropped (22.3%)
Capacity factor 2.0: capacity 2048 per expert, 655 overflowing assignments dropped (8.0%)
Bias update step 1: max/mean load = 2.63, bias of expert 0 -0.001
Bias update step 300: max/mean load = 1.02, bias of expert 0 -0.187
Bias update step 3000: max/mean load = 1.03, bias of expert 0 -0.155
MoE layer: output shape (1024, 256), 3.15M parameters, 0.79M active per token (about 2x the compute and 8x the parameters of one dense FFN of the same width)
Linear attention: max difference between parallel and recurrent forms 8.9e-16; recurrent state 32×32 elements, independent of sequence length
SSM: max difference between recurrent and convolutional outputs 1.4e-14; once Mamba makes B, C and Δ input-dependent there is no fixed kernel, so it uses a parallel scan
Delta rule: distance of the read-out from v2 1.9e-15; linear attention reads v1+v2, distance from v2 8.13
Jamba: 4 attention layers out of 32, KV cache 4 GiB; Mixtral (attention in all 32 layers) 32 GiB
Qwen3-Next-80B-A3B: 12 gated-attention layers out of 48, KV cache 6 GiB; the recurrent state of the 36 Gated DeltaNet layers totals 18.9M elements, independent of context length
Notes: active parameters in part 1 include the embedding and output layers and count the router as active; the routing skew in parts 2 and 3 is set by hand to demonstrate load statistics and bias updates and does not represent any real model; part 4 implements the MoE feed-forward layer with a loop over experts for readability, whereas real systems gather each expert’s tokens into a batch and use grouped matrix multiplication or block-sparse kernels.
Exercises
- Unit project: replace the feed-forward layer of your small GPT with the
MoEclass from part 4 (8 experts, top-2) and compare validation loss with the dense version on the same data; every few steps, count the tokens each expert receives, with no auxiliary loss, with the Switch auxiliary loss (α = 0.01) and with bias updates, and compare the load distributions. - Following the Hugging Face MoE blog, extend part 1 of the example to the
config.jsonof another open MoE model, compute total and active parameters and check them against its model card. - Install Mamba as described in the official repository, run its example and compare throughput and memory of Mamba and a Transformer of the same size on one GPU at different generation lengths.
- Replace some attention layers of a small model with Gated DeltaNet layers from flash-linear-attention (for example keeping one attention layer in every four), and compare training speed, validation loss and accuracy on a simple synthetic key–value retrieval task.
Suggested reading order
Start with the Hugging Face MoE blog for the overall picture, then read about routing and load balancing in the gating and balancing sections of Shazeer et al. (2017), Switch Transformer section 2, DeepSeekMoE section 3 and section 2.1.2 of the DeepSeek-V3 technical report. For SSMs, read The Annotated S4 and section 3 of the Mamba paper, then Tri Dao’s blog on Mamba-2; for linear attention, section 3 of Katharopoulos et al. (2020) and the gated delta rule sections of the Gated DeltaNet paper. For hybrids, read the Jamba paper and the Qwen3-Next model card. Then move on to Distributed Training and Clusters and How LLMs Generate Text to see how expert parallelism and the KV cache play out at the systems level.
FAQ
Why does an MoE model save compute at inference but not memory?
Each token passes through only a few experts, so compute per token is close to that of a dense model with the same number of active parameters; but which expert will be chosen is not known in advance, so all expert weights must stay in memory or be quickly reachable. Mixtral 8x7B activates about 12.9B parameters per token while all 46.7B must be held in memory. MoE pays off most with large batches in which every expert gets enough tokens; with a single request and small batches, the bandwidth needed to read expert weights is often the bottleneck.
Do experts really specialise by subject or domain?
Not necessarily. The Mixtral paper analysed expert assignments on subsets of The Pile and found the distributions for ArXiv, PubMed and PhilPapers text very similar, with no obvious topic specialisation; routing showed more syntactic regularities, for example ‘self’ in Python, ‘Question’ in English and code indentation often going to the same expert, and consecutive tokens often sharing an expert. DeepSeekMoE’s fine-grained and shared experts are designed precisely to make experts more specialised.
Why does Mamba not need a KV cache at inference?
A Transformer attends to all previous tokens at each step, so it caches the keys and values of the whole history and the cache grows linearly with context. State space models such as Mamba compress the history into a fixed-size state; each step updates the state from the current input and reads out the output, and the state size does not depend on context length. The price is that history is compressed, so exact retrieval and copying over long distances are weaker than with attention, which is why hybrids keep a few attention layers.
How are linear attention and Mamba related?
Both can be written as a matrix state that is updated recurrently and read out by a query. Katharopoulos et al. (2020) showed that once softmax is replaced by a kernel feature map, causal attention can be written as an RNN; the Mamba-2 paper went further with state space duality (SSD), showing that a class of structured SSMs and masked linear attention are two ways of writing the same computation, and used this to build a core layer 2–8× faster than Mamba’s. Gated DeltaNet improves the state update rule within this framework.
Will diffusion language models replace autoregressive models?
There is no settled answer yet. LLaDA (2025) trained an 8B masked diffusion language model from scratch and reports in-context learning competitive with LLaMA3 8B and better results than GPT-4o on a reversal poem-completion task, suggesting that core LLM abilities do not necessarily depend on autoregression. Mainstream open and commercial models are still autoregressive Transformers, and the inference efficiency, long-form generation and tool use of diffusion language models are still being studied.