16. Attention

Attention is the operation the paper approximates. Its Eq. 1 ([refinekv], Section 2) is one query attending to \(N\) cached keys and values; this chapter says where those vectors come from, why the formula has the shape it has, and how a real model arranges it: several heads, query heads sharing key-value heads (GQA), and positions encoded by rotations (RoPE). It ends with Eq. 1 in C for one decoding step, with its FLOPs and bytes counted. Chapter 17 turns that count into the reason the KV cache is the bottleneck; chapter 18 replaces groups of keys by representatives; chapter 20 returns to the GQA question the paper has to answer.

16.1 Tokens and embeddings

A language model reads text as a sequence of tokens: pieces of words from a fixed vocabulary of \(V\) entries, chosen by a tokenizer such as byte-pair encoding, which starts from bytes and repeatedly merges the most frequent adjacent pair into a new symbol [slp3]. Common words become one token, rare ones several. To the model a token is an integer \(t \in \{0, \dots, V-1\}\).

The first layer replaces each token by a vector. The embedding matrix \(E\) has one row of \(d_{\text{model}}\) numbers per vocabulary entry, and token \(t\) becomes row \(t\). As linear algebra, that is the one-hot vector \(e_t\) times \(E\) (section 9.1); as code it is an array index, a lookup table:

/* C-like pseudocode: the embedding of a token sequence */
for (pos = 0; pos < T; pos++)
    memcpy(x[pos], E[token[pos]], d_model * sizeof(float));

The rows are learned in training, so that tokens used alike end up with similar vectors. From here on each position \(t\) carries a vector \(x_t \in \mathbb{R}^{d_{\text{model}}}\), the hidden state. A transformer is a stack of layers, each of which updates every hidden state twice, by adding to it [vaswani]:

\[ x_t \leftarrow x_t + \operatorname{Attn}(x_1, \dots, x_t), \qquad x_t \leftarrow x_t + \operatorname{MLP}(x_t). \]

(Normalization steps before each part are left out here.) The MLP works on each position alone. Attention is the only place where one position reads others. After the last layer, a matrix maps the hidden state of the last position to \(V\) logits, and their softmax (chapter 15) is the distribution of the next token.

16.2 Attention as a soft lookup

A hash table stores pairs (key, value). A lookup with a query returns the value of the key equal to the query, or nothing. Attention is the same operation made continuous:

\[ o = \sum_{i=1}^{N} \alpha_i v_i, \qquad \alpha = \operatorname{softmax}(s), \quad s_i = q^\top k_i. \]

The weights are positive and sum to 1, so \(o\) is a convex combination of the values (section 8.2): it lies inside their hull. If one key matches far better than the rest, softmax puts nearly all the weight on it and the result is nearly that key's value: the hard lookup is the limit. If several match, the result blends them. Because every step is smooth, the model can learn its keys and queries by gradient descent (section 7.5), which a hard lookup would not allow. Bahdanau, Cho and Bengio introduced the mechanism to let a translation model look back at the relevant source words [bahdanau]; the dot-product form used today is from [vaswani].

Four keys on the unit circle, a query between keys 1 and 0 but closer to 1, and the similarities multiplied by a growing scale:

#include <math.h>
#include <stdio.h>

int main(void)
{
    /* four keys on the unit circle, each with a value; the query is near key 1 */
    double ang[4] = { 0.0, 1.2, 2.4, 4.0 }, v[4] = { 10, 20, 30, 40 };
    double q[2] = { cos(1.0), sin(1.0) };
    double scales[4] = { 1, 4, 16, 64 };
    for (int t = 0; t < 4; t++) {
        double s[4], w[4], m = -INFINITY, l = 0, o = 0;
        for (int i = 0; i < 4; i++) {
            s[i] = scales[t] * (q[0] * cos(ang[i]) + q[1] * sin(ang[i]));   /* scaled q.k_i */
            m = fmax(m, s[i]);
        }
        for (int i = 0; i < 4; i++) l += w[i] = exp(s[i] - m);
        for (int i = 0; i < 4; i++) { w[i] /= l; o += w[i] * v[i]; }
        printf("scale %2.0f: weights %.3f %.3f %.3f %.3f  output %.2f\n",
               scales[t], w[0], w[1], w[2], w[3], o);
    }
    return 0;
}
scale  1: weights 0.289 0.449 0.200 0.063  output 20.36
scale  4: weights 0.142 0.825 0.032 0.000  output 18.91
scale 16: weights 0.001 0.999 0.000 0.000  output 19.99
scale 64: weights 0.000 1.000 0.000 0.000  output 20.00

