Repository navigation
fix(sc): SWE PPO fixes for token capture and Megatron critic memory - #4776
Conversation
bg51717
left a comment
There was a problem hiding this comment.
Summary
Five independent fixes for SWE PPO on the single controller with token capture:
- fp32 logprob grad reuses the logits storage (
model_utils.py). It works for a single consumer, but it crashes backward when another autograd node saved the same logits or a view of them (inline). - Critic clears transient Megatron caches. The helper move is byte-identical for the policy. The critic reads
value.megatron_cfg, notpolicy.megatron_cfg(inline). - Gym rollout metrics on the capture path. The lifecycle is sound: the entry is popped before any await, and the abort path cleans up. One test assertion is vacuous (inline).
token_capture.nan_generation_logprobs. The pinned Gym already rejects non-finite logprobs at staging, so this branch is unreachable (inline).- Malformed think-tag penalty on capture. The per-(carry, generation) check matches the echo path's (user, assistant) pairs. The new
thinking_tagsfield has no effect, and the reference config is out of sync, which breakstest_config_v2(inline).
PR description
- Usage: the critic flag is
value.megatron_cfg.clear_memory_caches_before_refit, notpolicy.megatron_cfg(see the inline comment onmegatron_value_worker.py). - Memory claims (commits 1-2): the ~12 GiB figure is an estimate. Could you add
torch.cuda.max_memory_allocated()for one step before and after: on the fp32_lm_head + chunked + CP config for commit 1, and on the critic with the flag on and off for commit 2?
Lint: pre-commit run --all-files passes. taplo-format was skipped because it has no aarch64 build, and the PR touches no TOML.
Reviewed with six agents (RL, bug finder, tests, design, devil's advocate, leader). Findings are read from source, not measured; no GPU was available, so the suggested tests were collected but not run.
Generated by Claude Code
7e61e44 to
08f4fd4
Compare
|
/ok to test 08f4fd4 |
08f4fd4 to
97e2386
Compare
|
/ok to test 97e2386 |
svcnvidia-nemo-ci
left a comment
There was a problem hiding this comment.
Reviewed all 25 changed files and their directly affected loss, finalization, replay, and recovery paths.
The earlier shared-logits backward issue is addressed by the opt-in reuse flag and the new shared-storage regressions. The half-resolved tag guard, abort-path cleanup assertion, finalizer tokenizer wiring, and guide updates are also present in the current source.
The inline comments identify a recovery-compatibility gap, incorrect newly published truncation metrics, and two nonblocking verification/guideline items. The extracted cache helper retains the policy behavior and gives the critic a shared implementation.
Validation was source-only: tests, linters, GPU memory measurements, and independent agent review were not executed in this read-only environment.
Inline comments (escaped v1):
-
nemo_rl/experience/reward_penalties.pyline 240: 1 action item, please fix in this PR.
TL;DR — recovery records the new penalty flag but not its tag rules, so a restart can silently reinterpret saved rollouts.AI-1 — [BUG] Persist the active think-tag rules (confidence: 98)
PR-introduced: the checkpoint projection now accepts the malformed-tag penalty, but retains only enabled flags, unwanted IDs, and effort settings. For example, save with the penalty enabled and
think_open=1, think_close=2, then resume withthink_open=3, think_close=4: both projections are identical, so the restore compatibility check succeeds. Yet finalization reads those IDs and the resolved strings, changing which unfinished rows receive zero reward while already-finalized rows retain their old rewards.Action: extend the projection, serialization/parser, and compatibility comparison to include the resolved open/close ID pair (or explicitly no ID check) and resolved tag strings only while this penalty is active. Feed the same resolved rules used by the finalizer into controller checkpoint settings and bootstrap normalization; reading only the raw penalty block misses inferred IDs and environment-derived strings. Preserve the versioned reader contract with an explicit version/migration decision rather than silently defaulting missing active rules. This requires coordinated schema/wiring edits, not a safe one-line patch.
Acceptance — proposed, not run: round-trip an enabled
(1,2)configuration, then require compatibility against(3,4)and expect a field-specificValueError; repeat with changed resolved strings and with ID-check versus string-only mode. Unchanged rules must resume successfully. Keep disabled think-tag fields irrelevant, and retain the existing unwanted-ID normalization and inactive-option assertions. -
nemo_rl/experience/rollout_manager.pyline 2441: 1 action item, please fix in this PR.
TL;DR — forwarding the whole receipt metrics dictionary publishes truncation=0 and natural termination=1 even for truncated capture rows.AI-1 — [BUG] Source truncation metrics from finalized rows (confidence: 97)
This PR introduces publication of pre-existing placeholder values: receipt completions always set
truncated=False, and metric construction turns that into three termination-rate keys. The new capture sidecar attachment sends these values to step logging. For a healthy captured rollout whose rebuilt length equals the configured maximum, the canonical truncation field is true, but the published global and agent truncation rates remain zero.Action: omit placeholder-derived termination rates from receipt-side metrics and produce the global and per-agent rates from finalized rows using the same canonical truncation predicate. Preserve Gym timing/routing metrics and the echo path's real completion-based rates. The treatment of rejected placeholder rows needs an explicit denominator decision; do not simply infer truncation from unverified manifest lengths.
Acceptance — proposed, not run: finalize two valid rows, one at the maximum length and one below it; logged
truncation_rate,natural_termination_rate, and the agent truncation rate should each be0.5. An all-truncated valid group should report1,0, and1. Keep the existing echo mixed-completion assertions, plus the new Gym timing sidecar preservation assertion. -
nemo_rl/models/value/workers/megatron_value_worker.pyline 1041: 1 action item.AI-1 — [GUIDELINE] Avoid adding a consumer-side default (confidence: 100)
PR-introduced: this new flag read supplies
Falseat the consumer, contrary to the repository's optional-config convention. The field is optional, so a truthiness check without a fallback preserves the behavior:if self.cfg["megatron_cfg"].get("clear_memory_caches_before_refit"):Action: use this replacement in the critic branch; no broader policy-worker refactor is needed. Missing and explicit-false flags must skip clearing, while true must clear after offload without changing the earlier eval/offload order.
Acceptance — source reasoning, not executed: retain the true/false event-order assertion; an absent flag must follow the same no-clear branch as false. Verify the suggestion before adopting it.
-
nemo_rl/distributed/model_utils.pyline 315: 1 action item.
TL;DR — the memory savings are plausible from source, but the supplied review material still has no measured before/after peak.AI-1 — [PERF-EVIDENCE] Add measured memory results (confidence: 95)
For these PR-introduced memory optimizations, the description provides an allocation estimate and reports successful runs, but not quantitative peak-memory comparisons. The fp32 storage-reuse branch and critic cache-clearing branch address different memory lifetimes, so one successful run does not quantify both benefits.
Action: add a small results table with identical model, sequence lengths, TP/CP, packing, and precision settings: peak allocated memory for fused-packed fp32 chunked backward with reuse disabled/enabled; and critic allocated memory after training/offload plus the following-stage peak with cache clearing disabled/enabled. Include a step-time comparison to expose any cache-rebuild cost. This is a nonblocking evidence request, not a claim that the optimizations fail.
Acceptance — measurements requested, not performed here: provide actual values and the measurement boundaries, with peak counters reset for each comparison. Preserve the leaf/storage-reuse assertions and shared-logits/narrow-view gradient parity checks; do not broaden reuse to obtain a larger measured saving.
Review generated by codex. This was a full review. Request a full review with /review reset=true.
|
/ok to test 96ec8a3 |
|
Replies to the review:
|
yuki-97
left a comment
There was a problem hiding this comment.
Bringing the malformed think-tag penalty to token capture with a per-span check that matches the echo path rule for rule, and getting the capture path's Gym rollout metrics into W&B, close two real gaps for SWE PPO on the single controller; the Megatron critic now also releases the same transient caches as the policy.
Thanks for running grpo_async_gym_single_controller.sh with token capture both with and without the think-tag penalty, and for the extensive self-review.
Scope: whole PR, at 96ec8a3
Checked:
- Capture think-tag check — per-span ID and string rules match the echo path case by case; only Gym's message-level flag is absent, as the guide says.
- Think-tag sources — resolver, finalizer and recovery settings all read
get_nemo_gym_thinking_tags, so resume compares the rules the finalizer applies. clear_transient_megatron_caches— identical to the removed policy block; every cleared attribute is rebuilt on the next forward at Megatron-LM 3e95097.- Capture metrics lifecycle — stored and popped with no await in between, aborts pop, no double attach.
reuse_logits_storage— only the fused packed path enables it, and a consumer that saved the logits through autograd fails loudly.
Remaining comments are on:
reuse_logits_storage: documenting the overwritten logits, and moving that commit to its own PR- capture metrics that cover only the re-dispatched siblings on a retry
- think-tag precondition errors that are swallowed or surface late
clear_memory_caches_before_refitmissing from the exemplar YAMLs
nit, not blocking merging — the PR body still says "Four independent commits" and does not mention the think-tag rules now persisted for resume or the termination rates now computed from finalized rows. No shipped config sets fp32_lm_head: true, so the reported end-to-end run does not exercise the in-place grad write.
terrykong
left a comment
There was a problem hiding this comment.
This PR conflicts with main — please rebase first.
What works well: the per-span think-tag check matches the echo rules; capture metrics go to W&B; there is one shared cache-clear helper (clear_transient_megatron_caches in megatron/common.py, next to the helpers both workers already import); has_malformed_think_tag is a pure function that takes decode, so it is easy to unit test; and the finalizer loads the tokenizer only when the penalty is on.
Summary of comments:
- (C1) Reply on yuki's split question: agree to split; 3 asks for the new PR.
- (C2) Nit: the resume error names the wrong config path.
- (C3) Reply on the follow-up thread: one more case for the shared predicate.
Optional (not an inline): a small test that the finalizer actor loads the tokenizer (RolloutReassemblerActor.__init__ → get_tokenizer). The actor is # pragma: no cover, but a break there fails loudly at startup, so this is optional.
Verified: lint passes on all changed files; the merge commit 96ec8a3 matches a clean re-merge; CPU unit tests for the reward-penalty, recovery, reassembler and new logprob tests pass. Megatron worker tests and all GPU tests were not run.
Visual explainer: https://terrykong.github.io/gh-pages-poc/terryk/pr-4776-think-tag-capture.html
Visual explainer: https://terrykong.github.io/gh-pages-poc/terryk/pr-4776-logits-reuse.html
Generated by Claude Code
With megatron_cfg.clear_memory_caches_before_refit the policy worker releases the RotaryEmbedding lru_cache and the MoE dispatcher routing tensors (whose probs keep the activation-recompute context alive). The Megatron value worker never did, so a critic trained with recompute on variable-length SWE rollouts kept both resident across its CPU offload. Move that logic into megatron.common.clear_transient_megatron_caches; the policy worker's _clear_rope_and_moe_dispatcher_caches now calls it, and MegatronValueWorkerImpl.finish_training calls it under the same flag after the offload. Co-Authored-By: Claude Opus 5.5 <[email protected]> Signed-off-by: bg51717 <[email protected]>
On the echo path TQReplayBuffer.commit stores each PromptGroupRecord's rollout_metrics in the replay metadata (the ROLLOUT_METRICS sidecar), and the train pump merges them into the step metrics. On the token-capture path the finalizer builds the rows and the controller commits them with commit_finalized, which has no PromptGroupRecord: RolloutManager .generate_for_finalization discarded the record returned by run_rollout, so every per-group Gym metric (agent and verifier timings, error types, evaluation completion, effort-shaping and routing metrics) was silently missing from W&B for capture runs. RolloutManager now keeps each dispatched group's rollout_metrics keyed by group_id (dropped again if the dispatch is abandoned), and SingleControllerActor._finalize_with_actor pops them before any await and attaches them to the committed meta's extra_info under ROLLOUT_METRICS, the same sidecar the echo path writes. The finalizer's own meta is not mutated. Co-Authored-By: Claude Opus 5.5 <[email protected]> Signed-off-by: bg51717 <[email protected]>
Token capture rejected reward_penalties.penalize_malformed_think_tag. Check it in finalize_capture_reward over the verified (carry, generation) spans, the capture equivalent of the echo path's (user, assistant) pairs: - Tag-ID check: when think_open/think_close are single tokens, the prompt delta sets the expected tag counts in the generation. - String check: the decoded generation must hold no open tag and at most one close tag. The finalizer actor gets the policy tokenizer and the resolved tags only when the penalty is on. Gym's message-level has_malformed_thinking flag has no capture source and is not checked. Setup now rejects a half-resolved think-tag ID pair, so both paths fail the same way. Co-Authored-By: Claude Opus 5.5 <[email protected]> Signed-off-by: bg51717 <[email protected]>
The malformed-think-tag penalty runs at finalization, like the unwanted-token penalty whose IDs are already part of CaptureRewardSettings. Record the configured think-tag IDs and the resolved tag strings while the penalty is on, and reject a resume whose rules differ. Version-1 sidecars could not enable this penalty before (capture rejected it), so the version stays 1. Co-Authored-By: Claude Opus 5.5 <[email protected]> Signed-off-by: bg51717 <[email protected]>
Receipt completions carry a placeholder truncated=False, so the forwarded receipt metrics always logged truncation_rate=0 and natural_termination_rate=1 on the capture path. Drop those keys in receipt mode; the finalizer now counts valid rows at max_seq_len (the TRUNCATED predicate), and the rates are pooled over valid rows like the penalty rates. Co-Authored-By: Claude Opus 5.5 <[email protected]> Signed-off-by: bg51717 <[email protected]>
Read the NotRequired clear_memory_caches_before_refit flag without a fallback, and take the reassembler's thinking_tags from the resolved config only when the think-tag penalty is on. Co-Authored-By: Claude Opus 5.5 <[email protected]> Signed-off-by: bg51717 <[email protected]>
…equest generate_for_finalization now returns (request, rollout_metrics) and _finalize_with_actor takes the metrics as an argument, replacing the _capture_rollout_metrics side-channel dict and its pops. Metrics are kept only when the successful attempt dispatched every sibling: a retry of the unsealed siblings alone would under-report the group in the ROLLOUT_METRICS sidecar. Co-Authored-By: Claude Opus 5.5 <[email protected]> Signed-off-by: bg51717 <[email protected]>
- finalize_capture_reward raises RuntimeError when built without decode or tags, so the per-row ValueError handler cannot turn a mis-wired finalizer into reward_processing rejects. - resolve_reward_penalty_config rejects fewer than two thinking tags at setup instead of skipping the ID pair. - Drop the now unreachable RolloutReassembler constructor check. - The half-set think-tag ID error names both fixes: set both IDs or omit both. Co-Authored-By: Claude Opus 5.5 <[email protected]> Signed-off-by: bg51717 <[email protected]>
require_compatible now names reward_penalties.*, env.nemo_gym.thinking_tags and env.nemo_gym.effort_levels.*, the paths a user edits, instead of the internal penalties./effort./thinking_tags names. Co-Authored-By: Claude Opus 5.5 <[email protected]> Signed-off-by: bg51717 <[email protected]>
…onfigs Add the field (default false) under policy.megatron_cfg in grpo_math_1B and ppo_math_1B and under value.megatron_cfg in ppo_math_1B, mirrored in the reference configs. Co-Authored-By: Claude Opus 5.5 <[email protected]> Signed-off-by: bg51717 <[email protected]>
Drop the one-line _clear_rope_and_moe_dispatcher_caches wrapper on the policy worker; offload_before_refit calls the shared helper, as the critic already does. The wrapper's tests duplicated the helper's, except the best-effort case, which now targets the helper. The critic comment no longer claims it always trains with activation recompute. Co-Authored-By: Claude Opus 5.5 <[email protected]> Signed-off-by: bg51717 <[email protected]>
… ID check runs Label each finalizer count prefix pooled by the capture reward aggregation, and note in the single-controller guide that configured think-tag IDs also enable the ID check. Co-Authored-By: Claude Opus 5.5 <[email protected]> Signed-off-by: bg51717 <[email protected]>
…and termination rates RolloutReassembler._truncated_flags is now the only truncation rule: Forest rows use their rollout's Gym-reported truncation, ordinary rows count when they fill max_seq_len. The termination counts are taken per rollout over the same rows as the reward observations, so Forest groups, which have several rows per rollout, now report termination rates too. Co-Authored-By: Claude Opus 5.5 <[email protected]> Signed-off-by: bg51717 <[email protected]>
The Forest recovery checkpoint test passes thinking_tags to CaptureRewardSettings.from_configs, and the Forest retry test's fake run_rollout returns a record, as the real one does, now that capture reads its rollout metrics. Co-Authored-By: Claude Opus 5.5 <[email protected]> Signed-off-by: bg51717 <[email protected]>
96ec8a3 to
ffdd950
Compare
|
/ok to test ffdd950 |
|
/ok to test ffdd950 |
Co-Authored-By: Claude Opus 5.5 <[email protected]> Signed-off-by: bg51717 <[email protected]>
yuki-97
left a comment
There was a problem hiding this comment.
Merge blockers — please rebase on main and resolve conflicts.
Thanks for addressing the previous review comments.
Scope: fix commits c0c4d70 through ffdd950, checked against the previous review threads, plus a scan of the changed files for new issues.
Checked:
generate_for_finalizationnow returns metrics explicitly, and partial sibling retries omit incomplete group statistics.- Think-tag cardinality and ID-pair errors fail during setup; a missing finalizer decoder propagates
RuntimeError. - Forest termination counts and the training
TRUNCATEDcolumn share one predicate, with rates counted once per logical rollout.
Remaining comments are on:
- A rebase collision leaves the finalizer and controller both writing
ROLLOUT_METRICS, so Gym receipt metrics overwrite verified token metrics. Consolidate assembly and writing in the controller, with each metric having one source.
nit
- An echo-path thinking-tag check that the new setup check makes unreachable.
clear_memory_caches_before_refitstill missing from the other root exemplars' policy blocks.
Generated by Codex
The finalizer wrote verified token metrics into ROLLOUT_METRICS and the controller then replaced the list with the Gym rollout metrics, dropping the generated-token statistics. The finalizer now returns its token metrics on FinalizedGroup, receipt mode no longer emits total-token metrics, and the controller merges the two disjoint sets into one sidecar, failing the commit if both report the same key. Co-Authored-By: Claude Opus 5.5 <[email protected]> Signed-off-by: bg51717 <[email protected]>
Setup already rejects thinking tags without an open and close pair, so apply_reward_penalties only receives validated tags. Co-Authored-By: Claude Opus 5.5 <[email protected]> Signed-off-by: bg51717 <[email protected]>
…egatron exemplars Co-Authored-By: Claude Opus 5.5 <[email protected]> Signed-off-by: bg51717 <[email protected]>
Co-Authored-By: Claude Opus 5.5 <[email protected]> Signed-off-by: bg51717 <[email protected]>
|
/ok to test 8659913 |
Main gained #4776, which adds a thinking_tags argument to RolloutReassembler and RolloutReassemblerActorConfig for the malformed think-tag reward penalty. This branch added an argument with the same name for the message-level detector, and the auto-merge kept both. Both resolve to env.nemo_gym.thinking_tags or the default, so one argument now serves both checks: setup sets it when the think-tag penalty or a message-level penalty is on. Other conflicts: _spinup_gym keeps main's rollout-recovery arguments, and the single-controller guide keeps main's reflowed text and drops its "remain unsupported with capture" sentence for the new paragraph. Also: - Pin Gym to c3e5931262, NVIDIA-NeMo/Gym#5447 merged with Gym main. It descends from main's pin 9e2e5d0ad0, and Gym's dependencies and version did not change, so uv.lock stays valid. - Every check reads the active algorithm block, so PPO gets the same support. Add a PPO validation test, and name both blocks in the guide. - Shorten three in-function comments to two lines. Co-Authored-By: Claude Opus 5.5 <[email protected]> Signed-off-by: Yi-Fu Wu <[email protected]>
What does this PR do ?
Fixes and small features needed to run SWE PPO on the single controller with token capture: lower Megatron critic memory, keep Gym rollout metrics and termination rates on the capture path, and support the malformed think-tag penalty on the capture path.
The fp32 logits-storage reuse for the chunked logprob grad moved to #4973. The shared echo/capture think-tag predicate is tracked in #5008.
Changes
Rebased on
main. Each commit can be reviewed on its own; the later ones address review feedback.fix(value): clear transient Megatron caches after critic training.With
megatron_cfg.clear_memory_caches_before_refit, the policy worker already released the RoPE cache and the MoE dispatcher routing tensors; the Megatron value worker never did. The logic moves intomegatron.common.clear_transient_megatron_caches, which the policy'soffload_before_refitand the critic'sfinish_trainingboth call under the same flag. The exemplar configs now list the flag for the policy and the critic.fix(sc): keep Gym rollout metrics on the token-capture path.The capture path commits finalized rows without a
PromptGroupRecord, so per-group Gym metrics never reached W&B.generate_for_finalizationnow returns them next to the reassembly request and_finalize_with_actorattaches them to the committed meta, the sameROLLOUT_METRICSsidecar the echo path uses. A retry that re-dispatches only the unsealed siblings logs no metrics for that group rather than an under-count.feat(capture): support the malformed think-tag reward penalty.reward_penalties.penalize_malformed_think_tagwas rejected with token capture. The finalizer now checks each verified(carry, generation)span: a token-ID check when think-tag IDs are configured or each tag is a single token, plus a decoded-string check. The finalizer actor gets the policy tokenizer and the resolved tags only when the penalty is on. Gym's message-levelhas_malformed_thinkingflag is not used on capture.env.nemo_gym.thinking_tags; a finalizer built without a tokenizer fails the run instead of rejecting every row.fix(capture): report termination rates from finalized rows.Receipt completions carry a placeholder
truncated=False, so capture always loggedtruncation_rate=0. The rates now come from the finalized rows, with the same rule as theTRUNCATEDtraining column (max_seq_lenfor ordinary rows, Gym's truncation for Forest rows), counted once per rollout.Usage
Forest training still rejects reward penalties.
Testing
ffdd950):test_config_v2.py,tests/unit/single_controller,tests/unit/data_plane,tests/unit/experience,test_grpo.py,test_config_validation.py, the NeMo-Gym environment tests and the touched Megatron worker tests, in the default, NeMo-Gym, mcore and vLLM lanes.ffdd950:grpo_async_gym_single_controller.shwith++token_capture.enabled=true ++reward_penalties.penalize_malformed_think_tag=true, andgrpo_async_gym_single_controller_context_compaction.sh(Forest). Both pass their metric checks and log the Gym rollout metrics and termination rates every step.Before your PR is "Ready for review"
Pre checks: