PythiloLesson 4 of 9 · progress kept in this browser

Practice in Lab: Isolate packed documents in causal attention →

Isolate packed documents in causal attention

Packing several documents into one tensor improves utilization, but a causal triangle alone permits one document to read an earlier unrelated document. Attention must combine ordering, document identity and padding. The loss needs a separate boundary rule for next-token targets; an attention mask does not prevent scoring a document transition as a target. This Lab perturbs one packed document and checks another document’s output and gradients. Padding creates fully forbidden query rows, which must remain finite during backward rather than being hidden after an undefined softmax.

import torch
ids = torch.tensor([0, 0, 1, -1])
same = ids[:, None] == ids[None, :]
print(same & (ids[:, None] >= 0))
This example uses torch. Run it in the Pythilo app, where these features are available.
Your task

q,k,v have aligned nonempty [B,H,T,D] shapes. Long segments[B,T] assigns document identities or -1 padding. A query may see only earlier-or-equal positions with the same nonnegative document identity. Return differentiable attention output. Padded queries produce finite zero outputs and zero gradients. Block cross-document influence even when both documents share one row; reject invalid shapes or segment values below -1.

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.