Skip to content

Capture the full training step, optimizer included, in GraphTrainer - #5626

Open
jemitche1 wants to merge 6 commits into
pytorch:mainfrom
jemitche1:jerome_m/feature/graph-trainer-optimizer-capture
Open

jemitche1 wants to merge 6 commits into
pytorch:mainfrom
jemitche1:jerome_m/feature/graph-trainer-optimizer-capture

Conversation

@jemitche1

@jemitche1 jemitche1 commented Oct 26, 2026 •

Copy link
Copy Markdown
Contributor

Summary

This PR lets graph trainer trace gradient clipping and optimizer.step() into the same graph as the forward and backward passes, so optim.enable_accelerator_graph = True replays the whole training step as one graph instead of being rejected.

Problem

GraphTrainer traces forward, loss, and backward into one graph, but rejects
optim.enable_accelerator_graph, so the optimizer always runs eagerly after
the graph.

config = graph_trainer_llama3_debugmodel()
config.optim.enable_accelerator_graph = True
# main: ValueError, GraphTrainer rejects the flag
# this PR: forward, backward, clipping, the non-finite check, and
#          optimizer.step() run as one graph per training step

What changed

  • TracedOptimizerUpdate (traced_optimizer.py) traces the existing
    Optim._update into the joint SPMD graph, so there is one copy of the update
    logic. Optim.step still runs the first-step sync, LR scheduler, and EMA;
    only its update slot returns the grad norm the graph produced.
  • Optimizer state is threaded through the graph like parameters and buffers:
    torch.optim.swap_in_optimizer_params_and_state swaps it in, so state
    tensors become graph inputs that the traced optimizer.step() updates in
    place. State is read without state-dict hooks (a device lr stays a live
    input) and counts as static input for graph capture.
  • The dead-code pass dropped every aten._assert_async, silently removing the
    optimizer's non-finite guard; asserts traced from the optimizer update are
    now kept.
  • Unsupported combinations raise ValueError: PP, SDC replay,
    sac_and_paged_stash, and precompiled artifacts at config time; gradient
    accumulation in the engine; optimizers with step hooks when the update is
    built.
  • The engine waits for async checkpoint staging before the step graph runs,
    because the graph writes parameters and optimizer state.
  • Mechanical (safe to skim): optimizer_update threaded through the graph
    builders and runtime factories (graph_builder.py, graph_pp/pipeline.py,
    spmd_gradient_accumulation_graph_builder.py), and minimal_fx_tracer /
    run_traced / extract_train_state take optimizers: Sequence[Optimizer].

User-facing changes

Before After
optim.enable_accelerator_graph = True raises in GraphTrainer The optimizer update runs inside the step graph (SPMD, no gradient accumulation)

Numerics

Debug model, seed 42, deterministic=True, regional Inductor, 30 steps:

Comparison Layout Loss and grad_norm
In the step graph vs Optim capturing its own graph (both capturable=True) FSDP2xTP2, FSDP2 bitwise identical
In the step graph, repeated runs FSDP2xTP2, FSDP2 bitwise identical
Captured vs uncaptured FSDP2, FSDP2xTP2 bitwise identical

Flag off vs on is not bitwise equal because the flag switches AdamW to
capturable=True with a device lr, which rounds differently from the second
update on. A NaN injected into a parameter stops training at the next step.

Memory and performance

Llama 3 8B, FSDP2xTP4, seq 4096, regional Inductor, same node, mean of steps
26-30:

Optimizer Peak memory tps
Eager 19.69 GiB 623.2
Optim captures its own graph 20.09 GiB 622.6
In the step graph (this PR) 18.32 GiB 630.4

Peak memory drops 7% with no throughput cost, while a separate optimizer
graph adds memory. Measured on one backend; the implementation is
backend-agnostic (torch.accelerator).

