Sparsity
Can a model use only a small part of itself for each token, and still be trained?
The part opens on DeepSeek-V3, where 8 of 256 experts and one shared expert light up for each word, and traces three threads to it: experts, sparse attention and sparse weights. It starts in 1991, where Jacobs, Jordan, Nowlan and Hinton make experts compete by weighting each one's own error with its posterior responsibility, and follows Shazeer's top-k gate of 2017 to the modern layer. The router's gradient is derived and checked by finite differences: a chosen score moves by its gate times how far its expert beat the gate-weighted average, and an unchosen score gets nothing. A mixture is then trained on the series' character transformer against dense models of equal arithmetic and of equal parameters. The part turns on collapse: left alone the router plays favourites, Switch's auxiliary loss spreads the load at the cost of a second goal, and DeepSeek's bias steers the choice without touching the loss. Capacity factors, the all-to-all between chips, parameter counts and upcycling follow from the same picture of loads. The second half asks the same question of depth (mixture-of-depths), of attention (windows, block selection, a learned indexer on a recall task) and of weights (lottery tickets, 2:4 pruning, sparse activations), and ends with the open mixtures and sparse-attention models of late 2026.
What you need. Calculus and linear algebra; the softmax Jacobian of Part 4 and the transformer block of Part 13.
- Mathematics and history
- mixture-of-experts routing and balancing, expert parallelism, sparse attention (NSA, DSA), pruning
- Models, data
- DeepSeek-V3.x, GLM, Kimi
What you will be able to do
Undergraduate
- Explain what a router, a gate and an expert are, and why a top-k mixture has many more parameters than it uses for one token.
- Count the total and the active parameters of a mixture-of-experts model from its configuration.
Master's
- Derive the router's gradient through a top-k softmax gate and through DeepSeek-V3's sigmoid gate, and check it by finite differences.
- Derive Switch's auxiliary loss and its lower bound, and compute the share of token slots dropped at a capacity factor.
- Compute what mixture-of-depths saves in matrix work and in attention scores at a routed fraction.
Research
- Compare block selection (NSA, MoBA) with a learned indexer (DSA) as sparse attention, and state what each can and cannot retrieve at a fixed number of keys per query.
- State the lottery ticket hypothesis with rewinding, and say which control (re-initialized masks, random masks) separates the mask from the initial weights.
Engineering
- Choose between an auxiliary loss, a loss-free bias and a capacity factor for a mixture, and say what each costs in dropped tokens and in the busiest chip's load.
- Compute the all-to-all bytes and the experts' FLOPs per token per layer, and compare their ratio with a chip's ridge.
Contents
Each chapter has a home level. Choose a track to see what to read and watch: Undergraduate 15 min · Master's 39 min · Research 46 min · Engineering 22 min.
- 0A few experts at a timeUndergraduate3 min
- 1Competing experts, 1991Undergraduate3 min
- 2Top-k gates and the router's gradientMaster's3 min
- 3A mixture, trainedUndergraduate2 min
- 4Collapse, and Switch's lossMaster's3 min
- 5Balancing without a lossMaster's2 min
- 6Fine-grained and shared expertsMaster's2 min
- 7Capacity and dropped tokensEngineering3 min
- 8Experts across chipsEngineering2 min
- 9Counting parameters, and upcyclingUndergraduate3 min
- 10What experts learnMaster's1 min
- 11Mixture-of-depthsMaster's2 min
- 12How sparse is attention?Master's2 min
- 13Sparse attention by designResearch4 min
- 14Lottery ticketsUndergraduate2 min
- 15Two in four, and sparse activationsEngineering2 min
- 16The frontier, late 2026Research2 min
- Recap, problems, and what comes nextAll tracks2 min
Also on this page: Lecture · Key results · Try it · Lab · Problems · Notes and sources · 中文 · Build the film.
Lecture
The text of each chapter is the film's narration, as it is spoken, so you can read along or revise without the film. The pictures are in the film. A dashed box stands for a number the film computes when it is rendered (hover over it to see what is computed); the README's figures for each chapter, where it lists them, follow the chapter's text.
A few experts at a timeUndergraduate3 min
DeepSeek-V3 has six hundred and seventy-one billion parameters. But for each token it reads, it uses only 37 billion of them. Each of its expert layers holds 256 small networks, called experts, and a router sends each token to just 8 of them, plus one that everyone shares. Watch: every word lights up a different few. And the models keep getting sparser. Kimi K3, released in July 2026, has 896 experts in a layer and uses 16 of them, plus 2 shared: 3.7 percent of its weights for each token.
How did we get here? Three threads, which this part follows. The first is experts. In 1991 Robert Jacobs, Michael Jordan, Steven Nowlan and Geoffrey Hinton proposed a gate that picks which of several networks should answer. In 2017 Noam Shazeer and colleagues, with Hinton again, made it sparse: thousands of experts, only a few run per token, a hundred and thirty-seven billion parameters. Google scaled it with GShard and the Switch Transformer, to a trillion and a half parameters; Mixtral made it open in 2023, and DeepSeek-V3 made it the frontier's standard. The second thread is attention that reads only some of the past: fixed patterns from 2019, sliding windows, and in 2025 patterns the model learns to choose. The third is the oldest: removing weights. Yann LeCun's optimal brain damage in 1990, the lottery tickets of 2018, and the two-in-four pattern NVIDIA built into its chips in 2020.
This is Part 16 of AI, Built: using only some of a model at a time. In this part: the mixture of experts, from its 1991 origin to the router's gradient, trained here on our own characters; how to keep every expert busy, with Switch's loss derived and DeepSeek's loss-free bias; capacity, chips and counting; what experts learn, and mixture-of-depths; attention that reads only some of the past, trained on a recall task; and sparse weights and activations, from lottery tickets to the two-in-four pattern. Every experiment runs on this computer.
1Competing experts, 1991Undergraduate3 min
In 1991 the question was how to make several networks share one job, instead of training one network to do everything. Jacobs, Jordan, Nowlan and Hinton's answer is the mixture of experts. Several small networks, the experts, each make a guess, and a gate, one more matrix and a softmax, decides how much to trust each one for this input. The answer is the trusted mix. The gate's numbers are like part seven's mixture weights, except that they change with the input: for one input the gate leans on expert two, for another on expert four. Their test was telling apart vowel sounds spoken by many people.
The new idea was in the loss. The obvious loss fits the blend: the squared error of the gated sum. Its gradient tells every expert to chase the blend's error, so each expert's lesson depends on all the others: they cooperate, and they all end up a little responsible for everything. Jacobs and his colleagues instead treated the experts as a mixture of Gaussians, part seven's mixture model, and minimized the negative log likelihood. Now each expert chases its own error, weighted by h, the posterior probability that it was the one responsible: how much the gate trusted it, times how well it already explains the answer. Part seven's EM called this the responsibility. An expert learns most from the cases it already wins. They compete, and they become specialists.
Here's that difference, trained on this computer. A curve with three regimes, a rise, a plateau and a fall, and four experts that can each draw only a straight line, with a gate that looks at x. The same mixture, trained the two ways. Watch the gates below the curves.
In those early mixtures, every expert ran on every input, and the gate only weighed them. In 1994 Jordan and Jacobs stacked gates into hierarchies and trained them with EM. In 2017 Noam Shazeer and colleagues at Google turned the mixture into a way to grow. Keep only the top k gate scores, and set the rest to minus infinity, so their gates are exactly zero and those experts need never run. Add a little noise to the scores, so the router keeps trying other experts. Then the number of experts can grow without the expert work per token growing at fixed k; routing still adds overhead. They put thousands of experts between the layers of an LSTM, a hundred and thirty-seven billion parameters, more than a thousand times the capacity of the models before. That's the sparse mixture of experts every model in this part uses.
2Top-k gates and the router's gradientMaster's3 min
Here's one layer of a modern mixture of experts. The feed-forward network of each transformer block becomes several smaller ones, the experts. A router, just one matrix, gives the token a score against every expert. Only the top k scores count: here, two of eight. Those experts run; the others don't. Their outputs are added up, weighted by gates: a softmax over the chosen experts' scores alone, so the gates add to one. That's Mixtral's gate, and the one most models use.
What does the router learn from? Take the gradient of the loss with respect to a score s j. The output depends on the scores only through the gates, so by the chain rule it's a sum over the chosen experts of u i, how much expert i's output pushes the loss, times the gate's derivative. The gates are a softmax, whose Jacobian is part four's g i times delta i j minus g j. Collect the terms: the gradient is g j times u j minus u bar, the gate-weighted average of the chosen experts. A chosen expert that helped more than the average gets its score raised; one that helped less gets it lowered. And an expert that wasn't chosen has no gate, so its score gets no gradient at all. The router only learns about the experts it tried. It never finds out whether an unchosen expert would have done better.
Let's check it. One token, eight experts that are random linear maps, the top two chosen, and a squared error. Nudge each score up and down by a millionth and watch the loss: that's the gradient by finite differences. The formula gives the same bars, and so does automatic differentiation: they agree to 9 decimal places, relative to the largest bar. 6 of the 8 bars are exactly zero: only the chosen experts' scores move. We ran the same check on the router of the mixture layer we'll train in the next chapter, every one of its weights: they agree to 8 decimal places.
Pause and predict. With one expert per token, and its gate renormalized to one, what does the router learn? Here are the four gates side by side. With two experts, mixed by a softmax or by DeepSeek's sigmoids, the two chosen scores learn. Switch's single expert is multiplied by its full softmax probability, so every score learns, through the softmax's denominator. But renormalize a single expert's gate and it's always exactly one: the router learns nothing, ever. That's why Switch keeps the raw probability. Either way, a router learns only from what it tried, which is why it needs noise to explore, and, as the next chapters show, help to share the work.
3A mixture, trainedUndergraduate2 min
Now we build one. Part 13's transformer, shrunk to fit a laptop: two blocks, sixty-four numbers wide, reading sixty-four characters of the thirty novels. In the first model, each block's feed-forward layer is dense, two hundred and fifty-six wide. In the mixture it becomes eight experts, each half as wide, and a router picks two for each character: the same arithmetic per character, about 111 thousand parameters used, but 318 thousand in all. And the third is a dense model with all those parameters, one feed-forward layer four times as wide, which does three times the arithmetic. Each is trained three times, from three seeds, on exactly the same characters.
Here are all nine runs. Shown are seven post-initialization checkpoints on ninety-six fixed held-out windows; each line is the mean of three seeds, and the band runs from the best seed to the worst. Final scores at right use four hundred windows.
Here is the first seed's routing replay: which experts receive each common character, in both blocks. Each token has two distinct choices, and shares count both slots, so any expert's share is at most fifty percent. With randomly initialized parameters the choices are already concentrated by character: the average largest expert share is percent. At the saved checkpoint at step , it is percent. What the experts end up doing is chapter ten's question.
One caution before we celebrate. The mixture does the same arithmetic as the small dense model, but on this computer a training step takes 1.9 times as long as the dense model's. Sorting tokens by expert, gathering them, and scattering the answers back costs time that the arithmetic count doesn't see. Big labs win the time back with kernels and hardware built for routing, and lose some of it to moving tokens between chips, chapter eight's subject.
4Collapse, and Switch's lossMaster's3 min
A router learns only from the experts it tries. So what happens to the ones it stops trying? Train our mixture with no help, and watch how the tokens are shared out. It's a rich-get-richer loop: an expert that's chosen more is trained more, gets better, and is chosen even more; a starved expert stops learning, and its parameters are wasted. Shazeer saw it in 2017, and called it a self-reinforcing imbalance.
Shazeer's team met this in 2017 and added losses to fight it. The first: add up each expert's gate values over the batch, its importance, and penalize the squared coefficient of variation of those totals, the standard deviation divided by the mean. It's zero only when every expert is equally important. For our unbalanced router, measured on its token shares, the coefficient of variation is 0.33. Pause and think: why divide by the mean? Because then the penalty doesn't care about the overall scale of the gates, only about how unevenly they're spread. A second loss balanced the expected number of tokens, since equal importance can still hide unequal counts.
The classic fix adds a penalty to the loss. Two numbers per expert. f i, the share of the batch's token slots actually sent to expert i: a count, so it has no gradient. P i, the router's average probability for expert i: that one is differentiable. The Switch Transformer's penalty is alpha times E times the sum of f i times P i, with alpha a hundredth. Why that product? If the router's probabilities match where tokens go, it's E times the sum of f i squared, which by Cauchy-Schwarz is at least one, with equality only when every expert gets one E-th. And its gradient pushes each expert's probability down in proportion to how busy that expert already is: the favourites get pushed hardest. GShard had used a similar penalty a year earlier, and in 2022 ST-MoE added a second, the z-loss, which keeps the router's scores from growing huge.
Here is our mixture again, the same seed, trained with and without the penalty. But the penalty is a second goal, competing with the first. Make alpha too small and the router collapses; make it too big and it bends the routing away from what predicts best. The next chapter removes the trade-off.
5Balancing without a lossMaster's2 min
In 2024 DeepSeek removed the trade-off. Give every expert a bias, a single number, and add it to the expert's score only when choosing the top k. The gates that mix the chosen experts use the scores alone: the bias changes the choice, without being added to the mixing scores. After every step, look at the loads: an expert busier than average has its bias lowered by a small step gamma, and an idle one has it raised. There's no extra loss, so no gradient fights the language model. Lean Wang and colleagues reported both better balance and lower perplexity than the auxiliary loss, and DeepSeek-V3 was trained this way.
Here is DeepSeek-V3's routing mechanism, since it's become a template. Each expert gets a score from a sigmoid, its own yes-or-no, rather than a softmax that makes experts compete. The top k are chosen by score plus the balancing bias. The gates use the scores alone, rescaled to add to one. And one shared expert sees every token, to hold what everything needs; the routed sum is scaled by two point five. The bias moved by a thousandth a step for the first fourteen point three trillion tokens, then froze; a tiny extra loss kept single sequences from piling onto a few experts; and no token was ever dropped.
Here are all three rules at once, replayed through training: each bar is one expert's share of the tokens in the first block. On the right, the bias holds every expert near its fair share. Below, the biases themselves: each is a running tally of how often its expert was too busy or too idle.
The scoreboard, over three seeds each. One caution: our bias model also uses DeepSeek's sigmoid gates, while the other two use softmax gates, so the comparison is between routers, not just between balancing rules. The lesson DeepSeek drew: balance by steering the choice, not by changing the loss.
6Fine-grained and shared expertsMaster's2 min
In January 2024 Damai Dai and colleagues at DeepSeek asked how big an expert should be. Mixtral used a few big experts and chose two. Cut every expert into four smaller ones, and choose four times as many: the same total expert matrix size and matrix work per token, but each token's mixture is assembled from finer pieces. And set one expert aside to be shared by every token, so that what every token needs, like common words and grammar, is learned once instead of being copied into every expert. They called these fine-grained segmentation and shared-expert isolation.
They reported that it pays. At two billion parameters, DeepSeekMoE matched GShard's design with one and a half times the expert parameters and computation. Scaled to sixteen billion, it matched Meta's dense LLaMA 2 7B with about forty percent of the computation. Those are the makers' own numbers; let's check the idea on ours.
Why should finer pieces help? Count the teams a token can get. Two of eight experts can be chosen 28 ways. Eight of thirty-two, the same expert matrix work, can be chosen 10.5 million ways. The count grows like a power of k: it's squeezed between N over k and e N over k, to the power k. DeepSeek's own example: two of sixteen experts gives 120 teams; cut each into four and choose eight of sixty-four, and there are 4.4 billion. Each token can get a team built more precisely for it.
We trained all three with matched total expert matrix size and active expert width, two seeds each. Router parameters and estimated FLOPs differ slightly. At the frontier the direction is clear: DeepSeek-V3 has two hundred and fifty-six fine experts and chooses eight, plus one shared; Kimi K3 has eight hundred and ninety-six, chooses sixteen, and shares two.
7Capacity and dropped tokensEngineering3 min
On real hardware, each expert gets a buffer of fixed size, so that every chip knows its work in advance. The capacity: a factor c times an expert's fair share of the batch, k N over E. When more tokens than that choose one expert, the extra ones are dropped: they skip the layer, carried along by the residual connection, as if the layer weren't there. GShard and Switch trained with factors of one to one and a quarter, and accepted a few dropped tokens. The more uneven the router, the more it drops.
How much is dropped? Expert i is asked for f i times k N slots, its share of all of them. Ignoring integer rounding, its buffer holds c times k N over E. Whatever doesn't fit is dropped. Divide by the number of slots, and the dropped share is the sum over experts of how far each one's share exceeds c over E. Pause and predict: with perfectly even routing, what factor drops nothing? One. And if one expert gets twice its share, a factor of one drops exactly the extra: one E-th of all the slots.
We can measure this on our trained routers: impose a capacity afterwards, and count what's dropped. At a factor of one, the unbalanced router drops percent of its token slots, the router trained with Switch's loss percent, and the router with the loss-free bias percent. In bits, a factor of one costs the unbalanced model bits a character, and the bias model .
What if the limit is there during training? There's another way to avoid drops: let each expert choose its tokens instead, expert choice, from Yanqi Zhou and colleagues in 2022. It balances perfectly by construction, but an expert's choice depends on the whole batch, including tokens that come later, a problem chapter eleven meets again. DeepSeek-V3 drops nothing at all: its balance is good enough, and its kernels flexible enough, to take whatever arrives.
8Experts across chipsEngineering2 min
A model with hundreds of experts doesn't fit on one chip, so the experts are spread out: expert parallelism, which part 18 builds. Here, eight experts on four GPUs. Each GPU holds some of the tokens, and the router sends them anywhere. So every MoE layer begins with an all-to-all, each GPU sending every token to its experts' GPU, and ends with another, bringing the answers home.
How expensive is that? Take DeepSeek-V3, one token, one MoE layer. It sends eight copies of a 7,168-number vector out, in eight-bit numbers, and gets eight answers back in sixteen bits: 172 kilobytes. The eight experts do 705 million operations on it. That's 4,096 operations per byte moved: twice the expert's width, whatever the model. But a GPU doing eight-bit arithmetic needs about 39,580 operations per byte from InfiniBand to stay busy, part seventeen's roofline. Sent naively, the network would take 10 times as long as the experts. So DeepSeek sent each token to at most four of its eight machines, crossing InfiniBand once per machine and spreading over NVLink inside it, dispatched in eight bits, and hid the rest by computing one batch while another was in flight.
And balance, which looked like a matter of using every parameter, turns out to be a matter of speed. Put our trained experts on four GPUs, two each, and count each GPU's share of the work. Every GPU must finish before the next layer can start, so the step takes as long as the busiest GPU. Without balancing, that's 1.36 times a fair share; with Switch's loss, 1.18; with the bias, 1.01. On a real cluster that factor multiplies the time of every MoE layer.
9Counting parameters, and upcyclingUndergraduate3 min
What do numbers like six hundred and seventy-one billion parameters, thirty-seven billion active, actually count? We can work them out from DeepSeek-V3's published configuration. One expert is a SwiGLU network: three matrices of 7,168 by 2,048, 44 million parameters. 256 of them in each of 58 MoE layers: 654 billion, nearly everything. Attention, part fifteen's latent attention, adds 11.4 billion across all 61 layers. With the three dense layers, the shared experts, the routers and the embeddings, the total comes to 671.0 billion: the report's 671. Count nine experts per MoE layer, eight routed and one shared. Our accounted active proxy is 37.6 billion, including the full input embedding table; a lookup reads one row. The report gives thirty-seven billion under its active-parameter convention.
Routed experts hold nearly all of DeepSeek-V3's parameters. Small segments are enlarged here, and the router is omitted from the bars. The accounted active proxy is 5.6 percent of total capacity, including the full input embedding table. Within this proxy the experts are 61 percent, and attention is 30 percent. The same arithmetic explains Mixtral's name. Eight times seven billion would be fifty-six, but Mixtral 8x7B has 46.7 billion, because only the feed-forward layers are copied eight times; the attention is shared. Its active proxy is 12.9 billion per token under the same full-table convention. And when you see six hundred and eighty-five billion for DeepSeek-V3, that includes a module that predicts a second token ahead, part eighteen's multi-token prediction.
Training a big mixture from scratch is expensive. What if you already have a good dense model? Copy its feed-forward layer into every expert, add a new router, and keep training. At the moment of copying, the new model computes exactly what the old one did: every chosen expert gives the same answer, and the gates add to one. Training then pulls the copies apart. Aran Komatsuzaki and colleagues called it sparse upcycling, in 2022; Qwen's first mixture, in 2024, was made this way too.
We tried it. A dense model one expert wide, trained for a thousand steps, then copied into eight experts with one percent multiplicative noise, and trained for a thousand more, beside the same dense model kept dense, and our mixture trained from scratch. Curves use ninety-six held-out windows; final values use four hundred.
10What experts learnMaster's1 min
What do the experts learn? Here's where our mixture sends each common character's tokens, in its last block: one column per character just read, one row per expert. But is it about the character itself, or about what comes next? We can measure it.
Mutual information, from part one: how many bits the choice of expert tells you about a character. The shuffled bars use permuted character labels as a reference on the same positions.
The big models look similar. Mistral's analysis of Mixtral found no experts for topics like biology or philosophy. Instead, syntax: the same expert for the word self in Python, for indentation, and often for consecutive tokens. OLMoE, a fully open mixture from 2024, found clearer specialization, by domain and by vocabulary. The name is a little misleading. An expert isn't a specialist in chemistry; it's a slice of the network that a router learned to reach for, often for reasons on the surface of the text.
And the scoreboard, the series' running test on a chapter of The Maltese Falcon.
11Mixture-of-depthsMaster's2 min
Experts make the width sparse. Can the depth be sparse too? Does every token need every layer? In 2024 David Raposo and colleagues at Google DeepMind gave some blocks a router of their own. It scores every token in the sequence; only the top k go through the block, attention and feed-forward both, and the rest skip it along the residual stream. The block's output is multiplied by the router's score, so the router learns from the loss, as in a mixture of experts. They found it worked best with only an eighth of the tokens in every other block, and sampling from their models was upwards of fifty percent faster.
What does it save? In a routed block that takes a fraction c of the T tokens, the matrices act on only c T tokens, and attention, among the chosen tokens only, computes c T squared scores. At an eighth, that's an eighth of the matrix work and a sixty-fourth of the attention. Route every other block of four, and the matrices cost about nine sixteenths of the full model's, per token.
We trained it. Our four-block transformer, with blocks two and four routed, against dense models of two, three and four blocks. Estimated sparse arithmetic per character on one axis, held-out bits on the other. Our code still executes dense operations. The dense models make a line: more blocks, more compute, fewer bits.
Which tokens get the deep treatment? Here's one stretch of held-out text: lit, the characters the routed blocks process. The router favours : it takes percent of them. But there's a catch. Choosing the top eighth of a sequence means looking at the whole sequence, later tokens included, which a model writing one token at a time can't do. The paper trains the router to predict its own top-k choice, with an extra loss, so that at generation it can decide alone.
12How sparse is attention?Master's2 min
Attention reads every earlier token, so its cost grows with the square of the length. The first answers fixed the pattern in advance. OpenAI's Sparse Transformer, in 2019, read a local window and every k-th key, for a cost that grows like the length to the power one and a half. In 2020, Longformer added a few global keys that everyone reads, and Google's BigBird added random ones as well, and proved that such patterns lose no expressive power in principle. Mistral 7B, in 2023, kept just a sliding window, and stacked layers let information travel further back. Part 19 measures what windows save at serving time. But all of these decide in advance which keys a query may read. Does that match where attention actually goes?
Attention looks at every earlier token, but how much of that does it use? Take part thirteen's transformer and, for each query, rank its keys by weight. Each line is one head: how much of the attention its top k keys hold. On average, the top sixteen keys, out of between a hundred and twenty-eight and two hundred and fifty-six, hold 92 percent. Most of the attention goes to a few keys.
Pause and predict. If each query may keep only eight keys, which choice loses less: the eight most recent, or the eight the query itself scores highest? The window is cheap to compute: it's fixed in advance. Choosing by score needs the scores first.
So let each query use only k keys. Which k? The simplest choice is the most recent ones, a sliding window: with keys, bits a character. Better, take the keys it would weight most: .
13Sparse attention by designResearch4 min
Choosing by score is what real models now do. Here's one query in our transformer, and how it weighs its last forty-eight keys. Together they hold 90 percent of its attention, and most of it lands on a handful of characters well back from the end. A sliding window keeps only the last eight keys: they hold just 7 percent. DeepSeek's native sparse attention cuts the past into blocks and squeezes each one into a summary. The query scores the summaries, reads selected blocks in full, and keeps a recent window. In this illustration we choose blocks by their full-attention mass, without training a compressor: 75 percent, from 16 keys. In DeepSeek-V3.2, a tiny, fast indexer gives every past token a score, and the query attends to the top ones only: two thousand and forty-eight in the real model, eight here with an ideal indexer, holding 76 percent. The trick in both is that finding the important keys must be much cheaper than attending to all of them.
In equations: NSA's output is a gated sum of three attentions, over the block summaries, over the chosen blocks in full, and over a recent window, with gates the model learns. DSA's indexer scores each past token with a few small heads: a weighted sum of rectified dot products, where any negative score is set to zero, part nine's ReLU, all computed in eight-bit numbers: each rounded to one of two hundred and fifty-six values, to save time and memory. Then real attention runs over the top two thousand and forty-eight. The indexer still looks at every pair, but it's so small that the expensive part now grows with the length times two thousand, not the length squared.
Can a model learn where to look? We need a task where it matters. Each sequence starts with eight facts, each a single token that binds a key to a value: key three goes with value eleven, say. Then forty tokens of filler. Then each key is asked, and the model must answer with its value. The fact it needs is at least forty tokens back. We train our small transformer on it with full attention, and with three sparse patterns with nominal 8-key selection budgets: a sliding window; block selection, the query's own block of four and the one block whose average key it scores best, as in MoBA and NSA; and a learned indexer that may pick any 8 keys, as in DeepSeek's sparse attention. The indexer also keeps the current token if it was not selected, so it can read up to 9 keys.
Here's training, the share of answers right. This year's frontier combines the ideas. DeepSeek-V4, released in April 2026, compresses every 4 keys and values into one entry, and a lightning indexer chooses the best 1,024 of those for each query, with a window of the last 128 tokens for local detail. Other layers compress 128 to one and read everything that's left. Its indexer has 64 heads, computed in 4-bit numbers. At a million tokens, DeepSeek reports 27 percent of V3.2's computation per token and 10 percent of its cache. What the cache saves is part fifteen's subject, and serving it is part nineteen's.
14Lottery ticketsUndergraduate2 min
The third kind of sparsity is the oldest: removing weights. In 1990 Yann LeCun, John Denker and Sara Solla removed the weights whose loss the Hessian said would hurt least, and called it optimal brain damage. In 2015 Song Han and colleagues showed how much can go: prune the smallest weights, retrain, repeat, and AlexNet shrank 9 times, VGG 13 times, with no loss in accuracy. But a strange thing was known: the small pruned network, trained from scratch, did worse. In 2018 Jonathan Frankle and Michael Carbin found that it trains well only from its original starting weights. Their conjecture: a big random network contains a small subnetwork, a winning lottery ticket, that could have been trained alone to the same accuracy. The big network is how you buy enough tickets.
How do you find a ticket? Train, prune, rewind, repeat. Train the network; remove the 20 percent of weights smallest in size; rewind the survivors to the values they had early in training, here at step 50; and train again. Rewinding to a few steps in, rather than to the very start, was Frankle's later fix for bigger networks. Our network reads three characters and guesses the next. Here is a corner of its weights, round by round, as the mask thins to 22 percent. The tests: the same mask with fresh random weights, and a random mask of the same size.
Here are the three, round by round, as the network thins. The catch: finding the smallest ticket took full trainings. Lottery tickets changed how people think about why big networks train well. To save compute in practice, sparsity has to be found cheaply, and has to suit the hardware: the next chapter.
15Two in four, and sparse activationsEngineering2 min
Removing half the weights doesn't make a network twice as fast. The zeros are scattered, and a GPU reads and multiplies in dense blocks. Here's a corner of our dense model's first feed-forward matrix. In 2020 NVIDIA's A100 introduced a compromise: two in four. In every group of four consecutive weights, exactly two must be zero. Then the matrix can be stored as two values and two small position indices per group, and the sparse tensor cores of part seventeen multiply it at twice the dense rate.
What does two in four cost? We pruned the block attention and feed-forward matrices, three seeds; embeddings and output stayed dense. That's NVIDIA's recipe: prune once, then retrain. For big language models, SparseGPT in 2023 pruned without retraining, using part nineteen's GPTQ machinery.
Sparsity also hides in the activations. Here are our dense model's feed-forward activations, after the GELU: 39 percent of them have magnitude below a tenth. A neuron whose activation is zero needn't be computed, nor its weights read. Calibrate fixed thresholds on the dense model's training batch, then score held-out text. Targets of half and ninety percent cost 0.064 and 0.47 bits a character.
With ReLU the zeros are exact. In the small ReLU network of the lottery chapter, the last recorded training batch snapshots average 36 percent zero activations across both hidden layers and seeds. In 2022 Zonglin Li and colleagues found that only three percent of T5-Base's activations are nonzero, and called it the lazy neuron phenomenon. Modern models use GELU and SwiGLU, without exact zeros, but in 2024 TEAL zeroed the smallest forty to fifty percent of Llama's activations, with little loss, and decoded up to 1.8 times faster, because a zero means a column of weights that needn't be read. The common thread of this part: sparsity pays when the hardware can skip it.
16The frontier, late 2026Research2 min
Where has all this led? Here are the large open mixtures of the last three years, by how many experts each layer holds. In December 2023 Mixtral had eight. A year later DeepSeek-V3 had two hundred and fifty-six, plus a shared one. In 2025 the field followed: Qwen3, Kimi K2 with three hundred and eighty-four, GLM-4.5, OpenAI's gpt-oss, MiniMax, and Qwen3-Next with five hundred and twelve. And in 2026, GLM-5, Qwen3.5, DeepSeek-V4, Mistral Large 4 released this week, and Kimi K3, with 896 experts in a layer and 16 chosen. Almost all of them are fine-grained, and most keep a shared expert.
Compare each maker's reported active-parameter share. Embedding and output conventions vary. Mixtral reports 28 percent; DeepSeek-V3, 5.5. Recent reports are around three to five percent: DeepSeek-V4-Pro 3.1, Kimi K3 3.7, and the sparsest here, DeepSeek-V4-Pro, 3.1. The thirty- to fifty-billion dense-model comparison for a trillion-parameter mixture is only a rough selected-matrix arithmetic analogy, not a measured cost equivalence. Mixtures are also in the closed models: Google's Gemini 1.5 and 2.5 reports describe sparse mixtures of experts, and OpenAI's open gpt-oss is one, though most labs don't publish their architecture.
And attention. In February 2025, DeepSeek's native sparse attention and Moonshot's MoBA both chose blocks of the past, and MoBA was already serving Kimi's long requests. In September, DeepSeek-V3.2's indexer chose single tokens. Not everyone was convinced: MiniMax went back to full attention for M2, saying its efficient hybrids matched full attention on the usual benchmarks but fell short on multi-step reasoning. But in 2026 GLM-5 adopted DeepSeek's sparse attention, DeepSeek-V4 compressed before choosing, MiniMax came back to sparse attention for M3, and Kimi K3 went mostly linear, part fifteen's subject. The 2026 recipe, then: many fine experts, a shared one, balancing that steers instead of penalizing, and attention that compresses, then chooses.
Recap, problems, and what comes nextAll tracks2 min
Let's take stock. In 1991 experts learned to compete and specialize. A router learns only from the experts it tries, which is why it needs noise to explore and help to share. Left alone, routers play favourites; Switch's loss and DeepSeek's bias spread the work, and the bias does it without bending the model. Finer experts, a shared one, capacity and chips, all follow from the same picture. Attention can choose its keys too, if the choice is learned. And weights can be pruned: lottery tickets exist, and two-in-four is the pattern hardware can use.
All of this comes back. The tensor cores and links that make experts and two-in-four fast are next time's subject, part seventeen. Part eighteen trains across thousands of chips, with expert parallelism and its all-to-all. Part nineteen serves experts and sparse attention. Image and video models use experts too, in part twenty-two. And in part thirty, sparsity shows up inside the network itself: features that fire only rarely, found with sparse autoencoders.
Here are six problems to try, from the router's gradient to counting Mixtral's parameters. Pause here, and work through them; full solutions are in this part's notes.
Next time: silicon. Why does all of this run on GPUs, and what limits it: arithmetic, memory, and the wires between chips. Part seventeen.
To go further, the Switch Transformer and DeepSeek-V3 papers are good places to start. Thanks for watching, and see you in part seventeen.
Where it goes next. The tensor cores and links that make experts and 2:4 sparsity fast are Part 17. Expert parallelism and its all-to-all return in Part 18, serving experts and sparse attention in Part 19, experts in image and video models in Part 22, and sparsity inside the network, as features found by sparse autoencoders, in Part 30.
Key results
The part's results in one place, for revision.
Try it
Lab 16 · The router's gradient, and balance without a loss
For one token and eight random linear experts, compare the router's gradient from the film's formula, from the series' autodiff and from finite differences, for Mixtral's softmax gate and DeepSeek-V3's sigmoid gate. Then route 512 tokens a step through a router that plays favourites, and let the loss-free bias even it out.
python -m videos.ai.labs 16
needs numpy, scipy, matplotlib · download lab16.py ·
source on GitHubsoftmax gate: formula against finite differences 1.4e-09 (relative)
softmax gate: autodiff against finite differences 1.4e-09 (relative)
sigmoid gate: formula against finite differences 2.9e-09 (relative)
sigmoid gate: autodiff against finite differences 2.9e-09 (relative)
scores with any gradient 2 of 8 (k = 2)
no balancing: busiest expert 2.56 x a fair share MaxVio 1.56
no balancing: slots dropped at c = 1 37.1% by the formula 37.1% filling buffers
no balancing: E sum f_i^2 1.733 (Switch's penalty when P = f; at least 1)
loss-free bias: busiest expert 1.04 x a fair share MaxVio 0.04
loss-free bias: slots dropped at c = 1 1.6% by the formula 1.6% filling buffers
loss-free bias: E sum f_i^2 1.001 (Switch's penalty when P = f; at least 1)
A router learns only from the experts it tried: the unchosen scores have gradient exactly zero. A bias added to the scores only when choosing spreads the load, and a capacity factor of 1 then drops almost nothing.
The code (144 lines; it asserts its own result)
"""Lab 16: check the router's gradient through a top-k gate three ways, then balance a lopsided router with a bias."""
import numpy as np
from videos.coursekit import labs
from explainer.ai.autodiff import Tensor, log_softmax, sigmoid
TITLE = "The router's gradient, and balance without a loss"
GOAL = ("For one token and eight random linear experts, compare the router's gradient from the film's formula, from "
"the series' autodiff and from finite differences, for Mixtral's softmax gate and DeepSeek-V3's sigmoid gate. "
"Then route 512 tokens a step through a router that plays favourites, and let the loss-free bias even it out.")
TASKS = [
"Set K_TOP = 1 with the softmax gate (a renormalized top-1 gate). What is the gradient, and why does Switch keep "
"the raw probability instead?",
"Raise GAMMA from 0.01 to 0.2. Does the busiest expert's load settle closer to a fair share or further from it?",
"Replace the bias by capacity alone: keep the unbalanced router and find the capacity factor that drops under 1% "
"of the token slots.",
]
E, K_TOP, D = 8, 2, 6
GAMMA, STEPS, BATCH = 0.01, 600, 512
def gates(s, chosen, kind):
"""The gates of the chosen experts as a Tensor: a softmax over the chosen scores, or sigmoids rescaled to add to 1."""
if kind == "softmax":
return log_softmax(s[chosen]).exp()
sg = sigmoid(s[chosen])
return sg / sg.sum()
def formula(s, chosen, u, kind):
"""dL/ds_j = g_j (u_j - u_bar) for chosen experts (times 1 - sigma_j for the sigmoid gate), 0 otherwise."""
out = np.zeros(E)
if kind == "softmax":
g = np.exp(s[chosen] - s[chosen].max())
g /= g.sum()
out[chosen] = g * (u - g @ u)
else:
sg = 1 / (1 + np.exp(-s[chosen]))
g = sg / sg.sum()
out[chosen] = (1 - sg) * g * (u - g @ u)
return out
def loads(scores, bias):
"""Each expert's share of the token slots when the top k are chosen by score + bias."""
pick = np.argsort(-(scores + bias), axis=1)[:, :K_TOP]
return np.bincount(pick.ravel(), minlength=E) / pick.size, pick
def dropped_by_buffers(pick, c):
"""Fill each expert's buffer of ceil(c k N / E) slots in token order and count the slots that do not fit."""
cap, used, lost = int(np.ceil(c * pick.size / E)), np.zeros(E, int), 0
for e in pick.ravel():
if used[e] < cap:
used[e] += 1
else:
lost += 1
return lost / pick.size
def run(seed=0):
rng = np.random.default_rng(seed)
lab = labs.Lab()
# 1. the router's gradient: formula, autodiff, finite differences
A = rng.standard_normal((E, D, D))
x, target = rng.standard_normal(D), rng.standard_normal(D)
s0 = rng.standard_normal((E, D)) @ x
chosen = np.argsort(-s0)[:K_TOP]
Y = A[chosen] @ x # the chosen experts' outputs, one row each
def loss(s, kind):
y = gates(s, chosen, kind) @ Tensor(Y)
return ((y - target) ** 2).sum() * 0.5, y
grads = {}
for kind in ("softmax", "sigmoid"):
s = Tensor(s0, requires_grad=True)
L, y = loss(s, kind)
L.backward()
u = Y @ (y.data - target) # u_i: how hard expert i's output pushes the loss
fd = np.zeros(E)
for i in range(E):
h = np.zeros(E)
h[i] = 1e-6
fd[i] = (loss(Tensor(s0 + h), kind)[0].data - loss(Tensor(s0 - h), kind)[0].data) / 2e-6
ana = formula(s0, chosen, u, kind)
scale = max(np.abs(fd).max(), 1e-12)
grads[kind] = (fd, ana, s.grad)
lab.row(f"{kind} gate: formula against finite differences", f"{np.abs(ana - fd).max() / scale:.1e} (relative)")
lab.row(f"{kind} gate: autodiff against finite differences", f"{np.abs(s.grad - fd).max() / scale:.1e} (relative)")
assert np.abs(ana - fd).max() / scale < 1e-5 and np.abs(s.grad - fd).max() / scale < 1e-5, kind
rest = np.setdiff1d(np.arange(E), chosen)
assert np.all(s.grad[rest] == 0) and np.abs(fd[rest]).max() < 1e-9, "an unchosen score gets no gradient"
if K_TOP > 1:
assert np.count_nonzero(s.grad) == K_TOP, "every chosen score learns"
lab.row("scores with any gradient", f"{np.count_nonzero(grads['softmax'][2])} of {E} (k = {K_TOP})")
# 2. a router that plays favourites, balanced by a bias that only steers the choice
favour = np.linspace(1.2, -1.2, E)
draw = lambda: favour + rng.standard_normal((BATCH, E)) # noqa: E731
bias, trace = np.zeros(E), []
for _ in range(STEPS):
f, _ = loads(draw(), bias)
trace.append(E * f.max() - 1) # MaxVio: the busiest expert's excess over a fair share
bias -= GAMMA * np.sign(f - 1 / E)
test = favour + rng.standard_normal((20 * BATCH, E))
out = {}
for name, b in (("no balancing", np.zeros(E)), ("loss-free bias", bias)):
f, pick = loads(test, b)
drop = np.maximum(0, f - 1 / E).sum()
out[name] = dict(f=f, maxvio=E * f.max() - 1, drop=drop, sim=dropped_by_buffers(pick, 1.0))
lab.row(f"{name}: busiest expert", f"{E * f.max():.2f} x a fair share MaxVio {out[name]['maxvio']:.2f}")
lab.row(f"{name}: slots dropped at c = 1", f"{drop:.1%} by the formula {out[name]['sim']:.1%} filling buffers")
lab.row(f"{name}: E sum f_i^2", f"{E * (f ** 2).sum():.3f} (Switch's penalty when P = f; at least 1)")
assert abs(drop - out[name]["sim"]) < 2e-3, "dropped share = sum of max(0, f_i - c/E)"
a, b = out["no balancing"], out["loss-free bias"]
assert a["maxvio"] > 0.5 and a["drop"] > 0.15, "the unbalanced router overloads its favourites"
assert b["maxvio"] < 0.1 and b["drop"] < 0.03, "the bias brings every expert near its fair share"
assert E * (b["f"] ** 2).sum() < E * (a["f"] ** 2).sum()
lab.note = ("A router learns only from the experts it tried: the unchosen scores have gradient exactly zero. A bias "
"added to the scores only when choosing spreads the load, and a capacity factor of 1 then drops almost "
"nothing.")
fig, ax = labs.figure(2, size=(11, 4.2))
fd, ana, auto = grads["softmax"]
w = 0.27
for k, (vals, color, name) in enumerate(((fd, labs.GREY, "finite differences"), (ana, labs.GOLD, "g_j (u_j - u_bar)"),
(auto, labs.BLUE, "autodiff"))):
ax[0].bar(np.arange(E) + (k - 1) * w, vals, w, color=color, label=name)
ax[0].axhline(0, color=labs.MUTED, lw=0.8)
ax[0].set(title=f"The router's gradient, softmax gate: {K_TOP} of {E} scores learn", xlabel="expert",
ylabel="dL/ds")
ax[0].set_xticks(range(E), [f"{i}*" if i in chosen else str(i) for i in range(E)])
ax[0].legend(title="* = chosen", loc="best")
ax[1].bar(np.arange(E) - 0.2, E * a["f"], 0.4, color=labs.RED, label="no balancing")
ax[1].bar(np.arange(E) + 0.2, E * b["f"], 0.4, color=labs.GREEN, label="loss-free bias")
ax[1].axhline(1, color=labs.MUTED, ls="--", lw=1, label="fair share = capacity at c = 1")
ax[1].set(title="Each expert's load, in fair shares", xlabel="expert", ylabel="share of token slots x E",
ylim=(0, 1.25 * E * a["f"].max()))
ax[1].legend(loc="upper right")
lab.fig = fig
return lab
Now change it
- Set K_TOP = 1 with the softmax gate (a renormalized top-1 gate). What is the gradient, and why does Switch keep the raw probability instead?
- Raise GAMMA from 0.01 to 0.2. Does the busiest expert's load settle closer to a fair share or further from it?
- Replace the bias by capacity alone: keep the unbalanced router and find the capacity factor that drops under 1% of the token slots.
Problems, with solutions
Try each problem before opening its solution.
-
For DeepSeek-V3's gates g_i = σ(s_i)/Σ_{j∈K} σ(s_j), show that ∂L/∂s_j = (1 − σ(s_j)) g_j (u_j − ū) for j ∈ K, and 0 otherwise.
Solution
With S = Σ_{j∈K} σ_j and σ′_j = σ_j(1 − σ_j): ∂g_i/∂s_j = (δ_ij σ′_j S − σ_i σ′_j)/S² = (σ′j/S)(δ_ij − g_i) = (1 − σ_j) g_j (δ_ij − g_i). So ∂L/∂s_j = Σ{i∈K} u_i ∂g_i/∂s_j = (1 − σ_j) g_j (u_j − Σ_i g_i u_i). An unchosen s_j appears nowhere in the output (the top-k choice is piecewise constant in s), so its gradient is 0.
-
Show that if f = P, Switch's E Σ_i f_i P_i ≥ 1, with equality only when every f_i = 1/E. Why does it matter that f has no gradient?
Solution
With f = P and Σ f_i = 1, Cauchy–Schwarz gives (Σ f_i)² ≤ E Σ f_i², so E Σ f_i² ≥ 1, with equality iff all f_i are equal, i.e. 1/E. f is a count (piecewise constant), so the gradient flows only through P: ∂L_aux/∂P_i = αE f_i, which pushes the probability of the busiest experts down hardest; the product makes the penalty differentiable while still measuring where tokens actually go.
-
Show that (N/k)^k ≤ C(N, k) ≤ (eN/k)^k, and compute C(64, 8)/C(16, 2).
Solution
C(N, k) = Π_{i<k} (N − i)/(k − i) and each factor is ≥ N/k (since N ≥ k), giving the lower bound. And C(N, k) ≤ N^k/k! with k! ≥ (k/e)^k (because e^k = Σ_n k^n/n! ≥ k^k/k!), giving the upper bound. C(64, 8) = 4,426,165,368 and C(16, 2) = 120: a ratio of about 36.9 million.
-
Eight experts get these shares of the token-slots: 0.3, 0.2, 0.2, 0.1, 0.1, 0.05, 0.03, 0.02. What share is dropped at capacity factors 1 and 1.25?
Solution
Capacity per expert is c/E of the slots: 0.125 at c = 1 and 0.15625 at c = 1.25. Dropped = Σ max(0, f_i − c/E): at c = 1, 0.175 + 0.075 + 0.075 = 0.325; at c = 1.25, 0.14375 + 0.04375 + 0.04375 = 0.23125.
-
DeepSeek-V4-Pro: d = 7,168, experts of width 3,072, 6 routed per token. Compute the all-to-all bytes per token per layer (FP8 out, BF16 back), the experts' FLOPs, and their ratio.
Solution
Bytes: k d (1 + 2) = 6 × 7,168 × 3 = 129,024 (about 129 kB). FLOPs: 2 · 3 d h · k = 6 × 7,168 × 3,072 × 6 = 792,723,456 (about 793 million). Ratio: 2h = 6,144 FLOPs per byte, against about 39,580 for an H100-class GPU's FP8 arithmetic over 50 GB/s InfiniBand: sent naively, the network would take about 6.4 times as long as the experts.
-
Mixtral 8x7B: 32 layers, d = 4,096, SwiGLU experts of width 14,336, 32 query heads and 8 key-value heads of 128, a vocabulary of 32,000. Count its total and active parameters.
Solution
Attention per layer: 2 × 4,096² + 2 × 4,096 × 1,024 = 41,943,040. One expert: 3 × 4,096 × 14,336 = 176,160,768; eight: 1,409,286,144; router 32,768; two norms 8,192. Per layer 1,451,270,144; × 32 = 46,440,644,608; embeddings and output 2 × 32,000 × 4,096 = 262,144,000; final norm 4,096: total 46,702,792,704 ≈ 46.7B. Active: per layer 41,943,040 + 2 × 176,160,768 + 32,768 + 8,192 = 394,305,536; × 32 + 262,148,096 = 12,879,925,248 ≈ 12.9B.
Notes and sources
Glossary
| English | 中文 |
|---|---|
| mixture of experts (MoE), expert | 混合专家(MoE),专家 |
| gate, gating network | 门控,门控网络 |
| router, router score | 路由器,路由分数 |
| top-k gating, KeepTopK | top-k门控,KeepTopK |
| noisy top-k gating | 带噪声的top-k门控 |
| competitive / cooperative loss | 竞争式 / 合作式损失 |
| responsibility (posterior) | 责任(后验概率) |
| active parameters, total parameters | 激活参数,总参数 |
| load balancing, routing collapse | 负载均衡,路由坍缩 |
| importance loss, coefficient of variation (CV) | 重要性损失,变异系数(CV) |
| auxiliary loss (Switch), z-loss | 辅助损失(Switch),z损失 |
| auxiliary-loss-free balancing, balancing bias | 无辅助损失的负载均衡,均衡偏置 |
| sigmoid gate | sigmoid门控 |
| MaxVio (maximal violation) | 最大违背度(MaxVio) |
| fine-grained expert, shared expert | 细粒度专家,共享专家 |
| capacity, capacity factor, dropped token | 容量,容量因子,被丢弃的词元 |
| expert-choice routing | 专家选择路由 |
| expert parallelism, all-to-all | 专家并行,全对全通信 |
| node-limited routing | 节点受限路由 |
| sparse upcycling | 稀疏升级(upcycling) |
| mixture-of-depths | 深度混合(MoD) |
| sliding-window attention, block selection | 滑动窗口注意力,块选择 |
| native sparse attention (NSA), MoBA | 原生稀疏注意力(NSA),MoBA |
| DeepSeek sparse attention (DSA), lightning indexer | DeepSeek稀疏注意力(DSA),闪电索引器 |
| compressed sparse attention (CSA), heavily compressed attention (HCA) | 压缩稀疏注意力(CSA),重度压缩注意力(HCA) |
| associative recall | 联想回忆 |
| pruning, magnitude pruning | 剪枝,按幅度剪枝 |
| lottery ticket hypothesis, winning ticket | 彩票假设,中奖彩票 |
| iterative magnitude pruning, rewinding | 迭代幅度剪枝,回卷 |
| unstructured / structured sparsity, 2:4 sparsity | 非结构化 / 结构化稀疏,2:4稀疏 |
| sparse tensor cores | 稀疏张量核心 |
| Wanda, SparseGPT | Wanda,SparseGPT |
| activation sparsity, lazy neuron phenomenon | 激活稀疏,懒惰神经元现象 |
Sources
Fact-check notes (checked October 2026)
- DeepSeek-V3: config.json (
n_routed_experts256,num_experts_per_tok8,n_shared_experts1,moe_intermediate_size2048,first_k_dense_replace3, 61 layers, d 7168, vocab 129,280); our count gives 671.0B total and 37.6B active with the input embedding (36.6B without); the report gives 671B and 37B, and 685B on Hugging Face including the 14B multi-token-prediction module. Routing details from the report (Secs. 2.1.2, 3.2, 4.2). DeepSeek-V3.2-Exp's config.json: indexer 64 heads of 128, top 2,048. - DeepSeek-V4 (arXiv 2606.19348, 2026): V4-Pro 1.6T/49B, 384 routed + 1 shared, 6 active; V4-Flash 284B/13B, 256 + 1, 6 active; CSA compression 4, HCA 128, indexer top-k 1,024 (Pro) / 512 (Flash), window 128, 64 indexer heads of 128 in FP4; 27% of V3.2's single-token FLOPs and 10% of its KV cache at 1M tokens (the makers' figures).
- Kimi K3: Hugging Face model card (2.8T, 104B active, 896 experts, 16 selected, 2 shared, 69 KDA + 24 gated MLA layers). Qwen3.5-397B-A17B and Qwen3-Next-80B-A3B: model cards (512 experts, 10 routed + 1 shared). GLM-5 and GLM-4.5: model cards and config.json (GLM-5: 744B/40B, 256 + 1, 8 active, DSA with 32 indexer heads; GLM-4.5: 160 + 1, 8 active). MiniMax-M2: model card (230B/10B) and config.json (256 experts, 8 active, full attention in all 62 layers); MiniMax's post "Why Did M2 End Up as a Full Attention Model?". MiniMax-M3: model card (≈428B/23B, MiniMax Sparse Attention, 1M context). Mistral Large 4: model card (≈1T, 52B active including embedding and output layers, 49B excluding both; 128 routed + 1 shared, 4 active; weights 29 October 2026). Llama 4: Meta's blog (5 April 2025). Kimi K2: model card. gpt-oss: model card.
- Switch-C: 1,571B parameters, 2,048 experts (Fedus et al., Table 9); α = 10⁻². GLaM: 1.2T, 96.6B activated (8%). GShard: 600B, 2,048 TPU v3, 4 days. Shazeer et al.: up to 137B parameters, >1000× capacity. DeepSeekMoE: 2B ≈ GShard 2.9B, 16B ≈ LLaMA2 7B with ≈40% of the computation (abstract).
- NSA: l = 32, d = 16, l′ = 64, n = 16, w = 512; 27B/3B model; up to 9.0× forward, 6.0× backward, 11.6× decoding at 64k (the decoding figure is an expected speedup from memory access). MoBA: deployed for Kimi's long-context requests (abstract). Mixture-of-depths: 12.5% capacity every other block; "upwards of 50% faster to step during post-training sampling". Sparse upcycling: "~50% of the initial dense pretraining sunk cost". Lazy neurons: 3.0% nonzero in T5-Base, 6.3% in ViT-B16. TEAL: 40–50% model-wide sparsity, up to 1.53×/1.8× decoding speed-ups.
- Claims resting on a single or company source: all model configurations and the makers' efficiency figures (DeepSeek-V4's 27%/10%, NSA's speed-ups, DeepSeekMoE's comparisons, MiniMax's reasons), Gemini's architecture statement, MoBA's deployment.
About this partfrom its README
Part 16 of a thirty-one-part series on how modern AI works and how it came to be (see the series plan). Using only some of a model at a time: mixtures of experts, mixture-of-depths, attention that reads only some of the past, and sparse weights and activations. A hook, sixteen chapters and an outro, about 50 minutes, in English and Chinese. Every model shown training is trained here, on a CPU, at equal active parameters and FLOPs, with several seeds and the spread shown; the computed results are listed under Results.
What is computed and built
Historical original-recipe results are retained below for provenance. In particular, the MI rows describe the
legacy special population and its window-boundary pairing; they do not satisfy the corrected Special contract.
These lines are not receipts for corrected outputs or for experiments performed with this source branch. Read-only
python -m videos.ai.ai16.results requires independently reviewed inputs and reports the versioned Special data.
- Mixture against dense (held-out bits per character, mean (range) of 3 seeds, 2,000 steps): dense with the mixture's arithmetic 2.246 (2.241–2.255), the mixture 2.146 (2.133–2.168), dense with its parameters 2.164 (2.155–2.179); on the scoreboard's passage 2.438, 2.343, 2.365. Parameters (total/used per character): 120,320/109,632, 317,952/110,656, 316,928.
- Milliseconds per training step on one core: dense 92, mixture 177, wide dense 175.
- no balancing: busiest expert 1.85× a fair share (end, mean over seeds and blocks), starved experts 2 of 48, MaxVio 0.98, bits 2.152 (2.135–2.164).
- Switch's loss: busiest expert 1.36× a fair share (end, mean over seeds and blocks), starved experts 0 of 48, MaxVio 0.47, bits 2.144 (2.137–2.154).
- loss-free bias: busiest expert 1.02× a fair share (end, mean over seeds and blocks), starved experts 0 of 48, MaxVio 0.21, bits 2.146 (2.133–2.168).
- Coarse / fine / fine + shared (2 seeds): 2.135 (2.133–2.137), 2.156 (2.150–2.161), 2.155 (2.153–2.156).
- Token-slots dropped at capacity factor 1 (imposed after training): none 21.9%, aux 8.1%, moe 1.6%; trained with c = 1: 2.168 (2.159–2.177) against 2.135 (2.133–2.137).
- Four simulated GPUs, busiest GPU's share × 4: none 1.36, aux 1.18, moe 1.01. DeepSeek-V3: 172,032 bytes and 705 MFLOP per token per MoE layer (4,096 FLOP/byte) against 39,580 for FP8 over InfiniBand.
- DeepSeek-V3 counted from its config: 671.0B total, 37.6B active (36.6B without the input embedding); Mixtral 46.70B / 12.88B.
- Upcycling (2 seeds): kept dense 2.308 (2.306–2.310), upcycled 2.237 (2.236–2.238), mixture from scratch 2.135 (2.133–2.137); upcycled training compute 86% of from scratch.
- Mutual information, block 1 (bits, 3 seeds): previous 0.25, current 1.53, next 0.24, shuffled 0.009.
- Mutual information, block 2 (bits, 3 seeds): previous 0.37, current 0.77, next 0.34, shuffled 0.009.
- Mixture-of-depths (MFLOP per character, bits, 2 seeds): dense_active 0.70, 2.242 (2.241–2.242); dense_l3 1.02, 2.198 (2.180–2.217); dense_l4 1.34, 2.168 (2.158–2.178); mod50 1.02, 2.212 (2.203–2.222); mod12 0.78, 2.250 (2.248–2.252). Deciding causally, the 12.5% model routes 13% and scores 2.248 (2.247–2.250).
- Router gradient: formula and autograd agree with finite differences to 1.4e-10 (relative); our MoE layer's router to 5.9e-09.
- 1991 mixture: the gate's trust in its favourite expert 0.919 (0.918–0.922) competing, 0.441 (0.404–0.493) cooperating.
- Recall (8 keys per query, 2 seeds): full 100%, window 7%, blocks 84%, index 100%; imposed on the full model: window 6%, blocks 76%, topk 100%.
- Part 13's transformer: all keys 1.791 bits; 8 keys by score 1.800, a window of 8 1.849.
- Lottery seed 0: dense 2.726; at 22% of the weights: ticket 2.768, re-initialized 2.976, random mask 3.151.
- Lottery seed 1: dense 2.766; at 22% of the weights: ticket 2.775, re-initialized 3.004, random mask 3.172.
- 2:4 on the dense model (3 seeds): dense 2.253 (2.246–2.257); magnitude_24 3.457 (3.388–3.593); wanda_24 3.197 (3.146–3.258); unstructured 2.930 (2.850–3.087); random_24 5.179 (4.875–5.359); retrained magnitude 2:4 2.355 (2.336–2.373), Wanda 2:4 2.355 (2.346–2.370).
- Activations zeroed (share, bits): 0% 2.253, 25% 2.258, 50% 2.317, 75% 2.560, 90% 2.718, 95% 2.906.
- Scoreboard rows: Part 16: dense, same arithmetic 2.438, Part 16: mixture of experts 2.343, Part 16: dense, same parameters 2.365.
Chapter notes
- A few experts at a time (hook). DeepSeek-V3's 256 experts per layer, 8 and a shared one lighting up for each word; Kimi K3 (July 2026): 896 experts, 16 chosen and 2 shared. How we got here, in three threads: experts (1991 → Shazeer 2017 → GShard, Switch → Mixtral → DeepSeek-V3 → Kimi K3), attention (Sparse Transformer 2019, Longformer and BigBird 2020, sliding windows, NSA/MoBA/DSA 2025, DeepSeek-V4 2026) and weights (Optimal Brain Damage 1990, Han et al. 2015, lottery tickets 2018, 2:4 on the A100 2020, SparseGPT and Wanda 2023). Objectives.
- 1. Competing experts, 1991. The mixture of experts defined (Jacobs, Jordan, Nowlan & Hinton 1991). The cooperative loss against the competitive one, derived: the competitive gradient is each expert's own error weighted by its posterior responsibility h_i (Part 7's EM). Computed: four straight-line experts and a softmax gate on a three-regime curve, trained both ways (three seeds), the gates replayed through training. Jordan & Jacobs (1994); Shazeer et al. (2017): noisy top-k gating, KeepTopK, 137 billion parameters.
- 2. Top-k gates and the router's gradient. The layer (Mixtral's gate). The router's gradient derived: ∂L/∂s_j = g_j (u_j − ū) for chosen experts, 0 otherwise. Checked by finite differences and autograd (float64), and on our own MoE layer's router. Pause and predict: top-1 with a renormalized gate learns nothing (Switch keeps p_i).
- 3. A mixture, trained. Our character transformer (Part 13's, d = 64, 2 blocks, 64 characters of context): dense with the mixture's arithmetic (hidden 256), the mixture (8 experts of 128, 2 per character, DeepSeek-V3's router), dense with the mixture's parameters (hidden 1,024); three seeds each, curves with spread; the routing replayed through training; wall-clock per step on one core (sparse arithmetic is not free time).
- 4. Collapse, and Switch's loss. Training without balancing: each expert's share of the tokens, replayed; the rich-get-richer loop. Shazeer's importance loss (CV²). Switch's auxiliary loss derived: f_i counted, P_i differentiable, E Σ f_i P_i ≥ 1 by Cauchy–Schwarz when f = P, ∂/∂P_i = αE f_i. GShard; ST-MoE's z-loss. Computed: with and without the loss (three seeds).
- 5. Balancing without a loss. DeepSeek's auxiliary-loss-free bias (Wang et al. 2024): the bias chooses, never weighs. DeepSeek-V3's router exactly (sigmoid scores, normalized gates, a shared expert; γ = 0.001 for 14.3T tokens, α = 0.0001 sequence-wise, no token dropping). The three rules replayed side by side; the biases through training; a table of busiest expert, starved experts, MaxVio and held-out bits.
- 6. Fine-grained and shared experts. DeepSeekMoE (Dai et al. 2024) and its reported results; the number of teams, (N/k)^k ≤ C(N,k) ≤ (eN/k)^k; computed: coarse (2 of 8), fine (8 of 32) and fine + shared (1 + 7 of 31) at equal active and total parameters (two seeds).
- 7. Capacity and dropped tokens. C = ⌈c·kN/E⌉; GShard and Switch. Computed: tokens dropped and bits lost against the capacity factor for each trained router; training with c = 1. Expert-choice routing (Zhou et al. 2022).
- 8. Experts across chips. Expert parallelism and the all-to-all (link: Part 18). DeepSeek-V3's traffic per token per MoE layer (FP8 out, BF16 back) against its experts' FLOPs: 2h FLOPs per byte against the GPU's ~40,000 per InfiniBand byte; node-limited routing, DualPipe. Computed: our routers placed on four simulated GPUs, the busiest GPU's share (every GPU waits for it).
- 9. Counting parameters, and upcycling. DeepSeek-V3's 671B and 37B derived from its config.json, matrix by matrix; drawn to scale; Mixtral's 46.7B and 12.9B; the 14B multi-token-prediction module. Sparse upcycling (Komatsuzaki et al. 2022) and why it starts exact; computed: a dense model upcycled halfway against it kept dense and against a mixture from scratch (two seeds), with training compute.
- 10. What experts learn. Where each character's tokens go (last block); mutual information between the chosen expert and the previous, current and next character against shuffled chance (three seeds, both blocks); fine experts; Mixtral's and OLMoE's analyses. The scoreboard, with this part's rows.
- 11. Mixture-of-depths. Raposo et al. (2024): a router per block takes the top 12.5%. Compute derived (an eighth of the matrices, a sixty-fourth of the scores). Computed: compute per character against held-out bits for dense models of 2, 3 and 4 blocks and routed models at 50% and 12.5% (two seeds); which characters it routes; the causal problem (top-k peeks at later tokens) and the router deciding alone.
- 12. How sparse is attention? Fixed patterns: strided (Child et al. 2019), window + global (Longformer), + random (BigBird), sliding windows (Mistral 7B). In Part 13's transformer: the attention mass held by the top k keys; bits per character with k keys chosen by score or as a window.
- 13. Sparse attention by design. One real query of Part 13's transformer: what a window, NSA's blocks and DSA's top-k keep; NSA's and DSA's equations. A recall task (after Zoology's MQAR): full attention, a sliding window, block selection (MoBA/NSA) and a learned lightning indexer (DSA's two stages) at 8 keys per query, two seeds; the patterns imposed on the full model without retraining. DeepSeek-V4's compressed sparse and heavily compressed attention (2026).
- 14. Lottery tickets. Optimal Brain Damage, Han et al., Frankle & Carbin; iterative magnitude pruning with rewinding; computed on a ReLU character network: the ticket against the same masks re-initialized and random masks, eight rounds to 22% of the weights (two seeds), the mask replayed.
- 15. Two in four, and sparse activations. 2:4 structured sparsity (A100, 2020; Part 17); computed on our dense transformer: unstructured 50%, 2:4 by magnitude, by Wanda's score and at random, and 2:4 retrained (three seeds); the feed-forward activations' distribution and the bits lost when the smallest are zeroed (TEAL-style); exact zeros in a ReLU network through training; the lazy neuron phenomenon; TEAL.
- 16. The frontier, late 2026. The large open mixtures of 2023–26 by experts per layer and share of parameters used per token (Mixtral → Kimi K3 and Mistral Large 4); mixtures in closed models (Gemini 1.5 and 2.5 reports); sparse attention since 2025 (NSA, MoBA, DSA, MiniMax-M2's return to full attention, GLM-5, DeepSeek-V4, MiniMax-M3, Kimi K3).
- Recap, where it comes back (Parts 17, 18, 19, 22, 30), problems, Part 17's teaser, references.
Companion material in this repository
The syllabus's plan for this partfrom SYLLABUS.md, the plan of record
- Top-k gating and the router's gradient.
- Switch balancing loss derived; DeepSeekMoE fine-grained and shared experts.
- Aux-loss-free bias; sigmoid routing.
- Capacity factor; expert parallelism and all-to-all cost; active-parameter accounting; upcycling.
- Specialization measured on our MoE (scoreboard row).
- Mixture-of-depths.
- Sparse attention: sliding window, NSA, MoBA, DSA's lightning indexer.
- Lottery tickets, pruning, 2:4 sparsity, activation sparsity.
中文讲义
本讲的中文部分(与英文版对应)。
中文
第16部分:稀疏。 每次只用模型的一部分:混合专家、深度混合、只读部分过去内容的注意力,以及稀疏的权重和激活。
习题
- 对DeepSeek-V3的门控 g_i = σ(s_i)/Σ_{j∈K} σ(s_j),证明对 j ∈ K 有 ∂L/∂s_j = (1 − σ(s_j)) g_j (u_j − ū),其余为0。
- 证明当 f = P 时,Switch的 E Σ_i f_i P_i ≥ 1,当且仅当每个 f_i = 1/E 时取等号。为什么 f 没有梯度很重要?
- 证明 (N/k)^k ≤ C(N, k) ≤ (eN/k)^k,并计算 C(64, 8)/C(16, 2)。
- 八个专家分到的词元槽份额为 0.3、0.2、0.2、0.1、0.1、0.05、0.03、0.02。容量因子为1和1.25时,丢弃的份额各是多少?
- DeepSeek-V4-Pro:d = 7168,专家宽度3072,每个词元路由到6个专家。计算每个词元、每层的全对全通信字节数(发出用FP8, 返回用BF16)、专家的浮点运算量,以及两者之比。
- Mixtral 8x7B:32层,d = 4096,SwiGLU专家宽度14336,32个查询头和8个键值头,每头128维,词表32000。数一数它的总参数和激活参数。
解答
Solutions
- 记 S = Σ_{j∈K} σ_j,σ′_j = σ_j(1 − σ_j)。则 ∂g_i/∂s_j = (σ′j/S)(δ_ij − g_i) = (1 − σ_j) g_j (δ_ij − g_i),所以 ∂L/∂s_j = Σ{i∈K} u_i ∂g_i/∂s_j = (1 − σ_j) g_j (u_j − Σ_i g_i u_i)。没被选中的 s_j 不出现在输出里(top-k选择对 s 是分段常数),梯度为0。
- f = P 且 Σ f_i = 1 时,由柯西–施瓦茨不等式 (Σ f_i)² ≤ E Σ f_i²,所以 E Σ f_i² ≥ 1,当且仅当所有 f_i 相等(都是1/E) 时取等号。f 是计数(分段常数),梯度只经过 P:∂L_aux/∂P_i = αE f_i,最忙的专家的概率被压得最狠;乘积让惩罚可微, 同时仍然衡量词元实际去了哪里。
- C(N, k) = Π_{i<k} (N − i)/(k − i),每个因子都 ≥ N/k,得下界;C(N, k) ≤ N^k/k!,且 k! ≥ (k/e)^k(因为 e^k = Σ_n k^n/n! ≥ k^k/k!),得上界。C(64, 8) = 4 426 165 368,C(16, 2) = 120,比值约3690万。
- 每个专家的容量是 c/E 的槽位:c = 1 时0.125,c = 1.25 时0.15625。丢弃 = Σ max(0, f_i − c/E):c = 1 时 0.175 + 0.075 + 0.075 = 0.325;c = 1.25 时 0.14375 + 0.04375 + 0.04375 = 0.23125。
- 字节:k d (1 + 2) = 6 × 7168 × 3 = 129 024(约129 kB)。浮点运算:2 · 3 d h · k = 792 723 456(约7.93亿)。 比值:2h = 6144次运算每字节;而H100级GPU的FP8算力配50 GB/s的InfiniBand,需要约39 580次运算每字节:直接发送的话, 网络要花的时间约是专家计算的6.4倍。
- 每层注意力:2 × 4096² + 2 × 4096 × 1024 = 41 943 040。一个专家:3 × 4096 × 14336 = 176 160 768,八个 1 409 286 144;路由器32 768;两个归一化8192。每层1 451 270 144,乘32得46 440 644 608;输入嵌入和输出层 2 × 32000 × 4096 = 262 144 000;最后的归一化4096:总计46 702 792 704 ≈ 467亿。激活:每层 41 943 040 + 2 × 176 160 768 + 32 768 + 8192 = 394 305 536,乘32再加262 148 096,得12 879 925 248 ≈ 129亿。
Build the film
python -m videos.ai.ai16.compute # the part's numbers, into .cache/ai16
python tools/build.py ai16 # render and assemble the film
EXPLAINER_TTS=silent python tools/qa_scene.py ai16 Hook # one chapter, silent, with a contact sheet
Scenes: videos/ai/ai16. Setup: see the course page. Source of these notes: the README and the scenes' narration.