17. Decoding and the KV cache

Chapter 16 computed one attention output from a query and a set of keys and values. A language model uses that computation in a loop: it writes text one token at a time, and each new token attends to everything before it. This chapter follows the loop. It shows why the keys and values of past tokens are kept in a KV cache, how big that cache gets, and why reading it, not computing with it, sets the speed of generation. Then it surveys the two ways to read less: throw entries away for good (eviction), or decide per query what to read (query-aware access). The paper [refinekv] starts from exactly this choice in its Section 2, and its answer leads to the clusters of chapter 18.

17.1 Generating one token at a time

A language model is a function from a sequence of tokens to a probability distribution over the next token (section 12.6 on softmax as a distribution). To write text it runs autoregressively: pick a token from that distribution, append it to the sequence, run again. Token \(t+1\) cannot be computed before token \(t\) exists, so the loop is serial, like a chain of dependent loads.

Inside each layer, the newest token \(t\) makes a query \(q_t\), a key \(k_t\) and a value \(v_t\) (section 16.3), and attends to all positions \(1, \dots, t\) with the causal mask (section 16.5). In the paper's notation, with \(N\) tokens so far:

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

This is Eq. 1 of [refinekv]. The keys \(k_i\) and values \(v_i\) of the old tokens depend only on those tokens, and in a causal model the old tokens never change. So their keys and values computed at an earlier step are still right. Recomputing them each step is pure waste. Keeping them is the KV cache: a memo table, filled once per token.

The cost, counted in multiply-adds for one head with projection matrices \(W_Q, W_K, W_V \in \mathbb{R}^{d \times d}\): computing \(k_i = W_K x_i\) and \(v_i = W_V x_i\) costs \(2d^2\) per token. Without a cache, step \(t\) recomputes them for all \(t\) tokens, so \(T\) steps cost \(2d^2 (1 + 2 + \dots + T) = d^2 T(T+1)\): quadratic in \(T\). With the cache each token is projected once, \(2d^2 T\) in total: linear. The attention itself, \(t\) dot products \(q_t^\top k_i\) and \(t\) scaled additions \(\alpha_i v_i\) at step \(t\), is the same in both, \(2d \cdot T(T+1)/2\) over the run. The cache removes the redundant projections; it cannot remove the attention, because every step's query is new.

A toy run makes the claim concrete: one head with \(d = 8\), each step's input built from the previous output (so the steps really are serial), 64 steps, once without and once with the cache.

/* A toy autoregressive loop: one attention head, d = 8. Each step's input is
   built from the previous step's output. Run it twice: recomputing every key
   and value each step, and keeping them in a cache. Same outputs, less work. */
#include <math.h>
#include <stdio.h>

#define D 8
#define T 64

static double Wq[D][D], Wk[D][D], Wv[D][D];
static long macs;                               /* multiply-adds done */

static void matvec(double W[D][D], const double *x, double *y)
{
    for (int i = 0; i < D; i++) {
        y[i] = 0;
        for (int j = 0; j < D; j++) y[i] += W[i][j] * x[j];
    }
    macs += D * D;
}

/* attend: q against n keys/values, output o */
static void attend(const double *q, double K[][D], double V[][D], int n, double *o)
{
    double s[T], m = -INFINITY, z = 0;
    for (int i = 0; i < n; i++) {
        s[i] = 0;
        for (int j = 0; j < D; j++) s[i] += q[j] * K[i][j];
        s[i] /= sqrt(D);
        if (s[i] > m) m = s[i];
    }
    for (int j = 0; j < D; j++) o[j] = 0;
    for (int i = 0; i < n; i++) {
        double w = exp(s[i] - m);
        z += w;
        for (int j = 0; j < D; j++) o[j] += w * V[i][j];
    }
    for (int j = 0; j < D; j++) o[j] /= z;
    macs += 2L * n * D;
}

static double run(int use_cache)
{
    static double X[T][D], K[T][D], V[T][D];
    double q[D], o[D], check = 0;
    macs = 0;
    for (int j = 0; j < D; j++) X[0][j] = cos(j);      /* the prompt: one token */
    for (int t = 0; t < T; t++) {
        if (use_cache) {                               /* only the new token */
            matvec(Wk, X[t], K[t]);
            matvec(Wv, X[t], V[t]);
        } else {                                       /* all tokens again */
            for (int i = 0; i <= t; i++) {
                matvec(Wk, X[i], K[i]);
                matvec(Wv, X[i], V[i]);
            }
        }
        matvec(Wq, X[t], q);
        attend(q, K, V, t + 1, o);
        if (t + 1 < T)
            for (int j = 0; j < D; j++) X[t + 1][j] = tanh(o[j] + X[t][j]);
        check += o[0];
    }
    return check;
}

int main(void)
{
    for (int i = 0; i < D; i++)
        for (int j = 0; j < D; j++) {
            Wq[i][j] = sin(1.0 + i * D + j);
            Wk[i][j] = sin(2.0 + i * D + j);
            Wv[i][j] = sin(3.0 + i * D + j);
        }
    double a = run(0); long ma = macs;
    double b = run(1); long mb = macs;
    printf("no cache:   checksum %.15f   multiply-adds %ld\n", a, ma);
    printf("with cache: checksum %.15f   multiply-adds %ld\n", b, mb);
    return 0;
}
no cache:   checksum 15.637875770109703   multiply-adds 303616
with cache: checksum 15.637875770109703   multiply-adds 45568

How the program maps to the formulas. matvec is one projection, \(d^2\) multiply-adds; attend is Eq. 1 for one query against \(n = t + 1\) cached rows, with the max subtracted before exp as in section 15.2, and it charges \(2nd\) multiply-adds (the dot products and the weighted sum). The only difference between the two runs is the branch on use_cache: the uncached run fills rows \(0..t\) of K and V again at every step, the cached run fills only row \(t\). The next input \(x_{t+1} = \tanh(o_t + x_t)\) is a stand-in for “sample a token and embed it”: it makes step \(t+1\) depend on the output of step \(t\), which is what forces generation to be serial.

The checksums agree to the last digit, which is the point: \(k_i = W_K x_i\) depends only on \(x_i\), which never changes after step \(i\), so recomputing it yields the same bits. The counts match the formulas: with the cache \(3 \cdot 64 \cdot 64 = 12288\) for the projections plus \(16 \cdot 2080 = 33280\) for attention, 45568; without it the K and V projections alone are \(d^2 \, T(T+1) = 64 \cdot 4160 = 266240\). That is 6.7 times more work in total, and the gap grows linearly with \(T\).

17.2 Prefill and decode

A request has two phases. In prefill the whole prompt, say \(P\) tokens, is known in advance. All \(P\) queries are ready at once, so attention is a matrix product: the \(P \times d\) matrix of queries times the \(d \times P\) matrix of keys, masked to its lower triangle. In decode the model produces the answer one token per step: one new query row against the whole cache, a matrix–vector product.

q1 q2 q3 q4 q5 q6 q7 q8 q9 q10 k1 k2 k3 k4 k5 k6 k7 k8 k9 k10 prefill: all prompt queries at once decode: one new query per step, one row
Figure 17.1. Causal attention for a 6-token prompt and 4 generated tokens. Each row is a query, each column a key; a cell is one dot product \(q^\top k\). Prefill computes the blue block in one matrix product. Decode computes one orange row per step, after the previous token is chosen.

The difference matters because of reuse. Section 9.3 showed that a matrix–matrix product does \(n^3\) multiply-adds on \(n^2\) numbers, so with blocking each number fetched from memory is used about \(n\) times. In prefill, each key is used by every later prompt query: hundreds or thousands of uses per fetch. In decode, each key is used by one query and dropped. Same arithmetic per key pair, very different traffic.

