Transformers/The Transformer Architecture

Lesson 5.22,073 words

The Transformer Architecture

This part takes the scaled dot-product attention of the previous lesson and assembles the full transformer architecture around it: multi-head attention so several relations can be read at once, the transformer block of residual connections and layer norm that makes deep stacks trainable, positional embeddings that restore word order, the decoder-only language model, and the encoder, decoder, and encoder-decoder shapes — closing with the 2017 paper and the pre-norm, FlashAttention, and RoPE refinements that scaled it up.

╌╌╌╌

This builds on Transformers and Self-Attention, which developed the attention operation: from each input, project a query, key, and value; score each query against the keys; scale by , softmax into weights, and mix the values; and mask the future to make the layer causal. The rest of the transformer exists to run that operation in parallel across several relations at once and to stack it many layers deep. This part builds those pieces.

Multi-head attention

Two words can relate along several axes at once. In the keys to the cabinet were on the table, the verb were has a syntactic agreement link to keys, a semantic link to table, and a different link again to cabinet. A single attention layer produces one set of weights and so can emphasize only one kind of relationship at a time. Multi-head attention runs several attention operations in parallel, each with its own , so each head can specialize in a different relation.1

Each head projects the input into its own lower-dimensional space, of size , so that running heads costs about the same as one full-width head. The heads' outputs are concatenated and a final linear map mixes them back to the model dimension , keeping the layer's output shape equal to its input shape so the blocks can stack:

Multi-head attention: heads each run scaled dot-product attention with their own query/key/value projections over the same input, and their outputs are concatenated and projected down to by so the result matches the input shape.

The self-attention equation is unchanged inside each head; multi-head attention is copies of it plus a concatenation and one more linear layer.1

For example, take the original transformer's numbers: and heads, so each head works in . Each head's projections are , mapping a -dimensional input down to a -dimensional per-head space. A head produces an output; concatenating all eight gives , back to the model width, and is . The total parameter count of the four projection matrices is the same as one full-width single head would use: eight -dimensional views cost no more than one -dimensional view, because the width is split rather than multiplied.

The transformer block

One attention layer mixes information across positions but does little else. A transformer block wraps it in a position-wise feedforward network, residual connections, and layer normalization, which together make deep stacks trainable.2

  • Feedforward network. After attention has mixed information across positions, a small two-layer feedforward network is applied to each position independently, giving the block non-linear processing capacity on top of the linear value mixing.
  • Residual connections. Each sublayer adds its input back to its output, . This lets information and gradients skip the sublayer, giving upper layers direct access to lower ones and making very deep stacks trainable.
  • Layer normalization. After each residual add, the summed vector is normalized to zero mean and unit variance across its components (then rescaled by learned gain and offset), keeping activations in a range that gradient descent handles well.

The block computes attention, adds and normalizes, then applies the feedforward network, and adds and normalizes again:

Layer norm standardizes each vector using its own mean and standard deviation over its components, then applies learned gain and offset :

Because the block's input and output have the same shape, blocks stack directly, and a transformer is of them in sequence — the original transformer used , and modern language models use dozens.

One transformer block: multi-head self-attention and a feedforward network, each wrapped in a residual add (the input routed around the sublayer) followed by layer norm. The output shape matches the input, so blocks stack.

Positional embeddings

The block still cannot represent word order: self-attention is permutation-invariant. The output for position is a sum over the value vectors weighted by content-based scores; permute the inputs and the same permuted outputs come back. the dog bit the man and the man bit the dog would produce identical representations, which is clearly wrong. Recurrence encoded order for free by reading left to right; attention has to be told the order explicitly.3

The fix is a positional embedding: a vector that encodes where a token sits, added to its word embedding before the first block. The composite input carries both what the word is and where it stands.

There are two common recipes. Learned positional embeddings keep a trainable vector for each position up to some maximum length, learned alongside the word embeddings — simple, but positions near the length limit are seen rarely in training and generalize poorly. Sinusoidal positional embeddings instead compute each position with a fixed family of sines and cosines at geometrically spaced frequencies, so that nearby positions get similar vectors and the function extends smoothly to any length. The original transformer used the sinusoidal form.3

Positional embeddings restore word order: a learned or sinusoidal position vector is added to each word embedding , and the composite is what the first transformer block reads.

Transformers as language models

With the pieces assembled, a decoder-only transformer is a language model. Stack causal transformer blocks on top of the position-augmented embeddings, put a linear layer plus softmax over the vocabulary on top of the final block, and train it to predict the next word by teacher forcing with a cross-entropy loss — the same objective as the recurrent language model, but computed for every position in parallel, since each output depends only on earlier inputs and no serial recurrence links them.4

Algorithm:TransformerLM\textsc{TransformerLM} — next-token distributions for a whole sequence, in parallel
  1. 1
    input: token embeddings e1,,eN\mathbf{e}_1, \ldots, \mathbf{e}_N; positional embeddings p1,,pN\mathbf{p}_1, \ldots, \mathbf{p}_N
  2. 2
    for each position ii do
  3. 3
    xiei+pi\mathbf{x}_i \gets \mathbf{e}_i + \mathbf{p}_i
  4. 4
    H[x1;;xN]\mathbf{H} \gets [\mathbf{x}_1; \ldots; \mathbf{x}_N]
  5. 5
    for each block b=1,2,,Lb = 1, 2, \ldots, L do
  6. 6
    AMaskedMultiHead(H)\mathbf{A} \gets \mathrm{MaskedMultiHead}(\mathbf{H})
    causal mask: position ii sees only jij \le i
  7. 7
    HLayerNorm(H+A)\mathbf{H} \gets \mathrm{LayerNorm}(\mathbf{H} + \mathbf{A})
  8. 8
    HLayerNorm(H+FFN(H))\mathbf{H} \gets \mathrm{LayerNorm}(\mathbf{H} + \mathrm{FFN}(\mathbf{H}))
  9. 9
    for each position ii do
  10. 10
    yisoftmax(Whi)\mathbf{y}_i \gets \mathrm{softmax}(\mathbf{W}\,\mathbf{h}_i)
    distribution over next token
  11. 11
    return y1,,yN\mathbf{y}_1, \ldots, \mathbf{y}_N

Encoder, decoder, and decoder-only

The same block appears in three architectural shapes, distinguished by which attention masks they use and whether they read one sequence or two.5

  • Encoder-only. A stack of bidirectional transformer blocks that turns an input sequence into contextual representations, with no masking and no generation. This is the shape used for understanding tasks — classification, tagging, retrieval.
  • Encoder-decoder. An encoder reads the source with bidirectional attention; a decoder generates the target with causal attention, plus an extra cross-attention sublayer in each block. Cross-attention is ordinary attention with the queries coming from the decoder but the keys and values coming from the encoder's output, so each generated word attends over the whole source. This is the classic shape for machine translation.
  • Decoder-only. A single stack of causal blocks that both reads a prompt and continues it, with no separate encoder. This is the shape of the modern large language model.
Encoder-decoder with transformers. The encoder (bidirectional) maps the source to representations; each decoder block adds a cross-attention sublayer whose queries come from the decoder and whose keys and values come from the encoder output.

The 2017 paper and what came after

Everything above is the transformer of Vaswani et al., Attention Is All You Need (NeurIPS 2017), the paper that named the architecture and set its defaults.6 Their model was the encoder-decoder of the last section, with blocks on each side, , heads (so ), and a feedforward inner width of . Earlier translation systems added attention on top of a recurrent backbone; the paper's claim, reflected in the title, was that the recurrence could be deleted outright, leaving only attention. It reached state-of-the-art English-to- German translation while training in a fraction of the time, precisely because the layer parallelizes where recurrence serialized. The design has barely changed since; what changed is scale and a handful of refinements below.

Where the layer norm goes. The 2017 block put layer norm after the residual add — the post-norm arrangement of the equations above. Later work found this hard to train deep, because the residual stream is renormalized at every block and gradients to the earliest layers degrade. Moving the norm inside the residual branch, so it acts on the sublayer input rather than the sum — pre-norm, — keeps a clean residual path from input to output and lets stacks of dozens to hundreds of blocks train stably (Xiong et al., 2020).7 Essentially every large model today is pre-norm.

The quadratic cost, addressed two ways. Forming costs in both time and memory, which caps context length. Two lines of work address this. The first keeps exact attention but computes it without ever writing the matrix to memory: FlashAttention (Dao et al., 2022) tiles the computation and fuses the softmax so memory grows linearly in , turning long-context attention from memory-bound to compute-bound and delivering large wall-clock speedups with identical numerics.8 The second changes the operation to a cheaper approximation — sparse attention patterns (Child et al., 2019), low-rank or kernel approximations like Linformer and Performer — trading exactness for sub-quadratic scaling. In practice FlashAttention prevailed: at the context lengths in common use, exact attention computed efficiently outperformed the sub-quadratic approximations.

Positional information without an added vector. The sinusoidal and learned embeddings of the last section are absolute: they tag each token with its index. Rotary position embedding (RoPE; Su et al., 2021) instead rotates the query and key vectors by an angle proportional to their position, so that the dot product ends up depending only on the relative offset .9 Relative position is what attention usually needs — the adjective two words back, not the word at absolute index 47 — and RoPE extends more gracefully to sequences longer than any seen in training. It is now the default positional scheme in most open large language models.

None of these change the idea. Attention is still a query scored against keys, softmaxed into weights, mixing values. The refinements make it train deeper (pre-norm), run longer (Flash), and generalize across length (RoPE), but the operation in the numeric trace of the previous part is the one still running inside every current model.

This is the architecture the rest of modern NLP is built on. Scaled up and pretrained on enormous text corpora, the decoder-only transformer becomes the large language model; the deep-learning course gives the same machinery a second, complementary treatment. What made all of it possible is the one move in these two parts: replace the recurrent chain with a layer where every position attends directly to every other, in parallel.

Footnotes

  1. Jurafsky & Martin, §9.7.2 — Multihead Attention (Eqs. 9.43–9.45): parallel heads, each with its own projection matrices and dimension , capture different relations; head outputs are concatenated and projected by back to the model dimension. 2
  2. Jurafsky & Martin, §9.7.1 — Transformer Blocks (Eqs. 9.37–9.42): self-attention and a feedforward layer, each with a residual connection and layer normalization; layer norm standardizes a vector to zero mean and unit variance and rescales by learned and .
  3. Jurafsky & Martin, §9.7.3 — Modeling Word Order: Positional Embeddings: self-attention is order-agnostic, so a learned or sinusoidal positional embedding is added to each word embedding to encode absolute position. 2
  4. Jurafsky & Martin, §9.8 — Transformers as Language Models (Fig. 9.21): a decoder-style transformer trained by teacher forcing with cross-entropy to predict the next word, with all positions computed in parallel unlike the serial RNN.
  5. Jurafsky & Martin, Ch. 10, §10.6 — Encoder-Decoder with Transformers (Figs. 10.15–10.16): a bidirectional encoder and a causal decoder whose blocks add a cross-attention sublayer taking queries from the decoder and keys and values from the final encoder output.
  6. Vaswani, Shazeer, Parmar, Uszkoreit, Jones, Gomez, Kaiser, Polosukhin (2017), Attention Is All You Need, NeurIPS 2017. Introduces the transformer: an encoder-decoder built only from scaled dot-product multi-head attention and position-wise feedforward layers, with blocks per side, , heads (), feedforward width , and sinusoidal positional encodings. Reaches state-of-the-art WMT English-German/English-French translation at a large reduction in training cost relative to recurrent and convolutional baselines.
  7. Xiong, Yang, He, Zheng, Zheng, Xing, Zhang, Lan, Wang, Liu (2020), On Layer Normalization in the Transformer Architecture, ICML 2020. Shows analytically and empirically that the original post-norm placement produces large gradients near the output and unstable early training requiring learning-rate warmup, while pre-norm (layer norm inside the residual branch) yields well-behaved gradients and trains deep transformers stably.
  8. Dao, Fu, Ermon, Rudra, Ré (2022), FlashAttention: Fast and Memory-Efficient Exact Attention with IO-Awareness, NeurIPS 2022. An exact-attention algorithm that tiles the computation and fuses the softmax so the score matrix is never materialized in high-bandwidth memory; reduces memory from quadratic to linear in sequence length and gives substantial wall-clock speedups with numerically identical output.
  9. Su, Lu, Pan, Murtadha, Wen, Liu (2021), RoFormer: Enhanced Transformer with Rotary Position Embedding. Rotary position embedding rotates query and key vectors by a position-dependent angle so that the attention score depends only on the relative offset ; it improves length generalization and is widely adopted in open large language models. (See also Sennrich/Child/Linformer/Performer lines cited in text for sparse and approximate attention.)

╌╌ END ╌╌