Lesson 3 · The problem
Returns and discounting
The problem
The agent's aim is to collect as much reward as it can over time. To turn that into something it can maximise, we need one number per run that scores "how much reward, over time". Two cases show that plain adding up isn't enough.
Sooner should beat later. On the grid from the first lesson, one robot reaches the goal in 5 moves. Another wanders for 12 moves and then reaches it. Both collect the same rewards: zeros, then one +1.
Adding them up scores both runs as 1. But the 5-move route is better.
Some tasks never end. In the coupon MDP, she orders pizza every week, forever. Never sending a coupon earns about 0.45 a week, and coupons at B and C earn about 0.545. Add up forever and both totals are infinite. You can't compare infinity with infinity.
One small change fixes both: shrink each reward by a fixed factor for every step you have to wait for it.
Shrinking future rewards
Pick a number (gamma) between 0 and 1, say 0.5. A reward arriving now counts in full. One step later it counts as much, two steps later as much, and so on.
Worked example
Rewards 0, 0, 4 with γ = 0.5
The first reward, 0, arrives now. It counts in full: .
The 4 is worth only 1 today, because it's two steps away.
Predict first
γ = 0.5. The next three rewards are 0, 0, +1. What is the discounted sum?
The discounted sum of all the rewards from a time step on is the return, written for the return from step . The number is the discount factor.
Read it as: take every reward after time . Shrink the one steps away by . Add them all. The is sum notation; is the next reward, , which isn't shrunk at all.
The return from the start of an episode, , scores the whole run. The agent's job is to pick actions that make the return large. Since what happens is random, that means large on average: its expected value. That's where the next lesson starts.
See it
The strip shows a run of rewards. Each bar's outline is the reward. The filled part is what's left after discounting: its share of the return. Drag and switch between the three timelines.
Return G₀ with γ = 0.5: 1.00 (dashed outline = reward, filled = its discounted share γᵗ·r)
Return G₀ = 1.000
0.50² × 4 = 1.000
Things to notice:
- 0, 0, 4: at the return is 1. At nothing shrinks and the return is 4. At only the first reward counts, so the return is 0.
- Grid episode: the 12-move episode from the first lesson. At its +1 is 11 steps after the first reward, so . The 5-move route would give . Discounting rewards speed.
- +1 every step: at the bars after about step 20 are tiny. , so rewards 22 or more steps away count less than a tenth.
Working backwards
There's a faster way to compute returns. The return from step is the next reward plus the discounted return from step :
Check it on the expanded sum: , which is everything in after the first reward.
So start at the end of the episode, where nothing is left, and work backwards. For 0, 0, 4 with :
| Step | ||
|---|---|---|
| 2 | 4 | |
| 1 | 0 | |
| 0 | 0 |
One pass gives the return from every step, not only from the start. This "reward now, plus times what comes after" pattern is the seed of the Bellman equation, the most-used equation in the course.
Tasks that end and tasks that don't
The grid has terminal states. Every episode ends, then a new one starts. A task like that is an episodic task. Games, mazes and a robot arm picking up one object are all episodic.
The coupon MDP has no end. She orders every week, forever. A task like that is a continuing task. Heating control, ad placement and stock trading are continuing tasks.
For a continuing task, discounting is what keeps the return finite. Watch a reward of +1 every step, forever:
After 60 steps: γ = 1 gives 60; γ = 0.9 gives 9.98
Keep going forever and γ = 1 never stops climbing. γ = 0.9 never passes 10.00.
Predict first
Every step pays +1, forever, and γ = 0.9. What does the return settle at?
The geometric series
The sum , where each term is the one before times the same ratio, is a geometric series. When is between 0 and 1, it adds up to a finite number:
Check it with easy numbers:
- : , and . Each term fills half of the gap that's left to 2.
- : .
- : .
The first terms add up to . As grows, shrinks to 0, which leaves .
This bounds every return. Say no reward is ever bigger than in size. Then each term of is at most in size, so
In the coupon MDP, the rewards are between −0.5 and +1. With , every return lies between and . Both policies now get a finite score, so they can be compared.
Why does it settle? Multiplying by a number smaller than 1, over and over, shrinks towards 0. It's the one-number version of the settle-or-explode rule for matrices in the eigenvectors lesson, where the spectral radius plays the part of . Later lessons use exactly that rule to show that their values settle.
DeeperWhy 1 + γ + γ² + … = 1/(1 − γ)Shift the sum by one place and subtract: almost everything cancels. A picture shows why. · 3 min
Call the sum :
Multiply every term by . Each term turns into the next one:
That's without its first term. So subtracting leaves only the first term:
The picture lays each term out as a block, end to end. The top row is . The bottom row is : the same blocks without the first. Every block in the bottom row sits under an equal block in the top row. So the top row is longer by exactly the first block, of length 1.
(1 − γ)·S = 1, so S = 1/(1 − 0.50) = 2.00
One condition hides in the argument: has to be a finite number before you subtract. That's true when . At , grows forever, and "" makes no sense.
How far ahead does the agent look?
The weight on a reward steps away is . Plot those weights, and you can see how far ahead the agent looks.
Effective horizon at γ = 0.9: 10 steps
The first 10 steps carry 65% of all the weight. A reward 10 steps away counts 0.35 as much as one now.
The weights fade smoothly. There's no step where they suddenly stop. But the total weight is : the same as giving full weight to steps and none after. That number is the effective horizon.
| Effective horizon | Weight on the reward that far away | |
|---|---|---|
| 0 | 1 | only the next reward counts |
| 0.5 | 2 | |
| 0.9 | 10 | |
| 0.99 | 100 |
Things to notice:
- At the agent looks about 10 steps ahead. The first 10 steps carry of all the weight.
- At it looks about 100 steps ahead.
- For near 1, a reward one horizon away keeps about a third of its size, so it still counts.
Predict first
γ goes up from 0.9 to 0.99, a change of only 0.09. What happens to the effective horizon?
Choosing γ
is part of the problem, not a detail. It says how much the future matters, and different values can make different policies best.
In the coupon MDP, a coupon at B costs now and pays off over later weeks. At the agent sees only this week, and the coupon loses. At it sees about 10 weeks ahead, and the coupon wins. The action values lesson works out exactly where that flip happens.
Three ways to read :
- Sooner is better. Like interest on money: 1 now is worth more than 1 next year.
- The future is uncertain. Say that each step, there's a chance that the task suddenly stops for good. Then a reward steps away is still collected only with chance . Discounting with is then the same as plain adding up, on average.
- The maths needs it. For continuing tasks, keeps returns finite.
This course uses for the grid and the coupon MDP. Episodic tasks that always end, such as the cliff walk, can use , since their sums are finite anyway. Deep RL usually uses : about 100 steps ahead.
DigressionReward versus long-term worth: collegeA step can cost you now and still be the right move. · 1 min
Going to college costs money and years of low pay. Each of those steps has a negative reward. But it can lead to better-paid work later, so its long-term worth can be high.
The same is true on the grid and in the coupon MDP. A step's reward says how good that one step was. The return says how good everything from there on was. A coupon at B has expected reward 0 this week, against 0.2 without it. It's still the better choice at , because of the weeks that follow.
Decisions should be judged by returns, never by one step's reward. The next lesson puts a number on the long-term worth of each state: its value.
DigressionAverage reward: another way to handle tasks that never endScore a continuing task by its reward per step in the long run, with no discounting. · 2 min
The Markov decision processes lesson scored coupon policies by their long-run average reward per week: 0.45 for "never", 0.545 for "coupons at B and C". That's another way to give continuing tasks a finite score. Instead of discounting, divide the total by the number of steps.
The two scores are closely linked. Multiply the expected discounted return by . As gets close to 1, the result gets close to the average reward. For "never send a coupon", starting at A:
| Expected return from A | Times | |
|---|---|---|
| 0.9 | 5.30 | 0.530 |
| 0.99 | 45.9 | 0.459 |
| 0.999 | 450.9 | 0.451 |
The last column heads for the average reward, 0.45. Where she starts matters less and less as the horizon grows.
Average reward suits tasks where the far future matters as much as now, such as keeping a server farm cool forever. Its theory and algorithms are a little harder, so this course uses discounting throughout.
In PyTorch
The backwards loop is the standard way to compute returns in code. It takes a tensor of rewards from one episode and gives the return from every step:
def discounted_returns(rewards: torch.Tensor, gamma: float) -> torch.Tensor:
"""G_t for every step t of one episode: G_t = R_{t+1} + gamma * G_{t+1}, working backwards.
rewards: shape (T,), rewards[t] is R_{t+1}, the reward for step t.
Returns shape (T,): returns[0] is the return of the whole episode, G_0.
"""
returns = torch.empty_like(rewards)
g = torch.zeros((), dtype=rewards.dtype, device=rewards.device) # the return after the last step is 0
for t in reversed(range(rewards.shape[0])):
g = rewards[t] + gamma * g
returns[t] = g
return returnsThings to notice:
rewards[t]holds , the reward for step . The result's entry 0 is , the return of the whole episode.torch.empty_like(rewards)makes the output with the same shape, dtype and device as the input, so the function works on a GPU too.- On
[0, 0, 4]withgamma=0.5it returns[1, 2, 4]: the table above.
The loop runs once per step, which is fine for episodes of a few thousand steps. The REINFORCE lesson reuses this function. The weights are one line, which gives a second way to get : a dot product of rewards and weights.
def discount_weights(gamma: float, n: int, dtype: torch.dtype = torch.float64) -> torch.Tensor:
"""The weight on the reward k steps ahead, gamma**k, for k = 0 ... n - 1. Shape (n,)."""
return gamma ** torch.arange(n, dtype=dtype)
def effective_horizon(gamma: float) -> float:
"""About how many steps ahead the agent looks: 1 / (1 - gamma)."""
return float("inf") if gamma >= 1 else 1.0 / (1.0 - gamma)rewards @ discount_weights(0.5, 3) gives , the same .
Common misconceptions
"The first reward is discounted too." counts in full; the weights start at . A reward two steps after it gets , not .
"γ = 0.99 is about the same as γ = 0.9." The horizon depends on . Going from 0.9 to 0.99 multiplies it by ten, from 10 steps to 100.
"Rewards past the effective horizon are ignored." They fade gradually and never drop to zero. At , a reward 10 steps away still counts about a third.
"Discounting is only a trick to make sums finite." It also says sooner is better, and it can change which policy is best. In the coupon MDP, the best action at B depends on .
"γ = 1 is never allowed." It's fine for episodic tasks that always end, because their sums are finite. It's only a problem for tasks that can go on forever.
Recap
- The return scores everything that happens after step .
- The discount factor between 0 and 1 makes sooner rewards count more. With , rewards 0, 0, 4 give a return of 1.
- Returns satisfy , so one backwards pass computes them all.
- Episodic tasks end; continuing tasks don't. For continuing tasks, keeps the return finite: at most .
- The geometric series: .
- The effective horizon is about how far ahead the agent looks: 10 steps at , 100 at .
- PyTorch names used:
torch.tensor,torch.empty_like,torch.zeros,torch.arangeand@for the dot product.