The paper puts it the same way ([refinekv], Appendix C.2.4): prefill runs as “regular, highly optimized matrix–matrix multiplications”, while batch-one decoding “executes sequentially for each generated token and is often dominated by memory-intensive KV-cache access.” Its Table 6 measures Llama-3.1-8B: with a 32K-token prompt, prefill takes 2.41 s and 1024 decode steps take 22.37 s. Per token that is 73.5 µs of prefill against 21.8 ms of decode, a factor of about 300. Decode is where the time goes, so decode is what [refinekv] speeds up.

17.3 The KV cache and its size

Every layer has its own attention, so every layer has its own cache. With grouped-query attention (section 16.6) the cache holds one key and one value per KV head, not per query head. Per token the cache stores, for each layer and each KV head, a key and a value of \(d\) numbers each:

\[ \text{bytes per token} = 2 \cdot \text{layers} \cdot \text{KV heads} \cdot \text{head dim} \cdot \text{bytes per element}. \]

The 2 counts K and V. Llama-3.1-8B has 32 layers, 8 KV heads (shared by 32 query heads, 4 per KV head) and head dimension 128; that is its published configuration [llama3], and the paper repeats it in Appendix C.2.1 [refinekv]. Stored in bf16 (2 bytes, section 14.7):

\[ 2 \cdot 32 \cdot 8 \cdot 128 \cdot 2 = 131072 \text{ bytes} = 128 \text{ KiB per token}. \]

At the model's 128K-token context (\(131072\) tokens) that is \(2^{17} \cdot 2^{17} = 2^{34}\) bytes, 16 GiB, for one sequence. For comparison, the model's 8 billion weights take about 16 GB in bf16. The cache of one long conversation is as large as the model.

model (bf16)KV headsper token4K tokens32K tokens128K tokens
Llama-3.1-8B8128 KiB0.5 GiB4 GiB16 GiB
the same with MHA32512 KiB2 GiB16 GiB64 GiB
Qwen2.5-7B456 KiB0.22 GiB1.75 GiB7 GiB

The second line shows what GQA buys: with a KV head per query head (plain multi-head attention) the cache would be four times larger, 64 GiB at 128K. Qwen2.5-7B, the paper's other model (28 layers, 4 KV heads, head dimension 128, Appendix C.2.1), needs \(2 \cdot 28 \cdot 4 \cdot 128 \cdot 2 = 57344\) bytes, 56 KiB, per token. The size is linear in every factor, so the levers are visible in the formula: fewer KV heads (GQA, MQA), fewer bytes per element (8-bit caches), or fewer tokens kept (section 17.5).

tokens 0 … N−1 → K cache 32 layers head 0 head 7 tokens 0 … N−1 → V cache 32 layers head 0 head 7 blue: one key, d = 128 numbers green: the next token, appended
Figure 17.2. The cache of Llama-3.1-8B as two arrays, K[32][8][N][128] and V[32][8][N][128]: layers, KV heads, tokens, coordinates. Each decode step appends one token (green) to every layer and head. One attention head at one step reads one horizontal strip: all \(N\) keys and values of its KV head in its layer.

The memory is allocated as the sequence grows and freed when it ends. Serving systems store it in fixed-size blocks, mapped through a per-sequence table like virtual-memory pages, so that sequences of unknown length do not fragment GPU memory; that is PagedAttention [vllm]. A block of contiguous tokens is also the natural unit for the methods of section 17.6 and chapter 18.

17.4 Why decoding is memory-bound

Count one decode step of one query head against \(N\) cached tokens:

So the arithmetic intensity, FLOPs per byte moved from memory, is

\[ \frac{4Nd \text{ FLOP}}{4Nd \text{ byte}} = 1 \text{ FLOP/byte}. \]

With GQA the 4 query heads of a group read the same keys and values, so a kernel that handles them together gets 4 FLOP/byte; that is still tiny. Compare prefill, where a key fetched once serves up to \(P\) queries, giving an intensity that grows with \(P\).

