Parallel Data Mining and Quality Control
Mine parallel text from the web, align sentences, filter candidate pairs, and screen for training-evaluation contamination in translation corpora.
Language AI HandbookAll chapters Parallel Data Mining and Quality Control
A translated web page looks like a source of training pairs until you try to match the sentences. Navigation text can appear on only one side, a translator can split one sentence into two, and two stories about the same news event may have no translated sentences in common. Here we retrieve candidates, decide which ones to keep, and screen the resulting corpus for overlap with your evaluation set.
Parallel data mining recovers candidate text pairs from existing sources. One approach extracts text from the web, embeds sentences in a multilingual space, and retrieves likely matches by similarity. Quality control checks whether those matches express the same content.
A multilingual site might publish translated pages without sentence-level alignment. A miner can recover candidate sentence pairs from the pages and ask people to label a smaller sample for calibration. The procedure below works from existing translations and leaves their correspondence to be checked.
The chapter follows these stages.
crawl → clean → propose page pairs → retrieve or align sentences → score → filter → screen overlap
The pipeline first extracts usable text from raw pages. Embeddings support cross-lingual retrieval, and scoring ranks the retrieved candidates. Alignment can establish sentence correspondences inside candidate document pairs before final pair filtering. Back-translation can supply an additional stream of pairs, and an overlap audit can screen both streams before training.
Two organizing ideas carry through everything below:
- Mining is retrieval. You have millions of source sentences and millions of target sentences. You want the pairs that are translations. The core operation is a similarity search in a shared vector space, exactly like the dense retrieval systems you met in Part XLIV: Retrieval-Augmented Generation.
- Quality control is classification. Given a candidate pair, decide keep or drop. The features are heuristic (length ratios, punctuation, numbers), statistical (language model scores), or learned (quality estimation models).
On a fixed set of candidates, raising the margin cutoff can only retain the same number or fewer pairs. Precision can rise, fall, or stay flat depending on the labels of the pairs removed. Choose a cutoff by measuring both precision and recall on labeled candidates.
Choose a cutoff for the language pair, domain, encoder, and candidate pool you plan to use. If those inputs change, measure the score distribution and recheck the cutoff against labeled pairs. Evaluate downstream training effects on held-out data.
Why Parallel Data Is a Bottleneck
Start by checking the bitext already available for the language pair and intended domain. OPUS aggregates several separately released collections. Inspect the underlying releases and compare their counts, domains, and segmentation before deciding what to mine.
Four forces have shaped the data available today:
- Institutional corpora. Europarl and the United Nations Parallel Corpus provide translated proceedings and documents in the registers used by those institutions. Check the terms for the particular distribution you use.
- Subtitles and localization. OpenSubtitles provides conversational parallel text. Inspect alignment around short turns and subtitle boundaries. Lison and Tiedemann, 2016
- Web mining. CCMatrix reports mining about 4.5 billion sentence pairs across 38 languages. WikiMatrix mined 135 million pairs across 1,620 language pairs from Wikipedia articles in 85 languages. ParaCrawl collects parallel texts by crawling and aligning web pages.
- Synthetic and back-translated data. Monolingual text in the target language, translated back into the source by a model, then used as additional training data.
These sources serve different purposes when you mix them. Proceedings contain institutional language. Subtitle timing can cut across sentence boundaries. A web candidate can be a translated page with the wrong sentence matched, and a synthetic generator can repeat an error. Evaluate the mixture on the language pair, domain, and register you need.
A project with little curated bitext can use a labeled seed to check multilingual retrieval, mine more candidates, and verify a sample of what it finds. Part XXVII: Machine Translation and Speech Translation continues with this topic in Many-to-Many and Low-Resource Translation.
The size of a crawl is an upper bound on the pages you can search. The useful yield depends on how many relevant translations are present, what retrieval finds, and which candidates pass the checks. Measure each of those quantities separately when deciding whether to mine another source.
A bitext is a collection of text fragments paired with their translations. In this chapter, a supervised translation example uses one fragment as the source input and its translation as the target.
Bitext Mining
The retrieval workflow here uses document retrieval, sentence embeddings, and margin scoring. These stages restrict where to search, represent what to compare, and score the proposed pairs.
Start document screening with recall in mind. If it drops a page pair, no later sentence filter can recover pairs from those pages. The sentence encoder provides comparable vectors, and margin scoring compares a candidate to nearby alternatives. Check the errors at each stage because a downstream score can miss mistakes made upstream.
Document-level retrieval
Before aligning sentences in two different languages, retrieve pages likely to contain translations of each other. This workflow uses two kinds of clues.
- Structural signals. Use repeated URL patterns, alternate-language links, or corresponding page layouts to propose document pairs. Resnik and Smith used document structure together with a separate textual-equivalence check. Resnik and Smith, 2003
- Content signals. Embed the page (or a sample of sentences from it) and retrieve pages in the other language with high aggregate similarity.
An alternate-language link only proposes a page pair. A translated page without a link can still be found by text retrieval, and an unrelated page about the same event can score highly. Check candidate pairs from both sources.
A site can reuse the same navigation, layout, image positions, and headings across unrelated pages. Treat matching DOM structure as a retrieval feature and compare the text in corresponding sections before accepting the pair.
You can represent a page by pooling embeddings for a sample of its sentences. A second check of several corresponding passages or a structural clue can help distinguish a translation from an independent page on the same topic.
An all-pairs comparison of 10 billion sentences on each side would score pairs. Restrict comparisons to proposed document pairs and add up the products of their respective sentence counts to estimate the remaining work. The reduction depends on the number and lengths of the candidate documents.
With n source sentences and m target sentences, the full search scores nm pairs. A document shortlist limits any subsequent exhaustive comparisons to the selected blocks. The separate page-retrieval cost depends on how the shortlist is built.
Sentence embeddings
A multilingual sentence encoder maps source and target sentences into a space where they can be compared. LaBSE trains for bilingual sentence retrieval with a translation-ranking objective. Feng et al., §2
A translation-ranking objective gives the model known translations as positives and other candidate sentences as negatives. It rewards a higher score for the positives. Check actual retrieval on the languages and domains you need because the training objective alone does not establish score separation on a new corpus.
The key properties to look for in an encoder are:
- Cross-lingual alignment. Translations of the same sentence land near each other regardless of language.
- Semantic sensitivity. Paraphrases are close; unrelated sentences are far.
- Robustness to translationese. Machine-translated text and human text are embedded similarly.
- Efficient inference. Estimate total encoding time from measured throughput and the number of sentences to encode.
Include both human-written and translated text in a calibration sample if both occur in the candidate pool. If the two groups have different score distributions, a shared cutoff can retain them at different rates.
The encoders in Table mining-encoders offer examples of different coverage and architectures.
| Model | Dimensions | Released | Notes |
|---|---|---|---|
| LASER and LASER2 | 1024 | 2019 and 2022 | Meta released the original LASER encoder for 93 languages. LASER2 updates that encoder. LASER3 adds language-specific encoders for broader coverage. |
| LaBSE | 768 | 2020 | Google's BERT-based sentence encoder for 109 languages |
| SONAR | 1024 | 2023 | Meta reports 200 languages for its text models and 37 for its speech encoders |
| paraphrase-multilingual-MiniLM-L12-v2 | 384 | 2021 | Sentence Transformers multilingual sentence encoder |
| multilingual-e5-large | 1024 | 2023 | Microsoft, trained on diverse retrieval tasks |
Choose an encoder by measuring retrieval quality and throughput on your target languages and domain. The worked example uses constructed unit vectors to show the scoring and filtering steps without downloading a pretrained encoder. In production, the sentence vectors would come from the encoder you evaluated.
Normalize each nonzero source and target vector to unit length, so . Cosine similarity between a source vector and a target vector is:
where:
- : the unit-length embedding of source sentence
- : the unit-length embedding of target sentence
- : the dot product of the two unit vectors, which equals their cosine similarity
The divisor drops out because both norms equal , so the similarity reduces to a dot product. Approximate search can propose the top target candidates. Measure retrieval recall and latency with your index, hardware, and corpus size.
An unnormalized dot product depends on vector norms as well as direction. A less similar target can outrank another if its norm is large enough. After unit normalization, the inner product equals cosine similarity, so the same inner-product ranking can serve either score.
Margin-based scoring
A high cosine can be ambiguous if many competing targets score almost as well. Artetxe and Schwenk (2019) compare candidates with neighborhoods in both languages. Their ratio divides the candidate cosine by the average of the source-to-target and target-to-source neighborhood means. They also evaluate a distance margin that subtracts this background instead of dividing.
The small example here uses a one-sided variant so you can inspect each source independently. Let Aₖ(xᵢ, yⱼ) contain the k highest-cosine target alternatives to xᵢ after excluding yⱼ. The toy ratio is:
The numerator is the candidate cosine. The denominator is the mean cosine of exactly k other targets, so k must be at least one and smaller than the target count. The example uses positive competitor means. A nonpositive mean is outside this ratio's intended range, and the code marks that score undefined. If two pairs have the same positive cosine, the pair with stronger alternatives receives the lower ratio. A small positive background can still inflate the ratio of a weak match, so also inspect the cosine itself.
You can separately require mutual top-one retrieval, in which each sentence chooses the other as its best neighbor under a specified score. With one tie-broken winner per sentence, this prevents several sources from claiming the same target but can also discard correct alternatives.
Thresholds and calibration
Collect a labeled sample of retrieved candidates for each language pair and domain. Sweep a candidate cutoff and inspect precision and recall before choosing an operating point. Recalibrate after changing the encoder, extraction method, or composition of the candidate pool. A held-out sample for evaluation serves a different purpose from the labeled sample used to select the threshold.
Using an explicit cosine floor can block a low-cosine candidate whose background is especially weak. It does not guarantee adequacy, and the cutoffs in the worked example apply only to its constructed scores. The general calibration procedure is described in Part XX, Ch 6: Quality Filtering.
Sentence Alignment
Mining produces candidate document pairs. Within a document pair, you still need to figure out which sentence in one language corresponds to which sentence in the other. This is sentence alignment.
Check for boilerplate, sidebars, and differences in paragraph breaks even after accepting a page pair. Pairing sentences solely by position fails when one side inserts a navigation sentence or the translation reorders sentences.
There is a deeper reason alignment is hard: translation is not a sentence-by-sentence operation, even when humans try to make it one. A translator may merge two short source sentences into one, split a long sentence into three, reorder clauses across sentence boundaries, or drop a sentence entirely because it is redundant in the target language. Alignment algorithms therefore have to consider not just one-to-one matches but many-to-many groupings, and they have to do so without knowing in advance where the boundaries are.
The next four sections compare alignment signals based on length, dictionaries, machine translation, and multilingual embeddings.
Length-based alignment (Gale-Church)
Gale and Church (1993) modeled the relationship between the character lengths of translated segments. The teaching model here conditions on the source length. For positive source and target character counts and , the model assumes:
where:
- : the length in characters of the source sentence
- : the length in characters of the target sentence
- : the average length ratio between the two languages
- : a variance parameter that scales the Gaussian noise
- : a normal distribution with mean and variance , which makes the spread of the difference grow with the source length
With fixed, the standard deviation grows like the square root of . For a given absolute residual, the quadratic penalty relative to the peak is smaller for longer source segments.
The conditional log density in this teaching model, for and , is:
The example uses as an illustrative coefficient. The original aligner estimated length and variance from its own corpus, used a pooled length in the residual normalization, and converted a two-sided normal-tail probability into a distance. The example below uses a Gaussian log density and illustrative move penalties, so its scores and decisions can differ from the original program.
The figure compares each curve to its own peak to isolate the change in width.
VisualizationOut [4]Expand

Given this model, alignment becomes a dynamic program. Let be the best score for aligning the first source sentences with the first target sentences. The recurrences are:
where:
- : the best score for aligning the first source sentences with the first target sentences
- : the set of allowed alignment patterns, where means source sentences align to target sentences
- : one allowed pattern, taking source and target sentences
- : the sum of the lengths of the source sentences in the segment
- : the sum of the lengths of the target sentences in the segment
- : the log weight for the move shape
- : the conditional log density for two nonempty segments, or zero for a gap, whose cost comes from
Set , initialize other states to minus infinity, and consider only predecessors with valid indices. With a fixed move set of bounded segment size, the DP takes time and space for documents with and sentences. Similar character counts can still produce a wrong or over-grouped alignment because the score has no lexical signal.
The set of allowed moves is where the algorithm's assumptions live. The move handles the common case. The and moves allow sentences to be dropped or inserted, which is how the aligner copes with untranslated boilerplate. The , , and moves handle merges and splits. Each move has a log weight. In the toy below, every other move has a lower weight than the one-to-one move. A split or merge can make up the difference with a better length score. A gap has no length score, so its local cost comes from its log weight.
A dynamic-programming method for sentence alignment that scores segment moves using their length relationship. The original implementation turns a two-sided normal-tail probability into a distance. Gale and Church, 1993
Lexical alignment (Hunalign)
Hunalign (Varga et al., 2005) extends the length-based approach with a dictionary. If the source and target sentences share translation pairs, the alignment gets a bonus. This disambiguates cases where multiple alignments have similar length-based scores.
Dictionary evidence can break a tie when several candidate segments have similar lengths. If one target contains a known translation of a source word and another does not, the lexical signal can distinguish otherwise similar candidates.
Hunalign can use a supplied bilingual dictionary. In its automatic dictionary-building mode it first aligns without a dictionary, induces one from its initial alignment, and aligns the sentences again with that dictionary. Hunalign documentation
The second pass can use lexical evidence that the first pass lacked. Check a sample of alignments in your domain, especially when the initial length matches are weak enough to produce misleading dictionary entries.
Translation-based alignment (Bleualign)
Bleualign (Sennrich and Volk, 2010) aligns documents using translations of one side. Bleualign paper
- Translate one side of the document with an MT system.
- Score each candidate sentence pair by BLEU between the translation and the target.
- Use high-similarity alignments as anchors, then fill gaps with BLEU-based and length-based heuristics.
The method requires translations for one side of the document. Compare its alignment quality with a length-based baseline on checked examples, particularly if the available MT system performs poorly on the language pair or domain.
A correct target may phrase the sentence differently from the MT output, and a wrong target may share many words with it. BLEU provides evidence of text overlap. Errors in the MT output or repeated phrasing can give the wrong correspondence a high score.
Embedding-based alignment (Vecalign)
Vecalign (Thompson and Koehn, 2019) scores candidate segments using embeddings and searches for a monotonic alignment. It uses a coarse-to-fine approximation to restrict the dynamic-programming search instead of comparing all sentence pairs in the document. The paper reports linear time and space in the number of sentences aligned for its procedure.
The four approaches compared here use different bilingual signals:
| Method | Signal | Input needed |
|---|---|---|
| Gale-Church | Character lengths | Segmented sentences |
| Hunalign | Length and dictionary evidence | Segmented text, optionally a bilingual dictionary |
| Bleualign | Translated-text overlap | Machine translations for one side |
| Vecalign | Segment embeddings | Bilingual sentence embeddings |
If you already have an encoder that covers both languages, compare Vecalign with a length-based baseline on some hand-aligned documents.
Word Alignment
Word alignment identifies corresponding word positions inside an accepted sentence pair. This adds a finer-grained description than the segment alignments above.
The IBM models provide names for quantities that appear below. Fertility counts how many words an input word generates, and the NULL position represents output words without a corresponding input word.
The IBM models
Brown, Della Pietra, Della Pietra, and Mercer (1993) introduced five increasingly complex generative models of translation. The simplest, IBM Model 1, assumes:
where:
- : the source sentence, with tokens
- : the target sentence, with tokens
- : the latent alignment of target position into the source, where means NULL (no source word)
- : the uniform alignment prior over the source positions plus NULL
- : the translation probability of target word given the aligned source word
The translation table is unobserved, so the model is trained with EM. The E-step computes expected word alignments under the current table, and the M-step re-estimates the table from expected counts.
The E-step assigns each target position a fractional count for every possible source position, including NULL. The M-step pools and normalizes those counts. Words that frequently co-occur can still compete for the same target, so co-occurrence alone does not identify the correct links. Brown et al., 1993
The five models add progressively more realism:
- Model 1: uniform alignment prior, no word order.
- Model 2. The position model conditions on the connected positions and sentence lengths.
- Model 3. Adds a fertility model and explicitly models how many output words are generated from NULL. The NULL position is already part of the paper’s general alignment convention.
- Model 4. Uses relative-position distortion for placement.
- Model 5. Accounts for vacant target positions during placement to fix the deficiency of Model 4. Brown et al., 1993, §4
Fertility can express the case where an input compound is translated into two output words. An alignment restricted to one output word per input word cannot represent that link pattern.
GIZA++ is an implementation of classical word alignment training for directional models. A phrase-based pipeline can train both directions and symmetrize the resulting alignments as a separate step.
Directional alignments can disagree because each direction chooses correspondences from a different side. A symmetrization heuristic such as grow-diag-final starts from their intersection, grows it using adjacent links from the union, and then considers additional links.
Modern aligners
The sentence-level training objective below only needs sentence pairs. If you have checked word links, you can use them to build a lexicon or estimate how much of a source a candidate translation covers.
- fast_align uses a log-linear reparameterization of IBM Model 2 and estimates its parameters with EM. Dyer et al. report faster training than Model 4 under their experimental conditions. Dyer et al., 2013
- eflomal uses Bayesian word alignment and can estimate Dirichlet priors over lexical probabilities, alignment jumps, and fertility. The project builds on Östling and Tiedemann’s 2016 efmaral work. eflomal project
The Dirichlet priors smooth estimates when observed counts are sparse. For example, the lexical prior contributes to the estimated translation probabilities alongside the word alignment counts. Compare the aligners on your own bitext and a checked sample of word links.
A third family has emerged from multilingual encoders:
- SimAlign (Jalili Sabet et al., 2020) extracts alignments from multilingual token embeddings without training a task-specific aligner.
- Awesome-align (Dou and Neubig, 2021) can extract alignments from multilingual BERT and improve them by fine-tuning on parallel sentences. The fine-tuning objectives can use sentence pairs without hand-labeled word links.
Both methods draw on cross-lingual information in multilingual token embeddings. SimAlign extracts links from pretrained representations, while Awesome-align also provides objectives for improving the alignments with parallel text.
A QC model can use word-alignment coverage as one feature. Compare coverage with human judgments on the intended language pair before choosing how to use it.
For example, two linked source words out of ten give source-side coverage of 0.2 under this definition. Low coverage can indicate omissions, a mispaired sentence, or a failure of the aligner. The score does not distinguish those cases on its own.
Quality Control
This section compares six available quality signals. Choose checks according to the errors you see on labeled pairs and the compute budget you can measure.
A length ratio can flag a truncated segment, language identification can flag a wrong language, and a language model can flag unusual text. Bilingual similarity, quality estimation, and round-trip comparison offer additional clues about adequacy. Their cost and usefulness depend on the implementation and on the kinds of mistakes in the candidate pool.
Length ratio
A length-ratio check compares both sides in one chosen unit, such as words or characters. Compute the ratio for nonempty sources:
where:
- : the number of words (or characters) on the target side
- : the number of words (or characters) on the source side
- : the length ratio of the pair
Treat very short or very long targets as candidates for inspection. Set the accepted range using labeled examples from the language pair and the same definition of length you will use in production.
Count the same kind of unit on both sides and state which tokenizer or character convention you use. A whitespace count will miss word boundaries in text that does not mark them with spaces.
A two-word target for a 20-word source yields a ratio of 0.1. A 100-word target for a five-word source yields 20. A concise but adequate translation can also have an extreme ratio, so sample rejected pairs before imposing a hard cutoff.
Calculating the ratio needs the chosen token or character counts and a division. Run it before expensive models when audits show it removes enough invalid pairs without discarding the examples you need.
Language identification
A page labeled Portuguese can contain Spanish sentences. Sentence-level language identification can flag those cases. Candidate detectors include the fastText lid.176 models and CLD3. fastText language-identification models · CLD3 project
- Identify the dominant language of each side.
- Keep the pair only if the source is detected as and the target as .
- For code-switched or mixed-language documents, use a lower confidence threshold or skip the filter entirely.
Short inputs give the classifier little evidence. Inspect error rates by length and language before changing your cutoff. Part XX, Ch 3: Language Identification
A short interjection can occur in texts in several languages. Mixed-language inputs and closely related languages deserve separate checks of language-ID error rates. You can route ambiguous cases to other checks instead of assuming that a single language label is correct.
Language model fluency
A language model can flag text that is unusual under the model for the expected language. For a nonempty sequence of tokens, compute per-token perplexity:
Here is the model probability of token given the preceding tokens. The exponent is mean negative log probability using natural logs. Perplexity is the reciprocal of the geometric mean token probability, so higher perplexity means lower probability under the model. For token probabilities and , the geometric mean is and perplexity is .
Unusual domain vocabulary can have high perplexity even in fluent text. Calibrate by language, tokenizer, and domain. Fluency also gives no assurance of translation adequacy, so use a separate bilingual signal.
Cross-lingual similarity
An absolute cosine floor can remove a pair with a weak similarity score even when few competing neighbors give it a good margin. Inspect examples rejected by this additional check.
Treat the mining margin and the absolute QC cosine as separate scores. Sweep both cutoffs on labeled candidates from the exact encoder, language pair, and domain you will use.
A filter only selects from pairs retrieval supplies. A recall-oriented retrieval stage leaves more candidates to check, while a later cosine floor can reject weak matches. Measure the effect on both recall and precision before choosing the two cutoffs.
Quality estimation models
Reference-free quality estimation scores a hypothesis given its source. COMETKiwi is one example. Its joint encoder reads the source and hypothesis together. COMETKiwi system paper
- Score every pair with a QE model.
- Convert scores to a percentile within the batch.
- Keep the top proportion of pairs, where depends on the data budget.
Choose a batch-relative share when the retained count is a fixed budget. Round the requested count and break ties consistently if you need exactly that many rows. The score cutoff and resulting precision can change with the batch composition.
Check whether QE improves the decisions on pairs that pass cheaper filters, for example by flagging omissions or additions. Measure inference before running the model on the full candidate pool.
A joint encoder can batch several source–hypothesis pairs. Each score still depends on both inputs, so an index of separately cached sentence vectors cannot reproduce that inference. A retrieval stage can narrow the candidates before the joint model scores them.
Round-trip translation
A backward reconstruction check can help assess an existing mined pair. Take a candidate pair . Translate back to the source language using a backward model :
Then score against with an automatic metric (BLEU, chrF, or the same multilingual encoder). Pairs with low round-trip scores are rejected.
This comparison needs no target-language reference. A backward model can turn a valid target into a poor source reconstruction or turn a wrong target into a plausible one. Check which errors occur before using the score as a filter.
Consider a correct translation with a poor reconstruction and an incorrect translation whose error the backward model reverses. A high round-trip score is neither necessary nor sufficient for adequacy. Measure whether a round-trip check adds information beyond your other scores.
Quality estimation predicts translation quality without a target-language reference. A system can use handcrafted features or a learned source–hypothesis representation. Compare its scores with task-specific human judgments before using a cutoff.
Putting the filters together
A realistic pipeline composes filters in order of cost:
- Cheap heuristics. Length ratio, punctuation match, number match, script match.
- Language ID. Reject wrong-language sentences.
- Embedding similarity. Reject pairs below a cosine threshold.
- Margin filter. Reject pairs that fail the margin criterion.
- LM scores. Reject pairs with very low fluency in either language.
- QE models. Reject low-scoring survivors.
- Contamination check. Remove pairs that overlap with the evaluation set.
Run inexpensive checks first so expensive QE models see fewer candidates. The figure uses constructed counts to show the change in scale between selected stages of the funnel.
The funnel is easiest to grasp as a sequence of attrition points.
VisualizationOut [6]Expand

