← Back to Pull requests

[TRANSFORMATIONS][CPU] Share activations scaling between GPU and CPU #38563

Open
goyaladitya05 opened this pull request with 717 lines diff across 17 files
View on GitHub
goyaladitya05 goyaladitya05 commented on Oct 02, 2026 12:52 UTC
Author

Details:


- This PR is a follow up to #37041, it moves GPU's activations scaling pipeline into a common ov::pass::ActivationsScaling ModelPass. GPU now registers this pass; its output is bit-identical to before.
- CPU registers the pass on x86-64 when inference_precision is f16 and activations_scale_factor > 0. The factor comes from the property or the IR's runtime_options, where optimum-intel sets it to 8 for diffusion text encoders and VAEs.
- The pass runs on a copy of the caller's PassConfig, so plugin callbacks apply to its inner passes while its LPT disables stay local.
- On AMX-FP16 CPUs, MLP/QKV fusion is skipped when scaling is on, so the MatMuls stay visible to the pass.
- EliminateScalarMul now also matches when a Convert sits between the scale and the norm, which happens because CPU keeps norms in f32.
- SharedOpOptimization keeps the output type when it upgrades v0::ShapeOf. It used to hardcode i64, which broke CPU's i32 shape subgraphs and failed T5 compilation.

Tickets:


- Closes #37039

AI Assistance:


- AI assistance used: yes
- If yes, summarize how AI was used and what human validation was performed (build/tests/manual checks). Used for occasional code generation and review.

Diff: 717 lines (+638 / -79) across 17 files Reviewer: v-Golubev Review duration: 16148m
All Vouch review confidence checks passed
Residual risk 0.07 = Change Risk (0.71) × (1 − Review Confidence (0.90)). Review depth and reviewer attention state are adequate.
Model 1 · Change Risk (XGBoost)
Score: 0.71 · 717 lines diff across 17 files
0.71
Model 2 · Review Depth (DistilBERT)
Depth Score: 0.88 · 5 substantive comment(s)
0.88
Model 3 · Review Timing & Attention
Session adequacy: 100% · Reviewer familiarity: 50%
90%
Bedrock Claude 3 · Risk Narration
(disconnected)
Groq
Groq Risk Narration
AWS Bedrock is currently disconnected. Generate high-confidence PR triage narration on-demand using Groq.
Model 1 · Change Risk Attribution
SHAP Weights
Diff Size diff_size
0.393
Mass File Touch mass_file_touch
0.080
Real PR Conversation Timeline
23 items
goyaladitya05 goyaladitya05 commented on Oct 02, 2026 12:58 UTC
Author

Results (LTX-Video, Core Ultra 7 258V, f16):
- T5 encoder: 100% NaN without scaling, 0 NaN with it (cosine 0.99998 vs f32).
- Overhead: about 0.1–0.4% latency on the T5 encoder and the VAE.
- Full 97-frame sample -->

https://github.com/user-attachments/assets/bd357139-3666-4615-b0f4-7548a19f3367

goyaladitya05 goyaladitya05 commented on Oct 02, 2026 13:09 UTC
Author

@v-Golubev @CuriousPanCake Please take a look, thanks!

p-durandin p-durandin commented on Oct 05, 2026 07:12 UTC
Contributor

build_jenkins

CuriousPanCake CuriousPanCake commented on Oct 06, 2026 09:39 UTC
Contributor

build_jenkins

p-durandin p-durandin commented on Oct 08, 2026 09:12 UTC
Contributor

build_jenkins

Copilot Copilot commented on code on Oct 08, 2026 10:01 UTC
Code Review
src/common/transformations/src/transformations/common_optimizations/activations_scaling.cpp:1
@@ -383,4 +410,69 @@ 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();
+
+    // 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>();
+
+    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);
+    });
+
+    manager.register_pass<activations_scaling::ScaleDownSingleLayer>(m_scale_factor, m_scaled_prec);
+    manager.register_pass<SharedOpOptimization>();

The exported model pass is not idempotent: every invocation rematches the same MatMul/Convolution nodes and inserts another scale pair, so registering or running it twice scales by an additional factor and adjusts normalization epsilon again. Mark already processed linear ops (or recognize the existing scale pair) so a second run is a no-op, and cover this with a double-run transformation test.

