smartyfy.mrindigi.com

Python Master Course V2 — 155. N-Gram Language Models and Perplexity

Purpose and learning outcomes

A language model assigns probabilities to token sequences. Before using neural networks, you can learn this idea with a short table of observed transitions. You will build a character bigram model, give unseen transitions nonzero probability, measure held-out cross-entropy, and generate a bounded sample. The model predicts characters from local counts; it is not a source of factual answers.

  • Estimate next-token probabilities with smoothing
  • Generate bounded sequences from a seeded n-gram model
  • Compute held-out cross-entropy and interpret perplexity fairly

Prerequisites

  • 126: probability
  • 151: tokenization

Environment and execution

Use a project-specific virtual environment with a currently supported Python 3 release compatible with the packages below. Python 3.11 or 3.12 is a practical starting point. Run shell commands in a terminal, then run the Python blocks in order in one script or notebook kernel. They use only included data and local CPU computation. No account, API key, camera, or external dataset is required. Record the installed package versions with python -m pip freeze when you save your results; a random seed does not guarantee identical numerical behavior across library versions.

This lesson uses the Python standard library only; there is nothing else to install.

python -m venv .venv
# macOS/Linux: source .venv/bin/activate
# Windows PowerShell: .venv\Scripts\Activate.ps1

Understand the model and its assumptions

A bigram model estimates the next token from the previous one. Its limited memory is explicit: once the current character is known, earlier characters do not affect the probability table. This simplification makes training and inspection easy but prevents the model from representing long-range agreements or document structure.

Maximum-likelihood counts assign zero probability to an unobserved transition. One zero makes a sequence's log probability negative infinity. Add-alpha smoothing adds a positive pseudocount to every possible next-token outcome, then normalizes by the context count plus alpha times vocabulary size. Larger alpha pulls distributions toward uniformity; it does not guarantee better predictions.

Cross-entropy is the average negative log probability of the actual held-out next tokens. With natural logarithms its units are nats per token. Perplexity is the exponential of that average. It can be interpreted as an effective uncertainty scale, but comparisons require the same tokenization, vocabulary, boundary rules, and evaluation text. A word-level perplexity and character-level perplexity are not directly comparable.

Split complete passages before estimating counts. Randomly splitting overlapping windows allows nearly identical contexts from one passage to appear in both partitions. Our vocabulary is a declared alphabet of lowercase ASCII letters, space, and three boundary symbols. That is an explicit exercise constraint, not a multilingual tokenizer. Unknown characters map to an unknown token; report how often this occurs, because a model can appear to improve simply by collapsing difficult input into one symbol.

Worked example: build it in stages

Each passage starts with a beginning marker and ends with an end marker. The beginning marker is a context, never a generated outcome. Train counts separately for every passage so the end of one does not predict the start of another. Evaluate all transition events including end markers, then generate with a local seeded random generator and a strict maximum length.

from collections import Counter, defaultdict
import math
import random
import string

BOS, EOS, UNK = "<BOS>", "<EOS>", "<UNK>"
outcomes = list(string.ascii_lowercase + " ") + [EOS, UNK]
alphabet = set(string.ascii_lowercase + " ")
training = ["the lamp is warm", "the room is calm", "a bird rests", "a dog rests"]
validation = ["the bird is calm", "a lamp is warm"]
final_test = ["the dog is calm"]

def encode(text):
    return [c if c in alphabet else UNK for c in text]

counts = defaultdict(Counter)
for passage in training:
    tokens = [BOS] + encode(passage) + [EOS]
    for previous, following in zip(tokens, tokens[1:]):
        counts[previous][following] += 1

def probability(previous, following, alpha):
    if alpha <= 0:
        raise ValueError("alpha must be positive")
    row = counts.get(previous, Counter())
    return (row[following] + alpha) / (sum(row.values()) + alpha * len(outcomes))

def cross_entropy(passages, alpha):
    losses = []
    for passage in passages:
        tokens = [BOS] + encode(passage) + [EOS]
        losses.extend(-math.log(probability(a, b, alpha))
                      for a, b in zip(tokens, tokens[1:]))
    if not losses:
        raise ValueError("no evaluation events")
    return sum(losses) / len(losses)