Numbers, dates, and punctuation can flag misalignment. Their surface forms can also change across languages, as when a translation writes a number in words or localizes a date. Audit examples before making a mismatch an automatic rejection.
The funnel can leave stylistically mismatched pairs or targets that are plausible sentences but change the source meaning. Review a sample of accepted pairs to learn which errors the checks miss.
Worked Example: Mining and Filtering a Tiny Corpus
The ten English sentences and twelve German candidates below give each score an inspectable label. Their unit vectors are a constructed fixture. It represents cosine patterns to test filtering logic offline, not measured behavior of a language encoder or a claim about any language pair.
Each row shows which candidate would win under cosine retrieval. Two rows are constructed to test the cutoffs independently: one has a weak but distinctive wrong match, and one has a wrong match with close competitors.
The executable cells use NumPy, pandas, and Matplotlib. They use authored examples and require no pretrained weights, network requests, or model download.
We start with a small English sentence set, the corresponding German translations, and two deliberate noise sentences.
PythonIn [7]Expand
import matplotlib.pyplot as plt
import numpy as np
import pandas as pd
# Ten English sentences and their correct German translations.
en_sents = [
"The cat sat on the mat.",
"Where is the train station?",
"I would like a cup of coffee, please.",
"The weather is beautiful today.",
"She reads books every evening.",
"Thank you very much for your help.",
"This is a very good restaurant.",
"The meeting starts at nine o'clock.",
"He works as a software engineer.",
"We need to buy some groceries.",
]
de_gold = [
"Die Katze saß auf der Matte.",
"Wo ist der Bahnhof?",
"Ich hätte gerne eine Tasse Kaffee, bitte.",
"Das Wetter ist heute wunderschön.",
"Sie liest jeden Abend Bücher.",
"Vielen Dank für Ihre Hilfe.",
"Das ist ein sehr gutes Restaurant.",
"Die Besprechung beginnt um neun Uhr.",
"Er arbeitet als Softwareentwickler.",
"Wir müssen einige Lebensmittel einkaufen.",
]
# Two noise sentences: one unrelated, one generic.
de_noise = [
"Die Regierung kündigte heute neue Maßnahmen an.",
"Vielen Dank.",
]
de_cands = de_gold + de_noise
assert len(de_cands) == len(en_sents) + len(de_noise)The candidates include the ten labeled translations and two distractors. The fixture uses the generic German phrase to illustrate a weak absolute match that still ranks first in its row.
Build the cosine fixture with one orthogonal coordinate per German candidate. Each English vector uses its desired candidate cosines along those coordinates. An extra coordinate, unused by all German vectors, makes each English vector unit length. The full product therefore has shape 10 by 12.
PythonIn [8]Expand
n_sources, n_targets = len(en_sents), len(de_cands)
desired_cosine = np.full((n_sources, n_targets), 0.02)
for i in range(n_sources):
desired_cosine[i, i] = 0.76
desired_cosine[i, (i + 1) % n_sources] = 0.32
desired_cosine[i, (i + 2) % n_sources] = 0.25
desired_cosine[i, n_sources] = 0.12
# A weak but distinctive wrong match.
desired_cosine[5] = 0.02
desired_cosine[5, [5, 6, 10, 11]] = [0.40, 0.04, 0.04, 0.42]
# A stronger wrong match with several nearly tied alternatives.
desired_cosine[7] = 0.02
desired_cosine[7, [3, 7, 8, 9]] = [0.48, 0.50, 0.51, 0.49]
tgt_vectors = np.eye(n_targets, n_targets + 1)
remaining_sq_norm = 1.0 - np.sum(desired_cosine**2, axis=1)
assert np.all(remaining_sq_norm >= 0)
src_vectors = np.column_stack((desired_cosine, np.sqrt(remaining_sq_norm)))
assert np.allclose(np.linalg.norm(src_vectors, axis=1), 1.0)
assert np.allclose(np.linalg.norm(tgt_vectors, axis=1), 1.0)
sim = src_vectors @ tgt_vectors.TFor every pair, take exactly three alternatives after excluding that pair's target. Division is defined only when their mean cosine is positive.
PythonIn [9]Expand
def margin_matrix(sim: np.ndarray, k: int = 3) -> np.ndarray:
n_sources, n_targets = sim.shape
if not 1 <= k < n_targets:
raise ValueError("k must be positive and smaller than the target count")
margins = np.full(sim.shape, np.nan, dtype=float)
for i, row in enumerate(sim):
for j in range(n_targets):
competitors = np.delete(row, j)
background = np.sort(competitors)[-k:].mean()
if background > 0:
margins[i, j] = row[j] / background
return margins
margin_mat = margin_matrix(sim)
cosine_cutoff, margin_cutoff = 0.5, 1.05Retrieve the best target per source by cosine. The target with the same index as the source is its labeled translation. Here ranking uses cosine and margin is used only as a gate. The raw scores are kept for every comparison.
PythonIn [10]Expand
source_indices = np.arange(n_sources)
best_j = sim.argmax(axis=1)
best_cos = sim[source_indices, best_j]
best_margin = margin_mat[source_indices, best_j]
main_df = pd.DataFrame(
{
"source_id": [f"S{i + 1}" for i in source_indices],
"english": en_sents,
"best_german": [de_cands[j] for j in best_j],
"cosine": best_cos,
"margin": best_margin,
"is_correct": best_j == source_indices,
}
)| source_id | english | best_german | cosine | margin | is_correct | |
|---|---|---|---|---|---|---|
| 0 | S1 | The cat sat on the mat. | Die Katze saß auf der Matte. | 0.76 | 3.304 | True |
| 1 | S2 | Where is the train station? | Wo ist der Bahnhof? | 0.76 | 3.304 | True |
| 2 | S3 | I would like a cup of coffee, please. | Ich hätte gerne eine Tasse Kaffee, bitte. | 0.76 | 3.304 | True |
| 3 | S4 | The weather is beautiful today. | Das Wetter ist heute wunderschön. | 0.76 | 3.304 | True |
| 4 | S5 | She reads books every evening. | Sie liest jeden Abend Bücher. | 0.76 | 3.304 | True |
| 5 | S6 | Thank you very much for your help. | Vielen Dank. | 0.42 | 2.625 | False |
| 6 | S7 | This is a very good restaurant. | Das ist ein sehr gutes Restaurant. | 0.76 | 3.304 | True |
| 7 | S8 | The meeting starts at nine o'clock. | Er arbeitet als Softwareentwickler. | 0.51 | 1.041 | False |
| 8 | S9 | He works as a software engineer. | Er arbeitet als Softwareentwickler. | 0.76 | 3.304 | True |
| 9 | S10 | We need to buy some groceries. | Wir müssen einige Lebensmittel einkaufen. | 0.76 | 3.304 | True |
The table includes one incorrect winner below the cosine threshold and a different incorrect winner below the margin threshold. The scatter plots up to three target candidates per source. The bar chart shows the cosine winner's margin and keeps each source identifier attached as the bars are sorted.
PythonIn [12]Expand
records = []
for i in source_indices:
for j in np.argsort(-sim[i], kind="stable")[:3]:
records.append(
{
"cosine": sim[i, j],
"margin": margin_mat[i, j],
"is_correct": j == i,
}
)
scatter_df = pd.DataFrame(records)
correct_points = scatter_df.loc[scatter_df["is_correct"]]
other_points = scatter_df.loc[~scatter_df["is_correct"]]
bar_df = main_df.sort_values("margin", ascending=False)VisualizationsOut [13]Expand


