Skip to content

Use cascade summation for CPU vector norms with ord 0, 1 and 2 - #202533

Closed
egeboy35 wants to merge 10 commits into
pytorch:mainfrom
egeboy35:fix-cpu-norm-cascade
Closed

egeboy35 wants to merge 10 commits into
pytorch:mainfrom
egeboy35:fix-cpu-norm-cascade

Conversation

@egeboy35

@egeboy35 egeboy35 commented Oct 29, 2026 •

Copy link
Copy Markdown
Contributor

Linked issue or supporting maintainer

Fixes #65815

BC-breaking?

Yes, for CPU nansum and nanmean, 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)

Drafted by Claude (AI) for @egeboy35.

For real floating inputs, CPU vector_norm with ord 0, 1 and 2 and _powsum with ord 1 and 2 now use sum()'s cascade summation, with |x|, x * x or x != 0 applied as each element is loaded (nansum's NaN masking already worked this way, so its load policies become generic). _powsum ord 0 counts zeros too, so it keeps its old kernel. cascade_powsum_kernel checks the ord and dtypes itself and returns false otherwise, and the old kernels take the rest. Half and bfloat16 reduce into a float temporary and round once, because the cascade kernel can add partial sums into its output. A reduction to one element uses at::parallel_reduce, so the per-thread results are added once and not passed through the load map again; it keeps them in float and writes the output once, so a half or bfloat16 result with one element needs no temporary. Either way, the ord=2 square root is taken before rounding to half or bfloat16, with std::sqrt as on main; after a reduction to several outputs it is a separate pass that does not use sqrt_kernel, because with MKL that calls vsSqrt, which is not correctly rounded. The ord=2 last-dim fast paths are removed. For float32 input, cascade_sum does the same additions on NEON, AVX2 and SVE256 (#197037) apart from rows of 4 to 7 elements, so most norms stay identical across them at a given thread count, as #197252 intended. Half and bfloat16 inputs and those short rows can differ in the last bits between them, as they already do for torch.sum. Other ords, complex inputs and CUDA are unchanged. Reductions whose reduced dims cannot be merged into one (e.g. dim=(0, 2)) still add row partials one after another, as torch.sum does.

On current main, vector_norm(randn(10**8)) is 1.1% low and vector_norm(ones(10**4, 10**4), 1) returns 16777216. With this change, ord 0, 1 and 2 match a float64 reference to about 1e-7 at 1 and 7 threads. BC, all on CPU and in the last bits or special values only: (1) A multi-threaded nansum used to give a finite result when inf and -inf fell in one thread's chunk (32768 for ones(2**16) starting with [inf, -inf] at 4 threads, on 2.14.1), while one thread gave NaN. It now gives NaN at any thread count, as np.nansum does; test_nansum_keeps_inf_minus_inf checks this, and ngimel accepted the change in review. (2) A multi-threaded nansum to one element now adds the per-thread partial sums one after another rather than in the cascade loop, so its last bits can differ from main for finite inputs too. nanmean is built on nansum, so (1) and (2) apply to it as well. (3) More norms now depend on the thread count in the last bits. On main, ord 2 with dim=None (and _powsum ord 2) on a contiguous float, double or bfloat16 tensor took a last-dim path that only splits work across outputs, and multi-output norms and _powsum on strided inputs used binary_kernel_reduce, which reduces each output on one thread. Both now go through the cascade kernel's parallel reduction, so their last bits can change with the number of threads, as those of contiguous ord 0 and 1 norms already could on main.

Timings, 1 thread, ms, median over 6 interleaved runs of each build (WSL2, x86 AVX2). ord=3 runs the same code in both builds; its main/fix ratio stayed within 1.03x-1.14x per dtype, which is the noise level.

case main this PR
float32 randn(10**7), ord=2 4.43 3.91
float32 randn(10**7), ord=1 18.24 3.56
float32 randn(10**7), ord=0 20.27 3.76
float32 4096x4096, ord=2, dim=-1 9.56 7.21
float32 4096x4096, ord=2, dim=0 425.19 10.85
float64 4096x4096, ord=2, dim=-1 14.10 14.70
bfloat16 4096x4096, ord=2 9.25 4.04
float16 randn(10**7), ord=2 26.68 2.28
float32 1000 elements, ord=2 0.005 0.005

Float32 rows of 3 and 4 elements with ord=2 and dim=-1, which main reduced in one pass with binary_kernel_reduce_lastdim, and F.normalize on them, in ms, median over 5 interleaved runs of each build. The 4-thread times of one build varied by up to 1.8x between runs; the best F.normalize (2**20, 3) runs at 4 threads took 3.94 ms on main and 3.99 ms here.

case threads main this PR
vector_norm (2**20, 3) 1 6.69 5.11
vector_norm (2**20, 4) 1 7.30 5.30
vector_norm (2**20, 3) 4 3.41 2.96
vector_norm (2**20, 4) 4 3.77 2.71
F.normalize (2**20, 3) 1 10.06 8.24
F.normalize (2**20, 4) 1 11.74 10.68
F.normalize (2**20, 3) 4 4.51 5.37
F.normalize (2**20, 4) 4 5.26 5.34

A half or bfloat16 norm of 1000 elements took about 3 us more than float32 with the float temporary; written directly, it takes the same 4-5 us per call as float32 in this build. Half and bfloat16 reductions to more than one element still pay for the temporary and the copy back.

Tested on a Linux CPU build without MKL or LAPACK: test_vector_norm_keeps_small_terms (float vector_norm and _powsum, at 1 and 4 threads), test_norm_reduced_precision_cascade (half and bfloat16 vector_norm and _powsum ord 1 over 224 + 218 zero-stride elements, to one and two outputs, at 1 thread) and test_nansum_keeps_inf_minus_inf fail on main and pass here; test_vector_norm_special_values (ord 0, 1 and 2 on nan, inf, -inf, -0.0 and negative inputs through the vectorized maps, float, half and bfloat16, against numpy), test_nansum_nan_multithreaded (a NaN-containing nansum to one element at 1 and 4 threads), test_powsum_size_one_dim (the cascade kernel's elementwise loop, reached by a _powsum over a size-1 dim) and test_powsum_ord_zero_counts_zeros add coverage and also pass on main; test_norm_reduced_precision_accumulates_in_float covers the float temporary of vector_norm and _powsum for half and bfloat16, and test_norm_reduced_precision_all_reduce their reduction to one element at 1 and 4 threads; the norm, powsum, sum, clip_grad and foreach-norm tests in test_linalg, test_reductions, test_nn, test_foreach and test_ops pass. On 27 inputs (with NaN, inf and -inf or finite) in 4 dtypes at 1 and 4 threads, the latest commit's vector_norm and _powsum results (ord 0 to 3 and inf) are bitwise equal to those of the previous commit and of f8ebd08, and its nansum and sum results to those of f8ebd08. With MKL, the previous commit's multi-output float32 norms differed by one ulp in CI (test_vector_norm_special_values and the torch_np TestNormSingle.test_axis); the torch_np norm tests need LAPACK, so CI checks them.

🤖 Generated with Claude Code

cc @jgong5 @mingfeima @XiaobingSuper @sanchitintel @ashokei @jingxu10 @aditew01

@pytorch-bot

pytorch-bot Bot commented Oct 29, 2026 •

Copy link
Copy Markdown

PR Status: Approved 🚀

Please fix all CI failures and trigger merge by commenting "@pytorchbot merge".

✅ AUTOMATED REVIEW - OUTDATED (earlier commit) - Ready for human review:

On CPU, this PR routes vector_norm (ord 0/1/2) and _powsum (ord 1/2) for real
floating inputs through sum()'s cascade summation, reduces half/bf16 into float,
and removes the ord=2 last-dim fast paths. All blocking findings from the
previous review are fixed at HEAD. Recommendation: Approve, with only
non-blocking points left.

Findings (3):

[minor] aten/src/ATen/native/cpu/SumKernel.cpp:690
Non-blocking: the new comment "nansum keeps that combine, which also masks a NaN
per-thread result" presents the inf/-inf bug as intended behaviour. When `inf`
and `-inf` fall in the same thread's chunk, the final pass of
`two_pass_reduction` runs `NanToZeroMap` over the per-thread buffer and zeroes
the NaN partial. Multi-threaded CPU `nansum` then returns a finite value that
depends on the thread count. ngimel called this "clearly buggy" and approved
fixing it in this PR, but the latest commit reverted the fix and deleted
`test_nansum_keeps_inf_minus_inf` with no explanation in the thread. Either
restore the approved fix, or reword the comment to call this a known bug and
link a tracking issue.

[minor] test/test_linalg.py:2029
Non-blocking: no half/bfloat16 test can tell whether the new cascade path ran.
In the reduced-precision, all-reduce, special-values and powsum size-one-dim
tests, every expected sum is exact under linear float accumulation, so the old
`binary_kernel_reduce` fallback passes them too (the PR body confirms they pass
on main). A regression where `cpu_powsum_in_float` returns false, or where the
dtype gate in `cascade_powsum_kernel` turns half/bf16 away, would pass every
test. Suggested fix using zero-stride `expand`:
- bf16: ord 1 over `torch.ones((), dtype=torch.bfloat16).expand(2**24 + 2**18)`,
expect `2**24 + 2**18`, with `dim=None` at 1 thread. Also add `.expand(2**24 +
2**18, 2)` with `dim=0`.
- half: ord 1 over `torch.full((), 2**-10, dtype=torch.half).expand(2**24 +
2**18)`, expect 16640 (main stalls at `2**14`).

[minor] aten/src/ATen/native/cpu/SumKernel.cpp:716
Non-blocking: float ord=2 norms over short last-dim rows were never benchmarked.
On main, a float `(N, 3)` or `(N, 4)` input with `dim=-1` took
`binary_kernel_reduce_lastdim` (removed at ReduceOpsKernel.cpp:212), a single
pass that writes `sqrt(sum)` per row. At HEAD the same input takes three passes:
1. `fill_(0)`
2. `parallel_reduce(loop)`, which falls to `scalar_inner_sum` because the row is
shorter than `Vectorized<float>::size()`
3. a separate `unary_op` + `sqrt_kernel` pass

The shortest row in the posted benchmarks is 64. This is the default norm and
the path `F.normalize` takes for point-cloud and quaternion data. Please time
float32 `(2**20, 3)` and `(2**20, 4)`, ord=2, `dim=-1`, at 1 and 4 threads. The
accepted regression covered only the half/bf16 float temporary, not this case.

Reviewed commit: b767baa (NOT the current head 2a42f7e)

Review run

🐛 Report a bad review

🔗 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 (image):

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:

  • BC Lint / bc_linter (gh)
    ##[error]API rate limit exceeded for installation. If you reach out to GitHub Support for help, please include the request ID 6C40:383D18:26817F8:79284D6:6AFCE1B2 and timestamp 2026-11-17 23:22:27 UTC. For more on scraping GitHub and how it may affect your rights, please review our Terms of Service (https://docs.github.com/en/site-policy/github-terms/github-terms-of-service) - https://docs.github.com/en/rest/using-the-rest-api/getting-started-with-the-rest-api#rate-limiting

    AI verdict: AI verdict: infra issue

    The BC Lint job failed during actions/checkout. The step that looks up the repo's default branch hit "API rate limit exceeded for installation" three times and gave up, so the linter never ran. The suspect commit only edits the C++ file aten/src/ATen/native/cpu/SumKernel.cpp, which has no way to affect GitHub API quota or the checkout step.

    Full reasoning on HUD →

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

@pytorch-bot pytorch-bot Bot added module: cpu CPU specific problem (e.g., perf, algorithm) release notes: linalg_frontend release notes category labels Oct 29, 2026
@egeboy35
egeboy35 marked this pull request as ready for review October 29, 2026 10:36
@egeboy35
egeboy35 requested a review from lezcano as a code owner October 29, 2026 10:36
@egeboy35

Copy link
Copy Markdown
Contributor Author

@ngimel

Drafted by Claude (AI) for @egeboy35.

Thanks for adding the label on #65815. This is the fix: ord 0, 1 and 2 now go through sum()'s cascade summation on CPU, and the description has the accuracy check and 1-thread timings. Could you take a look, and approve the CI workflows when you have a moment? They wait for maintainer approval because the PR comes from a fork.

@egeboy35
egeboy35 requested a review from nikitaved as a code owner October 29, 2026 10:36
@github-actions
github-actions Bot requested a review from ngimel October 29, 2026 10:49
@github-actions github-actions Bot added bot-triaged This is a label only to be used by the auto triage bot triaged This issue has been looked at a team member, and triaged and prioritized into an appropriate module labels Oct 29, 2026
@ngimel

ngimel commented Oct 29, 2026

Copy link
Copy Markdown
Collaborator

@claude review this PR, pay attention to code quality, subtle correctness bugs and breaking existing behacvior, outside of intended fixes.

@claude

claude Bot commented Oct 29, 2026 •

Copy link
Copy Markdown

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 nansum behavior with no test, and the new half/bfloat16 float-accumulation path in linalg_vector_norm has no test of its own.

PR Review: #202533

Summary

For real floating inputs on CPU with ord 0, 1 and 2, linalg_vector_norm and linalg__powsum now use cascade_sum. This works by generalizing nansum's NaN-masking load policies into a Map parameter. For half and bfloat16 the reduction goes into a float temporary. I found no correctness bug in the new Map load policies, the per-thread partials path, or the dtype routing. The problems are an unflagged nansum behavior change, test gaps, eligibility logic duplicated in three places, and per-call overhead on small reduced-precision inputs.

Backward Compatibility

  • nansum semantics change, outside the scope of Overflow error in torch.linalg uncaught #65815 (aten/src/ATen/native/cpu/SumKernel.cpp, the basic_loop branch and the new !is_identity partials block in cascade_sum).
    • Before this PR, nansum masked NaN in the accumulator in two places:
      • the "not a true reduction" basic_loop path (a_notnan);
      • the final combine of two_pass_reduction, which used NanSumCastLoadPolicy on the per-thread partials.
    • After this PR, a NaN produced by inf + (-inf) is kept. Example: torch.nansum(torch.tensor([inf, -inf, 1.]).expand(...)) along a non-inner dim, or a full reduction at more than one thread, used to return finite values and now returns NaN.
    • The new result matches NumPy and is consistent across thread counts, so it is arguably a fix. But it is user-visible, it is not listed under "BC-breaking?", and no test pins it.
    • Either split it into its own PR, or add a test (test_reductions: nansum of [inf, -inf, 1] across dims and thread counts, checked against np.nansum) and mention it in the release notes.

Testing

  • The half/bfloat16 float-temporary path in linalg_vector_norm_out has no test (LinearAlgebra.cpp:2952-2962). test_powsum_reduced_precision_accumulates_in_float only calls torch.linalg._powsum, which goes through the separate copy at LinearAlgebra.cpp:3021-3030. Extend the test (or add a sibling) to cover torch.linalg.vector_norm(x, ord, dim=(0, 2)) for ord 0, 1 and 2 with half and bfloat16. The sqrt_ that runs on the float temporary before copy_ is also currently untested for these dtypes.
  • No test for the parallel Map partials path with a non-IdentityMap other than the norms. test_vector_norm_keeps_small_terms reaches it at more than one thread, but nothing checks that nansum gives the same result at 1 and N threads, which the description claims. Use torch.set_num_threads in a test, or rely on the nansum test above.

Code Quality

  • The rule for which ords and dtypes take the cascade path lives in three places, and they already differ.

    • use_cascade_powsum in ReduceOpsKernel.cpp, plus val != 0.0 at its powsum call site;
    • the norm branch at LinearAlgebra.cpp:2955 (ord 0/1/2);
    • the powsum branch at LinearAlgebra.cpp:3023 (ord 1/2).

    If the frontend sends half/bfloat16 to a float temporary but the kernel's predicate later diverges, the result is still correct, but the float temporary and copy are wasted with no benefit. Put the ord/dtype predicate in one shared declaration (e.g. next to cascade_powsum_kernel in SumKernel.h, or in ReduceOpsUtils.h) and call it from all three sites.

  • The partials loop in cascade_sum copies TensorIteratorBase::parallel_reduce's heuristics (numel >= GRAIN_SIZE, get_num_threads() > 1, !in_parallel_region(), single-element output) and reimplements two_pass_reduction (TensorIteratorReduce.cpp:23-73). If those heuristics change, the two copies drift apart silently. If one does start applying Map twice, the norms come out wrong (for example |x|^2 gets squared again) and no error is raised.

    • Since the hazard is that two_pass_reduction's final reduction reuses the first-pass loop, a cleaner fix is a parallel_reduce overload (or an internal variant) that takes a separate combine loop. The identity CastLoadPolicy loop would then do the final reduction.
    • At minimum, add a comment in TensorIteratorReduce.cpp pointing to this copy.
  • Exposing the float-temporary decision in device-generic LinearAlgebra.cpp. The comment says "as mean() does", but the float temporary is only needed because cascade_sum's CastStoreAccumulate adds partial row sums into the output. The old binary_kernel_reduce path already accumulated each output element fully in opmath_type (float) and rounded once. So the temporary is a property of this kernel, not of the op. Say that in the comment, so nobody "simplifies" it away or copies it to CUDA/MPS.

Performance

  • Fixed per-call overhead on small half/bfloat16 inputs, measured in the PR at about 5 → 8 us for 1000 bfloat16 elements. On CPU, _foreach_norm / clip_grad_norm_ call linalg_vector_norm once per parameter, so models with many small bfloat16 parameters pay roughly +3 us per tensor (one empty plus one copy_ per call, and a separate sqrt_ pass).
    • When the reduction is a single merged contiguous dim, the kernel never accumulates partials into the output, so the float temporary buys nothing there.
    • Consider writing into result directly in that case. Or keep the removed last-dim fast path for small bfloat16 inputs, running on the cascade loop body.
  • iter.output().sqrt_() (ReduceOpsKernel.cpp, norm branch) adds a dispatcher call and a second pass over the output. For the half/bfloat16 path it could be folded into the frontend (at::sqrt_out(result, result_float) instead of copy_ + sqrt_), which removes one pass.

Recommendation

Request Changes

Blocking: the nansum behavior change needs a decision (split it out, or test and document it), and the linalg_vector_norm half/bfloat16 float-accumulation path needs its own test. The duplicated predicate and the copied parallel_reduce heuristics should also be fixed before merge.

Not checked: whether test_vector_norm_keeps_small_terms passes on CUDA. It is not @onlyCPU, and the ord=0 case uses rtol=0 on 33M elements.

@ngimel ngimel added the in progress PR is being worked on by the author, until the automated review accepts it label Oct 29, 2026
github-actions[bot]

This comment was marked as outdated.

@egeboy35

Copy link
Copy Markdown
Contributor Author

@ngimel

Drafted by Claude (AI) for @egeboy35.

Thanks for running the review. The new commit addresses both automated reviews:

  • nansum: the change stays, since it makes the result the same at any thread count and matches np.nansum. test_nansum_keeps_inf_minus_inf checks it at 1 and 4 threads (on 2.14.1 the 4-thread case returns 32768, not NaN), and the description now lists it under BC-breaking. Should the PR also get the "topic: bc breaking" label?
  • The hand-rolled per-thread reduction is now at::parallel_reduce, used for every non-identity map with a one-element output, so nothing depends on TensorIterator::parallel_reduce's threading rules any more.
  • The ord/dtype rule is one function, use_cascade_powsum in ReduceOpsUtils.h, used by both kernels and by a single float-temporary helper in LinearAlgebra.cpp. Its comment now says the temporary exists because this kernel adds partial sums into its output.
  • The norm tests set the thread count (1 and 4), cover double, and cover the half/bfloat16 path of vector_norm for ord 0, 1 and 2. test_vector_norm_keeps_small_terms is CPU-only now. test_norm_reduced_precision_accumulates_in_float also passes on main, since binary_kernel_reduce accumulates in float there; it guards this PR's kernel, which without the float temporary would stop at 4096 (half) or 512 (bfloat16).

Not changed: the ~3 us float temporary on small half/bfloat16 inputs. Skipping it would need the frontend to know when the kernel adds partial sums, which is the kind of duplicated rule the reviews asked to remove. I can gate it in a follow-up if you prefer.

github-actions[bot]

This comment was marked as outdated.

github-actions[bot]

This comment was marked as outdated.

github-actions[bot]

This comment was marked as outdated.

@egeboy35

egeboy35 commented Nov 2, 2026

Copy link
Copy Markdown
Contributor Author

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

@ngimel

ngimel commented Nov 2, 2026

Copy link
Copy Markdown
Collaborator

Bot is still unhappy

@egeboy35

egeboy35 commented Nov 3, 2026

Copy link
Copy Markdown
Contributor Author

@pytorchbot label "topic: bc breaking"

@pytorch-bot pytorch-bot Bot added the topic: bc breaking topic category label Nov 3, 2026
github-actions[bot]

This comment was marked as outdated.

github-actions[bot]

This comment was marked as outdated.

@ngimel

ngimel commented Nov 3, 2026

Copy link
Copy Markdown
Collaborator

@egeboy35 if you rebase github bot should become more consistent and not find new nits in already reviewed code

@egeboy35
egeboy35 force-pushed the fix-cpu-norm-cascade branch from 0cbc21b to 0489e38 Compare November 3, 2026 20:40
@ngimel

ngimel commented Nov 17, 2026

Copy link
Copy Markdown
Collaborator

@pytorchbot rebase

@pytorchmergebot

Copy link
Copy Markdown
Collaborator

@pytorchbot started a rebase job onto refs/remotes/origin/viable/strict. Check the current status here

egeboy35 and others added 10 commits November 17, 2026 22:50
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]>
@pytorchmergebot

Copy link
Copy Markdown
Collaborator

Successfully rebased fix-cpu-norm-cascade onto refs/remotes/origin/viable/strict, please pull locally before adding more changes (for example, via git checkout fix-cpu-norm-cascade && git pull --rebase)

@egeboy35

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 Nov 18, 2026
@egeboy35

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

@egeboy35

Copy link
Copy Markdown
Contributor Author

@pytorchbot merge

@pytorchmergebot

Copy link
Copy Markdown
Collaborator

Can't merge closed PR #202533

egeboy35 added a commit to egeboy35/pytorch that referenced this pull request Nov 18, 2026
`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]>
pytorchmergebot pushed a commit that referenced this pull request Nov 20, 2026
#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
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

bot-triaged This is a label only to be used by the auto triage bot ciflow/trunk Trigger trunk jobs on your pull request Merged module: cpu CPU specific problem (e.g., perf, algorithm) open source ready for review Automated review passed, ready for a final review by a maintainer. release notes: linalg_frontend release notes category topic: bc breaking topic category triaged This issue has been looked at a team member, and triaged and prioritized into an appropriate module

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Overflow error in torch.linalg uncaught

4 participants