Hands-on exercises · Give to learners

Module 1 — Embeddings, Similarity Search and Reranking: Exercises

Hands-on exercise sheet. Try every TODO yourself before you see the solution.

For learnersAbout 50 minutesNo API key needed

What you will build

Time: about 50 minutes  ·  API key needed: No (everything in this module runs on your laptop)

How to do these exercises

  1. Finish the setup first: 11-rag-setup/Setup_Guide_for_Learners.html.
  2. Open the folder 1_GIVE_FIRST_Starter_Code. Every file has blanks marked # ----- TODO n: ... -----.
  3. Replace the placeholder line under each TODO (for example scores = [] # replace with your code) with your own code.
  4. Stuck for more than 5 minutes? Open the hint under the TODO on this page. Still stuck? Ask your instructor.
  5. Check your work with the "You are done when" box at the end of each exercise.
First run downloads models

Exercise 1.1 downloads a 66 MB word model. Exercises 1.2 and 1.3 download two small models (about 90 MB each). After the first time they load from your laptop.

Exercise 1.1 — Word embeddings notebook

File: 1_GIVE_FIRST_Starter_Code/1_word_embeddings.ipynb

Story: A computer cannot read the word king. It only works with numbers. An embedding is a list of numbers that stands for a word, and words with similar meanings get similar lists. Your job is to look at these numbers and use them.

Run the cells from top to bottom. Fill in these blanks:

TODO 1Get the vector for the word "king" and print its shape and first 5 numbers

Expected: the shape is (50,), which means 50 numbers.

Need a hint?
  • The model works like a dictionary: model["some_word"]
  • A numpy array has a .shape attribute
TODO 2Use word maths to answer "king - man + woman = ?"

Do the analogy king − man + woman. Which word comes back?

Need a hint?
  • model.most_similar(positive=[words to add], negative=[words to subtract], topn=1)
TODO 3Capital cities: "paris - france + india = ?"

Paris is to France as ? is to India.

Need a hint?
  • Same pattern as TODO 2. Words to add: paris, india. Word to subtract: france
TODO 4Write a cosine_similarity(a, b) function using numpy

Formula: cosine(a, b) = (a · b) / (|a| × |b|). Your numbers must match gensim's numbers.

Need a hint?
  • np.dot(a, b) gives a · b
  • np.linalg.norm(a) gives |a|
You are done when
  • TODO 2 prints queen and TODO 3 prints an Indian city
  • In TODO 4, "my answer" and "gensim" show the same three numbers
  • king vs queen scores clearly higher than king vs banana

Exercise 1.2 — Similarity search app (Top-K) web app

File: 1_GIVE_FIRST_Starter_Code/2_similarity_search_app.py

Story: You have a pile of sentences (documents). A user types a question. Show the K sentences whose meaning is closest to the question, even if they share no words with it. This is the R (Retrieval) in RAG.

Documentsone per line
→
Embedding modeleach line → 384 numbers
→
Cosine similarityquestion vs every line
→
Sort + keep Kbest first
TODO 1Write the cosine similarity formula
Need a hint?
  • cosine(a, b) = (a · b) / (|a| × |b|)
  • np.dot(a, b) and np.linalg.norm(a) are all you need
TODO 2Embed all documents and the query
Need a hint?
  • model.encode(list_of_texts) returns one vector per text
  • Encode the query as a list with one item, then take [0]
TODO 3Score every document against the query and sort best-first
Need a hint?
  • Build a list of (doc, score) pairs with zip(docs, doc_embeddings)
  • list.sort(key=lambda pair: pair[1], reverse=True) puts the highest score first

Run it:

Terminal (inside the starter folder)
python 2_similarity_search_app.py

Open the link shown in the terminal (usually http://127.0.0.1:7860). The sample documents and query are already filled in. Click Retrieve Top K.

You are done when
  • For the query fruit and nutrition, the two fruit sentences (bananas, apples and oranges) are the top 2 rows
  • Changing the query to share prices falling puts the stock market and Sensex sentences on top
  • Moving the K slider changes how many rows you get

Exercise 1.3 — Retrieve, then Rerank web app

File: 1_GIVE_FIRST_Starter_Code/3_reranking_app.py

Story: Fast search (Exercise 1.2) is good at finding roughly related text, but it can be fooled by sentences that just repeat the question's words. A reranker (a cross-encoder) reads the question and each document together and gives a sharper relevance score. Real systems do both: retrieve many quickly, then rerank the few that came back.

Step 1: Retrievebi-encoder, fast, top K
→
Step 2: Rerankcross-encoder, slow, precise
→
Final orderbest answer first
TODO 1Embed the documents and the query, score them with cosine similarity, sort, keep top k

This is the same idea as Exercise 1.2, written with scikit-learn's cosine_similarity, which scores all documents in one call.

Need a hint?
  • bi_encoder.encode(documents) -> matrix (one row per document)
  • bi_encoder.encode([query]) -> matrix with ONE row
  • cosine_similarity(query_matrix, doc_matrix)[0] -> one score per document
TODO 2Score every (query, document) pair with the cross-encoder and sort best first
Need a hint?
  • Build pairs like [(query, doc1), (query, doc2), ...]
  • cross_encoder.predict(pairs) -> one score per pair (higher = more relevant)

Run it: python 3_reranking_app.py, open the link, click 1) Retrieve Top K, then 2) Rerank.

You are done when
  • Both tables show all 8 documents with a score
  • The order in the "Reranked" table is different from the "Top-K" table
  • Write down: which sentence is #1 before reranking, and which is #1 after?

Think about it (answer in 1–2 lines each)

  1. In Exercise 1.1, when we search with the raw vector for king − man + woman, the top word is king itself. Why?
  2. Why do we compare embeddings with cosine similarity (the angle) and not just by subtracting the numbers?
  3. A cross-encoder gives better scores. So why don't we run it on all one million documents in a real system?
  4. Exercise 1.3 has a document saying COVID-19 causes memory loss and confusion. That is not a common COVID symptom. Did the reranker push it down? What does that tell you about what a reranker checks?
  5. If you set K = 2 in Exercise 1.3, can the reranker still find the best document? Why or why not?

Your instructor will discuss the answers after the exercise.

Stretch challenges (if you finish early)