Module contents
Lesson 3 of 24Core 110 min

Smoothing: from Laplace to Kneser-Ney

Study probability smoothing, Good-Turing, interpolation, backoff and Kneser-Ney, with controlled evaluations.

After this lesson you can

  • Explain how smoothing redistributes probability mass.
  • Calculate Good-Turing and continuation statistics.
  • Derive normalized Kneser-Ney and compare discounting and backoff.
  • Distinguish normalized probabilities from retrieval scores.

Before you start

A new continuation is not impossible

You have trained a bigram and test contains a continuation never seen after that context. Maximum likelihood assigns it zero probability, so one such decision makes perplexity infinite for the entire evaluation. A zero count expresses absence of evidence in the corpus; turning it into zero probability is an estimator choice, not proof of impossibility.

Smoothing means reserving probability mass and deciding how to distribute it. The second choice matters as much as the first. Here we compare models on the same vocabulary and events, including sentence endings. Parameters are fitted on training and validation; repeatedly consulting test for exploration makes its results no longer an independent final evaluation.

InteractiveWhere does the mass go?

Five toy training sentences: «el gato duerme», «el gato come», «el perro duerme», «el gato duerme», «perro come». Fixed validation: «el perro come», «perro duerme», «el gato perro». Each sentence starts with BOS and contributes one EOS; UNK is reserved in the vocabulary but does not appear in training.

Color distinguishes successors observed after gato and zero-count successors. Context selection changes only the displayed row: validation always uses the same 11 events from the three sentences.

el0.033
gato0.033
perro0.066
duerme0.566
come0.233
EOS0.066
UNK0.000

■ Seen after this context · ■ Unseen after this context. An absent bar can have zero probability.

Validation perplexity versus d

110.0∞01

Logarithmic vertical axis. The ∞ symbol sits outside the scale; it does not replace infinity with a finite value. The readout above corresponds to the exact control value.

Add-k distributes pseudocounts among the seven symbols. Absolute discounting uses add-0.5 unigram as its base. KN uses distinct predecessors among training pairs and mixes 99% of that base with 1% uniform, an explicit extension to support UNK. With d = 0, a successor unseen after an observed context may still have zero probability.

Good-Turing uses N₁/N as unseen mass, distributes it uniformly among absent symbols and renormalizes raw adjusted counts to distribute remaining mass. An absent row or a row whose remaining mass cannot be distributed is undefined. PPL is infinite if an event has zero probability; if a needed row is undefined, PPL is also undefined. This teaching sample does not measure performance on a real language.

Estimator
0.50
Total row mass1.0000
Mass on unseen successors0.2004
Validation PPL3.054
Zero-probability validation events0 / 11
Undefined events0 / 11
Compare distributions and perplexity on a toy corpus with fixed validation.

Add pseudocounts

For a finite output vocabulary V\mathcal V with VV symbols and k>0k>0, additive smoothing uses

Pk(w∣h)=C(h,w)+kC(h)+kV.P_k(w\mid h)=\frac{C(h,w)+k}{C(h)+kV}.

Each row sums to one. If the context is absent, the formula returns the uniform distribution. With a symmetric Dirichlet prior of parameter kk for each category and categorical observations of the context, it is also the posterior predictive distribution. That equivalence depends on the chosen prior and vocabulary: it does not prove that prior describes every language.

If VhV_h continuations appear after hh, mass assigned to the rest is (V−Vh)k/(C(h)+kV)(V-V_h)k/(C(h)+kV). With many possible symbols and little data it can dominate the row, especially for k=1k=1. The exact result depends on counts: there is no reason to claim add-1 always gives away nearly all mass. <eos> and <unk> are outputs if included by the protocol; <bos> and <pad> should not accidentally occupy output categories.

Frequency of frequencies

The Good-Turing estimator asks how many types appeared once, twice and so on. Let NcN_c be the number of types observed exactly cc times and N=∑c≥1cNc>0N=\sum_{c\ge1}cN_c>0 the number of observations. Total mass of unseen types is estimated by N1/NN_1/N. For a type observed c>0c>0 times, the classical adjusted count is

c∗=(c+1)Nc+1Nc,Nc>0.c^*=(c+1)\frac{N_{c+1}}{N_c}, \qquad N_c>0.

This is an estimate supported by a sampling model, not the true unknown mass in every sample. Aggregate mass also does not determine the probability of each new type. If output support is finite and known and absent types remain, distribute it uniformly among them or use a base normalized over that subset. If the base was defined over the whole vocabulary, restrict and renormalize it over absent types provided it assigns them positive mass. If no absent types remain but N1/N>0N_1/N>0, the raw estimate cannot be assigned within that support: a different consistent convention is needed, not division by zero.

In the tail, NcN_c is noisy; Nc+1N_{c+1} may be absent even if the observed type is frequent. Applying the raw formula without adjustment could even yield zero adjusted count. Implementations smooth frequency of frequencies, apply a criterion to retain high counts and check normalization. Specify the procedure and what happens if a denominator is zero. Frequency distribution and estimated discounts must come from the chosen corpus, not a curve drawn to confirm a trend. Chen and Goodman study these choices and several smoothing families.

InteractiveFrequency of frequencies

Complete toy sequence: sol mar sol luna sol luna viento sol luna nube sol luna sol arbol rio flor mar mar mar piedra faro isla uva hoja uva. Only its first 25 tokens are counted; this is not a real language sample.

Each N_c point counts types occurring c times. The chart uses logarithmic scales on both axes; zeroes and undefined values appear only in the table. The selected count is 1.

0.101.0010.001234567Count c, log scale

For c = 1: N_c = 9, N_(c+1) = 1. The raw formula gives 0.222.

cN_cN_(c+1)Raw c*c* with line
1 · selected910.2221.011
2100.0002.013
302Undefined3.014 · no types
4200.0004.014
501Undefined5.015 · no types
6100.0006.015
700Undefined7.015 · no types

● Observed N_c and fitted line · ● Raw c* · ■ Smoothed c* with observed types · □ rule value with no observed types. The selected point is highlighted in N_c when it exists.

Raw: c* = (c+1)N_(c+1)/N_c, defined only when N_c > 0. The line fits log N_c against log c by unweighted least squares using positive frequencies only; at least two distinct counts are required. It is then evaluated at c and c+1. The pseudocount uses Ñ_j = N_j + α. When N_c = 0, the smoothed value comes from the chosen rule: no types with that count were observed. Depending on the gap’s location, the line interpolates or extrapolates.

Both rules are teaching models, not the Simple Good-Turing procedure or a guarantee of improvement. Adjusted counts alone are not a normalized distribution and can exceed c; a usable estimator needs a reserve for unseen types, tail treatment and normalization. Without a fixed vocabulary N₀ is unknown, as is how to distribute N₁/N among absent types. Neither figure demonstrates constant discounting or generalizable numbers.

25
1
Illustrative smoothing
Observed types13
Types occurring c times9
Raw c*0.222
c* with line1.011
Unseen mass N₁/N0.360
Inspect gaps in a toy corpus and how they affect the adjusted count.

Mix orders or back off

Jelinek-Mercer interpolation combines a long-context distribution with a shorter-context one:

P(w∣h)=λPalto(w∣h)+(1−λ)Pbajo(w∣h′),0≤λ≤1.P(w\mid h)=\lambda P_{\mathrm{alto}}(w\mid h) +(1-\lambda)P_{\mathrm{bajo}}(w\mid h'), \qquad 0\le\lambda\le1.

If both components sum to one, so does the mixture. The expression can be applied recursively across orders. For a context with no counts, use a defined lower-order distribution directly; a zero row is not a normalized component.

You can choose λ\lambda by maximizing validation likelihood. In a two-component mixture, the higher-order component’s responsibility for an event is rt=λpalto,t/[λpalto,t+(1−λ)pbajo,t]r_t=\lambda p_{\mathrm{alto},t}/[\lambda p_{\mathrm{alto},t}+(1-\lambda)p_{\mathrm{bajo},t}] (“alto” and “bajo” mean high and low); an EM update averages these responsibilities. If the denominator is zero, that event has zero probability and the fraction is indeterminate. This can happen if both components assign zero or the only component assigning mass has zero weight. A base with positive support and strictly positive weight avoids this for the fixed vocabulary; otherwise report failure. Test does not participate in fitting.

Katz backoff distributes a discounted portion among seen successors and consults lower order only for unseen ones. If ShS_h is the seen-successor set and PdP_d assigns them nonnegative mass summing to at most one, the constant for remaining continuations is

α(h)=1−∑w∈ShPd(w∣h)1−∑w∈ShPbajo(w∣h′).\alpha(h)=\frac{1-\sum_{w\in S_h}P_d(w\mid h)} {1-\sum_{w\in S_h}P_{\mathrm{bajo}}(w\mid h')}.

The denominator is mass the base assigns to unseen continuations after hh. If it is zero and positive mass remains to distribute, that base cannot normalize backoff: change it or declare the case. If no residual mass remains, no probability need be assigned outside ShS_h. Backing off without this adjustment changes the row sum.

One way to choose Katz discounts starts with global NcN_c frequencies of n-grams at the considered order. With cutoff KK, for 1≤c≤K1\le c\le K calculate A=(K+1)NK+1/N1A=(K+1)N_{K+1}/N_1 and factor dc=(c∗/c−A)/(1−A)d_c=(c^*/c-A)/(1-A) using Good-Turing’s c∗c^*. For c>Kc>K retain the undiscounted count. These ratios require enough observed classes and values between zero and one; with a small sample the cell reports when it falls back to another discount. The lab variant backs off directly to a smoothed unigram, illustrating normalization without claiming to implement every option of a production multilevel system.

Discount and continuation

Absolute discounting subtracts dd from every positive count and distributes the released mass to a lower-order model. For positive integer counts, 0≤d≤10\le d\le1 prevents subtracting more than observed. The best value depends on data and fitting procedure. Although a discount near 0.75 can be a working reference, it does not universally follow from Good-Turing.

Which lower-order distribution is appropriate? “York” could appear many times in a corpus almost always after “Nueva.” Its raw frequency does not reveal few preceding contexts. By contrast, a word like “casa” could appear after many distinct predecessors. Continuation probability measures that context diversity. The example supports these conclusions only if specific counts do.

InteractiveFrequency and context variety

Toy corpus: (de, york) occurs 4 times; (de, casa), (a, casa), (en, casa) and (por, casa) each occur once. These are given pairs, without starts or EOS. With four repetitions this reproduces the corpus in this lesson’s exercises.

Continuation: each bar shows the probability of a continuation.

0.000.250.500.751.00york0.20casa0.80

Scroll the table horizontally to see all distributions.

SuccessorRaw frequencyDistinct predecessorsUnigramMLEContinuationKN
york41 (de)0.5000.8000.2000.710
casa44 (de, a, en, por)0.5000.2000.8000.290

Unigram divides successor occurrences by 8. Continuation divides its distinct predecessors by the 5 bigram types. For the chosen context, MLE divides each count by C(h) = 5; if C(h) = 0 no MLE row is defined.

For C(h) > 0, KN = max(C(h,w) − d, 0)/C(h) + λP_cont(w), where λ = dT(h)/C(h) and T(h) = 2. If the context is absent, we use P_cont directly. The support here contains only «york» and «casa»; any other successor has zero probability. This example does not demonstrate how a real corpus would behave.

4
0.75
Displayed distribution
Bigram occurrences8
Bigram types5
Context occurrences5
Interpolated mass λ0.300
Repeat a bigram and compare its raw frequency with distinct predecessors.

For bigrams, let N1+(∙ w)N_{1+}(\bullet\,w) be the number of distinct predecessors of ww and N1+(∙ ∙)N_{1+}(\bullet\,\bullet) the total number of distinct bigrams. Then

Pcont(w)=N1+(∙ w)N1+(∙ ∙).P_{\mathrm{cont}}(w)=\frac{N_{1+}(\bullet\,w)}{N_{1+}(\bullet\,\bullet)}.

The sum over the output vocabulary is one if the denominator is positive and counted bigrams use the same support and boundaries. If there are no bigrams, the expression is undefined and a declared alternative base is needed.

Interpolated Kneser-Ney

Interpolated Kneser-Ney combines discounting and continuation. For an observed context hh, let T(h)=N1+(h ∙)T(h)=N_{1+}(h\,\bullet) be the number of distinct successors. With 0≤d≤10\le d\le1,

PKN(w∣h)=max⁡(C(h,w)−d,0)C(h)+λ(h)Pcont(w),λ(h)=d T(h)C(h).P_{\mathrm{KN}}(w\mid h)= \frac{\max(C(h,w)-d,0)}{C(h)} +\lambda(h)P_{\mathrm{cont}}(w),\qquad \lambda(h)=\frac{d\,T(h)}{C(h)}.

Each observed successor loses d/C(h)d/C(h), so the direct part sums to 1−dT(h)/C(h)1-dT(h)/C(h). The second part sums to λ(h)\lambda(h) because PcontP_{\mathrm{cont}} is normalized; the full row sums to one. For C(h)=0C(h)=0 use the base directly. Being normalized does not imply positive probability for every word: if an output has zero probability at every level, perplexity can still be infinite.

At higher orders, lower Kneser-Ney levels use continuation counts: for a sequence at that level, distinct predecessors are counted, not all raw occurrences. Sentence-marker treatment must be fixed before counting. The highest order uses training counts; the rest use corresponding continuation statistics.

The modified variant of Chen and Goodman distinguishes discounts D1D_1, D2D_2 and D3+D_{3+} for counts 1, 2 and at least 3. Their 1998 report presents estimators in terms of frequency-of-frequency statistics appropriate to each level:

Y=N1N1+2N2,D1=1−2YN2N1,D2=2−3YN3N2,D3+=3−4YN4N3.Y=\frac{N_1}{N_1+2N_2},\quad D_1=1-2Y\frac{N_2}{N_1},\quad D_2=2-3Y\frac{N_3}{N_2},\quad D_{3+}=3-4Y\frac{N_4}{N_3}.

These formulas require nonzero denominators and can be unstable with small corpora. Check discounts are valid for the counts they apply to and declare an alternative when they cannot be estimated. Interpolated mass must be the sum of actually applied discounts divided by the context total; if clipping a discount to its count, calculate with the clipped discount. Teh relates hierarchical Pitman-Yor process predictives to these ideas; a specific MKN implementation is not automatically exact Bayesian inference for that model.

Scale without confusing score and probability

Stupid Backoff retains the MLE ratio for a seen n-gram and otherwise consults a lower order multiplied by a factor. Brants and colleagues used 0.4 in the described configuration and studied its utility as a translation feature with large corpora. Its scores are not normalized per context: they are not probabilities and should not be used to calculate perplexity as if they were. Utility as a relative score in a specific system does not demonstrate a distribution.

KenLM offers query structures trading memory against speed. Scalable modified Kneser-Ney estimation is described in later work by Heafield and colleagues. Speed figures depend on model, machine and configuration; documentation also distinguishes memory and temporary disk during estimation.

An ∞-gram searches for the longest context suffix with useful occurrences in the corpus, without fixing one nn in advance. A suffix array sorts text positions and permits binary search for query matches. The longest context found sets effective order; a particular continuation can still have zero count. If a match reaches document end, you need an end marker or a rule excluding it from the denominator: you cannot silently cross into the next document.

InteractiveFind the longest context

Teaching index of code points over the previous lesson’s training excerpt: En un lugar de la Mancha, de cuyo nombre no quiero acordarme. This is a single NFC-normalized and lowercased sequence followed by EOS. It is not a web-scale index or a measurement of production Infini-gram.

Testing de␠la, searching for the boundary lower. The middle index 30 is after the query. The table shows a window into the sorted array; indices are positions in that array.

IndexStart in corpusSuffix start
2727e␠cuyo␠nombre␠no
2813e␠la␠mancha,␠de␠
2939e␠no␠quiero␠acor
30 · selected0en␠un␠lugar␠de␠l
3147ero␠acordarmeEOS
328gar␠de␠la␠mancha
3322ha,␠de␠cuyo␠nomb

Advance to the last comparison to show the distribution. If no suffix of the current length has a continuation, the algorithm removes its first code point and searches again.

Both boundaries of each interval are found with binary search and comparison uses numerical code point order, with EOS before any character. An empty context counts all document tokens and EOS. The distribution consists of frequencies over observed continuations: other outputs have zero probability. There is no interpolation or generalization estimate in this figure.

0
Comparison1 / 12
Boundary soughtlower
Active interval[0, 61)
Queried suffixde␠la
Effective orderPending
Step through actual binary searches in a teaching suffix index and calculate continuations.

A mixture of the ∞-gram with another normalized model can reserve mass for continuations unseen in the long context. To guarantee full support over the vocabulary, the base must have it and receive positive weight. The paper’s production index operates at far larger scale than the local lab; building a naive array by materializing every suffix can exhaust memory. Construction and queries must be measured separately.

Labs

Smoothers and normalization

This lab implements add-k, a local Good-Turing variant, interpolation with weights selected on validation, Katz backoff, interpolated absolute discounting and modified Kneser-Ney. Katz uses frequency-class Good-Turing correction up to a cutoff and an add-0.5 unigram base; insufficient classes or invalid discounts use a fixed absolute fallback declared in output. Formula and cutoff follow SRILM. If all outputs are already seen, it retains the MLE row because no remaining support can receive the discount. It checks mass on observed contexts of the small sample and one absent context; for larger texts it checks the first 64 observed rows and declares this. The MKN base includes a 1% uniform mixture to support output symbols: this is an explicit variant.

The sample contains short excerpts from chapters I and II of part one of Don Quixote, Project Gutenberg edition 2000, prepared by an anonymous volunteer and Joaquín Cuenca Abela. Its listing identifies US public-domain status; consult Project Gutenberg terms and applicable law. The first excerpt is split by position into training and validation, with its own ending for each segment; the second is exploratory test. You can replace TRAIN and TEST with complete chapters. The sample only checks the pipeline.

[ ]Smoothing and mass conservationBrowser
"""Add-k, Good-Turing local, interpolación, backoff y MKN para corpus pequeños.

Fragmentos de la primera parte de Don Quijote, de Miguel de Cervantes,
capítulos I y II, Project Gutenberg 2000:
https://www.gutenberg.org/files/2000/2000-0.txt . La ficha declara dominio
público en EE. UU.; consulta https://www.gutenberg.org/policy/license.html
y las leyes aplicables antes de redistribuir. La muestra solo comprueba el
recorrido. El lector puede pegar los capítulos completos en TRAIN y TEST.
"""
import math
import re
import unicodedata
from collections import Counter, defaultdict

TRAIN = 'En un lugar de la Mancha, de cuyo nombre no quiero acordarme'
TEST = 'Hechas, pues, estas prevenciones, no quiso aguardar más tiempo'
TOKEN_PATTERN = re.compile(r"\w+(?:['’]\w+)*|[^\w\s]", re.UNICODE)
SPECIAL = {'<s>', '</s>', '<unk>', '<pad>'}


def tokenize(text):
    return TOKEN_PATTERN.findall(unicodedata.normalize('NFC', text).lower())


def events(sentence, n):
    context = ['<s>'] * (n - 1)
    for token in [*sentence, '</s>']:
        yield tuple(context), token
        if n > 1:
            context = (context + [token])[-(n - 1):]


def katz_ratios(histogram, cutoff=5, fallback=.5):
    # Katz: cociente corregido Good-Turing hasta el corte. Con clases
    # insuficientes o cocientes inválidos, descuento absoluto explícito.
    if cutoff < 1 or not 0 <= fallback <= 1:
        raise ValueError('Corte o respaldo inválido')
    n1 = histogram[1]
    correction = (cutoff + 1) * histogram[cutoff + 1] / n1 if n1 else math.inf
    ratios, origins = {}, {}
    for count in sorted(histogram):
        if count > cutoff:
            ratios[count], origins[count] = 1., 'sin descuento'
            continue
        ratio = None
        if n1 and correction < 1 and histogram[count + 1]:
            adjusted = (count + 1) * histogram[count + 1] / histogram[count]
            candidate = (adjusted / count - correction) / (1 - correction)
            if math.isfinite(candidate) and 0 <= candidate <= 1:
                ratio = candidate
        ratios[count] = ratio if ratio is not None else (count - fallback) / count
        origins[count] = 'Good-Turing corregido' if ratio is not None else 'respaldo absoluto'
    return ratios, origins


class Models:
    def __init__(self, train, order, epsilon=.01, fallback=.5):
        if not train or SPECIAL.intersection(train) or order < 2:
            raise ValueError('Entrenamiento vacío, marcadores literales u orden inválido')
        if not 0 < epsilon <= 1 or not 0 <= fallback <= 1:
            raise ValueError('Parámetros fuera de rango')
        self.order, self.epsilon = order, epsilon
        self.vocab = sorted(set(train) | {'<unk>', '</s>'})
        self.allowed = set(self.vocab)
        self.raw = {}
        for n in range(1, order + 1):
            table = defaultdict(Counter)
            for context, word in events(train, n):
                table[context][word] += 1
            self.raw[n] = table
        raw_histogram = Counter(count for row in self.raw[order].values() for count in row.values())
        self.katz_ratios, self.katz_origin = katz_ratios(raw_histogram, fallback=fallback)
        # En niveles inferiores c*(h,w) cuenta predecesores distintos.
        # El símbolo de inicio puede ser predecesor, nunca salida.
        self.adjusted = {order: self.raw[order]}
        for n in range(order - 1, 0, -1):
            predecessors = defaultdict(set)
            for context, successors in self.raw[n + 1].items():
                for word in successors:
                    predecessors[(context[1:], word)].add(context[0])
            table = defaultdict(Counter)
            for (context, word), preceding in predecessors.items():
                table[context][word] = len(preceding)
            self.adjusted[n] = table
        self.discounts = {}
        self.discount_origin = {}
        for n in range(2, order + 1):
            histogram = Counter(count for row in self.adjusted[n].values() for count in row.values())
            a, b, c, d = (histogram[i] for i in (1, 2, 3, 4))
            values = None
            if a and b and c:
                y = a / (a + 2 * b)
                candidate = (1 - 2 * y * b / a, 2 - 3 * y * c / b, 3 - 4 * y * d / c)
                if all(math.isfinite(x) and 0 <= x <= limit for x, limit in zip(candidate, (1, 2, 3))):
                    values = candidate
            self.discounts[n] = values if values is not None else (fallback, fallback, fallback)
            self.discount_origin[n] = 'frecuencias de frecuencias' if values else 'respaldo fijo'

    def map(self, token):
        return token if token in self.allowed else '<unk>'

    def map_sentence(self, sentence):
        if SPECIAL.intersection(sentence):
            raise ValueError('El texto incluye un marcador literal reservado')
        return [self.map(token) for token in sentence]

    def row(self, n, context, adjusted=False):
        table = self.adjusted[n] if adjusted else self.raw[n]
        return table.get(tuple(context[-(n - 1):]) if n > 1 else (), Counter())

    def add_k(self, context, word, k=.5):
        if not math.isfinite(k) or k <= 0:
            raise ValueError('k debe ser finito y positivo')
        row = self.row(self.order, context)
        count, total = row[self.map(word)], sum(row.values())
        if k >= 1:
            # Divide por k para evitar desbordar al calcular k × V.
            return (count / k + 1) / (total / k + len(self.vocab))
        return (count + k) / (total + k * len(self.vocab))

    def gt(self, context, word):
        row = self.row(self.order, context)
        total, v = sum(row.values()), len(self.vocab)
        if total == 0:
            return 1 / v
        unseen = v - len(row)
        if unseen < 0:
            raise ValueError('El vocabulario no contiene todos los sucesores')
        histogram = Counter(row.values())
        reserved = histogram[1] / total if unseen else 0.
        # Un c+1 ausente usa c como respaldo, en lugar de borrar un tipo visto.
        adjusted = {token: ((count + 1) * histogram[count + 1] / histogram[count]
                            if histogram[count + 1] else count)
                    for token, count in row.items()}
        norm = sum(adjusted.values())
        word = self.map(word)
        return (1 - reserved) * adjusted[word] / norm if word in row else reserved / unseen

    def uniform(self, word):
        return 1 / len(self.vocab)

    def unigram(self, word):
        row = self.raw[1][()]
        # Base con soporte positivo para todos los símbolos de salida.
        return (row[self.map(word)] + .5) / (sum(row.values()) + .5 * len(self.vocab))

    def jm(self, context, word, weight):
        if not 0 <= weight <= 1:
            raise ValueError('Peso fuera de rango')
        row = self.row(self.order, context)
        total = sum(row.values())
        if not total:
            return self.unigram(word)
        return weight * row[self.map(word)] / total + (1 - weight) * self.unigram(word)

    def tune_jm(self, validation, steps=25):
        weight = .5
        # Corte de pesos para mantener la base estrictamente positiva.
        for _ in range(steps):
            responsibilities = []
            for context, word in events(self.map_sentence(validation), self.order):
                row = self.row(self.order, context)
                total = sum(row.values())
                if not total:
                    continue  # Esta fila se evalúa solo con la base.
                high, low = row[word] / total, self.unigram(word)
                denominator = weight * high + (1 - weight) * low
                if denominator <= 0:
                    raise ValueError('Evento de validación sin soporte')
                responsibilities.append(weight * high / denominator)
            if not responsibilities:
                break
            weight = min(1 - 1e-6, max(1e-6, sum(responsibilities) / len(responsibilities)))
        return weight

    def absolute(self, context, word, discount=.5):
        if not 0 <= discount <= 1:
            raise ValueError('Descuento fuera de rango')
        row = self.row(self.order, context)
        total = sum(row.values())
        if not total:
            return self.unigram(word)
        removed = discount * len(row) / total
        return max(row[self.map(word)] - discount, 0) / total + removed * self.unigram(word)

    def katz_backoff(self, context, word):
        # Descuentos de clases globales; la base es unigrama add-0,5.
        row = self.row(self.order, context)
        total = sum(row.values())
        if not total:
            return self.unigram(word)
        word = self.map(word)
        if len(row) == len(self.vocab):
            return row[word] / total  # No queda soporte para repartir masa.
        if word in row:
            return row[word] * self.katz_ratios[row[word]] / total
        unigram = self.raw[1][()]
        base_total = sum(unigram.values()) + .5 * len(self.vocab)
        # Resta recuentos enteros, no probabilidades casi iguales.
        missing_base = (sum(unigram.values()) - sum(unigram[w] for w in row)
                        + .5 * (len(self.vocab) - len(row))) / base_total
        if missing_base <= 0:
            raise ValueError('La base no concede masa a continuaciones ausentes')
        residual = sum(count * (1 - self.katz_ratios[count]) for count in row.values()) / total
        return residual * self.unigram(word) / missing_base

    def kn(self, context, word, n=None):
        n = self.order if n is None else n
        word = self.map(word)
        if n == 1:
            row = self.adjusted[1].get((), Counter())
            total = sum(row.values())
            continuation = row[word] / total if total else self.uniform(word)
            # Extensión explícita: 1 % uniforme mantiene soporte de UNK/EOS.
            return (1 - self.epsilon) * continuation + self.epsilon * self.uniform(word)
        row = self.row(n, context, adjusted=True)
        total = sum(row.values())
        if not total:
            return self.kn(context, word, n - 1)
        discounts = self.discounts[n]
        def discount(count):
            if count <= 0:
                return 0.
            return min(count, discounts[0 if count == 1 else 1 if count == 2 else 2])
        removed = sum(discount(count) for count in row.values()) / total
        count = row[word]
        return (count - discount(count)) / total + removed * self.kn(context, word, n - 1)


def evaluate(model, sentence, fn):
    total, count = 0., 0
    unknown = sum(word not in model.allowed for word in sentence)
    for context, word in events(model.map_sentence(sentence), model.order):
        p = fn(context, word)
        count += 1
        if not math.isfinite(p) or p < 0 or p > 1 + 1e-12:
            raise ValueError('Probabilidad no válida')
        if p == 0:
            return {'events_until_zero': count, 'zero': True, 'ppl': math.inf, 'oov': unknown}
        total += math.log(p)
    return {'events': count, 'zero': False, 'ppl': math.exp(-total / count), 'oov': unknown}


def check_normalization(model, functions):
    # En la muestra pequeña comprueba todos los contextos observados; para
    # capítulos grandes limita la auditoría iterativa a 64 filas explícitas.
    contexts = sorted(model.raw[model.order])
    audited = contexts if len(contexts) <= 64 else contexts[:64]
    audited = audited + [('contexto-no-visto',) * (model.order - 1)]
    for context in audited:
        for name, fn in functions.items():
            values = [fn(context, word) for word in model.vocab]
            if not all(math.isfinite(p) and 0 <= p <= 1 + 1e-12 for p in values):
                raise ValueError('Probabilidad fuera de rango: ' + name)
            if not math.isclose(sum(values), 1., rel_tol=1e-10, abs_tol=1e-10):
                raise ValueError('Fila no normalizada: ' + name)
    return len(audited) - 1, len(contexts)


def main():
    all_train = tokenize(TRAIN)
    split = max(1, int(len(all_train) * .8))
    train, validation, test = all_train[:split], all_train[split:], tokenize(TEST)
    if not validation:
        raise ValueError('Se requiere validación separada con al menos un token')
    print('Tokens train, validación, test:', len(train), len(validation), len(test))
    for n in range(2, 6):
        model = Models(train, n)
        if n == 2:
            for bad_k in (0., -1., math.nan, math.inf):
                try:
                    model.add_k(('<s>',), model.vocab[0], bad_k)
                except ValueError:
                    continue
                raise AssertionError('Debe rechazar k inválido')
            assert math.isclose(sum(model.add_k(('<s>',), w, 1e308) for w in model.vocab), 1., abs_tol=1e-12)
        weight = model.tune_jm(validation)
        functions = {'add-k': lambda c, w: model.add_k(c, w),
                     'good-turing-local': lambda c, w: model.gt(c, w),
                     'jelinek-mercer': lambda c, w: model.jm(c, w, weight),
                     'backoff-katz': lambda c, w: model.katz_backoff(c, w),
                     'descuento-absoluto': lambda c, w: model.absolute(c, w),
                     'mkn-base-uniforme': lambda c, w: model.kn(c, w)}
        checked, total = check_normalization(model, functions)
        print('\nOrden', n, '| peso JM', weight, '| descuentos', model.discounts,
              '| origen', model.discount_origin, '| filas auditadas', checked, 'de', total, '+ contexto ausente')
        print('Katz: cocientes por recuento', model.katz_ratios, '| origen', model.katz_origin)
        for name, fn in functions.items():
            print(name, 'test exploratorio:', evaluate(model, test, fn))
    print('MKN usa mezcla uniforme 1 % en la base; es una variante explícita.')
    print('Muestra breve y test exploratorio: ninguna comparación demuestra superioridad general.')


main()

A suffix index for experiments

This lab uses NumPy locally. Because Pyodide cells have a time limit, large-index construction is proposed as a local run to be measured in your environment. Initial mode uses short excerpts. To request one million characters, set ORYON_LONG_SUFFIX=1 and ORYON_CORPUS_PATH to a local UTF-8 file of known provenance, up to 64 MiB and with at least 1,000,050 code points after normalization. The first million is used for train and the next 50 for exploratory test; the cell calculates the file hash. It downloads no data and uses no report files.

Construction sorts indices and ranks instead of materializing all suffixes. As a base, a single-discount KN5 with 1% uniform is trained only on the first 20,000 training characters; it is mixed with the index at weight 0.5. Perplexity counts EOS and may correspond to a sequence containing <unk>. This is a bounded example, not the production infini-gram system. Large construction consumes memory proportional to text size and timings depend on hardware.

[ ]Suffix index and KN5 mixtureLocal GPU
"""Índice de sufijos y mezcla con KN5, práctica local de memoria acotada.

Requiere NumPy. El modo inicial usa dos fragmentos breves atribuidos a Miguel
de Cervantes, Don Quijote, primera parte, capítulos I y II, edición Project
Gutenberg 2000, https://www.gutenberg.org/files/2000/2000-0.txt . Consulta
https://www.gutenberg.org/policy/license.html antes de redistribuir. Para un
millón de caracteres fija ORYON_LONG_SUFFIX=1 y ORYON_CORPUS_PATH a un archivo
UTF-8 local de procedencia conocida con al menos 1 000 050 caracteres tras NFC
y minúsculas y un máximo de 64 MiB. La descarga no se realiza automáticamente. Las primeras
1 000 000 posiciones son train y las siguientes 50 son test exploratorio.

La construcción usa prefix doubling y arrays de trabajo de tamaño O(N) por
pasada, con coste de ordenación dependiente de NumPy; no copia todos los sufijos.
El KN5 se ajusta con un prefijo declarado de 20 000 caracteres de entrenamiento
para limitar RAM. Los tiempos son mediciones locales bajo carga compartida.
"""
import hashlib
import math
import os
import time
import unicodedata
from collections import Counter, defaultdict
from pathlib import Path

import numpy as np

TRAIN_SMALL = 'En un lugar de la Mancha, de cuyo nombre no quiero acordarme'
TEST_SMALL = 'Hechas, pues, estas prevenciones, no quiso aguardar más tiempo'
BOS, EOS, UNK = '\x03', '\x02', '\x04'
RESERVED = {BOS, EOS, UNK}


def normalize(text):
    return unicodedata.normalize('NFC', text).lower()


def suffix_array(text):
    n = len(text)
    if not n:
        raise ValueError('Texto vacío')
    codes = np.fromiter((ord(c) for c in text), dtype=np.int32, count=n)
    _, ranks = np.unique(codes, return_inverse=True)
    ranks = ranks.astype(np.int32) + 1  # cero es el centinela fuera del texto
    del codes
    step = 1
    while step < n:
        right = np.zeros(n, dtype=np.int32)
        right[:-step] = ranks[step:]
        order = np.lexsort((right, ranks))
        left_sorted, right_sorted = ranks[order], right[order]
        starts = np.empty(n, dtype=np.bool_)
        starts[0] = True
        starts[1:] = ((left_sorted[1:] != left_sorted[:-1]) |
                      (right_sorted[1:] != right_sorted[:-1]))
        new_ranks = np.empty(n, dtype=np.int32)
        new_ranks[order] = np.cumsum(starts, dtype=np.int32)
        ranks = new_ranks
        if int(ranks[order[-1]]) == n:
            return order
        step *= 2
    return np.argsort(ranks)


def matches(text, suffixes, needle):
    length = len(needle)
    def bound(upper):
        lo, hi = 0, len(suffixes)
        while lo < hi:
            mid = (lo + hi) // 2
            prefix = text[int(suffixes[mid]):int(suffixes[mid]) + length]
            if prefix < needle or (upper and prefix == needle):
                lo = mid + 1
            else:
                hi = mid
        return lo
    return suffixes[bound(False):bound(True)]


def infini_distribution(text, suffixes, history):
    # text termina con EOS. Nunca se consultan cadenas que incluyan EOS.
    for length in range(len(history), -1, -1):
        query = history[-length:] if length else ''
        starts = matches(text, suffixes, query)
        counts = Counter(text[int(i) + length] for i in starts if int(i) + length < len(text))
        if counts:
            total = sum(counts.values())
            return {token: count / total for token, count in counts.items()}, length + 1
    raise ValueError('No hay ninguna continuación válida')


def events(text, n):
    context = [BOS] * (n - 1)
    for token in text + EOS:
        yield tuple(context), token
        if n > 1:
            context = (context + [token])[-(n - 1):]


class KN5:
    def __init__(self, train, vocabulary, discount=.5, epsilon=.01):
        if not train or not 0 <= discount <= 1 or not 0 < epsilon <= 1:
            raise ValueError('Configuración inválida')
        self.vocab = tuple(sorted(vocabulary))
        self.discount, self.epsilon = discount, epsilon
        raw = {}
        for n in range(1, 6):
            table = defaultdict(Counter)
            for context, token in events(train, n):
                table[context][token] += 1
            raw[n] = table
        self.tables = {5: raw[5]}
        for n in range(1, 5):
            seen = defaultdict(set)
            for context, successors in raw[n + 1].items():
                for token in successors:
                    seen[(context[1:], token)].add(context[0])
            table = defaultdict(Counter)
            for (context, token), previous in seen.items():
                table[context][token] = len(previous)
            self.tables[n] = table

    def prob(self, history, token, n=5):
        if token not in self.vocab:
            token = UNK
        if n == 1:
            row = self.tables[1].get((), Counter())
            total = sum(row.values())
            p = row[token] / total if total else 1 / len(self.vocab)
            return (1 - self.epsilon) * p + self.epsilon / len(self.vocab)
        padded = [BOS] * max(0, n - 1 - len(history)) + list(history[-(n - 1):])
        row = self.tables[n].get(tuple(padded), Counter())
        total = sum(row.values())
        if not total:
            return self.prob(history, token, n - 1)
        return (max(row[token] - self.discount, 0) / total +
                self.discount * len(row) / total * self.prob(history, token, n - 1))


def self_check():
    toy = 'banana' + EOS
    suffixes = suffix_array(toy)
    assert suffixes.tolist() == sorted(range(len(toy)), key=lambda i: toy[i:])
    for needle in ('', 'a', 'ana', 'nana', 'x'):
        actual = sorted(int(i) for i in matches(toy, suffixes, needle))
        expected = [i for i in range(len(toy)) if toy.startswith(needle, i)]
        assert actual == expected
    dist, effective_n = infini_distribution(toy, suffixes, 'ana')
    assert effective_n == 4 and math.isclose(sum(dist.values()), 1.)
    model = KN5('banana', set('banana') | {EOS, UNK})
    for history in ('', 'ba', 'xyz'):
        assert math.isclose(sum(model.prob(history, word) for word in model.vocab), 1., abs_tol=1e-10)


def main():
    self_check()
    if os.environ.get('ORYON_LONG_SUFFIX') == '1':
        path = os.environ.get('ORYON_CORPUS_PATH')
        if not path:
            raise ValueError('Falta ORYON_CORPUS_PATH para el modo de un millón')
        with Path(path).open('rb') as source_file:
            raw = source_file.read(64 * 1024 * 1024 + 1)
        if len(raw) > 64 * 1024 * 1024:
            raise ValueError('El archivo supera el límite de 64 MiB')
        digest = hashlib.sha256(raw).hexdigest()
        text = normalize(raw.decode('utf-8-sig'))
        if len(text) < 1_000_050:
            raise ValueError('El archivo no contiene 1 000 050 caracteres normalizados')
        train, test = text[:1_000_000], text[1_000_000:1_000_050]
        source = {'path': path, 'sha256': digest, 'bytes': len(raw)}
    else:
        train, test = normalize(TRAIN_SMALL), normalize(TEST_SMALL)
        source = {'source': 'Project Gutenberg 2000, fragmentos breves'}
    if RESERVED.intersection(train + test):
        raise ValueError('El texto contiene un carácter reservado')
    vocabulary = set(train) | {EOS, UNK}
    mapped_test = ''.join(token if token in vocabulary else UNK for token in test)
    indexed = train + EOS
    start = time.perf_counter()
    suffixes = suffix_array(indexed)
    build_time = time.perf_counter() - start
    base_train = train[:20_000]
    model = KN5(base_train, vocabulary)
    mixture_weight = .5
    losses = []
    effective_orders = []
    query_start = time.perf_counter()
    for i, token in enumerate(mapped_test + EOS):
        history = mapped_test[:i]
        distribution, n = infini_distribution(indexed, suffixes, history)
        p = mixture_weight * distribution.get(token, 0.) + (1 - mixture_weight) * model.prob(history, token)
        if not math.isfinite(p) or p <= 0 or p > 1 + 1e-12:
            raise ValueError('Probabilidad de mezcla inválida')
        losses.append(-math.log(p))
        effective_orders.append(n)
    elapsed = time.perf_counter() - query_start
    print('Fuente:', source, '| NumPy:', np.__version__)
    print('Train:', len(train), '| test exploratorio:', len(test), '| train KN5:', len(base_train))
    print('OOV de caracteres:', sum(a != b for a, b in zip(test, mapped_test)))
    print('Construcción del índice en segundos:', build_time, '| evaluación en segundos:', elapsed)
    print('Órdenes efectivos:', effective_orders)
    print('Perplejidad por evento de la mezcla, incluido EOS:', math.exp(sum(losses) / len(losses)))
    print('Base KN5 con d=0,5 y 1 % uniforme; peso de infini =', mixture_weight)
    print('Tiempos orientativos, no comparables con el sistema infini-gram de producción.')


if __name__ == '__main__':
    main()
This cell needs the local lab (PyTorch with your GPU). Start it with npm run lab and open the connection link.

Comparison with NLTK

You need nltk installed locally. This cell compares rows and scores of a custom Kneser-Ney bigram with KneserNeyInterpolated, aligning vocabulary and BOS and EOS markers; it checks training, test, absent context and OOV. It uses a single discount and continuation base without uniform mixture, and all of TRAIN: these differ from the previous MKN lab, which reserves validation and adds uniform support. Their values therefore need not match.

The cell also displays sums of StupidBackoff scores without calculating perplexity from them. Short excerpts only verify the pipeline.

[ ]KN and Stupid Backoff comparisonLocal GPU
"""Contraste autocontenido de KN bigrama y Stupid Backoff con nltk.lm.

Necesita NLTK en el entorno local. Fragmentos de Don Quijote, Miguel de
Cervantes, primera parte, capítulos I y II, edición Project Gutenberg 2000:
https://www.gutenberg.org/files/2000/2000-0.txt . La ficha declara dominio
público en EE. UU.; consulta https://www.gutenberg.org/policy/license.html
y la legislación aplicable. Se pueden pegar capítulos completos en TRAIN y TEST.
La muestra breve solo verifica el recorrido y el test se considera exploratorio.
Este contraste usa todo TRAIN, descuento único y base de continuación sin
suavizado uniforme; no reproduce la división train/validación ni la base
extendida del laboratorio MKN anterior.
"""
import math
import re
import unicodedata
from collections import Counter, defaultdict

import nltk
from nltk.lm import KneserNeyInterpolated, StupidBackoff, Vocabulary

TRAIN = 'En un lugar de la Mancha, de cuyo nombre no quiero acordarme'
TEST = 'Hechas, pues, estas prevenciones, no quiso aguardar más tiempo'
PATTERN = re.compile(r"\w+(?:['’]\w+)*|[^\w\s]", re.UNICODE)


def tokenize(text):
    return PATTERN.findall(unicodedata.normalize('NFC', text).lower())


def bigram_events(sentence):
    context = '<s>'
    for word in [*sentence, '</s>']:
        yield context, word
        context = word


class KNBigram:
    def __init__(self, sentence, discount=.5):
        if not sentence or not 0 <= discount <= 1:
            raise ValueError('Corpus vacío o descuento fuera de rango')
        self.discount = discount
        self.vocab = set(sentence) | {'</s>', '<unk>'}
        self.rows = defaultdict(Counter)
        for context, word in bigram_events(sentence):
            self.rows[context][word] += 1
        types = {(context, word) for context, row in self.rows.items() for word in row}
        self.cont = Counter(word for _, word in types)
        self.types = len(types)

    def prob(self, word, context):
        word = word if word in self.vocab else '<unk>'
        context = context if context in self.vocab or context == '<s>' else '<unk>'
        base = self.cont[word] / self.types
        row = self.rows.get(context)
        if not row:
            return base
        count = sum(row.values())
        return max(row[word] - self.discount, 0) / count + self.discount * len(row) / count * base


def fit_nltk(sentence, vocabulary, discount):
    # Unigramas sin BOS y bigramas con un BOS y un EOS exactamente.
    grams = [(word,) for word in [*sentence, '</s>']] + list(bigram_events(sentence))
    symbols = sorted(vocabulary | {'<s>', '</s>', '<unk>'})
    kn = KneserNeyInterpolated(2, discount=discount,
                               vocabulary=Vocabulary(symbols, unk_label='<unk>'))
    sb = StupidBackoff(alpha=.4, order=2,
                       vocabulary=Vocabulary(symbols, unk_label='<unk>'))
    kn.fit([grams])
    sb.fit([grams])
    return kn, sb


def evaluate(sentence, probability):
    loss = 0.
    for i, (context, word) in enumerate(bigram_events(sentence), 1):
        p = probability(word, context)
        if not math.isfinite(p) or p < 0 or p > 1:
            raise ValueError('Probabilidad inválida')
        if p == 0:
            return {'events_until_zero': i, 'perplexity': math.inf}
        loss -= math.log(p)
    return {'events': len(sentence) + 1, 'perplexity': math.exp(loss / (len(sentence) + 1))}


def main():
    train, test = tokenize(TRAIN), tokenize(TEST)
    own = KNBigram(train, discount=.5)
    kn, sb = fit_nltk(train, own.vocab, discount=.5)
    contexts = sorted(set(own.rows) | {'<unk>'})
    vocabulary = sorted(own.vocab)
    print('Versión NLTK:', nltk.__version__, '| descuento único:', own.discount)
    print('Comparación KN normalizada, incluyendo EOS y UNK:')
    for context in contexts:
        own_row = [own.prob(word, context) for word in vocabulary]
        nltk_row = [kn.score(word, [context]) for word in vocabulary]
        assert math.isclose(sum(own_row), 1., abs_tol=1e-10)
        assert math.isclose(sum(nltk_row), 1., abs_tol=1e-10)
        for word, expected, actual in zip(vocabulary, own_row, nltk_row):
            assert math.isclose(expected, actual, abs_tol=1e-12, rel_tol=1e-12), (context, word, expected, actual)
        sb_total = sum(sb.score(word, [context]) for word in vocabulary)
        print('contexto', repr(context), 'suma KN', sum(nltk_row), 'suma puntuaciones SB', sb_total)
    # Además de UNK explícito, comprueba el mapeo de OOV crudos en ambos ejes.
    for context in ('<s>', '<unk>', 'contexto-no-visto'):
        for word in ('<unk>', 'palabra-no-vista', train[0], '</s>'):
            assert math.isclose(own.prob(word, context), kn.score(word, [context]),
                                abs_tol=1e-12, rel_tol=1e-12), (context, word)
    for name, sentence in [('train', train), ('test exploratorio', test)]:
        own_metrics = evaluate(sentence, own.prob)
        nltk_metrics = evaluate(sentence, lambda word, context: kn.score(word, [context]))
        assert own_metrics.keys() == nltk_metrics.keys()
        for key in own_metrics:
            expected, actual = own_metrics[key], nltk_metrics[key]
            assert expected == actual or math.isclose(expected, actual, rel_tol=1e-12, abs_tol=1e-12), (name, key, expected, actual)
        if name == 'train':
            assert math.isfinite(own_metrics['perplexity'])
        print(name, 'KN:', own_metrics, '| NLTK:', nltk_metrics)
    print('Stupid Backoff no está normalizado: no se calcula perplejidad con sus puntuaciones.')
    print('Esta comparación usa descuento único, no la variante modificada de tres descuentos.')


if __name__ == '__main__':
    main()
This cell needs the local lab (PyTorch with your GPU). Start it with npm run lab and open the connection link.

When comparing implementations, align vocabulary, tokenization, boundaries, empty context and base. In the documented version, NLTK KneserNeyInterpolated uses a single discount, default 0.1; it is not automatically the modified three-discount variant. Compare its scores with the custom case using the same convention. With StupidBackoff, inspect score sums rather than treating its output as valid perplexity.

Exercises

NumericMass without a name yet
A corpus has 50,000 observations and 3,000 types appear once. What aggregate unseen mass does Good-Turing estimate?
NumericAdjust a singleton
In the same corpus N₁ = 3,000 and N₂ = 1,100. According to raw Good-Turing, what adjusted count corresponds to a type observed once?
ProofEvery unit of mass has a destination
Prove: Show that the interpolated Kneser-Ney bigram sums to one for an observed context.
0
Assume C(h)>0, integer counts, 0≤d≤1 and a continuation base normalized over the output vocabulary.

Step 1 of 3. If T(h) is the number of distinct successors, how much mass does discounting remove from the MLE part?

NumericFrequency and context variety
A corpus of eight bigrams contains four occurrences of (de, york) and one each of (de, casa), (a, casa), (en, casa) and (por, casa). What is P_cont(york), using distinct predecessors?
NumericThe other continuation
In the previous exercise's eight-bigram corpus, what is P_cont(casa)?
CodeContinuation and discounting
Implement continuation_prob(word, bigrams) and kn_bigram(word, prev, bigrams, d). bigrams is a nonempty list of (predecessor, successor) pairs, with repetitions. The base uses distinct predecessor count over distinct bigram count. For observed context apply interpolated absolute discounting with 0≤d≤1; for absent context return the base. Reject an empty corpus and out-of-range discounts with ValueError.
def continuation_prob(word, bigrams):
  pass

def kn_bigram(word, prev, bigrams, d):
  pass
Shift+Enter to run
QuizA useful score need not sum to one
What does Stupid Backoff's usefulness as a feature in a translation system allow us to claim?
Key idea
Smoothing means choosing where mass comes from and where it goes. A reliable count-based method states its support, boundaries, empty contexts and normalization before comparing predictions.