The keys are unit vectors at angles ang[i], so \(q^\top k_i = \cos(1 - \text{ang}_i)\): 0.54, 0.98, 0.17 and \(-0.99\). Multiplying all of them by scales[t] is a softmax temperature of \(1/\text{scale}\) (exercise 15.2): it does not change which key is most similar, only how decisively softmax prefers it. The softmax is the safe form of section 15.2. At scale 1 the output 20.36 is a blend dominated by no one; by scale 64 it is the value of key 1, 20.00, and the soft lookup has become a hard one. Section 16.4 is about where a real model sits on this scale.

16.3 Queries, keys and values

The query, keys and values are not the hidden states themselves. Each is a linear map of one, with its own learned matrix:

\[ q_t = W_Q x_t, \qquad k_i = W_K x_i, \qquad v_i = W_V x_i, \]

with \(W_Q, W_K \in \mathbb{R}^{d \times d_{\text{model}}}\) and \(W_V \in \mathbb{R}^{d_v \times d_{\text{model}}}\). Three maps because a token plays three roles: what it is looking for (\(q\)), what it can be found by (\(k\)), and what it hands over when found (\(v\)). These need not be the same: a pronoun looks for a noun, and offers itself as a pronoun.

The new token at position \(t\) attends to positions \(1, \dots, N\) with \(N = t\) (itself included). In the paper's notation, with the scaling of section 16.4 included, this is its Eq. 1:

\[ o = \sum_{i=1}^{N} \alpha_i v_i, \qquad \alpha_i = \frac{\exp\!\big(q^\top k_i/\sqrt{d}\big)}{\sum_{j=1}^{N} \exp\!\big(q^\top k_j/\sqrt{d}\big)}, \qquad q, k_i \in \mathbb{R}^{d},\; v_i \in \mathbb{R}^{d_v}. \]

The logits are \(s_i = q^\top k_i/\sqrt d\) and the weights \(\alpha_i = \operatorname{softmax}(s)_i\). When all positions are processed at once (training, or reading a prompt), the queries, keys and values are the rows of matrices \(Q\), \(K\), \(V\), and all outputs are \(\operatorname{softmax}(QK^\top/\sqrt{d})\,V\), the softmax taken row by row [vaswani]: one matrix product for all the logits, one for all the weighted sums.

One property makes decoding cheap and is the reason the paper exists. \(k_i\) and \(v_i\) depend on position \(i\)'s hidden state only, and with the causal mask of section 16.5 that state depends only on tokens up to \(i\). So once computed, keys and values never change: they can be stored and reused for every later token. That store is the KV cache (section 17.3). The query is new at every step; the \(N\) keys and values are old.

16.4 Why divide by \(\sqrt{d}\)

Suppose the coordinates of \(q\) and \(k\) are independent, with mean 0 and variance 1. Then each product \(q_j k_j\) has mean 0 and variance \(\operatorname{E}[q_j^2]\operatorname{E}[k_j^2] = 1\), the \(d\) products are independent, and variances of independent terms add (section 12.7):

\[ \operatorname{E}[q^\top k] = 0, \qquad \operatorname{Var}(q^\top k) = \sum_{j=1}^{d} \operatorname{Var}(q_j k_j) = d. \]

So raw logits have a spread of \(\sqrt{d}\): 11.3 for \(d = 128\). By section 16.2 that is a large scale: softmax on logits spread over \(\pm 20\) or more gives nearly all weight to one key whatever the query “meant”. A saturated softmax also has nearly zero gradient (its derivative is \(\alpha_i(\delta_{ij} - \alpha_j)\), small when every \(\alpha\) is near 0 or 1), so training would stall. Dividing by \(\sqrt d\) brings the variance back to 1 for every \(d\) [vaswani]. Training is free to make logits larger where it wants sharp attention; it starts from a sane scale.

The program measures the variance and two sharpness numbers on random Gaussian \(q\) and \(N = 1024\) keys: the largest weight, and the effective number of keys \(1/\sum_i \alpha_i^2\), which is \(N\) for uniform weights and 1 for a single key.

#include <math.h>
#include <stdint.h>
#include <stdio.h>

static uint64_t st = 99;
static double gauss(void)                /* Box-Muller: mean 0, variance 1 */
{
    st = st * 6364136223846793005u + 1442695040888963407u;
    double u1 = ((st >> 11) + 1.0) / 9007199254740993.0;
    st = st * 6364136223846793005u + 1442695040888963407u;
    double u2 = (st >> 11) / 9007199254740992.0;
    return sqrt(-2 * log(u1)) * cos(6.283185307179586 * u2);
}

int main(void)
{
    enum { N = 1024, T = 200 };
    int ds[4] = { 16, 64, 128, 256 };
    for (int t = 0; t < 4; t++) {
        int d = ds[t];
        double var = 0, maxw[2] = { 0, 0 }, eff[2] = { 0, 0 };
        for (int trial = 0; trial < T; trial++) {
            double q[256], s[N];
            for (int j = 0; j < d; j++) q[j] = gauss();
            for (int i = 0; i < N; i++) {
                s[i] = 0;
                for (int j = 0; j < d; j++) s[i] += q[j] * gauss();     /* q.k_i */
                var += s[i] * s[i] / ((double)N * T);
            }
            for (int sc = 0; sc < 2; sc++) {           /* 0: raw q.k, 1: q.k / sqrt(d) */
                double c = sc ? 1 / sqrt(d) : 1, m = -INFINITY, l = 0, l2 = 0;
                for (int i = 0; i < N; i++) m = fmax(m, c * s[i]);
                for (int i = 0; i < N; i++) { double e = exp(c * s[i] - m); l += e; l2 += e * e; }
                maxw[sc] += 1 / l / T;                  /* the largest weight is 1/l */
                eff[sc] += l * l / l2 / T;              /* 1 / sum(alpha_i^2) */
            }
        }
        printf("d = %3d: var(q.k) = %6.1f | raw: max weight %.2f, eff. keys %5.1f"
               " | scaled: max weight %.3f, eff. keys %5.1f\n",
               d, var, maxw[0], eff[0], maxw[1], eff[1]);
    }
    return 0;
}
d =  16: var(q.k) =   15.7 | raw: max weight 0.41, eff. keys   8.1 | scaled: max weight 0.016, eff. keys 420.7
d =  64: var(q.k) =   63.8 | raw: max weight 0.70, eff. keys   2.3 | scaled: max weight 0.017, eff. keys 393.0
d = 128: var(q.k) =  127.4 | raw: max weight 0.78, eff. keys   1.7 | scaled: max weight 0.016, eff. keys 392.1
d = 256: var(q.k) =  256.6 | raw: max weight 0.86, eff. keys   1.4 | scaled: max weight 0.017, eff. keys 385.6

