Skip to content

[caffe2/veclib] Fix aarch64 f32->u8 type conversion divergence (#196646) - #196646

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

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

Conversation

@Nicoshev

@Nicoshev Nicoshev commented Sep 10, 2026 •

Copy link
Copy Markdown
Contributor

Summary:

Fix NEON/SVE vectorized f32->u8 quant conversion routines having a different behaviour than c10::convert/AVX

The inputs differing are out-of-range

f32->uint8_t has well defined behaviour in TypeCast.h, supporting inputs fitting up to an int64_t, to get consistent results across CPU/GPU

Addresses: github.com//issues/168972

Test Plan: CI

Reviewed By: Rajeev975

Differential Revision: D119352973

cc @jgong5 @mingfeima @XiaobingSuper @sanchitintel @ashokei @jingxu10 @aditew01 @voznesenskym @penguinwu @EikanWang @Guobing-Chen @zhuhaozhe @blzheng @wenzhe-nrv @jiayisunx @ipiszy @kadeng @muchulee8 @amjames @chauhang @aakhundov @coconutruben @jataylo

@pytorch-bot

pytorch-bot Bot commented Sep 10, 2026 •

Copy link
Copy Markdown

🔗 Helpful Links

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

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

✅ You can merge normally! (2 Unrelated Failures)

As of commit 13caca3 with merge base 253d0a2 (image):

UNSTABLE - The following jobs are marked as unstable, possibly due to flakiness on trunk:

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 10, 2026
@meta-codesync

meta-codesync Bot commented Sep 10, 2026

Copy link
Copy Markdown

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

@Nicoshev Nicoshev added the ciflow/linux-aarch64 linux aarch64 CI workflow label Sep 10, 2026
@pytorch-bot

pytorch-bot Bot commented Sep 10, 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

@Nicoshev Nicoshev added the ciflow/trunk Trigger trunk jobs on your pull request label Sep 10, 2026
@meta-codesync meta-codesync Bot changed the title [caffe2/veclib] Fix NEON f32->i8/u8 type conversion divergence [caffe2/veclib] Fix NEON f32->i8/u8 type conversion divergence (#196646) Sep 10, 2026
Nicoshev added a commit to Nicoshev/pytorch that referenced this pull request Sep 10, 2026
…ch#196646)

Summary:

Fix NEON vectorized f32->i8/u8 conversion routines have a different behaviour than c10::convert/AVX

The inputs differing are out-of-range, but f32->uint8_t has well defined behaviour in TypeCast.h to get consistent results across CPU/GPU

f32->int8_t has well defined behaviour in AVX headers, clamping to support inputs fitting int32_ts

Test Plan: CI

Differential Revision: D119352973
@Skylion007

Copy link
Copy Markdown
Collaborator

@claude review this PR

@claude

claude Bot commented Sep 11, 2026 •

Copy link
Copy Markdown

Claude finished @Skylion007's task in 42m 7s —— View job


The uint8_t half of this fix looks correct and well-motivated, but the int8_t half changes ARM's eager .to(torch.int8) from low-byte truncation to saturation, which creates a new ARM-vs-x86 divergence rather than removing one — and the xfailIf(IS_ARM64) on test_float32_to_uint8 still needs to be dropped for CI to go green.

Full review

Review checklist

  • Read PR diff (aten/src/ATen/cpu/vec/vec128/vec128_convert.h, +105)
  • Verify NEON intrinsic sequences (lane ordering, zero-fill, saturation points)
  • Compare against c10::convert / TypeCast.h and the AVX2 convert_float_to_int8
  • Check the reported CI failure
  • Check test coverage

Blocking

1. @xfailIf(IS_ARM64) must be removed — this is the reported CI failure

test/inductor/test_cpu_repro.py:5935 still carries the xfail, so the test now reports "Unexpected success" and fails. Dr. CI already caught this. The referenced issue #168972 is what this PR fixes, so the decorator (and its comment) should go.

    @xfailIf(IS_ARM64)  # see https://github.com/pytorch/pytorch/issues/168972
    def test_float32_to_uint8(self):

Fix this →


Correctness concerns

2. The int8_t change makes ARM eager diverge from x86 eager (opposite of the stated goal)

convertImpl<float, int8_t> (lines 25–37) is the buffer-level at::vec::convert(const float*, int8_t*, n) used by the eager copy kernel (aten/src/ATen/native/cpu/CopyKernel.cpp:307), not the inductor vector path. On x86 there is no specialization for this pair, so it falls through to the generic at::vec::convert in vec_base.h:1480, which calls c10::convert<int8_t> → plain static_cast<int8_t>(float) → low-byte truncation.

Concretely, torch.tensor([300.0]).to(torch.int8):

before after
x86 eager 44 44
ARM eager (clang-17+) 44 127

The pre-existing ARM/x86 divergence for f32→i8 is much narrower than the PR implies: both platforms truncate the low byte for anything inside int32 range. They only differ once |f| >= 2^31, where aarch64's fcvtzs saturates to INT32_MAX (low byte 0xff) while x86's cvttss2si produces the integer-indefinite value (low byte 0x00). Clamping to [-128, 127] changes the result for every out-of-int8 input, including the whole [128, 2^31) range where the two platforms already agreed.

The PR description justifies this with "f32->int8_t has well defined behaviour in AVX headers, clamping to support inputs fitting int32_ts" — but that clamping lives in convert_float_to_int8<int8_t> (vec256_qint.h:130), which backs the Vectorized path (VecConvert<int8_t,1,float,n>), not the buffer path. Applying it to convertImpl conflates the two. Making the new VecConvert<int8_t, ...> saturate to match AVX2 is defensible; also changing convertImpl is what introduces the regression.

Which target is intended here — x86 eager (c10::convert, low byte) or AVX2/CUDA vec (saturate)? Note CUDA's cvt.rzi.s8.f32 does saturate, so if saturation is the desired canonical semantics, that's a reasonable position — but then it should be a deliberate, documented, cross-platform change (including x86's c10::convert), not an ARM-only one.

3. Same-arch behavior now depends on the host compiler

The convertImpl specializations sit inside #if defined(__clang__) && (__clang_major__ >= 17) (line 12), while the new VecConvert specializations at 369–447 are outside it. So on a GCC aarch64 build, at::vec::convert(float*, int8_t*, n) keeps c10::convert truncation while the clang build saturates. Eager .to(torch.int8) output would then differ between two ARM builds of the same source. The uint8_t case is fine here (GCC's generic path already goes through the int64_t intermediate), but the int8_t case makes the compiler user-visible.

4. src_n == 3 (and src_n >= 5) silently drop elements

Both helpers are templated on unconstrained src_n, and the else if constexpr (src_n >= 2) branch only ever reads src[0] and src[1]:

} else if constexpr (src_n >= 2) {
    return vcombine_s8(vqmovn_s16(to_i16(src[0], src[1])), zero);
}

For src_n == 3 this converts 8 of 12 elements and zero-fills the rest; the generic fallback it replaces converted min(12, 16) = 12. Same for any src_n > 4. Today inductor only produces src_n ∈ {1, 2} on NEON (_get_num_vectors = ceil(tiling_factor * 4 * 8 / 128) with tiling_factor ∈ {4, 8}, cpp.py:2903), so it isn't reachable — but a silently-wrong specialization that shadows a correct generic fallback is a bad trap to leave for whoever changes the tiling factor. Please constrain it: static_assert(src_n <= 4), or enable_if_t<src_n <= 4> so out-of-range src_n falls back to the generic path, or handle the general case.


Performance

5. The f32 -> f64 -> s64 widening for uint8_t is unnecessary — the "true low byte" above 2^31 is always zero

The comment at 398–403 says converting via int32_t "would report 0xff rather than the true low byte across [2^31, 2^63)". The premise is misleading: every float in that range is an exact multiple of 256, so its true low byte is always 0.

A float of magnitude v >= 2^31 is M * 2^(e-23) with M ∈ [2^23, 2^24) and e >= 31, so e - 23 >= 8 and v is divisible by 2^8. The int64_t truncation is exact, hence low byte 0.

So the elaborate double-widening path buys exactly "0 instead of 0xff", which a mask gets far more cheaply. Roughly:

const float32x4_t bound = vdupq_n_f32(2147483648.0f);  // 2^31
int32x4_t i = vcvtq_s32_f32(f);
// |f| >= 2^31 saturates; its true low byte is 0 (any such float is a
// multiple of 256), so clear those lanes instead of keeping 0x7fffffff.
i = vbicq_s32(i, vreinterpretq_s32_u32(vcageq_f32(f, bound)));

That's ~2 extra instructions per 4 lanes versus the current 2xfcvtl + 2xfcvtzs.s64 per 4 lanes (plus it keeps the source in a single register width, so the final byte extraction needs one tbl/xtn chain rather than two vqtbl4q_u8). NaN still lands on 0 (vcageq is false, fcvtzs(NaN) == 0), matching c10::convert on aarch64. It also happens to match x86 above 2^63, where the current version yields 0xff and x86 yields 0x00.

This matters most for the scalar convertImpl<float, uint8_t> at 39–48: static_cast<uint8_t>(static_cast<int64_t>(src[i])) forces clang to emit the f32 -> f64 -> s64 widening, roughly 2-4x the work of the previous s32 lowering, on the eager .to(torch.uint8) copy kernel — a very common op in image preprocessing. Some numbers on that path would be good to see. (I haven't benchmarked either version, so treat the estimates as directional.)

6. vqtbl4q_u8 is oversized in the src_n == 4 path

low_bytes builds a 4-register (64-byte) table and indexes {0, 8, ..., 56, 64, ..., 120}, relying on indices >= 64 returning zero. That's correct per ARM semantics and load-bearing for the src_n <= 2 cases, where the zeros are exactly the required zero-fill. But in the src_n == 4 branch the upper 8 indices are pure waste, since both results are immediately vget_low_u8'd. vqtbl4_u8 with a uint8x8_t index vector gives the same 8 bytes at half the shuffle cost.


Testing

7. No test exercises any of the fixed behavior

The whole PR is about out-of-range inputs, but the C++ vec suite can't see them: test_convert_to in aten/src/ATen/test/vec_test_all_types.cpp:2206 generates values in [-100, 100] (or [0, 100] for unsigned), where old and new code agree bit-for-bit. test_float32_to_uint8 only covers [-1, -4].

Given how subtle the saturation boundaries are (2^31, 2^63, NaN, int8 vs int32 clamp points), please add a targeted test over out-of-range floats — something like {-1e10, -300, -129, -1, 0, 127, 128, 300, 1e10, 2^31, 2^63, NaN, inf} — asserting both the buffer path (at::vec::convert(ptr, ptr, n)) and the Vectorized path against c10::convert<dst_t>. Note the existing helper's reference is static_cast<dst_t>(x[i]), which is not c10::convert semantics for uint8_t (no int64_t intermediate), so a new test should compare against c10::convert directly. This also pins the behavior so a future perf rewrite of these intrinsics can't silently regress it.


Minor / style

8. Name collides conceptually with the AVX helpers. convert_float_to_int8 here returns a raw int8x16_t and takes a VectorizedN<float, src_n>, whereas convert_float_to_int8<T> in vec256_qint.h:126 / vec512_qint.h:128 takes a Vectorized<float> and returns Vectorized<T>. No ODR problem (separate CPU_CAPABILITY builds, and the aarch64 block of vec256_qint.h:1394 only defines convert_int8_to_float), but reusing the name with a different signature and different semantics is a readability trap. Consider convert_float_to_int8_neon, or match the existing convention and return Vectorized<int8_t>.

9. Missing <limits> include. The file now uses std::numeric_limits directly (lines 34–35) but neither it nor its includes pull in <limits>. It compiles transitively today (and vec_convert.h:49 already leans on the same thing), so this is IWYU hygiene, not a bug. std::clamp is fine — <algorithm> comes in via vec_base.h:22.

10. const int8x8_t zero = vdup_n_s8(0); (line 377) is dead in the src_n == 4 instantiation. Harmless (DCE'd, and no warning since it's referenced in a discarded branch), but moving it into the branches that use it would read better.

11. Little-endian assumption. vreinterpretq_u8_s64 + the {0, 8, 16, ...} index constant assume LE byte order. Fine for PyTorch's supported aarch64 targets; noting it only because the index table would silently produce the high bytes on BE.


Remaining divergence (follow-up, not this PR)

VecRoundConvert is untouched, so at::vec::round_convert<uint8_t> on aarch64 still uses the generic implementation in vec_convert.h:40, which clamps to [0, 255] (300.0 -> 255). AVX2's round_convert_float_to_int8<uint8_t> (vec256_qint.h:197) clamps to int32 bounds and then takes the low byte (300.0 -> 44). That's the same class of bug in the sibling code path and likely affects quantized inductor kernels. Worth a follow-up issue if it isn't already tracked.


What I verified

I traced the intrinsic sequences by hand and they are internally self-consistent, which is the good news:

  • Lane ordering is correct in every branch. For int8, to_i16(src[0], src[1]) yields int16 lanes [f0..f3, f4..f7], and vqmovn_s16 + vcombine_s8 assembles [f0..f15]. For uint8, the table registers a=lo(src[0]), b=hi(src[0]), c=lo(src[1]), d=hi(src[1]) map to byte offsets 0/8, 16/24, 32/40, 48/56, so the index constant reads f0..f7 in order.
  • Zero-fill matches the VectorizedN::loadu(buf, count) semantics of the fallback in vec_convert.h:26 for src_n ∈ {1, 2, 4}.
  • Scalar and vector paths agree with each other on ARM. int8: vqmovn_s32 then vqmovn_s16 saturates at [-32768, 32767] then [-128, 127], matching clamp(static_cast<int32_t>(f), -128, 127) at every boundary including ±1e10 and NaN. uint8: the vqtbl4q low-byte extraction from the s64 conversion matches static_cast<uint8_t>(static_cast<int64_t>(f)), including saturation at the int64 bounds.
  • No template ambiguity introduced. VecConvert<dst_t, dst_n, src_t, src_n, enable_if_t<is_same_v<dst_t, src_t> && ...>> at vec_convert.h:61 SFINAEs out for float -> int8_t, and the is_8bit_integer_v specializations at 346/357 go the other direction.
  • uint8_t is genuinely broken today and this PR fixes it: pre-PR clang-17+ ARM did static_cast<uint8_t>(src[i]), which for 1e10f saturates through int32 to 0xff, whereas c10::convert<uint8_t> (TypeCast.h:98-108, which routes through int64_t specifically for CPU/GPU consistency) gives 0. That half of the diff is the right fix; my concerns are the int8_t direction, the src_n guard, and the cost of the chosen uint8_t lowering.

I did not build or run anything — no ARM64 hardware in this environment, and a PyTorch build plus the aarch64 vec test suite is out of reach here. All findings above are from reading the intrinsic semantics and the surrounding dispatch, so the behavior tables should be confirmed on real hardware before acting on them.

| Branch: `export-D119352973`

@Skylion007 Skylion007 added the release notes: cpu (aarch64) release notes category for aarch64, arm, etc. label Sep 11, 2026
@meta-codesync meta-codesync Bot changed the title [caffe2/veclib] Fix NEON f32->i8/u8 type conversion divergence (#196646) [caffe2/veclib] Fix NEON f32->u8 type conversion divergence (#196646) Sep 11, 2026
Nicoshev added a commit to Nicoshev/pytorch that referenced this pull request Sep 11, 2026
…196646)

Summary:

Fix NEON vectorized f32->u8 quant conversion routines have a different behaviour than c10::convert/AVX

The inputs differing are out-of-range

f32->uint8_t has well defined behaviour in TypeCast.h, supporting inputs fitting up to an int64_t, to get consistent results across CPU/GPU

Addresses: github.com/pytorch/issues/168972

Test Plan: CI

Differential Revision: D119352973
@Nicoshev

Copy link
Copy Markdown
Contributor Author

@Skylion007 @aditew01 I just changed the PR to only change f32->u8 behaviour, which has consensus and has been reported as broken in github.com/pytorch/pytorch/issues/168972

I'll leave f32->i8 for another PR, as it has greater divergencies across platforms

@Nicoshev
Nicoshev requested a review from Skylion007 September 11, 2026 18:46
Nicoshev added a commit to Nicoshev/pytorch that referenced this pull request Sep 11, 2026
…196646)

Summary:

Fix NEON vectorized f32->u8 quant conversion routines have a different behaviour than c10::convert/AVX

The inputs differing are out-of-range

f32->uint8_t has well defined behaviour in TypeCast.h, supporting inputs fitting up to an int64_t, to get consistent results across CPU/GPU

Addresses: github.com/pytorch/issues/168972

Test Plan: CI

Differential Revision: D119352973
Nicoshev added a commit to Nicoshev/pytorch that referenced this pull request Sep 11, 2026
…196646)

Summary:

Fix NEON vectorized f32->u8 quant conversion routines have a different behaviour than c10::convert/AVX

The inputs differing are out-of-range

f32->uint8_t has well defined behaviour in TypeCast.h, supporting inputs fitting up to an int64_t, to get consistent results across CPU/GPU

Addresses: github.com/pytorch/issues/168972

Test Plan: CI

Differential Revision: D119352973
Nicoshev added a commit to Nicoshev/pytorch that referenced this pull request Sep 11, 2026
…196646)

Summary:

Fix NEON vectorized f32->u8 quant conversion routines have a different behaviour than c10::convert/AVX

The inputs differing are out-of-range

f32->uint8_t has well defined behaviour in TypeCast.h, supporting inputs fitting up to an int64_t, to get consistent results across CPU/GPU

Addresses: github.com/pytorch/issues/168972

Test Plan: CI

Differential Revision: D119352973
Nicoshev added a commit to Nicoshev/pytorch that referenced this pull request Sep 11, 2026
…196646)

Summary:
Pull Request resolved: pytorch#196646

Fix NEON vectorized f32->u8 quant conversion routines have a different behaviour than c10::convert/AVX

The inputs differing are out-of-range

f32->uint8_t has well defined behaviour in TypeCast.h, supporting inputs fitting up to an int64_t, to get consistent results across CPU/GPU

Addresses: github.com/pytorch/issues/168972

Test Plan: CI

Reviewed By: Rajeev975

Differential Revision: D119352973
@meta-codesync

meta-codesync Bot commented Sep 14, 2026

Copy link
Copy Markdown

@pytorchbot merge -i

(Initiating merge automatically since Phabricator Diff has merged, merging with -i because oss signals were bypassed internally)

@pytorchmergebot

Copy link
Copy Markdown
Collaborator

