Reinforcement learning3 / 5

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 (gamma) between 0 and 1, say 0.5. A reward arriving now counts in full. One step later it counts γ=0.5\gamma = 0.5 as much, two steps later γ2=0.25\gamma^2 = 0.25 as much, and so on.

Worked example

Rewards 0, 0, 4 with γ = 0.5

  1. The first reward, 0, arrives now. It counts in full: 00.

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 GtG_t for the return from step tt. The number γ\gamma is the discount factor.

Gt=Rt+1+γRt+2+γ2Rt+3+⋯=∑k=0∞γkRt+k+1G_t = R_{t+1} + \gamma R_{t+2} + \gamma^2 R_{t+3} + \dots = \sum_{k=0}^{\infty} \gamma^k R_{t+k+1}

Read it as: take every reward after time tt. Shrink the one kk steps away by γk\gamma^k. Add them all. The ∑\sum is sum notation; k=0k = 0 is the next reward, Rt+1R_{t+1}, which isn't shrunk at all.

The return from the start of an episode, G0G_0, 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 γ\gamma and switch between the three timelines.

s₀ar 00.00s₁ar 00.00s₂ar 41.00s₃

Return G₀ with γ = 0.5: 1.00 (dashed outline = reward, filled = its discounted share γᵗ·r)

Return G₀ = 1.000

0.50² × 4 = 1.000

Each reward's outline is its full size; the filled part is γᵗ times it, its share of the return G₀. Lower γ shrinks later rewards faster.

Things to notice:

  • 0, 0, 4: at γ=0.5\gamma = 0.5 the return is 1. At γ=1\gamma = 1 nothing shrinks and the return is 4. At γ=0\gamma = 0 only the first reward counts, so the return is 0.
  • Grid episode: the 12-move episode from the first lesson. At γ=0.9\gamma = 0.9 its +1 is 11 steps after the first reward, so G0=0.911≈0.31G_0 = 0.9^{11} \approx 0.31. The 5-move route would give 0.94≈0.660.9^4 \approx 0.66. Discounting rewards speed.
  • +1 every step: at γ=0.9\gamma = 0.9 the bars after about step 20 are tiny. 0.922≈0.0980.9^{22} \approx 0.098, 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 tt is the next reward plus the discounted return from step t+1t + 1:

Gt=Rt+1+γ Gt+1G_t = R_{t+1} + \gamma\, G_{t+1}

Check it on the expanded sum: γGt+1=γRt+2+γ2Rt+3+…\gamma G_{t+1} = \gamma R_{t+2} + \gamma^2 R_{t+3} + \dots, which is everything in GtG_t after the first reward.

So start at the end of the episode, where nothing is left, and work backwards. For 0, 0, 4 with γ=0.5\gamma = 0.5:

Step ttRt+1R_{t+1}Gt=Rt+1+0.5 Gt+1G_t = R_{t+1} + 0.5\, G_{t+1}
244+0.5×0=44 + 0.5 \times 0 = 4
100+0.5×4=20 + 0.5 \times 4 = 2
000+0.5×2=10 + 0.5 \times 2 = 1

One pass gives the return from every step, not only from the start. This "reward now, plus γ\gamma 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:

01020304050600102030405060steps so farrunning total1/(1 − γ) = 10.0γ = 1γ = 0.9

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.

A reward of +1 every step. Undiscounted (γ = 1), the running total climbs forever. Discounted, it levels off at 1/(1 − γ): 10 when γ = 0.9.

Predict first

Every step pays +1, forever, and γ = 0.9. What does the return settle at?

The geometric series

The sum 1+γ+γ2+γ3+…1 + \gamma + \gamma^2 + \gamma^3 + \dots, where each term is the one before times the same ratio, is a geometric series. When γ\gamma is between 0 and 1, it adds up to a finite number:

1+γ+γ2+γ3+⋯=11−γ1 + \gamma + \gamma^2 + \gamma^3 + \dots = \frac{1}{1 - \gamma}

Check it with easy numbers:

  • γ=0.5\gamma = 0.5: 1+0.5+0.25+0.125+⋯=21 + 0.5 + 0.25 + 0.125 + \dots = 2, and 1/(1−0.5)=21/(1 - 0.5) = 2. Each term fills half of the gap that's left to 2.
  • γ=0.9\gamma = 0.9: 1/(1−0.9)=101/(1 - 0.9) = 10.
  • γ=0.99\gamma = 0.99: 1/(1−0.99)=1001/(1 - 0.99) = 100.

The first nn terms add up to 1−γn1−γ\dfrac{1 - \gamma^n}{1 - \gamma}. As nn grows, γn\gamma^n shrinks to 0, which leaves 11−γ\dfrac{1}{1 - \gamma}.

This bounds every return. Say no reward is ever bigger than Rmax⁡R_{\max} in size. Then each term of GtG_t is at most γkRmax⁡\gamma^k R_{\max} in size, so

∣Gt∣≤Rmax⁡ (1+γ+γ2+… )=Rmax⁡1−γ|G_t| \le R_{\max}\,(1 + \gamma + \gamma^2 + \dots) = \frac{R_{\max}}{1 - \gamma}

In the coupon MDP, the rewards are between −0.5 and +1. With γ=0.9\gamma = 0.9, every return lies between −0.5×10=−5-0.5 \times 10 = -5 and 1×10=101 \times 10 = 10. 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 γ\gamma. 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 SS:

S=1+γ+γ2+γ3+…S = 1 + \gamma + \gamma^2 + \gamma^3 + \dots

Multiply every term by γ\gamma. Each term turns into the next one:

γS=γ+γ2+γ3+…\gamma S = \gamma + \gamma^2 + \gamma^3 + \dots

That's SS without its first term. So subtracting leaves only the first term:

S−γS=1(1−γ) S=1S=11−γ\begin{aligned} S - \gamma S &= 1 \\ (1 - \gamma)\, S &= 1 \\ S &= \frac{1}{1 - \gamma} \end{aligned}

The picture lays each term out as a block, end to end. The top row is SS. The bottom row is γS\gamma S: 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.

S = 1 + γ + γ² + … = 2.00γS = γ + γ² + … = 1.00S − γS = 1

(1 − γ)·S = 1, so S = 1/(1 − 0.50) = 2.00

Top: the blocks 1, γ, γ², … end to end, total S. Bottom: γ times the same, which is the same blocks without the first. The difference is one block of length 1, so (1 − γ)S = 1.

One condition hides in the argument: SS has to be a finite number before you subtract. That's true when 0≤γ<10 \le \gamma < 1. At γ=1\gamma = 1, S=1+1+1+…S = 1 + 1 + 1 + \dots grows forever, and "S−S=1S - S = 1" makes no sense.

How far ahead does the agent look?

The weight on a reward kk steps away is γk\gamma^k. Plot those weights, and you can see how far ahead the agent looks.

05101520253000.20.40.60.81steps ahead, kweight γᵏ 1/(1 − γ) = 10

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 γᵏ on rewards k steps ahead. The dashed line marks 1/(1 − γ), the effective horizon. Higher γ spreads the weight over many more steps.

The weights fade smoothly. There's no step where they suddenly stop. But the total weight is 1/(1−γ)1/(1 - \gamma): the same as giving full weight to 1/(1−γ)1/(1 - \gamma) steps and none after. That number is the effective horizon.

γ\gammaEffective horizon 1/(1−γ)1/(1-\gamma)Weight on the reward that far away
01only the next reward counts
0.520.52=0.250.5^2 = 0.25
0.9100.910≈0.350.9^{10} \approx 0.35
0.991000.99100≈0.370.99^{100} \approx 0.37

Things to notice:

  • At γ=0.9\gamma = 0.9 the agent looks about 10 steps ahead. The first 10 steps carry 1−0.910≈65%1 - 0.9^{10} \approx 65\% of all the weight.
  • At γ=0.99\gamma = 0.99 it looks about 100 steps ahead.
  • For γ\gamma 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 γ

γ\gamma 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 γ=0\gamma = 0 the agent sees only this week, and the coupon loses. At γ=0.9\gamma = 0.9 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 γ\gamma:

  • 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 1−γ1 - \gamma that the task suddenly stops for good. Then a reward kk steps away is still collected only with chance γk\gamma^k. Discounting with γ\gamma is then the same as plain adding up, on average.
  • The maths needs it. For continuing tasks, γ<1\gamma < 1 keeps returns finite.

This course uses γ=0.9\gamma = 0.9 for the grid and the coupon MDP. Episodic tasks that always end, such as the cliff walk, can use γ=1\gamma = 1, since their sums are finite anyway. Deep RL usually uses γ=0.99\gamma = 0.99: 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 γ=0.9\gamma = 0.9, 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 1−γ1 - \gamma. As γ\gamma gets close to 1, the result gets close to the average reward. For "never send a coupon", starting at A:

γ\gammaExpected return from ATimes 1−γ1 - \gamma
0.95.300.530
0.9945.90.459
0.999450.90.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:

Discounted returns, backwards
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 returns

Things to notice:

  • rewards[t] holds Rt+1R_{t+1}, the reward for step tt. The result's entry 0 is G0G_0, 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] with gamma=0.5 it 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 γk\gamma^k are one line, which gives a second way to get G0G_0: a dot product of rewards and weights.

The weights γᵏ and the effective horizon
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 0×1+0×0.5+4×0.25=10 \times 1 + 0 \times 0.5 + 4 \times 0.25 = 1, the same G0G_0.

Common misconceptions

"The first reward is discounted too." Rt+1R_{t+1} counts in full; the weights start at γ0=1\gamma^0 = 1. A reward two steps after it gets γ2\gamma^2, not γ3\gamma^3.

"γ = 0.99 is about the same as γ = 0.9." The horizon depends on 1−γ1 - \gamma. 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 γ=0.9\gamma = 0.9, 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 γ\gamma.

"γ = 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 Gt=Rt+1+γRt+2+γ2Rt+3+…G_t = R_{t+1} + \gamma R_{t+2} + \gamma^2 R_{t+3} + \dots scores everything that happens after step tt.
  • The discount factor γ\gamma between 0 and 1 makes sooner rewards count more. With γ=0.5\gamma = 0.5, rewards 0, 0, 4 give a return of 1.
  • Returns satisfy Gt=Rt+1+γGt+1G_t = R_{t+1} + \gamma G_{t+1}, so one backwards pass computes them all.
  • Episodic tasks end; continuing tasks don't. For continuing tasks, γ<1\gamma < 1 keeps the return finite: at most Rmax⁡/(1−γ)R_{\max}/(1 - \gamma).
  • The geometric series: 1+γ+γ2+⋯=1/(1−γ)1 + \gamma + \gamma^2 + \dots = 1/(1 - \gamma).
  • The effective horizon 1/(1−γ)1/(1 - \gamma) is about how far ahead the agent looks: 10 steps at γ=0.9\gamma = 0.9, 100 at γ=0.99\gamma = 0.99.
  • PyTorch names used: torch.tensor, torch.empty_like, torch.zeros, torch.arange and @ for the dot product.