Skip to content

[caffe2/SumKernel] Adjust NEON ILP to match AVX2 and SVE256 fp32 computation - #197037

Closed
Nicoshev wants to merge 1 commit into
pytorch:mainfrom
Nicoshev:export-D117910533
Closed

Nicoshev wants to merge 1 commit into
pytorch:mainfrom
Nicoshev:export-D117910533

Conversation

@Nicoshev

@Nicoshev Nicoshev commented Sep 14, 2026 •

Copy link
Copy Markdown
Contributor

Summary:
Double the number of accumulators in SumKernel for NEON builds, making it compute the exact same FP32 reduction as AVX2 and SVE256 builds.

This allows interoperatibility within a large set of systems

Test Plan: CI

Reviewed By: Rajeev975

Differential Revision: D117910533

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

Summary:
Double the number of accumulators in SumKernel for NEON builds, making it compute the exact same reduction than AVX2 and SVE256.

This allows interoperatibility within a large set of systems

Test Plan: CI

Reviewed By: Rajeev975

Differential Revision: D117910533
@pytorch-bot

pytorch-bot Bot commented Sep 14, 2026 •

Copy link
Copy Markdown

🔗 Helpful Links

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

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

✅ No Failures

As of commit 8129246 with merge base 5fc5e53 (image):
💚 Looks good so far! There are no failures yet. 💚

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

@pytorch-bot pytorch-bot Bot added the module: cpu CPU specific problem (e.g., perf, algorithm) label Sep 14, 2026
@meta-codesync

meta-codesync Bot commented Sep 14, 2026

Copy link
Copy Markdown

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

@Nicoshev Nicoshev added ciflow/trunk Trigger trunk jobs on your pull request ciflow/linux-aarch64 linux aarch64 CI workflow labels Sep 14, 2026
@pytorch-bot

pytorch-bot Bot commented Sep 14, 2026

Copy link
Copy Markdown

Warning: Unknown label ciflow/linux-aarch64.
Currently recognized labels are

  • ciflow/b200
  • ciflow/b200-distributed
  • ciflow/b200-symm-mem
  • ciflow/binaries
  • ciflow/binaries_libtorch
  • ciflow/binaries_wheel
  • ciflow/docker
  • ciflow/dtensor
  • ciflow/h100
  • ciflow/h100-cutlass-backend
  • ciflow/h100-distributed
  • ciflow/h100-symm-mem
  • ciflow/inductor
  • ciflow/inductor-cu126
  • ciflow/inductor-micro-benchmark
  • ciflow/inductor-micro-benchmark-cpu-x86
  • ciflow/inductor-pallas
  • ciflow/inductor-perf-compare
  • ciflow/inductor-perf-test-nightly-rocm-mi300
  • ciflow/inductor-perf-test-nightly-rocm-mi350
  • ciflow/inductor-perf-test-nightly-x86-zen
  • ciflow/inductor-perf-test-nightly-xpu
  • ciflow/inductor-periodic
  • ciflow/inductor-rocm-mi200
  • ciflow/inductor-rocm-mi300
  • ciflow/mps
  • ciflow/native-aot
  • ciflow/nightly
  • ciflow/op-benchmark
  • ciflow/periodic
  • ciflow/periodic-rocm-mi200
  • ciflow/periodic-rocm-mi300
  • ciflow/periodic-strict
  • ciflow/pull
  • ciflow/riscv64
  • ciflow/rocm-mi200
  • ciflow/rocm-mi300
  • ciflow/rocm-navi31
  • ciflow/rocm-nightly
  • ciflow/rocm-preview
  • ciflow/s390
  • ciflow/slow
  • ciflow/slow-rocm-mi200
  • ciflow/torchtitan
  • ciflow/triton_binaries
  • ciflow/trunk
  • ciflow/tsan
  • ciflow/unstable
  • ciflow/win-arm64
  • ciflow/xpu

Please add the new label to .github/pytorch-probot.yml

@Skylion007

Copy link
Copy Markdown
Collaborator

@claude review this PR

@claude

claude Bot commented Sep 15, 2026 •

Copy link
Copy Markdown

Claude finished @Skylion007's task in 31m 26s —— View job


Reviewed — the float/double equivalence claim checks out, but I believe bfloat16/Half inner sums still diverge from AVX2, and AVX512 was left out, so the stated goal is only partially achieved; details below.

Full review of #197037

PR Review: #197037

Summary

Doubles the ILP factor (4 → 8) and adds a 2-wide tail in vectorized_inner_sum / vectorized_outer_sum for aarch64 non-SVE256 builds so that 128-bit NEON performs the same cascade partitioning as 256-bit AVX2. I traced the element→accumulator mapping and the claim holds bitwise for float and double (including the subtle detail that the tail adds must happen before the partial-sum fold, which the PR gets right). However the claim does not hold for BFloat16/Half, AVX512 is left diverging, and there is no test locking in the invariant this PR exists to establish.

Code Quality

1. BFloat16 / Half inner sums still do not match AVX2 — the PR's central claim fails for these dtypes.

aten/src/ATen/native/cpu/SumKernel.cpp:444-450 tunes ilp_factor, but for reduced-precision inputs InnerSumCastLoadPolicy (SumKernel.cpp:113-127) performs one floating-point add inside the load, and its pairing distance is vacc_t::size() — which ilp_factor cannot compensate for:

vec::load_to_float<scalar_t>(ptr, first, second);
return first + second;   // lane l  =  x[l] + x[l + vacc_t::size()]

I confirmed load_to_float is a low/high split, not a deinterleave, on all three targets: AVX2 via cvtbf16_fp32 (vec256_16bit_float.h:43-48), NEON via the scalar LOAD_FP32_NON_VECTORIZED_INIT path (vec256_bfloat16.h:277, macro at vec256_16bit_float.h:818-833), SVE256 via svzip1/svzip2 (sve/vec_bfloat16.h:233-243).

So the pairing distance is 8 on AVX2 (Vectorized<BFloat16>::size()=16, Vectorized<float>::size()=8) but 4 on NEON (8 and 4 — vec128_reduced_precision_common_neon.h:25-28, vec128_float_neon.h:122-124). The ILP chunk size does coincide at 64 scalars on both, so the cascade levels line up, but the partition inside the chunk does not. For one 64-element chunk:

partials[0] accumulates
AVX2 (ilp=4, tail=1) {0, 8, 16, 24, 32, 40, 48, 56}
NEON after this PR (ilp=8, tail=2) {0, 4, 16, 20, 32, 36, 48, 52}

Different partitions of the same 64 values ⇒ different rounding. (Contrast float, where no fold happens in the load and I get partials[l] == {l, 8+l, 16+l, 24+l} on both — identical element-for-element and order-for-order, which is why float/double do work.)

Note this cannot be fixed by re-tuning ilp_factor/tail_ilp_factor at all: distance 4 is baked into the 128-bit load. Making bf16/Half match would need an aarch64 reduced-precision load policy that consumes two NEON vectors so the fold distance becomes 8. Please either do that, or explicitly scope the PR description and the commit message to float/double so downstream users don't rely on an equivalence that isn't there for reduced precision.

Fix this →

2. Hardcode the invariant, don't hardcode the architecture. The same #if defined(__aarch64__) && !defined(CPU_CAPABILITY_SVE256) block is duplicated at SumKernel.cpp:444 and SumKernel.cpp:512, and neither 8 nor 2 carries a comment explaining the relationship to AVX2. The actual invariant is "one ILP group spans 32 bytes × 4 of scalar data", which is expressible directly:

// Keep the cascade partitioning identical across vector widths: one ILP group
// must span the same number of scalars as a 4-wide group of 256-bit vectors.
constexpr int64_t ilp_factor = 4 * 32 / VECTOR_WIDTH;

That is 8 for aarch64/SVE128 (VECTOR_WIDTH 16, vec_base.h:72-82), 4 for AVX2/SVE256/VSX, and — as a side effect — 2 for AVX512, which brings AVX512 into line too. Which raises the next point.

3. AVX512 still diverges from AVX2, so "interoperatibility within a large set of systems" is not delivered on x86 either. With ilp_factor left at 4 and Vectorized<float>::size() == 16, an AVX512 build chunks at 64 scalars against AVX2's 32. Since sum_stub dispatches on runtime CPU capability, two x86 hosts already give different results for the same input. If the goal is a single reduction order everywhere, this needs to be in scope; if it is deliberately out of scope, say so in the description.

4. Missing static_assert on the new relationship between the two constants. The fold at SumKernel.cpp:469-473 indexes partial_sums[k + h] for k stepping by tail_ilp_factor and h < tail_ilp_factor, which only stays in bounds when tail_ilp_factor divides ilp_factor. Add static_assert(ilp_factor % tail_ilp_factor == 0); so a future width gets a compile error rather than an out-of-bounds read.

5. vectorized_inner_sum now reimplements row_sum instead of calling it. row_sum at SumKernel.cpp:412-431 still has its own hardcoded ilp_factor = 4 and is the same algorithm minus the tail factor. Rather than duplicating it, template it on ilp_factor/tail_ilp_factor and call it from both places — otherwise the two copies will drift, and scalar_inner_sum (which routes through row_sum) silently keeps the old partitioning.

6. Loop style does not match the file. for (int64_t h = 0; h < tail_ilp_factor; h += 1) (lines 464, 470, 481) — the rest of this file uses c10::irange for exactly this (e.g. SumKernel.cpp:370, :396, :525), and h += 1 should be ++h.

Testing

No test covers the invariant this PR establishes. Everything in test/test_reductions.py is tolerance-based assertEqual — test_sum_noncontig_lowp (line 1330) tops out around 50³, test_sum_vs_numpy (line 1750) uses atol=7e-05 for float32 and 0.4 for float16, and nothing pins a golden value or reduction order. There is no test comparing results across ATEN_CPU_CAPABILITY settings (the env var is only used in test/inductor/test_cpu_repro.py), and none exercising the vectorized_inner_sum and vectorized_outer_sum paths at reduction lengths large enough (≥ a few thousand) for reordering to be observable.

