Skip to content

[aarch64] Match c10::convert for contiguous half/bfloat16 -> uint8 - #198744

Closed
malfet wants to merge 3 commits into
mainfrom
malfet/aarch64-uint8-via-int32
Closed

malfet wants to merge 3 commits into
mainfrom
malfet/aarch64-uint8-via-int32

Conversation

@malfet

@malfet malfet commented Sep 27, 2026 •

Copy link
Copy Markdown
Collaborator

On aarch64, contiguous x.byte() for float16/bfloat16 still does a direct static_cast<uint8_t>, which clang lowers to a saturating fcvtzu (-1 -> 0), while strided copies go through c10::convert, which narrows via int64 (-1 -> 255). This breaks test_non_contig_byte_cpu_{float16,bfloat16}, test_contig_vs_every_other_byte_cpu_{float16,bfloat16} and their _refs variants on Apple Silicon (e.g. https://github.com/pytorch/pytorch/actions/runs/36282025606/job/108516516926). #196646 fixed the same mismatch for float32, but by widening to int64, which on NEON means going through float64 and halves the lane count.

This makes operations ridiculously slow, but match the wrapped-around cast behavior. Probably follow up PR is to kill the test, as uniform behavior is not something one should worry about for UB-values

🤖 Generated with Claude Code

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

…onvert

On aarch64, contiguous `x.byte()` for float16/bfloat16 still does a direct `static_cast<uint8_t>`, which clang lowers to a saturating `fcvtzu` (-1 -> 0), while strided copies go through `c10::convert`, which narrows via int64 (-1 -> 255). This breaks `test_non_contig_byte_cpu_{float16,bfloat16}`, `test_contig_vs_every_other_byte_cpu_{float16,bfloat16}` and their `_refs` variants on Apple Silicon (e.g. https://github.com/pytorch/pytorch/actions/runs/36282025606/job/108516516926). #196646 fixed the same mismatch for float32, but by widening to int64, which on NEON means going through float64 and halves the lane count.

This adds float16/bfloat16 specializations and switches float32 to narrow via int32 instead, using the fact that a type with p significant bits has only multiples of 256 above 2^(p+7): every finite fp16 fits in int32; bf16 is clamped to +-2^16; float32 maps |x| >= 2^31 to 0. All three match `c10::convert` bit for bit wherever it is defined (|x| < 2^63), verified exhaustively for every float16, bfloat16 and float32 bit pattern.

Performance of `x.byte()`, 4M elements, single thread, M5 Pro (us):

| dtype    | main | this PR |
|----------|------|---------|
| float32  | 353  | 294     |
| float16  | 101  | 172     |
| bfloat16 | 170  | 281     |

For reference, a direct (UB) float32 -> uint8 cast takes ~180us, so the defined float32 path is now ~1.6x the plain cast instead of ~2x.

Question for reviewers: does defining this behavior make sense at all? `torch.Tensor.to` documents that when the truncated value cannot fit into the target type "the behavior is undefined and the result may vary across platforms", so the int64 wraparound is a convention that dates back to #36807 (CPU/CUDA consistency) rather than a documented contract. Keeping it costs ~1.7x for float16/bfloat16 relative to the plain cast. The alternative is to drop the int64 convention on the vectorized paths (including #196646's) and restrict the `byte` OpInfo's test inputs to the uint8 range (`domain=(0, None)`), accepting that contiguous and strided copies may disagree on out-of-range values.

The register-level `VecConvert<uint8_t, 1, float, N>` from #196646 (used by inductor) is left unchanged; it still narrows via int64 and gives identical results.

Test Plan:
```
python -m pytest test/test_unary_ufuncs.py test/test_ops.py -k "cpu and (byte or char or uint8 or _refs__conversions or float16 and to)"   # 5560 passed
python -m pytest test/test_torch.py test/test_type_promotion.py -k "cpu and (uint8 or byte or cast or copy or to_)"   # 219 passed
```
plus exhaustive bit-pattern checks of contiguous vs strided vs `x.double().to(torch.int64).to(torch.uint8)`.

This PR was authored with the help of an AI assistant (Claude Code).

Co-Authored-By: Claude Opus 5.5 <[email protected]>
@pytorch-bot

pytorch-bot Bot commented Sep 27, 2026 •

Copy link
Copy Markdown

🔗 Helpful Links

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

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

✅ No Failures

As of commit 4d63c3d with merge base d1529c3 (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 27, 2026
@malfet
malfet marked this pull request as ready for review September 27, 2026 02:38
@malfet malfet added the ciflow/trunk Trigger trunk jobs on your pull request label Sep 27, 2026
@malfet malfet added topic: bug fixes topic category release notes: cpu (aarch64) release notes category for aarch64, arm, etc. labels Sep 27, 2026
The int32 routes matched c10::convert for every finite input below 2^63, but not for +inf and larger values, where the scalar int64 route saturates to 0xff. That made contiguous and strided copies disagree again for those inputs and broke test_float_to_int_conversion_nonfinite_cpu_uint8 on ARM64. Use the same int64 narrowing for all three dtypes so contiguous and strided results are identical for every input.

Test Plan:
```
python test/test_tensor_creation_ops.py -k float_to_int_conversion   # 12 passed
python -m pytest test/test_unary_ufuncs.py test/test_ops.py -k "cpu and (byte or char or uint8 or _refs__conversions or float16 and to)"   # 5560 passed
```
plus contiguous vs strided equality over every float16/bfloat16 bit pattern (incl. inf/nan) and 16M random float32 values.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
@malfet malfet changed the title [aarch64] Narrow float/half/bfloat16 -> uint8 via int32 in at::vec::convert [aarch64] Match c10::convert for contiguous half/bfloat16 -> uint8 Sep 27, 2026

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

Good catch

@Nicoshev

Copy link
Copy Markdown
Contributor

@pytorchbot merge

@pytorchmergebot

Copy link
Copy Markdown
Collaborator

Merge failed

Reason: Approvers from one of the following sets are needed:

  • CPU ATen backend (mingfeima, XiaobingSuper, jgong5, vfdev-5, leslie-fang-intel, ...)
  • CPU inductor (leslie-fang-intel, jgong5, EikanWang, CaoE)
  • Metamates (aditvenk, AmesingFlank, angelayi, anshul-si, aorenste, ...)
  • Greenlight Review Bot (pytorchgreenlight)
  • Core Reviewers (mruberry, lezcano, Skylion007, ngimel, peterbell10, ...)
  • Core Maintainers (soumith, gchanan, ezyang, malfet, albanD, ...)
Details for Dev Infra team Raised by workflow job

Failing merge rule: Core Maintainers

@Nicoshev

Copy link
Copy Markdown
Contributor

The bahviour change is good, but we should instantiate the templates within the guards for fp16/bf16: __ARM_FEATURE_FP16_VECTOR_ARITHMETIC and __ARM_FEATURE_BF16.

Code should look something like:

template <>
inline void convert(const at::Half* src, uint8_t* dst, int64_t n) {
const float16_t* srcPtr = reinterpret_cast<const float16_t*>(src);
convertToUint8(srcPtr, dst, n);
}

Using native fp16/bf16 types allows better autovectorization.

@Nicoshev

Copy link
Copy Markdown
Contributor

We should also add matching VecConvert specializations, otherwise casting a single vector variable may yield different results than casting a tensor

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

Requesting changes for the VecConvert templates and native types usage

@malfet

malfet commented Sep 27, 2026

Copy link
Copy Markdown
Collaborator Author

Requesting changes for the VecConvert templates and native types usage

I don't care about perf in this case, I just want to unblock the failing test and in followup change undo all this madness, unless there is a good reason why torch.tensor([-1.0, 1, 2]).to(torch.uint8) must return (255, 1, 2) rather than (0, 1, 2)

@Nicoshev

Copy link
Copy Markdown
Contributor

__ARM_FEATURE_FP16_VECTOR_ARITHMETIC and __ARM_FEATURE_BF16

The VecConvert templates are important. Without them, using such cast falls through to the generic static_cast<dst_t> in vec_convert.h:24, which is UB when the value is out of range. This leads to inconsistent behaviour. For example, f16 negatives come out as 0 on that path (16125 patterns differ).

I agree that we should have a separate discussion on why do we enforce behaviour on UB cases in the first case. But I think that merging this plus the corresponding VecConvert templates is the right step as of today.

@huydhn

huydhn commented Sep 29, 2026

Copy link
Copy Markdown
Contributor

@claude Review this change, does it have any side effects?

@claude

claude Bot commented Sep 29, 2026 •

Copy link
Copy Markdown

Claude finished @huydhn's task in 2m 21s —— View job


The only behavior change is that contiguous half/bfloat16 → uint8 casts with out-of-range values now wrap around instead of saturating on aarch64 builds compiled with clang 17 or newer. The other side effects are a slowdown on that path and a possible new UBSan report on GCC builds.

PR Review: #198744

Summary

On aarch64, this PR sends contiguous at::vec::convert for Half/BFloat16 → uint8_t through int64_t, the same way c10::convert does. It does this by removing CONVERT_FROM_FP16_TEMPLATE(uint8_t) and CONVERT_FROM_BF16_TEMPLATE(uint8_t) and adding explicit specializations that reuse the loop already used for float32.

Scope of the behavior change:

  • Which builds: only aarch64 builds compiled with clang 17 or newer, because only they had the removed auto-vectorized specializations. GCC builds and CPU_CAPABILITY_SVE256 builds already fell back to the generic vec_base.h:1470 template, which calls c10::convert, so their results don't change. The new specializations now also compile on those builds. That's harmless: I found no conflicting SVE specialization.
  • Which calls: every caller of at::vec::convert<Half|BFloat16, uint8_t> changes, not only .byte(). The main one is the contiguous copy_ path (CopyKernel.cpp:307), so .to(torch.uint8), type_as and copy_ into a uint8 tensor are all affected.
  • Which values: only out-of-range ones. Values in [0, 256) give the same result as before. Negative and >= 256 values now wrap (-1 → 255, 256 → 0) instead of saturating (-1 → 0), which matches the strided path, x86 and CUDA. NaN and ±inf should give the same result as before (0, 255, 0), but I didn't check this exhaustively.

Code Quality

  • vec128_convert.h:21: new UBSan report on aarch64 GCC builds. convertToUint8 uses a plain static_cast<int64_t>(src[i]). c10::convert does the same narrowing through unchecked_cast_to_int, which is marked __ubsan_ignore_undefined__ (torch/headeronly/util/TypeCast.h:67-71). Those GCC builds used to take the UBSan-clean generic path, so bfloat16 inf/NaN/|x| >= 2^63 and half inf/NaN inputs would now trigger float-cast-overflow there. The same problem already exists for the float32 specialization on main.
    • Suggested fix: use dst[i] = c10::convert<uint8_t>(src[i]); in the loop. The results are identical, the code no longer duplicates the rule, and it's UBSan-clean. Fix this →
  • The Half/BFloat16 specializations may not be needed at all. Once the two uint8_t macro lines are removed, overload resolution already picks the generic vec_base.h template, which does exactly this. The only reason to keep them is the __restrict hint for auto-vectorization, and that deserves a one-line comment if it's the intent.

Performance

  • Slower on clang 17+ aarch64. The fp16 path used to be a native float16_t → uint8_t conversion. It now goes at::Half → float → int64, and converting float to int64 on NEON means widening to f64 first (2 lanes per register). Commit 8ab01ba measured the int32 variant at 101→172 µs for float16 and 170→281 µs for bfloat16 (4M elements, M5 Pro). The final int64 variant is expected to be slower still, and there are no updated numbers for it.

Out of scope, not introduced here

  • VecConvert<uint8_t, 1, Half|BFloat16, N> still falls back to the generic static_cast<dst_t> in vec_convert.h:24, so register-level casts can still disagree with tensor copies. This is the point Nicoshev raised.
    • It doesn't regress with this PR.
    • My guess is that inductor usually upcasts reduced-precision inputs to float before casting to uint8, which would take the int64-based VecConvert<uint8_t,1,float,N> path, but I didn't verify that.

Recommendation

Approve. The change is contained and matches existing CPU/CUDA/strided behavior, and the existing test_non_contig_byte / test_contig_vs_every_other_byte OpInfo tests cover it. Switching the loop body to c10::convert<uint8_t> would fix the UBSan issue at no cost. The performance regression is intentional according to the PR description.

@malfet
malfet dismissed Nicoshev’s stale review September 29, 2026 23:38

Let's do it as followup, now time to fix CI

@malfet

malfet commented Sep 29, 2026

Copy link
Copy Markdown
Collaborator Author

@pytorchbot merge -f "Lint + trunk jobs are green"

@pytorchmergebot

Copy link
Copy Markdown
Collaborator

Merge started

Your change will be merged immediately since you used the force (-f) flag, bypassing any CI checks (ETA: 1-5 minutes). Please use -f as last resort and instead consider -i/--ignore-current to continue the merge ignoring current failures. This will allow currently pending tests to finish and report signal before the merge.

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

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

ciflow/trunk Trigger trunk jobs on your pull request Merged module: cpu CPU specific problem (e.g., perf, algorithm) open source release notes: cpu (aarch64) release notes category for aarch64, arm, etc. topic: bug fixes topic category

Projects

None yet

Development

Successfully merging this pull request may close these issues.

5 participants