Scaled dot product and mask
Quick answer
Scaled dot-product attention divides scores by the square root of key width and excludes forbidden positions before softmax. Causal and padding masks solve different problems. Examples are static Python snippets tested locally on CPU; PyTorch is required for selected examples. ByteMind execution is unverified.
Combined allowed mask
valid=[True,True,False]print([[int(j<=i and valid[j]) for j in range(3)] for i in range(3)])Expected output (locally tested): [[1, 0, 0], [1, 1, 0], [1, 1, 0]]. The padded query row still exists; ignore its output if it is invalid.
How it works
Compute scores QK^T/sqrt(d_k), then normalize allowed scores over the S source positions and multiply by V. For independent unit-variance coordinates the dot-product variance grows with d_k; division by sqrt(d_k) controls that scale under the assumption, not every possible input. A causal mask for ordinary square self-attention permits key j only when j <= query i; this prevents dependence on future tokens in autoregressive prediction. A padding mask excludes invalid source positions regardless of time. Combine the allowed conditions by logical AND. A key padding mask does not automatically zero padded query outputs; exclude those outputs from pooling or loss. PyTorch functional scaled_dot_product_attention Boolean True means allowed; nn.MultiheadAttention Boolean attn_mask and key_padding_mask True means blocked. Never pass one convention blindly into the other. The functional API applies the supplied dropout probability even in evaluation, so pass zero there. In this course reject all-masked rows in hand implementations; library behavior can differ by operation and version.
Native functional mask
import torchfrom torch.nn.functional import scaled_dot_product_attention as sdpaq=torch.zeros(1,1,1,2);k=torch.zeros(1,1,3,2);v=torch.tensor([[[[2.],[6.],[99.]]]])mask=torch.tensor([[True,True,False]])print(sdpa(q,k,v,attn_mask=mask,dropout_p=0.).flatten().tolist())Expected output (locally tested): [4.0]. Equal allowed logits average values 2 and 6; 99 is blocked.
Common mistakes
Do not multiply disallowed logits by zero before softmax: zero logits still receive mass. Do not substitute a padding mask for a causal mask, or confuse True means allowed with True means blocked.
Practice and next steps
For three time steps with valid keys [1,1,0], write the combined allowed matrix. Check that the last key never receives weight and the first query cannot read the second.
Check Your Understanding
Solidify your learning with the interactive assessment directly below this lesson.
Concept Quiz & Questions
Scaled dot product and mask — knowledge check
Apply scaled dot product and mask to small examples and debugging scenarios.
Why divide by sqrt(d_k)?
What does a causal mask block?
What does functional SDPA Boolean True mean?
Does a key padding mask zero padded query outputs?
How combine causal and padding allow masks?