Cheat sheets

BERT, GPT and T5 Compared

Encoder-only, decoder-only and encoder-decoder side by side. Objectives, masks, blocks, decoding and when to pick each.

  • Concepts and terms
  • Tasks and commands
  • Annotated code
  • Diagrams
  • Comparisons
  • Defaults and numbers
  • Troubleshooting
  • Questions and tips

Source

Three families side by side#

FactorBERTGPTT5 / BART
StackEncoder onlyDecoder onlyEncoder and decoder
AttentionBidirectional, no maskCausal triangle maskBidirectional encoder, causal decoder
Cross-attentionNoneNoneQ from decoder, K/V from encoder
ObjectiveMLM on 15% of tokensNext token, shift by oneSpan corruption or denoising
PredictsP(x_{\text{masked}} \mid x_{\text{unmasked}})P(x_t \mid x_{<t})Target spans or the clean sequence
Generates textNoYes, token by tokenYes, from the encoder output
Best forClassification, retrieval, NERChat, code, reasoningTranslation, speech to text
ExamplesBERT, DeBERTa, ModernBERTGPT, Llama, QwenT5, BART, Whisper

From Lesson 07.05, Lesson 07.06, Lesson 07.07, Lesson 07.08

Block wiring#

K, VclientSource tokensembed + positionprocessEncoder blockLN, self MHA, LN, FFNstoreEncoder output(N_src, d_model), runsonceclientTarget tokensshift by oneprocessMaskedself-attentionsublayer 1processCross-attentionsublayer 2processFFNsublayer 3modelNext-token logitsfinal LN + projectionK, VclientSource tokensembed + positionprocessEncoder blockLN, self MHA, LN, FFNstoreEncoder output(N_src, d_model), runsonceclientTarget tokensshift by oneprocessMaskedself-attentionsublayer 1processCross-attentionsublayer 2processFFNsublayer 3modelNext-token logitsfinal LN + projection

From Lesson 07.05, Lesson 07.08

One encoder-decoder forward pass#

1Embedtokens become vectors. Add RoPE or a sinusoidalposition signal.2Encodereach block runs pre-norm self-attention, thenpre-norm FFN, each with a residual.3Encoder outputthe encoder runs once per input. Cache it forlong inputs.4Decoder self-attentionmasked, so position i sees positions up to ionly.5Decoder cross-attentionthe only place encoder information enters thedecoder.6Decoder FFNthen a final LN before the output projection.7Checka 6-token source and a 5-token target giveoutput shape (5, vocab).

From Lesson 07.05, 07.05 code/main.py, Lesson 07.08

Tasks in the lesson code#

TaskCode
BERT 80/10/10 maskingcreate_mlm_batch(tokens, vocab_size)
Mask whole wordswhole_word_mlm(tokens, spans, vocab_size)
GPT causal maskcausal_mask(n)
Next-token losscross_entropy_shifted(logits, target_ids)
T5 span corruptioncorrupt_spans(tokens, mask_rate=0.15)
Rebuild the originalround_trip(source, target)
One encoder blockencoder_block(x, p)
One decoder blockdecoder_block(x, enc_out, p)

From 07.05 code/main.py, 07.06 code/main.py, 07.07 code/main.py, 07.08 code/main.py

Load each family#

tok = AutoTokenizer.from_pretrained("answerdotai/ModernBERT-base")
model = AutoModel.from_pretrained("answerdotai/ModernBERT-base")
out = model(**inputs).last_hidden_state(1, N, 768), embeddings only
model = AutoModelForCausalLM.from_pretrained("<model>")
out = model.generate(**inputs, max_new_tokens=64,
temperature=0.7, top_p=0.9, do_sample=True)sample a reply
model = T5ForConditionalGeneration.from_pretrained("google/flan-t5-base")
inputs = tok("translate English to French: <text>", return_tensors="pt")task name in the input
out = model.generate(**inputs, max_new_tokens=32)
print(tok.decode(out[0], skip_special_tokens=True))

From Lesson 07.06, Lesson 07.07, Lesson 07.08

Pretraining objectives#

