Compute floor_divide in float for Half and BFloat16 - #193766
Open
krrishapatel wants to merge 1 commit into
Open
Conversation
torch.floor_divide computed its intermediates in the input dtype in the tensor-tensor CPU and CUDA kernels, but widened to float when the divisor was a scalar. In Half and BFloat16 a - fmod(a, b) can round back up to a, so the quotient comes out too high and the two paths disagreed. A size-1 tensor is squeezed to 0-dim and takes the scalar divisor path, so the answer depended on the length of the input. Widen the scalar loop and the vectorized loop to the op math type, which is what the scalar divisor path already did. This replaces the SVE256 bfloat16 specialization of div_floor_floating_vec, which did the same widening for one backend only and so left SVE256 disagreeing with its own scalar loop. On arm64 this is also about 9x faster for both dtypes, because Vectorized<BFloat16>::fmod and ::floor go through map/map2 and call scalar libm once per element. Fixes pytorch#193754
krrishapatel
requested review from
Aidyn-A,
eqy,
mruberry and
syed-ahmed
as code owners
August 17, 2026 05:54
🔗 Helpful Links🧪 See artifacts and rendered test results at hud.pytorch.org/pr/193766
Note: Links to docs will display an error until the docs builds have been completed. This comment was automatically generated by Dr. CI and updates every 15 minutes. |
Author
|
@pytorchbot label "release notes: python_frontend" "topic: bug fixes" "module: cuda" |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
Fixes #193754.
torch.floor_divideonbfloat16andfloat16gives a different answer depending on the length of the input:186 is right.
Cause
div_floor_kernelhas two paths. When the divisor is a scalar it dispatches throughAT_DISPATCH_REDUCED_FLOATING_TYPESand computes inopmath_t, sobfloat16runs in float. The tensor-tensor path computes inscalar_t.A size-1 tensor is squeezed to 0-dim, which makes
iter.is_scalar(2)true, so it takes the widened path. That is the whole length dependence.Staying in
bfloat16is what gets the wrong answer. From NOTE: [Floor Division in Python], the quotient is(a - fmod(a, b)) / b. For 560 and 3 that is558 / 3, but 558 needs 10 significand bits andbfloat16has 8, so it rounds to 560, and560 / 3rounds to 187.std::fmoddoes not save this.c10::BFloat16has its own overload returningc10::BFloat16, so every step inc10::div_floor_floatingrounds.The error is not bounded to one unit either. Over 4096 random values the largest difference from float math was 64.
Fix
Widen both loops in the tensor-tensor path to
opmath_t, matching the scalar divisor path. Same one-line cast on CUDA, whose general path had the same split against its ownis_cpu_scalar(2)branch.In the vectorized loop this replaces the
CPU_CAPABILITY_SVE256 && __ARM_FEATURE_BF16specialization ofdiv_floor_floating_vec, which already did exactly this widening for one backend and one dtype. Since it did not widen the scalar loop next to it, SVE256 has the same length dependence today, just in the other direction.Written as
if constexpronis_reduced_floating_point_vrather than two specializations, so the float body is not instantiated forHalfandBFloat16at all.git diff -won that hunk is small, the body is only reindented.float and double are unaffected.
opmath_type<float>isfloat, so the cast is a no-op and theif constexprpicks the existing body.Correctness
4000 random pairs per dtype, comparing the tensor-tensor result against the same op elementwise on 0-dim tensors, and against float math narrowed once:
560 // 3inbfloat16is now 186 at lengths 1, 2, 3, 8, 16, 64 and 1000, and at 0-dim.Performance
This is faster, not slower. Single threaded, arm64, best of 7.
At n = 4096: bfloat16 51.5 -> 11.8 us, float16 31.6 -> 9.1 us.
Vectorized<BFloat16>::fmodismap2(q, std::fmod)and::floorismap(floor_impl), so the old path spilled each vector to memory and called scalar libm per lane, andstd::fmodonBFloat16converted to float and back anyway. Converting once up front getsSleef_fmodandvrndmq_f32on real float vectors. This is what the SVE comment predicted, that most of these instructions end up as f32 anyway.Tests
test_div_floor_reduced_precisionintest/test_binary_ufuncs.py. It compares against float math narrowed once withatol=0, rtol=0, since the defaultbfloat16tolerance is wide enough to hide an off-by-one quotient. It also checks lengths 1, 2 and 3 so the scalar loop and the vectorized loop are both covered.Before this change it fails on 240 / 4096 elements for
bfloat16and 18 / 4096 forfloat16.test_binary_ufuncs.pypasses, 12713 passed.test_ops.py -k "floor_divide or div_floor_rounding"passes, 169 passed.I do not have a CUDA machine, so that one line is only reasoned about and left to CI.
cc @ptrblck @msaroufim @eqy @tinglvv @nWEIdia @jgong5 @mingfeima @XiaobingSuper @sanchitintel @ashokei @jingxu10 @aditew01