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:

  1. tokenize(text: str) -> List[str]

    • Convert text to lowercase, then extract contiguous runs of word characters (\w+) and individual non-whitespace punctuation symbols ([^\w\s]) in left-to-right order.
  2. 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 when temperature is small.
    • Raise ValueError if temperature <= 0, probs is empty, or any entry of probs is <= 0.
  3. top_k_filter(weights: List[float], k: int) -> List[float]

    • Return a new list preserving the k largest entries of weights at their original indices and setting all other entries to 0.0. Break ties in favor of smaller indices, and raise ValueError if k < 1.
  4. NGramModel(k: float = 1.0, seed: Optional[int] = None)

    • Raise ValueError if k <= 0. Use random.Random(seed) as the model's internal random generator.
    • fit(file_path: str, n: int) -> "NGramModel": Raise ValueError if n < 1. Read file_path as UTF-8, tokenize each line, ignore lines with zero tokens, and treat every remaining line as one sentence padded with n - 1 leading "<s>" tokens and one trailing "</s>" token. Define the predictable vocabulary vocab (sorted lexicographically) as every distinct training word plus "</s>" and "<unk>" (excluding "<s>"). Count all n-grams and (n - 1)-token contexts across the padded sentences and return self.
    • prob(history: Sequence[str], token: str) -> float: Return the add-k smoothed conditional probability (C(context, target) + k) / (C(context) + k * V) where V = len(vocab). Form context from the last n - 1 tokens of history (left-padded with "<s>" when len(history) < n - 1, or () when n == 1), mapping any non-"<s>" token outside vocab (in history or token) to "<unk>".
    • distribution(history: Sequence[str]) -> Dict[str, float]: Return {w: self.prob(history, w)} for every w in vocab (summing to 1.0).
    • perplexity(file_path: str) -> float: Return exp(-(1 / N) * sum log P(w_t | context_t)) over all N predicted positions in file_path (every sentence token plus "</s>" per non-empty tokenized line, never scoring "<s>"). Raise ValueError if N == 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 of start_tokens and append up to max_len generated 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", raising ValueError for unknown strategies.
    • Calling prob, distribution, perplexity, or generate before fit() must raise ValueError.
  5. select_n(train_path: str, valid_path: str, candidates: Sequence[int], k: float = 1.0) -> Tuple[int, Dict[int, float]]

    • Fit NGramModel(k=k) on train_path for each candidate n in candidates, compute perplexity(valid_path), and return (best_n, {n: perplexity}). Break ties toward whichever candidate appears earlier in candidates, and raise ValueError if candidates is empty.

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, and len(candidates) >= 1 (invalid arguments must raise ValueError).
  • 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 ValueError in perplexity.
  • 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

  1. 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 preceding n - 1 tokens:

    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 1 everywhere: 1. Sentence boundaries (<s> and </s>): Each non-empty line is treated as one sentence, padded on the left with n - 1 start-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 vocabulary vocab consists 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 in vocab, because <s> is only given as context — never predicted! 3. Add-k smoothing: Raw relative frequencies assign probability 0 to any unseen word pair, making held-out perplexity infinite. Adding k > 0 pseudo-counts to every vocabulary slot guarantees strictly positive, normalized probabilities, and we discuss stronger back-off / Kneser-Ney smoothing when selecting n. 4. Testable helper API: Alongside fit and generate, exposing prob, distribution, perplexity, and select_n lets us verify normalization and model selection directly.

  2. 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. Our tokenize helper 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 sentences
    
  3. Sliding-window counting of n-grams and contexts

    For each sentence, we pad [BOS] * (n - 1) + sentence + [EOS] and slide a window of width n across every target index i = 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 increment context_counts[context] inside the exact same loop as next_counts[context][token], guaranteeing context_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}                  1
    

    When 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 self
    
  4. Add-k smoothing and out-of-vocabulary handling

    Add-k smoothing imagines we saw every token in self.vocab an extra k times after every context h:

    P(w | h) = (C(h, w) + k) / (C(h) + k * V),    where V = len(self.vocab)
    

    Summing the numerator across all V tokens in self.vocab gives sum_w C(h, w) + k * V = C(h) + k * V, so the conditional probabilities always add up to 1.0 — even for an unseen context (C(h) = 0, where every token gets 1 / 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: when n == 1, width = 0, and in Python history[-0:] equals history[0:] (the entire list rather than an empty slice!), so we return () early when width == 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 result
    
  5. Evaluating 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 of 10 means 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.05 underflows 64-bit floats straight to 0.0. 2. Score </s> at the end of every sentence, never <s>: Knowing when a sentence ends is a real prediction, whereas the n - 1 leading <s> tokens are given as conditioning context.

    Worked trace on Example 1's validation line "go fast\n" (3 predicted 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.904
    
    import 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)
    
  6. Sampling strategies: greedy, multinomial, top-k, and temperature

    To generate text, we start from list(start_tokens) and sample up to max_len new 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 distribution P(w | h). Under add-k smoothing, thousands of unseen words each keep k / (C(h) + k * V) weight, occasionally injecting random unrelated words. - top_k: Zeroes out everything except the k highest-weight tokens (ties go to earlier sorted tokens) before sampling, trimming away the noisy add-k tail. - temperature: Rescales probabilities to p_i^(1 / T) / sum_j p_j^(1 / T). T < 1 sharpens peaks (e.g. [0.6, 0.2, 0.2] at T = 0.5 squares to [0.36, 0.04, 0.04] -> [9/11, 1/11, 1/11]), while T > 1 flattens toward uniform. Computing s_i = (log p_i) / T and subtracting max(s) before exp prevents underflow to all zeros when T is 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 kept
    
  7. Selecting optimal n, better smoothing, and memory scaling

    Choosing n is a classic bias-variance trade-off: - Small n (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. - Large n (n >= 4): Low bias, but explosive sparsity — V^(n - 1) possible contexts grows exponentially. With V = 10,000, there are 10^8 possible 2-word contexts (n = 3) and 10^12 possible 3-word contexts (n = 4), so on a 10-million-token corpus at least 90%+ 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 smaller n when ties occur (scores[n] < scores[best_n]). On deterministic text ("north east south west" repeated), n = 2 dramatically beats n = 1 and ties n = 3, picking n = 2; on independent random tokens, n = 1 wins because longer contexts only add estimation noise.

    Why smoothing interacts with n: Add-k breaks down on large vocabularies — if V = 10,000 and a context appeared 10 times across 3 followers, k = 1 hands 9,997 / 10,010 ≈ 99.87% of the probability mass to unseen words (and even k = 0.01 hands them 99.97 / 110 ≈ 90.9%), forcing unseen contexts back to a blind 1 / V guess 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 appear 40 times in a corpus with 1,000 distinct bigrams, where "francisco" only follows "san" (1 distinct left-neighbor) while "glasses" follows 40 different words. After "reading" (where neither bigram appeared in training), unigram back-off treats both equally, whereas Kneser-Ney gives P_cont("glasses") = 40 / 1000 vs P_cont("francisco") = 1 / 1000 — 40x higher probability for "glasses"!

    Complexity and memory footprint across n: For N training positions and V vocabulary words, fit takes O(N * n) time and stores at most min(N, V^n) distinct n-grams plus one hash table per distinct (n - 1)-context. On a 220,000-token synthetic Zipf corpus (V = 5,000) in Python dictionaries, n = 1 uses ~1 MB (1 context), n = 2 uses ~9 MB (~5k contexts), n = 3 jumps to ~45 MB (~105k contexts), and n = 5 reaches ~76 MB (~177k single-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 memory 10x–20x.

  8. 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 all N sliding-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 the max_len steps, distribution evaluates all V vocabulary tokens in O(V * n) time (and top-k sampling — keeping only the k highest-weight candidates before sampling — sorts the V weights in O(V log V) time).
  • perplexity and select_n — O(N_valid * n) per candidate: Evaluating held-out perplexity touches each validation token once with an O(n) probability lookup; select_n runs one fit and one perplexity call per candidate n.

Edge cases

  • Unigram model (n = 1): Context width is 0. In Python, history[-0:] evaluates to history[0:] (the whole list!) instead of [], so _context_of explicitly returns () when width == 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 history or token map to <unk>. If an entire (n - 1)-token context never occurred in training (C(h) = 0), add-k smoothing gracefully returns the uniform distribution 1 / V summing to 1.0.
  • Empty files and zero-length generation: An empty training file still has vocab = {"</s>", "<unk>"} (V = 2), so generate excludes <unk>, immediately draws </s>, and returns start_tokens unchanged. An empty validation file has 0 predicted tokens and raises ValueError in perplexity. max_len = 0 returns a copy of start_tokens.
  • Small temperatures in apply_temperature: Temperature scaling raises probabilities to 1 / T and renormalizes; computing p_i^(1 / T) directly when T = 0.01 underflows every float to 0.0, whereas shifting (log p_i) / T by subtracting max_log before exp keeps the largest weight equal to 1.0 and never underflows.

Common mistakes

  • Including <s> inside self.vocab: Because <s> is never predicted as a next token, including it in V steals k / (C(h) + k * V) probability mass away from real tokens on every step.
  • Counting (n - 1)-grams separately from n-grams: If sentence-end tokens are handled slightly differently between the two loops, C(h) no longer equals sum_w C(h, w), and distribution(h) stops summing to 1.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 around 10^(-800), underflowing IEEE-754 float64 (min ≈ 5e-324) to 0.0.
  • Selecting n on training perplexity or random line splits: Training perplexity decreases monotonically with n as 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> shrinks V and 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 uniform 1 / V.
  • Interpolated Kneser–Ney smoothing: Kneser–Ney smoothing subtracts a fixed discount d (around 0.75) from observed counts and distributes the leftover weight proportionally to each word's continuation count (how many distinct left-contexts precede w), 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 probability C(h) / (C(h) + k * V), sample w proportionally to observed counts C(h, w) among seen followers only; otherwise (with probability k * V / (C(h) + k * V)), pick a uniformly random index from 0 .. V - 1 (rejecting and redrawing <unk>). That avoids iterating over all V words 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 by 60%–80% with minimal perplexity loss. For massive web scale where exact normalization is unnecessary, "Stupid Backoff" stores raw counts and multiplies by 0.4 each 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-likelihood L = -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 divide L by the number of UTF-8 bytes or characters to compare bits per byte (BPB) or bits per character (BPC).

Follow-up questions

Similar questions

More Runway interview questions

All 2 Runway questions →