Skip to content

18.4 Distributed RL Training

Goal of this section: understand the sources and corrections of training-inference mismatch, learn how veRL assigns models and GPUs with ResourcePool, Worker, and Driver, review common techniques for generation throughput and training memory, and decide when asynchronous scheduling is necessary.

The final diagnostic step in the previous section compared model versions and probabilities on the generation and training sides. That check assumed that generation, scoring, and updating were three sequential function calls in one script. Once training moves to a cluster, the assumption no longer holds.

Training a 70B mathematics model together with a Reference Model and Reward Model can involve more than one hundred billion parameters. Generation must run on one GPU group and updates on another. A batch then moves through a distributed loop:

  1. Generation: rollout GPUs generate responses from the current policy, often taking seconds per response.
  2. Scoring: reward processes consume the responses and call verifiers or reward models.
  3. Updating: training GPUs compute gradients and update the Actor, often in hundreds of milliseconds.
  4. Synchronization: the new parameters must return promptly to the rollout GPUs.

On one machine these are function calls. Across machines each becomes data transfer and waiting between processes. If parameters arrive late, the next batch is still generated by an old policy and the consistency established in 18.3 is lost.

This section answers four questions: where generation-training probability differences come from, how models are placed on GPUs, which bottleneck to address first—generation speed or training memory—and when asynchronous scheduling is worth the stale-experience cost. MoE models add expert routing and pipeline utilization to the same design.

First-pass takeaway

Remember the order: generation → reward → update → synchronize parameters. veRL, slime, and OpenRLHF implement it differently, but all decide which GPUs perform these four steps and when data moves between them.


Where Training-Inference Mismatch Comes From

Parameter synchronization solves version drift: rollout and training GPUs receive the same weights. The same weights do not guarantee the same probabilities.

Suppose vLLM on the rollout side computes a token probability of 0.30 in FP8, while the trainer recomputes 0.29 from the same weights with BF16 and different kernels. Neither computation is inherently wrong. The paths differ: vLLM or SGLang uses KV caches and low precision for generation speed, while FSDP or Megatron retains a computation graph for backpropagation.

Let denote the policy actually executed by the rollout engine and the old policy recorded by the trainer. They should match. Floating-point precision, kernel implementations, and MoE routing can make them diverge. This is training-inference mismatch.

  • The rollout side usually generates with vLLM or SGLang in FP8 or BF16 and uses KV-cache optimizations.
  • The training side usually computes log probabilities and gradients with FSDP or Megatron in BF16 or FP32, sometimes with activation recomputation.

Small errors on high-probability tokens are often harmless. Errors on many low-probability tokens can accumulate and directly distort the importance ratio in PPO.

Why PPO Clipping Cannot Correct This Mismatch

PPO constrains the size of one update with

where

measures how much better action is than the current baseline, and controls the allowed deviation from 1. If the old policy assigns probability and the new policy assigns , then , exactly the upper boundary when .

This calculation assumes that the denominator is the policy that generated the action. If the response came from while the trainer recomputed along a different numerical path, the ratio is wrong before any update begins. Clipping can limit parameter movement; it cannot reconcile probabilities computed by two engines.

Diagnose the mismatch in this order:

  1. Verify the model version used for rollout and confirm that synchronization completed.
  2. Record log probabilities for the same tokens on both sides and locate where errors concentrate.
  3. Align precision and kernels, then measure whether the discrepancy shrinks.
  4. For MoE models, record expert routing and verify that training reproduces the rollout route.

Correcting Training-Inference Mismatch

  • Align numerical precision: temporarily replace FP8 rollout with FP16 or BF16 to determine whether low precision dominates the error. If FP8 remains necessary, monitor the discrepancy and apply importance-sampling corrections.
  • Record the actual behavior policy: save rollout-time log probabilities rather than treating a trainer-side recomputation as the behavior probability.
  • Recompute and validate: recompute log probabilities with the training engine and compare them token by token. Recalculation does not recover the true behavior policy, but it exposes the location and size of the mismatch.
  • Limit extreme ratios: Truncated Importance Sampling clips unusually large ratios so that a few anomalous tokens cannot dominate the gradient.
  • Handle tail tokens: dynamic vocabulary pruning can remove the lowest-probability region where discrepancies are largest.
  • Replay MoE routing: R3, or Rollout Routing Replay, reproduces rollout expert choices during training.

