Foundations to Frontier
Tests

Sentence Embeddings and Embedding Models for Retrieval

A sentence embedding maps a whole text to one vector so that texts with similar meaning are close. Embedding models (Sentence-BERT, E5, BGE, GTE and API embedding models) are usually Transformer encoders with mean pooling, fine-tuned contrastively: matching pairs (question and answer, query and passage, paraphrases) are pulled together and other texts in the batch pushed apart (InfoNCE). In a bi-encoder, documents are embedded once and searched by nearest neighbours; a slower cross-encoder can rerank a shortlist. This page covers pooling, contrastive training with in-batch and hard negatives, bi-encoders versus cross-encoders, evaluation (recall@k, MRR) and practical choices. In the exercises you implement masked mean pooling, InfoNCE and top-k search, then retrieve documents for queries written with synonyms of the document's words. TF-IDF found none of them (recall@1 0.00). Mean-pooled word vectors reached 0.32 and IDF-weighted pooling 0.59. Pooling weights learned contrastively from 600 example pairs reached 0.99 on unseen documents, by cutting filler words to 0.12× the weight of content words. A full 64 × 64 projection head trained the same way overfitted (0.81 on training pairs, 0.29 on test).

Level 0: Foundation

★☆☆☆☆ Introductory⏱ 5 minGeneral audience. No mathematics required.

One vector per sentence, for search by meaning

To search by meaning rather than by exact words, turn every sentence into a vector so that sentences meaning the same thing land close together, even if they use different words. “Engine lost thrust” should be near “powerplant failure”. Such embedding models are trained on many pairs of matching texts: they learn to pull each pair together and push unrelated texts apart. The demo shows word vectors; sentence vectors combine them.

Language lab
cos(king, queen) = 0.874. king − man + woman lands nearest to queen: directions in embedding space can encode relations.
Why engineers care

Semantic search over manuals, procedures, incident databases and requirements is built on embedding models. They are the retrieval half of retrieval-augmented generation (F10).

📝 Quick check (Level 0)
0/3 answered
  1. 1. A sentence embedding maps…
  2. 2. Embedding search finds texts that…
  3. 3. Embedding models are trained on…

Level 1: Beginner

★★☆☆☆ Basic⏱ 20 minSecondary-school mathematics: arithmetic and elementary algebra.

By hand

  • Pooling: average the token vectors of an encoder over non-padding positions (mean pooling), or use the [CLS] token. Mean pooling is the usual default.
  • Contrastive training (InfoNCE): for a batch of B pairs (q_i, d_i), loss = −(1/B) Σ log [exp(cos(q_i, d_i)/τ) / Σ_j exp(cos(q_i, d_j)/τ)]. Other documents in the batch serve as negatives. At chance the loss is ln B (4.16 for B = 64). Hard negatives (similar but wrong documents) sharpen the model.
  • Bi-encoder vs cross-encoder: a bi-encoder embeds query and documents separately, so documents are indexed once; a cross-encoder reads (query, document) together and is more accurate but needs one forward pass per document. Use it only to rerank the top results.
  • Evaluation: recall@k (is the right document in the top k?) and mean reciprocal rank (MRR), on benchmarks such as MTEB/BEIR and, more importantly, on your own queries.
  • Storage: 1M documents × 768 float32 dimensions = 3.07 GB; quantised or lower-dimensional (Matryoshka) embeddings cut this.
📝 Quick check (Level 1)
0/3 answered
  1. 1. InfoNCE loss at chance with batch 64:
  2. 2. A cross-encoder is used to…
  3. 3. Recall@2 for ranks 1, 3, 2, 10:

Level 2: Intermediate

★★★☆☆ Intermediate⏱ 25 minUndergraduate students and practising engineers.

Embedding models in code

Exercise 1.

  • Mean-pool token vectors while ignoring padding.
  • Compute the in-batch InfoNCE loss; it equals ln B when documents are indistinguishable.
  • Retrieve the top-k documents by cosine similarity.

Practice.

  • sentence-transformers loads and fine-tunes embedding models (MultipleNegativesRankingLoss is InfoNCE with in-batch negatives); vector databases (F10) store the results.
  • Use the model’s prefixes if it expects them (for example “query: “ and “passage: “ for E5).
  • Fine-tune on a few thousand in-domain pairs when terminology differs from general text; mine hard negatives with BM25.
  • Evaluate on held-out real queries; check that the model is not simply matching surface words.
from sentence_transformers import SentenceTransformer, util
model = SentenceTransformer("BAAI/bge-small-en-v1.5")
docs = ["Loss of engine thrust during climb", "Cabin pressure warning at cruise", "Landing gear failed to retract"]
D = model.encode(docs, normalize_embeddings=True)
q = model.encode("powerplant failure after takeoff", normalize_embeddings=True)
print(util.cos_sim(q, D))       # the first report should score highest
🐍 Exercise 1: pooling, InfoNCE and top-k
Implement masked mean pooling, the in-batch InfoNCE loss and top-k cosine retrieval.
📝 Quick check (Level 2)
0/3 answered
  1. 1. sentence-transformers' InfoNCE loss:
  2. 2. Hard negatives can be mined with…
  3. 3. E5 expects inputs prefixed with…

Level 3: Advanced

★★★★☆ Advanced⏱ 25 minGraduate level, with full derivations and proofs.

Theory

What contrastive training learns. InfoNCE is a lower bound on the mutual information between query and document representations. It rewards features that identify which document matches, and ignores features shared by all texts. Filler words that appear everywhere carry no such information, so a trained model down-weights them.

Why pooling choices matter. Plain averaging gives every token equal weight, so frequent uninformative words dominate the sentence vector. Classic fixes (IDF or SIF weighting, removing the first principal component) help; contrastive fine-tuning learns the weighting from data.

Capacity and overfitting. Few task-specific parameters (per-word weights, or a small head on a strong pretrained encoder) generalise from limited pairs. A large head trained on few pairs memorises them. Large-scale embedding models therefore train on hundreds of millions of weakly supervised pairs before fine-tuning on curated ones.

📝 Quick check (Level 3)
0/3 answered
  1. 1. InfoNCE lower-bounds…
  2. 2. Plain averaging is dominated by…
  3. 3. A large head trained on few pairs tends to…

Level 4: Expert

★★★★★ Expert⏱ 30 minResearchers: original papers and open problems.

Can an embedding model find documents that share no words with the query?

History.

  • N. Reimers and I. Gurevych, “Sentence-BERT” (EMNLP 2019).
  • V. Karpukhin et al., “Dense passage retrieval for open-domain question answering” (EMNLP 2020).
  • S. Arora, Y. Liang and T. Ma, “A simple but tough-to-beat baseline for sentence embeddings” (ICLR 2017), SIF weighting.
  • N. Muennighoff et al., “MTEB: massive text embedding benchmark” (EACL 2023).

Exercise 2.

  • Concepts: 120, each with a document word and a synonym used only in queries; both appear in the same contexts in a 12,000-sentence background corpus, from which 64-dimensional PPMI + SVD word vectors are built.
  • Documents: 6 concepts plus 6 general filler words each. A query names 3 of its document’s concepts with the synonyms, plus 2 filler words, so query and document share no content word.
  • Methods:
    • TF-IDF;
    • mean-pooled word vectors;
    • IDF-weighted pooling;
    • pooling with one weight per word learned by InfoNCE on 600 training query–document pairs.
  • Test: retrieve each of 300 new queries’ document among the 300 new documents.
method recall@1 MRR
TF-IDF (lexical) 0.000 0.028
mean-pooled word vectors 0.317 0.464
IDF-weighted pooling 0.593 0.704
contrastively learned word weights 0.987 0.993
  • Lexical search fails completely when queries use synonyms.
  • Word vectors know the synonyms (each query word’s nearest document word was its synonym 100% of the time), but plain averaging is swamped by filler words.
  • Contrastive training learns what matters: filler words ended with 0.12× the weight of content words, and retrieval on unseen documents became nearly perfect.
  • Capacity matters: a full 64 × 64 projection head trained the same way (300 steps) reached 0.81 recall@1 on its training pairs but only 0.29 on new ones, no better than mean pooling. It memorised 600 pairs; one weight per word generalised.
  • Seeds: seeds 1 and 2 gave learned weights 0.960/0.980, IDF 0.570/0.557, mean 0.343/0.273, TF-IDF 0.007/0.000.
🐍 Exercise 2 (research): can an embedding model find documents that share no words with the query?
Retrieve documents for synonym-based queries with TF-IDF, mean-pooled word vectors, IDF-weighted pooling and contrastively learned word weights.

Embedding models in AI, robotics and aerospace

  • Technical document search: finding the right procedure when operators describe symptoms in their own words.
  • Deduplicating reports: spotting incident reports that describe the same event differently.
  • RAG systems: the retrieval stage that feeds an LLM with relevant documents.
  • Design lesson: train the representation on the matching task itself, with few enough task-specific parameters to generalise.

References

  1. N. Reimers and I. Gurevych (2019). “Sentence-BERT: sentence embeddings using Siamese BERT-networks.” Proc. EMNLP.
  2. V. Karpukhin et al. (2020). “Dense passage retrieval for open-domain question answering.” Proc. EMNLP.
  3. S. Arora, Y. Liang and T. Ma (2017). “A simple but tough-to-beat baseline for sentence embeddings.” Proc. ICLR.
  4. N. Muennighoff, N. Tazi, L. Magne and N. Reimers (2023). “MTEB: massive text embedding benchmark.” Proc. EACL.