Skip to content

Late interaction: ColBERT's MaxSim as a reranker

ColBERT keeps one vector per token and matches each query token to its best document token. Compute MaxSim by hand, rerank BM25's candidates with it in CodeSplash, and see what reranking fixes and what it can't.

Applied ~13 min8 steps

What runs in CodeSplash

You will be able to

  • Compute a MaxSim score from token similarities
  • Explain why late interaction is used to rerank a short candidate list
  • Read a reranked list against its first-stage scores
  • Recognize failures that reranking leaves in place, such as negation

Read first

01

Token by token

Read

A dense retriever squeezes a whole text into one vector. ColBERT keeps one vector per token and compares texts at the token level, late, after both are encoded. For each query token, find its most similar document token; add those best matches up:

s(q,d)=∑i∈qmax⁡j∈d  qi⊤djs(q, d) = \sum_{i \in q} \max_{j \in d}\; q_i^{\top} d_j

In the reference program, two query tokens meet two document tokens. Their best matches are 1.0 and 0.8, so the MaxSimColBERT MaxSimScores a text by finding, for each query token vector, its best match among the text's token vectors, then summing. score is 1.8. Every query word has to find a partner somewhere in the document.

DExplorable · Retrieval: BM25, dense vectors and late interaction

When does matching words beat matching meanings, and how do we score a ranking?

Query

Each query has graded relevance labels for the ten documents.

Method

BM25 and TF-IDF match words; the toy dense vectors and MaxSim match themes.

3

Metrics look at the top k documents.

1.2

How fast repeated words stop adding score.

0.75

How much long documents are penalized.

  1. 1●○Car insurance prices rise again this year2.12
  2. 2●●How much does vehicle maintenance cost per year2.01
  3. 3○○Bayesian priors and posterior distributions explained0.00
  4. 4○○Weather forecast: heavy rain and strong wind expected tomorrow0.00
  5. 5○○A beginner's guide to the p-value and multiple testing correction0.00
  6. 6○○Baking bread at home: flour, water, yeast and salt0.00
  7. 7○○Storm warning issued as rainfall totals climb0.00
  8. 8●●Fixing an automobile engine: a mechanic explains common repairs0.00
  9. 9○○Bonferroni and Holm corrections control the familywise error rate0.00
  10. 10○○Sourdough starter tips for better loaves0.00
BM250.60 / 0.67TF-IDF cosine0.60 / 0.67Toy dense vectors0.97 / 1.00Late interaction (MaxSim)0.97 / 1.00
  • nDCG@3
  • Recall@3
nDCG@k
0.601
Recall@k
0.667
Precision@k
0.667
Reciprocal rank
1.000
  • Puzzle: For “car repair cost”, find a method that puts both very relevant documents in the top 3.
  • Puzzle: For the query “holm”, find a method with reciprocal rank 1.
BM25 for “car repair cost”: nDCG@3 0.601, recall@3 0.67, reciprocal rank 1.00. The top document is “Car insurance prices rise again this year”. The dense vectors here are a hand-made toy with four themes, not a trained encoder.

BM25 for “car repair cost”: nDCG@3 0.601, recall@3 0.67, reciprocal rank 1.00. The top document is “Car insurance prices rise again this year”. The dense vectors here are a hand-made toy with four themes, not a trained encoder.

02

Why rerank, not search

Read

Token vectors are costly: a passage of a hundred tokens needs a hundred stored vectors instead of one. So ColBERT is often used as a reranker. A cheap first stage, BM25 or a dense search, proposes candidates, and MaxSim rescores only the top ones. The rerank depthRerank depthHow many of the first search's best texts the reranker rescores; a text below it can never be reranked up. sets how many.

A reranker can reorder candidates and pull up ones from below the cutoff, but never find a text the first stage missed entirely. Deeper reranking finds more and costs more.

03

Reranking BM25

Read
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,
})

The same three queries as the BM25 lesson, now with Rerank: ColBERT MaxSim over BM25's top 8. BM25 tied rows 1 and 12 for "late goal in the match"; MaxSim puts row 12 first. Row 4, outside BM25's top five, rises to third. For "interest rates", the four-way BM25 tie is resolved by meaning rather than by row order.

04

What reranking can't fix

Predict

Predict first

The query is "comfortable to wear". One review says "Not comfortable. Blisters on day one." Where can a retriever with ColBERT reranking put it?

It ranks it last, because it says the oppositeIt can rank it high, because it shares the topic wordsIt removes it
Reveal

High. Retrieval scores topical similarity, and "comfortable" matches strongly whether or not a "not" comes first.

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

2 queries over 59 texts by words and meaning (reciprocal rank fusion); best match for query 1: row 2.

Texts
59
Queries
2
Distinct words (BM25)
240

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.079Q1r02
30.613Q1r04
30.524Q1r06
30.519Q1r03
30.998Q2r04
30.932Q2r41
30.829Q2r15
30.807Q2r46

Assumptions

  • Words or meaning — Hybrid search combines both rankings, so a text matched by words or by meaning can rise.
  • English text — The stop list and all-MiniLM-L6-v2 are English.

Best-ranked texts

QueryQuery textRankRowidTextMaxSim scoreBM25 scoreCosine similarityFusion score
1battery life12r02The bass is good, but the battery life is terrible.31.0797.4380.37940.0328
1battery life24r04Comfortable, light and the noise cancelling works really well.30.61300.20410.0306
1battery life36r06Sound quality is okay, nothing special.30.52400.21650.0305
1battery life43r03Not bad at all for the price :)30.51900.20970.0310
2comfortable to wear14r04Comfortable, light and the noise cancelling works really well.30.9982.2480.56230.0315
2comfortable to wear241r41Super comfortable from the first run.30.9322.8410.57210.0325
2comfortable to wear315r15Excellent value, extremely comfortable for long sessions.30.8292.4160.47730.0315
2comfortable to wear446r46Not comfortable. Blisters on day one.30.8072.8410.57570.0325

Ties keep row order. Fusion score = Σ 1 / (k + rank) over the BM25 and the dense rankings. ColBERT reranked the 4 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
1battery life
2comfortable to wear
  • 1 of 60 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 100a00f9ddac368f
# Dataset: s5_reviews (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 <- "review text"
LABEL <- "id"
df <- as.data.frame(nanoparquet::read_parquet("tests/parity/fixtures/s5_reviews.parquet", col_select = c("review text", "id")))
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("battery life; comfortable to wear")
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 <- "hybrid"
TOP_K <- min(as.integer(4), 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(2), 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

2 queries over 59 texts by words and meaning (reciprocal rank fusion); best match for query 1: row 2.

Texts
59
Queries
2
Distinct words (BM25)
240

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

Assumptions

  • Words or meaning — Hybrid search combines both rankings, so a text matched by words or by meaning can rise.
  • English text — The stop list and all-MiniLM-L6-v2 are English.

Best-ranked texts

QueryQuery textRankRowidTextMaxSim scoreBM25 scoreCosine similarityFusion score
1battery life12r02The bass is good, but the battery life is terrible.31.0797.4380.37940.0328
1battery life24r04Comfortable, light and the noise cancelling works really well.30.61300.20410.0306
1battery life36r06Sound quality is okay, nothing special.30.52400.21650.0305
1battery life43r03Not bad at all for the price :)30.51900.20970.0310
2comfortable to wear14r04Comfortable, light and the noise cancelling works really well.30.9982.2480.56230.0315
2comfortable to wear241r41Super comfortable from the first run.30.9322.8410.57210.0325
2comfortable to wear315r15Excellent value, extremely comfortable for long sessions.30.8292.4160.47730.0315
2comfortable to wear446r46Not comfortable. Blisters on day one.30.8072.8410.57570.0325

Ties keep row order. Fusion score = Σ 1 / (k + rank) over the BM25 and the dense rankings. ColBERT reranked the 4 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
1battery life
2comfortable to wear
  • 1 of 60 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 100a00f9ddac368f
# Dataset: s5_reviews (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 = "review text"
LABEL = "id"
df = pd.read_parquet("tests/parity/fixtures/s5_reviews.parquet", columns=["review text", "id"])
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("battery life; comfortable to wear")
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 = "hybrid"
TOP_K = min(int(4), 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(2), 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,
})

Here that review ranks fourth for "comfortable to wear". If polarity matters, label sentiment or ask a judge; don't expect retrieval scores to carry it.

05

The lab: pooled vectors vs MaxSim

Read

The reference chapter's second lab compares mean-pooled vectors with MaxSim on handcrafted token vectors with graded relevance labels. Both methods retrieve every relevant document in the top two; MaxSim's tied scores, broken by document id, put a less relevant document first, so its graded nDCG drops below the pooled method's.

The lab's point is method, not a winner: score representations and evaluate rankings separately, and compare retrievers on real judged queries, with intervals, at equal index budgets.

06

Where it stands in CodeSplash

Read
07

Check: late interaction

Checkpoint

Check yourself

A query has tokens A and B. A's similarities to the document's tokens are 0.2, 0.9 and 0.4; B's are 0.7, 0.1 and 0.3. What is the MaxSim score?

Show the answer

Answer: b

Take each query token's best match (0.9 for A, 0.7 for B) and add them: 1.6. The document's other tokens don't count.

Check yourself

A relevant text sits at BM25 rank 40, and the rerank depth is 20. What does ColBERT reranking do for it?

Show the answer

Answer: b

A reranker can only reorder what the first stage hands it. Raise the depth, or improve the first stage, to reach deeper texts.

Check yourself

Why is ColBERT usually used to rerank a short list rather than to search a whole collection?

Show the answer

Answer: b

Token-level vectors multiply storage and computation. Reranking spends that cost only on likely candidates.

Check yourself

After reranking, a negative review still ranks high for a positive query. What is the right fix?

Show the answer

Answer: b

Retrieval measures topical similarity. Polarity, correctness and faithfulness need separate checks.

08

Recap

Recap
  • MaxSim adds each query token's best match among the document's tokens.
  • Token vectors are costly, so late interaction reranks a first stage's top candidates; it can't find what the first stage missed.
  • Reranking breaks ties and lifts near misses; it doesn't understand negation.
  • Semantic search offers Rerank: ColBERT MaxSim (answerai-colbert-small-v1) over BM25, dense or hybrid search, in Python and R.

Concepts in this lesson