REAL PYTORCH · CPU TRAINING AND AUTOGRAD

Decode chunks with an owned, offset-aware KV cache

A cached query begins after the keys already stored.

Run this Lab in Pythilo

Open Labs, choose its topic and tap Download entire topic, or Download entire category for all its Labs, including the required Python packages, then load the starter or worked answer and tap Trace. Progress, pause, resume and removal are in Downloads. Independent checks execute real CPU training and gradients.

No GPU, external model weights or API key is required. After downloading the topic and packages, this Lab runs offline.

PyTorch is unavailable in this browser runtime. The code and lessons are readable here; execution and checks run in the app.

Pythilo on the App Store →

Read lesson: Decode chunks with an owned, offset-aware KV cache →

Your task

Inference-only q,k,v have the same nonempty [B,H,T,D] shape. Optional cache has exactly k/v with matching batch/head/width/dtype/device. Append current keys and values and admit key position <= past_length+query_index. Return output and a detached cloned k/v cache; do not mutate or alias old cache or new input chunks. Full, tokenwise and multi-token chunked execution must agree. No dropout or positional transform is applied here.

Starter

import torch


def cached_attention(q, k, v, cache=None):
    return None
Inspect the worked answer
import math
import torch


@torch.no_grad()
def cached_attention(q, k, v, cache=None):
    if q.ndim != 4 or q.shape != k.shape or k.shape != v.shape or min(q.shape) < 1:
        raise ValueError('aligned nonempty [B,H,T,D] chunks required')
    past = 0
    if cache is not None:
        if set(cache) != {'k', 'v'} or cache['k'].shape != cache['v'].shape or cache['k'].ndim != 4:
            raise ValueError('owned key/value cache required')
        old = cache['k']
        if old.shape[:2] != k.shape[:2] or old.shape[-1] != k.shape[-1] or old.dtype != k.dtype or old.device != k.device:
            raise ValueError('cache and chunk dimensions must agree')
        past = old.shape[2]
        keys = torch.cat((cache['k'], k), dim=2)
        values = torch.cat((cache['v'], v), dim=2)
    else:
        keys, values = k, v
    query_positions = torch.arange(past, past + q.shape[2], device=q.device)
    key_positions = torch.arange(keys.shape[2], device=q.device)
    allow = key_positions[None, :] <= query_positions[:, None]
    scores = q @ keys.transpose(-2, -1) / math.sqrt(q.shape[-1])
    weights = torch.softmax(scores.masked_fill(~allow, float('-inf')), dim=-1)
    return weights @ values, {'k': keys.detach().clone(), 'v': values.detach().clone()}

About this algorithm

How Decode chunks with an owned, offset-aware KV cache works

The idea

Generating text one token at a time would repeat a great deal of work if every step re-ran attention over the whole sequence. Under a causal mask, the keys and values of earlier tokens never change when new tokens arrive, so they can be stored once and reused. Each step then scores only the new queries against the stored keys plus the new ones.

What makes it correct is the offset. New queries start not at position 0 but at past, the number of keys already cached, so query i of the chunk may see keys up to past + i. With that offset, full, token-by-token and chunked passes all agree. The returned cache is a detached clone, so later edits cannot reach the old cache or the inputs.

How it works

  1. Check that q, k, v share one nonempty [B, H, T, D] shape and that any cache holds exactly k and v with matching batch, heads, width, dtype and device.
  2. Set past to the cached length, or 0 without a cache, and concatenate cached and new keys and values along the time axis.
  3. Number the queries from past upward in query_positions and the keys from 0 in key_positions.
  4. Build allow as key position <= query position, and fill every other score with -inf before the softmax.
  5. Return weights @ values and a new cache built with detach().clone().

What it costs

Per chunk
O(T·(past + T)·D)
Cache
grows with every token
No cache
rescore the whole prefix

Only the new queries are scored, against all stored keys, so a step costs time proportional to the context length rather than its square; this Lab also copies the whole cache on each call.

Where it is used

  • Hugging Face Transformers generate() reuses past_key_values when use_cache=True, so each step feeds only the newest token through the model.
  • llama.cpp keeps a KV cache for each context and can save it to a prompt cache file so a repeated prompt is not evaluated again.
  • vLLM's PagedAttention stores the KV cache in fixed-size blocks, in the manner of virtual memory pages.

Watch out for

  • Masking with a plain tril over the chunk: query i then sees keys only up to i instead of past + i, and chunked output stops matching the full pass.
  • Returning the concatenated tensors, or the caller's k and v, without clone(): an in-place edit of the new cache would then change the old cache or the inputs.
  • Caching with gradients enabled, so the cache drags an autograd graph along. The Lab runs under torch.no_grad() and checks that the cache does not require gradients.