Repository navigation
Conversation
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
🔗 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 FailuresAs of commit 8129246 with merge base 5fc5e53 ( This comment was automatically generated by Dr. CI and updates every 15 minutes. |
|
@Nicoshev has exported this pull request. If you are a Meta employee, you can view the originating Diff in D117910533. |
|
Warning: Unknown label
Please add the new label to .github/pytorch-probot.yml |
|
@claude review this PR |
|
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 #197037PR Review: #197037SummaryDoubles the ILP factor (4 → 8) and adds a 2-wide tail in Code Quality1.
vec::load_to_float<scalar_t>(ptr, first, second);
return first + second; // lane l = x[l] + x[l + vacc_t::size()]I confirmed So the pairing distance is 8 on AVX2 (
Different partitions of the same 64 values ⇒ different rounding. (Contrast Note this cannot be fixed by re-tuning 2. Hardcode the invariant, don't hardcode the architecture. The same // 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 ( 3. AVX512 still diverges from AVX2, so "interoperatibility within a large set of systems" is not delivered on x86 either. With 4. Missing 5. 6. Loop style does not match the file. TestingNo test covers the invariant this PR establishes. Everything in 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 PerformanceRegister pressure on the one architecture this targets, with no measurements. RecommendationRequest 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 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.
|
|
@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 |
|
I'm generally amenable to increasing acc precision but yes doing it without regressing perf is tricky |
ezyang
left a comment
There was a problem hiding this comment.
I'd really appreciate tests though.....
|
@pytorchbot merge (Initiating merge automatically since Phabricator Diff has merged) |
|
Adding the |
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 |
…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
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]>
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]>
## 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]>
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