New Tool Radar

AI Concepts

How to Offload the KV Cache to CPU Memory for Long Contexts

Enable an offloaded cache when GPU memory runs out, and accept a small throughput cost in exchange for a context that fits.

Schematic with three steps: Confirm the failure is the cache, not; Enable the offloaded cache; Run the long prompt and compare speed.

The KV cache can occupy a significant portion of memory and become a bottleneck for long-context generation. Offloading the cache saves GPU memory by moving the KV cache for model layers except one to the CPU, keeping only the current layer cache on the GPU during each forward iteration, and asynchronously prefetching the next layer cache. Use offloading when you have a small GPU and you are getting out-of-memory errors on long contexts, and accept that moving key and value states back and forth costs some throughput.

What you need

  • A model and a long prompt that runs out of GPU memory
  • Enough CPU memory to hold the offloaded cache
  • A note of the throughput you can accept

Step 1: Confirm the failure is the cache, not the weights

If the model loads but a long prompt fails with an out-of-memory error, the cache is the likely cause. If the model itself does not load, offloading the cache will not help.

Step 2: Enable the offloaded cache

Set cache_implementation to offloaded for the dynamic cache, or offloaded_static for the static cache, in generate or GenerationConfig. You can also pass an offloaded DynamicCache directly with offloading set to True.

Step 3: Run the long prompt and compare speed

Run the prompt that failed before and confirm it completes. Then compare the generation speed with a short prompt that fit in GPU memory, so you know what the offload costs.

Worked example: synthetic KV cache offload check

The table below is a synthetic example. It shows the expected result of offloading the cache; no model was run.

Setting 32k-token prompt Speed
GPU cache Out of memory Not run
Offloaded cache Completes About 15 percent slower
Short prompt, GPU cache Completes Full speed
Decision Offload for long prompts Fits, small speed cost

Expected result (UNTESTED). the offloaded cache completes the 32k-token prompt at about 15 percent lower speed, while the GPU cache runs out of memory. This check was not run live; the table shows the expected result for the synthetic example.

Limits

  • You may notice a small degradation in generation throughput compared with a full on-device cache, depending on the model and generation choices.
  • Offloading is available for both DynamicCache and StaticCache, with offloaded_static for the static version.
  • Layers using sliding window attention are usually short, so offloading them may incur a speed penalty for little saving.
  • If the model itself does not fit, offloading the cache is the wrong fix; quantize the weights instead.

Sources

See all