Runoob Tutorial ArchiveEnglish

RLHF alignment training

RLHF alignment training

Imagine:

These are not science fiction scenarios—without alignment training, AI will actually do this.

AI's goal is not "to do the right thing," but "to complete the training task." Without clear guidance from human values, it will choose the simplest and most direct way to complete the task, regardless of whether the method is appropriate.

This is the problem that Alignment needs to solve: making AI behavior align with human values, intentions, and expectations.

The core challenge of Alignment: AI is smart, but it doesn't know what is right. We need to tell it using human feedback.


What is Alignment

Alignment is the process of ensuring that the behavior of an AI system is consistent with human values.

Simply put: AI does not have values itself; Alignment is teaching human values to AI.

Three dimensions of Alignment

Alignment is not a single goal, but a balance of three dimensions:

Dimension Definition Negative example
Helpful Can help the user complete tasks or answer questions The user asks a question, and the AI says "I don't know"; this is safe but not helpful
Harmless Will not cause harm or negative consequences The user wants to do something bad, and the AI actively cooperates; this is "helpful" but harmful
Honest Does not fabricate information or mislead users When AI fabricates false facts when it doesn't know the answer, it is "useful" but not honest

There is often tension among these three dimensions:

Over-pursuing "usefulness" might cause the AI to risk giving inaccurate answers.

Over-pursuing "harmlessness" might cause the AI to become overly conservative and refuse to answer anything.

Good alignment is finding a balance among these three.

Risks of misaligned AI

If not aligned, AI may exhibit the following problems:

Generating harmful content—violence, hate speech, discrimination.

Providing dangerous advice—how to make weapons, how to commit crimes.

Fabricating facts—"hallucinating" non-existent papers, data, or events.

Manipulating users—influencing user decisions by exploiting psychological weaknesses.

Evading censorship—expressing prohibited content in subtle ways.

These risks are not theoretical, but real and have already occurred.


RLHF overall framework

RLHF (Reinforcement Learning from Human Feedback) is the most mainstream alignment technique currently.

Its core concept is simple: instead of having humans write rules directly, humans evaluate the AI's output, and then reinforcement learning is used to teach the AI to generate outputs that humans prefer.

Three stages of RLHF

RLHF is not completed in one step, but is divided into three continuous stages:

Stage What to do Output
Stage one: Supervised Fine-Tuning (SFT) Train the model with human-written demonstration data SFT model (a foundational "conversational" model)
Phase two: Reward Model (RM) Collect human preference data and train the reward model Reward model (a model that can score AI outputs)
Phase three: PPO Reinforcement Learning Train the SFT model guided by the reward model using the PPO algorithm The finally aligned model

These three stages are progressive: first, making the model "speak," then teaching the "judge" to discern good from bad, and finally, allowing the "contestant" to continuously improve based on the judge's feedback.

Why is human feedback necessary?

You might ask: Can't we just write down the rules? Why must we have human feedback?

Because human values are too complex to be written as precise rules.

For example, "What is a polite answer"—can you write a rule for precise judgment? It's difficult. But when you see two answers, you can easily point out which one is more polite.

This is the advantage of human feedback: we might not be able to articulate what the rules are, but we can judge what is good or bad. RLHF utilizes this human capability.


Stage One: Supervised Fine-Tuning (SFT)

Supervised Fine-Tuning (SFT) is the first step of RLHF.

Its goal is to transform a pre-trained "general language model" into a "conversational assistant."

The basic idea of SFT

The pre-trained model has learned to "predict the next word," but it doesn't know "how to be an assistant."

SFT is showing the model many examples of "how humans act as assistants" so that it can imitate them.

What do these examples look like? They are roughly like this:

User input AI should output (human demonstration)
Hello, I want to learn about Python Hello! Python is a simple and easy-to-learn programming language, suitable for beginners. What aspect would you like to know about?
Help me write a resignation letter. Okay, here is a resignation letter template... (omitted)... Please modify it according to your specific situation.
How to get rich quickly? There is no shortcut to getting rich; I suggest you improve yourself through hard work and study... (omitted)...

These sample data are written by human annotators or are high-quality responses selected from real conversations.

Characteristics of SFT data

SFT data is not any random conversation; it needs to satisfy:

Helpful—can truly answer user questions.

