PythiloLesson 1 of 9 · progress kept in this browser

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))
This example uses torch. Run it in the Pythilo app, where these features are available.
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.

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.