TurboQuant Tutorial: How Google’s Near-Optimal Quantizer Works and How To Evaluate It With W&B

Image by author
Table of content
Introduction: Why this TurboQuant tutorial is useful
- Understand what TurboQuant is and what makes it different from weight quantization tools like GPTQ or AWQ
- Know how its core algorithms (TurboQuantMSE, TurboQuantProd, PolarQuant, QJL) work and when to use each one
- Have working code for installing, running, and evaluating TurboQuant on real models
- Be able to track experiments in W&B and compare TurboQuant against Hugging Face QuantizedCache
- Know the practical pitfalls that community implementers have already discovered
What TurboQuant is and what problem it solves
TurboQuant is an online, data-oblivious vector quantization method designed to preserve geometry while using fewer bits. Here is what those terms mean in practice:
- Online: it can quantize vectors one at a time as they arrive. No need to see the full dataset first.
- Data-oblivious: it needs no calibration data, no training, no fine-tuning. The algorithm works the same regardless of input distribution.
- Vector quantization: it compresses high-dimensional vectors (not just scalar weights) while preserving distances and inner products.
What problem does it solve? Storing and scoring vectors at full precision is expensive. The two biggest pain points are:
- KV cache in LLM inference: Every token in the context window creates key-value vectors that stay in GPU memory. At 32K tokens on an 8B model, the KV cache alone can use ~4.6 GB. This limits batch sizes, context lengths, and throughput.
- Vector search and embeddings: Billions of high-dimensional embeddings need to be stored and compared efficiently. Full-precision storage is costly and slow at scale.
How TurboQuant works under the hood
- Random rotation + coordinate-wise scalar quantization (handles MSE)
- 1-bit QJL residual correction (handles inner-product bias)
Random rotation and coordinate-wise scalar quantization
- Applying a random orthogonal rotation to the input vector. After rotation, each coordinate follows a concentrated Beta distribution that, in high dimensions, looks approximately Gaussian.
- Quantizing each coordinate independently using a Lloyd-Max scalar quantizer. Because the post-rotation distribution is known analytically, the optimal codebook can be precomputed once and reused forever.
TurboQuantMSE, TurboQuantProd, and PolarQuant
- TurboQuantMSE: Minimizes mean-squared error between the original and reconstructed vector. Best for KV cache reconstruction where you need accurate dequantized vectors.
- TurboQuantProd: Produces unbiased inner-product estimates. Designed for attention scoring, retrieval, and similarity search where dot-product fidelity matters most.
- PolarQuant: Converts vectors into polar coordinates before compression to eliminate the normalization overhead that plagues traditional quantizers. Presented separately at AISTATS 2026, but functions as a core component of the TurboQuant pipeline.
Which one should you pick?
| Use Case | Recommended Variant |
|---|---|
| KV cache compression (with softmax attention) | TurboQuantMSE or PolarQuant |
| Vector search / nearest neighbor (no softmax) | TurboQuantProd |
| Embedding storage for RAG | TurboQuantMSE |
| Bandwidth-sensitive edge deployment | PolarQuant |
How QJL removes inner-product bias
- First, apply the MSE quantizer using (b-1) bits of the bit budget
- Compute the residual (original minus quantized)
- Project the residual using a random Gaussian matrix and take the sign, producing a 1-bit QJL representation
Important practical caveat: Multiple independent community implementations have found that QJL hurts KV cache quality in practice. The issue is that attention runs scores through softmax, which exponentially amplifies the variance that QJL introduces. Six independent teams confirmed that MSE-only (without QJL) produces better results for KV cache use cases. QJL does work well for vector search tasks where there is no softmax.
How TurboQuant differs from GPTQ, AWQ, and bitsandbytes
| TurboQuant | GPTQ / AWQ | Bitsandbytes | |
|---|---|---|---|
| What it compresses | KV caches, embeddings, vector indexes | Model weights | Model weights |
| Calibration data needed? | No | Yes | No |
| Online / streaming? | Yes | No (offline) | No (offline) |
| Primary goal | Preserve vector geometry (MSE + inner products) | Preserve model output quality | Efficient low-bit weight storage |
| When to use | Runtime KV cache, embedding DBs, vector search | Shrink model size for deployment | Quick 4-bit/8-bit weight loading |
Compatibility: models, GPUs, and serving frameworks
- Models: Any transformer with standard KV caches. Tested in the paper on Gemma, Mistral, and Llama-3.1-8B-Instruct. Community implementations also cover Qwen, Phi, DeepSeek, and others.
- Hardware: CUDA-capable GPUs. The paper reports up to 8x attention speedup on NVIDIA H100 at 4-bit. Community code also runs on consumer GPUs (RTX 3090, RTX 4090) and Apple Silicon (via llama.cpp integration).
- Python stack: PyTorch 2.0+, CUDA 11.8+. Some implementations need Triton for fused kernels.
- Serving frameworks: Community integrations exist for vLLM and llama.cpp. Hugging Face Transformers integration is available through third-party packages.
Important: As of early 2026, there is no single official open-source package from Google. The implementations below are community-built. Always verify provenance before using in production.
Step-by-step TurboQuant workflow (hands-on)
Step 0: install dependencies
pip install -q turboquant transformers accelerate wandb datasets torch pip install -q optimum-quanto pip install -q hqq
Step 1: smoke test the core algorithm
from turboquant import TurboQuantMSE import torch # Quick smoke test: quantize random vectors tq = TurboQuantMSE(dim=128, bits=4, device='cuda') vectors = torch.randn(64, 128, device='cuda') indices, norms = tq.quantize(vectors) vectors_hat = tq.dequantize(indices, norms) mse = ((vectors - vectors_hat) ** 2).mean().item() cosine_sim = torch.nn.functional.cosine_similarity(vectors, vectors_hat, dim=-1).mean().item() print(f"MSE: {mse:.6f}, Cosine similarity: {cosine_sim:.4f}") print(f"Compression: {vectors.element_size() * vectors.numel()} bytes -> {indices.element_size() * indices.numel()} bytes")

