Skip to content

Perplexity, honestly: what a language model score can and can't say

Turn next-token probabilities into cross-entropy and perplexity, put an interval on it, and catch the two traps that make a perplexity look better than it is, unknown words and a different tokenizer. Then score text with a pretrained GPT-2.

Applied ~14 min9 steps

What runs in CodeSplash

You will be able to

  • Compute cross-entropy and perplexity from next-token probabilities
  • Read a held-out perplexity with its interval over resampled rows
  • Explain why a high unknown-word rate can make perplexity look better
  • Say what a pretrained scorer such as GPT-2 measures, and what it doesn't

Read first

01

From probabilities to one number

Read

Score a held-out text token by token. Cross-entropy is the average surprise, the mean negative log-probability the model gave to the tokens that actually came. PerplexityPerplexity (language model)exp of the average negative log probability per word: how many equally likely words the model is choosing between. is its exponential:

H=−1N∑t=1Nlog⁡p(wt∣ht),PPL=eHH = -\frac{1}{N}\sum_{t=1}^{N} \log p(w_t \mid h_t), \qquad \mathrm{PPL} = e^{H}

The reference program scores four tokens that got probabilities between one half and four fifths. Their mean negative log-probability is 0.446 nats, so perplexity is 1.56. Read perplexity k as "as unsure as choosing among k equally likely tokens". With base-2 logs, H is bits per wordBits per wordlog₂ of perplexity: the average number of bits needed to encode each held-out word with the model..

DExplorable · N-gram smoothing and perplexity

Why does a language model need to give probability to word pairs it never saw, and how much?

Sentences

A tiny training set and three held-out sentences.

Model

A unigram ignores context; a bigram conditions on the previous word.

0.10

Pseudo-count added to every possible next word; 0 is maximum likelihood.

  • Held-out sentences
  • Training sentences
Training perplexity
3.30
Held-out perplexity
5.66
Held-out tokens with probability 0
0
Unseen held-out bigrams
4
Probability of the shown pair
0.1038
  • Puzzle: With the bigram model, find a k that gives the lowest held-out perplexity on the sweep.
  • Puzzle: Make the held-out perplexity infinite.
Bigram model with k = 0.10 over 16 vocabulary entries: training perplexity 3.30, held-out perplexity 5.66. The held-out text has 4 word pairs the model never saw, and smoothing gives each of them some probability. Low training perplexity with infinite held-out perplexity is overfitting in its purest form.

Bigram model with k = 0.10 over 16 vocabulary entries: training perplexity 3.30, held-out perplexity 5.66. The held-out text has 4 word pairs the model never saw, and smoothing gives each of them some probability. Low training perplexity with infinite held-out perplexity is overfitting in its purest form.

02

An interval, not a point

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

2-gram Kneser–Ney: perplexity 13.2 on 15 held-out rows (3.72 bits per word).

Held-out perplexity
13.158
Bits per word
3.718
Training perplexity
7.744
Unknown-word rate
0.4356
Vocabulary
76

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
Training124.241
Training27.744
Held out117.129
Held out213.158

Assumptions

  • Scored on held-out rows — Scored on 15 held-out rows drawn at random (15 of 61); the training rows never include them.
  • Same words and vocabulary — 43.6% 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
124.24117.129
27.74413.158

Least predictable held-out rows

RowWordsUnknownBits per word
581144.788
541154.409
60834.301
111234.066
121363.955
261263.923
591143.745
331163.725
231153.692
61363.620
  • 1 rows have no text (or no words) and are left out.
  • 44% of held-out words are unknown to the model; perplexity looks better than it would with a full vocabulary.
The exact R script · R 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 b453844b944cad14
# 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 <- NULL
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.25, SEED)
}
train_docs <- docs[!is_test]
test_docs <- docs[is_test]

# %% Fit: vocabulary from the training rows, counts and discounts for every order
ORDER <- 2L
SMOOTHING <- "kneser_ney"
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 <- 300
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/kn_bigram_random_holdout/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"))
))
Python

2-gram Kneser–Ney: perplexity 13.2 on 15 held-out rows (3.72 bits per word).

Held-out perplexity
13.158
Bits per word
3.718
Training perplexity
7.744
Unknown-word rate
0.4356
Vocabulary
76

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 drawn at random (15 of 61); the training rows never include them.
  • Same words and vocabulary — 43.6% 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
124.24117.129
27.74413.158

Least predictable held-out rows

RowWordsUnknownBits per word
581144.788
541154.409
60834.301
111234.066
121363.955
261263.923
591143.745
331163.725
231153.692
61363.620
  • 1 rows have no text (or no words) and are left out.
  • 44% of held-out words are unknown to the model; perplexity looks better than it would with a full vocabulary.
The exact Python script · Python 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 b453844b944cad14
# 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 = None
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.25, 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 = 2
SMOOTHING = "kneser_ney"
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 = 300
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/kn_bigram_random_holdout/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"}],
})

A bigram Kneser–Ney model held out 15 rows at random. Held-out perplexity is 13.2, with a 95% interval from 10.9 to 15.5. The interval resamples whole rows, because words inside a row aren't independent.

Fifteen short rows give a wide interval. Before calling one model better, check that the gap is larger than this kind of spread, on the same rows.

03

Where an interval comes from

Explore

AExplorable · The bootstrap urn

How can resampling your own data show how much an estimate would vary?

Draw n points with replacement. What share of the original points appears at least once?

0.65
How sure?

Statistic

Data

30
Simulating…

Commit your prediction above to see the result

Make your prediction first; the figure appears when you commit.

Make your prediction to see the result.

Each resample draws rows with replacement from the sample and recomputes the statistic; the spread of those recomputed values is the interval. Lower n and watch the interval widen: with fifteen held-out rows, perplexity's interval is wide for the same reason.

04

The unknown-word trap

Predict

Predict first

Now the model trains on every theme except finance and is scored on the finance rows. A new topic should be harder. What happens to held-out perplexity?

Higher: new topic, new wordsLower, because most new words collapse into one easy unknown tokenAbout the same
Reveal

Lower, and misleadingly so. Most finance words were never seen, so they all become one unknown token that the model learns to expect.

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

2-gram modified Kneser–Ney: perplexity 7.2 on 21 held-out rows (2.85 bits per word).

Held-out perplexity
7.217
Bits per word
2.851
Training perplexity
11.009
Unknown-word rate
0.7824
Vocabulary
76

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
Training128.023
Training211.009
Held out17.616
Held out27.217

Assumptions

  • Scored on held-out rows — Scored on 21 held-out rows marked "finance" in theme; the training rows never include them.
  • Same words and vocabulary — 78.2% 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
128.0237.616
211.0097.217

Least predictable held-out rows

RowWordsUnknownBits per word
48963.907
491073.546
581183.338
511083.041
591172.996
41982.882
45982.882
57972.872
47972.812
541192.726
  • 1 rows have no text or no training/test label (or no words) and are left out.
  • 78% of held-out words are unknown to the model; perplexity looks better than it would with a full vocabulary.
The exact R script · R 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 02a189d606877afe
# 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 <- "theme"
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 <- "finance"
  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 <- 2L
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 <- 100
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/theme_as_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"))
))
Python

2-gram modified Kneser–Ney: perplexity 7.2 on 21 held-out rows (2.85 bits per word).

Held-out perplexity
7.217
Bits per word
2.851
Training perplexity
11.009
Unknown-word rate
0.7824
Vocabulary
76

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

Assumptions

  • Scored on held-out rows — Scored on 21 held-out rows marked "finance" in theme; the training rows never include them.
  • Same words and vocabulary — 78.2% 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
128.0237.616
211.0097.217

Least predictable held-out rows

RowWordsUnknownBits per word
48963.907
491073.546
581183.338
511083.041
591172.996
41982.882
45982.882
57972.872
47972.812
541192.726
  • 1 rows have no text or no training/test label (or no words) and are left out.
  • 78% of held-out words are unknown to the model; perplexity looks better than it would with a full vocabulary.
The exact Python script · Python 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 02a189d606877afe
# 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 = "theme"
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 = "finance"
    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 = 2
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 = 100
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/theme_as_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"}],
})

