- Introduced by
- Raffel, C.; Shazeer, N.; Roberts, A.; et al. (Google Brain)
- Year
- 2020
- Type
- Pre-trained encoder-decoder Transformer (sequence-to-sequence)
What does it do?
T5 is a sequence-to-sequence deep learning framework introduced by Raffel et al. at Google in 2020 and published in the Journal of Machine Learning Research (Vol. 21, No. 140).
It recasts NLP tasks such as classification, translation, summarisation and question answering as text-to-text problems, so that input and output are always strings and one encoder-decoder Transformer can be pre-trained once and fine-tuned across tasks through the same interface. T5 introduced the C4 corpus and a span-corruption pre-training objective as part of a systematic study of transfer learning, and its largest variant (11B parameters) reported strong results on several benchmarks at the time of publication.
The intuition behind the method
Think of T5 as a model that turns every language problem into the same kind of exercise: given a string of text, produce another string. For example, the input 'translate English to French: The cat sat on the mat' is answered by generating the French sentence, and 'summarize: ...' is handled by the same model in the same way. T5 first learns general language structure by reading a large web corpus and predicting randomly removed spans of text (span corruption). It then adapts this knowledge to a specific task by training on labelled input-output text pairs. Because the encoder-decoder design generates output token by token, it suits tasks whose answers vary in length. BERT, by contrast, is an encoder-only model that produces per-token representations and is not designed to generate variable-length output text autoregressively.
History
T5 was developed by Colin Raffel, Noam Shazeer, Adam Roberts and colleagues at Google and published in the Journal of Machine Learning Research in 2020 (Vol. 21, No. 140). The work is a systematic study of choices in transfer learning for NLP, including pre-training objectives, dataset scale and fine-tuning strategy. The C4 corpus was introduced in the paper, and the architecture is an encoder-decoder Transformer based on Vaswani et al. (2017). At release, the T5-11B model reported strong results on GLUE and SuperGLUE and other benchmarks; see Raffel et al. (2020) for the specific numbers. Later models such as mT5, CodeT5 and FLAN-T5 build on T5.
When to use it
Choose T5 when the task can be written as generating a string from an input string, for example summarisation, translation, question answering, extraction, or classification where the label is produced as a word. It is a suitable choice when you have labelled input-output pairs to fine-tune on and enough compute to load a pre-trained checkpoint; the smaller checkpoints are the practical option on a single modest GPU, while the largest variants require multi-GPU infrastructure. It is a reasonable baseline for sequence-to-sequence NLP, especially when the output length varies. Do not choose T5 for purely numeric regression or structured tabular prediction, since it assumes textual input and output and tabular data would have to be serialised into text first. Whatever variant you use, validate on held-out data and report the checkpoint size and decoding settings (beam width, length penalty) together with the scores.
Limitations and considerations
- The largest checkpoint (T5-11B) needs very large GPU memory even for inference, which limits who can run it.
- Encoder-decoder models process the input with a separate encoder pass, so their speed relative to decoder-only models depends on input length, output length and model size; benchmark on your own workload.
- Behaviour on inputs longer than those seen in training is not established by the cited sources for T5's relative position biases, so evaluate on your own input lengths.
- Expressing a task as a string is awkward when the output has rich structure with hard constraints, such as strictly valid graphs or program outputs with many interdependent parts.
- The original pre-training corpus is English C4, so the base checkpoints are predominantly English; multilingual use relies on separately pre-trained variants such as mT5.
- Fine-tuning on small datasets can overwrite much of the pre-trained knowledge, so the learning rate and number of training epochs need careful selection on validation data.
Source conditions do not replace independent scientific review or validation by an analysis engine.
Strengths
- The text-to-text interface lets one architecture and one training recipe cover many NLP task types.
- The paper's systematic comparison of pre-training objectives, corpus choices and fine-tuning strategies makes the design choices documented and comparable.
- Span-corruption pre-training trains the decoder to reconstruct multi-token spans, which gives a different learning signal from single-token masking while keeping the number of prediction targets per sample lower.
- Released under Apache 2.0 with checkpoints at several scales (Small, Base, Large, 3B, 11B), so the cost of a model can be matched to the deployment setting.
- Extended in later work (mT5, CodeT5, FLAN-T5), which gives a documented family of related models to compare against.
Applications
- Abstractive text summarisation, with fine-tuning on corpora such as CNN/DailyMail and XSum.
- Machine translation, where a text prefix specifies the language direction.
- Question answering in both extractive (SQuAD) and abstractive (NarrativeQA) settings.
- Natural language inference and sentiment classification, where the model generates the label word.
- Data-to-text generation and dialogue response generation.
How it works
How it works
Every task is reformulated as a mapping from one string to another, usually by prepending a short task prefix to the input. For classification the output is the label written as a word; for summarisation it is the summary; for translation it is the translated sentence. Because the same interface serves every task, a single architecture and training loop can be used without task-specific output layers.
During pre-training on the C4 corpus, T5 replaces contiguous spans of tokens in the input with unique sentinel tokens (for example <extra_id_0>) rather than masking individual tokens. The decoder is trained to generate a target sequence made of the sentinel tokens each followed by the dropped-out span, so the loss is a standard autoregressive cross-entropy over this target sequence, conditioned on the corrupted input. The systematic comparison reported by Raffel et al. found that a mean span length of 3 with a corruption rate of 15% performed well among the objectives it tested, including BERT-style masking and language-model objectives.
Formula
\mathcal{L}_{\text{span}} = -\sum_{t=1}^{T'} \log P\big(y_t \mid y_{<t},\, \text{enc}(\tilde{x});\ \theta\big)T5 uses an encoder-decoder Transformer. The encoder processes the full input through stacked self-attention and feed-forward layers. The decoder attends to its previously generated tokens through causal self-attention and to the encoder output through cross-attention, producing the output one token at a time. The formula shown is the scaled dot-product attention of Vaswani et al. (2017), given as background for the attention operation; T5 implementations differ from it in some details (for example in how scaling is handled), so consult Raffel et al. (2020) and the released code if you need to reproduce the exact computation.
Formula
\text{Attention}(Q, K, V) = \text{softmax}\!\left(\frac{QK^{\top}}{\sqrt{d_k}}\right)VInstead of adding absolute positional embeddings to the input, T5 adds a learned scalar bias to the attention logits that depends on the relative offset between a query position and a key position. Offsets are mapped into a limited number of buckets, and each bucket has its own learned bias (per attention head). The formula shown is schematic: the bias term is b(bucket(j−i)) added to the query-key logit, and the exact bucketing should be taken from the original paper.
Formula
a_{ij} = \frac{q_i^{\top} k_j}{\sqrt{d_k}} + b\big(\text{bucket}(j-i)\big)After pre-training, the whole model is fine-tuned end-to-end on labelled (input, output) text pairs for each downstream task. The loss is standard teacher-forced cross-entropy: at each decoding step t the model is trained to assign high probability to the correct target token y_t, given the preceding target tokens and the encoder representation of the input. Task prefixes used in the text-to-text format are kept during fine-tuning so that the task framing stays consistent. Choose the learning rate and number of epochs by performance on held-out validation data rather than fixed defaults.
Formula
\mathcal{L}_{\text{FT}} = -\sum_{t=1}^{T} \log P(y_t \mid y_{<t},\, \text{enc}(x);\ \theta)Common pitfalls
- Dropping the task prefix from the input string. The model then has to infer the task from the text alone, which can degrade results for tasks that share input formats.
- Using a learning rate that is too high during fine-tuning, which can overwrite the pre-trained weights rather than adapt them.
- Comparing T5 checkpoints of different sizes as if they were the same model; reported results depend strongly on scale.
- Reporting greedy-decoding results as final performance while beam width and length penalty are left at defaults, since these settings change the generated outputs and the metric scores.
Frequently asked questions
How is T5 different from BERT?
BERT is an encoder-only model pre-trained with masked token prediction; it produces per-token representations and is not designed to generate text autoregressively. T5 is an encoder-decoder model that generates output text of variable length, so it suits summarisation, translation and other tasks whose answer is a string. Both use Transformer attention, but T5 uses the same text-to-text interface for every task.
What is span corruption and why is it used instead of token masking?
Span corruption replaces contiguous groups of tokens with a sentinel token and asks the model to generate the removed spans as its output. Compared with token-level masking as in BERT, it gives fewer prediction targets per sample while still requiring the model to use context to fill in multi-token gaps. Raffel et al. report a mean span length of 3 with 15% corruption as a well-performing setting among the objectives they compared.
Which T5 variant should I start with?
T5-Base is a practical starting point for many research settings, since it fits on a single modern GPU and fine-tunes relatively quickly. T5-Small is appropriate when memory or latency is the hard constraint. Larger variants (Large, 3B, 11B) generally give better results but need multi-GPU setups and longer fine-tuning runs. Instruction-tuned FLAN-T5 checkpoints are one option to evaluate when labelled data are limited; compare them with base T5 on your own validation set.
Can T5 be used for tasks outside NLP, such as tabular data?
T5 is designed for text input and output. Tabular data can be serialised as text, for example by writing column names and values as strings, but T5 is not built for purely numeric or structured data. For tabular prediction, tree-based ensembles or models designed for tabular data are usually a more suitable choice.
Related methods
Sources
Raffel, C., Shazeer, N., Roberts, A., Lee, K., Narang, S., Matena, M., Zhou, Y., Li, W., & Liu, P. J. (2020). Exploring the Limits of Transfer Learning with a Unified Text-to-Text Transformer. Journal of Machine Learning Research, 21(140), 1–67.
Open publication referenceVaswani, A., Shazeer, N., Parmar, N., Uszkoreit, J., Jones, L., Gomez, A. N., Kaiser, Ł., & Polosukhin, I. (2017). Attention is All You Need. Advances in Neural Information Processing Systems, 30.
Open publication referenceDevlin, J., Chang, M.-W., Lee, K., & Toutanova, K. (2019). BERT: Pre-training of Deep Bidirectional Transformers for Language Understanding. Proceedings of NAACL-HLT 2019, 4171–4186.
Open publication reference