Merge failed

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

  • CPU inductor (leslie-fang-intel, jgong5, EikanWang, CaoE)
  • Metamates (aditvenk, AmesingFlank, amirafzali, angelayi, 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 Author

@pytorchbot merge -f "CI failures are unrelated"

@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

@pytorchmergebot

Copy link
Copy Markdown
Collaborator

Merge failed

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

  • CPU inductor (leslie-fang-intel, jgong5, EikanWang, CaoE)
  • Metamates (aditvenk, AmesingFlank, amirafzali, angelayi, 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 Author

@pytorchbot merge -f "CI failures are unrelated"

@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

@malfet

malfet commented Sep 27, 2026

Copy link
Copy Markdown
Collaborator

Hmm, it did not fix anything, as it tries to force certain behavior out of compiler, which is absolutely not guaranteed. Root cause of the failure is that casting negative to unsigned type results in undefined behavior, from C99/C11 6.3.1.4

When a finite value of real floating type is converted to an integer type other than _Bool, the fractional part is discarded (i.e., the value is truncated toward zero). If the value of the integral part cannot be represented by the integer type, the behavior is undefined.

malfet added a commit to huydhn/pytorch that referenced this pull request Sep 27, 2026
…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). pytorch#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 pytorch#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 pytorch#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 pytorch#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]>
@Flamefire

Copy link
Copy Markdown
Collaborator

It fixes the UB you quoted in the vectorized part. The eager part does not have this issue because it does not use real->unsigned conversion: it does real->signed->unsigned

So either PyTorch contains superflous code in the eager part or this does fix an actual issue.

It basically depends on how PyTorch defines the "cast operator", not how C++ defines it.
The existing code and this PR define it as "mod N"-wrapping for reals similar to signed->unsigned. And that is guaranteed behavior, not dependent on undefined or implementation defined behavior.

pytorchmergebot pushed a commit that referenced this pull request Sep 29, 2026
…198744)

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](https://claude.com/claude-code)

Pull Request resolved: #198744
Approved by: https://github.com/huydhn

Co-authored-by: Claude Opus 5.5 <[email protected]>
pytorchmergebot pushed a commit to AlekseiNikiforovIBM/pytorch that referenced this pull request Oct 26, 2026
Make it similar to aarch64 fix in PR pytorch#196646

This change fixes test test_float32_to_uint8
in test/inductor/test_cpu_repro.py.
AlekseiNikiforovIBM added a commit to AlekseiNikiforovIBM/pytorch that referenced this pull request Oct 27, 2026
Make it similar to aarch64 fix in PR pytorch#196646

This change fixes test test_float32_to_uint8
in test/inductor/test_cpu_repro.py.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

ciflow/inductor 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) module: inductor release notes: cpu (aarch64) release notes category for aarch64, arm, etc.

Projects

None yet

Development

Successfully merging this pull request may close these issues.

7 participants