The degree of on-policy training depends on the distance between and the current policy. Parameter synchronization controls version distance; precision alignment, probability logging, and importance-sampling correction control computation-path differences.


Allocating Models and GPUs

Once probabilities align, five roles still need GPU placement and data exchange: Actor, Critic, Reference Model, Reward Model, and rollout engine. veRL divides this problem into the algorithm loop, model computation, and resource allocation.

HybridFlow uses single-controller, multi-model orchestration. One Driver runs the algorithm loop and resource scheduler, directing Workers on individual GPUs. Workers represent the Actor, Critic, Reference Model, Reward Model, and rollout engine and share ResourcePools.

Three Core Abstractions

ResourcePool: groups of GPUs. A pool can host one or more models. Models can share GPUs through colocation or use separate disaggregated pools.

Worker: an encapsulated model instance. ActorWorker handles loss, backpropagation, and optimizer updates. RolloutWorker handles batched generation and weight synchronization.

Driver: the single controller. It executes the RL loop: synchronize weights to rollout → sample responses → score them → compute values with the Critic → compute advantages and update the Actor → update the Critic.

HybridFlow's “hybrid” design allows one framework to combine 3D parallelism (TP × PP × DP), colocated or disaggregated deployment, FSDP/Megatron/DeepSpeed ZeRO training backends, and vLLM/SGLang/Hugging Face generation backends.

Comparing Mainstream Framework Architectures

FrameworkOrchestrationTraining BackendInference BackendTypical ScaleRepresentative UsersBest Fit
veRL (HybridFlow)Single controllerFSDP, Megatron-LM, DeepSpeed ZeROvLLM, SGLang, HF generate8–1024 GPUsQwen, DeepSeek, ByteDanceLarge-scale production and flexible resource combinations
OpenRLHFSingle controller with Ray Actor isolationFSDP, DeepSpeedvLLM8–256 GPUsCommunity and research teamsResearch and medium-scale training
NeMo-AlignerMultiple controllersMegatronTensorRT-LLM8–512 GPUsNVIDIA ecosystem and enterprise clustersProduction environments already using NeMo
TRLSingle processHugging Face AccelerateHF generate1–8 GPUsLearners and rapid prototypesAlgorithm learning and small experiments

Choose from current scale and the existing stack: TRL for learning and prototypes; OpenRLHF or veRL for research and medium scale; veRL or NeMo-Aligner for large production systems.


Generation Speed and Training Memory

After placement, two bottlenecks dominate. Generation often consumes most of an iteration, while training must store weights, gradients, optimizer state, and activations. We first increase rollout throughput, then distribute training memory.

Core vLLM Optimizations

TechniqueProblemPrincipleTypical BenefitImportance for GRPO
PagedAttentionContiguous KV-cache allocation fragments memory and yields 50%–70% utilizationDivide KV cache into fixed blocks and allocate them on demand, like virtual-memory pages95%+ utilization and 2–4× larger effective batchesFoundational
Continuous BatchingStatic batches wait for every sequenceInsert a new sequence as soon as another emits EOS5–10× higher aggregate throughputLargest benefit for long responses
Speculative DecodingAutoregressive decoding has low compute densityA small draft model predicts several tokens and the large model verifies them in parallel2–3× typical inference throughputUseful for short, latency-sensitive responses
Prefix Caching responses to one prompt repeat prefix computationHash and reuse the prompt's KV cacheSaves 70%–80% of prefix computation for A core GRPO optimization

SGLang Generation and Scheduling

SGLang uses RadixAttention to manage KV cache in a radix tree and reuse it across requests. Its programmatic frontend supports multi-turn calls, branches, and loops, and constrained decoding supports JSON and regular expressions.

EngineCore StrengthBest Fit
vLLMMature PagedAttention and Continuous Batching ecosystemGeneral rollout, single-turn generation, GRPO for mathematics and code
SGLangRadixAttention, multi-turn control flow, structured outputAgentic rollout, multi-turn tools, constrained decoding
TensorRT-LLMDeep NVIDIA optimization and strong FP8 supportMaximum-throughput production on NVIDIA hardware

Distributing Memory Across GPUs

A 70B model cannot perform full-parameter BF16 training on one 80GB H100. With BF16 weights and gradients plus FP32 master weights and Adam moments, each parameter requires about 16 bytes:

ComponentTypeBytes per Parameter70B ModelPurpose
WeightsBF16/FP162 B140 GBCurrent parameters
GradientsBF16/FP162 B140 GBAccumulated after backpropagation
Master weightsFP324 B280 GBStable optimizer copy
Adam first momentFP324 B280 GBGradient moving average
Adam second momentFP324 B280 GBSquared-gradient moving average
ActivationsBF16/FP16Dynamic~100 GBDepends on batch and sequence length
Total16 B/parameter~1.22 TBFar beyond one H100

DeepSpeed ZeRO shards progressively more state:

LevelOptimizer StateGradientsWeightsPer-GPU SavingCommunicationBest Fit
ZeRO-1ShardedReplicatedReplicated~4×LowMedium models or communication-limited systems
ZeRO-2ShardedShardedReplicated~8×MediumDefault for many training jobs
ZeRO-3ShardedShardedSharded× for GPUsHighFull-parameter large-model training

ZeRO-3 all-gathers the needed parameters temporarily during forward and backward passes. FSDP is PyTorch's native equivalent and veRL's default training backend.

Gradient checkpointing exchanges compute for memory. It saves only selected forward activations and recomputes the rest during backpropagation, reducing activation memory from to for Transformer layers while slowing training by roughly 20%–30%.

For a 70B model on 80GB H100s:

ConfigurationPer-GPU MemorySpeedFeasible?
Full parameters + Adam, no sharding~940 GBBaselineNo
ZeRO-3 training-state sharding~118 GB10%–15% slowerStill no
ZeRO-3 + gradient checkpointing~30 GB30%–40% slowerYes
ZeRO-3 + checkpointing + LoRA~8 GB~40% slower per step, but far fewer trainable parametersYes

Industrial 70B RL often combines LoRA with FSDP to balance memory, speed, and training quality.


When Task Durations Diverge: Asynchronous Scheduling

Synchronous scheduling assumes similar rollout durations. Mathematics and ordinary code problems often satisfy that assumption. Tool and browser tasks do not: one trajectory may wait for an environment response while another has finished, leaving training GPUs idle behind the slowest task.

Asynchronous training lets generation and updating advance independently through a queue. Its cost is stale experience: the policy may update several times while a trajectory is being generated.

Comparing Three Asynchronous Frameworks

FrameworkPublisherCore DesignStaleness HandlingTypical ScalePublished SpeedupRepresentative Use
LlamaRLMeta, 2025Decentralized rollout and training workers with asynchronous weight broadcastNo explicit importance correction; continual version updates replace old samples4096+ GPUs10.4× over synchronous Llama-3-70B GRPOVery large reasoning jobs
AReaLAnt Group + Tsinghua, 2025Fully asynchronous rollout; each trajectory records policy version and log probabilityToken-level weights , clipped to 1024 GPUs2.77× for 671B MoE GRPOMoE tasks requiring explicit bias control
AgentRLTHUDM/Zhipu, 2025Asynchronous generation-training pipeline plus a unified environment interfaceQueues, task isolation, and independently managed multi-turn sessionsMulti-machine, multi-environmentUsed for AutoGLMSWE, computer use, and deep research

LlamaRL favors simple horizontal scale: no central worker and no explicit correction. AReaL stores more trajectory metadata to compute and clip an explicit correction. AgentRL adds environment management because external interaction can take longer than model generation itself.


MoE and Pipeline Idle Time

The preceding design assumed a dense model and a full pipeline. MoE adds expert routing and all-to-all communication, while uneven sequences create pipeline bubbles.

Additional Complexity from MoE

DeepSeek V3, Qwen3, and GLM-4.5 use MoE. Each token activates only a few experts, distributing parameters across GPUs, but RL changes the token distribution and therefore expert load.

For illustration, a model may have about 20B dense parameters plus 256 experts of 5B parameters each. A sample activates eight experts, so roughly 40B expert parameters and 60B total parameters are active out of about 1.3T.

ChallengeSymptomMitigationRepresentative Work
Expert-load imbalanceHot experts are overused while others remain idleBalancing loss toward activation frequency and dynamic routingDeepSeek-V3, GShard
Cross-GPU communicationExpert parallelism requires token all-to-allOptimize all-to-all kernels and overlap communication with computationDeepEP
High token-level IS varianceRouting differences make token ratios fluctuateUse one importance ratio for the whole sequenceGSPO

Reducing Pipeline Idle Time

TechniqueProblemPrincipleBenefit
DualPipePipeline bubbles prevent forward/backward overlapBidirectional scheduling overlaps forward stage with backward stage on one GPUBubble ratio falls from to
Best-Fit PackingUneven micro-batches finish at different timesBin-pack different sizes across GPUsDeepSeek V3 reports utilization rising from 70% to 95%

Locating Performance Bottlenecks

Every optimization can move the bottleneck. Faster generation may expose weight synchronization; sharding may expose communication; packing may expose data loading.

ToolPurposeWhat It ShowsBest Stage
PyTorch ProfilerPyTorch performance analysisCPU/CUDA timeline, memory, kernel time, expensive operationsTraining optimization
NVIDIA Nsight SystemsSystem-level GPU profilingCUDA kernels, CPU-GPU synchronization, NCCL communication, stream overlapCommunication and scheduling
veRL ProfilerRL pipeline decompositionRollout, Actor, Critic, synchronization, and communication sharesFirst choice for RL pipelines
SymptomThresholdDirection
Slow rolloutMore than 80% of total timeAdd rollout GPUs, enable prefix caching, increase batch size, or separate deployment
Slow weight synchronizationMore than 5%Synchronize LoRA adapters, pack NCCL transfers, or synchronize less often
Heavy cross-GPU communicationall-reduce/all-gather over 10%Increase micro-batches, accumulate gradients, or change the parallel partition
Activation OOMCUDA out of memory during trainingEnable checkpointing, shorten maximum sequences, or reduce batch size
Expert imbalanceSome GPUs at 90% while others are near 30%Add expert-balancing loss and adjust routing or EP balancing
StragglersLongest sequence determines the batch timeLength bucketing or predicted-length grouping

Model FLOPs Utilization is

ConfigurationTypical MFUMain Bottleneck
Dense + FSDP + checkpointing, synchronous35%–45%Activation recomputation and all-reduce
MoE + expert parallelism + DualPipe50%–60%Expert all-to-all and load imbalance
Asynchronous RL with separate rolloutTrainer 40%–50%, rollout 70%–80%Synchronization and queue waiting

Below 30% MFU, inspect communication, data loading, and rollout waiting with the time decomposition.


Summary

Distributed training still follows generation → reward → update → synchronize parameters. Every technique in this section addresses a bottleneck in that loop.

  • Training-inference mismatch: identical weights do not guarantee identical probabilities. PPO clipping cannot repair differences between inference and training computation paths. Align precision, record the true behavior policy, and clip extreme importance ratios.
  • Resource allocation: veRL groups GPUs with ResourcePool, encapsulates models with Worker, and runs the algorithm loop through a single Driver.
  • Two bottlenecks: PagedAttention, Continuous Batching, and Prefix Caching improve rollout throughput; FSDP/ZeRO and gradient checkpointing distribute training memory. A 70B model needs roughly 1.2TB for full training state, while ZeRO-3 plus checkpointing can reduce the per-GPU requirement to about 30GB.
  • Synchronous versus asynchronous: synchronous training keeps data fresh. Asynchronous training reduces waiting but introduces stale trajectories. LlamaRL applies no explicit correction, AReaL corrects explicitly, and AgentRL isolates multi-turn environment tasks.
  • MoE and pipelines: MoE adds expert imbalance and all-to-all communication; DualPipe and Best-Fit Packing reduce idle time.

Distributed systems coordinate compute, but training still needs a steady supply of executable and verifiable data. 18.5 Large-Scale RL Data Engineering follows the lifecycle of a trajectory through tasks, environments, rewards, and failure feedback.

Further Reading

Hands-on Modern Reinforcement Learning