Skip to content

Spinning Up in Deep RL

optionalcorefundamentalcourserubric 10/122018 · OpenAI · ~360 min

Joshua Achiam

Status

TL;DR. A short documentation-style course from OpenAI (2018): key concepts, a taxonomy of algorithms, a derivation of policy gradients with matching PyTorch code, and clean single-file implementations of VPG, TRPO, PPO, DDPG, TD3 and SAC. For this site it is the code-first bridge for stages 2–3 of the course map: from REINFORCE to PPO, with honest notes on what PPO does and does not guarantee.

Why it matters now. Almost every LLM-RL codebase still has the shape of Spinning Up’s PPO: collect rollouts, compute advantages with a value baseline, then take several clipped gradient steps. Part 3 is also the clearest explanation of why the policy-gradient “loss” you log in an RLHF run is not a measure of performance.

  • Site: spinningup.openai.com. The introduction says it is “currently in maintenance mode”, with an initial release on Nov 8, 2018. Code: github.com/openai/spinningup, with PyTorch and TensorFlow 1 versions. The repository’s citation lists Joshua Achiam as author.
  • Scope: model-free deep RL for control (Gym and MuJoCo-style tasks). There is nothing on LLMs, reward models or RLHF.
Spinning Up reading path from key concepts to PPO Six boxes left to right: Part 1 key concepts, Part 2 taxonomy, Part 3 policy-gradient derivation, VPG with GAE, TRPO with a KL limit, PPO with clip 0.2. Under Part 3 a box lists its tools: the expected grad-log-prob lemma, reward-to-go and baselines. Under PPO a box explains how the implementation keeps updates small: the clip ratio, early stopping when mean KL exceeds target_kl 0.01, and at most 80 policy steps. Part 1 Key concepts Part 2 Taxonomy Part 3 PG derivation VPG GAE λ = 0.97 TRPO KL limit PPO clip ε = 0.2 Part 3 tools EGLP lemma: E[∇ log π] = 0 so reward-to-go and baselines keep the mean How the PPO code keeps updates small clip ratio 0.2 (not a constraint by itself) stop epoch if mean KL > target_kl = 0.01 DDPG, TD3, SAC pages: off-policy control, skip for the LLM path
Original sketch. The Spinning Up reading path from concepts to PPO, and the two mechanisms its PPO implementation uses to keep updates small.
PageWhat it coversPrepares you forPriority
Part 1: Key Concepts in RLstates and observations, action spaces, policies, trajectories, reward and return, value functions, optimal Q, Bellman equations, advantage functionsMDPs and returns, Value functions and BellmanCore
Part 2: Kinds of RL Algorithmstaxonomy: model-free vs model-based; policy optimization vs Q-learning and their trade-offsPlacing DQN vs PPOSkim
Part 3: Intro to Policy Optimizationderiving the simplest policy gradient; implementing it; Expected Grad-Log-Prob lemma; reward-to-go (“Don’t let the past distract you”); baselines; other forms (Q, advantage, GAE pointer)REINFORCE, Actor-critic, GAECore: most important
Vanilla Policy Gradienton-policy PG with a value baseline and GAE-Lambda (lam = 0.97 by default)Actor-critic, GAECore
TRPOKL-constrained update, natural gradient, conjugate gradient, line searchTRPOCore
PPOPPO-Penalty vs PPO-Clip, why clipping removes the incentive to move far, early stopping on KL, exploration caveatPPO, then GRPOCore
DDPG, TD3, SAC pagesoff-policy continuous controlNot on the LLM pathSkip
Spinning Up as a Deep RL Researcherbackground, learning by doing, developing a project, doing rigorous researchStage 6 habits: Evaluating reasoning RLRead once
Key Paperscurated deep-RL papers by topic (to 2018)Background reading listReference
ExercisesProblem Set 1 (implementation basics, including the PPO policy), Problem Set 2 (algorithm failure modes), challengesSelf-tests for stages 2–3Do PS1

The simplest policy gradient. For trajectories τ sampled from the policy, ∇θJ=Eτ[∑t∇θlog⁡πθ(at∣st) R(τ)]\nabla_\theta J = \mathbb{E}_\tau\big[\sum_t \nabla_\theta \log \pi_\theta(a_t\mid s_t)\, R(\tau)\big]. The code example (pg_math/1_simple_pg.py) builds a “loss” whose gradient is this estimate.

