Skip to content

Share CUDA graph memory between training and validation - #5241

Merged
fegin merged 14 commits into
mainfrom
gh/fegin/184/head
Oct 17, 2026
Merged

fegin merged 14 commits into
mainfrom
gh/fegin/184/head

Conversation

@fegin

@fegin fegin commented Oct 9, 2026 •

Copy link
Copy Markdown
Contributor

Stack from ghstack (oldest at bottom):


Summary

Add optional validation CUDA graphs with validator.enable_cuda_graphs=True. Training, validation, and optimizer graphs share the existing memory pool. Capturing eval first lets its temporary buffers share storage with training gradients.

  • Keep scheduled step 1 eval. After training and optimizer warmup, run eager eval, then captured eval. This allows us to reuse the memory, otherwise we will see memory jump during the warmup.
  • Preserve memory reuse through _CUDAGraphGradientState.
  • Prepare PP metadata outside capture and finish PP/FSDP eval cleanup.
  • Wait for checkpoint staging before eval can update model buffers.
  • Document tensor lifetimes in cuda_graph.md

Memory usage

Peak allocated memory per GPU for muse glimmer 30B:

• Training only: 59.024 GiB.
• Original main train/eval (w/o cudagraph): 61.531 GiB.
• This PR's train/eval (w/ cudagraph): 61.530 GiB.

fegin added 2 commits October 9, 2026 11:43
[ghstack-poisoned]
[ghstack-poisoned]
@pytorch-bot pytorch-bot Bot added the ciflow/rl label Oct 9, 2026
@meta-cla meta-cla Bot added the CLA Signed This label is managed by the Meta Open Source bot. label Oct 9, 2026
fegin added 2 commits October 12, 2026 00:18
[ghstack-poisoned]
[ghstack-poisoned]
fegin added a commit that referenced this pull request Oct 12, 2026
- Capture eval before training with the existing shared pool.
- Use real validation runs for warmup and keep scheduled step 1 eval.
- Prepare PP metadata outside capture and finish PP/FSDP eval cleanup.
- Reject eval capture in unsupported trainers and document tensor lifetimes.
- Add CPU and GPU tests for capture order, numerics, and memory reuse.

CPU and GPU tests passed. Full Muse Glimmer 30B matched eager over 10 updates on 8 GPUs.

ghstack-source-id: 8331835
Pull-Request: #5241
fegin added 2 commits October 12, 2026 12:05
[ghstack-poisoned]
[ghstack-poisoned]
fegin added a commit that referenced this pull request Oct 12, 2026
- Capture eval before training with the existing shared pool.
- Use real validation runs for warmup and keep scheduled step 1 eval.
- Prepare PP metadata outside capture and finish PP/FSDP eval cleanup.
- Reject eval capture in unsupported trainers and document tensor lifetimes.
- Add CPU and GPU tests for capture order, numerics, and memory reuse.

CPU and GPU tests passed. Full Muse Glimmer 30B matched eager over 10 updates on 8 GPUs.

ghstack-source-id: 0891679
Pull-Request: #5241
@fegin
fegin marked this pull request as ready for review October 12, 2026 19:07
@pytorch-bot pytorch-bot Bot added the ciflow/fake-pg Run 1-GPU Fake PG integration tests label Oct 12, 2026
[ghstack-poisoned]
fegin added a commit that referenced this pull request Oct 12, 2026
- Capture eval before training with the existing shared pool.
- Use real validation runs for warmup and keep scheduled step 1 eval.
- Prepare PP metadata outside capture and finish PP/FSDP eval cleanup.
- Reject eval capture in unsupported trainers and document tensor lifetimes.
- Add CPU and GPU tests for capture order, numerics, and memory reuse.

CPU and GPU tests passed. Full Muse Glimmer 30B matched eager over 10 updates on 8 GPUs.

ghstack-source-id: feba0b9
Pull-Request: #5241
fegin added 2 commits October 14, 2026 13:57
[ghstack-poisoned]
[ghstack-poisoned]
fegin added a commit that referenced this pull request Oct 14, 2026
- Capture eval before training with the existing shared pool.
- Use real validation runs for warmup and keep scheduled step 1 eval.
- Prepare PP metadata outside capture and finish PP/FSDP eval cleanup.
- Reject eval capture in unsupported trainers and document tensor lifetimes.
- Add CPU and GPU tests for capture order, numerics, and memory reuse.

CPU and GPU tests passed. Full Muse Glimmer 30B matched eager over 10 updates on 8 GPUs.

ghstack-source-id: 75e1c5b
Pull-Request: #5241
Comment thread docs/cuda_graph.md Resolved
Comment thread docs/cuda_graph.md Resolved
Comment thread docs/cuda_graph.md Resolved
Comment thread docs/cuda_graph.md Resolved
Comment thread docs/cuda_graph.md Resolved
Comment thread docs/cuda_graph.md Resolved
Comment thread torchtitan/trainer.py Resolved
Comment thread torchtitan/trainer.py Resolved
Comment thread torchtitan/trainer.py Resolved
fegin added 2 commits October 15, 2026 23:50
[ghstack-poisoned]
[ghstack-poisoned]
fegin added a commit that referenced this pull request Oct 16, 2026
- Capture eval before training with the existing shared pool.
- Run one validation pass per call and use real runs for warmup.
- Let CUDA graph wrappers prepare PP metadata outside capture.
- Finish PP/FSDP eval cleanup and reject capture in unsupported trainers.
- Document tensor lifetimes and test capture order, numerics, and memory reuse.

CPU and GPU tests passed. Full Muse Glimmer 30B has not been rerun for this revision.

ghstack-source-id: 310eece
Pull-Request: #5241
@fegin

fegin commented Oct 16, 2026

Copy link
Copy Markdown
Contributor Author

@tianyu-l I updated the design, the logic is still the same but make the decision self-contained in validator. Let's chat on this.

Comment thread torchtitan/training_engine.py Resolved
Comment thread torchtitan/distributed/CUDA_GRAPH.md Resolved
Comment thread torchtitan/distributed/CUDA_GRAPH.md Resolved
Comment thread torchtitan/trainer.py Resolved
Comment thread torchtitan/components/validator.py Resolved
Comment thread torchtitan/components/validator.py Resolved
Comment thread torchtitan/distributed/fsdp.py Resolved
Comment thread torchtitan/components/validator.py Resolved
Comment thread torchtitan/distributed/fsdp.py Resolved
@tianyu-l

Copy link
Copy Markdown
Contributor

@claude review this PR

@claude

claude Bot commented Oct 17, 2026 •

Copy link
Copy Markdown
Contributor

Claude finished @tianyu-l's task in 3m 13s —— View job


Review: Share CUDA graph memory between training and validation

  • Gather context (diff, CLAUDE.md)
  • Review core changes (cuda_graph.py, validator.py, trainer.py, training_engine.py)
  • Review PP/FSDP helpers and docs
  • Review tests
  • Post review

The current design is much simpler than the earlier version. The trainer no longer runs validation twice. The validator holds capture_allowed=False until every registered wrapper has warmed up, and its own second pass turns capture back on. I traced the call order: step 1 runs eager eval, step 2 captures eval on the first group and replays the rest, and step 3 captures training and the optimizer. This matches CUDA_GRAPH.md. The bit-exact PP+FSDP train/eval GPU test over 10 steps and 4 schedules covers the main risk well.

Below are the remaining concerns, most important first. I only read the code: I could not run Python, pytest or pre-commit in this sandbox, and I could not read the installed torch pipelining source.


1. PP stage has_backward is not restored after eval prepare (question / possible silent bug)

torchtitan/distributed/pipeline_parallel.py prepare_pipeline_schedule_for_cuda_graph:

schedule._has_backward = has_backward and not for_eval
try:
    for stage in stages:
        stage.has_backward = schedule._has_backward
    initialize(...)
