Skip to content

Reduce bfloat16/float16 CPU sums into float without a float copy - #203408

Open
egeboy35 wants to merge 1 commit into
pytorch:mainfrom
egeboy35:cpu-lowp-sum-float-out
Open

egeboy35 wants to merge 1 commit into
pytorch:mainfrom
egeboy35:cpu-lowp-sum-float-out

Conversation

@egeboy35

@egeboy35 egeboy35 commented Nov 4, 2026 •

Copy link
Copy Markdown
Contributor

Linked issue or supporting maintainer

Fixes #202882
Supported by @frost-intel

BC-breaking?

No

Summary (human written only)

See #202882. On CPU, bfloat16/float16 mean and sum(dtype=torch.float32) now accumulate in float directly instead of reducing a float32 copy of the input.

Agent details (if applicable)

Drafted by Claude (AI) for @egeboy35.

sum_out used 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). mean_out always goes through that path for bfloat16/float16. The CPU sum kernel already loads bfloat16/float16 and accumulates in float, so cascade_sum now also writes a float result for them and sum_out builds the iterator with the input dtype on CPU. make_reduction_from_out_ty itself is unchanged (prod, mean on other devices and all/any share it), and should_use_acc_buffer is keyed on the output dtype. The stale comment in mean_out about the CPU cast is removed.

Medians of 3 interleaved runs (i7-11800H, AVX512, WSL2), on a CPU build of main at 87f51fb (after #202533 landed) with and without this change. The issue said 4 threads gave the same ratios as 1 thread; that run had actually timed 1 thread (torch.utils.benchmark.Timer defaults to num_threads=1). These numbers set the thread count explicitly:

op dtype input threads before ms after ms speedup
mean bfloat16 1e7, full 1 16.68 1.06 15.69x
mean bfloat16 4096x4096, dim=-1 1 33.32 2.59 12.88x
mean bfloat16 4096x4096, dim=0 1 32.22 6.96 4.63x
sum(dtype=torch.float32) float16 1e7, full 1 15.97 1.03 15.53x
sum(dtype=torch.float32) float16 4096x4096, dim=0 1 33.02 6.06 5.45x
mean bfloat16 1e7, full 4 9.74 0.35 27.91x
mean float16 4096x4096, dim=-1 4 16.28 0.95 17.23x
mean bfloat16 4096x4096, dim=0 4 19.28 2.86 6.75x
sum(dtype=torch.float32) float16 1e7, full 4 8.07 0.35 23.30x
sum(dtype=torch.float32) bfloat16 4096x4096, dim=0 4 18.79 2.74 6.86x

Across all 24 measured cases the speedup is 4.6x to 18.9x at 1 thread and 6.8x to 27.9x at 4 threads (dim=0 gains least). A same-dtype sum takes the same code path as before and stays within noise (0.89x to 1.11x).

Tests, on the same two builds: test_reductions.py (4517 passed with and without the change, including the new test_sum_lowp_float_out, which covers full, dim=0, dim=1, transposed, strided and unsqueezed inputs above GRAIN_SIZE for both dtypes), the bfloat16/float16 sum/mean cases in TestCommonCPU (44 passed) and test_linalg.py -k "norm and cpu" (43 passed). lintrunner --take CLANGFORMAT,RUFF,FLAKE8 reports nothing.

🤖 Generated with Claude Code

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

@pytorch-bot

pytorch-bot Bot commented Nov 4, 2026 •

Copy link
Copy Markdown

PR Status: in progress

To become ready for review, please address automated review on your PR either with a code/PR description change. If a review comment is irrelevant, react with 👎 on that specific comment to reject it, and leave a short reply explaining why. The change must pass any running CI and existing failures must be classified as unrelated (see status below in this comment).

Passing automated review does not guarantee that this PR will be merged. It still requires maintainer review and may be closed if its design or direction does not align with the project.

To minimize iteration time, feel free to run the pr-review skill from the repo locally. To trigger a fresh automated review, make a new push or comment @pytorchbot review. To bypass automated review, please add the "no automated review" label.

✅ AUTOMATED REVIEW - Ready for human review:

On CPU, the PR makes bfloat16/float16 `sum(dtype=torch.float32)` and `mean` read
the low-precision input directly and accumulate in float, instead of first
making a float32 copy, and the review found no correctness, security or
backward-compatibility bugs. Recommendation: Approve, with every point raised
labelled non-blocking.

Findings (5):

[minor] aten/src/ATen/native/cpu/SumKernel.cpp:721
(non-blocking) The new branch checks only `iter.input_dtype() != iter.dtype()`,
then hardcodes `out_t = float`. The PR removes the `static_assert` that guarded
the identity map's same-dtype assumption, so nothing checks this precondition
any more. No caller can hit this today, but a future iterator with bf16 input
and, say, double output would write the wrong element width: float stores for
partial reductions, and a bf16 store through the `else` at line 701 for full
reductions. `cascade_powsum_kernel` in the same file (lines 756760) checks both
dtypes. Either tighten the condition to
`isReducedFloatingType(iter.input_dtype()) && iter.dtype() == kFloat`, or add
`TORCH_INTERNAL_ASSERT(iter.dtype() == kFloat)` in the branch.

[minor] aten/src/ATen/native/ReduceOps.cpp:1486
(non-blocking) The PR deletes the comment about materializing the FP32 copy, but
the comment kept above it (lines 1474-1476) still describes the CPU flow as
`cast_fp32 -> sum -> div -> cast_bf16_or_fp16`. The input is no longer cast; it
is accumulated in fp32. Suggested wording: "accumulate in fp32 -> div -> cast".

[minor] test/test_reductions.py:1422
(non-blocking) `test_sum_lowp_float_out` calls `t.double()` but has no `@​
skipIfMPS`. `TestReductionsDevice` is instantiated with `allow_mps=True` (line
4310), and MPS has no float64. The neighbouring `test_sum_noncontig_lowp` (line
1374) and other float64 tests in this class (e.g. lines 551 and 2928) skip MPS
for this reason. CI's MPS job doesn't run this file, so only local and
out-of-tree MPS runs will hit the failure.

[minor] aten/src/ATen/native/cpu/SumKernel.cpp:677
(non-blocking) Bitwise results change: CPU `sum(bf16/fp16, dtype=float)` and
`mean(bf16/fp16)` won't be bit-identical to earlier releases. Accuracy is not
worse; both paths accumulate in fp32. Two things change the summation order:
`InnerSumCastLoadPolicy` (`SumKernel.cpp:116-130`) now loads a full bf16 vector,
converts it to two float vectors and adds them before accumulating; and
multithreaded full reductions now combine per-thread results with `std::plus` in
`at::parallel_reduce` instead of the cascade loop in `two_pass_reduction`. The
description says "BC-breaking? No" and doesn't mention this. Please note the
last-bit change in the release notes, since downstream tests comparing exactly
against old outputs may change. The `release notes: linalg_frontend` label also
looks wrong for a CPU sum/mean change.

[info] aten/src/ATen/native/ReduceOps.cpp:1313
(non-blocking follow-up) The accumulation-buffer path for permuted same-dtype
bf16/fp16 sums (issue # 83149) at line 1328 still runs
`at::sum_outf(self.to(ScalarType::Float), ...)`, which makes the full float copy
this PR removes elsewhere. Fix: `at::sum_outf(self, opt_dim, keepdim,
/*dtype=*/kFloat, tmp_output)`. The meta function accepts this call, and
`mean_out` already makes it at line 1486. On re-entry `cpu_lowp_to_f32` is true
and `should_use_acc_buffer` returns false, so the recursion ends at `sum_stub`.
The kernel accumulates straight into the float buffer, so the fix for # 83149
still holds.

Reviewed commit: 35d10e8

Review run

🐛 Report a bad review

🔗 Helpful Links

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

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

⚠️ 5 Awaiting Approval

As of commit 35d10e8 with merge base 87f51fb (image):

AWAITING APPROVAL - The following workflows need approval before CI can run:

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 Nov 4, 2026
@vadimkantorov

Copy link
Copy Markdown
Contributor

Maybe related issue, but for (bool, int32) pair:

@egeboy35

egeboy35 commented Nov 7, 2026

Copy link
Copy Markdown
Contributor Author

Thanks for the pointer! #55366 is the integer side of the same problem. I have a local fix for it and posted the details and numbers there: #55366 (comment)

Drafted with Claude (AI) and edited by me.

`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]>
@egeboy35
egeboy35 force-pushed the cpu-lowp-sum-float-out branch from 2c2728c to 35d10e8 Compare November 18, 2026 22:20
@egeboy35
egeboy35 marked this pull request as ready for review November 18, 2026 22:24
@github-actions
github-actions Bot requested a review from frost-intel November 18, 2026 22:26
@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 Nov 18, 2026
@pytorch-bot pytorch-bot Bot added the in progress PR is being worked on by the author, until the automated review accepts it label Nov 18, 2026

@github-actions github-actions Bot 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.

Automated review of 35d10e8: nothing blocking; ready for human review.

On CPU, the PR makes bfloat16/float16 sum(dtype=torch.float32) and mean read the low-precision input directly and accumulate in float, instead of first making a float32 copy, and the review found no correctness, security or backward-compatibility bugs. Recommendation: Approve, with every point raised labelled non-blocking.

⚪ 5 non-blocking findings

if (iter.input_dtype() != iter.dtype()) {

(non-blocking) The new branch checks only iter.input_dtype() != iter.dtype(), then hardcodes out_t = float. The PR removes the static_assert that guarded the identity map's same-dtype assumption, so nothing checks this precondition any more. No caller can hit this today, but a future iterator with bf16 input and, say, double output would write the wrong element width: float stores for partial reductions, and a bf16 store through the else at line 701 for full reductions. cascade_powsum_kernel in the same file (lines 756760) checks both dtypes. Either tighten the condition to isReducedFloatingType(iter.input_dtype()) &amp;&amp; iter.dtype() == kFloat, or add TORCH_INTERNAL_ASSERT(iter.dtype() == kFloat) in the branch.


at::sum_out(result_temp, self, opt_dim, keepdim, sum_out_dtype).div_(dim_prod);

(non-blocking) The PR deletes the comment about materializing the FP32 copy, but the comment kept above it (lines 1474-1476) still describes the CPU flow as cast_fp32 -&gt; sum -&gt; div -&gt; cast_bf16_or_fp16. The input is no longer cast; it is accumulated in fp32. Suggested wording: "accumulate in fp32 -> div -> cast".


ref = t.double().sum(dim)

(non-blocking) test_sum_lowp_float_out calls t.double() but has no @ skipIfMPS. TestReductionsDevice is instantiated with allow_mps=True (line 4310), and MPS has no float64. The neighbouring test_sum_noncontig_lowp (line 1374) and other float64 tests in this class (e.g. lines 551 and 2928) skip MPS for this reason. CI's MPS job doesn't run this file, so only local and out-of-tree MPS runs will hit the failure.


if constexpr (!is_identity || !std::is_same_v<scalar_t, out_t>) {

(non-blocking) Bitwise results change: CPU sum(bf16/fp16, dtype=float) and mean(bf16/fp16) won't be bit-identical to earlier releases. Accuracy is not worse; both paths accumulate in fp32. Two things change the summation order: InnerSumCastLoadPolicy (SumKernel.cpp:116-130) now loads a full bf16 vector, converts it to two float vectors and adds them before accumulating; and multithreaded full reductions now combine per-thread results with std::plus in at::parallel_reduce instead of the cascade loop in two_pass_reduction. The description says "BC-breaking? No" and doesn't mention this. Please note the last-bit change in the release notes, since downstream tests comparing exactly against old outputs may change. The release notes: linalg_frontend label also looks wrong for a CPU sum/mean change.


at::isReducedFloatingType(self.scalar_type()) && result.scalar_type() == kFloat;

(non-blocking follow-up) The accumulation-buffer path for permuted same-dtype bf16/fp16 sums (issue # 83149) at line 1328 still runs at::sum_outf(self.to(ScalarType::Float), ...), which makes the full float copy this PR removes elsewhere. Fix: at::sum_outf(self, opt_dim, keepdim, /*dtype=*/kFloat, tmp_output). The meta function accepts this call, and mean_out already makes it at line 1486. On re-entry cpu_lowp_to_f32 is true and should_use_acc_buffer returns false, so the recursion ends at sum_stub. The kernel accumulates straight into the float buffer, so the fix for # 83149 still holds.

This review is AI-generated and advisory. Each new automated review replaces the previous one. Report a bad review

@pytorch-bot pytorch-bot Bot added ready for review Automated review passed, ready for a final review by a maintainer. and removed in progress PR is being worked on by the author, until the automated review accepts it labels Nov 18, 2026
@vadimkantorov

Copy link
Copy Markdown
Contributor

For CUDA, it would still copy?

@egeboy35

Copy link
Copy Markdown
Contributor Author

@vadimkantorov I was wondering about that too, so I looked into the GPU path. It turns out there's no copy happening there. I've included the details below.

Drafted by Claude (AI) for @egeboy35.

No. On CUDA and XPU, make_reduction_from_out_ty keeps a bfloat16/float16 input as is when the output is float32 (gpu_lowp_to_f32 in ReduceOpsUtils.h), and the non-CPU branch of mean_out builds its iterator through the same function before calling mean_stub, so neither makes a float32 copy there. On CPU the same function picks float32 as the input dtype, so make_reduction reduced self.to(kFloat), and CPU mean_out computes bfloat16/float16 means through sum_out(dtype=float). This PR only changes the CPU case (cpu_lowp_to_f32 is gated on self.is_cpu()).

@egeboy35

egeboy35 commented Dec 2, 2026

Copy link
Copy Markdown
Contributor Author

@frost-intel Would you mind taking a look at this PR when you get a chance?

Drafted by Claude (AI), edited by @egeboy35.

This addresses #202882 by accumulating directly in float on CPU for bfloat16/float16 mean and sum(dtype=torch.float32), avoiding an intermediate float32 copy of the input.

The automated review on Nov 18 found no blocking issues. I've also addressed vadimkantorov's question about CUDA above — that path doesn't make a copy.

This branch was previously deployed

1 inactive deployment
bedrock — 35d10e82 Deployed Nov 18, 2026 by egeboy35
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 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 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.

CPU mean and sum(dtype=torch.float32) are 4–12x slower on bfloat16/float16 tensors because they convert the entire input to float32 first.

3 participants