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.
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.
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%.
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.
Rearchitecting LLMs ebook for free