Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
The table of contents is too big for display.
Diff view
Diff view
  •  
  •  
  •  
217 changes: 82 additions & 135 deletions README.md
Original file line number Diff line number Diff line change
@@ -1,6 +1,10 @@
<p align="center">
<!-- <p align="center">
<img src="./docs/drmas/drmas_logo.png" alt="logo" width="25%">
</p>
</p> -->

<h1 align="center">
Dr. MAS: Stable Reinforcement Learning for Multi-Agent LLM Systems</b>
</h1>


<p align="center">
Expand All @@ -17,80 +21,37 @@
<img src="https://img.shields.io/badge/Twitter-Channel-000000?style=flat-square&logo=x" alt="X Channel"></a>
</p>

`Dr.MAS` is designed for training **Multi-Agent LLM Systems** via **Reinforcement Learning (RL)**, supporting both homogeneous (shared-LLM) and heterogeneous (non-shared, multi-LLM) agent configurations.
`Dr.MAS` is designed for training **Multi-Agent LLM Systems** via **Reinforcement Learning (RL)**, supporting sophisticated multi-agent setups where specialized LLM-based agents collaborate to tackle complex reasoning and decision-making tasks.

Unlike single-agent approaches, `Dr.MAS` supports sophisticated multi-agent setups where specialized LLM-based agents collaborate to tackle complex reasoning and decision-making tasks. The framework features **flexible agent registry**, **customizable multi-agent orchestration**, **model sharing/non-sharing (e.g., heterogeneous LLMs)**, **per-agent configuration**, and **shared resource pooling**, making it well suited for training multi-agent LLM systems with RL.
This framework features **flexible agent registry**, **customizable multi-agent orchestration**, **LLM sharing/non-sharing (e.g., heterogeneous LLMs)**, **per-agent configuration**, and **shared resource pooling**, making it well suited for training multi-agent LLM systems with RL.

<p align="center">
<img src="./docs/drmas/drmas_framework.png" alt="framework" width="100%">
</p>

# Quick Feature Summary
# Feature Summary

| Feature Category | Supported Capabilities|
| - | - |
| **Flexible Agent Registry** | ✅ Decorator-based agent registration (`@AgentRegistry.register`)<br>✅ Clear role specialization per agent<br>✅ Easy agent composition and management |
| **Multi-Agent Orchestration** | ✅ User-defined orchestration via `BaseOrchestra`<br>✅ Sequential, hierarchical, and conditional execution<br>✅ Built-in Search Orchestra (Verifier → Search/Answer)<br>✅ Built-in Math Orchestra (Solver ↔ Verifier loop) |
| **Agent-Model Assignment** | ✅ Flexible model-sharing or dedicated-model setups<br>✅ Heterogeneous LLMs per agent (different model families/sizes/checkpoints)<br>✅ Automatic logical mapping of agents to LLM worker groups|
| **Per-Agent Configuration** | ✅ Agent-specific actor hyperparameter<br>✅ Per-agent training overrides for fine-grained control |
| **Shared Resource Pooling** | ✅ Shared GPU pool across multiple LLM worker groups for efficient hardware utilization <br>✅ SGLang for high-throughput, low-latency inference|
| **Flexible Agent Registry** | ✅ User-defined agent registration via `@AgentRegistry.register`<br>✅ Clear role specialization per agent<br> |
| **Multi-Agent Orchestration** | ✅ User-defined multi-agent orchestration<br>✅ Sequential, hierarchical, and conditional workflows<br>✅ Built-in Search/Math Orchestra |
| **Agent-Model Assignment** | ✅ Logical agents (1,...,K) mapped to LLM worker groups<br>✅ **LLM non-sharing**: one LLM per agent (supports heterogeneous model families/checkpoints)<br>✅ **LLM Sharing**: agents using the same model share one LLM worker group |
| **Per-Agent Configuration** | ✅ Per-agent training overrides for fine-grained control <br>✅ Per-agent learning rates, micro-batch sizes, and other hyperparameters|
| **Shared Resource Pooling** | ✅ Shared GPU pool across multiple LLM worker groups for efficient hardware utilization<br>✅ Gradient updates applied independently for each worker group during optimization |
| **Environments** | ✅ Math<br>✅ Search |
| **Model Support** | ✅ Qwen2.5<br>✅ Qwen3<br>✅ LLaMA<br>and more |
| **RL Algorithms** | ✅ GRPO<br>✅ GiGPO<br>✅ DAPO <br>✅ RLOO <br>and more |
| **Model Support** | ✅ Qwen2.5<br>✅ Qwen3<br>✅ LLaMA3.2<br>and more |
| **RL Algorithms** | ✅ Dr.MAS<br>✅ GRPO<br>🧪 GiGPO (experimental)<br>🧪 DAPO (experimental) <br>🧪 RLOO (experimental) <br>🧪 PPO (experimental) <br>and more |

# Table of Contents

- [Key Features](#key-features)
- [Installation](#installation)
- [Install veRL](#install-verl)
- [Install Supported Environments](#install-supported-environments)
- [Run Examples](#run-examples)
- [Math](#math)
- [Search](#search)
- [Math](#math)
- [Usage Guide](#usage-guide)
- [How to register Custom Agents](#how-to-register-custom-agents)
- [How to Create Custom Orchestras](#how-to-create-custom-orchestras)
- [Agent Configuration](#agent-configuration)
- [Acknowledgement](#acknowledgement)
- [Citation](#citation)


# Key Features

## 1. Flexible Agent Registry

`Dr.MAS` provides a clean, decorator-based mechanism for defining and registering specialized agents:
- Register agents using `@AgentRegistry.register("Agent Name")` decorator
- Each agent can have specialized roles (e.g., Verifier, Search, Answer, Solver)
- Centralized registry makes it straightforward to discover and manage available agents

## 2. Multi-Agent Orchestration

`Dr.MAS` supports user-defined multi-agent orchestra, which governs the agents' execution flow.

- Create custom orchestras by inheriting from `BaseOrchestra`
- Support for sequential, hierarchical, and conditional decision flows

## 3. Agent-Model Assignment

A core assignment logic maps logical agents $(1, ..., K)$ to physical LLM worker groups, enabling flexible model sharing strategies (see [here](./verl/trainer/config/ppo_trainer.yaml#L296)):
- **Non-sharing**: Each agent uses its own LLM, supporting heterogeneous model families, sizes, and checkpoints
- **Sharing**: Agents with the same model share one LLM worker group

## 4. Per-Agent Configuration

`Dr.MAS` offers fine-grained control of each agent's training behavior:

- Per-agent learning rates, PPO micro-batch sizes, and other hyperparameters.
- Shared-model agents undergo consistency checks to avoid conflicting configurations.

## 5. Shared Resource Pooling and Scheduling

`Dr.MAS` manages GPU resources for high efficiency, allowing LLM worker groups to operate within a shared resource pool:

- Shared resource pool across multiple LLM worker groups
- SGLang for fast, parallel LLM decoding
- Gradient updates applied independently for each worker group during optimizatio

# Installation

Expand All @@ -100,25 +61,16 @@ A core assignment logic maps logical agents $(1, ..., K)$ to physical LLM worker
conda create -n DrMAS python==3.12 -y
conda activate DrMAS

pip3 install psutil
pip3 install torch==2.6.0 --index-url https://download.pytorch.org/whl/cu124
pip3 install flash-attn==2.7.4.post1 --no-build-isolation
pip3 install -r requirements_sglang.txt
pip3 install flash-attn==2.7.4.post1 --no-build-isolation --no-cache-dir

pip3 install -e .
pip3 install -r requirements_sglang.txt
```

## Install Supported Environments

### 1. Math
Prepare the dataset:
```bash
cd repo_root/
python examples/data_preprocess/drmas_math.py
```


### 2. Search
### 1. Search
```bash
conda activate DrMAS
cd ./agent_system/environments/env_package/search/third_party
Expand All @@ -135,21 +87,13 @@ python examples/data_preprocess/drmas_search.py

Since faiss-gpu is not available via pip, we setup a separate conda environment for the local retrieval server. Running this server will use around 6GB of GPU memory per GPU, so make sure to account for this in your training run configuration. Build Retriever environments:
```bash
# Create and activate the retriever environment with Python 3.10
conda create -n retriever python=3.10 -y
conda activate retriever

# Install PyTorch (with GPU support) and related libraries
conda install numpy==1.26.4
pip install torch==2.6.0 torchvision==0.21.0 torchaudio==2.6.0 --index-url https://download.pytorch.org/whl/cu124

# Install other Python packages
pip install transformers datasets pyserini huggingface_hub

# Install the GPU version of faiss
conda install faiss-gpu==1.8.0 -c pytorch -c nvidia -y

# Install the API service framework
pip install uvicorn fastapi
```

Expand All @@ -172,135 +116,138 @@ conda activate retriever
bash examples/search/retriever/retrieval_launch.sh > retrieval_server.log
```

### 2. Math
Prepare the dataset:
```bash
cd repo_root/
python examples/data_preprocess/drmas_math.py
```


# Run Examples

## Math
## Search

Train a 2-agent system (Solver, Verifier) for mathematical problem solving:
**Search (hierarchical routing)**: a 3-agent hierarchy where **Verifier** decides whether information is sufficient; it routes to **Search Agent** (generate queries) or **Answer Agent** (final response). See [`agent_system/agent/orchestra/search/README.md`](./agent_system/agent/orchestra/search/README.md).
<p align="center">
<img src="./docs/drmas/search_multi_agent_workflow.png" alt="Multi-Agent Workflow" width="60%">
</p>


```bash
bash examples/drmas_trainer/run_search.sh # Dr.MAS
```
```bash
bash examples/multi_agent_trainer/run_math.sh
bash examples/grpo_trainer/run_search.sh # GRPO
```

After training completes, evaluate the multi-agent system on the full test dataset:
```bash
bash examples/multi_agent_trainer/run_math.sh eval
bash examples/drmas_trainer/run_search.sh eval # Dr.MAS
```
```bash
bash examples/grpo_trainer/run_search.sh eval # GRPO
```

## Search
## Math

Train a 3-agent system (Verifier, Search, Answer) for search tasks:
**Math (iterative refinement)**: a 2-agent loop where **Solver** proposes step-by-step solutions and **Verifier** checks them; items are iterated until approved or max loops reached. See [`agent_system/agent/orchestra/math/README.md`](./agent_system/agent/orchestra/math/README.md).
<p align="center">
<img src="./docs/drmas/math_multi_agent_workflow.png" alt="Multi-Agent Workflow" width="45%">
</p>


```bash
bash examples/drmas_trainer/run_math.sh # Dr.MAS
```
```bash
bash examples/multi_agent_trainer/run_search.sh
bash examples/grpo_trainer/run_math.sh # GRPO
```

After training completes, evaluate the multi-agent system on the full test dataset:
```bash
bash examples/multi_agent_trainer/run_search.sh eval
bash examples/drmas_trainer/run_math.sh eval # Dr.MAS
```
```bash
bash examples/grpo_trainer/run_math.sh eval # GRPO
```

# Usage Guide

## How to Register Custom Agents
For a **comprehensive guide** on developing custom multi-agent LLM systems, including detailed examples and best practices, see the **[Multi-Agent Development Guide](./docs/MULTI_AGENT_DEVELOPMENT_GUIDE.md)**.

To register a new agent:
The guide covers:
- Architecture overview and core components
- Step-by-step agent creation and registration
- Orchestra development patterns
- Configuration options and per-agent parameter overrides
<!--
## Quick Start: Register Custom Agents

1. **Create Agent Class**: Inherit from [BaseAgent](./agent_system/agent/agents/base.py#L13) and implement the `call` method:

```python
MY_AGENT_PROMPT = """
# Task
{env_prompt}

# Team Context
{team_context}

# Your Role
You are a "Custom Agent". Your task is to...
"""

@AgentRegistry.register("Custom Agent")
class CustomAgent(BaseAgent):
def __init__(self, wg_id: str, tokenizer, processor, config):
...
super().__init__("Custom Agent", MY_PROMPT, wg_id, tokenizer, processor, config)

def call(self, gen_batch: DataProto, env_obs: Dict[str, Any],
team_context: List[str], actor_rollout_wg,
agent_active_mask, step: int) -> Tuple[DataProto, List[str]]:
# Build prompt, generate with LLM, parse output
...
```

2. **Import Agent Module**: Ensure the agent module is imported before use (typically done in the orchestra's `__init__`):
2. **Import Agent Module** in the orchestra's `__init__`:

```python
import importlib
importlib.import_module("agent_system.agent.agents.my_agent_module")
```

3. **Register in Configuration**: Add the agent to your configuration:

```yaml
agent:
agent_ids: ["Custom Agent", "Other Agent"]
model_ids: ["model/path/1", "model/path/2"]
```

## How to Create Multi-Agent Orchestras
## Quick Start: Create Custom Orchestras

To create a custom orchestra:

1. **Create New Orchestra Class**: Inherit from [BaseOrchestra](./agent_system/agent/orchestra/base.py#L53):
1. **Create Orchestra Class**: Inherit from [BaseOrchestra](./agent_system/agent/orchestra/base.py#L53):

```python
class MyOrchestra(BaseOrchestra):
# Define agent name constants
AGENT_1 = "Agent 1"
AGENT_2 = "Agent 2"

def __init__(self, agent_ids, model_ids, agents_to_wg_mapping, tokenizers, processors, config):
# Import agent modules
import importlib
importlib.import_module("agent_system.agent.agents.my_agents")

...
super().__init__(agent_ids, model_ids, agents_to_wg_mapping, tokenizers, processors, config)

def run(self, gen_batch: DataProto, env_obs: Dict[str, Any],
actor_rollout_wgs, active_masks: np.ndarray,
step: int) -> Tuple[List[str], Dict[str, DataProto]]:
"""Define the execution flow of agents."""
def run(self, gen_batch, env_obs, actor_rollout_wgs, active_masks, step):
# Define the execution flow of agents
...

```

2. **Register Orchestra**: Add it to the rollout loop [here](./agent_system/multi_turn_rollout/rollout_loop.py#L365):
2. **Register Orchestra** in [rollout_loop.py](./agent_system/multi_turn_rollout/rollout_loop.py#L381):

```python
# In agent_system/multi_turn_rollout/rollout_loop.py
if orchestra_type == "my_orchestra":
from agent_system.agent.orchestra.my_orchestra import MyOrchestra as orchestra
```

## Agent Configuration

Key configuration sections:
```yaml
agent:
multi_agent: True
agent_ids: ["Agent 1", "Agent 2", "Agent 3"]
model_ids: ["model/path/1", "model/path/2", "model/path/3"]
model_sharing: False # Whether to share models across agents
orchestra_type: search # Orchestra type: "search", "math", or custom
model_sharing: False # False = dedicated LLM per agent
orchestra_type: search # "search", "math", or your custom type

# Agent-specific parameter overrides
# The list order corresponds to the order of agent_ids
# Per-agent parameter overrides (order matches agent_ids)
agent_specific_parameters:
actor.optim.lr: [1e-6,1e-6,1e-7]
actor.ppo_micro_batch_size_per_gpu: [4,8,8]
actor.optim.lr: [1e-6, 1e-6, 1e-7]
actor.ppo_micro_batch_size_per_gpu: [4, 8, 8]
```

For detailed examples and advanced patterns, see the **[Multi-Agent Development Guide](./docs/MULTI_AGENT_DEVELOPMENT_GUIDE.md)**. -->

# Acknowledgement

This codebase is built upon [verl-agent](https://github.com/langfengQ/verl-agent) and [verl](https://github.com/volcengine/verl). The Search environment is adapted from [Search-R1](https://github.com/PeterGriffinJin/Search-R1) and [SkyRL-Gym](https://github.com/NovaSky-AI/SkyRL/tree/main/skyrl-gym). The Math environment is adapted from [DeepScaleR](https://github.com/rllm-org/rllm) and [DAPO](https://github.com/volcengine/verl/tree/main/recipe/dapo).

We extend our gratitude to the authors and contributors of these projects for their valuable work.

We extend our gratitude to the authors and contributors of these projects for their valuable work.
7 changes: 5 additions & 2 deletions agent_system/agent/orchestra/math/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,10 @@

## Overview

<p align="center">
<img src="../../../../docs/drmas/math_multi_agent_workflow.png" alt="Math Multi-Agent Workflow" width="80%">
</p>

This is an iterative two-agent architecture designed for mathematical problem solving tasks. The architecture follows an iterative refinement approach with two specialized agents: a Solver Agent that generates step-by-step solutions, and a Verifier Agent that reviews and validates the solutions. The agents work collaboratively in an iterative loop until solutions are approved or a maximum iteration limit is reached.

## Iterative Architecture
Expand Down Expand Up @@ -45,5 +49,4 @@ Iteration Loop (max_loop_num iterations):
4. If max_loop_num reached → Exit loop
```

The architecture supports parallel processing of multiple problems, with each problem tracked independently through the approval process. Once a problem is approved by the Verifier Agent, it is excluded from subsequent iterations, allowing the system to focus computational resources on problems that still need refinement.

The architecture supports parallel processing of multiple problems, with each problem tracked independently through the approval process. Once a problem is approved by the Verifier Agent, it is excluded from subsequent iterations, allowing the system to focus computational resources on problems that still need refinement.
7 changes: 5 additions & 2 deletions agent_system/agent/orchestra/search/README.md
Original file line number Diff line number Diff line change
@@ -1,6 +1,11 @@
# Search Multi-Agent Architecture

## Overview
<p align="center">
<img src="../../../../docs/drmas/search_multi_agent_workflow.png" alt="Search Multi-Agent Workflow" width="80%">
</p>



This is a hierarchical three-agent architecture designed for information search and question answering tasks. The architecture follows a hierarchical structure with distinct layers: a control layer (Verifier Agent) that orchestrates the execution, and an execution layer (Search Agent and Answer Agent) that performs the actual work.

Expand Down Expand Up @@ -46,5 +51,3 @@ Layer 1 (Control):
├─ If "no" → Layer 2 (Execution): Search Agent → Generates search query → Return search query
└─ If "yes" → Layer 2 (Execution): Answer Agent → Generates answer → Return answer
```


Loading