LeetLLM
My PlanLearnGlossaryTracksPracticeBlog
LeetLLM

Your go-to resource for mastering AI & LLM systems.

Product

  • Learn
  • Glossary
  • Tracks
  • Practice
  • Blog
  • RSS

Legal

  • Terms of Service
  • Privacy Policy

© 2026 LeetLLM. All rights reserved.

All Topics
Your Progress
0%

0 of 196 articles completed

🛠️Computing Foundations0/9
Git, Shell, Linux for AIDocker for Reproducible AIPython for AI EngineeringNumPy and Tensor ShapesCUDA for ML TrainingMPS & Metal for ML on MacData Structures for AISQL and Data ModelingAlgorithms for ML Engineers
📊Math & Statistics0/9
Gradients and BackpropVectors, Matrices & TensorsLinear Algebra for MLAdam, Momentum, SchedulersProbability for Machine LearningBayesian Inference from EvidenceStatistics and UncertaintyDistributions and SamplingHypothesis Tests, Intervals, and pass@k
📚Preparation & Prerequisites0/13
Neural Networks from ScratchCNNs from ScratchTraining & BackpropagationSoftmax, Cross-Entropy & OptimizationRNNs, LSTMs, GRUs, and Sequence ModelingAutoencoders and VAEsThe Transformer Architecture End-to-EndLanguage Modeling & Next TokensFrom GPT to Modern LLMsPrompt Engineering FundamentalsCalling LLM APIs in ProductionFirst AI App End-to-EndThe LLM Lifecycle
🧮ML Algorithms & Evaluation0/15
Linear Regression from ScratchLogistic Regression and MetricsDecision Trees, Forests, and BoostingReinforcement Learning BasicsValidation and LeakageStatistical Learning and GeneralizationConformal Prediction and UncertaintyClustering and PCAProbabilistic Generative ModelsCore Retrieval AlgorithmsDecoding AlgorithmsExperiment Design and A/B TestingCausal Inference and CounterfactualsPyTorch Training LoopsDataset Pipelines and Data Quality
📦Production ML Systems0/6
Feature Engineering for Production MLBatch and Streaming Feature PipelinesGradient Boosted Trees in ProductionRanking and Recommendation SystemsForecasting and Anomaly DetectionMonitoring Predictive Models
🧪Core LLM Foundations0/8
The Bitter Lesson & ComputeBPE, WordPiece, and SentencePieceStatic to Contextual EmbeddingsPerplexity & Model EvaluationFile Ingestion for AIChunking StrategiesLLM Benchmarks & LimitationsInstruction Tuning & Chat Templates
🧰Applied LLM Engineering0/25
Dimensionality Reduction for EmbeddingsCoT, ToT & Self-Consistency PromptingFunction Calling & Tool UseMCP & Tool Protocol StandardsContext EngineeringPrompt Injection DefenseResponsible AI GovernancePrivacy-Preserving Machine LearningData Labeling and Human FeedbackEvaluating AI AgentsProduction RAG PipelinesHybrid Search: Dense + SparseReranking and Cross-Encoders for RAGRAG Evaluation for Reliable AnswersLLM-as-a-Judge EvaluationBias & Fairness in LLMsHallucination Detection & MitigationLLM Observability & MonitoringExperiment Tracking with MLflow and W&BPrompt Optimization with DSPyModel Versioning & DeploymentSemantic Caching & Cost OptimizationLLM Cost Engineering & Token EconomicsModel Gateways, Routing, and FallbacksDesign an Automated Support Agent
🎓Portfolio Capstones0/9
Capstone: Delivery ETA PredictionCapstone: Product RankingCapstone: Demand ForecastingCapstone: Image Damage ClassifierCapstone: Production ML PipelineCapstone: Document QACapstone: Eval DashboardCapstone: Fine-Tuned ClassifierCapstone: Reproducible ML Study
🧠Transformer Deep Dives0/8
Sentence Embeddings & Contrastive LossEmbedding Similarity & QuantizationScaled Dot-Product AttentionVision Transformers and Image EncodersPositional Encoding: RoPE & ALiBiLayer Normalization: Pre-LN vs Post-LNMechanistic InterpretabilityDecoding Strategies: Greedy to Nucleus
🧬Advanced Training & Adaptation0/17
Scaling Laws & Compute-Optimal TrainingPre-training Data at ScaleBuild GPT from Scratch LabJAX for PyTorch ResearchersContinued Pretraining for Domain ShiftSynthetic Data PipelinesSupervised Fine-Tuning PipelineMixed Precision TrainingDistributed Training: FSDP & ZeROLoRA & Parameter-Efficient TuningTraining Run OperationsReward Modeling from Preference DataRLHF & DPO AlignmentConstitutional AI & Red TeamingRLVR & Verifiable RewardsKnowledge Distillation for LLMsModel Merging and Weight Interpolation
🤖Advanced Agents & Retrieval0/16
Vector DB Internals: HNSW & IVFAdvanced RAG: HyDE & Self-RAGGraphRAG & Knowledge GraphsRAG Security & Access ControlStructured Output GenerationReAct & Plan-and-ExecuteGuardrails & Safety FiltersCode Generation & SandboxingComputer-Use / GUI / Browser AgentsHuman-in-the-Loop Agent ArchitectureAI Coding Workflow with AgentsAgent Memory & PersistenceAgent Failure & RecoveryRecursive Language Models (RLM)Multi-Agent OrchestrationCapstone: Production Agent
⚡Inference & Production Scale0/31
Inference: TTFT, TPS & KV CacheMulti-Query & Grouped-Query AttentionKV Cache & PagedAttentionPrefix Caching and Prompt CachingFlashAttention & Memory EfficiencyContinuous Batching & SchedulingScaling LLM InferenceModel Parallelism for LLM InferenceAccelerator Architecture Field GuideCorrect GPU Profiling and BenchmarkingGPU Kernel Performance Engineering LabGPU Parallel Primitives LabGPU Compilers and Kernel LanguagesGEMM From Naive CUDA to Tensor CoresLow-Precision GPU ProgrammingGPU Runtime Execution LabAI-Generated Kernel EngineeringModel Quantization: GPTQ, AWQ & GGUFLocal LLM DeploymentSLM Specialization & Edge DeploymentSpeculative DecodingLong Context Window ManagementMixture of Experts ArchitectureMamba & State Space ModelsReasoning & Test-Time ComputeAdvanced MLOps & DevOps for AIGPU Serving & AutoscalingGPU Failure OperationsDistributed Inference Data PlaneServing Benchmark EngineeringA/B Testing for LLMs
🏗️System Design Capstones0/9
Content Moderation SystemCode Completion SystemMulti-Tenant LLM PlatformLLM-Powered Search EngineVision-Language Models & CLIPMultimodal LLM ArchitectureDiffusion Models: Images & TextReal-Time Voice AI AgentReasoning Agent System Design
🎤AI Lab Interviewing0/4
AI Lab Coding Interview: Python SystemsAI Lab System Design InterviewAI Lab Behavioral InterviewAI Lab Technical Presentation
🔬Project Deep Dives0/17
Deep Dive - vLLMDeep Dive - SkyRLDeep Dive - FlashAttentionDeep Dive - FlashInferDeep Dive - DeepGEMMDeep Dive - NCCLDeep Dive - MegatronDeep Dive - DeepSpeedDeep Dive - RayDeep Dive - MLflowDeep Dive - PyTorchDeep Dive - TransformersDeep Dive - SGLangDeep Dive - slimeDeep Dive - DeepEPDeep Dive - TinkerDeep Dive - Light-PEFT
Back to Topics
LearnInference & Production ScaleMixture of Experts Architecture
🧠HardTransformer Architecture

Mixture of Experts Architecture

Trace top-k MoE routing by hand, separate active FLOPs from full expert residency, and measure dense-vs-sparse serving from Mixtral through GLM-5.2 and DeepSeek V4 Flash.

37 min read
Learning path
Step 158 of 196 in the full curriculum
Long Context Window ManagementMamba & State Space Models

Personalize this lesson

Adapt explanations and teaching visuals to your background and preferred voice.

Suppose a serving team wants one model to handle code, math, and tool use, but each request needs only a small slice of that capability. In a dense Transformer, its Feed-Forward Network (FFN) processes every token with the same weights, so adding capacity raises work for every token.

Mixture of Experts (MoE) breaks that coupling. It keeps many expert FFNs and uses a lightweight router to score them, then sends each token to only a few highest-scoring experts. One token can activate a small amount of expert compute while the model stores a much larger capacity pool.