Copilot Copilot commented on code on Oct 08, 2026 10:01 UTC
Code Review
src/plugins/intel_cpu/src/config.cpp:1
@@ -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 {
+                activationsScaleFactorSetExplicitly = true;
+                activationsScaleFactor = val.as<float>();

Set the explicit flag only after conversion succeeds. Plugin::set_property() applies this directly to the shared engConfig, so an invalid value currently throws after leaving the flag set; subsequent compilations then ignore a valid model rt_info value and silently retain the default factor.

Copilot Copilot commented on code on Oct 08, 2026 10:01 UTC
Code Review
src/plugins/intel_cpu/tests/functional/custom/subgraph_tests/src/x64/activations_scaling.cpp:1
@@ -0,0 +1,139 @@
+// Copyright (C) 2018-2026 Intel Corporation
+// SPDX-License-Identifier: Apache-2.0
+//
+
+#include "common_test_utils/common_utils.hpp"
+#include "common_test_utils/file_utils.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: RMSNorm -> MatMul -> Gelu -> MatMul -> Add(residual) -> RMSNorm,
+// 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.
+class ActivationsScalingCPUTest : public testing::WithParamInterface<float>, virtual public SubgraphBaseTest {
+public:
+    static std::string getTestCaseName(const testing::TestParamInfo<float>& obj) {
+        std::ostringstream result;
+        result << "scale_factor=" << 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) {
+        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);
+        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(), 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);
+        auto weights0 = ov::op::v0::Constant::create(ov::element::f32, ov::Shape{hidden_size, inter_size}, {1.f});
+        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::op::v0::Constant::create(ov::element::f32, ov::Shape{inter_size, hidden_size}, {8.f});
+        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);
+        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);
+    core->set_property(ov::cache_dir(cache_dir));

Setting the cache directory on this core mutates the shared PluginCache Core used by other SubgraphBaseTest fixtures. Removing the directory does not clear that property, so later tests remain cache-enabled against this test-specific path and can become order-dependent or leave artifacts. Pass the cache directory through this fixture's per-compile configuration instead.

copilot-pull-request-reviewer[bot] copilot-pull-request-reviewer[bot] commented on Oct 08, 2026 10:01 UTC
Reviewer

<!-- ccr-overview-v2 -->

🟡 Changes recommended

The pass is not idempotent, and property parsing plus cache-test setup can leave persistent invalid state.

<details open>
<summary><strong>3 open findings</strong></summary>

  • <picture><source media="(prefers-color-scheme: dark)" srcset="https://github.githubassets.com/static/images/icons/copilot-code-review/medium-v2-dark.svg"><source media="(prefers-color-scheme: light)" srcset="https://github.githubassets.com/static/images/icons/copilot-code-review/medium-v2-light.svg"><img src="https://github.githubassets.com/static/images/icons/copilot-code-review/medium-v2-light.png" alt="Medium severity" width="62" height="18" align="texttop"></picture> [Make exported model pass idempotent](#discussion_r4217543119) · New

  • <picture><source media="(prefers-color-scheme: dark)" srcset="https://github.githubassets.com/static/images/icons/copilot-code-review/medium-v2-dark.svg"><source media="(prefers-color-scheme: light)" srcset="https://github.githubassets.com/static/images/icons/copilot-code-review/medium-v2-light.svg"><img src="https://github.githubassets.com/static/images/icons/copilot-code-review/medium-v2-light.png" alt="Medium severity" width="62" height="18" align="texttop"></picture> [Set explicit flag only after successful conversion](#discussion_r4217543221) · New

  • <picture><source media="(prefers-color-scheme: dark)" srcset="https://github.githubassets.com/static/images/icons/copilot-code-review/medium-v2-dark.svg"><source media="(prefers-color-scheme: light)" srcset="https://github.githubassets.com/static/images/icons/copilot-code-review/medium-v2-light.svg"><img src="https://github.githubassets.com/static/images/icons/copilot-code-review/medium-v2-light.png" alt="Medium severity" width="62" height="18" align="texttop"></picture> [Avoid mutating shared plugin cache configuration](#discussion_r4217543294) · New

  • </details>

    <details>
    <summary><strong>What changed in this PR</strong></summary>

    Shares activation scaling between GPU and x86-64 CPU through a common transformation pass.

    Changes:

  • Introduces reusable ActivationsScaling and extends normalization handling.

  • Adds CPU property plumbing, pipeline registration, and tests.

  • Preserves i32 output when upgrading ShapeOf.
  • | File | Description |
    | ---- | ----------- |
    | src/​plugins/​intel_gpu/​src/​plugin/​transformations_pipeline.cpp | Uses the common scaling pass. |
    | src/​plugins/​intel_cpu/​tests/​functional/​sources.cmake | Registers the CPU test. |
    | src/​plugins/​intel_cpu/​tests/​functional/​custom/​subgraph_tests/​src/​x64/​activations_scaling.cpp | Tests inference and caching. |
    | src/​plugins/​intel_cpu/​tests/​functional/​custom/​behavior/​ov_plugin/​properties.cpp | Checks plugin property exposure. |
    | src/​plugins/​intel_cpu/​tests/​functional/​custom/​behavior/​ov_executable_network/​properties.cpp | Tests property values and precedence. |
    | src/​plugins/​intel_cpu/​src/​transformations/​transformation_pipeline.cpp | Enables scaling for CPU f16. |
    | src/​plugins/​intel_cpu/​src/​plugin.cpp | Exposes the CPU property. |
    | src/​plugins/​intel_cpu/​src/​config.h | Stores scaling configuration. |
    | src/​plugins/​intel_cpu/​src/​config.cpp | Parses property and runtime metadata. |
    | src/​plugins/​intel_cpu/​src/​compiled_model.cpp | Reports compiled-model property. |
    | src/​common/​transformations/​tests/​common_optimizations/​shared_ops_optimization.cpp | Tests i32 ShapeOf preservation. |
    | src/​common/​transformations/​tests/​common_optimizations/​activations_scaling_test.cpp | Extends transformation coverage. |
    | src/​common/​transformations/​src/​transformations/​common_optimizations/​shared_ops_optimization.cpp | Preserves ShapeOf output type. |
    | src/​common/​transformations/​src/​transformations/​common_optimizations/​activations_scaling.cpp | Implements the common pipeline. |
    | src/​common/​transformations/​include/​transformations/​common_optimizations/​activations_scaling.hpp | Declares and documents the pass. |
    | docs/​articles_en/​openvino-workflow/​running-inference/​optimize-inference/​precision-control.rst | Documents CPU support. |
    | docs/​articles_en/​openvino-workflow/​running-inference/​inference-devices-and-modes/​cpu-device.rst | Lists the CPU property. |
    </details>

    🧠 Review effort: Balanced

    ---

    Give feedback about Copilot approvals in this survey to enter a drawing for a $150 gift card.

    v-Golubev v-Golubev commented on code on Oct 08, 2026 10:18 UTC
    Code Review
    src/common/transformations/src/transformations/common_optimizations/activations_scaling.cpp:1
    @@ -383,4 +410,69 @@ 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();
    +
    +    // 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>();
    +
    +    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);
    +    });
    +
    +    manager.register_pass<activations_scaling::ScaleDownSingleLayer>(m_scale_factor, m_scaled_prec);
    +    manager.register_pass<SharedOpOptimization>();

    This is the original ActivationsScaling behavior, we shouldn't change it within this PR

    goyaladitya05 goyaladitya05 commented on code on Oct 08, 2026 15:58 UTC
    Code Review
    src/plugins/intel_cpu/tests/functional/custom/subgraph_tests/src/x64/activations_scaling.cpp:1
    @@ -0,0 +1,139 @@
    +// Copyright (C) 2018-2026 Intel Corporation
    +// SPDX-License-Identifier: Apache-2.0
    +//
    +
    +#include "common_test_utils/common_utils.hpp"
    +#include "common_test_utils/file_utils.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: RMSNorm -> MatMul -> Gelu -> MatMul -> Add(residual) -> RMSNorm,
    +// 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.
    +class ActivationsScalingCPUTest : public testing::WithParamInterface<float>, virtual public SubgraphBaseTest {
    +public:
    +    static std::string getTestCaseName(const testing::TestParamInfo<float>& obj) {
    +        std::ostringstream result;
    +        result << "scale_factor=" << 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) {
    +        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);
    +        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(), 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);
    +        auto weights0 = ov::op::v0::Constant::create(ov::element::f32, ov::Shape{hidden_size, inter_size}, {1.f});
    +        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::op::v0::Constant::create(ov::element::f32, ov::Shape{inter_size, hidden_size}, {8.f});
    +        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);
    +        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);
    +    core->set_property(ov::cache_dir(cache_dir));

    done

    goyaladitya05 goyaladitya05 commented on code on Oct 08, 2026 15:58 UTC
    Code Review
    src/plugins/intel_cpu/src/config.cpp:1
    @@ -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 {
    +                activationsScaleFactorSetExplicitly = true;
    +                activationsScaleFactor = val.as<float>();

    done

    v-Golubev v-Golubev commented on Oct 09, 2026 07:49 UTC
    Contributor

    build_jenkins

    v-Golubev v-Golubev commented on code on Oct 12, 2026 11:02 UTC
    Code Review
    src/common/transformations/src/transformations/common_optimizations/activations_scaling.cpp:1
    @@ -209,11 +226,13 @@ 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()});
    +    // the normalization may be kept in f32
    +    auto post_convert_m = pattern::optional<v0::Convert>(mul_m);

    Please note: EliminateScalarMul is shared with GPU, so this extension changes GPU graphs as well, not only CPU ones. GPU also keeps some norms in f32 (e.g. DisableFP16CompForGemma3RMSPattern keeps RMS in f32, so ConvertPrecision inserts a Convert in front of it), and now the scale-up Multiply is eliminated there too. So, as far as I see, GPU output is not guaranteed to be bit-identical anymore, as the description states.

    I believe the change itself is correct, but since it affects GPU accuracy, could you please validate it on GPU on a model with f32 norms (e.g. Gemma3 with ACTIVATIONS_SCALE_FACTOR) and cover this case in src/plugins/intel_gpu/tests/functional/subgraph_tests/dynamic/activations_scaling.cpp? Please also update the PR description accordingly

    v-Golubev v-Golubev commented on code on Oct 12, 2026 11:02 UTC
    Code Review
    src/common/transformations/src/transformations/common_optimizations/activations_scaling.cpp:1
    @@ -209,11 +226,13 @@ 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()});
    +    // 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()});

    Please note: #38680 changes exactly this pattern and adds tests right after EliminateScalarMulTest, so the PRs conflict in activations_scaling.cpp and activations_scaling_test.cpp. When resolving the conflict, the gamma-less branch must take post_convert_m as well, otherwise Multiply -> Convert -> RMS will be handled only for RMS with gamma:

        auto rms_with_gamma_m = pattern::wrap_type<ov::op::internal::RMS>({post_convert_m, pattern::any_input()});
        auto rms_without_gamma_m = pattern::wrap_type<ov::op::internal::RMS>({post_convert_m});
    

    Also, #38680 adds the ActivationsScalingFeatureAxisRMS GPU test, which will go through the new ActivationsScaling pass, so GPU activations scaling tests should be re-run by whichever PR is merged second.

    v-Golubev v-Golubev commented on code on Oct 12, 2026 11:02 UTC
    Code Review
    src/common/transformations/include/transformations/common_optimizations/activations_scaling.hpp:1
    @@ -30,6 +32,45 @@ 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 and removing the compensating scale-up at normalization 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, multiplies the output back, and moves that scale-up
    + * Multiply down the graph (through Add, residual connections and data movement ops) with LPT. A
    + * normalization is invariant to the input scale, Norm(s * x) = Norm(x) with epsilon / s^2, so the
    + * scale-up is dropped there and the subgraph between two normalizations runs scaled.
    + *
    + * Before:                              After:
    + *
    + *   residual    x                        residual          x
    + *      │        │                           │              │
    + *      │     MatMul                    Multiply(1/s)  Multiply(1/s)
    + *      │        │                           │              │
    + *      └──Add───┘                           │           MatMul
    + *          │                                └─────Add──────┘
    + *        Norm(eps)                                 │
    + *                                            Norm(eps / s^2)
    + *
    + * 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:
    +    float m_scale_factor;
    +    ov::element::Type m_scaled_prec;

    Minor:

        const float m_scale_factor;
        const ov::element::Type m_scaled_prec;
    

    v-Golubev v-Golubev commented on code on Oct 12, 2026 11:49 UTC
    Code Review
    src/plugins/intel_cpu/src/transformations/transformation_pipeline.cpp:1
    @@ -1142,8 +1143,9 @@ void Transformations::PostLpt() {
         // 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) &&
                                      (config.inferencePrecision == element::bf16);
    +    // ActivationsScaling (registered below) can't scale MatMuls once they are fused into LLMMLP/QKVProjection
         auto can_use_amx_fp16 = dnnl::impl::cpu::x64::mayiuse(dnnl::impl::cpu::x64::avx512_core_amx_fp16) &&
    -                            (config.inferencePrecision == element::f16);
    +                            (config.inferencePrecision == element::f16) && config.activationsScaleFactor <= 0.F;

    We mustn't disable the existing perf optimizations because of activations scaling. Let's better register ActivationsScaling before MLPFusion/QKVProjFusion

    Please note: I suppose MLPFusion pattern may need to tolerate a scalar Multiply between the gate MatMul and the activation after scaling, since the scale-up can't be moved through Swish/Gelu. QKVProjFusion should be fine since it matches on the shared input. Could you please double check this?

    v-Golubev v-Golubev commented on code on Oct 12, 2026 11:49 UTC
    Code Review
    src/plugins/intel_cpu/src/transformations/transformation_pipeline.cpp:1
    @@ -1193,6 +1195,15 @@ void Transformations::PostLpt() {
                               ov::pass::RMSFusion,
                               false /* force_tail_convert */,
                               enable_without_gamma);
    +#if defined(OPENVINO_ARCH_X86_64)

    Activations scaling is needed on all platforms which use f16 inference precision (e.g. f16 is the default precision on ARM), so let's register it for all platforms, not only x64. Please note: RMSFusion and DecomposeRMSNorm are registered only for x64 now, and the RMSNorm node itself requires avx2+, so on other platforms we need RMSFusion -> ActivationsScaling -> DecomposeRMSNorm as well, otherwise the scale-up is not eliminated at the norms. The functional test and the docs ("x86-64 only") should be updated accordingly

    v-Golubev v-Golubev commented on Oct 13, 2026 07:10 UTC
    Contributor

    build_jenkins

    goyaladitya05 goyaladitya05 commented on code on Oct 13, 2026 07:35 UTC
    Code Review
    src/plugins/intel_cpu/src/transformations/transformation_pipeline.cpp:1
    @@ -1193,6 +1195,15 @@ void Transformations::PostLpt() {
                               ov::pass::RMSFusion,
                               false /* force_tail_convert */,
                               enable_without_gamma);
    +#if defined(OPENVINO_ARCH_X86_64)

    done, registered for all platforms with RMSFusion -> ActivationsScaling -> DecomposeRMSNorm outside x64.

    updated tests and docs as well

    goyaladitya05 goyaladitya05 commented on code on Oct 13, 2026 07:36 UTC
    Code Review
    src/common/transformations/src/transformations/common_optimizations/activations_scaling.cpp:1
    @@ -209,11 +226,13 @@ 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()});
    +    // 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()});

    thanks for the heads up, will take care of this!

    goyaladitya05 goyaladitya05 commented on Oct 13, 2026 07:48 UTC
    Author

    Thanks for the review @v-Golubev!
    I haven't addressed all the changes yet, will address the remaining ones soon :)

    Reviewers
    Assignees
    goyaladitya05 goyaladitya05
    Labels
    risk: low confidence: 90.2% reviewed
    Vouch Risk Breakdown
    AI-powered review risk analysis
    Change Risk
    Change Risk · Model 1 (XGBoost)
    Predicted defect probability (0.00–1.00) based on diff churn, modified sensitive files, and author risk history.
    Score: 70.9% (HIGH) · Higher = larger blast radius
    70.9%
    Review Confidence
    Review Confidence · Models 2 & 3
    Scrutiny score (0.00–1.00) combining DistilBERT semantic review depth with reviewer familiarity and session dwell time.
    Score: 90.2% · Lower = rushed or shallow review
    90.2%
    Residual Risk
    Residual Risk · Core Equation
    Residual = Change × (1 − Confidence)
    Unmitigated risk surviving review. ≥ 0.65 triggers an automated re-queue to protect production.
    Score: 7.0% · Safe to merge
    7.0%