AgentGym-RL

repository·main·Indexed 21 days ago

https://github.com/woooodyy/agentgym-rl

A framework for training LLM agents to handle complex, multi-turn, long-horizon decision-making tasks using Reinforcement Learning. It features a modular system with environments for Web Navigation (WebArena), Deep Search (Search-R1), Digital Games (TextCraft), Embodied Tasks (BabyAI), and Scientific Tasks (SciWorld). The framework introduces ScalingInter-RL for progressive horizon scaling and extends the verl library with specialized RolloutHandlers, EnvClients, and support for RL algorithms including PPO, GRPO, RLOO, and REINFORCE++.

Tokens
30K
Snippets
58
Records
96
Agent score
74%

What's inside AgentGym-RL

  1. Overview of the verl RL training framework

    main

    verl is a flexible, efficient, and production-ready Reinforcement Learning (RL) training framework designed for Large Language Model (LLM) post-training. It is an open-source implementation of the HybridFlow paper.

    Key Capabilities

    • Algorithm Extension: Uses a Hybrid programming model to combine single-controller and multi-controller paradigms, allowing users to build complex RL dataflows with minimal code.
    • Modular Integration: Decouples computation and data dependencies to integrate seamlessly with existing LLM infrastructure like PyTorch FSDP, Megatron-LM, and vLLM.
    • Scalable Parallelism: Supports flexible device mapping to place models on different GPU sets for efficient resource utilization across various cluster sizes.
    • High Throughput: Achieves state-of-the-art throughput by integrating SOTA training/inference frameworks and utilizes a 3D-HybridEngine for efficient actor model resharding, which reduces memory redundancy and communication overhead during transitions between training and generation phases.
  2. Overview of AgentGym-RL

    main

    AgentGym-RL is a framework designed for training Large Language Model (LLM) agents to perform multi-turn interactive decision-making using Reinforcement Learning (RL). Unlike single-turn RL (e.g., math or coding), AgentGym-RL focuses on long-horizon tasks in diverse, real-world environments.

    Key components include:

    • Environment Module: Uses a standardized server-client architecture with HTTP protocols for parallel requests.
    • Agent Module: Handles reasoning, decision-making, long-horizon planning, and self-reflection.
    • Training Module: Implements RL pipelines and optimization methods.

    The framework also introduces ScalingInter-RL, a method that progressively increases the interaction horizon (number of turns) during training to balance exploration and exploitation.

  3. Supported RL algorithms and features in verl

    main

    verl provides support for several post-training and reinforcement learning tasks:

    RL Algorithms:

    • PPO (Proximal Policy Optimization)
    • GRPO (Group Relative Policy Optimization)
    • ReMax
    • Supports both model-based rewards and function-based (verifiable) rewards.

    Training & Inference Infrastructure:

    • Training Backends: PyTorch FSDP and Megatron-LM.
    • Rollout Generation: vLLM and TGI (SGLang support coming soon).
    • Model Support: Seamless integration with HuggingFace models.
    • Optimization Techniques: Flash-attention, sequence packing, long context support (via DeepSpeed Ulysses), LoRA, and Liger-kernel.

    Experiment Tracking:

    • Integrates with wandb, swanlab, and mlflow.
  4. Understand the HybridFlow design in verl

    main

    The verl library implements the HybridFlow architecture, which treats Reinforcement Learning (RL) as a two-level dataflow problem. This design decouples the high-level algorithm logic from the low-level neural network computations to balance performance and flexibility.

    The Two Levels of Dataflow

    1. Control Flow: Defines the high-level execution of the RL algorithm (e.g., in PPO: Rollout $\rightarrow$ Advantage Computation $\rightarrow$ Training). This defines the core logic of the RL algorithm.
    2. Computation Flow: Defines the neural network operations (e.g., model forward, backward, optimizer steps). This is the standard tensor-level computation.

    The Hybrid Approach

    Unlike unified multi-controller systems that couple control and computation flows, verl uses a separated flow strategy:

    • Single-process Control Flow: The controller (the RL algorithm logic) runs on a single process. This makes it simple to implement new RL algorithms by just defining a new control flow.
    • Multi-process Computation Flow: The heavy lifting (generator/actor workers, critic workers) runs on multiple processes across specific resource groups. This allows for high-performance, scalable neural network training (e.g., using FSDP or Megatron).

    Trade-off: While this separation introduces some data communication overhead when the controller interacts with workers, it provides significantly higher reusability. You can swap computation engines (e.g., from FSDP to Megatron) without rewriting your RL algorithm's control logic.

  5. Use the Megatron-LM Backend with 3D HybridEngine

    main

    The Megatron-LM backend allows for high scalability and throughput by supporting 3D parallelism and sequence parallelism. It utilizes a 3DHybridEngine (implemented via megatron_vllm.py) that combines Megatron-LM and vLLM to reduce peak memory usage and minimize weight synchronization overhead between the actor and rollout models.

    Note for Developers: When using this backend, you must:

    1. Implement your own models for Megatron-LM.
    2. Implement a corresponding weight_loader to:
      • Synchronize model weights between the actor (Megatron) and the rollout (vLLM).
      • Load weights from checkpoints into the Megatron-LM model.
  6. ScalingInter-RL: Progressive Horizon Scaling

    main

    ScalingInter-RL is a training strategy designed to improve optimization stability and exploration in agent RL. It uses a progressive horizon-scaling strategy that adaptively adjusts the number of interaction turns during training:

    1. Early Training: Starts with a smaller horizon to allow the agent to exploit its policy and gain proficiency on simpler tasks.
    2. Progressive Scaling: Gradually extends the interaction horizon, enabling the agent to explore longer decision paths and develop higher-order cognitive behaviors.
  7. Understand verl training and rollout backends

    main

    The verl library supports different backends depending on whether you are performing training or rollout generation:

    Training Backends

    • FSDP: Recommended for investigation, research, and prototyping different models, datasets, and RL algorithms.
    • Megatron-LM: Recommended for users pursuing better scalability. Currently supports Megatron-LM v0.4 (requires patching).

    Rollout Generation Backends

    • vLLM: Supported for rollout generation.
    • TGI: Supported for rollout generation.
    • SGLang: Support is coming soon.
  8. Supported Environments in AgentGym-RL

    main

    AgentGym-RL provides several diverse environments for training and evaluating agents:

    • Web Navigation: Includes WebArena (online shopping, discussion forums, collaborative development, and business content management).
    • Deep Search: Based on Search-R1, a RAG-based environment for multi-turn retrieval and reasoning via search engines.
    • Digital Games: Includes TextCraft, a text-based crafting game requiring natural language interaction and planning.
    • Embodied Tasks: Includes BabyAI, a controllable grid world with text instructions.
    • Scientific Tasks: Includes SciWorld, a scientific exploration simulator for text-driven reasoning cycles.
  9. Understand WorkerGroup and Worker construction

    main

    The RayPPOTrainer manages the PPO loop using WorkerGroup and Worker abstractions:

    • Worker: A remote process running on a specific GPU. Workers expose APIs (like init_model, generate_sequences, compute_log_prob) that are invoked via remote calls.
    • WorkerGroup: A proxy object that manages a list of workers. It runs in the process of its constructor and serves as the interface for the controller to interact with the remote workers.

    Common WorkerGroups in PPO:

    1. ActorRolloutRef: Manages the actor, rollout, and reference policy. It can colocate these components (e.g., actor and rollout) to enable fast weight transfers via NCCL or efficient LoRA PPO.
    2. Critic: Manages the critic model.
    3. Reward: Manages the reward model.

    Each WorkerGroup is constructed on a designated ResourcePool (a set of GPUs in the Ray cluster).

  10. Use PPORayTrainer for RL training

    main
    The PPORayTrainer is a trainer that runs on the driver process (typically on a single CPU/GPU node). It manages three core responsibilities: data preparation, WorkerGroup initialization, and the PPO training loop. It is designed to load batches of samples and dispatch them to various worker_groups running on different GPUs.
  11. How the HybridFlow execution model works

    main

    In a verl reinforcement learning job, execution is distributed between a central controller and specialized workers:

    1. Controller (Single Process): Orchestrates the entire RL algorithm. It manages the sequence of operations and coordinates data movement between different worker groups.
    2. Workers (Multi-process): Specialized groups of processes assigned to specific tasks:
      • Generator/Actor Workers: Perform rollout/sample generation.
      • Critic Workers: Perform value estimation/critic updates.

    Data Flow Pattern:

    • The controller sends data/instructions to a worker group (e.g., sending prompts to the Generator for rollout).
    • The worker group performs the high-level computation (e.g., generating samples).
    • The worker group sends the resulting data back to the controller.
    • The controller then uses that data to trigger the next step in the algorithm (e.g., passing samples to the Critic or Actor for training).
  12. Optimize performance by colocating WorkerGroups

    main

    To save redundant CUDA and distributed context overhead, you can merge different roles (e.g., actor, critic, reference, reward model) into the same process using create_colocated_worker_cls.

    Important Considerations:

    • Resource Pools: If you need different resource pools (and thus different parallel sizes) for each role, do not use create_colocated_worker_cls. Instead, pass different resource pools directly to different worker groups.
    • Megatron Backend: When colocating roles in the same process, all roles will share the same 3D parallel size. If you require different 3D parallel sizes for different roles, you must initialize each role's worker_group separately (as shown in the non-colocated example) rather than using the colocation optimization.
    • Rollout Initialization: It is recommended to create the actor_rollout worker group last to allow vllm to better estimate KV cache memory requirements.
    # initialize WorkerGroup
    all_wg = {}
    for resource_pool, class_dict in self.resource_pool_to_cls.items():
        worker_dict_cls = create_colocated_worker_cls(class_dict=class_dict)
        wg_dict = self.ray_worker_group_cls(resource_pool=resource_pool, ray_cls_with_init=worker_dict_cls)
        spawn_wg = wg_dict.spawn(prefix_set=class_dict.keys())
        all_wg.update(spawn_wg)
    
    if self.use_critic:
        self.critic_wg = all_wg['critic']
        self.critic_wg.init_model()
    
    if self.use_reference_policy:
        self.ref_policy_wg = all_wg['ref']
        self.ref_policy_wg.init_model()
    
    if self.use_rm:
        self.rm_wg = all_wg['rm']
        self.rm_wg.init_model()
    
    # we should create rollout at the end so that vllm can have a better estimation of kv cache memory
    self.actor_rollout_wg = all_wg['actor_rollout']
    self.actor_rollout_wg.init_model()