I got through the core implementation fine but stumbled when they pushed on shapes during the head-split step.
Start by outlining the overall architecture and tensor shapes, then implement each component step-by-step with clear comments on shape transformations. Emphasize the mathematical operations and complexity, and discuss practical considerations like masking and numerical stability.
Pro tip: Demonstrate awareness of production concerns by mentioning memory-efficient attention variants (e.g., FlashAttention) and how mixed precision affects softmax stability, showing you think beyond the basic implementation.
Restate the problem: implement multi-head self-attention with optional masks. Sketch the high-level flow: linear projections, head splitting, attention, concatenation, output projection.
Write code for Q, K, V linear layers. Reshape and transpose to split into h heads. Track shapes: (batch, seq, d_model) -> (batch, seq, h, d_k) -> (batch, h, seq, d_k).
Compute scores = Q @ K^T / sqrt(d_k), apply padding and causal masks, softmax, then weighted sum with V. Handle mask broadcasting and numerical stability.
Transpose and reshape heads back to (batch, seq, d_model), then apply final linear layer. Verify shapes match input.
Discuss time O(n^2 d) and memory O(n^2 + n d) complexity. Explain softmax scaling, mask handling, and mixed precision concerns (e.g., using float32 for softmax).
AI-generated suggestions, not part of the candidate's original notes. May be inaccurate — verify before relying on them.