13.3 MLE, Laplace, absolute discounting
The byte bigram at the start of AI Engineering already smooths: it adds one to every count, because a byte pair never seen in training would otherwise get probability 0, the sampler could never produce it, and its NLL on new text would be infinite. That was one formula in one place. Later systems estimate distributions from counts everywhere. The Unigram tokenizer re-estimates its piece probabilities from expected counts on every EM step, the n-gram model with Kneser-Ney estimates the next word for millions of contexts most of which were seen once or never, and PMI divides co-occurrence counts.
Concepts from other sections (9)
This section uses these ideas. Each has a short definition and a link to the section that explains it in full. Tap a dotted term in the text to preview it.
- Negative log-likelihood (NLL): , the surprise of the true token under the model, in nats. Read more: 17.2 Perplexity, bits per byte, NLL accumulator
- KL divergence: , the excess cost of predicting with ; nonnegative and asymmetric. Read more: 17.1 Entropy, cross-entropy, KL, JS, and the k3 estimator
- Perplexity: , the geometric mean of ; the effective number of choices per token. Read more: 17.2 Perplexity, bits per byte, NLL accumulator
- counts of counts: , the number of grams at one order whose adjusted count is . Read more: 8.1 n-gram language model with interpolated modified Kneser-Ney in AI Engineering
- Gibbs’ inequality: , with equality if and only if ; coding data from with a code built for always costs extra bits, so cross-entropy is never below entropy. Read more: Chapter 17: Information Theory
- Likelihood: , the probability of the observed data as a function of the parameter. Read more: 13.10 Probability problem set, part b: joint distributions, covariance, MLE
- Laplace smoothing: adding one pseudo-count per vocabulary entry, . Read more: 13.10 Probability problem set, part b: joint distributions, covariance, MLE
- n-gram model: a language model that conditions each token only on the previous tokens. Read more: 8.1 n-gram language model with interpolated modified Kneser-Ney in AI Engineering
- modified Kneser-Ney: Kneser-Ney with three discounts per order (, , ) estimated from counts of counts. Read more: 8.1 n-gram language model with interpolated modified Kneser-Ney in AI Engineering
Each of those needs the same three decisions made correctly: what the best estimate from counts is, how much probability to keep for what was not seen, and where that probability goes. This section makes those decisions once, as functions with exact answers. You will prove that the observed frequency is the maximum-likelihood estimate, see why it fails on unseen outcomes, and build the two classical repairs: add-alpha smoothing and absolute discounting, the core of Kneser-Ney.
No code from earlier sections is needed. The reading background is natural logs and nats from Exponents, logs, and units of information and counting from the Discrete math 1 problem set. The reference implementation is course/solutions/python/tinyllm/prob/mle.py, with its contract in mle.pyi.
Learning objectives
- Prove that maximizes the log-likelihood of a categorical distribution, using the KL divergence.
- Explain why the MLE makes unseen outcomes impossible and what that does to perplexity.
- Implement add-alpha smoothing with the denominator over the whole vocabulary.
- Implement absolute discounting so that exactly the freed mass goes to a backoff distribution, including for fractional counts.
- Compute Ney’s discount from counts of counts.
Notation
Section titled “Notation”| Symbol | Meaning | Type / shape |
|---|---|---|
| the vocabulary: every outcome the model can assign probability to; its size | int | |
| how many times outcome was observed: an integer from counting, or a fraction when it is an expected count from EM | int or float | |
| the number of observations | int | |
| any distribution over : , | dict[K, float] | |
| the log-likelihood of the counts under , in nats | float | |
| an estimate of the true probability of | float | |
| the pseudo-count of add-alpha smoothing | float | |
| the absolute discount | float | |
| the number of distinct outcomes seen | int | |
| a backoff distribution over (a simpler model) | dict[K, float] | |
| the number of outcomes seen exactly times (count of counts) | int |
Likelihood and the MLE
Section titled “Likelihood and the MLE”If the observations are independent draws from , the probability of the data is (each observation of contributes a factor ; the order does not matter for estimating ). Its log is . Terms with contribute nothing, whatever is, by the convention . A term with and is : the data is impossible under .
The maximum-likelihood estimate is the that maximizes . It is the observed frequency, , and here is why. For any ,
because the Kullback-Leibler divergence is never negative (Gibbs’ inequality, proved in Entropy, cross-entropy, and KL), and it is 0 only when . So the frequency wins against every other distribution, which can also be checked numerically by scoring random competitors. It needs : with no data, is not an estimate.
The zero problem
Section titled “The zero problem”The MLE’s optimality is also its weakness: it puts all its mass on what was seen. A word with gets , and new text containing it gets likelihood 0 and perplexity (see Perplexity, bits per byte, and the NLL accumulator). In language most words are rare, so most of the vocabulary has in any given context: this is the normal case, not an edge case. The rest of the section is about how to take some probability away from what was seen and give it to what was not.
Add-alpha (Laplace) smoothing
Section titled “Add-alpha (Laplace) smoothing”The bluntest repair is to pretend every word of the vocabulary was seen extra times:
The denominator adds once per word of , including the words that are not keys of counts at all; summing the numerator over all of gives , so the estimate is a distribution. Every word gets at least . recovers the MLE and the uniform ; with no data it is exactly uniform. (Bayesian reading: this is the posterior mean under a symmetric Dirichlet() prior; is Laplace’s rule of succession.)
Its weakness is that it takes mass in proportion to , which for a 50 000-word vocabulary and a context seen 10 times hands almost everything to unseen words.
Absolute discounting
Section titled “Absolute discounting”A better repair takes mass from seen words in proportion to how much their counts overstate the future. Church and Gale (1991) counted bigrams in one half of a corpus and looked them up in the other: a bigram seen times in the first half appeared on average about times in the second. Seen counts overstate the future by a roughly constant amount. So subtract a constant from every seen count and give the freed mass to a backoff distribution (in Kneser-Ney, the next lower-order model):
Each word gives up : if it has that much, its whole count if not. So is precisely the freed fraction and . For integer counts with every seen word has at least and every unseen word has nothing, so , the form in most textbooks. The matters for keys whose count is 0, and the for the fractional expected counts of EM in the Unigram tokenizer: a word expected 0.3 times cannot lose 0.5. A seen word keeps plus its share of the backoff; an unseen one gets only . With there is nothing to discount and the answer is itself.
That leaves the question of how large should be. Ney, Essen and Kneser (1994) derived from leaving one observation out at a time, where and count the words seen once and twice. It lies in when . Modified Kneser-Ney uses three such discounts, for counts 1, 2, and 3 or more.
Working it by hand
Section titled “Working it by hand”Take counts a = 3, b = 2, c = 1, d = 0, over the vocabulary a b c d e (; e is not even a key). , .
MLE. for a b c d, and e would be 0 too.
Log-likelihood. nats. The d term is .
Laplace, . The denominator is , giving:
| word | a | b | c | d | e (not a key) |
|---|---|---|---|---|---|
| 4 | 3 | 2 | 1 | 1 | |
| 4/11 | 3/11 | 2/11 | 1/11 | 1/11 |
The five sum to . Dividing by (only the keys) would give over the keys and leave for e on top: a total of . The Laplace estimate’s log-likelihood is , lower than the MLE’s, as it must be.
Absolute discounting, , uniform backoff . The freed mass is , so each word gets from the backoff:
| word | |||
|---|---|---|---|
a | |||
b | |||
c | |||
d | |||
e |
Sum: . Without the clamp, d would get .
Ney’s discount. One word seen once (c), one seen twice (b): .
These numbers are the first five test cases a correct implementation must reproduce.
Designing the interface
Section titled “Designing the interface”Five functions cover the section:
def mle(counts: Mapping[K, int]) -> dict[K, float] # c_k / Ndef log_likelihood(counts: Mapping[K, int], probs: Mapping[K, float]) -> float # nats; -inf if impossibledef laplace(counts: Mapping[K, int], vocab_size: int, alpha: float = 1.0) -> dict[K, float]def absolute_discount(counts: Mapping[K, int], d: float, backoff: Mapping[K, float]) -> dict[K, float]def ney_discount(counts: Mapping[K, int]) -> float # n1 / (n1 + 2 n2)Counts are finite non-negative numbers: integers from counting (numpy integers are fine) or floats from EM; NaN, infinity, bools, and strings are a ValueError. laplace returns the keys of counts only; the contract states the probability of every other word. absolute_discount returns every key of backoff.
Building it step by step
Section titled “Building it step by step”Seven decisions determine the implementation.
- Counts are numbers, checked once. Every function starts from
counts, so one validator rejects what is not a finite non-negative real (bools areintsubclasses in Python and are rejected explicitly) and returns , summed withmath.fsumso fractional EM counts do not drift. - The MLE is , and needs . The KL argument proves the frequency is optimal; with it is , so the function raises instead of returning NaNs.
- The log-likelihood skips zero counts before looking up . by convention, and a zero-count key need not even be in
probs. For , a missing or zero makes the data impossible: return immediately. - Laplace divides by . One pseudo-count per word of the vocabulary, not per key, so the keys plus the unseen words sum to 1. The function returns only the keys; every other word’s probability is by the same formula.
- Absolute discounting: clamp, charge exactly what was taken, spread it by . Each key loses ; is the sum of those losses over ; every word of the backoff vocabulary gets . The output ranges over
backoff’s keys because that is the vocabulary the smoothed distribution covers, so every counted key must be in it. - No data means the backoff, as a fresh dict. With nothing was freed and nothing was seen; the answer is . Returning a copy matters because Kneser-Ney may edit one context’s distribution.
- Ney’s needs a singleton. With the discount would be 0 (no smoothing) or ; raise.
The validator, the MLE, and the log-likelihood come first:
def _check_counts(counts: Mapping[Hashable, float]) -> float: for k, c in counts.items(): # bool is a subclass of int: True would silently count as 1. if isinstance(c, bool) or not isinstance(c, numbers.Real): raise ValueError(f"count of {k!r} must be a number, got {c!r}") if not math.isfinite(c) or c < 0: raise ValueError(f"count of {k!r} must be finite and >= 0, got {c}") return math.fsum(float(c) for c in counts.values()) # N, exactly rounded
def mle(counts: Mapping[Hashable, float]) -> dict: n = _check_counts(counts) if n == 0: raise ValueError("mle needs at least one observation (N = 0 gives 0 / 0)") return {k: float(c) / n for k, c in counts.items()} # divide by N, not by the number of keys
def log_likelihood(counts, probs) -> float: _check_counts(counts) terms = [] for k, c in counts.items(): if c == 0: continue # 0 * log 0 = 0: an unseen outcome costs nothing (and need not be in probs) q = float(probs.get(k, 0.0)) if q <= 0.0: return -math.inf # an observed outcome the model calls impossible terms.append(float(c) * math.log(q)) return math.fsum(terms)numbers.Real accepts Python ints, floats, and numpy integer and float scalars, which is what counting code produces.
Laplace smoothing is a few lines once the denominator is right:
def laplace(counts, vocab_size: int, alpha: float = 1.0) -> dict: if not alpha > 0: # also rejects NaN raise ValueError(f"alpha must be > 0, got {alpha!r}") if len(counts) > vocab_size: # more keys than words: the vocabulary is wrong raise ValueError(f"{len(counts)} keys do not fit a vocabulary of {vocab_size}") n = _check_counts(counts) # The denominator adds alpha once per outcome of the vocabulary, seen or not. denom = n + alpha * vocab_size return {k: (float(c) + alpha) / denom for k, c in counts.items()}On the hand example, denom is and the keys get elevenths; e, not a key, has by the same formula, and the five sum to 1.
Absolute discounting carries most of the validation, because its inputs come from two places that must agree:
def absolute_discount(counts, d: float, backoff) -> dict: if not 0.0 < d <= 1.0: raise ValueError(f"d must lie in (0, 1], got {d!r}") total_b = math.fsum(float(v) for v in backoff.values()) if abs(total_b - 1.0) > 1e-9: raise ValueError(f"backoff must sum to 1, got {total_b!r}") missing = [k for k in counts if k not in backoff] if missing: # a counted word outside the output vocabulary would lose its mass raise ValueError(f"{missing[0]!r} is counted but not in the backoff vocabulary") n = _check_counts(counts) if n == 0: return {k: float(v) for k, v in backoff.items()} # a copy, never the caller's dict # Exactly the mass the discount removed: d from each seen count, or the # whole count when it is smaller than d (fractional EM counts). For # integer counts this is d * T / N with T the number of seen keys. lam = math.fsum(min(float(c), d) for c in counts.values()) / n return { k: max(float(counts.get(k, 0)) - d, 0.0) / n + lam * float(b) # clamp: a zero count stays >= 0 for k, b in backoff.items() }On the hand example, is , so ; d (count 0) gets . A zero-count key contributes to , so counting only over seen keys falls out of the formula without a separate test.
Ney’s discount is the last piece:
def ney_discount(counts) -> float: _check_counts(counts) n1 = sum(1 for c in counts.values() if c == 1) # words seen once n2 = sum(1 for c in counts.values() if c == 2) # words seen twice if n1 == 0: raise ValueError("no outcome was seen exactly once: Ney's discount would be 0") return n1 / (n1 + 2 * n2) # in (0, 1] once n1 > 0The full solution is mle.py.
Why this design
Section titled “Why this design”Every function is (and absolute_discount over the backoff), one or two passes, with fsum adding a small constant factor for exact summation.
The general is preferred over the textbook . They agree for integer counts, but is wrong for EM’s fractional counts: a count of 0.3 would be charged 0.5, and the distribution would sum to more than 1. The general form costs nothing extra.
Laplace returns a sparse output. Returning a dict over the whole vocabulary would cost per call, and the n-gram model calls this for millions of contexts. Returning the keys and stating the formula for the rest keeps it proportional to what was seen.
Among the alternatives, Good-Turing re-estimates each count from and is noisy for large ; add-alpha is simple but hands too much mass to a large vocabulary. Absolute discounting with a backoff is the base of Kneser-Ney, the best classical n-gram smoother, which is why the n-gram model builds on it.
One tradeoff is accepted: the backoff check uses a tolerance and the count checks are strict, so a slightly unnormalized backoff from a long float computation is accepted but a negative count never is.
What can go wrong
Section titled “What can go wrong”A correct solution reproduces the hand example, satisfies the normalization properties on random inputs, and handles the boundaries. The checks are listed here with why each matters later.
| Case | Kind of check | Checks | Why it matters downstream |
|---|---|---|---|
| MLE by hand | unit | 1/2, 1/3, 1/6, 0 | everyone agrees on the definition |
| Laplace by hand | unit | 4/11, 3/11, 2/11, 1/11, and 1/11 for e | the denominator counts the whole vocabulary |
| absolute discounting by hand | unit | 7/15, 3/10, 2/15, 1/20, 1/20 | the formula Kneser-Ney builds on |
| Ney’s discount by hand | unit | the starting discount of Kneser-Ney | |
| log-likelihood by hand | unit | for the MLE, for Laplace | smoothing costs training likelihood |
| the MLE maximizes the likelihood | property | random competitors and small perturbations score lower | the defining property |
| the MLE is a distribution | property | sums to 1; zeros stay 0 | no NaN, no missing key |
| Laplace over the whole vocabulary | property | keys plus the unseen words sum to 1 for three | the whole vocabulary is normalized |
| Laplace limits | unit | tiny is the MLE, huge and no data are uniform | interpolates |
| absolute discounting sums to 1 | property | random counts with zeros, random backoffs, four | is exactly the freed mass |
| zero-count keys | boundary | a zero-count key gets only | no negative probability |
| no data | boundary | returns a copy of | an unseen context in the n-gram model |
| boundary | singletons get only backoff mass | the edge of the allowed range | |
| bad arguments | boundary | negative, NaN, infinite, bool, or string counts; no data; bad , , , or backoff | upstream counting bugs fail here |
| fractional counts from EM | unit | the MLE of expected counts; when a count is below | EM in the Unigram tokenizer produces fractions |
| Ney’s discount edge cases | unit | all singletons give 1; no singletons raise | |
| zero terms and impossible data | boundary | ; an observed outcome with gives | infinite perplexity |
The mistakes behind failures of these checks fall into three groups.
The first group gets the normalizer wrong. Dividing by the number of distinct words instead of produces “probabilities” that sum to ; the solution divides by n from _check_counts. A Laplace denominator of (number of keys) makes the keys alone sum to 1, so the unseen words’ mass is extra and the total is above 1; the solution uses denom = n + alpha * vocab_size.
The second group charges the wrong amount in absolute discounting. Counting over every key, zero counts included, hands more mass to the backoff than was freed; sums min(c, d), which is 0 for a zero count. Using with fractional counts charges a count of 0.3 the full 0.5, so the result sums to more than 1. Omitting the clamp at 0 gives a key counted zero times a negative probability; the solution uses max(... - d, 0.0). And Ney’s discount written as is too large; the factor 2 matters.
Warning: Returning the caller’s backoff dict when looks harmless, but Kneser-Ney edits one context’s distribution and would corrupt the shared lower order. Always build a new dict.
The third group mishandles edge inputs. Scoring zero-count terms, or indexing a missing probability, turns into or a KeyError; the solution does continue on c == 0 and then probs.get(k, 0.0). Accepting NaN or infinite counts, or estimating from no data, yields NaN probabilities or a ZeroDivisionError; _check_counts rejects the former and mle raises on .
Where this leads
Section titled “Where this leads”These estimators reappear wherever counts become probabilities. The Unigram tokenizer seeds its piece probabilities with mle of substring counts, and each EM step is the same estimate over expected counts. Interpolated Kneser-Ney is absolute_discount per context with ney_discount-style and a continuation-count backoff. Mutual information, PMI, and PPMI divides joint and marginal MLEs from co-occurrence counts, and in Perplexity, bits per byte, and the NLL accumulator, is the NLL per token whose exponential is perplexity.
Further reading
Section titled “Further reading”- Jurafsky and Martin, Speech and Language Processing (3rd ed. draft), chapter 3, “N-gram Language Models”.
- Chen and Goodman, “An Empirical Study of Smoothing Techniques for Language Modeling” (1998).
- KenLM,
lm/builder/adjust_counts.cc: modified Kneser-Ney with three discounts per order estimated from count-of-counts, on disk-backed sorted n-gram streams. - scikit-learn’s
MultinomialNB(sklearn/naive_bayes.py): the same add-alpha estimate per class, as itsalphaparameter. - The SentencePiece Unigram trainer,
src/unigram_model_trainer.cc: EM where the M-step is this MLE plus a digamma correction (a Bayesian variant) and pruning.
Key terms
Section titled “Key terms”- Log-likelihood: , the log probability of the observed counts under a distribution .
- Maximum-likelihood estimate (MLE): the distribution that maximizes the log-likelihood; for counts, the frequency .
- Add-alpha (Laplace) smoothing: adding a pseudo-count to every word of the vocabulary before normalizing.
- Absolute discounting: subtracting a fixed from each seen count and giving the freed mass to a backoff distribution.
- Backoff distribution: a simpler model that receives the probability mass freed by discounting.
- Count of counts: , the number of outcomes seen exactly times.
- Ney’s discount: the estimate of the absolute discount.
Summary
Section titled “Summary”- The maximum-likelihood estimate of a categorical distribution is the observed frequency ; no other distribution gives the data a higher log-likelihood, because the gap is .
- The MLE gives every unseen outcome probability 0, so a single unseen word in new text makes its likelihood 0 and its perplexity infinite.
- Add-alpha smoothing divides by , one pseudo-count per word of the whole vocabulary, seen or not.
- Absolute discounting takes from every count and gives exactly that mass, for integer counts, to a backoff distribution: the core of Kneser-Ney.
- Ney’s gives a principled starting discount and needs at least one singleton.
Review questions
Section titled “Review questions”-
Why is the Laplace denominator and not ?
Answer
Every word of the vocabulary receives a pseudo-count, including words that are not keys of
countsat all. Summing over all of gives . With only the keys in the denominator, the keys alone sum to 1 and the unseen words’ comes on top, for a total above 1 (1.1 in the hand example). -
Why does
absolute_discountclamp withmax(c - d, 0)when and counts are integers?Answer
Keys can have count 0 (they were listed but not seen), and
counts.get(k, 0)returns 0 for every backoff word not counted. Without the clamp each of those would get , which can be negative ( in the hand example). The clamp says an unseen word loses nothing because it had nothing. -
Why does
log_likelihoodcontinueonc == 0before readingprobs?Answer
for any , including (by the convention). Reading first would either compute or return for data that is perfectly possible, and a zero-count key may be absent from
probsentirely. -
With , why return a copy of the backoff rather than
backoffitself?Answer
The answer is mathematically , but the n-gram model stores one distribution per context and may adjust it later. Returning the shared lower-order dict would let an edit to one unseen context change the backoff for every context.
-
Why does
ney_discountraise when no word was seen exactly once?Answer
is 0 when (or when too). A zero discount frees no mass, so unseen words would get probability 0, the problem smoothing exists to solve. Raising tells the caller that this count-of-counts gives no usable estimate.