Trajectory Sampling
Rather than wasting computational budget updating every state in an enormous state space equally, trajectory sampling simulates rollouts using an internal environment model. This restricts planning updates exclusively to states that the agent will actually encounter under its current policy.
Why Does This Exist?
In model-based reinforcement learning and Dynamic Programming, planning algorithms improve value functions and policies by simulating transitions through an internal environment model. The traditional approach is uniform sweeping: the planner iterates through the entire state space in an exhaustive round-robin fashion, applying Bellman backups to each state with equal frequency.
While uniform sweeping guarantees global convergence in small, toy Markov Decision Processes, it fails completely when scaled to practical problems:
- The Curse of Irrelevant States: In realistic tasks, the state space is combinatorial or massive. Worse, the vast majority of these states are either physically unreachable from starting conditions or represent bizarre, pathological configurations that an agent following a reasonable policy will never encounter.
- Diluted Computational Budget: If an environment contains states but the agent only ever visits of them along plausible goal-oriented trajectories, uniform sweeping expends of its planning computation updating values for states that have literally zero impact on decision-making. Important bottleneck states receive only a trickle of updates.
Trajectory sampling exists to align the distribution of planning computation with the distribution of actual agent experience.
Instead of sweeping the state space uniformly, the agent uses its learned model to simulate complete episodes starting from initial states and selecting actions according to its current policy . By executing planning updates exclusively along these simulated rollouts, updates are distributed according to the on-policy state distribution . States that are frequently visited under the policy receive intense, focused refinement, while unreachable states consume zero computational cycles.
Think of It Like This
The Continental GPS Router
Imagine programming a GPS navigation engine to compute the fastest driving route from Seattle to San Francisco.
A uniform sweeping router would load every intersection, dirt road, alleyway, and rural roundabout across the entire North American continent—from Anchorage, Alaska to Key West, Florida—into memory. It would iterate through every single crossroads in round-robin order, recalculating speed limits and traffic lights for all of them equally.
For hours, your computer fan would spin at maximum speed while the system calculated optimal left turns in southern Ohio and downtown Miami—intersections that have literally zero relevance to driving down the Pacific coast.
A trajectory sampling router operates with common sense:
- It begins at your current Seattle coordinates ().
- It projects prospective travel corridors southward along major highways (Interstate 5 and US-101), querying its road network model to simulate intersections along plausible paths toward San Francisco.
- It refines junction choices along that prospective corridor, ignoring the millions of irrelevant roads in other states.
Because 100% of the processor's budget is concentrated on the corridor of reachable travel, you receive a near-optimal driving itinerary in milliseconds.
Where the analogy stops: Road networks have static, fixed highway layouts. In reinforcement learning, the environment's transition probabilities and rewards can be stochastic, and updating the policy alters which future states become reachable. Consequently, trajectory sampling must maintain sufficient exploratory action selection to prevent missing newly promising corridors.
How It Actually Works
The On-Policy Distribution and Simulated Rollout Mechanism
In planning frameworks such as Dyna-Q and Real-Time Dynamic Programming (RTDP), trajectory sampling generates simulated trajectories using the agent's learned or given model .
The On-Policy State Distribution
Let an agent start at state and follow target policy . The discounted on-policy state distribution is defined as:
where:
- is the starting state distribution.
- is the discount factor.
- is the probability that state is occupied at time step under policy .
When a planner samples trajectories according to , the frequency of planning updates applied to state is directly proportional to its probability of being visited during actual task execution.
Algorithmic Flow of Trajectory Sampling Planning
At each planning cycle:
- Initialize State: Sample a start state (or select the agent's current real-world state).
- Rollout Loop: Until a terminal state is reached or horizon limit is met: a. Action Selection: Select action according to behavior policy (e.g., -greedy with respect to current ): b. Model Query: Query the internal transition model to generate a simulated next state and reward : c. In-Place Planning Update: Update the action-value estimate using a sample backup: (or alternatively apply a full expected Bellman backup if branching is small). d. Advance Simulation: Step forward along the simulated trajectory:
The Short-Term vs. Long-Term Convergence Trade-off
Richard Sutton and Andrew Barto analyzed the fundamental trade-off between uniform sweeping and on-policy trajectory sampling (Section 8.6):
Policy Value / Convergence ▲ │ Trajectory Sampling (Fast early gains) │ .────────────────────────────────────────────► │ . - ' │ . - ' │ . - ' Uniform Sweeps (Sluggish start, slow global convergence) │ . ' .────────────────────────────────────────────► │ ' . - - - - ' │ . - - - - ' └──────────────────────────────────────────────────────────────► Planning Updates 0 Low Budget (Practical) Infinite Budget (Asymptotic)- Under Low-to-Moderate Budgets: Trajectory sampling converges dramatically faster. By directing 100% of backups to reachable states along the current trajectory, the agent rapidly discovers a working policy to reach the goal.
- Under Infinite Budgets: Uniform sweeping eventually guarantees that all states in —even bizarre, unreachable corners—converge to their true Bellman values. However, because an optimal agent will never visit unreachable states anyway, investing compute to evaluate them provides zero performance benefit in real tasks.
Worked numerical comparison
Consider an environment with total discrete states: .
- The task begins at start state .
- Under policy , the reachable chain is: .
- States ( states, of the state space) are unreachable or irrelevant loops with zero reward.
- Transition dynamics: Reward is on intermediate transitions, with a terminal reward of upon exiting .
- Discount factor: . Step-size learning rate: .
True Optimal Values on Reachable States
Working backward from the goal:
All states are initialized to . The planner is allocated a budget of exactly planning updates.
Case A: Uniform Sweeping ( Updates)
With total states, a uniform round-robin sweep updates each state in sequence () across complete passes ( updates per state).
- Reachable states (): Each state receives only updates.
- Unreachable states (): Absorb updates ( of total budget) calculating transitions for states the agent never visits!
After passes, the value estimates on the reachable chain are:
Mean Squared Error (MSE) on the task states:
The start state has barely registered that a goal exists ( vs true ) because updates were diluted across the entire state space.
Case B: Trajectory Sampling ( Updates)
The planner simulates trajectories starting from following policy :
Each simulated rollout executes state updates. Within the -update budget, the planner completes full trajectories ().
- Reachable states (): Each state receives focused updates ( more than uniform sweeping).
- Unreachable states (): Absorb updates ( wasted compute).
After simulated rollouts, the value estimates are:
Mean Squared Error (MSE) on the task states:
Conclusion: For the exact same computational budget ( updates), trajectory sampling achieves a reduction in prediction error ( vs ) and brings the start state value close to convergence.
Code
from typing import Dict, List, Tuple
def evaluate_planning_convergence( num_total_states: int, reachable_chain: List[int], gamma: float = 0.9, alpha: float = 0.5, terminal_reward: float = 10.0, total_budget: int = 40,) -> Tuple[Dict[str, float], Dict[str, float]]: """Compare Uniform Sweeping vs Trajectory Sampling on a fixed computational budget.
Args: num_total_states: Total size of discrete state space |S|. reachable_chain: Sequential state ids forming the task trajectory. gamma: Discount factor in [0, 1]. alpha: Planning update step-size. terminal_reward: Reward achieved upon reaching terminal state. total_budget: Fixed number of planning backups allowed.
Returns: Tuple of (uniform_results_summary, trajectory_results_summary). """ chain_len = len(reachable_chain)
# 1. Uniform Sweeps (Exhaustive round-robin across all states) v_uniform: Dict[int, float] = {s: 0.0 for s in range(num_total_states)} rounds = total_budget // num_total_states for _ in range(rounds): for s in range(num_total_states): if s in reachable_chain: idx = reachable_chain.index(s) if idx == chain_len - 1: target = terminal_reward else: next_s = reachable_chain[idx + 1] target = gamma * v_uniform[next_s] else: target = gamma * v_uniform[s] # Irrelevant self-looping state v_uniform[s] += alpha * (target - v_uniform[s])
# 2. Trajectory Sampling (Simulated on-policy rollouts starting from S0) v_traj: Dict[int, float] = {s: 0.0 for s in range(num_total_states)} trajectories = total_budget // chain_len for _ in range(trajectories): for idx, s in enumerate(reachable_chain): if idx == chain_len - 1: target = terminal_reward else: next_s = reachable_chain[idx + 1] target = gamma * v_traj[next_s] v_traj[s] += alpha * (target - v_traj[s])
# Compute Ground Truth V* on reachable chain true_v: Dict[int, float] = {} curr_val = terminal_reward for s in reversed(reachable_chain): true_v[s] = curr_val curr_val *= gamma
mse_uniform = sum((v_uniform[s] - true_v[s]) ** 2 for s in reachable_chain) / chain_len mse_traj = sum((v_traj[s] - true_v[s]) ** 2 for s in reachable_chain) / chain_len
res_uniform = { "mse": round(mse_uniform, 4), "v_start": round(v_uniform[reachable_chain[0]], 4), "wasted_updates": total_budget - (rounds * chain_len), } res_traj = { "mse": round(mse_traj, 4), "v_start": round(v_traj[reachable_chain[0]], 4), "wasted_updates": 0, } return res_uniform, res_traj
# Execute simulation matching the worked numerical comparisonu_res, t_res = evaluate_planning_convergence( num_total_states=10, reachable_chain=[0, 1, 2, 3], gamma=0.9, alpha=0.5, terminal_reward=10.0, total_budget=40,)
# Automated verificationassert u_res["wasted_updates"] == 24assert t_res["wasted_updates"] == 0assert abs(u_res["v_start"] - 0.4556) < 1e-4assert abs(t_res["v_start"] - 6.0370) < 1e-4assert abs(u_res["mse"] - 21.5051) < 1e-4assert abs(t_res["mse"] - 0.4439) < 1e-4
print(f"Uniform Sweeps | Start V(S0): {u_res['v_start']:6.4f} | MSE: {u_res['mse']:7.4f} | Wasted Updates: {u_res['wasted_updates']}")print(f"Trajectory Sample | Start V(S0): {t_res['v_start']:6.4f} | MSE: {t_res['mse']:7.4f} | Wasted Updates: {t_res['wasted_updates']}")
# -> Uniform Sweeps | Start V(S0): 0.4556 | MSE: 21.5051 | Wasted Updates: 24# -> Trajectory Sample | Start V(S0): 6.0370 | MSE: 0.4439 | Wasted Updates: 0Watch Out For
The Trajectory Sampling Myopia and Exploration Trap
While trajectory sampling dramatically outperforms uniform sweeping by focusing on on-policy states, purely greedy trajectory sampling () creates a severe failure mode: policy lock-in.
The Failure Mode: If the behavior policy during simulated rollouts is purely greedy with respect to initial, inaccurate value estimates, the planner repeatedly simulates the exact same suboptimal trajectory.
Because states off this chosen path are never visited in simulation, their values are never updated. Even if a neighboring branch contains a massive positive reward, the planner remains completely blind to it. The agent becomes trapped in a self-fulfilling prophecy: it only plans along paths it believes are good, and it only updates paths it plans along.
Concrete Fix:
- Always use an exploratory rollout policy: During model simulation, select actions using -greedy exploration () or Boltzmann softmax exploration. This guarantees that simulated trajectories occasionally branch into unvisited states, allowing the model to discover shortcut paths.
- Combine with Prioritized Sweeping: In deterministic or tabular domains, pair trajectory sampling with a priority queue (such as Prioritized Sweeping) that tracks states with large Bellman error . If an exploratory rollout uncovers a large reward, the priority queue immediately propagates that error backward across all predecessor states, preventing lock-in.
The Quick Version
- Uniform sweeps waste over of planning computation in large state spaces by updating unreachable or irrelevant states.
- Trajectory sampling simulates rollouts using an internal environment model, distributing updates according to the on-policy state distribution .
- States along realistic task trajectories receive dense, concentrated planning updates, achieving near-optimal policies in orders of magnitude fewer operations.
- Rollout action selection must remain exploratory (-greedy) to avoid myopic lock-in on early suboptimal trajectories.