4/26
Part 1 of 4 · Why a cache helpsLearn and do

Old tokens never change, because of the causal mask

Why is it safe to keep old results? Because of the causal mask.

import math
import torch


def attend(x: torch.Tensor, causal: bool = True) -> torch.Tensor:
    """x: (T, d), each token's query, key and value. Returns (T, d)."""
    T = x.size(0)
    att = x @ x.T / math.sqrt(x.size(1))
    if causal:
        mask = torch.ones(T, T, dtype=torch.bool).tril()
        att = att.masked_fill(~mask, float("-inf"))
    return att.softmax(dim=-1) @ x


torch.manual_seed(0)
# 5 tokens, 4 numbers each
x = torch.randn(5, 4)
print(torch.allclose(attend(x[:4]), attend(x)[:4]))
print(torch.allclose(attend(x[:4], causal=False), attend(x, causal=False)[:4]))
Predict

Run attend on the first 4 tokens, then on all 5, and compare the first 4 outputs. What do the two lines print, with the mask and without it?

Pick one to see what it prints.
Pick an answer above to see the rest