AI Wiki中文/EN

Policy gradients: differentiate action probabilities

策略梯度

Check a gradient with four trajectories and separate time discounts, occupancy and action-independent baselines.

On this pageIntuitionMathematics & methodImplementationLimitationsExercisesResearch connections

Four routes are enough to check a policy gradient

Consider a two-step game. The first action chooses a left or right branch; choosing right immediately costs 0.1. On the left, the second action earns 0.4 for action 0 and zero for action 1. On the right, action 1 earns 1 and action 0 earns zero. Discount the second reward by 0.9. Always choosing right and then 1 earns 0.8; always choosing left and then 0 earns 0.36. An initial policy need not know which route pays.

A value method estimates action values before using them to choose actions. A policy-gradient method adjusts the parameters of the action distribution directly. Increasing the probability of successful actions sounds reasonable, but assigning credit across decisions and differentiating a probability require a precise rule. Policy-gradient derivation

We use three Bernoulli logits: one at the start and one on each branch. There are only four possible trajectories, so enumeration, an analytic score estimator and finite differences can all check the same result. Start with Markov decision processes and the chain rule.

Four trajectories check the score gradient against finite differences; changing gamma changes the start-state objective.
Four trajectories check the score gradient against finite differences; changing gamma changes the start-state objective.

Environment factors disappear from a derivative, not from the problem

Let tau be a trajectory of length T, rho the initial-state distribution, P the transition law and pi a differentiable stochastic policy. Assume the initial distribution, environment and reward mechanism do not directly depend on policy parameters and that policy support is fixed. Finite states and horizon make exchanging sums and derivatives valid here. The objective discounts rewards r_t from the start:

pθ(τ)=ρ(s0)∏t=0T−1πθ(at∣st)P(st+1∣st,at),Jγ(θ)=Eτ∼pθ ⁣[∑t=0T−1γtrt].p_\theta(\tau)=\rho(s_0)\prod_{t=0}^{T-1}\pi_\theta(a_t\mid s_t)P(s_{t+1}\mid s_t,a_t),\qquad J_\gamma(\theta)=\mathbb E_{\tau\sim p_\theta}\!\left[\sum_{t=0}^{T-1}\gamma^t r_t\right].

Random rewards can also be included in the trajectory probability; their parameter-independent factors contribute no log derivative. Write the derivative of a probability as that probability times its log derivative, then expand the log of the product:

∇Jγ=E ⁣[Rγ(τ)∑t=0T−1∇log⁡πθ(at∣st)],Rγ=∑tγtrt.\nabla J_\gamma=\mathbb E\!\left[R_\gamma(\tau)\sum_{t=0}^{T-1}\nabla\log\pi_\theta(a_t\mid s_t)\right],\qquad R_\gamma=\sum_t\gamma^t r_t.

The environment still determines trajectory frequencies and rewards. This estimator simply avoids differentiating a transition model. An action cannot change rewards already realized. Conditional on the preceding history, its score has mean zero, so multiplying that score by a past reward contributes zero in expectation. Removing those terms gives reward-to-go:

Gt=∑k=tT−1γk−trk,∇Jγ=E ⁣[∑t=0T−1γt∇log⁡πθ(at∣st)Gt].G_t=\sum_{k=t}^{T-1}\gamma^{k-t}r_k,\qquad \nabla J_\gamma=\mathbb E\!\left[\sum_{t=0}^{T-1}\gamma^t\nabla\log\pi_\theta(a_t\mid s_t)G_t\right].

The outer gamma^t preserves the reward’s time position in the start-state objective. Omitting it generally changes the expected update. Some implementations combine discounted advantages with uniform time sampling and an undiscounted update form; that approximation needs an explicit explanation rather than the claim that the exact derivation is unchanged. Discount conventions in practice

A baseline b_t may be subtracted if, conditional on state and time, it does not depend on the current sampled action. A baseline fitted on earlier data is held constant in the current differentiation:

∑aπθ(a∣s)∇log⁡πθ(a∣s)bt(s)=bt(s)∇∑aπθ(a∣s)=0.\sum_a\pi_\theta(a\mid s)\nabla\log\pi_\theta(a\mid s)b_t(s) =b_t(s)\nabla\sum_a\pi_\theta(a\mid s)=0.

Replacing G_t by G_t−b_t therefore preserves the expectation. It does not permit subtracting each action’s own observed return, which would erase the signal. The policy-gradient theorem also rewrites the trajectory sum using occupancy and action value. For an infinite horizon with gamma below 1 and bounded rewards, define the unnormalized discounted occupancy d_gamma:

