Skip to content

HEvaluate predictions · evaluate.perplexity

N-gram language model perplexity

How predictable is held-out text under a smoothed n-gram language model, and how much does a longer context help?

Fits a word n-gram language model to the training rows of a text column and scores the held-out rows: perplexity (how many equally likely words the model is choosing between, on average), cross-entropy in bits per word and the share of unknown words, for every order up to the one you pick. Interpolated Kneser–Ney or modified Kneser–Ney smoothing (discounts estimated from the counts), or add-one Laplace for comparison; a bootstrap over held-out rows gives an interval. Identical in Python and R; R's kgrams package is the oracle. GPT-2 small, a pretrained language model that runs on this computer after a one-time download, can score the text instead (perplexity per token), with the Min-K% Prob check for text the model may have seen in training.

Not verified yet Python and R agree to 10 decimals Seeded Also called perplexity, language model, n-gram model…

A real result

Example “Mkn trigram split”, recorded in both engines. In the app, “Try this example” loads it into Analyze.

N-gram language model perplexityRecorded · Python and R agreeRecorded 2026-11-25 · 29 values compared
R

3-gram modified Kneser–Ney: perplexity 11.6 on 15 held-out rows (3.54 bits per word).

Held-out perplexity
11.598
Bits per word
3.536
Training perplexity
5.560
Unknown-word rate
0.4875
Vocabulary
77

Plots

Perplexity by n-gram orderHow does the series move over time, and where is an estimated break?

Lower is better. A gap that grows with the order means longer contexts are memorized rather than learned.

View data
RowsN-gram orderPerplexity
Training126.124
Training210.443
Training35.560
Held out115.336
Held out212.849
Held out311.598

Assumptions

  • Scored on held-out rows — Scored on 15 held-out rows marked "test" in split; the training rows never include them.
  • Same words and vocabulary — 48.8% of held-out words are unknown (<unk>, minimum count 2). Compare perplexities only between models with the same tokens and unknown-word rule.
  • Rows are independent — The interval resamples whole rows; repeated or threaded rows make it too narrow.

Perplexity by order

OrderTraining perplexityHeld-out perplexity
126.12415.336
210.44312.849
35.56011.598

Least predictable held-out rows

RowWordsUnknownBits per word
441034.863
48954.648
60834.635
121364.102
56943.879
401033.832
321263.594
81053.484
521063.386
41263.284
  • 1 rows have no text or no training/test label (or no words) and are left out.
  • 49% of held-out words are unknown to the model; perplexity looks better than it would with a full vocabulary.
  • Training perplexity (5.6) is far below held-out perplexity (11.6): the model has memorized the training rows.
Python

3-gram modified Kneser–Ney: perplexity 11.6 on 15 held-out rows (3.54 bits per word).

Held-out perplexity
11.598
Bits per word
3.536
Training perplexity
5.560
Unknown-word rate
0.4875
Vocabulary
77

To keep this page light, the plots are shown once, under the R tab.

Assumptions

  • Scored on held-out rows — Scored on 15 held-out rows marked "test" in split; the training rows never include them.
  • Same words and vocabulary — 48.8% of held-out words are unknown (<unk>, minimum count 2). Compare perplexities only between models with the same tokens and unknown-word rule.
  • Rows are independent — The interval resamples whole rows; repeated or threaded rows make it too narrow.

Perplexity by order

OrderTraining perplexityHeld-out perplexity
126.12415.336
210.44312.849
35.56011.598

Least predictable held-out rows

RowWordsUnknownBits per word
441034.863
48954.648
60834.635
121364.102
56943.879
401033.832
321263.594
81053.484
521063.386
41263.284
  • 1 rows have no text or no training/test label (or no words) and are left out.
  • 49% of held-out words are unknown to the model; perplexity looks better than it would with a full vocabulary.
  • Training perplexity (5.6) is far below held-out perplexity (11.6): the model has memorized the training rows.

Do it in CodeSplash Run it on your own data, in Python or R, with the code to prove it.

