KatInterview

Building and Analyzing Scaled Dot-Product Attention

Machine LearningModel answer
HardModel answerMachine Learningdeep learningattentionpytorch

Last updated

Implement a production-grade multi-head attention module in PyTorch, handle numerical precision and causal masking, and analyze performance trade-offs for large sequences.

In modern Transformer architectures, scaled dot-product attention serves as the core building block for context modeling.

  1. Implementation: Write a complete, vectorized PyTorch implementation of Multi-Head Scaled Dot-Product Attention (MHA) from scratch using torch.nn.Module. Your implementation should support arbitrary batch dimensions, arbitrary sequence lengths, linear projection layers, optional dropout, dynamic padding masks, and causal masking options.
  2. Numerical & Architectural Details:
    • Explain why the scaling factor $1 / \sqrt{d_k}$ is mathematically necessary.
    • Explain how to maintain numerical stability during mixed-precision execution (e.g., FP16/BF16) when applying soft-max over masked entries.
    • Explain the gradient implications when adding a static linear bias to key vectors.
  3. Complexity & Scaling: Analyze the computational complexity (FLOPs) and memory footprint with respect to sequence length $N$ and hidden dimension $D$. Describe two algorithmic strategies used to scale attention to long context lengths ($N \gg 10^4$).

Hints

Hint 1

Recall that the variance of the dot product of two independent random vectors with zero mean and variance 1 scales with the vector dimension.

Hint 2

Consider how -inf values interact with float16 range limits and how subtraction of maximum row values stabilizes exponentiation.

Hint 3

For memory analysis, pay attention to the space required to store intermediate attention matrices during the forward pass for backpropagation.