Module contents
Lesson 17 of 37Core 110 min

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.

InteractiveEach sample contributes a direction

Preparing Gaussian samples.

Adjust policy and reward and compare individual contributions with their mean.

Parametrized policies and their score function

For discrete actions a softmax policy turns logits hθ(s,a)h_\theta(s,a) into probabilities. With features ϕ(s)\phi(s) and vector θa\theta_a per action,

πθ(a∣s)=eθa⊤ϕ(s)∑beθb⊤ϕ(s),∇θblog⁡πθ(a∣s)=(1{a=b}−πθ(b∣s))ϕ(s).\pi_\theta(a\mid s)=\frac{e^{\theta_a^\top\phi(s)}}{\sum_b e^{\theta_b^\top\phi(s)}}, \qquad \nabla_{\theta_b}\log\pi_\theta(a\mid s) =(\mathbf1_{\{a=b\}}-\pi_\theta(b\mid s))\phi(s).

Positive probabilities allow logarithms; near an almost deterministic policy sensitivity and frequency of alternative actions can become very small. Discrete entropy −∑aπ(a∣s)log⁡π(a∣s)-\sum_a\pi(a\mid s)\log\pi(a\mid s) measures spread, not performance.

For a one-dimensional Gaussian A∼N(μ,σ2)A\sim\mathcal N(\mu,\sigma^2) parametrized by μ\mu and ℓ=log⁡σ\ell=\log\sigma, holding observed action fixed when differentiating,

∂log⁡π(A)∂μ=A−μσ2,∂log⁡π(A)∂ℓ=(A−μ)2σ2−1.\frac{\partial\log\pi(A)}{\partial\mu}=\frac{A-\mu}{\sigma^2}, \qquad \frac{\partial\log\pi(A)}{\partial\ell} =\frac{(A-\mu)^2}{\sigma^2}-1.

In multiple independent dimensions log-probabilities add. Differential entropy of the untransformed Gaussian is 12log⁡(2πeσ2)\tfrac12\log(2\pi e\sigma^2) per dimension. Bounding ℓ\ell helps prevent exploding or nearly zero deviations; it also changes the reachable policy space. If actions must be bounded, a transformation such as tanh⁡\tanh 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 TT with dynamics and initial distribution independent of θ\theta, bounded rewards and a differentiable policy whose support does not change as θ\theta 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 Rt+1R_{t+1} after AtA_t and

J(θ)=Eπθ ⁣[∑t=0T−1γtRt+1],0≤γ≤1.J(\theta)=\mathbb E_{\pi_\theta}\!\left[\sum_{t=0}^{T-1}\gamma^tR_{t+1}\right], \quad 0\leq\gamma\leq1.

For trajectory τ=(s0,a0,…,sT)\tau=(s_0,a_0,\ldots,s_T) its density factors into initial distribution, policies and transitions. Since only policies depend on θ\theta,

∇θlog⁡pθ(τ)=∑t=0T−1∇θlog⁡πθ(at∣st).\nabla_\theta\log p_\theta(\tau) =\sum_{t=0}^{T-1}\nabla_\theta\log\pi_\theta(a_t\mid s_t).

Thus ∇J=E[G0∑t∇log⁡π(At∣St)]\nabla J=\mathbb E[G_0\sum_t\nabla\log\pi(A_t\mid S_t)], with G0=∑tγtRt+1G_0=\sum_t\gamma^tR_{t+1}. 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 AtA_t cannot depend on that action once prior history is fixed. Their expected contribution is zero because ∑aπ(a∣s)∇log⁡π(a∣s)=∇∑aπ(a∣s)=0\sum_a\pi(a\mid s)\nabla\log\pi(a\mid s)=\nabla\sum_a\pi(a\mid s)=0. Defining return from tt as Gt=∑k=tT−1γk−tRk+1G_t=\sum_{k=t}^{T-1}\gamma^{k-t}R_{k+1} gives

∇J(θ)=Eπθ ⁣[∑t=0T−1γt∇θlog⁡πθ(At∣St) Gt].\nabla J(\theta)= \mathbb E_{\pi_\theta}\!\left[\sum_{t=0}^{T-1} \gamma^t\nabla_\theta\log\pi_\theta(A_t\mid S_t)\,G_t\right].

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 Qtπ(s,a)Q_t^\pi(s,a) be expected discounted return from time tt, and Vtπ(s)=∑aπθ(a∣s)Qtπ(s,a)V_t^\pi(s)=\sum_a\pi_\theta(a\mid s)Q_t^\pi(s,a). For finite horizon include tt in the state if needed. Differentiating Bellman’s equation with fixed dynamics,

