Attention Alternatives, Mixture of Experts
Tatsu covers two advanced architecture ideas layered on top of the basic transformer. First, attention alternatives that trade the quadratic cost of softmax attention for near-linear cost — linear attention and its RNN duality, gated variants like Mamba-2 and gated delta net used in hybrids, and DeepSeek's sparse attention. Second, mixture of experts, which buys more parameters without more FLOPs by routing each token to a few experts, tamed in practice by top-k routing and load-balancing losses.
Why attention gets expensive, and the basic toolkit
Everyone wants longer context — more knowledge packed in, agents operating over more state — and if you plot context window size against release date on a log scale, there’s a clear rush by the top vendors toward millions of tokens. The problem is cost. Split a transformer layer’s compute into the feed-forward part and the attention part and watch what happens as the sequence grows: feed-forward starts large but grows linearly; attention is an all-to-all interaction between positions, so it grows quadratically and quickly outpaces everything else. At short sequence lengths feed-forward dominates; at long ones, attention is the whole problem.
There are two cheap ways to fight this before changing the math. The first is to combine local attention with occasional global attention — if you do full global attention only once every eight layers and keep the rest local, you have controlled the cost while keeping some long-range mixing. The second is pure systems engineering, and Tatsu is emphatic that this is underappreciated: “constant factors really, really matter.”
But if you want 5–10 million tokens, constant factors aren’t enough. You want a genuinely milder dependence on sequence length.
Linear attention and the RNN in disguise
Standard attention is , with and . The product is what costs , and is the millions-long context. Now forget the softmax for a moment — pretend it’s the identity. Then multiplication is associative, and you can move the parentheses:
That single re-grouping changes which factor is quadratic. Instead of you pay . The key and value dimensions can be large in principle, but they’re usually thousands to tens of thousands — nobody has a million hidden coordinates — so depending on instead of is a huge win.
The re-grouped form has a second gift. The right-hand product, read incrementally as you sweep left to right, looks exactly like an RNN with a fixed-size state :
Unlike the lossy softmax-dropping step, this equivalence between the linear form and the recurrent form is exact. Minimax M1, a large high-performance open model, uses a 7-to-1 hybrid — seven linear-attention layers per one full softmax layer — and stays competitive with models like O3 and DeepSeek-R1 while scaling much more gently in context length. No one has yet proven out fully linear attention at scale; everything that works is a hybrid.
Making the recurrence expressive: gating, and a sparse alternative
Plain linear attention feels too naive, so people elaborate the recurrence — and the rule of thumb is that as long as the new terms are input-dependent (functions of ) and not state-dependent, the parallel/serial duality survives.
Mamba-2 adds a gate. Linear attention always passes the whole state forward; Mamba-2 modulates it, with , borrowing the LSTM lesson that knowing when to forget matters. (It also adds a residual pass-through to the output, which isn’t core.) Nemotron-3 uses a roughly 3-to-1 Mamba-2 / attention hybrid and gets good throughput at long context.
Gated delta net pushes further with a second gate — a “no-input” gate that, at , refuses to write the current token into the state — plus a delta update:
The blue acts like a projector that erases previous information in the direction of the current key before writing the new key in — not just adding, but clearing out. The same update has been reinvented from meta-learning least-squares, fast weight programming, and test-time training. Qwen 3.5 and Qwen Next use a 3-to-1 gated delta net / attention hybrid with strong decoding throughput as context grows.
A controlled study (ByteDance Seed and UC Santa Cruz) sweeps the hybrid ratio: at low ratios of RNN-style layers there’s basically no hit, but past a point long-context retrieval and QA degrade, ending badly at a pure RNN. The all-to-all softmax connection is expressive in a way a finite state can’t fully replace.
A completely different attack is DeepSeek Sparse Attention (DSA). Instead of attending to all tokens, a lightweight “lightning indexer” scores each preceding token, , and full attention runs only on the top- selected tokens. This isn’t linear time — the indexer still does all-to-all inner products — but the indexer can be tiny (low precision, low dimension), and the expensive full attention runs on a small bounded subset. Better still, you can bolt it on after dense short-context pretraining, during the long-context extension stage. DeepSeek v3.2 and GLM-5 both do this and lose almost nothing versus full attention. The top- selection idea returns immediately in the second half of the lecture.
Mixture of experts: more parameters, same FLOPs
Conceptually MoEs don’t change the game — a mixture of experts is just a more efficient MLP. Take the feed-forward network and replace it with several feed-forward networks plus a selector that picks which one(s) each input uses. If you have four experts but activate one per token, you have 4× the FFN parameters but pay only one FFN’s worth of compute per forward or backward pass.
Why is this everywhere now? Because for fixed compute, more sparse parameters just keeps helping. Fedus et al. (Switch Transformer, 2022) show test loss dropping monotonically from 1 expert to 256 experts at constant active parameters; OlMoE shows an MoE training roughly 2× faster than its dense counterpart to the same loss; and on the activated-parameter axis that governs inference cost, released MoEs like DeepSeek-V2 sit well above dense models of the same active size. MoEs also open a new parallelism axis — each expert is a natural chunk you can place on its own device (expert parallelism) — at the cost of shipping activations between devices, a comms/compute trade-off explored in the systems lecture.
Designing the router and the experts
Three things vary: the routing function, the expert sizes, and the training procedure.
For routing, almost everyone does token-choice top-: each token picks its favorite experts. The alternatives — expert-choice (each expert picks tokens), global assignment via a linear-assignment solver, hashing, and RL-learned routes — all exist, but token-choice gets lower validation loss than expert-choice (per OlMoE), hashing is a common baseline that’s never deployed, global assignment is too expensive at scale, and RL is the theoretically “correct” bandit framing (Bengio 2013) that loses on gradient variance and overhead. The standard DeepSeek v1–v2 router is barely more than a softmax:
g_{i,t} = \begin{cases} s_{i,t}, & s_{i,t} \in \text{Topk}(\{s_{j,t}\}, K) \\ 0, & \text{otherwise}\end{cases}$$ with gates $s_{i,t} = \text{Softmax}_i(u_t^{l\top} e_i^l)$ — an inner product between the input and a learned direction per expert. (Some models, like Mixtral, DBRX, and DeepSeek v3, apply the softmax *after* the top-$k$ selection instead of before.) <Definition term="Shared and fine-grained experts"> DeepSeekMoE's now-standard design. Cut the experts into many smaller (fine-grained) chunks, and make a few of them **shared experts** that are always on and bypass the router entirely. The shared experts absorb common processing every token needs, freeing the routed experts to specialize. DeepSeek's ablations show both fine-grained segmentation and shared isolation help (especially TriviaQA, NaturalQuestions); OlMoE agrees that fine-grained helps but finds shared experts don't add much. Recent MoEs run anywhere from 8 to 256 routed experts with 1–2 active per token and 0–2 shared. </Definition> ## Training MoEs: heuristics that shouldn't work but do Here's the hard part. We need sparsity for training-time efficiency, but a sparse top-$k$ gating decision isn't differentiable, and we never observe the experts we *didn't* pick — an RL-bandit-flavored problem. There are three families of fixes: RL to optimize the gating policy, stochastic perturbations (inject noise so near-ties get explored, as in the original Shazeer 2017 MoE), and a pile of heuristic **balancing losses**. In practice, everyone uses the heuristics — the stochastic tricks were even removed in later Google work with no harm. The reason you need balancing is expert collapse. Route with plain gradient descent and the strongest experts get more signal, get stronger weights, get selected more often, and run away with everything while the rest starve. So you add an auxiliary loss that evens out the token distribution. <Theorem name="The load-balancing loss"> The Switch Transformer loss over $N$ experts and a batch of $T$ tokens is $\text{loss} = \alpha \cdot N \cdot \sum_{i=1}^{N} f_i P_i$, where $f_i$ is the *fraction of tokens dispatched* to expert $i$ and $P_i$ is the *router probability mass* assigned to it. The objective itself isn't obvious, but its gradient is: $\partial/\partial P_i$ is proportional to $f_i$, so the more tokens an expert already gets, the harder its probability mass is pushed down. It is a proportional penalty on popularity. DeepSeek adds a second copy of the same loss aggregated *per device*, so all machines stay evenly utilized; DeepSeek v3 replaces most of it with a per-expert bias tuned by online learning ("auxiliary- loss-free balancing"), though a small sequence-wise aux loss still remains. </Theorem> OlMoE's ablation makes the stakes concrete: remove the load-balancing loss and training loss climbs, validation loss climbs, and nearly all tokens funnel into two experts — the rest are dead weight for most of training. With the loss, utilization is even and every expert works. Two more MoE-specific hazards. Stability: the router adds yet another softmax, and exponentials are a numerical danger zone (a 0.5 roundoff in bf16 can shift a softmax output by 36%), so the fix is to run just the router in fp32, often with a **z-loss** $L_z(x) = \frac{1}{B}\sum_i\big(\log\sum_j e^{x_j^{(i)}}\big)^2$ to keep logits from blowing up — OlMoE's loss curves are visibly spikier without it. Fine-tuning: sparse MoEs overfit small datasets badly (huge train/val gap), so people fine-tune only the non-MoE layers or attention, or just use a lot of data (DeepSeek's 1.4M-example SFT set). A historical trick, **upcycling** — copy a trained dense model's MLP into many experts and continue training — gave early wins (MiniCPM, Qwen 1.5-MoE) but has faded now that people just train MoEs from scratch. And DeepSeek v3 folds in two orthogonal ideas worth knowing: multi-head latent attention (MLA), which caches a low-dimensional latent instead of full K and V, and multi-token prediction (MTP), which doubles as a built-in speculative decoder. <KeyTakeaways> - Attention cost is quadratic in sequence length; local/global hybrids and flash attention (a constant-factor systems win) help, but linear attention changes the asymptotics by dropping the softmax and applying associativity: $(QK^\top)V = Q(K^\top V)$. - Linear attention has an exact RNN form, giving a duality — train in the dense parallel form, infer in the serial fixed-state form; Mamba-2 and gated delta net add input-dependent gates that preserve this duality, and both are used only in hybrids with full attention. - DeepSeek sparse attention keeps full attention but runs it on a top-$k$ subset chosen by a cheap indexer — not linear time, but a small constant factor, bolt-on during long-context extension. - A mixture of experts replaces the MLP with many expert FFNs and a router, buying more parameters at fixed FLOPs; token-choice top-$k$ routing plus shared and fine-grained experts (DeepSeekMoE) is the standard design. - Sparse routing is non-differentiable, so training relies on heuristic load-balancing losses that penalize popular experts proportionally, preventing expert collapse; without them, a couple of experts dominate and the rest die. - MoE stability needs an fp32 router and often a z-loss; fine-tuning risks overfitting, handled by tuning non-MoE layers or using lots of data. </KeyTakeaways> ## Check yourself Conceptual and back-of-envelope exercises in the spirit of the lecture — no assignment code. <Problem number="4.1" source="linear-attention FLOP saving"> For a sequence of $n = 10^6$ tokens with $d_k = d_v = 128$, compare the dominant FLOP cost of standard attention's $QK^\top$ against linear attention's re-grouped $Q(K^\top V)$. Roughly what factor do you save, and why doesn't the saving depend on making $d_k, d_v$ small? <div slot="solution"> Standard: the $QK^\top$ term scales like $n^2 d_k = (10^6)^2 \cdot 128 \approx 1.3\times10^{17}$. Linear: $Q(K^\top V)$ scales like $2 n d_v d_k = 2\cdot 10^6 \cdot 128 \cdot 128 \approx 3.3\times10^{10}$. The ratio is about $4\times10^{6}$ — roughly the factor $n^2 / (2 d_v d_k)$. The saving comes from removing the $n^2$ dependence, not from shrinking the hidden dims: with $n$ in the millions and $d$ in the hundreds-to-thousands, $n^2$ dwarfs $d_v d_k$ regardless. The catch is that the win requires dropping the softmax, which is the lossy step. </div> </Problem> <Problem number="4.2" source="duality reasoning"> A colleague trains a pure linear-attention model using the serial recurrent form $S_t = S_{t-1} + k_t v_t^\top$, looping over the sequence, and finds training painfully slow. What should they do, and why is it valid? <div slot="solution"> Train with the dense parallel form $Q(K^\top V)$ instead. The serial loop has a sequential dependency through $S$ that can't be parallelized across time, which is exactly the classic RNN training bottleneck; the dense matmul form has no such dependency and saturates the hardware. It is valid because the linear form and the recurrent form are *mathematically exact* equivalents — this is the duality. Reserve the serial form for inference, where its fixed-size state $S$ (no growing KV cache) is the advantage. </div> </Problem> <Problem number="4.3" source="MoE parameter vs FLOP accounting"> An MoE layer has 64 routed experts, activates the top 2 per token, and each expert is the same size as the dense FFN it replaces. Relative to that dense layer, what happens to (a) the FFN parameter count and (b) the per-token FFN FLOPs? Why is this the whole appeal? <div slot="solution"> (a) Parameters scale with the *total* number of experts: 64× the dense FFN's parameters. (b) FLOPs scale with the *active* experts: top-2 means 2× the dense FFN's per-token FLOPs (and if $k=1$, exactly 1×). The appeal is precisely this decoupling — parameter count grows with the number of experts while compute grows only with $k$ — so you get the modeling benefit of far more parameters at nearly fixed FLOPs, which is why fixed-compute test loss keeps dropping as you add experts. </div> </Problem> <Problem number="4.4" source="load-balancing gradient"> Explain, via its gradient, why the Switch load-balancing loss $\alpha N \sum_i f_i P_i$ prevents expert collapse. What failure mode appears if you drop it entirely? <div slot="solution"> $f_i$ is the fraction of tokens dispatched to expert $i$ (effectively constant with respect to the router's continuous outputs) and $P_i$ is the router's probability mass on expert $i$. The derivative with respect to $P_i$ is proportional to $f_i$, so an expert already receiving many tokens gets a large negative gradient on its probability mass — a penalty proportional to its popularity that pushes it back down. This counteracts the rich-get-richer loop where selected experts strengthen and get selected even more. Drop it and you get expert collapse: OlMoE's ablation shows almost all tokens routing to two experts while the rest stay unused, and both training and validation loss get worse. </div> </Problem> <Problem number="4.5" source="sparse-attention classification"> DeepSeek sparse attention runs full attention over only the top-$k$ tokens chosen by a lightweight indexer. Is the overall mechanism linear time in sequence length $n$? Where does the real cost saving come from, and what makes bolting it on cheap? <div slot="solution"> No — it is not linear time. The indexer must compute $q\cdot k$ inner products against all preceding tokens to know what to select, which is inherently all-to-all (quadratic), and the subsequent full attention is quadratic in $k$. The saving is a *constant-factor* one: the indexer is made very cheap (low precision like FP8, lower-dimensional projections), and the expensive full attention runs on a small bounded subset $k$ rather than the whole context. It's cheap to add because you don't train it from scratch — you train a normal dense short-context transformer, then drop the indexer in during the long-context extension stage you were going to run anyway. </div> </Problem>