AI Wiki中文/EN

TRPO: find an update direction, then check the distribution change

TRPO

Compute a Fisher direction and backtrack, separating measured KL, local quadratic models and maximum-state theory.

On this pageIntuitionMathematics & methodImplementationLimitationsExercisesResearch connections

How far do action probabilities move when parameters move a little?

Adding 0.5 to a logit changes a distribution differently when its original action probability is 0.5 or 0.99. TRPO constrains a change in policy distributions rather than relying only on Euclidean parameter distance. It computes a local candidate direction, then checks the actual KL and surrogate objective before accepting a step. TRPO paper

Our teaching environment has three contexts and one binary action before termination. Context weights are [0.3,0.4,0.3]. The first context rewards action 0; the others reward action 1, with reward 1 for the correct action. A two-parameter policy shares features [1,−1],[1,0.25],[1,1]. This retains distribution constraints, Fisher solving and backtracking while omitting long-trajectory occupancy changes.

Exact contextual updates check measured KL; a rare state and a rejected full step expose two different limits.
Exact contextual updates check measured KL; a rare state and a rejected full step expose two different limits.

A local surrogate, a curvature model and a final check

Let theta0 be the data-collection policy and A0 a frozen advantage estimate under that policy. A new/old probability ratio reweights old-policy action samples, assuming positive old probability on the actions used. Omitting a theta-independent constant, the surrogate is:

rθ(s,a)=πθ(a∣s)πθ0(a∣s),L(θ)=Es∼μ0, a∼πθ0[rθ(s,a)A0(s,a)].r_\theta(s,a)=\frac{\pi_\theta(a\mid s)}{\pi_{\theta_0}(a\mid s)},\qquad L(\theta)=\mathbb E_{s\sim\mu_0,\,a\sim\pi_{\theta_0}}[r_\theta(s,a)A_0(s,a)].

Mu0 denotes the chosen old-policy state weights. Using normalized discounted occupancy requires consistent positive normalization factors in the full objective. In a multi-step task, the surrogate retains the old state distribution and does not equal new-policy return. Under suitable conditions they agree to first order locally, but can diverge farther from the old policy. Surrogate derivation

We fix the KL direction to old||new. Define mean KL and its Hessian F at the old parameters:

D‾(θ)=Es∼μ0∑aπθ0(a∣s)log⁡πθ0(a∣s)πθ(a∣s),F=∇θ2D‾(θ0).\overline D(\theta)=\mathbb E_{s\sim\mu_0}\sum_a\pi_{\theta_0}(a\mid s)\log\frac{\pi_{\theta_0}(a\mid s)}{\pi_\theta(a\mid s)},\qquad F=\nabla_\theta^2\overline D(\theta_0).

At the old point, KL and its gradient are zero, and the local quadratic model has Fisher curvature. Let g be the old-point surrogate gradient and Delta a parameter increment. For positive-definite F and nonzero g, the Lagrange conditions for a linear objective under a quadratic constraint give:

max⁡Δg⊤Δs.t.12Δ⊤FΔ≤ε,x=F−1g,Δ∗=2εg⊤x x.\max_\Delta g^\top\Delta\quad\text{s.t.}\quad\tfrac12\Delta^\top F\Delta\leq\varepsilon, \qquad x=F^{-1}g,\qquad \Delta^*=\sqrt{\frac{2\varepsilon}{g^\top x}}\,x.

This explains the natural-gradient direction and step scaling, but quadratic KL is only an approximation. F may be singular. The program adds0.01I when computing direction and scale, then checks the actual undamped KL. Damping changes the local metric, so the step is not the exact solution of the undamped problem. Local solving and implementation

There is no need to form a large dense F. For a shared-feature Bernoulli policy, its vector product is a direct sum. Conjugate gradient repeatedly calls this product to solve the linear system:

Fv=∑sμ0(s)p0(s)(1−p0(s))xs(xs⊤v),(F+ηI)x=g.Fv=\sum_s\mu_0(s)p_0(s)(1-p_0(s))x_s(x_s^\top v),\qquad (F+\eta I)x=g.

Conjugate gradient starts at x=0 with residual r=g and direction p=r. Each iteration uses alpha=(r·r)/(p·Hp) to update x and r, then forms the next conjugate direction using the new/old squared-residual ratio. A sufficiently small residual stops immediately; nonpositive curvature must not be used as a divisor. H is the damped operator. General implementations can obtain Hessian-vector products through automatic differentiation rather than matrix inversion.

Finally, test fractions 1,1/2,1/4 and so on from the same old-parameter starting point. Both conditions must hold; if all allowed trials fail, retain the original parameters:

θtrial=θ0+αΔ∗,D‾(θtrial)≤ε,L(θtrial)>L(θ0).\theta_{\mathrm{trial}}=\theta_0+\alpha\Delta^*,\qquad \overline D(\theta_{\mathrm{trial}})\leq\varepsilon,\qquad L(\theta_{\mathrm{trial}})>L(\theta_0).

The paper’s theoretical bound involves maximum statewise changes and exact advantages. Practical sampled mean KL, estimated advantages and local models provide different conditions. Suppose an ordinary state is unchanged while a rare state of weight 0.001 changes Bernoulli probability from 0.5 to 0.99:

Drare=DKL(Bern⁡(0.5)∥Bern⁡(0.99))≈1.614463,D‾=0.001Drare≈0.001614<0.01.D_{\mathrm{rare}}=D_{\mathrm{KL}}(\operatorname{Bern}(0.5)\Vert\operatorname{Bern}(0.99))\approx1.614463,\qquad \overline D=0.001D_{\mathrm{rare}}\approx0.001614<0.01.

A passing average permits a large rare-state change. In real RL, surrogate error, finite data and occupancy changes further affect return; small mean KL is not a per-state or per-update performance guarantee.

Even a two-dimensional solver keeps backtracking and restoration

The standard-library program exactly enumerates three contexts and two actions. It uses old||new KL, damping 0.01, KL limit 0.01 and at most 12 halving trials for each of 12 updates. Advantages and distributions are known exactly here; this is not a complete trajectory-sampled TRPO trainer. Old probabilities and advantages remain fixed within each solve and line search.

"""Small exact-distribution TRPO update for a shared-feature contextual bandit.

No trajectory importance correction, neural network, or benchmark claim.
The candidate is accepted only after measuring old||new KL and surrogate gain.
"""
import json
import math

FEATURES = ((1., -1.), (1., 0.25), (1., 1.))
WEIGHTS = (0.3, 0.4, 0.3)
REWARDS = ((1., 0.), (0., 1.), (0., 1.))


def dot(a, b):
    if len(a) != len(b):
        raise ValueError('vector dimensions differ')
    return sum(x*y for x, y in zip(a, b))


def sigmoid(x):
    if not math.isfinite(x):
        raise ValueError('finite logit required')
    return 1/(1+math.exp(-x)) if x >= 0 else math.exp(x)/(1+math.exp(x))


def softplus(x):
    return max(x, 0.)+math.log1p(math.exp(-abs(x)))


def old_new_kl(old_logit, new_logit):
    # KL(Bernoulli(sigmoid(old)) || Bernoulli(sigmoid(new))).
    p = sigmoid(old_logit)
    sigmoid(new_logit)  # Validate finite input.
    return softplus(new_logit)-softplus(old_logit)-p*(new_logit-old_logit)


def batch(theta):
    rows = []
    for x, w, (r0, r1) in zip(FEATURES, WEIGHTS, REWARDS):
        old_logit = dot(theta, x)
        p = sigmoid(old_logit)
        value = (1-p)*r0+p*r1
        rows.append((x, w, old_logit, r0-value, r1-value))
    return tuple(rows)


def surrogate(theta, rows):
    return sum(w*((1-sigmoid(dot(theta, x)))*a0+sigmoid(dot(theta, x))*a1)
               for x, w, _, a0, a1 in rows)


def mean_kl(theta, rows):
    return sum(w*old_new_kl(old, dot(theta, x)) for x, w, old, _, _ in rows)


def gradient(rows):
    n = len(rows[0][0])
    return [sum(w*sigmoid(old)*(1-sigmoid(old))*(a1-a0)*x[j]
                for x, w, old, a0, a1 in rows) for j in range(n)]


