Compute multi-head latent attention scores from the latent cache

Why it matters MLA shrinks the KV cache to one latent plus one small RoPE key per token, which is why DeepSeek models can serve long contexts cheaply.

Multi-head latent attention (MLA, from DeepSeek-V2) caches one small latent vector c per token instead of full keys. Per-head keys are k_h = c @ Wuk[h], and a separate shared RoPE key k_rope carries position. At decode time the up-projection is absorbed into the query, so keys are never rebuilt.

Write mla_scores(xq, c, Wq, Wuk, q_rope, k_rope). Shapes: xq (Tq, d), c (Tk, r), Wq (H, d, hd), Wuk (H, r, hd), q_rope (H, Tq, dr), k_rope (Tk, dr). For each head h:
1. q_h = xq @ Wq[h] (Tq, hd) and the absorbed query a_h = q_h @ Wuk[h].T (Tq, r).
2. scores_h = (a_h @ c.T + q_rope[h] @ k_rope.T) / sqrt(hd + dr).
Return the (H, Tq, Tk) scores (no mask, no softmax).

Signaturedef mla_scores(xq, c, Wq, Wuk, q_rope, k_rope)

Example

xq = [[1, 1]], c = [[1, 1]], Wq and Wuk all ones of shape (1, 2, 2), q_rope = [[[1]]], k_rope = [[1]] gives (8 + 1) / sqrt(3) = [[[5.1962]]].

Understand the idea

Normal attention caches a key and a value for every head. MLA instead caches one short latent vector c per token, like storing a zip file instead of every document, and rebuilds per-head keys with k = c Wuk when needed.

The trick is that you never actually unzip. A score is q . k = q (c Wuk)^T = (q Wuk^T) c^T. So multiply the query by Wuk^T once (the "absorbed" query, r numbers) and dot it straight with the cached latents.

Tiny check: q = [2, 2], Wuk all ones (2 by 2), c = [1, 1]. Absorbed query = [4, 4], dot c = 8. Explicit key c Wuk = [2, 2], dot q = 8. Same answer.

RoPE cannot be absorbed this way because its rotation depends on position, so MLA adds a small decoupled RoPE part: score = (a_h . c + q_rope . k_rope) / sqrt(hd + dr).

DeepSeek-V2 and V3 use this design, and their cache per token is just r + dr numbers per layer.

Shapes and data flow

xq (Tq, d) -> q_h (Tq, hd) -> a_h = q_h Wuk[h]^T (Tq, r); c (Tk, r) -> a_h c^T (Tq, Tk); q_rope[h] (Tq, dr) k_rope^T (dr, Tk) -> (Tq, Tk); stack -> (H, Tq, Tk)
solution.pyPython idle
Ctrl/Cmd + Enter runs sample tests

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

  • Sample 1: examplemla_scores([[1.0, 1.0]], [[1.0, 1.0]], np.ones((1, 2, 2)), np.ones((1, 2, 2)), [[[1.0]]], [[1.0]])
  • Sample 2: randommla_scores(XQ, C, WQ, WUK, QR, KR)