Natural Language Processing Questions
Core natural language processing building blocks: text preprocessing and tokenization (word, character, subword BPE/WordPiece/unigram, multilingual, Unicode and noisy user-generated text), word and sentence embeddings (Word2Vec, GloVe, contextual embeddings, pooling and semantic similarity search), text classification, sentiment and intent detection (including limited labels, active learning and long documents), sequence labeling and named entity recognition (BIO tagging, CRFs, relation extraction, slot filling and semantic parsing), sequence-to-sequence models and machine translation (teacher forcing, exposure bias, beam search, BLEU, low-resource and cross-lingual transfer), topic modeling and theme extraction, language-model basics such as perplexity, and fine-tuning pretrained encoders like BERT for NLP tasks, including task-appropriate evaluation metrics, annotation and error analysis. Excludes transformer architecture internals, LLM pretraining and decoding behavior, retrieval-augmented generation and vector index engineering, parameter-efficient fine-tuning, and model serving or MLOps.
Design the text preprocessing for training one machine translation model across 10 languages with different scripts. How would you handle normalization, tokenization and vocabulary, and what are the compute implications of your choices?
Sample Answer
Direct answer
I would normalize with Unicode NFC plus a short explicit mapping list, train one shared subword model (SentencePiece, a library that learns a vocabulary straight from raw text, with the BPE algorithm, which repeatedly merges the most frequent adjacent pair, or the unigram algorithm, which prunes a large candidate vocabulary down to the pieces that explain the text best) on text sampled across the ten languages with a temperature that up-weights the small ones, give it a byte fallback (a character never seen in training is spelled out as its raw bytes) so no character is ever unknown, and tell the model the target language with a tag token. The compute consequences come from three numbers: the vocabulary size (it sets the embedding table, which holds one learned vector per vocabulary entry, and the output layer, which scores every vocabulary entry at each position), the tokens-per-word ratio per language (it sets sequence length, and attention cost grows with the square of length), and how many times the training schedule repeats the small languages. I would start with one shared vocabulary of 64,000 pieces and a sampling temperature of 5, then adjust both from the per-language results below. Each number is computed.
1. Normalization: decide what to rewrite, because the target side is rewritten too
Every character has a code point, the number Unicode assigns to it (written U+0041 for A), and one visible letter can be one code point or several. Unicode therefore defines normalization forms that rewrite equivalent spellings into one. NFC composes characters (e plus a combining accent, two code points, becomes the single é). NFKC does that and also maps "compatibility" characters, such as ligatures and fullwidth letters, to plain equivalents. Normalization on the source side only affects the input; on the target side it changes the text the system outputs. The program prints code point counts and the NFKC result for six examples.
import unicodedata
import numpy as np
# 1. What normalization forms do to text from different scripts (code point counts).
samples = {
"fullwidth Latin": "NATO", # fullwidth N A T O
"fi ligature": "fish",
"Arabic lam-alef form": "ﻻ",
"Devanagari qa (precomposed)": "क़",
"superscript two": "x²",
"Japanese half-width katakana": "カナ",
}
print(f"{'sample':30s} {'raw':>3s} {'NFC':>3s} {'NFKC':>4s} NFKC result")
for name, s in samples.items():
nfc, nfkc = unicodedata.normalize("NFC", s), unicodedata.normalize("NFKC", s)
shown = " ".join(f"U+{ord(c):04X}" for c in nfkc)
print(f"{name:30s} {len(s):3d} {len(nfc):3d} {len(nfkc):4d} {shown}")
print("NFKC maps x^2 to 'x2':", unicodedata.normalize("NFKC", "x²") == "x2")
# 2. Temperature sampling over languages. Corpus sizes are INVENTED for illustration (millions of sentence pairs).
langs = ["en", "ru", "zh", "ar", "ja", "hi", "ko", "el", "th", "sw"]
size = np.array([200, 80, 60, 20, 18, 5, 4, 2, 1, 0.3])
budget = 300.0 # millions of sentences seen in training (invented)
print("\nlang size T=1 share T=5 share epochs@T=1 epochs@T=5 seen@T=1 seen@T=5")
p1 = size / size.sum()
p5 = size ** (1 / 5); p5 /= p5.sum()
for l, n, a, b in zip(langs, size, p1, p5):
print(f"{l:4s} {n:6.1f} {a:8.3f} {b:9.3f} {a * budget / n:10.2f} {b * budget / n:10.2f} {a * budget:8.1f} {b * budget:8.1f}")
# The same formula by hand on two languages of size 100 and 1 (million pairs).
two = np.array([100.0, 1.0])
for T in (1, 5):
w = two ** (1 / T)
print(f"two languages 100 and 1, T={T}: weights {w[0]:.3f} and {w[1]:.3f}, shares {w[0] / w.sum():.3f} and {w[1] / w.sum():.3f}")
# 3. Parameter and compute budget of a shared output layer, d_model = 512.
d = 512
print("\nvocab size V embedding params V*d output-layer FLOPs per target token 2*V*d")
for V in (32000, 64000, 250000):
print(f"{V:12d} {V * d:20,d} {2 * V * d:24,d}")
print("10 separate 32000 vocabs, one per language:", f"{10 * 32000 * d:,d}", "embedding params")
# 4. Sequence-length inflation: tokens per word differs by script. Attention scores grow with length squared.
for f_a, f_b in [(1.3, 2.6), (1.3, 3.9)]:
print(f"fertility {f_a} vs {f_b}: length ratio {f_b / f_a:.1f}x, attention-score count ratio {(f_b / f_a) ** 2:.1f}x")
Output:
sample raw NFC NFKC NFKC result
fullwidth Latin 4 4 4 U+004E U+0041 U+0054 U+004F
fi ligature 3 3 4 U+0066 U+0069 U+0073 U+0068
Arabic lam-alef form 1 1 2 U+0644 U+0627
Devanagari qa (precomposed) 1 2 2 U+0915 U+093C
superscript two 2 2 2 U+0078 U+0032
Japanese half-width katakana 2 2 2 U+30AB U+30CA
NFKC maps x^2 to 'x2': True
lang size T=1 share T=5 share epochs@T=1 epochs@T=5 seen@T=1 seen@T=5
en 200.0 0.512 0.172 0.77 0.26 153.7 51.5
ru 80.0 0.205 0.143 0.77 0.54 61.5 42.9
zh 60.0 0.154 0.135 0.77 0.68 46.1 40.5
ar 20.0 0.051 0.108 0.77 1.63 15.4 32.5
ja 18.0 0.046 0.106 0.77 1.77 13.8 31.8
hi 5.0 0.013 0.082 0.77 4.93 3.8 24.6
ko 4.0 0.010 0.079 0.77 5.89 3.1 23.6
el 2.0 0.005 0.068 0.77 10.26 1.5 20.5
th 1.0 0.003 0.060 0.77 17.86 0.8 17.9
sw 0.3 0.001 0.047 0.77 46.81 0.2 14.0
two languages 100 and 1, T=1: weights 100.000 and 1.000, shares 0.990 and 0.010
two languages 100 and 1, T=5: weights 2.512 and 1.000, shares 0.715 and 0.285
vocab size V embedding params V*d output-layer FLOPs per target token 2*V*d
32000 16,384,000 32,768,000
64000 32,768,000 65,536,000
250000 128,000,000 256,000,000
10 separate 32000 vocabs, one per language: 163,840,000 embedding params
fertility 1.3 vs 2.6: length ratio 2.0x, attention-score count ratio 4.0x
fertility 1.3 vs 3.9: length ratio 3.0x, attention-score count ratio 9.0x
Reading the first table (a nukta is a dot-below mark that Devanagari adds to a letter to write another sound, and a composition exclusion is a character that Unicode lists as never being recombined into one code point by NFC): fullwidth Latin letters map to ordinary Latin (4 code points either way); the fi ligature expands from 3 to 4 code points; the Arabic lam-alef presentation form (U+FEFB) becomes the two letters U+0644 U+0627; the Devanagari letter QA (U+0958) is decomposed to KA plus nukta even by NFC (it is a composition exclusion), so a precomposed and a decomposed spelling of the same letter become identical only after normalizing; half-width katakana become full-width; and NFKC turns x² into x2, a meaning change that is harmless for a search index but wrong in a translation someone will read.
Decisions:
- Source side: NFKC, then collapse whitespace, strip control and zero-width characters (keeping the zero-width joiner and the zero-width non-joiner, invisible characters that ask neighbouring letters to join or to stay apart, because Indic conjuncts and the spelling of some Arabic-script languages such as Persian depend on them), and drop language-specific noise such as Arabic tatweel (the elongation mark).
- Target side: NFC plus a short explicit list (non-breaking space, fullwidth Latin, ligatures). Blanket NFKC would silently rewrite superscripts and symbols in the output.
- Case: keep it. Lower-casing destroys information the target needs, and a shared vocabulary can hold both forms.
- Do not strip diacritics for translation: in many Latin-script languages an accent changes the word.
- Script-specific quirks (Indic nukta forms, Arabic alef variants) are handled by NFC and a per-language list reviewed by a speaker of the language.
- Data filtering belongs here too: language identification, length ratio between source and target, and removing duplicates, because noisy pairs hurt low-resource languages the most.
2. Tokenization and vocabulary: one shared subword model, no word-level pre-splitting
- Chinese, Japanese and Thai have no spaces, so a rule such as "split on whitespace first" fails for them. SentencePiece-style tokenizers operate on the raw character stream and treat whitespace as a symbol, so one procedure covers all ten languages.
- Vocabulary size trades parameters against length: a larger vocabulary means shorter sequences but more embedding and output parameters. The printed table shows the cost of each size.
- Training data for the vocabulary must be sampled with the same temperature idea as the model (next section); sampling in proportion to size would give the small languages almost no merges, and their words would then be cut into characters.
- Byte fallback represents any unseen character as its bytes, removing
[UNK]at a cost of several tokens per rare character. - Language tag: prepend a target-language token (for example
<2ar>) to the source so one model can translate into any of the ten. - Shared vs separate vocabularies: with a shared vocabulary, the Latin-script languages share pieces and names copy across languages; ten separate 32000-entry vocabularies cost 163,840,000 embedding parameters (printed below), five times the 32,768,000 of one shared 64,000-entry vocabulary, and block that sharing. I commit to shared.
3. Sampling across languages: temperature
If language i has ni sentence pairs, sampling probability with temperature T is
pi=∑jnj1/Tni1/Twhere T=1 is proportional to size and larger T flattens the distribution toward uniform. Raising each size to the power 1/T shrinks the gaps between them: with two languages of 100 and 1 million pairs, T=1 gives shares 0.990 and 0.010, while T=5 gives weights 1000.2=2.512 and 10.2=1, so shares 0.715 and 0.285 (the last two lines of the second printed block show these). A language 100 times larger now gets only 2.5 times the weight.
The program's second table uses invented corpus sizes (in millions of sentence pairs, for illustration) and an invented training budget of 300 million sentences seen. An epoch is one pass over a language's data, so "epochs" is the number of times each of its sentences is used. At T=1 every language is passed over 0.77 times, but that equal pass count hides very unequal absolute amounts: English supplies 51% of the batches (153.7 million sentences seen) while Swahili gets 0.3 million pairs times 0.77, about 0.2 million sentences seen, about 670 times fewer, so the smallest languages are barely learned. At T=5 the shares move toward even (Swahili sees 14.0 million sentences), but its 0.3 million pairs would be repeated about 47 times, and Thai about 18 times; repeating the same pairs that often invites memorization, so in practice you pick an intermediate temperature and watch the development loss per language. Start at 5 because it gives the smallest languages a usable share, then try lower values such as 2 or 3 if the small languages overfit; treat the exact T as a tuned hyperparameter, not a known constant.
4. Compute implications
- Embedding and output layer: with hidden size 512, a 32000-entry vocabulary has 16,384,000 embedding parameters, a 64000 vocabulary 32,768,000, a 250000 vocabulary 128,000,000. The output layer needs about 2Vd floating-point operations (FLOPs, counting each multiply and each add) per generated token (a matrix of size d×V times a vector), which at V=250000 is 256,000,000 per token, about eight times the 32000 case. Ten separate 32000-entry vocabularies would cost 163,840,000 embedding parameters, five times the 32,768,000 of one shared 64000-entry vocabulary.
- Sequence length: fertility (tokens per word) differs by script. With illustrative fertilities of 1.3 and 2.6 the second language's sentences are 2.0 times longer, and the attention score count (which grows with length squared) is 4.0 times larger; at 1.3 versus 3.9 it is 3.0 times longer and 9.0 times the scores. Measure fertility per language on held-out text and watch the languages whose fertility is far above the others: they pay more compute per sentence and are truncated first at a maximum length.
- Padding waste: batch by length bucket per language.
5. How to evaluate the choices
Report per language, never an average only. Use a character-based metric such as chrF (a character n-gram F-score) next to BLEU (a score for how many word sequences in the output also appear in a reference translation), since BLEU depends on how a language is tokenized for scoring; keep the scoring tokenization fixed across experiments. Track fertility, the byte-fallback rate and round-trip fidelity (turning text into token ids and back returns the normalized text exactly) per language as health checks of the preprocessing itself.
Running the code
pip install numpy # numpy 2.1.3
# save the program above to a file and run it with python
Implement in Python the core training loop for Byte-Pair Encoding (BPE) merges. Given a tokenized corpus (list of words) where each word is a list of characters (you can add an end-of-word marker), produce merge operations until a target vocabulary size is reached. Focus on correctness: count pair frequencies, choose highest-frequency pair, merge it, and update counts. Explain runtime trade-offs.
Sample Answer
Direct answer
BPE (byte-pair encoding) learns a subword vocabulary by repeated merging. Start with every word split into characters plus an end-of-word marker, count how often each adjacent pair of symbols occurs (weighting by word frequency), merge the single most frequent pair into a new symbol everywhere, and repeat until the vocabulary has the target size. The ordered list of merges is the whole model: to tokenize new text you split into characters and apply the merges in the order they were learned.
Algorithm in steps
- Pre-tokenize the corpus (split the raw text into words, usually on spaces and punctuation) and count each distinct word once with its frequency (
{"low": 5, ...}), so a word that occurs 5 times is processed once and its pair counts are multiplied by 5. - Represent each word as a tuple of symbols: its characters plus
</w>, the end-of-word marker. The marker lets the model tell "est" inside a word from "est" at the end. - Count pair frequencies: for every adjacent pair (a,b) in a word with frequency f, add f to its count.
- Pick the pair with the highest count. Ties need a fixed rule (here: the smaller pair in sorted order), otherwise two runs learn different merges and the same text would be tokenized differently by two copies of the tokenizer.
- Merge it in every word, left to right and without overlap (in "aaa" the pair (a, a) merges the first two letters only), and record the merge.
- Stop when
initial symbols + mergesreaches the target vocabulary size. The vocabulary is the set of symbols the tokenizer knows; in this simple version its size is the initial alphabet plus the number of merges (an intermediate symbol that no longer occurs is still counted).
Implementation and check
Below are two implementations. bpe_naive recounts all pairs after each merge. bpe_incremental keeps pair counts and an index from each pair to the words that contain it, and after a merge it updates only the words that contained the merged pair. The program asserts that both learn the same merge list, prints the merges for a four-word corpus, counts how many symbol positions each version scanned, tokenizes two unseen words with the learned merges, and finally prints the table of pair counts before the first merge so that every choice can be checked by hand. In the incremental version, the line that rebuilds counts from a dictionary comprehension simply forgets pairs whose count has dropped to zero.
from collections import Counter, defaultdict
def merge_word(sym, pair):
"""Replace non-overlapping left-to-right occurrences of pair in a tuple of symbols."""
out, i = [], 0
while i < len(sym):
if i < len(sym) - 1 and (sym[i], sym[i + 1]) == pair:
out.append(sym[i] + sym[i + 1]); i += 2
else:
out.append(sym[i]); i += 1
return tuple(out)
def best_pair(counts):
return min(counts, key=lambda p: (-counts[p], p)) # highest count; ties broken by the pair itself
def pair_counts_of(words):
c = Counter()
for sym, f in words.items():
for a, b in zip(sym, sym[1:]):
c[(a, b)] += f
return c
def bpe_naive(words, n_merges):
"""Recount every pair after every merge. Returns merges and the number of symbol positions scanned."""
words, merges, work = dict(words), [], 0
for _ in range(n_merges):
counts = pair_counts_of(words)
work += sum(len(s) - 1 for s in words)
if not counts:
break
p = best_pair(counts); merges.append(p)
new = {}
for s, f in words.items():
m = merge_word(s, p); new[m] = new.get(m, 0) + f
words = new
return merges, work
def bpe_incremental(words, n_merges):
"""Keep pair counts and an index pair -> words containing it; only touch affected words."""
words = dict(words)
counts, where, merges, work = pair_counts_of(words), defaultdict(set), [], 0
for s in words:
for a, b in zip(s, s[1:]):
where[(a, b)].add(s)
for _ in range(n_merges):
counts = Counter({p: c for p, c in counts.items() if c > 0}) # forget pairs whose count fell to zero
if not counts:
break
p = best_pair(counts); merges.append(p)
for s in list(where[p]):
f = words.pop(s)
for a, b in zip(s, s[1:]): # remove the old contribution of this word
counts[(a, b)] -= f; where[(a, b)].discard(s)
m = merge_word(s, p); work += len(s) - 1
words[m] = words.get(m, 0) + f
for a, b in zip(m, m[1:]): # add the new contribution
counts[(a, b)] += f; where[(a, b)].add(m)
return merges, work
corpus = {"low": 5, "lower": 2, "newest": 6, "widest": 3} # word -> frequency
words = {tuple(w) + ("</w>",): f for w, f in corpus.items()} # characters plus an end-of-word marker
n_chars = len({c for s in words for c in s})
target_vocab = n_chars + 10 # initial symbols + 10 merges
m_naive, w_naive = bpe_naive(words, target_vocab - n_chars)
m_inc, w_inc = bpe_incremental(words, target_vocab - n_chars)
assert m_naive == m_inc, "incremental and naive merge lists differ"
print("initial symbols:", n_chars, "| target vocabulary:", target_vocab)
for i, p in enumerate(m_inc, 1):
print(i, p)
print("positions scanned, naive:", w_naive, "| incremental:", w_inc)
def encode(word, merges):
sym = tuple(word) + ("</w>",)
for p in merges: # apply merges in the order they were learned
sym = merge_word(sym, p)
return list(sym)
print("encode 'lowest' ->", encode("lowest", m_inc))
print("encode 'newer' ->", encode("newer", m_inc))
def after(k):
"""The corpus after the first k merges."""
cur = dict(words)
for p in m_inc[:k]:
nxt = {}
for s, f in cur.items():
m = merge_word(s, p); nxt[m] = nxt.get(m, 0) + f
cur = nxt
return cur
print("pair counts before any merge:")
for p, c in sorted(pair_counts_of(words).items(), key=lambda kv: (-kv[1], kv[0])):
print(" ", p, c)
print("words after merge 1:", {" ".join(s): f for s, f in after(1).items()})
print("top pairs before merge 10:", sorted(pair_counts_of(after(9)).items(), key=lambda kv: (-kv[1], kv[0]))[:3])
Output:
initial symbols: 11 | target vocabulary: 21
1 ('e', 's')
2 ('es', 't')
3 ('est', '</w>')
4 ('l', 'o')
5 ('lo', 'w')
6 ('e', 'w')
7 ('ew', 'est</w>')
8 ('n', 'ewest</w>')
9 ('low', '</w>')
10 ('d', 'est</w>')
positions scanned, naive: 120 | incremental: 54
encode 'lowest' -> ['low', 'est</w>']
encode 'newer' -> ['n', 'ew', 'e', 'r', '</w>']
pair counts before any merge:
('e', 's') 9
('s', 't') 9
('t', '</w>') 9
('w', 'e') 8
('l', 'o') 7
('o', 'w') 7
('e', 'w') 6
('n', 'e') 6
('w', '</w>') 5
('d', 'e') 3
('i', 'd') 3
('w', 'i') 3
('e', 'r') 2
('r', '</w>') 2
words after merge 1: {'l o w </w>': 5, 'l o w e r </w>': 2, 'n e w es t </w>': 6, 'w i d es t </w>': 3}
top pairs before merge 10: [(('d', 'est</w>'), 3), (('i', 'd'), 3), (('w', 'i'), 3)]
Reading the output: the corpus has 11 starting symbols (ten letters and </w>), so ten merges give a vocabulary of 21. The table of pair counts is built word by word: "low" (frequency 5) adds 5 to each of ('l','o'), ('o','w') and ('w','</w>'); "lower" (2) adds 2 to ('l','o'), ('o','w'), ('w','e'), ('e','r') and ('r','</w>'); "newest" (6) and "widest" (3) both contain e,s,t,</w> in a row. So ('e','s') is 6 + 3 = 9, and ('s','t') and ('t','</w>') are also 6 + 3 = 9, a three-way tie; the tie-break rule picks ('e', 's') because it sorts first. ('l','o') is 5 + 2 = 7, and ('w','e') is 2 (from "lower") + 6 (from "newest") = 8. After merge 1 the four words read l o w </w>, l o w e r </w>, n e w es t </w> and w i d es t </w>, and only pairs touching es change count. The next two grow it to est</w>. Merge 10 is ('d', 'est</w>') because by then three pairs, ('d','est</w>'), ('i','d') and ('w','i'), all sit at 3: they come only from "widest" (frequency 3), whose letters w, i and d are still separate in front of est</w>, and the sorted-order rule picks the one starting with d. The earlier merges built est</w>, low and ewest</w>. Unseen "lowest" is encoded as ['low', 'est</w>']: two known pieces. "newer" becomes ['n', 'ew', 'e', 'r', '</w>']; the final r and the marker stay separate because no learned merge covers them. A word whose characters are all in the starting alphabet but that no merge covers falls back to single characters, so no unknown token is needed. A character outside the starting alphabet would need an unknown token in this simple version; byte-level BPE avoids that by making the starting alphabet all 256 byte values.
Runtime and design trade-offs
Let W be the number of distinct words, ℓ the average word length in symbols and M the number of merges.
- Naive: each merge scans every symbol of every distinct word, so about O(M⋅W⋅ℓ) symbol positions in total. In the run it scanned 120 positions for 10 merges on four words.
- Incremental: a merge only visits the words that contain the chosen pair. On the same corpus it scanned 54 positions. The savings grow with a large vocabulary, because later merges are rare pairs found in few words. The count only measures word positions; the line that rebuilds
countsin this version still walks every distinct pair on each merge, so a production version selects the best pair with a max-heap (a structure that always hands back its largest entry first) and lazy deletion (push the updated count as a new entry and discard stale older entries when they surface), giving roughly O(logP) per updated pair, where P is the number of distinct pairs and O(logP) means the work grows only with the logarithm of that number. - Counting words once (not tokens) is what makes training on large corpora feasible: cost depends on the number of distinct words, not the corpus size.
- Memory: the pair-to-words index holds one set entry per pair occurrence in each distinct word.
Practical points: a larger vocabulary shortens sequences (a transformer's attention compares every token with every other, so fewer tokens is cheaper, and more text fits in the context window) but spreads training signal over more, rarer tokens and enlarges the embedding table (the lookup table with one vector per token, so vocabulary size times embedding dimension). BPE is greedy and frequency-driven, so it can split morphology unevenly; unigram language-model tokenizers start from a large candidate vocabulary and prune it by likelihood (how probable the training text is under the pieces) instead. Encoding applies merges in learned order, so encoding one word costs O(M) passes in this simple form; real tokenizers store each merge with its rank (its position in the learned order) and look pairs up by rank to avoid scanning all of them.
Common mistakes
- Merging overlapping pairs ("aaa") or merging inside one pass using already-merged symbols from the same pass.
- Forgetting word frequencies (counting each distinct word once) or forgetting to remove the old pair counts after a merge, so counts drift.
- No tie-breaking rule, so results are not reproducible.
- Applying merges to new text in the wrong order (it must be learned order, not frequency re-sorted).
- Forgetting the end-of-word marker, which removes the distinction between prefix, middle and suffix pieces.
Design a model that jointly performs named-entity recognition and relation extraction from a shared pretrained encoder. How do you represent entities, balance the two losses, keep one task from hurting the other, and evaluate them together?
Sample Answer
Direct answer
Use one pretrained encoder (a BERT-style network that turns each token into a context-aware vector) with two heads. The entity head scores spans (start and end token plus a type, or "not an entity"). The relation head takes pairs of entity representations from the same encoder output and classifies the relation, including an explicit "no relation" class. Train both heads together with a weighted sum of losses, feed the relation head gold entities during training with some predicted ones mixed in, and evaluate with strict entity F1 and strict relation F1 ("strict" means a prediction counts only if every part of it matches the gold annotation exactly; F1 is the harmonic mean of precision and recall) and with the relation F1 you would get if entities were perfect, so you can see where errors come from. Keep single-task models as baselines to prove the sharing helps rather than hurts.
NER (named-entity recognition) finds and types spans such as people and organizations. Relation extraction labels the relation between two entities, such as works_for(PER, ORG).
One sentence, end to end
Take the ten-token sentence Maria joined Acme in Paris , and Tom founded Zeta (token positions 0 to 9). Its gold annotation has five entities and three relations:
| Step | What it looks like on this sentence |
|---|---|
| BIO tags | B-PER O B-ORG O B-LOC O O B-PER O B-ORG (B- begins an entity, I- continues one, O is outside; here every entity is one token, so there is no I-) |
| Entity spans (first token, last token, type) | (0, 0, PER) Maria, (2, 2, ORG) Acme, (4, 4, LOC) Paris, (7, 7, PER) Tom, (9, 9, ORG) Zeta |
| Ordered entity pairs | 5 entities give 5 x 4 = 20 pairs |
| Relation labels | Maria to Acme: works_for; Acme to Paris: located_in; Tom to Zeta: founded; the other 17 pairs: none |
The program below prints this same trace. The relation head's job is to label each of those 20 pairs, and the entity head's job is to produce the five spans the pairs are built from.
Representing entities
Two common choices:
| Representation | How | Good for | Cost |
|---|---|---|---|
| Token tagging (BIO: each token is Beginning, Inside or Outside an entity of a type) | one label per token, optionally a CRF (a layer that scores whole tag sequences so illegal ones like I-ORG after O are penalised) | flat, non-overlapping entities, cheap | cannot represent nested entities (one entity inside another, such as "America" inside "Bank of America") |
| Span classification | enumerate every span up to a maximum width, represent each as one vector made by joining three pieces (the encoder's vector at the span's first token, its vector at the last token, and a small learned vector for how many tokens wide the span is), classify type or "none" | nested and overlapping entities, direct entity vectors for the relation head | many candidates |
I would choose span classification when the relation schema can involve nested entities or when pair representations should use the entity boundaries directly. The program also sizes it (our ten-token sentence has 27 candidate spans of width up to 3): for a 40-token sentence with spans up to 8 tokens there are 292 candidate spans, and pairing all of them would be 84,972 ordered pairs, which is why you prune. Keeping only the top K=10 scored entity spans leaves 90 ordered relation candidates (K=5 leaves 20, K=20 leaves 380). Prune by score threshold or top-K, and tune K for recall of gold entities on dev data, since a pruned-away entity can never be linked.
A relation candidate representation: [head span vector; tail span vector; head type embedding; tail type embedding; pooled context between the spans] into a small feed-forward network, then a softmax over relation types plus "none". Relations are directed, so (A, B) and (B, A) are different candidates. A heavier option is typed markers: insert tags around the two candidate entities in the text, for example <PER>Maria</PER> joined <ORG>Acme</ORG> in Paris, and run the encoder again so it reads that pair directly. It is often stronger, at the price of one extra encoder pass per candidate group, so treat it as a later experiment rather than part of the first build.
Training: the shared encoder and the two losses
L=wNERLNER+wRELREwhere LNER is cross-entropy over span labels, LRE is cross-entropy over relation labels for sampled pairs, and w are weights.
- Gold entities with mixing: if the relation head only ever sees gold entities, it meets noisy predicted ones for the first time at inference (the same train/test mismatch as teacher forcing in sequence models). Feed gold entities early, then replace a fraction with the entity head's predictions as it improves.
- Negative pair sampling: most pairs have no relation. Use all positive pairs plus a sampled set of "none" pairs (for example several negatives per positive, or hard negatives, meaning "none" pairs that look like real ones, such as an ORG and a LOC that are not related, when other ORG-LOC pairs are
located_in). Without this, the relation loss is dominated by "none". - Balancing the two losses. Two quantities can differ between tasks: the loss value, and the size of the gradient (the vector of directions and amounts by which each parameter would change to reduce that loss). What matters for sharing is the gradient each task sends into the shared encoder, measured as its norm (length). To measure it, compute each task's loss separately, ask autograd (the library feature that computes gradients) for the gradient of that loss with respect to only the shared encoder's parameters, and take the length of that vector; Part 3 of the program does exactly this on a small untrained toy network with random data. There the losses are 1.056 (NER) and 3.074 (RE), a ratio near 3, yet the gradient norms are 0.131 and 0.156, so with equal weights RE supplies 0.54 of the encoder's gradient. Loss size is a poor guide to gradient size, which is why you measure the norms on your own model and data (they change during training) rather than assume. Scaling RE by the ratio of the norms (0.839 here) makes the shares 0.50 each. The uncertainty weighting rule gives each task a learned number si and minimises ∑ie−siLi+si. For one task, take the derivative with respect to si: −e−siLi+1=0, so esi=Li, that is si=lnLi and the task's weight e−si equals 1/Li. A task with a smaller loss therefore gets a larger weight (0.947 for NER against 0.325 for RE in the toy), and the added si term stops the model from driving every weight to zero. These are heuristics; compare against single-task baselines on the dev set, and treat dev F1 for both tasks as the number that matters.
- Keeping one task from hurting the other (when it does, this is called negative transfer: training on one task makes the other worse). Do these in order. First, warm up on NER alone for an epoch or two so the relation head sees sensible entity vectors, and use a lower learning rate for the encoder than for the heads. Second, always compare against the single-task models: if joint training lowers NER F1, the sharing is hurting. Only if it is, try the heavier tools. If the two gradients on the shared parameters point in opposing directions (their cosine similarity, the dot product divided by both lengths, is negative; measure it on a few batches, Part 3 prints it), PCGrad is one published fix: when the dot product of the two gradients is negative, remove from one gradient its component along the other. In Part 4,
g_a = (3, 1)andg_b = (-2, 2)have dot product -4; subtracting(-4 / 8)timesg_bfromg_agives(2, 2), whose dot product withg_bis 0, so the update no longer undoes the other task. Another option is an adapter (a small extra trainable layer inserted into a shared network for one task) or giving each task its own top layers while sharing the lower ones.
import numpy as np
import torch
import torch.nn as nn
import torch.nn.functional as F
torch.set_num_threads(1)
# Part 0: one sentence, traced end to end.
tokens = "Maria joined Acme in Paris , and Tom founded Zeta".split()
gold_ents = {(0, 0, "PER"), (2, 2, "ORG"), (4, 4, "LOC"), (7, 7, "PER"), (9, 9, "ORG")} # (first token, last token, type)
gold_rels = {((0, 0, "PER"), (2, 2, "ORG"), "works_for"),
((2, 2, "ORG"), (4, 4, "LOC"), "located_in"),
((7, 7, "PER"), (9, 9, "ORG"), "founded")}
bio = ["O"] * len(tokens)
for s, e, ty in gold_ents:
bio[s] = "B-" + ty
for i in range(s + 1, e + 1):
bio[i] = "I-" + ty
print("tokens:", list(enumerate(tokens)))
print("BIO tags:", bio)
text = lambda ent: tokens[ent[0]] + "/" + ent[2]
ents = sorted(gold_ents)
rel_of = {(h, t): lab for h, t, lab in gold_rels}
pairs = [(h, t) for h in ents for t in ents if h != t]
print(f"{len(ents)} entities -> {len(pairs)} ordered pairs, {len(rel_of)} with a relation:")
for h, t in pairs:
if (h, t) in rel_of:
print(" ", text(h), "->", text(t), ":", rel_of[(h, t)])
print("all other pairs get the label 'none':", len(pairs) - len(rel_of))
# Part 1: size of the span-based formulation for a sentence of n tokens, spans up to width w.
def n_spans(n, w):
return sum(n - k + 1 for k in range(1, w + 1))
print(f"this sentence: {n_spans(len(tokens), 3)} candidate spans of width <= 3")
for n in (20, 40, 80):
s = n_spans(n, 8)
print(f"n={n}: candidate spans (width<=8)={s}, ordered pairs of ALL spans={s*(s-1)}")
for K in (5, 10, 20):
print(f"keep K={K} entities: ordered relation candidates={K*(K-1)}")
# Part 2: strict evaluation on the same sentence: the model gets one entity type and two relations wrong.
pred_ents = {(0, 0, "PER"), (2, 2, "ORG"), (4, 4, "ORG"), (7, 7, "PER"), (9, 9, "ORG")} # Paris typed ORG
pred_rels = {((0, 0, "PER"), (2, 2, "ORG"), "works_for"), # correct
((2, 2, "ORG"), (4, 4, "ORG"), "located_in"), # tail entity type is wrong
((7, 7, "PER"), (9, 9, "ORG"), "works_for")} # wrong relation label
def prf(pred, gold):
tp = len(pred & gold)
p = tp / len(pred) if pred else 0.0
r = tp / len(gold) if gold else 0.0
f = 2 * p * r / (p + r) if p + r else 0.0
return round(p, 2), round(r, 2), round(f, 2)
print("entity P/R/F1:", prf(pred_ents, gold_ents))
print("strict relation P/R/F1 (boundaries, both types, label):", prf(pred_rels, gold_rels))
strip = lambda rels: {(h[:2], t[:2], l) for h, t, l in rels} # relaxed: drop entity types, keep boundaries and label
print("relaxed relation P/R/F1 (no entity types):", prf(strip(pred_rels), strip(gold_rels)))
# Part 3: measuring loss scale and gradient size on a shared encoder (an untrained toy network, random data).
torch.manual_seed(0)
enc = nn.Sequential(nn.Linear(8, 16), nn.Tanh()) # stand-in for the shared encoder
ner_head, re_head = nn.Linear(16, 3), nn.Linear(16, 20) # 3 entity labels, 20 relation labels
x = torch.randn(64, 8)
h = enc(x)
loss_ner = F.cross_entropy(ner_head(h), torch.randint(0, 3, (64,)))
loss_re = F.cross_entropy(re_head(h), torch.randint(0, 20, (64,)))
shared = list(enc.parameters())
flat = lambda loss: torch.cat([g.flatten() for g in torch.autograd.grad(loss, shared, retain_graph=True)])
g_ner, g_re = flat(loss_ner), flat(loss_re) # each task's gradient on the shared parameters only
n_ner, n_re = g_ner.norm().item(), g_re.norm().item()
print(f"losses: NER {loss_ner.item():.3f}, RE {loss_re.item():.3f}; shared-encoder gradient norms: NER {n_ner:.3f}, RE {n_re:.3f}")
print(f"equal weights: share of encoder gradient from RE = {n_re / (n_ner + n_re):.2f}")
w_re = n_ner / n_re # scale RE so both norms match
print(f"norm-balanced weights: NER 1.000, RE {w_re:.3f} -> RE share = {w_re * n_re / (n_ner + w_re * n_re):.2f}")
for name, L in (("NER", loss_ner.item()), ("RE", loss_re.item())):
s = np.log(L)
print(f"uncertainty weighting {name}: optimal s=ln(L)={s:.3f}, weight exp(-s)={np.exp(-s):.3f} (= 1/L)")
print("cosine similarity of the two gradients:", round(F.cosine_similarity(g_ner, g_re, dim=0).item(), 3))
# Part 4: PCGrad on two hand-set conflicting gradients: remove from g_a its component along g_b.
g_a, g_b = np.array([3.0, 1.0]), np.array([-2.0, 2.0])
dot = g_a @ g_b
g_a_new = g_a - (dot / (g_b @ g_b)) * g_b if dot < 0 else g_a
print("dot product before:", dot, "| projected g_a:", g_a_new, "| dot product after:", g_a_new @ g_b)
Output:
tokens: [(0, 'Maria'), (1, 'joined'), (2, 'Acme'), (3, 'in'), (4, 'Paris'), (5, ','), (6, 'and'), (7, 'Tom'), (8, 'founded'), (9, 'Zeta')]
BIO tags: ['B-PER', 'O', 'B-ORG', 'O', 'B-LOC', 'O', 'O', 'B-PER', 'O', 'B-ORG']
5 entities -> 20 ordered pairs, 3 with a relation:
Maria/PER -> Acme/ORG : works_for
Acme/ORG -> Paris/LOC : located_in
Tom/PER -> Zeta/ORG : founded
all other pairs get the label 'none': 17
this sentence: 27 candidate spans of width <= 3
n=20: candidate spans (width<=8)=132, ordered pairs of ALL spans=17292
n=40: candidate spans (width<=8)=292, ordered pairs of ALL spans=84972
n=80: candidate spans (width<=8)=612, ordered pairs of ALL spans=373932
keep K=5 entities: ordered relation candidates=20
keep K=10 entities: ordered relation candidates=90
keep K=20 entities: ordered relation candidates=380
entity P/R/F1: (0.8, 0.8, 0.8)
strict relation P/R/F1 (boundaries, both types, label): (0.33, 0.33, 0.33)
relaxed relation P/R/F1 (no entity types): (0.67, 0.67, 0.67)
losses: NER 1.056, RE 3.074; shared-encoder gradient norms: NER 0.131, RE 0.156
equal weights: share of encoder gradient from RE = 0.54
norm-balanced weights: NER 1.000, RE 0.839 -> RE share = 0.50
uncertainty weighting NER: optimal s=ln(L)=0.055, weight exp(-s)=0.947 (= 1/L)
uncertainty weighting RE: optimal s=ln(L)=1.123, weight exp(-s)=0.325 (= 1/L)
cosine similarity of the two gradients: 0.152
dot product before: -4.0 | projected g_a: [2. 2.] | dot product after: 0.0
Evaluating them together
Define and state each convention:
- Entity F1, strict: a predicted entity is correct only if start, end and type all match a gold entity. (F1 is the harmonic mean of precision, the share of predictions that are right, and recall, the share of gold items found.)
- Relation F1, strict: a predicted relation is correct only if both entities match gold (boundaries and types) and the relation label matches. On our sentence the model types
Parisas ORG instead of LOC. That gives 5 gold entities with 4 correct (entity F1 0.80). Of the three predicted relations only the first is right:Acme to Pariscarries the wrong tail type (so a wrong entity breaks a relation that has the right label) andTom to Zetahas the wrong label. Strict relation F1 is therefore 1 of 3 = 0.33; ignoring entity types (the relaxed convention: boundaries and relation label must match, types need not), it is 2 of 3 = 0.67. Report both so a reader sees how much comes from entity errors. (The example is small and hand-made: it shows how errors compound, not typical scores.) - Relation F1 with gold entities (an oracle setting: the correct answer for one sub-step is handed to the model so the remaining step can be measured alone; here, perfect entities for the relation head): isolates the relation head. The gap to strict F1 is the error propagated from entity prediction.
- Per-type and per-relation breakdowns, macro-F1 (unweighted mean over types) for rare types, and an "out-of-schema" check.
- Dataset hygiene: split by document, not sentence, so the same entity pair is not in train and test; check that relations that cross sentence boundaries are either in scope or excluded explicitly.
- Ablations (remove one ingredient and re-measure): joint vs single-task, with and without the pair-type embeddings, with and without predicted-entity mixing.
Failure modes
- Error propagation from an entity miss to every relation that touches it.
- Class imbalance of "none" pairs. Monitor recall of positives while tuning the sampling ratio.
- Direction and symmetric relations: define whether
married_tois stored in both directions. - Overlapping spans that give the same relation twice; deduplicate by a rule.
Common mistakes
- Reporting relation F1 only with gold entities and calling it end to end.
- Counting a relation correct when the entity types are wrong.
- Using fixed equal loss weights without checking either task against its single-task baseline.
Compare Byte-Pair Encoding (BPE), WordPiece, and the Unigram Language Model (used by SentencePiece) for subword segmentation. Explain algorithmic differences, what objective each optimizes, typical hyperparameters (e.g., vocab size), and the implications for multilingual models and rare-word handling.
Sample Answer
The idea. If you only learn one of these, learn BPE: it is the simplest, WordPiece is a close variant of it, and the Unigram model reaches a similar vocabulary from the opposite direction (pruning instead of merging); the worked trace below starts with BPE. All three methods build a vocabulary of subword pieces (units between a single character and a whole word) from a text corpus, so that frequent words stay whole and rare words are split into reusable parts. They differ in how they choose the pieces. BPE (Byte-Pair Encoding) and WordPiece build the vocabulary bottom-up by repeatedly merging two adjacent symbols, and differ in which pair they merge. The Unigram language model (used by SentencePiece, a tokenizer library that works on raw text) goes top-down: start with a large candidate vocabulary and prune it, keeping the pieces that matter most for a probabilistic model of the text.
How each one builds a vocabulary, step by step
- BPE. Start with each word as a sequence of characters (or bytes). Count every adjacent pair across the corpus, weighted by word frequency. Merge the single most frequent pair into a new symbol, add it to the vocabulary, record the merge rule, and repeat until the vocabulary reaches the target size. Objective: none beyond greedy compression, the most frequent pair wins.
- WordPiece. Same loop, but the pair chosen is the one that most increases the likelihood of the training data. Likelihood here means how probable the training text is under a simple language model of pieces: each piece gets a probability equal to its share of all piece occurrences, and a text's probability is the product of its pieces' probabilities. Why this leads to a ratio: replacing every adjacent a,b by one piece ab changes the log-likelihood by about count(a,b)⋅logP(a)P(b)P(ab), and P(a)P(b)P(ab) is proportional to count(a)count(b)count(a,b) where count(a,b) is how often the pair occurs and count(a), count(b) are the counts of each part. Many implementations score pairs by that ratio directly, as the program below does; the exact likelihood gain also has the leading factor count(a,b), so the ratio is a simplification that ranks pairs by how strongly the parts stick together, not by how many times the pair occurs. A pair whose parts almost never occur apart scores high even if it is not frequent. Pieces that continue a word carry a prefix (BERT-style models write
##). - Unigram LM. Start from a big seed of candidate pieces (all frequent substrings plus single characters). Assume each piece has a probability and a segmentation's probability is the product of its pieces' probabilities (sums of logs are used in practice, so the numbers below are log-probabilities, which are negative: closer to 0 is more probable). Alternate two steps: estimate the probabilities with expectation-maximization (EM: guess the probabilities; for each word consider every possible segmentation and weight it by its probability under the guess; count each piece in proportion to the weight of the segmentations that contain it; turn the counts into new probabilities; and repeat until they settle), then remove the pieces whose removal hurts the total corpus likelihood least (single characters are always kept so nothing is unknown). The original method drops a fixed fraction of the pieces in each round, keeping the best 80 percent in the paper's example, rather than one piece at a time. Repeat until the vocabulary hits the target size.
Segmentation at inference is deterministic in the base case. BPE replays the stored merge rules in the order they were learned. WordPiece uses greedy longest-match-first: take the longest prefix that is in the vocabulary, then continue from there with the ## form. Unigram picks the segmentation with the highest probability, found with the Viterbi algorithm (dynamic programming over split points). The same input therefore always gives the same pieces, unless you turn on a regulariser (a deliberate source of randomness that stops the model overfitting one segmentation): BPE-dropout skips some merges at random, and Unigram can sample among segmentations in proportion to their probability. Both give the model several views of one word during training.
A tiny worked example. Corpus of four words with counts: low x5, lower x2, newest x6, widest x3. The program below runs the three algorithms. It is a minimal teaching implementation: the Unigram part uses hard EM (hard means each word counts only toward its single best segmentation, instead of every segmentation counting in proportion to its probability) and prunes one piece at a time, which is a simplification of the real method.
import math
from collections import Counter
word_counts = {"low": 5, "lower": 2, "newest": 6, "widest": 3}
def merge_symbols(seq, a, b, new):
out, i = [], 0
while i < len(seq):
if i + 1 < len(seq) and seq[i] == a and seq[i + 1] == b:
out.append(new); i += 2
else:
out.append(seq[i]); i += 1
return out
def train_merges(score_name, n_merges):
words = {w: (list(w) if score_name == "bpe" else [w[0]] + ["##" + c for c in w[1:]]) for w in word_counts}
merges = []
for _ in range(n_merges):
pair_c, sym_c = Counter(), Counter()
for w, seq in words.items():
c = word_counts[w]
for s in seq: sym_c[s] += c
for a, b in zip(seq, seq[1:]): pair_c[(a, b)] += c
if score_name == "bpe":
score = {p: n for p, n in pair_c.items()}
else:
score = {p: n / (sym_c[p[0]] * sym_c[p[1]]) for p, n in pair_c.items()}
best = max(sorted(score), key=lambda p: score[p])
new = best[0] + best[1].replace("##", "", 1) if score_name == "wordpiece" else best[0] + best[1]
merges.append((best, round(score[best], 4), new))
for w in words: words[w] = merge_symbols(words[w], best[0], best[1], new)
return merges, words
for name in ("bpe", "wordpiece"):
merges, words = train_merges(name, 6)
print(name, "first 6 merges (pair, score, new piece):")
for m in merges: print(" ", m)
bpe_merges, _ = train_merges("bpe", 6)
def bpe_segment(word):
seq = list(word)
for (a, b), _, new in bpe_merges: seq = merge_symbols(seq, a, b, new)
return seq
print("BPE applies the merge list in order; 'lowest' ->", bpe_segment("lowest"))
wp_merges, wp_words = train_merges("wordpiece", 6)
wp_vocab = {s for seq in wp_words.values() for s in seq} | {m[2] for m in wp_merges} | {w[0] for w in word_counts} | {"##" + c for w in word_counts for c in w[1:]}
def wp_segment(word):
out, i = [], 0
while i < len(word):
j = len(word)
while j > i:
piece = word[i:j] if i == 0 else "##" + word[i:j]
if piece in wp_vocab: out.append(piece); i = j; break
j -= 1
else:
return ["[UNK]"]
return out
print("WordPiece greedy longest-match 'lowest' ->", wp_segment("lowest"))
# Unigram LM: pieces carry probabilities; Viterbi finds the best segmentation.
def viterbi(word, logp):
best = [(0.0, None)] + [(-1e18, None)] * len(word)
for j in range(1, len(word) + 1):
for i in range(max(0, j - 6), j):
p = word[i:j]
if p in logp and best[i][0] + logp[p] > best[j][0]:
best[j] = (best[i][0] + logp[p], i)
out, j = [], len(word)
while j > 0:
i = best[j][1]; out.append(word[i:j]); j = i
return out[::-1], best[len(word)][0]
chars = {c for w in word_counts for c in w}
seed = Counter()
for w, c in word_counts.items():
for i in range(len(w)):
for j in range(i + 1, min(len(w), i + 4) + 1): seed[w[i:j]] += c
def normalise(cnt):
tot = sum(cnt.values()); return {p: math.log(n / tot) for p, n in cnt.items()}
logp = normalise(seed)
def corpus_nll(lp):
return -sum(c * viterbi(w, lp)[1] for w, c in word_counts.items())
def reestimate(lp):
cnt = Counter()
for w, c in word_counts.items():
for p in viterbi(w, lp)[0]: cnt[p] += c
for ch in chars: cnt[ch] += 0.5
return normalise(cnt)
for _ in range(3): logp = reestimate(logp)
target = 12
print("candidate pieces before pruning:", len(logp))
first_round = True
while len(logp) > target:
base = corpus_nll(logp)
losses = {}
for p in logp:
if p in chars: continue
lp2 = {q: v for q, v in logp.items() if q != p}
losses[p] = corpus_nll(lp2) - base
drop = min(sorted(losses), key=lambda p: losses[p])
if first_round:
ranked = sorted(losses.items(), key=lambda kv: (kv[1], kv[0]))
print("first pruning round, loss in total log-likelihood if the piece is removed:")
print(" ", [(p, round(v, 3)) for p, v in ranked])
first_round = False
del logp[drop]
logp = reestimate(logp)
print("unigram vocabulary after pruning to", len(logp), ":", sorted(logp))
seg, lp = viterbi("lowest", logp)
print("unigram Viterbi 'lowest' ->", seg, "log-prob", round(lp, 3))
print(" piece log-probs:", {p: round(logp[p], 3) for p in seg}, "| their sum:", round(sum(logp[p] for p in seg), 3))
print("another valid split ['l','o','w','e','s','t'] log-prob", round(sum(logp[c] for c in "lowest"), 3))
Output:
bpe first 6 merges (pair, score, new piece):
(('e', 's'), 9, 'es')
(('es', 't'), 9, 'est')
(('l', 'o'), 7, 'lo')
(('lo', 'w'), 7, 'low')
(('e', 'w'), 6, 'ew')
(('ew', 'est'), 6, 'ewest')
wordpiece first 6 merges (pair, score, new piece):
(('##i', '##d'), 0.3333, '##id')
(('w', '##id'), 0.3333, 'wid')
(('l', '##o'), 0.1429, 'lo')
(('##s', '##t'), 0.1111, '##st')
(('lo', '##w'), 0.0769, 'low')
(('##e', '##r'), 0.0588, '##er')
BPE applies the merge list in order; 'lowest' -> ['low', 'est']
WordPiece greedy longest-match 'lowest' -> ['low', '##e', '##st']
candidate pieces before pruning: 15
first pruning round, loss in total log-likelihood if the piece is removed:
[('ower', 9.704), ('wid', 30.329), ('low', 45.055), ('new', 64.816), ('est', 100.873)]
unigram vocabulary after pruning to 12 : ['d', 'e', 'est', 'i', 'l', 'low', 'n', 'o', 'r', 's', 't', 'w']
unigram Viterbi 'lowest' -> ['low', 'est'] log-prob -3.759
piece log-probs: {'low': -2.005, 'est': -1.754} | their sum: -3.759
another valid split ['l','o','w','e','s','t'] log-prob -22.089
Reading the output
-
How to read the Unigram part. The seed pieces were re-estimated three times, which leaves 15 pieces in use: the 10 single characters, which are never removed, and 5 longer pieces. In the first pruning round the program asks, for each longer piece, how much worse the total log-likelihood of the corpus becomes if that piece is deleted (the loss, in the printed list from cheapest to costliest).
owercosts only about 9.7 because it appears just inlower(2 times) and its characters can stand in for it, whileestcosts about 100.9 because it is insidenewestandwidest, 9 occurrences in all. The cheapest piece goes first, the probabilities are re-estimated, and the round repeats until 12 pieces remain. The scores come from a short chain of numbers:lowhas log-probability -2.005 andest-1.754, so the segmentationlow+estscores -2.005 + -1.754 = -3.759, while spellinglowestwith six single characters adds six much smaller probabilities and scores -22.089. -
The Viterbi function fills
best[j]with the best log-probability of segmenting the firstjcharacters, plus the start positioniof the last piece. For each endjit tries every startiup to 6 characters back, keeps the split wherebest[i]plus the log-probability of the pieceword[i:j]is largest, and finally walks the stored start positions backwards from the end of the word to read off the pieces. -
BPE merges
e+sfirst because that pair occurs 9 times (6 innewest, 3 inwidest), thenes+t, thenl+o, and so on. Applying the six stored rules in order to the unseen wordlowestgiveslow+est. -
WordPiece picks a different first merge:
##i+##dwith score 0.3333, becauseianddoccur only together (count 3 over 3 x 3). Raw frequency would have chosenes. After the same six merges it segmentslowestaslow,##e,##st, since##estwas never formed in six merges. -
Unigram keeps 12 pieces including
lowandestplus single characters, and its Viterbi segmentation oflowestislow+estwith log-probability -3.759, against -22.089 for spelling it out character by character. Probability, not merge order, decides.
Hyperparameters that matter
- Vocabulary size: the main knob. Commonly tens of thousands (for example 32,000), larger for broad multilingual coverage. Bigger means shorter sequences and a bigger embedding table; smaller means longer sequences and better handling of rare words.
- Character coverage (in SentencePiece, the share of characters in the training text that must be in the base alphabet, for example 99.95 percent; the rarest characters map to unknown or fall back to bytes). It matters for scripts with thousands of characters.
- Byte-level base: byte-level BPE starts from the 256 byte values so nothing is ever unknown, and SentencePiece has a
byte_fallbackoption that breaks characters outside the vocabulary into UTF-8 byte tokens. - Regularisation strength: BPE-dropout rate (the chance of skipping each merge), or the smoothing exponent alpha for Unigram sampling (each segmentation's probability is raised to the power alpha and renormalised, so a small alpha flattens the distribution and unlikely splits are sampled more often, while a large alpha sharpens it).
- Normalisation (standardising the text before splitting, such as one Unicode form for accented letters) and pre-tokenization (whether text is first split on spaces and punctuation). SentencePiece treats the space as an ordinary symbol, so it works on languages without spaces and is reversible.
Multilingual models and rare words
- The vocabulary is shared, so frequent languages claim most merges. A language with little training text is split into many short pieces, giving longer sequences and weaker embeddings for it. Fix by sampling the tokenizer's training text to up-weight low-resource languages, and by raising vocabulary size.
- Rare words: all three degrade gracefully into known pieces. Byte-level BPE never produces unknowns; WordPiece returns an unknown token for a word it cannot cover (the code above returns
[UNK]in that case); Unigram with all characters kept never does. - Unigram gives alternative segmentations and sampling, which helps noisy or morphologically rich text. BPE and WordPiece are simpler and faster to train and give one fixed segmentation.
Common mistakes. Saying WordPiece and BPE "are the same" (the merge criterion differs). Saying Unigram merges pieces (it prunes). Retraining the tokenizer without retraining the model (ids no longer match embeddings). Comparing perplexity across tokenizers, which is not meaningful because the number of tokens per text differs.
Compute BLEU (up to 4-grams) by hand for one reference: 'the cat is on the mat' and candidate: 'the cat cat on mat'. Show n-gram precision for 1-4 grams, apply brevity penalty, and explain why BLEU can be misleading for single sentence evaluation. Suggest two alternatives or complements to BLEU for sentence-level quality.
Sample Answer
Direct answer
BLEU is a geometric mean of clipped n-gram precisions for n = 1 to 4, multiplied by a brevity penalty. An n-gram is a run of n consecutive words (1-grams are single words, 2-grams are adjacent pairs, and so on), and a geometric mean multiplies the four numbers and takes the 4th root, so a single zero makes the whole result zero. For this pair the precisions are 4/5, 1/4, 0/3 and 0/2, so unsmoothed BLEU-4 is exactly 0 even though the candidate shares four words with the reference. Smoothing (add 1 to the numerator and denominator for n = 2 to 4) gives 0.3309. That fragility is why BLEU is meant to be computed over a whole test set, not one sentence.
The definition, with every symbol named
BLEU=BP⋅exp(n=1∑4wnlnpn),wn=41 pn=number of n-grams in the candidate∑g∈cand n-gramsmin(countcand(g), maxrefscountref(g)),BP={1e1−r/cc>rc≤rHere pn is the modified (clipped) n-gram precision: a candidate n-gram is credited at most as many times as it occurs in the reference, so repeating a correct word cannot buy extra credit. c is the candidate length in tokens and r is the reference length (with several references, the length closest to c). wn are the weights, uniform here. Convention used here: whitespace tokens, lower-case text, a single reference, no tokenizer beyond splitting.
Step by step on the given pair
Reference: the cat is on the mat (6 tokens). Candidate: the cat cat on mat (5 tokens).
- 1-grams. Candidate counts: the 1, cat 2, on 1, mat 1. Reference counts: the 2, cat 1, is 1, on 1, mat 1. Clipped credit: the min(1,2) = 1, cat min(2,1) = 1, on 1, mat 1, total 4 of 5. The second
catis clipped away. - 2-grams. Candidate:
the cat,cat cat,cat on,on mat. Reference:the cat,cat is,is on,on the,the mat. Onlythe catmatches, so 1 of 4. - 3-grams. Candidate has 3, none appear in the reference: 0 of 3.
- 4-grams. Candidate has 2, none match: 0 of 2.
- Brevity penalty: c=5<r=6, so BP=e1−6/5=e−0.2.
- Combine. One precision is 0, so ln0 is undefined and the geometric mean is 0. Standard implementations return 0 and warn.
- Smoothed version. Adding 1 to numerator and denominator for n = 2 to 4 turns the precisions into 4/5, 2/5, 1/4 and 1/3. Their product is 0.8×0.4×0.25×0.3333=0.02667, the 4th root is 0.4041, and 0.4041×0.8187=0.3309. The program below prints each of these steps.
import math
import warnings
warnings.filterwarnings("ignore")
from collections import Counter
from nltk.translate.bleu_score import sentence_bleu, SmoothingFunction
from nltk.translate.chrf_score import sentence_chrf
ref = "the cat is on the mat".split()
cand = "the cat cat on mat".split()
def ngrams(t, n):
return Counter(tuple(t[i:i + n]) for i in range(len(t) - n + 1))
precisions = []
for n in range(1, 5):
c, r = ngrams(cand, n), ngrams(ref, n)
clipped = sum(min(v, r[g]) for g, v in c.items())
total = sum(c.values())
precisions.append((clipped, total))
print(f"{n}-gram: clipped matches {clipped} / candidate n-grams {total} = {clipped / total:.4f}")
c_len, r_len = len(cand), len(ref)
bp = 1.0 if c_len > r_len else math.exp(1 - r_len / c_len)
print(f"candidate length {c_len}, reference length {r_len}, brevity penalty {bp:.4f}")
def bleu(precs, bp, smooth):
ps = []
for k, (m, t) in enumerate(precs):
if smooth == "add1" and k > 0:
ps.append((m + 1) / (t + 1))
else:
ps.append(m / t)
if min(ps) == 0:
return 0.0
return bp * math.exp(sum(math.log(p) for p in ps) / 4)
mine_raw = bleu(precisions, bp, "none")
mine_add1 = bleu(precisions, bp, "add1")
print(f"BLEU-4 unsmoothed: {mine_raw:.4f}")
print(f"BLEU-4 add-1 on orders 2-4: {mine_add1:.4f}")
smoothed = [m / t if k == 0 else (m + 1) / (t + 1) for k, (m, t) in enumerate(precisions)]
print("add-1 precisions:", " x ".join(f"{m + (k > 0)}/{t + (k > 0)}" for k, (m, t) in enumerate(precisions)),
f"= product {math.prod(smoothed):.5f}")
print(f"fourth root {math.prod(smoothed) ** 0.25:.4f}, times brevity penalty {bp:.4f} = {bp * math.prod(smoothed) ** 0.25:.4f}")
sm = SmoothingFunction()
nl_raw = sentence_bleu([ref], cand, weights=(0.25,) * 4)
nl_add1 = sentence_bleu([ref], cand, weights=(0.25,) * 4, smoothing_function=sm.method2)
print(f"nltk unsmoothed: {nl_raw:.4f} nltk method2 (add-1, orders 2+): {nl_add1:.4f}")
assert abs(mine_raw - nl_raw) < 1e-9 and abs(mine_add1 - nl_add1) < 1e-9
print("matches nltk 3.9.1: True")
def edit_distance(a, b):
d = [[0] * (len(b) + 1) for _ in range(len(a) + 1)]
for i in range(len(a) + 1):
d[i][0] = i
for j in range(len(b) + 1):
d[0][j] = j
for i in range(1, len(a) + 1):
for j in range(1, len(b) + 1):
d[i][j] = min(d[i - 1][j] + 1, d[i][j - 1] + 1,
d[i - 1][j - 1] + (a[i - 1] != b[j - 1]))
return d[-1][-1]
e = edit_distance(cand, ref)
print(f"word edit distance {e}, divided by reference length {r_len} = {e / r_len:.4f}")
print(f"chrF (nltk 3.9.1 defaults) {sentence_chrf(ref, cand):.4f}")
para = "the feline is on the rug".split()
print(f"correct paraphrase 'the feline is on the rug': BLEU add-1 {sentence_bleu([ref], para, weights=(0.25,)*4, smoothing_function=sm.method2):.4f}")
Output:
1-gram: clipped matches 4 / candidate n-grams 5 = 0.8000
2-gram: clipped matches 1 / candidate n-grams 4 = 0.2500
3-gram: clipped matches 0 / candidate n-grams 3 = 0.0000
4-gram: clipped matches 0 / candidate n-grams 2 = 0.0000
candidate length 5, reference length 6, brevity penalty 0.8187
BLEU-4 unsmoothed: 0.0000
BLEU-4 add-1 on orders 2-4: 0.3309
add-1 precisions: 4/5 x 2/5 x 1/4 x 1/3 = product 0.02667
fourth root 0.4041, times brevity penalty 0.8187 = 0.3309
nltk unsmoothed: 0.0000 nltk method2 (add-1, orders 2+): 0.3309
matches nltk 3.9.1: True
word edit distance 2, divided by reference length 6 = 0.3333
chrF (nltk 3.9.1 defaults) 0.3598
correct paraphrase 'the feline is on the rug': BLEU add-1 0.4273
The program reproduces the hand figures (0.8, 0.25, 0, 0, brevity penalty 0.8187). Its BLEU matches nltk 3.9.1 sentence_bleu both unsmoothed and with SmoothingFunction().method2, which adds 1 to numerator and denominator for orders above 1.
Why single-sentence BLEU misleads
- It is a corpus statistic. The standard computation sums clipped matches and candidate n-gram counts over all sentences before dividing, and takes the brevity penalty from total lengths. Per sentence, a short output has few 3-grams and 4-grams (here 3 and 2), so one miss zeroes the whole score. The number jumps between 0 and a moderate value on tiny changes, and a smoothing choice decides the result.
- One reference punishes valid wording.
the feline is on the rugis a correct paraphrase, yet it scores only 0.4273 smoothed, just 0.0964 above the brokenthe cat cat on matat 0.3309, a far smaller gap than the difference in quality deserves. - It does not see meaning, grammar or word order beyond 4-gram windows. The repeated
catis penalised only through clipping. - Smoothing variants differ, so scores from different tools are not comparable unless the tokenizer and smoothing are reported.
Two complements for sentence-level quality
- chrF compares character n-gram precision and recall (spaces ignored). It gives partial credit for morphological variants and has no zero cliff:
nltk3.9.1 defaults give 0.3598 here. The program below redoes that number from the counts: for each n from 1 to 6 it counts the character n-grams the candidate shares with the reference, forms precision (matches over candidate n-grams) and recall (matches over reference n-grams), combines them as F3=10PR/(9P+R) (beta = 3 counts recall as three times as important as precision), and averages the six F3 values. That per-order averaging is hownltkcomputes it. The original chrF definition (Popovic, 2015, and the one SacreBLEU uses) first averages the precisions and the recalls over the six orders and then forms a single F3 from the two averages. The program prints both variants; they agree to four decimals on this pair and can differ slightly on other inputs, so name the implementation when reporting chrF.
from nltk.translate.chrf_score import sentence_chrf
ref = "the cat is on the mat".split()
cand = "the cat cat on mat".split()
def char_ngrams(text, n):
s = "".join(text) # characters with spaces removed
return [s[i:i + n] for i in range(len(s) - n + 1)]
def f_beta(p, r, beta=3.0):
return (1 + beta**2) * p * r / (beta**2 * p + r) if p + r else 0.0
fs, ps, rs = [], [], []
for n in range(1, 7):
cn, rn = char_ngrams(cand, n), char_ngrams(ref, n)
overlap = sum(min(cn.count(g), rn.count(g)) for g in set(cn))
p, r = overlap / len(cn), overlap / len(rn)
fs.append(f_beta(p, r)); ps.append(p); rs.append(r)
print(f"n={n}: matches {overlap}, precision {overlap}/{len(cn)} = {p:.4f}, recall {overlap}/{len(rn)} = {r:.4f}, F3 {fs[-1]:.4f}")
mine = sum(fs) / len(fs)
print(f"mean of the six F3 values {mine:.4f}; nltk sentence_chrf {sentence_chrf(ref, cand):.4f}")
assert abs(mine - sentence_chrf(ref, cand)) < 1e-9
P, R = sum(ps) / 6, sum(rs) / 6
print(f"original definition: mean precision {P:.4f}, mean recall {R:.4f}, one F3 from the two means {f_beta(P, R):.4f}")
Output:
n=1: matches 12, precision 12/14 = 0.8571, recall 12/16 = 0.7500, F3 0.7595
n=2: matches 8, precision 8/13 = 0.6154, recall 8/15 = 0.5333, F3 0.5405
n=3: matches 5, precision 5/12 = 0.4167, recall 5/14 = 0.3571, F3 0.3623
n=4: matches 3, precision 3/11 = 0.2727, recall 3/13 = 0.2308, F3 0.2344
n=5: matches 2, precision 2/10 = 0.2000, recall 2/12 = 0.1667, F3 0.1695
n=6: matches 1, precision 1/9 = 0.1111, recall 1/11 = 0.0909, F3 0.0926
mean of the six F3 values 0.3598; nltk sentence_chrf 0.3598
original definition: mean precision 0.4122, mean recall 0.3548, one F3 from the two means 0.3598
For n = 1, 12 of the candidate's 14 characters are matched and 12 of the reference's 16 are covered, which gives precision 0.8571 and recall 0.7500. The score falls with n because longer character runs are broken more often by the missing and repeated words, and the mean of the six values is the 0.3598 shown above. It is a standard complement for morphologically rich languages.
2. Edit-based rate (TER, translation edit rate, family). Count word insertions, deletions and substitutions to turn the candidate into the reference, divided by reference length. The shift-free version computed above is 2 edits over 6 words = 0.3333; real TER also allows block shifts, so it can be lower.
Learned metrics that score a candidate against the source and reference with a trained model (COMET and BLEURT are examples) and human adequacy and fluency ratings are the usual next step when decisions matter. A learned metric is itself a model trained on human judgments, so validate it on your language pair and domain before trusting it.
Common mistakes
- Reporting 0 as "no overlap" when unigrams overlap; the zero comes from the missing higher orders.
- Forgetting clipping and counting
cattwice (5 of 5 unigrams would be wrong). - Using the candidate length where the reference length belongs in the brevity penalty, or applying the penalty when the candidate is longer.
- Comparing BLEU numbers across tokenizers, smoothing methods or reference sets.
Unlock Full Question Bank
Get access to all 24 Natural Language Processing interview questions and detailed answers.
Sign in to ContinueJoin thousands of developers preparing for their dream job.