Skip to content

[Reland] Port D104346887/PR 182675 for index_add fast path (#184824) - #184824

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

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

Conversation

@AlbertDachiChen

@AlbertDachiChen AlbertDachiChen commented May 21, 2026 •

Copy link
Copy Markdown
Contributor

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

@pytorch-bot

pytorch-bot Bot commented May 21, 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 added the ci-no-td Do not run TD on this PR label May 21, 2026
@pytorch-bot

pytorch-bot Bot commented May 21, 2026 •

Copy link
Copy Markdown

🔗 Helpful Links

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

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:

❌ 3 New Failures, 22 Unrelated Failures

As of commit c0df5c0 with merge base 7659779 (image):

NEW FAILURES - The following jobs have failed:

  • pull / linux-jammy-aarch64-py3.10 / build-osdc (gh)
    Executing the custom container implementation failed. Please contact your self hosted runner administrator.

    AI verdict:

    The failure is a self-hosted runner infrastructure error ("Executing the custom container implementation failed. Please contact your self hosted runner administrator.") unrelated to the code change. Recent trunk commits on the same job all pass successfully.

    Full reasoning on HUD →

  • trunk / win-vs2022-cpu-py3 / build (gh)
    Process completed with exit code 1.

    AI verdict:

    The build failed during pip dependency installation ("ERROR: To modify pip") before reaching compilation. The commit only changes CUDA kernel code and a test file, which cannot cause pip installation failures.

    Full reasoning on HUD →

  • trunk / win-vs2022-cuda13.0-py3 / build (gh)
    Process completed with exit code 1.

    AI verdict:

    The build failed during pip dependency installation ("ERROR: To modify pip") before any source compilation occurred. The commit only changes CUDA C++ code and Python tests, which weren't reached.

    Full reasoning on HUD →

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 21, 2026

Copy link
Copy Markdown

@AlbertDachiChen has exported this pull request. If you are a Meta employee, you can view the originating Diff in 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
@meta-codesync meta-codesync Bot changed the title [Reland] Port D104346887/PR 182675 for index_add fast path [Reland] Port D104346887/PR 182675 for index_add fast path (#184824) May 22, 2026
@AlbertDachiChen
AlbertDachiChen force-pushed the export-D105959759 branch 2 times, most recently from f15e941 to c0df5c0 Compare May 22, 2026 14:24
AlbertDachiChen added a commit to AlbertDachiChen/pytorch that referenced this pull request May 22, 2026
…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
@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)

@pytorch-bot

pytorch-bot Bot commented May 22, 2026

Copy link
Copy Markdown

This PR needs to be approved by an authorized maintainer before merge.

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

@pytorch-bot

pytorch-bot Bot commented May 22, 2026

Copy link
Copy Markdown

This PR needs to be approved by an authorized maintainer before merge.

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

@pytorch-bot

pytorch-bot Bot commented May 22, 2026

Copy link
Copy Markdown

This PR needs to be approved by an authorized maintainer before merge.

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

@pytorch-bot

pytorch-bot Bot commented May 22, 2026

Copy link
Copy Markdown

This PR needs to be approved by an authorized maintainer before merge.

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

@pytorch-bot

pytorch-bot Bot commented May 22, 2026

Copy link
Copy Markdown

This PR needs to be approved by an authorized maintainer before merge.

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

@pytorch-bot

pytorch-bot Bot commented May 22, 2026

Copy link
Copy Markdown

This PR needs to be approved by an authorized maintainer before merge.

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

@pytorch-bot

pytorch-bot Bot commented May 23, 2026

Copy link
Copy Markdown

This PR needs to be approved by an authorized maintainer before merge.

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

@pytorch-bot

pytorch-bot Bot commented May 23, 2026

Copy link
Copy Markdown

This PR needs to be approved by an authorized maintainer before merge.

@jeanschmidt

Copy link
Copy Markdown
Contributor

@pytorchmergebot merge -f "merged internally"

@pytorchmergebot

Copy link
Copy Markdown
Collaborator

Merge started

Your change will be merged immediately since you used the force (-f) flag, bypassing any CI checks (ETA: 1-5 minutes). Please use -f as last resort and instead consider -i/--ignore-current to continue the merge ignoring current failures. This will allow currently pending tests to finish and report signal before the merge.

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

@meta-codesync

meta-codesync Bot commented Jun 24, 2026

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.

@pytorch-bot
pytorch-bot Bot dismissed wdvr’s stale review June 24, 2026 15:59

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

atalman added a commit that referenced this pull request Jun 25, 2026
…dd fast path (#184824)" (#188196)

Revert "[Reland] Port D104346887/PR 182675 for index_add fast path (#184824) (#184824)"

This reverts commit 9e051b3.

Reverted #184824 on behalf of https://github.com/meta-codesync due to Diff reverted internally ([comment](#184824 (comment)))

(cherry picked from commit eaa0ca8)

Co-authored-by: PyTorch MergeBot <[email protected]>
pytorchmergebot pushed a commit that referenced this pull request Jul 14, 2026
…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
gplutop7 pushed a commit to gplutop7/pytorch that referenced this pull request Jul 15, 2026
…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
vishalgoyal316 pushed a commit to vishalgoyal316/pytorch that referenced this pull request Jul 16, 2026
…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
DamJanusz pushed a commit to DamJanusz/pytorch that referenced this pull request Jul 21, 2026
…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
youlituao pushed a commit to youlituao/pytorch that referenced this pull request Jul 28, 2026
…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
aws-kingrj pushed a commit to amazon-contributing/upstream-to-pytorch that referenced this pull request Jul 29, 2026
…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
aws-kingrj pushed a commit to amazon-contributing/upstream-to-pytorch that referenced this pull request Jul 29, 2026
aws-kingrj pushed a commit to amazon-contributing/upstream-to-pytorch that referenced this pull request Jul 29, 2026
…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
@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 Aug 23, 2026
@github-actions github-actions Bot closed this Sep 22, 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