Stochastic Gradient Descent in RL
Stochastic Gradient Descent adapts parameterized value functions by taking incremental steps against the gradient of squared prediction errors on sampled state transitions. In reinforcement learning, SGD must overcome moving bootstrap targets, non-i.i.d. autocorrelated samples, and shifting policy distributions.
Why Does This Exist?
When scaling reinforcement learning to continuous or high-dimensional state spaces, tabular lookup tables become intractable. We must approximate the true value function using a parameterized function governed by a weight vector .
To optimize , we turn to Stochastic Gradient Descent (SGD)—the bedrock optimization algorithm of modern machine learning. In classical supervised learning, SGD minimizes a loss function across millions of static training examples by taking small, noisy steps in the direction opposite to the gradient of the error on individual data samples:
However, applying SGD to reinforcement learning fundamentally violates the core theoretical foundations of supervised learning:
- Target Non-Stationarity (Moving Goalposts): In supervised learning, the ground truth label is fixed. In reinforcement learning, the true value is unknown. We substitute bootstrapped targets like . Because the target itself depends on the current parameter vector , every parameter update shifts the target surface.
- Autocorrelated Samples (Non-i.i.d. Data): Supervised learning assumes samples are drawn independently from a static dataset. In RL, states arrive along sequential Markovian trajectories , where subsequent states are heavily correlated in time.
- Distribution Shift: As the value function improves, the agent updates its policy , which in turn alters the environmental state visitation distribution , reshaping the loss surface itself.
Understanding SGD in reinforcement learning requires adapting classical gradient descent to navigate dynamic bootstrap targets, non-independent data streams, and semi-gradient approximations.
Think of It Like This
Hiking Downhill on Shifting Terrain in Dense Fog
Imagine navigating down a steep mountain toward sea level during a heavy fog:
- The Classical Supervised Descent: The mountain is a solid, granite geological formation. You cannot see the distant valley floor through the fog, but you can feel the local slope of the rock under your boots. At every step, you take a short stride in the direction of steepest downward tilt. Because the granite mountain never moves, taking small steps guarantees that you will eventually reach the valley basin ().
- The Reinforcement Learning Descent: You are still hiking in dense fog, but now you are hiking on an active volcanic mudslide or shifting glacial moraine. Whenever you take a stride downhill, the weight of your boots causes the surrounding slope ahead of you to subtly shift, elevate, or buckle. The elevation target you are trying to reach is not fixed—it is estimated based on where you believe the next step will land.
- The Semi-Gradient Shortcut: To avoid calculating the complex tectonic physics of how your step deforms the entire mountain slope ahead (the gradient of the target with respect to your position), you treat your immediate footing as fixed for the duration of that single step. You step downward relative to current local ground level, and reassess after your foot lands.
Where the analogy breaks down: Mountain topography obeys 3D spatial Euclidean constraints. In reinforcement learning, the parameter space can encompass millions of dimensions, and state transitions are governed by Markov decision processes where distant states can be coupled through long temporal credit horizons.
How It Actually Works
The Objective, Semi-Gradients, and Robbins-Monro Convergence
To optimize parameterized value functions via SGD, we formalize the error metric, derive the update equations, and establish the conditions required for stochastic convergence.
1. The Mean Squared Value Error Objective
Because , an approximator cannot match the true value function across all states simultaneously. The Mean Squared Value Error () weights squared estimation errors by how frequently each state is visited under policy :
where is the on-policy state distribution (). In continuing tasks, is the stationary distribution of the Markov chain; in episodic tasks, it represents normalized discounted visitation time steps.
2. The Ideal Gradient Update
The gradient of with respect to is:
SGD approximates this global expectation by sampling single transitions . The true stochastic gradient update rule is:
where is the step-size learning rate.
3. Semi-Gradient Methods in Practice
Because the true value is unknown, practical RL replaces with an empirical target :
- In Gradient Monte Carlo, (the realized discounted return). Because is an unbiased sample of () and does not depend on , Monte Carlo represents true gradient descent.
- In One-Step Temporal Difference [TD(0)], . Here, the target itself is parameterized by . A true gradient update would require computing , which introduces a term proportional to .
Ignoring this target dependency yields the semi-gradient TD(0) update:
In linear function approximation (), , simplifying the update to:
4. The Robbins-Monro Convergence Conditions
Because SGD samples individual stochastic transitions rather than computing exact batch expectations, convergence to the optimum depends critically on the step-size schedule . According to the classical Robbins-Monro theorem, convergence to a fixed point is guaranteed if and only if:
- Condition 1 (): The step sizes must be sufficiently large to traverse any arbitrary initial parameter error regardless of starting point .
- Condition 2 (): The step sizes must shrink fast enough to damp out the variance introduced by stochastic sample noise.
If a constant step size is used, the parameters do not converge to a single fixed point. Instead, they continually fluctuate within an asymptotic noise ball around the optimum—a phenomenon known as asymptotic limit-cycle jitter.
Worked numerical example
Let us trace two consecutive steps of SGD on a 2-feature linear parameter vector with learning rate .
The linear value model is:
Initial parameters:
Step 1: First Experience Transition
- The agent observes state with feature vector .
- Target return is observed: .
- Compute Prediction:
- Compute Error:
- Compute Gradient:
- SGD Parameter Update:
Step 2: Second Experience Transition
- The agent transitions to sequential state with feature vector .
- Target return is observed: .
- Compute Prediction under :
- Compute Error:
- Compute Gradient:
- SGD Parameter Update:
Verification of Value Predictions under
Let us re-evaluate predictions for both states under the updated weights :
- At : (improved toward target ).
- At : (improved toward target ).
Both predictions adjusted in parallel, demonstrating how shared parameters coordinate value adjustments across the state space.
Code
The following self-contained Python script implements the worked numerical SGD calculation and directly contrasts convergence on a stationary target versus a moving bootstrap target:
import mathfrom typing import List, Tuple
def run_numerical_two_step_sgd() -> Tuple[List[float], float, float]: """Execute the exact 2-step worked numerical SGD example.""" w: List[float] = [0.0, 0.0] alpha: float = 0.1
# Step 1 x1: List[float] = [1.0, 2.0] u1: float = 5.0 pred1: float = sum(wi * xi for wi, xi in zip(w, x1)) delta1: float = u1 - pred1 w[0] += alpha * delta1 * x1[0] w[1] += alpha * delta1 * x1[1]
# Step 2 x2: List[float] = [2.0, 1.0] u2: float = 4.0 pred2: float = sum(wi * xi for wi, xi in zip(w, x2)) delta2: float = u2 - pred2 w[0] += alpha * delta2 * x2[0] w[1] += alpha * delta2 * x2[1]
# Re-evaluate predictions under updated weights new_pred1 = w[0] * x1[0] + w[1] * x1[1] new_pred2 = w[0] * x2[0] + w[1] * x2[1]
return w, new_pred1, new_pred2
def compare_stationary_vs_moving_targets() -> Tuple[float, float]: """Compare SGD convergence on stationary vs moving bootstrap targets. 1. Stationary target: True v*(x) = 3.0 * x 2. Moving bootstrap target: U(x, w) = 0.5 * x + 0.8 * (w * x) Theoretical fixed point: w* = 0.5 / (1.0 - 0.8) = 2.5 """ # 1. Stationary Target Training w_stationary = 0.0 alpha_stat = 0.05 for _ in range(100): for x in [0.5, 1.0]: target = 3.0 * x pred = w_stationary * x error = target - pred w_stationary += alpha_stat * error * x
# 2. Moving Bootstrap Target Training (Semi-gradient TD) w_moving = 0.0 alpha_moving = 0.1 for _ in range(500): for x in [0.5, 1.0]: # Target shifts dynamically with current weight w_moving target = 0.5 * x + 0.8 * (w_moving * x) pred = w_moving * x error = target - pred w_moving += alpha_moving * error * x
return w_stationary, w_moving
def main() -> None: # 1. Verify worked numerical example w_final, v1, v2 = run_numerical_two_step_sgd() print("--- 2-Step Numerical SGD Walkthrough ---") print(f"Final weights w: [{w_final[0]:.4f}, {w_final[1]:.4f}]") print(f"New prediction v_hat(S1): {v1:.4f}") print(f"New prediction v_hat(S2): {v2:.4f}")
assert abs(w_final[0] - 0.9) < 1e-6 assert abs(w_final[1] - 1.2) < 1e-6 assert abs(v1 - 3.3) < 1e-6 assert abs(v2 - 3.0) < 1e-6
# 2. Verify stationary vs moving bootstrap comparison w_stat, w_mov = compare_stationary_vs_moving_targets() print("\n--- Stationary vs Moving Bootstrap Convergence ---") print(f"Stationary target weight w: {w_stat:.4f} (True optimum: 3.0000)") print(f"Moving bootstrap weight w: {w_mov:.4f} (TD fixed point: 2.5000)")
assert abs(w_stat - 3.0) < 0.02 assert abs(w_mov - 2.5) < 0.02
if __name__ == "__main__": main()
# -> Expected output:# -> --- 2-Step Numerical SGD Walkthrough ---# -> Final weights w: [0.9000, 1.2000]# -> New prediction v_hat(S1): 3.3000# -> New prediction v_hat(S2): 3.0000# -> # -> --- Stationary vs Moving Bootstrap Convergence ---# -> Stationary target weight w: 2.9950 (True optimum: 3.0000)# -> Moving bootstrap weight w: 2.5000 (TD fixed point: 2.5000)Watch Out For
Asymptotic Jitter and the Moving Target Bias
Practitioners commonly experience optimization instability when applying textbook supervised SGD to reinforcement learning without accounting for non-stationarity and sample autocorrelation:
1. Asymptotic Limit-Cycle Jitter: In supervised learning, keeping a constant step size causes weights to gently oscillate near the global minimum. In RL, because bootstrap targets amplify stochastic environmental noise, constant step sizes lead to violent asymptotic limit cycles and parameter divergence. The Fix: Implement learning rate schedules satisfying Robbins-Monro conditions (), or employ modern adaptive optimizers like Adam paired with learning rate warm-up and decay.
2. Target Network Drift and the Deadly Triad: When bootstrapping interacts with non-linear neural networks and off-policy data, moving targets create positive feedback loops where overestimations reinforce subsequent targets, triggering unbounded value divergence. The Fix: Decouple the target computation from the parameters being trained using Target Networks (). Freeze and update it slowly via periodic synchronization or Polyak averaging ( with ), stabilizing the moving loss landscape.
3. Autocorrelation Bias: Sequential rollout transitions violate i.i.d. sampling. Consecutive gradients pull parameters along local trajectory tangents, causing catastrophic forgetting of distant state values. The Fix: Use an Experience Replay Buffer to randomly shuffle transitions across thousands of historical episodes, breaking autocorrelation and restoring approximate i.i.d. conditions.
The Quick Version
- Incremental Error Minimization: SGD in RL adjusts parameters along the negative gradient of prediction errors on individual transition samples to minimize the Mean Squared Value Error .
- Three RL Breaches: Unlike supervised learning, RL SGD must contend with moving bootstrap targets, non-i.i.d. autocorrelated Markov trajectories, and policy-driven state distribution shifts.
- The Semi-Gradient Principle: Bootstrapped TD methods ignore the gradient of the target with respect to , converging to a well-defined TD fixed point rather than the true global minimum.
- Robbins-Monro Guarantees: Asymptotic convergence requires step sizes to decay such that (sufficient learning capacity) and (damping stochastic sample variance).