§3.1The Transformer Architecture

Part I NLPT pp. 1–4 · ~8 min read

  • transformer
  • encoder-decoder architecture
  • encoder
  • decoder
  • token embedding
  • positional embedding
  • encoder-only
  • decoder-only
  • encoder-decoder

In [Chapter 2 of the full book] we saw how to fine-tune and use a transformer ; this chapter opens the hood and builds one from scratch in PyTorch. We start from the original 2017 architecture, assemble a working encoder piece by piece, peek at the decoder, and finish with a tour of the model zoo. A deep grasp of the internals isn’t strictly needed to apply transformers, but it is what lets you reason about their limits and adapt them to new domains.

Recap from Chapter 2 (assumed background). Text is first tokenized into sub-word units, each mapped to an integer input id; an embedding lookup table then turns each id into a dense vector. Everything below operates on those vectors.

The encoder–decoder architecture

The original Transformer was designed for sequence-to-sequence problems such as machine translation, and uses an encoder–decoder architecture with two halves:

  • The encoder converts an input sequence of tokens into a sequence of embedding vectors — the hidden state or context.
  • The decoder uses that hidden state to iteratively generate an output sequence of tokens, one at a time.
ENCODERTime flieslike an arrowtokenized inputtoken +positional emb.Encoder ×Nhidden states(K, V)DECODERDie Zeitfliegt wie einoutput so fartoken +positional emb.Decoder ×Nlinear +softmax headnext token„Pfeil“K, V fed to every decoder block
Figure 3-1 (recreated). The encoder reads the whole input at once; the decoder consumes the encoder’s keys and values and generates the output autoregressively.

Three things about the architecture are already visible:

  1. Positions are injected on purpose. Because attention is order-blind (see §3.4), the token embeddings are summed with positional embeddings so the model knows where each token sits.
  2. Both halves are stacks. The encoder is a stack of identical encoder layers (“blocks”), much like stacking convolutional layers in vision; the decoder has its own stack.
  3. The encoder feeds the decoder. The encoder’s output is handed to every decoder layer, which then predicts the most probable next token — and that prediction is fed back in to produce the next one, until an end-of-sequence (EOS) token appears.

Watch the decoder generate

Step through translating “Time flies like an arrow” into German. Notice the encoder runs once, while the decoder loops — each predicted token becomes part of the next step’s input.

Autoregressive decoding: the encoder runs once; the decoder generates “Die Zeit fliegt wie ein Pfeil” one token at a time, feeding each prediction back in.
source (encoded): Time flies like an arrow output so far:

1Encode the source

The encoder reads the whole English sentence at once and turns it into a set of hidden states (keys and values). The decoder has produced nothing yet; it will start from a special begin-of-sequence token.

step 1 / 8

Zooming into the encoder

The encoder is a stack of identical layers, each of which takes a sequence of embeddings and passes them through two sublayers: a multi-head self-attention layer and a position-wise feed-forward layer. Crucially, the output embeddings have the same shape as the inputs — a layer’s job is to update each embedding with context (the word “apple” drifts toward “company” when “keynote” or “phone” sits nearby). That shape-preserving property is what lets us stack the layers.

encoder block× 6
x_out (same shape)
x_in (embeddings)

Click a sublayer to see what it does. Data flows bottom → top; the output has the same shape as the input.

Each sublayer is also wrapped in a skip connection and layer normalization — standard tricks for training deep networks that we add in §3.4. For now, the takeaway is the two-sublayer shape. To really understand the encoder we have to go deeper, starting with its beating heart: the self-attention layer.

Three flavors of transformer

Although the original design pairs an encoder with a decoder, each half was soon used on its own. Almost every model you’ll meet is one of three types.

The three transformer families. Click any cell for detail.
Encoder-onlyDecoder-onlyEncoder–decoder
AttentionBidirectionalCausal / autoregressiveBi- + causal + cross
Context a token seesleft + rightleft onlywhole source + output so far
Example modelsBERT, RoBERTa, DistilBERTGPT, GPT-2/3, CTRLT5, BART, M2M-100
Best suited toclassification, NER, extractive QAtext generation, autocompletetranslation, summarization
Dotted-underlined cells have explanations — click one.
  • Encoder-only models (BERT and friends) build a rich representation using bidirectional attention — great for classification, NER, and extractive QA (Ch. 7).
  • Decoder-only models (the GPT family) auto-complete text using causal (autoregressive) attention , where each token sees only what came before it.
  • Encoder–decoder models (T5, BART) map one sequence to another — translation, summarization.

Note — the boundaries are fuzzy

The split isn’t absolute. Decoder-only GPT models can be primed to do translation (conventionally a seq-to-seq task), and encoder-only BERT can be coaxed into summarization. The categories describe a model’s natural fit, not a hard limit.

With the map in hand, let’s descend into the mechanism that makes all three work — self-attention.

Check yourself: the transformer architecture

1.What does the encoder produce from an input sequence of tokens?

2.Why must positional embeddings be added to the token embeddings?

3.During autoregressive decoding, what is fed back into the decoder at each step?

4.You need a model for extractive question answering and text classification. Which family fits best?

5.Predict: in a decoder-only (GPT-style) model, which tokens can position 3 attend to?

5 questions