Category: Build & Trace

  • CD0003 Multi-Head Attention From Scratch

    Mode B · Build & Trace 30 Min PyTorch 2.x 4 Tensor Blanks

    Anthropic's model teams build the transformer blocks behind Claude from first principles, and their coding rounds test whether you can re-derive the attention stack rather than call it. In that interview, you must implement a batched causal Multi-Head Self-Attention module, CausalSelfAttention, in PyTorch from scratch. You may use only nn.Linear, tensor reshape and transpose operations, torch.matmul, and F.softmax. Calling nn.MultiheadAttention or F.scaled_dot_product_attention inside the forward pass is forbidden.

    The input has shape (B, T, C) with batch size B, sequence length T, model dimension C, and H heads of size D = C / H. Your module must project queries, keys, and values with one fused linear layer, split heads without corrupting token order, apply scaled dot-product attention with a causal mask, and merge the heads back to (B, T, C).

    Complete the 4 missing tensor operations in the skeleton below and trace the exact tensor shape after each line. Then compute the activation and KV-cache memory footprint in FP16, and verify your module against F.scaled_dot_product_attention(..., is_causal=True) using torch.testing.assert_close.

    Skeleton Code (Fill Blanks 1-4):

    01  import math
    02  import torch
    03  import torch.nn as nn
    04  import torch.nn.functional as F
    05
    06
    07  class CausalSelfAttention(nn.Module):
    08      def __init__(self, C: int, H: int, max_T: int = 1024):
    09          super().__init__()
    10          assert C % H == 0, "C must be divisible by H"
    11          self.H, self.D = H, C // H
    12          self.qkv = nn.Linear(C, 3 * C)    # fused Q, K, V projection
    13          self.proj = nn.Linear(C, C)       # output projection
    14          mask = torch.tril(torch.ones(max_T, max_T, dtype=torch.bool))
    15          self.register_buffer("mask", mask.view(1, 1, max_T, max_T),
    16                               persistent=False)
    17
    18      def forward(self, x: torch.Tensor) -> torch.Tensor:
    19          B, T, C = x.shape                 # x: (B, T, C)
    20          H, D = self.H, self.D
    21          # TODO (Blank 1): fused QKV projection, split into q, k, v
    22          #                 each of shape (B, H, T, D)
    23          q, k, v = ...
    24          # TODO (Blank 2): scaled attention scores, shape (B, H, T, T)
    25          scores = ...
    26          # TODO (Blank 3): apply causal mask to scores, then normalize weights
    27          attn = ...
    28          # TODO (Blank 4): weighted sum of values, merge heads to (B, T, C)
    29          y = ...
    30          return self.proj(y)               # (B, T, C)
    Operator contract for causal self-attention: input x of shape (B, T, C) flows through a fused QKV linear layer, then three question-marked steps (split into heads, scaled scores with causal mask, merge heads), then an output projection back to (B, T, C); below, boxes list the forbidden calls, the allowed building blocks, and the SDPA test oracle

    Figure 1: the input and output contract is fixed at (B, T, C), the fused projection is given, and the three layout-sensitive steps in between are yours to write without any fused attention call.

    Interactive PyTorch Workspace: Switch to the split-screen workspace to fill Blanks 1-4 in the live editor and verify against the SDPA oracle.

    Open in Colab ↗
    Progressive Hints (Free · Zero Spoilers)
    1Inspection Checklist (Where to Look)

    (1) Layout-Respecting Split: Split the fused projection along its existing memory order before permuting the head axis forward.
    (2) Variance-Preserving Scale: Scale dot products by the per-head dimension \sqrt{D}, not \sqrt{C}.
    (3) Dtype-Safe Causal Mask: Slice the registered lower-triangular buffer to T and fill blocked positions with the dtype's finite minimum before key-axis softmax.
    (4) Contiguous Merge: Transpose heads back beside D and restore contiguity before flattening to (B, T, C).

    2Visual Review Map (Figure 2)
    Shape trace for causal self-attention: the top row marks Blank 1's target shapes from x (B, T, C) through the fused projection and its head-split intermediates to q, k, v of (B, H, T, D); the bottom row shows the target shapes Blanks 2 to 4 must produce

    Figure 2: The shape trace a strong candidate narrates aloud. Every blank shows the target shapes it must produce; writing the ops that reach them is the exercise.

    3Interviewer Nudge & Line Focus

    Pin the exact input/output shape and memory stride of each blank before writing the PyTorch op:

    Blank 1 (Fused QKV Split): self.qkv(x) has shape (B, T, 3 * C) with Q, K, and V stored as 3 blocks of width C = H * D. Must your 5D .view(...) place (3, H, D) or (H, 3, D) at the tail before permuting to (3, B, H, T, D)?
    Blank 2 (Scaled Dot-Product): Each head dot-products vectors of length D (so unscaled variance grows as D, not C). Which two axes of k must transpose so q @ ... produces (B, H, T, T)?
    Blank 3 (Mask + Softmax): Slice self.mask from max_T down to :T, :T, invert the boolean mask to target future keys j > i, fill with torch.finfo(scores.dtype).min, and normalize along the key axis.
    Blank 4 (Head Merge): attn @ v has shape (B, H, T, D). Why does calling .view(B, T, C) directly after .transpose(1, 2) crash whenever T > 1, even though a toy test at T = 1 lets it slip by?
    Answer
    Login to view more content