Skip to content

Reinforcement Learning: An Introduction, Ch. 5–6 — Monte Carlo, Temporal-Difference Learning and Q-learning

main track #3corefundamentalbookrubric 11/122018 · MIT Press (2nd ed.), Ch. 5–6 · ~75 min

Richard S. Sutton, Andrew G. Barto

Read first: Reinforcement Learning: An Introduction, Ch. 3–4 — Value Functions, Bellman Equations and Dynamic Programming

Status

TL;DR. Dynamic programming needs a model of the environment. Real agents only have experience. Monte Carlo (MC) methods estimate a value by averaging actual returns, so they must wait until the episode ends. Temporal-difference (TD) methods update after one step, using the reward they saw plus their own estimate of the next state’s value: this is bootstrapping. The quantity they learn from, the TD error δt\delta_t, reappears in actor–critic methods, GAE and PPO. Q-learning applies the same idea to action values with a max in the target, which lets it learn the optimal policy from data collected by a different, exploratory policy.

Why it matters now. GRPO’s group-mean baseline is a Monte Carlo value estimate. PPO’s critic is trained with returns built from TD errors. Multi-turn agent methods such as ArCHer use an off-policy value learner at the turn level. Knowing the bias–variance trade between MC and TD is what lets you read those design choices.

Monte Carlo prediction (S&B Eq. 6.1, constant-α form). After an episode, move the estimate toward the observed return:

V(St)←V(St)+α[Gt−V(St)].V(S_t) \leftarrow V(S_t) + \alpha\left[G_t - V(S_t)\right].

The target GtG_t is an unbiased sample of vπ(St)v_\pi(S_t). Its weakness is variance: it contains every random reward and action until the end of the episode.

TD(0) prediction (Eq. 6.2). Replace the full return with one real reward plus the current estimate of what follows, which is the Bellman equation used as a sampled target:

V(St)←V(St)+α[Rt+1+γV(St+1)−V(St)],δt=Rt+1+γV(St+1)−V(St)(Eq. 6.5).V(S_t) \leftarrow V(S_t) + \alpha\left[R_{t+1} + \gamma V(S_{t+1}) - V(S_t)\right], \qquad \delta_t = R_{t+1} + \gamma V(S_{t+1}) - V(S_t) \quad \text{(Eq. 6.5)}.

In plain words, δt\delta_t is “how much better this step went than expected”: the reward you just got, plus what you now expect from where you landed, minus what you expected before the step. It can be computed immediately, so TD learns online and works on episodes that never end. The price is bias: if V(St+1)V(S_{t+1}) is wrong, the target is wrong.

MC error = sum of TD errors. If VV does not change during the episode, the Monte Carlo error splits into discounted TD errors (Eq. 6.6):

Gt−V(St)=∑k=tT−1γk−t δk.G_t - V(S_t) = \sum_{k=t}^{T-1} \gamma^{k-t}\, \delta_k .

Keep this identity in mind: GAE is exactly a way to choose how much of this sum to keep.

Control: Sarsa and Q-learning. To improve the policy without a model we learn action values. Sarsa (Eq. 6.7) uses the next action the agent actually takes, Q(St+1,At+1)Q(S_{t+1}, A_{t+1}), so it learns the value of the policy it follows (on-policy). Q-learning (Eq. 6.8) uses the best next action:

Q(St,At)←Q(St,At)+α[Rt+1+γmax⁡aQ(St+1,a)−Q(St,At)].Q(S_t, A_t) \leftarrow Q(S_t, A_t) + \alpha\left[R_{t+1} + \gamma \max_{a} Q(S_{t+1}, a) - Q(S_t, A_t)\right].

This is a sampled version of the Bellman optimality equation for q∗q_*. Because the target assumes greedy behaviour from the next step on, the data can come from any sufficiently exploratory policy, such as ε-greedy: Q-learning is off-policy. Taking a max over noisy estimates overestimates on average (maximization bias, §6.7); keeping two estimates and using one to choose and the other to evaluate (“double learning”) reduces it.

Off-policy Monte Carlo (§5.5) is the other route: reweight returns from a behaviour policy bb by the importance ratio ∏kπ(Ak∣Sk)/b(Ak∣Sk)\prod_k \pi(A_k \mid S_k)/b(A_k \mid S_k). This is the same correction as inverse-propensity scoring in counterfactual learning to rank, and the ratio is the same object PPO clips.

Monte Carlo, TD(0) and Q-learning targets on one episode One episode of the search-or-answer MDP: from Q the agent searches, paying 0.1, reaches E, answers, and receives reward 1. Monte Carlo updates V of Q toward the full return 0.8 after the episode ends. TD(0) updates V of Q right after the first step toward minus 0.1 plus 0.9 times V of E. Q-learning updates Q of Q and search toward minus 0.1 plus 0.9 times the largest action value in E. Q E ⊥ search, r = −0.1 answer, r = 1 Episode Monte Carlo target for V(Q) = −0.1 + 0.9 · 1 = 0.8 (whole return) waits until ⊥; unbiased, but carries all later noise TD(0) −0.1 + 0.9 · V(E) δ = target − V(Q) one real step, then trust the estimate (bootstrap) Q-learning −0.1 + 0.9 · max Q(E, ·) for Q(Q, search) max = act greedily next, so the data can be off-policy
Original sketch. What each method uses as its target on the search-or-answer MDP: MC waits for the full return, TD(0) bootstraps from V(E), Q-learning bootstraps from the best action value in E.

Search-or-answer MDP, γ = 0.9, all estimates start at 0, α = 0.5. The agent follows π₀ and sees three episodes:

  1. Q –search→ E –answer→ correct (rewards −0.1, then 1)
  2. Q –answer→ wrong (reward 0)
  3. Q –search→ E –answer→ wrong (rewards −0.1, then 0)
After episodeTD(0): V(Q), V(E)Constant-α MC: V(Q), V(E)
1δ = −0.1 → −0.05; δ = 1 → 0.5G = 0.8 → 0.4; G = 1 → 0.5
2δ = 0.05 → −0.025; 0.5G = 0 → 0.2; 0.5
3δ = −0.1 + 0.9 × 0.5 + 0.025 = 0.375 → 0.1625; δ = −0.5 → 0.25G = −0.1 → 0.05; G = 0 → 0.25

(True values under π₀: v(Q)=0.46v(Q) = 0.46, v(E)=0.8v(E) = 0.8. With only three episodes neither is close, and the sample-average MC estimate, V(Q)=(0.8+0−0.1)/3≈0.233V(Q) = (0.8 + 0 - 0.1)/3 \approx 0.233, V(E)=0.5V(E) = 0.5, is not much better.)

The interesting row is episode 3. MC lowers V(Q)V(Q) because this episode returned −0.1. TD raises V(Q)V(Q), because the step Q → E landed in a state it already believes is worth 0.5: the failure is blamed on the answer in E (whose δ is −0.5), not on the decision to search. That is credit assignment by bootstrapping, and it is right here because searching really is the better choice.

Q-learning on the same episodes. Episode 1: Q(Q,search)Q(Q,\text{search}) target =−0.1+0.9×max⁡(0,0)=−0.1= -0.1 + 0.9 \times \max(0, 0) = -0.1, giving −0.05; Q(E,answer)→0.5Q(E,\text{answer}) \to 0.5. Episode 2: Q(Q,answer)Q(Q,\text{answer}) target 0, stays 0. Episode 3: Q(Q,search)Q(Q,\text{search}) target =−0.1+0.9×0.5=0.35= -0.1 + 0.9 \times 0.5 = 0.35, giving −0.05+0.5×0.40=0.15-0.05 + 0.5 \times 0.40 = 0.15; Q(E,answer)→0.25Q(E,\text{answer}) \to 0.25. The greedy policy is already “search in Q”, even though the data came from a policy that answered half the time.

Sanity check of Eq. 6.6 with the true values: on episode 1, δ0=−0.1+0.9×0.8−0.46=0.16\delta_0 = -0.1 + 0.9 \times 0.8 - 0.46 = 0.16 and δ1=1−0.8=0.2\delta_1 = 1 - 0.8 = 0.2. Then δ0+0.9 δ1=0.34=G0−v(Q)=0.8−0.46\delta_0 + 0.9\,\delta_1 = 0.34 = G_0 - v(Q) = 0.8 - 0.46.

LLM token generation. A completion with a verifier reward is one Monte Carlo episode. Sampling several completions per prompt and averaging their rewards is a sample-average MC estimate of V(prompt)V(\text{prompt}); that is exactly the baseline in GRPO and RLOO. A PPO value head is trained toward targets built from TD errors along the tokens, and with only a terminal reward and γ = 1, the per-token TD error is just V(prefix+token)−V(prefix)V(\text{prefix} + \text{token}) - V(\text{prefix}) (plus the last-step reward). Token-level Q-learning over a 100k-word vocabulary is rarely used for fine-tuning; turn-level value learning is the more common off-policy route for agents.

A search agent. MC credit assignment says “the whole session was good or bad”. TD says “this particular query moved the estimated chance of success from 0.4 to 0.7”, which is a per-tool-call signal you can inspect. Q-learning lets you learn from logged sessions of an older agent (off-policy), the same situation as learning a ranker from production click logs, and it inherits the same need for enough exploration in the logs.

  • TD(0) converges to vπv_\pi in the tabular case under standard step-size conditions, and on the random-walk example it learns faster than constant-α MC (§6.2, Example 6.2).
  • Batch TD vs batch MC (§6.3): on the same finite data, batch MC finds the estimates that minimise squared error on the training returns, while batch TD finds the estimates that would be exactly correct for the maximum-likelihood model of the Markov process (the certainty-equivalence estimate). The book uses this to explain why TD tends to converge faster.
  • Cliff walking (Example 6.6): Q-learning learns the optimal path along the cliff but, while still exploring with ε-greedy, gets worse online returns than Sarsa, which learns a safer path. On-policy and off-policy optimise different things during learning.
  • Maximization bias (§6.7, Figure 6.5): Q-learning initially prefers a noisy bad action much more often than optimal; Double Q-learning is essentially unaffected.

§5.1–5.3 (MC prediction and control), §5.5 (importance sampling), §6.1–6.5 (TD prediction, Sarsa, Q-learning), §6.7 (maximization bias). Then skim Ch. 7 (n-step returns) and §11.3 (the deadly triad) before the DQN page.

  • Bias versus variance is a dial, not a choice. n-step and λ-returns interpolate; the best setting is task-dependent and rarely reported in LLM-RL papers.
  • Bootstrapping needs a decent value function. Early in training, or with a value head that cannot read long contexts well, TD targets can point the wrong way. This is one motivation for critic-free methods such as GRPO.
  • Off-policy agent data is cheap but risky. Learning from logged agent sessions mixes all three elements of the deadly triad; how far that can be pushed for LLM agents is still open.

Questions to think through

These questions have no single right answer. Write or say your answer before you open the hints. Mark a question once you could defend your answer in a reading group.

  1. Derive / compute

    In the search-or-answer MDP (γ = 0.9, values initialised to 0, step size α = 0.5), the agent sees three episodes: (1) search, then a correct answer; (2) answer directly, wrong; (3) search, then a wrong answer. Trace V(Q) and V(E) under TD(0) and under constant-α Monte Carlo. Explain why TD raises V(Q) after episode 3 even though that episode failed.

    What a strong answer covers
    • TD(0), episode 1: δ for Q is −0.1 + 0.9·0 − 0 = −0.1, so V(Q) = −0.05; δ for E is 1 − 0 = 1, so V(E) = 0.5. Episode 2: δ = 0 − (−0.05), so V(Q) = −0.025.
    • TD(0), episode 3: δ for Q = −0.1 + 0.9·0.5 + 0.025 = 0.375, so V(Q) = 0.1625; δ for E = 0 − 0.5, so V(E) = 0.25.
    • Constant-α MC uses the full returns 0.8, 0 and −0.1 for Q, and 1 and 0 for E: V(Q) goes 0.4 → 0.2 → 0.05, V(E) goes 0.5 → 0.25. The true values under π₀ are 0.46 and 0.8.
    • TD updates Q toward −0.1 + 0.9·V(E) using what it already learned about E (0.5 from episode 1), so reaching E counts as good news regardless of this episode's outcome. MC only sees that this episode returned −0.1.
  2. Mechanism

    Why is the TD(0) target R + γV(S′) biased but usually lower-variance than the Monte Carlo target G, and why can Q-learning learn optimal action values from data collected by an exploratory policy while Sarsa learns the values of the policy it actually follows?

    What a strong answer covers
    • The MC target is an unbiased sample of the return, but it sums every future random reward and action, so its variance grows with episode length.
    • The TD target contains one random reward and transition plus an estimate. It is biased whenever V(S′) is wrong, but it does not carry the noise of the rest of the episode.
    • Q-learning's target uses max over a′ of Q(S′, a′), the value of acting greedily next, whatever action the behaviour policy actually took. So it estimates q* (off-policy).
    • Sarsa's target uses Q(S′, A′) for the action actually taken next, so it estimates q of the behaviour policy, including its exploration (on-policy).
  3. Connect

    Counterfactual learning-to-rank reweights logged clicks by 1/propensity. Relate this to off-policy Monte Carlo with importance sampling (S&B §5.5): what plays the role of the behaviour and target policies, what is the ratio, and why does variance blow up for long episodes such as multi-turn search sessions?

    What a strong answer covers
    • Behaviour policy b = the production ranker or logging policy that produced the data; target policy π = the new ranker or agent being evaluated.
    • The importance ratio is the product over steps of π(A|S)/b(A|S). Weighting each logged return by it makes the average an unbiased estimate of the target policy's value (ordinary importance sampling, Eq. 5.5).
    • IPS in LTR is the one-step special case, with the examination propensity in the denominator.
    • For a session of many steps the ratio is a product of many terms, so a few trajectories get huge weights. Weighted importance sampling, clipping and per-step corrections trade variance for bias, the same move PPO's clipped ratio makes.
  4. What if…

    S&B §11.3 says instability arises when function approximation, bootstrapping and off-policy training are all present, and can be avoided if any one is removed. For a neural Q-learner trained on logged search-agent sessions, describe the three single-component ablations, predict what each does to stability and to what is learned, and say which one is practical.

    What a strong answer covers
    • Drop function approximation (tabular): stable, but impossible when every transcript is a new state.
    • Drop bootstrapping (regress on Monte Carlo returns): stable and unbiased for the logging policy, but higher variance, and without importance weights it learns the logging policy's values, not optimal values.
    • Drop off-policy (collect fresh data with the current policy, Sarsa-style targets): stable in the linear on-policy case, but expensive because every policy change needs new rollouts.
    • In practice none is dropped completely; DQN-style tricks (replay, a frozen target network) and n-step or λ targets reduce rather than remove the risk.
  5. Design

    You have 50,000 logged search-agent sessions with a judged final answer each. Design a TD-based value learner that scores every intermediate transcript, so you can tell which tool calls helped. Specify the state representation, the target, how you handle sessions cut off at the tool-call limit, and how you would validate the scores.

    What a strong answer covers
    • State: question plus transcript up to each tool call. Reward: the judged answer at the end, plus any per-call cost; 0 elsewhere.
    • Target: r + γ·V(next transcript), or an n-step / λ-return to reduce bias from a poor early V. Terminal states bootstrap from 0.
    • Truncated sessions are not terminal: bootstrap from V at the cut-off transcript instead of treating it as a zero-reward ending, or drop the final step from training.
    • The values are for the logging policy, not the optimal one; say so when interpreting them.
    • Validate: on held-out sessions, check calibration of V at each step against final outcomes, and check that the TD error at a tool call correlates with independently judged usefulness of what it retrieved.

Done with this page?

Status