Sequence Models, Attention & Transformers
Language forces three demands no fixed-size feedforward net meets: inputs are variable-length, order matters, and a word’s meaning is context-dependent. The subject is the arc that answers them, each stage fixing the previous one’s bottleneck. Static word vectors (word2vec, GloVe) give dense meaning but one vector per word-type. Recurrence (RNN/LSTM) threads a hidden state through time to carry context — but serially, and it forgets across long gaps. Seq2seq maps one sequence to another through a single summary vector — which is itself a bottleneck. Attention removes it by letting the decoder look directly at every source position. The Transformer then throws out recurrence entirely — attention is all you need — buying full parallelism and constant-distance interaction between any two tokens. Finally pretraining learns the representation once on raw text and finetunes it everywhere, which is what made today’s large language models. A single quantity recurs as the villain — the product of Jacobians through time that makes vanilla RNNs forget — and the LSTM’s additive cell, attention’s direct paths, and the Transformer’s residual stream are all ways to keep it from vanishing. Prerequisites cashed in: backprop, the rule, , vanishing/exploding gradients, residual connections, softmax, Adam, layer/batch norm (track 11a); the chain rule and Jacobians (track 2); cross-entropy and MLE (tracks 3, 6); the SVD co-occurrence view (track 2).
1. Word vectors — meaning from distribution
- The representation problem. One-hot vectors (dimension = vocabulary size) are sparse, huge, and orthogonal — “motel” and “hotel” share nothing. Distributional semantics: a word’s meaning is given by the company it keeps (the words in a window around it). Goal: a dense vector per word encoding that context — a word embedding.
- Two families. Count-based (co-occurrence matrix + SVD: rows of in are embeddings) is fast but dominated by frequent words and tied to a fixed vocabulary. Prediction-based (word2vec) learns embeddings by an iterative prediction task and captures linear analogies. GloVe unifies them.
- word2vec / skip-gram. Each word has two vectors: when it is the center word, when an outside/context word (two vectors only to keep the math clean — a single vector creates an awkward term). Predict context from center via softmax over similarity (dot product):
Objective: minimize average negative log-likelihood over every center–context pair in the corpus, .
- The center-vector gradient — derive it (the canonical NLP derivation). Differentiate the log-probability:
First term:
Second term, chain rule through the log then the sum. The outer log contributes times the derivative of the sum:
Differentiate the inner sum term by term, using :
Substitute back and move the denominator inside the sum:
The ratio is exactly the softmax :
Combine:
Observed minus expected — the exact form of the logistic/softmax gradient (, track 11a). The update vanishes precisely when the model’s predicted context distribution matches the data.
- Numeric anchor: vocab , center vector , context vectors . Scores → softmax . If the true context word is , the gradient is — it pushes toward the observed , which is exactly observed − expected.
- Negative sampling (SGNS) — the softmax denominator sums over the whole vocabulary, far too expensive. Replace it with binary logistic discrimination of the true pair against noise words:
Push the true pair’s dot product up, the noise pairs’ down. Sample noise from the unigram distribution raised to the power (then renormalized) to upsample rarer words. Skip-gram (predict context from center) vs CBOW (predict center from context bag).
- GloVe — fuse counts and prediction. Make the dot product approximate the log co-occurrence, so that ratios of co-occurrence probabilities (which encode meaning components) come out linear:
with a weighting that down-clips very frequent pairs. Trains fast on a global matrix and matches word2vec’s analogies.
- Evaluation. Intrinsic (analogy/similarity subtasks — exclude the input words, which otherwise win) vs extrinsic (downstream task, e.g. named-entity recognition). ~300 dimensions is the usual sweet spot. A single vector per word is a superposition of its senses, separable with enough data.
Implications
- The observed-minus-expected gradient is the same engine as logistic regression and softmax classification — one move across tracks.
- Static embeddings give one vector per type, blind to context — the limitation that the later sections (§4 onward, contextual representations) exist to fix.
Core competency set
- Derive the skip-gram center-vector gradient to and read off observed − expected.
- State the SGNS objective and why (denominator cost); give GloVe’s log-bilinear objective and what it unifies.
2. Recurrent neural networks
- Why recurrence. A fixed window over previous words can’t handle arbitrary length and grows in parameters with the window. An RNN applies the same weights at every timestep to a running hidden state, so it handles any length with fixed parameters:
and emits an output (e.g. a softmax over the vocabulary) at each step. Advantages: any length, fixed model size, symmetric weight use. Disadvantages: serial (slow), and in practice it struggles to use information from many steps back. Picture (draw it): the RNN unrolled through time — the same cell (same ) copied left-to-right, each copy taking the previous hidden state and the new embedding and passing rightward; the shared box repeated is weight sharing across time (the sequence analogue of convolution’s sharing across space, track 11a).
- Language modeling & training. Predict the next word at every position; loss is cross-entropy = negative log-likelihood:
Teacher forcing: feed the true previous word at each step (not the model’s own prediction) so training is one-step-ahead and stable. Evaluate with perplexity = = geometric mean of inverse next-word probabilities; lower is better.
- Backprop through time (BPTT). is reused at every step, so depends on it through every hidden state . The multivariate chain rule sums the contribution down each of those paths:
where the -th term treats as appearing only at step (the other steps’ copies held fixed). Abbreviating that summand :
In practice: compute the gradient at step and propagate it back through earlier steps, accumulating; apply the summed update once. For long sequences, truncate to the last ~20 steps.
- Vanishing / exploding through time. Backprop multiplies the recurrent Jacobian once per step, so gradient from far back is a long product (track 11a’s villain, now along the time axis): it shrinks toward 0 — the model learns only short-range effects and can’t connect distant words — or blows up. Exploding is patched by gradient clipping (rescale when exceeds a threshold). Vanishing needs an architecture fix → §3.
- Generation: seed with a start token and , sample from the output softmax, feed the sample back in, repeat until an end token.
- Bidirectional RNNs concatenate a left-to-right and right-to-left pass so each position’s representation sees both sides — only usable when the whole input is available (not for generation). Multi-layer (stacked) RNNs let lower layers capture low-level features and higher layers abstract structure; a few stacked layers with a modest hidden size beat one huge layer.
Implications
- The RNN solves variable length and order with weight sharing across time — the same parameter-sharing idea as convolution across space (track 11a).
- BPTT’s summed gradient and its vanishing product are why vanilla RNNs forget, motivating the LSTM.
Core competency set
- Write the RNN recurrence and the LM cross-entropy / perplexity; explain teacher forcing.
- Derive BPTT’s gradient as a sum over timesteps and explain vanishing/exploding as a Jacobian product through time; name clipping.
3. LSTMs and GRUs — a gradient highway through time
- The fix: a protected memory. The LSTM adds a cell state alongside the hidden state . The cell carries long-term information and is updated additively, which is what preserves the gradient across many steps. Three gates (each an -vector in from a sigmoid) control the flow: forget , input , output , plus a tanh candidate . Each gate is a sigmoid of the same inputs with its own weights, the candidate a tanh:
All gates and the candidate depend only on , so they compute in parallel.
- Why it beats vanishing. Differentiate the cell recurrence with respect to . The candidate term touches only indirectly (through the gates, via ) and contributes little; the direct term dominates:
The cell-to-cell Jacobian is just elementwise multiplication by the forget gate — no learned matrix. Chaining it back steps multiplies forget gates, so with the gradient passes essentially unchanged:
Contrast the vanilla RNN, whose compounds into a vanishing/exploding matrix power. It is trivial for the LSTM to preserve information (set ); learning when to forget is the harder, learned part. (Initialize the forget-gate bias positive so starts near 1.) This is the same additive gradient-highway idea as the ResNet skip connection, track 11a §6.
- GRU — a lighter variant with two gates (update , reset ) and no separate cell state; it merges the forget/input gates into one and often matches the LSTM at lower cost. Default to the LSTM when in doubt, GRU when compute-bound.
Implications
- “Carry state through an additive path” is the recurring cure for vanishing gradients — LSTM cell, GRU, ResNet, and the Transformer residual stream are the same move.
- Gates are learned, soft read/write/erase controls — an early form of the content-based selection that attention generalizes.
Core competency set
- Write the LSTM cell update and explain why the additive preserves gradient (forget gate ≈ 1).
- Relate it to ResNet skips; state what the GRU simplifies.
4. Seq2seq and attention
- Encoder–decoder (seq2seq). Two RNNs: an encoder reads the source and its final hidden state initializes a decoder that generates the target. It is a conditional language model — the decoder predicts the next target word conditioned on the source:
Trained end-to-end with teacher forcing on a parallel corpus; used for translation, summarization, parsing, dialogue.
- The bottleneck. The entire source must be squeezed into one fixed encoder vector — long sentences overflow it. Attention fixes this: at each decoder step, look directly back at all encoder states and pull what’s relevant.
- Attention, mechanically. With encoder states and decoder state :
then concatenate to predict the word. Bonus: is a soft alignment you can inspect for free.
- Numeric anchor: scores over three encoder states → softmax ; with the attention output is — dominated by , the position the query best matches. Picture (draw it): the alignment heatmap — target words down the rows, source words across the columns, each cell shaded by ; for translation it lights up roughly along the diagonal, bending where word order differs — a free, readable picture of what the decoder looked at.
- The general idea — query/key/value. Attention is a way to get a fixed-size summary of a set of values, weighted by how well each matches a query (like content-addressable memory). The recipe is always score → softmax → weighted sum; only the score function varies:
- dot product (needs equal dimensions);
- multiplicative (learnable, but is large — dimension-squared);
- reduced-rank multiplicative (low-rank );
- additive (a small MLP).
- Decoding the target. Greedy (take the argmax each step) can’t undo a bad choice. Exhaustive search is exponential. Beam search keeps the best partial hypotheses by log-probability (–10); since longer hypotheses accrue more negative terms, normalize the score by length. Evaluate translation with BLEU (n-gram precision overlap with reference + brevity penalty) — useful but imperfect (penalizes valid paraphrases).
Implications
- Attention turns a fixed summary into a dynamic, query-dependent lookup — the conceptual leap that the Transformer makes the whole architecture.
- The QKV framing (set of values, a query, a weighted summary) is the reusable abstraction; the score function is the only knob.
Core competency set
- Write seq2seq as a conditional LM and state the bottleneck.
- Give the three-step attention computation and the QKV interpretation; list the score-function variants; explain beam search + length normalization and BLEU.
5. The Transformer
- Why drop recurrence. RNNs take serial steps for two tokens apart to interact (long-range dependencies are slow and gradient-fragile), and they can’t parallelize across time (each hidden state waits for the previous). Replace recurrence with attention applied within one sequence: any two tokens interact in one step, and all positions compute in parallel.
- Self-attention. Draw queries, keys, values from the same sequence. From input vectors (output of the previous layer), project with learned matrices :
Score every query against every key, softmax, weight the values. In matrix form with :
- Scaled dot product — derive the . A score is a dot product of a query and key over the head dimension , . Take the components independent, mean 0, variance 1; then each product has mean 0 and variance 1, and the of them are independent, so the variances add:
i.e. scores have standard deviation — growing with dimension. Large logits push the softmax toward one-hot, where its Jacobian and the gradient through attention vanishes. Divide the scores by to pull the softmax input back to unit scale:
-
Multi-head attention. One attention pattern can attend to only one thing at a time. Use heads, each with its own , run them independently, concatenate, and mix with a learned :
Each head runs its own attention:
Concatenate the head outputs and mix with the learned :
(Splitting across heads keeps the total compute the same.)
- Position — because attention is order-blind. Self-attention operates on a set (permute the inputs, the outputs just permute) so sequence order must be injected. Add a position vector to each input: . Either fixed sinusoids (extrapolate to unseen lengths but not learnable) or learned (flexible but can’t extrapolate past ).
- Nonlinearity and stabilizers. Self-attention is only weighted averaging, so follow each block with a per-position feed-forward network . Two training essentials wrap every sublayer:
- residual connection — learn the difference, smooth the landscape, keep a gradient highway (track 11a §6);
- layer normalization — normalize each token vector to unit mean/variance (over its features, not the batch), with learned gain/bias: . (Per-token, so it doesn’t depend on batch composition — unlike batch norm.)
- Future masking. A decoder must not peek ahead, so before the softmax set scores to future positions to (a causal lower-triangular mask) — done all at once, preserving parallelism.
- The blocks.
- Encoder block: multi-head self-attention → add & norm → feed-forward → add & norm. Stack of them.
- Decoder block: masked multi-head self-attention → add & norm → cross-attention (queries from the decoder, keys/values from the encoder output — the seq2seq memory access of §4) → add & norm → feed-forward → add & norm.
- Picture (draw it): the block as a vertical stack — input → [multi-head attention] → ⊕ (residual add) → norm → [feed-forward] → ⊕ → norm → output, with the residual arrows skipping around each sublayer; stack identical blocks into a tower, embeddings + positional encodings entering at the bottom. The skip arrows are the gradient highway (11a §6); the alternation is mix across tokens (attention) → process each token (FFN).
- Cost and variants. All-pairs attention is — quadratic in sequence length, prohibitive for very long documents. Efficient variants (e.g. BigBird) replace dense all-pairs attention with a mix of local-window, global, and random connections to get near-linear cost.
Implications
- The Transformer trades recurrence’s serial bottleneck for parallel, constant-distance interaction — the architecture that scaling rode to LLMs.
- Residual + layer norm + scaled dot product are the training tricks that make deep attention stacks trainable; they’re 11a’s Jacobian-product fixes ported to attention.
Core competency set
- Write self-attention in matrix form and derive the scaling; explain multi-head and positional encoding.
- Give the encoder and decoder block layouts, the role of cross-attention and causal masking, and the cost.
6. Shapes, normalization, and the residual stream
The single biggest source of confusion in a transformer is bookkeeping the tensor shapes. One convention dissolves most of it.
-
The mental model. Every activation flowing through a transformer has three axes:
- = batch — independent sequences processed together;
- = sequence length — tokens/positions in a sequence;
- = model dimension () — the length of each token’s feature vector.
So the working tensor is : sequences, each tokens, each token a -vector. (A plain MLP has no time axis: ; a convnet uses , channels-then-spatial.)
-
Operations split by which axis they touch:
| Operation | Computes along | Mixes tokens? | Shape map |
|---|---|---|---|
| Linear / FFN | features (last axis) | no — per token | |
| Layer norm | features | no — per token | |
| Attention | positions | yes | |
| Batch norm | batch (+ ) | no — per feature |
The realization that clears most confusion: a linear layer only ever touches the last axis. on is the same weight matrix applied independently to all token vectors — it broadcasts over and . So read any linear/FFN layer’s shape as just ; the batch and sequence axes ride along untouched. Only attention moves information between positions.
-
Batch norm vs layer norm — it’s entirely about the axis. Both compute then rescale by learned of shape (per-feature). They differ only in the set are taken over:
- Batch norm (track 11a §4): for each feature, average across the batch (and sequence) → statistics of shape , one mean/var per feature. “Normalize a feature down the batch.” Couples examples together → needs running averages at test time, degrades with small batches, and is awkward when varies.
- Layer norm: for each token, average across its own features → statistics of shape , one mean/var per token vector. “Normalize a token across its features.” Each token is normalized using only itself — no batch coupling, identical at train and test, indifferent to . That is why transformers use layer norm, not batch norm.
Concretely, for one token vector , layer norm computes , , output — run independently for every one of the tokens.
-
Pre-norm vs post-norm — where the LayerNorm sits relative to the residual add. Each sublayer (attention, FFN) is wrapped in a residual connection (track 11a §6); the only question is whether the norm goes before or after the add:
- Post-norm (original 2017 Transformer): normalize the block’s output, after the residual add —
- Pre-norm (GPT-2 onward, now standard): normalize the sublayer’s input, inside the residual branch; the residual stream itself is never normalized —
Why pre-norm won — look at the Jacobian each adds to the backward path. Pre-norm’s update differentiates to
whose identity term is a clean pass-through, so a gradient travels from the last block to the first essentially undiminished (the §3 / 11a gradient-highway argument). Post-norm’s update instead wraps the whole sum in the norm:
so every block multiplies the backward signal by a LayerNorm Jacobian ; across blocks that is a product of such Jacobians — the vanishing/exploding-product problem again, which is why deep post-norm transformers are unstable and need learning-rate warmup. Pre-norm leaves an unbroken residual stream from input to output, so very deep stacks train stably. Its one cost: the residual stream’s variance grows with depth, fixed by a single final LayerNorm before the output head.
- The FFN, spelled out. The position-wise feed-forward network is a 2-layer MLP applied to each token independently. Start from input of shape . Expand with (conventionally , e.g. ):
Contract back with :
“Position-wise” means the same hit every token, and no information crosses positions (attention already did that). Parameters — about two-thirds of a transformer’s weights live here. The rhythm of a transformer block is therefore mix across tokens (attention) → process each token nonlinearly (FFN), repeated times.
-
Full shape walkthrough of one block. Concrete numbers: sequences, tokens, , heads (so head size ), .
- input : .
- , each is → : .
- split heads: transpose .
- scores over the last two axes: ; scale by ; causal-mask the block; softmax over the last (key) axis.
- weighted values (scores): .
- merge heads: ; output projection → .
- residual add + layer norm → .
- FFN: ; residual add + norm → .
- output — the same shape as the input, which is exactly what lets you stack blocks.
That invariant tensor is the residual stream: a fixed-width bus running through the whole network, which every block reads from and adds its update back to.
Implications
- Read shapes by axis role, not by memorizing: linear/FFN/layer-norm act on the last () axis per token; attention is the only thing that mixes the axis; batch norm is the only thing that mixes the axis.
- Layer norm beats batch norm in sequence models precisely because it is per-token (batch- and length-independent); pre-norm beats post-norm because it preserves the residual gradient highway.
Core competency set
- State the convention and classify each op by the axis it touches; explain why a linear layer reads as .
- Contrast batch vs layer norm by the axis their statistics are computed over (and the shape of those statistics); say why transformers use layer norm.
- Write pre-norm vs post-norm and explain why pre-norm trains deep stacks stably.
- Spell out the FFN (, , position-wise) and walk one block’s shapes start to finish.
7. Pretraining and large language models
- Subword tokenization (BPE). A fixed word vocabulary makes every novel word
UNK. Byte-pair encoding starts from characters and greedily merges the most frequent adjacent pair into a new subword, repeating to a target vocab — common words stay whole, rare words split into pieces. Novel words decompose into known subwords (so “word” embeddings are really subword embeddings). - The paradigm shift. Previously: pretrained word vectors + a large randomly-initialized model trained per task. Now: pretrain almost all parameters on raw text by hiding parts of the input and reconstructing them (a scaled-up word2vec idea), then finetune on the task. Why it helps: SGD finetuning stays near the good pretrained , landing in minima that generalize better with friendlier gradients. Pretraining is compute-heavy; finetuning is cheap.
- Three architectures, three objectives.
- Decoders (GPT) — autoregressive language modeling: predict the next token from the past. Plenty of data (any text). Finetune by adding a linear head on the final hidden state and backpropagating through the whole net; better still, reframe the task as text (e.g. natural-language inference fed as
Start … Delim … Extract) and keep the architecture fixed. Can’t condition on the future (that’s required to pretrain as an LM); easy to sample from. - Encoders (BERT) — bidirectional, so they can’t do next-token LM. Instead masked language modeling: replace ~15% of tokens and predict them, with the 80/10/10 trick (80%
[MASK], 10% random token, 10% unchanged) so the model can’t shortcut by only working on[MASK]positions and must build a full representation. (BERT’s original next-sentence-prediction objective was later judged unhelpful; RoBERTa = BERT trained longer without it; SpanBERT masks contiguous spans.) Great for understanding tasks; awkward for generation. - Encoder–decoders (T5) — span corruption: replace random spans with placeholders and decode the removed spans. Combines bidirectional encoding with generation; strong on QA after finetuning.
- Decoders (GPT) — autoregressive language modeling: predict the next token from the past. Plenty of data (any text). Finetune by adding a linear head on the final hidden state and backpropagating through the whole net; better still, reframe the task as text (e.g. natural-language inference fed as
- Emergent in-context learning (GPT-3). Very large LMs perform tasks without gradient updates, just from examples placed in the prompt — the in-context examples specify the task and the conditional distribution mimics performing it. Not finetuned, still not fully understood.
- Where the field went after these notes (2020–21), for orientation (verified against current ground truth, not in the source): decoder-only models came to dominate; instruction tuning + RLHF (reinforcement learning from human feedback) aligns raw LMs into assistants; scaling laws made size/data/compute the main lever; and context lengths, retrieval augmentation, and mixture-of-experts pushed the efficient-attention agenda of §5 much further.
Implications
- Pretraining decouples learning the representation (once, on cheap unlabeled text) from using it (cheap finetuning) — the economic shift behind modern NLP.
- Decoder/encoder/encoder-decoder is the same Transformer with a different masking + reconstruction objective; the objective, not the architecture, sets what the model is good at.
Core competency set
- Explain BPE and the pretrain→finetune paradigm and why it helps.
- Contrast GPT (autoregressive decoder), BERT (masked encoder + 80/10/10), T5 (span-corruption encoder-decoder) by objective and capability; state GPT-3 in-context learning.
8. Memorize cold
- Distributional semantics: meaning = context; embeddings are dense vectors replacing orthogonal one-hots.
- Skip-gram ; center gradient = observed − expected.
- SGNS ; noise unigram. GloVe .
- RNN ; LM loss CE ; perplexity . BPTT: ; clip exploding gradients.
- LSTM cell , — additive cell ⇒ gradient highway (≈ ResNet skip). GRU = update + reset gate, no cell.
- Attention: scores → → output . QKV = weighted summary of values by query-key match. Beam search keeps top- by length-normalized log-prob; BLEU = n-gram precision + brevity penalty.
- Self-attention ; stops the softmax saturating. Multi-head: heads of dim , concat, mix with . Positional encoding added (sinusoid/learned). Causal mask = future scores .
- Transformer encoder block: self-attn → add&norm → FFN → add&norm. Decoder: masked self-attn → add&norm → cross-attn (Q decoder, K/V encoder) → add&norm → FFN → add&norm. Cost .
- Shapes: tensor is ; linear/FFN/layernorm act per-token on the last axis (, broadcast over ); attention mixes ; batch norm mixes . Block maps — the residual stream.
- Batch vs layer norm (both rescale by ): batch norm averages per feature across the batch (stats , needs test-time running stats); layer norm averages per token across its features (stats , batch/length-independent → used in transformers).
- Pre-norm (clean residual highway, trains deep, standard) vs post-norm (original, needs warmup).
- FFN: , position-wise, , params (~⅔ of the model).
- Pretraining: BPE subwords; GPT = autoregressive decoder; BERT = masked LM, 15% with 80/10/10; T5 = span corruption. GPT-3 = in-context learning, no gradient steps.
Named moves (cross-track glossary): distributional-meaning (context defines the vector); observed-minus-expected (word2vec gradient = softmax/logistic gradient, track 11a); negative-sampling (turn a big softmax into binary discrimination); share-weights-across-time (RNN, cf. convolution’s share-across-space); Jacobian-product-through-time (the vanishing-gradient villain); additive-gradient-highway (LSTM cell / GRU / ResNet skip / Transformer residual — one idea); score-softmax-weighted-sum (the attention recipe); query-key-value (content-addressable summary); attention-is-all-you-need (drop recurrence for parallel all-pairs); scale-by- (keep the softmax unsaturated); read-shapes-by-axis (: linear/FFN/LN per-token, attention mixes , batch norm mixes ); normalize-per-token-not-per-batch (layer norm vs batch norm); pre-norm-residual-highway (LN inside the branch, stream unbroken); residual-plus-layernorm (train deep stacks); causal-mask (no peeking ahead); pretrain-then-finetune (learn the representation once); objective-not-architecture (GPT/BERT/T5 differ by masking + reconstruction goal); in-context-learning (task from the prompt, no gradients).