The tradeoff moves rather than disappears: weights still need a home, routed token states may cross GPUs, and skewed choices can overload one expert. For one token, the router chooses a few experts and blends their outputs. Skipped experts do no expert computation for that token, but their weights still have to be stored or fetched for other tokens.

Switch Transformer[1]Reference 1Switch Transformers: Scaling to Trillion Parameter Models with Simple and Efficient Sparsity.https://arxiv.org/abs/2101.03961 showed that sparse activation could reach trillion-parameter scale. Later open-weight designs such as Mixtral,[2]Reference 2Mixtral of Experts.https://arxiv.org/abs/2401.04088 DeepSeek-V2,[3]Reference 3DeepSeek-V2: A Strong, Economical, and Efficient Mixture-of-Experts Language Modelhttps://arxiv.org/abs/2405.04434 DeepSeek-V3,[4]Reference 4DeepSeek-V3 Technical Report.https://arxiv.org/abs/2412.19437 Qwen3.6-35B-A3B,[5]Reference 5Qwen3.6-35B-A3Bhttps://huggingface.co/Qwen/Qwen3.6-35B-A3B GLM-5.2,[6]Reference 6GLM-5.2 Model Cardhttps://huggingface.co/zai-org/GLM-5.2 and DeepSeek V4 Flash 0731[7]Reference 7DeepSeek-V4-Flash-0731 Model Cardhttps://huggingface.co/deepseek-ai/DeepSeek-V4-Flash-0731 make different choices about expert pools, routing, attention, and serving. We'll compare those choices after deriving the small case.

What link does MoE break compared with a dense FFN layer?

Answer

A dense FFN uses all of its parameters for every token. MoE separates total capacity from active compute by storing many expert FFNs but routing each token to only a small top-k subset.

From one FFN to many experts

In a standard Transformer layer, the FFN sublayer is one dense network. In an MoE layer, that FFN is replaced by NNN parallel expert FFNs plus a router (also called a gating network) that picks which kkk experts handle each token. Those winners are a top-k subset.[8]Reference 8Outrageously Large Neural Networks: The Sparsely-Gated Mixture-of-Experts Layer.https://arxiv.org/abs/1701.06538

In many modern LLMs, experts replace only the FFN. Attention stays dense and shared across tokens.[2]Reference 2Mixtral of Experts.https://arxiv.org/abs/2401.04088[3]Reference 3DeepSeek-V2: A Strong, Economical, and Efficient Mixture-of-Experts Language Modelhttps://arxiv.org/abs/2405.04434 A common router is a single linear projection: multiply the token's hidden state by a learned matrix WgW_gWg​ to get NNN scores. The router chooses a path through the FFN; it doesn't choose which tokens attend to one another.

Before the figure, make two predictions: with scores 0.52, 0.17, 0.26, and 0.05 and top-2 routing, which experts run, and do the skipped experts disappear from memory? The next walkthrough checks both answers. Bar length is the softmax probability, not a decorative meter.

MoE layer for one token: shared attention feeds a router, softmax scores 0.52, 0.17, 0.26, and 0.05 select experts E1 and E3 as top-2, skipped experts stay inactive, and the blended FFN output uses renormalized weights 0.67 and 0.33.
Track one token through the layer: shared attention runs first, the router keeps E1 (0.52) and E3 (0.26), skipped experts stay inactive, and the blend uses the renormalized weights 0.67 and 0.33.

Which parts of a Transformer layer are usually replicated in modern MoE LLMs?

Answer

The FFN sublayer is replaced by expert FFNs. Attention, embeddings, normalization, and most shared block logic usually stay dense and shared.

A concrete routing walkthrough

Before any formula, make a prediction: with top-k=2k = 2k=2, only two experts can contribute, but their blend weights won't be the original softmax probabilities. Trace one token through the layer by hand to see where that renormalization comes from.

This is the computation Mixtral-style models run at every token and every MoE layer.

Setup

  • One token arrives with a hidden state xxx of dimension 4.
  • There are 4 experts, each a small FFN.
  • The router uses top-k=2k = 2k=2.

Step 1: Router scores

The router multiplies the token by a learned weight matrix WgW_gWg​ to get a raw score for each expert. Suppose the scores come out as:

ExpertRaw score (logit)
1-0.65
2-1.77
3-1.35
4-3.00

Step 2: Softmax probabilities

Apply softmax so the scores become probabilities that sum to 1. Approximate probabilities:

ExpertProbability
10.52
20.17
30.26
40.05

Step 3: Top-k selection

Pick the top 2 experts: Expert 1 (0.52) and Expert 3 (0.26).

Step 4: Renormalize

The selected weights are renormalized so they sum to 1 inside the chosen subset:

  • Expert 1: 0.52/(0.52+0.26)≈0.670.52 / (0.52 + 0.26) \approx 0.670.52/(0.52+0.26)≈0.67
  • Expert 3: 0.26/(0.52+0.26)≈0.330.26 / (0.52 + 0.26) \approx 0.330.26/(0.52+0.26)≈0.33

Step 5: Expert computation

Only Experts 1 and 3 run. Each processes the same input token xxx through its own FFN weights.

  • E1(x)E_1(x)E1​(x) produces output vector o1o_1o1​
  • E3(x)E_3(x)E3​(x) produces output vector o3o_3o3​

Step 6: Weighted sum

The layer output blends the two expert outputs with the renormalized gate weights:

Output=0.67⋅E1(x)+0.33⋅E3(x)\text{Output} = 0.67 \cdot E_1(x) + 0.33 \cdot E_3(x)Output=0.67⋅E1​(x)+0.33⋅E3​(x)

Experts 2 and 4 never process this token, so they contribute no expert-FFN FLOPs for this decision. Their weights still need to be stored or fetched for other tokens that may select them.

The next snippet uses the exact logits, not the rounded table, and should recover the same selected pair and 0.67 / 0.33 split.

routing-walkthrough.py
1from math import exp 2 3logits = [-0.65, -1.77, -1.35, -3.00] 4unnormalized = [exp(score) for score in logits] 5probabilities = [value / sum(unnormalized) for value in unnormalized] 6selected = sorted(range(len(probabilities)), key=probabilities.__getitem__, reverse=True)[:2] 7selected_total = sum(probabilities[index] for index in selected) 8weights = [probabilities[index] / selected_total for index in selected] 9 10print("selected experts:", [index + 1 for index in selected]) 11print("renormalized weights:", [round(weight, 2) for weight in weights]) 12print("selected weight sum:", round(sum(weights), 2))
Output
1selected experts: [1, 3] 2renormalized weights: [0.67, 0.33] 3selected weight sum: 1.0

What are the six steps for tracing one token through top-k MoE routing?

Answer

Compute router logits, apply softmax, select the top-k experts, renormalize the selected weights, run only the selected expert FFNs, then blend their outputs with the renormalized gate weights.

The general MoE layer formula

The same walkthrough is one compact equation. For an input token xxx:

MoE(x)=∑i∈TopK(g(x))g~i(x)⋅Ei(x)\text{MoE}(x) = \sum_{i \in \text{TopK}(g(x))} \tilde{g}_i(x) \cdot E_i(x)MoE(x)=i∈TopK(g(x))∑​g~​i​(x)⋅Ei​(x)

The router computes a gate distribution g(x)g(x)g(x) over all NNN experts. Keep the configured top-kkk entries, zero the rest, and renormalize the survivors into g~(x)\tilde{g}(x)g~​(x) so those remaining weights sum to 1. Mixtral uses top-2 out of 8; later architectures choose different expert counts and scoring functions.[2]Reference 2Mixtral of Experts.https://arxiv.org/abs/2401.04088[3]Reference 3DeepSeek-V2: A Strong, Economical, and Efficient Mixture-of-Experts Language Modelhttps://arxiv.org/abs/2405.04434 Each selected expert EiE_iEi​ processes xxx independently, then the outputs are blended with g~i\tilde{g}_ig~​i​.

Why do selected expert weights need renormalization after top-k selection?

Answer

The original softmax probabilities include experts that are later zeroed out. Renormalization makes the surviving top-k weights sum to 1, so the blended output keeps the intended scale.

The weighted sum explains one token's result. The next question is resource accounting: what grows with the full expert pool, and what stays tied to kkk?

Why sparse activation can pay off

Two quantities now diverge. An MoE layer can keep per-token expert FLOPs tied mostly to kkk while total weight residency follows all experts. Distributed serving adds token-dispatch traffic, so active parameters alone can't predict latency.

