Does KV Caching Really Speed Up LLM Inference?
From the publisher’s feed, collected in the ZeroLabs newsroom.
Understanding prefill, decoding, GPU memory, and inference latency by benchmarking Qwen2.5–0.5B with KV caching enabled and disabled.When we ask a language model to generate text, it doesn’t produce the entire response in one operation. It generates tokens sequentially, using the previously generated tokens as context.But here’s an interesting question:Does an LLM need to recalculate information from all previous tokens every time it generates a new one?Without KV caching, much of that computation is repeated. With KV caching, the model stores previously computed attention keys and values so it can reuse them.I wanted to understand how much difference this actually makes.So I ran a small experiment using Qwen2.5–0.5B-Instruct on a Google Colab Tesla T4 GPU, comparing inference with KV caching enabled and disabled.The initial results were interesting:With a 40-token prompt, KV caching improved generation speed by 1.15×.With a 512-token prompt, the improvement increased to 1.39×.For the longer prompt, caching reduced median inference time from 2.308 seconds to 1.656 seconds.Peak GPU memory allocation increased by approximately 2.63 MB.The experiment highlights an important trade-off: using additional GPU memory can sometimes reduce computation and improve inference speed.Here, we’ll reproduce the experiment step by step using Google Colab, Hugging Face Transformers, PyTorch, and Matplotlib.No model training or fine-tuning is required.What will we build?By the end, we’ll have a notebook that can:Run inference using a pretrained language model.Inspect prefill and token-by-token decoding.Observe how a KV cache grows.Compare generation with KV caching enabled and disabled.Benchmark different input sequence lengths.Measure inference latency and output tokens per second.Analyse GPU memory consumption.Visualise performance and memory trade-offs using Matplotlib.We’ll use the same language model throughout, changing its caching behaviour to understand the difference.Before we begin: What is KV caching?Transformer language models use an attention mechanism to determine how tokens relate to one another.During attention computation, each token is transformed into three representations:Query (Q): What information is the current token looking for?Key (K): What information can this token be matched against?Value (V): What information does the token contribute?** Think of it like taking notes while reading a long document. Without notes, you repeatedly reread earlier sections to recover important information. With notes, you can reference information you’ve already processed.KV caching follows a similar principle, except the stored information consists of numerical tensors rather than human-readable notes.Setup Google Collab And Run the following to inspect your environment.import sysimport torchprint("=== ENVIRONMENT CHECK ===")print("Python:", sys.version.split()[0])print("PyTorch:", torch.__version__)print("CUDA available:", torch.cuda.is_available())if torch.cuda.is_available(): gpu = torch.cuda.get_device_properties(0) print("GPU:", torch.cuda.get_device_name(0)) print( "GPU Memory:", round(gpu.total_memory / 1024**3, 2), "GB" ) print("CUDA Version:", torch.version.cuda)My environment looked like this, but it might differ based on available colabStep 2: Install the required libraries%pip install -q \ "transformers==5.23.0" \ "accelerate==1.15.0" \ "huggingface-hub==1.33.0" \ matplotlibimport transformersimport accelerateimport huggingface_hubprint("Transformers:", transformers.__version__)print("Accelerate:", accelerate.__version__)print("Hugging Face Hub:", huggingface_hub.__version__)Step 3: Load Qwen2.5–0.5B-InstructI selected Qwen2.5–0.5B-Instruct.It’s small enough to run on a Tesla T4 and supports standard autoregressive generation with Hugging Face Transformers.import torchfrom transformers import ( AutoTokenizer, AutoModelForCausalLM)MODEL_ID = "Qwen/Qwen2.5-0.5B-Instruct"tokenizer = AutoTokenizer.from_pretrained(MODEL_ID)model = AutoModelForCausalLM.from_pretrained( MODEL_ID, dtype=torch.float16).to("cuda")model.eval()#Now inspect the model:total_params = sum( p.numel() for p in model.parameters())gpu_memory = torch.cuda.memory_allocated() / 1024**3print("Model:", MODEL_ID)print("Parameters:", f"{total_params:,}")print("Precision:", next(model.parameters()).dtype)print("Device:", next(model.parameters()).device)print("Default KV Cache:", model.config.use_cache)print("Allocated GPU Memory:", round(gpu_memory, 3), "GB")My output:Model: Qwen/Qwen2.5-0.5B-InstructParameters: 494,032,768Precision: torch.float16Device: cuda:0Default KV Cache: TrueAllocated GPU Memory: 0.928 GBNotice the final line:Default KV Cache: TrueThe model is already configured to use caching during generation.We’ll explicitly switch it on and off in our experiments.Step 4: Generate text and measure inference timeBefore comparing caching strategies, let’s generate some text.We’ll use the following prompt:Explain how solar panels generate electricity in simple terms.First, convert the prompt into tokens using the model’s chat template.messages = [ { "role": "user", "content": ( "Explain how solar panels generate " "electricity in simple terms." ) }]inputs = tokenizer.apply_chat_template( messages, tokenize=True, add_generation_prompt=True, return_dict=True, return_tensors="pt").to("cuda")Now generate up to 100 tokens while measuring execution time.import timeinput_tokens = inputs["input_ids"].shape[-1]torch.cuda.synchronize()start = time.perf_counter()with torch.inference_mode(): outputs = model.generate( **inputs, max_new_tokens=100, do_sample=False, use_cache=True, pad_token_id=tokenizer.eos_token_id )torch.cuda.synchronize()elapsed = time.perf_counter() - startgenerated_tokens = outputs.shape[-1] - input_tokensresponse = tokenizer.decode( outputs[0][input_tokens:], skip_special_tokens=True)print("Input tokens:", input_tokens)print("Generated tokens:", generated_tokens)print("Inference time:", round(elapsed, 3), "seconds")print( "Output throughput:", round(generated_tokens / elapsed, 2), "tokens/second")print("\nMODEL RESPONSE:")print(response)My Output:This first run shouldn’t be treated as a reliable benchmark. It can include initialization and GPU warm-up overhead.The response also stopped before completing its explanation because generation reached the configured token limit.Three terms are important here.Inference latency is the elapsed time needed to produce the response.Output throughput, in this experiment, is the number of generated tokens divided by elapsed time.GPU synchronisation ensures that queued GPU operations finish before we stop the timer.Without synchronisation, Python timing can underestimate GPU execution time because CUDA operations are generally asynchronous.Step 5: Understand prefill and decodingPrefillThe model processes the input prompt and calculates the attention representations needed to predict the next token.In our example, the prompt contains 40 tokens.With caching enabled, the model can store the keys and values calculated during this phase.DecodeAfter prefill, the model generates tokens one at a time.When caching is enabled, each subsequent forward pass can process the newest token while reusing the keys and values associated with earlier positions.Let’s inspect this directly.with torch.inference_mode(): prefill = model( **inputs, use_cache=True ) cache = prefill.past_key_values print("=== PREFILL ===") print("Input tokens:", inputs["input_ids"].shape[-1]) print("Cache type:", type(cache).__name__) print("Cached positions:", cache.get_seq_length()) next_token = prefill.logits[:, -1, :].argmax( dim=-1, keepdim=True ) print( "\nNext predicted token:", repr(tokenizer.decode(next_token[0])) ) decode = model( input_ids=next_token, attention_mask=torch.ones( (1, inputs["input_ids"].shape[-1] + 1), dtype=torch.long, device=next_token.device ), past_key_values=cache, use_cache=True ) print("\n=== ONE DECODE STEP ===") print( "New input tokens processed:", next_token.shape[-1] ) print( "Cached positions after decode:", decode.past_key_values.get_seq_length() )My output:=== PREFILL ===Input tokens: 40Cache type: DynamicCacheCached positions: 40Next predicted token: 'Solar'=== ONE DECODE STEP ===New input tokens processed: 1Cached positions after decode: 41This is our first direct observation of KV caching.After processing 40 input tokens, the cache contained 40 positions.We then supplied one additional token, and the cache grew to 41 positions.The model didn’t need to recompute all the previous tokens’ keys and values.An important detail: the cache stores information for tokens that have already been processed, not every token that has merely been predicted.Step 6: Disable KV caching and observe the differenceNow let’s disable caching.We’ll perform two manual forward passes.In the first pass, the model processes the original 40-token prompt.In the second pass, we’ll append the predicted token and process the entire 41-token sequence again.original_ids = inputs["input_ids"]original_mask = inputs["attention_mask"]with torch.inference_mode(): first_pass = model( input_ids=original_ids, attention_mask=original_mask, use_cache=False ) first_token = first_pass.logits[:, -1, :].argmax( dim=-1, keepdim=True ) extended_ids = torch.cat( [original_ids, first_token], dim=-1 ) extended_mask = torch.ones_like(extended_ids) second_pass = model( input_ids=extended_ids, attention_mask=extended_mask, use_cache=False )print("Original prompt tokens:", original_ids.shape[-1])print("First forward pass tokens:", original_ids.shape[-1])print("Second forward pass tokens:", extended_ids.shape[-1])print("Cache returned:", second_pass.past_key_values)My output:Original prompt tokens: 40First forward pass tokens: 40Second forward pass tokens: 41Cache returned: NoneThis demonstrates the computational difference.However, processing 41 tokens instead of one doesn’t mean the second approach will be 41 times slower.GPUs process operations in parallel, and caching introduces its own overhead.To understand the actual speed difference, we need a benchmark.Step 7: Benchmark KV Cache ON versus OFFWe’ll use the same model and input prompt, generating 64 tokens for each configuration.We’ll also include warm-up runs and repeated measurements.import timeimport statisticsimport torchMAX_NEW_TOKENS = 64WARMUP_RUNS = 2MEASURED_RUNS = 3def benchmark_cache(use_cache): timings = [] token_counts = [] for run in range(WARMUP_RUNS + MEASURED_RUNS): torch.cuda.synchronize() start = time.perf_counter() with torch.inference_mode(): output = model.generate( **inputs, max_new_tokens=MAX_NEW_TOKENS, min_new_tokens=MAX_NEW_TOKENS, do_sample=False, use_cache=use_cache, pad_token_id=tokenizer.eos_token_id ) torch.cuda.synchronize() elapsed = time.perf_counter() - start generated = ( output.shape[-1] - inputs["input_ids"].shape[-1] ) if run >= WARMUP_RUNS: timings.append(elapsed) token_counts.append(generated) return { "median_latency": statistics.median(timings), "median_tokens_per_second": statistics.median( tokens / seconds for tokens, seconds in zip( token_counts, timings ) ), "timings": timings, "generated_tokens": token_counts }cache_on = benchmark_cache(True)cache_off = benchmark_cache(False)print("KV Cache ON:", cache_on)print("KV Cache OFF:", cache_off)speedup = ( cache_off["median_latency"] / cache_on["median_latency"])print("Caching speedup:", round(speedup, 2), "x")Note that this first benchmark measures all Cache ON runs before Cache OFF runs. We improve the measurement order in the next step.My results: 40-token promptMeasured speedup: 1.15xCaching was faster, but the improvement was modest.Why?Our prompt contained only 40 tokens, and we generated another 64.The total sequence was relatively short, so recomputing the earlier token representations wasn’t as expensive as it could become with a longer context.This raises the next question:Will the advantage become larger when the prompt contains more tokens?Step 8: Repeat the experiment with a longer promptWe’ll increase the input length from 40 to 512 tokens while keeping generation fixed at 64 tokens.First, create a longer text:paragraph = ( "Machine learning systems process data using mathematical " "models. During inference, a trained model receives input " "tokens and predicts output tokens. Transformer models use " "attention mechanisms to understand relationships between " "tokens in the input sequence. ")long_text = paragraph * 30Tokenize the long prompt:long_messages = [ { "role": "user", "content": ( "Summarize the following technical explanation " "in simple terms:\n\n" + long_text ) }]long_inputs = tokenizer.apply_chat_template( long_messages, tokenize=True, add_generation_prompt=True, return_dict=True, return_tensors="pt").to("cuda")long_inputs = { "input_ids": long_inputs["input_ids"][:, :512], "attention_mask": long_inputs["attention_mask"][:, :512]}print("Input tokens:", long_inputs["input_ids"].shape[-1])Our benchmark uses the first 512 tokens for a controlled input length.This truncation can remove the closing chat-template markers, so it’s suitable here for a computational comparison rather than an evaluation of response quality.In an application, we’d truncate the document content while preserving the chat template.Now create a timing function:def timed_generation(use_cache): torch.cuda.synchronize() start = time.perf_counter() with torch.inference_mode(): output = model.generate( **long_inputs, max_new_tokens=64, min_new_tokens=64, do_sample=False, use_cache=use_cache, pad_token_id=tokenizer.eos_token_id ) torch.cuda.synchronize() elapsed = time.perf_counter() - start return ( elapsed, output.shape[-1] - long_inputs["input_ids"].shape[-1] )Warm up both configurations:for setting in [True, False]: timed_generation(setting)Then alternate measurement order:results = { True: [], False: []}for order in [ [True, False], [False, True], [True, False]]: for setting in order: elapsed, count = timed_generation(setting) assert count == 64 results[setting].append(elapsed)on_median = statistics.median(results[True])off_median = statistics.median(results[False])print("Cache ON timings:", results[True])print("Cache OFF timings:", results[False])print("Cache ON median:", round(on_median, 3), "s")print("Cache OFF median:", round(off_median, 3), "s")print("Speedup:", round(off_median / on_median, 2), "x")My results: 512-token promptThe benefit increased from 1.15× with the short prompt to 1.39× with the longer prompt.With caching disabled, the model had to repeatedly process a larger history during decoding.With caching enabled, previously calculated attention keys and values were reused.This is consistent with what KV caching is designed to do.However, the benchmark contains only three measured runs per configuration, and GPU timings can fluctuate. These figures describe my Colab environment and shouldn’t be interpreted as universal speedup estimates.Step 8A: Visualise inference latency with MatplotlibNow let’s plot both experiments.import matplotlib.pyplot as pltimport numpy as npprompt_lengths = [40, 512]cache_on_latency = [1.695, 1.656]cache_off_latency = [1.950, 2.308]x = np.arange(len(prompt_lengths))width = 0.34fig, ax = plt.subplots(figsize=(9, 5))bars_on = ax.bar( x - width / 2, cache_on_latency, width, label="KV Cache ON")bars_off = ax.bar( x + width / 2, cache_off_latency, width, label="KV Cache OFF")for bars in [bars_on, bars_off]: for bar in bars: height = bar.get_height() ax.annotate( f"{height:.3f}s", ( bar.get_x() + bar.get_width() / 2, height ), ha="center", va="bottom", xytext=(0, 4), textcoords="offset points" )ax.set_xticks(x)ax.set_xticklabels([ "40 input tokens", "512 input tokens"])ax.set_xlabel("Input prompt length")ax.set_ylabel("Median inference latency (seconds)")ax.set_title("KV Cache ON vs OFF — Qwen2.5-0.5B")ax.legend()ax.grid(axis="y", alpha=0.2)plt.tight_layout()plt.show()This chart will show that caching improved inference latency in both configurations, with a larger measured benefit for the longer prompt.Step 9: Measure GPU memory consumptionSo far, caching looks beneficial for speed.But what does it cost?KV caching stores key and value tensors for previously processed tokens, which requires memory.Let’s compare GPU memory allocation with caching enabled and disabled.We’ll measure three things:Baseline memory: Memory allocated before generation.Peak memory: Maximum PyTorch GPU memory allocation during generation.Additional peak memory: The difference between peak allocation and the starting baseline.import gcimport statisticsimport torchdef measure_gpu_memory( use_cache, prompt_inputs, max_tokens=64): gc.collect() torch.cuda.empty_cache() torch.cuda.synchronize() baseline = torch.cuda.memory_allocated() torch.cuda.reset_peak_memory_stats() with torch.inference_mode(): output = model.generate( **prompt_inputs, max_new_tokens=max_tokens, min_new_tokens=max_tokens, do_sample=False, use_cache=use_cache, pad_token_id=tokenizer.eos_token_id ) torch.cuda.synchronize() peak = torch.cuda.max_memory_allocated() result = { "baseline_mb": baseline / 1024**2, "peak_mb": peak / 1024**2, "additional_peak_mb": ( peak - baseline ) / 1024**2 } del output return resultRun three memory measurements for each configuration:memory_results = {}for setting in [False, True]: label = "Cache ON" if setting else "Cache OFF" runs = [ measure_gpu_memory(setting, long_inputs) for _ in range(3) ] memory_results[label] = runs print(f"\n{label}") for metric in [ "baseline_mb", "peak_mb", "additional_peak_mb" ]: value = statistics.median( r[metric] for r in runs ) print(metric, round(value, 2), "MB")My measured GPU memoryEnabling caching increased the measured peak allocation by approximately 2.63 MB.At the same time, median inference latency fell from 2.308 seconds to 1.656 seconds.This demonstrates an interesting performance trade-off.Is 2.63 MB the KV-cache size?No.This difference represents total peak PyTorch memory allocation between the two execution paths.Both paths use temporary tensors and intermediate computations.The measured difference is not an isolated measurement of the key and value tensors stored by the cache.To determine the exact cache tensor memory, we’d need to inspect the tensors themselves, which is outside the scope of this beginner-friendly experiment.Step 10: Visualise the memory trade-offFinally, let’s create a Matplotlib chart showing the additional peak GPU allocation for both configurations.import matplotlib.pyplot as pltimport statisticslabels = ["KV Cache OFF", "KV Cache ON"]additional_memory = [ statistics.median( r["additional_peak_mb"] for r in memory_results["Cache OFF"] ), statistics.median( r["additional_peak_mb"] for r in memory_results["Cache ON"] )]latencies = [2.308, 1.656]fig, ax = plt.subplots(figsize=(9, 5))bars = ax.bar( labels, additional_memory, width=0.5)for bar, memory, latency in zip( bars, additional_memory, latencies): ax.annotate( f"{memory:.2f} MB", ( bar.get_x() + bar.get_width() / 2, memory ), ha="center", va="bottom", xytext=(0, 6), textcoords="offset points" ) ax.text( bar.get_x() + bar.get_width() / 2, memory / 2, f"{latency:.3f}s\ninference", ha="center", va="center" )ax.set_title( "KV Cache: GPU Memory and Inference Latency\n" "512 Input Tokens | 64 Output Tokens")ax.set_ylabel("Additional Peak GPU Memory (MB)")ax.set_ylim(0, max(additional_memory) * 1.3)ax.grid(axis="y", alpha=0.2)plt.tight_layout()plt.show()This final chart makes the trade-off visible.In my test configuration, KV caching used slightly more peak GPU memory but reduced inference time.Final results: What did we learn?There are three main lessons.1. KV caching reduces repeated computation during decoding2. The benefit depends on sequence length3. Lower memory usage doesn’t always mean better performanceConclusionKV caching makes LLM inference more efficient by storing and reusing previously computed attention keys and values instead of recalculating them during decoding.In our experiment using Qwen2.5–0.5B-Instruct on a Tesla T4 GPU, KV caching delivered up to 1.39× speedup, reducing inference latency by 28% (652 ms), with just 2.63 MB of additional peak GPU memory allocation.While 652 milliseconds may seem small, such improvements can add up when processing thousands of requests, although real-world gains depend on the serving workload.The key takeaway: Inference optimization often involves trade-offs. Here, a small increase in memory usage helped reduce computation and improve response time.And with a simple Google Colab experiment, we can measure these trade-offs ourselves.Github Link : https://github.com/arijit1/hugging-face/blob/main/inference/llm_inference_kv_cache.ipynbDoes KV Caching Really Speed Up LLM Inference? was originally published in Towards AI on Medium, where people are continuing the conversation by highlighting and responding to this story.