Repository navigation
Expand file tree
/
Copy pathgrpo.py
More file actions
6347 lines (5759 loc) · 286 KB
/
Copy pathgrpo.py
File metadata and controls
6347 lines (5759 loc) · 286 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
# Copyright (c) 2026, NVIDIA CORPORATION. All rights reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
import gc
import json
import os
import time
import warnings
from concurrent.futures import Future, ThreadPoolExecutor
from contextlib import nullcontext
from dataclasses import dataclass, fields
from typing import Any, Callable, Optional, TypeVar, cast
import numpy as np
import ray
import torch
from pydantic import BaseModel, Field, model_validator
from torchdata.stateful_dataloader import StatefulDataLoader
from transformers import AutoProcessor
from transformers.tokenization_utils_base import PreTrainedTokenizerBase
from nemo_rl.algorithms import opd as opd_module
from nemo_rl.algorithms.advantage_estimator import (
AdvEstimatorConfig,
GDPOAdvantageEstimator,
GRPOAdvantageEstimator,
OPDAdvantageEstimator,
ReinforcePlusPlusAdvantageEstimator,
)
from nemo_rl.algorithms.logits_sampling_utils import (
TrainingSamplingParams,
need_top_k_or_top_p_filtering,
)
from nemo_rl.algorithms.loss import (
ClippedPGLossConfig,
ClippedPGLossDataDict,
ClippedPGLossFn,
)
from nemo_rl.algorithms.loss.interfaces import LossFunction
from nemo_rl.algorithms.metric_utils import (
GRAD_NORM_KEY,
LOSS_KEY,
MEAN_GEN_TOKENS_PER_SAMPLE_KEY,
REWARD_KEY,
SETUP_TIMING_PREFIX,
SetupTimingMetrics,
print_setup_timing_summary,
)
from nemo_rl.algorithms.opd import OnPolicyDistillationConfig
from nemo_rl.algorithms.reward_functions import (
RewardShapingConfig,
apply_reward_shaping,
)
from nemo_rl.algorithms.utils import (
WALL_CLOCK_EFFICIENCY_CATEGORIES,
calculate_baseline_and_std_per_prompt,
calculate_trivial_reward_distributions,
compute_seq_logprob_errors,
get_gdpo_reward_component_keys,
log_generation_metrics,
print_efficiency_summary,
print_performance_metrics,
set_seed,
)
from nemo_rl.data import DataConfig
from nemo_rl.data.collate_fn import rl_collate_fn
from nemo_rl.data.dataloader import CyclingDataLoader, MultipleDataloaderWrapper
from nemo_rl.data.datasets import AllTaskProcessedDataset
from nemo_rl.data.interfaces import DatumSpec, LLMMessageLogType, VLMMessageLogType
from nemo_rl.data.llm_message_utils import (
batched_message_log_to_flat_message,
get_keys_from_message_log,
)
from nemo_rl.data.multimodal_utils import PACKED_MULTIMODAL_FIELDS, PackedTensor
from nemo_rl.data.utils import extract_necessary_env_names, load_dataloader_state
from nemo_rl.data_plane.interfaces import DataPlaneConfig
from nemo_rl.distributed.batched_data_dict import BatchedDataDict
from nemo_rl.distributed.virtual_cluster import (
TOPO_RANK_UNKNOWN,
ClusterConfig,
RayVirtualCluster,
get_ray_cluster_topology,
prepare_segment_topology,
)
from nemo_rl.environments.interfaces import EnvironmentInterface
from nemo_rl.environments.nemo_gym import (
NemoGymShardSet,
build_nemo_gym_actors,
should_use_nemo_gym,
validate_dataset_agent_coverage,
)
from nemo_rl.environments.utils import shutdown_environments
from nemo_rl.experience.interfaces import (
FRONTIER_ORDINAL_KEY,
NEMO_GYM_TASK_INDEX_KEY,
NEXT_NEMO_GYM_TASK_INDEX_KEY,
PENDING_PROMPTS_KEY,
RESUME_BASE_ORDINAL_KEY,
RETAINED_TASK_INDICES_KEY,
TRAINED_TASK_INDICES_KEY,
)
from nemo_rl.experience.metric_utils import is_histogram_metric
from nemo_rl.experience.rollouts import (
EffortLevelsConfig,
attach_initial_nemo_gym_image_payloads,
backfill_missing_routed_experts,
get_effort_config,
get_nemo_gym_thinking_tags,
run_async_multi_turn_rollout,
run_multi_turn_rollout,
run_nemo_gym_rollout_sync,
should_mask_flagged_samples,
)
from nemo_rl.models.generation.dynamo import DynamoConfig, DynamoGeneration
from nemo_rl.models.generation.interfaces import (
GenerationConfig,
GenerationInterface,
GenerationSamplingParams,
should_use_async_rollouts,
)
from nemo_rl.models.generation.megatron import MegatronGeneration
from nemo_rl.models.generation.sglang.config import SGLangConfig
from nemo_rl.models.generation.sglang.sglang_generation import SGLangGeneration
from nemo_rl.models.generation.trtllm import TrtllmConfig, TrtllmGeneration
from nemo_rl.models.generation.trtllm.config import (
replica_width,
resolve_disagg_layout,
)
from nemo_rl.models.generation.vllm import VllmConfig, VllmGeneration
from nemo_rl.models.generation.vllm.config import (
REFITTABLE_FP8_KV_CACHE_DTYPES,
VLLM_SPARSE_REFIT_TRANSPORTS,
normalize_nvfp4_pertoken_policy_config,
normalize_vllm_refit_config,
)
from nemo_rl.models.megatron.router_replay import (
configure_vllm_for_router_replay,
router_replay_enabled,
)
from nemo_rl.models.megatron.zero_train_gen_mismatch import validate_zero_train_gen_kl
from nemo_rl.models.policy import PolicyConfig
from nemo_rl.models.policy.draft_config import coerce_draft_config
from nemo_rl.models.policy.interfaces import ColocatablePolicyInterface
from nemo_rl.models.policy.lm_policy import Policy
from nemo_rl.telemetry.config import TelemetryConfig
from nemo_rl.telemetry.instrumentation import (
RL_ITERATION_ATTR,
current_trace_carrier,
efficiency_span,
evaluate_span,
iteration_scope,
managed_span,
umbrella_span,
umbrella_trace_fn,
)
from nemo_rl.telemetry.setup import get_telemetry_handle
from nemo_rl.telemetry.span_groups import RLSpanGroup
from nemo_rl.telemetry.vocabulary import INIT_TOTAL_CATEGORY, WORKER_GROUP_ENV
from nemo_rl.utils.checkpoint import (
CheckpointingConfig,
CheckpointManager,
)
from nemo_rl.utils.length_penalty import LengthPenaltyConfig
from nemo_rl.utils.logger import (
Logger,
LoggerConfig,
print_message_log_samples,
should_log_nemo_gym_full_result_tables,
)
from nemo_rl.utils.memory_tracker import MemoryTracker
from nemo_rl.utils.multimodal_payload_metrics import (
collect_multimodal_payload_metrics,
drain_multimodal_payload_metrics,
merge_multimodal_payload_metrics,
print_multimodal_payload_metrics,
)
from nemo_rl.utils.nsys import maybe_gpu_profile_step
from nemo_rl.utils.timer import TimeoutChecker, Timer
from nemo_rl.utils.venvs import make_actor_runtime_env
from nemo_rl.weight_sync.checkpoint_engine_config import (
checkpoint_engine_refit_config,
)
from nemo_rl.weight_sync.factory import (
create_weight_synchronizer,
validate_offload_policy_before_refit,
)
from nemo_rl.weight_sync.nccl_reshard_utils import check_nccl_reshard_refit_support
# ===============================================================================
# Configuration
# ===============================================================================
TokenizerType = TypeVar("TokenizerType", bound=PreTrainedTokenizerBase)
def _maybe_restore_async_replay_buffer_checkpoint(
replay_buffer: Any,
checkpoint_path: str,
*,
load_replay_buffer: bool | None,
num_prompts_per_step: int,
current_training_step: int,
max_age_steps: int,
) -> dict[str, Any] | None:
"""Restore async replay state unless the config explicitly opts out.
With ``checkpointing.load_replay_buffer=false`` the buffer starts empty
and, on a frontier-aligned checkpoint, the whole buffered window is
regenerated fresh from the rewound dataloader — the empty-retained-set
case of the same resume path. This trades resume compute for an unbiased
step composition: retained groups are the ones whose longest rollout
happened to finish before the save, so reusing them skews the next steps
toward short-rollout prompts.
Returns:
The restore metadata from ``load_from_path``, or ``None`` when the
restore was skipped or no checkpoint file exists.
"""
if load_replay_buffer is False:
print(
"📦 Skipping replay buffer restore (checkpointing.load_replay_buffer=false)"
)
return None
replay_buffer_path = os.path.join(checkpoint_path, "replay_buffer.pt")
if not os.path.exists(replay_buffer_path):
print(
f"⚠️ No replay buffer checkpoint found at {replay_buffer_path}. "
"Starting with an empty replay buffer."
)
return None
print(f"📦 Restoring replay buffer from checkpoint: {replay_buffer_path}")
restore_metadata = ray.get(
replay_buffer.load_from_path.remote(
replay_buffer_path,
num_prompts_per_step=num_prompts_per_step,
current_training_step=current_training_step,
max_age_steps=max_age_steps,
)
)
print("✅ Replay buffer restored from checkpoint")
return restore_metadata
def _save_async_replay_buffer_checkpoint(
replay_buffer: Any,
checkpoint_path: str,
) -> int:
"""Checkpoint replay state inside its actor."""
print("📦 Saving replay buffer state...")
num_buffered_trajectories = ray.get(
replay_buffer.save_to_path.remote(
os.path.join(checkpoint_path, "replay_buffer.pt")
)
)
print(f"✅ Saved replay buffer with {num_buffered_trajectories} trajectories")
return num_buffered_trajectories
class RewardScalingConfig(BaseModel, extra="allow"):
"""Configure linear reward scaling with clamping.
When `enabled` is True, each reward is clamped to the source interval
[source_min, source_max] and linearly mapped to the target interval
[target_min, target_max]. Refer to the scale_rewards function for the implementation.
"""
enabled: bool = False
source_min: float = 0.0
source_max: float = 1.0
target_min: float = 0.0
target_max: float = 1.0
class AsyncGRPOConfig(BaseModel, extra="allow"):
enabled: bool = False
# Maximum trajectory age in training steps for samples drawn from the
# async replay buffer. Trajectories older than this are excluded during
# sampling; buffer sizing also scales with this value.
max_trajectory_age_steps: int = 1
# Generation-worker failures tolerated before the AsyncTrajectoryCollector
# aborts the run. A successful batch worker resets the count.
# 0 makes the very first worker exception fatal.
max_generation_failures: int = 0
# Does the weight synchronization as soon as the training is done
# without waiting for the pending generations to finish.
in_flight_weight_updates: bool = False
# Recomputes the KV cache after weight updates.
recompute_kv_cache_after_weight_updates: bool = False
class RewardPenaltyTokenIdsConfig(BaseModel, extra="allow"):
"""Optional token IDs for reward penalties."""
unwanted: list[int] | None = None
think_open: int | None = None
think_close: int | None = None
class RewardPenaltyConfig(BaseModel, extra="allow"):
"""Reward-zeroing penalties applied to NeMo-Gym rollout results."""
penalize_duplicated_reasoning: bool = False
penalize_empty_final_answer: bool = False
penalize_unwanted_tokens: bool = False
penalize_malformed_think_tag: bool = False
# Optional token IDs. token_ids.unwanted is required when
# penalize_unwanted_tokens is true;
# think-tag IDs are inferred from configured tag strings when possible.
token_ids: Optional[RewardPenaltyTokenIdsConfig] = None
@model_validator(mode="after")
def _require_unwanted_token_ids_when_penalized(self) -> "RewardPenaltyConfig":
if self.penalize_unwanted_tokens and (
self.token_ids is None or not self.token_ids.unwanted
):
raise ValueError(
"reward_penalties.token_ids.unwanted must be set when "
"reward_penalties.penalize_unwanted_tokens is true"
)
return self
_REWARD_PENALTY_FLAGS = (
"penalize_duplicated_reasoning",
"penalize_empty_final_answer",
"penalize_unwanted_tokens",
"penalize_malformed_think_tag",
)
class GRPOConfig(BaseModel, extra="allow"):
num_prompts_per_step: int = 32
num_generations_per_prompt: int = 16
max_num_epochs: int = 1
max_num_steps: int = 1000000
max_rollout_turns: int = 1
normalize_rewards: bool = True
# Clipping bounds for normalized advantages to prevent extreme values
# When set, advantages are clipped to [advantage_clip_low, advantage_clip_high] after normalization
# Default: null (no clipping)
advantage_clip_low: float | None = None
advantage_clip_high: float | None = None
use_leave_one_out_baseline: bool = True
val_period: int = 10
# First training step eligible for periodic validation; -1 disables the delay.
val_start_at: int = -1
val_batch_size: int | None = 256 # None for NeMo-Gym compatibility
val_at_start: bool = False
# Whether to run validation on the last training step. Setting this to True ensures the
# final checkpoint has validation metrics, which is required for get_best_checkpoint_path().
val_at_end: bool = False
# Counts PROMPTS, not rollouts: with val_num_generations_per_prompt = k,
# total validation rollouts = max_val_samples * k.
max_val_samples: int | None = 256 # None for NeMo-Gym compatibility
# Number of independent validation rollouts generated for each prompt;
# k > 1 additionally reports pass@k over each prompt's k rollouts as the
# pass_k metric.
val_num_generations_per_prompt: int = 1
# Early stop: end training once this validation metric (e.g. accuracy,
# always reported, or pass_k with grouped validation) reaches
# stop_at_validation_threshold; null disables early stopping.
stop_at_validation_metric: str | None = None
# Threshold for the early stop; required when stop_at_validation_metric
# is set.
stop_at_validation_threshold: float | None = None
skip_reference_policy_logprobs_calculation: bool = False
seed: int = 42
# Legacy async config block; SC reads its async knobs from `async_rl` instead.
async_grpo: AsyncGRPOConfig | None = Field(default_factory=AsyncGRPOConfig)
overlong_filtering: bool = False
# whether to enable dynamic sampling, i.e.
# whether to discard prompts whose rewards have zero standard deviation
use_dynamic_sampling: bool = False
# When using dynamic sampling, the maximum number of batches to generate
# before throwing an error
dynamic_sampling_max_gen_batches: int = 10
# When using dynamic sampling, generation prompt batch size will equal
# num_prompts_per_step * batch_multiplier
batch_multiplier: float = 1.0
reward_shaping: RewardShapingConfig = Field(default_factory=RewardShapingConfig)
reward_scaling: RewardScalingConfig = Field(default_factory=RewardScalingConfig)
# By default advantages are calculated on CPU. Setting this flag to true leverages GPU for their computation.
calculate_advantages_on_gpu: bool = False
# Sequence-level logprob error masking for training stability. If set, mask sequences with mult_prob_error exceeding this threshold (same scale as token_mult_prob_error metric, e.g., 1.5)
# Note that this is slightly different than Masked Importance Sampling (MIS) because this uses the absolute value of the difference between the training and generation logprobs, whereas MIS just uses the difference between the training and generation logprobs.
seq_logprob_error_threshold: float | None = None
# Advantage value to assign to invalid tool call tokens. When set (e.g. -5.0), overwrites the
# computed advantage for those tokens to penalize them; absent/None disables the penalty.
invalid_tool_call_advantage: float | None = None
# Advantage value to assign to tokens with malformed <think>/</think> tags. When set (e.g. -5.0),
# overwrites the computed advantage for those tokens; absent/None disables the penalty.
malformed_thinking_advantage: float | None = None
# Advantage estimator configuration (grpo or reinforce_plus_plus)
adv_estimator: AdvEstimatorConfig = Field(default_factory=AdvEstimatorConfig)
# Share and compact immutable image/video/audio payload segments across
# logical GRPO rows. Prompt identity is never used as proof of equality.
deduplicate_multimodal_data: bool = False
# Emit exact-boundary and logical-vs-physical payload metrics.
debug_payload_metrics: bool = False
# Optional per-prompt-group length penalties/bonuses applied to NeMo-Gym
# training rollout rewards (binary single-reward envs only); see
# docs/guides/length-penalty.md. None/absent disables the feature.
length_penalty: Optional[LengthPenaltyConfig] = None
@dataclass
class GRPOSaveState:
consumed_samples: int
current_step: int
current_epoch: int
total_steps: int
total_valid_tokens: int # Track total number of non-padding tokens during training
val_reward: float # May be removed when no validation metrics are available
# SC may advance the policy version independently from the optimizer-step
# counter. None preserves compatibility with checkpoints predating it.
trainer_version: Optional[int] = None
# SingleController only: name of the sampler that wrote the replay buffer,
# used to gate the SC buffer restore. None on checkpoints from the other
# algorithms and from SC runs that predate this field.
sampler_name: Optional[str] = None
# SingleController only: exact last admitted dispatch batch. None preserves
# compatibility with checkpoints that only recorded the trainer version.
sampler_dispatch_index: Optional[int] = None
def _initial_grpo_save_state() -> GRPOSaveState:
return GRPOSaveState(
consumed_samples=0,
current_step=0,
current_epoch=0,
total_steps=0,
total_valid_tokens=0,
val_reward=-99999999.0,
trainer_version=None,
sampler_name=None,
sampler_dispatch_index=None,
)
def _get_grpo_save_state(
loaded_state: Optional[dict[str, Any]],
) -> GRPOSaveState:
if loaded_state is None:
return _initial_grpo_save_state()
# Start from current defaults so partial/legacy checkpoints remain loadable.
known_fields = {field.name for field in fields(GRPOSaveState)}
state_values = vars(_initial_grpo_save_state()).copy()
state_values.update(
{key: value for key, value in loaded_state.items() if key in known_fields}
)
return GRPOSaveState(**state_values)
class MasterConfig(BaseModel, extra="allow"):
policy: PolicyConfig
loss_fn: ClippedPGLossConfig
env: dict[str, Any]
data: DataConfig
grpo: GRPOConfig
logger: LoggerConfig
cluster: ClusterConfig
checkpointing: CheckpointingConfig
reward_penalties: RewardPenaltyConfig = Field(default_factory=RewardPenaltyConfig)
data_plane: Optional[DataPlaneConfig] = None
on_policy_distillation: Optional[OnPolicyDistillationConfig] = None
telemetry: Optional[TelemetryConfig] = None
# ===============================================================================
# Setup & Initialization
# ===============================================================================
def _validate_seq_logprob_error_in_loss(master_config: MasterConfig) -> None:
"""Validate the single-forward threshold path before allocating workers."""
if not master_config.loss_fn.seq_logprob_error_in_loss:
return
if master_config.grpo.seq_logprob_error_threshold is None:
raise ValueError(
"loss_fn.seq_logprob_error_in_loss requires seq_logprob_error_threshold"
)
loss = master_config.loss_fn
if not loss.force_on_policy_ratio or not loss.token_level_loss:
raise ValueError(
"loss_fn.seq_logprob_error_in_loss requires force_on_policy_ratio=true "
"and token_level_loss=true"
)
if master_config.grpo.adv_estimator.name != "grpo" or loss.use_kl_in_reward:
raise ValueError(
"loss_fn.seq_logprob_error_in_loss requires the grpo advantage estimator "
"without use_kl_in_reward"
)
policy = master_config.policy
if "megatron_cfg" not in policy or not policy["megatron_cfg"]["enabled"]:
raise ValueError(
"loss_fn.seq_logprob_error_in_loss requires the Megatron backend"
)
draft = coerce_draft_config(policy.get("draft"))
if (
policy["megatron_cfg"].get("mtp_num_layers")
or (draft is not None and draft.enabled)
or loss.positive_example_nll_weight != 0
or opd_module.is_opd_enabled(master_config)
):
raise ValueError(
"loss_fn.seq_logprob_error_in_loss does not support MTP, draft, "
"positive-example NLL, or distillation losses"
)
def _validate_multimodal_dedup_capability(master_config: MasterConfig) -> None:
"""Reject configurations whose media transfer path is not qualified."""
if not master_config.grpo.deduplicate_multimodal_data:
return
generation_config = master_config.policy["generation"]
if generation_config.get("backend") != "vllm":
raise NotImplementedError(
"grpo.deduplicate_multimodal_data=true is currently qualified "
"only with policy.generation.backend=vllm."
)
# The data plane accepts deduplicated payloads, so the wire format is not
# the constraint -- but note what dedup buys there. ``to_wire`` emits one
# row per *logical* row, so a shared segment is concatenated once per
# generation: the saving is in driver RAM (the deepcopy memo), not in wire
# or TQ-storage bytes, which stay O(G x images). The one gap is NeMo-Gym:
# ``grpo_train_sync`` does not call
# ``attach_initial_nemo_gym_image_payloads``, which supplies the initial
# image tensors a Gym dataset omits from ``extra_env_info``. That helper is
# itself gated on ``should_use_nemo_gym``, so non-Gym recipes never needed
# it and are unaffected.
if (master_config.data_plane or {}).get("enabled", False) and (
should_use_nemo_gym(master_config)
):
raise NotImplementedError(
"grpo.deduplicate_multimodal_data=true with data_plane.enabled=true "
"is not supported for NeMo-Gym runs: the TransferQueue trainer does "
"not attach the initial Gym image payloads. Non-Gym recipes are "
"supported."
)
def _needs_hf_refit_handshake(
generation_backend: str,
nccl_reshard_refit_enabled: bool,
colocated_inference: bool,
) -> bool:
"""Whether setup must run the HF-schema prepare_refit_info handshake."""
if generation_backend == "megatron":
return False
return not (nccl_reshard_refit_enabled and not colocated_inference)
def _uses_managed_noncolocated_refit(
generation_backend: str,
nccl_reshard_refit_enabled: bool,
offload_policy_before_refit: bool,
) -> bool:
"""Whether non-colocated setup must attach a weight synchronizer."""
return (
nccl_reshard_refit_enabled
or generation_backend == "dynamo"
or offload_policy_before_refit
)
def _shutdown_completed_nemo_gym_startup(
future: Future[tuple[NemoGymShardSet, float]] | None,
) -> None:
if future is None:
return
try:
shard_set, _ = future.result()
except BaseException:
return
shard_set.shutdown()
def setup(
master_config: MasterConfig,
tokenizer: TokenizerType,
dataset: AllTaskProcessedDataset | dict[str, AllTaskProcessedDataset],
val_dataset: Optional[AllTaskProcessedDataset],
processor: Optional[AutoProcessor] = None,
policy_factory: Optional[Callable[..., ColocatablePolicyInterface]] = None,
) -> tuple[
ColocatablePolicyInterface,
Optional[GenerationInterface],
Optional[EnvironmentInterface],
tuple[RayVirtualCluster, RayVirtualCluster],
StatefulDataLoader | MultipleDataloaderWrapper,
Optional[StatefulDataLoader],
ClippedPGLossFn,
Logger,
CheckpointManager,
GRPOSaveState,
MasterConfig,
dict[str, Any],
dict[str, str],
]:
"""Main entry point for running GRPO algorithm.
Returns:
A 13-tuple, in order:
policy, policy_generation, nemo_gym (the NeMo-Gym env actor, or None
when not enabled), cluster, dataloader, val_dataloader, loss_fn,
logger, checkpointer, grpo_save_state, master_config,
teacher_worker_groups, alias_to_group_alias.
"""
# Start timing the entire setup process
setup_start_time = time.perf_counter()
# Extract individual configs for easier access
policy_config = master_config.policy
generation_config = policy_config["generation"]
loss_config: ClippedPGLossConfig = master_config.loss_fn
env_configs = master_config.env
data_config = master_config.data
grpo_config = master_config.grpo
logger_config = master_config.logger
cluster_config = master_config.cluster
checkpointing_config = master_config.checkpointing
checkpointing_pretrained = checkpointing_config.get("pretrained_checkpoint")
if checkpointing_pretrained is not None:
policy_config["pretrained_checkpoint"] = checkpointing_pretrained
assert generation_config is not None, (
"A generation config in the PolicyConfig is required for GRPO"
)
if generation_config["backend"] == "vllm":
normalize_nvfp4_pertoken_policy_config(policy_config, entry_point="grpo")
normalize_vllm_refit_config(cast(VllmConfig, generation_config))
elif generation_config["backend"] == "dynamo":
# Validate the complete managed-Dynamo boundary before allocating Ray
# placement groups or starting any external services.
if grpo_config.async_grpo.in_flight_weight_updates:
raise ValueError(
"grpo.async_grpo.in_flight_weight_updates must be false when "
"policy.generation.backend='dynamo'; managed Dynamo drains "
"rollouts before layerwise weight refit"
)
generation_config.setdefault("vllm_kwargs", {})["hf_overrides"] = (
policy_config.get("hf_config_overrides") or {}
)
generation_config = DynamoConfig.model_validate(generation_config).model_dump()
policy_config["generation"] = generation_config
# generation.disaggregation is written in backend-agnostic terms, but only
# the TRT-LLM backend implements it today: every other backend would
# silently ignore the block and serve aggregated, so refuse to start.
if (
resolve_disagg_layout(generation_config).enabled
and generation_config["backend"] != "trtllm"
):
raise ValueError(
"policy.generation.disaggregation.enabled is only supported for "
f"backend='trtllm', got '{generation_config['backend']}'. Set it to "
"false, or switch the backend."
)
# The disagg frontends are only reachable over HTTP, so without NeMo-Gym
# the whole fleet would come up and fail at the first rollout instead.
if resolve_disagg_layout(generation_config).enabled and not should_use_nemo_gym(
master_config
):
raise ValueError(
"policy.generation.disaggregation.enabled requires NeMo-Gym "
"rollouts (env.should_use_nemo_gym=true). Set it to false, or run "
"through the NeMo-Gym entrypoint."
)
_validate_multimodal_dedup_capability(master_config)
_validate_seq_logprob_error_in_loss(master_config)
# Validation-only sampling is honored only on the NeMo-Gym vLLM rollout
# path; everywhere else validation must sample exactly like training.
val_sampling_overridden = (
generation_config["val_temperature"] != generation_config["temperature"]
or generation_config["val_top_p"] != generation_config["top_p"]
or generation_config["val_top_k"] != generation_config["top_k"]
)
if val_sampling_overridden:
assert generation_config["backend"] == "vllm" and should_use_nemo_gym(
master_config
), (
"generation.val_temperature/val_top_p/val_top_k differing from the "
"train sampling params is only supported for vLLM NeMo-Gym rollouts."
)
# The NeMo-Gym path only stamps temperature/top_p onto requests and
# rejects any top_k at rollout time, so a val_top_k override can never
# be honored — fail here instead of at the first validation step.
assert not generation_config["val_top_k"], (
"generation.val_top_k is not supported: the NeMo-Gym rollout path "
"only honors val_temperature/val_top_p. Leave val_top_k null."
)
assert grpo_config.val_num_generations_per_prompt >= 1, (
"grpo.val_num_generations_per_prompt must be >= 1"
)
# pass_k is only reported when k > 1; catch the mismatch here instead of
# at the first validation step.
assert not (
grpo_config.stop_at_validation_metric == "pass_k"
and grpo_config.val_num_generations_per_prompt <= 1
), (
"grpo.stop_at_validation_metric='pass_k' requires "
"grpo.val_num_generations_per_prompt > 1"
)
# opd_full is implemented only on the SingleController runtime, which has its
# own setup(). This entry point never reads on_policy_distillation.full, so
# accepting it would silently train the sampled-token top-k objective while
# the user believes they configured the full-vocabulary reverse KL.
if opd_module.get_opd_full_config(master_config) is not None:
raise ValueError(
"on_policy_distillation.full is only implemented on the "
"SingleController runtime (examples/run_grpo_single_controller.py). "
"This entry point never reads it, so leaving it enabled here would "
"silently train the sampled-token top-k objective instead of the "
"full-vocabulary reverse KL."
)
# Set seed for all random number generators
set_seed(grpo_config.seed)
# ==========================
# Logger
# ==========================
logger = Logger(logger_config)
logger.log_hyperparams(master_config.model_dump())
# ==========================
# Checkpointing
# ==========================
checkpointer = CheckpointManager(checkpointing_config)
last_checkpoint_path = checkpointer.get_latest_checkpoint_path()
loaded_state = checkpointer.load_training_info(last_checkpoint_path)
grpo_save_state = _get_grpo_save_state(loaded_state)
# ==========================
# Data
# ==========================
# num_prompts_per_step and dataloader_batch_size will be different when using multiple dataloaders
num_prompts_per_step = grpo_config.num_prompts_per_step
if data_config["use_multiple_dataloader"]:
dataloader_batch_size = data_config["num_prompts_per_dataloader"]
else:
dataloader_batch_size = num_prompts_per_step
# Validate batch_multiplier
batch_multiplier = grpo_config.batch_multiplier
if grpo_config.use_dynamic_sampling:
num_prompts_per_step = int(num_prompts_per_step * batch_multiplier)
dataloader_batch_size = int(dataloader_batch_size * batch_multiplier)
else:
assert batch_multiplier == 1, (
"batch_multiplier>1 can only be used if use_dynamic_sampling=True"
)
# Validate the early-stop pairing
if grpo_config.stop_at_validation_metric is not None:
assert grpo_config.stop_at_validation_threshold is not None, (
"grpo.stop_at_validation_threshold must be set when "
"grpo.stop_at_validation_metric is set"
)
# Validate number of prompts per step
if data_config["use_multiple_dataloader"]:
assert num_prompts_per_step % dataloader_batch_size == 0, (
"Expected num_prompts_per_step to be a multiple of num_prompts_per_dataloader, "
f"but got {num_prompts_per_step} and {dataloader_batch_size}. "
"Please check the configuration of num_prompts_per_step and num_prompts_per_dataloader. "
"If use_dynamic_sampling is enabled and batch_multiplier is used, please also check the configuration of batch_multiplier."
)
# Load train dataset
def init_train_dataloader(dataset, suffix: str = ""):
dataloader = StatefulDataLoader(
dataset,
batch_size=dataloader_batch_size,
shuffle=data_config["shuffle"],
collate_fn=rl_collate_fn,
drop_last=True,
num_workers=data_config["num_workers"],
)
if last_checkpoint_path is not None:
load_dataloader_state(dataloader, last_checkpoint_path, data_config, suffix)
return dataloader
if data_config["use_multiple_dataloader"]:
# Initialize dataloaders
dataloaders = {}
for task_name, task_dataset in dataset.items():
dataloaders[task_name] = init_train_dataloader(
task_dataset, f"_{task_name}"
)
print(
f" ✓ Training dataloader {task_name} loaded with {len(task_dataset)} samples",
flush=True,
)
train_sample_count = sum(
len(task_dataloader) for task_dataloader in dataloaders.values()
)
# Wrap dataloader
dataloader = MultipleDataloaderWrapper(
expected_num_prompts=num_prompts_per_step,
data_config=data_config,
dataloaders=dataloaders,
)
else:
dataloader = init_train_dataloader(dataset)
train_sample_count = len(dataloader)
print(
f" ✓ Training dataloader loaded with {train_sample_count} samples",
flush=True,
)
# Load validation dataset if provided
val_dataloader: Optional[StatefulDataLoader] = None
# If validation is enabled, load the validation dataloader
if grpo_config.val_period > 0 or grpo_config.val_at_start or grpo_config.val_at_end:
assert val_dataset is not None, (
"Validation dataset is required if validation is enabled"
)
val_dataloader = StatefulDataLoader(
val_dataset,
batch_size=grpo_config.val_batch_size,
shuffle=False,
collate_fn=rl_collate_fn,
num_workers=data_config["num_workers"],
)
print(
f" ✓ Validation dataloader loaded with {len(val_dataset)} samples",
flush=True,
)
# ==========================
# Loss Function
# ==========================
# Fused linear logprobs compute next-token logprobs directly from hidden states
# (chunked over the sequence) and never materialize the full
# [batch, seq_len, vocab_size] logit tensor, which significantly reduces peak
# memory. It is only available on the Megatron backend.
# Both megatron_cfg and use_fused_linear_logprobs are NotRequired, and many
# configs (e.g. nemo_gym, modelopt, non-megatron) omit them -- use .get() with
# a {} fallback to avoid a KeyError.
megatron_cfg = policy_config.get("megatron_cfg", {})
use_fused_linear_logprobs = bool(
megatron_cfg.get("enabled") and megatron_cfg.get("use_fused_linear_logprobs")
)
if use_fused_linear_logprobs:
# Sequence packing is not yet validated with the fused path: the fused
# forward rolls labels over the whole (packed) sequence and would mix
# tokens across packed-sequence boundaries.
assert not policy_config["sequence_packing"]["enabled"], (
"Linear CE fusion loss is not supported with sequence packing for GRPO. "
"The fused path has not been validated with cu_seqlens-based logprob "
"aggregation. Set policy.megatron_cfg.use_fused_linear_logprobs=false "
"or policy.sequence_packing.enabled=false."
)
# The fused forward gathers the logprob of the realized token from the raw
# (unfiltered) logits, so top-k/top-p training-time filtering cannot be
# applied. This also keeps prev/reference logprobs (computed via the fused
# get_logprobs path) consistent with the actor logprobs.
assert not need_top_k_or_top_p_filtering(
TrainingSamplingParams(
top_k=generation_config["top_k"],
top_p=generation_config["top_p"],
)
), (
"Linear CE fusion loss is not supported with top-k/top-p training-time "
"filtering for GRPO. The fused path computes logprobs from unfiltered "
"logits. Set policy.megatron_cfg.use_fused_linear_logprobs=false, or "
"disable filtering (policy.generation.top_k=null, "
"policy.generation.top_p=1.0)."
)
loss_fn = ClippedPGLossFn(
loss_config,
use_fused_linear_logprobs=use_fused_linear_logprobs,
seq_logprob_error_threshold=grpo_config.seq_logprob_error_threshold,
)
# Validate force_on_policy_ratio
if loss_config.force_on_policy_ratio:
assert (
grpo_config.num_prompts_per_step * grpo_config.num_generations_per_prompt
== policy_config["train_global_batch_size"]
), (
"force_on_policy_ratio requires train_global_batch_size == num_prompts_per_step * num_generations_per_prompt"
)
os.environ["NRL_IGNORE_TP_ACCURACY_CHECK"] = "1"
print(" ✓ force_on_policy_ratio enabled")
# Validate skip_reference_policy_logprobs_calculation
if grpo_config.skip_reference_policy_logprobs_calculation:
assert loss_config.reference_policy_kl_penalty == 0, (
"grpo.skip_reference_policy_logprobs_calculation=True requires "
"loss_fn.reference_policy_kl_penalty == 0"
)
print(
"Reference policy logprob calculation will be skipped since `grpo.skip_reference_policy_logprobs_calculation` is set to True and `loss_fn.reference_policy_kl_penalty` is 0."
)
_validate_use_kl_in_reward_compat(master_config)
# Fail on an invalid zero-KL config before Ray allocates GPUs.
validate_zero_train_gen_kl(policy_config, check_environment=False)
# ==========================
# Cluster
# ==========================
print("\n▶ Setting up compute cluster...", flush=True)
colocated_inference = generation_config["colocated"]["enabled"]
env_name_list = extract_necessary_env_names(data_config)
rm_env_enabled = "reward_model" in env_name_list
# NeMo Gym is initialized inside setup() (rather than by the caller) so its
# spinup can overlap with vLLM model loading via deferred model load.
enable_nemo_gym = should_use_nemo_gym(master_config)
_raise_if_reward_penalties_enabled_without_nemo_gym(
master_config, enable_nemo_gym=enable_nemo_gym
)
_raise_if_length_penalty_enabled_without_nemo_gym(
master_config, enable_nemo_gym=enable_nemo_gym
)
nemo_gym_actor = None
def _spinup_nemo_gym(base_urls, model_name, policy_api_key=None):
"""Spin up the NeMo Gym stack against the given generation server URLs.
Returns a shard set, which is the one actor of an unsharded job as much
as it is the K of a sharded one. ``policy_api_key`` is the bearer token
the generation server requires on its OpenAI routes (the vLLM backend's
``http_server_api_key``), or None when the server checks none.
"""
t0 = time.perf_counter()
shard_set = build_nemo_gym_actors(
env_configs,
base_urls=base_urls,
model_name=model_name,
tokenizer=tokenizer,
enable_router_replay=router_replay_enabled(policy_config),
use_fastokens=bool(policy_config["tokenizer"].get("use_fastokens")),
policy_api_key=policy_api_key,
)
train_splits = (
{f"train[{name}]": split for name, split in dataset.items()}
if isinstance(dataset, dict)
else {"train": dataset}
)
try:
validate_dataset_agent_coverage(
shard_set, {**train_splits, "validation": val_dataset}
)
except BaseException:
shard_set.shutdown()
raise
return shard_set, time.perf_counter() - t0
total_nodes = cluster_config.num_nodes
segment_size = cluster_config.segment_size
# Topology of nodes left over after policy/inference placement; non-colocated
# OPD teachers are placed within it so their collectives stay on NVLink.
teacher_segment_topology: Optional[dict[str, tuple[str, int]]] = None
if rm_env_enabled:
rm_resource = env_configs["reward_model"]["resources"]
rm_nodes = rm_resource["num_nodes"]
rm_gpus_per_node = rm_resource["gpus_per_node"]
else:
rm_nodes = 0
rm_gpus_per_node = 0
if total_nodes == 1:
policy_nodes = total_nodes
else:
policy_nodes = total_nodes - rm_nodes
assert policy_nodes > 0, (
"policy_nodes must be > 0, but got "
f"policy_nodes:{policy_nodes} + rm_nodes:{rm_nodes} = total_nodes:{total_nodes}"
)
# Reserve nodes for non-colocated OPD teachers so training doesn't claim them.
opd_teacher_nodes = 0
enable_opd_teachers = opd_module.is_non_colocated_teachers_enabled(master_config)
if enable_opd_teachers: