forked from THUDM/slime
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy patharguments.py
More file actions
1784 lines (1659 loc) · 76.1 KB
/
arguments.py
File metadata and controls
1784 lines (1659 loc) · 76.1 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import argparse
import json
import logging
import os
from typing import Any
import yaml
from sglang_router.launch_router import RouterArgs
from slime.backends.sglang_utils.arguments import sglang_parse_args
from slime.backends.sglang_utils.arguments import validate_args as sglang_validate_args
from slime.utils.eval_config import EvalDatasetConfig, build_eval_dataset_configs, ensure_dataset_list
from slime.utils.logging_utils import configure_logger
logger = logging.getLogger(__name__)
def reset_arg(parser, name, **kwargs):
"""
Reset the default value of a Megatron argument.
:param parser: The argument parser.
:param name: The name of the argument to reset.
:param default: The new default value.
"""
for action in parser._actions:
if name in action.option_strings:
if "default" in kwargs:
action.default = kwargs["default"]
break
else:
parser.add_argument(name, **kwargs)
def get_slime_extra_args_provider(add_custom_arguments=None):
def add_slime_arguments(parser):
# Ray
def add_cluster_arguments(parser):
parser.add_argument("--actor-num-nodes", type=int, default=1, help="Number of nodes for training actor")
parser.add_argument(
"--actor-num-gpus-per-node", type=int, default=8, help="Number of gpus per node for training actor"
)
parser.add_argument(
"--critic-num-nodes", type=int, default=None, help="Number of nodes for training actor"
)
parser.add_argument(
"--critic-num-gpus-per-node", type=int, default=None, help="Number of gpus per node for training actor"
)
parser.add_argument(
"--rollout-num-gpus",
type=int,
default=None,
help=(
"Number of GPUs for inference. Note that when using --colocate, "
"i.e. the training and the inference engines are on the same gpus, this param will be ignored and will be set as "
"actor_num_gpus_per_node * actor_num_nodes."
),
)
parser.add_argument(
"--rollout-num-gpus-per-engine",
type=int,
default=1,
help="Number of GPUs per inference engine, just like the tp_size in sglang.",
)
parser.add_argument(
"--num-gpus-per-node",
type=int,
default=8,
help=(
"Number of gpus per node for rollout."
"Notice: If you are going to use less than 8 gpus per node under colocate mode, you should set this number."
),
)
parser.add_argument(
"--colocate",
action="store_true",
default=False,
help=(
"Whether to colocate the inference engines and the actor. "
"Turning this on will also set --offload to true."
),
)
parser.add_argument(
"--offload",
action="store_true",
default=False,
help=("Equivalent to --offload-train + --offload-rollout. "),
)
parser.add_argument(
"--offload-train",
action=argparse.BooleanOptionalAction,
help=(
"Whether to offload the training actor to CPU during training. "
"This will always be true when --colocate is set."
),
)
parser.add_argument(
"--offload-rollout",
action=argparse.BooleanOptionalAction,
help=(
"Whether to offload the rollout generator to CPU during training. "
"This will always be true when --colocate is set."
),
)
reset_arg(parser, "--distributed-backend", type=str, default="nccl")
reset_arg(parser, "--distributed-timeout-minutes", type=int, default=10)
return parser
def add_train_arguments(parser):
# --train-backend is parsed early in _pre_parse_mode() and merged later.
parser.add_argument(
"--qkv-format",
type=str,
choices=["thd", "bshd"],
default="thd",
help="The qkv layout for Megatron backend.",
)
parser.add_argument(
"--true-on-policy-mode",
action="store_true",
default=False,
help="Whether to enable true-on-policy mode.",
)
parser.add_argument(
"--train-env-vars",
type=json.loads,
default="{}",
help="Extra environment variables for training process, e.g. PyTorch memory management ones.",
)
parser.add_argument(
"--train-memory-margin-bytes",
type=int,
default=1024**3,
help="Add margin for train memory allocation. By default we will reserve 1GB as margin.",
)
parser.add_argument(
"--disable-weights-backuper",
action="store_false",
dest="enable_weights_backuper",
help="Whether to disable weights backuper to save host memory.",
)
parser.add_argument(
"--megatron-to-hf-mode",
choices=["raw", "bridge"],
default="raw",
help="The method to convert megatron weights to hugging face weights for SGLang.",
)
parser.add_argument(
"--custom-model-provider-path",
type=str,
default=None,
help=(
"Path to a custom model provider function. "
"If set, we will use this function instead of the default model provider. "
"The function should have the signature "
"`def custom_model_provider(pre_process: bool, post_process: bool, vp_stage: int | None = None) -> GPTModel`. "
"Example: 'my_module.my_model_provider'."
),
)
parser.add_argument(
"--recompute-loss-function",
action="store_true",
help="Whether to disable recompute loss function to save memory during training.",
)
parser.add_argument(
"--log-probs-chunk-size", type=int, default=-1, help="Chunk size to compute log probs to save memory"
)
parser.add_argument(
"--only-train-params-name-list",
type=str,
nargs="*",
default=None,
help="""List of regex patterns of parameter names to TRAIN. All other parameters will be FROZEN.
Supports Python regex syntax (re.search).
Examples:
1. Train ONLY MoE experts:
--only-train-params-name-list experts
2. Train ONLY Indexer parameters:
--only-train-params-name-list self_attention.wq_b self_attention.wk self_attention.k_norm self_attention.weights_proj
3. Train ONLY Layer 20 to 23:
--only-train-params-name-list layers\.2[0-3]\.
""",
)
parser.add_argument(
"--freeze-params-name-list",
type=str,
nargs="*",
default=None,
help="""List of regex patterns of parameter names to FREEZE. Other parameters will remain trainable.
Supports Python regex syntax (re.search).
Examples:
1. Freeze Embeddings and Output Layer (common for fine-tuning):
--freeze-params-name-list embedding output_layer
2. Freeze Indexer parameters:
--freeze-params-name-list self_attention.wq_b self_attention.wk self_attention.k_norm self_attention.weights_proj
3. Freeze specific projection layers (e.g., all Gate/Up projections):
--freeze-params-name-list linear_fc1
""",
)
parser.add_argument(
"--allgather-cp",
action="store_true",
default=False,
)
return parser
# rollout
def add_rollout_arguments(parser):
parser.add_argument(
"--hf-checkpoint",
type=str,
default=None,
help=(
"The huggingface checkpoint of the trained model. "
"This is used to initialize sglang and also provide the tokenizer. "
"Note that, we will always update the parameters in sglang with that of megatron before training, "
"so you only need to provide a huggingface checkpoint that has the same architecture as the model you want to train. "
"It doesn't necessary need to contain the most up-to-date parameters."
),
)
parser.add_argument(
"--model-name",
type=str,
default=None,
help=(
"The name of the model, this is used to convert the megatron weights into huggingface format. "
"If not set, we will use `type(AutoConfig.from_pretrained(args.hf_checkpoint)).__name__.lower()` as model_name. "
"Also, sometimes this will help alleviate the bug that transformers cannot find certain model."
),
)
parser.add_argument(
"--rollout-function-path",
type=str,
default="slime.rollout.sglang_rollout.generate_rollout",
help=(
"Path to the rollout generation function."
"You should use this model to create your own custom rollout function, "
"and then set this to the path of your custom rollout function. "
"The signature of the function should be "
"`def generate_rollout(args, rollout_id, data_source, evaluation=False) -> RolloutFnTrainOutput | RolloutFnEvalOutput`"
"and within the output sample, you should at least set `tokens`, `response_length`, `reward` "
"and `status`."
),
)
parser.add_argument(
"--rollout-temperature",
type=float,
default=1.0,
help="the temperature for the inference engine during rollout.",
)
parser.add_argument(
"--rollout-top-p", type=float, default=1.0, help="the top-p for the inference engine during rollout."
)
parser.add_argument(
"--rollout-top-k", type=int, default=-1, help="the top-k for the inference engine during rollout."
)
parser.add_argument(
"--rollout-max-context-len",
type=int,
default=None,
help=(
"The maximum context size for the inference engine during rollout."
"It should no exceed the `max_position_embeddinds` in Huggingface model's `config.json`"
),
)
parser.add_argument(
"--rollout-max-prompt-len",
type=int,
default=None,
help=(
"The maximum length of the prompt for the inference engine during rollout. "
"If set, we will filter out the long prompts during initialization of the global dataset. "
"This is not recommended if the dataset is large."
),
)
parser.add_argument(
"--rollout-max-response-len",
type=int,
default=None,
help=(
"The maximum length of the response for the inference engine during rollout. "
"It is basically `max_tokens` in sglang."
),
)
parser.add_argument(
"--rollout-skip-special-tokens",
action="store_true",
default=False,
help=(
"Whether to skip special tokens in the response during rollout. "
"This is useful when you want to use the response as a prompt for the next rollout."
),
)
parser.add_argument(
"--rollout-stop",
type=str,
nargs="+",
default=None,
help=(
"The stop words for the inference engine during rollout. "
"It can be a list of strings or a single string. "
"It may be hard to pass special tokens in command line, in that case rollout_stop_token_ids can be used."
),
)
parser.add_argument(
"--rollout-stop-token-ids",
type=int,
nargs="+",
default=None,
help=(
"The stop token ids for the inference engine during rollout. "
"It can be a list of integers or a single integer."
),
)
parser.add_argument(
"--rollout-shuffle",
action="store_true",
default=False,
help=("Whether to shuffle the prompts during rollout."),
)
parser.add_argument(
"--rollout-seed",
type=int,
default=42,
help=(
"The seed for the random number generator during rollout. "
"This is used to shuffle the prompts and also for the random sampling of the prompts."
),
)
# sampling
parser.add_argument(
"--over-sampling-batch-size",
type=int,
default=None,
help=(
"This defines the granularity of the sampling batch in the rollout function. "
"When the number of available samples falls below the target, a sampling "
"operation of size over_sampling_batch_size will be triggered."
"Regardless of whether partial rollout is used or filters are applied, "
"the sampling granularity is always determined by this value. "
"If this value is None, rollout_batch_size will be used as the default over_sampling_batch_size."
),
)
parser.add_argument(
"--dynamic-sampling-filter-path",
type=str,
default=None,
help=(
"This is the filter function for dynamic sampling. "
"It should be able to judge whether the result of a prompt should be selected or not."
"We will do dynamic filter for sampling as in DAPO. e.g. not all correct or all wrong samples."
"You could use `slime.rollout.filter_hub.dynamic_sampling_filters.check_reward_nonzero_std` as an example."
),
)
# partial rollout
parser.add_argument(
"--partial-rollout",
action="store_true",
default=False,
help=(
"Whether to use partial rollout. "
"If set, the unfinished samples during dynamic sampling will be recycled back to data buffer. "
"This is useful for long responses."
),
)
parser.add_argument(
"--mask-offpolicy-in-partial-rollout",
action="store_true",
default=False,
help=(
"Whether to mask previous generation in partial rollout. "
"If set, only on-policy generated tokens will be used in training"
),
)
parser.add_argument(
"--custom-generate-function-path",
type=str,
default=None,
help=(
"Only substitue the `def generate(args, sample, sampling_params)` function within the example rollout function. "
"This should be useful if you need to implement some special rollout logic, e.g. multi-turn, function calling."
),
)
parser.add_argument(
"--custom-rollout-log-function-path",
type=str,
default=None,
help=(
"The custom function for logging rollout data. The signature of the functions is: "
"def log_rollout_data(rollout_id, args, samples, rollout_extra_metrics, rollout_time) -> bool. "
"The return value indicates whether to skip the default logging. "
),
)
parser.add_argument(
"--custom-eval-rollout-log-function-path",
type=str,
default=None,
help=(
"The custom function for logging eval rollout data. "
"def log_eval_rollout_data(rollout_id, args, data, extra_metrics) -> bool. "
"The return value indicates whether to skip the default logging. "
),
)
parser.add_argument(
"--buffer-filter-path",
type=str,
default=None,
help=(
"Path to the buffer filter function. "
"It should be able to select the samples in the buffer. "
"The function should take list[list[Sample]] and return list[list[Sample]]."
),
)
# update weight
parser.add_argument(
"--update-weight-buffer-size",
type=int,
default=512 * 1024**2,
help=(
"buffer size for update weight, in bytes. "
"This is used for updating weights by chunk and should be useful for MoE models."
),
)
parser.add_argument(
"--update-weights-interval",
type=int,
default=1,
help="Interval for updating the weights",
)
parser.add_argument(
"--keep-old-actor",
action="store_true",
help="Whether to keep the rollout model on training process",
)
parser.add_argument(
"--rollout-data-postprocess-path",
type=str,
default=None,
help=(
"The called after we have all the rollout data including log_probs. "
"It may be helpful for updating loss mask."
),
)
parser.add_argument(
"--rollout-external",
action="store_true",
default=False,
help="Use external SGLang instances instead of launching them inside the framework.",
)
parser.add_argument(
"--rollout-external-engine-addrs",
type=str,
default=None,
nargs="+",
help="Address and ports of the external engines.",
)
return parser
def add_fault_tolerance_arguments(parser):
parser.add_argument(
"--use-fault-tolerance",
action="store_true",
default=False,
help="Whether to enable the fault tolerance function during rollout.",
)
parser.add_argument(
"--rollout-health-check-interval",
type=float,
default=30.0,
help="Interval in seconds between rollout engine /health_generate checks during generate/eval.",
)
parser.add_argument(
"--rollout-health-check-timeout",
type=float,
default=30.0,
help="Timeout in seconds to wait for a rollout engine /health_generate response before killing it.",
)
parser.add_argument(
"--rollout-health-check-first-wait",
type=float,
default=0,
help="Initial grace period (in seconds) before starting health checks. This allows time for model compilation and initialization. Increase this value significantly when using deepgemm.",
)
return parser
# data
def add_data_arguments(parser):
# dataset
# TODO: maybe add an num_epoch and calculate the num_rollout from buffer
parser.add_argument(
"--num-rollout",
type=int,
default=None,
help="Number of rollout steps. If not set, we will calculate the number of rollout steps from the dataset size.",
)
parser.add_argument(
"--num-epoch",
type=int,
default=None,
help=(
"Number of epochs for the training. "
"This is used to calculate the number of rollout steps from the dataset size. "
"If set, we will calculate the number of rollout steps as `num_rollout = num_epoch * dataset_size // rollout_batch_size`."
"If both `--num-epoch` and `--num-rollout` are set, `--num-epoch` will be ignored."
),
)
parser.add_argument(
"--disable-rollout-global-dataset",
action="store_false",
dest="rollout_global_dataset",
help=(
"Whether to use a global dataset for rollout. "
"If set, the rollout will use the `--prompt-data` as the prompt dataset, "
"and the prompts for rollout will be sampled from the dataset. "
"If not set, you need to manage the data by your self."
),
)
parser.add_argument(
"--data-source-path",
type=str,
default="slime.rollout.data_source.RolloutDataSourceWithBuffer",
help="The data source class for rollout data.",
)
parser.add_argument(
"--prompt-data",
type=str,
default=None,
help=(
"The path to the prompt data. "
"Currently we only support jsonl format, and each line should contains --input-key and --label-key, "
"which will be used as the prompt and the label respectively. "
"If you want to use a custom template, you can set --apply-chat-template to true, in that case, "
"the input should be the same structure as an openai message, e.g. [{'role': 'user', 'content': 'blabla'}]. "
),
)
parser.add_argument("--apply-chat-template", action="store_true", default=False)
# Temporarily be JSON-serialized str, will be a real dict after using Omegaconf
parser.add_argument("--apply-chat-template-kwargs", type=json.loads, default="{}")
parser.add_argument("--input-key", type=str, default="input", help="JSON dataset key")
parser.add_argument("--label-key", type=str, default=None, help="JSON dataset key")
parser.add_argument(
"--multimodal-keys",
type=json.loads,
default=None,
help=(
'JSON string for multimodal data mapping media types to data keys. Example: \'{"image": "image_file"}\''
),
)
parser.add_argument("--metadata-key", type=str, default="metadata", help="JSON dataset key")
parser.add_argument(
"--tool-key",
type=str,
default="tools",
help=(
"When need to add tools during apply_chat_template, you should provide the key for the tools in the prompt dataset."
),
)
parser.add_argument(
"--start-rollout-id",
type=int,
default=None,
help=(
"The starting rollout step, if not set, will try to load the step from --load when doing continue training, "
"otherwise will be set to 0, meaning training from start."
),
)
# batch sizes
parser.add_argument(
"--rollout-batch-size",
type=int,
required=True,
help=(
"The number of prompts in each rollout step. "
"The total data returned should be rollout_batch_size * n_samples_per_prompt. "
),
)
parser.add_argument(
"--n-samples-per-prompt", type=int, default=1, help="Number of responses for each prompt in generation"
)
# gbs of the training, note that the gbs is of sample, not of prompts,
# so if you hope to train 1 step for each rollout, the global_bach_size should be set as
# `rollout_batch_size * n_samples_per_prompt`.
reset_arg(parser, "--global-batch-size", type=int, default=None)
parser.add_argument(
"--num-steps-per-rollout",
type=int,
default=None,
help=(
"Number of steps per rollout, e.g. It is equivalent to setting gbs as "
"`rollout_batch_size * n_samples_per_prompt // num_steps_per_rollout`."
),
)
# mbs for the training, will be ignored if `use_dynamic_batch_size` is set.
reset_arg(parser, "--micro-batch-size", type=int, default=1)
parser.add_argument(
"--balance-data",
action="store_true",
default=False,
help=(
"Balance the number of tokens between data parallel ranks with `karmarkar_karp` for verl. "
"Note that this may allocate the different response of the same prompt into different training steps."
),
)
parser.add_argument(
"--use-dynamic-batch-size",
action="store_true",
default=False,
help=(
"Because the sample length varies, to maximize the GPU utilization, "
"we will use the dynamic batch size to adjust the micro batch size according to the maximum number of tokens each gpu can run. "
"For example, if we have 3 samples, with the length of 100, 200, and 300, and the max_tokens_per_gpu is 300, when enabling "
"dynamic batch size, slime will make 2 micro batches, i.e. [100, 200], [300]."
),
)
parser.add_argument(
"--max-tokens-per-gpu",
type=int,
default=None,
help=(
"The maximum number of tokens per GPU for dynamic batch size. "
"Note that when enabling context parallel (CP), the max tokens per gpu should be around "
"`max_response_len // cp_size` instead of `max_response_len`."
),
)
parser.add_argument(
"--log-probs-max-tokens-per-gpu",
type=int,
default=None,
help=(
"The maximum number of tokens per GPU for calculating log probs. "
"This is used to calculate the log probs of the responses during rollout, "
"and should be set to a larger value than `max_tokens_per_gpu` if you want better performance. "
),
)
return parser
def add_eval_arguments(parser):
parser.add_argument(
"--eval-function-path",
type=str,
default=None,
help=(
"Path to the eval generation function."
"If not set, we will use rollout_function_path as the default. "
),
)
# change the default value of eval_interval from Megatron to None
reset_arg(parser, "--eval-interval", type=int, default=None)
parser.add_argument(
"--eval-prompt-data",
type=str,
default=None,
nargs="+",
help=(
"Path to the evaluation prompt data, "
"should first input the name of the eval dataset and then the path, e.g. "
"aime /path/to/aime.jsonl"
),
)
parser.add_argument(
"--eval-config",
type=str,
default=None,
help=(
"Path to an OmegaConf YAML/JSON file describing evaluation datasets. "
"When provided, this overrides --eval-prompt-data."
),
)
parser.add_argument(
"--skip-eval-before-train",
action="store_true",
default=False,
help="Whether to skip evaluation before training.",
)
# The following keys are used to override the rollout version during eval.
parser.add_argument("--eval-input-key", type=str, default=None, help="JSON dataset key")
parser.add_argument("--eval-label-key", type=str, default=None, help="JSON dataset key")
parser.add_argument("--eval-tool-key", type=str, default=None, help="JSON dataset key")
parser.add_argument(
"--n-samples-per-eval-prompt",
type=int,
default=1,
help="number of responses for each prompt in generation",
)
parser.add_argument("--eval-temperature", type=float, default=None)
parser.add_argument("--eval-top-p", type=float, default=None)
parser.add_argument("--eval-top-k", type=int, default=None)
parser.add_argument("--eval-max-response-len", type=int, default=None)
parser.add_argument("--eval-max-prompt-len", type=int, default=None)
parser.add_argument("--eval-min-new-tokens", type=int, default=None)
parser.add_argument("--eval-max-context-len", type=int, default=None)
return parser
def add_algo_arguments(parser):
parser.add_argument(
"--ref-load",
type=str,
default=None,
help=(
"The checkpoint for reference model. "
"When --load is not set, this will be used as the initial checkpoint for training. "
),
)
parser.add_argument(
"--ref-ckpt-step", type=int, default=None, help="The checkpoint step for reference model. "
)
reset_arg(parser, "--load", type=str, default=None)
reset_arg(parser, "--save", type=str, default=None)
reset_arg(parser, "--save-interval", type=int, default=None)
reset_arg(parser, "--async-save", action="store_true")
reset_arg(
parser,
"--no-save-optim",
action="store_true",
default=False,
help=(
"If set, do not save the optimizer state when saving checkpoints. "
"This reduces checkpoint size but disables training resumption from the saved checkpoint."
),
)
parser.add_argument(
"--save-hf",
type=str,
default=None,
help=(
"Path to save the model in HuggingFace format when using Megatron backend. "
"The model will be saved to `save_hf.format(rollout_id)`. "
),
)
reset_arg(parser, "--seed", type=int, default=1234)
reset_arg(parser, "--clip-grad", type=float, default=1.0)
reset_arg(parser, "--calculate-per-token-loss", action="store_true")
reset_arg(parser, "--lr", type=float, default=1e-6)
parser.add_argument("--num-critic-only-steps", type=int, default=0, help="Number of critic only steps")
parser.add_argument("--critic-load", type=str, default=None, help="The checkpoint for critic model.")
parser.add_argument("--critic-save", type=str, default=None, help="The checkpoint for critic model.")
parser.add_argument("--critic-lr", type=float, default=None, help="The lr for critic model")
parser.add_argument("--critic-train-only", action="store_true", default=False, help="Only train critic")
parser.add_argument(
"--critic-lr-warmup-iters",
type=int,
default=0,
help="number of iterations to linearly warmup for critic model.",
)
parser.add_argument("--eps-clip", type=float, default=0.2, help="PPO clip range")
parser.add_argument("--eps-clip-high", type=float, default=None, help="PPO clip upper range")
parser.add_argument(
"--eps-clip-c",
type=float,
default=None,
help="lower bound of the value for Dual-clip PPO from https://arxiv.org/pdf/1912.09729",
)
parser.add_argument("--value-clip", type=float, default=0.2, help="the clip for value loss")
parser.add_argument(
"--kl-coef",
type=float,
default=0.00,
help="KL penalty coefficient for reward shaping. This is applied to the reward signal before advantage calculation.",
)
parser.add_argument(
"--loss-type",
type=str,
choices=["policy_loss", "sft_loss", "custom_loss"],
default="policy_loss",
help=(
"Choose loss type, currently support ppo policy_loss or sft_loss, "
"if custom_loss is set, we will use the function path from `--custom-loss-function-path`."
),
)
parser.add_argument(
"--custom-loss-function-path",
type=str,
default=None,
help=(
"Path to the custom loss function, if the loss_type is `custom_loss`, "
"we will use this function to calculate the loss. "
),
)
parser.add_argument(
"--kl-loss-type",
type=str,
choices=["k1", "k2", "k3", "low_var_kl"],
default="k1",
help="Choose KL loss type: kl, k2, k3, low_var_kl",
)
parser.add_argument(
"--advantage-estimator",
type=str,
choices=[
"grpo",
"gspo",
"reinforce_plus_plus",
"reinforce_plus_plus_baseline",
"ppo",
],
default="grpo",
help=(
"Advantage estimator to use. Note: on-policy distillation (OPD) is now orthogonal "
"to the advantage estimator. Use --opd-kl-coef > 0 to enable OPD on top of any estimator."
),
)
parser.add_argument(
"--disable-compute-advantages-and-returns",
action="store_false",
dest="compute_advantages_and_returns",
help=(
"Whether to disable computing advantages and returns. "
"If set, we will not compute the advantages and returns, "
"This is useful for sft or custom loss function."
),
)
parser.add_argument(
"--use-kl-loss", action="store_true", default=False, help="whether to use KL loss from GRPO"
)
parser.add_argument(
"--kl-loss-coef",
type=float,
default=0.0,
help="KL penalty coefficient for the loss function. This is added to the final PPO loss.",
)
parser.add_argument(
"--use-unbiased-kl",
action="store_true",
default=False,
help="Whether to enable unbiased KL estimation.",
)
parser.add_argument(
"--ref-update-interval",
type=int,
default=None,
help="Interval (in rollout steps) to update ref model from actor. If None, ref model is not updated.",
)
parser.add_argument("--entropy-coef", type=float, default=0.0, help="Entropy loss coef")
parser.add_argument("--gamma", type=float, default=1.0, help="PPO GAE gamma")
parser.add_argument("--lambd", type=float, default=1.0, help="PPO GAE lambd")
parser.add_argument("--normalize-advantages", action="store_true", default=False)
parser.add_argument(
"--disable-grpo-std-normalization",
action="store_false",
dest="grpo_std_normalization",
help="from Dr.GRPO https://arxiv.org/pdf/2503.20783",
)
parser.add_argument(
"--disable-rewards-normalization",
action="store_false",
dest="rewards_normalization",
help="Disable rewards normalization",
)
parser.add_argument(
"--use-rollout-entropy",
action="store_true",
default=False,
help=(
"Whether to calculate the entropy when calculating the logprobs from actor and reference model. "
"This is useful for doing special loss mask."
),
)
parser.add_argument(
"--get-mismatch-metrics",
action="store_true",
default=False,
help="Whether to calculate the mismatch metrics.",
)
parser.add_argument(
"--reset-optimizer-states",
action="store_true",
default=False,
help=(
"Whether to reset optimizer states after each rollout. "
"If enabled, the optimizer's history will be cleared at the end of each rollout, which can sometimes help with training stability or fulfill specific experiment requirements."
),
)
parser.add_argument(
"--use-rollout-logprobs",
action="store_true",
default=False,
help=(
"Whether to use the rollout logprobs when calculating the importance sampling ratios. "
"If not set, we will use the logprobs from the actor model."
),
)
# Off-Policy Correction using Importance Sampling: https://fengyao.notion.site/off-policy-rl
parser.add_argument(
"--use-tis",
action="store_true",
default=False,
help="Enable TIS from https://fengyao.notion.site/off-policy-rl for off-policy importance sampling.",
)
parser.add_argument(
"--tis-clip",
type=float,
default=2.0,
help="Clipping threshold C for importance sampling ratios to control variance.",
)
parser.add_argument(
"--tis-clip-low",
type=float,
default=0,
help="Lower bound clipping threshold C for importance sampling ratios to control variance.",
)
parser.add_argument(
"--custom-tis-function-path",
type=str,
default=None,
help="Path to the custom TIS/RS function (e.g., examples/train_infer_mismatch_helper/mis.py:compute_mis_weights_with_cp).",
)
parser.add_argument(
"--custom-pg-loss-reducer-function-path",
type=str,
default=None,
help="Path to a custom reducer function for pg_loss only. When set, pg_loss will use this custom reducer while other metrics (pg_clipfrac, ppo_kl, entropy_loss, etc.) still use the default sum_of_sample_mean. (e.g., examples/Dr.GRPO/custom_reducer.py:get_pg_loss_reducer).",
)
parser.add_argument(
"--use-routing-replay",
action="store_true",
default=False,
help="The routing replay technique from https://arxiv.org/abs/2507.18071",
)
parser.add_argument(
"--use-rollout-routing-replay",
action="store_true",
default=False,
help="The rollout routing replay technique from https://arxiv.org/abs/2510.11370",
)
parser.add_argument(
"--use-opsm",
action="store_true",
default=False,
help="Whether to enable Off-Policy Sequence Masking (OPSM).",
)
parser.add_argument(
"--opsm-delta",
type=float,
default=1e-4,
help="The threshold for Off-Policy Sequence Masking (OPSM).",
)
return parser
def add_on_policy_distillation_arguments(parser):
"""Add on-policy distillation (OPD) related arguments.
OPD is orthogonal to advantage estimators and can be applied on top of
any estimator (GRPO, PPO, etc.) by adding a KL penalty to advantages.
"""
parser.add_argument(
"--use-opd",
action="store_true",
default=False,
help="Enable on-policy distillation (OPD). Must specify --opd-type when enabled.",
)
parser.add_argument(
"--opd-type",
type=str,
choices=["sglang", "megatron"],
default=None,
help=(
"Type of on-policy distillation. "
"'sglang': Teacher log-probs are obtained from external SGLang server during rollout. "
"'megatron': Teacher model is loaded via --opd-teacher-load and forwarded during training."
),
)
parser.add_argument(
"--opd-kl-coef",
type=float,
default=1.0,
help="On-policy distillation KL penalty coefficient. Default is 1.0.",
)
parser.add_argument(
"--opd-teacher-load",
type=str,
default=None,
help=(
"The checkpoint for OPD teacher model. Required when --opd-type=megatron. "