What is quantization in the context of embeddings, and how does it contribute to reducing the memory footprint of models while preserving representation quality?
Embedding quantization reduces the bit-width or representation precision of embedding vectors—for example, compressing 32-bit floats to int8 (4x reduction), int4 (8x), binary 1-bit codes (32x), or compact Product Quantization (PQ) codebook indices. Using per-vector scaling, quantization-aware training, or subspace codebooks preserves relative cosine geometry and nearest-neighbor rankings while shrinking RAM/VRAM footprints and accelerating retrieval.
Study Card: Quantization of Embeddings
Direct Answer
Embedding quantization lowers the storage precision of high-dimensional vector tables—both token embedding tables inside LLMs and dense document/image vector indexes in RAG & search—to dramatically reduce memory bandwidth and footprint while retaining semantic geometry:
- Scalar Quantization (int8, int4, fp8): Maps continuous
float32components to low-bit integers via per-vector (or per-channel/group) scale and optional zero-point :
Converting fp32 (32 bits) to int8 gives an exact memory reduction, and int4 gives (plus negligible metadata for per-vector scales).
2. Binary Quantization (1-bit): Stores only sign(x) > 0 packed into bits ( memory reduction), allowing ultra-fast Hamming distance search via XOR + popcount, typically paired with float/int8 rescoring of the top- candidates.
3. Vector & Product Quantization (VQ / PQ): PQ splits a -dimensional vector into sub-vectors of dimension , clusters each subspace independently into centroids (commonly , 256 centroids), and stores only byte codes—enabling – compression with fast Asymmetric Distance Computation (ADC) via precomputed lookup tables.
Why quality holds: Semantic similarity relies on relative angles and ordering rather than 32-bit mantissa precision; per-vector calibration (avoiding naive global tensor scales distorted by outliers) and optional Quantization-Aware Training (QAT) or two-stage rescoring keep recall above 95%–99% of fp32 baselines.
Key Terms
- Scalar Quantization: Quantizing individual coordinate values (
fp32 -> int8 / int4), ideally with per-vector or per-group scale factors. - Binary Quantization: Compressing each embedding coordinate to 1 bit (
sign), giving size reduction and bit-packed Hamming search. - Product Quantization (PQ): Decomposing vectors into orthogonal sub-vectors and encoding each sub-vector by its nearest -means centroid ID.
- Asymmetric Distance Computation (ADC) & Rescoring: Comparing a full-precision query against quantized index vectors, then re-ranking top candidates with higher-precision vectors.
Example
Consider an embedding table with 50,000 tokens and dimension :
float32(4 bytes): ( / ).int8(1 byte + 4-byte scale per row): () — a reduction.1-bit binary( per vector): — a reduction.
Similarly, a RAG database of 10M 1024-D fp32 embeddings needs ~41 GB of RAM; PQ with 8-bit subquantizers shrinks the index to ~640 MB so it fits comfortably in memory or L3/GPU cache.
Code Implementation
import numpy as np
import torch
import torch.nn.functional as F
torch.manual_seed(0)
embeddings = F.normalize(torch.randn(1000, 768), dim=-1)
# 1. Per-vector symmetric int8 quantization (preserves dynamic range per embedding)
scales = embeddings.abs().amax(dim=-1, keepdim=True).clamp(min=1e-8) / 127.0
q_int8 = torch.round(embeddings / scales).clamp(-127, 127).to(torch.int8)
deq_int8 = q_int8.float() * scales
cos_retention = F.cosine_similarity(embeddings, deq_int8, dim=-1).mean().item()
print(f"fp32 bytes: {embeddings.numel() * 4:,} | int8 bytes: {q_int8.numel():,} | Mean cosine retention: {cos_retention:.6f}")
# 2. Binary 1-bit quantization (32x compression via bit-packing)
binary_bits = (embeddings > 0).numpy().astype(np.uint8)
packed_binary = np.packbits(binary_bits, axis=-1) # Shape: (1000, 96) bytes
print(f"Packed 1-bit shape: {packed_binary.shape} ({packed_binary.nbytes:,} bytes)")
# 3. Product Quantization (PQ) example using Faiss (requires faiss-cpu / faiss-gpu)
# import faiss
# m, n_bits = 8, 8 # 8 subspaces x 8 bits = 8 bytes per 768-D vector
# pq_index = faiss.IndexPQ(768, m, n_bits)
# data_np = embeddings.numpy().astype("float32")
# pq_index.train(data_np)
# pq_index.add(data_np) # In-place
# reconstructed = pq_index.reconstruct_n(0, 1) # Works directly on IndexPQ (for IndexIVFPQ call make_direct_map() first)
Related Concepts
- Matryoshka Representation Learning (MRL): Trains embeddings so leading prefixes (e.g., first 128 of 1,024 dims) stay informative, combining cleanly with quantization for extreme compression.
- HNSW + Quantized Storage: Combining graph-based ANN routing (HNSW) with
int8orPQcompressed vectors. - Quantization-Aware Training (QAT): Simulating quantization rounding errors via Straight-Through Estimators (STE) during training to minimize accuracy loss.
- GPTQ / AWQ: Weight quantization techniques for LLM linear layers using Hessian or activation-aware scaling.