Machine translation: matching words is only one part of the job
机器翻译
Define translation requirements, derive a lexical alignment model, and separate likelihood, decoding and translation quality.
machine-translationA dictionary can preserve the words and lose the instruction
Imagine a shop translating an invented delivery notice: “The courier must not leave the parcel outside.” A system that keeps the nouns but drops “not” changes the instruction. A system that uses a different natural phrase may preserve it perfectly. The task is to convey the source meaning in a target language under a specified style and domain, not merely to maximize shared vocabulary.
Start with a non-learning baseline: reuse an approved translation when the full notice matches exactly, apply an approved glossary to terminology, and route unmatched material to a qualified translator. Measure coverage and handling time. A learned system should improve that workflow on new notices while preserving negation, numbers, names and required terminology. Its acceptable error rate depends on the use case; a product label and an informal browsing aid need different review policies.
Separate three components. A translation model assigns scores to possible outputs. A decoder searches among them. An evaluation procedure decides whether the outputs satisfy the task. A higher model score is not automatically a better translation, and an approximate decoder may fail to find even the best model-scored candidate.
What a lexical alignment model knows—and cannot know
One possible decoding target is the most probable complete output given source x:
The optimization ranges over sequences, including their lengths. It is different from selecting the most probable word independently at each source position. Neural sequence models can factor this conditional probability over successively generated target tokens and learn an EOS decision. Conditional sequence model, §2
To inspect a simpler component, consider IBM Model 1. Let source length be L and insert NULL at source position zero. Let target length M be given. A lexical table T assigns a target-word distribution to each source-word type. Each target position j independently chooses a source alignment position a-j uniformly among L+1 positions, then emits its target word:
Summing over alignments is tractable because the choices factor across target positions:
This is the Model 1 lexical/alignment component conditioned on length. Brown and colleagues describe its uniform alignments, NULL word and efficient marginalization. Their presentation temporarily uses a constant length factor; the program here instead conditions on M explicitly. It does not fit a normalized distribution over output lengths. Model 1, §4.1, printed pp.270–272
For fitting, Bayes’ rule gives the posterior responsibility of source position i for target occurrence j:
Add these fractional counts across the parallel training pairs. E and V below denote source vocabulary size including NULL, and target vocabulary size. C has shape E-by-V; its M-step is row normalization:
Repeated words are repeated positions. For source [1,1], target [0,1], and lexical rows [[.5,.5],[.8,.2],[.1,.9]], the target-0 responsibilities are [5/21,8/21,8/21]. The two copies of source ID 1 both contribute. Target-1 responsibilities are [5/9,2/9,2/9]. Their marginal target probabilities are 0.7 and 0.3, giving sequence probability 0.21. One M-step changes the NULL row to [3/10,7/10] and source-1 row to [12/19,7/19].
An unseen source type has no expected count; the program keeps its previous row. If all source positions assign zero probability to an observed target, it reports an error rather than hiding it with an epsilon. Positive initialization avoids many such accidental zero exclusions. EM should not reduce this training likelihood beyond rounding, but a flat objective can leave multiple parameter settings indistinguishable. A monotone trace does not prove a unique dictionary or meaningful alignment.
Fit the component and expose its missing word order
This complete original NumPy program uses invented parallel symbol pairs. Source IDs 1 and 2 stand for apple and pear; target IDs 0 and 1 stand for 苹果 and 梨. NULL has its own source row. The experiment fits lexical probabilities; it is not a sentence translator. Run with Python 3.12 and NumPy 1.26.4.
"""Original IBM Model 1 component, conditioned on the output length.
No length distribution or language model is fitted. This lexical alignment
component cannot distinguish output permutations and is not a full translator.
Source ID 0 is NULL and is inserted once by this implementation.
"""
import itertools
import json
import math
import numpy as np
def integer(x, low, high):
if isinstance(x,(bool,np.bool_)) or not isinstance(x,(int,np.integer)) or not low<=x<=high:
raise ValueError(f'Expected integer in [{low},{high}]')
return int(x)
def table(value):
t=np.asarray(value,dtype=float)
if t.ndim!=2 or not 1<=t.shape[0]<=64 or not 1<=t.shape[1]<=64:
raise ValueError('Use a 1..64 by 1..64 lexical table, including NULL')
if not np.isfinite(t).all() or (t<0).any() or not np.allclose(t.sum(1),1,rtol=0,atol=1e-12):
raise ValueError('Each lexical row must be a probability distribution')
return t
def sentence(source,target,t):
source=list(source);target=list(target)
integer(len(source),0,32);integer(len(target),0,32)
for token in source:integer(token,1,len(t)-1)
for token in target:integer(token,0,t.shape[1]-1)
return [0]+source,target
def posterior(source,target,t):
"""Position responsibilities q[j,i] and log P(target | source, length)."""
t=table(t);source,target=sentence(source,target,t)
weights=t[np.asarray(source)][...,target].T
denom=weights.sum(1)
if (denom==0).any():
raise ValueError('An observed target has zero probability under every source position')
q=weights/denom[:,None]
return q,float(np.log(denom/len(source)).sum())
def expectation(pairs,t):
t=table(t);pairs=list(pairs);integer(len(pairs),1,64)
counts=np.zeros_like(t);ll=0.
for source,target in pairs:
source,target=sentence(source,target,t)
q,value=posterior(source[1:],target,t);ll+=value
for j,word in enumerate(target):
# Repeated source IDs occupy different alignment positions.
np.add.at(counts[:,word],source,q[j])
return counts,ll
def fit(pairs,initial,steps=40):
t=table(initial).copy();pairs=list(pairs);integer(steps,0,500)
_,ll=expectation(pairs,t);trace=[ll]
for _ in range(steps):
expected,_=expectation(pairs,t);denom=expected.sum(1,keepdims=True)
t=np.divide(expected,denom,out=t.copy(),where=denom>0)
_,value=expectation(pairs,t)
if value<trace[-1]-1e-10*(1+abs(trace[-1])):
raise ArithmeticError('EM likelihood decreased beyond rounding tolerance')
trace.append(value)
return t,np.asarray(trace)
def enumerate_alignments(source,target,t):
"""Independent exponential reference, limited to 4096 alignments."""
t=table(t);source,target=sentence(source,target,t)
if len(source)**len(target)>4096:
raise ValueError('Enumeration is limited to 4096 alignments')
total=0.;expected=np.zeros((len(target),len(source)))
for alignment in itertools.product(range(len(source)),repeat=len(target)):
mass=1.
for j,i in enumerate(alignment):mass*=t[source[i],target[j]]/len(source)
total+=mass
for j,i in enumerate(alignment):expected[j,i]+=mass
if total==0:
raise ValueError('No positive-probability alignment')
return total,expected/total
def demo():
# Invented aligned training pairs: source IDs apple=1, pear=2;
# target IDs 苹果=0, 梨=1. No held-out translation-quality claim.
pairs=[([1],[0]),([1,1],[0,0]),([2],[1]),([2,2],[1,1]),([1,2],[0,1])]
initial=np.full((3,2),.5);learned,trace=fit(pairs,initial)
hand=np.array([[.5,.5],[.8,.2],[.1,.9]])
q,lp=posterior([1,1],[0,1],hand)
marginal,_=enumerate_alignments([1,1],[0,1],hand)
_,forward=posterior([1,2],[0,1],learned)
_,reverse=posterior([1,2],[1,0],learned)
return dict(lexical_table=learned.tolist(), log_likelihood=trace.tolist(),
hand_responsibilities=q.tolist(), hand_probability=math.exp(lp),
enumerated_probability=marginal,
output_order_log_probabilities=[forward,reverse], steps=40,
conditions='Output length is given; NULL included; invented training data only')
if __name__=='__main__':print(json.dumps(demo(),indent=2,allow_nan=False))
After 40 EM iterations, the observed fruit rows strongly prefer their intended target words, while NULL stays [0.5,0.5]. Yet target orders [0,1] and [1,0] both receive log probability −1.386294 for source [1,2]. Multiplication is commutative, so permuting target words cannot change this model’s score. More training cannot fix an invariance built into the model.
Tests independently enumerate alignments, sum over all short target sequences at a fixed length to check normalization, and verify repeated-position counts and the hand update. The normal E-step takes O(M(L+1)) per sentence; each M-step also normalizes E×V counts. The implementation stores that table and one sentence’s responsibilities. Exponential enumeration is only a reference for at most 4,096 alignments, not the training algorithm. It caps lexical dimensions at 64, sentence lengths at 32 and training pairs at 64.
For a real system, make the surrounding pipeline explicit: collect appropriately usable parallel text, identify language/domain and sentence alignment, split by document before fitting the vocabulary, train on the training portion, choose decoding and terminology constraints on validation data, then inspect a frozen test set. Record source/target tokenization, model version, length limit, latency, cost per processed unit and the fraction requiring review. Check the baseline on exactly the same test items.
Score translations, then inspect what the score misses
BLEU aggregates clipped candidate n-gram matches against references over a corpus, then combines modified precisions p-n with a brevity penalty. For each candidate n-gram, clip its count to the largest count in any single reference; repeated matching words cannot earn unlimited credit. With positive weights summing to one, candidate length c>0 and effective reference length r:
The original baseline uses N=4 and equal weights; r sums per-sentence closest reference lengths. Any zero precision yields zero without smoothing. Empty candidates need an explicit convention. Corpus BLEU is not an arithmetic mean of sentence BLEU, nor the percentage of correctly translated sentences. Metric definition, §§2.1–2.3
For comparison, record the exact test set, references, segmentation, case handling, smoothing and score scale. Inspect meaning-sensitive errors separately: a missing negation can be harmful despite extensive phrase overlap. Our program does not compute BLEU or claim an industry score; its output is an alignment-component experiment.
Model 1 lacks target word order and context-sensitive lexical meaning. A richer sequence model addresses a different hypothesis class, but still needs evidence about rare terms, changed domains and constrained content. Similar-looking source and test sentences can leak through document duplicates. Keep document-level partitions and analyze errors by category instead of relying on one average. When comparing two systems, paired judgments on the same sources help reveal whether a gain comes from the examples that matter to the workflow.
Decide whether a better number solves the task
- Why can the Model 1 component assign the same score to two target word orders?
Answer: Its marginalized likelihood is a product of position-independent word terms. Permuting those terms leaves the product unchanged. It has no target order mechanism to learn.
- In the hand example, what is the total responsibility of source ID 1 for target word 0?
Answer: 8/21+8/21=16/21. The two source positions share a word ID but both remain possible alignment positions; deduplicating them would change the model.
- A source word has zero expected counts in the corpus. Does preserving its old lexical row establish the correct translation?
Answer: No. The data did not identify that row. Preserving it is an explicit implementation convention, not learned evidence. Add suitable data or report the uncertainty.
- Two systems have different BLEU scores, but one used different references and segmentation. Can the larger number determine which system to deploy?
Answer: No. First evaluate both under the same declared protocol, then compare the workflow’s error categories, review burden and cost. A metric difference under incompatible conditions does not isolate model quality.
Follow one component through a complete translation workflow
Brown and colleagues provide the lexical alignment model examined here. Sutskever and colleagues provide a conditional sequence-learning formulation with learned generation and termination. Papineni and colleagues provide the BLEU definition. These are different contributions, not interchangeable measures of translation competence. This article reproduces none of their reported benchmark results; its numerical evidence concerns only the original small lexical experiment.
Make a prediction, then check
Why does Model1 give equal scores to two permutations of the same target words?
Learning objectives
- Separate translation requirements, model scores and decoding.
- Derive Model1 responsibilities and expected lexical counts.
- Explain why output-length conditioning does not model length choice.
- Compare translations under a fixed evaluation protocol.
Prerequisites & connections
Explore related knowledge →References
- The Mathematics of Statistical Machine Translation: Parameter Estimation
Peter F. Brown, Stephen A. Della Pietra, Vincent J. Della Pietra, Robert L. Mercer · 1993 - Bleu: a Method for Automatic Evaluation of Machine Translation
Kishore Papineni, Salim Roukos, Todd Ward, Wei-Jing Zhu · 2002 - Sequence to Sequence Learning with Neural Networks
Ilya Sutskever, Oriol Vinyals, Quoc V. Le · 2014
Version1 · Editorial status: Recorded technical checks completed
View technical check record (AI)
Codex · 2026-09-12 · Single AI author checked six paired equations, four explained exercises and the engineering workflow against scoped Brown Model1 and visually checked BLEU definitions, with Sutskever conditional generation. Independent alignment enumeration, fixed-length normalization, repeated-position responsibilities,0.21 marginal, row updates, empty/zero-probability cases and nonidentifiability checked. Output-order equality exposes the lexical component limit; no full translator or benchmark reproduction claimed.
- Single AI author checked six paired equations, four explained exercises and the engineering workflow against scoped Brown Model1 and visually checked BLEU definitions, with Sutskever conditional generation. Independent alignment enumeration, fixed-length normalization, repeated-position responsibilities,0.21 marginal, row updates, empty/zero-probability cases and nonidentifiability checked. Output-order equality exposes the lexical component limit; no full translator or benchmark reproduction claimed.
- Four computed SVGs bind exact bilingual MDX. The four-topic group passed eight numeric/encoding checks and24 isolated language/width cases with four fallback fonts; eight actual screenshots inspected by the AI author. Literal-prose AST checked before freezing. Full article browser acceptance is separate; no human peer review.
Source locations checked:
- The Mathematics of Statistical Machine Translation: Parameter Estimation · Section4.1, printed270/272 visually checked: Model1, NULL, length-factor caveat, marginalization and expected counts. Other models and benchmark tables not reproduced.
- Bleu: a Method for Automatic Evaluation of Machine Translation · Sections2.1–2.3 and physical page5 visually checked: clipped corpus n-grams, closest reference lengths, brevity penalty and geometric combination. Full human evaluation and correlations not reproduced.
- Sequence to Sequence Learning with Neural Networks · v3 dated2014-12-14; first submitted2014-09-10. Section2 layout118–157 and beam decoding193–211: conditional sequence factorization, LSTM encoder/decoder and EOS. Toy tanh program is original, not paper reproduction.
Related topics