PropertyDense baseline (~active compute)MoE model (Mixtral-shaped)
Total parameters~13B illustrative dense peer~46.7B (8 experts)
Active parameters/token~13B~12.9B (top-2 of 8)
Training FLOPsPer total paramsPer active params
Quality at fixed active computeBaselineOften stronger if routing trains well
Inference compute/tokenPer total paramsRoughly per active params

Adding experts while keeping top-kkk fixed grows the FFN parameter pool, but each token still runs only a small subset. Routing, batching, and communication still add overhead, so "same active parameters" isn't identical latency.

Compute per token is sparse. The serving system still needs access to the full expert pool, so memory footprint and communication often scale with total parameters, not active parameters.

Only the FFN blocks are replicated across experts. Attention layers, embeddings, normalization layers, and the router stay shared. That's why Mixtral 8x7B is about 46.7B total parameters and about 12.9B active parameters per token, not the naive 56B and 14B you would get from multiplying everything by 8. The Mixtral paper rounds those counts to 47B and 13B.[2]Reference 2Mixtral of Experts.https://arxiv.org/abs/2401.04088

Active parameters mostly drive per-token expert FLOPs. Total parameters drive weight memory and checkpoint size. Network traffic depends on where selected experts live.

capacity-versus-compute.py
1shared_parameters_b = 3.0 2expert_parameters_b = 2.0 3expert_count = 8 4top_k = 2 5 6total_parameters_b = shared_parameters_b + expert_count * expert_parameters_b 7active_parameters_b = shared_parameters_b + top_k * expert_parameters_b 8 9print("illustrative total parameters:", f"{total_parameters_b:.1f}B") 10print("illustrative active parameters/token:", f"{active_parameters_b:.1f}B") 11print("weights needed for residency:", f"{total_parameters_b:.1f}B")
Output
1illustrative total parameters: 19.0B 2illustrative active parameters/token: 7.0B 3weights needed for residency: 19.0B

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 amount of expert weight memory the serving system must keep available.

A top-k router you can run

The walkthrough hid the matrix multiply. Here the gate is an explicit 4×44 \times 44×4 matrix. For the unit vector x=[1,0,0,0]x = [1, 0, 0, 0]x=[1,0,0,0], predict what WgxW_g xWg​x should return: the first column contains the four logits, so the same top-2 pair and weights should come back.

topk-router.py
1from math import exp 2 3def matvec(matrix: list[list[float]], vector: list[float]) -> list[float]: 4 return [sum(weight * value for weight, value in zip(row, vector)) for row in matrix] 5 6def softmax(logits: list[float]) -> list[float]: 7 peak = max(logits) 8 unnormalized = [exp(score - peak) for score in logits] 9 total = sum(unnormalized) 10 return [value / total for value in unnormalized] 11 12def topk_route( 13 hidden: list[float], 14 gate: list[list[float]], 15 top_k: int, 16) -> tuple[list[int], list[float]]: 17 logits = matvec(gate, hidden) 18 probabilities = softmax(logits) 19 selected = sorted( 20 range(len(probabilities)), 21 key=probabilities.__getitem__, 22 reverse=True, 23 )[:top_k] 24 selected_total = sum(probabilities[index] for index in selected) 25 weights = [probabilities[index] / selected_total for index in selected] 26 return selected, weights 27 28gate = [ 29 [-0.65, 0.0, 0.0, 0.0], 30 [-1.77, 0.0, 0.0, 0.0], 31 [-1.35, 0.0, 0.0, 0.0], 32 [-3.00, 0.0, 0.0, 0.0], 33] 34hidden = [1.0, 0.0, 0.0, 0.0] 35selected, weights = topk_route(hidden, gate, top_k=2) 36 37print("logits:", [round(score, 2) for score in matvec(gate, hidden)]) 38print("selected experts:", [index + 1 for index in selected]) 39print("renormalized weights:", [round(weight, 2) for weight in weights]) 40print("weight sum:", round(sum(weights), 2))
Output
1logits: [-0.65, -1.77, -1.35, -3.0] 2selected experts: [1, 3] 3renormalized weights: [0.67, 0.33] 4weight sum: 1.0

Switch Transformer used top-1 routing. Mixtral and DeepSeek-V2 select multiple routed experts per token.[1]Reference 1Switch Transformers: Scaling to Trillion Parameter Models with Simple and Efficient Sparsity.https://arxiv.org/abs/2101.03961[2]Reference 2Mixtral of Experts.https://arxiv.org/abs/2401.04088[3]Reference 3DeepSeek-V2: A Strong, Economical, and Efficient Mixture-of-Experts Language Modelhttps://arxiv.org/abs/2405.04434 Extra selected experts change quality, compute, capacity, and communication. They aren't automatically a better serving configuration.

What additional trade-off does top-2 routing introduce compared with top-1?

Answer

Top-2 lets a token blend two routed outputs, but it also executes and dispatches more expert work per token. Whether that trade improves quality or serving efficiency has to be measured for the architecture and hardware.

Alternative: expert choice routing

The standard top-k router forces each token to choose its top kkk experts. Expert Choice Routing[9]Reference 9Mixture-of-Experts with Expert Choice Routinghttps://arxiv.org/abs/2202.09368 flips the mechanism: each expert selects a fixed bucket of top-scoring tokens from the current batch.

Each expert processes a fixed token budget, so expert-side load is predictable and easier to schedule. Coverage moves to the token side: one token may land in many expert buckets, one bucket, or none unless the design adds coverage rules. Token-choice routing with balancing losses remains the simpler picture for open-weight MoE LLMs. Expert-choice routing still shows up in training-efficiency papers.

expert-choice-coverage.py
1expert_buckets = { 2 "E1": ["t0", "t1"], 3 "E2": ["t0", "t2"], 4 "E3": ["t2", "t3"], 5} 6all_tokens = {"t0", "t1", "t2", "t3", "t4"} 7selected_tokens = [token for bucket in expert_buckets.values() for token in bucket] 8uncovered = sorted(all_tokens - set(selected_tokens)) 9 10print("tokens per expert:", [len(bucket) for bucket in expert_buckets.values()]) 11print("t0 expert count:", selected_tokens.count("t0")) 12print("uncovered tokens:", uncovered)
Output
1tokens per expert: [2, 2, 2] 2t0 expert count: 2 3uncovered tokens: ['t4']

What trade-off does expert choice routing make compared with token choice top-k routing?

Answer

Expert choice gives each expert a fixed token budget, so load balancing is easy. The risk moves to the token side: some tokens may get many experts while others may be skipped unless the design enforces coverage.

Why routers collapse without a balancing policy

During training, routers can drift toward expert collapse: many tokens route to a few popular experts while others starve. Load statistics tell you whether this is occurring. They don't prove that a perfectly uniform router is best for model quality.

Suppose four interchangeable experts start with nearly tied scores, but E1 wins slightly more often on common tokens. Predict the next step: E1 receives more assignments, so it gets more gradient updates. It can improve faster on the tokens it already sees, which makes the router even more likely to choose it.

That feedback starves E2 through E4. After enough steps, E1 may take most assignments while the others stay under-trained. The model still reserves memory for all four experts, but that isn't a math expert plus three specialists. It's one overworked expert and three idle parameter blocks.

The histograms use the same 60 / 20 / 15 / 5 split as the numeric loss check later. Compare them with quality, overflow, and communication before you pick a balancing policy.

Two expert-load histograms for four experts. Collapsed routing assigns 60%, 20%, 15%, and 5% of tokens. Balanced routing assigns 25% to each expert.
Collapsed routing puts 60% of assignments on E1. The uniform 25% panel is a reference distribution, not proof that equal load maximizes quality.

The router is trained jointly with the rest of the network.[8]Reference 8Outrageously Large Neural Networks: The Sparsely-Gated Mixture-of-Experts Layer.https://arxiv.org/abs/1701.06538 Inspect assignment shares, overflow, task loss, and communication load together.

routing-load-monitor.py
1assignments = [0] * 12 + [1] * 4 + [2] * 3 + [3] 2expert_count = 4 3counts = [assignments.count(expert) for expert in range(expert_count)] 4shares = [count / len(assignments) for count in counts] 5max_share = max(shares) 6 7print("assignment shares:", [round(share, 2) for share in shares]) 8print("flag for investigation:", max_share > 0.50)
Output
1assignment shares: [0.6, 0.2, 0.15, 0.05] 2flag for investigation: True

Why does expert collapse reinforce itself during training?

Answer

