Skip to content

[graph_trainer] Flex_shard integration (opt use instead_of simple_fsdp) - #6245

Open
IvanKobzarev wants to merge 6 commits into
pytorch:pr-5842from
IvanKobzarev:graph-trainer-flex-shard-integration
Open

IvanKobzarev wants to merge 6 commits into
pytorch:pr-5842from
IvanKobzarev:graph-trainer-flex-shard-integration

Conversation

@IvanKobzarev

@IvanKobzarev IvanKobzarev commented Nov 19, 2026 •

Copy link
Copy Markdown
Contributor

Depends on flex_shard addition meta-pytorch/flex_shard#125

Optional replacement of simple_fsdp with flex_shard.

  1. Introducing config use_flex_shard_instead_simple_fsdp

The main difference in processing:

  1. tracing flex_shard gives already bucketed graph, but without any scheduling (simple_fsdp was per parameter)
    We disable OverlapManualBucketing that was done on simple_fsdp and add new pass for scheduling of the buckets comms.
    The flex_shard bucket comms are identified via meta annotations (look at flex_shard PR that adds it [graph_trainer] flex_shard -> graph_trainer integrations meta-pytorch/flex_shard#125)

  2. Various passes do some fsdp comms matching in graph, this part for flex_shard will be different. Mostly this is just fork of the variant for simple_fsdp using flex_shard identification.
    E.g. deduplicate_flex_shard_unshard_pass pass instead of deduplicate_unshard_pass for chunked loss

  3. flex_shard bucketing uses mutation ops like forech_copy_, copy_.
    Current graph_trainer has very limited support of mutation ops. Most of the changes are connected with just general GraphTrainer support of mutation ops for various passes.

The problems with mutations are mostly around SAC remat. We solved it via assigning meta "recompute_region" to the group of nodes that must be together and make SAC reason, remat based on this meta.

Testing:

Model / configuration GPUs Step S/F (ms) Delta step TFLOPS/GPU S/F Delta TFLOPS MFU S/F (%) Delta MFU Active S/F (GiB) Delta active Reserved S/F (GiB) Delta reserved Numerics
Qwen3 14B BF16, full remat, BS16 (earlier verification) 4 5787.59 / 5762.36 -0.44% 1064.84 / 1069.25 +0.41% 42.59 / 42.77 +0.41% 84.76 / 85.06 +0.35% 89.52 / 89.35 -0.20% Loss/norm/state exact
DSv3 72.65B prefix BF16, EP8, BS4 (earlier verification) 16 972.02 / 979.69 +0.79% 779.93 / 773.89 -0.77% 31.20 / 30.96 -0.77% 203.68 / 204.98 +0.64% 212.32 / 212.86 +0.25% Loss/norm/state exact
DSv3 16B BF16, EP4, GA1, no remat 4 796.96 / 804.18 +0.91% 744.90 / 738.16 -0.90% 29.80 / 29.53 -0.90% 197.93 / 198.32 +0.20% 199.03 / 199.46 +0.22% Loss/norm/grads/state exact
DSv3 16B BF16, EP2, GA4, full remat 4 3057.26 / 3019.39 -1.24% 776.40 / 786.15 +1.26% 31.06 / 31.45 +1.26% 169.41 / 169.32 -0.05% 172.32 / 172.57 +0.14% Loss/norm/grads/state exact
DSv3 16B MXFP8, EP4, GA1, selective remat 4 826.91 / 836.15 +1.12% 717.91 / 709.97 -1.11% N/A / N/A N/A 151.68 / 151.68 +0.00% 155.27 / 155.15 -0.08% Loss/norm/grads/state exact
DSv3 16B MXFP8, EP2, GA4, full remat 4 2841.08 / 2769.76 -2.51% 835.57 / 857.05 +2.57% N/A / N/A N/A 160.48 / 160.44 -0.02% 164.07 / 162.73 -0.82% Loss/norm/grads/state exact
DSv3 72.65B prefix BF16, EP8, BS4; eager FlexShard (earlier verification) 16 1121.25 - 675.87 - 27.03 - 212.16 - 253.21 - Loss/norm/state exact

S/F = GraphTrainer SimpleFSDP / GraphTrainer FlexShard. Deltas are relative to SimpleFSDP; only FlexShard regressions greater than 2% are bold. The eager row is an absolute reference. All GraphTrainer comparisons are within the 2% performance and memory regression threshold.
All runs use GB300 GPUs, sequence length 4096, seed 42 and deterministic execution. Each run has 41 steps: warmup 1-10, timing 11-40, profiling 41. Memory peaks cover steps 1-40 across all ranks. The four DSv3 16B configurations use the full 27-layer model, Dist-MoE, BS8/GPU and DP4. GA4 reuses unsharded parameters across microbatches. MXFP8 MFU is unavailable because the trainer does not report MFU for quantized models.

@meta-cla meta-cla Bot added the CLA Signed This label is managed by the Meta Open Source bot. label Nov 19, 2026
@IvanKobzarev
IvanKobzarev force-pushed the graph-trainer-flex-shard-integration branch 4 times, most recently from 956026d to 6b31b1e Compare November 20, 2026 14:07
@IvanKobzarev
IvanKobzarev marked this pull request as ready for review November 20, 2026 14:23
@pytorch-bot pytorch-bot Bot added ciflow/b200 Trigger B200 CI ciflow/fake-pg Run 1-GPU Fake PG integration tests labels Nov 20, 2026
@IvanKobzarev IvanKobzarev added the ciflow/h100.8 Trigger H100.8 CI label Nov 20, 2026
@IvanKobzarev
IvanKobzarev force-pushed the graph-trainer-flex-shard-integration branch from 6b31b1e to f58606a Compare November 20, 2026 17:23
@aditvenk

Copy link
Copy Markdown
Contributor

@claude review

@claude

claude Bot commented Nov 21, 2026 •

Copy link
Copy Markdown
Contributor

Claude finished @aditvenk's task in 5m 27s —— View job


Request changes: see the review.

flex_shard_fsdp_scheduling,
)

passes.append(functools.partial(flex_shard_fsdp_scheduling))

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.

@claude Why can't we reuse (perhaps in a slightly different configuration) the existing joint_transformer_block_bucketing_reordering_pass and instead need a new pass?

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Scheduling of flex_shard is different, because it is using more mutation ops copy_ , forech_copy_, that we should handle via regions moving.

I tried to put it into one pass, but as we should support 2 different scheduling - this makes it more complicated and errorprone during maintaining vs 2 separate passes.
In this case we can retest only one of simple_fsdp and flex_shard vs both for joint case.

@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 -- this builds a second, boolean-selected FlexShard integration alongside the in-flight parallelism.fsdp_backend = FlexShardConfig() stack (#5842, #6010, #6243, ...). The new tests can't run in CI. Several shared GraphTrainer passes also change behavior for the default SimpleFSDP path with no main-vs-branch evidence.

What this PR does. It adds GraphTrainer.Config.use_flex_shard_instead_simple_fsdp and flex_shard_placement_fn. When the flag is set, the model is sharded with FlexShard buckets (one per transformer block, with routed experts split out under EP) instead of SimpleFSDP. That flag is then threaded into about 10 places so each SimpleFSDP-specific graph pass switches to a FlexShard fork keyed on flex_shard_* node metadata: unshard dedup, region extraction for GraphPP/GA, comm scheduling (in place of joint_transformer_block_bucketing_reordering_pass), and full-recompute tagging. Separately, it teaches the shared partition, grad-accumulation, SAC-tagging and remat passes to follow writes through aliases (_foreach_copy_/copy_ into fresh buffers).

Example.

# torchtitan_recipes/tests/graph_trainer/b200.py, this PR
config = graph_trainer_deepseek_v3_debugmodel_dist_moe_bf16_fsdp2_ep2()
config.use_flex_shard_instead_simple_fsdp = True        # GraphTrainer-only selector
# vs. #5842's selector for the same backend in the core trainer:
config.parallelism.fsdp_backend = FlexShardConfig()     # ignored by GraphTrainer here

Must fix

  1. Design: build on parallelism.fsdp_backend. Use one FlexShard backend object instead of a bool in about 10 call sites. if use_flex_shard branches sit in fsdp_passes.py, split_fsdp_collectives.py, graph_builder_utils.py, passes.py, memory_policy.py, model.py, pipeline.py, pp_graph_builder.py, spmd_gradient_accumulation_graph_builder.py, precompile_main.py and trainer.py. Adding a third backend would mean editing all of them again. Pick the backend from the fsdp_backend config type once, and have the GraphTrainer side expose its dedup pass, region finder, scheduling pass and recompute prep from one place, chosen when the pass list is built (per the graph_trainer CLAUDE.md "Pass Configuration" rule). Bucket construction and EP handling in apply_flex_shard overlap with #5842/#6010's apply_fsdp_to_decoder, so reuse that and keep only the GraphTrainer-specific graph passes here.
  2. trainer.py:441 -- bool + callable config fields duplicate #5842's selector.
  3. trainer.py:120 -- the configured gradient clipper is replaced at runtime.
  4. memory_policy.py:522 -- only memory_policy="full" handles FlexShard. default uses the SimpleFSDP-only unshard matcher, so fsdp_reshard_after_forward is not honored (unverified at runtime). Wire the other policies or raise ValueError.
  5. memory_policy.py:383 and selective_activation_remat.py:78 -- ungated changes to shared SAC/remat behavior. common_utils.py:317 and make_fx_tracer.py:211 (backward custom keys now win over forward ones) are ungated too. Gate them to FlexShard, or show main-vs-branch SimpleFSDP bitwise loss/grad_norm and peak memory. Split real main bugs into their own PRs.
  6. precompile_main.py:138 -- flex_shard_placement_fn is dropped in precompile.
  7. integration_tests.py:679 -- flex_shard isn't installed in CI and the APIs depend on unmerged meta-pytorch/flex_shard#125, so the new integration entries fail and the new unit tests always skip. The SimpleFSDP BF16 FSDP+EP B200 entry is also removed.
  8. tests/flex_shard_mxfp8.py:30 -- production code in tests/, imported by a recipe.

Should consider

  • pipeline.py:895 -- imports from flex_shard's internal module path.
  • flex_shard.py:240-304 -- there are two init and clipping paths. Without a custom placement_fn, an aliased DTensor wrapper is stashed on every param (_graph_trainer_dtensor_param). With one, ad-hoc _graph_trainer_norm_groups are used. Could the norm-groups path cover plain Shard as well? That would delete the DTensor path (DTensor.from_local, _StridedShard, DeviceMesh._concatenate). If DTensor init is needed for seeded-RNG parity with SimpleFSDP, say so in a comment.
  • flex_shard.py:404-533 -- mark_flex_shard_unshard_recompute_regions_pass calls policy_fn on copy.copy(node) and assumes layers.<i> FQNs. Would putting module_fqn on the bucket nodes upstream (the flex_shard#125 annotations) remove the copy trick?

Questions

  • What does FlexShard enable here that SimpleFSDP can't? The table shows parity within about ±2.5%. Is the motivation MXFP8 block-sharded storage or DistMuon placements? Please say so in the description and show the configuration that needs it.
  • Could flex_shard_fsdp_scheduling (about 170 lines of hand-written reordering) reuse PyTorch's manual overlap scheduling on already-bucketed collectives instead? If not, what's missing upstream?
  • PP: get_default_transformer_block_buckets(len(model.config.layers)) names every layer plus tok_embeddings/norm/lm_head. Does FlexShard accept patterns that match nothing on a stage? Is there a PP + FlexShard run behind the GraphPP changes?
Details

Overlap. #5842 says "Our goal is to fully replace FSDP2 with FlexShard". It adds FlexShardConfig selected by type, torchtitan/distributed/flex_shard_fsdp.py, a FlexShard-aware clipper in components/optim/optim.py, and a GPU workflow change. #6010 adds per-MoE-block dense and routed-expert buckets, the same split apply_flex_shard builds here. The maintainers should decide whether GraphTrainer consumes that config, or whether GraphTrainer's FlexShard integration is intentionally separate. In either case it shouldn't be a second user-facing selector.

Size. +2515/-112, of which about 1300 lines are tests. Removing the bool threading, the duplicate bucket builder and the clipper subclass, and reusing the #5842 pieces, would likely shrink the non-test diff by about 300 lines (rough estimate).

Shared-path changes that also affect SimpleFSDP: partition.py (node_closure -> _node_closure_with_mutations, _forward_mutations_to_materialize now uses autograd_backward instead of backward closure), split_fsdp_collectives.extract_fsdp_unshard_graph (passthrough inputs now computed from retained outputs, plus unshard-graph DCE), pp_graph_builder.py (side-effect outputs taken by slice), split_di_dw.py (extra DCE), grad_accumulation.py (anchor after aliasing writers). These look intended to be general, but the PR has no SimpleFSDP before/after numbers.

Not verified: GPU runtime behavior (memory-policy effect in item 4, PP + FlexShard). A maintainer still needs to review.

Comment on lines +441 to +444
use_flex_shard_instead_simple_fsdp: bool = False
"""Use FlexShard instead of simple_fsdp for model parameter sharding."""

flex_shard_placement_fn: "PlacementFn | None" = None

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 adds a second way to pick the FSDP backend: a boolean plus a free-floating PlacementFn callable on GraphTrainer.Config. #5842 (and its stack: #6010 EP, #6243 PP, #6011 chunked loss) adds parallelism.fsdp_backend = FlexShardConfig(), which picks the backend by config type. rules/config.md asks for that ("not by a mode string, a name lookup, or a boolean flag").

As written, a user who sets parallelism.fsdp_backend = FlexShardConfig() and runs GraphTrainer still gets SimpleFSDP, and the two FlexShard bucket builders will drift apart.

Smallest fix: drop both fields. Have GraphTrainer read parallelism.fsdp_backend (raise in __post_init__ for any backend it doesn't support). Put the placement policy on FlexShardConfig, or on a GraphTrainer subclass of it, rather than here.

Comment on lines +120 to +125
if self.config.use_flex_shard_instead_simple_fsdp:
from .flex_shard import FlexShardGradientClipper

self.optim.gradient_clipper = FlexShardGradientClipper(
self.config.optim.gradient_clipper,
)

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 replaces the configured clipper at runtime. Whatever optim.gradient_clipper the recipe set is silently thrown away and swapped for FlexShardGradientClipper, which only receives the old config. That breaks the "build complete, never mutate afterwards" rule, and the clipper is already a Configurable chosen by config type.

Give FlexShardGradientClipper its own Config, select it in the recipe or config, and raise in __post_init__ if FlexShard is selected with an incompatible clipper. Also check #5842, which changes components/optim/optim.py so the default clipper handles FlexShard's plain local shards. If that lands, this subclass may not be needed at all.

Comment on lines +522 to +532
policy_fn = _make_full_memory_policy(config.compile.full_recompute_save_ops)
force_save_nodes = None
if config.use_flex_shard_instead_simple_fsdp:
from torchtitan.experiments.graph_trainer.flex_shard import (
prepare_flex_shard_full_recompute,
)

force_save_nodes = prepare_flex_shard_full_recompute(
gm, policy_fn=policy_fn, parallelism=config.parallelism
)
tag_sac_policy(gm, policy_fn=policy_fn, force_save_nodes=force_save_nodes)

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.

Only the full policy is wired for FlexShard. default (the default memory_policy), eager, min_cut, and sac_and_offload don't call mark_flex_shard_unshard_recompute_regions_pass. default also finds unshards to save with _find_fsdp_unshard_save_nodes, which matches SimpleFSDP chains only, so it won't see FlexShard bucket unshards.

Expected effect (unverified, needs a memory snapshot), given that apply_flex_shard hard-codes reshard_after_forward=False and relies on graph remat for resharding:

  • with fsdp_reshard_after_forward=False, the bucket all-gathers can be recomputed in backward anyway;
  • with True, the new Pass 1b saves the _foreach_copy_/copy_ targets, so the full unsharded parameters stay alive until backward.

Either way the policy silently stops matching the config. Either wire FlexShard into every policy GraphTrainer supports, or raise ValueError in GraphTrainer.Config.__post_init__ for FlexShard with any policy other than full/none.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

default, full, and eager now prepare FlexShard unshard regions; sac_and_offload inherits default. In real DP2 tests with ordinary Shard and mixed block placements, never has three forward gathers; always adds two model-layer backward gathers with fresh buffers. Ten deterministic steps match eager loss, gradient norm, every gradient, parameters, and Adam state exactly.

none and min_cut retain their existing save-all/save-collectives behavior. SimpleFSDP min_cut also saves the gathers with both reshard settings. The paged-stash policy inherits the default preparation, but the dense paged runtime cases required an unrelated optional-HybridEP fix that is excluded from this PR; those cases are not evidence for the published tree.

Comment on lines +383 to +390
_is_backward_node(node)
or "recompute" not in node.meta
or not isinstance(node.target, torch._ops.OpOverload)
or not node.target._schema.is_mutable
or node.meta.get("recompute_region") is not None
):
continue
node.meta["recompute"] = CheckpointPolicy.MUST_SAVE
if "recompute" in node.meta:
node.meta["recompute"] = CheckpointPolicy.MUST_SAVE

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 changes the SimpleFSDP path too, not only FlexShard. On main, mutable forward ops without a recompute tag (for example writes under lm_head/loss, which Pass 1 skips) were ignored. Now their users get MUST_SAVE, and so do every mutation target and its base that carries a tag. That can change the save set, and so peak memory, for existing recipes.

The PR's table compares SimpleFSDP and FlexShard on this branch. It doesn't compare SimpleFSDP on main with SimpleFSDP on this branch. Please either gate the new behavior to FlexShard regions, or add main-vs-branch SimpleFSDP evidence (bitwise loss/grad_norm plus peak memory, with memory_policy=default and full).

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Compared SimpleFSDP on the PR parent fb1d2ba with the branch fixes: Llama DP2, default and full, reshard always, ten steps with seed 42 and strict determinism, regional Inductor, and real CUDA graph capture. Loss, actual clipping grad_norm, every gradient, parameters, Adam state, and TensorBoard values match exactly on every rank.

Steady-state peaks (steps 4-10) are identical for both policies and revisions: 49,375,744 allocated bytes and 121,634,816 reserved bytes per rank. HSDP replicate2 x shard2 with GA2, default, and reshard never also matches numerically and in steady-state peaks. These training comparisons preceded the latest mechanical refactors; subsequent FX snapshots are identical. This covers the tested DP2/HSDP configurations, not PP or EP.

Comment on lines +78 to +79
if _is_backward_node(node) and _get_module_fqn(node).startswith("layers."):
break

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 ungated change affects every GraphTrainer run. Region collection now stops at the first backward node whose module_fqn starts with layers., so any loss/lm_head node after that point no longer moves start_idx. It also hard-codes the Decoder FQN layout into the remat pass. What breaks on main without it, and is it FlexShard-specific? If it's a separate fix, it belongs in its own PR with the failing case. If it's FlexShard-only, gate it on the FlexShard regions.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This is a generic tied-weight case. When a layer weight is shared with lm_head, autograd can emit a final gradient-combining add after the layer backward that still carries the loss FQN. The old scan moves the loss boundary past the model backward and misses its recompute region.

The existing test_loss_region_excluded_from_remat passes with the guard and fails without it. A real CPU trace using the parent metadata/tagging functions reproduces the ordering without FlexShard. Separating this generic fix into another PR remains a scope question; it is not a FlexShard-only fix.

Comment on lines +138 to +140
parallelize_kwargs = {}
if config.use_flex_shard_instead_simple_fsdp:
parallelize_kwargs["use_flex_shard_instead_simple_fsdp"] = True

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.

Precompile passes only the boolean, not flex_shard_placement_fn. A recipe that sets a custom placement (for example configure_flex_shard_mxfp8_blocks) is precompiled with _default_placement_fn (plain Shard), while training uses block placements, so the precompiled artifact describes a different graph. Pass config.flex_shard_placement_fn too. Better still, reuse GraphTrainer._parallelize_kwargs so the two call sites can't diverge. The conditional dict is also unnecessary, because GraphTrainerModel.parallelize already accepts both kwargs.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Fixed: precompile now forwards config.flex_shard_placement_fn alongside the backend flag. The regression test verifies that the exact same callable reaches model.parallelize and produces the expected custom placements.

)

if use_flex_shard_instead_simple_fsdp:
from flex_shard.flex_shard.flex_shard import FlexShardModule

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.

flex_shard.flex_shard.flex_shard.FlexShardModule is an internal module path of the dependency, and the cast only satisfies the type checker. Use a public export, or add one upstream (with a TODO linking the flex_shard issue). Also: why does GraphPP need to reshard() and clear grads after metadata inference when the non-PP path doesn't? A short comment would help here.

from torchtitan.experiments.graph_trainer.trainer import GraphTrainer


class FlexShardMXFP8Linear(FlexShardPrequantizedLinear, Linear):

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 file isn't a test. It defines a model component (FlexShardMXFP8Linear), a placement policy, and a config transform, and torchtitan_recipes/tests/graph_trainer/b200.py imports it. Recipes shouldn't depend on an experiment's tests/ folder. Move it next to the code it extends (for example graph_trainer/flex_shard.py, or a quantization-adjacent module in the experiment). Also, the configure_* function mutates a finished config (setattr(parent, attr, ...), setting use_flex_shard_instead_simple_fsdp). That fits a ModelConfigTransform or the recipe builder better (see direction.md).

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The MXFP8 linear adapter, placement policy, and configuration helper now live together in graph_trainer/flex_shard.py; the recipe imports them there. The separate flex_shard_mxfp8.py module is removed. The moved definitions, recipe/meta-model configuration, and FX snapshots are unchanged. The helper still mutates the config, so the ModelConfigTransform part of this comment remains open.

Comment on lines +317 to +326
sources: dict[int, list[torch.Tensor]] = {}
for param, grad in zip(params, grads, strict=True):
if grad is None:
continue
param_sources = sources.setdefault(id(param), [])
# Tied weights can return the same combined gradient in multiple slots.
# Accumulate that source once per parameter in this graph call.
if any(_is_same_tensor_view(source, grad) for source in param_sources):
continue
param_sources.append(grad)

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 dedup runs for every backend. If tied weights double-accumulate on main with SimpleFSDP, that's a real bug with its own failing case, and it belongs in a separate PR with that example. If only FlexShard returns the same gradient view in two slots, say so in the comment. Then ask whether the graph should return the gradient once rather than deduplicating at accumulation time.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

In the tested DP2 tied-linear case, native FlexShard preserves one shared Parameter and returns two aliased views of its already-combined gradient. Without dedup, accumulation doubles that gradient. SimpleFSDP installs distinct sharded Parameters and distinct gradient storage in the same case; both backends match eager after accumulation.

Dedup checks Parameter identity and the exact source tensor view, so distinct gradient contributions still accumulate. The per-FQN graph-output slots preserve the state/layout calling convention; returning the gradient only once would also require changing that mapping.

@IvanKobzarev
IvanKobzarev force-pushed the graph-trainer-flex-shard-integration branch 3 times, most recently from 25aaade to e9abd52 Compare November 23, 2026 19:56
@IvanKobzarev

Copy link
Copy Markdown
Contributor Author

Follow-up on the CI item in the Claude review: both GraphTrainer GPU workflows now install git+https://github.com/meta-pytorch/flex_shard.git@main, and the SimpleFSDP BF16 Dist-MoE FSDP+EP B200 entry is retained. CI still depends on landing the companion meta-pytorch/flex_shard#125 because upstream main does not yet expose its annotation APIs; the dependency installation alone does not resolve that sequencing requirement.

@IvanKobzarev
IvanKobzarev force-pushed the graph-trainer-flex-shard-integration branch from e9abd52 to c8ecb2f Compare November 25, 2026 21:12
@IvanKobzarev
IvanKobzarev changed the base branch from main to pr-5842 November 25, 2026 21:13
tianyu-l added a commit that referenced this pull request Nov 26, 2026
… deterministic mode (#6398)

## Summary (human-written)
<!-- Write this yourself, not with an AI tool. 2-5 sentences: the
problem, why
     this approach, and what you checked yourself. -->

## Why
Since torch `2.16.0.dev20261125`, "1 GPU Integration (Fake PG)" fails on
every PR and "8 GPU Integration (Real PG - full suite - models)" fails
on main. The A10G golden losses drift in the low digits. Torch
`dev20261124` passed (last green: 11:04 UTC run 45601059954), and every
run after the nightly switch fails the same tests with the same values.

The cause is pytorch/pytorch#204322, "[inductor] Deterministic mode:
turn off Triton FMA contraction, emit explicit FMAs". In
`config.deterministic` mode, Inductor now compiles its generated Triton
kernels with `enable_fp_fusion=False`, so the result no longer depends
on which block size or `num_warps` autotuning picks. The golden runs set
`debug.deterministic=True`, so their rounding changes. This is an
intentional upstream numerics change, not a torchtitan bug, so the fix
is to regenerate the goldens.

**Example** (`llama3_fsdp+tp+cp`, Fake PG, A10G):

```
step  golden (dev20261124)          dev20261125
4     3.6361570  gn 0.76279575      3.6361570  gn 0.76279598
5     3.6227007                     3.6228001
10    3.4226971                     3.4225903
```

## How the cause was isolated
The two nightlies are 70 PyTorch commits apart
(283f59dd27...122eafd311), and the new torch also pins cuDNN 9.28.1 (was
9.26.0). I bisected locally on GB300 with `deepseek_v3_fsdp+ep` (Fake
PG), which reproduces the drift there. Each row below gives
bitwise-identical results on repeat runs.

| torch binary | cuDNN | Python change | step 1 loss |
| --- | --- | --- | --- |
| dev20261124 | 9.26.0 | -- | 7.990665912628174 |
| dev20261124 | 9.28.1 | -- | 7.990665912628174 |
| dev20261125 | 9.28.1 | -- | 7.990651607513428 |
| dev20261125 | 9.28.1 | dev20261124's `_inductor`/`_dynamo`/`fx`/... |
7.990665912628174 |
| dev20261125 | 9.28.1 | only #204322 reverted | **7.990665912628174** |
| dev20261125 | 9.28.1 | only #204320 reverted | 7.990651607513428 |
| dev20261125 | 9.28.1 | #184946, #206365, #203784, #203888 reverted |
7.990651607513428 |

So the cuDNN bump has no effect, and reverting #204322 alone restores
the old numerics bit for bit.

## What changed
Mechanical: the numeric rows of 11 golden files are replaced. Headers
and step counts are unchanged and were checked against the source
blocks.

| Golden file | Tests | max rel. loss diff | final loss old -> new |
| --- | --- | --- | --- |
| `fake_pg/a10g/llama3.txt` | `llama3_fsdp+tp+cp`, `+region_ac` |
3.1e-05 | 3.42270 -> 3.42259 |
| `fake_pg/a10g/deepseek_v3.txt` | `deepseek_v3_fsdp+ep` | 4.0e-05 |
6.32932 -> 6.32955 |
| `fake_pg/a10g/qwen3.txt` | `qwen3_moe_fsdp+tp+cp+ep_param_groups` |
5.5e-03 | 2.96522 -> 2.98026 |
| `fake_pg/a10g/muse_glimmer.txt` | `muse_glimmer_text_fsdp` | 3.4e-04 |
6.71710 -> 6.71748 |
| `real_pg/a10g/llama3.txt` | `llama3_fsdp+tp+cp`, `+region_ac` |
7.1e-05 | 4.05240 -> 4.05239 |
| `real_pg/a10g/llama3_pp.txt` | `llama3_fsdp+tp+pp` | 6.3e-05 | 4.19607
-> 4.19609 |
| `real_pg/a10g/deepseek_v3.txt` | `deepseek_v3_fsdp+ep` | 1.1e-04 |
3.81001 -> 3.81031 |
| `real_pg/a10g/deepseek_v3_cp_pp.txt` | `deepseek_v3_fsdp+cp+pp+ep` |
2.5e-04 | 3.83078 -> 3.83064 |
| `real_pg/a10g/gpt_oss_pp.txt` | `gpt_oss_pp+fsdp+cp+ep+sacop` |
1.7e-03 | 3.90803 -> 3.90858 |
| `real_pg/a10g/qwen3.txt` | `qwen3_moe_fsdp+tp+cp+ep_param_groups` |
6.8e-05 | 5.34935 -> 5.34934 |
| `real_pg/a10g/muse_glimmer.txt` | `muse_glimmer_text_fsdp` | 8.0e-03 |
3.71158 -> 3.70928 |

Over 10 steps, last-bit differences grow more in some runs than others
(`real_pg` `muse_glimmer` 8.0e-3, `gpt_oss_pp` 1.7e-3, `fake_pg` `qwen3`
5.5e-3). Final losses move in both directions. Fake PG grad norms are
already meaningless (up to ~1e17) and change by more.

`{fake_pg,real_pg}/a10g/sft.txt` are unchanged and still pass.
`gpt_oss_fsdp+tp+ep` (`gpt_oss.txt`), and `gpt_oss_pp+fsdp+ep+sacop` in
Real PG, crash under `dev20261125` for a separate reason.
pytorch/pytorch#206398 made varlen's lse differentiable, and only FA4
can backpropagate through it. That is fixed in a separate PR, so this
PR's Fake PG and Real PG jobs still fail on those two tests.

## Numerics
The new values are the "Baseline metrics in import file format" blocks
that `loss_compare` printed in the A10G CI logs under `dev20261125`.
A10G numerics can't be reproduced off that hardware, so they come
straight from CI. The values agree across runs:
- Fake PG: #6395 (main HEAD deb3e43) == #6245 == #5678 == #6389. #5629
differs only in tests its own changes touch.
- Real PG: main 7ccb1bb == d2a8af2 == 7a60bbb == 8919259 (the
scheduled run).

## Testing
- This PR's CI is the test. `ciflow/fake-pg` checks the 4 fake-PG files.
`ciflow/real-pg` is added so the full Real PG suite checks all 7 real-PG
files. The `real_pg_required` subset only covers `llama3_pp`,
`deepseek_v3_cp_pp` and `gpt_oss_pp`.
- The local bisection above used `python -m
tests.integration_tests.run_tests --execution_mode fake_pg --ngpu 1
--test_name deepseek_v3_fsdp+ep` on GB300, with each torch/cuDNN
combination as a `PYTHONPATH` overlay.
- `pre-commit run` on the changed files passes.

## Known issues / follow-ups
- `real_pg/mi350x/*` is not updated. The ROCm workflow
(`integration_test_rocm.yaml`) still passes on main because the ROCm
nightly index serves torch `dev20261119`, which predates #204322 (run
45670678052). Expect the same drift on MI350X once the ROCm nightly
advances. Those goldens need a refresh from that run's logs then.
- `real_pg/kimi_k3_b200.txt` (B200 workflow) and `rl_grpo_cuda.txt` (RL
loss guard) are unaffected for now. Those jobs end up on pinned older
torch (`dev20261102` and `dev20261107` in today's runs). Expect the same
drift when their torch pins move past `dev20261125`.
- The goldens track whatever nightly CI installs, so a later nightly can
shift them again.
@IvanKobzarev
IvanKobzarev force-pushed the graph-trainer-flex-shard-integration branch 2 times, most recently from 83c75b7 to 56ae4f8 Compare November 30, 2026 20:47
@IvanKobzarev
IvanKobzarev force-pushed the graph-trainer-flex-shard-integration branch from 56ae4f8 to fafd9d5 Compare December 1, 2026 13:09
Port the Cuspy configuration and golden-loss updates from pytorch#6390 and pytorch#6398. Use the GPT-OSS attention backend split from pytorch#6400 so varlen LSE backward runs on FA4 hardware. Select both Gloo and NCCL for the Muon CPU-offload test mesh.
Install the FlexShard revision that supplies make_fx tracing hooks and collective metadata. Recognize PartitionSpec EP shards when reducing gradient norms, use complete parallelism fixtures, and align precompile attention metadata with training. Include the working-tree graph-region and recompute refactor.
Remove the nightly profiler, golden-loss, core model-test, and optimizer fixture updates. Retain the GraphTrainer dependency pin, test fixtures, EP clipping repair, and existing working-tree refactor.
Ubuntu package setup failed over HTTPS too. Keep the PR focused on the proven GraphTrainer fixes; runner archive connectivity needs an infrastructure fix.

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/b200 Trigger B200 CI ciflow/fake-pg Run 1-GPU Fake PG integration tests ciflow/h100.8 Trigger H100.8 CI 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.

2 participants