Practice in Lab: Mask attention with finite empty-row gradients →
Mask attention with finite empty-row gradients
Causal, padding and authorization constraints eventually become a participation mask over attention scores. Mask meaning varies between APIs, so this exercise explicitly uses true for an admitted key. A row with no admitted key is an important edge case: ordinary softmax of all negative infinity produces an undefined intermediate. The implementation must avoid that intermediate before multiplying the final mask. Checks examine finite backward values and forbidden-key gradients as well as forward outputs, so replacing a visible NaN after an invalid computation is insufficient.
import torch
allow = torch.tensor([[True, False]])
print(allow.any(-1, keepdim=True))Review the design
Mask semantics and the loss denominator are separate contracts. Fused backends and mixed precision need their own numerical and performance validation.
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.
The explanation opens here once every check passes.