Worked examples in the app

  • Mkn trigram splittxt1_lm · split: split · text: text
  • Kn bigram random holdouttxt1_lm · text: text
  • Laplace unigramtxt1_lm · split: split · text: text
  • Mkn 4gram whitespace caseml_corpus · text: text
  • Kn topics min3ml_topics · text: text
  • Theme as splittxt1_lm · split: theme · text: text
  • Gpt2 splittxt1_lm · split: split · text: text
  • Gpt2 all rows min ktxt2_reviews · text: review text

In the guides

Where it sits in the decision guides

  • Multimodal data exploration (text, image, video) · DS & ML Decision Guide · Describe — summarize and visualize
  • Generate: quality (human or automated); relevance, safety, bias; task-specific metrics (BLEU, ROUGE, LLM-as-judge) · DS & ML Decision Guide · How to evaluate — common metrics by question type

What you need

Textcategorical · 1 column
The text column; each row is one document or sentence. Rows with no words are left out.
Training or test (optional)categorical · 0–1 column
Which rows are held out: rows whose value is the test label below are scored, the rest train the model. Without it a random share is held out.

Choices you make

model

Language modeldefault ngram

Which model scores the text: an n-gram model fitted to your training rows here, or GPT-2 small, a pretrained model that runs on this computer after a one-time download you approve.

  • N-gram model (fitted here)(default) — Counts word sequences in the training rows and scores the held-out rows; perplexity per word.
  • GPT-2 small (pretrained, ~548 MB) — OpenAI's 124-million-parameter English language model (MIT license); nothing is fitted to your rows. Perplexity per GPT-2 token, plus Min-K%.
N-gram orderdefault 3

How many words the model looks at: 1 = single words, 2 = word pairs, 3 = the two previous words. Every lower order is shown too.

Smoothingdefault modified_kn

How probability is moved from seen word sequences to unseen ones. Modified Kneser–Ney is the standard choice.

  • Modified Kneser–Ney(default) — Three discounts per order (for sequences seen once, twice, three or more times), estimated from the counts (Chen & Goodman 1999).
  • Kneser–Ney — One discount per order, D = n1 / (n1 + 2 n2), from the counts of sequences seen once and twice.
  • Add-one (Laplace) — Adds one to every count at the chosen order. Simple but gives far too much weight to unseen words; shown for comparison.

preprocess

Minimum word countdefault 2

Training words seen fewer times become <unk>, so the model learns how often unknown words appear.

Wordsdefault words

How text is split into words before counting.

  • Runs of letters and digits(default) — Punctuation is dropped; "don't" becomes "don" and "t".
  • Split on spaces — Keeps punctuation attached; use it for text that was tokenized before it reached the app.
Ignore casedefault on

Lower-case the text first, so "The" and "the" are one word.

statistics

Held-out sharedefault 0.2

Without a training/test column: the share of rows held out at random (at least one row on each side).

Test labeldefault test

With a training/test column: the value that marks held-out rows. Every other value trains the model.

Bootstrap resamplesdefault 1000

Held-out rows resampled with replacement for the perplexity interval. 0 skips it.

Confidence leveldefault 0.95

How sure the bootstrap interval should be: 0.95 gives a 95% interval.

Min-K% sharedefault 20

Min-K% Prob averages each text's least likely tokens, this share of them; text GPT-2 saw in training scores higher (closer to 0).

Checks and remedies

CodeSplash checks each testable assumption on every run and shows the result on the card; premises the data can’t test are marked. If a check fails, these are the ways forward.

  • Scored on held-out rows

    Perplexity on the training rows always looks better; only rows the model never saw say how well it predicts new text.

  • Same words and vocabulary

    Perplexities are comparable only with the same tokens, case handling and unknown-word rule; many unknown words make perplexity look better than it is.

  • Rows are independent

    The interval resamples rows; rows that repeat each other (copies, threads) make it too narrow.

What it reports

n_train
Rows that fitted the model and rows it was scored on; rows with no words or no training/test label are left out.
n_test
Rows that fitted the model and rows it was scored on; rows with no words or no training/test label are left out.
n_dropped
Rows that fitted the model and rows it was scored on; rows with no words or no training/test label are left out.
train_tokens
Words in the training and held-out rows after splitting; each row also predicts one end-of-row token.
test_tokens
Words in the training and held-out rows after splitting; each row also predicts one end-of-row token.
vocab_size
Training words seen at least the minimum count; every other word becomes <unk>.
oov_rate
Share of held-out words the model maps to <unk> because they were rare or absent in training.
order
A probability for the next word given the words before it; an n-gram model looks back n − 1 words.
smoothing
Subtracts a discount from every seen count and gives the mass to a lower order built from how many contexts a word follows.
perplexity
exp of the average negative log probability per word: how many equally likely words the model is choosing between.
perplexity_ci_low
Bootstrap percentile interval of held-out perplexity from resampling whole held-out rows.
perplexity_ci_high
Bootstrap percentile interval of held-out perplexity from resampling whole held-out rows.
cross_entropy
log₂ of perplexity: the average number of bits needed to encode each held-out word with the model.
train_perplexity
Perplexity on the rows the model was fitted to; always flattering. A big gap to held-out perplexity means memorizing.

Per group, level or term: lm_<statistic>, perplexity[<order>], train_perplexity[<order>], discount[<order>], discount1[<order>], discount2[<order>], discount3[<order>]

Python and R

Python and R agree to 10 decimals (relative tolerance 1e-10). Python uses pandas, numpy, codesplash; R uses nanoparquet, codesplashr.

Default traps between the two languages

  • Both engines run the same twins (codesplash.text.ngram_lm ↔ codesplashr R/text_ngram_lm.R) and draw the held-out rows and bootstrap resamples from the shared Wichmann–Hill stream. R's kgrams package is the oracle for the Kneser–Ney, modified Kneser–Ney and add-one probabilities (tests/crosscheck/w5txt1_ngram.R).
  • Case folding uses each language's own lower-casing (Python str.lower, R tolower), which agree on Latin, Greek and Cyrillic letters; rare special cases such as the German ẞ can differ.
  • GPT-2 small (1.1.0) runs the same float64 twins in both engines (codesplash.text.gpt2 ↔ R/text_gpt2.R; byte-level BPE codesplash.text.bpe ↔ R/text_bpe.R); token log-probabilities match transformers' GPT2LMHeadModel in float64 and each other to about 1e-13 (tests/crosscheck/w8txt3_gpt2.py), so the tolerances hold. Without the downloaded weights the run stops with CS_WEIGHTS_MISSING in both engines.
Python

The exact script CodeSplash ran for example “Mkn trigram split” · Python 3.13.5 · scipy 1.18.1 · pandas 3.1.0

# N-gram language model perplexity
# Generated by CodeSplash Analytics 1.0.0 on 2026-11-09 · method evaluate.perplexity 1.1.1 · spec 4951b03decd93f98
# Dataset: txt1_lm (version 1)
# Runs on its own: outside the app, cs.publish() writes $CS_RESULT_PATH or prints the result JSON.
# %% Setup
import math
import os

import numpy as np
import pandas as pd

import codesplash as cs
from codesplash import ml as csml
from codesplash.text import metrics as tm
from codesplash.text import ngram_lm as lm

# %% Rows: text present (and a training/test label when that column is used), at least one word
TEXT = "text"
SPLIT = "split"
TOKENS = "words"
LOWER = True
df = pd.read_parquet("tests/parity/fixtures/txt1_lm.parquet", columns=[TEXT] + ([SPLIT] if SPLIT else []))
warnings = []
ok = df[TEXT].notna().to_numpy()
if SPLIT:
    ok = ok & df[SPLIT].notna().to_numpy()
docs_all = [lm.tokenize(t, TOKENS, LOWER) if o else [] for t, o in zip(df[TEXT], ok)]
rows = np.array([i for i in range(len(df)) if ok[i] and len(docs_all[i]) > 0], dtype=int)
n_dropped = len(df) - len(rows)
if n_dropped:
    warnings.append(f"{n_dropped} rows have no text{' or no training/test label' if SPLIT else ''} (or no words) and are left out.")