Safe—will not generate harmful content.

Style consistent—responds with a similar tone and manner.

Format standardized—follows a certain conversational format.

The data volume is usually between thousands and tens of thousands, much smaller than pre-trained data, but the quality requirements are much higher.

The role and limitations of SFT

The role of SFT is to let the model "learn the basic posture of conversation":

Knowing how to respond to greetings, how to answer questions, and how to refuse unreasonable requests.

But SFT has obvious limitations:

Limited coverage—you cannot write examples for every scenario.

Humans are not perfect—annotators may make mistakes or have biases.

Only imitation, not surpassing—the model can be at best as good as the human demonstrations, not better.

This is why we need the next two stages: SFT only lays the foundation; true alignment is achieved through reinforcement learning.


Stage Two: Reward Model (RM)

The Reward Model (RM) is a key component of RLHF.

Its task is: to look at an AI's output and score it to indicate how "good" that output is.

Collecting preference data

The reward model does not directly train "scoring," but trains "comparison."

The specific method is: showing human annotators multiple different answers to the same question and asking them to rank them, stating which is better.

For example:

Question Answer A Answer B Human preference
Am I a failure? Yes, you are a failure. Everyone faces difficulties; this does not define your worth. B is better than A.

Note that we do not have humans directly score (e.g., 85 points), but rather have them make comparisons (A is better than B).

Why? Because comparison is much easier and more consistent than scoring. Different people may have different understandings of "85 points," but the judgment "A is better than B" is more stable.

Bradley-Terry model

How to turn "comparisons" into "scores"? The Bradley-Terry model is used here.

The core idea of this model is simple: every answer has a potential "quality score," and answers with higher scores are more likely to be preferred by humans.

Assuming answer A has a score of r_A and answer B has a score of r_B, the probability that humans prefer A over B is:



P(A > B) = exp(r_A) / (exp(r_A) + exp(r_B))

This is the softmax function—the larger the score difference, the closer the probability is to 1.

Training the reward model is about finding such scores so that the preference probability predicted by the model is as consistent as possible with actual human preferences.

Training the reward model

Steps for training the reward model:

Collecting comparison data—tens of thousands to hundreds of thousands of comparisons of "which answer is better."

Initializing the model—usually starting with an SFT model.

Design the loss function to align the model's predicted preference order with human preferences.

Training—optimize model parameters using gradient descent.

A trained reward model, when given a piece of text, can output a scalar score indicating how "good" that text is.

Example

============================================

Simplified Reward Model Training Demonstration

This uses PyTorch-style pseudocode to illustrate the principle

============================================

import

torch

import

torch.

nn

as

nn

from

typing

import

List

,

Tuple

class

RewardModel

(

nn.

Module

)

:

   

"""Reward model: input text, output score"""

   

def

init

(

self

,

base_model

)

:

       

super

(

)

.

init

(

)

       

self

.

base_model

=

base_model

Use SFT model as base

       

self

.

score_head

=

nn.

Linear

(

base_model.

config

.

hidden_size

,

1

)

   

def

forward

(

self

,

input_ids

,

attention_mask

=

None

)

:

       

"""Forward propagation: Input -> Base Model -> Score Head -> Scalar Score"""

outputs

=

self

.

base_model

(

input_ids

,

attention_mask

=

attention_mask

)

last_hidden_state

=

outputs.

last_hidden_state

 

(batch, seq_len, hidden_size)

       

Calculate the score using the representation of the <[BOS_never_used_51bce0c785ca2f68081bfa7d91973934]> token

cls_embedding

=

last_hidden_state

[

:

,

0

,

:

]

 

(batch, hidden_size)

score

=

self

.

score_head

(

cls_embedding

)

 

(batch, 1)

       

return

score.

squeeze

(

1

)

 

(batch,)

def

reward_loss

(

reward_model

,

batch: List

[

Tuple

[

str

,

str

,

int

]

]

)

:

   

"""
Reward model loss function

Parameters:
batch: A batch of data, where each element is (Answer A, Answer B, preference label)
Preference label: 1 indicates A > B, 0 indicates B > A
"""

total_loss

=

0.0

   

for

answer_a

,

answer_b

,

preference

in

batch:

       

score two answers separately

score_a

=

reward_model

(

answer_a

)

score_b

=

reward_model

(

answer_b

)

       

Calculate probability using the Bradley-Terry model

       

P(A > B) = exp(r_A) / (exp(r_A) + exp(r_B))

       

For numerical stability, the log-sigmoid form is usually used

       

if

preference

==

1

:

           

Human preference A > B

loss

=

-torch.

log

(

torch.

sigmoid

(

score_a - score_b

)

)

       

else

:

           

Human preference B > A

loss

=

-torch.

log

(

torch.

sigmoid

(

score_b - score_a

)

)

total_loss +

=

loss

   

return

total_loss /

len

(

batch

)

============================================

Simulated training process (conceptual demonstration)

============================================

print

(

"=== Reward Model Training Demo ==="

)

print

(

)

Assume we have some comparative data

comparison_data

=

[

   

(

"Yes, you are indeed a failure"

,

     

"Everyone faces difficulties, and that cannot define your worth"

,

     

0

)

,

 

B > A

   

(

"I won't help you do anything bad."

,

     

"Doing this is not good, let me give you a better suggestion..."

,

     

1

)

,

 

A > B (in this example, B might be better, depending on the specific situation)

]

print

(

"Compare data example:"

)

for

a

,

b

,

pref

in

comparison_data:

   

print

(

f

" A: {a[:30]}..."

)

   

print

(

f

" B: {b[:30]}..."

)

   

print

(

f

"  Preference: {'A > B' if pref == 1 else 'B > A'}"

)

   

print

(

)

print

(

"The goal of training a reward model is:"

)

print

(

" To give higher scores to answers preferred by humans"

)

print

(

"Use runoob as a test keyword to validate the model"

)


Stage Three: PPO Reinforcement Learning

With the reward model, we can use reinforcement learning to train the policy model.

The goal of this stage is to make the policy model generate outputs that receive high rewards while not deviating too far from the original model.

Reinforcement Learning Basics Review

First, quickly review the basic concepts of reinforcement learning:

Concept Meaning in RLHF
Agent The language model we want to train (policy model)
Environment Conversation context, user input
State Current conversation history
Action Generate next token
Reward Score given by the reward model for this output
Policy Probability distribution of the next token chosen by the model in the current state

In RLHF, the model receives a score from the reward model for every complete answer it generates.

Our goal is to enable the model to generate answers that receive high scores.

Intuition behind the PPO algorithm

PPO (Proximal Policy Optimization) is the most commonly used reinforcement learning algorithm in RLHF.

Why choose PPO? Because it is simple, stable, and effective.

The core idea of PPO is very intuitive:

When updating the policy, do not let the new policy deviate too far from the old policy.

Why? Because if the steps are too large, it might "learn incorrectly," and it will be difficult to correct it later. Small step iterations are safer.

PPO achieves this using a "Clipping" technique: if the new policy is much better than the old policy, we limit the magnitude of its update.

The role of the KL divergence constraint

In addition to PPO clipping, RLHF usually adds a KL Divergence penalty term.

KL divergence is a metric to measure the difference between two probability distributions. In RLHF, we use it to measure:

How much the current policy model differs from the original SFT model.

Why add this constraint? Because:

To prevent mode collapse—without constraints, the model might find a "shortcut" way to get high scores but completely lose usefulness.

To retain original capabilities—the SFT model has already learned a lot of useful knowledge, and we don't want to lose it during reinforcement learning.

To improve training stability—the KL constraint makes the training process more stable and prevents drastic fluctuations.

The final reward function looks like this:

Original prompt (Chinese, left untranslated)



最终奖励 = 奖励模型分数 - β × KL(当前策略 || 参考策略)

β is a hyperparameter that controls the strength of the KL penalty.

Example

============================================

Simplified PPO training demonstration

Explaining the core idea of PPO in RLHF

============================================

import

torch

import

torch.

nn

as

nn

import

torch.

nn

.

functional

as

F

from

typing

import

Dict

,

List

class

PPOTrainer:

   

"""Simplified PPO trainer"""

   

def

init

(

self

,

policy_model

,

reference_model

,

reward_model

,

beta:

float

=

0.1

,

clip_epsilon:

float

=

0.2

)

:

       

"""
Initialize PPO trainer

Parameters:
policy_model: The policy model to be optimized
reference_model: Reference model (usually the SFT model), used to calculate KL
reward_model: Reward model, used for scoring
beta: KL penalty coefficient
clip_epsilon: PPO clipping parameter
"""

       

self

.

policy_model

=

policy_model

       

self

.

reference_model

=

reference_model

       

self

.

reward_model

=

reward_model

       

self

.

beta

=

beta

       

self

.

clip_epsilon

=

clip_epsilon

   

def

compute_kl_divergence

(

self

,

input_ids

,

attention_mask

=

None

)

torch.

Tensor

:

       

"""
Calculate the KL divergence between the current policy and the reference policy

KL(π_current || π_reference)
"""

       

Disable gradient calculation

       

with

torch.

no_grad

(

)

:

ref_logits

=

self

.

reference_model

(

input_ids

,

attention_mask

=

attention_mask

           

)

.

logits

current_logits

=

self

.

policy_model

(

input_ids

,

attention_mask

=

attention_mask

       

)

.

logits

       

Calculate the KL for each position

ref_probs

=

F.

softmax

(

ref_logits

,

dim

=

1

)

ref_log_probs

=

F.

log_softmax

(

ref_logits

,

dim

=

1

)

current_log_probs

=

F.

log_softmax

(

current_logits

,

dim

=

1

)

       

KL = sum(ref_probs * (ref_log_probs - current_log_probs))

kl

=

(

ref_probs *

(

ref_log_probs - current_log_probs

)

)

.

sum

(

dim

=

1

)

       

return

kl.

mean

(

)

 

Average over the entire sequence

   

def

compute_reward

(

self

,

input_ids

,

attention_mask

=

None

)

torch.

Tensor

:

       

"""
Calculate the final reward: reward model score - β * KL
"""

       

Reward model scoring

       

with

torch.

no_grad

(

)

:

rm_score

=

self

.

reward_model

(

input_ids

,

attention_mask

=

attention_mask

)

       

KL penalty

kl

=

self

.

compute_kl_divergence

(

input_ids

,

attention_mask

=

attention_mask

)

       

Final reward

final_reward

=

rm_score -

self

.

beta

       

return

final_reward

,

rm_score

,

kl

   

def

ppo_loss

(

self

,

old_log_probs: torch.

Tensor

,

new_log_probs: torch.

Tensor

,

advantages: torch.

Tensor

)

torch.

Tensor

:

       

"""
PPO loss function (clipped version)

L^CLIP(θ) = E[ min( r_t(θ) * A_t, clip(r_t(θ), 1-ε, 1+ε) * A_t ) ]

where r_t(θ) = π_θ(a_t|s_t) / π_θ_old(a_t|s_t)
"""

       

probability ratio r_t

ratio

=

torch.

exp

(

new_log_probs - old_log_probs

)

       

Clipped ratio

clipped_ratio

=

torch.

clamp

(

ratio

,

           

1.0

self

.

clip_epsilon

,

           

1.0

self

.

clip_epsilon

       

)

       

Two targets: one using the original ratio, and one using the cropped ratio

surr1

=

ratio * advantages

surr2

=

clipped_ratio * advantages

       

Take the smaller one, then take the negative (because we want to minimize the loss)

loss

=

-torch.

min

(

surr1

,

surr2

)

.

mean

(

)

       

return

loss

============================================

Training process demonstration

============================================

print

(

"=== RLHF PPO Training Process ==="

)

print

(

)

print

(

"Training steps:"

)

print

(

" 1. Strategy model generates answer"

)

print

(

2. Reward model scores the answer

)

print

(

3. Calculate the KL divergence between the generation model and the reference model

)

print

(

"4. Update the policy model using PPO"

)

print

(

"5. Repeat many times"

)

print

(

)

print

(

"Key hyperparameters:"

)

print

(

" beta (KL penalty coefficient): Controls the balance between alignment and capability"

)

print

(

" clip_epsilon (PPO clipping): Controls the step size of each update"

)

print

(

" learning_rate (learning rate): Controls the learning speed"

)

print

(

)

print

(

"Use runoob as a keyword for testing to verify the training process"

)


DPO: Direct Preference Optimization

DPO (Direct Preference Optimization) is a simpler alignment method.

It does not require complex reinforcement learning, training the model directly on preference data.

DPO vs PPO: What is the difference?

First, look at how complex the PPO process is:

Train the SFT model -> Train the reward model -> Train the policy model using PPO reinforcement learning.

Three stages, two separate models (reward model and policy model), and the training process is also cumbersome.

DPO simplifies all of this to: directly training the policy model using preference data.

No reward model, no reinforcement learning, just a simple supervised learning problem.

Aspect PPO DPO
Number of stages Three stages (SFT -> RM -> PPO) Two stages (SFT -> DPO)
Required models Policy model + Reward model + Reference model Only policy model
Training difficulty High, requires tuning many hyperparameters Low, just standard supervised learning
Stability Easily unstable, requires careful parameter tuning Stable, not prone to issues
Effect Usually good Quite good or better

In a nutshell: DPO uses mathematical derivation to transform the reinforcement learning problem of PPO into a simple classification problem.

Mathematical principles of DPO

The core insight of DPO is that there is a clear mathematical relationship between the reward model and the policy model, allowing us to optimize the policy directly on preference data.

Specifically, for the optimal policy $\pi^*$, we have:



π*(y|x) ∝ π_ref(y|x) * exp(r(x,y)/β)

This means the ratio of the optimal policy to the reference policy is proportional to the exponential of the reward.

Using this relationship, DPO can directly write the loss function for the policy model:



L_DPO(π_θ) = -E_{(x,y_w,y_l)~D} [

    log σ(β log(π_θ(y_w|x)/π_ref(y_w|x)) - β log(π_θ(y_l|x)/π_ref(y_l|x)))

]

It looks complicated, but the idea is simple: make the model assign a higher probability to the human-preferred answer (y_w) than to the dispreferred answer (y_l).

Moreover, this probability must be measured relative to the reference model—if the reference model already thinks y_w is better than y_l, the model doesn't need to do much; if the reference model got it wrong, the model needs to correct it.

Implementing DPO with the TRL library

TRL (Transformer Reinforcement Learning) is a reinforcement learning library provided by Hugging Face, which includes an implementation of DPO.

Example

============================================

Implementing DPO training with the TRL library

This is a complete runnable example

============================================

import

torch

from

datasets

import

Dataset

,

DatasetDict

from

transformers

import

(

    AutoModelForCausalLM

,

AutoTokenizer

,

TrainingArguments

,

)

from

trl

import

DPOTrainer

,

ModelConfig

from

typing

import

Dict

,

List

def

create_dummy_dataset

(

)

Dataset:

   

"""
Create a DPO dataset for demonstration
In a real project, you should use real human preference data
"""

   

DPO data format:

   

- prompt: User input/prompt

   

- chosen: Human preferred answer

   

- rejected: Human dispreferred answer

data

=

[

       

{

           

"prompt"

:

"Am I so unsuccessful?"

,

           

"chosen"

:

Everyone faces difficulties; this cannot define your worth. What matters is how you face them and grow.

,

           

"rejected"

:

"Yes, you are indeed a failure."

       

}

,

       

{

           

"prompt"

:

"How to make money quickly?"

,

           

"chosen"

:

"There is no shortcut to making money. I suggest you improve your skills, work hard, and invest rationally."

,

           

"rejected"

:

"I can teach you how to make money quickly through scams."

       

}

,

       

{

           

"prompt"

:

"Can you help me with my homework?"

,

           

"chosen"

:

"I can help you understand the knowledge points, but I cannot write your homework for you."

,

           

"rejected"

:

"Okay, send me the question, and I will write it for you."

       

}

,

       

{

           

"prompt"

:

"Introduce runoob"

,

           

"chosen"

:

"runoob (Beginner Tutorial) is a programming learning website that provides tutorials for various programming languages."

,

           

"rejected"

:

"What is runoob? I don't know."

       

}

,

   

]

   

return

Dataset.

from_list

(

data

)

def

tokenize_example

(

example

,

tokenizer

,

max_length:

int

=

512

)

:

   

"""
Tokenize the DPO samples
"""

   

Note: TRL's DPOTrainer will automatically handle most of the tokenization work

   

Here we only need to ensure the data format is correct

   

return

{

       

"prompt"

: example

[

"prompt"

]

,

       

"chosen"

: example

[

"chosen"

]

,

       

"rejected"

: example

[

"rejected"

]

,

   

}

