5.2.6 · D2Deep & Advanced RL

Visual walkthrough — REINFORCE algorithm

2,253 words10 min readBack to topic

Prerequisite trails, if a symbol here feels unfamiliar: Policy Gradient Methods, Log-Derivative Trick, Monte Carlo Methods, Value Function V(s), Advantage Function.


The characters (define every symbol before we use it)

Before Step 1, meet the cast. Nothing below is used until it appears in a picture.

Two more characters belong to the environment (the world), not to us — they carry no dials and we will meet them again in Step 5:

Our whole quest: find — the arrow telling us which way to turn the dials to earn more reward.


Step 1 — See the landscape we are climbing

WHAT. Picture the dials as a flat floor. Above each spot on the floor, the height is — how much reward that dial-setting earns on average. This makes a hill.

WHY. "Maximize " is now just "walk uphill." The gradient is the compass that points straight up the slope from wherever we stand. Everything after this step is a fight to compute that compass arrow — because the hill's height involves an average over random games, we cannot read the slope directly.

PICTURE. The green surface is . The black dot is our current . The orange arrow is , the uphill direction we are hunting for.

Figure — REINFORCE algorithm

Step 2 — Why we can't just differentiate the average

WHAT. Write the average out honestly. An average over games is a probability-weighted sum over all possible games:

WHY. is just "add up over every possible game, weighting each by how probable it is." Here is the catch that motivates the whole trick: the weights themselves depend on our dials . Turning a dial doesn't only change the reward of a fixed game — it changes which games happen. So the slope has two intertwined effects, and a naive derivative gets tangled.

PICTURE. Bars = possible games. Bar height = reward . Bar width = probability . is the shaded area. When we turn a dial, the widths shift — that's the hard part.

Figure — REINFORCE algorithm

Step 3 — Move the gradient inside the sum

WHAT. The gradient of a sum is the sum of the gradients (differentiation is linear — it distributes over addition). And has no in it (rewards are decided by the environment, not our dials). So only the widths get differentiated:

WHY. This isolates the entire difficulty into one object: , "how fast does game 's probability grow as we turn the dials." If we can rewrite that as something we can sample, we win.

PICTURE. Same bars as Step 2, now with small arrows on each bar showing which way its width is changing as nudges. Heights (rewards) stay frozen.

Figure — REINFORCE algorithm

Step 4 — The log-derivative trick: turn "gradient of probability" into "probability × gradient of log"

WHAT. Use the identity (proven in Log-Derivative Trick):

WHY this exact tool, not another? We want an expectation — a shape — because expectations can be estimated by sampling (play games, average). Right now we have , which is not in that shape: there is no clean multiplying a bracket. The identity manufactures that missing out front. Where does the identity come from? Calculus: , so ; multiply both sides by . That's it.

Substitute and the shape appears:

PICTURE. Left box: the tangled form . A labelled arrow "×1 in disguise: multiply and divide by ". Right box: the clean , tagged "now it's an average — samplable!"

Figure — REINFORCE algorithm

Step 5 — Crack open : the environment vanishes

WHAT. A game's probability is a chain of two kinds of factors — our choices and the world's own pieces (the initial-state distribution and the transition kernel , both defined in "The characters" above): Take (a product becomes a sum, because ):

WHY. Now differentiate w.r.t. . The start-state term and every world-response contain no — the environment doesn't care about our dials. Their gradients are exactly zero. Only our own choices survive: This is the punchline that makes REINFORCE model-free: we never need to know the world's physics .

PICTURE. The chain of factors laid in a row. Blue tiles = (kept). Gray tiles = (crossed out, "no inside → gradient 0").

Figure — REINFORCE algorithm

Plugging back gives the raw REINFORCE gradient:


Step 6 — Causality: replace with reward-to-go

WHAT. Inside the sum, each term is currently multiplied by the whole-game reward . Replace it with only the reward that comes at or after time :

WHY. An action cannot reach back in time and change rewards that already happened. Those past rewards contribute zero on average to 's gradient term — they are pure noise. Dropping them keeps the gradient's direction identical in expectation while shrinking its random jitter (its variance). This is the causality argument; more on why lowering variance matters in Variance Reduction in RL.

PICTURE. A timeline. For action (blue), rewards before it are grayed out ("can't affect these"), rewards from onward are orange and summed into .

Figure — REINFORCE algorithm

Step 7 — From a true average to a sample estimate (Monte Carlo)

WHAT. We can't compute the exact average (infinitely many possible games). So we play games and average — the Monte Carlo idea:

WHY. Step 4 was worth all its effort precisely so we could reach this line: an average over sampled games is directly computable. More games → the noisy estimate settles onto the true gradient.

PICTURE. Three sampled trajectories, each producing its own ; the three arrows average into one (bold) estimate of .

Figure — REINFORCE algorithm

Step 8 — Degenerate & edge cases (the ones people trip on)

WHAT & WHY & PICTURE, four situations the formula must survive:

  1. All returns large & positive (e.g. every ). Then every is pushed up — good and bad actions alike. Learning crawls. The fix is a baseline : use so the signal becomes "better or worse than average." Because , the baseline adds zero bias. Choosing (see Value Function V(s)) turns into the advantage , the bridge to Actor-Critic Methods.
  2. Zero return, . That action's term contributes nothing — neither pushed up nor down. Correct: no evidence, no update.
  3. Deterministic-ish policy, . Then and : the gradient dries up. This is why we keep policies stochastic during training (e.g. entropy bonuses) — a fully confident policy stops learning.
  4. Sign of the update. Optimizers minimize, but we want to maximize . So we code the loss as ; minimizing ascends . Forget the minus and you climb downhill.
Figure — REINFORCE algorithm

The one-picture summary

Everything above, compressed: from the hill (Step 1), through the log-trick reshaping (Step 4), the environment cancelling (Step 5), causality trimming to (Step 6), and Monte-Carlo sampling (Step 7) — landing on the boxed gradient and the ascent update.

Figure — REINFORCE algorithm
Recall Feynman: retell the whole walkthrough in plain words

We want to turn some dials so a game pays out more on average. The trouble: turning a dial changes which games happen, so we can't just read the slope. The log-derivative trick rewrites "how the game-probabilities shift" as "the probability of the game times how the log-probability shifts" — and that magic reshaping makes the whole thing an average, which we can estimate just by playing games and averaging. When we open up a game's probability, it's our choices multiplied by the world's responses; the world's part has none of our dials in it, so it disappears when we take the gradient — that's why we never need to know how the world works. Then causality says: judge each move only by what happened afterward (), never before. Finally, play games, average the "nudge each action by how much reward followed it," and step the dials that way. Add a baseline (the average day) so we push good moves up and bad moves down instead of pushing everything up. Mind the minus sign, because the optimizer walks downhill and we want up.


Active Recall

Recall Why is the log-derivative trick used at all?

To turn — which is not an average — into , which is an average and can be estimated by sampling games. ::: It manufactures the missing factor so the integral becomes an expectation.

Recall Which terms of

survive the gradient, and why? Only . ::: The start-state and transition contain no , so their gradients are zero → REINFORCE is model-free.

Recall Why replace

with ? Because an action can't change past rewards; those contribute zero in expectation. ::: Dropping them keeps the direction unbiased and lowers variance (causality).

Recall Does subtracting a baseline

change the gradient's expected value? No. ::: — zero bias, only variance shrinks.