Mixture of Experts, Explained

Fractional CTO · Founder of Injuria.ai
Mixture of Experts (MoE) is a neural network architecture that enables models to scale to trillions of parameters while keeping the computational cost of inference manageable. Instead of a single, monolithic network processing every input, an MoE model contains a collection of smaller subnetworks called "experts". For any given input, a routing mechanism selects a small subset of these experts to perform the computation. This conditional computation means that model size and performance can grow dramatically without a proportional increase in the floating-point operations (FLOPs) required for each prediction, representing a fundamental shift in scaling laws for deep learning.
This technique is not new, with conceptual roots in the early 1990s, but recent advancements have made it the predominant architecture for state-of-the-art large language models[1] (LLMs). Understanding MoE is critical for any technical leader or engineer working with modern AI, as it involves significant tradeoffs in memory, communication overhead, and training complexity that directly impact system design and deployment strategy.
How Mixture of Experts Works
At its core, the MoE architecture modifies a standard Transformer model[2]. In a typical Transformer, the self-attention layers are followed by a position-wise feed-forward network[3] (FFN). This FFN block is where most of the model's parameters reside. An MoE model replaces this dense FFN layer with a sparse MoE layer, which contains the key components that make conditional computation possible.
The Components of an MoE Layer
An MoE layer consists of two primary elements:
-
A set of expert networks: These are typically identical in architecture to each other. In the context of a Transformer, each expert is its own FFN. For example, in a model described as "8x7B", there are eight distinct expert networks, each with approximately 7 billion parameters. These experts are the "knowledge workers" of the layer.
-
A gating network, or router: This is a small neural network that acts as a traffic controller. Its job is to examine each input token and decide which of the experts are best suited to process it. The router is the brain of the operation, and its performance is crucial for the effectiveness of the entire model.
The Routing Mechanism: Step-by-Step
The process of routing a single token through an MoE layer is a precise, multi-step sequence. Let's assume we have N experts and we want to select the top k experts for each token (a common configuration is k=2).
-
Input: A token, represented by a high-dimensional vector
x, arrives at the MoE layer from the preceding layer (e.g., a self-attention layer). -
Scoring: The token vector
xis fed into the gating network. The gating network is usually a simple linear layer with a weight matrixW_g. It produces a vector of logits,h(x) = x · W_g, which contains a score for each of theNexperts. -
Gating Values: A softmax function[4] is applied to the logits. This converts the scores into a probability distribution,
G = softmax(h(x)). Thei-th value inG,G_i, represents the router's confidence that expertE_iis the correct choice for this token. -
Expert Selection: Instead of using all experts, the router employs a sparse strategy called Top-k routing. It identifies the
kexperts with the highest probability scores in the vectorG. All other experts will be ignored for this specific token. -
Combining Outputs: The original token vector
xis sent only to the selectedkexperts. The final output of the MoE layer for this token is a weighted sum of the outputs from these active experts. The weights are the normalized softmax scores of the selected experts. The formula isy = Σ (G_i * E_i(x))for theiin the topkexperts. This ensures that the experts deemed more important by the router have a greater influence on the final result.
Load Balancing and Auxiliary Losses
A naive routing strategy presents a serious problem: the gating network might quickly learn to favor a small number of experts, sending most tokens to them. This leads to undertrained and useless experts, defeating the purpose of the architecture. This phenomenon is known as expert collapse.
To counteract this, MoE models include an auxiliary loss function[5] during training, as detailed in the paper that re-popularized the technique, "Outrageously Large Neural Networks"[6]. This loss incentivizes the router to distribute tokens more evenly across all available experts. It's calculated based on the fraction of tokens in a training batch that are assigned to each expert. If one expert receives a disproportionately large number of tokens, the auxiliary loss adds a penalty term to the main model loss, which is then minimized during backpropagation[7]. This forces the router to learn a more balanced routing policy, ensuring all experts become specialized and contribute to the model's overall capability.
A Brief History and Evolution
The concept of using mixtures of experts is not a recent invention. The foundational ideas were laid out in a 1991 paper, "Adaptive Mixtures of Local Experts" by Robert Jacobs, Michael Jordan, Stephen Nowlan, and Geoffrey Hinton. They proposed a system where different networks (experts) would specialize in different parts of the input space, managed by a gating network. However, for decades, the approach remained a niche academic topic due to training instability and computational and software complexities that made it impractical to implement at scale.
The modern resurgence of MoE began with the 2017 paper from Google researchers including Noam Shazeer, which introduced sparse gating with the crucial load-balancing loss. This made it possible to train models with hundreds of billions of parameters. The true turning point for LLMs came with another Google paper, "GShard: Scaling Giant Models with Conditional Computation and Automatic Sharding" in 2020. This work successfully applied the MoE architecture to the Transformer, demonstrating massive performance gains in machine translation and setting the blueprint for today's MoE-based LLMs.
This led directly to the development of models like Google's Gemini[8] family and influential open-source models such as Mistral AI's Mixtral 8x7B[9] and Databricks' DBRX[10], cementing MoE as a key architecture for pushing the boundaries of AI.
A Worked Example: Simplified MoE Layer
Here is a simplified implementation of an MoE layer in PyTorch[11] to illustrate the core concepts. This example omits optimizations like capacity factors and the full auxiliary loss for clarity, but demonstrates the essential routing logic.
import torch
import torch.nn as nn
import torch.nn.functional as F
class SimpleExpert(nn.Module):
"""A simple feed-forward network as an expert."""
def __init__(self, input_dim, output_dim, hidden_dim=256):
super().__init__()
self.net = nn.Sequential(
nn.Linear(input_dim, hidden_dim),
nn.ReLU(),
nn.Linear(hidden_dim, output_dim)
)
def forward(self, x):
return self.net(x)
class SimpleMoELayer(nn.Module):
"""A simplified Mixture of Experts layer."""
def __init__(self, input_dim, output_dim, num_experts, top_k=2):
super().__init__()
self.num_experts = num_experts
self.top_k = top_k
# Create the expert networks
self.experts = nn.ModuleList([SimpleExpert(input_dim, output_dim) for _ in range(num_experts)])
# Create the gating network (router)
self.gate = nn.Linear(input_dim, num_experts)
def forward(self, x):
# x has shape: (batch_size, seq_len, input_dim)
batch_size, seq_len, input_dim = x.shape
x = x.view(-1, input_dim) # Reshape to (batch_size * seq_len, input_dim)
# 1. Get router logits from the gating network
router_logits = self.gate(x)
# 2. Get weights and indices of the top_k experts
# Gating values are softmax over the logits
gating_weights = F.softmax(router_logits, dim=1)
# Select top_k gating values and their indices
top_k_weights, top_k_indices = torch.topk(gating_weights, self.top_k, dim=1)
# 3. Normalize the top_k weights so they sum to 1
top_k_weights = top_k_weights / top_k_weights.sum(dim=1, keepdim=True)
# 4. Create a sparse tensor to hold the final output
final_output = torch.zeros_like(x)
# This is a simplified, non-vectorized loop for clarity.
# In practice, this is done with efficient scatter/gather operations.
for i in range(x.size(0)): # For each token
for j in range(self.top_k): # For each chosen expert
expert_idx = top_k_indices[i, j].item()
weight = top_k_weights[i, j]
# Get the output from the chosen expert
expert_output = self.experts[expert_idx](x[i].unsqueeze(0))
# Weight the expert's output and add to the token's final output
final_output[i] += weight * expert_output.squeeze(0)
return final_output.view(batch_size, seq_len, -1)
# Example Usage
input_dim = 512
output_dim = 512
num_experts = 8
top_k = 2
moe_layer = SimpleMoELayer(input_dim, output_dim, num_experts, top_k)
# Create a dummy input tensor
# Batch of 4 sequences, each with 10 tokens of dimension 512
input_tensor = torch.randn(4, 10, input_dim)
output_tensor = moe_layer(input_tensor)
print("Input shape:", input_tensor.shape)
print("Output shape:", output_tensor.shape)
This code defines an SimpleMoELayer that routes each token to its top_k experts and combines their outputs. The loop in the forward pass is intentionally explicit to show the logic; real-world implementations use highly optimized, parallelized operations to avoid such loops.
The Real Tradeoffs: Costs and Benefits
Adopting an MoE architecture is a significant engineering decision with profound consequences for model performance and system requirements.
Benefit: Decoupling Parameters from Computation
The primary advantage of MoE is separating the number of model parameters from the computational cost (FLOPs) per inference step. A model can contain trillions of parameters, giving it a vast capacity for knowledge, but only activate a small fraction (e.g., 25 billion out of 1 trillion) for any single token. This results in inference speeds comparable to a much smaller dense model while achieving the performance benefits of a much larger one. For a fixed compute budget, MoE models consistently outperform their dense counterparts.
Cost: Increased Memory (VRAM) Requirements
This is the most significant drawback. While only a few experts are active at any moment, all experts must be loaded into the accelerator's memory (e.g., GPU VRAM) to be available for the router. An 8x7B MoE model does not have the memory footprint of a 7B or 14B model; it requires enough memory to hold all 8 experts (totaling 56B parameters) plus the shared attention and gating parameters. This makes running large MoE models impossible on most consumer hardware and requires substantial, often distributed, memory resources in data centers.
Cost: Communication Overhead
In a distributed setting, where the model is spread across multiple GPUs or TPUs, the MoE layer introduces a communication bottleneck. Each token's representation must be sent from its current accelerator to the accelerator holding the expert selected by the router. After computation, the result must be sent back. This all-to-all communication pattern can be extremely demanding on the network interconnect between accelerators. High-speed interconnects like NVIDIA NVLink[12] or Google's custom Inter-Chip Interconnect (ICI) are essential to prevent communication from becoming the primary performance bottleneck.
Cost: Training Instability and Complexity
MoE models are notoriously more difficult to train than dense models. The dynamics of the gating network, combined with the need to tune the auxiliary load balancing loss, introduce new hyperparameters[13] and potential instabilities. Issues like expert capacity (an expert receiving more tokens than it can handle in a batch) and dropped tokens must be managed. Effective fine-tuning also requires careful consideration of whether to train the gating network, the experts, or both.
The Technical Leader's Decision Lens
Deciding whether to build or deploy an MoE model requires weighing these tradeoffs.
When to consider MoE:
- You are building a frontier foundation model where scaling parameters is the goal, but inference FLOPs are a constraint.
- You have access to a distributed computing cluster with high-memory accelerators and high-speed interconnects.
- Your team possesses the expertise to manage complex distributed training, fine-tuning, and potential training instabilities.
- The objective is to achieve the highest possible model quality for a given inference compute budget.
When to avoid MoE:
- Your primary deployment constraint is memory (VRAM), not computational throughput.
- The model needs to run on consumer-grade hardware or resource-constrained edge devices.
- Your team is smaller or focused on rapid application development rather than deep infrastructure and training optimization.
- A smaller, dense model provides "good enough" performance for your task, making the complexity of MoE unnecessary.
Correcting Common Misconceptions
Misconception 1: "An 8x7B MoE is the same as a 56B dense model."
Correction: This is false. While it has parameters in the ballpark of a 56B model (specifically, 8 * 7B for the experts plus shared parameters), its computational cost for inference is closer to a 14B model (if k=2), since only two experts are active per token. Its performance is not that of a dense 56B model, but it is substantially better than a dense 7B or 14B model, offering a powerful compromise.
Misconception 2: "Each expert specializes in a human-interpretable topic like 'history' or 'coding'."
Correction: This is a tempting but inaccurate analogy. While experts do specialize, this specialization occurs in a high-dimensional mathematical space that does not neatly map to human concepts. The router learns to group tokens that require similar computational patterns, not necessarily tokens that are semantically related in a way we would understand. Research into interpreting expert function is ongoing, but for now, it's best to think of them as specialized computational pathways, not topical knowledge bases.
Misconception 3: "MoE is a brand new technology invented for LLMs."
Correction: The core concepts of MoE have existed since the early 1990s. The recent excitement is due to a confluence of factors: algorithmic breakthroughs in training stability (like the load balancing loss), the development of hardware (GPUs/TPUs with high memory) capable of holding the models, and the discovery that the Transformer architecture scales exceptionally well with the MoE approach.
The State of MoE Today
Today, MoE is the de facto standard for building top-tier LLMs. Its adoption is widespread across both proprietary and open-source models. It has proven to be the most effective known method for scaling model quality while keeping inference latency and cost under control.
Major deep learning frameworks like TensorFlow[14], JAX[15], and PyTorch provide the necessary primitives for building MoE models. Specialized libraries such as Microsoft's DeepSpeed[16] and NVIDIA's Megatron-LM[17] offer highly optimized implementations for large-scale distributed training of MoE models. As research continues, future work will likely focus on more dynamic and intelligent routing strategies, methods to reduce the memory footprint through techniques like quantization or expert offloading, and a deeper understanding of the specialization that occurs within the experts.
Sources (17)
- Large language model - Wikipedia
- Transformer (machine learning model) - Wikipedia
- Feedforward neural network - Wikipedia
- Softmax function - Wikipedia
- Loss function - Wikipedia
- Outrageously Large Neural Networks - arXiv
- Backpropagation - Wikipedia
- Introducing Gemini - Google DeepMind
- Mixtral of Experts - Mistral AI
- Introducing DBRX - Databricks
- PyTorch
- NVIDIA NVLink
- Hyperparameter (machine learning) - Wikipedia
- TensorFlow
- JAX - GitHub
- Microsoft DeepSpeed - GitHub
- NVIDIA Megatron-LM - GitHub