Part I · Foundations · Chapter 1
What is reinforcement learning?
Agent, environment, action, reward. How learning from reward differs from learning from labels.
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 :
action a_t
┌───────────────────────────────┐
│ ▼
┌─────────┐ ┌──────────────┐
│ agent │ │ environment │
└─────────┘ └──────────────┘
▲ │
└───────────────────────────────┘
reward r_t, next state s_{t+1}
- The agent observes the state : whatever information it gets about the current situation.
- It picks an action .
- The environment responds with a reward , a single number saying how good that step was, and moves to a new state .
- Repeat.
The reward is the one that arrives after action . (Sutton & Barto’s textbook calls it . 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 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
| Problem | Agent | State (what it sees) | Actions | Reward |
|---|---|---|---|---|
| Atari game | the game-playing program | the last few screen frames | joystick moves | change in the game score |
| Go | AlphaGo | the board position | where to put a stone | +1 for a win, −1 for a loss, only at the end |
| Thermostat | the controller | indoor and outdoor temperature, time of day | heating power | minus the discomfort minus the energy cost |
| Robot arm | the control software | joint angles, velocities, a camera image | motor torques | +1 when the object is in the bin, minus effort |
| Recommender | the recommendation system | the user’s history and context | which item to show | a click, or minutes watched |
| Fusion plasma | a neural controller | magnetic sensor readings | voltages on the shaping coils | how close the plasma is to a target shape |
| Chatbot | the language model | the conversation so far | the next token, or a whole reply | thumbs-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?
From the learning player's point of view, the opponent's replies are just how the world responds to its moves, even if the opponent is a copy of itself. That is why self-play fits the standard loop.
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 and ends the episode. Landing in a pit P gives 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 . The thing to maximize is the return: the sum of future rewards, each one discounted by a factor per step of delay:
where is the length of the episode: it ends on arriving in state , so the last reward is . With this is the plain sum. With a reward that arrives 10 steps from now counts for of its face value.
A worked example
Take and step reward 0, with no slipping. Walking the bridge, you collect and then :
| 0 | 1 | 2 | 3 | 4 | 5 | |
|---|---|---|---|---|---|---|
| 0 | 0 | 0 | 0 | 0 | +1 | |
| 1 | 0.9 | 0.81 | 0.729 | 0.6561 | 0.59049 | |
| 0 | 0 | 0 | 0 | 0 | 0.59049 |
So the bridge’s return is . The long way round reaches G on its 10th move, so . 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 . The bridge pays five times, then :
The long way round pays nine times, then : . 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.
- 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.
- Uncertainty. If there is a probability at each step that the episode is cut short, then the expected undiscounted return equals the discounted return. Discounting is then just honest bookkeeping.
- Mathematics. In a task that never ends, the plain sum of rewards can be infinite. With and bounded rewards it cannot: if every , then . A geometric series is the only tool needed.
The value of sets how far ahead the agent looks. With only the immediate reward counts (a completely myopic agent). As approaches 1, distant rewards count almost as much as near ones. Chapter 3 makes this precise as an effective horizon of about 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:
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₀?
G₀ = 1 + 0.5·0 + 0.25·2 = 1.5. Going backwards: G₂ = 2, G₁ = 0 + 0.5·2 = 1, G₀ = 1 + 0.5·1 = 1.5.
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 as it arrives, the weight it gets, and your running return . 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.
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 . 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 , 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 : 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 for the probability that policy chooses action in state . The lab has two hand-written deterministic policies, bridge and safe, and a stochastic one, random, which gives each of the four actions probability 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 under a policy is the expected return if you start in and follow from then on:
Some numbers, all at from the start square:
| slip 0 | slip 0.2 | |
|---|---|---|
| bridge policy | 0.590 | −0.027 |
| safe policy | 0.387 | 0.264 |
| random policy | −0.442 | −0.442 |
| best possible | 0.590 | 0.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 , is the expected return if you take action in first and follow afterwards. The colored squares and arrows in the demo show the agent’s estimates of action values: the color is its largest estimated 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 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 and , what and 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 or a . 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.
| Supervised | Unsupervised | Reinforcement | |
|---|---|---|---|
| Feedback | correct answer for each input | none | a scalar reward for what you did |
| When | immediately, per example | – | possibly much later |
| Data | fixed dataset, i.i.d. | fixed dataset, i.i.d. | generated by the learner’s own actions |
| Goal | predict labels | describe structure | maximize expected return |
Quick check Which of these is a problem RL faces that ordinary supervised learning on a fixed dataset does not?
The other three happen in supervised learning too. Only in RL (and other interactive settings) does the learner's behavior decide which data it gets. An agent that never tries the bridge never gets data about the bridge.
Three problems that make RL hard
Credit assignment
An episode ends with or . 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 , 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 legal positions. An Atari screen is 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?
One number for 2,000 decisions: which ones deserve the credit? That is credit assignment. Simple methods give every token the same credit; better methods try to estimate which steps actually mattered.
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 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 when looping is worth more? With , looping is worth from the start, against 0.590 for the bridge. Exercise 1.8 works through this.
- A positive step reward. Set the step reward to . “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 the agent prefers to finish exactly when the step reward is below , 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 , 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()andstep(a). - The agent’s objective is the return, the discounted sum of future rewards: . The discount sets how far ahead it looks.
- A policy says how to act. A value is the expected return from a state when following . 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 , 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
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.
- A thermostat controlling a home’s heating.
- A program that learns chess by playing against itself.
- A music app choosing the next song to play.
- A robot vacuum cleaner.
- A chatbot whose replies users can rate with thumbs up or down.
Solution
- 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.
- 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.
- 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.
- 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.
- 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).
An episode gives the rewards , , , , and then ends.
- Compute for , , and .
- For , compute using the backward recursion . Check that you get the same .
- A different, never-ending task pays at every step. What is for ? For ?
Solution
-
.
- : .
- : .
- : .
- : only the first reward counts, .
A myopic agent ( 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 .
-
Backward with : . . . . Same answer. Each step backward is one multiply and one add, with no powers of needed.
-
A geometric series: . That is for and for . As a rule of thumb, an agent with discount “sees” about steps ahead (Chapter 3).
Which kind of learning fits each problem best? Some are genuinely borderline; say why.
- Predicting house prices from a dataset of past sales.
- Grouping a shop’s customers into segments, with no labels.
- Adjusting a patient’s drug dose week by week based on how they respond.
- Learning to translate French into English from a large set of human translations.
- Training a model to write proofs that an automatic proof checker accepts.
- Choosing which of 10 ad designs to show each visitor to maximize clicks.
Solution
- Supervised. Each example comes with its correct answer (the sale price), the data are fixed, and our predictions don’t change the data.
- Unsupervised. No labels and no notion of a good or bad action. We want structure.
- 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.
- 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.)
- 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.
- 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.
Use the demo.
- 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?
- 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?
- 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.
- Why is the agent’s average return (blue line) well below “best possible”, even after it has learned?
Hint
Solution
- 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 , 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.
- 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.)
- 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 , 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).
- 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.
Take , step reward 0 and slip probability . Use this simplified model of the two routes:
- Bridge: five risky moves. On each, you fall into a pit with probability ; otherwise you move right. If you survive all five, you reach G at the 6th move ( at ). For simplicity, pretend that a fall also delivers its at .
- Long way round: no risk; reach G at the 10th move ( at ). Ignore slips that only waste time.
- Write the expected return of each route as a function of .
- Find the slip probability at which they are equal.
- Repeat for . How does a more patient agent feel about the risky shortcut?
- In the real gridworld at , the lab’s two hand-written policies (bridge and safe) have equal expected return at . (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
Solution
-
Let be the probability of crossing safely. Under the model all of the bridge’s reward arrives at , so
-
Set them equal: , so and
Then . Take logs: ; divide by 5: ; exponentiate: . So and . Below this slip probability the bridge is better; above it, the long way round is.
-
With : , so and . A patient agent loses almost nothing by taking 4 extra steps (), so it accepts almost no risk for the shortcut. An impatient one ( loses 34% by waiting 4 steps) gambles more. The exact crossover for is also .
-
Three simplifications favor the bridge, so the true crossover is lower:
- A fall actually happens before , so its 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 .
- 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 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 .
Set slip to 0, 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.
- 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?
- 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?
- Now tick optimistic start and reset a few times. Even with ε = 0, the agent finds the bridge every time. Why?
Hint
Solution
-
On S, the arrow points up, with value 0.39 (, 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.
-
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 . Both in a row: . 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.
-
With optimistic start, every move begins with an estimated value of , 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.
Suppose every ordinary move earns a step reward (which might be positive), reaching G earns and ends the episode, and . Compare two behaviors from some square:
- Finish: walk to G, arriving on the -th move.
- Loiter: never finish (ignore the demo’s 100-step limit).
- Write the return of each.
- Show that finishing is better if and only if , whatever the distance .
- In the demo with , what happens with step reward ? With ? Check with the agent. What does “best possible” show for , and why that number?
- What happens at with step reward 0? Try it in the demo and describe the agent’s arrows.
Hint
Solution
-
Loitering: .
Finishing: ordinary moves, then the move onto G:
-
Subtract:
Since , the sign depends only on : finishing is better exactly when . The distance only scales the difference. An intuitive reading: by finishing, you swap the loiterer’s endless stream of per step, worth , for a single . (At 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.)
-
With the threshold is . At the agent still heads for G (though with less urgency than at ). At it never finishes. It wanders, carefully avoiding both G and the pits. “Best possible” shows about . That is the loitering return , cut off at 100 steps: . 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”.
-
With and , 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 ) is what makes “faster” better.
The bonus tile sits at row 0, column 3, on the long route. It pays each time the agent steps onto it. Take , step reward 0, no slip.
- 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.
- 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)?
- How small would the bonus have to be for looping forever not to beat walking the bridge?
- Propose two ways to change the reward so that it still encourages visiting the top row, but cannot be farmed.
Hint
Solution
-
Rewards are at and 0 otherwise:
The 100-step limit cuts off only terms of size about , so the demo agrees to three decimals.
-
Coin at , then five more moves along the top row and down the right side to G: at . . 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.
-
Looping beats the bridge when , that is when . Any bonus above about 0.17 gets farmed.
-
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 of the state, say higher on the top row, and add to every reward. Over an episode these extra terms telescope:
which depends only on the start and end states, not on the path. Set on the terminal squares G and P (or let ), and every policy’s return changes by the same constant . So the shaping cannot change which policy is optimal. In particular, going round in a circle back to the same state after steps collects of shaping reward when : 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.
-
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.
- List at least three ways a model could get a high reward without fixing the bug.
- For each, propose a change to the reward or the environment that blocks it.
- Are any of your fixes themselves exploitable? What can’t be fixed by changing the reward alone?
Hint
Solution
Possible exploits and fixes (there are others):
- 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.
- 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. - 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.
- 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.
- 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.
Download the lab below and work through the five tasks in gridworld.py:
- Task 1,
discounted_return(rewards, gamma): the return, computed backwards with . - Task 2,
GridWorld.reset()andGridWorld.step(a): the environment, including slips. - Task 3,
random_policyandsafe_policy: two policies.bridge_policyis given as an example. - Task 4,
run_episode(env, policy, gamma, max_steps, rng): the agent–environment loop. - Task 5,
estimate_return(...): a Monte Carlo estimate of , 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
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 overreversed(rewards)withG = r + gamma * G, starting fromG = 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, thens2 = self._move(self.state, actual), then reward for'G', for'P',self.step_rewardotherwise, withdonetrue 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 ), and right if you find yourself on the bridge.run_episode:s = env.reset(), then up tomax_stepsiterations ofa = policy(s, rng); s, r, done = env.step(a), collecting rewards and breaking ondone; return(discounted_return(rewards, gamma), rewards).estimate_return: onenp.random.default_rng(seed)shared by all episodes, thenmeanandstd(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 passFirst time? See Exercises & setup.
Further reading
- Sutton & Barto (2018), Reinforcement Learning: An Introduction, 2nd ed., ch. 1 and 3.1–3.2. The standard textbook, free online. Chapter 1 covers this chapter’s ground with a tic-tac-toe example, and section 3.2 has the reward hypothesis.
- OpenAI Spinning Up (2018), Part 1: Key Concepts in RL. A compact, deep-RL-flavored tour of the same vocabulary, with notation close to ours.
- Krakovna et al. (2020), Specification gaming: the flip side of AI ingenuity. A short essay on why reward hacking happens, with a link to a list of real examples. Read it before Chapter 19.
- Clark & Amodei (2016), Faulty reward functions in the wild. The CoastRunners boat, with video.
- Mnih et al. (2015), Human-level control through deep reinforcement learning. The DQN paper. Readable now for the setup and results; Chapter 6 explains the method.
- Ouyang et al. (2022), Training language models to follow instructions with human feedback. InstructGPT. Skim the introduction and Figure 2 now to see where the course is going.
- Bowling, Martin, Abel & Dabney (2023), Settling the reward hypothesis. For when you want to know exactly when a scalar reward is enough.
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.