Skip to content

[FSDP2] Vectorize the cast path of the fused chunk_cat kernel - #204752

Closed
fegin wants to merge 6 commits into
gh/fegin/377/basefrom
gh/fegin/377/head
Closed

fegin wants to merge 6 commits into
gh/fegin/377/basefrom
gh/fegin/377/head

Conversation

@fegin

@fegin fegin commented Nov 13, 2026 •

Copy link
Copy Markdown
Contributor

Stack from ghstack (oldest at bottom):

Summary (human-written)

The cast path of the fused FSDP2 chunk_cat kernel (fsdp::chunk_cat_mixed_dtype) reads only 2 bytes at a time. This PR vectorizes the cast path to speed up the FSDP2 copy-in for gradient groups with mixed dtypes. ATen _chunk_cat is not changed.

Agent Summary

fsdp::chunk_cat_mixed_dtype copies a reduce-scatter group with mixed gradient dtypes in one fused kernel: one launch copies the fp32 gradients and one launch casts the bf16 or fp16 gradients into the fp32 reduce-scatter input. The cast launch converted one element per thread per iteration with 2-byte loads and 4-byte stores, and the grid was sized for 16 output bytes per thread. It reached 1.7 TB/s on H100.

The cast branch of copy_chunk_with_pad in torch/csrc/distributed/fsdp/ChunkCat.cu now uses the same head / aligned body / tail split as the copy path. The head makes dst 16-byte aligned. Each body iteration (unit) loads 8 source elements with the widest load the source alignment allows (16, 8, 4, or 2 bytes, through the read-only cache), converts them with the same c10 cast as before, and writes two 16-byte stores. Padding past the source is written as zeros in the same stores. cast_bytes_per_block sizes the cast grid: each thread takes one unit up to three waves of resident threads, two up to six waves, and so on, up to four. On one GB200, with 8 chunks of 16 or 128 bf16 inputs into fp32 (1 MB to 4 GB of output), a fixed one unit per thread is 11-17% slower than this at 64 MB and 46-53% slower from 1 GB up, and a fixed four units per thread is up to 17% slower at 16 MB. The heuristic is within 3.5% of the best fixed choice at every size.

Only the FSDP kernel changes. Uniform groups go through _chunk_cat, whose ATen kernel has the same cast loop; changing it is left to a separate PR.

The output is bitwise identical, including padding, all source and destination alignments, odd sizes, and both bf16 and fp16. The tests compare against _chunk_cat of the inputs cast to fp32 first, which runs the same-dtype copy kernel. test_numerics_cast_alignments covers all four load widths, every head length of the padded chunk, padded units and tails, an all-padding chunk, and chunks that span several blocks. test_numerics_cast_several_units_per_thread covers an input large enough for four units per thread on GPUs with up to 304 SMs.

Kernel time from the profiler, FSDP2 copy-in, bf16 into fp32, old -> new:

H100 GB300 GB200
285M elements, 64 chunks 0.955 -> 0.841 ms (1.14x) 0.709 -> 0.266 ms (2.66x) 0.721 -> 0.260 ms (2.77x)
201M elements, 1 chunk 0.710 -> 0.585 ms (1.21x) 0.544 -> 0.180 ms (3.02x) 0.552 -> 0.181 ms (3.05x)

The GB300 numbers come from a standalone build of the old and new kernels.

Test Plan:

python -m pytest test/distributed/_composable/fsdp/test_fully_shard_comm.py -k "ChunkCatMixedDtype or NativeCollectiveCopy or PythonCustomOp"
python -m pytest test/distributed/_composable/fsdp/test_fully_shard_comm.py test/distributed/_composable/fsdp/test_fully_shard_mixed_precision.py

On 2 GB200 GPUs, the first command passes 15 of 15 and the second passes 136 of 137. The one failure, test_fully_shard_alloc_from_pg, expects NCCL to register no buffer before allocation from the process group is enabled, but NCCL 2.30.7 registers a 2 MB buffer. This change does not touch that path.

This change was written with an AI assistant (Claude).

[ghstack-poisoned]
@pytorch-bot pytorch-bot Bot added the release notes: distributed (fsdp) release notes category label Nov 13, 2026
@pytorch-bot

pytorch-bot Bot commented Nov 13, 2026 •

Copy link
Copy Markdown

PR Status: Approved 🚀

Please fix all CI failures and trigger merge by commenting "@pytorchbot merge".

