Skip to content

Port D104346887/PR 182675 for index large select (#183455) - #183455

Closed
AlbertDachiChen wants to merge 1 commit into
pytorch:mainfrom
AlbertDachiChen:export-D104669063
Closed

AlbertDachiChen wants to merge 1 commit into
pytorch:mainfrom
AlbertDachiChen:export-D104669063

Conversation

@AlbertDachiChen

@AlbertDachiChen AlbertDachiChen commented May 12, 2026 •

Copy link
Copy Markdown
Contributor

Summary:

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 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

@pytorch-bot

pytorch-bot Bot commented May 12, 2026

Copy link
Copy Markdown

This appears to be a diff that was exported from phabricator, but the PR author does not have sufficient permissions to run CI. @AlbertDachiChen, please do step 2 of internal wiki to get write access so you do not need to get CI approvals in the future. If you think this is a mistake, please contact the Pytorch Dev Infra team.

@pytorch-bot

pytorch-bot Bot commented May 12, 2026 •

Copy link
Copy Markdown

🔗 Helpful Links

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

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

❗ 1 Active SEVs

There are 1 currently active SEVs. If your PR is affected, please view them below:

✅ You can merge normally! (2 Unrelated Failures)

As of commit fc753f1 with merge base 9cd5f70 (image):

FLAKY - The following jobs failed but were likely due to flakiness present on trunk:

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

@meta-codesync

meta-codesync Bot commented May 12, 2026

Copy link
Copy Markdown

@AlbertDachiChen has exported this pull request. If you are a Meta employee, you can view the originating Diff in D104669063.

@AlbertDachiChen

Copy link
Copy Markdown
Contributor Author

@pytorchbot label "Open Source"

@pytorch-bot

pytorch-bot Bot commented May 12, 2026

Copy link
Copy Markdown

Didn't find following labels among repository labels: Open Source

@eqy
eqy requested a review from liqiangxl May 12, 2026 17:27
@liqiangxl

Copy link
Copy Markdown
Collaborator

Nice work! Just one thought: is it possible to route through scatter_add_ itself? We can avoid duplicating TMA/faster kernel eligible check fast_scatter_add_kernel_eligible and let scatter_add_ selects which version to use. Similar to #180430

@drisspg

drisspg commented May 12, 2026

Copy link
Copy Markdown
Contributor

@claude Please do a deep review focused on subtle correctness bugs and regressions that are easy for human reviewers to miss. Prioritize findings over summary. I dont care about anything that isnt a real bug drop all the noise but that, if you there isnt anything to report just say so with a small comment

@claude

claude Bot commented May 12, 2026 •

Copy link
Copy Markdown

Claude finished @drisspg's task in 6m 18s —— View job


Deep Correctness Review

  • Read changed files and understand the fast path logic
  • Analyze for subtle correctness bugs (argument mapping, alignment invariants, overflow, semantics)
  • Post findings

No correctness bugs found. I checked:

  1. Argument mapping to tma_scatter_add_kernel_launch — The sliceSize → D, selfAddDimSize → self_dim_size, slice_bytes → both stride args all map correctly. The kernel divides stride_bytes / sizeof(scalar_t) to recover element strides, which yields sliceSize — matching the contiguous dim=0 layout.

  2. 16-byte alignment invariant for cp.async.bulk — The get_alignment(slice_bytes) == 16 gate ensures all chunk boundaries produce 16-byte-aligned sizes (since chunk_elems * sizeof(scalar_t) is either 512 or slice_bytes itself, both multiples of 16). Pointer alignment is similarly guaranteed since base ptrs are checked and row strides are multiples of 16.

  3. int overflow in entry_id — The numIndex <= INT_MAX guard means grid_x = ceil_div(INT_MAX, 8) = 268435456, so the max blockIdx.x * 8 + 7 = INT_MAX — exactly at the boundary, no overflow.

  4. Semantic equivalence — index_add_(0, idx, src) with alpha=1 on contiguous tensors is indeed a row-wise scatter-add, which the TMA kernel implements correctly (each warp handles one entry_id, reads idx[entry_id] for dst row, copies the full D-element slice via bulk-reduce-add).

  5. Deterministic mode — The deterministicAlgorithms() early-return at line 1159 happens before the fast path, so non-deterministic TMA atomics are never used in deterministic mode.

  6. Scalar/edge cases — Scalars can't hit the fast path (alignment check on element_size fails for all dtypes). Empty index (numIndex == 0) is excluded by the numIndex > 0 guard and falls through correctly.

The implementation is sound.


Comment thread aten/src/ATen/native/cuda/Indexing.cu Resolved
@meta-codesync meta-codesync Bot changed the title Port D104346887/PR 182675 for index large select Port D104346887/PR 182675 for index large select (#183455) May 12, 2026
AlbertDachiChen added a commit to AlbertDachiChen/pytorch that referenced this pull request May 12, 2026
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}

Differential Revision: D104669063
AlbertDachiChen added a commit to AlbertDachiChen/pytorch that referenced this pull request May 12, 2026
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}