if not len(rows):
    cs.cs_error("CS_E_NO_ROWS")  # no row has any words
docs = [docs_all[i] for i in rows]

# %% Held-out rows: the test label, or a random share on the shared Wichmann–Hill stream
SEED = 42
if SPLIT:
    TEST_LEVEL = "test"
    is_test = np.array([str(v) == TEST_LEVEL for v in df[SPLIT].iloc[rows]])
    if is_test.all() or not is_test.any():
        cs.cs_error("CS_E_TOO_FEW_GROUPS", column=SPLIT, min=2, k=1)  # needs both training and test rows
else:
    if len(rows) < 2:
        cs.cs_error("CS_E_TOO_FEW_ROWS", what="A held-out perplexity", min=2, n=len(rows))
    is_test = lm.holdout(len(rows), 0.2, SEED)
train_docs = [d for d, t in zip(docs, is_test) if not t]
test_docs = [d for d, t in zip(docs, is_test) if t]

# %% Fit: vocabulary from the training rows, counts and discounts for every order
ORDER = 3
SMOOTHING = "modified_kn"
vocab = lm.vocabulary(train_docs, 2)
train_ids = lm.encode(train_docs, vocab)
test_ids = lm.encode(test_docs, vocab)
model = lm.fit(train_ids, ORDER, SMOOTHING, len(vocab))

# %% Perplexity for every order up to the chosen one (training and held-out rows)
by_order = []
for k in range(1, ORDER + 1):
    tr_lp, tr_n, _ = lm.row_scores(model, train_ids, k)
    te_lp, te_n, te_unk = lm.row_scores(model, test_ids, k)
    by_order.append({"order": k, "train": lm.perplexity(tr_lp, tr_n), "test": lm.perplexity(te_lp, te_n)})
    if k == ORDER:
        lp, n_pred, unk = te_lp, te_n, te_unk

# %% Bootstrap over held-out rows (shared Wichmann–Hill stream)
B = 1000
CONF = 0.95
ppl = by_order[-1]["test"]
lo = hi = None
if B > 0:
    reps = lm.bootstrap_ppl(lp, n_pred, B, SEED + 1)
    lo, hi = tm.percentile_ci(reps, CONF)

# %% Artifacts: one row per input row
out = csml.out_dir("target/academy-parity/run-8142/evaluate.perplexity/mkn_trigram_split/out-python")
tr_lp, tr_n, tr_unk = lm.row_scores(model, train_ids, ORDER)
art_rows, ti, ri = [], 0, 0
for j, r in enumerate(rows):
    if is_test[j]:
        a, m, u, which = lp[ti], n_pred[ti], unk[ti], "test"
        ti += 1
    else:
        a, m, u, which = tr_lp[ri], tr_n[ri], tr_unk[ri], "train"
        ri += 1
    art_rows.append({"row": int(r), "split": which, "tokens": int(m) - 1, "unknown": int(u), "logprob": float(a), "perplexity": math.exp(-float(a) / float(m))})
pd.DataFrame(art_rows).to_parquet(os.path.join(out, "scores.parquet"), index=False)

# %% Result
LABELS = {"modified_kn": "modified Kneser–Ney", "kneser_ney": "Kneser–Ney", "laplace": "add-one (Laplace)"}
test_words = float(np.sum(n_pred) - len(test_ids))
values = {
    "n_train": len(train_ids), "n_test": len(test_ids), "n_dropped": n_dropped,
    "train_tokens": int(sum(len(d) for d in train_ids)), "test_tokens": int(test_words),
    "vocab_size": len(vocab), "oov_rate": float(np.sum(unk)) / test_words,
    "order": ORDER, "smoothing": LABELS[SMOOTHING],
    "perplexity": ppl, "perplexity_ci_low": lo, "perplexity_ci_high": hi,
    "cross_entropy": math.log2(ppl), "train_perplexity": by_order[-1]["train"],
}
for row in by_order:
    values[f"perplexity[{row['order']}]"] = row["test"]
    values[f"train_perplexity[{row['order']}]"] = row["train"]
