Sub topic 6
Choosing a pretrained model: BART, T5, MarianMT and mBART
This chapter helps you pick a pretrained encoder-decoder model for a summarisation or translation job. It assumes you can run Hugging Face Transformers code in Python and that you know the encoder, decoder and cross-attention parts of the architecture from earlier chapters. You do not need to train anything here.
Why the choice matters
All four model families in this chapter share one design: an encoder reads the source text and an autoregressive decoder writes the target text. They differ in three things that decide whether they fit your task:
- Pretraining objective. This is the task the model solved before you touched it.
- Task interface. Some models need a text prefix or a language code, and others do not.
- Language coverage. Some models cover one language pair, and others cover dozens of languages.
A wrong choice rarely produces an error message. You get fluent but poor output, such as a news-style summary of a legal contract, or a translation into the wrong language.
The four families at a glance
| Family | Pretraining idea | Typical checkpoint | Best used for |
|---|---|---|---|
| BART | Corrupt text, then reconstruct it | `facebook/bart-large-cnn` | English summarisation |
| T5 | Text-to-text with span corruption and a task prefix | `t5-small`, `t5-base` | Several tasks with one model |
| MarianMT | Translation-only training on parallel text | `Helsinki-NLP/opus-mt-en-de` | One language pair, fast inference |
| mBART | BART-style denoising across many languages | `facebook/mbart-large-50-many-to-many-mmt` | Many language pairs in one model |
BART: denoising autoencoder
BART is trained by corrupting text and asking the decoder to restore the original. The corruptions include masking spans, deleting tokens and shuffling sentences. The encoder sees the damaged text and the decoder writes the clean text.
This objective suits summarisation well. The decoder is used to copying and rewriting content from the encoder's view of the source. The checkpoint facebook/bart-large-cnn was then fine-tuned on the CNN/DailyMail news dataset, so it is a ready-made news summariser.
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"])Things to know about this checkpoint:
- It is English only. It will not summarise German text well.
- It takes at most 1024 input tokens. Longer input is cut off, a problem a later chapter covers.
- Its style comes from CNN/DailyMail, where the key facts sit in the first sentences. Expect summaries that lean on the opening of the document and often copy phrases from it.
- A BART checkpoint that was not fine-tuned for summarisation, such as
facebook/bart-large, is a good starting point for fine-tuning but is not useful for summarising as it is.
T5: everything as text-to-text
T5 casts every task as text in, text out. A short prefix in the input tells the model which task to do. The original T5 checkpoints were pretrained on unlabelled text with span corruption, where spans of the input are replaced by sentinel tokens and the decoder predicts the missing spans. They were also trained on a mix of supervised tasks, which is why prefixes such as translate English to German: and summarize: work without any fine-tuning.
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)Both prompts go through the same model and the same generate call. Only the prefix differs.
Points that matter in practice:
- The prefix is part of the input text. If you forget it or misspell it, the model guesses the task and the output degrades.
- The built-in translation prefixes cover only a few pairs: English to German, French and Romanian. For other pairs, use a different model or fine-tune.
t5-smallhas about 60 million parameters. It is quick to run and good for learning, but its summaries are weaker than those of BART-large. Larger sizes (t5-base,t5-large) improve quality at the cost of memory and speed.- Newer variants such as FLAN-T5 were instruction-tuned on many more tasks and usually follow prompts better. They are a sensible default if you want one general model.
- The original T5 vocabulary was built mostly from English text with some German, French and Romanian. Text in other scripts becomes many unknown or fragmented tokens.
MarianMT: one model per language pair
MarianMT models come from the OPUS-MT project. Each checkpoint is trained only for translation, and for one direction of one language pair. The name tells you the direction: opus-mt-en-de goes from English to German, and opus-mt-de-en goes the other way.
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))Strengths:
- Small and fast. A typical checkpoint has roughly 75 million parameters, so it runs on a CPU and is cheap to serve.
- Focused. A model that handles only one pair often matches or beats a larger general model on that pair, especially for high-resource languages.
- Simple interface. No prefix or language code is needed for most pairs.
Weaknesses:
- Many checkpoints. Supporting ten languages in all directions can mean up to 90 separate models to load, version and monitor.
- Coverage gaps. Not every pair exists. For a missing pair you can pivot through English (translate A to English, then English to B), but errors in the first step carry into the second.
- Some checkpoints are multi-target. For these you must put a target-language token such as
>>fra<<at the start of the source text. Check the model card before use. - Sentence-level training. The models work best on single sentences or short paragraphs. Pass whole documents sentence by sentence.
mBART: one model for many languages
mBART applies the BART denoising objective to monolingual text in many languages. The fine-tuned mbart-large-50-many-to-many-mmt checkpoint can translate directly between any of 50 languages. This includes pairs that do not involve English, so there is no pivot step.
Unlike MarianMT, mBART needs language codes. You set the source language on the tokenizer and force the first generated token to be the target language code:
from transformers import MBartForConditionalGeneration, MBart50TokenizerFast
name = "facebook/mbart-large-50-many-to-many-mmt"
tokenizer = MBart50TokenizerFast.from_pretrained(name, src_lang="fr_XX")
model = MBartForConditionalGeneration.from_pretrained(name)
batch = tokenizer(["Le temps est agréable aujourd'hui."], return_tensors="pt")
outputs = model.generate(
**batch,
forced_bos_token_id=tokenizer.lang_code_to_id["de_DE"],
num_beams=4,
max_new_tokens=64,
)
print(tokenizer.batch_decode(outputs, skip_special_tokens=True))Two details cause most mBART mistakes:
src_langmust match the input. It adds the source language token that the encoder expects.forced_bos_token_idselects the output language. If you leave it out, the model may produce text in the wrong language, often copying the source.
Note that lang_code_to_id exists in some Transformers versions and has been deprecated in newer ones. If it raises an error, use tokenizer.convert_tokens_to_ids("de_DE") instead.
The trade-off is size. The checkpoint has about 610 million parameters, roughly eight times a Marian model. It needs a GPU for comfortable throughput. Its quality for any single pair can be lower than a dedicated Marian model for the same pair, because its capacity is shared across 50 languages and low-resource languages benefit less.
How the checkpoints differ internally
The design differences explain the interface differences:
- BART and mBART use a shared vocabulary and a standard encoder-decoder, with the decoder initialised from the pretraining run.
- T5 uses a SentencePiece vocabulary and relative position information, and it has no task-specific heads. Everything goes through the language-model output layer.
- Marian uses a smaller Transformer configuration trained from scratch on parallel data, with a vocabulary built for the language pair.
The diagram below summarises the decision process.
Decision criteria
Work through these questions in order:
- What is the task? For summarisation of English news, start with
facebook/bart-large-cnn. For translation, go to question 2. For something else, such as summarising dialogues or scientific papers, search the Hub for a checkpoint fine-tuned on similar data, or plan to fine-tune. - How many language pairs? For one or two pairs, look for an
opus-mtmodel first. For many pairs or for non-English pairs, consider mBART-50. - What are your resource limits? A Marian model fits on a CPU. BART-large and mBART-large are better served on a GPU.
- Do you need one model for several tasks? T5 or FLAN-T5 handles both summarisation and translation with prefixes, which keeps your deployment simple. Expect lower quality than a specialised checkpoint at the same size.
- Will you fine-tune? Fine-tuning works with all four families. BART and T5 are common starting points for new summarisation data, and Marian is a strong start for a new domain in a language pair that it already covers.
- What is the licence? Check the model card. Licences differ between checkpoints, and some restrict commercial use.
Common errors
| Symptom | Likely cause | Fix |
|---|---|---|
| Summary of a long article ignores the end | Input exceeds the model's token limit and is truncated | Chunk the text or use a long-input model |
| T5 output is unrelated to the task | Missing or wrong task prefix | Add the exact prefix, such as `summarize: ` |
| mBART returns text in the source language | `forced_bos_token_id` not set | Set it to the target language code |
| Marian output has odd language mixing | Multi-target checkpoint used without `>>xxx<<` token | Prefix each source with the target-language token |
| Poor output on a specialised domain | Checkpoint trained on news or general text | Fine-tune on in-domain data |
| Out-of-memory error loading a model | Large checkpoint on a small GPU | Use a smaller size or half precision |
Exercises
Exercise
You need to translate customer emails between Spanish and Polish, in both directions, and the emails never involve English. Which model family do you try first, and why?
Show answer
Try mBART-50 (facebook/mbart-large-50-many-to-many-mmt). It translates directly between non-English pairs. With MarianMT you would probably need to pivot through English, which adds a second step and lets errors compound. You would also set src_lang on the tokenizer and forced_bos_token_id to the target language code.
Exercise
A colleague loads t5-small, passes the text "The council approved a plan to add 40 km of bike lanes." and gets a poor, mostly copied output. What did they forget, and how do they fix it?
Show answer
They forgot the task prefix. T5 reads the task from the input text. Fix it by writing "summarize: The council approved a plan to add 40 km of bike lanes." before tokenising.
Exercise
Why can a MarianMT model for one pair outperform mBART-50 on that pair, even though mBART is much larger?
Show answer
A Marian model puts all its capacity and its vocabulary into one language pair. mBART shares its capacity across 50 languages, so each pair gets less. For a high-resource pair that has a dedicated Marian model, the specialised model often matches or beats the larger general one, while using far less memory.