Masks: causality, padding and additive biases
Build causal, padding, and document masks as additive biases before softmax. Study parallel autoregressive training, packed sequences, empty rows, numerical safety, ALiBi, and FlexAttention.
After this lesson you can
- Construct and combine causal, padding, and document masks using broadcasting.
- Prove that causal attention at position t depends only on earlier inputs and verify it with gradients.
- Explain parallel autoregressive training with shifted targets.
- Diagnose fully masked rows and NaNs and apply numerically safe solutions.
- Express masks and positional biases as additive score biases.
Before you start
See only what is allowed
A language model predicts the next token from the prefix. During training you know the entire sequence and want to calculate all predictions simultaneously, but a position must not query future tokens. The previous lesson’s scaled attention lets each query see all keys; now we restrict its connections.
The figure uses explicit scores , three lengths, and two documents of three positions. These are not model measurements. Rules are combined by conjunction: a connection survives only if every active rule allows it. To make the edge case visible, padding queries are also masked; the figure returns zeros in their empty rows, which are not probability distributions and must be excluded from the loss.
A mask is a bias before normalization
For query and key , let . An additive attention bias modifies the calculation to row-wise. For a Boolean mask, if the connection is valid and if it is forbidden. Provided at least one valid key exists, and mass is redistributed among the remaining keys.
Multiplying by zero after softmax is insufficient: if a row originally assigns and you forbid the last key, sums to 0.5. Renormalizing over valid keys could reconstruct the mathematical result, but must explicitly handle empty rows and is not equivalent to omitting that renormalization. Before normalization the mask can also be combined with finite biases, for example a distance cost.
The causal mask allows and blocks : it is a lower triangular matrix when queries and keys share positions. Index queries the present and preceding tokens. With a cache or different query and key lengths, absolute indices must be aligned: a rectangular triangular mask without that offset may represent a different causal relation.
Causality of a layer and a stack
If depends only on and each only on , the output depends exclusively on . Its scores and softmax denominator also use only those positions. By induction, if every layer is causal and its normalizations and MLP operate per position, its outputs preserve that property; a local residual connection preserves it too. A mask within attention is insufficient if another operation mixes the entire sequence.
The figure calculates central differences with step for scalar attention and six fixed inputs. Bars are absolute approximate derivatives rounded to three decimals, not a universal proof. Subtracting the mean of the entire sequence before attention lets a future input change even earlier representations: the mask cannot undo this leakage. By contrast, normalization over each token’s features does not mix positions. The lab verifies causality through perturbations and automatic gradients.
Parallel predictions and shifted targets
Autoregressive factorization writes . With teacher forcing, known inputs are, for example, and targets are . The causal mask prevents row from reading later inputs, and the losses are calculated in parallel. Parallel autoregressive training does not remove the sequential dependency of generation, where the next token is not yet known.
The figure compares dependency schedules, not times or trained architectures. An RNN computes consecutive sequence states, although its internal products and batch examples may run in parallel. In a transformer, each causal layer computes its positions simultaneously; layers remain sequential with respect to one another. If inputs and targets are not shifted, a position can see exactly the token it is trying to predict and learn a trivial copy.
Padding, documents, and windows
The padding mask prevents a valid query from assigning mass to positions added to equalize batch lengths. Padding queries must also be excluded from the loss. With right padding, a dummy query row may have earlier valid keys, but its output must not be treated as a real prediction. With left padding, blocking padding keys while applying causality can leave the first dummy rows empty.
The packed-document mask lets read only when both have the same document ID. Combined with causality it produces triangular blocks; without it, a later document can read text from an earlier one. This can be a deliberate corpus decision, but is not equivalent to training on independent documents. Full equivalence also requires controlling positions, boundary targets, and any operation that mixes documents.
A causal window of size permits . ALiBi adds, for a head with positive slope , a finite bias at causal positions; by itself it does not replace the mask that prevents seeing the future. FlexAttention distinguishes score modifications from a BlockMask: the latter can skip completely forbidden blocks. Savings depend on block shape, not only the percentage of forbidden elements.
Empty rows and numerical types
For a row of only , stable softmax calculates , an indeterminate operation that produces NaN. The relationship with special values and IEEE formats matters: cannot fit as a finite float16 number and may become or cause a conversion error. Replacing it with the minimum finite value avoids that overflow, but a complete row of equal finite values produces a uniform distribution, not a zero row. Even in mixed rows, a finite sentinel is not an absolute mathematical prohibition for arbitrary logits.
One safe policy is to check for valid keys, return zeros for an empty row, and exclude that output from the loss. That zero row must not be called a distribution. If every real query has at least one valid key, another approach is to process only real queries. In any case, do not ignore NaNs with a later average: prevent them or explicitly handle the empty case before normalization.
Lab: masks and a causality test
This code uses right padding and shape , which broadcasts over heads. doc_ids assigns a document to each position; padding positions are excluded by length. Dummy query rows are empty by design.
import numpy as np
def build_mask(lengths, causal=True, doc_ids=None):
lengths=np.asarray(lengths)
B=len(lengths)
T=doc_ids.shape[1] if doc_ids is not None else int(lengths.max(initial=0))
i=np.arange(T)[None,:,None]; j=np.arange(T)[None,None,:]
ok=(i<lengths[:,None,None]) & (j<lengths[:,None,None])
if causal: ok &= (j<=i)
if doc_ids is not None: ok &= doc_ids[:,:,None] == doc_ids[:,None,:]
return np.where(ok[:,None,:,:], 0., -np.inf)
docs=np.array([[0,0,0,1,1,1],[0,0,1,1,-1,-1],[0,0,-1,-1,-1,-1]])
mask=build_mask([6,4,2],True,docs)
print('forma:',mask.shape,'filas vacías:',np.isneginf(mask).all(axis=-1).sum())def safe_attention(x, bias):
s=x @ x.T / np.sqrt(x.shape[-1]) + bias
valid=np.isfinite(s).any(axis=-1,keepdims=True)
maximum=np.max(np.where(valid,s,0.),axis=-1,keepdims=True)
e=np.where(np.isfinite(s),np.exp(np.where(np.isfinite(s),s-maximum,-np.inf)),0.)
z=e.sum(axis=-1,keepdims=True)
return np.divide(e,z,out=np.zeros_like(e),where=z>0) @ x
rng=np.random.default_rng(18); x=rng.normal(size=(6,3))
bias=build_mask([6],True,np.zeros((1,6),int))[0,0]
y=safe_attention(x,bias); altered=x.copy(); altered[4:]+=10
yp=safe_attention(altered,bias)
print('máximo cambio de posiciones 1 a 4:',np.max(np.abs(y[:4]-yp[:4])))
assert np.allclose(y[:4],yp[:4])
empty=safe_attention(x, np.full((6,6),-np.inf))
assert np.isfinite(empty).all() and np.all(empty==0)PyTorch and sparse blocks
In scaled_dot_product_attention, a Boolean mask True means that the connection participates. This convention does not necessarily match other APIs. Compare the triangular mask with is_causal=True and verify zero future gradients. The optional FlexAttention block requires Linux, CUDA, Triton, and torch.compile; it compares a window implemented by score_mod with BlockMask, times both after compilation, and validates against SDPA. Mask construction and compilation are excluded from those timings, so they do not describe the cost of one call from scratch.
import sys, time
import torch
import torch.nn.functional as F
torch.manual_seed(18)
device='cuda' if torch.cuda.is_available() else 'cpu'
x=torch.randn(1,1,6,4,device=device,requires_grad=True)
tri=torch.ones(6,6,dtype=torch.bool,device=device).tril()
a=F.scaled_dot_product_attention(x,x,x,attn_mask=tri,dropout_p=0.)
b=F.scaled_dot_product_attention(x,x,x,is_causal=True,dropout_p=0.)
assert torch.allclose(a,b,atol=1e-5,rtol=1e-5)
grad=torch.autograd.grad(a[0,0,2].sum(),x)[0]
print('error máscaras:',(a-b).abs().max().item(),'gradiente futuro:',grad[0,0,3:].abs().max().item())
assert torch.allclose(grad[0,0,3:],torch.zeros_like(grad[0,0,3:]))
if sys.platform.startswith('linux') and torch.cuda.is_available():
import triton
from torch.nn.attention.flex_attention import flex_attention, create_block_mask
T=1024; W=128
q=torch.randn(1,4,T,32,device=device); k=torch.randn_like(q); v=torch.randn_like(q)
def window(b,h,qi,ki): return (qi>=ki)&(qi-ki<W)
def score_mod(score,b,h,qi,ki): return torch.where(window(b,h,qi,ki),score,-float('inf'))
block=create_block_mask(window,B=None,H=None,Q_LEN=T,KV_LEN=T,device=device)
flex=torch.compile(flex_attention)
dense=flex(q,k,v,score_mod=score_mod); sparse=flex(q,k,v,block_mask=block)
idx=torch.arange(T,device=device); allowed=(idx[:,None]>=idx[None,:])&((idx[:,None]-idx[None,:])<W)
reference=F.scaled_dot_product_attention(q,k,v,attn_mask=allowed,dropout_p=0.)
assert torch.allclose(sparse,reference,atol=2e-4,rtol=2e-4)
assert torch.allclose(dense,sparse,atol=2e-4,rtol=2e-4)
print('error Flex:',(sparse-reference).abs().max().item(),'bloques omitidos (%):',block.sparsity())
for label,kw in [('score_mod',dict(score_mod=score_mod)),('block_mask',dict(block_mask=block))]:
for _ in range(5): flex(q,k,v,**kw)
torch.cuda.synchronize(); start=time.perf_counter()
for _ in range(30): flex(q,k,v,**kw)
torch.cuda.synchronize(); print(label,'segundos:',(time.perf_counter()-start)/30)
else:
print('FlexAttention compilado requiere el entorno Linux CUDA con Triton.')npm run lab and open the connection link.The reference run for this lesson was also checked on Linux with CUDA and Triton: a 128-position window over 1024 had maximum error of approximately against SDPA. BlockMask.sparsity() reports 76.5625% skipped blocks in that configuration, compared with 88.2751% forbidden elements. Times depend on GPU, compilation, shape, and workload; repeat the measurement in your environment and count setup cost if the mask is not reused.
Exercises
Step 1 of 2. On which inputs does an attention output at t depend?
import numpy as np
def build_mask(lengths, causal, doc_ids):
pass