Overview
Instead of one large network that handles every input, a mixture of experts keeps several smaller networks and a gate that decides which of them should answer. In the sparse form, the gate picks only the best few experts for each input and the rest are not run at all. Different inputs travel through different experts, so the experts can specialise. The model holds many parameters in total but uses only a fraction of them on any one input. This template is a small regression version of the routing used inside large language models.
A short history
Robert Jacobs, Michael Jordan, Steven Nowlan and Geoffrey Hinton introduced mixtures of experts in 1991: several networks specialise on parts of the input space and a gating network decides which to trust. In 2017 Noam Shazeer and colleagues made the gate sparse, so only the top few experts run for each input, which lets a model grow much larger without a matching rise in compute. Sparse expert layers are now used inside some large language models, including Mistral's Mixtral.
How it works
- The gate computes one score per expert from the input: .
- Keep the top_k highest scores in each row and take a softmax over just those. Every other expert gets weight exactly 0.
- Run each expert only on the rows routed to it. An expert is one ReLU hidden layer followed by a linear output.
- The output is the gate-weighted sum of the chosen experts' outputs.
- Backpropagate the half squared error. Chosen experts and their gate scores receive gradient, dropped experts receive none.
- During training, optional Gaussian noise of size noise_std is added to the scores so that close calls sometimes go the other way and load spreads out.
Watch out for
- With top_k set to 1 the single chosen expert always has weight 1, so the gate gets no gradient and keeps its random initial routing. Use top_k of at least 2 if the gate should learn.
- A few experts can win almost every input while the rest are never trained. Check expert_usage and raise noise_std if the load is uneven.
- The choice of which experts are kept is a hard cut with no gradient, so the gate only learns how to weight the experts it already selected.
- This is a small version. Production systems add a load-balancing loss and run experts on separate devices, which the template does not do.
Use cases
When to use it
When you want more model capacity without paying for all of it on every input, or when the data has distinct regimes that different sub-networks can handle. It is the idea behind the expert layers in large language models.
In industry
- Language model providers
- Sparse expert layers inside Transformers, which raise capacity while each token activates only a few experts.
- Machine translation
- Large multilingual models in which different experts come to specialise in different languages or domains.
- Recommendation
- Routing different kinds of users or contexts to specialised sub-networks within one ranking model.
Choosing it: what must hold
- Inputs that fall into regimes which benefit from different specialised functions.
- Enough data for every expert to receive a useful share of the examples.
- A load balancing term or similar measure, so the gate does not send everything to one expert.
When to choose something else
| If | Use instead |
|---|---|
| The dataset is small or uniform | A single MLP of the same total size |
| You have several tasks, not several input regimes | Multi-gate Mixture-of-Experts (MMoE) |
| You want the benefit of combining models on tabular data | A random forest or gradient boosted trees |
Math foundations
Gate scores
One score per expert, a linear function of the input. A higher score means the gate thinks that expert suits this input better.
Top-k gate
is the set of the highest-scoring experts for this row. The softmax runs over that set only, so the kept weights sum to 1.
One expert
Each expert is a small network of its own. It is evaluated only for rows where .
The output and loss
A weighted sum over the kept experts only, scored by half the mean squared error.
Gradient at the gate scores
The softmax rule restricted to the kept experts. A score rises when its expert helps more than the weighted average of the kept experts. With the bracket is , so the gate cannot learn.
Share of experts computed
The saving that makes the method worthwhile: the cost per input depends on , while the capacity depends on .
Symbols
- input row
- number of experts, num_experts
- experts used per input, top_k
- gate scores, one per expert
- weights and bias of the gate
- the set of the k highest-scoring experts for this row
- gate weight of expert e
- the function computed by expert e
- hidden and output parameters of expert e
- prediction and target
- how the loss changes as expert e gets more weight
Worked by hand
Four experts, . For one input the gate scores are and the experts would output , , and .
The output is 2.46. Experts 3 and 4 are never evaluated, so their outputs of 7 and play no part.
Visual example
Loading the example.
Try this
- Drag the input x from -2 to 2 and watch which experts light up in the diagram.
- Set top_k to 1 and read how far training moved the gate: it cannot learn where to send each input.
- Set the gate noise to 0 and check whether one expert ends up used far more than the others.
Code sample
import numpy as np
from impl import MoE
from config import MoEConfig
rng = np.random.default_rng(0)
X = rng.uniform(-1, 1, size=(400, 2))
y = np.where(X[:, 0] > 0, 2.0 * X[:, 1] + 1.0, -3.0 * X[:, 1]) # two regimes
model = MoE(MoEConfig(num_experts=4, top_k=2, epochs=100)).fit(X, y)
print(np.mean((model.predict(X) - y) ** 2), y.var()) # squared error is a few percent of the variance of y
print((model.gates(X) > 0).sum(axis=1)[:5]) # exactly top_k experts are active per row: [2 2 2 2 2]
print(model.expert_usage(X).round(2)) # share of routing slots that go to each expertRead the implementation (166 lines)
"""Sparse Mixture-of-Experts with top-k gating, manual backpropagation and Adam.
NumPy only. With n rows, d features, E experts of hidden width h and o outputs:
scores = X Wg + bg (n, E)
gate = softmax over the top_k scores of each row, 0 elsewhere (n, E)
expert_e(x) = relu(x W1[e] + b1[e]) W2[e] + b2[e] evaluated only for the rows routed to e
output = sum_e gate[:, e] * expert_e(x) (n, o)
"""
from __future__ import annotations
import numpy as np
try:
from .config import MoEConfig
except ImportError: # run from the template's own folder
from config import MoEConfig
class _Adam:
"""Adam optimizer over a dict of NumPy arrays; `step` updates the arrays in place."""
def __init__(self, params: dict, lr: float, beta1: float = 0.9, beta2: float = 0.999, eps: float = 1e-8) -> None:
self.params, self.lr, self.beta1, self.beta2, self.eps = params, lr, beta1, beta2, eps
self.m = {k: np.zeros_like(v) for k, v in params.items()}
self.v = {k: np.zeros_like(v) for k, v in params.items()}
self.t = 0
def step(self, grads: dict) -> None:
"""Apply one update. grads: same keys and shapes as the parameters."""
self.t += 1
for k, g in grads.items():
self.m[k] = self.beta1 * self.m[k] + (1 - self.beta1) * g
self.v[k] = self.beta2 * self.v[k] + (1 - self.beta2) * g * g
m_hat = self.m[k] / (1 - self.beta1**self.t)
v_hat = self.v[k] / (1 - self.beta2**self.t)
self.params[k] -= self.lr * m_hat / (np.sqrt(v_hat) + self.eps)
class MoE:
"""Sparse MoE regressor. After `fit`: `params`, `loss_history_` (mean loss per epoch)."""
def __init__(self, config: MoEConfig | None = None) -> None:
self.config = config or MoEConfig()
self.params: dict[str, np.ndarray] = {}
self.loss_history_: list[float] = []
self._single_target = False
def initialize(self, n_features: int, n_outputs: int = 1) -> None:
"""Create the weights for `n_features` inputs and `n_outputs` outputs."""
cfg = self.config
rng = np.random.default_rng(cfg.seed)
d, E, h, o = n_features, cfg.num_experts, cfg.hidden_dim, n_outputs
self.params = {
"Wg": 0.5 * rng.normal(size=(d, E)),
"bg": np.zeros(E),
"W1": np.sqrt(2.0 / d) * rng.normal(size=(E, d, h)),
"b1": np.zeros((E, h)),
"W2": np.sqrt(1.0 / h) * rng.normal(size=(E, h, o)),
"b2": np.zeros((E, o)),
}
def gate_weights(self, X: np.ndarray, noise: np.ndarray | None = None) -> np.ndarray:
"""Top-k gate. X: (n, d). noise: optional (n, E) added to the scores. Returns (n, E) with k non-zeros per row."""
scores = X @ self.params["Wg"] + self.params["bg"]
if noise is not None:
scores = scores + noise
k = self.config.top_k
kth = np.partition(scores, -k, axis=1)[:, -k][:, None] # the k-th largest score of each row
keep = scores >= kth
# In case of ties at the k-th score keep exactly k, taking the lowest expert indices first.
extra = keep.sum(axis=1) > k
for row in np.flatnonzero(extra):
tied = np.flatnonzero(scores[row] == kth[row, 0])
surplus = keep[row].sum() - k
keep[row, tied[len(tied) - surplus :]] = False
masked = np.where(keep, scores, -np.inf)
e = np.exp(masked - masked.max(axis=1, keepdims=True))
return e / e.sum(axis=1, keepdims=True)
def _forward(self, X: np.ndarray, noise: np.ndarray | None = None) -> dict:
"""Run the network. X: (n, d). Returns the output (n, o), the gate and per-expert caches."""
p = self.params
G = self.gate_weights(X, noise)
out = np.zeros((len(X), p["W2"].shape[2]))
per_expert = []
for e in range(self.config.num_experts):
rows = np.flatnonzero(G[:, e] > 0) # only the rows routed to this expert are computed
hidden = np.maximum(X[rows] @ p["W1"][e] + p["b1"][e], 0.0)
expert_out = hidden @ p["W2"][e] + p["b2"][e]
out[rows] += G[rows, e][:, None] * expert_out
per_expert.append((rows, hidden, expert_out))
return {"G": G, "out": out, "experts": per_expert}
def loss_and_grads(self, X: np.ndarray, Y: np.ndarray, noise: np.ndarray | None = None) -> tuple[float, dict]:
"""Half mean squared error on a batch and its gradient for every parameter.
X: (n, d). Y: (n, o). noise: optional (n, E) gate noise, held fixed while differentiating.
"""
p = self.params
n = len(X)
cache = self._forward(X, noise)
G = cache["G"]
diff = cache["out"] - Y
loss = 0.5 * np.sum(diff**2) / n
d_out = diff / n
grads = {key: np.zeros_like(value) for key, value in p.items()}
dG = np.zeros_like(G)
for e, (rows, hidden, expert_out) in enumerate(cache["experts"]):
if len(rows) == 0:
continue
dG[rows, e] = np.sum(d_out[rows] * expert_out, axis=1)
d_expert = G[rows, e][:, None] * d_out[rows]
grads["W2"][e] = hidden.T @ d_expert
grads["b2"][e] = d_expert.sum(axis=0)
d_hidden = (d_expert @ p["W2"][e].T) * (hidden > 0)
grads["W1"][e] = X[rows].T @ d_hidden
grads["b1"][e] = d_hidden.sum(axis=0)
# Softmax backward over the kept experts; dropped experts have G = 0 and so get no gradient.
d_scores = G * (dG - np.sum(G * dG, axis=1, keepdims=True))
grads["Wg"] = X.T @ d_scores
grads["bg"] = d_scores.sum(axis=0)
return float(loss), grads
def fit(self, X: np.ndarray, y: np.ndarray) -> "MoE":
"""Train with mini-batch Adam. X: features, shape (n, d). y: real targets, shape (n,) or (n, o)."""
cfg = self.config
X = np.asarray(X, dtype=float)
y = np.asarray(y, dtype=float)
if X.ndim != 2 or len(X) != len(y):
raise ValueError("X must have shape (n, d) and y must have n rows")
self._single_target = y.ndim == 1
Y = y.reshape(len(y), -1)
self.initialize(X.shape[1], Y.shape[1])
optimizer = _Adam(self.params, cfg.lr)
rng = np.random.default_rng(cfg.seed + 1)
self.loss_history_ = []
n = len(X)
for _ in range(cfg.epochs):
order = rng.permutation(n)
total = 0.0
for start in range(0, n, cfg.batch_size):
rows = order[start : start + cfg.batch_size]
noise = cfg.noise_std * rng.normal(size=(len(rows), cfg.num_experts)) if cfg.noise_std > 0 else None
loss, grads = self.loss_and_grads(X[rows], Y[rows], noise)
optimizer.step(grads)
total += loss * len(rows)
self.loss_history_.append(total / n)
return self
def predict(self, X: np.ndarray) -> np.ndarray:
"""Predicted targets (no gate noise). X: (n, d). Returns shape (n,) or (n, o)."""
if not self.params:
raise RuntimeError("call fit (or initialize) before predicting")
out = self._forward(np.asarray(X, dtype=float))["out"]
return out[:, 0] if self._single_target else out
def gates(self, X: np.ndarray) -> np.ndarray:
"""Gate weights without noise. X: (n, d). Returns (n, E); each row has `top_k` non-zeros that sum to 1."""
if not self.params:
raise RuntimeError("call fit (or initialize) before predicting")
return self.gate_weights(np.asarray(X, dtype=float))
def expert_usage(self, X: np.ndarray) -> np.ndarray:
"""Share of the n * top_k routing slots that go to each expert. X: (n, d). Returns (E,), sums to 1."""
active = self.gates(X) > 0
return active.sum(axis=0) / active.sum()- Repository
- Not published yet
- Needs
- Python 3.10 and NumPy
- Tests
- 8, run with
python3 -m unittest -v
Practice
Create data where y follows one rule when the first feature is positive and a different rule when it is negative. Fit MoE with MoEConfig num_experts 4 and top_k 2. Call gates and expert_usage to see which experts take which half of the data. Then set top_k to 1 and compare expert_usage and the last value of loss_history_ with the first run.
Check on learning
- With top_k equal to 1 the gate never changes during training, yet the loss still falls. What is learning, and what is not?
A way to think about it
Look at the gradient formula for when the kept set has one member. Then ask which parameters still receive gradient from the output error.
- A dense mixture runs every expert and weights them all. What does the sparse version give up in exchange for its lower cost?
A way to think about it
Think about an input that would benefit a little from a low-ranked expert, and about how an expert that is never selected could ever improve.
- After training, expert_usage shows one expert taking 70 percent of the routing slots. Why is this self-reinforcing, and how does noise on the scores help?
A way to think about it
An expert that is chosen more gets more training and becomes better, which gets it chosen again. Consider what a random perturbation does to close decisions.
- You double num_experts and keep top_k fixed. Predict the effect on parameter count, on the cost of one forward pass, and on how much data each expert sees.
A way to think about it
Use the ratio . The cost per input stays the same, but the same rows are now divided among more experts.