Can a language model live in a CPU cache?
Why I built a tiny, from-scratch language model that writes emails inside your browser tab, how a language model is built step by step, and how every step maps onto the hardware it runs on. Animated, measured, and technical.
The question
What if the model lived where the arithmetic is?
A language model writes one word at a time, and to write each word it has to read every one of its weights. So the speed limit is rarely the arithmetic. It is how fast the weights can be fetched.
Cerebras has a beautiful answer: build a chip the size of a dinner plate with tens of gigabytes of on-chip memory, keep the whole model on it, and the bottleneck disappears (the Cerebras idea; this project is inspired by it and not affiliated with them).
I kept wondering what a tiny version of that looks like on hardware I already own. Your CPU has on-chip memory too, called cache: a megabyte or two of L2 per core, and from 4 to 96 MB of shared L3. No useful language model fits in there. Unless you build one that does.
On the my laptop (Ryzen 5 2500U, 4 MB of L3): 1M fits · 4M fits · 12M spills · 21M spills · 40M spills
Model sizes are the packed weights of the trained models (the file the engine loads). Cache sizes are the CPU's.
So that became the experiment: make language models small enough to live in a CPU cache, write an engine that runs them flat out, and measure how fast they go, in a browser tab, on whatever CPU someone has. The leaderboard on this site is the measuring stick, and this document is the lab notebook.
A warning up front: the quality is low, and that is the price of fitting in a cache. These models write plausible short emails and then make mistakes: filler sentences, a swapped detail, nonsense on unusual requests. The question was always how fast, not how smart. A good part of this document is about getting the smart part as far as it would go anyway.
How to read this
- Part I (this part) is the idea, and a tour of the CPU: where numbers live and how far they have to travel.
- Part II builds the model in seven steps, in the order I did them: the job, the words, the architecture, the number formats, the data, the training, and the loop of fixing what is wrong.
- Part III takes the trained model and makes it run fast on a CPU, one layer of the machinery at a time, from the bits of a weight to threads sharing a cache.
- Part IV has the results, two experiments that did not pay off, and where I stopped.
- Every figure with ▶ is animated and every chart with buttons is interactive. All the timings were measured on the laptop that built this project; the code is in the repository.
A tour of the hardware
Caches, cache lines, vector registers and cores: the parts of a CPU that decide how fast a model runs.
Everything in the rest of this document happens on a few square centimetres of silicon, and the shape of that silicon explains most of the speed. This chapter is a short tour of the parts that matter: where numbers live, how far they have to travel, and what a “vector instruction” is. All the numbers are measured on the laptop that built this project (an AMD Ryzen 5 PRO 2500U: 4 cores, 8 hardware threads, 512 KB of L2 per core, 4 MB of L3).
The floor plan
Each core has two hardware threads that share its execution units, its L1 and its L2. Everything above the dashed line is on the same piece of silicon. Latencies are the pointer-chase measurements below; the 19 GB/s is from the streaming benchmark in the memory-staircase chapter.
A load, from the core to RAM
When a program reads a value, the hardware looks in the nearest, smallest store first and moves outward until it finds it. Step through the trip. The time shown for each level is a measured dependent-load latency on this machine, not a datasheet figure.
The latency staircase, measured
To measure latency honestly you need loads that cannot overlap. The benchmark builds a random cycle through N cache lines, so the address of the next load is the value read by the last one, and times how long a lap takes. As the cycle outgrows each cache level the time per load climbs in steps:
1.7 ns in L1, about 4 ns across most of L2, climbing to 10–26 ns through the L3 and to 90–120 ns in RAM: roughly a 70× gap between the nearest and the farthest level. Hover the dots for exact values. (Source: explore/kernels/latency.mjs.)
Memory moves in lines, not bytes
Latency is half of the story. The other half is that the CPU never fetches a single byte: memory is organised in 64-byte cache lines, and a line is the smallest unit that travels. How you lay out your data decides whether those 64 bytes are all useful or 63 of them are wasted.
One instruction, sixteen numbers
The other idea that changes everything is SIMD (single instruction, multiple data). A vector register is a wide box divided into lanes; a vector instruction does the same thing to every lane at once.
The rest of the document is about arranging the model so that those sixteen lanes are always busy with useful work, and so that the numbers they need are already in a cache when they ask. Part III shows exactly how. First, though, the model has to exist.
Step 1 · Shrink the problem
A narrow job, four rules, and a pipeline where the clever part is not the model.
The first decision was not about neural networks at all. It was about how small the task could be. A general chatbot needs billions of parameters, because the space of things it might be asked is the space of everything. “Write email to john saying that is all good” has a tiny space: a short email, a name, one fact. A few million weights can do that, if you are clever about what you ask them to remember.
I set myself four rules. Cache-sized: 0.6 to 12.6 MB of weights. Built from scratch: my own tokenizer, model, training loop and inference engine, no llama.cpp and not even Microsoft’s bitnet.cpp. No GPU, no server: inference happens in a static web page. And a narrow job: turn a one-line request into a short, friendly email.
The clever part is the second box. A small model cannot memorise names, dates and amounts, so it never sees them: a small parser lifts them out of your request and leaves placeholders. The model learns where a name goes in a sentence, not what the name is, and afterwards the page puts your real values back. That one decision is what makes a model with a few million weights dependable on real input, and it shapes everything after it: the vocabulary (next step), the training data (step 5) and the bugs (step 7).
Step 2 · Words to numbers
A fixed list of whole words, a parser, and an embedding table.
A neural network can only do arithmetic on numbers, so the first job is to turn text into numbers in a way the network can learn from. In a big model this is a subtle subject (sub-word tokenizers, byte-pair merges). Here it is deliberately simple, because the whole model has to fit in a cache: a fixed list of whole words, plus a trick for everything else. Type your own request and watch the real tokenizer work.
Why whole words?
Most chat models split text into sub-word fragments: roughly 30,000 to 100,000 of them, so that any string at all can be represented. That is the right trade for a model with billions of weights. For a model of a few million it is the wrong one, for two reasons that come straight from the hardware:
- The vocabulary is on the critical path of every token. The final layer computes one score per entry (the “logits”). With 3,596 words that is 3,596 dot products. With 32,000 it would be nine times the work and the table alone would be larger than the whole 4M model. The profile later in this document shows the vocabulary step already costing a quarter of a small model's time.
- Whole words make short sequences. One token per word, not three. Short sequences mean fewer tokens to read before the first word (time to first token), fewer to write, and a smaller key/value cache.
What about the words that are not in the list?
Three fallbacks keep the vocabulary small without losing information. A word that is rare but known to the request (“gazebo”) travels as a copy slot: the parser replaces it with <WORD_1> and the page puts it back. A word the model has never seen and that is not in the request is spelled out one character at a time between start and end markers, which is slow but always possible. And names are placeholders (<NAME_1>), so the model needs one embedding row for “a person” instead of thousands of names.
Why int8 rows: the embedding table is stored as one byte per number with a per-row scale. It is also reused, unchanged, as the matrix that scores the next word (the output layer is “tied” to the input), which is why it earns its place in the 4M model's 1.9 MB.
Step 3 · The architecture
One loop, one stack of identical layers, and where every step sits.
Before taking the machine apart, here is the whole thing in one picture. A language model like this one is a loop: take the latest token, push it through a stack of identical layers, turn what comes out into a word, and repeat. This is the loop's journey for a single token, with the size and number format of every step, and (from the profiler) how much of the time each step takes on a real CPU. Pick a model and step through.
- 1Embedding lookup
- 2RMSNorm + int8 quantise 3%
- ↓ stages 2 to 9 repeat once per layer (8×) ↓
- 3QKV projection 16%
- 4RoPE + write the KV cache
- 5Attention 13%
- 6Output projection + residual 5%
- 7RMSNorm + quantise (again)
- 8Gate and up projection + SwiGLU 24%
- 9Down projection + residual 10%
- ↓ after the last layer ↓
- 10Final norm + vocabulary scores 25%
- 11Sample the next token 0%
Time shares are from the browser profiler on short real emails, one thread (the “other” 5 to 10% of a token is timers, loop and bookkeeping). A ternary layer's weights take two bits each: this model's 8 layers hold 11.8 million of them, 2.95 MB.
What the model is, in one paragraph
A stack of 8 identical blocks. Each block has two sub-layers: attention, which lets the current word gather information from the words before it, and a feed-forward network, which transforms each word on its own. Both add their result back onto a running vector (“residual connection”), so information can flow past a block untouched; this is what lets deep stacks train. Between them, a normalisation keeps the numbers in a reasonable range. At the very top the vector becomes a score for every word. That is all a transformer is. Everything else in the field, from chatbots to image models, is this idea scaled, tweaked or pointed at a different kind of data.
What this project changes is the number format inside the blocks. In an ordinary model every weight is a 16- or 32-bit decimal number, and each of the matrix multiplications above is millions of real multiplications. Here the four big matrices of each block are ternary, which the next section explains.
The loop that decides the speed
To write an email the model produces one token, feeds it back in, and produces the next. Every step of that loop runs the whole network again, which means every step reads all of its weights again. This single fact is the reason caches matter:
The model is a small decoder-only transformer: 4 to 10 layers, 128 to 640 numbers wide, with rotary positions, RMSNorm, a SwiGLU feed-forward block and a 256-token context. The next step is what makes the weights small.
Step 4 · Weights of 1.58 bits
Three number formats, bit by bit, and the idea that makes the model small.
Every number in a neural network lives in memory as bits, and how many bits you give it decides how much memory the model needs and how much work the CPU does to use it. This project uses three formats at different places, and the whole idea hangs on the third. Drag the slider to change one weight and watch the same value in all three.
= 0.0173000
back: 37 ÷ 127 × 0.06 = 0.0175
error 1.8e-4
stored as 10 (the weight plus one)
back: 1 × 0.02 = 0.0200
error 0.0027
A single ternary weight is a terrible approximation (see the error). The trick is that there are millions of them and the network is trained knowing it can only use these three values, so the layers learn to compensate (the training chapter).
What it costs in memory
The 21M model has about 21 million weights. Here is what they weigh in each format. The embedding table (3,596 words × 512 numbers) is int8 in all of the compact versions and adds 1.8 MB.
Compare with the CPU in the memory-staircase chapter: a laptop's L2 cache is 0.5 MB per core and L3 is 4 MB. Only the ternary column has any chance of fitting.
The three formats, and where each is used
- float32 for training, for the norm scales, and for the handful of numbers that must be precise (the RMSNorm gain, rotary tables, the softmax inside attention).
- int8 for the activations entering each matrix multiply (the int8 chapter), the embedding table, and optionally the KV cache (the KV-cache chapter). Eight bits is the sweet spot because CPUs have fast 8-bit dot-product instructions.
- ternary for nearly every weight of the transformer layers. This is what lets 21 million of them sit in 5 MB, and what turns multiplication into add, subtract or skip.
The format of the weights and the activations do not have to match. The multiply of a ternary weight by an int8 activation is exact in integers: a 16-bit lane is plenty, and the one floating-point multiply per output (the scale) happens after the sum. That is why the engine's output is bit-identical between the scalar C version and every SIMD version.
Ternary in motion
Following the BitNet b1.58 recipe, nearly every weight is −1, 0 or +1 (ternary). That is about 1.58 bits of information per weight, so four of them pack into one byte and “multiplying” by a weight becomes adding, subtracting or skipping, which a CPU does very well:
Training such a network is not obvious (a ternary weight cannot take a small step), and that comes in step 6. First, the data the network will learn from.
Step 5 · The data
Teaching it with other models’ homework, and making the examples match what the browser will see.
My first plan was the Enron email corpus: real emails, redact the names, invert each into an instruction. It gave me stiff corporate prose, instructions that did not match the emails, and a model that was cheerfully off-topic. So I switched to synthetic data from a bigger model, through OpenRouter, which lets you pick the cheapest model that is good enough. I settled on Ling 3.0 Flash, at around two cents per million tokens.
Two lessons cost real money. Ling quietly spends thousands of hidden “reasoning” tokens per answer unless you switch that off. And reusing HTTP connections per thread, instead of opening a fresh one per request, was worth about a 9× speed-up. With both fixed, a few dollars of credit buys hundreds of thousands of raw pairs. The master file now holds 577,637 of them, organised by the generator that made each batch, so every training set can be rebuilt from it.
The second stage matters most: the request side of every pair is produced by the same parser that runs in your browser, and the email is written from the placeholder request only. The model is therefore trained on exactly the input it will get at run time.
Step 6 · Training
How a network is trained when its weights may only be −1, 0 or +1.
If every weight must be −1, 0 or +1, how do you train them? Gradient descent needs to nudge a weight by a tiny amount, and a ternary weight cannot move by a tiny amount. The standard answer (BitNet, and this project) is to keep two copies of every weight and use them for different jobs.
A normal float32 number, updated by the optimiser by small steps. It is a vote, kept only during training. The 12M model has 12 million of them: 48 MB, not the 4.4 MB you download.
The latent weight, rounded: round(w / g) clamped to −1, 0, +1, where g is the average |w| of the whole matrix. This is what the forward pass uses, and what gets exported.
The straight-through estimator
Rounding has a problem: its slope is zero almost everywhere, and infinite at the jumps. Back-propagation multiplies by that slope, so no gradient would ever reach the latent weight and nothing would learn. The fix is a deliberate lie. In the forward pass, use the rounded value. In the backward pass, pretend rounding was the identity function and let the gradient straight through. It is one line of PyTorch:
The .detach() hides the difference from the gradient: the value is the ternary weight, the derivative is that of w. The same line, applied to the activations, trains the network to expect int8 rounding. Watch what it does to one weight, and what happens without it:
One weight, loss (t·g − 0.8g)², cosine learning-rate decay like the real trainer. With the estimator the latent weight climbs past the 0.5 threshold, flips to +1, overshoots the target, and is pulled back: it dithers around the threshold until the shrinking learning rate lets it settle. Without it the gradient is exactly zero and the weight never moves.
What the toy gets right about the real thing
- Weights flip near thresholds. In a real network, many latent weights sit close to ±g/2 and change their ternary value over and over while the learning rate is high. This is why the trainer uses a cosine decay down to 5% of the peak, and why loss keeps falling in the last stretch even though the average weight barely moves.
- The scale g is recomputed from the weights each step (mean of |w|, with a small floor). It is one number per matrix, so it adds nothing to the model size, and it is what the engine multiplies by at the end of each matvec.
- Embeddings and norms stay precise. The 3,596 × d embedding table is int8 after training and tied to the output layer; RMSNorm gains stay float. Rounding these to ternary hurts far more than it saves.
- Mixed precision on the GPU. The matmul runs in bfloat16 on the GPU even though the ternary values are exact in it. The point of ternary here is memory and CPU speed at inference time, not faster training.
- Validation loss versus emails. The loss is measured with ternary weights and int8 activations, i.e. exactly as the engine will run them. I still found the loss a poor guide to how good an email was (step 7 of this document), which is why the grades there were done by hand.
Where the training runs
Training happens on RunPod: a rented GPU for 20 to 35 cents an hour, used for under an hour per run. A launcher does the boring parts every time: create a pod, check that the GPU genuinely works, upload the data once, start training, poll, download, and always delete the pod, even when something crashes.
Renting from a marketplace is a lottery, and the launcher grew a scar for each loss. One host’s GPU drivers were broken. One never answered SSH. One accepted the connection and then could not finish uploading 12 MB, three times running. Three jobs on one 24 GB card ran out of memory, so now it is one job per pod. Each of those is now a retry instead of a wasted hour.
A chart taught me something counter-intuitive. On the first dataset, validation loss bottomed out after about six passes and then got worse as the model started memorising. “Train it for longer” was the wrong instinct, and it stayed wrong: later I trained the 12M model six times longer and the loss came down nicely while the emails did not get better. The fix was never more steps. It was better data.
Step 7 · Fix what is wrong
Every failure became a dataset, and the only measurement I trusted was reading emails.
The loop that actually improved the model was dull and effective. Try to break it, name the failure, generate data aimed at exactly that, retrain, then read the results by hand.
| Version | What went wrong | What I changed |
|---|---|---|
| v1 | Enron-era data: off-topic, invented details, long waffle. | Synthetic, two-stage, filtered “faithful” pairs: short, friendly, only the facts given. |
| v2 | Recipients that were not first names (“the team”, “my landlord”) left an unfilled <NAME_1>. Rare words were swapped for common ones (“the gazebo” became “the doctor”). | A second dataset of edge cases (titles, groups, negations, conditions) and copy slots for rare words. |
| v3–v5 | “Hi john that’s great thanks” was not recognised as addressed to John. “tell mike …” lost Mike, who had leaked into the vocabulary as an ordinary word. | Ten request styles, family words, a discovered-names list, parser fixes. Four sizes trained (1M, 4M, 21M, 40M). |
| v6–v7 | Typos broke the parser. “Ask X to …” sometimes did not ask. Business jargon and negative or firm tones were thin. | Typo and shorthand noise in the data, a fuzzy matcher in the parser, “asks” and hard-tone batches, business vocabulary. |
| v8–v9 | Temperature 0.7 was too wild for the small model. Longer training and bigger models lowered the loss but not the mistakes. | Default to 0.5, a 12M middle size, and hand grading on a fixed bank of requests. |
| v10 | “Tell Dave it works” and “can you tell Dave it works” need opposite readings, and several-sentence requests lost information. | 14,000 pairs for the second-person rule with a filter that rejects the wrong reading, and 12,000 multi-sentence pairs. |
Two things surprised me. First, some of the biggest gains were free: fixing the parser and the decoder, with no retraining, raised the share of emails I would send as they came from 38% to 46% on the 4M model and from 44% to 53% on the 21M. Second, validation loss was a poor guide. Models with nearly identical loss wrote clearly different emails, so the only measurement I trusted was reading twenty hard requests and giving each an A (send it), B (small fix) or C (wrong).
One sample per request, graded by me, not blind: read it as a direction, not a measurement. The v10 models fixed the “tell Dave” readings; the 80k-step 12M did no better than the 40k one.
The v10 models fixed the “tell Dave” readings that older ones got wrong, and the v10 21M was the best of the set, at 17 of 20 sendable. They also learned a new habit: a little extra filler. I also tried teaching the model from its own mistakes with preference tuning (ORPO). It did not help, so it never shipped. That is the model. Part III is about running it.
Packing the weights
The interleaved layout, and why it makes unpacking free of shuffles.
A ternary weight needs two bits, so four of them fit in a byte. How you choose which four share a byte is a design decision with a measurable cost, because the CPU has to take them apart again for every multiply. Step through the two layouts below. They store exactly the same information.
The real code
This is the layout comment from the engine, and the whole unpack, in full. The four planes come from wasm_u16x8_shr by 0, 2, 4 and 6 followed by a bitwise AND with 3. WebAssembly has no 8-bit shift that a typical x86 CPU can do in one instruction, so the shift is done on 16-bit lanes and the mask removes the bits that leaked in from the neighbouring byte:
w0 = p & 3 → weights of x[ 0..15]
w1 = (p >> 2) & 3 → weights of x[32..47]
w2 = (p >> 4) & 3 → weights of x[64..79]
w3 = (p >> 6) & 3 → weights of x[96..111]
Seven instructions (3 shifts, 4 ands) turn 16 bytes into four vectors of 16 weights each, ready to be multiplied against four contiguous loads of the activations. There is no shuffle, no table lookup and no temporary buffer: the unpacked weights exist only in registers and never touch memory. The dot-product chapter shows what happens to them next, and an experiment later in this document measured how much of the total time these seven instructions cost (about 15%).
Why 128 and why this stride
- 128 inputs = 32 bytes = exactly two 16-byte loads, so the inner loop has no remainder handling for any layer width that is a multiple of 128 (all of ours are: 256, 384, 512, 640, 768, 1024).
- The stride (32) is the number of bytes in the block, so slot k of byte b is input b + 32k: the unpacked vectors come out in memory order.
- The weights are stored row by row, so a matrix-vector multiply streams through the file once, in order. The hardware prefetcher loves this.
The dot product, one instruction at a time
Lanes, 16-bit sums and the “plus one” trick, with relaxed and plain SIMD side by side.
This is the heart of the engine: the loop that runs for every layer of every token. A row of ternary weights is dotted with a vector of int8 activations. The CPU does it 16 values at a time, so the explanation is really about lanes: 16 byte-wide slots in a 128-bit register, all doing the same thing in lockstep.
(One group is shown; the real kernel repeats this for every 16 bytes of the row and for four rows at a time, so each activation load is used four times.)
Why the “plus one”?
The natural thing would be to store the weights as −1, 0, +1 and multiply. But the instruction that makes this fast (pmaddubsw on x86, behind WebAssembly's relaxed_dot) multiplies an unsigned 7-bit number by a signed 8-bit one. Signed weights would not fit. Shifting the weights up by one gives 0, 1, 2, which fit trivially, and the error is a constant per output row that can be removed with one subtraction:
Σ x is the same for every output row of a layer, so it is computed once while the activations are quantised (the int8 chapter). The correction costs one scalar subtraction per output.
Relaxed versus plain SIMD: side by side
WebAssembly has two ways to do this multiply-and-add. The plain SIMD128 way widens 8-bit lanes to 16 bits (once for the low half, once for the high half), multiplies, and adds. The relaxed way has one instruction that does the lot, but its exact behaviour is allowed to differ between CPUs (here it cannot, because the inputs are in range, so the results are identical).
pmaddubsw.Same weights, same activations, identical outputs. The matmuls are about half of a token (the profiling chapter), which is why the visible win in a full email was around 20% and not 2×.
Squeezing activations to int8
Absmax scaling and a float-bit trick for rounding in two instructions.
Everything the ternary weights touch has to be an 8-bit integer, but the values coming out of a layer are floats. So before every matrix multiply there is a small step that squeezes one token's vector into int8. It runs 4 to 7 times per layer per token, so even though it is cheap per call, it adds up, and it is a nice place to see how a floating-point number is really just bits.
Why a scale per token, not per layer?
If one fixed scale were used for the whole layer, a token with unusually big values would clip and a token with small values would waste most of its 256 levels. A scale per token adapts, at the cost of computing one maximum. The remaining weakness is the outlier: if one channel is 12 times bigger than the rest (it happens at the input of the feed-forward down-projection) the other channels only use a few of their 256 levels. The Hadamard chapter is about fixing that.
Rounding with the float's own bits
The expensive-looking part of the loop is “round to nearest integer, then convert float to int”. In WebAssembly SIMD that is f32x4.nearest then i32x4.trunc_sat_f32x4. The second one must handle NaN and overflow, and the browser's compiler has to emulate that on x86, turning one instruction into around ten. There is a way to get both jobs from a single ordinary floating-point addition:
Floats between 2²³ and 2²⁴ have no fractional bits at all: the spacing between neighbours is exactly 1. So adding 1.5×2²³ forces the CPU to round v to the nearest whole number (to even on a tie, which is the IEEE default) and leaves that integer sitting in the low mantissa bits. Read them back as an integer, subtract the constant's bit pattern, and you have the rounded value. Two instructions, no special cases. Try it:
Side by side
The trick only works for |v| < 2²², and the values here are at most 127 after scaling, so it is exact. Measured with the standalone microbenchmark in explore/kernels/membench.mjs.
The memory staircase
Measured bandwidth at every cache level, and why one thread is not memory-bound.
The premise of the whole project is that the weights fit in a cache. But what does that buy you? Here is the measurement the premise needs. A WebAssembly loop reads a block of memory over and over, summing it with SIMD, and the block grows from 4 KB to 64 MB. Whenever the block outgrows a cache level, the speed falls off a cliff.
Dashed lines: the packed weights of the 4M, 12M and 21M models. Each point is the best of 7 timings. The two lines come from the same harness in explore/kernels/membench.mjs.
Three things the staircase says
1. The cliffs are where the textbook says
The curve steps down at 32 KB (L1 data cache), around 512 KB to 2 MB (L2, 512 KB per core here, with some help from the prefetcher), and at 4 MB (L3). Beyond that the loop is reading from RAM at roughly 19 GB/s, a quarter of the L1 speed. The 4M model's 1.9 MB of weights sits comfortably in L2/L3. The 21M model's 7.1 MB does not fit this laptop's L3 and lives in RAM. That is the premise, measured.
2. But one thread is nowhere near the limit
The orange line is the actual ternary matvec kernel on matrices of the same total size. It consumes weights at a steady 8 to 9 GB/s, flat from 4 KB to 2 MB, then dips only once the matrix is bigger than the L3. That is about one tenth of what L1 can deliver and an eighth of L2. A single thread is compute-bound: it spends its time unpacking and multiplying, not waiting for memory. So caches do not make one thread faster. Why then does the project care?
3. Because threads add up
Each thread consumes ~8.5 GB/s. Two threads need 17 GB/s, four need 34 GB/s, eight 68 GB/s, and the RAM interface is a single shared resource. Single-threaded RAM reads topped out at 19 GB/s here, and the memory controller can serve somewhat more with several readers, but not four times as much. Once a model lives in RAM, adding threads stops helping long before the cores are used up; once it lives in L2/L3 (each core has its own L2 and a bigger aggregate bandwidth), it keeps scaling. That is the hypothesis, now with a mechanism:
Red line: what one thread reads from RAM on this machine (19 GB/s). Bars beyond it are demand a model living in RAM could not sustain with one reader; models in L2/L3 are not limited by this line. The threads chapter shows the actual scaling.
Attention and the KV cache
What the cache holds, how it grows, and fp32 versus int8.
A transformer generates one token at a time, and each new token has to “look at” all the earlier ones. The model does not recompute the earlier tokens every time. It keeps, for every layer, the key and value vectors of every token so far. That store is the KV cache, and for a small model it is surprisingly big.
How big does the cache get?
Per token and per layer the cache stores one key vector and one value vector, each as wide as the model: 2 × d numbers. Across the whole model that is 2 × layers × d numbers per token. With a 256-token context window the model reserves room for all 256. Drag the slider to see it fill, and compare storing the numbers as 32-bit floats (the default) against 8-bit integers (an option):
Each square = 4 tokens of context. Attention reads all of the used cache in every layer for every new token, so the bytes read per token grow as the email gets longer. Compare with the weights: the 12M model is 4.4 MB, and its float32 cache is 6.3 MB when full: bigger than the model itself.
Does int8 help? Measured
Storing keys and values as int8 (with a small float scale per vector) shrinks the cache four times, so more of it stays in L1/L2 and less memory is read for each token. The cost is a conversion when reading and a little rounding in the attention. Here is the native engine decoding all the way to the 256-token context on one quiet core, where attention is at its most expensive:
Decode throughput at full context, one thread, median of 3. The gain is large for the 4M model (attention is a big share of its time at this length) and vanishes for the 21M, whose time is dominated by its matmuls.
This is why int8 KV stays an option and not the default: for the short emails this project writes (40 to 90 tokens including the request), attention is a small share (the profiling chapter) and the cache easily fits in L2 either way, so the gain would be a few percent while adding a rounding step to every attention score. It would matter for long contexts or on a CPU with a small cache.
Logits, fast logits and sampling
Scoring 3,596 words cheaply, then choosing one with temperature and top-k.
The last step of every token has two parts. First the model produces a score (a “logit”) for each of its 3,596 words. Then something has to choose one. Both have tricks.
Part 1: scoring 3,596 words without scoring 3,596 words
The profile in the profiling chapter showed the vocabulary step at 17 to 25% of a token. Each word needs a dot product of the model's final vector (512 numbers for the 21M) with the word's own vector. But we do not need every score exactly: sampling uses only the top 30 (top-k), so what matters is which words are in the top 30, and their exact scores. That allows a two-stage search with a proof attached.
Illustration with synthetic scores (so the fractions are not the real model's). In the real model the survivors are about 1.5% of the vocabulary.
Measured
The browser engine decoding all the way to the 256-token context on one thread, with the fast path on and off (explore harness: the demo page's “Engine benchmark”, median of 10 runs). Outputs are identical.
Part 2: choosing a word
Scores become probabilities with a softmax. A temperature T divides the scores first: a low temperature sharpens the distribution (the best word wins almost every time), a high one flattens it. Top-k removes everything below the k best words before the draw. Below, two temperatures are applied to the same scores for a made-up choice of first word, and 400 emails' worth of draws are made from each.
Pale bar: the probability. Solid bar: how often that word was drawn in 400 samples. Orange words are poor email openers.
Why the engine defaults to 0.5
For a big model a hot temperature means variety. For a tiny one it means damage. A 4M-parameter model's probability for a bad word is small but never zero, and each email is about 40 draws. One unlucky draw (“Lol” as an opener, or half of a misspelled word) makes the rest of the email follow the wrong lead, because every later word is conditioned on it. I graded the same requests at 0.7 and 0.5 and found 0.5 consistently better for the small models, so that became the default; it also explains why the home page's slider goes to 1.2 but starts at 0.5. At temperature 0 the model always takes its single best word, which is repeatable but can loop, so it is not the default either.
Where a token’s time really goes
Profiles of real emails: matmuls, attention, the vocabulary table.
It is easy to assume that a model spends its time in its big matrix multiplications. These measurements say that is only about half the story. They come from the page's own profiler: a real email request is run in headless Chromium and every part of every decoded token is timed with the browser's high-resolution clock (so the profile adds a little overhead; read it as a split, not a score).
The bar lengths share one scale, so the slower configuration is longer. One 16-token request, median of the runs on each setting; different requests move the numbers by a few percent.
What stands out
The vocabulary table is a quarter of a small model
Every token ends with the “logits” step: a dot product of the final vector with each of the 3,596 words' vectors, to score every possible next word. For the 4M model that is 3,596 × 256 = 0.92 million multiply-adds per token, more than the feed-forward down-projection (0.79 million) and about ten times the attention's at this email length. On the one-thread profile it is 25.5% of the model's time, and it falls to 22.5% for the 21M, because the layers grow and the vocabulary does not. This is why a 3,596-word vocabulary (and the fast-logits trick of the sampling chapter) matters so much at this size.
Attention grows with the text, the matmuls do not
Matrix multiplications cost the same for every token. Attention reads the whole key/value cache, so a token near the end of a long email costs more than one near the start. These profiles use short emails (about 16 prompt tokens and 30 generated), where attention is a tenth of the time. When the same 4M model is run to its full 256-token context in the native profiler, the split changes completely:
At full context attention is 35% and the four matmuls only 33%. Emails stay short, which is the regime the engine is tuned for; a long-context version would need a different optimisation plan (an int8 KV cache, the KV-cache chapter).
More threads help the matmuls, and hurt the small stuff
Compare the 1-thread and 4-thread profiles of the same model. The matmul rows shrink, but the “norms + quant” and “other” rows grow: those pieces run on one thread and now also pay to wake the helpers and wait at a barrier. The next chapter is about exactly that.
The table behind the bars
| µs per token | 4M · 1 | 4M · 4 | 12M · 1 | 12M · 4 | 21M · 1 | 21M · 4 |
|---|---|---|---|---|---|---|
| qkv matvec | 131 | 77 | 203 | 164 | 333 | 254 |
| wo matvec | 48 | 47 | 68 | 68 | 113 | 100 |
| w13 matvec | 217 | 93 | 307 | 236 | 502 | 358 |
| w2 matvec | 82 | 45 | 129 | 112 | 230 | 172 |
| attention | 82 | 68 | 169 | 119 | 196 | 157 |
| norms + quant | 39 | 47 | 34 | 64 | 42 | 104 |
| vocabulary (logits) | 222 | 124 | 317 | 181 | 423 | 243 |
| sampling | 9 | 10 | 6 | 11 | 6 | 12 |
| other | 41 | 47 | 31 | 57 | 31 | 68 |
| total | 872 | 558 | 1264 | 1012 | 1877 | 1468 |
| tok/s | 1147 | 1793 | 791 | 988 | 533 | 681 |
| time to first token (ms) | 8.8 | 3.8 | 17.9 | 11 | 34.8 | 16.6 |
Columns: model · threads. Profiling inflates every number slightly, so tok/s here is a little lower than the leaderboard's.
Threads and the barrier
How rows are split across workers, false sharing, and the scaling that results.
One thread unpacks and multiplies at about 8.5 GB/s (the memory-staircase chapter). To go faster, split the work. The engine uses a small pool of threads (WebAssembly Web Workers in the browser) that all work on the same layer, then synchronise. It is simple to describe and surprisingly hard to make fast.
What the scaling really looks like
I measured this on the laptop that is running this project, and it taught me something the diagram only hints at. The CPU has four physical cores, but two of them share their time with the editor and other programs, and in a single-thread test they decoded at 1,117 tok/s against 2,300 on the two quiet cores. Pin threads to the quiet cores first, then add the slow ones:
⚠ the 3rd and 4th thread run on the shared, slower cores. With the barrier, everyone waits for them.
Short real emails with the profiler on; the OS chooses the cores.
Bar length: speed relative to the 1-thread run (a bar reaching 100% would be a 2.2× speed-up). Native: taskset to cores 4, 6, then 2, then 0, and --threads t. A 3-thread run is slower than a 2-thread one for every model.
The lesson of the barrier
- The team runs at the speed of its slowest member. Each layer ends with a barrier. With two fast cores and one slow one, the fast cores finish their slice, then spin, waiting for the slow core. Three threads were slower than two for all three models. This is the practical reason the engine's slices are equal and fixed: if one thread is late, everyone is late.
- Two quiet cores give about 1.5×. That is far from 2×, and it is the barrier and the serial part at work: in the previous chapter's one-thread profile about a tenth of a token is plainly serial (norms, quantisation, sampling, bookkeeping), and everything else has to wait at a barrier for the slowest thread.
- Model size barely matters at this scale. Two quiet cores give 1.43× (4M), 1.55× (12M) and 1.49× (21M): in theory longer slices amortise the barrier better, but the differences are within the noise of a laptop shared with other programs.
- In a browser you do not choose the cores. The operating system places the workers, shares them with every other tab, and the pool can only react by spinning. That is why a browser run on a busy laptop is noisier than the leaderboard would like.
Why every shared counter gets its own cache line
The pool pads each shared integer to 64 bytes. That looks wasteful until you see what the hardware does when two cores write different variables that happen to share a line. I measured it with two C threads on two cores, each incrementing its own counter 100 million times:
Best of 3 on two physical cores with taskset; source explore/kernels/falsesharing.c. The same effect is why the pool gives each helper its own completion slot instead of one shared counter.
How the browser's pool works
There is no operating-system thread library inside WebAssembly, so the engine has its own pool built from shared memory and atomic instructions. The design is small enough to describe completely:
- A generation counter. To start a job the main thread writes the job description (function, data pointer, size) and increments one shared integer,
job_gen. Helpers are spinning on that integer; the change is their go signal. - Fixed slices. Thread t of T always takes rows [n·t/T, n·(t+1)/T). The slice for a given matrix is the same on every token, so each core keeps its part of the weights in its own L2 cache instead of fighting over them.
- One completion slot per helper. Each helper stores the generation number into its own
done[t]when finished; the main thread, after finishing its own slice, waits until every slot shows the current generation. No atomic add, no shared counter to fight over. - Every counter on its own cache line. Each shared integer is padded to 64 bytes. Two threads writing different variables in the same line force the line to bounce between cores (false sharing); padding removes that.
- Spin, then sleep. During an email, helpers spin on
job_gen(about 4 million checks, several milliseconds) so a new job is noticed in nanoseconds. Only after that long without work do they sleep inAtomics.wait, and the main thread callsnotifyonly if someone is actually asleep, because in browsers every notify takes a lock. That one rule took an idle tab from burning ~20% of a core to 0.1%. - Small matrices stay on one thread. A matvec is split only from 128 output rows up. Below that the barrier costs more than the work saved.
Putting it together
The sequence of optimisations, what each was worth, and how every one was proven safe.
Everything above is the finished machine. This is how it got that way: a thousand lines of C that compile to a 95 KB WebAssembly file, with a native build of the same code to test the browser against. The first browser numbers were sobering: a few hundred tokens a second for the 21M model. So I added a profiler to the page, the one behind the profiling chapter, and optimisation became a game of finding whatever was biggest:
- A faster kernel. The browser’s relaxed SIMD dot product, summing in 16 bits like the native code, was worth about 20% of a whole token (2.3× on the matmuls alone).
- Dodging what the browser emulates. Some WebAssembly instructions have no x86 equivalent and expand into many. Rewriting two of them (the float-to-int conversion and the 8-bit shifts) gave identical results much faster.
- Fewer, fatter steps. RoPE and the cache write moved inside attention, SwiGLU inside the matrix multiply, normalise-and-quantise became one pass (fused kernels).
- A leaner [[thread-pool|thread pool]]. Spin while there is work, sleep when there is not: an idle open tab fell from ~20% of a core to 0.1%.
- [[fast-logits|Fast logits]]. Score the vocabulary cheaply in int8 with a provable error bound, then recompute exactly only the ~1.5% of words that could win. Same output, 12–15% faster.
- [[jit-tiers|Warm-up]]. The browser compiles WebAssembly twice, quickly and then well, so the first email was 2 to 3 times slower than the tenth. The page now warms up before it says “ready”.
| Steady-state tok/s, 4 threads, on the dev laptop | Before | After |
|---|---|---|
| 1M model | 10,400 | 13,200 |
| 4M model | 3,100 | 4,200 |
| 21M model | 1,070 | 1,110 |
| 40M model | 660 | 675 |
Every change had to keep the output identical, so the test suite became part of the craft: the request parser is compared against the native one on 44 requests, the browser against the native engine, one thread against four, and fast logits against the full computation on 480 emails. When two words tie within 0.001 in the score, floating-point order alone can pick either, so the test now reports a near-tie with the gap instead of crying wolf.
What a server CPU does with it
The hypothesis, tested on a CPU with a 64 MB cache.
The dev laptop has 4 MB of L3, so most of the models spill out of cache. To test the hypothesis properly I rented a CPU-only machine for a few minutes: an AMD EPYC 4564P, 16 cores, 1 MB of L2 per core and 64 MB of L3, about 56 cents an hour. A script ran the same benchmark the site uses, for the native engine and for the browser build in headless Chromium, and the pod was deleted about two minutes later.
| 4 threads, tok/s | Dev laptop (browser) | EPYC (browser) | EPYC (native) |
|---|---|---|---|
| 1M | 13,200 | 24,100 | 24,800 |
| 4M | 4,200 | 12,500 | 13,200 |
| 21M | 1,110 | 3,900 | 6,100 |
| 40M | 680 | 2,800 | 3,800 |
That is the answer, or a first one: yes. Put a model in a big enough cache and a browser writes thousands of words a second, and native code on a good CPU tens of thousands. The 21M model gains 3.5× from the move to a CPU with a bigger cache and more cores; the 1M, which already fit, gains less than 2×. The native engine is faster still because it can use 256-bit vectors and pin threads to cores, which browsers cannot (cores and threads).
Experiment: fusing the unpacking
Could a smarter kernel hide the cost of unpacking the weights? I wrote six and timed them.
With the obvious work done, I went looking for the next speed-up in two places people building low-bit models keep mentioning. The code for both is in the repository under explore/. Neither made it into the engine, and the reasons are the useful part.
Each 16-byte group of weights has to be unpacked into four vectors before the dot products, which costs seven instructions for every sixteen. I wrote a dozen variants in a standalone WebAssembly file and timed whole models, so the weights stream through the caches the way they do in a real token. Every variant but the ceiling gives bit-identical results to a scalar reference.
Best of five timings per cell, one thread, on a Ryzen 5 2500U laptop (no VNNI). Run-to-run noise is about ±5%, so gaps under 5% are not real. Every kernel except the ceiling gives bit-identical results to the scalar reference.
- The ceiling is not far away. Even if unpacking were completely free, the kernel would be only 14 to 20% faster. The dot products, not the unpacking, are the cost.
- Unpack once, reuse for several tokens helps only when many tokens are processed together, which happens while the model reads your request, and gains 8 to 11% there. Reading the request is about half of a short email’s time, so that is roughly 2% overall, and it would need a rewrite of how the engine batches tokens. Not worth it.
- Lazy widening (add in 16 bits for eight steps before widening to 32) is within noise.
- The fused dot-and-add instruction looks perfect on paper and is 50% slower. This laptop has no VNNI, so the browser expands it into several instructions. It might win on a newer CPU; I could not check.
Experiment: rotating the activations
The Hadamard transform in practice: what the real models’ activations say, what it costs, and why I did not ship it.
The int8 chapter ended with a problem: when one activation is much larger than the others, squeezing the vector into int8 wastes the 256 levels on the outlier. A Hadamard transform is a way to spread the outlier out. It is also an unusually cheap, elegant algorithm, and a good illustration of how structure turns an n² problem into an n log n one.
The output is not scaled yet: dividing by √n makes the transform orthonormal, which means it preserves the vector's length and applying it twice returns the original. That is what makes it safe: nothing is lost, the same information is just arranged differently. The engine can skip the division, because the next step (int8 quantisation) divides by the vector's own maximum anyway.
Side by side: matrix versus butterfly
A Hadamard transform is a matrix multiplication: the matrix is made entirely of +1 and −1 (and 1/√n), arranged recursively. Doing it as a matrix costs n² multiply-adds. Doing it as a butterfly network costs n·log₂n additions:
Bars share one scale. At n = 1024 the butterfly is 100× less work.
In WebAssembly SIMD the butterfly is a gift. The first two stages happen inside a single 4-lane vector (a swizzle and a multiply by a sign vector), and the remaining stages are plain vector adds and subtracts of two memory blocks, with no data dependency inside a stage. I measured it at 0.26 µs for 256 numbers, 0.56 µs for 512 and 1.2 µs for 1024, about 1.1 ns per element, exact against a scalar version.
Why spreading helps
Every output of the transform is a sum of all the inputs with signs. A single huge input contributes the same magnitude to every output (with a plus or minus), and the small ones scatter and mostly cancel. The result looks like random noise with a modest spread, which is exactly what int8 rounding handles best:
Same numbers, same total energy, just seen from a different angle. int8 quantisation scales every value by the biggest one, so one tall spike makes all the small values coarse. Spreading the spike out first makes the rounding finer for everyone. This is an illustration with made-up numbers; the measurements on the real models are in the Hadamard experiment chapter.
The catch
Rotating the activations is only free if the weights are rotated the opposite way: W x = (W Hᵀ)(H x). For a normal network W Hᵀ is simply a different set of numbers. For a ternary network it is not ternary any more, so a finished model cannot be rotated after the fact. The rotation has to be built into training, which then learns ternary weights in the rotated basis. That is the experiment prepared in explore/hadamard/train_h.py; the last chapters of this document report what the real models' activations say about it.
What the real models say
I measured it on the real models, using hundreds of real training emails and the input to each ternary layer:
| Layer input | Spikiness (peak ÷ typical) | int8 error: plain → rotated | int4 error: plain → rotated |
|---|---|---|---|
| after the first norm (qkv) | 3.1–3.4, already flat | 0.7% → 0.7% | 13% → 13% |
| attention output (wo) | 3.7–4.3 → 3.0–3.2 | 0.8–1.0% → 0.7% | 15–18% → 13% |
| after the second norm (w13) | 3.2–3.4, already flat | 0.7–0.8% → 0.7% | 13–14% → 13% |
| feed-forward output (w2) | 10.7–12.2 → 3.0–3.3 | 2.9–3.1% → 0.7% | 30% → 12% |
The result is very clear and very narrow. Only one place has real outliers, the input to the feed-forward down-projection (w2), where rotating cuts the int8 error by four times. Everywhere else the activations are already flat. The transform itself is cheap: 0.56 µs for a 512-wide vector and 1.2 µs for 1024-wide, which adds roughly 2 to 4% to a token for the 4M model and 1.5 to 2% for the 21M.
Why it is not in the engine
Two honest reasons. A rotation only helps if the model is trained to expect it: rotating a finished model’s weights would stop them being ternary, so the model has to be retrained with the rotation inside it. And the payoff is fidelity, not speed. WebAssembly has no 4-bit dot product, so there is nothing faster to cash the better rounding in for. At 8 bits the plain model’s error on its worst layer is already about 3%.
Then I trained it with the rotation
The rotation inside training is simple: the inputs to the attention output projection and the feed-forward down-projection are multiplied by a Hadamard matrix before they are squeezed to int8, and the weights learn in that rotated basis. I trained a 1M model both ways with identical settings (30,000 steps, the v10 data). Validation loss is noisy at this size, so the fair comparison is the average of the last 20 evaluations, not the single best one:
| 1M model, v10 data | best eval | mean of last 20 evals |
|---|---|---|
| plain | 0.699 | 0.720 |
| with the rotation (attention output and w2 input) | 0.680 | 0.717 |
Shipping it, and where it stops
A free site, a name, and why I stopped.
The site is a SvelteKit app with DaisyUI on Cloudflare Pages, scores in D1 (serverless SQLite), and everything in the free tiers; the models are static files. The benchmark page tries 1, 2, 4 and 8 threads, keeps the fastest, runs ten steady-state passes for the score, and measures time to first token on ten real emails. The gotchas were instructive: cross-origin isolation restricts what a page may embed, browsers hide the CPU model so the site asks you once, and scores are self-reported, so it is a fun board and not a benchmark authority.
The name comes from a pilot who flew the wrong way on purpose, or said he did not. Everyone else in AI is flying towards bigger and smarter; corrigan38 went the other way. The story is here.
What I would do next, and why I am not
The question has an answer. Yes, a language model can live in a CPU cache, and yes, in that form it can write a decent short email in a few milliseconds, in a browser tab, for free. What it cannot do is be reliably good. A 4M-parameter model with this much data plateaus: every extra pass of training lowered the loss and left the emails the same, and each round of targeted data fixed one kind of mistake and let a small new one in.
- A model of 20 to 40M parameters trained on much more varied data would probably write better, and still fit in a server’s L3.
- An AVX-512/VNNI kernel for the native engine, since server CPUs sit on instructions I am not using.
- The Hadamard-trained model, as a single 30-cent experiment, to settle that question properly.
- A WebGPU run, to replace my guess (“the CPU wins at this size”) with a measurement.
I am stopping here, because more money for a model that is not very useful is not a good trade. The code, the data pipeline and the leaderboard are all in place. If you have an unusual CPU, an old laptop, a new Mac or a phone, run the benchmark and put it on the board. I would love to see where the cache cliffs are.