Introduction

Volcano Engine Reinforcement Learning (VERL) is an open-source framework for fine-tuning large language models (LLMs) with reinforcement learning. VERL (open-sourced by ByteDance as “HybridFlow”) provides a flexible, modular architecture to implement RL algorithms (like PPO and many variants) at scale. It is designed for RLHF-style training: aligning LLMs (e.g. Qwen-3, Gemma-3, Llama, etc.) to desired behaviors by optimizing a reward signal (from humans or programs). VERL abstracts the RL training loop into distributed components so that even very large models (tens of billions of parameters) can be fine-tuned efficiently across multiple GPUs. In this tutorial, we will rigorously examine VERL’s architecture, core algorithms, and how to use it – including the VERL-Agent extension for interactive reasoning tasks – with detailed explanations and code examples.

Key Goals: We will explain how VERL’s major modules work together to enable RL fine-tuning of LLMs. This includes:

  • An overview of VERL’s architecture and major packages (trainers, workers, controllers, etc.) and their purpose.
  • The RL algorithms and objectives supported (from PPO to newer variants like GRPO, DAPO, etc.) and how reward modeling is incorporated.
  • Mathematical formulations for important objectives (e.g. PPO loss, reward calculations) to ground the discussion.
  • A walkthrough of the implementation: how VERL collects data (model rollouts), computes rewards, and updates the model (policy and value). We’ll inspect components like the reward model, policy trainer logic, dataflow between actor/critic, and how VERL interfaces with LLM backbones.
  • Using VERL-Agent for multi-turn reasoning tasks (LLM agents in environments): how to integrate an environment, define prompts, and apply algorithms like GiGPO for long-horizon credit assignment.
  • Practical tips on multi-GPU training (e.g. using 4×H100 GPUs): how to configure distributed training, use sharded models, and scale up to large models.

Throughout, we include code snippets, configuration examples, and references to the VERL codebase to illustrate these concepts in practice. Let’s start by looking at the overall architecture and design of VERL.

VERL Architecture and Components

VERL follows a controller-worker architecture to orchestrate the complex RL training loop for LLMs. The design cleanly separates different responsibilities (policy model, value model, data generation, reward evaluation, etc.) into modular components. Major components include:

  • Trainer Controller – The central controller that coordinates the RL training loop. In VERL, this is often a Ray-based trainer (e.g. RayPPOTrainer) that spawns and manages multiple worker processes. The trainer reads the config (hyperparameters, model paths, etc.), initializes workers, and implements the high-level loop (collect rollouts, compute rewards, update model, etc.). For example, main_ppo.py is the entry script that constructs a RayPPOTrainer with the given config and kicks off training.
  • Workers (Actor, Critic, etc.) – Separate processes (on one or multiple GPUs) that hold portions of the model and perform specific roles in the RL pipeline. VERL defines Role enums for different functionalities:
    • Actor: the policy model that generates outputs (the LLM we are fine-tuning).
    • Rollout: a module handling generation/inference (for producing rollouts from the actor).
    • Critic: the value function model (if using an actor-critic algorithm) that predicts value of a given state or input.
    • Ref (Reference Policy): a fixed reference model (usually a copy of the pre-trained model) used to compute KL divergence penalties for KL-controlled RLHF.
    • Reward Model: a model to score the outputs (for learning from a learned reward function).
    • Hybrid roles: combinations for efficiency, e.g. ActorRollout (a worker that holds both actor and rollout functionality) or ActorRolloutRef (holds actor, rollout, and reference policy together). These “hybrid engine” workers allow sharing one process/GPU for multiple roles to reduce overhead. For instance, VERL provides a pre-built ActorRolloutRefWorker that can be configured to act as just an actor, just rollout, or both, depending on the context.
  • Single-Controller and Resource Manager – VERL uses a single-controller paradigm with hierarchical control to manage distributed training efficiently. The trainer (controller) uses a ResourcePoolManager to assign workers to hardware resources. In configuration, you specify trainer.n_gpus_per_node and trainer.nnodes (number of GPUs per node and number of nodes); VERL then creates resource pools. For example, a global pool might consist of all 4 GPUs on a node, and all roles (actor, critic, etc.) can be mapped to that pool (meaning they share those 4 GPUs). This co-location approach is often used for moderate model sizes. The Resource Manager supports more complex mappings too – e.g., isolating certain roles on different GPU sets if needed (for very large models or custom parallelism).
  • Backends for Training and Inference – VERL is backend-agnostic and integrates with multiple frameworks:
    • FSDP (Fully Sharded Data Parallel): a PyTorch distributed training backend where the model is sharded across GPUs to save memory. VERL fully supports PyTorch FSDP (and its improved version FSDP2) for large models. In config, actor.strategy = 'fsdp' (or 'fsdp2') enables this. FSDP shards model weights and gradients across processes, allowing models up to 70B or more to be trained on multiple GPUs. VERL’s fsdp_workers.py defines worker classes for this backend (e.g. DPActor for data-parallel actor).
    • Megatron-LM: integration for model-parallel training (e.g. tensor and pipeline parallelism). VERL can leverage NVIDIA’s Megatron-LM for extremely large models by splitting them across GPUs (intra-layer or inter-layer parallelism). The megatron_workers.py and submodules define analogous worker classes for Megatron-based models.
    • vLLM & Transformers: for text generation (rollouts), VERL can use high-performance inference engines. Notably, it integrates vLLM (a specialized LLM inference engine) to generate responses very efficiently. vLLM uses optimized KV caching and can serve many prompts in parallel, which greatly boosts rollout throughput. There’s also integration with HuggingFace Transformers or TGI for generation. These are used in the Rollout workers – e.g. vllm_rollout.py implements generation using vLLM’s fast APIs.
    • Sharding & Hybrid Engine: A highlight of VERL’s design is the 3D-HybridEngine for actor model resharding. This addresses the challenge of switching a large model between training mode (needs model sharded across GPUs for backprop) and generation mode (ideally model replicated or loaded for fast forward passes). VERL’s sharding_manager module (files like fsdp_vllm.py, megatron_vllm.py) implements logic to reshard or move the actor model between these phases with minimal overhead. It ensures there’s zero redundant memory copy – e.g., it can keep sharded weights in GPU memory and only assemble them on the fly for generation or use distributed generation without full replication. This dramatically reduces memory overhead and communication when alternating between training and rollout phases in RLHF. In practice, when ActorRollout roles are combined, the worker can seamlessly shift from using the actor in shard mode for training to using it for generation via these managers.
  • Utilities and Data – VERL also provides supportive modules:
    • Dataset interfaces: The verl.utils.dataset package defines how training data is loaded. For RLHF fine-tuning, data typically consists of prompts (and possibly reference responses or other metadata). VERL expects data in a Parquet format for efficiency, and provides an RLHFDataset class to load/tokenize it. At minimum, each data entry should have a prompt field (the input text). Additional fields (like a reference answer, or tags to choose a reward function) can also be included. VERL’s examples include preprocessing scripts for popular datasets (GSM8K, MATH, HH-RLHF, etc.).
    • Reward functions and models: Under verl.utils.reward_score are function-based reward implementations for specific tasks. For example, gsm8k.py contains a function to extract the final answer from a math solution and assign a reward of 1 for correct or 0 for incorrect. These task-specific reward functions are used when a straightforward automated check is possible (math, code tests, etc.). VERL also supports model-based rewards: i.e., using a learned reward model (often a Transformer scoring model) to evaluate responses. The RewardModelWorker in VERL is designed to host a HuggingFace AutoModelForSequenceClassification as a reward model. If config.reward_model.enable=True, VERL will spin up a reward model worker, load the specified model, and query it to get reward scores. The RewardManager class wraps both approaches, deciding which reward function to apply based on the dataset or context. For instance, if the data source tag is 'openai/gsm8k', the manager uses the GSM8k function; if it’s a human feedback dataset with a learned reward model, it uses the model’s score directly.
    • Logging and Tracking: VERL can log metrics to various trackers (Weights & Biases, TensorBoard, etc. as configured). This helps monitor reward scores, losses, KL divergence, etc., during training.

Repository Structure: To ground this in code, here is a simplified view of VERL’s repository layout:

verl/
├── trainer/
│   ├── main_ppo.py            # Entry point for PPO training jobs (config parsing, trainer init)
│   └── ppo/ray_trainer.py     # Core training loop implementation (RayPPOTrainer class, Role definitions, etc.)
├── config/
│   ├── ppo_trainer.yaml       # Hydra config template for PPO training (hyperparams, paths, etc.)
│   └── generation.yaml        # Config template for generation (rollout settings like sampling)
├── workers/
│   ├── fsdp_workers.py        # Worker classes for FSDP backend (ActorRolloutRefWorker, CriticWorker, RewardModelWorker)
│   ├── megatron_workers.py    # Worker classes for Megatron backend
│   ├── actor/dp_actor.py      # Implementation of Actor model (forward, backward) under FSDP (data-parallel)
│   ├── actor/megatron_actor.py # Implementation of Actor under Megatron (model-parallel)
│   ├── critic/dp_critic.py    # Critic model for FSDP
│   ├── rollout/vllm/vllm_rollout.py    # Rollout (generation) logic using vLLM engine
│   ├── rollout/hf_rollout.py           # Rollout using HuggingFace Transformers
│   └── sharding_manager/fsdp_vllm.py   # Utilities for resharding model between FSDP training and vLLM inference
├── utils/
│   ├── dataset/rlhf_dataset.py # Dataset loading classes for RLHF
│   ├── reward_score/gsm8k.py   # Example function-based reward computation for GSM8K
│   ├── reward_score/math.py    # Reward functions for MATH dataset, etc.
│   └── seqlen_balancing.py     # Sequence length balancing utilities (optimize packing/padding for efficiency)
└── models/
    ├── llama/           # Integration for loading LLaMA, Gemma, etc. into Megatron format
    ├── transformers/    # Integration with HuggingFace models (DeepSpeed-Ulysses optimizations, etc.)
    └── weight_loader_registry.py   # Registry that maps model names to appropriate loader (HF vs Megatron)

This modular design lets VERL plug into different model implementations and hardware setups. Next, we’ll dive into the RL algorithms and training objectives that VERL supports, and how they are implemented.

RL Algorithms and Objectives in VERL

VERL is algorithm-flexible – it supports the standard PPO for RLHF as well as a growing list of advanced variants and research algorithms. The core goal in all cases is to fine-tune the LLM (the “policy”) such that it produces higher-reward outputs, while maintaining stability (preventing divergence or loss of quality). We’ll first discuss Proximal Policy Optimization (PPO), then outline other notable algorithms (e.g. GRPO, DAPO, PF-PPO, RLOO, etc.), and explain how reward modeling fits into the training objective.

Proximal Policy Optimization (PPO)

PPO is a popular on-policy RL algorithm and is the workhorse for many RLHF implementations. In VERL, the PPO objective is implemented in the actor update step of RayPPOTrainer. Conceptually, PPO maximizes the expected reward while penalizing too large a change in the policy from the previous iteration (to ensure stable, small updates). The clipped policy objective per time step t can be written as:

LPPO(θ)=Et[min⁡(rt(θ)At,  clip(rt(θ),1−ϵ,1+ϵ) At)],L_{\text{PPO}}(\theta) = \mathbb{E}_t\Big[ \min\big(r_t(\theta) A_t,; \text{clip}\big(r_t(\theta), 1-\epsilon, 1+\epsilon\big) ,A_t\big)\Big],

where is the probability ratio of the new policy vs. old policy for the taken action, and is the advantage estimate. The with clipping means if the policy tries to change too much (beyond ), the objective is capped, preventing the update from going in a direction that would drastically change the policy. This helps keep training stable.

In LLM fine-tuning context:

  • The “state” can be thought of as the input prompt (or conversation state), and the “action” is the model’s generated response. Often we consider an entire prompt→response as one decision (for single-turn tasks).
  • The reward is obtained after the model produces a response. VERL uses either a learned reward model or a function-based evaluator to assign a scalar reward to the response (higher for preferred outputs). In PPO, this reward is typically converted to an advantage , where is the value function’s prediction (the baseline for that prompt).
  • VERL maintains a Critic (Value) model in PPO training. The critic is a model (often initialized as a copy of the LLM with an extra value head) that is trained to predict the reward (or return) given the prompt. The critic is updated by minimizing a value loss to fit the observed rewards. This helps provide better advantage estimates over time.

KL Penalty (RLHF-specific): In RLHF, we usually include a Kullback-Leibler penalty to keep the fine-tuned policy from straying too far from the initial model (which preserves fluency and prevents nonsense). VERL incorporates this via a reference policy and a KL coefficient:

  • The reference policy is a frozen copy of the original model (or a pretrained model) that does not update. During training, for each generated response, the KL divergence between the new policy and the reference is computed (often summed over the tokens of the response).
  • The reward is then modified as: , where is the raw reward (from the reward function or model) and (configurable) is the KL penalty coefficient. Intuitively, this means the policy is encouraged to maximize the original reward but is penalized if its output distribution diverges too much from the reference. A small (e.g. 0.001 in the GSM8K example) keeps the language model’s style/tone closer to the original while still optimizing the reward.
  • VERL’s config algorithm.kl_ctrl.kl_coef sets this . VERL also supports dynamic adjustment of KL coefficient (kl control) to target a certain KL value, though by default a fixed coefficient can be used.

In VERL, PPO training proceeds roughly as:

  1. Rollout Generation: Sample a batch of prompts from the dataset. Each prompt is fed to the actor model (policy) to generate a response. This generation can be done with strategies like temperature sampling, and is often truncated to a max length. VERL uses the Rollout workers (possibly using vLLM for speed) to generate these outputs in parallel.
  2. Reward Evaluation: For each prompt+response, compute a reward. If using a reward model, the RewardModel worker returns a score (often the predicted “quality” or preference). If using function-based rewards, the RewardManager calls the appropriate function – e.g., checking if the math answer is correct. If a KL penalty is in use, compute the log-prob of the response under the reference model as well (the RefPolicy worker does this) and combine it with the reward.
  3. Compute Advantage: The advantage is computed for each sample (where comes from the critic model’s forward pass on the prompt). If using Generalized Advantage Estimation (GAE) for multi-step scenarios, the advantages would be computed over trajectories; but for single-turn tasks, advantage is often just reward minus baseline. In VERL’s single-turn RLHF examples, they effectively treat each prompt-response as one step, so .
  4. Policy Update: The actor model is updated via gradient ascent on the PPO objective. VERL will take the batch of (prompt, response, advantage, old log-probs, etc.) and perform several epochs of mini-batch updates on the policy. Hyperparameters like ppo_mini_batch_size and ppo_epochs control this. The loss includes the clipped policy loss and typically an entropy regularization term to encourage policy entropy (to avoid a too-deterministic policy). VERL logs metrics like policy loss, policy KL, entropy, etc. for each update step.
  5. Value Update: Simultaneously, the critic (value network) is updated by minimizing the value loss () on the batch, and possibly a value clipping (to avoid too large value function updates, similar to PPO’s policy clipping logic). VERL’s logs show critic/vf_loss and critic/grad_norm for these updates.
  6. Repeat: The process iterates for many batches/steps. Typically after each update, the old policy is set to current for the next iteration. VERL organizes training into epochs or iterations, and can periodically evaluate on a validation set (e.g., by generating answers for val prompts and computing a reward metric).