finally:
    schedule._has_backward = has_backward   # stage.has_backward is NOT restored

After the eval prepare_for_capture runs, every stage keeps has_backward=False while the schedule says True.

  • With training capture: the training prepare_for_capture runs before training capture and sets the stages back to True. This path is fine.
  • PP + eager training + validator.enable_cuda_graphs=True: Trainer.Config.__post_init__ allows this setup. Here the next eager schedule.step() depends on torch detecting the mode change and re-initializing the stages. If it does not, backward could be skipped or misconfigured with no error.

The GPU test test_pp_fsdp_train_eval_shared_pool always captures training, so this path is untested. Please either restore stage.has_backward in the finally block, or add a PP case with eager training and eval capture (or reject that combination).

2. The single-flag request from the latest review is not addressed

@tianyu-l's approving review said: "in this PR let's use one flag to determine both training and eval". The code still has a separate validator.enable_cuda_graphs. CUDA_GRAPH.md:47-48 still justifies eval-only capture, and the __post_init__ coupling in trainer.py:91 still exists. One flag would also remove the eval-only path that causes concern #1, and the "eval-only capture" paragraphs in the doc. The other renames from that review are also still pending:

  • cuda_graph_per_accumulation_group -> cuda_graph_per_microbatch_group. The docstring and doc now say "microbatch group", but the flag name does not.
  • _init_evaluate_fn / _evaluate_body -> _init_validate_fn / _validate_body.
  • finish_fsdp_eval -> a CUDA-graph-explicit name.

3. Extra full validation passes at startup

Validator.should_validate returns True at every step until eval captures. That is at least 2 extra passes (steps 1 and 2) whatever freq is. The default is steps=-1, which consumes the whole validation dataset, so each pass can be expensive. Each pass also logs a validation metric at a step the user did not schedule. The doc mentions this, but a one-time logger.info would help users who see an unexpected eval at step 2. Alternatively, cap the warmup and capture passes at one microbatch group. One group is enough to warm up and capture, though it would mean not reporting a loss for those passes.

4. maybe_wait_for_staging only runs when eval graphs are enabled (trainer.py:503-508)

The comment says "Eval can update buffers that checkpoint staging reads". That applies to eager eval as well: any buffer written in forward, such as MoE load-balancing counters, races with async staging the same way. Either the wait is needed in both paths, or the comment should explain why capture specifically needs it.

5. finish_fsdp_eval and PP clear_runtime_states now run on the eager path too

validator.py:_evaluate_body calls finish_fsdp_eval and stage.clear_runtime_states() even when eval graphs are off. Both use private APIs (_get_fsdp_state, _modules_to_run_forward, _post_forward, _stage/_stages). This is probably correct, since it frees memory the old code held. Still, it changes behavior on the existing eager validation path, which CLAUDE.md asks us to protect. Please confirm that the existing validation integration tests (e.g. llama3_debugmodel_validation_tp2_cp2_pp2) still give identical losses.

Two related points:

  • The isinstance(PipelineScheduleSingle) / PipelineScheduleMulti stage-list logic now appears in both validator.py and pipeline_parallel.py. A small helper in pipeline_parallel.py, e.g. _get_schedule_stages(schedule), would remove the duplication. That follows CLAUDE.md "Reuse over duplication".
  • The fsdp.py comment "Loss can call one grouped module after the root forward ends" should name the concrete case: lm_head called from ChunkedLossWrapper with skip_lm_head=True, as @tianyu-l asked.

6. Minor

  • training_engine.py:248/272/510: _forward_backward_cuda_graph_enabled is only read on the line right after it is set. Make it a local variable or remove it.
  • validator.py:342: the validator passes max_num_documents and max_context_length=self.seq_len, but not **preprocess_inputs_kwargs or global_routing_token_counts the way training does (training_engine.py:675-678). That is probably fine for eval. Just confirm that no model needs global_routing_token_counts to keep eval shapes static under capture.
  • cuda_graph.py: renaming _CUDAGraphManager to the public CUDAGraphManager / cuda_graph_manager, and run_eager_on_cuda_graph_stream to private, are API changes. Check for out-of-tree users; grep found none in-tree.
  • CUDAGraphManager.teardown() no longer has the if not self._initialized: return guard, and TrainingEngine.close() now always calls it. That is fine because teardown only touches Python state. Moving teardown after checkpointer.close() also keeps the GraphTrainer stash-free ordering correct. Nice.
  • validate() now saves and restores each module's training flag instead of calling model.train(). This is an improvement, since modules that were already in eval mode stay that way. It is still a quiet behavior change worth one line in the PR description.

Tests

  • Good coverage overall: the CPU gate and config tests, the bit-exact PP schedules ×4, varlen eval replay, grouped-FSDP cleanup, and the eval-first workspace reuse test.
  • Gaps: PP + eager training + eval capture (Add profiler #1), and an integration test with PP. shared_eval_cuda_graph is FSDP-only.

fegin added 2 commits October 16, 2026 22:57
[ghstack-poisoned]
[ghstack-poisoned]
fegin added a commit that referenced this pull request Oct 17, 2026
- Capture eval before training with the existing shared pool.
- Run one validation pass per call and use real runs for warmup.
- Let CUDA graph wrappers prepare PP metadata outside capture.
- Finish PP/FSDP eval cleanup and reject capture in unsupported trainers.
- Document tensor lifetimes and test capture order, numerics, and memory reuse.

CPU and GPU tests passed. Full Muse Glimmer 30B has not been rerun for this revision.

ghstack-source-id: ead5181
Pull-Request: #5241
@pytorch-bot pytorch-bot Bot added the ciflow/b200 Trigger B200 CI label Oct 17, 2026
@fegin

fegin commented Oct 17, 2026

Copy link
Copy Markdown
Contributor Author

Response to Claude's review

  1. PP stage flags
    PyTorch sets stage.has_backward at each schedule.step() call. It also
    rebuilds metadata when the mode changes. We did not find a missing
    restoration bug, so we did not add another restoration step.

  2. Flags and names
    Validation now follows training's capture mode. We removed
    validator.enable_cuda_graphs and applied the requested method and
    microbatch-group names. Unsupported validation paths remain eager and warn.

  3. Startup validation
    Step 1 is already part of the normal validation schedule. Capture can add
    validation at step 2 if it is not scheduled. We kept full validation passes
    and their reported losses.

  4. Checkpoint staging
    We removed the validation staging wait. We found no validation writes to
    checkpointed model or optimizer tensors. MoE usage counters are training-
    only and nonpersistent. The existing wait before optimizer updates remains.

  5. Eager cleanup
    We kept cleanup in the shared validation body. We do not claim that eager
    numerical correctness requires it. The grouped-FSDP test now covers the
    actual chunked-loss sequence and subsequent training. Its eager reference
    does not call the cleanup helper.

  6. Other suggestions
    The engine's capture-mode field now supplies the validator's mode, so it is
    no longer a one-use field. Routing token counts serve training-only
    auxiliary losses in the inspected router.

[ghstack-poisoned]
fegin added a commit that referenced this pull request Oct 17, 2026
- Capture eval before training with the existing shared pool.
- Run one validation pass per call and use real runs for warmup.
- Let CUDA graph wrappers prepare PP metadata outside capture.
- Finish PP/FSDP eval cleanup and reject capture in unsupported trainers.
- Document tensor lifetimes and test capture order, numerics, and memory reuse.

CPU and GPU tests passed. Full Muse Glimmer 30B has not been rerun for this revision.

ghstack-source-id: e80e2f4
Pull-Request: #5241
@fegin
fegin changed the base branch from gh/fegin/184/base to main October 17, 2026 06:53
@fegin
fegin merged commit 3c7b0c9 into main Oct 17, 2026
@github-actions github-actions Bot mentioned this pull request Oct 17, 2026
wwwjn added a commit to wwwjn/torchtitan that referenced this pull request Oct 19, 2026
pytorch#3980 made PP preprocessing return (arg_mbs, kwarg_mbs, target_mbs,
loss_kwarg_mbs), but two callers still unpacked three values:

