Skip to content

OpenVINO™ is an open source toolkit for optimizing and deploying AI inference

[CPU][Core] Fix FP8 conversion double rounding and NaN handling (#39400)

Bo Liueea2e80c7c4b
diff --git a/src/core/dev_api/openvino/core/type/float_util.hpp b/src/core/dev_api/openvino/core/type/float_util.hpp
index b0fcf28b47d..9d26f16caec 100644
--- a/src/core/dev_api/openvino/core/type/float_util.hpp
+++ b/src/core/dev_api/openvino/core/type/float_util.hpp
@@ -37,6 +37,23 @@ inline float u32_bits_to_f32(uint32_t bits) {
std::memcpy(&value, &bits, sizeof(bits));
return value;
}
+
+/**
+ * @brief Round float value to 5 mantissa bits with round-to-odd.
+ *
+ * The 18 low bits are cleared and bit 18 is set if any of them was set. As it keeps at least two more bits than
+ * f8e4m3 and f8e5m2, rounding the result to f8 with round-to-nearest-even gives the same result as a single rounding
+ * of the input value. The result is exact in f16 unless it becomes zero or overflows in f8.
+ *
+ * @param value Input float value.
+ * @return The rounded float value.
+ */
+inline float round_to_odd_for_f8(float value) {
+ constexpr uint32_t dropped_bits = 18; // f32 mantissa bits below the 5 kept ones
+ constexpr uint32_t mask = (uint32_t{1} << dropped_bits) - 1;
+ const uint32_t bits = f32_to_u32_bits(value);
+ return u32_bits_to_f32((bits | ((bits & mask) + mask)) & ~mask);
+}
} // namespace
} // namespace util
} // namespace ov
diff --git a/src/core/reference/include/openvino/reference/fake_convert.hpp b/src/core/reference/include/openvino/reference/fake_convert.hpp
index bbbeb2cd00e..7ea79f56bd5 100644
--- a/src/core/reference/include/openvino/reference/fake_convert.hpp
+++ b/src/core/reference/include/openvino/reference/fake_convert.hpp
@@ -5,6 +5,7 @@
#pragma once
#include <cmath>
+#include <type_traits>
#include <vector>
#include "openvino/reference/autobroadcast_binop.hpp"
@@ -29,20 +30,26 @@ void emulate_f8e5m2_on_fp16(const float16* const arg_f, float16* out_f, size_t c
* @param arg_f Pointer to the input data.
* @param out_f Pointer to the otuput data.
* @param count Number of elements in the data input.
- * @param use_clamp If use clamp.
- *
- * Exponent denormal values 0 -7
- * Exponent normal values 1..15 -6..8 (7 - exponent)
- * Exponent NaN values 15 8
- *
+ * @param use_clamp If use clamp: out of range values and inf saturate to +-448, otherwise they become NaN.
*/
void emulate_f8e4m3_on_fp16(const float16* arg_f, float16* out_f, size_t count, bool use_clamp = true);
} // namespace func
namespace fake_convert_details {
+/**
+ * @brief Round float data to odd in place, so that the following f32 -> f16 -> f8 conversion rounds only once.
+ */
+void round_to_odd_for_f8(float* data, size_t count);
+
template <bool INVERT, typename T>
inline T scale_shift(T val, T scale, T shift) {
- return INVERT ? static_cast<T>((val + shift) / scale) : static_cast<T>(val * scale - shift);
+ if constexpr (INVERT) {
+ // adding zero shift would turn -0 into +0 (-0 + 0 == +0), so skip it to keep the sign of zero
+ const T shifted = shift == T(0) ? val : static_cast<T>(val + shift);
+ return static_cast<T>(shifted / scale);
+ } else {
+ return static_cast<T>(val * scale - shift);
+ }
}
/**
* @brief Apply scale and shift for the data input.
@@ -192,6 +199,13 @@ void fake_convert(const T* data,
fake_convert_details::apply_scale_shift<T>(out, data, scale, shift, data_shape, scale_shape, shift_shape, false);
std::vector<ov::float16> tmp_fp16(element_count, 0.f);
+ // Round to odd keeps f32 -> f16 -> f8 a single rounding, it is valid only for f8e4m3/f8e5m2.
+ // out is an intermediate here, it is overwritten by the result below.
+ if constexpr (std::is_same_v<T, float>) {
+ if (destination_type == element::f8e4m3 || destination_type == element::f8e5m2) {
+ fake_convert_details::round_to_odd_for_f8(out, element_count);
+ }
+ }
reference::convert(out, tmp_fp16.data(), element_count);
fake_convert_details::apply_conversion(tmp_fp16.data(), tmp_fp16.data(), element_count, destination_type);
reference::convert(tmp_fp16.data(), out, element_count);
diff --git a/src/core/reference/src/op/fake_convert.cpp b/src/core/reference/src/op/fake_convert.cpp
index 8ced48f2647..dc7e80db27b 100644
--- a/src/core/reference/src/op/fake_convert.cpp
+++ b/src/core/reference/src/op/fake_convert.cpp
@@ -4,6 +4,11 @@
#include "openvino/reference/fake_convert.hpp"
+#include <cmath>
+
+#include "openvino/core/type/float8_e4m3.hpp"
+#include "openvino/core/type/float_util.hpp"
+
namespace ov {
namespace reference {
namespace func {
@@ -28,6 +33,8 @@ void emulate_f8e5m2_on_fp16(const float16* const arg_f, float16* out_f, size_t c
constexpr uint16_t grs_bitmask = 0x00FF; /// 0 00000 0011111111, grs denotes guard, round, sticky bits
constexpr uint16_t rne_tie = 0x0180; /// 0 00000 0110000000, rne denotes round to nearest even
constexpr uint16_t fp16_inf = 0x7C00;
+ constexpr uint16_t fp16_mant = 0x03FF;
+ constexpr uint16_t fp16_quiet_nan_bit = 0x0200;
for (size_t i = 0; i < count; ++i) {
/// converts float number to half precision in round-to-nearest-even mode and returns half with converted value.
@@ -47,6 +54,9 @@ void emulate_f8e5m2_on_fp16(const float16* const arg_f, float16* out_f, size_t c
// 100 - this is a tie : round up if the mantissa's bit just before G is 1, else do nothing
// 101, 110, 111 - round up > 0x0080
val_bit_repr += (((rnmask > 0x0080) || (rnmask_tie == rne_tie)) << lshift);
+ } else if ((val_bit_repr & fp16_mant) != 0) {
+ /* set quiet bit of NaN, so it stays NaN (not inf) after mantissa truncation */
+ val_bit_repr |= fp16_quiet_nan_bit;
}
val_bit_repr &= mask_mant; /* truncation */
if (use_clamp) {
@@ -63,89 +73,39 @@ void emulate_f8e5m2_on_fp16(const float16* const arg_f, float16* out_f, size_t c
* @param arg_f Pointer to the input data.
* @param out_f Pointer to the otuput data.
* @param count Number of elements in the data input.
- * @param use_clamp If use clamp.
- *
- * Exponent denormal values 0 -7
- * Exponent normal values 1..15 -6..8 (7 - exponent)
- * Exponent NaN values 15 8
+ * @param use_clamp If use clamp. f8e4m3 has no infinity, so without clamp values out of range (and inf) become NaN,
+ * with clamp finite and infinite values saturate to +-448. NaN always stays NaN.
*
+ * The conversion is done by float8_e4m3 which rounds to nearest even, including subnormal range and keeps the sign
+ * of zero. The f16 -> f32 -> f16 steps used on the way are exact, so no double rounding happens.
*/
void emulate_f8e4m3_on_fp16(const float16* arg_f, float16* out_f, size_t count, bool use_clamp) {
- const auto arg_u = reinterpret_cast<const uint16_t*>(arg_f);
- auto out_u = reinterpret_cast<uint16_t*>(out_f);
- uint16_t val_bit_repr;
-
- constexpr auto exp_bits = 5;
- constexpr auto mbits = 9;
- constexpr auto non_mant_bits = exp_bits + 1; /// exponent + sign
- constexpr auto lshift = 10 - (mbits - non_mant_bits);
- constexpr auto fp16_exp_bias = 15;
- constexpr auto f8e4m3_min_val = 0.001953125f; /// 2**-9
-
- constexpr uint16_t mask_mant = static_cast<uint16_t>(0xFFFF << lshift); /// 1111111111111111 -> 1 11111 1111000000
- constexpr uint16_t grs_bitmask = 0x007F; /// 0 00000 0001111111, grs denotes guard, round, sticky bits
- constexpr uint16_t rne_tie = 0x00C0; /// 0 00000 0011000000, rne denotes round to nearest even
- constexpr uint16_t rne_mask = 1;
- constexpr uint16_t fp16_inf = 0x7C00;
+ constexpr float f8e4m3_max = 448.0f;
for (size_t i = 0; i < count; ++i) {
- val_bit_repr = arg_u[i];
- /* flush values below 1-4-3 (offset=4) subnormal range to zero */
- if (std::abs(static_cast<float>(arg_f[i])) < f8e4m3_min_val) {
- val_bit_repr = 0;
- }
-
- short exp_h = static_cast<short>((val_bit_repr & fp16_inf) >> 10) -
- fp16_exp_bias; /// 0111110000000000 -> 0000000000011111 - 15, biased exponent for fp16
- const short sign_h = (val_bit_repr & 0x8000); /// & 1 00000 0000000000
- short mantissa_h = (val_bit_repr & 0x03FF); /// & 0 00000 1111111111
- ///(val_bit_repr && 0111111111111111) < 0 10010 1110000000 (19326)
- const bool can_round = ((val_bit_repr & 0x7FFF) < 0b101111110000000) ? true : false;
- bool is_naninf = ((val_bit_repr & fp16_inf) == fp16_inf) ? true : false;
-
- int dshift = 0;
- if (exp_h > 8) { // too large, set it to NaN or inf
- is_naninf = true;
- if (use_clamp) {
- exp_h = 8;
- mantissa_h = 0b0000001100000000;
- } else {
- mantissa_h = 0;
- exp_h = 16;
- }
- } else if (exp_h < -9) { /// -13, -12, -11 for rounding
- /* flush values below 1-4-3 (offset=4) subnormal range to zero */
- exp_h = -15;
- mantissa_h = 0;
+ const float val = static_cast<float>(arg_f[i]);
+ if (std::isnan(val)) {
+ out_f[i] = arg_f[i];
+ continue;
}
-
- if (exp_h == 8 && mantissa_h >= 0b0000001100000000) {
- mantissa_h = 0b0000001100000000;
- }
- /* nearest rounding masks, & 0 00000 000 111 1111 - mantissa bits below f8e4m3 (grs) */
- const uint16_t rnmask = (mantissa_h & grs_bitmask);
- /* & 0 00000 0011000000 - edge between f8e4m3 and fp16 mantissa */
- const uint16_t rnmask_tie = (mantissa_h & rne_tie);
- if (!is_naninf && can_round && rne_mask) {
- /* round to nearest even, if rne_mask is enabled */
- /// rnmask > 0 00000 0001000000(64) or 0 00000 0011000000 - edge bits is 1
- /// += 0 00000 0010000000
- mantissa_h += (((rnmask > 0x0040) || (rnmask_tie == rne_tie)) << lshift);
+ const float8_e4m3 f8(val);
+ float res = static_cast<float>(f8);
+ if (std::isnan(res) && use_clamp) {
+ // overflow (or inf) which is not NaN on input: saturate
+ res = std::signbit(val) ? -f8e4m3_max : f8e4m3_max;
}
- if (exp_h < -6) { /* handle denormals -11, -10, -9, dshift 1, 2, 3 */
- dshift = (-6 - exp_h);
- mantissa_h = mantissa_h >> dshift;
- }
- mantissa_h &= mask_mant; /* truncation */
- mantissa_h <<= dshift;
- mantissa_h += ((exp_h + 15) << 10);
- val_bit_repr = mantissa_h | sign_h;
- out_u[i] = val_bit_repr;
+ out_f[i] = float16(res);
}
}
} // namespace func
namespace fake_convert_details {
+void round_to_odd_for_f8(float* data, size_t count) {
+ for (size_t i = 0; i < count; ++i) {
+ data[i] = util::round_to_odd_for_f8(data[i]);
+ }
+}
+
/**
* @brief Call conversion of fp16 value to the desired destination type
*
diff --git a/src/core/src/type/float16.cpp b/src/core/src/type/float16.cpp
index eb8afe9a9af..2d8b52d76ad 100644
--- a/src/core/src/type/float16.cpp
+++ b/src/core/src/type/float16.cpp
@@ -75,8 +75,8 @@ float16::float16(float value) {
return;
}
int16_t biased_exp_16 = (biased_exp_field_32 >> 23) - 127 + 15;
- // In the normalized_16 realm
- if ((frac & rhalf_16) == rodd_16 || (frac & rnorm_16) != 0) {
+ // In the normalized_16 realm, subnormal values are rounded below after restoring the hidden 1
+ if (biased_exp_16 > 0 && ((frac & rhalf_16) == rodd_16 || (frac & rnorm_16) != 0)) {
frac += reven_16;
if (0 != (frac & emask_16)) {
frac &= emask_16;
diff --git a/src/core/src/type/float8_e4m3.cpp b/src/core/src/type/float8_e4m3.cpp
index 1476d507038..6336ead41b3 100644
--- a/src/core/src/type/float8_e4m3.cpp
+++ b/src/core/src/type/float8_e4m3.cpp
@@ -129,7 +129,8 @@ float8_e4m3::float8_e4m3(const uint32_t sign, const uint32_t biased_exponent, co
: m_value(((sign & 0x01U) << (f8e4m3_e_size + f8e4m3_m_size)) |
(biased_exponent & (f8e4m3_e_mask >> f8e4m3_m_size)) << f8e4m3_m_size | (fraction & f8e4m3_m_mask)) {}
-float8_e4m3::float8_e4m3(const float value) : m_value{f16_to_f8e4m3_bits(static_cast<float16>(value))} {}
+float8_e4m3::float8_e4m3(const float value)
+ : m_value{f16_to_f8e4m3_bits(static_cast<float16>(util::round_to_odd_for_f8(value)))} {}
float8_e4m3::operator float() const {
auto f32_bits = util::f32_to_u32_bits(f8_to_float_lut[m_value & (f8e4m3_e_mask | f8e4m3_m_mask)]);
diff --git a/src/core/src/type/float8_e5m2.cpp b/src/core/src/type/float8_e5m2.cpp
index ab4be4471f7..bff42495d89 100644
--- a/src/core/src/type/float8_e5m2.cpp
+++ b/src/core/src/type/float8_e5m2.cpp
@@ -7,6 +7,7 @@
#include <cmath>
#include <limits>
+#include "openvino/core/type/float_util.hpp"
#include "openvino/reference/fake_convert.hpp"
namespace ov {
@@ -27,7 +28,8 @@ constexpr uint8_t f8e5m2_m_size = 2; // f8e5m2 mantissa bits size
constexpr uint8_t f8e5m2_m_mask = 0x03; // f8e5m2 mantissa bit mask
uint8_t f32_to_f8e5m2_bits(const float value) {
- auto f16 = static_cast<float16>(value);
+ // round to odd first to avoid double rounding error
+ auto f16 = static_cast<float16>(util::round_to_odd_for_f8(value));
reference::func::emulate_f8e5m2_on_fp16(&f16, &f16, 1, false);
return static_cast<uint8_t>((f16.to_bits() >> byte_shift));
}
diff --git a/src/core/src/type/float8_e8m0.cpp b/src/core/src/type/float8_e8m0.cpp
index 83db20098db..55d573e5a3a 100644
--- a/src/core/src/type/float8_e8m0.cpp
+++ b/src/core/src/type/float8_e8m0.cpp
@@ -31,7 +31,10 @@ uint8_t f32_to_f8e8m0_bits(const float value) {
const auto input = util::f32_to_u32_bits(value);
const auto input_exponent_bits = static_cast<uint8_t>((input & f32_exponent_bits_mask) >> f32_mantissa_bits);
- if (std::signbit(value)) {
+ if (std::isnan(value)) {
+ // check NaN first, as NaN with sign bit set is still NaN
+ return 0b11111111;
+ } else if (std::signbit(value)) {
return 0b00000000;
} else if (input_exponent_bits >= 0b11111110) {
return input_exponent_bits - static_cast<uint8_t>(std::isinf(value));
diff --git a/src/core/tests/float16.cpp b/src/core/tests/float16.cpp
index c59372a6fb0..a332ef06104 100644
--- a/src/core/tests/float16.cpp
+++ b/src/core/tests/float16.cpp
@@ -10,6 +10,7 @@
#include <random>
#include "common_test_utils/float_util.hpp"
+#include "openvino/core/type/float_util.hpp"
namespace ov::test {
@@ -100,6 +101,15 @@ TEST(float16, values) {
EXPECT_EQ(static_cast<float16>(65520.0).to_bits(), 0x7c00);
}
+TEST(float16, f32_subnormal_rounding) {
+ // values just below a power of two in f16 subnormal range, carry of the mantissa rounding must not be lost
+ EXPECT_EQ(float16(ov::util::u32_bits_to_f32(0x337FFFFF)).to_bits(), 0x0001);
+ EXPECT_EQ(float16(ov::util::u32_bits_to_f32(0x33FFFFFF)).to_bits(), 0x0002);
+ EXPECT_EQ(float16(ov::util::u32_bits_to_f32(0x377FFFFF)).to_bits(), 0x0100);
+ // rounded up from the largest subnormal to the smallest normal
+ EXPECT_EQ(float16(ov::util::u32_bits_to_f32(0x387FFFFF)).to_bits(), 0x0400);
+}
+
TEST(float16, to_string) {
const float16 f16{1.5f};
EXPECT_EQ(std::to_string(f16), std::to_string(1.5f));
diff --git a/src/core/tests/float8_e4m3.cpp b/src/core/tests/float8_e4m3.cpp
index 1fa8c7d9857..1acb207536d 100644
--- a/src/core/tests/float8_e4m3.cpp
+++ b/src/core/tests/float8_e4m3.cpp
@@ -8,8 +8,11 @@
#include <climits>
#include <cmath>
+#include <vector>
#include "common_test_utils/float_util.hpp"
+#include "openvino/core/type/float_util.hpp"
+#include "openvino/reference/fake_convert.hpp"
namespace ov {
namespace test {
@@ -168,10 +171,11 @@ TEST(F8E4M3Test, f32_gt_zero_le_f8_half_lowest_subnormal) {
EXPECT_EQ(f8.to_bits(), 0x00);
}
-TEST(F8E4M3Test, f32_in_f16_format_le_zero_gt_f8_half_lowest_subnormal) {
+TEST(F8E4M3Test, f32_gt_f8_half_lowest_subnormal_but_tie_in_f16) {
const auto f8 = ov::float8_e4m3(0.00097656273283064365387f);
- EXPECT_EQ(f8.to_bits(), 0x00);
+ // The value is rounded to half of f8 lowest subnormal in f16, but it is greater than it in f32, so it rounds up
+ EXPECT_EQ(f8.to_bits(), 0x01);
}
TEST(F8E4M3Test, f32_in_f16_format_gt_zero_gt_f8_half_lowest_subnormal) {
@@ -222,6 +226,33 @@ TEST(F8E4M3Test, f32_le_f8_lowest_not_within_round_to_lowest) {
EXPECT_EQ(f8.to_bits(), 0xff);
}
+TEST(F8E4M3Test, f32_just_above_tie_round_up) {
+ // 1.0625 + 2^-20 is rounded to 1.0625 (tie between 1.0 and 1.125) in f16
+ const auto f8 = ov::float8_e4m3(ov::util::u32_bits_to_f32(0x3F880008));
+
+ EXPECT_EQ(f8.to_bits(), 0x39);
+}
+
+TEST(F8E4M3Test, f32_just_above_subnormal_tie_round_up) {
+ // 2^-10 + 2^-33 is rounded to 2^-10 (tie between 0 and 2^-9) in f16
+ const auto f8 = ov::float8_e4m3(ov::util::u32_bits_to_f32(0x3A800001));
+
+ EXPECT_EQ(f8.to_bits(), 0x01);
+}
+
+TEST(F8E4M3Test, f32_just_above_max_tie_round_to_nan) {
+ // 464 + 2^-15 is rounded to 464 (tie between f8 max 448 and overflow) in f16
+ const auto f8 = ov::float8_e4m3(ov::util::u32_bits_to_f32(0x43E80001));
+
+ EXPECT_EQ(f8.to_bits(), 0x7F);
+}
+
+TEST(F8E4M3Test, f32_negative_nan) {
+ const auto f8 = ov::float8_e4m3(ov::util::u32_bits_to_f32(0xFFC00000));
+
+ EXPECT_EQ(f8.to_bits(), 0xFF);
+}
+
TEST(F8E4M3Test, stream_operator) {
std::stringstream s;
s << ov::float8_e4m3(2.5f);
@@ -298,5 +329,41 @@ TEST_P(F8E4M3PTest, f32_to_f8_bits) {
EXPECT_EQ(f8.to_bits(), exp_value);
}
+
+// input, use_clamp, expected
+using f8e4m3_emulate_params = std::tuple<ov::float16, bool, float>;
+class F8E4M3EmulatePTest : public testing::TestWithParam<f8e4m3_emulate_params> {};
+
+INSTANTIATE_TEST_SUITE_P(overflow_inf_nan,
+ F8E4M3EmulatePTest,
+ testing::Values(f8e4m3_emulate_params{ov::float16(448.f), true, 448.f},
+ f8e4m3_emulate_params{ov::float16(1000.f), true, 448.f},
+ f8e4m3_emulate_params{ov::float16(-1000.f), true, -448.f},
+ f8e4m3_emulate_params{ov::float16::from_bits(0x7C00), true, 448.f},
+ f8e4m3_emulate_params{ov::float16::from_bits(0xFC00), true, -448.f},
+ f8e4m3_emulate_params{ov::float16::from_bits(0x7E00), true, f32_qnan},
+ f8e4m3_emulate_params{ov::float16::from_bits(0x7C01), true, f32_qnan},
+ f8e4m3_emulate_params{ov::float16(448.f), false, 448.f},
+ f8e4m3_emulate_params{ov::float16(1000.f), false, f32_qnan},
+ f8e4m3_emulate_params{ov::float16(-1000.f), false, f32_qnan},
+ f8e4m3_emulate_params{ov::float16::from_bits(0x7C00), false, f32_qnan},
+ f8e4m3_emulate_params{ov::float16::from_bits(0xFC00), false, f32_qnan},
+ f8e4m3_emulate_params{ov::float16::from_bits(0x7E00), false, f32_qnan},
+ f8e4m3_emulate_params{ov::float16::from_bits(0x7C01), false, f32_qnan}));
+
+TEST_P(F8E4M3EmulatePTest, emulate_on_fp16) {
+ const auto& params = GetParam();
+ const auto input = std::get<0>(params);
+ const auto use_clamp = std::get<1>(params);
+ const auto& exp_value = std::get<2>(params);
+ ov::float16 output;
+ ov::reference::func::emulate_f8e4m3_on_fp16(&input, &output, 1, use_clamp);
+
+ if (std::isnan(exp_value)) {
+ EXPECT_TRUE(std::isnan(static_cast<float>(output)));
+ } else {
+ EXPECT_EQ(static_cast<float>(output), exp_value);
+ }
+}
} // namespace test
} // namespace ov
diff --git a/src/core/tests/float8_e5m2.cpp b/src/core/tests/float8_e5m2.cpp
index 0a8cdd9d801..ac038e00306 100644
--- a/src/core/tests/float8_e5m2.cpp
+++ b/src/core/tests/float8_e5m2.cpp
@@ -6,9 +6,12 @@
#include <gtest/gtest.h>
+#include <array>
#include <climits>
+#include <cmath>
#include "common_test_utils/float_util.hpp"
+#include "openvino/core/type/float_util.hpp"
namespace ov {
namespace test {
@@ -128,7 +131,8 @@ TEST(F8E5M2Test, f16_sig_nan) {
const auto f8 = ov::float8_e5m2(std::numeric_limits<ov::float16>::signaling_NaN());
EXPECT_TRUE(std::isnan(f8));
- EXPECT_EQ(f8.to_bits(), 0b01111101);
+ // signaling NaN is converted to quiet NaN
+ EXPECT_EQ(f8.to_bits(), 0b01111111);
EXPECT_EQ(std::numeric_limits<ov::float8_e5m2>::signaling_NaN().to_bits(), 0b01111101);
}
@@ -144,8 +148,9 @@ TEST(F8E5M2Test, f32_sig_nan) {
const auto f8 = ov::float8_e5m2(std::numeric_limits<float>::signaling_NaN());
const auto f8_bits = f8.to_bits();
- const auto allowed_nan = (f8_bits == 0b01111101) || (f8_bits == 0b01111110);
- EXPECT_TRUE(allowed_nan);
+ // signaling NaN is converted to quiet NaN
+ const auto is_quiet_nan = (f8_bits & 0b01111110) == 0b01111110;
+ EXPECT_TRUE(is_quiet_nan);
EXPECT_TRUE(std::isnan(f8));
EXPECT_EQ(std::numeric_limits<ov::float8_e5m2>::signaling_NaN().to_bits(), 0b01111101);
@@ -215,6 +220,35 @@ TEST(F8E5M2Test, f32_lt_f16_lowest_lt_f8_lowest_round_to_minus_inf) {
EXPECT_EQ(f8.to_bits(), 0b11111100);
}
+TEST(F8E5M2Test, f32_just_below_max_tie_round_to_max) {
+ // 61439.996 is rounded to 61440 (tie between f8 max 57344 and inf) in f16
+ const auto f8 = ov::float8_e5m2(ov::util::u32_bits_to_f32(0x476FFFFF));
+
+ EXPECT_EQ(f8.to_bits(), 0x7B);
+}
+
+TEST(F8E5M2Test, f32_just_above_subnormal_tie_round_up) {
+ // 2^-17 + 2^-40 is rounded to 2^-17 (tie between 0 and 2^-16) in f16
+ const auto f8 = ov::float8_e5m2(ov::util::u32_bits_to_f32(0x37000001));
+
+ EXPECT_EQ(f8.to_bits(), 0x01);
+}
+
+TEST(F8E5M2Test, f32_positive_nan_without_f16_payload) {
+ // NaN payload bits are lost in f16, so the f16 quiet bit must be set to keep NaN
+ const auto f8 = ov::float8_e5m2(ov::util::u32_bits_to_f32(0x7F800001));
+
+ EXPECT_TRUE(std::isnan(f8));
+ EXPECT_EQ(f8.to_bits() & 0x80, 0x00);
+}
+
+TEST(F8E5M2Test, f32_negative_nan_without_f16_payload) {
+ const auto f8 = ov::float8_e5m2(ov::util::u32_bits_to_f32(0xFF9FFFFF));
+
+ EXPECT_TRUE(std::isnan(f8));
+ EXPECT_EQ(f8.to_bits() & 0x80, 0x80);
+}
+
template <class TContainer>
std::vector<std::tuple<uint8_t, typename TContainer::value_type>> enumerate(const TContainer& values) {
std::vector<std::tuple<uint8_t, typename TContainer::value_type>> enum_values;
@@ -329,10 +363,10 @@ TEST_P(F8E5M2PTest, f32_to_f8_bits) {
EXPECT_TRUE(std::isnan(f8));
exp_value--;
} else if (exp_value == 0x7D || exp_value == 0xFD) { // signaling NaN
- // signaling NaN representation can be implementation defined
- const auto allowed_nan = (f8_bits == exp_value) || (f8_bits == ++exp_value);
+ // signaling NaN is converted to quiet NaN, its payload can be implementation defined
+ const auto is_quiet_nan = (f8_bits & 0x7E) == 0x7E && (f8_bits & 0x80) == (exp_value & 0x80);
EXPECT_TRUE(std::isnan(f8));
- EXPECT_TRUE(allowed_nan);
+ EXPECT_TRUE(is_quiet_nan);
return;
}
diff --git a/src/core/tests/float8_e8m0.cpp b/src/core/tests/float8_e8m0.cpp
index d37f63a6164..d6b296dc9e3 100644
--- a/src/core/tests/float8_e8m0.cpp
+++ b/src/core/tests/float8_e8m0.cpp
@@ -10,6 +10,7 @@
#include <tuple>
#include "common_test_utils/float_util.hpp"
+#include "openvino/core/type/float_util.hpp"
namespace ov {
namespace test {
@@ -57,6 +58,19 @@ TEST(F8E8M0Test, f32_nan_signaling) {
EXPECT_EQ(f8.to_bits(), 0b11111111);
}
+TEST(F8E8M0Test, f32_negative_nan_quiet) {
+ // default NaN on x86 has sign bit set
+ const auto f8 = ov::float8_e8m0(ov::util::u32_bits_to_f32(0xFFC00000));
+
+ EXPECT_EQ(f8.to_bits(), 0b11111111);
+}
+
+TEST(F8E8M0Test, f32_negative_nan_signaling) {
+ const auto f8 = ov::float8_e8m0(ov::util::u32_bits_to_f32(0xFF800001));
+
+ EXPECT_EQ(f8.to_bits(), 0b11111111);
+}
+
TEST(F8E8M0Test, f32_zero) {
const auto f8 = ov::float8_e8m0(0.0f);
diff --git a/src/plugins/intel_cpu/src/emitters/plugin/x64/jit_eltwise_emitters.cpp b/src/plugins/intel_cpu/src/emitters/plugin/x64/jit_eltwise_emitters.cpp
index af889d19b56..821641cda05 100644
--- a/src/plugins/intel_cpu/src/emitters/plugin/x64/jit_eltwise_emitters.cpp
+++ b/src/plugins/intel_cpu/src/emitters/plugin/x64/jit_eltwise_emitters.cpp
@@ -3342,29 +3342,30 @@ void jit_clamp_emitter::emit_isa(const std::vector<size_t>& in_vec_idxs,
auto vmm_src0 = Vmm(in_vec_idxs[0]);
auto vmm_dst = Vmm(out_vec_idxs[0]);
- auto uni_vclamp = [this](Vmm vmm_dst, Vmm vmm_src0) {
- switch (exec_prc_) {
- case ov::element::f32:
- h->uni_vmaxps(vmm_dst, vmm_src0, table_val("min"));
- h->uni_vminps(vmm_dst, vmm_dst, table_val("max"));
- break;
- case ov::element::i32:
- h->uni_vpmaxsd(vmm_dst, vmm_src0, table_val("min"));
- h->uni_vpminsd(vmm_dst, vmm_dst, table_val("max"));
- break;
- default:
- OV_CPU_JIT_EMITTER_THROW("Unsupported precision");
- }
- };
+ if (exec_prc_ == ov::element::f32) {
+ // (v)maxps/(v)minps return the second source if any operand is NaN, so keep the data there to propagate NaN.
+ // Bounds are loaded to aux, as only the second source can be a memory operand.
+ auto vmm_aux = Vmm(aux_vec_idxs[0]);
+ h->uni_vmovups(vmm_aux, table_val("min"));
+ h->uni_vmaxps(vmm_aux, vmm_aux, vmm_src0); // aux = (aux > src) ? aux : src
+ h->uni_vmovups(vmm_dst, table_val("max")); // src is not needed anymore
+ h->uni_vminps(vmm_dst, vmm_dst, vmm_aux); // dst = (dst < aux) ? dst : aux
+ return;
+ }
- if (isa == x64::sse41) {
- if (vmm_src0.getIdx() != vmm_dst.getIdx()) {
- h->uni_vmovups(vmm_dst, vmm_src0);
- }
- uni_vclamp(vmm_dst, vmm_dst);
- } else {
- uni_vclamp(vmm_dst, vmm_src0);
+ if (exec_prc_ != ov::element::i32) {
+ OV_CPU_JIT_EMITTER_THROW("Unsupported precision");
+ }
+ if (isa == x64::sse41 && vmm_src0.getIdx() != vmm_dst.getIdx()) {
+ h->uni_vmovups(vmm_dst, vmm_src0);
+ vmm_src0 = vmm_dst;
}
+ h->uni_vpmaxsd(vmm_dst, vmm_src0, table_val("min"));
+ h->uni_vpminsd(vmm_dst, vmm_dst, table_val("max"));
+}
+
+size_t jit_clamp_emitter::aux_vecs_count() const {
+ return exec_prc_ == ov::element::f32 ? 1 : 0;
}
std::set<std::vector<element::Type>> jit_clamp_emitter::get_supported_precisions(
diff --git a/src/plugins/intel_cpu/src/emitters/plugin/x64/jit_eltwise_emitters.hpp b/src/plugins/intel_cpu/src/emitters/plugin/x64/jit_eltwise_emitters.hpp
index 80750838517..ba3a9751978 100644
--- a/src/plugins/intel_cpu/src/emitters/plugin/x64/jit_eltwise_emitters.hpp
+++ b/src/plugins/intel_cpu/src/emitters/plugin/x64/jit_eltwise_emitters.hpp
@@ -994,6 +994,7 @@ public:
const std::shared_ptr<ov::Node>& node = nullptr);
private:
+ size_t aux_vecs_count() const override;
void emit_impl(const std::vector<size_t>& in_vec_idxs, const std::vector<size_t>& out_vec_idxs) const override;
template <dnnl::impl::cpu::x64::cpu_isa_t isa>
diff --git a/src/plugins/intel_cpu/tests/functional/custom/single_layer_tests/instances/x64/activation.cpp b/src/plugins/intel_cpu/tests/functional/custom/single_layer_tests/instances/x64/activation.cpp
index 84ce08a6ca9..949b372c119 100644
--- a/src/plugins/intel_cpu/tests/functional/custom/single_layer_tests/instances/x64/activation.cpp
+++ b/src/plugins/intel_cpu/tests/functional/custom/single_layer_tests/instances/x64/activation.cpp
@@ -98,6 +98,37 @@ const auto basicCases5D = ::testing::Combine(
INSTANTIATE_TEST_SUITE_P(smoke_Activation5D_Eltwise_CPU_Blocked, ActivationLayerCPUTest, basicCases5D, ActivationLayerCPUTest::getTestCaseName);
+/* ============= Clamp with NaN and inf ============= */
+// NaN must be propagated, +-inf is clamped to the bounds
+class ClampNanLayerCPUTest : public ActivationLayerCPUTest {
+protected:
+ void generate_inputs(const std::vector<ov::Shape>& targetInputStaticShapes) override {
+ ActivationLayerCPUTest::generate_inputs(targetInputStaticShapes);
+ auto* data = inputs.begin()->second.data<float>();
+ data[0] = std::numeric_limits<float>::quiet_NaN();
+ data[1] = -std::numeric_limits<float>::quiet_NaN();
+ data[2] = std::numeric_limits<float>::infinity();
+ data[3] = -std::numeric_limits<float>::infinity();
+ }
+};
+
+TEST_P(ClampNanLayerCPUTest, CompareWithRefs) {
+ run();
+ CheckPluginRelatedResults(compiledModel, "Eltwise");
+}
+
+INSTANTIATE_TEST_SUITE_P(smoke_ClampNan_CPU, ClampNanLayerCPUTest,
+ ::testing::Combine(
+ ::testing::ValuesIn(static_shapes_to_test_representation(basic3D())),
+ ::testing::Values(activationShapes()),
+ ::testing::Values(std::make_pair(Clamp, std::vector<float>{-2.0f, 2.0f})),
+ ::testing::Values(ov::element::f32),
+ ::testing::Values(ov::element::f32),
+ ::testing::Values(ov::element::f32),
+ ::testing::ValuesIn(filterCPUSpecificParams(cpuParams3D())),
+ ::testing::Values(false)),
+ ClampNanLayerCPUTest::getTestCaseName);
+
} // namespace
} // namespace Activation
} // namespace test
diff --git a/src/plugins/intel_cpu/tests/functional/custom/single_layer_tests/instances/x64/conversion.cpp b/src/plugins/intel_cpu/tests/functional/custom/single_layer_tests/instances/x64/conversion.cpp
index 96334451e9a..76f559f673e 100644
--- a/src/plugins/intel_cpu/tests/functional/custom/single_layer_tests/instances/x64/conversion.cpp
+++ b/src/plugins/intel_cpu/tests/functional/custom/single_layer_tests/instances/x64/conversion.cpp
@@ -3,6 +3,7 @@
//
#include "custom/single_layer_tests/classes/conversion.hpp"
+#include "openvino/core/type/float_util.hpp"
#include "utils/cpu_test_utils.hpp"
#include "utils/filter_cpu_info.hpp"
@@ -49,6 +50,56 @@ INSTANTIATE_TEST_SUITE_P(smoke_ConvertCPULayerTest_Blocked, ConvertCPULayerTest,
::testing::ValuesIn(filterCPUSpecificParams(memForm4D_static_blocked))),
ConvertCPULayerTest::getTestCaseName);
+class ConvertToFP8RoundingCPULayerTest : public ConvertCPULayerTest {
+protected:
+ // Bit-exact check: the default comparator skips NaN, inf and max values, and ignores the sign of zero
+ void validate() override {
+ const auto actual = get_plugin_outputs();
+ const auto expected = calculate_refs();
+ ASSERT_EQ(expected.size(), 1);
+ ASSERT_EQ(actual.size(), 1);
+ ASSERT_EQ(expected[0].get_element_type(), actual[0].get_element_type());
+ ASSERT_EQ(expected[0].get_byte_size(), actual[0].get_byte_size());
+ const auto* expected_data = static_cast<const uint8_t*>(expected[0].data());
+ const auto* actual_data = static_cast<const uint8_t*>(actual[0].data());
+ for (size_t i = 0; i < expected[0].get_byte_size(); ++i) {
+ EXPECT_EQ(static_cast<int>(expected_data[i]), static_cast<int>(actual_data[i])) << "element " << i;
+ }
+ }
+
+ void generate_inputs(const std::vector<ov::Shape>& targetInputStaticShapes) override {
+ // f32 values with a tie in f16 but not in f32 (1.0625 + 2^-20, 1.1875 - 2^-20, 2^-10 + 2^-33, 2^-17 + 2^-40,
+ // 464 + 2^-15, 61439.996), and NaNs whose payload does not fit to f16
+ static const std::vector<uint32_t> values = {0x3F880008, 0xBF880008, 0x3F97FFF8, 0x3A800001,
+ 0xBA800001, 0x37000001, 0x43E80001, 0x476FFFFF,
+ 0x7F800001, 0xFF800001, 0xFF9FFFFF, 0x80000000};
+ inputs.clear();
+ const auto funcInput = function->inputs().front();
+ ov::Tensor tensor(funcInput.get_element_type(), targetInputStaticShapes.front());
+ auto* data = tensor.data<float>();
+ for (size_t i = 0; i < tensor.get_size(); ++i) {
+ data[i] = ov::util::u32_bits_to_f32(values[i % values.size()]);
+ }
+ inputs.insert({funcInput.get_node_shared_ptr(), tensor});
+ }
+};
+
+TEST_P(ConvertToFP8RoundingCPULayerTest, CompareWithRefs) {
+ run();
+}
+
+// 24 elements: one full vector of 16 f32 elements and a tail
+const std::vector<InputShape> inShapes_fp8_rounding = {{{1, 2, 3, 4}, {{1, 2, 3, 4}}}};
+
+INSTANTIATE_TEST_SUITE_P(smoke_ConvertToFP8RoundingCPULayerTest, ConvertToFP8RoundingCPULayerTest,
+ ::testing::Combine(
+ ::testing::ValuesIn(inShapes_fp8_rounding),
+ ::testing::Values(ov::element::f32),
+ ::testing::Values(ov::element::f8e4m3, ov::element::f8e5m2),
+ ::testing::Values(ov::test::SpecialValue::none),
+ ::testing::Values(CPUSpecificParams({nchw}, {nchw}, {}, "ref"))),
+ ConvertToFP8RoundingCPULayerTest::getTestCaseName);
+
INSTANTIATE_TEST_SUITE_P(smoke_ConvertCPULayerTest_BOOL_Static, ConvertToBooleanCPULayerTest,
::testing::Combine(
::testing::ValuesIn(inShapes_4D_static()),
diff --git a/src/plugins/intel_cpu/thirdparty/onednn b/src/plugins/intel_cpu/thirdparty/onednn
index 8a88df54e30..2f25ebfc4dd 160000
--- a/src/plugins/intel_cpu/thirdparty/onednn
+++ b/src/plugins/intel_cpu/thirdparty/onednn
@@ -1 +1 @@
-Subproject commit 8a88df54e304c2003fba85f3643fd01ce4709ca3
+Subproject commit 2f25ebfc4dd24b97229747322e36e5709deff2e5
diff --git a/src/plugins/template/tests/functional/op_reference/fake_convert.cpp b/src/plugins/template/tests/functional/op_reference/fake_convert.cpp
new file mode 100644
index 00000000000..76d256e15f8
--- /dev/null
+++ b/src/plugins/template/tests/functional/op_reference/fake_convert.cpp
@@ -0,0 +1,125 @@
+// Copyright (C) 2018-2026 Intel Corporation
+// SPDX-License-Identifier: Apache-2.0
+//
+
+#include "openvino/op/fake_convert.hpp"
+
+#include <gtest/gtest.h>
+
+#include <cmath>
+#include <limits>
+
+#include "base_reference_test.hpp"
+#include "openvino/op/constant.hpp"
+#include "openvino/op/parameter.hpp"
+
+using namespace ov;
+using namespace reference_tests;
+
+namespace {
+
+struct FakeConvertParams {
+ std::string name;
+ element::Type data_type;
+ element::Type destination_type;
+ std::vector<float> data;
+ std::vector<float> expected;
+};
+
+ov::Tensor make_tensor(const element::Type& type, const std::vector<float>& values) {
+ ov::Tensor tensor(type, Shape{values.size()});
+ for (size_t i = 0; i < values.size(); ++i) {
+ if (type == element::f32) {
+ tensor.data<float>()[i] = values[i];
+ } else if (type == element::f16) {
+ tensor.data<float16>()[i] = float16(values[i]);
+ } else if (type == element::bf16) {
+ tensor.data<bfloat16>()[i] = bfloat16(values[i]);
+ } else {
+ OPENVINO_THROW("Unsupported data type: ", type);
+ }
+ }
+ return tensor;
+}
+
+float get_value(const ov::Tensor& tensor, size_t i) {
+ const auto& type = tensor.get_element_type();
+ if (type == element::f32)
+ return tensor.data<const float>()[i];
+ if (type == element::f16)
+ return static_cast<float>(tensor.data<const float16>()[i]);
+ if (type == element::bf16)
+ return static_cast<float>(tensor.data<const bfloat16>()[i]);
+ OPENVINO_THROW("Unsupported data type: ", type);
+}
+
+class ReferenceFakeConvertLayerTest : public testing::TestWithParam<FakeConvertParams>, public CommonReferenceTest {
+public:
+ void SetUp() override {
+ const auto& params = GetParam();
+ const auto data = std::make_shared<op::v0::Parameter>(params.data_type, Shape{params.data.size()});
+ const auto scale = op::v0::Constant::create(params.data_type, Shape{1}, {1.f});
+ const auto shift = op::v0::Constant::create(params.data_type, Shape{1}, {0.f});
+ const auto fake_convert = std::make_shared<op::v13::FakeConvert>(data, scale, shift, params.destination_type);
+ function = std::make_shared<Model>(OutputVector{fake_convert}, ParameterVector{data});
+ inputData = {make_tensor(params.data_type, params.data)};
+ refOutData = {make_tensor(params.data_type, params.expected)};
+ }
+
+ // Exact check: the default comparator treats -0 and +0 as equal
+ void Validate() override {
+ const auto& expected = refOutData[0];
+ const auto actual = inferRequest.get_tensor(executableNetwork.output());
+ ASSERT_EQ(expected.get_element_type(), actual.get_element_type());
+ ASSERT_EQ(expected.get_size(), actual.get_size());
+ for (size_t i = 0; i < expected.get_size(); ++i) {
+ const auto expected_value = get_value(expected, i);
+ const auto actual_value = get_value(actual, i);
+ if (std::isnan(expected_value)) {
+ EXPECT_TRUE(std::isnan(actual_value)) << "index " << i;
+ } else {
+ EXPECT_EQ(expected_value, actual_value) << "index " << i;
+ EXPECT_EQ(std::signbit(expected_value), std::signbit(actual_value)) << "index " << i;
+ }
+ }
+ }
+
+ static std::string getTestCaseName(const testing::TestParamInfo<FakeConvertParams>& obj) {
+ const auto& params = obj.param;
+ std::ostringstream result;
+ result << params.data_type << "_to_" << params.destination_type << "_" << params.name;
+ return result.str();
+ }
+};
+
+TEST_P(ReferenceFakeConvertLayerTest, CompareWithRefs) {
+ Exec();
+}
+
+constexpr auto nan = std::numeric_limits<float>::quiet_NaN();
+constexpr auto inf = std::numeric_limits<float>::infinity();
+
+// f8e4m3 subnormal step is 2^-9; signed zero inputs are exact in f16 and bf16
+const std::vector<float> signed_zero_data{-0.f, -0x1p-11f, -0.5f * 0x1p-9f, -0.625f * 0x1p-9f, 0.f, 0.5f * 0x1p-9f};
+const std::vector<float> signed_zero_expected{-0.f, -0.f, -0.f, -0x1p-9f, 0.f, 0.f};
+
+INSTANTIATE_TEST_SUITE_P(
+ smoke_FakeConvert_Rounding_Special_Values_With_Hardcoded_Refs,
+ ReferenceFakeConvertLayerTest,
+ ::testing::Values(
+ FakeConvertParams{"subnormal_sign_nan",
+ element::f32,
+ element::f8e4m3,
+ {1.25f * 0x1p-10f, 3 * 0x1p-10f, 7 * 0x1p-10f, -0x1p-11f, nan},
+ {0x1p-9f, 0x1p-8f, 0x1p-7f, -0.f, nan}},
+ // just above a tie in f32, which is a tie in f16
+ FakeConvertParams{"near_tie", element::f32, element::f8e4m3, {1.0625f + 0x1p-20f}, {1.125f}},
+ FakeConvertParams{"signed_zero", element::f16, element::f8e4m3, signed_zero_data, signed_zero_expected},
+ FakeConvertParams{"signed_zero", element::bf16, element::f8e4m3, signed_zero_data, signed_zero_expected},
+ // -2^-18 is below half of the lowest f8e5m2 subnormal
+ FakeConvertParams{"negative_zero", element::f32, element::f8e5m2, {-0x1p-18f}, {-0.f}},
+ FakeConvertParams{"near_tie", element::f32, element::f8e5m2, {1.125f + 0x1p-19f}, {1.25f}},
+ FakeConvertParams{"inf_nan", element::f16, element::f8e5m2, {inf, -inf, nan}, {57344.f, -57344.f, nan}}),
+ ReferenceFakeConvertLayerTest::getTestCaseName);
+
+} // namespace
diff --git a/src/plugins/template/tests/functional/op_reference/sources.cmake b/src/plugins/template/tests/functional/op_reference/sources.cmake
index 8fd640a01c5..b1a1ceff408 100644
--- a/src/plugins/template/tests/functional/op_reference/sources.cmake
+++ b/src/plugins/template/tests/functional/op_reference/sources.cmake
@@ -77,6 +77,7 @@ set(OV_TEMPLATE_TESTS_OP_REFERENCE_SRCS
${CMAKE_CURRENT_LIST_DIR}/experimental_detectron_topkrois.cpp
${CMAKE_CURRENT_LIST_DIR}/extract_image_patches.cpp
${CMAKE_CURRENT_LIST_DIR}/eye.cpp
+ ${CMAKE_CURRENT_LIST_DIR}/fake_convert.cpp
${CMAKE_CURRENT_LIST_DIR}/fake_quantize.cpp
${CMAKE_CURRENT_LIST_DIR}/floor.cpp
${CMAKE_CURRENT_LIST_DIR}/floor_mod.cpp