10/26
Part 2 of 4 · What the cache holdsLearn and do

Every shape in a cached step

Here is the start of a cached forward pass:

# T counts the new tokens only
B, T, C = x.shape
q, k, v = self.qkv(x).split(C, dim=2)
q, k, v = (t.view(B, T, self.n_head, C // self.n_head).transpose(1, 2) for t in (q, k, v))
if cache is not None:
    # past first, then new, on the time axis
    k = torch.cat([cache[0], k], dim=2)
    v = torch.cat([cache[1], v], dim=2)

The three lines of code before the if are plain multi-head attention. Two things are new: x holds only the new tokens, and a cache may come in, holding the keys and values of everything before them.

With H heads, head size d = C / H, TpastT_\text{past} cached tokens and TnewT_\text{new} new ones, here is where a cached step starts:

TensorShapeWhat it is
x(B, T_new, C)the new tokens only
q, k, v(B, H, T_new, d)after the split, view and transpose
cache[0], cache[1](B, H, T_past, d)keys and values of every earlier token

Every other shape follows from these and the code. The mask is one grid, new tokens by keys, shared by every batch entry and every head.

In the editor, shapes lists six tensors of one cached step, for a batch of 2, 4 heads of size 8, 5 cached tokens and 2 new ones. Fill in each shape, with numbers or with the letters B, H, d, C, T_past and T_new.