PythiloLesson 3 of 9 · progress kept in this browser

Practice in Lab: Decode chunks with an owned, offset-aware KV cache →

Decode chunks with an owned, offset-aware KV cache

A cached query begins after the keys already stored. Applying an ordinary upper-left triangular mask to a short new chunk can hide most of its past or expose later tokens incorrectly. This Lab derives absolute query positions from cache length and compares incremental results with one full causal pass. The returned cache owns its tensors, so later caller mutations cannot corrupt earlier results. It is an exclusive-owner CPU inference cache with fixed head geometry; paging, eviction, concurrency and server memory allocation remain outside the exercise.

import torch
past, count = 3, 2
query = torch.arange(past, past+count)
keys = torch.arange(past+count)
print(keys[None, :] <= query[:, None])
This example uses torch. Run it in the Pythilo app, where these features are available.
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.

This lesson uses torch, which Python in this browser does not include. Read it here, and run and check it in the Pythilo app on iPhone or iPad.