if SMOOTHING != "laplace":
    for k in range(1, ORDER + 1):
        disc = (model["raw"][k] if k == ORDER else model["cont"][k])["disc"]
        if SMOOTHING == "kneser_ney":
            values[f"discount[{k}]"] = disc[0]
        else:
            values[f"discount1[{k}]"], values[f"discount2[{k}]"], values[f"discount3[{k}]"] = disc

held = f"Scored on {len(test_ids)} held-out rows " + (f'marked "{TEST_LEVEL}" in {SPLIT}' if SPLIT else f"drawn at random ({len(test_ids)} of {len(rows)})") + "; the training rows never include them."
assumptions = [
    {"key": "held_out", "label": "Scored on held-out rows", "status": "pass", "detail": held},
    {"key": "same_vocabulary", "label": "Same words and vocabulary", "status": "warn" if values["oov_rate"] > 0.1 else "info",
     "detail": f"{values['oov_rate']:.1%} of held-out words are unknown (<unk>, minimum count 2). Compare perplexities only between models with the same tokens and unknown-word rule."},
    {"key": "rows_independent", "label": "Rows are independent", "status": "info",
     "detail": "The interval resamples whole rows; repeated or threaded rows make it too narrow."},
]
if values["oov_rate"] > 0.1:
    warnings.append(f"{values['oov_rate']:.0%} of held-out words are unknown to the model; perplexity looks better than it would with a full vocabulary.")
if by_order[-1]["train"] < 0.5 * ppl and ORDER > 1:
    warnings.append(f"Training perplexity ({by_order[-1]['train']:.1f}) is far below held-out perplexity ({ppl:.1f}): the model has memorized the training rows.")

order_rows = [{"order": r["order"], "train": r["train"], "test": r["test"]} for r in by_order]
order_cols = [{"key": "order", "label": "Order", "type": "number"}, {"key": "train", "label": "Training perplexity", "type": "number"}, {"key": "test", "label": "Held-out perplexity", "type": "number"}]
bits = [(-float(a) / float(m)) / math.log(2) for a, m in zip(lp, n_pred)]
test_rows_idx = [int(r) for r, t in zip(rows, is_test) if t]
top = sorted(range(len(bits)), key=lambda i: (-bits[i], i))[:10]
surprise_rows = [{"row": test_rows_idx[i] + 1, "words": int(n_pred[i]) - 1, "unknown": int(unk[i]), "bits": bits[i]} for i in top]
surprise_cols = [{"key": "row", "label": "Row", "type": "number"}, {"key": "words", "label": "Words", "type": "number"},
                 {"key": "unknown", "label": "Unknown", "type": "number"}, {"key": "bits", "label": "Bits per word", "type": "number"}]
xs = [r["order"] for r in by_order] * 2
ys = [r["train"] for r in by_order] + [r["test"] for r in by_order]
gs = ["Training"] * ORDER + ["Held out"] * ORDER
charts = [cs.chart("orders", "series-line", "Perplexity by n-gram order", {
    "x": cs.col("N-gram order", xs, "numeric"),
    "y": cs.col("Perplexity", ys, "numeric"),
    "group": cs.col("Rows", gs, "categorical", ["Training", "Held out"]),
}, note="Lower is better. A gap that grows with the order means longer contexts are memorized rather than learned.")]
cs.publish({
    "title": "N-gram language model perplexity",
    "engine": cs.engine_info("numpy", "pandas"),
    "n": len(rows),
    "summary": f"{ORDER}-gram {LABELS[SMOOTHING]}: perplexity {ppl:.1f} on {len(test_ids)} held-out rows ({math.log2(ppl):.2f} bits per word).",
    "statistics": [
        {"key": "perplexity", "label": "Held-out perplexity", "value": ppl},
        {"key": "cross_entropy", "label": "Bits per word", "value": values["cross_entropy"]},
        {"key": "train_perplexity", "label": "Training perplexity", "value": values["train_perplexity"]},
        {"key": "oov_rate", "label": "Unknown-word rate", "value": values["oov_rate"]},
        {"key": "vocab_size", "label": "Vocabulary", "value": len(vocab)},
    ],
    "tables": [
        {"key": "orders", "title": "Perplexity by order", "columns": order_cols, "rows": order_rows},
        {"key": "surprising", "title": "Least predictable held-out rows", "columns": surprise_cols, "rows": surprise_rows},
    ],
    "assumptions": assumptions,
    "charts": charts,
    "values": values,
    "warnings": warnings,
    "artifacts": [{"key": "scores", "path": os.path.join(out, "scores.parquet"), "format": "parquet"}],
})
R

