Simple Algorithm
Deep Learning · Representation · 24 min

The Transformer Block

Residual stream, normalization, feed-forward layers and positional information.

Attention moves information between positions; everything else in a transformer works on one position at a time. The block wraps the two in residual connections and normalization, receives positional information from somewhere, and is stacked dozens of times. Here you assemble it, count its parameters and FLOPs, and see which choices keep a deep stack trainable.

What you’ll learn

  • Write the pre-LN block x←x+Attn⁡(Norm⁡(x))\mathbf x\leftarrow\mathbf x+\operatorname{Attn}(\operatorname{Norm}(\mathbf x)), x←x+FFN⁡(Norm⁡(x))\mathbf x\leftarrow\mathbf x+\operatorname{FFN}(\operatorname{Norm}(\mathbf x)), contrast it with post-LN, and read the result as a residual stream.
  • Derive the parameter count of a block, about 12d212d^2 with dff=4dd_{\text{ff}}=4d, and of a whole model, about 12Ld212Ld^2 plus embeddings, and check it against GPT-2.
  • Compare learned absolute, sinusoidal, relative-bias, rotary and ALiBi position information.
  • Distinguish encoder and decoder blocks, place cross-attention, and explain tied input and output embeddings.
  • Derive the training cost of about 6N6N FLOPs per token, and the correction from attention, T/12dT/12d relative to the weights.

Two sublayers and a residual stream

A transformer block applies two sublayers to the sequence of token vectors X∈RT×dX\in\R^{T\times d}: multi-head attention, the only operation that mixes positions, and a position-wise feed-forward network (FFN), a two-layer MLP applied to every token separately with shared weights. In the pre-LN arrangement used by most models since GPT-2, each sublayer reads a normalized copy of its input and adds its result back:

X←X+MHA⁡(LN⁡(X)),X←X+FFN⁡(LN⁡(X)),FFN⁡(x)=W2 ϕ(W1x+b1)+b2X\leftarrow X+\operatorname{MHA}\big(\operatorname{LN}(X)\big),\qquad X\leftarrow X+\operatorname{FFN}\big(\operatorname{LN}(X)\big),\qquad\operatorname{FFN}(\mathbf x)=W_2\,\phi(W_1\mathbf x+\mathbf b_1)+\mathbf b_2
W1∈Rdff×dW_1\in\R^{d_{\text{ff}}\times d} and W2∈Rd×dffW_2\in\R^{d\times d_{\text{ff}}} with dff=4dd_{\text{ff}}=4d in the original design; ϕ\phi was ReLU in 2017 and GELU in GPT and BERT. Layer normalization standardizes each token's vector and applies a learned scale and shift.
python
import torch.nn as nn

class Block(nn.Module):
    """Pre-LN decoder block: x + Attn(LN(x)), then x + FFN(LN(x))."""
    def __init__(self, d, n_heads):
        super().__init__()
        self.ln1, self.ln2 = nn.LayerNorm(d), nn.LayerNorm(d)
        self.attn = MultiHeadAttention(d, n_heads)    # from Self-Attention & Multi-Head Attention
        self.ffn = nn.Sequential(nn.Linear(d, 4 * d), nn.GELU(), nn.Linear(4 * d, d))

    def forward(self, x):                             # x: (B, T, d), the residual stream
        x = x + self.attn(self.ln1(x), causal=True)   # read a normalized copy, add the result
        x = x + self.ffn(self.ln2(x))
        return x

A post-LN block, as in the 2017 paper, would instead compute x = ln1(x + attn(x)) and x = ln2(x + ffn(x)), normalizing after each addition.

The residual stream. Unroll the additions over LL blocks: the final state of every token is its embedding plus the sum of everything each sublayer wrote,

h(L)=h(0)+∑ℓ=1L(a(ℓ)+f(ℓ)).\mathbf h^{(L)}=\mathbf h^{(0)}+\sum_{\ell=1}^{L}\Big(\mathbf a^{(\ell)}+\mathbf f^{(\ell)}\Big).