dγπ(s)=∑t=0∞γtPr⁡π(st=s),∇Jγ=∑sdγπ(s)∑a∇πθ(a∣s)Qπ(s,a).d_\gamma^\pi(s)=\sum_{t=0}^{\infty}\gamma^t\Pr_\pi(s_t=s),\qquad \nabla J_\gamma=\sum_s d_\gamma^\pi(s)\sum_a\nabla\pi_\theta(a\mid s)Q^\pi(s,a).

Sampling from the normalized distribution(1−gamma)d_gamma requires the corresponding 1/(1−gamma) factor. Occupancy does depend on the policy; the derivation absorbs that dependence through the value recursion rather than adding a separate occupancy derivative to this expression. A finite horizon requires time-indexed Q or remaining time as part of the state. The theorem and occupancy definition

For p=sigmoid(theta), the Bernoulli action log-probability derivative is a−p. With all three parameters zero, each trajectory has probability 1/4. Enumeration gives:

∇θlog⁡πθ(a)=a−p,J0.9(0)=0.265,∇J0.9(0)=(0.0425,−0.045,0.1125).\nabla_\theta\log\pi_\theta(a)=a-p,\qquad J_{0.9}(0)=0.265,\qquad \nabla J_{0.9}(0)=(0.0425,-0.045,0.1125).

The negative left-branch component reduces the probability of its unrewarded action 1. The positive start component favors going right, while reflecting that the current right-branch policy earns the final reward only half the time.

Three calculations of one objective

This standard-library Python program enumerates four trajectories, sums score times relative return with the time weight, and independently perturbs each parameter for central finite differences. It uses theta=[0.2,−0.4,0.7]. Output also shows the incorrect omission of the outer discount and the effect of subtracting time baselines. Baselines should preserve the gradient; dropping the discount generally does not.

"""Exact policy gradients in a finite two-decision MDP; standard library only."""
import itertools
import json
import math


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 trajectories(theta, gamma=0.9):
    if len(theta) != 3 or not 0 <= gamma <= 1:
        raise ValueError('three logits and gamma in [0,1] required')
    p = [sigmoid(x) for x in theta]
    for a0, a1 in itertools.product((0, 1), repeat=2):
        branch = 1 + a0
        prob = (p[0] if a0 else 1-p[0]) * (p[branch] if a1 else 1-p[branch])
        r0, r1 = -0.1*a0, (float(a1) if a0 else 0.4*(1-a1))
        score0, score1 = [a0-p[0], 0., 0.], [0., 0., 0.]
        score1[branch] = a1-p[branch]
        yield prob, (r0, r1), (score0, score1)


def evaluate(theta, gamma=0.9, baseline=(0., 0.), outer_discount=True):
    """Baselines are fixed by time, independent of sampled actions and theta."""
    if len(baseline) != 2 or not all(math.isfinite(x) for x in baseline):
        raise ValueError('two finite time baselines required')
    value, gradient = 0., [0., 0., 0.]
    for prob, (r0, r1), scores in trajectories(theta, gamma):
        value += prob*(r0+gamma*r1)
        for t, ret in enumerate((r0+gamma*r1, r1)):
            weight = gamma**t if outer_discount else 1.
            for j in range(3):
                gradient[j] += prob*weight*scores[t][j]*(ret-baseline[t])
    return value, gradient


def finite_difference(theta, gamma=0.9, h=1e-5):
    if not math.isfinite(h) or h <= 0:
        raise ValueError('positive finite difference step required')
    result = []
    for j in range(3):
        plus, minus = list(theta), list(theta)
        plus[j] += h
        minus[j] -= h
        result.append((evaluate(plus, gamma)[0]-evaluate(minus, gamma)[0])/(2*h))
    return result


def main():
    theta = [0.2, -0.4, 0.7]
    value, gradient = evaluate(theta)
    print(json.dumps({'objective': 'E[r0 + 0.9*r1]', 'theta': theta,
                     'value': value, 'score_gradient': gradient,
                     'finite_difference': finite_difference(theta),
                     'missing_outer_discount': evaluate(theta, outer_discount=False)[1],
                     'with_time_baseline': evaluate(theta, baseline=(0.3, 0.7))[1]}, indent=2))


if __name__ == '__main__':
    main()
Inspect the complete recorded output
{
  "objective": "E[r0 + 0.9*r1]",
  "theta": [
    0.2,
    -0.4,
    0.7
  ],
  "value": 0.37269289771466074,
  "score_gradient": [
    0.07075049290221774,
    -0.038936599024747415,
    0.10971474784054656
  ],
  "finite_difference": [
    0.07075049290039548,
    -0.03893659902276525,
    0.1097147478423821
  ],
  "missing_outer_discount": [
    0.07075049290221774,
    -0.0432628878052749,
    0.12190527537838508
  ],
  "with_time_baseline": [
    0.07075049290221772,
    -0.038936599024747415,
    0.10971474784054656
  ]
}

Enumeration is cheap for T=2 and parameter dimension d=3. In general, A actions over T steps can produce A to the powerT trajectories. Accumulating scores from B sampled trajectories takes O(BTd) scalar work and O(d) accumulator space, in addition to policy computation and trajectory storage. Finite differences evaluate the objective again for each parameter: useful for small checks, unsuitable as a large-model training strategy.

A correct gradient estimate can still be noisy

One sampled trajectory may point toward lower true return; unbiasedness concerns its sampling expectation. Long episodes, rare rewards and nearly deterministic policies complicate estimation or exploration. Baselines, actor–critic methods and advantage estimators change the estimator with their own conditions. A baseline need not reduce variance in every problem; REINFORCE gives a counterexample.

Sutton and colleagues also study compatible function approximation: critic features must match policy scores and satisfy a particular weighted residual-orthogonality condition. Training an arbitrary value network beside the policy does not establish those conditions. Compatibility conditions Policy-dependent environment parameters, changing support or nonintegrable returns require revisiting the derivation.

Check the symbols against the routes

  1. Why is the left-branch gradient negative? Answer: Action 0 there earns 0.4; action 1 earns zero. Increasing that branch’s logit favors action 1 and reduces return. It is a different parameter from the start-state right-branch choice.
  2. Set gamma to zero. What is the gradient at zero parameters? Answer: (−0.025,0,0). Only the immediate right-branch cost remains, with derivative−0.1 times 0.25. Both second-decision parameters cease to affect the objective.
  3. Subtracting the actual G_t makes every gradient zero. Is that a valid baseline? Answer: Generally no. G_t depends on the current action, violating the baseline condition. The zero-mean score argument for a state baseline does not cover action-dependent returns.
  4. How would you retain a reliable check with 100-step trajectories? Answer: Train by trajectory sampling while retaining a small enumerable environment for finite-difference and analytic comparisons. Tiny differences computed from independent random samples in the long environment may be dominated by sampling noise; control randomness and report estimation error.

Read the trajectory derivation before the occupancy theorem

Spinning Up makes the log derivative, causal removal of terms and baseline argument accessible; its VPG documentation also explains the implementation’s discount convention. The reading here covers rl_intro3 lines 1–124,277–344,389–461 and VPG documentation 1–100 at commit 038665d. No upstream implementation was executed. Teaching reference

Sutton and colleagues’1999 paper, PDF 2–4, develops average reward, discounted occupancy and compatible approximation. Later full convergence proofs were not audited. These sources support the derivation and conditions; the four-route numerical results come from our independent program, not a reproduction of paper performance. Original paper

Make a prediction, then check

For E[r0+0.9r1], what factor multiplies the second-step reward-to-go score?

Choose one answer

Learning objectives

  • Derive the score-function gradient from trajectory probabilities with the correct outer discount.
  • Check one objective by enumeration and finite differences, stating when a baseline preserves the expectation.

Prerequisites & connections

Explore related knowledge →

References

  1. Policy Gradient Methods for Reinforcement Learning with Function Approximation — scoped theorem reading
    Richard S. Sutton; David McAllester; Satinder Singh; Yishay Mansour · 1999
  2. Spinning Up — scoped policy-gradient derivation
    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: Identity on PDF1; read2–4 and viewed3/4. Average reward, discounted occupancy and both compatible-approximation conditions. No later full proof audit or experiment replication. Fixed commit. Read rl_intro3 lines1–124,277–344,389–461 and VPG docs1–100: finite-horizon derivation, zero-mean score and baselines. README/license fully read; VPG code cached but unread. No upstream execution or copying. 6 paired equations and four explained exercises. Four-trajectory score gradient checked against finite differences and full-return enumeration; outer time discount, gamma0 boundary, baseline cancellation and unnormalized occupancy distinguished. Fixed support and parameter-independent environment assumptions retained; no arbitrary-critic compatibility claim.

  • Four-trajectory score gradient checked against finite differences and full-return enumeration; outer time discount, gamma0 boundary, baseline cancellation and unnormalized occupancy distinguished. Fixed support and parameter-independent environment assumptions retained; no arbitrary-critic compatibility claim.
  • 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.