REINFORCE: adjust action probabilities from complete episodes
REINFORCE
Run sampled training in a two-step environment and inspect reward-to-go, baselines and gradient variance.
reinforceAn episode ended. Which actions should become more likely?
In the two-step game from policy gradients, going right costs 0.1 before action 1 earns 1; on the left, action 0 earns 0.4. Discount the final reward by 0.9. One successful right-branch episode returns 0.8, but abruptly making both sampled actions certain is not a reliable update. REINFORCE multiplies return by each action’s log-probability gradient and averages such samples to estimate an update direction. Original REINFORCE
It can wait for a complete episode without learning a next-state value. The cost is that later randomness affects many earlier action gradients. As with Monte Carlo value estimation, episodes must actually end, or the treatment of truncation must be explicit.
Return sets the weight; the score tells a probability how to move
Let J_gamma discount return from the start. Collect B independent episodes under one frozen policy. Let z_t be the action log-probability gradient, G_t the return discounted relative to time t, and b_t a baseline independent of the current action. The update is:
Reward-to-go removes past rewards the current action cannot influence while preserving the expectation. The outer gamma^t belongs to the start-discounted objective. This program averages across episodes after summing within each episode; separately dividing by each episode’s length could change the relative weights of different-length episodes. Discounted objective Reward-to-go
Given the current state, time and frozen learning history, an action-independent baseline satisfies:
Fitting a baseline on the current batch before forming that batch’s actor gradient can make it depend on the sampled actions. The identity does not automatically cover that dependence. Cross-fitting, separate baseline data or an explicit dependence analysis are possible remedies. Here the old baseline remains fixed throughout sampling; only after the actor update does the batch fit the baseline for the next batch.
State value is an interpretable baseline but need not minimize variance. At one fixed state, the mean of vector gradient z(G−b) does not depend on b. Minimizing the trace of its covariance therefore amounts to minimizing its second moment. Differentiating with respect to a scalar baseline gives:
This minimizes the covariance trace for this one state contribution, not all cross-time covariances in a general trajectory gradient or every coordinate separately. Only under additional conditions can the squared-score weight be dropped to give ordinary expected return.
Consider a one-step Bernoulli policy with action 1 probability p=0.8, reward equal to action a and a logit parameter. Its score is a−p. Exact results for zero baseline, value baseline 0.8 and optimal baseline 0.2 are:
At b=0.2, action 0 yields(−0.8)(−0.2)=0.16 and action 1 yields 0.2 times 0.8=0.16. Both outcomes agree. The value baseline has nine times the zero-baseline variance here. This is a local arithmetic counterexample, not advice to discard value baselines in general training.
For the two-step game, let p0 be the probability of going right and pL,pR the action 1 probabilities on each branch. The true expectation supplies a training-independent evaluation:
The three zeros in the last expression are logits, not probabilities: each probability is 0.5. The optimal deterministic route returns 0.8.
Collect a batch before updating either table
The standard-library program uses 16 episodes per batch,400 updates and actor learning rate 0.4. A learned state baseline moves toward its batch-average return with rate 0.2; unvisited states keep their values. Zero-baseline and learned-baseline variants each run seeds 0–7. Policy and baseline stay frozen within a batch, and output retains every seed’s exact expected return.
"""Episodic REINFORCE with a baseline frozen before each sampled batch."""
import json
import math
import random
def sigmoid(x):
if not math.isfinite(x):
raise ValueError('finite logit required')
return 1/(1+math.exp(-x)) if x >= 0 else math.exp(x)/(1+math.exp(x))
def expected_return(theta, gamma=0.9):
p0, left, right = map(sigmoid, theta)
return (1-p0)*gamma*0.4*(1-left)+p0*(-0.1+gamma*right)
def sample_episode(theta, rng):
p = list(map(sigmoid, theta))
a0 = int(rng.random() < p[0])
branch = 1+a0
a1 = int(rng.random() < p[branch])
return [(0, a0, -0.1*a0), (branch, a1, float(a1) if a0 else 0.4*(1-a1))]
def episode_gradient(theta, episode, baseline, gamma=0.9):
"""Old policy and baseline are fixed for the complete episode."""
g, returns, ret = [0., 0., 0.], [], 0.
for _, _, reward in reversed(episode):
ret = reward+gamma*ret
returns.append(ret)
returns.reverse()
for t, ((state, action, _), ret) in enumerate(zip(episode, returns)):
g[state] += gamma**t*(action-sigmoid(theta[state]))*(ret-baseline[state])
return g, returns
def train(seed=0, iterations=400, batch_size=16, lr=0.4, use_baseline=True):
if iterations < 0 or batch_size < 1 or not math.isfinite(lr) or lr <= 0:
raise ValueError('nonnegative iterations, positive batch size and learning rate required')
rng, theta, baseline = random.Random(seed), [0., 0., 0.], [0., 0., 0.]
for _ in range(iterations):
gradients, targets = [0., 0., 0.], [[], [], []]
# Nothing updates until the entire on-policy batch has been collected.
for _ in range(batch_size):
episode = sample_episode(theta, rng)
grad, returns = episode_gradient(theta, episode, baseline)
gradients = [x+y for x, y in zip(gradients, grad)]
for (state, _, _), ret in zip(episode, returns):
targets[state].append(ret)
theta = [x+lr*g/batch_size for x, g in zip(theta, gradients)]
if use_baseline:
for state, samples in enumerate(targets):
if samples:
baseline[state] += 0.2*(sum(samples)/len(samples)-baseline[state])
return {'seed': seed, 'return': expected_return(theta), 'logits': theta}
def bernoulli_gradient_moments(p, baseline):
if not 0 < p < 1 or not math.isfinite(baseline):
raise ValueError('p in (0,1) and finite baseline required')
terms = [(1-p, (-p)*(-baseline)), (p, (1-p)*(1-baseline))]
mean = sum(weight*g for weight, g in terms)
return {'mean': mean, 'variance': sum(weight*(g-mean)**2 for weight, g in terms)}
def main():
runs = {name: [train(seed, use_baseline=use) for seed in range(8)]
for name, use in [('zero_baseline', False), ('learned_baseline', True)]}
print(json.dumps({'initial_return': expected_return([0., 0., 0.]),
'optimal_return': 0.8, 'runs': runs,
'failures_below_0_7': {name: [r['seed'] for r in rows if r['return'] < 0.7]
for name, rows in runs.items()},
'p_0_8_moments': {str(b): bernoulli_gradient_moments(0.8, b)
for b in (0., 0.8, 0.2)}}, indent=2))
if __name__ == '__main__':
main()
Inspect the complete recorded output
{
"initial_return": 0.265,
"optimal_return": 0.8,
"runs": {
"zero_baseline": [
{
"seed": 0,
"return": 0.7854301037046606,
"logits": [
4.259959677058475,
-1.1229066206961638,
4.80450499732589
]
},
{
"seed": 1,
"return": 0.7853456727039227,
"logits": [
4.245423213452434,
-1.1138746931080217,
4.808546657304588
]
},
{
"seed": 2,
"return": 0.7855351503258651,
"logits": [
4.267012670321997,
-1.0474776135237511,
4.822220566790887
]
},
{
"seed": 3,
"return": 0.7856210916863787,
"logits": [
4.2872818359617835,
-1.0776073994613355,
4.810037205708471
]
},
{
"seed": 4,
"return": 0.7850140766295528,
"logits": [
4.1965503871303875,
-1.0912752939320158,
4.816252091417712
]
},
{
"seed": 5,
"return": 0.7853920896497786,
"logits": [
4.242732110755607,
-1.1204044921936993,
4.816978351474286
]
},
{
"seed": 6,
"return": 0.7855722323132484,
"logits": [
4.285137782844394,
-0.9726319924301566,
4.819344555779045
]
},
{
"seed": 7,
"return": 0.7857910413349127,
"logits": [
4.315598913020313,
-0.916789303751068,
4.8276620496702085
]
}
],
"learned_baseline": [
{
"seed": 0,
"return": 0.7852777777718062,
"logits": [
4.266291925667588,
-1.117144646234485,
4.777990751123101
]
},
{
"seed": 1,
"return": 0.7858233228722652,
"logits": [
4.284002459221973,
-1.034318355625502,
4.848094942432917
]
},
{
"seed": 2,
"return": 0.7855394179507232,
"logits": [
4.25048552643619,
-1.0235472053412273,
4.843393263597488
]
},
{
"seed": 3,
"return": 0.7856745355298493,
"logits": [
4.238484361075901,
-1.1035589131750387,
4.8647294902510625
]
},
{
"seed": 4,
"return": 0.7856179785611188,
"logits": [
4.36465302083818,
-1.0753649230080067,
4.73907953581004
]
},
{
"seed": 5,
"return": 0.7863301508456916,
"logits": [
4.3688771813842,
-1.0854825846094596,
4.831681521464777
]
},
{
"seed": 6,
"return": 0.7848818059185237,
"logits": [
4.261119248604663,
-1.0207612113051507,
4.742227720208462
]
},
{
"seed": 7,
"return": 0.7862500424060973,
"logits": [
4.343950288926442,
-0.9871058862860478,
4.85648802994492
]
}
]
},
"failures_below_0_7": {
"zero_baseline": [],
"learned_baseline": []
},
"p_0_8_moments": {
"0.0": {
"mean": 0.15999999999999998,
"variance": 0.006399999999999996
},
"0.8": {
"mean": 0.15999999999999998,
"variance": 0.05760000000000002
},
"0.2": {
"mean": 0.15999999999999998,
"variance": 6.162975822039153e-34
}
}
}All eight seeds in both groups exceed the preset 0.7 check threshold, ending around 0.785–0.786. This is not evidence that baseline learning improved training performance. As policies diverge, the same seed does not ensure identical episode data in both groups. The separate one-step variance calculation uses exact enumeration and is easier to interpret.
B episodes of length T with d parameters require O(BTd) gradient-accumulation work. Returns can be computed backward in O(T) per trajectory. This implementation retains the current trajectory and per-state return targets, the latter occupying up to O(BT) space. Neural policies add forward and backward computation costs.
The cost of waiting for an episode
REINFORCE does not bootstrap, so under this finite-episode sampling setup it does not introduce critic next-value error. Long episodes increase waiting time and gradient variability. A continuing task cannot simply wait for a complete return. Artificially truncating and treating later rewards as zero changes the objective; adding a terminal value introduces bootstrap error.
A single update can lower true return, especially with a large step. Williams’s expected-gradient statements and baseline conditions do not promise improvement at every step or seed; generalized REINFORCE step-size factors also have dependence restrictions. Original conditions For more frequent updates consider actor–critic. Repeatedly optimizing the same batch also requires explaining the old-policy distribution and probability ratios.
Give a plausible baseline a counterexample
- Why form the actor gradient before updating the baseline? Answer: The baseline then depends only on earlier data, not the current batch’s action conditional on state and history. Fitting and reusing the same batch does not automatically preserve the zero-mean proof.
- For p=0.8 and b=0, what gradients can occur? Answer: Action 0 gives zero with probability 0.2; action 1 gives 0.2 with probability 0.8. Their mean is 0.16 and variance is 0.2 times 0.16 squared plus 0.8 times 0.04 squared, or 4/625.
- With varying episode lengths, is averaging inside each episode before averaging episodes still the original gradient estimator? Answer: Generally not. It adds a1/T weight and downweights longer episodes. Here gradients are summed within an episode before averaging episodes.
- How would you adapt to a deployment task without a natural endpoint? Answer: First specify a finite-horizon, discounted or average-reward objective, then choose fragment bootstrapping or an appropriate continuing-task algorithm. Record truncation separately from termination and check endpoint-value error; a loop limit alone is not task termination.
Check the original conditions and the modern episodic form separately
Williams’s 1992 paper gives REINFORCE gradient rules. The reading here covers PDF 4–7, including conditional baseline independence and the Bernoulli-logistic score, but not all delayed-reward chapters or appendices. Publisher metadata identifies May 1992, Machine Learning 8:229–256. The publisher PDF failed to download, so the original-paper mirror was used. Original paper
The pinned Spinning Up derivation supports the finite-episode and causal reward-to-go explanations; Sutton and colleagues’1999 PDF 2–4 covers the discounted start-state objective and occupancy. Teaching derivation Policy-gradient theorem The game, training settings and variance example are original teaching experiments, not benchmark replications.
Make a prediction, then check
With p=0.8 and reward equal to the action, which scalar baseline gives zero logit-gradient variance?
Learning objectives
- Implement episodic batch updates with frozen policies and baselines, avoiding current-sample baseline leakage.
- Calculate Bernoulli gradient variance and explain why the value baseline is not universally optimal.
Prerequisites & connections
Explore related knowledge →References
- Simple Statistical Gradient-Following Algorithms for Connectionist Reinforcement Learning — scoped original-paper reading
Ronald J. Williams · 1992 - Policy Gradient Methods for Reinforcement Learning with Function Approximation — scoped theorem reading
Richard S. Sutton; David McAllester; Satinder Singh; Yishay Mansour · 1999 - Spinning Up — scoped policy-gradient derivation
OpenAI; Joshua Achiam and contributors · 2020
Version1 · Editorial status: Recorded technical checks completed
View technical check record (AI)
Codex · 2026-09-23 · Single AI author. Scoped reading: Publisher metadata: May1992, Machine Learning8:229–256. Publisher PDF failed; original-paper mirror at gwern read on PDF1 for identity and4–7 in full, viewed6. Conditional baseline independence and expected gradient only; later delayed-reward chapters and appendices unaudited. Identity on PDF1; read2–4 and viewed3/4. Average reward, discounted occupancy and both compatible-approximation conditions. No later full proof audit or experiment replication. Fixed commit. Read rl_intro3 lines1–124,277–344,389–461 and VPG docs1–100: finite-horizon derivation, zero-mean score and baselines. README/license fully read; VPG code cached but unread. No upstream execution or copying. 5 paired equations and four explained exercises. Frozen policy and prior-batch baseline; exact expected episodic gradients and Bernoulli baseline-variance counterexample. All eight seeds for both variants retained. Same-state scalar variance optimum is not a whole-trajectory covariance optimum; no demonstrated general training advantage.
- Frozen policy and prior-batch baseline; exact expected episodic gradients and Bernoulli baseline-variance counterexample. All eight seeds for both variants retained. Same-state scalar variance optimum is not a whole-trajectory covariance optimum; no demonstrated general training advantage.
- Four computed SVG variants per topic;16 numeric/geometry tests and36 current responsive cases passed. All twelve selected current captures directly viewed. Three groups retain initial captures; three use their actually viewed revised captures. Actual assets and manuscripts are SHA bound. Full article acceptance recorded separately.
Source locations checked:
- Simple Statistical Gradient-Following Algorithms for Connectionist Reinforcement Learning — scoped original-paper reading · Publisher metadata: May1992, Machine Learning8:229–256. Publisher PDF failed; original-paper mirror at gwern read on PDF1 for identity and4–7 in full, viewed6. Conditional baseline independence and expected gradient only; later delayed-reward chapters and appendices unaudited.
- Policy Gradient Methods for Reinforcement Learning with Function Approximation — scoped theorem reading · Identity on PDF1; read2–4 and viewed3/4. Average reward, discounted occupancy and both compatible-approximation conditions. No later full proof audit or experiment replication.
- Spinning Up — scoped policy-gradient derivation · Fixed commit. Read rl_intro3 lines1–124,277–344,389–461 and VPG docs1–100: finite-horizon derivation, zero-mean score and baselines. README/license fully read; VPG code cached but unread. No upstream execution or copying.
Related topics