yuccaaa commited on
Commit
dcdf780
·
verified ·
1 Parent(s): 41c6b7d

Upload ms-swift/docs/source_en/Instruction/GRPO.md with huggingface_hub

Browse files
ms-swift/docs/source_en/Instruction/GRPO.md ADDED
@@ -0,0 +1,366 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # GRPO
2
+ Paper Links
3
+
4
+ [DeepSeekMath: Pushing the Limits of Mathematical Reasoning in Open Language Models](https://arxiv.org/abs/2402.03300)
5
+ [DeepSeek-R1: Incentivizing Reasoning Capability in LLMs via Reinforcement Learning](https://arxiv.org/abs/2501.12948)
6
+
7
+ environments
8
+
9
+ ```bash
10
+ pip install math_verify # reward function
11
+ pip install -U trl
12
+ ```
13
+
14
+ **Note**: It is normal for the loss to approach zero during training. Refer to this [issue](https://github.com/huggingface/open-r1/issues/239#issuecomment-2646297851) for more details.
15
+
16
+ ## Cluster Support
17
+
18
+ ![](../../resources/grpo.png)
19
+
20
+ In SWIFT's GRPO training, the training model preferentially uses the front portion of the available GPUs, while the rollout process utilizes the rear portion of the available GPUs. This means:
21
+
22
+ - **If both `NPROC_PER_NODE` and `num_infer_workers` in the command are equal to the number of available GPUs**, training and inference are assigned to the same GPUs. In this case, you need to configure `sleep_level`.
23
+ - **If the sum of `NPROC_PER_NODE` and `num_infer_workers` equals the total number of available GPUs**, training will use the front GPUs and rollout will use the rear GPUs. In this scenario, you can configure `async_generate`.
24
+
25
+ > Note: async_generate uses the policy model and responses of current_step-1, so in fact the `clip` method will be ignored
26
+ > If you encountered unstable in training, turn off this argument.
27
+ > In our experiments, unstable cases is not frequently occurring when async_generate is true.
28
+
29
+ ## Reward Functions
30
+ ### Custom Reward Functions
31
+ A reward function takes the text `completions` generated by a model and other columns from the dataset as parameters(kwargs), and scores the model's generated text. Below is an example that demonstrates how to implement a simple length-based reward function. This function will give a reward signal of 1.0 if the length of the generated text exceeds 1024; otherwise, the reward signal will be 0.0.
32
+
33
+ ```python
34
+ from swift.plugin import ORM, orms
35
+
36
+ class DummyLengthRewardFunction(ORM):
37
+ def __call__(self, completions, **kwargs):
38
+ return [1.0 if len(completion) > 1024 else 0.0 for completion in completions]
39
+
40
+ orms['dummy']= DummyLengthRewardFunction
41
+ ```
42
+ You can add this reward function in `swift/examples/train/grpo/plugin/plugin.py` and register it using the parameter `--external_plugins examples/train/grpo/plugin/plugin.py`, then specify it using the reward_funcs parameter.
43
+
44
+ For an example of how to execute the script, refer to [here](https://github.com/modelscope/ms-swift/tree/main/examples/train/grpo/plugin/run_external_rm.sh).
45
+
46
+
47
+
48
+ ### Built-in Reward Functions
49
+ Swift provides five rule-based reward functions built into the system(The code can be found in swift/plugin/orm.py.)
50
+
51
+
52
+ | Reward Function | Paper |
53
+ |----------------|----------------------------------------------------------------------------|
54
+ | accuracy | [DeepSeek-R1: Incentivizing Reasoning Capability in LLMs via RL](https://arxiv.org/abs/2501.12948) |
55
+ | format | Same as above |
56
+ | cosine | [Demystifying Long Chain-of-Thought Reasoning in LLMs](https://arxiv.org/abs/2502.03373) |
57
+ | repetition | Same as above |
58
+ | soft_overlong | [Decoupled Clip and Dynamic sAmpling Policy Optimization (DAPO)](https://arxiv.org/abs/2503.14476) |
59
+
60
+ #### 1. **accuracy**
61
+
62
+ This function compares the model's generated result with the solution column in the dataset to calculate an accuracy score. If the generated result matches the standard answer, the score is 1.0; otherwise, it is 0.0.
63
+
64
+ Note: This reward function uses the math_verify library to parse the generated results and the answers in the solution, and it may only be applicable to specific mathematical datasets.
65
+
66
+ #### 2. **format**
67
+
68
+ The paper uses the following system prompt to enforce a fixed format for model responses:
69
+ ```
70
+ A conversation between User and Assistant. The user asks a question, and the Assistant solves it. 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>
71
+ ```
72
+ This function checks whether the model generates text in the format `<think>think content</think><answer>answer content</answer>`. If the generated text adheres to the format requirements, the score is 1.0; otherwise, it is 0.0.
73
+
74
+ #### 3. **cosine**
75
+
76
+ The paper found that training with only the accuracy reward function could lead to overly long generated sequences, affecting training performance. The cosine reward function optimizes the training process by controlling the length of the generated sequences:
77
+
78
+ - For text that generates the correct answer, the reward value decreases as the length increases, encouraging concise responses.
79
+ - For text that generates incorrect answers, the reward value increases as the length increases, encouraging deeper reasoning.
80
+
81
+ A cosine function is used to smoothly adjust the reward value, ensuring that the changes are within a reasonable range. The parameters for the cosine function include the length of the generated text, the maximum length limit, and the minimum and maximum reward values.
82
+
83
+ Parameters:
84
+ - cosine_min_len_value_wrong (default: -0.5): Reward value corresponding to the minimum length when the answer is incorrect.
85
+ - cosine_max_len_value_wrong (default: 0.0): Reward value corresponding to the maximum length when the answer is incorrect.
86
+ - cosine_min_len_value_correct (default: 1.0): Reward value corresponding to the minimum length when the answer is correct.
87
+ - cosine_max_len_value_correct (default: 0.5): Reward value corresponding to the maximum length when the answer is correct.
88
+ - cosine_max_len (default value equal to the model's maximum generation capacity): Maximum length limit for generated text.
89
+
90
+ #### 4. **repetition**
91
+
92
+ This function penalizes repetition in generated text by detecting repeated n-gram patterns and assigning penalties based on the level of repetition.
93
+
94
+ The function splits the generated text into words and extracts n-grams of a specified size (default is 3-gram). It calculates the repetition ratio based on the proportion of unique n-grams to the total number of n-grams. If the proportion of repeated n-grams is high, a significant negative reward (penalty) is applied. The penalty value is computed based on the repetition ratio and a maximum penalty value (default: -1.0).
95
+
96
+ Parameters:
97
+ - repetition_n_grams (default: 3): Size of the n-gram used to detect repetition.
98
+ - repetition_max_penalty (default: -1.0): Maximum penalty value, which controls the intensity of the penalty.
99
+
100
+ #### 5. **soft overlong punishment**
101
+ Define the length penalty interval. Within this interval, a linear penalty of [-1, 0] is applied.
102
+
103
+ Parameters:
104
+ - soft_max_length: L_max in the paper, the maximum generation length of the model, default is equal to max_completion_length.
105
+ - soft_cache_length: L_cache in the paper, controls the length penalty interval, which is defined as [soft_max_length - soft_cache_length, soft_max_length].
106
+
107
+ Original text from the paper:
108
+ > a length-aware penalty mechanism designed to shape the reward for truncated samples. Specifically, when the response length exceeds the predefined maximum value, we define a punishment interval. Within this interval, the longer the response, the greater the punishment it receives. This penalty is added to the original rule-based correctness reward, thereby signaling to the model to avoid excessively long responses.
109
+
110
+ #### 6. **Reward Models**
111
+
112
+ In addition to rule-based reward functions, this framework also supports using reward models as reward functions. When using a reward model, you need to specify the `reward_model` parameter, similar to the `model` parameter, which is used to specify the path or name of the reward model. Note that either `reward_model` or `reward_funcs` needs to be specified.
113
+
114
+
115
+ ## Arguments and Execution Script
116
+ Arguments
117
+
118
+ - num_generations: The number of samples for each prompt, referred to as the G value in the paper, needs to be divisible by per_device_eval_batch_size * - nproc_per_node.
119
+ - max_completion_length: The maximum length for sampling generation, default is 512.
120
+ - ds3_gather_for_generation: This parameter applies to DeepSpeed ZeRO-3. If enabled, the policy model weights are gathered for generation, improving generation speed. However, disabling this option allows training models that exceed the VRAM capacity of a single GPU, albeit at the cost of slower generation. Disabling this option is not compatible with vLLM generation. The default is True.
121
+ - reward_funcs: Reward functions to score the results generated by the model. Includes built-in accuracy, format , cosine and repetition rule-based functions, detailed in the swift/plugin/orm.py file.
122
+ - reward_weights: Weights for each reward function. Must match the number of reward functions. If `None`, all rewards are weighted equally with weight `1.0`.
123
+ - Note: If `--reward_model` is included in GRPO training, it is added to the end of the reward functions.
124
+ - log_completions: Whether to log the model-generated content during training, to be used in conjunction with `--report_to wandb`, default is False.
125
+ - Note: If `--report_to wandb` is not set, a `completions.jsonl` will be created in the checkpoint to store the generated content.
126
+ - use_vllm: Whether to use vLLM as the back-end for sampling generation; default is False, using it is recommended to speed up training.
127
+ - vllm_device: Device for deploying vLLM, default is auto, meaning the first unused GPU. Use cuda:x to specify a particular card.
128
+ - vllm_gpu_memory_utilization: vLLM pass-through parameter.
129
+ - vllm_max_model_len: vLLM pass-through parameter.
130
+ - reward_model: Same as the model, using a reward model as a reward function. At least one of reward_funcs and reward_model needs to be specified.
131
+ - num_iterations: number of iterations per batch. Default is 1.
132
+ - epsilon: epsilon value for clipping. Default is 0.2.
133
+ - epsilon_high: Upper clip coefficient, default is None. When set, it forms a clipping range of [epsilon, epsilon_high] together with epsilon.
134
+ - async_generate: Use async rollout to improve train speed,default `false`.
135
+ - sleep_level: vllm specific,when both actor and rollout in the same GPU,you can make vllm sleep when model is training.
136
+ - move_model_batches: When moving model parameters to fast inference frameworks such as vLLM/LMDeploy, determines how many batches to divide the layers into. The default is `None`, which means the entire model is not split. Otherwise, the model is split into `move_model_batches + 1` (non-layer parameters) + `1` (multi-modal component parameters) batches.
137
+ - offload_optimizer: Whether to offload optimizer parameters during inference with vLLM/LMDeploy. The default is `False`.
138
+ - offload_model: Whether to offload the model itself during inference with vLLM/LMDeploy. The default is `False`.
139
+ - Note: If this parameter is set to True and the grad_norm remains zero during training, please install vllm==0.7.3.
140
+ - gc_collect_after_offload: Whether to perform garbage collection (both Python GC and GPU GC) after offloading. The default is `False`.
141
+ - multi_turn_func: The multi turn GRPO plugin name. Add your multi-turn implementation in plugin/multi_turn.py
142
+ - mini_batch_size: Used to further split the batch size on each device (per_device_batch) into smaller sub-batches. To ensure the split is valid, per_device_train_batch_size needs be divisible by mini_batch_size
143
+ - dynamic_sample: Exclude data within the group where the reward standard deviation is 0, and additionally sample new data. Default is False.
144
+ - max_resample_times: Under the dynamic_sample setting, limit the number of resampling attempts to a maximum of 3. Default is 3 times.
145
+ - overlong_filter: Skip overlong truncated samples, which will not be included in loss calculation. Default is False.
146
+ The hyperparameters for the reward function can be found in the [Built-in Reward Functions section](#built-in-reward-functions).
147
+
148
+ You can use vLLM and LMDeploy as sampling backends to accelerate training.
149
+
150
+ Multi-GPU vLLM
151
+ ```bash
152
+ # async mode
153
+ # The requirement is that num_infer_workers (deployment) + NPROC_PER_NODE (training) = device_count.
154
+ CUDA_VISIBLE_DEVICES=0,1,2,3,4,5,6,7 \
155
+ NPROC_PER_NODE=7 \
156
+ swift rlhf \
157
+ --rlhf_type grpo \
158
+ --model Qwen/Qwen2.5-7B \
159
+ --reward_funcs accuracy format cosine repetition\
160
+ --use_vllm true \
161
+ --vllm_device auto \
162
+ --vllm_gpu_memory_utilization 0.7 \
163
+ --vllm_max_model_len 8192 \
164
+ --num_infer_workers 1 \
165
+ --train_type full \
166
+ --torch_dtype bfloat16 \
167
+ --dataset 'AI-MO/NuminaMath-TIR#5000' \
168
+ --max_completion_length 2048 \
169
+ --num_train_epochs 1 \
170
+ --per_device_train_batch_size 1 \
171
+ --per_device_eval_batch_size 1 \
172
+ --learning_rate 1e-6 \
173
+ --gradient_accumulation_steps 2 \
174
+ --eval_steps 200 \
175
+ --save_steps 200 \
176
+ --save_total_limit 2 \
177
+ --logging_steps 5 \
178
+ --max_length 4096 \
179
+ --output_dir output \
180
+ --warmup_ratio 0.05 \
181
+ --dataloader_num_workers 4 \
182
+ --dataset_num_proc 4 \
183
+ --num_generations 7 \
184
+ --temperature 0.9 \
185
+ --system 'examples/train/grpo/prompt.txt' \
186
+ --deepspeed zero2 \
187
+ --log_completions true
188
+
189
+ # colocate mode
190
+ # The requirement is that num_infer_workers (deployment) = NPROC_PER_NODE (training) = device_count.
191
+ CUDA_VISIBLE_DEVICES=0,1,2,3,4,5,6,7 \
192
+ NPROC_PER_NODE=8 \
193
+ swift rlhf \
194
+ --rlhf_type grpo \
195
+ --model Qwen/Qwen2.5-1.5B \
196
+ --reward_funcs accuracy format \
197
+ --use_vllm true \
198
+ --vllm_device auto \
199
+ --vllm_gpu_memory_utilization 0.7 \
200
+ --vllm_max_model_len 8192 \
201
+ --num_infer_workers 8 \
202
+ --train_type full \
203
+ --torch_dtype bfloat16 \
204
+ --dataset 'AI-MO/NuminaMath-TIR#5000' \
205
+ --max_completion_length 2048 \
206
+ --num_train_epochs 1 \
207
+ --per_device_train_batch_size 1 \
208
+ --per_device_eval_batch_size 1 \
209
+ --learning_rate 1e-6 \
210
+ --gradient_accumulation_steps 2 \
211
+ --eval_steps 200 \
212
+ --save_steps 200 \
213
+ --save_total_limit 2 \
214
+ --logging_steps 5 \
215
+ --max_length 4096 \
216
+ --output_dir output \
217
+ --warmup_ratio 0.05 \
218
+ --dataloader_num_workers 4 \
219
+ --dataset_num_proc 4 \
220
+ --num_generations 8 \
221
+ --temperature 0.9 \
222
+ --system 'examples/train/grpo/prompt.txt' \
223
+ --deepspeed zero2 \
224
+ --log_completions true \
225
+ --sleep_level 1 \
226
+ --offload_model true \
227
+ --offload_optimizer true \
228
+ --gc_collect_after_offload true \
229
+ --log_completions true \
230
+ ```
231
+
232
+ Single-GPU
233
+ ```bash
234
+ # PT backend
235
+ CUDA_VISIBLE_DEVICES=0 \
236
+ swift rlhf \
237
+ --rlhf_type grpo \
238
+ --model Qwen/Qwen2.5-7B \
239
+ --reward_funcs accuracy format cosine repetition\
240
+ --train_type lora \
241
+ --lora_rank 8 \
242
+ --lora_alpha 32 \
243
+ --target_modules all-linear \
244
+ --torch_dtype bfloat16 \
245
+ --dataset 'AI-MO/NuminaMath-TIR#1000' \
246
+ --max_completion_length 1024 \
247
+ --num_train_epochs 1 \
248
+ --per_device_train_batch_size 4 \
249
+ --per_device_eval_batch_size 4 \
250
+ --learning_rate 1e-5 \
251
+ --gradient_accumulation_steps 1 \
252
+ --eval_steps 100 \
253
+ --save_steps 100 \
254
+ --save_total_limit 2 \
255
+ --logging_steps 5 \
256
+ --max_length 2048 \
257
+ --output_dir output \
258
+ --warmup_ratio 0.05 \
259
+ --dataloader_num_workers 4 \
260
+ --dataset_num_proc 4 \
261
+ --num_generations 4 \
262
+ --temperature 0.9 \
263
+ --system 'examples/train/grpo/prompt.txt' \
264
+ --log_completions true
265
+
266
+ # vLLM backend
267
+ CUDA_VISIBLE_DEVICES=0 \
268
+ swift rlhf \
269
+ --rlhf_type grpo \
270
+ --model Qwen/Qwen2.5-7B \
271
+ --vllm_gpu_memory_utilization 0.5 \
272
+ --use_vllm true \
273
+ --sleep_level 1 \
274
+ --offload_model true \
275
+ --offload_optimizer true \
276
+ --gc_collect_after_offload true \
277
+ --reward_funcs accuracy format \
278
+ --train_type lora \
279
+ --lora_rank 8 \
280
+ --lora_alpha 32 \
281
+ --target_modules all-linear \
282
+ --torch_dtype bfloat16 \
283
+ --dataset 'AI-MO/NuminaMath-TIR#1000' \
284
+ --max_completion_length 1024 \
285
+ --num_train_epochs 1 \
286
+ --per_device_train_batch_size 4 \
287
+ --per_device_eval_batch_size 4 \
288
+ --learning_rate 1e-5 \
289
+ --gradient_accumulation_steps 1 \
290
+ --eval_steps 100 \
291
+ --save_steps 100 \
292
+ --save_total_limit 2 \
293
+ --logging_steps 5 \
294
+ --max_length 2048 \
295
+ --output_dir output \
296
+ --warmup_ratio 0.05 \
297
+ --dataloader_num_workers 4 \
298
+ --dataset_num_proc 4 \
299
+ --num_generations 4 \
300
+ --temperature 0.9 \
301
+ --system 'examples/train/grpo/prompt.txt' \
302
+ --log_completions true
303
+ ```
304
+
305
+ ## DAPO
306
+ Decoupled Clip and Dynamic Sampling Policy Optimization (DAPO) introduces several tricks based on GRPO, which are:
307
+ - Clip Higher
308
+ - Dynamic Sampling
309
+ - Overlong Filtering
310
+ - Token level Loss
311
+ - Soft Overlong Punishment
312
+
313
+ Among these, Token level Loss is implemented by default and does not require additional settings. For the other tricks, we can achieve the desired setup based on GRPOTrainer by configuring the following parameters.
314
+
315
+
316
+ | Parameter | Type | Value |
317
+ |----------------------|-----------|-------------|
318
+ | `--epsilon_high` | `float` | `0.28` |
319
+ | `--dynamic_sample` | `bool` | `true` |
320
+ | `--overlong_filter` | `bool` | `true` |
321
+ | `--reward_funcs` | `str` | `soft_overlong`|
322
+ | `--max_resample_times` | `int` | `3` |
323
+
324
+ Reference training script (for 8-card colocate mode):
325
+
326
+ ```bash
327
+ CUDA_VISIBLE_DEVICES=0,1,2,3,4,5,6,7 \
328
+ NPROC_PER_NODE=8 \
329
+ WANDB_API_KEY=xxx \
330
+ swift rlhf \
331
+ --rlhf_type grpo \
332
+ --model Qwen/Qwen2.5-1.5B \
333
+ --reward_funcs accuracy soft_overlong \
334
+ --max_completion_length 4096 \
335
+ --soft_cache_length 819 \
336
+ --epsilon 0.2 \
337
+ --epsilon_high 0.28 \
338
+ --dynamic_sample true \
339
+ --overlong_filter true \
340
+ --max_resample_times 3 \
341
+ --use_vllm true \
342
+ --vllm_gpu_memory_utilization 0.6 \
343
+ --num_infer_workers 8 \
344
+ --train_type full \
345
+ --torch_dtype bfloat16 \
346
+ --dataset AI-MO/NuminaMath-TIR#5000 \
347
+ --num_train_epochs 1 \
348
+ --per_device_train_batch_size 4 \
349
+ --per_device_eval_batch_size 4 \
350
+ --learning_rate 1e-6 \
351
+ --eval_steps 1000 \
352
+ --save_steps 1000 \
353
+ --save_total_limit 2 \
354
+ --logging_steps 5 \
355
+ --warmup_ratio 0.05 \
356
+ --dataloader_num_workers 4 \
357
+ --dataset_num_proc 4 \
358
+ --num_generations 8 \
359
+ --temperature 1.0 \
360
+ --top_p 1.0 \
361
+ --deepspeed zero2 \
362
+ --log_completions true \
363
+ --num_iterations 1 \
364
+ --report_to tensorboard wandb \
365
+ --beta 0.0 \
366
+ ```