Build an N-Gram Language Model: Smoothing, Generation, and Tuning N
Machine LearningModel answerLast updated
Implement a trainable n-gram language model with smoothing and sampling, then reason through how to pick the right n for your data.
N-Gram Language Model
A language model assigns probabilities to sequences of tokens. The n-gram approach is one of the oldest and most instructive: it approximates the probability of the next word using only the previous n−1 words as context (the Markov assumption).
Your task is to build a working implementation and reason through the design decisions.
What to implement
Build a class NGramLM with two methods:
fit(file_path, n)
- Read a plain-text file and tokenize it consistently (same tokenizer used everywhere).
- Build frequency tables for every n-gram and its (n−1)-gram prefix.
- Apply smoothing so that no token ever receives zero probability. Add-k smoothing is fine; briefly note the trade-offs versus Kneser–Ney.
- Handle rare words by mapping tokens below a minimum count threshold to an
<UNK>token.
generate(start_tokens, max_len, sampling_strategy)
- Given a seed sequence, repeatedly sample the next token from the learned conditional distribution.
- Support at least two sampling strategies: multinomial sampling and top-k sampling. Temperature rescaling is a bonus.
- Stop when an end-of-sequence token is produced or
max_lentokens have been generated.
What to discuss
After the implementation, address the following:
- Choosing n. How would you select the best
nfor a given corpus and task? Walk through a concrete validation procedure. - Metrics. What does perplexity measure, and why does it require a properly normalized model?
- Smoothing trade-offs. What goes wrong without smoothing? When would you prefer Kneser–Ney over add-k?
- Complexity. What is the time and space cost of
fitandgenerateas functions of corpus sizeN, vocabulary sizeV, and ordern? At what point does memory become the bottleneck in practice? - Edge cases. How do you handle an unseen context at generation time, a start sequence shorter than
n−1tokens, orn = 1?
Hints
Hint 1
Pad each sentence with n−1 <BOS> tokens on the left and one <EOS> on the right before counting. This lets every position have a full context of length n−1, including the first real word of the sentence.
Hint 2
Store counts at every context length from 0 up to n−1 in a single pass. That way backoff — falling back to a shorter context when the full one was never seen — is just a lookup at a shorter key, not a recount.
Hint 3
Perplexity is 2^(average cross-entropy), which requires probabilities that sum to 1 over the vocabulary. Make sure your smoothed distribution is properly normalized before computing it, otherwise you will get nonsensical numbers.
Model answer
Hard Try it yourself first — then compare your approach, complexity and edge cases.
Approach
The Markov assumption and what it buys you
An n-gram model makes one structural bet: the next token depends only on the previous n−1 tokens.
P(w_i | w_1 … w_{i-1}) ≈ P(w_i | w_{i-n+1} … w_{i-1})
This is wrong in general — real language has long-range dependencies — but it is easy to estimate from counts, fast to evaluate, and a useful baseline for any sequence-modeling problem.
Fitting in four steps
1. Tokenize once, reuse everywhere. A common mistake is tokenizing differently at train, eval, and generation time. Lowercase, split punctuation from words with a regex like r"[a-z0-9']+|[^\sa-z0-9']", and apply the same function every time.
2. Pad sentences. Wrap each sentence in n−1 <BOS> tokens on the left and one <EOS> on the right. This ensures every position, including the first word, has a full context of length n−1.
3. Build a vocabulary, then map rare tokens to <UNK>. Any token appearing fewer than min_count times becomes <UNK> at training time and at generation time. <BOS> is a context marker only and should never appear as a predicted token.
4. Count at every order from 0 to n−1. Store counts[m][context][word] for context lengths m = 0, 1, …, n−1. The unigram level (m = 0) always exists, so backoff always terminates.
Smoothing
Without smoothing, any n-gram unseen in training gets probability zero. A single zero in a test sentence makes perplexity infinite — it only takes one.
Add-k smoothing is simple and interpretable:
P(w | ctx) = (C(ctx, w) + k) / (C(ctx) + k·|V|)
Setting k = 1 is Laplace smoothing; smaller values like k = 0.1 work better in practice because Laplace over-smooths and steals too much probability mass from seen n-grams.
Kneser–Ney smoothing is the production-quality alternative. Instead of uniform pseudo-counts, it redistributes probability in proportion to how many distinct contexts a word appears in. A word like "Francisco" has high unigram frequency but almost always follows "San", so it should have low backoff weight in novel contexts. Kneser–Ney captures this. The downside is that it is harder to implement correctly and harder to explain in a quick interview.
Backoff rule. When the full context (w_{i-n+1}, …, w_{i-1}) was never seen in training, back off to the longest suffix of that context that was seen. Because the empty context always exists (it just gives the unigram distribution), the chain always terminates and the model is properly normalized.
Generation
At each step:
- Take the last
n−1tokens of the current output as the context. - Build the full distribution over the vocabulary using the smoothed probabilities.
- Apply the sampling strategy.
- Append the sampled token; stop at
<EOS>ormax_len.
Multinomial: sample directly from the distribution.
Top-k: zero out all but the k highest-probability tokens, renormalize, then sample. This removes the long noisy tail that smoothing artificially inflates.
Temperature: raise each probability to the power 1/T before renormalizing. T < 1 sharpens the distribution toward greedy decoding; T > 1 flattens it toward uniform sampling.
Selecting n
This is where the real engineering judgment lives. The right n depends on two opposing forces:
- Higher n captures more context and produces more fluent, coherent text — but requires exponentially more data to estimate well. On a small corpus, most 5-grams are seen exactly once.
- Lower n generalizes better on sparse data but misses longer-range structure.
Validation procedure:
- Split the corpus into train (80%), validation (10%), and test (10%) sets at the sentence level.
- Train models for
n ∈ {1, 2, 3, 4, 5}on the training set. - Compute perplexity on the validation set for each. Perplexity =
2^(−(1/M) Σ log2 P(w_i | context))where M is the number of predicted tokens. - Pick the
nwith the lowest validation perplexity. If it keeps falling as n increases, your corpus is large enough to support higher order — re-run withn ∈ {5, 6, 7}. - Report final perplexity on the held-out test set exactly once.
A rough rule of thumb: n-gram models need on the order of 10×|V|^(n-1) training tokens to estimate n-gram probabilities reliably. For a 50k-word vocabulary, that is 500k tokens for bigrams and 25 billion for trigrams — which is why large corpora are a prerequisite.
Complexity
| Operation | Time | Space |
|---|---|---|
fit | O(N · n) | O(N · n), bounded by V^n |
| One generation step | O(n) lookup + O(V) to build distribution | O(V) |
| Perplexity over M tokens | O(M · n) | O(1) extra |
Memory is the practical bottleneck. Each n-gram entry in a Python dict costs roughly 100–200 bytes (tuple key + Counter entry). At 100M training tokens with n = 5 and all orders stored, you can easily hit tens of GB. Production implementations address this with integer token IDs, tries or sorted arrays (KenLM), count pruning (drop singletons), and quantized probabilities.
Edge cases to handle explicitly
- n = 1: the context is empty; the model is a smoothed unigram. Valid and useful as a baseline.
- Unseen context at generation time: backoff to the longest seen suffix, down to the unigram if necessary.
- Start tokens shorter than n−1: left-pad with
<BOS>. - Start tokens longer than n−1: use only the last
n−1tokens. - Empty file: raise
ValueErrorimmediately rather than silently fitting an empty model. - top_k > |V|: clip to
|V|rather than crashing.
Python implementation
import math
import random
import re
from collections import Counter, defaultdict
class NGramLM:
BOS, EOS, UNK = "<BOS>", "<EOS>", "<UNK>"
def __init__(self, k: float = 0.1, min_count: int = 1):
if k <= 0:
raise ValueError("k must be > 0")
self.k = k
self.min_count = min_count
# ── tokenization ──────────────────────────────────────────────────────────
@staticmethod
def _tokenize(text: str) -> list[str]:
return re.findall(r"[a-z0-9']+|[^\sa-z0-9']", text.lower())
def _read_sentences(self, file_path: str) -> list[list[str]]:
with open(file_path, encoding="utf-8") as f:
sentences = [self._tokenize(line) for line in f if line.strip()]
if not sentences:
raise ValueError("Training file is empty.")
return sentences
def _map(self, token: str) -> str:
return token if token in self.vocab else self.UNK
# ── training ──────────────────────────────────────────────────────────────
def fit(self, file_path: str, n: int) -> "NGramLM":
if n < 1:
raise ValueError("n must be >= 1")
self.n = n
sentences = self._read_sentences(file_path)
# Build vocabulary from tokens that meet the frequency threshold
freq = Counter(tok for sent in sentences for tok in sent)
self.vocab = {tok for tok, c in freq.items() if c >= self.min_count}
self.vocab |= {self.EOS, self.UNK} # <BOS> is context-only, not predicted
self.vocab_list = sorted(self.vocab) # stable ordering for distributions
self.V = len(self.vocab_list)
# counts[m][context_tuple][next_token] for context length m in 0..n-1
self.counts: list[defaultdict] = [defaultdict(Counter) for _ in range(n)]
for sent in sentences:
# Pad: (n-1) BOS markers on the left, one EOS on the right
tokens = (
[self.BOS] * (n - 1)
+ [self._map(t) for t in sent]
+ [self.EOS]
)
for i in range(n - 1, len(tokens)):
word = tokens[i]
# Update every context length from 0 (unigram) up to n-1
for m in range(n):
ctx = tuple(tokens[i - m : i])
self.counts[m][ctx][word] += 1
# Pre-compute context totals to avoid re-summing in every prob call
self.totals = [
{ctx: sum(cnt.values()) for ctx, cnt in level.items()}
for level in self.counts
]
return self
# ── probability ───────────────────────────────────────────────────────────
def _best_context(self, history: list[str]) -> tuple[int, tuple]:
"""Return the longest suffix of history (up to n-1 tokens) seen in training."""
for m in range(self.n - 1, 0, -1):
ctx = tuple(history[-m:])
if ctx in self.counts[m]:
return m, ctx
return 0, () # unigram fallback always works
def prob(self, word: str, history: list[str]) -> float:
m, ctx = self._best_context(history)
c = self.counts[m][ctx].get(word, 0)
return (c + self.k) / (self.totals[m].get(ctx, 0) + self.k * self.V)
def _distribution(self, history: list[str]) -> list[float]:
m, ctx = self._best_context(history)
cnt = self.counts[m][ctx]
total = self.totals[m].get(ctx, 0)
denom = total + self.k * self.V
return [(cnt.get(w, 0) + self.k) / denom for w in self.vocab_list]
# ── generation ────────────────────────────────────────────────────────────
def generate(
self,
start_tokens: list[str],
max_len: int = 50,
sampling_strategy: str = "multinomial",
top_k: int = 10,
temperature: float = 1.0,
seed: int | None = None,
) -> list[str]:
if sampling_strategy not in {"multinomial", "top_k", "greedy"}:
raise ValueError(f"Unknown sampling_strategy: {sampling_strategy!r}")
if temperature <= 0:
raise ValueError("temperature must be > 0")
rng = random.Random(seed)
# Map start tokens through the vocabulary; pad history with BOS
mapped = [self._map(t) for t in start_tokens]
history = [self.BOS] * (self.n - 1) + mapped
output = list(mapped)
for _ in range(max_len):
probs = self._distribution(history)
if sampling_strategy == "greedy":
idx = max(range(self.V), key=probs.__getitem__)
else:
# Apply temperature scaling
weights = [p ** (1.0 / temperature) for p in probs]
if sampling_strategy == "top_k":
k_clipped = min(max(1, top_k), self.V)
top_indices = set(
sorted(range(self.V), key=weights.__getitem__, reverse=True)[
:k_clipped
]
)
weights = [w if i in top_indices else 0.0
for i, w in enumerate(weights)]
idx = rng.choices(range(self.V), weights=weights, k=1)[0]
next_token = self.vocab_list[idx]
if next_token == self.EOS:
break
output.append(next_token)
history.append(next_token)
return output
# ── evaluation ────────────────────────────────────────────────────────────
def perplexity(self, file_path: str) -> float:
"""
Compute per-token perplexity on a held-out file.
Requires a fitted model (call fit first).
"""
sentences = self._read_sentences(file_path)
log_sum = 0.0
token_count = 0
for sent in sentences:
tokens = (
[self.BOS] * (self.n - 1)
+ [self._map(t) for t in sent]
+ [self.EOS]
)
for i in range(self.n - 1, len(tokens)):
word = tokens[i]
history = tokens[max(0, i - (self.n - 1)) : i]
p = self.prob(word, history)
log_sum += math.log2(p)
token_count += 1
return 2 ** (-log_sum / token_count)
Common mistakes
- Not sharing the tokenizer. If you tokenize differently at fit vs. generate time, tokens will silently map to
<UNK>and the model will produce garbage. - "Stupid backoff" instead of normalized backoff. Multiplying by a fixed discount factor (like 0.4) and not renormalizing produces scores that do not sum to 1. Perplexity is then undefined.
- Forgetting
<EOS>in perplexity. Each sentence-end token is a real prediction and must be included in the cross-entropy sum, or perplexity will be artificially low. - Picking n on the test set. Hyperparameter selection must use only the validation split; the test set is touched exactly once to report the final number.