Smoothed N-Gram Language Model and Order Selection
Hard · Machine Learning · Machine Learning Engineer · Technical Screen
Problem Statement
Build a word-level smoothed n-gram language modeling toolkit in Python capable of tokenizing UTF-8 corpora, estimating conditional token probabilities with out-of-vocabulary handling, evaluating held-out perplexity, generating text under multiple decoding schemes, and choosing the context order n on a validation split.
Use the boundary and unknown markers BOS = "<s>", EOS = "</s>", and UNK = "<unk>", and implement the following functions and class matching starter.py:
-
tokenize(text: str) -> List[str]- Convert
textto lowercase, then extract contiguous runs of word characters (\w+) and individual non-whitespace punctuation symbols ([^\w\s]) in left-to-right order.
- Convert
-
apply_temperature(probs: List[float], temperature: float) -> List[float]- Given a non-empty list of strictly positive probabilities and
temperature > 0, return[p_i^(1 / T) / sum_j p_j^(1 / T)]computed without numerical underflow whentemperatureis small. - Raise
ValueErroriftemperature <= 0,probsis empty, or any entry ofprobsis<= 0.
- Given a non-empty list of strictly positive probabilities and
-
top_k_filter(weights: List[float], k: int) -> List[float]- Return a new list preserving the
klargest entries ofweightsat their original indices and setting all other entries to0.0. Break ties in favor of smaller indices, and raiseValueErrorifk < 1.
- Return a new list preserving the
-
NGramModel(k: float = 1.0, seed: Optional[int] = None)- Raise
ValueErrorifk <= 0. Userandom.Random(seed)as the model's internal random generator. fit(file_path: str, n: int) -> "NGramModel": RaiseValueErrorifn < 1. Readfile_pathas UTF-8, tokenize each line, ignore lines with zero tokens, and treat every remaining line as one sentence padded withn - 1leading"<s>"tokens and one trailing"</s>"token. Define the predictable vocabularyvocab(sorted lexicographically) as every distinct training word plus"</s>"and"<unk>"(excluding"<s>"). Count alln-grams and(n - 1)-token contexts across the padded sentences and returnself.prob(history: Sequence[str], token: str) -> float: Return the add-ksmoothed conditional probability(C(context, target) + k) / (C(context) + k * V)whereV = len(vocab). Formcontextfrom the lastn - 1tokens ofhistory(left-padded with"<s>"whenlen(history) < n - 1, or()whenn == 1), mapping any non-"<s>"token outsidevocab(inhistoryortoken) to"<unk>".distribution(history: Sequence[str]) -> Dict[str, float]: Return{w: self.prob(history, w)}for everywinvocab(summing to1.0).perplexity(file_path: str) -> float: Returnexp(-(1 / N) * sum log P(w_t | context_t))over allNpredicted positions infile_path(every sentence token plus"</s>"per non-empty tokenized line, never scoring"<s>"). RaiseValueErrorifN == 0.generate(start_tokens: List[str], max_len: int, sampling_strategy: str = "multinomial", top_k: int = 10, temperature: float = 1.0) -> List[str]: Start with a copy ofstart_tokensand append up tomax_lengenerated tokens. On each step, exclude"<unk>"from candidate tokens; if"</s>"is selected, stop immediately without appending"</s>". Support"greedy"(highest weight, ties broken by earliest sorted candidate),"multinomial","top_k", and"temperature", raisingValueErrorfor unknown strategies.- Calling
prob,distribution,perplexity, orgeneratebeforefit()must raiseValueError.
- Raise
-
select_n(train_path: str, valid_path: str, candidates: Sequence[int], k: float = 1.0) -> Tuple[int, Dict[int, float]]- Fit
NGramModel(k=k)ontrain_pathfor each candidatenincandidates, computeperplexity(valid_path), and return(best_n, {n: perplexity}). Break ties toward whichever candidate appears earlier incandidates, and raiseValueErrorifcandidatesis empty.
- Fit
Examples
Example 1
Input:
tokenize("Run, dog! Run.")
Training file ("train.txt"):
go fast
go home
Validation file ("valid.txt"):
go fast
Output (with model = NGramModel(k=1.0).fit("train.txt", n=2)):
tokenize("Run, dog! Run.") -> ["run", ",", "dog", "!", "run", "."]
model.prob([], "go") -> 3/7
model.prob(["go"], "fast") -> 2/7
model.prob(["fast"], "</s>") -> 1/3
model.prob(["nowhere"], "go") -> 0.2
model.perplexity("valid.txt") -> 24.5 ** (1 / 3) # approx 2.90436
Walk-through: The vocabulary is ["</s>", "<unk>", "fast", "go", "home"] (V = 5). Padded bigrams give C(("<s>",)) = 2 ("go": 2), C(("go",)) = 2 ("fast": 1, "home": 1), and C(("fast",)) = 1 ("</s>": 1). With k = 1, P("go" | ["<s>"]) = 3/7, P("fast" | ["go"]) = 2/7, P("</s>" | ["fast"]) = 2/6 = 1/3, and unseen "nowhere" maps to "<unk>" with count 0, giving 1/5 = 0.2. Across the 3 predicted tokens of "go fast", the joint probability is (3/7) * (2/7) * (1/3) = 2/49, so perplexity is (49/2)^(1/3) = 24.5^(1/3).
Example 2
Input:
apply_temperature([0.6, 0.2, 0.2], temperature=0.5)
top_k_filter([0.15, 0.35, 0.35, 0.15], k=1)
top_k_filter([0.15, 0.35, 0.35, 0.15], k=2)
Training file: 20 lines of "red blue green"
Output:
apply_temperature([0.6, 0.2, 0.2], 0.5) -> [9/11, 1/11, 1/11]
top_k_filter([0.15, 0.35, 0.35, 0.15], 1) -> [0.0, 0.35, 0.0, 0.0]
top_k_filter([0.15, 0.35, 0.35, 0.15], 2) -> [0.0, 0.35, 0.35, 0.0]
NGramModel(k=0.1).fit(path, 2).generate(["red"], 5, "greedy")
-> ["red", "blue", "green"]
Walk-through: At T = 0.5, probabilities square (1 / 0.5 = 2) to [0.36, 0.04, 0.04], which normalizes to [9/11, 1/11, 1/11]. In top_k_filter, the tied 0.35 entries at indices 1 and 2 break toward index 1 when k = 1. Greedy bigram decoding from ["red"] picks "blue", then "green", then "</s>" (halting early without appending "</s>").
Example 3
Input:
train.txt: 30 lines of "north east south west"
valid.txt: 4 lines of "north east south west"
candidates = [1, 2, 3], k = 0.01
Output:
best_n, scores = select_n("train.txt", "valid.txt", [1, 2, 3], k=0.01)
best_n -> 2 (with scores[2] < scores[1] and scores[2] == scores[3])
Walk-through: In "north east south west", each single word uniquely determines the next word (including "</s>" after "west"), so a bigram (n = 2) achieves the exact same held-out perplexity as a trigram (n = 3) while beating a memoryless unigram (n = 1); tie-breaking selects the earlier candidate 2.
Constraints
n >= 1,k > 0,temperature > 0,top_k >= 1,max_len >= 0, andlen(candidates) >= 1(invalid arguments must raiseValueError).- Input files are valid UTF-8 text; blank or whitespace-only lines must be ignored, while a validation file with zero total tokens must raise
ValueErrorinperplexity. - Probabilities and perplexities must remain free of floating-point underflow even on multi-thousand-token validation files or small temperatures such as
T = 0.01.
Step-by-step walkthrough
Overview of the n-gram language model and design choices
A language model assigns probabilities to sequences of words by predicting one token at a time given everything before it. Because tracking infinitely long histories is impossible with raw counts, an n-gram model makes the
(n - 1)-order Markov assumption — each token depends only on the immediately precedingn - 1tokens:P(w_1, w_2, ..., w_T) ≈ product over t=1..T of P(w_t | w_{t - n + 1}, ..., w_{t - 1})Before writing a single line of code, lock down four modeling conventions so probabilities sum to
1everywhere: 1. Sentence boundaries (<s>and</s>): Each non-empty line is treated as one sentence, padded on the left withn - 1start-of-sentence markers<s>(so the very first word still has a full(n - 1)-token context) and on the right with one end-of-sentence marker</s>(so the model learns where sentences naturally end). 2. Closed vocabulary with<unk>: The predictable vocabularyvocabconsists of every training word plus</s>and<unk>. Any out-of-vocabulary word encountered during evaluation or prompting is mapped to<unk>so its probability mass is properly accounted for. Crucially,<s>is not invocab, because<s>is only given as context — never predicted! 3. Add-k smoothing: Raw relative frequencies assign probability0to any unseen word pair, making held-out perplexity infinite. Addingk > 0pseudo-counts to every vocabulary slot guarantees strictly positive, normalized probabilities, and we discuss stronger back-off / Kneser-Ney smoothing when selectingn. 4. Testable helper API: Alongsidefitandgenerate, exposingprob,distribution,perplexity, andselect_nlets us verify normalization and model selection directly.Consistent tokenization and sentence reading
Training text, validation text, and generation prompts must pass through the exact same tokenizer — otherwise
"Cat,"in training and"cat"at test time look like completely unrelated symbols. Ourtokenizehelper lowercases text and splits it into contiguous word-character runs (\w+) and single punctuation marks ([^\w\s]):"Run, dog! Run." -> ["run", ",", "dog", "!", "run", "."]from typing import List import re BOS = "<s>" EOS = "</s>" UNK = "<unk>" # Matches either a contiguous word (\w+) or a single punctuation symbol ([^\w\s]). _TOKEN_PATTERN = re.compile(r"\w+|[^\w\s]") def tokenize(text: str) -> List[str]: """Lowercase, then split into runs of word characters and single punctuation marks.""" return _TOKEN_PATTERN.findall(text.lower()) def read_sentences(file_path: str) -> List[List[str]]: """Return one token list per non-empty line of a UTF-8 text file.""" sentences: List[List[str]] = [] with open(file_path, encoding="utf-8") as file_handle: for line in file_handle: tokens = tokenize(line) if tokens: sentences.append(tokens) return sentencesSliding-window counting of n-grams and contexts
For each sentence, we pad
[BOS] * (n - 1) + sentence + [EOS]and slide a window of widthnacross every target indexi = n - 1 .. len(padded) - 1. Instead of counting(n - 1)-grams in a separate loop (where off-by-one bugs at sentence endings easily break normalization), we incrementcontext_counts[context]inside the exact same loop asnext_counts[context][token], guaranteeingcontext_counts[context] == sum(next_counts[context].values()):Training file: "go fast\ngo home\n", n = 2 (1 start token <s>, 1 end token </s>) Sentence 1 padded: [ <s>, go, fast, </s> ] window i=1: (<s>,) -> go window i=2: (go,) -> fast window i=3: (fast,) -> </s> Sentence 2 padded: [ <s>, go, home, </s> ] window i=1: (<s>,) -> go window i=2: (go,) -> home window i=3: (home,) -> </s> Resulting tables (vocab = ["</s>", "<unk>", "fast", "go", "home"], V = 5): context next_counts[context] context_counts[context] ("<s>",) {"go": 2} 2 ("go",) {"fast": 1, "home": 1} 2 ("fast",) {"</s>": 1} 1 ("home",) {"</s>": 1} 1When
n = 1(a unigram model),n - 1 = 0, so there are zero<s>tokens and every context is the empty tuple().from typing import Dict, List, Optional, Tuple import random class NGramModel: def __init__(self, k: float = 1.0, seed: Optional[int] = None) -> None: if k <= 0: raise ValueError("k must be > 0") self.k = k self.rng = random.Random(seed) self.n = 0 # vocab: sorted list of predictable tokens (excludes <s>, which is never predicted) self.vocab: List[str] = [] self.vocab_set = set() # next_counts: {context_tuple: {next_token: count}}, e.g. {("a",): {"b": 1, "</s>": 1}} self.next_counts: Dict[Tuple[str, ...], Dict[str, int]] = {} # context_counts: {context_tuple: total_next_tokens}, matching sum of next_counts[context] self.context_counts: Dict[Tuple[str, ...], int] = {} def fit(self, file_path: str, n: int) -> "NGramModel": """Count every n-gram of the file and how often each (n-1)-token context occurs.""" if n < 1: raise ValueError("n must be >= 1") self.n = n sentences = read_sentences(file_path) # Include </s> and <unk> in the output vocabulary, but exclude prefix-only <s>. vocab = {EOS, UNK} for sentence in sentences: for token in sentence: vocab.add(token) self.vocab = sorted(vocab) self.vocab_set = vocab # Slide an n-token window across each padded sentence: (n-1)-token context -> next token. self.next_counts = {} self.context_counts = {} for sentence in sentences: padded = [BOS] * (n - 1) + sentence + [EOS] for i in range(n - 1, len(padded)): context = tuple(padded[i - n + 1:i]) token = padded[i] if context not in self.next_counts: self.next_counts[context] = {} self.context_counts[context] = 0 followers = self.next_counts[context] followers[token] = followers.get(token, 0) + 1 self.context_counts[context] += 1 return selfAdd-k smoothing and out-of-vocabulary handling
Add-k smoothing imagines we saw every token in
self.vocaban extraktimes after every contexth:P(w | h) = (C(h, w) + k) / (C(h) + k * V), where V = len(self.vocab)Summing the numerator across all
Vtokens inself.vocabgivessum_w C(h, w) + k * V = C(h) + k * V, so the conditional probabilities always add up to1.0— even for an unseen context (C(h) = 0, where every token gets1 / V). Using Example 1's"go fast\ngo home\n"bigram counts (V = 5,k = 1): -P("go" | []) = P("go" | ["<s>"]) = (2 + 1) / (2 + 5) = 3/7-P("fast" | ["go"]) = (1 + 1) / (2 + 5) = 2/7-P("go" | ["nowhere"]) = (0 + 1) / (0 + 5) = 1/5 = 0.2("nowhere"maps to"<unk>", an unseen context)Watch out for one subtle Python slicing trap in
_context_of: whenn == 1,width = 0, and in Pythonhistory[-0:]equalshistory[0:](the entire list rather than an empty slice!), so we return()early whenwidth == 0.from typing import Dict, Sequence, Tuple class NGramModel: def _require_fitted(self) -> None: """Raise ValueError if fit() has not been called yet.""" if self.n < 1: raise ValueError("call fit() before using the model") def _context_of(self, history: Sequence[str]) -> Tuple[str, ...]: """Return the last n-1 tokens of history, left-padded with <s> and OOV mapped to <unk>.""" self._require_fitted() width = self.n - 1 # Guard width == 0 explicitly because in Python history[-0:] returns the whole list! if width == 0: return () padded_history = [BOS] * width + list(history[-width:]) recent_slice = padded_history[-width:] context = [] for token in recent_slice: if token != BOS and token not in self.vocab_set: token = UNK context.append(token) return tuple(context) def prob(self, history: Sequence[str], token: str) -> float: """Return add-k smoothed P(token | history) = (C(context, token) + k) / (C(context) + k * V).""" self._require_fitted() if token not in self.vocab_set: token = UNK context = self._context_of(history) followers = self.next_counts.get(context, {}) observed_count = followers.get(token, 0) context_total = self.context_counts.get(context, 0) vocab_size = len(self.vocab) return (observed_count + self.k) / (context_total + self.k * vocab_size) def distribution(self, history: Sequence[str]) -> Dict[str, float]: """Return P(token | history) for every token in self.vocab; probabilities sum to 1.""" self._require_fitted() result = {} for token in self.vocab: result[token] = self.prob(history, token) return resultEvaluating held-out text with perplexity
Perplexity measures how surprised the model is on a test file: it is the exponential of the average negative log-probability per predicted token (
PP = exp(-(1 / N) * sum_t log P(w_t | h_t))), which equals the inverse geometric mean probability(prod_t P_t)^(-1 / N). Intuitively, a perplexity of10means the model is as uncertain at each step as rolling a fair 10-sided die — lower is better.Two implementation rules are essential: 1. Sum logs instead of multiplying raw probabilities: Multiplying even a few hundred probabilities around
0.05underflows 64-bit floats straight to0.0. 2. Score</s>at the end of every sentence, never<s>: Knowing when a sentence ends is a real prediction, whereas then - 1leading<s>tokens are given as conditioning context.Worked trace on Example 1's validation line
"go fast\n"(3predicted positions:"go","fast","</s>"):P("go" | ["<s>"]) = 3/7, P("fast" | ["go"]) = 2/7, P("</s>" | ["fast"]) = (1 + 1) / (1 + 5) = 1/3 Product = (3/7) * (2/7) * (1/3) = 2/49 PP = (2/49)^(-1/3) = (49/2)^(1/3) = 24.5^(1/3) ≈ 2.904import math class NGramModel: def perplexity(self, file_path: str) -> float: """Return exp(-(1/N) * sum log P(token | context)) over all words plus </s> per sentence.""" self._require_fitted() # Accumulate log-probabilities rather than multiplying raw probabilities to avoid underflow. log_prob_sum = 0.0 predicted_count = 0 for sentence in read_sentences(file_path): padded = [BOS] * (self.n - 1) + sentence + [EOS] for i in range(self.n - 1, len(padded)): history_slice = padded[i - self.n + 1:i] target_token = padded[i] log_prob_sum += math.log(self.prob(history_slice, target_token)) predicted_count += 1 if predicted_count == 0: raise ValueError("no tokens to evaluate") return math.exp(-log_prob_sum / predicted_count)Sampling strategies: greedy, multinomial, top-k, and temperature
To generate text, we start from
list(start_tokens)and sample up tomax_lennew tokens one by one. At each step we drop<unk>from the candidate pool (so generated text never emits literal"<unk>"placeholders) and stop immediately without appending if</s>is drawn.The four decoding strategies trade off predictability vs diversity: -
greedy: Always picks the highest-probability token (argmax). Deterministic, though prone to repetitive loops on real corpora. -multinomial: Draws proportionally to the full smoothed distributionP(w | h). Under add-k smoothing, thousands of unseen words each keepk / (C(h) + k * V)weight, occasionally injecting random unrelated words. -top_k: Zeroes out everything except thekhighest-weight tokens (ties go to earlier sorted tokens) before sampling, trimming away the noisy add-k tail. -temperature: Rescales probabilities top_i^(1 / T) / sum_j p_j^(1 / T).T < 1sharpens peaks (e.g.[0.6, 0.2, 0.2]atT = 0.5squares to[0.36, 0.04, 0.04] -> [9/11, 1/11, 1/11]), whileT > 1flattens toward uniform. Computings_i = (log p_i) / Tand subtractingmax(s)beforeexpprevents underflow to all zeros whenTis tiny (e.g.T = 0.01).from typing import List, Tuple import math def apply_temperature(probs: List[float], temperature: float) -> List[float]: """Return p_i^(1/T) / sum_j p_j^(1/T) for strictly positive probabilities.""" if temperature <= 0: raise ValueError("temperature must be > 0") if not probs: raise ValueError("probs must be non-empty") # Compute (log p_i) / T and subtract max_log before exp() so small T never underflows to 0. scaled_logs: List[float] = [] for prob in probs: if prob <= 0: raise ValueError("probabilities must be strictly positive") scaled_logs.append(math.log(prob) / temperature) max_log = max(scaled_logs) weights: List[float] = [] for log_val in scaled_logs: weights.append(math.exp(log_val - max_log)) total_weight = sum(weights) normalized: List[float] = [] for weight in weights: normalized.append(weight / total_weight) return normalized def top_k_filter(weights: List[float], k: int) -> List[float]: """Keep the k largest weights and set the rest to 0 (ties go to the lower index).""" if k < 1: raise ValueError("k must be >= 1") # Sort (-weight, index) so larger weights come first and ties break toward smaller indices. ranked: List[Tuple[float, int]] = [] for i in range(len(weights)): ranked.append((-weights[i], i)) ranked.sort() kept = [0.0] * len(weights) for _, index in ranked[:k]: kept[index] = weights[index] return keptSelecting optimal n, better smoothing, and memory scaling
Choosing
nis a classic bias-variance trade-off: - Smalln(n = 1, 2): High bias (short memory —"the dog barked at the ..."forgets"dog"under a bigram), but low variance because short contexts occur frequently. - Largen(n >= 4): Low bias, but explosive sparsity —V^(n - 1)possible contexts grows exponentially. WithV = 10,000, there are10^8possible 2-word contexts (n = 3) and10^12possible 3-word contexts (n = 4), so on a 10-million-token corpus at least90%+of trigram contexts never appear in training!Validation procedure to pick
n: 1. Split documents (or time periods, not random shuffled sentences from the same document, which leak recurring phrases) into train / validation / test (e.g.80% / 10% / 10%), fixing the vocabulary on train so perplexities are directly comparable. 2. Tune(n, smoothing_hyperparameter)on validation perplexity, preferring the smallernwhen ties occur (scores[n] < scores[best_n]). On deterministic text ("north east south west"repeated),n = 2dramatically beatsn = 1and tiesn = 3, pickingn = 2; on independent random tokens,n = 1wins because longer contexts only add estimation noise.Why smoothing interacts with
n: Add-k breaks down on large vocabularies — ifV = 10,000and a context appeared10times across3followers,k = 1hands9,997 / 10,010 ≈ 99.87%of the probability mass to unseen words (and evenk = 0.01hands them99.97 / 110 ≈ 90.9%), forcing unseen contexts back to a blind1 / Vguess instead of using shorter suffixes. Production n-gram models combine orders via linear interpolation or interpolated Kneser-Ney:Linear interpolation (trigram, weights lambda_1 + lambda_2 + lambda_3 = 1): P(w | u, v) = lambda_3 * P_ML(w | u, v) + lambda_2 * P_ML(w | v) + lambda_1 * P_ML(w) Interpolated Kneser-Ney (bigram, absolute discount d ≈ 0.75): P(w | v) = max(C(v, w) - d, 0) / C(v) + lambda(v) * P_cont(w) lambda(v) = (d / C(v)) * (# distinct words seen after v) P_cont(w) = (# distinct left-neighbors seen before w) / (total distinct bigram types)Concrete Kneser-Ney intuition: suppose
"francisco"and"glasses"both appear40times in a corpus with1,000distinct bigrams, where"francisco"only follows"san"(1distinct left-neighbor) while"glasses"follows40different words. After"reading"(where neither bigram appeared in training), unigram back-off treats both equally, whereas Kneser-Ney givesP_cont("glasses") = 40 / 1000vsP_cont("francisco") = 1 / 1000—40xhigher probability for"glasses"!Complexity and memory footprint across
n: ForNtraining positions andVvocabulary words,fittakesO(N * n)time and stores at mostmin(N, V^n)distinct n-grams plus one hash table per distinct(n - 1)-context. On a220,000-token synthetic Zipf corpus (V = 5,000) in Python dictionaries,n = 1uses~1 MB(1context),n = 2uses~9 MB(~5kcontexts),n = 3jumps to~45 MB(~105kcontexts), andn = 5reaches~76 MB(~177ksingle-entry context dicts). Production systems (like KenLM) map tokens to 32-bit integer IDs, prune singleton high-order n-grams, and pack counts into flat sorted arrays or tries to cut memory10x–20x.Complete solution
from typing import Dict, List, Optional, Sequence, Tuple import math import random import re BOS = "<s>" EOS = "</s>" UNK = "<unk>" # Matches either a contiguous word (\w+) or a single punctuation symbol ([^\w\s]). _TOKEN_PATTERN = re.compile(r"\w+|[^\w\s]") def tokenize(text: str) -> List[str]: """Lowercase, then split into runs of word characters and single punctuation marks.""" return _TOKEN_PATTERN.findall(text.lower()) def read_sentences(file_path: str) -> List[List[str]]: """Return one token list per non-empty line of a UTF-8 text file.""" sentences: List[List[str]] = [] with open(file_path, encoding="utf-8") as file_handle: for line in file_handle: tokens = tokenize(line) if tokens: sentences.append(tokens) return sentences def apply_temperature(probs: List[float], temperature: float) -> List[float]: """Return p_i^(1/T) / sum_j p_j^(1/T) for strictly positive probabilities.""" if temperature <= 0: raise ValueError("temperature must be > 0") if not probs: raise ValueError("probs must be non-empty") # Compute (log p_i) / T and subtract max_log before exp() so small T never underflows to 0. scaled_logs: List[float] = [] for prob in probs: if prob <= 0: raise ValueError("probabilities must be strictly positive") scaled_logs.append(math.log(prob) / temperature) max_log = max(scaled_logs) weights: List[float] = [] for log_val in scaled_logs: weights.append(math.exp(log_val - max_log)) total_weight = sum(weights) normalized: List[float] = [] for weight in weights: normalized.append(weight / total_weight) return normalized def top_k_filter(weights: List[float], k: int) -> List[float]: """Keep the k largest weights and set the rest to 0 (ties go to the lower index).""" if k < 1: raise ValueError("k must be >= 1") # Sort (-weight, index) so larger weights come first and ties break toward smaller indices. ranked: List[Tuple[float, int]] = [] for i in range(len(weights)): ranked.append((-weights[i], i)) ranked.sort() kept = [0.0] * len(weights) for _, index in ranked[:k]: kept[index] = weights[index] return kept class NGramModel: """Word n-gram language model with add-k smoothing. Each non-empty line of the training file is one sentence. A sentence is padded with n - 1 copies of <s> on the left and one </s> on the right. The vocabulary is every training token plus </s> and <unk>; unknown words are mapped to <unk>. """ def __init__(self, k: float = 1.0, seed: Optional[int] = None) -> None: if k <= 0: raise ValueError("k must be > 0") self.k = k self.rng = random.Random(seed) self.n = 0 # vocab: sorted list of predictable tokens (excludes <s>, which is never predicted) self.vocab: List[str] = [] self.vocab_set = set() # next_counts: {context_tuple: {next_token: count}}, e.g. {("a",): {"b": 1, "</s>": 1}} self.next_counts: Dict[Tuple[str, ...], Dict[str, int]] = {} # context_counts: {context_tuple: total_next_tokens}, matching sum of next_counts[context] self.context_counts: Dict[Tuple[str, ...], int] = {} def fit(self, file_path: str, n: int) -> "NGramModel": """Count every n-gram of the file and how often each (n-1)-token context occurs.""" if n < 1: raise ValueError("n must be >= 1") self.n = n sentences = read_sentences(file_path) # Include </s> and <unk> in the output vocabulary, but exclude prefix-only <s>. vocab = {EOS, UNK} for sentence in sentences: for token in sentence: vocab.add(token) self.vocab = sorted(vocab) self.vocab_set = vocab # Slide an n-token window across each padded sentence: (n-1)-token context -> next token. self.next_counts = {} self.context_counts = {} for sentence in sentences: padded = [BOS] * (n - 1) + sentence + [EOS] for i in range(n - 1, len(padded)): context = tuple(padded[i - n + 1:i]) token = padded[i] if context not in self.next_counts: self.next_counts[context] = {} self.context_counts[context] = 0 followers = self.next_counts[context] followers[token] = followers.get(token, 0) + 1 self.context_counts[context] += 1 return self def _require_fitted(self) -> None: """Raise ValueError if fit() has not been called yet.""" if self.n < 1: raise ValueError("call fit() before using the model") def _context_of(self, history: Sequence[str]) -> Tuple[str, ...]: """Return the last n-1 tokens of history, left-padded with <s> and OOV mapped to <unk>.""" self._require_fitted() width = self.n - 1 # Guard width == 0 explicitly because in Python history[-0:] returns the whole list! if width == 0: return () padded_history = [BOS] * width + list(history[-width:]) recent_slice = padded_history[-width:] context: List[str] = [] for token in recent_slice: if token != BOS and token not in self.vocab_set: token = UNK context.append(token) return tuple(context) def prob(self, history: Sequence[str], token: str) -> float: """Return add-k smoothed P(token | history) = (C(context, token) + k) / (C(context) + k * V).""" self._require_fitted() if token not in self.vocab_set: token = UNK context = self._context_of(history) followers = self.next_counts.get(context, {}) observed_count = followers.get(token, 0) context_total = self.context_counts.get(context, 0) vocab_size = len(self.vocab) return (observed_count + self.k) / (context_total + self.k * vocab_size) def distribution(self, history: Sequence[str]) -> Dict[str, float]: """Return P(token | history) for every token in self.vocab; probabilities sum to 1.""" self._require_fitted() result: Dict[str, float] = {} for token in self.vocab: result[token] = self.prob(history, token) return result def perplexity(self, file_path: str) -> float: """Return exp(-(1/N) * sum log P(token | context)) over all words plus </s> per sentence.""" self._require_fitted() # Accumulate log-probabilities rather than multiplying raw probabilities to avoid underflow. log_prob_sum = 0.0 predicted_count = 0 for sentence in read_sentences(file_path): padded = [BOS] * (self.n - 1) + sentence + [EOS] for i in range(self.n - 1, len(padded)): history_slice = padded[i - self.n + 1:i] target_token = padded[i] log_prob_sum += math.log(self.prob(history_slice, target_token)) predicted_count += 1 if predicted_count == 0: raise ValueError("no tokens to evaluate") return math.exp(-log_prob_sum / predicted_count) def generate(self, start_tokens: List[str], max_len: int, sampling_strategy: str = "multinomial", top_k: int = 10, temperature: float = 1.0) -> List[str]: """Return start_tokens followed by up to max_len generated tokens (stopping at </s>).""" self._require_fitted() tokens = list(start_tokens) for _ in range(max_len): dist = self.distribution(tokens) # Exclude <unk> from candidates so generated text only contains real words or </s>. candidates: List[str] = [] weights: List[float] = [] for token in self.vocab: if token != UNK: candidates.append(token) weights.append(dist[token]) next_token = self._pick(candidates, weights, sampling_strategy, top_k, temperature) # Stop early when end-of-sentence </s> is sampled, without appending </s>. if next_token == EOS: break tokens.append(next_token) return tokens def _pick(self, candidates: List[str], weights: List[float], strategy: str, top_k: int, temperature: float) -> str: """Select one candidate token using greedy, multinomial, top_k, or temperature sampling.""" if strategy == "greedy": best_index = 0 for i in range(1, len(weights)): if weights[i] > weights[best_index]: best_index = i return candidates[best_index] if strategy == "top_k": weights = top_k_filter(weights, top_k) elif strategy == "temperature": weights = apply_temperature(weights, temperature) elif strategy != "multinomial": raise ValueError("unknown sampling strategy: " + strategy) return self.rng.choices(candidates, weights=weights, k=1)[0] def select_n(train_path: str, valid_path: str, candidates: Sequence[int], k: float = 1.0) -> Tuple[int, Dict[int, float]]: """Fit one model per candidate n and return (best_n, {n: validation_perplexity}).""" if not candidates: raise ValueError("candidates must be non-empty") scores: Dict[int, float] = {} best_n: Optional[int] = None for n in candidates: model = NGramModel(k=k).fit(train_path, n) scores[n] = model.perplexity(valid_path) # Strict '<' breaks ties in favor of earlier candidates (list smaller n first). if best_n is None or scores[n] < scores[best_n]: best_n = n assert best_n is not None return best_n, scores✅ Submit now — all tests should pass.
Intuition & how it works
Think of an n-gram (a contiguous sequence of n tokens) language model as autocomplete powered by a phrasebook: under the Markov assumption (the simplifying rule that the next word depends only on the last n - 1 words rather than the entire document), we scan a training file after tokenization (splitting raw text into normalized words and punctuation symbols) and count how often every word followed every (n - 1)-word prefix. To avoid assigning probability zero to brand-new word combinations, add-k smoothing (also called Laplace smoothing when k = 1, adding k virtual counts to every vocabulary item) gives unseen continuations a small positive floor, while an out-of-vocabulary (<unk>) token reserves probability mass for words never seen during training.
Why naive counting and naive model selection fail: Unsmoothed relative frequencies C(h, w) / C(h) give 0 probability the first time a test sentence uses an unfamiliar phrase, multiplying the sentence probability by zero and sending perplexity (the exponential of average negative log-probability per token, representing the effective branching factor of the model's uncertainty) to infinity. Similarly, picking n on the training set fails completely because larger n memorizes exact training lines — driving training perplexity toward 1 while collapsing into near-random guesses on held-out text whenever (n - 1)-word contexts do not repeat.
Walk through a tiny concrete example on Example 1's two-line training corpus "go fast" and "go home" with n = 2 and k = 1:
- Padding and vocabulary: Sentences become <s> go fast </s> and <s> go home </s>; predictable vocab = {"</s>", "<unk>", "fast", "go", "home"} (V = 5, excluding <s>).
- Counts and smoothed probabilities: Context ("<s>",) occurs 2 times ("go": 2), giving P("go" | ["<s>"]) = (2 + 1) / (2 + 5) = 3/7. Context ("go",) occurs 2 times ("fast": 1, "home": 1), giving P("fast" | ["go"]) = (1 + 1) / (2 + 5) = 2/7. Context ("fast",) occurs 1 time ("</s>": 1), giving P("</s>" | ["fast"]) = (1 + 1) / (1 + 5) = 1/3.
- Perplexity on "go fast": Across the 3 predicted tokens ("go", "fast", "</s>"), the joint probability is (3/7) * (2/7) * (1/3) = 2/49, so perplexity is (2/49)^(-1/3) = 24.5^(1/3) ≈ 2.904.
Complexity
Let N be the number of predicted token positions in the training file (word tokens plus one </s> per non-empty line), V the vocabulary size, D_n the number of distinct observed n-grams (D_n <= min(N, V^n)), and H the number of distinct observed (n - 1)-token contexts (H <= min(N, V^(n - 1))):
fit— O(N * n + V log V) time, O(D_n + H * n) space: We scan allNsliding-window positions once, slicing and hashing an(n - 1)-token tuple in O(n) work per position, plus O(V log V) to sort the vocabulary once. Memory stores one integer count per distinct n-gram (D_n) plus one(n - 1)-tuple key and inner dictionary per distinct context (H * n).prob— O(n) average time: Building and hashing the(n - 1)-token context tuple takes O(n) time, followed by two O(1) dictionary lookups.generate— O(max_len * (V * n + V log V)) time: At each of themax_lensteps,distributionevaluates allVvocabulary tokens in O(V * n) time (and top-k sampling — keeping only thekhighest-weight candidates before sampling — sorts theVweights in O(V log V) time).perplexityandselect_n— O(N_valid * n) per candidate: Evaluating held-out perplexity touches each validation token once with an O(n) probability lookup;select_nruns onefitand oneperplexitycall per candidaten.
Edge cases
- Unigram model (
n = 1): Context width is0. In Python,history[-0:]evaluates tohistory[0:](the whole list!) instead of[], so_context_ofexplicitly returns()whenwidth == 0. - Short prompts (
len(start_tokens) < n - 1): Left-padding with<s>aligns short or empty prompts ([]) with sentence-initial contexts seen during training. - Unseen words and unseen contexts: Unknown tokens in either
historyortokenmap to<unk>. If an entire(n - 1)-token context never occurred in training (C(h) = 0), add-k smoothing gracefully returns the uniform distribution1 / Vsumming to1.0. - Empty files and zero-length generation: An empty training file still has
vocab = {"</s>", "<unk>"}(V = 2), sogenerateexcludes<unk>, immediately draws</s>, and returnsstart_tokensunchanged. An empty validation file has0predicted tokens and raisesValueErrorinperplexity.max_len = 0returns a copy ofstart_tokens. - Small temperatures in
apply_temperature: Temperature scaling raises probabilities to1 / Tand renormalizes; computingp_i^(1 / T)directly whenT = 0.01underflows every float to0.0, whereas shifting(log p_i) / Tby subtractingmax_logbeforeexpkeeps the largest weight equal to1.0and never underflows.
Common mistakes
- Including
<s>insideself.vocab: Because<s>is never predicted as a next token, including it inVstealsk / (C(h) + k * V)probability mass away from real tokens on every step. - Counting
(n - 1)-grams separately fromn-grams: If sentence-end tokens are handled slightly differently between the two loops,C(h)no longer equalssum_w C(h, w), anddistribution(h)stops summing to1.0. - Forgetting
</s>or scoring<s>during perplexity: Omitting</s>lets models assign zero probability to finite sentences without penalty, while scoring<s>pads the denominator with free deterministic tokens. - Multiplying raw probabilities instead of summing
math.log(prob): A 500-word paragraph easily has joint probability around10^(-800), underflowing IEEE-754float64(min ≈ 5e-324) to0.0. - Selecting
non training perplexity or random line splits: Training perplexity decreases monotonically withnas the model memorizes sentences, and random line splits leak document-specific names across train and validation. - Comparing perplexities across different vocabularies or tokenizers: Mapping more rare words to
<unk>shrinksVand artificially lowers perplexity without improving real predictions.
Alternative approaches
- Linear interpolation and Katz back-off: Blending maximum-likelihood estimates across orders
1 .. n(sum_m lambda_m P_ML(w | h_{m-1})) ensures an unseen trigram falls back smoothly to a bigram and unigram rather than jumping straight to uniform1 / V. - Interpolated Kneser–Ney smoothing: Kneser–Ney smoothing subtracts a fixed discount
d(around0.75) from observed counts and distributes the leftover weight proportionally to each word's continuation count (how many distinct left-contexts precedew), preventing words like"francisco"(frequent only after"san") from dominating unseen contexts. - Compact integer tries and hash tables: Instead of nested Python
dicts of strings, C++/Rust toolkits like KenLM map words to integer IDs and pack counts into a trie (a prefix tree sharing common context prefixes across n-grams) or linear-probing array, shrinking RAM by an order of magnitude.
Follow-up questions
- How can multinomial next-token sampling in generate() be accelerated so each step runs in time proportional to seen continuations rather than the full vocabulary size? Notice that add-k probability
(C(h, w) + k) / (C(h) + k * V)is an exact two-component mixture: with probabilityC(h) / (C(h) + k * V), samplewproportionally to observed countsC(h, w)among seen followers only; otherwise (with probabilityk * V / (C(h) + k * V)), pick a uniformly random index from0 .. V - 1(rejecting and redrawing<unk>). That avoids iterating over allVwords on every generated step for multinomial sampling! - What architecture and data structures would you use to count and serve high-order n-grams when the training corpus is hundreds of gigabytes and exceeds single-machine memory? First stream the corpus once to build the integer word-ID vocabulary (replacing rare tail words below a count cutoff with
<unk>). Next, use an external-memory sort or distributed MapReduce/Spark shuffle emitting(ngram_int_tuple, 1)records and summing counts per key, pruning high-order (n >= 3) n-grams seen only once (count == 1), which often cuts table size by60%–80%with minimal perplexity loss. For massive web scale where exact normalization is unnecessary, "Stupid Backoff" stores raw counts and multiplies by0.4each time it backs off to a shorter suffix. - Why is raw per-token perplexity invalid for comparing a word-level n-gram model against a subword Transformer, and what metric makes the comparison fair? Word-level and subword models segment the exact same validation document into different token counts
N_word != N_subword, making per-token perplexity apples-to-oranges. Instead, sum the total negative log-likelihoodL = -sum_t log_2 P(token_t | context_t)over the exact same raw validation text (ensuring no<unk>cheating; open-vocabulary models must spell out rare words) and divideLby the number of UTF-8 bytes or characters to compare bits per byte (BPB) or bits per character (BPC).
Follow-up questions
- How can multinomial next-token sampling in generate() be accelerated so each step runs in time proportional to seen continuations rather than the full vocabulary size?
- What architecture and data structures would you use to count and serve high-order n-grams when the training corpus is hundreds of gigabytes and exceeds single-machine memory?
- Why is raw per-token perplexity invalid for comparing a word-level n-gram model against a subword Transformer, and what metric makes the comparison fair?
Similar questions
- Multimodal Video Retrieval and Ranking at Billion-Clip Scale
- Low-Latency Tree Ensemble Inference
- Select Score Cutoff for Target Precision
- Payment Fraud Detection Under Class Imbalance and Drift
- Diagnosing and Fixing Overfitting in Supervised Learning
- Correlation Bounds, Equicorrelated Variables, and Box-Muller Sampling