Machine translation
Study notes on Machine Translation: definitions, statistical and neural methods (noisy-channel, IBM Model 1 EM, phrase-based SMT, encoder–decoder with attention, Transformer), formulas, worked exam-style answers, common mistakes, and quick checks.
Drafted with Aria, reviewed by the AiCanCode.org team · Updated . How we write and check our notes. Spotted an error? Use Give Feedback at the bottom of the page.
Why it matters
Machine translation (MT) turns text in one language to text in another automatically. Engineers use MT in multilingual applications: cross-language information access, user-facing translation services, localisation pipelines, and as components in bigger NLP systems (search, summarisation, assistants).
Key ideas
Parallel corpus — a dataset of sentence pairs (source, target) assumed to be translations of each other. MT methods learn from parallel corpora; monolingual corpora are used for language models, back-translation, or unsupervised MT.
Noisy-channel model — a decomposition of the translation problem using Bayes' rule. We want the best target sentence e given a source sentence f. By Bayes: choose e that maximises P(e|f) = P(f|e)P(e)/P(f). Since P(f) is constant for given f, we pick e to maximise P(f|e)P(e). Here P(e) is the language model (fluency of e) and P(f|e) is the translation model (how likely e generates f). Assumption: translation generation is modelled as a channel that produces f from e.
Step-by-step derivation (exam style):
- Start with definition: we seek e* = argmax_e P(e|f).
- Apply Bayes' rule: P(e|f) = P(f|e)P(e)/P(f).
- Since P(f) constant over e, e* = argmax_e P(f|e)P(e).
Word alignment — a mapping between words (or positions) in target and source sentences indicating which words translate to which. In many models, we introduce a hidden alignment variable a and model P(f|e) = sum_a P(f, a | e). Assumption: alignments explain how source words are generated from target words.
IBM Model 1 — the simplest statistical alignment model. Assumptions: (1) Bag-of-words model with no distortion: each source token is generated independently given the target sentence and its (hidden) aligned target token (no fertility modelling); (2) Uniform alignment prior: every alignment position (including a NULL token) is equally likely. Parameter: t(f|e) = probability that target word e translates to source word f. Use Expectation–Maximisation (EM) to estimate t.
EM sketch for IBM Model 1 (exam derivation required):
- E-step: compute expected counts c(e,f) using current t, where expected count for a given sentence pair (e, f) and source token f_i is t(f_i|e_j) normalized over all e_j (including a NULL token).
- M-step: update t(f|e) = total_expected_count(e,f) / total_expected_count(e,·) (normalise over all f).
Phrase-based SMT — extends word-based models by learning phrase correspondences (source phrase ↔ target phrase) and their probabilities, plus a reordering model. Main components: phrase table (phrase translation probabilities), distortion model (penalise reordering), and language model. Assumption: translation units can be contiguous phrases. Scoring is usually a log-linear combination of features with weights tuned on a development set (e.g., MERT/MIRA/PRO), and decoding uses beam search.
Evaluation: BLEU — an automatic metric comparing n-gram overlap between candidate translation and one or more references. Uses modified n-gram precisions and a brevity penalty to penalise short outputs.
Neural Machine Translation (NMT) — end-to-end models that directly model P(e|f) with neural networks, typically using an encoder to convert source to continuous representations and a decoder that generates the target sentence. NMT learns from parallel corpora by maximum likelihood training. In practice, NMT is often improved using monolingual target data via back-translation.
Encoder–decoder (sequence-to-sequence) — architecture where an encoder (often recurrent or Transformer blocks) converts source tokens into vectors; a decoder generates target tokens conditioned on encoder outputs and previously generated tokens.
Attention mechanism — allows the decoder to focus on different parts of the source when generating each target token. For each decoder step, compute compatibility scores between a decoder query and encoder keys, convert to weights via softmax, and produce a weighted sum of encoder values.
Exam derivation to show: scaled dot-product attention formula and why scaling by sqrt(d_k) helps (it keeps softmax inputs in a reasonable numerical range as dimensionality d_k grows).
Transformer — an architecture using stacks of self-attention and feed-forward layers, with positional encodings to inject token order. Advantages: parallel computation over sequence length, better long-range modelling; downside: self-attention cost grows quadratically with sequence length.
Important assumptions: tokens are split (subword segmentation like BPE), models are trained with teacher forcing, and evaluation often uses BLEU. At inference, decoding is typically done with beam search; NMT often applies a length penalty to avoid favoring short outputs.
Where unsure: I have described standard assumptions of IBM Model 1 and Transformer; hyperparameter-specific behaviors depend on the implementation and are not covered here.
Diagrams to draw when asked in exams:
- For noisy-channel: draw a box labelled "Channel" from target sentence e to observed source sentence f; annotate P(e) before channel and P(f|e) at channel.
- For attention: draw encoder sequence of vectors (boxes) on left, decoder query vector on top; arrows showing similarity scores to each encoder vector; show softmax normalisation to weights and weighted sum to produce context vector.
- For Transformer layer: draw multi-head self-attention block, add & norm, position-wise feed-forward block, add & norm, with residual arrows.
Formulas
e* = argmax_e P(e | f)
- e*: best target sentence; f: source sentence. Applies to decision rule for translation.
P(e | f) = P(f | e) P(e) / P(f)
- Bayes' rule. Probabilities are dimensionless. Use to derive noisy-channel formulation; P(f) constant for given f.
e* = argmax_e P(f | e) P(e)
- Equivalent decision ignoring P(f).
P(f | e) = sum_a P(f, a | e)
- a: alignment variable; sums over all possible alignments. Applies in alignment-based statistical models.
t(f | e) = count(f,e) / sum_{f'} count(f', e)
- IBM Model 1 M-step update: t is translation probability. Dimensionless. count are expected counts from E-step.
Attention(Q, K, V) = softmax(Q K^T / sqrt(d_k)) V
- Q: matrix of queries (dimension n_q × d_k), K: keys (n_k × d_k), V: values (n_k × d_v), sqrt(d_k) scaling keeps dot products numerically stable. Applies to scaled dot-product attention.
softmax(x_i) = exp(x_i) / sum_j exp(x_j)
- Converts scores to probabilities over j. Dimensionless.
BLEU = BP * exp(sum_{n=1}^N w_n log p_n)
- BP: brevity penalty; p_n: modified n-gram precision for n-grams of size n; w_n: weights (often uniform). Dimensionless.
BP = 1 if c > r else exp(1 - r/c)
- c: candidate total length; r: effective reference length. Applies in BLEU computation.
Self-attention complexity per layer = O(n^2 * d)
- n: sequence length; d: model hidden size. This is the time complexity for full self-attention; the dominant additional memory cost is O(n^2) for the attention weights (plus O(n d) for activations).
Worked examples
Example 1 — Derive EM updates for IBM Model 1 and show one E/M iteration on a tiny corpus.
Question (model answer): Explain EM for IBM Model 1 and compute one iteration for corpus: target side vocabulary {e1="house", e2=NULL}, source sentences: f1 sequence [f1="maison"] aligned to target sentence [e1="house"]. Initialise t(f|e) uniformly over source vocab size 1 (so t(maison|house)=1). Show E and M steps.
Answer:
- Define: For IBM Model 1, P(f | e) = product over source positions i of sum over target positions j of t(f_i | e_j) / (|e| + 1) because uniform alignment prior; include NULL token.
- E-step: compute expected counts. Here only one sentence pair. For source token "maison", probability it aligns to "house" is proportional to t(maison|house) and to NULL token t(maison|NULL). With initialisation t(maison|house)=1 and t(maison|NULL)=1, and a uniform alignment prior over the two alignment options (house and NULL), the posterior normalisation gives 0.5 to each.
- Expected count count(house, maison) = 0.5.
- M-step: update t(maison|house) = total_count(house, maison)/total_count(house, ·). If only this one source token and one possible source form, t becomes 1 after normalisation across all f for house. (Show normalisation steps numerically.)
Explain: this example is trivial but shows the expected-count computation and normalisation step. In larger corpora, E-step sums expected counts over all sentence pairs; M-step normalises to produce probabilities.
Example 2 — Compute attention weights for a small numerical example.
Question (model answer): Given Q=[1,0], K=[[1,0],[0,1]], V=[[1,1],[2,2]], and d_k=2, compute Attention(Q,K,V).
Answer:
- Compute Q K^T = [1,0] × [[1,0],[0,1]]^T = [11 + 00, 10 + 01] = [1, 0].
- Divide by sqrt(d_k) = sqrt(2) ≈ 1.414: scores = [1/1.414, 0/1.414] ≈ [0.7071, 0].
- Apply softmax: exp(0.7071)=2.028, exp(0)=1 ⇒ softmax = [2.028/(3.028), 1/3.028] ≈ [0.6696, 0.3304].
- Weighted sum with V: 0.6696*[1,1] + 0.3304*[2,2] = [0.6696+0.6608, 0.6696+0.6608] = [1.3304, 1.3304].
- Final context vector ≈ [1.3304, 1.3304].
Describe diagram: draw query vector pointing to keys with arrows labelled with raw scores, then show softmax weights and final weighted sum.
Example 3 — Short theoretical answer: Compare phrase-based SMT and NMT.
Model answer points (complete answer must include):
- Training data needed: both require parallel corpora, but NMT often needs larger data and is sensitive to domain.
- Modelling: SMT factorises into translation model + language model; NMT models P(e|f) directly with continuous representations.
- Strengths/weaknesses: SMT handles rare words and explicit phrase tables; NMT produces more fluent output and handles context better but may fail on rare words or produce hallucinations.
Common mistakes
- Confusing source and target when naming P(f|e) vs P(e|f).
- For IBM Model 1, forgetting the NULL token or the uniform alignment prior assumption in likelihood.
- For attention, forgetting the sqrt(d_k) scaling factor or miscomputing softmax (not normalising correctly).
- Stating Transformer has linear complexity in sequence length without clarifying that self-attention is quadratic in n.
- For BLEU, using raw n-gram precisions without clipping or missing brevity penalty.
For your exam
Typical question types:
- Definitions and short notes: define MT, alignment, phrase-based SMT, NMT, attention. Full marks: clear definitions with assumptions.
- Derivations: derive noisy-channel decomposition, EM updates for IBM Model 1, attention softmax derivation. Full marks: show each algebra step, explain priors and normalisations.
- Numericals: compute EM E-step counts for a given tiny corpus; compute attention outputs for small matrices. Full marks: show all intermediate calculations and final numeric vector or probabilities.
- Diagrams: draw encoder–decoder with attention, or Transformer layer. Full marks: correctly labelled boxes (encoder, decoder, keys, queries, values, softmax weights), arrows showing flow.
- Essay/comparison: compare SMT and NMT. Full marks: discuss modelling differences, data requirements, typical failure modes, and examples.
Quick check
- State the noisy-channel decision rule for MT in one expression.
- What does the attention mechanism compute from Q, K and V? Name the normalization used.
- In BLEU, what is the purpose of the brevity penalty?
Answers: 1) e* = argmax_e P(f | e) P(e). 2) It computes softmax(Q K^T / sqrt(d_k)) V, using softmax for normalization. 3) To penalise excessively short candidate translations so precision-only scores do not prefer short outputs.
Finished this topic? Mark it so your progress, study plan and readiness keep up.
Stuck on something here?