Reusing the Prompt Prefix with a Key-Value Cache for SLM Optimization A second article in a KDnuggets series on small language model (SLM) optimization details reusing the prompt prefix with a key-value cache to cut per-item pre-fill costs, benchmarked on Qwen2.5-0.5B-Instruct in float16 via Hugging Face Transformers on an M2 MacBook Air with 24GB RAM and a 16-core Neural Engine. The technique exploits the fact that key and value vectors for a fixed prefix depend only on tokens to the left and are identical on every call, so computing them once shrinks pre-fill to only the changed tokens; the baseline re-encodes a few-shot support-ticket prompt in full for each of 600 records across the labels billing, technical, and account. Reusing the Prompt Prefix with a Key-Value Cache for SLM Optimization In this second article in our short series on SLM optimization techniques we focus on the reuse of the prompt prefix with a key-value cache. In a previous article https://www.kdnuggets.com/constraining-output-space-small-language-model-narrow-automation-optimization we discussed constraining output space for small language model SLM narrow automation optimization. We mentioned at the time that this was the first in a short series of SLM optimization strategy articles. We are now at the second of those. This time we will focus on the reuse of the prompt prefix with a key-value cache. Let's not waste any further time on the niceties and get right to it instead. As in our previous article, all benchmarks below use Qwen2.5-0.5B-Instruct https://huggingface.co/Qwen/Qwen2.5-0.5B-Instruct in float16 through Hugging Face Transformers https://huggingface.co/docs/transformers/index , running on an M2 Macbook Air with 24GB RAM and a 16-core Neural Engine. First, make sure you set up a Python environment and install your requirements: pip install torch transformers accelerate We will continue to use the support ticket framing from our first article https://www.kdnuggets.com/constraining-output-space-small-language-model-narrow-automation-optimization . Why Reuse the Prompt Prefix with a Key-Value Cache Narrow automation prompts are relatively static. A task instruction, a taxonomy definition, and a few examples make up the bulk of the tokens, and only a short prompt tail changes from item to item. If your instruction block runs to a couple of hundred tokens and each ticket adds twenty or thirty, then the overwhelming majority of every prompt is byte-for-byte identical to the last one. It's clearly wasteful to be recomputing all of it, for every layer, on every call. Transformers compute a key and a value vector for each token at each layer, and these depend only on the tokens to the left. This means that for a fixed prefix, they are identical on every call. Computing them once and holding onto them shrinks the per-item pre-fill down to just the tokens that actually changed. Re-encoding Every Ticket First, the baseline: a realistic few-shot prompt, re-encoded in full for every ticket. The constrained scoring trick from our earlier article is carried forward here, so the decision is a single forward pass and the only thing left to optimize is the pre-fill. Note that the chat template is written out by hand rather than going through apply chat template , because the next script needs to split the prompt at a known boundary. python import os import time import torch from transformers import AutoTokenizer, AutoModelForCausalLM MODEL ID = "Qwen/Qwen2.5-0.5B-Instruct" torch.set num threads os.cpu count or 1 tokenizer = AutoTokenizer.from pretrained MODEL ID model = AutoModelForCausalLM.from pretrained MODEL ID, dtype=torch.float32 model.eval our toy data to classify 600 records LABELS = "billing", "technical", "account" tickets = "My card was charged twice for the same invoice.", "The mobile app crashes whenever I open the settings page.", "I need to change the email address on my profile.", 200 constrained scoring, carried over from the previous article: the prompt ends at the start of the assistant turn, so comparing the logits of each label's FIRST token is enough to pick a winner, provided those first tokens are distinct label first ids = tokenizer.encode label, add special tokens=False 0 for label in LABELS assert len set label first ids == len LABELS , "Labels share a first token; score full label sequences instead." label first ids = torch.tensor label first ids, device=model.device SYSTEM PROMPT = """You classify customer support tickets into exactly one category. Categories: - billing: payments, invoices, refunds, charges, subscription costs - technical: crashes, errors, performance problems, broken features - account: profile changes, login access, permissions, account deletion Examples: Ticket: I was billed twice in March. Category: billing Ticket: The dashboard never finishes loading. Category: technical Ticket: Please remove my old phone number from my profile. Category: account Ticket: My promo code was rejected at checkout. Category: billing Ticket: Exporting to CSV throws a 500 error. Category: technical Ticket: I cannot reset my password. Category: account """ the chat template is written out by hand so the prompt can be split at a known token boundary; this is the exact ChatML layout Qwen2.5-Instruct expects prefix text = f"<|im start| system\n{SYSTEM PROMPT}<|im end| \n" def suffix text ticket : return f"<|im start| user\nTicket: {ticket}\nCategory:<|im end| \n" f"<|im start| assistant\n" def encode text : return tokenizer text, add special tokens=False "input ids" the split has to be token-clean: encoding the two halves separately must give exactly the same ids as encoding the whole prompt in one go, or the cached keys in the next script will not line up with what the model would otherwise have seen probe = suffix text tickets 0 assert encode prefix text + encode probe == encode prefix text + probe , "Prefix/suffix split is not token-clean; move the boundary." prefix len = len encode prefix text full len = prefix len + len encode probe print f"Static prefix length: {prefix len} tokens" print f"Full prompt length: {full len} tokens {100 prefix len / full len:.0f}% of it static " time inference baseline predictions = start = time.time for n, ticket in enumerate tickets, start=1 : this loop runs for minutes on CPU, so report progress rather than sitting silent if n % 100 == 0: print f" {n}/{len tickets } tickets { time.time - start / n:.2f}s each ", flush=True full = tokenizer prefix text + suffix text ticket , add special tokens=False, return tensors="pt" .to model.device with torch.no grad : logits = model full .logits 0, -1, : baseline predictions.append LABELS int logits label first ids .argmax duration full = time.time - start output task metrics print f"Recomputing the full prompt every time: {duration full:.2f} seconds" print f" {1000 duration full / len tickets :.1f} ms per ticket " Output: Loading weights: 100%|████████████████████████████████████████████████████████████████████| 290/290 00:01<00:00, 156.40it/s Static prefix length: 145 tokens Full prompt length: 167 tokens 87% of it static 100/600 tickets 0.31s each 200/600 tickets 0.30s each 300/600 tickets 0.30s each 400/600 tickets 0.31s each 500/600 tickets 0.31s each 600/600 tickets 0.31s each Recomputing the full prompt every time: 184.85 seconds 308.1 ms per ticket Reusing the Prompt Prefix We now run the prefix through the model exactly once, keep the resulting cache, and feed each item only its own tokens. This continues in the same script, so the model, the tokenizer, the prompt halves, and the baseline timing are all still in scope. python import os import time import torch from transformers import AutoTokenizer, AutoModelForCausalLM, DynamicCache MODEL ID = "Qwen/Qwen2.5-0.5B-Instruct" torch.set num threads os.cpu count or 1 tokenizer = AutoTokenizer.from pretrained MODEL ID model = AutoModelForCausalLM.from pretrained MODEL ID, dtype=torch.float32 model.eval our toy data to classify 600 records LABELS = "billing", "technical", "account" tickets = "My card was charged twice for the same invoice.", "The mobile app crashes whenever I open the settings page.", "I need to change the email address on my profile.", 200 constrained scoring, carried over from the previous article: the prompt ends at the start of the assistant turn, so comparing the logits of each label's FIRST token is enough to pick a winner, provided those first tokens are distinct label first ids = tokenizer.encode label, add special tokens=False 0 for label in LABELS assert len set label first ids == len LABELS , "Labels share a first token; score full label sequences instead." label first ids = torch.tensor label first ids, device=model.device SYSTEM PROMPT = """You classify customer support tickets into exactly one category. Categories: - billing: payments, invoices, refunds, charges, subscription costs - technical: crashes, errors, performance problems, broken features - account: profile changes, login access, permissions, account deletion Examples: Ticket: I was billed twice in March. Category: billing Ticket: The dashboard never finishes loading. Category: technical Ticket: Please remove my old phone number from my profile. Category: account Ticket: My promo code was rejected at checkout. Category: billing Ticket: Exporting to CSV throws a 500 error. Category: technical Ticket: I cannot reset my password. Category: account """ the chat template is written out by hand so the prompt can be split at a known token boundary; this is the exact ChatML layout Qwen2.5-Instruct expects prefix text = f"<|im start| system\n{SYSTEM PROMPT}<|im end| \n" def suffix text ticket : return f"<|im start| user\nTicket: {ticket}\nCategory:<|im end| \n" f"<|im start| assistant\n" def encode text : return tokenizer text, add special tokens=False "input ids" the split has to be token-clean: encoding the two halves separately must give exactly the same ids as encoding the whole prompt in one go, or the cached keys will not line up with what the model would otherwise have seen probe = suffix text tickets 0 assert encode prefix text + encode probe == encode prefix text + probe , "Prefix/suffix split is not token-clean; move the boundary." prefix = tokenizer prefix text, add special tokens=False, return tensors="pt" .to model.device prefix ids = prefix "input ids" prefix len = prefix ids.shape 1 full len = prefix len + len encode probe print f"Static prefix length: {prefix len} tokens" print f"Full prompt length: {full len} tokens {100 prefix len / full len:.0f}% of it static " Populate the cache once with the static instruction block prefix cache = DynamicCache with torch.no grad : model input ids=prefix ids, attention mask=torch.ones like prefix ids , past key values=prefix cache, use cache=True, def classify cached ticket : suffix = tokenizer suffix text ticket , add special tokens=False, return tensors="pt" .to model.device suffix ids = suffix "input ids" suffix len = suffix ids.shape 1 the mask must cover the cached prefix as well as the new tokens, and the new tokens must be told they start at position prefix len, not at position 0 attention mask = torch.ones 1, prefix len + suffix len , device=model.device, dtype=torch.long cache position = torch.arange prefix len, prefix len + suffix len, device=model.device with torch.no grad : out = model input ids=suffix ids, attention mask=attention mask, past key values=prefix cache, cache position=cache position, use cache=True, logits = out.logits 0, -1, : label = LABELS int logits label first ids .argmax roll the cache back so the next ticket starts from the prefix alone prefix cache.crop prefix len return label def classify full ticket : """Reference path: re-encode the whole prompt, no cache. Used only to verify.""" full = tokenizer prefix text + suffix text ticket , add special tokens=False, return tensors="pt" .to model.device with torch.no grad : logits = model full .logits 0, -1, : return LABELS int logits label first ids .argmax correctness first: the cached path must agree with the uncached one on every distinct ticket, otherwise the speedup below is measuring the wrong computation mismatches = t for t in dict.fromkeys tickets if classify cached t = classify full t assert not mismatches, f"Cached path disagrees with full re-encoding on: {mismatches}" print f"Cache verified against full re-encoding on {len set tickets } distinct tickets" time inference predictions = start = time.time for n, ticket in enumerate tickets, start=1 : this loop is fast, but report progress anyway so the two scripts look alike if n % 100 == 0: print f" {n}/{len tickets } tickets { time.time - start / n:.2f}s each ", flush=True predictions.append classify cached ticket duration cached = time.time - start output task metrics print f"Reusing the cached prefix: {duration cached:.2f} seconds" print f" {1000 duration cached / len tickets :.1f} ms per ticket " Output: Static prefix length: 145 tokens Full prompt length: 167 tokens 87% of it static Cache verified against full re-encoding on 3 distinct tickets 100/600 tickets 0.13s each 200/600 tickets 0.13s each 300/600 tickets 0.13s each 400/600 tickets 0.13s each 500/600 tickets 0.13s each 600/600 tickets 0.13s each Reusing the cached prefix: 80.07 seconds 133.5 ms per ticket Our baseline script version ran for 184.85 seconds total, with an average of ~0.3s for each ticket. The cached prompt prefix version of the script is 80.07 seconds total, with an average of 0.13s per ticket. This is an overall runtime reduction of ~57%. The gain scales with the ratio between your static and dynamic content, which is why this technique rewards long, detailed instruction blocks rather than punishing them. And just to note: the predictions should be identical on every ticket, which is the result you want: this is a pure compute optimization, not a change to the model's behavior. Some further explanation of the code above: - DynamicCache holds the per-layer key and value tensors for the prefix. Passing it as past key values tells the model those positions are already computed, so the forward pass only processes the new tokens while still attending backward across the full context. - Two arguments have to agree with the cache or the results will be deceivingly wrong. The attention mask covers the cached prefix and the new tokens, so its width is prefix len + suffix len even though only suffix len ids are passed in. cache position tells the model the new tokens begin at offset prefix len , so the rotary embeddings match what the full prompt would have produced. Recent versions of Transformers infer the positions from the cache length, but passing them explicitly documents the intent and guards against version drift. - The call to prefix cache.crop prefix len is not optional. The forward pass appends the suffix keys and values to the cache, so without the crop the second ticket would attend to the first ticket's tokens and the cache would grow without bound. - Split the prompt at a clean boundary — the end of a line, or a chat template delimiter. Tokenizing two halves separately can produce a different token sequence than tokenizing the concatenation if the split comes mid-word, and then the cached keys no longer correspond to what the model would have seen. The assertion in the first script checks this directly. - Keep the whole pipeline under torch.no grad rather than torch.inference mode . Tensors created inside inference mode carry a flag that makes them awkward to slice and reassign afterwards, which is exactly what crop does to the cache. Wrapping Up This was the second entry in our attempts at optimizing SLMs for narrow automation, and our target technique this time was prefix caching . This technique replaces the full and complete re-encoding of a static instruction block with a single pre-fill whose key and value tensors are computed once and reused, leaving us to only account for the tokens that differ. By implementing it, we get the same predictions the naive loop produced at a far lower compute cost. The longer and more detailed our instructions grow, the better the trade becomes. A small language model, such as our use of a 0.5B parameter model today, becomes a practical production choice for narrow automation once the code around it stops treating every call as an isolated event. The prompt is mostly the same every time. Once your loop knows that, the small model stops being a compromise and starts being the obvious answer. \ Matthew Mayo\ https://www.kdnuggets.com/wp-content/uploads/./profile-pic.jpg https://www.linkedin.com/in/mattmayo13/ @mattmayo13 https://twitter.com/mattmayo13 holds a master's degree in computer science and a graduate diploma in data mining. As managing editor of KDnuggets https://www.kdnuggets.com/ & Statology https://www.statology.org/ , and contributing editor at Machine Learning Mastery https://machinelearningmastery.com/ , Matthew aims to make complex data science concepts accessible. His professional interests include natural language processing, language models, machine learning algorithms, and exploring emerging AI. He is driven by a mission to democratize knowledge in the data science community. Matthew has been coding since he was 6 years old.