The roofline model [roofline] turns this into a speed limit. A machine can do at most \(F\) FLOP/s and move at most \(B\) byte/s. A loop with intensity \(I\) runs at most at \(\min(F, B \cdot I)\) FLOP/s. Below the ridge point \(I = F/B\) the bandwidth decides; above it the arithmetic does. A GPU's ridge point is far above 4 FLOP/byte, which is why [pope] find that decode attention is limited by the time to load the KV cache, and why batching more queries per key, as GQA and multi-query attention do [mqa], helps.

The same thing on one core of fbsd-srv (an Intel Core i5-9400). The program first just reads a 512 MiB key array to measure the bandwidth one core gets, then computes \(K q\) for one query, then \(K Q\) for \(B\) queries that share each key fetch. Floats, not bf16, so here one query is 0.5 FLOP/byte for the keys alone.

/* Time s = K q for 2^20 keys of d = 128 floats (512 MiB, far beyond any CPU
   cache), then for B queries at once: the keys read once, used B times.
   Keys are stored in tiles of 32 (tile[j][l] = key l, coordinate j) so the
   inner loop runs across keys, 4 floats per SSE instruction. One core. */
#define _POSIX_C_SOURCE 199309L                /* clock_gettime, in glibc too */
#include <stdio.h>
#include <stdlib.h>
#include <time.h>

#define D 128
#define N (1L << 20)
#define TL 32

static double now(void)
{
    struct timespec t;
    clock_gettime(CLOCK_MONOTONIC, &t);
    return t.tv_sec + 1e-9 * t.tv_nsec;
}

int main(void)
{
    float *K = malloc(sizeof(float) * N * D);
    float *Q = malloc(sizeof(float) * 64 * D);
    float *s = malloc(sizeof(float) * N * 64);
    if (!K || !Q || !s) return 1;
    for (long i = 0; i < N * D; i++) K[i] = (float)((i * 2654435761u) % 1000) / 1000 - 0.5f;
    for (long i = 0; i < 64 * D; i++) Q[i] = (float)(i % 7) / 7 - 0.5f;

    double best = 1e9, sum = 0;                     /* first: just read K */
    for (int rep = 0; rep < 5; rep++) {
        float acc[TL] = { 0 };
        double t0 = now();
        for (long i = 0; i < N * D; i += TL)
            for (int l = 0; l < TL; l++) acc[l] += K[i + l];
        double dt = now() - t0;
        if (dt < best) best = dt;
        for (int l = 0; l < TL; l++) sum += acc[l];
    }
    printf("read only: %6.1f ms  %5.1f GB/s  (sum %g)\n", best * 1e3,
           sizeof(float) * (double)N * D / best / 1e9, sum);

    int bs[] = { 1, 2, 4, 16, 64 };
    for (int t = 0; t < 5; t++) {
        int B = bs[t];
        best = 1e9;
        for (int rep = 0; rep < 5; rep++) {
            double t0 = now();
            for (long i0 = 0; i0 < N; i0 += TL) {
                const float *tile = K + i0 * D;            /* D rows of TL keys */
                for (int b = 0; b < B; b++) {
                    const float *q = Q + b * D;
                    float acc[TL] = { 0 };
                    for (int j = 0; j < D; j++)
                        for (int l = 0; l < TL; l++) acc[l] += q[j] * tile[j * TL + l];
                    for (int l = 0; l < TL; l++) s[(i0 + l) * B + b] = acc[l];
                }
            }
            double dt = now() - t0;
            if (dt < best) best = dt;
        }
        double bytes = (double)N * D * sizeof(float), flops = 2.0 * N * D * B;
        printf("B = %2d:    %7.1f ms  %5.1f GB/s of keys  %5.1f GFLOP/s  (%4.1f FLOP/byte)\n",
               B, best * 1e3, bytes / best / 1e9, flops / best / 1e9, flops / bytes);
    }
    printf("check %f\n", s[12345]);
    free(K); free(Q); free(s);
    return 0;
}
read only:   24.2 ms   22.2 GB/s  (sum -335543)
B =  1:       26.3 ms   20.4 GB/s of keys   10.2 GFLOP/s  ( 0.5 FLOP/byte)
B =  2:       36.1 ms   14.9 GB/s of keys   14.9 GFLOP/s  ( 1.0 FLOP/byte)
B =  4:       53.6 ms   10.0 GB/s of keys   20.0 GFLOP/s  ( 2.0 FLOP/byte)
B = 16:      164.4 ms    3.3 GB/s of keys   26.1 GFLOP/s  ( 8.0 FLOP/byte)
B = 64:      606.3 ms    0.9 GB/s of keys   28.3 GFLOP/s  (32.0 FLOP/byte)
check 0.275429

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 the program is built, and why. The keys are not stored as \(N\) rows of \(d\) but in tiles of 32 keys laid out coordinate-major (tile[j*TL + l] is coordinate \(j\) of key \(l\)). Then the inner loop over l computes 32 partial dot products \(s_l \mathrel{+}= q_j k_{lj}\) side by side with no dependency between them, which the compiler turns into SSE instructions; the row layout would instead give one long sum per key, a chain of dependent additions that runs at the adder's latency, not its throughput. Without that, the loop would be slow for reasons that have nothing to do with memory, and the experiment would measure the wrong thing. The loop over b sits inside the tile loop: a tile (16 KiB) is fetched from DRAM once and then stays in L1 while all \(B\) queries use it, so the FLOPs grow with \(B\) while the bytes from memory do not: intensity \(2dB / 4d = B/2\) FLOP/byte. The first loop, a plain sum over K, measures the bandwidth one core gets with no arithmetic to speak of: it is the \(B\) of the roofline. Each timing is the best of five, so page faults of the first touch and the other users of the machine count as little as possible.

With one query, \(Kq\) streams the keys at 20.4 GB/s, 92% of the 22.2 GB/s a bare read gets, while doing 10.2 GFLOP/s, about a third of the 28.3 GFLOP/s the same loop reaches when each key is reused 64 times. The arithmetic units idle two thirds of the time, waiting for memory. Adding a second query costs only 37% more time; adding 63 more costs 23 times more, but by then each key is reused enough that the loop is compute-bound.

1/4 1 4 16 64 1 4 16 64 B=1 B=2 B=4 B=16 B=64 22.2 GB/s × intensity 28.3 GFLOP/s FLOP per byte read GFLOP/s
Figure 17.3. The roofline of this loop on one core: the sloped line is bandwidth times intensity, the flat line the compute roof (both measured above), log scales. Red points are the runs with \(B\) queries per key. Decode attention lives at the far left.

For the full model the arithmetic is brutal. One decode step at \(N = 131072\) reads the whole 16 GiB cache once (every layer, every KV head) for \(32 \cdot 32 \cdot 4Nd \approx 68.7\) GFLOP of attention. At the 22.2 GB/s measured above, reading it alone would take 774 ms per generated token. On a GPU the bandwidth is far higher than one CPU core's, but the shape is the same: time per token grows linearly with \(N\), and the cost is bytes read. The rest of the book is about reading fewer bytes while keeping \(o\).

In the machine. This is the Pentium Pro lesson again: a loop that touches each byte once and does one operation per byte runs at the speed of the memory bus, and a faster ALU does nothing for it. The cures are the old ones too: reuse each fetched line more (batch queries, GQA), fetch fewer bytes (smaller formats, section 14.7), or skip lines you can prove you do not need (section 17.6).

17.5 Evicting entries

The first idea is to keep only some of the cache: a budget of entries per head, and a rule for which to drop when it is full. A dropped entry is gone for good; every later query attends over what remains, renormalized. The methods differ in the rule:

The paper also compares with TOVA [tova], which keeps the tokens the current queries attend to most, and RoCo [roco]. Its Section 6 names the common flaw: “these methods make irreversible decisions about the KV cache: discarded or merged token-level states are no longer fully accessible to future queries.” A token judged useless at step 100 may be exactly what the query at step 500 needs, and then it is not there.

