KatInterview

Build a Scaled Dot-Product Multi-Head Attention Block

Machine LearningModel answer
MediumModel answerMachine Learningpytorchattentiontransformers

Last updated

Write a PyTorch multi-head self-attention module that projects, splits into heads, attends, merges, and projects back to the input shape.

Task: Write a Multi-Head Self-Attention Module

Using PyTorch, implement a MultiHeadAttention nn.Module that takes an input tensor x of shape (batch_size, seq_len, embed_dim) and returns a tensor with the identical shape.

Your implementation must:

  1. Project to Q, K, V. Apply three independent linear layers (no bias sharing between them) to produce query, key, and value tensors, each of shape (batch_size, seq_len, embed_dim).
  2. Split into heads. Reorganize each of Q, K, V into (batch_size, num_heads, seq_len, head_dim), where head_dim = embed_dim // num_heads.
  3. Attend. Compute softmax((Q @ K.transpose(-2, -1)) / sqrt(head_dim)) @ V using torch.softmax.
  4. Merge and project. Concatenate the per-head outputs back along the feature axis and pass the result through one final linear layer.

Required signature

import torch
import torch.nn as nn

class MultiHeadAttention(nn.Module):
    def __init__(self, embed_dim, num_heads):
        super().__init__()
        pass

    def forward(self, x):
        pass

Constraints

  • embed_dim must be divisible by num_heads; otherwise raise an error.
  • Use torch.softmax for the attention weights.
  • Do not hardcode batch size or sequence length — any batch size must work.

Example

mha = MultiHeadAttention(embed_dim=512, num_heads=8)
x = torch.randn(32, 10, 512)
assert mha(x).shape == (32, 10, 512)

Edge cases to reason about

  • seq_len == 1.
  • batch_size == 1 and other arbitrary batch sizes.
  • An embed_dim that is not divisible by num_heads.

Discuss in your answer: the shape at each step, why the 1/sqrt(head_dim) scaling is needed, the computational cost, and how padding or causal masks would be applied.

Hints

Hint 1

The key trick is the layout `(B, H, L, d)` — with that arrangement, `torch.matmul` batches over `(B, H)` automatically, so no Python loop over heads is needed.

Hint 2

To merge heads, transpose dimensions 1 and 2 back, then flatten the last two dimensions; use `reshape` (or call `.contiguous()` before `view`) because the transposed tensor is not contiguous.

Hint 3

Softmax must be applied over the key axis (`dim=-1`), and masked positions should be filled with `-inf` *before* the softmax so they receive zero weight.