Repository navigation
Conversation
This PR needs a
|
🔗 Helpful Links🧪 See artifacts and rendered test results at hud.pytorch.org/pr/182675
Note: Links to docs will display an error until the docs builds have been completed. ❗ 1 Active SEVsThere are 1 currently active SEVs. If your PR is affected, please view them below: ⏳ 14 Pending, 1 Unrelated FailureAs of commit 514438e with merge base af16333 ( FLAKY - The following job failed but was likely due to flakiness present on trunk:
This comment was automatically generated by Dr. CI and updates every 15 minutes. |
| int block_size = entries_per_block * threads_per_entry; | ||
|
|
||
| int buf_elems = 2 * chunk_elems; | ||
| int entry_data_bytes = buf_elems * static_cast<int>(sizeof(scalar_t)); |
There was a problem hiding this comment.
this must be aligned to 8 bytes due to the kernel just reinterpret casting smem_raw + entry_data_bytes to a 8 byte type, but IIUC, chunk_elems could be aligned to 1 (e.g. if D is odd) and buf_elems thus aligned to 2, and entry_data_bytes thus aligned to 4 if we assume smallest supported dtype is 2 bytes large.
There was a problem hiding this comment.
|
@claude I think (and so does codex) that there might be a subtle issue if the contiguous dim is sliced but still passes alignment checks can you double check the fast path checks with slicing |
|
Claude finished @drisspg's task in 12m 28s —— View job Checking fast path eligibility with slicing
There is indeed a correctness bug in the TMA kernel path with sliced tensors. The vectorized fallback path is fine. The IssueConsider the scenario: self = torch.zeros(100, 256, device='cuda')[:, 64:192] # shape [100, 128], stride [256, 1]
src = torch.randn(1000, 256, device='cuda')[:, 64:192] # shape [1000, 128], stride [256, 1]
idx = torch.randint(0, 100, (1000,), device='cuda').unsqueeze(1).expand_as(src)
self.scatter_add_(0, idx, src)The
All checks pass, but in the TMA kernel ( const scalar_t* src_entry = src_data + static_cast<int64_t>(entry_id) * D;
scalar_t* dst_entry = self_data + ind * D;Here Why the vectorized path is safeThe vectorized kernel ( scalar_t* dst_slice = reinterpret_cast<scalar_t*>(
reinterpret_cast<char*>(self_data) + ind * self_stride_bytes);
auto vec = at::native::memory::ld_vec<Alignment>(
reinterpret_cast<const char*>(src_data) + entry_id * static_cast<int32_t>(src_stride_bytes) + off);Suggested FixAdd a contiguity check only before dispatching to the TMA path in if (at::cuda::getCurrentDeviceProperties()->major >= 9 &&
self_stride_bytes == static_cast<decltype(self_stride_bytes)>(slice_size) &&
src_stride_bytes == static_cast<decltype(src_stride_bytes)>(slice_size)) {
// TMA path: requires truly contiguous rows (stride == D)
at::native::tma_scatter_add_kernel_launch<scalar_t, index_t>(...);
return;
}
// Fall through to vectorized path which handles arbitrary aligned stridesAlternatively, the TMA kernel could be modified to accept stride parameters, but restricting to contiguous cases is simpler and the vectorized path handles the non-contiguous case well. |
…ors (pytorch#175760)" (pytorch#182693) Summary: D94314062 introduced a VecSize=4 fast path in indexFuncLargeIndex that amortizes divmod and index lookup by having each thread process consecutive elements. On uniform-random workloads this gives a ~1.8-2.0x speedup. However, when the index distribution is heavy-tailed (e.g. zipf, or skewed where a few hot rows receive millions of writes), the fast path issues 4 atomicAdds back-to-back from the same warp into consecutive cache lines of the same destination row. The L2 atomic queue cannot drain between the unrolled rounds, and the resulting serialization causes a 4.7x slowdown on fp32 zipf inputs (and ~2x on bf16). Measured on a B200 with dst=[1.72M,128] and nIdx=7.77M: {F1989310065} Proposal https://fb.workplace.com/groups/482605989533128/permalink/1656067795520269/ exhibits highly skewed behavior and saw a regression with the diffs We back the current implementation out temporarily and will be following the approach of pytorch#182675 instead and address the contention problem Test Plan: CI Reviewed By: yjhao Differential Revision: D104098792
…ors (pytorch#175760)" (pytorch#182693) Summary: D94314062 introduced a VecSize=4 fast path in indexFuncLargeIndex that amortizes divmod and index lookup by having each thread process consecutive elements. On uniform-random workloads this gives a ~1.8-2.0x speedup. However, when the index distribution is heavy-tailed (e.g. zipf, or skewed where a few hot rows receive millions of writes), the fast path issues 4 atomicAdds back-to-back from the same warp into consecutive cache lines of the same destination row. The L2 atomic queue cannot drain between the unrolled rounds, and the resulting serialization causes a 4.7x slowdown on fp32 zipf inputs (and ~2x on bf16). Measured on a B200 with dst=[1.72M,128] and nIdx=7.77M: {F1989310065} Proposal https://fb.workplace.com/groups/482605989533128/permalink/1656067795520269/ exhibits highly skewed behavior and saw a regression with the diffs We back the current implementation out temporarily and will be following the approach of pytorch#182675 instead and address the contention problem Test Plan: CI Reviewed By: yjhao Differential Revision: D104098792
…ors (pytorch#175760)" (pytorch#182693) Summary: D94314062 introduced a VecSize=4 fast path in indexFuncLargeIndex that amortizes divmod and index lookup by having each thread process consecutive elements. On uniform-random workloads this gives a ~1.8-2.0x speedup. However, when the index distribution is heavy-tailed (e.g. zipf, or skewed where a few hot rows receive millions of writes), the fast path issues 4 atomicAdds back-to-back from the same warp into consecutive cache lines of the same destination row. The L2 atomic queue cannot drain between the unrolled rounds, and the resulting serialization causes a 4.7x slowdown on fp32 zipf inputs (and ~2x on bf16). Measured on a B200 with dst=[1.72M,128] and nIdx=7.77M: {F1989310065} Proposal https://fb.workplace.com/groups/482605989533128/permalink/1656067795520269/ exhibits highly skewed behavior and saw a regression with the diffs We back the current implementation out temporarily and will be following the approach of pytorch#182675 instead and address the contention problem Test Plan: CI Reviewed By: yjhao Differential Revision: D104098792
## Vectorized scatter_add with TMA bulk reduce on sm_90+ ### Summary Add a fast path for `scatter_add` on dim=0 when self, src are contiguous and index is expanded (same eligibility as the existing `vectorized_gather` fast path, with roles of self/src swapped). On sm_90+ (Hopper/Blackwell), uses `cp.reduce.async.bulk` to offload the entire accumulation to the TMA unit, avoiding the serial `atomicAdd` stall that limits both the existing `scatter_add` and `index_add` under contention. The kernel uses warp-per-slice scheduling, TMA loads (`cp.async.bulk.shared::cta.global`), double-buffered shared memory with chunking for arbitrary D, and mbarrier-based completion tracking. On pre-sm_90 NVIDIA, falls back to a vectorized scatter_add kernel using `ld_vec<16>` + per-element `atomicAdd` with warp-per-slice packing. ROCm is excluded (has its own optimized warp-level atomic coalescing on gfx942/gfx950). Also fixes a precedence bug in the existing `fast_gather_kernel_eligible` where `static_cast<size_t>(iter.strides(1)[1] == 0)` had the comparison inside the cast. ### Benchmarks (GB200, sm_100) **High contention** (D103765236 scenario: 7.77M indices, 3.89M targeting one row, 1.72M output rows): | D | scatter_add (this PR) | index_add (baseline) | speedup | |---|----------------------|---------------------|---------| | 128 f32 | 18.4 ms | 84.0 ms | 4.6x | | 128 bf16 | 17.5 ms | 83.1 ms | 4.7x | | 1024 f32 | 40.6 ms | 170.6 ms | 4.2x | | 1024 bf16 | 36.7 ms | 165.5 ms | 4.5x | **Uniform** (500K random indices, 100K output rows): | D | scatter_add (this PR) | index_add (baseline) | speedup | |---|----------------------|---------------------|---------| | 128 f32 | 136 us | 265 us | 2.0x | | 128 bf16 | 131 us | 201 us | 1.5x | | 1024 f32 | 927 us | 2068 us | 2.2x | | 1024 bf16 | 450 us | 1549 us | 3.4x | Supported types: float32, float64, float16, bfloat16. `cp.reduce.async.bulk.add` does not support float min/max, so scatter_reduce with min/max/prod is unaffected. ### Test plan - [ ] Correctness verified against reference `scatter_add` for all supported dtypes and D values - [ ] Benchmarked high contention and uniform workloads across D=128..1024, f32/bf16 - [ ] Pre-sm_90 fallback verified to compile and dispatch correctly (vectorized kernel with atomicAdd) - [ ] ROCm excluded from fast path to preserve existing warp-level atomic coalescing Authored with Claude. Pull Request resolved: pytorch#182675 Approved by: https://github.com/drisspg
…ors (pytorch#175760)" (pytorch#182693) (pytorch#182693) Summary: D94314062 introduced a VecSize=4 fast path in indexFuncLargeIndex that amortizes divmod and index lookup by having each thread process consecutive elements. On uniform-random workloads this gives a ~1.8-2.0x speedup. However, when the index distribution is heavy-tailed (e.g. zipf, or skewed where a few hot rows receive millions of writes), the fast path issues 4 atomicAdds back-to-back from the same warp into consecutive cache lines of the same destination row. The L2 atomic queue cannot drain between the unrolled rounds, and the resulting serialization causes a 4.7x slowdown on fp32 zipf inputs (and ~2x on bf16). Measured on a B200 with dst=[1.72M,128] and nIdx=7.77M: {F1989310065} Proposal https://fb.workplace.com/groups/482605989533128/permalink/1656067795520269/ exhibits highly skewed behavior and saw a regression with the diffs We back the current implementation out temporarily and will be following the approach of pytorch#182675 instead and address the contention problem Test Plan: CI Reviewed By: yjhao Differential Revision: D104098792 Pull Request resolved: pytorch#182693 Approved by: https://github.com/drisspg
…h#182675)" This reverts commit fee4fd3. Reverted pytorch#182675 on behalf of https://github.com/ngimel due to internal build failure ([comment](pytorch#182675 (comment)))
## Vectorized scatter_add with TMA bulk reduce on sm_90+ ### Summary Add a fast path for `scatter_add` on dim=0 when self, src are contiguous and index is expanded (same eligibility as the existing `vectorized_gather` fast path, with roles of self/src swapped). On sm_90+ (Hopper/Blackwell), uses `cp.reduce.async.bulk` to offload the entire accumulation to the TMA unit, avoiding the serial `atomicAdd` stall that limits both the existing `scatter_add` and `index_add` under contention. The kernel uses warp-per-slice scheduling, TMA loads (`cp.async.bulk.shared::cta.global`), double-buffered shared memory with chunking for arbitrary D, and mbarrier-based completion tracking. On pre-sm_90 NVIDIA, falls back to a vectorized scatter_add kernel using `ld_vec<16>` + per-element `atomicAdd` with warp-per-slice packing. ROCm is excluded (has its own optimized warp-level atomic coalescing on gfx942/gfx950). Also fixes a precedence bug in the existing `fast_gather_kernel_eligible` where `static_cast<size_t>(iter.strides(1)[1] == 0)` had the comparison inside the cast. ### Benchmarks (GB200, sm_100) **High contention** (D103765236 scenario: 7.77M indices, 3.89M targeting one row, 1.72M output rows): | D | scatter_add (this PR) | index_add (baseline) | speedup | |---|----------------------|---------------------|---------| | 128 f32 | 18.4 ms | 84.0 ms | 4.6x | | 128 bf16 | 17.5 ms | 83.1 ms | 4.7x | | 1024 f32 | 40.6 ms | 170.6 ms | 4.2x | | 1024 bf16 | 36.7 ms | 165.5 ms | 4.5x | **Uniform** (500K random indices, 100K output rows): | D | scatter_add (this PR) | index_add (baseline) | speedup | |---|----------------------|---------------------|---------| | 128 f32 | 136 us | 265 us | 2.0x | | 128 bf16 | 131 us | 201 us | 1.5x | | 1024 f32 | 927 us | 2068 us | 2.2x | | 1024 bf16 | 450 us | 1549 us | 3.4x | Supported types: float32, float64, float16, bfloat16. `cp.reduce.async.bulk.add` does not support float min/max, so scatter_reduce with min/max/prod is unaffected. ### Test plan - [ ] Correctness verified against reference `scatter_add` for all supported dtypes and D values - [ ] Benchmarked high contention and uniform workloads across D=128..1024, f32/bf16 - [ ] Pre-sm_90 fallback verified to compile and dispatch correctly (vectorized kernel with atomicAdd) - [ ] ROCm excluded from fast path to preserve existing warp-level atomic coalescing Authored with Claude. Pull Request resolved: pytorch#182675 Approved by: https://github.com/drisspg
…84824) Summary: Reland of D104669063, which was reverted following SEV S664741. The underlying TMA smem stage-alignment bug in scatter_add's CuTeDSL override has since been fixed in PR pytorch#184554 (sibling commit in this stack); this diff re-applies the `index_add -> scatter_add` delegation unchanged from the original, with one minor follow-up (see "Follow-ups from D104669063 review" below). Adopts the vectorized scatter_add(dim=0) kernel from D104346887 / PR pytorch#182675 as a fast path for `index_add_` on CUDA. `index_add_(0, idx, src)` is mathematically equivalent to `self.scatter_add_(0, idx.unsqueeze(-1).expand_as(src), src)` when `alpha == 1`, so we delegate so scatter_add's own TMA/vectorized eligibility check + dispatch is the single source of truth. Eligibility (all required to enter the fast path): - `dim == 0` - `alpha == 1` - dtype supported by scatter_add (excludes complex + bool) - `index.dim() <= 1` and contiguous, `numIndex > 0` - scatter_add gates internally per-dtype: TMA sm_90+; vec-scatter sm_60+/sm_70+/sm_90+ for fp32/fp16/bf16 - CUDA 12.8+ at compile time Outside the eligible regime, falls through to the existing `indexFunc{Small,Large}Index` dispatch (untouched). ## Why this reland is safe The original revert was triggered by an IFR MTML embedding-backward job. Diagnostic logs surfaced a latent bug in scatter_add's CuTeDSL TMA path: the 2-stage pipeline buffer is laid out column-major in smem, so stage 1 sits at offset `chunk_bytes` from stage 0's 128B-aligned base. `cp.async.bulk` requires 128B-aligned smem destinations. When `chunk_bytes` is not a multiple of 128 (e.g. fp32 D=8 -> chunk_bytes=32, or fp32 D=36 -> chunk_bytes=144), AND a CTA does more than one iteration (M_src > grid_x cap of sm*64), the kernel writes stage 1 at a misaligned smem address and faults with `cudaErrorMisalignedAddress`. Prod repro: src shape `(104280, 8)` fp32 stride `(568, 1)`, self shape `(13, 8)`. chunk_bytes = 8 * 4 = 32 (< 128), M_src = 104280 > sm * 64 = 8448 -> fault. Confirmed by a local unit-test reproducer at the exact prod call shape. PR pytorch#184554 (parent of this diff in the stack) fixes the kernel by padding the 2-stage pipeline buffer's stage stride to a multiple of 128 bytes: ``` stage_stride_elems = _round_up(chunk_elems, 128 // elem_bytes) sBuf = smem.allocate_tensor( dtype, cute.make_layout((chunk_elems, 2), stride=(1, stage_stride_elems)), 128, ) ``` With that fix in place, every shape this delegation can produce runs through the TMA fast path correctly. PR pytorch#184554 ships kernel-level regression tests (`test_smem_stage_alignment_multi_iter`, parametrized over both `chunk_bytes < 128` and `chunk_bytes in (128, 512) not multiple of 128` cases). This diff adds `test_index_add_smem_stage_alignment_regression` in `test_indexing.py` to pin the same regime through the `index_add` public-API path, so a future refactor of the delegation re-exposing the same shape class is caught here rather than in prod. ## Benchmarks Kernel-side perf is unchanged from D104669063 (the delegation forwards to the same scatter_add kernel, now with PR pytorch#184554's smem padding). See D104669063 summary for full B200 and H100 benchmark tables. Highlights: - Real workloads: B200 4.52x (bf16) / 2.74x (fp32); H100 2.97x (bf16) / 1.42x (fp32). - bf16 sweeps up to 7.40x on B200; zipf high-contention is neutral on both arches (atomic-contention-bound, not bandwidth-bound). PR pytorch#184554's stage-stride padding is a one-extra-smem-byte change in the worst case (chunk_bytes already padded for chunk_bytes >= 128), so no measurable perf delta from the parent commit. Test Plan: Re-running the original D104669063 test suite plus the new small-D + high-M_src regression added in this diff: ``` buck2 test fbcode//mode/opt -c fbcode.enable_gpu_sections=true \ -c fbcode.platform010_cuda_version=12.8 -c fbcode.nvcc_arch=h100a \ fbcode//caffe2/test:test_others_cuda -- \ --regex 'test_index_add_fast_path|test_index_add_excluded_dtypes|test_index_add_smem_stage_alignment_regression' ``` Expected: pass on all parametrized variants (fp32 / fp64 / half / bf16 across 3 shapes x 2 index dtypes for `test_index_add_fast_path`; complex64 / complex128 / bool for `test_index_add_excluded_dtypes`; fp32 / bf16 for the new regression). `test_index_add_smem_stage_alignment_regression` specifically reproduces the SEV-class shape (D=8, M_src = sm * 64 + 256 so every CTA enters stage 1) and asserts numerical equality against a CPU reference. Without PR pytorch#184554 in the same build, this test crashes with `cudaErrorMisalignedAddress`; with the parent commit present, it passes cleanly. No regressions in existing `index_add` tests. https://www.internalfb.com/mlhub/pipelines/runs/mast/mvai-training-online-2122147583-mrs_cog-test-3bd717?job_attempt=0&version=0&tab=logs&env=PRODUCTION f1085796899 mvai-training-online-2122002363-mrs_cog-test-a767bb Reviewed By: slayton58 Differential Revision: D105959759
…84824) Summary: Reland of D104669063, which was reverted following SEV S664741. The underlying TMA smem stage-alignment bug in scatter_add's CuTeDSL override has since been fixed in PR pytorch#184554 (sibling commit in this stack); this diff re-applies the `index_add -> scatter_add` delegation unchanged from the original, with one minor follow-up (see "Follow-ups from D104669063 review" below). Adopts the vectorized scatter_add(dim=0) kernel from D104346887 / PR pytorch#182675 as a fast path for `index_add_` on CUDA. `index_add_(0, idx, src)` is mathematically equivalent to `self.scatter_add_(0, idx.unsqueeze(-1).expand_as(src), src)` when `alpha == 1`, so we delegate so scatter_add's own TMA/vectorized eligibility check + dispatch is the single source of truth. Eligibility (all required to enter the fast path): - `dim == 0` - `alpha == 1` - dtype supported by scatter_add (excludes complex + bool) - `index.dim() <= 1` and contiguous, `numIndex > 0` - scatter_add gates internally per-dtype: TMA sm_90+; vec-scatter sm_60+/sm_70+/sm_90+ for fp32/fp16/bf16 - CUDA 12.8+ at compile time Outside the eligible regime, falls through to the existing `indexFunc{Small,Large}Index` dispatch (untouched). ## Why this reland is safe The original revert was triggered by an IFR MTML embedding-backward job. Diagnostic logs surfaced a latent bug in scatter_add's CuTeDSL TMA path: the 2-stage pipeline buffer is laid out column-major in smem, so stage 1 sits at offset `chunk_bytes` from stage 0's 128B-aligned base. `cp.async.bulk` requires 128B-aligned smem destinations. When `chunk_bytes` is not a multiple of 128 (e.g. fp32 D=8 -> chunk_bytes=32, or fp32 D=36 -> chunk_bytes=144), AND a CTA does more than one iteration (M_src > grid_x cap of sm*64), the kernel writes stage 1 at a misaligned smem address and faults with `cudaErrorMisalignedAddress`. Prod repro: src shape `(104280, 8)` fp32 stride `(568, 1)`, self shape `(13, 8)`. chunk_bytes = 8 * 4 = 32 (< 128), M_src = 104280 > sm * 64 = 8448 -> fault. Confirmed by a local unit-test reproducer at the exact prod call shape. PR pytorch#184554 (parent of this diff in the stack) fixes the kernel by padding the 2-stage pipeline buffer's stage stride to a multiple of 128 bytes: ``` stage_stride_elems = _round_up(chunk_elems, 128 // elem_bytes) sBuf = smem.allocate_tensor( dtype, cute.make_layout((chunk_elems, 2), stride=(1, stage_stride_elems)), 128, ) ``` With that fix in place, every shape this delegation can produce runs through the TMA fast path correctly. PR pytorch#184554 ships kernel-level regression tests (`test_smem_stage_alignment_multi_iter`, parametrized over both `chunk_bytes < 128` and `chunk_bytes in (128, 512) not multiple of 128` cases). This diff adds `test_index_add_smem_stage_alignment_regression` in `test_indexing.py` to pin the same regime through the `index_add` public-API path, so a future refactor of the delegation re-exposing the same shape class is caught here rather than in prod. ## Benchmarks Kernel-side perf is unchanged from D104669063 (the delegation forwards to the same scatter_add kernel, now with PR pytorch#184554's smem padding). See D104669063 summary for full B200 and H100 benchmark tables. Highlights: - Real workloads: B200 4.52x (bf16) / 2.74x (fp32); H100 2.97x (bf16) / 1.42x (fp32). - bf16 sweeps up to 7.40x on B200; zipf high-contention is neutral on both arches (atomic-contention-bound, not bandwidth-bound). PR pytorch#184554's stage-stride padding is a one-extra-smem-byte change in the worst case (chunk_bytes already padded for chunk_bytes >= 128), so no measurable perf delta from the parent commit. Test Plan: Re-running the original D104669063 test suite plus the new small-D + high-M_src regression added in this diff: ``` buck2 test fbcode//mode/opt -c fbcode.enable_gpu_sections=true \ -c fbcode.platform010_cuda_version=12.8 -c fbcode.nvcc_arch=h100a \ fbcode//caffe2/test:test_others_cuda -- \ --regex 'test_index_add_fast_path|test_index_add_excluded_dtypes|test_index_add_smem_stage_alignment_regression' ``` Expected: pass on all parametrized variants (fp32 / fp64 / half / bf16 across 3 shapes x 2 index dtypes for `test_index_add_fast_path`; complex64 / complex128 / bool for `test_index_add_excluded_dtypes`; fp32 / bf16 for the new regression). `test_index_add_smem_stage_alignment_regression` specifically reproduces the SEV-class shape (D=8, M_src = sm * 64 + 256 so every CTA enters stage 1) and asserts numerical equality against a CPU reference. Without PR pytorch#184554 in the same build, this test crashes with `cudaErrorMisalignedAddress`; with the parent commit present, it passes cleanly. No regressions in existing `index_add` tests. https://www.internalfb.com/mlhub/pipelines/runs/mast/mvai-training-online-2122147583-mrs_cog-test-3bd717?job_attempt=0&version=0&tab=logs&env=PRODUCTION f1085796899 mvai-training-online-2122002363-mrs_cog-test-a767bb Reviewed By: slayton58 Differential Revision: D105959759
…184824) Summary: Reland of D104669063, which was reverted following SEV S664741. The underlying TMA smem stage-alignment bug in scatter_add's CuTeDSL override has since been fixed in PR #184554 (sibling commit in this stack); this diff re-applies the `index_add -> scatter_add` delegation unchanged from the original, with one minor follow-up (see "Follow-ups from D104669063 review" below). Adopts the vectorized scatter_add(dim=0) kernel from D104346887 / PR #182675 as a fast path for `index_add_` on CUDA. `index_add_(0, idx, src)` is mathematically equivalent to `self.scatter_add_(0, idx.unsqueeze(-1).expand_as(src), src)` when `alpha == 1`, so we delegate so scatter_add's own TMA/vectorized eligibility check + dispatch is the single source of truth. Eligibility (all required to enter the fast path): - `dim == 0` - `alpha == 1` - dtype supported by scatter_add (excludes complex + bool) - `index.dim() <= 1` and contiguous, `numIndex > 0` - scatter_add gates internally per-dtype: TMA sm_90+; vec-scatter sm_60+/sm_70+/sm_90+ for fp32/fp16/bf16 - CUDA 12.8+ at compile time Outside the eligible regime, falls through to the existing `indexFunc{Small,Large}Index` dispatch (untouched). ## Why this reland is safe The original revert was triggered by an IFR MTML embedding-backward job. Diagnostic logs surfaced a latent bug in scatter_add's CuTeDSL TMA path: the 2-stage pipeline buffer is laid out column-major in smem, so stage 1 sits at offset `chunk_bytes` from stage 0's 128B-aligned base. `cp.async.bulk` requires 128B-aligned smem destinations. When `chunk_bytes` is not a multiple of 128 (e.g. fp32 D=8 -> chunk_bytes=32, or fp32 D=36 -> chunk_bytes=144), AND a CTA does more than one iteration (M_src > grid_x cap of sm*64), the kernel writes stage 1 at a misaligned smem address and faults with `cudaErrorMisalignedAddress`. Prod repro: src shape `(104280, 8)` fp32 stride `(568, 1)`, self shape `(13, 8)`. chunk_bytes = 8 * 4 = 32 (< 128), M_src = 104280 > sm * 64 = 8448 -> fault. Confirmed by a local unit-test reproducer at the exact prod call shape. PR #184554 (parent of this diff in the stack) fixes the kernel by padding the 2-stage pipeline buffer's stage stride to a multiple of 128 bytes: ``` stage_stride_elems = _round_up(chunk_elems, 128 // elem_bytes) sBuf = smem.allocate_tensor( dtype, cute.make_layout((chunk_elems, 2), stride=(1, stage_stride_elems)), 128, ) ``` With that fix in place, every shape this delegation can produce runs through the TMA fast path correctly. PR #184554 ships kernel-level regression tests (`test_smem_stage_alignment_multi_iter`, parametrized over both `chunk_bytes < 128` and `chunk_bytes in (128, 512) not multiple of 128` cases). This diff adds `test_index_add_smem_stage_alignment_regression` in `test_indexing.py` to pin the same regime through the `index_add` public-API path, so a future refactor of the delegation re-exposing the same shape class is caught here rather than in prod. ## Benchmarks Kernel-side perf is unchanged from D104669063 (the delegation forwards to the same scatter_add kernel, now with PR #184554's smem padding). See D104669063 summary for full B200 and H100 benchmark tables. Highlights: - Real workloads: B200 4.52x (bf16) / 2.74x (fp32); H100 2.97x (bf16) / 1.42x (fp32). - bf16 sweeps up to 7.40x on B200; zipf high-contention is neutral on both arches (atomic-contention-bound, not bandwidth-bound). PR #184554's stage-stride padding is a one-extra-smem-byte change in the worst case (chunk_bytes already padded for chunk_bytes >= 128), so no measurable perf delta from the parent commit. Test Plan: Re-running the original D104669063 test suite plus the new small-D + high-M_src regression added in this diff: ``` buck2 test fbcode//mode/opt -c fbcode.enable_gpu_sections=true \ -c fbcode.platform010_cuda_version=12.8 -c fbcode.nvcc_arch=h100a \ fbcode//caffe2/test:test_others_cuda -- \ --regex 'test_index_add_fast_path|test_index_add_excluded_dtypes|test_index_add_smem_stage_alignment_regression' ``` Expected: pass on all parametrized variants (fp32 / fp64 / half / bf16 across 3 shapes x 2 index dtypes for `test_index_add_fast_path`; complex64 / complex128 / bool for `test_index_add_excluded_dtypes`; fp32 / bf16 for the new regression). `test_index_add_smem_stage_alignment_regression` specifically reproduces the SEV-class shape (D=8, M_src = sm * 64 + 256 so every CTA enters stage 1) and asserts numerical equality against a CPU reference. Without PR #184554 in the same build, this test crashes with `cudaErrorMisalignedAddress`; with the parent commit present, it passes cleanly. No regressions in existing `index_add` tests. https://www.internalfb.com/mlhub/pipelines/runs/mast/mvai-training-online-2122147583-mrs_cog-test-3bd717?job_attempt=0&version=0&tab=logs&env=PRODUCTION f1085796899 mvai-training-online-2122002363-mrs_cog-test-a767bb Reviewed By: slayton58 Differential Revision: D105959759 Pull Request resolved: #184824 Approved by: https://github.com/wdvr
## Vectorized scatter_add with TMA bulk reduce on sm_90+ ### Summary Add a fast path for `scatter_add` on dim=0 when self, src are contiguous and index is expanded (same eligibility as the existing `vectorized_gather` fast path, with roles of self/src swapped). On sm_90+ (Hopper/Blackwell), uses `cp.reduce.async.bulk` to offload the entire accumulation to the TMA unit, avoiding the serial `atomicAdd` stall that limits both the existing `scatter_add` and `index_add` under contention. The kernel uses warp-per-slice scheduling, TMA loads (`cp.async.bulk.shared::cta.global`), double-buffered shared memory with chunking for arbitrary D, and mbarrier-based completion tracking. On pre-sm_90 NVIDIA, falls back to a vectorized scatter_add kernel using `ld_vec<16>` + per-element `atomicAdd` with warp-per-slice packing. ROCm is excluded (has its own optimized warp-level atomic coalescing on gfx942/gfx950). Also fixes a precedence bug in the existing `fast_gather_kernel_eligible` where `static_cast<size_t>(iter.strides(1)[1] == 0)` had the comparison inside the cast. ### Benchmarks (GB200, sm_100) **High contention** (D103765236 scenario: 7.77M indices, 3.89M targeting one row, 1.72M output rows): | D | scatter_add (this PR) | index_add (baseline) | speedup | |---|----------------------|---------------------|---------| | 128 f32 | 18.4 ms | 84.0 ms | 4.6x | | 128 bf16 | 17.5 ms | 83.1 ms | 4.7x | | 1024 f32 | 40.6 ms | 170.6 ms | 4.2x | | 1024 bf16 | 36.7 ms | 165.5 ms | 4.5x | **Uniform** (500K random indices, 100K output rows): | D | scatter_add (this PR) | index_add (baseline) | speedup | |---|----------------------|---------------------|---------| | 128 f32 | 136 us | 265 us | 2.0x | | 128 bf16 | 131 us | 201 us | 1.5x | | 1024 f32 | 927 us | 2068 us | 2.2x | | 1024 bf16 | 450 us | 1549 us | 3.4x | Supported types: float32, float64, float16, bfloat16. `cp.reduce.async.bulk.add` does not support float min/max, so scatter_reduce with min/max/prod is unaffected. ### Test plan - [ ] Correctness verified against reference `scatter_add` for all supported dtypes and D values - [ ] Benchmarked high contention and uniform workloads across D=128..1024, f32/bf16 - [ ] Pre-sm_90 fallback verified to compile and dispatch correctly (vectorized kernel with atomicAdd) - [ ] ROCm excluded from fast path to preserve existing warp-level atomic coalescing Authored with Claude. Pull Request resolved: pytorch#182675 Approved by: https://github.com/drisspg
…ors (pytorch#175760)" (pytorch#182693) (pytorch#182693) Summary: D94314062 introduced a VecSize=4 fast path in indexFuncLargeIndex that amortizes divmod and index lookup by having each thread process consecutive elements. On uniform-random workloads this gives a ~1.8-2.0x speedup. However, when the index distribution is heavy-tailed (e.g. zipf, or skewed where a few hot rows receive millions of writes), the fast path issues 4 atomicAdds back-to-back from the same warp into consecutive cache lines of the same destination row. The L2 atomic queue cannot drain between the unrolled rounds, and the resulting serialization causes a 4.7x slowdown on fp32 zipf inputs (and ~2x on bf16). Measured on a B200 with dst=[1.72M,128] and nIdx=7.77M: {F1989310065} Proposal https://fb.workplace.com/groups/482605989533128/permalink/1656067795520269/ exhibits highly skewed behavior and saw a regression with the diffs We back the current implementation out temporarily and will be following the approach of pytorch#182675 instead and address the contention problem Test Plan: CI Reviewed By: yjhao Differential Revision: D104098792 Pull Request resolved: pytorch#182693 Approved by: https://github.com/drisspg
…h#182675)" This reverts commit fee4fd3. Reverted pytorch#182675 on behalf of https://github.com/ngimel due to internal build failure ([comment](pytorch#182675 (comment)))
## Vectorized scatter_add with TMA bulk reduce on sm_90+ ### Summary Add a fast path for `scatter_add` on dim=0 when self, src are contiguous and index is expanded (same eligibility as the existing `vectorized_gather` fast path, with roles of self/src swapped). On sm_90+ (Hopper/Blackwell), uses `cp.reduce.async.bulk` to offload the entire accumulation to the TMA unit, avoiding the serial `atomicAdd` stall that limits both the existing `scatter_add` and `index_add` under contention. The kernel uses warp-per-slice scheduling, TMA loads (`cp.async.bulk.shared::cta.global`), double-buffered shared memory with chunking for arbitrary D, and mbarrier-based completion tracking. On pre-sm_90 NVIDIA, falls back to a vectorized scatter_add kernel using `ld_vec<16>` + per-element `atomicAdd` with warp-per-slice packing. ROCm is excluded (has its own optimized warp-level atomic coalescing on gfx942/gfx950). Also fixes a precedence bug in the existing `fast_gather_kernel_eligible` where `static_cast<size_t>(iter.strides(1)[1] == 0)` had the comparison inside the cast. ### Benchmarks (GB200, sm_100) **High contention** (D103765236 scenario: 7.77M indices, 3.89M targeting one row, 1.72M output rows): | D | scatter_add (this PR) | index_add (baseline) | speedup | |---|----------------------|---------------------|---------| | 128 f32 | 18.4 ms | 84.0 ms | 4.6x | | 128 bf16 | 17.5 ms | 83.1 ms | 4.7x | | 1024 f32 | 40.6 ms | 170.6 ms | 4.2x | | 1024 bf16 | 36.7 ms | 165.5 ms | 4.5x | **Uniform** (500K random indices, 100K output rows): | D | scatter_add (this PR) | index_add (baseline) | speedup | |---|----------------------|---------------------|---------| | 128 f32 | 136 us | 265 us | 2.0x | | 128 bf16 | 131 us | 201 us | 1.5x | | 1024 f32 | 927 us | 2068 us | 2.2x | | 1024 bf16 | 450 us | 1549 us | 3.4x | Supported types: float32, float64, float16, bfloat16. `cp.reduce.async.bulk.add` does not support float min/max, so scatter_reduce with min/max/prod is unaffected. ### Test plan - [ ] Correctness verified against reference `scatter_add` for all supported dtypes and D values - [ ] Benchmarked high contention and uniform workloads across D=128..1024, f32/bf16 - [ ] Pre-sm_90 fallback verified to compile and dispatch correctly (vectorized kernel with atomicAdd) - [ ] ROCm excluded from fast path to preserve existing warp-level atomic coalescing Authored with Claude. Pull Request resolved: pytorch#182675 Approved by: https://github.com/drisspg
…189506) Summary: Second reland of the `index_add -> scatter_add` delegation. This reland sits on top of D110978969 ([native] Move scatter-add N-dim to dynamic, #188820), which moves the scatter_add CuTeDSL override's compile-cache key for the inner dimension to dynamic, so a single compile serves all N sizes instead of recompiling per application (dtype and contig/non-contig still recompile). With D110978969 landed, the issue behind the most recent revert of this diff is resolved, so the delegation is re-applied here unchanged. Adopts the vectorized scatter_add(dim=0) kernel from D104346887 / PR #182675 as a fast path for `index_add_` on CUDA. `index_add_(0, idx, src)` is mathematically equivalent to `self.scatter_add_(0, idx.unsqueeze(-1).expand_as(src), src)` when `alpha == 1`, so we delegate so scatter_add's own TMA/vectorized eligibility check + dispatch is the single source of truth. Eligibility (all required to enter the fast path): - `dim == 0` - `alpha == 1` - dtype supported by scatter_add (excludes complex + bool) - `index.dim() <= 1` and contiguous, `numIndex > 0` - scatter_add gates internally per-dtype: TMA sm_90+; vec-scatter sm_60+/sm_70+/sm_90+ for fp32/fp16/bf16 - CUDA 12.8+ at compile time Outside the eligible regime, falls through to the existing `indexFunc{Small,Large}Index` dispatch (untouched). ## Benchmarks Kernel-side perf is unchanged from D104669063 (the delegation forwards to the same scatter_add kernel, now with PR #184554's smem padding). See D104669063 summary for full B200 and H100 benchmark tables. Highlights: - Real workloads: B200 4.52x (bf16) / 2.74x (fp32); H100 2.97x (bf16) / 1.42x (fp32). - bf16 sweeps up to 7.40x on B200; zipf high-contention is neutral on both arches (atomic-contention-bound, not bandwidth-bound). PR #184554's stage-stride padding is a one-extra-smem-byte change in the worst case (chunk_bytes already padded for chunk_bytes >= 128), so no measurable perf delta from the parent commit. bypass-github-export-checks unrelated failure Test Plan: Re-running the original D104669063 test suite plus the new small-D + high-M_src regression added in this diff: ``` buck2 test fbcode//mode/opt -c fbcode.enable_gpu_sections=true \ -c fbcode.platform010_cuda_version=12.8 -c fbcode.nvcc_arch=h100a \ fbcode//caffe2/test:test_others_cuda -- \ --regex 'test_index_add_fast_path|test_index_add_excluded_dtypes|test_index_add_smem_stage_alignment_regression' ``` Expected: pass on all parametrized variants (fp32 / fp64 / half / bf16 across 3 shapes x 2 index dtypes for `test_index_add_fast_path`; complex64 / complex128 / bool for `test_index_add_excluded_dtypes`; fp32 / bf16 for the new regression). `test_index_add_smem_stage_alignment_regression` specifically reproduces the SEV-class shape (D=8, M_src = sm * 64 + 256 so every CTA enters stage 1) and asserts numerical equality against a CPU reference. Without PR #184554 in the same build, this test crashes with `cudaErrorMisalignedAddress`; with the parent commit present, it passes cleanly. No regressions in existing `index_add` tests. Check that issues gone in https://www.internalfb.com/mlhub/pipelines/runs/mast/fire-albertchen-train-f1110230424?job_attempt=1&version=0&tab=summary https://www.internalfb.com/mlhub/pipelines/runs/mast/fire-albertchen-train-mast-UDD-2026-06-27-3d-f958b44a?job_attempt=1&version=0&tab=summary&env=PRODUCTION https://www.internalfb.com/mlhub/pipelines/runs/mast/mvai-training-online-2115904614?version=0&env=PRODUCTION Differential Revision: D111254885 Pull Request resolved: #189506 Approved by: https://github.com/jeanschmidt
## Vectorized scatter_add with TMA bulk reduce on sm_90+ ### Summary Add a fast path for `scatter_add` on dim=0 when self, src are contiguous and index is expanded (same eligibility as the existing `vectorized_gather` fast path, with roles of self/src swapped). On sm_90+ (Hopper/Blackwell), uses `cp.reduce.async.bulk` to offload the entire accumulation to the TMA unit, avoiding the serial `atomicAdd` stall that limits both the existing `scatter_add` and `index_add` under contention. The kernel uses warp-per-slice scheduling, TMA loads (`cp.async.bulk.shared::cta.global`), double-buffered shared memory with chunking for arbitrary D, and mbarrier-based completion tracking. On pre-sm_90 NVIDIA, falls back to a vectorized scatter_add kernel using `ld_vec<16>` + per-element `atomicAdd` with warp-per-slice packing. ROCm is excluded (has its own optimized warp-level atomic coalescing on gfx942/gfx950). Also fixes a precedence bug in the existing `fast_gather_kernel_eligible` where `static_cast<size_t>(iter.strides(1)[1] == 0)` had the comparison inside the cast. ### Benchmarks (GB200, sm_100) **High contention** (D103765236 scenario: 7.77M indices, 3.89M targeting one row, 1.72M output rows): | D | scatter_add (this PR) | index_add (baseline) | speedup | |---|----------------------|---------------------|---------| | 128 f32 | 18.4 ms | 84.0 ms | 4.6x | | 128 bf16 | 17.5 ms | 83.1 ms | 4.7x | | 1024 f32 | 40.6 ms | 170.6 ms | 4.2x | | 1024 bf16 | 36.7 ms | 165.5 ms | 4.5x | **Uniform** (500K random indices, 100K output rows): | D | scatter_add (this PR) | index_add (baseline) | speedup | |---|----------------------|---------------------|---------| | 128 f32 | 136 us | 265 us | 2.0x | | 128 bf16 | 131 us | 201 us | 1.5x | | 1024 f32 | 927 us | 2068 us | 2.2x | | 1024 bf16 | 450 us | 1549 us | 3.4x | Supported types: float32, float64, float16, bfloat16. `cp.reduce.async.bulk.add` does not support float min/max, so scatter_reduce with min/max/prod is unaffected. ### Test plan - [ ] Correctness verified against reference `scatter_add` for all supported dtypes and D values - [ ] Benchmarked high contention and uniform workloads across D=128..1024, f32/bf16 - [ ] Pre-sm_90 fallback verified to compile and dispatch correctly (vectorized kernel with atomicAdd) - [ ] ROCm excluded from fast path to preserve existing warp-level atomic coalescing Authored with Claude. Pull Request resolved: pytorch#182675 Approved by: https://github.com/drisspg
…ors (pytorch#175760)" (pytorch#182693) (pytorch#182693) Summary: D94314062 introduced a VecSize=4 fast path in indexFuncLargeIndex that amortizes divmod and index lookup by having each thread process consecutive elements. On uniform-random workloads this gives a ~1.8-2.0x speedup. However, when the index distribution is heavy-tailed (e.g. zipf, or skewed where a few hot rows receive millions of writes), the fast path issues 4 atomicAdds back-to-back from the same warp into consecutive cache lines of the same destination row. The L2 atomic queue cannot drain between the unrolled rounds, and the resulting serialization causes a 4.7x slowdown on fp32 zipf inputs (and ~2x on bf16). Measured on a B200 with dst=[1.72M,128] and nIdx=7.77M: {F1989310065} Proposal https://fb.workplace.com/groups/482605989533128/permalink/1656067795520269/ exhibits highly skewed behavior and saw a regression with the diffs We back the current implementation out temporarily and will be following the approach of pytorch#182675 instead and address the contention problem Test Plan: CI Reviewed By: yjhao Differential Revision: D104098792 Pull Request resolved: pytorch#182693 Approved by: https://github.com/drisspg
…h#182675)" This reverts commit fee4fd3. Reverted pytorch#182675 on behalf of https://github.com/ngimel due to internal build failure ([comment](pytorch#182675 (comment)))
## Vectorized scatter_add with TMA bulk reduce on sm_90+ ### Summary Add a fast path for `scatter_add` on dim=0 when self, src are contiguous and index is expanded (same eligibility as the existing `vectorized_gather` fast path, with roles of self/src swapped). On sm_90+ (Hopper/Blackwell), uses `cp.reduce.async.bulk` to offload the entire accumulation to the TMA unit, avoiding the serial `atomicAdd` stall that limits both the existing `scatter_add` and `index_add` under contention. The kernel uses warp-per-slice scheduling, TMA loads (`cp.async.bulk.shared::cta.global`), double-buffered shared memory with chunking for arbitrary D, and mbarrier-based completion tracking. On pre-sm_90 NVIDIA, falls back to a vectorized scatter_add kernel using `ld_vec<16>` + per-element `atomicAdd` with warp-per-slice packing. ROCm is excluded (has its own optimized warp-level atomic coalescing on gfx942/gfx950). Also fixes a precedence bug in the existing `fast_gather_kernel_eligible` where `static_cast<size_t>(iter.strides(1)[1] == 0)` had the comparison inside the cast. ### Benchmarks (GB200, sm_100) **High contention** (D103765236 scenario: 7.77M indices, 3.89M targeting one row, 1.72M output rows): | D | scatter_add (this PR) | index_add (baseline) | speedup | |---|----------------------|---------------------|---------| | 128 f32 | 18.4 ms | 84.0 ms | 4.6x | | 128 bf16 | 17.5 ms | 83.1 ms | 4.7x | | 1024 f32 | 40.6 ms | 170.6 ms | 4.2x | | 1024 bf16 | 36.7 ms | 165.5 ms | 4.5x | **Uniform** (500K random indices, 100K output rows): | D | scatter_add (this PR) | index_add (baseline) | speedup | |---|----------------------|---------------------|---------| | 128 f32 | 136 us | 265 us | 2.0x | | 128 bf16 | 131 us | 201 us | 1.5x | | 1024 f32 | 927 us | 2068 us | 2.2x | | 1024 bf16 | 450 us | 1549 us | 3.4x | Supported types: float32, float64, float16, bfloat16. `cp.reduce.async.bulk.add` does not support float min/max, so scatter_reduce with min/max/prod is unaffected. ### Test plan - [ ] Correctness verified against reference `scatter_add` for all supported dtypes and D values - [ ] Benchmarked high contention and uniform workloads across D=128..1024, f32/bf16 - [ ] Pre-sm_90 fallback verified to compile and dispatch correctly (vectorized kernel with atomicAdd) - [ ] ROCm excluded from fast path to preserve existing warp-level atomic coalescing Authored with Claude. Pull Request resolved: pytorch#182675 Approved by: https://github.com/drisspg
…torch#183455) Summary: Adopts the vectorized scatter_add(dim=0) kernel from D104346887 / PR pytorch#182675 as a fast path for `index_add_` on CUDA. `index_add_(0, idx, src)` is mathematically equivalent to `self.scatter_add_(0, idx.unsqueeze(-1).expand_as(src), src)` when `alpha == 1`, so we can call `tma_scatter_add_kernel_launch` directly. Eligibility (all required to enter the fast path): - `dim == 0` - `alpha == 1` - dtype in `{float, double, half, bfloat16}` - `self_` and `source_` contiguous, `index` 1-D contiguous, `numIndex > 0` - 16-byte alignment of self/src ptrs, slice size, and row strides - sm_90+ at runtime - CUDA 12.8+ at compile time Outside the eligible regime, falls through to the existing `indexFunc{Small,Large}Index` dispatch (untouched). The block is preprocessed out entirely on CUDA < 12.8, since the upstream vectorized fallback contains an int32 stride overflow that triggers `cudaErrorIllegalAddress` on the production workloads we're targeting; pre-Hopper builds therefore stay on the existing baseline rather than picking up the broken vectorized fallback. ## Benchmarks Bench script: `caffe2/benchmarks/operator_benchmark/pt/bench_index_add_large.py` (in parent commit). Baseline = parent commit; fast path = this commit. Each was a fresh `buck2 run mode/opt` build with the same CUDA toolchain. Per-call timing via CUDA events. ### B200 (sm_100, CUDA 12.8, TMA path) Real workloads: | Workload | Baseline (us) | Fast path (us) | Speedup | |---|---:|---:|---:| | REAL bf16 [4036236,128] dim=0 nIdx=4036236 (H100 shape) | 4388 | 971 | **4.52x** | | REAL fp32 [1722482,128] dim=0 nIdx=7773925 (B200 shape) | 6968 | 2542 | **2.74x** | bf16 sweep (dim=0): | Shape | Baseline (us) | Fast path (us) | Speedup | |---|---:|---:|---:| | 1M x 128 | 1076 | 280 | 3.85x | | 4M x 128 | 4349 | 1001 | 4.34x | | 4M x 256 | 8335 | 1309 | 6.36x | | 4M x 512 | 16612 | 2244 | **7.40x** | fp32 distribution sweep (dst=[1.7M, 128], nIdx=7.77M): | Distribution | Baseline (us) | Fast path (us) | Speedup | |---|---:|---:|---:| | uniform | 6837 | 2518 | 2.72x | | zipf s=1.0 | 17740 | 16659 | 1.06x | | zipf s=1.5 | 22465 | 21280 | 1.06x | | skewed 80/20 | 6614 | 2119 | 3.12x | | skewed hot=100 | 6584 | 2307 | 2.85x | bf16 distribution sweep: | Distribution | Baseline (us) | Fast path (us) | Speedup | |---|---:|---:|---:| | uniform | 8074 | 1940 | 4.16x | | zipf s=1.0 | 37692 | 16495 | 2.29x | | zipf s=1.5 | 47448 | 20843 | 2.28x | | skewed 80/20 | 7934 | 1724 | 4.60x | | skewed hot=100 | 7923 | 1736 | 4.56x | ### H100 (sm_90, CUDA 12.8, TMA path) Real workloads: | Workload | Baseline (us) | Fast path (us) | Speedup | |---|---:|---:|---:| | REAL bf16 [4036236,128] dim=0 nIdx=4036236 (H100 shape) | 4859 | 1636 | **2.97x** | | REAL fp32 [1722482,128] dim=0 nIdx=7773925 (B200 shape) | 8537 | 6001 | **1.42x** | fp32 distribution sweep: | Distribution | Baseline (us) | Fast path (us) | Speedup | |---|---:|---:|---:| | uniform | 8349 | 5985 | 1.39x | | zipf s=1.0 | 19768 | 19751 | neutral | | zipf s=1.5 | 24052 | 24196 | neutral | | skewed 80/20 | 7641 | 3240 | 2.36x | | skewed hot=100 | 7354 | 4183 | 1.76x | bf16 distribution sweep: | Distribution | Baseline (us) | Fast path (us) | Speedup | |---|---:|---:|---:| | uniform | 9182 | 3088 | 2.97x | | zipf s=1.0 | 41165 | 18610 | 2.21x | | zipf s=1.5 | 53089 | 23986 | 2.21x | | skewed 80/20 | 8622 | 2409 | 3.58x | | skewed hot=100 | 8541 | 2692 | 3.17x | ### Cross-arch observations - bf16 wins are large on both arches because the dominant cost in baseline is scalar bf16 atomicAdd (CAS-loop). The TMA kernel's `cp.reduce.async.bulk.add.bf16` replaces that with hardware-supported reduction. - B200 wins are larger than H100 on non-contention workloads — Blackwell's TMA throughput is meaningfully higher than Hopper's. - bf16 zipf high-contention is arch-invariant (2.21x H100 vs 2.28-2.29x B200) — that workload is bottlenecked on atomic contention into the same hot rows, so neither generation can pull ahead. - fp32 zipf high-contention is neutral on H100 and only ~1.06x on B200 — same reason: contention dominates. ### CUDA 12.4 build verification A separate run with `-c fbcode.platform010_cuda_version=12.4` confirms the gate works: `strings Indexing.cu.o | grep -c index_add_fast` returns 0, the fast-path block is preprocessed out, and the bench runs against the existing baseline path with no crash and no regression. Pre-Hopper / older-CUDA users land safely on the existing kernel path. Test Plan: Added `test_index_add_fast_path` in `caffe2/test/test_indexing.py`. Parametrized over `dtypes(float32, float64, half, bfloat16)` across 3 shapes × 2 index dtypes (int32/int64), with 7 sub-cases per (shape, idx_dtype): 1. Fast path: `dim=0 + alpha=1 + contig + 16B aligned` -> hits TMA kernel 2. Fallback: `alpha != 1` (alpha=2.5) 3. Fallback: discontiguous src (strided slice) 4. Fallback: misaligned self (one-element pointer offset) 5. Fallback: `dim != 0` (dim=1) 6. Fallback: sliced inner-dim (not `is_contiguous()`) 7. Edge case: empty index (no-op) All sub-cases assert correctness against a CPU reference. Tolerances bound the CPU-vs-CUDA atomicAdd-order noise (`fp32/fp64: 1e-5/1e-3`, `half: 5e-2/5e-2`, `bf16: 0.5/0.5`); shapes keep `n/m <= ~1` to bound the per-row sum noise. Test results on B200 (CUDA 12.8): ``` $ buck2 test fbcode//mode/opt -c fbcode.enable_gpu_sections=true \ -c fbcode.platform010_cuda_version=12.8 -c fbcode.nvcc_arch=b200a \ fbcode//caffe2/test:test_others_cuda -- --regex 'test_index_add_fast_path' Pass 5. Fail 0. $ buck2 test ... fbcode//caffe2/test:test_torch_cuda -- --regex 'test_index_add' Pass 7. Fail 0. Skip 1 (pre-existing, unrelated). ``` No regressions in existing index_add tests. Build verification on CUDA 12.4 (gate behavior): `strings Indexing.cu.pic.o | grep -c index_add_fast` returns 0, confirming the fast-path block is preprocessed out cleanly when CUDA < 12.8. Bench run with CUDA 12.4 + a100 confirms no crash and no behavioral change vs baseline (numbers are neutral, as expected since the fast path is gated out). See diff Summary for full B200 + H100 benchmark numbers. https://www.internalfb.com/mlhub/pipelines/runs/mast/fire-albertchen-f1081016863?job_attempt=0&version=0&tab=summary {F1989741342} vs prod https://www.internalfb.com/mlhub/pipelines/runs/mast/mvai-training-online-2134319967?job_attempt=7&version=37&tab=summary {F1989741358} Skew workload https://www.internalfb.com/mast/job/fire-yujiah-20260512-1008-9a6ab7ff trace: https://www.internalfb.com/intern/kernelhub/perfetto/?bucket=mvai_gpu_traces&trace_path=tree%2Ftraces%2Fdynocli%2Ffire-yujiah-20260512-1008-9a6ab7ff%2F0%2Frank-0.May_12_11_00_53.4196.pt.trace.json.gz {F1989752493} baseline: https://www.internalfb.com/mast/job/fire-yujiah-20260512-1000-8f514189 trace: https://www.internalfb.com/intern/kernelhub/perfetto/?bucket=mvai_gpu_traces&trace_path=tree%2Ftraces%2Fdynocli%2Ffire-yujiah-20260512-1000-8f514189%2F0%2Frank-0.May_12_10_40_33.4216.pt.trace.json.gz {F1989752599} Reviewed By: drisspg Differential Revision: D104669063 Pull Request resolved: pytorch#183455 Approved by: https://github.com/drisspg
…84824) (pytorch#184824) Summary: Reland of D104669063, which was reverted following SEV S664741. The underlying TMA smem stage-alignment bug in scatter_add's CuTeDSL override has since been fixed in PR pytorch#184554 (sibling commit in this stack); this diff re-applies the `index_add -> scatter_add` delegation unchanged from the original, with one minor follow-up (see "Follow-ups from D104669063 review" below). Adopts the vectorized scatter_add(dim=0) kernel from D104346887 / PR pytorch#182675 as a fast path for `index_add_` on CUDA. `index_add_(0, idx, src)` is mathematically equivalent to `self.scatter_add_(0, idx.unsqueeze(-1).expand_as(src), src)` when `alpha == 1`, so we delegate so scatter_add's own TMA/vectorized eligibility check + dispatch is the single source of truth. Eligibility (all required to enter the fast path): - `dim == 0` - `alpha == 1` - dtype supported by scatter_add (excludes complex + bool) - `index.dim() <= 1` and contiguous, `numIndex > 0` - scatter_add gates internally per-dtype: TMA sm_90+; vec-scatter sm_60+/sm_70+/sm_90+ for fp32/fp16/bf16 - CUDA 12.8+ at compile time Outside the eligible regime, falls through to the existing `indexFunc{Small,Large}Index` dispatch (untouched). ## Why this reland is safe The original revert was triggered by an IFR MTML embedding-backward job. Diagnostic logs surfaced a latent bug in scatter_add's CuTeDSL TMA path: the 2-stage pipeline buffer is laid out column-major in smem, so stage 1 sits at offset `chunk_bytes` from stage 0's 128B-aligned base. `cp.async.bulk` requires 128B-aligned smem destinations. When `chunk_bytes` is not a multiple of 128 (e.g. fp32 D=8 -> chunk_bytes=32, or fp32 D=36 -> chunk_bytes=144), AND a CTA does more than one iteration (M_src > grid_x cap of sm*64), the kernel writes stage 1 at a misaligned smem address and faults with `cudaErrorMisalignedAddress`. Prod repro: src shape `(104280, 8)` fp32 stride `(568, 1)`, self shape `(13, 8)`. chunk_bytes = 8 * 4 = 32 (< 128), M_src = 104280 > sm * 64 = 8448 -> fault. Confirmed by a local unit-test reproducer at the exact prod call shape. PR pytorch#184554 (parent of this diff in the stack) fixes the kernel by padding the 2-stage pipeline buffer's stage stride to a multiple of 128 bytes: ``` stage_stride_elems = _round_up(chunk_elems, 128 // elem_bytes) sBuf = smem.allocate_tensor( dtype, cute.make_layout((chunk_elems, 2), stride=(1, stage_stride_elems)), 128, ) ``` With that fix in place, every shape this delegation can produce runs through the TMA fast path correctly. PR pytorch#184554 ships kernel-level regression tests (`test_smem_stage_alignment_multi_iter`, parametrized over both `chunk_bytes < 128` and `chunk_bytes in (128, 512) not multiple of 128` cases). This diff adds `test_index_add_smem_stage_alignment_regression` in `test_indexing.py` to pin the same regime through the `index_add` public-API path, so a future refactor of the delegation re-exposing the same shape class is caught here rather than in prod. ## Benchmarks Kernel-side perf is unchanged from D104669063 (the delegation forwards to the same scatter_add kernel, now with PR pytorch#184554's smem padding). See D104669063 summary for full B200 and H100 benchmark tables. Highlights: - Real workloads: B200 4.52x (bf16) / 2.74x (fp32); H100 2.97x (bf16) / 1.42x (fp32). - bf16 sweeps up to 7.40x on B200; zipf high-contention is neutral on both arches (atomic-contention-bound, not bandwidth-bound). PR pytorch#184554's stage-stride padding is a one-extra-smem-byte change in the worst case (chunk_bytes already padded for chunk_bytes >= 128), so no measurable perf delta from the parent commit. Test Plan: Re-running the original D104669063 test suite plus the new small-D + high-M_src regression added in this diff: ``` buck2 test fbcode//mode/opt -c fbcode.enable_gpu_sections=true \ -c fbcode.platform010_cuda_version=12.8 -c fbcode.nvcc_arch=h100a \ fbcode//caffe2/test:test_others_cuda -- \ --regex 'test_index_add_fast_path|test_index_add_excluded_dtypes|test_index_add_smem_stage_alignment_regression' ``` Expected: pass on all parametrized variants (fp32 / fp64 / half / bf16 across 3 shapes x 2 index dtypes for `test_index_add_fast_path`; complex64 / complex128 / bool for `test_index_add_excluded_dtypes`; fp32 / bf16 for the new regression). `test_index_add_smem_stage_alignment_regression` specifically reproduces the SEV-class shape (D=8, M_src = sm * 64 + 256 so every CTA enters stage 1) and asserts numerical equality against a CPU reference. Without PR pytorch#184554 in the same build, this test crashes with `cudaErrorMisalignedAddress`; with the parent commit present, it passes cleanly. No regressions in existing `index_add` tests. https://www.internalfb.com/mlhub/pipelines/runs/mast/mvai-training-online-2122147583-mrs_cog-test-3bd717?job_attempt=0&version=0&tab=logs&env=PRODUCTION f1085796899 mvai-training-online-2122002363-mrs_cog-test-a767bb Reviewed By: slayton58 Differential Revision: D105959759 Pull Request resolved: pytorch#184824 Approved by: https://github.com/wdvr
…84824) (pytorch#189506) Summary: Second reland of the `index_add -> scatter_add` delegation. This reland sits on top of D110978969 ([native] Move scatter-add N-dim to dynamic, pytorch#188820), which moves the scatter_add CuTeDSL override's compile-cache key for the inner dimension to dynamic, so a single compile serves all N sizes instead of recompiling per application (dtype and contig/non-contig still recompile). With D110978969 landed, the issue behind the most recent revert of this diff is resolved, so the delegation is re-applied here unchanged. Adopts the vectorized scatter_add(dim=0) kernel from D104346887 / PR pytorch#182675 as a fast path for `index_add_` on CUDA. `index_add_(0, idx, src)` is mathematically equivalent to `self.scatter_add_(0, idx.unsqueeze(-1).expand_as(src), src)` when `alpha == 1`, so we delegate so scatter_add's own TMA/vectorized eligibility check + dispatch is the single source of truth. Eligibility (all required to enter the fast path): - `dim == 0` - `alpha == 1` - dtype supported by scatter_add (excludes complex + bool) - `index.dim() <= 1` and contiguous, `numIndex > 0` - scatter_add gates internally per-dtype: TMA sm_90+; vec-scatter sm_60+/sm_70+/sm_90+ for fp32/fp16/bf16 - CUDA 12.8+ at compile time Outside the eligible regime, falls through to the existing `indexFunc{Small,Large}Index` dispatch (untouched). ## Benchmarks Kernel-side perf is unchanged from D104669063 (the delegation forwards to the same scatter_add kernel, now with PR pytorch#184554's smem padding). See D104669063 summary for full B200 and H100 benchmark tables. Highlights: - Real workloads: B200 4.52x (bf16) / 2.74x (fp32); H100 2.97x (bf16) / 1.42x (fp32). - bf16 sweeps up to 7.40x on B200; zipf high-contention is neutral on both arches (atomic-contention-bound, not bandwidth-bound). PR pytorch#184554's stage-stride padding is a one-extra-smem-byte change in the worst case (chunk_bytes already padded for chunk_bytes >= 128), so no measurable perf delta from the parent commit. bypass-github-export-checks unrelated failure Test Plan: Re-running the original D104669063 test suite plus the new small-D + high-M_src regression added in this diff: ``` buck2 test fbcode//mode/opt -c fbcode.enable_gpu_sections=true \ -c fbcode.platform010_cuda_version=12.8 -c fbcode.nvcc_arch=h100a \ fbcode//caffe2/test:test_others_cuda -- \ --regex 'test_index_add_fast_path|test_index_add_excluded_dtypes|test_index_add_smem_stage_alignment_regression' ``` Expected: pass on all parametrized variants (fp32 / fp64 / half / bf16 across 3 shapes x 2 index dtypes for `test_index_add_fast_path`; complex64 / complex128 / bool for `test_index_add_excluded_dtypes`; fp32 / bf16 for the new regression). `test_index_add_smem_stage_alignment_regression` specifically reproduces the SEV-class shape (D=8, M_src = sm * 64 + 256 so every CTA enters stage 1) and asserts numerical equality against a CPU reference. Without PR pytorch#184554 in the same build, this test crashes with `cudaErrorMisalignedAddress`; with the parent commit present, it passes cleanly. No regressions in existing `index_add` tests. Check that issues gone in https://www.internalfb.com/mlhub/pipelines/runs/mast/fire-albertchen-train-f1110230424?job_attempt=1&version=0&tab=summary https://www.internalfb.com/mlhub/pipelines/runs/mast/fire-albertchen-train-mast-UDD-2026-06-27-3d-f958b44a?job_attempt=1&version=0&tab=summary&env=PRODUCTION https://www.internalfb.com/mlhub/pipelines/runs/mast/mvai-training-online-2115904614?version=0&env=PRODUCTION Differential Revision: D111254885 Pull Request resolved: pytorch#189506 Approved by: https://github.com/jeanschmidt
…84824) (pytorch#189506) Summary: Second reland of the `index_add -> scatter_add` delegation. This reland sits on top of D110978969 ([native] Move scatter-add N-dim to dynamic, pytorch#188820), which moves the scatter_add CuTeDSL override's compile-cache key for the inner dimension to dynamic, so a single compile serves all N sizes instead of recompiling per application (dtype and contig/non-contig still recompile). With D110978969 landed, the issue behind the most recent revert of this diff is resolved, so the delegation is re-applied here unchanged. Adopts the vectorized scatter_add(dim=0) kernel from D104346887 / PR pytorch#182675 as a fast path for `index_add_` on CUDA. `index_add_(0, idx, src)` is mathematically equivalent to `self.scatter_add_(0, idx.unsqueeze(-1).expand_as(src), src)` when `alpha == 1`, so we delegate so scatter_add's own TMA/vectorized eligibility check + dispatch is the single source of truth. Eligibility (all required to enter the fast path): - `dim == 0` - `alpha == 1` - dtype supported by scatter_add (excludes complex + bool) - `index.dim() <= 1` and contiguous, `numIndex > 0` - scatter_add gates internally per-dtype: TMA sm_90+; vec-scatter sm_60+/sm_70+/sm_90+ for fp32/fp16/bf16 - CUDA 12.8+ at compile time Outside the eligible regime, falls through to the existing `indexFunc{Small,Large}Index` dispatch (untouched). ## Benchmarks Kernel-side perf is unchanged from D104669063 (the delegation forwards to the same scatter_add kernel, now with PR pytorch#184554's smem padding). See D104669063 summary for full B200 and H100 benchmark tables. Highlights: - Real workloads: B200 4.52x (bf16) / 2.74x (fp32); H100 2.97x (bf16) / 1.42x (fp32). - bf16 sweeps up to 7.40x on B200; zipf high-contention is neutral on both arches (atomic-contention-bound, not bandwidth-bound). PR pytorch#184554's stage-stride padding is a one-extra-smem-byte change in the worst case (chunk_bytes already padded for chunk_bytes >= 128), so no measurable perf delta from the parent commit. bypass-github-export-checks unrelated failure Test Plan: Re-running the original D104669063 test suite plus the new small-D + high-M_src regression added in this diff: ``` buck2 test fbcode//mode/opt -c fbcode.enable_gpu_sections=true \ -c fbcode.platform010_cuda_version=12.8 -c fbcode.nvcc_arch=h100a \ fbcode//caffe2/test:test_others_cuda -- \ --regex 'test_index_add_fast_path|test_index_add_excluded_dtypes|test_index_add_smem_stage_alignment_regression' ``` Expected: pass on all parametrized variants (fp32 / fp64 / half / bf16 across 3 shapes x 2 index dtypes for `test_index_add_fast_path`; complex64 / complex128 / bool for `test_index_add_excluded_dtypes`; fp32 / bf16 for the new regression). `test_index_add_smem_stage_alignment_regression` specifically reproduces the SEV-class shape (D=8, M_src = sm * 64 + 256 so every CTA enters stage 1) and asserts numerical equality against a CPU reference. Without PR pytorch#184554 in the same build, this test crashes with `cudaErrorMisalignedAddress`; with the parent commit present, it passes cleanly. No regressions in existing `index_add` tests. Check that issues gone in https://www.internalfb.com/mlhub/pipelines/runs/mast/fire-albertchen-train-f1110230424?job_attempt=1&version=0&tab=summary https://www.internalfb.com/mlhub/pipelines/runs/mast/fire-albertchen-train-mast-UDD-2026-06-27-3d-f958b44a?job_attempt=1&version=0&tab=summary&env=PRODUCTION https://www.internalfb.com/mlhub/pipelines/runs/mast/mvai-training-online-2115904614?version=0&env=PRODUCTION Differential Revision: D111254885 Pull Request resolved: pytorch#189506 Approved by: https://github.com/jeanschmidt
…84824) (pytorch#189506) Summary: Second reland of the `index_add -> scatter_add` delegation. This reland sits on top of D110978969 ([native] Move scatter-add N-dim to dynamic, pytorch#188820), which moves the scatter_add CuTeDSL override's compile-cache key for the inner dimension to dynamic, so a single compile serves all N sizes instead of recompiling per application (dtype and contig/non-contig still recompile). With D110978969 landed, the issue behind the most recent revert of this diff is resolved, so the delegation is re-applied here unchanged. Adopts the vectorized scatter_add(dim=0) kernel from D104346887 / PR pytorch#182675 as a fast path for `index_add_` on CUDA. `index_add_(0, idx, src)` is mathematically equivalent to `self.scatter_add_(0, idx.unsqueeze(-1).expand_as(src), src)` when `alpha == 1`, so we delegate so scatter_add's own TMA/vectorized eligibility check + dispatch is the single source of truth. Eligibility (all required to enter the fast path): - `dim == 0` - `alpha == 1` - dtype supported by scatter_add (excludes complex + bool) - `index.dim() <= 1` and contiguous, `numIndex > 0` - scatter_add gates internally per-dtype: TMA sm_90+; vec-scatter sm_60+/sm_70+/sm_90+ for fp32/fp16/bf16 - CUDA 12.8+ at compile time Outside the eligible regime, falls through to the existing `indexFunc{Small,Large}Index` dispatch (untouched). ## Benchmarks Kernel-side perf is unchanged from D104669063 (the delegation forwards to the same scatter_add kernel, now with PR pytorch#184554's smem padding). See D104669063 summary for full B200 and H100 benchmark tables. Highlights: - Real workloads: B200 4.52x (bf16) / 2.74x (fp32); H100 2.97x (bf16) / 1.42x (fp32). - bf16 sweeps up to 7.40x on B200; zipf high-contention is neutral on both arches (atomic-contention-bound, not bandwidth-bound). PR pytorch#184554's stage-stride padding is a one-extra-smem-byte change in the worst case (chunk_bytes already padded for chunk_bytes >= 128), so no measurable perf delta from the parent commit. bypass-github-export-checks unrelated failure Test Plan: Re-running the original D104669063 test suite plus the new small-D + high-M_src regression added in this diff: ``` buck2 test fbcode//mode/opt -c fbcode.enable_gpu_sections=true \ -c fbcode.platform010_cuda_version=12.8 -c fbcode.nvcc_arch=h100a \ fbcode//caffe2/test:test_others_cuda -- \ --regex 'test_index_add_fast_path|test_index_add_excluded_dtypes|test_index_add_smem_stage_alignment_regression' ``` Expected: pass on all parametrized variants (fp32 / fp64 / half / bf16 across 3 shapes x 2 index dtypes for `test_index_add_fast_path`; complex64 / complex128 / bool for `test_index_add_excluded_dtypes`; fp32 / bf16 for the new regression). `test_index_add_smem_stage_alignment_regression` specifically reproduces the SEV-class shape (D=8, M_src = sm * 64 + 256 so every CTA enters stage 1) and asserts numerical equality against a CPU reference. Without PR pytorch#184554 in the same build, this test crashes with `cudaErrorMisalignedAddress`; with the parent commit present, it passes cleanly. No regressions in existing `index_add` tests. Check that issues gone in https://www.internalfb.com/mlhub/pipelines/runs/mast/fire-albertchen-train-f1110230424?job_attempt=1&version=0&tab=summary https://www.internalfb.com/mlhub/pipelines/runs/mast/fire-albertchen-train-mast-UDD-2026-06-27-3d-f958b44a?job_attempt=1&version=0&tab=summary&env=PRODUCTION https://www.internalfb.com/mlhub/pipelines/runs/mast/mvai-training-online-2115904614?version=0&env=PRODUCTION Differential Revision: D111254885 Pull Request resolved: pytorch#189506 Approved by: https://github.com/jeanschmidt
## Vectorized scatter_add with TMA bulk reduce on sm_90+ ### Summary Add a fast path for `scatter_add` on dim=0 when self, src are contiguous and index is expanded (same eligibility as the existing `vectorized_gather` fast path, with roles of self/src swapped). On sm_90+ (Hopper/Blackwell), uses `cp.reduce.async.bulk` to offload the entire accumulation to the TMA unit, avoiding the serial `atomicAdd` stall that limits both the existing `scatter_add` and `index_add` under contention. The kernel uses warp-per-slice scheduling, TMA loads (`cp.async.bulk.shared::cta.global`), double-buffered shared memory with chunking for arbitrary D, and mbarrier-based completion tracking. On pre-sm_90 NVIDIA, falls back to a vectorized scatter_add kernel using `ld_vec<16>` + per-element `atomicAdd` with warp-per-slice packing. ROCm is excluded (has its own optimized warp-level atomic coalescing on gfx942/gfx950). Also fixes a precedence bug in the existing `fast_gather_kernel_eligible` where `static_cast<size_t>(iter.strides(1)[1] == 0)` had the comparison inside the cast. ### Benchmarks (GB200, sm_100) **High contention** (D103765236 scenario: 7.77M indices, 3.89M targeting one row, 1.72M output rows): | D | scatter_add (this PR) | index_add (baseline) | speedup | |---|----------------------|---------------------|---------| | 128 f32 | 18.4 ms | 84.0 ms | 4.6x | | 128 bf16 | 17.5 ms | 83.1 ms | 4.7x | | 1024 f32 | 40.6 ms | 170.6 ms | 4.2x | | 1024 bf16 | 36.7 ms | 165.5 ms | 4.5x | **Uniform** (500K random indices, 100K output rows): | D | scatter_add (this PR) | index_add (baseline) | speedup | |---|----------------------|---------------------|---------| | 128 f32 | 136 us | 265 us | 2.0x | | 128 bf16 | 131 us | 201 us | 1.5x | | 1024 f32 | 927 us | 2068 us | 2.2x | | 1024 bf16 | 450 us | 1549 us | 3.4x | Supported types: float32, float64, float16, bfloat16. `cp.reduce.async.bulk.add` does not support float min/max, so scatter_reduce with min/max/prod is unaffected. ### Test plan - [ ] Correctness verified against reference `scatter_add` for all supported dtypes and D values - [ ] Benchmarked high contention and uniform workloads across D=128..1024, f32/bf16 - [ ] Pre-sm_90 fallback verified to compile and dispatch correctly (vectorized kernel with atomicAdd) - [ ] ROCm excluded from fast path to preserve existing warp-level atomic coalescing Authored with Claude. Pull Request resolved: pytorch#182675 Approved by: https://github.com/drisspg
…ors (pytorch#175760)" (pytorch#182693) (pytorch#182693) Summary: D94314062 introduced a VecSize=4 fast path in indexFuncLargeIndex that amortizes divmod and index lookup by having each thread process consecutive elements. On uniform-random workloads this gives a ~1.8-2.0x speedup. However, when the index distribution is heavy-tailed (e.g. zipf, or skewed where a few hot rows receive millions of writes), the fast path issues 4 atomicAdds back-to-back from the same warp into consecutive cache lines of the same destination row. The L2 atomic queue cannot drain between the unrolled rounds, and the resulting serialization causes a 4.7x slowdown on fp32 zipf inputs (and ~2x on bf16). Measured on a B200 with dst=[1.72M,128] and nIdx=7.77M: {F1989310065} Proposal https://fb.workplace.com/groups/482605989533128/permalink/1656067795520269/ exhibits highly skewed behavior and saw a regression with the diffs We back the current implementation out temporarily and will be following the approach of pytorch#182675 instead and address the contention problem Test Plan: CI Reviewed By: yjhao Differential Revision: D104098792 Pull Request resolved: pytorch#182693 Approved by: https://github.com/drisspg
…h#182675)" This reverts commit fee4fd3. Reverted pytorch#182675 on behalf of https://github.com/ngimel due to internal build failure ([comment](pytorch#182675 (comment)))
## Vectorized scatter_add with TMA bulk reduce on sm_90+ ### Summary Add a fast path for `scatter_add` on dim=0 when self, src are contiguous and index is expanded (same eligibility as the existing `vectorized_gather` fast path, with roles of self/src swapped). On sm_90+ (Hopper/Blackwell), uses `cp.reduce.async.bulk` to offload the entire accumulation to the TMA unit, avoiding the serial `atomicAdd` stall that limits both the existing `scatter_add` and `index_add` under contention. The kernel uses warp-per-slice scheduling, TMA loads (`cp.async.bulk.shared::cta.global`), double-buffered shared memory with chunking for arbitrary D, and mbarrier-based completion tracking. On pre-sm_90 NVIDIA, falls back to a vectorized scatter_add kernel using `ld_vec<16>` + per-element `atomicAdd` with warp-per-slice packing. ROCm is excluded (has its own optimized warp-level atomic coalescing on gfx942/gfx950). Also fixes a precedence bug in the existing `fast_gather_kernel_eligible` where `static_cast<size_t>(iter.strides(1)[1] == 0)` had the comparison inside the cast. ### Benchmarks (GB200, sm_100) **High contention** (D103765236 scenario: 7.77M indices, 3.89M targeting one row, 1.72M output rows): | D | scatter_add (this PR) | index_add (baseline) | speedup | |---|----------------------|---------------------|---------| | 128 f32 | 18.4 ms | 84.0 ms | 4.6x | | 128 bf16 | 17.5 ms | 83.1 ms | 4.7x | | 1024 f32 | 40.6 ms | 170.6 ms | 4.2x | | 1024 bf16 | 36.7 ms | 165.5 ms | 4.5x | **Uniform** (500K random indices, 100K output rows): | D | scatter_add (this PR) | index_add (baseline) | speedup | |---|----------------------|---------------------|---------| | 128 f32 | 136 us | 265 us | 2.0x | | 128 bf16 | 131 us | 201 us | 1.5x | | 1024 f32 | 927 us | 2068 us | 2.2x | | 1024 bf16 | 450 us | 1549 us | 3.4x | Supported types: float32, float64, float16, bfloat16. `cp.reduce.async.bulk.add` does not support float min/max, so scatter_reduce with min/max/prod is unaffected. ### Test plan - [ ] Correctness verified against reference `scatter_add` for all supported dtypes and D values - [ ] Benchmarked high contention and uniform workloads across D=128..1024, f32/bf16 - [ ] Pre-sm_90 fallback verified to compile and dispatch correctly (vectorized kernel with atomicAdd) - [ ] ROCm excluded from fast path to preserve existing warp-level atomic coalescing Authored with Claude. Pull Request resolved: pytorch#182675 Approved by: https://github.com/drisspg
Vectorized scatter_add with TMA bulk reduce on sm_90+
Summary
Add a fast path for
scatter_addon dim=0 when self, src are contiguous and index is expanded (same eligibility as the existingvectorized_gatherfast path, with roles of self/src swapped).On sm_90+ (Hopper/Blackwell), uses
cp.reduce.async.bulkto offload the entire accumulation to the TMA unit, avoiding the serialatomicAddstall that limits both the existingscatter_addandindex_addunder contention. The kernel uses warp-per-slice scheduling, TMA loads (cp.async.bulk.shared::cta.global), double-buffered shared memory with chunking for arbitrary D, and mbarrier-based completion tracking.On pre-sm_90 NVIDIA, falls back to a vectorized scatter_add kernel using
ld_vec<16>+ per-elementatomicAddwith warp-per-slice packing. ROCm is excluded (has its own optimized warp-level atomic coalescing on gfx942/gfx950).Also fixes a precedence bug in the existing
fast_gather_kernel_eligiblewherestatic_cast<size_t>(iter.strides(1)[1] == 0)had the comparison inside the cast.Benchmarks (GB200, sm_100)
High contention (D103765236 scenario: 7.77M indices, 3.89M targeting one row, 1.72M output rows):
Uniform (500K random indices, 100K output rows):
Supported types: float32, float64, float16, bfloat16.
cp.reduce.async.bulk.adddoes not support float min/max, so scatter_reduce with min/max/prod is unaffected.Test plan
scatter_addfor all supported dtypes and D valuesAuthored with Claude.