Building an RLHF Alignment Training Pipeline from Scratch

    Learn how to build a large language model alignment pipeline using supervised fine-tuning, reward modeling, and reinforcement learning from human feedback (RLHF). This article covers data design, pairwise preference learning, KL-constrained policy optimization, evaluation, cloud infrastructure, and common failure modes, with a focus on how the three training stages work together.

    1. The Starting Point: The Gap Between Pretraining and User Intent

    Large-scale self-supervised pretraining optimizes for next-token prediction. Its objective maximizes likelihood over a training corpus—not whether an answer is helpful, harmless, or honest. This creates a structural mismatch: a model tends to produce fluent text that reflects common patterns in its data, but it may fail to follow instructions, acknowledge uncertainty, or correct its mistakes.

    Alignment addresses this mismatch. A common approach is to leave the pretraining objective unchanged and add a post-training process that uses human preferences as supervision. Reinforcement learning from human feedback (RLHF) is one of the most representative approaches.

    RLHF is not an exclusive feature of any particular product. It is a widely used technique for post-training large language models. Its central value is turning the difficult-to-formalize judgment of “what makes a good answer” into a numerical signal that can be learned and optimized.

    2. The Three-Stage Alignment Pipeline

    A typical RLHF pipeline consists of three sequential stages, with each stage supplying inputs to the next:

    1. Supervised fine-tuning (SFT): Train a base model on high-quality instruction–response pairs written or selected by humans so that it learns conversation formats and instruction following.
    2. Reward modeling: Collect human comparisons between candidate responses to the same instruction and train a model that assigns a scalar reward.
    3. Reinforcement learning (RL): Optimize the policy model against the learned reward, using a KL-divergence constraint to limit how far it moves from the SFT model.

    In short, SFT establishes the starting point, the reward model defines the direction, and reinforcement learning determines how to improve without drifting too far.

    3. Stage One: Supervised Fine-Tuning and Annotation Design

    SFT strongly shapes the quality that the alignment pipeline can achieve. Improving data quality often provides greater marginal value than simply increasing dataset size. Common practices include:

    • Instruction diversity: Cover question answering, summarization, rewriting, code generation, logical reasoning, and refusal tasks. Avoid building a model that performs well only on one type of interaction.
    • Response quality tiers: Have annotators write demonstration responses or select the best responses from multiple candidates. Prioritize information-rich answers without unnecessary pleasantries or repetition.
    • Refusal and uncertainty examples: Explicitly include responses such as “I don’t know” and “This request is beyond my capabilities.” These examples help teach the model to acknowledge limitations and support error correction at inference time.
    • Consistent formatting: Standardize conversation templates and role markers. Inconsistent templates can contaminate the input distribution used in subsequent reward-model training.

    A minimal data record might look like this:

    1. {
    2. "instruction": "Explain why database indexes speed up queries",
    3. "response": "An index replaces a full table scan with a lookup in an ordered structure...",
    4. "meta": {"task_type": "explanation", "quality": "expert_written"}
    5. }

    4. Stage Two: Turning Preferences into Scalar Rewards

    People often struggle to assign an exact score such as “0.73” to an answer, but can more readily judge whether response A is better than response B. Reward modeling therefore commonly uses pairwise comparisons.

    For each instruction, sample K responses and ask annotators to rank them or compare them in pairs. This produces preference pairs (y_w, y_l), where y_w is the preferred response and y_l is the less-preferred response.

    The training objective encourages the reward model to give the preferred response a higher score. A common formulation is the pairwise logistic loss:

    1. loss = -E[ log sigmoid( r(x, y_w) - r(x, y_l) ) ]

    Here, x is the instruction and r(x, y) is the reward assigned to a response.

    Key engineering considerations include:

    • Reward-model size: The reward model is often comparable in scale to the policy model or somewhat smaller. An oversized model increases scoring costs; an undersized model may produce noisy reward signals.
    • Annotation consistency: Use multiple annotators and agreement checks. Samples with substantial disagreement should be removed or down-weighted.
    • Reward hacking: The policy may exploit weaknesses in the reward model by producing longer answers, more lists, or more flattering language. Mitigations include length normalization, formatting penalties, and periodic reward-model retraining with fresh preference data.

    5. Stage Three: Constrained Policy Optimization

    The reinforcement learning stage treats language generation as sequential decision-making. The state is the generated prefix, the action is the next token, and the reward model supplies a reward when the sequence is complete.

    The objective is commonly written as:

    1. maximize E[ r(x, y) ] - β * KL( π(y|x) || π_ref(y|x) )

    Here, π_ref is the frozen SFT reference model, and β controls the strength of the constraint. The KL term is central to training stability:

    • If β is too small: The policy may aggressively exploit the reward model, leading to repetitive output, excessive verbosity, or degraded instruction following.
    • If β is too large: The policy changes very little, limiting alignment gains.
    • In practice: PPO clipping is often combined with advantage normalization and reward whitening. Clipping importance ratios relative to the old sampling policy helps prevent excessively large updates.

    The following schematic pseudocode illustrates the training loop. Reference-policy refresh is shown as an optional periodic step; between refreshes, the reference remains frozen.

    1. for step in range(N):
    2. batch = sample_prompts()
    3. y = policy.generate(batch) # Sample responses
    4. r = reward_model.score(batch, y) # Scalar rewards
    5. kl = beta * per_token_kl(policy, ref, y) # Per-token constraint
    6. loss = ppo_clipped_loss(policy, old, y, r - kl)
    7. loss.backward(); optimizer.step()
    8. if step % M == 0: refresh_reference() # Periodically refresh the reference policy

    Beyond PPO, direct preference optimization methods are also being explored. These approaches do not require an explicit reward model, but still rely on pairwise preference data. They combine reward modeling and policy optimization into a single training stage.

    When choosing an approach, consider three factors: training stability, GPU memory and compute requirements, and sensitivity to the amount of preference data available.

    6. Evaluation: Reward Scores Are Not Enough

    A rising reward score does not necessarily mean a better user experience. Evaluation should cover at least four categories:

    • Automated metrics: Task accuracy, format compliance, and appropriate refusal rates.
    • Model-based evaluation: Use a stronger model to score responses against a rubric, while controlling for position bias.
    • Human evaluation: Small-scale blind comparisons and win rates provide the final check.
    • Safety regression testing: Run the full regression suite for jailbreak prompts, harmful requests, and privacy leakage at every evaluation cycle.

    Also monitor signs of degradation. A sudden increase in average response length, higher repetition rates, or an unusual concentration of particular sentence patterns may be outward signs of reward hacking.

    7. Cloud Infrastructure for Deployment

    Building an entire pipeline in-house can be expensive. Teams can lower the operational burden by combining general-purpose cloud infrastructure:

    • Container platforms: Run distributed training workloads and support elastic scaling.
    • Object storage: Manage versioned training corpora and model checkpoints.
    • Message queues: Decouple annotation tasks from training jobs.
    • Logging, monitoring, and alerting: Track reward curves, KL divergence, and GPU memory usage.
    • Data annotation services: Organize preference collection and annotator agreement checks.

    Platforms such as Baidu AI Cloud offer these general infrastructure categories and may be considered as potential foundations for such a pipeline. Specific service availability, specifications, and pricing should be checked in the official documentation rather than assumed to apply across regions.

    8. Common Failure Modes

    Symptom Likely cause Corrective direction
    Responses become longer and more verbose Reward is strongly correlated with response length Apply length normalization or add a penalty
    Instruction following deteriorates β is too small or policy updates are too large Increase β and tighten the clipping range
    Refusal rates rise unexpectedly Too many refusal examples in SFT, or an overly conservative reward model Rebalance the data mix
    Training becomes unstable or collapses Unnormalized advantages or drifting reward scales Apply reward whitening and gradient clipping
    Responses converge on a single phrasing pattern Preference data comes from a narrow range of sources Diversify annotator backgrounds and task types

    9. Conclusion

    Human-feedback alignment turns a subjective notion of “good” into an optimizable signal through a three-stage pipeline: data sets the foundation, rewards define the direction, and constraints limit drift.

    Understanding how these stages interact matters more than memorizing any single algorithm. Many production failures arise from distribution mismatches between stages rather than from an incorrect formula. A reliable pipeline therefore depends on treating data preparation, reward modeling, policy optimization, and evaluation as a connected system.