Repository navigation
Conversation
🔗 Helpful Links🧪 See artifacts and rendered test results at hud.pytorch.org/pr/200179
Note: Links to docs will display an error until the docs builds have been completed. ✅ No FailuresAs of commit c56fb65 with merge base 90ef23c ( 🟡 GREEN LIGHT - OUTDATED (earlier commit) - PR requires human review:
reason: This comment was automatically generated by Dr. CI and updates every 15 minutes. |
…ard bit for bit torchtitan is getting a toggle between FSDP2 and FlexShard, and training with FlexShard's Shard placements should then be bitwise identical to FSDP2's. Matching placements is not enough: NCCL sums each element of a reduce-scatter in an order fixed by the buffer's layout and size, so a bucket's buffers have to match the fully_shard group's byte for byte. FlexShard's Shard buckets differed in three ways. They order parameters as named_parameters() does, while fully_shard walks its modules in post-order and takes a module's own parameters after its children's. They reduce-scatter every trainable parameter, with zeros for missing grads, while FSDP2 leaves out parameters without a grad. And FSDP2 groups the reduce-scatter by sharded grad dtype. torchtitan also shards stacked linears on their matrix rows, which FlexShard buckets rejected: they supported only Shard(0). Buckets now take Shard(i) on any dim, mixed in one bucket, with FSDP2's rules: Shard(i > 0) must split evenly, and only Shard(0) pads. A Shard bucket copies its parameters directly between their layouts and the collective buffers with FSDP's native collective copies. fsdp::_all_gather_copy_out_, from pytorch/pytorch#197204 (landed as 90ef23c2ba6), writes every rank's chunk into its strided place in the parameter, given each tensor's leading size, the product of the dims before its shard dim (1 for Shard(0)), with the kernel behind split_with_sizes_copy. fsdp::chunk_cat_mixed_dtype, given the number of dims before each grad's shard dim through num_leading_dims from pytorch/pytorch#200179, chunks each grad along its shard dim straight into the reduce-scatter buffer, casting it to the reduce dtype as it copies, with chunk_cat's fused kernel; grads of mixed dtypes share one call. FSDP2's default copies reorder Shard(i > 0) chunks through temporaries instead; both fill the same buffers. Non-contiguous Shard(i > 0) grads are reordered first. FlexShard calls the ops unconditionally, so Shard placements need a PyTorch with pytorch/pytorch#197204 and pytorch/pytorch#200179, as the README says: a nightly or source build with both until a release includes them, after which FlexShard's minimum PyTorch goes up. BucketSpec(fsdp2_compatible=True) gives a bucket fully_shard's parameter order and reduce-scatter order, and leaves parameters without a grad out of the reduce-scatter; like FSDP2, every rank must then produce grads for the same parameters. It requires Shard placements. get_mesh returns a FlexShard parameter's bucket mesh, next to get_placements and get_global_shape, so a caller can view local grads as the DTensors FSDP2 would give it, e.g. for torchtitan's grad-norm clipping. test_flex_shard_fsdp2_parity compares fsdp2_compatible buckets with fully_shard on four GPUs, where sums of four values make the reduction order observable. Its toy decoder has torchtitan's FSDP groups (embeddings, one per block, the norm with the output projection, the root), Shard(1) stacked linears, uneven Shard(0) parameters with an empty shard on the last rank, a block that owns a parameter registered before its children, and unused and frozen parameters. Over param/reduce dtypes fp32/None, bf16/fp32, bf16/bf16 and bf16/None, the default divide factor and torchtitan's 1.0, and one microbatch, two synced microbatches or two with no-sync, the all-gather and reduce-scatter inputs, losses, local grads and AdamW parameters match bit for bit over three steps. The test fails with fsdp2_compatible off, with zeros kept for missing grads, and with wrong leading sizes in the native copy-out. Its grads never mix dtypes in one copy-in, so a unit test checks that case against FSDP2's reorder and chunk_cat, with bf16 and fp32 grads on Shard(0), Shard(1) and Shard(2) in one bucket; it fails if the copy-in chunks Shard(i > 0) grads along dim 0. The tests ran on PyTorch 2.16.0a0+git90ef23c with pytorch/pytorch#200179, so the parity test checks the native CUDA kernels. On an H100 with 8 shards, bf16 parameters and fp32 reduction, the native copies of a Llama 3 8B transformer block, whose stacked w13 is Shard(1), take 0.446 ms for the copy-out and 0.853 ms for the copy-in, against 0.676 ms and 1.175 ms when the Shard(1) chunks go through 224 MiB of temporaries. For 4 routed experts row-sharded over 8 shards they take 0.219 ms and 0.406 ms, against 0.422 ms and 0.716 ms (medians of 3 runs). ghstack-source-id: 864fbc1 Pull-Request: #48
…ard bit for bit torchtitan is getting a toggle between FSDP2 and FlexShard, and training with FlexShard's Shard placements should then be bitwise identical to FSDP2's. Matching placements is not enough: NCCL sums each element of a reduce-scatter in an order fixed by the buffer's layout and size, so a bucket's buffers have to match the fully_shard group's byte for byte. FlexShard's Shard buckets differed in three ways. They order parameters as named_parameters() does, while fully_shard walks its modules in post-order and takes a module's own parameters after its children's. They reduce-scatter every trainable parameter, with zeros for missing grads, while FSDP2 leaves out parameters without a grad. And FSDP2 groups the reduce-scatter by sharded grad dtype. torchtitan also shards stacked linears on their matrix rows, which FlexShard buckets rejected: they supported only Shard(0). Buckets now take Shard(i) on any dim, mixed in one bucket, with FSDP2's rules: Shard(i > 0) must split evenly, and only Shard(0) pads. A Shard bucket copies its parameters directly between their layouts and the collective buffers with FSDP's native collective copies. fsdp::_all_gather_copy_out_, from pytorch/pytorch#197204 (landed as 90ef23c2ba6), writes every rank's chunk into its strided place in the parameter, given each tensor's leading size, the product of the dims before its shard dim (1 for Shard(0)), with the kernel behind split_with_sizes_copy. fsdp::chunk_cat_mixed_dtype, given the number of dims before each grad's shard dim through num_leading_dims from pytorch/pytorch#200179, chunks each grad along its shard dim straight into the reduce-scatter buffer, casting it to the reduce dtype as it copies, with chunk_cat's fused kernel; grads of mixed dtypes share one call. FSDP2's default copies reorder Shard(i > 0) chunks through temporaries instead; both fill the same buffers. Non-contiguous Shard(i > 0) grads are reordered first. FlexShard calls the ops unconditionally, so Shard placements need a PyTorch with pytorch/pytorch#197204 and pytorch/pytorch#200179, as the README says: a nightly or source build with both until a release includes them, after which FlexShard's minimum PyTorch goes up. BucketSpec(fsdp2_compatible=True) gives a bucket fully_shard's parameter order and reduce-scatter order, and leaves parameters without a grad out of the reduce-scatter; like FSDP2, every rank must then produce grads for the same parameters. It requires Shard placements. get_mesh returns a FlexShard parameter's bucket mesh, next to get_placements and get_global_shape, so a caller can view local grads as the DTensors FSDP2 would give it, e.g. for torchtitan's grad-norm clipping. test_flex_shard_fsdp2_parity compares fsdp2_compatible buckets with fully_shard on four GPUs, where sums of four values make the reduction order observable. Its toy decoder has torchtitan's FSDP groups (embeddings, one per block, the norm with the output projection, the root), Shard(1) stacked linears, uneven Shard(0) parameters with an empty shard on the last rank, a block that owns a parameter registered before its children, and unused and frozen parameters. Over param/reduce dtypes fp32/None, bf16/fp32, bf16/bf16 and bf16/None, the default divide factor and torchtitan's 1.0, and one microbatch, two synced microbatches or two with no-sync, the all-gather and reduce-scatter inputs, losses, local grads and AdamW parameters match bit for bit over three steps. The test fails with fsdp2_compatible off, with zeros kept for missing grads, and with wrong leading sizes in the native copy-out. Its grads never mix dtypes in one copy-in, so a unit test checks that case against FSDP2's reorder and chunk_cat, with bf16 and fp32 grads on Shard(0), Shard(1) and Shard(2) in one bucket; it fails if the copy-in chunks Shard(i > 0) grads along dim 0. The tests ran on PyTorch 2.16.0a0+git90ef23c with pytorch/pytorch#200179, so the parity test checks the native CUDA kernels. On an H100 with 8 shards, bf16 parameters and fp32 reduction, the native copies of a Llama 3 8B transformer block, whose stacked w13 is Shard(1), take 0.446 ms for the copy-out and 0.853 ms for the copy-in, against 0.676 ms and 1.175 ms when the Shard(1) chunks go through 224 MiB of temporaries. For 4 routed experts row-sharded over 8 shards they take 0.219 ms and 0.406 ms, against 0.422 ms and 0.716 ms (medians of 3 runs). ghstack-source-id: e207d4b Pull-Request: #48
| // keeping its leading dims in each chunk, as Shard(i) needs for i > 0. | ||
| m.def( | ||
| "chunk_cat_mixed_dtype(Tensor[] tensors, int dim, int num_chunks, *, Tensor(a!) out) -> ()"); | ||
| "chunk_cat_mixed_dtype(Tensor[] tensors, int dim, int num_chunks, *, Tensor(a!) out, int[]? num_leading_dims=None) -> ()"); |
There was a problem hiding this comment.
num_leading_dims comes after out here, and the FC check in the backwards_compat job flags it: "Function schema should have the same number of out arguments". The check finds the first out arg and counts everything after it as out args, so num_leading_dims looks like a second one. Can we move it before out?
There was a problem hiding this comment.
the original chunk_cat_mixed_dtype is landed this morning, and i am doing a fast follow up on num_leading_dims. i changed added this fsdp folder to allowlist, just like csrs/c10d . error should be gone after that
|
@pytorchmergebot merge |
Merge startedYour change will be merged once all checks pass (ETA 0-4 Hours). Learn more about merging in the wiki. Questions? Feedback? Please reach out to the PyTorch DevX Team |
Merge failedReason: 1 mandatory check(s) failed. The first few are: Dig deeper by viewing the failures on hud |
This PR was authored with an AI assistant (Claude Code). The description below is AI-generated and is pending author review. > #197204 added `fsdp::_reduce_scatter_copy_in_` next to > `fsdp::chunk_cat_mixed_dtype`. Both pack gradients into a reduce-scatter > input with the same CUDA kernel, but `_reduce_scatter_copy_in_` takes leading > dims with one input dtype, and `chunk_cat_mixed_dtype` takes mixed dtypes > without leading dims. A group with both, such as a Shard(1) bf16 weight next > to an fp32 norm, had to reorder its Shard(i > 0) gradients through > temporaries before the copy-in. > > This gives `chunk_cat_mixed_dtype` an optional `num_leading_dims` and removes > `_reduce_scatter_copy_in_`, which nothing in PyTorch calls yet. With dim 0, a > nonzero `num_leading_dims[i]` chunks `tensors[i]` along that dim, keeping its > leading dims in each chunk, as Shard(i) needs for i > 0. On CUDA, leading > dims or mixed dtypes take the fused kernel. It copies inputs of out's dtype > and casts one other dtype into an fp32 out, which can now be fp16 as well as > bf16, since `_reduce_scatter_copy_in_` cast fp16. So mixed fp16/fp32 groups > no longer cast each gradient first. The composite and input checks move over > from `_reduce_scatter_copy_in_`, except that inputs must be castable to out's > dtype instead of sharing one dtype. The op registers its composite for > Functionalize, as `_reduce_scatter_copy_in_` did, so functionalized traces > decompose it instead of auto-functionalizing it. FSDP2 runs its > reduce-scatter in hooks that Dynamo skips, so its traces don't change. > > Widening `_reduce_scatter_copy_in_` to mixed dtypes instead would have left > two ops for one copy-in. #197701, the FSDP2 opt-in, can then pass > `num_leading_dims` to `chunk_cat_mixed_dtype`. > > Test Plan > > ``` > python test/distributed/_composable/fsdp/test_fully_shard_comm.py > python test/distributed/_composable/fsdp/test_fully_shard_mixed_precision.py > ``` > > The new leading-dims numerics test covers each dtype mix the fused kernel > takes and one it doesn't. `test_kernels` checks for two fused launches with > and without leading dims, `opcheck` covers both paths, and the CUDA graph > test replays the copy-in through `chunk_cat_mixed_dtype`. Both files pass on > 4 H100s except `test_fully_shard_alloc_from_pg`, which fails on this machine > because its NCCL 2.30.7 logs buffer registrations even for plain collectives > without FSDP, and the test asserts there are none. > > FlexShard, with its copy-in switched to `num_leading_dims`, passes its suite > on this build, including its bit-for-bit parity test against `fully_shard`. > Its copy-in for a Llama 3 8B block over 8 shards takes 0.85 ms on an H100, as > with `_reduce_scatter_copy_in_`. ghstack-source-id: 07b9821 Pull-Request: #200179
|
@pytorchmergebot merge |
Merge startedYour change will be merged once all checks pass (ETA 0-4 Hours). Learn more about merging in the wiki. Questions? Feedback? Please reach out to the PyTorch DevX Team |
torchtitan shards stacked linears, such as the w13 of every Llama 3 feed-forward, and routed experts on their matrix rows, Shard(1), while FlexShard buckets took only Shard(0). Buckets now take Shard(i) on any dim, mixed in one bucket, with FSDP2's rules: Shard(i > 0) must split evenly, and only Shard(0) pads. A Shard bucket copies its parameters directly between their layouts and the collective buffers with FSDP's native collective copies, as FSDP2's with_native_copy functions do. fsdp::_all_gather_copy_out_, from pytorch/pytorch#197204 (landed as 90ef23c2ba6), writes every rank's chunk into its strided place in the parameter, given each tensor's leading size, the product of the dims before its shard dim (1 for Shard(0)), with the kernel behind split_with_sizes_copy. fsdp::chunk_cat_mixed_dtype, given the number of dims before each grad's shard dim through num_leading_dims from pytorch/pytorch#200179, chunks each grad along its shard dim straight into the reduce-scatter buffer, casting it to the reduce dtype as it copies, with chunk_cat's fused kernel; grads of mixed dtypes share one call. FSDP2's default copies reorder Shard(i > 0) chunks through temporaries instead; both fill the same buffers. Non-contiguous Shard(i > 0) grads are reordered first. FlexShard calls the ops unconditionally, so Shard placements need a PyTorch with pytorch/pytorch#197204 and pytorch/pytorch#200179, as the README says: a nightly or source build with both until a release includes them, after which FlexShard's minimum PyTorch goes up. get_mesh returns a FlexShard parameter's bucket mesh, next to get_placements and get_global_shape, so a caller can view local grads as the DTensors FSDP2 would give it, e.g. for torchtitan's grad-norm clipping. test_flex_shard_fsdp2_parity trains a toy decoder on two GPUs through fully_shard and through FlexShard buckets with the same groups and placements: torchtitan's FSDP groups (embeddings, one per block, the norm with the output projection, the root), Shard(1) stacked linears and uneven Shard(0) parameters. The buckets order their parameters differently from fully_shard, but a sum of two values does not depend on order, so losses, local grads and AdamW parameters match bit for bit over three steps. That holds over param/reduce dtypes fp32/None, bf16/fp32, bf16/bf16 and bf16/None, the default divide factor and torchtitan's 1.0, and one microbatch, two synced microbatches or two with no-sync. The test fails with wrong leading sizes in the copy-out and with Shard(i > 0) grads chunked along dim 0 in the copy-in. A unit test checks a copy-in of bf16 and fp32 grads on Shard(0), Shard(1) and Shard(2) against FSDP2's reorder and chunk_cat. The tests ran on PyTorch 2.16.0a0+git90ef23c with pytorch/pytorch#200179. On an H100 with 8 shards, bf16 parameters and fp32 reduction, the native copies of a Llama 3 8B transformer block, whose stacked w13 is Shard(1), take 0.446 ms for the copy-out and 0.853 ms for the copy-in, against 0.676 ms and 1.175 ms when the Shard(1) chunks go through 224 MiB of temporaries. For 4 routed experts row-sharded over 8 shards they take 0.219 ms and 0.406 ms, against 0.422 ms and 0.716 ms (medians of 3 runs). ghstack-source-id: d8e5851 ghstack-comment-id: 6049586021 Pull-Request: #51
torchtitan shards stacked linears, such as the w13 of every Llama 3 feed-forward, and routed experts on their matrix rows, Shard(1), while FlexShard buckets took only Shard(0). Buckets now take Shard(i) on any dim, mixed in one bucket, with FSDP2's rules: Shard(i > 0) must split evenly, and only Shard(0) pads. A Shard bucket copies its parameters directly between their layouts and the collective buffers with FSDP's native collective copies, as FSDP2's with_native_copy functions do. fsdp::_all_gather_copy_out_, from pytorch/pytorch#197204 (landed as 90ef23c2ba6), writes every rank's chunk into its strided place in the parameter, given each tensor's leading size, the product of the dims before its shard dim (1 for Shard(0)), with the kernel behind split_with_sizes_copy. fsdp::chunk_cat_mixed_dtype, given the number of dims before each grad's shard dim through num_leading_dims from pytorch/pytorch#200179, chunks each grad along its shard dim straight into the reduce-scatter buffer, casting it to the reduce dtype as it copies, with chunk_cat's fused kernel; grads of mixed dtypes share one call. FSDP2's default copies reorder Shard(i > 0) chunks through temporaries instead; both fill the same buffers. Non-contiguous Shard(i > 0) grads are reordered first. FlexShard calls the ops unconditionally, so Shard placements need a PyTorch with pytorch/pytorch#197204 and pytorch/pytorch#200179, as the README says: a nightly or source build with both until a release includes them, after which FlexShard's minimum PyTorch goes up. get_mesh returns a FlexShard parameter's bucket mesh, next to get_placements and get_global_shape, so a caller can view local grads as the DTensors FSDP2 would give it, e.g. for torchtitan's grad-norm clipping. test_flex_shard_fsdp2_parity trains a toy decoder on two GPUs through fully_shard and through FlexShard buckets with the same groups and placements: torchtitan's FSDP groups (embeddings, one per block, the norm with the output projection, the root), Shard(1) stacked linears and uneven Shard(0) parameters. The buckets order their parameters differently from fully_shard, but a sum of two values does not depend on order, so losses, local grads and AdamW parameters match bit for bit over three steps. That holds over param/reduce dtypes fp32/None, bf16/fp32, bf16/bf16 and bf16/None, the default divide factor and torchtitan's 1.0, and one microbatch, two synced microbatches or two with no-sync. The test fails with wrong leading sizes in the copy-out and with Shard(i > 0) grads chunked along dim 0 in the copy-in. A unit test checks a copy-in of bf16 and fp32 grads on Shard(0), Shard(1) and Shard(2) against FSDP2's reorder and chunk_cat. The tests ran on PyTorch 2.16.0a0+git90ef23c with pytorch/pytorch#200179. On an H100 with 8 shards, bf16 parameters and fp32 reduction, the native copies of a Llama 3 8B transformer block, whose stacked w13 is Shard(1), take 0.446 ms for the copy-out and 0.853 ms for the copy-in, against 0.676 ms and 1.175 ms when the Shard(1) chunks go through 224 MiB of temporaries. For 4 routed experts row-sharded over 8 shards they take 0.219 ms and 0.406 ms, against 0.422 ms and 0.716 ms (medians of 3 runs). ghstack-source-id: d8e5851 ghstack-comment-id: 6049586021 Pull-Request: #51
torchtitan shards stacked linears, such as the w13 of every Llama 3 feed-forward, and routed experts on their matrix rows, Shard(1), while FlexShard buckets took only Shard(0). Buckets now take Shard(i) on any dim, mixed in one bucket, with FSDP2's rules: Shard(i > 0) must split evenly, and only Shard(0) pads. A Shard bucket copies its parameters directly between their layouts and the collective buffers with FSDP's native collective copies, as FSDP2's with_native_copy functions do. fsdp::_all_gather_copy_out_, from pytorch/pytorch#197204 (landed as 90ef23c2ba6), writes every rank's chunk into its strided place in the parameter, given each tensor's leading size, the product of the dims before its shard dim (1 for Shard(0)), with the kernel behind split_with_sizes_copy. fsdp::chunk_cat_mixed_dtype, given the number of dims before each grad's shard dim through num_leading_dims from pytorch/pytorch#200179, chunks each grad along its shard dim straight into the reduce-scatter buffer, casting it to the reduce dtype as it copies, with chunk_cat's fused kernel; grads of mixed dtypes share one call. FSDP2's default copies reorder Shard(i > 0) chunks through temporaries instead; both fill the same buffers. Non-contiguous Shard(i > 0) grads are reordered first. FlexShard calls the ops unconditionally, so Shard placements need a PyTorch with pytorch/pytorch#197204 and pytorch/pytorch#200179, as the README says: a nightly or source build with both until a release includes them, after which FlexShard's minimum PyTorch goes up. get_mesh returns a FlexShard parameter's bucket mesh, next to get_placements and get_global_shape, so a caller can view local grads as the DTensors FSDP2 would give it, e.g. for torchtitan's grad-norm clipping. test_flex_shard_fsdp2_parity trains a toy decoder on two GPUs through fully_shard and through FlexShard buckets with the same groups and placements: torchtitan's FSDP groups (embeddings, one per block, the norm with the output projection, the root), Shard(1) stacked linears and uneven Shard(0) parameters. The buckets order their parameters differently from fully_shard, but a sum of two values does not depend on order, so losses, local grads and AdamW parameters match bit for bit over three steps. That holds over param/reduce dtypes fp32/None, bf16/fp32, bf16/bf16 and bf16/None, the default divide factor and torchtitan's 1.0, and one microbatch, two synced microbatches or two with no-sync. The test fails with wrong leading sizes in the copy-out and with Shard(i > 0) grads chunked along dim 0 in the copy-in. A unit test checks a copy-in of bf16 and fp32 grads on Shard(0), Shard(1) and Shard(2) against FSDP2's reorder and chunk_cat. The tests ran on PyTorch 2.16.0a0+git90ef23c with pytorch/pytorch#200179. On an H100 with 8 shards, bf16 parameters and fp32 reduction, the native copies of a Llama 3 8B transformer block, whose stacked w13 is Shard(1), take 0.446 ms for the copy-out and 0.853 ms for the copy-in, against 0.676 ms and 1.175 ms when the Shard(1) chunks go through 224 MiB of temporaries. For 4 routed experts row-sharded over 8 shards they take 0.219 ms and 0.406 ms, against 0.422 ms and 0.716 ms (medians of 3 runs). ghstack-source-id: d8e5851 ghstack-comment-id: 6049586021 Pull-Request: #51
This PR was authored with an AI assistant (Claude Code). The description below is AI-generated and is pending author review. > With gradient accumulation and `set_is_last_backward(False)`, FSDP2 keeps > `post_forward_order` across backwards: only the last backward's > `_end_backward_iteration` clears it. Each forward appends after the previous > forward's entries, so in every microbatch after the first, the first group's > implicit backward prefetch targets the previous forward's last group. That is > a no-op while the target is unsharded. But when only the last backward > reshards (`set_reshard_after_backward(True)` on the last microbatch, as > torchtitan does with deferred gradient reduction), the last group reshards > after its own backward, and the first group's backward all-gathers it again > for nothing. In torchtitan, with DeepSeek V3 layers and 16 accumulated > microbatches, that is one extra 1.77 GB all-gather of the output projection > per step. > > The root's post-backward final callback now clears `post_forward_order` once > no group holds a post-forward index, that is, once every recorded forward has > run its backward. Under pipeline schedules, groups of microbatches whose > backward hasn't run yet still hold indices, so the order is kept for them, as > before. Clearing after every backward instead would drop their entries. > > Only the implicit backward prefetch popped a group's index, so a group with > explicit backward prefetch (`set_modules_to_backward_prefetch`) kept its > indices and the clear never ran. torchtitan sets explicit backward prefetch on > the transformer blocks and the output projection, leaving only the first > module implicit. `pre_backward` now pops the index under explicit prefetch > too. > > Test Plan > > ``` > python test/distributed/_composable/fsdp/test_fully_shard_comm.py -k TestFullyShardPrefetch > ``` > > `test_backward_prefetch_with_gradient_accumulation` runs with and without > explicit backward prefetch on the later modules: no backward may unshard a > module that the last microbatch's backward resharded. The implicit variant > fails without the clear, and the explicit variant fails without the pop in > `pre_backward`. The prefetch tests ran with this change on 4 H100s, on a build > of 90ef23c plus #200179. All pass except > `test_unused_backward_prefetch_with_post_forward_mesh`, which needs #199729 > and fails the same way on that build without this change. > > In torchtitan, on that build with this change, a half-scale run (8 H100s, 16 > accumulated microbatches, deferred reduction, 10 steps) has 10 all-gathers per > step instead of 11, and no backward prefetch targets a sharded group. Loss and > grad norm are bitwise equal to a run without the change, and step time and > peak reserved memory are unchanged. A pipeline-parallel run (2 ranks x 8 > virtual stages, Interleaved1F1B, 16 microbatches) is bitwise equal as well. ghstack-source-id: 17aa446 Pull-Request: #200476
…orch#200179) This PR was authored with an AI assistant (Claude Code). The description below is AI-generated and is pending author review. > pytorch#197204 added `fsdp::_reduce_scatter_copy_in_` next to > `fsdp::chunk_cat_mixed_dtype`. Both pack gradients into a reduce-scatter > input with the same CUDA kernel, but `_reduce_scatter_copy_in_` takes leading > dims with one input dtype, and `chunk_cat_mixed_dtype` takes mixed dtypes > without leading dims. A group with both, such as a Shard(1) bf16 weight next > to an fp32 norm, had to reorder its Shard(i > 0) gradients through > temporaries before the copy-in. > > This gives `chunk_cat_mixed_dtype` an optional `num_leading_dims` and removes > `_reduce_scatter_copy_in_`, which nothing in PyTorch calls yet. With dim 0, a > nonzero `num_leading_dims[i]` chunks `tensors[i]` along that dim, keeping its > leading dims in each chunk, as Shard(i) needs for i > 0. On CUDA, leading > dims or mixed dtypes take the fused kernel. It copies inputs of out's dtype > and casts one other dtype into an fp32 out, which can now be fp16 as well as > bf16, since `_reduce_scatter_copy_in_` cast fp16. So mixed fp16/fp32 groups > no longer cast each gradient first. The composite and input checks move over > from `_reduce_scatter_copy_in_`, except that inputs must be castable to out's > dtype instead of sharing one dtype. The op registers its composite for > Functionalize, as `_reduce_scatter_copy_in_` did, so functionalized traces > decompose it instead of auto-functionalizing it. FSDP2 runs its > reduce-scatter in hooks that Dynamo skips, so its traces don't change. > > Widening `_reduce_scatter_copy_in_` to mixed dtypes instead would have left > two ops for one copy-in. pytorch#197701, the FSDP2 opt-in, can then pass > `num_leading_dims` to `chunk_cat_mixed_dtype`. > > Test Plan > > ``` > python test/distributed/_composable/fsdp/test_fully_shard_comm.py > python test/distributed/_composable/fsdp/test_fully_shard_mixed_precision.py > ``` > > The new leading-dims numerics test covers each dtype mix the fused kernel > takes and one it doesn't. `test_kernels` checks for two fused launches with > and without leading dims, `opcheck` covers both paths, and the CUDA graph > test replays the copy-in through `chunk_cat_mixed_dtype`. Both files pass on > 4 H100s except `test_fully_shard_alloc_from_pg`, which fails on this machine > because its NCCL 2.30.7 logs buffer registrations even for plain collectives > without FSDP, and the test asserts there are none. > > FlexShard, with its copy-in switched to `num_leading_dims`, passes its suite > on this build, including its bit-for-bit parity test against `fully_shard`. > Its copy-in for a Llama 3 8B block over 8 shards takes 0.85 ms on an H100, as > with `_reduce_scatter_copy_in_`. Pull Request resolved: pytorch#200179 Approved by: https://github.com/anshul-si
## BC-breaking? > No: adds an experimental setter and module; FSDP's default copies are unchanged. ## Summary (human written only) better perf for Shard(1)/Shard(2) to unblock torchtitan EFSDP sharding ## Agent details (if applicable) > AI-assisted implementation and summary prepared with Codex and Claude Code. > > Add an `FSDPModule.set_reduce_scatter_input_fn` setter, and call the native all-gather copy-out (`fsdp::_all_gather_copy_out_`, #197204) and reduce-scatter copy-in (`fsdp::chunk_cat_mixed_dtype` with `num_leading_dims`, #200179) through `torch.distributed.fsdp.experimental`, which exports `AllGatherInput`, `all_gather_output_fn_with_native_copy` and `reduce_scatter_input_fn_with_native_copy`. The original intermediate copies remain the defaults. The all-gather copy-out has no setter here: #199726 installs it through `set_all_gather_layout` as `DefaultAllGatherLayout(all_gather_output_fn_with_native_copy)`; until then, the tests here install it through the private `FSDPParamGroup._all_gather_output_fn` hook. > > The all-gather op copies within one dtype, so its callback copies mixed-dtype groups as bytes, and it requires exact output sizes, so the callback uses the default copy-out for groups with a Tensor payload smaller than its cached output. The reduce-scatter copy-in takes mixed gradient dtypes, such as a deferred bf16 Shard(1) weight gradient next to an fp32 norm gradient, so it needs no dtype fallback; noncontiguous gradients sharded on a nonzero dim still use the chunk-and-concatenate reorder. > > Native copying writes contiguous tensors without intermediate buffers and benefits wide CUDA tensors with small outer_size, such as Shard(1) over [2,F,D]. Its CPU time, GPU time and metadata memory grow with a group's total outer size, and strided collective buffers take a slower path, so the documentation recommends benchmarking the target workload. > > Test Plan: > ```bash > python test/distributed/_composable/fsdp/test_fully_shard_comm.py -k test_strided_allocation -k test_reduce_scatter_input_fn_setter -k TestFullyShardNativeReduceScatterInputFn > python test/distributed/_composable/fsdp/test_fully_shard_extensions.py -k test_all_gather_input_layouts -k test_all_gather_extension_smaller_payload > python test/distributed/_composable/fsdp/test_fully_shard_mixed_precision.py -k test_reduce_dtype -k test_native_copy_in_mixed_grad_dtypes > python test/distributed/_composable/fsdp/test_fully_shard_training.py -k test_train_parity_single_group -k test_inference > python test/test_public_bindings.py -k test_correct_module_names > ``` > All pass on this revision. `test_native_copy_in_mixed_grad_dtypes` fails if the callback falls back to the default copy-in for mixed gradient dtypes, `test_strided_allocation` if a copy reorders its input, `test_reduce_scatter_input_fn_setter` if the setter ignores `recurse` or `None`, `test_all_gather_input_layouts` if the native all-gather copy falls back to the default one, and `test_all_gather_extension_smaller_payload` if it has no fallback for smaller payloads. > > Measured on one B200 with world-size-8 layouts (copies only, native time / default time): a [2, 8192, 4096] Shard(1) group copies out in 0.53x GPU and 0.41x CPU time and copies in in 0.38 to 0.45x GPU and 0.67 to 0.70x CPU time; Shard(1) experts [2/8, 1408, 2048] x3 copy out in 0.36 to 0.51x GPU time; native copies of contiguous tensors also skip the intermediate buffers, lowering a Shard(1)/Shard(2) group's peak memory by about 24 to 830 MB. Groups with many rows before the shard dim are slower: Shard(2) experts copy out in 1.7 to 1.8x GPU time and up to 5.6x CPU time, and a Llama-8B block's Shard(1) parameters (outer size 43010) copy out in 0.74 to 0.78x GPU but 3.2 to 4.4x CPU time, which is why the documentation recommends benchmarking. Pull Request resolved: #197701 Approved by: https://github.com/anshul-si ghstack dependencies: #200985, #200986, #200034
This PR was authored with an AI assistant (Claude Code). The description below is AI-generated and is pending author review. > With gradient accumulation and `set_is_last_backward(False)`, FSDP2 keeps > `post_forward_order` across backwards: only the last backward's > `_end_backward_iteration` clears it. Each forward appends after the previous > forward's entries, so in every microbatch after the first, the first group's > implicit backward prefetch targets the previous forward's last group. That is > a no-op while the target is unsharded. But when only the last backward > reshards (`set_reshard_after_backward(True)` on the last microbatch, as > torchtitan does with deferred gradient reduction), the last group reshards > after its own backward, and the first group's backward all-gathers it again > for nothing. In torchtitan, with DeepSeek V3 layers and 16 accumulated > microbatches, that is one extra 1.77 GB all-gather of the output projection > per step. > > The root's post-backward final callback now clears `post_forward_order` once > no group holds a post-forward index, that is, once every recorded forward has > run its backward. Under pipeline schedules, groups of microbatches whose > backward hasn't run yet still hold indices, so the order is kept for them, as > before. Clearing after every backward instead would drop their entries. > > Only the implicit backward prefetch popped a group's index, so a group with > explicit backward prefetch (`set_modules_to_backward_prefetch`) kept its > indices and the clear never ran. torchtitan sets explicit backward prefetch on > the transformer blocks and the output projection, leaving only the first > module implicit. `pre_backward` now pops the index under explicit prefetch > too. > > Test Plan > > ``` > python test/distributed/_composable/fsdp/test_fully_shard_comm.py -k TestFullyShardPrefetch > ``` > > `test_backward_prefetch_with_gradient_accumulation` runs with and without > explicit backward prefetch on the later modules: no backward may unshard a > module that the last microbatch's backward resharded. The implicit variant > fails without the clear, and the explicit variant fails without the pop in > `pre_backward`. The prefetch tests ran with this change on 4 H100s, on a build > of 90ef23c plus #200179. All pass except > `test_unused_backward_prefetch_with_post_forward_mesh`, which needs #199729 > and fails the same way on that build without this change. > > In torchtitan, on that build with this change, a half-scale run (8 H100s, 16 > accumulated microbatches, deferred reduction, 10 steps) has 10 all-gathers per > step instead of 11, and no backward prefetch targets a sharded group. Loss and > grad norm are bitwise equal to a run without the change, and step time and > peak reserved memory are unchanged. A pipeline-parallel run (2 ranks x 8 > virtual stages, Interleaved1F1B, 16 microbatches) is bitwise equal as well. ghstack-source-id: 5cdf9a8 Pull-Request: #200476
This PR was authored with an AI assistant (Claude Code). The description below is AI-generated and is pending author review. > With gradient accumulation and `set_is_last_backward(False)`, FSDP2 keeps > `post_forward_order` across backwards: only the last backward's > `_end_backward_iteration` clears it. Each forward appends after the previous > forward's entries, so in every microbatch after the first, the first group's > implicit backward prefetch targets the previous forward's last group. That is > a no-op while the target is unsharded. But when only the last backward > reshards (`set_reshard_after_backward(True)` on the last microbatch, as > torchtitan does with deferred gradient reduction), the last group reshards > after its own backward, and the first group's backward all-gathers it again > for nothing. In torchtitan, with DeepSeek V3 layers and 16 accumulated > microbatches, that is one extra 1.77 GB all-gather of the output projection > per step. > > The root's post-backward final callback now clears `post_forward_order` once > no group holds a post-forward index, that is, once every recorded forward has > run its backward. Under pipeline schedules, groups of microbatches whose > backward hasn't run yet still hold indices, so the order is kept for them, as > before. Clearing after every backward instead would drop their entries. > > Only the implicit backward prefetch popped a group's index, so a group with > explicit backward prefetch (`set_modules_to_backward_prefetch`) kept its > indices and the clear never ran. torchtitan sets explicit backward prefetch on > the transformer blocks and the output projection, leaving only the first > module implicit. `pre_backward` now pops the index under explicit prefetch > too. > > Test Plan > > ``` > python test/distributed/_composable/fsdp/test_fully_shard_comm.py -k TestFullyShardPrefetch > ``` > > `test_backward_prefetch_with_gradient_accumulation` runs with and without > explicit backward prefetch on the later modules: no backward may unshard a > module that the last microbatch's backward resharded. The implicit variant > fails without the clear, and the explicit variant fails without the pop in > `pre_backward`. The prefetch tests ran with this change on 4 H100s, on a build > of 90ef23c plus #200179. All pass except > `test_unused_backward_prefetch_with_post_forward_mesh`, which needs #199729 > and fails the same way on that build without this change. > > In torchtitan, on that build with this change, a half-scale run (8 H100s, 16 > accumulated microbatches, deferred reduction, 10 steps) has 10 all-gathers per > step instead of 11, and no backward prefetch targets a sharded group. Loss and > grad norm are bitwise equal to a run without the change, and step time and > peak reserved memory are unchanged. A pipeline-parallel run (2 ranks x 8 > virtual stages, Interleaved1F1B, 16 microbatches) is bitwise equal as well. ghstack-source-id: 46cd0a9 Pull-Request: #200476
This PR was authored with an AI assistant (Claude Code). The description below is AI-generated and is pending author review. > With gradient accumulation and `set_is_last_backward(False)`, FSDP2 keeps > `post_forward_order` across backwards: only the last backward's > `_end_backward_iteration` clears it. Each forward appends after the previous > forward's entries, so in every microbatch after the first, the first group's > implicit backward prefetch targets the previous forward's last group. That is > a no-op while the target is unsharded. But when only the last backward > reshards (`set_reshard_after_backward(True)` on the last microbatch, as > torchtitan does with deferred gradient reduction), the last group reshards > after its own backward, and the first group's backward all-gathers it again > for nothing. In torchtitan, with DeepSeek V3 layers and 16 accumulated > microbatches, that is one extra 1.77 GB all-gather of the output projection > per step. > > The root's post-backward final callback now clears `post_forward_order` once > no group holds a post-forward index, that is, once every recorded forward has > run its backward. Under pipeline schedules, groups of microbatches whose > backward hasn't run yet still hold indices, so the order is kept for them, as > before. Clearing after every backward instead would drop their entries. > > Only the implicit backward prefetch popped a group's index, so a group with > explicit backward prefetch (`set_modules_to_backward_prefetch`) kept its > indices and the clear never ran. torchtitan sets explicit backward prefetch on > the transformer blocks and the output projection, leaving only the first > module implicit. `pre_backward` now pops the index under explicit prefetch > too. > > Test Plan > > ``` > python test/distributed/_composable/fsdp/test_fully_shard_comm.py -k TestFullyShardPrefetch > ``` > > `test_backward_prefetch_with_gradient_accumulation` runs with and without > explicit backward prefetch on the later modules: no backward may unshard a > module that the last microbatch's backward resharded. The implicit variant > fails without the clear, and the explicit variant fails without the pop in > `pre_backward`. The prefetch tests ran with this change on 4 H100s, on a build > of 90ef23c plus #200179. All pass except > `test_unused_backward_prefetch_with_post_forward_mesh`, which needs #199729 > and fails the same way on that build without this change. > > In torchtitan, on that build with this change, a half-scale run (8 H100s, 16 > accumulated microbatches, deferred reduction, 10 steps) has 10 all-gathers per > step instead of 11, and no backward prefetch targets a sharded group. Loss and > grad norm are bitwise equal to a run without the change, and step time and > peak reserved memory are unchanged. A pipeline-parallel run (2 ranks x 8 > virtual stages, Interleaved1F1B, 16 microbatches) is bitwise equal as well. ghstack-source-id: ba282f2 Pull-Request: #200476
Stack from ghstack (oldest at bottom):
This PR was authored with an AI assistant (Claude Code). The description below is AI-generated and is pending author review.