I tried to fix a prompt-injection detector by editing its weights by hand, without training or fine-tuning
In this article I am gonna share how I tried to improve an open source prompt injection detection model by changing its weights directly by hand. I did not train the model and I did not fine-tune it. I will share what worked, what did not work, and the mistakes I made on the way.
I am sharing this article for educational purposes only and these are my personal opinions.
What is the problem?
A prompt injection detection model checks if a user message is an attack on an AI application. It gives one of two answers: SAFE or INJECTION.
Most of these models have one common problem. If a normal message has words like "ignore" or "bypass", the model thinks it is an attack. For example, "please ignore the typo above" gets marked as an attack. I call this a false alarm.
So I wanted two things from this work:
- Fewer false alarms on normal messages
- More real attacks caught
Where the idea came from
I got this idea from a blog post called Weight-Space Programming by Rikiya Takehi.
Normally we improve a model by training it on more data. This blog says something different. A model is just a big list of numbers, and these numbers are called weights. We can look inside the model, understand what is going wrong, and change the numbers ourselves.
I wanted to check if this works on a real security model.
The model I used
I used protectai/deberta-v3-base-prompt-injection-v2 from Hugging Face. It has 184 million weights.
I followed one rule in this work. I can run the model on examples to understand it, but every number I change must come from simple math like averages. No training steps at all.
Baseline model scores
First I tested the original model on five public datasets. I kept half of each dataset aside for testing.
| Dataset | Messages | Attacks caught (%) | False alarms (%) |
|---|---|---|---|
| safe-guard-prompt-injection | 5,065 | 84.3 | 0.1 |
| deepset/prompt-injections | 330 | 41.2 | 1.5 |
| jailbreak-classification | 385 | 88.1 | 0.3 |
| Gandalf ignore-instructions | 500 | 100.0 | n/a |
| NotInject (normal messages with scary words) | 169 | n/a | 46.2 |
| All together | 6,449 | 85.4 | 2.0 |
n/a means there is nothing to measure. Gandalf has only attacks and NotInject has only normal messages.
In the above table, look at NotInject. It has only normal messages which contain words like "ignore" or "bypass". The model marks 46% of them as attacks. That is almost half.
The model also misses more than half of the attacks in the deepset dataset.
Finding the problem inside the model
The model reads a message in 12 steps. These steps are called layers. The final answer is made from the output of step 12.
After each step I checked one simple thing. Can the model tell the difference between a real attack and a normal message with scary words? I gave a score out of 100, where 100 means it can always tell and 50 means it is just guessing.
| Step (layer) | Score out of 100 |
|---|---|
| 5 | 90 |
| 7 | 98.5 |
| 8 | 98.9 |
| 11 | 97 |
| 12 (the final answer is made from this) | 91 |
This was the most interesting finding for me. The model already knows the difference in the middle steps. But it loses that knowledge at the last step, just before giving the answer.
Then I checked more closely and found the exact place. It is the last part of the last layer. If I read the model just before this part, false alarms on scary word messages come down to around 15%. If I read just after it, they are around 30%.
So the model is throwing away useful information at the very end.
How I changed the weights
The final answer depends only on one position in the last layer. So I can change the last layer and nothing else in the model gets disturbed. I did four things:
- I picked one slot in the last layer and emptied it, so I can use it to carry a new signal.
- I changed four small units in the last layer. Two of them turn on when the model is missing a real attack. The other two turn on when the model is raising a false alarm on a normal message.
- I connected that slot to the final answer, so these four units can push the answer towards INJECTION or towards SAFE.
- I made the model slightly less eager to say INJECTION, to bring the false alarms down.
In total I changed 15,363 numbers out of 184 million. That is about 0.008% of the model.
Note: I calculated every number using averages and simple statistics from example messages. I added the units one by one, and each new unit was made to fix the mistakes which were still left.
Results
I made six versions. Each new version was made because the previous one had a problem.
Version 1 and 2: looked great, but failed on new data
I built the first version using five datasets and tested it on the half I kept aside.
| Test half of the five datasets | Original model | Version 2 |
|---|---|---|
| Attacks caught, out of 2,233 | 1,907 | 2,108 |
| False alarms, out of 4,216 | 85 | 42 |
False alarms became half and the model caught 200 more attacks. I was very happy with this result.
Then I tested it on messages written by real people from other places. These were jailbreak prompts collected from Reddit and Discord, attack emails from the Microsoft LLMail-Inject challenge, and normal questions from OpenAssistant and Dolly.
| 8,790 messages written by real people | Attacks caught (%) | False alarms (%) |
|---|---|---|
| Original model | 31.0 | 4.0 |
| Version 2 | 40.3 | 6.6 |
| Original model with a lower cut-off score | 46.1 | 6.6 |
In the above table, version 2 catches more attacks but it also raises more false alarms. It started marking normal questions like "What's the best book on gravitation?" as attacks.
The third row is the important one. Every detection model has a cut-off score. If I simply lower the cut-off of the original model, it catches more attacks than my version 2 with the same number of false alarms. So my change was worse than changing one setting.
The reason is simple. My units learned how attacks look in my five datasets, and not how attacks look in general.
Version 3: only reducing false alarms
In this version I kept only the two units which push the answer towards SAFE. A change like this cannot create new false alarms.
On the five datasets, false alarms came down from 85 to 25. On NotInject they came down from 46.2% to 13.0%. The cost was only 6 missed attacks out of 1,907.
But on the messages written by real people there was almost no change. It had 13 fewer false alarms and caught 60 fewer attacks.
So version 3 is useful only if false alarms on scary words are your main problem.
Version 4 and 5: using more types of data
This time I used 13 different data sources to build the change. I added the Reddit jailbreaks, the attack emails, normal emails and real user messages.
I also kept 7 data sources completely aside. The model change never saw them. I did this because I stopped trusting results on data I had already looked at many times.
| Original model | Version 5 | |
|---|---|---|
| New examples from the 13 sources I used (14,755 messages) | ||
| Attacks caught, out of 3,626 | 2,333 (64.3%) | 3,198 (88.2%) |
| False alarms, out of 11,129 | 253 (2.3%) | 202 (1.8%) |
| The 7 sources it never saw (9,119 messages) | ||
| Attacks caught, out of 4,120 | 2,731 (66.3%) | 2,763 (67.1%) |
| False alarms, out of 4,999 | 90 (1.8%) | 78 (1.6%) |
This is the result I am confident about. Version 5 catches more attacks and raises fewer false alarms on both sets.
But look at the size of the improvement on the 7 sources it never saw. It is only 32 more attacks and 12 fewer false alarms out of 9,119 messages. The improvement is real but it is small.
| Source it never saw | Messages | Original model | Version 5 |
|---|---|---|---|
| LLMail-Inject phase 2, attacks caught | 2,000 | 715 | 749 |
| Attacks in many languages, caught | 974 | 956 | 956 |
| Tensor Trust game attacks, caught | 922 | 902 | 900 |
| ToxicChat jailbreaks, caught | 182 | 122 | 123 |
| A list of known jailbreaks, caught | 42 | 36 | 35 |
| ToxicChat normal user messages, false alarms | 3,000 | 86 | 74 |
| UltraChat normal messages, false alarms | 1,999 | 4 | 4 |
On the 13 sources I used, most of the improvement came from attack emails. The model went from catching 15.8% of them to 92.9%. Not everything improved. The Reddit jailbreaks went down a little, from 68.4% to 65.8%.
Is there a better signal somewhere else in the model?
After version 5 I thought this method had reached its limit. But all my changes were reading only one place in the model. So I checked the other places also.
I did a stricter test this time. I split the 13 sources into four groups. I used three groups to find a signal and tested it on the fourth group, which it had never seen. Then I counted how many of the 3,629 attacks get caught without raising more false alarms than the original model.
| What I read from the model | Attacks caught | Can I build it into the weights? |
|---|---|---|
| Nothing extra (original model) | 2,337 | |
| Any single layer | 2,323 at best | |
| The strongest word for each of many features, layer 10 | 2,512 to 2,635 | No, it needs too many parts |
| The strongest word for one feature, layer 10 | 2,419 to 2,434 | Yes |
| The strongest word for one feature, layer 11 | 2,333 at best | Yes, but no improvement |
| The average over all words | 2,307 at best | Yes, but no improvement |
So I was partly wrong about the limit. There is a better signal at layer 10. In simple words, the signal is: "does any one word in the message look very strongly like an attack?"
The problem is that this signal is spread across hundreds of features. The full version cannot be built into the model easily. The version I can build gives only about one third of the improvement.
Version 6: building it anyway
I built the simple version to see what happens. I changed one part of layer 11 so that it finds the word which looks most like an attack, and passes that value to the last layer.
The part works correctly. The value which reaches the last layer matches what I wanted, and adding it changed only 10 answers out of 38,648.
But it did not help detection. It caught only about 28 more attacks, and it made no improvement on top of version 5. It also changes 234,357 numbers instead of 15,363.
So version 5 is still the best one.
Does this beat normal training?
This is the question I had left open. Normal training means backpropagation: show the model examples and let it adjust its own weights step by step. So I ran it on the same data and compared it with version 5.
I trained three models. All three saw only the same examples from the 13 sources which I used to build version 5. I ran each one three times with a different random seed.
- Same weights: training is allowed to change only the same numbers which version 5 changed, and nothing else.
- Last layer: training is allowed to change the whole last part of the model where my change lives. That is 5.3 million numbers.
- Full fine-tuning: training is allowed to change all 184 million numbers. I used one standard setting and did not tune it.
To keep the comparison fair, I set the cut-off score of every model so that it raises the same number of false alarms as version 5. Then I counted the attacks caught.
| Model | Numbers changed | New examples from the 13 sources, attacks caught out of 3,626 (at 202 false alarms) | The 7 sources never seen, attacks caught out of 4,120 (at 78 false alarms) |
|---|---|---|---|
| Original model | 0 | 2,227 | 2,645 |
| Version 5 (by hand) | 15,363 | 3,198 | 2,763 |
| Training, same weights | 15,365 | 3,276 to 3,301 | 2,735 to 2,825 |
| Training, last layer | 5.3 million | 3,329 to 3,339 | 2,554 to 2,731 |
| Full fine-tuning | 184 million | 3,472 to 3,490 | 3,177 to 3,295 |
"3,276 to 3,301" is the lowest and highest result of the three runs. The same weights row has 15,365 numbers because version 5 also moved the two final bias numbers.
So the answer is no. My hand change does not beat normal training.
Full fine-tuning is better on both sets. On the 7 sources it never saw, it catches around 410 to 530 more attacks than version 5 with the same 78 false alarms. With the normal cut-off it also raises fewer false alarms on the first set, 112 to 127 against 202 for version 5.
The same weights row is the closest comparison, because it has the same budget as my change. On new examples from the 13 sources, training won in all three runs. On the 7 sources never seen it is a tie. Two runs were better than version 5 and one run was worse.
There is one place where the hand change did better. Training only the last layer was worse than version 5 on the 7 sources never seen, in all three runs. It learned my 13 sources well but it carried less of that to new sources.
Two more things I noticed about full fine-tuning. Most of its improvement on the 7 sources came from LLMail-Inject phase 2, where it went from 715 attacks caught to between 1,155 and 1,302. Those emails are close to the phase 1 emails it trained on. And in all three runs it lost some attacks in other languages, going from 956 caught to around 915.
Version 7: trying to beat training with editing
After that comparison I did not want to stop. I wanted to know if editing can get closer to training when I do it in a better way. I changed two things.
- I allowed least squares. Until now every number came from averages and simple statistics. Least squares is still one formula with no training loop and no gradient steps, but it is a stronger tool.
- I read the average over all words. All my earlier versions read only one position in the model, the first one. This time I also checked the average of all word positions going into the last layer.
First I tested this outside the model. I fitted a least squares readout on the same examples from the 13 sources and counted the attacks caught at the same number of false alarms as version 5.
| What the readout reads | New examples from the 13 sources, out of 3,626 | The 7 sources never seen, out of 4,120 |
|---|---|---|
| The one position my earlier versions read | 3,342 | 2,862 |
| The average over all words | 3,420 | 3,193 |
This was a surprise for me. The signal was much stronger in the word average than in the single position I had been reading from the start.
How I built it into the weights
- I took one attention head in the last layer and removed its query. A head with no query looks at every word equally, so it computes an average over all words.
- I set this head to write one number into an empty slot. The number is the least squares direction applied to the word average.
- I made the rest of the last layer blind to that slot, so the number reaches the end untouched.
- I used two small units just before the final answer to read the slot exactly and add it to the model's score. The strength of this connection comes from a least squares with only two variables.
This changes 162,118 numbers out of 184 million, which is about 0.09% of the model. I checked the result with the real model after saving it. The real model and my calculation agreed on every one of the 38,648 messages.
A problem on the way
The first build worked on the 13 sources but lost most of the improvement on the 7 sources never seen. The number arriving at the end was not the number I had written.
I think the reason is that the model rescales its whole state two times between the head and the final answer, and the amount is different for every message. Making my signal stronger helped. The real fix was a small trick. Rescaling can change the size of a number but it cannot change its sign. So I shifted the signal so that zero sits exactly at the decision point. After that, rescaling could not push a message across the line.
| Build | New examples from the 13 sources, out of 3,626 | The 7 sources never seen, out of 4,120 |
|---|---|---|
| First build | 3,402 | 2,837 |
| Signal 10 times stronger | 3,423 | 3,122 |
| Zero placed at the decision point | 3,420 | 3,179 |
| The readout outside the model | 3,420 | 3,193 |
Version 7 against training
This is the same comparison as before, with version 7 added. Every model is set to the same number of false alarms as version 5.
| Model | Numbers changed | New examples from the 13 sources, attacks caught out of 3,626 (at 202 false alarms) | The 7 sources never seen, attacks caught out of 4,120 (at 78 false alarms) |
|---|---|---|---|
| Original model | 0 | 2,227 | 2,645 |
| Version 5 (by hand) | 15,363 | 3,198 | 2,763 |
| Training, same weights as version 5 | 15,365 | 3,276 to 3,301 | 2,735 to 2,825 |
| Training, last layer | 5.3 million | 3,329 to 3,339 | 2,554 to 2,731 |
| Version 7 (least squares, no training) | 162,118 | 3,420 | 3,179 |
| Full fine-tuning | 184 million | 3,472 to 3,490 | 3,177 to 3,295 |
So did editing beat training? Partly.
- Version 7 beats training on the same weights and training on the last layer. It is ahead of every run of both, on both sets.
- On the 7 sources never seen, version 7 is level with the weakest full fine-tuning run (3,179 against 3,177) and behind the other two (3,290 and 3,295).
- On new examples from the 13 sources, full fine-tuning is still ahead by 52 to 70 attacks.
With the normal cut-off, full fine-tuning is also cleaner. On the 7 sources never seen, version 7 catches 3,246 attacks with 93 false alarms. Full fine-tuning catches 3,145 to 3,303 with 68 to 79 false alarms.
Version 7 also helped with the problem I started with. On the NotInject messages, which are normal messages with scary words, false alarms went from 73 to 23 out of 162 with the normal cut-off. That is from 45% to 14%.
Note: I should be honest about what version 7 is. The least squares gives almost all the weight to the new word average signal and very little to the model's own answer. So version 7 is mostly a new simple classifier which reads the model's internal state, written into the weights without training. It is not a small repair of the old answer like version 5 was.
Can editing go further?
I tested richer readouts outside the model. They also read the inner units of layers 9 and 10 for every word. The best ones reach the bottom of the full fine-tuning range on both sets, around 3,471 and 3,184. None of them was clearly better than full fine-tuning on both. I built one of them into the weights. That is version 8.
Version 8: one more signal
Version 7 reads only the word average going into the last layer. Version 8 adds a second signal from one layer earlier.
- In the layer before the last, every word has 3,072 inner units. I made that layer write one extra number for every word into an empty slot. The number is a score calculated from those inner units.
- The averaging head from version 7 now reads both things together: the word average and the average of this new score. It writes its answer into a second empty slot.
- The rest is the same as version 7. The last layer is blind to both slots, two small units read the answer exactly, and zero sits at the decision point.
I also changed how the weights are calculated. Plain least squares cares about every message equally, even the easy ones. For version 8 I used a margin rule, which cares only about the messages near the decision line. I calculated it with about 12 rounds of weighted least squares. There are still no gradient steps on the model, but this is one more step away from the "averages only" rule.
Version 8 changes 178,253 numbers. The real model and my calculation again agreed on every one of the 38,648 messages.
| Model | Numbers changed | New examples from the 13 sources, attacks caught out of 3,626 (at 202 false alarms) | The 7 sources never seen, attacks caught out of 4,120 (at 78 false alarms) |
|---|---|---|---|
| Training, same weights as version 5 | 15,365 | 3,276 to 3,301 | 2,735 to 2,825 |
| Training, last layer | 5.3 million | 3,329 to 3,339 | 2,554 to 2,731 |
| Version 7 | 162,118 | 3,420 | 3,179 |
| Version 8 | 178,253 | 3,429 | 3,231 |
| Full fine-tuning | 184 million | 3,472 to 3,490 | 3,177 to 3,295 |
Version 8 is a small step forward, and it still does not beat full fine-tuning.
- On the 7 sources never seen, version 8 catches 52 more attacks than version 7. It is now ahead of the weakest full fine-tuning run (3,231 against 3,177) and behind the other two (3,290 and 3,295).
- On new examples from the 13 sources, it gains only 9 attacks. Full fine-tuning is still ahead by 43 to 61.
- The same readout outside the model gave 3,460 and 3,197. So the built version lost a little on the 13 sources and gained a little on the unseen ones. I think this is the effect of the rescaling inside the model, and I would not read much into it.
With the normal cut-off, version 8 raises more false alarms than version 7. On new examples from the 13 sources it catches 3,420 attacks with 195 false alarms, where version 7 catches 3,397 with 163. On the 7 sources never seen it catches 3,319 with 96 false alarms. On NotInject it has 29 false alarms out of 162, where version 7 has 23. So with the normal cut-off, full fine-tuning is still the cleaner model.
Observations and Analysis
Looking inside the model before changing it was very useful. I found that the last part of the last layer throws away something the model already knows, and that told me exactly where to make the change.
Changing a few thousand numbers by hand can give a big improvement on the type of data you used to build the change. It gives only a small improvement on new types of data.
Normal fine-tuning on the same data beats the hand change of version 5. Even when training is allowed to touch only the same 15,363 numbers, it does as well or better.
Version 7 changed this picture a little. With least squares and a better place to read from, editing beat the two limited kinds of training and came close to full fine-tuning. Version 8 added a second signal and moved a little closer. Neither of them beat full fine-tuning. The biggest improvement did not come from a better formula. It came from looking inside the model again and finding that the word average carries a much stronger signal than the single position I was reading.
Note: Always compare your changed model with the original model at the same number of false alarms. Two times I had a better looking score but actually a worse model.
Note: Always keep some data sources completely aside, and read the actual messages in your datasets. I removed one dataset because the original model marked 82% of its normal messages as attacks. When I read the messages, I could not tell its normal messages and attack messages apart myself. The labels were the problem and not the model.
Things to keep in mind
- The improvement on the 7 unseen sources is small. I tried five settings in the last step and only one of them improved both numbers. I picked it after looking at those results.
- In the stricter test, where one full group of sources is hidden, the four units did not beat the original model on both numbers. The change works much better on new examples from known sources than on totally new sources.
- I looked at the first test sets many times while building versions 1 to 3. So those numbers are not a clean test anymore.
- Some datasets have wrong labels. For example, deepset marks simple role play requests as attacks.
- The model reads only the first 512 pieces of a message. If an attack is hidden late in a long email, no version can see it.
- While building version 7 I tried many variants and checked all of them on the same two test sets. So the version 7 numbers are a little optimistic. The full fine-tuning numbers did not get this advantage.
- Version 7 uses least squares, which is a step beyond the "averages only" rule I started with. It also changes about ten times more numbers than version 5.
- The model on Hugging Face is still version 5. I have not uploaded version 7 or version 8.
- Version 8 is one build. I ran it once and I did not try other settings for it.
- In the comparison with normal training, I did not tune the full fine-tuning settings and I ran only three seeds. A tuned run could do even better.
- For the 7 sources never seen, the cut-off in that comparison was set on those same messages, in the same way for every model. Also, the same weights and last layer models were scored by an exact calculation of the last layer and were not saved as models.
How to run it yourself
pip install modal && modal setup
modal run wsp_app.py --stage prep # download model and five datasets
modal run wsp_app.py --stage baseline # baseline model scores
modal run wsp_app.py --stage diagnose # check each layer
modal run wsp_app.py --stage oracle # find where the signal is lost
modal run wsp_eval2.py --version v3 # test on messages written by real people
modal run wsp_v4.py --stage prep # 13 sources to build, 7 kept aside
modal run wsp_v4.py --stage select # the stricter test
modal run wsp_v4.py --stage final --cfg '{"lam":0.3,"fn_q":0.99,"fp_q":0.995,"fn_delta":16,"fp_delta":16,"rounds":2,"order":["fn","fp"]}'
modal run wsp_v4.py --stage bake --cfg 3.79 # version 5
modal run wsp_probe.py --stage combo # search for a better signal
modal run wsp_v6.py # version 6
modal run wsp_backprop.py # compare with normal training
modal run wsp_v7.py # version 7
modal run wsp_v8.py # version 8
The code which changes the weights is in wsp_path.py. It is about 120 lines. The numbers behind every table are in the results folder. The changed model (version 5) is on Hugging Face: rootxhacker/deberta-v3-base-prompt-injection-v2-weight-edited.
Credits and data
The idea is from Weight-Space Programming by Rikiya Takehi. The model is deberta-v3-base-prompt-injection-v2 from ProtectAI.
Datasets I used to build and test the change: deepset/prompt-injections, xTRam1/safe-guard-prompt-injection, leolee99/NotInject, jackhhao/jailbreak-classification, Lakera/gandalf_ignore_instructions, TrustAIRLab/in-the-wild-jailbreak-prompts, microsoft/llmail-inject-challenge (phase 1), OpenAssistant/oasst1, databricks/databricks-dolly-15k, fka/awesome-chatgpt-prompts, tatsu-lab/alpaca and the normal emails from SetFit/enron_spam.
Datasets I kept completely aside: lmsys/toxic-chat, qxcv/tensor-trust, microsoft/llmail-inject-challenge (phase 2), yanismiraoui/prompt_injections, rubend18/ChatGPT-Jailbreak-Prompts and HuggingFaceH4/ultrachat_200k.