Policy gradients (REINFORCE) and baselines
For a policy π that samples actions a and then receives a reward R, derive ∇E[R] = E[R ∇log π(a)] and turn it into a sampled update. Explain why subtracting a baseline from R reduces variance without adding bias.
Builds on: Gradient descent and the learning rate, From base model to assistant
What the animation says
A gradient through a dice roll?
In reinforcement learning, the model rolls a die: it samples an action, say a token, from its policy. Then a black box scores it: a test suite, or a human rating. We want to climb the expected reward with gradient ascent. But you can't differentiate through 'pick option three', or through the grader. So where does a usable gradient come from?
Push up what you sampled
Here's the idea: try an action and look at its reward. Then nudge the parameters so that action becomes more likely, in proportion to how good it was. The gradient of the log probability is exactly that direction: it raises this action's chance. Two actions, A and B, start at fifty-fifty. A pays eleven, B pays nine. We sample B and step by nine times its arrow. What happens to B's probability?
The log-derivative trick
B went up. Every positive reward pushes its sample up. The math agrees. Expected reward is a sum over actions of probability times reward. The reward doesn't depend on the parameters, so the gradient lands only on the probability. Multiply and divide by the probability. Gradient of pi over pi is the gradient of log pi. So the sum becomes an average over samples: reward times the gradient of log probability. In practice: sample a few actions and step along that average, scaled by the learning rate.
Subtract a baseline, for free
Only relative quality matters, so subtract a baseline: a typical reward. Each sample is now scaled by reward minus baseline. Below the baseline, that factor is negative, and the action is pushed down. Does this bias the average? The extra term is b times the sum of the gradients of the probabilities. That's b times the gradient of one, which is zero. But that only works if b can be pulled out of the sum. Which of these may the baseline depend on?
Two actions, one parameter
Right: anything fixed before sampling, like the prompt. Never the sampled action. Now see why it helps. One parameter, starting at zero: A and B are fifty-fifty. A's log-gradient is plus a half, B's is minus a half. The true gradient is a half. With no baseline, an A sample gives five and a half, a B sample gives minus four and a half, pointing the wrong way. Variance: twenty-five. Drag the baseline until every sample gives the true gradient.
Make good samples more likely
The REINFORCE gradient
Why a baseline adds no bias
Two actions, one parameter
Remember this
On Bytewise this lesson comes in small steps with a check at the end, and the app brings it back right before you would forget it.
Bytewise
All courses