The variance tracks \(d\), as derived. Without scaling, attention collapses toward one key, and more so the larger \(d\) is: 1.4 effective keys at \(d = 256\). With scaling the numbers no longer depend on \(d\). How the program gets there: var averages \(s_i^2\) over all keys and trials, which estimates \(\operatorname{Var}(q^\top k)\) since the mean is 0. In the safe softmax the largest term is \(e^0 = 1\), so the largest weight is exactly \(1/l\) with \(l = \sum_i e^{s_i - m}\), and no division per key is needed. Likewise \(\sum_i \alpha_i^2 = \sum_i e^{2(s_i - m)}/l^2\), so the effective number is \(l^2/\sum_i e^{2(s_i - m)}\): two running sums give both measures. Keys are drawn fresh in the inner loop and never stored, because only their dot products with \(q\) matter.

16.5 The causal mask

A language model predicts each token from the ones before it, so position \(t\) may attend to positions \(i \le t\) only. When many positions are processed together, the matrix of logits \(s_{ti}\) is computed in full and the entries with \(i > t\) are set to \(-\infty\) before the softmax. Since \(e^{-\infty} = 0\), those keys get weight exactly 0, and the remaining weights still sum to 1. The weights form a lower-triangular matrix. Five positions with arbitrary logits (mask.c):

query 0: 1.000 0.000 0.000 0.000 0.000
query 1: 0.730 0.270 0.000 0.000 0.000
query 2: 0.095 0.284 0.621 0.000 0.000
query 3: 0.431 0.384 0.116 0.069 0.000
query 4: 0.160 0.060 0.091 0.305 0.383

Row \(t\) is the attention of query \(t\); position 0 can only attend to itself. During decoding the mask disappears: the one new query is the last position, and every cached key is before it. In the merged-state form of section 15.5, a masked key is a key whose state is never merged; a block of keys that is entirely masked has the empty state \((-\infty, 0, 0)\), the case of exercise 15.5.

16.6 Heads, MQA and GQA

One attention computes one weighted average per position. A layer runs \(H\) of them side by side, the heads, each with its own \(W_Q^h, W_K^h, W_V^h\) and a smaller dimension, typically \(d = d_{\text{model}}/H\). Each head can look for something different: the previous word, the subject of the sentence, a matching bracket. The \(H\) outputs are concatenated and mapped back to \(d_{\text{model}}\) by a matrix \(W_O\) [vaswani]. The cost in FLOPs is about that of one head of full width; the cost in memory is \(H\) sets of keys and values per position.

That memory is what decoding reads at every step (section 16.8), so later designs share it. In multi-query attention (MQA) all \(H\) query heads use a single key head and a single value head [mqa]: the cache shrinks \(H\)-fold, at some loss of quality. Grouped-query attention (GQA) is the middle ground: \(H_{kv}\) key-value heads, each shared by a group of \(H/H_{kv}\) query heads [gqa]. With \(H_{kv} = H\) it is ordinary multi-head attention, with \(H_{kv} = 1\) it is MQA.

q0q1q2q3 q4q5q6q7 K, V head 0K, V head 1
Figure 16.1. GQA with \(H = 8\) query heads and \(H_{kv} = 2\) key-value heads: query head \(h\) reads KV head \(\lfloor h / 4 \rfloor\). Multi-head attention would draw eight KV boxes, MQA one.

Llama-3.1-8B, one of the two models in the paper's experiments, has 32 layers, 32 query heads and 8 KV heads of dimension \(d = 128\) per layer [llama3]: groups of 4. Its \(d_{\text{model}} = 4096 = 32 \times 128\).

GQA creates a problem for any method that decides which keys to read. The cache is stored per KV head, so whatever is read is read for the whole group, while each of the group's query heads has its own query and its own opinion of which clusters matter. The paper's answer is to aggregate the decisions of the group: GQA-any expands a cluster if any query head in the group asks for it, GQA-mean if their average risk does ([refinekv], Section 4; section 20.2).

16.7 Positions and RoPE

Nothing so far knows the order of the tokens. Eq. 1 is a sum over \(i\), and permuting the cached pairs \((k_i, v_i)\) does not change it. Word order matters, so position must be put into the vectors. Rotary position embedding (RoPE) does it by rotation [rope]. Split a \(d\)-dimensional query or key into \(d/2\) pairs of coordinates. For a vector at position \(p\), rotate pair \(j\) in its plane by the angle \(p\,\theta_j\), with frequencies

\[ \theta_j = b^{-2j/d}, \quad j = 0, \dots, d/2 - 1, \]

with base \(b = 10000\) in [rope].

Write \(R_p\) for the whole operation: a block-diagonal matrix of \(2 \times 2\) rotations \(R(p\theta_j)\). A rotation is orthogonal, \(R(\alpha)^\top = R(-\alpha)\), and rotations of one plane compose by adding angles, \(R(\alpha)R(\beta) = R(\alpha + \beta)\) (section 9.6). So for a query at position \(m\) and a key at position \(n\),

\[ (R_m q)^\top (R_n k) = q^\top R_m^\top R_n k = q^\top R_{n - m}\, k. \]

The logit depends on the positions only through their difference \(n - m\): the same pair of tokens three apart scores the same at the start of a book and at its end. Rotations preserve length, so \(\|R_p q\| = \|q\|\) and the scale of section 16.4 is untouched. The frequencies run from \(\theta_0 = 1\) radian per position down to nearly \(1/b\): the fast pairs distinguish neighbouring positions, the slow ones distances of thousands, like the hands of a clock from seconds to hours. (Implementations differ in which coordinates they pair and in \(b\); the argument is the same.)

#include <math.h>
#include <stdio.h>

enum { D = 8 };

static void rope(const double *x, double *y, int pos)   /* rotate pair j by pos * theta_j */
{
    for (int j = 0; j < D / 2; j++) {
        double th = pos * pow(10000.0, -2.0 * j / D), c = cos(th), s = sin(th);
        y[2 * j]     = c * x[2 * j] - s * x[2 * j + 1];
        y[2 * j + 1] = s * x[2 * j] + c * x[2 * j + 1];
    }
}

static double dot(const double *a, const double *b)
{
    double s = 0;
    for (int j = 0; j < D; j++) s += a[j] * b[j];
    return s;
}

int main(void)
{
    double q[D] = { 1, 2, -1, 0.5, 3, -2, 0.1, 1 }, k[D] = { 0.3, -1, 2, 1, -0.5, 1, 2, -1 };
    int pos[4][2] = { { 5, 2 }, { 103, 100 }, { 1003, 1000 }, { 7, 2 } };
    for (int t = 0; t < 4; t++) {
        double rq[D], rk[D];
        rope(q, rq, pos[t][0]);                 /* the query at position m */
        rope(k, rk, pos[t][1]);                 /* the key at position n */
        printf("m = %4d, n = %4d, m - n = %d: q.k = %.6f, |Rq| = %.6f\n",
               pos[t][0], pos[t][1], pos[t][0] - pos[t][1], dot(rq, rk), sqrt(dot(rq, rq)));
    }
    printf("without rotation: q.k = %.6f, |q| = %.6f\n", dot(q, k), sqrt(dot(q, q)));
    return 0;
}
m =    5, n =    2, m - n = 3: q.k = -4.811580, |Rq| = 4.501111
m =  103, n =  100, m - n = 3: q.k = -4.811580, |Rq| = 4.501111
m = 1003, n = 1000, m - n = 3: q.k = -4.811580, |Rq| = 4.501111
m =    7, n =    2, m - n = 5: q.k = -5.429329, |Rq| = 4.501111
without rotation: q.k = -7.500000, |q| = 4.501111

rope is \(R_p\): for each pair \(j\) it forms the angle \(p\,\theta_j\) with \(\theta_j = 10000^{-2j/D}\) and applies the \(2 \times 2\) rotation \(\begin{pmatrix} \cos & -\sin \\ \sin & \cos \end{pmatrix}\) to coordinates \(2j\) and \(2j+1\). The first three lines put the query and key at different absolute positions with the same difference 3, and the dot product is the same to all printed digits, as \(q^\top R_{n-m} k\) says. At difference 5 it changes. The norm column is the orthogonality: \(\|R_p q\| = \|q\|\) at every position. The dot product without rotation is different from all of them because it is \(q^\top R_0 k\), difference 0.

