Overview

9 Dynamic routing with Mixture of Experts

Mixture of Experts is presented as a practical dynamic routing strategy that adapts computation at runtime instead of forcing every token through the same dense path. The chapter begins by contrasting MoE with other dynamic inference methods such as early exiting and token dropping, then argues that MoE is the most mature and relevant of the three for modern small language models. The core idea is simple: replace dense MLP modules with specialized experts and a learned router that decides, token by token, which expert or experts should process the hidden states.

The first hands-on project builds a two-expert MoE on SmolLM2-1.7B-Instruct using sparse upcycling, where selected MLP layers are duplicated into a frozen general expert and a trainable clinical expert. A new MoE block is inserted into deeper layers, while attention and normalization remain unchanged, and training focuses only on the clinical expert and the router. The chapter explains soft routing, where both experts contribute with learned weights, and hard routing, where a binary decision sends each token to a single expert. It also shows how training data from both clinical extraction and general conversation helps the router learn to separate domains without harming the model’s broader abilities.

The second project reuses a previously fine-tuned clinical model as an expert, turning the MoE into a transplant-and-adapt setup. A more general top-k MoE class is introduced to support multiple experts and selective activation, with inference using only the most relevant experts per token. Because the transplanted MLP had originally been paired with different attention layers, the chapter adds a small extra training phase to adapt the expert’s tail layers and recover full clinical performance. Across both projects, the results show that MoE can preserve or even improve general behavior while adding specialization, and the chapter closes by connecting these toy-scale implementations to larger research systems such as sparse upcycling and Mixtral-style routing.

The MoE block replaces the MLP module in selected transformer layers. A router receives the hidden states and assigns routing weights to two experts that process in parallel — expert_general, which holds the original MLP weights (frozen), and expert_clinical, the trainable copy. Attribute names in parentheses correspond directly to the model's code structure.
The MoE block replaces the MLP module in selected transformer layers. A router receives the hidden states and assigns routing weights to two experts that process in parallel — expert_general, which holds the original MLP weights (frozen), and expert_clinical, the trainable copy. Attribute names in parentheses correspond directly to the model's code structure.
Two routing behaviors applied to the same token. Soft routing (left, top-k = 2) runs both experts in parallel and combines their outputs in a weighted sum — × 0.38 for expert_general, × 0.62 for expert_clinical. Hard routing (right, top-k = 1) selects expert_clinical via argmax and passes its output through directly.
Two routing behaviors applied to the same token. Soft routing (left, top-k = 2) runs both experts in parallel and combines their outputs in a weighted sum — × 0.38 for expert_general, × 0.62 for expert_clinical. Hard routing (right, top-k = 1) selects expert_clinical via argmax and passes its output through directly.
Benchmark comparison across five general-knowledge tasks for the base model, MoE Soft, and MoE Hard. Delta values expressed in percentage points (pp) relative to the baseline.
Benchmark comparison across five general-knowledge tasks for the base model, MoE Soft, and MoE Hard. Delta values expressed in percentage points (pp) relative to the baseline.
Two views of the same top-k routing decision. Left: the router produces one logit score per expert for each token; the two highest scores per row (highlighted) are selected. Right: the same assignments reorganized by expert, showing which tokens each expert will process and their renormalized weights — for each token, those weights sum to 1 across its assigned experts. The example uses four experts rather than two so that top_k = 2 leaves half the experts idle per token. The loop in TrainableTopKMoE.forward performs exactly this regrouping.
Two views of the same top-k routing decision. Left: the router produces one logit score per expert for each token; the two highest scores per row (highlighted) are selected. Right: the same assignments reorganized by expert, showing which tokens each expert will process and their renormalized weights — for each token, those weights sum to 1 across its assigned experts. The example uses four experts rather than two so that top_k = 2 leaves half the experts idle per token. The loop in TrainableTopKMoE.forward performs exactly this regrouping.
Two-phase training strategy for the upcycled MoE. Phase 1 trains only the router across all 24 layers (lr = 1e-3) for three epochs — 98,304 parameters, 0.0034% of the model — reaching 90% schema compliance. Phase 2 reduces the router learning rate to lr = 1e-6 and unfreezes the expert_clinical tail layers 18–23 at lr = 1e-5 for one epoch, bringing trainable parameters to 10.35% and compliance to 100%.
Two-phase training strategy for the upcycled MoE. Phase 1 trains only the router across all 24 layers (lr = 1e-3) for three epochs — 98,304 parameters, 0.0034% of the model — reaching 90% schema compliance. Phase 2 reduces the router learning rate to lr = 1e-6 and unfreezes the expert_clinical tail layers 18–23 at lr = 1e-5 for one epoch, bringing trainable parameters to 10.35% and compliance to 100%.
Benchmark comparison across five general-knowledge tasks for the upcycled MoE, baseline vs top_k=2 vs top_k=1.
Benchmark comparison across five general-knowledge tasks for the upcycled MoE, baseline vs top_k=2 vs top_k=1.

Summary

  • Dynamic inference techniques, like early exiting, token dropping, and Mixture of Experts, allow the model to make runtime decisions about what to compute. Of the three, MoE is the most mature and the only one with growing support in standard inference libraries.
  • An MoE architecture is built around three elements. Experts process information independently, the router decides which expert acts on each token, and the combined forward pass merges their outputs into a single response.
  • Building an MoE starting from a copy of the base model weights allows initializing the experts with already-acquired knowledge, instead of starting from scratch. This strategy, known as sparse upcycling, speeds up convergence.
  • Soft routing and hard routing are two inference behaviors that can be obtained on the same trained weights, by modifying only the forward method. The model's behavior depends both on its weights and on how the experts' outputs are combined.
  • The router does not work on raw tokens, but on their hidden states, which accumulate the context of everything that has occurred before in the sequence. That is why the same token can be sent to different experts depending on the context in which it appears.
  • The TrainableTopKMoE class generalizes the architecture to accept a configurable number of experts and a top-k parameter that controls how many of them are activated per token.
  • An MLP Module from a pre-trained model can be transplanted directly as an expert into an MoE architecture, without the need to retrain it from scratch. This opens the door to reusing existing specialized models as components of a larger system.
  • If the transplanted expert comes from a model with a different Attention Module than the base model, it might need a light adjustment to adapt to the tensors it receives. A light training of the layers closest to the output is usually enough to recover full performance.
  • Specializing an expert in a specific domain does not necessarily penalize the general capabilities of the model. General benchmarks of the MoE model built in this chapter are maintained or improved compared to the base model.

FAQ

What is dynamic inference, and why is it useful for LLMs?Dynamic inference is a runtime strategy that decides what to compute, skip, or route for each token instead of running the full model identically for every input. It is useful because many inputs do not need the full computational cost of a dense forward pass, so the model can become more efficient or specialized.
What are the three main dynamic inference techniques covered in this chapter?The chapter covers early exiting, token dropping, and Mixture of Experts. Early exiting stops computation once the model is confident enough, token dropping removes less important tokens from later layers, and MoE routes tokens to specialized experts.
How does early exiting decide when to stop processing?Early exiting uses intermediate exit points in the model and checks whether the logits indicate enough confidence in the answer. If the probability distribution is concentrated enough on a likely token, the model exits before finishing all layers.
How does token dropping reduce computation?Token dropping removes tokens that appear less important, often based on attention weights, so later layers process a shorter sequence. This also reduces KV cache usage, which is especially beneficial for long contexts.
What is a Mixture of Experts architecture in this chapter?A Mixture of Experts replaces dense MLP modules with multiple specialized experts plus a router. The router decides, token by token, which expert or experts should process each hidden state, allowing the model to specialize without changing the whole network.
What are the three core components of an MoE block?The three components are the experts, the router, and the combined forward pass. The experts process the input independently, the router assigns weights or selections, and the combined pass merges the expert outputs into one result.
What is sparse upcycling in the context of building an MoE?Sparse upcycling means initializing new MoE experts from already trained dense model weights instead of random initialization. In this chapter, the model’s MLP layers are duplicated so one expert preserves the base behavior while another can specialize.
What is the difference between soft routing and hard routing?Soft routing blends the outputs of multiple experts using router-assigned weights, so every selected expert contributes to the final output. Hard routing makes a binary choice per token and sends it to only one expert, which is more selective at inference time.
Why does the chapter add noise to router logits during training?Noise helps prevent the router from collapsing too early to a single expert. By encouraging exploration in the first epochs, both experts get training signal and the specialized expert has time to learn useful behavior.
How does the chapter reuse a previously fine-tuned clinical model as an MoE expert?It extracts the clinical model’s MLP layers and inserts them as an expert in a new MoE, while keeping the base model as another expert. Then it trains mainly the router, and later lightly fine-tunes the expert’s tail layers to adapt it to the base model’s attention outputs.

pro $24.99 per month

  • access to all Manning books, MEAPs, liveVideos, liveProjects, and audiobooks!
  • choose one free eBook per month to keep
  • exclusive 50% discount on all purchases
  • renews monthly, pause or cancel renewal anytime

lite $19.99 per month

  • access to all Manning books, including MEAPs!

team

5, 10 or 20 seats+ for your team - learn more


Close
choose your plan

team

monthly
annual
$49.99
$499.99
only $41.67 per month
  • five seats for your team
  • access to all Manning books, MEAPs, liveVideos, liveProjects, and audiobooks!
  • choose another free product every time you renew
  • choose twelve free products per year
  • exclusive 50% discount on all purchases
  • renews monthly, pause or cancel renewal anytime
  • renews annually, pause or cancel renewal anytime
  • Rearchitecting LLMs Rearchitecting LLMs ebook for free
Close
choose your plan

team

monthly
annual
$49.99
$499.99
only $41.67 per month
  • five seats for your team
  • access to all Manning books, MEAPs, liveVideos, liveProjects, and audiobooks!
  • choose another free product every time you renew
  • choose twelve free products per year
  • exclusive 50% discount on all purchases
  • renews monthly, pause or cancel renewal anytime
  • renews annually, pause or cancel renewal anytime
  • Rearchitecting LLMs Rearchitecting LLMs ebook for free