Reinforcement Learning

Policy Gradient

Policy gradients update a stochastic policy directly: a sampled action becomes more or less likely according to its return relative to a baseline, through grad log pi.

status: reviewimportance: criticaldifficulty 4/5math: graduateread: 22mlive demo

Concept Structure

Policy Gradient

01Intuition

Start with the picture, metaphor, or geometric mechanism.

02Math

Make the objects explicit and connect them with notation.

03Code

Mirror the equations with runnable implementation details.

04Interactive Demo

Manipulate the mechanism and watch the idea respond.

2prerequisites
2next concepts
3related links

Learner Contract

What this page should let you do.

You are here becausePolicy gradients update a stochastic policy directly: a sampled action becomes more or less likely according to its return relative to a baseline, through grad log pi.

This Reinforcement Learning concept is the current idea: keep the same invariant visible across Intuition, Math, Code, Interactive Demo.

By the end4/4 sections ready | runnable code expected | live demo

Explain the mechanism, trace the main notation, and test one prediction in the live demo.

Do this firstIntuition

Read the intuition before the notation; the math should name a mechanism you already felt.

Test the linkManipulate one control and predict the visible change.Then continue to RLHF as Reinforcement Learning (review)

Claim/source review status

Substantive review recorded

1/1 claims have bounded review metadata; still check caveats and source scope.Metadata-derived; review may be AI-assisted. Not a human certification.
Claims1/1 reviewed
Sources2 cited
Codeattached
Demolive
Reviewed2026-07-03
Updatedpage 2026-07-03

Learning item flow

4/4 sections readyAsk about thisResearch room
ConceptPolicy GradientReinforcement Learning
2 sources attachedLocal snapshot ready
concept:reinforcement-learning/policy-gradient
01

01

Intuition

Build the mental picture first so the rest of the page has something to attach to.

Section prompt

Q-learning and SARSA learn an action-value table first, then choose actions from that table. A policy-gradient method asks a more direct question:

If this policy actually sampled an action, did the outcome make that sampled action deserve more probability or less probability next time?

The policy is not told which action was best. It only sees the action it sampled, the return that followed, and a baseline for what this state usually earns. If the return beats the baseline, the update nudges the policy to make the sampled action more likely. If the return falls below the baseline, the same sampled action is nudged down.

The strange-looking object is θlogπθ(as)\nabla_\theta \log \pi_\theta(a \mid s), often called the score function. It points in the parameter direction that would increase the log-probability of the sampled action. Multiplying it by an advantage-like number, Gtb(St)G_t - b(S_t), decides whether that direction is followed or reversed.

02

02

Math

Translate the story into symbols, assumptions, and a derivation you can inspect.

Section prompt

Let πθ(as)\pi_\theta(a \mid s) be a differentiable stochastic policy with parameters θ\theta. In an episodic MDP, a trajectory is

τ=(S0,A0,R1,,ST).\tau = (S_0,A_0,R_1,\ldots,S_T).

Write G(τ)G(\tau) for the return from the trajectory, and define the objective

J(θ)=Eτπθ[G(τ)].J(\theta) = \mathbb{E}_{\tau \sim \pi_\theta}[G(\tau)].

The score-function identity starts from

θJ(θ)=θτpθ(τ)G(τ).\nabla_\theta J(\theta) = \nabla_\theta \sum_\tau p_\theta(\tau)G(\tau).

Multiplying and dividing by pθ(τ)p_\theta(\tau) gives

θJ(θ)=τpθ(τ)G(τ)θlogpθ(τ)=Eτπθ[G(τ)θlogpθ(τ)].\nabla_\theta J(\theta) = \sum_\tau p_\theta(\tau)G(\tau)\nabla_\theta \log p_\theta(\tau) = \mathbb{E}_{\tau \sim \pi_\theta} \left[ G(\tau)\nabla_\theta \log p_\theta(\tau) \right].

For an MDP whose start-state distribution and environment dynamics do not depend on θ\theta,

pθ(τ)=ρ(S0)t=0T1πθ(AtSt)p(St+1,Rt+1St,At).p_\theta(\tau) = \rho(S_0)\prod_{t=0}^{T-1} \pi_\theta(A_t \mid S_t)\,p(S_{t+1},R_{t+1}\mid S_t,A_t).

So the only differentiable terms in the trajectory probability are the policy probabilities:

θlogpθ(τ)=t=0T1θlogπθ(AtSt).\nabla_\theta \log p_\theta(\tau) = \sum_{t=0}^{T-1} \nabla_\theta \log \pi_\theta(A_t \mid S_t).

