Skip to content

Finding passages: BM25, dense retrieval, SPLADE and Contriever

Retrieval by shared words or by meaning. Run BM25 and dense search side by side, see how DPR, SPLADE and Contriever are trained, and fuse rankings with reciprocal rank fusion, while watching for ties and filler results.

Applied ~16 min8 steps

What runs in CodeSplash

You will be able to

  • Explain what BM25 rewards and where it fails
  • Describe how a dense bi-encoder such as DPR is trained with negatives
  • Contrast learned sparse retrieval (SPLADE) with BM25 and dense vectors
  • Read a fused ranking critically, including ties and filler results

Read first

01

Matching words

Read

BM25BM25A text-search score that adds up the query's words found in a text, weighting rare words more and long texts less. scores a document by the query words it contains. Rare words count more than common ones (inverse document frequency), extra repeats of a word count less and less (saturation, set by k1), and long documents are discounted (length normalization, set by b). It needs no training and no download, and it is hard to beat on names, codes and exact phrases.

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

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

Texts
61
Queries
3
Distinct words (BM25)
231

Plots

Best-ranked texts per query (bm25 score)Which words or phrases appear most in a text column, overall or by group?
View data
BM25 scoreQueryText
7.521Q1d01
7.521Q1d12
2.797Q1d07
2.188Q1d19
2.055Q1d03
6.653Q2d36
6.044Q2d27
3.856Q2d28
3.327Q2d31
2.905Q2d32
4.028Q3d50
3.784Q3d41
3.784Q3d42
3.784Q3d46
3.784Q3d57

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 textRankRowdocTextBM25 score
1late goal in the match11d01The striker scored a late goal and the team won the match at home7.521
1late goal in the match212d12League rivals met in a tense match that ended with a late goal7.521
1late goal in the match37d07The referee awarded a penalty and the striker scored the winning goal2.797
1late goal in the match419d19Training focused on set pieces before the derby match2.188
1late goal in the match53d03The coach praised the defence after a clean sheet in the league match2.055
2bake bread with flour and butter136d36Slice the bread and serve it warm with butter and soup6.653
2bake bread with flour and butter227d27Bake the bread until the crust is golden and sounds hollow6.044
2bake bread with flour and butter328d28Whisk the eggs with sugar then fold in the flour gently3.856
2bake bread with flour and butter431d31Fry the fish in butter and finish it with lemon and herbs3.327
2bake bread with flour and butter532d32Let the dough rest before you roll it out and bake it2.905
3interest rates150d50The currency weakened after the bank cut interest rates4.028
3interest rates241d41Shares fell as investors worried about rising interest rates3.784
3interest rates342d42The central bank raised interest rates to slow inflation3.784
3interest rates446d46Inflation eased and the bank signalled lower interest rates3.784
3interest rates557d57The fund manager bought bonds as interest rates peaked3.784

Ties keep row order.

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 611d7166eac896fa
# 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(5), 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)

# %% 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)
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]
    }
    result_rows[[length(result_rows) + 1]] <- row
  }
}
score_label <- c(bm25 = "BM25 score", dense = "Cosine similarity", hybrid = "Fusion score")[[RETRIEVER]]
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")))
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 "")),
  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 1.

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 textRankRowdocTextBM25 score
1late goal in the match11d01The striker scored a late goal and the team won the match at home7.521
1late goal in the match212d12League rivals met in a tense match that ended with a late goal7.521
1late goal in the match37d07The referee awarded a penalty and the striker scored the winning goal2.797
1late goal in the match419d19Training focused on set pieces before the derby match2.188
1late goal in the match53d03The coach praised the defence after a clean sheet in the league match2.055
2bake bread with flour and butter136d36Slice the bread and serve it warm with butter and soup6.653
2bake bread with flour and butter227d27Bake the bread until the crust is golden and sounds hollow6.044
2bake bread with flour and butter328d28Whisk the eggs with sugar then fold in the flour gently3.856
2bake bread with flour and butter431d31Fry the fish in butter and finish it with lemon and herbs3.327
2bake bread with flour and butter532d32Let the dough rest before you roll it out and bake it2.905
3interest rates150d50The currency weakened after the bank cut interest rates4.028
3interest rates241d41Shares fell as investors worried about rising interest rates3.784
3interest rates342d42The central bank raised interest rates to slow inflation3.784
3interest rates446d46Inflation eased and the bank signalled lower interest rates3.784
3interest rates557d57The fund manager bought bonds as interest rates peaked3.784

Ties keep row order.

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 611d7166eac896fa
# 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(5), 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)])

# %% 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}
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])
        result_rows.append(row)
score_label = {"bm25": "BM25 score", "dense": "Cosine similarity", "hybrid": "Fusion score"}[RETRIEVER]
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"}]
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 "")},
    {"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,
})

For "interest rates", the top text scores 4.03, and the next four tie at 3.78: they contain the same query words once each. Their order is a tie-break, not a judgment.

02

Matching meaning: DPR

Read

A dense retrieverDense retrievalSearch that embeds each text and query and ranks texts by cosine similarity, so a match can share meaning without sharing words. encodes queries and passages separately into vectors and ranks passages by dot product. Dense Passage Retrieval trained two BERT encoders on question–passage pairs. Each question's true passage is contrasted with the other passages in the batch and with hard negativesHard negativesWrong but plausible examples (like BM25 hits that don't answer), used in training so a retriever learns more than word overlap.: passages BM25 ranks high that don't answer it.

In the reference program one query scores three passages 0.98, 0.80 and −0.34; the softmax loss for the first being correct is 0.743.

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

3 queries over 61 texts by meaning (sentence embeddings); best match for query 1: row 1.

Texts
61
Queries
3

Plots

Best-ranked texts per query (cosine similarity)Which words or phrases appear most in a text column, overall or by group?
View data
Cosine similarityQueryText
0.4538Q1d01
0.4193Q1d12
0.4105Q1d07
0.5649Q2d39
0.4048Q2d27
0.3409Q2d28
0.4967Q3d58
0.4616Q3d42
0.4565Q3d46

Assumptions

  • Words or meaning — Dense search matches meaning; exact names, numbers and codes can rank lower than with BM25.
  • English text — The stop list and all-MiniLM-L6-v2 are English.

Best-ranked texts

QueryQuery textRankRowdocTextCosine similarity
1football game result11d01The striker scored a late goal and the team won the match at home0.4538
1football game result212d12League rivals met in a tense match that ended with a late goal0.4193
1football game result37d07The referee awarded a penalty and the striker scored the winning goal0.4105
2a recipe for a cake139d39Bake the cake for forty minutes and let it cool on a rack0.5649
2a recipe for a cake227d27Bake the bread until the crust is golden and sounds hollow0.4048
2a recipe for a cake328d28Whisk the eggs with sugar then fold in the flour gently0.3409
3the economy is slowing down158d58Markets fell sharply on fears of slower growth and higher rates0.4967
3the economy is slowing down242d42The central bank raised interest rates to slow inflation0.4616
3the economy is slowing down346d46Inflation eased and the bank signalled lower interest rates0.4565

Ties keep row order.

Queries

QueryText
1football game result
2a recipe for a cake
3the economy is slowing down
  • 1 of 62 rows were left out because a value was missing.
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 91d002dcec445888
# 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("football game result; a recipe for a cake; the economy is slowing down")
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 <- "dense"
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)

# %% 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)
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]
    }
    result_rows[[length(result_rows) + 1]] <- row
  }
}
score_label <- c(bm25 = "BM25 score", dense = "Cosine similarity", hybrid = "Fusion score")[[RETRIEVER]]
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")))
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 "")),
  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 meaning (sentence embeddings); best match for query 1: row 1.

Texts
61
Queries
3

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

Assumptions

  • Words or meaning — Dense search matches meaning; exact names, numbers and codes can rank lower than with BM25.
  • English text — The stop list and all-MiniLM-L6-v2 are English.

Best-ranked texts

QueryQuery textRankRowdocTextCosine similarity
1football game result11d01The striker scored a late goal and the team won the match at home0.4538
1football game result212d12League rivals met in a tense match that ended with a late goal0.4193
1football game result37d07The referee awarded a penalty and the striker scored the winning goal0.4105
2a recipe for a cake139d39Bake the cake for forty minutes and let it cool on a rack0.5649
2a recipe for a cake227d27Bake the bread until the crust is golden and sounds hollow0.4048
2a recipe for a cake328d28Whisk the eggs with sugar then fold in the flour gently0.3409
3the economy is slowing down158d58Markets fell sharply on fears of slower growth and higher rates0.4967
3the economy is slowing down242d42The central bank raised interest rates to slow inflation0.4616
3the economy is slowing down346d46Inflation eased and the bank signalled lower interest rates0.4565

Ties keep row order.

Queries

QueryText
1football game result
2a recipe for a cake
3the economy is slowing down
  • 1 of 62 rows were left out because a value was missing.
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 91d002dcec445888
# 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("football game result; a recipe for a cake; the economy is slowing down")
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 = "dense"
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)])

# %% 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}
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])
        result_rows.append(row)
score_label = {"bm25": "BM25 score", "dense": "Cosine similarity", "hybrid": "Fusion score"}[RETRIEVER]
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"}]
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 "")},
    {"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,
})

"football game result" finds a match report that shares none of those words.

03

Learned sparse: SPLADE

Read

SPLADELearned sparse retrievalRetrieval with sparse, learned word weights that can include words absent from the text (synonyms), served from an inverted index. keeps BM25's inverted index but learns the weights. A masked-language-model head scores every vocabulary word for each passage, including words that don't appear, and keeps a sparse set: "car" can add weight to "vehicle". Each word's weight is the log of one plus its largest positive score over the passage's tokens.

The reference program gets weights 0.693, 0.588 and 0.405 for three vocabulary words, and a query–passage score of 0.336.

04

Without labels: Contriever

Read

Contriever trains a dense retriever with no question–passage pairs: two random crops of the same document are a positive pair, other documents are negatives, under a contrastive loss with temperature τ. The reference program shows how much τ matters. The same similarities give loss 0.051 at τ = 0.1, 0.615 at 0.5 and 0.828 at 1.

Unsupervised retrievers help where no labeled pairs exist, and they are often fine-tuned afterwards.

Reference · LNG057 · Explained hereContrieverLearns dense retrieval representations from unlabeled text through contrastive training. Different views or spans of the same document provide positive pairs, reducing dependence on human relevance labels for…

The contrastive loss behind dense retrievers, on a toy you can train here.

DExplorable · InfoNCE: temperature, negatives, collapse

How does contrastive learning learn useful embeddings without labels, and what keeps it from collapsing?

After training with this objective, where do the embeddings end up?

How sure?
0.20

Batch size

Each item's negatives are the rest of the batch.

Objective

Without labels, a batch can't tell them apart. Off: they're masked out.

0.30
300
0.80

Multiplied by min(τ, 0.15)², so low temperatures take smaller steps.

Simulating…

Commit your prediction above to see the result

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

Make your prediction to see the result.

05

Fusing two rankings

Read

Reciprocal rank fusionReciprocal rank fusion (RRF)Combines rankings by adding 1 / (k + rank) from each; a text ranked well by any list rises, and raw scores never need rescaling. adds 1/(k + rank) from each retriever, so a text ranked well by either rises. It uses ranks only, so BM25 scores and cosines needn't share a scale.

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

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

Texts
61
Queries
3
Distinct words (BM25)
231

Plots

Best-ranked texts per query (fusion score)Which words or phrases appear most in a text column, overall or by group?
View data
Fusion scoreQueryText
0.0931Q1Row 2
0.0911Q1Row 11
0.0889Q1Row 7
0.0817Q1Row 14
0.0931Q2Row 51
0.0911Q2Row 45
0.0839Q2Row 58
0.0745Q2Row 53
0.0952Q3Row 25
0.0672Q3Row 1
0.0661Q3Row 3
0.0639Q3Row 29

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 textRankRowTextFusion scoreBM25 scoreCosine similarity
1goalkeeper saved a penalty12Fans cheered as the goalkeeper saved a penalty in the final minute0.09319.2160.7317
1goalkeeper saved a penalty211The goalkeeper made three saves to keep the team in the cup0.09112.7970.7613
1goalkeeper saved a penalty37The referee awarded a penalty and the striker scored the winning goal0.08892.7970.6687
1goalkeeper saved a penalty414A penalty miss cost the team the match against the league leaders0.08172.7970.5440
2stock markets151Stock markets hit a record as investors bought technology shares0.09314.8590.5988
2stock markets245Investors moved money into bonds as stock markets fell0.09115.1540.4718
2stock markets358Markets fell sharply on fears of slower growth and higher rates0.08392.2220.5311
2stock markets453Bond markets priced in further interest rate rises this year0.07452.3570.3239
3roasting vegetables125Roast the vegetables with olive oil garlic and fresh herbs0.09523.6220.7718
3roasting vegetables21The striker scored a late goal and the team won the match at home0.067200.0521
3roasting vegetables33The coach praised the defence after a clean sheet in the league match0.066100.0958
3roasting vegetables429Simmer the beans with tomatoes onions and a pinch of salt0.063900.3891

Ties keep row order. Fusion score = Σ 1 / (k + rank) over the BM25 and the dense rankings.

Queries

QueryText
1goalkeeper saved a penalty
2stock markets
3roasting vegetables
  • 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 24d507113075661b
# 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 <- NULL
df <- as.data.frame(nanoparquet::read_parquet("tests/parity/fixtures/ml_corpus.parquet", col_select = c("text")))
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("goalkeeper saved a penalty; stock markets; roasting vegetables")
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 = 20)))
}
final <- matrix(final, nrow = m)

# %% 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)
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]
    }
    result_rows[[length(result_rows) + 1]] <- row
  }
}
score_label <- c(bm25 = "BM25 score", dense = "Cosine similarity", hybrid = "Fusion score")[[RETRIEVER]]
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")))
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 "")),
  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 and meaning (reciprocal rank fusion); best match for query 1: row 2.

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 — 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 textRankRowTextFusion scoreBM25 scoreCosine similarity
1goalkeeper saved a penalty12Fans cheered as the goalkeeper saved a penalty in the final minute0.09319.2160.7317
1goalkeeper saved a penalty211The goalkeeper made three saves to keep the team in the cup0.09112.7970.7613
1goalkeeper saved a penalty37The referee awarded a penalty and the striker scored the winning goal0.08892.7970.6687
1goalkeeper saved a penalty414A penalty miss cost the team the match against the league leaders0.08172.7970.5440
2stock markets151Stock markets hit a record as investors bought technology shares0.09314.8590.5988
2stock markets245Investors moved money into bonds as stock markets fell0.09115.1540.4718
2stock markets358Markets fell sharply on fears of slower growth and higher rates0.08392.2220.5311
2stock markets453Bond markets priced in further interest rate rises this year0.07452.3570.3239
3roasting vegetables125Roast the vegetables with olive oil garlic and fresh herbs0.09523.6220.7718
3roasting vegetables21The striker scored a late goal and the team won the match at home0.067200.0521
3roasting vegetables33The coach praised the defence after a clean sheet in the league match0.066100.0958
3roasting vegetables429Simmer the beans with tomatoes onions and a pinch of salt0.063900.3891

Ties keep row order. Fusion score = Σ 1 / (k + rank) over the BM25 and the dense rankings.

Queries

QueryText
1goalkeeper saved a penalty
2stock markets
3roasting vegetables
  • 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 24d507113075661b
# 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 = None
df = pd.read_parquet("tests/parity/fixtures/ml_corpus.parquet", columns=["text"])
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("goalkeeper saved a penalty; stock markets; roasting vegetables")
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=20) for j in range(m)])

# %% 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}
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])
        result_rows.append(row)
score_label = {"bm25": "BM25 score", "dense": "Cosine similarity", "hybrid": "Fusion score"}[RETRIEVER]
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"}]
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 "")},
    {"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,
})

For "roasting vegetables", the top result is right, but ranks 2 and 3 are football reports: only one text is about roasting, and the search always fills its k slots. Read a ranking with its scores and a cutoff in mind, never as k relevant texts.

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.

06

Where it stands in CodeSplash

Read
EntryIn CodeSplash
Dense Passage Retrieval (LNG054)Runs in CodeSplash: Semantic search BM25, dense (MiniLM) and hybrid; DPR's own weights are non-commercial
SPLADE (LNG056)Explained here; its weights are non-commercial
Contriever (LNG057)Explained here; its weights are non-commercial
07

Check: retrieval

Checkpoint

Check yourself

A query says "car" and the best document says "vehicle" throughout. How does BM25 rank it?

Show the answer

Answer: b

BM25 matches surface words. Dense retrieval, learned sparse weights or query expansion handle synonyms.

Check yourself

Why did DPR train with BM25-retrieved passages that don't answer the question?

Show the answer

Answer: b

Random negatives are easy to tell apart. Near misses force the model to separate topical similarity from actual answers.

Check yourself

CodeSplash's dense search uses MiniLM rather than the original DPR encoders. Which reason fits CodeSplash's rules?

Show the answer

Answer: b

Only commercially usable weights ship. The bi-encoder idea runs with MiniLM (Apache-2.0) in Semantic search, in Python and R.

Check yourself

What can SPLADE do that BM25 can't?

Show the answer

Answer: b

Its masked-language-model head expands each passage over the vocabulary, keeping sparse, learned weights that an inverted index can still serve.

Check yourself

Why does SPLADE push most vocabulary weights to exactly zero?

Show the answer

Answer: a

A sparsity penalty and the ReLU keep the representation short; dense weights over the whole vocabulary would defeat the index.

Check yourself

Where do Contriever's positive pairs come from?

Show the answer

Answer: b

Cropping turns any collection into contrastive training data, so no labeled question–passage pairs are needed.

Check yourself

Contriever's loss on the same similarities differs a lot between τ = 0.1 and τ = 1. What does that mean in practice?

Show the answer

Answer: b

A small τ sharpens the contrast between the positive and the negatives; too sharp can destabilize training.

Check yourself

A hybrid search for a rare topic returns four results; only the first is on topic. Why?

Show the answer

Answer: b

Rankings always produce k items. Judge relevance with scores, a cutoff or a check of the texts.

08

Recap

Recap
  • BM25 rewards rare shared words, with saturation and length normalization; it fails on synonyms and ties often.
  • Dense retrievers like DPR encode queries and passages separately, trained with in-batch and hard negatives.
  • SPLADE learns sparse expansions; Contriever learns from document crops without labels.
  • Semantic search runs BM25, dense (MiniLM) and RRF hybrid search in Python and R; DPR, SPLADE and Contriever checkpoints are non-commercial, so they are explained here.

Concepts in this lesson