Skip to content

[scatter_add] Reject misaligned data_ptr / row stride in CuTeDSL override cond - #184257

Closed
AlbertDachiChen wants to merge 2 commits into
pytorch:mainfrom
AlbertDachiChen:export-D105569971
Closed

AlbertDachiChen wants to merge 2 commits into
pytorch:mainfrom
AlbertDachiChen:export-D105569971

Conversation

@AlbertDachiChen

@AlbertDachiChen AlbertDachiChen commented May 18, 2026 •

Copy link
Copy Markdown
Contributor

Summary:
The CuTeDSL scatter_add override at torch/_native/ops/scatter_add/ (added in D105049595, reverted in D105339314, re-landed in D105407754) currently accepts inputs whose effective data_ptr() or outer row stride is not 16-byte aligned. Both override paths require 16B alignment of the global memory operand:

  • TMA path: cp.reduce.async.bulk requires 16B alignment of the gmem operand by PTX ISA.
  • vec-scatter path: cute.autovec_copy emits LDG.128 with _VEC_BYTES == 16, which also requires 16B alignment of the source address.

When a caller hands the override a misaligned tensor (commonly an autograd-produced gradient buffer whose storage_offset * itemsize puts data_ptr() off a 16B boundary), the cond accepts, the kernel launches, and the call faults with cudaErrorMisalignedAddress. This mirrors the contract enforced by fast_scatter_add_kernel_eligible<16> in caffe2/aten/src/ATen/native/cuda/IndexKernelUtils.h for the native C++ kernel.

This diff adds an _alignment_contract_ok helper and wires it into both _is_tma_supported and _is_vec_scatter_supported. When the contract isn't satisfied, the cond returns False, the eager_router falls through to aten's native scatter_add (which has its own predicate plus safe fallback to vectorized_scatter_add_kernel_launch / indexFunc{Small,Large}Index), and the call completes correctly.

Additionally, _make_cond's requires_out branch now calls _alignment_contract_ok(out, src) directly. The .out impl runs the kernel on out, not self (see _make_impls.out_impl), so out may have different alignment from self; without this check, a misaligned out with aligned self would slip past the cond and fault in the kernel -- the same SEV-class crash this diff prevents, just on the .out variant. (Caught by Devmate AI reviewer.)

Test Plan:
Added three new tests:

  • TestScatterAddOverrideConds.test_rejects_data_ptr_not_16_aligned: builds tensors with storage_offset chosen so data_ptr() % 16 != 0 (allocate one extra element and slice from index 1). Asserts both cond paths reject for misaligned self, misaligned src, and both misaligned.
  • TestScatterAddOverrideConds.test_rejects_row_stride_not_16_aligned: builds a self with outer row stride of (D+1) * elem_size, asserts both cond paths reject.
  • TestScatterAddOverrideCorrectness.test_misaligned_data_ptr_falls_through_to_aten (parametrized over which=self/src/both): end-to-end test that calls torch.scatter_add with misaligned inputs and verifies the result matches a naive CPU reference — proving the fall-through path works correctly.

Before this change the three cond tests fail (cond returns True for all misaligned cases) and the end-to-end test crashes with cudaErrorMisalignedAddress. After this change all three pass.

Run:

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_scatter_gather_ops_cuda -- \
    --regex 'TestScatterAddOverride'

All existing override tests continue to pass; only the new alignment-rejection tests change cond behavior, and only for inputs that would have faulted at kernel time.

Following Devmate reviewer feedback: also added TestScatterAddOverrideConds.test_out_cond_rejects_misaligned_out. The .out variant runs the kernel on out, not self (see _make_impls.out_impl), so the requires_out branch of _make_cond now calls _alignment_contract_ok(out, src) in addition to the existing support_check(self, dim, index, src). Without this, a misaligned out with aligned self would slip past the cond and fault in the kernel -- exactly the SEV-class crash this diff prevents, just on the .out variant.

Reviewed By: slayton58

Differential Revision: D105569971

@pytorch-bot

pytorch-bot Bot commented May 18, 2026

Copy link
Copy Markdown

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

@pytorch-bot

pytorch-bot Bot commented May 18, 2026

Copy link
Copy Markdown

This PR needs a release notes: label

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

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

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

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

@pytorch-bot

pytorch-bot Bot commented May 18, 2026 •

Copy link
Copy Markdown

🔗 Helpful Links

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

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:

❌ 1 New Failure, 1 Unrelated Failure

As of commit dfc6eff with merge base 59a25c4 (image):

NEW FAILURE - The following job has failed:

UNSTABLE - The following job is marked as unstable, possibly due to flakiness on trunk:

  • pull / linux-jammy-rocm-py3.10 / build-osdc (gh) (PyTorch OSDC job marked as unstable)
    [OSDC] Step script exited with code 1. This is a script/workflow error, not an infrastructure issue. Check the step logs above for the actual failure.

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

@meta-codesync

meta-codesync Bot commented May 18, 2026

Copy link
Copy Markdown

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

@pytorch-bot pytorch-bot Bot added the ciflow/trunk Trigger trunk jobs on your pull request label May 18, 2026
…ride cond

Summary:
The CuTeDSL `scatter_add` override at `torch/_native/ops/scatter_add/` (added in D105049595, reverted in D105339314, re-landed in D105407754) currently accepts inputs whose effective `data_ptr()` or outer row stride is not 16-byte aligned. Both override paths require 16B alignment of the global memory operand:

- TMA path: `cp.reduce.async.bulk` requires 16B alignment of the `gmem` operand by PTX ISA.
- vec-scatter path: `cute.autovec_copy` emits `LDG.128` with `_VEC_BYTES == 16`, which also requires 16B alignment of the source address.

When a caller hands the override a misaligned tensor (commonly an autograd-produced gradient buffer whose `storage_offset * itemsize` puts `data_ptr()` off a 16B boundary), the cond accepts, the kernel launches, and the call faults with `cudaErrorMisalignedAddress`. This mirrors the contract enforced by `fast_scatter_add_kernel_eligible<16>` in `caffe2/aten/src/ATen/native/cuda/IndexKernelUtils.h` for the native C++ kernel.

This diff adds an `_alignment_contract_ok` helper and wires it into both `_is_tma_supported` and `_is_vec_scatter_supported`. When the contract isn't satisfied, the cond returns False, the `eager_router` falls through to aten's native `scatter_add` (which has its own predicate plus safe fallback to `vectorized_scatter_add_kernel_launch` / `indexFunc{Small,Large}Index`), and the call completes correctly.

Additionally, `_make_cond`'s `requires_out` branch now calls `_alignment_contract_ok(out, src)` directly. The `.out` impl runs the kernel on `out`, not `self` (see `_make_impls.out_impl`), so `out` may have different alignment from `self`; without this check, a misaligned `out` with aligned `self` would slip past the cond and fault in the kernel -- the same SEV-class crash this diff prevents, just on the `.out` variant. (Caught by Devmate AI reviewer.)

Test Plan:
Added three new tests:

- `TestScatterAddOverrideConds.test_rejects_data_ptr_not_16_aligned`: builds tensors with `storage_offset` chosen so `data_ptr() % 16 != 0` (allocate one extra element and slice from index 1). Asserts both cond paths reject for misaligned self, misaligned src, and both misaligned.
- `TestScatterAddOverrideConds.test_rejects_row_stride_not_16_aligned`: builds a self with outer row stride of `(D+1) * elem_size`, asserts both cond paths reject.
- `TestScatterAddOverrideCorrectness.test_misaligned_data_ptr_falls_through_to_aten` (parametrized over which=self/src/both): end-to-end test that calls `torch.scatter_add` with misaligned inputs and verifies the result matches a naive CPU reference — proving the fall-through path works correctly.

Before this change the three cond tests fail (cond returns True for all misaligned cases) and the end-to-end test crashes with `cudaErrorMisalignedAddress`. After this change all three pass.

Run:
```
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_scatter_gather_ops_cuda -- \
    --regex 'TestScatterAddOverride'
```

All existing override tests continue to pass; only the new alignment-rejection tests change cond behavior, and only for inputs that would have faulted at kernel time.



Following Devmate reviewer feedback: also added `TestScatterAddOverrideConds.test_out_cond_rejects_misaligned_out`. The `.out` variant runs the kernel on `out`, not `self` (see `_make_impls.out_impl`), so the `requires_out` branch of `_make_cond` now calls `_alignment_contract_ok(out, src)` in addition to the existing `support_check(self, dim, index, src)`. Without this, a misaligned `out` with aligned `self` would slip past the cond and fault in the kernel -- exactly the SEV-class crash this diff prevents, just on the `.out` variant.

Reviewed By: slayton58

Differential Revision: D105569971
@pytorch-bot

pytorch-bot Bot commented May 18, 2026 •

Copy link
Copy Markdown

Workflows were awaiting approval. CI has now been triggered for the ciflow labels on this PR.

@slayton58

Copy link
Copy Markdown
Contributor

@pytorchbot lint

@pytorchmergebot

Copy link
Copy Markdown
Collaborator

Successfully applied lint patches in https://github.com/pytorch/pytorch/actions/runs/26163166320. Please pull locally before pushing more changes.

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
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
pytorchmergebot pushed 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]>
Pull Request resolved: #184554
Approved by: https://github.com/ngimel
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
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
@github-actions

Copy link
Copy Markdown
Contributor

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

@github-actions github-actions Bot added the Stale label Jul 19, 2026
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
@github-actions github-actions Bot closed this Aug 18, 2026
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 fb-exported meta-exported Stale

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants