TurboQuant: How a Random Rotation Makes LLM Quantization Near-Optimal

TurboQuant: How a Random Rotation Makes LLM Quantization Near-Optimal

Backer ●1 ●6 ●23
calendar_today • schedule14 min read
— Originally published at sesen.ai

A long conversation with a language model needs memory for the earlier tokens as well as the model's weights. Compressing the stored vectors could make room for more context, but coarse rounding can discard information that attention still needs. TurboQuant explores a way to change the vectors' representation before quantising them. At long contexts, those stored vectors can occupy memory comparable to the weights themselves.

Large coordinates dominate the rounding scale, while a random rotation spreads their contribution. Our NumPy comparison reduces MSE from 0.007602 to 0.000237. The real-model test reports roughly 5x compression at 99.5% attention cosine similarity. We implement the rotation and quantiser to inspect where the improvement comes from.

By the end of this post, you will implement TurboQuant's core algorithm from scratch in NumPy, see exactly why the rotation works (with visualisations), build an optimal scalar quantiser via Lloyd-Max, and measure the distortion improvement against naive quantisation.

Let's Build It

Click the badge to open the interactive notebook:

Open In Colab

Watch how random rotation transforms a spiky, outlier-heavy vector into one with evenly spread coordinates, dramatically reducing quantisation error:

Animation showing a 2D vector being randomly rotated before quantisation. The outlier-heavy vector snaps to a grid point far from its true direction, but the rotated version lands much closer after grid quantisation and inverse rotation.

Here is the complete TurboQuant MSE quantiser in under 60 lines:

import numpy as np
from scipy.stats import norm
from scipy.integrate import quad

def random_rotation_matrix(d, seed=42):
    """Haar-distributed random orthogonal matrix via QR decomposition."""
    rng = np.random.default_rng(seed)
    G = rng.standard_normal((d, d))
    Q, R = np.linalg.qr(G)
    # Fix sign ambiguity so Q is a proper rotation
    Q *= np.sign(np.diag(R))
    return Q

def lloyd_max_codebook(d, bits, max_iter=200, tol=1e-10):
    """Optimal scalar quantiser for N(0, 1/d) via Lloyd-Max iteration."""
    n_levels = 2 ** bits
    sigma = 1.0 / np.sqrt(d)
    pdf = lambda x: norm.pdf(x, 0, sigma)

    # Initialise centroids uniformly across [-3.5*sigma, 3.5*sigma]
    lo, hi = -3.5 * sigma, 3.5 * sigma
    centroids = np.array([lo + (hi - lo) * (i + 0.5) / n_levels for i in range(n_levels)])

    for _ in range(max_iter):
        boundaries = (centroids[:-1] + centroids[1:]) / 2.0
        edges = np.concatenate([[-np.inf], boundaries, [np.inf]])
        new_centroids = np.empty(n_levels)
        for i in range(n_levels):
            num, _ = quad(lambda x: x * pdf(x), edges[i], edges[i + 1])
            den, _ = quad(pdf, edges[i], edges[i + 1])
            new_centroids[i] = num / den if den > 1e-15 else centroids[i]
        if np.max(np.abs(new_centroids - centroids)) < tol:
            break
        centroids = new_centroids

    boundaries = (centroids[:-1] + centroids[1:]) / 2.0
    return centroids, boundaries

def quantize_scalar(x, centroids):
    """Map each scalar to the index of its nearest centroid."""
    return np.argmin(np.abs(x[:, None] - centroids), axis=1)

def turboquant_mse(x, bits=3, seed=42):
    """
    TurboQuant MSE quantise-dequantise cycle.
    x: (d,) unit-norm vector
    Returns: reconstructed vector, MSE
    """
    d = len(x)
    Pi = random_rotation_matrix(d, seed)
    centroids, _ = lloyd_max_codebook(d, bits)

    # Rotate -> quantise each coordinate -> dequantise -> unrotate
    y = Pi @ x
    indices = quantize_scalar(y, centroids)
    y_hat = centroids[indices]
    x_hat = Pi.T @ y_hat

    mse = np.mean((x - x_hat) ** 2)
    return x_hat, mse

