Language-model smoothing: where does the probability go?
语言模型平滑
Derive add-k, interpolation, discounting and continuation mass; distinguish normalized likelihoods, unseen-token support and backoff scores.
smoothing-language-modelsAn unseen pair need not be an impossible sentence
Our invented training set contains eight copies of harbor quay, followed by old route, new route, coastal route and old bridge. A bigram maximum-likelihood model assigns zero probability to new quay: new has been followed only by route. Yet both words occur in training, and the missing combination is exactly the kind of event a finite sample can fail to include.
Smoothing redistributes probability under an explicit model so that observed count zero need not imply probability zero. It trades some fit to observed combinations for support elsewhere. The recipient distribution matters: quay occurs eight times, always after harbor; route occurs only three times but after three different words. Which should be a more plausible continuation of a new context?
This question leads from add-k and interpolation to continuation-based Kneser-Ney smoothing. We work with small bigrams whose probability mass can be checked exactly. N-gram models supplies the preceding counting and perplexity conventions; this article concentrates on how probabilities change after counting. The methods follow scoped readings of the SLP draft and the Chen–Goodman report. SLP, interpolation and backoff TR-10-98, smoothing definitions
Every borrowed bit of probability must come from somewhere
Declare the events and vocabulary
A history h is the preceding token. Each sentence starts with one BOS history and ends with one EOS prediction. BOS is not a predicted target; EOS and UNK are in the fixed target vocabulary. Training-only min_count decides which rare words map to UNK. With the default threshold one, our 12 sentences produce 36 prediction events, V=9 target types and 12 distinct observed bigram types.
Let C(h,w) count transitions, N_h their sum for history h, T_h the number of distinct observed followers, and M the total number of events:
For N_h>0, the maximum-likelihood estimate is C(h,w)/N_h. Our unigram base p_0(w) is the total target count C(w)/M, including EOS events. Each conditional probability model must sum to one across the same target vocabulary. For an unobserved history, MLE has no denominator and our implementation rejects it.
Add-k pays for a positive floor across the whole vocabulary
For α>0, add-k, named add-k in the code, adds the same pseudo-count to every target:
Summing the numerator gives N_h+αV, proving normalization. Even an unseen history gives a uniform distribution. A fixed V is essential: changing the vocabulary changes every denominator. Here old has N_h=2, T_h=2, with one route and one bridge. At α=0.5, the denominator is 6.5; each seen target receives 3/13, and each of the seven unseen targets receives 1/13. Their sum is one.
Increasing V while keeping α fixed adds more total pseudo-count mass. “Just add one” can therefore substantially flatten a distribution. A positive floor on this declared finite vocabulary does not give separate probabilities to every possible out-of-vocabulary spelling; those spellings still map to UNK.
Interpolation mixes complete distributions
Jelinek–Mercer-style linear interpolation in this experiment uses a fixed weight λ between zero and one:
The mixture is normalized because both component sums are one. Seen events can receive lower-order mass too; this is not a rule that consults the lower model only when the high-order count is zero. Weight one returns MLE for observed histories; weight zero returns the unigram base. We explicitly use the base alone when the history has never occurred. Interpolation weights should be selected using development data rather than the reported test set. SLP, §3.6.3
Witten-Bell uses the number of distinct observed followers to determine a history-dependent mixture:
Its high-order component has total mass N_h/(N_h+T_h); the lower component gets the remaining T_h/(N_h+T_h). Many distinct followers relative to observations give the base more weight. This is the interpolated form with our declared unigram base; the unseen-history policy again uses that base. TR-10-98, §2.5, equations 14–17
Absolute discounting removes a fixed amount per observed type
For a single discount D between zero and one and an observed history:
Positive counts are integers at least one. Thus each observed type loses exactly D counts, or D/N_h probability, including the endpoint D=1. Across T_h types the removed mass is DT_h/N_h. The base term restores precisely that amount. This proof depends on the stated discount range; arbitrary D>1 would invalidate the simple removed-mass expression. TR-10-98, §2.6, equations 18–20
At old, D=0.5 removes a total probability mass of 0.5. route receives 1/4 from its discounted count plus (1/2)(3/36) from the unigram base, giving 7/24. Unseen quay receives (1/2)(8/36)=1/9. Here Witten-Bell happens to give the same values because its high-order weight is also one half. The two formulas do not agree for every count table.
Kneser-Ney changes what the lower model counts
A frequent word may owe its frequency to one repeated context. The continuation distribution counts distinct predecessor types instead of raw occurrences:
Each observed bigram type contributes once to the denominator and once to its target’s numerator, so this distribution sums to one. In our corpus, quay has one distinct predecessor and route has three. Their continuation probabilities are 1/12 and 3/12, reversing the ordering of their unigram frequencies 8/36 and 3/36.
Replace the absolute-discount base with that continuation distribution:
At old with D=0.5, route gets 1/4+(1/2)(3/12)=3/8; quay gets (1/2)(1/12)=1/24. This is single-discount interpolated bigram Kneser-Ney, with continuation backoff for an unseen history. It is not a higher-order recursive implementation, the original backoff-only form, or modified Kneser-Ney with count-dependent discounts. TR-10-98, §2.7, interpolated equation 22
There is a useful marginal check. Let H_w be the number of distinct predecessors of w and B the total bigram type count. Averaging over observed histories with weights N_h/M, the discounted part contributes [C(w)−D H_w]/M. The redistributed part contributes (D B/M)(H_w/B), canceling the subtraction. Therefore:
This identity uses one fixed D, the declared boundary counts and the empirical history weights. It is not a claim that every smoothing method or every unobserved context preserves these marginals. The tests check all target words at D=0,0.25,0.5,1 with exact fractions.
A backoff score need not be a probability
Our bigram Stupid Backoff comparison keeps MLE scores on observed pairs and uses a scaled unigram score on unobserved pairs:
The seen scores already sum to one, before any positive unseen scores are added. At old, the seen targets are route and bridge, whose unigram mass totals 4/36. With β=0.4, the complete score sum is 1+0.4(32/36)=61/45. At a completely unobserved history, our specified fallback has total mass 0.4. Taking logarithms cannot make either sum one. The evaluator rejects this method for probability perplexity. Normalizing its scores would define another model. SLP, §3.6.4
Good-Turing is more than plugging a ratio into every count
Let n_r count the observed bigram types occurring exactly r times. The raw Good-Turing adjusted-count expression and unseen-mass estimate are:
Our global diagnostic gives n_1=7, n_2=1, n_3=1 and n_8=3, so n_1/M=7/36; raw adjusted counts for r=1 and 2 are 2/7 and 3. At r=3 or 8, the next bucket is missing. The program flags that gap instead of assigning zero probability to frequent types. A usable estimator needs a treatment of frequency-of-frequency noise, unseen types and conditional normalization. This diagnostic supplies none of those missing pieces and is not a complete Good-Turing or Katz model. TR-10-98, §2.2
Check the mass before computing perplexity
Save the complete block as smoothing.py and run python3 smoothing.py. It needs only the standard library; the repository checks use Python 3.12.4. Fraction keeps small-model counts and probabilities exact. Float parameters are interpreted by their round-trip decimal spelling: the supplied 0.4 means 2/5. Logarithms and printed decimals remain floating-point calculations.
"""Original exact small-bigram smoothing laboratory.
Count tables share one vocabulary and one EOS per sentence. Fractions keep mass
accounting exact for small examples; this is not an efficient production LM.
Stupid Backoff is exposed as a score and is rejected by probability evaluation.
"""
from collections import Counter, defaultdict
from fractions import Fraction
import json
import math
BOS='<s>';EOS='</s>';UNK='<unk>'
METHODS=('mle','add-k','interpolation','witten-bell','absolute','kneser-ney','stupid-backoff')
def sentence(row):
if not isinstance(row,(list,tuple)) or any(not isinstance(w,str) or not w or w in (BOS,EOS,UNK) or any(0xD800<=ord(c)<=0xDFFF for c in w) for w in row):
raise ValueError('Supply nonempty Unicode tokens without reserved markers or surrogates')
return list(row)
def corpus(rows):
if not isinstance(rows,(list,tuple)) or not rows:raise ValueError('A nonempty sentence collection is required')
return [sentence(row) for row in rows]
def number(value,low=0,high=None,strict_low=False):
if isinstance(value,bool) or not isinstance(value,(int,float)) or (isinstance(value,float) and not math.isfinite(value)):
raise ValueError('Finite numeric parameter required')
if value<low or (strict_low and value==low) or (high is not None and value>high):raise ValueError('Parameter outside declared bounds')
# A supplied float is interpreted by its round-trip decimal spelling.
return Fraction(str(value))
def fit(rows,min_count=1):
rows=corpus(rows)
if type(min_count) is not int or min_count<1:raise ValueError('Positive integer min_count required')
frequency=Counter(w for row in rows for w in row);kept={w for w,c in frequency.items() if c>=min_count}
vocabulary=tuple(sorted(kept|{EOS,UNK}));counts=defaultdict(Counter);unigram=Counter();predecessors=defaultdict(set)
for row in rows:
mapped=[w if w in kept else UNK for w in row];previous=BOS
for word in mapped+[EOS]:
counts[previous][word]+=1;unigram[word]+=1;predecessors[word].add(previous);previous=word
total=sum(unigram.values());types=sum(len(c) for c in counts.values())
return {'vocabulary':vocabulary,'counts':dict(counts),'unigram':dict(unigram),
'predecessor_types':{w:len(predecessors[w]) for w in vocabulary},'bigram_types':types,
'events':total,'sentences':len(rows),'min_count':min_count}
def history_key(model,history):
if history is None or history==BOS:return BOS
if not isinstance(history,str) or not history or history==EOS or any(0xD800<=ord(c)<=0xDFFF for c in history):
raise ValueError('History is one pre-EOS token, or None for BOS')
return history if history in model['vocabulary'] else UNK
def probabilities(model,history,method='kneser-ney',alpha=.5,weight=.5,discount=.5,backoff=.4):
if method not in METHODS:raise ValueError('Unknown smoothing method')
a=number(alpha,strict_low=True);mix=number(weight,high=1);d=number(discount,high=1);factor=number(backoff,high=1)
h=history_key(model,history);row=model['counts'].get(h,{});n=sum(row.values());t=len(row);v=model['vocabulary']
base={w:Fraction(model['unigram'].get(w,0),model['events']) for w in v}
continuation={w:Fraction(model['predecessor_types'][w],model['bigram_types']) for w in v}
if method=='add-k':return {w:(row.get(w,0)+a)/(n+a*len(v)) for w in v}
if not n:
if method=='mle':raise ValueError('No MLE distribution for an unobserved history')
if method=='stupid-backoff':return {w:factor*base[w] for w in v}
return continuation if method=='kneser-ney' else base
high={w:Fraction(row.get(w,0),n) for w in v}
if method=='mle':return high
if method=='interpolation':return {w:mix*high[w]+(1-mix)*base[w] for w in v}
if method=='witten-bell':return {w:Fraction(row.get(w,0),n+t)+Fraction(t,n+t)*base[w] for w in v}
if method=='stupid-backoff':return {w:high[w] if row.get(w,0) else factor*base[w] for w in v}
lower=continuation if method=='kneser-ney' else base
return {w:max(Fraction(row.get(w,0))-d,Fraction(0))/n+d*t/n*lower[w] for w in v}
def inspect(model,history,method,**options):
p=probabilities(model,history,method,**options);mass=sum(p.values());h=history_key(model,history)
return {'history':h,'method':method,'probabilities_or_scores':{w:float(v) for w,v in p.items()},
'exact_values':{w:str(v) for w,v in p.items()},'total_mass':float(mass),'exact_mass':str(mass),
'is_probability_model':method!='stupid-backoff','normalized_at_this_history':mass==1,
'numeric_underflow_targets':[w for w,v in p.items() if v>0 and float(v)==0]}
def evaluate(model,rows,method='kneser-ney',**options):
if method=='stupid-backoff':raise ValueError('Unnormalized Stupid Backoff scores are not probability perplexities')
rows=corpus(rows);terms=[];zero_events=[];events=0
for index,row in enumerate(rows):
mapped=[w if w in model['vocabulary'] else UNK for w in row];events+=len(mapped)+1;h=BOS
for position,w in enumerate(mapped+[EOS]):
p=probabilities(model,h,method,**options)[w]
if p==0:zero_events.append({'sentence':index,'event':position,'reason':'zero_target'});break
terms.append(math.log(p.numerator)-math.log(p.denominator));h=w
if zero_events:return {'status':'zero_probability','events':events,'mean_nll_nats':None,'perplexity':None,'zero_events':zero_events}
loss=-math.fsum(terms)/events
try:pp=math.exp(loss)
except OverflowError:pp=None
return {'status':'finite_log_probability','events':events,'mean_nll_nats':loss,'perplexity':pp,'perplexity_overflow':pp is None}
def tune_interpolation(model,development,grid=(0.,.25,.5,.75,1.)):
development=corpus(development)
if not isinstance(grid,(list,tuple)) or not grid:raise ValueError('Supply a nonempty candidate-weight list')
trials=[]
for weight in grid:
number(weight,high=1);score=evaluate(model,development,'interpolation',weight=weight)
trials.append({'weight':weight,'evaluation':score})
finite=[(t['evaluation']['mean_nll_nats'],i) for i,t in enumerate(trials) if t['evaluation']['status']=='finite_log_probability']
if not finite:raise ValueError('No finite development likelihood on this grid')
_,index=min(finite)
return {'weight':trials[index]['weight'],'trials':trials,'scope':'Finite declared grid, chosen by development event-weighted loss; not a continuous optimizer or test-set selection.'}
def good_turing_diagnostic(model):
buckets=Counter(c for row in model['counts'].values() for c in row.values());entries=[]
for r,nr in sorted(buckets.items()):
following=buckets.get(r+1,0)
entries.append({'count':r,'types':nr,'next_types':following,
'raw_adjusted_count':float(Fraction((r+1)*following,nr)) if following else None,
'status':'raw_ratio' if following else 'next_bucket_missing'})
return {'count_of_counts':entries,'unseen_mass_estimate':float(Fraction(buckets.get(1,0),model['events'])),
'scope':'Global observed-bigram count-of-counts diagnostic only. Missing next buckets are flagged, not assigned zero probability. No smoothed frequency-of-frequency model, unseen-type allocation or complete Katz implementation.'}
def demo():
train=[['harbor','quay'] for _ in range(8)]+[['old','route'],['new','route'],['coastal','route'],['old','bridge']]
development=[['new','quay'],['old','route']];test=[['coastal','bridge']];model=fit(train)
chosen=tune_interpolation(model,development)
rows={method:inspect(model,'old',method) for method in METHODS}
scores={method:{'known':evaluate(model,[['harbor','quay']],method),
'recombined':evaluate(model,[['new','quay']],method),
'oov':evaluate(model,[['novel','route']],method)} for method in METHODS if method!='stupid-backoff'}
rare=fit(train,min_count=2)
return {'training':train,'events':model['events'],'vocabulary':list(model['vocabulary']),'bigram_types':model['bigram_types'],
'unigram_counts':model['unigram'],'predecessor_types':model['predecessor_types'],
'after_old':rows,'scores':scores,'good_turing':good_turing_diagnostic(model),
'development_selection':{'development':development,'selection':chosen,'test':test,
'test_after_selection':evaluate(model,test,'interpolation',weight=chosen['weight'])},
'trained_unk':{'vocabulary':list(rare['vocabulary']),'unk_targets':rare['unigram'].get(UNK,0),
'oov_score':evaluate(rare,[['novel','route']],'kneser-ney')},
'scope':'Original small bigram experiment with exact rational mass accounting. Base is unigram MLE, KN is single-discount interpolated bigram KN, not modified KN. Reserved but unseen UNK can still have zero mass. No benchmark claim.'}
if __name__=='__main__':print(json.dumps(demo(),ensure_ascii=False,indent=2,allow_nan=False))
The default after_old output uses λ=0.5, α=0.5, D=0.5 and β=0.4. Each row reports both fractions and decimal values, plus its sum. is_probability_model distinguishes a declared probability model from a backoff score; a score that happens to sum to one for one history is not certified as a distribution for all histories.
The known sentence harbor quay has MLE probability (8/12)×1×1=2/3. Its two words plus EOS give three events, so perplexity is (3/2)^(1/3). For successful probability evaluation over E events, the program uses:
The recombination new quay has zero MLE probability. With the example’s interior parameters, the other five probability smoothers give it positive probability. novel route exposes a different issue: the default vocabulary reserves UNK but never trains an UNK event. Its unigram and continuation masses remain zero, so all demonstrated probability methods except add-k still give the sentence zero probability. Reserving a symbol is not the same as learning support for it.
Refit with min_count=2. The three singleton words new, coastal and bridge now become UNK training targets, producing three UNK targets and a six-item vocabulary. The novel sentence’s KN likelihood becomes positive. This changes the model’s vocabulary and counts; perplexities across such token-mapping policies are not directly comparable as if they scored the same events.
When a true probability is zero, the evaluator reports zero_probability and leaves numeric NLL/perplexity fields null rather than emitting nonstandard JSON infinities. Otherwise it logs a fraction as log(numerator)−log(denominator). A positive rational can underflow to zero in a displayed float while retaining a finite logarithm through this calculation; numeric_underflow_targets exposes that distinction. Exponentiating a finite large NLL can still overflow, which has a separate flag.
The development set is new quay, old route; the test set is coastal bridge. The program compares only λ∈[0,0.25,0.5,0.75,1], picks the smallest event-weighted development loss and uses original grid order for ties. The chosen λ is 0.75, after which the test set is scored once with that choice. This is a finite grid search, not a continuous optimum, and the training counts stay fixed throughout. SLP, development-set interpolation
Computational scope
For T input tokens, S sentences and B distinct observed bigrams, fitting takes expected O(T + S + V log V) work under bounded token comparison costs: counting includes one EOS per sentence and the vocabulary is sorted and stores O(B+V) count/type statistics, beyond copied inputs. Each probability call constructs full V-entry base, continuation and output dictionaries. Scoring E events therefore makes O(EV) rational-operation-scale work, plus sentence scanning and the cost of summing a selected history’s counts. The stored diagnostics also materialize distributions. This design favors inspection over throughput.
Fraction arithmetic is not constant-time: numerator and denominator bit lengths affect multiplication, division, reduction and logarithm conversion. Exact mass in this tiny model does not imply efficient exact arithmetic for a large corpus. A production implementation would cache distributions or score only requested targets, handle higher orders and sparse storage, and validate its own floating-point contract.
Support and fit are different questions
A normalized distribution can still assign zero probability to a needed event. A positive distribution can still rank continuations badly. Neither a unit mass sum nor finite toy perplexity establishes useful language quality. Vocabulary construction, boundary policy, corpus size and evaluation events must be held fixed when comparing probability losses.
The unigram bases here include EOS. Unknown spellings collapse to a single symbol; this is not an open-vocabulary model. The constant-D KN example is deliberately narrow, and the Good-Turing table cannot stand in for missing smoothing, backoff allocation or modified-KN discounts. Use held-out results under a declared setup before choosing a method. The report’s definitions are used here; its experimental rankings and speech error rates were not reviewed or reproduced.
Account for the missing probability
1. Understanding: an unseen pair versus an unseen word
Why can new quay receive positive KN probability while novel route still gets zero with the default vocabulary?
Answer: quay is an observed target with a positive continuation count, so discounting can assign it mass after a new pairing. novel maps to reserved UNK, whose continuation and unigram counts are zero at threshold one. No mass reaches that target under the demonstrated KN model. Add-k supplies a vocabulary-wide floor, while training rare words as UNK changes the learned support by another mechanism.
2. Hand calculation: where does half the mass go?
At history old, compute route and quay probabilities with D=0.5 under absolute discounting and KN. Use the supplied counts.
Answer: N_h=T_h=2, so the lower model receives DT_h/N_h=1/2. route has high-order mass (1−0.5)/2=1/4. Absolute discounting gives 1/4+(1/2)(3/36)=7/24 and unseen quay gets (1/2)(8/36)=1/9. KN substitutes continuation masses 3/12 and 1/12, giving 3/8 and 1/24. The high-order discount is identical; the redistribution changes the result.
3. Counterexample: log scores are not log probabilities
Show why β=0.4 Stupid Backoff is not normalized at old. Would averaging negative log scores fix it? What if the Good-Turing next count bucket is absent?
Answer: The observed-pair scores sum to one. Unseen targets have base mass 32/36, so the full sum is 1+(2/5)(32/36)=61/45. Logging and averaging do not change the model’s missing normalization. Separately, a missing Good-Turing bucket makes the raw ratio unreliable; our diagnostic flags it instead of replacing an observed type’s probability with zero. Neither issue is repaired by calling the resulting number perplexity.
4. Transfer: compare models on the same events
You choose λ=0.75 on the supplied development grid, then find that another λ scores the test sentence better. May you report that new choice as untouched-test performance? May you compare a threshold-two UNK model’s perplexity directly with threshold one without qualification?
Answer: Selecting again on test data turns that test into selection data; reserve another test set for a fresh final estimate or report the selection honestly. Changing the UNK threshold changes vocabulary, counts and scored symbols, so record the mapping and do not treat different event spaces as an equal perplexity contest. Neither adjustment is just a numerical correction to the existing model.
Keep the method and the publication version specific
The SLP chapter used here is the August 19, 2026 draft; the scoped reading covers interpolation, development weights and the distinction between Stupid Backoff scores and probabilities. The Chen–Goodman PDF is technical report TR-10-98: its cover says August 1998 and its inner title is dated July 24, 1998. The hosting publication page’s 1996 label must not be used to redate this PDF. The 1996 conference version and 1999 journal version were not read for this article.
The report review covered the Good-Turing discussion and Witten-Bell, absolute-discount and continuation definitions; pages 13–17 were also viewed to check the equations. It did not cover the experimental comparisons or the modified-KN section. The tiny corpus, exact-rational implementation, numerical examples and counterexamples are original. To extend this laboratory, first specify the higher-order recursion, discount estimator, unknown-token policy and a common evaluation corpus; then compare against independently checked reference outputs.
Make a prediction, then check
A backoff method returns scores summing to 61/45 for one history. Can those scores be used directly as probabilities for perplexity?
Learning objectives
- Derive the removed and redistributed mass in bigram smoothing.
- Distinguish unigram frequency from continuation diversity.
- Identify when an unknown token still has zero probability.
- Separate development selection, normalized likelihood and backoff scores.
Prerequisites & connections
Explore related knowledge →References
- Speech and Language Processing, third-edition draft: interpolation and backoff
Daniel Jurafsky; James H. Martin · 2026 - An Empirical Study of Smoothing Techniques for Language Modeling, TR-10-98
Stanley F. Chen; Joshua Goodman · 1998
Version1 · Editorial status: Recorded technical checks completed
View technical check record (AI)
Codex · 2026-09-08 · Codex single-AI-author technical check: scoped SLP August19,2026 and 1998 TR-10-98 definitions, eleven paired equations, add-k/interpolation/Witten-Bell/absolute mass, single-discount interpolated bigram KN continuation and empirical marginal identity, unnormalized backoff rejection, partial Good-Turing diagnostic, UNK support, EOS/event-weighted likelihood, exact-rational versus floating logs, complexity and four explained exercises. Not modified KN, complete Katz, a natural-language benchmark or human peer review.
- Compared both languages: one BOS history and one EOS target, exact add-k and mixture mass, constant-D removed mass, predecessor-type continuation and KN marginal cancellation, Stupid Backoff61/45 rejection, missing Good-Turing buckets, untrained/trained UNK, zero probability versus numerical underflow, and development-only grid selection. Eleven equations and four explained exercises correspond.
- Formal suite executes production MDX:20 original prototype checks,3 article hand/boundary/identity cases and6 publication checks. Exact Fraction mass and KN marginals across four discounts, event counts, independent fractions, finite logs at tiny alpha and known sentence perplexity checked. Training includes sentence/EOS traversal and sorted vocabulary; rational bit-cost caveat retained.
- Four original SVGs bind the exact MDX results; seven figure tests check data, arithmetic, bars and bilingual references. Isolated18 language/width combinations and four fallback fonts passed after a recorded English-label repair. Actual desktop/mobile screenshots inspected. Full article browser acceptance recorded separately; no human peer review or upstream code execution.
Source locations checked:
- Speech and Language Processing, third-edition draft: interpolation and backoff · Cached August 19, 2026 chapter 3, layout-text lines 884–967: interpolation, development-set weights and Stupid Backoff not being a probability distribution. Only this scoped reading.
- An Empirical Study of Smoothing Techniques for Language Modeling, TR-10-98 · 1998 report: cover August, inner title July 24. Layout-text lines 335–408 and 520–761; rendered pages 13–17, Witten-Bell/absolute discount/interpolated KN equations and continuation types. No experiments or modified-KN review; not the 1996 conference or 1999 journal version.
Related topics