# What Is Product Quantization?

> What product quantization is, how it shrinks each vector into a short code, and the accuracy it costs, explained for your AI interview.

**In short:** Product quantization splits each vector into short pieces and replaces every piece with the ID of its nearest typical example, so a long vector becomes a short code. It cuts memory a lot for search over millions of chunks, at the cost of some accuracy.

AI and LLM interview question Q122, Retrieval-augmented generation (RAG). Advanced, occasional (our estimate). From Venkat R. Murty's free Interview Kit: https://designervenkat.online/interview/ai/what-is-product-quantization

## Say it in 30 seconds

Product quantization shrinks a vector so search can hold millions of them in memory. I split each vector into short pieces, then swap each piece for the ID of its nearest typical example, called a centroid. The list of IDs is the code. Search builds a small table of distances, then scores the codes fast. It costs some accuracy, so I re-check the best few candidates against the full vectors.

## Say it in 2 minutes

Picture a legal-tech team with 40 million text chunks from client contracts. Each chunk is stored as a vector of 768 numbers. Stored in full, those vectors take about 123 GB, just to search. That is the problem product quantization solves.

The method splits each vector into pieces, here 96 pieces of 8 numbers. For each piece, the index keeps a codebook: a set of typical examples, called centroids, learned from sample data. Each piece is replaced by the ID of its nearest centroid, so the whole vector becomes 96 one-byte IDs. That is 96 bytes instead of 3,072, about 32 times less memory.

Search does not rebuild the full vectors. It builds a small table of distances from the query to every centroid, then scores each code by adding table values. That is fast, but the distances are estimates, so the ranking can slip. The fix is to take the best 20 candidates and check them against the full vectors, which costs a little extra work.

So the honest answer is a trade: less memory and faster search, for some accuracy. You measure that trade on real questions before you ship. Build time also rises with the sample size used to learn the codebooks, and I would say that plainly in the interview.

## What is product quantization, in plain words?

Product quantization, or PQ, is a way to shrink the vectors that an AI search stores. A vector is a long list of numbers that stands for the meaning of a chunk of text. A big search index can hold millions of them, and that takes a lot of memory.

PQ cuts each vector into short pieces. For each piece, it keeps a small set of typical examples, called centroids. Then it replaces each piece with the ID of the nearest centroid, so the whole vector becomes a short list of IDs.

Think of a courier sorting parcels. At each hub they do not read the full street address. They read a short route code that stands for a whole area. The code is less exact, but it is enough to sort. A legal-tech team holding 40 million contract chunks can do the same: keep short codes in memory, and check only a few full vectors for each question.

- **Vector:** A list of numbers that stands for the meaning of a piece of text, an image or an item.
- **Centroid:** The centre of a cluster of similar pieces. It stands for all of them.
- **Codebook:** The set of centroids learned for one piece of the vector.
- **Short code:** The list of centroid IDs that replaces a vector. It is what gets stored.

## How are the codes built?

Building happens before any search. Microsoft's documentation for its Azure DocumentDB product describes the steps: cut each vector into smaller parts (the docs call them subspaces), group sample parts into clusters with a standard method called k-means, which finds the centre of each group, then store each vector as the cluster IDs of its parts.

- **Step one: Cut the vector.** Split every vector into equal pieces. A made-up 768-number vector becomes 96 pieces of 8 numbers.
- **Step two: Learn the codebooks.** For each piece, cluster sample pieces to find the centroids. Each piece gets its own codebook.
- **Step three: Write the code.** Swap each piece for its nearest centroid ID. The 96 IDs are the short code for that vector.

*Diagram, Turning one vector into a short code: A vector goes in whole and comes out as a short code. Each piece is matched to its nearest centroid, and the codebooks were learned in advance from sample data. Only the IDs are stored.*
1. Cut the 768-number vector into 96 pieces of 8 numbers each.
2. For each piece, find the closest centroid in its learned codebook.
3. Keep only the 96 centroid IDs. They are the short code.

Why 256? The usual design gives each piece 256 centroids. An ID from 0 to 255 fits in one byte, because eight bits give 256 values. So 96 pieces give a 96-byte code.

The idea is old and well known. Jégou, Douze and Schmid described the method in a 2011 paper in IEEE Transactions on Pattern Analysis and Machine Intelligence.

Here it is in plain Python, with made-up numbers. Read the encode function: it is the step that matters.

```python
# A small sketch with made-up numbers: a 4-number vector,
# split into 2 pieces, with 3 centroids for each piece.
CODEBOOKS = [
    [(0.0, 0.0), (1.0, 1.0), (2.0, 0.5)],
    [(0.0, 1.0), (1.5, 0.0), (1.0, 2.0)],
]

def dist2(a, b):
    return sum((x - y) ** 2 for x, y in zip(a, b))

def encode(vec):
    codes = []
    for i, book in enumerate(CODEBOOKS):
        piece = vec[2 * i:2 * i + 2]
        codes.append(min(range(len(book)), key=lambda j: dist2(piece, book[j])))
    return codes

def decode(codes):
    rebuilt = []
    for i, c in enumerate(codes):
        rebuilt.extend(CODEBOOKS[i][c])
    return rebuilt

vec = [1.2, 0.9, 1.4, 0.1]
codes = encode(vec)
rebuilt = decode(codes)
print("original:", vec)
print("codes:", codes)
print("rebuilt:", rebuilt)
print("error:", round(dist2(vec, rebuilt) ** 0.5, 3))
```

Output:

```text
original: [1.2, 0.9, 1.4, 0.1]
codes: [1, 1]
rebuilt: [1.0, 1.0, 1.5, 0.0]
error: 0.265
```

## How does search use the codes?

A question is turned into a vector too. The search does not compare that vector with every full vector. It builds a small table of distances from the query to each centroid, once. Then each stored code is scored by adding up the table values for its IDs. Adding table values is much cheaper than full vector maths for every chunk, and that is where the speed comes from.

In plain terms, the table turns the query into a lookup, so the search does far less full arithmetic. In the 2017 paper on billion-scale GPU search, Johnson, Douze and Jégou call this table lookup the key to PQ's efficiency.

*Diagram, Searching the codes, then checking a few: The search first ranks cheaply, using the table and the short codes. It then checks the few best candidates against full vectors, so the final order is more accurate.*
1. The query is compared with every centroid of every piece, once.
2. Each stored code is scored by adding up table values. Full vectors are not read yet.
3. The best 20 candidates move on to an exact check.
4. The 10 closest chunks go to the model as context.

IVFADC is one of the indexing methods originally built upon product quantization. It puts an inverted file index (IVF) in front. IVF groups the vectors into clusters, so the search checks only a few clusters before it scores the PQ codes. Most interview answers only need to name it.

## What does it cost, and what does it save?

- **Saves: Memory.** Each vector becomes a short code of 96 bytes in the example below, instead of 3,072 bytes of numbers.
- **Costs: Accuracy.** Distances are estimates. A true near neighbour can drop out of the top list.
- **Costs: Build time.** Learning the codebooks takes time. In Azure, a larger training sample (pqSampleSize) gives better quality but a longer build.

> "PQ compression can lead to precision loss in distance calculations." (Microsoft, Azure DocumentDB docs)
>
> "These extra candidates are used to refine the search using the original, full-precision vectors, improving the final top k accuracy." (Microsoft, Azure DocumentDB docs)

Here is a made-up case with real arithmetic. A legal-tech company indexes 40 million text chunks, each as a 768-number vector. Each number is a 32-bit value, which is 4 bytes, so one vector is 768 × 4 = 3,072 bytes. For 40 million vectors that is about 123 GB of raw data. With 96 one-byte codes per vector, the codes take 96 bytes each, about 3.8 GB in total. That is 32 times less memory for the codes held in RAM, so they fit easily in the RAM of one server.

The price is accuracy, so the team keeps the full vectors on disk and checks the best 20 candidates against them. That check is what helps recover the ranking quality the codes lose, at a small extra cost in time.

> **Tip:** Asked about the trade-off, say how you would measure it: recall (the share of the true best answers the search still finds) on real questions with and without PQ, the memory saved, and the build time. Then name the fix: re-rank a few candidates with full vectors, and raise the candidate count if recall is too low.

### How would you cut the memory of a 40-million-chunk index?

Start with the errors users can live with. In contract search, a missed clause is a real risk, so the bar for recall is high and must be tested before any compression goes live.

1. **Measure first:** Build a set of real lawyer questions. For each one, run an exact search and keep its top 10 as the baseline.
2. **Compress and take extra candidates:** Compress with PQ, then take more candidates than you need. Azure's oversampling setting does this: it fetches extra candidates and refines them with the full-precision vectors.
3. **Size the training sample:** Give the codebooks enough sample vectors. A larger sample gives better quality, but the build takes longer, so budget that time.
4. **Compare and decide:** Record recall at 10 for the compressed search: how many of the exact top 10 it still returns. If recall drops too far, raise the candidate count or use less aggressive compression. If it holds, ship the smaller index and keep watching recall.

## What does the interviewer want to hear?

**A strong answer covers**

- [ ] A plain definition: split each vector into pieces, then store the IDs of their nearest centroids.
- [ ] The memory saving, with a rough size: about 32 times less in the example above.
- [ ] The cost: distances are estimates, so accuracy drops.
- [ ] The fix: re-rank a few candidates against the full vectors.
- [ ] Where it fits: very large indexes that must fit in memory, often with IVF in front (IVF groups vectors into clusters first).
- [ ] How you would tune it: recall tests, sample size and build time.

**Common traps**

- Trap: "Product quantization makes search exact, just smaller." Better: It makes the distances approximate. Re-rank a few candidates with the full vectors to win accuracy back.
- Trap: "Use it on every index." Better: A small index fits in memory anyway. Use PQ when memory or cost is the real limit.
- Trap: "Each vector gets its own codebook." Better: The codebooks are shared. One codebook per piece is learned from sample data and reused for every vector.

## Can you spot the right pipeline?

**Spot the pipeline:** A team has 40 million chunks, memory is tight, and the answers must stay close to an exact search. Which pipeline fits?

A. Build the distance table, score every code, return the top 10.
B. Build the distance table, score every code, re-rank the top 20 with full vectors, return the top 10.
C. Load every full vector into the model, then search them in order.
D. Retrain the embedding model, then compress the query.

**Answer:** B. The second pipeline keeps memory small with codes, then checks the best candidates against full vectors, which wins back the accuracy. The first skips that check. The third loads the full index, which is what PQ avoids.

**Quick check:** A chunk index holds 40 million vectors and must fit in RAM. What does product quantization change?

A. It stores short codes of centroid IDs instead of full vectors
B. It makes the embedding model smaller
C. It adds more chunks to the index
D. It removes the need to rank the results

**Answer:** A. Each piece of a vector becomes one centroid ID, so the codes are far smaller. PQ does not touch the model, add chunks or remove ranking. The trade is accuracy, so checks are still needed.

## Can you answer these from memory?

**Flash cards**

- **What is product quantization?** It splits a vector into pieces and stores the IDs of their nearest centroids as a short code.
- **What is a centroid?** The centre of a cluster of similar pieces. It stands for all of them.
- **Why does it save memory?** Each piece becomes one small ID, so a 768-number vector (3,072 bytes) can shrink to about 96 bytes.
- **What is the cost?** Distances are estimates, so accuracy drops. Re-ranking a few candidates wins some back.
- **How does search use the codes?** It builds a small table of distances for the query, then scores each code by adding table values.
- **Why 256 centroids per piece?** Typically 256, so one centroid ID fits in one byte.

## Likely follow-up questions

- Q119 What is approximate nearest-neighbour search? https://designervenkat.online/interview/ai/what-is-approximate-nearest-neighbour-search
- Q120 How does HNSW work? https://designervenkat.online/interview/ai/how-does-hnsw-work
- Q121 How does IVF indexing work? https://designervenkat.online/interview/ai/how-does-ivf-indexing-work
- Q123 What is hybrid search (BM25 + vectors)? https://designervenkat.online/interview/ai/what-is-hybrid-search
- Q131 Retrieval metrics: recall@k, MRR, nDCG? https://designervenkat.online/interview/ai/retrieval-metrics-recall-at-k-mrr-ndcg
