[XLA] Fix a bug in SplitF64ToF32

Overflows in SplitF64ToF32 could result in non-finite lower components which,
when reconstructed, would result in NaN.

PiperOrigin-RevId: 343889763
Change-Id: Ie4dffd64738a22c4bc2377a40e4760cfe776e95a
This commit is contained in:
David Majnemer 2020-11-23 11:20:54 -08:00 committed by TensorFlower Gardener
parent f6ff120014
commit 46f86abb7b
2 changed files with 15 additions and 7 deletions

View File

@ -367,15 +367,15 @@ string SanitizeFileName(string file_name) {
// precision, Numerische Mathematik, vol. 18, pp. 224242, 1971.
std::pair<float, float> SplitF64ToF32(double x) {
const float x_f32 = static_cast<float>(x);
// Early return if x is an infinity or NaN.
if (!std::isfinite(x)) {
return std::make_pair(x_f32, 0.0f);
}
// Only values within the range of F32 are supported, unless it is infinity.
// Small values with large negative exponents would be rounded to zero.
// Early return if x is an infinity or NaN.
if (!std::isfinite(x_f32)) {
LOG(WARNING) << "Out of range F64 constant detected: " << x;
// Only values within the range of F32 are supported, unless it is infinity.
// Small values with large negative exponents would be rounded to zero.
if (std::isfinite(x)) {
LOG(WARNING) << "Out of range F64 constant detected: " << x;
}
return std::make_pair(x_f32, 0.0f);
}
// The high float is simply the double rounded to the nearest float. Because

View File

@ -126,5 +126,13 @@ TEST(UtilTest, RoundTripFpToString) {
"-nan");
}
TEST(UtilTest, SplitF64ToF32) {
// Overflowing the F32 exponent in SplitF64ToF32 should result in a pair of
// [∞,0].
EXPECT_EQ(SplitF64ToF32(std::numeric_limits<double>::max()).first,
std::numeric_limits<float>::infinity());
EXPECT_EQ(SplitF64ToF32(std::numeric_limits<double>::max()).second, 0.0f);
}
} // namespace
} // namespace xla