LLMModule 08 · Stage 03

Next-gen architectures: MoE, state-space models, linear & ring attention

Standard attention costs grow with the square of the sequence length, and dense models pay for every parameter on every token. This stage covers the four main ways around that: route each token to a few experts, replace attention with a recurrent state, make attention linear, or spread one long sequence across many GPUs.

PrerequisitesStage 01, a working Transformer (06 Day 14), basic RNNs
Time20–30 h (reading 8–10 h, MoE project 10–15 h, SSM notebook 4–6 h)
HardwareLaptop for the reading and demo · Colab GPU (T4 or better) for the MoE project · multi-GPU only for the full version
Key papersShazeer et al. 2017 · Fedus et al. 2021 (Switch) · Gu et al. 2021 (S4) · Gu & Dao 2023 (Mamba) · Katharopoulos et al. 2020 · Liu et al. 2023 (Ring Attention)

Source: Suraj Sharma, X post, stage 3 · MoE routing at frontier scale and linear attention (KDA) are covered in depth in Module 05. This page links to it and focuses on what's new.

Start here (no maths needed)

Big AI models are slow because every part of the model works on every word, and every word looks back at every other word. New designs let only a few parts work at a time, or keep a short summary instead of rereading everything.

Think of it like this

Think of a big hospital. A patient doesn't see every doctor. A receptionist sends them to the one or two specialists who fit their problem. That's a mixture of experts. But if the receptionist sends everyone to the same doctor, that doctor gets a huge queue and the others sit idle. So the receptionist gets a rule: spread people out. That's load balancing.

Now think of reading a long book. One way is to flip back through every earlier page each time you read a new sentence. That gets slower and slower. Another way is to keep a small notebook of what matters and update it as you go. That's a state-space model: a fixed-size memory, updated one step at a time.

How it works

  1. Experts: a model has many small "expert" blocks. A tiny router picks one or two of them for each word.
  2. Balancing: during training, an extra penalty punishes the router if it keeps choosing the same experts.
  3. Notebook memory: a state-space model reads words in order and keeps a fixed-size summary, so long texts cost the same per word.
  4. Sharing the reading: ring attention splits a very long text across many computers sitting in a ring. They pass their pages round the ring until everyone has seen everything.

Why robots care

A robot's camera sends new pictures many times a second, for hours. A model that has to look back at every past picture gets slower the longer the robot runs. A model with a small, fixed notebook memory runs at the same speed whether the robot has been on for a minute or a day.

Try it

Words to know

Expert
One of many small sub-networks. Only a few are used for each word.
Router
The tiny part that decides which experts each word goes to.
Load balancing
Making sure work is spread evenly across experts.
State
A fixed-size memory that gets updated as each new word arrives.
Context length
How much text the model can look at in one go.

Going deeper: everything below is the full version, with some maths. On a first read, skim the headings, try the demo, and read the reality check.

1. What this stage covers

TL;DR

Two different costs limit Transformers. Width cost: a dense model uses every weight for every token. Mixture-of-experts layers decouple total parameters from per-token compute, at the price of routing, load balancing and communication. Length cost: attention is O(L²) in compute and its KV cache grows with L. State-space models and linear attention swap the growing cache for a fixed-size recurrent state. Ring attention keeps exact attention but spreads the sequence across devices. In 2026 the frontier mostly uses MoE plus a hybrid of cheap recurrent layers and a few full-attention layers, not a clean replacement of attention.

2. Concepts, explained

Mixture-of-experts routing and the auxiliary load-balancing loss

An MoE layer replaces the Transformer's single feed-forward block with E expert feed-forward blocks and a router. The router is a linear layer that gives each token a score per expert. The token goes to its top-k experts, and their outputs are summed, weighted by the router's gate values. Shazeer et al. (2017, "Outrageously Large Neural Networks") made this work at scale with a noisy top-k gate between LSTM layers. Switch Transformer (Fedus, Zoph & Shazeer, 2021) simplified it to top-1: one expert per token, less compute and less communication, and reported up to 7× faster pre-training than a dense T5 baseline at the same compute.

The failure mode is collapse. Early in training, a few experts get slightly better, so the router sends them more tokens, so they get better still. The rest starve. Switch's fix is an auxiliary loss added to the training loss:

f_i = fraction of tokens in the batch whose top-1 choice is expert i     (hard counts)
P_i = mean router probability for expert i over the batch               (soft, differentiable)

L_aux = α · E · Σ_i f_i · P_i          α ≈ 0.01 in the Switch paper

uniform routing:     f_i = P_i = 1/E   →  E · Σ f_i P_i = 1   (the minimum)
total collapse:      f_1 = P_1 ≈ 1     →  E · Σ f_i P_i ≈ E

Why both f and P? The counts f aren't differentiable, but the probabilities P are. Multiplying them means the gradient pushes down the probability of experts that are already overloaded. The factor E keeps the loss scale the same whatever the number of experts.

Capacity factor. For efficient batched kernels each expert gets a fixed number of slots: capacity = (tokens / E) × capacity_factor. Tokens routed to a full expert are dropped: they skip the layer and pass through on the residual connection only. A capacity factor above 1 leaves headroom for imbalance but wastes slots and memory when routing is balanced. The demo below shows both effects.

What Module 05 adds. The auxiliary loss is a trade-off: too weak and experts collapse, too strong and it fights the language-modelling loss. Newer models often drop it in favour of a per-expert bias that only affects selection. Module 05's routing deep dive explains that approach and Kimi K3's Quantile Balancing for 896 experts, with its own demo. Read it after this section.

Interactive: Switch-style load balancing and capacity

512 tokens, top-1 routing. Bars: fi, the share of tokens each expert receives (accent) and Pi, its mean router probability (muted). The dashed line is each expert's capacity. Token logits are random per token plus a fixed per-expert "popularity" scaled by Router skew (seeded, so results are repeatable).

E · Σ f·P
–
L_aux (α = 0.01)
–
Tokens dropped
–
Empty slots
–

Try this: at skew 0 the loss sits close to its minimum of 1 and only a few tokens drop. At skew 3 the loss climbs and a large share of tokens is dropped even at capacity factor 2. The loss can never go below 1, and it reaches E only if every token goes to one expert.

State-space models: S4 and Mamba

A state-space model comes from control theory, which is why it feels familiar to roboticists. A continuous input u(t) drives a hidden state x(t) of size N, and the output reads from the state:

continuous:   x'(t) = A x(t) + B u(t)        y(t) = C x(t)
discretised:  x_k = Ā x_{k-1} + B̄ u_k        y_k = C x_k      (Ā, B̄ from A, B and a step size Δ)

as a convolution (when A, B, C don't depend on the input):
  y = K * u,   K = (C B̄, C Ā B̄, C ² B̄, …)

The same layer has two forms. For training, compute the kernel K once and apply it as a long convolution over the whole sequence, which parallelises well (via FFT). For generation, run the recurrence: one fixed-size state update per token, no growing cache.

S4 (Gu, Goel & Ré, 2021) made this work for long sequences. Two ingredients: initialising A from HiPPO theory, so the state stores a compressed history of the input, and a structured parameterisation of A that makes computing K fast. S4 did very well on the Long Range Arena benchmark, including tasks with sequences of thousands of steps that Transformers struggled with.

Mamba (Gu & Dao, 2023) fixed S4's weakness on language. In S4, A, B, C and Δ are the same for every token, so the model can't decide to remember this token and ignore that one. Mamba makes B, C and Δ functions of the current input. This is the "selective" SSM. A large Δ means "reset and take in this token"; a small Δ means "ignore it and keep the state". The cost: with input-dependent parameters there's no single kernel K, so the convolution trick is gone. Mamba instead uses a hardware-aware parallel scan that keeps the expanded state in fast on-chip memory. The paper reports about 5× higher inference throughput than Transformers and a 3B model that matches Transformers twice its size. A follow-up, Mamba-2 (Dao & Gu, 2024), showed a close mathematical link between selective SSMs and a form of linear attention.

Linear attention

Softmax attention computes softmax(QKᵀ)V, which needs the full L×L score matrix. Katharopoulos et al. (2020, "Transformers are RNNs") replaced the softmax with a feature map φ and used associativity:

softmax attention:   o_t = Σ_{s≤t} exp(q_t·k_s) v_s / Σ_{s≤t} exp(q_t·k_s)        O(L²)
linear attention:    o_t = φ(q_t)ᵀ S_t / φ(q_t)ᵀ z_t
                     S_t = S_{t-1} + φ(k_t) v_tᵀ     (a d×d matrix state)
                     z_t = z_{t-1} + φ(k_t)                                       O(L)

The causal version is literally an RNN with a matrix-valued state. That is the same shape as an SSM, which is why the two families have merged. Plain linear attention only adds to its state and never forgets, so it degrades on long text. Modern variants add decay (gating) and the delta rule, which overwrites old associations instead of piling new ones on top. Kimi Delta Attention is one such variant. Module 05's length deep dive explains it and why K3 still keeps one full-attention layer in four.

Ring attention

Ring attention (Liu, Zaharia & Abbeel, 2023) attacks a different problem. It doesn't change what attention computes. It keeps exact softmax attention and spreads the memory across devices.

  1. Split a sequence of length L into D blocks, one per device. Each device keeps its own query block.
  2. Each device computes attention between its queries and the key/value block it currently holds, using the blockwise "online softmax" trick (keep a running max and running sum, as in FlashAttention), so partial results can be combined exactly.
  3. Each device passes its K/V block to the next device in the ring and receives one from the previous device.
  4. After D steps every query block has seen every K/V block. The send for the next step overlaps with the compute of the current one, so if each block is big enough, communication is hidden.
per-device activation memory  ∝ L / D        (one block of Q, K, V at a time)
total attention compute       ∝ L²           (unchanged: it's still exact attention)
max context                   ≈ D × (what one device can hold)

The paper's title says "near-infinite". The honest reading: context grows linearly with the number of devices, and the paper reports sequences of millions of tokens. The total compute is still quadratic. Ring attention is a training and long-prefill tool for clusters. It does nothing for a single GPU.

3. The practice project

(a) Laptop / Colab version: a Switch MoE in a tiny GPT

  1. Start from a small character-level GPT (nanoGPT-style): 4 layers, dmodel = 256, context 256, on Tiny Shakespeare. Train it dense as the baseline.
  2. Swap the feed-forward block in every other layer for the MoE layer below, with E = 8 experts, top-1, each expert the same size as the dense feed-forward block. Active compute per token stays roughly the same; total parameters in those layers grow about 8×.
  3. Train three variants for the same number of steps: dense; MoE with α = 0; MoE with α = 0.01.
  4. Measure: validation loss against steps; tokens per second (forward + backward, after warm-up, with torch.cuda.synchronize() around the timer); per-expert load histogram every 200 steps; fraction of dropped tokens.
  5. Repeat at capacity factor 1.0 and 1.5.
import torch, torch.nn as nn, torch.nn.functional as F

class SwitchMoE(nn.Module):
    def __init__(s, d, h, E, cf=1.25):
        super().__init__()
        s.E, s.cf = E, cf
        s.router = nn.Linear(d, E, bias=False)
        s.w1 = nn.Parameter(torch.randn(E, d, h) * d**-0.5)
        s.w2 = nn.Parameter(torch.randn(E, h, d) * h**-0.5)

    def forward(s, x):                       # x: (B, T, d)
        B, T, d = x.shape
        x = x.reshape(-1, d)
        p = F.softmax(s.router(x), -1)        # (N, E)
        gate, idx = p.max(-1)                # top-1
        f = F.one_hot(idx, s.E).float().mean(0)
        aux = s.E * (f * p.mean(0)).sum()    # Switch loss, multiply by α outside
        cap = int(s.cf * x.shape[0] / s.E)
        out = torch.zeros_like(x)
        for e in range(s.E):                 # simple loop, fine for E=8
            sel = (idx == e).nonzero().squeeze(-1)[:cap]   # drop overflow
            h = F.gelu(x[sel] @ s.w1[e])
            out[sel] = gate[sel, None] * (h @ s.w2[e])
        return out.reshape(B, T, d), aux

What to expect, honestly. With α = 0 you should see the load histogram skew, sometimes badly, and dropped tokens rise. With α = 0.01 the loads should stay much flatter. On loss per step, the MoE will usually match or beat the dense baseline, since it has more parameters at similar compute. On tokens per second, the MoE will very likely be slower than dense at this size. The Python loop, the gather/scatter and the small per-expert matmuls dominate. That's a real finding, not a bug: MoE throughput wins need grouped-matmul kernels and large batches.

(b) The full version from the post

Benchmarking MoE throughput "against a dense transformer" properly means a GPT-2-scale or larger model, many experts (16–64), and expert parallelism: experts live on different GPUs and tokens move with an all-to-all collective. Use an existing kernel library (for example MegaBlocks-style grouped/block-sparse matmuls) rather than the loop above. Compare against two baselines: a dense model with the same active parameters (same FLOPs per token) and one with the same total parameters. Report tokens/s, loss at fixed tokens, peak memory and all-to-all time from a profiler. Hardware: one multi-GPU node is enough to see the communication cost. Cost scales with tokens trained; estimate it with the 6 × Nactive × D FLOPs rule from Day 25 before renting anything.

(c) Pitfalls

4. Reality check

The post's claim: quadratic attention is being replaced. Half true.

5. In this course

6. Why it matters for robotics

7. Self-check

Why does the Switch auxiliary loss multiply fi by Pi instead of using fi alone?

fi comes from a hard argmax count, so it has no gradient. Pi is a mean of softmax probabilities and is differentiable. The product lets gradients reduce the probability mass on experts that are already receiving many tokens.

With E experts and perfectly uniform routing, what is E·Σ fiPi? And with total collapse?

Uniform: E · E · (1/E)(1/E) = 1, the minimum. Total collapse onto one expert with probability near 1: about E.

What happens to a token routed to an expert that's already at capacity?

It's dropped from that layer: the expert doesn't process it and it continues only through the residual connection. Raising the capacity factor reduces drops but wastes slots and memory.

Why can S4 train with a convolution but Mamba can't?

In S4, Ā, B̄ and C are the same at every step, so the output is a fixed kernel convolved with the input. Mamba makes B, C and Δ depend on each token, so there's no single kernel. It uses a parallel scan instead.

Does ring attention make attention cost linear in sequence length?

No. Total compute is still quadratic. It divides activation memory across D devices, so maximum context grows roughly D times, and it hides communication behind computation.

Why do hybrid models keep some full-attention layers?

A fixed-size state must compress the past, so it loses exact recall of arbitrary earlier tokens. A few global-attention layers restore precise retrieval while the cheap layers handle most of the depth.

8. Courses & content

ResourceTypeUse it for
Stanford CS336 lecturesUniversity course (free materials)Architecture variants and mixture of experts
Hugging Face · Mixture of Experts ExplainedBlog guideRouting, load-balancing loss, capacity factor
A Visual Guide to Mixture of ExpertsIllustrated guideMoE intuition with diagrams
A Visual Guide to Mamba and State Space ModelsIllustrated guideFrom RNNs to S4 to Mamba's selective scan
The Annotated S4Annotated codeS4 implemented step by step
Stanford CS25 · Transformers UnitedSeminar talks (free)Talks from the people building new architectures

Start with the Hugging Face MoE guide: it maps directly onto the practice project. Then do the Annotated S4 for the SSM half.

Full course map for all 12 stages →

9. Papers & docs