T5: Casting Every NLP Task as Text-to-Text and Systematically Comparing Transfer Learning's Knobs
T5 casts translation, classification and summarization as text in, text out, trains one encoder-decoder with one loss, and compares architectures, objectives, datasets and scale. Denoising beats language modeling, corrupting spans is cheaper, and large clean C4 beats repeated small data.
On this page
- Why this paper is worth reading
- Text-to-text: one model, one loss, one decoding procedure
- C4: about 750GB of cleaned text
- One comparison setup
- The systematic comparison: architecture, objective, data, scale
- The final T5
- Checking it in code
- Limitations and cautions
- What to take from this paper
- Further reading
- FAQ
Why this paper is worth reading
In 2018 and 2019, pre-train-then-fine-tune methods (BERT, GPT, XLNet, RoBERTa and others) were multiplying, but each used its own architecture, pre-training objective, dataset and fine-tuning recipe, so results were hard to compare. The T5 paper (Raffel et al., Google, posted October 2019, JMLR 2020) did two things:
- It proposed a unified text-to-text framework in which every task is “text in, text out”.
- Inside that framework it compared every knob of transfer learning (architecture, pre-training objective, dataset, fine-tuning strategy, scale) under one setup, then scaled up the best choices into T5.
It reads more like a systematic experimental handbook: its value is not one new module but dozens of choices on one table, and, unusually, it measured noise: the baseline was trained from scratch 10 times, and the standard deviation tells you which differences mean anything.
Text-to-text: one model, one loss, one decoding procedure
Figure 1 of the paper gives a few examples:
| Task | Input | Output |
|---|---|---|
| Translation | translate English to German: That is good. | Das ist gut. |
| Grammatical acceptability (CoLA) | cola sentence: The course is jumping well. | not acceptable |
| Semantic similarity (STS-B) | stsb sentence1: The rhino grazed on the grass. sentence2: A rhino is grazing in a field. | 3.8 |
| Summarization | summarize: state authorities dispatched emergency crews tuesday ... | six people hospitalized after a storm in attala county. |
Classification outputs a label word (such as entailment for MNLI); an output that matches no valid label counts as wrong, which the paper says never happened in a trained model. STS-B is a regression task whose scores are annotated in steps of 0.2, so scores are rounded to the nearest 0.2 and written as strings. The task prefix is in essence a hyperparameter, and the paper found that rewording it had limited impact.
So all tasks share one loss (teacher forcing with cross-entropy) and one decoding procedure (greedy or beam search); switching tasks means switching data. Later instruction tuning, and the way large models cast everything as prompt plus continuation, follow the same line of thought.
C4: about 750GB of cleaned text
The paper starts from the April 2019 Common Crawl web text and applies a set of heuristics to obtain C4. The rules include:
- keep only lines that end in terminal punctuation (period, exclamation mark, question mark, closing quote);
- drop pages with fewer than 3 sentences and keep only lines with at least 5 words;
- drop pages containing words from a bad-words list, pages with “lorem ipsum”, and pages with a curly bracket
{(to avoid code); remove lines containing “Javascript” or boilerplate such as privacy and cookie notices; - keep only one copy of any three-sentence span that occurs more than once in the dataset;
- use langdetect to keep only English pages, with probability at least 0.99.
The result is about 750GB of text (Table 8 says 745GB), several orders of magnitude larger than most pre-training datasets at the time. The paper also reports the unfiltered version (6.1TB): GLUE 81.46, almost 2 points below the filtered 83.28.
One comparison setup
The baseline (Base) is a Transformer with a 12-layer encoder and a 12-layer decoder, , feed-forward width 3072, 12 heads and , about 220 million parameters, roughly twice BERT-Base because it has two stacks. The other settings:
| Item | Value |
|---|---|
| Optimizer | AdaFactor; greedy decoding at test time |
| Pre-training | steps, sequence length 512, batch of 128 sequences (about tokens after packing), about B tokens in total |
| Learning rate | ”inverse square root” schedule with for pre-training; constant 0.001 for fine-tuning |
| Vocabulary | SentencePiece, 32,000 wordpieces shared with German, French and Romanian |
| Position information | Simplified relative position bias: each bias is a scalar added to the attention logit, 32 of them, with ranges growing logarithmically up to an offset of 128 and one shared bucket beyond |
| Fine-tuning | steps |
Table 1 gives the baseline averages and the standard deviation over 10 from-scratch runs; differences smaller than about two standard deviations should not be interpreted:
| Setting | GLUE | CNNDM | SQuAD | SGLUE | EnDe |
|---|---|---|---|---|---|
| Baseline mean | 83.28 | 19.24 | 80.88 | 71.36 | 26.98 |
| Baseline std. dev. | 0.235 | 0.065 | 0.343 | 0.416 | 0.112 |
| No pre-training | 66.22 | 17.60 | 50.31 | 53.04 | 25.86 |
Pre-training helps GLUE, SQuAD and SuperGLUE far more than the noise. (In the tables, CNNDM is ROUGE-2, SGLUE is the SuperGLUE average and EnDe is WMT English-to-German BLEU.)
The systematic comparison: architecture, objective, data, scale
Architecture (Table 2, all with a denoising objective). is the parameter count of one 12-layer stack and the FLOPs the encoder-decoder needs for a sequence.
| Architecture | GLUE | CNNDM | SQuAD | SGLUE | EnDe |
|---|---|---|---|---|---|
| Encoder-decoder ( parameters, compute) | 83.28 | 19.24 | 80.88 | 71.36 | 26.98 |
| Encoder-decoder, shared parameters (, ) | 82.81 | 18.78 | 80.63 | 70.73 | 26.72 |
| Encoder-decoder, 6 layers each (, ) | 80.88 | 18.97 | 77.59 | 68.42 | 26.38 |
| Language model (, ) | 74.70 | 17.93 | 61.14 | 55.02 | 25.09 |
| Prefix language model (, ) | 81.82 | 18.61 | 78.94 | 68.11 | 26.43 |
The encoder-decoder doubles the parameters but costs the same compute as the single-stack models and is best on every task; sharing parameters costs little; halving the layers clearly hurts.
Pre-training objective (Tables 4 to 7). Denoising clearly beats prefix language modeling and deshuffling; the variants of denoising differ very little:
| Objective | GLUE | CNNDM | SQuAD | SGLUE | EnDe |
|---|---|---|---|---|---|
| Prefix language modeling | 80.69 | 18.94 | 77.99 | 65.27 | 26.86 |
| Deshuffling | 73.17 | 18.59 | 67.61 | 58.47 | 26.11 |
| BERT-style (reconstruct the full text) | 82.96 | 19.17 | 80.65 | 69.85 | 26.78 |
| Replace corrupted spans, predict only the corrupted part (baseline) | 83.28 | 19.24 | 80.88 | 71.36 | 26.98 |
| Corruption rate 50% | 81.27 | 19.32 | 79.80 | 70.33 | 27.01 |
| Span corruption, mean span length 3 | 83.49 | 19.62 | 81.84 | 72.53 | 26.86 |
Corruption rates between 10% and 25% differ little, while 50% is clearly worse on GLUE and SQuAD; a mean span length of 3 slightly outperforms independent token corruption on most non-translation tasks, which the paper calls “slightly (but significantly)”. The paper therefore recommends choosing the objective mainly by computational cost, that is, by keeping targets short.
Data (Tables 8 and 9).
| Dataset | GLUE | CNNDM | SQuAD | SGLUE | EnDe |
|---|---|---|---|---|---|
| C4 (745GB) | 83.28 | 19.24 | 80.88 | 71.36 | 26.98 |
| C4, unfiltered (6.1TB) | 81.46 | 19.14 | 78.78 | 68.04 | 26.55 |
| RealNews-like (35GB) | 83.83 | 19.23 | 80.39 | 72.38 | 26.75 |
| WebText-like (17GB) | 84.03 | 19.31 | 81.42 | 71.40 | 26.80 |
| Wikipedia (16GB) | 81.85 | 19.31 | 81.29 | 68.01 | 26.94 |
| Wikipedia + TBC (20GB) | 83.65 | 19.28 | 82.08 | 73.24 | 26.77 |
Small datasets close to a downstream domain win on individual tasks (TBC is fiction, and MultiRC exact match rises from 25.78 to 50.93), but small datasets get repeated. In Table 9 C4 is truncated while training still covers tokens: 64 repeats have limited impact (GLUE 82.87), 256 repeats begin to hurt (82.62, SQuAD 79.78), 1,024 repeats clearly hurt (GLUE 79.55, SQuAD 76.27) and 4,096 repeats hurt more (GLUE 76.34); the paper uses the training loss to argue that the model is memorizing.
Scale (Table 13, all with 4× compute except ensembling).
| Method | GLUE | CNNDM | SQuAD | SGLUE | EnDe |
|---|---|---|---|---|---|
| Baseline | 83.28 | 19.24 | 80.88 | 71.36 | 26.98 |
| Same size, 4× training steps | 85.33 | 19.33 | 82.45 | 74.72 | 27.08 |
| Same size, 4× batch size | 84.60 | 19.42 | 82.52 | 74.64 | 27.07 |
| 2× size, 2× steps | 86.18 | 19.66 | 84.18 | 77.18 | 27.52 |
| 4× size, same steps | 85.91 | 19.73 | 83.86 | 78.04 | 27.47 |
| Ensemble of 4 models | 84.77 | 20.10 | 83.09 | 71.74 | 28.05 |
Conclusion: more data, more parameters and ensembling all help, and model size and training time are complementary; in the paper’s tasks a 2× larger model trained 2× longer is not clearly different from a 4× larger one.
The final T5
The final recipe scales up those choices:
- Objective: span corruption with mean span length 3 and 15% corruption.
- Data: C4, 1 million pre-training steps with sequences of length 512 per batch, about 1 trillion tokens, 32 times the baseline.
- Multi-task pre-training: unsupervised and supervised tasks mixed during pre-training, followed by fine-tuning on each task separately.
- Sizes: Small (, feed-forward 2048, 8 heads, 6 layers per stack), Base, Large (, feed-forward 4096, 16 heads, 24 layers per stack), and 3B and 11B (, , 24 layers, feed-forward widths 16,384 and 65,536, 32 and 128 heads). The authors deliberately scaled the feed-forward width because TPUs are most efficient on large dense matrix multiplications.
Table 14 reports test-set results (SQuAD uses the validation set):
| Model | GLUE | SuperGLUE | SQuAD EM | CNN/DM ROUGE-2 | WMT En-De BLEU |
|---|---|---|---|---|---|
| Previous best (as of Oct 24, 2019) | 89.4 | 84.6 | 90.1 | 20.30 | 33.8 |
| T5-Small | 77.4 | 63.3 | 79.10 | 19.56 | 26.7 |
| T5-Base | 82.7 | 76.2 | 85.44 | 20.34 | 30.9 |
| T5-Large | 86.4 | 82.3 | 86.66 | 20.68 | 32.0 |
| T5-3B | 88.5 | 86.4 | 88.53 | 21.02 | 31.8 |
| T5-11B | 90.3 | 88.9 | 91.26 | 21.55 | 32.1 |
T5-11B reached the best result at the time on 18 of the 24 tasks studied, including a GLUE average of 90.3 and a SuperGLUE average of 88.9 (human baseline 89.8); it was not best on any of the WMT translation tasks, which the authors attribute in part to using only English pre-training data while the strongest translation systems use tricks such as back-translation. The paper also ran a control: a baseline pre-trained on 1 trillion tokens (Baseline-1T) is still clearly worse than T5-Base with the same amount of pre-training (GLUE 84.80 versus 85.97, SQuAD 83.01 versus 85.44), so the gains are not only from scale but also from the paper’s “non-scaling” choices.
Checking it in code
The code does two things: (1) it reproduces the span corruption of Figure 2, then applies span corruption to 568 raw tokens the way the official T5 code does (fix the number of noise tokens and spans first, then split at random) and looks at input and target lengths, against independent per-token corruption; (2) it counts the parameters of every size from the architecture in the paper.
import random
def corrupt(tokens, noise):
"""Build (inputs, targets) from a boolean mask; one sentinel <k> per run."""
inputs, targets, k, prev = [], [], 0, False
for tok, is_noise in zip(tokens, noise):
if is_noise:
if not prev: # a new span starts: a sentinel in both sequences
inputs.append(f"<{k}>")
targets.append(f"<{k}>")
k += 1
targets.append(tok)
else:
inputs.append(tok)
prev = is_noise
targets.append(f"<{k}>") # final sentinel marks the end (<Z> in Fig. 2)
return inputs, targets
# The example of Figure 2: "for", "inviting" and "last" are picked
words = "Thank you for inviting me to your party last week .".split()
mask = [w in ("for", "inviting", "last") for w in words]
inp, tgt = corrupt(words, mask)
print("inputs :", " ".join(inp))
print("targets:", " ".join(tgt))
def random_spans(n, rng, density=0.15, mean_span=3.0):
"""Like the official random_spans_noise_mask: counts first, then split."""
noise = round(n * density)
spans = round(noise / mean_span)
def split(total): # randomly cut `total` into `spans` positive integers
cuts = sorted(rng.sample(range(1, total), spans - 1))
return [b - a for a, b in zip([0] + cuts, cuts + [total])]
mask = []
# spans alternate, starting with a kept span
for keep, drop in zip(split(n - noise), split(noise)):
mask += [False] * keep + [True] * drop
return mask
rng = random.Random(0)
n = 568 # raw window length for which the official code gets 512 inputs
mask = random_spans(n, rng)
inp, tgt = corrupt(list(range(n)), mask)
spans = len(tgt) - sum(mask) - 1
print(f"span: {n} raw tokens -> inputs {len(inp) + 1} (with EOS), "
f"targets {len(tgt)}, noise {sum(mask)}, spans {spans}")
# Comparison: the same 15%, but each token corrupted independently (i.i.d.)
trials, li, lt = 2000, 0, 0
for _ in range(trials):
iid = [rng.random() < 0.15 for _ in range(n)]
inp, tgt = corrupt(list(range(n)), iid)
li, lt = li + len(inp) + 1, lt + len(tgt)
print(f"iid : {n} raw tokens -> inputs {li / trials:.1f}, "
f"targets {lt / trials:.1f} (mean of {trials})")
def t5_params(d_model, d_ff, d_kv, heads, layers, vocab=32128, buckets=32):
"""Encoder-decoder size: no biases, ReLU FFN, tied embeddings (T5 v1.0)."""
attn = 4 * d_model * heads * d_kv # q, k, v, o projections
ffn = 2 * d_model * d_ff
enc = layers * (attn + ffn + 2 * d_model) # 2 LayerNorms per layer
dec = layers * (2 * attn + ffn + 3 * d_model) # plus cross-attention
rel = 2 * buckets * heads # relative-position bias: encoder and decoder
return enc + dec + rel + vocab * d_model + 2 * d_model
configs = { # from Sections 3.1.1 and 3.7 of the paper
"Small": (512, 2048, 64, 8, 6, 60e6),
"Base": (768, 3072, 64, 12, 12, 220e6),
"Large": (1024, 4096, 64, 16, 24, 770e6),
"3B": (1024, 16384, 128, 32, 24, 2.8e9),
"11B": (1024, 65536, 128, 128, 24, 11e9),
}
for name, (*cfg, paper) in configs.items():
n = t5_params(*cfg)
print(f"{name:5s} {n / 1e6:9.1f}M paper {paper / 1e6:8.0f}M "
f"ratio {n / paper:.3f}")
Output (pure Python, near-instant; a different Python version draws a different random sequence, so the decimals of the i.i.d. line may vary slightly):
inputs : Thank you <0> me to your party <1> week .
targets: <0> for inviting <1> last <2>
span: 568 raw tokens -> inputs 512 (with EOS), targets 114, noise 85, spans 28
iid : 568 raw tokens -> inputs 556.2, targets 159.0 (mean of 2000)
Small 60.5M paper 60M ratio 1.008
Base 222.9M paper 220M ratio 1.013
Large 737.7M paper 770M ratio 0.958
3B 2851.6M paper 2800M ratio 1.018
11B 11307.3M paper 11000M ratio 1.028
How to read these numbers:
- The Figure 2 example is reproduced exactly. The input is “Thank you
<0>me to your party<1>week .” and the target is “<0>for inviting<1>last<2>”. - 568 raw tokens become exactly 512 input tokens. The number of noise tokens is , the number of spans , the input length and the target length . The official code uses exactly this arithmetic to work backwards from the desired input length to the raw window length.
- Span corruption makes sequences shorter. For the same 568 tokens and the same 15% corruption, independent per-token sampling needs 556.2 input tokens and 159.0 target tokens on average, because independent sampling produces about 72 spans (about ) and every span costs one sentinel; span corruption gives targets about 28% shorter and inputs about 8% shorter. This agrees with the paper’s statement that span corruption speeds up training; the numbers are from my own simulation, the paper does not give them.
- Parameter counts match except for Large. From the architecture in the paper, the counts for Small, Base, 3B and 11B are within 3% of the stated values; Large comes to 737.7M, 32.3M below the stated 770M, which is close to the size of one embedding matrix (M), but the paper does not explain the difference.
Limitations and cautions
- Limited by its time. The evaluations are the 2019 GLUE, SuperGLUE, SQuAD, WMT and CNN/DM, several of which are close to saturated today; T5’s “state of the art” is the state of the art of October 2019 and cannot be compared directly with current models.
- Compared within the pre-train-then-fine-tune paradigm. The conclusions (encoder-decoder is best, denoising beats language modeling) were drawn in that paradigm; today’s chat models (such as Llama and DeepSeek-V3 covered on this site) are mostly decoder-only and used through prompting and post-training, so the architecture conclusion does not extrapolate directly.
- Most gaps are small. The paper itself says the variants of denoising objectives differ little; compare against the baseline standard deviations of 0.1 to 0.4 points. Variance was measured only for the baseline and assumed to hold for all variants.
- Scale and data effects are not separated. The final T5 scaled model and data together; the Table 15 control only answers whether the “non-scaling” choices contributed, not how much each choice contributed.
- Translation was not state of the art. With only English unsupervised pre-training, T5 trailed systems using back-translation and similar tricks, so scale plus English pre-training is not enough.
- Parameter statement. The stated parameter count of Large does not match the architecture given in the paper (see point 4 above); rely on your own count or the official checkpoint when you quote it.
What to take from this paper
- The value of a unified interface. Writing every task as text-to-text buys one model, one loss and one decoding procedure, and makes systematic comparison possible.
- Choose the pre-training objective mainly by compute cost. Denoising objectives differ little, but shorter targets are cheaper, so corrupting contiguous spans and predicting only the corrupted part is a sensible default.
- Data should be large and clean, not small and repeated. Unfiltered C4 is worse, and small datasets repeated beyond roughly 256 times start to hurt.
- Scale and training time are complementary. The same compute can buy a bigger model or a longer run, and combining both is the safest choice.
- A good experimental habit. Repeat the baseline to measure the standard deviation before deciding which differences deserve interpretation.
Further reading
- Paper: Exploring the Limits of Transfer Learning with a Unified Text-to-Text Transformer
- The span-corruption implementation in the official code: t5/data/preprocessors.py (
random_spans_noise_maskandrandom_spans_helper) - Related notes: BERT (the origin of T5’s denoising objective) and the GPT series
- Related wiki pages: The Transformer Block, The Pretraining Pipeline, Next-Token Prediction
FAQ
- What is T5's span-corruption pre-training objective?
- Randomly pick 15% of the tokens, replace each run of consecutive picked tokens with a unique sentinel token, and ask the model to output the dropped spans, separated by the matching sentinels and ended by one more sentinel. The final T5 uses a mean span length of 3. It produces shorter inputs and targets than corrupting tokens independently, so training is cheaper.
- Why does T5 use an encoder-decoder instead of BERT's encoder-only or GPT's decoder-only stack?
- Because the text-to-text format must both read an input and generate an output. At equal compute the paper compares an encoder-decoder, a language model and a prefix language model; with a denoising objective the encoder-decoder is best on every task, and sharing encoder and decoder parameters costs little. That comparison was made in the 2019 pre-train-then-fine-tune setting and does not transfer directly to today's chat models.
- What is C4 and how was it cleaned?
- C4 (Colossal Clean Crawled Corpus) is the English corpus the authors filtered from the April 2019 Common Crawl web text, about 750GB (the paper's table says 745GB). The rules keep only lines ending in terminal punctuation, drop pages with fewer than 3 sentences, pages containing words from a bad-words list, curly brackets or "lorem ipsum", keep one copy of any three-sentence span that repeats, and keep only pages that a language detector labels English with probability at least 0.99.
- What sizes does T5 come in?
- The paper releases Small, Base, Large, 3B and 11B, stated as about 60M, 220M, 770M, 3B and 11B parameters. Counting from the architecture in the paper, Small, Base, 3B and 11B agree with the stated values within 3%, while Large comes to about 737.7M, which does not match the stated 770M.