A small model is fixing your code. It learned by copying thousands of perfect runs. Then the test tool returns an error it has never seen. Press Run 24 again and watch the copy break.
Teach a model to act by letting it study recordings of a stronger agent at work, then see exactly what that teaches and what it cannot.
Drag the tool failure rate, then switch between the two agents. Watch which runs finish. Then we build, piece by piece, everything underneath: what an agent is, what a trace holds, how the training loss counts tokens, how TRL runs it, and why copying alone cannot teach recovery.
You need a rough idea of how a chatbot works (text goes in, text comes out) and a little Python for the code. We build the rest from zero.
Based on Step 1 of A curriculum for post-training agents by Ben Burtenshaw, Sergio Paniego and Merve (Hugging Face, 20 October 2026), the glossary Harness, Scaffold, and the AI Agent Terms Worth Getting Right by Sergio Paniego and Aritra Roy Gosthipaty, and the TRL SFT Trainer docs. The livestream is Training Agents 1. Every idea is re-taught here in our own words and devices.
Illustrative toy, not a measurement. A task has 4 tool calls. Each call fails on its own with the chosen chance. The copy-only agent never saw a failed result in training (the post: it “has not learned how to recover”), so one failure ends the run. The other agent retries a failed call once. The percentages in the read-out are the exact averages of that rule, (1 − p)4 and (1 − p2)4; the 24 runs are one seeded sample.
Chapter 0
See why a model that chats well can still fumble a ten-step job, and where fine-tuning on recorded runs fits in a five-step plan
Picture a small open model and a broken code project. Three tests fail. You ask the model to fix them. A chat model answers with a paragraph of advice: “Check your imports, and make sure the function returns a number.” That advice may be right. It does not fix anything.
What you want is a different kind of answer. Open the test file. Read the error. Open the code that the error points to. Change one line. Run the tests again. Look at the new result. If a test still fails, go back.
This is not one answer. It is a series of small acts, each one based on what the last one showed.
A model that works this way is an agent. It works over many turns (one turn is one thing the model says, then one thing the world says back). On each turn it may call a tool, which is a function the model asks for, like “run these tests”. It reads the result and decides what to do next. The Hugging Face post that this lesson follows puts it this way: the agent “calls tools, reads the results and decides what to do next.”
A model starts life in pretraining. It reads a huge pile of text and learns to guess the next word. After that stage it can continue text, but it does not yet follow instructions or use tools. The stages that come after are called post-training. The post names three: supervised fine-tuning, distillation and reinforcement learning. They “turn a pretrained model into one that follows instructions, uses tools or solves a specific task.”
For a chat answer, each training example is one question and one answer. For an agent it is not. The unit is a whole run of many turns. So the post uses a new name: agentic post-training applies these stages to agents, and “training has to account for the whole sequence of turns instead of a single answer.” Keep that sentence in mind. Every chapter here asks what changes when the example is a sequence.
The post lays out a curriculum of five steps, plus a step 0 for vocabulary. Each step answers one question: what does the model learn from? Press through them below. Notice that the answer gets richer from left to right: first a recording, then a teacher’s opinion on each word, then a score, then the outcome of acting, then whole runs of a real agent.
Each box is one step of the post’s curriculum. Choose a step to see what the model learns from and which TRL trainer runs it. This lesson lives in the first box.
The table text is the post’s own “Steps at a glance” table. The one-line needs in the read-out (a dataset of traces, prompts and a teacher, prompts and a reward function, tasks and an environment, tasks plus an environment and an agent harness) come from the same table.
Step 1 is the cheapest and the calmest. The post says the model “learns to copy agent traces”: recordings of an agent solving a task, “with every tool call and its result, usually produced by a stronger model.” It is “cheap and stable.” You do not need a teacher online, a reward function or a sandbox. You need a dataset.
The price is in one more sentence of the post, and it drives the whole lesson: “The model only sees correct traces, never its own attempts. When it makes a mistake while solving a task, it has not learned how to recover from it.” The hero at the top of this page is that sentence made playable. Steps 2 to 5 exist to fix it, by training on the model’s own outputs.
The post gives Step 1 three things: a livestream (Training Agents 1: fine-tune a coding agent), a write-up (Training Agents: Class 1, SFT from scratch), and the SFT Trainer docs. The post’s step 0 adds a glossary of agent terms, which we need first. If fine-tuning itself is new to you, the post points to the Hugging Face LLM Course; this lesson also teaches the loss from zero in Chapter 4. For the other steps, follow the links in Chapter 10.
Chapter 1
Separate four words that people mix up, so you can say exactly which part a training run changes
Two coding tools sit side by side. Both use the same underlying language model. In the first, you type a request and it edits your files, runs your tests and keeps going until they pass. In the second, you type the same request and it writes a tidy explanation. Nothing about the model weights differs. So what does?
The answer is everything around the model. Before we train anything, we need names for the parts. The words are slippery. After ICLR in 2026, one of the glossary authors asked what “harness” and “scaffold” mean, and heard explanations that “did not converge to a single explanation.” The glossary post by Sergio Paniego and Aritra Roy Gosthipaty is their attempt to fix this. This chapter retells its core in our words.
The model is the language model itself. Text goes in. Text comes out. On its own it has “no memory between calls, and no loop.” It answers one prompt and stops. Think of a very skilled typist who is handed one sheet of paper, types one reply and then forgets the sheet.
The model can say that it wants to use a tool. It writes something like “please run the tests.” But writing the request does nothing. Something else has to read the request and carry it out.
The scaffolding is, in the glossary’s words, “the behavior-defining layer around the model.” It has four ingredients: the system prompt (standing instructions), the tool descriptions (a menu of what the model may ask for), the rule for parsing the model’s replies (how to find the tool request in the text), and what the agent remembers across steps (context management). Think of the desk the typist sits at: the instructions pinned up, the menu of errands, the notepad.
The scaffold shapes how the model “sees the world and acts in it.” It does this both when we train the model and when we run it.
The harness is the execution layer. It calls the model, handles the model’s tool calls and decides when to stop. In our picture it is the clerk who carries each sheet in, runs each errand and rings the bell when the day ends. The glossary says the harness “is what makes the agent run.” Designing it well, such as when to stop, how to handle errors and what guardrails to add, is called harness engineering. Our harness engineering lesson goes deeper.
The word agent comes from reinforcement learning. There it is a function that takes an observation and returns an action. The environment takes that action and returns a new observation, and the loop repeats. That loop is still the core of LLM agents. In the LLM world the glossary defines an agent as “a model plus everything around it that lets it act, not just respond.” The community shorthand is Agent = Model + Harness. Its blunt version: “If you’re not the model, you’re the harness.”
You may notice a catch. Products such as Claude Code, Codex and Antigravity CLI call the whole thing a harness, scaffolding included. That is the broad use. The split between scaffold and harness matters most “when you need to reason about them separately, as in a training pipeline.” We are in a training pipeline, so we will use the narrow words: the scaffold is what the model reads, and the harness is the loop that runs it. Try the parts below.
The outer frame is the agent. Choose a part to light it. Then press a swap button to change the model or the harness and keep the rest.
The part definitions and the swap sentences follow the glossary post. The boxes are a teaching diagram, not a software architecture: real products draw the lines in different places, and the glossary says many of these terms have no universally accepted definition yet.
Try the swaps. Put a better model into the same harness and the experience changes. Keep the model and change the harness and the experience changes again. The glossary says it directly: two products on the same model “can feel completely different because their harnesses make different choices.” The model, the harness and the product are three different things.
The glossary uses a coding agent as its worked example, and so will we. The system prompt says “you are a coding assistant; work in this folder.” The tool descriptions list read_file, edit_file and run_tests. The output format says how to write a tool request. Those three are the scaffolding. The loop that calls the model, finds the tool request, runs it, appends the result and decides to stop is the harness. At training time, the glossary adds, the harness “also runs many of these loops in parallel and feeds the results back to update the model.”
One more word will matter. A policy is the behavior an agent follows: in any situation, the probability of each possible action. Part of the policy is learned in the weights. But the glossary notes the behavior “also depends on the surrounding scaffolding and harness.” A policy is not an agent. The policy is the behavior; the agent is the whole system. Training changes the weights. The policy you get also depends on the scaffold you train inside.
Chapter 2
Follow a single agent loop, message by message, and see exactly what the model reads and writes on each turn
A tool call looks like magic from outside. The agent “ran the tests.” But a language model cannot run anything. It can only write text. So what actually crosses between the model and your computer? Let us watch one run, line by line, because a training example is nothing more than a saved copy of these lines.
Every call to the model carries two things. The first is a list of messages. Each message has a role (who wrote it) and content (what they wrote). The roles are system for the standing instructions, user for the request, assistant for the model, and tool for a tool’s result. The second is the tools list: a menu where each tool has a name, a plain description and the shape of its inputs, written as a JSON schema (a standard way to describe the fields of a JSON object).
json// the menu: one tool, described for the model { "type": "function", "function": { "name": "run_tests", "description": "Run the project's tests and return the output.", "parameters": { "type": "object", "properties": { "path": { "type": "string" } }, "required": ["path"] } } }
The model’s reply is also a message. When it wants a tool, the reply holds a tool_calls entry instead of plain text: the tool’s name and its arguments. The glossary says modern inference APIs treat this as a “first-class object: the harness receives the call directly and routes it to the right function.” Here is one reply, then the result the harness sends back. (The field names follow the common chat format. TRL’s docs say tool-calling datasets carry tool_calls and tool role messages, and a tools column of schemas. The exact fields are in the TRL dataset formats page.)
json{ "role": "assistant", "content": "", "tool_calls": [{ "type": "function", "function": { "name": "run_tests", "arguments": { "path": "tests/test_cart.py" } } }] } { "role": "tool", "name": "run_tests", "content": "1 failed: test_total, assert 30 == 33" }
Now the harness. Remember: the model has no memory between calls. So on every turn the harness must send the whole list again, with the newest messages at the end. The loop is short.
pythonmessages = [system, user] while True: reply = model(messages, tools=TOOLS) # one call: text in, text out messages.append(reply) if not reply.tool_calls: # no tool requested: the agent is done break for call in reply.tool_calls: # the harness runs each request result = run_tool(call.name, call.arguments) messages.append({"role": "tool", "name": call.name, "content": result})
Read it as a story. The harness calls the model. The model replies. If the reply asks for a tool, the harness runs it and appends the result. Then it calls the model again, this time with a longer list. The loop ends when the model replies without a tool call. This is one stop rule. Real harnesses add others, such as a limit on turns, because “deciding when the agent should stop” is part of their job.
Step through a full run below. A real run has the same four phases on every turn: send, reply, run, append.
Left: the loop, with the active phase lit. Below: the message list the model reads on the next call. Press Step to move one phase, or Play to run it.
Illustrative run: the messages are made up for this lesson, not taken from a real trace. Token counts use a rule of thumb of about 4 characters per token, so they are rough. The shape is real: each model call re-reads the whole list, so the text it reads only grows.
Watch the counter. On the first call the model reads only the system message and the request. By the last call it re-reads every earlier call and result as well. The model learned nothing new between calls. It is simply handed a longer page each time.
The model does not read a list of dictionaries. A chat template turns the whole message list into one string, with special marker tokens that show where each role starts and ends. A tokenizer then cuts the string into token ids. So for a run with T tokens, the model receives an integer tensor of shape [1, T]. For every position it returns scores over the vocabulary, shape [1, T, V], where V is the number of distinct tokens the model knows. Only the scores at the last position are used to pick the next token. Chapter 4 shows what training does with the other positions.
Here is the first way an agent fails, and it has nothing to do with intelligence. Symptom: the agent says it will run the tests, and nothing runs. Measurement: count how many replies contain a tool call the harness could parse. If 3 of 40 replies are plain text that merely describes a call, the parse rate is 92.5% and every miss is a stalled run. Fix: the model must write the call in exactly the format the harness expects. The scaffold states that format; fine-tuning on traces that use it teaches the habit. Chapter 9 returns to this.
Chapter 3
Turn one recorded agent run into one row of a dataset, and see where the prompt ends and the part to learn begins
Imagine a stronger model, say a large one you rent, fixing bugs all day inside your harness. The harness writes down every message of every run. By morning you have 5,000 recordings. Each shows a task, a string of tool calls, the results and a final answer. These recordings are your training data.
The glossary has a name for one such recording: a rollout, “one full agent run from start to finish: what the agent saw, what it did, and what reward it got at each step.” It adds that a rollout is “also called a trajectory or a trace, depending on the context.” In this lesson a trace is the saved message list of one run: the same list you watched grow in Chapter 2.
A dataset here is a table. Each row is one training example. For an agent, one row holds a whole run, not one question and one answer. The TRL docs say a tool-calling row needs two things: the conversation messages, “including any tool calls (tool_calls) and tool responses (tool role messages),” and the list of available tools in a tools column, “typically provided as JSON schemas.”
Why keep the tools list in the row? The model saw that menu when the stronger model produced the run. If the menu is missing from the training text, the model learns to call tools it was never shown. Record a run below and watch the row take shape.
The bar is the run, one block per message, wide in proportion to its length. Press Record next message to add one. Then switch the view to see the same row split into a prompt and a completion.
The run is the same made-up one as Chapter 2, not a real recording. Block widths use about 4 characters per token, so they are rough. The two shapes follow the TRL dataset formats: a conversational language-modeling row and a conversational prompt-completion row.
The TRL docs say SFT “supports both language modeling and prompt-completion datasets,” in a standard (plain text) or conversational (messages) form. That makes four shapes. For agents we use the two conversational ones, because tool calls only exist inside messages.
| Shape | What a row looks like | Use for agents |
|---|---|---|
| Standard language modeling | {"text": "The sky is blue."} | No: no roles, no tool calls |
| Conversational language modeling | {"messages": [{"role": ..., "content": ...}]} | Yes: the whole run as one list |
| Standard prompt-completion | {"prompt": "The sky is", "completion": " blue."} | No: plain strings |
| Conversational prompt-completion | {"prompt": [...], "completion": [...]} | Yes: the task as prompt, the run as completion |
The split matters in Chapter 5. In a prompt-completion row, the system message and the request are the prompt: what the agent is given. Everything after is the completion: what the agent does and sees. The docs say that by default, for prompt-completion rows, the loss is computed on the completion only.
Suppose you collect 5,000 successful traces. The TRL defaults, from the SFTConfig page, are a batch of 8 rows per device per step and 3.0 epochs. An epoch is one full pass over the data. So one epoch is 5,000 ÷ 8 = 625 steps. Three epochs make 625 × 3 = 1,875 optimizer steps on one device. A step here means one update of the model’s weights. If one trace averages 1,800 tokens (a made-up figure), the data holds 5,000 × 1,800 = 9 million tokens, and the model reads about 27 million token-positions over three epochs. That is a modest job, which is why the post calls Step 1 cheap.
The post stresses one rule in a single line: “The model only sees correct traces.” Think about what happens if one wrong trace sneaks in. Symptom: your fine-tuned agent confidently ends a run with a patch that does not work. Measurement: re-run each trace’s final check, such as the tests, and count how many traces end in a pass. If 4,700 of 5,000 do, then 300 traces teach a wrong ending, and 6% of what the model copies is wrong. Fix: keep only traces whose check passes. SFT has no way to tell good from bad on its own. It copies whatever you give it.
Chapter 4
Work the next-token loss by hand on one tool call, and see why lowering it makes the model write what the stronger model wrote
A student copies a teacher’s worked solution. After the first line, she covers the rest and tries to write the next word from memory. Then she peeks. If she was close, good. If she was far off, she notices and adjusts. Do this for thousands of pages and she starts to write like the teacher.
Supervised fine-tuning is that exercise, run on a model. The TRL docs state it plainly: the model is trained “in a fully supervised fashion using pairs of input and output sequences,” with the goal to “minimize the negative log-likelihood (NLL) of the target sequence, conditioning on the input.” Let us unpack every word of that.
Chapter 2 ended with the model returning scores for each next token. Turn those scores into probabilities: numbers from 0 to 1 that add up to 1 across the vocabulary. The model might say the next token after run is _tests with probability 0.55, and spread the other 0.45 over everything else.
Now peek at the recording. The stronger model really wrote _tests. How surprised should we be? If the model gave it 0.99, not surprised. If it gave 0.01, very surprised.
A logarithm turns that into a number. We use the natural log, written ln. It answers “what power of e gives this number?” The surprise of a token with probability p is −ln p. For p = 1, the surprise is 0. As p falls toward 0, the surprise grows without bound. This quantity is also called the negative log-likelihood.
For a whole target of T tokens, we add the surprises. The docs write it this way.
Take a tiny target: the five tokens run, _tests, (, path, ). Say the model starts out giving the true token these probabilities: 0.20, 0.55, 0.60, 0.30 and 0.85. (These are made up.) Compute −ln p for each.
−ln 0.20 = 1.609 −ln 0.55 = 0.598 −ln 0.60 = 0.511 −ln 0.30 = 1.204 −ln 0.85 = 0.163
Add them: 1.609 + 0.598 + 0.511 + 1.204 + 0.163 = 4.085. That is the summed loss. The trainer reports the average instead. The docs say loss is “the average cross-entropy loss computed over non-masked tokens.” So divide by 5: 4.085 ÷ 5 = 0.817. Training pushes each probability up. Try it.
Each bar is the probability the model gives the true token. The purple number under it is its surprise, −ln p. Press Train and watch the bars rise. A higher learning rate takes bigger steps.
Toy model, not TRL. Each token is a yes-or-no bet with a score z, p = 1 ÷ (1 + e−z), and each step nudges z by the learning rate times (1 − p), the true slope of −ln p. A real model has a score for every token in its vocabulary and shares its weights across all positions. The starting probabilities are made up.
Notice what the loss does not know. It does not know that run_tests is a tool call. It does not know the call was a good idea. To the loss, a tool name, a bracket and an English word are all the same kind of thing: one token, one probability, one surprise. The model learns to write tool calls only because the recordings contain tool calls.
How does one recording become many guesses? The docs describe it: “the loss is computed using a one-token shift: the model is trained to predict each token in the sequence based on all previous tokens.” Take a recording of T tokens, x1 to xT. The input is x1 to xT−1. The labels are the same sequence moved left by one: x2 to xT. Position 1 must guess token 2, position 2 must guess token 3, and so on. Because of the causal mask inside the model, position t cannot see token t+1. One forward pass therefore gives T − 1 guesses at once.
Padding, the filler that makes rows in a batch equal in length, is handled with an ignore index: padded positions get the label −100, and the loss skips them. The next chapter uses the same trick on purpose, for tokens that are real but should not count.
The docs list the metrics a run records. Three help here. loss is the average above. mean_token_accuracy is “the proportion of non-masked tokens for which the model’s top-1 prediction matches the ground truth token.” entropy is the average spread of the model’s predicted distribution: low means it is sure. A falling loss with rising accuracy is the healthy picture.
One caution, from plain machine learning. A loss can fall to near zero because the model memorized your rows. Symptom: training loss looks great and the agent fails on a task it has not seen. Measurement: hold out some traces and compute the loss on them too. The docs list eval_strategy with a default of 'no', so by default no held-out check runs. Fix: switch it on and compare. If the held-out loss rises while the training loss falls, stop.
Chapter 5
Choose which tokens of a trace the loss may judge, so the model learns its own words and not the world’s replies
A student is handed a page with four parts: the exam question, her teacher’s first try at a solution, a note from the grader that says “3 of 5 marks”, and the teacher’s fix. She is asked to practise writing. Should she practise writing the exam question? The grader’s note? Or only the teacher’s own lines?
A trace has the same four kinds of text. The system message and the request come from the builder. The tool calls and answers come from the model. The tool results come from the world. In Chapter 4 the loss judged every token. That is a choice, and it is not always the right one. A mask is a way to say: judge these tokens, skip those.
The mechanism is tiny. For each training row the trainer builds labels: the tokens the model should guess, one per position. By default the labels are a copy of the input tokens (shifted by one, as you saw). To mask a position, replace its label with the ignore index, −100. The docs say the loss ignores such positions: padding “is ignored in the loss computation by applying an ignore index (default: −100).” The model still reads the masked tokens as context. It just is not graded on guessing them.
TRL gives you two switches for agent data.
completion_only_loss=False to train on the full sequence.assistant_only_loss=True. The loss is then computed “only on the assistant responses, ignoring user or system messages.” The docs add a condition: the chat template must contain {% generation %} and {% endgeneration %} keywords around the assistant text. For known model families such as Qwen3, TRL patches the template for you.The two can combine: “Training on completion only is compatible with training on assistant messages only.” Use a conversational prompt-completion dataset and set assistant_only_loss=True.
Below is a short trace, one chip per token. Each chip carries a made-up surprise. Pick a mask and see which chips still count, and what happens to the average loss.
Chips are tokens, coloured by who wrote them: pink markers, teal the builder, orange the model, blue the tool. Faded chips are masked. The bars show each token’s surprise.
Illustrative: every token’s surprise is made up (role markers 0.02, system words 0.05, request words 0.9, the model’s tokens 0.5, tool-result words 1.6). The trace is a toy. Which marker tokens fall inside the mask depends on the chat template; here the assistant mask keeps the model’s words and its end-of-turn token and skips the role markers.
The average moves because the set it averages over moves. With every token counted, the long tail of easy tokens (markers and system words) pulls the average down, and the hard tool-result tokens pull it up. Keep only the model’s words and the average describes the one thing you want to improve. This also means loss numbers from runs with different masks cannot be compared. Symptom: you switch on assistant_only_loss and the logged loss shifts, and in the toy above it falls from 0.59 to 0.50. Measurement: the shift equals the change in the averaged set, not a worse model. Fix: compare runs only under one mask.
At run time the harness writes every tool result. The model never samples those tokens; it only reads them. Teaching it to predict them would spend learning on text it will never be asked to write. The docs name user and system messages as the ones assistant_only_loss skips. The mask comes from the generation keywords in the chat template, so check how your template treats the tool role. Look at the rendered text, not just the settings.
One more token needs the mask to include it: the end-of-turn token, the marker that says “my message stops here.” The docs warn that the EOS token must match the chat template “to ensure the model’s responses terminate correctly,” and give the example eos_token="<|im_end|>" for Qwen2.5. In an agent this is vital. A tool call must end the model’s turn, so the harness can run the tool.
Symptom of getting this wrong: after writing a tool call, the model keeps going and invents the result itself, as if it had run the tool. Measurement: count replies that hold a tool call followed by more text. Fix: keep the end-of-turn token inside the loss of every assistant message, and keep the model’s turn short.
assistant_only_loss=True, what happens to the user and system messages in a conversational trace?Chapter 6
Follow a dataset row through TRL’s trainer, and set the few options that decide whether a long agent trace survives
You have a table of 5,000 traces and you want a model that writes like them. Hugging Face’s TRL library packs the whole recipe from Chapters 4 and 5 into one class, SFTTrainer. The docs open with a quick start of three lines of real work.
pythonfrom trl import SFTTrainer from datasets import load_dataset trainer = SFTTrainer( model="Qwen/Qwen3-0.6B", train_dataset=load_dataset("trl-lib/Capybara", split="train"), ) trainer.train()
That trains a 0.6 billion parameter model on Capybara, a chat dataset. Swap the dataset for your traces and the same three lines train an agent, if your rows have the shape from Chapter 3. Now let us see what happens inside trainer.train(), one stage at a time, with the shapes.
from_pretrained. The docs warn that if you give no dtype, it defaults to float32 (a 32-bit number format), which differs from plain from_pretrained. Pass model_init_kwargs={"dtype": torch.bfloat16} to load in a lighter format.max_length is cut off.input_ids and labels have shape [8, L].Look hard at step 4. The docs give max_length a default of 1024 tokens, and the truncation mode is keep_start: it keeps the start of the row and cuts the rest, so the beginning of the row survives and the end is cut. For a chat answer that may be fine. For an agent trace the end is where the last test run and the final answer live.
Worked example. A trace has 1,800 tokens. With the default, the trainer keeps the first 1,024 and drops 776. That is 776 ÷ 1,800 = 43% of the trace. The model never sees the closing tool result or the final message, so it never learns how a run ends.
Symptom: the fine-tuned agent starts well and never finishes. Measurement: tokenize your rows and count how many exceed max_length. Fix: raise max_length above the longest trace you care about, or filter out traces that are too long, or set it to None (no truncation, which costs memory). Use the builder below to see the effect.
The histogram is the length of 5,000 traces. The line is max_length. Everything to its right is cut off. Move the line, flip the switches, and read the config the trainer would get.
Illustrative: the 5,000 trace lengths follow a made-up bell curve on a log scale, with a median of 1,800 tokens. Real datasets differ; measure yours. The options, their names and their defaults (max_length 1024, learning rate 2e-5, about 1e-4 when training adapters) are from the TRL docs; the dataset path is a placeholder.
Learning rate. The default is 2e-5. The docs say that when training adapters you “typically use a higher learning rate (≈1e-4) since only new parameters are being learned.” An adapter is a small set of new weights added next to the frozen model; LoRA is the common kind, enabled with peft_config=LoraConfig(). It trains far fewer numbers than full fine-tuning.
Packing. With packing=True, the trainer joins several rows into one fixed-length block “to improve computational efficiency and reduce padding,” using max_length as the block length. That helps most when rows are short. Agent traces are long, so the gain is smaller. This is our reasoning, not the docs’. Check the docs’ Packing page before you rely on it.
The log. Every logging_steps (default 10) the trainer records loss, mean_token_accuracy, entropy, grad_norm (the size of the update before clipping at max_grad_norm, default 1.0), and num_tokens. Watch the loss fall and the accuracy rise. If grad_norm spikes, lower the learning rate.
max_length at its default. What does the trainer do?Chapter 7
Watch one small slip push a copied agent into a place its training data never visited, and see why long runs make it worse
A new driver practises only on a straight, empty road, beside an instructor who never makes a mistake. Every lesson is recorded and she studies the recordings. On the test day a gust of wind pushes the car half a metre toward the verge. In all the recordings, the car was never near the verge. She has no memory of what to do.
That is the weak point of Step 1, in one picture. The post says it in two sentences: “The model only sees correct traces, never its own attempts. When it makes a mistake while solving a task, it has not learned how to recover from it.” This chapter shows why a small mistake becomes a big one.
At any moment, an agent is in a situation: the message list so far. The strong model that made your traces visited a particular set of situations, the ones that arise when you make no mistakes. Call that set the data’s territory. Inside it, your fine-tuned model has seen what a good next move looks like, thousands of times.
Now run the trained model on a fresh task. Mostly it follows the recordings. But it is not a perfect copy. Sometimes it writes a wrong argument. Sometimes a tool fails for a reason that has nothing to do with the model: a file is locked, a network call times out. Say a tool returns Error: no such file ‘cart.py’. In 5,000 clean traces, perhaps no trace ever showed a result like that. The agent is now outside the data’s territory. What it writes next is a guess, and the training never tried to improve that guess.
It gets worse. The guess from outside the territory often leads to a situation that is further outside. A wrong edit produces a stranger test result, which leads to a stranger next edit. Each step is less like the data than the last. Errors do not just add up. They snowball, because every new mistake makes the next input less familiar.
The usual name for the fix is to train on situations the model reaches by itself. Data produced by the model being trained is called on-policy data. Recall from Chapter 1 that the policy is the behavior. The post says on-policy distillation and RL “address this by training on the model’s own outputs.” Copying recordings is off-policy: the data comes from someone else.
Try the toy below. It is a model of the idea, not of a real agent. Each path is one run of 8 steps. The band is the territory of your data. Slips push a run sideways. Inside the band the agent knows how to step back. Outside it, it does not.
Left to right is the run, step 0 to step 8. The middle line is the stronger model’s path. The green band is how far off that path the training data ever went. Paths turn red where they leave the band.
Illustrative toy. Each step the agent slips with the chosen chance, one level to a random side. Inside the band it steps back one level per step. Past the band it has no example to follow: it holds still or drifts further with equal chance. A run counts as derailed when it first leaves the band. Coverage 0 matches the post’s SFT: traces that never leave the path. Nothing here is measured from a real model.
Set coverage to 0 and leave the slip rate at 10%. Any slip derails the run. A run of 8 steps with no slip has probability 0.9 × 0.9 × … eight times. Compute it in pieces: 0.92 = 0.81, 0.94 = 0.812 = 0.656, 0.98 = 0.6562 = 0.430. So only 43% of 8-step runs finish. Make the task 20 steps long and you get 0.920 = 0.12: only 12% finish. A longer task does not need a worse model. It needs only more chances to slip.
Now raise the coverage to 1. A slip of one level is no longer fatal, because the agent has seen how to step back. The picture changes at once. That is what extra kinds of training experience buy. Chapters 8 and 9 look at how much, and what the post proposes.
Symptom of drift in a real project: demos on short tasks look good, and long tasks fail more than a straight-line guess would suggest. Measurement: plot the finish rate against the number of steps in the task. A curve that falls like 0.9n says every step is an independent chance to fall off. Fix: the post’s later steps, where the model learns from its own runs.
Chapter 8
Measure how much a single retry is worth over a long task, and see how Steps 2 to 5 of the curriculum get it
Back to the hero at the top of this page. You dragged the failure rate and the copy-only agent collapsed while the other held up. The second agent was not smarter. It had one extra habit: when a tool call failed, it tried again. This chapter turns that into numbers, so you can say exactly how much recovery is worth.
Let a task need n tool calls in a row. Let each call fail with probability p, independently. (Real failures are not so tidy. We choose the simplest model that shows the effect.)
A copy-only agent has no habit for failure. One failed call ends the run. It finishes only if all n calls work. Each works with probability 1 − p. Independent chances multiply, so the finish rate is (1 − p)n.
An agent that retries r times fails a step only if the first try and all r retries fail. That has probability pr+1. A step therefore works with probability 1 − pr+1, and the finish rate is (1 − pr+1)n.
A worked example, at n = 10 and p = 0.2. Copy-only: 0.810. Square three times: 0.82 = 0.64, 0.84 = 0.4096, 0.88 = 0.168, and 0.168 × 0.64 = 0.107. So 11 runs in 100 finish. One retry: each step fails with 0.22 = 0.04, so it works with 0.96, and 0.9610 = 0.665. So 66 in 100 finish. Two retries: 0.23 = 0.008, 0.99210 = 0.923, so 92 in 100. Check it in the device.
Each curve is the share of runs that finish, for tasks of 1 to 20 calls. The dot marks the task length you pick. Choose how many retries the agent has and drag the failure rate.
Illustrative model: calls fail independently with the same chance, and a retry is a fresh independent try. Real failures are correlated (a missing file stays missing), so a blind retry is a weaker habit than this model grants. The formula is exact for the model; no number here is measured from a trained agent.
Two lessons come out. First, the gap grows with length: at p = 20% and n = 1 the three agents finish 80%, 96% and 99% of runs; at n = 20 they finish 1%, 44% and 85%. Second, a little recovery goes a long way: the first retry adds more than the second. That is why recovery is not a luxury for agents. It decides whether long tasks are possible at all.
Could you simply show the model recoveries? You could record a stronger model that hits an error and recovers. But those would be the stronger model’s slips, not yours. The slips a small model makes differ from the slips a large one makes. The post’s answer is different and deeper: train on the model’s own outputs. That is our reading of its sentence that on-policy distillation and RL “address this by training on the model’s own outputs.”
The post names what each later step learns from. Read them as four ways to put the model’s own attempts into the training loop.
| Step | Where the signal comes from | What the post says it costs or limits |
|---|---|---|
| 2. Distillation | A teacher supervises the student, through the data it writes or its probabilities on the student’s own tokens. One value per token. | The student is limited by what the teacher knows. On-policy distillation runs the teacher at every training step. |
| 3. RL | A reward scores the model’s own answer. The post names GRPO, which compares several answers to the same prompt. | One number for the whole answer, so the signal is weaker and the model needs many attempts. |
| 4. RL environments | The model acts several times in an environment and sees each result. | Episodes are longer, so generating rollouts becomes the slowest part. |
| 5. Harnesses and scale | Each rollout is a full run through a real agent harness in a sandbox. | Needs generation and training on separate GPUs so long episodes do not leave the trainer idle. |
If you want to go deeper, our on-policy distillation and knowledge distillation lessons cover Step 2, and GRPO and DAPO covers the algorithm of Step 3. Step 1, our subject, stays valuable because it is cheap and stable and needs nothing but a dataset.
One more trap sits here. Symptom: the log shows mean_token_accuracy of 0.98, yet runs fail. Measurement: a run has hundreds of tokens, and one wrong token in a tool call can break it. If a 300-token completion needed every token right, and each were right with probability 0.98, the whole would be right with 0.98300 = 0.002. That is a worst case, since most tokens are easy and forced. The point is the direction: a high per-token number does not give a high per-task number. Fix: measure what you care about, the finish rate of whole runs on tasks the model has not seen.
Chapter 9
Check that the traces you copy were written in the same setting where the agent will run, before a mismatch costs you a retraining
A cook learns every recipe in a kitchen where the salt is on the left and the stove has dials. She is moved to a kitchen where the salt is on the right and the stove has buttons. She knows the recipes. She still reaches left for salt and turns a dial that is not there. The skill was real. It was tied to the kitchen.
A fine-tuned agent has the same problem. Its traces were produced inside one scaffold: one set of tool names, one way of writing a call, one end-of-turn marker, one system prompt. Chapter 1 named those parts. If the agent later runs inside a different scaffold, its habits no longer fit.
The glossary has a sharp line about context engineering, the craft of deciding what goes into the model’s context window: system prompt, tool descriptions, conversation history, retrieved knowledge. It matters at both times, but “the cost of getting it wrong is very different.” At inference, it is “just text: change a prompt and redeploy.” At training, “what the model sees shapes what gets learned. Get it wrong and you’re retraining.”
So the scaffold in your dataset is not a detail. It is baked into the weights. The post states the principle in its fifth step: training through the same harness the agent uses in practice “means the model learns in the setting where it will run.” Step 1 gets there by a cheaper route. You record, or re-render, your traces in the deployment scaffold on purpose.
tool_calls and tool messages become text.The glossary also points readers to the Tool Schema Rendering Atlas, which shows “how tool schemas become prompt text across models, showing what each model actually sees after provider templates are applied.” The lesson: the model never sees your JSON. It sees the text a template renders from it. Check that text.
Below, a model trained on traces from one scaffold writes a tool call. A harness from a different setting tries to read it. Flip the ingredients between “same” and “different” and watch what the harness does.
The model writes the call the way its training traces did. Each switch makes one ingredient of the deployment harness differ from training. The harness reads the reply and gives a verdict.
Illustrative: the formats, the tool names and the end tokens are invented for this toy and are not any real harness. The order of the checks (format, then name, then end token) is a simplification; a real harness may fail in another order. A different system prompt does not stop the parse, but the model then works from instructions it never trained under, which is a quieter risk.
Worked example. Suppose 2,000 of your 5,000 traces call a tool named search and the deployment harness calls it grep. Then 2,000 ÷ 5,000 = 40% of the training examples teach the old name. The model will write search often, and the harness will answer “unknown tool.” Every one of those answers is a result the model has never seen in training. It lands in the territory of Chapter 7.
Symptom: in your own harness the fine-tuned agent says what it will do and nothing happens, or it invents tools. Measurement: replay 100 held-out tasks through the deployment harness and count the replies its parser can read. If 61 are readable, the parse rate is 61% and every miss is a stalled run. Fix: change the data, not the prompt. Re-render the traces in the deployment scaffold, then train.
Chapter 10
Review the numbers, the terms and the code, run the checklist on your own project, and see where to go next
You can now explain Step 1 of the Hugging Face curriculum from memory. An agent is a model plus a harness. A run of that agent leaves a trace. A trace becomes a dataset row. The trainer turns the row into labels, hides the tokens that are not the model’s words, and lowers the surprise of the rest. The result copies a good agent well and recovers from nothing it never saw.
Supervised fine-tuning on agent traces teaches a model to copy recordings of a stronger agent, with every tool call and its result. It is cheap and stable, and it needs only a dataset. TRL’s SFTTrainer applies the chat template, tokenizes, cuts at max_length, shifts the labels by one token, masks what you choose, and minimizes the average next-token loss. Because the model “only sees correct traces, never its own attempts,” it has not learned to recover, and the finish rate of long tasks falls like (1 − p)n. Steps 2 to 5 of the curriculum add the model’s own outputs to the training.
| What | Number | Why it matters |
|---|---|---|
| Curriculum | 5 steps after a step 0; Step 1 uses SFTTrainer | What the model learns from gets richer each step |
| TRL defaults (SFTConfig) | batch 8, 3.0 epochs, learning rate 2e-5, max_grad_norm 1.0, logging every 10 steps | Chat defaults, not agent defaults |
| Truncation default | max_length 1024, keep_start; a 1,800-token trace loses 776 tokens (43%) | The ending of a long run is cut |
| Adapter learning rate | about 1e-4 (docs) | Fewer new weights, so a higher rate |
| Steps for 5,000 traces | 5,000 ÷ 8 = 625 per epoch; 1,875 over 3 epochs | Step 1 is cheap |
| Five-token loss (made-up probabilities) | sum 4.085, average 0.817 | The logged loss is an average |
| Toy mask, 38 tokens | 0.59 (all), 0.70 (completion), 0.50 (assistant) | Compare losses under one mask only |
| Finish rate, n = 10, p = 0.2 | 11% no recovery; 66% one retry; 92% two retries | Recovery decides long tasks |
| Token accuracy vs task | 0.98300 ≈ 0.2% (worst case) | A token number is not a task number |
| Term | Meaning | Where |
|---|---|---|
| Agent | Model plus harness; acts over many turns | Ch 0, 1 |
| Scaffolding | System prompt, tool descriptions, parsing, memory across steps | Ch 1, 9 |
| Harness | The loop that calls the model, runs tools, decides when to stop | Ch 1, 2 |
| Trace / rollout | The saved messages of one full run | Ch 3 |
| Loss mask | Labels set to −100 so the loss skips them | Ch 5 |
| Policy | The behavior: a probability for each action in each situation | Ch 1, 7 |
| On-policy data | Data produced by the model being trained | Ch 7, 8 |
These two sketches are the whole of Chapters 2 and 6. The dataset path is a placeholder. Model, option names and defaults come from the TRL docs.
python# the harness (Ch 2): the loop that makes the agent run messages = [system, user] while True: reply = model(messages, tools=TOOLS) messages.append(reply) if not reply.tool_calls: break for call in reply.tool_calls: messages.append({"role": "tool", "name": call.name, "content": run_tool(call)}) # the trainer (Ch 6): copy the recordings from datasets import load_dataset from trl import SFTConfig, SFTTrainer from peft import LoraConfig # optional: adapters dataset = load_dataset("your-org/agent-traces", split="train") # rows: messages + tools trainer = SFTTrainer( model="Qwen/Qwen3-0.6B", train_dataset=dataset, peft_config=LoraConfig(), args=SFTConfig( output_dir="agent-sft", max_length=4096, # the default 1024 cuts the end of long runs (Ch 6) assistant_only_loss=True, # loss on the model's words only (Ch 5) learning_rate=1e-4, # adapters take a higher rate ), ) trainer.train()
Tick each line that is true of your project. The bar fills as you go, and the read-out names the first line still open.
The eight lines come from Chapters 3 to 9. They are a checklist of this lesson, not an official Hugging Face list.
This lesson re-teaches Step 1 of A curriculum for post-training agents by Ben Burtenshaw, Sergio Paniego and Merve (Hugging Face, 20 October 2026), with the vocabulary of Harness, Scaffold, and the AI Agent Terms Worth Getting Right by Sergio Paniego and Aritra Roy Gosthipaty (25 May 2026) and the mechanics of the TRL SFT Trainer docs (the SFT method was contributed to TRL by Younes Belkada). The post links the livestream Training Agents 1: fine-tune a coding agent and a model repository, burtenshaw/gemma4-pi-mono-youtube-livestream-1-scripts. All toy numbers here are labelled illustrative and are ours.
Now press Present or Teach and explain one fine-tuning run out loud, from memory: what an agent is, what is in a trace, which tokens the loss counts, what the trainer does with a row, and why a perfect copy still cannot recover. Then go back to the 24 runs at the top and drag the failure rate with the numbers in your head.