Reinforcement Learning for Sequence Generation

Dive into Deep Learning · §15.8

Reinforcement Learning for Sequence Generation and LLMs
token-level MDP · credit decomposition · verifiable rewards (RLVR) · GRPO & asymmetric clipping · k3 KL penalty · DPO

From Next-Token Imitation to Verifier Post-Training

Motivation

  • Outcome-Level Supervision: The model generates a full completion y = (a_1, \dots, a_T) to prompt x, and a deterministic verifier returns a single scalar score r(x, y) at EOS.
  • The 4-Prompt Verifier Benchmark: Reference \pi_{\textrm{ref}} passes the exact checker on 6.2\% of prompts (ceiling 50\%), while a lenient substring checker rewards the hedged reply on every prompt.

Autoregressive Text Generation as a Token-Level MDP

The Token MDP

  • Every response y = (a_1, \dots, a_T) is a trajectory in a deterministic-transition MDP where state s_t = (x, a_1, \dots, a_{t-1}) is the prefix and action a_t is the next token: \pi_\theta(y \mid x) = \prod_{t=1}^{T} \pi_\theta(a_t \mid s_t) \nabla_\theta \log \pi_\theta(y \mid x) = \sum_{t=1}^{T} \nabla_\theta \log \pi_\theta(a_t \mid s_t)
  • With \gamma = 1 and a single terminal reward r(x, y) at EOS, the sequence-level bandit gradient and the token-level MDP policy gradient are algebraically identical.

Computing Response vs. Token Credit on Two Digits

Credit Assignment

To compare whole-response weighting against per-token credit assignment, consider answering 3*4 with a two-digit number y = 10 a_1 + a_2 where only 12 (a_1 = 1, a_2 = 2) receives reward r = 1:

def token_credit(p1, p2, r):
    """For two-digit responses y = 10 a1 + a2: pi(y | x), the response
    weight r - V(x) and the token advantages A(s_1, a1), A(s_2, a2)."""
    a1, a2 = np.divmod(np.arange(100), 10)
    prob = p1[a1] * p2[a2]
    V_x, V_xa = prob @ r, r.reshape(10, 10) @ p2   # V(x), V(x, a1)
    return prob, r - V_x, V_xa[a1] - V_x, r - V_xa[a1]
  • Prefix Value Functions: Under a uniform policy (p_1 = p_2 = 0.1), the prompt value is V(x) = 1/100 = 0.01, the prefix value after a correct tens digit is V(x, a_1{=}1) = 1/10 = 0.10, and V(x, a_1{\neq}1) = 0.

Why Response Weights Penalize Correct Prefix Tokens

Credit Comparison

Evaluating the whole-response weight r(x, y) - V(x) alongside the prefix-conditioned token advantages A(s_1, a_1) = V(x, a_1) - V(x) and A(s_2, a_2) = r - V(x, a_1) on replies 12, 13, and 52:

response   r - V(x)   A(s_1, a_1)   A(s_2, a_2)
      12       0.99          0.09          0.90
      13      -0.01          0.09         -0.10
      52      -0.01         -0.01          0.00
same expected gradient for the tens digit: True
variance: r - V(x) 0.0099, A(s_1, a_1) 0.0009, A(s_2, a_2) 0.0090
  • On reply 13 (correct tens digit 1, wrong units digit 3), the response weight puts -0.01 on both digits (pushing the correct tens digit down), whereas A(s_1, 1) = +0.09 rewards 1 and A(s_2, 3) = -0.10 punishes 3.

Orthogonal Variance Decomposition Across Tokens

Why Per-Token Credit Matters

r(x, y) - V(x) = A(s_1, a_1) + A(s_2, a_2)

  • Uncorrelated increments: Because \mathbb{E}[A(s_2, a_2) \mid s_1, a_1] = 0, token advantages are orthogonal and their variances add: 0.0009 + 0.0090 = 0.0099.
  • The 11\times variance tax: Using the whole-response weight inflates the first token’s gradient variance 11\times by injecting downstream token noise.

What the Token MDP Simplifies and What Remains

