Skip to content

Pretrained text models: a language model's verdict, reranking and subwords

Score texts with a pretrained language model (GPT-2) and check for memorized text with Min-K%, rerank search results with ColBERT, give unseen words vectors from their spelling, and know when votes help an AI labeler.

Applied ~14 min5 steps

What runs in CodeSplash

You will be able to

  • Read GPT-2 perplexity per token and per word, and say why it isn't an n-gram perplexity
  • Interpret Min-K% Prob as a hint of memorized text, not proof
  • Explain what ColBERT reranking changes and why it only rescores the top candidates
  • Describe how subword vectors give words outside the vocabulary a vector

Read first

01

A pretrained model's view of your text

Read

An n-gram model learns from your training rows. A pretrained language model has already learned from a large public text collection, so nothing is fitted to your rows. CodeSplash runs GPT-2 small (OpenAI, 124 million parameters) on this computer after a one-time download. It gives every token of every row a log-probability.

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"}],
})

On the 15 rows marked as test, GPT-2 has a perplexityPretrained language model perplexityHow predictable a pretrained model (GPT-2 small) finds each text, per GPT-2 token or per word. of 76.7 per token, or 95.3 per word. The other rows give 80.3: close, because GPT-2 never trained on either set.

GPT-2 splits text into byte-level pieces, so a long or rare word costs several tokens. That is why per-token and per-word perplexity differ, and why neither can be compared with an n-gram model's perplexity per word.

Check yourself

A trigram model has held-out perplexity 140 per word; GPT-2 has 80 per token on the same rows. What can you conclude?

Show the answer

Answer: b

Perplexities compare only with the same tokens. Compare GPT-2's per-word value with the n-gram model's, and still read it as a rough guide.

02

Was this text in the training data?

Read

A model that trained on a text rarely finds any of its tokens very surprising. Min-K% ProbMin-K% ProbThe mean log-probability of a text's least likely K% of tokens; higher means the model may have seen the text. averages the log-probabilities of a text's least likely K% of tokens. A higher (less negative) value hints that the model may have seen the text.

Here the test rows average −8.33 and the other rows −8.08. Both sets were written for these lessons, so a small gap is expected.

HistogramHow is one numeric variable distributed?
View data
score
52.300
57.400
67.200
66.900
49.600
37.100
66.400
70
55.200
69.600
81.900
55.600
75.700
87.300
57.500
73.900
61.700
44.100
50.400
48.800
47.100
66.800
50
52.900
51
76.200
62.400
53.300
54.600
54.100
74.600
75.400
75
68.600
77.300
50.400
50.400
79.700
76.500
62.600
60.600
63.500
55.300
61.900
45.800
58.200
57.900
57
60.100
68.900
47.700
41.800
59.200
80.700
72.800
54.200
79.300
46.900
67.600
80.900

First 60 of 1500 rows.

Check yourself

One review gets the highest Min-K% score of all your rows. What does that show?

Show the answer

Answer: b

Min-K% ranks texts; it is not a test. Compare rows you know were public with rows you know were not before reading anything into one score.

03

Reranking the top results

Read

Search by words or by one vector per text is fast, but it squeezes a whole text into a single score or vector. ColBERTColBERT MaxSimScores a text by finding, for each query token vector, its best match among the text's token vectors, then summing. keeps one vector per token: for each query token it finds the best-matching token in the text, and sums those best matches (MaxSim).

Semantic searchRecorded · Python and R agreeRecorded 2026-11-25 · 32 values compared
R

3 queries over 61 texts by words (BM25); best match for query 1: row 12.

Texts
61
Queries
3
Distinct words (BM25)
231

Plots

Best-ranked texts per query (maxsim score)Which words or phrases appear most in a text column, overall or by group?
View data
MaxSim scoreQueryText
31.236Q1d12
31.193Q1d01
30.894Q1d04
31.045Q2d36
30.884Q2d27
30.790Q2d28
31.184Q3d42
31.151Q3d60
31.105Q3d57

Assumptions

  • Words or meaning — BM25 matches shared words only; texts that use other words for the same idea score 0.
  • English text — The stop list and all-MiniLM-L6-v2 are English.

Best-ranked texts

QueryQuery textRankRowdocTextMaxSim scoreBM25 score
1late goal in the match112d12League rivals met in a tense match that ended with a late goal31.2367.521
1late goal in the match21d01The striker scored a late goal and the team won the match at home31.1937.521
1late goal in the match34d04A thrilling match ended level after the striker hit the post twice30.8941.938
2bake bread with flour and butter136d36Slice the bread and serve it warm with butter and soup31.0456.653
2bake bread with flour and butter227d27Bake the bread until the crust is golden and sounds hollow30.8846.044
2bake bread with flour and butter328d28Whisk the eggs with sugar then fold in the flour gently30.7903.856
3interest rates142d42The central bank raised interest rates to slow inflation31.1843.784
3interest rates260d60Savers welcomed higher interest rates on bank deposits31.1513.784
3interest rates357d57The fund manager bought bonds as interest rates peaked31.1053.784

Ties keep row order. ColBERT reranked the 8 best texts of each query: MaxSim = Σ over the query's 32 token vectors of the best dot product with a text's token vectors.

Queries

QueryText
1late goal in the match
2bake bread with flour and butter
3interest rates
  • 1 of 62 rows were left out because a value was missing.
  • BM25: Lucene's idf ln(1 + (N − n + 0.5) / (n + 0.5)) with k1 and b; tokens are lower-cased words of two or more letters, common English words left out.
The exact R script · R R version 4.5.1 (2025-06-13)
# Semantic search (BM25, sentence embeddings, hybrid)
# Generated by CodeSplash Analytics 1.0.0 on 2026-11-09 · method describe.semantic_search 1.1.0 · spec 63209487ee3523da
# Dataset: ml_corpus (version 1)
# Runs on its own: outside the app, cs_publish() writes $CS_RESULT_PATH or prints the result JSON.

# %% Setup
library(codesplashr) # cs_bm25*, cs_search_* (twins of codesplash.text.search) and cs_minilm_embed

# %% Data (rows with a text)
TEXT <- "text"
LABEL <- "doc"
df <- as.data.frame(nanoparquet::read_parquet("tests/parity/fixtures/ml_corpus.parquet", col_select = c("text", "doc")))
n_input <- nrow(df)
keep_rows <- which(!is.na(df[[TEXT]]))
df <- df[keep_rows, , drop = FALSE]
warnings <- list()
if (n_input - nrow(df) > 0) warnings <- c(warnings, cs_warning("CS_W_ROWS_DROPPED", dropped = n_input - nrow(df), total = n_input))
if (nrow(df) == 0) cs_error("CS_E_NO_ROWS")
rows <- as.integer(keep_rows)  # 1-based input rows
texts <- as.character(df[[TEXT]])
n <- length(texts)
doc_names <- if (!is.null(LABEL)) as.character(df[[LABEL]]) else rep(NA_character_, n)
unique_names <- !is.null(LABEL) && !anyNA(doc_names) && !anyDuplicated(doc_names)
doc_label <- if (unique_names) doc_names else sprintf("Row %d", rows)

# %% Queries and settings
QUERIES <- cs_search_split_list("late goal in the match; bake bread with flour and butter; interest rates")
if (!length(QUERIES)) cs_error("CS_E_INVALID_OPTION", option = "Queries", allowed = "at least one query (separate several with semicolons)", value = "(empty)")
if (length(QUERIES) > 50) cs_error("CS_E_INVALID_OPTION", option = "Queries", allowed = "at most 50 queries", value = sprintf("%d queries", length(QUERIES)))
RETRIEVER <- "bm25"
TOP_K <- min(as.integer(3), n)
m <- length(QUERIES)

# %% Scores
bm25 <- NULL
dense <- NULL
n_terms <- NA
no_match <- integer(0)
if (RETRIEVER %in% c("bm25", "hybrid")) {
  bm <- cs_bm25(texts, k1 = 1.2, b = 0.75)
  if (bm$avgdl <= 0) cs_error("CS_E_UNDEFINED", what = "BM25 scores", reason = "no text has a word of two or more letters outside the common-word list")
  n_terms <- cs_bm25_n_terms(bm)
  bm25 <- do.call(rbind, lapply(QUERIES, function(q) cs_bm25_scores(bm, q)))  # queries x texts
  no_match <- which(apply(bm25, 1, function(s) !any(s > 0)))
  for (j in no_match) {
    warnings <- c(warnings, sprintf("Query %d (“%s”) shares no word with any text, so its BM25 ranking is just row order.", j, cs_search_snippet(QUERIES[j], 40)))
  }
}
if (RETRIEVER %in% c("dense", "hybrid")) {
  if (!cs_minilm_available()) cs_error("CS_WEIGHTS_MISSING", model = "all-MiniLM-L6-v2 (download it from Discover → Topics in text → Pretrained embeddings)")
  model <- cs_minilm_load()
  dense <- cs_search_cosine(cs_minilm_embed(QUERIES, model), cs_minilm_embed(texts, model))  # queries x texts
}
final <- if (RETRIEVER == "bm25") {
  bm25
} else if (RETRIEVER == "dense") {
  dense
} else {
  do.call(rbind, lapply(seq_len(m), function(j) cs_search_rrf(list(cs_search_ranks(bm25[j, ]), cs_search_ranks(dense[j, ])), k = 60)))
}
final <- matrix(final, nrow = m)

# %% ColBERT rerank (cs_colbert_* ↔ codesplash.text.colbert): each query's best candidates rescored by MaxSim
cmodel <- cs_colbert_load()  # answerai-colbert-small-v1; stops with CS_WEIGHTS_MISSING when it isn't downloaded
DEPTH <- min(max(as.integer(8), TOP_K), n)
first <- final
final <- matrix(-Inf, m, n)  # only the candidates get a MaxSim score; the rest are never listed
doc_vecs <- list()
for (j in seq_len(m)) {
  Qv <- cs_colbert_query_vectors(QUERIES[j], cmodel)
  for (i in utils::head(cs_search_ranking(first[j, ]), DEPTH)) {
    key_i <- as.character(i)
    if (is.null(doc_vecs[[key_i]])) doc_vecs[[key_i]] <- cs_colbert_doc_vectors(texts[i], cmodel)
    final[j, i] <- cs_colbert_maxsim(Qv, doc_vecs[[key_i]])
  }
}

# %% Rankings
retriever_label <- c(bm25 = "words (BM25)", dense = "meaning (sentence embeddings)", hybrid = "words and meaning (reciprocal rank fusion)")[[RETRIEVER]]
values <- list(n_docs = n, n_queries = m, top_k = TOP_K, retriever = retriever_label,
               n_terms = n_terms, n_no_match = if (!is.null(bm25)) length(no_match) else NA)
values$rerank_model <- "ColBERT MaxSim (answerai-colbert-small-v1)"
values$rerank_depth <- DEPTH
result_rows <- list()
for (j in seq_len(m)) {
  order_j <- utils::head(cs_search_ranking(final[j, ]), TOP_K)
  key <- sprintf("q%d", j)
  values[[sprintf("top_row[%s]", key)]] <- rows[order_j[1]]
  values[[sprintf("top_score[%s]", key)]] <- final[j, order_j[1]]
  for (r in seq_along(order_j)) {
    i <- order_j[r]
    values[[sprintf("row[%s:%d]", key, r)]] <- rows[i]
    values[[sprintf("score[%s:%d]", key, r)]] <- final[j, i]
    row <- list(query = j, query_text = cs_search_snippet(QUERIES[j], 60), rank = r, row = rows[i], document = doc_label[i],
                text = cs_search_snippet(texts[i]), score = final[j, i])
    if (RETRIEVER == "hybrid") {
      row$bm25 <- bm25[j, i]
      row$similarity <- dense[j, i]
    }
    row$first_stage <- first[j, i]
    result_rows[[length(result_rows) + 1]] <- row
  }
}
score_label <- c(bm25 = "BM25 score", dense = "Cosine similarity", hybrid = "Fusion score")[[RETRIEVER]]
first_label <- score_label
score_label <- "MaxSim score"
cols <- list(list(key = "query", label = "Query", type = "integer"), list(key = "query_text", label = "Query text", type = "string"),
             list(key = "rank", label = "Rank", type = "integer"), list(key = "row", label = "Row", type = "integer"))