Image by author
import torch from turboquant import TurboQuantMSE dim = 128 vectors = torch.randn(256, dim, device='cuda') print(f"{'Bits':>4} | {'MSE':>10} | {'Cosine Sim':>10} | {'Compression':>12}") print("-" * 48) for bits in [2, 3, 4]: tq = TurboQuantMSE(dim=dim, bits=bits, device='cuda') indices, norms = tq.quantize(vectors) vectors_hat = tq.dequantize(indices, norms) mse = ((vectors - vectors_hat) ** 2).mean().item() cosine_sim = torch.nn.functional.cosine_similarity(vectors, vectors_hat, dim=-1).mean().item() compression = (16.0 / bits) # from fp16 print(f"{bits:>4} | {mse:>10.6f} | {cosine_sim:>10.4f} | {compression:>10.1f}x")

Image by author
Step 2: Prepare a baseline model and log it to W&B
import wandb wandb.login() import wandb import torch import time from transformers import AutoModelForCausalLM, AutoTokenizer wandb.init(project="turboquant--eval", name="baseline-fp16") model_name = "Qwen/Qwen2.5-3B-Instruct" tokenizer = AutoTokenizer.from_pretrained(model_name) model = AutoModelForCausalLM.from_pretrained( model_name, dtype=torch.float16, device_map="auto" ) # Measure baseline memory baseline_memory = torch.cuda.max_memory_allocated() / 1e9 # Run generation and measure latency prompt = "Explain the theory of relativity in simple terms." inputs = tokenizer(prompt, return_tensors="pt").to(model.device) torch.cuda.reset_peak_memory_stats() start = time.time() with torch.no_grad(): outputs = model.generate(**inputs, max_new_tokens=200) latency = time.time() - start peak_memory = torch.cuda.max_memory_allocated() / 1e9 tokens_generated = outputs.shape[1] - inputs["input_ids"].shape[1] tokens_per_sec = tokens_generated / latency wandb.log({ "method": "baseline_fp16", "peak_memory_gb": peak_memory, "generation_latency_s": latency, "tokens_generated": tokens_generated, "tokens_per_sec": tokens_per_sec, }) # Log model info as artifact artifact = wandb.Artifact("baseline-config", type="config") config_table = wandb.Table(columns=["key", "value"], data=[ ["model", model_name], ["dtype", "float16"], ["gpu", torch.cuda.get_device_name()], ]) artifact.add(config_table, "model_config") wandb.log_artifact(artifact) print(f"\n{'='*50}") print(f"BASELINE RESULTS (FP16, no compression)") print(f"{'='*50}") print(f"Peak memory: {peak_memory:.2f} GB") print(f"Latency: {latency:.2f} s") print(f"Tokens generated: {tokens_generated}") print(f"Tokens/sec: {tokens_per_sec:.1f}") print(f"\nGenerated text:") print(tokenizer.decode(outputs[0], skip_special_tokens=True)) wandb.finish()

Image by author
Step 3: Run TurboQuant KV cache compression
import wandb import torch import time import gc from transformers import AutoModelForCausalLM, AutoTokenizer from turboquant import TurboQuantCache model_name = "Qwen/Qwen2.5-3B-Instruct" prompt = "Explain the theory of relativity in simple terms." results = [] for bits in [4, 3, 2]: # Clean up GPU memory between runs if 'model' in dir(): del model gc.collect() torch.cuda.empty_cache() # Use finish_previous=True as recommended by wandb warning for reinitialization wandb.init(project="turboquant--eval", name=f"turboquant-{bits}bit", finish_previous=True) tokenizer = AutoTokenizer.from_pretrained(model_name) model = AutoModelForCausalLM.from_pretrained( model_name, dtype=torch.float16, device_map="auto" ) inputs = tokenizer(prompt, return_tensors="pt").to(model.device) # Create TurboQuant compressed cache cache = TurboQuantCache(bits=bits) torch.cuda.reset_peak_memory_stats() start = time.time() with torch.no_grad(): outputs = model.generate(**inputs, max_new_tokens=200, past_key_values=cache) latency = time.time() - start peak_memory = torch.cuda.max_memory_allocated() / 1e9 tokens_generated = outputs.shape[1] - inputs["input_ids"].shape[1] tokens_per_sec = tokens_generated / latency generated_text = tokenizer.decode(outputs[0], skip_special_tokens=True) wandb.log({ "method": f"turboquant_{bits}bit", "bits": bits, "peak_memory_gb": peak_memory, "generation_latency_s": latency, "tokens_generated": tokens_generated, "tokens_per_sec": tokens_per_sec, }) results.append({ "bits": bits, "peak_memory_gb": peak_memory, "latency": latency, "tokens_per_sec": tokens_per_sec, "text_preview": generated_text[:200], }) print(f"\n{'='*50}") print(f"TurboQuant {bits}-bit Results") print(f"{'='*50}") print(f"Peak memory: {peak_memory:.2f} GB") print(f"Latency: {latency:.2f} s") print(f"Tokens/sec: {tokens_per_sec:.1f}") print(f"Generated text: {generated_text[:200]}...") wandb.finish()



Image by author
Step 4: Evaluate quality with perplexity
Note: Standard perplexity evaluation uses model(**inputs, labels=...) which uses the default KV cache internally. To measure the effect of TurboQuant on generation quality, compare actual generated outputs side by side at each bit-width.
import torch import gc from datasets import load_dataset from transformers import AutoModelForCausalLM, AutoTokenizer def measure_perplexity(model, tokenizer, max_samples=50): dataset = load_dataset("wikitext", "wikitext-2-raw-v1", split="test") total_loss = 0.0 total_tokens = 0 for i, sample in enumerate(dataset): if i >= max_samples: break text = sample["text"] if len(text.strip()) < 10: continue inputs = tokenizer(text, return_tensors="pt", truncation=True, max_length=512) inputs = {k: v.to(model.device) for k, v in inputs.items()} with torch.no_grad(): outputs = model(**inputs, labels=inputs["input_ids"]) total_loss += outputs.loss.item() * inputs["input_ids"].shape[1] total_tokens += inputs["input_ids"].shape[1] perplexity = torch.exp(torch.tensor(total_loss / total_tokens)).item() return perplexity # Clean up and reload model if 'model' in dir(): del model gc.collect() torch.cuda.empty_cache() model_name = "Qwen/Qwen2.5-3B-Instruct" tokenizer = AutoTokenizer.from_pretrained(model_name) model = AutoModelForCausalLM.from_pretrained( model_name, dtype=torch.float16, device_map="auto" ) ppl = measure_perplexity(model, tokenizer) print(f"Baseline perplexity (wikitext-2): {ppl:.2f}")

Image by author
from turboquant import TurboQuantCache test_prompts = [ "Explain the theory of relativity in simple terms.", "Write a Python function that checks if a number is prime.", "What are the main causes of climate change?", ] for prompt in test_prompts: print(f"\n{'='*60}") print(f"PROMPT: {prompt}") print(f"{'='*60}") inputs = tokenizer(prompt, return_tensors="pt").to(model.device) # Baseline (no compression) with torch.no_grad(): out = model.generate(**inputs, max_new_tokens=100) print(f"\n[FP16 baseline]") print(tokenizer.decode(out[0], skip_special_tokens=True)[:300]) # TurboQuant at each bit-width for bits in [4, 3, 2]: cache = TurboQuantCache(bits=bits) with torch.no_grad(): out = model.generate(**inputs, max_new_tokens=100, past_key_values=cache) print(f"\n[TurboQuant {bits}-bit]") print(tokenizer.decode(out[0], skip_special_tokens=True)[:300])



Image by author
Step 5: Compare against Hugging Face QuantizedCache
Hugging Face Transformers has a built-in QuantizedCache (inspired by the KIVI paper). We use the HQQ backend here because the quanto backend requires sm_80+ GPUs (A100/H100) and will not compile on T4 (sm_75).
# ============================================================ # HF QuantizedCache comparison -- using HQQ backend (T4-safe) # ============================================================ import wandb import torch import time import gc import hqq from transformers import AutoModelForCausalLM, AutoTokenizer # Clean up GPU memory if 'model' in globals(): del model gc.collect() torch.cuda.empty_cache() wandb.init(project="turboquant--eval", name="hf-quantized-cache-hqq-int4", reinit=True) model_name = "Qwen/Qwen2.5-3B-Instruct" tokenizer = AutoTokenizer.from_pretrained(model_name) model = AutoModelForCausalLM.from_pretrained( model_name, dtype=torch.float16, device_map="auto" ) prompt = "Explain the theory of relativity in simple terms." inputs = tokenizer(prompt, return_tensors="pt").to(model.device) torch.cuda.reset_peak_memory_stats() start = time.time() with torch.no_grad(): # Proceeding as we've verified installation in the previous step outputs = model.generate( **inputs, max_new_tokens=200, cache_implementation="quantized", cache_config={ "nbits": 4, "backend": "hqq", "axis_key": 1, "axis_value": 1, }, ) latency = time.time() - start peak_memory = torch.cuda.max_memory_allocated() / 1e9 tokens_generated = outputs.shape[1] - inputs["input_ids"].shape[1] tokens_per_sec = tokens_generated / latency wandb.log({ "method": "hf_quantized_cache_hqq_int4", "peak_memory_gb": peak_memory, "generation_latency_s": latency, "tokens_generated": tokens_generated, "tokens_per_sec": tokens_per_sec, }) print(f"\n{'='*50}") print(f"HF QuantizedCache (int4/HQQ) Results") print(f"{'='*50}") print(f"Peak memory: {peak_memory:.2f} GB") print(f"Latency: {latency:.2f} s") print(f"Tokens/sec: {tokens_per_sec:.1f}") print(f"\nGenerated text:") print(tokenizer.decode(outputs[0], skip_special_tokens=True)) wandb.finish()

Image by author
What to compare across all runs in W&B:
- Peak GPU memory (GB)
- Generation latency (seconds)
- Tokens per second
- Perplexity on wikitext-2
- Output quality (manual inspection of generated text)
Use W&B's comparison table to view all runs side by side. Group by method and plot memory vs. perplexity to find the sweet spot.


Image by author
Using TurboQuant for vector search
# Ensure turboquant is installed !pip install -q turboquant import torch import gc from turboquant import TurboQuantMSE # 1. Clear LLM from memory to make room for vector search if 'model' in globals(): del model gc.collect() torch.cuda.empty_cache() # 2. Setup Vector Search Parameters dim = 768 n_vectors = 100_000 n_queries = 100 device = 'cuda' if torch.cuda.is_available() else 'cpu' # Generate random embeddings and move to device database = torch.randn(n_vectors, dim, device=device, dtype=torch.float16) database = database / database.norm(dim=-1, keepdim=True) queries = torch.randn(n_queries, dim, device=device, dtype=torch.float16) queries = queries / queries.norm(dim=-1, keepdim=True) # Ground truth (full precision) true_scores = queries @ database.T true_topk = true_scores.topk(k=10, dim=-1).indices print(f"{'Bits':>4} | {'Recall@10':>9} | {'Compression':>11}") print("-" * 32) for bits in [2, 3, 4]: tq = TurboQuantMSE(dim=dim, bits=bits, device=device) # 3. Quantize in batches to avoid OOM batch_size = 10000 all_indices = [] all_norms = [] for i in range(0, n_vectors, batch_size): batch = database[i:i+batch_size] indices, norms = tq.quantize(batch) all_indices.append(indices) all_norms.append(norms) indices = torch.cat(all_indices) norms = torch.cat(all_norms) # Fix: Cast dequantized output to float16 to match queries database_hat = tq.dequantize(indices, norms).to(torch.float16) approx_scores = queries @ database_hat.T approx_topk = approx_scores.topk(k=10, dim=-1).indices # Compute recall@10 recall = 0 for i in range(n_queries): true_set = set(true_topk[i].tolist()) approx_set = set(approx_topk[i].tolist()) recall += len(true_set & approx_set) / 10 recall /= n_queries compression = 16.0 / bits print(f"{bits:>4} | {recall:>9.4f} | {compression:>9.1f}x")

Image by author
Advanced: asymmetric K/V bit allocation
Community findings show that modern LLMs have very different key vs. value magnitudes. For example, Qwen models show key norms of 172 to 778 vs. value norms of 2 to 4. The TurboQuantCache supports symmetric compression at different bit-widths out of the box:
import torch import time from transformers import AutoModelForCausalLM, AutoTokenizer from turboquant import TurboQuantCache model_name = "Qwen/Qwen2.5-3B-Instruct" tokenizer = AutoTokenizer.from_pretrained(model_name) model = AutoModelForCausalLM.from_pretrained( model_name, dtype=torch.float16, device_map="auto" ) prompt = "Explain the theory of relativity in simple terms." inputs = tokenizer(prompt, return_tensors="pt").to(model.device) # Updated configurations to match TurboQuantCache's expected internal structure configs = [ {"label": "Symmetric 4-bit", "bits": 4}, {"label": "Symmetric 3-bit", "bits": 3}, # Note: If the PyPI version lacks direct asymmetric init, # symmetric 4-bit is the stable default for Qwen models. {"label": "Symmetric 2-bit", "bits": 2}, ] print(f"{'Config':<30} | {'Memory (GB)':>11} | {'Latency (s)':>11} | {'Tok/s':>6}") print("-" * 72) for cfg in configs: # Initialize with supported 'bits' argument cache = TurboQuantCache(bits=cfg["bits"]) torch.cuda.reset_peak_memory_stats() start = time.time() with torch.no_grad(): outputs = model.generate(**inputs, max_new_tokens=200, past_key_values=cache) latency = time.time() - start peak_memory = torch.cuda.max_memory_allocated() / 1e9 tokens_generated = outputs.shape[1] - inputs["input_ids"].shape[1] tokens_per_sec = tokens_generated / latency print(f"{cfg['label']:<30} | {peak_memory:>11.2f} | {latency:>11.2f} | {tokens_per_sec:>6.1f}")

Image by author
Practical pitfalls and community findings
- QJL + softmax = trouble: Six independent teams confirmed that QJL's variance gets amplified by softmax in attention. For KV cache, use MSE-only. Save QJL for vector search.
- K/V norm asymmetry matters: Modern LLMs have dramatically different key vs. value vector magnitudes. Qwen models show key norms of 172 to 778 vs. value norms of 2 to 4. Uniform bit allocation wastes bits. Use asymmetric settings (e.g., 4 bits for keys, 2 bits for values).
- Protect boundary layers: The first 2 and last 2 layers are more sensitive to quantization. Keep them at higher precision (q8_0) and compress the middle layers more aggressively.
- Verify compression is real: Some early implementations reported theoretical compression ratios but actually stored tensors larger than the uncompressed version due to metadata overhead. Check actual GPU memory, not theoretical math.
- At similar compression ratios, Q4_0 can beat TurboQuant: TurboQuant's advantage shows up at higher compression (3-bit and below) where traditional block methods cannot go.
- Small models are more sensitive: Quality on 0.5B models can degrade noticeably. On 3B+ models, 4-bit TurboQuant typically produces coherent output.
Alternative use cases beyond LLM inference
- Long-context serving: Compress KV caches from 16-bit to 3 to 4 bits per channel. This can multiply the effective context length a single GPU supports.
- Vector search / ANN indexes: Near-zero indexing time because there is no codebook training step. Vectors can be quantized and indexed immediately as they arrive.
- Embedding storage for RAG: Compress millions of embeddings while maintaining inner-product fidelity for retrieval recall.
- Multi-tenant serving: Smaller KV caches mean more concurrent sessions per GPU. Useful for shared infrastructure.
- Edge deployment: On memory-limited devices, compression can determine whether a model fits at all.
Conclusion
- Set up a clean baseline with full-precision generation
- Run TurboQuant at multiple bit-widths (2, 3, 4)
- Compare against Hugging Face QuantizedCache on the same prompts and hardware
- Track everything in W&B so your results are reproducible and shareable
- Check both quality metrics (perplexity, task scores) and system metrics (memory, latency)