Vibe Engines is free, interactive AI engineering & system design — runs in your browser. Pick a learning path →
T5,
explained.
NLP in 2019 was a zoo — a different model head for classification, another for translation, another for question answering, each with its own quirks. T5 asked a disarmingly simple question: what if every task were just text in, text out? One model, one loss, one format. That reframing, plus a giant clean dataset and a rigorous study of what actually matters, made T5 both a strong model and a map of the whole field.
Contents 20 sections
The delta The task zoo The big idea: everything is text-to-text Why one format is such a win The architecture: full encoder-decoder Span corruption and the C4 corpus The real contribution: a systematic study The limits Why it still matters How it works The math The evidence T5 trade-offs: one text interface against task heads and decoder-only models Common mistakes when fine-tuning or reproducing T5 Where T5 shows up in production Since then Solve it yourself Questions Check yourself Where this sitsWhat changes against BERT: every task becomes one task
BERT (rung 1) gives you a representation and then a different head, a different loss and a different output format for each task — classification, span extraction, regression. T5's change is to delete that variety: every task is text in, text out. Translation, summarisation, sentiment, even a regression target are all expressed as a string to be generated. One model, one loss, one interface.
Stated in rung 1's units: BERT's largest useful configuration was 340M parameters; T5's largest is 11B, a ~32× jump. And where BERT was pre-trained on a curated corpus of books and Wikipedia, T5 introduces a filtered web-scale corpus (C4), which is the first appearance on this ladder of the idea that the dataset is a designed artefact rather than a given.
The other reason this rung matters for what follows: the paper is explicitly an empirical survey. It holds the text-to-text interface fixed and ablates the rest — architecture, objective, corpus, training length — to find which choices actually pay. That methodology is the ancestor of rungs 4 and 5, which do the same thing to a single question.
The task zoo
Post-BERT, transfer learning had swept NLP: pre-train once, fine-tune per task. But "fine-tune" hid a mess. Classification bolted a softmax head on the [CLS] token. Span-extraction tasks predicted start/end positions. Sequence tagging labeled every token. Translation used a separate encoder-decoder entirely. Each task had its own output layer, its own loss, its own plumbing.
That fragmentation made it hard to compare ideas cleanly — was a gain due to the model, the objective, the data, or the task-specific head? The T5 authors wanted one framework general enough to express every task the same way, so they could study what really drove transfer learning without the confound of a dozen architectures.
The big idea: everything is text-to-text
T5's move is to treat every NLP problem as mapping an input string to an output string. No task-specific heads. The label isn't a class id — it's the literal word. Sentiment analysis outputs the text "positive." Translation outputs the translated sentence. Even regression-style tasks output a number rendered as text.
A short task prefix in the input tells the model which job to do. Prepend "translate English to German:" and the same model translates; prepend "summarize:" and it summarizes. One model, one training objective, one decoding process — the task lives in the words, not the architecture.
Why one format is such a win
Uniformity buys leverage. Because every task shares the same input/output shape and loss (predict the next token of the target text), a single set of hyperparameters, a single fine-tuning procedure, and a single model can cover them all. You can even train on many tasks at once — multi-task learning — simply by mixing their examples, since they're already the same format.
It also makes the model a clean experimental testbed. Want to know if a different pre-training objective helps? Swap it and re-measure across every task with no architecture changes. That controlled comparability is exactly what the paper was built to exploit.
The architecture: full encoder-decoder
Where BERT kept only the Transformer's encoder and GPT kept only the decoder, T5 uses the full encoder-decoder — the original Transformer shape. The encoder reads the input text bidirectionally; the decoder generates the output text one token at a time, attending to the encoder. Because the output is always generated text, this design fits the text-to-text framing naturally.
The paper's careful comparison found that for this unified, generation-based setup, the encoder-decoder generally beat the decoder-only and prefix-LM alternatives it compared (encoder-only models were not tested, since they cannot generate text) — a reminder that the "best" architecture depends on how you frame the problem, not an absolute ranking.
Span corruption and the C4 corpus
T5's pre-training task is span corruption. Take a sentence, drop out random contiguous spans of words, replace each with a unique sentinel token, and train the model to generate the missing spans as its target text. It's masked language modeling reimagined for text-to-text: instead of predicting single hidden tokens in place, the model produces the removed pieces as an output sequence. Concretely, with two spans dropped:
input: the quick <extra_id_0> fox <extra_id_1> the lazy dog …
target: <extra_id_0> brown <extra_id_1> jumps over <extra_id_2>
The sentinels line up input to target, so the pair is perfectly invertible — the original is fully reconstructable.
Feeding this needs data — enormous, clean data. So the team built C4, the Colossal Clean Crawled Corpus: ~750GB of English web text scraped from Common Crawl and aggressively filtered to strip boilerplate, duplicates, offensive text, and non-English pages. C4 outlived the paper, becoming a standard pre-training corpus across the field.
The name is literal: T5 = Text-To-Text Transfer Transformer — five T's. The whole thesis is compressed into the acronym.
The real contribution: a systematic study
T5 is as much a survey as a model. Using the unified framework as a control, the authors ran a huge, methodical sweep: which architecture, which pre-training objective, which dataset, how much data, which fine-tuning and multi-task strategy, and how it all scales. Because every variant shared the same text-to-text harness, the comparisons were unusually clean.
| Question studied | T5's finding (roughly) |
|---|---|
| Architecture | encoder-decoder wins for text-to-text |
| Objective | span corruption > token masking here |
| Data | bigger, cleaner (C4) helps |
| Scale | bigger models keep improving |
The flagship T5 model (11 billion parameters) set state-of-the-art on many benchmarks, but the durable value is the recipe and the ablations — a well-lit map of which knobs matter for transfer learning, backed by a single consistent framework.
The limits
Text-to-text is elegant but not free. Emitting labels as text is slower than a classification head reading off one logit, and generation can produce outputs outside the valid label set that you must constrain or post-process. The encoder-decoder also has roughly double the parameters of a decoder-only model at the same depth.
And T5 still fine-tunes per task — it predates the in-context, prompt-only paradigm that GPT-3 popularized the same year. It's the peak of the "pre-train then fine-tune" era rather than a step beyond it, and it inherits that era's hunger for labeled data at fine-tuning time.
Why it still matters
The text-to-text idea won. Framing tasks as strings — with an instruction in the input and an answer in the output — is exactly how we prompt modern chat models. When you type "summarize this" or "translate to French" to an assistant, you're using T5's mental model, now scaled up and made zero-shot.
T5's descendants (mT5 for multilingual, Flan-T5 for instruction tuning, and others) remain workhorses for encoder-decoder tasks like summarization and translation. And its greatest gift may be methodological: it showed the value of a unified framework plus rigorous ablation, a template for how to study these systems honestly rather than chase one benchmark.
T5 turned "different task, different model" into "different words, same model." Prompting a chat model — instruction in, answer out — is that idea grown up and made instant.
How T5 trained its baseline and its final models, step by step
T5 is two things at once: a controlled experiment and a final model. The experiment fixes one baseline recipe and changes one component at a time; the final models combine the winners and scale them up. The baseline, which every ablation starts from, runs like this.
- Write every task as text. Each example becomes an input string with a task prefix and a target string. Classification targets are label words. STS-B, a similarity regression scored from 1 to 5, is rounded to the nearest 0.2 and written out as a number string, which turns regression into a choice among 21 strings.
- Filter a web crawl into C4. Starting from the April 2019 Common Crawl text, keep only lines that end in terminal punctuation; drop pages with fewer than three sentences and lines with fewer than five words; drop any page containing a word from a list of obscene words, the placeholder phrase lorem ipsum, or a curly brace, a cheap detector for code; drop lines mentioning Javascript and cookie or privacy-policy boilerplate; keep one copy of any three-sentence span that repeats; and keep only pages that langdetect labels English with probability at least 0.99. About 750 GB of text remains.
- Tokenize. One SentencePiece vocabulary of 32,000 wordpieces is shared by input and output. Because some tasks are translation, it was trained on C4 mixed with German, French and Romanian text in a 10:1:1:1 ratio.
- Corrupt spans. Drop 15% of the tokens, replace each run of consecutive dropped tokens with one unique sentinel, and make the target the sentinels followed by the tokens they replaced. The final models switch to sampling spans directly, with a mean length of 3.
- Build the encoder-decoder. Twelve blocks in the encoder and twelve in the decoder, dmodel = 768, 12 heads and a feed-forward size of 3,072: about 220M parameters, roughly twice BERT-BASE because there are two stacks. Layer normalization has no bias and sits outside the residual path, and position enters as a learned scalar added to each attention logit, bucketed by relative distance (32 buckets, reaching out to 128 tokens) and shared across layers.
- Pre-train. 2^19 = 524,288 steps on batches of 128 sequences of 512 tokens, packed to about 2^16 = 65,536 tokens, so about 34B tokens in all, which the paper notes is far less than BERT or RoBERTa saw. The optimizer is AdaFactor with an inverse-square-root learning-rate schedule.
- Fine-tune and decode. Each task is fine-tuned separately for 2^18 = 262,144 steps at a constant learning rate of 0.001, saving a checkpoint every 5,000 steps and reporting the best one on the dev set. Decoding is greedy.
The final models
The winners go into five sizes: Small (about 60M parameters), Base (220M), Large (770M), 3B and 11B. Each is pre-trained for 1M steps on batches of 2^11 sequences of 512 tokens, about 1 trillion tokens, on a multi-task mixture of span corruption and the supervised tasks, and then fine-tuned per task. The 11B model is wide rather than deep: 24 blocks per stack, dmodel 1,024, a 65,536-wide feed-forward layer and 128 attention heads.
The objective, the learning-rate schedule and the task-mixing rule
x— the input string, a task prefix plus corrupted text or the task input;y— the target string. The same teacher-forced cross-entropy is used for pre-training and for every fine-tuning task.n— the training step;k— warmup steps. The rate holds at 0.01 for the first 10,000 steps and then falls as 1/√n.em— the number of examples in task m;K— an artificial cap, so a huge task such as unsupervised C4 cannot drown the small ones;T— a temperature applied to the capped rates.
At the extremes: with K → ∞ and T = 1 the mix is plain examples-proportional, and the unsupervised task takes almost every sample. As T → ∞ the mix becomes equal across tasks, which over-samples tiny tasks until they overfit while large ones are undertrained; equal mixing was markedly the worst strategy in the paper's comparison.
What the T5 study ran, and what it found
Every ablation is the baseline with one change, scored after fine-tuning on GLUE, SuperGLUE, SQuAD, CNN/Daily Mail summarization and WMT English to German, French and Romanian. The baseline averages 83.28 on GLUE. Trained from scratch with no pre-training, the same network scores 66.22, and SQuAD falls from 80.88 to 50.31, while English to French barely moves (39.82 against 39.77 BLEU), because that task alone has plenty of labeled data.
| Question | Variants compared | Finding |
|---|---|---|
| Architecture | encoder-decoder; same with shared weights; 6+6 layers; decoder-only LM; prefix LM | Encoder-decoder best; sharing weights lost little at half the parameters; halving depth hurt; the plain LM was clearly worst, the prefix LM in between |
| Objective family | prefix LM, BERT-style denoising, deshuffling | Denoising won; deshuffling was clearly worst |
| Corruption rate | 10%, 15%, 25%, 50% | Little difference up to 25%; 50% hurt |
| Span length | independent tokens vs mean spans of 2, 3, 5, 10 | Short spans matched or slightly beat independent masking with shorter targets; 10 was slightly worse |
| Pre-training data | C4, unfiltered C4, RealNews-like, WebText-like, Wikipedia, Wikipedia + Toronto Books | Removing the filters hurt every task; small in-domain corpora won on matching tasks |
| Data repetition | C4 truncated so it repeats 64 to 4,096 times | 64 repeats barely hurt; 1,024 and more hurt badly, and training loss showed memorization |
| Multi-task training | proportional, temperature-scaled and equal mixing | Multi-task alone trailed pre-train-then-fine-tune; multi-task pre-training followed by fine-tuning matched it |
At publication the 11B model set the state of the art on most of the benchmarks it was tested on, GLUE and SuperGLUE among them; on SuperGLUE it scored 88.9 against a human baseline of 89.8. The clearest negative result is translation: T5 did not reach the state of the art on any of the WMT pairs, which the authors attribute to English-only pre-training and to not using back-translation, a technique the best translation systems relied on.
T5 trade-offs: one text interface against task heads and decoder-only models
Text-to-text buys one model, one loss and one serving path for every task. It pays for that at inference: a label becomes a short generation instead of one forward pass, and the encoder-decoder carries two stacks.
| Encoder + task head (BERT) | Encoder-decoder (T5) | Decoder-only | |
|---|---|---|---|
| Parameters at the same depth | One stack | About twice, two stacks | One stack |
| Classifying one input | One pass, read one logit | Encode once, then decode the label tokens | Read the whole prompt, then decode |
| Output always valid | Yes, fixed label set | No, may emit a string that is not a label | No |
| Long input, short output | Fits, no generation | Fits well: encoder reads input once, decoder cross-attends | Every input token sits in the cache during decoding |
| New task | New head and new loss | New prefix and data, same code | New prompt, often no training |
The sweet spot is input-heavy generation with modest outputs, such as summarization and translation, where the encoder's bidirectional read of the source is worth the extra stack.
Common mistakes when fine-tuning or reproducing T5
- Borrowing BERT's learning rate
T5 was fine-tuned with AdaFactor at a constant 0.001, fifty times BERT's 2e-5. The optimizers differ, but copying BERT's range into AdamW makes T5 look weak when the setting is at fault; Hugging Face's T5 docs suggest 1e-4 to 3e-4 for AdamW.
- Running bfloat16 weights in float16
The checkpoints were trained in bfloat16 on TPUs. Some activations exceed float16's range, and fp16 inference or fine-tuning can produce NaNs or garbage. Use bf16 or fp32.
- Scoring generated labels by exact match
The model may emit
positve, a paraphrase, or a label from another task. Exact match counts these as wrong, and that hides how often it happens. Rank each valid label string by its likelihood, or constrain decoding to the label set, and log out-of-set outputs. - Dropping or changing the task prefix
The released checkpoints were pre-trained on a multi-task mixture keyed by prefixes such as
summarize:. Fine-tuning without one works, but mixing prefixed and unprefixed data, or reusing a prefix for a different task, invites interference from what the prefix already means. - Treating the ablation winners as universal
The study fixed a budget near 34B tokens and a 220M baseline. Its rankings of objectives and architectures hold at that scale; the authors themselves warn they may not hold at another. Re-check a choice at your own size before building on it.
Where T5 shows up in production
- Summarization and translation models
Fine-tuned T5, multilingual mT5 and instruction-tuned Flan-T5 checkpoints are still common choices for summarization, rewriting and translation services that need a small model with a fixed task.
- Text encoders for image generation
Google's Imagen conditions its diffusion model on a frozen T5-XXL encoder, and Stable Diffusion 3 uses a T5 encoder alongside CLIP. The encoder half of T5 turns out to be a strong general text representation.
- Libraries and data
Hugging Face Transformers provides
T5ForConditionalGeneration, and its tokenizer reserves the<extra_id_N>sentinels used for span corruption. C4 is distributed through TensorFlow Datasets and the Hugging Face hub. - In interviews
Common questions: encoder-decoder against decoder-only at matched compute, span corruption against BERT-style masking, how to make a classifier's generated output safe, and why the instruction-plus-answer format of chat models descends from task prefixes.
What the authors admit, and what happened next
The paper is unusually direct that its results are relative, not absolute: it compares choices under a fixed budget, and it warns that the winning configuration at one scale need not win at another. Read after rung 5, that caveat is close to prophetic — several of the field's later corrections are exactly the case of a conclusion drawn at one scale failing at a larger one.
It also concedes that the encoder-decoder shape it lands on costs roughly twice the parameters of a decoder-only model for the same layer count, and justifies it on measured quality rather than principle.
How it held up: the text-to-text interface won completely — every instruction-following model on rungs above this one is text in, text out, and the "prompt" is that interface under a different name. The encoder-decoder architecture did not win; the field went decoder-only from rung 3 onward, largely for generation efficiency. The survey methodology won twice over, and the C4-style filtered web corpus became the default base of every pre-training mix until rung 6 questions filtering itself.
Corrupt a sentence like T5 does
T5's entire pre-training signal is one text-to-text transformation, and it's small enough to implement. This drops random contiguous spans from a sentence, swaps each for a unique sentinel in the input, and packs the removed spans behind matching sentinels in the target — the actual span-corruption objective. The proof that it's a well-posed task: reconstruct(input, target) returns the original exactly. Change the corruption rate or span length and watch the input, target, and reconstruction update.
Write the body of reconstruct. Everything else in the file is
already written; this is the function the paper is about. Press ▶ Run to check it against
the 5 assertions below — they start red.
- Corruption collapses spans, so the input is shorter than the original
- Every sentinel in the input reappears in the target
- Input + target reconstruct the original exactly
- The corruption rate is about the requested 15%
- The sentinels in the input are all distinct
Questions people ask about T5
How does T5's span corruption choose and replace tokens?
In the baseline, 15% of tokens are chosen independently at random, and each run of consecutive chosen tokens is collapsed into a single sentinel token, with a different sentinel for each run. The target lists each sentinel followed by the tokens it hid, and ends with a final sentinel. For the final models the authors sampled spans directly, with an average span length of 3 tokens, keeping the 15% rate. Because several hidden tokens share one sentinel, both input and target are shorter than with one mask per token, which makes each training step cheaper. In the paper's comparisons, short average spans performed about as well as independent masking, a span length of 10 was slightly worse, and corrupting 50% of tokens hurt.
What filtering rules were used to build the C4 dataset?
C4 starts from the April 2019 Common Crawl text. The T5 paper keeps only lines that end in a period, exclamation mark, question mark or closing quote; discards pages with fewer than three sentences and lines with fewer than five words; removes pages containing any word from a public list of obscene words, pages with lorem ipsum placeholder text, and pages containing a curly brace, which mostly flags code; removes lines that mention Javascript and lines of cookie or privacy-policy boilerplate; deduplicates by keeping one copy of any three-sentence span that appears more than once; and keeps only pages that langdetect classifies as English with probability at least 0.99. About 750 GB of text survives.
Why did T5 use an encoder-decoder instead of a decoder-only model?
Because it won the paper's controlled comparison. The authors compared architectures at matched compute rather than matched parameters: an encoder-decoder with L layers in each stack has about twice the parameters of an L-layer decoder-only model but roughly the same cost per example, since the encoder processes only the input and the decoder only the target. With the denoising objective, the encoder-decoder scored best; sharing weights between encoder and decoder cost little; a decoder-only language model was clearly worst; and a prefix LM, a decoder that sees its input bidirectionally, landed in between. Encoder-only models were not compared, because they cannot generate text. Later large models went decoder-only, mainly for generation efficiency.
Does repeating pre-training data hurt, according to T5?
Yes, once the repetition is heavy. The authors truncated C4 so that the fixed pre-training budget of about 34 billion tokens repeated a smaller set 64, 256, 1,024 or 4,096 times. Sixty-four repeats barely moved downstream scores, while at 1,024 and 4,096 repeats performance dropped substantially and the training loss fell in a way that suggested memorization. Their advice was to use large pre-training corpora where possible. Muennighoff and colleagues (2023) later measured the trade-off directly and found that up to about four repetitions are nearly as good as fresh data, with returns falling off sharply after that.
How did T5 mix tasks for multi-task training?
Three ways. Examples-proportional mixing samples each task in proportion to its size, but with an artificial cap K, so the huge unsupervised task cannot swamp the rest. Temperature-scaled mixing raises each capped rate to the power 1/T and renormalizes, which flattens the mix toward small tasks as T grows. Equal mixing samples every task equally. Training on a multi-task mixture alone generally fell short of pre-training then fine-tuning, and equal mixing was markedly worse, because small tasks were seen too often and overfit while large ones were undertrained. Multi-task pre-training followed by fine-tuning on each task matched the standard recipe, and that is what the final T5 models used.
How many tokens was T5 pre-trained on?
Two very different amounts, depending on which models you mean. The baseline used in every ablation was pre-trained for 524,288 steps on batches of about 65,536 tokens, roughly 34 billion tokens, which the authors note is far less than BERT or RoBERTa saw. The final models, from 60 million to 11 billion parameters, were pre-trained for 1 million steps on batches of 2,048 sequences of 512 tokens, about 1 trillion tokens, on a mixture of span corruption over C4 and the supervised tasks. That roughly thirtyfold increase in training is one reason the final models improved so much on the baseline.
4 questions to test what you just read
Work each one out before you open it — a number, a prediction or a reason, not a definition. Producing the answer is what makes it stick. Your progress is kept on this device.
The T5 baseline trains for 2^19 steps on batches of about 2^16 tokens. How many tokens is that, and how many times more did the final models see?
Show answer
2^19 × 2^16 = 2^35 ≈ 34B tokens. The final models ran 10^6 steps × 2,048 sequences × 512 tokens ≈ 1.05 × 10^12, about 30× more. So every ablation in the study was run on a small fraction of the final training budget.
In a prefix-LM mask over 5 tokens with a 2-token prefix, which positions can token 1 attend to, and which can token 4?
Show answer
Token 1 is in the prefix, so it sees both prefix tokens, 1 and 2 — including token 2, which comes after it. Token 4 is in the target, so it sees the whole prefix plus targets up to itself: 1, 2, 3 and 4. The prefix is bidirectional; everything after it is causal.
Three tasks have 400,000, 100,000 and 10,000 examples. With examples-proportional mixing capped at K = 200,000, what are the sampling rates, and what does T = 2 do to them?
Show answer
Capped sizes 200k, 100k and 10k sum to 310k, so the rates are 0.645, 0.323, 0.032. With T = 2, take square roots (0.803, 0.568, 0.180) and renormalize: about 0.52, 0.37, 0.12. The smallest task's share more than triples.
Why do spans with a mean length of 3 make training cheaper than masking 15% of tokens independently?
Show answer
Each run of hidden tokens costs one sentinel. Independent masking leaves most hidden tokens isolated: a 512-token input hides about 77 tokens in about 65 runs, so the target is about 140 tokens. With spans averaging 3, the same 77 tokens fall in about 26 spans and the target is about 100. The input shrinks by the same sentinel count.
Pre-training, and the scaling laws
The ladder where rung 5 overturns rung 4. Read `scaling-laws` before `chinchilla` — the second measures the same axis in the same units and gets a different answer.
Explore the topic
See this alongside everything else on the same subject — handbooks, system designs, challenges and tools, in one place.
More Paper Breakdowns
- Attention Is All You NeedThe paper that introduced the Transformer — the architecture underneath GPT, BERT, Claude, and Gemini. Self-attention, Query/Key/Value, multi-head attention, positional encoding, and the real BLEU results, explained in depth with analogies and animated visuals, not just equations.Read →
- BERTThe paper that made "pre-train once, fine-tune anywhere" the default for NLP. Bidirectional context, masked language modeling, next-sentence prediction, the [CLS]/[SEP] tokens, and the GLUE sweep — explained with analogies, not just equations.Read →
- Chain-of-Thought PromptingShow a model a few worked examples with their reasoning and it starts solving problems it used to fail. Why reasoning emerges only at scale, the GSM8K jump, zero-shot "Let's think step by step", and how CoT seeded modern reasoning models.Read →
- LoRAThe paper that made fine-tuning affordable. Freeze the giant pretrained model and train two tiny low-rank matrices instead — up to 10,000x fewer trainable parameters, no extra inference latency, and swappable per-task adapters. The road to QLoRA and PEFT.Read →
- Direct Preference OptimizationRLHF without the RL. Align a model to human preference pairs with one simple classification-style loss — no separate reward model, no unstable reinforcement learning. Why "your LM is secretly a reward model", and how DPO became the default alignment method.Read →
- ChinchillaThe compute-optimal scaling law that said models were too big. Parameters and training tokens should scale together — ~20 tokens per parameter — so a 70B model trained on 1.4T tokens beat the 280B giants. Why every model since trains on trillions of tokens.Read →