Skip to content

perf(megatron): add manual_gc to align Python GC across policy ranks - #4857

Merged
terrykong merged 10 commits into
mainfrom
sniverty/megatron-manual-gc
Oct 29, 2026
Merged

terrykong merged 10 commits into
mainfrom
sniverty/megatron-manual-gc

Conversation

@snivertynv

@snivertynv snivertynv commented Oct 22, 2026 •

Copy link
Copy Markdown
Contributor

In a distributed training job, an automatic full python garbage collection lands on whichever rank crosses its threshold which can leave every other rank waiting for it in the next collective. On a 32-node SFT run, ~1s GC collections hit up to 90 of 128 ranks in a single step at different points, stretching 66 s steps to 75-85 s.

policy.megatron_cfg.manual_gc mirrors Megatron's manual_gc: the Megatron policy workers disable automatic GC and every rank collects together at the end of every manual_gc_interval-th finish_train_step (0 = never collect).

This ensures that all ranks collect at the same time, removing the scenario where staggered GCs slow down everyone else.

The screenshot below shows how in a 4-rank setup, when the last rank at the bottom hits a GC event in the middle of a training step that lasts about 1 second (no GPU activity), the other 3 ranks above it are stuck on a NCCL synchronization call.

image

Perf measurements - results below for text-only SFT through SFT v2 (examples/run_sft_v2.py), Megatron policy, 32 nodes × 4 GPUs (128 ranks), 100 steps, a save every 10 steps. Manual GC ran with manual_gc_interval: 10 (an env-flag prototype with the same logic as this PR).

auto GC manual GC, interval 10
step time, mean / p99 (90 non-post-save steps) 64.5 / 74.5 s 62.7 / 69.3 s
peak host RSS per policy worker, median / max (128 ranks) 123.3 / 131.4 GB 123.3 / 131.4 GB

With manual GC, the ten collection steps together cost 11.5 s over a normal step, equal to each rank's own total GC pause time (median 11.5 s): aligned collections cost about one rank's collection time. With automatic GC, the same 90 steps took ~190 s longer, against at least ~26 s of GC work per rank, so most of the automatic-GC cost was ranks waiting on another rank's collection. Peak RSS was unchanged at this interval. Only interval 10 and only the SFT v2 entrypoint were measured; v1 run_sft.py was not.

Usage

policy:
  megatron_cfg:
    manual_gc: true
    manual_gc_interval: 10   # collect on every rank every 10 optimizer steps; 0 = never
uv run examples/run_sft.py --config examples/configs/sft.yaml \
  policy.megatron_cfg.enabled=true \
  policy.megatron_cfg.manual_gc=true policy.megatron_cfg.manual_gc_interval=10

Before your PR is "Ready for review"

Pre checks:

  • Make sure you read and followed Contributor guidelines
  • Did you write any new necessary tests?
  • Did you run the unit tests and functional tests locally? Visit our Testing Guide for how to run tests
  • Did you add or update any necessary documentation? Visit our Document Development Guide for how to write, build and test the docs.

An automatic full Python GC lands on whichever rank crosses its threshold,
and every other rank then waits for it in the next collective. On a
32-node NM4 Nano SFT run, ~1 s gen-2 collections hit up to 90 of 128 ranks
in a single step, stretching 66 s steps to 75-85 s.

policy.megatron_cfg.manual_gc mirrors Megatron's manual_gc: the Megatron
policy workers disable automatic GC and every rank collects together at the
end of every manual_gc_interval-th finish_train_step (0 = never collect).
Forked children re-enable GC. Off by default.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Signed-off-by: sniverty <[email protected]>
@snivertynv snivertynv self-assigned this Oct 22, 2026
@snivertynv snivertynv added the CI:L1 Run doctests, unit tests, and functional tests label Oct 22, 2026
@copy-pr-bot

copy-pr-bot Bot commented Oct 22, 2026

Copy link
Copy Markdown

This pull request requires additional validation before any workflows can run on NVIDIA's runners.

Pull request vetters can view their responsibilities here.

Contributors can view more details about this message here.

@snivertynv

Copy link
Copy Markdown
Contributor Author

/ok to test cdd9b68

@saumishr saumishr left a comment •

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Overall: the diagnosis is solid and the mechanism is faithful to upstream on the path where it fires — I verified the collect position, the disable-site semantics, the interval >= 0 validation, and the modulo cadence all match Megatron-LM at the pinned SHA, and the register_at_fork guard improves on it. The one substantive issue is that the collection hook sits on finish_train_step, which the v1 entrypoints never reach, so the feature cannot fire on sft.yaml or rm.yaml as shipped.

Also checked and clean, so you don't have to re-litigate them: gc.disable() does not leak into the vLLM workers (separate Ray actors, separate processes); the fork handler cannot stack (no max_restarts, no __setstate__); rank counters cannot desync on the SC path (run_all_workers_single_data fans out to every rank); config coverage across all 22 megatron_cfg exemplars and 7 reference configs is complete; and the repo's pre-commit suite (ruff, ruff-format, pyrefly) passes on this diff.

