12. RAG Foundations — Embeddings, Similarity Search & Reranking#
A fast, conceptual revision guide for 12-rag-embeddings-similarity-reranking. Focused on the "R" (Retrieval) in RAG — how text becomes meaning-preserving vectors, why cosine similarity measures direction rather than length, how Top-K semantic search beats keyword matching, and why production systems pair fast bi-encoders with precise cross-encoder rerankers.
Word Embeddings & Semantic Vector Space#
Revision Notes#
Reference files: 1_GIVE_FIRST_Starter_Code/1_word_embeddings.ipynb, 2_SHARE_AFTER_Solution_Code/1_word_embeddings.ipynb, 2_SHARE_AFTER_Solution_Explainer.html (runs locally, no API key needed)
Concept#
Computers cannot read words or grasp meaning directly — they only operate on numbers. An embedding maps a piece of text to a dense list of floating-point numbers (a vector) learned from large text corpora so that words used in similar contexts land near each other in vector space. In Exercise 1.1, glove-wiki-gigaword-50 (loaded via gensim) maps 400,000 lower-case English words to 50-dimensional vectors (shape = (50,)).
Key Mental Models#
- The "giant map of meanings" analogy: Imagine every word or sentence as a pin on a multi-dimensional map. Related concepts (king, prince, queen, emperor) cluster tightly together, while unrelated ones (king vs. banana) sit far apart.
- Meaning lives in the pattern, not individual numbers: No single coordinate out of the 50 numbers means "royalty" or "gender". Meaning is distributed across the entire vector pattern.
- Semantic relationships are directions ("word maths"): Because contexts encode relationships geometrically, vector arithmetic captures analogies:
- Gender shift:
king − man + woman ≈ queen(start at king, subtract the man direction, add the woman direction). - Capital-of shift:
paris − france + india ≈ delhi(the model learned a "capital of" direction purely from reading Wikipedia and news text).
- Gender shift:
Trade-Offs & Pitfalls#
- The raw vector search gotcha: If you manually compute
model["king"] - model["man"] + model["woman"]and run a plain nearest-neighbour lookup (similar_by_vector), the #1 result is usuallykingitself because the vector only moved slightly from where it started.most_similar(positive=[...], negative=[...])solves this by automatically excluding the input words. - Fixed, lower-case vocabulary: Static word models like GloVe only know words seen during training (all lower-case). Looking up an unknown or capitalized word raises a
KeyError, and a single word gets one static vector regardless of context.
Code Reference#
# Libraries:
# numpy -> maths on lists of numbers (vectors)
# gensim -> gives us ready-made word vectors (GloVe)
import numpy as np
import gensim.downloader as api
# "glove-wiki-gigaword-50" = static GloVe vectors trained on Wikipedia + news co-occurrence stats.
# Every word in its vocabulary (400,000 words) maps to a single 50-dimensional vector
# (context-independent: "bank" has one vector regardless of river vs. finance).
model = api.load("glove-wiki-gigaword-50")
print("Words in vocabulary:", len(model.key_to_index))
# --- next cell ---
# ----- TODO 1: Get the vector for the word "king" and print its shape and first 5 numbers -----
# Hint: The model works like a dictionary: model["some_word"]
# Hint: A numpy array has a .shape attribute
v_king = None # replace None with your code
print("Shape of the 'king' vector:", v_king.shape) # expect (50,)
print("First 5 numbers:", v_king[:5])
# --- next cell ---
# most_similar() computes cosine similarity against all 400k vectors and excludes the query word itself.
for word, score in model.most_similar("king", topn=5):
print(f"{word:<10} {score:.3f}")
# --- next cell ---
# ----- TODO 2: Use word maths to answer "king - man + woman = ?" -----
# Linear analogies work because semantic shifts (gender, royalty, capitals) correspond to
# consistent direction offsets in the embedding space.
# Hint: model.most_similar(positive=[words to add], negative=[words to subtract], topn=1)
answer = None # replace None with your code
print("king - man + woman =", answer)
# --- next cell ---
# The same maths done "by hand" with numpy, to see the gotcha for yourself:
# similar_by_vector() does NOT filter out the input words, so "king" itself often ranks #1.
new_vector = model["king"] - model["man"] + model["woman"]
# -> ndarray shape (50,); raw nearest: [('king', 0.8860), ('queen', 0.8610), ('daughter', 0.7685)]
print("Raw vector search (input words NOT removed):", model.similar_by_vector(new_vector, topn=3))
# --- next cell ---
# ----- TODO 3: Capital cities: "paris - france + india = ?" -----
# Hint: Same pattern as TODO 2. Words to add: paris, india. Word to subtract: france
answer_2 = None # replace None with your code
print("paris - france + india =", answer_2)
# --- next cell ---
# ----- TODO 4: Write a cosine_similarity(a, b) function using numpy -----
# Cosine similarity measures the angle between two vectors (range -1 to 1), ignoring vector
# magnitude so frequent words with larger norms don't dominate similarity scores.
# Hint: np.dot(a, b) gives a · b
# Hint: np.linalg.norm(a) gives |a|
def cosine_similarity(a, b):
return 0.0 # replace with the formula
pairs = [("king", "queen"), ("cricket", "football"), ("king", "banana")]
for w1, w2 in pairs:
mine = cosine_similarity(model[w1], model[w2])
library = model.similarity(w1, w2) # gensim's own answer, to check yours
print(f"{w1:>8} vs {w2:<9} -> my answer: {mine:.3f} | gensim: {library:.3f}")
Words in vocabulary: 400000
# Cell 2 (before TODO 1 is filled in):
# AttributeError: 'NoneType' object has no attribute 'shape'
# Cell 3:
prince 0.824
queen 0.784
ii 0.775
emperor 0.754
son 0.746
# Cell 4 (before TODO 2):
king - man + woman = None
# Cell 5:
Raw vector search (input words NOT removed): [('king', 0.88598347), ('queen', 0.86095822), ('daughter', 0.76845127)]
# Cell 6 (before TODO 3):
paris - france + india = None
# Cell 7 (before TODO 4 — stub returns 0.0):
king vs queen -> my answer: 0.000 | gensim: 0.784
cricket vs football -> my answer: 0.000 | gensim: 0.756
king vs banana -> my answer: 0.000 | gensim: 0.221
# Libraries:
# numpy -> maths on lists of numbers (vectors)
# gensim -> gives us ready-made word vectors (GloVe)
import numpy as np
import gensim.downloader as api
# "glove-wiki-gigaword-50" = static GloVe vectors trained on Wikipedia + news co-occurrence stats.
# Every word in its vocabulary (400,000 words) maps to a 50-dimensional float32 vector.
model = api.load("glove-wiki-gigaword-50")
print("Words in vocabulary:", len(model.key_to_index))
# --- next cell ---
# ----- TODO 1 (solved): Get the vector for the word "king" and print its shape and first 5 numbers -----
# Indexing into KeyedVectors returns the 1D numpy embedding for that token.
v_king = model["king"]
# -> ndarray shape (50,), float32: [0.5045, 0.6861, -0.5952, -0.0228, 0.6005, ...]
print("Shape of the 'king' vector:", v_king.shape) # expect (50,)
print("First 5 numbers:", v_king[:5])
# --- next cell ---
# most_similar() ranks all vocabulary words by cosine similarity and excludes the query token itself.
for word, score in model.most_similar("king", topn=5):
print(f"{word:<10} {score:.3f}")
# --- next cell ---
# ----- TODO 2 (solved): Use word maths to answer "king - man + woman = ?" -----
# Gensim normalizes each input vector to unit length before adding/subtracting and
# automatically filters out the input words ("king", "woman", "man") from the results.
answer = model.most_similar(positive=["king", "woman"], negative=["man"], topn=1)
# -> [('queen', 0.8524)]
print("king - man + woman =", answer)
# --- next cell ---
# The same maths done "by hand" with numpy, to see the gotcha for yourself:
# Without excluding inputs, the resulting vector stays closest to "king" itself.
new_vector = model["king"] - model["man"] + model["woman"]
# -> ndarray shape (50,); raw nearest: [('king', 0.8860), ('queen', 0.8610), ('daughter', 0.7685)]
print("Raw vector search (input words NOT removed):", model.similar_by_vector(new_vector, topn=3))
# --- next cell ---
# Subtracting a regional language vector shifts the embedding away from that cultural/geographic dimension.
model.similar_by_vector(model["india"] - model["bengali"], topn=5)
# --- next cell ---
# ----- TODO 3 (solved): Capital cities: "paris - france + india = ?" -----
# Tests whether the capital-of-country offset learned from European geography transfers to South Asia.
answer_2 = model.most_similar(positive=["paris", "india"], negative=["france"], topn=1)
# -> [('delhi', 0.8187)]
print("paris - france + india =", answer_2)
# --- next cell ---
# ----- TODO 4 (solved): Write a cosine_similarity(a, b) function using numpy -----
# Dividing the dot product by the product of L2 norms isolates directional similarity
# (angle between vectors) from vector length, matching gensim's internal similarity metric.
def cosine_similarity(a, b):
return float(np.dot(a, b) / (np.linalg.norm(a) * np.linalg.norm(b)))
# -> 0.784 ('king','queen'), 0.756 ('cricket','football'), 0.221 ('king','banana')
pairs = [("king", "queen"), ("cricket", "football"), ("king", "banana")]
for w1, w2 in pairs:
mine = cosine_similarity(model[w1], model[w2])
library = model.similarity(w1, w2) # gensim's own answer, to check yours
print(f"{w1:>8} vs {w2:<9} -> my answer: {mine:.3f} | gensim: {library:.3f}")
Words in vocabulary: 400000
Shape of the 'king' vector: (50,)
First 5 numbers: [ 0.50451 0.68607 -0.59517 -0.022801 0.60046 ]
prince 0.824
queen 0.784
ii 0.775
emperor 0.754
son 0.746
king - man + woman = [('queen', 0.8523604273796082)]
Raw vector search (input words NOT removed): [('king', 0.88598347), ('queen', 0.86095822), ('daughter', 0.76845127)]
[('india', 0.8124), ('pakistan', 0.7318), ('indian', 0.7192), ('china', 0.6951), ('australia', 0.6814)]
paris - france + india = [('delhi', 0.8186619877815247)]
king vs queen -> my answer: 0.784 | gensim: 0.784
cricket vs football -> my answer: 0.756 | gensim: 0.756
king vs banana -> my answer: 0.221 | gensim: 0.221
Cosine Similarity: Measuring Meaning by Direction#
Revision Notes#
Reference files: 2_SHARE_AFTER_Solution_Code/1_word_embeddings.ipynb, 2_SHARE_AFTER_Solution_Code/2_similarity_search_app.py, 2_SHARE_AFTER_Solution_Explainer.html
Concept#
Once text is converted into vectors, we need a mathematical way to measure how close two meanings are. Almost every RAG and semantic search system uses cosine similarity, defined as cosine(a, b) = (a · b) / (|a| × |b|) — computed with np.dot and np.linalg.norm (or batch-computed via sklearn.metrics.pairwise.cosine_similarity).
Key Mental Models#
- Direction carries meaning; length does not:
- The dot product (
a · b) is large when two vectors rise and fall together. - Dividing by both vector magnitudes (
|a| × |b|) normalizes away length, leaving only the angle between the vectors. - Why not just subtract the numbers (Euclidean distance)? A short sentence and a long sentence about the exact same topic can have very different vector magnitudes while still pointing in the same direction.
- The dot product (
- Interpreting the score range (
-1to1):- Near
1: Very similar meaning (e.g.,kingvs.queen≈0.784,cricketvs.football≈0.696). - Near
0: Unrelated topics (e.g.,kingvs.banana≈0.221). - Negative: Pointing in opposite directions.
- Near
Code Reference#
import gradio as gr
import numpy as np
from sentence_transformers import SentenceTransformer
# A small, free bi-encoder embedding model that runs locally (no API key needed).
# Unlike static word vectors (GloVe), all-MiniLM-L6-v2 encodes whole sentences into
# contextual 384-dim vectors so paraphrases map close together.
model = SentenceTransformer("sentence-transformers/all-MiniLM-L6-v2")
SAMPLE_DOCS = """The cat sat on the mat.
A dog ran in the park.
The stock market crashed today.
Bananas are a great source of potassium.
Apples and oranges are healthy fruits.
Sensex fell 800 points after the RBI announcement.
Virat Kohli scored a century in the final."""
# ----- TODO 1 (solved): Write the cosine similarity formula -----
# Cosine similarity compares vector direction (meaning) independent of magnitude,
# returning values near 1.0 for semantically similar sentences.
def cosine_similarity(a, b):
return float(np.dot(a, b) / (np.linalg.norm(a) * np.linalg.norm(b)))
def retrieve_top_k(documents_text, query, k):
"""Return the top-k documents as rows: [document, score]."""
# 1. Split on newlines and drop blank lines so each non-empty line is indexed as one chunk
docs = [line.strip() for line in documents_text.strip().splitlines() if line.strip()]
if not docs or not query.strip():
return []
# ----- TODO 2 (solved): Embed all documents and the query -----
# Batch-encode all documents in one forward pass, then embed the query in the same vector space.
doc_embeddings = model.encode(docs)
# -> ndarray shape (7, 384) (one 384-dim vector per SAMPLE_DOCS line)
query_embedding = model.encode([query.strip()])[0]
# -> ndarray shape (384,) for "fruit and nutrition"
# ----- TODO 3 (solved): Score every document against the query and sort best-first -----
# Brute-force scan over all docs is fine for small lists; production RAG uses an ANN index (HNSW).
scores = [(doc, cosine_similarity(query_embedding, emb)) for doc, emb in zip(docs, doc_embeddings)]
scores.sort(key=lambda pair: pair[1], reverse=True)
# -> [
# ('Apples and oranges are healthy fruits.', 0.6512),
# ('Bananas are a great source of potassium.', 0.5148),
# ('The cat sat on the mat.', 0.0684), ...
# ]
# 4. Clamp k to len(docs) so requesting k > number of documents never errors
top = scores[: min(int(k), len(docs))]
return [[doc, f"{score:.4f}"] for doc, score in top]
# ----------------------------------------------------------------------------
# The web page (Gradio builds it for us from Python)
# ----------------------------------------------------------------------------
with gr.Blocks(title="Similarity Search") as demo:
gr.Markdown("# Similarity Search (Top-K)\nCreated by Shivank Agarwal")
gr.Markdown("Enter documents (one per line), type a query, and get the K most similar documents.")
with gr.Row():
documents_input = gr.Textbox(label="Documents (one per line)", lines=12, value=SAMPLE_DOCS, scale=2)
with gr.Column(scale=1):
query_input = gr.Textbox(label="Query", value="fruit and nutrition", lines=2)
k_input = gr.Slider(label="K — number of results", value=3, minimum=1, maximum=20, step=1)
retrieve_btn = gr.Button("Retrieve Top K", variant="primary")
results_table = gr.Dataframe(headers=["Document", "Similarity Score"], label="Top-K Results", interactive=False, wrap=True)
# ... (see full file: 2_similarity_search_app.py)
$ python 2_SHARE_AFTER_Solution_Code/2_similarity_search_app.py
* Running on local URL: http://127.0.0.1:7860
--- Gradio UI Result (Query: "fruit and nutrition", K = 3) ---
Rank | Document | Similarity Score
-----+------------------------------------------+-----------------
1 | Apples and oranges are healthy fruits. | 0.6512
2 | Bananas are a great source of potassium. | 0.5148
3 | The cat sat on the mat. | 0.0684
Sentence Embeddings & Top-K Similarity Search#
Revision Notes#
Reference files: 1_GIVE_FIRST_Starter_Code/2_similarity_search_app.py, 2_SHARE_AFTER_Solution_Code/2_similarity_search_app.py, 2_SHARE_AFTER_Solution_Explainer.html
Concept#
Real search and RAG systems rarely search single words — they search sentences, paragraphs, or document chunks. Exercise 1.2 upgrades from 50-number GloVe word vectors to a local sentence-embedding model (sentence-transformers/all-MiniLM-L6-v2), which converts any sentence into a 384-dimensional vector, and wraps Top-K semantic retrieval inside a Gradio web app.
How It Works#
Documents and the user query are independently projected into a shared 384-dimensional meaning space, scored by directional cosine similarity rather than vector magnitude, and sorted to return the Top-K matches.
Key Mental Models#
- Semantic search beats keyword search: For the query
"fruit and nutrition", "Bananas are a great source of potassium." ranks at the top even though it shares zero words with the query. Similarly,"share prices falling"retrieves both the stock market and Sensex/RBI sentences. - This is the "R" in RAG: Everything a basic RAG retriever does at its core is embed documents, embed the user's question, score every document against the question with cosine similarity, sort descending, and return the top
K. - Interactive verification with Gradio:
gr.Blocks()wires Python functions directly to UI inputs (document box, query box,Kslider) and output tables (gr.Dataframe), letting you test how queries andKaffect retrieval order without writing HTML or JavaScript.
Trade-Offs & Pitfalls#
- Exact scores vary slightly across environments: Hardware and library versions can shift decimal places slightly — always judge retrieval quality by ranking order, not exact floating-point scores.
- Superficial topical overlap can fool embedding search: Because the query and each document are compressed into separate vectors independently, short documents that merely echo the query's words can outscore longer, actually informative answers. This motivates Stage 2 (reranking).
Code Reference#
import gradio as gr
import numpy as np
from sentence_transformers import SentenceTransformer
# A small, free bi-encoder embedding model that runs locally (no API key needed).
# It maps any sentence into a 384-dimensional vector where semantically close texts cluster together.
model = SentenceTransformer("sentence-transformers/all-MiniLM-L6-v2")
SAMPLE_DOCS = """The cat sat on the mat.
A dog ran in the park.
The stock market crashed today.
Bananas are a great source of potassium.
Apples and oranges are healthy fruits.
Sensex fell 800 points after the RBI announcement.
Virat Kohli scored a century in the final."""
# ----- TODO 1: Write the cosine similarity formula -----
# Cosine similarity isolates the angle between vectors so sentence length does not skew ranking.
# Hint: cosine(a, b) = (a · b) / (|a| × |b|)
# Hint: np.dot(a, b) and np.linalg.norm(a) are all you need
def cosine_similarity(a, b):
return 0.0 # replace with the formula
def retrieve_top_k(documents_text, query, k):
"""Return the top-k documents as rows: [document, score]."""
# 1. Treat each non-empty line as an independent document chunk
docs = [line.strip() for line in documents_text.strip().splitlines() if line.strip()]
if not docs or not query.strip():
return []
# ----- TODO 2: Embed all documents and the query -----
# Both documents and query must be encoded by the exact same model to share a vector space.
# Hint: model.encode(list_of_texts) returns one vector per text
# Hint: Encode the query as a list with one item, then take [0]
doc_embeddings = [] # replace with your code
query_embedding = None # replace with your code
# ----- TODO 3: Score every document against the query and sort best-first -----
# Hint: Build a list of (doc, score) pairs with zip(docs, doc_embeddings)
# Hint: list.sort(key=lambda pair: pair[1], reverse=True) puts the highest score first
scores = [] # replace with your code
# 4. Keep only the first k results and format the score nicely for the table
top = scores[: min(int(k), len(docs))]
return [[doc, f"{score:.4f}"] for doc, score in top]
# ----------------------------------------------------------------------------
# The web page (Gradio builds it for us from Python)
# ----------------------------------------------------------------------------
with gr.Blocks(title="Similarity Search") as demo:
gr.Markdown("# Similarity Search (Top-K)\nCreated by Shivank Agarwal")
gr.Markdown("Enter documents (one per line), type a query, and get the K most similar documents.")
with gr.Row():
documents_input = gr.Textbox(label="Documents (one per line)", lines=12, value=SAMPLE_DOCS, scale=2)
with gr.Column(scale=1):
# ... (see full file: 2_similarity_search_app.py)
$ python 1_GIVE_FIRST_Starter_Code/2_similarity_search_app.py
* Running on local URL: http://127.0.0.1:7860
--- Gradio UI Result (before completing TODOs 1-3) ---
Top-K Results table is empty: []
--- Expected Result after completing TODOs 1-3 (Query: "fruit and nutrition", K = 3) ---
1. Apples and oranges are healthy fruits. | 0.6512
2. Bananas are a great source of potassium. | 0.5148
3. The cat sat on the mat. | 0.0684
Two-Stage Retrieval: Bi-Encoder vs. Cross-Encoder Reranking#
Revision Notes#
Reference files: 1_GIVE_FIRST_Starter_Code/3_reranking_app.py, 2_SHARE_AFTER_Solution_Code/3_reranking_app.py, 2_SHARE_AFTER_Solution_Explainer.html
Concept#
Production RAG and search systems rarely rely on a single model. Instead, they use a two-stage pipeline ("Retrieve, then Rerank") that combines a fast, coarse bi-encoder (sentence-transformers/all-MiniLM-L6-v2) with a slow, high-precision cross-encoder (cross-encoder/ms-marco-MiniLM-L6-v2, trained on MS MARCO web search query–passage pairs).
How It Works#
Stage 1 scans millions of pre-computed vectors in milliseconds for broad recall, while Stage 2 runs full cross-attention on (query, candidate) pairs across only the Top-K finalists to promote genuinely informative answers.
Key Mental Models#
- The hiring analogy:
- Stage 1 (Bi-encoder) is the resume filter — scans 5,000 resumes in seconds and keeps the top 20.
- Stage 2 (Cross-encoder) is the interview — slow and thorough, only worth running on those 20 finalists.
- Bi-encoder vs. Cross-encoder architecture:
- Bi-encoder: Encodes the query and each document separately into fixed vectors, then compares them with cosine similarity. Document vectors can be pre-computed once and indexed in a vector database, making search over millions of documents take milliseconds — but the model never sees the query and document words interact.
- Cross-encoder: Feeds
(query, document)together as one joint input and directly outputs a relevance score (cross_encoder.predict(pairs)). Every word of the query attends to every word of the document, producing far sharper relevance judgments — but nothing can be pre-computed, requiring a full model forward pass per candidate at query time.
- Why reranking fixes the COVID-19 example:
- Before reranking (bi-encoder): Empty echoes like "COVID-19 has many symptoms." and "COVID-19 symptoms are bad." score near the top because their vectors closely match the phrase
"COVID-19 Symptoms". - After reranking (cross-encoder): Passages that actually list symptoms (fever, chills, cough, sore throat, loss of smell/taste) jump to the top, while unrelated passages (like Dementia) stay near the bottom.
- Before reranking (bi-encoder): Empty echoes like "COVID-19 has many symptoms." and "COVID-19 symptoms are bad." score near the top because their vectors closely match the phrase
Trade-Offs & Pitfalls#
- Cross-encoder scores are unnormalized logits, not probabilities: Unlike cosine similarity,
ms-marco-MiniLM-L6-v2outputs raw relevance scores that are not bounded between 0 and 1 and can even be negative. Only the relative ordering matters (higher = more relevant). - Never run a cross-encoder over the full corpus: Running a full transformer pass over 1,000,000
(query, doc)pairs for every user question is prohibitively slow. Always narrow the pool with a bi-encoder first.
Code Reference#
import gradio as gr
import pandas as pd
from sentence_transformers import CrossEncoder, SentenceTransformer
from sklearn.metrics.pairwise import cosine_similarity
# Stage 1 — Bi-encoder: encodes query and each document independently into vectors.
# Fast enough to search thousands of docs (embeddings can be precomputed), but misses fine token-level interaction.
bi_encoder = SentenceTransformer("sentence-transformers/all-MiniLM-L6-v2")
# Stage 2 — Cross-encoder: feeds (query, document) together through full transformer self-attention.
# Much slower (cannot precompute), so it is used only to rerank the small Top-K candidate set.
# Trained on MS MARCO, it distinguishes informative answers from vague keyword-matching sentences.
cross_encoder = CrossEncoder("cross-encoder/ms-marco-MiniLM-L6-v2")
SAMPLE_DOCS = """COVID-19 has many symptoms.
COVID-19 symptoms are bad.
COVID-19 symptoms are not nice
COVID-19 symptoms are really bad.
COVID-19 is a disease caused by a virus. The most common symptoms are fever, chills, and sore throat, but there are a range of others.
COVID-19 symptoms can include: a high temperature or shivering (chills); a new, continuous cough; a loss or change to your sense of smell or taste; and many more
Dementia has the following symptom: Experiencing memory loss, poor judgment, and confusion.
COVID-19 has the following symptom: Experiencing memory loss, poor judgment, and confusion."""
# ----------------------------------------------------------------------------
# Core search logic (no UI code here)
# ----------------------------------------------------------------------------
def get_top_k(query: str, documents: list[str], k: int) -> list[tuple[str, float]]:
"""Step 1: bi-encoder retrieval. Returns [(document, cosine_score), ...] best first."""
# ----- TODO 1: Embed the documents and the query, score them with cosine similarity, sort, keep top k -----
# Hint: bi_encoder.encode(documents) -> matrix (one row per document)
# Hint: bi_encoder.encode([query]) -> matrix with ONE row
# Hint: cosine_similarity(query_matrix, doc_matrix)[0] -> one score per document
return [] # replace with your code
def rerank(query: str, documents: list[str]) -> list[tuple[str, float]]:
"""Step 2: cross-encoder reranking. Returns [(document, relevance_score), ...] best first."""
# ----- TODO 2: Score every (query, document) pair with the cross-encoder and sort best first -----
# Note: cross-encoder outputs unbounded relevance logits (can be negative or > 1), not cosine scores.
# Hint: Build pairs like [(query, doc1), (query, doc2), ...]
# Hint: cross_encoder.predict(pairs) -> one score per pair (higher = more relevant)
return [] # replace with your code
# ----------------------------------------------------------------------------
# Button handlers (connect the UI to the logic above)
# ----------------------------------------------------------------------------
def to_table(results):
return pd.DataFrame([(doc, round(float(score), 4)) for doc, score in results], columns=["Document", "Score"])
def on_retrieve(documents_text, query, k):
docs = [line.strip() for line in documents_text.splitlines() if line.strip()]
if not docs or not query.strip():
raise gr.Error("Please enter some documents and a query.")
return to_table(get_top_k(query.strip(), docs, int(k)))
def on_rerank(query, top_k_table):
# We rerank exactly the documents shown in the Top-K table
# ... (see full file: 3_reranking_app.py)
$ python 1_GIVE_FIRST_Starter_Code/3_reranking_app.py
* Running on local URL: http://127.0.0.1:7860
--- Gradio UI Result (before completing TODOs 1-2) ---
Retrieve Top-K table: empty DataFrame (0 rows)
Rerank table: empty DataFrame (0 rows)
--- Expected Behavior after completing TODOs 1-2 (Query: "What are the symptoms of COVID-19?") ---
Stage 1 (Bi-encoder): ranks short keyword-heavy lines like "COVID-19 has many symptoms." near the top.
Stage 2 (Cross-encoder): promotes detailed answers listing fever, chills, cough, and loss of smell to #1 and #2.
import gradio as gr
import pandas as pd
from sentence_transformers import CrossEncoder, SentenceTransformer
from sklearn.metrics.pairwise import cosine_similarity
# Stage 1 — Bi-encoder: encodes each text independently into a 384-dim vector.
# Enables fast vector search over large corpora, but compresses each sentence into one vector before comparison.
bi_encoder = SentenceTransformer("sentence-transformers/all-MiniLM-L6-v2")
# Stage 2 — Cross-encoder: jointly attends across (query, document) tokens to score true answer relevance.
# Trained on MS MARCO, it penalizes hollow keyword matches ("COVID-19 symptoms are bad.") and rewards actual answers.
cross_encoder = CrossEncoder("cross-encoder/ms-marco-MiniLM-L6-v2")
SAMPLE_DOCS = """COVID-19 has many symptoms.
COVID-19 symptoms are bad.
COVID-19 symptoms are not nice
COVID-19 symptoms are really bad.
COVID-19 is a disease caused by a virus. The most common symptoms are fever, chills, and sore throat, but there are a range of others.
COVID-19 symptoms can include: a high temperature or shivering (chills); a new, continuous cough; a loss or change to your sense of smell or taste; and many more
Dementia has the following symptom: Experiencing memory loss, poor judgment, and confusion.
COVID-19 has the following symptom: Experiencing memory loss, poor judgment, and confusion."""
# ----------------------------------------------------------------------------
# Core search logic (no UI code here)
# ----------------------------------------------------------------------------
def get_top_k(query: str, documents: list[str], k: int) -> list[tuple[str, float]]:
"""Step 1: bi-encoder retrieval. Returns [(document, cosine_score), ...] best first."""
# ----- TODO 1 (solved): Embed the documents and the query, score them with cosine similarity, sort, keep top k -----
# cosine_similarity(1x384, Nx384) returns a 1xN matrix; [0] flattens it to N scalar scores.
doc_embeddings = bi_encoder.encode(documents)
# -> ndarray shape (8, 384) (8 SAMPLE_DOCS lines)
query_embedding = bi_encoder.encode([query])
# -> ndarray shape (1, 384) (2D matrix required by sklearn cosine_similarity)
scores = cosine_similarity(query_embedding, doc_embeddings)[0]
# -> ndarray shape (8,): [0.7814, 0.7429, ..., 0.7105, 0.7318, ...]
pairs = list(zip(documents, scores))
pairs.sort(key=lambda pair: pair[1], reverse=True)
return pairs[:k]
# -> Top-5 starts with hollow echoes ('COVID-19 has many symptoms.', 0.7814)
def rerank(query: str, documents: list[str]) -> list[tuple[str, float]]:
"""Step 2: cross-encoder reranking. Returns [(document, relevance_score), ...] best first."""
# ----- TODO 2 (solved): Score every (query, document) pair with the cross-encoder and sort best first -----
# CrossEncoder.predict returns raw relevance logits (unbounded floats); higher means a better answer.
pairs = [(query, doc) for doc in documents]
# -> 5 (query, candidate_doc) tuples from Stage 1 Top-5
scores = cross_encoder.predict(pairs)
# -> ndarray shape (5,) of logits: [2.1340, 0.4821, 8.6412, 7.9185, 0.1954]
ranked = list(zip(documents, scores))
ranked.sort(key=lambda pair: pair[1], reverse=True)
# -> [
# ('COVID-19 symptoms can include: a high temperature...', 8.6412),
# ('COVID-19 is a disease caused by a virus. The most common...', 7.9185),
# ('COVID-19 has many symptoms.', 2.1340), ...
# ]
return ranked
# ----------------------------------------------------------------------------
# Button handlers (connect the UI to the logic above)
# ----------------------------------------------------------------------------
def to_table(results):
return pd.DataFrame([(doc, round(float(score), 4)) for doc, score in results], columns=["Document", "Score"])
def on_retrieve(documents_text, query, k):
docs = [line.strip() for line in documents_text.splitlines() if line.strip()]
if not docs or not query.strip():
# ... (see full file: 3_reranking_app.py)
$ python 2_SHARE_AFTER_Solution_Code/3_reranking_app.py
* Running on local URL: http://127.0.0.1:7860
--- Stage 1: Bi-Encoder Top-5 (Query: "What are the symptoms of COVID-19?") ---
1. COVID-19 has many symptoms. | 0.7814
2. COVID-19 symptoms are bad. | 0.7429
3. COVID-19 symptoms can include: a high temperature or shivering (chills)... | 0.7318
4. COVID-19 is a disease caused by a virus. The most common symptoms are fever... | 0.7105
5. COVID-19 symptoms are really bad. | 0.7042
--- Stage 2: Cross-Encoder Reranked (same 5 candidates, relevance logits) ---
1. COVID-19 symptoms can include: a high temperature or shivering (chills)... | 8.6412
2. COVID-19 is a disease caused by a virus. The most common symptoms are fever... | 7.9185
3. COVID-19 has many symptoms. | 2.1340
4. COVID-19 symptoms are bad. | 0.4821
5. COVID-19 symptoms are really bad. | 0.1954
Relevance vs. Truth & Retrieval Bottlenecks#
Revision Notes#
Reference files: 1_GIVE_FIRST_Exercise_Questions.html, 2_SHARE_AFTER_Solution_Explainer.html, 2_SHARE_AFTER_Solution_Code/3_reranking_app.py
Concept#
Even with a strong two-stage retrieve-and-rerank pipeline, two fundamental system-design limits govern RAG accuracy: a reranker cannot verify facts, and a reranker cannot rescue documents that Stage 1 missed.
Key Mental Models#
- Rerankers judge relevance, not truth:
- In Exercise 1.3, one sample document falsely claims: "COVID-19 has the following symptom: Experiencing memory loss, poor judgment, and confusion."
- The cross-encoder does not push this sentence to the bottom — because it matches the right topic and has the exact shape of a direct answer to
"COVID-19 Symptoms". - Takeaway for RAG: Reranking optimizes relevance to the query, never factual accuracy. Data quality and trusted knowledge-base curation are non-negotiable because an LLM fed a high-scoring false chunk will confidently repeat it.
- Stage 1 (
K) is the recall ceiling for Stage 2:- In
3_reranking_app.py, clicking Rerank only re-orders the exact rows returned in the Top-K table. - If you set
K = 2and the true best document ranked #5 in bi-encoder retrieval, the cross-encoder never sees it and can never surface it. - Production rule of thumb: Retrieve generously in Stage 1 (e.g.,
K = 20–50for high recall), then rerank down to the best3–5chunks for high precision before passing context to the LLM.
- In
How All Building Blocks Connect#
Revision Notes#
Each exercise in 12-rag-embeddings-similarity-reranking builds one layer of the modern RAG retrieval stack:
- Exercise 1.1 (
1_word_embeddings.ipynb): Establishes the core intuition — text becomes dense vectors (glove-wiki-gigaword-50), meaning is geometry (analogies via vector arithmetic), and closeness is measured by direction (cosine_similarity). - Exercise 1.2 (
2_similarity_search_app.py): Scales from single words to whole sentences (all-MiniLM-L6-v2, 384 dimensions) and implements Top-K semantic retrieval — finding relevant documents even with zero shared keywords. - Exercise 1.3 (
3_reranking_app.py): Solves bi-encoder blindness to superficial word repetition by adding a Stage 2 cross-encoder (ms-marco-MiniLM-L6-v2) that reads(query, document)pairs jointly, while demonstrating both theKrecall bottleneck and the difference between relevance and factual truth.
Module 12 builds sequentially from static 50-d word vector geometry to contextual 384-d sentence recall and two-stage cross-encoder precision, bounded by Stage 1 recall (K) and source-document truth.
Quick Self-Check Questions#
Self-Check Questions#
Why does raw vector search on model["king"] - model["man"] + model["woman"] return king as the #1 match?
Subtracting man and adding woman shifts the vector only slightly, so it remains closest to the starting point (king). most_similar(positive=..., negative=...) fixes this by excluding the input words from candidate results.
Why do RAG systems use cosine similarity instead of subtracting vector coordinates (Euclidean distance)?
Cosine similarity normalizes by vector length and measures only the angle (direction) between vectors. A short phrase and a long paragraph about the same topic point in the same direction even if their lengths differ.
How can semantic search retrieve "Bananas are a great source of potassium." for the query "fruit and nutrition" with zero overlapping words?
A sentence-embedding model (all-MiniLM-L6-v2) maps both texts into nearby regions of 384-dimensional meaning space, giving them a high cosine similarity despite having no shared keywords.
Why not skip the bi-encoder and run a cross-encoder on all 1,000,000 documents directly?
A cross-encoder must run a full model forward pass on every (query, document) pair at query time because nothing can be pre-computed. A bi-encoder pre-computes document vectors once so Stage 1 search takes milliseconds, leaving only K candidates for the cross-encoder.
What does it mean if a cross-encoder outputs a negative score like -2.4?
Cross-encoder outputs (such as from ms-marco-MiniLM-L6-v2) are raw relevance scores, not probabilities bounded between 0 and 1. Negative scores are normal; only the relative ranking order (higher = more relevant) matters.
In Exercise 1.3, why didn't the cross-encoder sink the false sentence "COVID-19 has the following symptom: Experiencing memory loss..." to the bottom?
Because a reranker judges relevance (topic + answer shape), not factual truth. Preventing misinformation in RAG requires curating trusted source documents in the knowledge base.
If you set K = 2 in Stage 1, can Stage 2 reranking still find the best document in your corpus?
Only if Stage 1 already placed that document inside the top 2. A reranker can only re-order the candidates it receives, which is why real systems retrieve a wider pool (e.g., K = 20–50) and rerank down to the top 3–5.