Foundations to Frontier
Tests
F. NLP and Large Language Models › F4 Transformer Language Models

Encoder-Only (BERT), Decoder-Only (GPT) and Encoder–Decoder (T5)

Transformers come in three arrangements. Encoder-only models (BERT, RoBERTa) use bidirectional self-attention, so every token sees the whole input; they excel at understanding tasks such as classification, tagging and retrieval, but do not generate text naturally. Decoder-only models (GPT, LLaMA) use causal attention and generate token by token; given a prompt, they can do almost any task by producing the answer as text. Encoder–decoder models (T5, BART) read the input bidirectionally with an encoder and generate the output with a decoder that cross-attends to it; they suit transduction tasks such as translation and summarisation. This page covers the masks, pretraining objectives, cross-attention, costs and why decoder-only models now dominate. In the exercises you build the three attention patterns, then tag each token with a label that depends on the next token. Bidirectional attention scored 0.998. A causal decoder labelling each token at its own position scored 0.75, exactly the best possible without seeing the next token. Emitting each label one step later, after reading the needed token, gave 1.00.

Level 0: Foundation

★☆☆☆☆ Introductory⏱ 5 minGeneral audience. No mathematics required.

Three ways to wire a Transformer

An encoder reads the whole sentence at once, looking both ways, which is great for understanding (“is this report about an engine fault?”). A decoder writes text one token at a time, looking only backwards, which is great for generating answers. An encoder–decoder does both: one part reads the input, the other writes the output while glancing back at the input, as in translation. The demo shows the decoder’s one-way mask; an encoder’s would be a full square.

LLM lab
Row i shows what token i may attend to: itself and earlier tokens only (36 of 64 pairs). This is what lets one forward pass train on every next-token prediction at once.
Why engineers care

Choosing the architecture affects cost and accuracy: compact encoders classify and search millions of reports cheaply, while decoder models handle open-ended questions and report writing.

📝 Quick check (Level 0)
0/3 answered
  1. 1. An encoder attends…
  2. 2. A decoder is best at…
  3. 3. Translation classically uses…

Level 1: Beginner

★★☆☆☆ Basic⏱ 20 minSecondary-school mathematics: arithmetic and elementary algebra.

By hand

  • Encoder-only (BERT): bidirectional self-attention (T² pairs); pretrained by masked-LM (about 15% of positions are targets); a task head on top (classification uses the [CLS] vector, tagging uses each token’s vector).
  • Decoder-only (GPT): causal self-attention; pretrained by next-token prediction (every position is a target); tasks are posed as prompts and answered by generation. KV caching makes generation efficient (F8).
  • Encoder–decoder (T5, BART): encoder self-attention (bidirectional), decoder self-attention (causal) and decoder-to-encoder cross-attention (each decoder position attends to all encoder positions). With n layers each side there are 3n attention blocks. Pretrained by span corruption (T5) or denoising (BART).
  • Text-to-text: T5 phrases every task as input text → output text (“translate English to German: …”).
  • Today: large decoder-only models handle understanding, generation and translation via prompting; encoders remain the efficient choice for embeddings, retrieval and high-volume classification.
📝 Quick check (Level 1)
0/3 answered
  1. 1. Attention blocks in a 12 + 12-layer encoder–decoder:
  2. 2. Cross-attention lets the decoder attend to…
  3. 3. BERT's pretraining targets per 512 tokens (15%):

Level 2: Intermediate

★★★☆☆ Intermediate⏱ 25 minUndergraduate students and practising engineers.

The three architectures in code

Exercise 1.

  • Build encoder (full) and decoder (causal) attention patterns.
  • State the shape of cross-attention between decoder and encoder.
  • Format a task as T5 text-to-text.

Practice.

  • Hugging Face classes: AutoModelForSequenceClassification / AutoModelForTokenClassification (encoders), AutoModelForCausalLM (decoders), AutoModelForSeq2SeqLM (encoder–decoders).
  • For classification or retrieval at scale, a fine-tuned encoder (or embedding model) is usually cheaper and as accurate as a large decoder.
  • For generation with a decoder, put the input first and the output after it, so the output can attend to all of the input.
  • Encoder–decoders remain strong for translation, summarisation and speech recognition (Whisper).
from transformers import AutoTokenizer, AutoModelForSeq2SeqLM
tok = AutoTokenizer.from_pretrained("google/flan-t5-small"); t5 = AutoModelForSeq2SeqLM.from_pretrained("google/flan-t5-small")
ids = tok("summarize: The left engine showed high EGT during climb and was shut down as a precaution.", return_tensors="pt")
print(tok.decode(t5.generate(**ids, max_new_tokens=20)[0], skip_special_tokens=True))
🐍 Exercise 1: attention patterns and text-to-text
Build encoder and decoder masks, give the cross-attention shape, and format a T5 task string.
📝 Quick check (Level 2)
0/3 answered
  1. 1. Hugging Face class for encoder–decoders:
  2. 2. In a decoder prompt, the output should come…
  3. 3. Whisper (speech recognition) is…

Level 3: Advanced

★★★★☆ Advanced⏱ 25 minGraduate level, with full derivations and proofs.

Theory

Information each position can use. In an encoder every output depends on the whole input. In a decoder, output i depends only on positions ≤ i. A label that depends on later tokens therefore cannot be computed at position i by a decoder, whatever its size; it must be produced later, after the needed tokens have been read.

Why decoders took over. Decoder-only models train on every position (a denser signal than masked-LM), unify all tasks as text generation, scale simply and cache past keys and values for fast generation. Wang and colleagues (2022) found causal decoders best for zero-shot generalisation after pretraining, with encoder–decoders better after multitask fine-tuning.

Costs. Bidirectional encoders must recompute everything when the input changes, while decoders append. Encoder–decoders split parameters between reading and writing, which is efficient when inputs are long and outputs short (summarisation, ASR).

📝 Quick check (Level 3)
0/3 answered
  1. 1. A decoder's output at position i depends on…
  2. 2. Decoder pretraining gives a denser signal because…
  3. 3. Encoder–decoders are efficient when…

Level 4: Expert

★★★★★ Expert⏱ 30 minResearchers: original papers and open problems.

What can each attention pattern compute?

History.

  • J. Devlin et al., “BERT” (NAACL 2019).
  • A. Radford et al., “Language models are unsupervised multitask learners” (2019).
  • C. Raffel et al., “Exploring the limits of transfer learning with a unified text-to-text transformer” (JMLR 2020), T5.
  • T. Wang et al., “What language model architecture and pretraining objective work best for zero-shot generalization?” (ICML 2022).

Exercise 2.

  • Task: sequences of 12 tokens (vocabulary 10). Label each token 1 if the next token is larger, else 0, so the label needs information that comes after the token.
  • Model: the one-layer attention network from F4-1 with a 2-class output, in three set-ups:
    • encoder (bidirectional attention), label at each position;
    • decoder (causal attention), label at each position;
    • decoder emitting each label one step later (output after input, as in text-to-text generation).
  • Reference: the best possible accuracy without the next token (predict “larger” when the current token is small) is 0.75.
set-up accuracy
encoder, bidirectional 0.998
decoder, label at the same position 0.750
decoder, label one step later 1.000
best possible without the next token 0.750
  • Bidirectional attention solves the task because each position sees its successor.
  • A causal decoder hits a hard ceiling: at position i it cannot see token i + 1, and it reached exactly the 0.75 achievable from the current token alone.
  • Reordering the output fixes it: emitting the label after reading the needed token gives perfect accuracy. This is why decoder-only models put the answer after the input, and why encoder–decoders read first and write second.
  • Seed 1: 0.999, 0.746 and 0.998.
🐍 Exercise 2 (research): what can each attention pattern compute?
Tag tokens by a property of the next token using bidirectional attention, causal attention at the same position, and causal attention with the label emitted one step later.

Architectures in AI, robotics and aerospace

  • High-volume triage: fine-tuned encoders classify and route reports quickly and cheaply.
  • Assistants: decoder models answer engineering questions and draft documents.
  • Transduction: encoder–decoders for speech recognition of radio calls and summarisation of logs.
  • Design lesson: make sure every output can see the inputs it depends on; with a decoder, write the answer after the question.

References

  1. J. Devlin, M.-W. Chang, K. Lee and K. Toutanova (2019). “BERT: pre-training of deep bidirectional transformers for language understanding.” Proc. NAACL.
  2. C. Raffel et al. (2020). “Exploring the limits of transfer learning with a unified text-to-text transformer.” JMLR 21.
  3. M. Lewis et al. (2020). “BART: denoising sequence-to-sequence pre-training.” Proc. ACL.
  4. T. Wang et al. (2022). “What language model architecture and pretraining objective work best for zero-shot generalization?” Proc. ICML.