Repository navigation
feat(sc): compute advantages in dedicated and sharded Ray actors - #4326
Conversation
833e26a to
6a512a1
Compare
saumishr
left a comment
There was a problem hiding this comment.
Reviewed at 6a512a1f0. Two blocking issues, plus some cleanup.
The module does not import. single_controller_utils/utils.py uses @dataclass without importing it, so the entire single-controller path raises NameError at import time. Confirmed by executing the module.
The new sharding is only valid for two of the six estimators. split_meta_by_prompt_group preserves whole prompt groups, which covers the group-relative baseline, but gdpo, reinforce_plus_plus, raw_reward, and gae all additionally normalize over the whole batch. With num_advantage_workers >= 2 those four silently produce different advantages than a single-worker run. Details inline.
The rest is minor: a dead _advantage_input_fields, an unused field import, two unread fields on AdvantageRequest that the inventory test now pins, a soft=False pin that contradicts its sibling branch's stated rationale, and algo: Any where the union type is known.
Things I checked that are clean: reduce_advantage_pump_metrics(**self._step_log_dict) is a kwargs splat so the rewards/sample_masks/masked_advantages rename is consistent end to end and no test still passes the old kwargs; REWARD_KEY is "reward" so collapsing the masked and unmasked branches does not rename the metric; num_generations_per_prompt exists on both GRPOConfig and PPOConfig, so the unconditional read in _advantage_stage is safe for PPO; KVBatchMeta.slice carries tags and sequence_lengths along with the rows; and the config field follows the BaseModel-default-plus-exemplar-YAML convention with no reference_configs entry covering this exemplar.
Dropping the unrelated throughput metrics in the force-push was the right call -- the PR reads much more cleanly as a single concern now.
6a512a1 to
554bb3f
Compare
|
Addressed all seven at Both blocking issues are fixed and verified: the
Commit split: everything except the sharding gate folded into commit 1; the Still outstanding: the unit tests have not been executed anywhere (no torch in the environment I am working from), and the CMH numbers are still a TODO in the description. |
|
/ok to test 554bb3f |
554bb3f to
6f47152
Compare
|
/ok to test 6f47152 Lint fix only. The failure was import ordering ( No behaviour change -- the only edits are import order. |
|
/ok to test 6f47152 |
6f47152 to
6d331f5
Compare
|
/ok to test 6d331f5 |
Move advantage computation off the SingleController into a pool of AdvantageActor workers sized by num_advantage_workers, with the stage wiring extracted into single_controller_utils/advantage_stage.py. At Ultra scale the in-controller stage blocked the controller's event loop long enough to miss Ray's actor liveness ping, and it held a whole cohort's advantage inputs in the controller's heap. num_advantage_workers defaults to 0, which keeps the historical in-controller path. Actor placement excludes the dedicated Ray head so the pool does not put its host-memory peak beside the controller. On clusters with no dedicated head _placement_node_ids returns empty and placement falls back to soft SPREAD. assert_metadata_only and its forbidden-key set move out of rollout_reassembler_actor.py into nemo_rl/utils/rpc_guard.py so the advantage actor can enforce the same metadata-only RPC contract on its own boundary. That move is behaviour-preserving. Signed-off-by: Saurabh Mishra <[email protected]>
Split each advantage call across the whole actor pool instead of handing
one actor the entire batch. This engages whenever the pool exists and
declines to a single call whenever the group layout cannot be proven.
Group boundaries come from num_generations_per_prompt. An earlier
revision keyed them on DATASET_SOURCE_TAG, which replay_buffer.py only
stamps when a dataset row carries a `dataset` key; datasets without one
made the splitter decline on every call while reporting timings
indistinguishable from the unsharded path.
Because that failure was silent, the stage now logs
advantage stage: N row(s) over M shard(s), pool=P
so "over 1 shard(s)" identifies a decline immediately rather than
hiding behind an unchanged measurement.
Signed-off-by: Saurabh Mishra <[email protected]>
6d331f5 to
93c8818
Compare
|
/ok to test 93c8818 |
test_pins_round_robin_off_the_head_when_one_exists failed the first time it was ever executed. NodeAffinitySchedulingStrategy validates node_id on construction -- it decodes as a 28-byte hex string and raises on a nil result -- so the "aaa"/"bbb"/"head" stubs could never reach the assertion: ValueError: Invalid node_id 'aaa'. Node ID must be a valid hex string. Only the pinning path constructs the strategy object, which is why the SPREAD sibling passed and this one did not. The product code is unaffected. 13 passed on aws-cmh (GB300, aarch64) after the change; previously 4 passed and the run aborted on maxfail before test_advantage_stage.py ran at all. Signed-off-by: Saurav Muralidharan <[email protected]> (cherry picked from commit 14de98bac1ac08e982460200d9cc4dee177dd2b5)
The advantage-stage tests build the controller with object.__new__ and set the gates by hand, but the stage now reads them off _advantage_stage_config and runs through _advantage_computer, both assigned only in __init__. The stub left them missing, so _advantage_stage raised AttributeError before reaching any assertion. pyproject sets -x in addopts, so the run aborted at the first of these and the remaining seven never reported. All eight are fixed together: every attribute the changed path reads is now stamped, including the _opd_stat_* accumulators that _absorb_advantage_outcome adds to unconditionally. The helper derives the config from the gates the caller already set rather than restating them, so a new field on AdvantageStageConfig does not need an edit at every stub -- which is how this broke. _available_advantage_actors is deliberately absent: the empty pool returns before it is touched. Signed-off-by: Saurabh Mishra <[email protected]>
|
/ok to test f0cd64c |
The gae stub is stamped shardable=False, which routes _advantage_stage into the branch that names the estimator it declined to shard -- stage_cfg.algo.adv_estimator.name. The stub's _algo_cfg only carried seq_logprob_error_threshold and overlong_filtering, so that read raised AttributeError on a types.SimpleNamespace. Nothing else on this path is missing. Inside _advantage_stage the only other algo read is num_generations_per_prompt, which sits in the shardable arm of a conditional expression and is never evaluated here; in AdvantageComputer, overlong_filtering and seq_logprob_error_threshold are already present, and the invalid_tool_call/malformed_thinking reads are behind message_level_advantage_penalties_enabled, which this stub sets False. Signed-off-by: Saurabh Mishra <[email protected]>
…okens
calculate_baseline_and_std_per_prompt groups rows with
torch.unique(prompts, dim=0), and the single-controller path fed it the
prompt_ids_for_adv token column. Two distinct groups can carry identical
prompt text -- DAPO-Math-17k stores each of its 17,917 prompts 100 times,
about seven same-prompt pairs per 512-prompt chunk -- and the token key
gave those two groups one shared baseline whenever they landed in the
same call. Which groups shared therefore moved with the streaming chunk
boundaries, and after the advantage stage learned to shard, with
num_advantage_workers: two groups merged when one actor saw the whole
batch and separated when the split put them on different actors.
That also made SHARD_INVARIANT_ESTIMATORS wrong about grpo. It claims a
whole-group shard reproduces the whole-batch numbers, which only holds
once the key is per group.
The key already existed. The controller mints one group id per group and
pack_payload turns it into "{group_id}_g{i}", so this stamps it on the
row tags instead of leaving it implicit in a naming convention, and
AdvantageComputer.run turns the per-row ids into the [N, 1] integer
column the baseline compares. Every estimator already documents
prompt_ids as "identifying which prompt each sample belongs to", and
several ignore it outright, so an index is the documented shape. A row
with no tag raises: falling back to tokens is the bug.
split_meta_by_prompt_group now cuts where the tag changes rather than
assuming num_generations_per_prompt rows per group, so variable-size
groups are safe instead of silently mis-cut, and a trimmed trailing
group no longer makes the whole batch decline. An interleaved layout has
no contiguous whole-group cut, so it still declines.
prompt_ids_for_adv is no longer read on this path, so the stage stops
fetching it and AdvantageConfig.prompt_ids_field goes away.
_group_ids_from_meta reads the tag too, rather than keeping a second
description of what a group is. The column is still written: deciding
what it should contain once nothing reads it is the separate question of
whether to pack it at all, which also governs the finalizer's
copy-a-sibling's-prompt workaround, left in place here.
Signed-off-by: Saurabh Mishra <[email protected]>
terrykong
left a comment
There was a problem hiding this comment.
Thanks @saumishr. This moves the advantage stage off the controller's event loop into a pool of CPU actors, and splits grpo/opd work across the pool by prompt group.
What works well:
- One
AdvantageComputerserves both the in-process path and the actor, so the two can't drift, and the stage can now be unit-tested without Ray. RewardPartial/AdvantagePartialare the right shape for metrics that merge across shards.- The actor pool follows the same pattern as the token-capture finalizer pool.
- The shardable allow-list fails safe: a new estimator is not sharded until someone checks it.
- Thanks too for the fixes from your own self-review.
- Thanks for the quick pyrefly fix.
Convergence. The main thing to check is convergence. On data that repeats prompts, num_advantage_workers changes the GRPO advantages (details). Unless #4371 lands in this PR, please post a short same-seed A/B of num_advantage_workers: 0 vs 8 on a dataset that repeats prompts (e.g. DAPO-Math-17k), overlaying reward and advantages/*. On data with unique prompts the two should match exactly.
Evidence (not blocking):
- Please confirm the measured run's log showed more than 1 shard: sharding is skipped without any error when it can't split, and the screenshots were taken before the commit that limits sharding to grpo/opd.
- Which dataset was it, and do its prompts repeat? See the
SHARD_INVARIANT_ESTIMATORScomment.
Docs. Please add async_rl.num_advantage_workers to docs/guides/single-controller.md next to the other async_rl knobs.
Small cleanup. rollout_manager.py still imports assert_metadata_only from rollout_reassembler_actor, and the _FORBIDDEN_RPC_KEYS alias now only serves a test. Both can import from nemo_rl.utils.rpc_guard.
PR description. The "ran the unit and functional tests locally" box is checked, but your own comment says the tests haven't run anywhere yet; please uncheck it until they have. Also remove the template leftovers: the empty Issues section, the code-snippet placeholder, and "* ...".
Generated by Claude Code
Resolves one import-block conflict in tests/unit/single_controller/test_checkpointing.py: main added a ClusterConfig import next to the schema import this branch had extended with GROUP_ID_TAG. Both are kept. Signed-off-by: Saurabh Mishra <[email protected]>
test_restored_permits_are_released_by_a_live_pump is the one restore test with max_num_steps > 0, so it is the only one whose pump body reads the group-id tag off the restored rows. Its rows carried only a weight_version. The tag has to match each group's declared "group_id" rather than be unique per row, because the pump cross-checks the ids it selects against the training claims the restore created. Stamped the sibling restore fixtures the same way so the next test to raise max_num_steps does not rediscover this. Signed-off-by: Saurabh Mishra <[email protected]>
main added an OPD metric fix that reports teacher_student_logprob_gap_mean from a raw pooled gap instead of the advantage mean. Three of its four edits land in untouched regions and merged cleanly; the fourth accumulates the gap inside the advantage computation, which this branch moved out of the controller and into AdvantageComputer. Ported that accumulation to the new home: AdvantageOutcome carries opd_gap_sum as this call's contribution, the computer fills it under the same teacher_logprobs_required guard and before GRPO clipping as on main, and _absorb_advantage_outcome folds it in. Summing partials across shards gives the same total as the single in-process pass, matching how the other OPD moments already cross the RPC boundary. git aligned the hunk against this branch's shard-decline log, which is unrelated code that happens to end in the same delimiter; that side is kept as-is. Signed-off-by: Saurabh Mishra <[email protected]>
Running the unit lanes locally rather than pushing surfaced 43 failures from the main merge, in three groups. _absorb_advantage_outcome folds opd_gap_sum in unconditionally, the way it already does the other OPD moments, so the stubs that bypass __init__ need the attribute to exist even for non-OPD tests. Added it to the two shared builders instead of the individual tests. main turned AdvEstimatorConfig into a BaseModel, so the OPD estimator stub can no longer be constructed from a bare dict; it now reuses the config the surrounding GRPOConfig already holds, matching the GRPO branch beside it. test_opd_advantage_stage_pools_raw_gap_separately_under_tropd asserted on _step_log_dict["masked_advantages"], which this branch reduced to an AdvantagePartial. It now reads the post-clip column the stage wrote, which is what that key used to hold, flattening the jagged payload to compare against the dense mask. Its gap assertion is unchanged and is what validates the ported accumulation. Also stamped the group-id tag on the remaining train-pump fixtures and the replay-buffer tag assertion, and declared opd_gap_sum in the RPC dataclass inventory so that guard stays a deliberate choice. Local run of the L0_Unit_Tests_Other selection: 4474 passed, 39 skipped. The 14 remaining failures (native_checkpoint, mooncake backend_config, trtllm wheel mirror, flops_counter, venv creation) fail identically on a pristine main checkout in the same container, as they need GPUs, RDMA or network that a login node does not have. Signed-off-by: Saurabh Mishra <[email protected]>
|
/ok to test e5d9f2e |
Resolves the conflict with NVIDIA-NeMo#4347 (full per-step training data dump). The dump's two load-bearing pieces -- the pre_seq_error_sample_mask clone and the add_chunk call -- sat inside the in-process advantage body this branch relocates into advantage_stage.py, so git aligned them against unrelated code and left an empty "ours" side on all three hunks. Keeping either side verbatim would have dropped one of the two features. main's hooks that survive the relocation (imports, the TrainDataDump the controller owns, finish_step on the optimizer step) are untouched. The two that moved now live in AdvantageComputer.run, which is the only code that still holds the untruncated tensors: the controller stopped fetching them when the computation moved off it. Because the stage can run in a pool, TrainDataDump is now a sharded writer. Each shard owns train_data_step<N>.jsonl.part-<shard_id> and finish_step merges them in shard order, assigning idx across the merged file -- no single writer sees every row, so no writer can number them. The controller publishes a step it never wrote, which the previous row-counter guard rejected. Sharding also moves the JSON serialization, which is the expensive half of the feature, off the controller. The dump's timing survives the move as a float on AdvantageOutcome and is replayed into the controller's timer, so the train_data_dump metric still reports when the work happened in an actor. Two of main's assertions encoded behaviour this branch changed on purpose: the estimator now receives the prompt-group key rather than the dense prompt matrix, and a pump fixture needed the group_id tag this branch makes mandatory. prompt_ids_for_adv returns to AdvantageConfig as a dump-only column. Verified locally in the CI container before pushing: 1553 passed in the single-controller blast radius, and 4495 passed in a full L0_Unit_Tests_Other with only this node's five known environmental failures (no GPU, no RDMA, no HF access). Signed-off-by: Saurabh Mishra <[email protected]>
The advantage stage writes the dump wherever it runs, so with a pool the controller merges part files it did not write. A pool that does not share the controller's filesystem still runs and still reports, and its parts are simply absent -- which would publish a short dump that looks complete. Carry the per-call row count back on AdvantageOutcome and check the merged total against it before the atomic publish. Signed-off-by: Saurabh Mishra <[email protected]>
|
/ok to test 67707d4 |
|
Record of the CI failures on head 67707d4 (run 37150580820), so they aren't mistaken for problems in this PR. Failing (4 jobs). None are caused by this PR:
All 4 fail the same way. Every Megatron generation call raises: The cause is the Ray 2.58 bump on main (#4419), not this PR: Ray 2.58 added a check in Fix: #4469 (main) and #4468 (r0.8.0). Both were verified on Ray 2.58, where all 4 jobs pass. Everything else passed (103 jobs), including the single-controller tests that run this PR's code with vLLM: One gap: the Megatron single-controller test fails during the first rollout, before the advantage stage runs. So this PR's code has not been tested with Megatron generation yet. That will be covered once the Ray fix is on main and this branch is rebased. Heads-up for the rebase: main also had an unrelated |
|
force merged this PR given the tests failed should be solved by #4468 (since it's broken on main) and this PR is fairly high priority |
…quet-logging Main moved the advantage stage into AdvantageComputer and a sharded actor pool (NVIDIA-NeMo#4326). Trajectory records are now submitted once per chunk after all shards have written their advantages, from the merged batch meta. Co-Authored-By: Claude Opus 5.5 <[email protected]> Signed-off-by: Marat Kitov <[email protected]>
…ics-20260930 Conflicts: - grpo.py: keep _apply_async_sample_masks beside the #4160 participation helpers, and capture dataset_loss_multiplier before calling it (the helper clones loss_multiplier, so the reference stays the dataset weight). - single_controller.py: take main's _advantage_stage, whose body #4326 moved into AdvantageComputer.run, and drop the unused helper import. - test_grpo.py: keep both sides' imports and test classes. Move the SingleController port with the code it changed: - advantage_stage.py: apply _apply_async_sample_masks in AdvantageComputer.run, fold the logprob-error count into num_masked_seqs_total, and return the counts as AdvantageOutcome.sample_mask_metrics. - single_controller.py: _absorb_advantage_outcome appends them to _step_log_dict["sample_mask_metrics"]. - test_advantage_stage.py: classify the new AdvantageOutcome field. - test_utils.py: use the reward_partials/advantage_partials parameter names from #4326. Signed-off-by: Peter Jin <[email protected]>
The controller's host-memory peak is set by cohort postprocessing, which is fixed by the batch shape rather than by cluster size, so sharing a node with GPU workers puts it a few hundred GB from the kernel OOM killer. Job 847389 died that way: the head was carrying the Ray head, the driver and four GPU workers when the controller went from ~60 GB to at least 330 GB, and the kernel took the step before the first refit. ray.sub's DEDICATED_RAY_HEAD=1 already reserves a compute-free node and advertises it as `ray_head`; nothing was claiming it. `_placement_node_ids` in advantage_actor (NVIDIA-NeMo#4326) already keeps the advantage pool off that node on the stated assumption that the controller claims it, so this closes a gap a merged component already relies on. The placement reads the live cluster rather than the env var so a mismatch between launcher and allocation cannot silently pin nothing, and claims the whole unit rather than a fraction, since the point is that nothing else lands on that node. NRL_PIN_CONTROLLER_TO_HEAD=0 separates the two decisions, for a run that wants the reserved head without the pin. docs/cluster.md's DEDICATED_RAY_HEAD entry gains the corresponding note. Signed-off-by: Saurabh Mishra <[email protected]>
The controller's host-memory peak is set by cohort postprocessing, which is fixed by the batch shape rather than by cluster size, so sharing a node with GPU workers puts it a few hundred GB from the kernel OOM killer. Job 847389 died that way: the head was carrying the Ray head, the driver and four GPU workers when the controller went from ~60 GB to at least 330 GB, and the kernel took the step before the first refit. ray.sub's DEDICATED_RAY_HEAD=1 already reserves a compute-free node and advertises it as `ray_head`; nothing was claiming it. `_placement_node_ids` in advantage_actor (NVIDIA-NeMo#4326) already keeps the advantage pool off that node on the stated assumption that the controller claims it, so this closes a gap a merged component already relies on. The placement reads the live cluster rather than the env var so a mismatch between launcher and allocation cannot silently pin nothing, and claims the whole unit rather than a fraction, since the point is that nothing else lands on that node. NRL_PIN_CONTROLLER_TO_HEAD=0 separates the two decisions, for a run that wants the reserved head without the pin. docs/cluster.md's DEDICATED_RAY_HEAD entry gains the corresponding note. Signed-off-by: Saurabh Mishra <[email protected]>
The controller's host-memory peak is set by cohort postprocessing, which is fixed by the batch shape rather than by cluster size, so sharing a node with GPU workers puts it a few hundred GB from the kernel OOM killer. Job 847389 died that way: the head was carrying the Ray head, the driver and four GPU workers when the controller went from ~60 GB to at least 330 GB, and the kernel took the step before the first refit. ray.sub's DEDICATED_RAY_HEAD=1 already reserves a compute-free node and advertises it as `ray_head`; nothing was claiming it. `_placement_node_ids` in advantage_actor (NVIDIA-NeMo#4326) already keeps the advantage pool off that node on the stated assumption that the controller claims it, so this closes a gap a merged component already relies on. The placement reads the live cluster rather than the env var so a mismatch between launcher and allocation cannot silently pin nothing, and claims the whole unit rather than a fraction, since the point is that nothing else lands on that node. NRL_PIN_CONTROLLER_TO_HEAD=0 separates the two decisions, for a run that wants the reserved head without the pin. docs/cluster.md's DEDICATED_RAY_HEAD entry gains the corresponding note. Signed-off-by: Saurabh Mishra <[email protected]>
What does this PR do ?
Moves advantage computation off the
SingleControllerinto a pool of dedicated CPU Ray actors, shards each call across that pool on prompt-group boundaries, and keys the group-relative baseline on the prompt group's id rather than on its prompt tokens.The baseline key is the reason the three are one PR.
calculate_baseline_and_std_per_promptgrouped rows by prompt tokens, so two groups that happen to share prompt text shared one baseline whenever they landed in the same call and got separate baselines when a shard split them. Under that keygrpois not shard-invariant, sonum_advantage_workersmoved the numerics. Keying on the controller's group id makes the shard-invariance claim true, and only then is the sharding safe to land.num_advantage_workersdefaults to0, which keeps the historical in-controller path.Issues
Fixes #4371.
Usage
Nano 3.5, RLVR, 344 GPUs run experiments with 8 Advantage Actors, 8192 GBS
~10% faster Step Time:
~97% faster Advantage Calculation Time
Evidence for the measurement
advantage stage: N row(s) over 8 shard(s), pool=8and never once logged a decline:...-advshardon all 40 of its advantage calls and...-advshard-s0on all 115 of its (55 before a restart, 60 after), 155 in total, every one an 8-way split. Rawrgcounts triple these, because Ray mirrors each driver line into the driver log, the owning worker's stderr and the W&B output log.num_advantage_workers: 8and it did create the actors, but the per-call shard log line was added by this PR's own sharding commit, so the three candidate runs that predate it (...-advactor,...-dolphin,...-fixedeos) emit it zero times. At that revision every decline was silent — the bug this PR fixes — so "split 8 ways" and "declined and ran the whole chunk on one actor" are indistinguishable from those logs. That distinction matters for attribution: even a decline moves the stage out of the controller process, which could account for much of the speedup on its own. So the screenshots show that the stage got faster, and the two runs above show that sharding is what the code does; the screenshots alone do not prove the 97% came from sharding rather than from offloading.grpo, which is inSHARD_INVARIANT_ESTIMATORS, so the split was permitted rather than skipped.curriculum_v35_inescapable-sawfly.train.efforts0p15_qamathcode.jsonl, a NeMo-Gym curriculum blend of QA / math / code. Its prompts do repeat. Of the first 60,000 of its 99,840 rows: 50,048 prompts are distinct, 5,025 appear two or more times, 14,977 rows (25%) share their prompt text with another row, and one prompt appears 16 times. So the measured run is exactly the case where the old prompt-token key made the advantages a function ofnum_advantage_workers— which is why the fix for GRPO baseline groups rows by prompt text instead of by group id (single controller) #4371 is in this PR rather than following it.A same-seed
num_advantage_workers: 0vs8A/B is not posted here for two reasons. First, with the baseline keyed on the group id the two are now exactly equal rather than approximately equal, andtest_sharded_pool_matches_in_processasserts that equality row by row for both shard-invariant estimators — a convergence plot is a weaker statement than the test. Second, the async path cannot be seed-matched across the two configurations: undersampler: ready_firstwithmax_staleness_versions: 1, group arrival order is a function of generation timing, so the two runs would not consume the same batches no matter what the advantage code does.Before your PR is "Ready for review"
Pre checks:
The unit tests have not been executed anywhere, including locally — the environment this was developed in has no
torchand its pinned venv is a dangling symlink. The changed paths were verified by executing the real function bodies against stubs (the decline branch over all six cases, the splitter over 25 layouts) and by cross-checking the new controller fixture's attribute set againstsingle_controller.pywith an AST pass. That is not a substitute for the CI run; treat the unit-test lane as the first real execution.Additional Information