Skip to content

[Eager] [Bitwise-Equivalence] Implement an INNER_TREE sum reduction (#182986) - #182986

Closed
njriasan wants to merge 1 commit into
pytorch:mainfrom
njriasan:export-D100024904
Closed

njriasan wants to merge 1 commit into
pytorch:mainfrom
njriasan:export-D100024904

Conversation

@njriasan

@njriasan njriasan commented May 8, 2026 •

Copy link
Copy Markdown
Contributor

Summary:

Adds the triton-style inner tree reduction kernel for sum in the caffe2/ATen CUDA backend, including partitioned launch variants, tests, and the output/input offset handling from D104676317 so TensorIterator output strides and strided outer input rows are preserved.

Test Plan:
arc lint -a fbcode/caffe2/aten/src/ATen/native/cuda/ReduceSumProdKernel.cu xplat/caffe2/aten/src/ATen/native/cuda/ReduceSumProdKernel.cu fbcode/caffe2/test/test_reductions.py xplat/caffe2/test/test_reductions.py

buck2 test fbcode//caffe2/test:torch_cuda_cuda -- TestInnerTreeSum

Differential Revision: D100024904

@pytorch-bot

pytorch-bot Bot commented May 8, 2026 •

Copy link
Copy Markdown

🔗 Helpful Links

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

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

✅ No Failures

As of commit e58930b with merge base 0893b64 (image):
💚 Looks good so far! There are no failures yet. 💚

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

@meta-codesync

meta-codesync Bot commented May 8, 2026

Copy link
Copy Markdown

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

}

static bool use_inner_tree_reduction() {
static const bool disabled = (std::getenv("PYTORCH_SUM_LEGACY") != nullptr);

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This will default to False after CI runs.

@meta-codesync meta-codesync Bot changed the title [Eager] [Bitwise-Equivalence] Implement an INNER_TREE sum reduction [Eager] [Bitwise-Equivalence] Implement an INNER_TREE sum reduction (#182986) May 8, 2026
@njriasan
njriasan force-pushed the export-D100024904 branch from cbe84a5 to 472f445 Compare May 8, 2026 21:23
njriasan added a commit to njriasan/pytorch that referenced this pull request May 8, 2026
…ytorch#182986)

Summary:

Adds support for an inner_tree sum reduction algorithm with multiple launcher strategies. An inner tree reduction is a tree reduction where we reduce values based on their index with all bits match except for i at stage i. For example to reduce 4 elements it will be:

``` 
                 result
                    |
          ┌─────────┴──────────┐                                                                                                                            
          │                    │
      ┌───┴───┐            ┌───┴───┐                                                                                                                       
      │       │            │       │                                                                                                                       
    x[0]   x[1]         x[2]     x[3] 
```

This pattern continues/composes for increasing powers of 2 until reaching the final result. By rewriting the reduction algorithm in this way, we should be able to maintain strong performance but have a reduction algorithm that is much more robust to subtle layout differences or warp count changes, better enabling bitwise equivalence between eager and compile.

In addition, our tree is not fully optimal for large sizes. From experimentation once we exceed 8192  on all data types the perform drops off due to increased register usage/spilling to maintain our tree. This then extends the eager algorithm to do a *persistent reduction* based on kMaxTreeThreshold and then does a linear sum. Any user written or inductor generated kernel can match this pattern and maintain bitwise equivalence.

This then creates 4 kernel launch patterns:
- inner_tree_reduction_kernel: Main kernel to reduce on a whole tree.
- inner_tree_reduction_looped_kernel: Persistent reduction for when N is slightly greater than 8192 so the launch overhead of additional kernels would be too large.
- inner_tree_reduction_multirow_kernel: Variation of inner_tree_reduction_kernel that processes multiple rows as once. Used for small N values.
- two kernel reduction: Persistent reduction using two separate kernels, 1 for each tree of 8192 and one to sum the results. This is helpful because we can assign warps per tree size, including the final reduction and for large N values we don't need to round up to multiple of 8192 (we round the last result to its nearest power of 2).

In the future I expect future optimizations to be largely launch grid oriented and still consist of the same core "tree-reduction" algorithm.

Note: There are still performance cases that need investigating.

Test Plan:
Correctness:

`buck test fbcode//caffe2/test:test_reductions -- TestTritonStyleSum`

Correctness compared to Triton inner-tree:
`buck run fbcode//scripts/njriasan/bitwise_equiv:sum_kernel_benchmark -- accuracy`

Peformance testing:
Command: `CUDA_VISIBLE_DEVICES=5  TRITON_REDUCE_STRATEGY=OLD_EAGER buck run fbcode//scripts/njriasan/bitwise_equiv:sum_kernel_benchmark -- benchmark` and `CUDA_VISIBLE_DEVICES=5 TRITON_REDUCE_STRATEGY=EAGER buck run fbcode//scripts/njriasan/bitwise_equiv:sum_kernel_benchmark -- benchmark`

Results on a H100 server

CSV of results: https://gist.github.com/njriasan/569d01e408032b80f94ae6de84ea4cb1
Claude Analysis: https://gist.github.com/njriasan/bb5e4f2194be1c9ae2e3b90577b1f912

Based on these insights the most important shape to optimize next is the M=1 case, probably needing num_splits. 

High-level graph without nuance about how important each combination is or overall time.

 {F1989532624}

Differential Revision: D100024904
@meta-codesync meta-codesync Bot changed the title [Eager] [Bitwise-Equivalence] Implement an INNER_TREE sum reduction (#182986) [Eager] [Bitwise-Equivalence] Implement an INNER_TREE sum reduction May 22, 2026
@njriasan
njriasan force-pushed the export-D100024904 branch from 472f445 to a7f7150 Compare May 22, 2026 13:20
@jansel

jansel commented May 22, 2026

Copy link
Copy Markdown
Contributor

@claude explain those CI failures, are they related?

@claude

claude Bot commented May 22, 2026 •

Copy link
Copy Markdown

Claude finished @jansel's task in 1m 43s —— View job


CI Failure Analysis

  • Examine the lint failure in torch/csrc/cuda/Module.cpp
  • Examine the ROCm/HIP build failure (constexpr error)
  • Examine the ONNX test failure
  • Determine if failures are related

TL;DR: Two of the three failures are caused by this PR. The ONNX failure is unrelated.

1. Lint failure (lintrunner-clang-partial) — Related to this PR

The lint job flags torch/csrc/cuda/Module.cpp. This PR adds a new function THCPModule_getInnerTreeThreshold (line 263) and a new #include <ATen/native/ReduceOps.h>. The clang-partial lint likely fires on the new code (possibly include ordering, missing static keyword, or a clang-tidy diagnostic). The existing THCPModule_getCompiledVersion right below follows the same pattern, so this may be a pre-existing style issue that the partial lint now surfaces because the new code touches nearby lines.

2. ROCm/HIP build failure — Related to this PR

ReduceSumProdKernel.hip:358:17: error: constexpr variable 'warp_load_elements' must be initialized by a constant expression

This is the key failure. At line 356 of ReduceSumProdKernel.cu:

constexpr int warp_load_elements = C10_WARP_SIZE * vec_size;

On ROCm (HIP), C10_WARP_SIZE expands to C10_WARP_SIZE_INTERNAL() which is a function call (not a compile-time constant) in host code. Specifically, in torch/headeronly/macros/Macros.h lines 359-404:

  • For USE_ROCM + __HIPCC__ in device code: C10_WARP_SIZE_INTERNAL() is constexpr (returns 64 or 32 depending on arch)
  • For USE_ROCM + __HIPCC__ in host code (non-__device__): it calls at::cuda::warp_size() which is a runtime function

Since compute_inner_tree_params is a host function (no __device__ annotation), C10_WARP_SIZE is non-constexpr on ROCm, so constexpr int warp_load_elements = C10_WARP_SIZE * vec_size fails.

Fix: Replace constexpr with const for warp_load_elements, or use C10_WARP_SIZE_LOWER_BOUND (which is always a macro constant) for the host-side launch parameter computation.

3. ONNX test_rotary_embedding_opcheck — Unrelated

This PR doesn't touch any ONNX code. DrCI itself notes "this job did not run on the merge base, so DrCI cannot tell whether the failure is pre-existing." The test is about torch.onnx.ops.rotary_embedding, which has nothing to do with sum reductions.


@jansel jansel left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

fix test failures

@meta-codesync meta-codesync Bot changed the title [Eager] [Bitwise-Equivalence] Implement an INNER_TREE sum reduction [Eager] [Bitwise-Equivalence] Implement an INNER_TREE sum reduction (#182986) Jun 5, 2026
@njriasan
njriasan force-pushed the export-D100024904 branch from a7f7150 to 1252388 Compare June 5, 2026 19:49
njriasan added a commit to njriasan/pytorch that referenced this pull request Jun 5, 2026
…ytorch#182986)

Summary:

Adds the triton-style inner tree reduction kernel for sum in the caffe2/ATen CUDA backend, including partitioned launch variants, tests, and the output/input offset handling from D104676317 so TensorIterator output strides and strided outer input rows are preserved.

Test Plan:
arc lint -a fbcode/caffe2/aten/src/ATen/native/cuda/ReduceSumProdKernel.cu xplat/caffe2/aten/src/ATen/native/cuda/ReduceSumProdKernel.cu fbcode/caffe2/test/test_reductions.py xplat/caffe2/test/test_reductions.py

buck2 test fbcode//caffe2/test:torch_cuda_cuda -- TestInnerTreeSum

Differential Revision: D100024904
@jansel

jansel commented Jun 5, 2026

Copy link
Copy Markdown
Contributor

@claude explain those CI failures, are they related?

@claude

claude Bot commented Jun 5, 2026 •

Copy link
Copy Markdown

Claude finished @jansel's task in 1m 31s —— View job


CI Failure Analysis

  • Examine the lint failure in torch/csrc/cuda/Module.cpp
  • Examine the ROCm/HIP build failure (constexpr error)
  • Determine if failures are related to this PR

Yes, both failures are caused by this PR. They are independent issues (one lint, one compile error) but both stem from code added in this commit.

1. ROCm/HIP Build Failure — constexpr error

ReduceSumProdKernel.hip:358:17: error: constexpr variable 'warp_load_elements'
must be initialized by a constant expression

Root cause: At ReduceSumProdKernel.cu:356:

constexpr int warp_load_elements = C10_WARP_SIZE * vec_size;

On ROCm, C10_WARP_SIZE expands to C10_WARP_SIZE_INTERNAL() which is a runtime function call in host code (it calls at::cuda::warp_size()). See torch/headeronly/macros/Macros.h:364-365:

static __host__ inline int C10_WARP_SIZE_INTERNAL() {
  return at::cuda::warp_size();
}

Only in __device__ code (non-SPIRV) is it constexpr. Since compute_inner_tree_params is a host-only template function, this fails on ROCm.

Fix options:

  1. Replace constexpr with const for warp_load_elements (and the downstream constexpr on line 361/394 that also depends on compile-time constants)
  2. Use C10_WARP_SIZE_LOWER_BOUND (always a macro constant #define) for the host-side launch parameter computation — this is the intended replacement per the comments in Macros.h:350-353

Option 2 is more correct since compute_inner_tree_params uses these values for compile-time dispatch decisions (template parameters, switch cases). Using C10_WARP_SIZE_LOWER_BOUND (32) would give correct but potentially sub-optimal launch params on gfx9 (warp=64) hardware.

2. Lint Failure — torch/csrc/cuda/Module.cpp

The lintrunner-clang-partial job flags the new code in Module.cpp. This PR adds:

  • A new #include <ATen/native/ReduceOps.h> (line 6)
  • A new function THCPModule_getInnerTreeThreshold (line 263)

The lint error is likely a clang-format issue with the function definition style — the new function uses a multi-line signature format:

PyObject* THCPModule_getInnerTreeThreshold(
    PyObject* self,
    PyObject* noargs) {

while adjacent functions (e.g., THCPModule_getCompiledVersion at line 269) use single-line:

PyObject* THCPModule_getCompiledVersion(PyObject* self, PyObject* noargs) {

The exact lint diagnostic isn't fully quoted in the bot comment, but it's specific to code added by this PR.

Summary

Failure Related? Severity
ROCm/HIP constexpr error Yes — caused by this PR Build-breaking on ROCm
Lint torch/csrc/cuda/Module.cpp Yes — caused by this PR Lint warning

@njriasan
njriasan force-pushed the export-D100024904 branch from 1252388 to 8fe1983 Compare June 8, 2026 14:44
njriasan added a commit to njriasan/pytorch that referenced this pull request Jun 8, 2026
…ytorch#182986)

Summary:

Adds the triton-style inner tree reduction kernel for sum in the caffe2/ATen CUDA backend, including partitioned launch variants, tests, and the output/input offset handling from D104676317 so TensorIterator output strides and strided outer input rows are preserved.

Test Plan:
arc lint -a fbcode/caffe2/aten/src/ATen/native/cuda/ReduceSumProdKernel.cu xplat/caffe2/aten/src/ATen/native/cuda/ReduceSumProdKernel.cu fbcode/caffe2/test/test_reductions.py xplat/caffe2/test/test_reductions.py

buck2 test fbcode//caffe2/test:torch_cuda_cuda -- TestInnerTreeSum

Differential Revision: D100024904
njriasan added a commit to njriasan/pytorch that referenced this pull request Jun 8, 2026
…ytorch#182986)

Summary:

Adds the triton-style inner tree reduction kernel for sum in the caffe2/ATen CUDA backend, including partitioned launch variants, tests, and the output/input offset handling from D104676317 so TensorIterator output strides and strided outer input rows are preserved.

Test Plan:
arc lint -a fbcode/caffe2/aten/src/ATen/native/cuda/ReduceSumProdKernel.cu xplat/caffe2/aten/src/ATen/native/cuda/ReduceSumProdKernel.cu fbcode/caffe2/test/test_reductions.py xplat/caffe2/test/test_reductions.py

buck2 test fbcode//caffe2/test:torch_cuda_cuda -- TestInnerTreeSum

Differential Revision: D100024904
@njriasan
njriasan force-pushed the export-D100024904 branch from 8fe1983 to 04e14aa Compare June 8, 2026 14:44
@albanD
albanD requested a review from jansel June 29, 2026 18:56
@albanD
albanD dismissed jansel’s stale review June 29, 2026 18:56

Approval from an old version

@albanD
albanD removed request for PaulZhang12 and albanD June 29, 2026 18:56
@njriasan
njriasan requested review from eellison and ngimel June 29, 2026 20:07
@njriasan

Copy link
Copy Markdown
Contributor Author

@eellison @jansel @ngimel This is moved to CuteDSL and working now. The only remaining feedback to apply should be the decision to reduce "Compile-cache pressure". Other than the startup cost of hitting a new path with an initial compilation, can this have side-effects on other kernels (e.g. a max cache side) or will this be isolated behind the flag.

I will turn the flag off by default now that I have confirmed CI is working.

@slayton58

Copy link
Copy Markdown
Contributor

@claude inspect the cuteDSL kernel code in this PR and suggest areas where existing cuteDSL abstractions and techniques could be used - pay special attention to vectorized loads / stores

@slayton58

Copy link
Copy Markdown
Contributor

I would pay special attention to the host-side overhead of this override, especially with the 2-kernel versions of the code - it can easily make DSL code noticeably slower end-to-end even if the underlying kernel is faster.

I do also have a prototype implementation of all reduction operators in aten, with work in progress on pointwise -- it might be worth comparing notes to see if there's some common ground / kernels we can use.

@claude

claude Bot commented Jun 30, 2026 •

Copy link
Copy Markdown

Claude finished @slayton58's task in 2m 57s —— View job


CuTeDSL abstraction review — focus on vectorized loads/stores

I read both kernel modules (inner_tree_kernel.py, cutedsl_impl.py) and cross-referenced the CuteDSL helpers vendored in torch/_vendor/quack/ (copy_utils.py, reduce.py, reduction_base.py, utils.py) to ground these against abstractions that actually exist in this tree.

The kernels are a careful, deliberately literal port of the CUDA originals, and the bitwise-equivalence constraint legitimately forces some hand-rolling (see "what should stay hand-rolled" below). But the load path is fully scalar today and is the one place where existing abstractions would help without touching reduction order.


🔴 The biggest gap: loads are scalar, not vectorized

_load_vec_dyn (inner_tree_kernel.py:251-276) and _load_vec_static (:242-248) issue vec_size separate scalar loads with a per-element branch:

for i in cutlass.range_constexpr(vec_size):
    off = base + Int32(i)
    v = zero
    if off < Int32(N):
        v = acc(mIn[row, off])      # one scalar LDG per element
    vals.append(v)

The reduced dim is contiguous (the predicate enforces es_in[0] == 1) and vec_size = 16 // itemsize is exactly a 128-bit group by construction (_vec_size, :94). This is the textbook case for a single vectorized LD.E.128, and the repo already has the machinery:

  • copy_utils.tiled_copy_2d(dtype, threads_per_row=_WARP_SIZE, num_threads, num_copy_elems=vec_size) (copy_utils.py:150) builds a TV-tiled copy whose num_copy_bits = vec_size * dtype.width → 128-bit vectorized loads, and partitions the whole warp's lane×vec footprint in one shot. This is precisely what ReductionBase._get_tiled_copy (reduction_base.py:42-50) uses for row reductions — the closest existing analog to this kernel.
  • Or, more lightweight: recast the contiguous row slice to a vector-of-vec_size view (cute.recast_tensor / cute.tiled_divide) and cute.autovec_copy it into an rmem fragment. copy_utils.contiguous(src) / load_s2r(src) (copy_utils.py:72-83) already wrap cute.autovec_copy into a freshly-allocated rmem tensor for exactly this.

Why this is bitwise-safe: vectorizing the load changes only the memory transaction width — the register values handed to the reduction tree are identical to the scalar path. The accumulation DAG (_inner_tree_reduce / _streaming_push / _warp_butterfly) is untouched, so the bitwise contract holds. The win is memory throughput (1 transaction vs vec_size), which for a memory-bound reduction is the whole game. Explore this →


🟠 Per-element bounds checks → vector predication

The if off < Int32(N) guard runs vec_size times per group. With a vectorized load this collapses to a single predicate per vector keyed on the group's base column, which is exactly what copy_utils.predicate_k (copy_utils.py:169-182) builds and utils.fill_oob (utils.py:174-191) consumes — predicate the copy and fill OOB lanes with zero (the additive identity you already rely on). Combined with cute.make_identity_tensor + thr_copy.partition_S, the manual base = warp_start + load*wle + lane*vec_size index arithmetic (:371, :469) becomes the TV partition's job rather than hand-computed Int32 math.

Important alignment caveat: a 128-bit load requires each row's base to be 16-byte aligned. The inner stride is 1, but the outer row stride (in_row_stride from _geometry, cutedsl_impl.py:174-187) is arbitrary, so row r's start can be misaligned even when row 0 is aligned. A vectorized path therefore needs either (a) a predicate-side guard that declines (falls back to ATen) when in_row_stride * itemsize % 16 != 0, or (b) a narrower vector / scalar-tail fallback for the ragged last group. The current scalar loads sidestep alignment entirely, so this is the real cost of the change — worth gating in _base_cond_ok/_int32_indexing_safe rather than discovering it at runtime.


🟡 Two-kernel accumulate: the partials read is also scalar

_make_two_accum (inner_tree_kernel.py:520-527) sums a row's partials one scalar at a time:

s = mPartials[base]
for b in cutlass.range(1, num_batches):   # runtime loop
    s = s + mPartials[base + b]

The partials for a row are contiguous (base = row * num_batches), so the reads could be vectorized via autovec_copy into a fragment even though the accumulation must stay linear (matches the CUDA order) and num_batches is intentionally a runtime loop. Lower value than the main load path (this is the finalize step, and the linear-order constraint limits how much you can restructure), but it's the same scalar-load pattern.


✅ What should stay hand-rolled (don't "fix" these)

  • _warp_butterfly (:230-239) — the docstring is right: cute.arch.warp_reduction / cute.TensorSSA.reduce use descending shuffle offsets, which is a bitwise-different summation order. The ASCENDING hand-roll is load-bearing for the bitwise contract. Same reasoning blocks dropping in quack.reduce.row_reduce / block_reduce (reduce.py:14-123) for the cross-warp combine (:380-390), even though that smem-buffer + barrier + cross-warp pattern is structurally identical to what warp_writes reimplements — the combine itself goes through _warp_butterfly for the same order reason. Worth a one-line comment at the warp_writes block pointing at block_reduce and noting why it can't be reused, so the next reader doesn't try.
  • _inner_tree_reduce (:201-211) — the in-vec tree order (vec_size >= 4) must match the CUDA tree; TensorSSA.reduce(ADD) would pick the DSL's own order. Keep it. (Only the vec_size < 4 linear in-vec case is order-equivalent to frag.load().reduce(ADD), but it's not worth special-casing.)
  • Scalar mOut[row] stores (:301, :397, :527) — one output per row/warp; there's nothing to vectorize on the store side here, so copy_utils.store* wouldn't buy anything.

Net

The reduction/shuffle hand-rolling is justified by the bitwise goal and should stay. The clear, bitwise-neutral win is vectorizing the gmem load in _load_vec_dyn/_load_vec_static via cute.autovec_copy/tiled_copy_2d (with vector predication replacing the per-element branch), which the vendored quack helpers already support and ReductionBase already uses for row reductions. The main thing that makes it non-trivial is per-row alignment of the outer stride — that needs a predicate-side guard or a tail fallback, not a runtime surprise.
• branch export-D100024904

@slayton58

Copy link
Copy Markdown
Contributor

claude suggestions look reasonable to me - I don't remember seeing benchmarks, but aten's reductions are pretty well optimized and you'll need heavy vectorization to be competitive

@njriasan
njriasan force-pushed the export-D100024904 branch from 6bdf433 to fd91224 Compare June 30, 2026 04:55
njriasan added a commit to njriasan/pytorch that referenced this pull request Jun 30, 2026
…ytorch#182986)

Summary:

Adds the triton-style inner tree reduction kernel for sum in the caffe2/ATen CUDA backend, including partitioned launch variants, tests, and the output/input offset handling from D104676317 so TensorIterator output strides and strided outer input rows are preserved.

Test Plan:
arc lint -a fbcode/caffe2/aten/src/ATen/native/cuda/ReduceSumProdKernel.cu xplat/caffe2/aten/src/ATen/native/cuda/ReduceSumProdKernel.cu fbcode/caffe2/test/test_reductions.py xplat/caffe2/test/test_reductions.py

buck2 test fbcode//caffe2/test:torch_cuda_cuda -- TestInnerTreeSum

Differential Revision: D100024904
@eellison
eellison removed their request for review July 14, 2026 19:32
@njriasan
njriasan force-pushed the export-D100024904 branch from fd91224 to 04d64ef Compare July 28, 2026 05:14
njriasan added a commit to njriasan/pytorch that referenced this pull request Jul 28, 2026
…ytorch#182986)

Summary:

Adds the triton-style inner tree reduction kernel for sum in the caffe2/ATen CUDA backend, including partitioned launch variants, tests, and the output/input offset handling from D104676317 so TensorIterator output strides and strided outer input rows are preserved.

Test Plan:
arc lint -a fbcode/caffe2/aten/src/ATen/native/cuda/ReduceSumProdKernel.cu xplat/caffe2/aten/src/ATen/native/cuda/ReduceSumProdKernel.cu fbcode/caffe2/test/test_reductions.py xplat/caffe2/test/test_reductions.py

buck2 test fbcode//caffe2/test:torch_cuda_cuda -- TestInnerTreeSum

Differential Revision: D100024904
@njriasan
njriasan force-pushed the export-D100024904 branch from 04d64ef to 9dd1544 Compare July 28, 2026 05:17
njriasan added a commit to njriasan/pytorch that referenced this pull request Jul 28, 2026
…ytorch#182986)

Summary:

Adds the triton-style inner tree reduction kernel for sum in the caffe2/ATen CUDA backend, including partitioned launch variants, tests, and the output/input offset handling from D104676317 so TensorIterator output strides and strided outer input rows are preserved.

Test Plan:
arc lint -a fbcode/caffe2/aten/src/ATen/native/cuda/ReduceSumProdKernel.cu xplat/caffe2/aten/src/ATen/native/cuda/ReduceSumProdKernel.cu fbcode/caffe2/test/test_reductions.py xplat/caffe2/test/test_reductions.py

buck2 test fbcode//caffe2/test:torch_cuda_cuda -- TestInnerTreeSum

Differential Revision: D100024904
@njriasan
njriasan force-pushed the export-D100024904 branch from 9dd1544 to bec7d6d Compare July 29, 2026 18:46
@njriasan

njriasan commented Aug 7, 2026

Copy link
Copy Markdown
Contributor Author

Here is the associated data from Karthick's benchmark on a GB200. I constructed two benchmarks. One where I just ran the kernel as is, shown below:

strict_numerics_row_reduction_gbps_vs_n

And one where I took the same kernels and implemented Cudagraphs supported (with a circular buffer on repeated measurements to avoid excessive cache hits).

strict_numerics_row_reduction_cudagraph_gbps_vs_n

Based on this result I think there are 3 real issues:

  • Kernel launch overhead appears to be much greater with the CuteDSL version.
  • Large M appears to be a regression at all N.
  • Large N appears to be a regression for all M.

I believe at least the last 2 are possible to resolve based on prior experiments/optimization stacks, but I think they should be a followup since this will not be enabled by default.

…ytorch#182986)

Summary:

Adds the triton-style inner tree reduction kernel for sum in the caffe2/ATen CUDA backend, including partitioned launch variants, tests, and the output/input offset handling from D104676317 so TensorIterator output strides and strided outer input rows are preserved.

Test Plan:
arc lint -a fbcode/caffe2/aten/src/ATen/native/cuda/ReduceSumProdKernel.cu xplat/caffe2/aten/src/ATen/native/cuda/ReduceSumProdKernel.cu fbcode/caffe2/test/test_reductions.py xplat/caffe2/test/test_reductions.py

buck2 test fbcode//caffe2/test:torch_cuda_cuda -- TestInnerTreeSum

Differential Revision: D100024904
@njriasan

njriasan commented Aug 7, 2026

Copy link
Copy Markdown
Contributor Author

@pytorchbot merge

@pytorchmergebot

Copy link
Copy Markdown
Collaborator

Merge failed

Reason: This PR has internal changes and must be landed via Phabricator! Please try reimporting/rexporting the PR!

Details for Dev Infra team Raised by workflow job

@njriasan

njriasan commented Aug 7, 2026

Copy link
Copy Markdown
Contributor Author

@pytorchbot merge

1 similar comment
@njriasan

njriasan commented Aug 7, 2026

Copy link
Copy Markdown
Contributor Author

@pytorchbot merge

@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

The merge job was canceled or timed out. This most often happen if two merge requests were issued for the same PR, or if merge job was waiting for more than 6 hours for tests to finish. In later case, please do not hesitate to reissue the merge command
For more information see pytorch-bot wiki.

@njriasan

njriasan commented Aug 8, 2026

Copy link
Copy Markdown
Contributor Author

@pytorchbot merge

@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

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 Merged meta-exported topic: not user facing topic category

Projects

None yet

Development

Successfully merging this pull request may close these issues.

7 participants