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])Review the design
Keep positional encoding offsets, cache identity and model version consistent. Detached inference caches do not implement recurrent training or durable serving state.
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.
The explanation opens here once every check passes.