Skip to content

Sentence embeddings: SBERT, SimCSE, E5 and BGE-M3

One vector per text, so that similar texts land close together. See how SBERT pools a fine-tuned encoder, how SimCSE trains with dropout as the only augmentation, why E5 needs prefixes, and what BGE-M3 adds.

Applied ~15 min8 steps

What runs in CodeSplash

You will be able to

  • Explain mean pooling and cosine similarity for sentence embeddings
  • Describe SimCSE's contrastive objective and the role of its temperature
  • Add the right E5 prefixes and say why they matter
  • Name BGE-M3's three kinds of output and which one runs in CodeSplash

Read first

01

One vector per text

Read

A BERT encoder outputs one vector per token. Comparing two sentences by running them through BERT together is accurate but slow: every pair needs its own pass. Sentence-BERT encodes each text once into a sentence embeddingSentence embeddingA fixed-length vector for a whole text from a model trained so that texts with similar meaning get nearby vectors., usually the mean of its token vectors, and fine-tunes the encoder on sentence pairs so that the vectors of related texts point the same way.

Texts are then compared by cosine similarityCosine similarityThe cosine of the angle between two vectors: 1 for the same direction, 0 for unrelated, −1 for opposite., which ignores length. The reference program compares two vectors pointing in exactly the same direction, one shorter than the other: cosine 1.0.

02

Search by meaning

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

Semantic search with Search by: Meaning embeds each of the 61 texts once with MiniLM, a Sentence-BERT model, and ranks them by cosine to each query. The query about a cake recipe finds a baking text with cosine 0.56, though the two share almost no words.

Cosine values from different encoders aren't on a common scale: compare rankings within one encoder, never raw scores across encoders.

03

SimCSE: dropout as the augmentation

Read

SimCSE fine-tunes an encoder without labels. Pass the same sentence through the encoder twice: dropout makes the two vectors differ slightly. Treat them as a positive pair and the other sentences in the batch as negatives, with the InfoNCEInfoNCE lossA loss that asks each row to pick out its own corrupted view among the views of every row in the batch. loss:

ℓ=−log⁡ecos⁡(hi,hi+)/τ∑jecos⁡(hi,hj)/τ\ell = -\log\frac{e^{\cos(h_i, h_i^{+})/\tau}}{\sum_j e^{\cos(h_i, h_j)/\tau}}

The temperature τ sharpens the contrast. With similarities to the positive and two negatives and τ = 0.1, the reference program's loss is 0.0068: the positive already wins by a wide margin. The loss also spreads vectors apart, countering the tendency of raw BERT vectors to crowd into a narrow cone.

The contrastive loss behind it, 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.

04

E5: tell the encoder which side it is on

Read

E5E5 text embeddingsSentence embeddings trained on text pairs; each text is read as "query: …" or "passage: …". was trained on hundreds of millions of text pairs with two prefixes: query: before searches and passage: before the documents searched. Leave them off and the vectors drift from what the model learned. CodeSplash adds them for you.

On the same reviews, settings and folds, a frozen E5-small with a linear head reaches cross-validated ROC AUC 0.884, against 0.827 for MiniLM. Three folds on a few dozen reviews is thin evidence; repeat on your own data.

05

BGE-M3: three outputs from one model

Read

BGE-M3BGE-M3 embeddingsA multilingual embedding model; through a local Ollama it gives 1,024-value dense vectors, cached per text. gives each text three things at once: a dense vector, sparse per-token weights like a learned keyword index, and one vector per token for late interaction. Their scores can be blended; the reference program mixes all three with fixed weights into hybrid scores 0.66 and 0.62 for two documents.

In CodeSplash, BGE-M3's dense vectors run through a local Ollama model as the Embedding model, cached per model. Its sparse and multi-vector outputs are explained here only.

06

Where it stands in CodeSplash

Read
EntryIn CodeSplash
Sentence-BERT (LNG017)Runs in CodeSplash: MiniLM in Semantic search, BERTopic, Zero-shot text labels and Text encoder
SimCSE (LNG018)Explained here
E5 (LNG019)Runs in CodeSplash: Encoder: E5-small-v2 in Text encoder, prefixes added for you
BGE-M3 (LNG020)Partly runs in CodeSplash: dense vectors through a local Ollama model; sparse and multi-vector outputs aren't built
Reference · LNG020 · Partly runs in CodeSplash (Predict)BGE-M3 embeddingsCombines multilingual text representations with dense, sparse, and multi-vector retrieval modes in one embedding framework.
07

Check: sentence embeddings

Checkpoint

Check yourself

Why encode each text once (Sentence-BERT) rather than feed every pair of texts through BERT together?

Show the answer

Answer: b

Joint encoding is accurate but scales with the number of pairs. Separate embeddings can be computed once, stored and searched quickly.

Check yourself

Encoder A gives two texts cosine 0.82; encoder B gives them 0.45. What can you conclude?

Show the answer

Answer: b

Each encoder spreads its vectors differently. Rankings and retrieval metrics compare encoders; raw cosines don't.

Check yourself

In unsupervised SimCSE, where does the positive pair come from?

Show the answer

Answer: b

Dropout noise is the only augmentation; everything else in the batch serves as negatives.

Check yourself

What does lowering SimCSE's temperature τ do?

Show the answer

Answer: b

Dividing similarities by a small τ stretches their differences before the softmax. Too small can make training unstable.

Check yourself

You embed a search query with E5 but forget the query: prefix. What is the risk?

Show the answer

Answer: b

E5 learned different roles for "query:" and "passage:" texts. CodeSplash adds the prefixes automatically.

Check yourself

E5-small beats MiniLM by a few points of ROC AUC on 48 training reviews over three folds. What is the honest summary?

Show the answer

Answer: b

A small gap on few rows can flip with a different split. Repeated cross-validation and a paired comparison settle it.

Check yourself

Which three outputs does BGE-M3 produce for a text?

Show the answer

Answer: a

One model serves dense, lexical-style and late-interaction retrieval. In CodeSplash only its dense vectors run, through a local Ollama model.

Check yourself

You switch the embedding model from MiniLM to BGE-M3 for a search index. What must happen to the stored document vectors?

Show the answer

Answer: b

Vectors from different encoders can't be compared with each other. CodeSplash caches vectors per model for this reason.

08

Recap

Recap
  • Sentence-BERT pools a pair-trained encoder into one vector per text; compare with cosine, rankings within one encoder.
  • SimCSE uses dropout as augmentation and InfoNCE with a temperature.
  • E5 needs query: and passage: prefixes; CodeSplash adds them.
  • BGE-M3 gives dense, sparse and multi-vector outputs; its dense vectors run here through Ollama.

Concepts in this lesson