Apply the two cutoffs and a separate target/source length-ratio band. This example counts whitespace-delimited words on both sides.
PythonIn [14]Expand
main_df["length_ratio"] = [
len(de_cands[j].split()) / len(en_sents[i].split())
for i, j in enumerate(best_j)
]
main_df["pass_margin"] = main_df["margin"].ge(margin_cutoff)
main_df["pass_cosine"] = main_df["cosine"].ge(cosine_cutoff)
main_df["pass_length"] = main_df["length_ratio"].between(0.5, 2.0)
main_df["keep"] = main_df[["pass_margin", "pass_cosine", "pass_length"]].all(
axis=1
)
filter_masks = {
"Margin": main_df["pass_margin"],
"Cosine": main_df["pass_cosine"],
"Length ratio": main_df["pass_length"],
"All three": main_df["keep"],
}
summary = pd.DataFrame(
[
{
"filter": name,
"survivors": int(passes.sum()),
"correct among survivors": int(
(passes & main_df["is_correct"]).sum()
),
}
for name, passes in filter_masks.items()
]
)| filter | survivors | correct among survivors | |
|---|---|---|---|
| 0 | Margin | 9 | 8 |
| 1 | Cosine | 9 | 8 |
| 2 | Length ratio | 9 | 8 |
| 3 | All three | 8 | 8 |
The margin filter alone keeps the weak match for S6. The cosine floor alone keeps the crowded match for S8. Applying all three filters retains the eight correct winners. That result follows from the constructed score patterns. Estimate real filter precision and recall on independently labeled pairs.
Aligning a document
Mining gives candidate document pairs. To see how sentence alignment works on one, we use a five-sentence English paragraph paired with a six-sentence German translation in which one English sentence was split into two German sentences. The example uses a length-only dynamic program inspired by Gale–Church.
PythonIn [16]Expand
en_para = [
"The committee met on Tuesday to discuss the budget.",
"Several members raised concerns about the proposed cuts.",
"In the end, they agreed to postpone the decision.",
"The chair thanked everyone.",
"The next meeting will be held in May.",
]
de_para = [
"Der Ausschuss traf sich am Dienstag, um den Haushalt zu besprechen.",
"Mehrere Mitglieder äußerten Bedenken.",
"Es ging dabei um die vorgeschlagenen Kürzungen.",
"Am Ende einigten sie sich darauf, die Entscheidung zu verschieben.",
"Die Vorsitzende dankte allen.",
"Das nächste Treffen findet im Mai statt.",
]
en_lens = [len(s) for s in en_para]
de_lens = [len(s) for s in de_para]The paragraph is constructed so that a naive index-based pairing would fail:
- English sentence 1 corresponds to German sentence 1.
- English sentence 2 corresponds to German sentences 2 and 3 together.
- From that point on, every index is off by one.
A pipeline that assumed sentence aligns to sentence would produce four wrong pairs out of five, which is exactly the kind of silent corruption that ruins a mined corpus.
This length-only dynamic program shares the prefix-alignment idea of Gale-Church and uses the conditional Gaussian teaching score above.
PythonIn [17]Expand
MOVES = [(1, 1), (1, 0), (0, 1), (2, 1), (1, 2), (2, 2)]
MOVE_LOG_PRIOR = {
(1, 1): 0.0,
(1, 0): -6.0,
(0, 1): -6.0,
(2, 1): -2.0,
(1, 2): -2.0,
(2, 2): -5.0,
}
def gc_logprob(l1, l2, c, s2):
if l1 == 0 or l2 == 0:
return 0.0
return -0.5 * np.log(2 * np.pi * s2 * l1) - ((l2 - c * l1) ** 2) / (
2 * s2 * l1
)
def align_gc(src_lens, tgt_lens, c=1.0, s2=7.5, merge_22_log_weight=-5.0):
move_log_weights = {**MOVE_LOG_PRIOR, (2, 2): merge_22_log_weight}
n, m = len(src_lens), len(tgt_lens)
dp = np.full((n + 1, m + 1), -np.inf)
back = -np.ones((n + 1, m + 1), dtype=int)
dp[0, 0] = 0.0
for i in range(n + 1):
for j in range(m + 1):
if not np.isfinite(dp[i, j]):
continue
for mi, (di, dj) in enumerate(MOVES):
ni, nj = i + di, j + dj
if ni > n or nj > m:
continue
l1 = sum(src_lens[i:ni])
l2 = sum(tgt_lens[j:nj])
if l1 == 0 and l2 == 0:
continue
score = (
dp[i, j]
+ gc_logprob(l1, l2, c, s2)
+ move_log_weights[(di, dj)]
)
if score > dp[ni, nj]:
dp[ni, nj] = score
back[ni, nj] = mi
pairs = []
i, j = n, m
while i > 0 or j > 0:
mi = back[i, j]
di, dj = MOVES[mi]
pairs.append((list(range(i - di, i)), list(range(j - dj, j))))
i, j = i - di, j - dj
pairs.reverse()
return pairs, dp[n, m]The back array stores the move that produced each best score, so the function can recover the path from the final cell. The example assumes positive character lengths and . The additive values in MOVE_LOG_PRIOR penalize splits, merges, and gaps relative to a one-to-one move. They are illustrative weights, with (2,2) optionally overridden for the comparison below.
We estimate the length ratio from the data and run the aligner.
PythonIn [18]Expand
c_hat = sum(de_lens) / sum(en_lens)
pairs, score = align_gc(en_lens, de_lens, c=c_hat, s2=7.5)
loose_pairs, _ = align_gc(
en_lens, de_lens, c=c_hat, s2=7.5, merge_22_log_weight=-3.0
)
gc_rows = []
for src_idx, tgt_idx in pairs:
gc_rows.append(
{
"english": " ".join(en_para[k] for k in src_idx),
"german": " ".join(de_para[k] for k in tgt_idx),
"shape": f"{len(src_idx)}-{len(tgt_idx)}",
}
)
gc_df = pd.DataFrame(gc_rows)Estimated length ratio c = 1.300 Move shapes with a weaker 2-to-2 penalty: [(1, 1), (1, 2), (2, 2), (1, 1)]
| english | german | shape | |
|---|---|---|---|
| 0 | The committee met on Tuesday to discuss the bu... | Der Ausschuss traf sich am Dienstag, um den Ha... | 1-1 |
| 1 | Several members raised concerns about the prop... | Mehrere Mitglieder äußerten Bedenken. Es ging ... | 1-2 |
| 2 | In the end, they agreed to postpone the decision. | Am Ende einigten sie sich darauf, die Entschei... | 1-1 |
| 3 | The chair thanked everyone. | Die Vorsitzende dankte allen. | 1-1 |
| 4 | The next meeting will be held in May. | Das nächste Treffen findet im Mai statt. | 1-1 |
At the displayed 2-to-2 log weight of , the program finds the intended 1-to-2 split at English sentence 2 and four 1-to-1 matches. Relaxing that weight to leaves the split intact but groups English sentences 3 and 4 with German sentences 4 and 5. The table and figure use . The additional printed path shows how the assumed move weights change what the same length evidence supports.
The example estimates from the complete paired paragraph. An application can estimate a stabler value from a representative set of aligned segments rather than using a single noisy document.
Dictionary or embedding evidence can distinguish plausible segmentations with similar lengths. Compare a length-only baseline with the added signal on the same held-out human alignments to see whether it helps.
Key Parameters
- Encoder. The choice changes the geometry and cosine distribution. Measure performance on your target languages.
- Neighborhood size. For the one-sided toy score, choose the number of other targets averaged after excluding the candidate.
- Cosine and margin cutoffs. Calibrate the floors on labeled candidates from your intended domain. The toy cutoffs illustrate two constructed failure cases.
- Length-ratio interval. Choose a length unit and estimate an interval for the pair and domain.
- Length model parameters. The example estimates from the paired text and uses a fixed illustrative . Move weights can also change the selected segmentation.
VisualizationOut [20]Expand

Back-Translation and Synthetic Parallel Data
Mining recovers candidate bitext that already exists. Back-translation constructs additional pairs from monolingual text on the target side. Translate each target sentence into the source language with a backward model, then pair the generated source with the original target.
Sennrich, Haddow, and Birch (2016) reported gains from this approach on their English–German and Turkish-to-English neural translation tasks. Two properties matter when choosing how to use it.
- Additional coverage. Target-side monolingual data can add vocabulary and domains that are scarce in the available bitext.
- Synthetic source cues. The decoding strategy changes the generated sources. Caswell et al. (2019) found that tagging those sources could deliver gains similar to adding noise in their experiments.
The direction matters. To train a source-to-target system with back-translation, generate source-language sentences from authentic target text. Forward translation generates target-language sentences from authentic source text, which changes the supervision the model receives.
The loss with back-translated data
The training objective becomes a weighted combination:
where:
- : the authentic bitext
- : the synthetic bitext produced by the backward model
- : the weight that controls the mix of synthetic and authentic data
You can control the influence of synthetic examples with the loss weight, with the frequency at which the sampler draws them, or with both.
For authentic pairs, synthetic pairs, and , divide the weighted loss by when that sum is positive. Drawing a synthetic pair with probability and sampling uniformly within each group gives the same expected normalized loss. Finite training runs can still see different examples, batches, and gradients. Tune the mixture on held-out authentic bitext for the intended domain.
Variants
Several refinements matter at scale.
- Iterative back-translation. Train translation systems on earlier synthetic pairs, then use the updated backward model to generate new pairs. Hoang et al. (2018) reported gains in their tested settings. Evaluate each round against the previous model before using its output for another round.
- Tagged back-translation. Caswell et al. (2019) prepend a special tag to synthetic source sentences so the forward model can distinguish them from authentic sources.
- Online versus offline. Offline back-translation generates the synthetic corpus before training. Online back-translation generates examples during training and can use an updated backward model, with additional generation work during training.
- Quality filtering. Inspect synthetic pairs for adequacy, length, and language. Calibrate any cutoffs on samples from the generation setup because the sources can differ from ordinary mined text.
The quality of the backward system matters. In the English–German experiments of Hoang et al. (2018), synthetic data from the weakest backward systems provided no benefit over the corresponding baseline. Track each translation direction on held-out authentic pairs, since improving one round or direction gives no guarantee about the next.
A data augmentation technique in which a target-side monolingual sentence is translated into the source language by a backward model, producing a synthetic source-target pair for training. Gains depend on the ratio of synthetic to authentic data and on the quality of the backward model.
A toy lexical coverage filter
Use a fixed word lookup as a small stand-in for backward translation. Its coverage is visible by construction: an out-of-dictionary word produces <unk>. For this example the fraction of recognized words measures only dictionary coverage. It cannot check word order or whether the generated English carries the same meaning.
PythonIn [21]Expand
de_mono = [
"Die Katze saß auf der Matte.",
"Wo ist der Bahnhof?",
"Ich hätte gerne eine Tasse Kaffee, bitte.",
"Das Wetter ist heute wunderschön.",
"Die Regierung kündigte heute neue Maßnahmen an.",
]
de_to_en_toy = {
"die": "the",
"katze": "cat",
"saß": "sat",
"auf": "on",
"der": "the",
"matte": "mat",
"wo": "where",
"ist": "is",
"bahnhof": "train station",
"ich": "i",
"hätte": "would like",
"gerne": "gladly",
"eine": "a",
"tasse": "cup",
"kaffee": "coffee",
"bitte": "please",
"das": "the",
"wetter": "weather",
"heute": "today",
"wunderschön": "beautiful",
}
def toy_backtranslate(sent: str) -> tuple[str, float]:
tokens = [word.strip(".,!?") for word in sent.lower().split()]
tokens = [word for word in tokens if word]
translated = [de_to_en_toy.get(word, "<unk>") for word in tokens]
coverage = (
sum(word in de_to_en_toy for word in tokens) / len(tokens)
if tokens
else 0.0
)
return " ".join(translated), coverage
backtranslations = [toy_backtranslate(sentence) for sentence in de_mono]
bt_df = pd.DataFrame(
{
"german": de_mono,
"back_translated_english": [output for output, _ in backtranslations],
"dictionary_coverage": [coverage for _, coverage in backtranslations],
}
)
bt_df["keep"] = bt_df["dictionary_coverage"].ge(0.8)| german | back_translated_english | dictionary_coverage | keep | |
|---|---|---|---|---|
| 0 | Die Katze saß auf der Matte. | the cat sat on the mat | 1.000 | True |
| 1 | Wo ist der Bahnhof? | where is the train station | 1.000 | True |
| 2 | Ich hätte gerne eine Tasse Kaffee, bitte. | i would like gladly a cup coffee please | 1.000 | True |
| 3 | Das Wetter ist heute wunderschön. | the weather is today beautiful | 1.000 | True |
| 4 | Die Regierung kündigte heute neue Maßnahmen an. | the <unk> <unk> today <unk> <unk> <unk> | 0.286 | False |
The dictionary recognizes every word in the first four sentences and two of the seven words in the fifth. With the example cutoff of , the fifth pair is rejected. High coverage only verifies that the decoder used known entries. To run a two-leg round-trip check on real back-translated data, translate the synthetic source forward into the original target language and compare the resulting sentence with the original target. Treat agreement as one signal of consistency, since both models can share errors.
Synthetic Parallel Data from Stronger Models
A teacher can generate synthetic source or target text for training a student. Choose what to generate, keep the authentic side identifiable, and test whether the resulting pairs improve the intended model.
The workflow looks like this:
- Select monolingual inputs. Choose text for the side that will stay authentic and for the domain you want the student to cover.
- Translate with the teacher. Use greedy or a fixed decoding policy and preserve generated outputs for repeatable comparisons.
- Choose quality checks. Inspect teacher outputs for the recurring errors relevant to your task.
- Mix with authentic data. Compare several sampling weights while evaluating against the same authentic validation set.
- Validate on a human-translated test set. Measure whether the gains hold.
A fixed decoding policy is part of the experimental setup. Low-temperature sampling can still produce different translations across runs. Archive the generated corpus with the teacher checkpoint, decoding settings, and sampling seed when one is used.
Check synthetic pairs for repeated teacher errors as well as isolated mistakes. A generator that consistently mistranslates a phrase can repeat the same bad target across different examples. Set the review policy using labeled synthetic and authentic pairs from the intended task.
- Style narrowing. Repeated teacher phrasing can make the generated targets less varied.
- Hallucinated content. The teacher adds information the source does not contain.
- Domain mismatch. Check how the teacher handles terminology and register in the intended domain.
- Licensing and provenance. Record the input collection, model checkpoint, generation terms, and intended use. Check those terms before distributing outputs.
A single error rate can hide what the examples teach. If wrong targets repeatedly copy their source, an English-to-German student sees repeated examples in which copying is rewarded. Inspect the kinds of error you retain and test whether they recur in the trained model.
For more on generation and filtering, see Synthetic Data. Recursive Training and Model Collapse examines what can happen when generated data enters successive training rounds.
Contamination Checks
Training–evaluation contamination occurs when training includes content the evaluation is meant to hold out. Shared sources are a reason to audit actual membership. FLORES-101 used Wikipedia in its original release, while the IWSLT 2014 evaluation used TED and TEDx talks. Check the exact release and split against your own data. FLORES-101 paper · IWSLT 2014 organizers
Suppose a crawl and a later evaluation both draw from the same news site. The crawl might contain a test article, a revised copy, or another article about the same event. Compare the actual training and evaluation texts before interpreting a benchmark score as evidence of generalization.
The two screens here compare lexical overlap and embedding similarity. Both propose candidate overlaps for inspection.
N-gram overlap
For each test sentence with -grams , compute the fraction of -grams that also appear in the training corpus :
where:
- : a test sentence
- : the training corpus
- : the set of -grams extracted from the test sentence
- : the set of -grams occurring anywhere in the training corpus
- : the number of test -grams that also occur in the training corpus
- : the total number of test -grams, which normalizes the count into a fraction
Choose the n-gram length and flagging threshold for the kind of overlap you want to catch. A test string shorter than has no -grams to compare.
- Replacing one token affects at most contiguous length- windows. The token's position, the sentence length, and repeated grams determine how many distinct grams are lost. Short grams can also match common phrases in unrelated text.
- Larger requires longer shared sequences and can miss rewritten sentences.
The example uses lowercase whitespace tokens and a set of distinct grams. Choose preprocessing rules to match the risk you want to measure and report those rules with the overlap results.
Containment measures the fraction of test grams found anywhere in training. Distinct grams can be scattered across unrelated training rows, so a score of one alone does not establish a verbatim copy. If an exact test string with at least tokens is present after the same preprocessing, all of its grams occur in the corpus.
PythonIn [23]Expand
def ngram_set(text: str, n: int) -> set:
tokens = text.lower().split()
return {
tuple(tokens[i : i + n]) for i in range(max(len(tokens) - n + 1, 0))
}
def containment(test: str, corpus: list[str], n: int = 3) -> float | None:
if n < 1:
raise ValueError("n must be positive")
test_ng = ngram_set(test, n)
if not test_ng:
return None
corpus_ng = set()
for doc in corpus:
corpus_ng |= ngram_set(doc, n)
return len(test_ng & corpus_ng) / len(test_ng)
train_corpus = [
"The quick brown fox jumps over the lazy dog.",
"Machine translation systems rely on large parallel corpora.",
"Neural networks learn distributed representations of words.",
"The committee met on Tuesday to discuss the budget.",
]
test_sents = [
"The committee met on Tuesday to discuss the budget.",
"The committee met on Thursday to discuss the budget.",
"Machine translation systems rely on large monolingual corpora.",
"A new restaurant opened downtown last week.",
]| test_sentence | containment_3gram | flagged | |
|---|---|---|---|
| 0 | The committee met on Tuesday to discuss the bu... | 1.000000 | True |
| 1 | The committee met on Thursday to discuss the b... | 0.571429 | True |
| 2 | Machine translation systems rely on large mono... | 0.666667 | True |
| 3 | A new restaurant opened downtown last week. | 0.000000 | False |
At , the exact copy scores , the date replacement scores , the terminology replacement scores , and the new topic scores . The cutoff flags the first three rows, including the terminology replacement, which shares a prefix with its training neighbor. These scores are overlap signals. The two changed sentences have different edits and lengths, so there is no reason for their scores to be in narrative order.
The containment scores from the table are easier to compare as a bar chart.
VisualizationOut [25]Expand