∇Vtπ(s)=∑a∇πθ(a∣s) Qtπ(s,a)+γ∑a,s′πθ(a∣s)P(s′∣s,a)∇Vt+1π(s′).\nabla V_t^\pi(s) =\sum_a\nabla\pi_\theta(a\mid s)\,Q_t^\pi(s,a) +\gamma\sum_{a,s'}\pi_\theta(a\mid s)P(s'\mid s,a)\nabla V_{t+1}^\pi(s').

The terminal condition is ∇VTπ=0\nabla V_T^\pi=0. Recursively substitute the second part and average over S0S_0: each visit at time tt contributes the first summand with factor γt\gamma^t. Using ∇π=π∇log⁡π\nabla\pi=\pi\nabla\log\pi recovers

∇J=∑t=0T−1γtE[∇log⁡πθ(At∣St)Qtπ(St,At)].\nabla J= \sum_{t=0}^{T-1}\gamma^t \mathbb E[\nabla\log\pi_\theta(A_t\mid S_t)Q_t^\pi(S_t,A_t)].

For discounted infinite horizon, 0≤γ<10\leq\gamma<1, bounded rewards and conditions justifying interchange, define normalized discounted occupancy dγπ(s)=(1−γ)∑t≥0γtP(St=s)d_\gamma^\pi(s)=(1-\gamma)\sum_{t\geq0}\gamma^tP(S_t=s). Then factor 1/(1−γ)1/(1-\gamma) appears:

∇J=11−γ ES∼dγπ,A∼π[∇log⁡π(A∣S)Qπ(S,A)].\nabla J=\frac{1}{1-\gamma}\, \mathbb E_{S\sim d_\gamma^\pi,A\sim\pi} [\nabla\log\pi(A\mid S)Q^\pi(S,A)].

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.

InteractiveThe landscape of a softmax policy

Preparing the surface.

Explore the MDP's exact return and a trajectory of sampled updates.

Baselines and variance

For any function b(s)b(s) independent of the current action, conditioning on state gives

EA∼π[b(s)∇θlog⁡πθ(A∣s)]=b(s)∇θ∑aπθ(a∣s)=0.\mathbb E_{A\sim\pi}[ b(s)\nabla_\theta\log\pi_\theta(A\mid s)] =b(s)\nabla_\theta\sum_a\pi_\theta(a\mid s)=0.

Thus GtG_t can be replaced by Gt−b(St)G_t-b(S_t) 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 −log⁡πθ(At∣St)stopgrad⁡(Gt−b(St))-\log\pi_\theta(A_t\mid S_t)\operatorname{stopgrad}(G_t-b(S_t)). 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.

InteractiveWhat does a baseline change?

Preparing estimators.

Compare estimator distributions and batch sizes in an explicit environment.

A baseline does not always reduce variance. For one term and one scalar parameter, write S=∂θlog⁡π(A∣s)S=\partial_\theta\log\pi(A\mid s) and GG for the random signal. Since E[S∣s]=0\mathbb E[S\mid s]=0, the mean of S(G−b)S(G-b) does not depend on bb. If E[S2∣s]>0\mathbb E[S^2\mid s]>0, minimizing variance is equivalent to minimizing E[S2(G−b)2∣s]\mathbb E[S^2(G-b)^2\mid s]; differentiating with respect to bb gives

b∗(s)=E[S2G∣s]E[S2∣s].b^*(s)=\frac{\mathbb E[S^2G\mid s]}{\mathbb E[S^2\mid s]}.

It need not be Vπ(s)V^\pi(s). 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 γtGt\gamma^tG_t. Using discounted GtG_t but omitting γt\gamma^t weights temporal visits differently. This can be a practical choice, but is not generally the gradient of the same JJ; 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, S0=0S_0=0, both actions are 0 or 1 and S1=A0S_1=A_0. First reward is A0/2A_0/2 and second (2A1−1)(1+S1)(2A_1-1)(1+S_1). The policy uses logistic probability with features (1,s)(1,s). We can sum the four trajectories to obtain JJ and compare its finite-difference gradient with mean REINFORCE. Standard error is calculated across independent trajectories in this experiment, not steps of one trajectory.

[ ]Check the gradient on four trajectoriesBrowser
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.

[ ]NumPy REINFORCE on CartPoleBrowser
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 [−5,1][-5,1].

Each update collects episodes with fixed policy. The objective is discounted episode return from the start and the loss uses γt\gamma^t multiplying remaining return GtG_t. 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.

[ ]Discrete and Gaussian REINFORCE with baselineLocal GPU
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'])
This cell needs the local lab (PyTorch with your GPU). Start it with 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

ProofUnrolling the Bellman gradient
Prove: Prove the policy gradient theorem for a finite-horizon finite MDP and differentiable policy.
0
Initial distribution and dynamics do not depend on θ, πθ support is fixed and probabilities positive. Post-action reward is discounted by γ∈[0,1]. Time is part of state if needed; VT=0.

Step 1 of 3. When differentiating Vₜ(s)=Σₐπθ(a|s)Qₜ(s,a), what is the first term?

ProofUnbiasedness and optimal baseline
Prove: At a fixed state study one parameter and a return signal G.
0
S=∂θ log πθ(A|s), E[S|s]=0 and E[S²|s]>0. Assume necessary finite moments. Scalar baseline b(s) is fixed independently of the current action.

Step 1 of 3. How does the expectation of S(G−b) change?

NumericOne softmax score component
Two actions use φ(s)=(1,2), θ₀=(0,0) and θ₁=(ln 3,0). Action 1 is observed. Calculate ∂ log π(1|s) / ∂ θ₁,₂, where θ₁,₂ is the second component of action 1's vector.
[ ]Check the softmax scoreBrowser
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)
CodeSurrogate loss and its gradients
Implement policy_gradient_loss(params, actions, returns, baseline, factors, kind). There are B≥1 one-decision episodes; returns, baseline and factors are finite real arrays of shape (B,) and constant when differentiating. With kind='categorical', params has shape (B,A), A≥2, and actions contains valid integer indices (B,). With kind='normal', params has shape (B,2D), first D columns means and last D log σ, and actions has shape (B,D); D≥1 and log σ lies between −5 and 1. Return (loss, grad), where loss=−mean(factors(returns−baseline)log π(actions)) and grad is its derivative with respect to params, with the same shape. For the diagonal Gaussian sum log densities across dimensions. Implement numerically stable logits in NumPy; do not change inputs. You may assume data satisfy the contract.
import numpy as np

def policy_gradient_loss(params, actions, returns, baseline, factors, kind):
  pass
Shift+Enter to run
QuizWhat signal can you subtract?
For ordinary trajectories of a finite MDP and J discounted from the start, which statement is correct?