Reproducible CPU Lab · LLM

Causal attention on CPU

Companion Writing
Causal Attention from First Principles: Shapes, Masks, and Numerical Checks →

Implement causal attention on CPU, trace every tensor dimension, and test outputs and gradients against PyTorch before reasoning about performance.

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/attention -p "test_*.py" -v
labs/.venv/bin/python labs/llm/attention/attention.py

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
Implementationattention.py
40 lines
/labs/llm/attention/attention.pyRaw file ↓
python
"""CPU causal attention. Random tensors demonstrate mechanics, not model quality."""

import math
import torch
from torch import Tensor


# region:attention
def causal_attention(q: Tensor, k: Tensor, v: Tensor, *, offset: int = 0) -> Tensor:
    # Shapes: q [B,H,Tq,D], k/v [B,H,Tk,D]. Offset is the prefix length.
    if q.ndim != 4 or k.ndim != 4 or v.ndim != 4:
        raise ValueError("expected rank-four tensors")
    if q.shape[:2] != k.shape[:2] or k.shape != v.shape or q.shape[-1] != k.shape[-1]:
        raise ValueError("incompatible batch, head, or feature dimensions")
    if offset < 0 or offset + q.shape[-2] != k.shape[-2] or q.shape[-2] == 0:
        raise ValueError("keys must cover prefix plus current queries")
    scores = q @ k.transpose(-2, -1) / math.sqrt(q.shape[-1])
    query_positions = torch.arange(q.shape[-2], device=q.device) + offset
    key_positions = torch.arange(k.shape[-2], device=q.device)
    allowed = key_positions[None, :] <= query_positions[:, None]
    probabilities = scores.masked_fill(~allowed, float("-inf")).softmax(dim=-1)
    return probabilities @ v


# endregion:attention

if __name__ == "__main__":
    torch.manual_seed(7)
    q, k, v = [torch.randn(2, 4, 8, 16) for _ in range(3)]
    result = causal_attention(q, k, v)
    reference = torch.nn.functional.scaled_dot_product_attention(
        q, k, v, is_causal=True, dropout_p=0.0
    )
    print(
        {
            "device": str(q.device),
            "shape": list(result.shape),
            "max_absolute_error": (result - reference).abs().max().item(),
        }
    )
Verification Suitetest_attention.py
54 lines
/labs/llm/attention/test_attention.pyRaw file ↓
python
import unittest
import torch
from attention import causal_attention


class AttentionTests(unittest.TestCase):
    def setUp(self):
        torch.manual_seed(7)
        torch.set_num_threads(1)

    def test_reference_output_and_gradients(self):
        inputs = [
            torch.randn(2, 2, 5, 4, dtype=torch.float64, requires_grad=True)
            for _ in range(3)
        ]
        ours = causal_attention(*inputs)
        reference = torch.nn.functional.scaled_dot_product_attention(
            *inputs, is_causal=True, dropout_p=0.0
        )
        torch.testing.assert_close(ours, reference, atol=1e-10, rtol=1e-8)
        grad1 = torch.autograd.grad(ours.square().sum(), inputs, retain_graph=True)
        grad2 = torch.autograd.grad(reference.square().sum(), inputs)
        for a, b in zip(grad1, grad2):
            torch.testing.assert_close(a, b, atol=1e-10, rtol=1e-8)

    def test_future_is_invisible(self):
        q, k, v = [torch.randn(1, 2, 6, 4) for _ in range(3)]
        original = causal_attention(q, k, v)
        k2 = k.clone()
        v2 = v.clone()
        k2[:, :, 3:] += 100
        v2[:, :, 3:] -= 100
        torch.testing.assert_close(
            original[:, :, :3], causal_attention(q, k2, v2)[:, :, :3]
        )

    def test_cached_non_square_mask(self):
        q = torch.randn(1, 2, 2, 4)
        k = torch.randn(1, 2, 6, 4)
        v = torch.randn_like(k)
        mask = torch.arange(6)[None, :] <= torch.arange(4, 6)[:, None]
        reference = torch.nn.functional.scaled_dot_product_attention(
            q, k, v, attn_mask=mask, dropout_p=0.0
        )
        torch.testing.assert_close(causal_attention(q, k, v, offset=4), reference)

    def test_bad_offset(self):
        x = torch.randn(1, 1, 2, 4)
        with self.assertRaises(ValueError):
            causal_attention(x, x, x, offset=1)


if __name__ == "__main__":
    unittest.main()
Recorded Outputattention-result.txt
1 lines
/labs/results/attention-result.txtRaw file ↓
text
{'device': 'cpu', 'shape': [2, 4, 8, 16], 'max_absolute_error': 2.384185791015625e-07}