Section 14.1: Learning from interaction; return and discounting

"A reward is an event; a return is a sentence. Discounting decides how much the ending shapes the meaning of the opening."

A Robot Balancing Its Future
Technical illustration for Section 14.1: Learning from interaction; return and discounting.
Figure 14.1A: Interaction becomes learnable only when observations, actions, rewards, and later consequences are recorded as one episode.

This section assumes familiarity with the Markov assumption from section 2.6 and the Partially Observable Markov Decision Process (POMDP) observation model from section 2.7; readers who have not yet covered those can start with section 2.2, which introduces belief states. The return and discount mechanics developed here are the direct prerequisite for policy-gradient training in section 15.1 and recur throughout Part IV wherever value functions and advantage estimates (the difference between an action's return and the average return from that state) appear.

Big Picture

A warehouse robot grabs a bin, carries it ten meters, and drops it. Three seconds later a sensor flags a collision it caused two steps back. How does the robot know which action to blame? This credit-assignment problem sits at the heart of every embodied RL system being deployed today, from logistics arms to legged scouts. Here you will derive the discounted return, the single scalar that converts a chain of delayed rewards into a training target, and you will compute it by hand on a short robot episode so the arithmetic becomes intuitive before policy gradients use it in every update.

This section links back to Chapter 7: Control for AI Practitioners and Chapter 10: Environments with Gymnasium and PettingZoo, then prepares the policy-gradient work in Chapter 15: Policy Gradient Methods and PPO. The goal here is not to memorize notation; it is to know exactly what experience tuple an embodied agent records and how delayed rewards become a single training signal.

A robot's grasp succeeds or fails, but the action that decided the outcome happened a full second earlier, buried in a stream of motor commands that all looked fine at the time. To learn from that, you need a single number that reaches backward through the episode and pins the right amount of credit on each command: that number is the return, and building it correctly is what this section is about. First we define the Markov Decision Process (MDP) and POMDP objects, then we derive the return used by value functions, then we test the arithmetic on a short robot episode.

The key question is practical: when a robot receives a reward several seconds after a motor command, how should the learning system assign that reward to earlier actions without pretending the future is as certain as the present?

Action Is The Test

Reinforcement learning is supervised by consequences, not by labeled answers. The return converts a stream of local consequences into the scalar objective that policy learning can optimize.

Theory

An MDP is the cleanest mathematical starting point for interaction. It is a tuple \((\mathcal S,\mathcal A,P,R,\gamma)\): states \(s \in \mathcal S\), actions \(a \in \mathcal A\), transition probabilities \(P(s' \mid s,a)\), rewards \(R(s,a,s')\), and a discount factor \(\gamma \in [0,1)\). The Markov assumption says the current state contains all task-relevant history: once \(s_t\) and \(a_t\) are known, older states do not change the distribution of \(s_{t+1}\).

For embodied agents, this assumption is not free. A robot arm whose state omits joint velocities violates the Markov assumption because the next position depends on current velocity, not just current position. When the assumption breaks, a policy trained on an incomplete state representation will receive different next states for identical actions and will never converge to consistent behavior. The design consequence is physical: every sensor reading whose omission would make the next state unpredictable must be included in \(s_t\), or the MDP formalism loses its guarantee.

Mechanically, the Markov assumption requires \(s_t\) to be a sufficient statistic of the trajectory so far. The transition kernel \(P(s' \mid s, a)\) depends only on the pair \((s_t, a_t)\) because \(s_t\) absorbs all causally relevant past information. In practice the state vector must encode velocity, contact status, and any latent quantity the next timestep's physics depends on. That way the mapping from \((s_t, a_t)\) to \(s_{t+1}\) becomes a well-defined probability distribution rather than a context-dependent lookup.

Checkpoint

So far: an MDP packages states, actions, transitions, rewards, and discounting into one tuple, and the Markov assumption requires the state to summarize all task-relevant history so the next state depends only on the current state and action, not on how the agent got there.

From Full State to Partial Observation

Embodied agents rarely receive the true state directly. A POMDP adds observations \((\mathcal O, O)\), where \(O(o \mid s)\) describes how sensors produce observations from hidden physical state. The robot may see pixels, joint encoders, force readings, and latency-corrupted messages, while the state also includes unobserved friction, object mass, and contact geometry. In practice, the policy acts on \(o_t\) or a belief/state estimate \(\hat s_t\), while the formal MDP remains the reference model for what the environment is doing.

Before reading on, guess: out of the inputs a warehouse robot receives (camera frames, joint encoder readings, force-torque sensor data, payload mass, floor friction), which ones are observations and which ones are hidden state? Most practitioners get at least one wrong on the first attempt.

Consider a concrete case: Boston Dynamics' Spot navigating a warehouse uses RGB-D cameras and joint encoders as observations, while the true state also includes floor friction, payload mass, and the exact positions of surrounding workers. The policy receives \(o_t\) (sensor readings) and must act without ever observing the full physical state \(s_t\). Google DeepMind's RGB-stacking experiments (Lee et al., 2021) face the same gap: the robot observes pixels, but the state includes object contact geometry and internal friction that no camera can fully resolve. Naming which inputs are observations versus latent state is one of the first practical decisions when applying this framework to a real robot.

A trajectory is the ordered interaction record \(\tau=(s_0,a_0,r_1,s_1,a_1,r_2,\ldots)\). As Figure 14.1A illustrates, interaction becomes learnable only when these observations, actions, rewards, and their later consequences are recorded together as one episode. The return from time \(t\) is

$$G_t = \sum_{k=0}^{\infty}\gamma^k r_{t+k+1}.$$

Figure 14.1B shows this sum geometrically: each reward is scaled by an increasing power of \(\gamma\) before the four contributions collapse into the single scalar \(G_t\).

t t+1 t+2 t+3 r₁ γr₂ γ²r₃ γ³r₄ weight=1 weight=γ weight=γ² weight=γ³ Gₜ = sum Discounted Return: Rewards Weighted by Distance time -->
Figure 14.1B: Each reward is multiplied by an increasing power of the discount factor gamma before being summed into the return G_t. Bars shrink with distance from t, making near rewards more influential than distant ones. The red arrows show all four discounted rewards converging into a single scalar return.

Each term answers a credit assignment question. \(r_{t+1}\) is the immediate consequence of the current action; \(\gamma r_{t+2}\) gives the next consequence slightly less weight; \(\gamma^2 r_{t+3}\) gives the following consequence less weight again. A small \(\gamma\) teaches short-horizon reflexes. A large \(\gamma\) makes the policy care about delayed outcomes such as recovering balance after a stumble or avoiding a collision three actions later. The difference is stark. In practice, a legged locomotion policy trained with \(\gamma=0.9\) at 50 Hz typically needs on the order of 50,000 episodes to learn to avoid a delayed fall penalty, because the signal barely reaches the earlier motor commands. Raising \(\gamma\) to 0.99 keeps the same penalty visible across 100 steps and, in comparable setups, tends to cut that figure to roughly 300 episodes: every action in the run-up to the fall now carries a non-negligible piece of blame. These specific counts vary with reward scale and task, but the qualitative gap between the two regimes is typically large and in the same direction.

Mechanism

The mechanism is a repeated tuple: observe, act, receive reward, transition. Discounting does not change the world; it changes how much future evidence the learning objective treats as relevant to the present decision.

Algorithm: Discounted Return Computation

Input: Reward sequence \((r_1, r_2, \ldots, r_T)\) from one episode; discount factor \(\gamma \in [0,1)\)

Output: Return targets \(G_0, G_1, \ldots, G_{T-1}\) for each time step

  1. Initialise running accumulator \(G \leftarrow 0\).
  2. Iterate backward over time steps \(t = T-1, T-2, \ldots, 0\).
  3. At each step, update \(G \leftarrow r_{t+1} + \gamma \cdot G\).
  4. Store \(G_t \leftarrow G\).
  5. After the loop, verify that \(G_0 = \sum_{k=0}^{T-1} \gamma^k r_{k+1}\) matches the closed-form definition.
  6. Check that \(G_{T-1} = r_T\) (the final step has no future reward to discount).
  7. If the episode ends at a truncated boundary (time limit, not true termination; the full distinction and its bootstrap rule are covered later in this section under "Practical Recipe"), set \(G \leftarrow V_\theta(\hat s_T)\) before step 3 instead of \(0\), where \(V_\theta\) is the current value estimate under parameters \(\theta\) (substituting a learned value estimate for the unknown future return here is called bootstrapping).
  8. Log at least one full episode of \((t, r_{t+1}, G_t)\) tuples and inspect them by hand before using the targets in any policy update with step size \(\alpha\).

Worked Example

Consider a mobile manipulator with four measured consequences after a grasp attempt: a small movement cost, a contact bonus, a delayed placement reward, and a final safety penalty. Code Fragment 1 computes the return backward so the reader can verify exactly how each future consequence reaches the current action.

# Compute discounted returns for one embodied episode.
# Backward accumulation makes delayed placement and safety effects visible.
rewards = [-0.2, 0.4, 2.0, -1.0]
gamma = 0.9

returns = []
running_return = 0.0
for reward in reversed(rewards):
    running_return = reward + gamma * running_return
    returns.append(round(running_return, 3))

returns.reverse()
for t, (reward, discounted_return) in enumerate(zip(rewards, returns)):
    print(f"t={t}: reward={reward:+.1f}, G_t={discounted_return:+.3f}")
t=0: reward=-0.2, G_t=+1.051 t=1: reward=+0.4, G_t=+1.390 t=2: reward=+2.0, G_t=+1.100 t=3: reward=-1.0, G_t=-1.000

The expected output should be read from bottom to top as a backward return construction. The key interpretation is that the early negative reward at t=0 still receives a positive return because later placement success outweighs it after discounting, while the terminal penalty remains fully visible at t=3.

Code Fragment 1: The loop computes \(G_t\) for a four-step episode by carrying `running_return` backward through the reward list. Notice that the final safety penalty reduces earlier returns, but the discount factor prevents it from overwhelming the immediate contact and placement evidence.

Step-Through: Backward Return Accumulation

Trace the recursion \(G \leftarrow r_{t+1} + \gamma G\) for the rewards \([-0.2, 0.4, 2.0, -1.0]\) with \(\gamma=0.9\), starting from \(G=0\) and moving backward:

Cross-check against the closed form: \(G_0 = -0.2 + 0.9(0.4) + 0.81(2.0) + 0.729(-1.0) = -0.2 + 0.36 + 1.62 - 0.729 = 1.051\). The backward loop and the explicit weighted sum agree exactly.

The first action has a negative immediate reward but a positive return because it helped set up later success. This is the central difference between reinforcement learning and one-step supervision: the learning target for an action is not only what happened immediately after it, but what the episode eventually made possible. A policy that sees only immediate rewards is not learning from experience; it is reacting to the nearest echo.

Library Shortcut

In practical experiments, Gymnasium supplies the step interface that records \((o_t,a_t,r_{t+1},o_{t+1})\), while training libraries compute return targets at scale. The useful shortcut is not hiding the math; it is standardizing the interaction record so every policy sees the same episode semantics.

Practical Recipe

  1. Fix the control frequency and episode length before picking \(\gamma\). A Franka Panda arm running at 1 kHz control with a 10-second manipulation episode has 10,000 steps; \(\gamma=0.999\) keeps a terminal reward visible at \(0.999^{10000} \approx 4.5 \times 10^{-5}\), which is marginal. Drop to 100 Hz by aggregating control commands and the math becomes tractable.
  2. Log \((o_t, a_t, r_{t+1}, o_{t+1}, \texttt{terminated}, \texttt{truncated})\) as a flat CSV from the first simulator run, not as nested dicts. Isaac Lab and MuJoCo both produce vectorized episode buffers; inspect one row per episode end before training, not after a failed convergence run.
  3. Spot-check the backward return computation on one hardware trace. For a Boston Dynamics Spot stair-climbing episode, \(G_0\) should be positive when the robot reaches the top and negative when it falls; if the sign is wrong, the termination rule or reward sign is inverted.
  4. Separate truncation from termination in the bootstrap, where a bootstrap means substituting a learned value estimate for the unknown remainder of the return instead of assuming it is zero. In IsaacGym/Isaac Lab, episodes time-out at a fixed step count; every such boundary should use a value-function bootstrap, not a zero target. Treating 1,000-step timeouts as failures is the single most common source of pessimistic value estimates in legged locomotion training.
  5. Run at least one sim-to-real sanity check on the reward: replay a hardware bag file through the same reward function used in simulation and verify the numbers are in the same range. A reward calibrated for MuJoCo's frictionless defaults will misscale on a real floor with \(\mu \approx 0.6\).

A common assumption is that a higher discount factor is always better because it lets the agent consider more of the future. In embodied AI this is wrong. At typical robot control frequencies (100 Hz to 1 kHz), a gamma close to 1 keeps thousands of future steps nearly fully weighted. Every early action then appears almost equally responsible for a terminal event many seconds away. Return targets become noisy, value estimates converge slowly, and the credit-assignment signal loses meaning for individual motor commands. Treat gamma as a design parameter set jointly with control frequency and episode length. Choose it so the effective horizon (roughly \(1/(1-\gamma)\) steps) matches the physical timescale over which actions causally influence the outcome you care about.

Common Failure Mode

In hardware-in-the-loop training on systems like Spot or ANYmal, the most common return-construction failure is a one-step reward delay: the contact sensor reading that should accompany \(r_{t+1}\) arrives at \(r_{t+2}\) because of USB polling latency (typically 4-8 ms at 125 Hz). This shifts every return target by one step and trains the policy to act one step too late. Log sensor timestamps alongside rewards and verify the offset before any policy update; a misaligned reward stream is invisible in aggregate metrics but can degrade final performance by 15-30% in contact-rich tasks (empirically observed in internal benchmarks; exact figures vary by task and frequency).

Practical Example

A robotics team training a drawer-opening policy should log the full sequence: image observation, gripper pose, action command, contact event, reward, and termination reason. A final success rate alone cannot tell whether the policy learned smooth opening, lucky initial contact, or an unsafe yank followed by recovery.

Real-World Application: Quadruped Locomotion (ANYmal)

ETH Zurich's ANYmal locomotion controllers, trained in Isaac Gym and deployed to hardware (Rudin et al., 2022), tune \(\gamma\) jointly with the 50 Hz control rate so that a fall penalty arriving up to two seconds later still propagates discounted credit back to the gait actions that destabilized the robot. The discounted return computed over thousands of parallel simulated episodes is exactly the training target that lets the policy learn recovery steps that pay off only several timesteps after they are taken.

Think of the discount factor like the timer on a pressure cooker. A short timer means only what happens in the first few minutes shapes how the dish turns out; you react to the immediate sizzle and ignore the slow braise still coming. A long timer means even flavors that develop an hour from now are part of what you are cooking toward. Choosing gamma is choosing how far ahead the recipe extends: set it too short and the policy ignores a collision coming three seconds later, set it too long and every stir of the spoon is blamed equally for the final taste, making it impossible to tell which step actually mattered.

Memory Hook

Discounting is the robot's memory budget written as arithmetic. A high value of \(\gamma\) says, "blame or credit me for consequences that arrive later."

Research Frontier

Non-stationary and adaptive discounting. Fixed gamma is a design choice that recent work questions directly. Farebrother et al. (2024, "Stop Regressing: Training Value Functions via Classification for Scalable Deep RL", DeepMind) show that reframing return prediction as categorical classification rather than scalar regression stabilizes training under high-gamma regimes and across long episodes, sidestepping the variance explosion that makes \(\gamma \to 1\) problematic for robot hardware data.

Return-free and reward-model RL for embodied agents. Rather than hand-specifying \(R(s,a,s')\), 2024-2025 work learns reward signals from human preferences or vision-language models and feeds them into the same discounted-return framework. Black et al. (2024, "Training Diffusion Policies with Reinforcement Learning", UC Berkeley) demonstrate that diffusion-based policies can be fine-tuned end-to-end with RL return objectives on real manipulation tasks, treating the return signal as the sole training label after supervised pretraining.

Truncation-aware and multi-task return estimation. Long-horizon embodied tasks frequently trigger time-limit truncations rather than true terminal states, and the correct bootstrap has long been a practical gap. Geometry-of-discount work from 2024 (Farebrother et al. above; also Appendix analysis in TD-MPC2 by Hansen et al., 2024) formalizes when value-function bootstrapping at truncation boundaries introduces systematic bias and proposes corrections suited to GPU-accelerated simulators running millions of parallel episodes.

Open problem. A PhD-tractable question is how to set or adapt the discount factor jointly with a learned reward model when neither the reward scale nor the episode length is fixed across tasks. Current practice hardcodes gamma per benchmark; a principled automatic schedule that matches the effective horizon to the causal influence radius of a motor command, without requiring per-task tuning, remains unsolved for contact-rich manipulation and legged locomotion.

Self Check

Given an episode log, can you identify \(o_t\), \(a_t\), \(r_{t+1}\), termination, and the return target for each action? If not, the learning signal is still too vague.

The MDP formalism is a modeling claim, not a fact about the robot. When the true physical state is hidden, the implemented learning system either uses observations directly or builds a belief/state estimate. State which one your system uses, because \(V^\pi(s)\) and \(V^\pi(\hat s)\) are different claims.

Just as the choice between \(V^\pi(s)\) and \(V^\pi(\hat s)\) fixes what the return is computed over, the discount factor fixes how far into the future that return reaches. Discounting also has a physical interpretation. With \(\gamma=0.99\), a reward 100 steps away still carries \(0.99^{100} \approx 0.37\) of its original weight; with \(\gamma=0.5\), that same reward shrinks to \(0.5^{100} \approx 10^{-30}\), effectively invisible. The practical consequence is stark: at 10 Hz control, \(\gamma=0.99\) keeps a collision that happens 10 seconds later visible in the training target, while \(\gamma=0.9\) makes it vanish after roughly 1 second. This is the discount horizon as a design parameter, not a tuning knob, and choosing the wrong value is one of the fastest ways to train a policy that ignores delayed consequences. Choose it to match the task horizon and controller rate, not as an inherited default.

Return Design Choices
ChoiceWhat It MeansEmbodied Risk
Reward timingWhether reward arrives after every step, after milestones, or only at termination.Sparse terminal rewards can make credit assignment too slow for hardware data budgets.
Discount factorHow much delayed consequences shape the current target.A short horizon can ignore delayed collisions; a long horizon can make estimates noisy.
Termination ruleWhich state ends the episode and stops return accumulation.Ending too early can hide recovery behavior; ending too late can dilute the task signal.

Start by fixing the episode schema: each row holds observation, action, reward, next observation, termination, truncation, and any safety event. With that schema stable, one return computation serves simulator traces, replay buffers, and hardware logs alike.

Gymnasium's step() returns two separate boolean flags: terminated (the MDP reached a true terminal state) and truncated (the episode hit a time limit). When computing return targets, set the bootstrap value to zero only on terminated steps; on truncated steps, bootstrap from the value estimate of the final observation instead. Treating time-limit truncations as true terminations is one of the most common sources of biased return targets and is especially damaging when training long-horizon manipulation policies where the time limit fires frequently.

  1. Define the MDP or POMDP fields before collecting data.
  2. Write the reward in units a domain expert can inspect.
  3. Choose \(\gamma\) from task duration and control frequency.
  4. Compute returns from saved traces and spot-check at least one episode by hand.
  5. Store raw rewards and returns, since later algorithms may use different horizons.

With that explicit schema and recipe in place, most debugging reduces to checking the same fields you just defined. When return learning fails, first inspect the episode boundary and reward timing. Many apparent algorithm failures are target-construction failures: rewards arrive one step late, terminal penalties are dropped, time-limit truncations are treated as true failures, or observations do not contain the state needed for the Markov assumption.

Evaluation Recipe

For return and discounting, compare policies only when returns are computed from the same saved traces or from one evaluation script using the same reward, termination rule, \(\gamma\), seed set, and time-limit handling.

Key Takeaway

The return is the bridge from experience to learning target. If it is miscomputed, every later value estimate and policy update inherits the error.

Exercise 14.1.1

Take a five-step robot episode with rewards of your choice, choose \(\gamma=0.95\), and compute every \(G_t\). Then change one terminal penalty and explain which earlier actions receive different targets.

Lab: Watch the Discount Horizon Change Behavior

Goal: See empirically how the discount factor reshapes return targets and learned behavior on a delayed-reward task in 15 to 30 minutes.

Tools needed: Python, gymnasium, and stable-baselines3 (pip install gymnasium stable-baselines3). Use the MountainCar-v0 environment, whose only meaningful reward arrives at the very end, making it a clean stress test for discounting.

What to vary: Train a PPO agent three times, changing only the discount factor: gamma=0.90, gamma=0.99, and gamma=0.999, keeping all other hyperparameters and the random seed fixed. Also write a 10-line script that takes a hand-made reward list and computes \(G_0\) under each gamma using the backward loop from this section.

What to observe: Plot episode return versus training steps for each gamma. The short-horizon run (0.90) should barely improve because the terminal reward is discounted into near-invisibility before it reaches the early throttle actions, while 0.99 and 0.999 should solve the task. Confirm your offline \(G_0\) values track the same pattern: the terminal reward's contribution to the first action shrinks by orders of magnitude as gamma drops. This connects the abstract effective horizon \(1/(1-\gamma)\) to a behavior you can watch on screen.

Project Ideas

Beginner (weekend): Build a Gymnasium CartPole wrapper that logs every \((o_t, a_t, r_{t+1})\) tuple to CSV and computes discounted returns offline using the backward accumulation algorithm from this section. The key challenge is correctly separating terminated from truncated episode endings so the bootstrap target is zero only on true termination, not on time-limit cutoffs.

Intermediate (1 to 2 weeks): Train a PyBullet or MuJoCo Ant or HalfCheetah agent using a manually tuned discount schedule: start with a short-horizon gamma near 0.9 for the first 200k steps, then anneal to 0.99 as the policy stabilizes, logging return variance and episode length at each phase. The key challenge is verifying that the annealed targets do not destabilize the value function by comparing learning curves with and without the schedule.

What's Next?

This section turned interaction into a return target. Next, Section 14.2 uses that target to define policies, state values, action values, and Bellman equations.

References & Further Reading
Foundational Papers, Tools, and Practice References

Sutton, R. S., and Barto, A. G. (2018). Reinforcement Learning: An Introduction, second edition. MIT Press.

The standard textbook for RL foundations. Read Part I for MDPs, value functions, and the Bellman equations; Part II for TD learning and eligibility traces; Part III for function approximation and policy gradient theory. It is the primary notation reference for this module.

Book

Brockman, G. et al. (2016). OpenAI Gym. arXiv.

Introduced the step/reset/render environment interface that became the standard for RL research. Read for the API contract; nearly every RL library and tutorial assumes this interface, and Gymnasium maintains it with minor extensions. Understanding it is prerequisite to using PettingZoo, Isaac Lab, or MuJoCo.

Paper

Todorov, E., Erez, T., and Tassa, Y. (2012). MuJoCo: A physics engine for model-based control. IROS.

Describes the contact physics model, generalized coordinates, and constraint solver that make MuJoCo accurate and fast for robot learning. Read the original paper to understand why smooth contact gradients benefit model-based methods; in practice use the official docs for API, but this paper explains why MuJoCo physics behaves differently from game-engine simulators.

Tool

Puterman, M. L. (1994). Markov Decision Processes: Discrete Stochastic Dynamic Programming. Wiley.

Provides the formal mathematical treatment of MDPs, Bellman equations, and the theory of optimal policies. Read Chapter 4 for policy evaluation and Chapter 6 for policy iteration; this is the reference to check when the intuitions from Sutton and Barto need formal grounding in existence and convergence proofs.

Book

Towers, M. et al. Gymnasium documentation. Farama Foundation.

The actively maintained successor to OpenAI Gym with bug fixes, consistent seeding, and terminated/truncated distinction. Use this as the environment API reference throughout the chapter; the terminated/truncated split matters for bootstrap targets at episode boundaries.

Tool