Skip to content

Commit f014775

Browse files
Merge pull request #52707 from elfringham:init_ops_test_fix
PiperOrigin-RevId: 416941851 Change-Id: Iefa5a9b841b053b36f6b105cd82c9d32d5e47850
2 parents 3f91846 + 55deb9b commit f014775

File tree

3 files changed

+21
-8
lines changed

3 files changed

+21
-8
lines changed

tensorflow/core/kernels/sequence_ops.cc

Lines changed: 13 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -91,13 +91,19 @@ class RangeOp : public OpKernel {
9191
errors::InvalidArgument(
9292
"Requires start >= limit when delta < 0: ", start, "/", limit));
9393
}
94-
int64_t size = 0;
95-
if (std::is_integral<T>::value) {
96-
size = static_cast<int64_t>(
97-
(std::abs(limit - start) + std::abs(delta) - 1) / std::abs(delta));
98-
} else {
99-
size = static_cast<int64_t>(std::ceil(std::abs((limit - start) / delta)));
100-
}
94+
auto size_auto = (std::is_integral<T>::value
95+
? (Eigen::numext::abs(limit - start) +
96+
Eigen::numext::abs(delta) - T(1)) /
97+
Eigen::numext::abs(delta)
98+
: Eigen::numext::ceil(
99+
Eigen::numext::abs((limit - start) / delta)));
100+
OP_REQUIRES(
101+
context, size_auto <= std::numeric_limits<int64_t>::max(),
102+
errors::InvalidArgument("Requires ((limit - start) / delta) <= ",
103+
std::numeric_limits<int64_t>::max()));
104+
105+
int64_t size = static_cast<int64_t>(size_auto);
106+
101107
TensorShape shape;
102108
OP_REQUIRES_OK(context, shape.AddDimWithStatus(size));
103109
Tensor* out = nullptr;

tensorflow/core/ops/math_ops.cc

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1489,6 +1489,13 @@ Status RangeSize(const Tensor* start_t, const Tensor* limit_t,
14891489
Eigen::numext::abs(delta))
14901490
: (Eigen::numext::ceil(
14911491
Eigen::numext::abs((limit - start) / delta))));
1492+
1493+
// Undefined behaviour if size will not fit into int64_t
1494+
if (size > std::numeric_limits<int64_t>::max()) {
1495+
return errors::InvalidArgument("Requires ((limit - start) / delta) <= ",
1496+
std::numeric_limits<int64_t>::max());
1497+
}
1498+
14921499
c->set_output(0, c->Vector(static_cast<int64_t>(size)));
14931500
return Status::OK();
14941501
}

tensorflow/python/kernel_tests/array_ops/init_ops_test.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -548,7 +548,7 @@ def testLargeLimits(self):
548548
def testLargeStarts(self):
549549
# Test case for GitHub issue 46899.
550550
with self.session():
551-
with self.assertRaises(errors_impl.InvalidArgumentError):
551+
with self.assertRaises((ValueError, errors_impl.InvalidArgumentError)):
552552
v = math_ops.range(start=-1e+38, limit=1)
553553
self.evaluate(v)
554554

0 commit comments

Comments
 (0)