RL basics: reward, value, advantage
All of Part 4 was about where to get demonstrations, but demonstrations have a ceiling: a robot that copies an operator won't become faster or more careful than the operator and won't learn what to do where the operator never took it. Reinforcement learning (RL) works differently. The robot tries acting on its own, gets a number after every step that says how well it went, and learns to choose the actions after which the sum of these numbers is larger. This idea underlies the DeepMind program that learned to play Atari games from screen pixels in 2013, the walking policies of the four-legged robot ANYmal trained in simulation, and π*0.6 from lesson 3.8, which learns from its own attempts. In this lesson, we'll go through the foundation they all share: how to express a goal as a number, how to estimate how much good is still ahead, and how to tell that one action is better than another. Everything is computed in Ada's apartment from lesson 0.4, where the estimates can be obtained exactly and examined cell by cell.
When there are no demonstrations, or they aren't good enough
Ada is a home humanoid on a wheeled base; the course labs are built around her. More about her in lesson 0.1.
Part 4 ended with a question that demonstrations don't answer. A model that learns by imitation does, at best, what the operator did: no faster and no more carefully, and where the operator never took it, it doesn't know what to do. In lesson 1.2, DAgger patched this hole: a person showed how to get out of the states the policy itself leads to. In lesson 3.8, π*0.6 went further and learned from its own attempts, telling its better actions from its worse ones. This kind of learning needs two things: a score for each attempt, expressed as a number, and a way to turn the scores into better actions.
This is what reinforcement learning does: the robot tries acting on its own, gets a numerical score after every step and learns to choose the actions after which the sum of the scores is larger. This number is called the reward. No teacher who knows the right action is needed here: it's enough to be able to say how well things went. In their textbook “Reinforcement Learning: An Introduction” (2nd edition, 2018), Richard Sutton and Andrew Barto call this the reward hypothesis: “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).”
The reward says what to achieve, not how: in Sutton and Barto's words, it tells the agent “what you want achieved, not how you want it achieved.” Their example is chess: the program is rewarded for winning, not for taking pieces, or it will learn to take pieces at the cost of the game. A robot that is learning to walk is rewarded for moving forward, and a robot in a maze gets a reward of −1 for every step until it gets out. If Ada needs to drive to the kitchen, nobody tells her where to turn: she gets a reward when she arrives and works out for herself how to get it more often and sooner.
But the reward for getting there comes at the end, and Ada has to decide where to go from the very first step. How do you choose an action now from numbers that arrive later? First, let's agree on what the problem consists of.
The agent, the environment and one step of interaction
Reinforcement learning describes a problem as an exchange between two parties. The agent is the one that makes decisions and learns; here it's Ada's control system. The environment is everything else: the apartment, the objects, the people. According to Sutton and Barto, even the robot's own motors and sensors are better counted as part of the environment, because “anything that cannot be changed arbitrarily by the agent is considered to be outside of it.” Time moves in steps At each step, the agent receives a state , a description of what is happening right now, and chooses an action . In response, the environment moves to a new state and gives out a reward .
The rule by which the agent chooses an action is the policy, familiar from lesson 0.1. In reinforcement learning, it is written as the probability of choosing action in state ; a policy can also be deterministic, that is, always choose the same action in a given state. The chain of steps from the start of the task to its end is called an episode: it ends in a terminal state, for example when Ada has arrived, and then everything starts over.
If the state contains everything that matters for the future, then the next state and the reward depend only on the current state and action, not on how the agent got there. Such a problem is called a Markov decision process (MDP). All the theory in this lesson is written for it; what to do when the camera doesn't see everything, we'll cover in later lessons.
In this lesson, the environment is Ada's apartment from lesson 0.4: two bedrooms on the left of the plan, the living room in the middle and the kitchen on the right. The plan is divided into a grid of 12 × 8 cells, 50 cm each. The state is the cell where Ada stands, and there are 71 free cells in total. There are four actions: up, right, down or left on the plan. Ada can't drive into a wall or furniture: if she tries, she stays where she is. Ada has to drive from the bed in the upper bedroom to the stove. For entering the cell by the stove she gets a reward of +10, and the episode ends; every other step gives her 0.
This world is much simpler than the real one. There's no randomness in the apartment, the state is known exactly, and all the rewards and transitions can be written down in a table. But in this world, every quantity in this lesson can be computed exactly and seen. A real robot's problem has the same structure, except that the state is camera frames and joint angles, the actions are continuous, and the reward is put together from several terms. For the four-legged ANYmal in the work of Rudin et al. (2021), “the total reward is a weighted sum of nine terms”: the robot is rewarded for following the commanded velocity and penalized for joint torques and accelerations, for abrupt changes of joint targets and for collisions. The behavior depends on the form of a penalty. The ANYmal authors (Hwangbo et al., 2019) noticed that an unbounded penalty for the command tracking error makes falling the better strategy early in training, when the errors are large: a fall ends the episode, and the penalties end with it. So they bounded the penalty.
Rewards arrive step by step, but the decision is made once. How do you combine the rewards of future steps into a single number?
Return and discounting: why the future weighs less
Ada chooses her first action at the bed and gets the +10 twelve steps later, at the stove. So an action has to be chosen by all the rewards that will come after it, not by the reward for the next step, which is almost always 0. This weighted sum of future rewards is called the discounted return, or simply the return:
Here is the return from step , is the reward that will arrive steps after it, and is the discount factor, a number between 0 and 1. A reward steps ahead enters the return with weight : at , a reward one step ahead is worth 0.9 of the same reward now, two steps ahead 0.81, and ten steps ahead 0.35. When the episode ends, there are no more rewards, and the sum stops.
Why reduce the weight of the future? The first reason is mathematical. Many of a robot's tasks don't split into episodes: it works for hours. If every step gives +1, the undiscounted sum is infinite, while with it is at most . The second reason is practical: with , the same reward is worth more sooner than later, so the agent hurries. The third reason is statistical: the paper on generalized advantage estimation (GAE; Schulman et al., 2016) explicitly calls a way “to reduce variance by downweighting rewards corresponding to delayed effects.” Distant rewards depend on many future random actions, and lowering their weight makes the estimate more stable at the cost of a small bias.
The factor sets how far ahead the agent looks. At , in Sutton and Barto's words, the agent is “myopic” and cares only about the next reward; the closer is to 1, the more far-sighted it becomes. A handy measure of how far it looks is the number of steps after which a reward's weight halves: one step at , about 6.6 at 0.9 and 69 at 0.99. The ANYmal authors tuned for each task: for walking on command they took , which by their calculation “corresponds to a half-life of 5.77 s,” and they warn that “too high discount factor might result in a slow convergence.”
The return has a property the whole lesson rests on: it can be expressed through itself. The return from step is the reward for the next step plus the discounted return from the step after it: . That's why it's convenient to compute it backward from the end of the episode. Before computing, check how discounting feels by eye.
Forecasting the return: how much Ada will collect from each step
Ada drives from the upper bedroom to the stove by the shortest path, which takes 12 steps. The map shows her route, and each cell on it carries the number of the step at which Ada is in that cell. The chart has the step on the horizontal axis and the return on the vertical one: how much Ada will collect from that cell to the end of the episode. The reward for each step is written under the chart. Draw your forecast by dragging across the chart with a mouse or a finger, and compare it with the calculation.
The map shows the apartment from above; a cell is 50 × 50 cm. The orange line on it is Ada's route, the numbers show the step , and the crosshair marks the cell by the stove. On the chart, the horizontal axis is the step , and the vertical axis is the return in units of reward. The orange dots are your forecast. The blue dots show the return computed by the formula; they appear after the check. Under the axis is the reward for the step from cell .
Under the hood: the return counted from the end, the horizon and the half-life
Counting from the end. Let the episode end at step ; then , and going backward, . For Ada's route, . If the whole reward comes on the last step, the return from step equals : each step back multiplies it by , so the curve on the chart follows powers of rather than a straight line. With a reward like π*0.6's ( for every step and 0 for the last, successful one) and , the return equals : minus the number of steps left before the last one.
The horizon. If a reward arrives at every step without end, the return is the sum of a geometric series:
The quantity is called the effective horizon: it is 2 steps at , 10 at 0.9 and 100 at 0.99. The number of steps over which the weight halves comes from : . That's 1 step at , 6.58 at 0.9, 68.97 at 0.99 and 577 at 0.9988, as for ANYmal.
A note on notation. In the return formula, the reward for the step from cell is written , not : it arrives together with the next state. This is how Sutton and Barto write it, but papers use both conventions; in the GAE paper, for example, the reward for step is written .
The return is computed for a single episode, after Ada has driven and all the rewards have arrived. To choose an action, you need to know it in advance, and not for one route but for any cell and any action. RL has a separate quantity for that.
State value and action value
The return depends on what the agent will do next and, in general, also on the randomness of the environment, so you don't know it in advance. What you can know is the average. The state value is the expected return if the agent starts in state and then acts according to the policy . The action value is the expected return if you take action in state and then act according to :
Here is the average over all the episodes that can happen if the agent acts according to . Together these are called value functions, and is often called the Q-function. They are related simply: the state value is the average value of the actions, weighted by how often the policy chooses them, . If the policy is deterministic, equals the of the action it chooses.
The forecast in the interactive is a value too: on a fixed route without randomness, the return from step is exactly the of the cell where Ada stands. You've met value before. In lesson 2.3, SayCan's skill value functions were trained with a reward of 1 for success and 0 for failure, without discounting, and the value was the probability of success. In lesson 3.8, π*0.6 gets a reward of −1 per step, and its value equals minus the number of steps until success, as in the third forecast mission.
A policy whose value is at least as high as that of any other policy in all states at once is called optimal, and its values are written and . If is known, acting is simple: in each state, take the action with the largest . But how do you find it without trying every policy, when Ada has of them?
The Bellman equation: a cell's value through its neighbors
The same recursion of the return gives a hint. Since , the value of a cell also equals the reward for the next step plus the discounted value of the cell that step leads to. For the optimal policy, a choice is added: of all the actions, the one that gives the most is taken. This is the Bellman equation. It is named after Richard Bellman, who in 1957 called this approach dynamic programming. In Ada's apartment, where the transitions are deterministic, it looks like this:
Here is the cell Ada reaches from with action , is the reward for that step, and the cell by the stove, where the episode ends, has . The expression in brackets is the action value : the equation says that a cell's value equals the value of the best action in it. If the environment is random, the single cell is replaced by an average over all possible cells, weighted by their probabilities; we give this form in the lab's “Under the hood.”
The equation links every cell to its neighbors but doesn't say where to start: the neighbors' values are unknown too. The simplest way out is to turn the equation into an update rule: start with zero estimates in all cells and recompute all the cells again and again, plugging the estimates from the previous pass into the right-hand side. This is value iteration. Sutton and Barto show that it converges to from any initial estimates if .
Value iteration is related to Dijkstra's algorithm from lesson 0.4. If the reward is −1 for every step and , a cell's value equals minus the length of the shortest path to the goal, and value iteration finds the same paths as Dijkstra, except that it recomputes all the cells at once instead of expanding them one by one. In exchange, it works with any rewards and, in its general form, with a random environment too, where Dijkstra doesn't apply. Let's see what this looks like in Ada's apartment.
Value iteration in Ada's apartment
The apartment is the same as in lesson 0.4, and we look at it from above: on the left of the plan are two bedrooms, in the middle is the living room with a table and a sofa, and on the right is the kitchen with the sink, the stove, the fridge and a table in the middle. Ada stands at the bed in the upper bedroom and has to drive to the cell by the stove: there she gets +10, and the episode ends. The color of a cell shows the current estimate of its value, and the number in the cell is the estimate itself. An arrow shows the action with the largest under the current estimates; if all the actions in a cell are still equal, there's no arrow. At first, all estimates are zero. Hover over a cell or click it, and its Bellman update will appear under the scene.
Top-down view of the apartment; a cell is 50 × 50 cm. A blue fill means a positive value estimate for the cell (the darker, the closer to 10), and a red fill means a negative one. Gray arrows show the best action under the current estimates, and the orange line is the route Ada will take by following these arrows.
Legend: marks on the scene
Under the hood: the algorithm, convergence and the puddle thresholds
The algorithm. In the lab, all cells are recomputed at the same time, from the estimates of the previous iteration; that's how the wave is easiest to see:
Sutton and Barto more often update in place, plugging in the new estimates right away; this way the iteration usually converges faster, and the result is the same. It converges because each update shrinks the distance to the solution: , that is, the error shrinks by a factor of at least per iteration. In Ada's apartment, the only reward is at the stove, and after iterations a cell's estimate already accounts for all paths of at most steps, so the estimates become exact as soon as reaches the longest of the shortest paths.
A random environment. If action can take Ada from to different cells with probabilities , for example because the wheels slip on a wet floor, the Bellman equation takes the average:
Where the routes split. Past the kitchen door, Ada has two paths to the stove: past the sink, through the puddle, in 4 steps, and around the table in 6. With a reward at the stove, a penalty for the puddle and no penalty per step, the path through the puddle is worth , and the detour is worth . Ada goes through the puddle if : the two extra steps cost her a share of the reward, and that share has to be compared with the puddle penalty. With and , this holds for roughly between 0.10 and 0.946. At , Ada goes through the puddle only if the puddle costs less than 0.197, or if each step costs more than 0.412, or if the stove reward is above 50.8.
Value iteration knows nothing about routes: all it does, pass after pass, is compare neighbors. The route emerges from the estimates by itself, because the arrows point to where the estimate is higher. And which route is better depends not only on the reward but also on : two extra steps cost the impatient Ada 75% of the reward and the far-sighted one 2%, so with the same puddle they drive differently.
Value iteration goes straight for the best policy. But often a policy already exists (for example, Ada was trained on demonstrations), and you need to find out exactly where it does worse than it could.
Advantage: how much better an action is than usual
Comparing actions by itself is awkward. Near the stove all the values are about 10, in the bedroom about 3, and the number alone doesn't tell you whether an action is good or bad. What matters is something else: whether the action is better than what the agent usually does in that state. This difference is called the advantage:
Here is how much Ada will collect if she does now and then drives as usual, and is how much she will collect if she drives as usual now too. A positive advantage means the action is better than her habitual behavior, and a negative one means it's worse. Schulman et al. put it exactly this way in the GAE paper: the advantage “measures whether or not the action is better or worse than the policy's default behavior.” For a stochastic policy, equals the average over its actions, so some actions come out better than average and others worse.
You've met this word in lesson 3.8: π*0.6 computed the advantage of each of its actions from the value function, labeled actions “Advantage: positive” when the advantage was above a threshold, and learned to output the labeled ones more often. The advantage also gives the simplest improvement rule: in every state, switch to an action with a positive advantage. Sutton and Barto prove the policy improvement theorem: the new policy will be no worse than the old one in any state, and if the advantage was above zero in at least one state, it will be strictly better. If after switching you evaluate the policy again, compute the advantages and switch again, and keep going until there's nothing left to improve, you get policy iteration. Let's try it on an Ada who can already drive, but not in the best way.
Advantage arrows: where Ada's habit costs her
Ada was taught to drive from demonstrations. Each time, the operator took her from the bed to the stove along the same long road: along the top wall of the living room, away from the table, and around the kitchen table on its right side. This road takes 18 steps instead of 12. Where the operator never drove, the policy repeats the most frequent action in the demonstrations, “right,” and runs into walls. The puddle has been wiped up, Ada still gets +10 at the stove, and .
At first, the plan shows only the habitual actions: a thick arrow in each cell shows what Ada does there. After the calculation, every cell gets four colored arrows, one per action: green means the action is better than the habitual one, red means worse, and gray means the same. Click a cell, and its numbers will appear under the scene, along with buttons that change the habitual action.
Top-down view of the apartment; a cell is 50 × 50 cm. The thick outlined arrow shows the habitual action in a cell. The short colored arrows show the advantage of the four actions: a green one is better than the habitual action, a red one is worse, and a gray one is the same; the brighter the arrow, the bigger the difference. The blue fill shows the cell's value when Ada drives by habit. The orange line is Ada's route from the bed, and a ring marks the selected cell.
Legend: marks on the scene
Under the hood: policy evaluation, the sum of advantages and the improvement theorem
Policy evaluation. For a deterministic policy , the cell values are linked by the Bellman equation without the maximum: , where is the cell the habitual action leads to. This is a system of 70 linear equations; the lab solves it with the same update as value iteration, only without choosing the best action. Where Ada's habit runs her into a wall and she stays put, : she will never arrive. Then, for each of the four actions, the lab computes and .
Why the habitual action has zero advantage. is exactly , so . For a stochastic policy, the same rule takes the form of an average: . That's why the advantage shows the difference from how the agent acts on average, not whether an action is good or bad in itself.
The policy improvement theorem. If for two deterministic policies in all states, that is, no new action has a negative advantage relative to the habit, then in all states (Sutton and Barto, section 4.2). The proof expands one step ahead and applies the inequality again, step after step, until the whole return is computed under the new policy. There are finitely many deterministic policies, and each next one is strictly better, so policy iteration stops after a finite number of rounds, and the last policy is optimal.
When there is no model. Here and are computed exactly: the engine knows where every action leads. On a robot, the advantage is estimated from experience, for example like this: , that is, the reward for the step plus the value estimate after it minus the estimate before it. How to combine such estimates into an accurate and stable one is covered in the GAE paper and in lesson 5.2.
Policy iteration and value iteration arrived at the same route by different paths: the first improves an existing policy by advantages, the second goes straight for the best values. But both knew everything in advance: where each action leads and what reward it gives. In a real apartment, the robot has no such table.
Exploration and exploitation: why it sometimes pays to drive the wrong way
Value iteration and policy iteration are planning: they know where each action leads and what reward it gives. Sutton and Barto call these methods dynamic programming and immediately state the limitation: they need a perfect model of the environment. A robot in a real apartment has no such model. It learns about a reward only by receiving it, and about what happens after an action only by taking it. That's why RL methods estimate values from their own experience: from episodes and individual transitions. The authors of DQN (Deep Q-Network), which the next section is about, stress that the method is model-free: it learns from transitions drawn from the game emulator.
Experience raises a new problem. If you always choose the action that currently looks best, that is, exploit what you already know, you may never find out that another action is better. If you keep trying new things all the time, that is, explore, you'll get few rewards. The simplest compromise is the ε-greedy strategy: with probability it chooses the action that is best under the current estimates, and with probability a random one.
Sutton and Barto compare such strategies on a problem with ten options, where each option has its own average reward with random spread. Each strategy is run 2,000 times for 1,000 steps. The greedy strategy, , found the best option in only about a third of the tasks: its first tries of the best option happened to go badly, and it never came back to it. Its average reward per step leveled off at about 1, while the best possible was 1.54. The strategy with found the best option sooner, but because of its random choices it took it in no more than 91% of the steps. DQN, which learned to play Atari in 2013, started with , that is, with nothing but random actions, and lowered to 0.1 over the first million frames.
For Ada, this means that to find out she can also get around the kitchen table, she has to turn that way at least once in a while, as long as she doesn't yet know where the arrows lead. And when the states are not 71 cells but as many as the different frames the camera can see, a table of values no longer fits in any memory.
Value and advantage in modern methods
A table of values works while there are few states. The authors of DQN (DeepMind, 2013) note that estimating the value separately for each state is “totally impractical”: in an Atari game, the state is a sequence of frames. So they train a convolutional network that outputs for each action from the pixels, and they train it with the same Bellman equation: the target for is . The same architecture, with no tuning for each game, was tested on seven Atari games: it outperformed all previous approaches on six of them and an experienced human player on three. During training, the rewards were clipped to ±1 so that one learning rate would suit all the games.
Today, robots learn to walk in simulation with policy gradient methods, which use the advantage directly; they are the subject of lesson 5.2. In the 2019 work, the ANYmal policy was trained with TRPO in nine days of simulated time, which took four hours of computation. In 2021, Rudin et al. trained 4,096 copies of ANYmal in parallel on a single GPU: the policy learned to walk on flat ground in under four minutes and on uneven terrain in twenty. Their PPO uses and estimates the advantage with GAE.
An action value learned from the robot's own experience is at the core of methods that train robots directly in the real world; we'll cover them in lesson 5.3. With such a method, SERL (2024) taught an arm to assemble a circuit board, route a cable and relocate objects in 25–50 minutes of training per task on average. And π*0.6 from lesson 3.8 estimates value from its own episodes, computes the advantage from it and learns to output the actions labeled as better more often. Under the hood, they all use the same return, value, Bellman equation and advantage as in Ada's apartment.
Eight common misconceptions
Lesson takeaways
- In reinforcement learning, the agent acts in the environment on its own and gets a reward after every step. The reward sets what to achieve, not how; an engineer designs it, and the shape of the penalties changes the behavior: for ANYmal, an unbounded penalty made falling pay off.
- The return is the sum of future rewards with weights . The factor sets how far ahead the agent looks: at 0.5 a reward's weight halves in one step, at 0.99 in 69 steps. When the only reward is at the stove, the return doesn't grow toward it along a straight line: each step back multiplies it by , and at the bed, with , it is 3.14 out of 10.
- The value is the expected return from a state, and is the expected return after an action. The Bellman equation expresses a cell's value through its neighbors, and value iteration recomputes all cells until the estimates stop changing: in Ada's apartment, the estimate reached the bed in 12 iterations, one cell per iteration, and settled after the 16th.
- The choice depends on : Ada with drives through the puddle, and Ada with goes around the table. The two extra steps cost the first 75% of the reward and the second 2%.
- The advantage tells you whether an action is better than the habitual one: for the habitual action of a deterministic policy, it is zero. Switching to actions with never makes the policy worse; policy iteration took Ada from her habit of 18 steps and a return of 1.67 to 12 steps and 3.14, the same as value iteration.
- All of this was planning with a known model. Without one, values are estimated from experience, and the agent has to both explore and exploit; in large problems, a network replaces the table, as in DQN, and the advantage is at the core of PPO and π*0.6.
Open questions
How do you design a reward that leaves the agent no loopholes?
The agent finds what the reward allows, not what the engineer meant: the chess program takes pieces at the cost of the game, and ANYmal falls to put an end to the penalties. Rudin et al.'s reward consists of nine terms, and their weights had to be tuned to remove gait artifacts such as “a dragging leg.” Sutton and Barto devote a separate section, 17.4, to designing reward signals, but there is no general way to specify a reward without loopholes. That's why interest has grown in rewards that are learned from demonstrations or from human ratings.
Which discount factor is the right one?
For an episodic task where only the final goal matters, suggests itself, but then the estimates spread more widely, and for tasks without an end the return is infinite. The ANYmal authors tuned for each task by how the learned walking looked, and in GAE is no longer treated as part of the task but as a knob that trades variance for bias. In Ada's apartment, the route changed with . So by choosing , the engineer also chooses the behavior, and there is no rule for doing that in advance.
Source guide
R. S. Sutton, A. G. Barto, “Reinforcement Learning: An Introduction”, 2nd ed., MIT Press, 2018: a free version is on the authors' website.
- Read closelyChapter 3, sections 3.1–3.6: the agent and the environment, reward, returns and episodes, policies and value functions, the Bellman equations, the gridworld example. Chapter 4, sections 4.1–4.4 and 4.6: policy evaluation, the improvement theorem, policy iteration, value iteration and generalized policy iteration, where evaluation and improvement pull each other along. Section 2.3: the ε-greedy strategy on the problem with ten options.
- Safe to skipSections 4.5 and 4.7 on asynchronous dynamic programming and its efficiency, as well as the proof exercises: they are worth coming back to after lesson 5.2.
- Question to keep in mindExercise 3.7: a robot in a maze gets +1 for escaping and 0 the rest of the time, with no discounting, and it doesn't learn. Why? What would change in Ada's apartment if the +10 at the stove were counted with ?
Papers in this lesson: Playing Atari with Deep Reinforcement Learning (DeepMind, 2013), High-Dimensional Continuous Control Using Generalized Advantage Estimation (Schulman et al., 2016), Learning Agile and Dynamic Motor Skills for Legged Robots (Hwangbo et al., 2019), Learning to Walk in Minutes Using Massively Parallel Deep RL (Rudin et al., 2021), SERL (2024), π*0.6 (Physical Intelligence, 2025).
Resources
- Sutton & Barto, 2nd editionThe whole textbook: the PDF and the example code on the authors' website
- legged_gymRudin et al.'s code: thousands of ANYmals in simulation, a reward made of terms, PPO
- SERLA library and videos of reinforcement learning on a real manipulator
Ada's apartment has few cells and only four moves, so the value of every cell fits in a table. But Ada's steering command can be any number, and her sensors never see the same picture twice, so such a table can't be built.