Testing

  • test_waits_for_staging_before_traced_update: the step graph does not run
    while async checkpoint staging still reads parameters.
  • TestTraceCapturableOptimizers: traced vs eager parity with several
    optimizers and a device lr (catches lr frozen into the graph).
  • test_dead_code_elimination_keeps_optimizer_update_assert: catches the
    non-finite guard being stripped.
  • Removed test_graph_training_engine_rejects_optimizer_accelerator_graph,
    which asserted the error this PR removes.
  • llama3_fsdp_tp integration config now enables the flag.

@meta-cla meta-cla Bot added the CLA Signed This label is managed by the Meta Open Source bot. label Oct 26, 2026
@jemitche1
jemitche1 force-pushed the jerome_m/feature/graph-trainer-optimizer-capture branch from 9266ce5 to bd2dd5d Compare October 29, 2026 16:00
@jemitche1
jemitche1 marked this pull request as ready for review October 29, 2026 16:00
@jemitche1
jemitche1 requested a review from tianyu-l as a code owner October 29, 2026 16:00
@pytorch-bot pytorch-bot Bot added the ciflow/fake-pg Run 1-GPU Fake PG integration tests label Oct 29, 2026
@pytorch-bot

pytorch-bot Bot commented Oct 29, 2026

Copy link
Copy Markdown

The following ciflow label(s) have been added but CI has not been triggered yet because the workflows are awaiting approval:

  • ciflow/fake-pg

Once a maintainer approves the workflows (scroll to the bottom of the PR page), the corresponding CI jobs will be triggered automatically. Please ping one of the reviewers if you do not have access to approve and run workflows.

Comment thread tests/unit_tests/cpu/test_trainer.py Resolved
@jemitche1

Copy link
Copy Markdown
Contributor Author

@tianyu-l could I receive a review for this PR? I would appreciate any feedback.

@tianyu-l

tianyu-l commented Nov 4, 2026

Copy link
Copy Markdown
Contributor

@claude review

@claude

claude Bot commented Nov 4, 2026 •

Copy link
Copy Markdown
Contributor

Claude finished @tianyu-l's task in 6m 9s —— View job


Request changes: see the review posted on this PR.

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

Verdict: Request changes -- the PR shows no numerics or perf evidence, doesn't compare against the much smaller two-graph option, and copies Optim's update logic into a second place that #5728 is about to change.

What this PR does. In GraphTrainer, setting optim.enable_accelerator_graph = True used to raise. Now it traces gradient clipping, the loss/grad-norm finite check, and optimizers.step() into the SPMD joint fwd+bwd graph. The graph returns (loss, grad_norm) instead of (loss, *grads), and the LR scheduler and EMA still run eagerly afterwards. PP, gradient accumulation, SDC replay, paged stash, precompile artifacts, and optimizer step hooks are all rejected.

Example.

# GraphTrainer, SPMD FSDP+TP, 1 microbatch, optim.enable_accelerator_graph = True
main: GraphTrainingEngine.__init__ -> ValueError("Optim CUDA graphs are not supported with GraphTrainer.")
PR:   graph(inputs) = fwd -> loss -> bwd -> clip_grad_norm_ -> assert finite -> optimizers.step()
                      -> (loss, grad_norm)          # grads never land in param.grad
      eager after replay: lr_schedulers.step(); ema.step()
      MoE load balancing / qk_clip / bf16 moments (step hooks) -> ValueError at first trace

Must fix

  1. Description. The description is one sentence. It has no "Summary (human-written)" section, no problem statement, no testing section, and no numerics. Please add:
    • Numerics: a bitwise loss and grad_norm comparison between enable_accelerator_graph on and off, with seed=42, deterministic=True (FSDP+TP is enough).
    • Value: a measured benefit (step time and/or peak memory).
    • Alternative: why this design over the smallest option, which is deleting the ValueError and letting Optim capture its own accelerator graph, as the eager trainer does (two graphs instead of one, about 2 LoC versus +457 net). If the gain is memory (grads die inside the graph) or overlap, the numbers should show it. Unverified whether the two-graph option works as-is.
  2. trainer.py:252 -- second copy of Optim.step/Optim._update. It will drift apart from the original, and #5728 (grad division moving into optim_step) would silently change numerics on whichever PR lands second. It also already drops the first-step sync.
  3. Validation is spread across four places:
    • spmd_graph_builder.py:237 -- the precompile check belongs in Config.__post_init__.
    • pipeline.py:756 -- the grad-accum check belongs in the engine, where num_microbatches is computed.
    • traced_optimizer.py:45 -- the PP check can never fire; delete it.

Should consider

  • trainer.py:250 -- optim_step gets the trace span twice on the default path.
  • make_fx_tracer.py:229 -- take only Sequence[Optimizer] and always return a list.
  • test_trace_module.py:1319 -- drop the three raise-only tests.
  • optimizer_update is threaded through about 10 functions, each with = None. Making it keyword-required in the private helpers would stop a caller from silently dropping it.

Questions

  • Rather than keeping a copy in TracedOptimizerUpdate, should Optim._update become traceable (take the parameters, reduce the finite flag with funcol)? That touches core, so it's a maintainer call, but it would remove both copies.
  • Does llama3_fsdp_tp (now with the flag on) check against golden losses? If not, nothing in CI ties traced-optimizer numerics to the eager optimizer at model scale.
Details
  • Gate: the problem is real (the flag raises on main), and the change is in the experiment folder, so it doesn't touch core. What's missing is evidence of value and a comparison with the existing Optim graph path.
  • Checked and OK:
    • Hooks are registered in _initialize_optim before _initialize_forward_backward, so the step-hook rejection sees them.
    • Tracing is lazy (at the first step), so it happens after load_checkpoint.
    • accumulate_param_grads_ skips the [None] placeholders.
    • The lazily created Optim._run_update graph wrapper is never instantiated, so all_wrappers_warmed_up isn't blocked.
    • Default fused=True AdamW traces the fused op, so no foreach/single-tensor switch is expected on the main path.
  • grad_norm reaches optim_step through a side channel (record_grad_norm). It's acceptable inside the experiment, but it relies on forward_backward running exactly once per optim_step.

Not verified: GPU numerics, FSDP+TP integration behavior, and whether skipping the first-step empty_cache affects peak memory.

Comment on lines +252 to +260
if self._optimizer_update is None:
return super().optim_step()
current_step = self.num_completed_steps + 1
grad_norm = self._optimizer_update.recorded_grad_norm()
self.optim.lr_schedulers.step()
if self.optim.ema is not None:
self.optim.ema.step(current_step)
self.num_completed_steps = current_step
return grad_norm

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.

This is a second copy of Optim.step's tail, and TracedOptimizerUpdate.__call__ is a second copy of Optim._update. The two copies will drift apart, and you can see it happening already:

Please coordinate with #5728 so the traced path does the division inside the graph, before clip_grad_norm_. Also either restore the first-step sync or explain why the traced path doesn't need it. At minimum, put a comment on each copy that names the eager function it mirrors.

@SherlockNoMad

Copy link
Copy Markdown
Contributor

can you explain the motivation for this PR? especially why is this helpful for Intel XPU? ( I suppose XPU is your optimization target)

I am supportive of having a path to include optimizer.step() in the training graph. TPU has already demonstrated an implementation, and I need to understand the design space for the tracer frontend, especially the optimizer state handling.

Also would appreciate an agent design doc before I read the code.

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

some questions

@jemitche1
jemitche1 force-pushed the jerome_m/feature/graph-trainer-optimizer-capture branch from bd9ed78 to 6d938fa Compare November 5, 2026 18:16
@jemitche1

Copy link
Copy Markdown
Contributor Author

@SherlockNoMad Thanks for taking a look!

With the optimizer in the step graph, the whole training step runs as one graph and optim.enable_accelerator_graph works in GraphTrainer instead of raising. The measured benefit is memory: on Llama 3 8B (FSDP2, TP4, seq 4096, regional Inductor), peak memory per rank drops from 19.69 to 18.32 GiB (7%), with throughput unchanged to slightly better (630.4 vs 623.2 tps). A separate optimizer graph raises memory to 20.09 GiB.

XPU is where I measured, but the change is backend agnostic (torch.accelerator). Also, would be interested in measurements from another backend.

For optimizer state, the tracer handles it like parameters and buffers: torch.optim.swap_in_optimizer_params_and_state swaps it in, so state tensors become graph inputs that the traced optimizer.step() updates in place. It is materialized before tracing so the graph signature is fixed, and per-step values (step, lr) must be device tensors (capturable=True). Could you point me to the TPU implementation? I'd like to compare its state handling.

@jemitche1

Copy link
Copy Markdown
Contributor Author

@SherlockNoMad

Summary

GraphTrainer traces forward, loss, and backward into one graph but rejects optim.enable_accelerator_graph, so the optimizer runs eagerly afterwards. This PR traces the existing Optim._update (clipping, the non-finite check, optimizer.step()) into the same graph, so one graph covers the whole step.

How it works

The traced step runs forward, loss, backward, then Optim._update(loss), and returns [loss, grad_norm]. Because it traces the method the eager path already uses, there is one copy of the update logic. TracedOptimizerUpdate points Optim.parameters at the traced parameters during tracing and keeps the non-finite assert from being removed by dead-code elimination. Optim.step still runs the first-step sync, LR scheduler, and EMA eagerly.

Optimizer state

State is handled like parameters and buffers, as graph inputs:

  • torch.optim.swap_in_optimizer_params_and_state swaps the live state in during tracing; tensors become graph inputs, hyperparameters constants.
  • State is read without state-dict hooks, so a device lr stays a live input instead of being frozen as a float.
  • State is initialized before tracing, so the graph signature is fixed.
  • The traced optimizer.step() updates the live tensors in place; the engine waits for async checkpoint staging before the step runs.
  • Per-step values (step, lr) must be device tensors (capturable=True), and state tensors are static inputs for graph capture.

Alternatives

  • Separate optimizer graph: uses more memory and is no faster.
  • Reimplementing the update: a second copy that would drift from Optim.
  • Functional optimizer API: needs a functional variant of every optimizer; swapping reuses torch.optim unchanged.

Results

Llama 3 8B, FSDP2xTP4, seq 4096, regional Inductor:

Optimizer Peak memory tps
Eager 19.69 GiB 623.2
Separate graph 20.09 GiB 622.6
In the step graph 18.32 GiB 630.4

Peak memory drops 7% with no throughput cost. Numbers are from one backend; the implementation is backend-agnostic (torch.accelerator).

@jemitche1
jemitche1 force-pushed the jerome_m/feature/graph-trainer-optimizer-capture branch from 6d938fa to 397146e Compare November 10, 2026 04:32
@jemitche1

Copy link
Copy Markdown
Contributor Author

Thanks for the discussion, @SherlockNoMad! I've addressed your comments and pushed the latest changes. When you have a chance, could you take another look?

@tianyu-l

Copy link
Copy Markdown
Contributor

@claude review again

@claude

claude Bot commented Nov 17, 2026 •

Copy link
Copy Markdown
Contributor

Claude finished @tianyu-l's task in 4m 47s —— View job


Request changes: see the review posted on this PR.

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

Verdict: Request changes -- the design problems from the last review are fixed (one copy of the update logic, validation at config time), but there is still no numerics proof, and open PR #5728 would silently break the traced path.

What changed since the last review. TracedOptimizerUpdate no longer keeps its own copy of the update logic. It now traces the real Optim._update, with Optim.parameters pointed at the traced parameters while tracing. The engine replaces Optim._run_update with a function that returns the grad norm recorded from the graph, so Optim.step still runs the first-step sync, the LR scheduler and EMA. The _assert_async in the update is annotated so dead-code elimination keeps it.

Example.

# GraphTrainer, FSDP4 x TP2, 1 microbatch, optim.enable_accelerator_graph = True
forward_backward: wait for checkpoint staging -> graph(fwd, loss, bwd, Optim._update) -> (loss, grad_norm)
optim_step:       Optim.step -> first-step sync -> _run_update = recorded grad_norm -> lr_schedulers.step -> ema.step

Earlier must-fix items

  • Second copy of Optim._update: resolved. The first-step sync is back, since Optim.step runs it.
  • Validation in four places: resolved. The precompile check is in __post_init__, the grad-accum check is in the engine, and the dead PP check is gone.
  • Description and numerics: still open (item 1 below).
  • Coordination with #5728: still open, now more specific (item 2).

Must fix

  1. Description and numerics. The PR body is still one sentence. The summary, the memory/tps table, and the comparison with the two-graph option are only in a comment. Please move them into the description, with the "Summary (human-written)" section. Also still missing is the bitwise loss and grad_norm comparison between the flag on and off (seed=42, deterministic=True, FSDP+TP), per "Validating Numerics".
  2. Conflict with #5728. #5728 divides the gradients in TrainingEngine.optim_step by iterating parameter.grad for self.optim.parameters. It also turns the loss into a sum. On this PR's traced path, parameter.grad is never set on the live parameters, and the graph has already clipped and applied the update before optim_step runs. So whichever PR lands second leaves the traced path updating with gradients that were never divided by the token count, which is wrong by that factor. Nothing raises. Please agree with the #5728 author where the division happens on this path (inside the graph, before clip_grad_norm_, which needs the global count as a graph input), or have the traced path raise until that is settled.
  3. trainer.py:173 -- the integration relies on three private details of core Optim (see inline comment).

Questions

  • Optim._update now traces an in-place torch.distributed.all_reduce on the loss mesh. make_fx records that as a raw c10d.allreduce_ op with the process group baked into the graph. The previous revision used funcol specifically to avoid this. Do the default regional-Inductor, bucketing, and remat passes handle that op? The existing test (test_full_inductor_pass_on_collective) only covers full Inductor.
  • @SherlockNoMad still has changes requested, asking for the motivation and a design doc. The author's reply is in the comments; a maintainer still needs to re-review.
Details
  • Checked and OK at HEAD:
    • wrap_with_accelerator_graph creates its wrapper lazily, so replacing _run_update leaves no wrapper stuck in warmup that would block all_wrappers_warmed_up.
    • Core config validation already rejects this flag combined with training.disable_accelerator_graphs, so the traced step is always captured by wrap_fwd_bwd_with_accelerator_graph.
    • init_optim_state runs before tracing and leaves parameters and counters unchanged.
    • extract_optimizer_state skips _save_host_lr, so the device lr stays a live graph input.
  • The all(capturable) gate at trainer.py:162 behaves the same as "Optim enabled capture", because ContainerOptimizers sets capturable exactly when it enables capture. When capture is unsupported, Optim warns and runs eagerly, the same as core.
  • GraphTrainingEngine.forward_backward waits for checkpoint staging only when _optimizer_update is set, because the graph mutates parameters before optim_step's own wait.

Not verified: GPU numerics, and whether the default pass pipeline handles the raw c10d.allreduce_. CI workflows for this commit are still awaiting approval.

@jemitche1

Copy link
Copy Markdown
Contributor Author

Thanks for the re-review!

On numerics: it turns out flag off vs on can't match bitwise, because turning the flag on also switches AdamW to capturable=True with a device lr, and that rounds a little differently from the second update onward. So, I compared against Optim's own separate optimizer graph, which uses the same capturable settings, and the traced path matches it bitwise for all 30 steps on both FSDP2, TP2 and FSDP2. I've put the full table in the description.

On c10d.allreduce_: both of those layouts all-reduce on the loss mesh, so the bitwise match also shows the default passes handle it fine.

On #5728: since it's still a draft, I think the cleanest plan is what @felipemello1 suggested; whichever PR lands second keeps the division inside the step graph, before clip_grad_norm_, and adds a test that traced and eager grad_norm match. @felipemello1, does that still sound right to you?

…aph-trainer-optimizer-capture

# Conflicts:
#	torchtitan/experiments/graph_trainer/trainer.py
@jemitche1

Copy link
Copy Markdown
Contributor Author

Merged main, no conflicts. On the private Optim dependencies at trainer.py:173: the traced path uses Optim._update, _run_update, and parameters. @tianyu-l would you prefer a small public hook on Optim for this, or should I keep the private access and add TODOs? Also, could someone approve the CI workflows? @SherlockNoMad the design doc and memory numbers are in the description, could you take another look?

@claude review

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

This PR doesn't really change core, so doesn't need my approval. Since @SherlockNoMad requested change before, I would like to wait for his review.

He is on vacation until end-of-month. Would be great if we could wait for a week.

@tianyu-l

Copy link
Copy Markdown
Contributor

@claude review again

@claude

claude Bot commented Nov 24, 2026 •

Copy link
Copy Markdown
Contributor

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


Approve (please address the items first; @SherlockNoMad's review is still pending): see the review posted on this PR.

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

Verdict: Approve -- please address the items below before merging. The description now has the problem, the numerics, and the memory and throughput numbers, and a maintainer accepted the private Optim dependencies. @SherlockNoMad still has changes requested, and @tianyu-l asked to wait for his review.

What this PR does. With optim.enable_accelerator_graph = True, GraphTrainer traces Optim._update into the SPMD joint graph. That covers clipping, the non-finite assert, and optimizers.step(). The graph returns (loss, grad_norm), while the first-step sync, the LR scheduler, and EMA still run eagerly in Optim.step. PP, SDC replay, sac_and_paged_stash, and precompile raise at config time. Gradient accumulation and optimizer step hooks raise in the engine.

Example.

# GraphTrainer, FSDP4 x TP2, 1 microbatch, optim.enable_accelerator_graph = True
main: ValueError("Optim CUDA graphs are not supported with GraphTrainer.")
PR:   forward_backward -> wait for staging -> graph(fwd, loss, bwd, Optim._update) -> (loss, grad_norm)
      optim_step       -> Optim.step: first-step sync, recorded grad_norm, lr_schedulers.step, ema.step

Earlier must-fix items

  • Description and numerics: resolved. Flag on vs off can't be bitwise equal because the flag turns on capturable=True. The right baseline is Optim's own graph, and the traced path matches it bitwise on FSDP2xTP2 and FSDP2. The 8B run shows peak memory 7% lower.
  • Conflict with #5728: addressed by agreement, not yet confirmed. #5728 is still a draft and hasn't been updated since 11-05. Please post the plan on #5728 itself, so its author sees it whichever PR lands first: divide inside the step graph before clip_grad_norm_, and add a test that traced and eager grad_norm match.
  • trainer.py:173 private Optim dependencies: resolved (@tianyu-l: "This is fine to me").

No code changed since the last review; the new commits are merges of main. The one merged-in optimizer feature, CPU-offloaded moments, adds no step hooks, so this PR doesn't need to change for it.

Must fix

  1. Description: put the opening paragraph under a ## Summary (human-written) heading, following .github/pull_request_template.md.

Should consider

  • tests/integration_tests.py:49 -- the flag is inherited by llama3_fsdp_tp_regional_inductor and llama3_fsdp_tp_sac_and_offload (see inline comment).
  • Nothing in CI checks that the traced update matches the eager Optim update. llama3_fsdp_tp has no golden losses, so a silent numerics change on this path (e.g. from #5728) would go unnoticed. A cheap guard is a single-GPU case in test_bitwise_deterministic.py comparing the loss and model hash of Trainer with Optim's graph against GraphTrainer with the traced update. Skip the gradient hash, since grads never land in param.grad. Today _run_steps uses its own torch.optim.Adam, so this needs a small extension of that helper.

Not verified: GPU numerics and the integration run. The CI workflows for this commit are still awaiting approval.

This branch has not been deployed

No deployments
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

ciflow/fake-pg Run 1-GPU Fake PG integration tests 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