RL for LLMs, Part I: From REINFORCE to the Policy Gradient Theorem - Derive Everything Yourself
Deriving policy gradients through exercises
When I was studying different areas of mathematics, my favorite thing was to try proving results myself, step by step, before reading their proofs. Doing this forced me to confront details I would otherwise have missed while reading a textbook, and often led to new insights. It also felt weirdly satisfying, like you really accomplished something! This post is an attempt to compile from different sources a set of intermediate results that allows me and reader to derive everything from first principles.
Of course, I couldn't always prove a result in one go and so I would usually try to find a staircase of lemmas / smaller results, each giving me something I needed for the next step, until the final "aha" moment of getting to the result. The steps had to be manageable enough that I could make progress, but challenging enough to keep me engaged and allow me to learn (tbh, after writing this I thought that this specific complexity requirement sounds very much similar to task complexity you would want in RL methods)
In this post, step by step, we will get to two points:
Derive REINFORCE and its several variants.
Connect the REINFORCE derivation to the policy gradient theorem.
The goal is to rederive each result yourself. I will split the derivation into small directed graph of results: you can prove them, open a hint, or read the worked solutions. Gradually you will derive most of the results necessary for understanding policy gradient methods. The only prerequisites for this post are probably Chapter 3 of Sutton and Barto (not even the whole chapter, but understanding of environment, policy, rewards and return), basic probability theory and intro to multivariate calculus.
This is the first part of a series in the second part we will connect derivations here to RL for training LLMs and will go over RLOO, ReMax, GRPO, and FlashREINFORCE.
Setup: trajectories and expected return
In reinforcement learning, a trajectory comes from the actions an agent takes and the responses of its environment. At time $t$, the agent observes $s_t$ and samples $a_t$ from its policy $\pi(a_t\mid s_t)$. The environment then produces a reward $r_{t+1}$ and next state $s_{t+1}$ according to $P(s_{t+1},r_{t+1}\mid s_t,a_t)$.
In this post, we consider episodic tasks, assuming that each episode has finite fixed trajectory length of T - to be honest this is a significant simplification and while episodes terminating earlier can be handled by introducing absorbing state that has zero rewards, the same machinery can't handle case of arbitrary length episodes, for that we need treat $T$ as a random variable (essentially stopping time), but that is outside of the scope of this post. In practice though, REINFORCE also applies to episodes of varying length. We consider a trajectory itself to be just a sequence of states, actions, and rewards, each one of them being a random variable:
Let $\mathcal S$, $\mathcal A$, and $\mathcal R$ denote the state, action, and reward spaces, then trajectory space is just cartesian product space of random variables.
A sampled trajectory is a random vector in $\Omega$, and $\tau$ denotes realization of that random variable. Each trajectory has return $R(\tau)$ obtained along the trajectory, that return is just discounted sum of rewards
$$R(\tau)=\sum_{t=0}^{T-1}\gamma^t r_{t+1}$$
where $0 < \gamma < 1 $ is the discount factor and $r_{t+1}$ is reward obtained during transition to state $s_{t+1}$, we assume that rewards are uniformly bounded i.e. $\exists R_{\max}<\infty:\ \forall r\in\mathcal R,\ |r|\le R_{\max}$.
In addition to uniform bound on rewards we make following three assumptions:
A Markov decision process (MDP), using Sutton and Barto’s joint next-state and reward formulation, with environment dynamics fixed as we vary $\theta$.
A stationary Markov policy.
An initial-state distribution $p_0$ that does not depend on policy.
Let’s express these assumptions in probability notation, if we define $h_t=(s_0,a_0,r_1,\ldots,s_t)$, which is just trajectory until state at time $t$ (i.e. history until $s_t$). Then
MDP, or more concretely Markov property of environment is just $P(s_{t+1},r_{t+1}\mid h_t,a_t)=P(s_{t+1},r_{t+1}\mid s_t,a_t).$
Initial state distribution is defined by fixed distribution $p_0(s_0)$
Optimization objective
In comparison to action value methods like Q-learning and SARSA, where policy is downstream of estimating action value function in policy gradient methods policy is optimized directly. Here we assume that policy is some parameterized probability distribution $\pi_{\theta}(a_t | s_t)$ and we are trying to find policy that maximizes expected return under trajectories generated by that policy.
This formulation implies that now trajectory probability also depends on the parameters $\theta$ as well $p_{\theta}(\tau)$.
To differentiate this objective under the integral sign, we make the following regularity assumptions.¹
We will make an assumption that $\pi_{\theta}(a_t | s_t)$ is differentiable in $\theta$. And also gradient of probability distribution of trajectory with respect to params is bounded by an integrable function everywhere in $B_{\epsilon}(\theta)$:
Use $\nabla_\theta p_\theta=p_\theta\nabla_\theta\log p_\theta$.
Proof
Starting from the objective,
$$\begin{aligned}
\nabla_\theta J(\theta)
&=\nabla_\theta\int_\Omega p_\theta(\tau)R(\tau)\,d\tau\\
&=\int_\Omega \nabla_\theta p_\theta(\tau)R(\tau)\,d\tau\\
&=\int_\Omega p_\theta(\tau)\nabla_\theta\log p_\theta(\tau)R(\tau)\,d\tau\\
&=\mathbb E_{p_\theta(\tau)}[\nabla_\theta\log p_\theta(\tau)R(\tau)].
\end{aligned}$$ You might notice that this exchange of order between integration and gradient taking requires assumption, first $\int_\Omega p_\theta(\tau)R(\tau)\,d\tau$ should exist, which is guaranteed by our assumption of bounded rewards and finite horizon. Then $\mathbb E_{p_\theta(\tau)}[\nabla_\theta\log p_\theta(\tau)R(\tau)]$ should exist which is guaranteed by both uniform boundedness of rewards (combined with finite horizon) and by assumption that norm of gradient for trajectory probability is bounded by integrable function.
Use the Markov property of the policy and the Markov property of the environment separately.
Proof
Let $h_t=(s_0,a_0,r_1,\ldots,s_t)$ represent the part of the trajectory before action $a_t$. This is the same definition we gave earlier in the post. By factorizing the joint distribution into conditional distributions, we get
The Markov policy gives $p_\theta(a_t\mid h_t)=\pi_\theta(a_t\mid s_t)$. The MDP assumption results in $p_\theta(s_{t+1},r_{t+1}\mid h_t,a_t)=P(s_{t+1},r_{t+1}\mid s_t,a_t)$. Applying these assumptions, it is easy to see that $h_t$ can be substituted by $s_t$ and we recover formula in proposition 2.
Substitute this result into Proposition 1 and you will get the expression for REINFORCE with full return.
The way this would work in implementation is that we sample multiple trajectories from the current policy and compute the return of each. For each trajectory, we sum the gradients of the log-policy probabilities at every action step with respect to the parameters. Multiplying that sum by the trajectory’s return and averaging across trajectories gives us an unbiased estimate of the gradient of expected return. We can then use this estimate to take a gradient-ascent step. The estimate from a single trajectory is
Here $k$ indexes training iterations, $\alpha_k>0$ is the learning rate, and all gradients are evaluated at the parameters used to sample the trajectories.
The main intuition is easy to see: if a trajectory has positive return, the gradient update pushes toward making that trajectory more likely by reinforcing the actions taken in the states visited. Note the higher the return, the stronger the reinforcement for the same log-probability gradient, meaning we would expect that actions from states in the current trajectories will increase likelihood!
Now there are a couple of interesting things to observe:
This can reinforce actions that did not contribute to the return. Imagine all rewards were accumulated by step 10 of the trajectory, and all later rewards are zero. Should the action at step 11 receive any reinforcement for those earlier rewards? With full-return REINFORCE, it still does and this creates unnecessary credit assignment problem. In fact more than that, what could happen, is that because earlier steps are so successful, through multiplication on full-return you might reinforce poor continuation!
Remember each reward is a random variable and when we include past rewards, those that simply cannot be affected by the current action, we can introduce extra noise into the gradient estimate. Removing them often reduces variance (though it is not guaranteed to do so in every case).
Is there a way to at least partially alleviate credit-assignment problem and also potentially decrease variance?
REINFORCE with reward-to-go
In this section we will try to simplify REINFORCE with full return, but before that we are going to prove a very important intermediate result that will come in handy in several other subsections, this is relatively simple and straightforward, but important part of the puzzle.
If we take any random time step $t$ within trajectory, trajectory can be viewed as consisting of 3 parts:
history of trajectory (you already saw this applied in multiple parts of this blog): $h_t$
That means that trajectory probability, which as we defined is just joint probability of actions, states and rewards, can be factorized using these 3 variables and then by applying markov policy assumption simplified:
One more concept that will come in handy is filtration. Let $H_t=(S_0,A_0,R_1,\ldots,S_t)$ be the random history, with realization $h_t$. We can write $\mathcal F_t=\sigma(H_t)$ for all the information available from this history, before choosing $A_t$. As we observe more of the trajectory, this information grows:
A random variable $X$ is measurable with respect to $\mathcal F_t$ if knowing the history $H_t$ is enough to determine its value. For example, the total reward already collected is $\mathcal F_t$-measurable, but the next reward generally is not. Another example - let's write $X=f(H_t)$ for a measurable, deterministic function $f$, $X$ is still random because the history is random. But once we observe $H_t=h_t$, its value is fixed: $X=f(h_t)$, this is why we can treat $X$ as fixed when conditioning on the $\mathcal F_t$.
Note, since we defined $\mathcal F_t=\sigma(H_t)$, conditioning on $H_t$ is the same as conditioning on $\mathcal F_t$.
Proposition 3. Let $C_t$ be an $\mathcal F_t$-measurable random variable, assuming the product below is integrable:
Note neither $C_t$, nor $\nabla_\theta\log\pi_\theta(a_t\mid s_t)$ depend on $f_t$, meaning they can be treated as constants with respect to conditional distribution $p_{\theta}(f_t \mid a_t, h_t)$, this means we can integrate $f_t$ out. The same argument about $C_t$ can be made when we are considering the conditional distribution $\pi_{\theta} ( a_t \mid s_t)$, since $h_t$ is held fixed there.
Hence $\mathbb E_{p_\theta(\tau)}\left[C_t\nabla_\theta\log\pi_\theta(A_t\mid S_t)\right]=0$. Insight definitely worth remembering here is that $C_t$ doesn't need to be statistically independent of the action - it only needs to be fixed when we fix the history before that action (i.e. measurable with respect to the filtration $\mathcal F_t$).
Note, if you derived proposition 3, it should also be clear that $\mathbb E_{p_\theta(\tau)}\left[C_t\nabla_\theta\log\pi_\theta(A_t\mid S_t)\right] = 0$ is not generally true if $C_t$ is measurable with respect to $\sigma(H_t, A_t)$ - this would be an important corollary for understanding several RL methods (including RLOO).
We can now apply Proposition 3 to full-return REINFORCE: the accumulated past reward is determined by the history, so its contribution to the expected gradient is zero.
Notice how gradient ascent now reinforces actions taken in the observed states according to the return that follows those actions, not the full trajectory return. Rewards received before an action no longer contribute to reinforcing it. In addition to that we might be getting rid of additional noise in gradient estimation, while still keeping gradients unbiased.
REINFORCE with a baseline
Another way we can use proposition 3, is that we can show that if we subtract any quantity that is determined by information before choosing the action at time $t$ (i.e. measurable with respect to $\mathcal F_t$), we still get unbiased estimate of gradient. Usually the quantity we subtract is called baseline
Let's start with a $B_t$, that is $\mathcal F_t$-measurable.
Using linearity of expectations it is easy to see that every term containing $B_t$ is zero and we reduce the expression to rewards-to-go version of REINFORCE.
Baselines are usually used to reduce variance, but we will not explore that in detail here. Instead, we will show how the results we have derived extend naturally to different choices of baseline.
One popular baseline is the policy’s value function, $V_{\pi_\theta}(S_t)$, which gives the expected remaining return from the current state under the current policy. Since $S_t$ is $\mathcal F_t$-measurable and the true value function is fixed for a given policy and time step, $V_{\pi_\theta}(S_t)$ is also $\mathcal F_t$-measurable, which means we can just reuse the baseline result we derived above.
This section explores another reformulation of REINFORCE through its relationship with action-value functions. Using our trajectory-distribution notation, we write Sutton's definition as follows.²
Start from REINFORCE with reward-to-go. At each time step, integrate out the future while holding the history and current action fixed. Use the Markov environment and policy to identify the conditional expected return, then sum over $t$ with weights $\gamma^t$.
The inner integral no longer gives one: it averages the return over possible futures. Under our Markov assumptions (environment & policy), the distribution of the future, at this fixed time, depends on the history only through $s_t$ and $a_t$. Therefore,
We have reorganized an expression for the gradient. We have not taken a new derivative of an objective containing $Q_{\pi_\theta}$, so there is no additional derivative of $Q_{\pi_\theta}$ here.
REINFORCE so far: bookkeeping of different flavors
Let us just connect the dots on all of the different flavors of REINFORCE we derived. Each node shows its gradient formula, and each arrow shows the transformation connecting the results.
The only new form we introduced is advantage form, which is just combination of baseline and action value forms and is very straightforward to obtain.
The policy gradient theorem
REINFORCE and Policy Gradient Theorem are easy to connect into cohesive picture, but I rarely see them clearly connected in the literature, we will try to do that.
As in Sutton and Barto’s Chapter 13, we use a stationary (Markov) policy: for fixed $\theta$, the same state gives the same action distribution $\pi_\theta(a\mid s)$ at every time step. In a standard batch implementation of REINFORCE, we collect multiple trajectories with the parameters held fixed, estimate the policy gradient using the appropriate return or baseline-adjusted return, and then update $\theta$. Thus, the policy changes between learning updates, while each batch is collected using one fixed policy. Stationarity additionally means that this policy does not depend explicitly on the time step (note that doesn't necessarily mean that time will not be rolled into state). This also applies to standard autoregressive LLM generation, where the LLM acts as the policy and the current prefix is the state: with model parameters and sampling settings fixed, the same prefix gives the same next-token distribution.
We can formalize this, requiring for any $t,k < T$,
There is one subtlety (I missed it! but Astra noticed during the review) with our fixed horizon: even under a stationary policy, the value of state-action combination can possibly depend on how many steps remain until horizon $T$. In the derivations below we make assumption it doesn't, i.e. for any $$s_t=s_k,\quad a_t=a_k\quad\Longrightarrow\ Q_{\pi_{\theta}}(a_t, s_t)=Q_{\pi_{\theta}}(a_k, s_k).$$ To be clear for time-homogeneous environments and stationary policies this is satisfied for random termination episodic case, but it is not truly guaranteed in our case.⁴
Note $S_t$ takes values in the same state space $\mathcal S$, and $A_t$ in the same action space $\mathcal A$, so when we integrate over $s_t$ and $a_t$ it means integrating over $\mathcal S$ and $\mathcal A$ ($s_t$ and $a_t$ are dummy vars). Schematics below shows intuition on how we can transition from summing over time and then integrating to marginalizing across time steps.
Let $d_t^{\pi_\theta}(s)$ denote the marginal density of $S_t$ at $s$ (for discrete states, $d_t^{\pi_\theta}(s)=\Pr(S_t=s)$). The time step is part of the function $d_t^{\pi_\theta}$, not of its argument: the same state $s$ generally has a different density at each time step. If we define:
The best way to look at it to get intuition is that for $\gamma=1$ and discrete case it is just expected number of visits to a state $s \in \mathcal S$.
Proposition 5: From time steps to state visitation. Assume $\mathbb E[\|f(S_t)\|]<\infty$ for every $t$. Then
Every integral is over the same space $\mathcal S$. Renaming the integration variable $s_t$ to $s$ leaves each time step's density $d_t^{\pi_\theta}$ unchanged:
Here $a$ is a dummy variable ranging over the same action space at every time step. With our stationary policy and time included in the state when needed, $f$ has no separate dependence on $t$. Thus,
In this post we derived foundations of policy gradient methods and in the next post we will try to map the concepts we learned here (in a more classical RL setting) into RL for LLMs.
¹ These are sufficient conditions chosen to keep the derivation simple, rather than necessary conditions. ↩
² Sutton and Barto write $\mathbb E_{\pi_\theta}$ for expectation when following policy $\pi_\theta$ in the environment. The policy, environment dynamics, and initial-state distribution together induce our trajectory distribution $p_\theta(\tau)$. Thus $\mathbb E_{p_\theta(\tau)}[G_t\mid S_t=s,A_t=a]$ and $\mathbb E_{\pi_\theta}[G_t\mid S_t=s,A_t=a]$ denote the same conditional expectation, including both policy and environment randomness. See Chapter 3. ↩
³ In our fixed-horizon episodic setting, this notation implicitly includes the time step in the state. The same underlying state-action pair can have different values depending on how many steps remain before the terminal time $T$. Including time in the state lets us write $Q_{\pi_\theta}(s,a)$ without a separate time index. ↩
⁴ Including the time step in the state makes these results applicable to fixed-horizon problems. However, visits to the same underlying state at different times now count as visits to different augmented states. The visitation formulation remains valid, but it no longer combines those visits into a single weight for the underlying state. ↩