5.2.6Deep & Advanced RL

REINFORCE algorithm

2,038 words9 min readdifficulty · medium1 backlinks

WHAT are we optimizing?

WHY a policy directly? In continuous or huge action spaces, taking argmaxaQ(s,a)\arg\max_a Q(s,a) is hard. A parameterized policy handles stochasticity, continuous actions, and gives smooth optimization.


HOW: deriving the Policy Gradient from scratch

We want θJ(θ)\nabla_\theta J(\theta). The trouble: the expectation is over a distribution that depends on θ\theta. We can't just push the gradient inside — so we use the log-derivative trick.

Step 1 — Write the expectation as an integral over trajectories. J(θ)=pθ(τ)R(τ)dτJ(\theta) = \int p_\theta(\tau)\, R(\tau)\, d\tau Why? An expectation is just a probability-weighted sum/integral of the quantity.

Step 2 — Differentiate; gradient moves inside the integral (linear operator). θJ=θpθ(τ)R(τ)dτ\nabla_\theta J = \int \nabla_\theta p_\theta(\tau)\, R(\tau)\, d\tau Why? R(τ)R(\tau) doesn't depend on θ\theta (rewards come from the environment), only pθ(τ)p_\theta(\tau) does.

Step 3 — The log-derivative trick. Note the identity θpθ(τ)=pθ(τ)θlogpθ(τ)\nabla_\theta p_\theta(\tau) = p_\theta(\tau)\, \nabla_\theta \log p_\theta(\tau) Why? Because θlogp=θpp\nabla_\theta \log p = \frac{\nabla_\theta p}{p} — just the chain rule on log\log. Multiply both sides by pp.

Substitute: θJ=pθ(τ)θlogpθ(τ)R(τ)dτ=Eτ[θlogpθ(τ)R(τ)]\nabla_\theta J = \int p_\theta(\tau)\, \nabla_\theta \log p_\theta(\tau)\, R(\tau)\, d\tau = \mathbb{E}_{\tau}\big[\nabla_\theta \log p_\theta(\tau)\, R(\tau)\big] Why this matters: it turned a gradient-of-an-expectation into an expectation of a gradient, which we can estimate by sampling trajectories (Monte Carlo).

Step 4 — Expand logpθ(τ)\log p_\theta(\tau). The trajectory probability is pθ(τ)=ρ(s0)t=0Tπθ(atst)P(st+1st,at)p_\theta(\tau) = \rho(s_0)\prod_{t=0}^{T} \pi_\theta(a_t\mid s_t)\, P(s_{t+1}\mid s_t,a_t) Take log (product → sum): logpθ(τ)=logρ(s0)+tlogπθ(atst)+tlogP(st+1st,at)\log p_\theta(\tau) = \log\rho(s_0) + \sum_t \log\pi_\theta(a_t\mid s_t) + \sum_t \log P(s_{t+1}\mid s_t,a_t) Now differentiate w.r.t. θ\theta. The environment terms ρ\rho and PP do not depend on θ\theta, so their gradients vanish! θlogpθ(τ)=t=0Tθlogπθ(atst)\nabla_\theta \log p_\theta(\tau) = \sum_{t=0}^{T} \nabla_\theta \log \pi_\theta(a_t\mid s_t) Why this is huge: We get the gradient without knowing the transition model PP — REINFORCE is model-free.

Why GtG_t (reward-to-go) instead of full R(τ)R(\tau)? The action at time tt can only affect future rewards. Rewards earned before tt are noise as far as ata_t's credit is concerned. Dropping them keeps the estimator unbiased but lowers variance. This is causality.

Figure — REINFORCE algorithm

The baseline: variance reduction

θJ=E ⁣[tθlogπθ(atst)(Gtb(st))]\nabla_\theta J = \mathbb{E}\!\left[\sum_t \nabla_\theta \log\pi_\theta(a_t\mid s_t)\,\big(G_t - b(s_t)\big)\right]

Why is this still unbiased? For any baseline that doesn't depend on the action: Eaπ[θlogπθ(as)b(s)]=b(s)aθπθ(as)=b(s)θaπθ(as)=1=b(s)0=0\mathbb{E}_{a\sim\pi}\big[\nabla_\theta \log\pi_\theta(a\mid s)\,b(s)\big] = b(s)\sum_a \nabla_\theta \pi_\theta(a\mid s) = b(s)\,\nabla_\theta \underbrace{\sum_a \pi_\theta(a\mid s)}_{=1} = b(s)\cdot 0 = 0 So the baseline changes variance but adds zero bias. A common choice: b(st)=V^(st)b(s_t) = \hat V(s_t), giving the advantage At=GtV^(st)A_t = G_t - \hat V(s_t).


The Algorithm (Monte Carlo, episodic)

Initialize θ (policy network), optional value net for baseline
repeat:
    Sample an episode τ = (s0,a0,r0,...,sT) using π_θ
    for t = 0 ... T:
        G_t = Σ_{k=t..T} γ^{k-t} r_k          # reward-to-go
        A_t = G_t - b(s_t)                     # optional baseline
    Loss  = - Σ_t log π_θ(a_t|s_t) * A_t       # minus: grad ASCENT
    θ ← θ + α ∇_θ ( -Loss )                    # via autograd + optimizer
until converged

Why the minus sign? Optimizers minimize. We want to maximize JJ, so we minimize J-J.


Worked Examples


Common Mistakes (Steel-manned)


Active Recall

Recall Feynman: explain to a 12-year-old

Imagine training a dog with treats. You can't tell the dog exactly what to do. So you just watch: whenever it does something and then good stuff happens, you say "do that more!" and whenever bad stuff follows, "do that less!" You strengthen the moves that were followed by rewards. REINFORCE does exactly this for a computer: it makes the actions that led to lots of reward more likely, and the ones that led to little reward less likely. To be fair, it only judges an action by what happened after it (not before), and it compares to an "average day" so it can tell a genuinely good move from just a lucky day.


Flashcards

What is the REINFORCE objective J(θ)J(\theta)?
The expected return under the policy, J(θ)=Eτπθ[R(τ)]J(\theta)=\mathbb{E}_{\tau\sim\pi_\theta}[R(\tau)].
State the REINFORCE policy-gradient formula.
θJ=E[tθlogπθ(atst)Gt]\nabla_\theta J = \mathbb{E}\big[\sum_t \nabla_\theta\log\pi_\theta(a_t\mid s_t)\,G_t\big].
What is the log-derivative trick?
θp=pθlogp\nabla_\theta p = p\,\nabla_\theta\log p, used to turn a gradient-of-expectation into an expectation-of-gradient.
Why is REINFORCE model-free?
In θlogpθ(τ)\nabla_\theta\log p_\theta(\tau) the transition terms P(ss,a)P(s'|s,a) and start-state ρ\rho don't depend on θ\theta, so they vanish; only tθlogπθ(atst)\sum_t\nabla_\theta\log\pi_\theta(a_t|s_t) remains.
What is GtG_t (reward-to-go) and why use it?
Gt=ktγktrkG_t=\sum_{k\ge t}\gamma^{k-t}r_k; using it (instead of full return) drops causally-irrelevant past rewards, lowering variance while staying unbiased.
Why does subtracting a baseline b(s)b(s) not bias the gradient?
Because Ea[logπb(s)]=b(s)θaπθ(as)=b(s)θ1=0\mathbb{E}_a[\nabla\log\pi\cdot b(s)] = b(s)\nabla_\theta\sum_a\pi_\theta(a|s)=b(s)\nabla_\theta 1 = 0.
What is the advantage AtA_t?
At=GtV^(st)A_t = G_t - \hat V(s_t): how much better an action's return was than the state's average.
Why the minus sign in the REINFORCE loss?
Optimizers minimize; we want to maximize JJ, so we minimize tlogπθ(atst)At-\sum_t\log\pi_\theta(a_t|s_t)A_t to perform gradient ascent.
Main weakness of vanilla REINFORCE?
High variance (Monte-Carlo returns) and sample inefficiency; needs baselines / Actor-Critic to help.

Connections

  • Policy Gradient Methods — REINFORCE is the foundational instance.
  • Actor-Critic Methods — replaces Monte-Carlo GtG_t with a learned critic (baseline + bootstrapping).
  • Advantage FunctionAt=GtV(st)A_t=G_t-V(s_t) used as the weighting.
  • Value Function V(s) — a natural baseline choice.
  • Monte Carlo Methods — REINFORCE returns are full-episode MC estimates.
  • Log-Derivative Trick — the core mathematical identity.
  • Softmax Policy / Gaussian Policy — common parameterizations of πθ\pi_\theta.
  • Variance Reduction in RL — baselines, reward-to-go, control variates.

Concept Map

maximizes

gradient needs

converts to

estimated by

requires

since P not on theta

implies

yields

feeds

used to

improves

Parameterized policy pi_theta a given s

Objective J theta max expected return

Log-derivative trick

Expectation of a gradient

Monte Carlo sampling of trajectories

Expand log p_theta tau

Env terms rho and P drop out

Model-free

REINFORCE gradient

Nudge theta to raise good actions

Hinglish (regional understanding)

Intuition Hinglish mein samjho

Dekho, REINFORCE ka core idea bahut simple hai: hum directly ek policy πθ(as)\pi_\theta(a|s) seekhte hain — yaani neural net batata hai ki kis state mein kaunsa action lene ka probability kitna ho. Value function ka jhanjhat nahi, seedha action ki probability tune karte hain. Rule ek line mein: jo action ke baad zyada reward mila, uski probability badha do; jiske baad kam reward mila, uski ghata do. Bilkul kutte ko treat dekar train karne jaisa.

Ab maths thoda: hum J(θ)=E[R(τ)]J(\theta)=\mathbb{E}[R(\tau)] ko maximize karna chahte hain, lekin expectation khud θ\theta pe depend karta hai. Yahan log-derivative trick kaam aata hai — p=plogp\nabla p = p\,\nabla\log p — isse gradient-of-expectation, expectation-of-gradient ban jaata hai jise hum trajectories sample karke estimate kar sakte hain. Jab hum logpθ(τ)\log p_\theta(\tau) ko todte hain, toh environment ke transition terms P(ss,a)P(s'|s,a) ka θ\theta se koi lena-dena nahi, isliye woh zero ho jaate hain. Result: sirf tlogπθ(atst)Gt\sum_t \nabla\log\pi_\theta(a_t|s_t)\,G_t bachta hai — matlab model-free, environment ka model jaanne ki zaroorat hi nahi!

Do practical baatein yaad rakho. Pehli: reward-to-go GtG_t use karo (action ke baad wala reward), kyunki action apne se pehle wale reward ke liye responsible nahi — isse variance kam hota hai bina bias aaye. Doosri: ek baseline b(s)b(s) (jaise V(s)V(s)) minus kar do, taaki signal center ho jaaye — "average se accha tha ya bura?" Ye baseline gradient ko biased nahi karta (proof: b(s)aπ=b(s)0b(s)\nabla\sum_a\pi = b(s)\cdot 0), sirf variance calm karta hai. Aur haan — code mein minus sign lagana mat bhoolna, kyunki optimizer minimize karta hai par humein JJ maximize karna hai (gradient ascent).

Go deeper — visual, from zero

Test yourself — Deep & Advanced RL

Connections