Mathematical aside: The inclusion of the reference model and KL penalty can also be viewed as maximizing a regularized objective: maximize . This connects to the idea of maximizing a reward while staying close to an original model (often preventing the language model from going out-of-distribution). If is small, the policy has more freedom; if large, the policy stays very near the original model (at , it wouldn’t change at all).

VERL’s PPO is a distributed implementation of the above: The heavy computation of forward/backward on the actor and critic is done in parallel across GPUs. For example, with 4 GPUs, if using FSDP, each GPU holds a shard of the model and they collectively compute the forward pass for a batch. Ray is used to coordinate these workers (sending prompts to the rollout worker, collecting rewards, then initiating training on actor/critic workers). The RayPPOTrainer.fit() method encapsulates these steps, and one can inspect its code for details. As a user, you typically don’t have to manage this manually – you configure the YAML and run the main_ppo.py launcher, which under the hood runs these steps and prints/logs the results.

Reward Modeling in VERL

A critical part of RLHF is the reward model (RM). Training such a model from human preference data is often a separate preceding step; however, VERL is mainly focused on the RL fine-tuning stage using an existing reward model. In VERL’s design:

  • If you have a pretrained reward model (say, a 6B reward model that scores outputs for helpfulness), you can load it via config (reward_model.path). VERL’s RewardModelWorker will load this model and use it to score each generated response. The RM is usually a classifier model that outputs a score or logit (which VERL interprets as a reward signal). The reward model is not updated during PPO; it provides a fixed objective.
  • If you don’t have a learned RM and the task has a verifiable metric, you can implement a custom reward function. For example, GSM8K math problems have a ground-truth answer, so one can programmatically check if the model’s answer is correct. VERL’s RewardManager makes it easy to plug in such logic. You implement a Python function that takes in the prompt and model output, and returns a float score. Then you register it in _select_rm_score_fn for a certain data tag. In the GSM8K example, the reward function uses regex to extract the final answer and compares to the true answer, giving +1 or 0. For code generation, a reward function might compile and run test cases, awarding points for passing tests.
  • Combination: VERL’s RewardManager can also combine multiple signals. For instance, one could have a reward that is a weighted sum of a grammar-check score, a factuality score, and a task-specific score. The code snippet in VERL’s PPO example shows pseudocode: “if model-based RM, call the model; if function-based, call function; finally combine all rewards”. In practice, most use cases pick one primary reward source, but VERL is flexible to multi-source rewards.

The reward signal ultimately guides the policy updates. It’s worth noting that reward scaling and normalization can be important. Some algorithms (like ReMax or others) might normalize rewards in a batch. PPO often benefits from advantage normalization (zero-mean, unit-std advantages). VERL likely normalizes advantages internally (this is common practice, though we would confirm in code). Also, if rewards are very sparse (mostly 0 and occasionally 1), techniques like moving average baselines or explicit curriculum may be needed – some of the advanced algorithms address this.

Beyond PPO: Advanced Algorithms in VERL

In addition to PPO, VERL implements several PPO variants and alternative RLHF algorithms. These often aim to improve training stability, sample efficiency, or handle scenarios where a critic is hard to train. We’ll briefly describe the major ones:

  • REINFORCE and REINFORCE++: REINFORCE is the classic policy gradient which simply uses the return as advantage (with optionally a baseline). It’s typically unstable for LLMs. REINFORCE++ is a recent improvement that incorporates techniques from PPO (like clipping and normalization) without using a critic network. Instead, REINFORCE++ uses the mean reward of the batch as a baseline (or other normalization). This greatly simplifies training (no value model needed) and can be more stable than naive REINFORCE. VERL includes REINFORCE++ as one option. Essentially, it treats the entire batch of trajectories and calculates relative advantages: each sample’s advantage = reward – (average reward of batch). This yields a zero-centered advantage which serves as a baseline, achieving a similar effect to a learned critic but more robustly. REINFORCE++ is sometimes the basis for other algorithms below.
  • GRPO (Groupwise PPO): This is a critic-free algorithm that extends the idea of REINFORCE++ by computing advantages based on groups of trajectories. The intuition is to use the relative ranking of a set of trajectories to determine advantages rather than absolute values. For example, you can take a group of complete episodes, sort them by total reward, and assign relative advantage scores (higher reward trajectories get positive advantages, lower get negative). GRPO eliminates the value network and uses only comparisons within a group to estimate . According to the VERL docs, GRPO “estimates relative advantages based on a group of full episode trajectories” and is critic-free. It’s related to the idea of ranking-based reward attribution. GRPO was found effective in single-turn tasks like math reasoning (improving stability when reward scaling is tricky). It’s essentially a form of ranking-based policy optimization where the policy is updated to favor trajectories that performed better than others in the group. VERL’s implementation of GRPO likely uses a batch of episodes as one group each iteration.
  • DAPO (Decoupled Clip and Dynamic sAmpling PPO): DAPO is an advanced PPO variant introduced by the team in early 2025. It incorporates four key techniques to improve LLM RL training. Two notable techniques mentioned are:
    • “Clip-Higher” (Decoupled Clipping): In normal PPO, we clip the policy ratio on both sides (preventing both excessively large increases and decreases in probability). The “clip-higher” trick raises the upper bound of the clip range, effectively allowing the policy to improve (increase probability of beneficial actions) more freely while still limiting decreases. This can prevent premature stagnation and “entropy collapse” – i.e. it encourages exploration by not over-penalizing large positive updates.
    • Dynamic Sampling (Experience filtering): DAPO dynamically filters or reweights the training samples based on reward quality. For example, it might drop trajectories with very noisy reward signals or up-sample trajectories with reliable high rewards. The idea is to focus learning on high-quality experiences and not let random bad rollouts introduce too much variance. This is sometimes called “dynamic experience replay” or “adaptive sample selection”. In the VERL context, enabling dynamic filtering can improve stability on long sequences or sparse reward tasks (this is mentioned as an option in OpenRLHF too).
    • Token-level value loss, and others: (From references in RLHF literature, DAPO and related work sometimes adjust how value heads are trained – e.g., training value at each token vs end-of-episode – and other tricks.)
    The combination of these makes DAPO achieve state-of-the-art results on some benchmarks. The VERL README notes that DAPO is open-sourced and achieved ~50 points on a reasoning benchmark (AIME) with a Qwen2.5-32B model. In practice, to use DAPO in VERL, one would choose the main_ppo.py (or a variant) with algorithm settings for DAPO (the config might have algorithm.name = dapo and extra options like clip_higher=True, dynamic_sampling=True).
  • RLOO (Reinforcement Learning with Leave-One-Out): RLOO is based on the Leave-One-Out policy gradient idea (inspired by a paper called LOOP). The approach here is to estimate advantage by removing each trajectory from a batch and seeing its effect. Concretely, a trajectory’s advantage might be (the leave-one-out baseline). This is similar to the batch-baseline but arguably with less bias. VERL’s RLOO uses a PPO-style clipped update (so it’s not pure REINFORCE). Essentially, it’s PPO but using the LOO baseline instead of a learned critic. This can stabilize training when reward distributions vary. The docs say it’s “closer to LOOP” (likely referencing the academic work that proposed leave-one-out RL). The benefit is reduced variance in advantage estimates without training a value network.
  • PF-PPO (Policy Filtration PPO): This is a method introduced by the VERL team (noted in May 2025 updates) to handle noisy reward signals. In human feedback data, some preference labels or reward model outputs can be noisy. PF-PPO addresses this by filtering out trajectories with unreliable rewards and preferentially reusing high-quality trajectories in training. For example, if the reward model is uncertain or the reward is near 0 (noise), those samples might be skipped or given lower weight; conversely, very clear high-reward samples might be replayed multiple times. This increases the efficiency of learning from limited high-quality feedback. In VERL, PF-PPO is likely implemented as an extension on top of PPO – perhaps an option to discard low confidence samples each iteration. The arXiv link in the README suggests a paper on PF-PPO exists.
  • Self-Play and Others: VERL also provides recipes like SPPO (Self-Play PPO). This is an alignment strategy where the model plays both roles (e.g., asks itself questions and answers, generating its own preference signal or using a heuristic). Self-play can generate additional training data without human labels. VERL’s SPPO likely uses the same PPO trainer but the data is generated by pairing two instances of the policy (one as user, one as assistant) and using a scoring mechanism to label the outcome. Another mention is PRIME (which might refer to an algorithm for training on comparisons or something like “Proximal Iterative Methods” – without more detail we just note it’s supported).
  • Dr. GRPO: This stands for D_ynamic _r_eward GRPO (also seen referenced as _Diverse GRPO in some contexts). It presumably applies the DAPO improvements to GRPO. Indeed, one source mentions “the Dr. GRPO paper proposed an alternative loss for GRPO to fix long-response penalties”. So DrGRPO likely integrates ideas like clip-higher or token-level updates into the GRPO algorithm to handle cases where longer responses get unfairly penalized under normal grouping. VERL lists it among supported algorithms.

Summary: VERL’s algorithm toolkit ranges from standard PPO (with critic) to critic-free approaches (REINFORCE++, GRPO) to hybrid approaches (RLOO, DAPO) that aim to make RLHF more stable and efficient. The choice of algorithm may depend on the task:

  • For tasks with dense, smooth rewards (or a well-shaped reward model), PPO with a critic can work well.
  • For tasks with very sparse rewards or difficult value function learning, one of the critic-free methods (GRPO, RLOO, etc.) might be preferred to avoid value model pitfalls.
  • DAPO’s enhancements are useful for large-scale runs to get the most out of the data (especially preventing policy collapse and encouraging exploration).
  • The good news is VERL’s design is flexible – many components (like rollout generation, model loading, multi-GPU distribution) are reused across these algorithms. Only the way advantages are computed and how the policy update is done changes. In fact, the code often reuses the same worker classes; to extend from PPO to a new algorithm, one can subclass the trainer or reuse the same dataflow with different math for advantage. The docs encourage this kind of extension.

Next, we will walk through how these components come together in an actual training run, using PPO as an example, and then discuss the VERL-Agent extension for multi-turn environments.

Implementation Walkthrough: How VERL Trains an LLM with PPO

To solidify understanding, let’s follow the flow of a PPO training job in VERL, step by step, tying together the components we described. We will use the GSM8K math dataset example (a single-turn QA task) as our running case, since VERL’s docs provide a clear example for it.

1. Launching Training: The user prepares a configuration (either by editing a YAML or via command-line overrides). For example, to run PPO on GSM8K, one might run:

python -m verl.trainer.main_ppo \
  data.train_files=~/data/gsm8k/train.parquet \
  data.val_files=~/data/gsm8k/test.parquet \
  actor_rollout_ref.model.path=Qwen/Qwen2.5-0.5B-Instruct \
  critic.model.path=Qwen/Qwen2.5-0.5B-Instruct \
  trainer.n_gpus_per_node=4 trainer.nnodes=1 \
  algorithm.kl_ctrl.kl_coef=0.001 \
  ...

This would use a 0.5B Qwen model as the policy (and reference and critic), running on 4 GPUs on one node, with an initial KL coefficient of 0.001, among other hyperparameters. In code, main_ppo.py loads the Hydra config (merging defaults and overrides), then proceeds to initialize the necessary objects.

2. Initializing Workers: Based on the config, VERL decides which worker classes to use. For example, if actor_rollout_ref.actor.strategy == 'fsdp', it will use the FSDP workers. It ensures actor and critic use the same strategy (asserting both are FSDP or both Megatron). Then it imports the appropriate classes, e.g.:

from verl.workers.fsdp_workers import ActorRolloutRefWorker, CriticWorker, RewardModelWorker
from verl.single_controller.ray import RayWorkerGroup

It sets up a mapping of Role → Worker class. In PPO with a reference model, the roles needed are: Actor+Rollout (combined), Critic, and RefPolicy. VERL maps these to the classes: Role.ActorRollout → ActorRolloutRefWorker, Role.Critic → CriticWorker, and Role.RefPolicy → ActorRolloutRefWorker (yes, the same class as actor, but configured to act as a static reference). If a reward model is enabled, it would also map Role.RewardModel → RewardModelWorker.

Next, VERL defines the resource pools. In our example, with 4 GPUs total, it might do:

resource_pool_spec = { "global_pool": [config.trainer.n_gpus_per_node] * config.trainer.nnodes }
mapping = {
    Role.ActorRollout: "global_pool",
    Role.Critic: "global_pool",
    Role.RefPolicy: "global_pool"
}

If n_gpus_per_node=4 and nnodes=1, this means "global_pool": [4]. So all three roles are assigned to the same pool of 4 GPUs. Internally, the ActorRolloutRefWorker and CriticWorker will each spawn processes on these GPUs such that the total processes = 4. For FSDP, typically one process per GPU, so we’ll have 4 actor processes (sharded actor model) and 4 critic processes (sharded critic). However, because actor and critic are in the same pool, an optimization is possible: they could share the same processes if using a combined worker. In this case, ActorRolloutRefWorker likely holds both the actor and reference model in one set of processes; the Critic is separate. They may or may not share processes depending on implementation (the mapping suggests all roles on one pool but does not necessarily merge them – likely they are separate Ray worker groups on the same set of nodes).

Now the trainer creates the Ray worker group with these specs. Ray is initialized (either explicitly or implicitly via Ray’s API). The RayWorkerGroup class in VERL handles launching the processes on each node for each role, setting appropriate CUDA device allocations. Once launched, each worker process will load the model weights:

  • The ActorRolloutRefWorker will load the policy model (from actor_rollout_ref.model.path) into memory. If it’s sharded, each process loads its shard. It will also load a copy for the reference (which might share underlying initial weights to save memory, since ref and actor start identical). VERL’s weight loading registry can download from HuggingFace or ModelScope automatically.
  • The CriticWorker loads the critic model (often same path as actor, but with a value head initialized). Sometimes the critic is just a clone of actor’s architecture but distinct weights.
  • If reward model is used, RewardModelWorker loads that model.

After initialization, the trainer prints that workers are ready. In code, this sequence is done by trainer.init_workers(), which handles all the above steps of spinning up processes and model initialization. VERL’s design decouples this from the actual training loop so that initialization can be done once at start (this helps with fault tolerance and resource allocation).

3. Rollout (Generation) Phase: Now the trainer enters the training loop (trainer.fit() call). In each iteration, the first step is to generate rollouts (samples of model output and compute their rewards):

  • The trainer instructs the ActorRollout workers to perform a forward pass to generate responses for a set of prompts. The prompts are taken from the dataset loaded in memory (the DataLoader likely pre-fetched a batch of prompt token IDs).
  • The ActorRolloutWorker uses either the model loaded in HF accelerate or vLLM to generate text. If using vLLM, the vllm_rollout.py will handle feeding the prompt to the vLLM engine and getting the output tokens. They might generate with a certain decoding strategy (could be greedy or sampling, depending on config).
  • Sequence Lengths: The config defines data.max_prompt_length and data.max_response_length to ensure prompts and responses fit model context. In our GSM8K example, they used 512 prompt and 256 response length. VERL may pad and efficiently batch these sequences (possibly using the seqlen_balancing.py utilities to group similar lengths and reduce padding overhead).
  • Once responses are generated, the ActorRollout worker also computes the log probabilities of the generated tokens under both the actor and the reference policy (since it has both loaded). This is efficient because the reference is just the frozen copy – it can be used to compute per-token likelihoods. These log-probs are needed for advantage calculation and KL penalty.
  • The outputs (prompts, responses, log-probs, etc.) are sent back to the controller. Ray handles the serialization (likely the data is not huge per batch, though with many samples it can be significant).
  • The trainer (controller) then hands off the responses to the Reward module. If a reward model is being used, it calls the RewardModel worker to get scores for each (prompt, response) pair. If a function is used, the RewardManager applies it locally. For GSM8K, the RewardManager calls gsm8k.compute_score() on each result to get 1 or 0.
  • The trainer now has for each sample: the prompt, the response, reward , log-prob of the response under current policy , and log-prob under reference . It can compute (averaged over tokens). It then forms the final reward . (In implementation, they might hand to the reward function or do it in trainer.)

At this point, we have all data needed for learning: each sample yields . If using a critic, we also query the critic to get for each (before update, using the old weights). That is used to compute the advantage . (Alternatively, some implementations might train the critic on-the-fly with Monte Carlo return if multiple steps; but for single step, this is straightforward.)

VERL’s logging output (as shown in the quickstart) prints some statistics after generation: e.g. response_length/mean, prompt_length/mean to monitor the lengths. This indicates the generation phase is happening and lengths are as expected (in GSM8K they got ~239 tokens mean response, near the 256 limit, meaning many solutions hit the max token limit).

  • Batching and Mini-batching: Note that VERL distinguishes between train batch size and PPO minibatch size. For example, they set data.train_batch_size=256 for GSM8K (meaning generate 256 responses per iteration) and then ppo_mini_batch_size=64. This means the 256 samples are split into 4 mini-batches of 64 for performing gradient updates (with perhaps 4 PPO epochs, each processing those mini-batches, totaling 16 update steps per iteration). This is standard PPO practice to reuse on-policy samples a few times. VERL also has ppo_micro_batch_size_per_gpu settings (e.g. 4). This is to handle large models that can’t consume the whole minibatch at once on one GPU. Micro-batching means each worker will accumulate gradients over smaller chunks (4 in this case) before finalizing an update step. This is especially useful if using gradient accumulation to fit larger batch through limited memory.

4. Policy and Critic Update Phase: Now the trainer broadcasts the gathered batch data to the training workers (actor and critic):

  • The CriticWorker receives the states (prompts) and the computed reward or returns, and performs a few epochs of training on its value head. It uses the standard supervised regression loss. VERL’s config might allow adjusting the weight of value loss, clip value changes, etc. After updates, the critic’s parameters are updated (note: if the critic shares the same backbone as the actor but just a different head, one might freeze some parts – but usually in RLHF, the critic is a separate copy of the network that does not directly affect the policy’s word generation).
  • The Actor (policy) worker receives the prompts, the generated actions, and the advantage for each. It also gets the old log-probabilities (to compute the ratio). It then runs the PPO loss computation. Under the hood, this means:
    • Feed the prompts (and maybe with the actions as well) into the policy network to get current log-probs. Since we have the output tokens, the policy can compute logits for those tokens given the prompt context. It compares with saved old log-probs to get .
    • Compute the PPO loss with clipping as per formula. Also compute an entropy bonus (VERL’s logs show actor/entropy_loss which is usually minus entropy times some coefficient, to encourage exploration).
    • Compute policy gradients and do backpropagation. Using FSDP, gradients are synchronized across shards automatically. If using 4 GPUs, each has a shard of the model – they exchange gradients and each update its shard of weights.
    • Apply optimizer step (likely Adam or AdamW) with the configured learning rate. In the config we saw they set actor.optim.lr=1e-6 for the small Qwen model.
    • This process is done for each minibatch. If 256 samples, 64 per minibatch, 4 minibatches * possibly multiple epochs (say 1 or 2 epochs by default). So total gradient updates might be a few per iteration.
  • The reference model is not updated (it remains a fixed baseline).
  • After actor updates, the KL between the new policy and reference will typically increase a bit (as policy diverges to get higher reward). If KL grows too much, in subsequent iterations an adaptive controller might increase to rein it in – VERL likely has an option for target KL (OpenAI’s implementation did this). Otherwise, one monitors actor/ppo_kl in logs and can manually adjust if needed.

VERL logs an extensive set of metrics each iteration, for example (from the snippet):

  • Timing for generation, ref evaluation, etc. (timing/gen, timing/ref).
  • actor/reward_kl_penalty and actor/reward_kl_penalty_coeff which indicate the KL penalty being applied (in step 0 it was 0, coeff 0.001 – meaning KL was minimal initially).
  • Value loss (critic/vf_loss) and clip fraction, value prediction stats.
  • Policy gradients stats: policy loss (actor/pg_loss), fraction of clips (actor/pg_clipfrac which shows how many updates hit the clipping bound), the measured KL (actor/ppo_kl which should be around the target, here 0.0 at step0 growing to some small number), gradient norms, learning rates, etc.
  • Reward stats: mean/max/min of critic/rewards which are the batch rewards, and critic/score (this might be after normalization or so).
  • Advantage stats: mean/max/min of advantages and returns.
  • Prompt/response length metrics as mentioned.

These help the practitioner see if learning is progressing (e.g., reward mean should ideally go up over time; value loss should go down; KL will gradually increase and should be controlled).

After each iteration, VERL may evaluate on the validation set (if configured trainer.test_freq). In the example, they compute a key metric val/test_score/openai/gsm8k every 10 steps. This likely means every 10 training iterations, they take the current policy, generate answers on the test set, and compute the average reward (or accuracy in GSM8K case). The user can watch this metric to see real improvement (for GSM8K, they reported going from ~0% to ~56% accuracy after PPO training from a pretrained model).

Finally, the training runs for a set number of epochs or iterations (in the example config, trainer.total_epochs=15 was set as number of iterations since each “epoch” here might correspond to one pass of PPO on the whole training set or a fraction of it, depending on how they define it).

Recap: This walkthrough illustrates how VERL automates the RLHF loop: prompt sampling, LLM generation, reward computation, advantage estimation, and policy/critic updates – all distributed across GPUs and coordinated by the Ray-based controller. The user can adjust parameters via config (batch sizes, learning rates, KL coeff, etc.) to tune performance. VERL’s abstraction (Roles, Workers, Controller) means that switching to another algorithm (say GRPO or DAPO) often only changes how is computed and how the loss is formulated, but the surrounding infrastructure (data loading, model parallelism, etc.) stays the same.

In fact, VERL’s documentation for extending to new algorithms suggests that one can reuse the ActorRolloutRefWorker and CriticWorker for most algorithms and just implement a new Trainer if needed. For example, a RayGRPOTrainer might skip the critic entirely and compute advantages by grouping returns. But it can still use the same actor worker for rollouts and policy updates (just with a different loss function). This reusability is a strength of the framework, enabling rapid experimentation with RLHF algorithm research.

Having covered single-turn tasks, we now shift focus to VERL-Agent, an extension of VERL for multi-turn, long-horizon environments. This will show how VERL can train an LLM to be an agent interacting with an environment (with possibly dozens of steps) rather than just producing a single response. We’ll see how the architecture adapts and how algorithms like GiGPO come into play.

