VERL and VERL-Agent: A Deep Dive into Reinforcement Learning for Fine-Tuning Reasoning in Large Language Models

1. Introduction

The advent of Large Language Models (LLMs) has revolutionized numerous fields, yet enhancing their reasoning capabilities remains a significant research frontier. Reinforcement Learning (RL), particularly Reinforcement Learning from Human Feedback (RLHF), has emerged as a potent technique for aligning LLMs with desired behaviors, including complex reasoning and decision-making. This report provides an in-depth analysis of VERL (Volcano Engine Reinforcement Learning) 1 and its extension, VERL-Agent 2, two open-source libraries designed to facilitate the fine-tuning of LLMs using RL.

VERL, originating from ByteDance and open-sourcing the principles of the HybridFlow framework 3, offers a flexible, efficient, and production-ready platform for RL-based post-training of LLMs. It addresses critical challenges in scaling RLHF, such as computational efficiency and framework extensibility. VERL-Agent builds upon this foundation, specifically targeting the training of LLM and Vision-Language Model (VLM) agents that operate in interactive environments requiring multi-turn reasoning and long-horizon planning.2 A key contribution within VERL-Agent is the Group-in-Group Policy Optimization (GiGPO) algorithm, a novel RL method tailored for the nuanced credit assignment challenges in agent training.5

This report will dissect the implementations of VERL and VERL-Agent, exploring their core architectures, key features, and supported algorithms. It will delve into their respective codebases, elucidating how LLMs are integrated and how RL algorithms like Proximal Policy Optimization (PPO) and GiGPO are realized. Furthermore, a comprehensive tutorial section will guide users on leveraging these frameworks to fine-tune reasoning models, complete with conceptual examples and customization advice. Advanced topics, community aspects, and future directions will also be discussed, providing a holistic understanding of these powerful tools.

2. Understanding VERL (Volcano Engine Reinforcement Learning)

2.1. Overview and Purpose

VERL (Volcano Engine Reinforcement Learning) is an open-source reinforcement learning training library initiated by the ByteDance Seed team and maintained by the VERL community.1 It is specifically engineered for the post-training of large language models, aiming to provide a framework that is flexible, efficient, and robust enough for production environments. The core philosophy of VERL is to simplify and accelerate the application of RL techniques to enhance LLM capabilities. VERL is the open-source implementation of the research paper “HybridFlow: A Flexible and Efficient RLHF Framework” 1, which details its underlying architectural innovations. The primary goal of VERL is to enable researchers and practitioners to easily implement and scale various RL algorithms for LLM alignment and improvement, supporting tasks ranging from mathematical reasoning to code generation and multi-modal applications.1

2.2. Core Architecture: The HybridFlow Framework

The foundation of VERL’s efficiency and flexibility lies in the HybridFlow framework.3 Traditional RL frameworks often struggle with the demands of RLHF for LLMs. Single-controller systems can become bottlenecks due to the overhead of dispatching control for distributed intra-node computations. Conversely, existing multi-controller RLHF systems can be inflexible due to the tight coupling of distributed computation and data communication.3

HybridFlow addresses these limitations by ingeniously combining the single-controller and multi-controller paradigms. It employs a single-controller approach at the inter-node level, which allows for flexible expression of data dependencies and streamlined coordination of inter-node data resharding with minimal overhead. Simultaneously, it integrates the multi-controller paradigm for intra-node computations, enhancing the efficiency of distributed execution within a node.3 This hybrid approach allows VERL to represent and execute diverse and complex RLHF dataflows with high throughput.

A key aspect of HybridFlow is its set of hierarchical APIs. These APIs are meticulously designed to decouple and encapsulate computation and data dependencies inherent in complex RLHF dataflows. This decoupling facilitates efficient orchestration of operations needed to implement various RLHF algorithms and allows for flexible mapping of these computations onto different GPU resources.3 For intra-node distributed computation, HybridFlow provides a base class, 3DParallelWorker. This class, given allocated devices, manages distributed model weight initialization and establishes 3D parallel groups (encompassing data parallelism, tensor parallelism, and pipeline parallelism) for each model involved in the RLHF process (e.g., actor, critic, reference, reward models).3

Further enhancing its performance, HybridFlow introduces the 3D-HybridEngine. This engine is specifically designed for the efficient execution of the actor model’s training and generation phases, which are major computational components in RLHF. The 3D-HybridEngine enables efficient model parameter resharding between these two phases, achieving this with zero memory redundancy and significantly reduced communication overhead.3 This is crucial for on-policy algorithms where frequent switching between generation and training is common.

The benefits of the HybridFlow architecture are manifold:

  • Flexible Dataflow Representation: Users can define complex RLHF dataflows, such as those for PPO or GRPO, with relatively few lines of code.1
  • Efficient Execution: The hybrid controller model and optimized engines ensure high throughput for both training and inference.7
  • Decoupling of Dependencies: Intra-node computation and inter-node data transfer are decoupled, allowing independent optimization of different model components without affecting others.3 This modularity is a cornerstone of VERL’s adaptability.
  • Flexible Device Mapping: Models can be placed on the same or different sets of GPUs, optimizing resource utilization across various cluster sizes.7

This architectural design, emphasizing modularity and a clear separation of concerns (control flow vs. computation flow), is pivotal for VERL’s extensibility. It allows new algorithms or distributed training backends to be integrated more seamlessly, as the core orchestration logic can remain stable while specific computational components are swapped or updated. This foresight in design positions VERL to adapt to the rapidly evolving landscape of LLM training and RL research.

2.3. Key Features of VERL

VERL distinguishes itself through a comprehensive suite of features designed for modern RLHF workflows 1:

  • Extensibility of Diverse RL Algorithms: Leveraging the HybridFlow programming model, VERL allows for the straightforward implementation and extension of various RL algorithms. Complex post-training dataflows for algorithms like GRPO, PPO, DAPO, ReMax, and RLOO can be constructed with minimal code.1
  • Seamless Integration with Existing LLM Infrastructure: VERL’s modular APIs decouple computation and data dependencies, enabling smooth integration with established LLM training and inference frameworks. This includes support for PyTorch Fully Sharded Data Parallel (FSDP), Megatron-LM, vLLM, and SGLang.1 This ensures that users can leverage state-of-the-art distributed training and inference optimizations.
  • Flexible Device Mapping: The framework supports sophisticated placement of different models (actor, critic, reward model, reference model) onto various sets of GPUs. This optimizes resource utilization and enhances scalability across diverse hardware configurations and cluster sizes.7
  • State-of-the-Art Throughput and Efficient Resharding: VERL integrates SOTA LLM training and inference engines, coupled with its 3D-HybridEngine for actor model resharding. This combination results in high RL throughput by minimizing memory redundancy and communication overhead during transitions between training and generation phases.1
  • Support for Diverse Tasks and Modalities:
    • Reward Modeling: Accommodates both model-based reward functions and function-based (verifiable) rewards, crucial for tasks like mathematics and coding where correctness can be programmatically assessed.1
    • Vision-Language Models (VLMs): Extends its capabilities to multi-modal RL, allowing for the training of VLMs.1
    • Multi-Turn Interaction with Tool Calling: Supports scenarios where LLMs engage in multiple rounds of interaction and can utilize external tools, a key feature for developing sophisticated agents.1
  • Advanced Optimizations: Incorporates techniques like Flash Attention 2, sequence packing, sequence parallelism (via DeepSpeed Ulysses), and LoRA (Low-Rank Adaptation) to enhance training speed and memory efficiency.1 Liger-kernel support is also mentioned.7
  • Scalability: Proven to scale up to 70B parameter models and hundreds of GPUs.1
  • Experiment Tracking: Integrates with popular experiment tracking tools such as Weights & Biases (wandb), SwanLab, MLflow, and TensorBoard.1
  • HuggingFace Model Integration: Offers ready integration with popular models from HuggingFace Transformers and ModelScope Hub, including Qwen, Llama, and Gemma series models.1

These features collectively make VERL a powerful and adaptable framework for pushing the boundaries of LLM alignment and capability enhancement through reinforcement learning.

2.4. Supported RL Algorithms in VERL

VERL provides implementations for a wide array of reinforcement learning algorithms, catering to different needs and research directions in LLM post-training. The supported algorithms include 1:

  • Proximal Policy Optimization (PPO): A widely used on-policy algorithm known for its stability and performance in LLM fine-tuning.
  • Group-based Reward Policy Optimization (GRPO): An algorithm that often performs well in RLHF, particularly for tasks requiring robust preference learning.
  • ReMax: Another algorithm relevant to preference learning and LLM alignment.
  • REINFORCE++: An advanced variant of the classic REINFORCE algorithm.
  • RLOO (Reinforcement Learning with Optimal Orthogonalization): An algorithm that can be effective in large-scale training.
  • PRIME (Process Reinforcement through Implicit Rewards): Likely focuses on learning from process-based feedback.
  • DAPO (Dynamic Advantage Policy Optimization): A state-of-the-art RL algorithm that has shown strong performance on math reasoning benchmarks, built upon VERL.7
  • DrGRPO (Distribution Ratio GRPO): An extension or variant of GRPO.

The availability of such a diverse set of algorithms underscores VERL’s commitment to flexibility, allowing users to choose the most appropriate method for their specific task and data. The framework’s design facilitates the addition of new algorithms, ensuring it can keep pace with ongoing research in RL for LLMs.

3. VERL Codebase Implementation

Understanding the structure and core components of the VERL codebase is essential for effective utilization and extension.

3.1. Repository Structure

The VERL GitHub repository (volcengine/verl) is organized to separate core library code, examples, documentation, and utility scripts.1 Key top-level directories include:

  • verl/: This is the heart of the library, containing the source code for the core VERL framework, including implementations of RL algorithms, the HybridFlow components, worker definitions, utility functions, and model integration logic.1
  • examples/: Contains runnable scripts and configurations demonstrating how to use VERL for various tasks and algorithms, such as PPO training on datasets like GSM8K.1 These examples serve as practical starting points for users.
  • recipe/: This directory likely houses configurations and scripts for reproducing results with specific RL algorithms and benchmarks, including DAPO.1 It may contain more standardized or optimized setups compared to general examples.
  • docs/: Contains the source files for generating VERL’s official documentation, hosted on Read the Docs.1
  • docker/: Provides Dockerfiles for creating containerized environments, simplifying setup and ensuring reproducibility, including support for AMD ROCm.8
  • scripts/: Utility scripts for development, testing, or deployment.
  • tests/: Contains unit tests and integration tests to ensure code quality and correctness.

This structure promotes modularity and ease of navigation for both users and developers contributing to the framework.

3.2. Core Components

Within the verl/ directory, several key components implement the HybridFlow architecture and provide the building blocks for RLHF pipelines.

  • verl.single_controller: This module is central to VERL’s HybridFlow programming model.8 It embodies the single-controller aspect for inter-node/inter-process communication and orchestration. The design aims to bridge the gap between single-process scripts and complex multi-process distributed applications.11
    • Decorator-based Registration: Methods within worker classes that are intended to be called remotely by the controller are registered using a decorator (e.g., @register). This decorator attaches metadata, such as dispatch_mode and execute_mode, to the method.11
    • Dispatch Modes: The dispatch_mode (e.g., Dispatch.DP_COMPUTE_PROTO) specifies how input data should be split and dispatched to distributed workers and how output data should be collected and aggregated by the controller.10 For instance, DP_COMPUTE_PROTO implies splitting data for data-parallel computation. ONE_TO_ALL might broadcast the same data to all workers. The verl.single_controller abstracts the complexities of distributed execution, allowing users to define RL algorithms (control flow) in a single-process manner while the underlying computations (computation flow) are executed in a distributed fashion across multiple worker processes.10
  • Worker and WorkerGroup: These abstractions encapsulate the actual model computations (e.g., forward pass, backward pass, generation).
    • Worker: A class (e.g., ActorRolloutRefWorker in fsdp_workers.py) that defines the computational tasks for a specific role, such as actor inference, rollout generation, or critic model evaluation.10 A single Worker class can be designed to handle multiple roles (e.g., actor and rollout) to optimize data transfer (like weight sharing via NCCL) or implement specific algorithm variants (like LoRA PPO where the reference policy is the base model).10
    • WorkerGroup: Manages a collection of Worker instances, potentially distributed across multiple GPUs or nodes. The controller interacts with a WorkerGroup to dispatch tasks and retrieve results. The WorkerGroup abstraction, combined with ResourcePool (which virtualizes GPU devices), allows for flexible placement of different model components onto different hardware resources.10

This design effectively separates the RL algorithm’s logic (control flow, managed by the single controller) from the distributed execution of LLM computations (computation flow, managed by Workers and WorkerGroups). This separation allows system researchers to optimize distributed computation backends independently of algorithm researchers developing new RL methods.10

3.3. PPO Implementation in VERL

Proximal Policy Optimization (PPO) is a cornerstone algorithm for RLHF and is well-supported in VERL.

  • General PPO Process: The PPO algorithm in the context of RLHF or code generation typically follows an iterative three-stage process 3:
    1. Response Generation (Rollout): The current actor model (policy πθk​​) generates responses (e.g., text, code) based on a batch of prompts.
    2. Data Preparation and Scoring:
      • The generated responses are evaluated. This involves obtaining rewards, often from a reward model or a human feedback mechanism. For code generation, this might involve executing the code in a sandbox and checking correctness.12
      • Values are computed using the critic model Vϕk​​.
      • Advantages A^k​ are estimated, commonly using Generalized Advantage Estimation (GAE).
      • Log probabilities of the generated actions under the reference policy πref​ (often a frozen version of the initial supervised fine-tuned model or an earlier iteration of the actor) are computed for KL divergence penalty calculation.
    3. Learning (Policy and Value Update): The actor (policy) and critic (value function) models are updated by optimizing their respective loss functions.
  • Key Files/Classes: While direct file paths are not exhaustively listed in the provided materials, the implementation would logically reside in verl/trainer/ppo/ (e.g., ray_trainer.py for the Ray-based PPO trainer 1), verl/algorithms/ or similar for the core PPO logic, and potentially verl/loss/ for loss function definitions. Configuration files for PPO examples (e.g., ppo_trainer.yaml) are found in the examples/ directory.1
  • PPO Loss Function: The PPO algorithm aims to maximize a clipped surrogate objective function for the policy (actor) update: LCLIP(θ)=E^t​[min(rt​(θ)A^t​,clip(rt​(θ),1−ϵ,1+ϵ)A^t​)] where rt​(θ)=πθk​​(at​∣st​)πθ​(at​∣st​)​ is the probability ratio, A^t​ is the estimated advantage, and ϵ is a hyperparameter defining the clipping range. Additionally, the PPO loss often includes a value function loss (e.g., mean squared error between predicted values and actual returns) and an entropy bonus to encourage exploration. A KL divergence penalty term against a reference policy is also common in RLHF to prevent the policy from deviating too far from a safe or known good distribution: Ltotal​(θ,ϕ)=LCLIP(θ)−c1​LVF(ϕ)+c2​Sπθ​−c3​DKL​(πθ​(⋅∣st​)∣∣πref​(⋅∣st​)) where LVF(ϕ) is the value function loss, S is the entropy bonus, DKL​ is the KL divergence, and c1​,c2​,c3​ are coefficients.
  • Policy and Value Function Representation: In VERL, the actor (policy) and critic (value function) are typically implemented as LLMs. These can be loaded from HuggingFace Transformers or other compatible sources.1 The reference policy is also an LLM.
  • Training Loop: The PPO training loop in VERL, often orchestrated by a RayTrainer (e.g., PPO Ray Trainer 1), manages the iterative process of rollouts, data aggregation, advantage computation, and distributed updates to the actor and critic models using backends like FSDP or Megatron-LM. The verl/trainer/ppo/ray_trainer.py file is a key entry point for this loop, and it is designed to be extensible for custom datasets and reward functions.13

3.4. LLM Integration

VERL is designed for seamless integration with various LLMs and distributed training backends.

  • HuggingFace Model Integration: VERL readily supports popular HuggingFace models (e.g., Llama, Qwen, Gemma).1 These models can be instantiated as the actor, critic, and reference policy components within the RLHF pipeline. The framework handles the loading and distribution of these models onto the specified GPU resources. The documentation provides guides on adding models with FSDP and Megatron-LM backends.1
  • Backend Integration (FSDP, Megatron-LM): For training large models, VERL integrates with established distributed training libraries:
    • PyTorch FSDP (Fully Sharded Data Parallel): Allows for sharding model parameters, gradients, and optimizer states across data parallel workers, significantly reducing per-GPU memory requirements.8 VERL supports FSDP and is moving towards FSDP2 for better throughput and memory usage.1
    • Megatron-LM: A framework for training giant language models using tensor parallelism, pipeline parallelism, and data parallelism.8 VERL provides support for using Megatron-LM as a backend. The Worker classes in VERL (e.g., ActorRolloutRefWorker) are responsible for managing the LLMs using these backends. The choice of backend can be specified in configuration files.
  • Role of 3D-HybridEngine: The 3D-HybridEngine is crucial for efficient transitions between the training and generation phases of the actor model, especially with large, sharded models.3 When using FSDP or Megatron-LM, model parameters are distributed (sharded) across multiple GPUs. For generation (rollout), the model might need to be in a different configuration (e.g., inference-optimized, potentially less sharded or differently sharded) than for training (e.g., optimizer states sharded). The 3D-HybridEngine manages this resharding process efficiently, minimizing data movement and memory overhead, which is critical for maintaining high throughput in on-policy RL algorithms that frequently alternate between these phases.1

3.5. Data and Reward Preparation

Effective RLHF hinges on appropriate data formatting and well-designed reward functions.

  • Data Preparation for Post-Training: VERL expects data in a specific format for post-training. The documentation includes guides on “Prepare Data for Post-Training”.1 This typically involves providing prompts for generation and, depending on the task, reference responses or data for reward model training.
  • RewardManager and Custom Reward Functions: VERL provides a RewardManager component that allows users to define and integrate custom reward functions.8
    • Pre-implemented Rewards: The framework may offer some standard reward functions.
    • Customized Rewards: Users can implement their own reward logic tailored to specific datasets or objectives (e.g., for math problems, code correctness, or alignment with human preferences). This is essential for guiding the LLM towards desired behaviors. The RewardManager is typically defined in the main training script (e.g., the main_task remote function in the controller process).10
    • Model-based vs. Function-based Rewards: VERL supports both model-based rewards (where another LLM predicts a scalar reward) and function-based rewards (where an explicit function or heuristic calculates the reward, often verifiable for tasks like math or coding).1 For code generation, a sandbox service might be used to execute generated code and assign rewards based on execution results and test case outcomes.12

Configuration files (e.g., ppo_trainer.yaml) allow users to specify dataset paths, reward function configurations, and other related parameters.8

4. Understanding VERL-Agent

VERL-Agent extends the capabilities of VERL to the domain of LLM-powered autonomous agents, focusing on complex reasoning within interactive environments.2

4.1. Purpose and Motivation

The primary purpose of VERL-Agent is to facilitate the training of LLM and VLM agents using reinforcement learning.2 As LLMs are increasingly explored for tasks requiring sequential decision-making, interaction with complex environments (digital or embodied), and long-term planning, specialized tools are needed. VERL-Agent aims to address the unique challenges of training such agents, particularly those involving reasoning over extended interaction sequences. It provides the infrastructure and algorithms necessary to develop agents capable of performing tasks in visual and text-based environments.2

4.2. Key Innovations

VERL-Agent introduces several key innovations tailored for agent training:

  • Scalability for Very Long-Horizon, Multi-Turn Optimization: A significant challenge in training LLM agents is managing the growing context length when interaction histories (states, actions, observations) are concatenated and fed back into the LLM. Prior approaches often suffer from rapidly increasing input/output lengths, making them difficult to scale for tasks with many steps (e.g., ALFWorld tasks can require up to 50 steps).2 VERL-Agent implements a step-wise independent interaction paradigm. Each interaction step is processed individually, without concatenating the entire history into a single monolithic input for the LLM. This aligns with standard RL pipelines and makes the system highly scalable for long-horizon scenarios.2 This design choice is crucial for practical agent training where memory and computational constraints are significant.
  • Parallelized Gym-Style Environments and Group Environments:
    • Gym-Style Interface: VERL-Agent provides an environment interface compatible with the popular OpenAI Gym (now Gymnasium) standard. This promotes interoperability and allows for the use of parallelized environments, which can significantly speed up data collection (rollouts) by running multiple environment instances concurrently.2
    • Group Environments: A novel concept introduced by VERL-Agent is “group environments.” In a group, all environment instances share identical initial states when reset() is called. This feature is particularly beneficial for RL algorithms like GRPO and DAPO (and by extension, GiGPO, which builds on group-based principles) that require multiple rollouts starting from the same initial condition to estimate relative advantages or explore different action sequences from a common point.2 The number of rollouts per group can be configured (e.g., via env.rollout.n in ppo_trainer.yaml).2

These innovations directly address the practical difficulties of applying RL to complex, multi-step agent tasks, enhancing both scalability and the effectiveness of certain classes of RL algorithms.

4.3. Supported Environments

VERL-Agent offers a diverse suite of interactive environments, enabling research and development across various agent domains 2:

  • Embodied AI Environments:
    • ALFWorld: An environment that combines text-based interactions (based on TextWorld) with visual elements, requiring agents to perform household tasks based on natural language instructions.
  • Visual Games:
    • Sokoban: A classic puzzle game where the agent must push boxes to target locations in a grid-world, often requiring visual reasoning and planning.
    • Gym Cards: Likely a card game environment requiring strategic decision-making based on visual and state information.
  • Digital Interface Control Tasks:
    • WebShop: An environment where agents must navigate and interact with a simulated e-commerce website to purchase items based on user instructions.
    • AppWorld (experimental): An environment likely focused on controlling applications or digital interfaces.

Support for these varied environments, including vision-language tasks, highlights VERL-Agent’s goal of enabling the development of versatile reasoning agents.2 Users must install and configure each environment separately before training agents within them.2

4.4. Supported RL Algorithms

VERL-Agent inherits RL algorithms from VERL and introduces its own specialized algorithm, GiGPO. The supported algorithms include 2:

  • PPO (Proximal Policy Optimization)
  • GRPO (Group-based Reward Policy Optimization)
  • DAPO (Dynamic Advantage Policy Optimization)
  • RLOO (Reinforcement Learning with Optimal Orthogonalization)
  • GiGPO (Group-in-Group Policy Optimization): This is a novel, state-of-the-art algorithm introduced with VERL-Agent and is the official implementation for the paper “Group-in-Group Policy Optimization for LLM Agent Training”.2 GiGPO is designed for fine-grained credit assignment in long-horizon agent training.
  • Algorithm Variants: VERL-Agent also supports variants of these algorithms enhanced with techniques like dynamic sampling and “clip-higher”.2

The inclusion of GiGPO is a significant aspect of VERL-Agent, offering a critic-free, memory-efficient, and stable approach specifically designed for the challenges of multi-step agent learning.

5. VERL-Agent Codebase Implementation

The VERL-Agent codebase is structured to support its specialized focus on LLM agent training, extending the foundational VERL framework.

5.1. Repository Structure

The langfengQ/verl-agent GitHub repository is organized with distinct directories for agent systems, environments, algorithms, and examples 2:

  • agent_system/: This core directory houses the logic for agent definitions, environment interactions, and prompt management.
    • environments/: Contains subdirectories for different environment packages (env_package/, e.g., webshop, alfworld) and prompt templates (prompts/).
  • examples/: Provides example scripts for training agents using various RL algorithms (GiGPO, PPO, GRPO, etc.) in the supported environments.2 This is a crucial resource for users to get started.
  • gigpo/: Specifically contains the implementation of the GiGPO algorithm, including its policy, loss function, and trainer logic.2
  • verl/: This directory likely contains the base VERL framework code that VERL-Agent extends or depends upon.2
  • docs/: Contains documentation, potentially including specific details on GiGPO.
  • docker/: Dockerfiles for containerized setups.

5.2. Core Components

  • agent_system/environments/: This is central to VERL-Agent’s functionality.
    • env_package/: Contains the actual implementations of various environments (e.g., ALFWorld, WebShop), typically wrapped to conform to a Gym-style interface.2
    • prompts/: Stores customizable prompt templates that define how the LLM agent should interpret tasks and generate actions for different environments.2
  • agent_system/env_manager.py: This file is responsible for registering new environments and managing them within the VERL-Agent framework. Developers adding new environments need to update this manager, following the EnvironmentManagerBase structure.2

5.3. Agent-Environment Interaction Loop

VERL-Agent implements a multi-step interactive loop where the agent perceives environmental feedback (observations) after each action and learns through RL.2

  • Step-wise Processing: As highlighted previously, VERL-Agent processes each interaction step independently. The agent receives the current observation from the environment, and the LLM policy generates an action. The full history is not necessarily concatenated and fed back into the LLM at each step, which is key to its scalability for long-horizon tasks.2 The exact state representation passed to the LLM at each step (e.g., current observation, a summary of recent history, or task description) would be defined by the specific environment wrapper and agent implementation.
  • Role of Prompts: Prompts play a critical role in guiding the LLM agent’s behavior. These prompts, stored in agent_system/environments/prompts/, can be customized to frame the task, specify the expected action format, and provide context to the LLM.2 For example, a prompt for ALFWorld might instruct the agent on its goal and how to describe its actions.

5.4. GiGPO (Group-in-Group Policy Optimization) Implementation

The GiGPO algorithm is a flagship contribution of VERL-Agent, designed for effective credit assignment in multi-step agent tasks.2 Its implementation is primarily located in the gigpo/ directory.2

  • Conceptual Overview: GiGPO employs a two-level grouping mechanism to estimate relative advantages without relying on a critic model:
    1. Episode-level groups: Capture overall task success (e.g., total return of an episode) by comparing multiple trajectories initiated from the same state, similar to GRPO.2
    2. Step-level groups: Identify “anchor states” – states that recur across different trajectories or within the same trajectory. Actions taken from the same anchor state are grouped, allowing for a more fine-grained comparison of their immediate or short-term consequences.2
  • Mathematical Formulation 15:
    • Episode-Level Macro Relative Advantage (AE​(τi​)): For a group of N trajectories {τi​}i=1N​ starting from an identical initial state, where R(τi​) is the total return of trajectory τi​: AE​(τi​)=Fnorm​{R(τj​)}j=1N​R(τi​)−mean{R(τj​)}j=1N​​ Fnorm​ is a normalization factor, typically the standard deviation or a constant.
    • Step-Level Micro Relative Advantage (AS​(at(i)​)): For an anchor state s~ encountered at step t in trajectory i (i.e., st(i)​=s~), let Rt(i)​=∑k=tT​γk−trk(i)​ be the discounted future return from that state-action pair. A step-level group GS​(s~) consists of all (at(j)​,Rt(j)​) pairs where st(j)​=s~. AS​(at(i)​)=Fnorm​{Rt(j)​∣(at(j)​,Rt(j)​)∈GS​(s~)}Rt(i)​−mean{Rt(j)​∣(at(j)​,Rt(j)​)∈GS​(s~)}​
    • Combined Group-in-Group Advantage: The two advantages are combined with a weighting coefficient ω≥0: A(at(i)​)=AE​(τi​)+ω⋅AS​(at(i)​)
    • GiGPO Objective Function: GiGPO uses a clipped policy optimization objective similar to PPO, but with the combined advantage A(at(i)​) and potentially a KL penalty against a reference policy​.
  • Critic-Free Nature: GiGPO is critic-free because its advantage estimation relies entirely on empirical returns and comparisons within sampled groups of trajectories, rather than a learned value function (critic network).5 The anchor state grouping for step-level advantages is performed retroactively on collected trajectories, incurring minimal computational overhead (e.g., using hashmaps to identify common states).15 This makes GiGPO memory-efficient and helps stabilize training, especially for LLMs.
  • Key Files/Classes 2:
    • gigpo/gigpo_trainer.py: Contains the GiGPOTrainer class, which orchestrates the overall training loop, including data collection, calling functions for advantage calculation, and performing policy updates.
    • gigpo/gigpo_loss.py: Implements the GiGPO loss function, taking policy outputs and the calculated two-level advantages to compute the objective for policy gradient updates.
    • gigpo/gigpo_policy.py: Defines the policy network, likely an LLM adapted for GiGPO.
    • gigpo/gigpo_utils.py: Contains utility functions for tasks like grouping trajectories, calculating returns, and managing anchor states. The calculation of AE​ and AS​ and their combination would occur within the GiGPOTrainer, potentially using helper functions from gigpo_utils.py, before being passed to the loss function in gigpo_loss.py.

The GiGPO implementation in VERL-Agent provides a powerful, specialized tool for training reasoning agents, demonstrating significant performance gains over baselines like GRPO on challenging benchmarks such as ALFWorld and WebShop, while maintaining similar resource overhead.5

6. Tutorial: Fine-Tuning Reasoning Models with VERL and VERL-Agent

This section provides a guide on using VERL and VERL-Agent to fine-tune reasoning models with reinforcement learning.

6.1. Installation and Setup

VERL Installation 1:

  1. Create a Conda Environment: It is recommended to use a dedicated conda environment.

    Bash

    conda create -n verl python=3.10 # Or a compatible version
    conda activate verl
    
  2. Install PyTorch: Install a version of PyTorch compatible with your CUDA version. Refer to the official PyTorch website for specific commands.

  3. Install Dependencies: Install other necessary dependencies, which may include transformers, ray, vllm, etc. Specific versions might be required; consult the VERL documentation or requirements.txt.

  4. Install FlashAttention (Optional but Recommended): For improved performance with Transformer models.

    Bash

    pip install flash-attn --no-build-isolation
    
  5. Install VERL: Clone the VERL repository and install it.

    Bash

    git clone https://github.com/volcengine/verl.git
    cd verl
    pip install -e.
    

    VERL also provides Docker images, including support for AMD ROCm, which can simplify setup.8 For AMD GPUs, specific environment variables and Docker configurations are needed.9

VERL-Agent Installation 2:

VERL-Agent builds upon VERL. It is crucial to install environments in separate conda environments if possible to avoid conflicts.

  1. Create a Conda Environment for VERL-Agent:

    Bash

    conda create -n verl-agent python==3.12 -y # As per VERL-Agent README
    conda activate verl-agent
    
  2. Install PyTorch and FlashAttention:

    Bash

    pip3 install torch==2.6.0 --index-url https://download.pytorch.org/whl/cu124 # Example version
    pip3 install flash-attn --no-build-isolation
    
  3. Install VERL-Agent:

    Bash

    git clone https://github.com/langfengQ/verl-agent.git
    cd verl-agent
    pip3 install -e.
    
  4. Install vLLM:

    Bash

    pip3 install vllm==0.8.2 # Example version
    
  5. Install Supported Environments: Each environment has specific installation steps. It is strongly recommended to install each in its own dedicated conda environment to manage dependencies.

    • ALFWorld: Requires gymnasium, stable-baselines3, alfworld, thinc. Download PDDL/Game files using alfworld-download -f.
    • WebShop: Requires Python 3.9. Create a separate conda environment. Run setup.sh within its directory.
    • Sokoban: Requires matplotlib, gym, gym_sokoban.
    • Gym Cards: Install via pip3 install -e./agent_system/environments/env_package/gym_cards/gym-cards/.
    • AppWorld (Experimental): Involves installing its package and downloading data. Refer to the VERL-Agent README for precise commands for each environment.2 After installing an environment in its dedicated conda space, you might need to reinstall verl-agent dependencies in the main verl-agent conda environment if you switch back to run the trainer.

6.2. General Workflow for RL Fine-Tuning

The general process for fine-tuning an LLM for reasoning tasks using VERL or VERL-Agent involves several steps:

  1. Define Task and Environment: Clearly specify the reasoning task (e.g., mathematical problem solving, code generation, interactive question answering) and select or create an appropriate environment.
  2. Prepare Dataset and Pre-trained Model:
    • Dataset: Collect or prepare a dataset of prompts relevant to the task. For RLHF, this might also include preference data or demonstrations.
    • Pre-trained LLM: Choose a suitable pre-trained LLM (e.g., from HuggingFace) as the starting point for fine-tuning. This model will serve as the initial actor policy and potentially the base for the reference and critic models.
  3. Configure Reward Function: This is a critical step. The reward function must accurately reflect the desired reasoning behavior.
    • In VERL, use the RewardManager to define custom rewards.8 This could be a rule-based function (e.g., checking the correctness of a math solution) or a learned reward model.
    • In VERL-Agent, rewards are typically provided by the environment (e.g., a sparse reward upon task completion in ALFWorld, or a score in WebShop).
  4. Select and Configure RL Algorithm: Choose an RL algorithm (e.g., PPO for general tasks, GiGPO for agent-based tasks). Configure its hyperparameters in a YAML file (e.g., ppo_trainer.yaml, gigpo_config.yaml) or via command-line arguments. This includes learning rates, batch sizes, clipping parameters, discount factors, and algorithm-specific parameters (like ω for GiGPO).
  5. Set Up Training Infrastructure:
    • Configure the models (actor, critic, reference policy) and their backends (FSDP, Megatron-LM).
    • Specify resource allocation (GPUs) for each component. VERL’s flexible device mapping is useful here.
    • If using distributed training, set up a Ray cluster.8
  6. Run Training and Monitor: Launch the training script. Monitor training progress using integrated tools like TensorBoard or WandB.1 Track metrics such as reward, episode length, KL divergence, and loss values.
  7. Evaluate Fine-tuned Model: After training, evaluate the performance of the fine-tuned LLM on a held-out test set or in the target environment to assess improvements in reasoning capabilities.

6.3. Fine-Tuning with PPO in VERL (Conceptual Example - GSM8K)

Let’s consider fine-tuning an LLM for mathematical reasoning on the GSM8K dataset using PPO in VERL.1

  1. Data Preparation:
    • Use GSM8K questions as prompts. Each prompt is a math word problem.
    • The LLM actor will generate a step-by-step solution and a final answer.
    • VERL documentation provides guidance on data formatting (Prepare Data for Post-Training).8
  2. Reward Function:
    • Implement a custom reward function using VERL’s RewardManager.
    • The reward could be binary: +1 if the LLM’s final numerical answer matches the ground truth answer, 0 or -1 otherwise.
    • More sophisticated rewards could consider the correctness of intermediate reasoning steps if a process-based reward model is available.
  3. Model Setup:
    • Actor: An LLM (e.g., Qwen2-7B-Instruct 9) that generates solutions.
    • Critic: Another LLM (or a shared body with a different head) that estimates the value of states (prompts/partial solutions).
    • Reference Policy: A frozen copy of the initial SFT model, used for KL divergence regularization.
  4. Configuration (ppo_trainer.yaml) 8:
    • data: Paths to the GSM8K dataset.
    • actor_model_name_or_path, critic_model_name_or_path, ref_model_name_or_path.
    • reward_fn_path or configuration for the custom reward.
    • algorithm: PPO hyperparameters (learning rate, batch size, epochs, clip_epsilon, KL coefficient).
    • trainer: Ray configuration, GPU allocation, backend (FSDP). The VERL documentation includes explanations for ppo_trainer.yaml for the FSDP backend.8
  5. Running the PPO Trainer:
    • Use a script similar to those in examples/ (e.g., run_gsm8k_example.sh if available, or adapt existing PPO examples).
    • The PPO Ray Trainer will manage the distributed training loop: sampling solutions, calculating rewards and advantages, and updating actor and critic models.1

6.4. Fine-Tuning an Agent with GiGPO in VERL-Agent (Conceptual Example - ALFWorld)

Let’s outline fine-tuning an LLM agent for tasks in ALFWorld using GiGPO with VERL-Agent.2

  1. Environment Setup:
    • Install ALFWorld and its dependencies in a separate conda environment as per VERL-Agent instructions.2
    • Ensure alfworld-download -f has been run to get necessary game files.
  2. Reward Function:
    • ALFWorld typically provides a sparse reward: +1 for successful task completion, 0 otherwise. This reward is naturally provided by the environment.
    • The configuration for VERL-Agent would point to using this environment-provided reward. While specific YAML keys like reward_key or reward_fn are not detailed in the overview snippets, the environment wrapper for ALFWorld would handle reward extraction.
  3. Model Setup:
    • Policy: An LLM (e.g., Qwen2.5-1.5B-Instruct or Qwen2.5-7B-Instruct 16) acts as the agent’s policy, taking observations (text descriptions of the environment state and task) and generating actions (text commands).
    • GiGPO is critic-free, so no separate critic model is needed.5
  4. Configuration (Script Arguments / YAML):
    • The example scripts like examples/gigpo_trainer/run_alfworld.sh will contain command-line arguments to configure the training.2 These arguments would specify:
      • Environment name (alfworld).
      • Model name or path.
      • GiGPO hyperparameters: num_rollouts_per_prompt (for group environment, N), omega (weight for step-level advantage), learning rate, batch size, clipping epsilon, KL coefficient if using a reference policy.
      • Rollout parameters: max_episode_length.
    • The env.rollout.n parameter in a ppo_trainer.yaml (if used by GiGPO trainer structure) would control rollouts per group for group environments.2
  5. Running the GiGPO Trainer:
    • Execute the provided shell script: Bash
      bash examples/gigpo_trainer/run_alfworld.sh
      
    • The GiGPOTrainer will manage:
      • Interacting with parallel ALFWorld environments (using the step-wise independent paradigm).
      • Collecting trajectories.
      • Calculating episode-level macro advantages (AE​) based on task success.
      • Performing anchor state grouping to calculate step-level micro advantages (AS​).
      • Updating the LLM agent’s policy using the combined GiGPO advantage and objective function.15

6.5. Customization and Extension

Both VERL and VERL-Agent are designed for extensibility.

  • Adding New Models:
    • VERL provides documentation on how to add models with FSDP and Megatron-LM backends.1 This typically involves ensuring the model architecture is compatible and configuring the chosen distributed backend correctly. The 3DParallelWorker and 3D-HybridEngine facilitate this by abstracting many distributed complexities.3
  • Defining Custom Reward Functions in VERL:
    • As mentioned, the RewardManager allows users to plug in their Python functions for reward calculation.8 These functions take generated responses and other relevant data as input and return a scalar reward.
  • Adding New Environments in VERL-Agent:
    1. Create the environment package with a Gym-style interface, ensuring it supports multi-process execution. Place it in agent_system/environments/env_package/.2
    2. Define corresponding prompt files in agent_system/environments/prompts/ to guide the LLM agent’s interaction with the new environment.2
    3. Register the new environment in agent_system/env_manager.py by creating a new class that inherits from EnvironmentManagerBase and implements its methods.2

The underlying HybridFlow architecture of VERL, with its decoupled control and computation flows, is what makes these extensions relatively straightforward. Users can focus on the specifics of their model, reward, or environment without needing to modify the core distributed orchestration logic extensively. This adaptability is a significant strength, allowing the frameworks to evolve with new research and application needs.

7. Advanced Topics and Best Practices

7.1. Distributed Training with Ray

VERL extensively utilizes Ray for scaling out RLHF and agent training workloads.9 Ray is a flexible, open-source framework for building and running distributed applications.

  • Orchestration: VERL’s HybridFlow programming model, particularly the single_controller and WorkerGroup abstractions, integrates with Ray to manage distributed worker processes.10 The controller process, running on a single Ray actor or process, dispatches tasks to WorkerGroups (collections of Ray actors, each potentially managing one or more GPUs).
  • Resource Management: Ray handles the allocation of resources (CPUs, GPUs) to these distributed workers. VERL’s ResourcePool abstraction likely maps to Ray’s resource specification capabilities.12
  • Scalability: By leveraging Ray, VERL can scale training from a single machine to large clusters, distributing the computationally intensive tasks of LLM inference (for rollouts) and training (for policy/value updates) across many nodes and GPUs.8 The PPO trainer, for example, is often implemented as a PPO Ray Trainer.8
  • Multi-Node Setup: VERL documentation provides guidance on setting up multi-node Ray clusters and submitting jobs, including on Slurm-managed clusters and with tools like dstack.8 Specific scripts for multi-node training on AMD clusters are also available.8

7.2. Performance Tuning

Achieving optimal performance in large-scale RLHF is crucial. VERL incorporates and recommends several techniques:

  • High-Performance Inference Engines: For fast rollouts, VERL supports integration with SOTA inference engines like vLLM and SGLang.1 Upgrading to recent versions (e.g., vLLM >= v0.8.2) is often recommended.1
  • Kernel Optimizations:
    • Flash Attention 2: Using optimized attention mechanisms like Flash Attention 2 can significantly speed up Transformer computations and reduce memory usage.7
    • Fused Kernels: VERL aims to use fused kernels for operations like alignment loss to improve efficiency.13
  • Memory Optimizations:
    • Sequence Packing: Combines multiple shorter sequences into a single packed sequence to improve GPU utilization during training.7
    • LoRA (Low-Rank Adaptation): Fine-tuning only a small number of adapter parameters instead of the full model can drastically reduce memory requirements and improve training speed for RL.7
    • Efficient Resharding: The 3D-HybridEngine minimizes memory redundancy during model resharding between training and generation.1
  • Performance Tuning Guide: VERL provides a detailed performance tuning guide in its documentation to help users optimize throughput for on-policy RL algorithms.1 This guide likely covers aspects like batch sizing, parallelization strategies, and optimal configuration of underlying engines like FSDP or Megatron-LM.

7.3. Debugging

Debugging distributed RL applications can be challenging. VERL documentation suggests using 8:

  • Ray Distributed Debugger VSCode Extension (Recommended): This provides a more integrated debugging experience for Ray applications.
  • Legacy Ray Debugger: Older debugging tools available within the Ray ecosystem. Understanding Ray’s dashboard and logging capabilities is also essential for diagnosing issues in distributed runs.

7.4. Multi-Modal RL

VERL explicitly supports vision-language models (VLMs) and multi-modal RL.1 This means the framework can handle data that includes both visual and textual components, and train policies that reason over such combined inputs.

  • Example: The Geo3K dataset is mentioned in the context of GRPO training with a multi-modal model in VERL’s documentation.8
  • VERL-Agent: Also supports VLM agents, enabling development in environments where visual perception is key (e.g., Sokoban, potentially ALFWorld with visual inputs).2 The underlying infrastructure (e.g., data loading, model wrappers) would need to be adapted to handle multi-modal data streams.

7.5. Considerations for Reasoning Tasks

Fine-tuning LLMs for complex reasoning presents unique challenges:

  • Reward Shaping: For tasks with sparse rewards or complex multi-step reasoning, designing effective reward functions is critical. Simple outcome-based rewards might not provide sufficient signal. Techniques like reward shaping (providing intermediate rewards for correct reasoning steps) or using process-based reward models (which evaluate the reasoning process itself) can be beneficial. VERL’s custom RewardManager is key here.
  • Handling Long Interaction Histories: Reasoning often unfolds over many turns of interaction.
    • VERL-Agent’s step-wise independent interaction paradigm is specifically designed to address the scalability issues of concatenating long histories.2
    • However, the agent still needs access to relevant past information. This might be managed through explicit memory mechanisms, summarization, or by designing the state representation to include crucial historical context.
  • Credit Assignment: In long sequences of actions, determining which actions were responsible for the final outcome (success or failure) is difficult.
    • Traditional methods like PPO with GAE attempt to address this.
    • VERL-Agent’s GiGPO offers a more nuanced, critic-free approach with its two-level advantage estimation (episode-level for overall task success, step-level for local action effectiveness via anchor states).5 This is particularly relevant for improving fine-grained decision-making in reasoning agents.

8. Ecosystem and Community

VERL and VERL-Agent are part of a growing ecosystem of tools and research focused on LLM alignment and agent development.

VERL’s effectiveness is amplified by its integration with and relation to several other important projects and technologies in the LLM space:

  • Inference and Serving Engines:
    • SGLang and vLLM: VERL integrates with these SOTA LLM inference engines for high-throughput generation during rollouts.1 There are community blogs highlighting joint work, such as “SGLang, verl, OpenBMB and Tsinghua University: Pioneering End-to-End Multi-Turn RLHF”.1
  • Distributed Training Frameworks:
    • PyTorch FSDP and Megatron-LM: Core backends for distributed training of large models in VERL.1
    • DeepSpeed Ulysses: VERL supports sequence parallelism via DeepSpeed Ulysses, enhancing its ability to handle long sequences efficiently.7
  • Memory Efficiency Techniques:
    • LoRA (Low-Rank Adaptation): Supported for memory-efficient fine-tuning.1
  • Kernel Libraries:
    • Liger-kernel: Mentioned as an integrated optimization.7
  • RL Algorithm Research: VERL serves as a platform for implementing and testing novel RL algorithms. Projects and papers built on or related to VERL include:
    • DAPO: A SOTA RL algorithm achieving high scores on math benchmarks, with training fully powered by VERL.7
    • PRIME (Process reinforcement through implicit rewards).7
    • RAGEN (a general-purpose reasoning agent training framework).7
    • PURE (Credit assignment for process reward models).7
    • GiGPO: Developed within VERL-Agent.2

This interconnectedness demonstrates that VERL is not an isolated framework but rather a component that leverages and contributes to the broader advancements in LLM infrastructure and RL research.

8.2. Community Contributions and Development

VERL is presented as a community-maintained project, building on its initial development by the ByteDance Seed team.1 Its open-source nature encourages contributions and extensions.

  • Active Development: The GitHub repository shows ongoing development, with news updates about releases (e.g., verl v0.2.0.post2) and presentations at conferences and meetups (Ray Summit, Ray Forward, EuroSys, vLLM Beijing Meetup, LMSys Meetup).1 This indicates a vibrant project with continued investment.
  • Research Output: VERL (as HybridFlow) is itself a research contribution accepted to EuroSys 2025.1 Several papers cite or use VERL/HybridFlow, showcasing its adoption in the research community.1
  • Community Engagement:
    • Blogs and Tutorials: Community members have written blogs about using VERL, such as guides for GRPO distributed training and analyses of the HybridFlow paper.1
    • Hardware Support: Efforts to enable VERL on different hardware, like AMD GPUs with ROCm integration, involve community contributions and pull requests to both VERL and related libraries like Ray.1
    • Feature Requests and Issue Tracking: The GitHub issues section 13 reflects active engagement from users and developers, shaping the project’s roadmap.

This active development and community involvement suggest that VERL is a “living framework” that is continuously evolving. Users can anticipate new features, performance improvements, and broader hardware/model support. The planned “engine interface for training backends” 13 and efforts to make the Ray trainer easier to extend without modifying source code further point towards a commitment to modularity and user-driven extensibility. This architectural foresight, rooted in the HybridFlow design, is critical for the long-term viability and adaptability of the framework in the fast-paced field of LLM research.

9. Conclusion and Future Directions

VERL and its agent-focused extension, VERL-Agent, represent significant contributions to the field of large language model fine-tuning through reinforcement learning. VERL, built upon the innovative HybridFlow architecture, provides a flexible, efficient, and scalable platform for applying a wide range of RL algorithms to LLMs. Its key strengths lie in the hybrid controller model, efficient 3D-HybridEngine for model resharding, seamless integration with SOTA LLM infrastructure, and support for diverse tasks including multi-modal RL and tool use.

VERL-Agent specializes these capabilities for the burgeoning domain of LLM agents. Its step-wise independent interaction paradigm addresses scalability for long-horizon tasks, and the novel GiGPO algorithm offers a sophisticated, critic-free solution to the critical challenge of credit assignment in multi-step agent reasoning. Together, these frameworks empower researchers and practitioners to develop more capable and aligned LLMs and intelligent agents.

The future trajectory of VERL and VERL-Agent appears to be driven by a dual focus: enhancing core system performance and efficiency while simultaneously expanding algorithmic and modeling capabilities. On the systems side, developments like fused kernels, FP8 precision for RL, and speculative decoding integration aim to push throughput and reduce computational costs.13 On the algorithmic and modeling front, support for new SOTA models (e.g., Gemma3, DeepSeek v3), additional RL algorithms (e.g., Dr. GRPO), and broader hardware compatibility (e.g., stable Ascend NPU support) are on the roadmap.13 This balanced strategy is essential for keeping the frameworks at the cutting edge.

Moreover, as LLM reasoning tasks and agent interactions grow in complexity, VERL and VERL-Agent will likely need to evolve further. The current suite of environments, while challenging, represents a starting point. Training truly general reasoning agents may necessitate advancements in areas such as:

  • Sophisticated Reward Modeling: Moving beyond sparse or simple outcome-based rewards to incorporate more nuanced process-based feedback or learned reward models that can capture complex human preferences for reasoning quality.
  • Automated Curriculum Learning: Developing mechanisms for automatically adjusting task difficulty or generating new training scenarios to ensure continuous learning and prevent stagnation.
  • Handling Partial Observability and Uncertainty: Enhancing agent architectures and training methods to cope with incomplete information and ambiguous situations, which are common in real-world reasoning.
  • Multi-Agent Reinforcement Learning: Extending the frameworks to support scenarios where multiple agents interact, collaborate, or compete, opening new avenues for complex collective reasoning.

In conclusion, VERL and VERL-Agent provide a robust and evolving ecosystem for fine-tuning the reasoning abilities of large language models. Their strong architectural foundations, coupled with active community development and a clear vision for future enhancements, position them as valuable tools for advancing the frontiers of artificial intelligence.