That “loss” is not a loss. Spinning Up gives two reasons. The data distribution depends on the parameters (data must come from the current policy). And it does not measure performance, even in expectation. Only its gradient at the current parameters means anything. Minimising it for many steps on one batch can make the policy worse; the page says it usually will.

Expected Grad-Log-Prob lemma. Ex∼Pθ[∇θlog⁡Pθ(x)]=0\mathbb{E}_{x\sim P_\theta}[\nabla_\theta \log P_\theta(x)] = 0. So you can add or subtract anything that does not depend on the action without changing the expected gradient. That is what makes reward-to-go (drop rewards earned before the action) and baselines (subtract V(st)V(s_t)) legal. Both keep the mean and reduce variance. Spinning Up’s intuition for the value baseline: if an agent gets exactly the return it expected, the update should be neutral.

PPO as implemented. PPO-Clip has no KL term and no constraint; clipping only removes the incentive to push the ratio outside [1−ϵ,1+ϵ][1-\epsilon, 1+\epsilon]. Because the new policy can still drift too far, the implementation stops further policy updates for the epoch when the estimated mean KL to the old policy exceeds 1.5 × target_kl. With the default target_kl = 0.01 (the docs suggest 0.01 or 0.05), the cutoff is 0.015. Other defaults: clip ratio 0.2, up to 80 policy steps per epoch, γ = 0.99, GAE λ = 0.97, 4,000 environment steps per epoch. The page also warns that PPO is on-policy, explores only through sampling, becomes less random over training, and can get stuck in local optima.

Toy (shared with the course map): s₀ “no evidence”, s₁ “evidence in context”. From s₀, search costs 0.1 and moves to s₁, while answer is right with probability 0.2. From s₁, answer is right with probability 0.9. Use γ = 1, so the expected returns from s₀ are 0.8 for search and 0.2 for answer.

  1. Lemma check. With π(search)=σ(θ)\pi(\text{search}) = \sigma(\theta) at θ = 0, the scores are +0.5 for search and −0.5 for answer, and their probability-weighted sum is 0.
  2. Without a baseline, a single-sample gradient is 0.8 × 0.5 = 0.4 or 0.2 × (−0.5) = −0.1. The mean is 0.15 and the variance 0.0625.
  3. With the baseline V(s₀) = 0.5, both samples equal 0.15. The mean is the same and the variance is zero. In this two-action toy the exact baseline removes all the variance from the action choice; real tasks keep reward noise.
  4. Reward-to-go. For the trajectory search, search, answer with rewards −0.1, −0.1, +1, the full-return weights are 0.8, 0.8, 0.8; reward-to-go gives 0.8, 0.9, 1.0.
  5. For an LLM with one reward at the end, reward-to-go equals the final reward for every token, unless per-token KL penalties are folded into the reward. Per-token credit then has to come from a critic (GAE) or process rewards.
  • Frozen in 2018: no LLMs, no RLHF, no reward models, no group baselines.
  • Algorithms target continuous-control benchmarks. Token-level issues (length normalisation, sequence-level rewards, reference-model KL) are absent.
  • The PyTorch and TF1 code is educational; it is not a template for LLM-scale training.

Questions to think through

