Skip to content
E
Educatum

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?

Curated by Educatum AI teamLast updated:
Large Language Models (LLMs)
Direct Answer

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 πθ(yt∣x,y<t)\pi_\theta(y_t \mid x, y_{<t}) generating completion tokens yy (actions) given prompt xx (initial state), scored by a scalar reward rϕ(x,y)r_\phi(x, y) (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 πref\pi_{\text{ref}}:

max⁡θ  Ex∼D, y∼πθ(⋅∣x) ⁣[rϕ(x,y)−β DKL ⁣(πθ(⋅∣x) ∥ πref(⋅∣x))]\max_{\theta}\; \mathbb{E}_{x \sim \mathcal{D},\, y \sim \pi_\theta(\cdot \mid x)}\!\left[r_\phi(x, y) - \beta\, D_{\mathrm{KL}}\!\left(\pi_\theta(\cdot \mid x) \,\|\, \pi_{\text{ref}}(\cdot \mid x)\right)\right]

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 βDKL(πθ∥πref)\beta D_{\mathrm{KL}}(\pi_\theta \| \pi_{\text{ref}}) 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 (πθ\pi_\theta): The LLM outputting next-token probability distributions over the vocabulary given the prompt and prefix.
  • Reference Policy (πref\pi_{\text{ref}}): Frozen SFT checkpoint used to compute the per-token KL divergence penalty and curb reward hacking.
  • Policy Gradient (REINFORCE / PPO / GRPO): Optimization methods updating θ\theta via ∇θE[Alog⁡πθ(yt∣st)]\nabla_\theta \mathbb{E}[A \log \pi_\theta(y_t \mid s_t)] 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 y∼πθ(⋅∣x)y \sim \pi_\theta(\cdot \mid x), scoring them with a reward function r(x,y)r(x, y), subtracting a baseline b(x)b(x) to compute advantage A=r−bA = r - b, and adding a per-token KL penalty β(log⁡πθ−log⁡πref)\beta (\log \pi_\theta - \log \pi_{\text{ref}}), 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}")
  • 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.
View all →

Try keywords like RoPE, FlashAttention, DPO, or Blind 75.