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.
What runs in CodeSplash
- LNG054Dense Passage Retrieval (DPR) Runs in CodeSplash
- LNG056SPLADE sparse lexical retrieval Explained here
- LNG057Contriever Explained here
- Semantic search (BM25, sentence embeddings, hybrid) Not verified yet
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
Matching words
ReadBM25BM25A 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.
3 queries over 61 texts by words (BM25); best match for query 1: row 1.
- Texts
- 61
- Queries
- 3
- Distinct words (BM25)
- 231
Plots
View data
| BM25 score | Query | Text |
|---|---|---|
| 7.521 | Q1 | d01 |
| 7.521 | Q1 | d12 |
| 2.797 | Q1 | d07 |
| 2.188 | Q1 | d19 |
| 2.055 | Q1 | d03 |
| 6.653 | Q2 | d36 |
| 6.044 | Q2 | d27 |
| 3.856 | Q2 | d28 |
| 3.327 | Q2 | d31 |
| 2.905 | Q2 | d32 |
| 4.028 | Q3 | d50 |
| 3.784 | Q3 | d41 |
| 3.784 | Q3 | d42 |
| 3.784 | Q3 | d46 |
| 3.784 | Q3 | d57 |
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
| Query | Query text | Rank | Row | doc | Text | BM25 score |
|---|---|---|---|---|---|---|
| 1 | late goal in the match | 1 | 1 | d01 | The striker scored a late goal and the team won the match at home | 7.521 |
| 1 | late goal in the match | 2 | 12 | d12 | League rivals met in a tense match that ended with a late goal | 7.521 |
| 1 | late goal in the match | 3 | 7 | d07 | The referee awarded a penalty and the striker scored the winning goal | 2.797 |
| 1 | late goal in the match | 4 | 19 | d19 | Training focused on set pieces before the derby match | 2.188 |
| 1 | late goal in the match | 5 | 3 | d03 | The coach praised the defence after a clean sheet in the league match | 2.055 |
| 2 | bake bread with flour and butter | 1 | 36 | d36 | Slice the bread and serve it warm with butter and soup | 6.653 |
| 2 | bake bread with flour and butter | 2 | 27 | d27 | Bake the bread until the crust is golden and sounds hollow | 6.044 |
| 2 | bake bread with flour and butter | 3 | 28 | d28 | Whisk the eggs with sugar then fold in the flour gently | 3.856 |
| 2 | bake bread with flour and butter | 4 | 31 | d31 | Fry the fish in butter and finish it with lemon and herbs | 3.327 |
| 2 | bake bread with flour and butter | 5 | 32 | d32 | Let the dough rest before you roll it out and bake it | 2.905 |
| 3 | interest rates | 1 | 50 | d50 | The currency weakened after the bank cut interest rates | 4.028 |
| 3 | interest rates | 2 | 41 | d41 | Shares fell as investors worried about rising interest rates | 3.784 |
| 3 | interest rates | 3 | 42 | d42 | The central bank raised interest rates to slow inflation | 3.784 |
| 3 | interest rates | 4 | 46 | d46 | Inflation eased and the bank signalled lower interest rates | 3.784 |
| 3 | interest rates | 5 | 57 | d57 | The fund manager bought bonds as interest rates peaked | 3.784 |
Ties keep row order.
Queries
| Query | Text |
|---|---|
| 1 | late goal in the match |
| 2 | bake bread with flour and butter |
| 3 | interest 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
))
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
| Query | Query text | Rank | Row | doc | Text | BM25 score |
|---|---|---|---|---|---|---|
| 1 | late goal in the match | 1 | 1 | d01 | The striker scored a late goal and the team won the match at home | 7.521 |
| 1 | late goal in the match | 2 | 12 | d12 | League rivals met in a tense match that ended with a late goal | 7.521 |
| 1 | late goal in the match | 3 | 7 | d07 | The referee awarded a penalty and the striker scored the winning goal | 2.797 |
| 1 | late goal in the match | 4 | 19 | d19 | Training focused on set pieces before the derby match | 2.188 |
| 1 | late goal in the match | 5 | 3 | d03 | The coach praised the defence after a clean sheet in the league match | 2.055 |
| 2 | bake bread with flour and butter | 1 | 36 | d36 | Slice the bread and serve it warm with butter and soup | 6.653 |
| 2 | bake bread with flour and butter | 2 | 27 | d27 | Bake the bread until the crust is golden and sounds hollow | 6.044 |
| 2 | bake bread with flour and butter | 3 | 28 | d28 | Whisk the eggs with sugar then fold in the flour gently | 3.856 |
| 2 | bake bread with flour and butter | 4 | 31 | d31 | Fry the fish in butter and finish it with lemon and herbs | 3.327 |
| 2 | bake bread with flour and butter | 5 | 32 | d32 | Let the dough rest before you roll it out and bake it | 2.905 |
| 3 | interest rates | 1 | 50 | d50 | The currency weakened after the bank cut interest rates | 4.028 |
| 3 | interest rates | 2 | 41 | d41 | Shares fell as investors worried about rising interest rates | 3.784 |
| 3 | interest rates | 3 | 42 | d42 | The central bank raised interest rates to slow inflation | 3.784 |
| 3 | interest rates | 4 | 46 | d46 | Inflation eased and the bank signalled lower interest rates | 3.784 |
| 3 | interest rates | 5 | 57 | d57 | The fund manager bought bonds as interest rates peaked | 3.784 |
Ties keep row order.
Queries
| Query | Text |
|---|---|
| 1 | late goal in the match |
| 2 | bake bread with flour and butter |
| 3 | interest 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.
Matching meaning: DPR
ReadA 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.
3 queries over 61 texts by meaning (sentence embeddings); best match for query 1: row 1.
- Texts
- 61
- Queries
- 3
Plots
View data
| Cosine similarity | Query | Text |
|---|---|---|
| 0.4538 | Q1 | d01 |
| 0.4193 | Q1 | d12 |
| 0.4105 | Q1 | d07 |
| 0.5649 | Q2 | d39 |
| 0.4048 | Q2 | d27 |
| 0.3409 | Q2 | d28 |
| 0.4967 | Q3 | d58 |
| 0.4616 | Q3 | d42 |
| 0.4565 | Q3 | d46 |
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
| Query | Query text | Rank | Row | doc | Text | Cosine similarity |
|---|---|---|---|---|---|---|
| 1 | football game result | 1 | 1 | d01 | The striker scored a late goal and the team won the match at home | 0.4538 |
| 1 | football game result | 2 | 12 | d12 | League rivals met in a tense match that ended with a late goal | 0.4193 |
| 1 | football game result | 3 | 7 | d07 | The referee awarded a penalty and the striker scored the winning goal | 0.4105 |
| 2 | a recipe for a cake | 1 | 39 | d39 | Bake the cake for forty minutes and let it cool on a rack | 0.5649 |
| 2 | a recipe for a cake | 2 | 27 | d27 | Bake the bread until the crust is golden and sounds hollow | 0.4048 |
| 2 | a recipe for a cake | 3 | 28 | d28 | Whisk the eggs with sugar then fold in the flour gently | 0.3409 |
| 3 | the economy is slowing down | 1 | 58 | d58 | Markets fell sharply on fears of slower growth and higher rates | 0.4967 |
| 3 | the economy is slowing down | 2 | 42 | d42 | The central bank raised interest rates to slow inflation | 0.4616 |
| 3 | the economy is slowing down | 3 | 46 | d46 | Inflation eased and the bank signalled lower interest rates | 0.4565 |
Ties keep row order.
Queries
| Query | Text |
|---|---|
| 1 | football game result |
| 2 | a recipe for a cake |
| 3 | the 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
))
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
| Query | Query text | Rank | Row | doc | Text | Cosine similarity |
|---|---|---|---|---|---|---|
| 1 | football game result | 1 | 1 | d01 | The striker scored a late goal and the team won the match at home | 0.4538 |
| 1 | football game result | 2 | 12 | d12 | League rivals met in a tense match that ended with a late goal | 0.4193 |
| 1 | football game result | 3 | 7 | d07 | The referee awarded a penalty and the striker scored the winning goal | 0.4105 |
| 2 | a recipe for a cake | 1 | 39 | d39 | Bake the cake for forty minutes and let it cool on a rack | 0.5649 |
| 2 | a recipe for a cake | 2 | 27 | d27 | Bake the bread until the crust is golden and sounds hollow | 0.4048 |
| 2 | a recipe for a cake | 3 | 28 | d28 | Whisk the eggs with sugar then fold in the flour gently | 0.3409 |
| 3 | the economy is slowing down | 1 | 58 | d58 | Markets fell sharply on fears of slower growth and higher rates | 0.4967 |
| 3 | the economy is slowing down | 2 | 42 | d42 | The central bank raised interest rates to slow inflation | 0.4616 |
| 3 | the economy is slowing down | 3 | 46 | d46 | Inflation eased and the bank signalled lower interest rates | 0.4565 |
Ties keep row order.
Queries
| Query | Text |
|---|---|
| 1 | football game result |
| 2 | a recipe for a cake |
| 3 | the 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.
Learned sparse: SPLADE
ReadSPLADELearned 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.
Without labels: Contriever
ReadContriever 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?
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.
Multiplied by min(τ, 0.15)², so low temperatures take smaller steps.
Commit your prediction above to see the result
Make your prediction to see the result.
Fusing two rankings
ReadReciprocal 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.
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
View data
| Fusion score | Query | Text |
|---|---|---|
| 0.0931 | Q1 | Row 2 |
| 0.0911 | Q1 | Row 11 |
| 0.0889 | Q1 | Row 7 |
| 0.0817 | Q1 | Row 14 |
| 0.0931 | Q2 | Row 51 |
| 0.0911 | Q2 | Row 45 |
| 0.0839 | Q2 | Row 58 |
| 0.0745 | Q2 | Row 53 |
| 0.0952 | Q3 | Row 25 |
| 0.0672 | Q3 | Row 1 |
| 0.0661 | Q3 | Row 3 |
| 0.0639 | Q3 | Row 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
| Query | Query text | Rank | Row | Text | Fusion score | BM25 score | Cosine similarity |
|---|---|---|---|---|---|---|---|
| 1 | goalkeeper saved a penalty | 1 | 2 | Fans cheered as the goalkeeper saved a penalty in the final minute | 0.0931 | 9.216 | 0.7317 |
| 1 | goalkeeper saved a penalty | 2 | 11 | The goalkeeper made three saves to keep the team in the cup | 0.0911 | 2.797 | 0.7613 |
| 1 | goalkeeper saved a penalty | 3 | 7 | The referee awarded a penalty and the striker scored the winning goal | 0.0889 | 2.797 | 0.6687 |
| 1 | goalkeeper saved a penalty | 4 | 14 | A penalty miss cost the team the match against the league leaders | 0.0817 | 2.797 | 0.5440 |
| 2 | stock markets | 1 | 51 | Stock markets hit a record as investors bought technology shares | 0.0931 | 4.859 | 0.5988 |
| 2 | stock markets | 2 | 45 | Investors moved money into bonds as stock markets fell | 0.0911 | 5.154 | 0.4718 |
| 2 | stock markets | 3 | 58 | Markets fell sharply on fears of slower growth and higher rates | 0.0839 | 2.222 | 0.5311 |
| 2 | stock markets | 4 | 53 | Bond markets priced in further interest rate rises this year | 0.0745 | 2.357 | 0.3239 |
| 3 | roasting vegetables | 1 | 25 | Roast the vegetables with olive oil garlic and fresh herbs | 0.0952 | 3.622 | 0.7718 |
| 3 | roasting vegetables | 2 | 1 | The striker scored a late goal and the team won the match at home | 0.0672 | 0 | 0.0521 |
| 3 | roasting vegetables | 3 | 3 | The coach praised the defence after a clean sheet in the league match | 0.0661 | 0 | 0.0958 |
| 3 | roasting vegetables | 4 | 29 | Simmer the beans with tomatoes onions and a pinch of salt | 0.0639 | 0 | 0.3891 |
Ties keep row order. Fusion score = Σ 1 / (k + rank) over the BM25 and the dense rankings.
Queries
| Query | Text |
|---|---|
| 1 | goalkeeper saved a penalty |
| 2 | stock markets |
| 3 | roasting 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
))
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
| Query | Query text | Rank | Row | Text | Fusion score | BM25 score | Cosine similarity |
|---|---|---|---|---|---|---|---|
| 1 | goalkeeper saved a penalty | 1 | 2 | Fans cheered as the goalkeeper saved a penalty in the final minute | 0.0931 | 9.216 | 0.7317 |
| 1 | goalkeeper saved a penalty | 2 | 11 | The goalkeeper made three saves to keep the team in the cup | 0.0911 | 2.797 | 0.7613 |
| 1 | goalkeeper saved a penalty | 3 | 7 | The referee awarded a penalty and the striker scored the winning goal | 0.0889 | 2.797 | 0.6687 |
| 1 | goalkeeper saved a penalty | 4 | 14 | A penalty miss cost the team the match against the league leaders | 0.0817 | 2.797 | 0.5440 |
| 2 | stock markets | 1 | 51 | Stock markets hit a record as investors bought technology shares | 0.0931 | 4.859 | 0.5988 |
| 2 | stock markets | 2 | 45 | Investors moved money into bonds as stock markets fell | 0.0911 | 5.154 | 0.4718 |
| 2 | stock markets | 3 | 58 | Markets fell sharply on fears of slower growth and higher rates | 0.0839 | 2.222 | 0.5311 |
| 2 | stock markets | 4 | 53 | Bond markets priced in further interest rate rises this year | 0.0745 | 2.357 | 0.3239 |
| 3 | roasting vegetables | 1 | 25 | Roast the vegetables with olive oil garlic and fresh herbs | 0.0952 | 3.622 | 0.7718 |
| 3 | roasting vegetables | 2 | 1 | The striker scored a late goal and the team won the match at home | 0.0672 | 0 | 0.0521 |
| 3 | roasting vegetables | 3 | 3 | The coach praised the defence after a clean sheet in the league match | 0.0661 | 0 | 0.0958 |
| 3 | roasting vegetables | 4 | 29 | Simmer the beans with tomatoes onions and a pinch of salt | 0.0639 | 0 | 0.3891 |
Ties keep row order. Fusion score = Σ 1 / (k + rank) over the BM25 and the dense rankings.
Queries
| Query | Text |
|---|---|
| 1 | goalkeeper saved a penalty |
| 2 | stock markets |
| 3 | roasting 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.
Metrics look at the top k documents.
How fast repeated words stop adding score.
How much long documents are penalized.
- 1●○Car insurance prices rise again this year2.12
- 2●●How much does vehicle maintenance cost per year2.01
- 3○○Bayesian priors and posterior distributions explained0.00
- 4○○Weather forecast: heavy rain and strong wind expected tomorrow0.00
- 5○○A beginner's guide to the p-value and multiple testing correction0.00
- 6○○Baking bread at home: flour, water, yeast and salt0.00
- 7○○Storm warning issued as rainfall totals climb0.00
- 8●●Fixing an automobile engine: a mechanic explains common repairs0.00
- 9○○Bonferroni and Holm corrections control the familywise error rate0.00
- 10○○Sourdough starter tips for better loaves0.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.
Where it stands in CodeSplash
Read| Entry | In 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 |
Check: retrieval
CheckpointCheck 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.
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