Mixture of experts: store many, evaluate a few
混合专家模型
Compute dense and sparse gates, train a small conditional mixture and distinguish active computation from stored capacity.
mixture-of-expertsStart with the problem
A mixture of experts contains several separately parameterized functions and a gate that decides how to combine them for a particular input. “Expert” names a component; it does not guarantee that the component has acquired a human-recognizable specialty.
Jacobs, Jordan, Nowlan and Hinton’s 1991 paper studies supervised expert specialization through a gating network. Shazeer and colleagues use sparse gates inside a deep model so only selected experts need evaluation at each position. Our example implements a conditional weighted-output layer and its own squared-error training objective, not the original 1991 learning procedure.
Definitions and derivation
Append an intercept feature to a two-coordinate input. Each of three gate rows produces a score, and each expert row produces a scalar output. A dense mixture evaluates all three:
Softmax weights sum to one, but expert outputs can be negative or exceed one. Thus the result is a regression output, not a class probability. The gate depends on x, unlike a fixed-weight ensemble.
To make computation sparse, select the k highest scores and normalize only over that set:
Unselected expert functions are not evaluated. This is the deterministic top-k convention used here, without the learned Gaussian noise in Shazeer’s training gate. Reusing the original full-softmax probabilities without renormalizing would compute a different function. With k=1 in this particular normalized convention, the selected weight is exactly one. Within a region where its selected index stays fixed, the output has no gradient through the gate scores. This must not be generalized to every top-1 router: expert routing describes a convention that retains the original gate magnitude.
For dense training, differentiate the weighted output and use the softmax Jacobian:
The expert gradient receives its gate weight. The gate gradient compares that expert’s output with the current mixture output. Summing the score derivatives across experts gives zero, consistent with adding one shared constant to every score. If all expert outputs are identical, the task-loss gate gradient vanishes even when the prediction is wrong; a separate balancing objective may still supply a signal.
Run the calculation
The complete Python 3.12 / NumPy 1.26.4 program first compares dense, top-2 and top-1 evaluation at the same input and initial parameters. It then trains the dense gate and all expert parameters on four declared regression examples for 100 steps.
import numpy as np
def softmax(scores):
values = np.exp(scores - np.max(scores))
return values / values.sum()
def initial():
gates = np.array([[1,-1,0],[.5,-.5,0],[0,0,0]], dtype=float)
experts = np.array([[1,0,0],[0,1,3],[-1,1,1]], dtype=float)
return gates, experts
def mixture(x, gates, experts, k=None):
x, gates, experts = [np.asarray(v,dtype=float) for v in (x,gates,experts)]
if x.shape != (2,) or gates.shape != (3,3) or experts.shape != (3,3) or not all(np.isfinite(v).all() for v in (x,gates,experts)):
raise ValueError('Use a two-feature input and two finite 3x3 parameter matrices.')
if k is not None and (type(k) is not int or not 1 <= k <= 3):
raise ValueError('Select one, two or three experts.')
augmented = np.r_[x,1.0]; scores = gates @ augmented
chosen = list(range(3)) if k is None else sorted(range(3),key=lambda i:(-scores[i],i))[:k]
weights = softmax(scores[chosen])
values = np.array([experts[i] @ augmented for i in chosen])
return float(weights @ values), chosen, weights, values
def dense_loss_grad(x, target, gates, experts):
value, _, probabilities, values = mixture(x,gates,experts)
residual = value - target; augmented = np.r_[x,1.0]
dg = residual * (probabilities * (values-value))[:,None] * augmented
de = residual * probabilities[:,None] * augmented
return residual**2/2, dg, de
def train(steps=100):
if type(steps) is not int or not 0 <= steps <= 300:
raise ValueError('Use 0 to 300 training steps.')
gates, experts = initial()
x = np.array([[1,-1],[-1,1],[1,1],[-1,-1]],dtype=float); y = np.array([.5,.5,1,1])
history = []
for _ in range(steps):
rows = [dense_loss_grad(a,b,gates,experts) for a,b in zip(x,y)]
history.append(float(np.mean([r[0] for r in rows])))
gates -= .05*np.mean([r[1] for r in rows],axis=0)
experts -= .05*np.mean([r[2] for r in rows],axis=0)
final = float(np.mean([dense_loss_grad(a,b,gates,experts)[0] for a,b in zip(x,y)]))
return gates, experts, history, final
if __name__ == '__main__':
gates, experts = initial()
for k in (None,2,1):
value, chosen, weights, _ = mixture([1,-1],gates,experts,k)
print('k',k,'chosen',chosen,'weights',weights.round(9).tolist(),'output',round(value,9),'expert evaluations',len(chosen))
_, _, history, final = train()
print('dense training initial / final loss',round(history[0],9),round(final,9))
print('stored parameter entries',gates.size+experts.size,'router dot-product terms 9; expert terms 3 per chosen expert')
Actual output:
k None chosen [0, 1, 2] weights [0.665240956, 0.244728471, 0.090030573] output 1.064667325 expert evaluations 3
k 2 chosen [0, 1] weights [0.731058579, 0.268941421] output 1.268941421 expert evaluations 2
k 1 chosen [0] weights [1.0] output 1.0 expert evaluations 1
dense training initial / final loss 0.889538366 0.029400843
stored parameter entries 18 router dot-product terms 9; expert terms 3 per chosen expert
Dense output is 1.064667325, top-2 output is 1.268941421, and top-1 output is 1. The computation policies are not interchangeable approximations with a guaranteed error bound. The printed dense training loss falls from 0.889538366 to 0.029400843; this is a four-example fit, not a generalization benchmark.
The model stores eighteen parameter entries: nine gate entries and nine expert entries. Every input still uses nine router dot-product terms; each selected expert adds three. Selecting one of three experts therefore does not cut total model work to one third. In a realistic sparse layer, dispatch, selection, normalization and communication also count.
When the method fails
Sparse activation trades computation for routing complexity. If most inputs choose the same expert, some devices become bottlenecks while other parameters receive little training. Very small batches per expert can use accelerators poorly even when nominal arithmetic is low; Shazeer discusses this shrinking-batch problem explicitly.
Experts can collapse toward similar functions, or specialize in patterns that do not transfer to new data. A gate’s high weight is not a guarantee of expertise. The training rule must specify selection noise, capacity, overflow policy, auxiliary losses and whether gate weights are renormalized. The dense mixture trained here has no overflow or inter-device traffic, and its sparse examples demonstrate conditional evaluation rather than a distributed MoE system.
Exercises with answers
- Why do the dense and top-2 outputs differ even before retraining?
Answer 1: An expert is removed and the retained gate weights are renormalized, changing the weighted function.
- How many parameters remain stored when this model evaluates one expert?
Answer 2: All eighteen. Sparse evaluation does not delete unselected parameters.
- What happens to task-loss gate gradients if all expert outputs coincide?
Answer 3: They are zero because each Eₑ−ŷ term is zero, even if the common output misses the target.
- Does top-1 always mean a gate weight of one?
Answer 4: No. It does in this selected-set normalization, but other routers retain the full-softmax gate magnitude.
Sources and next steps
The scanned first page of the 1991 paper establishes the supervised gating/specialization setting. Shazeer’s physical pages 3–4 define the sparse weighted layer, noisy top-k gate and shrinking-batch concern. The affine experts, dense gradients and literal routing comparison are original. Continue with expert routing to audit capacity and dropped contributions.
Make a prediction, then check
What is still computed when only one expert is selected in this example?
Learning objectives
- Derive dense expert and router gradients.
- Separate stored capacity, selected experts and normalization conventions.
Prerequisites & connections
Explore related knowledge →References
- Adaptive Mixtures of Local Experts
Robert A. Jacobs; Michael I. Jordan; Steven J. Nowlan; Geoffrey E. Hinton · 1991 - Outrageously Large Neural Networks: The Sparsely-Gated Mixture-of-Experts Layer — arXiv v1
Noam Shazeer et al. · 2017
Version1 · Editorial status: Recorded technical checks completed
View technical check record (AI)
Codex · 2026-09-06 · Codex single-AI-author technical check: primary-source scope, explicit assumptions, original calculations, independent mathematical references and bilingual tests; not independent human or second-agent review.
- Single-AI-author technical check: bounded primary-source reading, explicit assumptions, original calculations, runnable examples and matching bilingual equations, code and exercises. Not an independent human or second-agent review.
- Four focused CPython 3.12.4 tests passed per chapter, including independent finite differences, literal calculations, recurrence and convolution comparisons, permutation symmetry, closed-form limits and expressive counterexamples. All eight programs use NumPy 1.26.4. CPU teaching calculations, not framework or GPU benchmarks.
- Promoted the full prose, equations, code and exercises. Tests read formal MDX only; removed temporary fallbacks/draft skips and updated review assertion to checked. Algorithm and independent references are unchanged; final record binds both locale hashes.
- Publication navigation points published topics to complete articles and removes corresponding pending wording, retaining directory entries for unwritten targets. Principles, equations, programs and exercises are unchanged; final article SHA values rebound.
Source locations checked:
- Adaptive Mixtures of Local Experts · Scanned physical page 1 / printed page 79 inspected as an image: title, four authors, 1991 publication and supervised gating/specialization framing.
- Outrageously Large Neural Networks: The Sparsely-Gated Mixture-of-Experts Layer — arXiv v1 · Physical pages 3–4, Section 2 Equation 1, Section 2.1 Equations 2–5 and Section 3.1: sparse weighted outputs, noisy top-k normalization, k>1 gate gradients and shrinking batches.
Related topics