Architectural Simplifications

  • Eliminated in single-turn LLM RL: No learned world model is needed because token concatenation is exact, and no replay Q-network is used because |\mathcal{A}| \sim 10^5 tokens creates severe \max_a bias.
  • Essential surviving mechanisms: Group baselines (GRPO/RLOO) or prefix critics reduce variance, while ratio clipping and KL penalties guard multi-epoch updates and prevent reward hacking.

Verifiable Rewards (RLVR) and Grader Loopholes

Verifiers & Loopholes

Training directly against deterministic checkers such as unit tests, math verifiers, or proof assistants (RLVR; DeepSeek-R1, 2025) eliminates learned reward-model approximation error, unless the checker itself has a specification loophole:

def sloppy_checker(task):
    """A lenient checker: 1 if the answer appears anywhere in response y."""
    return lambda x, y: float(task.answers[x] in task.resp[y])

task = d2l.VerifierTask()
sloppy = sloppy_checker(task)
print(f'reference: exact score {task.success(task.pi_ref):.3f}, '
      f'lenient score {task.success(task.pi_ref, sloppy):.3f}')
reference: exact score 0.062, lenient score 0.065
  • On VerifierTask, no ordinary reply solves 8*8 or 9*9 (so the exact ceiling is 0.500), while sloppy_checker checks only substring inclusion (answer in resp), paying +1 to the hedged reply “one of 4, 12, 64 or 81” on every prompt.

Folding KL Regularization into the Group Step

KL-Penalized Group Update

To restrain the policy from collapsing onto the loophole, kl_group_step folds the per-sample reverse-KL log-ratio -\beta \log\big(\pi_\theta(y \mid x)/\pi_{\textrm{ref}}(y \mid x)\big) directly into the reward passed to d2l.group_step:

def kl_group_step(task, theta, K, reward, rng, beta, lr=2.0):
    """d2l.group_step with the reward r - beta log(pi(y|x) / pi_ref(y|x))."""
    pi = task.policy(theta)                    # the policy that samples
    def penalized(x, y):
        return reward(x, y) - beta * np.log(pi[x, y] / task.pi_ref[x, y])
    return d2l.group_step(task, theta, K, penalized, rng, lr)
  • Unbiased Reverse-KL Gradient: By the zero-mean score identity \mathbb{E}_{y \sim \pi_\theta}[\nabla_\theta \log \pi_\theta(y \mid x)] = 0, weighting \nabla_\theta \log \pi_\theta by r(x, y) - \beta \log(\pi_\theta/\pi_{\textrm{ref}}) yields an unbiased estimate of \nabla_\theta\big(\mathbb{E}[r] - \beta D_{\textrm{KL}}(\pi_\theta \Vert \pi_{\textrm{ref}})\big).

Closed-Form Prediction of the Loophole Threshold

Exact Threshold Analysis

\frac{\pi^\star(y_{\textrm{hedge}} \mid x)}{\pi^\star(y_{\textrm{ord}} \mid x)} = \frac{\pi_{\textrm{ref}}(y_{\textrm{hedge}} \mid x)}{\pi_{\textrm{ref}}(y_{\textrm{ord}} \mid x)}\, e^{(1 - 0)/\beta} = e^{1/\beta - 4}

  • Reference odds: Under \pi_{\textrm{ref}}, the hedge has logit -4 vs. 0 for ordinary replies (e^{-4} \approx 0.018).
  • Critical threshold (\beta = 1/4 = 0.25): The hedge dominates unsolvable prompts for \beta < 0.25 and is suppressed for \beta > 0.25.

Empirical Beta Sweep vs. Exact Tilted Optima

Theory Meets Training

Training with kl_group_step (K = 32 samples per prompt, 400 updates) across \beta \in \{0.0, 0.1, 0.2, 0.3, 0.5\} matches the closed-form tilted optimum \pi^\star within 0.02 at every temperature:

beta   trained: lenient  exact  hedge  optimum: lenient  exact  hedge
 0.0               1.00   0.50   0.50
 0.1               0.99   0.50   0.49              0.99   0.49   0.50
 0.2               0.60   0.48   0.12              0.60   0.47   0.14
 0.3               0.44   0.40   0.04              0.43   0.39   0.04
 0.5               0.25   0.23   0.01              0.27   0.25   0.01

The Regularization Trade-off: At \beta = 0, the policy achieves a perfect lenient score (1.00) by placing 100\% of its mass on the hedge for 8*8 and 9*9 (0.50 hedge average). Raising \beta to 0.3 > 0.25 suppresses the hedge (0.04), while over-penalizing at \beta = 0.5 drags the exact score back down (from 0.50 to about 0.25).

Stale Samples, Sequence Ratios, and Asymmetric Clipping

Scale Systems Nuances

  • Sequence Geometric Mean (GSPO; Zheng et al., 2025): Replaces exploding product W = \prod_{t=1}^T \rho_t with \bar{\rho} = W^{1/T} = \exp(\frac{1}{T}\sum_t \log \rho_t) on long chain-of-thought rollouts.
  • Asymmetric Clipping (Clip-Higher in DAPO; Yu et al., 2025): Widens the band to [0.80, 1.28] so rare high-advantage reasoning tokens can grow faster without entropy collapse.

Group Relative Policy Optimization (GRPO)

The Complete GRPO Update

\hat{A}_j = \frac{r_j - \bar{r}}{\sigma_r + 10^{-8}}

  • Critic-free group baseline (Shao et al., 2024): Standardizes rewards across K parallel completions per prompt and optimizes the clipped surrogate minus \beta k_3.

Group Relative Policy Optimization (GRPO) (Code)

The Complete GRPO Update

def grpo_step(task, theta, K, reward, rng, beta=0.04, epsilon=0.2,
              num_epochs=4, lr=2.0):
    """One group of K responses per prompt, reused for num_epochs clipped
    ascent steps with the k3 penalty; returns theta and each epoch's ratios."""
    pi_old, n = task.policy(theta), len(task.resp)
    ys = np.stack([rng.choice(n, K, p=p) for p in pi_old])      # (prompts, K)
    A = np.stack([d2l.standardize(np.array([reward(x, y) for y in ys[x]]))
                  for x in range(len(ys))])
    rows, onehot, ratios = np.arange(len(ys))[:, None], np.eye(n)[ys], []
    for _ in range(num_epochs):
        pi = task.policy(theta)
        rho = pi[rows, ys] / pi_old[rows, ys]
        live = np.where(A > 0, rho < 1 + epsilon, rho > 1 - epsilon)
        u = live * A * rho - beta * (1 - task.pi_ref[rows, ys] / pi[rows, ys])
        theta = theta + lr * np.einsum('xk,xkn->xn', u, onehot - pi[:, None]) / K
        ratios.append(rho)
    return theta, ratios

Multi-Epoch Group Reuse in GRPO

GRPO Diagnostics

Reusing a single group of K = 32 responses per prompt for 4 epochs (grpo_step, \epsilon_{\textrm{clip}} = 0.2) lifts the exact verifier score from 0.062 (\pi_{\textrm{ref}}) to 0.111 (1 epoch) to 0.137 (4 epochs):

epoch 1: ratios from 1.00 to 1.00, 0% outside the band
epoch 2: ratios from 0.81 to 1.97, 5% outside the band
epoch 3: ratios from 0.74 to 2.23, 14% outside the band
epoch 4: ratios from 0.75 to 2.39, 30% outside the band
exact score: reference 0.062, one epoch 0.111, four epochs 0.137
  • At epoch 1 every ratio is \rho = 1.00; after the very first step, correct answers’ ratios already jump past 1.50 (> 1 + \epsilon_{\textrm{clip}}), confirming that PPO/GRPO clipping halts further gradient contribution without bounding the parameter step itself.

The k3 KL Estimator and Its Forward-KL Gradient

KL Loss Subtlety

  • Direct loss vs. reward penalty (Tang & Munos, 2025): With h = \log(\pi_\theta/\pi_{\textrm{ref}}), differentiating k_1 = h directly gives zero expected gradient, while k_2 = \frac{1}{2}h^2 (or folding h into the reward) gives the reverse-KL gradient (suppressing the hedge to 0.017).
  • Forward-KL trap of k_3 = e^{-h} + h - 1: Differentiating k_3 directly yields the forward-KL gradient \nabla_\theta D_{\textrm{KL}}(\pi_{\textrm{ref}} \Vert \pi_\theta), leaving the rare hedge unrestrained at 0.500.

Direct Preference Optimization: Inverting the Tilt

Offline Preference Learning

r(x, y) = \beta \log \frac{\pi^\star(y \mid x)}{\pi_{\textrm{ref}}(y \mid x)} + \beta \log Z(x)

  • Partition cancellation (Rafailov et al., 2023): Substituting r(x, y) into the Bradley–Terry difference r(x, y_w) - r(x, y_l) cancels \beta \log Z(x) completely.
  • Offline binary cross-entropy: Trains \pi_\theta directly on logged preference pairs (y_w \succ y_l) without a separate reward model or online rollouts.

Concept Check: Token Credit, Clipping, and Tools

Check Your Understanding

Test your understanding on three practical LLM post-training scenarios:

  1. Token Advantages on Wrong Prefixes: In our two-digit 3*4 = 12 task (uniform policy, V(x) = 0.01, V(x, 1) = 0.1, V(x, 5) = 0), what are the token advantages A(s_1, 5) and A(s_2, 2) for the wrong reply 52, versus the response weight r - V(x)?
  2. Softmax Coupling After Clipping: In GRPO with \epsilon_{\textrm{clip}} = 0.2, suppose a correct reply has \hat{A} = +2.6 and ratio \rho = 1.9 > 1.2, while a wrong reply has \hat{A} = -0.4 and \rho = 0.9 \in [0.8, 1.2]. Can the next epoch still increase the correct reply’s probability?

Answers:

  1. Response weight puts -0.01 on both digits (unfairly penalizing the 2 in the units place); token advantages give A(s_1, 5) = -0.01 and A(s_2, 2) = 0 - 0 = 0.00 (recognizing that once 5 was chosen, the failure was already sealed).
  2. Yes. Although the correct reply’s own clipped term has zero gradient, the unclipped wrong reply pushes its own logit down, which increases the correct reply’s probability through the shared softmax denominator.

Concept Check: Token Credit, Clipping, and Tools (cont.)

Check Your Understanding

  1. Masking External Tool Outputs: When an agentic LLM emits a query y^{(1)}, receives an external Python interpreter output o \sim P_{\textrm{tool}}(\cdot \mid x, y^{(1)}), and emits a final answer y^{(2)}, why must the tokens of o be masked out of \sum_t \nabla_\theta \log \pi_\theta(a_t \mid s_t)?

Answer:

  1. The tool’s transition P_{\textrm{tool}}(o \mid x, y^{(1)}) does not depend on \theta and cancels in the trajectory ratio; differentiating \log \pi_\theta(o \mid x, y^{(1)}) violates \mathbb{E}[\nabla \log \pi] = 0 and biases the model to hallucinate tool outputs.

Summary: Post-Training Methods for Language Models

Key Takeaways

Method / Variant Baseline / Critic Ratio & Clipping KL Regularization Primary Use Case & Trade-off
RLHF with PPO Token value head \hat{V}_w(s_t) + GAE Per-token \rho_t clipped at 1 \pm 0.2 Per-token -\beta \log(\pi_\theta/\pi_{\textrm{ref}}) in reward Fine-grained token credit, but requires training a separate critic LLM
GRPO (Shao et al.) Group standardization (r_j - \bar{r})/\sigma_r Per-token \rho_{j,t} clipped at 1 \pm 0.2 Direct per-token \beta k_3 loss (forward KL gradient) Saves \sim 50\% critic memory; standard for verifiable math/code reasoning
DAPO / Dr. GRPO Group mean r_j - \bar{r} (drops \sigma_r, T_j divisors) Asymmetric [0.80, 1.28] (Clip-Higher) Often \beta = 0 on exact verifiers Prevents entropy collapse on rare tokens and eliminates length bias
GSPO (Zheng et al.) Group baseline \hat{A}_j Sequence geometric mean \bar{\rho} = W^{1/T} Sequence-level KL penalty Stabilizes importance weights on very long chain-of-thought rollouts
DPO (Rafailov et al.) Implicit via paired y_w vs. y_l None (offline supervised loss) Exact reverse-KL parameterization \beta \log(\pi_\theta/\pi_{\textrm{ref}}) Fast offline preference tuning without online rollouts or reward model