Skip to content

[scatter_add] Fix two alignment crashes in CuTeDSL override - #184554

Closed
slayton58 wants to merge 2 commits into
gh/slayton58/92/basefrom
gh/slayton58/92/head
Closed

slayton58 wants to merge 2 commits into
gh/slayton58/92/basefrom
gh/slayton58/92/head

Conversation

@slayton58

@slayton58 slayton58 commented May 20, 2026 •

Copy link
Copy Markdown
Contributor

Stack from ghstack (oldest at bottom):

Subsumes #184257.

Two latent crashes on shapes the cond accepted but the kernel couldn't
safely run:

  1. Gmem alignment. The cond didn't check data_ptr() or outer row
    stride alignment. Adds _alignment_contract_ok covering:

    • src.data_ptr(): 16B (LDG.128 / TMA load).
    • self.data_ptr() (kernel destination): 16B for TMA
      (cp.reduce.async.bulk gmem operand); 4B for vec-scatter
      (natural alignment of the fp32 atomicAdd / f16x2 / bf16x2 paired
      atomics). The 4B path lets fp32 storage_offset slices stay on
      the override fast path instead of falling through to aten.
    • row stride: 16B for both paths so each row of src starts on a
      16B boundary for the LDG.128 read.
      Wired into both _is_*_supported checks and the out-variant
      branch of _make_cond so a misaligned out (the kernel's actual
      destination on the .out impl) is also caught.
  2. 128B smem alignment in the TMA kernel. The 2-stage pipeline buffer
    was a contiguous (chunk_elems, 2), so stage 1 started at offset
    chunk_bytes. cp.async.bulk requires 128B-aligned smem
    destinations, so any chunk_bytes not a multiple of 128 (e.g. fp32
    D=8 -> 32 B, D=36 -> 144 B) produced a misaligned stage 1 and
    faulted as soon as M_src > grid_x. Pads the smem column stride up
    to 128 B.

Tests cover cond rejection (data_ptr / row stride / out),
fall-through correctness on misaligned inputs, the 4B vec-scatter
relaxation for fp32, and a stage-1 regression over D in {8, 16} for
fp32/bf16 with M_src = sm*64 + 256.

Authored with assistance from Claude.

Co-authored-by: Albert Chen [email protected]
Co-authored-by: @AlbertDachiChen [email protected]

[ghstack-poisoned]
@slayton58
slayton58 requested a review from drisspg as a code owner May 20, 2026 14:44
@pytorch-bot

pytorch-bot Bot commented May 20, 2026 •

Copy link
Copy Markdown

🔗 Helpful Links

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

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:

✅ No Failures

As of commit 02d89e0 with merge base 59a25c4 (image):
💚 Looks good so far! There are no failures yet. 💚

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

@slayton58 slayton58 added the topic: not user facing topic category label May 20, 2026
slayton58 added a commit that referenced this pull request May 20, 2026
Subsumes #184257.

Two latent crashes on shapes the cond accepted but the kernel couldn't
safely run:

1. Gmem alignment. The cond didn't check `data_ptr()` or outer row
   stride alignment. Adds `_alignment_contract_ok` covering:
     - `src.data_ptr()`: 16B (LDG.128 / TMA load).
     - `self.data_ptr()` (kernel destination): 16B for TMA
       (`cp.reduce.async.bulk` gmem operand); 4B for vec-scatter
       (natural alignment of the fp32 atomicAdd / f16x2 / bf16x2 paired
       atomics). The 4B path lets fp32 storage_offset slices stay on
       the override fast path instead of falling through to aten.
     - row stride: 16B for both paths so each row of `src` starts on a
       16B boundary for the LDG.128 read.
   Wired into both `_is_*_supported` checks and the `out`-variant
   branch of `_make_cond` so a misaligned `out` (the kernel's actual
   destination on the `.out` impl) is also caught.

2. 128B smem alignment in the TMA kernel. The 2-stage pipeline buffer
   was a contiguous `(chunk_elems, 2)`, so stage 1 started at offset
   `chunk_bytes`. `cp.async.bulk` requires 128B-aligned smem
   destinations, so any chunk_bytes not a multiple of 128 (e.g. fp32
   D=8 -> 32 B, D=36 -> 144 B) produced a misaligned stage 1 and
   faulted as soon as M_src > grid_x. Pads the smem column stride up
   to 128 B.

Tests cover cond rejection (data_ptr / row stride / `out`),
fall-through correctness on misaligned inputs, the 4B vec-scatter
relaxation for fp32, and a stage-1 regression over D in {8, 16} for
fp32/bf16 with M_src = sm*64 + 256.

Authored with assistance from Claude.

Co-authored-by: Albert Chen <[email protected]>
Co-authored-by: AlbertDachiChen <[email protected]>
ghstack-source-id: f6af973
Pull-Request: #184554
[ghstack-poisoned]
slayton58 added a commit that referenced this pull request May 20, 2026
Subsumes #184257.

Two latent crashes on shapes the cond accepted but the kernel couldn't
safely run:

1. Gmem alignment. The cond didn't check `data_ptr()` or outer row
   stride alignment. Adds `_alignment_contract_ok` covering:
     - `src.data_ptr()`: 16B (LDG.128 / TMA load).
     - `self.data_ptr()` (kernel destination): 16B for TMA
       (`cp.reduce.async.bulk` gmem operand); 4B for vec-scatter
       (natural alignment of the fp32 atomicAdd / f16x2 / bf16x2 paired
       atomics). The 4B path lets fp32 storage_offset slices stay on
       the override fast path instead of falling through to aten.
     - row stride: 16B for both paths so each row of `src` starts on a
       16B boundary for the LDG.128 read.
   Wired into both `_is_*_supported` checks and the `out`-variant
   branch of `_make_cond` so a misaligned `out` (the kernel's actual
   destination on the `.out` impl) is also caught.

2. 128B smem alignment in the TMA kernel. The 2-stage pipeline buffer
   was a contiguous `(chunk_elems, 2)`, so stage 1 started at offset
   `chunk_bytes`. `cp.async.bulk` requires 128B-aligned smem
   destinations, so any chunk_bytes not a multiple of 128 (e.g. fp32
   D=8 -> 32 B, D=36 -> 144 B) produced a misaligned stage 1 and
   faulted as soon as M_src > grid_x. Pads the smem column stride up
   to 128 B.

Tests cover cond rejection (data_ptr / row stride / `out`),
fall-through correctness on misaligned inputs, the 4B vec-scatter
relaxation for fp32, and a stage-1 regression over D in {8, 16} for
fp32/bf16 with M_src = sm*64 + 256.

Authored with assistance from Claude.

Co-authored-by: Albert Chen <[email protected]>
Co-authored-by: AlbertDachiChen <[email protected]>
ghstack-source-id: df6ff48
Pull-Request: #184554
@slayton58

Copy link
Copy Markdown
Contributor Author

@pytorchbot merge

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

Copy link
Copy Markdown
Collaborator

Merge started

Your change will be merged once all checks pass (ETA 0-4 Hours).

Learn more about merging in the wiki.

Questions? Feedback? Please reach out to the PyTorch DevX Team

Advanced Debugging
Check the merge workflow status
here

@pytorchmergebot

Copy link
Copy Markdown
Collaborator

Merge failed

Reason: 1 mandatory check(s) failed. The first few are:

Dig deeper by viewing the failures on hud

Details for Dev Infra team Raised by workflow job

Failing merge rule: Core Maintainers

@slayton58

Copy link
Copy Markdown
Contributor Author

@pytorchbot merge -i 'Good signal, waiting forever for osdc+aarch64'

@pytorch-bot

pytorch-bot Bot commented May 20, 2026

Copy link
Copy Markdown

❌ 🤖 pytorchbot command failed:

@pytorchbot: error: unrecognized arguments: Good signal, waiting forever for osdc+aarch64

usage: @pytorchbot [-h]
                   
                   {merge,revert,rebase,label,drci,lint,fix-lint,apply-lint,cherry-pick}
                   ...

Try @pytorchbot --help for more info.

@slayton58

Copy link
Copy Markdown
Contributor Author

@pytorchbot merge -i

@pytorchmergebot

Copy link
Copy Markdown
Collaborator

Merge started

Your change will be merged while ignoring the following 1 checks: 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

pytorchmergebot pushed a commit to weishi-deng/pytorch that referenced this pull request May 21, 2026
…184554)

Subsumes pytorch#184257.

Two latent crashes on shapes the cond accepted but the kernel couldn't
safely run:

1. Gmem alignment. The cond didn't check `data_ptr()` or outer row
   stride alignment. Adds `_alignment_contract_ok` covering:
     - `src.data_ptr()`: 16B (LDG.128 / TMA load).
     - `self.data_ptr()` (kernel destination): 16B for TMA
       (`cp.reduce.async.bulk` gmem operand); 4B for vec-scatter
       (natural alignment of the fp32 atomicAdd / f16x2 / bf16x2 paired
       atomics). The 4B path lets fp32 storage_offset slices stay on
       the override fast path instead of falling through to aten.
     - row stride: 16B for both paths so each row of `src` starts on a
       16B boundary for the LDG.128 read.
   Wired into both `_is_*_supported` checks and the `out`-variant
   branch of `_make_cond` so a misaligned `out` (the kernel's actual
   destination on the `.out` impl) is also caught.

2. 128B smem alignment in the TMA kernel. The 2-stage pipeline buffer
   was a contiguous `(chunk_elems, 2)`, so stage 1 started at offset
   `chunk_bytes`. `cp.async.bulk` requires 128B-aligned smem
   destinations, so any chunk_bytes not a multiple of 128 (e.g. fp32
   D=8 -> 32 B, D=36 -> 144 B) produced a misaligned stage 1 and
   faulted as soon as M_src > grid_x. Pads the smem column stride up
   to 128 B.

Tests cover cond rejection (data_ptr / row stride / `out`),
fall-through correctness on misaligned inputs, the 4B vec-scatter
relaxation for fp32, and a stage-1 regression over D in {8, 16} for
fp32/bf16 with M_src = sm*64 + 256.

Authored with assistance from Claude.

Co-authored-by: Albert Chen <[email protected]>
Co-authored-by: @AlbertDachiChen <[email protected]>
Pull Request resolved: pytorch#184554
Approved by: https://github.com/ngimel
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
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
pytorchmergebot pushed a commit that referenced this pull request May 26, 2026
…184824)

Summary:

Reland of D104669063, which was reverted following SEV S664741. The underlying TMA smem stage-alignment bug in scatter_add's CuTeDSL override has since been fixed in PR #184554 (sibling commit in this stack); this diff re-applies the `index_add -> scatter_add` delegation unchanged from the original, with one minor follow-up (see "Follow-ups from D104669063 review" below).

Adopts the vectorized scatter_add(dim=0) kernel from D104346887 / PR #182675 as a fast path for `index_add_` on CUDA. `index_add_(0, idx, src)` is mathematically equivalent to `self.scatter_add_(0, idx.unsqueeze(-1).expand_as(src), src)` when `alpha == 1`, so we delegate so scatter_add's own TMA/vectorized eligibility check + dispatch is the single source of truth.

Eligibility (all required to enter the fast path):
- `dim == 0`
- `alpha == 1`
- dtype supported by scatter_add (excludes complex + bool)
- `index.dim() <= 1` and contiguous, `numIndex > 0`
- scatter_add gates internally per-dtype: TMA sm_90+; vec-scatter sm_60+/sm_70+/sm_90+ for fp32/fp16/bf16
- CUDA 12.8+ at compile time

Outside the eligible regime, falls through to the existing `indexFunc{Small,Large}Index` dispatch (untouched).

## Why this reland is safe

The original revert was triggered by an IFR MTML embedding-backward job. Diagnostic logs surfaced a latent bug in scatter_add's CuTeDSL TMA path: the 2-stage pipeline buffer is laid out column-major in smem, so stage 1 sits at offset `chunk_bytes` from stage 0's 128B-aligned base. `cp.async.bulk` requires 128B-aligned smem destinations. When `chunk_bytes` is not a multiple of 128 (e.g. fp32 D=8 -> chunk_bytes=32, or fp32 D=36 -> chunk_bytes=144), AND a CTA does more than one iteration (M_src > grid_x cap of sm*64), the kernel writes stage 1 at a misaligned smem address and faults with `cudaErrorMisalignedAddress`.

Prod repro: src shape `(104280, 8)` fp32 stride `(568, 1)`, self shape `(13, 8)`. chunk_bytes = 8 * 4 = 32 (< 128), M_src = 104280 > sm * 64 = 8448 -> fault. Confirmed by a local unit-test reproducer at the exact prod call shape.

PR #184554 (parent of this diff in the stack) fixes the kernel by padding the 2-stage pipeline buffer's stage stride to a multiple of 128 bytes:
```
stage_stride_elems = _round_up(chunk_elems, 128 // elem_bytes)
sBuf = smem.allocate_tensor(
    dtype,
    cute.make_layout((chunk_elems, 2), stride=(1, stage_stride_elems)),
    128,
)
```

With that fix in place, every shape this delegation can produce runs through the TMA fast path correctly. PR #184554 ships kernel-level regression tests (`test_smem_stage_alignment_multi_iter`, parametrized over both `chunk_bytes < 128` and `chunk_bytes in (128, 512) not multiple of 128` cases). This diff adds `test_index_add_smem_stage_alignment_regression` in `test_indexing.py` to pin the same regime through the `index_add` public-API path, so a future refactor of the delegation re-exposing the same shape class is caught here rather than in prod.

## Benchmarks

Kernel-side perf is unchanged from D104669063 (the delegation forwards to the same scatter_add kernel, now with PR #184554's smem padding). See D104669063 summary for full B200 and H100 benchmark tables. Highlights:
- Real workloads: B200 4.52x (bf16) / 2.74x (fp32); H100 2.97x (bf16) / 1.42x (fp32).
- bf16 sweeps up to 7.40x on B200; zipf high-contention is neutral on both arches (atomic-contention-bound, not bandwidth-bound).

PR #184554's stage-stride padding is a one-extra-smem-byte change in the worst case (chunk_bytes already padded for chunk_bytes >= 128), so no measurable perf delta from the parent commit.

Test Plan:
Re-running the original D104669063 test suite plus the new small-D + high-M_src regression added in this diff:

```
buck2 test fbcode//mode/opt -c fbcode.enable_gpu_sections=true \
    -c fbcode.platform010_cuda_version=12.8 -c fbcode.nvcc_arch=h100a \
    fbcode//caffe2/test:test_others_cuda -- \
    --regex 'test_index_add_fast_path|test_index_add_excluded_dtypes|test_index_add_smem_stage_alignment_regression'
```

Expected: pass on all parametrized variants (fp32 / fp64 / half / bf16 across 3 shapes x 2 index dtypes for `test_index_add_fast_path`; complex64 / complex128 / bool for `test_index_add_excluded_dtypes`; fp32 / bf16 for the new regression).

`test_index_add_smem_stage_alignment_regression` specifically reproduces the SEV-class shape (D=8, M_src = sm * 64 + 256 so every CTA enters stage 1) and asserts numerical equality against a CPU reference. Without PR #184554 in the same build, this test crashes with `cudaErrorMisalignedAddress`; with the parent commit present, it passes cleanly.

No regressions in existing `index_add` tests.

https://www.internalfb.com/mlhub/pipelines/runs/mast/mvai-training-online-2122147583-mrs_cog-test-3bd717?job_attempt=0&version=0&tab=logs&env=PRODUCTION

f1085796899

mvai-training-online-2122002363-mrs_cog-test-a767bb

Reviewed By: slayton58

Differential Revision: D105959759

Pull Request resolved: #184824
Approved by: https://github.com/wdvr
@github-actions
github-actions Bot deleted the gh/slayton58/92/head branch June 21, 2026 02:30
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
…184554)

Subsumes pytorch#184257.

Two latent crashes on shapes the cond accepted but the kernel couldn't
safely run:

1. Gmem alignment. The cond didn't check `data_ptr()` or outer row
   stride alignment. Adds `_alignment_contract_ok` covering:
     - `src.data_ptr()`: 16B (LDG.128 / TMA load).
     - `self.data_ptr()` (kernel destination): 16B for TMA
       (`cp.reduce.async.bulk` gmem operand); 4B for vec-scatter
       (natural alignment of the fp32 atomicAdd / f16x2 / bf16x2 paired
       atomics). The 4B path lets fp32 storage_offset slices stay on
       the override fast path instead of falling through to aten.
     - row stride: 16B for both paths so each row of `src` starts on a
       16B boundary for the LDG.128 read.
   Wired into both `_is_*_supported` checks and the `out`-variant
   branch of `_make_cond` so a misaligned `out` (the kernel's actual
   destination on the `.out` impl) is also caught.

2. 128B smem alignment in the TMA kernel. The 2-stage pipeline buffer
   was a contiguous `(chunk_elems, 2)`, so stage 1 started at offset
   `chunk_bytes`. `cp.async.bulk` requires 128B-aligned smem
   destinations, so any chunk_bytes not a multiple of 128 (e.g. fp32
   D=8 -> 32 B, D=36 -> 144 B) produced a misaligned stage 1 and
   faulted as soon as M_src > grid_x. Pads the smem column stride up
   to 128 B.

Tests cover cond rejection (data_ptr / row stride / `out`),
fall-through correctness on misaligned inputs, the 4B vec-scatter
relaxation for fp32, and a stage-1 regression over D in {8, 16} for
fp32/bf16 with M_src = sm*64 + 256.

Authored with assistance from Claude.

Co-authored-by: Albert Chen <[email protected]>
Co-authored-by: @AlbertDachiChen <[email protected]>
Pull Request resolved: pytorch#184554
Approved by: https://github.com/ngimel
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
…184554)

Subsumes pytorch#184257.

Two latent crashes on shapes the cond accepted but the kernel couldn't
safely run:

1. Gmem alignment. The cond didn't check `data_ptr()` or outer row
   stride alignment. Adds `_alignment_contract_ok` covering:
     - `src.data_ptr()`: 16B (LDG.128 / TMA load).
     - `self.data_ptr()` (kernel destination): 16B for TMA
       (`cp.reduce.async.bulk` gmem operand); 4B for vec-scatter
       (natural alignment of the fp32 atomicAdd / f16x2 / bf16x2 paired
       atomics). The 4B path lets fp32 storage_offset slices stay on
       the override fast path instead of falling through to aten.
     - row stride: 16B for both paths so each row of `src` starts on a
       16B boundary for the LDG.128 read.
   Wired into both `_is_*_supported` checks and the `out`-variant
   branch of `_make_cond` so a misaligned `out` (the kernel's actual
   destination on the `.out` impl) is also caught.

2. 128B smem alignment in the TMA kernel. The 2-stage pipeline buffer
   was a contiguous `(chunk_elems, 2)`, so stage 1 started at offset
   `chunk_bytes`. `cp.async.bulk` requires 128B-aligned smem
   destinations, so any chunk_bytes not a multiple of 128 (e.g. fp32
   D=8 -> 32 B, D=36 -> 144 B) produced a misaligned stage 1 and
   faulted as soon as M_src > grid_x. Pads the smem column stride up
   to 128 B.

Tests cover cond rejection (data_ptr / row stride / `out`),
fall-through correctness on misaligned inputs, the 4B vec-scatter
relaxation for fp32, and a stage-1 regression over D in {8, 16} for
fp32/bf16 with M_src = sm*64 + 256.

Authored with assistance from Claude.

Co-authored-by: Albert Chen <[email protected]>
Co-authored-by: @AlbertDachiChen <[email protected]>
Pull Request resolved: pytorch#184554
Approved by: https://github.com/ngimel
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
…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
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

ciflow/trunk Trigger trunk jobs on your pull request Merged topic: not user facing topic category

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants