You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
{{ message }}
Repository navigation
[RFC] Add trainer for Direct Preference Optimization (DPO)
#6357
Verl offers superior training infrastructure: Ray-based orchestration, FSDP/FSDP2 + DDP device meshes, dynamic batch sizing, MoE-optimizations, Sequence parallelism, and a unified TrainingWorker engine abstraction that handles micro-batching, profiling, checkpointing, and mixed precision transparently. Features like Dynamic batch sizing helps get a much higher throughput with better GPU utilization on real-world datasets compared to the existing RLHF framework. Experiments and information around this showed speed-ups up to 4x with the Verl-SFT implementation and upto 50% reduction in VRAM usage in FFT implementations were observed.
Despite these advantages, Verl has no DPO support. This means preference alignment workloads must still use a RLHF based framework, preventing the team from consolidating into a single framework. The gap includes:
No DPO loss functions.
No preference dataset pipeline — SFT datasets produce single sequences; DPO needs paired (chosen/rejected) outputs with matched prompts
No reference model workflow — DPO requires computing log-probs from both a policy model and a frozen reference model; the SFT trainer only manages one model
No DPO-specific configuration — Hyperparameters like beta, loss_type, and label_smoothing don't exist in the current config schema
Given the advantages we see with the Verl framework and to consolidate all training recipes under a single training framework, there is a need to start supporting DPO training in Verl. This technical document discusses adding this support for training models using DPO in Verl, covering loss functions, data pipeline, trainer architecture, and configuration.
2. Scope
This document covers the design and implementation of DPO (Direct Preference Optimization) support in Verl, organized into three phases:
Phase 1: Core DPO Infrastructure (In Progress)
The foundation layer that makes DPO training possible. This includes
Implementing 7 loss function variants into a new registry following Verl's conventions.
Creating a dataset pipeline for single-turn preference data that produces paired (chosen and rejected samples) tokenized sequences compatible with the TrainingWorker engine.
Implementing the DPO trainer class following the same SPMD pattern as the SFT trainer. The DPO trainer will support both Lora and FFT based training.
Adding Hydra configuration for DPO-specific hyperparameters.
Phase 2: Validation
Unit tests for loss functions, dataset, and trainer integration.
Evaluation setup to compare the Verl DPO results against existing baselines.
Migrating existing DPO recipes from openrlhf to Verl.
Phase 3: Advanced features
This phase will cover advanced features that we can integrate like Multi-turn support, support for new dataset formats etc.
Phase
Subtasks
Status
Phase 1: Core
Loss functions, data pipeline, trainer, config, CLI, Lora support, FFT support, MLFlow logging
Complete
---
---
---
Phase 2: Validation
Unit tests, E2E testing
Lora (In Progress), Recipes (Proposed)
Phase 3: Advanced features
Multi-turn support, support for other dataset formats like OpenAI
TBD
3. DPO Loss Functions
3.1 Background: How DPO Loss Works
Standard DPO derives from the RLHF objective. Instead of training a reward model and running RL, DPO reparameterizes the reward(r(x, y)) as a function of the policy(model/π_θ) itself:
`r(x, y) = β · log(π_θ(y|x) / π_ref(y|x)) + cons`
Let y_w represent a chosen response for a given prompt x,y_l represent a rejected response, and π_θ represent the policy model we would like to optimize and π_ref represent the frozen base/reference model. The DPO loss L_DPO pushes the model to assign higher implicit reward to chosen responses vs rejected by increasing the probability that the policy model picks a chosen response instead of rejected:
All loss variants share the same 4 inputs (per-sequence scalar log-probabilities):
Input
Notation
Shape
Description
chosen_logps
log π_θ(y_w
x)
(B,)
---
---
---
---
rejected_logps
log π_θ(y_l
x)
(B,)
ref_chosen_logps
log π_ref(y_w
x)
(B,)
ref_rejected_logps
log π_ref(y_l
x)
(B,)
From these, we derive:
Log-ratios: chosen_logratios = chosen_logps - ref_chosen_logps (how much the policy diverged from reference for chosen)
Logits: logits = chosen_logratios - rejected_logratios (the reward margin)
Implicit rewards: β × logratios
3.2 Implementation Options Considered
Option
Description
Pros
Cons
A: Add to PPO registry (core_algos.py)
Register DPO losses in existing POLICY_LOSS_REGISTRY
No new files; shared infrastructure
PPO and DPO losses have different signatures (4 inputs vs 2); PPO losses take (old_log_prob, log_prob, advantages, response_mask) while DPO takes (chosen_logps, rejected_logps, ref_chosen_logps, ref_rejected_logps)
New file to maintain but its also a pro as it simplifies the open source upstreaming
C: Single DPOLoss class (like openrlhf)
One nn.Module class with loss_type dispatch via if/elif
Familiar to openrlhf implementation; single class to import
200+ line if/elif chain; adding new loss requires modifying existing code;
3.3 Recommended: Option B — Separate Registry
DPO and PPO losses are fundamentally different algorithms with different mathematical foundations, different input signatures, and different output semantics. A separate registry is a cleaner approach and follows the same decorator pattern (@register_dpo_loss) as PPO's @register_policy_loss. This is also better than using a single class because it avoids unmaintainable and long if/else chains and makes it easier to add new loss types in the future.
beta (float, default 0.1): Temperature — higher = more conservative updates, lower = ignores the reference model
label_smoothing (float, default 0.0): Prevents overconfidence; adds penalty for being too certain
reference_free (bool, default False): When True, ignores reference model (sets ref_logps = 0)
3.5 Loss Scaling
Why scaling is needed
The verl engine processes a batch in two levels of splitting:
Data parallelism: The global batch is split across GPUs. Each GPU gets batch_num_pairs number of pairs.
Micro-batching: When dynamic batching is used, each GPU's pairs are further split into N micro-batches where sample assignment to each micro batch takes into account memory efficiency and improved GPU utilization.
After all micro-batches run, the engine does:
final_loss = SUM(all micro-batch losses on this GPU) → all_reduce(AVG across GPUs)
We want final_loss = the true global mean. Without scaling, it would be N× too large. Here true global mean is nothing but the average loss over all samples in the batch if it was to be run on a single device.
Deriving the formula
**Goal:** `final_loss` = `global_mean` (the mean loss over all pairs on all GPUs).
**What the engine does after our loss function returns:**
final_loss = SUM_over_microbatches(our_loss) / dp_size
We need: `SUM_over_microbatches(our_loss) / dp_size = global_mean`
Rearranging: `SUM_over_microbatches(our_loss) = global_mean × dp_size`
Since all GPUs have the same number of pairs, denoted by batch_num_pairs,
`global_mean ≈ local_mean` (mean over this GPU's pairs). So each
GPU needs:
SUM_over_microbatches(our_loss) = local_mean × dp_size
If micro-batch `i` has `B_i` pairs out of batch_num_pairs on this GPU, we set:
our_loss_i = mean_i × (B_i / batch_num_pairs) × dp_size
**Verification — sum them up:**
SUM_i(mean_i × B_i / batch_num_pairs × dp_size)
= (dp_size / batch_num_pairs) × SUM_i(mean_i × B_i)
= (dp_size / batch_num_pairs) × (total sum of all individual pair losses on this GPU)
= **dp_size × local_mean**
After **`all_reduce`**`(AVG)`: `dp_size × local_mean / dp_size = `**`local_mean = global_mean`**
The final scaling formula:-
**scaled_loss = preference_loss × (micro_batch_size / batch_num_pairs) × dp_size**
Three multiplications, each fixing one piece:
preference_loss = mean over B pairs in this micro-batch
× B / batch_num_pairs = weight by fraction of total pairs (so summing micro-batches gives the correct weighted mean, not N× the mean)
× dp_size = pre-multiply so that dividing by dp_size (all_reduce AVG) gives back the true mean
Option A: Configurable preprocessor chain — YAML-driven processor pipeline with ProcessorMap registry. Pros: Maximum flexibility. Cons: No precedent in Verl.
Option B: Fixed workflow in dataset (like Verl's SFTDataset) — All preprocessing in getitem() with configurable column names. Pros: Simple; consistent with existing Verl datasets. Cons: Less flexible; users will need custom_cls if they would like to introduce custom preprocessing on their datasets. Custom_cls support also exists in verl.
Option C: Separate preprocessing module — Standalone functions callable by any dataset. Pros: Reusable. Cons: Adds coupling.
4.2 Recommended: Option B — Fixed Pipeline
Verl's existing datasets (SFTDataset, MultiTurnSFTDataset, RLHFDataset) all use inline processing in __getitem__(). Users who need custom preprocessing can use the custom_cls config option.
Implementation: verl/utils/dataset/dpo_dataset.py
Processing stages:
During initial dataset loading:
Load (load_data_file) — init: .parquet/.jsonl only
Extract (extract_columns) — init: pull columns into Python lists
Optionally filter out samples that have empty fields i.e either Chosen or Rejected response is an empty string.
When getitem is called:
Chat Template (apply_chat_template) — getitem: format prompt with tokenizer's template
Tokenize (tokenize_prompt_response) — getitem: separate prompt/response tokenization
Loss Mask (inline) — getitem: binary mask: 0 for prompt, 1 for response
Truncate (inline) — getitem: truncate to max_length, no padding
Fat-Pack - getitem : Concatenate chosen and rejected tensors per prompt into a single tensor to avoid losing the pairing during dynamic batch sizing. See Section 5.3.1 for more info.
4.3 Implementation Details
Data format: .parquet or .jsonl with three columns (configurable names) and huggingface format:
{"prompt": "What is Python?", "chosen": "A programming language.", "rejected": "A snake."}
Options are given in the config to let customers set the names for these columns based on their dataset and internally the keys are mapped back to the above three column names. If a list of files is submitted as input, their columns are validated and then the contents of the files are merged into a single dataframe before loading into local CPU RAM.
Per-sample processing (_process_sequence, called once for chosen, once for rejected):
Chat template: Applies the tokenizer's chat template in two passes to correctly identify the prompt/response boundary:
First pass: templates [{"role": "user", "content": prompt}] with add_generation_prompt=True → produces prompt_str
Uses longest common prefix matching between prompt_str and full_str to split them back into the formatted prompt portion and the formatted response portion. This ensures correct boundary detection even when the chat template inserts special tokens between turns.
Tokenize separately: Tokenizes prompt and response as separate strings to get the boundary for loss mask and appends eos_token to the response tokens.
loss_mask(chosen_seq_len + rejected_seq_len,) — Chosen loss mask + rejected loss mask
boundary_offset — integer value marking where the chosen sequence ends and the rejected sequence starts in the packed tensor
4.4 Key Design Decisions
4.4.1 Why Variable-Length and not padding?
The current version of the engine is built around flash attention's variable-length mode (flash_attn_varlen_func), which takes all tokens concatenated into a flat tensor plus cu_seqlens (cummulative sequence lengths: offsets to distinguish between concatenated samples of variable length) boundaries. NestedTensors store data this way:
.values() = flat tokens,
.offsets() = cu_seqlens.
4.4.2 Why attention_mask is not created ?
FSDPEngine creates its own attention handling from NestedTensor offsets (cu_seqlens). No dataset-provided mask is needed here. Same as MultiTurnSFTDataset.
output keys, no old-format keys, boundary_offset type/range, loss_mask binary/shape, prompt masked in both halves, response tokens have mask=1, all samples accessible
3
TestDPODatasetTruncation
3
right truncation, left truncation, invalid truncation
YAML format (header, no inline comments, blank lines), code constants exist, shuffle uses df.sample, load uses try-parse, resolve references constant
5. DPO Trainer
5.1 Implementation Options Considered
Option A: FSDP Direct — Manual FSDP wrapping, forward/backward in trainer.
Pros: Simplest implementation; full control; easy debugging.
Cons: Reimplementation required for some features like dynamic batch sizing, profiling, sequence parallelism.
Option B: SPMD TrainingWorker (based on sft_trainer.py) — Uses TrainingWorker abstraction provided by Verl.
Pros: Reuses engine infrastructure; consistent with Verl direction.
Cons: Needs some DPO specific implementations such as two-model (policy and reference) workflow; concatenated_forward for the chosen and rejected samples.
Option C: Ray Single-Controller — Ray driver orchestrates GPU workers via RPC.
Pros: Can overlap ref/policy compute.
Cons: This could prove to be un-necessarily complex approach for something that is as simple as offline DPO unlike RLAIF like training where you need to alternate between rollouts and training.
5.2 Recommended: Option B — SPMD TrainingWorker
Option B inherits dynamic batch sizing, profiling, sequence parallelism, MFU tracking, and checkpointing from the TrainingWorker which are features that would have a high reimplementation cost in other implementation approaches. Option A was initially prototyped but deprecated in favor of the TrainingWorker-based design. TrainingWorker is an abstraction layer provided by verl that uses specialized engines like FSDPEngine underneath to perform the actual training.
5.2.1 Architecture
The trainer mirrors the SFT trainer's initialization process (build config, dataset, engine, dataloader, checkpoint handler) and adds some DPO-specific methods:
5.2.2 Reference Model: Two Modes
LoRA mode (lora_rank > 0): No separate model needed. Uses self.engine.module.disable_adapter() to temporarily zero LoRA weights, making the base model act as the reference. Same mechanism as PPO/GRPO. Memory efficient — only one model in GPU memory.
FFT mode (lora_rank = 0): A second TrainingWorker with forward_only=True, which triggers CPUOffload(offload_params=True) in FSDP. The ref model streams layers from CPU→GPU one at a time during forward pass, minimizing GPU memory usage.
5.2.3 Training Step Flow
Each training step in DPOTrainer.fit() executes the following sequence:
Prepare fat-packed batch (get_seqlen_balanced_partitions_prepare_dpo_batch): Takes the collated batch from the dataloader (B fat sequences as NestedTensors + boundary_offsets as NonTensorStack) and adds position IDs for each fat sequence. The fat sequences are NOT expanded here — they stay packed so dynamic micro-batching can't break pairs. See Section 5.3.1 for more explanation.
Compute reference log-probs (_compute_ref_log_probs): Expands fat sequences into 2B separate interleaved sequences [chosen₀, rej₀, chosen₁, rej₁, ...] at the trainer level, runs the reference model (CPU-offloaded FFT or adapter-disabled LoRA), sums per-token log-probs into per-sequence scalars, and splits into ref_chosen_logps (B,) and ref_rejected_logps (B,).
Attach ref logps as (B, 2): Stacks ref_chosen and ref_rejected into a (B, 2) tensor and attaches to the fat batch. This 2D shape ensures correct slicing when the engine micro-batches the B fat sequences — each micro-batch gets its corresponding (B', 2) slice.
Build TensorDict with metadata: Wraps fat tensors + ref_logps into a TensorDict along with engine metadata (pad_mode, use_dynamic_bsz, temperature, etc.) and DPO-specific metadata (batch_num_pairs for loss scaling, dpo_batch_size).
Engine training call: Sets dpo_expand_packed_sequences=True flag in the TensorDict metadata, then passes it to policy_client.train_batch(). Inside the engine:
Dynamic micro-batching: prepare_micro_batches() splits B packed sequences into N micro-batches using bin-packing limited by max_token_len_per_gpu. Chosen-rejected pairs remain intact as single entries because they are packed into one sequence.
Flag-driven expansion (_expand_dpo_packed_sequences): After micro-batching, prepare_micro_batches() checks for the dpo_expand_packed_sequences flag. If True, it splits each packed sequence at its boundary_offset into separate chosen/rejected tensors, interleaves them [chosen₀, rej₀, chosen₁, rej₁, ...], creates independent position IDs, and expands ref_logps from (B', 2) to interleaved (2B'). For non-DPO trainers this flag is absent and the step is a no-op.
Forward pass: Model processes 2B' independent sequences with flash attention varlen mode (no cross-sequence attention).
DPO loss (dpo_loss): Sums per-token log-probs into per-sequence scalars (with shifted loss_mask alignment), calls the selected loss variant, and scales the loss (see section 3.6) for correct gradient magnitude.
Backward + optimize: Gradients accumulate across micro-batches, FSDP syncs across GPUs, optimizer steps.
Log metrics: Flattens per-micro-batch metrics into scalars, logs to TensorBoard/WandB including dpo/loss, dpo/accuracy, reward margins, grad_norm, MFU, and token throughput.
5.3 Design Decisions and Problems encountered
5.3.1 The Pairing Problem
DPO loss requires comparing a chosen response against a rejected response for the same prompt. The loss formula is:
L = -log sigmoid(beta * (chosen_logratio - rejected_logratio))
where chosen_logratio = log P_policy(chosen) - log P_ref(chosen), and similarly for rejected. The subtraction means chosen and rejected MUST come from the same DPO sample.
The challenge: The Verl engine processes batches through internal micro-batching (splitting large batches into smaller chunks for memory efficiency). With this process, a main problem that comes up is:
Problem 1: Dynamic micro-batching rearranges order. If we use dynamic batch sizing (use_dynamic_bsz=True), the engine's bin-packing algorithm groups sequences by token count to maximize GPU utilization. This rearranges sequence order, breaking the chosen/rejected pairing. This issue also goes pretty much undetected because the training can still continue with wrong pairs of chosen and rejected samples.
Now in micro-batch A, the loss function pairs chosen_2 with rejected_0 (WRONG — different prompts!) and chosen_0 with rejected_3 (WRONG!). The model gets a noisy learning signal.
5.3.2 Potential Solution 1: Concatenate Chosen and Rejected sample per prompt before dynamic batch sizing and separate before forward pass
Premise: Dynamic batch sizing splits the given batch into several micro batches and then iterates over each batch to compute the gradients. This means all the chosen and rejected samples for a given prompt still stay on the same device, and we just need to make sure they land in the same micro batch.
The solution follows the following steps:
For a given prompt, concatenate the chosen and rejected sample into the same tensor and maintain an offset value to mark the boundary between the two tensors.
Perform dynamic batch sizing to get micro batches.
Once the micro batches are ready, apply a transformation to separate the concatenated tensors back into two separate tensors.
Do the above step before both the forward steps in policy model as well as reference model
The total no of tokens in the micro batch will still be consistent as before the split so this should not affect the results of dynamic batch sizing.
The main advantage that we get from dynamic batch-sizing is that the micro-batch bins that are generated by the batching algorithm have the optimal arrangement of samples based on no-of-tokens in the sample. But because we concatenate the chosen and rejected samples in our case, the no-of-tokens that the batching algorithm sees is the combined value of the two samples. But after we expand them back before doing a forward pass, the new batch now has a different distribution of the no of tokens per sample. This could potentially negate the advantages of dynamic batching in some scenarios.
dynamic batch-sizing algorithm sees the post concatenation batch and rearranges them.
Potential micro batch distribution: = [110], [600,1000]
Post expansion into chosen and rejected tensors = [50,60], [100, 500, 600, 1000]
The example post expansion tensors show that the token distribution is no longer closer to each other within a micro batch. In most cases, this kind of setup could result in a small tensor ending up in a micro-batch with large tensors, because it was concatenated with a large tensor before dynamic batching was applied. This could go in two directions:
* The time taken by the small tensor’s computations are hidden behind that of the large tensors. This does not really have a negative effect as it does not increase the computation time.
* The small tensor is taking the spot of a larger tensor that could have been in this micro-batch if dynamic batch sizing was applied to non concatenated samples, but because they were concatenated, this larger tensor ended up in a different micro-batch. If all the tensors in that second micro-batch were very small compared to the large tensor, then that could potentially cause wasted GPU cycles. But this is an edge case scenario and a **tradeoff** for ensuring DPO algorithm **correctness** by concatenating the chosen and rejected samples per prompt before applying dynamic batch-sizing.
5.3.3 (Recommended) Flag-driven expansion in prepare_micro_batches
Premise: The initial solution (5.3.2) worked correctly but required passing a micro_batch_transform_fn callback through the engine class hierarchy (BaseEngine → FSDPEngine → forward_backward_batch). This means the common engine classes — which are shared across SFT, and other training algorithms — need to carry DPO-specific plumbing in their method signatures. This makes the engine layer aware of a concern (DPO pair expansion) that only one trainer algorithm cares about.
Alternative approach: Instead of injecting DPO logic via a callback into the engine, we move the expansion into prepare_micro_batches() in verl/workers/engine/utils.py, triggered by a boolean flag in the data TensorDict. The engine classes remain completely unaware of DPO.
The updated solution follows these steps:
The DPO dataset still packs chosen and rejected into the same fat sequence with a boundary_offset marker, exactly as before.
The DPO trainer sets a flag dpo_expand_fat_sequences=True as non-tensor metadata in the data TensorDict before calling train_batch().
prepare_micro_batches() runs dynamic batch sizing as normal, producing micro-batches where DPO pairs are guaranteed to stay together (because they are packed into single fat sequences).
After micro-batching, prepare_micro_batches() checks for the dpo_expand_fat_sequences flag. If present and True, it applies the expansion to split each fat sequence at its boundary_offset into separate chosen/rejected sequences, interleaved as [c0, r0, c1, r1, ...]. If the flag is absent (which it is for SFT, PPO, and all other trainers), this step is a complete no-op.
The engine's forward_backward_batch() receives already-expanded micro-batches and processes them normally — no knowledge of DPO required.
The total token count per micro-batch remains consistent before and after the split, so dynamic batch sizing results are unaffected.
Key benefit: The Base Engine classes are no longer affected by DPO specific implementation, All DPO-specific data manipulation is now localized to (1) the DPO dataset (fat packing), (2) the DPO trainer (setting the flag), and (3) a single conditional block in prepare_micro_batches (expansion) which is a utility function. The engine layer stays generic.
6. CLI Integration
DPO training continues to use Hydra for configuration management, following the same pattern as other trainers in verl. The config file verl/trainer/config/dpo_trainer.yaml defines defaults and DPO-specific overrides.
For Correctness test, one of the tests involves computing log probabilities and loss values in the first forward pass from the old openrlhf implementation as well as the new Verl implementation and compared against each other with the expectation that they should match if we keep constant other parameters like the sample used and the seed value.
First step (Forward pass only) artifacts comparison between openrlhf (reference) and Verl (candidate) :-
8. Evaluation
Alpaca dataset win-rate test against responses from GPT-4o is used to compare the new Verl-DPO implementation with the current openrlhf-DPO implementation. In this test, the GPT-4o model, an openrlhf-DPO trained model and our new Verl-DPO trained model are used for generating answers to prompts from the alpaca dataset. Then a large judge model like Mistral-Large is used to compare (GPT-4o, openrlhf-DPO), and then (GPT-4o, Verl-DPO) to see how many samples from the DPO model is picked by the judge model against GPT-4o which is what we call the win-rate here. All the openrlhf values come from [Phase 1] SageMaker SFT/DPO Recipe Validation.
Alpaca Win-rate Experiment setup:
Dataset: Ultrafeedback
Training dataset size: 800 samples
No of epochs: 3
Batch size: 16
Instance type: P5.48xlarge node
Judge model: Mistral Large
Model
openrlhf-DPO-Lora
Verl-DPO-Lora
openrlhf-DPO-FFT
Verl-DPO-FFT
Llama 3.2-1B
0.3644/0.33416
0.3511
0.2848
Qwen3 0.6B
0.2419
0.2521
Qwen 2.5 7B
0.5963
0.60248
0.53913
Llama-3.2-3B-Instruct
Llama-3.1-8B-Instruct
Llama-3.3-70B-Instruct
Qwen3-1.7B
Qwen3-4B
Qwen3-8B
Qwen3-14B
Qwen3-32B
gpt-oss-20b
gpt-oss-120b
DeepSeek-R1-Distill-Qwen-1.5B
DeepSeek-R1-Distill-Qwen-7B
DeepSeek-R1-Distill-Qwen-14B
DeepSeek-R1-Distill-Qwen-32B
DeepSeek-R1-Distill-Llama-8B
DeepSeek-R1-Distill-Llama-70B
Qwen-2.5-14B-Instruct
Qwen-2.5-32B-Instruct
Qwen-2.5-72B-Instruct
Qwen-3.5-4B
0.39272
Qwen-3.5-9B
0.4968
Qwen-3.5-27B
Validation and Throughput numbers experiment setup
Dataset: Ultrafeedback
Training dataset size: 1000 samples
No of epochs: 5
Batch size: 32
max_token_len_per_gpu (Verl): 16384
Instance type: P5.48xlarge node
For openrlhf:- micro_batch_size = 4
Model
Type
openrlhf-Val-Acc
Verl-Val-Acc
openrlhf-Val-loss
Verl-Val-Loss
openrlhf-Val-Reward-margin
Verl-Val-Reward-margin
openrlhf Step-based Throughput (tokens/sec)
Verl Step-based Throughput**(tokens/sec)**
openrlhf E2E throughput**(tokens/sec)**
Verl E2E throughput**(tokens/sec)**
Throughput improvement delta
Llama 3.2-1B
Lora
0.6875
0.75
0.562
0.533
0.462
0.523
28318.96
34412.77
22229.36
22897.85
3%
Llama-3.2-3B-Instruct
Lora
0.625
0.65625
0.723
0.649
0.348
0.351
14392.51
23939.4
11451.53
15774.21
37%
Qwen 2.5 7B
Lora
0.75
0.6875
0.573
0.829
1.897
2.185
9290.89
18431.66
6942.44
11451.61
64%
Qwen3-0.6B
Lora
0.6875
0.6875
0.554
0.654
0.646
0.421
18718.56
25492.68
16212.06
19199.26
18.40%
Qwen3-14B
Lora
0.843
0.812
0.427
0.406
1.01
1.596
4882.71
10681.6
3345.72
7104.3
112%
Llama-3.1-8B-Instruct
Lora
Llama-3.3-70B-Instruct
Lora
Qwen3-1.7B
Lora
Qwen3-4B
Lora
Qwen3-8B
Lora
Qwen3-32B
Lora
0.78
0.687
0.427
0.681
2.13
0.751
2492.36
5800.6
1827.26
3698.55
102%
gpt-oss-20b
Lora
gpt-oss-120b
Lora
DeepSeek-R1-Distill-Qwen-1.5B
Lora
DeepSeek-R1-Distill-Qwen-7B
Lora
DeepSeek-R1-Distill-Qwen-14B
Lora
DeepSeek-R1-Distill-Qwen-32B
Lora
DeepSeek-R1-Distill-Llama-8B
Lora
DeepSeek-R1-Distill-Llama-70B
Lora
0.589
0.53125
0.845
1.25
0.9
0.52
1481.68
3546.99
1029.88
1999.77
94%
Qwen-2.5-14B-Instruct
Lora
Qwen-2.5-32B-Instruct
Lora
Qwen-2.5-72B-Instruct
Lora
Qwen-3.5-4B
Lora
Qwen-3.5-9B
Lora
Qwen-3.5-27B
Lora
Uniform dataset comparison
9. Appendix (In progress)
9.1 General Experiment Runs
Standard experiment setup:
Total no of epochs: 3
Dataset: Ultrafeedback
Dataset limit: 800
Metrics from Verl
"dpo/loss": preference_loss.detach().item(), # Needs to be updated to scaled version
"dpo/accuracy": (chosen_rewards > rejected_rewards).float().mean(),
"dpo/chosen_reward": beta * (chosen_logps - ref_chosen_logps),
"dpo/rejected_reward": beta * (rejected_logps - ref_rejected_logps),
"dpo/reward_margin": (chosen_rewards - rejected_rewards).mean().item(),
"dpo/chosen_logps": chosen_logps.detach().mean().item(),
"dpo/rejected_logps": rejected_logps.detach().mean().item(),
reacted with thumbs up emoji reacted with thumbs down emoji reacted with laugh emoji reacted with hooray emoji reacted with confused emoji reacted with heart emoji reacted with rocket emoji reacted with eyes emoji
Uh oh!
There was an error while loading. Please reload this page.
Uh oh!
There was an error while loading. Please reload this page.
DPO Training support in Verl
Authors: Indra Kumar Vijaykumar (@Indra24710), Zhe Wang (@zhexjtu), Karel Mundnich (@kmaws), Sapana Chaudhary (@SapanaChaudhary), Jiayu Li (@Code4Graph) Theodore Vasiloudis (@thvasilo)
1. Background
Verl offers superior training infrastructure: Ray-based orchestration, FSDP/FSDP2 + DDP device meshes, dynamic batch sizing, MoE-optimizations, Sequence parallelism, and a unified TrainingWorker engine abstraction that handles micro-batching, profiling, checkpointing, and mixed precision transparently. Features like Dynamic batch sizing helps get a much higher throughput with better GPU utilization on real-world datasets compared to the existing RLHF framework. Experiments and information around this showed speed-ups up to 4x with the Verl-SFT implementation and upto 50% reduction in VRAM usage in FFT implementations were observed.
Despite these advantages, Verl has no DPO support. This means preference alignment workloads must still use a RLHF based framework, preventing the team from consolidating into a single framework. The gap includes:
Given the advantages we see with the Verl framework and to consolidate all training recipes under a single training framework, there is a need to start supporting DPO training in Verl. This technical document discusses adding this support for training models using DPO in Verl, covering loss functions, data pipeline, trainer architecture, and configuration.
2. Scope
This document covers the design and implementation of DPO (Direct Preference Optimization) support in Verl, organized into three phases:
Phase 1: Core DPO Infrastructure (In Progress)
The foundation layer that makes DPO training possible. This includes
Phase 2: Validation
Phase 3: Advanced features
This phase will cover advanced features that we can integrate like Multi-turn support, support for new dataset formats etc.
3. DPO Loss Functions
3.1 Background: How DPO Loss Works
Standard DPO derives from the RLHF objective. Instead of training a reward model and running RL, DPO reparameterizes the reward(r(x, y)) as a function of the policy(model/π_θ) itself:
Let y_w represent a chosen response for a given prompt x, y_l represent a rejected response, and π_θ represent the policy model we would like to optimize and π_ref represent the frozen base/reference model. The DPO loss L_DPO pushes the model to assign higher implicit reward to chosen responses vs rejected by increasing the probability that the policy model picks a chosen response instead of rejected:
All loss variants share the same 4 inputs (per-sequence scalar log-probabilities):
chosen_logpsrejected_logpsref_chosen_logpsref_rejected_logpsFrom these, we derive:
chosen_logratios = chosen_logps - ref_chosen_logps(how much the policy diverged from reference for chosen)logits = chosen_logratios - rejected_logratios(the reward margin)β × logratios3.2 Implementation Options Considered
core_algos.py)POLICY_LOSS_REGISTRY(old_log_prob, log_prob, advantages, response_mask)while DPO takes(chosen_logps, rejected_logps, ref_chosen_logps, ref_rejected_logps)dpo_losses.py)DPO_LOSS_REGISTRYnn.Moduleclass withloss_typedispatch via if/elif3.3 Recommended: Option B — Separate Registry
DPO and PPO losses are fundamentally different algorithms with different mathematical foundations, different input signatures, and different output semantics. A separate registry is a cleaner approach and follows the same decorator pattern (
@register_dpo_loss) as PPO's@register_policy_loss. This is also better than using a single class because it avoids unmaintainable and long if/else chains and makes it easier to add new loss types in the future.7 DPO loss variants:
sigmoid-log σ(β·logits)·(1-ε) - log σ(-β·logits)·εrobust/(1-2ε)normalizationipo(logits - 1/(2β))²hingemax(0, 1 - β·logits)exo_pairσ(β·logits)·[log σ(β·logits) - log(1-ε)] + ...aot_pairaotMain Loss:
LDPO(πθ;πref)=−E(x,yw,yl)∼Dlogσ(βlogπref(yw∣x)πθ(yw∣x)−βlogπref(yl∣x)πθ(yl∣x))]
Hyperparameters:
beta(float, default 0.1): Temperature — higher = more conservative updates, lower = ignores the reference modellabel_smoothing(float, default 0.0): Prevents overconfidence; adds penalty for being too certainreference_free(bool, default False): When True, ignores reference model (sets ref_logps = 0)3.5 Loss Scaling
Why scaling is needed
The verl engine processes a batch in two levels of splitting:
batch_num_pairsnumber of pairs.After all micro-batches run, the engine does:
We want
final_loss= the true global mean. Without scaling, it would be N× too large. Here true global mean is nothing but the average loss over all samples in the batch if it was to be run on a single device.Deriving the formula
Three multiplications, each fixing one piece:
preference_loss= mean over B pairs in this micro-batch× B / batch_num_pairs= weight by fraction of total pairs (so summing micro-batches gives the correct weighted mean, not N× the mean)× dp_size= pre-multiply so that dividing by dp_size (all_reduce AVG) gives back the true mean3.7 Test Coverage
77 parametrized unit tests across 5 classes:
4. DPO Data Workflow
4.1 Preprocessing Options Considered
Option A: Configurable preprocessor chain — YAML-driven processor pipeline with ProcessorMap registry. Pros: Maximum flexibility. Cons: No precedent in Verl.
Option B: Fixed workflow in dataset (like Verl's SFTDataset) — All preprocessing in getitem() with configurable column names. Pros: Simple; consistent with existing Verl datasets. Cons: Less flexible; users will need custom_cls if they would like to introduce custom preprocessing on their datasets. Custom_cls support also exists in verl.
Option C: Separate preprocessing module — Standalone functions callable by any dataset. Pros: Reusable. Cons: Adds coupling.
4.2 Recommended: Option B — Fixed Pipeline
Verl's existing datasets (SFTDataset, MultiTurnSFTDataset, RLHFDataset) all use inline processing in
__getitem__(). Users who need custom preprocessing can use the custom_cls config option.Implementation: verl/utils/dataset/dpo_dataset.py
Processing stages:
During initial dataset loading:
When getitem is called:
4.3 Implementation Details
Data format: .parquet or .jsonl with three columns (configurable names) and huggingface format:
{"prompt": "What is Python?", "chosen": "A programming language.", "rejected": "A snake."}
Options are given in the config to let customers set the names for these columns based on their dataset and internally the keys are mapped back to the above three column names. If a list of files is submitted as input, their columns are validated and then the contents of the files are merged into a single dataframe before loading into local CPU RAM.
Per-sample processing (_process_sequence, called once for chosen, once for rejected):
[{"role": "user", "content": prompt}]withadd_generation_prompt=True→ producesprompt_str[{"role": "user", "content": prompt}, {"role": "assistant", "content": response}]→ producesfull_strprompt_strandfull_strto split them back into the formatted prompt portion and the formatted response portion. This ensures correct boundary detection even when the chat template inserts special tokens between turns.Output per sample (2 tensors + 1 integer):
input_ids(chosen_seq_len + rejected_seq_len,)— Prompt + chosen response + EOS + Prompt + rejected response + EOS, variable lengthloss_mask(chosen_seq_len + rejected_seq_len,)— Chosen loss mask + rejected loss maskboundary_offset— integer value marking where the chosen sequence ends and the rejected sequence starts in the packed tensor4.4 Key Design Decisions
4.4.1 Why Variable-Length and not padding?
The current version of the engine is built around flash attention's variable-length mode (flash_attn_varlen_func), which takes all tokens concatenated into a flat tensor plus
cu_seqlens(cummulative sequence lengths: offsets to distinguish between concatenated samples of variable length) boundaries. NestedTensors store data this way:4.4.2 Why attention_mask is not created ?
FSDPEngine creates its own attention handling from NestedTensor offsets (cu_seqlens). No dataset-provided mask is needed here. Same as MultiTurnSFTDataset.
4.5 Test Coverage
67 tests across 10 sections
TestDPODatasetLoadingTestDPODatasetPackedOutputTestDPODatasetTruncationTestDPODatasetFilteringTestDPOCollatorTestYamlResolutionPreservationTestCollatorSubclassDefaultsTestShuffleDeterminismTestFileLoadingPreservationTestDpoYamlFormattingStandard+TestCodeQualityConstants5. DPO Trainer
5.1 Implementation Options Considered
Option A: FSDP Direct — Manual FSDP wrapping, forward/backward in trainer.
Pros: Simplest implementation; full control; easy debugging.
Cons: Reimplementation required for some features like dynamic batch sizing, profiling, sequence parallelism.
Option B: SPMD TrainingWorker (based on sft_trainer.py) — Uses TrainingWorker abstraction provided by Verl.
Pros: Reuses engine infrastructure; consistent with Verl direction.
Cons: Needs some DPO specific implementations such as two-model (policy and reference) workflow; concatenated_forward for the chosen and rejected samples.
Option C: Ray Single-Controller — Ray driver orchestrates GPU workers via RPC.
Pros: Can overlap ref/policy compute.
Cons: This could prove to be un-necessarily complex approach for something that is as simple as offline DPO unlike RLAIF like training where you need to alternate between rollouts and training.
5.2 Recommended: Option B — SPMD TrainingWorker
Option B inherits dynamic batch sizing, profiling, sequence parallelism, MFU tracking, and checkpointing from the TrainingWorker which are features that would have a high reimplementation cost in other implementation approaches. Option A was initially prototyped but deprecated in favor of the TrainingWorker-based design. TrainingWorker is an abstraction layer provided by verl that uses specialized engines like FSDPEngine underneath to perform the actual training.
5.2.1 Architecture
The trainer mirrors the SFT trainer's initialization process (build config, dataset, engine, dataloader, checkpoint handler) and adds some DPO-specific methods:
5.2.2 Reference Model: Two Modes
LoRA mode (
lora_rank > 0): No separate model needed. Usesself.engine.module.disable_adapter()to temporarily zero LoRA weights, making the base model act as the reference. Same mechanism as PPO/GRPO. Memory efficient — only one model in GPU memory.FFT mode (
lora_rank = 0): A second TrainingWorker withforward_only=True, which triggersCPUOffload(offload_params=True)in FSDP. The ref model streams layers from CPU→GPU one at a time during forward pass, minimizing GPU memory usage.5.2.3 Training Step Flow
Each training step in
DPOTrainer.fit()executes the following sequence:get_seqlen_balanced_partitions_prepare_dpo_batch): Takes the collated batch from the dataloader (B fat sequences as NestedTensors + boundary_offsets as NonTensorStack) and adds position IDs for each fat sequence. The fat sequences are NOT expanded here — they stay packed so dynamic micro-batching can't break pairs. See Section 5.3.1 for more explanation._compute_ref_log_probs): Expands fat sequences into 2B separate interleaved sequences [chosen₀, rej₀, chosen₁, rej₁, ...] at the trainer level, runs the reference model (CPU-offloaded FFT or adapter-disabled LoRA), sums per-token log-probs into per-sequence scalars, and splits intoref_chosen_logps(B,) andref_rejected_logps(B,).batch_num_pairsfor loss scaling,dpo_batch_size).dpo_expand_packed_sequences=Trueflag in the TensorDict metadata, then passes it topolicy_client.train_batch(). Inside the engine:prepare_micro_batches()splits B packed sequences into N micro-batches using bin-packing limited bymax_token_len_per_gpu. Chosen-rejected pairs remain intact as single entries because they are packed into one sequence._expand_dpo_packed_sequences): After micro-batching,prepare_micro_batches()checks for thedpo_expand_packed_sequencesflag. If True, it splits each packed sequence at itsboundary_offsetinto separate chosen/rejected tensors, interleaves them [chosen₀, rej₀, chosen₁, rej₁, ...], creates independent position IDs, and expands ref_logps from (B', 2) to interleaved (2B'). For non-DPO trainers this flag is absent and the step is a no-op.dpo_loss): Sums per-token log-probs into per-sequence scalars (with shifted loss_mask alignment), calls the selected loss variant, and scales the loss (see section 3.6) for correct gradient magnitude.5.3 Design Decisions and Problems encountered
5.3.1 The Pairing Problem
DPO loss requires comparing a chosen response against a rejected response for the same prompt. The loss formula is:
L = -log sigmoid(beta * (chosen_logratio - rejected_logratio))
where chosen_logratio = log P_policy(chosen) - log P_ref(chosen), and similarly for rejected. The subtraction means chosen and rejected MUST come from the same DPO sample.
The challenge: The Verl engine processes batches through internal micro-batching (splitting large batches into smaller chunks for memory efficiency). With this process, a main problem that comes up is:
Problem 1: Dynamic micro-batching rearranges order. If we use dynamic batch sizing (use_dynamic_bsz=True), the engine's bin-packing algorithm groups sequences by token count to maximize GPU utilization. This rearranges sequence order, breaking the chosen/rejected pairing. This issue also goes pretty much undetected because the training can still continue with wrong pairs of chosen and rejected samples.
Example of the pairing problem:
We have 4 DPO samples. After concatenation:
[chosen_0, rejected_0, chosen_1, rejected_1, chosen_2, rejected_2, chosen_3, rejected_3]
Dynamic micro-batching rearranges by token length into:
Micro-batch A: [chosen_2, rejected_0, chosen_0, rejected_3]
Micro-batch B: [rejected_2, chosen_1, rejected_1, chosen_3]
Now in micro-batch A, the loss function pairs chosen_2 with rejected_0 (WRONG — different prompts!) and chosen_0 with rejected_3 (WRONG!). The model gets a noisy learning signal.
5.3.2 Potential Solution 1: Concatenate Chosen and Rejected sample per prompt before dynamic batch sizing and separate before forward pass
Premise: Dynamic batch sizing splits the given batch into several micro batches and then iterates over each batch to compute the gradients. This means all the chosen and rejected samples for a given prompt still stay on the same device, and we just need to make sure they land in the same micro batch.
The solution follows the following steps:
For a given prompt, concatenate the chosen and rejected sample into the same tensor and maintain an offset value to mark the boundary between the two tensors.
Perform dynamic batch sizing to get micro batches.
Once the micro batches are ready, apply a transformation to separate the concatenated tensors back into two separate tensors.
Do the above step before both the forward steps in policy model as well as reference model
The total no of tokens in the micro batch will still be consistent as before the split so this should not affect the results of dynamic batch sizing.
The main advantage that we get from dynamic batch-sizing is that the micro-batch bins that are generated by the batching algorithm have the optimal arrangement of samples based on no-of-tokens in the sample. But because we concatenate the chosen and rejected samples in our case, the no-of-tokens that the batching algorithm sees is the combined value of the two samples. But after we expand them back before doing a forward pass, the new batch now has a different distribution of the no of tokens per sample. This could potentially negate the advantages of dynamic batching in some scenarios.
Example:
Let,
chosen_sample_1 = 100 tokens, rejected_sample_1 = 500 tokens,
chosen_sample_2 = 50 tokens, rejected_sample_2 = 60 tokens,
chosen_sample_3 = 500 tokens, rejected_sample_3 = 500 tokens
Post concatenation: Batch = [[600 tokens], [110 tokens], [1000 tokens]]
dynamic batch-sizing algorithm sees the post concatenation batch and rearranges them.
Potential micro batch distribution: = [110], [600,1000]
Post expansion into chosen and rejected tensors = [50,60], [100, 500, 600, 1000]
The example post expansion tensors show that the token distribution is no longer closer to each other within a micro batch. In most cases, this kind of setup could result in a small tensor ending up in a micro-batch with large tensors, because it was concatenated with a large tensor before dynamic batching was applied. This could go in two directions:
5.3.3 (Recommended) Flag-driven expansion in prepare_micro_batches
Premise: The initial solution (5.3.2) worked correctly but required passing a
micro_batch_transform_fncallback through the engine class hierarchy (BaseEngine → FSDPEngine → forward_backward_batch). This means the common engine classes — which are shared across SFT, and other training algorithms — need to carry DPO-specific plumbing in their method signatures. This makes the engine layer aware of a concern (DPO pair expansion) that only one trainer algorithm cares about.Alternative approach: Instead of injecting DPO logic via a callback into the engine, we move the expansion into
prepare_micro_batches()inverl/workers/engine/utils.py, triggered by a boolean flag in the data TensorDict. The engine classes remain completely unaware of DPO.The updated solution follows these steps:
boundary_offsetmarker, exactly as before.dpo_expand_fat_sequences=Trueas non-tensor metadata in the data TensorDict before callingtrain_batch().prepare_micro_batches()runs dynamic batch sizing as normal, producing micro-batches where DPO pairs are guaranteed to stay together (because they are packed into single fat sequences).prepare_micro_batches()checks for thedpo_expand_fat_sequencesflag. If present andTrue, it applies the expansion to split each fat sequence at itsboundary_offsetinto separate chosen/rejected sequences, interleaved as [c0, r0, c1, r1, ...]. If the flag is absent (which it is for SFT, PPO, and all other trainers), this step is a complete no-op.forward_backward_batch()receives already-expanded micro-batches and processes them normally — no knowledge of DPO required.Key benefit: The Base Engine classes are no longer affected by DPO specific implementation, All DPO-specific data manipulation is now localized to (1) the DPO dataset (fat packing), (2) the DPO trainer (setting the flag), and (3) a single conditional block in
prepare_micro_batches(expansion) which is a utility function. The engine layer stays generic.6. CLI Integration
DPO training continues to use Hydra for configuration management, following the same pattern as other trainers in verl. The config file
verl/trainer/config/dpo_trainer.yamldefines defaults and DPO-specific overrides.6.1 Launch Commands
Basic launch (single node, 8 GPUs)
With CLI overrides
6.2 Entry Point
The DPO trainer can be invoked as a Python module:
7. Correctness Test
For Correctness test, one of the tests involves computing log probabilities and loss values in the first forward pass from the old openrlhf implementation as well as the new Verl implementation and compared against each other with the expectation that they should match if we keep constant other parameters like the sample used and the seed value.
First step (Forward pass only) artifacts comparison between openrlhf (reference) and Verl (candidate) :-
8. Evaluation
9. Appendix (In progress)
9.1 General Experiment Runs
Standard experiment setup:
Total no of epochs: 3
Dataset: Ultrafeedback
Dataset limit: 800
Metrics from Verl
9.1.1 Llama-3-2-1B openrlhf DPO Lora
9.1.2 Llama-3-2-1B Verl DPO Lora
9.1.3 Llama-3-2-1B openrlhf DPO FFT
9.1.4 Llama-3-2-1B Verl DPO FFT
All reactions