Architectures/The Transformer Architecture

Lesson 6.62,563 words

The Transformer Architecture

The Transformer is the architecture built around the attention mechanism. This first part assembles the full encoder–decoder of "Attention Is All You Need" — embeddings and positional encoding, stacked self-attention and feed-forward sublayers wrapped in residual connections and LayerNorm, masked decoding and cross-attention — works through causal masking and the three modern families (encoder-only, decoder-only, encoder–decoder), and accounts for where the parameters and the O(n2)O(n^2) compute actually go.

╌╌╌╌

The previous lesson built the attention mechanism: scaled dot-product attention, multi-head projection, and the positional encoding that restores order to a permutation-equivariant operation. That is the operation. This lesson assembles the architecture: how those operations stack into the encoder–decoder of Attention Is All You Need, how the stack splits into the three families that dominate modern practice, and where its parameters and its quadratic cost actually live.1

The sublayer wrapper

The atom of the architecture is not a layer but a sublayer wrapper: a residual skip around a function , followed by layer normalization. Every attention block and every feed-forward block in the entire model is wrapped this way, so we fix the convention before stacking anything.

The expansion is not arbitrary. The FFN takes each token's -vector, projects it up into a wider space, applies a pointwise nonlinearity there, and projects back down to . The wide hidden layer is where the per-token computation happens: it gives the nonlinearity enough room to compute many independent features of the token before compressing the result. The original paper used ; most modern stacks swap in (a smooth gate , with the standard-normal CDF) or a gated variant like , which lowers loss at fixed width for reasons that remain partly empirical.

Track the shapes explicitly. A batch of sequences of length enters as a tensor of shape . Every operation below preserves the batch and sequence axes and acts only on the last (feature) axis:

The same apply at every one of the positions — the FFN carries no positional index and no cross-token interaction, which is what makes it a position-wise map.

Layer normalization is the other half of the wrapper, so its statistics matter for what follows. Given a single token vector , LayerNorm computes the mean and variance over the feature entries of that one token — not over the batch, not over the sequence — and standardizes:

with learned per-feature scale and shift (initialized to and ), and for numerical safety. Because the reduction is per-token, LayerNorm is independent of batch size and of the other positions — it behaves identically at training and inference and needs no running statistics — the reason it replaced BatchNorm for variable-length sequence models.2 The single addition it contributes is parameters ( and ) per LayerNorm.

The two wrapper styles differ only in where the normalization sits relative to the residual sum.

StyleSublayer formulaResidual path
Post-norm (original)passes through LN at every layer
Pre-norm (modern)clean identity, never normalized

The distinction looks cosmetic but governs whether a deep stack trains at all.2

Post-norm breaks that identity: each residual sum is squeezed back through a LayerNorm, so the gradient path is a product of normalization Jacobians and can vanish or explode with depth, which is why post-norm Transformers need a learning-rate warmup and pre-norm ones largely do not.

Post-norm (left) routes every skip through LayerNorm; pre-norm (right) normalizes only the branch input, leaving a clean identity highway (blue) up the stack.

Positional encoding

Attention is permutation-equivariant: shuffle the input tokens and the output set is the same, merely reordered. That is fatal for language, where dog bites man and man bites dog are different sentences built from identical tokens. The attention operator has no notion of position, so order has to be injected into the inputs before the first layer. The original Transformer adds a fixed sinusoidal positional encoding to the token embeddings.

The denominator sets the wavelength of each feature: the lowest feature () oscillates with period tokens, and the highest () with period tokens. Low-frequency channels change slowly and encode coarse, long-range position; high-frequency channels distinguish adjacent tokens. Together they give each position a unique fingerprint across a geometric band of scales, the same multi-resolution idea a place-value numeral uses to name any integer with a fixed set of digits.

Sinusoidal positional encoding as a frequency band. Each feature slot carries a sine/cosine of period : low- channels (top) oscillate fast and separate adjacent tokens; high- channels (bottom) oscillate slowly and encode coarse position.

Two properties make the sinusoidal choice more than a lookup table:

  • Relative position is linear. For any fixed offset , the encoding at is a fixed linear function (a rotation, from the angle-sum identities) of the encoding at . A single learned projection inside an attention head can therefore read relative distance, not just absolute index, which is what a language model actually needs.
  • Length extrapolation. Because the formula is defined for every real , a model can be evaluated on sequences longer than any it saw in training without a new parameter — the encoding simply continues.

The alternative is a learned positional embedding: a trainable table with one row per position, added just like a word embedding. Learned embeddings match or slightly beat sinusoids on in-distribution data and are the common choice for encoder-only models (BERT) and ViT, but they cap the context at the table's row count and cannot extrapolate past it. Modern decoder-only models mostly use neither and instead rotate the queries and keys inside attention (rotary embeddings, RoPE), which keeps the linear-relative property while removing the additive table entirely.