Differential Revision: D104669063
AlbertDachiChen added a commit to AlbertDachiChen/pytorch that referenced this pull request May 12, 2026
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}

Differential Revision: D104669063
AlbertDachiChen added a commit to AlbertDachiChen/pytorch that referenced this pull request May 13, 2026
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}

Differential Revision: D104669063
@AlbertDachiChen

Copy link
Copy Markdown
Contributor Author

Nice work! Just one thought: is it possible to route through scatter_add_ itself? We can avoid duplicating TMA/faster kernel eligible check fast_scatter_add_kernel_eligible and let scatter_add_ selects which version to use. Similar to #180430

Good suggestion and I followed the approach

AlbertDachiChen added a commit to AlbertDachiChen/pytorch that referenced this pull request May 13, 2026
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}

Differential Revision: D104669063
// regresses skewed/high-contention workloads vs indexFunc{Small,Large}Index
// (warp-per-entry scheduling concentrates atomic contention on hot rows).
// Older builds therefore stay on the existing indexFunc dispatch.
if (dim == 0 && alpha.toDouble() == 1.0 && numIndex > 0 &&

@drisspg drisspg May 13, 2026 •

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.

lets use alpah.equal(1) to not error on compelx

import tempfile

import torch
from torch.utils.cpp_extension import load_inline

cpp_source = r"""
#include <c10/core/Scalar.h>
#include <pybind11/pybind11.h>

#include <exception>
#include <string>

std::string check_alpha_predicate() {
  c10::Scalar real_one(1.0);
  c10::Scalar complex_one(c10::complex<double>(1.0, 0.0));
  c10::Scalar complex_nonreal(c10::complex<double>(1.0, 2.0));

  std::string out;
  out += "real_one.equal(1): " + std::to_string(real_one.equal(1)) + "\n";
  out += "complex_one.equal(1): " + std::to_string(complex_one.equal(1)) + "\n";
  out += "complex_nonreal.equal(1): " + std::to_string(complex_nonreal.equal(1)) + "\n";

  try {
    (void)complex_nonreal.toDouble();
    out += "complex_nonreal.toDouble(): succeeded unexpectedly\n";
  } catch (const std::exception& e) {
    out += "complex_nonreal.toDouble(): threw: ";
    out += e.what();
    out += "\n";
  }

  return out;
}

PYBIND11_MODULE(TORCH_EXTENSION_NAME, m) {
  m.def("check_alpha_predicate", &check_alpha_predicate);
}
"""

with tempfile.TemporaryDirectory() as build_dir:
    mod = load_inline(
        name="scalar_alpha_predicate_ext",
        cpp_sources=[cpp_source],
        build_directory=build_dir,
        verbose=True,
    )

    print(f"torch={torch.__version__}")
    print(mod.check_alpha_predicate())

@drisspg

drisspg commented May 13, 2026

Copy link
Copy Markdown
Contributor

Codex brings up; aten/src/ATen/native/cuda/Indexing.cu:1194 — the delegated scatter_add_ path does not support ComplexHalf, while the existing index_add CUDA dispatch explicitly does (AT_DISPATCH...ComplexHalf). On CUDA >= 12.8, complex32/ComplexHalf with dim == 0, contiguous index, and default alpha=1 will now route to scatter_add_ and likely fail dispatch instead of using the existing supported kernel.
Fix: exclude at::ScalarType::ComplexHalf from this fast path, or extend scatter_add_cuda_ support before delegating.

I agree let sjust completely restrict against complex types

@facebook-github-tools

Copy link
Copy Markdown

@pytorchbot merge -i

(Initiating merge automatically since Phabricator Diff has merged, merging with -i because oss signals were bypassed internally)

@pytorchmergebot

Copy link
Copy Markdown
Collaborator

Merge failed

Reason: This PR needs a release notes: label
If your changes are user facing and intended to be a part of release notes, please use a label starting with release notes:.

If not, please add the topic: not user facing label.

To add a label, you can comment to pytorchbot, for example
@pytorchbot label "topic: not user facing"

For more information, see
https://github.com/pytorch/pytorch/wiki/PyTorch-AutoLabel-Bot#why-categorize-for-release-notes-and-how-does-it-work.

Details for Dev Infra team Raised by workflow job

@AlbertDachiChen

Copy link
Copy Markdown
Contributor Author

@pytorchbot label "topic: not user facing"

@pytorch-bot pytorch-bot Bot added the topic: not user facing topic category label May 14, 2026
@facebook-github-tools

Copy link
Copy Markdown

@pytorchbot merge -i

(Initiating merge automatically since Phabricator Diff has merged, merging with -i because oss signals were bypassed internally)

@pytorchmergebot

Copy link
Copy Markdown
Collaborator

Merge started

Your change will be merged while ignoring the following 3 checks: trunk / linux-jammy-rocm-py3.10-mi355 / build, trunk / inductor-build / build, trunk / before-test / llm-retrieval

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

jemitche1 pushed a commit to jemitche1/pytorch that referenced this pull request May 14, 2026
…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
@facebook-github-tools

Copy link
Copy Markdown

@pytorchbot revert -m="Diff reverted internally" -c="ghfirst"

This Pull Request has been reverted by a revert inside Meta. To re-land this change, please open another pull request, assign the same reviewers, fix the CI failures that caused the revert and make sure that the failing CI runs on the PR by applying the proper ciflow label (e.g., ciflow/trunk).)

@pytorchmergebot

Copy link
Copy Markdown
Collaborator

@pytorchbot successfully started a revert job. Check the current status here.
Questions? Feedback? Please reach out to the PyTorch DevX Team

@pytorchmergebot

Copy link
Copy Markdown
Collaborator

@AlbertDachiChen your PR has been successfully reverted.

@pytorchmergebot pytorchmergebot added Reverted ci-no-td Do not run TD on this PR labels May 16, 2026
@pytorch-bot
pytorch-bot Bot dismissed drisspg’s stale review May 16, 2026 04:52

This PR was reopened (likely due to being reverted), so your approval was removed. Please request another review.

@github-actions

Copy link
Copy Markdown
Contributor

Looks like this PR hasn't been updated in a while so we're going to go ahead and mark this as Stale.
Feel free to remove the Stale label if you feel this was a mistake.
If you are unable to remove the Stale label please contact a maintainer in order to do so.
If you want the bot to never mark this PR stale again, add the no-stale label.
Stale pull requests will automatically be closed after 30 days of inactivity.

@github-actions github-actions Bot added the Stale label Jul 15, 2026
gplutop7 pushed a commit to gplutop7/pytorch that referenced this pull request Jul 15, 2026
…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
aws-kingrj pushed a commit to amazon-contributing/upstream-to-pytorch that referenced this pull request Jul 29, 2026
…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
aws-kingrj pushed a commit to amazon-contributing/upstream-to-pytorch that referenced this pull request Jul 29, 2026
@github-actions github-actions Bot closed this Aug 14, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

ci-no-td Do not run TD on this PR ciflow/trunk Trigger trunk jobs on your pull request fb-exported Merged meta-exported Reverted Stale topic: not user facing topic category

Projects

None yet

Development

Successfully merging this pull request may close these issues.

4 participants