The policy gradient theorem and REINFORCE
Change approach: instead of learning values and acting greedily, directly optimize a parametrized policy. Prove the policy gradient theorem, derive REINFORCE and its autograd surrogate-loss implementation, and reduce variance with causality and baselines, including the optimal baseline. Clarify which gradient common implementations actually compute.
After this lesson you can
- Parametrize softmax and Gaussian policies and compute ∇log π for both.
- Prove the policy gradient theorem and explain why dynamics disappear from the derivative.
- Implement REINFORCE with reward-to-go and a baseline in NumPy and PyTorch.
- Prove a state-dependent baseline introduces no bias and derive the minimum-variance baseline.
- Explain the discrepancy between the theoretical gradient with γ^t and that computed by implementations.
Before you start
Move a distribution, not choose a maximum
A stochastic policy can assign probability to several actions even in the same state. Small parameter changes continuously change the trajectory distribution, even though sampled discrete actions are not differentiable. In an adversarial game or partially observable environment, randomization can be part of the solution; in continuous control, a parametrized distribution also directly provides exploration.
REINFORCE multiplies the direction that would make the sampled action more probable by a return signal. A good trajectory pushes its probability up and a bad one can push it down if a reference is subtracted. Each sample is noisy; the mathematical claim concerns its expectation and depends on the specified objective and sampling.
Preparing Gaussian samples.
Parametrized policies and their score function
For discrete actions a softmax policy turns logits into probabilities. With features and vector per action,
Positive probabilities allow logarithms; near an almost deterministic policy sensitivity and frequency of alternative actions can become very small. Discrete entropy measures spread, not performance.
For a one-dimensional Gaussian parametrized by and , holding observed action fixed when differentiating,
In multiple independent dimensions log-probabilities add. Differential entropy of the untransformed Gaussian is per dimension. Bounding helps prevent exploding or nearly zero deviations; it also changes the reachable policy space. If actions must be bounded, a transformation such as requires including the Jacobian when computing transformed density. Clipping a sample then evaluating as if unclipped does not represent the same distribution. For mixed spaces specify the joint distribution and dependencies, rather than assuming every action Gaussian.
The trajectory log-derivative trick
Consider an episodic finite-horizon MDP with dynamics and initial distribution independent of , bounded rewards and a differentiable policy whose support does not change as varies. Also assume an integrable function locally dominates trajectory-density derivatives times return, or an equivalent condition justifying exchange of gradient and expectation. In finite spaces the finite sum avoids that difficulty. Take after and
For trajectory its density factors into initial distribution, policies and transitions. Since only policies depend on ,
Thus , with . Dynamics do not disappear from the problem: they determine observed trajectories and rewards. What disappears from this expression is the need to differentiate their density with respect to policy parameters.
Rewards before cannot depend on that action once prior history is fixed. Their expected contribution is zero because . Defining return from as gives
Reward-to-go removes past terms whose expectation was zero. It can reduce variance, but strict reduction does not follow for every distribution and estimator.
Policy gradient theorem
Let be expected discounted return from time , and . For finite horizon include in the state if needed. Differentiating Bellman’s equation with fixed dynamics,
The terminal condition is . Recursively substitute the second part and average over : each visit at time contributes the first summand with factor . Using recovers
For discounted infinite horizon, , bounded rewards and conditions justifying interchange, define normalized discounted occupancy . Then factor appears:
For variable-length episodes use an absorbing state with zero contribution or retain the survival indicator. This proves the policy gradient theorem with explicit visit distribution; see Sutton and colleagues.
Preparing the surface.
Baselines and variance
For any function independent of the current action, conditioning on state gives
Thus can be replaced by in the estimator. This identity remains valid for a baseline using parameters, but in the surrogate loss gradients through the signal must be stopped: compute . Differentiating the baseline too adds a term absent from the estimator. A baseline trained on the same data may introduce additional dependencies; for a clean proof fix it before the evaluated batch or use independent data.
Preparing estimators.
A baseline does not always reduce variance. For one term and one scalar parameter, write and for the random signal. Since , the mean of does not depend on . If , minimizing variance is equivalent to minimizing ; differentiating with respect to gives
It need not be . With multiple parameters or trajectory terms, scalar criterion, covariances and admissible baseline change the optimum. Greensmith, Bartlett and Baxter study variance reduction and show a common reference choice can be suboptimal.
The often-missing factor
If the objective is discounted return from the start and ordinary trajectories are sampled, the estimator above includes . Using discounted but omitting weights temporal visits differently. This can be a practical choice, but is not generally the gradient of the same ; Nota and Thomas analyze this discrepancy.
Averaging over trajectories preserves the per-episode sum estimator’s scale. Averaging over steps in a variable-length batch introduces length-dependent normalization and requires declaring what is being estimated. Normalizing advantages with the same batch’s mean and standard deviation changes the finite estimator and does not guarantee unbiasedness; zero deviation also needs handling. An optimizer’s results and the estimated mean direction are not necessarily identical.
REINFORCE takes a Monte Carlo sample of these contributions; with a baseline it uses the same identity, not proof that every sample has the correct sign. Lab code retains action and return as data for the surrogate loss and separates evaluation from training.
Lab: exact gradient and REINFORCE
In this two-decision MDP, , both actions are 0 or 1 and . First reward is and second . The policy uses logistic probability with features . We can sum the four trajectories to obtain and compare its finite-difference gradient with mean REINFORCE. Standard error is calculated across independent trajectories in this experiment, not steps of one trajectory.
import numpy as np
gamma = .8
theta = np.array([-.3,.7])
def sigmoid(x):
return 1/(1+np.exp(-x))
def policy(state, parameters):
return sigmoid(parameters[0]+parameters[1]*state)
def objective(parameters):
total = 0.
p0 = policy(0,parameters)
for a0 in (0,1):
chance0 = p0 if a0 else 1-p0
p1 = policy(a0,parameters)
for a1 in (0,1):
chance1 = p1 if a1 else 1-p1
r0, r1 = .5*a0, (2*a1-1)*(1+a0)
total += chance0*chance1*(r0+gamma*r1)
return total
def finite_difference(parameters, epsilon=1e-5):
result = np.zeros_like(parameters)
for i in range(len(parameters)):
step = np.zeros_like(parameters)
step[i] = epsilon
result[i] = (objective(parameters+step)-objective(parameters-step))/(2*epsilon)
return result
rng = np.random.default_rng(2217)
count = 30000
a0 = (rng.random(count)<policy(0,theta)).astype(float)
p1 = policy(a0,theta)
a1 = (rng.random(count)<p1).astype(float)
r0 = .5*a0
r1 = (2*a1-1)*(1+a0)
score0 = np.stack((a0-policy(0,theta),np.zeros(count)),axis=1)
score1 = np.stack((a1-p1,(a1-p1)*a0),axis=1)
samples = score0*(r0+gamma*r1)[:,None]+gamma*score1*r1[:,None]
mean = samples.mean(axis=0)
se = samples.std(axis=0,ddof=1)/np.sqrt(count)
reference = finite_difference(theta)
assert np.all(np.abs(mean-reference)<5*se+1e-10)
print('J exacto:',objective(theta),'gradiente por diferencias finitas:',reference)
print('REINFORCE:',mean,'error estándar:',se,'semilla: 2217, trayectorias:',count)The five-standard-error comparison is a reproducible check for this sample, not a guarantee for all seeds. Exact evaluation enumerates the MDP here, while REINFORCE observes only trajectories.
CartPole built with NumPy
The following simulation implements CartPole equations with explicit Euler integration and the same discrete-action type described in the Gymnasium implementation. It uses an external finite horizon of 200 steps as part of the objective; it does not claim to reproduce all wrappers or environment versions. Evaluation compares the same deterministic rule before and after with separate seeds, without promising to solve the problem.
import numpy as np
gravity, mass_cart, mass_pole = 9.8, 1., .1
half_length, force_mag, dt = .5, 10., .02
total_mass = mass_cart+mass_pole
polemass_length = mass_pole*half_length
angle_limit = 12*np.pi/180
gamma, horizon = .99, 200
def step_cartpole(state, action):
x, xdot, angle, angular_velocity = state
force = force_mag if action else -force_mag
sine, cosine = np.sin(angle), np.cos(angle)
temporary = (force+polemass_length*angular_velocity**2*sine)/total_mass
angular_acc = (gravity*sine-cosine*temporary)/(half_length*(4/3-mass_pole*cosine**2/total_mass))
x_acc = temporary-polemass_length*angular_acc*cosine/total_mass
new_state = np.array([x+dt*xdot,xdot+dt*x_acc,
angle+dt*angular_velocity,angular_velocity+dt*angular_acc])
terminal = abs(new_state[0])>2.4 or abs(new_state[2])>angle_limit
return new_state, bool(terminal)
def phi(state):
return np.r_[1.,state]
def probability(state, weights):
value = weights@phi(state)
if value >= 0:
return 1/(1+np.exp(-value))
exponential = np.exp(value)
return exponential/(1+exponential)
def episode(weights, rng, deterministic=False):
state = rng.uniform(-.05,.05,4)
scores = []
for t in range(horizon):
p = probability(state,weights)
action = int(p>=.5) if deterministic else int(rng.random()<p)
scores.append((action-p)*phi(state))
state, terminal = step_cartpole(state,action)
if terminal: break
return np.asarray(scores), len(scores)
def evaluate(weights, seed, n=12):
rng = np.random.default_rng(seed)
return np.array([episode(weights,rng,True)[1] for _ in range(n)])
weights = np.zeros(5)
initial = evaluate(weights,771)
rng = np.random.default_rng(2218)
training_lengths = []
for _ in range(160):
scores, length = episode(weights,rng)
returns = np.zeros(length)
running = 0.
for t in range(length-1,-1,-1):
running = 1.+gamma*running
returns[t] = running
# Escala fija conocida de antemano; no normaliza por el lote muestreado.
gradient = np.sum((gamma**np.arange(length)*returns)[:,None]*scores,axis=0)/100.
norm = np.linalg.norm(gradient)
if norm>5.: gradient *= 5./norm
weights += .02*gradient
if not np.isfinite(weights).all(): raise FloatingPointError('Política no finita')
training_lengths.append(length)
final = evaluate(weights,771)
print('Evaluación determinista, 12 estados iniciales reproducibles:')
print('Media antes:',initial.mean(),'después:',final.mean())
print('Últimos 20 episodios de entrenamiento, media:',np.mean(training_lengths[-20:]))
print('Parámetros finales:',weights)Evaluation seeds are common to both policies, but the training policy is stochastic and evaluation deterministic. Norm clipping modifies the update and this small run may improve or worsen. It is not a convergence proof or Gymnasium benchmark.
Train two independent policies: softmax in CartPole-v1 and a diagonal Gaussian transformed by tanh in MuJoCo InvertedPendulum-v5. For the latter install Gymnasium with MuJoCo support and mujoco. The continuous policy uses Gaussian change of variables via tanh, not clipped samples treated as retaining their original density. The Jacobian corresponds to the continuous transform: in float32 different latents can round to the same action, including endpoints. Actions exactly at a bound are counted and log σ is bounded to .
Each update collects episodes with fixed policy. The objective is discounted episode return from the start and the loss uses multiplying remaining return . The baseline is computed before fitting its network to that batch and detached from the policy graph. Average over episodes, not the varying number of steps. By default returns are not normalized using the batch’s own statistics: this transformation can change the estimator. ORYON_REINFORCE_SCALE allows dividing all returns and baseline by a positive constant fixed before sampling; it changes scale, not objective direction.
To compare variance, gradients with and without the same baseline are computed on the same episodes, before updating either network and before clipping the applied gradient norm. The trace of per-episode gradient sample covariance and its division by batch size are logged, estimating variance of the mean of independent episodes. A learned baseline may increase variance in a batch; improvement is not forced. Greedy or Gaussian-mean evaluation uses separate seeds. ORYON_QUICK=1 limits episodes to 48 steps and runs three two-episode updates per environment; it optimizes a short horizon and does not prove environments solved. The reduced run verifies operation; you run full training.
import json
import math
import os
import random
from pathlib import Path
import gymnasium as gym
import numpy as np
import torch
from gymnasium import spaces
from torch import nn
from torch.distributions import Categorical, Normal
from torch.nn import functional as F
quick = os.environ.get('ORYON_QUICK','0') == '1'
out = Path(os.environ.get('ORYON_REINFORCE_OUT','oryon-reinforce'))
out.mkdir(parents=True,exist_ok=True)
scale = float(os.environ.get('ORYON_REINFORCE_SCALE','1'))
if not math.isfinite(scale) or scale <= 0:
raise ValueError('ORYON_REINFORCE_SCALE debe ser finita y positiva')
device = torch.device('cuda' if torch.cuda.is_available() else 'cpu')
gamma = .99
def reward_to_go(rewards, discount):
result = [0.]*len(rewards)
running = 0.
for i in range(len(rewards)-1,-1,-1):
running = rewards[i]+discount*running
result[i] = running
return result
assert np.allclose(reward_to_go([1.,2.,3.],.5),[2.75,3.5,3.])
class Policy(nn.Module):
def __init__(self, observation, action_space):
super().__init__()
self.discrete = isinstance(action_space,spaces.Discrete)
self.actions = action_space.n if self.discrete else int(np.prod(action_space.shape))
self.net = nn.Sequential(nn.Linear(observation,64),nn.Tanh(),nn.Linear(64,64),nn.Tanh(),
nn.Linear(64,self.actions))
if not self.discrete:
if not isinstance(action_space,spaces.Box) or not np.isfinite(action_space.low).all() or not np.isfinite(action_space.high).all():
raise ValueError('Se requiere una caja de acciones acotada')
low = torch.as_tensor(action_space.low.reshape(-1),dtype=torch.float32)
high = torch.as_tensor(action_space.high.reshape(-1),dtype=torch.float32)
if not torch.all(high>low): raise ValueError('Límites de acción inválidos')
self.register_buffer('midpoint',(high+low)/2)
self.register_buffer('half_range',(high-low)/2)
self.log_std = nn.Parameter(torch.full((self.actions,),-.5))
def action(self, observation, deterministic=False):
params = self.net(observation)
if self.discrete:
distribution = Categorical(logits=params)
sample = params.argmax(-1) if deterministic else distribution.sample()
return int(sample.item()), distribution.log_prob(sample)
distribution = Normal(params,self.log_std.clamp(-5.,1.).exp())
latent = params if deterministic else distribution.sample()
bounded = self.midpoint+self.half_range*torch.tanh(latent)
# log(1-tanh(u)^2) estable, incluso con u grande.
log_jac = 2*(math.log(2.)-latent-F.softplus(-2*latent))
log_prob = (distribution.log_prob(latent)-self.half_range.log()-log_jac).sum(-1)
return bounded.detach().cpu().numpy().astype(np.float32), log_prob
def one_episode(env, policy, seed, max_steps, deterministic=False):
observation,_ = env.reset(seed=seed)
observations, log_probs, rewards = [], [], []
terminated = truncated = False
saturated_actions = 0
for t in range(max_steps):
state = torch.as_tensor(observation,dtype=torch.float32,device=device)
observations.append(state)
action, log_prob = policy.action(state,deterministic)
if not policy.discrete and np.any((action == env.action_space.low) | (action == env.action_space.high)):
saturated_actions += 1
observation, reward, terminated, env_truncated, _ = env.step(action)
rewards.append(float(reward)); log_probs.append(log_prob)
truncated = bool(env_truncated or (t+1==max_steps and not terminated))
if terminated or truncated: break
return {'obs':torch.stack(observations),'logp':torch.stack(log_probs),
'rewards':rewards,'terminated':bool(terminated),'truncated':bool(truncated),
'actions_at_bounds':saturated_actions}
def gradient_vector(loss, parameters):
grads = torch.autograd.grad(loss,parameters,retain_graph=True,allow_unused=True)
return torch.cat([(torch.zeros_like(p) if g is None else g).detach().reshape(-1)
for p,g in zip(parameters,grads)])
def trace_variance(vectors):
if len(vectors)<2: return None
x = torch.stack(vectors)
return float(((x-x.mean(0))**2).sum()/(len(vectors)-1))
def evaluate(env,policy,seeds,max_steps):
records = []
with torch.no_grad():
for seed in seeds:
ep = one_episode(env,policy,seed,max_steps,deterministic=True)
records.append({'seed':seed,'return':sum(ep['rewards']),
'discounted_finite_return':reward_to_go(ep['rewards'],gamma)[0],
'steps':len(ep['rewards']),'terminated':ep['terminated'],
'truncated':ep['truncated'],'actions_at_bounds':ep['actions_at_bounds']})
return records
def train(environment,seed):
random.seed(seed); np.random.seed(seed); torch.manual_seed(seed)
if torch.cuda.is_available(): torch.cuda.manual_seed_all(seed)
try:
env = gym.make(environment)
eval_env = gym.make(environment)
except Exception as exc:
raise RuntimeError(f'No se pudo abrir {environment}; instala gymnasium[mujoco] y mujoco si falta') from exc
policy = Policy(int(np.prod(env.observation_space.shape)),env.action_space).to(device)
baseline = nn.Sequential(nn.Linear(4,64),nn.Tanh(),nn.Linear(64,1)).to(device)
policy_opt = torch.optim.Adam(policy.parameters(),lr=.001)
value_opt = torch.optim.Adam(baseline.parameters(),lr=.001)
params = tuple(policy.parameters())
batches, batch_size, limit = (3,2,48) if quick else (300,8,1000)
report = []
try:
for update in range(batches):
episodes = [one_episode(env,policy,seed+100000*update+i,limit) for i in range(batch_size)]
losses, losses_plain, value_losses = [], [], []
for episode in episodes:
returns = torch.tensor(reward_to_go(episode['rewards'],gamma),device=device,dtype=torch.float32)
values = baseline(episode['obs']).squeeze(-1)
discounts = gamma**torch.arange(len(returns),device=device,dtype=torch.float32)
# Valores y retornos son constantes desde el punto de vista de la política.
plain = -(discounts*episode['logp']*(returns/scale).detach()).sum()
based = -(discounts*episode['logp']*((returns-values)/scale).detach()).sum()
losses_plain.append(plain); losses.append(based)
value_losses.append(F.mse_loss(values,returns.detach()))
plain_grads = [gradient_vector(loss,params) for loss in losses_plain]
baseline_grads = [gradient_vector(loss,params) for loss in losses]
plain_var, baseline_var = trace_variance(plain_grads), trace_variance(baseline_grads)
policy_loss = torch.stack(losses).mean()
value_loss = torch.stack(value_losses).mean()
if not torch.isfinite(policy_loss) or not torch.isfinite(value_loss):
raise FloatingPointError('Pérdida no finita')
policy_opt.zero_grad(set_to_none=True); policy_loss.backward()
if any(p.grad is not None and not torch.isfinite(p.grad).all() for p in params):
raise FloatingPointError('Gradiente no finito')
nn.utils.clip_grad_norm_(params,10.)
policy_opt.step()
if not policy.discrete:
with torch.no_grad(): policy.log_std.clamp_(-5.,1.)
value_opt.zero_grad(set_to_none=True); value_loss.backward(); value_opt.step()
row = {'update':update+1,'train_returns':[sum(e['rewards']) for e in episodes],
'train_steps':[len(e['rewards']) for e in episodes],
'train_terminated':[e['terminated'] for e in episodes],
'train_truncated':[e['truncated'] for e in episodes],
'train_actions_at_bounds':[e['actions_at_bounds'] for e in episodes],
'policy_loss':float(policy_loss.detach()),'baseline_mse':float(value_loss.detach()),
'gradient_variance_trace_plain':plain_var,'gradient_variance_trace_baseline':baseline_var,
'estimated_batch_mean_variance_plain':plain_var/batch_size if plain_var is not None else None,
'estimated_batch_mean_variance_baseline':baseline_var/batch_size if baseline_var is not None else None}
if (update+1)%(1 if quick else 25)==0 or update+1==batches:
eval_seeds = [100000000+1000*seed+i for i in range(2 if quick else 10)]
row['evaluation'] = evaluate(eval_env,policy,eval_seeds,limit)
report.append(row)
return {'environment':environment,'seed':seed,'updates':batches,'batch_size':batch_size,
'max_episode_steps':limit,'history':report}
finally:
env.close(); eval_env.close()
del policy,baseline,policy_opt,value_opt
if torch.cuda.is_available(): torch.cuda.empty_cache()
results = [train(name,221700+i) for i,name in enumerate(('CartPole-v1','InvertedPendulum-v5'))]
report = {'quick':quick,'gamma':gamma,'reward_scale':scale,'torch':torch.__version__,
'gymnasium':gym.__version__,'device':str(device),'evaluation':'voraz o media gaussiana con tanh',
'episode_seed_rule':'seed + 100000 * update_index + episode_index',
'evaluation_seed_rule':'100000000 + 1000 * train_seed + episode_index',
'gradient_variance':'traza de covarianza muestral por episodio; misma muestra para ambos estimadores',
'results':results}
(out/'reinforce-report.json').write_text(json.dumps(report,indent=2),encoding='utf-8')
for item in results:
last=item['history'][-1]
print(item['environment'],'evaluación media',np.mean([e['return'] for e in last['evaluation']]),
'varianza sin/con base',last['gradient_variance_trace_plain'],last['gradient_variance_trace_baseline'])npm run lab and open the connection link.The environment may end by its own signal or the experiment’s external limit; in either case this cell optimizes observed finite return, without bootstrapping an unobserved tail. Full mode limits to 1000 steps; CartPole may truncate earlier at its own limit. The Gaussian policy evaluates deterministically using tanh of latent mean, a particular evaluation rule, not necessarily the transformed distribution’s mean. Independent environment and evaluation do not make three episodes or one seed a benchmark. The surrogate loss has the desired gradient only with samples treated as constants and the indicated explicit factors. The REINFORCE reference is Williams, 1992.
Exercises
Step 1 of 3. When differentiating Vₜ(s)=Σₐπθ(a|s)Qₜ(s,a), what is the first term?
Step 1 of 3. How does the expectation of S(G−b) change?
import numpy as np
features = np.array([1., 2.])
logits = np.array([0., np.log(3.)])
probabilities = np.exp(logits - logits.max())
probabilities /= probabilities.sum()
print('Probabilidades:', probabilities)
print('Score de la acción 1:', (1 - probabilities[1]) * features)
print('Score de la acción 0:', -probabilities[0] * features)import numpy as np
def policy_gradient_loss(params, actions, returns, baseline, factors, kind):
pass