Article

Fundamentals of Reinforcement Learning

#RL
On this page 9

Background

Markov

Markov chains and Markov decision processes

In a Markov decision process, taking an action leads to a new state and a reward: st→atst+1,rts_t\xrightarrow{a_t}s_{t+1},\quad r_t.

Typical applications include:

  • Game decisions
  • Robot control
  • Autonomous driving

In all these problems, an action affects both the next decision and outcomes further into the future. Reinforcement learning was originally developed to learn how to make such sequential decisions.


How Reinforcement Learning Works

In state sts_t, the agent chooses an action aa in an environment and moves to a new state st+1s_{t+1}. The environment assigns a reward rtr_t to the transition. Reinforcement learning uses that reward to update the model that makes decisions.

A few more definitions:

  • Q(s,a)Q(s,a): the expected return from taking action aa in state ss.

  • τ=(s0,a0,r0,⋯ )\tau=(s_0,a_0,r_0,\cdots): a trajectory spanning multiple steps.

  • GtG_t: the long-term return from time tt, given by (rt+γrt+1+γ2rt+2+⋯ )(r_t+ \gamma r_{t+1} + \gamma^2 r_{t+2} + \cdots). The discount factor γ\gamma gives less weight to more distant rewards.


Three Main Families of RL Methods

Reinforcement learning methods fall into three broad families depending on what they learn:

  • Value-based
  • Policy-based
  • Actor-Critic

Value-based

We train a scoring model that takes ss and aa and returns QQ. An interesting feature of this process is bootstrapping.

Here is the workflow:

action-model

For example, here I estimate the long-term return from taking action ata_t in state sts_t.

The training signal is therefore a long-term return. The target yty_t is yt=rt+γmax⁡a′Q(st+1,a′)y_t = r_t+\gamma\max_{a'}Q(s_{t+1},a').

The long-term return is the immediate reward, which comes directly from the environment, plus the discounted future return estimated by the Q model itself.

This is bootstrapping. You can think of the signal as propagating backward from the terminal step, where yTerminatey_{Terminate} equals rTerminater_{Terminate}.


Policy-based

Here we learn a policy model.

The classic approach is policy gradient, which aims to increase the probability of choosing good actions. The diagram below shows the workflow.

policy-model

After completing a trajectory, we update the policy using the outcome of that trajectory.

The update is the tricky part. Our objective is J(θ)=E[G]J(\theta) = E[G], where E[G]E[G] is the expected return across trajectories.

The objective is:

J(θ)=Eτ∼Pθ[G(τ)]J(\theta) = \mathbb E_{\tau\sim P_\theta}[G(\tau)]

Here:

  • θ\theta denotes the policy parameters.
  • Pθ(τ)=∏πP_\theta(\tau) = \prod\pi is the probability that the current policy produces trajectory τ\tau.
  • G(τ)G(\tau) is the cumulative return for that trajectory.

Expanding the expectation gives:

J(θ)=Eτ∼Pθ[G(τ)]=∑τPθ(τ)G(τ)J(\theta) = \mathbb E_{\tau\sim P_\theta}[G(\tau)] = \sum_\tau P_\theta(\tau)G(\tau)

The expectation is an exact weighted sum over all possibilities. In training, we cannot enumerate the potentially unbounded number of trajectories, so we sample them.

We approximate the expectation with a Monte Carlo estimate, E[f(x)]≈1N∑if(xi)\mathbb E[f(x)] \approx \frac1N\sum_i f(x_i). As NN grows, the typical estimation error decreases at a rate of O(1N)O(\frac{1}{\sqrt{N}}).

The probability weights are implicit in how often each outcome is sampled.

Plugging that approximation straight into J(θ)J(\theta) gives J=1N∑iG(τi)J= \frac{1}{N} \sum_i G(\tau_i). If we treat the sampled trajectories as fixed and differentiate this average, the gradient is zero. The environment supplies the scores, and there is no differentiable path from those scores back to the model parameters.

To retain the dependence on PP while still using samples, we use the identity ∇log⁡f(x)=∇f(x)f(x)\nabla \log f(x) = \frac{\nabla f(x)}{f(x)}. Differentiating first gives a term of the form P∇log⁡PP \nabla \log P. The sampling distribution accounts for PP, leaving the gradient of log⁡P\log P in the estimator.

In equations:

∇θJ(θ)=∇θ∑yPθ(y)G(y)\nabla_\theta J(\theta) = \nabla_\theta \sum_{y} P_\theta(y) G(y)

Since GG has no explicit dependence on θ\theta, we can move ∇\nabla inside the sum:

\nabla_\theta J(\theta) = \sum_{y} G(y) \nabla_\theta P_\theta(y)\tag{1}

Applying the identity gives:

\nabla_\theta J(\theta) = \sum_{y} G(y) \cdot P_\theta(y) \nabla_\theta \log P_\theta(y) \tag{3}

We can now sample to obtain the final gradient estimate:

∇θJ(θ)≈1N∑i=1NG(yi)∇θlog⁡Pθ(yi)\nabla_\theta J(\theta) \approx \frac{1}{N} \sum_{i=1}^{N} G(y_i) \nabla_\theta \log P_\theta(y_i)

