---
title: Implement multi-head causal self-attention from scratch in PyTorch or JAX, without built-in attention functions. Be…
url: https://gurkanozkan.ai/learn/questions/research-multi-head-causal-self-attention-033/
markdown: https://gurkanozkan.ai/learn/questions/research-multi-head-causal-self-attention-033.md
kind: question
role: Research
stage: Coding
difficulty: Medium
json: https://gurkanozkan.ai/api/learn/questions/research-multi-head-causal-self-attention-033.json
robots: noindex
---

# Implement multi-head causal self-attention from scratch in PyTorch or JAX, without built-in attention functions. Be explicit about tensor shapes, the mask and the output projection.

Research · Coding · Medium

Theme reported publicly: [Anthropic](https://www.sundeepteki.org/advice)

## Answer

*Model answer, written in a candidate's voice*

### In short

- Project x (B,T,C) to Q,K,V (B,T,H*D), reshape to (B,T,H,D), transpose to (B,H,T,D).
- Compute scores q@k^T/sqrt(D) with shape (B,H,T,T); add causal mask (j<=i allowed, else -inf) before softmax over key axis.
- Apply softmax, optional dropout, weighted sum with V, transpose back and merge heads with reshape (not view: the tensor is non-contiguous) to (B,T,H*D), then output projection to (B,T,C).
- State cost: attention scores and weighted sum are O(B*H*T^2*D) = O(B*T^2*C), with O(B*H*T^2) attention-matrix memory.
- Validate on small random inputs against a reference such as F.scaled_dot_product_attention(is_causal=True), checking shapes, masked positions, and allclose outputs.

### In full

I would start from x of shape (B,T,C) and use three linear projections to get Q,K,V of shape (B,T,H*D), reshape each to (B,T,H,D), then transpose(1,2) to (B,H,T,D). Scores are q @ k.transpose(-2,-1) / sqrt(D), giving (B,H,T,T); I add a causal mask of shape (T,T) or (1,1,T,T) with 0 for allowed key positions j<=i and -inf for j>i before softmax, and softmax is over the last key axis. After softmax, optionally dropout the attention weights, then compute attn @ v to get (B,H,T,D), transpose back to (B,T,H,D), reshape to (B,T,H*D), and apply an output linear projection W_o from H*D to C to produce (B,T,C). The transpose leaves the tensor non-contiguous, so merging heads needs reshape (or .contiguous().view), not a bare view.

```python
import math, torch
import torch.nn as nn

class CausalSelfAttention(nn.Module):
    def __init__(self, C, H, p_drop=0.0):
        super().__init__()
        assert C % H == 0
        self.H, self.D = H, C // H
        self.qkv = nn.Linear(C, 3 * C)          # W_q, W_k, W_v fused
        self.proj = nn.Linear(C, C)             # output projection W_o
        self.drop = nn.Dropout(p_drop)

    def forward(self, x):                       # x: (B, T, C)
        B, T, C = x.shape
        q, k, v = self.qkv(x).split(C, dim=-1)  # each (B, T, C)
        q, k, v = (t.view(B, T, self.H, self.D).transpose(1, 2) for t in (q, k, v))  # (B, H, T, D)
        att = q @ k.transpose(-2, -1) / math.sqrt(self.D)                       # (B, H, T, T)
        mask = torch.tril(torch.ones(T, T, dtype=torch.bool, device=x.device))  # j <= i allowed
        att = att.masked_fill(~mask, float("-inf"))                             # mask BEFORE softmax
        att = self.drop(att.softmax(dim=-1))                                    # over the key axis
        y = att @ v                                                             # (B, H, T, D)
        y = y.transpose(1, 2).reshape(B, T, C)  # non-contiguous after transpose: reshape, not view
        return self.proj(y)                                                     # (B, T, C)
```

The compute is O(B*H*T^2*D), i.e. O(B*T^2*C) since H*D=C, and the attention matrix costs O(B*H*T^2) memory unless a memory-efficient kernel is used. I would test it on small random inputs with fixed seeds by comparing against a reference implementation such as PyTorch's F.scaled_dot_product_attention with is_causal=True, checking tensor shapes, that disallowed positions are masked before softmax, and that outputs match within tolerance.

*Corrected by an independent AI reviewer.*

## What a strong answer covers

- Q, K and V projections; reshape (B,T,H,D) → (B,H,T,D).
- Scores QKᵀ/√D; causal mask set to −inf *before* softmax; softmax over the key axis.
- Weighted sum, merge heads, output projection, optional dropout.
- States the O(T²D) cost.
- Tests against a reference implementation on small inputs.

## Common mistakes

- Softmax over the wrong axis, or masking after softmax.
- Using `view` on non-contiguous tensors.

## Topic guides

- [Coding for ML and LLM engineering](https://gurkanozkan.ai/learn/topics/coding-engineering.md)
- [Transformers, attention and scaling](https://gurkanozkan.ai/learn/topics/transformers.md)
---

*Study material compiled with AI: drafted by a local model (Inkling 2 Mini) from public sources, then checked against those sources by independent AI reviewers (Claude) in November 2026. Not reviewed line by line by a person.*
