Paper notes

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.

Published Updated 17 min read

On this page
  1. Why this paper is worth reading
  2. Text-to-text: one model, one loss, one decoding procedure
  3. C4: about 750GB of cleaned text
  4. One comparison setup
  5. The systematic comparison: architecture, objective, data, scale
  6. The final T5
  7. Checking it in code
  8. Limitations and cautions
  9. What to take from this paper
  10. Further reading
  11. 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:

  1. It proposed a unified text-to-text framework in which every task is “text in, text out”.
  2. 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:

TaskInputOutput
Translationtranslate 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
Summarizationsummarize: 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, dmodel=768d_{\text{model}}=768, feed-forward width 3072, 12 heads and dkv=64d_{kv}=64, about 220 million parameters, roughly twice BERT-Base because it has two stacks. The other settings:

ItemValue
OptimizerAdaFactor; greedy decoding at test time
Pre-training219=524,2882^{19}=524{,}288 steps, sequence length 512, batch of 128 sequences (about 2162^{16} tokens after packing), about 235≈342^{35}\approx34B tokens in total
Learning rate”inverse square root” schedule 1/max⁡(n,k)1/\sqrt{\max(n,k)} with k=104k=10^4 for pre-training; constant 0.001 for fine-tuning
VocabularySentencePiece, 32,000 wordpieces shared with German, French and Romanian
Position informationSimplified 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-tuning218=262,1442^{18}=262{,}144 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:

SettingGLUECNNDMSQuADSGLUEEnDe
Baseline mean83.2819.2480.8871.3626.98
Baseline std. dev.0.2350.0650.3430.4160.112
No pre-training66.2217.6050.3153.0425.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). PP is the parameter count of one 12-layer stack and MM the FLOPs the encoder-decoder needs for a sequence.

ArchitectureGLUECNNDMSQuADSGLUEEnDe
Encoder-decoder (2P2P parameters, MM compute)83.2819.2480.8871.3626.98
Encoder-decoder, shared parameters (PP, MM)82.8118.7880.6370.7326.72
Encoder-decoder, 6 layers each (PP, M/2M/2)80.8818.9777.5968.4226.38
Language model (PP, MM)74.7017.9361.1455.0225.09
Prefix language model (PP, MM)81.8218.6178.9468.1126.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:

ObjectiveGLUECNNDMSQuADSGLUEEnDe
Prefix language modeling80.6918.9477.9965.2726.86
Deshuffling73.1718.5967.6158.4726.11
BERT-style (reconstruct the full text)82.9619.1780.6569.8526.78
Replace corrupted spans, predict only the corrupted part (baseline)83.2819.2480.8871.3626.98
Corruption rate 50%81.2719.3279.8070.3327.01
Span corruption, mean span length 383.4919.6281.8472.5326.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).

DatasetGLUECNNDMSQuADSGLUEEnDe
C4 (745GB)83.2819.2480.8871.3626.98
C4, unfiltered (6.1TB)81.4619.1478.7868.0426.55
RealNews-like (35GB)83.8319.2380.3972.3826.75
WebText-like (17GB)84.0319.3181.4271.4026.80
Wikipedia (16GB)81.8519.3181.2968.0126.94
Wikipedia + TBC (20GB)83.6519.2882.0873.2426.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 2352^{35} 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).

MethodGLUECNNDMSQuADSGLUEEnDe
Baseline83.2819.2480.8871.3626.98
Same size, 4× training steps85.3319.3382.4574.7227.08
Same size, 4× batch size84.6019.4282.5274.6427.07
2× size, 2× steps86.1819.6684.1877.1827.52
4× size, same steps85.9119.7383.8678.0427.47
Ensemble of 4 models84.7720.1083.0971.7428.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 2112^{11} 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 (dmodel=512d_{\text{model}}=512, feed-forward 2048, 8 heads, 6 layers per stack), Base, Large (dmodel=1024d_{\text{model}}=1024, feed-forward 4096, 16 heads, 24 layers per stack), and 3B and 11B (dmodel=1024d_{\text{model}}=1024, dkv=128d_{kv}=128, 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):

ModelGLUESuperGLUESQuAD EMCNN/DM ROUGE-2WMT En-De BLEU
Previous best (as of Oct 24, 2019)89.484.690.120.3033.8
T5-Small77.463.379.1019.5626.7
T5-Base82.776.285.4420.3430.9
T5-Large86.482.386.6620.6832.0
T5-3B88.586.488.5321.0231.8
T5-11B90.388.991.2621.5532.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:

  1. 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>”.
  2. 568 raw tokens become exactly 512 input tokens. The number of noise tokens is round(568×0.15)=85\text{round}(568\times0.15)=85, the number of spans round(85/3)=28\text{round}(85/3)=28, the input length 483+28+1=512483+28+1=512 and the target length 85+28+1=11485+28+1=114. The official code uses exactly this arithmetic to work backwards from the desired input length to the raw window length.
  3. 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 568×0.15×0.85568\times0.15\times0.85) 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.
  4. 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 (32128×1024≈32.932128\times1024\approx32.9M), 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

  1. 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.
  2. 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.
  3. 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.
  4. 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.
  5. A good experimental habit. Repeat the baseline to measure the standard deviation before deciding which differences deserve interpretation.

Further reading

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.