KatInterview

Build an N-Gram Language Model: Smoothing, Generation, and Tuning N

Machine LearningModel answer
HardModel answerMachine Learningnlplanguage-modelsmoothing

Last 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_len tokens have been generated.

What to discuss

After the implementation, address the following:

  1. Choosing n. How would you select the best n for a given corpus and task? Walk through a concrete validation procedure.
  2. Metrics. What does perplexity measure, and why does it require a properly normalized model?
  3. Smoothing trade-offs. What goes wrong without smoothing? When would you prefer Kneser–Ney over add-k?
  4. Complexity. What is the time and space cost of fit and generate as functions of corpus size N, vocabulary size V, and order n? At what point does memory become the bottleneck in practice?
  5. Edge cases. How do you handle an unseen context at generation time, a start sequence shorter than n−1 tokens, or n = 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.