VERL-Agent: Training LLMs as Multi-Turn Reasoning Agents

While VERL’s base library handles one-shot prompt→response fine-tuning, verl-agent (the extension library) enables training LLM-based agents that interact with environments over multiple steps. This is crucial for tasks like interactive reasoning, tool use, or games (e.g. ALFWorld, WebShop) where the model must make a sequence of decisions. We will explain the architecture of VERL-Agent, how it integrates with VERL’s core, and the specific techniques it uses (notably the GiGPO algorithm) to address the challenges of long-horizon credit assignment.

Long-Horizon Agent Training Challenges

In a multi-turn environment (for example, ALFWorld is a text-based simulation where the agent might navigate rooms and pick up objects over 50 steps), two main challenges arise:

  1. State Representation: If the LLM were to take in the entire history (all previous observations and actions) as context each time, the prompt would grow very long (up to thousands of tokens) and become inefficient. Prior approaches often concatenated the full interaction history for each action, which is not scalable.
  2. Credit Assignment: The agent might only get a reward at the end of the task (sparse reward). It’s hard to tell which action in the 50-step sequence was crucial for success or failure. Standard PPO with a learned value function can struggle here, and pure REINFORCE would have high variance. This motivates algorithms like GiGPO to assign credit at both trajectory level and step level.

VERL-Agent addresses these by:

  • Treating each step independently in terms of model input. Rather than feeding the full history, it uses a state-dependent prompt template that includes a summary of recent events and the current observation. This keeps the prompt length bounded. The agent still has memory in the sense of the environment state, but the LLM is prompted only with what it needs at the current step (possibly a window of the last observations or a truncated “belief state”).
  • Using special prompt formatting to guide the LLM’s output for actions. For example, in WebShop (an e-commerce game), the prompt might be:
    You are an expert autonomous agent in the WebShop environment.
    Your task: {task_description}. You have taken {step_count} steps so far. Recent observations and actions: {action_history}.
    Now at step {current_step}, current observation: {current_observation}.
    Available actions: [{available_actions}].
    
    The agent is instructed: first think step-by-step (in a <think> reasoning tag), then output an action in an <action> tag. This prompt structure is provided by verl-agent for each environment (they have templates in agent_system/environments/prompts/). It effectively tells the LLM how to format its multi-turn reasoning and action choice.
  • Step-wise processing: The environment interaction loop is managed such that at each step: the LLM receives a prompt (as above) and produces an action, the environment simulator executes the action and returns a new observation and possibly reward or done signal. This repeats until episode ends. VERL-Agent ensures that this loop is integrated into the rollout phase of training. Instead of a single forward pass generating one answer, now a forward pass generates one action, and it might loop internally for multiple actions per episode.

Architecture of VERL-Agent

VERL-Agent builds on VERL’s modular design, adding components for environments and custom trainers for multi-step algorithms:

  • Environment Interfaces: Under verl_agent/agent_system/environments/, the code defines classes for each supported environment (ALFWorld, WebShop, Sokoban, etc.). These are often wrappers around existing simulators or Gym environments. They handle resetting the env, stepping with an action, and returning observations. VERL-Agent likely runs multiple env instances in parallel (to collect batches of episodes). They mention multi-process execution of envs, meaning each environment instance could run in its own process for efficiency, managed by an Environment Manager.
  • Environment Manager: There is an EnvironmentManagerBase and specific implementations (e.g. WebshopEnvManager). This manager coordinates the parallel simulation and interacts with the LLM policy. For example, it might spawn N environments, feed each the agent’s action, and gather the results, similar to how Gym vector environments work.
  • Prompt Template and History: The prompt for each step is dynamically generated using the template and the current history of observations/actions (limited to some history_length). The code for prompts is in environments/prompts/ as mentioned. By editing these templates, users can customize what context the agent sees (e.g., you could include a summarized memory or the last few actions).
  • Agent Policy Model: This is still an LLM like Qwen or Gemma, possibly the same as in single-turn. But now it’s used iteratively. The model might have a special output format (the <think> ... </think><action> ... </action> tags) which the environment parser will interpret – e.g., it will extract the text inside <action> to determine which action to execute. The reasoning inside <think> is not sent to the environment; it’s just the model’s chain-of-thought (which can improve the quality of the chosen action, as per the prompt design).
  • Reward Scheme: Typically, these environments provide a sparse reward at the end (e.g., +1 for success, 0 for failure), or some intermediate rewards. Verl-agent can treat the final return as the reward for the whole trajectory. For learning efficiency, sometimes shaped rewards are added (like a small negative reward for each step to encourage faster completion, etc., depending on the environment).

From an algorithmic perspective, standard PPO could be applied to these multi-step episodes, using the sum of discounted rewards as the return for each state, and using a recurrent or sequential value function. However, training a value network on 50-step partially observed trajectories of text is very challenging. This is where group-based algorithms come in:

GiGPO: Group-in-Group PPO for Fine-Grained Credit Assignment

GiGPO is a novel algorithm introduced with verl-agent to handle very long horizon tasks without a critic. It extends GRPO (the group-based, critic-free approach) by adding a second level of grouping:

  • Episode-level grouping (macro-level): Like GRPO, at the end of each episode, GiGPO looks at the total return of that episode. It then compares and groups multiple episodes to compute relative advantages. For example, if you have a batch of episodes, you can rank them by return; episodes in the top tier get positive advantage, bottom tier negative. This gives a coarse credit: “trajectory A was better than B, so actions in A should be more encouraged.” This is macro advantage estimation across full trajectories.
  • Step-level grouping (micro-level): GiGPO’s key innovation is to address which action in the trajectory deserves credit. It does this by an anchor state grouping mechanism. Essentially, it finds identical (or similar) states that occurred in different trajectories, and groups all those decision points together. For instance, consider a specific state (an observation situation). In some trajectories where occurred, the agent’s next action led to eventual success, in others it led to failure. GiGPO groups those occurrences of state and compares outcomes. If in trajectories where action was taken from the returns were higher than when action was taken from the same , then gets a higher relative advantage for that state. This yields a per-step relative advantage without a value function, by holding the state constant and varying the action outcome across trajectories. It’s like doing an ablation analysis per state: “when we were in state X, the group of trajectories where we did action Y turned out better than the group where we did action Z”.
  • By combining these: each action gets two signals – a macro advantage (how good was the whole trajectory relative to others) and a micro advantage (how good was that action choice given the state, relative to other choices for the same state across runs). GiGPO can use these to weight policy gradients.
  • Critic-free: GiGPO does not need a learned value network; it uses trajectory returns for macro advantage and peer comparisons for micro advantage. This keeps memory usage low (important when running very long sequences on GPUs) and also avoids destabilizing value learning in sparse-reward settings. The authors note it maintains the same memory footprint and rollout cost as GRPO (which was already lighter than PPO), yet significantly improves training efficiency and performance (they reported >12% gains on benchmarks like ALFWorld/WebShop vs. prior methods).

In VERL-Agent, to run GiGPO, one would use the provided script:

bash examples/gigpo_trainer/run_alfworld.sh

This script likely sets the config to use GiGPO (maybe calling a main_gigpo.py or main_ppo.py with algorithm=GiGPO). Under the hood, it will:

  • Collect a batch of trajectories (episodes) from the environment with the current policy (just like PPO rollout but multi-step).
  • Compute total return for each trajectory.
  • Perform the grouping: perhaps sort trajectories by return, compute macro advantages (maybe advantage = return - mean(return) for simplicity, or a rank-based value).
  • For micro advantage: for each unique state encountered (an “anchor state”), compare the returns of trajectories passing through that state with different actions. Compute an advantage for each action at that state (this likely requires storing the trajectory data in a structure that groups by state; since states are complex (e.g. text observations), “repeated state” might mean identical observation text or some abstraction of it).
  • Update policy: similar to PPO but using these advantages instead of a critic’s estimate. Likely still uses a clipped objective but now the advantage is this relative advantage. Since there’s no value baseline, they might normalize these advantages to zero-mean for stability.
  • GiGPO is said to be stable and converge well without a critic. It basically leverages more information from a batch of data (the cross-trajectory comparisons) to guide updates.

VERL-Agent also supports:

  • GRPO in multi-turn (treating each full trajectory’s return in a group).
  • PPO with a critic (one could attempt it, but again, training the value function might be challenging; still, it’s provided as an option for comparison).
  • RLOO and DAPO are also extended to the multi-turn setting, as listed in the README. DAPO’s dynamic sampling could be used here too (perhaps focusing on successful episodes).
  • A “dynamic” version of GiGPO combines DAPO techniques (clip-higher, dynamic sampling) with GiGPO for further performance.

Using VERL-Agent – Integration Steps

If an expert user wants to train a reasoning agent with VERL-Agent, the steps would be:

  1. Install VERL and VERL-Agent: The README provides conda environment instructions. You install verl (the base library) and then verl-agent. Ensure you have Python 3.12 (as recommended) and PyTorch setup with GPU support. Then, install any environment-specific dependencies.

  2. Install/Configure the Environment: For each target environment, you need to install its package:

    • ALFWorld: a text-based ALFRED environment – likely install via pip install alfworld or given instructions.
    • WebShop: requires Python 3.9 environment due to some older dependency (so one might create a separate env for that).
    • Sokoban: install gym and other packages as noted.
    • Gym Cards, AppWorld: similarly follow instructions.
      Each environment may also require resources (e.g., ALFWorld might need some data files, WebShop an e-commerce simulator setup, etc. – the README warns to follow their setup documentation).
  3. Set Up the Model: Choose an LLM to be the agent’s policy. The examples used Qwen2.5-1.5B or Qwen2.5-7B for experiments, which suggests those are good sizes. You might use any HuggingFace model that fits in memory (with FSDP, even larger ones can be used). Ensure the model is an instruct or chat-tuned model (since it needs to follow the prompt format and output actions properly).

  4. Run the Training Script: Use the provided scripts to launch training. For instance, run_alfworld.sh will contain the command to start a trainer configured for ALFWorld (likely specifying environment name, model path, algorithm=GiGPO, etc.). For example, it might call:

    python -m verl.trainer.main_ppo \
      algorithm.name=gigpo \
      env.name=alfworld \
      data.train_steps=100000 ...

    (The actual command can be seen in the examples/gigpo_trainer/ directory of verl-agent). This will kick off the Ray trainer similarly to before, but now integrated with the environment loop.

  5. Monitoring Training: As training progresses, you’ll see logs similar to PPO but with additional info:

    • Step-wise rewards or returns per episode (e.g., success rate).
    • Possibly intermediate metrics like average episode length, etc.
    • GiGPO might log how many state groupings it formed, etc.
      Typically, one will monitor the evaluation success rate. In ALFWorld, for example, you’d measure what percentage of tasks are completed successfully by the agent. The training should gradually improve this.
  6. Inference with the Trained Agent: After training, you can use the agent (the fine-tuned model) to act in the environment. Verl-agent might provide a way to run a trained policy in an environment loop for demonstration. Alternatively, one can manually prompt the model with the format and let it respond.

If customizing a new environment or task:

  • You’d implement a Gym-style environment class and a prompt template as per verl-agent’s guidelines. Then register it in env_manager.py so that the trainer knows how to instantiate it. This extensibility allows using VERL-Agent for custom interactive tasks (for instance, integrating a code execution environment or a dialogue simulator).

Example: Suppose we want to train an agent to solve a puzzle game via text. We create PuzzleEnv with reset() and step(action) methods. We write a prompt template guiding the model to output puzzle moves. We add PuzzleEnv to the EnvironmentManager. Then we can reuse GiGPO to train our agent by comparing trajectories (likely many will fail, a few succeed, and GiGPO will figure out which actions in the successful ones were critical).

VERL-Agent’s approach was inspired by prior projects (they acknowledge RAGEN and others), but it stands out in its ability to scale to very long sequences by not blowing up context length (processing stepwise) and leveraging a clever learning algorithm (GiGPO) to avoid credit assignment issues.

In summary, VERL-Agent extends VERL to a full Agent Training framework where the “environment step” is analogous to the “data sample” in RLHF. The same modular RL backend (workers, trainers) are used, but plugged into an environment loop. The result is a system that can train LLMs not just to give good static answers, but to strategize over multiple interactions to achieve goals in a simulated world.

Scaling Up: Multi-GPU and Multi-Node Training Tips

One of VERL’s core strengths is its ability to scale RL fine-tuning to large models and many GPUs. Let’s discuss how to set up a training run on, say, 4× H100 GPUs, and what configurations or techniques to use for efficiency.

1. Selecting a Parallelism Strategy: With 4 high-memory GPUs on one node, you have a few options:

  • Data Parallel (FSDP): If the model is moderately sized (<= 13B), you might even fit it on one GPU, but using all 4 for data parallel (each GPU gets a different batch) can increase throughput. VERL can do data-parallel updates by simply setting n_gpus_per_node=4 and using strategy=fsdp (which in the case of a model that fits on one GPU, FSDP will act like DP). This way, each GPU generates rollouts and computes gradients on its shard of data, and gradients are averaged. FSDP will still shard the model by default, but you could also use PyTorch DDP if you really wanted (VERL primarily focuses on FSDP though).
  • Fully Sharded (FSDP) for memory: If the model is larger (e.g., 30B or 70B), you must shard it. FSDP will partition the model across the 4 GPUs (each holds ~1/4 of the parameters). This allows training a model that wouldn’t fit in a single H100’s memory. Set strategy=fsdp and ensure tensor_model_parallel_size=1 (that parameter is for Megatron, not needed for pure FSDP).
  • Megatron Tensor Parallel: Alternatively, for extremely large models (like 70B with 4 GPUs might be tight, but possible if each GPU holds ~17.5B parameters in half precision), you could use Megatron’s model parallel by setting actor_rollout_ref.rollout.tensor_model_parallel_size=4 (all 4 GPUs share each layer). VERL supports this with strategy=megatron and proper config. Megatron can be combined with data parallel too (though with 4 GPUs total, you’d likely do pure tensor parallel).
  • FSDP2: PyTorch’s FSDP2 (Next-generation FSDP) is recommended in VERL for better performance. Enabling it is as simple as using 'fsdp2' in the strategy fields (as shown in [44]). FSDP2 has optimizations that improve throughput and memory, and supports features like torch.compile. It’s a good choice for multi-GPU training.
  • In config, you might specify:
    actor_rollout_ref:
      actor:
        strategy: fsdp2
        offload_policy: False   # example: can offload to CPU between microbatches if needed
      ref:
        strategy: fsdp2
    critic:
      strategy: fsdp2
    This ensures all models use FSDP2. If memory is a concern, setting offload_policy=True would offload shards to CPU during some computations (supported with FSDP2), though with H100s it might be better to keep everything on GPU if possible.

2. Distributed Launch: VERL uses Ray to manage processes, so you do not typically launch with torchrun manually. Just run python -m verl.trainer.main_ppo ... trainer.n_gpus_per_node=4 trainer.nnodes=1 and Ray will spawn 4 actors for you on that node (provided Ray is installed and can start a local instance). Ensure you have ray[default] or similar installed. If you run on a Slurm or multi-node cluster, you might need to start a Ray cluster or use Ray’s multi-node job submission. The details can be complex, but essentially:

  • For single-node 4 GPU, it should work out-of-the-box. The trainer will detect 4 GPUs and assign roles to them as per the resource mapping. You will see processes like worker_0, worker_1, worker_2, worker_3 start (for FSDP each managing a shard).
  • For multi-node (say 2 nodes, 4 GPUs each): you’d set nnodes=2, n_gpus_per_node=4. Ray needs to be configured to know about both nodes (either by running a head node and having the other join, or using Ray’s CLI to start a multi-node cluster). Once Ray spans both nodes, VERL’s trainer will allocate 8 GPUs total as specified. It will distribute the workers across nodes automatically. The communication backend for FSDP or Megatron will likely be NCCL under the hood, coordinated by Ray. This allows scaling to e.g. 8 or 16 GPUs effectively. The authors have demonstrated scaling to hundreds of GPUs and 70B models, so multi-node is definitely supported.

3. Memory and Batch Size: With 4×H100 (each 80GB if H100 SXM), you have 320GB GPU memory total. This is plenty for moderate model sizes. You can increase train_batch_size to utilize the capacity – e.g., if on 1 GPU we did batch 256, on 4 GPUs perhaps batch 1024 (as in some config), so each GPU handles 256 samples (though due to FSDP, the batch is typically split across GPUs automatically).

  • Watch out for the sequence length: long prompts or responses can inflate memory usage (self-attention memory grows with sequence length). If training on long dialogues, you might need to reduce batch size or use sequence packing. VERL supports FlashAttention 2 and sequence packing (combining multiple short sequences in one long sequence to better fill context) via DeepSpeed Ulysses integration. Enabling those can improve throughput on H100s dramatically. FlashAttention 2 requires specific PyTorch or custom kernels (VERL mentions using “Liger-kernel” for efficiency).
  • LoRA for RL: If you want to fine-tune a very large model (e.g. 70B) on limited hardware, VERL allows applying LoRA (Low-Rank Adaptation) to the model and only training the LoRA parameters during RL. This saves a ton of memory (the model weights remain frozen except small LoRA matrices). VERL’s README notes “Lora RL support to save memory”. In config, you would specify a LoRA adaptation (likely in the model instantiation). This way, even if the model is sharded, only LoRA layers get gradients – reducing communication and memory.
  • Gradient Accumulation: If you want to use a very large batch but can’t fit it in GPU memory at once, you can increase actor_rollout_ref.actor.ppo_micro_batch_size_per_gpu. For example, if batch is 1024 and you have 4 GPUs, that’s 256 per GPU. If 256 is too high to process at once, you could set micro_batch_per_gpu=64, so it does 4 forward/backward passes of 64 each to accumulate gradients to effectively have 256. This was done in the example (they used micro_batch 4 for actor when batch was 256).

4. Throughput and Tuning: The Performance Tuning Guide on VERL’s docs provides many tips. Key things to utilize for speed on H100:

  • Enable BF16 or FP16 mixed precision (FSDP will do this by default likely). H100 has great BF16 support.
  • Use FlashAttention (should be enabled if using appropriate model or DeepSpeed). If using HuggingFace models with HF’s transformer backend, ensure the model supports flash attn (many do).
  • Increase rollout.gpu_memory_utilization parameter (the example used 0.4 = 40%). This setting is specific to how vLLM offloads or allocates memory for generation. If you have more memory free, you can bump this so that the generation engine uses more of the GPU memory for caching, etc. Conversely, if you find out-of-memory during generation, you can lower it. In multi-GPU, since training already consumes a lot, one might keep it moderate.
  • Use multiple rollout workers if generation becomes a bottleneck. For instance, if policy update is fast but text generation is slow, you could allocate some GPUs primarily for generation. VERL’s flexible mapping would allow dedicating, say, 2 GPUs for Rollout role and 2 for Actor training role (this is an advanced setup). Right now, the example co-located them, but for very large scale, sometimes decoupling can help.
  • Monitor network overhead: if on multi-node, ensure high-bandwidth interconnect (InfiniBand or NCCL over RoCE) for gradient syncing and model sharding. Ray will use the network for communication and launching tasks, so network config (like setting RDMA if available) could matter.

5. Fault Tolerance: With long runs on multi-GPU, failures can happen. VERL supports checkpointing and fault tolerance. You can configure it to save model checkpoints periodically (trainer.save_freq) and resume if needed. The docs mention a checkpoint mechanism for fault-tolerant training (likely saving optimizer and model states).

In short, to use 4×H100 effectively:

  • Use FSDP to shard a big model or data parallel for smaller.
  • Set the config for 4 GPUs, and adjust batch sizes accordingly.
  • Turn on any memory optimization needed (offloading, LoRA, etc., if hitting limits).
  • Take advantage of the powerful tensor cores on H100 with BF16 and flash attention to speed up both training and generation.
  • Optionally, use FSDP2 which even allows torch.compile to optimize the model graph – this could yield additional speedups on newer PyTorch.

Finally, always validate that the scaling is working (the rewards on single GPU vs 4 GPU runs are comparable for a given number of training samples). In theory, 4 GPUs should simply give either 4× the batch size (for same walltime) or 4× faster training (for same batch per update). Due to communication and other overhead, you might not get perfect linear speedup, but VERL’s design has shown strong scaling efficiency thanks to careful engine optimization.

Conclusion

In this tutorial, we explored VERL and VERL-Agent in depth. We saw that VERL’s architecture cleanly separates concerns: a Ray-based controller coordinates trainer logic, while specialized worker modules handle heavy lifting for policy generation, model updating, and reward computation across GPUs. This enables fine-tuning large models (like Qwen, LLaMA, Gemma etc.) with state-of-the-art RL algorithms such as PPO and its many variants (e.g. GRPO, DAPO, RLOO, PF-PPO), each designed to tackle specific challenges in RLHF training. We provided mathematical context for PPO and explained how VERL implements the KL-regularized objective common in RLHF. We also discussed how reward modeling is integrated, either via learned reward models or custom functions for verifiable tasks.

Through an implementation walkthrough, we illustrated how VERL orchestrates data collection (rollouts) and learning updates in a distributed setting – from sampling prompts to updating the policy with clipped advantages. We then looked at VERL-Agent, which extends these capabilities to interactive environments, handling multi-step episodes with possibly sparse rewards. VERL-Agent’s use of GiGPO is a highlight, demonstrating cutting-edge research that allows credit assignment across long sequences without a value function. By grouping trajectories and states, GiGPO gives VERL-Agent the ability to train agents to solve complex tasks like ALFWorld and WebShop, achieving substantial performance gains.

Finally, we covered how to scale up training on multiple GPUs (like 4×H100), including using FSDP for memory-efficient training, leveraging H100 features (BF16, FlashAttention), and tuning batch sizes and parallelism for optimal throughput. VERL’s design has been proven to scale to dozens or hundreds of GPUs for training models up to 70B parameters, so the tools and tips we discussed will empower an expert user to push to that scale if needed.

With VERL, researchers and engineers have a powerful, flexible framework to perform RL fine-tuning (RLHF and beyond) on large language and multimodal models. Its modularity means you can mix-and-match components (e.g., plug in a new reward model or try a new RL algorithm) without reinventing the wheel for distributed training. We encourage users to explore the VERL documentation and source code – for example, the HybridFlow paper for system design insights, or VERL’s programming guide – and to experiment with the provided examples as a starting point. Happy fine-tuning!

Sources: The information and examples above were drawn from the VERL codebase, documentation, and associated research papers for HybridFlow and GiGPO, as well as the VERL-Agent README and config references, to ensure accuracy and rigor in describing the system.