MLM
select 15% of tokens. 80% become [MASK], 10% random, 10% unchanged.
Labels
the original token at selected positions. -100 at all other positions.
NSP
predict if sentence B follows A. RoBERTa showed it hurt. Modern encoders skip it.
Causal LM
input [t1, t2, t3], targets [t2, t3, t4]. Sum -\log P over positions.
Causal mask
M_{ij} = 0 if j \le i, else -\infty. Add it before softmax.
Span corruption
spans of mean length 3, 15% total, each replaced by <extra_id_0>, <extra_id_1>.
T5 target
only the corrupted spans, each after its sentinel.
BART
five noise functions. The decoder rebuilds the full original sequence.

From Lesson 07.06, Lesson 07.07, Lesson 07.08

Decoding strategies#

CommandWhat it does
sample_greedy(probs)Argmax each step. Code completion, deterministic tasks
sample_temperature(logits, t, rng)Divide logits by T. Higher T gives more diversity
sample_top_k(logits, k, rng)Sample from the top k tokens only
sample_top_p(logits, p, rng)Smallest set with cumulative prob at least p
sample_min_p(logits, min_p, rng)Keep tokens with p >= min_p * max_p
Beam searchWidth 4 to 5 for translation and summarization
Speculative decodingDraft model proposes N tokens. Big model verifies

From Lesson 07.07, 07.07 code/main.py, Lesson 07.08

Block: 2017 against 2026#

Component2017 block2026 block
NormalizationLayerNorm, post-normRMSNorm, pre-norm
FFN activationReLUSwiGLU
FFN expansion4×2.6× (three matrices)
PositionSinusoidal absoluteRoPE
AttentionFull MHAGQA (or MLA)
Bias termsYesNo

From Lesson 07.05

Defaults in the code#

SettingDefaultNote
mask_prob0.15BERT selection rate
IGNORE_INDEX-100Label at unselected positions
mask_rate0.15T5 share of tokens in spans
mean_span3.0T5 mean span length
mask_token<mask>BART mask and infill token
layer_norm eps1e-5Subtracts the mean
rms_norm eps1e-6No mean subtraction
temperature1.0softmax, top-k, top-p, min-p

From 07.05 code/main.py, 07.06 code/main.py, 07.07 code/main.py, 07.08 code/main.py

Use each family when#

  • Use BERT for classification, embeddings, NER, NLI and RAG rerankers. It runs 5 to 10× faster per token than decoders.
  • Do not use BERT for generation. The encoder cannot produce tokens autoregressively.
  • Use GPT for generation, chat, code and reasoning. Decoder-only scales cleanest.
  • Use min-p + temperature 0.7 as a default for open-weights models.
  • Use T5 or BART when the input is a clear source sequence: translation, speech, structured tasks.
  • Use beam search with an encoder-decoder. The output distribution is narrower than chat.
  • Summarization and extraction work with either encoder-decoder or decoder-only.

From Lesson 07.05, Lesson 07.06, Lesson 07.07, Lesson 07.08

Troubleshooting#

SymptomCauseFix
Model fails without [MASK] at fine-tuneTrained on 100% [MASK]Use the 80/10/10 rule
Model cheats by looking at the answerNo causal maskAdd the -inf triangle before softmax
Future weights not exactly zeroSoftmax never outputs an exact zeroPut -inf into future scores
Gradients vanish in a deep stackNo residual connectionsUse x + sublayer(x)
Activations explode after 12 layersPost-normSwitch to pre-norm
Corrupted span does not rebuildOff-by-one in span bookkeepingRun the round-trip check
Slow decode on long inputsEncoder runs again each stepCache the encoder output

From Lesson 07.05, Lesson 07.06, Lesson 07.07, Lesson 07.08

Questions#

Why can BERT use the right context?
The encoder has no causal mask.
Why is GPT training parallel?
One pass gives N next-token losses. Inference stays serial.
How many params in one block?
MHA is 4 · d². SwiGLU FFN is about 3rd².
Why is T5 pretraining cheaper than BART?
T5 decodes only the spans. BART decodes the full sequence.
Are embedding models BERT?
Yes. Same encoder, contrastive loss.

From Lesson 07.05, Lesson 07.06, Lesson 07.07, Lesson 07.08