✅ AUTOMATED REVIEW - OUTDATED (earlier commit) - Ready for human review:

The PR speeds up the bf16/fp16  fp32 cast in the fused
fsdp::chunk_cat_mixed_dtype kernel by splitting each chunk into an alignment
head, a vectorized 8-element-unit body and a tail, and by sizing the cast grid
from the GPU's resident-thread count. Recommendation: Approve. Only non-blocking
points remain, and adding ciflow/trunk before merge is strongly suggested.

Findings (3):

[minor] test/distributed/_composable/fsdp/test_fully_shard_comm.py:605
The new tests have not run on any CI GPU (non-blocking). The PR has no
`ciflow/*` label, and no pull.yml job runs these tests on a GPU: the
`distributed` config (pull.yml:103-110) runs only on CPU, so both `@​ onlyCUDA`
tests are skipped, and the CUDA 13.2, ROCm and XPU jobs only build. So far the
kernel has run only on the author's GB200s. `TestFullyShardChunkCatMixedDtype`
is a plain `TestCase`, so on GPU builds it runs through
`test_distributed_single_gpu` in the `default` shards. Adding `ciflow/trunk`
would run the tests on L4 (CUDA) and gfx950/MI350 (ROCm) before merge, which is
also the cheapest direct answer to the maintainer's hardware question.

[minor] torch/csrc/distributed/fsdp/ChunkCat.cu:205
The grid heuristic has not been measured against the old kernel at small sizes
or on A100/AMD (non-blocking). The cast launch always writes fp32, so the
smallest cast block now covers 128  1  8  4 = 4096 output bytes, against the old
`BYTES_PER_BLOCK` of 2048. Each chunk now gets ceil(chunk/4096) blocks instead
of ceil(chunk/2048); e.g. 8 chunks of 64 KB go from 256 blocks to 128, below
H100's 132 SMs. This is not necessarily a regression, since each thread does
more vectorized work, but the heuristic comparison ran only on one GB200 from 1
MB up, and the old-vs-new table covers only large inputs on H100, GB300 and
GB200. No small-size numbers and no A100 or MI-series numbers; on ROCm `doLdg`
is a plain load. A small (16 MB) and a large old-vs-new comparison on A100 or
H100 and on one MI-series GPU would settle this; a note next to the constants
would also do.

[minor] torch/csrc/distributed/fsdp/ChunkCat.cu:275
Stale header comment (non-blocking), ChunkCat.cu:20-22. It still says the device
code is "copied verbatim" from aten/src/ATen/native/cuda/TensorShape.cu apart
from namespace qualification. That is no longer true: the cast branch of
`copy_chunk_with_pad` (here, 275-313) has been rewritten, while
TensorShape.cu:302-315 still has the scalar `while` loops, and `CAST_VEC`,
`CAST_MAX_UNITS_PER_THREAD`, `cast_bytes_per_block` and `cast_units_with_pad`
have no ATen counterpart. Someone re-syncing this file from ATen could silently
undo the vectorization. Please say which parts are still verbatim and which now
differ.

Reviewed commit: 85f5a3b (NOT the current head d9278e2)

Review run

🐛 Report a bad review

🔗 Helpful Links

🧪 See artifacts and rendered test results at hud.pytorch.org/pr/204752

Note: Links to docs will display an error until the docs builds have been completed.

✅ No Failures

As of commit d9278e2 with merge base f81a081 (image):
💚 Looks good so far! There are no failures yet. 💚

🟡 GREEN LIGHT - OUTDATED (earlier commit) - PR requires human review:

  • Triviality
    • Rewrites the cast branch of copy_chunk_with_pad in torch/csrc/distributed/fsdp/ChunkCat.cu as a vectorized head/units/tail kernel with four load widths
    • Adds cast_bytes_per_block, a device-property grid-sizing heuristic that changes the cast launch's block count in fused_chunk_cat
    • A performance rewrite of a CUDA kernel fits no trivial class: not a small behavior-neutral tweak, a bugfix, or a test-only change
  • Correctness review
    • Read the alignment split: head aligns dst to 16 bytes, unit loads stay load_t-aligned, and reads past actual_num_elems are guarded and zero-padded
    • No defect found; new tests in test_fully_shard_comm.py compare bitwise against torch._chunk_cat across alignments, widths, and chunk counts
  • Scope
    • Only the FSDP cast path and its tests change; the same-dtype copy path and ATen _chunk_cat are untouched

reason: not_trivial
Reviewed commit: f1beb9a (NOT the current head d9278e2)

Inference job

🐛 Report a wrong verdict

This comment was automatically generated by Dr. CI and updates every 15 minutes.

[ghstack-poisoned]
fegin added a commit that referenced this pull request Nov 13, 2026
fsdp::chunk_cat_mixed_dtype copies a reduce-scatter group with mixed gradient dtypes in one fused kernel: one launch copies the fp32 gradients and one launch casts the bf16 or fp16 gradients into the fp32 reduce-scatter input. The cast launch converted one element per thread per iteration with 2-byte loads and 4-byte stores, and the grid was sized for 16 output bytes per thread. It reached 1.7 TB/s on H100.

The cast branch of copy_chunk_with_pad in torch/csrc/distributed/fsdp/ChunkCat.cu now uses the same head / aligned body / tail split as the copy path. The head makes dst 16-byte aligned. Each body iteration (unit) loads 8 source elements with the widest load the source alignment allows (16, 8, 4, or 2 bytes, through the read-only cache), converts them with the same c10 cast as before, and writes two 16-byte stores. Padding past the source is written as zeros in the same stores. cast_bytes_per_block sizes the cast grid: each thread takes one unit up to three waves of resident threads, two up to six waves, and so on, up to four. On one GB200, with 8 chunks of 16 or 128 bf16 inputs into fp32 (1 MB to 4 GB of output), a fixed one unit per thread is 11-17% slower than this at 64 MB and 46-53% slower from 1 GB up, and a fixed four units per thread is up to 17% slower at 16 MB. The heuristic is within 3.5% of the best fixed choice at every size.

Only the FSDP kernel changes. Uniform groups go through _chunk_cat, whose ATen kernel has the same cast loop; changing it is left to a separate PR.

The output is bitwise identical, including padding, all source and destination alignments, odd sizes, and both bf16 and fp16. The tests compare against _chunk_cat of the inputs cast to fp32 first, which runs the same-dtype copy kernel. test_numerics_cast_alignments covers all four load widths, every head length of the padded chunk, padded units and tails, an all-padding chunk, and chunks that span several blocks. test_numerics_cast_several_units_per_thread covers an input large enough for four units per thread on GPUs with up to 304 SMs.

Kernel time from the profiler, FSDP2 copy-in, bf16 into fp32, old -> new:

| | H100 | GB300 | GB200 |
|---|---|---|---|
| 285M elements, 64 chunks | 0.955 -> 0.841 ms (1.14x) | 0.709 -> 0.266 ms (2.66x) | 0.721 -> 0.260 ms (2.77x) |
| 201M elements, 1 chunk | 0.710 -> 0.585 ms (1.21x) | 0.544 -> 0.180 ms (3.02x) | 0.552 -> 0.181 ms (3.05x) |

The GB300 numbers come from a standalone build of the old and new kernels.

Test Plan:

```
python -m pytest test/distributed/_composable/fsdp/test_fully_shard_comm.py -k "ChunkCatMixedDtype or NativeCollectiveCopy or PythonCustomOp"
python -m pytest test/distributed/_composable/fsdp/test_fully_shard_comm.py test/distributed/_composable/fsdp/test_fully_shard_mixed_precision.py
```

On 2 GB200 GPUs, the first command passes 15 of 15 and the second passes 136 of 137. The one failure, test_fully_shard_alloc_from_pg, expects NCCL to register no buffer before allocation from the process group is enabled, but NCCL 2.30.7 registers a 2 MB buffer. This change does not touch that path.

This change was written with an AI assistant (Claude).

ghstack-source-id: e0fd5cd
Pull-Request: #204752
[ghstack-poisoned]
@fegin fegin changed the title Vectorize the cast path of the chunk_cat CUDA kernel [FSDP2] Vectorize the cast path of the chunk_cat CUDA kernel Nov 13, 2026
@fegin
fegin marked this pull request as ready for review November 13, 2026 19:15
@fegin
fegin requested a review from weifengpy as a code owner November 13, 2026 19:15
@pytorchbot pytorchbot added the in progress PR is being worked on by the author, until the automated review accepts it label Nov 13, 2026
@fegin fegin changed the title [FSDP2] Vectorize the cast path of the chunk_cat CUDA kernel [FSDP2] Vectorize the cast path of the fused chunk_cat kernel Nov 13, 2026
@fegin

fegin commented Nov 13, 2026

Copy link
Copy Markdown
Contributor Author

@claude review this PR

@claude

claude Bot commented Nov 13, 2026 •

Copy link
Copy Markdown

Claude encountered an error after 7s —— View job


I'll analyze this and get back to you.

@fegin

fegin commented Nov 13, 2026

Copy link
Copy Markdown
Contributor Author

@claude review this PR

@claude

claude Bot commented Nov 13, 2026 •

Copy link
Copy Markdown

Claude encountered an error after 20s —— View job


I'll analyze this and get back to you.

@pytorchgreenlight pytorchgreenlight Bot added the GL/human GreenLight marked as needing human review label Nov 13, 2026
@weifengpy

Copy link
Copy Markdown
Contributor

@claude consdier A100, H100 and blackwell, amd/hip/rocm. whether this PR is risky and could break existing callsites

@claude

claude Bot commented Nov 14, 2026 •

Copy link
Copy Markdown

Claude finished @weifengpy's task in 1m 37s —— View job


I'd rate this PR low risk on A100, H100, Blackwell and ROCm. It adds no inline PTX or arch-specific code, the output is meant to be bitwise identical, and the only callsite is FSDP2's reduce-scatter copy-in for groups that mix bf16/fp16 with fp32. The one real gap is CI coverage: ROCm, A100 and Blackwell haven't run this kernel on this PR.

Details

What can reach the new code

  • torch.ops.fsdp.chunk_cat_mixed_dtype has two callers: foreach_reduce_scatter_copy_in (_fsdp_collectives.py:1006) and fsdp/experimental/__init__.py:120.
  • Only the cast launch (bf16/fp16 → fp32, dim == 0, contiguous, non-overlapping inputs) changes. ChunkCat.cu:275 is now if constexpr, so the same-dtype <char, char> copy path compiles to the same code as before.
  • Uniform-dtype groups, ATen _chunk_cat, _all_gather_copy_out_, the CPU/XPU paths and the composite fallback are unchanged.

Per-platform analysis

Platform Concern Assessment
A100 (sm80) __ldg of uint4/uint2/uint32_t/uint16_t via doLdg All four overloads exist on sm35+. There is no new inline asm; the existing ld.global.nc/st.global.cs asm is only on the copy path, which is unchanged. 108 SMs × 2048 threads goes into the grid heuristic, which only affects speed. A100 numbers are not in the PR.
H100 (sm90) — Measured in the PR description (1.14–1.21x).
Blackwell (sm100/103) — Plain C++ loads and stores only, nothing arch-gated. GB200 and GB300 numbers are in the description.
ROCm (MI200/MI300) doLdg falls back to *p (DeviceUtils.cuh:115-121). uint2/uint4 are HIP vector types. maxThreadsPerMultiProcessor is reported by HIP. Correctness should be fine. Performance is unmeasured. The reinterpret_cast<load_t*>(vals) punning on local alignas(16) arrays relies on SROA/unrolling to keep vals/out in registers. If hipcc spills them to scratch, it would be a speed regression, not a correctness bug. The comment on test_numerics_cast_several_units_per_thread covers MI300X's 304 CUs (50M elements → 4 units per thread).

Correctness checks I traced (no bugs found)

  • dst alignment: out is fp32 and every chunk offset is a multiple of 4 bytes, so dst_misalign ∈ {0,4,8,12} and head ≤ 3. After the head, dst + i is always 16-byte aligned, because i is a multiple of 8 floats (32 bytes). If max_num_elems < head, then head is clamped, num_units = 0 and tail = max, so nothing is written past the chunk.
  • src alignment: each unit advances by 16 source bytes, so the load_t picked once from src holds for every unit.
  • Head and tail cover everything: head ≤ 3 and the tail has fewer than 8 elements, both smaller than num_threads (at least 128). So the single, non-looping elem(...) calls are enough.
  • Padding: actual can be negative, or end partway through a unit. In both cases the scalar fallback reads only i + j < actual and fills zeros. dst_t(0) gives the same +0.0f bits as the old static_cast_with_inter_type<float,int>(0).
  • Read-only (.nc) loads: these are safe only if no input aliases out or another input during the kernel. use_composite (ChunkCat.cu:565-587) already rejects any overlap among inputs and between inputs and out.
  • Grid: there are at least 1× and at most 4× 32 output bytes per thread. The kernel uses a grid-stride loop, so a smaller grid only affects speed. gridDim.y = num_chunks is unchanged.
  • Host overhead: getCurrentDeviceProperties() is cached and runs once per call. There is one extra pass over tensors on the host, which is negligible.

Gaps and suggestions

  1. CI coverage. Only pull, Lint, BC Lint and docs-build ran. Before landing, I'd add the trunk/periodic and ROCm ciflow labels so test_fully_shard_comm.py runs on sm80 and MI300. The new tests are @onlyCUDA, which still runs on ROCm because the device type is cuda, and there is no skipIfRocm.
  2. ROCm performance. A quick before/after on MI300 would confirm there's no scratch spill. This isn't a blocker for correctness.
  3. Memory needs of the new test. test_numerics_cast_several_units_per_thread uses about 0.7 GB in total (inputs, the .float() copies, expected, out). @largeTensorTest("1GB") covers that.

Bottom line: I found no correctness bug or API change. The remaining risk is performance on ROCm and coverage of A100/ROCm that hasn't been run, and running the ciflow jobs would close that.

[ghstack-poisoned]
fegin added a commit that referenced this pull request Nov 14, 2026
fsdp::chunk_cat_mixed_dtype copies a reduce-scatter group with mixed gradient dtypes in one fused kernel: one launch copies the fp32 gradients and one launch casts the bf16 or fp16 gradients into the fp32 reduce-scatter input. The cast launch converted one element per thread per iteration with 2-byte loads and 4-byte stores, and the grid was sized for 16 output bytes per thread. It reached 1.7 TB/s on H100.

The cast branch of copy_chunk_with_pad in torch/csrc/distributed/fsdp/ChunkCat.cu now uses the same head / aligned body / tail split as the copy path. The head makes dst 16-byte aligned. Each body iteration (unit) loads 8 source elements with the widest load the source alignment allows (16, 8, 4, or 2 bytes, through the read-only cache), converts them with the same c10 cast as before, and writes two 16-byte stores. Padding past the source is written as zeros in the same stores. cast_bytes_per_block sizes the cast grid: each thread takes one unit up to three waves of resident threads, two up to six waves, and so on, up to four. On one GB200, with 8 chunks of 16 or 128 bf16 inputs into fp32 (1 MB to 4 GB of output), a fixed one unit per thread is 11-17% slower than this at 64 MB and 46-53% slower from 1 GB up, and a fixed four units per thread is up to 17% slower at 16 MB. The heuristic is within 3.5% of the best fixed choice at every size.

Only the FSDP kernel changes. Uniform groups go through _chunk_cat, whose ATen kernel has the same cast loop; changing it is left to a separate PR.

The output is bitwise identical, including padding, all source and destination alignments, odd sizes, and both bf16 and fp16. The tests compare against _chunk_cat of the inputs cast to fp32 first, which runs the same-dtype copy kernel. test_numerics_cast_alignments covers all four load widths, every head length of the padded chunk, padded units and tails, an all-padding chunk, and chunks that span several blocks. test_numerics_cast_several_units_per_thread covers an input large enough for four units per thread on GPUs with up to 304 SMs.

Kernel time from the profiler, FSDP2 copy-in, bf16 into fp32, old -> new:

| | H100 | GB300 | GB200 |
|---|---|---|---|
| 285M elements, 64 chunks | 0.955 -> 0.841 ms (1.14x) | 0.709 -> 0.266 ms (2.66x) | 0.721 -> 0.260 ms (2.77x) |
| 201M elements, 1 chunk | 0.710 -> 0.585 ms (1.21x) | 0.544 -> 0.180 ms (3.02x) | 0.552 -> 0.181 ms (3.05x) |

The GB300 numbers come from a standalone build of the old and new kernels.

Test Plan:

```
python -m pytest test/distributed/_composable/fsdp/test_fully_shard_comm.py -k "ChunkCatMixedDtype or NativeCollectiveCopy or PythonCustomOp"
python -m pytest test/distributed/_composable/fsdp/test_fully_shard_comm.py test/distributed/_composable/fsdp/test_fully_shard_mixed_precision.py
```

On 2 GB200 GPUs, the first command passes 15 of 15 and the second passes 136 of 137. The one failure, test_fully_shard_alloc_from_pg, expects NCCL to register no buffer before allocation from the process group is enabled, but NCCL 2.30.7 registers a 2 MB buffer. This change does not touch that path.

This change was written with an AI assistant (Claude).

ghstack-source-id: 74ef3c6
Pull-Request: #204752
@pytorchgreenlight pytorchgreenlight Bot added GL/superseded GreenLight review is superseded by changes and removed GL/human GreenLight marked as needing human review labels Nov 14, 2026
github-actions[bot]

This comment was marked as outdated.

@fegin

fegin commented Nov 14, 2026

Copy link
Copy Markdown
Contributor Author

@claude review this PR

@claude

claude Bot commented Nov 14, 2026 •

Copy link
Copy Markdown

Claude finished @fegin's task in 1m 15s —— View job


I found no blocking issues in the vectorized cast path and recommend Approve. One stale comment needs fixing, but that is non-blocking.

Details

PR Review: #204752

Summary

The PR vectorizes the bf16/fp16 → fp32 cast branch of fsdp::chunk_cat_mixed_dtype. It splits each chunk into an unaligned head, aligned 8-element units, and a tail, and sizes the cast grid from the device's resident thread count. No REVIEW.md applies.

I traced these and found no correctness defect:

  • The head/units/tail split for every dst misalignment (head ≤ 3 because dst is float*).
  • The load_t alignment, which holds across units: each unit advances 16 bytes of source.
  • Padding when actual is negative or ends partway through a unit.
  • The single non-looping head and tail writes: both are under 8 elements, and num_threads is at least 128.
  • The __ldg read-only loads, which are safe because use_composite already rejects overlapping inputs and out.

This is the same commit (b3be9b3) as the previous automated review, and its points still apply.

Code Quality

  • Stale header comment, non-blocking (ChunkCat.cu:20-22). The comment still says the device code is "copied verbatim from aten/src/ATen/native/cuda/TensorShape.cu". The cast branch of copy_chunk_with_pad now differs from ATen, and cast_units_with_pad and cast_bytes_per_block have no ATen counterpart. Someone re-syncing from ATen could silently undo this PR. Suggested fix: say that the cast path is FSDP-specific.

Performance

  • Host work on copy-only groups, non-blocking (ChunkCat.cu:494). cast_bytes_per_block runs, and calls getCurrentDeviceProperties(), even when cast_chunk_bytes == 0, for example on a leading-dims-only group with no cast. The cost is negligible, but guarding it with cast_chunk_bytes > 0 would make clear that it only affects the cast launch.
  • Grid heuristic tuned on NVIDIA only, non-blocking (ChunkCat.cu:205-215). As the previous review noted, the smallest cast block now covers 4096 output bytes instead of 2048, and the heuristic was tuned only on GB200. A quick old-vs-new run on an MI-series GPU would confirm there is no regression on ROCm, where doLdg is a plain load. Running ciflow/trunk before merge would also execute the new @onlyCUDA tests on L4 and MI350.

Recommendation

Approve. Everything above is non-blocking.

[ghstack-poisoned]
fegin added a commit that referenced this pull request Nov 14, 2026
fsdp::chunk_cat_mixed_dtype copies a reduce-scatter group with mixed gradient dtypes in one fused kernel: one launch copies the fp32 gradients and one launch casts the bf16 or fp16 gradients into the fp32 reduce-scatter input. The cast launch converted one element per thread per iteration with 2-byte loads and 4-byte stores, and the grid was sized for 16 output bytes per thread. It reached 1.7 TB/s on H100.

The cast branch of copy_chunk_with_pad in torch/csrc/distributed/fsdp/ChunkCat.cu now uses the same head / aligned body / tail split as the copy path. The head makes dst 16-byte aligned. Each body iteration (unit) loads 8 source elements with the widest load the source alignment allows (16, 8, 4, or 2 bytes, through the read-only cache), converts them with the same c10 cast as before, and writes two 16-byte stores. Padding past the source is written as zeros in the same stores. cast_bytes_per_block sizes the cast grid: each thread takes one unit up to three waves of resident threads, two up to six waves, and so on, up to four. On one GB200, with 8 chunks of 16 or 128 bf16 inputs into fp32 (1 MB to 4 GB of output), a fixed one unit per thread is 11-17% slower than this at 64 MB and 46-53% slower from 1 GB up, and a fixed four units per thread is up to 17% slower at 16 MB. The heuristic is within 3.5% of the best fixed choice at every size.

Only the FSDP kernel changes. Uniform groups go through _chunk_cat, whose ATen kernel has the same cast loop; changing it is left to a separate PR.

The output is bitwise identical, including padding, all source and destination alignments, odd sizes, and both bf16 and fp16. The tests compare against _chunk_cat of the inputs cast to fp32 first, which runs the same-dtype copy kernel. test_numerics_cast_alignments covers all four load widths, every head length of the padded chunk, padded units and tails, an all-padding chunk, and chunks that span several blocks. test_numerics_cast_several_units_per_thread covers an input large enough for four units per thread on GPUs with up to 304 SMs.

Kernel time from the profiler, FSDP2 copy-in, bf16 into fp32, old -> new:

| | H100 | GB300 | GB200 |
|---|---|---|---|
| 285M elements, 64 chunks | 0.955 -> 0.841 ms (1.14x) | 0.709 -> 0.266 ms (2.66x) | 0.721 -> 0.260 ms (2.77x) |
| 201M elements, 1 chunk | 0.710 -> 0.585 ms (1.21x) | 0.544 -> 0.180 ms (3.02x) | 0.552 -> 0.181 ms (3.05x) |

The GB300 numbers come from a standalone build of the old and new kernels.

Test Plan:

```
python -m pytest test/distributed/_composable/fsdp/test_fully_shard_comm.py -k "ChunkCatMixedDtype or NativeCollectiveCopy or PythonCustomOp"
python -m pytest test/distributed/_composable/fsdp/test_fully_shard_comm.py test/distributed/_composable/fsdp/test_fully_shard_mixed_precision.py
```

On 2 GB200 GPUs, the first command passes 15 of 15 and the second passes 136 of 137. The one failure, test_fully_shard_alloc_from_pg, expects NCCL to register no buffer before allocation from the process group is enabled, but NCCL 2.30.7 registers a 2 MB buffer. This change does not touch that path.

This change was written with an AI assistant (Claude).

ghstack-source-id: 7a20964
Pull-Request: #204752

@github-actions github-actions 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.

Automated review of 85f5a3b: nothing blocking; ready for human review.

The PR speeds up the bf16/fp16 fp32 cast in the fused fsdp::chunk_cat_mixed_dtype kernel by splitting each chunk into an alignment head, a vectorized 8-element-unit body and a tail, and by sizing the cast grid from the GPU's resident-thread count. Recommendation: Approve. Only non-blocking points remain, and adding ciflow/trunk before merge is strongly suggested.

⚪ 3 non-blocking findings

The new tests have not run on any CI GPU (non-blocking). The PR has no ciflow/* label, and no pull.yml job runs these tests on a GPU: the distributed config (pull.yml:103-110) runs only on CPU, so both @ onlyCUDA tests are skipped, and the CUDA 13.2, ROCm and XPU jobs only build. So far the kernel has run only on the author's GB200s. TestFullyShardChunkCatMixedDtype is a plain TestCase, so on GPU builds it runs through test_distributed_single_gpu in the default shards. Adding ciflow/trunk would run the tests on L4 (CUDA) and gfx950/MI350 (ROCm) before merge, which is also the cheapest direct answer to the maintainer's hardware question.


inline int64_t cast_bytes_per_block(int64_t out_bytes, int64_t out_elem_size) {

The grid heuristic has not been measured against the old kernel at small sizes or on A100/AMD (non-blocking). The cast launch always writes fp32, so the smallest cast block now covers 128 1 8 4 = 4096 output bytes, against the old BYTES_PER_BLOCK of 2048. Each chunk now gets ceil(chunk/4096) blocks instead of ceil(chunk/2048); e.g. 8 chunks of 64 KB go from 256 blocks to 128, below H100's 132 SMs. This is not necessarily a regression, since each thread does more vectorized work, but the heuristic comparison ran only on one GB200 from 1 MB up, and the old-vs-new table covers only large inputs on H100, GB300 and GB200. No small-size numbers and no A100 or MI-series numbers; on ROCm doLdg is a plain load. A small (16 MB) and a large old-vs-new comparison on A100 or H100 and on one MI-series GPU would settle this; a note next to the constants would also do.


if constexpr (!std::is_same_v<dst_t, src_t>) {

Stale header comment (non-blocking), ChunkCat.cu:20-22. It still says the device code is "copied verbatim" from aten/src/ATen/native/cuda/TensorShape.cu apart from namespace qualification. That is no longer true: the cast branch of copy_chunk_with_pad (here, 275-313) has been rewritten, while TensorShape.cu:302-315 still has the scalar while loops, and CAST_VEC, CAST_MAX_UNITS_PER_THREAD, cast_bytes_per_block and cast_units_with_pad have no ATen counterpart. Someone re-syncing this file from ATen could silently undo the vectorization. Please say which parts are still verbatim and which now differ.

This review is AI-generated and advisory. Each new automated review replaces the previous one. Report a bad review

@pytorch-bot pytorch-bot Bot added ready for review Automated review passed, ready for a final review by a maintainer. and removed in progress PR is being worked on by the author, until the automated review accepts it labels Nov 14, 2026
[ghstack-poisoned]
fegin added a commit that referenced this pull request Nov 16, 2026
fsdp::chunk_cat_mixed_dtype copies a reduce-scatter group with mixed gradient dtypes in one fused kernel: one launch copies the fp32 gradients and one launch casts the bf16 or fp16 gradients into the fp32 reduce-scatter input. The cast launch converted one element per thread per iteration with 2-byte loads and 4-byte stores, and the grid was sized for 16 output bytes per thread. It reached 1.7 TB/s on H100.

The cast branch of copy_chunk_with_pad in torch/csrc/distributed/fsdp/ChunkCat.cu now uses the same head / aligned body / tail split as the copy path. The head makes dst 16-byte aligned. Each body iteration (unit) loads 8 source elements with the widest load the source alignment allows (16, 8, 4, or 2 bytes, through the read-only cache), converts them with the same c10 cast as before, and writes two 16-byte stores. Padding past the source is written as zeros in the same stores. cast_bytes_per_block sizes the cast grid: each thread takes one unit up to three waves of resident threads, two up to six waves, and so on, up to four. On one GB200, with 8 chunks of 16 or 128 bf16 inputs into fp32 (1 MB to 4 GB of output), a fixed one unit per thread is 11-17% slower than this at 64 MB and 46-53% slower from 1 GB up, and a fixed four units per thread is up to 17% slower at 16 MB. The heuristic is within 3.5% of the best fixed choice at every size.

Only the FSDP kernel changes. Uniform groups go through _chunk_cat, whose ATen kernel has the same cast loop; changing it is left to a separate PR.

The output is bitwise identical, including padding, all source and destination alignments, odd sizes, and both bf16 and fp16. The tests compare against _chunk_cat of the inputs cast to fp32 first, which runs the same-dtype copy kernel. test_numerics_cast_alignments covers all four load widths, every head length of the padded chunk, padded units and tails, an all-padding chunk, and chunks that span several blocks. test_numerics_cast_several_units_per_thread covers an input large enough for four units per thread on GPUs with up to 304 SMs.

Kernel time from the profiler, FSDP2 copy-in, bf16 into fp32, old -> new:

| | H100 | GB300 | GB200 |
|---|---|---|---|
| 285M elements, 64 chunks | 0.955 -> 0.841 ms (1.14x) | 0.709 -> 0.266 ms (2.66x) | 0.721 -> 0.260 ms (2.77x) |
| 201M elements, 1 chunk | 0.710 -> 0.585 ms (1.21x) | 0.544 -> 0.180 ms (3.02x) | 0.552 -> 0.181 ms (3.05x) |

The GB300 numbers come from a standalone build of the old and new kernels.

Test Plan:

```
python -m pytest test/distributed/_composable/fsdp/test_fully_shard_comm.py -k "ChunkCatMixedDtype or NativeCollectiveCopy or PythonCustomOp"
python -m pytest test/distributed/_composable/fsdp/test_fully_shard_comm.py test/distributed/_composable/fsdp/test_fully_shard_mixed_precision.py
```

On 2 GB200 GPUs, the first command passes 15 of 15 and the second passes 136 of 137. The one failure, test_fully_shard_alloc_from_pg, expects NCCL to register no buffer before allocation from the process group is enabled, but NCCL 2.30.7 registers a 2 MB buffer. This change does not touch that path.

This change was written with an AI assistant (Claude).

ghstack-source-id: 632530f
Pull-Request: #204752
@fegin

fegin commented Nov 17, 2026

Copy link
Copy Markdown
Contributor Author

@pytorchbot merge

@pytorch-bot pytorch-bot Bot added the ciflow/trunk Trigger trunk jobs on your pull request label Nov 17, 2026
@pytorchmergebot

Copy link
Copy Markdown
Collaborator

Merge started

Your 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

Advanced Debugging
Check the merge workflow status
here

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

Labels

ciflow/trunk Trigger trunk jobs on your pull request GL/superseded GreenLight review is superseded by changes Merged ready for review Automated review passed, ready for a final review by a maintainer. release notes: distributed (fsdp) release notes category

Projects

None yet

Development

Successfully merging this pull request may close these issues.

4 participants