The big idea in one picture
Computers compare numbers, not meanings. So we first turn text into numbers that capture meaning, and then compare the numbers.
Everyday analogy: think of each sentence as a pin on a giant map of meanings. "Train ticket refund" and "cancel my IRCTC booking" land close together. "Recipe for paneer tikka" lands far away. Search becomes: find the pins nearest to the question's pin.
1.1 Word embeddings
We used GloVe vectors: 400,000 English words, each stored as 50 numbers. They were learned from Wikipedia and news text, so words used in similar sentences end up with similar numbers.
TODO 1 — Get the vector for the word "king" and print its shape and first 5 numbers
v_king = model["king"]
The model behaves like a Python dictionary: word in, vector out.
Shape of the 'king' vector: (50,) First 5 numbers: [ 0.50451 0.68607 -0.59517 -0.022801 0.60046 ]
No single number means "royal" or "male". The pattern of all 50 numbers carries the meaning. That is why the nearest neighbours of king make sense:
prince 0.824 queen 0.784 ii 0.775 emperor 0.774 son 0.767
TODO 2 — Use word maths to answer "king - man + woman = ?"
answer = model.most_similar(positive=["king", "woman"], negative=["man"], topn=1)
king - man + woman = [('queen', 0.8523604273796082)]positive words are added, negative words are subtracted. Read it as: start at king, remove the 'man' direction, add the 'woman' direction.
If you build the vector yourself and search with it, the closest word is king, because the result is still very close to where we started. most_similar(positive=..., negative=...) automatically skips the input words.
Raw vector search (input words NOT removed): [('king', 0.886), ('queen', 0.861), ('daughter', 0.768)]TODO 3 — Capital cities: "paris - france + india = ?"
answer_2 = model.most_similar(positive=["paris", "india"], negative=["france"], topn=1)
paris - france + india = [('delhi', 0.8888585567474365)]The model has learned a "capital of" direction, just from reading text.
TODO 4 — Write a cosine_similarity(a, b) function using numpy
def cosine_similarity(a, b): return float(np.dot(a, b) / (np.linalg.norm(a) * np.linalg.norm(b)))
king vs queen -> my answer: 0.784 | gensim: 0.784 cricket vs football -> my answer: 0.696 | gensim: 0.696 king vs banana -> my answer: 0.221 | gensim: 0.221
Reading the formula: np.dot(a, b) is large when the two lists of numbers go up and down together.
Dividing by the two lengths (np.linalg.norm) removes the effect of size, so we only measure direction.
The result is between −1 and 1: near 1 = same meaning, near 0 = unrelated.
1.2 Similarity search app
Now we embed whole sentences instead of single words. The model sentence-transformers/all-MiniLM-L6-v2 is small
(about 90 MB), free, runs on a laptop CPU, and turns any sentence into 384 numbers.
TODO 1 — Write the cosine similarity formula
def cosine_similarity(a, b): return float(np.dot(a, b) / (np.linalg.norm(a) * np.linalg.norm(b)))
The same formula you wrote in 1.1. We wrap the answer in float() so Gradio shows a normal number.
TODO 2 — Embed all documents and the query
doc_embeddings = model.encode(docs) query_embedding = model.encode([query.strip()])[0]
model.encode takes a list of texts and returns one row of 384 numbers per text. We pass the query as a list of one item and take row [0].
TODO 3 — Score every document against the query and sort best-first
scores = [(doc, cosine_similarity(query_embedding, emb)) for doc, emb in zip(docs, doc_embeddings)] scores.sort(key=lambda pair: pair[1], reverse=True)
zip pairs each document with its vector. The lambda pair: pair[1] tells sort to sort by the score, and reverse=True puts the biggest score first.
What you should see
| Rank | Document | Score (pattern) |
|---|---|---|
| 1–2 | Apples and oranges are healthy fruits. / Bananas are a great source of potassium. | clearly the highest |
| 3 | any other sentence | much lower, close to 0 |
Exact numbers change slightly between laptops and library versions. The order is what matters. Notice that Bananas are a great source of potassium scores high even though it shares no words with "fruit and nutrition". Keyword search could never do that.
gr.Blocks() builds the page from Python. retrieve_btn.click(fn=retrieve_top_k, inputs=[...], outputs=results_table) means: when the button is clicked, call retrieve_top_k with the values of the input boxes and show what it returns in the table. No HTML or JavaScript needed.
1.3 Retrieve, then rerank
Bi-encoder (Step 1)
Embeds the query and each document separately, then compares vectors. Document vectors can be computed once and stored in a vector database, so searching millions is fast. But the model never sees the query and the document together.
Cross-encoder (Step 2)
Reads (query, document) as one input and outputs a relevance score. Much more accurate, because every word of the query can be matched against every word of the document. But nothing can be pre-computed, so it is slow. Use it only on the top K.
Analogy: hiring for a job. Step 1 is the resume filter that scans 5,000 resumes in seconds and keeps 20. Step 2 is the interview: slow and careful, but you only do it for those 20.
TODO 1 — Embed the documents and the query, score them with cosine similarity, sort, keep top k
doc_embeddings = bi_encoder.encode(documents) query_embedding = bi_encoder.encode([query]) scores = cosine_similarity(query_embedding, doc_embeddings)[0] pairs = list(zip(documents, scores)) pairs.sort(key=lambda pair: pair[1], reverse=True) return pairs[:k]
scikit-learn's cosine_similarity(A, B) compares every row of A with every row of B. With one query row we get one list of scores, hence [0].
TODO 2 — Score every (query, document) pair with the cross-encoder and sort best first
pairs = [(query, doc) for doc in documents] scores = cross_encoder.predict(pairs) ranked = list(zip(documents, scores)) ranked.sort(key=lambda pair: pair[1], reverse=True) return ranked
The cross-encoder model cross-encoder/ms-marco-MiniLM-L6-v2 was trained on MS MARCO, a large set of real web search questions with the passages that answered them. Its scores are not between 0 and 1. They can be negative. Only the order matters: bigger = more relevant.
What you should see
- Before reranking: short sentences that simply repeat the query words (COVID-19 has many symptoms., COVID-19 symptoms are bad.) score near the top, even though they tell you nothing.
- After reranking: the sentences that actually list symptoms (fever, chills, cough, loss of smell) move to the top. The Dementia sentence stays near the bottom.
Scores differ slightly by machine. Look at how the order changes.
The Rerank button reranks exactly the rows shown in the Top-K table (the table is an input to on_rerank). So if you change K and retrieve again, the reranker works on the new list. If you click Rerank first, the app shows a friendly error.
Answers to "Think about it"
king − man + woman moves the vector only a little, so it is still very close to king. A plain nearest-neighbour search does not know which words you started from. most_similar(positive, negative) removes the input words from the answers.
Cosine measures the direction of the vectors and ignores their length. A long sentence and a short sentence about the same thing point the same way but can have very different lengths. Direction is what carries meaning.
It has to run the full model once per (query, document) pair, every time a user asks something. One million documents would mean one million model runs per question. The bi-encoder's document vectors are computed once and reused, so retrieval takes milliseconds.
Look at where it landed: it usually does not sink to the bottom, because it looks like an answer to "COVID-19 symptoms" (right topic, right shape). A reranker judges relevance, not truth. Checking facts needs trusted sources, which is why RAG systems care so much about what goes into the knowledge base.
Only if the best document is already in the top 2 of Step 1. The reranker can only re-order what retrieval gives it. In practice we retrieve more (for example 20–50) and rerank down to the best 3–5.
Common errors and fixes
| You see | Why | Fix |
|---|---|---|
ModuleNotFoundError: No module named 'gensim' (or gradio, sentence_transformers) | Libraries not installed in the Python you are using | Activate your virtual environment, then pip install -r 00_Setup/requirements.txt. In Jupyter or VS Code, pick the same environment as the kernel. |
KeyError: "Key 'xyz' not present" | The word is not in GloVe's vocabulary (GloVe is lower-case) | Use lower-case common words |
OSError: [Errno 98] Address already in use / port 7860 | Another Gradio app is still running | Stop it with Ctrl+C in its terminal, or run demo.launch(server_port=7861) |
| The first run is very slow | Models are downloading | Wait once. Later runs load from disk. |
AttributeError: 'NoneType' object has no attribute ... | A TODO still has its placeholder (None / []) | Find the TODO and replace the placeholder line |