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 with batch size
, sequence length
, model dimension
, and
heads of size
. 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
.
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)
Figure 1: the input and output contract is fixed at , the fused projection is given, and the three layout-sensitive steps in between are yours to write without any fused attention call.
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 , not
.
(3) Dtype-Safe Causal Mask: Slice the registered lower-triangular buffer to and fill blocked positions with the dtype's finite minimum before key-axis softmax.
(4) Contiguous Merge: Transpose heads back beside and restore contiguity before flattening to
.
2Visual Review Map (Figure 2)

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:
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)?
D (so unscaled variance grows as D, not C). Which two axes of k must transpose so q @ ... produces (B, H, T, T)?
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.
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?