REAL PYTORCH · CPU TRAINING AND AUTOGRAD
Mask attention with finite empty-row gradients
Causal, padding and authorization constraints eventually become a participation mask over attention scores.
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: Mask attention with finite empty-row gradients →
Your task
For aligned q[B,H,Q,D], k[B,H,K,D], v[B,H,K,V], compute softmax(q@k.T/sqrt(D)) over allowed keys, then multiply by v. allow is boolean [B,1-or-H,Q,K], True means participate. Return output and weights. A fully forbidden query must produce zero weights/output and finite zero gradients, not NaN. Validate nonempty dimensions and exact mask shape/type. Use actual differentiable tensor operations; dropout is zero.
Starter
import torch
def masked_attention(q, k, v, allow):
return NoneInspect the worked answer
import math
import torch
def masked_attention(q, k, v, allow):
if q.ndim != 4 or k.ndim != 4 or v.ndim != 4 or k.shape[:3] != v.shape[:3] or q.shape[:2] != k.shape[:2] or q.shape[-1] != k.shape[-1]:
raise ValueError('aligned batch, head and attention dimensions required')
b, h, length, width = q.shape
if not width or not length or k.shape[2] == 0:
raise ValueError('nonempty queries and keys required')
if allow.dtype != torch.bool or allow.ndim != 4 or allow.shape[0] != b or allow.shape[1] not in (1, h) or allow.shape[2:] != (length, k.shape[2]):
raise ValueError('boolean [B,1-or-H,Q,K] participation mask required')
scores = q @ k.transpose(-2, -1) / math.sqrt(width)
active = allow.any(dim=-1, keepdim=True)
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, weights