| Sequence layer | |
|---|---|
| input of a sequence layer at position | |
| output of a sequence layer at position | |
| Jacobian of the output at position with respect to the input at position (the lecture writes ) | |
| sequence length | |
| model width, the size of each position's vector (512 in the course's models) | |
| Recurrent cells | |
| hidden state of a recurrent layer after reading position ; in the tanh RNN | |
| preactivation of the tanh RNN, | |
| input weights of the RNN, applied to the input in | |
| recurrent weights of the RNN, applied to the previous state at every step | |
| bias of the RNN preactivation | |
| bound on the absolute value of the activation's derivative (1 for tanh, 1/4 for the sigmoid) | |
| largest singular value of a matrix, its operator norm | |
| LSTM memory cell, ; in the residual-in-time RNN, the tanh candidate in | |
| LSTM candidate write, scaled by the input gate before it is added to the cell | |
| LSTM input gate in , which scales the candidate write | |
| LSTM forget gate, which scales the old cell in | |
| LSTM output gate, in | |
| GRU write gate in , in | |
| GRU tanh candidate state, mixed into with weight | |
| elementwise product | |
| next-token loss at the last position only | |
| mean next-token loss over all positions, | |
| Attention | |
| query vector at position , of dimension | |
| key vector at position , of dimension | |
| value vector at position , of dimension | |
| dimension of keys and queries (64 in the capacity example) | |
| dimension of values | |
| attention weight of output position on position , for softmax attention | |
| raw attention score of position on position , before a softmax or sigmoid turns it into a weight | |
| sink threshold (0.3, Gu et al.); a head counts as a sink when its average attention to the first token exceeds it | |
| Matrix-state layers | |
| matrix state of a linear-attention-style layer after position , read as | |
| decay in computed from the input, which multiplies the old state, as in Mamba-2's | |
| write strength in , the delta rule's step size in | |
| number of key-value pairs stored in a linear memory | |
| matrix whose columns are the stored keys | |
| matrix whose columns are the stored values | |
| pseudo-inverse of the key matrix ; the least-squares memory is | |
Context. A recurrent network applies the same weights at every step to a fresh input, so unrolled across a sequence it is a deep network with tied weights. It therefore inherits the vanishing and exploding gradients of depth. As Lecture 8 of Stanford's CS 312, Deep Learning Alchemy (Hashimoto and Kotha, Fall 2026), recounts, RNNs and LSTMs were for years as hard to train well as deep plain networks. The lecture asks what carries over from signal propagation in depth to propagation in time. Its unifying object is the sequence layer's generalized Jacobian, whose blocks the Jacobian of the output at position with respect to the input at position , a matrix for layer width ; the lecture writes for inputs and outputs form a block lower-triangular matrix. Three properties of this matrix organize sequence architectures: retentionhow well a signal travels from the input at one position to the output at a later position , that is, whether the Jacobian block stays large; a recurrence loses it through long products of per-step Jacobians, while attention keeps a direct path, mixinghow one output combines information from many earlier inputs , for example through attention weights , which must sum to one, and capacityhow many earlier inputs a layer can still recover at a given position; a fixed-size state caps it, at about key-value pairs for a linear memory read with its keys. Retention measures how well a signal travels from one past position to a later one, while mixing describes how one output combines many inputs. Capacity counts how many past inputs remain recoverable at time .
Each architecture family runs into a different one of these three limits. Recurrences fix retention the same way deep networks do, through an additive path in the state; the LSTM memory cell is a residual connection in time. One difference remains: the layer must decide token by token what to keep and what to erase, so input-dependent gates work where depth-style initialization tricks do not. Attention removes the retention bottleneck by linking every output directly to every input, shifting the pressure to mixing. Because softmax weights must sum to one, an idle head dumps its weight onto a sink token unless given an explicit no-op. Matrix-state recurrences (linear attention, Mamba-2, DeltaNet, and Gated DeltaNet) keep constant cost per token, so capacity becomes the binding constraint. A fixed state stores only so many key-value pairs, and the update rule (decay, selective overwrite, or both) decides which pairs survive. Modern hybrids such as Qwen3-Next pair three gated matrix-state layers with one attention layer.
Setting. Assignment 4 compares three architectures trained with one recipe: model width , vocabulary 4,096, context length 1,024 tokens, 614.4M training tokens, and AdamWAdam with decoupled weight decay; each coordinate moves by the learning rate times a running average of its gradient (the momentum), divided by the square root of a running average of its squared gradient, so every coordinate takes a step of similar size; weight decay then shrinks every weight by a small fixed fraction per step, applied to the weights directly instead of through that division (Loshchilov and Hutter, 2019). The transformer uses 8 blocks with pre-normnormalizing each sublayer's input and adding the sublayer's output to a stream that is itself never normalized. Reading note: Signal propagation in depth, RoPErotary position embedding: queries and keys are rotated by angles proportional to their positions, so attention scores depend on relative position, and gated MLPs. The modern tanh RNN uses 4 blocks, each pairing a tanh recurrence and an MLP with depth residuals and pre-norm LayerNormlayer normalization: subtract a vector's mean across its coordinates, divide by their standard deviation, then apply a learned gain and bias. The GRUgated recurrent unit: a recurrent cell whose state is a gated average of its previous value and a tanh candidate, (Cho et al., 2014; Chung et al., 2014) shares that same 4-block depth stack.
Vanishing and exploding gradients in RNNs. Because a recurrent layer multiplies by the same weight matrix at every step, long-range sensitivities vanish or explode exponentially with sequence length. Write the hidden state of a recurrent layer after reading position , carried to the next position for the hidden state of a tanh RNN, , with preactivation from input weights , recurrent weights , and bias . By the chain rule across steps,Pascanu et al. (2013) bound this product when the activation's derivative has magnitude at most ( for tanh, for the sigmoid). With the largest singular value of a matrix, its operator norm the largest singular value, . So guarantees exponential vanishing, and is necessary for explosion. Because the same repeats in every factor, the stable window is razor thin. Exploding gradients appear as steep walls in the loss surface where one update throws the weights far away. Pascanu et al. contain them with gradient clippingreplacing the gradient by whenever , for a threshold , which caps the step at a wall, though clipping cannot rescue vanishing gradients. In the 4-block tanh RNN, this decay shows directly in gradients with respect to the first layer's hidden states . The gradient of the last-token loss the next-token loss at the last position of the sequence only passes back through Jacobians and decays exponentially toward the start of the sequence. The mean loss the mean next-token loss over all positions, , with the loss at position supervises every position directly and leaves a roughly flat gradient profile.
The LSTM cell and input-dependent gates. The LSTM's cell is a residual connection in time, and input-dependent gates make it usable over long sequences. Hochreiter and Schmidhuber (1997) replaced repeated multiplication with an additive memory cell , where is the elementwise product. An input gate scales a candidate write , and an output gate reads . Apart from the gates' own dependence on the past, , so gradients carry back over 1,000 steps and more. Without a way to clear old writes, though, the cell grows unchecked over long sequences, much like an unnormalized residual stream in depth. Gers et al. (2000) added a forget gate , giving and letting the model shrink its state token by token instead of normalizing it. The GRU merges both gates into one write gate that blends the old state with a tanh candidate , giving . Large architecture sweeps show little else is essential. Greff et al. (2017) found only the forget gate and output tanh indispensable. Searching about 10,000 variants, Jozefowicz et al. (2015) found that initializing the forget-gate bias to 1 lets the LSTM match the GRU, with nothing clearly better. Applying depth tricks to time confirms that initialization alone falls short. Orthogonal or unitary , critical initialization, and fixed diagonal linear recurrences such as S4structured state space sequence model: a linear recurrence with a fixed, specially structured and LRUlinear recurrent unit: the linear recurrence of S4, with a fixed complex diagonal all solve long toy tasks of 784 to over 1,000 steps. None improved language models until Mambaa recurrent state-space layer, a linear recurrence like S4's whose decay and write strength are computed from the current input, so the layer can choose per token what to keep; it was the first such recurrence to improve language models (Gu and Dao, 2023) (Gu and Dao, 2023) made the decay depend on the input.
Controlled tests on the 4-block RNN. Changing only the time update in the 4-block RNN, while holding depth residuals, LayerNorm, and MLPs fixed, isolates what each mechanism buys. A plain residual in time, with the tanh candidate, adds a write at every step with no way to erase one, so the state norm grows across the sequence. The course's answer slides note that this unscaled path also turns vanishing early-step gradients into exploding ones. Dividing by its RMS after each step restores stability, yet still trails the plain tanh baseline. The course reads that gap as the cost of stripping away input-dependent control over the state's norm. Replacing the GRU's learned write gate with one tuned constant also hurts substantially. In the trained GRU runs, learned write gates vary across layers and inputs and often sit near 0 or 1, with about 40% of them outside . Switching writes on and off per token matters beyond the average gate value.
Context use and positional structure. Recurrent language models use a short window of context, while attention uses all of it. Khandelwal et al. (2018) found that LSTM language models effectively use about 200 tokens of context and rely on word order only within roughly the last 50. Attention links every pair of positions in one hop instead of recurrent steps. Kaplan et al. (2020) found that transformers keep lowering per-token loss across the whole context window, whereas LSTMs plateau after fewer than 100 tokens, and the gap widens with scale. Assignment 4 tests context use directly on the final target, comparing the full 1,023-input loss against keeping only the most recent inputs plus the first token. Recurrent states restart while transformer positions stay intact. Truncating hurts the transformer most, the tanh RNN least, and the GRU in between. The two families also get order from different sources. A recurrence encodes position through its step-by-step update, while a transformer sees order only through its causal mask and positional encoding. Adding RoPE therefore helps the transformer far more than its analogue helps the RNN.
Attention reads directly, and idle heads park weight on a sink. In a causal attention head, position forms a query , scores past keys , and returns a weighted sum of values :A head needs three read behaviors: sharp lookup of one token, broad averaging across many tokens, and a no-op when it has nothing useful to read, which is common in upper layers. Nonnegative weights summing to one handle the first two naturally, yet force an idle head to park its mass somewhere harmless. Trained models routinely carry idle heads and build such a dumping ground. In BERT, over half of middle-layer attention lands on [SEP] (Clark et al., 2019), and in a translation transformer, pruning 38 of 48 heads costs only 0.15 BLEU (Voita et al., 2019). In autoregressive language models past the first two layers, most heads attend heavily to the first token (Xiao et al., 2023). That token's value vector is near zero, so attending to it contributes almost nothing (Gu et al., 2025), making it an attention sinka token, usually the first, that receives a large share of attention while contributing almost nothing to the output. Sinks matter immediately at serving time. In Xiao et al.'s sliding-window cache test, evicting the first token spikes perplexity to 5,158. Keeping four initial tokens alongside the window holds perplexity at 5.40, matching the 5.43 of recomputing the window from scratch. Sun et al. (2024) link sinks to massive activationsa few hidden-state coordinates, usually on the first token, that are orders of magnitude larger than the rest, which vanish once heads receive an explicit key and value bias.
| Weights | Sink | Loss |
|---|---|---|
| Softmax | 18.2% | 3.73 |
| Sigmoid, divided by the row sum | 30.2% | 3.74 |
| Sigmoid , no normalization | 0.4% | 3.70 |
| 1B parameters | ||
| Softmax | 45.1% | 3.07 |
| Sigmoid, no normalization | 2.5% | 3.10 |
Practical fixes give a head an explicit no-op. Every modern fix relaxes the forced sum-to-one write onto real tokens. One option adds a learned sink logit to the softmax denominator so weights over real tokens can sum to less than one, as in gpt-ossa family of open-weight language models released in 2025, whose attention adds an extra learned logit to the softmax denominator so that a head's weights can sum to less than one. Other fixes add a learnable zero-value sink token or use unnormalized sigmoid attention. Another puts a sigmoid gate on each head's output (Qiu et al., 2025; used in Qwen3-Next), which lowered the average attention on the first token from 46.7% to 4.8%.
Matrix-state recurrences: linear attention and Mamba-2. Full attention's KV cache grows linearly with sequence length, so constant-cost alternatives compress past tokens into a fixed matrix state. Removing the softmax yields linear attentionattention with the softmax removed (up to a feature map and normalizer), so that it is the recurrence , on a fixed-size matrix state (Katharopoulos et al., 2020). Reading note: Softmax attention as a sum of RNNs. Reassociating the product as turns it into a recurrence over a matrix state the state of a linear-attention-style layer after position : a matrix that stores value-key associations (a separate note treats softmax attention as a sum of RNNs):Training runs the parallel matrix product, while inference steps the recurrence at constant cost per token. Plain linear attention only adds outer products and never forgets. Mamba-2a recurrent layer with a matrix state like linear attention's, , whose scalar decay is computed from the input and forgets every stored pair at the same rate (Dao and Gu, 2024). Reading note: Softmax attention as a sum of RNNs therefore multiplies the old state by an input-dependent scalar decay , giving plus a skip term. That decay clears room by shrinking every stored pair at the same rate.
# S: (d_v, d_k) state; k: (d_k,) unit-norm key; v: (d_v,); q: (d_k,)
# alpha, beta: scalars in (0, 1) computed from the current token
old = S @ k # value stored under k
S = alpha * (S - beta * torch.outer(old, k)) # decay, erase along k
S = S + beta * torch.outer(v, k) # write the new value
y = S @ q # read with the queryLong-context retrieval trades decay against overwrite. Lecture 8's table of 1.3B models shows why neither forgetting rule suffices alone. On a passkey hidden in synthetic filler at 8K tokens, decay alone (Mamba-2) succeeds 30.4% of the time, the delta rule alone (DeltaNet) reaches 98.8%, and Gated DeltaNet reaches 91.8%. On a number hidden in essays at 4K tokens, the first two swap places: Mamba-2 reaches 56.2%, DeltaNet drops to 18.6%, and Gated DeltaNet reaches 92.2%. Uniform decay discards long-lived memories inside filler, while the delta rule alone writes a trace on every varied token of real text and clogs the state. Adding the decay gate lets Gated DeltaNet clear stale noise while keeping selective overwrite.
State capacity and nonlinear readouts. State geometry sets a hard ceiling on how many past items survive. An RNN or LSTM carries a vector of numbers, where growing costs quadratic compute. Matrix-state layers carry a matrix decoupled from model width, while attention's KV cache stores numbers per past token and grows linearly with . For a linear memory holding the number of key-value pairs stored in a memory pairs, reading with key splits into signal and cross-talk:With random unit keys and values in dimensions, each cross term has size about . Summing random terms gives interference of norm about , which matches the signal near (64 pairs at ; a simulation here agrees). Stack the and as columns of and with pseudo-inverse ; the least-squares memory is the optimal linear memory and recovers any linearly independent keys exactly. The delta rule takes an online gradient step toward , though one pass falls short. In a check here with and 16 random unit keys in 64 dimensions, mean read-back error is about 0.33 times the stored value's norm. Nonlinear readouts hold far more. In the lecture's calculation (after Wang, 2026), a squared-ReLU MLP stores about pairs, and softmax over a cache at inverse temperature separates about million.
Copying, recall probes, and hybrid architectures. Empirical recall tests line up with these capacity gaps. Jelassi et al. (2024) found that transformers learn string copying from far fewer examples than state-space models, generalize better to longer strings, and copy better than perplexity-matched pretrained Mamba models. Synthetic probes such as MQARmulti-query associative recall: a context of key-value pairs followed by queries for several of the keys, scored on recalling their values map accuracy against state size, though optimization quirks can distort them. Okpekpe and Orvieto (2025) found that attention solves MQAR across almost any learning rate, while Mamba and Hyenaa sequence layer built from long convolutions whose filters are generated by a small network, interleaved with elementwise gates (Poli et al., 2023) learn it only inside a narrow learning-rate window that standard sweeps can miss. In their runs, recurrent layers also gained most from width, while attention gained most from depth. In practice, models mix both families: Qwen3-Next places three Gated DeltaNet layers per attention layer for fast inference, though controlled ablations of the mixing ratio remain scarce.
Limits. Most numbers above come from individual papers with distinct setups. The head-pruning, sink, and retrieval comparisons each draw on a single table, and the 4-block RNN measurements are single runs. The sink measure depends on its threshold , and for unnormalized sigmoid attention Gu et al. compute it from scores normalized after the fact. The capacity estimates assume random keys and one read per key.
Terms
- generalized Jacobian
- , : retention (one pair), mixing (one row), capacity (how many inputs survive)
- RNN gradient
- ; norm at most
- gradient clipping
- rescale the gradient to a threshold norm when it exceeds it; fixes exploding, not vanishing
- LSTM cell
- : a residual in time with a learned forget gate
- GRU
- ; learned gates near 0 or 1 matter
- attention sink
- first token that takes much of a head's attention with a near-zero value: a no-op under sum-to-one weights
- sink fixes
- sink logit, learned sink token, unnormalized sigmoid attention, per-head output gate
- linear attention
- ,
- Mamba-2
- : input-dependent decay
- delta rule
- : erase the old value along , write the new
- Gated DeltaNet
- linear-memory capacity
- interference about for random unit keys: about pairs; nonlinear readouts hold far more
Sources
Lecture 8, “Architecture 1: Signal propagation in time” (Oct 27, 2026), of Stanford CS 312 Deep Learning Alchemy, Fall 2026. Taught by Tatsunori Hashimoto and Suhas Kotha; course staff Kaiyue Wen and Tristan Thrush (CAs).
Course site Lecture slides Online quiz Quiz answers Assignment Assignment code
The lessons, experiments, figures and quiz problems in this note are the course's, shown here with the instructors' permission.
- Tatsunori Hashimoto and Suhas Kotha. CS 312 Deep Learning Alchemy, Lecture 8: Architecture 1: Signal propagation in time. Stanford, Fall 2026.
- Razvan Pascanu, Tomas Mikolov, and Yoshua Bengio. On the difficulty of training Recurrent Neural Networks. ICML, 2013.
- Xiangming Gu, Tianyu Pang, Chao Du, Qian Liu, Fengzhuo Zhang, Cunxiao Du, Ye Wang, and Min Lin. When Attention Sink Emerges in Language Models: An Empirical View. ICLR, 2025.
- Songlin Yang. DeltaNet Explained (Part I). Blog post, 2024.
- Tatsunori Hashimoto and Suhas Kotha. CS 312 Deep Learning Alchemy, Quiz 4 (Stability) and Assignment 4 (Transformers vs RNNs). Stanford, Fall 2026.
- Ilya Loshchilov and Frank Hutter. Decoupled Weight Decay Regularization. International Conference on Learning Representations, 2019.
- Junyoung Chung, Caglar Gulcehre, KyungHyun Cho, and Yoshua Bengio. Empirical Evaluation of Gated Recurrent Neural Networks on Sequence Modeling. arXiv preprint, 2014.
- Angelos Katharopoulos, Apoorv Vyas, Nikolaos Pappas, and François Fleuret. Transformers are RNNs: Fast Autoregressive Transformers with Linear Attention. International Conference on Machine Learning, 2020.
- Tri Dao and Albert Gu. Transformers are SSMs: Generalized Models and Efficient Algorithms Through Structured State Space Duality. International Conference on Machine Learning, 2024.
- Imanol Schlag, Kazuki Irie, and Jürgen Schmidhuber. Linear Transformers Are Secretly Fast Weight Programmers. International Conference on Machine Learning, 2021.
- Michael Poli, Stefano Massaroli, Eric Nguyen, Daniel Y. Fu, Tri Dao, Stephen Baccus, Yoshua Bengio, Stefano Ermon, and Christopher Ré. Hyena Hierarchy: Towards Larger Convolutional Language Models. International Conference on Machine Learning, 2023.
Connected notes
- Softmax attention as a sum of RNNsEfficient sequence models · Additive paths carry signal through depth and time
Linear attention's state is a running sum of key-value products that never forgets. Of Mamba-2's components added one at a time to a 300M model, a data-dependent decay of that sum and a short convolution carry nearly all the gain. Test loss goes from 3.13 to 2.88 with the decay alone, 2.93 with the convolution alone and 2.77 with both, while the other components move it by 0.07 or less.
PreNorm's unweighted running sum grows with depth and dilutes every earlier output, so Attention Residuals replace it with softmax-weighted averages over earlier block sums, bounding the mixed input by while keeping direct shortcuts across depth without the matrix-product instability of multi-stream mixing.
- A Mathematical Framework for Transformer CircuitsSuperposition · Additive paths carry signal through depth and time
Because every layer reads the residual stream linearly and adds its output back, an attention-only transformer expands directly into a sum of independent paths, linking any earlier write matrix directly to any later read matrix through virtual weights across intervening layers.
- Cross-layer connectionsNanoGPT speedrun · Additive paths carry signal through depth and time
The ordinary residual stream already carries early layers forward. In an 8-layer model a value shortcut from layer 2 or later adds little, because is reachable through the stream, and it helps once the residual chain is started at . Deep layers want the first-layer shortcut most, so a direct path helps where the single running sum no longer carries that information cleanly.