Each sublayer reads the current sum through a normalization and writes an increment, so the stream acts as a shared communication channel (Elhage et al., 2021): an attention head in layer 3 can read what a feed-forward layer in layer 1 wrote. The Emergence lesson Reading the Residual Stream decodes intermediate states directly.

Pre-LN versus post-LN. In pre-LN the stream itself is never normalized, so the gradient has an identity path from the loss to every layer. In post-LN every path passes through a normalization; Xiong et al. (2020) showed that at initialization the gradients near the output are then large, which is why post-LN transformers needed a learning-rate warmup, while pre-LN ones can train without it. GPT-2 moved normalization to the input of each sub-block and added a final one after the last block (Radford et al., 2019). Normalization & Stability in Transformers follows the story to the instabilities of large models.

Check your understanding

Which property of the pre-LN block is missing from the post-LN block?

  1. An identity path along the residual stream from the output back to the embeddings, untouched by any normalization
  2. Attention between positions
  3. A learned scale and shift in the normalization
  4. A feed-forward network at every position
Show the answer

A. An identity path along the residual stream from the output back to the embeddings, untouched by any normalization

Pre-LN adds each sublayer's output to an unnormalized stream, so ∂h(L)/∂h(0)\partial\mathbf h^{(L)}/\partial\mathbf h^{(0)} contains the identity. Post-LN normalizes after every addition, so every gradient path passes through 2L2L normalizations, which produces the large gradients near the output at initialization that Xiong et al. (2020) analyzed.

Counting parameters

DerivationParameters of one block and of a model
  1. Pattn=4d2+4dP_{\text{attn}}=4d^2+4d

    Attention has WQ,WK,WV,WO∈Rd×dW_Q,W_K,W_V,W_O\in\R^{d\times d} and four bias vectors (Self-Attention & Multi-Head Attention):

  2. Pffn=2⋅d⋅4d+4d+d=8d2+5d,PLN=2⋅2d=4dP_{\text{ffn}}=2\cdot d\cdot4d+4d+d=8d^2+5d,\qquad P_{\text{LN}}=2\cdot2d=4d

    The FFN has two d×4dd\times4d matrices and biases of sizes 4d4d and dd; the two LayerNorms have a gain and a bias each:

  3. Ntotal≈12Ld2⏟non-embedding N+∣V∣ d⏟tokens+Tmax⁡ d⏟positionsN_{\text{total}}\approx\underbrace{12Ld^2}_{\text{non-embedding }N}+\underbrace{|\mathcal V|\,d}_{\text{tokens}}+\underbrace{T_{\max}\,d}_{\text{positions}}

    So a block holds 12d2+13d12d^2+13d parameters, two-thirds of them in the FFN. A model adds a token embedding E∈R∣V∣×dE\in\R^{|\mathcal V|\times d}, learned position vectors if it uses them, a final LayerNorm, and an output layer, which is often the embedding itself (below):

Predict before you look

GPT-2's smallest model has L=12L=12, d=768d=768, a vocabulary of 50,25750{,}257 tokens, 1,0241{,}024 learned positions and an output layer tied to the token embedding. How many parameters does it have in total, in millions?

Show the answer

124.4 M

Blocks: 12×(12×7682+13×768)=85.0512\times(12\times768^2+13\times768)=85.05M. Token embedding: 50,257×768=38.6050{,}257\times768=38.60M. Positions: 0.790.79M. Final LayerNorm: 1,5361{,}536. Total 124,439,808124{,}439{,}808. Embeddings are 32% of this small model but a negligible fraction of large ones, which is why scaling laws count only the non-embedding 12Ld212Ld^2.

Tied embeddings. The output layer maps the final state to a logit for every token, ℓ=WU LN⁡(h(L))\boldsymbol\ell=W_U\,\operatorname{LN}(\mathbf h^{(L)}) with WU∈R∣V∣×dW_U\in\R^{|\mathcal V|\times d}, the same shape as the embedding table. Press and Wolf (2017) and Inan, Khosravi and Socher (2017) proposed setting WU=EW_U=E, which saves ∣V∣ d|\mathcal V|\,d parameters and gave better language models at the time; the original transformer shared these weights too, scaling the embeddings by d\sqrt d. Many large models of the mid-2020s untie them again, since the saving is small at their scale.

Two-thirds of a block's weights sit in the FFN, which is therefore the natural place to add capacity without adding computation: a mixture of experts replaces it by several FFNs and a router that sends each token to one or two of them.

Where position comes from

Without position information, self-attention is permutation-equivariant, so every transformer injects position somewhere: added to the inputs, added to the attention scores, or rotated into the queries and keys. A causal mask leaks some position information by itself, but all major models add it explicitly. The main schemes, in one line each:

SchemeWhat it doesKindUsed in
Learned absolutea learned vector pt\mathbf p_t added to the embedding of position t≤Tmax⁡t\le T_{\max}absolute; undefined beyond Tmax⁡T_{\max}BERT, GPT-2
Sinusoidalfixed sines and cosines of geometrically spaced frequencies added to the embeddingabsolute, fixed; offsets act as rotationsthe original transformer
Relative representationslearned vectors for each offset j−ij-i, clipped at a maximum distance, added to the keys and valuesrelative, learnedShaw, Uszkoreit & Vaswani (2018)
Relative bias bucketsone learned scalar per head and offset bucket added to the score; 32 buckets growing logarithmically up to offset 128, shared across layersrelative, learnedT5 (Raffel et al., 2020)
Rotary (RoPE)queries and keys rotated in 2-D pairs by angles proportional to their positions, in every layerrelative in the score, fixedSu et al. (2021); most open LLMs of the mid-2020s
ALiBia fixed penalty −mh(i−j)-m_h(i-j) added to the scores, with a different slope mhm_h per headrelative, fixedPress, Smith & Lewis (2022)
Relative schemes make the score depend on the offset i−ji-j rather than on ii and jj separately, which helps a model behave consistently at positions it has not seen together. The Artificial Intelligence course's lesson Positional Encodings derives RoPE's relative-position property and ALiBi's soft windows.

The choice matters most for length. A model with learned absolute positions has no vector for position Tmax⁡+1T_{\max}+1 at all. Sinusoidal codes and rotary angles are defined everywhere but produce combinations never seen in training beyond Tmax⁡T_{\max}, so rotary models are extended by rescaling positions or frequencies and fine-tuning briefly. ALiBi's penalty confines most heads to a recent window, which keeps perplexity stable on longer inputs but does not by itself make distant tokens useful.

Check your understanding

Which scheme changes the attention scores but adds nothing to the token embeddings, and depends only on the distance between query and key?

  1. Learned absolute positions
  2. Sinusoidal positions
  3. ALiBi
  4. None: every scheme adds a vector to the embeddings
Show the answer

C. ALiBi

ALiBi subtracts mh(i−j)m_h(i-j) from each score of head hh and leaves the embeddings alone. T5's bucketed biases are similar but learned; RoPE also leaves the embeddings alone but rotates queries and keys instead of adding to the scores.

Encoders, decoders and the output

BlockSublayers, each with a residual connection and normalizationUsed in
Encoderself-attention without a mask, then FFNBERT; the encoder half of T5 and of the original transformer; vision transformers
Decoder-onlycausal self-attention, then FFNthe GPT series and most large language models
Decoder of an encoder–decodercausal self-attention, then cross-attention to the encoder's output, then FFNthe original transformer, T5, Whisper
The three differ only in masking and in where keys and values come from; the FFN, residual additions and normalizations are the same.

In an encoder–decoder model the encoder runs once over the input, and every decoder block's cross-attention reads the encoder's final states, projected to keys and values separately in each layer. A decoder-only model has no cross-attention: it reads the input as the beginning of its own sequence, so one stack serves both roles. At the top, a final normalization and the output layer turn each position's state into logits over the vocabulary; in a decoder, position tt predicts token t+1t+1.

Think first An encoder–decoder translator and a decoder-only model both translate a 100-token sentence into a 100-token sentence. Where does each one look up the source sentence while writing the translation?

