Key-Value Cache Poisoning is an adversarial technique that directly modifies the stored key-value pairs within a transformer's attention mechanism during autoregressive generation. Unlike prompt injection, which targets raw text input, this attack operates on the model's internal latent representations, altering the mathematical weights that determine which tokens the model 'pays attention to' when predicting the next sequence element.
Glossary
Key-Value Cache Poisoning

What is Key-Value Cache Poisoning?
Key-Value Cache Poisoning is an inference-time attack that manipulates the transformer's stored attention state, causing the model to attend to adversarial tokens over legitimate context.
By injecting a crafted perturbation into the KV cache, an attacker can hijack the model's attention pattern, forcing it to prioritize attacker-controlled context while ignoring legitimate system prompts or safety instructions. This bypasses input-level guardrails entirely, as the malicious signal is introduced post-tokenization within the model's computational graph, making it a potent threat for agents relying on long-context caching for efficiency.
Primary Attack Vectors
The manipulation of the transformer's KV cache during inference to alter the model's attention pattern, causing it to attend to adversarial tokens over legitimate context.
Attention Hijacking
The core mechanism of KV cache poisoning involves overwriting or injecting adversarial Key-Value pairs into the cache. Since the attention mechanism computes relevance by comparing query vectors against stored keys, a poisoned cache causes the model to allocate disproportionate attention weights to attacker-controlled tokens. This effectively silences legitimate system prompts or retrieved context, redirecting the model's focus to malicious instructions hidden within the cache state.
Shared Prefix Exploitation
In serving systems that use prefix caching for efficiency, multiple users or requests may share a common KV cache prefix. An attacker can poison this shared prefix with adversarial key-value states. Subsequent requests that reuse the cached prefix inherit the poisoned attention pattern, enabling a cross-request attack where one user's malicious payload influences another user's model outputs without direct interaction.
Residual Stream Injection
This advanced variant bypasses token-level manipulation by directly injecting a crafted residual stream vector into the model's forward pass. The injected vector is added to the hidden states before they are projected into keys and values, effectively steering the entire attention computation. This allows an attacker to override internal representations without needing to place visible adversarial tokens in the text input, making detection significantly harder.
Cache Eviction Manipulation
Transformers with finite cache sizes must evict older KV pairs to make room for new tokens. Attackers exploit eviction policies by flooding the context with padding tokens that displace critical safety instructions from the cache. Once the system prompt's KV pairs are evicted, the model operates without safety constraints. This is a temporal attack that weaponizes the cache's limited capacity against itself.
Multi-Turn Cache Persistence
In conversational agents that persist the KV cache across dialogue turns, an attacker can poison the cache in an early turn and have the malicious attention pattern persist indefinitely. The poisoned keys and values remain resident in memory, influencing all subsequent reasoning. This long-range contamination is particularly dangerous because the attack surface extends across the entire session lifetime, not just a single prompt.
Speculative Decoding Attacks
Systems using speculative decoding generate candidate tokens with a draft model and verify them with the target model, sharing KV caches between the two. An attacker who compromises the draft model can inject poisoned KV states that the target model inherits during verification. This creates a supply-chain attack vector where a weaker, less-secured model poisons a more capable one through shared cache infrastructure.
KV Cache Poisoning vs. Related Attacks
Distinguishing KV cache poisoning from other context manipulation and adversarial injection techniques targeting transformer-based agents during inference.
| Feature | KV Cache Poisoning | Adversarial Context Injection | Indirect Prompt Injection |
|---|---|---|---|
Attack Surface | Transformer's key-value cache during autoregressive decoding | Agent's assembled context window (system prompt, history, retrieved docs) | External data sources ingested by the agent (web pages, emails, documents) |
Injection Point | Residual stream / attention layer activations | Textual input to the language model | Third-party content before agent retrieval |
Persistence | Persists across multiple generation steps within a single forward pass sequence | Persists for the duration of the context window or session | Persists as long as the poisoned source remains in the retrieval corpus |
Requires Model Access | |||
Bypasses Content Filters | |||
Exploits Attention Mechanism | |||
Mitigation Strategy | Cache integrity verification, attention head monitoring, activation anomaly detection | Input sanitization, strict prompt formatting, delimiter hardening | Data provenance validation, source reputation scoring, sandboxed retrieval |
Detection Difficulty | High | Medium | Medium |
Frequently Asked Questions
Key-Value Cache Poisoning is an advanced adversarial attack targeting the inference-time state of transformer models. Unlike prompt injection, which manipulates input text, this attack directly corrupts the model's internal attention mechanism, causing it to attend to attacker-chosen tokens over legitimate context.
Key-Value (KV) Cache Poisoning is an adversarial technique that manipulates the stored key and value tensors within a transformer's attention mechanism during autoregressive decoding. In standard inference, the KV cache stores pre-computed representations of previous tokens to avoid redundant computation. An attacker with access to this cache—through a shared inference infrastructure vulnerability, a side-channel, or a compromised serving layer—can overwrite specific key-value pairs. This causes the model's attention heads to allocate disproportionate weight to adversarial tokens, effectively hijacking the model's contextual understanding. The attack exploits the fact that attention is a differentiable, content-addressable memory: by injecting crafted vectors, the attacker redirects the query-key dot product scores to favor malicious values, altering the model's output without modifying the visible input prompt.
Enabling Efficiency, Speed & Accuracy
Intelligent Analysis, Decision & Execution
We build AI systems for teams that need search across company data, workflow automation across tools, or AI features inside products and internal software.
Talk to Us
Search across company data
Give teams answers from docs, tickets, runbooks, and product data with sources and permissions.
Useful when people spend too long searching or get different answers from different systems.

Automate internal workflows
Use AI to route work, draft outputs, trigger actions, and keep approvals and logs in place.
Useful when repetitive work moves across multiple tools and teams.

Add AI to products and internal tools
Build assistants, guided actions, or decision support into the software your team or customers already use.
Useful when AI needs to be part of the product, not a separate tool.
Related Terms
Key-value cache poisoning is one of many adversarial techniques targeting agent memory and attention. These related attack vectors exploit different stages of the inference and retrieval pipeline.
Activation Steering Attack
A direct manipulation of the model's residual stream during the forward pass. Unlike KV cache poisoning which targets stored key-value pairs, activation steering injects a crafted vector to override internal representations and force specific output behaviors without altering the cached context.
Adversarial Context Injection
The insertion of malicious content directly into an agent's context window to manipulate reasoning or trigger unintended tool use. While KV cache poisoning corrupts the attention mechanism's stored state, context injection exploits the input pipeline before caching occurs.
Chain-of-Thought Contamination
The injection of malicious reasoning steps into an agent's scratchpad or reflection loop. This causes the model to adopt a flawed logic path. When combined with KV cache poisoning, the corrupted attention pattern can amplify the contaminated reasoning across subsequent inference steps.
Context Window Overflow
An attack that exploits token limits by flooding the context window with irrelevant data. This displaces critical system prompts and safety instructions. KV cache poisoning can achieve a similar displacement effect by altering which tokens receive attention weight, even without exceeding the token budget.
Lost-in-the-Middle Exploit
Exploits the positional attention bias of transformers by placing malicious instructions in the middle of a long context where they are least scrutinized but still processed. KV cache poisoning can weaponize this same positional bias by corrupting attention weights for mid-sequence tokens.
Token Smuggling
Uses unusual tokenization boundaries or byte-pair encoding quirks to hide malicious instructions from content filters while remaining legible to the model. This technique can be combined with KV cache poisoning to ensure smuggled tokens receive disproportionate attention during decoding.

About the author
Prasad Kumkar
CEO & MD, Inference Systems
Prasad Kumkar is the CEO & MD of Inference Systems and writes about AI systems architecture, LLM infrastructure, model serving, evaluation, and production deployment. Over 5+ years, he has worked across computer vision models, L5 autonomous vehicle systems, and LLM research, with a focus on taking complex AI ideas into real-world engineering systems.
His work and writing cover AI systems, large language models, AI agents, multimodal systems, autonomous systems, inference optimization, RAG, evaluation, and production AI engineering.
Partnered with leading AI, data, and software stack.
How We Work
Custom AI workflows for your Business
One-fit-all AI don't work for modern businesses. At Inferensys, we aim to understand your business & custom requirements; which we use to define most efficient agentic workflows, the data, and the tools for your business.
01
Review the use case
We understand the task, the users, and where AI can actually help.
Read more02
Pick the right approach
We define what needs search, automation, or product integration.
Read more03
Build the first useful version
We implement the part that proves the value first.
Read more04
Improve from there
We add the checks and visibility needed to keep it useful.
Read moreThe first call is a practical review of your use case and the right next step.
Talk to Us