The order of operations matters:

Differentiate the expectation to expose the gradient of the parameterized probability distribution, then apply Monte Carlo estimation to the resulting expectation.

Substitute pθ(τ)=∏tπθ(at∣st)p_\theta(\tau)=\prod_{t}\pi_\theta(a_t\mid s_t), where τ=(a1,s1,…,at,st)\tau =(a_1,s_1,\dots,a_t,s_t).

After rolling out NN trajectories, the gradient estimate is:

∇θJ(θ)≈1N∑i=1N(∑t=0T∇θlog⁡πθ(ai,t∣si,t))⋅G(τi)\nabla_\theta J(\theta) \approx \frac{1}{N} \sum_{i=1}^{N} \left( \sum_{t=0}^{T} \nabla_\theta \log \pi_\theta(a_{i,t} | s_{i,t}) \right) \cdot G(\tau_i)

This is a trajectory-level update.

We wait for the complete trajectory before updating, as in REINFORCE.

Actor-critic, below, shows how to update at each step.


Actor-Critic

              state
                │
       ┌────────┴────────┐
       ↓                 ↓
     Actor             Critic
       ↓                 ↓
   Select action      Evaluate state
       │                 │
       └──────┬──────────┘
              ↓
         Update Actor

Policy gradients can be unstable. Using the total return RR can give more weight to trajectories that already perform well, and variability in the environment can make the gradient estimate noisy.

A relative score helps. The advantage AA is the observed return minus the expected return.

This introduces the state value function V(st)V(s_t), which the critic estimates.

Vπ(st)=E[Gt∣st]\boxed{V^\pi(s_t) = \mathbb E[G_t|s_t]}

The resulting advantage is At=Gt−V(st)\boxed{ A_t = G_t-V(s_t) }.

With a value function, we can bootstrap as in the value-based method. Here we estimate GtG_t using G^t=rt+γV(st+1)\hat G_t = r_t + \gamma V(s_{t+1}).

This yields the advantage estimate A^t=rt+γV(st+1)−V(st)\hat A_t = r_t+\gamma V(s_{t+1})-V(s_t), also known as the temporal-difference error or TD error.

At step tt, we can compute the TD error δt\boxed{\delta_t} and backpropagate without waiting for the trajectory to end. The actor loss at each step is Lactor=−A^tlog⁡π(at∣st)L_{\text{actor}} = -\hat A_t\log\pi(a_t|s_t).

Likewise, following the approach used in Q-learning, we can use yt=rt+γVϕ(st+1)\boxed{ y_t = r_t+\gamma V_\phi(s_{t+1})} as the target for updating the critic.

The critic evaluates the state. The actor provides the policy.


Combining RL and LLMs

A language model naturally acts as a policy if we take the full token prefix as its state. It predicts P(tokent∣token<t)P(token_t \mid token_{<t}).

The concepts line up as follows:

RL                         LLM

state s             =     Current context
action a            =     Next token
policy π(a|s)       =     LLM's next-token distribution
trajectory          =     Full generated text

As we ask more of LLMs, we want them to:

  • Solve more problems
  • Behave more safely
  • Reason their way to correct answers
  • Write code that passes tests

These goals can be hard to achieve with supervised learning alone. This is a motivation for reinforcement learning from human feedback (RLHF).

PPO

Proximal Policy Optimization

The basic setup is still actor-critic, with a limit on how far the policy moves in one update.

PPO was introduced because an ordinary policy-gradient update can take too large a step. Clipping limits the incentive for large changes.

Define the probability ratio:

rt(θ)=πθ(at∣st)πold(at∣st)r_t(\theta) = \frac{ \pi_\theta(a_t|s_t) }{ \pi_{\text{old}}(a_t|s_t) }

Then add a clipped ratio, clip⁡(rt,0.8,1.2)\operatorname{clip}(r_t,0.8,1.2).

The clipped objective is LPPO=E[min⁡(rtAt,clip⁡(rt,1−ϵ,1+ϵ)At)]L_{\text{PPO}} = \mathbb E\left[ \min\left( r_tA_t, \operatorname{clip}(r_t,1-\epsilon,1+\epsilon)A_t \right) \right].

The first term inside the minimum expands to:

rt(θ)At=πθ(at∣st)πold(at∣st)At\boxed{ r_t(\theta)A_t = \frac{\pi_\theta(a_t|s_t)} {\pi_{\text{old}}(a_t|s_t)} A_t }

The ratio is the extra factor relative to the usual actor-critic loss, Lactor=−A^tlog⁡π(at∣st)L_{\text{actor}} = -\hat A_t\log\pi(a_t|s_t).

GRPO

Group Relative Policy Optimization uses a score relative to the rollout group in place of a critic prediction.

Think of it as a PPO-style policy update with a group-relative advantage and no critic.

If μ\mu is the mean final reward for a group of rollouts, a simple advantage estimate is R−μR-\mu.

This example uses the final reward RR.

You could also use a return GG, though it may be harder to compute.