The exact script CodeSplash ran for example “Mkn trigram split” · R version 4.5.1 (2025-06-13)

# N-gram language model perplexity
# Generated by CodeSplash Analytics 1.0.0 on 2026-11-09 · method evaluate.perplexity 1.1.1 · spec 4951b03decd93f98
# Dataset: txt1_lm (version 1)
# Runs on its own: outside the app, cs_publish() writes $CS_RESULT_PATH or prints the result JSON.

# %% Setup
library(codesplashr)

# %% Rows: text present (and a training/test label when that column is used), at least one word
TEXT <- "text"
SPLIT <- "split"
TOKENS <- "words"
LOWER <- TRUE
df <- as.data.frame(nanoparquet::read_parquet("tests/parity/fixtures/txt1_lm.parquet", col_select = c(TEXT, SPLIT)))
warnings <- list()
ok <- !is.na(df[[TEXT]])
if (!is.null(SPLIT)) ok <- ok & !is.na(df[[SPLIT]])
docs_all <- lapply(seq_len(nrow(df)), function(i) if (ok[i]) cs_lm_tokenize(as.character(df[[TEXT]][i]), TOKENS, LOWER) else character(0))
rows <- which(ok & lengths(docs_all) > 0)
n_dropped <- nrow(df) - length(rows)
if (n_dropped) warnings <- c(warnings, sprintf("%d rows have no text%s (or no words) and are left out.", n_dropped, if (!is.null(SPLIT)) " or no training/test label" else ""))
if (!length(rows)) cs_error("CS_E_NO_ROWS")  # no row has any words
docs <- docs_all[rows]

# %% Held-out rows: the test label, or a random share on the shared Wichmann-Hill stream
SEED <- 42
if (!is.null(SPLIT)) {
  TEST_LEVEL <- "test"
  is_test <- as.character(df[[SPLIT]][rows]) == TEST_LEVEL
  if (all(is_test) || !any(is_test)) cs_error("CS_E_TOO_FEW_GROUPS", column = SPLIT, min = 2, k = 1)  # needs both training and test rows
} else {
  if (length(rows) < 2) cs_error("CS_E_TOO_FEW_ROWS", what = "A held-out perplexity", min = 2, n = length(rows))
  is_test <- cs_lm_holdout(length(rows), 0.2, SEED)
}
train_docs <- docs[!is_test]
test_docs <- docs[is_test]

# %% Fit: vocabulary from the training rows, counts and discounts for every order
ORDER <- 3L
SMOOTHING <- "modified_kn"
vocab <- cs_lm_vocabulary(train_docs, 2)
train_ids <- cs_lm_encode(train_docs, vocab)
test_ids <- cs_lm_encode(test_docs, vocab)
model <- cs_lm_fit(train_ids, ORDER, SMOOTHING, length(vocab))

# %% Perplexity for every order up to the chosen one (training and held-out rows)
by_order <- list()
for (k in seq_len(ORDER)) {
  tr <- cs_lm_row_scores(model, train_ids, k)
  te <- cs_lm_row_scores(model, test_ids, k)
  by_order[[k]] <- list(order = k, train = cs_lm_perplexity(tr$lp, tr$n), test = cs_lm_perplexity(te$lp, te$n))
  if (k == ORDER) { lp <- te$lp; n_pred <- te$n; unk <- te$unk }
}

# %% Bootstrap over held-out rows (shared Wichmann-Hill stream)
B <- 1000
CONF <- 0.95
ppl <- by_order[[ORDER]]$test
lo <- NULL; hi <- NULL
if (B > 0) {
  reps <- cs_lm_bootstrap(lp, n_pred, B, SEED + 1)
  ci <- cs_tm_percentile_ci(reps, CONF)
  lo <- ci[1]; hi <- ci[2]
}

# %% Artifacts: one row per input row
out <- cs_ml_out_dir("target/academy-parity/run-8142/evaluate.perplexity/mkn_trigram_split/out-r")
trs <- cs_lm_row_scores(model, train_ids, ORDER)
ti <- 0L; ri <- 0L
art <- vector("list", length(rows))
for (j in seq_along(rows)) {
  if (is_test[j]) { ti <- ti + 1L; a <- lp[ti]; m <- n_pred[ti]; u <- unk[ti]; which_split <- "test" }
  else { ri <- ri + 1L; a <- trs$lp[ri]; m <- trs$n[ri]; u <- trs$unk[ri]; which_split <- "train" }
  art[[j]] <- data.frame(row = as.integer(rows[j] - 1L), split = which_split, tokens = as.integer(m - 1), unknown = as.integer(u),
                         logprob = a, perplexity = exp(-a / m))
}
nanoparquet::write_parquet(do.call(rbind, art), file.path(out, "scores.parquet"))

# %% Result
LABELS <- c(modified_kn = "modified Kneser–Ney", kneser_ney = "Kneser–Ney", laplace = "add-one (Laplace)")
test_words <- sum(n_pred) - length(test_ids)
values <- list(
  n_train = length(train_ids), n_test = length(test_ids), n_dropped = n_dropped,
  train_tokens = sum(lengths(train_ids)), test_tokens = test_words,
  vocab_size = length(vocab), oov_rate = sum(unk) / test_words,
  order = ORDER, smoothing = unname(LABELS[SMOOTHING]),
  perplexity = ppl, perplexity_ci_low = lo, perplexity_ci_high = hi,
  cross_entropy = log2(ppl), train_perplexity = by_order[[ORDER]]$train
)
for (row in by_order) {
  values[[sprintf("perplexity[%d]", row$order)]] <- row$test
  values[[sprintf("train_perplexity[%d]", row$order)]] <- row$train
}
if (SMOOTHING != "laplace") {
  for (k in seq_len(ORDER)) {
    disc <- (if (k == ORDER) model$raw[[k]] else model$cont[[k]])$disc
    if (SMOOTHING == "kneser_ney") {
      values[[sprintf("discount[%d]", k)]] <- disc[1]
    } else {
      values[[sprintf("discount1[%d]", k)]] <- disc[1]
      values[[sprintf("discount2[%d]", k)]] <- disc[2]
      values[[sprintf("discount3[%d]", k)]] <- disc[3]
    }
  }
}
if (is.null(lo)) { values["perplexity_ci_low"] <- list(NULL); values["perplexity_ci_high"] <- list(NULL) }

held <- paste0(sprintf("Scored on %d held-out rows ", length(test_ids)),
               if (!is.null(SPLIT)) sprintf("marked \"%s\" in %s", TEST_LEVEL, SPLIT) else sprintf("drawn at random (%d of %d)", length(test_ids), length(rows)),
               "; the training rows never include them.")
assumptions <- list(
  list(key = "held_out", label = "Scored on held-out rows", status = "pass", detail = held),
  list(key = "same_vocabulary", label = "Same words and vocabulary", status = if (values$oov_rate > 0.1) "warn" else "info",
       detail = sprintf("%.1f%% of held-out words are unknown (<unk>, minimum count 2). Compare perplexities only between models with the same tokens and unknown-word rule.", 100 * values$oov_rate)),
  list(key = "rows_independent", label = "Rows are independent", status = "info",
       detail = "The interval resamples whole rows; repeated or threaded rows make it too narrow.")
)
if (values$oov_rate > 0.1) warnings <- c(warnings, sprintf("%.0f%% of held-out words are unknown to the model; perplexity looks better than it would with a full vocabulary.", 100 * values$oov_rate))
if (by_order[[ORDER]]$train < 0.5 * ppl && ORDER > 1) {
  warnings <- c(warnings, sprintf("Training perplexity (%.1f) is far below held-out perplexity (%.1f): the model has memorized the training rows.", by_order[[ORDER]]$train, ppl))
}

