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 , and derive , and from it.
- Define returns for episodic and continuing tasks, derive , and unify both kinds of task with an absorbing state.
- Compute effective horizons and truncation errors, and state when is allowed.
- Distinguish termination from truncation, and write the correct bootstrapped update against Gymnasium's
terminatedandtruncatedflags. - 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 At each step the agent observes the state and picks an action , drawn from its policy . The environment responds with a reward and a next state , drawn together from its dynamics
In Sutton and Barto's formulation this four-argument is the complete description of the environment. It depends only on , not on how the agent got there: that is the Markov property, the subject of Markov Decision Processes.
Sum out the reward to get the transition probabilities:
Average the reward over both outcomes to get the expected reward of an action, the of this course's MDP notation:
When the reward depends on where you land, condition on the next state as well. Averaging over recovers . (For continuous rewards the sums over are integrals.)
The agent's objective is to choose so that the expected return is large, for instance with . 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.
From state , action leads to with reward 4 (probability 0.5), to with reward 1 (probability 0.25), and to with reward 6 (probability 0.25). What are and ?
- and
- and
- and
- and
Show the answer
C. and
. Given that the next state is , which happens with probability 0.75, the reward is 4 with probability and 1 with probability , so . Check: .
Returns: episodes, continuing tasks and absorbing states
In an episodic task, interaction breaks into episodes that end at a random terminal time : a game ends, a robot reaches its goal or falls over. The return is then a finite sum, . 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:
Split off the first reward and factor out of the rest:
The bracket is the return from the next step:
In an episodic task set . The recursion then computes every return of an episode in one backward pass, work instead of . It is also the seed of every Bellman equation: take expectations of both sides and you arrive at Value Functions & the Bellman Equations.
| 3 | ||
| 2 | ||
| 1 | ||
| 0 |
A continuing task pays a reward of 1 on every other step, starting now: With , what is ?
Show the answer
5.26
. That is a little more than half of the 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: and , so .
How far ahead does γ look?
The weights sum to , the effective horizon, which has two precise readings. If every step ended the episode with probability , independently, the expected number of rewards collected would be exactly ; the Fixed Point lesson Discounting & Horizons develops this view. And it is the scale on which the weights decay: , so a reward steps away keeps only about of its weight.
Cut the return after rewards. With the tail is a geometric series:
For an error of at most , take logarithms. Because , the simpler condition on the right implies the exact one on the left:
So a horizon of a few effective horizons, times a logarithm, captures a discounted problem to accuracy . This is the depth that finite-horizon approximations and sample-based planners need, and each factor of in a bound is one horizon's worth of accumulated error.
| Steps holding 90% of the weight | Steps holding 99% of the weight | ||
|---|---|---|---|
| 0.9 | 10 | 22 | 44 |
| 0.95 | 20 | 45 | 90 |
| 0.99 | 100 | 230 | 459 |
| 0.999 | 1,000 | 2,302 | 4,603 |
A controller acts every 10 milliseconds and should weigh consequences over roughly the next 5 seconds. Which discount factor fits?
Show the answer
B.
Five seconds is 500 steps, so the effective horizon should be about 500: gives . Horizons are measured in decisions, not seconds, so the same task at a faster control rate needs a 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.
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 episodeTD(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 . Writing done instead of terminated in the target is a classic bug.
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?
- alone, because the episode is over
- 0, because truncated transitions should be thrown away
- , so that the estimate is left unchanged
- , because the pole is still up and the task could go on
Show the answer
D. , 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 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 to every reward of a continuing task changes nothing that matters. In an episodic task it can change everything.
Continuing task: every return shifts by the same amount, so the ranking of policies is untouched.
Episodic task ending at : the shift depends on the length of the episode, so policies whose episodes differ in length move by different amounts.
With shorter episodes gain, and with 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 ; the transition probabilities and the expected rewards and are its marginals and conditional means.
- Returns satisfy . An absorbing state turns episodic tasks into continuing ones, and is safe only when episodes end.
- The effective horizon sets the scale of discounting: truncating after steps loses at most .
- 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.
In an episode, , and . What is ?
Show the answer
D.
. The reward arrives on the step from to , so it is not discounted in ; everything in is discounted once more.
When can a task safely use ?
- Whenever the rewards are bounded
- When every policy under consideration ends the episode with probability 1, so that every return is a finite sum
- Only in continuing tasks
- Never: 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 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 with a negative living reward is one. In continuing tasks, is replaced by the average-reward criterion.
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?
- 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
- Nothing, because time-outs are rare
- The agent learns faster because its episodes are shorter
- 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: . 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).
A maze robot gets per step and at the exit, with . A colleague proposes adding to every reward to make the numbers nicer. What happens?
- Nothing changes, because adding a constant never matters
- The robot reaches the exit faster
- The step reward becomes 0, so the only remaining pressure toward short routes is the discounting of the exit reward, which is much weaker
- 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 , which depends on the episode length . With the step cost gone, a detour costs only a factor of 0.99 per step on the exit reward; with 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).