Module contents
Lesson 3 of 22Core 80 min

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.

InteractiveMask composer

Allowed: 1 yes, 0 no

1.00
0.00
0.00
0.00
0.00
0.00
1.00
1.00
0.00
0.00
0.00
0.00
1.00
1.00
1.00
0.00
0.00
0.00
1.00
1.00
1.00
1.00
0.00
0.00
1.00
1.00
1.00
1.00
1.00
0.00
1.00
1.00
1.00
1.00
1.00
1.00

Normalized weights

1.00
0.00
0.00
0.00
0.00
0.00
0.39
0.61
0.00
0.00
0.00
0.00
0.13
0.34
0.53
0.00
0.00
0.00
0.07
0.12
0.31
0.50
0.00
0.00
0.09
0.06
0.11
0.29
0.45
0.00
0.18
0.07
0.05
0.09
0.23
0.37
2
Empty rows0
Documents1-3 / 4-6
Select a sequence and combine causality, padding, documents, and a window. Each row is a query; compare allowed connections with the weights and observe empty rows.

The figure uses explicit scores cos⁡(i−j)\cos(i-j), 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 ii and key jj, let Sij=qi⊤kj/dkS_{ij}=\vb{q}_i\T\vb{k}_j/\sqrt{d_k}. An additive attention bias modifies the calculation to A=softmax⁡(S+M)A=\softmax(S+M) row-wise. For a Boolean mask, Mij=0M_{ij}=0 if the connection is valid and −∞-\infty if it is forbidden. Provided at least one valid key exists, e−∞=0e^{-\infty}=0 and mass is redistributed among the remaining keys.

Multiplying by zero after softmax is insufficient: if a row originally assigns (0.2,0.3,0.5)(0.2,0.3,0.5) and you forbid the last key, (0.2,0.3,0)(0.2,0.3,0) 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 j≤ij\le i and blocks j>ij>i: it is a lower triangular matrix when queries and keys share positions. Index ii 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 qtq_t depends only on xtx_t and each kj,vjk_j,v_j only on xjx_j, the output yt=∑j≤tatjvjy_t=\sum_{j\le t}a_{tj}v_j depends exclusively on x1,…,xtx_1,\ldots,x_t. 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.

InteractiveWho influences whom?
00.511.5x10.063x20.078x31.315x40x50x60
3
Sum of sensitivities to future inputs0.00000
Choose the output and compare sensitivity to each input. Enable the global mean to introduce leakage despite the causal mask.

The figure calculates central differences with step 10−510^{-5} 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 p(x1,…,xT)=∏tp(xt∣x<t)p(x_1,\ldots,x_T)=\prod_t p(x_t\mid x_{<t}). With teacher forcing, known inputs are, for example, (BOS,x1,…,xT−1)(\mathrm{BOS},x_1,\ldots,x_{T-1}) and targets are (x1,…,xT)(x_1,\ldots,x_T). The causal mask prevents row tt from reading later inputs, and the TT losses are calculated in parallel. Parallel autoregressive training does not remove the sequential dependency of generation, where the next token is not yet known.

InteractiveT predictions in one pass
Recurrent order
0t10t20t30t40t50t60
Parallel order
0t10t20t30t40t50t60
step 0
Available recurrent losses0 / 6
Available parallel losses0 / 6
Play the schedule: the same fixed probability table is evaluated in two computation orders. Equal losses come from using the same logits, not from different trained RNNs and transformers matching.

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 ii read jj 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 ww permits 0≤i−j<w0\le i-j<w. ALiBi adds, for a head with positive slope mhm_h, a finite bias −mh(i−j)-m_h(i-j) 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 −∞-\infty, stable softmax calculates −∞−(−∞)-\infty-(-\infty), an indeterminate operation that produces NaN. The relationship with special values and IEEE formats matters: −109-10^9 cannot fit as a finite float16 number and may become −∞-\infty 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 (B,1,T,T)(B,1,T,T), 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.

[ ]Build and combine masksBrowser
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())
[ ]Safe softmax and future perturbationBrowser
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.

[ ]SDPA, gradients, and FlexAttentionLocal GPU
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.')
This cell needs the local lab (PyTorch with your GPU). Start it with 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 2.6⋅10−62.6\cdot10^{-6} 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

Proof
Prove: A stack of causal attention and per-position MLPs is causal.
0
Assume projections, normalization, and residual connections are local to each position.

Step 1 of 2. On which inputs does an attention output at t depend?

Numeric
For T=1024, what fraction of square-matrix entries is allowed by a causal mask that includes the diagonal?
Numeric
For the same matrix, what fraction of entries is forbidden and would be calculated unnecessarily if the full dense product were materialized?
Quiz
How are positions added as padding treated, on both the left and right?
Code
Implement build_mask(lengths, causal, doc_ids) for right padding. doc_ids is an array of shape (B,T). Return a bias of shape (B,1,T,T), zero only for real queries and keys in the same document and, when causal is True, j≤i; return -inf elsewhere.
import numpy as np
def build_mask(lengths, causal, doc_ids):
  pass
Shift+Enter to run
Key idea
A mask specifies valid connections and is added to the logits before normalization. Causality of the entire network requires every operation to respect the prefix; padding, documents, and empty rows must be handled in both attention and the loss.