Let's test it on a vector with a massive outlier:

d = 128
rng = np.random.default_rng(0)

# Create a spiky vector: one huge coordinate, the rest near zero
x = rng.standard_normal(d) * 0.01
x[0] = 1.0
x = x / np.linalg.norm(x)  # normalise to unit length

# Naive quantisation (no rotation, uniform grid)
grid = np.linspace(-1/np.sqrt(d), 1/np.sqrt(d), 8)  # 3-bit uniform grid
y_naive = grid[np.argmin(np.abs(x[:, None] - grid), axis=1)]
mse_naive = np.mean((x - y_naive) ** 2)

# TurboQuant
x_hat, mse_turbo = turboquant_mse(x, bits=3)

print(f"Naive quantisation MSE:     {mse_naive:.6f}")
print(f"TurboQuant MSE:             {mse_turbo:.6f}")
print(f"Improvement:                {mse_naive / mse_turbo:.1f}x")
Naive quantisation MSE:     0.007602
TurboQuant MSE:             0.000237
Improvement:                32.1x

On a vector with a single dominant coordinate, TurboQuant reduces the quantisation error by over 30x. On well-behaved vectors the improvement is smaller, but it never hurts. That is the beauty of data-oblivious design: the rotation is always safe.

What Just Happened?

The algorithm has three stages. Let's walk through each one.

Step 1: Random Rotation via QR

We generate a random orthogonal matrix Π by drawing a matrix of i.i.d. Gaussian entries and applying QR decomposition. Multiplying a vector by Π rotates it to a uniformly random orientation on the unit sphere without changing its length.

Pi = random_rotation_matrix(d, seed=42)

# Verify: orthogonal means Pi @ Pi.T = I and ||Pi @ x|| = ||x||
print(f"Orthogonality check: {np.allclose(Pi @ Pi.T, np.eye(d))}")
print(f"Norm preserved: {np.linalg.norm(x):.6f} -> {np.linalg.norm(Pi @ x):.6f}")

Why does this help? Because the original vector x has one coordinate near 1.0 and the rest near 0. After rotation, the energy spreads across all d coordinates. Each coordinate of Π x now has roughly the same magnitude, on the order of 1/√(d).

Histogram of coordinate magnitudes before and after rotation. Before: one spike near 1.0, the rest clustered at 0. After: a symmetric bell curve centred at 0.

This is the concentration of measure phenomenon on the unit sphere. In high dimensions, a random rotation almost surely produces a vector whose coordinates are nearly independent draws from N(0, 1/d).

Step 2: Lloyd-Max Scalar Quantisation

Now that every coordinate lives in the same narrow range, we can design an optimal scalar quantiser for the distribution N(0, 1/d). This is the Lloyd-Max algorithm (also known as continuous 1-D K-Means):

  1. Initialise 2^(b) centroids uniformly across the distribution's support
  2. Set boundaries as the midpoints between adjacent centroids
  3. Update each centroid to the conditional mean 𝔼[X | X ∈ partitionᵢ]
  4. Repeat until convergence
centroids, boundaries = lloyd_max_codebook(d=128, bits=3)
print(f"3-bit centroids for d=128:")
print(f"  {centroids}")

The Lloyd-Max centroids are denser where the PDF is tallest (near zero) and sparser in the tails, unlike a uniform grid which wastes levels on regions with low probability mass. Each coordinate is quantised independently by mapping it to the nearest centroid.

Step 3: Inverse Rotation

After quantising the rotated vector Π x to get haty, we apply the inverse rotation Πᵀ haty to recover an approximation in the original space.

Because Π is orthogonal, Πᵀ = Π⁻¹, and the MSE is preserved: the error in the rotated space equals the error in the original space. The rotation does not introduce or amplify quantisation noise.

The full cycle is:

equation

where Q_LM applies Lloyd-Max quantisation coordinate-wise.

Going Deeper

Why Outliers Kill Naive Quantisation

Consider a d-dimensional unit vector where one coordinate is 1 - ε and the rest are O(ε / √(d)). If you quantise each coordinate with a b-bit grid scaled for the typical magnitude 1/√(d), the dominant coordinate saturates (it gets clipped to the grid maximum) and the small coordinates round to zero.

The result is a vector that points along a single cardinal direction. The angular error can be catastrophic: identifying one cardinal direction out of 2d requires only log₂(2d) bits, but you are spending b × d bits. Most of your bit budget is wasted on coordinates that carry no information.

Diagram illustrating how a spiky vector snaps to the nearest axis under naive quantisation, while a rotated version preserves angular information.

This is not a contrived edge case. Transformer models routinely produce activations with "massive" outlier coordinates (Sun et al. 2024, "Massive Activations in Large Language Models"). These outliers concentrate in a few fixed dimensions across all tokens, which is exactly the worst case for coordinate-wise quantisation.

The Beta Distribution After Rotation

The paper proves that after multiplying a unit vector by a random orthogonal matrix, each coordinate follows a Beta distribution:

equation

For dimensions d ≥ 64 (typical for LLM head dimensions), this is well-approximated by N(0, 1/d) via the central limit theorem. The coordinates also become nearly independent. This independence is what allows us to factorise the vector quantisation problem into d independent scalar quantisation problems, each solvable by Lloyd-Max.

Distortion Bounds

TurboQuant achieves per-coordinate MSE distortion bounded by:

equation

At 3 bits, this gives D_MSE ≤ 0.043 per coordinate. The information-theoretic lower bound for quantising a N(0, 1/d) source is D^* = 1/d · 2^(-2b), so TurboQuant is within a factor of 2.7x of the theoretical optimum. At 1-bit, this gap shrinks to just 1.45x.

MSE distortion vs bit-width for TurboQuant, naive uniform quantisation, and the information-theoretic lower bound. TurboQuant tracks close to the theoretical limit while naive quantisation degrades rapidly on outlier-heavy vectors.

Stage 2: Unbiased Inner Products via QJL

MSE-optimal quantisation is not always what you want. In attention, you compute langle q, k rangle between a query and many cached keys. MSE-quantised keys produce biased inner products because the rounding errors correlate with the key direction.

TurboQuant fixes this with a second stage. Of the b-bit budget per coordinate, b-1 bits go to the Lloyd-Max MSE quantiser, and the last bit stores the sign of a random projection of the residual (the Quantized Johnson-Lindenstrauss transform, or QJL).

The inner product estimate becomes:

equation

where r = k - hatk_MSE is the quantisation residual, S is a random Gaussian projection matrix, and m is the projection dimension. The first term is the inner product with the MSE reconstruction; the second term is an unbiased correction from the QJL-compressed residual.

Here is a minimal implementation of the inner product estimator:

def turboquant_inner_product(q, k, bits=3, seed=42):
    """
    Unbiased inner product estimation using TurboQuant Stage 1 + 2.
    q, k: (d,) unit-norm vectors
    Returns: estimated <q, k>
    """
    d = len(k)
    mse_bits = bits - 1  # reserve 1 bit for QJL

    # Stage 1: MSE quantise the key
    Pi = random_rotation_matrix(d, seed)
    centroids, _ = lloyd_max_codebook(d, mse_bits)
    y = Pi @ k
    indices = quantize_scalar(y, centroids)
    y_hat = centroids[indices]
    k_mse = Pi.T @ y_hat

    # Compute residual
    r = k - k_mse
    r_norm = np.linalg.norm(r)

    # Stage 2: QJL on residual
    rng = np.random.default_rng(seed + 1)
    S = rng.standard_normal((d, d))  # projection matrix
    qjl_signs = np.sign(S @ r)
    qjl_signs[qjl_signs == 0] = 1.0

    # Unbiased inner product estimate
    term1 = q @ k_mse
    term2 = r_norm * np.sqrt(np.pi / 2) / d * (S @ q) @ qjl_signs
    return term1 + term2

# Test: compare true vs estimated inner products
d = 256
rng = np.random.default_rng(0)
q = rng.standard_normal(d); q /= np.linalg.norm(q)
k = rng.standard_normal(d); k /= np.linalg.norm(k)
# Add outlier to key
k[0] = 5.0; k /= np.linalg.norm(k)

true_ip = q @ k
est_ip = turboquant_inner_product(q, k, bits=3)
mse_only_ip = q @ turboquant_mse(k, bits=3)[0]

print(f"True inner product:         {true_ip:.6f}")
print(f"TurboQuant (MSE+QJL):       {est_ip:.6f}")
print(f"TurboQuant (MSE only):      {mse_only_ip:.6f}")

The QJL correction is especially important at low bit-widths (2-3 bits) where the MSE residual is larger. At 4+ bits the MSE reconstruction is already accurate enough that the correction is negligible.

KV Cache Compression in Practice

In a real transformer, you would apply TurboQuant separately to each attention head's key and value vectors. Keys use the two-stage TurboQuantProd (because attention needs inner products), while values use the simpler TurboQuantMSE (because the output is a weighted sum, where MSE-optimal reconstruction is sufficient).

At 3 bits per coordinate, TurboQuant achieves roughly 5x compression over FP16 while maintaining 99.5% attention cosine similarity on real models (validated on Qwen2.5-3B with 8K context). The key result from the paper: on needle-in-a-haystack retrieval benchmarks, TurboQuant at 3.5 bits is quality-neutral compared to full-precision inference.

Where This Comes From

TurboQuant was introduced by Zandieh, Daliri, Hadian, and Mirrokni (Google Research) in their 2025 paper "TurboQuant: Online Vector Quantization with Near-optimal Distortion Rate", published at ICLR 2026.

The Core Contribution

The paper frames quantisation through Shannon's source coding theory. The key insight is that a random orthogonal rotation transforms any unit vector into one whose coordinates are nearly i.i.d. from a known distribution (the Beta distribution on the sphere), enabling closed-form optimal quantisation.

"We start by randomizing this vector by multiplying it with a random rotation matrix. We can generate the rotation by applying QR decomposition on a random matrix with i.i.d Normal entries."

This is data-oblivious: unlike methods that require calibration data to learn a good basis (such as QuIP and QuIP#), TurboQuant works on any vector without training. The rotation matrix can even be generated from a shared seed, so only the seed needs to be communicated, not the full matrix.

Relationship to Prior Work

The idea of using orthogonal transformations before quantisation appears in earlier work:

  • QuIP (Chee et al. 2024) uses random orthogonal matrices for weight quantisation, but requires expensive calibration with training data
  • QuIP# (Tseng et al. 2024) extends QuIP with the randomised Hadamard transform for faster rotation
  • PolarQuant (Hao et al. 2025) uses polar coordinates (separating norm and angle), which inspired some of the initial confusion around TurboQuant

TurboQuant's contribution is twofold: it provides tight theoretical distortion bounds (within 2.7x of information-theoretic optimum), and it adds the QJL residual correction for unbiased inner products, which is critical for attention computation.

Experimental Results

The paper validates TurboQuant on two tasks:

KV cache quantisation on Llama-3.1-8B: TurboQuant at 3.5 bits per coordinate matches full-precision performance on the needle-in-a-haystack benchmark and LongBench suite across question-answering, summarisation, and code completion. Competing methods (KIVI, SnapKV, PyramidKV) all show measurable degradation at the same compression rate.

Nearest-neighbour search on GloVe and OpenAI embeddings: TurboQuant delivers higher recall than Product Quantisation and RabitQ while reducing quantisation time from minutes (or hours) to milliseconds, because the codebook is precomputed analytically rather than learned from data.

Further Reading

  • Zandieh et al. (2025), "TurboQuant: Online Vector Quantization with Near-optimal Distortion Rate" (the primary paper)
  • Chee et al. (2024), "QuIP: 2-Bit Quantization of Large Language Models With Guarantees" (orthogonal rotation for weight quantisation)
  • Sun et al. (2024), "Massive Activations in Large Language Models" (the outlier phenomenon that motivates rotation)
  • Lloyd (1982), "Least Squares Quantization in PCM" (the Lloyd-Max algorithm)

Interactive Tools

Frequently Asked Questions

What is TurboQuant and when should I use it?

TurboQuant is a vector quantisation algorithm that compresses high-dimensional vectors to 2-4 bits per coordinate with near-optimal distortion. Use it when you need to compress LLM KV caches for long-context inference, build approximate nearest-neighbour indices, or quantise any high-dimensional vectors where outlier coordinates are common. It is data-oblivious, so no calibration data or training is required.

How does TurboQuant differ from standard weight quantisation methods like GPTQ or AWQ?

GPTQ and AWQ quantise model weights using calibration data to minimise output error. TurboQuant quantises activations (specifically KV cache vectors) at inference time, without any calibration. The key difference is that TurboQuant is an online algorithm: each vector is quantised independently using only a random rotation and a precomputed codebook, making it suitable for streaming inference where you cannot batch-calibrate.

Why not just use the randomised Hadamard transform instead of a full random rotation?

The Hadamard transform is O(d log d) compared to O(d²) for a full random rotation, so it is faster. QuIP# uses this approach. However, the Hadamard transform is a fixed structured rotation, not a Haar-random one, so its theoretical distortion guarantees are weaker. For moderate dimensions (d = 64-256, typical attention head sizes), the O(d²) cost is negligible compared to the attention computation itself.

What bit-width should I use for KV cache compression?

The paper shows that 3.5 bits per coordinate (3 bits for MSE + 1 bit for QJL on keys, 4 bits for values) is quality-neutral on needle-in-a-haystack benchmarks. At 2.5 bits, there is marginal degradation. Below 2 bits, distortion grows quickly. For most production settings, 3 bits for keys and 3-4 bits for values is a good starting point, giving 4-5x compression over FP16.

Can TurboQuant be applied to model weights, not just activations?

In principle yes, but weight quantisation methods like GPTQ and QuIP can exploit the weight distribution (which is fixed after training) to do better than a data-oblivious approach. TurboQuant's strength is that it works without calibration, which is essential for activations that change with every input. For weights, calibration-based methods generally achieve lower distortion at the same bit-width.

Does the random rotation need to be different for every vector?

No. A single rotation matrix (or a small set, one per attention head) is generated once from a shared seed and reused for all vectors in that head. This means the rotation matrix can be precomputed and cached, and only the integer seed needs to be stored. The key insight is that the rotation needs to be random relative to the vector distribution, not different per vector.

Want more #llm & #deep-learning deep dives?

Join 6,179+ developers sharing real benchmarks, code breakdowns, and projects. Free forever.

2 Comments

1 vote
1 vote

More Posts

Perceptual Loss and Super-Resolution: Why Pixel MSE Fails

berkansesenverified - Nov 23

Beyond Attention: Linear Attention & Mamba SSMs

berkansesenverified - Nov 17

Hamiltonian Neural Networks: Physics as Inductive Bias

berkansesenverified - Nov 29

Sovereign Intelligence: The Complete 25,000 Word Blueprint (Download)

Pocket Portfolio - Apr 1

Architecting a Local-First Hybrid RAG for Finance

Pocket Portfolio - Feb 25
chevron_left
1.9k Points • 30 Badges
London • sesen.ai
48Posts
0Comments
45Connections
AI Researcher, Consultant, Entrepreneur.

Related Jobs

View all jobs →

Commenters (This Week)

1 comment
1 comment
1 comment

Contribute meaningful comments to climb the leaderboard and earn badges!