def fisher_product(vector, rows, damping=0.01):
    if not math.isfinite(damping) or damping < 0:
        raise ValueError('nonnegative finite damping required')
    result = [damping*v for v in vector]
    for x, w, old, _, _ in rows:
        p = sigmoid(old)
        scale = w*p*(1-p)*dot(x, vector)
        result = [r+scale*xi for r, xi in zip(result, x)]
    return result


def conjugate_gradient(product, b, max_iter=20, tolerance=1e-12):
    if max_iter < 1 or not math.isfinite(tolerance) or tolerance <= 0:
        raise ValueError('positive iteration count and tolerance required')
    if not b or not all(math.isfinite(x) for x in b):
        raise ValueError('nonempty finite right hand side required')
    x, r, p = [0.]*len(b), list(b), list(b)
    rr = dot(r, r)
    if rr <= tolerance**2:
        return x
    for _ in range(max_iter):
        hp = product(p)
        curvature = dot(p, hp)
        if not math.isfinite(curvature) or curvature <= 0:
            raise ValueError('nonpositive or nonfinite search curvature')
        alpha = rr/curvature
        x = [xi+alpha*pi for xi, pi in zip(x, p)]
        r = [ri-alpha*hi for ri, hi in zip(r, hp)]
        new_rr = dot(r, r)
        if new_rr <= tolerance**2:
            return x
        p = [ri+new_rr/rr*pi for ri, pi in zip(r, p)]
        rr = new_rr
    return x


def trust_step(theta, rows, limit=0.01, damping=0.01, backtracks=12):
    if not math.isfinite(limit) or limit <= 0 or backtracks < 0:
        raise ValueError('positive finite KL limit and nonnegative backtracks required')
    if not rows or any(len(x) != len(theta) or abs(old-dot(theta, x)) > 1e-12
                       for x, _, old, _, _ in rows):
        raise ValueError('rows must describe this old policy')
    g = gradient(rows)
    if dot(g, g) < 1e-24:
        return list(theta), {'accepted': False, 'reason': 'zero_gradient', 'kl': 0., 'gain': 0.}
    product = lambda v: fisher_product(v, rows, damping)
    direction = conjugate_gradient(product, g)
    quadratic = dot(direction, product(direction))
    if not math.isfinite(quadratic) or quadratic <= 0:
        raise ValueError('invalid quadratic model')
    scale = math.sqrt(2*limit/quadratic)
    old_objective = surrogate(theta, rows)
    for index in range(backtracks):
        fraction = 0.5**index
        candidate = [old+fraction*scale*d for old, d in zip(theta, direction)]
        kl = mean_kl(candidate, rows)
        gain = surrogate(candidate, rows)-old_objective
        if math.isfinite(kl) and math.isfinite(gain) and kl <= limit and gain > 0:
            return candidate, {'accepted': True, 'fraction': fraction, 'kl': kl, 'gain': gain}
    return list(theta), {'accepted': False, 'reason': 'line_search_failed', 'kl': 0., 'gain': 0.}


def expected_return(theta):
    return sum(w*((1-sigmoid(dot(theta, x)))*r0+sigmoid(dot(theta, x))*r1)
               for x, w, (r0, r1) in zip(FEATURES, WEIGHTS, REWARDS))


def main():
    theta, history = [0., 0.], []
    for _ in range(12):
        theta, info = trust_step(theta, batch(theta))
        history.append(dict(info, value=expected_return(theta), logits=list(theta)))
    rare = old_new_kl(0., math.log(99.))
    print(json.dumps({'initial_return': 0.5, 'history': history,
                     'rare_state': {'mean_kl': 0.001*rare, 'max_kl': rare},
                     'direction': {'old_0_8_new_0_5': old_new_kl(math.log(4.), 0.),
                                   'old_0_5_new_0_8': old_new_kl(0., math.log(4.))}}, indent=2))


if __name__ == '__main__':
    main()
Inspect the complete recorded output
{
  "initial_return": 0.5,
  "history": [
    {
      "accepted": true,
      "fraction": 1.0,
      "kl": 0.009416551979636756,
      "gain": 0.06357512998936987,
      "value": 0.5635751299893699,
      "logits": [
        0.0897309489111102,
        0.31497394311654997
      ]
    },
    {
      "accepted": true,
      "fraction": 1.0,
      "kl": 0.009219273247272864,
      "gain": 0.06145530770845891,
      "value": 0.6250304376978288,
      "logits": [
        0.18131799820683048,
        0.634103061644611
      ]
    },
    {
      "accepted": true,
      "fraction": 1.0,
      "kl": 0.00900276956590894,
      "gain": 0.0583255112185675,
      "value": 0.6833559489163963,
      "logits": [
        0.27855411072156344,
        0.965757570193035
      ]
    },
    {
      "accepted": true,
      "fraction": 1.0,
      "kl": 0.008763287566087597,
      "gain": 0.05442405023281381,
      "value": 0.7377799991492101,
      "logits": [
        0.38558991227888373,
        1.3188198189763938
      ]
    },
    {
      "accepted": true,
      "fraction": 1.0,
      "kl": 0.00849391901596096,
      "gain": 0.04998595820603277,
      "value": 0.7877659573552429,
      "logits": [
        0.5071768791490894,
        1.7031622142383194
      ]
    },
    {
      "accepted": true,
      "fraction": 1.0,
      "kl": 0.008183323166937543,
      "gain": 0.0451834819208034,
      "value": 0.8329494392760463,
      "logits": [
        0.6487656235970767,
        2.1299546555336564
      ]
    },
    {
      "accepted": true,
      "fraction": 1.0,
      "kl": 0.007812439362546563,
      "gain": 0.0400767747323511,
      "value": 0.8730262140083973,
      "logits": [
        0.8164074787312559,
        2.6116986930219124
      ]
    },
    {
      "accepted": true,
      "fraction": 1.0,
      "kl": 0.00735002057989406,
      "gain": 0.03462050897657821,
      "value": 0.9076467229849756,
      "logits": [
        1.0165397927384996,
        3.1619776128621377
      ]
    },
    {
      "accepted": true,
      "fraction": 1.0,
      "kl": 0.006751411970818527,
      "gain": 0.028766566304586606,
      "value": 0.9364132892895621,
      "logits": [
        1.255917237306447,
        3.795127254585874
      ]
    },
    {
      "accepted": true,
      "fraction": 1.0,
      "kl": 0.005967045755024265,
      "gain": 0.022620640947955545,
      "value": 0.9590339302375177,
      "logits": [
        1.5417239782041754,
        4.525923413961706
      ]
    },
    {
      "accepted": true,
      "fraction": 1.0,
      "kl": 0.0049654229394753766,
      "gain": 0.01652839716616252,
      "value": 0.9755623274036802,
      "logits": [
        1.8807525493874544,
        5.368482148711809
      ]
    },
    {
      "accepted": true,
      "fraction": 1.0,
      "kl": 0.003776325765472546,
      "gain": 0.01101676367970683,
      "value": 0.986579091083387,
      "logits": [
        2.274839517758609,
        6.33283422145156
      ]
    }
  ],
  "rare_state": {
    "mean_kl": 0.0016144630803608506,
    "max_kl": 1.6144630803608506
  },
  "direction": {
    "old_0_8_new_0_5": 0.19274475702175742,
    "old_0_5_new_0_8": 0.2231435513142097
  }
}

Return rises from 0.5 to about 0.986579. All 12 steps pass actual-KL and surrogate-gain checks; the last KL is about 0.003776. Since a one-step contextual task has fixed context weights, its surrogate gain exactly equals true return improvement. That equality cannot be transferred directly to longer tasks with changing state occupancy.

For N contexts and d parameters, one Fisher product costs O(Nd) time and O(d) working space. K conjugate-gradient iterations cost about O(KNd), with J backtracking trials adding O(JNd). An explicit dense F requires O(d squared) storage; this program never builds it. Tests cover zero gradients, zero residuals, nonpositive curvature and retaining parameters after failed backtracking.

Specify both direction and distance

KL is asymmetric. Old||new and new||old share the local Fisher at the old point but need not give the same distant values or backtracking decisions. The pinned Spinning Up documentation uses new||old, its TF1 categorical implementation uses old||new, and its Gaussian implementation uses new||old. This article uses the paper’s direction consistently and checks an asymmetric example. Documentation and implementation