These questions have no single right answer. Write or say your answer before you open the hints. Mark a question once you could defend your answer in a reading group.

  1. Derive / compute

    In the search toy with γ = 1, let π(search|s0) = σ(θ) at θ = 0, and use the expected returns 0.8 for search and 0.2 for answer. Verify the Expected Grad-Log-Prob lemma for this policy, then compute the mean and variance of the single-sample gradient estimate with no baseline and with the baseline V(s0) = 0.5.

    What a strong answer covers
    • Scores: ∇ log π(search) = 1 − σ = 0.5 and ∇ log π(answer) = −σ = −0.5. Expected score = 0.5·0.5 + 0.5·(−0.5) = 0, which is the lemma.
    • No baseline: samples 0.8·0.5 = 0.4 or 0.2·(−0.5) = −0.1, each with probability 0.5. Mean 0.15, variance 0.5·0.16 + 0.5·0.01 − 0.0225 = 0.0625.
    • Baseline 0.5: samples (0.8 − 0.5)·0.5 = 0.15 or (0.2 − 0.5)·(−0.5) = 0.15. Mean still 0.15, variance 0.
    • The lemma is why the mean cannot change; with two actions and the exact value as baseline, the baseline removes all of the action-choice variance (reward noise would remain).
  2. Mechanism

    Spinning Up stresses that the policy-gradient "loss" in its simple PG example is not a loss function in the supervised sense. Give its two reasons, and explain what goes wrong if you minimise that "loss" for many steps on one batch.

    What a strong answer covers
    • The data distribution depends on the parameters: the batch must be sampled from the most recent policy, unlike a fixed supervised dataset.
    • It does not measure performance: its value does not approximate expected return even in expectation. Only its gradient at the current parameters, on data from those parameters, equals the performance gradient.
    • After the first step there is no connection to performance, so driving the "loss" down can make the policy much worse; the page notes it usually will.
    • This is why PPO adds an importance ratio and clipping: to make several steps on one batch meaningful.
  3. Connect

    Part 3 argues for the reward-to-go form ("Don't let the past distract you"). Compute reward-to-go weights for the toy trajectory search (−0.1), search (−0.1), answer (+1) with γ = 1. Then explain what reward-to-go buys you for an LLM that gets one reward at the end of the completion, with and without a per-token KL penalty.

    What a strong answer covers
    • Full-return weighting gives every action 0.8. Reward-to-go gives 0.8, 0.9 and 1.0: the second search is not blamed for the first search's cost.
    • With only a terminal reward, every token's reward-to-go equals the final reward, so reward-to-go alone gives no extra credit assignment.
    • With a per-token KL penalty folded into the reward (as in PPO-style RLHF), the reward-to-go differs by token and excludes penalties from earlier tokens.
    • Per-token credit beyond this needs a critic (GAE) or process rewards, which is the debate between PPO, GRPO and PRMs.
  4. Critique

    A blog post says "PPO guarantees the new policy stays within ε of the old one." Use Spinning Up's own description of PPO-Clip and its implementation to critique this.

    What a strong answer covers
    • Spinning Up states that PPO-Clip has no KL term in the objective and no constraint at all; the clip only removes the incentive to move the ratio beyond 1 ± ε.
    • The clip acts per sample. After many minibatch steps, ratios can still move outside the range because the parameters are shared across samples.
    • The implementation adds early stopping: if the estimated mean KL between new and old policy exceeds 1.5 × target_kl, policy updates stop for that epoch. With the default target_kl = 0.01 (docs suggest 0.01 or 0.05) the cutoff is 0.015.
    • So the practical "trust region" is clipping plus early stopping plus a cap on iterations (train_pi_iters = 80), not a guarantee.
  5. What if…

    Design an ablation with Spinning Up's PPO that isolates how much of its stability comes from the clip and how much from KL early stopping. Give the arms, what to log, and how you would read the outcome.

    What a strong answer covers
    • Arms: clip and early stopping (default); clip only (target_kl effectively infinite); early stopping only (clip ratio very large); neither; with train_pi_iters fixed at 80.
    • Log per epoch: mean KL to the old policy, number of policy steps actually taken before stopping, fraction of clipped samples, and return.
    • Sweep target_kl (0.01 versus 0.05) and clip_ratio (0.1, 0.2, 0.3) across several seeds.
    • If "early stopping only" matches the default, the clip contributes little in that setting; if "clip only" shows KL spikes and collapses, early stopping is doing the work.
  6. Design

    You want a weekend exercise that takes an IR student from Spinning Up Part 3 to a working policy-gradient search agent. Design it: environment, which Spinning Up pages and code to start from, the milestones, and the failure the student should be able to diagnose at the end.

    What a strong answer covers
    • Environment: the search toy as a Gym-style environment (states s0 and s1, actions search and answer), later extended with a real retriever and a correctness check.
    • Start from the simplest PG example and its reward-to-go version (pg_math 1 and 2), then switch to the VPG implementation with a value baseline and GAE.
    • Milestones: learn to search once then answer; then show the variance drop from the baseline; then compare with PPO.
    • Diagnosis: a policy that stops exploring and answers immediately (stuck in a local optimum, which the PPO page warns about for on-policy methods), detected via entropy and the search rate.

Done with this page?

Status