All courses

Treating the LLM as an RL policy

Cast generation as RL: the state is the prefix, an action is a token, the policy is π_θ, and the reward arrives at the end of the response. Write the policy-gradient update for a sampled response.

Builds on: Policy gradients (REINFORCE) and baselines, Autoregressive generation loop

▶ Watch this lesson Start the whole course

What the animation says

One score, many choices

Your model writes a two-hundred-token solution to a math problem. A checker reads it and says only one thing, at the very end: right, or wrong. There is no reference text to copy, so ordinary next-token training has nothing to imitate. Yet two hundred separate choices built this answer. So how does one score at the end adjust every one of those choices?

Generation is an episode

Look at generation as a sequence of decisions. The situation is the prompt plus everything written so far. Reinforcement learning calls it the state. The choice is the next token: the action. The model's softmax over tokens is the policy. Appending the token gives the next state, with no randomness. One full response is one episode. Two plus two equals, the model picks four, then the end token. Reward: one. The reward arrives after the end token. Which tokens does the update push on?

One signal, every token

Every sampled token, with the same weight. The log-probability of the whole response is the sum of each token's log-probability. So its gradient is a sum too, one term per token. Each term is scaled by reward minus a baseline, the score we expected on average. Baseline point six, reward one: plus point four goes to four and to the end token alike. Both become more likely. Now the checker says wrong: reward zero. What does the update do?

By hand: the logit gradient

Both go down. Reward zero sits below the baseline, so every token gets minus point six. Zoom into step one. Four, five and three had probabilities point five, point three, point two. For the sampled token, the gradient on the logits is its one-hot vector minus the probabilities. Times plus point four: point two for four, minus point one two for five, minus point zero eight for three. Now use minus point six instead. Tap every logit that goes up.

One step in code

Four drops; five and three rise. Here is the same step in code. Two response steps, three logits each. The sampled tokens are index zero, then index two. This line sums the sampled tokens' log-probabilities: minus point eight four four. This line is reward minus baseline, times one-hot minus probabilities, for both steps at once. One step uphill, and the log-probability rises to minus point seven six six. Real models backpropagate this into the weights. Above baseline, every token goes up. Below, every token goes down.

One score at the end, many token choices

Your model writes a 200-token solution. A checker only says *right* or *wrong* at the very end. There is no target text to imitate, so next-token training has nothing to copy. How do you turn **one end-of-response score** into a gradient that adjusts **every token choice** the model made along the way?

Generation already is a decision process

At each step the **situation** is the prompt plus everything written so far. The **choice** is the next token. The model's softmax is a probability distribution over choices: a **policy**. Appending the token gives the next situation, with no randomness. One full response is one **episode**, and the score arrives only after the end token. REINFORCE then applies directly.

State, action, policy, reward, update

**Plain words → RL symbols**, shown on prompt $x=$ "2+2=": - situation → **state** $s_t=(x,y_{<t})$. Example: $s_1=$ "2+2=", $s_2=$ "2+2=4" - next token (choice) → **action** $a_t=y_t$. Example: $a_1=$ "4", $a_2=$ ⟨end⟩ - model's softmax → **policy** $\pi_\theta(y_t\mid x,y_{<t})$, the softmax of the logits computed from $s_t$ - checker's score → **reward** $r(x,y)$, given once, at the end **The episode:** "2+2=" → "4" → ⟨end⟩ → $r=1$. With baseline $b=0.6$, the same $r-b=0.4$ goes back to **every** token: "4" ← 0.4 and ⟨end⟩ ← 0.4. **The update:** $\log\pi_\theta(y\mid x)=\sum_t \log\pi_\theta(y_t\mid x,y_{<t})$, so $$\theta\leftarrow\theta+\eta\,(r(x,y)-b)\sum_t \nabla_\theta\log\pi_\theta(y_t\mid x,y_{<t})$$

A two-token answer, by hand

Prompt "2+2=". Step 1 probabilities over {4, 5, 3} are $[0.5, 0.3, 0.2]$. The model samples "4", then samples the end token with $p=0.9$. So $\log\pi(y\mid x)=\ln0.5+\ln0.9=-0.798$. The reward is 1 and $b=0.6$, so $r-b=0.4$. The gradient of $\log p_a$ with respect to the logits is $\text{onehot}(a)-p$. Step 1 logit gradient: $0.4\cdot([1,0,0]-[0.5,0.3,0.2])=[0.2,-0.12,-0.08]$. This raises "4". If the reward were 0, then $r-b=-0.6$ and the gradient is $[-0.3,0.18,0.12]$.

One update step on the logits

This nudges the logits directly so the effect is visible. In a real model, the same per-step logit gradients are backpropagated into $\theta$. The log-probability of the sampled response goes up because $r>b$.
import numpy as np
def softmax(z): e = np.exp(z - z.max(-1, keepdims=True)); return e / e.sum(-1, keepdims=True)
Z = np.array([[2.0, 1.5, 1.0], [0.0, 0.5, 2.7]])  # logits at 2 response steps
y = np.array([0, 2])                               # sampled tokens
r, b, eta = 1.0, 0.6, 0.5                          # reward, baseline, step size
P = softmax(Z)
logp = np.log(P[np.arange(2), y]).sum()            # log pi(y|x)
G = (r - b) * (np.eye(3)[y] - P)                   # grad of (r-b)*logp w.r.t. Z
Z_new = Z + eta * G                                # gradient ascent
print(logp, np.log(softmax(Z_new)[np.arange(2), y]).sum())

Remember

Generation is an episode: the state is the prefix, the action is the next token, the policy is $\pi_\theta$, and one reward comes at the end. The update is $\eta(r-b)\sum_t\nabla\log\pi_\theta(y_t\mid x,y_{<t})$. It raises every token of an above-baseline response and lowers every token of a below-baseline one. Later ideas refine the baseline, limit how far the model drifts, and decide where rewards come from.

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.