Repository navigation
Conversation
9266ce5 to
bd2dd5d
Compare
|
The following ciflow label(s) have been added but CI has not been triggered yet because the workflows are awaiting approval:
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. |
bd2dd5d to
bd9ed78
Compare
|
@tianyu-l could I receive a review for this PR? I would appreciate any feedback. |
|
@claude review |
There was a problem hiding this comment.
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
- 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_graphon and off, withseed=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
ValueErrorand lettingOptimcapture 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.
- Numerics: a bitwise loss and grad_norm comparison between
trainer.py:252-- second copy ofOptim.step/Optim._update. It will drift apart from the original, and #5728 (grad division moving intooptim_step) would silently change numerics on whichever PR lands second. It also already drops the first-step sync.- Validation is spread across four places:
spmd_graph_builder.py:237-- the precompile check belongs inConfig.__post_init__.pipeline.py:756-- the grad-accum check belongs in the engine, wherenum_microbatchesis computed.traced_optimizer.py:45-- the PP check can never fire; delete it.
Should consider
trainer.py:250--optim_stepgets the trace span twice on the default path.make_fx_tracer.py:229-- take onlySequence[Optimizer]and always return a list.test_trace_module.py:1319-- drop the three raise-only tests.optimizer_updateis 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, shouldOptim._updatebecome 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 existingOptimgraph path. - Checked and OK:
- Hooks are registered in
_initialize_optimbefore_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_updategraph wrapper is never instantiated, soall_wrappers_warmed_upisn't blocked. - Default
fused=TrueAdamW traces the fused op, so no foreach/single-tensor switch is expected on the main path.
- Hooks are registered in
grad_normreachesoptim_stepthrough a side channel (record_grad_norm). It's acceptable inside the experiment, but it relies onforward_backwardrunning exactly once peroptim_step.
Not verified: GPU numerics, FSDP+TP integration behavior, and whether skipping the first-step empty_cache affects peak memory.
| 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 |
There was a problem hiding this comment.
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:
- Open PR [BC][engine] One sum-then-scale path: losses return sums, optim_step divides by the step's loss-token count #5728 moves the gradient division (
grads /= N, the step's loss-token count) intooptim_step, right before clipping. Whichever of the two PRs lands second, the traced path will either skip that division or run it twice. Neither case raises an error; only the loss and grad_norm change. - The
_is_first_step_callsynchronize +empty_cacheinOptim.step(NCCL all-reduce OOM despite reclaimable PyTorch cache during Kimi K3 training #5019) is already dropped here, without any explanation.
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.
|
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. |
bd9ed78 to
6d938fa
Compare
|
@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. |
SummaryGraphTrainer traces forward, loss, and backward into one graph but rejects How it worksThe traced step runs forward, loss, backward, then Optimizer stateState is handled like parameters and buffers, as graph inputs:
Alternatives
ResultsLlama 3 8B, FSDP2xTP4, seq 4096, regional Inductor:
Peak memory drops 7% with no throughput cost. Numbers are from one backend; the implementation is backend-agnostic ( |
6d938fa to
397146e
Compare
|
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? |
|
@claude review again |
There was a problem hiding this comment.
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, sinceOptim.stepruns 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
- 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". - Conflict with #5728. #5728 divides the gradients in
TrainingEngine.optim_stepby iteratingparameter.gradforself.optim.parameters. It also turns the loss into a sum. On this PR's traced path,parameter.gradis never set on the live parameters, and the graph has already clipped and applied the update beforeoptim_stepruns. 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, beforeclip_grad_norm_, which needs the global count as a graph input), or have the traced path raise until that is settled. trainer.py:173-- the integration relies on three private details of coreOptim(see inline comment).
Questions
Optim._updatenow traces an in-placetorch.distributed.all_reduceon the loss mesh.make_fxrecords that as a rawc10d.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_graphcreates its wrapper lazily, so replacing_run_updateleaves no wrapper stuck in warmup that would blockall_wrappers_warmed_up.- Core config validation already rejects this flag combined with
training.disable_accelerator_graphs, so the traced step is always captured bywrap_fwd_bwd_with_accelerator_graph. init_optim_stateruns before tracing and leaves parameters and counters unchanged.extract_optimizer_stateskips_save_host_lr, so the devicelrstays a live graph input.
- The
all(capturable)gate attrainer.py:162behaves the same as "Optim enabled capture", becauseContainerOptimizerssetscapturableexactly when it enables capture. When capture is unsupported,Optimwarns and runs eagerly, the same as core. GraphTrainingEngine.forward_backwardwaits for checkpoint staging only when_optimizer_updateis set, because the graph mutates parameters beforeoptim_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.
|
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
|
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
left a comment
There was a problem hiding this comment.
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.
|
@claude review again |
|
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. |
There was a problem hiding this comment.
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 isOptim'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:173privateOptimdependencies: 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
- 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 byllama3_fsdp_tp_regional_inductorandllama3_fsdp_tp_sac_and_offload(see inline comment).- Nothing in CI checks that the traced update matches the eager
Optimupdate.llama3_fsdp_tphas 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 intest_bitwise_deterministic.pycomparing the loss and model hash ofTrainerwithOptim's graph againstGraphTrainerwith the traced update. Skip the gradient hash, since grads never land inparam.grad. Today_run_stepsuses its owntorch.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.
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 afterthe graph.
What changed
TracedOptimizerUpdate(traced_optimizer.py) traces the existingOptim._updateinto the joint SPMD graph, so there is one copy of the updatelogic.
Optim.stepstill runs the first-step sync, LR scheduler, and EMA;only its update slot returns the grad norm the graph produced.
torch.optim.swap_in_optimizer_params_and_stateswaps it in, so statetensors become graph inputs that the traced
optimizer.step()updates inplace. State is read without state-dict hooks (a device
lrstays a liveinput) and counts as static input for graph capture.
aten._assert_async, silently removing theoptimizer's non-finite guard; asserts traced from the optimizer update are
now kept.
ValueError: PP, SDC replay,sac_and_paged_stash, and precompiled artifacts at config time; gradientaccumulation in the engine; optimizers with step hooks when the update is
built.
because the graph writes parameters and optimizer state.
optimizer_updatethreaded through the graphbuilders and runtime factories (
graph_builder.py,graph_pp/pipeline.py,spmd_gradient_accumulation_graph_builder.py), andminimal_fx_tracer/run_traced/extract_train_statetakeoptimizers: Sequence[Optimizer].User-facing changes
optim.enable_accelerator_graph = Trueraises in GraphTrainerNumerics
Debug model, seed 42,
deterministic=True, regional Inductor, 30 steps:Optimcapturing its own graph (bothcapturable=True)Flag off vs on is not bitwise equal because the flag switches AdamW to
capturable=Truewith a devicelr, which rounds differently from the secondupdate 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:
Optimcaptures its own graphPeak 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 runwhile async checkpoint staging still reads parameters.
TestTraceCapturableOptimizers: traced vs eager parity with severaloptimizers and a device
lr(catcheslrfrozen into the graph).test_dead_code_elimination_keeps_optimizer_update_assert: catches thenon-finite guard being stripped.
test_graph_training_engine_rejects_optimizer_accelerator_graph,which asserted the error this PR removes.
llama3_fsdp_tpintegration config now enables the flag.