# How an LLM learns to behave: training, RLHF, guardrails and how each breaks

> Pretraining, fine-tuning, RLHF, system prompts and guardrails in plain words, then the attacks on each: data poisoning, backdoors, jailbreaks and filter evasion.

- Published: 2026-11-23
- Topics: AI security, LLM security, Model training
- Canonical page: https://thesecguy.com/notes/llm-training-rlhf-guardrails-poisoning-jailbreaks/
- Publisher: The Sec Guy (https://thesecguy.com)

**Short answer:** A language model learns by guessing the next word across a huge pile of text. Later rounds of training, fine-tuning and human-preference training (RLHF), teach it to follow instructions and to refuse harmful requests. A system prompt and filter models then sit around it. Each layer has a documented failure. In a 2025 study, 250 poisoned documents backdoored every model size tested. Refusal has been switched off inside open models, system prompts get extracted, and filters have been evaded with character tricks. Keep secrets and hard limits in code outside the model.

---

A developer writes a program's behavior down as code. A language model's behavior is trained in over several stages, and then a prompt and a few filters are placed around the result. Every one of those stages can be attacked, and a behavior that was trained in can be trained, steered or talked back out.

## Pretraining, in plain words

Picture a student with a library card and one exercise. Cover the next word on the page, guess it, uncover it, see how wrong the guess was, adjust. Repeat for more pages than any person could read in many lifetimes.

Nobody tells this student which books are true. Whatever is on the shelves goes in, including the pages a stranger slipped between the covers.

<figure class="fig">
<p class="fig-k">The training loop, one round</p>
<div class="flow">
<div class="node"><b>1. Guess</b><span>The model reads some text and predicts the next token</span><div class="chips"><i class="chip">prediction</i></div></div>
<div class="node"><b>2. Score</b><span>The guess is compared with the real next token, giving a number called the loss</span><div class="chips"><i class="chip">loss</i></div></div>
<div class="node"><b>3. Nudge</b><span>Every weight moves a small amount in the direction that lowers the loss</span><div class="chips"><i class="chip">gradient descent</i></div></div>
<div class="node"><b>4. Repeat</b><span>Back to step 1 with the next piece of text</span><div class="chips"><i class="chip">many rounds</i></div></div>
</div>
<figcaption>Our illustration of the gradient descent steps in Google's Machine Learning Crash Course, applied to next-token prediction.</figcaption>
</figure>

## Pretraining, technically

The exercise is called causal language modeling. The [Hugging Face documentation](https://huggingface.co/docs/transformers/en/tasks/language_modeling) defines it in one line: "Causal language modeling predicts the next token in a sequence of tokens". A token is a word or a piece of one.

A model is a very large set of numbers called weights. The [Hugging Face LLM course](https://huggingface.co/learn/llm-course/chapter1/4?fw=pt) describes the start: "Pretraining is the act of training a model from scratch: the weights are randomly initialized". No person labels the data, because the right answer is already in the text. In the course's words, "the objective is automatically computed from the inputs of the model."

The adjusting is done by gradient descent. Google's [Machine Learning Crash Course](https://developers.google.com/machine-learning/crash-course/linear-regression/gradient-descent) lists the steps: "Calculate the loss with the current weight and bias", work out which direction reduces it, "Move the weight and bias values a small amount in the direction that reduces loss", and repeat. The loss is a single number for how wrong the prediction was. No step in the loop checks who wrote a sentence.

## Fine-tuning and instruction tuning, in plain words

Pretraining produces a well-read graduate who has never held a job. Give that graduate a prompt and they continue the text, which is different from answering it.

Fine-tuning is the job training: a short course on a small, chosen set of examples. Instruction tuning is one kind, where the examples are requests paired with good answers, so the graduate learns that a question calls for a reply.

<figure class="fig">
<p class="fig-k">Same method, different data</p>
<div class="flow">
<div class="node"><b>Pretraining</b><span>From random weights, on very large amounts of text. Can take weeks</span><div class="chips"><i class="chip">general language</i></div></div>
<div class="node"><b>Fine-tuning</b><span>More training on a small dataset for one task. Needs far less data</span><div class="chips"><i class="chip">a specialty</i></div></div>
<div class="node"><b>Instruction tuning</b><span>Fine-tuning on examples of requests and the answers people wanted</span><div class="chips"><i class="chip">a chat model</i></div></div>
</div>
<figcaption>Our summary of the Hugging Face LLM course and the InstructGPT paper (Ouyang et al., 2022).</figcaption>
</figure>

## Fine-tuning and instruction tuning, technically

The loop stays the same and the data changes. The Hugging Face course defines fine-tuning as "the training done after a model has been pretrained", using "a dataset specific to your task", and adds that it "requires way less data to get decent results."

OpenAI's 2022 paper ["Training language models to follow instructions with human feedback"](https://arxiv.org/abs/2203.02155v1) shows instruction tuning at work. The paper opens with "Making language models bigger does not inherently make them better at following a user's intent." So the authors started from GPT-3 and had hired labelers write out examples. In the paper's words, "we collect a dataset of labeler demonstrations of the desired model behavior". That dataset held about 13,000 training prompts.

We covered the cheap modern way of fine-tuning, and its privacy side, in [LoRA, differential privacy and conformal prediction](https://thesecguy.com/notes/lora-differential-privacy-conformal-prediction/).

## RLHF, in plain words

Examples only go so far. It's easier to say which of two answers is better than to write the perfect one.

So reviewers are shown pairs of answers and pick the one they prefer. A second model, the judge, studies thousands of those picks until it can predict the reviewers' taste. Then the main model practices against the judge and drifts toward answers the judge scores well.

Declining a harmful request is a habit learned in training of this kind, the way a person learns manners. Nothing locks it in place.

<figure class="fig">
<p class="fig-k">The three steps in the InstructGPT paper</p>
<div class="flow">
<div class="node"><b>Step 1: show</b><span>People write good answers and the model is fine-tuned on them</span><div class="chips"><i class="chip">about 13k prompts</i></div></div>
<div class="node"><b>Step 2: judge</b><span>People rank model answers. A reward model learns to predict their choice</span><div class="chips"><i class="chip">33k prompts</i></div></div>
<div class="node"><b>Step 3: practice</b><span>The model is trained to score well with the reward model</span><div class="chips"><i class="chip">31k prompts</i></div></div>
</div>
<figcaption>Source: Ouyang et al. (OpenAI), "Training language models to follow instructions with human feedback", 2022. Dataset sizes are the paper's training prompt counts.</figcaption>
</figure>

## RLHF, technically

RLHF stands for reinforcement learning from human feedback. The same OpenAI paper names its steps: "Collect demonstration data, and train a supervised policy", then "Collect comparison data, and train a reward model", then "Optimize a policy against the reward model using PPO", a reinforcement learning algorithm. The reward model is trained "to predict which model output our labelers would prefer."

The human side was small. The team "hired a team of about 40 contractors", and the paper is plain about what that means: the procedure "aligns the behavior of GPT-3 to the stated preferences of a specific group of people".

Safety behavior comes from the same kind of training. A 2024 paper on refusals opens with the sentence "Conversational large language models are fine-tuned for both instruction-following and safety". Our reading of what follows from that: a refusal is a tendency stored in the weights, sitting alongside every other learned tendency. No separate rulebook exists inside the model for anyone to audit.

## The system prompt, in plain words

A shop owner tapes a note behind the counter for the new hire: you work for this shop, be polite, never discuss supplier prices. Customers don't see the note. They do talk to the person who read it.

The hire reads the note and hears the customer through the same pair of ears. A persuasive customer can get the note read aloud.

<figure class="fig">
<p class="fig-k">Who the model is trained to listen to first</p>
<div class="rank">
<div class="rk"><b>1</b><span>System message<small>written by the app's developer</small></span></div>
<div class="rk"><b>2</b><span>User message<small>typed by the person using the app</small></span></div>
<div class="rk"><b>3</b><span>Third-party content<small>web pages, files and tool results the model reads</small></span></div>
</div>
<figcaption>Source: the order described in Wallace et al. (OpenAI), "The Instruction Hierarchy", 2024. It's a trained preference, so it can fail.</figcaption>
</figure>

## The system prompt and instruction hierarchy, technically

The system prompt is text the developer places ahead of the conversation. It reaches the model as tokens, like everything else.

OpenAI researchers described the weakness in an [April 2024 paper](https://arxiv.org/abs/2404.13208v1): "LLMs often consider system prompts (e.g., text from an application developer) to be the same priority" as text from untrusted users and third parties. Their proposal, an instruction hierarchy, "explicitly defines how models should behave when instructions of different priorities conflict". In that order, "system messages take precedence over user messages, and user messages take precedence over third-party content".

The order is enforced with more training: the model is shown conflicts and taught which side to follow. So the hierarchy is one more learned behavior. The authors trained GPT-3.5 Turbo this way, and they say their models are "likely still vulnerable to powerful adversarial attacks".

## Guardrails, in plain words

A guard stands at the shop door and checks bags on the way in and on the way out. The guard isn't the shop assistant, so a customer who charms the assistant still has to get past the guard. Guards get fooled as well, for instance by a bag with a false bottom.

<figure class="fig">
<p class="fig-k">Where the pieces sit, and what attacks each one</p>
<div class="flow">
<div class="node"><b>Training data</b><span>What the model learned from, before you ever saw it</span><div class="chips"><i class="chip">poisoning</i><i class="chip">backdoors</i></div></div>
<div class="node"><b>System prompt</b><span>The developer's instructions, sent with every request</span><div class="chips"><i class="chip">extraction</i></div></div>
<div class="node"><b>Input classifier</b><span>A separate model that screens what comes in</span><div class="chips"><i class="chip">character tricks</i></div></div>
<div class="node"><b>The model</b><span>Answers, with its trained habit of refusing</span><div class="chips"><i class="chip">jailbreaks</i><i class="chip">fine-tuning attacks</i></div></div>
<div class="node"><b>Output classifier</b><span>A separate model that screens what goes out</span><div class="chips"><i class="chip">evasion</i></div></div>
</div>
<figcaption>Our mapping of the research in this note onto a typical chat application.</figcaption>
</figure>

## Guardrails, technically

A guardrail here means a classifier: a model whose only output is a verdict such as safe or unsafe. Meta's [Llama Guard](https://arxiv.org/abs/2312.06674v1), from December 2023, is an open example. Its paper calls it "an LLM-based input-output safeguard model". It classifies prompts on the way in and model responses on the way out against a list of risk categories, and it is itself "a Llama2-7b model that is instruction-tuned" on the authors' dataset.

Anthropic's [Constitutional Classifiers](https://www.anthropic.com/research/constitutional-classifiers), published on 3 February 2025, follow the same layout: "input and output classifiers trained on synthetically generated data". In both cases the guardrail is a trained model too.

## Attack 1: poison the training data

On 9 October 2025, Anthropic, the UK AI Security Institute and the Alan Turing Institute [published a count](https://www.anthropic.com/research/small-samples-poison) of how many bad pages it takes. They found that "as few as 250 malicious documents can produce a "backdoor" vulnerability in a large language model". They trained models "ranging from 600M to 13B parameters". A parameter is one weight, so the count is a measure of model size. The largest saw over 20 times more data than the smallest, and the same 250 documents worked on all of them. In their setup that was "0.00016% of total training tokens". Before this, the write-up says, "Previous work assumed that adversaries must control a percentage of the training data to succeed".

Keep the limits in view. The backdoor was a narrow one: a trigger phrase, `<SUDO>`, that made the model "produce random, gibberish text". The authors call it a behavior "that is unlikely to pose significant risks in frontier models", and say "It remains unclear how far this trend will hold as we keep scaling up models."

A [2023 paper](https://arxiv.org/abs/2302.10149v2) by researchers at Google DeepMind, ETH Zurich and NVIDIA, among others, showed one way an outsider gets poisoned content in. Large datasets are often lists of web addresses, and domains expire. Buy the expired domain and you choose what later downloads receive. The authors estimate "we could have poisoned 0.01% of the LAION-400M or COYO-700M datasets for just $60 USD". Those are datasets of links to images. The paper states "We do not actually poison any datasets", and the maintainers were told.

<figure class="fig">
<p class="fig-k">Three numbers from the research</p>
<div class="tiles">
<div class="tile hot"><b>250</b><span>poisoned documents backdoored every model size tested</span><small>600M to 13B parameters, 2025</small></div>
<div class="tile"><b>$60</b><span>estimated cost to have poisoned 0.01% of a web-scale image dataset</span><small>LAION-400M or COYO-700M, 2023</small></div>
<div class="tile"><b>13</b><span>open chat models where one internal direction controlled refusal</span><small>up to 72B parameters, 2024</small></div>
</div>
<figcaption>Sources: Anthropic, UK AI Security Institute and Alan Turing Institute 2025; Carlini et al. 2023; Arditi et al. 2024.</figcaption>
</figure>

## Attack 2: a backdoor that survives safety training

Anthropic's ["Sleeper Agents"](https://arxiv.org/abs/2401.05566v2) paper, from January 2024, asked whether later safety training washes a backdoor out. The researchers built backdoored models on purpose, which they describe as "proof-of-concept examples". One was trained to "write secure code when the prompt states that the year is 2023, but insert exploitable code when the stated year is 2024". Then they applied the standard fixes, "including supervised fine-tuning, reinforcement learning, and adversarial training". The paper found that such a backdoor "can be made persistent", and that it was "most persistent in the largest models". Smaller models lost it more easily. Worse, "adversarial training can teach models to better recognize their backdoor triggers, effectively hiding the unsafe behavior".

The paper says it "does not assess the likelihood" of this happening in practice. What we take from it is that passing a safety evaluation doesn't prove a model is clean.

## Attack 3: jailbreak a behavior that was only learned

A jailbreak is an input that gets a model to drop its trained refusal. In open models, researchers have found a switch for it.

The paper ["Refusal in Language Models Is Mediated by a Single Direction"](https://arxiv.org/abs/2406.11717v3) studied "13 popular open-source chat models up to 72B parameters in size", including Llama, Gemma and Qwen models. Inside each one, the paper found refusal is "mediated by a one-dimensional subspace": a single direction in the model's internal activity. The authors report that "erasing this direction from the model's residual stream activations prevents it from refusing harmful instructions". The reverse works too: "adding this direction elicits refusal on even harmless instructions." They state the limits themselves. The findings "may not generalize to untested models", and the paper calls itself "more of an existence proof". The method also "has the obvious limitation that we require access to the model's weights." So it applies to open models you can download.

Hosted models have a different door: the fine-tuning service. A team from Princeton, Virginia Tech, IBM Research and Stanford [broke GPT-3.5 Turbo's safety behavior](https://arxiv.org/abs/2310.03693v1) by "fine-tuning it on only 10 such examples at a cost of less than $0.20". They also found that "benign and commonly used datasets can also inadvertently degrade the safety alignment of LLMs", "though to a lesser extent." Our LoRA note has the details. A third route needs no special access, only patience, and it's in our note on [temperature and retry jailbreaks](https://thesecguy.com/notes/temperature-speculative-decoding-side-channels/).

## Attack 4: read the system prompt

The note behind the counter gets read aloud. A paper by Zhang, Carlini and Ippolito, ["Effective Prompt Extraction from Language Models"](https://arxiv.org/abs/2307.06865v3), tested "3 different sources of prompts and 11 underlying large language models" and found that "simple text-based attacks can in fact reveal prompts with high probability".

Training helps: the instruction hierarchy paper reports that, for its GPT-3.5 Turbo model, "defense against system prompt extraction is improved by 63%". A better block rate still doesn't make the prompt a place for secrets. OWASP's guidance on [system prompt leakage](https://genai.owasp.org/llmrisk/llm072025-system-prompt-leakage/) is blunt: "the system prompt should not be considered a secret, nor should it be used as a security control".

## Attack 5: slip past the guardrail

In 2025 researchers from Mindgard and Lancaster University [tested six guardrail systems](https://arxiv.org/html/2504.11168v3), among them Azure Prompt Shield and Meta Prompt Guard. They rewrote known attack prompts with character tricks such as invisible zero-width characters, look-alike letters and text hidden inside emoji. The emoji trick did best. In the paper's words, "The most successful attack was Emoji Smuggling, which achieved a 100% ASR for both prompt injections and jailbreaks". ASR is attack success rate, which here means the share of attack prompts the guardrail labeled as harmless. The paper measured the guardrail only. It didn't measure whether a chat model behind it then acted on the hidden text. A related trick against the classifier's tokenizer, TokenBreak, is in our [tokenizer note](https://thesecguy.com/notes/tokenizer-bias-logit-bias-security/).

The defensive side has numbers too. Anthropic tested Constitutional Classifiers on a version of Claude 3.5 Sonnet with 10,000 generated jailbreak prompts. With no classifiers "the jailbreak success rate was 86%". With them it "was reduced to 4.4%", at a cost of 23.7% more compute. In an earlier two-month test of a prototype, 183 participants spent more than 3,000 hours and "no universal jailbreak was discovered." A universal jailbreak is a single method that gets past the defenses for every question in the test. Then came a public demo in February 2025. Of 339 jailbreakers, "four participants successfully cleared all levels", and one of them had what Anthropic judged a universal jailbreak. Anthropic concluded, "we therefore recommend using complementary defenses".

## What to check, with an example

One illustrative setup to hold in mind, made up for this list: an online store runs a support chatbot. It's an open model the team downloaded and fine-tuned on old support tickets. Its system prompt contains a staff discount code. A classifier screens incoming messages, and the bot can issue refunds.

1. **Who could have written your training data?** Pretraining data is out of your hands, but fine-tuning data isn't. In the store example, tickets are written by customers, so anyone could have submitted text that ends up in the fine-tuning set. The Anthropic study was about pretraining, but we think its lesson carries over: a small number of documents can matter. Read a sample before training and record where each batch came from.
2. **Do you trust the model file itself?** The store downloaded its base model. Sleeper Agents showed a backdoor can sit through safety training and stay quiet until its trigger appears, so a passed safety evaluation doesn't rule one out. Prefer the original publisher, pin the exact version, and limit what the model can do so a hidden behavior has less to work with.
3. **What happens when the model says yes to something it shouldn't?** Assume it will, because refusal is learned. The store's refund limit belongs in the refund code, where a $500 request fails no matter how the bot was persuaded.
4. **Is anything in the system prompt worth stealing?** The staff discount code is. Move it out. OWASP names "API keys, auth keys, database names" as things to keep out of system prompts.
5. **Has your guardrail seen disguised text?** Send the store's classifier a known attack prompt with zero-width characters inserted, and another in look-alike letters. If either passes, normalize the text before the classifier reads it. Keep an output check as well.
6. **Did you re-test safety after fine-tuning?** Qi and colleagues found that ordinary datasets can degrade safety behavior by accident. The store should run the same refusal tests before and after the ticket fine-tune, many times each.

Our [LLM security guide](https://thesecguy.com/notes/llm-security-guide/) says to treat model output as untrusted input, and that rule runs through all six checks. Training shapes what a model tends to do, and the code around it decides what it's allowed to do.

---

**Sources** (all checked 23 November 2026)
- Hugging Face, Transformers documentation, "Causal language modeling": [huggingface.co](https://huggingface.co/docs/transformers/en/tasks/language_modeling), and LLM course, "How do Transformers work?": [huggingface.co](https://huggingface.co/learn/llm-course/chapter1/4?fw=pt)
- Google, Machine Learning Crash Course, "Linear regression: Gradient descent": [developers.google.com](https://developers.google.com/machine-learning/crash-course/linear-regression/gradient-descent)
- Ouyang et al. (OpenAI), "Training language models to follow instructions with human feedback", 2022: [arxiv.org/abs/2203.02155](https://arxiv.org/abs/2203.02155v1) and full text at [ar5iv](https://ar5iv.labs.arxiv.org/html/2203.02155)
- Wallace et al. (OpenAI), "The Instruction Hierarchy: Training LLMs to Prioritize Privileged Instructions", 2024: [arxiv.org/abs/2404.13208](https://arxiv.org/abs/2404.13208v1)
- Inan et al., "Llama Guard: LLM-based Input-Output Safeguard for Human-AI Conversations", 2023: [arxiv.org/abs/2312.06674](https://arxiv.org/abs/2312.06674v1)
- Anthropic, "Constitutional Classifiers: Defending against universal jailbreaks", 3 February 2025: [anthropic.com](https://www.anthropic.com/research/constitutional-classifiers)
- Anthropic, UK AI Security Institute and Alan Turing Institute, "A small number of samples can poison LLMs of any size", 9 October 2025: [anthropic.com](https://www.anthropic.com/research/small-samples-poison)
- Carlini et al., "Poisoning Web-Scale Training Datasets is Practical", 2023: [arxiv.org/abs/2302.10149](https://arxiv.org/abs/2302.10149v2)
- Hubinger et al., "Sleeper Agents: Training Deceptive LLMs that Persist Through Safety Training", 2024: [arxiv.org/abs/2401.05566](https://arxiv.org/abs/2401.05566v2)
- Arditi et al., "Refusal in Language Models Is Mediated by a Single Direction", 2024: [arxiv.org/abs/2406.11717](https://arxiv.org/abs/2406.11717v3)
- Qi et al., "Fine-tuning Aligned Language Models Compromises Safety, Even When Users Do Not Intend To!", 2023: [arxiv.org/abs/2310.03693](https://arxiv.org/abs/2310.03693v1)
- Zhang, Carlini, Ippolito, "Effective Prompt Extraction from Language Models", 2023, revised 2024: [arxiv.org/abs/2307.06865](https://arxiv.org/abs/2307.06865v3)
- Hackett et al. (Mindgard, Lancaster University), "Bypassing LLM Guardrails: An Empirical Analysis of Evasion Attacks against Prompt Injection and Jailbreak Detection Systems", 2025: [arxiv.org](https://arxiv.org/html/2504.11168v3)
- OWASP GenAI Security Project, "LLM07:2025 System Prompt Leakage": [genai.owasp.org](https://genai.owasp.org/llmrisk/llm072025-system-prompt-leakage/)