Perplexity drops to 7.2 while the unknown-word rateUnknown-word rateShare of held-out words the model maps to <unk> because they were rare or absent in training. climbs to 78.2%. Always read perplexity next to the unknown-word rate, and compare only models with the same vocabulary rule.

05

A pretrained model as the scorer

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

GPT-2 small: perplexity 76.7 per token on 15 rows (6.26 bits per token); mean Min-20% log-probability -8.33.

Perplexity per token
76.702
Bits per token
6.261
Perplexity per word
95.290
Mean Min-20% log-probability
−8.332

Plots

Min-20% log-probability per textHow is one numeric variable distributed?

Higher (closer to 0) means GPT-2 finds even the text's least likely tokens predictable, as with text it saw in training.

View data
Min-20% log-probability
−9.521
−9.969
−9.791
−7.793
−9.920
−5.870
−7.779
−6.199
−7.136
−9.309
−6.581
−8.574
−8.269
−9.115
−9.149

Assumptions

  • Scored on held-out rows — GPT-2 small was not fitted to these rows: it was trained on WebText (English web pages, up to 2019). Rows marked "test" in split are summarized; the others are shown as training rows. A text that was in WebText looks more predictable than new text; Min-K% helps spot it.
  • Same words and vocabulary — Perplexity here is per GPT-2 token, so compare it only with other GPT-2 perplexities. Word perplexity (per word, as the Words setting splits text) is closer to an n-gram model's, but not equal.
  • Rows are independent — The interval resamples whole rows; repeated or threaded rows make it too narrow.

Least predictable rows

RowTokensBits per tokenMin-20% log-probability
56107.858−9.115
20117.725−9.920
6097.463−9.149
4127.338−9.521
40116.847−9.309
8106.501−9.969
52106.351−8.269
12136.292−9.791
28126.175−7.779
44106.060−6.581

Most familiar rows (highest Min-K%)

RowTokensMin-20% log-probabilityBits per token
2415−5.8704.697
3212−6.1994.584
4410−6.5816.060
3612−7.1365.510
2812−7.7796.175
1611−7.7935.557
5210−8.2696.351
4810−8.5746.006
5610−9.1157.858
609−9.1497.463
  • 1 rows have no text or no training/test label (or no words) and are left out.
The exact R script · R 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 7221e90eafd4cb1c
# 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]])
words_all <- vapply(seq_len(nrow(df)), function(i) if (ok[i]) length(cs_lm_tokenize(as.character(df[[TEXT]][i]), TOKENS, LOWER)) else 0L, integer(1))
rows <- which(ok & words_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

# %% Rows summarized: those marked with the test label; without a training/test column, every row (nothing is fitted)
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 rows on both sides
} else {
  is_test <- rep(TRUE, length(rows))
}

# %% GPT-2 small (cs_gpt2_* ↔ codesplash.text.gpt2): log-probability of every token after <|endoftext|>
MODEL <- cs_gpt2_load()  # stops with CS_WEIGHTS_MISSING when GPT-2 isn't downloaded
K <- 20
lp_row <- numeric(length(rows)); n_row <- numeric(length(rows)); mk_row <- numeric(length(rows)); cut_row <- logical(length(rows))
for (j in seq_along(rows)) {
  s <- cs_gpt2_token_logprobs(as.character(df[[TEXT]][rows[j]]), MODEL)
  lp_row[j] <- sum(s$lp)
  n_row[j] <- s$n
  mk_row[j] <- cs_gpt2_min_k(s$lp, K)
  cut_row[j] <- s$cut
}
words <- as.numeric(words_all[rows])
te <- is_test; tr <- !is_test
ppl <- cs_lm_perplexity(lp_row[te], n_row[te])
train_ppl <- if (any(tr)) cs_lm_perplexity(lp_row[tr], n_row[tr]) else NULL
n_cut <- sum(cut_row)

# %% Bootstrap over the summarized rows (shared Wichmann-Hill stream)
B <- 200
CONF <- 0.95
lo <- NULL; hi <- NULL
if (B > 0) {
  reps <- cs_lm_bootstrap(lp_row[te], n_row[te], 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/gpt2_split/out-r")
nanoparquet::write_parquet(data.frame(row = as.integer(rows - 1L), split = ifelse(is_test, "test", "train"), tokens = as.integer(n_row),
                                      words = as.integer(words), logprob = lp_row, perplexity = exp(-lp_row / n_row), min_k = mk_row),
                           file.path(out, "scores.parquet"))

# %% Result
values <- list(
  n_train = sum(tr), n_test = sum(te), n_dropped = n_dropped,
  train_tokens = sum(n_row[tr]), test_tokens = sum(n_row[te]),
  vocab_size = NULL, oov_rate = NULL, order = NULL, smoothing = NULL,  # n-gram settings: none for GPT-2
  perplexity = ppl, perplexity_ci_low = lo, perplexity_ci_high = hi, cross_entropy = log2(ppl),
  train_perplexity = train_ppl,
  lm_name = "GPT-2 small", lm_word_perplexity = exp(-sum(lp_row[te]) / sum(words[te])),
  lm_min_k = mean(mk_row[te]), lm_train_min_k = if (any(tr)) mean(mk_row[tr]) else NULL,
  lm_min_k_percent = K, lm_truncated = n_cut
)
for (k in c("vocab_size", "oov_rate", "order", "smoothing", "perplexity_ci_low", "perplexity_ci_high", "train_perplexity", "lm_train_min_k"))
  if (is.null(values[[k]])) values[k] <- list(NULL)
scored <- if (!is.null(SPLIT)) sprintf("Rows marked \"%s\" in %s are summarized; the others are shown as training rows.", TEST_LEVEL, SPLIT) else "Every row is summarized."
assumptions <- list(
  list(key = "held_out", label = "Scored on held-out rows", status = "info",
       detail = sprintf("GPT-2 small was not fitted to these rows: it was trained on WebText (English web pages, up to 2019). %s A text that was in WebText looks more predictable than new text; Min-K%% helps spot it.", scored)),
  list(key = "same_vocabulary", label = "Same words and vocabulary", status = "info",
       detail = "Perplexity here is per GPT-2 token, so compare it only with other GPT-2 perplexities. Word perplexity (per word, as the Words setting splits text) is closer to an n-gram model's, but not equal."),
  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 (n_cut) warnings <- c(warnings, sprintf("%d texts are longer than 1,023 GPT-2 tokens; only their first 1,023 tokens are scored.", n_cut))
bits <- (-lp_row / n_row) / log(2)
idx <- which(te)
top <- head(idx[order(-bits[idx], idx, method = "radix")], 10)
surprise_rows <- lapply(top, function(j) list(row = as.integer(rows[j]), tokens = as.integer(n_row[j]), bits = bits[j], min_k = mk_row[j]))
fam <- head(idx[order(-mk_row[idx], idx, method = "radix")], 10)
familiar_rows <- lapply(fam, function(j) list(row = as.integer(rows[j]), tokens = as.integer(n_row[j]), min_k = mk_row[j], bits = bits[j]))
mk_label <- sprintf("Min-%g%% log-probability", K)
cols <- list(list(key = "row", label = "Row", type = "number"), list(key = "tokens", label = "Tokens", type = "number"),
             list(key = "bits", label = "Bits per token", type = "number"), list(key = "min_k", label = mk_label, type = "number"))
fam_cols <- cols[c(1, 2, 4, 3)]
charts <- list(cs_chart("min_k", "histogram", sprintf("Min-%g%% log-probability per text", K), list(x = cs_col(mk_label, mk_row[te])),
                        note = "Higher (closer to 0) means GPT-2 finds even the text's least likely tokens predictable, as with text it saw in training."))
cs_publish(list(
  title = "N-gram language model perplexity",
  engine = cs_engine_info("codesplashr", "nanoparquet"),
  n = length(rows),
  summary = sprintf("GPT-2 small: perplexity %.1f per token on %d rows (%.2f bits per token); mean Min-%g%% log-probability %.2f.", ppl, sum(te), log2(ppl), K, values$lm_min_k),
  statistics = list(
    list(key = "perplexity", label = "Perplexity per token", value = ppl),
    list(key = "cross_entropy", label = "Bits per token", value = values$cross_entropy),
    list(key = "lm_word_perplexity", label = "Perplexity per word", value = values$lm_word_perplexity),
    list(key = "lm_min_k", label = sprintf("Mean Min-%g%% log-probability", K), value = values$lm_min_k)
  ),
  tables = list(
    list(key = "surprising", title = "Least predictable rows", columns = cols, rows = surprise_rows),
    list(key = "familiar", title = "Most familiar rows (highest Min-K%)", columns = fam_cols, rows = familiar_rows)
  ),
  assumptions = assumptions,
  charts = charts,
  values = values,
  warnings = warnings,
  artifacts = list(list(key = "scores", path = file.path(out, "scores.parquet"), format = "parquet"))
))
Python

GPT-2 small: perplexity 76.7 per token on 15 rows (6.26 bits per token); mean Min-20% log-probability -8.33.

Perplexity per token
76.702
Bits per token
6.261
Perplexity per word
95.290
Mean Min-20% log-probability
−8.332

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

Assumptions

  • Scored on held-out rows — GPT-2 small was not fitted to these rows: it was trained on WebText (English web pages, up to 2019). Rows marked "test" in split are summarized; the others are shown as training rows. A text that was in WebText looks more predictable than new text; Min-K% helps spot it.
  • Same words and vocabulary — Perplexity here is per GPT-2 token, so compare it only with other GPT-2 perplexities. Word perplexity (per word, as the Words setting splits text) is closer to an n-gram model's, but not equal.
  • Rows are independent — The interval resamples whole rows; repeated or threaded rows make it too narrow.

Least predictable rows

RowTokensBits per tokenMin-20% log-probability
56107.858−9.115
20117.725−9.920
6097.463−9.149
4127.338−9.521
40116.847−9.309
8106.501−9.969
52106.351−8.269
12136.292−9.791
28126.175−7.779
44106.060−6.581

Most familiar rows (highest Min-K%)

RowTokensMin-20% log-probabilityBits per token
2415−5.8704.697
3212−6.1994.584
4410−6.5816.060
3612−7.1365.510
2812−7.7796.175
1611−7.7935.557
5210−8.2696.351
4810−8.5746.006
5610−9.1157.858
609−9.1497.463
  • 1 rows have no text or no training/test label (or no words) and are left out.
The exact Python script · Python 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 7221e90eafd4cb1c
# 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 gpt2
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()
words_all = [len(lm.tokenize(t, TOKENS, LOWER)) if o else 0 for t, o in zip(df[TEXT], ok)]
rows = np.array([i for i in range(len(df)) if ok[i] and words_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

# %% Rows summarized: those marked with the test label; without a training/test column, every row (nothing is fitted)
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 rows on both sides
else:
    is_test = np.ones(len(rows), dtype=bool)

# %% GPT-2 small (codesplash.text.gpt2 ↔ codesplashr cs_gpt2_*): log-probability of every token after <|endoftext|>
MODEL = gpt2.Model()  # stops with CS_WEIGHTS_MISSING when GPT-2 isn't downloaded
K = 20
lp_row, n_row, mk_row, cut_row = [], [], [], []
for i in rows:
    t_lp, t_n, t_cut = gpt2.token_logprobs(str(df[TEXT].iloc[i]), MODEL)
    lp_row.append(float(np.sum(t_lp)))
    n_row.append(t_n)
    mk_row.append(gpt2.min_k(t_lp, K))
    cut_row.append(t_cut)
lp_row, n_row, mk_row = np.array(lp_row), np.array(n_row, dtype=float), np.array(mk_row, dtype=float)
words = np.array([words_all[i] for i in rows], dtype=float)
te, tr = is_test, ~is_test
ppl = lm.perplexity(lp_row[te], n_row[te])
train_ppl = lm.perplexity(lp_row[tr], n_row[tr]) if tr.any() else None
n_cut = int(sum(cut_row))

# %% Bootstrap over the summarized rows (shared Wichmann–Hill stream)
B = 200
CONF = 0.95
lo = hi = None
if B > 0:
    reps = lm.bootstrap_ppl(lp_row[te], n_row[te], 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/gpt2_split/out-python")
pd.DataFrame({
    "row": rows.astype(int), "split": np.where(is_test, "test", "train"), "tokens": n_row.astype(int), "words": words.astype(int),
    "logprob": lp_row, "perplexity": np.exp(-lp_row / n_row), "min_k": mk_row,
}).to_parquet(os.path.join(out, "scores.parquet"), index=False)

# %% Result
values = {
    "n_train": int(tr.sum()), "n_test": int(te.sum()), "n_dropped": n_dropped,
    "train_tokens": int(n_row[tr].sum()), "test_tokens": int(n_row[te].sum()),
    "vocab_size": None, "oov_rate": None, "order": None, "smoothing": None,  # n-gram settings: none for GPT-2
    "perplexity": ppl, "perplexity_ci_low": lo, "perplexity_ci_high": hi, "cross_entropy": math.log2(ppl),
    "train_perplexity": train_ppl,
    "lm_name": "GPT-2 small", "lm_word_perplexity": math.exp(-float(np.sum(lp_row[te])) / float(np.sum(words[te]))),
    "lm_min_k": float(np.mean(mk_row[te])), "lm_train_min_k": float(np.mean(mk_row[tr])) if tr.any() else None,
    "lm_min_k_percent": K, "lm_truncated": n_cut,
}
scored = (f'Rows marked "{TEST_LEVEL}" in {SPLIT} are summarized; the others are shown as training rows.' if SPLIT else "Every row is summarized.")
assumptions = [
    {"key": "held_out", "label": "Scored on held-out rows", "status": "info",
     "detail": f"GPT-2 small was not fitted to these rows: it was trained on WebText (English web pages, up to 2019). {scored} A text that was in WebText looks more predictable than new text; Min-K% helps spot it."},
    {"key": "same_vocabulary", "label": "Same words and vocabulary", "status": "info",
     "detail": "Perplexity here is per GPT-2 token, so compare it only with other GPT-2 perplexities. Word perplexity (per word, as the Words setting splits text) is closer to an n-gram model's, but not equal."},
    {"key": "rows_independent", "label": "Rows are independent", "status": "info",
     "detail": "The interval resamples whole rows; repeated or threaded rows make it too narrow."},
]
if n_cut:
    warnings.append(f"{n_cut} texts are longer than 1,023 GPT-2 tokens; only their first 1,023 tokens are scored.")
bits = (-lp_row / n_row) / math.log(2)
idx = [int(j) for j in np.flatnonzero(te)]
top = sorted(idx, key=lambda j: (-bits[j], j))[:10]
surprise_rows = [{"row": int(rows[j]) + 1, "tokens": int(n_row[j]), "bits": float(bits[j]), "min_k": float(mk_row[j])} for j in top]
fam = sorted(idx, key=lambda j: (-mk_row[j], j))[:10]
familiar_rows = [{"row": int(rows[j]) + 1, "tokens": int(n_row[j]), "min_k": float(mk_row[j]), "bits": float(bits[j])} for j in fam]
cols = [{"key": "row", "label": "Row", "type": "number"}, {"key": "tokens", "label": "Tokens", "type": "number"},
        {"key": "bits", "label": "Bits per token", "type": "number"}, {"key": "min_k", "label": f"Min-{K:g}% log-probability", "type": "number"}]
fam_cols = [cols[0], cols[1], cols[3], cols[2]]
charts = [cs.chart("min_k", "histogram", f"Min-{K:g}% log-probability per text", {"x": cs.col(f"Min-{K:g}% log-probability", mk_row[te])},
                   note="Higher (closer to 0) means GPT-2 finds even the text's least likely tokens predictable, as with text it saw in training.")]
cs.publish({
    "title": "N-gram language model perplexity",
    "engine": cs.engine_info("numpy", "pandas"),
    "n": len(rows),
    "summary": f"GPT-2 small: perplexity {ppl:.1f} per token on {int(te.sum())} rows ({math.log2(ppl):.2f} bits per token); mean Min-{K:g}% log-probability {values['lm_min_k']:.2f}.",
    "statistics": [
        {"key": "perplexity", "label": "Perplexity per token", "value": ppl},
        {"key": "cross_entropy", "label": "Bits per token", "value": values["cross_entropy"]},
        {"key": "lm_word_perplexity", "label": "Perplexity per word", "value": values["lm_word_perplexity"]},
        {"key": "lm_min_k", "label": f"Mean Min-{K:g}% log-probability", "value": values["lm_min_k"]},
    ],
    "tables": [
        {"key": "surprising", "title": "Least predictable rows", "columns": cols, "rows": surprise_rows},
        {"key": "familiar", "title": "Most familiar rows (highest Min-K%)", "columns": fam_cols, "rows": familiar_rows},
    ],
    "assumptions": assumptions,
    "charts": charts,
    "values": values,
    "warnings": warnings,
    "artifacts": [{"key": "scores", "path": os.path.join(out, "scores.parquet"), "format": "parquet"}],
})

GPT-2 small, one of the GPT familyLarge language modelA neural network trained on text to give a probability for the next token, used repeatedly to write text., was trained on a large web collection and isn't fitted to your rows. On the test rows it has perplexity 76.7 per byte-level token, or 95.3 per word. The per-token figure can't be set against the n-gram's per-word one: the units differ, and the n-gram hides unknown words.

GPT-2 runs on this Mac as a scorer, in Python and R. Chat models reached through local runtimes or cloud providers can't score a given text this way: they return probabilities only for tokens they generate. The lesson Pretrained text models goes further with this run.

06

What perplexity is not

Read

Perplexity measures how predictable a text is to one model. It rises for typos, rare names and new topics, and falls for boilerplate and for text the model has already seen. So it is useful for comparing models on the same text, and for flagging rows that look unusual to a model.

It doesn't measure truth, quality or helpfulness. A fluent false sentence can be very predictable. A low perplexity on a test set that leaked into training is memory, not skill.

07

Where it stands in CodeSplash

Read
EntryIn CodeSplash
Held-out perplexity (LNG001, EVA029)Runs in CodeSplash: Language model perplexity, with row-resampled intervals
GPT scorer (LNG033)Partly runs in CodeSplash: GPT-2 small in Language model perplexity; chat models can't score given text
Reference · LNG033 · Partly runs in CodeSplashGPT autoregressive language-model familyUses causal language modeling to generate text and perform tasks described in a prompt. GPT-1/2/3 historical size and training generations are consolidated here; prompt adaptation is distinct from parameter updates.
08

Check: perplexity

Checkpoint

Check yourself

A model gives four tokens probabilities 0.6, 0.5, 0.8 and 0.7. What is the perplexity (natural logs), to two decimals?

Show the answer

Answer: 1.5619699684601278

The mean negative log-probability is about 0.446, and e to that power is about 1.56.

Check yourself

Model A has held-out perplexity 40 with 2% unknown words; model B has 25 with 45% unknown words, on different vocabularies. Which predicts the text better?

Show the answer

Answer: b

Perplexity compares models only with the same tokens and the same unknown-word rule. A huge unknown share makes perplexity look better than the model is.

Check yourself

Why does CodeSplash's perplexity interval resample whole rows instead of single words?

Show the answer

Answer: a

The independent units are the documents. Treating dependent words as independent pretends there is more evidence than there is.

Check yourself

Why does CodeSplash score texts with GPT-2 on the Mac instead of asking a chat model through a local runtime?

Show the answer

Answer: b

A scorer must evaluate text it didn't write. GPT-2 runs in CodeSplash's own Python and R code, so every token's probability is available.

Check yourself

A set of generated answers gets a low perplexity under GPT-2. What does that show?

Show the answer

Answer: b

Perplexity measures predictability to a model. Truth and usefulness need checks against sources or people.

09

Recap

Recap
  • Cross-entropy is the mean surprise on held-out tokens; perplexity is its exponential.
  • Read it with its row-resampled interval and next to the unknown-word rate.
  • Compare only with the same tokens, vocabulary rule and rows.
  • GPT-2 scores text in CodeSplash; chat models can't. Low perplexity means predictable, never true.

Concepts in this lesson