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 None
Inspect 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

About this algorithm

How Mask attention with finite empty-row gradients works

The idea

Every rule about which tokens may attend to which, such as causal order, padding or access control, ends up as one boolean mask over query and key pairs. Here allow is True where a key may take part. Forbidden pairs get a score of -inf before the softmax, so their weight is exactly zero.

The trap is a query with no allowed key at all. Its row holds only -inf, the softmax has nothing to normalize and returns NaN, and that NaN spreads through the backward pass into everything. The fix is to detect such rows with allow.any(dim=-1), give them finite zero scores, and multiply the weights by allow afterwards. The row then produces zero output and finite zero gradients.

How it works

  1. Validate that q, k and v are aligned four-dimensional tensors and that allow is a boolean [B, 1 or H, Q, K] tensor, raising ValueError otherwise.
  2. Compute scores = q @ k.transpose(-2, -1) / math.sqrt(width).
  3. Record active = allow.any(dim=-1, keepdim=True), which is False for a query row with no permitted key.
  4. Fill forbidden positions with -inf, then use torch.where to replace inactive rows with zeros.
  5. Apply torch.softmax over the keys and multiply by allow, which zeroes every weight in an inactive row.
  6. Return weights @ v together with weights.

What it costs

Time
O(B·H·Q·K·D)
Memory
O(B·H·Q·K) scores

The score tensor holds one number for every query and key pair in every head, which is the quadratic term that limits sequence length.

Where it is used

  • torch.nn.functional.scaled_dot_product_attention accepts a boolean attn_mask in which True marks positions that take part in attention.
  • Hugging Face Transformers models take an attention_mask so that padding tokens in a batch are ignored.
  • torch.nn.MultiheadAttention takes key_padding_mask and attn_mask arguments to exclude padding and future positions.

Watch out for

  • Filling with -inf and calling softmax directly: a row with every key forbidden returns NaN, and backward() carries NaN into q, k and v.
  • Mixing up mask polarity: here True means participate, while torch.nn.MultiheadAttention treats True in a boolean mask as not allowed.
  • Accepting a float mask of ones and zeros: the Lab requires torch.bool and expects a ValueError for anything else.