Reproducible CPU Lab · LLM

A tiny cached decoder

Companion Writing
KV Cache Explained Through a Tiny Decoder →

Compare full-prefix and incremental decoding in the same CPU model. Verify positions, logits, cache growth, and measurement boundaries before claiming a speedup.

Run from the repository root (the directory containing labs). After downloading the archive, extract it and run from the extracted root.

sh
labs/.venv/bin/python -m unittest discover -s labs/llm/kv-cache -p "test_*.py" -v
labs/.venv/bin/python labs/llm/kv-cache/benchmark.py --output labs/results/cache-results.json

Go requires 1.24 or newer. Python requires 3.11 or newer. The two LLM labs additionally require CPU-capable PyTorch in labs/.venv; see the collection instructions.

Tests use deterministic substitutes or synthetic tensors. No paid API, cloud service, model-weight download, GPU, or external project checkout is required. A failed test is a correctness issue to investigate; raw timing changes alone do not fail the tests.

Read the source and tests together. The article's code excerpts are extracted from marked regions in these files during the website build.

Source & Verification Files

Primary implementation expanded · Click any file header to toggle
Implementationbenchmark.py
87 lines
/labs/llm/kv-cache/benchmark.pyRaw file ↓
python
"""Write raw CPU timings. This is not a GPU or language-quality benchmark."""

import argparse
import json
import platform
import statistics
import time
from datetime import datetime, timezone
from pathlib import Path
import torch
from decoder import TinyDecoder, cache_bytes


def main():
    parser = argparse.ArgumentParser()
    parser.add_argument("--output", type=Path, default=Path("cache-results.json"))
    parser.add_argument("--repeats", type=int, default=7)
    args = parser.parse_args()
    if args.repeats < 2:
        parser.error("use at least two repeats")
    torch.manual_seed(11)
    torch.set_num_threads(1)
    model = TinyDecoder().cpu().eval()
    rows = []
    with torch.inference_mode():
        for length in [16, 32, 64, 128]:
            ids = torch.randint(0, 64, (1, length))

            def full():
                for end in range(1, length + 1):
                    model(ids[:, :end])

            def cached():
                cache = None
                for pos in range(length):
                    _, cache = model(ids[:, pos : pos + 1], cache)
                return cache

            full()
            cached()
            raw = {"full": [], "cached": []}
            for repeat in range(args.repeats):
                # Alternate order to reduce a systematic first-run advantage.
                for name in (
                    ["full", "cached"] if repeat % 2 == 0 else ["cached", "full"]
                ):
                    start = time.perf_counter_ns()
                    (full if name == "full" else cached)()
                    raw[name].append((time.perf_counter_ns() - start) / 1e6)
            rows.append(
                {
                    "tokens": length,
                    "cache_bytes": cache_bytes(cached()),
                    "raw_ms": raw,
                    "median_ms": {
                        name: statistics.median(values) for name, values in raw.items()
                    },
                }
            )
    output = {
        "kind": "CPU random-weight teacher-forced decoder microbenchmark",
        "timestamp": datetime.now(timezone.utc).isoformat(),
        "python": platform.python_version(),
        "torch": torch.__version__,
        "platform": platform.platform(),
        "device": "cpu",
        "threads": 1,
        "seed": 11,
        "repeats": args.repeats,
        "warmup_runs_per_mode": 1,
        "model": {
            "layers": 1,
            "width": 32,
            "heads": 4,
            "vocab": 64,
            "dtype": "float32",
            "batch": 1,
        },
        "rows": rows,
    }
    args.output.parent.mkdir(parents=True, exist_ok=True)
    args.output.write_text(json.dumps(output, indent=2) + "\n")
    print(json.dumps(output, indent=2))


if __name__ == "__main__":
    main()
Implementationdecoder.py
76 lines
/labs/llm/kv-cache/decoder.pyRaw file ↓
python
"""One-block decoder with learned positions and explicit append-only KV state."""

from __future__ import annotations
import importlib.util
from pathlib import Path
import torch
from torch import Tensor, nn

_spec = importlib.util.spec_from_file_location(
    "lab_attention", Path(__file__).parents[1] / "attention" / "attention.py"
)
_attention = importlib.util.module_from_spec(_spec)
_spec.loader.exec_module(_attention)
causal_attention = _attention.causal_attention
Cache = tuple[Tensor, Tensor]


class TinyDecoder(nn.Module):
    def __init__(
        self, vocab: int = 64, width: int = 32, heads: int = 4, max_length: int = 256
    ):
        super().__init__()
        if width % heads:
            raise ValueError("width must divide evenly across heads")
        self.heads = heads
        self.width = width
        self.max_length = max_length
        self.token = nn.Embedding(vocab, width)
        self.position = nn.Embedding(max_length, width)
        self.norm1 = nn.LayerNorm(width)
        self.qkv = nn.Linear(width, 3 * width, bias=False)
        self.out = nn.Linear(width, width, bias=False)
        self.norm2 = nn.LayerNorm(width)
        self.mlp = nn.Sequential(
            nn.Linear(width, 2 * width), nn.GELU(), nn.Linear(2 * width, width)
        )
        self.final = nn.LayerNorm(width)
        self.head = nn.Linear(width, vocab, bias=False)

    # region:decode
    def forward(self, ids: Tensor, cache: Cache | None = None) -> tuple[Tensor, Cache]:
        batch, length = ids.shape
        if length < 1:
            raise ValueError("at least one token is required")
        offset = 0 if cache is None else cache[0].shape[-2]
        if offset + length > self.max_length:
            raise ValueError("position capacity exceeded")
        if cache is not None:
            k, v = cache
            if (
                k.shape != v.shape
                or k.shape[:2] != (batch, self.heads)
                or k.shape[-1] != self.width // self.heads
            ):
                raise ValueError("cache shape mismatch")
        positions = torch.arange(offset, offset + length, device=ids.device)
        x = self.token(ids) + self.position(positions)
        projected = self.qkv(self.norm1(x)).view(
            batch, length, 3, self.heads, self.width // self.heads
        )
        q, k, v = projected.permute(2, 0, 3, 1, 4).unbind(0)
        if cache is not None:
            k = torch.cat((cache[0], k), dim=-2)
            v = torch.cat((cache[1], v), dim=-2)
        attended = causal_attention(q, k, v, offset=offset)
        x = x + self.out(
            attended.transpose(1, 2).contiguous().view(batch, length, self.width)
        )
        x = x + self.mlp(self.norm2(x))
        return self.head(self.final(x)), (k, v)

    # endregion:decode


