Sub topic 1
Summarisation and Translation as Text-to-Text Problems
Prerequisites
This chapter assumes you have the following background:
- Basic Python, including calling functions and reading short scripts.
- Familiarity with neural networks and training with a loss function.
- A high-level idea of the Transformer and self-attention.
- Basic use of PyTorch tensors or the Hugging Face Transformers library.
You do not need to know how an encoder-decoder model works internally. The next chapters cover that. This chapter explains the problem framing that makes one architecture fit many tasks.
What "text-to-text" means
A text-to-text problem has one text as input and a new text as output. The output is not chosen from a fixed list of labels, and it is not a span copied from the input. The model writes it.
Two common tasks fit this form:
- Summarisation maps a long text to a shorter text that keeps the main points.
- Translation maps a text in one language to a text in another language that keeps the meaning.
Other tasks can be written the same way. Question answering maps a question and a passage to an answer string. Grammar correction maps a flawed sentence to a corrected one. A model that handles the general form is called a sequence-to-sequence model, usually shortened to seq2seq.
Why this framing is useful
Compare it with classification. A sentiment classifier reads a sentence and returns one of a few labels, so its output layer has one unit per label. A seq2seq model has no such limit. It produces a sequence of tokens, one at a time, and the sequence can have any length up to a cap you set.
This gives you three practical benefits:
- One interface covers many tasks. Input text goes in, output text comes out.
- You can reuse one pretrained model and one training loop across tasks. Only the data changes.
- The output length is not tied to the input length. A summary is shorter than its source. A translation may be shorter or longer, depending on the language pair.
Properties that separate these tasks from classification
Three properties shape the rest of this tutorial.
- The output is variable length. The model must decide when to stop. It does this by producing a special end-of-sequence token.
- The output is open-ended. Many different outputs can be correct. Two good translators will rarely write the same sentence.
- The output depends on its own earlier tokens. Each new token is chosen given the source and the tokens already written. This is called autoregressive generation.
The second property matters most for evaluation. There is no single right answer to compare against, so scoring is harder than computing accuracy. Chapter 12 returns to this.
Formal view
Let the source be a sequence of tokens x = (x1, ..., xn) and the target be y = (y1, ..., ym). The model estimates the probability of the target given the source:
P(y | x) = P(y1 | x) * P(y2 | x, y1) * ... * P(ym | x, y1, ..., y(m-1))Each factor is one prediction step. Training makes the real target likely under this product. Generation searches for a high-probability y for a new x. The two halves of the tutorial, training and decoding, correspond to these two uses of the same formula.
The shared architecture at a glance
The standard model for this framing is the encoder-decoder Transformer. The encoder reads the whole source and builds a representation of it. The decoder writes the target one token at a time, looking back at the encoder's representation as it goes.
The dotted arrow shows the autoregressive loop. Each token the decoder emits becomes part of the input for the next step. The details of the encoder, the decoder and cross-attention are in the next two chapters. For now, treat the model as a function from source text to target text.
Same model, different tasks
Because both tasks share the framing, the same code shape works for each. Only the model and the settings change.
Summarisation
The pipeline below loads BART fine-tuned on news articles. The setting do_sample=False makes decoding deterministic, so the same input gives the same summary.
from transformers import pipeline
summarizer = pipeline("summarization", model="facebook/bart-large-cnn")
article = (
"The city council voted on Tuesday to expand the bike lane network by 40 kilometres "
"over the next three years. Supporters said the plan would reduce traffic and emissions, "
"while some shop owners worried about losing parking spaces near their stores. "
"The first new lanes are expected to open next spring."
)
result = summarizer(article, max_length=60, min_length=15, do_sample=False)
print(result[0]["summary_text"])The input is a string and the output is a string. The max_length and min_length arguments bound the output length in tokens.
Translation
Here a MarianMT English-to-German model is loaded directly. This shows the steps the pipeline hides: tokenise, generate, decode.
from transformers import AutoTokenizer, AutoModelForSeq2SeqLM
name = "Helsinki-NLP/opus-mt-en-de"
tokenizer = AutoTokenizer.from_pretrained(name)
model = AutoModelForSeq2SeqLM.from_pretrained(name)
sentences = ["The weather is nice today.", "Where is the nearest train station?"]
batch = tokenizer(sentences, return_tensors="pt", padding=True)
outputs = model.generate(**batch, num_beams=4, max_new_tokens=64)
print(tokenizer.batch_decode(outputs, skip_special_tokens=True))The structure matches the summarisation example. Text goes in, token IDs go through generate, and text comes out. The model name decides the task. This model was trained only on English-to-German pairs, so it cannot summarise.
One model for both tasks
T5 takes the idea further. It was trained with a short text prefix at the start of the input that names the task. The same weights then perform different tasks.
from transformers import AutoTokenizer, AutoModelForSeq2SeqLM
name = "t5-small"
tokenizer = AutoTokenizer.from_pretrained(name)
model = AutoModelForSeq2SeqLM.from_pretrained(name)
prompts = [
"translate English to German: The house is wonderful.",
"summarize: The city council approved a plan to add 40 kilometres of bike lanes over three years.",
]
inputs = tokenizer(prompts, return_tensors="pt", padding=True)
outputs = model.generate(**inputs, num_beams=4, max_new_tokens=40)
for text in tokenizer.batch_decode(outputs, skip_special_tokens=True):
print(text)Here the task is part of the input text. Nothing in the code changes between the two prompts. This is the clearest demonstration of the text-to-text idea: the task description, the data and the result are all strings.
Two kinds of summarisation
The framing hides an important choice. A summary can be built in two ways.
| Approach | How it works | Strength | Weakness |
|---|---|---|---|
| Extractive | Selects whole sentences or phrases from the source | Every word comes from the source, so it is faithful | Can read as disjointed, and cannot rephrase |
| Abstractive | Generates new wording | Fluent, can compress and merge ideas | Can state things the source does not say |
Extractive summarisation is a selection problem, not a text-to-text problem, because the output is a subset of the input. Encoder-decoder models are used for the abstractive kind. That is why this tutorial spends a full chapter on hallucination, which is text that reads well but is not supported by the source.
Translation is not word substitution
It is tempting to picture translation as swapping each word for its equivalent. The text-to-text view shows why that fails. The model sees the whole source before it writes. This lets it handle several common differences between languages:
- Word order. German often places the verb at the end of a subordinate clause. English does not.
- Different lengths. One English word may correspond to several German words, or the reverse.
- Agreement and gender. The correct form of an article or adjective depends on a noun that may appear later in the sentence.
- Idioms. A literal rendering may be wrong, so the model must pick an equivalent phrase.
None of this is programmed as a rule. The model learns it from many pairs of aligned sentences.
Data format for training
The framing also fixes the training data format. Every example is a pair of strings: a source and a target.
| Task | Source | Target |
|---|---|---|
| Summarisation | A news article | A short human-written summary |
| Translation | An English sentence | The same sentence in German |
| Grammar correction | A flawed sentence | The corrected sentence |
If you can express a task as such pairs, you can fine-tune a seq2seq model on it. The quality of the model then depends mostly on how many pairs you have, how clean they are and how close they are to the text you will see in use.
When text-to-text is the wrong tool
The framing is general, but it is not always the best choice. Consider these cases before you commit:
- A fixed set of answers. If the output is one of five categories, a classifier is cheaper, faster and easier to evaluate. Generating the label as text adds a way to fail, since the model may write a string that is not a valid label.
- Strict faithfulness. In legal or medical text, an invented detail in an abstractive summary is costly. An extractive method, or a human check, may be safer.
- Very long inputs. Every model has a maximum input length. Text beyond it is cut off, so a summary may miss the end of the document. A later chapter covers workarounds.
- Low-resource languages. Translation quality depends on training data. A language pair with few examples will give weaker output.
What the rest of the tutorial covers
This chapter set up the problem. The remaining chapters follow the concept order of the plan:
- How the encoder, decoder and cross-attention work.
- How text becomes tokens, and how training uses teacher forcing.
- How to choose a pretrained model and a decoding strategy.
- How to summarise, translate, handle long inputs and fine-tune.
- How to evaluate with ROUGE, BLEU and chrF, and how to spot failure modes.
Exercise
A team wants to label support tickets as "billing", "technical" or "other". A colleague proposes a T5 model with the prefix "classify ticket:" that writes the label as text. Give two reasons a standard classifier might be a better choice, and one reason the text-to-text approach might still be attractive.
Show answer
Reasons for a classifier: (1) The label set is fixed, so the output layer can have exactly three units, which is cheaper and faster than autoregressive generation. (2) The generative model can write a string that is not a valid label, such as "billing issue", which needs extra handling, and a classifier cannot do this. Evaluation is also simpler with accuracy or F1. Reason for text-to-text: if the team also wants to handle other tasks, such as summarising the ticket, with the same model and training pipeline, a single seq2seq model gives one interface for all of them. It also lets them add new labels by changing the data, without changing the architecture.
Exercise
Write the probability of the target y = (y1, y2, y3) given the source x as a product, and say which property of the task this factorisation reflects.
Show answer
P(y | x) = P(y1 | x) P(y2 | x, y1) P(y3 | x, y1, y2). It reflects autoregressive generation: each target token is predicted from the source and from all previously produced target tokens.
Exercise
You load Helsinki-NLP/opus-mt-en-de and pass it the input "summarize: The council approved a plan." Explain what you expect and why.
Show answer
You should not expect a summary. The model was trained only on English-to-German sentence pairs and has no task prefixes, so it will most likely treat the whole input as English text and translate it, including the word "summarize", into German. The task is fixed by the training data of the model, not by the words in the input. Only a model trained with task prefixes, such as T5, responds to them.