Simple Algorithm
Reinforcement Learning · Bootstrapping · 22 min

Agents, Environments & Rewards

The interaction loop, rewards and returns: the problem every RL method solves.

Every algorithm in this course solves one problem: an agent and an environment take turns, rewards arrive, and the agent tries to make their long-run sum large. This lesson pins that problem down: who produces what and when, how returns are defined for tasks that end and tasks that do not, how far ahead a discount factor looks, what to do when a time limit cuts an episode short, and how to write rewards that ask for what you actually want.

What you’ll learn

  • Write the interaction protocol with the dynamics p(s′,r∣s,a)p(s', r \mid s, a), and derive P(s′∣s,a)P(s' \mid s, a), r(s,a)r(s,a) and r(s,a,s′)r(s,a,s') from it.
  • Define returns for episodic and continuing tasks, derive Gt=Rt+1+γGt+1G_t = R_{t+1} + \gamma G_{t+1}, and unify both kinds of task with an absorbing state.
  • Compute effective horizons and truncation errors, and state when γ=1\gamma = 1 is allowed.
  • Distinguish termination from truncation, and write the correct bootstrapped update against Gymnasium's terminated and truncated flags.
  • Apply the basic rules of reward design: reward outcomes rather than methods, weigh sparse against dense rewards, and predict the effect of per-step rewards in episodic tasks.

The interaction protocol

Time runs in discrete steps t=0,1,2,…t = 0, 1, 2, \dots At each step the agent observes the state St∈SS_t \in \mathcal S and picks an action At∈A(St)A_t \in \mathcal A(S_t), drawn from its policy π(⋅∣St)\pi(\cdot \mid S_t). The environment responds with a reward Rt+1∈RR_{t+1} \in \R and a next state St+1S_{t+1}, drawn together from its dynamics

p(s′,r∣s,a)=Pr⁡(St+1=s′, Rt+1=r ∣ St=s, At=a).p(s', r \mid s, a) = \Pr\big(S_{t+1} = s',\ R_{t+1} = r \,\big|\, S_t = s,\ A_t = a\big).

In Sutton and Barto's formulation this four-argument pp is the complete description of the environment. It depends only on (s,a)(s, a), not on how the agent got there: that is the Markov property, the subject of Markov Decision Processes.

DerivationEverything else follows from p
  1. P(s′∣s,a)=∑rp(s′,r∣s,a)P(s' \mid s, a) = \sum_{r} p(s', r \mid s, a)

    Sum out the reward to get the transition probabilities:

  2. r(s,a)=E[Rt+1∣St=s,At=a]=∑s′∑rr  p(s′,r∣s,a)r(s,a) = \E\big[R_{t+1} \mid S_t = s, A_t = a\big] = \sum_{s'}\sum_{r} r\; p(s', r \mid s, a)

    Average the reward over both outcomes to get the expected reward of an action, the r(s,a)r(s,a) of this course's MDP notation:

  3. r(s,a,s′)=∑rr  p(s′,r∣s,a)P(s′∣s,a),r(s,a)=∑s′P(s′∣s,a)  r(s,a,s′)r(s,a,s') = \frac{\sum_r r\; p(s', r \mid s, a)}{P(s' \mid s, a)},\qquad r(s,a) = \sum_{s'} P(s' \mid s, a)\; r(s,a,s')

    When the reward depends on where you land, condition on the next state as well. Averaging r(s,a,s′)r(s,a,s') over s′s' recovers r(s,a)r(s,a). (For continuous rewards the sums over rr are integrals.)

The agent's objective is to choose π\pi so that the expected return is large, for instance J(π)=Eπ[G0]J(\pi) = \E_\pi[G_0] with S0∼μS_0 \sim \mu. Two decisions hide in that sentence: how to add up the rewards, which the rest of this lesson settles, and whether a single scalar reward can express the goal at all, which the Fixed Point lesson The Reward Hypothesis examines.

Check your understanding

From state ss, action aa leads to s1s_1 with reward 4 (probability 0.5), to s1s_1 with reward 1 (probability 0.25), and to s2s_2 with reward 6 (probability 0.25). What are r(s,a)r(s,a) and r(s,a,s1)r(s,a,s_1)?

  1. r(s,a)=3.75r(s,a) = 3.75 and r(s,a,s1)=2.25r(s,a,s_1) = 2.25
  2. r(s,a)=3.75r(s,a) = 3.75 and r(s,a,s1)=2.5r(s,a,s_1) = 2.5
  3. r(s,a)=3.75r(s,a) = 3.75 and r(s,a,s1)=3r(s,a,s_1) = 3
  4. r(s,a)=11/3r(s,a) = 11/3 and r(s,a,s1)=3r(s,a,s_1) = 3
Show the answer

C. r(s,a)=3.75r(s,a) = 3.75 and r(s,a,s1)=3r(s,a,s_1) = 3

r(s,a)=0.5⋅4+0.25⋅1+0.25⋅6=3.75r(s,a) = 0.5 \cdot 4 + 0.25 \cdot 1 + 0.25 \cdot 6 = 3.75. Given that the next state is s1s_1, which happens with probability 0.75, the reward is 4 with probability 0.5/0.75=2/30.5/0.75 = 2/3 and 1 with probability 1/31/3, so r(s,a,s1)=3r(s,a,s_1) = 3. Check: 0.75⋅3+0.25⋅6=3.750.75 \cdot 3 + 0.25 \cdot 6 = 3.75.

Returns: episodes, continuing tasks and absorbing states

In an episodic task, interaction breaks into episodes that end at a random terminal time TT: a game ends, a robot reaches its goal or falls over. The return is then a finite sum, Gt=Rt+1+Rt+2+⋯+RTG_t = R_{t+1} + R_{t+2} + \dots + R_T. In a continuing task, such as running a data center's cooling or a power grid, there is no end, the plain sum can diverge, and the return is discounted instead:

Gt=∑k=0∞γkRt+k+1,∣Gt∣≤Rmax⁡1−γ  when ∣Rt∣≤Rmax⁡ and 0≤γ<1G_t = \sum_{k=0}^{\infty} \gamma^k R_{t+k+1},\qquad \abs{G_t} \le \frac{R_{\max}}{1-\gamma}\ \ \text{when } \abs{R_t} \le R_{\max} \text{ and } 0 \le \gamma < 1
The geometric series bounds every return, and with it every value.
DerivationThe return recursion
  1. Gt=Rt+1+γRt+2+γ2Rt+3+⋯=Rt+1+γ(Rt+2+γRt+3+⋯)G_t = R_{t+1} + \gamma R_{t+2} + \gamma^2 R_{t+3} + \cdots = R_{t+1} + \gamma\big(R_{t+2} + \gamma R_{t+3} + \cdots\big)

    Split off the first reward and factor γ\gamma out of the rest:

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

    The bracket is the return from the next step:

  3. GT=0,GT−1=RT,GT−2=RT−1+γRT,…G_{T} = 0,\qquad G_{T-1} = R_T,\qquad G_{T-2} = R_{T-1} + \gamma R_T,\qquad \dots

    In an episodic task set GT=0G_T = 0. The recursion then computes every return of an episode in one backward pass, O(T)O(T) work instead of O(T2)O(T^2). It is also the seed of every Bellman equation: take expectations of both sides and you arrive at Value Functions & the Bellman Equations.

ttRt+1R_{t+1}Gt=Rt+1+γGt+1G_t = R_{t+1} + \gamma G_{t+1}
3888+0.5⋅0=88 + 0.5 \cdot 0 = 8
2000+0.5⋅8=40 + 0.5 \cdot 8 = 4
1−1-1−1+0.5⋅4=1-1 + 0.5 \cdot 4 = 1
0222+0.5⋅1=2.52 + 0.5 \cdot 1 = 2.5
An episode with rewards 2,−1,0,82, -1, 0, 8 and γ=0.5\gamma = 0.5, computed backward. Directly: 2−0.5+0+0.125⋅8=2.52 - 0.5 + 0 + 0.125 \cdot 8 = 2.5.
Predict before you look

A continuing task pays a reward of 1 on every other step, starting now: R1=1,R2=0,R3=1,R4=0,…R_1 = 1, R_2 = 0, R_3 = 1, R_4 = 0, \dots With γ=0.9\gamma = 0.9, what is G0G_0?

Show the answer

5.26

G0=1+γ2+γ4+⋯=1/(1−γ2)=1/0.19≈5.26G_0 = 1 + \gamma^2 + \gamma^4 + \cdots = 1/(1-\gamma^2) = 1/0.19 \approx 5.26. That is a little more than half of the 1/(1−γ)=101/(1-\gamma) = 10 earned by a reward on every step, because the rewards that remain are the earlier one of each pair. The recursion gives the same answer: G0=1+γG1G_0 = 1 + \gamma G_1 and G1=0+γG0G_1 = 0 + \gamma G_0, so G0=1+γ2G0G_0 = 1 + \gamma^2 G_0.

How far ahead does γ look?

The weights γk\gamma^k sum to 1/(1−γ)1/(1-\gamma), the effective horizon, which has two precise readings. If every step ended the episode with probability 1−γ1-\gamma, independently, the expected number of rewards collected would be exactly 1/(1−γ)1/(1-\gamma); the Fixed Point lesson Discounting & Horizons develops this view. And it is the scale on which the weights decay: γk=ekln⁡γ≈e−k(1−γ)\gamma^k = e^{k\ln\gamma} \approx e^{-k(1-\gamma)}, so a reward 1/(1−γ)1/(1-\gamma) steps away keeps only about e−1≈37%e^{-1} \approx 37\% of its weight.

DerivationTruncating the return
  1. ∣ G0−∑k=0H−1γkRk+1∣=∣∑k≥HγkRk+1∣≤γHRmax⁡1−γ\Big|\,G_0 - \sum_{k=0}^{H-1}\gamma^k R_{k+1}\Big| = \Big|\sum_{k \ge H}\gamma^k R_{k+1}\Big| \le \frac{\gamma^H R_{\max}}{1-\gamma}

    Cut the return after HH rewards. With ∣Rt∣≤Rmax⁡\abs{R_t} \le R_{\max} the tail is a geometric series:

  2. H ≥ ln⁡(Rmax⁡/(ε(1−γ)))ln⁡(1/γ)⟸H ≥ 11−γ ln⁡Rmax⁡ε (1−γ)H \ \ge\ \frac{\ln\big(R_{\max}/(\varepsilon(1-\gamma))\big)}{\ln(1/\gamma)} \quad\Longleftarrow\quad H \ \ge\ \frac{1}{1-\gamma}\,\ln\frac{R_{\max}}{\varepsilon\,(1-\gamma)}

    For an error of at most ε\varepsilon, take logarithms. Because ln⁡(1/γ)≥1−γ\ln(1/\gamma) \ge 1-\gamma, the simpler condition on the right implies the exact one on the left:

  3. So a horizon of a few effective horizons, times a logarithm, captures a discounted problem to accuracy ε\varepsilon. This is the depth that finite-horizon approximations and sample-based planners need, and each factor of 1/(1−γ)1/(1-\gamma) in a bound is one horizon's worth of accumulated error.

γ\gamma1/(1−γ)1/(1-\gamma)Steps holding 90% of the weightSteps holding 99% of the weight
0.9102244
0.95204590
0.99100230459
0.9991,0002,3024,603
The first HH steps hold a fraction 1−γH1-\gamma^H of the total weight. Each row needs about 2.3 and 4.6 effective horizons: ln⁡10\ln 10 and ln⁡100\ln 100.
Check your understanding

A controller acts every 10 milliseconds and should weigh consequences over roughly the next 5 seconds. Which discount factor fits?

  1. γ=0.99\gamma = 0.99
  2. γ=0.998\gamma = 0.998
  3. γ=0.9999\gamma = 0.9999
  4. γ=0.9\gamma = 0.9
Show the answer

B. γ=0.998\gamma = 0.998

Five seconds is 500 steps, so the effective horizon should be about 500: 1/(1−γ)=5001/(1-\gamma) = 500 gives γ=0.998\gamma = 0.998. Horizons are measured in decisions, not seconds, so the same task at a faster control rate needs a γ\gamma closer to 1.

Time limits: termination versus truncation

Episodes in practice end for two different reasons. Termination is part of the task: the pole fell, the game was lost, the goal was reached. No reward follows, and the value after it is 0. Truncation is a cutoff imposed from outside, usually a time limit that keeps training episodes short: the gridworld widget of this course stops episodes after 200 steps, and Gymnasium's CartPole-v1 after 500. The world did not end; you simply stopped watching.

Pardo, Tavakoli, Levdik and Kormushev (2018) separate two cases. If the time limit is part of the task, as in a game with a clock, the remaining time must be part of the state: otherwise two situations that look identical but have different time left are merged, and the state is not Markov. If the limit is only a training convenience, the last transition of a cut-off episode should still bootstrap from the value of the state it reached, exactly like any other step. Treating truncation as termination teaches the agent that the world ends at the limit.

python
import numpy as np
import gymnasium as gym

env = gym.make("FrozenLake-v1", is_slippery=True, max_episode_steps=50)
V = np.zeros(env.observation_space.n)      # one value per state
alpha, gamma = 0.05, 0.99

for episode in range(20_000):
    s, info = env.reset(seed=episode)
    done = False
    while not done:
        a = env.action_space.sample()               # evaluate the random policy
        s2, r, terminated, truncated, info = env.step(a)
        target = r if terminated else r + gamma * V[s2]   # no future after a real end
        V[s] += alpha * (target - V[s])             # TD(0) update
        s = s2
        done = terminated or truncated              # either way, start a new episode

TD(0) evaluation of the uniformly random policy on FrozenLake. Only terminated (the agent fell into a hole or reached the goal) cuts off the bootstrap; an episode truncated by the 50-step limit still backs up γV(s′)\gamma V(s'). Writing done instead of terminated in the target is a classic bug.

Check your understanding

A CartPole agent balances the pole for all 500 steps, and the episode ends with truncated=True and terminated=False. Which target should the TD update use for that last transition?

  1. Rt+1R_{t+1} alone, because the episode is over
  2. 0, because truncated transitions should be thrown away
  3. V(St)V(S_t), so that the estimate is left unchanged
  4. Rt+1+γV(St+1)R_{t+1} + \gamma V(S_{t+1}), because the pole is still up and the task could go on
Show the answer

D. Rt+1+γV(St+1)R_{t+1} + \gamma V(S_{t+1}), because the pole is still up and the task could go on

Truncation is not an outcome of the task: the next state is an ordinary state with an ordinary future, so the target bootstraps from it. Using Rt+1R_{t+1} alone would tell the agent that balancing for 500 steps leads nowhere, and the values of states near the limit would collapse.

Writing rewards

The reward is the only channel through which you tell the agent what you want, and the agent optimizes exactly that number. Three rules of thumb follow.

  • Reward outcomes, not methods. A chess agent should be rewarded for winning, not for taking pieces or controlling the center: rewarded for subgoals, it may achieve them at the expense of the real goal (Sutton & Barto, §3.2). Knowledge about how belongs in the initial policy, a model or a value estimate, not in the reward.
  • Sparse rewards are honest but hard to learn from. A sparse reward, paid only on success, says exactly what you want, but an agent that never succeeds by chance never learns anything. Dense rewards give a signal at every step and invite loopholes; the Fixed Point lesson Reward Shaping derives the one form of dense reward that provably cannot change the optimal policy.
  • Constants are not neutral in episodic tasks. Adding cc to every reward of a continuing task changes nothing that matters. In an episodic task it can change everything.
DerivationAdding a constant to every reward
  1. Gt′=∑k≥0γk (Rt+k+1+c)=Gt+c1−γG'_t = \sum_{k\ge0}\gamma^k\,(R_{t+k+1} + c) = G_t + \frac{c}{1-\gamma}

    Continuing task: every return shifts by the same amount, so the ranking of policies is untouched.

  2. G0′=∑k=0T−1γk (Rk+1+c)=G0+c 1−γT1−γG'_0 = \sum_{k=0}^{T-1}\gamma^k\,(R_{k+1} + c) = G_0 + c\,\frac{1-\gamma^{T}}{1-\gamma}

    Episodic task ending at TT: the shift depends on the length of the episode, so policies whose episodes differ in length move by different amounts.

  3. With c<0c < 0 shorter episodes gain, and with c>0c > 0 longer ones do: an agent that can avoid ending at all will. This per-step reward is the living reward of the gridworld below.

Key takeaways

  • The environment is a distribution p(s′,r∣s,a)p(s', r \mid s, a); the transition probabilities and the expected rewards r(s,a)r(s,a) and r(s,a,s′)r(s,a,s') are its marginals and conditional means.
  • Returns satisfy Gt=Rt+1+γGt+1G_t = R_{t+1} + \gamma G_{t+1}. An absorbing state turns episodic tasks into continuing ones, and γ=1\gamma = 1 is safe only when episodes end.
  • The effective horizon 1/(1−γ)1/(1-\gamma) sets the scale of discounting: truncating after 11−γln⁡Rmax⁡ε(1−γ)\frac{1}{1-\gamma}\ln\frac{R_{\max}}{\varepsilon(1-\gamma)} steps loses at most ε\varepsilon.
  • Termination ends the future; truncation does not. Bootstrap at a time limit, unless the remaining time is part of the state.
  • Reward outcomes, not methods. Sparse rewards are hard to learn from, dense ones easy to game, and per-step constants change optimal behavior in episodic tasks.

Check yourself

In the interactive lesson these are scored with your confidence, and what you miss comes back for review.

Question 1

In an episode, R3=3R_3 = 3, G3=4G_3 = 4 and γ=0.5\gamma = 0.5. What is G2G_2?

  1. 77
  2. 22
  3. 3.53.5
  4. 55
Show the answer

D. 55

G2=R3+γG3=3+0.5⋅4=5G_2 = R_3 + \gamma G_3 = 3 + 0.5 \cdot 4 = 5. The reward R3R_3 arrives on the step from t=2t = 2 to t=3t = 3, so it is not discounted in G2G_2; everything in G3G_3 is discounted once more.

Question 2

When can a task safely use γ=1\gamma = 1?

  1. Whenever the rewards are bounded
  2. When every policy under consideration ends the episode with probability 1, so that every return is a finite sum
  3. Only in continuing tasks
  4. Never: γ\gamma must be below 1
Show the answer

B. When every policy under consideration ends the episode with probability 1, so that every return is a finite sum

With γ=1\gamma = 1 the return is the plain sum of rewards, which is finite only if the episode ends. Stochastic shortest-path problems work with proper policies, which terminate with probability 1; the classic gridworld at γ=1\gamma = 1 with a negative living reward is one. In continuing tasks, γ=1\gamma = 1 is replaced by the average-reward criterion.

Question 3

You train with a 1,000-step time limit on a task that has no natural time limit, and you treat every time-out as a terminal state. What goes wrong?

  1. The agent is told that nothing follows a time-out, so the values of states visited near the limit are pulled toward the rewards collected before the cut instead of their long-run values
  2. Nothing, because time-outs are rare
  3. The agent learns faster because its episodes are shorter
  4. The returns become infinite
Show the answer

A. The agent is told that nothing follows a time-out, so the values of states visited near the limit are pulled toward the rewards collected before the cut instead of their long-run values

Truncation is not part of the task, so the target at a time-out should bootstrap: R+γV(S′)R + \gamma V(S'). Treating it as terminal injects a systematic error that depends on the time step, which the state does not show, so the targets look non-Markov to the learner (Pardo et al., 2018).

Question 4

A maze robot gets −1-1 per step and +10+10 at the exit, with γ=0.99\gamma = 0.99. A colleague proposes adding +1+1 to every reward to make the numbers nicer. What happens?

  1. Nothing changes, because adding a constant never matters
  2. The robot reaches the exit faster
  3. The step reward becomes 0, so the only remaining pressure toward short routes is the discounting of the exit reward, which is much weaker
  4. Nothing changes, because the exit reward is still the largest
Show the answer

C. The step reward becomes 0, so the only remaining pressure toward short routes is the discounting of the exit reward, which is much weaker

In an episodic task a constant per-step reward shifts each return by c(1−γT)/(1−γ)c(1-\gamma^T)/(1-\gamma), which depends on the episode length TT. With the step cost gone, a detour costs only a factor of 0.99 per step on the exit reward; with γ=1\gamma = 1 there would be no pressure to hurry at all.

Go deeper

  • The Reward Hypothesis · Can every goal be written as a sum of rewards? What Markov rewards can and cannot express.
  • Discounting & Horizons · What γ really means, the effective horizon, and the trouble with discounting.
  • Reward Shaping · Potential-based shaping, why it keeps optimal policies, and how shaping backfires.

Further reading

  • R. S. Sutton & A. G. Barto, Reinforcement Learning: An Introduction, ch. 3 (MIT Press, 2nd ed., 2018).
  • F. Pardo, A. Tavakoli, V. Levdik & P. Kormushev, "Time limits in reinforcement learning," ICML, PMLR 80, 4045–4054 (2018).
  • D. P. Bertsekas & J. N. Tsitsiklis, Neuro-Dynamic Programming, ch. 2 (Athena Scientific, 1996).