The REINFORCE Algorithm
REINFORCE updates a neural network policy by waiting for complete episodes, increasing the probability of actions that produced high returns and penalizing actions that led to low returns.
Why Does This Exist?
In many real-world control tasks, such as robotic arm manipulation or drone attitude stabilization, the action space is continuous (torque voltages, thrust vectors). Value-based methods struggle here: to act greedily, they must solve at every timestep, which requires expensive continuous optimization inside the inner simulation loop. Furthermore, value-based methods cannot naturally learn stochastic policies, which are required in games of imperfect information or under state aliasing.
The REINFORCE algorithm (Williams, 1992) pioneered the policy gradient revolution. Instead of evaluating state-action values and deriving a policy indirectly, REINFORCE parameterizes the policy directly as —typically outputting the mean and variance of a Gaussian distribution or logits of a categorical distribution.
Crucially, REINFORCE answers a fundamental question: how can you differentiate an objective function that depends on environment transitions when you do not know the environment's transition dynamics ? By utilizing the log-derivative trick, REINFORCE converts the gradient of expected performance into an expectation of gradients, allowing agents to optimize policies via empirical Monte Carlo rollouts.
Think of It Like This
A basketball coach reviewing full game tape at the buzzer
Imagine a basketball coach who is not allowed to interrupt the game to give tactical corrections mid-play. Instead, the coach watches the entire 48-minute game from the stands without interfering, letting the players experiment with different passes and shots.
After the buzzer sounds and the final scoreboard confirms whether the team won or lost by 20 points, the coach sits down with the full game tape. For every shot taken in the fourth quarter, if the sequence ended in a scoring rally, the coach tells the player: "Do that exact dribble-drive move more often next time." If a sequence yielded turnovers and opponent fast-breaks, the coach says: "Reduce the frequency of that risky bounce pass."
Because the feedback is based on the entire completed game, credit is noisy—a brilliant pass in the first quarter might get dragged down by poor defense in the fourth. But across hundreds of games, the moves that systematically lead to high scores are reinforced, while moves that consistently lead to losses are suppressed.
How It Actually Works
Likelihood Ratio and Baseline Subtraction
Let a trajectory be sampled by following policy . The expected return objective is:
The probability of a trajectory factors into initial state distribution, policy actions, and unknown environment transition probabilities:
Taking the gradient directly is impossible because is unknown. Applying the likelihood ratio trick () eliminates the environment dynamics:
This yields the Policy Gradient Theorem:
Where is the return-to-go from step :
Because future actions cannot influence past rewards, causality dictates replacing total trajectory return with , drastically reducing gradient variance.
Baseline Variance Reduction
To further reduce variance without introducing bias, a state-dependent baseline is subtracted from . The update becomes:
The baseline does not introduce bias because:
Worked Example
Consider a 2-step episode in an environment with two discrete actions () parameterized by a single policy weight . The policy uses a softmax distribution where logit for is and logit for is :
The gradient with respect to is:
- If is chosen:
- If is chosen:
Let initial weight , so (). Discount factor , learning rate , and constant baseline .
Sampled Episode Rollout:
- Step 0 (): Agent samples . Receives reward .
- Step 1 (): Agent samples . Receives reward . Episode terminates ().
Step-by-Step Computations:
-
Returns-to-go:
-
Advantage with Baseline:
-
Log-Probability Gradients:
- At , action was :
- At , action was :
-
Total Policy Gradient:
-
Parameter Update:
New probability for : . The probability of taking action increased because its advantage was strongly positive.
Code
from typing import List, Tupleimport numpy as np
def reinforce_update( theta: float, actions: List[int], rewards: List[float], gamma: float = 1.0, alpha: float = 0.1, baseline: float = 5.0,) -> Tuple[float, List[float]]: """Executes a Monte Carlo REINFORCE parameter update over one episode.""" # Compute returns-to-go G_t backward from terminal step returns: List[float] = [0.0] * len(rewards) g = 0.0 for t in reversed(range(len(rewards))): g = rewards[t] + gamma * g returns[t] = g
# Softmax probability for action 0: p = 1 / (1 + exp(-theta)) prob_a1 = 1.0 / (1.0 + np.exp(-theta)) total_grad = 0.0 for t, action in enumerate(actions): advantage = returns[t] - baseline # Gradient of log pi: (1 - prob) if action 0, else -prob grad_log = (1.0 - prob_a1) if action == 0 else (-prob_a1) total_grad += grad_log * advantage
updated_theta = theta + alpha * total_grad return updated_theta, returns
# Episode: action 0 (a1) then action 1 (a2), rewards 2.0 and 8.0init_theta = 0.0new_theta, returns_computed = reinforce_update( theta=init_theta, actions=[0, 1], rewards=[2.0, 8.0], gamma=1.0, alpha=0.1, baseline=5.0,)
print(f"Returns G_t: {returns_computed}")# -> Returns G_t: [10.0, 8.0]
print(f"Updated Theta: {new_theta:.2f}")# -> Updated Theta: 0.10
new_prob = 1.0 / (1.0 + np.exp(-new_theta))print(f"Updated P(a1): {new_prob:.4f}")# -> Updated P(a1): 0.5250Watch Out For
The Monte Carlo Variance Explosion
Because REINFORCE computes full episodic returns by summing across all subsequent timesteps, the variance of the gradient estimator compounds exponentially with episode horizon . A single stochastic transition or exploratory action near the end of the episode introduces noise into the gradient of every preceding action in that episode, causing training to stall or destabilize.
Always implement reward-to-go instead of total trajectory return, normalize advantages across batch rollouts (), and subtract a learned state-value baseline . If episode horizons exceed a few hundred steps, transition from pure Monte Carlo REINFORCE to an Actor-Critic architecture that bootstraps after steps.
The Quick Version
- REINFORCE uses the log-derivative likelihood ratio trick to optimize parameterized policies without knowing environment transition dynamics.
- Updates occur strictly at the end of complete episodes using Monte Carlo returns-to-go: .
- Subtracting an unbiased baseline from preserves the expected gradient while dramatically reducing sampling variance.