Mixture-of-Experts Inference
Storing many experts and computing with a few: what a batch of tokens makes a layer read, four ways to run the layer, what each costs on a GPU, and why capacity limits make a token's answer depend on its neighbours.
The Mixtral 8x7B paper reports roughly 47 billion accessible parameters and 13 billion active parameters per token. The gap matters, but it is not a promise that inference is 47/13 times faster: the server must store or otherwise make reachable all the experts, route tokens to them, and pay for whichever expert weights a batch actually executes. In this chapter’s synthetic, Mixtral-shaped two-matrix layer, one token selected two of eight experts and the data-dependent expert loop took 3.95 milliseconds; at sixteen tokens it touched all eight and took 9.69 milliseconds. A dense two-matrix comparison layer with approximately the same active MLP width took 1.75 milliseconds at sixteen tokens. These are local layer timings, not measurements of Mixtral 8x7B, and they compare different implementations and, in the capacity-limited case, sometimes different amounts of work. The question is when the benefit from sparse activation outweighs dispatch, weight traffic, and capacity costs.
This chapter constructs a mixture-of-experts (MoE) layer and compares a Python reference, an all-experts implementation, a data-dependent expert loop, and a fixed-capacity dispatcher. It measures their local costs at different token counts and explores routing skew, overflow, and a subtle serving consequence: when a finite-capacity dispatcher drops assignments, the same token can receive a different output depending on the other tokens sharing its batch. The lossless implementations compute the same mathematical function, within floating-point differences; the dropping implementation is intentionally a different function whenever overflow occurs.
No trained mixture-of-experts checkpoint was loaded for these experiments. The local GPU measurements use randomly initialised expert layers; the coverage measurement combines real GPT-2 hidden states with an untrained random router; and the upcycling check copies a dense GPT-2 MLP into multiple experts. The router-skew, overflow, placement, and batch-dependence studies use synthetic inputs or routing distributions as specified below. This gives evidence about this implementation’s mechanics and cost, not about learned expert specialisation, production throughput, output quality, or the routing distribution of Mixtral or DeepSeek. Nor does a calculated weight-read floor prove which bytes the GPU fetched from device memory.
Where this sits
Chapters 7 and 11 separated launch overhead, weight traffic, and arithmetic; Chapter 18 demonstrated how CUDA graphs reduce host launch overhead for fixed-shape decoding. Chapters 14–16 concerned the KV memory occupied by requests, while this chapter concerns the model memory occupied by experts and the weights touched by a scheduled group of tokens. Chapter 15’s continuous batching changes that group each iteration. Chapter 17’s speculative verifier can score several proposed tokens together, potentially increasing the union of active experts, but no speculative MoE experiment was run. Those connections make the distinction between active arithmetic, resident model capacity, and physical traffic essential.
The Inference Lab adds examples/ch19/moe_lab.py: parameter and expert-coverage arithmetic; a routed two-matrix MoE layer; three alternative implementations checked against a token-by-token reference; a fixed-capacity variant that can drop assignments; a GPT-2 sparse-upcycling correctness check; GPU timing sweeps; and CPU-based capacity, synthetic placement, and batch-dependence experiments. The corresponding tests distinguish lossless dispatch from deliberate overflow. Chapter 20 will investigate routing and balancing more deeply; this chapter concentrates on how such decisions affect an inference engine’s work.
For the Pi series, a persistent agent may repeatedly use a model whose expert selection varies with its internal token states. With deterministic, capacity-unlimited top-\(k\) routing, the route is itself determined by the inputs, model and numerical execution; the choice of experts is not an unrelated random variable. With capacity-limited routing, however, an assignment can be dropped because earlier tokens in the same dispatch group filled an expert. In that implementation, batch composition and ordering become additional execution inputs. A reproducibility manifest therefore needs the routing configuration, dispatch/drop policy, numerical environment, and, where applicable, the scheduling context.
What a mixture layer is
A standard sparse MoE transformer replaces selected feed-forward sublayers with \(E\) candidate feed-forward networks and a router that chooses \(k\) experts per token. For a hidden state \(x\in\mathbb{R}^{d}\), the laboratory uses a bias-free linear router, top-\(k\) selection, and a softmax normalised among selected experts. This is the form described for Mixtral; it is not the only routing rule in use.
Total and active
Ignoring biases, a two-matrix expert with input/output width \(d\) and intermediate width \(f\) stores \(2df\) weights; a gated, three-matrix expert stores \(3df\). For \(E\) experts and top-\(k\) selection, the laboratory’s count is \(P_{\mathrm{stored}}=E(2df)+dE\) and \(P_{\mathrm{active}}=k(2df)+dE\), before any always-active shared branch; the router participates for every token. The table rounds these values to millions. The timing implementation also has expert biases, which the helper’s simplified weight count omits; their contribution is small here. Active parameters estimate per-token expert arithmetic, not per-step bytes fetched from GPU memory.
| Layer | Experts | Top-\(k\) | Stored parameters | Active per token |
|---|---|---|---|---|
| A: \(d = 768\), \(f = 3072\) | 8 | 2 | 37.8 M | 9.4 M |
| B: \(d = 768\), \(f = 384\) | 64 | 8 | 37.8 M | 4.8 M |
| C: \(d = 4096\), \(f = 14336\) | 8 | 2 | 939.6 M | 234.9 M |
A and B have essentially the same total expert-weight count: B divides the feed-forward capacity among sixty-four narrower experts and activates eight, so its routed expert weights per token are about half A’s. C adopts Mixtral’s \(d=4096\), \(f=14336\), \(E=8\), \(k=2\) dimensions, but implements two matrices per expert instead of Mixtral’s three-matrix SwiGLU. Thus its 939.6 million weights, or about 1.88 decimal GB in fp16, belong to this illustrative layer rather than to the actual Mixtral expert block. The small-layer totals likewise exclude the practical memory occupied by intermediate tensors, allocator workspace, and captured graphs.
The whole-model figures below come from the Mixtral of Experts and DeepSeek-V2 papers, not from the locally executed layers: approximately 47 billion accessible / 13 billion activated parameters for Mixtral 8x7B, and 236 billion total / 21 billion activated per token for DeepSeek-V2. Multiplying by two bytes gives ideal fp16 parameter storage and activated-parameter equivalents; multiplying by half a byte gives an ideal 4-bit storage estimate with no scales, metadata, mixed-precision exceptions or runtime buffers. These model totals also include non-expert components, so dividing total by active is not a benchmarked inference-speed ratio.
| Model | Stored (fp16) | Active per token (fp16) | Active fraction | If stored at 4 bits (ideal, no scales) |
|---|---|---|---|---|
| Mixtral 8x7B | 94 GB | 26 GB | 28% | 23.5 GB |
| DeepSeek-V2 | 472 GB | 42 GB | 8.9% | 118 GB |
Neither ideal fp16 whole-model size fits the book’s 12 GiB GPU. Total parameters determine the storage or placement obligation across devices, host memory, disks, or networked workers; they need not all reside on one GPU simultaneously. Active parameters affect the token’s nominal operations, but actual latency also depends on expert dispatch, interconnects, weight reuse, kernel efficiency and the union of experts used by a batch. The table contains no evidence that ideal 4-bit storage would achieve the same quality or performance. Later distributed chapters address expert placement and communication; Chapter 12 addresses the difference between a packed-weight estimate and a measured quantised implementation.
What a batch makes the layer read
If each of \(T\) independently routed tokens selects \(k\) distinct experts uniformly from \(E\), then a specified expert is absent from any one token’s selection with probability \(1-k/E\). It is untouched by the entire batch with probability \((1-k/E)^T\). Linearity of expectation gives the expected number of distinct experts touched; independence between experts is not required. This is a model of routing under independent uniform tokens, not a measurement of weight traffic or a universal property of trained routers.
No trained MoE router was available. The coverage experiment extracted 1,024 GPT-2 layer inputs from this book’s text, applied a randomly initialised linear router, and sampled token groups from those states. The reported coverage means come from repeated samples of that fixed set of states; they are not independent user requests and are not production decode batches. This deliberately imperfect setting is useful for testing what goes wrong if uniform selection is assumed without measuring the route distribution.
Under that untrained router, the busiest of eight experts received 31.3% of assignments, rather than the 12.5% uniform reference; with sixty-four experts, the busiest received 7.65%, versus 1.56% uniform. This establishes strong non-uniformity for these fixed GPT-2 states and random router weights. It does not isolate whether the cause is hidden-state geometry, weight realisation, biases, token correlations, or some combination, and it is no evidence that a trained Mixtral or DeepSeek router has the same skew. The practical lesson is to inspect the selected-expert histogram before applying the uniform occupancy estimate.
The following table compares mean unique-expert counts under the untrained GPT-2-state router with the independent-uniform formula. The empirical values are counts of selected expert identities in synthetic groups, not measured HBM transactions:
| Tokens in batch | 8 experts, top-2: measured | formula | 64 experts, top-8: measured | formula |
|---|---|---|---|---|
| 1 | 2.00 | 2.00 | 8.00 | 8.00 |
| 4 | 4.76 | 5.47 | 21.56 | 26.48 |
| 16 | 7.16 | 7.92 | 41.39 | 56.44 |
| 64 | 7.94 | 8.00 | 56.21 | 63.99 |
| 256 | 8.00 | 8.00 | 62.38 | 64.00 |
Skew reduces coverage in this sample, especially with sixty-four experts: at 16 tokens the measured mean is 41.39, compared with the uniform prediction of 56.44, while at 256 tokens it reaches 62.38 of 64. The eight-expert configuration is effectively covered earlier. Therefore the batch size at which sparse weight reads stop helping depends on expert popularity, token correlations, kernel strategy, cache state and hardware—not simply \(E/k\). These counts suggest which sizes are worth benchmarking, not a universal threshold where MoE ceases to be efficient.
Four ways to run the layer
The reference computes the top-\(k\) weighted sum for each token with no capacity limit. dense_all and expert_loop, and moe_capacity when given enough slots, approximate the same function up to floating-point ordering. The capacity-limited dispatcher need not: when an expert overflows, it omits part of the sum. The reference is intentionally slow and serves as a correctness oracle for lossless implementations, not a quality benchmark for overflow policy.
- Run everything (
dense_all). Compute all \(E\) experts for all \(T\) tokens, multiply by the selected-expert gate, and sum. It uses fixed shapes and can perform up to \(E/k\) times the selected-expert matrix arithmetic; it also visits every expert even when no token selected it. - Data-dependent expert loop (
expert_loop). For each expert, find the selected tokens, evaluate only those and scatter-add weighted outputs. Its routed arithmetic is sparse. This reference implementation usesnonzeroand per-expert Python branching, imposing synchronisation and many small launches on the measured CUDA path. That overhead is a feature of this implementation, not a theorem that every sparse dispatcher must synchronise once per expert. - Fixed capacity (
moe_capacity). Reserve \(C\) slots for every expert, sort token–expert assignments, keep up to \(C\) per expert, perform a fixed-shape batched matrix multiplication across all experts, and scatter back. Its buffers have stable shapes suitable for CUDA graph capture, but it still executes every expert and may drop assignments after capacity fills. In this lab, \(C=\lceil cTk/E\rceil\) with a minimum of one slot, or \(C=T\) to guarantee no dropped assignment. The formula generalises the top-1 capacity convention discussed in Switch Transformers to top-\(k\) assignments. - Python reference (
moe_reference). Run every selected expert for each token and accumulate the mixture; slow, straightforward, and used as the lossless comparison.
The following excerpt shows the sorting, per-expert slot assignment, overflow sentinel, full-buffer expert computation, and weighted scatter. Here \(T\) is the token count, \(k\) the selected experts per token, \(E\) the number of experts, and \(C\) the slots per expert. The actual implementation also calculates expert counts and prefix offsets, creates a spare overflow row, and returns the number of dropped assignments. Crucially, setting a gate weight to zero for a dropped assignment does not mean the expert work was skipped: torch.bmm still executes for every expert’s full fixed-capacity buffer.
order = torch.sort(flat_e, stable=True).indices # assignments grouped by expert
pos = torch.arange(T * k) - starts[flat_e[order]] # rank within the expert
keep = pos < capacity
slot = torch.where(keep, flat_e[order] * capacity + pos, E * capacity) # dropped ones go to a spare row
buf.index_copy_(0, slot, x[token_of])
y = torch.bmm(act(torch.bmm(buf[:-1].view(E, C, d), W1) + b1), W2) + b2
out.index_add_(0, token_of, y_flat[slot] * (gate * keep))
The drop counter is returned as a zero-dimensional tensor. An earlier version converted it to a Python integer during capture, forcing a device-to-host read incompatible with CUDA graph capture. Keeping it on-device removes that particular graph break, but it does not remove the cost of sorting, padding, copying or running every expert. Nor does graph capture guarantee that the capacity-limited result equals the reference; that requires demonstrating no overflow for the tested inputs.
Checking them
The CPU unit tests compare the lossless modes against the reference with random inputs, \(k=1\), \(k=E\), a single token, empty experts, and an optional always-active shared branch. Additional tests deliberately create over-capacity routing: they check the exact number of dropped assignments, verify that earlier assignments survive the stable sort and confirm that the dropped contributions are missing. A CUDA-only test checks that the fixed-capacity implementation can be captured and replayed. These checks do not establish lossless equivalence for capacity-factor-1.25 timing cells in which drops are recorded; they validate different contracts.
Sparse upcycling starts from a trained dense checkpoint and initialises expert weights from its dense feed-forward weights (Komatsuzaki et al., ICLR 2023). Here it is used as a diagnostic rather than as a new training result. All GPT-2 MLPs in the twelve-block model were replaced with four or eight identical expert copies and a random router. Because every selected expert computes the same MLP and the selected gate weights sum to one, any lossless mixture implementation should reproduce the original dense forward pass. On a 17-token prompt, all four dispatch modes agreed with dense logits to within approximately \(1.14\times10^{-4}\) absolute error, with unchanged per-position argmax. This checks the wiring of attention, residuals, routing and expert computation on real weights. Identical experts cannot test whether the router learns meaningful specialisation, and no upcycled model was trained.
To make expert identity matter, the experiment added Gaussian perturbations scaled to 5% of each copied tensor’s standard deviation to the eight expert copies. The perturbed model differed from dense GPT-2 by as much as 2.67 in logits and retained the same argmax at about 94% of the 17 prompt positions; the alternative lossless dispatches matched their common reference to no worse than \(9.2\times10^{-5}\) in maximum absolute logit difference. That is evidence that this routing-and-dispatch implementation operates consistently with non-identical experts. It does not measure accuracy or quality on natural text, and no finite-capacity drops were allowed in this upcycling check.
What it costs
Each GPU timing cell uses randomly initialised fp16 weights. Results come from three passes with a desktop-shared RTX 2060 12 GB; the table reports the lowest pass median, rather than the overall median, to reduce interference. The GPU was checked for low utilisation before each pass, not continuously throughout it, and an earlier contention-heavy run was discarded. The comparison also changes execution mode: dense baselines and capacity-limited dispatch are graphed; expert_loop and dense_all are eager. At capacity factor 1.25, some cells drop assignments. Accordingly, these tables measure the cost of specified implementations and policies, not a lossless, equal-output contest. Recorded drop counts and a separate no-drop graph timing are available in research/ch19/results.json; the manuscript calls out affected cells explicitly.
Small layers: the launch ceiling
Layers A and B each contain about 75.5 decimal MB of routed expert matrix weights in fp16 (excluding small router and bias terms). The dense comparison is a single two-matrix MLP of hidden width \(kf\): it approximates the same active matrix arithmetic and weight count per token but is not mathematically the same function as a routed weighted sum of experts. Both dense and capacity-limited columns use CUDA graph replay, while the data-dependent expert loop is timed eagerly. Times are milliseconds.
| Tokens | Dense, same active width | A: fixed capacity (graph) | B: fixed capacity (graph) | A: expert loop (eager) | B: expert loop (eager) |
|---|---|---|---|---|---|
| 1 | 0.18 / 0.12 | 0.45 | 0.45 | 2.25 | 11.1 |
| 16 | 0.18 / 0.15 | 0.47 | 0.51 | 5.25 | 44.7 |
| 64 | 0.20 / 0.17 | 0.52 | 0.58 | 5.68 | 48.3 |
| 256 | 0.51 / 0.28 | 0.97 | 0.95 | 6.60 | 46.5 |
| 1024 | 1.71 / 0.97 | 2.63 | 2.72 | 5.37 | 48.9 |
The dense columns correspond to A and B separately; B’s smaller active width makes its comparison cheaper. At the modelled 304 GB/s ceiling, one full read of either layer’s roughly 75.5 MB of expert weights would take about 0.25 ms, while reading only the two touched A experts or eight touched B experts at one token would have nominal floors of about 0.062 ms and 0.031 ms, respectively. Those are weight-byte/assumed-bandwidth estimates, not measured DRAM transactions or demonstrated lower bounds in the presence of caching. The graphed fixed-capacity path takes roughly 0.45–0.58 ms up to 64 tokens, while the eager expert loop pays 2.25–48 ms depending on expert count and batch size. The implementations differ in dispatch strategy and graph use, so the contrast cannot be attributed solely to synchronisation. Moreover, the 1.25-capacity graph drops assignments for A at 16 and 64 tokens (2/32 and 8/128) and B at 16 and 64 tokens (9/128 and 23/512). Its low timing therefore must not be described as a lossless speed-up. The no-drop graph variants in the evidence file provide the proper next comparison.
A Mixtral-shaped layer: the bandwidth ceiling
Layer C has \(d=4096\), \(f=14336\), eight two-matrix experts, totalling approximately 1.879 decimal GB of fp16 routed weights. A dense MLP with intermediate width \(kf\) contains roughly 470 MB. At an assumed effective bandwidth of 304 GB/s, streaming two expert weight sets once gives a nominal transfer time of 1.55 ms, and streaming all eight gives 6.18 ms. These are traffic scenarios, not kernel-level memory measurements; they omit router, activation, temporary, cache-residency and scheduling effects.
| Tokens | Experts touched | Floor: touched only | Per-expert loop (eager) | Fixed capacity (graph) | Run everything (eager) | Dense, same active width (graph) |
|---|---|---|---|---|---|---|
| 1 | 2 | 1.55 | 3.95 | 6.73 | 6.84 | 2.12 |
| 4 | 5 | 3.86 | 6.91 | 6.56 | 6.81 | 1.74 |
| 16 | 8 | 6.18 | 9.69 | 6.60 | 7.16 | 1.75 |
| 64 | 8 | 6.18 | 9.52 | 7.28 | 8.15 | 2.11 |
| 256 | 8 | 6.18 | 11.05 | 9.85 | 22.29 | 5.12 |
Times below are milliseconds; the fixed-capacity graph uses capacity factor 1.25. Its rows are not always lossless: for this recorded routing sample it dropped 1 of 8 assignments at four tokens and 1 of 32 at sixteen tokens. At one, sixty-four and 256 tokens, the recorded drop count was zero. expert_loop and dense_all retain their selected contributions, whereas the graphed capacity implementation can omit some. Thus the table is a timing comparison under the stated policies; the measured no-drop graph variant, also present in the evidence file, is needed to compare exact outputs. Four patterns are still informative:
- At one token the sparse expert loop executes only two experts. It took 3.95 ms, compared with 6.73 ms for the graphed capacity-1.25 path and 6.84 ms for eager all-experts execution. Only the loop avoids calling untouched expert matrices in these implementations. The difference between 3.95 ms and the hypothetical 1.55 ms two-expert transfer time is not a measured decomposition into launches and synchronisations.
- At four tokens the loop loses its observed timing lead. Five experts were selected in total; the loop took 6.91 ms and the 1.25-capacity graph 6.56 ms, but the latter dropped 1 of 8 assignments. This row therefore does not establish a lossless crossover. At sixteen tokens the loop took 9.69 ms and the 1.25-capacity graph 6.60 ms, again with one dropped assignment; the no-drop graph in the evidence file took about 6.87 ms.
- At sixteen tokens all eight experts are touched. The capacity-1.25 graph took about 6.60 ms against 1.75 ms for the equal-active-width dense MLP. That comparison has different weight organisation and, in this row, a dropped contribution. It is evidence of this implementation’s cost, not proof of a universal 4× MoE inference penalty.
- At 256 tokens the costs grow with batch work. The capacity graph took 9.85 ms, eager all-experts 22.29 ms and the dense comparator 5.12 ms. These figures are compatible with increasing arithmetic costs and dispatch overhead, but without profiling arithmetic utilisation and memory transactions they do not establish a compute-bound regime. The fixed-capacity implementation performs padded work on every expert even when the logical output remains sparse.
The useful conclusion is conditional: sparse expert arithmetic does not automatically translate to sparse weight traffic, and this lab’s unfused strategies can be slower than a dense two-matrix comparison with a similar active arithmetic budget. At batch one, the eager expert loop avoids six of eight large experts’ weights; at larger batches the union grows, while the fixed-shape code executes every expert regardless of that union. Optimised grouped GEMM, device-local caches, expert parallelism, overlap, routing skew and quantisation may change these crossovers substantially. These experiments cannot rank trained MoE models against trained dense models on throughput, quality or cost. They show what an implementation must measure: routed assignments, no-drop correctness, actual transferred bytes, occupancy, latency and dispatch overhead, all at a stated batch shape.
When routing is uneven
The remaining experiments use independent uniformly sampled top-\(k\) assignments or synthetic Zipf-weighted expert popularity. They isolate three mechanisms a serving engine must handle: how many assignments overflow finite slots, how expert popularity concentrates work, and how placement maps that concentration onto devices. The results do not characterise learned expert-routing distributions or any measured distributed all-to-all communication. Chapter 20 will explore the routing-policy questions these experiments leave open.
Capacity overflow under uniform routing. If each of \(T\) tokens independently selects \(k\) distinct experts uniformly among \(E\), a given expert’s assignment count is \(L\sim\mathrm{Binomial}(T,k/E)\). With capacity \(C=\lceil cTk/E\rceil\), the expected dropped assignment fraction is \(E\,\mathbb{E}[\max(L-C,0)]/(Tk)\). The exact finite sum in expected_drop_fraction was compared with 400 synthetic routing trials across 32 configurations, with absolute differences of about 0.0013 or less in the recorded results. For 64 experts, top-8 and 64 tokens, the simulated fractions were approximately 13.0% at factor 1.0, 4.6% at 1.25, 1.2% at 1.5 and 0.03% at 2.0. At 1,024 tokens the factor-1.0 fraction was about 3.3%. These are fractions of token–expert assignments, not necessarily fractions of completely lost tokens; a token may retain some of its \(k\) experts.
Effect of synthetic popularity skew. The experiment assigns experts Zipf-like weights \(p_i\propto 1/i^s\) and samples \(k\) distinct experts per token with Gumbel top-\(k\). Those weights are preferences, not the exact resulting marginal selection probabilities after choosing eight without replacement. With 64 experts, top-8 and factor 1.25, the measured dropped-assignment fraction at 64 tokens rose from roughly 4.5% under uniform selection to 13–15% for \(s=0.5\), about 33% for \(s=1\), and about 48% for \(s=1.5\). In this synthetic family the busiest expert approached eight times the mean selection count, the top-8 theoretical maximum ratio \(E/k\). The experiment establishes how this constructed skew affects a capacity cap; it is not a measured training or serving distribution.
Simulated placement imbalance. If the 64 expert identities are assigned to eight hypothetical devices, the recorded ratio of the busiest device’s assignment count to the average ranged from approximately 1.04–1.17 under uniform routing with contiguous placement. With Zipf exponents 0.5, 1.0 and 1.5, it rose to roughly 2.2, 3.7 and 4.9; round-robin placement spread the popular indices and reduced the corresponding ratios to roughly 1.2, 1.5 and 1.5. This is an assignment-count imbalance proxy. A real expert-parallel layer’s critical path also includes expert widths, packing, collective communication, device bandwidth, capacity drops and overlap; no actual multi-GPU execution was measured. Here round-robin wins partly because Zipf popularity was defined to decrease with expert index. Real placement should follow profiled routing and topology rather than an index-based general rule.
A token’s answer depends on its neighbours
Dropping routed assignments can make an MoE output depend on other tokens in a batch. The CPU experiment forms groups of 64 random hidden states, runs the fixed-capacity dispatcher with a given capacity factor, and compares each output to the same token processed alone without a capacity limit. A token is marked affected if its maximum absolute output difference exceeds \(10^{-4}\). This is an output-vector sensitivity test on randomly initialised small layers, not a count of wrong next tokens, a quality metric, or a measured production request dependency.
| No drops | Factor 2.0 | Factor 1.25 | Factor 1.0 | |
|---|---|---|---|---|
| 8 experts, top-2 | 0% | 0% | 5.8% | 19% |
| 64 experts, top-8 | 0% | 0.7% | 28.5% | 46% |
The table reports the mean fraction of tokens whose layer output differed from its solo, no-drop computation, over twenty batches. With 64 experts, top-8 and a capacity factor of 1.25, about 28.5% of tokens crossed the \(10^{-4}\) threshold; the corresponding eight-expert, top-2 case was about 5.8%. Those are affected-token fractions, not assignment-drop fractions. At factor 2.0, the fine-grained case still affected about 0.7% of tokens in this finite experiment, even though the eight-expert case showed none. The comparison fixes the token’s own input and weights; changing its place among competitors can change whether one of its experts overflows. This means a capacity-dropping MoE cannot, in general, promise that outputs depend only on an individual request and model manifest. Downstream KV states could also be batch-dependent if inference uses such dropping. This is a risk conditional on that policy: MoE without dropped assignments retains the ordinary per-request functional contract, subject to usual floating-point behaviour. No production engine’s inference-time drop policy or quality impact was tested here.
What the numbers do not show
- No trained MoE model. The local coverage router is untrained; the benchmark expert weights and synthetic routing have no learned specialisation. Training quality and actual expert popularity remain unknown.
- Implementation-specific dispatch. The Python
expert_looppays host coordination and many launches; a grouped GEMM or fused segmented kernel can dispatch sparsely without this exact overhead. The fixed-capacitybmmversion runs all experts, but a more sophisticated graph-captured engine can select or schedule expert work in ways not implemented here. These are not universal restrictions of MoE or CUDA graphs. - Comparisons do not always compute the same function. Several 1.25-capacity timing cases drop assignments;
dense_allandexpert_loopdo not. The dense comparison has the same approximate active MLP width but different parameter sharing, activation arrangement and routing semantics. The graph and eager columns also differ in launch overhead. Use no-drop runs for a performance-versus-performance claim at equal output. - No hardware traffic or compute-utilisation trace. The 304 GB/s weight-read floors assume one transfer of specified weights; no profiler established DRAM bytes, arithmetic saturation, kernel occupancy or the claimed launch/compute/bandwidth breakdown.
- One layer, one GPU. Device-imbalance figures are simulated assignment counts across eight hypothetical devices, not all-to-all timings or measurements of expert parallelism.
- Simplified, ungated fp16 experts. The measured layers have two matrices and GELU, unlike Mixtral’s three-matrix SwiGLU. Shared branches were checked in CPU correctness tests but excluded from GPU timings.
- A shared, drifting GPU. The reported best-of-three-pass medians reduce observed contention; they do not make the device isolated. Earlier heavily contended runs were discarded.
- Synthetic batch dependence, not model quality. The affected-token statistic compares layer vectors to a solo computation. No downstream text generation, accuracy test or quality judgement was made.
- Sparse upcycling as a diagnostic. Copying a GPT-2 MLP into identical experts verifies routing plumbing; it is not evidence for a trained or efficient MoE checkpoint.
Inference Lab increment
The Lab now has:
route: top-\(k\) logits and selected-expert softmax, with a tested equivalence to selecting and renormalising full-softmax probabilities.moe_reference,moe_dense_all,moe_expert_loop,moe_capacity: a lossless reference, two alternative lossless implementations, and a capacity dispatcher that can intentionally drop assignments. The latter returns its drop count as a device tensor.MoEParams,upcycle_layer,forward_moe: two-matrix expert parameters, an optional shared dense branch, and GPT-2 with substituted MoE MLPs for a correctness comparison.expected_distinct_experts,expert_capacity,expected_drop_fraction,moe_param_counts,bytes_read_by_experts: closed-form expectations and weight-storage/traffic estimates under stated assumptions.sample_routing,device_loads,imbalance: synthetic routing selection and assignment-count placement proxies, not a multi-GPU runtime.capture: captures a fixed-shape function using CUDA graphs in an appropriate environment.layer,layer_large,coverage,upcycle,balance,batch_dependence: reproducible local commands corresponding to the reported categories of evidence.
The rule added to the Inference Lab is: MoE decouples stored expert parameters from selected expert arithmetic, but its real inference cost depends on the union of selected experts, the dispatch kernel, and any expert-capacity policy. A data-dependent implementation may skip untouched weights; a naïve fixed-capacity implementation can compute on every expert and drop assignments; an optimised kernel may shift that trade-off. Evaluate throughput only after checking whether both paths compute the same function. If assignments are dropped, record the policy and batch context because a token’s layer result can change with its neighbours.
What you should now be able to do
- Calculate total expert weights, router weights and per-token active weights for two- and three-matrix experts, identifying shared branches and omitted metadata.
- Derive \(E[1-(1-k/E)^T]\) for independent uniform top-\(k\) routing, and explain why learned skew and caching change the practical implication.
- Implement and test lossless top-\(k\) routing/dispatch against a slow oracle, then separately test a capacity-limited policy that drops assignments.
- Use sparse upcycling to test execution plumbing while explaining why identical experts say nothing about expert specialisation.
- Distinguish bytes of weights potentially required from measured DRAM traffic, and distinguish eager/graph overhead from dispatch arithmetic.
- Calculate expected dropped assignment fraction from a binomial model, and avoid confusing it with affected-token fraction or quality loss.
- Explain when batch-dependent overflow makes an output depend on co-batched traffic, and identify ways an inference engine could preserve a lossless per-request contract.
- State exactly which claims need trained checkpoints, fused kernels, real traces or multi-device hardware before they can be made.
Key terms
- Expert: one feed-forward subnetwork available for conditional execution in an MoE layer.
- Router: the learned (or, here, randomly initialised) computation producing scores for expert selection.
- Top-\(k\): the number of distinct routed experts selected for each token, excluding any always-active shared branch.
- Stored parameters: all routed experts, router and shared parameters that must be placed or made reachable.
- Active parameters: the subset participating in a token’s nominal computation; not automatically the bytes fetched from GPU memory.
- Shared expert: an expert/branch used for every token independently of top-\(k\) routing.
- Capacity factor: a multiplier on the average token–expert assignments per expert used to allocate fixed slots.
- Dropped assignment: a token–expert contribution omitted because its selected expert has no remaining capacity; not necessarily a wholly dropped token.
- Dispatch: packing/scattering token states to expert computations and combining the outputs.
- Sparse upcycling: initialising a mixture from a trained dense checkpoint, used here only as a plumbing check.
- Expert coverage: the distinct expert identities selected by a group of tokens.
- Straggler proxy: busiest simulated device load divided by mean load; not a measured all-to-all latency.
Reader exercises
- Replace the two-matrix GELU expert with a three-matrix SwiGLU expert. Recalculate stored/active weights and the hypothetical transfer floors; then measure rather than assume the performance crossover.
- Implement a fused or segmented/grouped-GEMM dispatcher that evaluates only selected experts without the Python per-expert synchronisations. Compare it with
expert_loopon the same routed outputs and report maximum error and GPU time. - For a fixed token group, rerun the
moe_capacitysweep at capacity factor 1.25 and atcapacity=None. Record dropped assignments, lossless error againstmoe_reference, and speed-up separately. How much of the apparent gain came from omitting work? - Evaluate a Mixtral-shaped layer with a batch of one token versus a verifier that scores four additional speculative tokens (Chapter 17). Report both expert union and measured kernel time rather than inferring traffic from coverage alone.
- In the fine-grained 64-expert configuration, search for the smallest factor at which fewer than 1% of tokens exceed the \(10^{-4}\) solo-output difference threshold, over more seeds. Also report the dropped-assignment fraction.
- Change the overflow rule from stable input order to selecting the highest-weight assignments. Verify whether affected-token counts change, and disclose the extra sort/selection cost.
- With a trained MoE checkpoint, reproduce the expert-coverage and marginal-popularity histograms. Compare the trained distribution with the untrained GPT-2-state router; the current local experiment cannot answer this.
- Simulate placement using measured popularity and actual expert compute weights, then, if multiple devices are available, measure all-to-all and the critical path to test the placement proxy.
- Use profiler counters to compare modeled expert weight-read bytes with actual DRAM transactions for
dense_all,expert_loopand a lossless capacity path. When does cache reuse explain a mismatch?
References
- Mixtral of Experts — Jiang et al., 2024. Eight routed feed-forward experts per layer, top-2 routing, SwiGLU blocks, and the published whole-model figures of about 47B accessible / 13B active parameters; the local two-matrix layer is not Mixtral itself.
- Switch Transformers: Scaling to Trillion Parameter Models with Simple and Efficient Sparsity — Fedus, Zoph and Shazeer, JMLR 23 (2022). Top-1 expert selection, fixed expert capacity, overflow handling and load-balancing motivation. The lab generalises its capacity convention to \(Tk\) assignments.
- DeepSeekMoE: Towards Ultimate Expert Specialization in Mixture-of-Experts Language Models — Dai et al., ACL 2024. Fine-grained routed expert segmentation and shared experts, cited for architecture rather than as evidence of the lab’s performance.
- Sparse Upcycling: Training Mixture-of-Experts from Dense Checkpoints — Komatsuzaki et al., ICLR 2023. Initialising sparse expert models from trained dense checkpoints. The chapter adapts the identity check, without training an upcycled MoE.
- DeepSeek-V2: A Strong, Economical, and Efficient Mixture-of-Experts Language Model — DeepSeek-AI, 2024. The abstract reports 236B total / 21B activated parameters; its other efficiency claims involve multiple architectural choices, and are not reproduced or attributed to expert routing alone.
Evidence in this chapter
| Claim | Evidence and boundary |
|---|---|
| Mixtral ~47B accessible / ~13B active; DeepSeek-V2 236B total / 21B activated | Figures reported by the respective research papers, not locally benchmarked |
| Simplified expert parameter formulas, ideal fp16 and 4-bit bytes | Derived arithmetic; bias/metadata, shared branches and runtime allocations require separate accounting |
| Expected distinct experts \(E[1-(1-k/E)^T]\) | Derived under independent uniform top-\(k\) token routing; not a trained-router traffic measurement |
| Untrained router on GPT-2 states is skewed; 8-expert busiest share 31.3% and 64-expert busiest 7.65% | Local synthetic-router coverage experiment; trained router behaviour is unknown |
| GPT-2 sparse-upcycling plumbing preserves logits to approximately \(1.14\times10^{-4}\); perturbed experts produce different outputs but dispatches agree to \(9.2\times10^{-5}\) | Local correctness tests on one 17-token GPT-2 prompt; no MoE training or quality assessment |
| Small graphed capacity dispatch ~0.45–0.58 ms for 1–64 tokens; eager expert loop much slower | GPU implementation timings, three passes, best pass median; some factor-1.25 cells drop assignments |
| Mixtral-shaped layer: one-token eager loop 3.95 ms versus graphed capacity 6.73 ms; sixteen-token loop 9.69 ms versus graph 6.60 ms | Local two-matrix benchmark, not Mixtral; at sixteen tokens the 1.25-capacity graph dropped 1/32 assignments |
| Dense active-width MLP ~1.75 ms at sixteen tokens | Local arithmetic-budget comparator, different mathematical function; not a trained-model throughput ranking |
| 304 GB/s-based read floors and hypothetical straggler factors | Analytical byte/time estimates and synthetic assignment-count proxies; no hardware traffic or interconnect profiling |
| Uniform-routing capacity-drop formula agrees with Monte Carlo | Derived binomial expectation and 400 synthetic trials for 32 configurations; unit is token–expert assignments |
| Zipf skew raises overflow and simulated placement imbalance | Constructed Gumbel top-\(k\) distribution; not a measured learned router or distributed system |
| Fine-grained capacity factor 1.25 changes 28.5% of tokens’ layer outputs compared with solo no-drop execution | Local CPU simulation: 20 batches of 64 random states, threshold \(10^{-4}\); not token accuracy or text quality |
| Fused grouped-GEMM performance, trained expert specialisation, actual all-to-all, real request traces, and quality loss under dropping | Not measured; publication claims must not imply otherwise |