if (!is.null(LABEL)) cols <- c(cols, list(list(key = "document", label = if (unique_names) LABEL else "Document", type = "string")))
cols <- c(cols, list(list(key = "text", label = "Text", type = "string"), list(key = "score", label = score_label, type = "number")))
if (RETRIEVER == "hybrid") cols <- c(cols, list(list(key = "bm25", label = "BM25 score", type = "number"), list(key = "similarity", label = "Cosine similarity", type = "number")))
cols <- c(cols, list(list(key = "first_stage", label = first_label, type = "number")))
tables <- list(
  list(key = "results", title = "Best-ranked texts", columns = cols, rows = result_rows,
       note = paste0("Ties keep row order.", if (RETRIEVER == "hybrid") " Fusion score = Σ 1 / (k + rank) over the BM25 and the dense rankings." else "", sprintf(" ColBERT reranked the %d best texts of each query: MaxSim = Σ over the query's 32 token vectors of the best dot product with a text's token vectors.", DEPTH))),
  list(key = "queries", title = "Queries", columns = list(list(key = "query", label = "Query", type = "integer"), list(key = "text", label = "Text", type = "string")),
       rows = lapply(seq_len(m), function(j) list(query = j, text = QUERIES[j])))
)
charts <- list()
if (m <= 9) {  # the chart draws at most 9 panels; the table has every query
  rv <- function(k) vapply(result_rows, function(r) r[[k]], if (k == "score") numeric(1) else if (k == "query") integer(1) else character(1))
  charts[[1]] <- cs_chart("results", "ngram-bars", sprintf("Best-ranked texts per query (%s)", tolower(score_label)),
    list(term = cs_col("Text", rv("document"), kind = "categorical"), count = cs_col(score_label, rv("score")),
         group = cs_col("Query", sprintf("Q%d", rv("query")), kind = "categorical", levels = sprintf("Q%d", seq_len(m)))),
    controls = list(top = max(3L, TOP_K)))
}
assumptions <- list(
  list(key = "words_vs_meaning", label = "Words or meaning", status = "info",
       detail = c(bm25 = "BM25 matches shared words only; texts that use other words for the same idea score 0.",
                  dense = "Dense search matches meaning; exact names, numbers and codes can rank lower than with BM25.",
                  hybrid = "Hybrid search combines both rankings, so a text matched by words or by meaning can rise.")[[RETRIEVER]]),
  list(key = "language", label = "English text", status = "info", detail = "The stop list and all-MiniLM-L6-v2 are English.")
)
summary <- sprintf("%d quer%s over %d texts by %s; best match for query 1: row %d.", m, if (m == 1) "y" else "ies", n, retriever_label, values[["top_row[q1]"]])
cs_publish(list(
  method = "describe.semantic_search",
  methodVersion = "1.1.0",
  title = "Semantic search",
  engine = cs_engine_info("nanoparquet", "stringi"),
  n = n,
  summary = summary,
  statistics = c(list(list(key = "n_docs", label = "Texts", value = n), list(key = "n_queries", label = "Queries", value = m)),
                 if (!is.na(n_terms)) list(list(key = "n_terms", label = "Distinct words (BM25)", value = n_terms)) else list()),
  tables = tables,
  assumptions = assumptions,
  warnings = warnings,
  notes = if (!is.null(bm25)) list("BM25: Lucene's idf ln(1 + (N − n + 0.5) / (n + 0.5)) with k1 and b; tokens are lower-cased words of two or more letters, common English words left out.") else list(),
  charts = charts,
  values = values
))
Python

3 queries over 61 texts by words (BM25); best match for query 1: row 12.

Texts
61
Queries
3
Distinct words (BM25)
231

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

Assumptions

  • Words or meaning — BM25 matches shared words only; texts that use other words for the same idea score 0.
  • English text — The stop list and all-MiniLM-L6-v2 are English.

Best-ranked texts

QueryQuery textRankRowdocTextMaxSim scoreBM25 score
1late goal in the match112d12League rivals met in a tense match that ended with a late goal31.2367.521
1late goal in the match21d01The striker scored a late goal and the team won the match at home31.1937.521
1late goal in the match34d04A thrilling match ended level after the striker hit the post twice30.8941.938
2bake bread with flour and butter136d36Slice the bread and serve it warm with butter and soup31.0456.653
2bake bread with flour and butter227d27Bake the bread until the crust is golden and sounds hollow30.8846.044
2bake bread with flour and butter328d28Whisk the eggs with sugar then fold in the flour gently30.7903.856
3interest rates142d42The central bank raised interest rates to slow inflation31.1843.784
3interest rates260d60Savers welcomed higher interest rates on bank deposits31.1513.784
3interest rates357d57The fund manager bought bonds as interest rates peaked31.1053.784

Ties keep row order. ColBERT reranked the 8 best texts of each query: MaxSim = Σ over the query's 32 token vectors of the best dot product with a text's token vectors.

Queries

QueryText
1late goal in the match
2bake bread with flour and butter
3interest rates
  • 1 of 62 rows were left out because a value was missing.
  • BM25: Lucene's idf ln(1 + (N − n + 0.5) / (n + 0.5)) with k1 and b; tokens are lower-cased words of two or more letters, common English words left out.
The exact Python script · Python Python 3.13.5 · scipy 1.18.1 · pandas 3.1.0
# Semantic search (BM25, sentence embeddings, hybrid)
# Generated by CodeSplash Analytics 1.0.0 on 2026-11-09 · method describe.semantic_search 1.1.0 · spec 63209487ee3523da
# Dataset: ml_corpus (version 1)
# Runs on its own: outside the app, cs.publish() writes $CS_RESULT_PATH or prints the result JSON.

# %% Setup
import numpy as np
import pandas as pd

import codesplash as cs
from codesplash.text import search as ss  # BM25, rankings, rank fusion (twin: codesplashr cs_bm25*, cs_search_*)

# %% Data (rows with a text)
TEXT = "text"
LABEL = "doc"
df = pd.read_parquet("tests/parity/fixtures/ml_corpus.parquet", columns=["text", "doc"])
n_input = len(df)
df = df[df[TEXT].notna()]
warnings = []
if n_input - len(df):
    warnings.append(cs.cs_warning("CS_W_ROWS_DROPPED", dropped=n_input - len(df), total=n_input))
if not len(df):
    cs.cs_error("CS_E_NO_ROWS")
rows = (df.index.to_numpy() + 1).astype(np.int64)  # 1-based input rows
texts = df[TEXT].astype(str).tolist()
n = len(texts)
names = [None if pd.isna(v) else str(v) for v in df[LABEL].tolist()] if LABEL else [None] * n
unique_names = LABEL is not None and None not in names and len(set(names)) == n
doc_label = [names[i] if unique_names else f"Row {rows[i]}" for i in range(n)]

# %% Queries and settings
QUERIES = ss.split_list("late goal in the match; bake bread with flour and butter; interest rates")
if not QUERIES:
    cs.cs_error("CS_E_INVALID_OPTION", option="Queries", allowed="at least one query (separate several with semicolons)", value="(empty)")
if len(QUERIES) > 50:
    cs.cs_error("CS_E_INVALID_OPTION", option="Queries", allowed="at most 50 queries", value=f"{len(QUERIES)} queries")
RETRIEVER = "bm25"
TOP_K = min(int(3), n)
m = len(QUERIES)

# %% Scores
bm25 = dense = None
n_terms, no_match = None, []
if RETRIEVER in ("bm25", "hybrid"):
    bm = ss.Bm25(texts, k1=1.2, b=0.75)
    if bm.avgdl <= 0:
        cs.cs_error("CS_E_UNDEFINED", what="BM25 scores", reason="no text has a word of two or more letters outside the common-word list")
    n_terms = bm.n_terms
    bm25 = np.vstack([bm.scores(q) for q in QUERIES])  # queries × texts
    no_match = [j for j in range(m) if not np.any(bm25[j] > 0)]
    for j in no_match:
        warnings.append(f"Query {j + 1} (“{ss.snippet(QUERIES[j], 40)}”) shares no word with any text, so its BM25 ranking is just row order.")
if RETRIEVER in ("dense", "hybrid"):
    from codesplash.text import minilm  # all-MiniLM-L6-v2 in numpy (twin: cs_minilm_embed)

    if not minilm.available():
        cs.cs_error("CS_WEIGHTS_MISSING", model=f"{minilm.NAME} (download it from Discover → Topics in text → Pretrained embeddings)")
    model = minilm.Model()
    dense = ss.cosine(minilm.embed(QUERIES, model), minilm.embed(texts, model))  # queries × texts
if RETRIEVER == "bm25":
    final = bm25
elif RETRIEVER == "dense":
    final = dense
else:
    final = np.vstack([ss.rrf(ss.ranks(bm25[j]), ss.ranks(dense[j]), k=60) for j in range(m)])

# %% ColBERT rerank (codesplash.text.colbert ↔ codesplashr cs_colbert_*): each query's best candidates rescored by MaxSim
from codesplash.text import colbert

cmodel = colbert.Model()  # answerai-colbert-small-v1; stops with CS_WEIGHTS_MISSING when it isn't downloaded
DEPTH = min(max(int(8), TOP_K), n)
first = final
final = np.full((m, n), -np.inf)  # only the candidates get a MaxSim score; the rest are never listed
doc_vecs = {}
for j, q in enumerate(QUERIES):
    Qv = colbert.query_vectors(q, cmodel)
    for i in ss.ranking(first[j])[:DEPTH]:
        if i not in doc_vecs:
            doc_vecs[i] = colbert.doc_vectors(texts[i], cmodel)
        final[j, i] = colbert.maxsim(Qv, doc_vecs[i])

# %% Rankings
result_rows = []
values = {"n_docs": n, "n_queries": m, "top_k": TOP_K,
          "retriever": {"bm25": "words (BM25)", "dense": "meaning (sentence embeddings)", "hybrid": "words and meaning (reciprocal rank fusion)"}[RETRIEVER],
          "n_terms": n_terms, "n_no_match": len(no_match) if bm25 is not None else None}
values["rerank_model"] = "ColBERT MaxSim (answerai-colbert-small-v1)"
values["rerank_depth"] = DEPTH
for j, q in enumerate(QUERIES):
    order = ss.ranking(final[j])[:TOP_K]
    key = f"q{j + 1}"
    values[f"top_row[{key}]"] = int(rows[order[0]])
    values[f"top_score[{key}]"] = float(final[j][order[0]])
    for r, i in enumerate(order, start=1):
        values[f"row[{key}:{r}]"] = int(rows[i])
        values[f"score[{key}:{r}]"] = float(final[j][i])
        row = {"query": j + 1, "query_text": ss.snippet(q, 60), "rank": r, "row": int(rows[i]), "document": doc_label[i],
               "text": ss.snippet(texts[i]), "score": float(final[j][i])}
        if RETRIEVER == "hybrid":
            row["bm25"] = float(bm25[j][i])
            row["similarity"] = float(dense[j][i])
        row["first_stage"] = float(first[j][i])
        result_rows.append(row)
score_label = {"bm25": "BM25 score", "dense": "Cosine similarity", "hybrid": "Fusion score"}[RETRIEVER]
first_label, score_label = score_label, "MaxSim score"
cols = [{"key": "query", "label": "Query", "type": "integer"}, {"key": "query_text", "label": "Query text", "type": "string"},
        {"key": "rank", "label": "Rank", "type": "integer"}, {"key": "row", "label": "Row", "type": "integer"}]
if LABEL:
    cols.append({"key": "document", "label": LABEL if unique_names else "Document", "type": "string"})
cols += [{"key": "text", "label": "Text", "type": "string"}, {"key": "score", "label": score_label, "type": "number"}]
if RETRIEVER == "hybrid":
    cols += [{"key": "bm25", "label": "BM25 score", "type": "number"}, {"key": "similarity", "label": "Cosine similarity", "type": "number"}]
cols.append({"key": "first_stage", "label": first_label, "type": "number"})
tables = [
    {"key": "results", "title": "Best-ranked texts", "columns": cols, "rows": result_rows,
     "note": "Ties keep row order." + (" Fusion score = Σ 1 / (k + rank) over the BM25 and the dense rankings." if RETRIEVER == "hybrid" else "") + f" ColBERT reranked the {DEPTH} best texts of each query: MaxSim = Σ over the query's 32 token vectors of the best dot product with a text's token vectors."},
    {"key": "queries", "title": "Queries", "columns": [{"key": "query", "label": "Query", "type": "integer"}, {"key": "text", "label": "Text", "type": "string"}],
     "rows": [{"query": j + 1, "text": q} for j, q in enumerate(QUERIES)]},
]
charts = []
if m <= 9:  # the chart draws at most 9 panels; the table has every query
    qlevels = [f"Q{j + 1}" for j in range(m)]
    terms, scores, groups = [], [], []
    for res in result_rows:
        terms.append(res["document"])
        scores.append(res["score"])
        groups.append(f"Q{res['query']}")
    charts.append(cs.chart("results", "ngram-bars", f"Best-ranked texts per query ({score_label.lower()})", {
        "term": cs.col("Text", terms, kind="categorical"), "count": cs.col(score_label, scores),
        "group": cs.col("Query", groups, kind="categorical", levels=qlevels)}, controls={"top": max(3, TOP_K)}))
assumptions = [
    {"key": "words_vs_meaning", "label": "Words or meaning", "status": "info",
     "detail": {"bm25": "BM25 matches shared words only; texts that use other words for the same idea score 0.",
                "dense": "Dense search matches meaning; exact names, numbers and codes can rank lower than with BM25.",
                "hybrid": "Hybrid search combines both rankings, so a text matched by words or by meaning can rise."}[RETRIEVER]},
    {"key": "language", "label": "English text", "status": "info", "detail": "The stop list and all-MiniLM-L6-v2 are English."},
]
summary = f"{m} quer{'y' if m == 1 else 'ies'} over {n} texts by {values['retriever']}; best match for query 1: row {values['top_row[q1]']}."
cs.publish({
    "method": "describe.semantic_search",
    "methodVersion": "1.1.0",
    "title": "Semantic search",
    "engine": cs.engine_info("numpy", "pandas"),
    "n": n,
    "summary": summary,
    "statistics": [{"key": "n_docs", "label": "Texts", "value": n}, {"key": "n_queries", "label": "Queries", "value": m}]
    + ([{"key": "n_terms", "label": "Distinct words (BM25)", "value": n_terms}] if n_terms is not None else []),
    "tables": tables,
    "assumptions": assumptions,
    "warnings": warnings,
    "notes": ["BM25: Lucene's idf ln(1 + (N − n + 0.5) / (n + 0.5)) with k1 and b; tokens are lower-cased words of two or more letters, common English words left out."] if bm25 is not None else [],
    "charts": charts,
    "values": values,
})

BM25 found the candidates, and ColBERT rescored the best 8 of each query. For the first query, BM25 had two texts tied at the top; ColBERT puts row 12 first.

Top termsWhich words or phrases appear most in a text column, overall or by group?
View data
bigramcountrating
late delivery621–2 stars
refund501–2 stars
customer service451–2 stars
broken391–2 stars
never arrived331–2 stars
waste251–2 stars
wrong size251–2 stars
poor quality241–2 stars
support181–2 stars
return181–2 stars
great quality744–5 stars
fast shipping604–5 stars
love524–5 stars
fits perfectly384–5 stars
easy354–5 stars
recommend334–5 stars
comfortable314–5 stars
good value264–5 stars
gift164–5 stars
soft174–5 stars

Check yourself

The text that best answers a query is ranked 40th by BM25. You rerank the top 20 with ColBERT. Where can it end up?

Show the answer

Answer: b

A reranker can only reorder what the first search found. Raise the number of candidates, or use a meaning-based first search, when good texts are missing.

04

Words the model never saw

Read

Word vectors learn one vector per word in the vocabulary. With subwordsSubword word vectors (fastText)Each word's vector is the mean of its own vector and its character n-gram vectors, so unseen words get vectors too. (the fastText idea), a word is also the sum of its character pieces, so "matches" gets a vector even when only "match" was kept.

Word vectorsRecorded · Python and R agreeRecorded 2026-11-25 · 18 values compared
R

Skip-gram: 8-dimensional vectors for 107 words from 485 words of text. Closest to “match”: team (0.97).

Words with vectors
107
Words of text
485
Dimensions
8
Loss in the last pass
3.973

Plots

Map of the most frequent wordsWhich levels of a categorical variable does the model treat as alike?

The first two principal components of the word vectors; words close together are used in similar contexts.

View data
WordCountComponent 1Component 2
the891.1220.0021
and300.3988−0.0035
a170.1998−0.0082
in120.1578−0.0012
with110.11630.0018
rates100.0673−0.0027
after90.0699−0.0053
as80.06790.0120
it80.07750.0190
team8−0.0120−0.0049
interest70.06240.0072
match70.0052−0.0200
bank60.02030.0065
higher60.00460.0022
before5−0.0155−0.0112
for5−0.0169−0.0276
garlic50.0362−0.0126
inflation5−0.00470.0001
markets5−0.01660.0014
of5−0.01290.0152
profits5−0.01390.0032
shares50.02660.0049
striker5−0.0293−0.0069
to50.00090.0452
until5−0.00230.0014
bake4−0.04470.0044
fans4−0.0276−0.0102
investors40.0107−0.0011
league4−0.03600.0044
on40.0031−0.0117
onions4−0.0315−0.0241
sauce4−0.01880.0032
add3−0.0345−0.0223
bond30.0118−0.0241
coach3−0.08380.0173
company3−0.06440.0085
cup3−0.0446−0.0292
fell3−0.01490.0129
final3−0.04300.0056
goal3−0.02670.0093
goalkeeper3−0.02320.0051
herbs3−0.0216−0.0033
home3−0.04850.0057
its30.03570.0277
kept3−0.0379−0.0145
lemon30.00620.0034
let3−0.0152−0.0033
made3−0.03070.0087
oil3−0.02910.0157
olive3−0.0062−0.0064
penalty3−0.04500.0052
salt3−0.0176−0.0015
simmer3−0.0306−0.0060
stadium3−0.06180.0022
stock3−0.02980.0126
their30.1966−0.0076
against2−0.04790.0083
at2−0.0826−0.0050
ball2−0.0405−0.0059
bonds2−0.0413−0.0223
Nearest wordsWhich words or phrases appear most in a text column, overall or by group?
View data
Cosine similarityWordNeighbor
0.9677matchteam
0.9595matchafter
0.9496matchminutes
0.9883matchesafter
0.9870matchesrates
0.9862matchesthen
0.8767ovengolden
0.8623ovenmade
0.8104ovenwarm
0.7527ovenscaptain
0.6367ovenscut
0.6358ovensserve

Assumptions

  • Enough text — 485 words after rare words were removed; neighbors on this little text are noisy, so read them as hints.
  • The window sets the kind of similarity — A window of 2 word(s) on each side; smaller windows favor words with the same role, larger ones words on the same topic.
  • Coordinates are arbitrary — Compare neighbors and similarities, not single coordinates; another seed or method rotates the vectors.

Nearest words

WordRankNeighborCosine similarity
match1team0.9677
match2after0.9595
match3minutes0.9496
matches1after0.9883
matches2rates0.9870
matches3then0.9862
oven1golden0.8767
oven2made0.8623
oven3warm0.8104
ovens1captain0.7527
ovens2cut0.6367
ovens3serve0.6358
  • 1 rows have no text (or no words) and are left out.
  • Not in the vocabulary: matches, oven, ovens, zzz.
  • Built from character n-grams (no vector of their own): matches, oven, ovens.
The exact R script · R R version 4.5.1 (2025-06-13)
# Word vectors
# Generated by CodeSplash Analytics 1.0.0 on 2026-11-09 · method discover.word_vectors 1.1.0 · spec 31f6c56e97c2e0e5
# Dataset: ml_corpus (version 1)
# Runs on its own: outside the app, cs_publish() writes $CS_RESULT_PATH or prints the result JSON.

# %% Setup
library(codesplashr)

# %% Rows with at least one word
TEXT <- "text"
TOKENS <- "words"
LOWER <- TRUE
df <- as.data.frame(nanoparquet::read_parquet("tests/parity/fixtures/ml_corpus.parquet", col_select = TEXT))
warnings <- list()
docs_all <- lapply(seq_len(nrow(df)), function(i) cs_lm_tokenize(df[[TEXT]][i], TOKENS, LOWER))
rows <- which(lengths(docs_all) > 0)
n_dropped <- nrow(df) - length(rows)
if (n_dropped) warnings <- c(warnings, sprintf("%d rows have no text (or no words) and are left out.", n_dropped))
if (!length(rows)) cs_error("CS_E_NO_ROWS")  # no row has any words
docs <- docs_all[rows]

# %% Vocabulary and windows (rare words removed first; windows never cross rows)
MIN_COUNT <- 2
vv <- cs_wv_vocabulary(docs, MIN_COUNT, 2000)
vocab <- vv$vocab
counts <- vv$counts
if (length(vocab) < 2) cs_error("CS_E_UNDEFINED", what = "Word vectors", reason = sprintf("fewer than two words occur at least %d times", MIN_COUNT))
ids <- cs_wv_encode(docs, vocab)
WINDOW <- 2L
if (!nrow(cs_wv_pairs(ids, WINDOW))) cs_error("CS_E_UNDEFINED", what = "Word vectors", reason = "no two kept words are within the window of each other in any row")
V <- length(vocab)
DIM <- min(8L, V)
if (DIM < 8) warnings <- c(warnings, sprintf("Only %d words are kept, so the vectors have %d dimensions instead of 8.", V, V))

# %% Fit
METHOD <- "sgns"
SEED <- 42
EPOCHS <- 5
LR <- NULL
sv <- NULL; sv_share <- NULL; final_loss <- NULL
if (METHOD == "ppmi_svd") {
  X <- cs_wv_cooccurrence(ids, WINDOW, V, FALSE)
  if (!any(cs_wv_ppmi(X) > 0)) cs_error("CS_E_UNDEFINED", what = "Word vectors", reason = "every pointwise mutual information is zero or negative")
  fit <- cs_wv_ppmi_svd(X, DIM)
  vectors <- fit$vectors; sv <- fit$sv; sv_share <- fit$share
} else if (METHOD %in% c("sgns", "cbow")) {
  # Subwords (cs_subword_* ↔ codesplash.text.subword): each word is its own row plus its hashed character n-grams
  if (3 > 6) cs_error("CS_E_INVALID_OPTION", option = "Shortest n-gram", allowed = "at most the longest n-gram (6)", value = "3")
  SW_INDEX <- cs_subword_index(vocab, 3, 6, 2000000)
  fit <- cs_subword_sgns(ids, counts, SW_INDEX, DIM, WINDOW, 5, if (is.null(EPOCHS)) 20 else EPOCHS,
                         if (is.null(LR)) (if (METHOD == "sgns") 0.025 else 0.05) else LR, SEED, cbow = METHOD == "cbow")
  SW_IN <- fit$w_in
  vectors <- fit$vectors; final_loss <- fit$loss
} else {
  fit <- cs_wv_glove(cs_wv_cooccurrence(ids, WINDOW, V, TRUE), DIM, if (is.null(EPOCHS)) 50 else EPOCHS, if (is.null(LR)) 0.05 else LR, SEED)
  vectors <- fit$vectors; final_loss <- fit$loss
}

# %% Nearest neighbors of the looked-up words (default: the five most frequent)
QUERY <- "match, matches, oven, ovens, zzz"
asked <- strsplit(if (LOWER) tolower(QUERY) else QUERY, "[,[:space:]]+", perl = TRUE)[[1]]
asked <- unique(asked[nzchar(asked)])
queries <- head(asked[asked %in% vocab], 9)
missing <- asked[!(asked %in% vocab)]
if (length(missing)) warnings <- c(warnings, paste0("Not in the vocabulary: ", paste(missing, collapse = ", "), "."))
by_count <- order(-counts, seq_len(V), method = "radix")
if (!length(asked)) queries <- vocab[head(by_count, 5)]
K <- 3
nb_rows <- list()
values_nb <- list()
for (q in queries) {
  near <- cs_wv_neighbors(vectors, match(q, vocab), K)
  for (r in seq_along(near$index)) nb_rows[[length(nb_rows) + 1L]] <- list(word = q, rank = r, neighbor = vocab[near$index[r]], cosine = near$cosine[r])
  if (length(near$index)) {
    values_nb[[sprintf("nearest[%s]", q)]] <- vocab[near$index[1]]
    values_nb[[sprintf("similarity[%s]", q)]] <- near$cosine[1]
  }
}
# Words outside the vocabulary: a vector from their character n-grams that training used (skip-gram and CBOW only)
built <- character(0)
if (METHOD %in% c("sgns", "cbow")) {
  for (q in head(missing, max(0L, 9L - length(queries)))) {
    vec <- cs_subword_oov_vector(q, SW_INDEX, SW_IN)
    if (is.null(vec)) next
    near <- cs_subword_neighbors(vec, vectors, K)
    for (r in seq_along(near$index)) nb_rows[[length(nb_rows) + 1L]] <- list(word = q, rank = r, neighbor = vocab[near$index[r]], cosine = near$cosine[r])
    values_nb[[sprintf("nearest[%s]", q)]] <- vocab[near$index[1]]
    values_nb[[sprintf("similarity[%s]", q)]] <- near$cosine[1]
    built <- c(built, q)
  }
  if (length(built)) {
    warnings <- c(warnings, paste0("Built from character n-grams (no vector of their own): ", paste(built, collapse = ", "), "."))
    queries <- c(queries, built)
  }
}

# %% Artifacts: one row per word
out <- cs_ml_out_dir("target/academy-parity/run-8142/discover.word_vectors/sgns_subword_oov/out-r")
art <- data.frame(word = vocab, count = as.integer(counts))
for (k in seq_len(DIM)) art[[paste0("v", k)]] <- vectors[, k]
nanoparquet::write_parquet(art, file.path(out, "vectors.parquet"))

# %% Result
LABELS <- c(ppmi_svd = "PPMI-SVD", sgns = "Skip-gram", cbow = "CBOW", glove = "GloVe")
n_tokens <- sum(lengths(ids))
values <- list(n_docs = length(rows), n_dropped = n_dropped, n_tokens = n_tokens, vocab_size = V, dim = DIM, window = WINDOW,
               method = unname(LABELS[METHOD]), final_loss = final_loss, sv_share = sv_share)
if (is.null(final_loss)) values["final_loss"] <- list(NULL)
if (is.null(sv_share)) values["sv_share"] <- list(NULL)
if (!is.null(sv)) for (k in seq_len(DIM)) values[[sprintf("sv[%d]", k)]] <- sv[k]
if (METHOD %in% c("sgns", "cbow")) {
  values$method <- paste(values$method, "with subwords")
  values$subword_buckets <- length(SW_INDEX$used)
}
values <- c(values, values_nb)
assumptions <- list(
  list(key = "enough_text", label = "Enough text", status = if (n_tokens < 10000) "warn" else "pass",
       detail = paste0(sprintf("%d words after rare words were removed", n_tokens), if (n_tokens < 10000) "; neighbors on this little text are noisy, so read them as hints." else ".")),
  list(key = "window_meaning", label = "The window sets the kind of similarity", status = "info",
       detail = sprintf("A window of %d word(s) on each side; smaller windows favor words with the same role, larger ones words on the same topic.", WINDOW)),
  list(key = "coordinates_arbitrary", label = "Coordinates are arbitrary", status = "info",
       detail = "Compare neighbors and similarities, not single coordinates; another seed or method rotates the vectors.")
)
nb_cols <- list(list(key = "word", label = "Word"), list(key = "rank", label = "Rank", type = "number"),
                list(key = "neighbor", label = "Neighbor"), list(key = "cosine", label = "Cosine similarity", type = "number"))
top <- head(by_count, 60)
xy <- cs_wv_map_2d(vectors)
charts <- list(cs_chart("map", "embedding-map", "Map of the most frequent words", list(
  x = cs_col("Component 1", xy[top, 1], "numeric"),
  y = cs_col("Component 2", xy[top, 2], "numeric"),
  label = cs_col("Word", vocab[top], "categorical"),
  size = cs_col("Count", counts[top], "numeric")
), note = "The first two principal components of the word vectors; words close together are used in similar contexts."))
if (length(nb_rows)) {
  charts[[2]] <- cs_chart("neighbors", "ngram-bars", "Nearest words", list(
    term = cs_col("Neighbor", vapply(nb_rows, `[[`, "", "neighbor"), "categorical"),
    count = cs_col("Cosine similarity", vapply(nb_rows, `[[`, 0, "cosine"), "numeric"),
    group = cs_col("Word", vapply(nb_rows, `[[`, "", "word"), "categorical", queries)
  ))
}
summary <- sprintf("%s: %d-dimensional vectors for %d words from %d words of text.", LABELS[[METHOD]], DIM, V, n_tokens)
if (length(queries) && !is.null(values[[sprintf("nearest[%s]", queries[1])]])) {
  summary <- paste0(summary, sprintf(" Closest to “%s”: %s (%.2f).", queries[1], values[[sprintf("nearest[%s]", queries[1])]], values[[sprintf("similarity[%s]", queries[1])]]))
}
stats <- list(list(key = "vocab_size", label = "Words with vectors", value = V), list(key = "n_tokens", label = "Words of text", value = n_tokens),
              list(key = "dim", label = "Dimensions", value = DIM))
if (!is.null(sv_share)) stats[[length(stats) + 1L]] <- list(key = "sv_share", label = "PPMI kept by these dimensions", value = sv_share)
if (!is.null(final_loss)) stats[[length(stats) + 1L]] <- list(key = "final_loss", label = "Loss in the last pass", value = final_loss)
cs_publish(list(
  title = "Word vectors",
  engine = cs_engine_info("codesplashr", "nanoparquet"),
  n = length(rows),
  summary = summary,
  statistics = stats,
  tables = list(list(key = "neighbors", title = "Nearest words", columns = nb_cols, rows = nb_rows)),
  assumptions = assumptions,
  charts = charts,
  values = values,
  warnings = warnings,
  artifacts = list(list(key = "vectors", path = file.path(out, "vectors.parquet"), format = "parquet"))
))
Python

Skip-gram: 8-dimensional vectors for 107 words from 485 words of text. Closest to “match”: team (0.97).

Words with vectors
107
Words of text
485
Dimensions
8
Loss in the last pass
3.973

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

Assumptions

  • Enough text — 485 words after rare words were removed; neighbors on this little text are noisy, so read them as hints.
  • The window sets the kind of similarity — A window of 2 word(s) on each side; smaller windows favor words with the same role, larger ones words on the same topic.
  • Coordinates are arbitrary — Compare neighbors and similarities, not single coordinates; another seed or method rotates the vectors.

Nearest words

WordRankNeighborCosine similarity
match1team0.9677
match2after0.9595
match3minutes0.9496
matches1after0.9883
matches2rates0.9870
matches3then0.9862
oven1golden0.8767
oven2made0.8623
oven3warm0.8104
ovens1captain0.7527
ovens2cut0.6367
ovens3serve0.6358
  • 1 rows have no text (or no words) and are left out.
  • Not in the vocabulary: matches, oven, ovens, zzz.
  • Built from character n-grams (no vector of their own): matches, oven, ovens.
The exact Python script · Python Python 3.13.5 · scipy 1.18.1 · pandas 3.1.0
# Word vectors
# Generated by CodeSplash Analytics 1.0.0 on 2026-11-09 · method discover.word_vectors 1.1.0 · spec 31f6c56e97c2e0e5
# Dataset: ml_corpus (version 1)
# Runs on its own: outside the app, cs.publish() writes $CS_RESULT_PATH or prints the result JSON.
# %% Setup
import os
import re

import numpy as np
import pandas as pd

import codesplash as cs
from codesplash import ml as csml
from codesplash.text import ngram_lm as lm
from codesplash.text import word_vectors as wv

# %% Rows with at least one word
TEXT = "text"
TOKENS = "words"
LOWER = True
df = pd.read_parquet("tests/parity/fixtures/ml_corpus.parquet", columns=[TEXT])
warnings = []
docs_all = [lm.tokenize(t, TOKENS, LOWER) for t in df[TEXT]]
rows = [i for i, d in enumerate(docs_all) if len(d) > 0]
n_dropped = len(df) - len(rows)
if n_dropped:
    warnings.append(f"{n_dropped} rows have no text (or no words) and are left out.")
if not rows:
    cs.cs_error("CS_E_NO_ROWS")  # no row has any words
docs = [docs_all[i] for i in rows]

# %% Vocabulary and windows (rare words removed first; windows never cross rows)
MIN_COUNT = 2
vocab, counts = wv.vocabulary(docs, MIN_COUNT, 2000)
if len(vocab) < 2:
    cs.cs_error("CS_E_UNDEFINED", what="Word vectors", reason=f"fewer than two words occur at least {MIN_COUNT} times")
ids = wv.encode(docs, vocab)
WINDOW = 2
if not wv.pairs(ids, WINDOW):
    cs.cs_error("CS_E_UNDEFINED", what="Word vectors", reason="no two kept words are within the window of each other in any row")
V = len(vocab)
DIM = min(8, V)
if DIM < 8:
    warnings.append(f"Only {V} words are kept, so the vectors have {V} dimensions instead of 8.")

# %% Fit
METHOD = "sgns"
SEED = 42
EPOCHS = 5
LR = None
sv, sv_share, final_loss = None, None, None
if METHOD == "ppmi_svd":
    X = wv.cooccurrence(ids, WINDOW, V, False)
    if not np.any(wv.ppmi(X) > 0):
        cs.cs_error("CS_E_UNDEFINED", what="Word vectors", reason="every pointwise mutual information is zero or negative")
    vectors, sv, sv_share = wv.ppmi_svd(X, DIM)
elif METHOD in ("sgns", "cbow"):
    # Subwords (codesplash.text.subword ↔ cs_subword_*): each word is its own row plus its hashed character n-grams
    from codesplash.text import subword as sw

    if 3 > 6:
        cs.cs_error("CS_E_INVALID_OPTION", option="Shortest n-gram", allowed="at most the longest n-gram (6)", value="3")
    SW_INDEX = sw.Index(vocab, 3, 6, 2000000)
    vectors, SW_IN, final_loss = sw.sgns(ids, counts, SW_INDEX, DIM, WINDOW, 5, EPOCHS if EPOCHS is not None else 20,
                                         LR if LR is not None else (0.025 if METHOD == "sgns" else 0.05), SEED, cbow=METHOD == "cbow")
else:
    vectors, final_loss = wv.glove(wv.cooccurrence(ids, WINDOW, V, True), DIM, EPOCHS if EPOCHS is not None else 50,
                                   LR if LR is not None else 0.05, SEED)

# %% Nearest neighbors of the looked-up words (default: the five most frequent)
QUERY = "match, matches, oven, ovens, zzz"
asked = [w for w in re.split(r"[,\s]+", QUERY.lower() if LOWER else QUERY) if w]
index = {w: i for i, w in enumerate(vocab)}
queries = [w for w in dict.fromkeys(asked) if w in index][:9]
missing = [w for w in dict.fromkeys(asked) if w not in index]
if missing:
    warnings.append("Not in the vocabulary: " + ", ".join(missing) + ".")
if not asked:
    queries = [vocab[i] for i in sorted(range(V), key=lambda i: (-counts[i], i))[:5]]
K = 3
nb_rows = []
values_nb = {}
for q in queries:
    near = wv.neighbors(vectors, vocab, index[q], K)
    for r, (i, c) in enumerate(near, start=1):
        nb_rows.append({"word": q, "rank": r, "neighbor": vocab[i], "cosine": c})
    if near:
        values_nb[f"nearest[{q}]"] = vocab[near[0][0]]
        values_nb[f"similarity[{q}]"] = near[0][1]
# Words outside the vocabulary: a vector from their character n-grams that training used (skip-gram and CBOW only)
built = []
if METHOD in ("sgns", "cbow"):
    for q in missing[: max(0, 9 - len(queries))]:
        vec = sw.oov_vector(q, SW_INDEX, SW_IN)
        if vec is None:
            continue
        near = sw.neighbors_of(vec, vectors, K)
        for r, (i, c) in enumerate(near, start=1):
            nb_rows.append({"word": q, "rank": r, "neighbor": vocab[i], "cosine": c})
        values_nb[f"nearest[{q}]"] = vocab[near[0][0]]
        values_nb[f"similarity[{q}]"] = near[0][1]
        built.append(q)
    if built:
        warnings.append("Built from character n-grams (no vector of their own): " + ", ".join(built) + ".")
        queries = queries + built

# %% Artifacts: one row per word
out = csml.out_dir("target/academy-parity/run-8142/discover.word_vectors/sgns_subword_oov/out-python")
art = pd.DataFrame({"word": vocab, "count": counts.astype(int)})
for k in range(DIM):
    art[f"v{k + 1}"] = vectors[:, k]
art.to_parquet(os.path.join(out, "vectors.parquet"), index=False)

# %% Result
LABELS = {"ppmi_svd": "PPMI-SVD", "sgns": "Skip-gram", "cbow": "CBOW", "glove": "GloVe"}
n_tokens = int(sum(len(d) for d in ids))
values = {
    "n_docs": len(rows), "n_dropped": n_dropped, "n_tokens": n_tokens, "vocab_size": V, "dim": DIM, "window": WINDOW,
    "method": LABELS[METHOD], "final_loss": final_loss, "sv_share": sv_share,
}
if sv is not None:
    for k in range(DIM):
        values[f"sv[{k + 1}]"] = float(sv[k])
if METHOD in ("sgns", "cbow"):
    values["method"] += " with subwords"
    values["subword_buckets"] = len(SW_INDEX.used)
values.update(values_nb)
assumptions = [
    {"key": "enough_text", "label": "Enough text", "status": "warn" if n_tokens < 10000 else "pass",
     "detail": f"{n_tokens} words after rare words were removed" + ("; neighbors on this little text are noisy, so read them as hints." if n_tokens < 10000 else ".")},
    {"key": "window_meaning", "label": "The window sets the kind of similarity", "status": "info",
     "detail": f"A window of {WINDOW} word(s) on each side; smaller windows favor words with the same role, larger ones words on the same topic."},
    {"key": "coordinates_arbitrary", "label": "Coordinates are arbitrary", "status": "info",
     "detail": "Compare neighbors and similarities, not single coordinates; another seed or method rotates the vectors."},
]
nb_cols = [{"key": "word", "label": "Word"}, {"key": "rank", "label": "Rank", "type": "number"},
           {"key": "neighbor", "label": "Neighbor"}, {"key": "cosine", "label": "Cosine similarity", "type": "number"}]
top = sorted(range(V), key=lambda i: (-counts[i], i))[:60]
xy = wv.map_2d(vectors)
charts = [cs.chart("map", "embedding-map", "Map of the most frequent words", {
    "x": cs.col("Component 1", [float(xy[i, 0]) for i in top], "numeric"),
    "y": cs.col("Component 2", [float(xy[i, 1]) for i in top], "numeric"),
    "label": cs.col("Word", [vocab[i] for i in top], "categorical"),
    "size": cs.col("Count", [float(counts[i]) for i in top], "numeric"),
}, note="The first two principal components of the word vectors; words close together are used in similar contexts.")]
if nb_rows:
    charts.append(cs.chart("neighbors", "ngram-bars", "Nearest words", {
        "term": cs.col("Neighbor", [r["neighbor"] for r in nb_rows], "categorical"),
        "count": cs.col("Cosine similarity", [r["cosine"] for r in nb_rows], "numeric"),
        "group": cs.col("Word", [r["word"] for r in nb_rows], "categorical", queries),
    }))
summary = f"{LABELS[METHOD]}: {DIM}-dimensional vectors for {V} words from {n_tokens} words of text."
if queries and f"nearest[{queries[0]}]" in values:
    summary += f" Closest to “{queries[0]}”: {values[f'nearest[{queries[0]}]']} ({values[f'similarity[{queries[0]}]']:.2f})."
stats = [{"key": "vocab_size", "label": "Words with vectors", "value": V}, {"key": "n_tokens", "label": "Words of text", "value": n_tokens},
         {"key": "dim", "label": "Dimensions", "value": DIM}]
if sv_share is not None:
    stats.append({"key": "sv_share", "label": "PPMI kept by these dimensions", "value": sv_share})
if final_loss is not None:
    stats.append({"key": "final_loss", "label": "Loss in the last pass", "value": final_loss})
cs.publish({
    "title": "Word vectors",
    "engine": cs.engine_info("numpy", "pandas"),
    "n": len(rows),
    "summary": summary,
    "statistics": stats,
    "tables": [{"key": "neighbors", "title": "Nearest words", "columns": nb_cols, "rows": nb_rows}],
    "assumptions": assumptions,
    "charts": charts,
    "values": values,
    "warnings": warnings,
    "artifacts": [{"key": "vectors", "path": os.path.join(out, "vectors.parquet"), "format": "parquet"}],
})

"matches" and "ovens" aren't in the vocabulary, yet both get neighbors: the closest word to "matches" is “after”. On a few hundred words of text the neighbors are noisy; the point is that a vector exists at all, built from spelling.

Check yourself

"ovens" never appears in the training text. Where does its vector come from?

Show the answer

Answer: b

With subwords on, every word is the sum of its pieces, so a word the model never saw still gets a vector from its spelling. Without subwords, "ovens" would have no vector at all.

05

Votes for AI labels

Read

Label with AI can ask a local model the same question several times with sampling and keep the most common answer (self-consistencySelf-consistency votesAsks a model the same question several times with sampling and keeps the most common answer; its share is the confidence.). The winning label's share of the votes becomes its confidence. It costs as many calls as there are votes, and the votes share the model's blind spots, so a confident majority can still be wrong. Hosted models here aren't sent a sampling temperature, so votes need Ollama or LM Studio.

Concepts in this lesson