For the paper this means that the cached keys are the rotated ones, \(R_i k_i\), stored once at their own position. Its cluster means \(\bar k_C\) are means of rotated keys, which is one more reason the contiguous clusters of section 18.4 are natural: neighbouring keys have been rotated by nearly the same angles.

16.8 Attention in C

One decoding step of one layer, in the setting of the paper: \(H\) query heads, \(H_{kv}\) KV heads with \(N\) cached keys and values each, stored in bf16, arithmetic in fp32 (section 14.7). For query head \(h\), with \(g = \lfloor h / (H/H_{kv}) \rfloor\) its KV head,

\[ o_h = \sum_{i=1}^{N} \alpha_{h,i}\, v_{g,i}, \qquad \alpha_{h,\cdot} = \operatorname{softmax}\big(q_h^\top k_{g,i}/\sqrt{d}\big). \]

Cost. For each query head and each key, the logit is \(d\) multiply-adds and the weighted sum another \(d\): \(4 H N d\) floating-point operations, counting a multiply-add as 2. The data that must come from memory is the cache: \(2 H_{kv} N d\) numbers of 2 bytes. The ratio is

\[ \frac{4 H N d}{4 H_{kv} N d} = \frac{H}{H_{kv}} \text{ FLOPs per byte}, \]

the size of the query group: 4 for Llama-3.1-8B, 1 without sharing. Both are tiny next to what a processor can do per byte it loads, so decoding attention is limited by memory bandwidth (section 17.4), and the way to speed it up is to read fewer bytes. That is the paper's goal. The program uses that model's head counts and head size, with \(N = 4096\):

#include <math.h>
#include <stdint.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

enum { HQ = 32, HKV = 8, D = 128, N = 4096 };   /* Llama-3.1-8B's head counts and head size */

static float bf16_to_f(uint16_t h) { uint32_t b = (uint32_t)h << 16; float x; memcpy(&x, &b, 4); return x; }
static uint16_t f_to_bf16(float x)
{
    uint32_t b; memcpy(&b, &x, 4);
    return (uint16_t)((b + 0x7fff + ((b >> 16) & 1)) >> 16);
}

/* one layer, one new token: q[HQ][D] against the cache K, V [HKV][N][D] (bf16) */
static void attend(const float *q, const uint16_t *K, const uint16_t *V, float *o)
{
    for (int h = 0; h < HQ; h++) {
        int g = h / (HQ / HKV);                 /* the KV head this query head shares */
        const float *qh = q + h * D;
        float m = -INFINITY, l = 0, a[D] = { 0 };
        for (int i = 0; i < N; i++) {
            const uint16_t *k = K + ((size_t)g * N + i) * D, *v = V + ((size_t)g * N + i) * D;
            float s = 0;
            for (int j = 0; j < D; j++) s += qh[j] * bf16_to_f(k[j]);   /* fp32 accumulation */
            s /= sqrtf(D);
            float mn = fmaxf(m, s), r = expf(m - mn), p = expf(s - mn);
            l = l * r + p;
            for (int j = 0; j < D; j++) a[j] = a[j] * r + p * bf16_to_f(v[j]);
            m = mn;
        }
        for (int j = 0; j < D; j++) o[h * D + j] = a[j] / l;
    }
}

int main(void)
{
    size_t n = (size_t)HKV * N * D;
    uint16_t *K = malloc(n * 2), *V = malloc(n * 2);
    static float q[HQ * D], o[HQ * D];
    for (size_t i = 0; i < n; i++) {
        K[i] = f_to_bf16((float)sin(0.7 * i));
        V[i] = f_to_bf16((float)cos(0.3 * i));
    }
    for (int i = 0; i < HQ * D; i++) q[i] = (float)(2 * sin(1.3 * i));
    attend(q, K, V, o);

    double err = 0;                             /* check: two passes in double */
    for (int h = 0; h < HQ; h++) {
        const uint16_t *Kg = K + (size_t)(h / (HQ / HKV)) * N * D, *Vg = V + (Kg - K);
        static double s[N];
        double m = -INFINITY, l = 0;
        for (int i = 0; i < N; i++) {
            s[i] = 0;
            for (int j = 0; j < D; j++) s[i] += (double)q[h * D + j] * bf16_to_f(Kg[i * D + j]);
            s[i] /= sqrt(D);
            m = fmax(m, s[i]);
        }
        for (int i = 0; i < N; i++) l += exp(s[i] - m);
        for (int j = 0; j < D; j++) {
            double a = 0;
            for (int i = 0; i < N; i++) a += exp(s[i] - m) * bf16_to_f(Vg[i * D + j]);
            err = fmax(err, fabs(a / l - o[h * D + j]));
        }
    }
    printf("max |o - reference| over %d heads x %d: %.1e\n", HQ, D, err);

    double flops = 4.0 * HQ * N * D;            /* q.k and p*v: 2 flops per multiply-add */
    double bytes = 2.0 * HKV * N * D * 2;       /* K and V, 2 bytes each */
    printf("per layer: %.3g flops, %.3g bytes of K/V, %.1f flops per byte\n",
           flops, bytes, flops / bytes);
    printf("with %d KV heads (no sharing): %.1f flops per byte\n", HQ, flops / (bytes * HQ / HKV));
    double tok = 2.0 * 32 * HKV * D * 2;        /* K and V, 32 layers, bf16 */
    printf("KV cache per token, 32 layers: %.0f bytes; at 131072 tokens: %.1f GiB\n",
           tok, tok * 131072 / (1 << 30));
    free(K); free(V);
    return 0;
}
max |o - reference| over 32 heads x 128: 2.9e-09
per layer: 6.71e+07 flops, 1.68e+07 bytes of K/V, 4.0 flops per byte
with 32 KV heads (no sharing): 1.0 flops per byte
KV cache per token, 32 layers: 131072 bytes; at 131072 tokens: 16.0 GiB

Printed on FreeBSD 15.1 on amd64 (Core i5-9400), clang 19. It depends on the machine: elsewhere the timings, the random numbers or the last digits differ.

How it maps. The cache is laid out [HKV][N][D], so the \(N\) keys of one KV head are contiguous and a scan over \(i\) reads memory sequentially. g = h / (HQ / HKV) is \(\lfloor h/(H/H_{kv}) \rfloor\), the grouping of figure 16.1. The loop over keys is the online softmax of section 15.4 with the vector state \((m, l, a)\) of section 15.6: each key and value is converted from bf16 (a shift, section 14.7) as it is used, its logit is \(q_h^\top k_{g,i}/\sqrt{d}\) accumulated in fp32, and the state absorbs it. The output is \(a/l\). The check recomputes Eq. 1 with two passes in double from the same bf16 data, so it measures the fp32 arithmetic only; the error, \(3 \times 10^{-9}\), is small because these values average out to outputs near zero. The counts are the formulas above: \(4HND = 6.7 \times 10^7\) FLOPs against \(2 \cdot 2 H_{kv} N D = 1.7 \times 10^7\) bytes. Over all 32 layers, each token's keys and values take \(2 \times 32 \times 8 \times 128 \times 2 = 131072\) bytes, and a 128K-token context holds 16 GiB of cache, all of it read for every generated token.

One difference from a real kernel matters. Here the four query heads of a group each scan their KV head's keys separately, so each key is fetched four times (from cache memory, if lucky). A GPU kernel processes the group together, loading each key once and using it for all four queries; only then is the intensity really \(H/H_{kv}\). The paper's block-selection kernel works the same way, jointly processing the query heads of each KV head ([refinekv], Appendix B.2).

Exercises

  1. By hand: \(d = 2\), \(q = (1, 0)\), keys \(k_1 = (1, 0)\), \(k_2 = (0, 1)\), values \(v_1 = 10\), \(v_2 = 20\). Compute the logits with the \(\sqrt{d}\) scaling, the weights and the output.
    Answer

    \(s_1 = 1/\sqrt 2 \approx 0.707\), \(s_2 = 0\). \(\alpha_1 = e^{0.707}/(e^{0.707} + 1) \approx 0.670\), \(\alpha_2 \approx 0.330\), \(o \approx 0.670 \cdot 10 + 0.330 \cdot 20 = 13.30\).

  2. Show that without position information, permuting the cached pairs \((k_i, v_i)\) leaves the output unchanged. Why does this force a model to encode positions?
    Answer

    Eq. 1 is a sum over \(i\) of a term that depends on \((k_i, v_i)\) only, and the denominator is a sum over all \(j\); addition does not depend on order. So “dog bites man” and “man bites dog” would produce the same attention outputs at the last position; the order has to be put into the vectors, as RoPE does.

  3. If the coordinates of \(q\) and \(k\) have variance \(\sigma^2\) instead of 1 (still independent, mean 0), what is \(\operatorname{Var}(q^\top k)\), and what scale factor would bring it to 1?
    Answer

    Each product has variance \(\sigma^2 \cdot \sigma^2\), so \(\operatorname{Var}(q^\top k) = d\sigma^4\). Divide by \(\sigma^2 \sqrt{d}\). The \(1/\sqrt{d}\) of Eq. 1 assumes unit variance; the learned matrices \(W_Q, W_K\) absorb the rest.

  4. Llama-3.1-8B with ordinary multi-head attention (32 KV heads instead of 8): how large would the KV cache be per token and at 131072 tokens, in bf16?
    Answer

    \(2 \times 32 \times 32 \times 128 \times 2 = 524288\) bytes per token, four times the GQA figure; 64 GiB at 131072 tokens (ex.c). Together with about 16 GB of bf16 weights this would not fit on most single GPUs.

  5. Multiply out \(R(\alpha)^\top R(\beta)\) for \(R(\alpha) = \begin{pmatrix} \cos\alpha & -\sin\alpha \\ \sin\alpha & \cos\alpha \end{pmatrix}\) and show it equals \(R(\beta - \alpha)\).
    Answer

    The top-left entry is \(\cos\alpha\cos\beta + \sin\alpha\sin\beta = \cos(\beta - \alpha)\); the top-right is \(-\cos\alpha\sin\beta + \sin\alpha\cos\beta = -\sin(\beta - \alpha)\); the bottom row likewise gives \(\sin(\beta - \alpha)\) and \(\cos(\beta - \alpha)\). These are the angle-difference formulas.

  6. Restructure attend so that each key and value of a KV head is converted once and used by all \(H/H_{kv}\) query heads of the group. What do you need to keep per query head?
    Answer

    Loop over KV heads \(g\), then over keys \(i\), then over the group's query heads. Each query head needs its own state \((m, l, a)\): the softmaxes are different even though the keys are shared, because the logits are. The memory traffic for the cache drops by the group size; the FLOPs stay the same.

  7. In RefineKV's mixed attention, which quantities of Eq. 1 are used exactly and which are replaced?
    Answer

    The query \(q\) is exact. For an expanded cluster, its keys and values are exact. For any other cluster \(C\), the \(|C|\) pairs \((k_i, v_i)\) are replaced by one pair \((\bar k_C, \bar v_C)\) counted \(|C|\) times, so the logit is \(q^\top \bar k_C/\sqrt{d}\) and the mass is \(|C|\,e^{q^\top \bar k_C/\sqrt d}\) (the state of section 15.5). The normalizer is a sum over this mixed set. Section 18.5 builds it; chapter 19 bounds the error.

References