Multi-head attention inDocumentation Index
Fetch the complete documentation index at: https://mintlify.com/itsubaki/gpt/llms.txt
Use this file to discover all available pages before exploring further.
itsubaki/gpt projects the input hidden state into query, key, and value tensors through independent linear maps, reshapes them to expose the head dimension, applies Rotary Position Embeddings (RoPE) to queries and keys, computes scaled dot-product attention scores with a causal lower-triangular mask, and projects the concatenated head outputs back to the embedding dimension. An optional KV cache enables efficient single-token generation by reusing previously computed keys and values.
Constructor
Normal(0, 0.02):
| Matrix | Shape | Role |
|---|---|---|
Wq | [E, H×D] | Projects input to queries |
Wk | [E, H×D] | Projects input to keys |
Wv | [E, H×D] | Projects input to values |
Wo | [H×D, E] | Projects concatenated head outputs back to embedding dim |
Full forward pass
Step-by-step breakdown
Step 1 — Project Q, K, V. Each of the three independent linear layers maps the(B, C, E) input to (B, C, H×D).
Step 2 — Reshape and transpose. The H×D dimension is split into (H, D) then transposed to (B, H, C, D) so that each head’s sequence is contiguous in memory for the subsequent matmul.
Step 3 — Apply RoPE. The same RoPEFunc closure rotates pairs of head-dimension coordinates in Q and K using position-dependent angles. Keys and queries receive identical rotation at the same positions, so relative position information is encoded in their dot product.
Step 4 — KV cache. See the KV caching section below.
Step 5 — Scaled dot-product. K is transposed from (B, H, C, D) to (B, H, D, C) and multiplied with Q of shape (B, H, C, D) to produce attention scores (B, H, C, C). Dividing by sqrt(D) prevents the dot products from growing too large in high-dimensional spaces, which would push the softmax into regions with vanishing gradients.
Step 6 — Causal mask. A lower-triangular mask of ones is built with tensor.Tril. Positions where the mask value is 0 (the upper triangle) are filled with math.Inf(-1) before the softmax, ensuring each token can only attend to itself and earlier tokens.
Step 7 — Output projection. After softmax, the weight matrix is multiplied with V, the heads are concatenated by transposing back and reshaping to (B, C, H×D), and finally Wo maps back to (B, C, E).
Causal mask
tensor.Tril returns a C×C lower-triangular matrix with ones on and below the main diagonal. F.MaskFill replaces every score at a position where the mask is zero with negative infinity. After softmax those positions become exactly zero, which prevents any information flow from future tokens to the current token — enforcing the autoregressive constraint during both training and generation.
KV caching
Theoffset counter and the kCache / vCache fields enable incremental generation:
| State | Behaviour |
|---|---|
kCache == nil (first call) | Full prompt is processed; causal mask is applied; cache is initialized to K and V |
kCache != nil (subsequent calls) | Single new token; new K and V are appended along the sequence axis; causal mask is skipped because the new token can attend to all cached positions |
offset | Tracks the total number of tokens already processed; passed to RoPEFunc so new tokens receive the correct rotational angle |
Clearing the cache
nil and resetting the offset counter returns the layer to its initial state, making isFirstCall true on the next forward pass.