A synthetic experiment shows the effect (1024 random keys and values in \(d = 64\), 256 random queries; the numbers illustrate, they do not measure a model). For each query, take its critical set: the fewest keys whose weights \(\alpha_i\) add up to 90%. On average a critical set has 12.8% of the keys, and attention renormalized over it is off by 4.7% (relative error of the output). But the union of the 256 critical sets is 100% of the keys. Now evict H2O-style: rank keys by the attention the first 128 queries paid them in total, keep the top 131 (the average critical-set size), and serve the last 128 queries from that fixed set. Their output error is 71%; each query's own top 131 keys would give 4.4%.

The reason is in the definitions: a fixed set \(S\) serves query \(q\) well only if \(S\) contains most of \(q\)'s critical set, and when the critical sets of different queries barely overlap, no small \(S\) contains most of each. Random queries are the worst case for eviction; real ones share more, but section 17.6 shows that a real model is not far from this.

17.6 Query-aware access

The alternative keeps the whole cache and chooses, for each query, which part to read. The problem is the choice itself: to know which keys have large \(q^\top k_i\), you would compute all of them, which reads the whole cache, the thing to avoid. The way out is a summary: a few numbers per block of keys, small enough to read for every block, from which a bound on the block's logits follows.

Quest [quest] splits the cache into pages of contiguous tokens and stores for each page the coordinate-wise minimum \(m_j\) and maximum \(M_j\) of its keys: a box containing every key of the page. For a query, the dot product over the box is at most

\[ U = \sum_{j=1}^{d} \max(q_j m_j,\; q_j M_j) \;\ge\; q^\top k_i \quad \text{for every key } k_i \text{ in the page}, \]

because each term \(q_j k_{ij}\) is linear in \(k_{ij}\) on the interval \([m_j, M_j]\), so its largest value is at an end (this is the box bound of section 10.6). Quest scores each page by \(U\), loads the top pages and does exact attention over them alone. The other pages are skipped for this query, but kept for the next one. As C-like pseudocode:

for (p = 0; p < pages; p++) {           /* reads 2d numbers per page */
    U[p] = 0;
    for (j = 0; j < d; j++)
        U[p] += max(q[j] * lo[p][j], q[j] * hi[p][j]);
}
load the pages with the largest U[p];    /* exact attention over them */

The max is the sign test of the derivation: for \(q_j \ge 0\) the larger term is \(q_j M_j\), for \(q_j < 0\) it is \(q_j m_j\), so the loop picks, coordinate by coordinate, the corner of the box that is best for this query. That corner is usually no actual key, which is why \(U\) is an upper bound and not the maximum. The cost is \(2d\) numbers read per page instead of \(2d \cdot 16\) for its keys and values.

A synthetic check (4096 keys whose neighbours are alike, pages of 16, 32 of 256 pages loaded, 100 queries): the bound was below a page's true maximum logit in 0 of 25600 cases, as the derivation promises. It is loose, by 10 logits on average, but what Quest needs is the ranking, and the pages it picks hold 77.6% of the attention against 81.7% for the best possible 32 pages. The summary costs \(2d\) numbers per page of 16 keys, an eighth of the size of the keys it describes.

The paper's argument

Section 2 of [refinekv] measures how much of the cache a query really needs, on Llama-3.1-8B: all 32 layers, 20 segments of 1,024 tokens of WikiText-2 (Appendix C.1). For each query head it takes the smallest set of KV entries holding \(p\%\) of the attention, the query's critical set; the 4 query heads that share a KV head take the union of their sets. Its findings (Section 2, Figure 1 left):

The conclusion is the toy's, on real data: “different queries rely on different KV pairs, therefore a fixed subset of cache simply cannot work for all queries.” Any fixed subset small enough to save reads misses a large part of most later queries' critical sets. Figure 1 (right) checks it end to end: on WikiText-2 perplexity, oracle top-\(k\) per query beats H2O, RoCo and TOVA at the same fraction of entries read. So the access must be decided per query.

That leaves the efficiency question the paper's Section 3.1 starts from: decide per query without visiting each entry. Its answer is Quest's shape: “partition KV entries into clusters, and use only cluster-level summaries to decide which clusters require token-level access.” Unselected clusters can be pruned, as Quest and MoBA [moba] do, or replaced by a representative, as Multipole Attention [multipole] and Double-P [doublep] do. RefineKV takes the second route. Chapter 18 builds clusters and their representatives and measures what replacing a cluster costs; chapter 19 bounds that cost.

Exercises

  1. Qwen2.5-7B has 28 layers, 4 KV heads and head dimension 128. How large is its bf16 cache per token and at 128K tokens?
    Answer

    \(2 \cdot 28 \cdot 4 \cdot 128 \cdot 2 = 57344\) bytes = 56 KiB per token; times \(2^{17}\) tokens, 7 GiB. The smaller GQA group count (4 KV heads, 7 query heads each) is most of the saving.

  2. Llama-3.1-8B's cache is stored in an 8-bit format instead of bf16. Bytes per token, and size at 128K tokens?
    Answer

    Half: \(2 \cdot 32 \cdot 8 \cdot 128 \cdot 1 = 65536\) bytes = 64 KiB per token, 8 GiB at 128K. Halving the bytes also doubles the arithmetic intensity of decode, to 2 FLOP/byte per query head.

  3. In Qwen2.5-7B, 7 query heads share each KV head. What is the arithmetic intensity of decode attention (bf16) if a kernel processes a whole group per fetch? Is it still memory-bound on a machine whose ridge point is 50 FLOP/byte?
    Answer

    Each fetched key and value (\(4d\) bytes) now serves 7 heads of \(4d\) FLOPs: 7 FLOP/byte. Yes, far below 50.

  4. In the toy program of section 17.1 without the cache, how many key projections are done for \(T = 64\) steps, and how many multiply-adds for K and V together? Check against the printed total.
    Answer

    Step \(t\) (from 0) projects \(t + 1\) tokens: \(1 + \dots + 64 = 2080\) key projections, as many value projections, each \(d^2 = 64\) multiply-adds: \(2 \cdot 2080 \cdot 64 = 266240\). Add 64 query projections (4096) and the attention, \(16 \cdot 2080 = 33280\): 303616, as printed. With the cache the K and V part is \(2 \cdot 64 \cdot 64 = 8192\).

  5. Prove Quest's bound: if \(m_j \le k_j \le M_j\) for each \(j\), then \(q^\top k \le \sum_j \max(q_j m_j, q_j M_j)\). When is it exact?
    Answer

    If \(q_j \ge 0\), \(q_j k_j \le q_j M_j\); if \(q_j < 0\), \(q_j k_j \le q_j m_j\). Either way \(q_j k_j \le \max(q_j m_j, q_j M_j)\); add over \(j\). It is exact when one key of the page sits at the right corner of the box in every coordinate (for example, a page whose keys are all equal); for spread-out keys the corner is usually no real key, so the bound is loose.

  6. From the paper's Table 6: 32K prompt, prefill 2.41 s, 1024 decode steps 22.37 s. Time per token in each phase, and their ratio?
    Answer

    \(2.41 / 32768 \approx 73.5\) µs; \(22.37 / 1024 \approx 21.8\) ms; ratio about 297. Prefill tokens are processed in parallel with high reuse; decode tokens one at a time, each reading the weights and the whole cache.

  7. A user pastes a 100K-token contract and, after a long discussion, asks about clause 7, which is in the middle. Which of StreamingLLM, H2O and Quest can answer, and why?
    Answer

    StreamingLLM has dropped the middle: only the sinks and the recent window remain. H2O kept clause 7 only if earlier queries attended to it heavily, which a long unrelated discussion makes unlikely. Quest kept everything, and the new query's large \(q^\top k\) on clause 7's keys makes its pages score high, so they are loaded. This is the paper's Section 2 point in one example.

References