Concretely: had the bf16 divergence in finding 1 been an intended part of this change, CI would still be green. A regression that silently reverts this PR's partitioning would also be green. Please add a device-generic test that sums a fixed large input on both the inner (contiguous reduced dim) and outer (contiguous non-reduced dim) paths across float32/float64/bfloat16/float16 and asserts an exact reference value, so the partitioning is actually pinned. Per CLAUDE.md, use instantiate_device_type_tests and @parametrize.

Performance

Register pressure on the one architecture this targets, with no measurements. multi_row_sum holds num_levels * nrows accumulators (SumKernel.cpp:351-361); going to nrows = 8 makes that 32 live vacc_t values on a machine with exactly 32 128-bit vector registers, guaranteeing spills in the hot loop at SumKernel.cpp:364-389. The higher cascade levels are cold so the spills may be cheap, but the Test Plan is just "CI" and this is a hot reduction kernel whose ILP is being changed specifically for aarch64. Please include before/after numbers on a NEON host for the inner and outer paths at a few reduction sizes — if this costs throughput, that is a real trade-off against reproducibility that reviewers should see, not infer.

Recommendation

Request Changes

Two blockers: the bf16/Half inner-sum path does not achieve the equivalence the PR is titled for (finding 1), and there is no test pinning the reduction order this PR exists to fix (Testing). The AVX512 gap (finding 3) needs at minimum an explicit in-scope/out-of-scope statement. Findings 2 and 4-6 are cleanups that would also make the invariant self-documenting rather than encoded in a duplicated #if.

Caveat on confidence: the element→accumulator mappings above are from reading the code and hand-tracing, not from running a NEON build. Finding 1 is worth confirming empirically — summing a few thousand bf16 values on an aarch64 host and an AVX2 host and comparing bitwise should settle it in a minute.


  • Load PyTorch /pr-review guidelines
  • Read the diff and surrounding code in aten/src/ATen/native/cpu/SumKernel.cpp
  • Trace element→accumulator mapping for float/double/bfloat16 on NEON vs AVX2 vs SVE256
  • Check existing test coverage for sum reduction accuracy
  • Post review
    | Branch: export-D117910533

@Nicoshev Nicoshev changed the title [caffe2/SumKernel] Adjust NEON ILP to match AVX2 and SVE256 computation [caffe2/SumKernel] Adjust NEON ILP to match AVX2 and SVE256 fp32 computation Sep 16, 2026
@Nicoshev

Copy link
Copy Markdown
Contributor Author

@Skylion007 In response to Claude:

We decided to not modify AVX512 to not detriment it's speed, as we need to cut its ILP to half

Just changed the PR's title to only cover FP32, achieving it on FP16/BF16 required very ugly changes. Better to further analyze it and propose a different solution in a follow-up PR

@ezyang

ezyang commented Sep 16, 2026

Copy link
Copy Markdown
Contributor

I'm generally amenable to increasing acc precision but yes doing it without regressing perf is tricky

@Nicoshev
Nicoshev requested a review from ezyang September 16, 2026 14:26

@ezyang ezyang 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.

I'd really appreciate tests though.....

@meta-codesync

meta-codesync Bot commented Sep 16, 2026

Copy link
Copy Markdown

@pytorchbot merge

(Initiating merge automatically since Phabricator Diff has merged)

@pytorchmergebot

Copy link
Copy Markdown
Collaborator

Adding the topic: not user facing label automatically: this co-dev PR is being merged after its internal diff landed, without a release-notes label. If this change is user facing, please replace the label with the appropriate release notes: ... one.

@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 pushed a commit that referenced this pull request Sep 16, 2026
…n::norm fp32 computation (#197252)

Summary:
Double the number of accumulators in fp32 aten::norm kernel for NEON builds, making it compute the exact same reduction than AVX2 and SVE256.

This allows interoperatibility within a larger set of systems

Performance impact should be negligible

Same idea than in #197037

Test Plan: CI

Differential Revision: D119298153

Pull Request resolved: #197252
Approved by: https://github.com/ezyang
egeboy35 added a commit to egeboy35/pytorch that referenced this pull request Nov 3, 2026
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]>
pytorchmergebot pushed a commit to egeboy35/pytorch that referenced this pull request Nov 17, 2026
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]>
pytorchmergebot pushed a commit that referenced this pull request Nov 18, 2026
## 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 2**24 + 2**18 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](https://claude.com/claude-code)

Pull Request resolved: #202533
Approved by: https://github.com/ngimel

Co-authored-by: Claude Opus 5.5 <[email protected]>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

ciflow/linux-aarch64 linux aarch64 CI workflow ciflow/trunk Trigger trunk jobs on your pull request Merged meta-exported module: cpu CPU specific problem (e.g., perf, algorithm) topic: improvements topic category topic: not user facing topic category

Projects

None yet

Development

Successfully merging this pull request may close these issues.

4 participants