Building GPT-2 and TurboQuant KV-Cache Compression from Scratch

Home Blog Resume Contact LinAlg Visualizer

<- Back

We are going to build a full GPT-2 (124M) decoder-only transformer from scratch in PyTorch, wire in a pluggable KV Cache for fast text generation, implement Google Research’s TurboQuant KV-cache compression algorithm (arXiv:2504.19874) down to real bit-packed bytes, and finally train our own 124M weights from scratch on 10 billion tokens of FineWeb-Edu across 4× NVIDIA H100 GPUs.

Just like when I built my Fashion-MNIST neural network in pure NumPy, the goal here isn’t to call high-level wrappers and hope for the best; it’s to actually understand every tensor shape, every matrix transformation, and every failure mode along the way.

I definitely learned a lot from Andrej Karpathy’s Let’s reproduce GPT-2 (124M), Sebastian Raschka’s Understanding and Coding the KV Cache in LLMs from Scratch, and the original TurboQuant and QJL papers from Google Research.

All of the code, tests, and benchmarks from this write-up live on GitHub: meltyblend/TurboQuant-GPT-2-Implementation.


The Architecture: GPT-2 (124M) From Scratch

Before we can compress anything, we need a clean, standalone GPT-2 model that we own line by line.

Our model in MyGPT2.py follows the standard GPT-2 pre-norm decoder stack:

In total, that works out to 124,439,808 parameters, and because we match OpenAI’s submodule names (transformer.wte, transformer.h.N.attn.c_attn, etc.), we can either initialize random weights and train from scratch or drop OpenAI’s pretrained GPT-2 weights straight into our class for instant sanity checks.

Token + Position Embeddings & Weight Tying

Transformers don’t have a built-in sense of word order. Without positional information, "the cat chased the dog" and "the dog chased the cat" look identical to attention.

So at the very entrance of GPT2.forward, we look up each token’s learned meaning vector (wte) and add a learned position vector (wpe):

X=wte(idx)+wpe(pos),dim⁡(X)=(B,T,768)X = \text{wte}(\text{idx}) + \text{wpe}(\text{pos}), \qquad \dim(X) = (B, T, 768)

We also tie the input embedding weights to the final output projection (self.transformer.wte.weight = self.lm_head.weight). Both matrices map between vocabulary space (50,257) and residual-stream space (768), so sharing one matrix saves ~38.6M parameters and improves generalization.

Pre-Norm Transformer Blocks

Each TransformerBlock has two sub-layers wrapped in residual connections:

x←x+CausalSelfAttention(LayerNorm(x))x \leftarrow x + \text{CausalSelfAttention}(\text{LayerNorm}(x)) x←x+FeedForward(LayerNorm(x))x \leftarrow x + \text{FeedForward}(\text{LayerNorm}(x))

Here is a helpful mental model that makes the whole transformer click:

That distinction becomes super important the moment we add a KV cache.

Initialization Trick for Deep Residuals

Every block adds two projections (attn.c_proj and mlp.c_proj) straight back into the residual stream. Over 12 layers (24 residual additions), if you initialize every layer with standard deviation 0.02, the variance of the residual stream grows with depth.

Following GPT-2’s recipe, we scale the initialization std of every residual-writing projection by:

σproj=0.022⋅nlayer=0.0224≈0.004082\sigma_{\text{proj}} = \frac{0.02}{\sqrt{2 \cdot n_{\text{layer}}}} = \frac{0.02}{\sqrt{24}} \approx 0.004082

Why We Need a KV Cache (Prefill vs. Decode)

Now let’s think about what happens when GPT-2 actually generates text one word at a time.

Everything in a KV cache comes from one simple rule of causal attention:

Token tt can only attend to tokens 0,1,…,t0, 1, \dots, t, never to future tokens.

That means once we compute token tt‘s Key (ktk_t) and Value (vtv_t) vector at layer ℓ\ell, those numbers will never change, no matter how many new words get generated afterward!

Imagine our prompt is the 4 tokens "The cat sat on", and GPT-2 predicts "the":

Two quick intuition checks that really helped me:

The Memory Math Behind KV Caches

In our CausalSelfAttention, every layer stores k and v with shape:

(B,  nhead,  S,  head_dim)=(B,  12,  S,  64)(B,\; n_{\text{head}},\; S,\; \text{head\_dim}) = (B,\; 12,\; S,\; 64)

For GPT-2 124M in float32 (4 bytes per number), every single token costs:

2 (K & V)×12 layers×12 heads×64 dims×4 bytes=73,728 bytes≈72 KB per token2\text{ (K \& V)} \times 12\text{ layers} \times 12\text{ heads} \times 64\text{ dims} \times 4\text{ bytes} = 73{,}728\text{ bytes} \approx 72\text{ KB per token}

For 1 short prompt of 159 tokens, that’s 11.18 MB. Doesn’t sound scary, until you serve a batch of B = 32 sequences at full 1024-token context:

32×1024×73,728 bytes≈2.4 GB32 \times 1024 \times 73{,}728\text{ bytes} \approx 2.4\text{ GB}

That’s almost 5× larger than the entire 124M model’s weights, purely for temporary KV history! And because decoding has to stream that entire KV cache out of GPU memory for every single token generated, long-context inference quickly becomes memory-bandwidth bound. That is the exact bottleneck TurboQuant is built to crush.


Actual Coding! Building a Pluggable KV Cache

Instead of hiding cache tensors inside CausalSelfAttention, I put the cache in its own standalone file (kv_cache.py). That keeps weights separate from temporary per-prompt state, and better yet, it means later we can swap KVCache for TurboQuantKVCache without editing a single line of MyGPT2.py!

import torch

class KVCache:
    def __init__(self, n_layer):
        # 12 layers -> 12 empty shelves for K, and 12 empty shelves for V
        self.k = [None] * n_layer
        self.v = [None] * n_layer

    @property
    def seq_len(self):
        # How many tokens are currently stored in the cache?
        if self.k[0] is None:
            return 0
        # Tensor shape is (B, n_head, T, head_dim), so dim=2 is sequence length
        return self.k[0].size(2)

    def update(self, layer_idx, k_new, v_new):
        if self.k[layer_idx] is None:
            # Prefill: first time seeing this layer, just store them
            self.k[layer_idx] = k_new
            self.v[layer_idx] = v_new
        else:
            # Decode: glue the new token(s) onto the end of dim=2
            self.k[layer_idx] = torch.cat([self.k[layer_idx], k_new], dim=2)
            self.v[layer_idx] = torch.cat([self.v[layer_idx], v_new], dim=2)
        return self.k[layer_idx], self.v[layer_idx]

    def memory_bytes(self):
        # Exact PyTorch bytes currently stored across all layers (both K and V)
        total = 0
        for k_tensor, v_tensor in zip(self.k, self.v):
            if k_tensor is not None:
                total += k_tensor.numel() * k_tensor.element_size()
                total += v_tensor.numel() * v_tensor.element_size()
        return total

Testing kv_cache.py standalone with fake (1, 12, 4, 64) prompt tensors followed by a (1, 12, 1, 64) decode step:

start:        seq_len= 0
After prompt: shape= (1, 12, 4, 64) seq_len= 4
After 1 step: shape= (1, 12, 5, 64) seq_len= 5

Two Subtle Traps When Wiring KVCache Into MyGPT2.py

Wiring kv_cache=None through GPT2.forward → TransformerBlock.forward → CausalSelfAttention.forward only took ~20 lines, but there are two classic bugs that will silently wreck your outputs if you miss them:

  1. Position embedding offset (GPT2.forward): During decode, idx has shape (B, 1). If you still write pos = torch.arange(T), every new token gets position 0, tricking GPT-2 into thinking every generated word is the first word of the sentence! Instead, read past_len = kv_cache.seq_len before running the layer loop and offset:

    pos = torch.arange(past_len, past_len + T, device=idx.device)
  2. PyTorch SDPA rectangular causal mask (CausalSelfAttention.forward): During decode, q has length T = 1 while k has length S = past_len + 1 (e.g. 5). If you leave F.scaled_dot_product_attention(q, k, v, is_causal=True) turned on, PyTorch aligns the causal triangle to the top-left (row >= col), so your new token at row 0 can only see token 0 and masks out tokens 1..4!

    Instead, we handle all three cases cleanly:

        if kv_cache is not None:
            k, v = kv_cache.update(layer_idx, k, v)

        # Total cached keys = k.size(2), incoming queries = T
        past_len = k.size(2) - T

        if past_len == 0:
            # Prefill or no cache: square (T x T) attention, use built-in causal mask
            y = F.scaled_dot_product_attention(q, k, v, is_causal=True)
        elif T == 1:
            # Single-token decode: this token sits at the end, so it sees ALL keys
            y = F.scaled_dot_product_attention(q, k, v, is_causal=False)
        else:
            # Chunked prefill (e.g. adding 4 new tokens onto 10 cached tokens)
            q_pos = torch.arange(past_len, past_len + T, device=x.device).unsqueeze(1)
            k_pos = torch.arange(k.size(2), device=x.device).unsqueeze(0)
            attn_mask = k_pos <= q_pos  # True = allowed to attend
            y = F.scaled_dot_product_attention(q, k, v, attn_mask=attn_mask, is_causal=False)

Proving Our KV Cache Is Mathematically Exact

Because a KV cache is a pure speedup (zero approximation!), running GPT-2 with our cache must give the exact same numbers as running uncached GPT-2. I wrote test_kv_cache.py to test both 1-by-1 decoding and multi-token chunked prefill:

Test 1 (prefill + 1-by-1 decode) max diff: 0.000003
test 2 chunked prefill           max diff: 0.000002

A 0.000003 (3e-6) difference is just 32-bit floating-point rounding inside Flash Attention. Our KV cache is mathematically exact!

Running 150 tokens of greedy generation in generate.py on an RTX 4070 Super (12 GB) with OpenAI’s pretrained GPT-2 weights:

Running on: cuda
Exact token match: True
No cache:   1.106s
With cache: 1.081s  (1.02x faster)
Cache size: 11.18 MB for 159 tokens

Two neat observations from this baseline run:


Math Time! How TurboQuant Compresses the KV Cache

Now for the heart of this project: compressing those 32-bit float KV tensors down to 2–4 bits per coordinate without needing any calibration dataset!

The Problem: Outlier Channels

Why can’t we just divide each 64-dim key or value vector into evenly spaced buckets?

In real transformers, activation vectors are full of sharp outlier channels. For example, channel 0 might be 50.0 while the other 63 channels hover around 0.1. If you only have 2 bits (4 levels!) and stretch them evenly across [-50, +50], all 63 small channels get crushed straight to 0.

Step 1: Normalize + Random Orthogonal Rotation (Π\Pi)

TurboQuant solves outliers in two completely lossless operations:

  1. Normalize each 64-dim vector to length 1 (unit sphere):

    rx=∥x∥2,u=xrx+ϵr_x = \|x\|_2, \qquad u = \frac{x}{r_x + \epsilon}

    Now every vector has length 1.0, and we keep the single scalar rxr_x (stored in FP16, just 2 bytes!) so we can scale it back later.

  2. Multiply by a fixed random orthogonal matrix Π∈R64×64\Pi \in \mathbb{R}^{64 \times 64}:

    y=Πu(for PyTorch row vectors: y=uΠT)y = \Pi u \qquad (\text{for PyTorch row vectors: } y = u \Pi^T)

    Because Π\Pi is orthogonal (ΠTΠ=I\Pi^T \Pi = I), it is just a rigid rotation in 64D space; it loses zero information (u = y @ Pi undoes it exactly!).

    Here’s the magic: rotating a vector with one giant spike spreads that spike smoothly across all 64 dimensions! No matter what input vector you started with, every rotated coordinate now follows the exact same tight, symmetric Beta distribution on [−1,1][-1, 1]:

    f(t)∝(1−t2)(d−3)/2f(t) \propto (1 - t^2)^{(d - 3)/2}

    For GPT-2 (d = 64), the standard deviation of every coordinate is always σ=1/64=0.125\sigma = 1 / \sqrt{64} = 0.125.

def make_random_rotation(dim, seed=0):
    """Build a fixed Haar-random orthogonal (dim x dim) rotation matrix Pi."""
    gen = torch.Generator().manual_seed(seed)
    g = torch.randn(dim, dim, generator=gen)
    q, r = torch.linalg.qr(g)
    # Fix column signs so the rotation is uniformly random over all directions
    diag_sign = torch.sign(torch.diag(r))
    diag_sign[diag_sign == 0] = 1.0
    return q * diag_sign

def normalize_and_rotate(x, pi, eps=1e-8):
    norm = x.norm(dim=-1, keepdim=True)
    u = x / (norm + eps)
    y = u @ pi.T
    return y, norm

def unrotate_and_denormalize(y, norm, pi):
    u_back = y @ pi
    return u_back * norm

I tested this on a nasty fake GPT-2 tensor (1, 12, 4, 64) where channel 0 was set to 50.0 and the other 63 channels were ~0.1:

