Machine Translation
Prerequisites
- !Sequence-to-sequence models and teacher forcing
- !Tokenization and subword vocabularies
- !Precision and recall as applied to n-gram overlap
What You'll Learn
- 1Describe the failure modes that make translation harder than paraphrasing
- 2Clean a parallel corpus with length, deduplication and alignment filters
- 3Implement BLEU with a brevity penalty and explain what it cannot see
- 4Adapt a general model to a domain using back-translation and terminology constraints
Translation fails differently from other generation
Paraphrasing tolerates drift: if the meaning survives, the wording is free. Translation does not. A shift in tense can turn an allegation into a fact, a dropped negation reverses a contract clause, and a misassigned pronoun in a gendered language changes who acted. The model must preserve commitments while simultaneously solving problems that have no single right answer.
Those problems cluster into a few recurring types. Lexical ambiguity â "bank" resolved by a river or a balance sheet â is decided by context a sentence-local model may not see. Morphology requires generating forms the source never contains: translating English into Finnish or Arabic means producing case endings and agreement that the source language simply does not mark. Word order differs structurally, so a clause that arrives last in one language may need to lead the next. Idiom and register carry the speaker's stance; a literal rendering of "hit the hay" describes a farm accident. And implicit information â dropped pronouns, articles, plural markers â must be supplied rather than copied.
| Challenge | Source language effect | What the model must do |
|---|---|---|
| Lexical ambiguity | One word, several senses | Resolve with document context |
| Morphological richness | Few cues in source | Generate inflected forms |
| Word order divergence | Clause placement differs | Restructure, not re-order |
| Gender and honorifics | No gender marked | Infer or choose explicitly |
| Idiom and register | Non-compositional meaning | Match function, not words |
| Numbers, units, dates | Formatting conventions | Convert, never approximate |
The last row is worth isolating: numbers are the one class of content where a translation is either verifiably right or wrong, which makes them the cheapest target for automated checks.
Two of these failures are invisible to the reader who does not speak the target language, which is the core operational problem of translation work. A fluent sentence that reverses a clause reads perfectly plausible in review. Systems therefore need checks the reader cannot perform: number and date verification against the source, terminology audits against the glossary, and periodic back-translation as a smoke test. Each one catches a specific, recurring class of error without requiring a fluent reviewer for every document.
How the architecture evolved to suit the task
Early systems translated phrase by phrase, and statisticians spent a decade learning that word alignment plus a phrase table could get surprisingly far. Neural seq2seq changed the shape: an encoder reads the source into a vector sequence, a decoder generates the target while attending back to those positions, and the attention map itself becomes the alignment â one mechanism replaces alignment, phrase table and reordering model.
Modern systems are transformers on both sides with a few translation-specific choices. Subword vocabularies are shared or tightly coupled across languages so that rare names fragment consistently in both directions. Label smoothing is heavier than in classification, because the target distribution at each step is genuinely uncertain. Coverage mechanisms and copy attention help with numbers and named entities that must survive verbatim. And beam search with a length penalty runs instead of greedy decoding, since the highest-probability next token at every step does not produce the highest-probability sentence.
Cleaning the parallel corpus
Most translation quality is decided before training, in how carefully the pairs were filtered. Length ratio outliers are mistranslations, near-duplicate rows waste capacity, and mixed-language rows inject noise that the model cannot ignore.
import re
from collections import Counter
def clean_parallel(src_lines, tgt_lines, max_ratio=1.6, min_ratio=0.55,
min_chars=3, shared_vocab_threshold=0.15):
"""Filter a source/target pair stream. Returns kept pairs and stats."""
stats = Counter()
kept = []
seen = set()
for src, tgt in zip(src_lines, tgt_lines):
src, tgt = src.strip(), tgt.strip()
if len(src) < min_chars or len(tgt) < min_chars:
stats["too_short"] += 1
continue
ratio = len(tgt) / max(1, len(src))
if not (min_ratio <= ratio <= max_ratio):
stats["length_ratio"] += 1
continue
if re.search(r"[\u0400-\u04FF\u4e00-\u9fff\u0600-\u06ff]", src):
if re.search(r"[A-Za-z]", src):
stats["mixed_script"] += 1
continue
if src == tgt:
stats["identical"] += 1
continue
key = (src.lower(), tgt.lower())
if key in seen:
stats["duplicate"] += 1
continue
seen.add(key)
src_words = set(re.findall(r"[a-z0-9']+", src.lower()))
tgt_words = set(re.findall(r"[a-z0-9']+", tgt.lower()))
if src_words and tgt_words and not re.search(r"[A-Za-z]", tgt):
pass # target may be non-Latin by design; skip this check
elif src_words and tgt_words:
shared = len(src_words & tgt_words)
if shared / max(1, len(src_words)) > shared_vocab_threshold * 4:
stats["suspicious_alignment"] += 1
continue
kept.append((src, tgt))
stats["kept"] += 1
return kept, stats
pairs, report = clean_parallel(
["The cat sat on the mat.", "Hello world", "same", "x"],
["Le chat s'est assis sur le tapis.", "Bonjour le monde", "same", "y"],
)
print(report) # kept=2, identical=1, too_short=1
Add a language identifier per side if your pipeline can afford it â even a fast character-model classifier catches the mixed-language rows that slip past script heuristics. Then sample a hundred surviving pairs by hand. Automated filters remove obvious garbage; only a human notices that one side is a machine translation of the other from a different source.
Scoring output: BLEU and its blind spots
BLEU measures modified n-gram precision between candidate and reference translations, geometrically averaged, with a brevity penalty that punishes output shorter than the reference.
import math
import re
from collections import Counter
def sentence_bleu(candidate: str, reference: str, max_n: int = 4,
smooth: int = 1) -> float:
cand = re.findall(r"[a-z0-9']+", candidate.lower())
ref = re.findall(r"[a-z0-9']+", reference.lower())
if not cand or not ref:
return 0.0
precisions = []
for n in range(1, max_n + 1):
cand_ngrams = Counter(tuple(cand[i:i + n]) for i in range(len(cand) - n + 1))
ref_ngrams = Counter(tuple(ref[i:i + n]) for i in range(len(ref) - n + 1))
overlap = sum((cand_ngrams & ref_ngrams).values())
total = max(1, sum(cand_ngrams.values()))
# Add-k smoothing keeps a single zero order from killing the geometric mean.
precisions.append((overlap + smooth) / (total + smooth))
log_avg = sum(math.log(p) for p in precisions) / max_n
brevity = math.exp(1 - len(ref) / len(cand)) if len(cand) < len(ref) else 1.0
return brevity * math.exp(log_avg)
print(round(sentence_bleu(
"the cat sat on the mat",
"the cat was sitting on the mat",
), 3))
What BLEU misses matters more than its formula. It is precision-oriented, so a translation that omits a hard sentence scores better than one that attempts it and hedges. It is blind to meaning: "not approved" and "approved" differ by a single token and a world. And it rewards matching the reference's phrasing over an equally correct alternative â which is why a single reference per sentence caps the achievable score no matter how good the system becomes. chrF, character n-gram F-score, is more forgiving of morphology and closer to human judgements on richly inflected targets; use both, and never as the only gate.
Adapting a general model to your domain
General MT handles news well and your product's support content badly, because terminology, tone and sentence shapes differ. Full retraining is rarely the answer; three cheaper levers usually suffice.
Terminology constraints force glossary terms at decoding time by masking vocabulary that would violate them, turning "error 502" into the localized term your documentation uses instead of a paraphrase. Back-translation synthesizes source-side data from monolingual target text: translate your in-domain English sentences into German with the current model, pair the result with the original English, and retrain â cheap supervision that teaches style without new references. Adaptive or fine-tuning approaches update the model on a small set of in-domain pairs, with care to avoid catastrophic drift on the general content that shares the same endpoint.
Validate each lever against a held-out in-domain set scored by a human, because back-translation can make output more fluent and less accurate simultaneously â the exact failure a BLEU score on noisy synthetic pairs will not reveal.
Human evaluation and the post-editing loop
For high-stakes content, run adequacy and fluency reviews on a sample: does the translation carry all the source's meaning, and does it read naturally? Modern programmes prefer error.typing-based schemes such as MQM, which categorise mistakes â accuracy, terminology, fluency, locale â so that repeated error types point at specific fixes rather than a vague score. Track error density per thousand words and compare systems on the same document set.
Post-editing sits between raw output and human translation: a linguist corrects machine text, usually measured by how many seconds per segment the machine saved. It pays when volume is high and content is largely routine; it does not pay when segments arrive already wrong, because editing a bad translation takes longer than writing it. The operational signal is simple â if post-editors routinely rewrite rather than correct, your domain adaptation is unfinished, and adding glossary entries beats adding reviewers.
Common Mistakes
Training on parallel data that was never filtered
Fix: Apply length-ratio, deduplication and script filters, then hand-sample surviving pairs
Treating BLEU as a quality gate on its own
Fix: Pair BLEU with chrF and a human adequacy sample, and inspect number and negation accuracy separately
Ignoring terminology, translating product names differently per document
Fix: Enforce a maintained glossary as decoding constraints and audit violations continuously
Letting back-translation run without in-domain human checks
Fix: Score each adaptation round on held-out in-domain pairs reviewed by a linguist
Best Practices
- Keep source and target tokenizers coupled so named entities fragment consistently
- Verify numbers, units and dates programmatically â they are the cheapest correctness check available
- Use beam search with a length penalty rather than greedy decoding for production output
- Measure error density per thousand words by category so fixes map to root causes
- Re-measure after every domain change; terminology drifts faster than models do
Key Takeaways
- Translation must preserve commitments while resolving ambiguity, morphology and word order that the source does not determine
- Parallel-corpus quality decides more than architecture: filter by length ratio, duplication and script, then sample by hand
- BLEU is a regression signal, not a quality verdict â it is precision-oriented, meaning-blind and reference-capped
- Domain adaptation is mostly terminology constraints and back-translation, validated by human adequacy checks
- Post-editing economics flip when output is bad: measure whether editors correct or rewrite, and fix the model when they rewrite