def cache_bytes(cache: Cache) -> int:
    return sum(t.numel() * t.element_size() for t in cache)
Verification Suitetest_decoder.py
48 lines
/labs/llm/kv-cache/test_decoder.pyRaw file ↓
python
import unittest
import torch
from decoder import TinyDecoder, cache_bytes


class CacheTests(unittest.TestCase):
    def setUp(self):
        torch.manual_seed(11)
        torch.set_num_threads(1)
        self.model = TinyDecoder().eval()
        self.ids = torch.randint(0, 64, (2, 12))

    def test_incremental_matches_full_prefix(self):
        cache = None
        with torch.inference_mode():
            for position in range(self.ids.shape[1]):
                full, _ = self.model(self.ids[:, : position + 1])
                incremental, cache = self.model(
                    self.ids[:, position : position + 1], cache
                )
                torch.testing.assert_close(
                    full[:, -1], incremental[:, -1], atol=1e-5, rtol=1e-5
                )
                self.assertEqual(cache[0].shape, (2, 4, position + 1, 8))
                self.assertEqual(cache_bytes(cache), 2 * 2 * 4 * (position + 1) * 8 * 4)

    def test_chunked_prefill(self):
        with torch.inference_mode():
            full, _ = self.model(self.ids)
            _, cache = self.model(self.ids[:, :7])
            chunk, _ = self.model(self.ids[:, 7:], cache)
            torch.testing.assert_close(full[:, 7:], chunk, atol=1e-5, rtol=1e-5)

    def test_request_isolation(self):
        with torch.inference_mode():
            a, _ = self.model(self.ids)
            self.model(self.ids.flip(1))
            b, _ = self.model(self.ids)
            torch.testing.assert_close(a, b)

    def test_position_capacity(self):
        model = TinyDecoder(max_length=3)
        with self.assertRaises(ValueError):
            model(self.ids[:, :4])


if __name__ == "__main__":
    unittest.main()
Recorded Outputcache-results.json
134 lines
/labs/results/cache-results.jsonRaw file ↓
json
{
  "kind": "CPU random-weight teacher-forced decoder microbenchmark",
  "timestamp": "2026-09-09T02:46:09.627120+00:00",
  "python": "3.14.7",
  "torch": "2.14.0",
  "platform": "macOS-27.0-arm64-arm-64bit-Mach-O",
  "device": "cpu",
  "threads": 1,
  "seed": 11,
  "repeats": 7,
  "warmup_runs_per_mode": 1,
  "model": {
    "layers": 1,
    "width": 32,
    "heads": 4,
    "vocab": 64,
    "dtype": "float32",
    "batch": 1
  },
  "rows": [
    {
      "tokens": 16,
      "cache_bytes": 4096,
      "raw_ms": {
        "full": [
          0.99375,
          0.919,
          0.915333,
          0.973875,
          0.942833,
          0.901292,
          0.919667
        ],
        "cached": [
          0.729583,
          0.730583,
          0.761792,
          0.748334,
          0.741625,
          0.725333,
          0.734208
        ]
      },
      "median_ms": {
        "full": 0.919667,
        "cached": 0.734208
      }
    },
    {
      "tokens": 32,
      "cache_bytes": 8192,
      "raw_ms": {
        "full": [
          2.2525,
          2.15875,
          2.151167,
          2.242375,
          2.325417,
          2.182958,
          2.156041
        ],
        "cached": [
          1.388833,
          1.39825,
          1.446958,
          1.4115,
          1.467625,
          1.425292,
          1.374875
        ]
      },
      "median_ms": {
        "full": 2.182958,
        "cached": 1.4115
      }
    },
    {
      "tokens": 64,
      "cache_bytes": 16384,
      "raw_ms": {
        "full": [
          5.55875,
          5.42675,
          5.401792,
          5.606541,
          5.548917,
          5.48825,
          5.455791
        ],
        "cached": [
          2.953667,
          3.08025,
          2.931625,
          2.971375,
          3.001292,
          3.047792,
          2.834416
        ]
      },
      "median_ms": {
        "full": 5.48825,
        "cached": 2.971375
      }
    },
    {
      "tokens": 128,
      "cache_bytes": 32768,
      "raw_ms": {
        "full": [
          15.565542,
          15.889083,
          15.855417,
          15.691584,
          15.590042,
          15.929458,
          15.948208
        ],
        "cached": [
          6.251625,
          6.242834,
          6.337375,
          6.337792,
          6.188792,
          6.31475,
          6.190042
        ]
      },
      "median_ms": {
        "full": 15.855417,
        "cached": 6.251625
      }
    }
  ]
}