Generative AIby Dhruv Narang

Why Do We Need ANN?

Searching a few thousand vectors is easy. Searching millions is the problem. Here is the story.

The issue
A company stores 1 million chunks. A user asks a question, and we must find the few best chunks, fast.
The first try
Score the question against every vector, then sort. This is called brute force. It is exact: it always finds the true best chunks.
Why it fails
One question costs 1 million scores. Each score multiplies 1,536 pairs of numbers, so one question needs about 1.5 billion multiplications. Ten times more chunks means ten times more work, written O(N). And it is paid on every question.
The fix
Do not score everything. Look only in the places where the best chunks are likely to be. Once in a while we may miss the true best one, but the search becomes many times faster. This is ANN.
How the work grows with the number of vectors, for one question.
Vectors stored (N)Multiplications for ONE question (N × 1,536)Feeling
10,00015,360,000a moment
1,000,0001,536,000,000slow
100,000,000153,600,000,000far too slow
Big O: the work grows in a straight line with N. This is called flat or brute-force search, and written O(N × d). It is exact, but it is paid on every question.
d = 1,536 is the size of an OpenAI small embedding.

What Is ANN?

ANN stands for Approximate Nearest Neighbor. Let us break the name into its words.

Nearest neighbor
The stored vector that is closest to the question. We want the k nearest ones.
Approximate
We accept “very close” instead of “guaranteed the closest”. Rarely, the true best chunk is missed.
What we get
A big gain in speed, for a tiny loss in accuracy.
Exact search
Compare with every vector. Always finds the true closest ones. Slow on big data.
Approximate search
Look at a small part of the vectors, chosen cleverly. Very fast. Might miss a true neighbour now and then.
Recall tells you how good an ANN index is: of the true top 10, how many did it find? A recall of 0.95 means 9 or 10 of them. You can trade speed for recall with the index settings.
What ANN is
A shortcut that chooses which vectors to score, so we do not score all of them.
What it is not
A new way to score. We still score with cosine, dot product or Euclidean.
The flow
ANN picks a small set of candidates. The score ranks them. The top-k come back.

The Families of ANN Algorithms

There are dozens of ANN algorithms. You do not need to learn them all. They fall into five families, and each family uses one main trick.

FamilyThe trickA pictureAlgorithms
GroupsSort the vectors into groups. Search only the nearest groups.Books sorted into sectionsIVF
GraphsLink each vector to its neighbours. Walk from link to link toward the question.A road networkHNSW, DiskANN
CompressionStore a smaller copy of each vector, so more fit in memory and scoring is faster.A short summary instead of the whole bookPQ, ScaNN (ScaNN also uses groups)
HashingGive similar vectors the same label. Search only the matching label.Same postcode, same areaLSH
TreesCut the space in two, again and again, like a game of twenty questions.Twenty questionsAnnoy
We explain three in detail: IVF (groups), HNSW (graphs) and PQ (compression). For the others, know the name and the trick. Real systems often mix families, for example IVF together with PQ. A library such as FAISS gives you several of these, ready made.

IVF: Search Only the Right Section

IVF stands for Inverted File. Before the picture, let us see what the name means.

File
Just a stored list of things.
The normal way
For each vector, write which group it belongs to: vector 1 is in group A, vector 2 is in group C, and so on. To get all vectors of a group, you must read the whole list.
Inverted
Flip it. For each group, keep the list of the vectors inside it: group A holds vectors 1, 4, 9 and so on. It is the same as the index at the back of a book, which goes from a word to its pages.
In IVF
Each centre keeps the list of its vectors. We find the nearest centre, and then we read its list. That is all.
Centre (one group)Its list of vectors
Centre Avector 1, vector 4, vector 9, …
Centre Bvector 2, vector 5, vector 8, …
Centre Cvector 3, vector 6, vector 7, …
Example lists.
1. Group the vectors (once)Each colour is one group.The diamond is its centre.2. Compare with the centres only★QUESTIONThe question is compared with5 centres, not every dot.3. Search inside that group★QUESTIONOnly the red group is scored.The other groups are skipped.
Build once
Make clusters
Group the vectors with k-means. Each group has a centre.
For each question
Find the nearest centres
Compare the question with the few centres, not with all vectors.
Then
Search inside those clusters
The setting nprobe says how many clusters to open. More: better recall, slower.
The catch: if the true closest vector sits in a cluster you did not open, you miss it. A question near the edge of two clusters is the risky case.

How are the groups made? With a simple method called k-means. Say we have 100,000 vectors and want 100 groups.

Start
Pick 100 of the vectors at random. These are the first centres.
Assign
Give every vector to its nearest centre. Now there are 100 groups. They are uneven: one may hold 5,000 vectors and another 20,000.
Move
Move each centre to the average of the vectors in its group. The centres now sit in the middle of their groups.
Repeat
Assign again with the new centres, then move the centres again. Stop when the centres hardly move. A few rounds are usually enough (10 to 20 is common).
Result
100 centres. Every vector belongs to the group of its nearest centre.
The groups do not become equal in size. The goal is not equal groups. The goal is that each centre sits in the middle of its own group.
Why this is fast: with 100 groups of about 1,000 vectors each, a search compares the question with the 100 centres, then with one group of about 1,000. That is about 1,100 comparisons instead of 100,000.

HNSW: A Graph with Highways

HNSW stands for Hierarchical Navigable Small World. It is the most widely used ANN method, and the one Chroma uses.

LAYER 2LAYER 1LAYER 0n1n2n3n4n5n6n7n8n9n10n11n12★QUESTION
Each dot is a stored vector. The search starts at the top, takes big jumps, and goes down layer by layer. The red path replays every few seconds.
Start
At the top layer
Few dots, long links. Big jumps across the space.
Move
To the closest neighbour
Look at the linked dots. Step to the one nearest the question.
Drop
When nothing is closer
Go down one layer. More dots, shorter links. Repeat until layer 0.

HNSW has three settings you will meet in the docs.

max_neighbors (M)
How many links each dot keeps. More links: better recall, more memory. In the installed Chroma: 16.
ef_construction
How careful the index is when it is built. Higher: a better graph, slower build. In the installed Chroma: 100.
ef_search
How many candidate dots the search keeps in mind. Higher: better recall, slower search. In the installed Chroma: 100.
The cost
The work grows roughly with log N, not N. The price: the graph takes memory, and the result is approximate.

PQ: Make Each Vector Smaller

PQ stands for Product Quantization. It does not choose where to search. It makes every vector smaller, so more of them fit in memory and scoring is faster.

The issue
1 billion vectors of 1,536 numbers each need about 6 terabytes (every number takes 4 bytes). That does not fit in memory.
The idea
Keep a rough copy of each vector instead of the exact one. A rough copy is much smaller.
Cut
Cut each vector into pieces. A vector of 128 numbers becomes 8 pieces of 16 numbers.
Make a menu
For each piece position, the system learns a menu of 256 typical pieces. It uses k-means, the same trick as IVF.
Replace
Replace each piece by the number of its closest menu item. A number from 0 to 255 fits in one byte.
Result
128 numbers (512 bytes) become 8 small numbers (8 bytes). That is 64 times smaller, and a little less exact.
One vector
128 numbers
[0.12, -0.50, 0.31, …]
→
Cut
8 pieces of 16 numbers each
→
Each piece becomes a menu number
one byte each
→
Stored instead
[17, 203, 5, 88, 140, 9, 61, 254]
Example codes.
PQ is often used with IVF. IVF picks the groups to search, and PQ makes the scoring inside them cheap. The combination is called IVF-PQ. The price of PQ is a small loss of accuracy.

Other Ideas to Know

There are more ways to speed up search. You do not need all the details now, but you should know the names.

Hashing
LSH: Locality-Sensitive Hashing
Hash vectors so that similar ones land in the same bucket. Search only the matching bucket. Simple, but usually less accurate than HNSW.
Trees
Annoy
Builds many random trees that split the space. Search walks down the trees. Made at Spotify.
Google
ScaNN
Google's method, built for fast maximum inner-product search.
On disk
DiskANN
A graph method designed for huge data kept on disk, not only in memory.
A library
FAISS
A popular library from Meta. It has flat search, IVF, PQ and HNSW, so you can try them side by side.
Algorithm
The trick for searching faster: IVF, HNSW, PQ, LSH and so on.
Index
The structure built in advance with that trick, ready to search. Some people call it the map.
Library
Ready-made code that gives you several algorithms. FAISS is one.

In Chroma

Your code uses Chroma. Here is what it does for you.

vector_store = Chroma.from_documents(documents=doc_chunks,
    embedding=embeddingModel,
    persist_directory=DB_DIR,
    collection_name=COLLECTION_NAME)

retrieved_docs= vector_store.similarity_search(query=user_question,k=3)
from_documents
Embeds every chunk with the embedding model, builds the HNSW index, and saves the chunk text and metadata with each vector.
persist_directory
Saves everything to a folder, so the next run opens the saved database instead of embedding again.
similarity_search
Embeds the question, searches the index, and returns the chunk texts of the top k.
The metric
The default space is l2, the squared Euclidean distance. To use cosine, set space to cosine when the collection is created (see Where Do You Set It?).

Quick Revision

The whole lesson on one page.

Embeddings
Meaning as numbers
A model turns each chunk into one fixed-size vector. Close vectors mean close meaning. Same model for chunks and questions.
Similarity
Three ways to score
Cosine = angle. Dot product = angle and length. Euclidean = straight-line distance. For normalized vectors they rank the same. You set the choice when you create the collection: space in Chroma, metric in Pinecone, distance in Qdrant.
Search
Exact is slow, ANN is fast
Brute force scores everything, on every question. ANN scores only a small part. Five families: groups (IVF), graphs (HNSW), compression (PQ), hashing (LSH), trees (Annoy). A little recall is traded for a lot of speed.
Store the chunk too. The vector finds the chunk. The chunk text goes to the LLM.
Code
Simple RAG with Chroma and Gemini01_simple_rag.py · 63 linesShow code
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
from dotenv import load_dotenv
load_dotenv()
import os
from langchain_community.document_loaders import PyPDFLoader
from langchain_text_splitters import RecursiveCharacterTextSplitter

from langchain_google_genai import GoogleGenerativeAIEmbeddings
from langchain_chroma import Chroma
from langchain.chat_models import init_chat_model
from langchain_core.prompts import ChatPromptTemplate
from langchain_core.output_parsers import StrOutputParser

DB_DIR = "./chroma_db"
COLLECTION_NAME = "rag_knowledge"

# print(f"Step 1: Loaded {len(docs)} pages from PDF.")
# print(f"Step 2: Created {len(doc_chunks)} chunks.")


"""Embedding model: text -> a list of numbers (vector)"""
embeddingModel = GoogleGenerativeAIEmbeddings(model="models/gemini-embedding-001")

"""First run: load -> split -> embed -> store in Chroma (saved in ./chroma_db). Next runs: open the saved DB"""
if not os.path.exists(DB_DIR):
    loader = PyPDFLoader("data/iitd_ug_rules.pdf")
    docs = loader.load()
    splitter = RecursiveCharacterTextSplitter(chunk_size=500,chunk_overlap=50)
    doc_chunks = splitter.split_documents(docs)
    
    vector_store = Chroma.from_documents(documents=doc_chunks,
                                     embedding=embeddingModel,
                                     persist_directory=DB_DIR,
                                     collection_name=COLLECTION_NAME
                                     )
else:
     vector_store = Chroma(
        persist_directory=DB_DIR,
        embedding_function=embeddingModel,
        collection_name=COLLECTION_NAME
     )
    
user_question = "How much attendance is needed to request an I grade?"

"""Retrieve: find the 3 chunks closest in meaning to the question"""
retrieved_docs= vector_store.similarity_search(query=user_question,k=3)
context_text = "\n\n".join([doc.page_content for doc in retrieved_docs])

"""Augment + Generate: put the chunks in the prompt, the LLM answers from them"""
rag_prompt = ChatPromptTemplate.from_messages([
    ("system", "You are a helpful AI assistant. Answer the user's question ONLY based on the provided context. If the answer cannot be found in the context, say 'I cannot find the answer in the provided documents.'"),
    ("human", "Context:\n{context}\n\nQuestion: {question}")
])

model = init_chat_model("groq:openai/gpt-oss-20b")

rag_chain = rag_prompt | model | StrOutputParser()

response = rag_chain.invoke({"context":context_text , "question":user_question})

print(response)


#