QuiddityML

By · 9 November 2026 · 8 min read

Text generation tasks: translation, summarization, and open-ended generation

How translation, summarization and chat-style replies share one training and inference loop, where they differ, and how BLEU, ROUGE and human review score each one, with runnable Python for the two metrics.

Text generation is the family of NLP tasks where a model writes new text instead of picking a label or returning a document that already exists. Translation, summarization and chatbot replies all belong to it. Models read and write tokens, which can be whole words or pieces of words. The examples below split text on spaces and count words to keep things simple.

Generation versus retrieval

A retrieval system answers a query by ranking texts that already exist. A generation system writes its answer one token at a time. The model reads an input and gives a probability to every token in its vocabulary. A decoding rule picks one token, the model appends it to what it has written, and the loop repeats until the model writes a special end token or hits a length limit.

On the left, retrieval passes a query through an embedding model and returns a ranked list of existing texts. On the right, generation passes prompt tokens through a language model, which writes new output tokens one after another.

The input changes from task to task. It can be a prompt, a document to shorten or a sentence in another language. The loop that writes the output stays the same.

Training on input and target pairs

Training data comes in pairs of an input and the text the model should write for it. Examples are an English sentence with its French translation, an article with a reference summary, or a prompt with a good response.

The model learns to predict each target token from the input $x$ and the target tokens before it. If the target has $T$ tokens $y_1, \ldots, y_T$, the probability of the whole target is the product of the next-token probabilities:

$$P(y \mid x) = \prod_{t=1}^{T} P(y_t \mid x, y_{<t})$$

Here $y_{<t}$ means all target tokens before position $t$. At each position the model outputs logits, one raw score per vocabulary token, collected in a vector $z_t$. Cross-entropy compares those logits with the true next token, and the loss averages it over the $T$ positions:

$$L = \frac{1}{T}\sum_{t=1}^{T} \text{CE}(z_t, y_t)$$

For a three-token target the loss is the mean of three cross-entropy values. This is the same next-token objective a language model trains on, with a task input attached. The input tells the model what to write about, and the target shows what a correct output looked like.

Translation

Translation is generation where the input is text in one language and the output carries the same meaning in another. Training uses parallel text, also called bitext, where each source sentence is paired with its translation.

The French source tokens Je, suis, étudiant, a period and an end token enter an encoder that reads the source. A decoder writes the English target tokens I, am, a, student, a period and an end token.

Translation is not word-for-word replacement. The three French words "Je suis étudiant" become four English ones, "I am a student". Word order, grammar markers and phrasing can all change, and the output has to read naturally in the target language.

During training the model sees the source sentence and the true target prefix. With the target "Le chat dort", it learns to predict "Le" and then "chat" and then "dort". Each prediction uses the source and the correct earlier target tokens. Feeding the true previous tokens instead of the model's own guesses is called teacher forcing, explained in teacher forcing and exposure bias. At inference no target exists. The model starts from a beginning token, predicts the first output token and feeds its own prediction back in.

In training, the decoder reads the source plus the true target prefix and is scored on predicting the next target token. In inference, it reads the source plus its own generated prefix and chooses the next token itself.

Because inference builds on the model's own choices, the decoding rule changes the output. Greedy decoding takes the highest-probability token at each step and gives one fixed translation. Beam search keeps several partial translations at once. It often works well for translation, because a word that looks second best early can lead to a better full sentence, as beam search explained shows step by step.

Scoring a translation with BLEU

A sentence usually has many correct translations, so an exact-match score is too strict. BLEU compares a candidate translation with one or more reference translations by counting overlapping n-grams, runs of $n$ consecutive words.

For single words, the precision $p_1$ is the number of matching candidate words divided by the number of candidate words. Each word's matches are clipped at the number of times it appears in the reference:

$$p_1 = \frac{\sum_{w} \min(\text{count}_{cand}(w), \text{count}_{ref}(w))}{\sum_{w} \text{count}_{cand}(w)}$$

The clip stops a candidate from scoring well by repeating a common word. The candidate "the the the cat" against the reference "the cat sat" earns one match for "the" instead of three, plus one for "cat". That gives $p_1 = 2/4 = 0.50$.

The candidate the the the cat and the reference the cat sat. A table shows the appears 3 times in the candidate and once in the reference, so it is clipped to 1, and cat matches once. p1 = 2 / 4 = 0.50.

BLEU repeats the count for runs of two, three and four words, which gives $p_2$ to $p_4$. Matching longer runs rewards words that came out in the right order. The four precisions are combined with a geometric mean, so a zero at any length sends the whole score to zero. A brevity penalty then lowers the score of candidates shorter than the reference, since a two-word candidate that matched perfectly would otherwise score 1.0. With candidate length $c$ and reference length $r$, the penalty is 1 when $c > r$ and $e^{1 - r/c}$ otherwise.

BLEU gives a quick signal. It can still score a correct paraphrase low when the wording differs from the reference.

Summarization

Summarization produces a shorter text that keeps the main content of a longer one, such as an article, a report or a meeting transcript. A good summary is short enough to save time and complete enough to keep the important points. Every claim in it also has to trace back to the source.

Summaries come in two styles:

Top: an extractive selector picks some source sentences and copies them into the summary. Bottom: an abstractive generator combines source facts A, B and C into a new sentence, and the summary also states a Fact D that the source never had.

The choice follows the risk. A legal or medical tool may prefer extractive summaries or strict evidence checks. A news digest may use abstractive summaries and check each claim against the source.

Abstractive summarizers train like the translation model, on pairs of a document and a reference summary. At inference they usually get length limits: a maximum so the summary does not run on, and a minimum so it does not skip the content.

Scoring a summary with ROUGE

ROUGE is the common automatic metric for summaries. BLEU divides the clipped matches by the candidate's length, and ROUGE divides by the reference's length instead, so it measures how much of the reference the candidate recovered:

$$\text{ROUGE-}n = \frac{\sum_{g} \min(\text{count}_{cand}(g), \text{count}_{ref}(g))}{\sum_{g} \text{count}_{ref}(g)}$$

Here $g$ runs over the n-grams of the reference. ROUGE-1 counts single words and ROUGE-2 counts pairs. For the reference "the cat sat on the mat" and the candidate "the cat sat on the rug", 5 of the 6 reference words are matched, so ROUGE-1 recall is $5/6 \approx 0.83$. ROUGE-L uses the longest run of words the two texts share in the same order, even when those words are not next to each other.

Left: the reference the cat sat on the mat and the candidate the cat sat on the rug, with ROUGE-1 recall = 5 / 6 = 0.83. Right: a source says sales rose last quarter, the summary says sales rose 40 percent, and the number is not in the source, which overlap cannot catch.

ROUGE checks word overlap only. A summary that says "sales rose 40 percent" when the source says "sales rose last quarter" can still overlap well with a reference. Summaries therefore also need a faithfulness check, which means reading outputs and flagging every claim the source does not support.

BLEU and ROUGE in Python

Both metrics come down to the same clipped count with a different denominator:

1from collections import Counter
2 
3 
4def clipped_matches(candidate, reference):
5    cand, ref = Counter(candidate.split()), Counter(reference.split())
6    return sum(min(count, ref[word]) for word, count in cand.items())
7 
8 
9def unigram_precision(candidate, reference):   # BLEU's p1
10    return clipped_matches(candidate, reference) / len(candidate.split())
11 
12 
13def rouge1_recall(candidate, reference):
14    return clipped_matches(candidate, reference) / len(reference.split())
15 
16 
17print(unigram_precision("the the the cat", "the cat sat"))
18print(round(rouge1_recall("the cat sat on the rug", "the cat sat on the mat"), 2))
10.5
20.83

Counter counts how often each word appears. clipped_matches caps each candidate word at its count in the reference. Dividing by the candidate length gives BLEU's $p_1$, and dividing by the reference length gives ROUGE-1 recall. If a score comes out higher than the example by hand, check that repeated words are being clipped.

Open-ended generation

Open-ended generation covers continuing a text and replying to an instruction or a message. Finishing a story opening, completing a code comment and answering a chat request are examples. Training data can be documents, dialogues or pairs of instructions and responses written in the style the model should imitate.

One prompt can have many acceptable outputs, and each can be judged on the same qualities:

The prompt Explain the benefits of regular exercise leads to three different possible responses, A, B and C, each checked for being relevant, coherent, complete and formatted.

At inference the prompt is split into tokens and the model returns logits for the next token. The decoding rule picks one token, appends it and repeats. For the prompt "The weather today is", the model might give "sunny" a probability of 0.34 and "cold" 0.19, with smaller probabilities for thousands of other tokens. Greedy decoding picks "sunny".

Step 1, the prompt tokens The weather today is. Step 2, the next-token distribution with sunny 0.34, cold 0.19, warm 0.15, rainy 0.11 and mild 0.06. Step 3, greedy decoding appends sunny. Step 4, check whether an end token or the length limit was reached, otherwise continue.

The loop stops when the model writes an end token, produces a stop sequence or reaches a length limit.

The decoding rule shapes the output without changing the model's weights. Greedy decoding is stable but can repeat itself. Sampling draws a token at random from the distribution, which adds variety but can drift off topic. Temperature rescales the logits before they are turned into probabilities, and values below 1 sharpen the distribution while values above 1 flatten it. Top-p, also called nucleus sampling, keeps the smallest set of top tokens whose probabilities add up to $p$ and samples from those. LLM decoding strategies and LLM temperature explained go through each one with numbers.

One next-token distribution feeds five decoding controls: greedy, sampling, temperature, top-p and beam search. Each produces a different example output, and the probabilities themselves do not change.

Evaluating open-ended output

With no single reference answer, BLEU and ROUGE have little to compare against. Reviewers check each output for relevance to the prompt and coherence instead. They also check support from any source text, format, safety and repetition. An answer can be fluent and still fail several of these.

A source says refunds are available within 30 days. A generated answer says 45 days and repeats itself. It passes relevance, coherence, format and safety, and fails support and repetition.

Automatic scores help catch patterns across many outputs. They do not replace reading samples.

When each task fits, and common mistakes

Translation fits when the output must carry the same meaning in another language. Summarization fits when people need the content of a long text in less time, and extractive summaries suit settings where a wrong claim is costly. Open-ended generation fits replies, drafts and continuations where many outputs are acceptable.

Mistakes that come up often:

Encoder-decoder models are the classic architecture for translation and summarization, with one network reading the input and another writing the output. Question answering has the same split between copying from a source and writing new text. Retrieval and text ranking covers the ranking side of the comparison at the top of this post.

QuiddityML teaches text generation, translation, summarization and open-ended generation as four concepts in the Intro to NLP track. The exercises on them include writing the temperature formula as code and working out step by step how temperature reshapes the next-token probabilities.