KV Cache
KV vectors are used to calculate attention scores, and a KV cache stores these calculations so they can be reused without recomputing them.
Definition · At a glance · How it works
Definition
The key-value (KV) vectors are used to calculate attention scores. A KV cache stores these calculations so they can be reused without recomputing them. Transformers offers several Cache classes that implement different caching mechanisms. Some of these Cache classes are optimized to save memory while others are designed to maximize generation speed.
At a glance
The documentation describes how repeated KV calculation relates to caching.
How it works
DynamicCache is the default cache class. It allows the cache size to grow dynamically in order to store an increasing number of keys and values as generation progresses. For models using sliding window attention (Mistral, Gemma2, and others) or chunked attention (Llama4), the cache stops growing when the layers using these types of attention have reached their maximum size, which is the sliding window or chunk size.
Setting the use_cache option to False in generate() disables the cache. The default DynamicCache prevents you from taking advantage of most just-in-time (JIT) optimizations because the cache size is not fixed. A fixed-size cache (StaticCache) pre-allocates a specific maximum cache size for the kv pairs.
Generation can reach the maximum cache size without modifying it. StaticCache allows the decoding stage to be compiled, but it incurs a waste of tokens in the attention computation. Setting cache_implementation to static in generate() enables StaticCache and also turns on automatic compilation of the decoding stage for greedy and sample decoding strategies.
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. Only the current layer cache is maintained on the GPU during a model's forward iteration over the layers.
Offloading asynchronously prefetches the next layer's cache and sends the current layer's cache back to the CPU after attention computation. Compared to a full on-device cache, generation throughput may degrade slightly, depending on the model and generation choices (context size, number of generated tokens, number of beams, and so on). QuantizedCache reduces memory requirements by quantizing the KV values to a lower precision.
Quantizing the cache can harm latency if the context length is short and there is enough GPU memory available for generation without enabling cache quantization. The fp8 backend stores the KV values in 8-bit floating point. The fp8 backend does not take additional parameters, and it raises if it is given a group-wise one.
Mamba models, such as Mamba, require a specific cache because the model does not have an attention mechanism or kv states. EncoderDecoderCache is designed for encoder-decoder models.
Example
A cache can also work in iterative generation settings where there is back-and-forth interaction with a model (chatbots). Like regular generation, iterative generation with a cache allows a model to handle ongoing conversations without recomputing the entire context at each step. For iterative generation with a cache, start by initializing an empty cache class and then feed in new prompts.
Dialogue history is tracked with a chat template. The documented example demonstrates Llama-2-7b-chat-hf. The crop() method rolls back tokens from a cache, such as when a candidate continuation is rejected during iterative generation.
The number of tokens to remove is passed as a negative integer. Sliding-window and linear-attention layers discard past states as they go, so there is nothing to roll back to by default. In some situations, a Cache can be filled with kv pairs for a certain prefix prompt and reused to generate different sequences.
The prefix-caching example initializes a StaticCache and then caches an initial prompt. Several sequences can then be generated from the prefilled prompt.
import torch
from transformers import AutoTokenizer,AutoModelForCausalLM, DynamicCache, StaticCache
model_id = "meta-llama/Llama-2-7b-chat-hf"
model = AutoModelForCausalLM.from_pretrained(model_id, dtype=torch.bfloat16, device_map='auto')
tokenizer = AutoTokenizer.from_pretrained(model_id)
user_prompts = ["Hello, what's your name?", "Btw, yesterday I was on a rock concert."]
past_key_values = DynamicCache(config=model.config)
messages = []
for prompt in user_prompts:
messages.append({"role": "user", "content": prompt})
inputs = tokenizer.apply_chat_template(messages, add_generation_prompt=True, return_tensors="pt", return_dict=True).to(model.device)
input_length = inputs["input_ids"].shape[1]
outputs = model.generate(**inputs, do_sample=False, max_new_tokens=256, past_key_values=past_key_values)
completion = tokenizer.decode(outputs[0, input_length: ], skip_special_tokens=True)
messages.append({"role": "assistant", "content": completion})# Remove the last three tokens from the cache.
past_key_values.crop(-3)import copy
import torch
from transformers import AutoModelForCausalLM, AutoTokenizer, DynamicCache, StaticCache
model_id = "meta-llama/Llama-2-7b-chat-hf"
model = AutoModelForCausalLM.from_pretrained(model_id, dtype=torch.bfloat16, device_map={"": 0})
tokenizer = AutoTokenizer.from_pretrained(model_id)
# Init StaticCache with big enough max-length (1024 tokens for the below example)
# You can also init a DynamicCache, if that suits you better
prompt_cache = StaticCache(config=model.config, max_cache_len=1024)
INITIAL_PROMPT = "You are a helpful assistant. "
inputs_initial_prompt = tokenizer(INITIAL_PROMPT, return_tensors="pt").to(model.device.type)
# This is the common prompt cached, we need to run forward without grad to be able to copy
with torch.no_grad():
prompt_cache = model(**inputs_initial_prompt, past_key_values = prompt_cache).past_key_values
prompts = ["Help me to write a blogpost about travelling.", "What is the capital of France?"]
responses = []
for prompt in prompts:
new_inputs = tokenizer(INITIAL_PROMPT + prompt, return_tensors="pt").to(model.device.type)
past_key_values = copy.deepcopy(prompt_cache)
outputs = model.generate(**new_inputs, past_key_values=past_key_values,max_new_tokens=20)
response = tokenizer.batch_decode(outputs)[0]
responses.append(response)
print(responses)Sources
This page is written from the official sources below. Open them to check the original text.
- Official documentationhttps://huggingface.co/docs/transformers/kv_cacheFetched
Verified ·
This page is written by AI from the official sources above and checked automatically. This site has not tested it. Found a mistake? Tell us.