The basic REINFORCE estimator uses sampled returns:

g=t=0T1Gtθlogπθ(AtSt).g = \sum_{t=0}^{T-1} G_t \nabla_\theta \log \pi_\theta(A_t \mid S_t).

An action-independent baseline b(St)b(S_t) can be subtracted without changing the expected gradient:

g=t=0T1(Gtb(St))θlogπθ(AtSt).g = \sum_{t=0}^{T-1} \left(G_t - b(S_t)\right) \nabla_\theta \log \pi_\theta(A_t \mid S_t).

The baseline matters because the raw Monte Carlo estimator can be noisy. If GtG_t is above the baseline, the sampled action is reinforced. If GtG_t is below the baseline, the sampled action is suppressed. The baseline is not allowed to depend on the sampled action in a way that sneaks in extra action preference.

In the one-step two-action demo below, GtG_t is just the observed reward RR, and the sample update is

θθ+α(Rb)θlogπθ(a).\theta \leftarrow \theta + \alpha (R-b)\nabla_\theta \log \pi_\theta(a).
03

03

Code

Keep the implementation aligned with the notation so the algorithm is legible.

Section prompt
import numpy as np

alpha = 0.25
theta = np.array([0.40, -0.20])  # logits: [practice, hint]

def softmax(x):
    z = x - np.max(x)
    exp = np.exp(z)
    return exp / exp.sum()

def grad_log_prob(probs, action):
    grad = -probs.copy()
    grad[action] += 1.0
    return grad

cases = [
    ("above baseline", 0, 2.00, 0.80),
    ("below baseline", 0, 0.20, 0.80),
    ("hint helped", 1, 1.40, 0.80),
]

for name, action, reward, baseline in cases:
    probs = softmax(theta)
    advantage = reward - baseline
    score = grad_log_prob(probs, action)
    delta = alpha * advantage * score
    new_theta = theta + delta
    print(name)
    print("  probs", np.round(probs, 3))
    print("  advantage", round(advantage, 3))
    print("  score", np.round(score, 3))
    print("  logit delta", np.round(delta, 3))
    print("  new logits", np.round(new_theta, 3))

The code is intentionally small. It shows the whole update: softmax probabilities, the score-function vector for the sampled action, the advantage, and the resulting logit change.

04

04

Interactive Demo

Use direct manipulation to connect the explanation to a moving system.

Section prompt

Use the Policy Gradient Score-Function Lab to predict whether the sampled action's logit increases, decreases, or stays unchanged.

Choose a case, inspect the policy logits, sampled action, reward, and baseline, then commit to the update direction. After reveal, the lab shows the advantage, the score-function vector, the policy-gradient sample, the logit update, and the new logits.

The below-baseline case is the important one: a positive reward can still decrease the sampled action if the baseline says this state usually does better.

Live Concept Demo

Explore Policy Gradient

The stage is code-native and interactive. Use it to test the explanation against the mechanism.

difficulty 4/5graduatecode-aligned
Demo Prediction Checkpoint

Manipulate one control and predict the visible change.

Commit to what Policy Gradient should make visible before reading the result.

After The First Pass

Turn the concept into an inspected object.

Once the invariant is visible in the intuition, math, code, and demo, use these panels to inspect the mechanism visually, check source support, practice the idea, and attach a grounded research question.

Mechanism Storyboard

See the idea move before the page explains it

Policy gradients update a stochastic policy directly: a sampled action becomes more or less likely according to its return relative to a baseline, through grad log pi.

Prediction open01 / Intuition
Prediction lens

Start with the picture, metaphor, or geometric mechanism.

Commit first

Before reading further, choose the kind of change Policy Gradient should make visible.

Visual Inquiry

Make the image answer a mathematical question

Policy gradients update a stochastic policy directly: a sampled action becomes more or less likely according to its return relative to a baseline, through grad log pi.

4/4 stages readyLive demo connected
Prediction

Which visible object should carry the first intuition?

Commit first

Pick the cue that should make Policy Gradient easier to reason about before the page gives the answer.

Source Grounding

Canonical references for the mechanism on this page.

book · 2018Reinforcement Learning: An Introduction, Second EditionRichard S. Sutton and Andrew G. Barto

Canonical Chapter 13 source for differentiable policy parameterization, the policy-gradient theorem, REINFORCE, high-variance Monte Carlo updates, and action-independent baselines.

Open source
course-notes · 2026Stanford CS234: Lecture 5, Policy Gradient IStanford CS234

Graduate RL source for the likelihood-ratio derivation, trajectory log-probability decomposition, no-dynamics-model point, score-function estimator, baseline, and advantage form.

Open source

Claim Review

Policy gradients update a stochastic policy directly: a sampled action becomes more or less likely according to its return relative to a baseline, through grad log pi.

Status1 substantive review recorded

Claims without a substantive review badge still need exact source-support review.

Sources2 references

sutton-barto-2018-rl, stanford-cs234-policy-gradient-2026

Local checks4 local checks

Use equations, runnable code, and demos to check whether the source support is operational.

Substantively reviewedREINFORCE estimates a policy-gradient direction with (G_t - b(S_t)) grad log pi terms; an action-independent baseline can reduce variance without biasing the expected gradient.Claim metadata: source checked

The sources support direct stochastic-policy gradient ascent, the score-function identity, dropping environment-dynamics derivatives when dynamics are theta-independent, Monte Carlo return weighting, and subtracting an action-independent baseline to form an advantage-like sample without biasing the expected gradient.

Sources: Reinforcement Learning: An Introduction, Second Edition, Stanford CS234: Lecture 5, Policy Gradient IFinite episodic teaching setting with a two-action softmax bandit-style demo; excludes actor-critic bootstrapping, GAE, PPO/TRPO, entropy regularization, off-policy corrections, continuous action distributions, and deep-network implementation stability.A bounded review summary is present; still check caveats and exact reference scope.

Checked Sutton/Barto Chapter 13 for differentiable softmax policies, the policy-gradient theorem, the REINFORCE update, high variance, and the baseline argument; checked Stanford CS234 Lecture 5 for the likelihood-ratio derivation, trajectory log-probability decomposition into policy score terms, no-dynamics-model point, baseline, and advantage estimator. GPT Pro publication critique remains pending because 127.0.0.1:51672 is unavailable.

Reviewer: codex-local-source-review; reviewed 2026-07-03

Practice Loop

Try the idea before it explains itself

Policy gradients update a stochastic policy directly: a sampled action becomes more or less likely according to its return relative to a baseline, through grad log pi.

Readiness0/3 checks ready
Predict

Before touching the demo, predict one visible change that should happen in Policy Gradient.

Hint 1

Reveal when your model needs a nudge.

Hint 2

Reveal when your model needs a nudge.

Hint 3

Reveal when your model needs a nudge.

Grounded research drawerClose
ConceptPolicy GradientReinforcement Learning
Runnable code comparisonPolicy Gradient runnable code 1alpha = 0.25Prediction before revealPolicy Gradient interactive demoManipulate one control and predict the visible change.
Grounded room questionWhat is the smallest example that makes Policy Gradient click without losing the math?Local snapshot ready

Research Room

Attach the question to a claim, equation, code, or demo

Pick the concept, equation, source, runnable code, claim, misconception, or demo state before asking for help. The handoff keeps that page item in context.
Next local actionNo local draft saved yet

Open the draft below to save one note and next action in this browser.

conceptReinforcement Learning

Policy Gradient

Attached question

What is the smallest example that makes Policy Gradient click without losing the math?

Local action draftNo local draft saved yetExpand only when ready to capture one local next action
Local action draft

This draft stays in this browser, attached to the selected learning item.

No local draft saved.
Evidence to inspect
  • References to inspect: attached references on this page.
  • Definition, prerequisite, and contrast concept links
  • The equation or runnable code that makes the concept operational
  • One demo state that shows the invariant instead of a slogan
What would resolve this
  • The learner can state the mechanism in their own words
  • The learner can name the prerequisite that would repair confusion
  • The learner can predict how the mechanism changes under one perturbation
Grounded AI handoff

I am working in Continuous Function's research reading room. Object: concept - Policy Gradient Selected item key: recorded for copy. Context: Reinforcement Learning Page anchor: recorded for copy. Open question: What is the smallest example that makes Policy Gradient click without losing the math? Evidence to inspect: - References to inspect: attached references on this page. - Definition, prerequisite, and contrast concept links - The equation or runnable code that makes the concept operational - One demo state that shows the invariant instead of a slogan What would resolve this: - The learner can state the mechanism in their own words - The learner can name the prerequisite that would repair confusion - The learner can predict how the mechanism changes under one perturbation Answer as a careful research tutor: stay source-grounded, separate verified evidence from assumptions, name the relevant math objects, and end with one next action.

View it in context
concept/concept-notebook/reinforcement-learning/policy-gradient concept:reinforcement-learning/policy-gradient