Skip to content

feat(megatron): support fractional optimizer CPU offload - #3628

Merged
terrykong merged 13 commits into
NVIDIA-NeMo:mainfrom
seonjinn:perf/optimizer-cpu-offload-20260813
Aug 18, 2026
Merged

terrykong merged 13 commits into
NVIDIA-NeMo:mainfrom
seonjinn:perf/optimizer-cpu-offload-20260813

Conversation

@seonjinn

@seonjinn seonjinn commented Aug 13, 2026 •

Copy link
Copy Markdown
Contributor

What does this PR do?

Adds fractional optimizer CPU offload to the Megatron policy backend.

  • Supports optimizer_offload_fraction values in (0, 1].
  • Exposes Megatron Core's overlap_cpu_optimizer_d2h_h2d option.
  • Keeps optimizer placement owned by Megatron Core's
    HybridDeviceOptimizer.
  • Preserves existing behavior when CPU offload is disabled.

Optimizer CPU offload requires use_distributed_optimizer=true. This PR does
not change activation offload or NeMo RL's generic optimizer movement path.

Usage

policy:
  megatron_cfg:
    optimizer:
      use_distributed_optimizer: true
      optimizer_cpu_offload: true
      optimizer_offload_fraction: 0.5
      overlap_cpu_optimizer_d2h_h2d: true

Validation

  • Focused tests cover config validation, Megatron Core forwarding, and worker
    lifecycle behavior.
  • A CW H100 test completed 100 steps for disabled, 50%, and 100% offload
    configurations. All 400 recorded losses were finite.
  • The single-GPU Qwen3-0.6B microbenchmark confirms the expected memory versus
    throughput trade-off:
Case Mean step time Max sampled GPU memory
Disabled 0.752s 15.24 GiB
50%, no overlap 1.187s 14.13 GiB
50%, overlap 1.216s 14.65 GiB
100%, overlap 1.678s 10.53 GiB

Timings use steps 11-100. This is a functional microbenchmark, not a
production-scale throughput claim.

Before your PR is "Ready for review"

  • Read and followed the contributor guidelines.
  • Added focused unit/config tests.
  • Added user documentation and exemplar configuration.
  • Completed GPU functional validation.
  • Completed /review-pr-team self-review and resolved findings.

@copy-pr-bot

copy-pr-bot Bot commented Aug 13, 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.

@seonjinn seonjinn added CI:L1 Run doctests, unit tests, and functional tests Documentation Improvements or additions to documentation labels Aug 13, 2026
@seonjinn

Copy link
Copy Markdown
Contributor Author

Self-review (/review-pr-team) completed on 60b5c936d38c997a1c654e3d0c70ef3ee7205fb1.

Resolved findings:

  • Reject overlap_cpu_optimizer_d2h_h2d=true when optimizer CPU offload is disabled, avoiding a silent no-op.
  • Added the new overlap field to in-repo config fixtures and covered both policy and value-worker optimizer-placement lifecycles.
  • Documented the CPU-Adam bottleneck at high offload fractions and the transfer-overlap mitigation.

Direct Ruff, formatting, YAML parsing, Python compilation, and config validation checks pass. The remaining readiness gate is the Linux/GPU functional and off/50%/100% performance validation; the PR remains draft until that evidence is attached.

@seonjinn

Copy link
Copy Markdown
Contributor Author

/ok to test 60b5c93

@seonjinn

Copy link
Copy Markdown
Contributor Author

/ok to test 640283b

@seonjinn

Copy link
Copy Markdown
Contributor Author

/ok to test cf3cfd8

@seonjinn
seonjinn marked this pull request as ready for review August 13, 2026 21:28
@seonjinn
seonjinn requested review from a team as code owners August 13, 2026 21:28
@seonjinn
seonjinn requested a review from a team as a code owner August 13, 2026 22:39
@seonjinn

Copy link
Copy Markdown
Contributor Author

/ok to test 04f286f

@seonjinn

Copy link
Copy Markdown
Contributor Author

/ok to test 71ae2ed

@seonjinn

seonjinn commented Aug 13, 2026 •

Copy link
Copy Markdown
Contributor Author

Optimizer CPU Offload A/B Results

Result

CW job 15725145 completed four 100-step cases on one H100 GPU at the final
PR head. The primary window excludes the first ten startup steps and contains
90 samples per case.

Case Mean p50 p90 p99 Delta vs disabled Policy training Max sampled GPU memory GPU memory saved
Disabled 0.752s 0.749s 0.774s 1.034s baseline 0.752s 15.24 GiB baseline
50%, no transfer overlap 1.187s 1.172s 1.206s 1.656s +57.75% 1.186s 14.13 GiB 1.11 GiB
50%, transfer overlap 1.216s 1.195s 1.242s 1.614s +61.61% 1.215s 14.65 GiB 0.59 GiB
100%, transfer overlap 1.678s 1.656s 1.708s 2.124s +122.94% 1.677s 10.53 GiB 4.71 GiB

The slowdown remains stable when the analysis begins at steps 21, 41, or 61.
At 50% offload, transfer overlap was 2.45% slower than no overlap over steps
11-100. This supersedes the eight-step pilot, where overlap appeared 7.51%
faster; the pilot window was too short for that conclusion.

Interpretation

  • Fractional and full optimizer CPU offload execute successfully through
    Megatron Core's HybridDeviceOptimizer.
  • Greater offload fractions reduce sampled GPU memory, with full offload
    showing the clearest reduction.
  • The performance cost is almost entirely inside policy training. NeMo RL
    dispatch overhead is negligible in this microbenchmark.
  • Transfer overlap is not beneficial for this small, single-GPU workload. It
    may behave differently when transfer size and available compute overlap are
    larger, so this is not a multi-GPU production-throughput claim.
  • All 400 recorded losses are finite. The largest absolute difference from
    the disabled trajectory is 4.221e-3; this is a numerical sanity check, not
    a convergence claim.

Configuration

  • Model: Qwen/Qwen3-0.6B
  • Sequence length: 1024
  • GBS/MBS: 8/1
  • Parallelism: TP1, PP1, CP1
  • Sequence packing: disabled
  • Distributed and precision-aware optimizer: enabled
  • Validation, checkpointing, and W&B: disabled
  • Measurement window: steps 11-100

Provenance

  • Cluster: cw-dfw-cs-001
  • SLURM job: 15725145
  • Allocation: one node, one H100 GPU
  • Result: COMPLETED, exit code 0:0, elapsed 00:47:34
  • PR commit: ee766da42275892d4c0df4be51cb3596b3ffe73d
  • Container:
    /lustre/fs1/portfolios/coreai/projects/coreai_dlalgo_nemorl/users/sna/containers/nemo_rl_nightly_optimizer_offload_60b5c936_20260813_15710559.sqsh
  • Raw results:
    /lustre/fs1/portfolios/coreai/projects/coreai_dlalgo_nemorl/users/sna/experiments/optimizer-cpu-offload-20260813/results_100step
  • Driver log:
    /lustre/fs1/portfolios/coreai/projects/coreai_dlalgo_nemorl/users/sna/experiments/optimizer-cpu-offload-20260813/direct1_100step_15725145.log

@seonjinn

Copy link
Copy Markdown
Contributor Author

/ok to test 11104a9

@seonjinn

Copy link
Copy Markdown
Contributor Author

/ok to test ee766da

@seonjinn
seonjinn requested review from terrykong and yuki-97 August 17, 2026 22:04
@seonjinn

Copy link
Copy Markdown
Contributor Author

/ok to test 788fcf0

@seonjinn

Copy link
Copy Markdown
Contributor Author

Contributor self-review refresh for 62a0356547febb9c3b1906db9d0ed627b391bec3 after the latest main merge.

An independent source audit found no actionable correctness issues in optimizer offload validation, policy/value lifecycle handling, defaults, or docs. Ruff/format/config checks pass locally. Residual validation: rerun the 0%/50%/100% GPU matrix on the current Bridge/MCore pins and add checkpoint save/resume coverage; the earlier performance run used older dependency pins.

@seonjinn

Copy link
Copy Markdown
Contributor Author

/ok to test c599b31

@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.

Reviewed by an agent team (6 reviewers plus an adversarial pass), checking every Megatron Core claim against the pinned SHA d12f6c8c9aff51e166d872fd70151687a8e3f375.

No action items — the two things we would have raised you already fixed yourself in 788fcf0 (dropping the , False call-site default from the .get(), and deleting the redundant optimizer_kwargs.setdefault(...)), which is also what config-conventions asks for. The added adam/sgd guard there is right too: Megatron Core only wires CPUAdam/CPUSGD into the hybrid optimizer, so anything else would have failed obscurely.

Thanks for the validation write-up — the 100-step A/B with an explicit measurement window, the note superseding the 8-step pilot, and the finite-loss check made this much easier to review.

Context — no action. Things we verified and deliberately are not raising, in case it saves a round trip:

  • The optimizer_cpu_offload → use_distributed_optimizer guard is correct and worth keeping. The combination it rejects fails with a KeyError on the first optimizer step: Float16OptimizerWithFloat16Params.__init__ overwrites the HybridDeviceOptimizer's own param_groups with fresh fp32 clones (optimizer.py#L1018), while HDO keyed param_to_inner_param on the original tensors (hybrid_optimizer.py#L189) and step() looks them up unguarded (#L339). Your docs sentence about the "parameter mapping" is accurate.
  • Removing assert optimizer_offload_fraction == 1.0 is right: Megatron Core has always accepted arbitrary fractions (HDO's own default is 0.5) and range-checks the field nowhere, so your 0 < f <= 1 check is the only validation that exists.
  • _force_sync_optimizer_fp32_from_model stays correct at f<1 — it iterates the HDO maps rather than assuming full coverage, and the precision-aware on/off branches turn out to be covered by complementary levels (level 3 when it is on, level 1 when it is off).
  • The greedy per-parameter partition rounds the realized offload fraction up, never down, so it can never leave more on the GPU than requested.
  • Config coverage is complete: every YAML declaring optimizer_cpu_offload got the new key except two defaults:-based override files, where omitting it is correct.

One thing you may want to note in the docs paragraph at some point (not blocking): with optimizer_cpu_offload: false NeMo RL moves the whole optimizer state to CPU before colocated generation (offload_before_refit, and grpo.py's offload_after_refit() under if colocated_inference:), and both are gated on not self.optimizer_cpu_offload — so a fraction below 1.0 skips that eviction entirely and can leave a higher generation-phase peak than turning offload off. The worker gating is unchanged on main; this PR is just what makes f<1 reachable.

Two pre-existing items worth a follow-up issue rather than this PR: the _force_sync_optimizer_fp32_from_model docstring describes the upstream gap backwards (_copy_model_params_to_main_params does level 3 only and returns early, distrib_optimizer.py#L3067) — the same error is in Megatron-Bridge's copy; and that helper now duplicates Bridge's public sync_hybrid_device_optimizer_fp32_master_copies.

Generated by Claude Code

@terrykong
terrykong enabled auto-merge (squash) August 18, 2026 07:00
@terrykong
terrykong merged commit 7fa6e55 into NVIDIA-NeMo:main Aug 18, 2026
99 checks passed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

CI:L1 Run doctests, unit tests, and functional tests Documentation Improvements or additions to documentation

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants