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:
- 12 Transformer Blocks (
n_layer = 12) - 12 Attention Heads per block (
n_head = 12) - 768 Embedding Dimension (
n_embd = 768), which splits cleanly intohead_dim = 64per head () - 1024 Context Length (
block_size = 1024) - 50,257 Vocabulary Size (GPT-2’s BPE vocabulary via
tiktoken)
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):
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:
Here is a helpful mental model that makes the whole transformer click:
- Attention is the communication step: tokens look backward at earlier tokens and exchange information.
- FeedForward (MLP) is the thinking step: each token is widened (
768 → 3072), passed through GELU, and projected back (3072 → 768) completely on its own; it never looks at other tokens!
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:
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 can only attend to tokens , never to future tokens.
That means once we compute token ‘s Key () and Value () vector at layer , 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":
- Without a KV cache: To predict the word after
"the", we throw all 5 words back into all 12 layers and recompute and from scratch, only to throw away the first 4 logits and keep the last one. By token 500, we are redoing 499 tokens of work every single step! - With a KV cache: Generation splits into two phases:
- Prefill (1 pass): Run the entire prompt
(B, T_prompt)in parallel. Save each layer’sKandVtensors in memory, and use the last logit to pick the first new token. - Decode (loop, 1 token per pass): Feed only the single newest token
(B, 1). Compute just itsq_new,k_new,v_new, gluek_newandv_newonto the cached history, and letq_newattend to everything saved so far!
- Prefill (1 pass): Run the entire prompt
Two quick intuition checks that really helped me:
- Why don’t we cache Queries (
Q)? Past tokens never attend to future tokens, so their queries are never needed again. Only the newest token asks “which past tokens matter to me?” - Why don’t we cache
LayerNormorFeedForward? Because both are strictly token-wise! During decode, they automatically run on just the single(B, 1, 768)token, so we skip recomputing the MLP for every old token too.
The Memory Math Behind KV Caches
In our CausalSelfAttention, every layer stores k and v with shape:
For GPT-2 124M in float32 (4 bytes per number), every single token costs:
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:
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:
-
Position embedding offset (
GPT2.forward): During decode,idxhas shape(B, 1). If you still writepos = torch.arange(T), every new token gets position0, tricking GPT-2 into thinking every generated word is the first word of the sentence! Instead, readpast_len = kv_cache.seq_lenbefore running the layer loop and offset:pos = torch.arange(past_len, past_len + T, device=idx.device) -
PyTorch
SDPArectangular causal mask (CausalSelfAttention.forward): During decode,qhas lengthT = 1whilekhas lengthS = past_len + 1(e.g.5). If you leaveF.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 row0can only see token0and masks out tokens1..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:
11.18 MBmatches our formula to the hundredth of a megabyte (159 × 73,728 B = 11.18 MB).- Why was it only
1.02×faster atB = 1, T = 159? On a fast RTX 4070 Super, a tiny 124M model atB = 1finishes the actual GPU math almost instantly. Most of that1.08s(~7 ms/token) is Python overhead launching small CUDA kernels + callingtorch.cateach step. At larger batches or longer contexts (T = 700–1024), the uncached compute blows past launch overhead and the KV cache pulls far ahead. - Also, greedy
argmaxgeneration falls into hilarious repetition loops ("We're still in the early stages of development..."over and over), a classic phenomenon explored in Holtzman et al.’s The Curious Case of Neural Text Degeneration. We keptargmaxfor deterministic equivalence testing and added optional--temperature+--top_ksampling togenerate.pyfor natural text.
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 ()
TurboQuant solves outliers in two completely lossless operations:
-
Normalize each 64-dim vector to length 1 (unit sphere):
Now every vector has length
1.0, and we keep the single scalar (stored in FP16, just 2 bytes!) so we can scale it back later. -
Multiply by a fixed random orthogonal matrix :
Because is orthogonal (), it is just a rigid rotation in 64D space; it loses zero information (
u = y @ Piundoes 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 :
For GPT-2 (
d = 64), the standard deviation of every coordinate is always .
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 , where should we place our quantization levels (centroids)?
Instead of spacing them uniformly, we run the Lloyd-Max algorithm (essentially 1D weighted k-means on that exact PDF):
- Place each boundary halfway between neighboring centroids.
- Move each centroid to the probability-weighted center of mass of its bucket.
- 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-width | Levels | Relative MSE | Norm Ratio () |
|---|---|---|---|
| 1-bit | 2 | 0.3619 | 0.8010 |
| 2-bit | 4 | 0.1021 | 0.9361 |
| 3-bit | 8 | 0.0262 | 0.9981 |
| 4-bit | 16 | 0.0084 | 1.0283 |
Every extra bit slashes squared error by almost (matching the 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 before softmax, so if keys shrink toward zero, every dot product is systematically underestimated (biased!).
TurboQuant’s TurboQuant_prod fixes this with a clever two-stage split of a -bit budget:
-
Spend
b - 1bits onTurboQuant_mseto get , and compute the leftover residual error: -
Spend the last
1bit on a Quantized Johnson-Lindenstrauss (QJL) sketch of : multiply by a fixed random Gaussian matrix () and save only the+1 / -1signs plus the residual’s norm . -
Reconstruct an unbiased key estimator:
Why ? Because throwing away magnitudes and keeping only signs of standard Gaussian projections shrinks the expected value by . Multiplying by its exact inverse cancels the bias completely!
Testing on 2,000 correlated pairs (true average ):
| Total Bits | TurboQuant_mse Bias | TurboQuant_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:
- 1-bit (QJL signs): 8 values per byte →
64dims becomes8bytes - 2-bit: 4 values per byte →
64dims becomes16bytes - 3-bit:
3doesn’t divide8, but8 × 3 = 24 bits = 3 exact bytes! We pack 8 three-bit numbers into the bottom 24 bits of anint32and slice out 3uint8bytes →64dims becomes24bytes - 4-bit: 2 values per byte →
64dims becomes32bytes
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):
- Baseline FP32
KVCache:PPL = 112.95*,Size = 21.59 MB
| Config | sink_tokens | PPL | PPL | KL vs. FP32 | Top-1 Match | Real Cache Size | vs. FP32 |
|---|---|---|---|---|---|---|---|
| 4-bit MSE only | 0 | 114.69 | +1.74 | 0.0313 | 86.9% | 2,935.7 KB | 7.5× |
| 4-bit MSE only | 4 | 117.45 | +4.50 | 0.0331 | 88.9% | 3,041.4 KB | 7.3× |
| 4-bit Prod (QJL) | 0 | 136.16 | +23.21 | 0.2008 | 69.7% | 3,022.0 KB | 7.3× |
| 4-bit Prod (QJL) | 4 | 138.39 | +25.44 | 0.1942 | 75.0% | 3,126.7 KB | 7.1× |
| 3-bit MSE only | 0 | 133.23 | +20.28 | 0.1646 | 73.0% | 2,244.9 KB | 9.8× |
| 3-bit MSE only | 4 | 129.43 | +16.48 | 0.1348 | 72.5% | 2,359.7 KB | 9.4× |
| 3-bit Prod (QJL) | 0 | 274.70 | +161.75 | 0.8617 | 45.9% | 2,331.3 KB | 9.5× |
| 3-bit Prod (QJL) | 4 | 273.28 | +160.33 | 0.9226 | 44.7% | 2,444.9 KB | 9.0× |
| 2-bit MSE only | 0 | 218.75 | +105.80 | 0.6343 | 55.7% | 1,554.2 KB | 14.2× |
| 2-bit MSE only | 4 | 220.60 | +107.66 | 0.5911 | 54.1% | 1,677.9 KB | 13.2× |
| 2-bit Prod (QJL) | 0 | 882.01 | +769.06 | 1.9935 | 24.2% | 1,640.5 KB | 13.5× |
| 2-bit Prod (QJL) | 4 | 775.78 | +662.83 | 1.9016 | 20.9% | 1,763.2 KB | 12.5× |
*Baseline PPL is elevated because the test passage uses 2025 ML jargon (TurboQuant, prefill, attention sinks) outside GPT-2’s 2019 training set; PPL 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:
- Spending 1 extra bit on MSE cuts the squared error by .
- Spending that 1 bit on QJL instead leaves larger and injects random 1-bit sketch variance .
- Combined, QJL adds roughly more variance to each attention score! Look at our measured 4-bit KL ratio:
0.2008 / 0.0313 = 6.4×, matching the math almost to the exact decimal! - Because GPT-2 uses
head_dim = 64(half the128of modern Llama-3/Qwen models, doubling the variance) andsoftmaxexponentiates noisy attention scores, that extra QJL variance hurts more than MSE’s tiny ~3% bias!
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:
- Padded vocabulary (
vocab_size = 50304): Rounding50,257up to a multiple of64gives GPU Tensor Cores clean matrix dimensions (124,475,904params). bfloat16autocast + TF32 +torch.compile: Cuts activation memory in half and fuses elementwise ops on Hopper/Ada GPUs.- Weight-decay grouping: Fused
AdamW(betas=(0.9, 0.95)) applyingweight_decay = 0.1only to 2D weights and embeddings, never to biases orLayerNorms. - Linear warmup + cosine decay: Ramps
0 → 6e-4over715steps, then smoothly decays to6e-5across19,073steps (524,288tokens/step ≈10Btokens). - Lockstep DDP (
torchrun) + Atomic Checkpoints: Each GPU reads a non-overlapping slice (base_pos + rank * B * T) and rolls over shards together, syncing gradients over NVLink only on the last accumulation micro-step (require_backward_grad_sync). Checkpoints save atomically (latest.pt.tmp → latest.pt) with model, optimizer, step, and exact shard position.
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 () 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):
- Tokenizing 10B tokens: Ran at
~3.8–4.4M tokens/secacross 64 threads (~40 minutes total for all 100 shards). - 4× H100 DDP training (
B = 64/gpu, T = 1024, grad_accum = 2,524,288tok/step):
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

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):
| Config | sink_tokens | PPL | PPL | KL vs. FP32 | Top-1 Match | Real Cache Size | vs. FP32 |
|---|---|---|---|---|---|---|---|
| 4-bit MSE only | 0 | 156.33 | +21.43 | 0.1354 | 74.6% | 2,935.7 KB | 7.5× |
| 4-bit MSE only | 4 | 153.81 | +18.90 | 0.1239 | 76.2% | 3,041.4 KB | 7.3× |
| 4-bit Prod (QJL) | 0 | 300.36 | +165.46 | 0.7675 | 53.3% | 3,022.0 KB | 7.3× |
| 4-bit Prod (QJL) | 4 | 324.66 | +189.76 | 0.7751 | 50.4% | 3,126.7 KB | 7.1× |
| 3-bit MSE only | 0 | 219.26 | +84.35 | 0.4300 | 65.2% | 2,244.9 KB | 9.8× |
| 3-bit MSE only | 4 | 221.48 | +86.57 | 0.4612 | 65.6% | 2,359.7 KB | 9.4× |
| 3-bit Prod (QJL) | 0 | 708.12 | +573.21 | 1.5649 | 36.1% | 2,331.3 KB | 9.5× |
| 3-bit Prod (QJL) | 4 | 615.35 | +480.44 | 1.4800 | 38.1% | 2,444.9 KB | 9.0× |
| 2-bit MSE only | 0 | 472.87 | +337.96 | 1.1928 | 43.4% | 1,554.2 KB | 14.2× |
| 2-bit MSE only | 4 | 566.77 | +431.86 | 1.3627 | 36.1% | 1,677.9 KB | 13.2× |
| 2-bit Prod (QJL) | 0 | 879.60 | +744.69 | 1.9204 | 25.0% | 1,640.5 KB | 13.5× |
| 2-bit Prod (QJL) | 4 | 893.07 | +758.17 | 1.8957 | 27.9% | 1,763.2 KB | 12.5× |

Two really interesting takeaways from comparing both models side-by-side:
- 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’s6.4×and our theoretical~6.3×estimate forhead_dim = 64! - Dropout vs. quantization sensitivity: Notice our FineWeb-Edu checkpoint was slightly more sensitive to 4-bit quantization (
KL = 0.1239vs. OpenAI’s0.0331). A likely culprit is regularization: OpenAI trained GPT-2 for multiple epochs with0.1dropout (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 with0.0dropout, makingsink_tokens = 4especially 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
- Vaswani et al., Attention Is All You Need
- Andrej Karpathy, Let’s reproduce GPT-2 (124M)
- Sebastian Raschka, Understanding and Coding the KV Cache in LLMs from Scratch
- PyTorch Team, Accelerating Generative AI with PyTorch II: GPT, Fast
- kipply, Transformer Inference Arithmetic
- Holtzman et al., The Curious Case of Neural Text Degeneration
- Xiao et al., Efficient Streaming Language Models with Attention Sinks
- Zandieh et al., TurboQuant: Online Vector Quantization with Near-optimal Distortion Rate
- Zandieh, Daliri, Han, QJL: 1-Bit Quantized JL Transform for KV Cache Quantization with Zero Overhead
- Han et al., PolarQuant: Quantizing KV Caches with Polar Transformation
- Hugging Face, FineWeb-Edu Dataset