Generated by Claude Code

Comment thread nemo_rl/models/policy/__init__.py Resolved
snivertynv and others added 2 commits October 27, 2026 14:52
…erval, enable GC late

Addresses review feedback on manual_gc:

- The monolithic train() (v1 SFT, RM, DPO) now calls _maybe_run_manual_gc()
  after each optimizer step, so manual_gc no longer disables GC without ever
  collecting there. Both paths share one counter: the interval counts optimizer
  steps on train() and finish_train_step alike.
- manual_gc_interval is read with .get() like manual_gc, and manual_gc: true now
  requires a positive integer interval (missing, 0, negative, bool or str raise a
  ValueError at worker setup). The exemplar and reference configs ship 10
  instead of 0, so enabling manual_gc alone works.
- The config is validated early in __init__, but gc.collect() + gc.disable()
  now run at the end of __init__, so model, optimizer and checkpoint setup run
  with automatic GC and their garbage is collected before it is disabled.
- Tests: the off case covers manual_gc: false and the shipped defaults and
  checks no instance state is written; invalid intervals are parametrized;
  the finish_train_step error path asserts the MTP-scale reset and hook
  restore; structural tests pin the __init__ and train() call sites; a GPU
  test runs train() with manual_gc and checks GC is off and every optimizer
  step is counted on every worker.
- docs/design-docs/training-backends.md: new "Manual garbage collection"
  subsection with interval guidance and the host-memory trade-off.

Signed-off-by: sniverty <[email protected]>
@github-actions github-actions Bot added the Documentation Improvements or additions to documentation label Oct 27, 2026
saumishr
saumishr previously approved these changes Oct 27, 2026

@saumishr saumishr left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Thanks for addressing the comments!

@terrykong terrykong left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Thanks for this, @snivertynv, and for the quick fixes in b4c6733. Two places the flag still doesn't land right, neither covered in the earlier review:

  1. (C2) OPD/MOPD teacher workers copy the student's config, turn GC off, and never collect.
  2. (C4) The PPO Megatron value worker has the same stall but ignores the flag; please wire it in here too.

Visual explainer: https://terrykong.github.io/gh-pages-poc/terryk/pr-4857-manual-gc.html
Visual explainer: https://terrykong.github.io/gh-pages-poc/terryk/pr-4857-v1-never-collects.html

Generated by Claude Code

Comment thread nemo_rl/models/policy/__init__.py Resolved
…alue worker

Addresses review feedback (C2, C4):

- OPD/MOPD teacher workers copy the student's policy config, so a student's
  manual_gc: true disabled GC on teachers that never train and so never
  collect. TeacherWorkerGroup now resets the inherited manual_gc before
  applying the teacher's megatron_cfg_overrides, and raises if a teacher
  override turns it back on.
- The PPO Megatron value worker trains across data-parallel ranks like the
  policy and had the same stall, but ignored the flag. The manual GC methods
  move into ManualGCMixin (nemo_rl/models/megatron/manual_gc.py), inherited by
  both workers; the value worker validates early in __init__, enables at the
  end of __init__, and collects after each optimizer step in train().
  ppo_math_1B.yaml and its reference config gain the keys under
  value.megatron_cfg.
- Tests: the manual_gc unit and structural tests run for both workers; two
  teacher tests cover the reset and the rejected override. Docs updated.

Signed-off-by: sniverty <[email protected]>
@snivertynv

Copy link
Copy Markdown
Contributor Author

/ok to test 87ed093

@snivertynv

Copy link
Copy Markdown
Contributor Author

/ok to test cc291fd

snivertynv and others added 2 commits October 28, 2026 14:52
run_all_workers_single_data rejects positional args (issue #582), so the GPU
test called __ray_call__ through it and failed before checking anything. Call
each worker actor's __ray_call__ directly, with the reader defined inside the
helper so Ray pickles it by value.

Signed-off-by: sniverty <[email protected]>
@snivertynv

Copy link
Copy Markdown
Contributor Author

/ok to test dfc1617

terrykong
terrykong previously approved these changes Oct 28, 2026
@terrykong
terrykong enabled auto-merge (squash) October 28, 2026 22:21
@terrykong

Copy link
Copy Markdown
Collaborator

/ok to test 42db556

@terrykong terrykong added CI:Lfast Runs a fast test suite and re-use nightly `main` container (but sync dependencies to PRs version) and removed CI:L1 Run doctests, unit tests, and functional tests labels Oct 29, 2026
@terrykong
terrykong merged commit dd2e251 into main Oct 29, 2026
105 of 116 checks passed
@terrykong
terrykong deleted the sniverty/megatron-manual-gc branch October 29, 2026 19:58
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

CI:Lfast Runs a fast test suite and re-use nightly `main` container (but sync dependencies to PRs version) Documentation Improvements or additions to documentation

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants