On this page
An eight-expert layer routes every token to just two feed-forward networks. On paper that looks like a 4x smaller model, until you try to load the checkpoint onto a GPU and discover all eight experts still need memory. How can per-token arithmetic stay sparse while weight residency stays huge?
In a standard Transformer, a single feed-forward network (FFN) transforms every token after attention. Mixture of Experts (MoE) replaces that single FFN with parallel expert FFNs and a lightweight router (gating network) that chooses a top- subset for each token at every layer.[1] Attention, embeddings, and norms usually remain shared.[2][3]
That design decouples total parameter capacity (all experts stored in memory) from active compute per token (only the selected experts). The trade-off shifts from raw FLOPs to weight memory, load balance, token overflow, and cross-GPU dispatch.
From one FFN to many experts
Given a token hidden state , a linear router produces logits, converts them to probabilities , picks the top experts, and blends their outputs:
Follow one 4-dimensional token through a 4-expert top-2 Mixtral-style router with logits [-0.65, -1.77, -1.35, -3.00]:
- Softmax probabilities:
[0.521, 0.170, 0.259, 0.050]. - Top-2 selection: Expert 1 (
0.521) and Expert 3 (0.259). - Renormalize: and .
- Compute & blend: Run only and and compute .
Let's run the exact top-2 router in PyTorch:
import torch
gate = torch.tensor([[-0.65, 0., 0., 0.], [-1.77, 0., 0., 0.],
[-1.35, 0., 0., 0.], [-3.00, 0., 0., 0.]])
x = torch.tensor([1.0, 0.0, 0.0, 0.0])
probs = torch.softmax(gate @ x, dim=0)
top_probs, selected = torch.topk(probs, k=2)
weights = top_probs / top_probs.sum()
# Four simple diagonal-like expert projections mapping R^4 -> R^4
experts = torch.zeros(4, 4, 4)
experts[0, 0, 0], experts[1, 2, 0], experts[2, 1, 0], experts[3, 3, 0] = 2.0, 4.0, 3.0, 5.0
blended = weights @ (experts[selected] @ x)
print("selected experts:", (selected + 1).tolist())
print("renormalized weights:", [round(w, 3) for w in weights.tolist()])
print("blended output:", [round(v, 3) for v in blended.tolist()])selected experts: [1, 3]
renormalized weights: [0.668, 0.332]
blended output: [1.336, 0.995, 0.0, 0.0]Why sparse activation separates compute from memory
Because only FFN blocks are replicated while attention and embeddings stay shared, Mixtral 8x7B totals 46.7B parameters (not B) and activates 12.9B parameters per token under top-2 routing.[2]
| Property | Dense peer (~13B) | Mixtral 8x7B (top-2 of 8) |
|---|---|---|
| Total parameters (memory) | ~13B | ~46.7B |
| Active parameters (FLOPs) | ~13B | ~12.9B |
| Extra runtime work | None | Routing, token grouping, all-to-all dispatch |
Active parameters govern per-token FLOPs; total parameters govern VRAM weight residency. A model with 3B shared weights and eight 2B expert partitions activates only 7B weights (14 GB BF16) per token, yet still requires 38 GB BF16 to hold all 19B weights in memory.

If an MoE has 46.7B total parameters and 12.9B active parameters per token, which number drives FLOPs and which number drives memory residency?
Answer
Active parameters mostly drive per-token expert FLOPs. Total parameters drive checkpoint size and the weight memory the serving system must keep available.
Expert choice vs. token choice routing
Standard token-choice routing lets each token pick its top experts, guaranteeing every token gets experts at the risk of overloading popular experts. Expert-choice routing flips the direction: each expert selects its top-scoring fixed bucket of tokens from the batch.[5]
That guarantees balanced expert buckets, but introduces two subtle catches:
- Uncovered tokens: Some tokens can land in zero expert buckets (passing through the residual stream alone) while others land in multiple buckets.
- Causality leak in decoders: Because an expert ranks tokens across the batch, a future token with a higher score (
0.9) can knock an earlier token (0.6) out of the bucket despite causal attention masking. Autoregressive decoders therefore need prefix-consistent routing.
import numpy as np
# 3 experts (rows) each pick top-2 tokens from 5 tokens t0..t4 (columns)
scores = np.array([
[0.90, 0.80, 0.10, 0.05, 0.01],
[0.85, 0.20, 0.75, 0.10, 0.02],
[0.15, 0.25, 0.80, 0.70, 0.03],
])
buckets = np.argsort(-scores, axis=1, kind="stable")[:, :2]
counts = np.bincount(buckets.ravel(), minlength=5)
print("assignments per token:", counts.tolist(), "-> uncovered:", [f"t{i}" for i in np.flatnonzero(counts == 0)])
# Future token (0.9) displaces earlier token (0.6) in a 1-slot bucket
print("prefix winner:", ["earlier"][int(np.argmax([0.6]))])
print("with future token:", ["earlier", "future"][int(np.argmax([0.6, 0.9]))])assignments per token: [2, 1, 2, 1, 0] -> uncovered: ['t4']
prefix winner: earlier
with future token: futureWhy routers collapse without load balancing
Left to pure task loss, routers suffer from rich-get-richer collapse: an expert that wins slightly more tokens early gets more gradient updates, improves faster, attracts still more tokens, and starves its peers. You end up paying VRAM for every expert while only training a few.
The auxiliary load-balancing loss
Switch Transformer counters collapse with a differentiable penalty combining each expert's actual assignment fraction and its mean router probability across the batch:[4]
Hard counts stop gradients, so updates flow through to push down probabilities on heavily loaded experts. Under uniform routing (), the unscaled factor . On a skewed batch [0.60, 0.20, 0.15, 0.05] with mean probabilities [0.55, 0.22, 0.15, 0.08], it jumps to .
import torch
# 1. Skewed 4-expert batch: 4 * sum(f * p) = 1.602 vs uniform 1.0
f = torch.tensor([0.60, 0.20, 0.15, 0.05])
p = torch.tensor([0.55, 0.22, 0.15, 0.08])
print("skewed 4-expert score:", round((4 * torch.dot(f, p)).item(), 3))
# 2. Counterexample: Expert 2 gets 0 tokens yet score = 0.90 < 1.0!
probs = torch.tensor([[0.51, 0.09, 0.40], [0.09, 0.51, 0.40]])
winners = probs.argmax(dim=1)
fracs = torch.bincount(winners, minlength=3).float() / probs.shape[0]
score = 3 * torch.dot(fracs, probs.mean(dim=0))
print("dead-expert fractions:", fracs.tolist(), "score:", round(score.item(), 2))skewed 4-expert score: 1.602
dead-expert fractions: [0.5, 0.5, 0.0] score: 0.9![Left: Switch auxiliary balance terms f_i * p_i for four experts on a skewed batch are 0.330, 0.044, 0.0225, and 0.004, yielding N * sum(f_i * p_i) = 4 * 0.4005 = 1.602 versus uniform 1.00. Right: two-token, three-expert counterexample routing probabilities [[0.51, 0.09, 0.40], [0.09, 0.51, 0.40]] produce fractions [0.5, 0.5, 0.0] and score 3 * 0.30 = 0.90 < 1.0 even though E2 receives zero tokens.](https://assets.leetllm.com/v1/fdf522b0c5d5/fundamentals/mixture-of-experts-architecture/illustrations/_generated/balancing_objective_and_counterexample_dark.png)
Router z-loss for numerical stability
Even when load is balanced, drifting router logits can destabilize mixed-precision training. Router z-loss penalizes the squared log-partition function averaged over tokens.[6] Shifting logits [\log 0.75, \log 0.25] upward by +3 leaves softmax probabilities untouched at [0.75, 0.25] while raising log-sum-exp from 0 to 3 and z-loss from 0 to 9, keeping logit magnitudes bounded without distorting expert selection.
Capacity factor and token overflow
Fixed-shape GPU kernels pre-allocate a static token buffer per expert scaled by a capacity factor :
For tokens, top-, and experts, the uniform share is 256 slots per expert (308 at ). When a hot expert receives 400 assignments at , 144 overflow. Runtimes either drop overflowing assignments (leaving the residual pass-through),[4] reroute them to spare experts, or run dropless variable-length grouped GEMMs over all 400 assignments.[7]

How modern architectures scale the idea
Modern frontier MoEs shifted from coarse 8-expert pools to fine-grained pools of 160 to 256 experts paired with always-on shared experts and auxiliary-loss-free balancing:
| Model | Total / Active | Experts per MoE layer | Key routing innovation |
|---|---|---|---|
| Mixtral 8x7B[2] | 46.7B / 12.9B | 8 routed (top-2), SwiGLU[8] | Clean coarse-grained softmax top-2 |
| DeepSeek-V2[3] | 236B / 21B | 160 routed (top-6) + 2 shared | Fine-grained experts, shared experts, device-limited routing, MLA |
| DeepSeek-V3[9] | 671B / 37B | 256 routed (top-8) + 1 shared | Sigmoid affinity + bias-adjusted auxiliary-loss-free balancing |
| DeepSeek V4 Flash 0731[10][11] | 284B / 13B | 256 routed (top-6) + 1 shared | affinity, hash routing in first 3 blocks |
| GLM-5.3[12][13][14][15] | 744B / ~40B | 256 routed (top-8) + 1 shared | 3 dense + 75 MoE layers, routed scaling factor 2.5 |
| Qwen3.6-35B-A3B[16] | 35B / 3B | 256 routed (top-8) + 1 shared | Interleaved Gated DeltaNet + gated attention |

DeepSeek-V3's auxiliary-loss-free balancing computes sigmoid affinities , adds a dynamically updated bias only when picking top-8 expert IDs, and weights expert outputs using the original unbiased affinities (backed by a tiny sequence-wise balance guard), balancing load without fighting the language-modeling gradient.[9]
Note also that FFN sparsity and sequence mixing are independent choices: Qwen3.6-35B-A3B interleaves Gated DeltaNet layers with gated attention so both the feed-forward and memory paths stay lean.
Serving an MoE on real hardware
Sparse FLOPs do not automatically translate to lower latency: experts span GPUs, hidden states cross NVLink or InfiniBand, and small decode batches shrink expert matmuls.
Expert parallelism, wire traffic, and grouped GEMMs
While tensor parallelism (TP) shards each expert's matrices across GPUs, expert parallelism (EP) places whole experts on different GPUs and runs all-to-all dispatch and all-to-all combine.[7][17] Large serving clusters mix both (for example, DeepSeek-V3 pairs TP4 attention with EP320 decode and hot-expert replication via EPLB).[9][17]
If a fraction of assignments target remote GPUs, transferring an -element vector at bytes round-trip costs . When one token picks two experts on the same remote GPU, per-destination coalescing sends the input once, runs both experts remotely, and returns one already-weighted combined output, halving wire bytes (16 KiB vs. 32 KiB for a 4,096-wide BF16 vector) with identical expert math (though actual latency still depends on overlap and fixed overheads).

Inside each GPU, batched expert execution sorts assignments by expert ID for dense grouped GEMMs, applies each gate weight once, and scatter-adds weighted outputs back to each token's row so no route overwrites another:
import torch
inputs = torch.tensor([[1.0, 2.0], [3.0, 4.0], [5.0, 6.0]])
token_ids = torch.tensor([0, 1, 2, 0, 2])
expert_ids = torch.tensor([2, 0, 2, 1, 0])
gate_weights = torch.tensor([0.25, 1.0, 0.6, 0.75, 0.4])
scales = torch.tensor([2.0, -1.0, 0.5]) # Simple per-expert transforms
# Sort by expert for contiguous grouped GEMM, then weighted scatter-add by token ID
order = torch.argsort(expert_ids, stable=True)
p_tok, p_exp, p_w = token_ids[order], expert_ids[order], gate_weights[order]
p_out = inputs[p_tok] * scales[p_exp].unsqueeze(1)
combined = torch.zeros_like(inputs).index_add(0, p_tok, p_out * p_w.unsqueeze(1))
print("packed token order:", p_tok.tolist())
print("restored weighted rows:", [[round(v, 3) for v in row] for row in combined.tolist()])packed token order: [1, 2, 0, 0, 2]
restored weighted rows: [[-0.625, -1.25], [6.0, 8.0], [5.5, 6.6]]On consumer GPUs where the full expert pool exceeds VRAM, combining weight quantization with CPU/SSD expert offloading keeps shared layers on GPU and streams selected experts on demand.
When MoE is worth the complexity
Large prefill and high-concurrency decode batches amortize routing and all-to-all dispatch across many tokens per expert; single-request decode (batch = 1) exposes fixed launch and interconnect overhead every step. Evaluate MoE against a matched dense baseline across quality, p95 latency, and throughput together:
| Decision signal | Dense is usually simpler | MoE shines |
|---|---|---|
| Traffic shape | Low batch size, strict interactive p95 latency | High batch concurrency or offline throughput |
| Memory budget | Tight fixed VRAM ceiling | Enough memory/sharding for the full expert pool |
| Interconnect | Slow cross-node links | High-bandwidth NVLink / InfiniBand |
| Serving stack | Standard dense kernels | Grouped GEMMs, EP dispatch, load telemetry |

Diagnosing common MoE surprises
- 7B-active model OOMs on a 16 GB GPU: Always size VRAM from total parameters (plus KV cache and workspace), never active parameters.
- Uniform long-run histogram, degraded accuracy: Check per-step bursty overflow, dropped top-2 branches, and z-loss logit blowup separately.
- "Math expert" myths: Mixtral's routing analysis found experts specializing strongly in syntax and formatting (like indentation and Python
self) rather than neat high-level domains like "math" vs. "history."[2]