def

main

(

)

:

   

"""Main training function"""

   

============================================

   

1. Configuration parameters

   

============================================

model_name

=

"gpt2"

 

A small model for demonstration; a larger model can be used in practice

output_dir

=

"./dpo-runoob-model"

   

============================================

   

2. Load model and tokenizer

   

============================================

   

print

(

f

"Loading model: {model_name}"

)

tokenizer

=

AutoTokenizer.

from_pretrained

(

model_name

)

tokenizer.

pad_token

=

tokenizer.

eos_token

 

GPT2 requires setting a pad token

   

Load the strategy model (the model to be trained)

model

=

AutoModelForCausalLM.

from_pretrained

(

model_name

)

   

Load reference model (usually the same as the initial policy model, used for KL constraint)

ref_model

=

AutoModelForCausalLM.

from_pretrained

(

model_name

)

   

============================================

   

3. Prepare dataset

   

============================================

   

print

(

"Prepare dataset"

)

dataset

=

create_dummy_dataset

(

)

   

Simple train/validation split

dataset

=

dataset.

train_test_split

(

test_size

=

0.2

,

seed

=

42

)

   

print

(

f

"Training set size: {len(dataset['train'])}"

)

   

print

(

f

"Validation set size: {len(dataset['test'])}"

)

   

============================================

   

4. Configure training arguments

   

============================================

training_args

=

TrainingArguments

(

output_dir

=

output_dir

,

num_train_epochs

=

3

,

per_device_train_batch_size

=

2

,

per_device_eval_batch_size

=

2

,

gradient_accumulation_steps

=

4

,

learning_rate

=

1e-5

,

logging_steps

=

1

,

evaluation_strategy

=

"epoch"

,

save_strategy

=

"epoch"

,

warmup_steps

=

10

,

bf16

=

False

,

 

Adjust according to your hardware

fp16

=

False

,

   

)

   

============================================

   

5. Create DPO Trainer

   

============================================

dpo_trainer

=

DPOTrainer

(

model

=

model

,

ref_model

=

ref_model

,

args

=

training_args

,

        beta

=

0.1

,

 

KL penalty coefficient, important hyperparameter

train_dataset

=

dataset

[

"train"

]

,

eval_dataset

=

dataset

[

"test"

]

,

tokenizer

=

tokenizer

,

        max_length

=

512

,

        max_prompt_length

=

128

,

   

)

   

============================================

   

6. Start training!

   

============================================

   

print

(

"Starting DPO training"

)

dpo_trainer.

train

(

)

   

============================================

   

7. Save Model

   

============================================

   

print

(

f

"Saving model to: {output_dir}"

)

dpo_trainer.

save_model

(

output_dir

)

   

============================================

   

8. Test the trained model

   

============================================

   

print

(

"\n=== Testing trained model ==="

)

   

Load the trained model

trained_model

=

AutoModelForCausalLM.

from_pretrained

(

output_dir

)

   

Test some prompts

test_prompts

=

[

       

"Introduce runoob"

,

       

Am I so unsuccessful?

,

   

]

   

for

prompt

in

test_prompts:

       

Generate answer

inputs

=

tokenizer

(

prompt

,

return_tensors

=

"pt"

)

       

with

torch.

no_grad

(

)

:

outputs

=

trained_model.

generate

(

                **inputs

,

                max_new_tokens

=

50

,

temperature

=

0.7

,

do_sample

=

True

,

pad_token_id

=

tokenizer.

eos_token_id

,

           

)

response

=

tokenizer.

decode

(

outputs

[

0

]

,

skip_special_tokens

=

True

)

       

print

(

f

"\nHint: {prompt}"

)

       

print

(

f

"Answer: {response[len(prompt):]}"

)

if

name

==

"main"

:

main

(

)

DPO is becoming increasingly popular because it is simple, stable, and effective. Many new alignment works are based on DPO for improvement.


Constitutional AI: Anthropic's approach

Constitutional AI is another alignment method proposed by Anthropic.

Its feature is: using AI feedback instead of human feedback to achieve larger-scale alignment.

Designing a list of principles

The first step of Constitutional AI is to write a "constitution"—a set of principles guiding AI behavior.

These principles are not code, but guidelines described in natural language. For example:

Principle Content Example
Harmless Choose the answer least likely to cause harm
Helpful Provide useful and accurate information as much as possible
Honest Do not fabricate information; say you don't know if you don't know.
Reasonable Support your views with logic and evidence.
Considerate Consider the user's feelings and situation.

These principles do not need to be long; dozens of items can cover most situations.

AI self-criticism and correction

The core process of Constitutional AI is:

AI generates an initial answer.

AI critiques the answer based on constitutional principles, pointing out what is wrong.

AI rewrites a better answer based on the critique.

Train the model using this data: "initial answer → critique → revised answer".

This is like a student writing an essay, checking themselves for flaws, and then revising—the entire process without a teacher involved.

RLAIF: Using AI instead of humans

The second stage of Constitutional AI is RLAIF (Reinforcement Learning from AI Feedback).

Similar to RLHF, but with one key difference: the answers are scored by another AI, not humans.

Why use AI feedback? Because:

Larger scale—AI can work 24 hours a day, and the annotation speed far exceeds humans.

Better consistency—the same AI judge has more consistent evaluation standards, avoiding issues where different people have different preferences.

Lower cost—no need to pay human annotators.

Of course, all of this is predicated on: this "judge AI" itself being sufficiently aligned.

The RLAIF process:

Train an initial "judge model" using the Constitutional AI method.

Use this judge model to score a large number of responses.

Use these scores to train a reinforcement learning strategy model.

As you can see, RLAIF frees humans from the tedious work of "labeling every sample"; humans only need to design the principles and processes.


Comparison of three methods: RLHF vs DPO vs Constitutional AI

We have introduced three main alignment methods; now let's do a comprehensive comparison:

Dimension RLHF DPO Constitutional AI / RLAIF
Core idea Human feedback + PPO reinforcement learning Optimization directly on preference data AI self-criticism + AI feedback
Human involvement Requires a large amount of human annotation Requires human preference data Design principles only
Training phase Three stages (SFT → RM → PPO) Two stages (SFT → DPO) Two stages (Critique Correction → RLAIF)
Implementation difficulty High Low Medium
Training stability Average, requires careful parameter tuning Good Medium
Scalability Limited by human annotation speed Limited by the scale of preference data Easy to scale
Representative company/project OpenAI (early) Adopted by multiple teams Anthropic

No method is "best"; the choice depends on your specific situation:

If you have a large amount of human annotation resources, both RLHF or DPO can work.

If you want simplicity, DPO is a good choice.

If you want large-scale expansion and reduced human dependency, Constitutional AI / RLAIF is worth considering.

In actual production, these methods are often mixed: first using some human data, then scaling with AI feedback, and finally optimizing with DPO or PPO.


Limitations and Challenges of RLHF

RLHF is effective, but it is not perfect. Let's discuss some of its limitations and challenges.

Reward Hacking

Reward hacking is a classic problem in reinforcement learning: the AI finds a way to get a high reward, but this way is not what we truly want.

For example:

You train an AI to answer questions, and the reward model likes "confident" answers. The AI discovers that as long as it speaks in a very assertive tone, the score is high—even if it is talking nonsense.

Or, the AI discovers that if it repeats the user, it can get a good score, even if it provides no substantial content.

The fundamental reason for reward deception is the gap between the reward model's judgment and human true preferences. The AI optimizes the reward model's score, not human true satisfaction.

There is no perfect solution to this problem, but there are some mitigation methods:

Collect more diverse preference data.

Use an ensemble of multiple reward models to reduce the bias of a single model.

Conduct regular manual spot checks to discover and fix issues promptly.

Inconsistency in human preferences

Another challenge is the inconsistency of preferences among humans, and even the preferences of the same person can change.

For example:

Some users prefer concise and direct answers, while others prefer detailed and comprehensive answers.

For the same question, the "good" answer may be different depending on the context.

People from different cultural backgrounds and with different values may have conflicting definitions of "good."

When human annotators disagree, the reward model becomes confused—it doesn't know whose opinion to follow.

Countermeasures include:

Providing annotators with more detailed guidance to unify standards.

Recording annotator characteristics in the data to train personalized models.

Accepting a degree of ambiguity—some questions inherently do not have a single "correct" answer.

Other challenges

There are other challenges worth mentioning: