Skip to content

Commit ac06935

Browse files
authored
Merge pull request #6316 from hpcaitech/grpo-support-multi-machine
[feat] Manually schedule resources and support auto master address assigning
2 parents 8992def + 2f02a28 commit ac06935

File tree

3 files changed

+370
-7
lines changed

3 files changed

+370
-7
lines changed
Lines changed: 318 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,323 @@
1-
# Requirements
1+
# Distributed RL Framework for Language Model Fine-Tuning
22

3+
This repository implements a distributed Reinforcement Learning (RL) training framework designed to fine-tune large language models using algorithms such as **GRPO** and **DAPO**. It supports multi-node and multi-GPU setups, scalable rollout generation, and policy optimization using libraries like VLLM. Currently, we support two Reinforcement Learning with Verifiable Reward (RLVR) tasks: solving math problems and code generation.
4+
5+
**Please note that we are still under intensive development, stay tuned.**
6+
7+
---
8+
9+
## 🚀 Features
10+
11+
* **Distributed Training with Ray**: Scalable to multiple machines and GPUs.
12+
* **Support for GRPO and DAPO**: Choose your preferred policy optimization algorithm.
13+
* **Model Backends**: Support `vllm` as inference backends.
14+
* **Rollout and Policy Decoupling**: Efficient generation and consumption of data through parallel inferencer-trainer architecture.
15+
* **Evaluation Integration**: Easily plug in task-specific eval datasets.
16+
* **Checkpoints and Logging**: Configurable intervals and directories.
17+
18+
---
19+
20+
## 🛠 Installation
21+
22+
### Prepare Develop Environment
23+
24+
Install Colossalai & ColossalChat
25+
```bash
26+
git clone https://github.com/hpcaitech/ColossalAI.git
27+
git checkout grpo-latest
28+
BUILD_EXT=1 pip install -e .
29+
30+
cd ./applications/ColossalChat
31+
pip install -e .
32+
```
33+
34+
Install vllm
35+
```bash
36+
pip install vllm==0.7.3
37+
```
38+
39+
Install Ray.
40+
```bash
41+
pip install ray
42+
```
43+
44+
Install Other Dependencies
345
```bash
446
pip install cupy-cuda12x
547
python -m cupyx.tools.install_library --cuda 12.x --library nccl
648
```
49+
50+
To support long input/output sequence length (e.g., 32K), you may need to manually change the default setting (180 seconds) for the `timeout_s` variable in your ray installation to a larger value as shown in the screenshot below.
51+
52+
<div align="center">
53+
<p align="center">
54+
<img src="https://raw.githubusercontent.com/hpcaitech/public_assets/main/applications/chat/change_ray_timeout.png" width=700/>
55+
</p>
56+
</div>
57+
58+
Prepare Model & dataset
59+
```bash
60+
huggingface-cli download --local-dir-use-symlinks False Qwen/Qwen2.5-7B --local-dir /models/Qwen/Qwen2.5-7B
61+
```
62+
63+
## Architecture Design
64+
65+
<div align="center">
66+
<p align="center">
67+
<img src="https://raw.githubusercontent.com/hpcaitech/public_assets/main/applications/chat/producer-consumer-pattern.png" width=700/>
68+
</p>
69+
</div>
70+
Producer-Consumer Pattern: a classic software design pattern used for managing resources, data, or tasks between two different processes or threads.
71+
72+
* Producer: inference engine which rollouts out examples and saves them into a shared buffer.
73+
* Consumer: training framework which takes training examples from the shared buffer and train the policy model.
74+
75+
Key features for Producer-Consumer Pattern:
76+
* Buffer: Acts as a shared queue where the producer adds data and the consumer removes data.
77+
* Concurrency: Rollout and training can work concurrently.
78+
79+
## 🧠 Data Format
80+
81+
Samples in the training or evaluation `.jsonl` file should follow the format specific to the type of task. We currently support two RLVR tasks: solving math problems and code generation.
82+
83+
### Math Data Format
84+
```json
85+
{
86+
"messages": {
87+
"role": "user",
88+
"content": "Simplify $\\sqrt[3]{1+8} \\cdot \\sqrt[3]{1+\\sqrt[3]{8}}$."
89+
},
90+
"gt_answer": "3"
91+
}
92+
```
93+
94+
### Code Data Format
95+
We support [Prime code dataset format](https://github.com/PRIME-RL/PRIME). Inputs and outputs in test cases should be two lists containing only strings and matching in the number of elements. Your prompt must properly instruct the LLM to generate code to read test cases from stdin and output results to stdout.
96+
```json
97+
{
98+
"messages": {
99+
"role": "user",
100+
"content": "Solve the following coding problem using the programming language python:\n\nMikhail walks on a Cartesian plane. He starts at the point $(0, 0)$, and in one move he can go to any of eight adjacent points. For example, ..."
101+
},
102+
"test_cases": {
103+
"inputs": [
104+
"3\n2 2 3\n4 3 7\n10 1 9\n"
105+
],
106+
"outputs": [
107+
"1\n6\n-1\n"
108+
]
109+
}
110+
}
111+
```
112+
113+
---
114+
115+
## ⚙️ Hyperparameters & Arguments
116+
117+
| Argument | Description | Example |
118+
| ---------------- | --------------------------------------- | ----------------- |
119+
| `--model` | Model path or identifier | `/path/to/model` |
120+
| `--dataset` | Path to training `.jsonl` | `/path/to/train_data.jsonl` |
121+
| `--eval-dataset` | JSON of task\:eval\_dataset\_path pairs | `{"eval_1":"/path/to/eval_1.jsonl"}` |
122+
| `--project` | Project name | `Project1` |
123+
| `--num-episodes` | Number of training episodes | `1` |
124+
125+
### Distributed Training
126+
127+
| Argument | Description | Example |
128+
| ----------------------------- | ------------------------------------- | ------- |
129+
| `--num-trainers` | Number of trainer processes | `4` |
130+
| `--num-inferencer` | Number of inferencer processes | `4` |
131+
| `--inference-batch-size` | Prompts per inference step | `8` |
132+
| `--inference-microbatch-size` | Per-GPU batch size for inference | `8` |
133+
| `--train-batch-size` | Prompts per trainer step per dp group | `8` |
134+
| `--train-minibatch-size` | Mini-batch size before forward pass | `8` |
135+
| `--train-microbatch-size` | Per-GPU batch size for training | `2` |
136+
137+
### Sampling
138+
139+
| Argument | Description | Example |
140+
| --------------------- | --------------------- | -------------- |
141+
| `--backend` | Generation backend, choose from `vllm` | `vllm` |
142+
| `--temperature` | Sampling temperature for generation | `1.0` |
143+
| `--top-k` | Top-K sampling parameter for generation | `None` |
144+
| `--top-p` | Top-P sampling parameter for generation | `1.0` |
145+
| `--system-prompt` | System prompt, optional, default to the default system prompt for each reward types. For more information, refer to the [**reward type**](#-constraints-and-notes) section | `Please reason step by step, and put your final answer within \\boxed{}.` |
146+
| `--max-new-tokens` | Max generation tokens | `3584` |
147+
| `--max-prompt-tokens` | Max prompt tokens | `512` |
148+
149+
### GRPO Specific
150+
151+
| Argument | Description | Example |
152+
| ----------------- | ---------------------------- | ------------------- |
153+
| `--algo` | Algorithm (`GRPO` or `DAPO`), for more customization refer to [GRPO Settings](#️-grpo-settings) | `GRPO` |
154+
| `--learning-rate` | Learning rate | `1e-6` |
155+
| `--kl-coeff` | KL penalty coefficient, if nonzero, a reference model will be used | `0.01` |
156+
| `--reward-type` | Reward signal type (choose from 'think_answer_tags', 'boxed', 'code') For more information, refer to the [**reward type**](#-constraints-and-notes) section | `think_answer_tags` |
157+
| `--eval-interval` | Evaluation interval in number of training steps (positive value to enable evaluation) | `10` |
158+
159+
### Logging and Checkpointing
160+
161+
| Argument | Description | Example |
162+
| -------------------- | ------------------------- | ------------ |
163+
| `--save-interval` | Training steps between checkpoints | `20` |
164+
| `--save-dir` | Checkpoint directory | `./model` |
165+
| `--eval-save-dir` | Evaluation save path | `./eval` |
166+
| `--rollout-save-dir` | Rollout logs directory | `./rollouts` |
167+
168+
### Miscellaneous
169+
170+
| Argument | Description | Example |
171+
| ------------------ | --------------------------------------- | ------- |
172+
| `--ray_dir` | Custom Ray temp dir of a running Ray cluster (optional) | `None` |
173+
| `--master_address` | Master address of a running Ray cluster | `None` |
174+
| `--master_port` | Master port for torch DDP | `29506` |
175+
176+
---
177+
178+
## ⚙️ GRPO Settings
179+
180+
In addition to the two default training settings provided—`GRPO` and `DAPO`—users can customize their training by changing the following hyperparameters in `grpo_config` in `rl_example.py`.
181+
182+
| Argument Name | Description | Default |
183+
| ----------------------------- | ---------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------- |
184+
| `filter_range` | Filters out rollout group if the success rate within that group is out of this range.| `[0.01, 0.99]` |
185+
| `dynamic_batching` | Enables dynamic batching as described in the [DAPO paper](https://arxiv.org/abs/2503.14476). | `True` |
186+
| `clip_eps_low` | epsilon_low in DAPO in equation in [DAPO paper](https://arxiv.org/abs/2503.14476) | `0.2` |
187+
| `clip_eps_high` | epsilon_high in DAPO equation in [DAPO paper](https://arxiv.org/abs/2503.14476) | `0.28` |
188+
| `skip_threshold` | If ratio is above this threshold, the sample is skipped to avoid instability. | `20.0` |
189+
| `loss_variation` | Type of loss variation. Supports `"token_level"` for token-wise policy gradient loss and `sample_level` for original GRPO loss. | `"token_level"` |
190+
| `soft_over_length_punishment` | Whether to use soft overlength penalty in [DAPO paper](https://arxiv.org/abs/2503.14476) or not. | `True` |
191+
| `cache_length` | `L_cache` parameter for soft overlength penalty in e.q. 13 in [DAPO paper](https://arxiv.org/abs/2503.14476) | `min(1024, int(args.max_new_tokens / 4))` |
192+
| `filter_truncated_response` | Mask out truncated responses in loss calculation. | `True` |
193+
194+
195+
196+
## 🔄 Constraints and Notes
197+
198+
* `num_inferencer + num_trainer == NUM_GPUs`
199+
* `num_inferencer % num_trainer == 0`
200+
* `(num_inferencer * inference_batch_size) % (num_trainer * train_batch_size) == 0`
201+
* `train_batch_size >= train_minibatch_size >= train_microbatch_size`
202+
* `inference_batch_size >= inference_microbatch_size`
203+
* Set microbatch sizes based on **VRAM capacity**
204+
* To use tensor parallelism on inferencer
205+
* set backend to `vllm`
206+
* change `tensor_parallel_size` in `inference_model_config` in rl_example.py
207+
* set `num_inferencer = NUM_INFERENCE_GPUs / tensor_parallel_size`
208+
* To set tensor parallelism / pipeline parallelism / zero stage
209+
* change corresponding settings in `plugin_config` in rl_example.py
210+
* Ensure rollout generation rate matches trainer consumption:
211+
212+
```
213+
num_inferencer * inference_batch_size % (
214+
num_trainer * train_batch_size /
215+
train_pipeline_parallelism_size /
216+
train_tensor_parallelism_size
217+
) == 0
218+
```
219+
* Model weights sync every:
220+
221+
```
222+
(num_inferencer * inference_batch_size) /
223+
(num_trainer * train_batch_size /
224+
train_pipeline_parallelism_size /
225+
train_tensor_parallelism_size)
226+
```
227+
* Reward Type
228+
229+
We currently support three reward types--- `think_answer_tags`, `boxed`, `code`, each varies in details such as how answer is extracted and the reward calculation process. Please select one from `think_answer_tags`, `boxed` for math problem solving and use `code` for code generation. The default system prompt for each reward type is as follows. Please make sure your system prompt provides information for the answer to be correctly extracted from model responses.
230+
231+
* think_answer_tags
232+
233+
Answer extraction: extract the content between the last `<answer>`, `</answer>` tags.
234+
235+
```
236+
You are a helpful assistant. The assistant first thinks about the reasoning process in the mind and then provides the user with the answer. The reasoning process and answer are enclosed within <think> </think> and<answer> </answer> tags, respectively, i.e., <think> reasoning process here </think><answer> answer here </answer>. Now the user asks you to solve a math problem that involves reasoning. After thinking, when you finally reach a conclusion, clearly output the final answer without explanation within the <answer> </answer> tags, i.e., <answer> 123 </answer>.\n\n
237+
```
238+
* boxed
239+
240+
Answer extraction: extract the last content marked by `\\boxed{}`
241+
```
242+
Please reason step by step, and put your final answer within \\boxed{}.
243+
```
244+
* code
245+
246+
Answer extraction: extract code inside ` ```python\n...``` `
247+
```
248+
You are a helpful assistant.
249+
```
250+
---
251+
252+
## 🧪 Example: single machine 8-GPU Zero2 Strategy
253+
254+
```bash
255+
python rl_example.py \
256+
--dataset /path/to/train_data.jsonl \
257+
--model /path/to/Qwen2.5-3B/ \
258+
-t 4 -i 4 \
259+
-b vllm \
260+
-ibs 2 -tbs 4 -tMbs 1 -tmbs 4 -imbs 1 \
261+
-rt boxed \
262+
-g 4 \
263+
-ibs 1 \
264+
-tbs 2 \
265+
-tMbs 1 \
266+
-tmbs 2 \
267+
-imbs 1 \
268+
-s "Please reason step by step, and put your final answer within \\boxed{}." \
269+
-tMbs 8 \
270+
-p GRPO-Train-Align-Debug \
271+
```
272+
273+
## 🧪 Example: multi-machine TP+PP Strategy
274+
275+
### Create ray cluster on multi-machine
276+
For example, now we have 4 nodes and their IPs are 10.0.0.3, 10.0.0.4, 10.0.0.5, 10.0.0.6.
277+
We use 10.0.0.3 as master node. First we start a ray cluster on 10.0.0.3:
278+
```bash
279+
ray start --head --node-ip-address=10.0.0.3
280+
```
281+
282+
Then, for each slave node (10.0.0.4/10.0.0.5/10.0.0.6), we add to the ray cluster by following code:
283+
```bash
284+
ray start --address='10.0.0.3:6379'
285+
```
286+
287+
Modify plugin_config in ./applications/ColossalChat/rl_example.py
288+
```python
289+
plugin_config={
290+
"tp_size": 4,
291+
"pp_size": 2,
292+
"microbatch_size": max(
293+
1, args.train_microbatch_size // 2
294+
), # microbatch size should be set to train_microbatch_size // pp_size
295+
"zero_stage": 1,
296+
"max_norm": 1.0,
297+
}, # for pp, tp
298+
```
299+
300+
```bash
301+
# Hint1: replace /models/Qwen/Qwen2.5-7B to your model path
302+
# replace /datasets/train-alignment.jsonl to your dataset path
303+
python rl_example.py
304+
-m /path/to/Qwen2.5-Math-7B/ \
305+
-d /path/to/train_data.jsonl \
306+
--master_address '10.0.0.3'
307+
-t 16 \
308+
-i 16 \
309+
-p GRPO-Train-Align-Debug \
310+
-g 2 \
311+
-ibs 1 \
312+
-tbs 2 \
313+
-tMbs 1 \
314+
-tmbs 2 \
315+
-imbs 1 \
316+
-b vllm \
317+
-e 2 \
318+
-rt boxed \
319+
-s "Please reason step by step, and put your final answer within \\boxed{}."
320+
```
321+
322+
## Acknowledgement
323+
Colossal-RL is a distributed version of ColossalChat and inspired by a few awesome open-source projects. We would like to express our gratitude to the following awesome open-source projects and algorithms: GRPO, DAPO, TRL, Verl, OpenRLHF, StreamRL, Qwen, Logic-RL.

0 commit comments

Comments
 (0)