REINFORCE: Monte Carlo Policy Gradient
Imagine training a robot arm to grasp objects. Success is only known at the very end of a long sequence of joint movements. There is no teacher signal telling the arm which individual motion was good or bad. Only a final reward arrives at episode's end. This is the credit-assignment problem at the heart of reinforcement learning. REINFORCE was one of the first algorithms to solve it cleanly. It uses nothing but sampled trajectories and calculus. REINFORCE turns the abstract Policy-Gradient Theorem into a concrete, implementable algorithm. Rather than requiring a model of the environment or an estimate of action-values, it estimates the gradient of expected return directly from Monte Carlo rollouts. Play an entire episode, observe the total reward. Then nudge the probability of every action taken, in proportion to how good the episode turned out to be. This simplicity is precisely what makes REINFORCE both a foundational teaching tool and a genuine ancestor of modern deep-RL policy-gradient methods. These include methods used to fine-tune large language models with human feedback. The big picture is this: REINFORCE parameterizes a policy directly. Often this is a neural network mapping states to action probabilities. It performs gradient ascent on expected return using only the log-probabilities of actions actually taken and the returns actually observed. No value function is strictly required. No explicit model of transition dynamics is needed. The method works for both discrete and continuous action spaces without modification. Its price is high variance. Because each episode's contribution to the gradient depends on the entire random trajectory, learning can be slow and noisy. This article derives REINFORCE from the policy-gradient theorem. It gives working pseudocode and works a full numerical trace through several updates. It is honest about where the algorithm struggles. It sets up the natural next steps: reducing variance with baselines, and blending Monte Carlo returns with bootstrapped value estimates in Actor-Critic Methods.
- REINFORCE estimates the policy gradient using complete-episode Monte Carlo returns, requiring no environment model.
- The update rule multiplies the return by the gradient of the log-policy for each action taken.
- It is an unbiased but high-variance estimator of the true policy gradient.
- Works with any differentiable, parameterized policy — tabular softmax, linear, or deep neural network.
- Learning is episodic: gradients are only computed after an episode terminates.
- It is the direct ancestor of baseline-corrected and actor-critic policy-gradient methods.
REINFORCE increases the log-probability of actions in proportion to the total return that followed them, turning the policy-gradient theorem into a simple sample-based update.
The idea
REINFORCE is a Monte Carlo policy-gradient algorithm: it optimizes a parameterized policy directly by ascending an estimate of the gradient of expected return, where that estimate comes entirely from sampled, complete episodes. The policy is typically a differentiable function — a softmax over a linear combination of features, or a neural network — whose parameters are updated after each episode finishes. The starting point is the policy-gradient theorem, which states that the gradient of the expected return with respect to can be written as
where is the return (sum of discounted future rewards) from time step onward, and the expectation is over trajectories generated by following . REINFORCE simply replaces this expectation with a sample: run one full episode under the current policy, compute the actual returns observed at each time step, and use these as an unbiased Monte Carlo estimate of the gradient. Because requires knowledge of all rewards from time to episode end, REINFORCE is inherently an episodic algorithm — it cannot update mid-episode, only afterward. The key mechanical idea is the score function trick: (the eligibility vector or score function) tells you the direction in parameter space that most increases the probability of action in state . Multiplying this direction by the observed return means that actions followed by high returns get pushed to be more likely, and actions followed by low (or negative) returns get pushed to be less likely. No explicit value function estimation is required — the return itself, sampled directly from the environment, serves as the training signal. This is what distinguishes pure REINFORCE from Actor-Critic Methods, which replace the Monte Carlo return with a bootstrapped, learned estimate to reduce variance at the cost of some bias.
How it works
The algorithm alternates between two phases: generate a full episode using the current stochastic policy, then learn by walking backward (or forward) through the episode, accumulating gradient updates weighted by returns. Concretely, for each time step in the episode, REINFORCE computes the return and performs the update
where is a learning rate and is the discount factor. The factor arises directly from the derivation of the policy-gradient theorem for the discounted setting (it discounts the weight of each per-step gradient contribution according to how far into the episode it occurs); many practical implementations omit it for episodic tasks with close to 1, trading a small amount of theoretical correctness for simplicity and often better empirical performance. ``` Algorithm: REINFORCE (Monte Carlo Policy Gradient) Input: a differentiable policy parameterization π_θ(a | s) learning rate α > 0 discount factor γ ∈ [0, 1] Initialize policy parameters θ arbitrarily repeat forever (for each episode): generate an episode S_0, A_0, R_1, S_1, A_1, R_2, ..., S_{T-1}, A_{T-1}, R_T following π_θ(· | ·) for t = 0 to T - 1: G_t ← sum_{k=t}^{T-1} γ^(k - t) R_{k+1} // return from step t for t = 0 to T - 1: θ ← θ + α γ^t G_t ∇_θ log π_θ(A_t | S_t) until θ converges or a stopping criterion is met ``` Two implementation details matter in practice. First, the returns can be computed efficiently backward in a single pass, and , avoiding the naive recomputation. Second, the policy's score function is computed automatically by backpropagation in a neural-network implementation: define the negative log-likelihood loss weighted by the return, and let automatic differentiation produce the gradient. ``` Algorithm: REINFORCE with backward return computation for each episode: collect (S_0,A_0,R_1), (S_1,A_1,R_2), ..., (S_{T-1},A_{T-1},R_T) G ← 0 grad_accum ← 0 // accumulate the parameter update for t = T - 1 down to 0: G ← R_{t+1} + γ G grad_accum ← grad_accum + γ^t G ∇_θ log π_θ(A_t | S_t) θ ← θ + α grad_accum ```
Complexity & correctness
Time complexity. Generating one episode costs environment interactions, where is the episode length (a random variable in general). Computing all returns via the backward recurrence costs arithmetic operations rather than the naive from recomputing each sum from scratch. Each parameter update costs where is the number of policy parameters (for a neural network, this is one backward pass). Total per-episode cost is , dominated by the gradient computations, each of size . Over episodes, total time is .
Space complexity. REINFORCE must store the entire episode trajectory — every state, action, and reward — before it can compute any return, since depends on rewards arbitrarily far in the future. This costs space for the trajectory plus for the parameters and their gradients, giving total. This is the price of being purely Monte Carlo: unlike temporal-difference methods, no update can happen until the episode is fully observed, so nothing can be discarded early.
Correctness — why the estimator is unbiased. The core justification is that the sample-based gradient is an unbiased estimator of the true policy gradient given by the policy-gradient theorem. Formally, for the discounted episodic objective,
Since a single episode is a valid sample from the trajectory distribution induced by , the per-episode gradient computed by REINFORCE,
satisfies by construction — this is exactly what the policy-gradient theorem guarantees, since is itself an unbiased sample of (the expected return conditioned on state and action, averaged over the remaining trajectory). Averaging over many independently sampled episodes and taking a step in that averaged direction is standard stochastic gradient ascent, which converges to a stationary point of under the Robbins-Monro conditions on the learning-rate schedule (, ) and standard smoothness assumptions on .
The tradeoff: unbiasedness at the cost of variance. is a single noisy sample of a potentially very stochastic long-horizon quantity — different episodes starting from similar states can end with wildly different total returns due to unrelated randomness later in the trajectory. This is precisely the motivation for the follow-up techniques of subtracting a state-dependent baseline (which does not bias the gradient in expectation, since for any fixed ) and bootstrapping with a learned value function in actor-critic methods, both of which trade some bias or complexity for dramatically reduced variance.
Worked example
Consider a two-state, two-action toy MDP: states , actions , deterministic transitions (left keeps you moving forward, right ends the episode), reward at every step except a terminal reward of if you reach a goal and if you fall off. Suppose the policy is a softmax over a single scalar parameter controlling the preference for "right":
Initialize , so . Take , (no discounting, short episodes).
Episode 1. The agent samples: right goal, reward , episode ends ().
- .
- (standard softmax-gradient identity for two actions).
- Update: .
Episode 2. Now . Agent samples: left right off the edge, reward (, rewards ).
- (return from the second step onward).
- .
- At action was left: .
- At action was right: .
- Updates:
- Net change this episode: , so .
| Episode | Trajectory | used | Net | after |
|---|---|---|---|---|
| 1 | right (goal, ) | |||
| 2 | left right (fall, ) |
Notice the qualitative behavior: the good episode (reward for taking "right" immediately) pushed strongly upward, increasing the probability of "right." The bad episode (reward , ending in "right" at the second state) pushed the specific action that led to disaster ("right" at ) downward, while also pushing "left" at downward too — because was negative, and the gradient for the action not taken (right) moves in the opposite direction of the gradient for the action taken (left). This illustrates exactly how REINFORCE assigns credit (and blame) using only the total return, without any explicit value function to disentangle which step in a multi-step episode was truly responsible for the outcome — the seed of the variance problem that motivated baselines and actor-critic methods.
Common pitfalls & traps
| Pitfall | Why it happens | Fix |
|---|---|---|
| Forgetting the discount factor on the gradient step itself | Confusing 's internal discounting with the extra weighting from the theorem's derivation | Include both, or explicitly acknowledge the undiscounted approximation being used |
| Updating parameters mid-episode | Treating REINFORCE like a TD method | REINFORCE requires the complete return, so it can only update after termination |
| High variance mistaken for a bug | Returns swing wildly episode to episode, especially early in training | This is expected; use baselines, more episodes, or smaller learning rates before suspecting an implementation error |
| Not normalizing/whitening returns across a batch | Raw returns on different scales cause unstable gradients | Standardize returns (subtract mean, divide by std) across a batch of episodes as a simple variance-reduction step |
| Applying REINFORCE to continuing (non-episodic) tasks unmodified | The algorithm assumes finite to compute | Use truncated returns, a discounted average-reward formulation, or switch to bootstrapped actor-critic methods |
| Treating as an advantage | Using raw returns without subtracting a baseline conflates "this trajectory was good" with "this action was better than average" | Subtract a state-dependent baseline (foreshadowing variance-reduction techniques) |
Pioneers & history
REINFORCE was introduced by Ronald J. Williams in a 1992 paper that formalized a whole family of "REINFORCE" algorithms — the name itself is an acronym-like mnemonic for "REward Increment = Nonnegative Factor times Offset Reinforcement times Characteristic Eligibility," capturing the update's structure: a nonnegative learning rate, times a return-based reinforcement signal, times the eligibility (score function) of the action taken.
Origins · 1 minRonald J. Williams and how this was discovered
Williams worked at the intersection of neural networks and reinforcement learning in the late 1980s, a period when backpropagation was becoming the dominant tool for training multilayer networks. His 1992 paper connected stochastic gradient ascent, likelihood-ratio estimators from statistics, and the emerging framework of trial-and-error learning, giving reinforcement learning its first rigorous, general recipe for training stochastic policies with gradient methods — decades before deep policy-gradient methods became central to modern AI systems.
Where this matters
REINFORCE's direct descendants are everywhere in modern machine learning. Reinforcement learning from human feedback (RLHF), used to align large language models, applies policy-gradient updates that are structurally identical to REINFORCE (often via Proximal Policy Optimization, which adds a trust-region correction on top of the same score-function gradient). Robotics research uses REINFORCE-style updates when reward signals are sparse and only available at episode end, such as in manipulation or locomotion tasks with binary success signals. Neural architecture search has used REINFORCE to train a controller network whose "actions" are architectural decisions and whose "reward" is the validation accuracy of the resulting network. Combinatorial optimization systems (routing, scheduling) sometimes use REINFORCE to train sequence-generating policies where the objective — tour length, makespan — is only observable after a full solution is constructed. More broadly, any system that needs to differentiate through a discrete or stochastic sampling step — where standard backpropagation cannot pass a gradient — can fall back on the score-function trick that REINFORCE popularized, making it a foundational tool far beyond classical control-style reinforcement learning. It also serves as essential scaffolding for understanding Baselines and Variance Reduction and the shift toward bootstrapped, lower-variance updates in Actor-Critic Methods.
Ask the tutor: How does subtracting a baseline from the return reduce variance without introducing bias into the REINFORCE gradient estimate?
Is REINFORCE the same as the policy-gradient theorem?
No. The policy-gradient theorem is a mathematical statement about the exact gradient of expected return, expressed as an expectation over trajectories weighted by action-values or returns. REINFORCE is an algorithm that estimates that expectation using a single sampled Monte Carlo episode, plugging the observed return in place of the true expected value . The theorem tells you what the gradient equals in expectation; REINFORCE tells you how to approximate it from data you can actually collect by interacting with an environment.
Does REINFORCE need a value function at all?
Pure REINFORCE does not require a learned value function — it uses raw Monte Carlo returns as its training signal. However, practical implementations almost always add a learned baseline (often a state-value function) to subtract from the return before computing the gradient. This does not require an environment model and does not bias the gradient, but it substantially reduces variance. Once the baseline itself is bootstrapped (updated using one-step returns rather than full-episode returns), the algorithm transitions into the actor-critic family rather than being pure REINFORCE.
Why does REINFORCE have high variance?
Each gradient sample depends on the full return of an entire episode, which is a sum of many random rewards influenced by all the stochasticity in the policy and environment across the entire trajectory. Two episodes that take an identical first action can end with very different total returns purely due to what happens afterward, yet REINFORCE attributes the entire return to every action along the way. This coarse credit assignment, combined with the randomness of long trajectories, produces gradient estimates with large variance across episodes, requiring many samples or variance-reduction techniques to train reliably.
Can REINFORCE be used with continuous action spaces?
Yes. REINFORCE places no restriction on the action space beyond requiring a differentiable, parameterized policy from which actions can be sampled and log-probabilities computed. For continuous actions, a common choice is a Gaussian policy whose mean and (optionally) standard deviation are output by a neural network conditioned on the state; the score function is then simply the gradient of the Gaussian log-density with respect to the network parameters, which is straightforward to compute via backpropagation.
How does REINFORCE relate to supervised learning?
REINFORCE resembles supervised learning with a cross-entropy-style loss, but the "label" is the action actually taken, and the loss is weighted by the return instead of being a fixed target. In supervised learning, gradients push toward a known correct answer; in REINFORCE, gradients push toward whatever action was taken, scaled up if it led to good outcomes and scaled down (or reversed) if it led to bad ones. This is why REINFORCE-style updates are sometimes called "weighted maximum likelihood" or self-supervised policy learning driven by reward instead of ground-truth labels.
Why does REINFORCE sometimes fail to converge in practice?
Convergence guarantees rely on decaying learning rates satisfying the Robbins-Monro conditions and on unbiased, finite-variance gradient estimates. In practice, learning rates are often held constant, gradient variance can be very large (especially early in training with a poor policy), and function approximation introduces additional instability. Without variance reduction (baselines) or trust-region constraints (as in PPO or TRPO), a few unlucky high-variance updates can push the policy into a bad region of parameter space from which recovery is slow or impossible, especially if exploration collapses.
What is the difference between REINFORCE and Q-learning?
Q-learning is a value-based method that learns action-values and derives a policy implicitly (e.g., acting greedily), typically off-policy and using bootstrapped one-step updates. REINFORCE is a policy-based method that directly parameterizes and optimizes a stochastic policy using on-policy, full-episode Monte Carlo returns, with no value function required. REINFORCE naturally handles continuous and stochastic action spaces and produces stochastic policies useful for exploration, while Q-learning traditionally targets discrete action spaces and deterministic greedy policies, though many extensions blur this distinction.