Repository navigation
Conversation
PR Status: Approved 🚀Please fix all CI failures and trigger merge by commenting "@pytorchbot merge". ✅ AUTOMATED REVIEW - OUTDATED (earlier commit) - Ready for human review:
Findings (3): Reviewed commit: 🔗 Helpful Links🧪 See artifacts and rendered test results at hud.pytorch.org/pr/202533
Note: Links to docs will display an error until the docs builds have been completed. ✅ You can merge normally! (1 Unrelated Failure)As of commit 2a42f7e with merge base d3eab3c ( NEW FAILURES SUPPRESSED BY AI (non-blocking) - The following job failed, but the AI CI Advisor judged the failure not to be evidence against this change:
This comment was automatically generated by Dr. CI and updates every 15 minutes. |
|
|
@claude review this PR, pay attention to code quality, subtle correctness bugs and breaking existing behacvior, outside of intended fixes. |
|
Claude finished @ngimel's task in 3m 36s —— View job This PR is mostly sound, but I'd request changes for two reasons: it quietly changes PR Review: #202533SummaryFor real floating inputs on CPU with ord 0, 1 and 2, Backward Compatibility
Testing
Code Quality
Performance
RecommendationRequest Changes Blocking: the Not checked: whether |
|
|
@ngimel friendly ping: I pushed the changes requested in the review. Could you take another look and approve the pending CI workflows when you get a chance? Thanks! |
|
Bot is still unhappy |
|
@pytorchbot label "topic: bc breaking" |
|
@egeboy35 if you rebase github bot should become more consistent and not find new nits in already reviewed code |
0cbc21b to
0489e38
Compare
|
@pytorchbot rebase |
|
@pytorchbot started a rebase job onto refs/remotes/origin/viable/strict. Check the current status here |
On CPU, linalg.vector_norm adds |x|^ord into a single accumulator, so in float32 the running total stops growing once it is about 2**24 times larger than the terms: vector_norm(randn(10**8)) comes out 1.1% low, and vector_norm(ones(10**4, 10**4), 1) and vector_norm(..., 0) return 16777216 instead of 1e8. torch.sum does not have this problem because SumKernel.cpp uses cascade summation (pytorch#39516). For ord 0, 1 and 2 and real floating point inputs, the norm and powsum kernels now go through sum()'s cascade_sum, with the per-element function (x != 0, |x| or x * x) applied as each element is loaded. nansum already did this to mask out NaNs, so its load policies become generic ones that take the function as a parameter. cascade_sum adds its partial sums into the output, so half and bfloat16 inputs reduce into a float temporary and are rounded once at the end, as mean() does. The ord=2 last-dim fast paths are removed: cascade_sum is vectorized for inner and outer reductions. cascade_sum does the same float32 additions on NEON, AVX2 and SVE256 (pytorch#197037), so the norms stay identical across them as When the output has one element, TensorIterator::parallel_reduce adds up the per-thread results by running the same loop over them, which would apply the function a second time. cascade_sum adds them up itself in that case. For nansum this means that an inf - inf inside one thread's chunk now gives NaN at any thread count; before, the final pass dropped that NaN, so the result depended on the number of threads. Other values of ord, complex inputs and the CUDA kernels are unchanged. Reductions whose reduced dims cannot be merged into one (e.g. dim=(0, 2) of a 3-d tensor) still add the partial sums of rows one after another, as torch.sum does. I considered compensated (Kahan) summation in the existing NormOps, and accumulating float32 in double. Both add a second summation scheme next to sum()'s and cost more in the inner loop; reusing cascade_sum keeps one scheme for sum, nansum and the norms. Test Plan: test_vector_norm_keeps_small_terms fails before this change and passes after it; test_powsum_reduced_precision_accumulates_in_float covers the half and bfloat16 float temporary. ``` python test/test_linalg.py -k "cpu and (keeps_small_terms or powsum or vector_norm or norm)" python test/test_reductions.py -k "sum and cpu" python test/test_nn.py -k clip_grad python test/test_foreach.py -k "norm and cpu" ``` Authored with an AI assistant (Claude Code). Fixes pytorch#65815 Co-Authored-By: Claude Opus 5.5 <[email protected]>
A reduction to one element with a non-identity Map now always goes through at::parallel_reduce, instead of copying the threading rules of TensorIterator::parallel_reduce. The ord/dtype rule for the cascade path lives in one place (use_cascade_powsum in ReduceOpsUtils.h), and the two float-temporary blocks in LinearAlgebra.cpp become one helper. nansum keeps the NaN from inf + -inf at any thread count, as np.nansum does; test_nansum_keeps_inf_minus_inf checks it at 1 and 4 threads. The norm tests now set the thread count, cover double, and cover the half/bfloat16 float temporary of vector_norm. Test Plan (Linux CPU build, WSL2): ``` python -m pytest test/test_linalg.py -k "keeps_small_terms or reduced_precision_accumulates" python -m pytest test/test_reductions.py -k nansum_keeps_inf python -m pytest test/test_linalg.py -k "norm or powsum" python -m pytest test/test_reductions.py -k "sum or norm" python -m pytest test/test_nn.py -k clip_grad python -m pytest test/test_foreach.py -k norm python -m pytest test/test_ops.py -k "cpu and (vector_norm or nansum or linalg_norm)" lintrunner --take CLANGFORMAT,RUFF,FLAKE8 <changed files> ``` All pass (6 new tests; 43, 876, 13, 61 and 75 related), and lint is clean, except 17 _refs.linalg.norm OpInfo cases that need LAPACK, which this build lacks (svd: LAPACK library not found). Authored with Claude (AI assistant). Co-Authored-By: Claude Opus 5.5 <[email protected]>
For a half or bfloat16 vector_norm or _powsum with a one-element result, cpu_powsum_in_float allocated a float temporary and copied it back, and ord=2 ran a separate sqrt_. The cascade sum's all-reduce branch already keeps the per-thread partial sums in float and writes the output once, so it now writes the half or bfloat16 result directly: cpu_powsum_in_float skips one-element results, and use_cascade_powsum accepts a reduced precision output when it has one element. The ord=2 square root moved into cascade_powsum_kernel, so the one-element branch takes it before rounding. Outputs with more than one element get it from a cpu_kernel pass after the reduction, since SumKernel.cpp can't call Tensor operators. For float inputs with one output element, the root is now taken on the double accumulator instead of the rounded float. The output's fill_ moved below the all-reduce branch, which doesn't read it. test_norm_reduced_precision_all_reduce runs the all-reduce branch for half and bfloat16 at 1 and 4 threads, for vector_norm ord 0, 1 and 2 and _powsum ord 1 and 2. Its sliced input can't be merged into one dim, so each thread's chunk is summed row by row into the float partial; in half or bfloat16 that sum would stall well below the float64 reference. Test Plan: ``` python -m pytest test/test_linalg.py -k "reduced_precision_all_reduce" python -m pytest test/test_linalg.py -k "norm or powsum" python -m pytest test/test_reductions.py -k "sum or norm" lintrunner --take CLANGFORMAT,RUFF,FLAKE8 aten/src/ATen/native/LinearAlgebra.cpp aten/src/ATen/native/ReduceOpsUtils.h aten/src/ATen/native/cpu/ReduceOpsKernel.cpp aten/src/ATen/native/cpu/SumKernel.cpp aten/src/ATen/native/cpu/SumKernel.h test/test_linalg.py ``` At 1 thread, vector_norm of 1000 elements takes 4-5 us per call for bfloat16, float16 and float32 alike in the same build; with the temporary, bfloat16 took about 3 us more than float32. Authored with an AI assistant (Claude Code). Co-Authored-By: Claude Opus 5.5 <[email protected]>
test_norm_reduced_precision_all_reduce counted 2**18 nonzeros for vector_norm ord=0. That is above float16's max of 65504, so for float16 the result and the float64 reference both rounded to inf, and any count from 65520 up would have passed. ord=0 now runs on a copy of the input with one row in 8 left nonzero, so the count is 2**15, finite in float16 and bfloat16, and each of the 4 threads still gets nonzero rows. Test Plan: ``` python -m pytest test/test_linalg.py -k "reduced_precision_all_reduce or reduced_precision_accumulates or keeps_small_terms" lintrunner --take RUFF,FLAKE8,PYFMT test/test_linalg.py ``` Authored with an AI assistant (Claude Code). Co-Authored-By: Claude Opus 5.5 <[email protected]>
Addresses the automated review of 677b552. The test comment said the 4-thread runs split the reduction across threads, but only the dim=None cases go through parallel_reduce; the cases with 2 or 3 outputs are split across their outputs, so each output is still reduced by one thread. Also renames the loop variable in test_norm_reduced_precision_all_reduce that shadowed the outer x. Test Plan: ``` python -m pytest -q test/test_linalg.py -k 'keeps_small_terms or norm_reduced_precision_all_reduce' lintrunner --take RUFF,FLAKE8 test/test_linalg.py ``` Authored with an AI assistant (Claude Code). Co-Authored-By: Claude Opus 5.5 <[email protected]>
Addresses the automated review of cc948a6. The multi-output ord=2 sqrt pass now uses cpu_kernel_vec. For half and bfloat16, the 2-norm runs the powsum kernel into the float temporary and takes the square root in the same pass that rounds it to the result dtype, instead of a separate sqrt pass and a copy. cpu_powsum_in_float now states its condition through use_cascade_powsum (a float temporary is needed when the kernel can write float but not the input dtype), which drops the unused single_output argument and the separate numel() check. test_vector_norm_keeps_small_terms drops double, which accumulated in double on main and so could not fail there, and checks _powsum with ord 1 and 2 next to vector_norm. Test Plan: ``` python -m pytest -q test/test_linalg.py -k "cpu and (vector_norm or powsum or norm_reduced or keeps_small)" python -m pytest -q test/test_reductions.py -k "cpu and (nansum or nanmean)" python -m pytest -q test/test_ops.py -k "TestCommonCPU and (vector_norm or _powsum or normalize)" lintrunner --take CLANGFORMAT,RUFF,FLAKE8 aten/src/ATen/native/LinearAlgebra.cpp aten/src/ATen/native/cpu/SumKernel.cpp test/test_linalg.py ``` Small multi-output ord=2 norms (vector_norm dim=-1 and F.normalize on 32x128 to 4096x64, 1 and 4 threads) against main: float32 is 0.62x to 1.18x, bfloat16 0.70x to 1.71x, the slowest being 1 to 3 us more on the smallest shapes from the float temporary. Authored with an AI assistant (Claude Code). Co-Authored-By: Claude Opus 5.5 <[email protected]>
Addresses the automated review of 0489e38. The comments in SumKernel.h and ReduceOpsUtils.h now say that small terms are kept only while the reduced dims can be merged into one, as in sum(). The multi-element sqrt pass is only compiled for SquareMap. test_vector_norm_special_values runs ord 0, 1 and 2 on nan, inf, -inf, -0.0 and negative inputs long enough for the vectorized maps (67 elements with dim=None, and 67x32 with dim=0) for float, half and bfloat16, and compares exactly with numpy. test_nansum_nan_multithreaded sends a NaN-containing nansum to one element through the per-thread path at 1 and 4 threads for float, double, half and bfloat16. Test Plan: ``` python -m pytest -q test/test_linalg.py -k "cpu and (vector_norm or powsum or norm_reduced)" python -m pytest -q test/test_reductions.py -k "cpu and (nansum or nanmean)" lintrunner --take CLANGFORMAT,RUFF,FLAKE8 aten/src/ATen/native/cpu/SumKernel.cpp aten/src/ATen/native/cpu/SumKernel.h aten/src/ATen/native/ReduceOpsUtils.h test/test_linalg.py test/test_reductions.py ``` The two new tests also pass on main; they add coverage for these paths. Authored with an AI assistant (Claude Code). Co-Authored-By: Claude Opus 5.5 <[email protected]>
nansum is back to main's behavior: its elementwise loop masks a NaN in the accumulator again, and a nansum to one element combines the per-thread results with TensorIterator::parallel_reduce, which masks a NaN partial sum, as before. Only vector_norm and _powsum take the new all-reduce. This drops the nansum and nanmean BC notes; making nansum of inf and -inf independent of the thread count can be a separate change. cascade_powsum_kernel now checks p and the dtypes itself and returns false when it does not apply, so the norm and powsum kernels in ReduceOpsKernel.cpp fall back without repeating the rule, and use_cascade_powsum leaves ReduceOpsUtils.h. LinearAlgebra.cpp only shares cascade_powsum_supports (which p the kernel takes) to decide on the float temporary for half and bfloat16. It rejects _powsum with p == 0, which counts zeros too, and the kernel asserts that next to NonZeroMap. The float temporary of a multi-output half or bfloat16 norm now goes through norm_stub and result.copy_, instead of powsum_stub and at::sqrt_out, which allocated a second float tensor. The square root pass over a multi-element output reuses sqrt_kernel from UnaryOps.h. An alternative was to move the float temporary into the kernel, so that LinearAlgebra.cpp would not change at all. That needs a second reduction iterator and a cast copy inside a TORCH_ASSERT_NO_OPERATORS file, so the temporary stays in LinearAlgebra.cpp, as the review suggested. In the tests, the all-reduce test hard-codes its expected values instead of running the same kernel on double, the nansum test compares with np.nansum, and the dim=0 case of test_vector_norm_keeps_small_terms has 32 columns, so it takes vectorized_outer_sum. Two new tests cover the elementwise loop (a _powsum over a size-1 dim) and _powsum ord 0 with zeros. test_nansum_keeps_inf_minus_inf goes with the nansum change. Test Plan: On a Linux CPU build (g++ 15) of these ATen files on an older main (c3e43dd). In this branch's test_linalg.py, the ROCm-only RDNA3OrLater import, which that tree lacks, was defined as False. ``` python -m pytest test/test_linalg.py -k "cpu and (vector_norm or powsum or norm_reduced or keeps_small or norm)" python -m pytest test/test_reductions.py -k "cpu and (nansum or nanmean or sum)" python -m pytest test/test_nn.py -k "clip_grad or normalize" python -m pytest test/test_foreach.py -k "cpu and norm" python -m pytest test/test_ops.py -k "TestCommonCPU and (vector_norm or _powsum or normalize or nansum or nanmean)" ``` test_linalg: 55 passed. With main's kernel, only test_vector_norm_keeps_small_terms fails. test_reductions: 759 passed and 20 failed, the same 20 (dim_empty and float16 ref_small_input cases) as with main's kernel, because this branch's test file is newer than the build. test_nn, test_foreach and test_ops, from the build's own test files: 14, 60 and 65 passed. clang-format and the Python linters report nothing. A script compared the builds bitwise on 27 inputs (1-D to 3-D, contiguous, sliced, permuted, transposed and expanded, with NaN, inf and -inf or finite, and ones starting with inf, -inf), 4 dtypes and 1 or 4 threads. nansum and sum (432 results) equal main. vector_norm (ord 0, 1, 2, 3 and inf, also with dtype=float) and _powsum (ord 0 to 3), 2484 results, equal the previous commit. Authored with an AI assistant (Claude Code). Co-Authored-By: Claude Opus 5.5 <[email protected]>
The previous commit took nansum back to main's behavior to drop its BC notes, but ngimel had accepted that change in review on Oct 30, since main's result was clearly buggy. It comes back as in f8ebd08: the elementwise loop no longer masks a NaN accumulator, and a nansum to one element takes the all-reduce, so inf and -inf give NaN at any thread count. test_nansum_keeps_inf_minus_inf returns; the review fixes to test_nansum_nan_multithreaded stay. The existing half and bfloat16 tests expect sums that adding the elements one by one in float also gets exactly, so they pass on main too. test_norm_reduced_precision_cascade sums 2**24 + 2**18 zero-stride elements at one thread, to one and two outputs, where main stops at 2**24 (bfloat16 ones) or 2**14 (half 2**-10). The review also asked for timings of float32 norms over short rows, which main reduced with binary_kernel_reduce_lastdim. At one thread, (2**20, 3) and (2**20, 4) with ord=2 and dim=-1 take 5.1 and 5.3 ms here and 6.7 and 7.3 ms on main; at four threads they are as fast or faster. So nothing changes there; the numbers are in the PR description. Test Plan: On a Linux CPU build (g++ 15) of these ATen files on an older main (c3e43dd), with the ROCm-only RDNA3OrLater import of this branch's test_linalg.py defined as False, as before. ``` python -m pytest test/test_linalg.py -k "cpu and (vector_norm or powsum or norm_reduced or keeps_small or norm)" python -m pytest test/test_reductions.py -k "cpu and (nansum or nanmean or sum)" python -m pytest test/test_nn.py -k "clip_grad or normalize" python -m pytest test/test_foreach.py -k "cpu and norm" python -m pytest test/test_ops.py -k "TestCommonCPU and (vector_norm or _powsum or normalize or nansum or nanmean)" ``` test_linalg: 57 passed. With main's kernel, test_norm_reduced_precision_cascade (half and bfloat16) and test_vector_norm_keeps_small_terms fail. test_reductions: 761 passed and 20 failed; with main's kernel the same 20 fail (the test file is newer than the build), plus test_nansum_keeps_inf_minus_inf. test_nn, test_foreach and test_ops, from the build's own test files: 14, 60 and 65 passed. clang-format and the Python linters report nothing. The bitwise comparison script from the previous commit (27 inputs, 4 dtypes, 1 and 4 threads): nansum and sum (432 results) equal f8ebd08; against main, 12 nansum results differ, all at 4 threads, where main gives a finite value and this commit NaN. vector_norm and _powsum (2484 results) equal the previous commit. Authored with an AI assistant (Claude Code). Co-Authored-By: Claude Opus 5.5 <[email protected]>
CI on the previous commit failed test_vector_norm_special_values (float32, ord=2, dim=0) and the torch_np TestNormSingle.test_axis by one ulp. In b767baa, as the automated review suggested, the square root pass after a reduction to several outputs became sqrt_kernel instead of a cpu_kernel_vec with std::sqrt and Vectorized::sqrt. With MKL, sqrt_kernel calls vsSqrt, which is not correctly rounded: on an AVX512 machine, torch.sqrt in the 2.14.1, 2.15.0 and 2026-11-08 nightly CPU wheels differs from np.sqrt for 26092 of the float32 integers 1 to 2**22 at one thread (and for about 620000 in some multi-threaded runs). Main, and this kernel's reduction to one element, use std::sqrt, so these norms could differ from both in the last bit. The pass goes back to f8ebd08's cpu_kernel_vec, with a comment saying why, and UnaryOps.h is no longer included. The Linux build the previous commits were tested on has no MKL, so its sqrt_kernel used Vectorized::sqrt and the tests passed there. Test Plan: On a Linux CPU build (g++ 15, without MKL or LAPACK) of these ATen files on an older main (c3e43dd), with the ROCm-only RDNA3OrLater import of this branch's test_linalg.py defined as False, as before. ``` python -m pytest test/test_linalg.py -k "cpu and (vector_norm or powsum or norm_reduced or keeps_small or norm)" python -m pytest test/test_nn.py -k "clip_grad or normalize" python -m pytest test/test_foreach.py -k "cpu and norm" python -m pytest test/test_ops.py -k "TestCommonCPU and (vector_norm or _powsum or normalize or nansum or nanmean)" ``` test_linalg: 57 passed; with main's kernel, test_norm_reduced_precision_cascade (half and bfloat16) and test_vector_norm_keeps_small_terms fail. test_nn, test_foreach and test_ops: 14, 60 and 65 passed. clang-format reports nothing. Without MKL, sqrt_kernel took Vectorized::sqrt here too, so the comparison script's vector_norm and _powsum results (27 inputs, 4 dtypes, 1 and 4 threads, 2484 results) are bitwise equal to the previous commit's and to f8ebd08's. The torch_np norm tests need LAPACK, which this build lacks (15 of them fail with "svd: LAPACK library not found", on main too), so test_axis is left to CI. The sqrt counts, with the official CPU wheels: ``` OMP_NUM_THREADS=1 python -c "import torch, numpy as np; x = torch.arange(1, 2**22, dtype=torch.float32); print(int((torch.sqrt(x).numpy() != np.sqrt(x.numpy())).sum()))" ``` Authored with an AI assistant (Claude Code). Co-Authored-By: Claude Opus 5.5 <[email protected]>
|
Successfully rebased |
e09a4d5 to
2a42f7e
Compare
|
@pytorchbot merge |
|
@pytorchbot merge |
Merge startedYour 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 |
|
@pytorchbot merge |
|
Can't merge closed PR #202533 |
`sum(dtype=torch.float32)` and `mean` on a bfloat16 or float16 CPU tensor were 5x to 25x slower than a plain `sum`. `sum_out` builds its iterator with `make_reduction_from_out_ty`, which keeps a reduced floating point input as is only on CUDA, XPU and MPS; on CPU it reduced `self.to(kFloat)`, a full float32 copy of the input. `mean_out` always takes that path for bfloat16/float16, for accuracy. The CPU sum kernel already loads bfloat16/float16 and accumulates in float, so `cascade_sum` now also writes a float result for a reduced floating point input, and `sum_out` uses it on CPU. `make_reduction_from_out_ty` is left alone, since prod, mean on other devices and all/any share it. `should_use_acc_buffer` is now keyed on the output dtype, because the input and output dtypes can differ. Fixes pytorch#202882 Test Plan: ``` python -m pytest -q test/test_reductions.py python -m pytest -q test/test_ops.py -k "TestCommonCPU and (sum or mean) and (bfloat16 or float16)" python -m pytest -q test/test_linalg.py -k "norm and cpu" lintrunner --take CLANGFORMAT,RUFF,FLAKE8 aten/src/ATen/native/ReduceOps.cpp aten/src/ATen/native/cpu/SumKernel.cpp test/test_reductions.py ``` Run in WSL on a CPU build of main at 87f51fb (pytorch#202533 landed) with and without this change. test_reductions.py: 4517 passed with both, including the new `test_sum_lowp_float_out`, which covers full, dim=0, dim=1 and transposed/strided/unsqueezed inputs above GRAIN_SIZE for both dtypes. TestCommonCPU bfloat16/float16 sum/mean: 44 passed. test_linalg.py -k "norm and cpu": 43 passed. Medians of 3 interleaved runs on an i7-11800H (AVX512): `mean` and `sum(dtype=torch.float32)` on 4096x4096 and 1e7-element bfloat16/float16 inputs are 4.6x to 18.9x faster at 1 thread and 6.8x to 27.9x at 4 threads (dim=0 gains least); a same-dtype `sum` stays within noise (0.89x to 1.11x). Authored with an AI assistant (Claude Code). Co-Authored-By: Claude Opus 5.5 <[email protected]>
#202533 moved CPU vector_norm and _powsum with ord 0, 1 and 2 to a new cascade_powsum_kernel dispatched under a new kernel tag, cascade_powsum_cpu. Selective (mobile) builds keep only the dtypes their traced model lists name for each tag, and lists traced before #202533 have norm_cpu and powsum_cpu but not the new tag, so those builds now fail with "dtype 'Float' not selected for kernel tag cascade_powsum_cpu". Dispatch the cascade kernel under the tags of the kernels it replaces, and fall back to the old kernel when the build did not select the input dtype for that tag (e.g. a half input with a float output, which the old code reduced without a tagged dispatch). Builds traced before #202533 then behave as before or use the new kernel; full builds are unchanged. Regenerating every traced dtype list instead would leave any app not re-traced broken at runtime. Test Plan: Compiled SumKernel.cpp before and after this change, normally and with -DTEMPLATE_SELECTIVE_BUILD and a selected_mobile_ops.h selecting only Float for norm_cpu, powsum_cpu and sum_cpu. With the selection, the old object has no float cascade_powsum kernels (the dispatch throws), the new one has them: ``` nm -C sel.o | grep -o 'cascade_sum<[^(]*' # before: IdentityMap, float, float # after: AbsMap, IdentityMap, NonZeroMap, SquareMap (float, float) lintrunner -a aten/src/ATen/native/cpu/SumKernel.cpp ``` Authored with an AI assistant. Pull Request resolved: #205834 Approved by: https://github.com/izaitsevfb
Linked issue or supporting maintainer
Fixes #65815
BC-breaking?
Yes, for CPU
nansumandnanmean, which is built on it, and the last bits of more CPU norms can now depend on the thread count; see Agent details.Summary (human written only)
See #65815.
Agent details (if applicable)
🤖 Generated with Claude Code
cc @jgong5 @mingfeima @XiaobingSuper @sanchitintel @ashokei @jingxu10 @aditew01