One encoder layer

An encoder layer is two wrapped sublayers in series: multi-head self-attention, then a position-wise FFN. With pre-norm wrapping and an input ,

The self-attention is unrestricted: every position attends to every other, so each output position is a content-weighted summary of the whole input. This is the right behavior for an encoder: the entire sequence is available and there is no causality constraint.

Every tensor in the block has the same shape : the width is the invariant of the residual stream, so a layer's output plugs into the next layer's input without any reshaping. Trace one block for a concrete configuration , heads (so head width ), , input :

StepOperationOutput shape
0input
1 (per-token, over the features)
2project to , split into heads each
3scores , softmax over keys
4weighted values, concat heads
5output projection , add residual
6, up-project to
7ReLU, down-project, add residual

The only place the shape swells is the score tensor in step 3 and the FFN hidden in step 6 — the two costs, quadratic-in- and wide-FFN, that the accounting section makes precise.

Shapes through one pre-norm encoder block (, , , ). The width is the residual-stream invariant; only the attention scores () and FFN hidden ( wide) inflate before collapsing back to .
One encoder layer: multi-head self-attention then a position-wise FFN, each wrapped in add-and-norm. The blue arcs are the residual connections around each sublayer.

One decoder layer

A decoder layer has three wrapped sublayers. It must generate one token at a time without access to tokens it has not yet produced, and it must read the encoder. Two additions handle these requirements.

  • Masked self-attention. Before the softmax, the decoder sets the score for every , forbidding position from attending to any later position. Generation stays causal: token depends only on tokens .
  • Cross-attention. A middle sublayer draws its queries from the decoder state but its keys and values from the encoder's output. This is the channel through which a generated token reads the entire source sequence; in translation it is how each output word reads the sentence being translated.3
SublayerQueries fromKeys / values fromMask
Masked self-attentiondecoderdecodercausal (lower-triangular)
Cross-attentiondecoderencoder outputnone
Feed-forward

The full encoder–decoder

The complete Transformer stacks encoder layers and decoder layers, feeds both stacks token embeddings plus positional encodings, and routes the encoder's final output into the cross-attention sublayer of every decoder layer. A linear projection and softmax convert the decoder's top state into a distribution over the vocabulary.

The full encoder–decoder Transformer. The encoder (left) reads the source; its output feeds cross-attention (green) in every decoder layer, which masks self-attention and reads out through linear-plus-softmax.

The asymmetry is the whole point. The encoder reads bidirectionally because it sees the input all at once; the decoder reads causally because it produces the output left to right. Cross-attention is the only place the two streams meet.

Causal masking in detail

Masking is implemented additively, before the softmax. Define a mask matrix with for and for , and add it to the raw scores:

The entries become after exponentiation, so the softmax renormalizes over only the allowed (lower-triangular) positions. The result is row-causal: row of has support only on columns through .

The causal mask. Query row attends only to key columns : the lower triangle (blue) is kept, the upper triangle (shaded, ) is blocked before the softmax.
Algorithm:MaskedSelfAttention(X)\textsc{MaskedSelfAttention}(X) — causal scaled dot-product attention
  1. 1
    QXWQQ \gets X W_Q; KXWKK \gets X W_K; VXWVV \gets X W_V
  2. 2
    SQKT/dkS \gets Q K^{T} / \sqrt{d_k}
    n×nn \times n raw scores
  3. 3
    for each i,ji, j with j>ij > i do
  4. 4
    SijS_{ij} \gets -\infty
    forbid attending to the future
  5. 5
    for each row ii do
  6. 6
    Aisoftmax(Si)A_{i} \gets \softmax(S_{i})
    mass only on jij \le i
  7. 7
    return AVA V
    each row blends past values only

The three families

The encoder and decoder were designed to work as a pair, but each half is a complete model on its own. Modern practice splits the architecture into three families, distinguished by which stack they keep, how they mask attention, and what objective they train against.

FamilyStructureAttention maskingTraining objectiveExamples
Encoder-onlyencoder stack, bidirectionalnone (full self-attention)masked language modeling (predict held-out tokens)BERT, RoBERTa
Decoder-onlydecoder stack, no cross-attentioncausal (lower-triangular)autoregressive LM (next-token prediction)GPT, LLaMA
Encoder–decoderboth stacks, cross-attentionencoder full, decoder causalseq2seq (conditional generation)original Transformer, T5

The split follows directly from the masking. An encoder-only model sees the whole sequence, so it is built for understanding (classification, retrieval, token tagging) and is trained by corrupting input tokens and reconstructing them. A decoder-only model masks causally, so each position predicts the next token, making it a pure generator; this is the family that scaled into large language models. An encoder–decoder keeps both and is built for transduction: mapping one sequence to another, as in translation or summarization.4

