How can reinforcement learning be integrated into the training of large language models, and what challenges might arise in selecting suitable loss functions for RL-based approaches?
Reinforcement learning treats the autoregressive LLM as a stochastic policy that generates token sequences evaluated by a learned reward model or programmatic verifier. Because discrete token sampling and sequence-level rewards are non-differentiable, policy gradient algorithms like PPO or GRPO optimize expected reward regularized by a KL penalty against the reference SFT policy. Key loss-design challenges include high gradient variance, sparse credit assignment, and reward hacking.
Study Card: Integrating Reinforcement Learning into LLM Training
Direct Answer
In Reinforcement Learning from Human Feedback (RLHF) or RL with Verifiable Rewards (RLVR), a supervised fine-tuned (SFT) LLM acts as a policy generating completion tokens (actions) given prompt (initial state), scored by a scalar reward (from a preference-trained reward model or a deterministic verifier for math/code). The standard KL-regularized RL objective maximizes expected reward while preventing drift from the SFT reference policy :
Because discrete token sampling (argmax/multinomial) and sequence-level evaluators are non-differentiable, optimization relies on policy gradients (REINFORCE, PPO, or GRPO) rather than standard cross-entropy. Key challenges in designing RL losses include:
- Reward Hacking (Goodhart’s Law): Policies exploit flaws in a proxy reward model (e.g., verbosity bias, sycophancy, formatting tricks), making the KL penalty essential to anchor fluency and knowledge.
- High Gradient Variance & Instability: Raw REINFORCE gradients have high variance across long completions; PPO mitigates this with clipped importance ratios and a learned value baseline (GAE), while GRPO uses group-normalized rewards across multiple rollouts per prompt.
- Sparse Credit Assignment: Assigning a single terminal sequence reward to every token requires careful advantage estimation or per-token KL shaping.
Key Terms
- Policy (): The LLM outputting next-token probability distributions over the vocabulary given the prompt and prefix.
- Reference Policy (): Frozen SFT checkpoint used to compute the per-token KL divergence penalty and curb reward hacking.
- Policy Gradient (REINFORCE / PPO / GRPO): Optimization methods updating via without differentiating through the reward function or sampling step.
- Reward Hacking: Achieving high proxy reward scores while degrading true human quality or truthfulness.
- Direct Preference Optimization (DPO): An RL-free offline objective that derives an analytical policy-reward mapping to optimize preference pairs directly via binary cross-entropy.
Example
When aligning an LLM to write concise, accurate summaries or solve math problems, supervised next-token loss treats all token mistakes equally and cannot directly optimize non-differentiable criteria like unit-test pass rate or human pairwise preference. By sampling rollouts , scoring them with a reward function , subtracting a baseline to compute advantage , and adding a per-token KL penalty , the policy increases the log-probability of high-advantage completions without collapsing its language distribution.
Code Implementation
import copy
import torch
import torch.nn as nn
import torch.nn.functional as F
from torch.distributions import Categorical
torch.manual_seed(0)
# Minimal toy autoregressive token policy (vocab=10, prompt len=3, gen len=4)
class ToyCausalPolicy(nn.Module):
def __init__(self, vocab_size=10, hidden_dim=32):
super().__init__()
self.embed = nn.Embedding(vocab_size, hidden_dim)
self.gru = nn.GRU(hidden_dim, hidden_dim, batch_first=True)
self.head = nn.Linear(hidden_dim, vocab_size)
def forward(self, input_ids):
h, _ = self.gru(self.embed(input_ids))
return self.head(h) # (B, T, V)
def verifiable_reward(generated_tokens: torch.Tensor) -> torch.Tensor:
# Example reward: encourage higher token IDs (e.g., >= 5) while staying concise
return (generated_tokens >= 5).float().mean(dim=-1) # (B,)
policy = ToyCausalPolicy()
ref_policy = copy.deepcopy(policy).eval()
for p in ref_policy.parameters():
p.requires_grad = False
optimizer = torch.optim.AdamW(policy.parameters(), lr=1e-3)
prompt = torch.randint(0, 10, (16, 3))
beta_kl = 0.05
gen_steps = 4
for step in range(5):
# 1. Sample completion tokens without building a graph through discrete sampling
seq = prompt.clone()
with torch.no_grad():
for _ in range(gen_steps):
next_logits = policy(seq)[:, -1, :]
next_tok = Categorical(logits=next_logits).sample().unsqueeze(-1)
seq = torch.cat([seq, next_tok], dim=-1)
gen_tokens = seq[:, prompt.size(1):]
rewards = verifiable_reward(gen_tokens)
advantages = rewards - rewards.mean() # Group/batch baseline reduces variance
# 2. Recompute log-probs WITH gradients on the generated suffix only
logits = policy(seq)[:, prompt.size(1) - 1:-1, :]
log_probs = F.log_softmax(logits, dim=-1)
action_log_probs = log_probs.gather(-1, gen_tokens.unsqueeze(-1)).squeeze(-1)
with torch.no_grad():
ref_logits = ref_policy(seq)[:, prompt.size(1) - 1:-1, :]
ref_log_probs = F.log_softmax(ref_logits, dim=-1)
ref_action_log_probs = ref_log_probs.gather(-1, gen_tokens.unsqueeze(-1)).squeeze(-1)
# 3. KL-regularized policy gradient loss
kl_per_token = action_log_probs - ref_action_log_probs
pg_loss = -(advantages.unsqueeze(-1) * action_log_probs).mean() + beta_kl * kl_per_token.mean()
optimizer.zero_grad()
pg_loss.backward()
optimizer.step()
print(f"Step {step+1} | Mean Reward: {rewards.mean():.3f} | Loss: {pg_loss.item():.4f}")
Related Concepts
- PPO vs. GRPO: PPO trains a critic/value network to estimate per-token advantages; GRPO removes the critic by sampling a group of completions per prompt and normalizing rewards within the group.
- DPO (Direct Preference Optimization): Optimizes pairwise chosen vs. rejected responses directly without online rollouts or a separate reward model.
- Process vs. Outcome Reward Models (PRM vs. ORM): Step-level vs. final-answer supervision for multi-step reasoning tasks.
- RL with Verifiable Rewards (RLVR): Using deterministic checkers (math grading, code unit tests) to eliminate proxy reward-model hacking.