REAL PYTORCH · CPU TRAINING AND AUTOGRAD
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.
Run this Lab in Pythilo
Open Labs, choose its topic and tap Download entire topic, or Download entire category for all its Labs, including the required Python packages, then load the starter or worked answer and tap Trace. Progress, pause, resume and removal are in Downloads. Independent checks execute real CPU training and gradients.
No GPU, external model weights or API key is required. After downloading the topic and packages, this Lab runs offline.
PyTorch is unavailable in this browser runtime. The code and lessons are readable here; execution and checks run in the app.
Pythilo on the App Store →Read lesson: Isolate packed documents in causal attention →
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.
Starter
import torch
def packed_attention(q, k, v, segments):
return NoneInspect the worked answer
import math
import torch
def packed_attention(q, k, v, segments):
if q.ndim != 4 or q.shape != k.shape or k.shape != v.shape or min(q.shape) < 1:
raise ValueError('aligned nonempty [B,H,T,D] tensors required')
if segments.shape != (q.shape[0], q.shape[2]) or segments.dtype != torch.long or bool((segments < -1).any()):
raise ValueError('integer document identities or -1 padding required')
length = q.shape[2]
same = segments[:, :, None] == segments[:, None, :]
valid = (segments[:, :, None] >= 0) & (segments[:, None, :] >= 0)
causal = torch.ones(length, length, dtype=torch.bool, device=q.device).tril()
allow = (same & valid & causal)[:, None, :, :]
active = allow.any(dim=-1, keepdim=True)
scores = q @ k.transpose(-2, -1) / math.sqrt(q.shape[-1])
scores = scores.masked_fill(~allow, float('-inf'))
scores = torch.where(active, scores, torch.zeros_like(scores))
weights = torch.softmax(scores, dim=-1) * allow.to(scores.dtype)
return weights @ v