Courses / AI Engineering: LLMs, RAG and Agentic System Design / Chapter 12
Module 6 · Case studies: recommenders and reward design · Chapter 12 of 24
Case study: an agent that writes reward functions
Builds on AI agents and multi-agent systems and Agent design fundamentals. Next up: Building a reward-design agent.
Part 1 · Why rewards are hard
Reward, return and policy
Reinforcement learning trains a program by scoring its behaviour with a number, and writing that number well is slow expert work. This chapter studies a design that asks a language model to write the scoring rule and tests every proposal by training with it.
Four words carry the whole subject. The agent is the program being trained. The environment is the world it acts in, which here is a simulation. At each step the agent picks an action, the environment moves to a new state, and a reward (a single number) says how good that step was. The agent's policy is its rule for choosing an action in each state. Training adjusts the policy to raise the return, the sum of rewards over an episode.
The reward function is the only place where a person says what the agent should want. Everything else in the training loop is generic. That makes the reward the line with the most influence in the project, and also the easiest to get subtly wrong. The agent does not read your intent. It maximises the number you wrote, by whatever route the environment allows.
This is why a reward is usually built over many rounds: write a version, train, watch what the agent does, fix the version. The cycle is slow because each round needs a training run and a person's attention. The design in this chapter tries to automate the cycle. A model reads the environment's code, writes candidate rewards, a learner trains one policy per candidate, and the training statistics go back to the model as text so that it can write better candidates.
Reward hacking
A reward hack (also called specification gaming) is a behaviour that scores highly under the reward you wrote and fails the goal you meant. It is not a bug in the learner. The learner did exactly what it was asked. The reward was an imperfect stand-in for the goal, and the agent found the gap.
The smallest example is a corridor of six cells. The agent starts in cell 0 and the goal is cell 5. Each step moves one cell left or right, and the episode ends at the goal or after 20 steps. A designer who wants the agent to walk right might reason: give a point for passing the checkpoint in cell 2, because passing it means progress. Written as code, that is a reward of 1 whenever the agent enters cell 2 from another cell.
The corridor is deterministic and tiny, so the best possible behaviour under any reward can be computed exactly by dynamic programming: work backwards from the last step, and for each cell and time keep the best total reward reachable. No learner is involved, so the result is not a training accident. It is the true optimum of the reward as written.
CHECKPOINT = 2 def naive_reward(old, new, done): """+1 each time the agent enters the checkpoint cell.""" return 1.0 if new == CHECKPOINT and old != CHECKPOINT else 0.0 def potential(pos): return -(GOAL - pos) def fixed_reward(old, new, done): """Potential-based progress, a goal bonus and a step cost.""" progress = potential(new) - potential(old) return progress + (10.0 if done else 0.0) - 0.1
The two rewards. The fixed one is a difference of potentials.
The second reward is the repair. It pays for progress as the change in a potential, here minus the distance to the goal, so that moving right earns +1 and moving left costs 1. It adds 10 for reaching the goal and charges 0.1 per step. A reward built from a difference of potentials cannot be farmed by going back and forth, because the gains and losses cancel. This is potential-based shaping. Ng, Harada and Russell (ICML 1999, "Policy invariance under reward transformations") show that adding a reward of the form gamma times the potential of the new state minus the potential of the old one leaves the best policy unchanged, and that other kinds of added reward can change it. Here gamma is 1 and the episode is short, so the guarantee is only a guide; the dynamic program below checks the outcome directly. The goal bonus and step cost are separate terms we chose, not part of the shaping.
def best_return(reward): """Exact optimum over all action sequences (dynamic programming).""" # value[t][pos] = best total reward from pos with t steps used value = [[0.0] * N for _ in range(HORIZON + 1)] first_action = {} for t in range(HORIZON - 1, -1, -1): for pos in range(N - 1): best = None for a in (0, 1): new, done = step(pos, a) r = reward(pos, new, done) total = r + (0.0 if done else value[t + 1][new]) if best is None or total > best[0]: best = (total, a) value[t][pos] = best[0] first_action[(t, pos)] = best[1] # follow the best policy from the start pos, trail, total = 0, [0], 0.0 for t in range(HORIZON): a = first_action[(t, pos)] new, done = step(pos, a) total += reward(pos, new, done) pos = new trail.append(pos) if done: break return value[0][0], trail, pos == GOAL
Exact optimum over all action sequences.
What the optimum does
The script runs the dynamic program for both rewards and follows the best policy from cell 0.
naive: best return 10.0, reaches goal: False path: [0, 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1, 2] potential shaping + goal bonus: best return 14.5, reaches goal: True path: [0, 1, 2, 3, 4, 5]
Output from one run; yours will differ.
Under the checkpoint reward the best policy never reaches the goal. It walks to cell 2, steps back to cell 1, steps forward again, and repeats, collecting one point every two steps for ten points in all. Walking straight to the goal would earn one point, because the checkpoint is passed only once. The reward paid more for the loophole than for the task. Under the repaired reward the best policy is the straight walk, with a return of 14.5: five steps of +1, the goal bonus of 10 and five step costs of 0.1.
Three lessons follow. First, a reward can be wrong while looking sensible to its author. Second, a scoring rule you cannot test against the real goal is a guess, so a design that writes rewards automatically needs a separate ground-truth measure: success at the actual task, computed without the reward. Third, once a model is the author, the same gap opens faster, because it can write many plausible rewards quickly and none of them has been looked at by a person. The next lesson shows the loop that uses a ground-truth score to pick between them.
The checkpoint reward paid 10 for the best policy and the repaired reward paid 14.5. Why is that not a contradiction with the reward being repaired?
- The two numbers are returns under different rewards, so they cannot be compared.
- What matters is the behaviour: the first optimum never reaches the goal, the second does.
- A reward is judged by what the best policy under it does at the real task.
In the dynamic program, why does the best policy under the checkpoint reward oscillate between cells 1 and 2?
- Entering cell 2 from cell 1 pays 1 each time, and leaving it costs nothing.
- Over 20 steps, repeating that pair beats a single pass followed by a walk to the goal.
Part 2 · The design: search over reward code
Requirements
The system takes a task and an environment and returns a reward function that trains a good policy. Stated as requirements, the functional ones are short. It must read the environment's description and source. It must propose several candidate rewards. It must train a policy for each valid candidate. It must score each result with a ground-truth measure, keep the best, and feed what it learned back into the next round of proposals.
The non-functional requirements decide the design. Cost is first: every candidate needs a training run, so the number of runs must be bounded and known before the search starts. Safety is second: a candidate written by a model is untrusted input, and whatever form it takes must not be able to harm the machine running the search. Fairness of comparison is third: candidates must train with the same budget and be scored by the same measure, or the best one only looks best. Reproducibility is last: the seeds, budgets and chosen reward must be recorded so that a result can be audited.
The research system this chapter follows, Eureka, answers these in a particular way. Its paper reports a coding model that writes reward functions as program code for robot simulation tasks, with GPU-parallel training, across 29 environments and 10 robot morphologies. It reports better results than rewards written by human experts on 83 per cent of the tasks, with an average normalised improvement of 52 per cent. The paper also describes a variant that takes human feedback without any gradient updates. We keep the loop and change one choice, how a candidate is expressed, in the third lesson.
Entities and the loop
| Entity | What it holds | Relationship |
|---|---|---|
| Environment | Task text and source code the model may read | Given once to every round |
| Candidate | One proposed reward | Many per round; each is validated first |
| Training run | A policy trained with a fixed budget and seed | One or more per valid candidate |
| Statistics | Success, per-feature reward, other counters | Produced by a run; read by the model |
| Reflection | Statistics written as text for the next prompt | Built from the best candidate of a round |
Each round has four steps. Propose: the model reads the environment and, from the second round, the reflection from the last round, and writes a batch of candidates. Validate: code checks each candidate and turns invalid ones away before any training. Train and score: each valid candidate trains a policy with the same budget, and the policy is scored by ground truth. Reflect: the statistics of the best candidate become text for the next prompt.
The Eureka paper gives concrete numbers for its version of the loop. Each iteration samples 16 candidates, so that it is unlikely that all of them fail to run. Each candidate returns a total reward and a dictionary of its components. The best candidate of an iteration, together with its reflection, goes into the next iteration, and the whole search is repeated from scratch several times (five independent runs per environment) to avoid one unlucky start. The paper defines reward reflection as an automated text summary of the policy's training dynamics, built from the value of each reward component and the task score at checkpoints during training.
Reading the loop
The scene shows where each requirement is enforced. The validator is the safety and cost gate: a rejected candidate costs no training. The training step is where fairness lives, because every candidate gets the same budget. The statistics are the only channel back to the model, so what they contain decides what the model can learn.
This is an agent loop in the sense of the agents chapter, with a fixed order of steps rather than a model choosing tools. A step budget applies as it would to any loop: a cap on rounds and on training runs that stops the search when it is reached. The validator plays the role of the guard, a check in code that runs outside the model and decides whether a proposed action may proceed. Here the action is a training run.
Which requirement does the validator serve, and which does equal training budgets serve?
- The validator serves safety and cost, since a rejected candidate is never trained.
- Equal budgets serve fairness of comparison, so differences in score come from the reward.
Why does Eureka sample 16 candidates per iteration instead of one?
- Generated code may not run, so one sample could waste the whole iteration.
- With many independent samples it is unlikely that every candidate in the batch is broken.
What is the only channel by which training results reach the model?
- The reflection, a text summary of training statistics.
- The model sees no gradients or policies, so the choice of statistics shapes what it can fix.
Part 3 · Running generated rewards safely
What executing model code needs
The simplest way to use a reward written as program code is to run it. That means executing text a model produced, and a program that runs untrusted text can be made to do anything the process may do: read files, send data over the network, delete things, or run forever. The model need not be malicious. A prompt that includes text from an untrusted source, or a plain mistake, is enough to produce such code. The research paper's subject is reward quality, and this chapter does not claim how its authors isolated execution.
If you do run generated code, treat it as hostile and contain it. Run it in a separate process, not the one holding your keys and data. Give that process no network access, a read-only view of the files it needs, a memory limit and a wall-clock timeout that kills it. Pass data in and out as plain values, not live objects. Keep secrets out of its environment variables. Even then, the safest code is code that is never run.
Do not pass a model's reply to eval or exec in your own process. A reward that must be code belongs in a sandboxed process with the limits above: no network, no secrets, a memory limit and a timeout. This chapter avoids the problem instead of solving it, by never producing code to run.
There is a second, quieter risk that containment does not fix. A reward function can read any variable the environment exposes, including ones the agent could change to raise its own score. A candidate that scores itself highly by touching such a variable is a reward hack that no sandbox detects, because the code does nothing forbidden. Only the ground-truth measure, computed separately, catches it.
A smaller language
Our variant avoids the problem by making the candidate data rather than code. A candidate is a set of weights over a small, fixed list of named features that we implement ourselves. The reward is the weighted sum of the features on each step. The model chooses which features matter and how much, and it cannot write a new feature, so it cannot reach anything we did not offer.
The trade-off is expressiveness. A free-form reward can use any combination of state variables in any formula. A weighted sum of fixed features cannot, so a task whose good reward needs a feature we did not provide cannot be solved. For many tasks the designer can list the useful features in advance, and the search then tunes how much each counts. That is the narrower but safer problem we solve.
The check that goes with a data candidate is small. It must accept only known feature names and only weights that are numbers within a range, and it must say why it rejects something so that the reason can go back to the model. The corridor version is below. The next chapter builds the full one for a larger task.
FEATURES = {
"checkpoint": lambda old, new: 1.0 if new == CHECKPOINT
and old != CHECKPOINT else 0.0,
"progress": lambda old, new: float(potential(new) - potential(old)),
"goal": lambda old, new: 1.0 if new == GOAL else 0.0,
"step": lambda old, new: 1.0,
}
def check(spec):
"""Return weights or raise ValueError with a reason."""
for name, w in spec.items():
if name not in FEATURES:
raise ValueError(f"unknown feature {name!r}")
bad = isinstance(w, bool) or not isinstance(w, (int, float))
if bad or not abs(w) <= 20:
raise ValueError(f"bad weight for {name}: {w!r}")
return spec
def reward_from(spec):
spec = check(spec)
return lambda old, new: sum(w * FEATURES[n](old, new)
for n, w in spec.items())Known features and a validator. Model text is never executed.
The script computes the return of five steps right under a small weight set and then feeds four bad candidates to the checker. The last of them is a string that would be dangerous if executed. As data, it is just a name that is not on the list.
if __name__ == "__main__": from corridor import step r = reward_from({"progress": 1, "goal": 10, "step": -0.1}) pos, total = 0, 0.0 for _ in range(5): new, done = step(pos, 1) total += r(pos, new) pos = new print("five steps right earn", round(total, 2)) for bad in ({"speed": 1}, {"goal": 1000}, {"goal": "lots"}, {"__import__('os').getcwd()": 1}): try: reward_from(bad) except ValueError as e: print("rejected:", e)
The checks run on valid and on bad candidates.
What the lifecycle guarantees
The scene makes one rule visible: there is no path from proposed to trained that skips validation. In code that rule is a single function that is the only caller of the trainer, and the next chapter tests it directly. A rejected candidate is final. It is counted, its reason is recorded so that the model can be told, and it costs nothing else.
This is the same pattern as a permission tier from the agent design chapter: an action is allowed only after a check in code, and the check does not depend on the model agreeing. The difference is that the check here guards the cost and the safety of a training run, not a payment.
What is the difference between a reward written as code and one written as weights over named features?
- Code can express any formula but must be executed, so it needs isolation.
- Weights are data over features you implemented, so nothing from the model is ever executed.
In the corridor run, what happened to a candidate whose feature name was a string of Python?
- The validator rejected it as an unknown feature, because it is not in the list.
- Nothing in it was run, so it could do no harm.
Why can a sandbox not catch a reward that games the score by changing an environment variable?
- The code does nothing forbidden, so isolation sees no violation.
- Only a separate ground-truth success measure shows that the real task failed.
Part 4 · Compute and evaluation
Counting training runs
Compute decides whether a design like this can run at all. The number of training runs in a search is a product: candidates per iteration times iterations times independent restarts, plus the evaluation runs for the final answers. Each factor is a design choice, and each run costs simulation time, so the product, not any one factor, is what you pay.
The Eureka paper's numbers help to ground it. It samples 16 candidates per iteration for 5 iterations, repeats the whole search five times per environment, and evaluates each final reward with five training runs (the paper's section 3.2 and its policy-learning setup). The cost of one training run depends on the task and the hardware, so the calculator below takes it as an input. The figure of half an hour of GPU time per run is an example value for this lesson, not a measurement and not the paper's. The other inputs follow the paper's main setting.
def search_cost(candidates, iterations, restarts, eval_runs, hours_per_training): trainings = candidates * iterations * restarts final_evals = restarts * eval_runs total_runs = trainings + final_evals hours = round(total_runs * hours_per_training, 1) return {"search trainings": trainings, "final evaluations": final_evals, "total runs": total_runs, "gpu hours": hours}
The product of the design choices.
if __name__ == "__main__": # 16 candidates, 5 iterations, 5 restarts and 5 evaluation runs # follow the paper's main setting; 0.5 GPU hours per training is an # assumption for the example, not a measurement base = search_cost(16, 5, 5, 5, 0.5) print("example search:", base) for label, kw in (("half the candidates", dict(candidates=8)), ("3 restarts", dict(restarts=3)), ("shorter training (0.25 h)", dict(hours_per_training=0.25))): args = dict(candidates=16, iterations=5, restarts=5, eval_runs=5, hours_per_training=0.5) args.update(kw) print(f"{label}:", search_cost(**args))
Example inputs and three ways to cut the bill.
example search: {'search trainings': 400, 'final evaluations': 25,
'total runs': 425, 'gpu hours': 212.5}
half the candidates: {'search trainings': 200, 'final evaluations': 25,
'total runs': 225, 'gpu hours': 112.5}
3 restarts: {'search trainings': 240, 'final evaluations': 15, 'total
runs': 255, 'gpu hours': 127.5}
shorter training (0.25 h): {'search trainings': 400, 'final
evaluations': 25, 'total runs': 425, 'gpu hours': 106.2}Output from one run; yours will differ. Long lines are wrapped here.
Where the bill comes from
The output above shows what each lever does. Halving the candidates halves the search runs. Fewer restarts saves a fixed share. Shorter training saves the most per run but changes what is measured, because a reward may need a longer horizon to show its worth. In the scene the total is about 212 hours if the runs are done one after another. The paper's setting runs many simulated environments in parallel on a GPU, which is what makes each run short enough for the product to be affordable at all.
A search can also spend less by being selective. A screen is a cheap early test: train for a fraction of the budget and drop candidates that have not improved. A cache reuses the result for a candidate seen before. Both cut runs without changing the loop. The last lesson shows how much the first checks save on real proposals.
Measuring success
The score that picks the best candidate must come from the task, not from the candidate's own reward. In the paper, each candidate trains with its own reward, and the policy is then scored by the task's ground-truth fitness function. Comparing candidates by their own reward totals would be meaningless, since each has a different scale and a different set of mistakes.
For a task with a clear end state, the usual ground-truth measures are the success rate (the share of episodes that reach the goal), the steps taken, and counts of the failures you care about, such as hazards hit. These three belong in the statistics the model reads. A single number hides the difference between a policy that is slow and one that is unsafe. A success rate measured on a few episodes is itself uncertain, so a serious search scores every candidate over many start states and several seeds, as the next chapter does with 31 starts and 3 seeds, and does not trust a difference of a few per cent.
The human-feedback variant in the paper replaces the statistics with a person's judgement. The person watches behaviour from a candidate, says what is wrong in words, and the model rewrites the reward. It needs no gradient updates. In our terms it swaps the machine-computed reflection for a human-written one and leaves the loop unchanged. It trades compute for a person's attention, which is the right trade when the ground truth cannot be written as code, such as a motion that should look natural.
A search samples 16 candidates, runs 5 iterations and repeats 5 times, with 5 evaluation runs per restart. How many training runs in total?
- Search runs: 16 times 5 times 5 equals 400.
- Evaluation runs: 5 times 5 equals 25, so the total is 425, matching the calculator.
Why must candidates be compared by ground-truth success and not by their own reward totals?
- Each reward has its own scale and its own loopholes, so totals are not comparable.
- A hacked reward can have a very high total while the task fails.
What does the human-feedback variant change in the loop?
Part 5 · Design review and extensions
Cost controls, measured
A review of a design asks where it will fail and what it will cost. The first check here is cheap and uses real model output: how many of a round's proposals deserve a training run? The script asks the local model for 16 candidate rewards for the grid task that the next chapter builds, using the same prompt as the search, and then counts what the validator and a duplicate check remove before anything trains.
propose = model_proposer() valid, errors, seen = [], Counter(), set() dups = 0 for _ in range(16): raw = propose("Propose one reward.") try: w = validate(raw) except RewardError as e: errors[str(e).split(" (")[0]] += 1 continue if canonical(w) in seen: dups += 1 continue seen.add(canonical(w)) valid.append(w) print("proposals: 16") print("rejected by the validator:", sum(errors.values()), dict(errors)) print("duplicates of an earlier proposal:", dups) print("distinct valid rewards to train:", len(valid)) print("training runs without the checks:", 16 * len(SEEDS)) print("training runs with the checks: ", len(valid) * len(SEEDS))
Validate and de-duplicate 16 proposals before training.
proposals: 16 rejected by the validator: 14 {'weight for got_key out of range': 8, 'weight for reached_goal out of range': 1, 'weight for hit_hazard out of range': 5} duplicates of an earlier proposal: 1 distinct valid rewards to train: 1 training runs without the checks: 48 training runs with the checks: 3
Output from one run; yours will differ. Long lines are wrapped here.
Most proposals were turned away. The prompt stated that weights must lie between -20 and 20, and the model often wrote larger ones. This run removed 14 of 16 by range, one more as a repeat, and left one valid reward: 3 training runs instead of 48. Treat the exact counts as one run of one model. Earlier tries of the same script rejected 12 to 14 of the 16, and a later repeat rejected 13, left 3 distinct valid rewards and so needed 9 training runs instead of 48, so the direction was the same each time. A model's reading of a limit in a prompt is not a limit, and the validator is what enforces it.
Extensions and trade-offs
To move this design to real robots, three things change. Simulation is cheap and safe to fail in, so the first change is to keep all search in simulation and treat transfer to hardware as a separate, gated step with human review. The second is that rewards for real hardware must include safety terms (joint limits, force limits), and those should be constraints enforced outside the reward, not weights the search might trade away. The third is that the ground-truth score needs hardware-safe tests, which are far more expensive than simulated ones.
- Cost controls. Cap rounds, candidates and total runs before the search starts. Screen with a short budget. Cache results by the canonical form of a candidate.
- Safety. Keep candidates as data where the task allows it. If code is unavoidable, isolate it in a process with no network, limits on memory and time, and no secrets.
- Honest scoring. Compare candidates only by ground-truth measures computed apart from the reward, with the same seeds and budget for every one.
- Audit. Record every proposal, rejection reason, seed and score so that a chosen reward can be traced to the run that produced it.
There is also a design choice about the model's role. In this loop the model writes the candidate and a fixed procedure does everything else. The model never decides to run training or to stop. That makes the cost and safety properties checkable in code, and it matches the guidance from the agent design chapter that a workflow with fixed steps is the better design when the steps are known.
Questions to think through
These prompts are for working through on paper or with a colleague. There are no model answers here.
- The task changes from reaching a goal to moving smoothly. What ground-truth measure would you compute, and what would the reflection need to say?
- Training one candidate takes six hours. You can afford 40 runs in total. How do you split them between candidates per round and rounds, and what would you screen on?
- The model keeps proposing rewards that score high on its own totals and low on ground truth. Which part of the loop would you change first, and why?
What did the validator remove in the 16-proposal run, and why did the prompt's stated range not prevent it?
- It removed 14 for weights outside the range, plus 1 duplicate, leaving 1 valid reward.
- A range written in a prompt is a request, not a control, so the check in code is what enforces it.
Why keep safety limits such as joint force outside the reward weights?
- A weight can be traded off against other terms by the search, so a limit expressed as a weight can be given up.
- A constraint enforced outside the reward cannot be traded away.
Which three controls cap the cost of a search before it starts?
- A limit on rounds, a limit on candidates per round, and a limit on total training runs.
- Screening and caching reduce the cost further.
All chapters · Previous: Case study: a multi-agent conversational recommender