The encoder–decoder encodes the source once with bidirectional attention; each decoder layer's cross-attention then queries those 100 encoder states. The decoder-only model sees the source as the first 100 tokens of its own sequence, so the translation's tokens attend to them through ordinary causal self-attention, and the source tokens themselves are processed causally, each seeing only the source tokens before it.

FLOPs per token

DerivationForward and training cost
  1. Cdense≈2NFLOPs per tokenC_{\text{dense}}\approx2N\quad\text{FLOPs per token}

    Multiplying a vector by an m×nm\times n weight matrix costs 2mn2mn FLOPs, one multiply and one add per weight. Every weight of the blocks is used once per token, so the dense part of the forward pass costs twice the non-embedding parameter count:

  2. Cattn≈L⋅4⋅T2⋅d=2LTd,CattnCdense=2LTd2⋅12Ld2=T12dC_{\text{attn}}\approx L\cdot4\cdot\frac T2\cdot d=2LTd,\qquad\frac{C_{\text{attn}}}{C_{\text{dense}}}=\frac{2LTd}{2\cdot12Ld^2}=\frac{T}{12d}

    Attention adds work that no weight accounts for. A token at position tt forms tt scores and a weighted sum of tt values, 2td+2td2td+2td FLOPs per layer. Averaged over a causal sequence of length TT, t≈T/2t\approx T/2:

  3. Ctrain≈6N+6LTdFLOPs per token,C≈6ND  for D training tokensC_{\text{train}}\approx6N+6LTd\quad\text{FLOPs per token},\qquad C\approx6ND\ \text{ for }D\text{ training tokens}

    The backward pass computes, for every weight matrix, a gradient with respect to its input and one with respect to the weights, each as costly as the forward product: about twice the forward pass. Training therefore costs about three forward passes:

  4. 6×(1.75×1011)×(3×1011)≈3.15×10236\times(1.75\times10^{11})\times(3\times10^{11})\approx3.15\times10^{23}

    Example: GPT-3 has N≈175N\approx175 billion parameters and was trained on about 300300 billion tokens, so 6ND≈3.15×10236ND\approx3.15\times10^{23} FLOPs, matching the 3.14×10233.14\times10^{23} Brown et al. (2020) report. With its d=12,288d=12{,}288 and T=2,048T=2{,}048 the attention term adds only T/12d≈1.4%T/12d\approx1.4\%. Neural Scaling Laws builds on C≈6NDC\approx6ND.

Predict before you look

A model with width d=4096d=4096 is trained on sequences of T=32,768T=32{,}768 tokens. How large is the attention term relative to the dense term 2N2N, in percent?

Show the answer

67 %

T/12d=32,768/49,152≈0.67T/12d=32{,}768/49{,}152\approx0.67. At T=4096T=4096 it would be only about 8%. Long-context training is where the quadratic part of attention stops being a rounding error, which motivates the kernels of Efficient Transformers.

Key takeaways

  • A pre-LN block adds attention and an FFN to an unnormalized residual stream, X←X+MHA⁡(LN⁡(X))X\leftarrow X+\operatorname{MHA}(\operatorname{LN}(X)) then X←X+FFN⁡(LN⁡(X))X\leftarrow X+\operatorname{FFN}(\operatorname{LN}(X)), keeping an identity path that makes deep stacks trainable without warmup; post-LN normalizes after each addition.
  • A block has 12d2+13d12d^2+13d parameters with dff=4dd_{\text{ff}}=4d, two-thirds in the FFN; a model has about 12Ld212Ld^2 plus ∣V∣d|\mathcal V|d for embeddings (124.4 million in total for GPT-2 small, with tied output weights).
  • Position enters as learned or sinusoidal vectors added to the input, learned relative biases on the scores, rotations of queries and keys (RoPE) or fixed distance penalties (ALiBi); relative schemes depend only on the offset.
  • Encoder, decoder-only and encoder–decoder blocks differ only in masking and cross-attention; decoder-only models read their input as a prefix.
  • Training costs about 6N6N FLOPs per token, C≈6NDC\approx6ND in total, with attention adding a fraction T/12dT/12d that matters only for long contexts.

Check yourself

In the interactive lesson these are scored with your confidence, and what you miss comes back for review.

Question 1

A decoder has L=24L=24 blocks of width d=1024d=1024 with dff=4dd_{\text{ff}}=4d. About how many non-embedding parameters does it have?

  1. About 2525 million
  2. About 100100 million
  3. About 1.21.2 billion
  4. About 300300 million
Show the answer

D. About 300300 million

12Ld2=12×24×10242≈3.0×10812Ld^2=12\times24\times1024^2\approx3.0\times10^8. With GPT-2's vocabulary and 1,024 learned positions this is GPT-2 medium, about 355 million parameters in total.

Question 2

Which update is a pre-LN block?

  1. X←LN⁡(X+MHA⁡(X))X\leftarrow\operatorname{LN}\big(X+\operatorname{MHA}(X)\big), then X←LN⁡(X+FFN⁡(X))X\leftarrow\operatorname{LN}\big(X+\operatorname{FFN}(X)\big)
  2. X←X+MHA⁡(LN⁡(X))X\leftarrow X+\operatorname{MHA}\big(\operatorname{LN}(X)\big), then X←X+FFN⁡(LN⁡(X))X\leftarrow X+\operatorname{FFN}\big(\operatorname{LN}(X)\big)
  3. X←MHA⁡(LN⁡(X))X\leftarrow\operatorname{MHA}\big(\operatorname{LN}(X)\big), then X←FFN⁡(LN⁡(X))X\leftarrow\operatorname{FFN}\big(\operatorname{LN}(X)\big)
  4. X←LN⁡(MHA⁡(X)+FFN⁡(X))X\leftarrow\operatorname{LN}\big(\operatorname{MHA}(X)+\operatorname{FFN}(X)\big)
Show the answer

B. X←X+MHA⁡(LN⁡(X))X\leftarrow X+\operatorname{MHA}\big(\operatorname{LN}(X)\big), then X←X+FFN⁡(LN⁡(X))X\leftarrow X+\operatorname{FFN}\big(\operatorname{LN}(X)\big)

Each sublayer reads a normalized copy and adds its output to the unnormalized stream, keeping an identity path for gradients. The first option is the original post-LN block.

Question 3

About how many FLOPs does it take to train a model with N=109N=10^9 non-embedding parameters on 101110^{11} tokens, ignoring attention?

  1. 2×10202\times10^{20}
  2. 6×10206\times10^{20}
  3. 102010^{20}
  4. 6×10296\times10^{29}
Show the answer

B. 6×10206\times10^{20}

6ND=6×109×1011=6×10206ND=6\times10^9\times10^{11}=6\times10^{20}: 2N2N per token forward and about 4N4N backward.

Question 4

What does tying the input and output embeddings do?

  1. It uses the token embedding table as the output layer's weights, saving ∣V∣ d|\mathcal V|\,d parameters
  2. It forces the model to output the same token it reads
  3. It shares the attention weights across layers
  4. It ties each position's embedding to its token
Show the answer

A. It uses the token embedding table as the output layer's weights, saving ∣V∣ d|\mathcal V|\,d parameters

The logits become E LN⁡(h(L))E\,\operatorname{LN}(\mathbf h^{(L)}): a token's score is the inner product of the final state with that token's own embedding. In GPT-2 small this saves 38.6 million of the 124 million parameters.

Go deeper

Further reading

  • A. Vaswani, N. Shazeer, N. Parmar, J. Uszkoreit, L. Jones, A. N. Gomez, Ł. Kaiser & I. Polosukhin, "Attention is all you need," NeurIPS (2017).
  • R. Xiong et al., "On layer normalization in the transformer architecture," ICML (2020).
  • N. Elhage et al., "A mathematical framework for transformer circuits," Transformer Circuits Thread (2021).
  • J. Kaplan et al., "Scaling laws for neural language models," arXiv:2001.08361 (2020).
  • O. Press & L. Wolf, "Using the output embedding to improve language models," EACL (2017).