Module contents
Lesson 19 of 37Advanced 115 min

Monotonic improvement: performance difference, natural gradient and TRPO

An overly large gradient step destroys the policy and future data. Prove the performance difference lemma, construct the surrogate objective and monotonic-improvement bound, derive natural policy gradient using Fisher geometry, and implement TRPO with conjugate gradients and line search. Close with modern global convergence theory for policy-gradient methods.

After this lesson you can

  • Prove the performance difference lemma by telescoping.
  • Construct the surrogate objective and explain the KL-penalized improvement bound.
  • Derive natural policy gradient and its parametrization invariance.
  • Implement TRPO with Fisher-vector products, conjugate gradients and line search.
  • Summarize global convergence results for softmax-parametrized NPG.

Before you start

A local improvement can change the data

A policy update changes not only action probabilities but also states visited later. A step promising under old-policy data can take the agent into regions where that comparison no longer represents what happens. A trust region measures movement in policy space and limits it, not merely parameter distance.

InteractiveMoving on the simplex

Preparing the trust region.

Compare parameter movements with distances between resulting policies.

Performance difference by telescoping

Work in a finite discounted MDP with bounded rewards, fixed initial distribution μ\mu and 0≤γ<10\leq\gamma<1. For stationary policy π\pi, let J(π)=Eμ[Vπ(S0)]J(\pi)=\mathbb E_\mu[V^\pi(S_0)] and dμπ(s)=(1−γ)∑t≥0γtPπ(St=s)d^\pi_\mu(s)=(1-\gamma)\sum_{t\geq0}\gamma^tP_\pi(S_t=s) be its normalized discounted occupancy.

Fix reference policy π\pi and follow another policy π′\pi'. By the definition of advantage,

E[Aπ(St,At)∣St,At]=E[Rt+1+γVπ(St+1)−Vπ(St)∣St,At].\mathbb E[A^\pi(S_t,A_t)\mid S_t,A_t] =\mathbb E[R_{t+1}+\gamma V^\pi(S_{t+1})-V^\pi(S_t)\mid S_t,A_t].

Multiply by γt\gamma^t, sum from zero and take expectation under π′\pi'. Interior VπV^\pi terms cancel. The final term tends to zero because VπV^\pi is bounded and γ<1\gamma<1; the initial term is J(π)J(\pi). This gives the performance difference lemma:

J(π′)−J(π)=11−γES∼dμπ′, A∼π′(⋅∣S)[Aπ(S,A)].J(\pi')-J(\pi)= \frac{1}{1-\gamma} \mathbb E_{S\sim d^{\pi'}_\mu,\ A\sim\pi'(\cdot\mid S)} [A^\pi(S,A)].

The occupancy is that of π′\pi'. Knowing advantages in states frequent under π\pi is insufficient: the candidate may visit them at different frequencies. The identity is exact under the assumptions above; it does not alone make a sample estimate exact.

Surrogate and conservative bound

The surrogate objective retains old occupancy:

Lπ(π′)=J(π)+11−γES∼dμπ, A∼π′(⋅∣S)[Aπ(S,A)].L_\pi(\pi')=J(\pi)+\frac{1}{1-\gamma} \mathbb E_{S\sim d^\pi_\mu,\ A\sim\pi'(\cdot\mid S)} [A^\pi(S,A)].

At π′=π\pi'=\pi both quantities coincide because mean advantage under π\pi is zero. With suitable support, action expectation can be written using samples from π\pi and ratio π′(a∣s)/π(a∣s)\pi'(a\mid s)/\pi(a\mid s). That ratio corrects the action distribution, not the difference between state occupancies.

Conservative iteration by Kakade and Langford considers a mixture π′=(1−α)π+απcandidata\pi'=(1-\alpha)\pi+\alpha\pi_{\mathrm{candidata}} and limits policy change per update. Guaranteed improvement comes from the bound and its assumptions, not mixture alone. The TRPO version cited below extends the improvement argument to general stochastic policies.

InteractiveSurrogate versus true performance

Preparing the MDP and surrogate.

Compare old and new occupancy in an MDP where both are computed exactly.

Let ϵ=max⁡s,a∣Aπ(s,a)∣\epsilon=\max_{s,a}|A^\pi(s,a)| and α=max⁡sDTV(π(⋅∣s),π′(⋅∣s))\alpha=\max_sD_{\mathrm{TV}}(\pi(\cdot\mid s),\pi'(\cdot\mid s)). The conservative bound in the arXiv version of TRPO says

J(π′)≥Lπ(π′)−4ϵγ(1−γ)2α2.J(\pi')\geq L_\pi(\pi')- \frac{4\epsilon\gamma}{(1-\gamma)^2}\alpha^2.

The proof idea is quantitative. Couple both policies so that while sharing a state their actions differ with probability at most α\alpha. Probability of a disagreement before time tt is at most 1−(1−α)t1-(1-\alpha)^t. Meanwhile Aˉ(s)=Ea∼π′Aπ(s,a)\bar A(s)=\mathbb E_{a\sim\pi'}A^\pi(s,a) has magnitude at most 2ϵα2\epsilon\alpha, since its mean under π\pi is zero. The difference of expectations of Aˉ\bar A under the two state distributions is bounded by 4ϵα[1−(1−α)t]4\epsilon\alpha[1-(1-\alpha)^t]. Summing with weight γt\gamma^t and using 1−(1−α)t≤tα1-(1-\alpha)^t\leq t\alpha gives the bound’s term. Coupling and assumptions are detailed in the paper’s appendix.

Using the inequality employed there, α2≤max⁡sDKL(π(⋅∣s)∥π′(⋅∣s))\alpha^2\leq\max_sD_{\mathrm{KL}}(\pi(\cdot\mid s)\Vert\pi'(\cdot\mid s)), gives a bound with the same coefficient for maximum KL. If that KL is infinite, the bound is vacuous. Improvement of the bound relative to J(π)J(\pi) guarantees performance improvement in the exact model. Observing surrogate improvement alone is insufficient: subtract the penalty and know the bound quantities. The guarantee concerns exact advantages and divergences, not automatically a finite sample.

Fisher geometry

Mean KL under old occupancy, expanded around parameters θ\theta, has local form

DˉKL(θ,θ+Δ)=12Δ⊤F(θ)Δ+o(∥Δ∥2),F=Es∼dπ,a∼π[∇log⁡π(a∣s)∇log⁡π(a∣s)⊤].\bar D_{\mathrm{KL}}(\theta,\theta+\Delta) =\tfrac12\Delta^\top F(\theta)\Delta+o(\|\Delta\|^2), \qquad F=\mathbb E_{s\sim d^\pi,a\sim\pi} [\nabla\log\pi(a\mid s)\nabla\log\pi(a\mid s)^\top].

Matrix FF measures local distribution changes. If positive definite and g=∇θJg=\nabla_\theta J, maximizing g⊤Δg^\top\Delta under 12Δ⊤FΔ≤δ\tfrac12\Delta^\top F\Delta\leq\delta gives

Δ=2δg⊤F−1g F−1g,\Delta= \sqrt{\frac{2\delta}{g^\top F^{-1}g}}\,F^{-1}g,

if g≠0g\ne0 and δ>0\delta>0. Direction F−1gF^{-1}g is Kakade’s natural policy gradient. Under a smooth invertible reparametrization, Fisher and gradient transform so the infinitesimal direction in policy space agrees. Finite steps in different coordinates need not produce exactly the same policy.

Fisher is positive semidefinite, not always invertible. In tabular softmax, adding a constant to all logits of a state leaves policy unchanged and creates a null direction. One can work in quotient space, fix a reference or use a pseudoinverse; damping F+ξIF+\xi I eases computation but depends on coordinates and changes geometry. Small mean KL also need not control maximum KL at a rare state.

TRPO as an approximate algorithm

TRPO replaces direct bound optimization with a tractable problem: maximize a sample-estimated surrogate subject to a mean KL constraint between frozen old and candidate policies. It linearizes the objective, approximates KL quadratically and solves the system using conjugate gradients. Fisher-vector products can be computed with two backpropagations without forming the full matrix.

InteractiveSolve without forming the matrix

Preparing the linear system.

Follow conjugate iterations in an explicit two-dimensional system.

With an approximate direction, line search tries decreasing fractions of the step. Every candidate must satisfy empirical mean KL and improve the empirical surrogate; if none passes, old parameters are restored. Nonpositive curvature, near-zero gradient and numerical errors must also be handled. The KL reference is not updated during search. A shared-trunk implementation must ensure subsequent critic updates do not inadvertently alter the accepted policy.

Mean KL replaces the theorem’s maximum; advantages are estimated, the quadratic region is only local, and conjugate gradients stop at finite tolerance. Thus accepting a TRPO step does not guarantee true monotonic improvement each iteration. Hessian-vector products and line-search cost motivated simpler alternatives including PPO, studied next.

Can it converge globally?

In a finite MDP with positive-support tabular softmax, discounted-occupancy-weighted Fisher and exact gradients and advantages, the natural direction in each visited state’s logits is Aπ(s,a)/(1−γ)A^\pi(s,a)/(1-\gamma) up to an action-common constant. An additive step in those logits equals

πnueva(a∣s)∝π(a∣s)exp⁡ ⁣(ηAπ(s,a)1−γ).\pi_{\mathrm{nueva}}(a\mid s)\propto \pi(a\mid s)\exp\!\left(\frac{\eta A^\pi(s,a)}{1-\gamma}\right).

The common constant disappears on normalization. The expression requires declaring Fisher normalization and states with positive occupancy; another convention changes the scale factor. An optimal deterministic policy may be a limit of logits, not a finite-parameter point.

The global convergence theory of Agarwal and colleagues gives results for tabular cases under specific assumptions. For example, with rewards in [0,1][0,1], uniform initialization, exact gradients, Fisher pseudoinverse, fixed step η>0\eta>0 and the same initial distribution μ\mu for optimization and evaluation, theorem 16 bounds after TT iterations

V∗(μ)−VπT(μ)≤log⁡∣A∣ηT+1(1−γ)2T.V^*(\mu)-V^{\pi_T}(\mu) \leq \frac{\log|\mathcal A|}{\eta T} +\frac{1}{(1-\gamma)^2T}.

The result concerns value; it does not assert all logits converge. Function approximation or samples introduce estimation, representation and occupancy mismatch errors; these results do not make every deep TRPO training run a guaranteed global optimizer.

Labs

In this finite MDP transition and reward are known. Policy has one logit per action and state, γ is below one and initial distribution fixed. Compute value by solving Bellman and normalized discounted occupancy

dπ⊤=(1−γ)μ⊤(I−γPπ)−1.d_\pi^\top=(1-\gamma)\mu^\top(I-\gamma P_\pi)^{-1}.

With this convention, the gradient of J=μ⊤VπJ=\mu^\top V^\pi carries factor 1/(1−γ)1/(1-\gamma), while Fisher below is the mean score under dπd_\pi. Logits allow one common constant per state: Fisher is singular. Use the Moore–Penrose pseudoinverse and check both solution and equivalent policy step; no damping is added in this example.

[ ]Exact gradient and Fisher of a tabular policyBrowser
import numpy as np

gamma = .9
mu = np.array([1.,0.])
P = np.array([[[.95,.05],[.2,.8]], [[.7,.3],[.1,.9]]])
R = np.array([[0.,.4],[0.,1.]])
assert np.all(P >= 0) and np.allclose(P.sum(axis=2),1.)
assert np.all(mu >= 0) and np.isclose(mu.sum(),1.)

def policy(logits):
    shifted = logits-logits.max(axis=1,keepdims=True)
    x = np.exp(shifted)
    return x/x.sum(axis=1,keepdims=True)

def evaluate(logits):
    pi = policy(logits)
    transition = np.einsum('sa,san->sn',pi,P)
    reward = np.sum(pi*R,axis=1)
    matrix = np.eye(2)-gamma*transition
    value = np.linalg.solve(matrix,reward)
    occupancy = (1-gamma)*np.linalg.solve(matrix.T,mu)
    q = R + gamma*np.einsum('san,n->sa',P,value)
    advantage = q-value[:,None]
    return float(mu@value),pi,occupancy,value,advantage

def exact_gradient(logits):
    _,pi,d,_,advantage = evaluate(logits)
    return d[:,None]*pi*advantage/(1-gamma)

def fisher(logits):
    _,pi,d,_,_ = evaluate(logits)
    F = np.zeros((4,4))
    for s in range(2):
        F[2*s:2*s+2,2*s:2*s+2] = d[s]*(np.diag(pi[s])-np.outer(pi[s],pi[s]))
    return F

theta0 = np.array([[3.,-3.],[3.,-3.]])
J,pi,d,value,A = evaluate(theta0)
grad = exact_gradient(theta0)
eps = 1e-5
finite = np.zeros_like(theta0)
for s in range(2):
    for a in range(2):
        plus = theta0.copy(); minus = theta0.copy()
        plus[s,a] += eps; minus[s,a] -= eps
        finite[s,a] = (evaluate(plus)[0]-evaluate(minus)[0])/(2*eps)
F = fisher(theta0)
natural = (np.linalg.pinv(F,rcond=1e-12)@grad.ravel()).reshape(theta0.shape)
assert np.isclose(d.sum(),1.) and np.all(d > 0)
assert np.allclose(np.sum(pi*A,axis=1),0.,atol=1e-12)
assert np.allclose(grad,finite,atol=1e-9,rtol=1e-7)
assert np.allclose([email protected](),grad.ravel(),atol=1e-12)
# Cada fila solo está definida salvo una constante; comparar políticas evita fijar gauge.
eta = .12
mult = pi*np.exp(eta*A/(1-gamma)); mult /= mult.sum(axis=1,keepdims=True)
assert np.allclose(policy(theta0+eta*natural),mult,atol=1e-12)
assert np.allclose(evaluate(theta0+np.array([[4.],[7.]]))[0],J,atol=1e-12)
print('J inicial:',round(J,8),'ocupación:',np.round(d,8))
print('Gradiente exacto:',np.round(grad,8))
print('Error máximo de diferencias finitas:',float(np.max(np.abs(grad-finite))))
rank = np.linalg.matrix_rank(F,tol=1e-12)
assert rank == 2
print('Rango numérico Fisher, tolerancia 1e-12:',rank,'dimensión:',F.shape[0])
print('Residuo F·natural−gradiente:',float(np.max(np.abs([email protected]()-grad.ravel()))))

The comparison uses the same MDP and near-deterministic initial policy for both methods. First run the previous cell defining environment and common functions. At each iteration compute gradient using current-policy occupancy. Ordinary step adds ηg\eta g to logits; natural step adds ηF+g\eta F^+g. The same numeric η does not equalize KL distance or computation, so this trajectory illustrates a plateau in these coordinates and does not prove a general rate or superiority. In a small problem exact mean KL under old occupancy can be calculated; TRPO constrains it with line search, not implemented here.

[ ]Plateau and natural gradient in the same MDPBrowser
import numpy as np

def kl_mean(old_logits,new_logits):
    _,old_pi,d,_,_ = evaluate(old_logits)
    new_pi = policy(new_logits)
    return float(np.sum(d[:,None]*old_pi*(np.log(old_pi)-np.log(new_pi))))

def run(natural_step,iterations=35,eta=.12):
    theta = theta0.copy()
    scores = [evaluate(theta)[0]]
    divergences = []
    for _ in range(iterations):
        g = exact_gradient(theta)
        direction = (np.linalg.pinv(fisher(theta),rcond=1e-12)@g.ravel()).reshape(theta.shape) if natural_step else g
        next_theta = theta + eta*direction
        divergences.append(kl_mean(theta,next_theta))
        theta = next_theta
        scores.append(evaluate(theta)[0])
    return np.array(scores),np.array(divergences),policy(theta)

ordinary,kl_ordinary,pi_ordinary = run(False)
natural_curve,kl_natural,pi_natural = run(True)
assert np.all(np.diff(ordinary) >= -1e-10)
assert np.all(np.diff(natural_curve) >= -1e-10)
print('Actualizaciones:',len(ordinary)-1,'η:',.12)
for t in (0,5,15,35):
    print('paso',t,'J ordinario',round(ordinary[t],6),'J natural',round(natural_curve[t],6))
print('KL media máxima por paso, ordinario/natural:',
      round(float(kl_ordinary.max()),8),round(float(kl_natural.max()),8))
print('Política final ordinaria:',pi_ordinary)
print('Política final natural:',pi_natural)

Compare TRPO and A2C from scratch on Hopper-v5 or HalfCheetah-v5, with the same architecture, seeds, transition count and greedy evaluation in separate environments. Install PyTorch, gymnasium[mujoco]==1.4.0 and MuJoCo. ORYON_TRPO_ENV selects one of those environments, Hopper by default. Full mode uses five seeds and 2,048,000 transitions per method per seed. Shared seeds do not equalize trajectories once policies change. TRPO cost includes more actor evaluations and Fisher-vector products: equal transition count is not equal computation.

Actions come from a diagonal Gaussian and tanh affine to action bounds. The probability ratio uses the same latent under both policies: the continuous-transform Jacobian cancels. Analytic KL is that of latent Gaussians and corresponds to action KL under the continuous bijection; floating-point rounding is not bijective. Action components actually sent after scaling and conversion to the space dtype that equal a bound are counted; KL identity is not claimed for that finite implementation. Logged entropy is latent Gaussian entropy, not transformed-action entropy. Both methods use the same GAE and separate critic; A2C takes one first-order step on the same batch. Advantages are not normalized and the actor averages transitions without γᵗ: the practical estimator, not a claim of exact discounted-return gradient from the start.

TRPO uses the old||new mean-KL Hessian for Fisher-vector products, damping, conjugate gradients and line search. It accepts a step only if empirical mean KL is at most δ and measured surrogate strictly improves; otherwise it restores old parameters. This batch check does not guarantee real-return improvement or control maximum KL across all states. Evaluations, gradient norm, KL, acceptance, CG iterations, latent entropy and saturations are logged.

ORYON_QUICK=1 limits the experiment to one seed, two environments, 16 steps and two updates per method. It also limits episodes to 64 steps through an external TimeLimit and evaluates one episode per checkpoint. Truncation retains bootstrap from the final observation. The reduced run checks operation but is not a conclusive comparison; you run the full experiment.

[ ]TRPO and A2C from scratch in MuJoCoLocal GPU
import gc
import json
import math
import os
import random
import traceback
from pathlib import Path

import gymnasium as gym
import mujoco
import numpy as np
import torch
from torch import nn
from torch.distributions import Normal, kl_divergence

if not gym.__version__.startswith('1.4.'):
    raise RuntimeError('Este laboratorio usa el contrato vectorial de Gymnasium 1.4.x')
quick = os.environ.get('ORYON_QUICK', '0') == '1'
env_id = os.environ.get('ORYON_TRPO_ENV', 'Hopper-v5')
if env_id not in ('Hopper-v5', 'HalfCheetah-v5'):
    raise ValueError('ORYON_TRPO_ENV debe ser Hopper-v5 o HalfCheetah-v5')
out = Path(os.environ.get('ORYON_TRPO_OUT', 'oryon-trpo'))
out.mkdir(parents=True, exist_ok=True)
device = torch.device('cuda' if torch.cuda.is_available() else 'cpu')
seeds = [0] if quick else [0, 1, 2, 3, 4]
n_env, horizon = (2, 16) if quick else (8, 256)
updates = 2 if quick else 1000
gamma, lam, kl_limit, damping = .99, .95, .01, .1
cg_steps, line_steps = 10, 10
critic_epochs, critic_lr, actor_lr = (2 if quick else 10), .001, .0003
eval_every, eval_episodes = (1, 1) if quick else (50, 5)

def make_env():
    return gym.make(env_id, max_episode_steps=64) if quick else gym.make(env_id)

def tensor(x):
    return torch.as_tensor(np.asarray(x), dtype=torch.float32, device=device)

class Actor(nn.Module):
    def __init__(self, obs_dim, act_dim):
        super().__init__()
        self.net = nn.Sequential(nn.Linear(obs_dim, 64), nn.Tanh(),
                                 nn.Linear(64, 64), nn.Tanh(), nn.Linear(64, act_dim))
        self.log_std = nn.Parameter(torch.full((act_dim,), -.5))

    def dist(self, obs):
        mean = self.net(obs)
        return Normal(mean, self.log_std.clamp(-5., 1.).exp().expand_as(mean))

class Critic(nn.Module):
    def __init__(self, obs_dim):
        super().__init__()
        self.net = nn.Sequential(nn.Linear(obs_dim, 64), nn.Tanh(),
                                 nn.Linear(64, 64), nn.Tanh(), nn.Linear(64, 1))

    def forward(self, obs):
        return self.net(obs).squeeze(-1)

def flat_params(model):
    return torch.cat([p.detach().reshape(-1) for p in model.parameters()])

def set_params(model, flat):
    offset = 0
    with torch.no_grad():
        for p in model.parameters():
            n = p.numel()
            p.copy_(flat[offset:offset+n].reshape_as(p))
            offset += n
    if offset != flat.numel():
        raise ValueError('Número incorrecto de parámetros')

def flatten(parts):
    return torch.cat([x.reshape(-1) for x in parts])

def old_kl(actor, obs, old_mean, old_std):
    old = Normal(old_mean, old_std)
    return kl_divergence(old, actor.dist(obs)).sum(dim=-1).mean()

def fvp(actor, obs, old_mean, old_std, vector):
    params = tuple(actor.parameters())
    kl = old_kl(actor, obs, old_mean, old_std)
    first = flatten(torch.autograd.grad(kl, params, create_graph=True))
    second = flatten(torch.autograd.grad((first * vector).sum(), params)).detach()
    return second + damping * vector

def conjugate_gradient(product, b):
    x = torch.zeros_like(b)
    r = b.clone()
    p = r.clone()
    rr = torch.dot(r, r)
    count = 0
    for _ in range(cg_steps):
        if float(rr) < 1e-12:
            break
        ap = product(p)
        denom = torch.dot(p, ap)
        if not torch.isfinite(denom) or float(denom) <= 1e-12:
            break
        alpha = rr / denom
        x = x + alpha*p
        r = r - alpha*ap
        rr_next = torch.dot(r, r)
        count += 1
        if not torch.isfinite(rr_next) or float(rr_next) < 1e-12:
            break
        p = r + (rr_next/rr)*p
        rr = rr_next
    return x, count

def gae(reward, value, successor_value, terminated, truncated):
    answer = np.zeros_like(reward, dtype=np.float64)
    carry = np.zeros(reward.shape[1], dtype=np.float64)
    for t in range(len(reward)-1, -1, -1):
        delta = reward[t] + gamma*(~terminated[t])*successor_value[t] - value[t]
        carry = delta + gamma*lam*(~(terminated[t] | truncated[t]))*carry
        answer[t] = carry
    return answer

# Un truncamiento conserva bootstrap; ambas señales cortan el siguiente episodio.
assert np.allclose(gae(np.array([[1.],[2.]]), np.zeros((2,1)),
                       np.array([[3.],[9.]]), np.array([[False],[True]]),
                       np.array([[True],[False]])), [[1+gamma*3],[2]])

def successor(next_obs, term, trunc, info):
    done = term | trunc
    result = np.asarray(next_obs).copy()
    if done.any():
        if 'final_obs' not in info or '_final_obs' not in info:
            raise RuntimeError('Falta final_obs de SAME_STEP')
        if not np.array_equal(info['_final_obs'], done):
            raise RuntimeError('Máscara final_obs incompatible')
        for i in np.flatnonzero(done):
            result[i] = info['final_obs'][i]
    return result

def evaluate(actor, seed, low, high):
    env = make_env()
    episodes = []
    try:
        for i in range(eval_episodes):
            eval_seed = 100000 + 1000*seed + i
            obs, _ = env.reset(seed=eval_seed)
            total, length = 0., 0
            while True:
                with torch.no_grad():
                    latent = actor.dist(tensor(obs).unsqueeze(0)).mean[0].cpu().numpy()
                action = low + (np.tanh(latent)+1.)*(high-low)/2.
                obs, reward, term, trunc, _ = env.step(action.astype(env.action_space.dtype))
                total += float(reward)
                length += 1
                if term or trunc:
                    episodes.append({'seed':eval_seed, 'return':total, 'length':length,
                                     'terminated':bool(term), 'truncated':bool(trunc)})
                    break
    finally:
        env.close()
    return episodes

def train(method, seed):
    random.seed(seed)
    np.random.seed(seed)
    torch.manual_seed(seed)
    if torch.cuda.is_available():
        torch.cuda.manual_seed_all(seed)
    envs = gym.vector.SyncVectorEnv([make_env for _ in range(n_env)],
                                   autoreset_mode=gym.vector.AutoresetMode.SAME_STEP)
    try:
        obs, _ = envs.reset(seed=[seed*1000+i for i in range(n_env)])
        low, high = envs.single_action_space.low, envs.single_action_space.high
        if not np.isfinite(low).all() or not np.isfinite(high).all() or np.any(high<=low):
            raise ValueError('Se requieren límites de acción finitos y crecientes')
        actor = Actor(obs.shape[1], low.size).to(device)
        critic = Critic(obs.shape[1]).to(device)
        actor_optim = torch.optim.Adam(actor.parameters(), lr=actor_lr)
        critic_optim = torch.optim.Adam(critic.parameters(), lr=critic_lr)
        episode_return = np.zeros(n_env)
        history = []
        for update in range(1, updates+1):
            observations, latents, old_means, old_stds, old_logps = [], [], [], [], []
            rewards, values, next_values, terms, truncs = [], [], [], [], []
            completed, saturations, scalar_actions = [], 0, 0
            for _ in range(horizon):
                state = tensor(obs)
                with torch.no_grad():
                    dist = actor.dist(state)
                    z = dist.sample()
                    transformed = torch.tanh(z).cpu().numpy()
                    action = low+(transformed+1.)*(high-low)/2.
                    action_sent = action.astype(envs.single_action_space.dtype)
                    next_obs, reward, term, trunc, info = envs.step(action_sent)
                    real_next = successor(next_obs, term, trunc, info)
                    value, next_value = critic(state), critic(tensor(real_next))
                    observations.append(state)
                    latents.append(z)
                    old_means.append(dist.mean)
                    old_stds.append(dist.stddev)
                    old_logps.append(dist.log_prob(z).sum(-1))
                rewards.append(np.asarray(reward, dtype=float))
                values.append(value.cpu().numpy())
                next_values.append(next_value.cpu().numpy())
                terms.append(np.asarray(term, dtype=bool))
                truncs.append(np.asarray(trunc, dtype=bool))
                saturations += int(np.count_nonzero((action_sent == low) | (action_sent == high)))
                scalar_actions += action_sent.size
                episode_return += reward
                for i in np.flatnonzero(term | trunc):
                    completed.append(float(episode_return[i]))
                    episode_return[i] = 0.
                obs = next_obs
            obs_batch = torch.cat(observations)
            z_batch = torch.cat(latents)
            mean_old, std_old = torch.cat(old_means), torch.cat(old_stds)
            logp_old = torch.cat(old_logps)
            v = np.stack(values)
            advantages = gae(np.stack(rewards), v, np.stack(next_values), np.stack(terms), np.stack(truncs))
            adv_batch = tensor(advantages.reshape(-1))
            target = tensor((advantages+v).reshape(-1))
            def surrogate():
                logp = actor.dist(obs_batch).log_prob(z_batch).sum(-1)
                return (torch.exp(logp-logp_old)*adv_batch).mean()
            params = tuple(actor.parameters())
            g = flatten(torch.autograd.grad(surrogate(), params)).detach()
            grad_norm = float(torch.linalg.vector_norm(g))
            accepted, cg_count, kl_value, improvement = None, 0, None, None
            if method == 'TRPO':
                old_params = flat_params(actor)
                direction, cg_count = conjugate_gradient(lambda x: fvp(actor, obs_batch, mean_old, std_old, x), g)
                curvature = float(torch.dot(direction, fvp(actor, obs_batch, mean_old, std_old, direction)))
                accepted = False
                try:
                    if math.isfinite(curvature) and curvature > 1e-12:
                        full_step = direction*math.sqrt(2*kl_limit/curvature)
                        before = float(surrogate().detach())
                        for j in range(line_steps):
                            set_params(actor, old_params + (.5**j)*full_step)
                            with torch.no_grad():
                                candidate = float(surrogate())
                                candidate_kl = float(old_kl(actor, obs_batch, mean_old, std_old))
                            if math.isfinite(candidate) and math.isfinite(candidate_kl) and candidate>before and candidate_kl<=kl_limit:
                                accepted, kl_value, improvement = True, candidate_kl, candidate-before
                                break
                finally:
                    if not accepted:
                        set_params(actor, old_params)
                if not accepted:
                    kl_value, improvement = 0., 0.
            else:
                actor_optim.zero_grad(set_to_none=True)
                loss = -surrogate()
                loss.backward()
                nn.utils.clip_grad_norm_(actor.parameters(), .5, error_if_nonfinite=True)
                actor_optim.step()
                with torch.no_grad():
                    kl_value = float(old_kl(actor, obs_batch, mean_old, std_old))
            for _ in range(critic_epochs):
                critic_optim.zero_grad(set_to_none=True)
                loss_v = .5*(critic(obs_batch)-target).square().mean()
                loss_v.backward()
                nn.utils.clip_grad_norm_(critic.parameters(), .5, error_if_nonfinite=True)
                critic_optim.step()
            row = {'update':update, 'transitions':update*n_env*horizon,
                   'training_completed_returns':completed, 'actor_gradient_norm':grad_norm,
                   'latent_entropy_before_update':float(Normal(mean_old,std_old).entropy().sum(-1).mean()),
                   'saturated_action_components':saturations, 'action_components':scalar_actions,
                   'mean_kl_old_new':kl_value, 'accepted':accepted,
                   'surrogate_improvement':improvement, 'cg_iterations':cg_count}
            if update%eval_every == 0 or update==updates:
                row['evaluation'] = evaluate(actor, seed, low, high)
                print(method, seed, 'paso', update, 'retorno',
                      np.mean([x['return'] for x in row['evaluation']]), 'KL', kl_value, flush=True)
            history.append(row)
        return {'method':method, 'seed':seed, 'history':history}
    finally:
        envs.close()

report = {'quick':quick, 'environment':env_id, 'gymnasium':gym.__version__,
          'mujoco':mujoco.__version__, 'torch':torch.__version__, 'numpy':np.__version__, 'device':str(device), 'seeds':seeds,
          'configuration':{'n_env':n_env, 'horizon':horizon, 'updates':updates,
              'quick_time_limit':64 if quick else None, 'gamma':gamma, 'lambda':lam,
              'kl_limit':kl_limit, 'fisher_damping':damping, 'cg_max_iterations':cg_steps,
              'line_search_max_trials':line_steps, 'line_search_ratio':.5,
              'actor_lr_a2c':actor_lr, 'critic_lr':critic_lr, 'critic_epochs':critic_epochs,
              'gradient_clip_a2c_and_critic':.5, 'advantage_normalization':False,
              'saturation_definition':'componentes de action_sent iguales a low o high tras conversión de tipo',
              'actor_time_weighting':'uniforme por transición', 'autoreset':'SAME_STEP',
              'evaluation_every':eval_every, 'evaluation_episodes':eval_episodes,
              'evaluation_seed':'100000 + 1000 * train_seed + episode'}, 'runs':[]}
for seed in seeds:
    for method in ('TRPO','A2C'):
        failure = None
        try:
            result = train(method, seed)
        except Exception:
            failure = traceback.format_exc()
        finally:
            gc.collect()
            if torch.cuda.is_available():
                torch.cuda.empty_cache()
        if failure is not None:
            raise RuntimeError('Falló el entrenamiento; diagnóstico original:\n'+failure)
        report['runs'].append(result)
        (out/'trpo-report.json').write_text(json.dumps(report, indent=2, allow_nan=False), encoding='utf-8')
print('Informe:', out/'trpo-report.json')
This cell needs the local lab (PyTorch with your GPU). Start it with npm run lab and open the connection link.

Exercises

ProofA telescoping sum under the new policy
Prove: Prove the performance difference lemma for two fixed policies.
0
Consider a finite MDP with bounded rewards, discount γ∈[0,1), common initial distribution ρ₀ and policies π and π′. Define dρ₀^π′(s)=(1−γ)Σₜ≥₀γᵗPπ′(Sₜ=s). Use Vπ and Aπ, both for the same discount.

Step 1 of 3. What is the expectation of Aπ(Sₜ,Aₜ) conditioned on Sₜ and Aₜ?

ProofNatural direction as a multiplicative update
Prove: Derive the policy after an exact tabular NPG step.
0
Finite discounted MDP, bounded reward and softmax with finite logits θₛ,ₐ. Use normalized dρ^π, F=Eₛ∼d,a∼π[score·scoreᵀ] and J(θ)=Vπθ(ρ). Consider reachable states with d(s)>0. The step uses θ′=θ+ηF†∇J, η>0, with Moore–Penrose pseudoinverse.

Step 1 of 3. What are the Fisher block and gradient for a visited state?

CodeFisher-vector product
Implement fisher_vector_product(policy, states, v, damping) in PyTorch. policy(states) returns real logits of shape (N,K), N≥1, K≥2, deterministic and differentiable with respect to all trainable parameters. states and v have those parameters' device and dtype; v is a finite flat vector concatenating all trainable parameters in policy.parameters() order. damping is a finite nonnegative real scalar. Return Fv+damping*v where F is the state mean of Eₐ∼π[∇log π(a|s)∇log π(a|s)ᵀ], evaluated at the current policy. Use double backpropagation of mean KL(π_old||π_current), with old distribution detached. Do not modify parameters, states, v or existing .grad gradients. Reject invalid shapes and damping with ValueError. Tests compare against explicit Fisher built by summing action scores.
import torch

def fisher_vector_product(policy, states, v, damping):
  pass
Shift+Enter to run
NumericScale of a natural direction
In a local quadratic problem, g=(2,4), F=diag(2,4) and δ=0.03. Direction is x=F⁻¹g and proposed step αx with α=√(2δ/(gᵀx)). What is α?
QuizFrom a bound to an implementation
A proof uses exact advantages and a maximum-KL penalty across all states. What can invalidate its guarantee when implementing TRPO?
[ ]Check step scaleBrowser
import numpy as np
g=np.array([2.,4.])
F=np.diag([2.,4.])
delta=.03
x=np.linalg.solve(F,g)
alpha=np.sqrt(2*delta/(g@x))
print('Dirección:',x,'g·x:',g@x,'escala:',alpha)