- TrainingEngine's prepare_for_capture (PP + CUDA graphs, from pytorch#5241)
  raised "too many values to unpack" in every PP integration test. It now
  passes the first microbatch's loss arguments to schedule initialization,
  which calls the loss on that microbatch, as the real step does.
- GraphTrainer PP reuses the core preprocessing, so its forward-backward
  loop failed the same way. Per-microbatch loss arguments are rejected
  there, so the PP branch drops the empty fourth element.

The CPU test for prepare_for_capture still fed the old 3-tuple, which hid
the mismatch; it now uses the PP layout and checks the loss arguments.
wwwjn added a commit that referenced this pull request Oct 19, 2026
…x per layer (#5547)

**TLDR:** Two CI fixes for the GraphTrainer and 8 GPU Integration jobs.
1. Fixes #5366. The Flex eager-vs-trace bitwise tests compiled flex once
per layer in the eager reference, and after 8 graphs Dynamo silently ran
unfused eager flex. The traced side was correct; the eager reference
changed. With this PR the eager reference compiles flex once, like the
core and RL trainers, and hitting the recompile limit raises instead of
falling back.
2. Fixes PP after #3980. #3980 made PP preprocessing return 4 values,
but two callers still unpacked 3, so every PP + CUDA graph integration
test and the GraphTrainer PP numerics test fail on main with
`ValueError: too many values to unpack (expected 3)`.

## 1. Flex bitwise tests compiled flex per layer (#5366)

**Problem**
1. **The eager reference was annotated.** `_run_steps` called
`annotate_graph_trainer_model` for both `Trainer` and `GraphTrainer`. It
wraps every submodule's forward with `annotate_fn({"module_fqn": fqn})`.
Only GraphTrainer's graph passes read these tags. The core and RL
trainers never set them.
2. **Dynamo now guards on the annotation.** pytorch/pytorch#198959
(October 10 nightly, the first failing one) adds an `FX_ANNOTATION`
guard. Each layer's `inner_attention` has a different `module_fqn`, so
the eager compiled flex compiles once per layer: 8 graphs for Qwen3
debugmodel_moe, all identical.
3. **The graphs carry over between tests.** Dynamo caches them on
`flex_attention`'s code object, which outlives the `torch.compile`
wrapper rebuilt in `setUp`. Llama3 Flex leaves 6. Qwen3 MoE Flex then
passes the limit of 8 at its third layer.
4. **Silent fallback.** Past the limit, Dynamo runs flex eagerly, which
is the unfused implementation, so the eager loss changes: `hit
config.recompile_limit (8)`, then `eager vs aot_fx_trace: loss
mismatch`.

**Solution**
1. **Annotate only GraphTrainer runs.** The eager reference stays
unannotated, like the core and RL trainers.
2. **`fullgraph=True` and `recompile_limit=16`** on the test's flex
compile, the same settings as #5442. Hitting the limit raises instead of
falling back.
3. **`torch._dynamo.reset()` in `setUp`.** Tests no longer share flex
graphs.
4. **Unchanged:** the GraphTrainer runs, their annotations, and every
assertion.

## 2. PP callers still unpacked 3 values after #3980

**Problem**
1. #3980 made `TrainingEngine._preprocess_microbatch_group` return
`(arg_mbs, kwarg_mbs, target_mbs, loss_kwarg_mbs)` under PP.
2. `prepare_for_capture` (PP + CUDA graphs, added by #5241 before #3980
landed) still unpacked 3 values. Every PP test in the 8 GPU features job
fails there: 3d, pp_1f1b, pp_dp_tp, pp_looped_zero_bubble, lora, and
others. On main, that job passes at #3980's parent `efdde5eda` and fails
at #3980 `a4a62b349`.
3. GraphTrainer PP reuses the core preprocessing, and its
forward-backward loop also unpacked 3 values, so
`test_dense_llama3_hsdp_graph_pp_vs_eager` fails. The GraphTrainer job
uses `set -eux`, so it stops there and never reaches
`test_bitwise_deterministic.py`.
4. The CPU test for `prepare_for_capture` still fed the old 3-tuple,
which hid the mismatch.

**Solution**
1. **`prepare_for_capture`** unpacks 4 values and passes the first
microbatch's loss arguments plus `global_loss_token_counts` to schedule
initialization. Initialization calls the loss on that microbatch, as the
real step does.
2. **GraphTrainer PP** drops the fourth element. GraphTrainer rejects
per-microbatch loss arguments earlier, so it is always empty, and both
paths now return `(arg_mbs, kwarg_mbs, target_mbs)`, as before #3980.
3. **The CPU test** feeds the PP layout with a per-microbatch loss
argument and checks the loss arguments passed to initialization. It
fails without the fix with the same `ValueError`.

## Results
```text
torch 2.16.0.dev20261019+cu132, GB200 (2 GPUs), flash-attn-4

1. Llama3 Flex -> Qwen3 MoE Flex test_aot_fx_trace_vs_eager, in one process
main:     "hit config.recompile_limit (8)", then
          eager vs aot_fx_trace: loss mismatch: 6.995096683502197 vs 6.995151519775391
this PR:  pass, 1 flex graph per test, eager == traced == 6.995151519775391

flex graphs after the Qwen3 MoE Flex eager run (test run alone)
annotated eager (main):  8 (one per layer)
unannotated eager:       1, same loss

Full test_bitwise_deterministic.py
main:     recompile limit hit once; on GB200 it breaks
          TestDSv3FlexAttnBitwiseDeterministic::test_aot_fx_trace_vs_eager and
          ::test_ep_chunk_matches_eager_chunking_bitwise
this PR:  16 passed (Varlen and Flex), 9 skipped, no recompile limit hit

2. PP
pp_1f1b integration test (2 GPUs, PP + CUDA graphs)
main:     ValueError in prepare_for_capture
this PR:  10 steps pass

GraphTrainer PP (the HSDP+PP numerics config reduced to PP=2, 2 GPUs)
main:     ValueError in GraphTrainer _forward_backward_body
this PR:  trains
```

You may ask: does the core trainer recompile flex per layer too? No.
Llama3 1B (16 layers) with flex on the core `Trainer` compiles flex once
and never recompiles. Only an annotated eager model recompiles per
layer.

NOTE: GraphTrainer's validator runs the annotated model eagerly, so Flex
validation on a model with more than 8 layers should hit the same
per-layer recompiles. Not covered here.
NOTE: `test_dense_llama3_hsdp_graph_pp_vs_eager` needs 8 GPUs, so I
could not run it locally. On the PP=2 reduction, eager PP vs GraphPP
misses its grad_norm tolerance (max 1.7e-4) both with this PR and at
#3980's parent, so that gap comes from the reduced config, not this PR.
The full 8 GPU test passed on main before #3980.

**Test plan**
- `pytest
torchtitan/experiments/graph_trainer/tests/test_bitwise_deterministic.py`:
16 passed, 9 skipped.
- The Llama3 Flex -> Qwen3 MoE Flex pair from #5366 passes in one
process.
- `python -m tests.integration_tests.run_tests <out> --test_suite
features --test_name pp_1f1b --ngpu 2`: passes; fails on main.
- `pytest tests/unit_tests/cpu/test_trainer.py
tests/unit_tests/cpu/distributed/test_cuda_graph.py
tests/unit_tests/cpu/components/test_validator.py
tests/unit_tests/cpu/distributed/test_pipeline_parallel.py`: 135 passed.
- CI: GraphTrainer 8 GPU and 8 GPU Integration (features) jobs.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

ciflow/b200 Trigger B200 CI ciflow/fake-pg Run 1-GPU Fake PG integration tests ciflow/rl CLA Signed This label is managed by the Meta Open Source bot.

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants