As asked
Write a function that computes scaled dot-product attention given Q, K, V tensors and an optional causal mask. Handle the scaling, masking, and softmax correctly. Then describe how you would test it.
Sample answer outline
The function should compute scores as Q @ K.transpose(-2, -1) / sqrt(d_k), add the causal mask (large negative values at masked positions before softmax), apply softmax over the key dimension, then multiply by V. Testing should include shape assertions, checking that the causal mask prevents future token attention by verifying upper-triangle outputs are zeroed post-softmax, and numerical comparison with torch.nn.functional.scaled_dot_product_attention on the same inputs.
Reference implementation (python)
import torch
import torch.nn.functional as F
import math
def scaled_dot_product_attention(
q: torch.Tensor, # (batch, heads, seq_q, d_k)
k: torch.Tensor, # (batch, heads, seq_k, d_k)
v: torch.Tensor, # (batch, heads, seq_k, d_v)
causal: bool = False
) -> torch.Tensor:
# TODO: implement this
passExpect these follow-ups
- How would you extend this to multi-head attention?
- What changes are needed to make this numerically stable for very large or very small d_k values?