Fix a div_mod bug in generic_math.h (#157383)

Summary: There is a bug in integer div_mod that when the remainder is 0 and the divisor is negative, mod operation produces a negative number. Fixed in this PR.
Pull Request resolved: https://github.com/pytorch/pytorch/pull/157383
Approved by: https://github.com/angelayi, https://github.com/jingsh
This commit is contained in:
Bin Bao
2025-07-01 11:54:43 -07:00
committed by PyTorch MergeBot
parent ab2294d828
commit 34c8033fd3
2 changed files with 3 additions and 1 deletions

View File

@ -14,4 +14,6 @@ TEST(GenericMathTest, div_floor_test) {
EXPECT_DOUBLE_EQ(c10::div_floor_floating(5., -2.), -3.);
EXPECT_EQ(c10::div_floor_integer(5, 2), 2);
EXPECT_EQ(c10::div_floor_integer(5, -2), -3);
EXPECT_EQ(c10::div_mod(-9, -3), 0);
EXPECT_EQ(c10::div_mod(-9., -3.), 0.);
}

View File

@ -93,7 +93,7 @@ template <
std::enable_if_t<std::is_integral_v<scalar_t>, int> = 0>
inline C10_HOST_DEVICE scalar_t div_mod(scalar_t a, scalar_t b) {
auto mod = a % b;
if ((b < 0) != (mod < 0)) {
if (mod != 0 && (b < 0) != (mod < 0)) {
mod += b;
}
return mod;