Skip to content

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

[GPU] Fuse L2 normalization into RMS (#39317)

Kamil Wielochc8de4a4f3c3c
diff --git a/src/plugins/intel_gpu/sources.cmake b/src/plugins/intel_gpu/sources.cmake
index 4558b489337..18a84259f67 100644
--- a/src/plugins/intel_gpu/sources.cmake
+++ b/src/plugins/intel_gpu/sources.cmake
@@ -191,6 +191,7 @@ set(GPU_PLUGIN_TRANSFORMATIONS_SOURCES
${CMAKE_CURRENT_LIST_DIR}/src/plugin/transformations/keep_xattention_threshold_precision.cpp
${CMAKE_CURRENT_LIST_DIR}/src/plugin/transformations/kv_cache_compression.cpp
${CMAKE_CURRENT_LIST_DIR}/src/plugin/transformations/kv_cache_fusion.cpp
+ ${CMAKE_CURRENT_LIST_DIR}/src/plugin/transformations/l2_norm_to_rms.cpp
${CMAKE_CURRENT_LIST_DIR}/src/plugin/transformations/lora_horizontal_fusion.cpp
${CMAKE_CURRENT_LIST_DIR}/src/plugin/transformations/lora_subgraph_horizontal_fusion.cpp
${CMAKE_CURRENT_LIST_DIR}/src/plugin/transformations/normalize_l2_decomposition.cpp
diff --git a/src/plugins/intel_gpu/src/plugin/transformations/l2_norm_to_rms.cpp b/src/plugins/intel_gpu/src/plugin/transformations/l2_norm_to_rms.cpp
new file mode 100644
index 00000000000..94cd9d6c7ea
--- /dev/null
+++ b/src/plugins/intel_gpu/src/plugin/transformations/l2_norm_to_rms.cpp
@@ -0,0 +1,114 @@
+// Copyright (C) 2018-2026 Intel Corporation
+// SPDX-License-Identifier: Apache-2.0
+//
+
+#include "l2_norm_to_rms.hpp"
+
+#include <cmath>
+
+#include "openvino/core/graph_util.hpp"
+#include "openvino/core/rt_info.hpp"
+#include "openvino/op/add.hpp"
+#include "openvino/op/constant.hpp"
+#include "openvino/op/convert.hpp"
+#include "openvino/op/divide.hpp"
+#include "openvino/op/multiply.hpp"
+#include "openvino/op/power.hpp"
+#include "openvino/op/reduce_sum.hpp"
+#include "openvino/op/sqrt.hpp"
+#include "openvino/pass/pattern/op/optional.hpp"
+#include "openvino/pass/pattern/op/wrap_type.hpp"
+#include "ov_ops/rms.hpp"
+#include "transformations/utils/utils.hpp"
+
+namespace ov::intel_gpu {
+
+L2NormToRMS::L2NormToRMS(size_t max_work_group_size) {
+ using namespace ov::pass::pattern;
+
+ auto x = any_input();
+ auto x_convert = optional<ov::op::v0::Convert>({x});
+ auto power = wrap_type<ov::op::v1::Power>({x_convert, wrap_type<ov::op::v0::Constant>(value_matches("2"))});
+ auto axes = wrap_type<ov::op::v0::Constant>();
+ auto sum = wrap_type<ov::op::v1::ReduceSum>({power, axes}, consumers_count(1));
+ auto eps = wrap_type<ov::op::v0::Constant>();
+ auto add_eps = wrap_type<ov::op::v1::Add>({sum, eps}, consumers_count(1));
+ auto sqrt = wrap_type<ov::op::v0::Sqrt>({add_eps}, consumers_count(1));
+ auto div = wrap_type<ov::op::v1::Divide>({x_convert, sqrt}, consumers_count(1));
+ auto gamma = any_input();
+ auto mul = wrap_type<ov::op::v1::Multiply>({div, gamma});
+
+ ov::matcher_pass_callback callback = [=](Matcher& m) {
+ const auto& pm = m.get_pattern_value_map();
+ auto sum_node = ov::as_type_ptr<ov::op::v1::ReduceSum>(pm.at(sum).get_node_shared_ptr());
+ if (!sum_node || !sum_node->get_keep_dims() || transformation_callback(sum_node)) {
+ return false;
+ }
+
+ // Only the last axis, and only a static one: N goes into the rewritten gamma and eps.
+ const auto& in_shape = sum_node->get_input_partial_shape(0);
+ if (in_shape.rank().is_dynamic() || in_shape[in_shape.size() - 1].is_dynamic()) {
+ return false;
+ }
+ const auto rank = static_cast<int64_t>(in_shape.size());
+ // The GPU RMS kernel has bfyx and bfzyx implementations only.
+ if (rank > 5) {
+ return false;
+ }
+ auto axes_values = ov::as_type_ptr<ov::op::v0::Constant>(pm.at(axes).get_node_shared_ptr())->cast_vector<int64_t>();
+ if (axes_values.size() != 1 || (axes_values[0] != -1 && axes_values[0] != rank - 1)) {
+ return false;
+ }
+ const auto n = static_cast<size_t>(in_shape[rank - 1].get_length());
+
+ // Same limit RMSFusion applies on GPU: the kernel handles a row with one work group.
+ const size_t vec_size = 8;
+ if (n / vec_size > max_work_group_size) {
+ return false;
+ }
+
+ // RMS scales along the normalized axis, so gamma must be {..., 1, n} with no more dims than x. A gamma
+ // with n elements along another axis, e.g. {n, 1}, broadcasts per row instead.
+ const auto& gamma_out = pm.at(gamma);
+ const auto& gamma_shape = gamma_out.get_partial_shape();
+ if (gamma_shape.is_dynamic()) {
+ return false;
+ }
+ const auto gamma_dims = gamma_shape.to_shape();
+ if (gamma_dims.empty() || gamma_dims.size() > static_cast<size_t>(rank) || gamma_dims.back() != n || ov::shape_size(gamma_dims) != n) {
+ return false;
+ }
+
+ float eps_value = 0.f;
+ if (!ov::op::util::get_single_value(ov::as_type_ptr<ov::op::v0::Constant>(pm.at(eps).get_node_shared_ptr()), eps_value)) {
+ return false;
+ }
+
+ const auto x_out = pm.at(x);
+ // Nodes are visited in topological order, so the match lands on the Multiply before its Convert is
+ // seen; take a lone trailing Convert in as well so RMS writes the converted type directly.
+ std::shared_ptr<ov::Node> root = pm.at(mul).get_node_shared_ptr();
+ const auto& mul_users = root->get_output_target_inputs(0);
+ if (mul_users.size() == 1) {
+ if (auto convert = ov::as_type_ptr<ov::op::v0::Convert>(mul_users.begin()->get_node()->shared_from_this())) {
+ root = convert;
+ }
+ }
+ const auto output_type = root->get_output_element_type(0);
+
+ // x / sqrt(sum + eps) * gamma == x / sqrt(mean + eps / n) * (gamma / sqrt(n))
+ auto inv_sqrt_n = ov::op::v0::Constant::create(gamma_out.get_element_type(), {}, {1.0 / std::sqrt(static_cast<double>(n))});
+ auto scaled_gamma = std::make_shared<ov::op::v1::Multiply>(gamma_out, inv_sqrt_n);
+ auto rms = std::make_shared<ov::op::internal::RMS>(x_out, scaled_gamma, eps_value / static_cast<float>(n), output_type);
+
+ rms->set_friendly_name(root->get_friendly_name());
+ ov::copy_runtime_info(m.get_matched_nodes(), {scaled_gamma, rms});
+ ov::replace_node(root, rms);
+ return true;
+ };
+
+ auto m = std::make_shared<Matcher>(mul, "L2NormToRMS");
+ register_matcher(m, callback);
+}
+
+} // namespace ov::intel_gpu
diff --git a/src/plugins/intel_gpu/src/plugin/transformations/l2_norm_to_rms.hpp b/src/plugins/intel_gpu/src/plugin/transformations/l2_norm_to_rms.hpp
new file mode 100644
index 00000000000..ffb4ba4fa76
--- /dev/null
+++ b/src/plugins/intel_gpu/src/plugin/transformations/l2_norm_to_rms.hpp
@@ -0,0 +1,24 @@
+// Copyright (C) 2018-2026 Intel Corporation
+// SPDX-License-Identifier: Apache-2.0
+//
+
+#pragma once
+
+#include "openvino/pass/graph_rewrite.hpp"
+
+namespace ov::intel_gpu {
+
+// An RMS norm written as an L2 normalization over the last axis, the form ONNX LpNormalization(p=2)
+// decomposes to:
+// x / Sqrt(ReduceSum(x^2) + eps) * gamma
+// Since ReduceSum = N * ReduceMean over N elements, this is exactly
+// RMS(x, gamma / sqrt(N), eps / N)
+// RMSFusion does not take it: it looks for ReduceMean and requires gamma to be a Constant, while here
+// gamma may be computed at run time (e.g. a dequantized weight fed as a model input).
+class L2NormToRMS : public ov::pass::MatcherPass {
+public:
+ OPENVINO_MATCHER_PASS_RTTI("L2NormToRMS");
+ explicit L2NormToRMS(size_t max_work_group_size);
+};
+
+} // namespace ov::intel_gpu
diff --git a/src/plugins/intel_gpu/src/plugin/transformations_pipeline.cpp b/src/plugins/intel_gpu/src/plugin/transformations_pipeline.cpp
index 19e61d4bf8f..d6acb543c20 100644
--- a/src/plugins/intel_gpu/src/plugin/transformations_pipeline.cpp
+++ b/src/plugins/intel_gpu/src/plugin/transformations_pipeline.cpp
@@ -144,6 +144,7 @@
#include "plugin/transformations/disable_fp16_comp_sin_gen.hpp"
#include "plugin/transformations/increase_rms_input_precision.hpp"
#include "plugin/transformations/force_fp32_selective.hpp"
+#include "plugin/transformations/l2_norm_to_rms.hpp"
#include "transformations/common_optimizations/activations_scaling.hpp"
#include "transformations/common_optimizations/broadcast_elementwise_fusion.hpp"
#include "transformations/common_optimizations/broadcast_transition.hpp"
@@ -1762,6 +1763,7 @@ void TransformationsPipeline::apply(std::shared_ptr<ov::Model> func) {
manager.set_per_pass_validation(false);
manager.register_pass<ov::pass::ConvertWeightCompressedConv1x1ToMatmul>();
+ manager.register_pass<ov::intel_gpu::L2NormToRMS>(device_info.max_work_group_size);
manager.register_pass<ov::intel_gpu::IncreaseRMSInputPrecision>();
manager.register_pass<ov::intel_gpu::ClampFP16Output>();
manager.register_pass<ov::intel_gpu::ConvertMatMulToFullyConnected>(device_info.supports_immad);
diff --git a/src/plugins/intel_gpu/tests/functional/sources.cmake b/src/plugins/intel_gpu/tests/functional/sources.cmake
index 865dcdb6132..6d369322265 100644
--- a/src/plugins/intel_gpu/tests/functional/sources.cmake
+++ b/src/plugins/intel_gpu/tests/functional/sources.cmake
@@ -353,6 +353,7 @@ set(GPU_FUNCTIONAL_TEST_SOURCES
${CMAKE_CURRENT_LIST_DIR}/subgraph_tests/dynamic/split_reshape_eltwise.cpp
${CMAKE_CURRENT_LIST_DIR}/subgraph_tests/dynamic/swiglu_fusion.cpp
${CMAKE_CURRENT_LIST_DIR}/subgraph_tests/dynamic/transpose_matmul_fusion.cpp
+ ${CMAKE_CURRENT_LIST_DIR}/subgraph_tests/l2_norm_to_rms.cpp
${CMAKE_CURRENT_LIST_DIR}/subgraph_tests/loop.cpp
${CMAKE_CURRENT_LIST_DIR}/subgraph_tests/matmul_sum_fusion.cpp
${CMAKE_CURRENT_LIST_DIR}/subgraph_tests/mvn_layernorm_byxf.cpp
diff --git a/src/plugins/intel_gpu/tests/functional/subgraph_tests/l2_norm_to_rms.cpp b/src/plugins/intel_gpu/tests/functional/subgraph_tests/l2_norm_to_rms.cpp
new file mode 100644
index 00000000000..f2d7d1db986
--- /dev/null
+++ b/src/plugins/intel_gpu/tests/functional/subgraph_tests/l2_norm_to_rms.cpp
@@ -0,0 +1,219 @@
+// Copyright (C) 2018-2026 Intel Corporation
+// SPDX-License-Identifier: Apache-2.0
+//
+
+#include "common_test_utils/ov_tensor_utils.hpp"
+#include "shared_test_classes/base/ov_subgraph.hpp"
+
+#include "openvino/op/parameter.hpp"
+#include "openvino/op/constant.hpp"
+#include "openvino/op/result.hpp"
+#include "openvino/op/add.hpp"
+#include "openvino/op/sqrt.hpp"
+#include "openvino/op/divide.hpp"
+#include "openvino/op/multiply.hpp"
+#include "openvino/op/power.hpp"
+#include "openvino/op/reduce_sum.hpp"
+
+#include <memory>
+#include <ostream>
+#include <sstream>
+#include <string>
+#include <tuple>
+#include <vector>
+
+namespace {
+using ov::test::InputShape;
+
+/*
+ * The L2-normalization form of RMS norm produced by ONNX LpNormalization(p=2) exports:
+ *
+ * Input(F32) Const(F32)
+ * \ /
+ * Power(F32) (x^2)
+ * | Const(I64 axes=[-1])
+ * | /
+ * ReduceSum(F32, keep_dims=true)
+ * | Const(F32 eps)
+ * | /
+ * Add(F32)
+ * |
+ * Sqrt(F32)
+ * | \
+ * Input(F32) -> Divide(F32)
+ * | \
+ * | Parameter gamma (F32)
+ * | /
+ * Multiply(F32)
+ *
+ * ov::intel_gpu::L2NormToRMS rewrites it into a single RMS op
+ * (RMS(x, gamma/sqrt(n), eps/n)). These tests exercise that rewrite end-to-end
+ * on GPU against the CPU reference.
+ */
+
+enum class L2NormCase {
+ // gamma is a proper last-axis scale: {N}
+ Plain,
+ // gamma product equals N but broadcasts along a non-last axis: {N,1}
+ GammaColumn,
+ // rank-6 activations, the rms primitive has no bfwzyx implementation
+ RankSix,
+};
+
+using L2NormToRMSParams = std::tuple<L2NormCase, // pattern variant
+ std::vector<InputShape>, // input shapes for {x, gamma}
+ ov::element::Type>; // input precision
+
+class L2NormToRMS : public testing::WithParamInterface<L2NormToRMSParams>,
+ virtual public ov::test::SubgraphBaseTest {
+public:
+ static std::string getTestCaseName(const testing::TestParamInfo<L2NormToRMSParams>& obj) {
+ const auto& [l2_case, input_shapes, input_precision] = obj.param;
+
+ std::ostringstream result;
+ switch (l2_case) {
+ case L2NormCase::Plain: result << "Plain_"; break;
+ case L2NormCase::GammaColumn: result << "GammaColumn_"; break;
+ case L2NormCase::RankSix: result << "RankSix_"; break;
+ }
+ result << "IS=(";
+ for (const auto& shape : input_shapes) {
+ result << ov::test::utils::partialShape2str({shape.first}) << "_";
+ }
+ result << ")_TS=";
+ for (const auto& shape : input_shapes) {
+ result << "(";
+ if (!shape.second.empty()) {
+ auto itr = shape.second.begin();
+ do {
+ result << ov::test::utils::vec2str(*itr);
+ } while (++itr != shape.second.end() && result << "_");
+ }
+ result << ")_";
+ }
+ result << "input_precision=" << input_precision;
+ return result.str();
+ }
+
+protected:
+ L2NormCase l2_case = L2NormCase::Plain;
+
+ void SetUp() override {
+ targetDevice = ov::test::utils::DEVICE_GPU;
+
+ const auto& [l2case, input_shapes, input_precision] = GetParam();
+ l2_case = l2case;
+
+ init_input_shapes(input_shapes);
+
+ inType = outType = input_precision;
+
+ // tolerances are chosen so that the f16-output rounding of the fused RMS
+ // (<= ~2e-4 here) stays green, while a broadcast-semantics mismatch (observed ~0.35) fails
+ abs_threshold = 5e-3;
+ rel_threshold = 1e-2;
+
+ function = init_subgraph(inputDynamicShapes, input_precision);
+ }
+
+ std::shared_ptr<ov::Model> init_subgraph(const std::vector<ov::PartialShape>& input_shapes,
+ const ov::element::Type& precision) {
+ auto x = std::make_shared<ov::op::v0::Parameter>(precision, input_shapes[0]);
+ auto gamma = std::make_shared<ov::op::v0::Parameter>(precision, input_shapes[1]);
+
+ // x^2
+ auto power_const = ov::op::v0::Constant::create(precision, {}, {2.f});
+ auto power = std::make_shared<ov::op::v1::Power>(x, power_const);
+
+ // ReduceSum(x^2, axes=[-1], keep_dims=true)
+ auto axes_const = ov::op::v0::Constant::create(ov::element::i64, ov::Shape{1}, {-1});
+ auto sum = std::make_shared<ov::op::v1::ReduceSum>(power, axes_const, true);
+
+ // Sqrt(ReduceSum + eps)
+ auto eps = ov::op::v0::Constant::create(precision, {}, {1e-6f});
+ auto add_eps = std::make_shared<ov::op::v1::Add>(sum, eps);
+ auto sqrt = std::make_shared<ov::op::v0::Sqrt>(add_eps);
+
+ // x / Sqrt(ReduceSum + eps) * gamma
+ auto div = std::make_shared<ov::op::v1::Divide>(x, sqrt);
+ auto mul = std::make_shared<ov::op::v1::Multiply>(div, gamma);
+
+ auto model = std::make_shared<ov::Model>(ov::OutputVector{mul}, ov::ParameterVector{x, gamma}, "L2NormToRMS");
+ model->get_parameters()[0]->set_friendly_name("x");
+ model->get_parameters()[1]->set_friendly_name("gamma");
+ return model;
+ }
+
+ void generate_inputs(const std::vector<ov::Shape>& targetInputStaticShapes) override {
+ inputs.clear();
+ const auto& funcInputs = function->inputs();
+
+ auto x_tensor = ov::test::utils::create_and_fill_tensor(funcInputs[0].get_element_type(), targetInputStaticShapes[0]);
+ inputs.insert({funcInputs[0].get_node_shared_ptr(), x_tensor});
+
+ // Distinct per-index gamma values: for GammaColumn the row- and column-wise
+ // broadcast interpretations cannot coincide (a uniform gamma would mask the bug).
+ auto gamma_tensor = ov::Tensor(funcInputs[1].get_element_type(), targetInputStaticShapes[1]);
+ const size_t count = gamma_tensor.get_size();
+ const auto fill = [&](auto* data_ptr) {
+ using T = std::decay_t<std::remove_pointer_t<decltype(data_ptr)>>;
+ for (size_t i = 0; i < count; ++i) {
+ data_ptr[i] = static_cast<T>(0.5f + 2.0f * static_cast<float>(i) / static_cast<float>(count));
+ }
+ };
+ if (gamma_tensor.get_element_type() == ov::element::f16) {
+ fill(gamma_tensor.data<ov::float16>());
+ } else {
+ fill(gamma_tensor.data<float>());
+ }
+ inputs.insert({funcInputs[1].get_node_shared_ptr(), gamma_tensor});
+ }
+};
+
+TEST_P(L2NormToRMS, Inference) {
+ run();
+}
+
+// Plain gamma {N} over {1,3,48}: the fused RMS must reproduce the decomposed form.
+// x: 48 last dim -> n/8 = 6 <= max work group size, gamma size 48 == n -> the pass is expected to fire.
+const std::vector<InputShape> input_shapes_plain = {
+ {{1, 3, 48}, {{1, 3, 48}}},
+ {{48}, {{48}}},
+};
+
+// gamma {48,1} over x {1,48,48}: same element count as the last dim, so the pass fires,
+// but the original Multiply broadcasts gamma along axis 1 (per-row scale), while RMS
+// consumes gamma as a flat vector along the normalized axis (per-column scale).
+const std::vector<InputShape> input_shapes_gamma_column = {
+ {{1, 48, 48}, {{1, 48, 48}}},
+ {{48, 1}, {{48, 1}}},
+};
+
+// Rank-6 activations: rms has no bfwzyx implementation; the fused graph must still
+// compile (either the pass declines the pattern or the plugin falls back), and must match CPU.
+const std::vector<InputShape> input_shapes_rank_six = {
+ {{1, 1, 1, 1, 4, 16}, {{1, 1, 1, 1, 4, 16}}},
+ {{16}, {{16}}},
+};
+
+INSTANTIATE_TEST_SUITE_P(smoke_L2NormToRMS_plain,
+ L2NormToRMS,
+ ::testing::Combine(::testing::Values(L2NormCase::Plain),
+ ::testing::Values(input_shapes_plain),
+ ::testing::Values(ov::element::f32)),
+ L2NormToRMS::getTestCaseName);
+
+INSTANTIATE_TEST_SUITE_P(smoke_L2NormToRMS_gamma_column,
+ L2NormToRMS,
+ ::testing::Combine(::testing::Values(L2NormCase::GammaColumn),
+ ::testing::Values(input_shapes_gamma_column),
+ ::testing::Values(ov::element::f32)),
+ L2NormToRMS::getTestCaseName);
+
+INSTANTIATE_TEST_SUITE_P(smoke_L2NormToRMS_rank_six,
+ L2NormToRMS,
+ ::testing::Combine(::testing::Values(L2NormCase::RankSix),
+ ::testing::Values(input_shapes_rank_six),
+ ::testing::Values(ov::element::f32)),
+ L2NormToRMS::getTestCaseName);
+} // namespace
diff --git a/src/plugins/intel_gpu/tests/unit/sources.cmake b/src/plugins/intel_gpu/tests/unit/sources.cmake
index 6eecb5fc468..188ccacc57e 100644
--- a/src/plugins/intel_gpu/tests/unit/sources.cmake
+++ b/src/plugins/intel_gpu/tests/unit/sources.cmake
@@ -348,6 +348,7 @@ set(GPU_UNIT_TESTS_SRCS
${CMAKE_CURRENT_LIST_DIR}/transformations/keep_xattention_threshold_precision_test.cpp
${CMAKE_CURRENT_LIST_DIR}/transformations/kv_cache_compression.cpp
${CMAKE_CURRENT_LIST_DIR}/transformations/kv_cache_fusion_test.cpp
+ ${CMAKE_CURRENT_LIST_DIR}/transformations/l2_norm_to_rms_test.cpp
${CMAKE_CURRENT_LIST_DIR}/transformations/lora_horizontal_fusion.cpp
${CMAKE_CURRENT_LIST_DIR}/transformations/move_fc_reshape_to_weights.cpp
${CMAKE_CURRENT_LIST_DIR}/transformations/optimize_subsequent_reshapes_test.cpp
@@ -460,6 +461,8 @@ set(GPU_UNIT_TESTS_TRANSFORMATIONS_SRCS
${CMAKE_HOME_DIRECTORY}/src/plugins/intel_gpu/src/plugin/transformations/kv_cache_compression.hpp
${CMAKE_HOME_DIRECTORY}/src/plugins/intel_gpu/src/plugin/transformations/kv_cache_fusion.cpp
${CMAKE_HOME_DIRECTORY}/src/plugins/intel_gpu/src/plugin/transformations/kv_cache_fusion.hpp
+ ${CMAKE_HOME_DIRECTORY}/src/plugins/intel_gpu/src/plugin/transformations/l2_norm_to_rms.cpp
+ ${CMAKE_HOME_DIRECTORY}/src/plugins/intel_gpu/src/plugin/transformations/l2_norm_to_rms.hpp
${CMAKE_HOME_DIRECTORY}/src/plugins/intel_gpu/src/plugin/transformations/lora_horizontal_fusion.cpp
${CMAKE_HOME_DIRECTORY}/src/plugins/intel_gpu/src/plugin/transformations/lora_horizontal_fusion.hpp
${CMAKE_HOME_DIRECTORY}/src/plugins/intel_gpu/src/plugin/transformations/lora_subgraph_horizontal_fusion.cpp
diff --git a/src/plugins/intel_gpu/tests/unit/transformations/l2_norm_to_rms_test.cpp b/src/plugins/intel_gpu/tests/unit/transformations/l2_norm_to_rms_test.cpp
new file mode 100644
index 00000000000..979e2df2dc6
--- /dev/null
+++ b/src/plugins/intel_gpu/tests/unit/transformations/l2_norm_to_rms_test.cpp
@@ -0,0 +1,160 @@
+// Copyright (C) 2018-2026 Intel Corporation
+// SPDX-License-Identifier: Apache-2.0
+//
+
+#include "plugin/transformations/l2_norm_to_rms.hpp"
+
+#include <gtest/gtest.h>
+
+#include <cmath>
+#include <memory>
+
+#include "common_test_utils/ov_test_utils.hpp"
+#include "openvino/core/model.hpp"
+#include "openvino/op/add.hpp"
+#include "openvino/op/constant.hpp"
+#include "openvino/op/convert.hpp"
+#include "openvino/op/divide.hpp"
+#include "openvino/op/multiply.hpp"
+#include "openvino/op/parameter.hpp"
+#include "openvino/op/power.hpp"
+#include "openvino/op/reduce_sum.hpp"
+#include "openvino/op/result.hpp"
+#include "openvino/op/sqrt.hpp"
+#include "ov_ops/rms.hpp"
+
+using namespace testing;
+using namespace ov::intel_gpu;
+
+namespace {
+
+constexpr size_t hidden = 64;
+constexpr float eps = 1e-6f;
+
+// x / sqrt(ReduceSum(x^2, axis) + eps) * gamma, as an ONNX LpNormalization(p=2) followed by a scale exports it.
+std::shared_ptr<ov::Node> l2_norm(const ov::Output<ov::Node>& x, const ov::Output<ov::Node>& gamma, int64_t axis = -1, bool keep_dims = true) {
+ auto power = std::make_shared<ov::op::v1::Power>(x, ov::op::v0::Constant::create(x.get_element_type(), {}, {2.f}));
+ auto axes = ov::op::v0::Constant::create(ov::element::i64, {1}, {axis});
+ auto sum = std::make_shared<ov::op::v1::ReduceSum>(power, axes, keep_dims);
+ auto add = std::make_shared<ov::op::v1::Add>(sum, ov::op::v0::Constant::create(x.get_element_type(), {}, {eps}));
+ auto sqrt = std::make_shared<ov::op::v0::Sqrt>(add);
+ auto div = std::make_shared<ov::op::v1::Divide>(x, sqrt);
+ return std::make_shared<ov::op::v1::Multiply>(div, gamma);
+}
+
+std::shared_ptr<ov::Node> rms(const ov::Output<ov::Node>& x, const ov::Output<ov::Node>& gamma, ov::element::Type out_type) {
+ auto inv_sqrt_n = ov::op::v0::Constant::create(gamma.get_element_type(), {}, {1.0 / std::sqrt(static_cast<double>(hidden))});
+ auto scaled_gamma = std::make_shared<ov::op::v1::Multiply>(gamma, inv_sqrt_n);
+ return std::make_shared<ov::op::internal::RMS>(x, scaled_gamma, eps / static_cast<float>(hidden), out_type);
+}
+
+} // namespace
+
+TEST_F(TransformationTestsF, L2NormToRMS) {
+ {
+ auto x = std::make_shared<ov::op::v0::Parameter>(ov::element::f32, ov::PartialShape{1, -1, hidden});
+ auto gamma = std::make_shared<ov::op::v0::Parameter>(ov::element::f32, ov::Shape{hidden});
+ auto norm = l2_norm(x, gamma);
+ model = std::make_shared<ov::Model>(ov::OutputVector{norm}, ov::ParameterVector{x, gamma});
+ manager.register_pass<L2NormToRMS>(1024);
+ }
+ {
+ auto x = std::make_shared<ov::op::v0::Parameter>(ov::element::f32, ov::PartialShape{1, -1, hidden});
+ auto gamma = std::make_shared<ov::op::v0::Parameter>(ov::element::f32, ov::Shape{hidden});
+ model_ref = std::make_shared<ov::Model>(ov::OutputVector{rms(x, gamma, ov::element::f32)}, ov::ParameterVector{x, gamma});
+ }
+ comparator.enable(FunctionsComparator::CmpValues::CONST_VALUES);
+ comparator.enable(FunctionsComparator::CmpValues::ATTRIBUTES);
+}
+
+// f16 activations normalized in f32 and converted back: RMS takes the f16 input and writes f16 directly.
+TEST_F(TransformationTestsF, L2NormToRMSWithConverts) {
+ {
+ auto x = std::make_shared<ov::op::v0::Parameter>(ov::element::f16, ov::PartialShape{1, -1, hidden});
+ auto gamma = std::make_shared<ov::op::v0::Parameter>(ov::element::f32, ov::Shape{hidden});
+ auto x_f32 = std::make_shared<ov::op::v0::Convert>(x, ov::element::f32);
+ auto norm = l2_norm(x_f32, gamma);
+ auto out = std::make_shared<ov::op::v0::Convert>(norm, ov::element::f16);
+ model = std::make_shared<ov::Model>(ov::OutputVector{out}, ov::ParameterVector{x, gamma});
+ manager.register_pass<L2NormToRMS>(1024);
+ }
+ {
+ auto x = std::make_shared<ov::op::v0::Parameter>(ov::element::f16, ov::PartialShape{1, -1, hidden});
+ auto gamma = std::make_shared<ov::op::v0::Parameter>(ov::element::f32, ov::Shape{hidden});
+ model_ref = std::make_shared<ov::Model>(ov::OutputVector{rms(x, gamma, ov::element::f16)}, ov::ParameterVector{x, gamma});
+ }
+ comparator.enable(FunctionsComparator::CmpValues::CONST_VALUES);
+ comparator.enable(FunctionsComparator::CmpValues::ATTRIBUTES);
+}
+
+// Not normalized over the last axis: left alone.
+TEST_F(TransformationTestsF, L2NormToRMSNotLastAxis) {
+ auto x = std::make_shared<ov::op::v0::Parameter>(ov::element::f32, ov::PartialShape{1, hidden, hidden});
+ auto gamma = std::make_shared<ov::op::v0::Parameter>(ov::element::f32, ov::Shape{hidden, 1});
+ auto norm = l2_norm(x, gamma, 1);
+ model = std::make_shared<ov::Model>(ov::OutputVector{norm}, ov::ParameterVector{x, gamma});
+ manager.register_pass<L2NormToRMS>(1024);
+}
+
+// Without keep_dims the reduced tensor does not broadcast against x the way RMS needs: left alone.
+TEST_F(TransformationTestsF, L2NormToRMSNoKeepDims) {
+ auto x = std::make_shared<ov::op::v0::Parameter>(ov::element::f32, ov::PartialShape{hidden});
+ auto gamma = std::make_shared<ov::op::v0::Parameter>(ov::element::f32, ov::Shape{hidden});
+ auto norm = l2_norm(x, gamma, -1, false);
+ model = std::make_shared<ov::Model>(ov::OutputVector{norm}, ov::ParameterVector{x, gamma});
+ manager.register_pass<L2NormToRMS>(1024);
+}
+
+// A row too long for one work group of the RMS kernel (hidden / 8 > max work group size): left alone.
+TEST_F(TransformationTestsF, L2NormToRMSRowTooLong) {
+ auto x = std::make_shared<ov::op::v0::Parameter>(ov::element::f32, ov::PartialShape{1, -1, hidden});
+ auto gamma = std::make_shared<ov::op::v0::Parameter>(ov::element::f32, ov::Shape{hidden});
+ auto norm = l2_norm(x, gamma);
+ model = std::make_shared<ov::Model>(ov::OutputVector{norm}, ov::ParameterVector{x, gamma});
+ manager.register_pass<L2NormToRMS>(4);
+}
+
+// gamma {1, 1, n} still scales the normalized axis only: fused.
+TEST_F(TransformationTestsF, L2NormToRMSGammaWithLeadingOnes) {
+ {
+ auto x = std::make_shared<ov::op::v0::Parameter>(ov::element::f32, ov::PartialShape{1, -1, hidden});
+ auto gamma = std::make_shared<ov::op::v0::Parameter>(ov::element::f32, ov::Shape{1, 1, hidden});
+ auto norm = l2_norm(x, gamma);
+ model = std::make_shared<ov::Model>(ov::OutputVector{norm}, ov::ParameterVector{x, gamma});
+ manager.register_pass<L2NormToRMS>(1024);
+ }
+ {
+ auto x = std::make_shared<ov::op::v0::Parameter>(ov::element::f32, ov::PartialShape{1, -1, hidden});
+ auto gamma = std::make_shared<ov::op::v0::Parameter>(ov::element::f32, ov::Shape{1, 1, hidden});
+ model_ref = std::make_shared<ov::Model>(ov::OutputVector{rms(x, gamma, ov::element::f32)}, ov::ParameterVector{x, gamma});
+ }
+ comparator.enable(FunctionsComparator::CmpValues::CONST_VALUES);
+ comparator.enable(FunctionsComparator::CmpValues::ATTRIBUTES);
+}
+
+// gamma {n, 1} has n elements but scales each row, not the normalized axis: left alone.
+TEST_F(TransformationTestsF, L2NormToRMSGammaColumn) {
+ auto x = std::make_shared<ov::op::v0::Parameter>(ov::element::f32, ov::PartialShape{1, hidden, hidden});
+ auto gamma = std::make_shared<ov::op::v0::Parameter>(ov::element::f32, ov::Shape{hidden, 1});
+ auto norm = l2_norm(x, gamma);
+ model = std::make_shared<ov::Model>(ov::OutputVector{norm}, ov::ParameterVector{x, gamma});
+ manager.register_pass<L2NormToRMS>(1024);
+}
+
+// gamma with more dims than x would change the output rank: left alone.
+TEST_F(TransformationTestsF, L2NormToRMSGammaHigherRank) {
+ auto x = std::make_shared<ov::op::v0::Parameter>(ov::element::f32, ov::PartialShape{1, -1, hidden});
+ auto gamma = std::make_shared<ov::op::v0::Parameter>(ov::element::f32, ov::Shape{1, 1, 1, hidden});
+ auto norm = l2_norm(x, gamma);
+ model = std::make_shared<ov::Model>(ov::OutputVector{norm}, ov::ParameterVector{x, gamma});
+ manager.register_pass<L2NormToRMS>(1024);
+}
+
+// Rank 6 has no RMS implementation on GPU: left alone.
+TEST_F(TransformationTestsF, L2NormToRMSRankSix) {
+ auto x = std::make_shared<ov::op::v0::Parameter>(ov::element::f32, ov::PartialShape{1, 1, 1, 1, 4, hidden});
+ auto gamma = std::make_shared<ov::op::v0::Parameter>(ov::element::f32, ov::Shape{hidden});
+ auto norm = l2_norm(x, gamma);
+ model = std::make_shared<ov::Model>(ov::OutputVector{norm}, ov::ParameterVector{x, gamma});
+ manager.register_pass<L2NormToRMS>(1024);
+}