Off-Policy Monte Carlo Methods and Introduction to Temporal Difference Learning
Prerequisite Knowledge
This lecture builds on the following concepts from earlier lectures. If any feel unfamiliar, review the linked notes before proceeding.
Previously Covered in This Subject
- Monte Carlo Methods — on-policy MC control, importance sampling, and ordinary vs. weighted estimators — covered in Lecture 7
- Value functions and policies — state-value and action-value functions under a policy — covered in Lectures 4 and 5
9.1 The Role of Reinforcement Learning in Modern AI
9.1.1 RL as the Foundation for Iterative Refinement
Key terms:
- Agent: the learner/decision-maker
- Environment: everything the agent interacts with
- State : the situation the agent is in
- Action : what the agent can do
- Reward : scalar feedback at time
- Return : cumulative (possibly discounted) sum of future rewards:
- Policy : probability of taking action in state
Reinforcement Learning has become the foundation for almost all modern AI tasks. A few years ago, RL use cases were limited to domains like thermal power plant control — using sensors to measure physical parameters and using RL to keep them in control. Today, RL applications are far more prevalent.
Consider an information retrieval pipeline: you submit a query, the system tries to understand the query, decomposes it, fetches relevant documents, and ranks them so the most relevant appears at the top. With LLMs and RAG (Retrieval-Augmented Generation), there is a need to iteratively refine results. Iterative refinement — keep improving performance — is where RL comes in.
Even LLM training pipelines now use RL. There are algorithms like DPO (Direct Preference Optimization), but without understanding the basics of RL, it is impossible to adapt such algorithms to specific requirements. Unlike classic algorithms like quicksort — which are done, tested, and simply called — modern RL algorithms are recent and often need to be adapted to particular scenarios. This is why foundations are critical.
- A language model generates a response (action).
- A human rates the response as helpful or unhelpful (reward).
- A reward model is trained to predict human preferences.
- The LLM's policy is updated using RL (specifically PPO) to maximize the predicted reward.
- The cycle repeats, and the LLM becomes increasingly aligned with human preferences.
- The agent interacts with an environment sequentially
- Feedback comes as scalar rewards (not full labels)
- The goal is to maximize long-term cumulative reward
- The environment may be unknown (model-free setting)
Visual Intuition: Picture the RL loop as a circle: Agent → Action → Environment → Reward + New State → Agent (update) → ... This agent-environment interaction loop is the central diagram of RL. The agent sits on one side, the environment on the other. The only communication channels are actions (agent → environment) and observations + rewards (environment → agent). Every RL algorithm, from the simplest bandit to the most complex LLM trainer, fits this loop.
9.2 Agenda Overview
The plan for this session covers four core topics:
- Quick recap of on-policy Monte Carlo methods — the self-made learner that both generates and learns from its own experience.
- Foundations of off-policy Monte Carlo methods — separating the explorer (behavior policy) from the learner (target policy) via importance sampling.
- Ordinary vs. Weighted Importance Sampling & Control — statistical properties, the infinite variance proof, incremental implementation, and control algorithms.
- Advanced Off-Policy Ideas & Introduction to Temporal Difference (TD) learning — discounting-aware & per-decision IS, real-world applications, and the bridge to TD.
9.3 Recap: On-Policy Monte Carlo Methods
9.3.1 What Are Monte Carlo Methods?
9.3.2 Policy Evaluation with MC
9.3.3 Symbol Registry — On-Policy MC Control
| Symbol | Meaning | Type |
|---|---|---|
| Policy — mapping from states to action probabilities | Function | |
| Action-value function — expected return from state taking action | Scalar | |
| List of all returns observed for pair | List | |
| Return — cumulative (possibly discounted) sum of rewards: | Scalar | |
| Discount factor — trades off immediate vs future rewards | Scalar |
9.3.4 On-Policy First-Visit MC Control Algorithm
Initialize π as an arbitrary ε-soft policy
Initialize Q(s,a) arbitrarily for all s, a
Initialize Returns(s,a) as empty list for all s, a
Repeat forever:
Generate an episode S_0, A_0, R_1, S_1, A_1, R_2, ..., S_T using π
G ← 0
For t = T-1 down to 0:
G ← γ * G + R_{t+1}
Unless (S_t, A_t) appears in S_0, A_0, ..., S_{t-1}, A_{t-1}:
Append G to Returns(S_t, A_t)
Q(S_t, A_t) ← average(Returns(S_t, A_t))
A* ← argmax_a Q(S_t, a)
For all a in A(S_t):
π(a|S_t) ← { 1 - ε + ε/|A| if a = A*
{ ε/|A| otherwise
9.4 Motivation for Off-Policy Learning
9.4.1 The Two-Role Tension & Decoupling
Off-policy learning solves the exploration-exploitation tension by decoupling the agent into two separate policies:
| Policy | Role | Description |
|---|---|---|
| Behavior policy | Teacher / Explorer | Generates experience. Can bring prior knowledge, safety norms, constraints. Soft policy (). |
| Target policy | Learner / Optimizer | The policy being evaluated or improved. Starts arbitrary, converges to greedy/optimal. |
9.4.2 Coverage Assumption
9.5 Foundations of Importance Sampling
9.5.1 General Expectation Transformation & Proof Idea
9.5.2 Trajectory Probability and Model Dynamics Cancellation
9.5.3 Symbol Registry — Importance Sampling
| Symbol | Meaning | Type |
|---|---|---|
| Trajectory segment | Sequence | |
| Behavior policy probability of action in state | Scalar | |
| Target policy probability of action in state | Scalar | |
| Importance sampling ratio covering time steps through | Scalar | |
| Environment transition probability (cancels out in ) | Scalar |
9.5.4 Numerical Worked Example: Trajectory Probability & Ratio
9.6 Off-Policy Prediction: First-Visit vs. Every-Visit & Estimators
9.6.1 Visit Set Notation: vs.
To evaluate across multiple episodes, we collect the time steps at which state is visited:
- : The set of all time steps in all episodes at which (Every-Visit collection).
- : The set of only the first time step in each episode at which (First-Visit collection).
For instance, if one episode visits states , then receives two time indices from that episode, whereas receives only the first index.
9.6.2 Ordinary vs. Weighted Importance-Sampling Estimators
1. Ordinary Importance-Sampling Estimator (): Simple arithmetic average of importance-weighted returns. Divided by total visit count .
2. Weighted Importance-Sampling Estimator (): Weighted average normalized by the sum of importance ratios.
9.6.3 Numerical Comparison: First-Visit vs. Every-Visit Returns
Let observed returns be and . Let suffix ratios be and .
First-Visit Ordinary IS: Uses only the first visit (): Every-Visit Ordinary IS: Uses both visits ( and ): First-Visit Weighted IS: Every-Visit Weighted IS:
9.7 Off-Policy Prediction Worked Examples
9.7.1 Example 1: Long-Trajectory Weighting Can Dominate
| State | ||||||
|---|---|---|---|---|---|---|
| 0.6 | 0.3 | 0.1 | 0.3 | 0.4 | 0.3 | |
| 0.2 | 0.5 | 0.3 | 0.4 | 0.3 | 0.3 |
Two episodes starting from are observed under :
Episode 1:
Episode 2:
Ordinary Importance Sampling Estimate: Weighted Importance Sampling Estimate: Takeaway: Ordinary IS is pulled up to (far outside the range of observed returns ) because Episode 1 received a large ratio. Weighted IS normalizes by total weight, yielding a stable, bounded estimate of .
9.7.2 Example 2: Short Trajectory Calculation
- Episode 1: ; .
- Episode 2: ; .
Ordinary IS Estimate: Weighted IS Estimate:
9.7.3 Worked Grid-World Example
Trajectory : Trajectory : Weighted IS estimate for :
9.8 Bias, Variance, and Infinite Variance in Off-Policy Estimation
9.8.1 Empirical MSE Analysis: Reading the Blackjack Plot
In Sutton & Barto (Figure 5.4), state-value estimation in off-policy Blackjack is analyzed by plotting Mean-Squared Error (MSE) against the number of episodes (log scale):
- Ordinary Importance Sampling (Green Curve): Unbiased for first-visit MC, but starts with high error and exhibits extreme variance spikes even after millions of episodes. A single high-ratio trajectory can drastically distort the estimate.
- Weighted Importance Sampling (Red Curve): Biased in early finite samples due to random normalization, but error drops rapidly and smoothly. In practice, its variance is dramatically lower.
9.8.2 Summary Comparison Table
| Property | Ordinary Importance Sampling | Weighted Importance Sampling |
|---|---|---|
| Finite-sample Bias | Unbiased (for First-Visit MC) | Biased (due to random denominator ) |
| Variance | Can be extremely high; unbounded / infinite | Much lower; bounded by return range when returns bounded |
| Asymptotic Behavior | Consistent, but practically unstable | Bias asymptotically; highly preferred in practice |
| Denominator | Episode count | Cumulative sum of weights |
9.8.3 Formal Mathematical Proof of Infinite Variance
- Action transitions to terminal state with reward .
- Action transitions back to state with reward with probability , and to terminal state with reward with probability .
- Target policy : Always chooses (). Under with , .
- Behavior policy : Chooses and with equal probability ().
Consider episodes that consist of consecutive actions followed by termination with reward .
Under behavior policy , the probability of observing an episode with actions ending in reward is: The importance sampling ratio for such an episode is: The return for this episode is . Thus, .
Evaluating the Second Moment : Because the second moment diverges to infinity, the variance .
Conclusion: Ordinary importance sampling has infinite variance in this simple MDP. This formally proves why ordinary IS can fail to converge in finite time, necessitating Weighted Importance Sampling.
9.9 Incremental Implementation of Weighted Importance Sampling
9.9.1 Incremental Derivation
The weighted estimate after returns is: Let be the cumulative sum of weights. The update rule for upon receiving weight and return is: where with .
9.9.2 Numerical Step-by-Step Trace
| Observation | Cumulative Weight | Incremental Update Formula | New Estimate |
|---|---|---|---|
| 5.0 | |||
| 4.0 | |||
| 4.0 |
Verification with Batch Calculation: The incremental update matches the batch result exactly!
9.10 The Off-Policy MC Control Algorithm
9.10.1 Deterministic Target Policy & Break Condition
The Break Condition: If , the algorithm immediately exits the inner episode loop. Earlier state-action pairs in that episode receive weight , so no further updates are performed for that episode.
9.10.2 Algorithm Pseudocode
Initialize, for all s ∈ S, a ∈ A(s):
Q(s, a) ∈ ℜ (arbitrarily)
C(s, a) ← 0
π(s) ← argmax_a Q(s, a)
Loop forever (for each episode):
b ← any soft policy with coverage of π
Generate an episode using b: S_0, A_0, R_1, S_1, A_1, R_2, ..., S_T
G ← 0
W ← 1
Loop for each step of episode, t = T-1, T-2, ..., 0:
G ← γ * G + R_{t+1}
C(S_t, A_t) ← C(S_t, A_t) + W
Q(S_t, A_t) ← Q(S_t, A_t) + (W / C(S_t, A_t)) * [G - Q(S_t, A_t)]
π(S_t) ← argmax_a Q(S_t, a)
If A_t ≠ π(S_t) then exit inner loop
W ← W * (1 / b(A_t | S_t))
9.10.3 Worked Walkthrough: Line World Control
Episode 1 under :
Backward scan ():
- At (): . . .
- At (): . . Since , continue! .
- At (): . .
Episode 2 under :
- At : .
- At : .
- Target policy check at : .
- Observed action Exit inner loop!
Result: The target policy learns optimal deterministic path , ignoring sub-optimal exploratory actions taken by .
9.10.4 Worked Walkthrough: Five-State Grid Control
Episode 1: .
Episode 2: . At , greedy choice is (). Action inner loop breaks! Target policy keeps .
9.11 Advanced Off-Policy Ideas
9.11.1 Discounting-Aware Importance Sampling
Standard importance sampling applies a single ratio to the entire return . If and episodes are long, late rewards have negligible impact on , but their action ratios still multiply into , inflating variance unnecessarily. Discounting-aware IS decomposes the return by horizon to omit ratios for heavily discounted future steps.
9.11.2 Per-Decision Importance Sampling
9.12 Real-World Applications of Off-Policy Learning
9.12.1 Logged Recommendation Systems
In industrial recommendation (e.g., YouTube/Netflix), historical logs were generated by a production recommender (behavior policy ). The target policy is a new neural model. Off-policy correction reweights logged clicks/watch-time to eliminate popularity bias and train without live user risk.
9.12.2 Logged Bandit Feedback in Healthcare & Advertising
In medical treatment evaluation, historical treatments were chosen by clinicians (behavior policy). Evaluating a new treatment policy from medical records requires importance sampling to adjust for doctor preferences. Doubly robust estimators combine IS with outcome modeling for ultra-low variance.
9.13 Student Questions and Answers
A (Professor): Think of three entities: teacher (behavior ), learner (target ), and exam authority (environment rewards). The teacher acts and gets a return. As the learner, you reason: "The teacher took these actions and earned this return. But I act differently — taking some actions more often and others less." If you would take an action more often than the teacher, multiply by a factor . If less often, multiply by . That factor is .
A (Professor): Target policy is greedy with respect to . Behavior policy collects experience. After each episode, we update using importance-weighted returns from , and re-orient greedily towards the updated . Thus, improves continuously and can surpass .
9.14 Introduction to Temporal Difference (TD) Learning
| Method | Target | Waits for | Bootstraps? |
|---|---|---|---|
| Dynamic Programming (DP) | Nothing (1-step lookahead) | Yes | |
| Monte Carlo (MC) | (full episode return) | End of episode | No |
| Temporal Difference (TD) | One step | Yes |
9.15 Review Questions and Practice Problems
Solution: On-policy learning evaluates/improves the same policy that generates the data. Off-policy learning evaluates/improves a target policy using data generated by a separate behavior policy .
Solution: for all . If when , the behavior policy will never sample action , leaving no data to estimate its value under .
Solution: . The transition probabilities are identical in numerator and denominator.
Solution: .
Solution: . .
Solution: Ordinary IS divides by (episode count) instead of the sum of weights. A single trajectory with a large inflates the numerator without scaling the denominator, pulling the average far above any observed return.
Solution: Episode . First-visit uses only the first occurrence of (). Every-visit uses both occurrences ( and ).
Solution: The denominator is a random variable, introducing finite-sample bias. However, normalization bounds estimates to the range of returns, dramatically reducing variance compared to Ordinary IS.
Solution: In the 1-state MDP, taking left actions yields ratio with probability . The second moment , proving variance is infinite.
Solution: Target policy is deterministic greedy. If , then , making for all earlier time steps. Further updates in that episode would have zero weight.
Solution: Per step ratio . For 3 steps, .
Solution: At : . At : . At : .
Solution: Trajectory IS applies the full ratio to the whole return. Per-decision IS applies ratios only up to each reward's step ( for ), reducing variance.
Solution: State : user context/history. Action : recommended item slate. Reward : click/watch time. Behavior : old recommender. Target : new model. Importance sampling corrects for historical recommendation bias.
Solution: Behavior policy represents past doctor decisions. Target policy is a new treatment guideline. Off-policy evaluation measures 's expected clinical outcome without executing untested treatments on live patients.
9.16 Exam Guidance Summary
- Manual calculation: Multiply per-step ratios . Remember dynamics cancel out!
- OIS vs WIS formulas: OIS divides by ; WIS divides by .
- Off-Policy Control Scan: Work right-to-left, update , , and break immediately if .
- Infinite Variance Proof: Be prepared to write down the 1-state MDP geometric series summation .
9.17 Key Takeaways
- Off-policy learning decouples exploration (behavior policy ) from optimization (target policy ).
- Importance sampling corrects distribution mismatch via ratio ; environment transition probabilities cancel completely.
- Weighted IS is far more stable than Ordinary IS because normalization bounds returns and eliminates infinite variance issues in practice.
- Off-Policy MC Control uses weighted incremental updates and breaks backward scans on action mismatch.
- Per-decision IS reduces variance by scaling each reward only by action ratios up to its arrival.
- TD learning updates after every single step using bootstrapping .
9.18 Required Reading & References
Required Textbook Reading: Sutton, R. S., and Barto, A. G. (2018). Reinforcement Learning: An Introduction (2nd ed.). MIT Press. Chapter 5 (Sections 5.5 to 5.7 required; Sections 5.8 to 5.9 optional).
- Sutton, R. S., & Barto, A. G. (2018). Reinforcement Learning: An Introduction (2nd ed.). MIT Press.
- Precup, D., Sutton, R. S., & Singh, S. (2000). Eligibility traces for off-policy policy evaluation. Proceedings of ICML 2000.
- Dudik, M., Langford, J., & Li, L. (2011). Doubly robust policy evaluation and learning. Proceedings of ICML 2011.
- Chen, M., Beutel, A., Covington, P., Jain, S., Belletti, F., & Chi, E. (2019). Top-K off-policy correction for a REINFORCE recommender system. Proceedings of WSDM 2019.
- Sutton, R. S., Mahmood, A. R., Precup, D., & van Hasselt, H. (2014). A new Q() with interim forward view and Monte Carlo equivalence. Proceedings of ICML 2014.
DRL Lecture 9 notes · Off-Policy Monte Carlo Methods and Introduction to Temporal Difference Learning
Sections Breakdown
Foundation of RL as trial-and-error learning, the agent-environment loop, iterative refinement in RAG, and LLM alignment with RLHF and DPO.
Roadmap: on-policy MC recap, off-policy MC with importance sampling, infinite variance proof, off-policy control, and introduction to TD learning.
Complete review of MC methods — policy evaluation, first-visit vs every-visit MC, MC control algorithm, symbol registry, and the exploration-exploitation tension.
Decoupling exploration from optimization using separate behavior and target policies, safety constraints, learning from logs, and the coverage condition.
General expectation transformation, trajectory probabilities, cancellation of transition dynamics, model-free ratio derivation, and a 3-decision numerical calculation.
Visit set notation T_FV(s) vs T_EV(s), generic summation formulas for Ordinary IS and Weighted IS, and a complete numerical comparison.
Long-trajectory weighting dominance example (States X, Y with 3 actions), short-trajectory calculation, and grid-world state evaluation.
Empirical Blackjack MSE plot analysis, Ordinary vs Weighted IS comparison table, and the formal mathematical proof of infinite variance in a 1-state MDP.
Mathematical derivation of incremental weighted updates with cumulative weight C_n and a detailed numerical step-by-step update table.
Deterministic target policy assumption, break condition rationale, full pseudocode, Line-World control trace, and Five-State Grid control trace.
Discounting-aware IS for long horizon returns and per-decision IS for variance reduction.
Logged recommendation systems (Chen et al. 2019 WSDM) and logged bandit feedback in healthcare/advertising (Dudik et al. 2011 ICML).
In-depth clarifications on importance sampling intuition and target policy improvement from behavior policy experience.
TD(0) update rule, TD target, TD error, comparison table (DP vs MC vs TD), and why TD is foundational to modern RL.
15 comprehensive exam-ready review questions covering all aspects of off-policy MC methods with step-by-step solutions.
Key exam skills: manual rho computation, ordinary vs weighted IS formulas, off-policy algo trace, and understanding variable meanings.
Distilled takeaways spanning on-policy MC, off-policy MC, importance sampling, weighted IS, infinite variance, and TD preview.
Required reading from Sutton & Barto Chapter 5 and academic citations (Precup et al., Dudik et al., Chen et al., Sutton et al.).
Exam Revision Notes
Below is the distilled, exam-ready core of this lecture. Use this section for rapid review before tests.
On-Policy Monte Carlo Methods
Must-know: On-policy MC evaluates a policy by averaging complete returns from sampled episodes. The same policy both generates experience and learns from it. First-visit MC is unbiased.
Top pitfall: Confusing on-policy and off-policy — the presence of importance weights and cumulative sum signals off-policy.
Self-check: Why must the behavior policy in on-policy MC be -soft, and what would happen if it were purely greedy?
Connects to: Off-Policy MC, MC algorithm trace
Off-Policy Learning and Importance Sampling
Must-know: Off-policy learning separates behavior policy from target policy . The importance sampling ratio corrects for distribution mismatch while transition probabilities cancel out.
Top pitfall: Computing from the episode start instead of from the relevant step onward.
Self-check: If , compute for trajectory .
Connects to: Weighted IS, Coverage condition
Ordinary vs. Weighted Importance Sampling
Must-know: Weighted importance sampling is preferred in practice — denominator uses sum of weights not . Yields dramatically lower variance with negligible initial bias.
Top pitfall: Using ordinary IS formula when weighted IS is required, or using as denominator of weighted IS.
Self-check: Two episodes give and . Compute both ordinary and weighted IS estimates.
Connects to: Incremental average updates, Infinite Variance Proof
Proof of Infinite Variance in Ordinary IS
Must-know: Ordinary IS can have infinite variance even in simple 1-state MDPs because the second moment contains a diverging geometric series .
Top pitfall: Thinking infinite variance means the estimator is mathematically biased; ordinary IS is unbiased but practically unusable due to extreme variance.
Self-check: Why does weighted IS avoid infinite variance in the 1-state example?
Connects to: Ordinary IS, Weighted IS
Off-Policy MC Control Algorithm
Must-know: Processes episodes right-to-left, accumulating and . Updates via weighted incremental average. Breaks when action disagrees with deterministic target policy.
Top pitfall: Forgetting to add to before updating , or updating after hitting the break condition.
Self-check: In Line-World control, why does an episode starting with action Left cause the inner loop to exit immediately?
Connects to: Weighted importance sampling, Deterministic target policy
Per-Decision & Discounting-Aware Importance Sampling
Must-know: Per-decision IS applies importance weights only up to each reward's step: , eliminating unnecessary variance from later action ratios.
Top pitfall: Multiplying early rewards by full trajectory ratios when using per-decision IS.
Self-check: Why does per-decision IS reduce variance compared to standard trajectory-level IS?
Connects to: Variance reduction, Discounting-aware IS
Temporal Difference (TD) Learning
Must-know: TD updates after every single step using bootstrapped target . Combines MC's model-free learning with DP's bootstrapping.
Top pitfall: Confusing the TD target (one-step reward plus bootstrapped value) with the full MC return (complete episode return).
Self-check: In what situations would you prefer TD over MC, and vice versa?
Connects to: On-policy MC, DP bootstrapping, SARSA and Q-learning
Was this lecture useful?
BitsNotes AI Assistant
Subject Notes AssistantConfigure AI Chat
Choose how to access the chatbotSigned in as
Powered by BitsNotes — 20 messages per day. No API key needed. Want unlimited access? Use "Bring Your Own Key" mode.
Sign in to use AI Chat
Get 20 free AI messages per day to ask questions about your lecture notes. Sign in with Google or GitHub — it takes 5 seconds.
Sign In to BitsNotesSwitch to "Bring Your Own Key" tab above for unlimited access with any OpenAI-compatible provider.