Skip to main content

LLM inference kernels

KV Cache Explained: Stop Recomputing the Past

Published 6 min 21 sMeasured on NVIDIA L4

What this video shows

About this walkthrough

A decoder that recomputes keys and values for every earlier token repeats work on each step. This walkthrough explains keys and values, then edits a small single-head attention decoder to compute the newest key and value once and reuse the cached ones. Throughput goes from 9,409.2 to 119,699.6 tokens per second, with correctness passing in both runs. The result belongs to this simplified workload and is not a speedup claim for production language models.

Read along

Transcript

Select a time to play the video from that chapter.

0:00Stop repeating the same work

Batching lets independent requests run together. But every new token can still repeat work we already finished. Let's find that work and cache it in GPUFlight Performance Lab.

0:14Understand the workload and goal

This lab uses a small, single-head attention decoder, not a complete language model. It serves sixteen sequences together, using vectors with 128 values. The goal is to keep the output correct and increase aggregate tokens per second across those sequences.

0:35Keys and values, briefly

Attention uses a query to decide which earlier tokens matter. Each token has a key to compare with the query, and a value carrying information to combine. Softmax turns the matching scores into weights. The attention output is a weighted sum of the values. Here, multiplying a token's vector by weight matrices produces its key and value. Those are the results we will reuse.

1:04Find the repeated calculations

Look inside scores naive. For every token in the history, the inner loop calculates its key again. Now look at output naive. This inner loop recalculates the token's value before combining it with the attention weight. The old token vectors and projection weights have not changed. Repeating these projections does not add new information.

1:29Measure the unchanged baseline

The unchanged starter passes the reference check, but reaches only about nine thousand four hundred tokens per second. That is below the target of fifty thousand. Both versions use the same fixed workload and an L4 GPU. Open the baseline session to see where its kernel time goes.

1:51Explore the baseline timeline

The timeline shows the repeated execution of the decoder. A kernel is a function launched on the GPU. Zoom in to explore the launches. At wider views, the app groups several launches into a bar. For durations, return to the kernel table. Scores naive takes sixty-six point four percent of recorded kernel time, and output naive takes thirty-two percent. Together, those are the two stages we need to improve.

2:24Compute once, then reuse

Keep a cache indexed by sequence, token, and vector dimension. At step t, the newest available token is t minus one. Compute its key and value, then append them to the cache. Read earlier entries directly. When a new generation begins, each entry is overwritten before it is read again.

2:46Edit 1: append the newest key and value

First, add append K V. Each thread computes one output dimension for one sequence. This base offset selects the newest token's cache entry. The loop performs the same key and value projections as before, then stores both results. We calculate the new token once per step, instead of projecting the entire history again.

3:11Edit 2: read the cache

Next, replace the score kernel's projection loop with a read from the key cache. The dot product with the query and its scaling stay the same. In the output kernel, replace the value projection with a read from the value cache. The softmax weights still combine the values in the same order. Query calculation, softmax, and output normalization are unchanged.

3:38Edit 3: keep the launches ordered

Add the cache update before the score calculation, and pass the cache pointers to the new kernels. These launches use the same CUDA stream. The cache update completes before the later kernels read its results. We added a kernel launch, but removed repeated arithmetic. The goal is less total work, not simply fewer launches.

4:02Verify and profile the cached version

The cached version passes the reference check and clears the throughput target. Compare the baseline timeline with the cached version, using similar time windows. The cached trace contains more launches because this timed benchmark repeats faster decoding steps. Now compare the average kernel durations. The score stage drops from 1.13 milliseconds to 10.09 microseconds. The output stage drops from about 545 microseconds to 2.17 microseconds. Updating the cache adds about 34 microseconds per launch. That is much cheaper than repeatedly projecting the history.

4:49Compare measured throughput

Select the baseline and cached run in the history, then click Compare. Throughput increases from about 9,400 to 119,700 tokens per second. That is about 12.7 times the baseline. The harness generates repeatedly for about three seconds. More tokens fit into that window, even though total program time stays similar. This comparison uses the graded throughput from execution without the profiler attached. The profiling trace helps us explain how the execution changed.

5:28What the cache does not remove

The tradeoff is memory: we must keep the keys and values for the sequence history. This lab already allocates the cache buffers. We put them to use; we are not adding another allocation. Caching removes repeated projections. Attention still reads earlier keys and values, so longer histories still cost work. This is a small educational workload. The measured speedup is not a prediction for every language model.

6:00Keep results that remain valid

Look for intermediate results that stay valid between steps. Compute them once, reuse them, and check the result. Use the timeline to explain the execution, and the throughput measurement to judge the improvement. Try the key-value cache lab in GPUFlight Performance Lab.

Measure it yourself

Run the same experiment on a real GPU

Edit the kernel in your browser, run it on managed hardware, and read the profile the video walks through.

Run the KV cache lab