orthogonality error should be 0: 0.0000005
Before rotation - max |coord| of unit vector: 0.9999
After  rotation - max |coord| of unit vector: 0.3065
After  rotation - std of coords (theory 0.125): 0.1248
Round-trip error (should be ~0): 0.000023

Just like that, max |coord| dropped from 0.9999 (all energy jammed into one channel!) down to 0.3065, std hit 0.1248 (dead on the theoretical 0.125), and unrotating recovered the original 50.0 vector to 0.000023!

Step 2: Optimal Buckets With Lloyd-Max (TurboQuant_mse)

Now that every rotated coordinate comes from the exact same bell-like curve f(t)∝(1−t2)30.5f(t) \propto (1 - t^2)^{30.5}, where should we place our 2b2^b quantization levels (centroids)?

Instead of spacing them uniformly, we run the Lloyd-Max algorithm (essentially 1D weighted k-means on that exact PDF):

  1. Place each boundary halfway between neighboring centroids.
  2. Move each centroid to the probability-weighted center of mass of its bucket.
  3. Repeat 100 times!

Because GPT-2 uses head_dim = 64 across all four official sizes (gpt2 through gpt2-xl), we compute the optimal codebook once from pure math, with zero training or calibration data required!

def build_lloyd_max_codebook(dim, bits, n_iters=100):
    n_levels = 2 ** bits
    t = torch.linspace(-1.0, 1.0, 20001)
    weights = (1.0 - t ** 2).clamp(min=0.0) ** ((dim - 3) / 2.0)
    weights = weights / weights.sum()

    std = dim ** -0.5
    centroids = torch.linspace(-3.0 * std, 3.0 * std, n_levels)

    for _ in range(n_iters):
        boundaries = 0.5 * (centroids[:-1] + centroids[1:])
        bucket_ids = torch.bucketize(t, boundaries)
        for k in range(n_levels):
            mask = bucket_ids == k
            w_k = weights[mask].sum()
            if w_k > 0:
                centroids[k] = (t[mask] * weights[mask]).sum() / w_k

    boundaries = 0.5 * (centroids[:-1] + centroids[1:])
    return centroids, boundaries

Quantizing is now literally torch.bucketize(y, boundaries), and dequantizing is a fast table lookup centroids[indices.long()] followed by unrotate_and_denormalize!

Testing TurboQuant_mse on our 50.0 outlier tensor across 1 to 4 bits:

Bit-widthLevelsRelative MSENorm Ratio (∥x^∥/∥x∥\lVert\hat{x}\rVert / \lVert x\rVert)
1-bit20.36190.8010
2-bit40.10210.9361
3-bit80.02620.9981
4-bit160.00841.0283

Every extra bit slashes squared error by almost 4×4\times (matching the O(4−b)O(4^{-b}) theoretical rate in the TurboQuant paper!). At 4 bits we keep over 99% reconstruction accuracy even with a huge 50.0 outlier.

Wait, look closely at the Norm Ratio column at 1-bit (0.8010) and 2-bit (0.9361)! MSE-optimal quantizers pull vectors slightly toward the origin, making reconstructed vectors shorter than the originals.

Step 3: Fixing Inner-Product Bias With 1-Bit QJL (TurboQuant_prod)

For Values (V), TurboQuant_mse is already optimal. For Keys (K), attention computes dot products ⟨q,k⟩\langle q, k \rangle before softmax, so if keys shrink toward zero, every dot product ⟨q,k^⟩\langle q, \hat{k} \rangle is systematically underestimated (biased!).

TurboQuant’s TurboQuant_prod fixes this with a clever two-stage split of a bb-bit budget:

  1. Spend b - 1 bits on TurboQuant_mse to get k^mse\hat{k}_{\text{mse}}, and compute the leftover residual error:

    r=k−k^mser = k - \hat{k}_{\text{mse}}
  2. Spend the last 1 bit on a Quantized Johnson-Lindenstrauss (QJL) sketch of rr: multiply rr by a fixed random Gaussian matrix S∈R64×64S \in \mathbb{R}^{64 \times 64} (Sij∼N(0,1)S_{ij} \sim \mathcal{N}(0, 1)) and save only the +1 / -1 signs z=sign(Sr)z = \text{sign}(S r) plus the residual’s norm ∥r∥2\|r\|_2.

  3. Reconstruct an unbiased key estimator:

    k~=k^mse+π/2d ∥r∥2 (STz)\tilde{k} = \hat{k}_{\text{mse}} + \frac{\sqrt{\pi / 2}}{d} \, \|r\|_2 \, (S^T z)

Why π/2\sqrt{\pi / 2}? Because throwing away magnitudes and keeping only ±1\pm 1 signs of standard Gaussian projections shrinks the expected value by E[∣g∣]=2/π≈0.7979\mathbb{E}[|g|] = \sqrt{2 / \pi} \approx 0.7979. Multiplying by its exact inverse π/2≈1.2533\sqrt{\pi / 2} \approx 1.2533 cancels the bias completely!

Testing on 2,000 correlated (q,k)(q, k) pairs (true average ⟨q,k⟩=64.1\langle q, k \rangle = 64.1):

Total BitsTurboQuant_mse BiasTurboQuant_prod (QJL) Bias
2-bit-7.339-0.106 (~70× less bias!)
3-bit-2.171-0.019 (>100× less bias!)
4-bit-0.546-0.038 (~14× less bias!)

The systematic inner-product bias practically vanished!


Real Bit-Packing: Actually Shrinking GPU VRAM

Up to this point, PyTorch doesn’t have native 2-bit or 3-bit dtypes, so storing 2-bit bucket IDs inside uint8 tensors wastes 6 of every 8 bits! To get real VRAM savings (not just theoretical math), I built bitpack.py.

Here is how 4-bit packing works inside a single uint8 byte (a = 11 = 1011, b = 6 = 0110):

Unpacked (2 bytes):   [0 0 0 0 | 1 0 1 1]   [0 0 0 0 | 0 1 1 0]
                       ^^^^^^^ wasted!       ^^^^^^^ wasted!

Packed   (1 byte):    [0 1 1 0 | 1 0 1 1]   =   a | (b << 4)
                       ^^^ b ^^^ ^^^ a ^^^

Because GPT-2’s head_dim = 64 is divisible by 8, every bit-width packs cleanly with zero wasted padding:

Running bitpack.py on a (1, 12, 100, 64) tensor (300.0 KB in FP32):

Original FP32 tensor: 300.0 KB

1-bit | exact round-trip: True | packed shape: (1, 12, 100, 8)  | real size:   9.4 KB (32.0x smaller than FP32)
2-bit | exact round-trip: True | packed shape: (1, 12, 100, 16) | real size:  18.8 KB (16.0x smaller than FP32)
3-bit | exact round-trip: True | packed shape: (1, 12, 100, 24) | real size:  28.1 KB (10.7x smaller than FP32)
4-bit | exact round-trip: True | packed shape: (1, 12, 100, 32) | real size:  37.5 KB (8.0x smaller than FP32)

Every single bit-width round-trips losslessly (exact round-trip: True) and genuinely shrinks allocated PyTorch memory.


Putting TurboQuant Inside GPT-2: Surprises & Trade-Offs!

Because TurboQuantKVCache exposes the exact same seq_len, update(), and memory_bytes() methods as our uncompressed KVCache, it dropped straight into MyGPT2.py with zero changes to the transformer.

I also added a sink_tokens parameter inspired by StreamingLLM: transformers pour huge baseline attention mass onto the very first few tokens of a prompt (attention sinks), so keeping just the first 4 tokens in FP16 protects them from quantization noise for almost zero extra memory.

Here is the real benchmark (test_turboquant_gpt2.py) on pretrained GPT-2 124M across a 308-token passage (64-token prefill, 244 next-token predictions, real allocated GPU bytes):

Configsink_tokensPPLΔ\DeltaPPLKL vs. FP32Top-1 MatchReal Cache Sizevs. FP32
4-bit MSE only0114.69+1.740.031386.9%2,935.7 KB7.5×
4-bit MSE only4117.45+4.500.033188.9%3,041.4 KB7.3×
4-bit Prod (QJL)0136.16+23.210.200869.7%3,022.0 KB7.3×
4-bit Prod (QJL)4138.39+25.440.194275.0%3,126.7 KB7.1×
3-bit MSE only0133.23+20.280.164673.0%2,244.9 KB9.8×
3-bit MSE only4129.43+16.480.134872.5%2,359.7 KB9.4×
3-bit Prod (QJL)0274.70+161.750.861745.9%2,331.3 KB9.5×
3-bit Prod (QJL)4273.28+160.330.922644.7%2,444.9 KB9.0×
2-bit MSE only0218.75+105.800.634355.7%1,554.2 KB14.2×
2-bit MSE only4220.60+107.660.591154.1%1,677.9 KB13.2×
2-bit Prod (QJL)0882.01+769.061.993524.2%1,640.5 KB13.5×
2-bit Prod (QJL)4775.78+662.831.901620.9%1,763.2 KB12.5×

