Repository navigation
Conversation
[ghstack-poisoned]
[ghstack-poisoned]
|
@claude review this pr |
|
Claude finished @anshul-si's task in 2m 44s —— View job Approve -- please address the items before merging (empty human-written summary; assert that graphs were actually captured in the new tests). Review -- a maintainer still needs to review. |
There was a problem hiding this comment.
Verdict: Approve -- please address the items below before merging. The core change deletes a rejection that no longer protects anything on the non-EP, non-deferred path, and the new parity tests exercise both of the engine's graph modes. A maintainer still needs to review, since this touches torchtitan/distributed/.
What this PR does. It removes the "accelerator graphs" entry from validate_flex_shard_training. FlexShard runs now go through the training engine's graph wrappers and the validator's eval graph, the same as FSDP2 runs. Two GPU parity methods train llama3 and qwen3-MoE debug models with ChunkedLossWrapper under wrap_fwd_bwd_with_accelerator_graph (plus an eval graph in the same pool) and under the per-microbatch-group wrapper. They require bitwise-equal results against FSDP2.
Example.
config.parallelism.fsdp_backend = FlexShardConfig()
# training.disable_accelerator_graphs defaults to False
# before: ValueError "... accelerator graphs (set training.disable_accelerator_graphs=True)"
# after: forward-backward / optimizer / eval are captured and replayed, as with FSDP2EP > 1 is still rejected by the existing checks: graphs need HybridEP, and FlexShard under EP needs AllToAllTokenDispatcher. Deferred gradient reduction is still rejected too.
Must fix
- PR description -- the "Summary (human-written)" section is empty. The author needs to fill it in; agents don't write it (CLAUDE.md "PR Expectations" 2).
tests/unit_tests/gpu/distributed/test_flex_shard_fsdp.py:346-- nothing checks that a graph was captured. A silent eager fallback would pass the test without testing graphs. Assertaccelerator_graph_manager.capture's call count.
Should consider
tests/unit_tests/gpu/distributed/test_flex_shard_fsdp.py:487-- dropmicrobatches=1. The file's own rule is "two microbatches cover one", and with 2 microbatches the captured step covers both creating and accumulating grads.tests/unit_tests/gpu/distributed/test_flex_shard_fsdp.py:198-- makeaccelerator_graphkeyword-only.torchtitan/distributed/flex_shard_fsdp.py:294(outside the diff) -- FSDP2's path explains its explicitunshard()for graph capture atfsdp_lifecycle.py:136-137.flex_shard_partial_backwardsnow runs inside captured steps without one, and the only explanation (FlexShard releases all-gather buffers right after copy-out, so nothing eager carries into the capture) is in this PR's description. One line in that function's docstring would stop a later reader from "fixing" the asymmetry.
Details
- Gate: the problem is real. Graphs are on by default, so every FlexShard run on
mainmust setdisable_accelerator_graphs=True, and FlexShard can't be compared with FSDP2 in the recipes' configuration. The fix is in the right layer (deleting a FlexShard-only check), and there are no new knobs. Net LoC growth is all tests. - Order of operations in the "step" mode test: step 0 runs forward-backward warmup 1/2 and eval eagerly. Step 1 runs warmup 2/2, then the eval capture. Step 2 runs the forward-backward capture, and step 3 replays both. That matches the real validator, where
capture_allowed=Falseholds the training capture until eval has captured. - Per-group mode:
optim.zero_grad(set_to_none=False)matchestraining_engine.py:683, and the warmup counts calls, not steps, as the engine does. The bitwise check depends on FlexShard accumulating in place (param.grad += grad). The description shows that the per-group test fails if that becomes out-of-place, so the test guards this contract. - The reduce-scatter counts only cover warmup and capture, because replays don't go through Python. That's fine, since both backends are counted the same way.
- No stale "FlexShard + graphs unsupported" mentions remain in docs, recipes, or integration tests.
Not verified: the new GPU methods at CI's world_size=4 (the author ran them on 2 GPUs), and the trainer-level loss_compare results quoted in the description.
| model.train() | ||
| history.append((losses, grad_norm, grads, self._local_params(model))) | ||
| if accelerator_graph is not None: | ||
| accelerator_graph_teardown() |
There was a problem hiding this comment.
Nothing in the test checks that a graph was actually captured. The PR description says a one-off probe confirmed it, but that probe isn't in the PR. _wrap_with_accelerator_graph returns fn unchanged and only logs a warning when _unsupported_reason() is set. AcceleratorGraphWrapper.__call__ also stays eager while capture_allowed is False. In either case both backends would run eagerly, stay bitwise equal, and this test would pass without testing graphs (rules/tests.md: "Verify that the intended test actually ran").
A cheap guard is to wrap the manager's public capture and assert on how many times it was called:
with patch.object(
accelerator_graph_manager, "capture", wraps=accelerator_graph_manager.capture
) as capture:
for step in range(num_steps):
...
if accelerator_graph is not None:
# "step": forward-backward and eval; "microbatch_group": one group graph.
self.assertEqual(capture.call_count, 2 if accelerator_graph == "step" else 1)
accelerator_graph_teardown()| (build_qwen3_config, "debugmodel_moe"), | ||
| ), | ||
| ("default",), | ||
| (1, 2), |
There was a problem hiding this comment.
test_matches_fsdp2 in this same file says "Two microbatches cover one". The same reasoning applies under graphs. With 2 microbatches, the captured step both creates grads inside the graph (the first microbatch) and accumulates into them (the second). With 1 microbatch, it only creates them. Unless the 1-microbatch case catches something the 2-microbatch case doesn't, dropping it halves this method's cases on a 4-GPU job.
| (1, 2), | |
| (2,), |
| parallelism_context, | ||
| microbatches, | ||
| chunked_loss, | ||
| accelerator_graph: Literal["step", "microbatch_group"] | None = None, |
There was a problem hiding this comment.
Nit: accelerator_graph is a new option and has a default, so it could go after the * with optim, as a keyword-only argument (CLAUDE.md "Prefer keyword-only arguments"). The call site would then read self._train(model, *setup, microbatches, chunked_loss, accelerator_graph=accelerator_graph) instead of passing a fifth positional argument.
…fig()
Stacked on #5842, the expert-parallelism PR, the chunked-loss PR, the
checkpointing PR, the Hugging Face load PR, the tensor- and context-parallelism PR
and the DeepSeek V3 PR.
## Summary (human-written)
<!-- Write this yourself, not with an AI tool. 2-5 sentences: the problem, why
this approach, and what you checked yourself. -->
## Description
`validate_flex_shard_training` rejects accelerator graphs, but graphs are on by default
(`training.disable_accelerator_graphs=False`), and the Llama 3 and Qwen3 MoE debug
recipes capture the forward-backward unless expert parallelism is on. So every FlexShard
run has to turn graphs off, and FlexShard can't be compared with FSDP2 in the
configuration the recipes train in. This PR deletes the rejection. Nothing else in
torchtitan changes: FlexShard models go through the training engine's and the
validator's graph wrappers as FSDP2 models do, and training with graphs is bitwise
identical to FSDP2 with graphs. As in #5842, nothing on the FlexShard path creates a
DTensor.
A captured step has to finish everything it starts (all-gathers, reduce-scatters,
reshards) without syncing with the host, and leave nothing behind that the next step
waits on. FlexShard's own tests capture and replay its training steps bitwise against
eager ones (meta-pytorch/flex_shard#66, in CI's pin `d6bb546`). What remained was
torchtitan's side, whose graph modes changed after the fork's version of this PR. Three
of them needed a closer look:
- **`ChunkedLossWrapper` inside the captured step.** For FSDP2, `fsdp_partial_backwards`
gathers the norm and `lm_head` group with an explicit `unshard()` before the chunks.
In forward, FSDP2 frees a group's all-gather buffers only at the next all-gather, so
gathering the group in an eager warmup step would leave an event that the capture
then waits on. The chunked-loss PR's `flex_shard_partial_backwards` has no such
`unshard()`, since FlexShard rejected graphs. It doesn't need one: FlexShard orders
the release of an all-gather's buffers right after their copy-out, so nothing
crosses from one step into the next, and the first chunk gathers the bucket inside
the capture. The bucket setters that function calls change only host-side flags,
which the capture records with the rest of the step.
- **One graph per microbatch group (#5088,
`training.accelerator_graph_per_microbatch_group`).** The training engine then zeroes
the grads without freeing them, and each replay reduce-scatters its group's grads
and adds them to the sharded grads that existed at capture. FlexShard adds in place
(`param.grad += grad`), so the replays accumulate as eager microbatches do. The mode
requires `fsdp_defer_gradient_reduction=False`, as FlexShard does.
- **Eval graphs in the training graphs' memory pool (#5241).** The validator captures
eval before training, with `post_validate_fsdp_for_accelerator_graph` inside the eval
graph. The chunked-loss PR made that function call FlexShard's `reshard()`, which
closes the forward that the chunked loss leaves open on `lm_head`'s bucket, so the
training capture after it starts from resharded buckets.
Graphs under expert parallelism stay rejected, by two existing checks: torchtitan allows
them only with HybridEP and `non_blocking_capacity_factor`, because the other dispatchers
sync with the host, and FlexShard under EP accepts only `AllToAllTokenDispatcher` (the
expert-parallelism PR). Lifting that needs FlexShard's expert buckets checked against
FSDP2 with HybridEP, which isn't installed on the test machine. Deferred gradient
reduction is still rejected (#5842), so graphs with deferral aren't covered either. The
`fsdp_backend` docstring never listed accelerator graphs among FlexShard's limits, so it
doesn't change. The CPU tests of the `_apply_fsdp` rejection and of the checkpointers
no longer turn graphs off.
Two new parity methods in `test_flex_shard_fsdp.py` train llama3 `debugmodel` and qwen3
`debugmodel_moe` (`ep=1`) with `ChunkedLossWrapper`, as the recipes do, in graphs, and
require the same bitwise-equal losses, grad norms, grads and parameters, and the same
reduce-scatter count, as the other parity cases. They wrap the forward-backward with the
training engine's wrappers (`wrap_fwd_bwd_with_accelerator_graph`,
`wrap_with_accelerator_graph`) and warmup count, and run 4 steps: two eager warmup steps,
the capture, and a replay.
- `test_matches_fsdp2_with_accelerator_graphs` captures one graph per step, with one and
with two microbatches. After each step it also runs a validation forward of the
step's first microbatch as the validator does with graphs: in eval mode and without
grad, ending with `post_validate_fsdp_for_accelerator_graph`, eager at the first step,
then captured at the second in the same pool, before the training capture, and
replayed. The validation losses are compared with the training losses.
- `test_matches_fsdp2_with_accelerator_graph_per_microbatch_group` runs two microbatches
per step, each its own group, with the grads zeroed without being freed. Warmup
counts calls, so the capture is at step 1's first microbatch, and every later
microbatch replays it.
`_train` now prepares a step's microbatches before running them in one function, which
the graph modes wrap, as the training engine does. For the existing cases, this only
moves the preparation of a step's inputs ahead of its forwards. The loss's token count is
now built once, outside the graphs, since a blocking host-to-device copy can't be
captured.
Both new methods pass on 2 GB200 GPUs with `world_size` set to 2, and so do
`test_matches_fsdp2` and `test_matches_fsdp2_with_expert_parallelism` with the reworked
`_train`. A one-off probe of the graph wrappers after each run (not part of the PR) shows
that all 16 runs of the new methods (8 cases, 2 backends) captured their graphs, the eval
graph included. The new methods haven't run at CI's 4 GPUs: this machine has 2, and
FlexShard needs CUDA. With FlexShard edited locally to accumulate a reduce-scattered grad
out of place (`param.grad = param.grad + grad`, not part of this PR), the per-group method
fails at step 1, the capture, on the grad norm (llama3, its first case): each replay then
writes the pre-capture grad plus its own microbatch's grad, so a step loses all but its
last microbatch's grads. The tests build models with `model.parallelize`, not through
`TrainingEngine`, so they can't catch the config check coming back. The runs below do.
Through the trainer, `scripts/loss_compare.py . . --baseline-config <FSDP2>
--test-config <FlexShard> --assert-equal --metrics loss,grad_norm` on this commit (seed 42,
deterministic, 20 steps, 2 GB200 GPUs, `dp_shard=2`, the recipes' `ChunkedLossWrapper` and
activation remat, validation every 2 steps) reports equal loss and grad norm at every
step, and the max loss and validation loss in TensorBoard are equal too, for:
- llama3 `debugmodel` with graphs for training, the optimizer and eval (step-20 loss
3.17798), the same with SDC replay checking every step (3.17798), the same with two
microbatches per step (3.24869), and with one graph per microbatch group and two
microbatches (3.24869);
- qwen3 `debugmodel_moe` with graphs for training, the optimizer and eval (5.39370), and
with one graph per microbatch group and two microbatches (5.41419).
Each of these runs recorded its forward-backward, optimizer and validation graphs. They
use flex attention because the environment has no FA4. The two backends start from
different weights (#5842). These runs skip the seed checkpoint, so for these runs only, a
recipe-side patch initializes FSDP2's DTensor shards as their slices of one device's
initialization, as FlexShard's are. With graphs off, the patched runs match bit for bit
for both models (with one microbatch, and for qwen3 MoE also with two).
Peak active memory per step matches FSDP2's at every training step and validation of
llama3 with one microbatch. Elsewhere, it differs only slightly once the graphs replay:
- llama3 with two microbatches, in both graph modes: FlexShard is 0.5 KiB higher at the
steps before the first replay, and equal after.
- qwen3 MoE: FlexShard is 4 KiB lower at every training step and validation, as in eager
training. With two microbatches it is also 75 MiB higher at the steps before the first
replay, as at every step of eager training with two microbatches, and only 4 KiB lower
after.
The FSDP2 path doesn't change: this PR deletes a FlexShard-only check, so there is no
FSDP2 `loss_compare` A/B against the chunked-loss PR.
The earlier revision of this PR also covered deferred gradient reduction, tensor and
context parallelism and DeepSeek V3. #5842 now rejects deferral, and the others come with
later PRs in the stack.
Co-authored-by: Wei Feng <[email protected]>
ghstack-source-id: 049cf24
Pull-Request: pytorch/torchtitan#6210
Stack from ghstack (oldest at bottom):
Stacked on #5842, the expert-parallelism PR, the chunked-loss PR, the
checkpointing PR, the Hugging Face load PR, the tensor- and context-parallelism PR
and the DeepSeek V3 PR.
Summary (human-written)
Description
FlexShardConfig.validate_modelrejects accelerator graphs, but graphs are on bydefault (
training.disable_accelerator_graphs=False), and the Llama 3 and Qwen3 MoEdebug recipes capture the forward-backward unless expert parallelism is on. So every
FlexShard run has to turn graphs off, and FlexShard can't be compared with FSDP2 in the
configuration the recipes train in. This PR deletes the rejection, and with it the
trainingargument ofFlexShardConfig.validate_model, which only it read, and ofStorageConfig.validate_model. Nothing else in torchtitan changes: FlexShardmodels go through the training engine's and the validator's graph wrappers as FSDP2
models do, and training with graphs is bitwise identical to FSDP2 with graphs. As in
#5842, nothing on the FlexShard path creates a DTensor.
A captured step has to finish everything it starts (all-gathers, reduce-scatters,
reshards) without syncing with the host, and leave nothing behind that the next step
waits on. FlexShard's own tests capture and replay its training steps bitwise against
eager ones (meta-pytorch/flex_shard#66, in CI's pin
d6bb546). What remained wastorchtitan's side, whose graph modes changed after the fork's version of this PR. Three
of them needed a closer look:
ChunkedLossWrapperinside the captured step. For FSDP2,fsdp_partial_backwardsgathers the norm and
lm_headgroup with an explicitunshard()before the chunks.In forward, FSDP2 frees a group's all-gather buffers only at the next all-gather, so
gathering the group in an eager warmup step would leave an event that the capture
then waits on. The chunked-loss PR's
FlexShardConfig._partial_backwardshas no suchunshard(), since FlexShard rejected graphs. It doesn't need one: FlexShard ordersthe release of an all-gather's buffers right after their copy-out, so nothing
crosses from one step into the next, and the first chunk gathers the bucket inside
the capture. The bucket setters that function calls change only host-side flags,
which the capture records with the rest of the step.
training.accelerator_graph_per_microbatch_group). The training engine then zeroesthe grads without freeing them, and each replay reduce-scatters its group's grads
and adds them to the sharded grads that existed at capture. FlexShard adds in place
(
param.grad += grad), so the replays accumulate as eager microbatches do. The moderequires
fsdp_defer_gradient_reduction=False, as FlexShard does.eval before training, with the storage config's
reshard_after_evalinside the evalgraph. FlexShard's, from the chunked-loss PR, calls FlexShard's
reshard(), whichcloses the forward that the chunked loss leaves open on
lm_head's bucket, so thetraining capture after it starts from resharded buckets.
Graphs under expert parallelism stay rejected, by two existing checks: torchtitan allows
them only with HybridEP and
non_blocking_capacity_factor, because the otherdispatchers sync with the host, and FlexShard under EP accepts only
AllToAllTokenDispatcher(the expert-parallelism PR). Lifting that needs FlexShard'sexpert buckets checked against FSDP2 with HybridEP, which isn't installed on the test
machine. Deferred gradient reduction is still rejected (#5842), so graphs with deferral
aren't covered either. The
storagedocstring never listed accelerator graphsamong FlexShard's limits, so it doesn't change. The CPU tests of the
_apply_fsdprejection and of the checkpointers no longer turn graphs off.
Two new parity methods in
test_flex_shard_fsdp.pytrain llama3debugmodeland qwen3debugmodel_moe(ep=1) withChunkedLossWrapper, as the recipes do, in graphs, andrequire the same bitwise-equal losses, grad norms, grads and parameters, and the same
reduce-scatter count, as the other parity cases. They wrap the forward-backward with the
training engine's wrappers (
wrap_fwd_bwd_with_accelerator_graph,wrap_with_accelerator_graph) and warmup count, and run 4 steps: two eager warmupsteps, the capture, and a replay.
test_matches_fsdp2_with_accelerator_graphscaptures one graph per step, with one andwith two microbatches. After each step it also runs a validation forward of the step's
first microbatch as the validator does with graphs: in eval mode and without grad,
ending with the storage config's
reshard_after_eval, eager at the first step, thencaptured at the second in the same pool, before the training capture, and replayed.
The validation losses are compared with the training losses.
test_matches_fsdp2_with_accelerator_graph_per_microbatch_groupruns two microbatchesper step, each its own group, with the grads zeroed without being freed. Warmup
counts calls, so the capture is at step 1's first microbatch, and every later
microbatch replays it.
_trainnow prepares a step's microbatches before running them in one function, whichthe graph modes wrap, as the training engine does. For the existing cases, this only
moves the preparation of a step's inputs ahead of its forwards. The loss's token count
is now built once, outside the graphs, since a blocking host-to-device copy can't be
captured.
Both new methods pass on 2 GB200 GPUs with
world_sizeset to 2, and so dotest_matches_fsdp2andtest_matches_fsdp2_with_expert_parallelismwith the reworked_train. A one-off probe of the graph wrappers after each run (not part of the PR)shows that all 16 runs of the new methods (8 cases, 2 backends) captured their graphs,
the eval graph included. The new methods haven't run at CI's 4 GPUs: this machine has 2,
and FlexShard needs CUDA. With FlexShard edited locally to accumulate a reduce-scattered
grad out of place (
param.grad = param.grad + grad, not part of this PR), the per-groupmethod fails at step 1, the capture, on the grad norm (llama3, its first case): each
replay then writes the pre-capture grad plus its own microbatch's grad, so a step loses
all but its last microbatch's grads. The tests build models with
model.parallelize,not through
TrainingEngine, so they can't catch the config check coming back. The runsbelow do.
Through the trainer,
scripts/loss_compare.py . . --baseline-config <FSDP2> --test-config <FlexShard> --assert-equal --metrics loss,grad_normon this commit (seed42, deterministic, 20 steps, 2 GB200 GPUs,
dp_shard=2, the recipes'ChunkedLossWrapperand activation remat, validation every 2 steps) reports equal lossand grad norm at every step, and the max loss and validation loss in TensorBoard are
equal too, for:
debugmodelwith graphs for training, the optimizer and eval (step-20 loss3.17798), the same with SDC replay checking every step (3.17798), the same with two
microbatches per step (3.24869), and with one graph per microbatch group and two
microbatches (3.24869);
debugmodel_moewith graphs for training, the optimizer and eval (5.39370), andwith one graph per microbatch group and two microbatches (5.41419).
Each of these runs recorded its forward-backward, optimizer and validation graphs. They
use flex attention because the environment has no FA4. The two backends start from
different weights (#5842). These runs skip the seed checkpoint, so for these runs only,
a recipe-side patch initializes FSDP2's DTensor shards as their slices of one device's
initialization, as FlexShard's are. With graphs off, the patched runs match bit for bit
for both models (with one microbatch, and for qwen3 MoE also with two).
Peak active memory per step matches FSDP2's at every training step and validation of
llama3 with one microbatch. Elsewhere, it differs only slightly once the graphs replay:
steps before the first replay, and equal after.
training. With two microbatches it is also 75 MiB higher at the steps before the first
replay, as at every step of eager training with two microbatches, and only 4 KiB lower
after.
The FSDP2 path doesn't change: this PR deletes a FlexShard-only check, so there is no
FSDP2
loss_compareA/B against the chunked-loss PR.The earlier revision of this PR also covered deferred gradient reduction, tensor and
context parallelism and DeepSeek V3. #5842 now rejects deferral, and the others come
with later PRs in the stack.
Co-authored-by: Wei Feng [email protected]