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.
Add pseudocounts
For a finite output vocabulary with symbols and , additive smoothing uses
Each row sums to one. If the context is absent, the formula returns the uniform distribution. With a symmetric Dirichlet prior of parameter 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 continuations appear after , mass assigned to the rest is . With many possible symbols and little data it can dominate the row, especially for . 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 be the number of types observed exactly times and the number of observations. Total mass of unseen types is estimated by . For a type observed times, the classical adjusted count is
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 , the raw estimate cannot be assigned within that support: a different consistent convention is needed, not division by zero.
In the tail, is noisy; 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.
Mix orders or back off
Jelinek-Mercer interpolation combines a long-context distribution with a shorter-context one:
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 by maximizing validation likelihood. In a two-component mixture, the higher-order component’s responsibility for an event is (“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 is the seen-successor set and assigns them nonnegative mass summing to at most one, the constant for remaining continuations is
The denominator is mass the base assigns to unseen continuations after . 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 . Backing off without this adjustment changes the row sum.
One way to choose Katz discounts starts with global frequencies of n-grams at the considered order. With cutoff , for calculate and factor using Good-Turing’s . For 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 from every positive count and distributes the released mass to a lower-order model. For positive integer counts, 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.
For bigrams, let be the number of distinct predecessors of and the total number of distinct bigrams. Then
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 , let be the number of distinct successors. With ,
Each observed successor loses , so the direct part sums to . The second part sums to because is normalized; the full row sums to one. For 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 , and for counts 1, 2 and at least 3. Their 1998 report presents estimators in terms of frequency-of-frequency statistics appropriate to each level:
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 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.
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.
"""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.
"""Í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()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.
"""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()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
Step 1 of 3. If T(h) is the number of distinct successors, how much mass does discounting remove from the MLE part?
def continuation_prob(word, bigrams):
pass
def kn_bigram(word, prev, bigrams, d):
pass