Skip to content
E
Educatum

What is quantization in the context of embeddings, and how does it contribute to reducing the memory footprint of models while preserving representation quality?

Curated by Educatum AI teamLast updated:
Embeddings
Direct Answer

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:

  1. Scalar Quantization (int8, int4, fp8): Maps continuous float32 components to low-bit integers via per-vector (or per-channel/group) scale ss and optional zero-point zz:
q=clip ⁣(round ⁣(xs)+z,  qmin⁡,  qmax⁡),x^=s (q−z)q = \text{clip}\!\left(\text{round}\!\left(\frac{x}{s}\right) + z,\; q_{\min},\; q_{\max}\right), \qquad \hat{x} = s\,(q - z)

Converting fp32 (32 bits) to int8 gives an exact 4×4\times memory reduction, and int4 gives 8×8\times (plus negligible metadata for per-vector scales). 2. Binary Quantization (1-bit): Stores only sign(x) > 0 packed into bits (32×32\times memory reduction), allowing ultra-fast Hamming distance search via XOR + popcount, typically paired with float/int8 rescoring of the top-KK candidates. 3. Vector & Product Quantization (VQ / PQ): PQ splits a DD-dimensional vector into mm sub-vectors of dimension D/mD/m, clusters each subspace independently into 2b2^{b} centroids (commonly b=8b=8, 256 centroids), and stores only mm byte codes—enabling 16×16\times–64×64\times 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 32×32\times size reduction and bit-packed Hamming search.
  • Product Quantization (PQ): Decomposing vectors into mm orthogonal sub-vectors and encoding each sub-vector by its nearest kk-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 d=768d = 768:

  • float32 (4 bytes): 50,000×768×4=153,600,000 B50{,}000 \times 768 \times 4 = 153{,}600{,}000\text{ B} (153.6 MB153.6\text{ MB} / 146.5 MiB146.5\text{ MiB}).
  • int8 (1 byte + 4-byte scale per row): ≈38.4 MB\approx 38.4\text{ MB} (36.6 MiB36.6\text{ MiB}) — a 4×4\times reduction.
  • 1-bit binary (768/8=96 bytes768 / 8 = 96\text{ bytes} per vector): 4.8 MB4.8\text{ MB} — a 32×32\times reduction.

Similarly, a RAG database of 10M 1024-D fp32 embeddings needs ~41 GB of RAM; PQ with m=64m=64 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)
  • 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 int8 or PQ compressed 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.
View all →

Try keywords like RoPE, FlashAttention, DPO, or Blind 75.