Repository navigation
Conversation
…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]>
🔗 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 FailuresAs of commit 4d63c3d with merge base d1529c3 ( This comment was automatically generated by Dr. CI and updates every 15 minutes. |
Co-Authored-By: Claude Opus 5.5 <[email protected]>
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]>
|
@pytorchbot merge |
Merge failedReason: Approvers from one of the following sets are needed:
|
|
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 <> Using native fp16/bf16 types allows better autovectorization. |
|
We should also add matching VecConvert specializations, otherwise casting a single vector variable may yield different results than casting a tensor |
Nicoshev
left a comment
There was a problem hiding this comment.
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 |
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. |
|
@claude Review this change, does it have any side effects? |
|
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: #198744SummaryOn aarch64, this PR sends contiguous Scope of the behavior change:
Code Quality
Performance
Out of scope, not introduced here
RecommendationApprove. The change is contained and matches existing CPU/CUDA/strided behavior, and the existing |
Let's do it as followup, now time to fix CI
|
@pytorchbot merge -f "Lint + trunk jobs are green" |
Merge startedYour change will be merged immediately since you used the force (-f) flag, bypassing any CI checks (ETA: 1-5 minutes). Please use Learn more about merging in the wiki. Questions? Feedback? Please reach out to the PyTorch DevX Team |
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