Sign in

TRPO

Trust Region Policy Optimization

A policy-gradient method that takes the largest improving step whose change in the policy, measured by KL divergence, stays under a fixed limit.

Overview

A step that looks small in the network's weights can change the policy's behaviour a great deal, and a bad policy then collects bad data, which is hard to recover from. TRPO measures a step by its effect on behaviour instead. It uses the KL divergence, a measure of how different two probability distributions are, between the old and new action probabilities. Each update asks: within a fixed KL budget, which change improves the expected advantage most? The answer is the natural gradient, the ordinary gradient rescaled by how sensitive the policy is in each direction. A line search then confirms that the step really stays in budget and really improves. The template is a small NumPy version trained on a 4 by 4 grid.

A short history

John Schulman, Sergey Levine, Philipp Moritz, Michael Jordan and Pieter Abbeel published TRPO in 2015. Policy-gradient methods of the time could collapse after one step that was too large. Building on Sham Kakade's natural policy gradient and on conservative policy iteration, TRPO limited each update by the KL divergence between the old and new policy and solved the step with conjugate gradients and a line search. It gave reliable improvement on simulated locomotion and led directly to PPO.

How it works

  1. Collect steps_per_epoch steps, estimate advantages with GAE and standardise them.
  2. Compute the gradient gg of the surrogate objective at the current weights.
  3. Solve (F+cI) x=g(F + cI)\,x = g for the direction xx by conjugate gradient. Only products of FF with a vector are needed, so FF is never built.
  4. Scale xx so that the predicted KL divergence of the step equals max_kl.
  5. Try the full step. If the measured mean KL exceeds the limit or the surrogate did not improve, shrink the step by backtrack_coef and try again, up to backtrack_iters times.
  6. If no step is accepted, restore the old weights. Then fit the value network to the returns with value_iters regression steps.

Watch out for

  • The step size comes from a quadratic approximation of the KL divergence, which is only accurate close to the old weights. The line search exists because the true KL can exceed the prediction.
  • Conjugate gradient is stopped after a few iterations, so the direction is approximate. Too few iterations give a direction closer to the plain gradient than to the natural one.
  • Without damping the Fisher matrix can be nearly singular, and the solve becomes unstable. Too much damping turns the method back into ordinary gradient ascent.
  • The KL limit is an average over the visited states. Individual states, especially rare ones, can change by much more than the limit.

Use cases

When to use it

When each policy update must be guaranteed not to move too far, or as the reference method that PPO approximates. It is slower and more complex per update, so prefer PPO unless the hard limit is needed.

In industry

Robotics research
Learning simulated walking, hopping and swimming gaits, the continuous control tasks the original paper demonstrated.
Safety-minded control
Serving as the base for constrained methods such as Constrained Policy Optimization, where each update must also respect a cost limit.
Research and teaching
Explaining why the size of a policy step should be measured in terms of behaviour, not parameters.

Choosing it: what must hold

  • A simulator that supplies large batches of fresh on-policy experience for every update.
  • A policy network small enough for conjugate gradient and Fisher-vector products to be affordable.
  • No parameter sharing between policy and value networks, and no layers such as dropout that complicate the KL constraint.

When to choose something else

IfUse instead
You want nearly the same stability with far simpler codePPO
Environment steps are expensive and data must be reusedSAC or TD3
You are learning the basics firstVanilla policy gradient with a baseline

Math foundations

  1. The surrogate objective

    L(θ)=Et[πθ(at∣st)πθold(at∣st) A^t]L(\theta) = \mathbb{E}_t\left[ \frac{\pi_\theta(a_t \mid s_t)}{\pi_{\theta_{\text{old}}}(a_t \mid s_t)}\, \hat{A}_t \right]

    An estimate, from data collected by the old policy, of how much better the new policy would do. It is trustworthy only while the two policies stay close.

  2. The trust-region problem

    max⁡θ  L(θ)subject toDˉKL(θold,θ)=Es[DKL(πθold(⋅∣s) ∥ πθ(⋅∣s))]≤δ\max_\theta \; L(\theta) \quad \text{subject to} \quad \bar{D}_{\text{KL}}(\theta_{\text{old}}, \theta) = \mathbb{E}_s\Bigl[ D_{\text{KL}}\bigl( \pi_{\theta_{\text{old}}}(\cdot \mid s) \,\big\|\, \pi_\theta(\cdot \mid s) \bigr) \Bigr] \le \delta

    Improve the surrogate as much as possible while the mean KL divergence between old and new action probabilities stays within the budget δ\delta.

  3. The local approximation

    L(θ)≈L(θold)+g⊤Δθ,DˉKL≈12 Δθ⊤F ΔθL(\theta) \approx L(\theta_{\text{old}}) + g^{\top} \Delta\theta, \qquad \bar{D}_{\text{KL}} \approx \tfrac{1}{2}\, \Delta\theta^{\top} F\, \Delta\theta

    Near the old weights the objective is linear and the KL divergence is quadratic. FF is the Fisher information matrix, the Hessian of the mean KL at θold\theta_{\text{old}}.

  4. The natural gradient direction

    x=F−1gx = F^{-1} g

    The solution of the approximate problem points along F−1gF^{-1} g. It favours directions where the policy changes little per unit of weight change. Conjugate gradient finds xx from products FvFv alone.

  5. The step

    θ=θold+αk2δx⊤Fx  x\theta = \theta_{\text{old}} + \alpha^{k} \sqrt{\frac{2\delta}{x^{\top} F x}}\; x

    The square root scales xx so the predicted KL equals δ\delta exactly. The factor αk\alpha^{k} is the backtracking line search: kk is the first try at which the real KL and the real improvement both pass.

  6. The Fisher matrix of a softmax policy

    F=Es[Js⊤(diag⁡(ps)−psps⊤)Js]F = \mathbb{E}_s\Bigl[ J_s^{\top} \bigl( \operatorname{diag}(p_s) - p_s p_s^{\top} \bigr) J_s \Bigr]

    JsJ_s is the Jacobian of the logits with respect to the weights and psp_s the action probabilities in state ss. The template computes FvFv with one forward-mode pass and one backward pass.

Symbols

θ,θold\theta, \theta_{\text{old}}
policy weights after and before the step, as flat vectors
Δθ\Delta\theta
the change in the weights
A^t\hat{A}_t
advantage estimate from GAE
gg
gradient of the surrogate objective at the old weights
FF
Fisher information matrix of the policy
xx
the natural gradient direction
δ\delta
KL budget for one step (max_kl)
DˉKL\bar{D}_{\text{KL}}
KL divergence between old and new policy, averaged over visited states
cc
damping: a multiple of the identity added to F
α\alpha
line-search shrink factor (backtrack_coef)
kk
number of shrinks before a step was accepted
ps,Jsp_s, J_s
action probabilities in state s and the Jacobian of the logits there

Worked by hand

A toy policy has two weights. Suppose FF is diagonal with entries 44 and 11, the gradient is g=(2,1)g = (2, 1) and the budget is δ=0.02\delta = 0.02. Ignore damping and find the full step.

x=F−1g=(2/4,  1/1)=(0.5,  1)x = F^{-1} g = \bigl( 2 / 4,\; 1 / 1 \bigr) = (0.5,\; 1)
x⊤Fx=4×0.52+1×12=2x^{\top} F x = 4 \times 0.5^2 + 1 \times 1^2 = 2
2×0.02/2=0.02=0.1414\sqrt{2 \times 0.02 / 2} = \sqrt{0.02} = 0.1414
Δθ=0.1414×(0.5,  1)=(0.0707,  0.1414)\Delta\theta = 0.1414 \times (0.5,\; 1) = (0.0707,\; 0.1414)
12 Δθ⊤F Δθ=12(4×0.005+1×0.02)=0.02\tfrac{1}{2}\, \Delta\theta^{\top} F\, \Delta\theta = \tfrac{1}{2}\bigl( 4 \times 0.005 + 1 \times 0.02 \bigr) = 0.02

The plain gradient favours the first weight, but the policy is four times as sensitive to it, so the natural direction favours the second. The predicted KL of the step equals the budget of 0.02.

Visual example

Loading the example.

Try this

  • Press Step a few times: every TRPO step lands on the edge of its outlined region, however long or short it looks in the plane.
  • Click near a corner of the plane, where the policy is almost certain, and compare the size of the two first steps.
  • Raise the plain step size η until the plain gradient overshoots, then widen or narrow the KL budget δ.

Code sample

from impl import TRPO, GridWorld
from config import TRPOConfig

env = GridWorld(size=4)
agent = TRPO(env.obs_dim, env.n_actions, TRPOConfig(epochs=40))
returns = agent.train(env)        # return of every training episode
print(agent.evaluate(GridWorld(size=4)))   # return of the most likely actions; 0.5 is the best possible
Read the implementation (377 lines)
"""Trust Region Policy Optimization (TRPO) in NumPy, with a small gridworld to learn on.

Each epoch collects a batch of steps, estimates advantages with GAE(lambda) and then takes the largest
natural-gradient step that keeps the mean KL divergence between the old and the new policy under
`max_kl`. The step direction F^-1 g is found with conjugate gradient, using exact Fisher-vector
products computed with a forward-mode pass and a backward pass through the policy network; a
backtracking line search then enforces the KL limit and an improvement of the surrogate objective.
"""
from __future__ import annotations

import numpy as np

try:
    from .config import TRPOConfig
except ImportError:  # run from the template's own folder
    from config import TRPOConfig


class GridWorld:
    """Square grid: the agent starts in the top-left cell and must reach the bottom-right cell.

    Observation: one-hot vector of the agent's cell, shape (size * size,).
    Actions: 0 up, 1 right, 2 down, 3 left. A move into a wall leaves the agent where it is.
    Reward: +1.0 for the step that reaches the goal, -0.1 for every other step.
    `step` returns (obs, reward, terminated, truncated): terminated at the goal, truncated after
    `max_steps` steps. The best return is `optimal_return`, 0.5 for the default 4 x 4 grid.
    """

    n_actions = 4
    _MOVES = ((-1, 0), (0, 1), (1, 0), (0, -1))

    def __init__(self, size: int = 4, max_steps: int = 30) -> None:
        if size < 2:
            raise ValueError(f"size must be at least 2, got {size!r}")
        self.size = size
        self.max_steps = max_steps
        self.obs_dim = size * size
        self.row = self.col = self.t = 0

    @property
    def optimal_return(self) -> float:
        """Return of a shortest path: 2 * (size - 1) moves, the last one worth +1."""
        return 1.0 - 0.1 * (2 * (self.size - 1) - 1)

    def _obs(self) -> np.ndarray:
        obs = np.zeros(self.obs_dim)
        obs[self.row * self.size + self.col] = 1.0
        return obs

    def reset(self) -> np.ndarray:
        """Put the agent back on the start cell and return the observation, shape (obs_dim,)."""
        self.row = self.col = self.t = 0
        return self._obs()

    def step(self, action: int):
        """Apply one action (0..3). Returns (obs, reward, terminated, truncated)."""
        d_row, d_col = self._MOVES[int(action)]
        self.row = min(max(self.row + d_row, 0), self.size - 1)
        self.col = min(max(self.col + d_col, 0), self.size - 1)
        self.t += 1
        terminated = self.row == self.size - 1 and self.col == self.size - 1
        truncated = not terminated and self.t >= self.max_steps
        return self._obs(), (1.0 if terminated else -0.1), terminated, truncated


class MLP:
    """Fully connected network with tanh hidden layers and a linear output, trained by manual backprop.

    sizes: layer widths, for example (16, 32, 4) is 16 inputs, one hidden layer of 32 units, 4 outputs.
    rng:   NumPy generator used for the initial weights.
    lr:    Adam step size used by `step`.
    """

    def __init__(self, sizes, rng: np.random.Generator, lr: float = 1e-3) -> None:
        self.sizes = tuple(int(s) for s in sizes)
        self.weights = [rng.normal(0.0, np.sqrt(1.0 / m), size=(m, n)) for m, n in zip(self.sizes[:-1], self.sizes[1:])]
        self.biases = [np.zeros(n) for n in self.sizes[1:]]
        self.lr = lr
        self._m = [np.zeros_like(p) for p in self.params()]
        self._v = [np.zeros_like(p) for p in self.params()]
        self._t = 0
        self._acts: list[np.ndarray] = []

    def params(self) -> list[np.ndarray]:
        """All parameter arrays: the weight matrices, then the bias vectors."""
        return self.weights + self.biases

    def forward(self, x: np.ndarray) -> np.ndarray:
        """x: (batch, n_in) or (n_in,) -> (batch, n_out). Keeps the activations for `backward`."""
        h = np.atleast_2d(np.asarray(x, dtype=float))
        self._acts = [h]
        last = len(self.weights) - 1
        for i, (w, b) in enumerate(zip(self.weights, self.biases)):
            h = h @ w + b
            if i < last:
                h = np.tanh(h)
            self._acts.append(h)
        return h

    def backward(self, grad_out: np.ndarray):
        """Backpropagate through the most recent `forward` call.

        grad_out: d loss / d output, shape (batch, n_out).
        Returns (grads, grad_in): grads in the order of `params()`, grad_in = d loss / d input (batch, n_in).
        """
        g = np.asarray(grad_out, dtype=float)
        n_layers = len(self.weights)
        grad_w: list = [None] * n_layers
        grad_b: list = [None] * n_layers
        for i in reversed(range(n_layers)):
            if i < n_layers - 1:
                g = g * (1.0 - self._acts[i + 1] ** 2)
            grad_w[i] = self._acts[i].T @ g
            grad_b[i] = g.sum(axis=0)
            g = g @ self.weights[i].T
        return grad_w + grad_b, g

    def step(self, grads) -> None:
        """One Adam step that moves the parameters against `grads` (same order as `params()`)."""
        self._t += 1
        for p, g, m, v in zip(self.params(), grads, self._m, self._v):
            m *= 0.9
            m += 0.1 * g
            v *= 0.999
            v += 0.001 * g * g
            p -= self.lr * (m / (1.0 - 0.9**self._t)) / (np.sqrt(v / (1.0 - 0.999**self._t)) + 1e-8)

    def copy_from(self, other: "MLP", tau: float = 1.0) -> None:
        """Polyak update: params <- tau * other + (1 - tau) * params. tau = 1 is a plain copy."""
        for p, q in zip(self.params(), other.params()):
            p *= 1.0 - tau
            p += tau * q


class FlatMLP(MLP):
    """MLP that can also be read and written as one flat parameter vector, and differentiated forward."""

    def get_flat(self) -> np.ndarray:
        """All parameters joined into one vector, in the order of `params()`."""
        return np.concatenate([p.ravel() for p in self.params()])

    def set_flat(self, flat: np.ndarray) -> None:
        """Overwrite the parameters from a vector laid out like `get_flat()`."""
        start = 0
        for p in self.params():
            p[...] = flat[start:start + p.size].reshape(p.shape)
            start += p.size

    def unflatten(self, flat: np.ndarray) -> list[np.ndarray]:
        """Split a flat vector into arrays shaped like `params()`."""
        out, start = [], 0
        for p in self.params():
            out.append(flat[start:start + p.size].reshape(p.shape))
            start += p.size
        return out

    def jvp(self, tangent: np.ndarray) -> np.ndarray:
        """Directional derivative of the outputs of the most recent `forward` call.

        tangent: flat parameter direction. Returns d output / d epsilon at parameters + epsilon * tangent,
        shape (batch, n_out).
        """
        parts = self.unflatten(tangent)
        n_layers = len(self.weights)
        d_w, d_b = parts[:n_layers], parts[n_layers:]
        d_h = np.zeros_like(self._acts[0])
        for i in range(n_layers):
            d_h = d_h @ self.weights[i] + self._acts[i] @ d_w[i] + d_b[i]
            if i < n_layers - 1:
                d_h = d_h * (1.0 - self._acts[i + 1] ** 2)
        return d_h


def softmax(logits: np.ndarray) -> np.ndarray:
    """Row-wise softmax. logits: (batch, n_actions) -> probabilities of the same shape."""
    z = logits - logits.max(axis=-1, keepdims=True)
    e = np.exp(z)
    return e / e.sum(axis=-1, keepdims=True)


def sample_action(probs: np.ndarray, rng: np.random.Generator) -> int:
    """Draw one action index from a probability vector, shape (n_actions,)."""
    return min(int(np.searchsorted(np.cumsum(probs), rng.random())), len(probs) - 1)


def policy_gradient_logits(probs: np.ndarray, actions: np.ndarray, weights: np.ndarray) -> np.ndarray:
    """Gradient with respect to the logits of the loss -mean(weights * log pi(action | state)).

    probs: (n, n_actions) softmax outputs. actions: (n,) taken actions. weights: (n,) returns or advantages.
    Returns (n, n_actions).
    """
    n = len(actions)
    grad = probs * weights[:, None]
    grad[np.arange(n), actions] -= weights
    return grad / n


def gae(rewards: np.ndarray, values: np.ndarray, last_value: float, gamma: float, lam: float) -> np.ndarray:
    """Generalised advantage estimates for one trajectory segment.

    rewards: (n,) rewards r_0..r_{n-1}. values: (n,) critic values V(s_0)..V(s_{n-1}).
    last_value: V(s_n), 0.0 when s_n is terminal. Returns advantages, shape (n,).
    lam = 1 gives (discounted return - value), lam = 0 gives the one-step TD error.
    """
    next_values = np.append(values[1:], last_value)
    deltas = rewards + gamma * next_values - values
    advantages = np.zeros(len(rewards))
    running = 0.0
    for t in reversed(range(len(rewards))):
        running = deltas[t] + gamma * lam * running
        advantages[t] = running
    return advantages


def collect_steps(env, actor, critic, n_steps: int, gamma: float, lam: float, rng: np.random.Generator) -> dict:
    """Run the stochastic policy for n_steps environment steps, restarting episodes as they end.

    actor maps observations to action logits, critic maps observations to a value, both (batch, obs_dim) in.
    Returns a dict: obs (n, obs_dim), actions (n,), log_probs (n,), advantages (n,) from GAE,
    returns (n,) = advantages + values (the critic's regression target) and episode_returns, the list
    of returns of the episodes that ended inside this batch. A segment cut by the time limit or by the
    end of the batch is bootstrapped with the critic's value of the next observation.
    """
    obs_buf, act_buf, rew_buf, logp_buf, segments, episode_returns = [], [], [], [], [], []
    obs, episode_return = env.reset(), 0.0
    for t in range(n_steps):
        probs = softmax(actor.forward(obs))[0]
        action = sample_action(probs, rng)
        next_obs, reward, terminated, truncated = env.step(action)
        obs_buf.append(obs)
        act_buf.append(action)
        rew_buf.append(reward)
        logp_buf.append(np.log(probs[action] + 1e-12))
        episode_return += reward
        obs = next_obs
        if terminated or truncated or t == n_steps - 1:
            segments.append((t + 1, None if terminated else next_obs))
            if terminated or truncated:
                episode_returns.append(episode_return)
            obs, episode_return = env.reset(), 0.0
    obs_arr, rewards = np.array(obs_buf), np.array(rew_buf)
    values = critic.forward(obs_arr)[:, 0]
    advantages = np.zeros(n_steps)
    start = 0
    for end, bootstrap_obs in segments:
        last_value = 0.0 if bootstrap_obs is None else float(critic.forward(bootstrap_obs)[0, 0])
        advantages[start:end] = gae(rewards[start:end], values[start:end], last_value, gamma, lam)
        start = end
    return {"obs": obs_arr, "actions": np.array(act_buf), "log_probs": np.array(logp_buf),
            "advantages": advantages, "returns": advantages + values, "episode_returns": episode_returns}


def conjugate_gradient(matvec, b: np.ndarray, iters: int = 10, tol: float = 1e-10) -> np.ndarray:
    """Solve A x = b for a symmetric positive definite A given only the product `matvec(v) = A v`."""
    x = np.zeros_like(b)
    r = b.copy()
    p = b.copy()
    rs = float(r @ r)
    for _ in range(iters):
        if rs < tol:
            break
        a_p = matvec(p)
        alpha = rs / float(p @ a_p)
        x += alpha * p
        r -= alpha * a_p
        rs_new = float(r @ r)
        p = r + (rs_new / rs) * p
        rs = rs_new
    return x


def mean_kl(old_probs: np.ndarray, new_probs: np.ndarray) -> float:
    """Mean over states of KL(old || new) between categorical distributions, (n, n_actions) each."""
    return float(np.mean(np.sum(old_probs * (np.log(old_probs + 1e-12) - np.log(new_probs + 1e-12)), axis=1)))


class TRPO:
    """TRPO agent with a softmax policy network and a value network.

    obs_dim: length of an observation vector. n_actions: number of discrete actions.
    """

    def __init__(self, obs_dim: int, n_actions: int, config: TRPOConfig | None = None) -> None:
        cfg = self.config = config or TRPOConfig()
        self.obs_dim, self.n_actions = obs_dim, n_actions
        self.rng = np.random.default_rng(cfg.seed)
        self.actor = FlatMLP((obs_dim, cfg.hidden_size, n_actions), self.rng)
        self.critic = MLP((obs_dim, cfg.hidden_size, 1), self.rng, cfg.value_lr)

    def policy(self, obs: np.ndarray) -> np.ndarray:
        """Action probabilities. obs: (batch, obs_dim) or (obs_dim,) -> (batch, n_actions)."""
        return softmax(self.actor.forward(obs))

    def act(self, obs: np.ndarray, greedy: bool = False) -> int:
        """Sample an action for one observation; greedy=True takes the most likely action instead."""
        probs = self.policy(obs)[0]
        return int(np.argmax(probs)) if greedy else sample_action(probs, self.rng)

    def evaluate(self, env, episodes: int = 1, greedy: bool = True) -> float:
        """Mean return over `episodes` episodes of the greedy (or, with greedy=False, the sampled) policy."""
        total = 0.0
        for _ in range(episodes):
            obs, done = env.reset(), False
            while not done:
                obs, reward, terminated, truncated = env.step(self.act(obs, greedy=greedy))
                total += reward
                done = terminated or truncated
        return total / episodes

    def value(self, obs: np.ndarray) -> np.ndarray:
        """V(s). obs: (batch, obs_dim) or (obs_dim,) -> (batch,)."""
        return self.critic.forward(obs)[:, 0]

    def fisher_vector_product(self, obs: np.ndarray, vector: np.ndarray, damping: float = 0.0) -> np.ndarray:
        """(F + damping * I) @ vector, where F is the Fisher information matrix of the policy on `obs`.

        F is the Hessian of the mean KL divergence at the current parameters: J^T M J averaged over the
        states, with J the Jacobian of the logits and M = diag(p) - p p^T. vector: flat, like `actor.get_flat()`.
        """
        probs = self.policy(obs)
        d_logits = self.actor.jvp(vector)
        m_d = probs * d_logits - probs * np.sum(probs * d_logits, axis=1, keepdims=True)
        grads, _ = self.actor.backward(m_d / len(obs))
        return np.concatenate([g.ravel() for g in grads]) + damping * vector

    def update(self, batch: dict) -> dict:
        """One trust-region policy step and `value_iters` value steps from a `collect_steps` batch.

        Returns kl (mean KL of the accepted step, 0.0 if none was accepted), improvement (gain of the
        surrogate objective), accepted (bool) and value_loss.
        """
        cfg = self.config
        obs, actions, advantages, returns = batch["obs"], batch["actions"], batch["advantages"], batch["returns"]
        advantages = (advantages - advantages.mean()) / (advantages.std() + 1e-8)
        rows = np.arange(len(actions))
        old_probs = self.policy(obs)
        grads, _ = self.actor.backward(policy_gradient_logits(old_probs, actions, advantages))
        gradient = -np.concatenate([g.ravel() for g in grads])  # ascent direction of mean(ratio * advantage)

        def fvp(v):
            return self.fisher_vector_product(obs, v, cfg.damping)

        direction = conjugate_gradient(fvp, gradient, cfg.cg_iters)
        curvature = float(direction @ fvp(direction))
        old_flat = self.actor.get_flat()
        result = {"kl": 0.0, "improvement": 0.0, "accepted": False}
        if curvature > 0.0:
            full_step = np.sqrt(2.0 * cfg.max_kl / curvature) * direction
            for k in range(cfg.backtrack_iters):
                self.actor.set_flat(old_flat + cfg.backtrack_coef**k * full_step)
                new_probs = self.policy(obs)
                ratio = new_probs[rows, actions] / (old_probs[rows, actions] + 1e-12)
                improvement = float(np.mean(ratio * advantages) - np.mean(advantages))
                kl = mean_kl(old_probs, new_probs)
                if improvement > 0.0 and kl <= cfg.max_kl:
                    result = {"kl": kl, "improvement": improvement, "accepted": True}
                    break
            else:
                self.actor.set_flat(old_flat)
        value_loss = 0.0
        for _ in range(cfg.value_iters):
            errors = self.value(obs) - returns
            value_loss = float(np.mean(errors**2))
            grads, _ = self.critic.backward((2.0 * errors / len(errors))[:, None])
            self.critic.step(grads)
        result["value_loss"] = value_loss
        return result

    def train(self, env, epochs: int | None = None) -> list[float]:
        """Run `epochs` rounds of collect + update. Returns the returns of all finished episodes."""
        cfg = self.config
        returns: list[float] = []
        for _ in range(cfg.epochs if epochs is None else epochs):
            batch = collect_steps(env, self.actor, self.critic, cfg.steps_per_epoch, cfg.gamma, cfg.gae_lambda, self.rng)
            returns += batch["episode_returns"]
            self.update(batch)
        return returns
Repository
Not published yet
Needs
Python 3.10 and NumPy
Tests
12, run with python3 -m unittest -v

Practice

Using the template, call conjugate_gradient with a matvec that multiplies by the diagonal matrix of the worked example and b equal to (2, 1), and check that it returns (0.5, 1). Then train TRPO on GridWorld(size=4) with max_kl set to 0.005, 0.02 and 0.1, and for each look at the kl and accepted values that update returns.

Check on learning

  1. Why is distance in weight space a poor measure of how much a policy has changed, and what does the KL divergence measure that it does not?
    A way to think about it

    Consider two weights, one feeding a saturated unit and one feeding the logits directly. The same small change to each has very different effects on the action probabilities.

  2. In the worked example the gradient is larger for the first weight, yet the step is larger in the second. Explain the reversal in words.
    A way to think about it

    The step is chosen for improvement per unit of KL budget, not per unit of weight change. Compare gain and cost for each weight: the gain is gg, the cost grows with FF.

  3. The quadratic approximation predicts the KL will equal the budget exactly. Why does the template still measure the KL and sometimes shrink the step?
    A way to think about it

    An approximation made at θold\theta_{\text{old}} gets worse as you move away. Think about which is more reliable at the proposed new weights: the prediction, or a direct calculation from the new probabilities.

  4. PPO replaces the KL constraint with a clipped ratio. What does PPO give up compared with TRPO, and what does it gain?
    A way to think about it

    Compare what each method guarantees after an update and what each needs to compute. One has a measured bound and a second-order solve, the other has neither.