The router sends more tokens to an expert that looks slightly better. That expert gets more gradient updates, improves faster, and becomes even more attractive to the router, starving other experts.

An auxiliary load-balancing loss

How can a training run push back against that feedback loop? Switch Transformer uses a top-1 auxiliary loss that penalizes uneven routing.[1]Reference 1Switch Transformers: Scaling to Trillion Parameter Models with Simple and Efficient Sparsity.https://arxiv.org/abs/2101.03961 This form is also a useful teaching calculation for top-kkk routing when fif_ifi​ is normalized over routed assignments:

Lbalance=α⋅N∑i=1Nfi⋅pi\mathcal{L}_{\text{balance}} = \alpha \cdot N \sum_{i=1}^N f_i \cdot p_iLbalance​=α⋅Ni=1∑N​fi​⋅pi​

Multiply each expert's routed-assignment fraction fif_ifi​ by its average routing probability pip_ipi​ and sum them. If the router sends too many assignments to one expert (high fif_ifi​) and gives it high probability (high pip_ipi​), the product is large, so the loss penalizes that concentration.

It's a balancing pressure, not proof that equal utilization maximizes task quality.

where:

  • fi=assignments routed to expert itotal routed assignmentsf_i = \frac{\text{assignments routed to expert } i}{\text{total routed assignments}}fi​=total routed assignmentsassignments routed to expert i​; with top-kkk, the denominator is T×kT \times kT×k
  • pi=1T∑t=1Tsoftmax(Wg⋅xt)ip_i = \frac{1}{T}\sum_{t=1}^T \text{softmax}(W_g \cdot x_t)_ipi​=T1​∑t=1T​softmax(Wg​⋅xt​)i​ (average router probability)
  • α\alphaα is a configurable coefficient (Switch reports experiments including 10−210^{-2}10−2)
  • NNN is the number of experts

A balanced reference point is fi≈pi≈1/Nf_i \approx p_i \approx 1/Nfi​≈pi​≈1/N. A trained deployment still needs task-quality and systems measurements before you judge its observed specialization.

Here's a concrete top-1 numeric check. Suppose we have 4 experts and a mini-batch of 100 tokens:

Expertfif_ifi​ (actual fraction)pip_ipi​ (average prob)Product fi⋅pif_i \cdot p_ifi​⋅pi​
10.600.550.330
20.200.220.044
30.150.150.022
40.050.080.004
Sum0.400

If the load were perfectly uniform, each expert would get fi=pi=0.25f_i = p_i = 0.25fi​=pi​=0.25, and the sum would be 4×(0.25×0.25)=0.254 \times (0.25 \times 0.25) = 0.254×(0.25×0.25)=0.25. With positive α\alphaα, this auxiliary term applies pressure against the imbalanced 0.400 case. Tune its weight with task-quality measurements, because too much balancing pressure can fight the language-modeling objective.

The auxiliary loss says "use the expert pool evenly enough." The language-modeling loss still decides whether the model predicts the next token well.

load-balancing-score.py
1assignment_counts = [60, 20, 15, 5] 2mean_router_probability = [0.55, 0.22, 0.15, 0.08] 3expert_count = len(assignment_counts) 4assignment_total = sum(assignment_counts) 5fractions = [count / assignment_total for count in assignment_counts] 6 7concentration = expert_count * sum( 8 fraction * probability 9 for fraction, probability in zip(fractions, mean_router_probability) 10) 11uniform_reference = expert_count * sum((1 / expert_count) ** 2 for _ in fractions) 12 13print("scaled concentration:", round(concentration, 2)) 14print("uniform reference:", round(uniform_reference, 2)) 15print("excess balancing pressure:", round(concentration - uniform_reference, 2))
Output
1scaled concentration: 1.6 2uniform reference: 1.0 3excess balancing pressure: 0.6

In the load-balancing loss, what do fif_ifi​ and pip_ipi​ measure?

Answer

fif_ifi​ measures how many tokens were actually routed to expert iii. pip_ipi​ measures the router's average probability for expert iii. A high value for both means the expert is both preferred and overloaded.

Balancing asks how assignments are distributed on average. Capacity asks what happens when one batch is bursty and a hot expert fills its buffer.

Capacity factor and overflow policy

Start with a concrete batch: 4096 tokens choose top-2 from 32 experts. Uniform routing would send 256 token-slots to each expert. If one hot expert receives 400 assignments, 144 need an overflow policy.

In a batched environment, many MoE implementations use fixed-size expert buffers so the layer can run predictable tensor operations. The capacity factor multiplies that uniform slot estimate:

Expert Capacity=Tokens per Batch×kN×Capacity Factor\text{Expert Capacity} = \frac{\text{Tokens per Batch} \times k}{N} \times \text{Capacity Factor}Expert Capacity=NTokens per Batch×k​×Capacity Factor

That expression is the average number of tokens each expert would receive under perfectly uniform routing, then multiplied by the capacity factor. A factor of 1.01.01.0 sizes the buffer for uniform routing. Setting it to 1.21.21.2 lets an expert take 20% more tokens than the average.

What happens after an expert is assigned more tokens than its buffer allows depends on implementation:

  1. Dropping or pass-through: Switch-style designs can skip overflowed expert computations and rely on the residual path for those token-layer assignments.[1]Reference 1Switch Transformers: Scaling to Trillion Parameter Models with Simple and Efficient Sparsity.https://arxiv.org/abs/2101.03961
  2. Rerouting: A system can send overflow to another eligible expert, changing load and communication.
  3. Dropless execution: A system can execute all assignments with variable work, keeping quality paths while accepting less predictable workload.

A higher capacity factor reduces overflow risk but reserves more buffer space and may waste compute on empty slots. A lower factor is more compact, so whichever overflow policy you selected matters more.

Diagram showing Hot expert over capacity, Drop: skip FFN, residual continues, Reroute to another expert, and Dropless: run the extra work.
Hot expert over capacity, Drop: skip FFN, residual continues, Reroute to another expert, and Dropless: run the extra work.
capacity-overflow-policy.py
1from math import ceil 2 3tokens = 4096 4top_k = 2 5experts = 32 6capacity_factor = 1.0 7assigned_to_hot_expert = 400 8capacity = ceil(tokens * top_k / experts * capacity_factor) 9overflow = max(assigned_to_hot_expert - capacity, 0) 10 11print("per-expert capacity:", capacity) 12print("overflow assignments:", overflow) 13print("drop keeps:", capacity, "skips:", overflow) 14print("reroute keeps:", capacity, "sends elsewhere:", overflow) 15print("dropless runs:", assigned_to_hot_expert)
Output
1per-expert capacity: 256 2overflow assignments: 144 3drop keeps: 256 skips: 144 4reroute keeps: 256 sends elsewhere: 144 5dropless runs: 400

Why does a capacity factor of 1.2 reduce overflow risk versus 1.0, and what must you know when an expert is full?

Answer

1.2 gives each expert a 20% buffer above uniformly distributed assignments, reducing overflow. The result of overflow is an implementation policy: it may drop, reroute, or execute extra assignments, with different quality and throughput costs.

How modern architectures scale the idea

Routing, balance, and capacity are the knobs. The design question is now whether a larger expert pool adds useful capacity without making per-token compute, memory, or communication unmanageable. Production models turn those knobs in different directions: fewer coarse experts, many fine-grained routed experts, always-on shared experts, and routers that are no longer a plain softmax.

Mixtral 8x7B[2]Reference 2Mixtral of Experts.https://arxiv.org/abs/2401.04088

PropertyValue
Total params~46.7B (paper rounds to 47B)
Active params~12.9B (paper rounds to 13B)
Experts8
Top-K2
Expert typeStandard FFN (SwiGLU activation[10]Reference 10GLU Variants Improve Transformerhttps://arxiv.org/abs/2002.05202)
Reported qualityMixtral paper (2024): base model matches or exceeds Llama 2 70B and GPT-3.5 on its evaluated suite[2]Reference 2Mixtral of Experts.https://arxiv.org/abs/2401.04088

MoE is applied only to the FFN layers. Attention stays shared. Mixtral uses a SwiGLU (Swish Gated Linear Unit) expert, a Gated Linear Unit (GLU) variant that improved Transformer quality in the GLU-variants paper.

DeepSeek-V2[3]Reference 3DeepSeek-V2: A Strong, Economical, and Efficient Mixture-of-Experts Language Modelhttps://arxiv.org/abs/2405.04434

PropertyValue
Total params236B
Active params21B
Routed experts160 (fine-grained)
Shared experts2 (always-on)
Routed Top-K6
Total active experts8 (6 routed + 2 shared)

DeepSeek-V2 extends coarse-grained MoE in several ways:

  • Fine-grained experts: 160 smaller routed experts instead of a handful of coarse experts, which gives the router many more combinations per token.[3]Reference 3DeepSeek-V2: A Strong, Economical, and Efficient Mixture-of-Experts Language Modelhttps://arxiv.org/abs/2405.04434
  • Shared experts: 2 experts are always active for all tokens. The design aims to capture common computation and reduce redundancy among routed experts.[3]Reference 3DeepSeek-V2: A Strong, Economical, and Efficient Mixture-of-Experts Language Modelhttps://arxiv.org/abs/2405.04434
  • Device-limited routing: selected routed experts for each token are constrained to a small number of devices (the paper reports M≥3M \ge 3M≥3 as a practical setting), which bounds cross-device communication.[3]Reference 3DeepSeek-V2: A Strong, Economical, and Efficient Mixture-of-Experts Language Modelhttps://arxiv.org/abs/2405.04434
  • Multi-level balancing losses: expert-level, device-level, and communication-balance losses for cluster-scale routing.[3]Reference 3DeepSeek-V2: A Strong, Economical, and Efficient Mixture-of-Experts Language Modelhttps://arxiv.org/abs/2405.04434
  • Multi-head Latent Attention (MLA): compresses the KV cache into a low-rank latent vector.[3]Reference 3DeepSeek-V2: A Strong, Economical, and Efficient Mixture-of-Experts Language Modelhttps://arxiv.org/abs/2405.04434

DeepSeek's report pairs MLA with FP8 weights and KV-cache quantization averaging 6 bits. On one node with 8 H800 GPUs, using the prompt and generation-length distribution from its deployed DeepSeek 67B service, it reports more than 50K tokens per second, or 5.76× the DeepSeek 67B maximum generation throughput.[3]Reference 3DeepSeek-V2: A Strong, Economical, and Efficient Mixture-of-Experts Language Modelhttps://arxiv.org/abs/2405.04434 The paper doesn't give a separate output-correctness tolerance for this comparison, so reproduce the claim only with an equivalence check on your own workload.

Cell counts in the comparison are exact. Tile sizes are schematic.

Expert-pool comparison showing Mixtral selecting 2 of 8 routed experts and DeepSeek-V2 activating 2 shared experts plus 6 of 160 routed experts.
Mixtral chooses 2 of 8 routed experts. DeepSeek-V2 runs 2 shared experts plus 6 selected from 160 routed experts. Purple cells stay on for every token; green cells are the routed path for one token.

DeepSeek-V3[4]Reference 4DeepSeek-V3 Technical Report.https://arxiv.org/abs/2412.19437

DeepSeek-V3 keeps the DeepSeekMoE pattern at a larger reported scale. The first three layers stay dense FFNs; later layers are MoE. Compare it with the softmax walkthrough on two choices: how V3 selects routed experts and how it balances them.

PropertyValue
Total params671B
Active params37B
Routed experts256
Shared experts1
Routed Top-K8
Total active experts9 (8 routed + 1 shared)
Main load balancingBias-adjusted auxiliary-loss-free strategy
Auxiliary guardSequence-wise balance loss
Other key componentMulti-head Latent Attention (MLA)

Each MoE layer has 1 shared expert and 256 routed experts, with 8 routed experts activated per token.[4]Reference 4DeepSeek-V3 Technical Report.https://arxiv.org/abs/2412.19437

DeepSeek-V3 also changes scoring. It computes token-to-expert affinity with sigmoid scores, normalizes the selected scores, and adds a per-expert bias only when choosing the top-kkk routed experts. Training adjusts that bias from observed expert load. The weighted expert output still uses the original affinity score, not the routing bias.[4]Reference 4DeepSeek-V3 Technical Report.https://arxiv.org/abs/2412.19437

The paper calls the main batch-wise mechanism auxiliary-loss-free because it doesn't rely on an auxiliary loss to keep expert load balanced across a training batch. It still keeps a small complementary sequence-wise balance loss to prevent extreme imbalance inside one sequence.[4]Reference 4DeepSeek-V3 Technical Report.https://arxiv.org/abs/2412.19437 The softmax router you implemented is a teaching sketch, not a universal contract.

GLM-5.2 and DeepSeek V4 Flash 0731

These releases make stored-versus-active capacity impossible to ignore:

PropertyGLM-5.2DeepSeek V4 Flash 0731
Vendor core-size label744B total / about 40B active[11]Reference 11GLM-5 Repositoryhttps://github.com/zai-org/GLM-5284B total / 13B active[12]Reference 12DeepSeek-V4: Towards Highly Efficient Million-Token Context Intelligencehttps://arxiv.org/abs/2606.19348
Released artifact metadataAbout 753B BF16 parameters[6]Reference 6GLM-5.2 Model Cardhttps://huggingface.co/zai-org/GLM-5.2Hugging Face reports about 304B mixed-precision parameters; the model card says a DSpark module is attached[7]Reference 7DeepSeek-V4-Flash-0731 Model Cardhttps://huggingface.co/deepseek-ai/DeepSeek-V4-Flash-0731
Routed experts per MoE layer256[13]Reference 13GLM-5.2 Configurationhttps://huggingface.co/zai-org/GLM-5.2/blob/main/config.json256[12]Reference 12DeepSeek-V4: Towards Highly Efficient Million-Token Context Intelligencehttps://arxiv.org/abs/2606.19348
Routed experts per token8[13]Reference 13GLM-5.2 Configurationhttps://huggingface.co/zai-org/GLM-5.2/blob/main/config.json6[12]Reference 12DeepSeek-V4: Towards Highly Efficient Million-Token Context Intelligencehttps://arxiv.org/abs/2606.19348
Shared experts1[13]Reference 13GLM-5.2 Configurationhttps://huggingface.co/zai-org/GLM-5.2/blob/main/config.json1[12]Reference 12DeepSeek-V4: Towards Highly Efficient Million-Token Context Intelligencehttps://arxiv.org/abs/2606.19348
Layers78[13]Reference 13GLM-5.2 Configurationhttps://huggingface.co/zai-org/GLM-5.2/blob/main/config.json43[12]Reference 12DeepSeek-V4: Towards Highly Efficient Million-Token Context Intelligencehttps://arxiv.org/abs/2606.19348
Context1M text tokens[14]Reference 14GLM-5.2 Model Documentationhttps://docs.z.ai/guides/llm/glm-5.21M text tokens[12]Reference 12DeepSeek-V4: Towards Highly Efficient Million-Token Context Intelligencehttps://arxiv.org/abs/2606.19348
Long-context mechanismLatent KV compression + DSA + IndexShare[13]Reference 13GLM-5.2 Configurationhttps://huggingface.co/zai-org/GLM-5.2/blob/main/config.json[15]Reference 15GLM-5.2https://z.ai/blog/glm-5.2CSA + HCA hybrid attention[12]Reference 12DeepSeek-V4: Towards Highly Efficient Million-Token Context Intelligencehttps://arxiv.org/abs/2606.19348
Speculative pathOne MTP module[13]Reference 13GLM-5.2 Configurationhttps://huggingface.co/zai-org/GLM-5.2/blob/main/config.json[15]Reference 15GLM-5.2https://z.ai/blog/glm-5.2One MTP module plus attached DSpark module in the 0731 artifact[12]Reference 12DeepSeek-V4: Towards Highly Efficient Million-Token Context Intelligencehttps://arxiv.org/abs/2606.19348[16]Reference 16DeepSeek-V4-Flash-DSpark Model Cardhttps://huggingface.co/deepseek-ai/DeepSeek-V4-Flash-DSpark
LicenseMIT[6]Reference 6GLM-5.2 Model Cardhttps://huggingface.co/zai-org/GLM-5.2MIT[7]Reference 7DeepSeek-V4-Flash-0731 Model Cardhttps://huggingface.co/deepseek-ai/DeepSeek-V4-Flash-0731

This table is not a quality ranking. GLM-5.2 stores much more expert parameter capacity and targets long-horizon coding and tool workflows. Flash 0731 activates a smaller path and targets efficient agentic coding and serving.

Two V4 details change how you read the earlier softmax router. Every Transformer block is an MoE layer, and the first three MoE layers use hash routing from token identity instead of a learned gate.[12]Reference 12DeepSeek-V4: Towards Highly Efficient Million-Token Context Intelligencehttps://arxiv.org/abs/2606.19348 Affinity scores use softplus(⋅)\sqrt{\mathrm{softplus}(\cdot)}softplus(⋅)​ rather than V3's sigmoid, still with auxiliary-loss-free bias plus a small sequence-wise balance loss.[12]Reference 12DeepSeek-V4: Towards Highly Efficient Million-Token Context Intelligencehttps://arxiv.org/abs/2606.19348

Both checkpoints still need full-weight residency planning and workload-local evals. Inter-device expert communication and sparse kernels may be required for intended performance, depending on runtime and topology.[6]Reference 6GLM-5.2 Model Cardhttps://huggingface.co/zai-org/GLM-5.2[13]Reference 13GLM-5.2 Configurationhttps://huggingface.co/zai-org/GLM-5.2/blob/main/config.json[7]Reference 7DeepSeek-V4-Flash-0731 Model Cardhttps://huggingface.co/deepseek-ai/DeepSeek-V4-Flash-0731[12]Reference 12DeepSeek-V4: Towards Highly Efficient Million-Token Context Intelligencehttps://arxiv.org/abs/2606.19348

Qwen3.6 sparse MoE checkpoint[5]Reference 5Qwen3.6-35B-A3Bhttps://huggingface.co/Qwen/Qwen3.6-35B-A3B

Qwen3.6 puts the active-versus-total split in the model name:

CheckpointTotal paramsActivated paramsMoE pathWhat the suffix means
Qwen3.6-35B-A3B35B3B256 experts, 8 routed + 1 shared35B total, about 3B active per token

"A3B" hints at active compute, not full deployment footprint. You still need memory, sharding, quantization, or offload capacity for the full checkpoint, plus serving support for routing and grouped expert execution.

The backbone also interleaves Gated DeltaNet layers with gated attention. That is a sequence-mixer choice, not an FFN-routing choice, and it's the bridge into the next chapter.

What does DeepSeek-style fine-grained MoE add beyond "more experts"?

Answer

It uses many smaller routed experts, shared always-on experts, device-limited routing, and balancing policies designed for cluster-scale communication. The architecture problem is routing quality plus hardware efficiency, not parameter count alone.

The model comparisons answer how capacity is allocated. Serving adds a second question: can the runtime move, group, and execute those routed token states fast enough on its actual devices?

Serving an MoE on real hardware

Sparse compute per token doesn't remove the systems work. Experts often live on different devices, token states have to move, and decode microbatches re-expose that tax every step.

Communication overhead

In distributed training and inference, experts often reside on different devices to meet memory requirements. Routing a token to an expert on another GPU requires transferring the token's hidden state over a high-bandwidth interconnect such as NVLink within a node or InfiniBand across nodes.

That transfer can stall the layer. The usual pattern is an all-to-all dispatch that scatters tokens to the GPUs hosting their selected experts, then an all-to-all combine that returns expert outputs to the original token order. System designers try to overlap those transfers with useful compute so the network isn't the only thing running.

The next count uses four experts on two GPUs. Three of five assignments cross the link.

expert-placement-traffic.py
1expert_device = {"E0": "GPU0", "E1": "GPU0", "E2": "GPU1", "E3": "GPU1"} 2routed_assignments = [ 3 ("GPU0", "E0"), 4 ("GPU0", "E2"), 5 ("GPU1", "E2"), 6 ("GPU1", "E1"), 7 ("GPU0", "E3"), 8] 9remote = sum( 10 source_device != expert_device[expert] 11 for source_device, expert in routed_assignments 12) 13 14print("routed assignments:", len(routed_assignments)) 15print("remote assignments:", remote) 16print("remote rate:", f"{remote / len(routed_assignments):.0%}")
Output
1routed assignments: 5 2remote assignments: 3 3remote rate: 60%

Memory requirements

Unlike dense models with one FFN per layer, MoE models carry many expert FFNs. Fast GPU deployments generally keep those expert weights resident somewhere in the serving pool so routing doesn't stall on weight fetches.

That is the core MoE paradox: low active compute per token, high total weight residency. Mixtral 8x7B only activates about 12.9B parameters per token, yet the serving system still needs the full ~46.7B-parameter checkpoint available across the cluster.[2]Reference 2Mixtral of Experts.https://arxiv.org/abs/2401.04088 Tensor Parallelism (TP) splits individual layer computations across multiple GPUs, which helps large shared layers fit, but it doesn't solve expert placement. Expert Parallelism (EP) places different full experts on different GPUs while keeping every expert reachable when a token needs it.

Why doesn't tensor parallelism alone solve MoE serving?

Answer

Tensor parallelism shards individual matrix operations. MoE also needs expert placement, dispatch, and combine across whole expert FFNs, so serving systems use expert parallelism to keep different experts reachable across devices.

Training instability

MoE training can be more sensitive than training a comparable dense Transformer. The top-kkk routing step introduces discontinuities at expert-selection boundaries, and small routing biases can snowball into expert collapse. Gradients still flow through the selected experts and their gate weights, but the router is noisier to optimize than a dense FFN.

Router z-loss[17]Reference 17ST-MoE: Designing Stable and Transferable Sparse Expert Modelshttps://arxiv.org/abs/2202.08906 penalizes unnecessarily large routing logits; the ST-MoE paper reports improved training stability from this term. Input jitter is another candidate to test, but ST-MoE's XL-scale ablation improved stability while reducing quality.[17]Reference 17ST-MoE: Designing Stable and Transferable Sparse Expert Modelshttps://arxiv.org/abs/2202.08906 Track training loss, routing distribution, overflow, and downstream quality rather than assuming one stabilizer is free.

Expert parallelism layout

Large distributed MoE deployments commonly use Expert Parallelism. TP splits individual matrix multiplications. EP maps entire experts to specific GPUs. Real deployments can combine EP with TP, sequence parallelism, data parallelism, and redundant expert placement. DeepSeek-V3 describes a decoding layout with TP4 for attention and EP320 for the MoE path.[4]Reference 4DeepSeek-V3 Technical Report.https://arxiv.org/abs/2412.19437

The two-GPU sketch below matches the traffic snippet: GPU0 owns E0 and E1, GPU1 owns E2 and E3, and three of five token states cross the link. Expert weights never migrate.

Expert parallelism on two GPUs owning four experts. GPU0 keeps E0 and E1; GPU1 keeps E2 and E3. Five token assignments send t0 locally to E0 and t2 locally to E2, while t1, t3, and t4 cross the link, so three of five routes are remote. Expert weights stay on the owner GPU.
Green pills and cells are local. Warm marks a slot that received a remote token: t1, t3, and t4 cross the link, so three of five assignments are remote. Expert weights stay on GPU0 (E0, E1) and GPU1 (E2, E3).

At a larger 96-expert split the same ownership rule still holds:

text
1GPU 0: Attention layers (shared) + Experts 0-31 2GPU 1: Attention layers (shared) + Experts 32-63 3GPU 2: Attention layers (shared) + Experts 64-95

Sizing EP traffic

A lower bound on dispatch + combine volume for TTT tokens with top-kkk routing, hidden size HHH, and element size bbb bytes is:

bytesdispatch+combine≈2⋅T⋅k⋅H⋅b\text{bytes}_{\text{dispatch+combine}} \approx 2 \cdot T \cdot k \cdot H \cdot bbytesdispatch+combine​≈2⋅T⋅k⋅H⋅b

(plus small routing metadata). Compare that wire cost to expert GEMM work on a device that receives TexpT_{\text{exp}}Texp​ token-slots: roughly 4⋅Texp⋅H⋅I4 \cdot T_{\text{exp}} \cdot H \cdot I4⋅Texp​⋅H⋅I FLOPs for a two-projection FFN with intermediate size III, counting one multiply and one add as two FLOPs in each of the up and down projections. A gated three-projection FFN is roughly 6⋅Texp⋅H⋅I6 \cdot T_{\text{exp}} \cdot H \cdot I6⋅Texp​⋅H⋅I FLOPs under the same convention. When interconnect is weak or TTT is small (decode microbatches), the 2TkHb2TkHb2TkHb term can dominate even if active FLOPs look cheap.

Balanced global expert histograms aren't enough. If many popular experts land on the same EP rank, that rank's per-device token histogram spikes, capacity overflows, and the all-to-all waits on a straggler. Device-limited routing and capacity policy should be checked against per-rank token counts as well as expert-ID frequencies.

Prefill vs decode under EP: large prefill batches can amortize dispatch/combine across many tokens per expert. Decode microbatches re-expose router, grouping, and all-to-all latency every step, which is why dense paths sometimes win p95 at batch size 1 even when MoE wins throughput.

Expert prefetching

For CPU-offloaded serving (for example, running a quantized MoE checkpoint on consumer hardware), one possible design is:

  1. Keep attention weights and router weights in GPU memory (always needed).
  2. Keep expert weights on CPU or SSD.
  3. After a layer's router decides which experts are needed, transfer those expert weights before its expert computation.
  4. Optionally use prediction or caching to stage likely later-layer experts, accepting misses or unused transfers.

This can make large MoE checkpoints fit where full GPU residency can't, especially when combined with weight quantization, but it trades memory for transfer-dependent latency. You can't know an exact next-layer route until that layer receives its hidden state, so unconditional "prefetch the next experts" isn't free.

Batch routing efficiency

In batch serving, different tokens in a batch may route to different experts. Batched expert execution is the serving trick:

  1. Router assigns all tokens in the batch to their top-k experts.
  2. Group tokens by expert assignment.
  3. Execute each expert as a batched matrix multiply over its assigned tokens.
  4. Scatter results back to original token positions.

That groups many per-token expert calls into a smaller number of larger matrix multiplies, which helps keep GPU utilization high.

grouped-expert-execution.py
1from collections import defaultdict 2 3routes = [ 4 ("t0", "E2"), 5 ("t1", "E0"), 6 ("t2", "E2"), 7 ("t3", "E1"), 8 ("t4", "E2"), 9] 10grouped = defaultdict(list) 11for token, expert in routes: 12 grouped[expert].append(token) 13 14for expert in sorted(grouped): 15 print(expert, "batch tokens:", grouped[expert], "gemm rows:", len(grouped[expert]))
Output
1E0 batch tokens: ['t1'] gemm rows: 1 2E1 batch tokens: ['t3'] gemm rows: 1 3E2 batch tokens: ['t0', 't2', 't4'] gemm rows: 3

Benchmark slices instead of memorizing a crossover:

Measurement sliceWhat it exposes
Single request, batch size 1Fixed router, grouping, and dispatch overhead
Moderate and large batchesHow much grouped expert execution amortizes that overhead
Local versus remote expert routesCost of expert placement and all-to-all traffic
Strong versus weak interconnectWhether network bandwidth changes the winner

Exact outcomes depend on kernels, expert placement, interconnect, and request mix. MoE adds router computation, expert selection, token grouping, and sometimes all-to-all communication. Batching can amortize that overhead, but only measurements on the target system establish whether MoE wins latency or throughput.

Treat the next numbers as a fixture you would replace with benchmark output from the serving stack under evaluation.

These values are intentionally synthetic. For a real speed or latency claim, record accelerator and software versions, request shape and batch or concurrency, precision and kernel path, exact dense baseline, and a correctness check beside the measurement. Without that packet, 34.1% is a fixture result, not a portable benchmark.

measured-serving-gate.py
1dense = {"quality": 0.82, "p95_ms": 48, "tokens_per_second": 820} 2moe = {"quality": 0.83, "p95_ms": 55, "tokens_per_second": 1100} 3requirements = {"quality": 0.82, "max_p95_ms": 60, "min_tokens_per_second": 1000} 4 5approved = ( 6 moe["quality"] >= requirements["quality"] 7 and moe["p95_ms"] <= requirements["max_p95_ms"] 8 and moe["tokens_per_second"] >= requirements["min_tokens_per_second"] 9) 10 11print("moe throughput improvement:", f"{moe['tokens_per_second'] / dense['tokens_per_second'] - 1:.1%}") 12print("moe p95 delta ms:", moe["p95_ms"] - dense["p95_ms"]) 13print("candidate approved:", approved)
Output
1moe throughput improvement: 34.1% 2moe p95 delta ms: 7 3candidate approved: True

Why can dense models beat MoE on single-request latency even when MoE has fewer active parameters?

Answer

MoE adds router work, token grouping, expert dispatch, and often all-to-all communication. With batch size 1, that overhead may dominate. Larger batches amortize it across many routed tokens.

The serving measurements expose the real tradeoff. Now turn them into a deployment choice instead of inferring a winner from active-parameter counts.

When MoE is worth the complexity

Use MoE when the problem needs more model capacity at roughly fixed active compute, and the serving stack can absorb routing complexity. Prefer a dense model when the bottleneck is single-request latency, weak interconnect, or full-checkpoint memory.

Decision signalDense is likely betterMoE is worth testing
Traffic shapeLow batch size, strict p95 latencyLarge batches or offline throughput
Memory budgetOne model must fit on a small fixed GPU setFull checkpoint can be sharded, quantized, or offloaded
NetworkAll-to-all traffic already saturates linksFast interconnect and device-aware routing are available
Quality targetDense baseline already meets requirementsExtra capacity may improve harder tasks
Serving stackKernels lack grouped expert executionRuntime supports routing, dispatch, combine, and expert placement
ObservabilityNo routing, overflow, or per-expert metricsYou can inspect load balance, capacity, drops, and communication

Don't stop at "this model activates fewer parameters." Ask whether the target workload still gains quality or throughput after full weight residency, routing overhead, interconnect cost, and operational visibility.

What is the fastest practical dense-vs-MoE check?

Answer

Compare dense and MoE on the real serving regime. Require quality to meet the bar, p95 latency to fit the product budget, throughput to justify the extra routing machinery, and memory residency to fit the deployment plan.

Use each failure below as a hypothesis to test. Start with the symptom, trace the resource or routing signal behind it, then change one policy and rerun the same workload.

When MoE serving breaks down

"Active FLOPs are small, so deployment memory will be small too"

  • Symptom: FLOP estimates look cheap, but deployment still runs out of VRAM.
  • Cause: Team budgeted only for active parameters per token and forgot that the full expert pool must still be resident somewhere in the serving system.
  • Fix: Separate active expert FLOPs from total weight residency. Size memory for the full expert pool as well as the routed path.

"Router imbalance will fix itself later"

  • Symptom: One or two experts receive most tokens by early training.
  • Cause: Router found a slightly better path, that expert got more gradients, and collapse reinforced itself.
  • Fix: Track routing histograms from the start and tune the load-balancing policy before unused experts go stale. Evaluate router z-loss separately for numerical stability, and inspect capacity plus overflow policy separately for dropped or delayed work.

"Sparse compute guarantees lower latency"

  • Symptom: MoE benchmark wins disappear at batch size 1.
  • Cause: Sparse expert FLOPs aren't the whole latency story. Router work, grouping, dispatch, and all-to-all traffic can dominate single-request latency.
  • Fix: Evaluate MoE on the real serving regime. Use dense models for low-latency single requests when routing overhead outweighs sparse compute gains.

"Expert placement is a later infra detail"

  • Symptom: Throughput drops sharply after experts are split across GPUs.
  • Cause: Expert placement created communication hotspots. Tokens now bounce across devices faster than grouped GEMMs can amortize the transfers.
  • Fix: Treat routing and placement as one systems problem. Use expert parallelism, device-aware routing, and batching to keep all-to-all traffic under control.

"Balanced histograms mean routing is healthy"

  • Symptom: Quality drops even though router histograms look balanced.
  • Cause: Experts may be hitting capacity limits, and the configured overflow policy is dropping, rerouting, or delaying assignments.
  • Fix: Inspect overflow counts and policy directly. Evaluate capacity factor, routing balance, burstiness, and throughput before assuming the issue is elsewhere.

"Expert-choice routing covers every token automatically"

  • Symptom: Expert-choice routing leaves some tokens underprocessed.
  • Cause: Experts select their favorite tokens first, so token coverage is no longer guaranteed automatically.
  • Fix: Add explicit coverage rules or use token-choice top-k routing when every token must reliably receive expert computation.

"Experts are neat human-labeled topic buckets"

  • Symptom: Teams describe experts as clean topic buckets like "math expert" or "biology expert."
  • Cause: Human-friendly labels are being projected onto behavior that often follows token patterns, formatting, or structural clusters instead.
  • Fix: Validate specialization with routing traces, activation analysis, and targeted prompts that test a claimed specialty before telling a story about it.

What's the simplest way to tell whether someone understands MoE serving cost?

Answer

They separate three quantities: active FLOPs per token, total expert weight residency, and communication cost from routing tokens to experts across devices.

Replace selected dense FFNs with routed expert sets and activate only the configured paths per token. A real serving claim still has to pass the router trace, total-parameter versus active-compute distinction, balance, overflow policy, memory residency, and communication checks.

Complete the lesson

Mastery Check

Answer every question, then check your score. Score 75% or higher to mark this lesson complete.

1.Which parts of a Transformer layer are usually replicated in modern MoE LLMs?

Correct answer: The FFN sublayer is replaced by expert FFNs. Attention, embeddings, normalization, and most shared block logic usually stay dense and shared.

The expert pool is normally a replacement for the dense FFN sublayer, not for the whole Transformer block. Attention still mixes information across tokens through a shared path, while the router selects which expert FFNs process each token independently.

2.A token has router softmax probabilities [0.52, 0.17, 0.26, 0.05] for Experts 1-4 and top-k = 2. If E1(x) = [2, 0] and E3(x) = [0, 3], what blended expert output is produced after top-k renormalization?

Correct answer: [1.33, 1.00], because Experts 1 and 3 are selected and their weights renormalize to about 0.67 and 0.33.

Top-k keeps Experts 1 and 3 because 0.52 and 0.26 are the two largest probabilities. Their selected probability mass is 0.78, so the renormalized weights are 0.52/0.78 = 0.67 and 0.26/0.78 = 0.33. The blended output is 0.67 * [2, 0] + 0.33 * [0, 3] = [1.33, 1.00].

3.A team changes a Transformer FFN layer into an MoE layer with 16 expert FFNs and keeps top-k = 2. If they later add more experts but keep top-k fixed, what resource split should they expect?

Correct answer: Per-token expert FLOPs stay tied mostly to the 2 selected experts, while checkpoint size and expert weight residency grow with the full expert pool.

MoE sparsifies the FFN computation: each token runs only the selected experts, so active expert FLOPs are governed mainly by top-k. The unselected experts still exist as parameters and must be stored or made reachable, so total memory residency and checkpoint size grow with the expert pool.

4.During early MoE training, routing histograms show Expert 0 receives 70% of routed assignments while several experts receive almost none. Why can this imbalance become self-reinforcing?

Correct answer: The hot expert receives more assignments and gradient updates, can improve faster, and becomes even more attractive to the jointly trained router.

The router and experts are trained together. If one expert is favored early, it receives more tokens and therefore more gradient updates. That can make it improve faster than underused experts, which makes the router even more likely to select it unless balancing pressure or other mitigation intervenes.

5.For a top-1 batch with 4 experts, assignment fractions are [0.60, 0.20, 0.15, 0.05] and average router probabilities are [0.55, 0.22, 0.15, 0.08]. Ignoring alpha, what does N sum_i f_i p_i indicate?

Correct answer: It's about 1.6, above the uniform reference of 1.0, so the auxiliary term pressures against the concentration on Expert 1.

The product f_i p_i is large when an expert is both actually selected often and assigned high average router probability. Here the dot product is about 0.40, and multiplying by N = 4 gives about 1.6. A uniform 4-expert reference gives 1.0, so the term adds balancing pressure, not proof that the hot expert is semantically better.

6.A batch has 4096 tokens, top-k = 2, 32 experts, capacity factor 1.0, and one hot expert receives 400 routed assignments. What capacity problem must the implementation handle?

Correct answer: The nominal per-expert capacity is 256 assignments, so 144 assignments overflow and must be dropped, rerouted, or handled by dropless execution.

Capacity is (tokens per batch * k / number of experts) * capacity factor. That gives (4096 * 2 / 32) * 1.0 = 256 assignments per expert. A hot expert with 400 assignments exceeds the buffer by 144, and the quality or throughput impact depends on the configured overflow policy.

7.An MoE candidate activates fewer parameters per token than a dense model, but its batch-size-1 p95 latency is worse while batch-size-64 throughput is better. Which diagnosis fits this pattern?

Correct answer: At batch size 1, router work, grouping, dispatch, and all-to-all combine overhead can dominate; larger batches amortize those costs through grouped expert execution.

Sparse expert FLOPs don't automatically minimize latency. MoE adds routing, token grouping, dispatch to expert devices, and result combination. With one request there may be too little work to amortize that coordination, while larger batches can group many token assignments into efficient expert GEMMs.

8.A serving stack already uses tensor parallelism to shard large matrix multiplications, but an MoE layer places different full experts on different GPUs. What additional mechanism is needed for the routed FFNs?

Correct answer: Expert parallelism with token dispatch and combine, so each token's hidden state can reach the GPUs that own its selected experts and return outputs in token order.

Tensor parallelism shards individual matrix operations. MoE serving also has a placement problem: different whole expert FFNs may live on different devices, so routed token states must be sent to the owning GPUs and their outputs combined back into the original token order.

9.A team switches from token-choice top-k routing to expert-choice routing, where each expert picks a fixed-size bucket of top-scoring tokens from the batch. What problem is solved, and what new risk appears?

Correct answer: Expert-side load becomes predictable, but token coverage is no longer automatic; some tokens can be selected many times and others not at all.

Expert-choice routing fixes the number of tokens each expert processes, which makes expert-side load balancing predictable. The trade-off moves to the token side: unless coverage rules are added, a token may be selected by multiple experts or by none.

10.A cluster's all-to-all links are saturated, and routing traces suggest many experts duplicate common computation. Which change directly addresses both constraints while preserving sparse routed experts?

Correct answer: Add shared always-on experts for common work and limit each token's routed experts to a small set of devices.

Shared experts provide a common path intended to reduce redundant computation across routed experts. Device-limited routing constrains selected experts to fewer devices, directly reducing cross-device dispatch pressure. Increasing top-k or ignoring expert ownership can increase communication, while replicating attention changes the wrong sublayer.

10 questions remaining.

Next Step
Continue to Mamba & State Space Models

MoE sparsifies the feed-forward path, but most of these models still mix tokens with attention, so KV-cache growth remains a long-context cost. The next chapter compares selective state-space processing with attention, including why some production MoE backbones already interleave a linear-time mixer.

PreviousLong Context Window Management
Share this article
XFacebookLinkedInBlueskyRedditHacker NewsEmail
References

Switch Transformers: Scaling to Trillion Parameter Models with Simple and Efficient Sparsity.

Fedus, W., Zoph, B., & Shazeer, N. · 2022

https://arxiv.org/abs/2101.03961

Mixtral of Experts.

Jiang, A. Q., et al. · 2024

https://arxiv.org/abs/2401.04088

DeepSeek-V2: A Strong, Economical, and Efficient Mixture-of-Experts Language Model

DeepSeek-AI · 2024

https://arxiv.org/abs/2405.04434

DeepSeek-V3 Technical Report.

DeepSeek-AI · 2024 · arXiv preprint

https://arxiv.org/abs/2412.19437

Qwen3.6-35B-A3B

Qwen Team · 2026

https://huggingface.co/Qwen/Qwen3.6-35B-A3B

GLM-5.2 Model Card

Z.AI · 2026

https://huggingface.co/zai-org/GLM-5.2

DeepSeek-V4-Flash-0731 Model Card

DeepSeek-AI · 2026

https://huggingface.co/deepseek-ai/DeepSeek-V4-Flash-0731

Outrageously Large Neural Networks: The Sparsely-Gated Mixture-of-Experts Layer.

Shazeer, N., et al. · 2017 · ICLR 2017

https://arxiv.org/abs/1701.06538

Mixture-of-Experts with Expert Choice Routing

Zhou, Y., et al. · 2022

https://arxiv.org/abs/2202.09368

GLU Variants Improve Transformer

Shazeer, N. · 2020

https://arxiv.org/abs/2002.05202

GLM-5 Repository

Z.AI · 2026

https://github.com/zai-org/GLM-5

DeepSeek-V4: Towards Highly Efficient Million-Token Context Intelligence

DeepSeek-AI · 2026

https://arxiv.org/abs/2606.19348

GLM-5.2 Configuration

Z.AI · 2026

https://huggingface.co/zai-org/GLM-5.2/blob/main/config.json

GLM-5.2 Model Documentation

Z.AI · 2026

https://docs.z.ai/guides/llm/glm-5.2

GLM-5.2

Z.AI · 2026

https://z.ai/blog/glm-5.2

DeepSeek-V4-Flash-DSpark Model Card

DeepSeek-AI · 2026

https://huggingface.co/deepseek-ai/DeepSeek-V4-Flash-DSpark

ST-MoE: Designing Stable and Transferable Sparse Expert Models

Zoph, B., et al. · 2022

https://arxiv.org/abs/2202.08906

Discussion

Questions and insights from fellow learners.

Discussion loads when you reach this section.