Classify an image from the CLS token after one multi-head attention block

In a ViT the CLS token starts out knowing nothing about the image. Attention lets it pull information from every patch, and the classifier reads only the CLS state at the end.

Write vit_classify(tokens, Wq, Wk, Wv, Wo, heads, W_head, b_head). tokens is (N+1, D) with token 0 the CLS token. Wq, Wk, Wv, Wo are (D, D). W_head is (D, K), b_head is (K,). D is divisible by heads; dh = D / heads.
1. h = LN(tokens), where LN normalises each row to mean 0 and variance 1 with eps 1e-5 inside the square root and no learned scale or shift.
2. q = h Wq, k = h Wk, v = h Wv. Split the D columns into heads consecutive blocks of width dh.
3. Per head: A = softmax(q k^T / sqrt(dh)) over keys, out = A v. Concatenate heads back to (N+1, D), then multiply by Wo.
4. x = tokens + that result (residual).
5. Return logits = LN(x[0]) @ W_head + b_head, shape (K,).

Signaturedef vit_classify(tokens, Wq, Wk, Wv, Wo, heads, W_head, b_head)

Example

check: if Wo is all zeros, x equals tokens and the logits depend only on LN(tokens[0]).

Understand the idea

The CLS token starts with no knowledge of the image. One attention block lets it look at every patch and pull in what it needs, then a linear head reads only the CLS row to produce class scores. Multi-head attention splits the width D into heads blocks of size dh, runs attention in each, and joins them back. Worked example of one head step: dh = 4 and the CLS query has raw dot products [4, 0] with two keys. Divide by sqrt(dh) = 2 to get [2, 0]; softmax gives [0.8808, 0.1192]. If the values are [1] and [0], the head outputs 0.8808. Dividing by sqrt(D) instead would flatten the softmax when there are several heads. Rule: h = LN(tokens) with no learned scale; q, k, v = h Wq, h Wk, h Wv; per head A = softmax(q k^T / sqrt(dh)) over keys, out = A v; concatenate heads, multiply by Wo, add to tokens (residual); logits = LN(x[0]) W_head + b_head. If Wo is zero, the block passes tokens through unchanged. This mirrors the final stage of ViT image classifiers.

solution.pyPython idle
Ctrl/Cmd + Enter runs sample tests

Run checks the first 2 tests. Submit checks the hidden tests with Pro.

  • Sample 1: zero output projectionvit_classify(_tok, _Wq, _Wk, _Wv, np.zeros((8, 8)), 2, _Wh, _bh)
  • Sample 2: one headvit_classify(_tok, _Wq, _Wk, _Wv, _Wo, 1, _Wh, _bh)