# Lecture 20 — Credit assignment, PPO, and reinforcement learning for language models

The inspection assistant can generate several candidate answers to a report question. Some correctly compute a crack-width change; others produce plausible but unsupported conclusions. We can score the final result more easily than prescribe every intermediate token. How should those scores change the model, and how much can we reuse answers generated before the latest parameter update?

This chapter completes the policy-gradient derivation, adds baselines, develops PPO's clipped surrogate, and maps language generation into a decision process. The recording also discusses CISPO and group-relative rewards; their exact definitions are checked against primary papers. Our numerical examples, counterexamples, code, and derivations are teaching contributions. Research extension material is identified in place. The transcript determines topic order, while mathematical corrections prevent incidental caption or board shorthand from becoming false claims.

## 1. The past cannot be changed by the current action [03:47](https://www.youtube.com/watch?v=J7CossjMvEg&t=227s)

Consider a horizon-$H$ trajectory generated by policy $\pi_\theta$. Let $R_t$ be the reward following action $A_t$ in state $S_t$, and let $\gamma\in[0,1]$ be the discount. The objective is
$J(\theta)=\mathbb E[\sum_{u=0}^{H-1}\gamma^uR_u]$.
Define the score vector
$Z_t=\nabla_\theta\log\pi_\theta(A_t\mid S_t)$.
Lecture 18 established

$$\nabla_\theta J
=\mathbb E\left[\sum_tZ_t\sum_u\gamma^uR_u\right].$$

For a fixed state, the expected score is zero:

$$\mathbb E[Z_t\mid S_t=s]
=\sum_a\pi_\theta(a\mid s)\nabla_\theta\log\pi_\theta(a\mid s)
=\nabla_\theta\sum_a\pi_\theta(a\mid s)=0.$$

It is the expected gradient of log probability that vanishes. Expected log probability itself is generally negative entropy, not zero.

Let $\mathcal H_t$ denote the history through the state $S_t$, before sampling $A_t$. Every past reward $R_u$ for $u<t$ is fixed when conditioning on this history. Since the action is sampled from the stated policy,

$$\mathbb E[Z_tR_u]
=\mathbb E\left[R_u\,\mathbb E[Z_t\mid\mathcal H_t]\right]=0
\qquad(u<t).$$

This uses conditional expectation, not a false factorization of expectations of dependent random variables. The reward-to-go is

$$G_t=\sum_{u=t}^{H-1}\gamma^{u-t}R_u.$$

Therefore

$$\nabla_\theta J=
\mathbb E\left[\sum_{t=0}^{H-1}\gamma^t Z_tG_t\right].$$

The outer factor $\gamma^t$ is required for the displayed discounted objective. If reward-to-go is instead defined with absolute powers $\gamma^u$, that factor is already inside it. Mixing conventions loses a discount.

For rewards $(1,2,4)$ and $\gamma=0.5$, relative reward-to-go values are $(3,4,4)$, while the weights multiplying the respective score vectors are $(3,2,1)$. The final action should not receive credit for reward already obtained at time zero.

Removing irrelevant past terms often improves an estimator, but zero expectation alone does not prove that removing an arbitrary correlated random variable decreases variance in every setting. The exact identity and the variance claim are separate questions.

## 2. Baselines are control variates for the gradient [15:57](https://www.youtube.com/watch?v=J7CossjMvEg&t=957s)

Any baseline $b_t$ fixed given pre-action history satisfies
$\mathbb E[Z_tb_t]=0$. Thus

$$\nabla_\theta J=
\mathbb E\left[\sum_t\gamma^t Z_t(G_t-b_t)\right].$$

A common choice is a state-value estimate $b_t\approx V^\pi(S_t)$. The difference between action value and state value,
$A^\pi(s,a)=Q^\pi(s,a)-V^\pi(s)$,
is called the advantage. Here $Q^\pi(s,a)$ is expected future return after taking $a$ in $s$ and then following $\pi$. A sampled return minus an estimated baseline is an advantage estimator, not automatically the exact advantage.

The baseline can depend on $\theta$ as a fitted function, but must be treated as constant in the actor's score-function update. Differentiating through it would introduce additional terms not justified by the zero-score identity. A separate regression loss can train a value model.

### A constant baseline can reduce variance

Subtracting a constant does not change $\operatorname{Var}(R)$. But the policy-gradient estimator is $Z(R-b)$, not $R-b$ alone, and $Z$ is random. This distinction corrects an informal suggestion in the recording that a constant baseline cannot help.

Take a binary action with probability $p=1/2$, score $Z=A-p$, and rewards $10$ for action zero and $11$ for action one. Without a baseline, the estimator is $-5$ or $5.5$, equally likely. Its mean is $0.25$ and variance is $27.5625$. With constant baseline $b=10.5$, the estimator equals $0.25$ for either action. Its variance becomes zero while its mean is unchanged.

For a fixed state, minimize the second moment
$\mathbb E[\|Z\|^2(G-b)^2]$ with respect to scalar $b$. The mean gradient does not depend on $b$, so this also minimizes the trace of the estimator covariance. Differentiation gives

$$b^*=
\frac{\mathbb E[\|Z\|^2G]}{\mathbb E[\|Z\|^2]},
$$

provided the denominator is positive. The optimum is a score-weighted reward average. It equals the ordinary expected return only in special cases. For binary rewards $(r_0,r_1)$ under a logistic policy, substituting scores $-p$ and $1-p$ gives $b^*=pr_0+(1-p)r_1$. At $p=1/4$ and rewards $(0,2)$, this is $1.5$, whereas expected reward is $0.5$.

The following exact enumeration checks both the constant-baseline counterexample and the weighted optimum. Inputs are a probability strictly inside $(0,1)$, two finite rewards, and a finite baseline. The function returns mean and variance and has no random or external effects.

```python
import numpy as np


def gradient_moments(p, rewards, baseline):
    rewards = np.asarray(rewards, float)
    if not np.isfinite(p) or not 0 < p < 1:
        raise ValueError("Use an interior Bernoulli probability")
    if rewards.shape != (2,) or not np.isfinite(rewards).all():
        raise ValueError("Two finite rewards are required")
    if not np.isfinite(baseline):
        raise ValueError("Baseline must be finite")
    probabilities = np.array([1 - p, p])
    scores = np.array([-p, 1 - p])
    estimates = scores * (rewards - baseline)
    mean = probabilities @ estimates
    variance = probabilities @ (estimates - mean) ** 2
    return mean, variance


assert np.allclose(gradient_moments(0.5, [10, 11], 0), [0.25, 27.5625])
assert np.allclose(gradient_moments(0.5, [10, 11], 10.5), [0.25, 0])
assert np.allclose(gradient_moments(0.25, [0, 2], 1.5), [0.375, 0])
```

Zero variance here relies on a tiny deterministic-reward bandit. In realistic trajectories, even an excellent baseline leaves randomness from transitions, actions, and rewards. A poor baseline can increase variance.

## 3. Reusing old trajectories requires a distribution correction [26:39](https://www.youtube.com/watch?v=J7CossjMvEg&t=1599s)

The basic on-policy score estimator expects trajectories from the same policy whose gradient is being estimated. After an update, the old samples have a different distribution. They are not useless, but using them unchanged no longer gives the same unbiased estimator.

Importance sampling states

$$\mathbb E_{X\sim p}[f(X)]
=\mathbb E_{X\sim q}\left[\frac{p(X)}{q(X)}f(X)\right],$$

provided $q$ is positive wherever the target integrand requires probability mass, with suitable integrability. For complete trajectories whose environment dynamics are unchanged,

$$\frac{p_\theta(\tau)}{p_{\rm old}(\tau)}
=\prod_t\frac{\pi_\theta(a_t\mid s_t)}
{\pi_{\rm old}(a_t\mid s_t)}.$$

Environment factors cancel. This exact correction can have high variance because ratios multiply over a long trajectory. A per-action ratio

$$\rho_t(\theta)=
\frac{\pi_\theta(a_t\mid s_t)}
{\pi_{\rm old}(a_t\mid s_t)}$$

corrects the action distribution at a fixed state; it does not by itself correct the distribution of visited states.

### Why the missing state correction matters

Consider two steps. At the first step, an old policy enters state $G$ with probability $0.5$, while a new policy enters it with probability $0.9$. At the second step there is only one action, so its action ratio is exactly one. A reward of one occurs only in $G$. Averaging second-step reward over old states gives $0.5$, despite the new policy's true expected reward $0.9$. The local ratio cannot fix an earlier visitation change.

PPO uses old-state samples and fixed advantage estimates to build a local surrogate,
$\mathbb E_{\rm old}[\rho_t(\theta)\hat A_t]$,
with appropriate timestep weighting for the chosen objective. At the old parameters, the derivative of the ratio is the policy score. With exact old-policy advantages and consistent occupancy weighting, the surrogate agrees with the desired policy gradient at that point. Repeated updates move away from that local agreement.

[Schulman et al.](https://arxiv.org/abs/1707.06347) introduces PPO as an empirical optimization approach using repeated minibatch updates to a surrogate. It should not be described as an exact unbiased correction for arbitrary amounts of old trajectory reuse.

## 4. PPO clips incentives in a direction-dependent way [38:47](https://www.youtube.com/watch?v=J7CossjMvEg&t=2327s)

For a fixed sampled advantage $\hat A$, PPO's clipped per-sample objective is

$$\ell_{\rm PPO}(\rho,\hat A)=
\min\left(\rho\hat A,\,
\operatorname{clip}(\rho,1-\epsilon,1+\epsilon)\hat A\right),
\qquad 0<\epsilon<1.$$

We maximize this objective. Clipping clamps a scalar to the specified interval. The minimum produces asymmetric behavior according to the sign of advantage.

For $\hat A>0$, the expression equals
$\hat A\min(\rho,1+\epsilon)$.
It grows with the probability ratio until the upper threshold, then becomes flat. For $\hat A<0$, it equals
$\hat A\max(\rho,1-\epsilon)$.
It improves as the ratio decreases until the lower threshold, then becomes flat.

With $\epsilon=0.2$ and $\hat A=2$, ratios $0.5,1,1.5$ produce objective values $1,2,2.4$. With $\hat A=-2$, the same ratios produce $-1.6,-2,-3$. A bad action whose probability has grown too much remains penalized; a good action whose probability has fallen too much remains encouraged.

“Flat” means that this sample's objective supplies no further gradient in that region. It does not mean that its probability is forcibly held at the threshold. Other samples share the same parameters and can continue moving it.

### Clipping is not a hard trust-region guarantee

Suppose the old distribution over two actions is $(0.5,0.5)$, and a dataset contains only the first action with positive advantage. The sampled objective is already flat whenever its new probability exceeds $0.6$. It remains equally flat as that probability approaches one. Yet
$\operatorname{KL}(\pi_{\rm old}\|\pi_{\rm new})$
diverges as the new probability of the second action approaches zero. Thus the clipped sampled objective alone does not bound KL divergence.

This is a concrete limitation of the objective, not a claim that PPO necessarily takes such an update. Practical implementations monitor divergence, clip fractions, entropy, and optimization stability. A fixed reference policy used for a KL penalty is also different from the old rollout policy used in the denominator: one anchors behavior across training, the other records how a particular batch was sampled.

The next function implements the scalar clipped objective for array inputs and tests the flat regions with finite differences. It accepts finite positive ratios and finite advantages, returns per-sample objective values, and performs no optimization.

```python
def ppo_objective(ratio, advantage, epsilon=0.2):
    ratio, advantage = np.broadcast_arrays(
        np.asarray(ratio, float), np.asarray(advantage, float)
    )
    if not np.isfinite(ratio).all() or np.any(ratio <= 0):
        raise ValueError("Ratios must be positive and finite")
    if not np.isfinite(advantage).all() or not 0 < epsilon < 1:
        raise ValueError("Use finite advantages and epsilon in (0, 1)")
    return np.minimum(
        ratio * advantage,
        np.clip(ratio, 1 - epsilon, 1 + epsilon) * advantage
    )


assert np.allclose(ppo_objective([0.5, 1, 1.5], 2), [1, 2, 2.4])
assert np.allclose(ppo_objective([0.5, 1, 1.5], -2), [-1.6, -2, -3])
h = 1e-6
assert np.isclose((ppo_objective(1.5 + h, 2)
                   - ppo_objective(1.5 - h, 2)) / (2 * h), 0)
assert np.isclose((ppo_objective(0.5 + h, -2)
                   - ppo_objective(0.5 - h, -2)) / (2 * h), 0)
```

## 5. CISPO clips a detached importance weight [51:20](https://www.youtube.com/watch?v=J7CossjMvEg&t=3080s)

The [MiniMax-M1 technical report](https://arxiv.org/abs/2506.13585) defines CISPO, clipped importance-sampling-weight policy optimization. Its key operation differs from PPO:

$$\ell_{\rm CISPO}=
\operatorname{stopgrad}(\operatorname{clip}(\rho,l,u))
\hat A\log\pi_\theta(a\mid s).$$

Here $l,u$ are clipping bounds and the advantage is also treated as fixed. The resulting actor gradient is
$\operatorname{clip}(\rho,l,u)\hat A\nabla_\theta\log\pi_\theta(a\mid s)$.
The report's experiments omit an effective lower clip and tune the upper bound. This does not impose PPO's sign-dependent flat regions.

For an original scalar comparison, take $\rho=2$, $\hat A=1$, and upper bound $1.2$. PPO's sampled gradient is zero after its upper threshold; the detached-weight expression retains coefficient $1.2$ on the score. With negative advantage, that coefficient changes sign rather than disabling the sample.

Clipping weights introduces bias. Removing the stop-gradient changes the derivative and the algorithm. Neither construction guarantees exploration, bounded parameter steps, or universal superiority; the report's performance findings belong to its experimental setup.

## 6. Language generation supplies a particularly simple environment [56:25](https://www.youtube.com/watch?v=J7CossjMvEg&t=3385s)

For prompt $x$ and generated tokens $y_1,\ldots,y_T$, define state
$S_t=(x,y_{<t})$ and action $A_t=y_t$. The transition appends the chosen token. It is deterministic even though action sampling is stochastic. A terminal reward $R(x,y)$ can evaluate the answer after generation.

With $\gamma=1$ and no intermediate rewards, every token's reward-to-go equals the terminal reward. The same sequence-level advantage can therefore weight each token's score. This is statistically valid credit assignment for the expected sequence reward; it does not identify which individual token was causally responsible for success.

Intermediate generated reasoning text gives the model additional sequential computation before the final answer. [Wei et al.](https://arxiv.org/abs/2201.11903) studies few-shot chain-of-thought prompting, and [Kojima et al.](https://arxiv.org/abs/2205.11916) studies a zero-shot prompting procedure. Their reported gains are task- and model-specific, rather than a universal percentage improvement. A generated explanation also need not faithfully expose the model's internal computation.

Outcome-based training can avoid prescribing one exact intermediate solution. [DeepSeek-R1](https://arxiv.org/abs/2501.12948) provides primary evidence for reinforcement-learning-based reasoning development in its training setup. This does not imply that demonstrations or pretraining are unnecessary for every model; the initial policy must produce useful learning signal with feasible sampling effort.

### A verifier is part of the objective

For a crack-width arithmetic task, a deterministic verifier could parse a numeric answer and compare it with an independently computed result, including units and tolerance. Passing such a check establishes that result, not the safety of a repair recommendation.

The verifier can be wrong, incomplete, or exploitable. Exact string matching may reject equivalent fractions; a permissive parser may accept contradictory text containing one correct number. A language-model judge adds another learned component with its own errors. Track parser success, reward correctness, and downstream usefulness separately.

If independent sampled answers succeed with probability $p$, a group of $G$ contains at least one success with probability $1-(1-p)^G$. At $p=0.001$ and $G=8$, this is about $0.007972$, so most groups provide no positive outcome. More sampling, easier curriculum tasks, or a stronger starting policy can change the signal, but no optimizer can extract task-specific positive evidence from an all-zero reward batch alone.

## 7. Group-relative rewards remove a critic but introduce dependencies [70:47](https://www.youtube.com/watch?v=J7CossjMvEg&t=4247s)

For a fixed prompt, sample $G\ge2$ responses with rewards $R_1,\ldots,R_G$. Define group mean $\bar R=G^{-1}\sum_iR_i$. A centered advantage is $R_i-\bar R$; a standardized form divides by a group standard deviation, with a specified convention and numerical safeguard.

[DeepSeekMath](https://arxiv.org/abs/2402.03300) introduces group relative policy optimization, GRPO, using relative response rewards within a PPO-related training framework. The group statistics avoid fitting a separate value critic in that formulation. They are not literally a deterministic function of the prompt: they depend on sampled responses.

For rewards $(1,0,0,0,0,0,0,0)$, centered values are $7/8$ for the success and $-1/8$ for each failure. With the population standard deviation $\sqrt7/8$, standardized values are $\sqrt7$ and $-1/\sqrt7$. If all rewards agree, centered advantages vanish; division by zero must be handled explicitly.

### The current sample participates in its own baseline

Let $Z_i$ be the score of response $i$, and suppose responses are independent conditional on the prompt and sampled on policy. Let $g=\mathbb E[Z_iR_i]$ and $\mathbb E[Z_i]=0$. Then

$$\mathbb E[Z_i\bar R]
=\frac1G\mathbb E[Z_iR_i]
+\frac1G\sum_{j\ne i}\mathbb E[Z_i]\mathbb E[R_j]
=\frac gG.$$

Therefore

$$\mathbb E[Z_i(R_i-\bar R)]=(1-1/G)g.$$

For unstandardized centering, the expected gradient is scaled by $1-1/G$. A leave-one-out mean
$\bar R_{-i}=(G-1)^{-1}\sum_{j\ne i}R_j$
is independent of the current response under the assumptions and avoids this factor. Once dividing by a random group standard deviation, adding clipping, or reusing old data, the analysis changes; these operations are not captured by a single constant correction.

The following exhaustive two-response experiment verifies the centering factor without Monte Carlo noise. It enumerates a Bernoulli policy with success probability $1/4$, reward equal to the sampled action, and logistic score $A-p$. It also checks the eight-response arithmetic.

```python
from itertools import product

p = 0.25
group_estimate = 0.0
loo_estimate = 0.0
for actions in product([0, 1], repeat=2):
    a = np.asarray(actions, float)
    probability = np.prod(np.where(a == 1, p, 1 - p))
    scores = a - p
    group_estimate += probability * np.mean(scores * (a - a.mean()))
    loo_estimate += probability * np.mean(scores * (a - a[::-1]))
assert np.isclose(group_estimate, 0.5 * p * (1 - p))
assert np.isclose(loo_estimate, p * (1 - p))
rewards = np.array([1.0] + [0.0] * 7)
standardized = (rewards - rewards.mean()) / rewards.std(ddof=0)
assert np.isclose(standardized[0], np.sqrt(7))
assert np.allclose(standardized[1:], -1 / np.sqrt(7))
```

## Limitations and an auditable training loop

A complete loop records the rollout policy, sampling settings, generated tokens, old token log probabilities, verifier version, rewards, advantage construction, and update rule. Rollouts, evaluation, and gradient updates consume different resources. Long answers increase generation time and cached state; training on completed trajectories can process positions in parallel, but its relative cost depends on batch size and hardware.

For the inspection assistant, start with a finite set of verifiable arithmetic or document-extraction tasks, an independent held-out set, and a checked reward program. Measure success probability, answer length, reward disagreement, diversity, and distribution shift. Improved training reward is evidence about the implemented objective; it becomes evidence about the real task only after those two have been shown to agree.

## Exercises

1. For rewards $(1,2,4)$ and $\gamma=0.5$, derive relative reward-to-go and the absolute-discount score weights.
2. Verify the zero-variance constant-baseline example. Why does the statement $\operatorname{Var}(R-b)=\operatorname{Var}(R)$ not settle the question?
3. In the two-step visitation example, identify a trajectory importance ratio that corrects the expected terminal reward.
4. With $\epsilon=0.2$, calculate PPO's objective and derivative with respect to $\rho$ at $(\rho,\hat A)=(1.5,2)$ and $(1.5,-2)$. Compare a detached CISPO upper weight of $1.2$.
5. Derive the group-mean shrinkage factor for $G$ independent responses. Give the corrected factor for $G=8$, and explain why standardization prevents treating the entire procedure as this same correction.

<details>
<summary>Fully worked solutions</summary>

1. $G_2=4$, $G_1=2+0.5(4)=4$, and $G_0=1+0.5(2)+0.25(4)=3$. Multiplying by $\gamma^t$ yields score weights $(3,2,1)$. Using $(3,4,4)$ directly would correspond to a different weighting unless another part of the sampling convention supplies the discount.
2. Without a baseline, scores are $-0.5$ and $0.5$, giving estimators $-5$ and $5.5$. Their mean is $0.25$ and squared deviation is $5.25^2=27.5625$ in either case. After subtracting $10.5$, both products equal $0.25$. Reward variance is unchanged, but multiplication by the action-dependent score changes covariance and estimator variance.
3. For a trajectory entering $G$, the first-action ratio is $0.9/0.5=1.8$; the second-action ratio is one. Old-policy expectation of corrected reward is $0.5(1.8)(1)=0.9$. The other branch contributes zero reward, with ratio $0.1/0.5=0.2$. Including the earlier action corrects visitation.
4. At positive advantage, PPO is $1.2(2)=2.4$ with derivative zero. At negative advantage, PPO is $1.5(-2)=-3$ with derivative $-2$. CISPO instead supplies score-gradient coefficients $1.2(2)=2.4$ and $1.2(-2)=-2.4$. These are coefficients on $\nabla\log\pi$, not derivatives with respect to the ratio, so they must not be compared as if they were the same coordinate derivative.
5. Expand $\bar R=R_i/G+\sum_{j\ne i}R_j/G$. Cross terms vanish because other responses are independent and the score has mean zero, leaving $g/G$ for the baseline term. Centering yields $(1-1/G)g$; for $G=8$, multiplying the unstandardized estimator by $8/7$ corrects its mean under the stated assumptions. Dividing by sample standard deviation introduces another random quantity correlated with the rewards and scores, so that simple expectation factorization no longer applies.
</details>

## Primary sources

- Schulman et al., [Proximal Policy Optimization Algorithms](https://arxiv.org/abs/1707.06347).
- Shao et al., [DeepSeekMath](https://arxiv.org/abs/2402.03300).
- MiniMax, [MiniMax-M1: Scaling Test-Time Compute Efficiently with Lightning Attention](https://arxiv.org/abs/2506.13585), especially the CISPO formulation.
- Wei et al., [Chain-of-Thought Prompting Elicits Reasoning in Large Language Models](https://arxiv.org/abs/2201.11903).
- Kojima et al., [Large Language Models are Zero-Shot Reasoners](https://arxiv.org/abs/2205.11916).
- DeepSeek-AI, [DeepSeek-R1](https://arxiv.org/abs/2501.12948).
