Unit 2 of 11 · about 4 hours · derive

The score-function gradient for language trajectories, baselines and variance

The earlier REINFORCE derivation becomes a research tool here: it supplies an oracle for the language loss, and exposes normalization changes that no longer estimate the raw-reward gradient.

You'll be able to

  • Derive the completion-only score-function gradient for a fixed prompt distribution and parameter-independent reward.
  • Check baseline bias and variance by exact enumeration before trusting a language-model learning curve.
  • Translate the estimator into a detached-reward loss with independently checked token masks.

Covers

Score-function policy gradient for language trajectoriesBaselines, leave-one-out estimators and variance reduction
1

Read

In this order, only the parts listed

0 of 2 done

  1. CS336 Spring 2026 Assignment 5: gradient and baseline auditCS336 Assignment 5 - Alignment and Reasoning RL

    Sections 4.1.4 and 4.1.5, including baseline_calcs; Section 4.2.3, compute_policy_gradient_loss_on_policy

    Use the earlier policy-gradient units for prerequisite repair only. Spend this pass on the language loss and the baseline counterexample.

  2. RLHF Book Chapter 6: Reinforcement LearningRLHF Book - Policy Gradients, Reasoning and Rejection Sampling

    Deriving the Policy Gradient through REINFORCE Leave One Out (RLOO)

2

Focus on

  • For fixed prompts and rewards, . Sum only sampled completion actions, including sampled EOS.
  • Hold sampled IDs, rewards and baselines fixed during differentiation. Current selected log probabilities carry gradients; generated text need not be differentiable.
  • An action-independent baseline preserves the expected score-function gradient, but need not reduce variance. The reward mean is not generally the variance-minimizing baseline.
  • An inclusive group mean depends on the current completion. With independent siblings and no standard-deviation scaling, it shrinks the expected raw-reward gradient by .
Common mistakes · 3
  • Differentiating the sample-average reward directly. A detached discrete reward has no path through the sampled tokens; use the score-function loss.
  • Replacing the sum of token log probabilities with a response mean. Variable lengths then change the estimator, not just its numerical scale.
  • Calling all centering unbiased. Sibling dependence, inclusive means and random standard-deviation division require separate analysis.
3

Try it yourself

Closed-book, before checking anything

Derive baseline_calcs symbolically first, then check your expressions by enumeration on CPU. For a Bernoulli action with success probability , reward equal to the action and logit score , the single-sample estimator has mean 0.16. Its variance is 0.0064 with baseline 0, 0.0576 with baseline 0.8, and zero with baseline 0.2. Recover these values in float64; divide variance by the number of independent samples for a sample mean.
4

Quiz yourself

Answer first, then mark it. Missed ones go to Review.

0 got · 0 missed

  1. 1.Why does subtracting a fixed prompt-only baseline preserve the expected gradient?Answer

    Conditioned on the prompt, the expected policy score is zero, since the derivative of total probability 1 is zero.

  2. 2.Does a lower variance of raw rewards guarantee a lower variance of the gradient?Answer

    No. Gradient variance also depends on policy scores and their correlation with rewards. The reproduce example gives a counterexample to using the mean-reward baseline.

  3. 3.What changes if the reward itself depends differentiably on policy parameters?Answer

    The derivative also has an expected reward-derivative term. The fixed-verifier derivation assumes that term is absent.

5

Practice

  • CS336 Assignment 5: baseline_calcs and compute_policy_gradient_loss_on_policy

    Section 4.1.5, baseline_calcs parts (a) to (c); Section 4.2.3 with test_compute_policy_gradient_loss_on_policy

    The public test compares loss values with a snapshot; add your own selected-log-probability gradient and padding-invariance tests. Use public handouts and tests privately as study material; do not publish assignment solutions.

You're done when

Your baseline variance derivation agrees with exact enumeration, the on-policy loss snapshot passes, and your own test detects an included prompt token or a differentiated baseline.

Only when you can do this without notes.

Leads to

Notes

Resources · 2 for this unit, 18 more in the section
  • CS336 Assignment 5 - Alignment and Reasoning RLStanford University · primary

    Do Sections 3 to 5: prompting and grading baselines, baseline_calcs, then the Section 4.2 functions (tokenization, response log probabilities, rollout rewards, group-normalized rewards, loss aggregation, the on-policy GRPO step) until the GRPO and metrics tests pass on CPU. The handout runs OLMo-2 1B with a two-GPU vLLM loop; run a small GRPO on a model and task that fit your GPU instead, with one normalization ablation and one preserved failure.

  • RLHF Book - Policy Gradients, Reasoning and Rejection SamplingNathan Lambert · required

    Read Chapter 6 (policy gradients: REINFORCE, RLOO, PPO, GRPO and loss aggregation), Chapter 7 (reasoning), Chapter 9 (rejection sampling), Chapter 12 (distillation) and Chapter 15 (regularization). Do the Suggested Experiments in Chapters 6 and 9. Derive only the estimator used in your experiment, then use Chapters 14 and 15 to design the reward-hacking tests.

Also in this section