Poor rare-state coverage, advantage error, nearly singular Fisher matrices and distribution shift can weaken practical constraints. Stricter backtracking increases computation and may reject many updates. PPO uses a surrogate convenient for first-order optimization, but clipping does not impose the same hard KL constraint.

Audit a candidate against its acceptance rule

  1. Does a candidate pass if KL is acceptable but the surrogate falls? Answer: No. Actual KL must stay within the limit and the surrogate must strictly improve. Exhausting the trials returns the old parameters.
  2. Solve[[4,1],[1,3]] times x=[1,2]. Answer: x=[1/11,7/11]. Substitution gives 1 and 2 in the two rows, providing an independent conjugate-gradient check rather than trusting a convergence flag alone.
  3. Why does mean KL 0.001614 not prove all state KL values are below 0.01? Answer: The rare state’s KL is about 1.614, reduced in the mean by weight 0.001. Mean and maximum constraints differ.
  4. What evaluation must be added when extending the program to a multi-step environment? Answer: Collect independent new-policy trajectories to evaluate true return and state coverage rather than only old-state surrogate gain. Specify advantage estimation, sampling error, truncation and KL direction as well.

Keep the theoretical bound separate from the practical update

The reading covers TRPO PDF 1–6, with 3/4 viewed. Publisher metadata confirms 32nd ICML 2015, PMLR 37:1889–1897. The paper minimizes cost; this article consistently maximizes reward. Later result tables and separately attached proofs were not audited. TRPO

At Spinning Up commit 038665d, TRPO documentation 1–134, selected TF1 trpo.py ranges and all161 core.py lines were read for conjugate gradient, KL direction and backtracking. The PyTorch file is only an unimplemented stub. No upstream code was executed or copied; these results are exact contextual teaching calculations. Implementation reference

Make a prediction, then check

Does mean KL below0.01 guarantee every state KL is below0.01?

Choose one answer

Learning objectives

  • Derive a locally KL-constrained natural-gradient step and solve it with matrix-vector products.
  • Backtrack on measured old||new KL and surrogate improvement, stating the limit of average constraints.

Prerequisites & connections

Explore related knowledge →

References

  1. Trust Region Policy Optimization — scoped surrogate and practical update
    John Schulman; Sergey Levine; Philipp Moritz; Michael Jordan; Pieter Abbeel · 2015
  2. Spinning Up — scoped TRPO documentation and TF1 implementation
    OpenAI; Joshua Achiam and contributors · 2020

Version1 · Editorial status: Recorded technical checks completed

View technical check record (AI)

Codex · 2026-09-23 · Single AI author. Scoped reading: Publisher confirms32nd ICML2015, PMLR37:1889–1897; PDF footer mislabels31st. Read PDF1–6, viewed3/4. Cost-minimization sign, old||new KL and distinction between maximum-state bound and average constraint. No later table or separate proof audit. Read docs1–134, TF1 trpo.py1–96,165–328 and all161 core.py lines. PyTorch file is a stub. Docs/Gaussian use new||old; categorical code uses old||new. MIT reference, no upstream execution or copying. 6 paired equations and four explained exercises. Shared-feature exact contextual-bandit surrogate and old||new KL; Fisher quadratic checked by finite differences, CG against a known linear system, zero/nonpositive curvature and actual full-step rejection/half-step acceptance. Failed search restores old parameters; mean-KL rare-state counterexample retained. No trajectory benchmark or maximum-state guarantee.

  • Shared-feature exact contextual-bandit surrogate and old||new KL; Fisher quadratic checked by finite differences, CG against a known linear system, zero/nonpositive curvature and actual full-step rejection/half-step acceptance. Failed search restores old parameters; mean-KL rare-state counterexample retained. No trajectory benchmark or maximum-state guarantee.
  • Four computed SVG variants per topic;16 numeric/geometry tests and36 current responsive cases passed. All twelve selected current captures directly viewed. Three groups retain initial captures; three use their actually viewed revised captures. Actual assets and manuscripts are SHA bound. Full article acceptance recorded separately.

Source locations checked:

Related topics

No matches. Try a synonym or acronym.

0 results shown

Wrap the whole query in double quotes for a phrase match.