This technical overview details the mechanics of Transformer inference, specifically focusing on the optimization provided by the Key-Value (KV) cache during the decoding stage. Transformer inference is divided into two distinct phases: the prefill stage and the decode stage. During prefill, the model processes the initial input tokens in parallel to compute and store their corresponding key ($K$) and value ($V$) tensors in a cache. In the subsequent decode stage, the model generates text autoregressively, one token at a time. Rather than recomputing the attention mechanism for the entire sequence—which would involve redundant calculations—the model utilizes the KV cache to reuse previously computed $K$ and $V$ vectors. For each new step, the model only computes the query ($Q$), key ($K$), and value ($V$) vectors for the single most recent token. The new $K$ and $V$ vectors are appended to the existing cache, and the current query is multiplied by the transpose of the updated key matrix to produce attention scores. This process continues across every Multi-Head Attention block and every Transformer layer, requiring a dedicated set of cache pairs for each layer. While this method significantly improves computational efficiency by avoiding redundant operations, it introduces a memory trade-off, as the memory footprint required for the cache grows linearly with the context-window length.

Read original