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
[TRANSFORMATIONS][CPU] Share activations scaling between GPU and CPU (#38563)
Aditya Goyal9f5a30288376
diff --git a/docs/articles_en/openvino-workflow/running-inference/inference-devices-and-modes/cpu-device.rst b/docs/articles_en/openvino-workflow/running-inference/inference-devices-and-modes/cpu-device.rstindex 4d73bf046dc..625739ab8f2 100644--- a/docs/articles_en/openvino-workflow/running-inference/inference-devices-and-modes/cpu-device.rst+++ b/docs/articles_en/openvino-workflow/running-inference/inference-devices-and-modes/cpu-device.rst@@ -372,6 +372,7 @@ The plugin supports the following properties:- ``ov::hint::inference_precision``- ``ov::hint::performance_mode``- ``ov::hint::execution_mode``+ - ``ov::hint::activations_scale_factor``- ``ov::hint::num_request``- ``ov::hint::scheduling_core_type``- ``ov::hint::enable_hyper_threading``diff --git a/docs/articles_en/openvino-workflow/running-inference/optimize-inference/precision-control.rst b/docs/articles_en/openvino-workflow/running-inference/optimize-inference/precision-control.rstindex af759c0620f..660d7cf19c4 100644--- a/docs/articles_en/openvino-workflow/running-inference/optimize-inference/precision-control.rst+++ b/docs/articles_en/openvino-workflow/running-inference/optimize-inference/precision-control.rst@@ -103,7 +103,7 @@ To address this issue, activation scaling divides the input of linear operationsThe layer's output is then multiplied back by the activations scale factor to restore its original value, but overflow can occur again during this process.Activation scaling uses :doc:`LPT (Low Precision Transformations) <../../../documentation/openvino-extensibility/openvino-plugin-library/advanced-guides/low-precision-transformations>` to delay multiplication by the scale factor as much as possible, preventing overflow.The activations scale factor can be specified in the ``rt_info`` of the model IR or via ``ov::hint::activations_scale_factor``.-Currently, this property is supported on GPU.+Currently, this property is supported on GPU and on CPU... scrollbox::diff --git a/src/common/transformations/include/transformations/common_optimizations/activations_scaling.hpp b/src/common/transformations/include/transformations/common_optimizations/activations_scaling.hppindex 595c894c182..18f31ed99a2 100644--- a/src/common/transformations/include/transformations/common_optimizations/activations_scaling.hpp+++ b/src/common/transformations/include/transformations/common_optimizations/activations_scaling.hpp@@ -6,7 +6,9 @@#include <memory>+#include "openvino/core/type/element_type.hpp"#include "openvino/pass/matcher_pass.hpp"+#include "openvino/pass/pass.hpp"#include "transformations_visibility.hpp"namespace ov {@@ -30,6 +32,33 @@ class TRANSFORMATIONS_API MoveDownScalarMul;// For example, when this property is set as 16, activations are divided by 16.// If ov::hint::activations_scale_factor is less than or equal to zero, it is disabled.+/**+ * @ingroup ov_transformation_common_api+ * @brief Keeps activations of a reduced-precision model in range by scaling them down around+ * Convolution/MatMul layers.+ *+ * Linear layers can produce activations beyond the range of the scaled precision (e.g. above 65504+ * for f16), which turns into inf and then NaN at the following normalization. Since+ * Conv(x / s) = Conv(x) / s, the pass divides the input of every Conv/MatMul whose input already has+ * the scaled precision by the scale factor and multiplies the output back. The scale-up Multiplies+ * are then moved down the graph and eliminated where possible: against the scale-down of the next+ * Conv/MatMul, or at a normalization (see EliminateScalarMul).+ *+ * The pass runs its own pipeline on a copy of the caller's PassConfig: the caller's callbacks apply to+ * the inner passes, while the LPT transformations disabled here stay disabled only inside the pass.+ * A scale factor <= 0 disables the pass.+ */+class ov::pass::ActivationsScaling : public ov::pass::ModelPass {+public:+ OPENVINO_MODEL_PASS_RTTI("ActivationsScaling");+ ActivationsScaling(float scale_factor, ov::element::Type scaled_prec);+ bool run_on_model(const std::shared_ptr<ov::Model>& model) override;++private:+ const float m_scale_factor;+ const ov::element::Type m_scaled_prec;+};+// Add scale_down and scale_up layers around Convolution and MatMul nodes// Conv/MatMul// ==>@@ -40,15 +69,15 @@ public:ScaleDownSingleLayer(float scale_factor, ov::element::Type scaled_prec);};-// Normalization and ShapeOf have the following property.+// Normalization and ShapeOf are invariant to a scalar scale of the input://-// Norm(input * const_a) = Norm(input)+// Norm(input * s) = Norm(input) with epsilon / s^2 (epsilon / s for MVN with epsilon outside the sqrt)//-// So, we can skip Multiply that is connected to Normalization and ShapeOf.+// So the Multiply in front of them is dropped, also when a Convert follows it (normalizations kept in f32).//-// input --> Multiply --> Normalization/ShapeOf+// input --> Multiply --> [Convert] --> Normalization/ShapeOf// ==>-// input --> Normalization/ShapeOf+// input --> [Convert] --> Normalization/ShapeOf (epsilon adjusted)class ov::pass::activations_scaling::EliminateScalarMul : public ov::pass::MatcherPass {public:OPENVINO_MATCHER_PASS_RTTI("EliminateScalarMul", "0");diff --git a/src/common/transformations/src/transformations/common_optimizations/activations_scaling.cpp b/src/common/transformations/src/transformations/common_optimizations/activations_scaling.cppindex 481b3e0d201..b1dd873fe82 100644--- a/src/common/transformations/src/transformations/common_optimizations/activations_scaling.cpp+++ b/src/common/transformations/src/transformations/common_optimizations/activations_scaling.cpp@@ -7,7 +7,18 @@#include <memory>#include "itt.hpp"+#include "low_precision/convolution.hpp"+#include "low_precision/convolution_backprop_data.hpp"+#include "low_precision/fake_quantize_decomposition.hpp"+#include "low_precision/fold_convert.hpp"+#include "low_precision/fuse_convert.hpp"+#include "low_precision/group_convolution.hpp"+#include "low_precision/low_precision.hpp"+#include "low_precision/mat_mul.hpp"+#include "low_precision/multiply_to_group_convolution.hpp"+#include "low_precision/mvn.hpp"#include "low_precision/network_helper.hpp"+#include "low_precision/recurrent_cell.hpp"#include "openvino/core/graph_util.hpp"#include "openvino/core/rt_info.hpp"#include "openvino/op/add.hpp"@@ -15,22 +26,30 @@#include "openvino/op/convert.hpp"#include "openvino/op/convolution.hpp"#include "openvino/op/divide.hpp"+#include "openvino/op/fake_quantize.hpp"#include "openvino/op/group_normalization.hpp"#include "openvino/op/matmul.hpp"#include "openvino/op/multiply.hpp"#include "openvino/op/mvn.hpp"#include "openvino/op/reshape.hpp"#include "openvino/op/shape_of.hpp"+#include "openvino/op/transpose.hpp"#include "openvino/op/unsqueeze.hpp"+#include "openvino/op/util/shape_of_base.hpp"#include "openvino/op/variadic_split.hpp"#include "openvino/pass/constant_folding.hpp"#include "openvino/pass/manager.hpp"#include "openvino/pass/pattern/op/optional.hpp"#include "openvino/pass/pattern/op/or.hpp"#include "openvino/pass/pattern/op/wrap_type.hpp"+#include "openvino/pass/validate.hpp"#include "ov_ops/moe_compressed.hpp"#include "ov_ops/rms.hpp"#include "transformations/common_optimizations/lin_op_sequence_fusion.hpp"+#include "transformations/common_optimizations/move_eltwise_up_data_movement.hpp"+#include "transformations/common_optimizations/nop_elimination.hpp"+#include "transformations/common_optimizations/shared_ops_optimization.hpp"+#include "transformations/rt_info/dequantization_node.hpp"#include "transformations/utils/utils.hpp"namespace v0 = ov::op::v0;@@ -209,12 +228,14 @@ activations_scaling::EliminateScalarMul::EliminateScalarMul() {auto convert_m = pattern::optional<v0::Convert>(activation_m);auto scale_const_m = pattern::wrap_type<v0::Constant>(is_scalar_node);auto mul_m = pattern::wrap_type<v1::Multiply>({convert_m, scale_const_m});- auto mvn_m = pattern::wrap_type<v6::MVN>({mul_m, pattern::any_input()});- auto rms_m = pattern::wrap_type<ov::op::internal::RMS>({mul_m, pattern::any_input()}) |- pattern::wrap_type<ov::op::internal::RMS>({mul_m});+ // the normalization may be kept in f32+ auto post_convert_m = pattern::optional<v0::Convert>(mul_m);+ auto mvn_m = pattern::wrap_type<v6::MVN>({post_convert_m, pattern::any_input()});+ auto rms_m = pattern::wrap_type<ov::op::internal::RMS>({post_convert_m, pattern::any_input()}) |+ pattern::wrap_type<ov::op::internal::RMS>({post_convert_m});auto group_norm_m =- pattern::wrap_type<v12::GroupNormalization>({mul_m, pattern::any_input(), pattern::any_input()});- auto shape_of_m = pattern::wrap_type<v3::ShapeOf>({mul_m});+ pattern::wrap_type<v12::GroupNormalization>({post_convert_m, pattern::any_input(), pattern::any_input()});+ auto shape_of_m = pattern::wrap_type<ov::op::util::ShapeOfBase>({post_convert_m});auto norm_m = mvn_m | rms_m | group_norm_m | shape_of_m;ov::matcher_pass_callback callback = [OV_CAPTURE_CPY_AND_THIS](pattern::Matcher& m) {@@ -224,36 +245,44 @@ activations_scaling::EliminateScalarMul::EliminateScalarMul() {return false;}- auto scale_const = ov::as_type_ptr<v0::Constant>(pattern_map.at(scale_const_m).get_node_shared_ptr());+ const auto scale_const = ov::as_type_ptr<v0::Constant>(pattern_map.at(scale_const_m).get_node_shared_ptr());+ OPENVINO_ASSERT(scale_const && ov::shape_size(scale_const->get_shape()) == 1,+ "EliminateScalarMul: the scale is expected to be a scalar Constant");+ const double scale = scale_const->cast_vector<double>()[0];- if (pattern_map.count(shape_of_m) == 0 && scale_const->cast_vector<float>()[0] < 1.f)+ if (pattern_map.count(shape_of_m) == 0 && scale < 1.0)return false;auto activation = pattern_map.at(activation_m);auto norm = pattern_map.at(norm_m).get_node_shared_ptr();+ if (pattern_map.count(post_convert_m)) {+ // the Convert may have other consumers+ auto convert = pattern_map.at(post_convert_m).get_node_shared_ptr();+ // clone_with_new_inputs() doesn't copy rt_info+ auto new_convert = convert->clone_with_new_inputs({activation});+ ov::copy_runtime_info(convert, new_convert);+ activation = new_convert->output(0);+ }+norm->input(0).replace_source_output(activation);if (pattern_map.count(rms_m)) {auto rms = ov::as_type_ptr<ov::op::internal::RMS>(pattern_map.at(rms_m).get_node_shared_ptr());- auto eps = rms->get_epsilon();- double scale_const_val = scale_const->cast_vector<double>()[0];- rms->set_epsilon(eps / scale_const_val / scale_const_val);+ rms->set_epsilon(rms->get_epsilon() / scale / scale);} else if (pattern_map.count(group_norm_m)) {auto group_norm =ov::as_type_ptr<v12::GroupNormalization>(pattern_map.at(group_norm_m).get_node_shared_ptr());- auto eps = group_norm->get_epsilon();- double scale_const_val = scale_const->cast_vector<double>()[0];- group_norm->set_epsilon(eps / scale_const_val / scale_const_val);+ group_norm->set_epsilon(group_norm->get_epsilon() / scale / scale);} else if (pattern_map.count(mvn_m)) {auto mvn = ov::as_type_ptr<v6::MVN>(pattern_map.at(mvn_m).get_node_shared_ptr());auto eps_mode = mvn->get_eps_mode();auto eps = mvn->get_eps();- float scale_const_val = scale_const->cast_vector<float>()[0];+ const auto scale_f = static_cast<float>(scale);if (eps_mode == ov::op::MVNEpsMode::INSIDE_SQRT) {- mvn->set_eps(eps / scale_const_val / scale_const_val);+ mvn->set_eps(eps / scale_f / scale_f);} else {- mvn->set_eps(eps / scale_const_val);+ mvn->set_eps(eps / scale_f);}}@@ -385,4 +414,73 @@ activations_scaling::MoveDownScalarMul::MoveDownScalarMul() {this->register_matcher(m, callback);}+ActivationsScaling::ActivationsScaling(float scale_factor, ov::element::Type scaled_prec)+ : m_scale_factor(scale_factor),+ m_scaled_prec(scaled_prec) {}++bool ActivationsScaling::run_on_model(const std::shared_ptr<ov::Model>& model) {+ RUN_ON_MODEL_SCOPE(ActivationsScaling);+ if (m_scale_factor <= 0.f)+ return false;++ using namespace ov::pass::low_precision;++ // a copy keeps the caller's callbacks (e.g. plugin restrictions on MoveEltwiseUpThroughDataMovScalar),+ // while the disables below don't leak to the caller+ Manager manager(*get_pass_config(), "ActivationsScaling");+ manager.set_per_pass_validation(false);+ auto pass_config = manager.get_pass_config();++ manager.register_pass<activations_scaling::ScaleDownSingleLayer>(m_scale_factor, m_scaled_prec);+ manager.register_pass<SharedOpOptimization>();++ pass_config->set_callback<activations_scaling::ScaleDownSingleLayer>(+ [scaled_prec = m_scaled_prec](const std::shared_ptr<const Node>& node) -> bool {+ return node->input(0).get_element_type() != scaled_prec;+ });++ // Move down scalar-multiply layers as much as possible+ auto params = LayerTransformation::Params(false, m_scaled_prec, {m_scaled_prec}, true, true);+ auto lpt_pass = manager.register_pass<LowPrecision>(std::vector<PrecisionsRestriction>{},+ std::vector<QuantizationGranularityRestriction>{},+ params);+ lpt_pass->add_main<activations_scaling::EliminateScalarMul>();+ lpt_pass->add_main<activations_scaling::MoveDownScalarMul>();++ // keeps LPT's LinOpSequenceFusion prerequisite from fusing scale Multiplies into bias Adds+ pass_config->disable<AddMultiplyFusion>();+ pass_config->disable<RecurrentCellTransformation>();+ pass_config->disable<MultiplyToGroupConvolutionTransformation>();+ pass_config->disable<ConvolutionTransformation>();+ pass_config->disable<ConvolutionBackpropDataTransformation>();+ pass_config->disable<GroupConvolutionTransformation>();+ pass_config->disable<MatMulTransformation>();+ pass_config->disable<MVNTransformation>();+ // This LPT run only moves scalar Multiply layers. FakeQuantize layers left by the INT8 LPT run (e.g. Q/K+ // quantization before SDPA) must not be decomposed again: the f16 DataPrecision interval (+/-1e15)+ // overflows f16 and turns the quantized activations into inf/NaN.+ pass_config->disable<FakeQuantizeDecompositionTransformation>();++ pass_config->set_callback<FoldConvertTransformation>([](const std::shared_ptr<const Node>& node) -> bool {+ return ov::is_dequantization_node(node);+ });+ pass_config->set_callback<FuseConvertTransformation>([](const std::shared_ptr<const Node>& node) -> bool {+ return ov::is_dequantization_node(node) || ov::is_type<v0::FakeQuantize>(node);+ });++ // Move up remained scalar-multiply layers+ manager.register_pass<EliminateEltwise>();+ manager.register_pass<activations_scaling::MulShareTransformation>();++ const std::vector<DiscreteTypeInfo> allowed_data_movement_ops = {+ v1::Reshape::get_type_info_static(),+ v1::Transpose::get_type_info_static(),+ };+ manager.register_pass<MoveEltwiseUpThroughDataMovScalar>(allowed_data_movement_ops);+ manager.register_pass<SharedOpOptimization>();+ manager.register_pass<Validate>();++ return manager.run_passes(model);+}+} // namespace ov::passdiff --git a/src/common/transformations/src/transformations/common_optimizations/shared_ops_optimization.cpp b/src/common/transformations/src/transformations/common_optimizations/shared_ops_optimization.cppindex dfee6af700d..0ebe83464ac 100644--- a/src/common/transformations/src/transformations/common_optimizations/shared_ops_optimization.cpp+++ b/src/common/transformations/src/transformations/common_optimizations/shared_ops_optimization.cpp@@ -145,7 +145,9 @@ bool shape_of_upgrade(const shared_ptr<Model>& model) {rewritten = shape_of_upgrade(sub_graph) || rewritten;}} else if (auto v1_shape_of = ov::as_type_ptr<v0::ShapeOf>(op)) {- auto v3_shape_of = std::make_shared<ov::op::v3::ShapeOf>(v1_shape_of->input_value(0), element::i64);+ // keep the output type: a type-relaxed v0::ShapeOf may already produce i32+ auto v3_shape_of = std::make_shared<ov::op::v3::ShapeOf>(v1_shape_of->input_value(0),+ v1_shape_of->get_output_element_type(0));v3_shape_of->set_friendly_name(v1_shape_of->get_friendly_name());ov::replace_output_update_name(v1_shape_of, v3_shape_of);rewritten = true;diff --git a/src/common/transformations/tests/common_optimizations/activations_scaling_test.cpp b/src/common/transformations/tests/common_optimizations/activations_scaling_test.cppindex 933bbe820e4..b461cd05ea2 100644--- a/src/common/transformations/tests/common_optimizations/activations_scaling_test.cpp+++ b/src/common/transformations/tests/common_optimizations/activations_scaling_test.cpp@@ -7,12 +7,14 @@#include <gtest/gtest.h>#include <memory>+#include <sstream>#include <string>#include "common_test_utils/graph_comparator.hpp"#include "common_test_utils/ov_test_utils.hpp"#include "openvino/op/add.hpp"#include "openvino/op/constant.hpp"+#include "openvino/op/convert.hpp"#include "openvino/op/convolution.hpp"#include "openvino/op/gelu.hpp"#include "openvino/op/group_normalization.hpp"@@ -21,6 +23,7 @@#include "openvino/op/mvn.hpp"#include "openvino/op/parameter.hpp"#include "openvino/op/reshape.hpp"+#include "openvino/op/result.hpp"#include "openvino/op/shape_of.hpp"#include "openvino/op/variadic_split.hpp"#include "openvino/pass/manager.hpp"@@ -338,6 +341,239 @@ TEST_F(TransformationTestsF, EliminateScalarMulTest) {comparator.enable(FunctionsComparator::CmpValues::ACCURACY);}+namespace {+enum class NormType { RMS, RMSWithoutGamma, MVN, GroupNorm };++std::ostream& operator<<(std::ostream& os, NormType type) {+ switch (type) {+ case NormType::RMS:+ return os << "RMS";+ case NormType::RMSWithoutGamma:+ return os << "RMSWithoutGamma";+ case NormType::MVN:+ return os << "MVN";+ case NormType::GroupNorm:+ return os << "GroupNorm";+ default:+ OPENVINO_THROW("Unknown NormType");+ }+}++// f32 normalization over [1, 3, 4, 4], as kept by ConvertPrecision in an f16 model+std::shared_ptr<ov::Node> make_f32_norm(NormType type, const ov::Output<ov::Node>& input, double epsilon) {+ switch (type) {+ case NormType::RMS: {+ auto gamma = v0::Constant::create(ov::element::f32, ov::Shape{4}, {10});+ return std::make_shared<ov::op::internal::RMS>(input, gamma, epsilon, ov::element::f32);+ }+ case NormType::RMSWithoutGamma:+ return std::make_shared<ov::op::internal::RMS>(input, epsilon, ov::element::f32);+ case NormType::MVN: {+ auto axes = v0::Constant::create(ov::element::i64, ov::Shape{2}, {2, 3});+ return std::make_shared<ov::op::v6::MVN>(input,+ axes,+ true,+ static_cast<float>(epsilon),+ ov::op::MVNEpsMode::INSIDE_SQRT);+ }+ case NormType::GroupNorm: {+ auto scale = v0::Constant::create(ov::element::f32, ov::Shape{3}, {10});+ auto bias = v0::Constant::create(ov::element::f32, ov::Shape{3}, {10});+ return std::make_shared<v12::GroupNormalization>(input, scale, bias, 1, epsilon);+ }+ default:+ OPENVINO_THROW("Unknown NormType");+ }+}++class EliminateScalarMulF32NormTest : public TransformationTestsF, public WithParamInterface<NormType> {+public:+ static std::string getTestCaseName(const testing::TestParamInfo<NormType>& info) {+ std::ostringstream ss;+ ss << info.param;+ return ss.str();+ }++protected:+ void SetUp() override {+ TransformationTestsF::SetUp();+ comparator.enable(FunctionsComparator::ATTRIBUTES);+ manager.register_pass<ov::pass::activations_scaling::EliminateScalarMul>();+ }+};++constexpr float kScale = 8.f;+constexpr double kEpsilon = 1.0;+} // namespace++TEST_P(EliminateScalarMulF32NormTest, ConvertBeforeNorm) {+ {+ auto input = std::make_shared<v0::Parameter>(ov::element::f16, ov::PartialShape{1, 3, 4, 4});+ auto mul = std::make_shared<v1::Multiply>(input, v0::Constant::create(ov::element::f16, ov::Shape{}, {kScale}));+ auto convert = std::make_shared<v0::Convert>(mul, ov::element::f32);+ auto norm = make_f32_norm(GetParam(), convert, kEpsilon);+ model = std::make_shared<ov::Model>(ov::OutputVector{norm}, ov::ParameterVector{input});+ }+ {+ auto input = std::make_shared<v0::Parameter>(ov::element::f16, ov::PartialShape{1, 3, 4, 4});+ auto convert = std::make_shared<v0::Convert>(input, ov::element::f32);+ auto norm = make_f32_norm(GetParam(), convert, kEpsilon / kScale / kScale);+ model_ref = std::make_shared<ov::Model>(ov::OutputVector{norm}, ov::ParameterVector{input});+ }+}++TEST_P(EliminateScalarMulF32NormTest, SharedConvertBeforeNorm) {+ {+ auto input = std::make_shared<v0::Parameter>(ov::element::f16, ov::PartialShape{1, 3, 4, 4});+ auto mul = std::make_shared<v1::Multiply>(input, v0::Constant::create(ov::element::f16, ov::Shape{}, {kScale}));+ auto convert = std::make_shared<v0::Convert>(mul, ov::element::f32);+ auto norm = make_f32_norm(GetParam(), convert, kEpsilon);+ model = std::make_shared<ov::Model>(ov::OutputVector{norm, convert}, ov::ParameterVector{input});+ }+ {+ auto input = std::make_shared<v0::Parameter>(ov::element::f16, ov::PartialShape{1, 3, 4, 4});+ auto norm_convert = std::make_shared<v0::Convert>(input, ov::element::f32);+ auto norm = make_f32_norm(GetParam(), norm_convert, kEpsilon / kScale / kScale);+ auto mul = std::make_shared<v1::Multiply>(input, v0::Constant::create(ov::element::f16, ov::Shape{}, {kScale}));+ auto convert = std::make_shared<v0::Convert>(mul, ov::element::f32);+ model_ref = std::make_shared<ov::Model>(ov::OutputVector{norm, convert}, ov::ParameterVector{input});+ }+}++TEST_P(EliminateScalarMulF32NormTest, ScaleBelowOneIsKept) {+ auto input = std::make_shared<v0::Parameter>(ov::element::f16, ov::PartialShape{1, 3, 4, 4});+ auto mul = std::make_shared<v1::Multiply>(input, v0::Constant::create(ov::element::f16, ov::Shape{}, {0.5f}));+ auto convert = std::make_shared<v0::Convert>(mul, ov::element::f32);+ auto norm = make_f32_norm(GetParam(), convert, kEpsilon);+ model = std::make_shared<ov::Model>(ov::OutputVector{norm}, ov::ParameterVector{input});+}++INSTANTIATE_TEST_SUITE_P(+ TransformationTests,+ EliminateScalarMulF32NormTest,+ ::testing::Values(NormType::RMS, NormType::RMSWithoutGamma, NormType::MVN, NormType::GroupNorm),+ EliminateScalarMulF32NormTest::getTestCaseName);++namespace {+constexpr size_t kBlockHidden = 16;++// Convert as inserted by ConvertPrecision in front of a subgraph kept in f32+ov::Output<ov::Node> make_f32_convert(const ov::Output<ov::Node>& x) {+ auto convert = std::make_shared<v0::Convert>(x, ov::element::f32);+ disable_conversion(convert, ov::element::f16);+ disable_constant_folding(convert);+ return convert;+}++ov::Output<ov::Node> make_rms(const ov::Output<ov::Node>& x) {+ const auto& prec = x.get_element_type();+ auto gamma = v0::Constant::create(prec, ov::Shape{kBlockHidden}, {1.5f});+ return std::make_shared<ov::op::internal::RMS>(x, gamma, 1e-5, prec);+}++// RMS -> MatMul -> MatMul -> Add(residual) -> RMS; mixed: norms and residual Add kept in f32+std::shared_ptr<ov::Model> make_residual_block(bool mixed) {+ auto input = std::make_shared<v0::Parameter>(ov::element::f16, ov::PartialShape{1, 4, kBlockHidden});+ ov::Output<ov::Node> norm0 = make_rms(mixed ? make_f32_convert(input) : input);+ if (mixed)+ norm0 = std::make_shared<v0::Convert>(norm0, ov::element::f16);+ auto weights0 = v0::Constant::create(ov::element::f16, ov::Shape{kBlockHidden, kBlockHidden}, {0.1f});+ auto matmul0 = std::make_shared<v0::MatMul>(norm0, weights0);+ auto weights1 = v0::Constant::create(ov::element::f16, ov::Shape{kBlockHidden, kBlockHidden}, {0.1f});+ ov::Output<ov::Node> matmul1 = std::make_shared<v0::MatMul>(matmul0, weights1);+ ov::Output<ov::Node> residual = input;+ if (mixed) {+ matmul1 = make_f32_convert(matmul1);+ residual = make_f32_convert(residual);+ }+ auto add = std::make_shared<v1::Add>(residual, matmul1);+ ov::Output<ov::Node> norm1 = make_rms(add);+ if (mixed)+ norm1 = std::make_shared<v0::Convert>(norm1, ov::element::f16);+ return std::make_shared<ov::Model>(ov::OutputVector{norm1}, ov::ParameterVector{input});+}++class ActivationsScalingDisabledTest : public TransformationTestsF, public WithParamInterface<float> {};+} // namespace++TEST_P(ActivationsScalingDisabledTest, ModelIsUnchanged) {+ model = make_residual_block(true);+ manager.register_pass<ov::pass::ActivationsScaling>(GetParam(), ov::element::f16);+}++INSTANTIATE_TEST_SUITE_P(TransformationTests, ActivationsScalingDisabledTest, ::testing::Values(0.f, -1.f));++namespace {+// scale = 1 / 8: every scale-up Multiply is gone, the residual stream runs scaled and both norms get eps / 64+std::shared_ptr<ov::Model> make_scaled_residual_block(bool mixed) {+ using ov::op::TemporaryReplaceOutputType;+ using ov::op::TypeRelaxed;+ const auto f16 = ov::element::f16;+ const auto f32 = ov::element::f32;+ auto scale_down = [&]() {+ return v0::Constant::create(f16, ov::Shape{}, {0.125f});+ };++ auto input = std::make_shared<v0::Parameter>(f16, ov::PartialShape{1, 4, kBlockHidden});+ auto scaled_input = std::make_shared<v1::Multiply>(input, scale_down());+ ov::Output<ov::Node> norm0;+ if (mixed) {+ auto rms = make_rms(make_f32_convert(input));+ norm0 = std::make_shared<TypeRelaxed<v1::Multiply>>(ov::element::TypeVector{f32, f32},+ ov::element::TypeVector{f16},+ TemporaryReplaceOutputType(rms, f32).get(),+ TemporaryReplaceOutputType(scale_down(), f32).get());+ } else {+ auto gamma = v0::Constant::create(f16, ov::Shape{kBlockHidden}, {1.5f});+ auto rms = std::make_shared<ov::op::internal::RMS>(scaled_input, gamma, 1e-5 / 64, f16);+ norm0 = std::make_shared<v1::Multiply>(rms, scale_down());+ }+ auto weights0 = v0::Constant::create(f16, ov::Shape{kBlockHidden, kBlockHidden}, {0.1f});+ auto matmul0 = std::make_shared<v0::MatMul>(norm0, weights0);+ auto weights1 = v0::Constant::create(f16, ov::Shape{kBlockHidden, kBlockHidden}, {0.1f});+ auto matmul1 = std::make_shared<v0::MatMul>(matmul0, weights1);+ // with f32 norms the f16 Add inputs are converted inside a TypeRelaxed Add+ const auto add_prec = mixed ? f32 : f16;+ std::shared_ptr<ov::Node> add;+ if (mixed) {+ add = std::make_shared<TypeRelaxed<v1::Add>>(ov::element::TypeVector{f32, f32},+ ov::element::TypeVector{f32},+ TemporaryReplaceOutputType(scaled_input, f32).get(),+ TemporaryReplaceOutputType(matmul1, f32).get());+ } else {+ add = std::make_shared<v1::Add>(scaled_input, matmul1);+ }+ auto gamma1 = v0::Constant::create(add_prec, ov::Shape{kBlockHidden}, {1.5f});+ ov::Output<ov::Node> norm1 = std::make_shared<ov::op::internal::RMS>(add, gamma1, 1e-5 / 64, add_prec);+ if (mixed)+ norm1 = std::make_shared<v0::Convert>(norm1, f16);+ return std::make_shared<ov::Model>(ov::OutputVector{norm1}, ov::ParameterVector{input});+}++class ActivationsScalingResidualStreamTest : public TransformationTestsF, public WithParamInterface<bool> {+public:+ static std::string getTestCaseName(const testing::TestParamInfo<bool>& info) {+ return info.param ? "f32_norms" : "f16";+ }+};+} // namespace++TEST_P(ActivationsScalingResidualStreamTest, ScaleUpIsRemovedAtNorms) {+ model = make_residual_block(GetParam());+ model_ref = make_scaled_residual_block(GetParam());+ manager.register_pass<ov::pass::ActivationsScaling>(8.f, ov::element::f16);+ // LPT AddTransformation creates the residual-branch Multiply without copying rt_info+ disable_rt_info_check();+ // the pass must keep the model output; norm epsilons are checked exactly by EliminateScalarMulF32NormTest+ comparator.enable(FunctionsComparator::CONST_VALUES);+ comparator.enable(FunctionsComparator::ACCURACY);+}++INSTANTIATE_TEST_SUITE_P(TransformationTests,+ ActivationsScalingResidualStreamTest,+ ::testing::Values(false, true),+ ActivationsScalingResidualStreamTest::getTestCaseName);+TEST_F(TransformationTestsF, EliminateScalarMulRMSWithoutGammaTest) {constexpr double epsilon = 1.f;constexpr float scale_factor = 8.f;diff --git a/src/common/transformations/tests/common_optimizations/shared_ops_optimization.cpp b/src/common/transformations/tests/common_optimizations/shared_ops_optimization.cppindex aaddbda97af..45f2f4c56e8 100644--- a/src/common/transformations/tests/common_optimizations/shared_ops_optimization.cpp+++ b/src/common/transformations/tests/common_optimizations/shared_ops_optimization.cpp@@ -26,6 +26,7 @@#include "openvino/op/squeeze.hpp"#include "openvino/op/tile.hpp"#include "openvino/op/unsqueeze.hpp"+#include "ov_ops/type_relaxed.hpp"using namespace ov;@@ -495,6 +496,32 @@ TEST_F(SharedTransformationTestsF, SharedShapeOfTestMixed) {}}+// ConvertPrecision(i64->i32) turns v0::ShapeOf into TypeRelaxed<v0::ShapeOf> with i32 output,+// the upgrade to v3::ShapeOf must keep i32, otherwise the i32 shape subgraph gets an i64 input+TEST_F(SharedTransformationTestsF, ShapeOfUpgradeKeepsRelaxedOutputType) {+ PartialShape input_shape{-1, -1, 4};+ auto make_shape_subgraph = [](const Output<Node>& shape_of) {+ auto gather = std::make_shared<v8::Gather>(shape_of,+ v0::Constant::create(element::i32, Shape{1}, {0}),+ v0::Constant::create(element::i32, Shape{}, {0}));+ auto minus_one = v0::Constant::create(element::i32, Shape{1}, {-1});+ return std::make_shared<v0::Concat>(OutputVector{gather, minus_one}, 0);+ };+ {+ auto input = std::make_shared<v0::Parameter>(element::f32, input_shape);+ auto shape_of = std::make_shared<ov::op::TypeRelaxed<v0::ShapeOf>>(*std::make_shared<v0::ShapeOf>(input),+ element::TypeVector{},+ element::TypeVector{element::i32});+ model = std::make_shared<Model>(OutputVector{make_shape_subgraph(shape_of)}, ParameterVector{input});+ manager.register_pass<pass::SharedOpOptimization>();+ }+ {+ auto input = std::make_shared<v0::Parameter>(element::f32, input_shape);+ auto shape_of = std::make_shared<v3::ShapeOf>(input, element::i32);+ model_ref = std::make_shared<Model>(OutputVector{make_shape_subgraph(shape_of)}, ParameterVector{input});+ }+}+namespace {OutputVector createShapeNodesInMemory(const std::vector<size_t>& node_order_in_memory,std::shared_ptr<void>& memory,diff --git a/src/plugins/intel_cpu/src/compiled_model.cpp b/src/plugins/intel_cpu/src/compiled_model.cppindex 19289b60a6f..91244e82992 100644--- a/src/plugins/intel_cpu/src/compiled_model.cpp+++ b/src/plugins/intel_cpu/src/compiled_model.cpp@@ -309,6 +309,7 @@ ov::Any CompiledModel::get_property(const std::string& name) const {RO_property(ov::intel_cpu::enable_tensor_parallel.name()),RO_property(ov::intel_cpu::tbb_partitioner.name()),RO_property(ov::hint::dynamic_quantization_group_size.name()),+ RO_property(ov::hint::activations_scale_factor.name()),RO_property(ov::hint::kv_cache_precision.name()),RO_property(ov::key_cache_precision.name()),RO_property(ov::value_cache_precision.name()),@@ -398,6 +399,9 @@ ov::Any CompiledModel::get_property(const std::string& name) const {return static_cast<decltype(ov::hint::dynamic_quantization_group_size)::value_type>(config.fcDynamicQuantizationGroupSize);}+ if (name == ov::hint::activations_scale_factor) {+ return static_cast<decltype(ov::hint::activations_scale_factor)::value_type>(config.activationsScaleFactor);+ }if (name == ov::hint::kv_cache_precision) {return decltype(ov::hint::kv_cache_precision)::value_type(config.kvCachePrecision);}diff --git a/src/plugins/intel_cpu/src/config.cpp b/src/plugins/intel_cpu/src/config.cppindex 2ea0d7448d1..5bcb53d8aa0 100644--- a/src/plugins/intel_cpu/src/config.cpp+++ b/src/plugins/intel_cpu/src/config.cpp@@ -212,6 +212,15 @@ void Config::readProperties(const ov::AnyMap& prop, const ModelType modelType) {ov::hint::dynamic_quantization_group_size.name(),". Expected only unsigned integer numbers");}+ } else if (key == ov::hint::activations_scale_factor.name()) {+ try {+ activationsScaleFactor = val.as<float>();+ activationsScaleFactorSetExplicitly = true;+ } catch (const ov::Exception&) {+ OPENVINO_THROW("Wrong value for property key ",+ ov::hint::activations_scale_factor.name(),+ ". Expected only float numbers");+ }} else if (key == ov::enable_profiling.name()) {try {collectPerfCounters = val.as<bool>();@@ -625,6 +634,11 @@ void Config::applyRtInfo(const std::shared_ptr<const ov::Model>& model) {this->fcDynamicQuantizationGroupSize =model->get_rt_info<uint64_t>({"runtime_options", ov::hint::dynamic_quantization_group_size.name()});}+ if (!activationsScaleFactorSetExplicitly &&+ model->has_rt_info({"runtime_options", ov::hint::activations_scale_factor.name()})) {+ this->activationsScaleFactor =+ model->get_rt_info<float>({"runtime_options", ov::hint::activations_scale_factor.name()});+ }if (!keyCachePrecisionSetExplicitly && model->has_rt_info({"runtime_options", ov::key_cache_precision.name()})) {this->keyCachePrecision =model->get_rt_info<ov::element::Type>({"runtime_options", ov::key_cache_precision.name()});diff --git a/src/plugins/intel_cpu/src/config.h b/src/plugins/intel_cpu/src/config.hindex 19888f6da39..8e13a8bd5e9 100644--- a/src/plugins/intel_cpu/src/config.h+++ b/src/plugins/intel_cpu/src/config.h@@ -60,6 +60,8 @@ struct Config {float fcSparseWeiDecompressionRate = 1.0F;uint64_t fcDynamicQuantizationGroupSize = 32;bool fcDynamicQuantizationGroupSizeSetExplicitly = false;+ float activationsScaleFactor = -1.0F;+ bool activationsScaleFactorSetExplicitly = false;bool kvCachePrecisionSetExplicitly = false;bool keyCachePrecisionSetExplicitly = false;bool valueCachePrecisionSetExplicitly = false;diff --git a/src/plugins/intel_cpu/src/plugin.cpp b/src/plugins/intel_cpu/src/plugin.cppindex 946b8d66d5c..81f4933ae17 100644--- a/src/plugins/intel_cpu/src/plugin.cpp+++ b/src/plugins/intel_cpu/src/plugin.cpp@@ -530,6 +530,10 @@ ov::Any Plugin::get_property(const std::string& name, const ov::AnyMap& options)engConfig.fcDynamicQuantizationGroupSize);}+ if (name == ov::hint::activations_scale_factor) {+ return static_cast<decltype(ov::hint::activations_scale_factor)::value_type>(engConfig.activationsScaleFactor);+ }+if (name == ov::hint::kv_cache_precision) {return decltype(ov::hint::kv_cache_precision)::value_type(engConfig.kvCachePrecision);}@@ -610,6 +614,7 @@ ov::Any Plugin::get_ro_property(const std::string& name, [[maybe_unused]] constRW_property(ov::intel_cpu::enable_tensor_parallel.name()),RW_property(ov::intel_cpu::tbb_partitioner.name()),RW_property(ov::hint::dynamic_quantization_group_size.name()),+ RW_property(ov::hint::activations_scale_factor.name()),RW_property(ov::hint::kv_cache_precision.name()),RW_property(ov::key_cache_precision.name()),RW_property(ov::value_cache_precision.name()),diff --git a/src/plugins/intel_cpu/src/transformations/cpu_opset/common/pass/decompose_rms_norm.cpp b/src/plugins/intel_cpu/src/transformations/cpu_opset/common/pass/decompose_rms_norm.cppindex c5aeab14c9f..ac3337f3718 100644--- a/src/plugins/intel_cpu/src/transformations/cpu_opset/common/pass/decompose_rms_norm.cpp+++ b/src/plugins/intel_cpu/src/transformations/cpu_opset/common/pass/decompose_rms_norm.cpp@@ -10,10 +10,13 @@#include "openvino/cc/pass/itt.hpp"#include "openvino/core/graph_util.hpp"#include "openvino/core/node.hpp"+#include "openvino/core/node_vector.hpp"+#include "openvino/core/rt_info.hpp"#include "openvino/core/type.hpp"#include "openvino/core/type/element_type.hpp"#include "openvino/op/add.hpp"#include "openvino/op/constant.hpp"+#include "openvino/op/convert.hpp"#include "openvino/op/multiply.hpp"#include "openvino/op/power.hpp"#include "openvino/op/reduce_mean.hpp"@@ -37,23 +40,36 @@ DecomposeRMSNorm::DecomposeRMSNorm() {if (node == nullptr || transformation_callback(node)) {return false;}- auto data = node->input_value(0);- auto data_precision = node->get_input_element_type(0);+ // RMS may output another type than its input (e.g. f16 data with f32 gamma -> f32), so compute in it+ const auto output_precision = node->get_output_element_type(0);+ ov::NodeVector new_nodes;+ auto to_output_type = [&](const ov::Output<ov::Node>& input) -> ov::Output<ov::Node> {+ if (input.get_element_type() == output_precision) {+ return input;+ }+ new_nodes.push_back(std::make_shared<ov::op::v0::Convert>(input, output_precision));+ return new_nodes.back();+ };+ auto data = to_output_type(node->input_value(0));- auto power_const = ov::op::v0::Constant::create(data_precision, {}, std::vector<float>{2.F});+ auto power_const = ov::op::v0::Constant::create(output_precision, {}, std::vector<float>{2.F});auto power = std::make_shared<ov::op::v1::Power>(data, power_const);auto mean_axes = ov::op::v0::Constant::create(ov::element::i32, ov::Shape{1}, {-1});auto mean = std::make_shared<ov::op::v1::ReduceMean>(power, mean_axes, true);- auto eps = ov::op::v0::Constant::create(data_precision, {}, {node->get_epsilon()});+ auto eps = ov::op::v0::Constant::create(output_precision, {}, {node->get_epsilon()});auto add_eps = std::make_shared<ov::op::v1::Add>(mean, eps);auto sqrt = std::make_shared<ov::op::v0::Sqrt>(add_eps);- auto div_const = ov::op::v0::Constant::create(data_precision, {}, {-1});+ auto div_const = ov::op::v0::Constant::create(output_precision, {}, {-1});auto div = std::make_shared<ov::op::v1::Power>(sqrt, div_const);std::shared_ptr<ov::Node> result = std::make_shared<ov::op::v1::Multiply>(data, div);if (node->get_input_size() > 1) {- result = std::make_shared<ov::op::v1::Multiply>(node->input_value(1), result);+ new_nodes.push_back(result);+ result = std::make_shared<ov::op::v1::Multiply>(to_output_type(node->input_value(1)), result);}+ new_nodes.insert(new_nodes.end(), {power, mean, add_eps, sqrt, div, result});+ result->set_friendly_name(node->get_friendly_name());+ ov::copy_runtime_info(node, new_nodes);ov::replace_node(node, result);return true;};diff --git a/src/plugins/intel_cpu/src/transformations/cpu_opset/x64/pass/mlp_fusion.cpp b/src/plugins/intel_cpu/src/transformations/cpu_opset/x64/pass/mlp_fusion.cppindex 991eecde120..75ea5755f5f 100644--- a/src/plugins/intel_cpu/src/transformations/cpu_opset/x64/pass/mlp_fusion.cpp+++ b/src/plugins/intel_cpu/src/transformations/cpu_opset/x64/pass/mlp_fusion.cpp@@ -4,7 +4,10 @@#include "mlp_fusion.hpp"+#include <algorithm>+#include <cstddef>#include <memory>+#include <vector>#include "openvino/cc/pass/itt.hpp"#include "openvino/core/graph_util.hpp"@@ -31,6 +34,7 @@#include "openvino/util/pp.hpp"#include "transformations/cpu_opset/x64/op/llm_mlp.hpp"#include "transformations/symbolic_transformations/symbolic_optimizations.hpp"+#include "transformations/utils/utils.hpp"using namespace ov::pass;using namespace ov::pass::pattern;@@ -106,7 +110,12 @@ ov::intel_cpu::MLPFusionPass::MLPFusionPass() {auto mlp_gate_proj = wrap_type<MatMul>({input, gate_proj_weight | gate_proj_weight_deq},{{"transpose_a", false}, {"transpose_b", true}});- auto mlp_gate_act = wrap_type<Swish, Gelu>({mlp_gate_proj | gate_up_proj_split});+ // scale-up left by ActivationsScaling+ auto gate_scale = wrap_type<Constant>([](const Output<Node>& output) {+ return ov::shape_size(output.get_shape()) == 1;+ });+ auto mlp_gate_scaled = optional<Multiply>({mlp_gate_proj | gate_up_proj_split, gate_scale});+ auto mlp_gate_act = wrap_type<Swish, Gelu>({mlp_gate_scaled});auto mlp_up_proj = wrap_type<MatMul>({input, up_proj_weight | up_proj_weight_deq},{{"transpose_a", false}, {"transpose_b", true}});@@ -124,6 +133,10 @@ ov::intel_cpu::MLPFusionPass::MLPFusionPass() {if (pattern_map.count(gate_up_proj_split)) {// The gate half feeds the activation: gate at split output(0) is the normal layout, otherwise swapped.auto gate_src = pattern_map.at(mlp_gate_act).get_node_shared_ptr()->input_value(0);+ if (pattern_map.count(gate_scale)) {+ const auto gate_mul = gate_src.get_node_shared_ptr();+ gate_src = gate_mul->input_value(gate_mul->input_value(0) == pattern_map.at(gate_scale) ? 1 : 0);+ }gate_up_type = (gate_src.get_index() == 0) ? LLMMLPNode::GATE_UP_TYPE::COMBINED_GATE_UP: LLMMLPNode::GATE_UP_TYPE::COMBINED_UP_GATE;}@@ -247,6 +260,30 @@ ov::intel_cpu::MLPFusionPass::MLPFusionPass() {if (is_down_proj_int8) {new_args.push_back(pattern_map.at(down_proj_weight_scales_per_OC));}+ if (pattern_map.count(gate_scale)) {+ // safe to fold into the gate rows: the kernel accumulates the gate in f32+ const size_t gate_idx = is_gate_up_quantized_int8 ? 4 : 1;+ const auto& gate_w = new_args[gate_idx];+ const auto scale_const = ov::as_type_ptr<Constant>(pattern_map.at(gate_scale).get_node_shared_ptr());+ const auto rows = gate_w.get_shape()[0];+ std::vector<float> row_scales(rows, scale_const->cast_vector<float>()[0]);+ if (gate_up_type != LLMMLPNode::GATE_UP_TYPE::SEPARATE) {+ // combined weights hold the gate and up rows in two halves; only the gate half is scaled+ const size_t up_begin = (gate_up_type == LLMMLPNode::GATE_UP_TYPE::COMBINED_GATE_UP) ? rows / 2 : 0;+ std::fill_n(row_scales.begin() + static_cast<std::ptrdiff_t>(up_begin), rows / 2, 1.0F);+ }+ auto folded = ov::op::util::make_try_fold<Multiply>(+ gate_w,+ Constant::create(gate_w.get_element_type(), Shape{rows, 1}, row_scales));+ if (!ov::is_type<Constant>(folded)) {+ return false;+ }+ new_args[gate_idx] = folded;+ if (gate_up_type != LLMMLPNode::GATE_UP_TYPE::SEPARATE) {+ // the combined tensor is passed as both the gate and the up input+ new_args[gate_idx + 1] = folded;+ }+ }const auto& old_node = root;auto new_node = std::make_shared<LLMMLPNode>(new_args, config);diff --git a/src/plugins/intel_cpu/src/transformations/transformation_pipeline.cpp b/src/plugins/intel_cpu/src/transformations/transformation_pipeline.cppindex 9a2e41ed9b6..c47d5108854 100644--- a/src/plugins/intel_cpu/src/transformations/transformation_pipeline.cpp+++ b/src/plugins/intel_cpu/src/transformations/transformation_pipeline.cpp@@ -21,6 +21,7 @@#include "low_precision/qdq_stripping.hpp"#include "low_precision/quantization_details.hpp"#include "nodes/fullyconnected.h"+#include "nodes/rms_norm.h"#include "openvino/core/descriptor/tensor.hpp"#include "openvino/core/graph_util.hpp"#include "openvino/core/node.hpp"@@ -64,6 +65,7 @@#include "openvino/pass/node_registry.hpp"#include "openvino/pass/validate.hpp"#include "selective_build.h"+#include "transformations/common_optimizations/activations_scaling.hpp"#include "transformations/common_optimizations/add_fake_quantize_fusion.hpp"#include "transformations/common_optimizations/augru_cell_fusion.hpp"#include "transformations/common_optimizations/common_optimizations.hpp"@@ -82,12 +84,14 @@#include "transformations/common_optimizations/ngram_hash_function_fusion.hpp"#include "transformations/common_optimizations/nop_elimination.hpp"#include "transformations/common_optimizations/reshape_prelu.hpp"+#include "transformations/common_optimizations/rms_fusion.hpp"#include "transformations/common_optimizations/sdpa_fusion.hpp"#include "transformations/common_optimizations/shared_ops_optimization.hpp"#include "transformations/common_optimizations/transpose_sinking.hpp"#include "transformations/common_optimizations/weights_dequantize_to_fake_quantize.hpp"#include "transformations/common_optimizations/wrap_interpolate_into_transposes.hpp"#include "transformations/convert_precision.hpp"+#include "transformations/cpu_opset/common/pass/decompose_rms_norm.hpp"#include "transformations/fp16_compression/convert_compression_only_to_legacy.hpp"#include "transformations/fp16_compression/disable_bf16_comp_ltx_rope.hpp"#include "transformations/fp16_compression/mark_decompression_convert_constant_folding.hpp"@@ -205,7 +209,6 @@# include "low_precision/weightable_layer_transformation.hpp"# include "nodes/llm_mlp.h"# include "nodes/qkv_proj.h"-# include "nodes/rms_norm.h"# include "onednn/dnnl.h"# include "openvino/op/group_normalization.hpp"# include "openvino/op/mish.hpp"@@ -214,12 +217,10 @@# include "openvino/op/subtract.hpp"# include "snippets/lowered/pass/mha_parallel_wa_optimizer.hpp"# include "snippets/pass/common_optimizations.hpp"-# include "transformations/common_optimizations/rms_fusion.hpp"# include "transformations/common_optimizations/strided_slice_reshape_concat_fusion.hpp"# include "transformations/cpu_opset/common/op/sdpa.hpp"# include "transformations/cpu_opset/common/pass/causal_mask_preprocess_fusion.hpp"# include "transformations/cpu_opset/common/pass/convert_fq_rnn_to_quantized_rnn.hpp"-# include "transformations/cpu_opset/common/pass/decompose_rms_norm.hpp"# include "transformations/cpu_opset/x64/pass/convert_to_interaction.hpp"# include "transformations/cpu_opset/x64/pass/mlp_fusion.hpp"# include "transformations/cpu_opset/x64/pass/qkv_proj_fusion.hpp"@@ -1154,6 +1155,30 @@ void Transformations::PostLpt() {CPU_DISABLE_PASS_COMMON(postLPTPassManager, ov::pass::RoPEFusionCohere);CPU_REGISTER_PASS_X64(postLPTPassManager, CausalMaskPreprocessFusion);+ // gamma-less fusion keeps the variance in f32 for bf16, which has no ConvertPrecision markup; under+ // f16 the decomposed norm is already kept precise by ConvertPrecision, so fusing it there regresses it.+ const bool enable_without_gamma = config.inferencePrecision != ov::element::f16;+ CPU_REGISTER_PASS_COMMON(postLPTPassManager,+ ov::pass::RMSFusion,+ false /* force_tail_convert */,+ enable_without_gamma);+ CPU_REGISTER_PASS_COMMON(postLPTPassManager, ov::pass::FuseQSAIndexerQuery);+ // before DecomposeRMSNorm: scale_up multiplies are dropped only in front of fused RMS+ if (config.inferencePrecision == ov::element::f16 && config.activationsScaleFactor > 0.F) {+ CPU_REGISTER_PASS_COMMON(postLPTPassManager,+ ov::pass::ActivationsScaling,+ config.activationsScaleFactor,+ config.inferencePrecision);+ }+ CPU_REGISTER_PASS_COMMON(postLPTPassManager, ov::intel_cpu::DecomposeRMSNorm);+ CPU_SET_CALLBACK_COMMON(+ postLPTPassManager,+ [](const std::shared_ptr<const ov::Node>& node) -> bool {+ std::string errorMsg;+ return node::RMSNorm::isSupportedOperation(node, errorMsg);+ },+ ov::intel_cpu::DecomposeRMSNorm);+#if defined(OPENVINO_ARCH_X86_64)// MLP & QKV fusion optimizations is focused on throughput, only enabled on AMX-bf16 & LLM serving use cases.auto can_use_amx_bf16_int8 = dnnl::impl::cpu::x64::mayiuse(dnnl::impl::cpu::x64::avx512_core_amx) &&@@ -1202,23 +1227,6 @@ void Transformations::PostLpt() {}#endif // OPENVINO_ARCH_X86_64- // gamma-less fusion keeps the variance in f32 for bf16, which has no ConvertPrecision markup; under- // f16 the decomposed norm is already kept precise by ConvertPrecision, so fusing it there regresses it.- [[maybe_unused]] const bool enable_without_gamma = config.inferencePrecision != ov::element::f16;- CPU_REGISTER_PASS_X64(postLPTPassManager,- ov::pass::RMSFusion,- false /* force_tail_convert */,- enable_without_gamma);- CPU_REGISTER_PASS_COMMON(postLPTPassManager, ov::pass::FuseQSAIndexerQuery);- CPU_REGISTER_PASS_X64(postLPTPassManager, ov::intel_cpu::DecomposeRMSNorm);- CPU_SET_CALLBACK_X64(- postLPTPassManager,- [](const std::shared_ptr<const ov::Node>& node) -> bool {- std::string errorMsg;- return node::RMSNorm::isSupportedOperation(node, errorMsg);- },- ov::intel_cpu::DecomposeRMSNorm);-// markup Rope Input when BF16/F16 inference.if (any_of(config.inferencePrecision, ov::element::bf16, ov::element::f16)) {CPU_REGISTER_PASS_COMMON(postLPTPassManager, ov::pass::MarkRopeInputsToKeepInMixedPrecision);diff --git a/src/plugins/intel_cpu/tests/functional/custom/behavior/ov_executable_network/properties.cpp b/src/plugins/intel_cpu/tests/functional/custom/behavior/ov_executable_network/properties.cppindex 7080a7b0e27..b4921d63174 100644--- a/src/plugins/intel_cpu/tests/functional/custom/behavior/ov_executable_network/properties.cpp+++ b/src/plugins/intel_cpu/tests/functional/custom/behavior/ov_executable_network/properties.cpp@@ -50,6 +50,7 @@ TEST_F(OVClassConfigTestCPU, smoke_CpuExecNetworkSupportedPropertiesAreAvailableRO_property(ov::intel_cpu::enable_tensor_parallel.name()),RO_property(ov::intel_cpu::tbb_partitioner.name()),RO_property(ov::hint::dynamic_quantization_group_size.name()),+ RO_property(ov::hint::activations_scale_factor.name()),RO_property(ov::hint::kv_cache_precision.name()),RO_property(ov::key_cache_precision.name()),RO_property(ov::value_cache_precision.name()),@@ -227,6 +228,38 @@ TEST_F(OVClassConfigTestCPU, smoke_CpuExecNetworkCheckDynamicQuantizationGroupSiASSERT_EQ(groupSize, 64);}+TEST_F(OVClassConfigTestCPU, smoke_CpuExecNetworkCheckActivationsScaleFactor) {+ ov::Core core;+ ov::CompiledModel compiledModel;+ float scaleFactor = 0.0f;++ // disabled by default+ OV_ASSERT_NO_THROW(compiledModel = core.compile_model(model, deviceName));+ OV_ASSERT_NO_THROW(scaleFactor = compiledModel.get_property(ov::hint::activations_scale_factor));+ ASSERT_EQ(scaleFactor, -1.0f);++ core.set_property(deviceName, ov::hint::activations_scale_factor(8.0f));+ OV_ASSERT_NO_THROW(compiledModel = core.compile_model(model, deviceName));+ OV_ASSERT_NO_THROW(scaleFactor = compiledModel.get_property(ov::hint::activations_scale_factor));+ ASSERT_EQ(scaleFactor, 8.0f);+}++TEST_F(OVClassConfigTestCPU, smoke_CpuExecNetworkCheckActivationsScaleFactorRuntimeOptions) {+ ov::Core core;+ ov::CompiledModel compiledModel;+ float scaleFactor = 0.0f;++ model->set_rt_info("8.0", "runtime_options", ov::hint::activations_scale_factor.name());+ OV_ASSERT_NO_THROW(compiledModel = core.compile_model(model, deviceName));+ OV_ASSERT_NO_THROW(scaleFactor = compiledModel.get_property(ov::hint::activations_scale_factor));+ ASSERT_EQ(scaleFactor, 8.0f);++ // property has higher priority than rt_info+ OV_ASSERT_NO_THROW(compiledModel = core.compile_model(model, deviceName, ov::hint::activations_scale_factor(4.0f)));+ OV_ASSERT_NO_THROW(scaleFactor = compiledModel.get_property(ov::hint::activations_scale_factor));+ ASSERT_EQ(scaleFactor, 4.0f);+}+TEST_F(OVClassConfigTestCPU, smoke_CpuExecNetworkCheckKVCachePrecision) {ov::Core core;diff --git a/src/plugins/intel_cpu/tests/functional/custom/behavior/ov_plugin/properties.cpp b/src/plugins/intel_cpu/tests/functional/custom/behavior/ov_plugin/properties.cppindex e8766a0239c..928706f95ea 100644--- a/src/plugins/intel_cpu/tests/functional/custom/behavior/ov_plugin/properties.cpp+++ b/src/plugins/intel_cpu/tests/functional/custom/behavior/ov_plugin/properties.cpp@@ -64,6 +64,7 @@ TEST_F(OVClassConfigTestCPU, smoke_PluginAllSupportedPropertiesAreAvailable) {RW_property(ov::intel_cpu::enable_tensor_parallel.name()),RW_property(ov::intel_cpu::tbb_partitioner.name()),RW_property(ov::hint::dynamic_quantization_group_size.name()),+ RW_property(ov::hint::activations_scale_factor.name()),RW_property(ov::hint::kv_cache_precision.name()),RW_property(ov::key_cache_precision.name()),RW_property(ov::value_cache_precision.name()),diff --git a/src/plugins/intel_cpu/tests/functional/custom/subgraph_tests/src/common/activations_scaling.cpp b/src/plugins/intel_cpu/tests/functional/custom/subgraph_tests/src/common/activations_scaling.cppnew file mode 100644index 00000000000..ae38ad406c3--- /dev/null+++ b/src/plugins/intel_cpu/tests/functional/custom/subgraph_tests/src/common/activations_scaling.cpp@@ -0,0 +1,171 @@+// Copyright (C) 2018-2026 Intel Corporation+// SPDX-License-Identifier: Apache-2.0+//++#include <tuple>++#include "common_test_utils/common_utils.hpp"+#include "common_test_utils/file_utils.hpp"+#include "common_test_utils/node_builders/constant.hpp"+#include "common_test_utils/ov_tensor_utils.hpp"+#include "openvino/op/add.hpp"+#include "openvino/op/broadcast.hpp"+#include "openvino/op/concat.hpp"+#include "openvino/op/constant.hpp"+#include "openvino/op/divide.hpp"+#include "openvino/op/gather.hpp"+#include "openvino/op/gelu.hpp"+#include "openvino/op/matmul.hpp"+#include "openvino/op/multiply.hpp"+#include "openvino/op/parameter.hpp"+#include "openvino/op/power.hpp"+#include "openvino/op/reduce_mean.hpp"+#include "openvino/op/reshape.hpp"+#include "openvino/op/shape_of.hpp"+#include "openvino/op/sqrt.hpp"+#include "shared_test_classes/base/ov_subgraph.hpp"+#include "utils/precision_support.h"++namespace ov {+namespace test {++// T5-like block, the second MatMul output exceeds the f16 range. Like T5's attention mask, a Broadcast+// takes its target shape from ShapeOf(RMSNorm), so ActivationsScaling also processes the i32 shape subgraph.+//+// input+// │+// ┌─────┴─────┐+// │ RMSNorm ──────► ShapeOf+// │ │ │+// │ MatMul Gather(batch, seq)+// │ │ │+// │ Gelu Concat+// │ │ │+// │ MatMul Broadcast(mask)+// │ │ │+// └────Add────┘ Result+// │+// RMSNorm+// │+// Result+// scale factor, whether the RMSNorms have gamma+using ActivationsScalingCPUParams = std::tuple<float, bool>;++class ActivationsScalingCPUTest : public testing::WithParamInterface<ActivationsScalingCPUParams>,+ virtual public SubgraphBaseTest {+public:+ static std::string getTestCaseName(const testing::TestParamInfo<ActivationsScalingCPUParams>& obj) {+ std::ostringstream result;+ result << "scale_factor=" << std::get<0>(obj.param) << "_gamma=" << std::get<1>(obj.param);+ return result.str();+ }++protected:+ static constexpr size_t hidden_size = 64;+ static constexpr size_t inter_size = 256;++ static ov::Output<ov::Node> make_rms_norm(const ov::Output<ov::Node>& x, bool with_gamma) {+ auto square =+ std::make_shared<ov::op::v1::Power>(x, ov::op::v0::Constant::create(ov::element::f32, ov::Shape{}, {2.f}));+ auto axes = ov::op::v0::Constant::create(ov::element::i64, ov::Shape{1}, {-1});+ auto mean = std::make_shared<ov::op::v1::ReduceMean>(square, axes, true);+ auto eps = ov::op::v0::Constant::create(ov::element::f32, ov::Shape{}, {1e-6f});+ auto sqrt = std::make_shared<ov::op::v0::Sqrt>(std::make_shared<ov::op::v1::Add>(mean, eps));+ auto div = std::make_shared<ov::op::v1::Divide>(x, sqrt);+ if (!with_gamma) {+ return div;+ }+ auto gamma = ov::op::v0::Constant::create(ov::element::f32, ov::Shape{hidden_size}, {1.f});+ return std::make_shared<ov::op::v1::Multiply>(div, gamma);+ }++ void SetUp() override {+ targetDevice = ov::test::utils::DEVICE_CPU;+ configuration = {{ov::hint::inference_precision.name(), ov::element::f16},+ {ov::hint::activations_scale_factor.name(), std::get<0>(GetParam())}};+ const bool with_gamma = std::get<1>(GetParam());+ abs_threshold = 0.05;+ rel_threshold = 0.05;++ init_input_shapes({{{-1, -1, hidden_size}, {{1, 8, hidden_size}, {2, 5, hidden_size}}}});++ auto input = std::make_shared<ov::op::v0::Parameter>(ov::element::f32, inputDynamicShapes[0]);+ auto norm0 = make_rms_norm(input, with_gamma);+ // positive weights in [0.5, 1.5] and [4, 12]: each matmul1 output is ~1e5, above the f16 range+ auto weights0 = ov::test::utils::make_constant(ov::element::f32,+ ov::Shape{hidden_size, inter_size},+ ov::test::utils::InputGenerateData(0.5, 1, 1000, 1));+ auto matmul0 = std::make_shared<ov::op::v0::MatMul>(norm0, weights0);+ auto gelu = std::make_shared<ov::op::v7::Gelu>(matmul0);+ // second output, like T5's extended attention mask: expand(batch, 1, seq, seq) with batch and seq+ // taken from ShapeOf(RMSNorm)+ auto shape = std::make_shared<ov::op::v3::ShapeOf>(norm0);+ auto batch = std::make_shared<ov::op::v8::Gather>(shape,+ ov::op::v0::Constant::create(ov::element::i64, {1}, {0}),+ ov::op::v0::Constant::create(ov::element::i64, {}, {0}));+ auto seq = std::make_shared<ov::op::v1::Reshape>(+ std::make_shared<ov::op::v8::Gather>(shape,+ ov::op::v0::Constant::create(ov::element::i64, {}, {1}),+ ov::op::v0::Constant::create(ov::element::i64, {}, {0})),+ ov::op::v0::Constant::create(ov::element::i64, {1}, {1}),+ false);+ auto mask_shape = std::make_shared<ov::op::v0::Concat>(+ ov::OutputVector{batch, ov::op::v0::Constant::create(ov::element::i64, {1}, {1}), seq, seq},+ 0);+ auto mask = std::make_shared<ov::op::v3::Broadcast>(ov::op::v0::Constant::create(ov::element::f32, {1}, {1.f}),+ mask_shape,+ ov::op::BroadcastType::BIDIRECTIONAL);+ auto weights1 = ov::test::utils::make_constant(ov::element::f32,+ ov::Shape{inter_size, hidden_size},+ ov::test::utils::InputGenerateData(4, 8, 1000, 2));+ auto matmul1 = std::make_shared<ov::op::v0::MatMul>(gelu, weights1);+ auto residual = std::make_shared<ov::op::v1::Add>(input, matmul1);+ auto norm1 = make_rms_norm(residual, with_gamma);+ function = std::make_shared<ov::Model>(ov::OutputVector{norm1, mask},+ ov::ParameterVector{input},+ "ActivationsScaling");+ }++ void generate_inputs(const std::vector<ov::Shape>& targetInputStaticShapes) override {+ inputs.clear();+ const auto param = function->inputs()[0];+ // positive values, so the MatMul outputs do not cancel out+ auto tensor = ov::test::utils::create_and_fill_tensor(param.get_element_type(),+ targetInputStaticShapes[0],+ ov::test::utils::InputGenerateData(1, 10, 1, 1));+ inputs.insert({param.get_node_shared_ptr(), tensor});+ }+};++namespace {+TEST_P(ActivationsScalingCPUTest, CompareWithRefs) {+ if (!ov::intel_cpu::hasHardwareSupport(ov::element::f16)) {+ GTEST_SKIP() << "Skipping test, platform don't support precision f16";+ }+ run();+}++// the scale factor must survive export/import through the model cache+TEST_P(ActivationsScalingCPUTest, CompareWithRefs_cached) {+ if (!ov::intel_cpu::hasHardwareSupport(ov::element::f16)) {+ GTEST_SKIP() << "Skipping test, platform don't support precision f16";+ }+ const std::string cache_dir = ov::test::utils::generateTestFilePrefix() + "_cpu_model_cache";+ ov::test::utils::removeFilesWithExt(cache_dir, "blob");+ ov::test::utils::removeDir(cache_dir);+ configuration.insert(ov::cache_dir(cache_dir));+ compile_model(); // exports the blob+ run(); // imports it+ EXPECT_TRUE(compiledModel.get_property(ov::loaded_from_cache));+ EXPECT_EQ(compiledModel.get_property(ov::hint::activations_scale_factor), std::get<0>(GetParam()));+ ov::test::utils::removeFilesWithExt(cache_dir, "blob");+ ov::test::utils::removeDir(cache_dir);+}++INSTANTIATE_TEST_SUITE_P(smoke_ActivationsScaling,+ ActivationsScalingCPUTest,+ ::testing::Combine(::testing::Values(8.f), ::testing::Bool()),+ ActivationsScalingCPUTest::getTestCaseName);+} // namespace+} // namespace test+} // namespace ovdiff --git a/src/plugins/intel_cpu/tests/functional/sources.cmake b/src/plugins/intel_cpu/tests/functional/sources.cmakeindex 36fb0dfbb32..d41b03b9b44 100644--- a/src/plugins/intel_cpu/tests/functional/sources.cmake+++ b/src/plugins/intel_cpu/tests/functional/sources.cmake@@ -211,6 +211,7 @@ set(CPU_FUNC_TESTS_CUSTOM_SRCS${CMAKE_CURRENT_LIST_DIR}/custom/subgraph_tests/src/classes/stateful_sdpa_bool_mask.cpp${CMAKE_CURRENT_LIST_DIR}/custom/subgraph_tests/src/classes/stateful_sdpa_bool_mask.hpp${CMAKE_CURRENT_LIST_DIR}/custom/subgraph_tests/src/classes/undefined_et.cpp+ ${CMAKE_CURRENT_LIST_DIR}/custom/subgraph_tests/src/common/activations_scaling.cpp${CMAKE_CURRENT_LIST_DIR}/custom/subgraph_tests/src/common/add_convert_to_reorder.cpp${CMAKE_CURRENT_LIST_DIR}/custom/subgraph_tests/src/common/align_matmul_input_ranks.cpp${CMAKE_CURRENT_LIST_DIR}/custom/subgraph_tests/src/common/any_layout.cpp@@ -774,6 +775,7 @@ set(TMP_LIST_OF_ARM_SUBGRAPH_TESTS)set(TMP_LIST_OF_COMMON_SUBGRAPH_TESTS+ ${CMAKE_CURRENT_LIST_DIR}/custom/subgraph_tests/src/common/activations_scaling.cpp${CMAKE_CURRENT_LIST_DIR}/custom/subgraph_tests/src/common/add_convert_to_reorder.cpp${CMAKE_CURRENT_LIST_DIR}/custom/subgraph_tests/src/common/align_matmul_input_ranks.cpp${CMAKE_CURRENT_LIST_DIR}/custom/subgraph_tests/src/common/any_layout.cppdiff --git a/src/plugins/intel_cpu/tests/unit/sources.cmake b/src/plugins/intel_cpu/tests/unit/sources.cmakeindex 14bb35c8868..71dab6bd2a1 100644--- a/src/plugins/intel_cpu/tests/unit/sources.cmake+++ b/src/plugins/intel_cpu/tests/unit/sources.cmake@@ -35,6 +35,7 @@ set(CPU_UNIT_TESTS_SRCS${CMAKE_CURRENT_LIST_DIR}/transformations/convert_matmul_test.cpp${CMAKE_CURRENT_LIST_DIR}/transformations/convert_to_leaky_relu_test.cpp${CMAKE_CURRENT_LIST_DIR}/transformations/decompose_integer_divide.cpp+ ${CMAKE_CURRENT_LIST_DIR}/transformations/decompose_rms_norm_test.cpp${CMAKE_CURRENT_LIST_DIR}/transformations/disable_bf16_comp_cumsum_sin_gen_test.cpp${CMAKE_CURRENT_LIST_DIR}/transformations/move_fc_reshape_to_weights.cpp${CMAKE_CURRENT_LIST_DIR}/transformations/optimize_sequence_transposes_test.cpp@@ -200,6 +201,7 @@ set(CPU_UNIT_TESTS_X64_SRCS${CMAKE_CURRENT_LIST_DIR}/snippets_transformations/x64/lowered/buffer_allocation.cpp${CMAKE_CURRENT_LIST_DIR}/transformations/x64/convert_matmul_test_3d_weight.cpp${CMAKE_CURRENT_LIST_DIR}/transformations/x64/convert_to_interaction.cpp+ ${CMAKE_CURRENT_LIST_DIR}/transformations/x64/mlp_fusion_test.cpp${CMAKE_CURRENT_LIST_DIR}/transformations/x64/qkv_proj_fusion_test.cpp)@@ -278,6 +280,7 @@ if(ENABLE_UNITY_BUILD)${CMAKE_CURRENT_LIST_DIR}/transformations/convert_matmul_test.cpp${CMAKE_CURRENT_LIST_DIR}/transformations/convert_to_leaky_relu_test.cpp${CMAKE_CURRENT_LIST_DIR}/transformations/decompose_integer_divide.cpp+ ${CMAKE_CURRENT_LIST_DIR}/transformations/decompose_rms_norm_test.cpp${CMAKE_CURRENT_LIST_DIR}/transformations/disable_bf16_comp_cumsum_sin_gen_test.cpp${CMAKE_CURRENT_LIST_DIR}/transformations/move_fc_reshape_to_weights.cpp${CMAKE_CURRENT_LIST_DIR}/transformations/optimize_sequence_transposes_test.cppdiff --git a/src/plugins/intel_cpu/tests/unit/transformations/decompose_rms_norm_test.cpp b/src/plugins/intel_cpu/tests/unit/transformations/decompose_rms_norm_test.cppnew file mode 100644index 00000000000..03b0ae97250--- /dev/null+++ b/src/plugins/intel_cpu/tests/unit/transformations/decompose_rms_norm_test.cpp@@ -0,0 +1,82 @@+// Copyright (C) 2018-2026 Intel Corporation+// SPDX-License-Identifier: Apache-2.0+//++#include "transformations/cpu_opset/common/pass/decompose_rms_norm.hpp"++#include <gtest/gtest.h>++#include <memory>+#include <string>+#include <tuple>+#include <vector>++#include "common_test_utils/ov_test_utils.hpp"+#include "openvino/op/add.hpp"+#include "openvino/op/constant.hpp"+#include "openvino/op/convert.hpp"+#include "openvino/op/multiply.hpp"+#include "openvino/op/parameter.hpp"+#include "openvino/op/power.hpp"+#include "openvino/op/reduce_mean.hpp"+#include "openvino/op/sqrt.hpp"+#include "ov_ops/rms.hpp"++using namespace ov;+using namespace ov::op;++namespace {+constexpr double kEpsilon = 1e-5;++using DecomposeRMSNormParams = std::tuple<element::Type, // data precision, the RMS output is f32+ bool>; // with gamma++std::shared_ptr<Node> make_decomposed_rms(const Output<Node>& data, const std::shared_ptr<Node>& gamma) {+ const auto prc = data.get_element_type();+ auto power = std::make_shared<v1::Power>(data, v0::Constant::create(prc, {}, std::vector<float>{2.F}));+ auto mean = std::make_shared<v1::ReduceMean>(power, v0::Constant::create(element::i32, Shape{1}, {-1}), true);+ auto add_eps = std::make_shared<v1::Add>(mean, v0::Constant::create(prc, {}, {kEpsilon}));+ auto inv = std::make_shared<v1::Power>(std::make_shared<v0::Sqrt>(add_eps), v0::Constant::create(prc, {}, {-1}));+ std::shared_ptr<Node> norm = std::make_shared<v1::Multiply>(data, inv);+ return gamma ? std::make_shared<v1::Multiply>(gamma, norm) : norm;+}++class DecomposeRMSNormTest : public TransformationTestsF, public testing::WithParamInterface<DecomposeRMSNormParams> {+public:+ static std::string getTestCaseName(const testing::TestParamInfo<DecomposeRMSNormParams>& obj) {+ const auto& [data_prc, with_gamma] = obj.param;+ return "data=" + data_prc.get_type_name() + (with_gamma ? "_gamma" : "_no_gamma");+ }+};++// RMS outputs f32 for f16 data too, so the decomposition must run in the output type+TEST_P(DecomposeRMSNormTest, ComputesInOutputPrecision) {+ const auto& [data_prc, with_gamma] = GetParam();+ comparator.enable(FunctionsComparator::CmpValues::CONST_VALUES);+ {+ auto data = std::make_shared<v0::Parameter>(data_prc, PartialShape{-1, -1, 8});+ auto rms = with_gamma+ ? std::make_shared<ov::op::internal::RMS>(data,+ v0::Constant::create(element::f32, Shape{8}, {1.5F}),+ kEpsilon,+ element::f32)+ : std::make_shared<ov::op::internal::RMS>(data, kEpsilon, element::f32);+ model = std::make_shared<Model>(OutputVector{rms}, ParameterVector{data});+ manager.register_pass<ov::intel_cpu::DecomposeRMSNorm>();+ }+ {+ auto data = std::make_shared<v0::Parameter>(data_prc, PartialShape{-1, -1, 8});+ Output<Node> input = data;+ if (data_prc != element::f32) {+ input = std::make_shared<v0::Convert>(data, element::f32);+ }+ auto gamma = with_gamma ? v0::Constant::create(element::f32, Shape{8}, {1.5F}) : nullptr;+ model_ref = std::make_shared<Model>(OutputVector{make_decomposed_rms(input, gamma)}, ParameterVector{data});+ }+}++INSTANTIATE_TEST_SUITE_P(TransformationTests,+ DecomposeRMSNormTest,+ testing::Combine(testing::Values(element::f16, element::f32), testing::Bool()),+ DecomposeRMSNormTest::getTestCaseName);+} // namespacediff --git a/src/plugins/intel_cpu/tests/unit/transformations/x64/mlp_fusion_test.cpp b/src/plugins/intel_cpu/tests/unit/transformations/x64/mlp_fusion_test.cppnew file mode 100644index 00000000000..dda33a7da5c--- /dev/null+++ b/src/plugins/intel_cpu/tests/unit/transformations/x64/mlp_fusion_test.cpp@@ -0,0 +1,233 @@+// Copyright (C) 2018-2026 Intel Corporation+// SPDX-License-Identifier: Apache-2.0+//++#include "transformations/cpu_opset/x64/pass/mlp_fusion.hpp"++#include <gtest/gtest.h>++#include <memory>+#include <string>+#include <utility>+#include <vector>++#include "common_test_utils/ov_test_utils.hpp"+#include "common_test_utils/subgraph_builders/weights_decompression_builders.hpp"+#include "openvino/core/except.hpp"+#include "openvino/op/constant.hpp"+#include "openvino/op/convert.hpp"+#include "openvino/op/matmul.hpp"+#include "openvino/op/multiply.hpp"+#include "openvino/op/parameter.hpp"+#include "openvino/op/swish.hpp"+#include "openvino/op/variadic_split.hpp"+#include "openvino/pass/manager.hpp"+#include "ov_ops/type_relaxed.hpp"+#include "transformations/common_optimizations/activations_scaling.hpp"+#include "transformations/cpu_opset/x64/op/llm_mlp.hpp"++using namespace ov;+using namespace ov::op;+using ov::intel_cpu::LLMMLPNode;++namespace {+constexpr size_t kHidden = 16;+constexpr size_t kUp = 32;+constexpr float kScale = 8.0F;++using GateUpType = LLMMLPNode::GATE_UP_TYPE;++struct MLPParams {+ GateUpType type;+ bool int8;+};++// rows in [scaled_begin, scaled_end) are scaled+std::shared_ptr<v0::Constant> make_weights(size_t rows,+ size_t cols,+ float start,+ size_t scaled_begin = 0,+ size_t scaled_end = 0) {+ std::vector<float> values(rows * cols);+ for (size_t i = 0; i < values.size(); ++i) {+ const bool scaled = i / cols >= scaled_begin && i / cols < scaled_end;+ values[i] = (start + 0.001F * static_cast<float>(i % 97)) * (scaled ? kScale : 1.0F);+ }+ return v0::Constant::create(element::f16, Shape{rows, cols}, values);+}++// Convert(i8 [rows, kHidden]) * per-OC f32 scales [rows, 1]+std::shared_ptr<v1::Multiply> make_int8_weights(size_t rows, size_t seed) {+ using ov::test::utils::DecompressionType;+ auto deq = ov::test::utils::initMatMulDecompressionSubgraph(Shape{kHidden, rows},+ -1,+ element::f32,+ element::i8,+ element::f32,+ element::f32,+ true,+ DecompressionType::full,+ DecompressionType::empty,+ false,+ false,+ seed);+ return ov::as_type_ptr<v1::Multiply>(deq);+}++// i8 weights and their per-OC scales, rows in [scaled_begin, scaled_end) scaled+std::pair<Output<Node>, Output<Node>> make_ref_int8_weights(size_t rows,+ size_t seed,+ size_t scaled_begin,+ size_t scaled_end) {+ auto deq = make_int8_weights(rows, seed);+ auto scales = ov::as_type_ptr<v0::Constant>(deq->get_input_node_shared_ptr(1))->cast_vector<float>();+ for (size_t row = scaled_begin; row < scaled_end; ++row) {+ scales[row] *= kScale;+ }+ return {deq->get_input_node_ptr(0)->input_value(0), v0::Constant::create(element::f32, Shape{rows, 1}, scales)};+}++std::shared_ptr<Model> make_mlp(const MLPParams& params, bool scaled_gate) {+ const auto prc = params.int8 ? element::f32 : element::f16;+ auto weights = [&](size_t rows, float start, size_t seed) -> Output<Node> {+ if (params.int8) {+ return make_int8_weights(rows, seed);+ }+ return make_weights(rows, kHidden, start);+ };+ auto input = std::make_shared<v0::Parameter>(prc, PartialShape{-1, -1, kHidden});+ Output<Node> gate;+ Output<Node> up;+ if (params.type == GateUpType::SEPARATE) {+ gate = std::make_shared<v0::MatMul>(input, weights(kUp, 0.1F, 1), false, true);+ up = std::make_shared<v0::MatMul>(input, weights(kUp, 0.2F, 2), false, true);+ } else {+ auto gate_up = std::make_shared<v0::MatMul>(input, weights(2 * kUp, 0.1F, 1), false, true);+ auto split = std::make_shared<v1::VariadicSplit>(gate_up,+ v0::Constant::create(element::i32, Shape{}, {-1}),+ v0::Constant::create(element::i32, Shape{2}, {kUp, kUp}));+ const bool gate_first = params.type == GateUpType::COMBINED_GATE_UP;+ gate = split->output(gate_first ? 0 : 1);+ up = split->output(gate_first ? 1 : 0);+ }+ if (scaled_gate) {+ gate = std::make_shared<v1::Multiply>(gate, v0::Constant::create(prc, Shape{}, {kScale}));+ }+ auto gated = std::make_shared<v1::Multiply>(std::make_shared<v4::Swish>(gate), up);+ Output<Node> down_w = make_weights(kHidden, kUp, 0.3F);+ if (params.int8) {+ down_w = std::make_shared<v0::Convert>(down_w, element::f32);+ }+ auto down = std::make_shared<v0::MatMul>(gated, down_w, false, true);+ return std::make_shared<Model>(OutputVector{down}, ParameterVector{input});+}++// LLMMLP with the scale folded into the gate rows+std::shared_ptr<LLMMLPNode> make_ref_mlp(const Output<Node>& input, const MLPParams& params) {+ const size_t gate_begin = params.type == GateUpType::COMBINED_UP_GATE ? kUp : 0;+ const auto down_w = make_weights(kHidden, kUp, 0.3F);+ OutputVector args;+ if (params.int8 && params.type == GateUpType::SEPARATE) {+ auto gate = make_ref_int8_weights(kUp, 1, 0, kUp);+ auto up = make_ref_int8_weights(kUp, 2, 0, 0);+ args = {input, gate.first, up.first, down_w, gate.second, up.second};+ } else if (params.int8) {+ auto gate_up = make_ref_int8_weights(2 * kUp, 1, gate_begin, gate_begin + kUp);+ args = {input, gate_up.first, gate_up.first, down_w, gate_up.second, gate_up.second};+ } else if (params.type == GateUpType::SEPARATE) {+ args = {input, make_weights(kUp, kHidden, 0.1F, 0, kUp), make_weights(kUp, kHidden, 0.2F), down_w};+ } else {+ auto gate_up = make_weights(2 * kUp, kHidden, 0.1F, gate_begin, gate_begin + kUp);+ args = {input, gate_up, gate_up, down_w};+ }+ LLMMLPNode::Config config{};+ config.act = LLMMLPNode::ACT_FN::SILU;+ config.gate_up_quantized = params.int8;+ config.hidden_size = static_cast<int>(kHidden);+ config.up_size = static_cast<int>(kUp);+ config.gate_up_type = params.type;+ return std::make_shared<LLMMLPNode>(args, config);+}++void register_mlp_fusion(ov::pass::Manager& manager) {+ manager.register_pass<ov::intel_cpu::MLPFusion>();+ manager.get_pass_config()->set_callback<ov::intel_cpu::MLPFusionPass>([](const std::shared_ptr<const Node>&) {+ return true;+ });+}++std::string params_name(const testing::TestParamInfo<MLPParams>& info) {+ const std::string prc = info.param.int8 ? "Int8" : "F16";+ switch (info.param.type) {+ case GateUpType::SEPARATE:+ return prc + "Separate";+ case GateUpType::COMBINED_GATE_UP:+ return prc + "CombinedGateUp";+ case GateUpType::COMBINED_UP_GATE:+ return prc + "CombinedUpGate";+ default:+ OPENVINO_THROW("Unknown GateUpType");+ }+}++class MLPFusionGateScaleTest : public TransformationTestsF, public testing::WithParamInterface<MLPParams> {+protected:+ void SetUp() override {+ TransformationTestsF::SetUp();+ comparator.enable(FunctionsComparator::CmpValues::CONST_VALUES);+ }+};++class MLPFusionAfterActivationsScalingTest : public MLPFusionGateScaleTest {};+} // namespace++TEST_P(MLPFusionGateScaleTest, FoldedIntoGateRows) {+ comparator.enable(FunctionsComparator::CmpValues::ATTRIBUTES);+ model = make_mlp(GetParam(), true);+ register_mlp_fusion(manager);+ {+ const auto prc = GetParam().int8 ? element::f32 : element::f16;+ auto input = std::make_shared<v0::Parameter>(prc, PartialShape{-1, -1, kHidden});+ model_ref = std::make_shared<Model>(OutputVector{make_ref_mlp(input, GetParam())}, ParameterVector{input});+ }+}++TEST_P(MLPFusionAfterActivationsScalingTest, Fused) {+ // the Convert keeps the output tensor name, as in the ActivationsScaling tests+ auto mlp = make_mlp(GetParam(), false);+ auto convert = std::make_shared<v0::Convert>(mlp->get_results()[0]->input_value(0), element::f32);+ model = std::make_shared<Model>(OutputVector{convert}, mlp->get_parameters());+ manager.register_pass<ov::pass::ActivationsScaling>(kScale, element::f16);+ register_mlp_fusion(manager);+ {+ auto input = std::make_shared<v0::Parameter>(element::f16, PartialShape{-1, -1, kHidden});+ // LPT keeps the scale Multiplies type-relaxed, whose attributes the comparator can't compare+ auto scale = [](const Output<Node>& data, float value) {+ return std::make_shared<ov::op::TypeRelaxed<v1::Multiply>>(+ element::TypeVector{element::f16, element::f16},+ element::TypeVector{element::f16},+ data,+ v0::Constant::create(element::f16, Shape{}, {value}));+ };+ auto scale_up = scale(make_ref_mlp(scale(input, 1.0F / kScale), GetParam()), kScale);+ auto convert = std::make_shared<v0::Convert>(scale_up, element::f32);+ model_ref = std::make_shared<Model>(OutputVector{convert}, ParameterVector{input});+ }+}++const std::vector<MLPParams> f16_params = {{GateUpType::SEPARATE, false},+ {GateUpType::COMBINED_GATE_UP, false},+ {GateUpType::COMBINED_UP_GATE, false}};++const std::vector<MLPParams> all_params = {{GateUpType::SEPARATE, false},+ {GateUpType::COMBINED_GATE_UP, false},+ {GateUpType::COMBINED_UP_GATE, false},+ {GateUpType::SEPARATE, true},+ {GateUpType::COMBINED_GATE_UP, true}};++INSTANTIATE_TEST_SUITE_P(TransformationTests, MLPFusionGateScaleTest, testing::ValuesIn(all_params), params_name);+// ActivationsScaling only scales f16+INSTANTIATE_TEST_SUITE_P(TransformationTests,+ MLPFusionAfterActivationsScalingTest,+ testing::ValuesIn(f16_params),+ params_name);diff --git a/src/plugins/intel_cpu/tests/unit/transformations/x64/qkv_proj_fusion_test.cpp b/src/plugins/intel_cpu/tests/unit/transformations/x64/qkv_proj_fusion_test.cppindex 481a2942427..7ef97259a84 100644--- a/src/plugins/intel_cpu/tests/unit/transformations/x64/qkv_proj_fusion_test.cpp+++ b/src/plugins/intel_cpu/tests/unit/transformations/x64/qkv_proj_fusion_test.cpp@@ -5,6 +5,7 @@#include <gtest/gtest.h>#include <memory>+#include <vector>#include "common_test_utils/ov_test_utils.hpp"#include "common_test_utils/test_common.hpp"@@ -18,6 +19,8 @@#include "openvino/op/multiply.hpp"#include "openvino/op/parameter.hpp"#include "openvino/pass/visualize_tree.hpp"+#include "ov_ops/type_relaxed.hpp"+#include "transformations/common_optimizations/activations_scaling.hpp"using namespace testing;using namespace ov::pass;@@ -83,4 +86,63 @@ TEST_F(TransformationTestsF, QKVProjFusion1Test) {auto v_proj = std::make_shared<v0::Result>(qkv_proj->output(2));model_ref = std::make_shared<ov::Model>(OutputVector{q_proj, k_proj, v_proj}, ParameterVector{input_param});}-}\ No newline at end of file+}++namespace {+constexpr size_t kHidden = 64;+constexpr size_t kQProj = 64;+constexpr size_t kKVProj = 16;+constexpr float kScale = 8.0F;++std::shared_ptr<v0::Constant> make_proj_weights(size_t rows, float value) {+ return v0::Constant::create(element::f16, Shape{rows, kHidden}, std::vector<float>(rows * kHidden, value));+}+} // namespace++// the Q/K/V MatMuls must still share one input after ActivationsScaling+TEST_F(TransformationTestsF, QKVProjFusionAfterActivationsScaling) {+ comparator.enable(FunctionsComparator::CmpValues::CONST_VALUES);+ {+ auto input = std::make_shared<v0::Parameter>(element::f16, PartialShape{-1, -1, kHidden});+ OutputVector outputs;+ for (const auto& [rows, value] : {std::pair{kQProj, 0.1F}, {kKVProj, 0.2F}, {kKVProj, 0.3F}}) {+ auto proj = std::make_shared<v0::MatMul>(input, make_proj_weights(rows, value), false, true);+ // the Convert keeps the output tensor name, as in the ActivationsScaling tests+ outputs.push_back(std::make_shared<v0::Convert>(proj, element::f32));+ }+ model = std::make_shared<ov::Model>(outputs, ParameterVector{input});+ manager.register_pass<ov::pass::ActivationsScaling>(kScale, element::f16);+ manager.register_pass<ov::intel_cpu::QKVProjFusion>();+ manager.get_pass_config()->set_callback<ov::intel_cpu::QKVProjFusionPass1>(+ [](const std::shared_ptr<const ov::Node>&) -> bool {+ return true;+ });+ }+ {+ // LPT keeps the scale Multiplies type-relaxed+ auto scale_mul = [](const Output<Node>& data, float value) {+ return std::make_shared<ov::op::TypeRelaxed<v1::Multiply>>(+ element::TypeVector{element::f16, element::f16},+ element::TypeVector{element::f16},+ data,+ v0::Constant::create(element::f16, Shape{}, {value}));+ };+ auto input = std::make_shared<v0::Parameter>(element::f16, PartialShape{-1, -1, kHidden});+ intel_cpu::QKVProjectionNode::Config config{false,+ static_cast<int>(kHidden),+ static_cast<int>(kQProj),+ static_cast<int>(kKVProj),+ static_cast<int>(kKVProj),+ false};+ auto qkv_proj = std::make_shared<intel_cpu::QKVProjectionNode>(OutputVector{scale_mul(input, 1.0F / kScale),+ make_proj_weights(kQProj, 0.1F),+ make_proj_weights(kKVProj, 0.2F),+ make_proj_weights(kKVProj, 0.3F)},+ config);+ OutputVector outputs;+ for (size_t i = 0; i < 3; ++i) {+ outputs.push_back(std::make_shared<v0::Convert>(scale_mul(qkv_proj->output(i), kScale), element::f32));+ }+ model_ref = std::make_shared<ov::Model>(outputs, ParameterVector{input});+ }+}diff --git a/src/plugins/intel_gpu/src/plugin/transformations_pipeline.cpp b/src/plugins/intel_gpu/src/plugin/transformations_pipeline.cppindex 103b61519fb..848a62a4765 100644--- a/src/plugins/intel_gpu/src/plugin/transformations_pipeline.cpp+++ b/src/plugins/intel_gpu/src/plugin/transformations_pipeline.cpp@@ -25,15 +25,11 @@#include "intel_gpu/op/read_value.hpp"#include "low_precision/add.hpp"#include "low_precision/concat.hpp"-#include "low_precision/convolution.hpp"#include "low_precision/convolution_backprop_data.hpp"-#include "low_precision/fake_quantize_decomposition.hpp"#include "low_precision/fold_convert.hpp"#include "low_precision/fuse_convert.hpp"-#include "low_precision/group_convolution.hpp"#include "low_precision/qdq_stripping.hpp"#include "low_precision/low_precision.hpp"-#include "low_precision/mat_mul.hpp"#include "low_precision/multiply_to_group_convolution.hpp"#include "low_precision/mvn.hpp"#include "low_precision/network_helper.hpp"@@ -160,7 +156,6 @@#include "transformations/common_optimizations/fuse_gated_delta_net.hpp"#include "transformations/common_optimizations/glu_fusion.hpp"#include "transformations/common_optimizations/group_normalization_fusion.hpp"-#include "transformations/common_optimizations/lin_op_sequence_fusion.hpp"#include "transformations/common_optimizations/lora_subgraph_fusion.hpp"#include "transformations/common_optimizations/lstm_cell_fusion.hpp"#include "transformations/common_optimizations/move_eltwise_up_data_movement.hpp"@@ -243,7 +238,6 @@#include "transformations/opset_conversions/convert_opset3_to_opset2.hpp"#include "transformations/paged_attention/convert_pagedattn_inputs.hpp"#include "transformations/resolve_names_collisions.hpp"-#include "transformations/rt_info/dequantization_node.hpp"#include "transformations/rt_info/disable_precision_conversion.hpp"#include "transformations/rt_info/keep_const_precision.hpp"#include "transformations/smart_reshape/matmul_sr.hpp"@@ -982,59 +976,7 @@ void TransformationsPipeline::apply_activation_scaling_transformations(const stdfloat activations_scale_factor = config.get_activations_scale_factor();if (activations_scale_factor > 0.F && infer_precision == ov::element::f16) {- using namespace ov::pass::low_precision;-- auto supportedPrecisions = std::vector<PrecisionsRestriction>({});- auto perTensorQuantization = std::vector<QuantizationGranularityRestriction>({});-- pass_config->disable<ov::pass::AddMultiplyFusion>();- pass_config->disable<RecurrentCellTransformation>();- pass_config->disable<MultiplyToGroupConvolutionTransformation>();- pass_config->disable<ConvolutionTransformation>();- pass_config->disable<ConvolutionBackpropDataTransformation>();- pass_config->disable<GroupConvolutionTransformation>();- pass_config->disable<MatMulTransformation>();- pass_config->disable<MVNTransformation>();- // This LPT run only moves scalar Multiply layers. FakeQuantize layers left by the INT8 LPT run (e.g. Q/K- // quantization before SDPA) must not be decomposed again: the f16 DataPrecision interval (+/-1e15)- // overflows f16 and turns the quantized activations into inf/NaN.- pass_config->disable<FakeQuantizeDecompositionTransformation>();-- pass_config->set_callback<FoldConvertTransformation>(- [](const std::shared_ptr<const ov::Node> &node) -> bool {- return ov::is_dequantization_node(node);- });-- pass_config->set_callback<FuseConvertTransformation>(- [](const std::shared_ptr<const ov::Node> &node) -> bool {- return (ov::is_dequantization_node(node) || ov::is_type<ov::opset1::FakeQuantize>(node));- });-- manager.register_pass<ov::pass::activations_scaling::ScaleDownSingleLayer>(activations_scale_factor, infer_precision);- manager.register_pass<ov::pass::SharedOpOptimization>();-- pass_config->set_callback<ov::pass::activations_scaling::ScaleDownSingleLayer>(- [&infer_precision](const std::shared_ptr<const ov::Node> &node) -> bool {- return (node->input(0).get_element_type() != infer_precision);- });-- // Move down scalar-multiply layers as much as possible- auto params = LayerTransformation::Params(false, infer_precision, {infer_precision}, true, true);- auto lpt_pass = manager.register_pass<LowPrecision>(supportedPrecisions, perTensorQuantization, params);- lpt_pass->add_main<ov::pass::activations_scaling::EliminateScalarMul>();- lpt_pass->add_main<ov::pass::activations_scaling::MoveDownScalarMul>();-- // Move up remained scalar-multiply layers- manager.register_pass<ov::pass::EliminateEltwise>();- manager.register_pass<ov::pass::activations_scaling::MulShareTransformation>();-- const std::vector<DiscreteTypeInfo> allowed_data_movement_ops = {- ov::op::v1::Reshape::get_type_info_static(),- ov::op::v1::Transpose::get_type_info_static(),- };- manager.register_pass<ov::pass::MoveEltwiseUpThroughDataMovScalar>(allowed_data_movement_ops);- manager.register_pass<ov::pass::SharedOpOptimization>();- manager.register_pass<ov::pass::Validate>();+ manager.register_pass<ov::pass::ActivationsScaling>(activations_scale_factor, infer_precision);}manager.run_passes(func);diff --git a/src/plugins/intel_gpu/tests/functional/subgraph_tests/dynamic/activations_scaling.cpp b/src/plugins/intel_gpu/tests/functional/subgraph_tests/dynamic/activations_scaling.cppindex 807428f6e46..d49574eb6db 100644--- a/src/plugins/intel_gpu/tests/functional/subgraph_tests/dynamic/activations_scaling.cpp+++ b/src/plugins/intel_gpu/tests/functional/subgraph_tests/dynamic/activations_scaling.cpp@@ -16,6 +16,7 @@#include "openvino/op/sqrt.hpp"#include "openvino/op/divide.hpp"#include "openvino/op/fake_quantize.hpp"+#include "openvino/op/gather.hpp"#include "openvino/op/multiply.hpp"#include "openvino/op/power.hpp"#include "openvino/op/reduce_mean.hpp"@@ -276,6 +277,68 @@ TEST_F(ActivationsScalingFeatureAxisRMS, Inference) {run();}+// Gemma3-like layer: with the post norms kept in f32 by DisableFP16CompForGemma3RMSPattern, the embedding+// normalizer and the residual Adds stay in f32 while the following input norms run in f16, so the graph has+// Multiply(f32) -> Convert(f16) -> RMS. EliminateScalarMul must drop that Multiply: the embedding times the+// normalizer exceeds the f16 range, the embedding itself doesn't.+//+// ids -> Gather -> Multiply ─┬─> RMS -> MatMul -> RMS -> Add ─┬─> RMS -> MatMul -> RMS -> Add -> RMS+// └──────────────────────────────┘ └──────────────────────────────┘+class ActivationsScalingF32Norm : virtual public ov::test::SubgraphBaseTest {+protected:+ static constexpr size_t hidden_size = 64;+ static constexpr size_t vocab_size = 512;++ static ov::Output<ov::Node> make_rms_norm(const ov::Output<ov::Node>& x) {+ auto square = std::make_shared<ov::op::v1::Power>(x, ov::op::v0::Constant::create(ov::element::f32, {}, {2.f}));+ auto mean = std::make_shared<ov::op::v1::ReduceMean>(square, ov::op::v0::Constant::create(ov::element::i64, {1}, {-1}), true);+ auto eps = ov::op::v0::Constant::create(ov::element::f32, {}, {1e-6f});+ auto sqrt = std::make_shared<ov::op::v0::Sqrt>(std::make_shared<ov::op::v1::Add>(mean, eps));+ auto div = std::make_shared<ov::op::v1::Divide>(x, sqrt);+ auto gamma = ov::op::v0::Constant::create(ov::element::f32, {hidden_size}, {1.f});+ return std::make_shared<ov::op::v1::Multiply>(div, gamma);+ }++ static ov::Output<ov::Node> make_linear(const ov::Output<ov::Node>& x, int seed) {+ const auto weights =+ ov::test::utils::create_and_fill_tensor(ov::element::f32, {hidden_size, hidden_size}, ov::test::utils::InputGenerateData(-1, 2, 1000, seed));+ return std::make_shared<ov::op::v0::MatMul>(x, std::make_shared<ov::op::v0::Constant>(weights));+ }++ void SetUp() override {+ targetDevice = ov::test::utils::DEVICE_GPU;+ configuration = {{ov::hint::inference_precision.name(), ov::element::f16}, {ov::hint::activations_scale_factor.name(), 8.f}};+ abs_threshold = 0.05;+ rel_threshold = 0.05;++ init_input_shapes({{{-1, -1}, {{1, 12}, {2, 7}}}});++ auto ids = std::make_shared<ov::op::v0::Parameter>(ov::element::i64, inputDynamicShapes[0]);+ // embedding values up to 3000 fit f16, times the normalizer they don't+ const auto table =+ ov::test::utils::create_and_fill_tensor(ov::element::f16, {vocab_size, hidden_size}, ov::test::utils::InputGenerateData(1000, 2000, 1, 1));+ auto table_f32 = std::make_shared<ov::op::v0::Convert>(std::make_shared<ov::op::v0::Constant>(table), ov::element::f32);+ auto gather = std::make_shared<ov::op::v8::Gather>(table_f32, ids, ov::op::v0::Constant::create(ov::element::i64, {}, {0}));+ auto embedding = std::make_shared<ov::op::v1::Multiply>(gather, ov::op::v0::Constant::create(ov::element::f32, {}, {40.f}));++ auto residual0 = std::make_shared<ov::op::v1::Add>(embedding, make_rms_norm(make_linear(make_rms_norm(embedding), 1)));+ auto residual1 = std::make_shared<ov::op::v1::Add>(residual0, make_rms_norm(make_linear(make_rms_norm(residual0), 2)));+ function = std::make_shared<ov::Model>(ov::OutputVector{make_rms_norm(residual1)}, ov::ParameterVector{ids}, "ActivationsScalingF32Norm");+ }++ void generate_inputs(const std::vector<ov::Shape>& targetInputStaticShapes) override {+ inputs.clear();+ const auto ids = function->get_parameters()[0];+ auto tensor =+ ov::test::utils::create_and_fill_tensor(ov::element::i64, targetInputStaticShapes[0], ov::test::utils::InputGenerateData(0, vocab_size - 1, 1, 1));+ inputs.insert({ids, tensor});+ }+};++TEST_F(ActivationsScalingF32Norm, smoke_GPU_ActivationsScalingF32Norm) {+ run();+}+// FakeQuantize layers kept by the INT8 LPT run (Q/K quantization in front of SDPA, as in INT8 hybrid quantized// diffusion transformers) must keep their intervals when activations scaling runs LPT again. Decomposing them with// the f16 DataPrecision interval overflows f16 in the standalone quantize primitive and SDPA returns NaN.