The three families. Encoder-only (BERT) attends bidirectionally; decoder-only (GPT) masks causally; encoder–decoder (T5) joins both halves by cross-attention (green).

The residual stream

A productive way to read the stack is as a residual stream: a fixed-width -dimensional bus running from the embeddings to the output head. Each sublayer reads a normalized copy of the stream, computes an update, and writes that update back by addition. No sublayer overwrites the stream; they only accumulate into it.

This linear-accumulation view explains why Transformers are so editable: because contributions add, an attention head and an FFN can read each other's writes, and the final representation is literally the embedding plus every increment the sublayers added.

The residual stream. A fixed-width bus (black) runs up the stack; each block reads a normalized view (black) and writes an additive update back (green), never overwriting it.

Where the parameters and the compute live

Two accounting questions decide how a Transformer scales: where do its weights sit, and what dominates its runtime. Both have clean closed forms.5

Parameters. Per layer, attention contributes the four projection matrices , each , for . The FFN contributes and ; with that is . So per layer,

Two-thirds of a Transformer's weights live in the feed-forward networks, not the attention — a fact that motivates much of the work on sparsifying or scaling the FFN (mixture-of-experts) rather than attention.

The count ignores the small additive terms — the biases ( per layer) and the two LayerNorms' ( per layer) — which are linear in and vanish against the quadratic weights for any real width. Put , (the base configuration) into the table to see the actual per-layer budget:

ComponentFormulaShare
Attention
Feed-forward ()
LayerNorm (, two per layer)
Per layer total

A -layer encoder of this width holds weights in its blocks; the token embedding and output projection add on top, which for a vocabulary is another — a reminder that at small depth the vocabulary table, not the blocks, can dominate the count.

Compute. The cost split is reversed. The FFN is linear in sequence length — per layer — but the attention matrix is quadratic.

The crossover is at : for the per-layer cost is dominated by the projection and FFN work, but once the attention term takes over and grows quadratically. This single is the reason context windows are expensive and the target of nearly every efficient-attention variant.

Per-layer cost vs. sequence length (log–log). The projection/FFN term is linear (black); attention is quadratic (blue). They cross near , after which attention dominates.

That is the architecture and its cost model. The same design turns out to be indifferent to what a token is — image patches, DNA bases, or program tokens all work — and the decoder-only half of it scaled into the large language models that dominate current practice. Those applications, and the empirical scaling laws that make scale pay off so reliably, continue in Transformers in Practice.

Takeaways

  • The Transformer is attention plus position-wise feed-forward layers, stacked with residual + LayerNorm wrappers, with no recurrence or convolution anywhere.
  • Pre-norm () leaves a clean identity path up the stack, so deep Transformers train stably; post-norm () squeezes every residual through a norm and needs warmup.
  • Sinusoidal positional encoding gives each position a unique fingerprint across a geometric band of frequencies, makes relative offsets a linear map, and extrapolates past the training length; learned tables and rotary (RoPE) encodings are the modern alternatives.
  • The encoder attends bidirectionally; the decoder adds masked self-attention (causal, lower-triangular) and cross-attention to the encoder output, and reads out through linear + softmax.
  • The three families specialize the design: encoder-only (BERT, masked LM, understanding), decoder-only (GPT, causal LM, generation), encoder–decoder (T5, seq2seq, transduction).
  • Causal masking realizes the autoregressive factorization in a single parallel forward pass.
  • The residual stream view reads the stack as a fixed-width bus each sublayer reads from and adds back into, never overwriting — which is why contributions compose so cleanly.
  • Two-thirds of the parameters live in the FFN ( vs per layer), while compute is dominated by the attention term — the quadratic cost that bounds context length.

Footnotes

  1. Chollet, Deep Learning with Python, Ch. 11 — The Transformer Architecture: assembling embeddings, positional encoding, stacked attention + FFN sublayers, and the read-out head into the full model.
  2. Goodfellow, Deep Learning, §8.7.1 — Batch/normalization and §8.7.5 residual connections: why a clean identity path (here pre-norm) stabilizes optimization of very deep stacks. 2
  3. Chollet, Deep Learning with Python, Ch. 11 — The Transformer decoder: causal (masked) self-attention plus cross-attention to the encoder output for sequence-to-sequence generation.
  4. Chollet, Deep Learning with Python, Ch. 11 — encoder-only vs. decoder-only vs. encoder–decoder usage: how the masking and objective pick out BERT-style, GPT-style, and T5-style models.
  5. Goodfellow, Deep Learning, §10.11 — Explicit Memory & attention: the content-addressed read whose cost scales quadratically in sequence length, the bottleneck behind efficient-attention work.

╌╌ END ╌╌