OpenVINO™ is an open source toolkit for optimizing and deploying AI inference
C++ aicomputer-visiondeep-learningdeploy-aidiffusion-modelsgenerative-aigood-first-issueinferencellm-inferencenatural-language-processingnlpopenvinooptimize-aiperformance-boostrecommendation-systemspeech-recognitionstable-diffusiontransformersyolo
[CPU] Saturate f32 scalar constants exceeding bf16 range in BF16 inference (#39496)
Bo Liu7897adcfc9c4
diff --git a/src/plugins/intel_cpu/sources.cmake b/src/plugins/intel_cpu/sources.cmakeindex 01fb50ef259..da56b0b5d93 100644--- a/src/plugins/intel_cpu/sources.cmake+++ b/src/plugins/intel_cpu/sources.cmake@@ -593,6 +593,8 @@ set(CPU_PLUGIN_SRCS${CPU_SRC_DIR}/transformations/cpu_opset/common/pass/align_matmul_input_ranks.hpp${CPU_SRC_DIR}/transformations/cpu_opset/common/pass/causal_mask_preprocess_fusion.cpp${CPU_SRC_DIR}/transformations/cpu_opset/common/pass/causal_mask_preprocess_fusion.hpp+ ${CPU_SRC_DIR}/transformations/cpu_opset/common/pass/clamp_bf16_scalar_constants.cpp+ ${CPU_SRC_DIR}/transformations/cpu_opset/common/pass/clamp_bf16_scalar_constants.hpp${CPU_SRC_DIR}/transformations/cpu_opset/common/pass/convert_broadcast_to_tiles.cpp${CPU_SRC_DIR}/transformations/cpu_opset/common/pass/convert_broadcast_to_tiles.hpp${CPU_SRC_DIR}/transformations/cpu_opset/common/pass/convert_fq_rnn_to_quantized_rnn.cppdiff --git a/src/plugins/intel_cpu/src/transformations/cpu_opset/common/pass/clamp_bf16_scalar_constants.cpp b/src/plugins/intel_cpu/src/transformations/cpu_opset/common/pass/clamp_bf16_scalar_constants.cppnew file mode 100644index 00000000000..e41eba11dc9--- /dev/null+++ b/src/plugins/intel_cpu/src/transformations/cpu_opset/common/pass/clamp_bf16_scalar_constants.cpp@@ -0,0 +1,82 @@+// Copyright (C) 2018-2026 Intel Corporation+// SPDX-License-Identifier: Apache-2.0+//++#include "clamp_bf16_scalar_constants.hpp"++#include <algorithm>+#include <cmath>+#include <limits>+#include <memory>++#include "openvino/cc/pass/itt.hpp"+#include "openvino/core/node.hpp"+#include "openvino/core/node_output.hpp"+#include "openvino/core/rt_info.hpp"+#include "openvino/core/shape.hpp"+#include "openvino/core/type.hpp"+#include "openvino/core/type/bfloat16.hpp"+#include "openvino/core/type/element_type.hpp"+#include "openvino/op/add.hpp"+#include "openvino/op/constant.hpp"+#include "openvino/op/multiply.hpp"+#include "openvino/op/subtract.hpp"+#include "openvino/pass/matcher_pass.hpp"+#include "openvino/pass/pattern/matcher.hpp"+#include "openvino/pass/pattern/op/label.hpp"+#include "openvino/pass/pattern/op/or.hpp"+#include "openvino/pass/pattern/op/wrap_type.hpp"+#include "openvino/util/pp.hpp"++namespace ov::intel_cpu {++ClampBF16ScalarConstants::ClampBF16ScalarConstants() {+ MATCHER_SCOPE(ClampBF16ScalarConstants);+ using namespace ov::pass::pattern;+ using ov::pass::operator|;++ const auto bf16_max = static_cast<float>(std::numeric_limits<ov::bfloat16>::max());++ // f32 scalar constant with a finite value that would overflow to inf in bf16 (inf and NaN are kept as is)+ auto overflowing_const_m = wrap_type<ov::op::v0::Constant>([bf16_max](const ov::Output<ov::Node>& output) {+ const auto constant = ov::as_type_ptr<ov::op::v0::Constant>(output.get_node_shared_ptr());+ if (!constant || constant->get_element_type() != ov::element::f32 ||+ ov::shape_size(constant->get_shape()) != 1) {+ return false;+ }+ const float value = *constant->get_data_ptr<float>();+ return std::isfinite(value) && std::abs(value) > bf16_max;+ });++ // The constant can be either operand of the (possibly non-commutative) binary op+ auto const_second_m =+ wrap_type<ov::op::v1::Multiply, ov::op::v1::Add, ov::op::v1::Subtract>({any_input(), overflowing_const_m});+ auto const_first_m =+ wrap_type<ov::op::v1::Multiply, ov::op::v1::Add, ov::op::v1::Subtract>({overflowing_const_m, any_input()});+ auto binary_m = const_second_m | const_first_m;++ ov::matcher_pass_callback callback = [OV_CAPTURE_CPY_AND_THIS](Matcher& m) {+ const auto& pattern_map = m.get_pattern_value_map();+ const auto constant =+ ov::as_type_ptr<ov::op::v0::Constant>(pattern_map.at(overflowing_const_m).get_node_shared_ptr());+ const float value = *constant->get_data_ptr<float>();+ auto clamped = std::make_shared<ov::op::v0::Constant>(ov::element::f32,+ constant->get_shape(),+ std::clamp(value, -bf16_max, bf16_max));+ clamped->set_friendly_name(constant->get_friendly_name());+ ov::copy_runtime_info(constant, clamped);++ // Only this consumer is updated: the constant may be shared with ops that are not affected by bf16+ for (auto& input : m.get_match_root()->inputs()) {+ if (input.get_source_output().get_node() == constant.get()) {+ input.replace_source_output(clamped);+ }+ }+ return true;+ };++ auto m = std::make_shared<Matcher>(binary_m, matcher_name);+ this->register_matcher(m, callback);+}++} // namespace ov::intel_cpudiff --git a/src/plugins/intel_cpu/src/transformations/cpu_opset/common/pass/clamp_bf16_scalar_constants.hpp b/src/plugins/intel_cpu/src/transformations/cpu_opset/common/pass/clamp_bf16_scalar_constants.hppnew file mode 100644index 00000000000..dfa7e3e2a3e--- /dev/null+++ b/src/plugins/intel_cpu/src/transformations/cpu_opset/common/pass/clamp_bf16_scalar_constants.hpp@@ -0,0 +1,33 @@+// Copyright (C) 2018-2026 Intel Corporation+// SPDX-License-Identifier: Apache-2.0+//++#pragma once++#include "openvino/pass/matcher_pass.hpp"++namespace ov::intel_cpu {++/**+ * @brief Saturates f32 scalar constants of Multiply/Add/Subtract that exceed the bf16 range, which would otherwise+ * overflow to inf when the op runs in bf16.+ *+ * E.g. an attention mask `(1 - mask) * f32_lowest` is reassociated into `mask * f32_max + f32_lowest`, and in bf16+ * `mask * f32_max` becomes inf, so Softmax later produces NaN:+ *+ * before: mask -> Multiply(f32_max) -> Add(f32_lowest) -> ...+ * after: mask -> Multiply(bf16_max) -> Add(-bf16_max) -> ...+ *+ * Restrictions:+ * - Multiply/Add/Subtract only: the eltwise ops that mask-building chains consist of, and the ones that+ * ConvertToPowerStatic and Snippets pick up afterwards.+ * - Scalar constants only: no overflow with non-scalar ones has been reproduced.+ * - Must run before Snippets tokenization and ConvertToPowerStatic, which would otherwise consume the constants.+ */+class ClampBF16ScalarConstants : public ov::pass::MatcherPass {+public:+ OPENVINO_MATCHER_PASS_RTTI("ClampBF16ScalarConstants");+ ClampBF16ScalarConstants();+};++} // namespace ov::intel_cpudiff --git a/src/plugins/intel_cpu/src/transformations/transformation_pipeline.cpp b/src/plugins/intel_cpu/src/transformations/transformation_pipeline.cppindex 2b7a56d025c..e81a1936d57 100644--- a/src/plugins/intel_cpu/src/transformations/transformation_pipeline.cpp+++ b/src/plugins/intel_cpu/src/transformations/transformation_pipeline.cpp@@ -151,6 +151,7 @@#include "transformations/low_precision/mark_dequantization_subgraph.hpp"// CPU specific transformations+#include "transformations/cpu_opset/common/pass/clamp_bf16_scalar_constants.hpp"#include "transformations/cpu_opset/common/pass/disable_bf16_comp_cumsum_sin_gen.hpp"#include "transformations/cpu_opset/common/pass/insert_convert_after_extension.hpp"#include "transformations/cpu_opset/common/pass/ngram_fusion.hpp"@@ -1216,6 +1217,8 @@ void Transformations::PostLpt() {if (config.inferencePrecision == ov::element::bf16) {CPU_REGISTER_PASS_COMMON(postLPTPassManager, ov::pass::DisableBF16CompForLtxVideoRopePattern);CPU_REGISTER_PASS_COMMON(postLPTPassManager, ov::intel_cpu::DisableBF16CompCumSumSinGen);+ // Must be before Snippets tokenization and ConvertToPowerStatic (CpuSpecificOpSet)+ CPU_REGISTER_PASS_COMMON(postLPTPassManager, ov::intel_cpu::ClampBF16ScalarConstants);}// Should be before Snippets pipeline because Ngram pattern contains eltwise nodes that can be tokenized bydiff --git a/src/plugins/intel_cpu/tests/functional/custom/subgraph_tests/src/x64/bf16_attention_mask.cpp b/src/plugins/intel_cpu/tests/functional/custom/subgraph_tests/src/x64/bf16_attention_mask.cppnew file mode 100644index 00000000000..2013049b152--- /dev/null+++ b/src/plugins/intel_cpu/tests/functional/custom/subgraph_tests/src/x64/bf16_attention_mask.cpp@@ -0,0 +1,111 @@+// Copyright (C) 2018-2026 Intel Corporation+// SPDX-License-Identifier: Apache-2.0+//++#include <limits>+#include <string>++#include "internal_properties.hpp"+#include "openvino/op/add.hpp"+#include "openvino/op/constant.hpp"+#include "openvino/op/convert.hpp"+#include "openvino/op/matmul.hpp"+#include "openvino/op/multiply.hpp"+#include "openvino/op/softmax.hpp"+#include "openvino/op/subtract.hpp"+#include "openvino/op/unsqueeze.hpp"+#include "openvino/runtime/system_conf.hpp"+#include "shared_test_classes/base/ov_subgraph.hpp"++namespace ov::test {++/* `(1 - mask) * f32_lowest` shared by two attention blocks is reassociated into `mask * f32_max + f32_lowest`.+ f32_max overflows to +inf in bf16 and Softmax produces NaN (inf - inf). Covered with and without Snippets.++ mask[1,4]+ |+ Unsqueeze+ |+ Unsqueeze+ |+ Subtract(1, x)+ |+ Multiply(x, f32_lowest)+ / \+ / \+ Add(Q0 x K^T) Add(Q1 x K^T)+ | |+ Softmax Softmax+ | |+ x V x V+*/+class BF16AttentionMask : public testing::WithParamInterface<bool>, virtual public SubgraphBaseStaticTest {+public:+ static std::string getTestCaseName(const testing::TestParamInfo<bool>& obj) {+ return obj.param ? "Snippets=ON" : "Snippets=OFF";+ }++protected:+ void SetUp() override {+ if (!ov::with_cpu_x86_bfloat16()) {+ GTEST_SKIP() << "Native bf16 support is required";+ }+ targetDevice = utils::DEVICE_CPU;+ configuration[ov::hint::inference_precision.name()] = ov::element::bf16;+ if (!GetParam()) {+ configuration.insert(ov::intel_cpu::snippets_mode(ov::intel_cpu::SnippetsMode::DISABLE));+ }+ abs_threshold = 0.1f;++ const Shape qkv_shape{1, 1, 4, 4};+ auto query0 = std::make_shared<op::v0::Parameter>(element::f32, qkv_shape);+ auto query1 = std::make_shared<op::v0::Parameter>(element::f32, qkv_shape);+ auto key = std::make_shared<op::v0::Parameter>(element::f32, qkv_shape);+ auto value = std::make_shared<op::v0::Parameter>(element::f32, qkv_shape);+ auto mask = std::make_shared<op::v0::Parameter>(element::f32, Shape{1, 4});++ auto axes = op::v0::Constant::create(element::i64, Shape{1}, {1});+ auto expanded = std::make_shared<op::v0::Unsqueeze>(std::make_shared<op::v0::Unsqueeze>(mask, axes), axes);+ auto complement =+ std::make_shared<op::v1::Subtract>(op::v0::Constant::create(element::f32, Shape{1, 1, 1, 1}, {1.f}),+ expanded);+ auto extended_mask = std::make_shared<op::v1::Multiply>(+ complement,+ op::v0::Constant::create(element::f32, Shape{1, 1, 1, 1}, {std::numeric_limits<float>::lowest()}));++ OutputVector results;+ for (const auto& query : {query0, query1}) {+ auto scores = std::make_shared<op::v0::MatMul>(query, key, false, true);+ auto attention = std::make_shared<op::v1::Softmax>(std::make_shared<op::v1::Add>(scores, extended_mask), 3);+ auto output = std::make_shared<op::v0::MatMul>(attention, value);+ results.push_back(std::make_shared<op::v0::Convert>(output, element::bf16));+ }+ function = std::make_shared<Model>(results, ParameterVector{query0, query1, key, value, mask});+ }++ void generate_inputs(const std::vector<ov::Shape>&) override {+ inputs.clear();+ const auto& parameters = function->get_parameters();+ for (const auto& parameter : parameters) {+ ov::Tensor tensor{element::f32, parameter->get_shape()};+ auto* data = tensor.data<float>();+ // all positions of the mask are unmasked (1), so every Softmax row must stay finite+ const bool is_mask = parameter == parameters.back();+ for (size_t i = 0; i < tensor.get_size(); ++i) {+ data[i] = is_mask ? 1.f : static_cast<float>(i % 7) / 10.f;+ }+ inputs.insert({parameter, tensor});+ }+ }+};++TEST_P(BF16AttentionMask, CompareWithRefs) {+ run();+}++INSTANTIATE_TEST_SUITE_P(smoke_BF16AttentionMask,+ BF16AttentionMask,+ ::testing::Values(true, false),+ BF16AttentionMask::getTestCaseName);++} // namespace ov::testdiff --git a/src/plugins/intel_cpu/tests/functional/sources.cmake b/src/plugins/intel_cpu/tests/functional/sources.cmakeindex 43ec997b837..90e4db4551b 100644--- a/src/plugins/intel_cpu/tests/functional/sources.cmake+++ b/src/plugins/intel_cpu/tests/functional/sources.cmake@@ -299,6 +299,7 @@ set(CPU_FUNC_TESTS_X64_SRCS${CMAKE_CURRENT_LIST_DIR}/custom/single_layer_tests/instances/x64/rms_norm.cpp${CMAKE_CURRENT_LIST_DIR}/custom/single_layer_tests/instances/x64/softmax.cpp${CMAKE_CURRENT_LIST_DIR}/custom/single_layer_tests/instances/x64/transpose.cpp+ ${CMAKE_CURRENT_LIST_DIR}/custom/subgraph_tests/src/x64/bf16_attention_mask.cpp${CMAKE_CURRENT_LIST_DIR}/custom/subgraph_tests/src/x64/bf16_convert_saturation.cpp${CMAKE_CURRENT_LIST_DIR}/custom/subgraph_tests/src/x64/bf16_embed_tokens_rms.cpp${CMAKE_CURRENT_LIST_DIR}/custom/subgraph_tests/src/x64/bf16_rotary_emb_matmul.cpp