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 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 in float16 through Hugging Face Transformers, 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.
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.
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()
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
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 .
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
"""
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"]
_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)")
baseline_predictions = []
start = time.time()
for n, ticket in enumerate(tickets, start=1):
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
print(f"Recomputing the full prompt every time: {duration_full:.2f} seconds")
print(f" ({1000 * duration_full / len(tickets):.1f} ms per ticket)")
Output:
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.
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()
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
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 .
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
"""
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"]
_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)")
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]
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())]
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())]
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")
predictions = []
start = time.time()
for n, ticket in enumerate(tickets, start=1):
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
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:
DynamicCacheholds the per-layer key and value tensors for the prefix. Passing it aspast_key_valuestells 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_leneven though onlysuffix_lenids are passed in.cache_positiontells the model the new tokens begin at offsetprefix_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 thantorch.inference_mode(). Tensors created inside inference mode carry a flag that makes them awkward to slice and reassign afterwards, which is exactly whatcrop()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) (@mattmayo13) holds a master's degree in computer science and a graduate diploma in data mining. As managing editor of KDnuggets & Statology, and contributing editor at Machine Learning Mastery, 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.