best_alpha = min([0.1, 0.5, 1.0], key=lambda a: cross_entropy(validation, a))
loss = cross_entropy(final_test, best_alpha)
print("alpha:", best_alpha, "test nats:", loss, "test perplexity:", math.exp(loss))

def generate(alpha, seed=7, max_tokens=60):
    rng = random.Random(seed)
    previous, generated = BOS, []
    for _ in range(max_tokens):
        weights = [probability(previous, t, alpha) for t in outcomes]
        token = rng.choices(outcomes, weights=weights, k=1)[0]
        if token == EOS:
            break
        generated.append(token)
        previous = token
    return "".join(generated)

assert math.isclose(sum(probability("a", t, 0.5) for t in outcomes), 1.0)
print(generate(best_alpha))

What the output means

The script prints the validation-selected alpha, a measured final-test loss and perplexity, then a sample of at most sixty generated tokens. No particular sample or score is promised here. A sample may terminate immediately or contain the visible unknown marker because smoothing gives every permitted outcome positive probability. The normalization assertion has the expected result True and prints nothing when successful.

Guided lab and acceptance checks

Record validation loss for all three alpha values before selecting one. Lock that choice, then evaluate the final test once. Inspect the probability row after the character space and list its five most likely outcomes. Compare it with an unseen context, whose smoothed row is uniform.

Extend the corpus with two entirely new training passages, preserving the validation and test sets. Discuss whether improvement reflects more transition evidence rather than a better model family. Acceptance requires normalized rows, finite held-out loss, a documented alphabet, bounded generation, and a report separating validation selection from final evaluation.

Common mistakes and repairs

Never smooth the numerator without changing the denominator. Do not average per-passage perplexities and call the result corpus perplexity: aggregate token losses first, then exponentiate. Do not tune alpha on the final test. Avoid comparing perplexities after changing unknown-token policy, since the prediction task itself has changed.

Questions and answers

Why use log probabilities?

Multiplying many small probabilities underflows numerically. Logs convert products into sums and yield a stable loss. Averaging the negative log probabilities also makes every predicted token's contribution explicit, including boundary events if the protocol includes them.

Does lower perplexity guarantee better-looking samples?

No. It measures average predictive probability on the specified evaluation tokens. Sampling quality also depends on decoding choices, and a tiny model may assign sensible local probabilities while producing globally incoherent text. Evaluate the actual intended use separately.

Why include the end marker?

Stopping is part of sequence prediction. Without an end marker the model has no learned termination probability and must rely entirely on an external length limit. The limit is still necessary for bounded runtime and predictable output size.

What happens with an unseen context?

Every observed count in that row is zero. Add-alpha smoothing gives each allowed outcome the same probability, because their identical pseudocounts are divided by alpha times vocabulary size. This is uncertainty, not learned knowledge about that context.

Is choosing alpha on validation data leakage?

It is legitimate model selection when the validation role is declared and the final test remains untouched. Reporting the best validation score as unbiased final performance would overstate evidence, especially after trying many alternatives.

Exercises

1. Verify that an unseen context produces a uniform distribution. 2. Implement corpus loss from a supplied list of negative log probabilities. 3. Explain why an empty string still has one evaluation event under this boundary policy.

Worked solutions and reasoning

The geometric mean of inverse assigned probabilities, not an arithmetic mean of perplexities, gives corpus perplexity. For an empty passage the model still predicts EOS from BOS, so the evaluation denominator is one rather than zero.

uniform = [probability("<UNSEEN>", t, 0.5) for t in outcomes]
assert all(math.isclose(p, 1 / len(outcomes)) for p in uniform)
losses = [math.log(2), math.log(4)]
mean_loss = sum(losses) / len(losses)
assert math.isclose(math.exp(mean_loss), math.sqrt(8))
assert math.isfinite(cross_entropy([""], 0.5))

Recap

Language modeling is probability estimation under a defined token protocol. Smoothing, held-out passages, normalized distributions, and bounded decoding make a simple model honest and testable. The same evaluation discipline will matter when the probability table becomes a neural network.

Official references

Finish the exercises and mastery checkpoint before marking this lesson complete. Completion is stored on this browser.