---
title: Multi-head self-attention forward pass
url: https://gurkanozkan.ai/learn/coding/mle-multi-head-self-attention-forward-pass-14/
markdown: https://gurkanozkan.ai/learn/coding/mle-multi-head-self-attention-forward-pass-14.md
kind: coding
difficulty: Hard
topics:
  - Transformers
  - Attention
  - NumPy
json: https://gurkanozkan.ai/api/learn/coding/mle-multi-head-self-attention-forward-pass-14.json
robots: noindex
---

# Multi-head self-attention forward pass

- Shapes: `X` (T, d_model); `Wq`, `Wk`, `Wv` (d_model, d_model); `Wo` (d_model, d_out); no biases. - Compute `Q = XWq`, `K = XWk`, `V = XWv`. - Split the last dimension into `num_heads` **contiguous** blocks of size `h = d_model/num_heads`; head i uses columns `[i·h, (i+1)·h)`. - Apply scaled dot-product attention per head with scale `1/√h`. If `causal`, position t may only attend to positions ≤ t. - Concatenate the heads in order and multiply by `Wo`. Return shape (T, d_out).

## Signature

```python
def multi_head_attention(X, Wq, Wk, Wv, Wo, num_heads: int, causal: bool = False) -> np.ndarray: ...
```

## Examples

Each call and the value it should give.

```python
>>> close(multi_head_attention([[1.0, 0.0],[0.0, 1.0]], np.eye(2), np.eye(2), np.eye(2), np.eye(2), 1), [[0.669762, 0.330238], [0.330238, 0.669762]])
True

>>> close(multi_head_attention([[1.0, 0.0],[0.0, 1.0]], np.eye(2), np.eye(2), np.eye(2), np.eye(2), 2), [[0.731059, 0.5], [0.5, 0.731059]])
True
```

## Hints

1. Compute Q, K, V as XW; split the last dim into contiguous heads.
2. Per head: scaled dot-product attention with scale 1/sqrt(h); causal masks position t to attend to <= t only.
3. Concatenate heads in order, multiply by Wo, return (T, d_out).

## Reference solution

```python
import math
import numpy as np

def multi_head_attention(X, Wq, Wk, Wv, Wo, num_heads, causal=False):
    X = np.asarray(X, float)
    Q = X @ np.asarray(Wq, float); K = X @ np.asarray(Wk, float); V = X @ np.asarray(Wv, float)
    T, d = Q.shape
    assert d % num_heads == 0
    h = d // num_heads
    mask = np.tril(np.ones((T, T), bool)) if causal else None
    heads = []
    for i in range(num_heads):
        sl = slice(i * h, (i + 1) * h)
        o, _ = attention(Q[:, sl], K[:, sl], V[:, sl], mask)
        heads.append(o)
    return np.concatenate(heads, axis=1) @ np.asarray(Wo, float)

def attention(Q, K, V, mask=None):
    Q = np.asarray(Q, float); K = np.asarray(K, float); V = np.asarray(V, float)
    s = Q @ K.T / math.sqrt(Q.shape[1])
    if mask is not None:
        s = np.where(np.asarray(mask, bool), s, -np.inf)
    s = s - s.max(axis=1, keepdims=True)
    w = np.exp(s)
    w = w / w.sum(axis=1, keepdims=True)
    return w @ V, w
```

## What a strong solution covers

- Correct reshape/transpose (or slicing) per head.
- Uses the head dimension for scaling.
- Builds the causal mask with `np.tril`.
- Verifies shapes.
- Discusses batching (B, H, T, h), KV caching for decoding, and GQA.

## Common mistakes

- scaling by √d_model
- interleaving columns across heads instead of contiguous blocks.
---

*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.*