At , the exact copy still has all of its grams in the corpus. The date replacement has none. At every test row is too short to evaluate. Report those rows as unscored or check them using a separate exact string match.
Embedding similarity
Two paraphrases can share no word n-grams. A multilingual encoder can propose additional candidates by retrieving close training vectors for each evaluation sentence. Calibrate the score and check the returned texts, including translations and same-topic nonmatches.
Run lexical matching first if it reduces the volume of work for the embedding step in your setup. Use embedding similarity to look for some paraphrases or translations that wording-based matching misses.
A lexical comparison can identify exact copies under its tokenization and surface some near copies. A semantic comparison can retrieve independent texts on the same topic and still miss paraphrases or translations. Report what each pass searches and inspect examples it flags or misses.
Removing contamination
An overlap report can flag a test item or a training document for action. Use the decision that matches which artifact you can change:
- Replace flagged evaluation items. Document how the revised evaluation changes coverage and report its version.
- Exclude flagged training pairs. Record the rejected row IDs and look for remaining copies elsewhere in the corpus.
- Exclude flagged training documents. Remove their candidate pairs when surrounding context or repeated versions make row-by-row removal inadequate.
Removing a flagged document preserves benchmark membership and excludes all pairs you derived from that document. An undetected copy in a second document or a reformulation may remain. The fixture above reports flags and does not simulate document deletion.
For a release you control, publish which splits and languages you compared, the normalization or encoder, the cutoff, and how you handled flagged items. We return to benchmark validity in Benchmark Evaluation.
A pair can overlap by exact text, near copy, paraphrase, or translation. Detection depends on the benchmark and comparison method. Yang et al. found that lexical screening missed translated contamination in their settings and that the tested semantic methods differed. Yang et al., §5.2.1 and Table 5
Limitations and Impact
Mining converts retrieval and filtering decisions into the examples a translation model sees. Audit what those decisions keep and reject by language, domain, and type of error.
Noise type matters. Khayrallah and Koehn injected several types of noise into their training data. In one condition, copied source-language targets led the neural systems to copy inputs. Compare downstream results at matched noise rates before attributing an effect to the rate alone. Khayrallah and Koehn, 2018
Evaluate the filter with the model and training recipe you will use. Retest when the domain or training phase changes, and compare both the retained data and downstream errors.
Calibrate by language pair. A cutoff learned on English–German can over-filter or under-filter another pair. Compare labeled score distributions, accepted fractions, and rejection errors. Repeat the check for both length and QE filters if you use them.
If a cutoff rejects otherwise valid examples in one language, that language has fewer pairs in the resulting corpus. Trace the loss to retrieval, scoring, or the threshold before deciding which step to change.
Encoder scores depend on the encoder. A cosine value from LaBSE and another from SONAR come from different embedding spaces. Compare their decisions on the same labeled candidates and report per-language score distributions.
Suppose you report a mean ratio-margin score for each of 100 languages. If ten language means are 1.02 and the other ninety average about 1.0867, giving each language equal weight yields an overall mean of 1.08. These averages do not say how many pairs cross a cutoff. Report each language's score distribution and the fraction retained.
Record provenance and release terms. Keep the original source and release identifiers alongside any license or permissions metadata. Check the specific source and intended use before including it. Part XXI: Data Governance, Provenance, and Synthetic Ecosystems
Record whether a permission comes from the actual corpus release, its source documents, or an unresolved source. If your policy requires documented permission, track which sources you excluded so the remaining language and domain coverage can be audited.
Report overlap-screening scope. A benchmark score alone does not reveal training–evaluation duplication. Record which evaluation versions you screened, how you found matches, and what you removed.
Measure coverage after filtering. Large mined releases show what retrieval can collect. The relevant measure for a new project is the number and quality of verified pairs in each intended language and domain.
Summary
Parallel data mining and quality control turn raw web text into training data for translation systems. The essential ideas:
- Bitext mining is retrieval in a shared multilingual embedding space. Compute sentence embeddings, retrieve nearest neighbors across languages, and score pairs with the margin criterion to filter out generically similar but incorrect matches.
- Calibrate filters on labeled candidates. A margin and an absolute cosine floor can catch different mistakes. The intersection only improves precision when it rejects incorrect pairs at a higher rate than it rejects correct pairs.
- Sentence alignment operates on document pairs. Gale-Church uses length and DP, Hunalign adds a dictionary, Bleualign uses an MT system, and Vecalign uses embeddings. A length-only algorithm can miss the correct segmentation even in a short document.
- Use word alignment where it helps. A checked alignment can support lexicon extraction or coverage checks. Sentence-level neural training can also proceed without explicit links.
- Back-translation manufactures parallel data from monolingual text. Translate monolingual target text into the source language, check the resulting pairs, and choose a mixture with authentic data on held-out human translations.
- Filter teacher outputs and measure the result. Record which side was generated, the checkpoint and decoding settings, and the evaluation results for the chosen mix.
- Screen evaluation overlap. Use lexical matching and semantic retrieval as complementary checks. Report their thresholds, coverage, and the treatment of flagged items.
- Report what filtering changes. Inspect retention and errors by language and domain, and track the provenance of the included examples.
Measure coverage, yield, and downstream errors together. A stricter filter can remove bad pairs and useful pairs at the same cutoff.
The next chapter in Machine Translation and Speech Translation, Many-to-Many and Low-Resource Translation, considers ways to share supervision when mining yields little bitext and the backward model is weak.
Quiz
Ready to test your understanding? Take this quick quiz to reinforce what you've learned about parallel data mining, alignment, and quality control.
Parallel Data Mining and Quality Control Quiz
Join the discussionAsk a question or share what you learned.
Keep exploring
Reference
Citation details
Cite or share this article.


Comments
Add to the conversation
A question, a correction, or an example from your own work.
No comments yet. Be the first to share your thoughts!