*Baseline PPL is elevated because the test passage uses 2025 ML jargon (TurboQuant, prefill, attention sinks) outside GPT-2’s 2019 training set; Δ\DeltaPPL and KL isolate pure quantization drift.

The Big Surprise: Why Pure TurboQuant_mse Crushed Prod (QJL) on GPT-2!

Wait, didn’t QJL just cut inner-product bias by 100×?! Why did MSE only beat Prod (QJL) across every single bit-width inside real GPT-2?

It comes down to the classic Bias vs. Variance trade-off:

Meanwhile, 4-bit TurboQuant_mse hit +1.74 PPL (+1.5%), 0.0313 KL divergence, and 88.9% top-1 agreement (with 4 sink tokens) while shrinking real GPU cache memory from 21.59 MB down to 2.94 MB (7.5× smaller than FP32)!


Training Our Own 124M GPT-2 on 10 Billion Tokens (4× H100)

Pretrained OpenAI weights were awesome for testing TurboQuant fast and free on my local RTX 4070 Super, but the whole point of building GPT-2 from scratch is training our own weights too!

Step 1: Streaming Tokenization (prepare_data.py)

We built prepare_data.py to stream FineWeb-Edu (sample-10BT), tokenize documents using multi-threaded Rust tiktoken (encode_ordinary_batch), insert <|endoftext|> (50256) between every document, and save compact uint16 .npy shards (val_000000.npy + train_000001..99.npy, 100M tokens / 190.7 MB each).

Because uint16 takes only 2 bytes per token, all 10 billion tokens fit in ~19.1 GB.

Step 2: Multi-GPU DDP Training Loop (train.py)

We wrote train.py with every modern pretraining optimization while keeping it clean and readable:

Local Smoke Test (RTX 4070 Super)

Before spending a single dollar in the cloud, I ran a 2M-token slice (4 MB, tokenized in 2s at 820K tok/s) for 40 steps locally:

Device: cuda | bfloat16: True | compile: False
step  0 | val_loss 10.9546 | val_ppl 57215.36
step 10 | val_loss  8.3042 | val_ppl  4040.90
step 20 | val_loss  7.9602 | val_ppl  2864.66
step 30 | val_loss  7.8257 | val_ppl  2504.03
step 39 | val_loss  7.7293 | val_ppl  2273.97   (~33.5K tok/s)

Starting right near theoretical random cross-entropy (ln⁡(50304)≈10.83\ln(50304) \approx 10.83) and dropping smoothly every eval!

Full 10B Run on Lambda Cloud (4x H100 80 GB SXM5)

Once local tests passed, we spun up a 4× NVIDIA H100 (80 GB SXM5) node on Lambda Cloud (104 vCPUs, 900 GiB RAM, 11 TiB NVMe SSD, Lambda Stack 24.04):

Saved checkpoint -> checkpoints/latest.pt (next step: 501)
step   501/19073 | loss 5.1615 | lr 4.21e-04 | norm 0.91 | 286.6ms | 1,829,575 tok/s
step   502/19073 | loss 5.1573 | lr 4.22e-04 | norm 1.01 | 289.5ms | 1,811,120 tok/s
        [... steps omitted ...]
step   543/19073 | loss 5.1174 | lr 4.57e-04 | norm 1.04 | 298.4ms | 1,756,983 tok/s
step   544/19073 | loss 5.0950 | lr 4.57e-04 | norm 0.87 | 296.0ms | 1,771,113 tok/s

Over 1.75–1.83 million tokens per second (~440K tok/s per H100, roughly 33% MFU), turning a full 10-billion-token GPT-2 pretraining run into ~1 hour 37 minutes!

Final 10B Validation Curve & Checkpoints

Our validation loss dropped smoothly all the way to the very last step (step 19,072) with zero overfitting:

step     0 | val_loss 10.9522 | val_ppl 57081.17
step  1000 | val_loss  4.1406 | val_ppl    62.84
step  5000 | val_loss  3.3518 | val_ppl    28.55
step  9000 | val_loss  3.2116 | val_ppl    24.82
step 15000 | val_loss  3.1052 | val_ppl    22.31
step 19000 | val_loss  3.0723 | val_ppl    21.59
step 19072 | val_loss  3.0696 | val_ppl    21.53

GPT-2 124M FineWeb-Edu 10B training and validation loss curve

Our from-scratch model landed at val_loss = 3.0696 (val_ppl = 21.53), matching Andrej Karpathy’s 10B FineWeb-Edu GPT-2 124M benchmark (~3.07) and beating OpenAI’s released 2019 GPT-2 124M reference on FineWeb-Edu (~3.29)!

Running Our Own Trained Model Locally With 4-Bit TurboQuant

After downloading gpt2_fineweb10B.pt (1.425 GB) back to my local RTX 4070 Super, I generated text directly from our own weights using a 4-bit bit-packed TurboQuant KV cache:

python generate.py --checkpoint gpt2_fineweb10B.pt --turboquant_bits 4 --temperature 0.8
Running on: cuda
Loading custom checkpoint: gpt2_fineweb10B.pt
TurboQuant 4-bit: 3.680s for 150 tokens
Cache size: 1.59 MB for 159 tokens

--- Generated text ---
In a distant future where computers can compress memories, the information produced by a computer can be stored at a much cheaper cost. This can make the processor much more affordable.
The computer will be a lot more affordable.
The processor will be as low on the cost of a standard desktop computer as it is a low-priced mainframe.
A laptop will have to be large enough to give a much bigger memory.
The storage device will be as large as the computer.

Instead of 11.18 MB in FP32 for 159 tokens, our entire 4-bit KV cache fit in 1.59 MB (over 7× smaller real GPU memory)!

Benchmarking TurboQuant on Our Own FineWeb-Edu Weights vs. OpenAI GPT-2

Finally, I ran test_turboquant_gpt2.py --checkpoint gpt2_fineweb10B.pt on our newly trained weights (baseline FP32 PPL = 134.91, 21.59 MB for 307 tokens):

Configsink_tokensPPLΔ\DeltaPPLKL vs. FP32Top-1 MatchReal Cache Sizevs. FP32
4-bit MSE only0156.33+21.430.135474.6%2,935.7 KB7.5×
4-bit MSE only4153.81+18.900.123976.2%3,041.4 KB7.3×
4-bit Prod (QJL)0300.36+165.460.767553.3%3,022.0 KB7.3×
4-bit Prod (QJL)4324.66+189.760.775150.4%3,126.7 KB7.1×
3-bit MSE only0219.26+84.350.430065.2%2,244.9 KB9.8×
3-bit MSE only4221.48+86.570.461265.6%2,359.7 KB9.4×
3-bit Prod (QJL)0708.12+573.211.564936.1%2,331.3 KB9.5×
3-bit Prod (QJL)4615.35+480.441.480038.1%2,444.9 KB9.0×
2-bit MSE only0472.87+337.961.192843.4%1,554.2 KB14.2×
2-bit MSE only4566.77+431.861.362736.1%1,677.9 KB13.2×
2-bit Prod (QJL)0879.60+744.691.920425.0%1,640.5 KB13.5×
2-bit Prod (QJL)4893.07+758.171.895727.9%1,763.2 KB12.5×

TurboQuant KV-cache ablation comparing OpenAI GPT-2 and our FineWeb-Edu 10B GPT-2

Two really interesting takeaways from comparing both models side-by-side:

  1. The QJL variance gap reproduced independently: On our custom FineWeb-Edu weights, 4-bit QJL had 0.7675 / 0.1354 = 5.7× higher KL than 4-bit MSE, almost identical to OpenAI’s 6.4× and our theoretical ~6.3× estimate for head_dim = 64!
  2. Dropout vs. quantization sensitivity: Notice our FineWeb-Edu checkpoint was slightly more sensitive to 4-bit quantization (KL = 0.1239 vs. OpenAI’s 0.0331). A likely culprit is regularization: OpenAI trained GPT-2 for multiple epochs with 0.1 dropout (which acts like random noise injection during training and makes activations naturally more tolerant to quantization noise), whereas our single-epoch FineWeb-Edu run trained with 0.0 dropout, making sink_tokens = 4 especially helpful at 4-bit (PPL 156.33 → 153.81, KL 0.1354 → 0.1239, top-1 74.6% → 76.2%).

References & Reading That Helped Along the Way