Skip to content

Commit c1caad6

Browse files
authored
Treat a missing rounding mode in div_out_mode as true division (pytorch#24178)
Summary: `div.Tensor_mode(a, b, rounding_mode=None)` is true division. The HiFi `div_out_mode` sent `None` to the non-optimized path, where `mode_is_trunc` was false and the code fell through to `floor_divide` (its comment assumed the mode "must be floor"). So `7 / 2` returned 3 and `-7 / 2` returned -4. The kernel now delegates to `div_out` when `mode` has no value, which is what the portable and Fusion G3 `div_out_mode` already do. Authored with Claude Code. Reviewed By: DrJessop Differential Revision: D127746755 Pull Request resolved: pytorch#24178
1 parent 4cbe1c0 commit c1caad6

2 files changed

Lines changed: 29 additions & 0 deletions

File tree

‎backends/cadence/hifi/operators/op_div.cpp‎

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -210,6 +210,10 @@ Tensor& div_out_mode(
210210
Tensor& out) {
211211
ET_DCHECK_MSG(!tensor_has_zero(b), "divisor tensor contains zero");
212212

213+
if (!mode.has_value()) {
214+
return div_out(ctx, a, b, out);
215+
}
216+
213217
ET_KERNEL_CHECK(
214218
ctx,
215219
torch::executor::resize_to_broadcast_target_size(a, b, out) == Error::Ok,

‎backends/cadence/hifi/operators/tests/test_op_div.cpp‎

Lines changed: 25 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -59,6 +59,31 @@ TEST_F(HiFiDivTest, DISABLED_Int32FloorDivideTest) {
5959
EXPECT_TENSOR_EQ(out, tf.full(sizes, kExpectedResult));
6060
}
6161

62+
TEST_F(HiFiDivTest, FloatNoRoundingModeIsTrueDivision) {
63+
TensorFactory<ScalarType::Float> tf;
64+
const std::vector<int> sizes{2, 2};
65+
Tensor out = tf.zeros(sizes);
66+
const Tensor numerator = tf.make(sizes, {7.0, -7.0, 1.0, -1.0});
67+
const Tensor denominator = tf.make(sizes, {2.0, 2.0, 4.0, 4.0});
68+
69+
div_out_mode(numerator, denominator, std::nullopt, out);
70+
71+
EXPECT_TENSOR_EQ(out, tf.make(sizes, {3.5, -3.5, 0.25, -0.25}));
72+
}
73+
74+
TEST_F(HiFiDivTest, Int32NoRoundingModeIsTrueDivisionToFloat) {
75+
TensorFactory<ScalarType::Int> tf_int;
76+
TensorFactory<ScalarType::Float> tf_float;
77+
const std::vector<int> sizes{2, 2};
78+
Tensor out = tf_float.zeros(sizes);
79+
const Tensor numerator = tf_int.make(sizes, {7, -7, 1, -1});
80+
const Tensor denominator = tf_int.make(sizes, {2, 2, 4, 4});
81+
82+
div_out_mode(numerator, denominator, std::nullopt, out);
83+
84+
EXPECT_TENSOR_EQ(out, tf_float.make(sizes, {3.5, -3.5, 0.25, -0.25}));
85+
}
86+
6287
} // namespace
6388
} // namespace native
6489
} // namespace HiFi

0 commit comments

Comments
 (0)