4.4.12Alignment, Prompting & RAG

Vector databases and embeddings

1,740 words8 min readdifficulty · medium3 backlinks

WHY do we need embeddings at all?

WHAT an embedding is: a function f:textRdf: \text{text} \to \mathbb{R}^d that maps any piece of text to a fixed-length vector (e.g. d=384,768,1536d=384, 768, 1536). It is trained so that texts with similar meaning get vectors pointing in similar directions.

HOW it's learned: models (e.g. sentence-transformers, OpenAI text-embedding-3) are trained on huge corpora so that related sentences are pulled together and unrelated ones pushed apart (contrastive learning). We don't hand-design the numbers — the model discovers them.


Measuring closeness: from first principles

We need a number saying "how similar are vectors a\vec{a} and b\vec{b}?"

Derivation of cosine similarity. We want a measure that ignores length and cares only about direction (a long document about dogs and a short one about dogs should still match). Start from the dot product identity above and solve for cosθ\cos\theta:

cosθdirection only=abab\underbrace{\cos\theta}_{\text{direction only}} = \frac{\vec a\cdot\vec b}{\|\vec a\|\,\|\vec b\|}

This is cosine similarity. Why divide by the norms? To strip out magnitude so only the angle (meaning-direction) remains. Range: [1,1][-1, 1]; 11 = identical direction, 00 = orthogonal (unrelated), 1-1 = opposite.


Figure — Vector databases and embeddings

WHAT is a vector database?

Why not just a normal database? A SQL WHERE matches exact values. Here we need approximate geometric proximity over high-dimensional vectors, which needs specialized indexes.

Exact k-NN scans all NN vectors: cost O(Nd)O(N\cdot d). For N=109N=10^9 this is far too slow per query.

HOW ANN works — HNSW (the popular one): build a Hierarchical Navigable Small World graph. Nodes = vectors; edges connect nearby ones across multiple layers (like a skip-list). A query starts at a sparse top layer, greedily hops toward closer neighbours, then descends layer by layer to refine. This gives logarithmic-ish search.


The full pipeline (this is the 80/20 core)

  1. Chunk documents into passages (so each vector represents a focused idea).
  2. Embed each chunk → store vector + original text (metadata).
  3. Embed the user query with the same model.
  4. Search the DB for top-kk nearest chunks.
  5. Feed those chunks to an LLM (this step = RAG, see Retrieval-Augmented Generation).

Worked examples


Recall Feynman: explain to a 12-year-old

Imagine every sentence is a dot placed on a giant star-map. Sentences that mean the same thing are placed as neighbouring stars. To answer your question, the computer turns your question into a dot too, then just looks around it for the nearest stars and reads what they say. The "vector database" is the telescope that finds nearby stars super fast without checking every star in the sky.


Common mistakes


Flashcards

What is an embedding?
A learned function mapping text to a fixed-length vector in Rd\mathbb{R}^d where semantic similarity corresponds to geometric closeness.
Why use cosine similarity instead of raw dot product?
It divides out vector magnitude so only direction (meaning) matters; length of a document shouldn't affect topical match.
Formula for cosine similarity
abab=cosθ\dfrac{\vec a\cdot\vec b}{\|\vec a\|\|\vec b\|}=\cos\theta, range [1,1][-1,1].
What does a vector database do?
Indexes embeddings and answers fast (approximate) k-nearest-neighbour queries for a given query vector.
What is ANN and why use it?
Approximate Nearest Neighbour — trades tiny accuracy for near-logarithmic speed vs O(Nd)O(Nd) exact scan.
How does HNSW search work?
Multi-layer navigable small-world graph; greedy hop from sparse top layer down to dense bottom layer toward closer neighbours.
Why must query and documents use the same embedding model?
Different models live in different coordinate spaces, so cross-model cosine similarity is meaningless.
If vectors are unit-normalized, dot product equals
cosθ\cos\theta (cosine similarity directly).
Relation between Euclidean and cosine for unit vectors
ab2=22cosθ\|\vec a-\vec b\|^2 = 2-2\cos\theta, so they rank identically.
The 5-step retrieval pipeline
Chunk → Embed → Embed query → Search (k-NN) → Rank/feed to LLM (RAG).

Connections

Concept Map

needs comparison

motivates

function f maps text to R^d

meaning becomes geometry

learned via

compared by

divide by norms

strips out magnitude

pre-normalized so

stored in

answers

exact scan too slow O of N d

Text meaning

Keyword search fails

Embeddings

Fixed-length vectors

Similar meaning = close points

Contrastive learning

Dot product

Cosine similarity

Direction only

Vector database

k-NN queries

Approximate NN

Hinglish (regional understanding)

Intuition Hinglish mein samjho

Dekho, computer ke liye "dog" aur "puppy" bas alag-alag letters hain — usse pata nahi ki matlab same hai. Isliye hum har text ko ek embedding yaani numbers ki list (vector) mein badalte hain. Model aise train hota hai ki jo cheezein meaning mein similar hain, unke vectors space mein paas-paas aa jate hain. Matlab meaning ban jaati hai geometry — ab "similar dhundo" ka kaam sirf "paas ka point dhundo" ban gaya.

Similarity naapne ke liye hum cosine similarity use karte hain: dot product ko dono vectors ki length se divide kar do, taaki sirf direction (angle) matter kare, size nahi. Chota document ya bada document, agar dono dog ke baare mein hain to unki direction same hogi, similarity 1\approx 1. Ye reason hai ki hum norms se divide karte hain — magnitude ka distraction hata dete hain.

Ab crores vectors ko store karke turant "nearest" nikalne ke liye chahiye ek vector database (FAISS, Pinecone, Chroma, pgvector). Har vector ko exact check karna slow hai (O(N)O(N)), isliye ye ANN (approximate nearest neighbour) use karte hain, jaise HNSW graph — thoda accuracy chhod ke bahut speed. Pipeline simple hai: document ko chunk karo, embed karo, store karo; phir user ka question bhi usi model se embed karo, DB se top-kk nearest chunks nikaalo, aur LLM ko do (ye RAG hai).

Sabse important trap: query aur documents dono ko same embedding model se embed karna, warna vectors alag "coordinate world" mein honge aur similarity bekaar aayegi. Isko yaad rakho aur 80% kaam ho gaya.

Go deeper — visual, from zero

Test yourself — Alignment, Prompting & RAG

Connections