Lecture guide: Attention alternatives and mixture of experts#
Lecturer: course staff · Course: Stanford CS336 Language Modeling from Scratch, Spring 2026, lecture 4 · Length: 1:28:00 Video: watch on YouTube Chapters that cite this lecture: 04. Attention Alternatives and Mixture of Experts
In one sentence: Tatsu Hashimoto shows the two ways a transformer escapes its costs at scale, attention that keeps a fixed-size state instead of comparing every pair of tokens, and feed-forward layers split into experts of which each token visits only a few, with the evidence that both work only as hybrids or with balancing losses.
Before you watch#
The lecture builds on the previous one's transformer and leaves the rest to the systems lectures. Two ideas take most of the time: linear attention and the state-space models grown out of it, which need only the associativity of multiplication, and the mixture of experts, which needs a router and a balancing loss. Slides are on the course website and GitHub. The chapter Attention Alternatives and Mixture of Experts covers both in the same order.
The lecture, part by part#
0:00–5:14 Two advanced ideas, and why attention cost grows#
Two developments go beyond the tweaked transformer of the last lecture. Attention alternatives change the attention block to reach much longer contexts, mostly with linear rather than quadratic dependence on length; a mixture of experts changes the MLP, to get more parameters for the same compute. Context windows have grown quickly across vendors. The feed-forward cost grows linearly with length and attention, an all-to-all connection of all positions, quadratically, so attention takes over as contexts lengthen. Two tools control the cost: hybrids, for instance one global attention layer in eight with local layers between, and systems engineering. Constant factors matter: FlashAttention only rearranges the operation to move less memory, and in his plot it roughly doubles the speed over plain PyTorch and keeps running where the naive version no longer fits. That fixes nothing quadratic, so for contexts of millions of tokens something more radical is needed. In this book: Attention Alternatives and Mixture of Experts › 1. Constant factors come first · Attention Alternatives and Mixture of Experts › 2. Mix local and global layers.
5:14–8:00 Attention without the softmax: associativity#
After some false starts, recipes for linear-time attention have been battle-tested at scale in the last two years, which is why this is the first year he teaches them. One idea explains them all. Attention multiplies queries by keys, an all-to-all product with n² times the key dimension, normalizes with a softmax, and multiplies by the values. Drop the softmax and the parentheses move: the keys can be multiplied by the values first. The quadratic part is then the key dimension times the value dimension, thousands or tens of thousands, instead of n², with n in the millions. In this book: Attention Alternatives and Mixture of Experts › 3. Linear attention.
8:00–11:11 The same operation as a recurrent network#
The product of keys and values can also be built up incrementally: sweep left to right, add each token's contribution to a state, and multiply the state by the query. The dense form and this recurrent form are equivalent. A recurrent network carries a fixed-size state, which is ideal for inference but slow to train; here the dense form serves training and the recurrent form inference. The catch is that the operation is linear, hence weak. MiniMax M1, a strong open Chinese model, uses seven linear attention layers for each full softmax attention layer, and its cost grows mildly with length. Nobody has proven a fully linear-time model at scale: everything he covers in the next few slides is a hybrid. In this book: Attention Alternatives and Mixture of Experts › What the practitioners say.
11:11–14:00 Mamba-2: a gate on the state#
Start from the recurrent form of linear attention. Its problem is that the state always passes forward. LSTMs taught that a network must know when not to pass information on, so Mamba-2, of the Mamba family of state-space models, adds a gate. The gate depends only on the current input, not on the state, and decides how much of the old state to carry forward. Because it has no state dependence, the duality survives: the same layer can be computed in parallel for training or as a recurrence for inference. Nemotron 3 mixes Mamba-2 layers with occasional softmax attention, performs well against Qwen 3 and GPT-OSS, and keeps good throughput at long contexts, for a small open frontier model. In this book: Attention Alternatives and Mixture of Experts › 4. Add a state that can forget: Mamba-2 and Gated DeltaNet.
14:00–18:00 Gated DeltaNet: a second gate and a wiping term#
The rule of thumb: as long as every term of the recurrence is gated by input-dependent quantities only, the parallel and the serial form both exist. Gated DeltaNet is now among the most widely used state-space layers and was scaled up in Qwen 3.5. Mamba-2 also adds a residual-like term to its output, which is not core. Gated DeltaNet adds a second gate on the write: at zero, nothing of the current token enters the state, much like an LSTM's input gate. Its other idea gives it the "delta" in the name. When it writes the current key, it first removes, roughly, what the state already holds in that key's direction, with a term of the identity minus the gate times the key's outer product. Fast-weight programming and test-time training arrived at the same update from different principles. In this book: Attention Alternatives and Mixture of Experts › 4. Add a state that can forget: Mamba-2 and Gated DeltaNet.
18:00–22:54 Qwen 3.5, the controlled studies, and questions#
Qwen Next and Qwen 3.5, some of the best open models, use exactly this: three Gated DeltaNet layers per full attention layer. Qwen Next decodes much faster than Qwen 3 as context grows, at little cost in quality. Controlled studies are few. One, by a team at ByteDance Seed together with UC Santa Cruz, varies the number of recurrent layers: at low ratios there is no loss, past a point long-context performance degrades, and a pure recurrent model degrades clearly; single-key retrieval is a task these architectures optimize for explicitly, and question answering shows the same story. In questions he confirms that dropping the softmax is the only lossy step and that the equivalence between the two forms is exact. The extra output term of Mamba-2 acts like a residual connection, with a gate that controls how much of the current token passes through. In this book: Attention Alternatives and Mixture of Experts › What the practitioners say.
22:54–26:00 Sparse attention: select first, attend after#
Another family keeps the softmax. DeepSeek Sparse Attention, introduced with DeepSeek V3.2, has a lightweight indexer pick a small subset of the context and runs full attention on that subset only. The indexer scores each position from the query-key inner products, a ReLU and weights computed from the preceding tokens; the top k positions survive. Neither DeepSeek nor, by his account, GLM trains this from the start: the model is pretrained as a normal transformer, and the indexer is added during the long-context extension. V3.2 matched the frontier models of its day, among them Claude 4.5 Sonnet and Gemini 3, with better scaling of prefill and decoding than the earlier DeepSeek models. GLM 5, which he ranks among the best open models, adopted it too, with ablations that show little loss even on long-context retrieval, where recurrent models struggle. In this book: Attention Alternatives and Mixture of Experts › 5. Sparse attention.
26:00–32:35 Not linear, but cheaper#
This is not linear time. The indexer must score everything, so it is still quadratic in principle, but it can run in low precision and in a low-dimensional projection. The attention afterwards is quadratic in k, and k is chosen. The lesson is not to get stuck on quadratic against linear; constant factors count. In questions: the usual recipe is short-context pretraining, long-context extension and post-training, so the savings are bolted onto the extension stage, and it is surprising that a non-differentiable top k can be bolted on at all; k is bounded near the short-context length; he knows of no stability problem with this and expects it to help; low-precision attention is possible, though softmaxes are sensitive to underflow and overflow, which is one motivation for selecting cheaply and attending at full precision. On the future, he expects all these tricks thrown in together, with post-training that lets a model manage its own context by compaction and retrieval. In this book: Attention Alternatives and Mixture of Experts › 5. Sparse attention · Attention Alternatives and Mixture of Experts › Pitfalls.
32:35–34:23 The trade-off behind a fixed state#
Compared with softmax attention, the drawback of a state-space model is expressive power. The all-to-all connection is extremely strong and easy to train. State-space models caught on once the duality made them trainable in parallel, but one trade-off remains: a finite state loses information against carrying everything. There is no free lunch: a tiny state can hardly hold all of a long context, and a state as large as the context costs as much. In this book: Attention Alternatives and Mixture of Experts › The core idea.
34:23–39:45 More parameters for the same FLOPs#
Mixture of experts then takes over the rest of the lecture. Conceptually it changes nothing: it is a more efficient MLP. It is worth understanding because every large released model is one now, and because its building blocks, a top k and a balancing loss, appear in many other places. Replace the feed-forward network with several, say four, each of the usual size, and let some system pick one per input. The layer has four times the parameters and costs one network per forward and backward pass. That is the mental model: more parameters without more FLOPs. The reason for their popularity is that, at equal total compute, more sparse parameters keep giving better models. Plots from Fedus and colleagues in 2022 show the loss falling as experts are added with active parameters fixed, and better models at every training budget. The OLMo study found the same, with mixture-of-experts models reaching a dense model's quality in about half the training time. Released examples are far stronger than dense models with the same active parameters: DeepSeek's early mixture models matched or beat others on MMLU with far fewer active parameters. In this book: Attention Alternatives and Mixture of Experts › 6. Mixture of experts.
39:45–42:00 Another axis of parallelism, and who builds them#
Mixture of experts add an axis of parallelization: each expert is a natural chunk to place on its own device, with activations routed between devices. That is expert parallelism, for a later lecture. In the West the large open examples are Llama 4 and GPT-OSS, and releases have slowed. Much of the research and training happens in China, where Qwen, DeepSeek and MiniCPM did some of the earliest work: Qwen 1.5 MoE, with 2.7 billion active parameters, beat many 7-billion models of its time; that early proof of work, DeepSeek's as well as Qwen's, convinced the open-source community. On a question about communication between experts: it is paid in network traffic, so whether it is a net win depends on the topology. In this book: Attention Alternatives and Mixture of Experts › 6. Mixture of experts.
42:00–47:30 What makes them hard: sparsity during training#
Training is also sparse, and that is what makes experts hard. If all experts ran during training, the model would see which one is best for each input. It sees only the one or few that ran, yet must still learn to route, a problem with the flavour of a bandit, which practice solves with heuristics rather than reinforcement learning. Routing is per token, and routers are naive: a single matrix product, with no idea that a text is a medical question; a token that looks Japanese goes to expert seven. Sharding has an upper limit, since communication grows with the number of devices. DeepSeek's earlier papers ablate dense layers, hash routing and switch routing and are worth reading. Google pushed mixture of experts in 2022, yet they caught on only from 2024: the infrastructure is complex, the parameters hardly fit on one device, and training can blow up. Splitting attention into experts has been tried but is harder to tame. In this book: Attention Alternatives and Mixture of Experts › 6. Mixture of experts.
47:30–54:00 Three axes of design, and how to route#
Design varies along three axes: the routing function, the size and number of experts, and training. Routing always keeps a top k. A token can choose experts, an expert can choose its favourite tokens, or a global assignment can be computed. Nearly everyone uses token choice; the OLMo study shows it ahead of expert choice in validation loss and downstream scores, though expert choice trains too. The standard router is an inner product between the token and one vector per expert, as in the Switch Transformer, GShard, Grok, Mixtral, Qwen, DBRX and DeepSeek. Mysteriously, hashing the token and sending it to an expert by hash also brings gains, smaller ones; it is a baseline in papers, not used in deployment. Reinforcement learning, the theorist's natural answer to a bandit problem and tried by Bengio and colleagues in 2013, is rare, because of its overhead and randomness. Solving a linear assignment problem over all token-expert scores is exact but too expensive for scale. Top-k routing in equation form: a softmax over the experts gives scores, the top k survive and become the gates that weight each chosen expert's output. The gates are learned from inner products between a per-expert weight and the input. The same pattern appeared in the sparse attention indexer. In this book: Attention Alternatives and Mixture of Experts › 6. Mixture of experts.
54:00–58:00 Shared experts and fine-grained experts#
DeepSeekMoE introduced the design most models now copy. Some processing is common to all tokens, so the experts are cut into smaller pieces and a few of them are shared: always on, outside the router. In the classic design many experts were reusing their weights for that common modelling; a shared expert takes it over and lets the routed ones specialize. DeepSeek's ablation compares 16 large routed experts and no shared one, the GShard design, with fine-grained experts and one shared expert, and gains from both changes, with very large gains from the shared expert on TriviaQA and Natural Questions. OLMo disagrees in part: many fine-grained experts help, shared ones barely. Historically the first three mixture models came from Google, Mixtral, DBRX and Grok were early Western attempts, and DeepSeek V1's design became for experts what Llama's was for dense models. Qwen 3.5 and GLM use both. On a question: a shared expert brings no parallel savings; it can be copied to cut communication. In this book: Attention Alternatives and Mixture of Experts › 6. Mixture of experts.
58:00–63:00 Training: sparsity breaks the gradient#
He did not believe these could be trained well until he saw the tricks. Sparsity is needed at training time for efficiency, but then the routing decision is no longer differentiable and the unchosen experts' counterfactuals are never seen. Three solutions exist: reinforcement learning for the gating policy, stochastic perturbation, or heuristics that balance which experts receive tokens. Practice uses the third. The first two are worth knowing. Clark and colleagues in 2020 showed that reinforcement learning can learn routers, at the cost of gradient variance and complexity. The earliest mixture-of-experts paper, by Shazeer and colleagues, added noise scaled by the input to the routing scores before the top k, so that near-tied experts are explored at random. Fedus and colleagues added a uniform multiplicative jitter to harden experts, later removed: ablations show that doing without these stochastic tricks helps both stability and final quality. In this book: Attention Alternatives and Mixture of Experts › 6. Mixture of experts.
63:00–66:00 Expert collapse, and the balancing loss#
Plain gradient descent makes the rich richer. The strongest of the chosen experts gets more signal, its weight grows, it is chosen more, and it takes everything: expert collapse, or starvation. The fix is a loss added to the modelling loss that balances tokens across experts. The Switch Transformer version multiplies, for each expert, the fraction of tokens dispatched to it by the router's total probability mass on it. He does not derive the objective; he reads its derivative with respect to the probability mass, which equals the fraction of tokens received. So the gradient pushes down popular experts in proportion to their popularity. In this book: Attention Alternatives and Mixture of Experts › 6. Mixture of experts.
66:00–71:45 Balancing by device, and what happens without it#
DeepSeek V1 and V2 can be reconstructed from these pieces: gradients are pumped straight through, ignoring non-differentiability, and the Switch Transformer loss is added per expert. DeepSeek, sharp on systems, also balances per device, so that two machines of four experts each, in his example, run at full utilization. V3 replaces some of these losses with a per-expert bias updated online, though some auxiliary loss remains against extreme imbalance. OLMo's ablation shows what removal costs: losses rise, and almost all tokens go to two experts while the rest do nothing; with the loss, every expert is used. That such a crude object trains well surprises him: reinforcement of useful experts is cancelled out by the evening-out of expert use. The same pairing of a top k with an auxiliary loss appears in H-Net, an attempt to remove tokenizers, and he expects it in future architectures. On questions: experts do specialize by token type, punctuation or non-English characters, but with no semantics, no newspaper-domain expert; the per-device loss matters because the per-expert loss should not be pushed to full uniformity, which hurts training. In this book: Attention Alternatives and Mixture of Experts › 6. Mixture of experts · Attention Alternatives and Mixture of Experts › Pitfalls.
71:45–76:00 The systems side#
Data parallelism stops at the batch size and model parallelism where the model has no natural cuts; expert parallelism adds a third axis. Several experts on one GPU could be many small matrix products, which waste the hardware. Instead the computation maps onto the structured sparse matrix products that GPUs support natively, block-diagonal being the simplest: a hardware co-design. A recent trick from Nemotron 3: the residual stream is projected down before activations are sent to routed experts, which saves communication, while the shared expert, never communicated, stays large. Last, stochasticity. In naive infrastructure a popular expert's queue grows until tokens are dropped, earlier code returned zeros silently, and a user's result could depend on other users' queries. Dropless architectures, as in MegaBlocks, have removed the problem. In this book: Attention Alternatives and Mixture of Experts › 6. Mixture of experts · Parallelism › 6. The rest.
76:00–80:00 Stability and fine-tuning#
Routing adds yet another softmax, with an exponential and a division. Zoph and colleagues wrote a whole paper on stability in early Google mixture models. Sensitive parts such as the router are often kept in float32, and a z-loss on the router helps; OLMo's curves turn spiky without it. Mixture models also overfit badly when fine-tuned on a small dataset: training and validation loss separate far more than for a dense model, on a GLUE task in his plot. The fixes are to fine-tune only the attention or only the non-expert layers, or to use far more data, his example being 1.4 million examples, and retrain the experts as well. In this book: Attention Alternatives and Mixture of Experts › What the practitioners say.
80:00–1:28:00 Upcycling, the DeepSeek line, and a summary#
Upcycling copies a trained dense model, replicates its MLPs as experts, adds a randomly initialized router and continues training; the copies then specialize. MiniCPM grew a 2.4-billion model into one of 13.4 billion this way, and an early Qwen model was upcycled from the 1.8-billion model to 2.7 billion active parameters. He has seen no upcycled model in the lecture year: nobody trains a dense model first any more. The DeepSeek line is a lesson in evolution. V1 already has shared and fine-grained experts, top-k routing and a balancing loss, the platonic ideal of a mixture model. V2 scales it up with two shared experts and adds losses that balance devices and communication, evidence that successful training respects systems. V3 keeps the design with loss-free balancing and a different weighting of the experts. It also has multi-head latent attention, which produces a low-dimensional latent vector per token and derives queries, keys and values from it, so only the latent is cached; it conflicts with RoPE, which is why some dimensions stay non-latent to encode position. And multi-token prediction predicts several tokens at once, which builds in a speculative decoder; Liang's inference lecture covers that, and the idea has not caught on. His summary: sparsity gives more parameters than are paid for; routing looked impossible, and very simple things work at scale; mixture of experts are here to stay. In this book: Attention Alternatives and Mixture of Experts › What the practitioners say · Inference › 3. Shrink the KV cache · Inference › 6. Check instead of generate: speculative sampling.
What to take away#
- Removing the softmax from attention lets keys multiply values first, which turns attention into a recurrence with a fixed-size state; Mamba-2 adds a forget gate and Gated DeltaNet a write gate and a wipe along the key's direction.
- No fully linear-time model has been proven at scale: the recurrent models he shows are hybrids, such as three recurrent layers per full attention layer, and a pure fixed state loses long-context recall.
- Sparse attention keeps the softmax but scores everything cheaply and attends to only the top k tokens; top k is not linear, and constant factors still count.
- A mixture of experts buys parameters without FLOPs; token-choice top-k routing, shared plus fine-grained experts and a load-balancing loss are the consensus design.
- The cost is systems: communication for expert parallelism, a router softmax to stabilize, and overfitting when the experts are fine-tuned.
Sources#
- Tatsu Hashimoto and the course staff, "Attention alternatives and mixture of experts", Stanford CS336 Language Modeling from Scratch, Spring 2026: video.
- Course page: https://cs336.stanford.edu/.