🎉 75% of content is free forever — Unlock Premium from $10/mo →
CW
NEWSLIVESearch All Content
đŸ’ŧ Servicesâ„šī¸ Aboutâœ‰ī¸ ContactView Pricing Plansfrom $10

Reinforcement Learning for LLM Alignment

đŸŸĸ Free Lesson

Reinforcement Learning and LLM Alignment

Preference optimization is where a model stops predicting text and starts pursuing an objective — with all the hazards that implies.

Alignment

Prerequisites

  • !Supervised fine-tuning and cross-entropy loss
  • !Policy gradient intuition
  • !The RLHF pipeline at a conceptual level

What You'll Learn

  • 1Explain what supervised training cannot teach and preference optimization can
  • 2Collect preference pairs that do not encode annotator noise as signal
  • 3Describe PPO's components as they apply to text generation
  • 4Choose between PPO-style and direct preference methods for your constraints

What cross-entropy cannot teach

Supervised fine-tuning minimizes the difference between the model's next-token distribution and a reference corpus. That objective teaches form — how an answer of this type usually reads — but it is indifferent to qualities that have no single correct token. Helpfulness, harmlessness and honest uncertainty are properties of whole responses, and there is no gold sequence that embodies them.

Preference learning reframes the objective. Rather than imitating a target, the model is trained to prefer outputs that human raters favored over alternatives. The signal is comparative: this answer beats that one. Comparative judgments are dramatically more reliable than absolute ratings, and they transfer directly into an optimization objective via the reward implied by the ranking.

The consequence is a shift in what the system optimizes, and that shift is where both the gains and the risks live. Once a reward exists, the model will pursue it — including its unintended corners. Reward hacking, where the model discovers surface features that score well without being good, is not an edge case to be filtered later; it is the predictable behavior of any optimizer given an imperfect proxy. Designing around that fact is the core discipline of alignment work.

Preference data is the bottleneck

Every alignment method trains on pairs or rankings, and the quality of those pairs bounds everything downstream. Raters disagree about tone, length and how much hedging is appropriate, and that disagreement is not noise to be averaged away — it is signal about genuine ambiguity in the task.

python
def build_preference_pairs(responses, ratings, min_gap=0.5):
    """Form pairs where the rating gap justifies a preference signal."""
    pairs = []
    for i in range(len(responses)):
        for j in range(i + 1, len(responses)):
            gap = ratings[i] - ratings[j]
            if abs(gap) < min_gap:
                continue                      # too close to call
            chosen, rejected = (responses[i], responses[j]) if gap > 0 else (responses[j], responses[i])
            pairs.append({
                "prompt": responses[i]["prompt"],
                "chosen": chosen["text"],
                "rejected": rejected["text"],
                "rating_gap": abs(gap),
            })
    return pairs

def agreement_report(pairs, rater_pairs):
    """Flag pairs where two raters chose opposite winners."""
    conflicts = 0
    for pair, (r1, r2) in zip(pairs, rater_pairs):
        if r1["winner"] != r2["winner"]:
            conflicts += 1
    return {"n": len(pairs), "conflicts": conflicts, "conflict_rate": conflicts / max(len(pairs), 1)}

Collecting data with an explicit disagreement rate is more useful than pretending consensus. Pairs where raters consistently agree become high-weight training signal; pairs where they disagree can be dropped, down-weighted or used later to train a judge model that knows where the task is ambiguous.

Budget for ongoing collection rather than a single campaign. The model's behavior changes as training proceeds, and preference data gathered against the original policy grows less relevant with every update. Refreshing a slice of the pairs each cycle keeps the signal attached to the outputs the model actually produces now.

Reward models and their failure modes

A reward model is trained on the same pairs to assign scalar scores that preserve the observed rankings. It is a proxy, and proxies drift. Length bias — preferring longer answers regardless of quality — is the most documented failure, along with sycophancy, where the model learns to flatter because raters subtly favored agreeable answers.

python
import torch
import torch.nn as nn

class RewardModel(nn.Module):
    """Scalar scorer over a backbone, trained to rank chosen above rejected."""

    def __init__(self, backbone):
        super().__init__()
        self.backbone = backbone
        self.head = nn.Linear(backbone.config.hidden_size, 1)

    def forward(self, input_ids, attention_mask):
        hidden = self.backbone(
            input_ids=input_ids, attention_mask=attention_mask
        ).last_hidden_state
        last = hidden[:, -1, :]                 # score from the final token
        return self.head(last).squeeze(-1)

def preference_loss(chosen_scores, rejected_scores):
    """Bradley-Terry style loss: chosen should outscore rejected."""
    return -torch.nn.functional.logsigmoid(chosen_scores - rejected_scores).mean()

Evaluate the reward model before trusting it: check whether its scores correlate with length when quality is held constant, whether it rewards confident falsehoods over correct hedged answers, and whether it can be steered by formatting tricks. A reward model that fails these checks will faithfully teach those failures to the policy.

PPO for language models

Proximal policy optimization adapts the classical RL loop to text. The policy is the language model; the environment is the conversation; the reward comes from the reward model at the end of a generation. A KL penalty against the supervised policy keeps the model from wandering into text that scores well under the reward model but reads like nonsense.

python
def ppo_update(policy, ref_policy, reward_model, queries, ppo_epochs=4):
    """One PPO iteration, with KL anchoring to the supervised policy."""
    responses = policy.generate(queries)
    rewards = reward_model(responses) - KL_COEF * kl_divergence(
        policy.logprobs(responses), ref_policy.logprobs(responses)
    )

    values = critic(responses)
    advantages = rewards - values
    advantages = (advantages - advantages.mean()) / (advantages.std() + 1e-8)

    for _ in range(ppo_epochs):
        ratio = torch.exp(policy.logprobs(responses) - old_logprobs)
        clipped = torch.clamp(ratio, 1 - EPS, 1 + EPS)
        loss = -torch.min(ratio * advantages, clipped * advantages).mean()
        loss.backward()
        optimizer.step()
        optimizer.zero_grad()

The KL coefficient is the most consequential hyperparameter in the run. Too little, and the policy drifts into degenerate text that games the reward model. Too much, and optimization stalls and you have paid for a supervised run with extra steps. Watch both the mean reward and the KL estimate: rising reward with rising KL is the signature of drift, not progress.

Direct preference methods

Direct preference optimization removes the separate reward model and the RL loop entirely, optimizing the policy directly on preference pairs with a closed-form objective derived from the same Bradley-Terry assumptions. The practical gains are large: far fewer hyperparameters, no critic, no reward model to hack, and training that behaves like supervised fine-tuning.

python
from trl import DPOTrainer, DPOConfig

def train_dpo(base_model, tokenizer, preference_dataset):
    """Direct preference optimization — supervised-training simplicity."""
    config = DPOConfig(
        output_dir="./dpo",
        per_device_train_batch_size=4,
        gradient_accumulation_steps=8,
        learning_rate=5e-7,
        beta=0.1,                    # KL strength; lower drifts further
        max_length=1024,
        max_prompt_length=512,
        bf16=True,
        num_train_epochs=1,
    )
    trainer = DPOTrainer(
        model=base_model,
        args=config,
        train_dataset=preference_dataset,
        processing_class=tokenizer,
    )
    trainer.train()
    return trainer.model

The beta parameter controls the same tension the KL coefficient handled in PPO. Direct methods trade some of PPO's flexibility — no custom reward composition, no per-token shaping — for stability that most teams find worth it. Reach for PPO-style optimization only when you have a genuinely non-preference reward, such as verifiable correctness on math or code, that preference pairs cannot capture.

Trading helpfulness against safety

Alignment work almost always involves competing objectives, and the way they are combined decides the product's personality. A common setup scores helpfulness and harmlessness separately, then blends them with a weight that has to be chosen by someone. That weight is not a technical constant — it is a product policy that determines how often the assistant refuses a legitimate request in order to avoid a risky one.

python
def blend_rewards(helpful, harmless, w_helpful=0.6):
    """Combine objectives; the weight is a policy decision, not a default."""
    return w_helpful * helpful + (1 - w_helpful) * harmless

def report_tradeoff(scores, thresholds):
    """Show the operating point instead of a single blended number."""
    return {
        "helpful_mean": float(np.mean(scores["helpful"])),
        "harmless_mean": float(np.mean(scores["harmless"])),
        "refusal_rate": float(np.mean(scores["refused"])),
        "over_refusal": float(np.mean(scores["refused_but_benign"])),
        "under_refusal": float(np.mean(scores["allowed_but_harmful"])),
        "within_policy": bool(
            np.mean(scores["refused_but_benign"]) <= thresholds["over_refusal_max"]
            and np.mean(scores["allowed_but_harmful"]) <= thresholds["under_refusal_max"]
        ),
    }

Track over-refusal and under-refusal as separate numbers rather than collapsing them. A team that only watches the blended score cannot tell whether a new preference run improved alignment or simply made the model more timid — and timidity reads as improvement on many automatic safety rubrics.

Reward hacking in practice

Once a reward exists, look for the model exploiting it. Common signatures include answers that grow longer without becoming more informative, preambles that announce compliance with the rubric, refusal patterns that dodge hard questions under the guise of safety, and excessive formatting that pattern-matched to rater preference.

SignalWhat it may indicateFirst response
Reward up, human preference flatReward hackingAudit high-reward samples
Response length trending upLength bias in reward modelLength-normalize scoring
Refusal rate rising on benign promptsOver-regularizationReview refusal-labeled pairs
Formatting polish up, content flatSycophancy to rater tasteRecalibrate rating guidelines

The most reliable detector remains human review of the highest-reward samples each checkpoint. If the top-scoring outputs look strange to a person, the reward model is steering the policy somewhere you did not intend — and no automatic metric will tell you that as clearly as reading twenty samples.

âš ī¸Reward models drift as policies improve

A reward model trained on human preferences becomes less reliable as the policy surpasses the data those preferences came from. Budget for periodic re-annotation against the current policy's outputs.

Common Mistakes

Launching RLHF on preference data with no inter-rater agreement analysis

Fix: Measure agreement first; down-weight or drop pairs where raters consistently disagree.

Treating rising mean reward as proof the policy improved

Fix: Track KL divergence and audit the highest-reward samples — drift often masquerades as progress.

Choosing PPO because it sounds more rigorous than DPO

Fix: Default to direct preference methods; reach for PPO only when rewards are non-preference and verifiable.

Ignoring length as a confound in both rating and evaluation

Fix: Normalize for length in reward scoring and include length-controlled comparisons in evaluation.

Best Practices

  • Invest in preference data quality before investing in optimization algorithms
  • Evaluate the reward model on length, sycophancy and formatting bias before training a policy
  • Monitor KL divergence alongside reward so drift is visible in real time
  • Prefer direct preference optimization unless a custom reward is genuinely required
  • Keep a human review loop on high-reward samples at every checkpoint

Key Takeaways

  • Preference optimization teaches response-level qualities that cross-entropy cannot express
  • Pair quality and rater agreement bound everything downstream of the alignment stage
  • Reward models are proxies with known failure modes — audit them before training on them
  • PPO needs a KL anchor; DPO replaces the whole machinery with a supervised-style objective
  • Reward hacking is predictable, so monitor high-reward samples rather than trusting the scalar
CW

ChatWhole Learn Editorial Team

Written by experienced data scientists, software engineers, and educators. All content is reviewed by industry professionals to ensure accuracy and relevance.

Last reviewed: 2026-10-12

—
☆☆☆☆☆
0 ratings

Rate & Feedback

Need Expert Generative AI Help?

Get personalized tutoring, project support, or professional consulting.

Advertisement