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.
Given the last-layer hidden states of an encoder for a batch of padded sequences (shape [batch, seq_len, hidden_dim]) and the attention mask, produce a fixed-size sentence embedding. Implement the pooling you would use, explain how padding affects it, and say which strategy you would pick for semantic similarity and why.
Sample Answer
The idea
An encoder (a transformer that reads the whole sentence and outputs one vector per token) returns a tensor of shape [batch, seq_len, hidden_dim]. A sentence embedding is one vector per sentence, so something has to collapse the seq_len axis. That collapse is called pooling. The catch is padding: sentences in a batch have different lengths, so shorter ones are filled up with dummy tokens, and the attention mask (1 for a real token, 0 for padding) records which positions are real. A pooling that ignores the mask averages in vectors that mean nothing, and the same sentence then gets a different embedding depending on what it was batched with.
For semantic similarity I would use masked mean pooling over the last hidden layer, then L2-normalise (divide the vector by its own length, the square root of the sum of its squared entries, so it ends up with length 1), provided the checkpoint (a saved set of trained model weights) was trained for sentence similarity with mean pooling. The pooling must match how the embedding model was trained: the pooling is part of the model, not a free choice.
Implementation
Three poolings, all taking h of shape [B, T, H] and mask of shape [B, T]:
- Mean: multiply
hby the mask (shape[B, T, 1]afterunsqueeze), sum overT, divide by the number of real tokens. Summing the[B, T, 1]mask overTgives that count with shape[B, 1], which broadcasts against the[B, H]sum (the 2-D mask alone,mask.sum(dim=1), would have shape[B]). The divisor is the count of real tokens, notT. - Max: fill padded positions with
-infbefore taking the max overT. Filling with 0 is wrong whenever the real values in a dimension are all negative, because the 0 then wins. - CLS: take position 0 (the special classification token). Right padding means the dummy tokens are added at the end of a sentence, so position 0 is always a real token; left padding means they are added at the start, so position 0 could be a dummy.
import torch
import torch.nn.functional as F
torch.manual_seed(0)
torch.set_num_threads(1)
def masked_mean(h, mask):
# h: [B, T, H] hidden states, mask: [B, T] with 1 for real tokens, 0 for padding
m = mask.unsqueeze(-1).to(h.dtype) # [B, T, 1]
summed = (h * m).sum(dim=1) # [B, H]
counts = m.sum(dim=1).clamp(min=1.0) # [B, 1] number of real tokens; a whole number, so the clamp only touches an all-pad row
return summed / counts
def masked_max(h, mask):
h = h.masked_fill(mask.unsqueeze(-1) == 0, float("-inf"))
return h.max(dim=1).values
def cls_pool(h, mask):
return h[:, 0, :] # first position, padding never touches it (right padding)
def naive_mean(h, mask):
return h.mean(dim=1) # ignores the mask: the bug
B, T, H = 3, 6, 4
lengths = torch.tensor([6, 3, 2])
mask = (torch.arange(T)[None, :] < lengths[:, None]).long() # [3, 6]
h = torch.randn(B, T, H)
# pad positions in a real encoder still hold non-zero vectors; mimic that
print("mask:\n", mask)
# Reference: loop over each sequence and average only its real tokens
ref = torch.stack([h[i, : lengths[i]].mean(dim=0) for i in range(B)])
print("masked_mean matches per-sequence loop:", torch.allclose(masked_mean(h, mask), ref, atol=1e-6))
print("naive_mean matches per-sequence loop: ", torch.allclose(naive_mean(h, mask), ref, atol=1e-6))
# Same 2-token sentence encoded alone (T=2) and inside a batch padded to T=6
alone = h[2:3, :2, :]
alone_mask = torch.ones(1, 2, dtype=torch.long)
print("sentence 2 alone, masked mean :", masked_mean(alone, alone_mask).numpy().round(3))
print("sentence 2 padded, masked mean:", masked_mean(h, mask)[2].numpy().round(3))
print("sentence 2 padded, naive mean :", naive_mean(h, mask)[2].numpy().round(3))
# Cosine between the same sentence with and without padding
emb_pad = F.normalize(masked_mean(h, mask), dim=-1)[2]
emb_alone = F.normalize(masked_mean(alone, alone_mask), dim=-1)[0]
naive_pad = F.normalize(naive_mean(h, mask), dim=-1)[2]
print("cos(masked padded, alone):", round(float(emb_pad @ emb_alone), 4))
print("cos(naive padded, alone): ", round(float(naive_pad @ emb_alone), 4))
# Max pooling needs -inf, not 0, at pad positions
h_neg = -torch.ones(1, 4, 2) # all real values negative
m_neg = torch.tensor([[1, 1, 0, 0]])
zero_filled = (h_neg * m_neg.unsqueeze(-1)).max(dim=1).values
print("max with zero-filled pads:", zero_filled.numpy(), " masked_max:", masked_max(h_neg, m_neg).numpy())
print("shapes:", masked_mean(h, mask).shape, masked_max(h, mask).shape, cls_pool(h, mask).shape)
# Empty-sequence guard: an all-zero mask row gives zeros, not NaN
empty = torch.zeros(1, 3, dtype=torch.long)
print("all-pad row:", masked_mean(h[:1, :3], empty).numpy())
# Tiny hand-checkable case: 2 real tokens and 1 pad, 2-number vectors
t = torch.tensor([[[1.0, 2.0], [3.0, 4.0], [100.0, 100.0]]]) # the pad slot holds junk
tm = torch.tensor([[1, 1, 0]])
print("masked mean:", masked_mean(t, tm).numpy(), "| naive mean:", naive_mean(t, tm).numpy().round(2))
print("masked mean after L2-normalising:", F.normalize(masked_mean(t, tm), dim=-1).numpy().round(4))
Output:
mask:
tensor([[1, 1, 1, 1, 1, 1],
[1, 1, 1, 0, 0, 0],
[1, 1, 0, 0, 0, 0]])
masked_mean matches per-sequence loop: True
naive_mean matches per-sequence loop: False
sentence 2 alone, masked mean : [[-0.452 0.241 0.799 -0.109]]
sentence 2 padded, masked mean: [-0.452 0.241 0.799 -0.109]
sentence 2 padded, naive mean : [-0.157 0.278 0.206 0.456]
cos(masked padded, alone): 1.0
cos(naive padded, alone): 0.4461
max with zero-filled pads: [[-0. -0.]] masked_max: [[-1. -1.]]
shapes: torch.Size([3, 4]) torch.Size([3, 4]) torch.Size([3, 4])
all-pad row: [[0. 0. 0. 0.]]
masked mean: [[2. 3.]] | naive mean: [[34.67 35.33]]
masked mean after L2-normalising: [[0.5547 0.8321]]
Reading the output:
masked_meanequals a plain per-sentence loop that averages only the real tokens; the unmaskedh.mean(dim=1)does not.- The 2-token sentence gets the identical vector alone and inside a batch padded to 6 positions with masked mean (cosine 1.0). With the unmasked mean its cosine to the alone version is 0.4461. In this toy the pad positions hold random vectors, which is the point: whatever the encoder leaves at pad positions is contamination.
- Zero-filled max pooling returns 0 where masked max correctly returns -1.
- The clamp at 1 on the divisor makes a row that is entirely padding return zeros instead of NaN (0 divided by 0). A count of real tokens is a whole number, so the clamp changes no other row. A tiny clamp such as
1e-9would break this in float16, where1e-9rounds to 0 and the division gives NaN again. - The last two printed lines are the hand-checkable case. Real vectors (1, 2) and (3, 4) plus one junk pad (100, 100): the masked mean is ((1 + 3) / 2, (2 + 4) / 2) = (2, 3), while the unmasked mean divides everything by 3 and gets (34.67, 35.33), dominated by the junk. L2-normalising (2, 3) divides by its length 22+32=13≈3.606 and gives (0.5547, 0.8321).
Padding affects pooling in two separate ways. First, the pooling arithmetic, which the mask fixes as above. Second, the encoder itself: inside the encoder the same mask is applied in attention so real tokens never attend to padding. With right padding that makes the hidden states of real tokens independent of padding, up to small numerical differences from different batch shapes. With left padding the real tokens sit at shifted positions, so a model with absolute position embeddings only stays independent of padding if the position ids are computed from the mask. Once the pooling is masked and the positions are handled, the embedding is a function of the sentence alone.
Which strategy for semantic similarity
| Pooling | What it uses | Typical behaviour for similarity |
|---|---|---|
| Masked mean | Every real token equally | The usual choice for models trained with a similarity objective that pools by mean; uses all tokens, which is robust to one token carrying the meaning |
| CLS | One token | Good only if the model was trained so that this token summarises the sentence (for example a classification fine-tune or a model trained for CLS pooling); in a raw masked-language-model checkpoint (one trained only to guess hidden words) the token is not trained to be a sentence summary |
| Max | Strongest activation per dimension | Sensitive to single tokens and to outliers; occasionally helps for keyword-like signals |
Decision: masked mean, then normalise, then cosine similarity. What flips it: the model card or training recipe specifies CLS (use CLS), or a task-specific fine-tune shows on a held-out set that another pooling scores higher on the similarity metric you care about (for example Spearman correlation, which compares how two rankings order the same items, between the model's similarity scores and human similarity ratings, or recall@k, the fraction of the truly relevant items that appear in your top k results on your own queries). Pooled vectors from a model that was never trained for similarity are usually weak regardless of the pooling; the fix is a contrastive fine-tune (training that pulls paired sentences together and pushes others apart), not a cleverer pool.
Pitfalls
- Dividing by
Tinstead of the true length (the unmasked mean above). - An integer mask multiplied into half-precision states: cast the mask to
h.dtype, and accumulate the sum in float32 when running in fp16 or bf16 (half-precision formats that store each number in 16 bits instead of 32, which saves memory and time but rounds more coarsely, so long sums can lose accuracy). - Forgetting L2 normalisation (scaling each vector to length 1, as defined above): cosine similarity equals the dot product only for unit-length vectors, and many vector indexes assume it.
- Padding side: with left padding, CLS at position 0 is a pad token; use the mask to locate the first real token, or pool by mean.
- Mixing pooling at index time and query time. Both sides must use the same model, pooling and normalisation.
You are evaluating a named-entity-recognition system for legal documents. Which metrics would you report, how would you treat rare entity types, and how would you set acceptable thresholds from business impact?
Sample Answer
The idea
Report entity-level scores per entity type, with the rare types shown separately and with uncertainty, and set the confidence thresholds by the cost of each kind of error rather than by a generic F1 target. Token-level accuracy is a poor headline for NER because most tokens are outside any entity, so a system can score well while missing most entities.
Which metrics to report
An entity is a span (start, end) plus a type. Strict entity-level matching counts a prediction as correct only if span and type both match a gold entity exactly. Precision is correct predictions divided by predictions made, recall is correct predictions divided by gold entities (the human-labelled correct answers), and F1 is their harmonic mean, 2PR / (P + R), which stays low unless both are high (P = 0.9 and R = 0.5 give 0.643, not the arithmetic 0.7). Here the legal examples are: redaction, blacking out names and identifiers before a document is shared, and a conflict check, where a law firm searches its records for parties it already represents or opposes so it does not take a client with a conflicting interest. Report:
- Strict entity-level precision, recall and F1, per type. This is the primary table.
- Micro and macro averages. Micro-F1 pools all entities, so frequent types dominate. Macro-F1 averages per-type F1, so every type counts equally; it is the one that exposes a weak rare type.
- A relaxed (overlap-based) score next to the strict one. The gap between them is the share of errors that are boundary errors rather than missed or invented entities. Boundary errors matter differently by use: a redaction tool that cuts a name in half leaks the rest, while a search index may tolerate it.
- A type confusion table (gold type by predicted type), because a PARTY labelled as COURT is a different failure from a missed one.
- Token-level scores only as a secondary diagnostic.
Computed example
The sentence uses BIO tags, one tag per token: B-X marks the first token of an entity of type X, I-X a token inside the same entity, and O a token outside any entity. In the gold sentence, tokens 1-2 are a PARTY (B-PARTY I-PARTY), tokens 5-7 a STATUTE and token 11 a DATE; the prediction stops the PARTY after one token and the STATUTE after two. The function spans turns tags into (start, end, type) triples, so exact matching is a set intersection. Of the 12 tokens, 10 match, which is the token accuracy 0.833. The program first scores one sentence two ways: with a shortened party name and a shortened statute citation, token accuracy is 0.833, while strict entity precision and recall are both 0.333, because only the date is exactly right; the relaxed view counts all 3 gold spans as overlapped by a same-type prediction. It then builds a synthetic evaluation set (the entity counts, detection rates and confidence distributions are chosen by the program, not measured on legal text) with two common types, PARTY (400 gold) and DATE (300), and two rare ones, COURT (40) and STATUTE (25), to show per-type, micro/macro, uncertainty and cost-based thresholds. How the synthetic set is built: for each type the table types gives (gold count, detection rate, number of wrong predictions). Each gold entity is detected when rng.random() < detection rate; a detected entity gets a confidence drawn from a Beta distribution (a distribution on 0 to 1; Beta(8, 2) has mean 0.8, Beta(5, 2) mean 0.71 for the rare types) and a missed entity has no prediction at all (nan). Each wrong prediction (a false positive, FP) gets a low confidence from Beta(2, 4), with mean 0.33. A real NER model supplies such a confidence itself, commonly the probability it assigns to the predicted tags averaged over the span. The counts follow: a true positive (TP) is a detected entity at or above the threshold, FP is a wrong prediction at or above it, and the false negatives (FN) are the gold entities not counted as TP, including detected ones that fall below the threshold.
import numpy as np
# ---- 1. Entity-level (strict) metrics from BIO tags, and why token accuracy flatters ----
def spans(tags):
out, start, typ = set(), None, None
for i, t in enumerate(tags + ["O"]): # sentinel closes a span at the end
if start is not None and not (t.startswith("I-") and t[2:] == typ):
out.add((start, i, typ)); start, typ = None, None
if t.startswith("B-") or (t.startswith("I-") and start is None): # a stray I- starts a span
start, typ = i, t[2:]
return out
gold = "O B-PARTY I-PARTY O O B-STATUTE I-STATUTE I-STATUTE O O O B-DATE".split()
pred = "O B-PARTY O O O B-STATUTE I-STATUTE O O O O B-DATE".split()
g, p = spans(gold), spans(pred)
tp = len(g & p)
print("gold spans:", sorted(g))
print("pred spans:", sorted(p))
print(f"token accuracy {np.mean([a == b for a, b in zip(gold, pred)]):.3f} strict entity P {tp/len(p):.3f} R {tp/len(g):.3f}")
partial = sum(any(a[2] == b[2] and a[0] < b[1] and b[0] < a[1] for b in p) for a in g)
print(f"gold spans with a same-type overlapping prediction (partial credit view): {partial} of {len(g)}")
# ---- 2. Per-type metrics, micro vs macro, on a synthetic evaluation set ----
rng = np.random.default_rng(0)
types = {"PARTY": (400, .95, 30), "DATE": (300, .97, 20), "COURT": (40, .85, 8), "STATUTE": (25, .80, 6)}
rows = [] # (type, is_true_positive, confidence)
for ty, (n, rec, nfp) in types.items():
found = rng.random(n) < rec
a, b = (8, 2) if n > 100 else (5, 2)
for f in found:
rows.append((ty, bool(f), rng.beta(a, b) if f else np.nan))
for _ in range(nfp):
rows.append((ty, False, rng.beta(2, 4))) # a predicted entity that is wrong
def counts(ty, thr):
tp = sum(1 for t, ok, c in rows if t == ty and ok and c >= thr)
fp = sum(1 for t, ok, c in rows if t == ty and (not ok) and not np.isnan(c) and c >= thr)
fn = types[ty][0] - tp
return tp, fp, fn
def prf(tp, fp, fn):
p_ = tp / (tp + fp) if tp + fp else 0.0
r_ = tp / (tp + fn) if tp + fn else 0.0
return p_, r_, 2 * p_ * r_ / (p_ + r_) if p_ + r_ else 0.0
print("\nthreshold 0.0 type gold P R F1")
f1s, TP, FP, FN = [], 0, 0, 0
for ty in types:
tp, fp, fn = counts(ty, 0.0); TP += tp; FP += fp; FN += fn
p_, r_, f_ = prf(tp, fp, fn); f1s.append(f_)
print(f" {ty:8s} {types[ty][0]:5d} {p_:.3f} {r_:.3f} {f_:.3f}")
print(f"micro F1 {prf(TP, FP, FN)[2]:.3f} macro F1 {np.mean(f1s):.3f}")
# Uncertainty on a rare type: bootstrap recall for STATUTE over its 25 gold entities
n_gold = types["STATUTE"][0]
n_hit = sum(ok for t, ok, c in rows if t == "STATUTE")
hits = np.array([1] * n_hit + [0] * (n_gold - n_hit))
boot = [rng.choice(hits, n_gold).mean() for _ in range(2000)]
print(f"STATUTE recall {hits.mean():.3f}, bootstrap 95% interval [{np.percentile(boot, 2.5):.3f}, {np.percentile(boot, 97.5):.3f}] from {n_gold} gold entities")
# ---- 3. Thresholds from business cost: a missed entity costs c_fn, a wrong one costs c_fp ----
c_fn = {"PARTY": 10, "DATE": 5, "COURT": 20, "STATUTE": 20}
c_fp = 1
print("\ntype best threshold recall precision cost(best) cost(thr 0)")
for ty in types:
best = min(((c_fn[ty] * counts(ty, th)[2] + c_fp * counts(ty, th)[1], th) for th in np.arange(0, 0.96, 0.05)), key=lambda x: (x[0], x[1]))
tp, fp, fn = counts(ty, best[1]); p_, r_, _ = prf(tp, fp, fn)
tp0, fp0, fn0 = counts(ty, 0.0)
print(f"{ty:8s} {best[1]:13.2f} {r_:6.3f} {p_:9.3f} {best[0]:10d} {c_fn[ty]*fn0 + c_fp*fp0:11d}")
# One type by hand: DATE, with a missed date costing 5 and a false alarm costing 1
for th in (0.0, 0.45):
tp, fp, fn = counts("DATE", th)
print(f"DATE at threshold {th:.2f}: TP {tp} FP {fp} FN {fn} cost = 5*{fn} + 1*{fp} = {5*fn + fp}")
Output:
gold spans: [(1, 3, 'PARTY'), (5, 8, 'STATUTE'), (11, 12, 'DATE')]
pred spans: [(1, 2, 'PARTY'), (5, 7, 'STATUTE'), (11, 12, 'DATE')]
token accuracy 0.833 strict entity P 0.333 R 0.333
gold spans with a same-type overlapping prediction (partial credit view): 3 of 3
threshold 0.0 type gold P R F1
PARTY 400 0.926 0.938 0.932
DATE 300 0.935 0.957 0.946
COURT 40 0.822 0.925 0.871
STATUTE 25 0.786 0.880 0.830
micro F1 0.930 macro F1 0.895
STATUTE recall 0.880, bootstrap 95% interval [0.760, 1.000] from 25 gold entities
type best threshold recall precision cost(best) cost(thr 0)
PARTY 0.30 0.938 0.957 267 280
DATE 0.45 0.957 0.983 70 85
COURT 0.30 0.925 0.902 64 68
STATUTE 0.00 0.880 0.786 66 66
DATE at threshold 0.00: TP 287 FP 20 FN 13 cost = 5*13 + 1*20 = 85
DATE at threshold 0.45: TP 287 FP 5 FN 13 cost = 5*13 + 1*5 = 70
Reading it:
- Micro F1 is 0.930 while macro F1 is 0.895, and the STATUTE row (0.830) is where the macro score drops. A single pooled number hides that.
- STATUTE has only 25 gold entities. Its measured recall is 0.880 but the bootstrap 95% interval (resampling the 25 entities 2,000 times) runs from 0.760 to 1.000. A difference of a few points between two models on this type is within noise. The fixes are to enrich the test set for rare types (sample more documents that contain them), report counts next to every score, and use cross-validation or repeated annotation to tighten the interval.
- Rare types need their own bars. Do not let a combined threshold approve a model that has not been checked on them.
Setting thresholds from business impact
For each type, the model emits a confidence per predicted entity. A prediction is kept if its confidence is at least the threshold. Lower thresholds raise recall and lower precision. Choose the threshold that minimises the expected cost
cost(τ)=cFN⋅FN(τ)+cFP⋅FP(τ)where tau is the threshold, FN the missed gold entities, FP the wrong predictions, and c_FN and c_FP the business cost of each. In the program the assumed costs are 10 per missed PARTY, 5 per missed DATE, 20 per missed COURT or STATUTE, and 1 per false alarm. With these assumed costs the best thresholds in this draw are 0.30 (PARTY), 0.45 (DATE), 0.30 (COURT) and 0.00 (STATUTE, where no threshold beats keeping everything in this draw), and the cost falls from 280 to 267 for PARTY and from 85 to 70 for DATE. The costs are assumptions; in practice they come from the process around the model: the lawyer minutes to review a false alarm, and the exposure from a missed party in a conflict check or a missed identifier in a redaction.
The threshold search tries every value from 0 to 0.95 in steps of 0.05, computes the cost at each and keeps the lowest; if two thresholds tie, the lower one wins. Here is one type by hand, using the last two printed lines of the program: for DATE, missing a date costs 5 and a false alarm costs 1. At threshold 0 there are 287 TP, 20 FP and 13 FN, so cost = 5 x 13 + 1 x 20 = 85. At threshold 0.45 the same 287 true entities are still kept (their confidences are high) but only 5 of the 20 false alarms survive, so cost = 5 x 13 + 1 x 5 = 70. Raising the threshold paid off because it removed false alarms without losing any true entity. Whether it pays is decided by how well the confidences of the false alarms separate from those of the true entities: with a missed STATUTE costing 20 against 1 per false alarm, a threshold only lowers the cost if it removes many false alarms while dropping very few true entities, and in this draw no threshold does that for STATUTE. With only 25 gold STATUTE entities and 6 false alarms, the best threshold for that type rests on a handful of items and would move with a different sample, so treat it as an estimate and confirm it on a separate test set rather than reading it as a rule that rare types should never be thresholded.
A practical way to turn this into acceptance criteria:
- Name the failure that is expensive (for example, a missed party name in a redaction pipeline) and set a minimum recall for that type on the strict metric, with the confidence interval's lower bound, not the point estimate, meeting the bar.
- Set a precision floor from reviewer capacity: false alarms times minutes per review must fit the team's budget.
- Use human review for the low-confidence band rather than a hard accept or reject, and report how much volume goes to review.
- Tune thresholds on a validation set, confirm on a separate test set, and track the metrics again after each change in document templates (template drift: new contract formats or wording that the model has not seen).
Pitfalls
- Reporting one pooled F1 and nothing per type.
- Mixing metric conventions between papers and internal tools: strict span match, partial overlap and token-level scores can differ widely on the same predictions.
- Treating annotator disagreement as noise rather than a ceiling: measure inter-annotator agreement (how often two annotators labelling the same text independently give the same span and type) on entity boundaries first, because the model cannot be reliably better than the labels.
- Evaluating on documents from the same templates the model trained on, and calling it generalisation.
Describe strategies to handle out-of-vocabulary (OOV) words at inference time for both static embeddings and subword-based tokenizers. Which strategies are most effective for low-resource languages with limited token vocabularies and noisy orthography?
Sample Answer
The idea. An out-of-vocabulary (OOV) word is one the model has no entry for. Static embeddings (one fixed vector per word, learned from which words appear near which others, as in Word2Vec or GloVe) fail hard: no row, no vector. Subword tokenizers rarely fail, because they spell the word from smaller pieces, but the pieces can be so fragmented that meaning is lost. The strategies below fall into three families: change what you look up (normalize, correct, back off), change how the vector is built (compose it from character n-grams or pieces), and change training so the model has seen noise (augmentation).
Strategies for static embeddings, in the order I would try them
- Normalize first (case, Unicode form, repeated letters, known spelling variants). Many OOV words are one normalization away from a known word.
- Back off to a nearest known word by spelling (edit distance, the minimum number of insertions, deletions and substitutions) or by a transliteration table.
- Compose a vector from character n-grams (substrings of n characters, e.g. 3). This is the fastText-style approach: a word vector is the sum or mean of the vectors of its n-grams, so an unseen word still gets a vector built from n-grams it shares with known words.
- Last resort: a single shared unknown vector (UNK). It carries no word-specific meaning. Better than UNK alone is to train with word dropout (randomly replace some training words with UNK) so the model has learned what an unknown looks like.
Strategies for subword tokenizers
- Byte fallback or a byte-level base alphabet: a word with no matching pieces is spelled out one byte at a time, and any text is a sequence of bytes, so no input ever maps to an unknown token.
- Train or extend the tokenizer on text of the target language so its words are not shattered into single characters. If you add new tokens to an existing model, initialize each new embedding as the mean of the embeddings of the pieces it used to be split into, then fine-tune.
- Train with subword regularization (BPE-dropout, which randomly skips some of the learned merge steps while splitting a word, or Unigram sampling, which draws one of several likely splits at random) so that the model has seen several segmentations of the same word and is not thrown by a typo that changes the segmentation.
- Augment training data with synthetic noise (typos, dropped diacritics, alternate spellings).
A measured example. The stand-in below has no trained embeddings. It tests the lookup part only: given a noisy OOV word made from one of 38 known words by random insertions, deletions and substitutions, which method recovers the intended word? "unk" always returns the unknown vector (so it never recovers the word), "ngram" picks the known word with the highest overlap (Jaccard similarity, shared n-grams divided by all n-grams) of character trigrams, "edit" picks the known word with the smallest edit distance. Each row averages over about 1,900 noisy words (seed 0, no noisy word that is itself a vocabulary word). The code in four parts: ngrams cuts a word into overlapping 3-character pieces after adding < and > as boundary marks; lev fills the standard edit-distance table one row at a time; corrupt applies a chosen number of random substitutions (s), deletions (d) and insertions (i) to a word; and the three strategy_* functions each take a noisy word and return the vocabulary word they pick, with ties broken alphabetically so the run repeats. The driver corrupts every vocabulary word 50 times at each noise level and counts how often each strategy returns the original word.
import random
vocab = ("password reset order cancel refund account delivery payment invoice address "
"shipping update login logout email phone number support ticket balance transfer "
"deposit withdraw receipt product service customer message notification setting "
"profile security verify confirm subscribe unsubscribe download upload").split()
alphabet = "abcdefghijklmnopqrstuvwxyz"
def ngrams(w, n=3):
w = "<" + w + ">"
return {w[i:i + n] for i in range(len(w) - n + 1)}
def jaccard(a, b): return len(a & b) / len(a | b)
def lev(a, b):
prev = list(range(len(b) + 1))
for i, ca in enumerate(a, 1):
cur = [i]
for j, cb in enumerate(b, 1):
cur.append(min(prev[j] + 1, cur[-1] + 1, prev[j - 1] + (ca != cb)))
prev = cur
return prev[-1]
def corrupt(w, rng, edits):
w = list(w)
for _ in range(edits):
op = rng.choice("sdi"); i = rng.randrange(len(w))
if op == "s": w[i] = rng.choice(alphabet)
elif op == "d" and len(w) > 3: del w[i]
else: w.insert(i, rng.choice(alphabet))
return "".join(w)
def strategy_unk(w): return None
def strategy_ngram(w): return max(vocab, key=lambda v: (jaccard(ngrams(w), ngrams(v)), v))
def strategy_edit(w): return min(vocab, key=lambda v: (lev(w, v), v))
print("vocabulary size:", len(vocab))
print("char-trigram sets of 'pasword' vs 'password':", sorted(ngrams("pasword")), sorted(ngrams("password")))
for edits in (1, 2, 3):
rng = random.Random(0)
trials, hit = 0, {"unk": 0, "ngram": 0, "edit": 0}
for _ in range(50):
for target in vocab:
noisy = corrupt(target, rng, edits)
if noisy in vocab: continue
trials += 1
hit["unk"] += strategy_unk(noisy) == target
hit["ngram"] += strategy_ngram(noisy) == target
hit["edit"] += strategy_edit(noisy) == target
print(f"{edits} random edit(s), {trials} noisy OOV words: " + ", ".join(f"{k} {v / trials:.3f}" for k, v in hit.items()))
Output:
vocabulary size: 38
char-trigram sets of 'pasword' vs 'password': ['<pa', 'asw', 'ord', 'pas', 'rd>', 'swo', 'wor'] ['<pa', 'ass', 'ord', 'pas', 'rd>', 'ssw', 'swo', 'wor']
1 random edit(s), 1880 noisy OOV words: unk 0.000, ngram 0.998, edit 0.998
2 random edit(s), 1870 noisy OOV words: unk 0.000, ngram 0.939, edit 0.997
3 random edit(s), 1899 noisy OOV words: unk 0.000, ngram 0.798, edit 0.965
Reading the output. pasword and password share 6 trigrams out of 7 and 8 (<pa, pas, swo, wor, ord, rd>, where < and > mark word boundaries), which is exactly why an n-gram embedding gives the typo a vector close to the correct word's. On a 38-word vocabulary, spelling-based lookup recovers the intended word 99.8% of the time at one edit; the n-gram method falls to 79.8% at three edits while edit distance holds at 96.5%. This tells you that the n-gram lookup is a weaker matcher than edit distance on short words, not that it is a weaker embedding: in a real model n-gram vectors are learned together with the rest and also cover words that have no spelling neighbour. The vocabulary here is small; a real vocabulary has many more near neighbours, so recovery would be expected to be lower and ambiguity higher; this 38-word test does not measure by how much. The lookup test cannot show what an n-gram vector does, so the next part shows that directly.
What an n-gram vector does, and what stripped accents do to a tokenizer. The first half of the next program gives every character trigram a random vector (these are not trained vectors; a real model learns them) and builds each word's vector as the sum of its trigram vectors, which is the fastText-style construction. The second half splits words greedily, longest known piece first, using a small piece list taken from Vietnamese, where accent marks (diacritics) are part of the spelling. Glosses: "xin chào" is hello, "cảm ơn" is thank you, "bạn" is you.
import unicodedata
import numpy as np
# Part 1: what a character n-gram vector does. Every trigram gets a random vector (these are NOT
# trained vectors); a word vector is the sum of its trigram vectors, as in fastText-style models.
def ngrams(w, n=3):
w = "<" + w + ">"
return [w[i:i + n] for i in range(len(w) - n + 1)]
def cosine(a, b): return float(a @ b / (np.linalg.norm(a) * np.linalg.norm(b)))
def word_vec(w, table, rng, dim=64):
for g in ngrams(w):
if g not in table: table[g] = rng.normal(size=dim)
return sum(table[g] for g in ngrams(w))
shared = len(set(ngrams("pasword")) & set(ngrams("password")))
print("trigrams: pasword", len(ngrams("pasword")), "password", len(ngrams("password")), "shared", shared)
print("shared / sqrt(7 * 8) =", round(shared / (7 * 8) ** 0.5, 3))
sims_typo, sims_other = [], []
for seed in range(10):
rng, table = np.random.default_rng(seed), {}
typo, good, other = (word_vec(w, table, rng) for w in ("pasword", "password", "shipping"))
sims_typo.append(cosine(typo, good)); sims_other.append(cosine(other, good))
print(f"cosine(pasword, password) over 10 seeds: min {min(sims_typo):.2f}, max {max(sims_typo):.2f}")
print(f"cosine(shipping, password) over 10 seeds: min {min(sims_other):.2f}, max {max(sims_other):.2f}")
# Part 2: a word with its accents stripped, before and after folding. Greedy longest-match
# segmentation over a small piece vocabulary built from Vietnamese text with accents.
# Glosses: "xin chào" = hello, "cảm ơn" = thank you, "bạn" = you.
def fold(s):
s = s.replace("đ", "d").replace("Đ", "D")
return "".join(c for c in unicodedata.normalize("NFD", s) if not unicodedata.combining(c))
def segment(word, pieces):
out, i = [], 0
while i < len(word):
for j in range(len(word), i, -1):
if word[i:j] in pieces or j - i == 1:
out.append(word[i:j]); i = j; break
return out
accented = ["xin", "chào", "cảm", "ơn", "bạn"]
pieces = set(accented)
for w in ["chào", "chao", "cảm", "cam"]:
print(f"{w!r:8} -> {segment(w, pieces)}")
folded_pieces = {fold(p) for p in accented}
print("after folding both the text and the piece list:")
for w in ["chào", "chao", "cảm", "cam"]:
print(f"{w!r:8} -> {segment(fold(w), folded_pieces)}")
Output:
trigrams: pasword 7 password 8 shared 6
shared / sqrt(7 * 8) = 0.802
cosine(pasword, password) over 10 seeds: min 0.74, max 0.87
cosine(shipping, password) over 10 seeds: min -0.18, max 0.05
'chào' -> ['chào']
'chao' -> ['c', 'h', 'a', 'o']
'cảm' -> ['cảm']
'cam' -> ['c', 'a', 'm']
after folding both the text and the piece list:
'chào' -> ['chao']
'chao' -> ['chao']
'cảm' -> ['cam']
'cam' -> ['cam']
Reading it: pasword and password share 6 trigrams out of 7 and 8, so the cosine between their summed vectors is about 6/7×8=0.80 on average, and across 10 random seeds it stayed between 0.74 and 0.87. An unrelated word shares no trigram, and its cosine sat between -0.18 and 0.05 (near 0 means unrelated directions). That is how a fastText-style model hands a typo a vector close to the right word's, with no row for the typo itself. In the second half, the accented word is one known piece, while the same word typed without accents falls apart into single letters (4 pieces for chao), so the unit that carried the meaning is lost. Folding, meaning removing the combining accent marks from both the text and the piece list, restores one piece, at the price that words differing only by an accent become the same word; that is why the folding rule has to be checked against held-out text.
Low-resource languages with noisy orthography. Orthography means a language's spelling conventions. It is noisy when spelling is inconsistent, when diacritics (accent and tone marks) are often dropped, when one language is written in several scripts, or when people mix two languages in one sentence (code-switching). Transliteration means writing a word from one script using another script's letters. My recommendation, in order:
- A character-aware representation (n-gram embeddings, or a subword tokenizer trained on that language's own text so words are not shattered) is the most robust single choice, because it does not rely on exact word matches and noisy spellings share most of their pieces.
- Add text normalization rules the community actually uses (diacritic folding, transliteration between scripts), validated against held-out text, because the wrong rule merges different words.
- Train with synthetic spelling noise so the downstream model sees the variation.
- Use a pretrained multilingual encoder (one model trained on text from many languages) with byte or character fallback only if the language is covered; otherwise continue pretraining, which means training the model further on plain unlabeled text in that language before fine-tuning on your task, using whatever text exists.
What would flip this: if the language has a standard spelling and clean text, plain subword tokenization is enough and the extra machinery adds risk.
Diagnostics. Measure the unknown-token rate (static) or the average pieces per word (subword) on held-out text, and break it down by word frequency band; a rising pieces-per-word is the sign of fragmentation. Always check downstream accuracy on noisy versus clean slices.
Common mistakes. Mapping every OOV to UNK and calling it handled; lowercasing or stripping accents so aggressively that different words merge; adding tokens without initializing their embeddings sensibly; evaluating only on clean text.
Design a multi-stage semantic parsing pipeline: intent detection → slot filling → canonicalization → executable plan. For each stage, recommend model types, training data requirements, evaluation metrics, and techniques to handle error propagation between stages.
Sample Answer
Direct answer
A semantic parsing pipeline turns a free-text request into something a program can run. Run the four stages in order and give each its own model type, data and metric: intent detection (classify what the user wants), slot filling (find the spans that carry the arguments), canonicalization (map each span to a system identifier or normalized value), and plan construction (assemble a validated, executable call). The design problem is error propagation: a stage can only be as right as its input, so pass scored alternatives instead of single hard labels, validate every hand-off against a schema, measure each stage twice (on gold input and on real upstream output), and let low-confidence cases become a clarifying question instead of an action.
The four stages
Terms used below. A slot is a named argument of an intent (for a flight booking: origin, destination, date). BIO tagging labels every token as B (begins a slot span), I (inside one) or O (outside), so a sequence tagger can find spans: for "fly from san francisco to nyc on tuesday" a tagger outputs fly/O from/O san/B-origin francisco/I-origin to/O nyc/B-dest on/O tuesday/B-date (the program prints this). Span F1 counts a predicted slot as correct only if both its boundaries and its slot type match the gold span exactly. Canonicalization (also called normalization or entity linking) maps "nyc" to the airport code JFK and "friday" to a concrete date. Calibration means a model's stated confidence matches how often it is right. A pretrained encoder is a neural network already trained on large amounts of text that you then fine-tune on your labels. A reranker is a second model that reorders a short list of candidates produced by a cheaper first step. A constrained sequence-to-sequence decoder is a model that writes its output token by token but is only allowed tokens that keep the output valid under a grammar or schema. Multi-task learning trains one network on several tasks at once. An n-best list is the top few alternatives with their scores instead of only the winner. Hard negatives are examples that look like a class but are not in it (a refund request versus a cancellation). The out-of-scope false-accept rate is the share of requests the system should reject that it accepts as some intent. Cross-validated predictions are predictions for each example made by a model that was trained on the other folds and never saw that example. For a first version the core is: a linear intent model, a rule or tagger for slots, alias dictionaries, and templates for plans; the other options in the table are upgrades for when that baseline's measured errors justify them.
| Stage | Input to output | Model types worth considering | Training data needed | Evaluation metric |
|---|---|---|---|---|
| Intent detection | utterance to one of K intents plus an out-of-scope class | Linear model on TF-IDF n-grams as the baseline; a fine-tuned pretrained encoder as the upgrade | Labelled utterances per intent, hard negatives between neighbouring intents (cancel vs refund), and out-of-scope examples | Accuracy and macro-F1 (macro = average over intents, so rare intents count), the out-of-scope false-accept rate, calibration of the confidence |
| Slot filling | utterance (and the intent) to typed spans | BIO tagger on a pretrained encoder, optionally with a CRF (conditional random field) output layer that scores tag-to-tag transitions, so it learns to avoid illegal sequences such as I without B (decoding can also be constrained to forbid them outright); rules or regular expressions for closed formats | Span-annotated utterances, enough variation in phrasing and in slot values; an annotation guide that settles boundary cases | Span-level exact-match F1 per slot type, plus a looser overlap F1 to see how many errors are only boundary errors |
| Canonicalization | span to canonical value, or NONE | Alias dictionaries and a deterministic date/number grammar first; a retrieval step over the entity catalogue (character n-gram or embedding similarity) with a small reranker for ambiguous names | The catalogue itself, alias lists mined from logs, labelled (span, correct entity) pairs including ambiguous ones, and the reference date/locale for relative expressions | Exact-match accuracy of the canonical value, coverage (fraction not returned as NONE), and accuracy on the covered part |
| Plan construction | intent plus canonical slots to an executable call | Templates keyed by intent when plans are simple; a constrained sequence-to-sequence decoder that can only emit calls valid under the API schema when plans are compositional | Gold plans per utterance, or plan templates plus the API schema | Executable rate (parses and type-checks), exact-match plan accuracy, and execution accuracy (running the plan returns the same result as the gold plan) |
Two design choices cut across the table. First, every hand-off is a typed object, not free text: intent from a closed list, slots validated against that intent's schema, canonical values from the catalogue. That makes illegal states unrepresentable and lets a schema check act as an automatic error detector. Second, the stages run in the order shown only if the information flows that way; slot filling usually benefits from knowing the intent (the schema tells it which slots to look for), and the intent classifier can in turn be re-scored using whether its required slots were found.
Handling error propagation
Errors cascade because a wrong early decision is treated as fact later. The techniques, in the order of how much they usually buy for the engineering cost:
- Measure the propagation first. Report each stage on gold input (an upper bound, with the previous stages' answers injected from the labels) and on real upstream output. The gap between the two numbers is the damage done by the upstream stage. Stage accuracies do not simply multiply, because errors are correlated and some downstream stages are robust to upstream errors, so only the end-to-end run is the real number.
- Pass scores or an n-best list, not a hard label. Keep the top 2 or 3 intents with probabilities and let the later stages rescore them: an intent whose required slots are missing is less likely than one whose slots were all found. The program traces this on the utterance that cascades: the intent scores are a 0.50 / 0.50 tie between
book_flightandcancel_booking; the slot stage then finds origin, destination and date, which are exactly the slotsbook_flightrequires, so that candidate gets a +0.25 bonus (an arbitrary demonstration weight, to be tuned on labelled data) and wins 0.75 to 0.50. Plan accuracy on the 13 utterances becomes 10 of 13, the same as injecting the gold intent. - Validate at each hand-off and fail closed. A slot value that is not in the catalogue, a date in the past for a booking, a plan that violates the API schema: all return NONE or a low score instead of a guess.
- Train downstream stages on realistic upstream output. If the slot filler is trained only on gold intents, it never sees the distribution of wrong intents it receives in production. Use cross-validated predictions of the upstream model as the downstream training input for a share of the examples. The reason to avoid predictions on the upstream model's own training data: the model has memorised those examples, so it looks almost perfect there, and the downstream stage would learn to trust an input that is far cleaner than what it gets in production. The program prints three such rows: each has the utterance, the gold intent and what the upstream stage predicted with its confidence, and the third row is the case where they differ, which is the example the downstream stage must learn to cope with.
- Share representations or train jointly where the data allows. A single encoder with an intent head and a slot head (multi-task learning) lets the two tasks regularize each other. It couples the stages in training and release, which is a cost.
- Route uncertainty to the user. Ask a clarifying question when the intent confidence is low or a required canonical value is NONE. The threshold is a product decision: it trades wrong actions against annoying questions.
- Log stage outputs and run error analysis by stage, so each production failure is attributed to the stage that introduced it.
Worked example
How to read the code: intent() counts keyword hits per intent and returns the winner with its confidence; the key (scores[k], k) breaks a tie by the larger intent name alphabetically, which is why a 2-2 tie between cancel_booking and book_flight goes to cancel_booking. In slots(), the regular expression reads: the word "from", then lazily capture letters and spaces (the origin), then "to", then capture the destination, which ends at " on", the end of the text, " next" or a full stop; the lazy +? takes as few characters as possible so the origin stops at the first " to". canon() looks each span up in the dictionary and gives None if it is missing. run() is the pipeline; passing gold_intent skips the intent stage and uses the label with confidence 1.0, and passing gold_slots replaces the canonical slots with the labels, which is the gold-injection experiment.
The program below is a rule-based stand-in for the learned models (keyword-count intent scoring, a regular expression for slots, a dictionary for canonicalization); a real system would put the models from the table in those places. The 13 hand-written utterances are a toy set chosen to contain realistic failure types, so the printed rates illustrate the measurement method and say nothing about how a real system performs. Intent confidence is the share of keyword hits that went to the winning intent.
import re, json
from collections import Counter
INTENTS = {
"book_flight": ["fly", "flight", "book"],
"cancel_booking": ["cancel", "refund"],
"check_status": ["status", "delayed", "on time"],
}
CITIES = {"nyc": "JFK", "new york": "JFK", "sf": "SFO", "san francisco": "SFO", "boston": "BOS", "bos": "BOS"}
WEEKDAYS = ["monday","tuesday","wednesday","thursday","friday","saturday","sunday"]
def intent(text):
scores = {k: sum(w in text for w in ws) for k, ws in INTENTS.items()}
best = max(scores, key=lambda k: (scores[k], k))
total = sum(scores.values())
conf = scores[best] / total if total else 0.0
return best, conf
def slots(text):
out = {}
m = re.search(r"from ([a-z ]+?) to ([a-z ]+?)(?: on|$| next|\.)", text)
if m:
out["origin"], out["dest"] = m.group(1).strip(), m.group(2).strip()
for d in WEEKDAYS:
if d in text:
out["date"] = d
return out
def canon(sl):
out = {}
for k, v in sl.items():
if k in ("origin", "dest"):
out[k] = CITIES.get(v)
else:
out[k] = WEEKDAYS.index(v) if v in WEEKDAYS else None
return out
def plan(i, c):
if i == "book_flight" and all(c.get(k) is not None for k in ("origin","dest","date")):
return {"call": "search_flights", "args": c}
if i == "cancel_booking":
return {"call": "cancel", "args": {}}
if i == "check_status":
return {"call": "status", "args": {}}
return {"call": "ask_clarification", "args": {}}
DATA = [
("book a flight from nyc to sf on friday", "book_flight", {"origin":"JFK","dest":"SFO","date":4}),
("i want to fly from boston to new york on monday", "book_flight", {"origin":"BOS","dest":"JFK","date":0}),
("book me from sf to bos on sunday", "book_flight", {"origin":"SFO","dest":"BOS","date":6}),
("fly from san francisco to nyc on tuesday", "book_flight", {"origin":"SFO","dest":"JFK","date":1}),
("book a flight from chicago to sf on friday", "book_flight", {"origin":"ORD","dest":"SFO","date":4}),
("cancel my booking and refund me", "cancel_booking", {}),
("please cancel the trip", "cancel_booking", {}),
("is my flight delayed", "check_status", {}),
("what is the status of my booking", "check_status", {}),
("cancel my flight to sf on friday", "cancel_booking", {}),
("cancel the refund request and book a flight from nyc to sf on friday", "book_flight", {"origin":"JFK","dest":"SFO","date":4}),
("book from nyc to sf on monday not friday", "book_flight", {"origin":"JFK","dest":"SFO","date":0}),
("book boston to sf on monday", "book_flight", {"origin":"BOS","dest":"SFO","date":0}),
]
def run(text, gold_intent=None, gold_slots=None):
i, conf = intent(text) if gold_intent is None else (gold_intent, 1.0)
sl = slots(text)
c = canon(sl)
if gold_slots is not None:
c = gold_slots
return i, conf, sl, c, plan(i, c)
n = len(DATA)
gold_plans = [plan(gi, gs) for _, gi, gs in DATA]
intent_ok = sum(intent(t)[0] == gi for t, gi, _ in DATA)
slot_ok = sum(canon(slots(t)) == gs for t, gi, gs in DATA if gi == "book_flight")
nb = sum(gi == "book_flight" for _, gi, _ in DATA)
e2e = sum(run(t)[4] == gp for (t, _, _), gp in zip(DATA, gold_plans))
print(f"intent acc (raw text): {intent_ok}/{n}")
print(f"slot+canon exact match on booking utterances (raw text): {slot_ok}/{nb}")
print(f"plan correct end to end: {e2e}/{n}")
print("--- per-utterance trace of failures ---")
for (t, gi, gs), gp in zip(DATA, gold_plans):
i, conf, sl, c, p = run(t)
if p != gp:
print(f"{t!r}\n intent={i} (conf {conf:.2f}, gold {gi}) slots={sl} canon={c}\n plan={p} gold={gp}")
# error propagation: plan with gold intent but predicted slots, and gold slots but predicted intent
a = sum(run(t, gold_intent=gi)[4] == gp for (t, gi, _), gp in zip(DATA, gold_plans))
b = sum(run(t, gold_slots=gs)[4] == gp for (t, _, gs), gp in zip(DATA, gold_plans))
print(f"plan correct with gold intent injected: {a}/{n}")
print(f"plan correct with gold canonical slots injected: {b}/{n}")
# abstain policy: clarify when intent confidence < 1 or any canonical value is None
def guarded(text):
i, conf, sl, c, p = run(text)
if conf < 1.0 or any(v is None for v in c.values()):
return {"call": "ask_clarification", "args": {}}
return p
wrong_act = sum(1 for (t,_,_), gp in zip(DATA, gold_plans) if run(t)[4] != gp and run(t)[4]["call"] != "ask_clarification")
clar_plain = sum(run(t)[4]["call"] == "ask_clarification" for t,_,_ in DATA)
wrong_act_g = sum(1 for (t,_,_), gp in zip(DATA, gold_plans) if guarded(t) != gp and guarded(t)["call"] != "ask_clarification")
clar_g = sum(guarded(t)["call"] == "ask_clarification" for t,_,_ in DATA)
print(f"wrong actions executed, no guard: {wrong_act}; with guard: {wrong_act_g}; clarifications asked without guard: {clar_plain}, with guard: {clar_g}")
# BIO tags: what a learned slot tagger would output for an utterance (B = begins a slot, I = inside, O = outside).
def bio(text, sl):
toks = text.split()
tags = ["O"] * len(toks)
for name in ("origin", "dest", "date"):
if name in sl:
words = sl[name].split()
for s in range(len(toks) - len(words) + 1):
if toks[s:s + len(words)] == words:
tags[s] = "B-" + name
for j in range(1, len(words)):
tags[s + j] = "I-" + name
break
return list(zip(toks, tags))
print("--- BIO tagging ---")
for t in ("book a flight from nyc to sf on friday", "fly from san francisco to nyc on tuesday"):
print(" ".join(f"{w}/{g}" for w, g in bio(t, slots(t))))
# Training rows for a downstream stage: gold intent versus the upstream model's prediction for the same utterance.
# (A learned upstream model would make these predictions in cross-validation, from a fold that never saw the utterance.)
print("--- downstream training rows (utterance | gold intent | upstream prediction, confidence) ---")
for t, gi, _ in DATA[8:11]:
pi, pc = intent(t)
print(f"{t:68s} | {gi:14s} | {pi}, {pc:.2f}")
# Passing scored alternatives (n-best) to the next stage instead of one hard label.
SCHEMA = {"book_flight": {"origin", "dest", "date"}, "cancel_booking": set(), "check_status": set()}
def intent_nbest(text):
scores = {k: sum(w in text for w in ws) for k, ws in INTENTS.items()}
total = sum(scores.values())
return {k: (v / total if total else 0.0) for k, v in scores.items()}
def rescored(text):
found = set(slots(text))
out = {}
for k, conf in intent_nbest(text).items():
out[k] = conf + (0.25 if SCHEMA[k] and SCHEMA[k] <= found else 0.0) # bonus: its required slots were all found
return out
cascade = DATA[10][0]
print("--- n-best for:", cascade)
print("intent scores :", {k: round(v, 2) for k, v in intent_nbest(cascade).items()})
print("after slot check:", {k: round(v, 2) for k, v in rescored(cascade).items()})
def run_nbest(text):
r = rescored(text)
i = max(r, key=lambda k: (r[k], k))
c = canon(slots(text))
return plan(i, c)
nb_ok = sum(run_nbest(t) == gp for (t, _, _), gp in zip(DATA, gold_plans))
print(f"plan correct with n-best rescoring: {nb_ok}/{n}")
Output:
intent acc (raw text): 12/13
slot+canon exact match on booking utterances (raw text): 5/8
plan correct end to end: 9/13
--- per-utterance trace of failures ---
'book a flight from chicago to sf on friday'
intent=book_flight (conf 1.00, gold book_flight) slots={'origin': 'chicago', 'dest': 'sf', 'date': 'friday'} canon={'origin': None, 'dest': 'SFO', 'date': 4}
plan={'call': 'ask_clarification', 'args': {}} gold={'call': 'search_flights', 'args': {'origin': 'ORD', 'dest': 'SFO', 'date': 4}}
'cancel the refund request and book a flight from nyc to sf on friday'
intent=cancel_booking (conf 0.50, gold book_flight) slots={'origin': 'nyc', 'dest': 'sf', 'date': 'friday'} canon={'origin': 'JFK', 'dest': 'SFO', 'date': 4}
plan={'call': 'cancel', 'args': {}} gold={'call': 'search_flights', 'args': {'origin': 'JFK', 'dest': 'SFO', 'date': 4}}
'book from nyc to sf on monday not friday'
intent=book_flight (conf 1.00, gold book_flight) slots={'origin': 'nyc', 'dest': 'sf', 'date': 'friday'} canon={'origin': 'JFK', 'dest': 'SFO', 'date': 4}
plan={'call': 'search_flights', 'args': {'origin': 'JFK', 'dest': 'SFO', 'date': 4}} gold={'call': 'search_flights', 'args': {'origin': 'JFK', 'dest': 'SFO', 'date': 0}}
'book boston to sf on monday'
intent=book_flight (conf 1.00, gold book_flight) slots={'date': 'monday'} canon={'date': 0}
plan={'call': 'ask_clarification', 'args': {}} gold={'call': 'search_flights', 'args': {'origin': 'BOS', 'dest': 'SFO', 'date': 0}}
plan correct with gold intent injected: 10/13
plan correct with gold canonical slots injected: 12/13
wrong actions executed, no guard: 2; with guard: 1; clarifications asked without guard: 2, with guard: 7
--- BIO tagging ---
book/O a/O flight/O from/O nyc/B-origin to/O sf/B-dest on/O friday/B-date
fly/O from/O san/B-origin francisco/I-origin to/O nyc/B-dest on/O tuesday/B-date
--- downstream training rows (utterance | gold intent | upstream prediction, confidence) ---
what is the status of my booking | check_status | check_status, 0.50
cancel my flight to sf on friday | cancel_booking | cancel_booking, 0.50
cancel the refund request and book a flight from nyc to sf on friday | book_flight | cancel_booking, 0.50
--- n-best for: cancel the refund request and book a flight from nyc to sf on friday
intent scores : {'book_flight': 0.5, 'cancel_booking': 0.5, 'check_status': 0.0}
after slot check: {'book_flight': 0.75, 'cancel_booking': 0.5, 'check_status': 0.0}
plan correct with n-best rescoring: 10/13
Reading the output: intent is right on 12 of 13 utterances, yet the final plan is right on only 9 of 13, because slot extraction and canonicalization fail on three booking utterances (an airport that is missing from the dictionary, a regular expression that needs the word "from", and a correction "monday not friday" that the date logic reads wrongly). Injecting the correct intent lifts plan accuracy from 9 to 10 of 13; injecting the correct canonical slots lifts it from 9 to 12 of 13. So in this toy the slot and canonicalization stages are the bottleneck, and the gold-injection comparison is what shows it. The failure on "cancel the refund request and book a flight..." is the classic cascade: the intent tie goes to the wrong intent with confidence 0.50 and the plan stage executes a cancellation.
The guard in the wrong actions executed line (ask for clarification when intent confidence is below 1.0 or any canonical value is NONE) removes one of the two wrong actions, the cancellation, but asks 7 clarifications instead of 2. It misses "monday not friday", because that parse is confident and well-formed but wrong; only a stage that models the correction, or a read-back to the user ("Friday, correct?"), catches that kind of error. The BIO, training-row and n-best lines at the end of the output cover the points the table describes. This is a minimal illustration of confidence gating, not a production safety mechanism: it uses one crude confidence value, ignores the cost of each action type, and a production system must also handle confirmation for irreversible actions, authorization, and retries.
Trade-offs and pitfalls
- Modular pipeline versus one end-to-end model. The pipeline gives per-stage metrics, can reuse dictionaries and rules, and lets you fix one stage without retraining the rest. An end-to-end sequence-to-sequence parser removes hand-offs (no cascade) but needs more paired (utterance, plan) data, and its failures are harder to localize. With little plan-level data and a fixed set of intents, prefer the pipeline; with plentiful (utterance, plan) pairs and compositional requests, move to a constrained end-to-end decoder, keeping the schema validator at the end.
- Dictionaries and rules are not a weakness for closed-world slots such as airport codes or dates; they are deterministic, testable and auditable. Use learned models where the surface forms are open-ended.
- Evaluating stages only on gold input hides cascade damage; evaluating only end to end hides where to fix. Report both.
- Out-of-scope input is the most common production failure: without an explicit out-of-scope class and a rejection threshold, every utterance gets forced into some intent.
- Distribution shift in the catalogue (new airports, new product names) breaks canonicalization silently; monitor the NONE rate over time.
Running the code
# Python 3.12, standard library only (no install step)
python parse.py
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 41 Natural Language Processing interview questions and detailed answers.
Sign in to ContinueJoin thousands of developers preparing for their dream job.