order_rows <- lapply(by_order, function(r) list(order = r$order, train = r$train, test = r$test))
order_cols <- list(list(key = "order", label = "Order", type = "number"), list(key = "train", label = "Training perplexity", type = "number"),
                   list(key = "test", label = "Held-out perplexity", type = "number"))
bits <- (-lp / n_pred) / log(2)
test_rows_idx <- rows[is_test]
top <- head(order(-bits, seq_along(bits), method = "radix"), 10)
surprise_rows <- lapply(top, function(i) list(row = as.integer(test_rows_idx[i]), words = as.integer(n_pred[i] - 1), unknown = as.integer(unk[i]), bits = bits[i]))
surprise_cols <- list(list(key = "row", label = "Row", type = "number"), list(key = "words", label = "Words", type = "number"),
                      list(key = "unknown", label = "Unknown", type = "number"), list(key = "bits", label = "Bits per word", type = "number"))
xs <- rep(vapply(by_order, function(r) r$order, numeric(1)), 2)
ys <- c(vapply(by_order, function(r) r$train, numeric(1)), vapply(by_order, function(r) r$test, numeric(1)))
gs <- c(rep("Training", ORDER), rep("Held out", ORDER))
charts <- list(cs_chart("orders", "series-line", "Perplexity by n-gram order", list(
  x = cs_col("N-gram order", xs, "numeric"),
  y = cs_col("Perplexity", ys, "numeric"),
  group = cs_col("Rows", gs, "categorical", c("Training", "Held out"))
), note = "Lower is better. A gap that grows with the order means longer contexts are memorized rather than learned."))
cs_publish(list(
  title = "N-gram language model perplexity",
  engine = cs_engine_info("codesplashr", "nanoparquet"),
  n = length(rows),
  summary = sprintf("%d-gram %s: perplexity %.1f on %d held-out rows (%.2f bits per word).", ORDER, LABELS[[SMOOTHING]], ppl, length(test_ids), log2(ppl)),
  statistics = list(
    list(key = "perplexity", label = "Held-out perplexity", value = ppl),
    list(key = "cross_entropy", label = "Bits per word", value = values$cross_entropy),
    list(key = "train_perplexity", label = "Training perplexity", value = values$train_perplexity),
    list(key = "oov_rate", label = "Unknown-word rate", value = values$oov_rate),
    list(key = "vocab_size", label = "Vocabulary", value = length(vocab))
  ),
  tables = list(
    list(key = "orders", title = "Perplexity by order", columns = order_cols, rows = order_rows),
    list(key = "surprising", title = "Least predictable held-out rows", columns = surprise_cols, rows = surprise_rows)
  ),
  assumptions = assumptions,
  charts = charts,
  values = values,
  warnings = warnings,
  artifacts = list(list(key = "scores", path = file.path(out, "scores.parquet"), format = "parquet"))
))

Sources

  • Kneser R, Ney H (1995). Improved backing-off for M-gram language modeling. ICASSP 1995, 1, 181–184.
  • Chen SF, Goodman J (1999). An empirical study of smoothing techniques for language modeling. Computer Speech & Language, 13(4), 359–394.
  • Jurafsky D, Martin JH (2025). Speech and Language Processing, 3rd ed. draft, chapter 3: N-gram language models.
  • Gherardi V (2021). kgrams: Classical k-gram language models. R package, CRAN.
  • Radford A, Wu J, Child R, Luan D, Amodei D, Sutskever I (2019). Language models are unsupervised multitask learners. OpenAI technical report (GPT-2).
  • Sennrich R, Haddow B, Birch A (2016). Neural machine translation of rare words with subword units. ACL 2016, 1715–1725 (byte-pair encoding).
  • Shi W, Ajith A, Xia M, Huang Y, Liu D, Blevins T, Chen D, Zettlemoyer L (2024). Detecting pretraining data from large language models. ICLR 2024 (Min-K% Prob).

From the CodeSplash method registry · evaluate.perplexity v1.1.1.