Part I · Foundations · Chapter 1

What is reinforcement learning?

Agent, environment, action, reward. How learning from reward differs from learning from labels.

~120 min

Nobody gave you a dataset of correct handlebar angles when you learned to ride a bicycle. You got on, wobbled, fell, and tried something slightly different. The only feedback was how it went: you stayed up for a few more meters, or you scraped your knee. Out of that thin, delayed, noisy signal, your brain built a skill.

Reinforcement learning (RL) is the study of learning from that kind of signal. A learner acts, the world responds, and a number says how well things are going. No one ever says what the right action was. This chapter sets out the vocabulary of the field, lets you drive a small world by hand and then watch a program learn to drive it, and names the three problems that make RL hard. The rest of the course builds on these ideas. By the end of it you will see the same loop running inside a chatbot: it writes an answer, the answer is scored, and the model is nudged toward answers that score well.

The agent–environment loop

Every RL problem has two parts. The agent is the learner and decision-maker. The environment is everything else: the part of the world the agent interacts with but does not control directly. They talk to each other in a loop of discrete time steps t=0,1,2,…t = 0, 1, 2, \dots:

                    action a_t
          ┌───────────────────────────────┐
          │                               ▼
     ┌─────────┐                   ┌──────────────┐
     │  agent  │                   │ environment  │
     └─────────┘                   └──────────────┘
          ▲                               │
          └───────────────────────────────┘
              reward r_t, next state s_{t+1}
  1. The agent observes the state sts_t: whatever information it gets about the current situation.
  2. It picks an action ata_t.
  3. The environment responds with a reward rtr_t, a single number saying how good that step was, and moves to a new state st+1s_{t+1}.
  4. Repeat.

The reward rtr_t is the one that arrives after action ata_t. (Sutton & Barto’s textbook calls it Rt+1R_{t+1}. Same thing, shifted index; see the notation page.) Many tasks come in episodes that end: a game is won or lost, a robot reaches its target, a chatbot finishes its reply. The sequence s0,a0,r0,s1,a1,r1,…s_0, a_0, r_0, s_1, a_1, r_1, \dots of one episode is a trajectory.

In code, the loop is this short:

s = env.reset()                      # start an episode
done = False
while not done:
    a = agent.act(s)                 # decide
    s_next, r, done = env.step(a)    # the world responds
    agent.learn(s, a, r, s_next)     # improve from the experience
    s = s_next

That is the whole interface. You will write this loop in this chapter’s lab (without the learn line: learning starts in Chapter 2). Every algorithm in the course, up to the ones that train reasoning models, is a choice of what goes inside act and learn.

Where to draw the line

The agent–environment boundary is a modeling choice, not a physical one. For a robot, the motors and even the robot’s own body are usually part of the environment. The agent is the decision-making software, and its “actions” are the voltages it sends. If you know thermodynamics, it is the same move as choosing what counts as the system and what counts as the surroundings. The rule of thumb is that anything the agent cannot change at will is environment. That includes the reward: the agent cannot just decide to be rewarded. The reward is computed outside its control, even when, as with an animal’s pleasure and pain, it is physically produced inside the body.

The same loop, everywhere

ProblemAgentState (what it sees)ActionsReward
Atari gamethe game-playing programthe last few screen framesjoystick moveschange in the game score
GoAlphaGothe board positionwhere to put a stone+1 for a win, −1 for a loss, only at the end
Thermostatthe controllerindoor and outdoor temperature, time of dayheating powerminus the discomfort minus the energy cost
Robot armthe control softwarejoint angles, velocities, a camera imagemotor torques+1 when the object is in the bin, minus effort
Recommenderthe recommendation systemthe user’s history and contextwhich item to showa click, or minutes watched
Fusion plasmaa neural controllermagnetic sensor readingsvoltages on the shaping coilshow close the plasma is to a target shape
Chatbotthe language modelthe conversation so farthe next token, or a whole replythumbs-up, a learned score, or “the answer was correct”

The plasma row is real: in 2022 DeepMind and EPFL reported a controller trained with RL in simulation that then shaped plasmas on the TCV tokamak (Degrave et al., Nature). The last row is where this course is heading.

Quick check A program plays chess against itself. In the loop above, what is the opponent?

A tiny world to think with

Abstract definitions only stick once you use them, so here is one small world that we will use for the rest of the chapter and its lab. It is a gridworld (Chapters 3, 4 and 5 use gridworlds too):

    col:  0 1 2 3 4 5 6
    row 0 . . . . . . .      the long way round
    row 1 . # # # # # .
    row 2 S . . . . . G      the bridge
    row 3 . P P P P P .      pits under the bridge
  • The agent starts on S. Each step it chooses up, down, left or right.
  • Landing on the goal G gives reward +1+1 and ends the episode. Landing in a pit P gives −1-1 and also ends it.
  • Every other move gives the step reward, which is 0 unless we change it. Walking into a wall # or off the edge leaves you where you are.
  • Optionally, the floor is slippery. With probability equal to the slip probability, your move is replaced by one of the two perpendicular moves, each equally likely. Press “right” on the bridge and you may slide down into a pit.

There are two sensible routes. The bridge reaches G in 6 moves, with pits right underneath. The long way round goes up, along the top row and down: 10 moves, and safe. Which one is better? It depends, and working out what it depends on is a good first lesson in RL.

Reward and return

The agent does not want a large reward now. It wants a large total over time. Choosing the bridge gives a reward of 0 for five steps, and only then +1+1. The thing to maximize is the return: the sum of future rewards, each one discounted by a factor γ∈[0,1]\gamma \in [0, 1] per step of delay:

Gt=rt+γrt+1+γ2rt+2+⋯=∑k=0T−t−1γkrt+k,G_t = r_t + \gamma r_{t+1} + \gamma^2 r_{t+2} + \cdots = \sum_{k=0}^{T-t-1} \gamma^k r_{t+k},

where TT is the length of the episode: it ends on arriving in state sTs_T, so the last reward is rT−1r_{T-1}. With γ=1\gamma = 1 this is the plain sum. With γ=0.9\gamma = 0.9 a reward that arrives 10 steps from now counts for 0.910≈0.350.9^{10} \approx 0.35 of its face value.

A worked example

Take γ=0.9\gamma = 0.9 and step reward 0, with no slipping. Walking the bridge, you collect r0=r1=r2=r3=r4=0r_0 = r_1 = r_2 = r_3 = r_4 = 0 and then r5=+1r_5 = +1:

tt012345
rtr_t00000+1
γt\gamma^t10.90.810.7290.65610.59049
γtrt\gamma^t r_t000000.59049

So the bridge’s return is G0=0.95≈0.590G_0 = 0.9^5 \approx 0.590. The long way round reaches G on its 10th move, so G0=0.99≈0.387G_0 = 0.9^9 \approx 0.387. With no risk involved, discounting makes the shorter route better, which is what we want.

Now make every ordinary move cost a little: step reward −0.04-0.04. The bridge pays −0.04-0.04 five times, then +1+1:

G0=−0.04 (1+0.9+0.81+0.729+0.6561)+0.59049=−0.164+0.590=0.427.G_0 = -0.04\,(1 + 0.9 + 0.81 + 0.729 + 0.6561) + 0.59049 = -0.164 + 0.590 = 0.427 .

The long way round pays −0.04-0.04 nine times, then +1+1: G0=−0.04⋅1−0.991−0.9+0.99=−0.245+0.387=0.142G_0 = -0.04 \cdot \frac{1 - 0.9^9}{1 - 0.9} + 0.9^9 = -0.245 + 0.387 = 0.142. A step penalty is a second, more explicit way of saying “hurry up”.

Why discount at all?

There are three reasons, and they are worth keeping apart.

  1. Preference for sooner. A reward now is often worth more than the same reward later: money earns interest, and a robot’s battery may run out.
  2. Uncertainty. If there is a probability 1−γ1 - \gamma at each step that the episode is cut short, then the expected undiscounted return equals the discounted return. Discounting is then just honest bookkeeping.
  3. Mathematics. In a task that never ends, the plain sum of rewards can be infinite. With γ<1\gamma < 1 and bounded rewards it cannot: if every ∣rt∣≤rmax\lvert r_t \rvert \le r_\text{max}, then ∣Gt∣≤rmax/(1−γ)\lvert G_t \rvert \le r_\text{max}/(1 - \gamma). A geometric series is the only tool needed.

The value of γ\gamma sets how far ahead the agent looks. With γ=0\gamma = 0 only the immediate reward counts (a completely myopic agent). As γ\gamma approaches 1, distant rewards count almost as much as near ones. Chapter 3 makes this precise as an effective horizon of about 1/(1−γ)1/(1-\gamma) steps (Markov decision processes).

One small identity is worth noticing now, because the next four chapters are built on it. Pull out the first term of the return:

Gt=rt+γ(rt+1+γrt+2+⋯ )=rt+γ Gt+1.G_t = r_t + \gamma \left( r_{t+1} + \gamma r_{t+2} + \cdots \right) = r_t + \gamma\, G_{t+1}.

The return from now is the reward now plus the discounted return from the next step. It is also the fastest way to compute returns: go backwards through the episode. In Chapter 3, taking expectations of this recursion gives the Bellman equation.

Quick check An episode gives rewards r₀ = 1, r₁ = 0, r₂ = 2 and then ends. With γ = 0.5, what is the return G₀?

Drive it yourself, then watch an agent learn

The demo below is the gridworld above. Start in You drive mode. Move with the arrow keys (click the grid first), the on-screen buttons, or by tapping a square next to the agent. Below the grid you will see each reward rtr_t as it arrives, the weight γt\gamma^t it gets, and your running return G0G_0. The “best possible” number is what a perfect player would get on average with the current settings. The demo computes it exactly by planning with full knowledge of the rules, the way Chapter 4 will teach you.

Interactive Gridworld: drive it, then let an agent learn it

Rewards so far, and the weight γt each one gets in the return:

What to try: (1) Walk the bridge and check that your return is 0.590, then take the long way round (0.387). (2) Set slip to 0.2 and walk the bridge a few times: you will fall about 4 times in 10. (3) Switch to 'Let an agent learn', press Play, and set speed to 'fast'. Watch the arrows and the curve. Then press Reset agent a few times and compare runs. (4) Set slip to 0.2 and watch which route the agent settles on. (5) Tick the bonus tile and see what the agent does with it.

What you should have noticed

Randomness changes the right answer. With a dry floor, the bridge is clearly better (0.590 against 0.387). With slip 0.2, each of the five moves along the bridge drops you into a pit with probability 0.1, so you survive the crossing with probability only 0.95≈0.590.9^5 \approx 0.59. The long way round now wins. The map has not changed, only the dynamics. Exercise 1.5 finds the crossover by hand, and the lab finds it by simulation.

The agent knows nothing at first. In Let an agent learn mode, the agent starts with no idea what the colored squares mean. It sees only which square it is on, and the rewards. It runs an algorithm called Q-learning, which you will build yourself in Chapter 5. For now, treat it as a black box that keeps a table of estimates of how good each move is in each square, and nudges those estimates after every step. When “show what the agent has learned” is ticked, the arrows are its current choice in each square and the colors are its estimates of the return from there. With slip 0 and γ=0.9\gamma = 0.9, once it has learned to use the bridge you can read the numbers off the grid: 0.59 on S, 0.66 on the next square, then 0.73, 0.81, 0.90 and 1.00 next to G. Those are 0.95,0.94,…,0.900.9^5, 0.9^4, \dots, 0.9^0: the returns from each square of the bridge.

The curve flattens below the line. The learning curve shows the return of each episode. Even after learning, the average stays below “best possible”, because the agent still picks a random move a fraction ε of the time (10% by default) so that it keeps trying things. On the bridge a random move can be fatal. Slide ε to 0 after it has learned and the curve climbs to the line.

Sometimes it gets stuck on the long way round. Reset the agent a few times with slip 0. In most runs it finds the bridge within a few dozen episodes. In some runs it settles on the long route and stays there for thousands of episodes: the arrow on S points up, and with ε set to 0 its return sits at 0.387 instead of 0.590. It found something that works, and finding out that the bridge is better would mean walking the bridge, which its current choices never do. That is the exploration problem, which we come back to below. Tick optimistic start and the problem goes away. Exercise 1.6 asks you why.

Policy, value and model: the rest of the vocabulary

You have now met four of the core words (agent, environment, state, action) and two more (reward, return). Three more complete the vocabulary of the whole field. Here they are, lightly; later chapters make each one precise.

Policy: how the agent behaves

A policy is the agent’s rule for choosing actions: a mapping from states to actions. It can be deterministic (“on the bridge, go right”) or stochastic, giving a probability for each action. We write π(a∣s)\pi(a \mid s) for the probability that policy π\pi chooses action aa in state ss. The lab has two hand-written deterministic policies, bridge and safe, and a stochastic one, random, which gives each of the four actions probability 1/41/4 in every state. The goal of RL, in one line, is to find a policy that gets as much return as possible, on average.

Note that a policy must say what to do in every state, not just along its favorite path. On a slippery floor you can end up anywhere.

Value: how good it is to be here

The return of a single episode is random: on a slippery floor the same policy sometimes reaches G and sometimes falls. What we care about is its average. The value of a state ss under a policy π\pi is the expected return if you start in ss and follow π\pi from then on:

Vπ(s)=Eπ[ Gt∣st=s ].V^\pi(s) = \mathbb{E}_\pi\left[\, G_t \mid s_t = s \,\right].

Some numbers, all at γ=0.9\gamma = 0.9 from the start square:

slip 0slip 0.2
bridge policy0.590−0.027
safe policy0.3870.264
random policy−0.442−0.442
best possible0.5900.279

The “best possible” value at slip 0.2 is a little higher than the safe policy’s. The optimal policy knows a trick or two that the safe one does not (Exercise 1.4 asks you to find them). The random policy’s value does not depend on the slip at all. Can you see why? (A uniformly random action, sent through a slippery floor, is still uniformly random.)

A close cousin, the action value Qπ(s,a)Q^\pi(s, a), is the expected return if you take action aa in ss first and follow π\pi afterwards. The colored squares and arrows in the demo show the agent’s estimates of action values: the color is its largest estimated QQ in that square and the arrow is the action with that value. (To be exact, Q-learning estimates the action values of the best policy, not of the policy it is currently following. Chapter 5 explains why.) Chapter 3 defines value functions properly and shows how to compute them. In the lab you will estimate Vπ(S)V^\pi(\text{S}) the direct way, by averaging the returns of many episodes. That is called a Monte Carlo estimate, and Chapter 5 builds on it.

Value is the long-term counterpart of reward. Reward says how good this step was. Value says how good this situation is, counting everything that is likely to follow. A move with zero reward can lead to a state of high value (the square next to G), and vice versa.

Model: the agent’s own picture of the world

A model is the agent’s internal prediction of how the environment behaves: given ss and aa, what s′s' and rr come next. If you have a model, you can plan, trying out action sequences in your head before acting. The “best possible” number in the demo comes from planning with a perfect model (the demo knows the rules). Methods that learn or use a model are model-based. Methods that learn values or policies directly from experience, like the Q-learning agent in the demo, are model-free. Chapter 4 plans with a known model (Dynamic programming). Chapter 10 shows how AlphaZero and MuZero combine learned models with search (The wider RL landscape).

What makes RL different from other machine learning

You likely know supervised learning: fit a function to labeled examples, such as images with the correct class or sentences with their translations. And unsupervised learning: find structure (clusters, low-dimensional manifolds, a density) in unlabeled data. RL is neither, and the differences explain most of what makes it hard.

1. Evaluative feedback, not instructive feedback

A label is instructive: it says what the right answer was. A reward is evaluative: it says how good your answer was, and nothing about what you should have done instead. Compare two ways of marking an exam. In one you get back the correct answers. In the other you get back only “62%”. From the second you learn something, but you have to work out what by trying different answers and seeing how the score moves. That trial and error is built into RL. If the agent never tries an action, it never learns what that action would have earned.

2. Delayed consequences

In supervised learning, every prediction is judged on the spot. In RL, an action’s consequences can unfold over many steps. Stepping onto the bridge earns 0 right away. Whether it was a good idea is decided five steps later, by a +1+1 or a −1-1. A chess move might win or lose the game forty moves later. The agent must trade immediate reward against future reward, and it has to work out which earlier actions deserve the credit.

3. Your actions change your data

Supervised learning assumes the training examples are drawn independently from a fixed distribution. In RL, the agent’s own behavior decides which data it sees. An agent that always takes the long way round collects experience about the top row and almost none about the bridge. It then has nothing to update its beliefs about the bridge with. You saw exactly this in the demo, when an agent got stuck on the long route. The data are not independent (each state depends on the previous one), and their distribution shifts every time the policy changes. The objective and the data distribution are tied together, and that causes problems all the way up to LLM training. As Chapter 9 explains, one bad update produces a bad policy, which collects bad data, which makes the next update worse.

SupervisedUnsupervisedReinforcement
Feedbackcorrect answer for each inputnonea scalar reward for what you did
Whenimmediately, per example–possibly much later
Datafixed dataset, i.i.d.fixed dataset, i.i.d.generated by the learner’s own actions
Goalpredict labelsdescribe structuremaximize expected return

Quick check Which of these is a problem RL faces that ordinary supervised learning on a fixed dataset does not?

Three problems that make RL hard

Credit assignment

An episode ends with +1+1 or −1-1. Which of the many actions before it deserve the credit or the blame? That is the credit assignment problem. In the gridworld it is mild: episodes are short and the reward is clear. In Go, one bit of feedback (won or lost) arrives after about 200 moves, and the decisive mistake may have been move 37. For a reasoning model, one reward (was the final answer correct?) arrives after thousands of tokens of working.

RL’s main answer is the value function. If you can estimate how good every intermediate situation is, you can judge each action by whether it made things better or worse, without waiting for the end. Chapter 8 makes this precise as the advantage (Actor-critic and advantage estimation).

Exploration versus exploitation

To get reward, the agent should exploit what it already knows works. To find something better, it must explore: try actions whose value it is unsure of, and accept that some will turn out worse. You cannot do both with the same action. Picture choosing a restaurant: the favorite you know, or the new place that might be better or might be awful.

The stuck agent in the demo is a case of too little exploration. On S its arrow points up, and on the first bridge square its arrow points back to S, because retreating to the route it knows is the best thing it has seen. Its random moves (10% of the time) rarely carry it past both of those squares, so it seldom gets far enough along the bridge to learn that the bridge is better. Optimistic start fixes this in an instructive way. The agent begins by assuming every untried move is worth +1+1, so it keeps trying moves until experience talks it out of them. Chapter 2 studies exploration in its purest form (Bandits), including why optimism works and how to explore with provable guarantees.

Generalization

Our gridworld has 23 squares you can stand on, so the agent can keep a separate estimate for each. Real problems are not like that. Go has about 1017010^{170} legal positions. An Atari screen is 210×160210 \times 160 pixels. A language model’s “state” is any possible text prefix, which is astronomically many. The agent will almost never see the same state twice, so it must generalize: use what it learned in states it has seen to act well in states it has not. That is why neural networks entered RL, and why the combination is powerful but unstable (Chapter 6). Pretrained language models are an extreme case. They arrive with an enormous amount of general knowledge, which is a large part of why RL on top of them works at all.

Quick check A model writes a 2,000-token proof and gets reward 1 because the final answer is right. A few of the tokens were clever key steps, many were routine, and one was a harmless mistake. Which challenge is this?

The reward hypothesis, and how rewards go wrong

Everything above treats a single number per step as enough to say what we want. That is a strong claim, and it has a name. Sutton and Barto state the reward hypothesis like this (Reinforcement Learning: An Introduction, section 3.2):

That all of what we mean by goals and purposes can be well thought of as the maximization of the expected value of the cumulative sum of a received scalar signal (called reward).

It is a working hypothesis, not a theorem, and it can fail. Some goals are about risk, not averages: “never crash” is not the same as “crash rarely on average”. Some trade off several objectives in ways no fixed weighting captures. Bowling, Martin, Abel and Dabney (2023) worked out exactly which conditions a set of preferences over behaviors must satisfy to be expressible as expected cumulative reward. The hypothesis is still productive: a single scalar interface lets one algorithm handle Atari, robots and chatbots. But it puts all the weight on getting the reward right. That is much harder than it sounds.

Specification gaming

An RL agent optimizes the reward you wrote, not the goal you meant. When the two differ, a good optimizer finds the difference. In a well-known example from 2016, OpenAI trained an agent on the boat-racing game CoastRunners. The intended goal was to win the race, but the reward was the game’s score, which comes from hitting targets along the course. The agent found a lagoon where a few targets kept reappearing. It kept circling, catching fire and crashing into other boats, and never finished the race, yet scored higher than by racing. DeepMind researchers keep a public list of such cases. In one, an agent rewarded for the height of the bottom face of a red Lego block flipped the block over instead of stacking it on the blue one (Krakovna et al., 2020). The name for this behavior is specification gaming, or reward hacking.

You can produce both kinds of failure in the demo:

  • The “helpful” bonus tile. Suppose you want to encourage the agent to explore the top row, so you put a +0.3+0.3 bonus there. Tick it and let the agent learn. It walks to the coin and steps on and off it until time runs out. Why finish for +1+1 when looping is worth more? With γ=0.9\gamma = 0.9, looping is worth 0.3 γ4(1+γ2+γ4+… )=0.3⋅0.94/(1−0.81)≈1.040.3\,\gamma^4 (1 + \gamma^2 + \gamma^4 + \dots) = 0.3 \cdot 0.9^4/(1 - 0.81) \approx 1.04 from the start, against 0.590 for the bridge. Exercise 1.8 works through this.
  • A positive step reward. Set the step reward to +0.2+0.2. “Reward the agent for staying alive” sounds harmless. The agent’s answer is never to reach the goal at all. Exercise 1.7 shows that with γ<1\gamma < 1 the agent prefers to finish exactly when the step reward is below 1−γ1 - \gamma, however far away the goal is.

Neither agent is broken. Both are doing exactly what they were told. The bug is in the reward.

A short, honest history

RL draws on three older threads: the psychology of trial-and-error learning (Thorndike’s “law of effect”, 1911), optimal control, and the computer science of search and planning. Some milestones:

  • 1950s: Bellman and dynamic programming. Richard Bellman formulated sequential decision problems with the recursive structure you saw in Gt=rt+γGt+1G_t = r_t + \gamma G_{t+1}, and solved them by dynamic programming (his 1957 book Dynamic Programming). This is Chapter 4’s material.
  • 1959: Samuel’s checkers player. Arthur Samuel’s program improved by playing against itself and adjusting its evaluation of board positions toward later, better-informed evaluations. That idea later became temporal-difference learning.
  • 1988–1989: TD learning and Q-learning. Sutton formalized learning from temporal differences (1988), and Watkins introduced Q-learning in his 1989 PhD thesis. Q-learning is the algorithm running in the demo (Chapter 5).
  • 1992–1995: TD-Gammon. Gerald Tesauro trained a neural network by TD learning and self-play to play backgammon close to the level of the best human players. It was a striking early success, and for years a hard one to repeat in other games.
  • 2013–2015: DQN. DeepMind’s deep Q-network learned to play Atari games from raw pixels. The 2015 Nature paper reports one network architecture and one set of hyperparameters reaching a level comparable to a professional human games tester across 49 games. This started the modern era of deep RL (Chapter 6).
  • 2016: AlphaGo. AlphaGo defeated Lee Sedol 4–1 at Go, a game long considered beyond reach. It combined supervised learning on human games, RL from self-play and tree search. AlphaGo Zero (2017) and AlphaZero (2018) then dropped the human games entirely (Chapter 10).
  • 2017: Learning rewards from human preferences. Christiano and colleagues trained agents from human comparisons between pairs of behavior clips instead of a hand-written reward. This is the ancestor of RLHF (Chapter 12).
  • 2022: InstructGPT and ChatGPT. OpenAI fine-tuned GPT-3 with RL from human feedback (RLHF): a reward model trained on human rankings of responses, then optimization with PPO. Labelers preferred the outputs of a 1.3B-parameter InstructGPT model to those of the 175B-parameter GPT-3 (Ouyang et al., 2022). OpenAI said ChatGPT, released later that year, was trained with the same methods, with small differences in how the data was collected.
  • 2024–2025: Reasoning models. OpenAI’s o1 (September 2024) was trained with large-scale RL to produce a long chain of thought before answering. OpenAI reports that performance kept improving both with more RL training and with more thinking time at inference. In January 2025 DeepSeek published R1, with an open description of the recipe: RL with automatically checkable rewards on math and code problems. One variant, R1-Zero, was trained by RL directly from a base model with no supervised fine-tuning (Chapter 15).

The honest version of this story has long quiet stretches. For decades RL worked mostly on small or simulated problems. Many headline successes needed a perfect simulator, enormous amounts of experience or compute, and careful engineering, and many results were fragile to reproduce. RL for language models works as well as it does largely because pretraining supplies a policy that is already very good, so RL only has to steer it. Keep both halves in mind: RL is powerful, and it is finicky.

Summary

  • RL is learning to act from evaluative feedback. An agent takes actions in an environment, which returns rewards and new states. The whole interface is reset() and step(a).
  • The agent’s objective is the return, the discounted sum of future rewards: Gt=∑kγkrt+k=rt+γGt+1G_t = \sum_k \gamma^k r_{t+k} = r_t + \gamma G_{t+1}. The discount γ\gamma sets how far ahead it looks.
  • A policy π(a∣s)\pi(a \mid s) says how to act. A value Vπ(s)V^\pi(s) is the expected return from a state when following π\pi. A model predicts what the environment will do. The goal of RL is a policy with maximal expected return.
  • RL differs from supervised learning in three ways. Feedback says how good your action was, not what the right one was. Consequences can be delayed. The learner’s own actions decide what data it sees.
  • The three core challenges are credit assignment (which actions earned the reward), exploration versus exploitation (try new things or use what works), and generalization (act well in states never seen before).
  • What the best behavior is depends on the dynamics and on γ\gamma, not just the map. In the gridworld the bridge wins on a dry floor and loses once the slip probability passes about 0.07.
  • The reward hypothesis says a scalar reward can express any goal. In practice, the agent optimizes the reward you wrote, and specification gaming is what happens when that differs from what you meant. This is a central problem for RL on language models.

Exercises

Exercise 1.1Name the partsConcept●○○

For each scenario, identify the agent, the environment, the state, the actions and the reward. Then say in one sentence what is tricky about the reward.

  1. A thermostat controlling a home’s heating.
  2. A program that learns chess by playing against itself.
  3. A music app choosing the next song to play.
  4. A robot vacuum cleaner.
  5. A chatbot whose replies users can rate with thumbs up or down.
Solution
  1. Thermostat. Agent: the controller. Environment: the house, the heater, the weather and the occupants. State: indoor and outdoor temperature, time of day, maybe whether anyone is home. Actions: heating power (or on/off). Reward: minus discomfort (distance from the target temperature while people are home) minus energy cost. Tricky: the two terms trade off, and the weighting between them is a value judgement that someone has to choose.
  2. Chess by self-play. Agent: the learning player. Environment: the rules of chess and the opponent, even though the opponent is a copy of the agent. State: the board position (plus whose move it is, castling rights and so on). Actions: legal moves. Reward: +1 for a win, −1 for a loss, 0 for a draw, only at the end. Tricky: extreme delay. One bit of feedback for a whole game is the credit assignment problem in its purest form.
  3. Music app. Agent: the recommender. Environment: the listener (and the catalogue). State: listening history, time of day, the current session. Actions: which song to play next. Reward: e.g. +1 if the song is played to the end, −1 if skipped. Tricky: the easy-to-measure proxy (no skips) is not the same as the goal (a listener who enjoys the service over months). Optimizing short-term engagement can hurt long-term satisfaction.
  4. Robot vacuum. Agent: the control software. Environment: the room, the furniture, the dirt, and the robot’s own body and motors. State: sensor readings (bumpers, cliff sensors, camera, battery level), maybe a map. Actions: motor commands, suction on/off, return to dock. Reward: e.g. dirt collected, minus energy, minus collisions. Tricky: “dirt collected” can be gamed (dump the dirt and collect it again), and “no visible dirt” can be gamed by not looking.
  5. Chatbot. Agent: the language model. Environment: the user, the chat interface and whatever turns ratings into rewards. State: the conversation so far plus the tokens of the reply written so far. Actions: the next token. (Or, at a coarser level, the whole reply. Chapter 11 discusses both views.) Reward: +1 for thumbs up, −1 for thumbs down, at the end of a reply. Tricky: most replies get no rating at all. Ratings are noisy and say more about how the reply felt than whether it was correct. Users may also reward flattery or agreement, which teaches the model to be sycophantic (Chapter 19).
Exercise 1.2Returns by handPen & paper●○○

An episode gives the rewards r0=−1r_0 = -1, r1=−1r_1 = -1, r2=−1r_2 = -1, r3=+10r_3 = +10, and then ends.

  1. Compute G0G_0 for γ=1\gamma = 1, 0.90.9, 0.50.5 and 00.
  2. For γ=0.9\gamma = 0.9, compute G3,G2,G1,G0G_3, G_2, G_1, G_0 using the backward recursion Gt=rt+γGt+1G_t = r_t + \gamma G_{t+1}. Check that you get the same G0G_0.
  3. A different, never-ending task pays +1+1 at every step. What is G0G_0 for γ=0.9\gamma = 0.9? For γ=0.99\gamma = 0.99?
Solution
  1. G0=−1−γ−γ2+10γ3G_0 = -1 - \gamma - \gamma^2 + 10\gamma^3.

    • γ=1\gamma = 1: −3+10=7-3 + 10 = 7.
    • γ=0.9\gamma = 0.9: −1−0.9−0.81+10⋅0.729=−2.71+7.29=4.58-1 - 0.9 - 0.81 + 10 \cdot 0.729 = -2.71 + 7.29 = 4.58.
    • γ=0.5\gamma = 0.5: −1−0.5−0.25+10⋅0.125=−1.75+1.25=−0.5-1 - 0.5 - 0.25 + 10 \cdot 0.125 = -1.75 + 1.25 = -0.5.
    • γ=0\gamma = 0: only the first reward counts, G0=−1G_0 = -1.

    A myopic agent (γ\gamma small) sees this episode as bad, because the big reward is too far away. A far-sighted one sees it as good. The same experience is worth different amounts to agents with different γ\gamma.

  2. Backward with γ=0.9\gamma = 0.9: G3=10G_3 = 10. G2=−1+0.9⋅10=8G_2 = -1 + 0.9 \cdot 10 = 8. G1=−1+0.9⋅8=6.2G_1 = -1 + 0.9 \cdot 8 = 6.2. G0=−1+0.9⋅6.2=4.58G_0 = -1 + 0.9 \cdot 6.2 = 4.58. Same answer. Each step backward is one multiply and one add, with no powers of γ\gamma needed.

  3. A geometric series: G0=∑k=0∞γk=11−γG_0 = \sum_{k=0}^{\infty} \gamma^k = \frac{1}{1-\gamma}. That is 1010 for γ=0.9\gamma = 0.9 and 100100 for γ=0.99\gamma = 0.99. As a rule of thumb, an agent with discount γ\gamma “sees” about 1/(1−γ)1/(1-\gamma) steps ahead (Chapter 3).

Exercise 1.3Supervised, unsupervised, or RL?Concept●○○

Which kind of learning fits each problem best? Some are genuinely borderline; say why.

  1. Predicting house prices from a dataset of past sales.
  2. Grouping a shop’s customers into segments, with no labels.
  3. Adjusting a patient’s drug dose week by week based on how they respond.
  4. Learning to translate French into English from a large set of human translations.
  5. Training a model to write proofs that an automatic proof checker accepts.
  6. Choosing which of 10 ad designs to show each visitor to maximize clicks.
Solution
  1. Supervised. Each example comes with its correct answer (the sale price), the data are fixed, and our predictions don’t change the data.
  2. Unsupervised. No labels and no notion of a good or bad action. We want structure.
  3. RL. Sequential decisions with delayed effects: today’s dose changes next week’s state. The feedback is evaluative (how the patient is doing), not “the correct dose was 20 mg”. Our choices also decide which outcomes we ever observe. In practice you cannot experiment freely on patients, so this would be studied with offline RL from historical records (Chapter 10), and very carefully.
  4. Supervised. Human translations are labels. (Modern systems may add RL on top, to optimize a quality score, which is the LLM story of Part III.)
  5. RL, most naturally. The checker gives evaluative feedback (accepted or not), there are many valid proofs and no single label, and the model has to explore to find any proof at all. If you had a large set of human-written proofs you could also do supervised learning on them; many real systems do both, first supervised then RL. This mirrors the SFT-then-RL pipeline of Chapters 11 and 15.
  6. RL, of the simplest kind: a bandit (Chapter 2). There is one decision per visitor and no long-term state, but the feedback is still evaluative (you only see clicks on the ad you showed) and you must explore to learn which ad is best.
Exercise 1.4A slippery floorExplore the demo●●○

Use the demo.

  1. In You drive mode, set slip to 0.2 and walk the bridge ten times: keep pressing → until you reach G or fall in. (If a slip knocks you up or down off S, step back onto S first; that doesn’t count as a fall.) How often did you fall? What does the simple calculation “five risky moves, each with fall probability 0.1” predict?
  2. Switch to Let an agent learn, keep slip at 0.2, tick “show what the agent has learned”, and let it run at speed “very fast” for a few thousand episodes (watch the episode counter under the grid). Which route does it take from S?
  3. Look at the arrows on the bridge. On the squares nearest S, they usually point up, into the wall. Pressing up on the bridge does nothing 80% of the time. Why might that be a good idea? (Hint: when you press up, which way can you slip?) Also look at the square below S, at row 3, column 0.
  4. Why is the agent’s average return (blue line) well below “best possible”, even after it has learned?
Hint
For question 3: the perpendicular directions to “up” are left and right. For the square below S, compare the perpendicular directions of “up” and “left”.
Solution
  1. Each move along the bridge slips with probability 0.2, and half of those slips go down, into a pit: 0.1 per move. Five such moves survive with probability 0.95≈0.590.9^5 \approx 0.59, so you should fall about 4 times in 10. (Your 10 trials will scatter around this; a 95% range is roughly 1 to 7 falls.) The first move off S can also slip, but up or down from S there is no pit.
  2. It settles on the long way round: up from S, along the top row, down the right-hand column. (Exercise 1.5 shows the bridge stops being worth it above a slip of about 0.07.)
  3. If you press up on the bridge, you can only slip left or right, along the bridge. You can never fall. Pressing up is a safe way to “wait”: 80% of the time you bump the wall and stay put, 10% you drift left, 10% you drift right. Near S, drifting left gets you back to S, and from there onto the safe route. So if a slip has stranded you on the bridge, pressing up is a safe way back. (On the squares near G the arrows usually point right, because the goal is close enough to be worth the risk.) Below S, at (3,0)(3, 0), pressing up risks slipping right into a pit. Pressing left bumps the edge, and its slips go up (back to S, good) or down (off the grid, stay). The agent learns to press left there. Nobody told it any of this. It discovered “bump into the wall on purpose” from rewards alone. This is the bright side of the creativity that becomes specification gaming when the reward is wrong. These tricks are also why “best possible” (0.279) is a bit higher than the hand-written safe policy (0.264).
  4. The agent still explores: with probability ε = 0.1 it takes a random action, and on a slippery floor next to pits that sometimes costs a lot. “Best possible” assumes perfect behavior with no exploring. A smaller part of the gap is noise: on a slippery floor the agent’s estimates are averages of noisy samples, so they keep jittering.
Exercise 1.5Bridge or the long way round?Pen & paper●●○

Take γ=0.9\gamma = 0.9, step reward 0 and slip probability pp. Use this simplified model of the two routes:

  • Bridge: five risky moves. On each, you fall into a pit with probability p/2p/2; otherwise you move right. If you survive all five, you reach G at the 6th move (+1+1 at t=5t = 5). For simplicity, pretend that a fall also delivers its −1-1 at t=5t = 5.
  • Long way round: no risk; reach G at the 10th move (+1+1 at t=9t = 9). Ignore slips that only waste time.
  1. Write the expected return of each route as a function of pp.
  2. Find the slip probability p∗p^* at which they are equal.
  3. Repeat for γ=0.99\gamma = 0.99. How does a more patient agent feel about the risky shortcut?
  4. In the real gridworld at γ=0.9\gamma = 0.9, the lab’s two hand-written policies (bridge and safe) have equal expected return at p∗≈0.068p^* \approx 0.068. (This is computed exactly by solving the Bellman equations of Chapter 3, and the lab finds it by simulation.) Which simplifications push the true answer below yours?
Hint
Call the probability of surviving all five risky moves qq; it is a product of five equal factors. Under this model the bridge’s only nonzero reward, +1+1 or −1-1, always arrives at t=5t = 5, so its expected return is γ5\gamma^5 times the expected value of that one reward.
Solution
  1. Let q=(1−p/2)5q = (1 - p/2)^5 be the probability of crossing safely. Under the model all of the bridge’s reward arrives at t=5t = 5, so

    E[G0bridge]=γ5(q−(1−q))=γ5(2q−1),E[G0long]=γ9.\mathbb{E}[G_0^\text{bridge}] = \gamma^5 \big( q - (1 - q) \big) = \gamma^5 (2q - 1), \qquad \mathbb{E}[G_0^\text{long}] = \gamma^9 .
  2. Set them equal: γ5(2q−1)=γ9\gamma^5 (2q - 1) = \gamma^9, so 2q−1=γ42q - 1 = \gamma^4 and

    q∗=1+γ42=1+0.65612=0.82805.q^* = \frac{1 + \gamma^4}{2} = \frac{1 + 0.6561}{2} = 0.82805 .

    Then 1−p∗/2=(q∗)1/51 - p^*/2 = (q^*)^{1/5}. Take logs: ln⁡0.82805=−0.18868\ln 0.82805 = -0.18868; divide by 5: −0.037736-0.037736; exponentiate: 0.962970.96297. So p∗/2=0.03703p^*/2 = 0.03703 and p∗≈0.074p^* \approx 0.074. Below this slip probability the bridge is better; above it, the long way round is.

  3. With γ=0.99\gamma = 0.99: q∗=(1+0.994)/2=(1+0.96060)/2=0.98030q^* = (1 + 0.99^4)/2 = (1 + 0.96060)/2 = 0.98030, so (q∗)1/5=0.99603(q^*)^{1/5} = 0.99603 and p∗≈0.0079p^* \approx 0.0079. A patient agent loses almost nothing by taking 4 extra steps (0.994≈0.960.99^4 \approx 0.96), so it accepts almost no risk for the shortcut. An impatient one (γ=0.9\gamma = 0.9 loses 34% by waiting 4 steps) gambles more. The exact crossover for γ=0.99\gamma = 0.99 is also 0.0080.008.

  4. Three simplifications favor the bridge, so the true crossover is lower:

    • A fall actually happens before t=5t = 5, so its −1-1 is discounted less, which makes it more costly than the model assumes.
    • On the bridge, a slip upward bumps the wall and wastes a step, which delays the +1+1.
    • The very first move off S can slip up or down, which costs time.

    The long way round also loses time to slips, which partly offsets these, but the net effect lowers p∗p^* from 0.074 to 0.068. A crude model got within 10% of the right answer, and told us why the answer is what it is: the bridge is worth it only while (1−p/2)5>(1+γ4)/2(1 - p/2)^5 > (1 + \gamma^4)/2.

Exercise 1.6Stuck on the long way roundExplore the demo●●○

Set slip to 0, γ=0.9\gamma = 0.9 and ε = 0.1, and use speed “fast”. Press Reset agent and let it learn for about 500 episodes. Repeat until you get a run where the agent settles on the long way round: after a few hundred episodes, the arrow on S still points up and the agent walks the top row. (A quick test: set ε to 0 for a moment. A run that found the bridge then scores exactly 0.590 per episode; a stuck run scores 0.387.) In our tests about one run in six gets stuck.

  1. In a stuck run, look at the values and arrows on the bridge squares. What has the agent learned about them, and what has it not learned?
  2. Explain why exploring 10% of the time does not get it unstuck quickly. Roughly how likely is it, on a visit to S, to get past the first bridge square?
  3. Now tick optimistic start and reset a few times. Even with ε = 0, the agent finds the bridge every time. Why?
Hint
For question 2: the agent only learns that a bridge square is good by stepping from it onto a square it already knows is good. Values spread backwards from G one square at a time, and only along paths the agent actually walks.
Solution
  1. On S, the arrow points up, with value 0.39 (=0.99= 0.9^9, the long way round). On the first bridge square, the arrow points left, back to S, with a value of about 0.3: the agent has learned that the best thing it knows from there is to retreat to the familiar route. Further along the bridge the values are mostly 0 and several arrows are drawn faintly at once. Those are ties: the agent has no information, except that “down” is bad (it has fallen in a few times, so down has a negative estimate). It has not learned that moving right leads to G, because it has rarely or never got there that way.

  2. The agent learns that a square is valuable only by moving from it to a square it already believes is valuable. So the knowledge “G is near” has to travel backwards along the bridge, one square at a time, and only along moves the agent actually makes. Two greedy choices block the way: the arrow on S points up, and the arrow on the first bridge square points back to S. To get past both, the agent needs an exploratory move at each, and that move must happen to be “right”. With ε-greedy, each step is a random action with probability ε, and a random action is “right” with probability 1/4, so each has probability ε/4=0.025\varepsilon/4 = 0.025. Both in a row: 0.0252≈1/1,6000.025^2 \approx 1/1{,}600. Even then, the agent is on unexplored squares where it picks among tied actions at random, so it usually wanders back or falls in before reaching G. Each crossing that does reach G teaches only the last square or two. So unsticking can take thousands of episodes. The agent is behaving sensibly given what it knows. It just doesn’t know what it is missing. That is the exploration–exploitation dilemma.

  3. With optimistic start, every move begins with an estimated value of +1+1, as high as any return the agent can actually get in this world (with step reward 0). Whenever the agent tries a move, its estimate falls toward the truth, so moves it has not tried look better than moves it has. The agent is therefore drawn to try everything systematically, including every move on the bridge, until experience brings its estimates down to reality. It explores because of what it doesn’t know, not by chance. Chapter 2 develops this principle, “optimism in the face of uncertainty”, into the UCB algorithm.

Exercise 1.7When is finishing worth it?Pen & paper●●○

Suppose every ordinary move earns a step reward ss (which might be positive), reaching G earns +1+1 and ends the episode, and γ<1\gamma < 1. Compare two behaviors from some square:

  • Finish: walk to G, arriving on the nn-th move.
  • Loiter: never finish (ignore the demo’s 100-step limit).
  1. Write the return of each.
  2. Show that finishing is better if and only if s<1−γs < 1 - \gamma, whatever the distance nn.
  3. In the demo with γ=0.9\gamma = 0.9, what happens with step reward +0.05+0.05? With +0.2+0.2? Check with the agent. What does “best possible” show for +0.2+0.2, and why that number?
  4. What happens at γ=1\gamma = 1 with step reward 0? Try it in the demo and describe the agent’s arrows.
Hint
Loitering gives a geometric series. Finishing gives n−1n - 1 step rewards followed by γn−1\gamma^{n-1} times the +1+1. Subtract.
Solution
  1. Loitering: Gloiter=s+γs+γ2s+⋯=s1−γG^\text{loiter} = s + \gamma s + \gamma^2 s + \cdots = \dfrac{s}{1 - \gamma}.

    Finishing: n−1n - 1 ordinary moves, then the move onto G:

    Gfinish=s∑k=0n−2γk+γn−1⋅1=s 1−γn−11−γ+γn−1.G^\text{finish} = s \sum_{k=0}^{n-2} \gamma^k + \gamma^{n-1} \cdot 1 = s\,\frac{1 - \gamma^{n-1}}{1 - \gamma} + \gamma^{n-1}.
  2. Subtract:

    Gfinish−Gloiter=s−sγn−1−s1−γ+γn−1=γn−1(1−s1−γ).G^\text{finish} - G^\text{loiter} = \frac{s - s\gamma^{n-1} - s}{1 - \gamma} + \gamma^{n-1} = \gamma^{n-1}\left(1 - \frac{s}{1 - \gamma}\right).

    Since γn−1>0\gamma^{n-1} > 0, the sign depends only on 1−s/(1−γ)1 - s/(1-\gamma): finishing is better exactly when s<1−γs < 1 - \gamma. The distance nn only scales the difference. An intuitive reading: by finishing, you swap the loiterer’s endless stream of ss per step, worth s/(1−γ)s/(1-\gamma), for a single +1+1. (At s=1−γs = 1 - \gamma the two are exactly equal: every square is worth exactly 1, whether you finish or not, as long as you stay out of the pits.)

  3. With γ=0.9\gamma = 0.9 the threshold is 0.10.1. At s=+0.05s = +0.05 the agent still heads for G (though with less urgency than at s=0s = 0). At s=+0.2s = +0.2 it never finishes. It wanders, carefully avoiding both G and the pits. “Best possible” shows about 2.002.00. That is the loitering return 0.2/(1−0.9)=20.2/(1 - 0.9) = 2, cut off at 100 steps: 0.2 (1−0.9100)/0.1≈2.0000.2\,(1 - 0.9^{100})/0.1 \approx 2.000. The designer probably meant “+0.2 for surviving” as encouragement, and the agent read it as “the goal is a trap that ends the payments”.

  4. With γ=1\gamma = 1 and s=0s = 0, every route that reaches G (within the 100-step limit) has return exactly 1: there is no reason to hurry. The learned values are all close to 1 and the arrows look haphazard, sometimes pointing into walls. That is not a bug. Any route that doesn’t fall into a pit is optimal, so the agent has no reason to prefer the short one. A negative step reward (or γ<1\gamma < 1) is what makes “faster” better.

Exercise 1.8The helpful bonus tilePen & paper●●○

The bonus tile sits at row 0, column 3, on the long route. It pays +0.3+0.3 each time the agent steps onto it. Take γ=0.9\gamma = 0.9, step reward 0, no slip.

  1. The agent’s learned behavior: walk from S to the coin (up, up, right, right, right), then step off and on forever. Compute its return from S, and confirm the demo’s “best possible” of 1.036.
  2. A more “honest” plan: collect the coin once on the way, then continue to G along the top row. What is its return? Is it better than the plain bridge (0.590)?
  3. How small would the bonus bb have to be for looping forever not to beat walking the bridge?
  4. Propose two ways to change the reward so that it still encourages visiting the top row, but cannot be farmed.
Hint
The coin is first reached on the 5th move (t=4t = 4); after that the agent is back on it every second move.
Solution
  1. Rewards are +0.3+0.3 at t=4,6,8,…t = 4, 6, 8, \dots and 0 otherwise:

    G0=0.3 (γ4+γ6+γ8+⋯ )=0.3 γ41−γ2=0.3⋅0.65610.19=1.036.G_0 = 0.3\,(\gamma^4 + \gamma^6 + \gamma^8 + \cdots) = 0.3\,\frac{\gamma^4}{1 - \gamma^2} = 0.3 \cdot \frac{0.6561}{0.19} = 1.036 .

    The 100-step limit cuts off only terms of size about 0.9100≈3×10−50.9^{100} \approx 3 \times 10^{-5}, so the demo agrees to three decimals.

  2. Coin at t=4t = 4, then five more moves along the top row and down the right side to G: +1+1 at t=9t = 9. G0=0.3⋅0.94+0.99=0.197+0.387=0.584G_0 = 0.3 \cdot 0.9^4 + 0.9^9 = 0.197 + 0.387 = 0.584. This is slightly worse than the bridge’s 0.590. So the bonus doesn’t even change honest behavior much: its only big effect is to create the loop.

  3. Looping beats the bridge when b γ4/(1−γ2)>γ5b\,\gamma^4/(1 - \gamma^2) > \gamma^5, that is when b>γ(1−γ2)=0.9⋅0.19=0.171b > \gamma(1 - \gamma^2) = 0.9 \cdot 0.19 = 0.171. Any bonus above about 0.17 gets farmed.

  4. Some options:

    • Pay the bonus only once per episode. This works, but note that whether the coin has been collected is now part of the situation the agent is in. The state must include a “collected” flag, or the problem is no longer Markov (Chapter 3).

    • Potential-based shaping (Ng, Harada & Russell, 1999). Pick any function Φ(s)\Phi(s) of the state, say higher on the top row, and add F=γ Φ(st+1)−Φ(st)F = \gamma\,\Phi(s_{t+1}) - \Phi(s_t) to every reward. Over an episode these extra terms telescope:

      ∑t=0T−1γt(γΦ(st+1)−Φ(st))=γTΦ(sT)−Φ(s0),\sum_{t=0}^{T-1} \gamma^t \big(\gamma \Phi(s_{t+1}) - \Phi(s_t)\big) = \gamma^T \Phi(s_T) - \Phi(s_0),

      which depends only on the start and end states, not on the path. Set Φ=0\Phi = 0 on the terminal squares G and P (or let γT→0\gamma^T \to 0), and every policy’s return changes by the same constant −Φ(s0)-\Phi(s_0). So the shaping cannot change which policy is optimal. In particular, going round in a circle back to the same state ss after LL steps collects (γL−1) Φ(s)≤0(\gamma^L - 1)\,\Phi(s) \le 0 of shaping reward when Φ≥0\Phi \ge 0: nothing to farm. Physicists will recognize the move: adding a total time derivative to a Lagrangian changes the action only by boundary terms, so it leaves the equations of motion unchanged.

    • Don’t shape at all. Use a better exploration method instead (Exercise 1.6), and keep the reward equal to the real goal.

Exercise 1.9Design a reward, then break itConcept●●●

You want to train a language model to fix bugs in a code repository. Your first idea for the reward: the fraction of the repository’s unit tests that pass after the model’s edit.

  1. List at least three ways a model could get a high reward without fixing the bug.
  2. For each, propose a change to the reward or the environment that blocks it.
  3. Are any of your fixes themselves exploitable? What can’t be fixed by changing the reward alone?
Hint
Think about everything the model is allowed to touch: the code, the tests, the test runner, the process exit code. And think about tests that pass for the wrong reason.
Solution

Possible exploits and fixes (there are others):

  1. Edit or delete the failing tests. Fix: make test files read-only, or run a held-out copy of the tests that the model cannot see or modify.
  2. Special-case the tests: detect the exact inputs the tests use and return the expected outputs (if x == 3: return 7). Fix: hidden tests, randomized tests or property-based tests, and reward on tests the model never saw.
  3. Break the test harness: make the runner exit with a “success” code early, catch every exception, or disable assertions. Fix: run tests in a sandbox where the harness is outside the model’s reach, and check the actual test report, not just the exit code.
  4. Pass by doing nothing. If most tests already passed, the “fraction passing” is high before any edit. Fix: reward on the tests that were failing (and still require the others to pass), or reward the change in the pass rate.
  5. Make the fix, but also break something no test covers (delete error handling, hard-code a config). Fix: broader tests, a code-review model or human review, a penalty for large or unrelated diffs.

Can the fixes be exploited? Yes, often. A reviewer model can be flattered or confused. A diff-size penalty discourages legitimate large fixes. Hidden tests only check what they check. The deeper point: a reward is a finite test of an open-ended intention, and a strong optimizer searches exactly the space between the two. Better rewards shrink that space. Monitoring, held-out evaluations, limits on how hard you optimize (Chapter 11’s KL “leash”), and checking the agent’s actual behavior remain necessary. Chapter 18 looks at coding agents, and Chapter 19 at documented cases of exactly these hacks. Concrete Problems in AI Safety (Amodei et al., 2016) discusses the same issue for a cleaning robot.

Exercise 1.10Lab: build the gridworld and measure policiesCode●●○

Download the lab below and work through the five tasks in gridworld.py:

  1. Task 1, discounted_return(rewards, gamma): the return, computed backwards with Gt=rt+γGt+1G_t = r_t + \gamma G_{t+1}.
  2. Task 2, GridWorld.reset() and GridWorld.step(a): the environment, including slips.
  3. Task 3, random_policy and safe_policy: two policies. bridge_policy is given as an example.
  4. Task 4, run_episode(env, policy, gamma, max_steps, rng): the agent–environment loop.
  5. Task 5, estimate_return(...): a Monte Carlo estimate of Vπ(S)V^\pi(\text{S}), with a standard error.

When the tests pass, run python run.py. It prints sample episodes and average returns, and plots the expected return of the bridge and safe policies as the slip probability goes from 0 to 0.4. Check the crossover against your answer to Exercise 1.5, and check the table of values in this chapter against your estimates.

Hint
In step, do things in this order: decide whether the move slips (one call to self.rng.random()), and if so which perpendicular direction (a second call); then move with self._move; then look at the cell you landed on to set the reward and done. Remember to update self.state and self.done.
Solution

The reference solution is in solutions/gridworld.py. Key lines:

  • discounted_return: loop over reversed(rewards) with G = r + gamma * G, starting from G = 0.0.
  • step: if self.slip > 0 and self.rng.random() < self.slip: actual = (a + 1) % 4 if self.rng.random() < 0.5 else (a + 3) % 4, then s2 = self._move(self.state, actual), then reward +1+1 for 'G', −1-1 for 'P', self.step_reward otherwise, with done true for G and P.
  • safe_policy: up the left column (c == 0 and r > 0), right along row 0, down the right column (up from (3,6)(3, 6)), and right if you find yourself on the bridge.
  • run_episode: s = env.reset(), then up to max_steps iterations of a = policy(s, rng); s, r, done = env.step(a), collecting rewards and breaking on done; return (discounted_return(rewards, gamma), rewards).
  • estimate_return: one np.random.default_rng(seed) shared by all episodes, then mean and std(ddof=1) / sqrt(n) of the returns.

Expected output of run.py: at slip 0 the bridge gives 0.590 and the safe route 0.387, both with zero standard error, since nothing is random. At slip 0.2, the bridge gives about −0.03 and the safe route about 0.26. The plotted crossover lands near 0.07; the exact value is 0.068. The random policy scores about −0.44 at every slip probability.

Files: README.md, gridworld.py, test_gridworld.py, run.py

cd 01-what-is-rl
python -m pytest -q          # your code: tests fail until you fill in the TODOs
RL_SOLUTIONS=1 python -m pytest -q   # reference solutions: all pass

First time? See Exercises & setup.

Further reading

Next: the simplest RL problem there is, with no states at all, just a row of slot machines. It is the cleanest place to study exploration. On to Chapter 2: Bandits.