Attention Tracker: Detecting prompt injection attacks in large language modelsAttention Tracker: Detecting Prompt Injection Attacks in LLMs
The authors propose the training-free detector Attention Tracker, which uses the focus score of important attention heads to detect prompt injection, achieving a maximum AUROC of 1.00 on 5 open-source models.
According to Definition 1 of the paper: in an LLM-Integrated Application, the attacker inserts or modifies the delimiter S and the injected instruction Ij in the data D, causing the application to execute the injected task j rather than the target task t; the detector must be able to read the attention scores of the target LLM at inference time (the paper's Limitation points out that for closed-source models this is usually accessible only to developers).
- LLMs have difficulty distinguishing instructions from data, and prompt injection can make the model ignore the original instruction and execute the attacker's task, threatening LLM-integrated applications such as email and banking; the authors believe existing detectors have high training costs and insufficient generalization.
- The authors propose the distraction effect: when injection occurs, some attention heads (important heads) shift from the original instruction to the injected instruction. Attention Tracker uses 30 random sentences generated by GPT-4 plus naive ignore attacks to select important heads, then uses the aggregated attention of the last token to the instruction (focus score) for threshold-based judgment, requiring no training and no additional inference.
- On the two datasets Open-Prompt-Injection and deepset, across 5 open-source models of 1.5B–9B, Attention Tracker achieves AUROC of 0.97–1.00; the authors state this is up to 10.0% higher than all existing methods and up to 31.3% higher on average than training-free methods.
- Limitations pointed out by the authors: the method relies on internal information such as attention scores at inference time, which for closed-source models is usually accessible only to developers. The experiments cover only 2 datasets and 5 open-source models of 1.5B–9B, the attack types are the 4 types in Open-Prompt-Injection, and no adaptive attack evaluation is reported.
- Evaluated models
- Qwen2-1.5B-InstructPhi-3-mini-4k-instructMistral-7B-Instruct-v0.3Meta-Llama-3-8B-InstructGemma-2-9b-it
- Benchmarks
- Open-Prompt-Injectiondeepset prompt injection dataset
- Metrics
- AUROC
The researchers propose Attention Tracker, a training-free prompt injection attack detection method that identifies attacks by tracking the LLM's internal attention patterns toward instructions, without requiring additional LLM inference. The paper analyzes the intrinsic mechanism of such attacks and proposes the distraction effect, in which the focus of specific attention heads (important heads) shifts from the original instruction to the injected instruction. The method generalizes effectively across multiple models, datasets and attack types, improving AUROC by up to 10.0% over existing methods, and also performs well on small-sized LLMs.
Paper analysis
What problem does this paper attempt to solve?
Detecting prompt injection in LLM-integrated applications; the authors state that existing detectors are costly to train and generalize poorly.
Core problem: how to detect whether input data has been compromised by a prompt injection attack, with a method that is training-free, easy to deploy, and generalizes across models and attacks.
- Scenario and importance: LLMs cannot distinguish instructions from data, and attackers can embed malicious instructions in user input, making the model ignore the original instruction and execute the attacker-specified task. The authors claim this poses a threat to LLM-integrated applications such as email platforms and banking services, potentially leading to sensitive information leakage or unauthorized transactions (Introduction).
- Shortcomings of existing methods: The authors believe existing detectors require substantial training compute and often produce inaccurate results; trained methods are difficult to be robust on both datasets simultaneously, and training-free methods such as LLM-based and Known-answer perform unstably and often rely on larger LLMs (Sections 2, 5.2).
- Core observation: The authors analyze the attention mechanism and propose the distraction effect—when injection occurs, the attention of specific attention heads (called important heads) to the original instruction shifts to the injected instruction; the authors claim this effect exists across attack types and dataset distributions (Section 3.3).
- Method proposed in the paper: Attention Tracker, a training-free detector that uses a small amount of LLM-generated data to find important heads offline, then aggregates the attention of these heads to the instruction (focus score) at inference time for detection, without additional LLM inference (Section 4).
- Threat model (Definition 1, as stated in the paper):
- Attacker's goal: Make the LLM-Integrated Application complete the injected task j rather than the target task t.
- Attacker's capability: Sequentially insert or modify the delimiter S and the injected instruction Ij in the data D.
- Victim system: An LLM-Integrated Application that takes instruction It and data D as input.
- Detector's assumption: Can read the attention scores of the target LLM at inference time; the paper's Limitation points out that for closed-source models this information is usually accessible only to developers.
What related research exists?
Related work is divided into four groups: injection attacks, injection defenses, backdoor defenses, and attention mechanism analysis.
Prompt injection attacks
- Early work (Perez and Ribeiro 2022; Greshake et al. 2023; Liu et al. 2023; Jiang et al. 2023b): Shows that template strings can mislead LLMs into following injected instructions rather than the original instruction.
- Toyer et al. 2024; Debenedetti et al. 2024: Evaluate handcrafted injection methods for goal hijacking and prompt leaking through prompt injection games.
- Optimization-based attacks (Shi et al. 2024; Liu et al. 2024a; Zhang et al. 2024a): Use gradients to generate universal injections; Pasquini et al. 2024 treat the design of execution triggers as a differentiable search problem; Khomsky et al. 2024 target systems with defenses, and the paper states that many existing defense and detection strategies remain ineffective.
Prompt injection defenses
- Prompt-based methods (Jain et al. 2023; Hines et al. 2024; lea 2023): Add delimiters to the data portion to distinguish instructions from data.
- Training-based methods (Piet et al. 2024; Suo 2024; Chen et al. 2024; Wallace et al. 2024; Zverev et al. 2024): Fine-tune or train LLMs to learn the hierarchical relationship between instructions and data.
- Detectors: Liu et al. 2024b use querying the LLM itself, Known-answer, and PPL detection; ProtectAI and Meta trained detectors; Abdelnabi et al. 2024 find activation differences between normal and attack queries and train a classifier. The paper criticizes that existing detectors have high training costs and are often inaccurate.
Backdoor defenses
- Backdoor attacks (Saha et al. 2020; Gao et al. 2020) and instruction backdoors (Zhang et al. 2024c; Yao et al. 2024; Zhao et al. 2024b): The paper points out that backdoor attacks require planting triggers during training or in instructions, whereas prompt injection manipulates the input at inference time and does not require access to the training process; the two have different threat models.
LLM attention mechanisms
- Studies of functional heads: induction heads (Olsson et al. 2022), successor heads (Gould et al. 2024), function vectors (Todd et al. 2024), etc., showing that different attention heads have different functions.
- Using attention to analyze or manipulate models: Zhang et al. 2024b adjust attention scores to control output format; Lookback Lens (Chuang et al. 2024) detects context hallucination; AttenTD (Lyu et al. 2022) identifies trojan attacks.
Baselines and benchmarks: The comparison baselines are Protect AI detector, Prompt-Guard (both based on DeBERTa-v3-base fine-tuning), LLM-based detection, and Known-answer detection; the benchmarks are Open-Prompt-Injection and the deepset prompt injection dataset (Section 5.1).
Authors' positioning: This paper identifies the distraction effect of important heads under prompt injection and performs detection based on this effect, which differs from the above lines of work (end of Section 2).
How does the paper address this problem?
First find offline the important heads that exhibit the distraction effect, then use their focus score for threshold-based detection.
Overall idea: exploit the distraction effect caused by prompt injection—under injection, specific attention heads' attention to the original instruction decreases and shifts to the injected instruction. Attention Tracker finds these important heads offline in a single pass; at detection time it only aggregates the attention of these heads to the instruction, obtained "for free" along with normal inference.
Problem setting and attention definition
- Following Definition 1 of Liu et al. (2024b): the attack inserts a separator S and an injected instruction Ij into data D, causing the application to execute task j instead of t; the detection goal is to determine whether data D has been compromised (Section 3.1).
- For a transformer with L layers and H heads per layer, at the first output token define Attnl,h(I) = ∑i ∈ I αil,h, i.e., the sum of the softmax attention weights of the last token over the instruction's tokens, measuring head (l,h)'s attention to the instruction (Section 3.2).
Verification of the distraction effect
- Visualized with Llama3-8B on Open-Prompt-Injection: for normal data, the last token's attention to the instruction is higher than for attack data; under attack, attention shifts to the injected instruction (Figure 2, authors' interpretation).
- Figure 3 gives the distribution of aggregated attention under various attacks, with the legend labeling each attack and its corresponding attack success rate; the authors state that the stronger the attack, the lower the total attention, i.e., the more pronounced the distraction.
Finding important heads
- For head (l,h), compute the candidate score scorecandl,h = (μSN − kσSN) − (μSA + kσSA), and take heads with a score greater than 0 as important heads; meaning: the normal-data mean shifted left by k standard deviations is still higher than the attack-data mean shifted right by k standard deviations, i.e., the two classes of scores are stably separable (Equations 1, 2).
- Default k = 4. The head-selection data are unrelated to the test data: the instruction is "Say {random word}", 30 random sentences generated with GPT-4 are used as normal data, and a naive ignore attack string is concatenated as attack data (Section 4.1, Appendix A.6).
Detection procedure (Algorithm 1)
- One-time offline: using the generated data, compute the target model's important-head set Hi according to Equations 1, 2.
- Detection: input (Itest, Utest) into the target LLM and compute the focus score, i.e., the average of Attn(I) over all heads in Hi.
- If the focus score is below threshold t, classify as injection (reject); otherwise accept.
- Because Hi is predetermined, the focus score is obtained directly during the original inference of the test query; the authors state that the detection cost is negligible relative to the original inference.
Input placement and implementation
- For models supporting system/user templates (Qwen2, Phi3, Mistral, Llama3): the instruction is placed in the system prompt and the data in the user prompt; Gemma2 does not support this, so both instruction and data are placed in the user prompt, separated by "\nText:\n" (Section 5.1).
- Experiments use PyTorch and one NVIDIA RTX 3090; running two datasets for a single model takes about 1 hour (Appendix A.4).
What experiments did the paper conduct?
AUROC 0.97–1.00 on 2 datasets and 5 open-source models, plus ablations on generalization, number of heads, etc.
Experimental setup
- Models evaluated: Qwen2-1.5B-Instruct, Phi-3-mini-4k-instruct, Mistral-7B-Instruct-v0.3, Meta-Llama-3-8B-Instruct, Gemma-2-9b-it, with parameter sizes 1.5B–9B (Section 5.1).
- Datasets: Open-Prompt-Injection (5 tasks × 50 target-injection combinations × 4 attack types, 2,000 test queries in total, Appendix A.2); deepset prompt injection dataset test set (no instruction, uniformly using "Say xxxxxx" as the instruction).
- Baselines: Protect AI detector, Prompt-Guard (DeBERTa-v3-base fine-tuned), LLM-based detection, Known-answer detection.
- Metric: AUROC, higher is better; scores are averaged over different target/injection task combinations.
- Repeats: 5 random seeds; Protect AI detector, Prompt-Guard, and Attention Tracker are deterministic methods (Table 1 note).
- Head-selection data: 30 random sentences generated by GPT-4 + naive ignore attacks (Section 4.1).
Main results
According to Table 1 (AUROC, mean±std; deterministic methods have no std):
Swipe horizontally to read the table
Model Protect AI Prompt-Guard LLM-based Known-answer Attention Tracker Qwen2-1.5B (OPI / deepset) 0.69 / 0.90 0.97 / 0.75 0.52±0.03 / 0.49±0.04 0.90±0.02 / 0.50±0.06 1.00 / 0.98 Phi3-3B (OPI / deepset) same as above same as above 0.66±0.02 / 0.90±0.04 0.89±0.01 / 0.55±0.05 1.00 / 0.97 Mistral-7B (OPI / deepset) same as above same as above 0.57±0.01 / 0.80±0.01 0.99±0.00 / 0.45±0.01 1.00 / 0.99 Llama3-8B (OPI / deepset) same as above same as above 0.75±0.01 / 0.92±0.01 0.98±0.02 / 0.70±0.01 1.00 / 0.99 Gemma2-9B (OPI / deepset) same as above same as above 0.69±0.01 / 0.89±0.01 0.27±0.01 / 0.65±0.03 0.99 / 0.99 Note: Protect AI detector and Prompt-Guard are trained detectors; in Table 1, only one score is reported per dataset (it does not vary with the target model), and "same as above" in the table means the values are the same as the row above.
- The authors claim Attention Tracker improves AUROC by up to 3.1% on Open-Prompt-Injection and up to 10.0% on deepset; over training-free methods, the average improvement is 31.3% (Open-Prompt-Injection) and 20.9% (deepset).
- The authors believe no trained method is robust on both datasets, and that LLM-based and Known-answer perform unstably; Known-answer on Gemma2 on Open-Prompt-Injection is only 0.27±0.01.
- The authors claim the method is equally effective on the 1.5B small model and does not rely on a larger LLM.
Generalization analysis (Section 5.4)
- What was tested: On Qwen2, the mean difference in Attn(I) of each head between deepset, Open-Prompt-Injection, and LLM-generated head-selection data (Figure 5).
- Results: The figure shows that the magnitude of the difference varies with the dataset, but the relative pattern of differences across heads is consistent; the authors claim the heads with the largest differences are consistent across datasets, that the distraction effect generalizes well, and that head selection requires only naive attacks.
Number and location of heads (Table 2, Figure 8)
- Effect of k (Llama3, deepset, Table 2): All (100% of heads) AUROC 0.821; k=2 (10.4%) 0.906; k=3 (2.1%) 0.985; k=4 (0.3%) 0.986, the highest; k=5 (0.1%) drops to 0.869. The authors claim that selecting too many or too few heads both harm performance.
- Location (Figure 8): The authors claim that the important heads of each model are mostly in the first few layers or the middle layers.
Other ablations and analyses
- Data length (Figure 6, Llama3): The attention score decreases as the data becomes longer, but the authors claim the rate of decrease is negligible relative to the increase in length, and that the focus score is mainly affected by the instruction content.
- Itest selection (Table 3, Qwen2-1.8B, deepset): With random instructions, AUROC is 0.893–0.967; "Say xxxxxx" 0.979, "Output hello" 0.96; the authors claim that output-oriented instructions score higher.
- Qualitative analysis (Figures 4, 7): Under a grammar correction task + ignore attack, the attention of attack data to the instruction is lower than that of normal data and shifts to the injected instruction (the authors' interpretation).
What are some points that can be further explored?
The authors point out only the limitation of relying on internal attention information; the experiments cover 2 datasets and 5 open-source models.
Limitations and future directions pointed out by the authors
- Reliance on internal information (Limitation section): The method requires access to internal information such as the LLM's attention scores at inference time; for closed-source LLMs, this is usually accessible only to the model developer, unless aggregated statistics such as the focus score are exposed to users. The paper does not mention other explicit limitations or future directions.
Scope of experimental coverage
- Models evaluated: 5 open-source models with 1.5B–9B parameters (Qwen2-1.5B, Phi3-3B, Mistral-7B, Llama3-8B, Gemma2-9B), all instruction-tuned versions (Section 5.1).
- Datasets: Open-Prompt-Injection (2,000 queries, 5 tasks × 4 attack types: naive, ignore, escape, combine, Appendix A.2) and the deepset test set; head selection uses 30 random sentences generated by GPT-4.
- Attack types: Figure 3 additionally includes a visualization of the fake complete attack (Appendix A.1); the 4 attack types evaluated in the main table all come from Open-Prompt-Injection, and the paper does not report adaptive attacks against this detector.
- Repeats and significance: Non-deterministic methods are run with 5 seeds and report standard deviation; the paper does not report statistical significance tests.
- Evaluation method: The metric is AUROC, computed directly from the detection scores, with no LLM judging or human evaluation; the paper does not report metrics on the impact on normal utility, such as false rejection rate.
Summarize the main content of the paper
Training-free detector Attention Tracker: tracks the attention of important attention heads to the instruction, with AUROC up to 1.00.
A prompt injection detection paper that also provides a mechanism explanation at the attention level.
- Problem: LLMs cannot distinguish instructions from data, and prompt injection makes the model execute the attacker's task; the authors argue that existing detectors have high training costs and poor cross-dataset generalization.
- Core finding: The authors propose the distraction effect—when injection occurs, the attention of some attention heads (important heads) to the original instruction shifts to the injected instruction, and the authors claim this effect exists across models, attack types, and datasets.
- Method: Attention Tracker uses 30 random sentences generated by GPT-4 plus naive ignore attacks, and offline selects important heads according to "the difference between the mean scores of normal and attack exceeding k standard deviations" (k=4); during detection, it computes the average attention of these heads to the instruction (focus score), and judges injection if it is below the threshold, requiring no training and no additional LLM inference.
- Main results: On Open-Prompt-Injection, the AUROC for 5 models is 0.99–1.00, and on deepset it is 0.97–0.99 (Table 1); the authors claim a maximum improvement of 10.0% over all existing methods, and a maximum average improvement of 31.3% over training-free methods; with k=4, selecting only 0.3% of heads reaches 0.986 on Llama3/deepset (Table 2).
- Conclusion and implications: The authors believe the distraction effect provides a new perspective for understanding prompt injection, and that the detector is equally effective on small models; the limitation is that it relies on internal attention information at inference time, which for closed-source models is usually available only to developers (Limitation section).
Related papers
Show 2 more papers
- Selecting The Most Informative Tokens in Natural Language AutoencodersAnalysis / interpretabilityarXiv