Skip to content

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

[GPU] Fix fused eltwise rank reduction (#36889)

Wilson Seok2c9f4f168b45
diff --git a/src/plugins/intel_gpu/src/graph/impls/ocl/kernel_selector_helper.h b/src/plugins/intel_gpu/src/graph/impls/ocl/kernel_selector_helper.h
index bc3ed67e8be..cdabdaef4e8 100644
--- a/src/plugins/intel_gpu/src/graph/impls/ocl/kernel_selector_helper.h
+++ b/src/plugins/intel_gpu/src/graph/impls/ocl/kernel_selector_helper.h
@@ -17,12 +17,18 @@
#include "intel_gpu/primitives/reorder.hpp"
#include "intel_gpu/primitives/primitive.hpp"
+#include "intel_gpu/runtime/layout.hpp"
+
+#include "openvino/core/shape.hpp"
+#include "openvino/core/shape_util.hpp"
+
#include "kernel_selector_params.h"
#include "weight_bias_params.h"
#include "kernel_selector_common.h"
#include "tensor_type.h"
#include <cstdint>
+#include <optional>
#include <string>
#include <vector>
#include <memory>
@@ -262,6 +268,66 @@ inline bool broadcastable(const ov::PartialShape& first_pshape, const ov::Partia
return true;
}
+// Computes a lower-rank representation of a fused eltwise peer when collapsing its leading spatial
+// axes is an order-preserving reshape and the result broadcasts directly to the host layout.
+// E.g. peer [1,2,8,6,10] (bfzyx) folds to [1,2,48,10] (bfyx) for host [1,2,48,10]: axes 2 and 3 (8,6)
+// collapse into 48, which then matches the host shape exactly.
+inline std::optional<ov::PartialShape> fold_higher_rank_fused_peer(const layout& peer_layout, const layout& host_layout) {
+ const auto& peer_shape = peer_layout.get_partial_shape();
+ const auto& host_shape = host_layout.get_partial_shape();
+
+ const size_t peer_rank = peer_shape.size();
+ const size_t host_rank = host_shape.size();
+ if (peer_rank <= host_rank || host_rank < 3)
+ return std::nullopt;
+ if (peer_shape.is_dynamic() || host_shape.is_dynamic())
+ return std::nullopt;
+ if (peer_layout.data_padding || host_layout.data_padding)
+ return std::nullopt;
+
+ const auto& peer_format = peer_layout.format;
+ const auto& host_format = host_layout.format;
+ if (!format::is_default_format(peer_format) || !format::is_default_format(host_format))
+ return std::nullopt;
+ // A default format adjusted to another rank is always that rank's default format.
+ OPENVINO_ASSERT(format::adjust_to_rank(peer_format, host_rank) == host_format,
+ "Default format rank adjustment must match the host's default format");
+
+ const auto peer_dims = peer_shape.to_shape();
+ const auto host_dims = host_shape.to_shape();
+ const size_t fold_count = peer_rank - host_rank + 1;
+ ov::Shape folded_dims;
+ folded_dims.reserve(host_rank);
+ folded_dims.push_back(peer_dims[0]);
+ folded_dims.push_back(peer_dims[1]);
+
+ size_t grouped = 1;
+ for (size_t i = 2; i < 2 + fold_count; ++i) {
+ const auto grouped_size = ov::util::shape_size_safe({grouped, peer_dims[i]});
+ if (!grouped_size.has_value())
+ return std::nullopt;
+ grouped = grouped_size.value();
+ }
+ folded_dims.push_back(grouped);
+ folded_dims.insert(folded_dims.end(), peer_dims.begin() + 2 + fold_count, peer_dims.end());
+
+ const auto peer_total = ov::util::shape_size_safe(peer_dims);
+ const auto folded_total = ov::util::shape_size_safe(folded_dims);
+ if (!peer_total.has_value() || !folded_total.has_value())
+ return std::nullopt;
+ // Folding only regroups existing dims, so the element count is preserved whenever both totals fit.
+ OPENVINO_ASSERT(peer_total.value() == folded_total.value(), "Peer folding must preserve the total element count");
+ if (folded_dims.size() != host_dims.size())
+ return std::nullopt;
+
+ for (size_t i = 0; i < folded_dims.size(); ++i) {
+ if (folded_dims[i] != 1 && folded_dims[i] != host_dims[i])
+ return std::nullopt;
+ }
+
+ return ov::PartialShape(folded_dims);
+}
+
inline kernel_impl_params canonicalize_fused_shapes(const kernel_impl_params& impl_params) {
auto updated_impl_params = impl_params;
bool use_new_shape_infer = impl_params.prog->is_new_shape_infer();
@@ -269,12 +335,25 @@ inline kernel_impl_params canonicalize_fused_shapes(const kernel_impl_params& im
for (auto& fd : updated_impl_params.fused_desc) {
if (fd.is_type<eltwise>() && fd.total_num_deps == 2 && fd.has_outer_dep()) {
if (updated_impl_params.input_layouts.size() > size_t(fd.outer_dep_start_idx)) {
- const auto& out_pshape = updated_impl_params.output_layouts[0].get_partial_shape();
+ const auto& out_layout = updated_impl_params.output_layouts[0];
+ const auto& out_pshape = out_layout.get_partial_shape();
auto& dep_layout = updated_impl_params.input_layouts[fd.outer_dep_start_idx];
const auto& dep_shape = dep_layout.get_partial_shape();
- if (!broadcastable(dep_shape, out_pshape, use_new_shape_infer)) {
+ if (dep_shape.size() > out_pshape.size()) {
+ // Always fold higher-rank peers, regardless of broadcastable(): in legacy shape-infer mode
+ // broadcastable() only compares the first out_pshape.size() axes, so a peer whose leading
+ // axes are all 1 can be misreported as compatible while its rank still mismatches the host's
+ // iteration space, causing the fused-op kernel to index the peer incorrectly.
+ auto folded = fold_higher_rank_fused_peer(dep_layout, out_layout);
+ // can_fuse_reorder_to_prev() must have already declined fusion for any non-foldable peer.
+ OPENVINO_ASSERT(folded.has_value(),
+ "Unfoldable higher-rank fused eltwise peer reached canonicalization; "
+ "can_fuse_reorder_to_prev guard was expected to prevent this.");
+ dep_layout.set_partial_shape(*folded);
+ dep_layout.format = format::adjust_to_rank(dep_layout.format, out_pshape.size());
+ } else if (!broadcastable(dep_shape, out_pshape, use_new_shape_infer)) {
dep_layout.set_partial_shape(extend_shape_to_rank_from_begin(dep_shape, out_pshape.size()));
}
}
diff --git a/src/plugins/intel_gpu/src/graph/layout_optimizer.cpp b/src/plugins/intel_gpu/src/graph/layout_optimizer.cpp
index 888361270cf..a381d5bc745 100644
--- a/src/plugins/intel_gpu/src/graph/layout_optimizer.cpp
+++ b/src/plugins/intel_gpu/src/graph/layout_optimizer.cpp
@@ -47,6 +47,7 @@
#include "lstm_seq_inst.h"
#include "group_normalization_inst.h"
#include "to_string_utils.h"
+#include "impls/ocl/kernel_selector_helper.h"
#include <vector>
#include <memory>
#include <utility>
@@ -69,6 +70,47 @@ static size_t get_post_ops_count(const program_node& node) {
return onednn_post_ops_count;
}
+// A rank-reducing reorder may be fused into a producer only when every higher-rank external eltwise
+// peer has the same provable lower-rank representation that OCL fused-op canonicalization will use.
+//
+// Example graph this guards against: a Permute produces [1,2,8,6,10] (bfzyx) and has an Add fused into
+// it as a post-op, whose second input ("peer") is an independent branch also shaped [1,2,8,6,10]. A
+// downstream Reshape only needs [1,2,48,10] (bfyx), so the layout optimizer wants to fuse a rank-reducing
+// Reorder into the Permute, making its *own* output layout 4D. The peer is a separate node reached only
+// through this fused primitive and its own shape inference is untouched, so it stays 5D: the fused-op
+// kernel would then read a 5D buffer using 4D indexing and produce wrong results. Folding the peer's
+// shape to [1,2,48,10] (see fold_higher_rank_fused_peer) keeps the fusion; when no such fold exists (e.g.
+// the peer broadcasts over an inner spatial axis, like [1,2,8,1,10]) the reorder fusion is declined here
+// and the Permute keeps its native 5D output instead.
+static bool fused_peers_can_fold_to_layout(const program_node& prev, const layout& reduced_layout) {
+ if (!prev.has_fused_primitives())
+ return true;
+
+ const size_t reduced_rank = reduced_layout.get_rank();
+ if (prev.get_output_layout().get_rank() <= reduced_rank)
+ return true;
+
+ for (const auto& fd : prev.get_fused_primitives()) {
+ if (!fd.is_type<eltwise>() || !fd.has_outer_dep())
+ continue;
+
+ const auto outer_idx = static_cast<size_t>(fd.outer_dep_start_idx);
+ const size_t outer_count = fd.deps.size();
+ if (outer_idx >= prev.get_dependencies().size() || outer_count == 0 || outer_count > prev.get_dependencies().size() - outer_idx) {
+ return false;
+ }
+
+ for (size_t i = 0; i < outer_count; ++i) {
+ const auto peer_layout = prev.get_dependency(outer_idx + i).get_output_layout();
+ if (peer_layout.get_rank() > reduced_rank && !fold_higher_rank_fused_peer(peer_layout, reduced_layout).has_value()) {
+ return false;
+ }
+ }
+ }
+
+ return true;
+}
+
std::pair<std::shared_ptr<reorder>, bool> reorder_factory::get_reorder(primitive_id src_id,
int32_t src_port,
const layout& in_layout,
@@ -379,6 +421,14 @@ bool layout_optimizer::can_fuse_reorder(program_node& prev, program_node& next,
bool layout_optimizer::can_fuse_reorder_to_prev(program_node& prev, reorder_node& node, format fmt_prev, format fmt_next) {
bool allow_new_shape_infer = node.get_program().is_new_shape_infer();
+
+ // Do not fuse a rank-reducing reorder into a producer whose fused higher-rank
+ // eltwise peer cannot be indexed correctly at the reduced rank (inner-spatial
+ // broadcast over the collapsed axes). Keeping the producer at its higher rank
+ // keeps the fused peer rank-consistent so the fused-op kernel reads it right.
+ if (!node.get_output_layout().is_dynamic() && !fused_peers_can_fold_to_layout(prev, node.get_output_layout())) {
+ return false;
+ }
// Because kernels can work cross-layout, if reorder only performs type conversion,
// fusing reorder to the previous node can be done even if it is a dynamic shape case
if ((format::is_simple_data_format(fmt_prev) && format::is_simple_data_format(fmt_next)) &&
@@ -386,8 +436,7 @@ bool layout_optimizer::can_fuse_reorder_to_prev(program_node& prev, reorder_node
// We can void only that case if we can check whether the current node is backedge of the network.
// However no such handle is existing yet. (To be done in the future when we need to optimize out the type converting
// reorders in the body network)
- !node.get_program().is_body_program() && !prev.is_in_shape_of_subgraph() &&
- prev.get_preferred_impl_type() != cldnn::impl_types::cpu) {
+ !node.get_program().is_body_program() && !prev.is_in_shape_of_subgraph() && prev.get_preferred_impl_type() != cldnn::impl_types::cpu) {
// case for truncate mode
if ((prev.is_type<mvn>() || prev.is_type<concatenation>() || prev.is_type<gather>() || prev.is_type<broadcast>() ||
prev.is_type<select>() || prev.is_type<eltwise>() || prev.is_type<rms>()) &&
diff --git a/src/plugins/intel_gpu/tests/unit/fusions/permute_fusion_test.cpp b/src/plugins/intel_gpu/tests/unit/fusions/permute_fusion_test.cpp
index a483401a0a6..291de881d8a 100644
--- a/src/plugins/intel_gpu/tests/unit/fusions/permute_fusion_test.cpp
+++ b/src/plugins/intel_gpu/tests/unit/fusions/permute_fusion_test.cpp
@@ -11,7 +11,22 @@
#include <intel_gpu/primitives/data.hpp>
#include <intel_gpu/primitives/permute.hpp>
+#include <algorithm>
#include <cmath>
+#include <cstdlib>
+#include <string>
+#include <utility>
+#include <vector>
+
+#include <openvino/runtime/core.hpp>
+#include <openvino/core/model.hpp>
+#include <openvino/runtime/exec_model_info.hpp>
+#include "openvino/op/parameter.hpp"
+#include "openvino/op/constant.hpp"
+#include "openvino/op/matmul.hpp"
+#include "openvino/op/transpose.hpp"
+#include "openvino/op/reshape.hpp"
+#include "openvino/op/add.hpp"
using namespace cldnn;
using namespace ::tests;
@@ -858,3 +873,443 @@ INSTANTIATE_TEST_SUITE_P(fusings_gpu, permute_eltwise_reorder, ::testing::Values
permute_reorder_params{ CASE_PERMUTE_REORDER_TILED_BF16_11, 3, 5 },
permute_reorder_params{ CASE_PERMUTE_REORDER_TILED_BF16_12, 3, 5 },
}));
+
+// -----------------------------------------------------------------------------
+// Regression coverage for fold_higher_rank_fused_peer() (kernel_selector_helper.h):
+// Permute [1,2,8,6,10] bfzyx -> layout optimizer flattens to [1,2,48,10] bfyx for a
+// downstream Reshape -> Add fused in, peer stays 5D -> kernel misreads it (MSE ~12-20 vs CPU).
+// Uses the real GPU compile/layout/fusion pipeline; GPU output is compared against CPU.
+// Requires building and installing the GPU plugin.
+
+namespace {
+// can_fuse_reorder_to_prev -> fused_peers_can_fold_to_layout -> fold_higher_rank_fused_peer only
+// depends on shape/format/padding, not values, so any fixed-seed weights work. Shared by all models
+// in this file (5D and 6D); sized for the largest consumer, smaller ones slice a prefix.
+const std::vector<float> kFusedPeerFoldWeights1 = [] {
+ tests::random_generator rg;
+ rg.set_seed("fused_peer_fold_weights_1");
+ return rg.generate_random_1d<float>(96, -2, 2);
+}();
+
+const std::vector<float> kFusedPeerFoldWeights2 = [] {
+ tests::random_generator rg;
+ rg.set_seed("fused_peer_fold_weights_2");
+ return rg.generate_random_1d<float>(96, -2, 2);
+}();
+
+// Compiles the given model on device, runs one inference with (in1, in2), and returns the f16 output
+// flattened to float alongside the compiled model.
+std::pair<std::vector<float>, ov::CompiledModel> compile_and_infer(ov::Core& core,
+ const std::string& device,
+ const ov::AnyMap& cfg,
+ const std::shared_ptr<ov::Model>& model,
+ const ov::Tensor& in1,
+ const ov::Tensor& in2) {
+ auto compiled = core.compile_model(model, device, cfg);
+ auto req = compiled.create_infer_request();
+ req.set_input_tensor(0, in1);
+ req.set_input_tensor(1, in2);
+ req.infer();
+ auto out = req.get_output_tensor(0);
+ std::vector<float> vals(out.get_size());
+ const auto* p = out.data<ov::float16>();
+ for (size_t i = 0; i < out.get_size(); ++i)
+ vals[i] = static_cast<float>(p[i]);
+ return std::make_pair(vals, compiled);
+}
+
+// Scans a compiled model's runtime graph for the (at most one) node whose ORIGINAL_NAMES rt-info
+// contains every string in must_contain and none of must_not_contain. Used by every test below to
+// check whether the fused Add is present and at what rank/impl it executed.
+struct node_probe {
+ bool found = false;
+ int64_t rank = -1;
+ std::string impl_type;
+};
+
+node_probe probe_node(const std::shared_ptr<const ov::Model>& rt,
+ const std::vector<std::string>& must_contain,
+ const std::vector<std::string>& must_not_contain = {}) {
+ node_probe result;
+ for (const auto& node : rt->get_ordered_ops()) {
+ const auto& info = node->get_rt_info();
+ auto it = info.find(ov::exec_model_info::ORIGINAL_NAMES);
+ if (it == info.end())
+ continue;
+ const auto orig = it->second.as<std::string>();
+ const bool contains_all = std::all_of(must_contain.begin(), must_contain.end(), [&](const std::string& s) {
+ return orig.find(s) != std::string::npos;
+ });
+ if (!contains_all)
+ continue;
+ const bool excludes_all =
+ std::none_of(must_not_contain.begin(), must_not_contain.end(), [&](const std::string& s) {
+ return orig.find(s) != std::string::npos;
+ });
+ if (!excludes_all)
+ continue;
+ result.found = true;
+ result.rank = node->get_output_partial_shape(0).rank().get_length();
+ if (auto impl_it = info.find(ov::exec_model_info::IMPL_TYPE); impl_it != info.end())
+ result.impl_type = impl_it->second.as<std::string>();
+ }
+ return result;
+}
+
+double fused_peer_fold_mse(const std::vector<float>& a, const std::vector<float>& b, double& max_ae) {
+ double se = 0.0;
+ max_ae = 0.0;
+ for (size_t i = 0; i < a.size(); ++i) {
+ double d = static_cast<double>(a[i]) - static_cast<double>(b[i]);
+ se += d * d;
+ max_ae = std::max(max_ae, std::abs(d));
+ }
+ return se / static_cast<double>(a.size());
+}
+
+// GPU_ALLOW_NEW_SHAPE_INFER is a RELEASE_INTERNAL option (options.inl), so ov::Core rejects it when
+// passed through the public compile_model() config -- it can only be set via its OV_GPU_ env var.
+// Sets the variable for the lifetime of the guard and restores the previous state on destruction.
+class scoped_env_var {
+public:
+ scoped_env_var(std::string name, const std::string& value) : m_name(std::move(name)) {
+ if (const char* prev = std::getenv(m_name.c_str())) {
+ m_had_prev = true;
+ m_prev = prev;
+ }
+ set(value);
+ }
+
+ ~scoped_env_var() {
+ if (m_had_prev)
+ set(m_prev);
+ else
+ unset();
+ }
+
+ scoped_env_var(const scoped_env_var&) = delete;
+ scoped_env_var& operator=(const scoped_env_var&) = delete;
+
+private:
+ void set(const std::string& value) {
+#ifdef _WIN32
+ _putenv_s(m_name.c_str(), value.c_str());
+#else
+ ::setenv(m_name.c_str(), value.c_str(), 1);
+#endif
+ }
+
+ void unset() {
+#ifdef _WIN32
+ _putenv_s(m_name.c_str(), "");
+#else
+ ::unsetenv(m_name.c_str());
+#endif
+ }
+
+ std::string m_name;
+ std::string m_prev;
+ bool m_had_prev = false;
+};
+
+bool discover_gpu_and_cpu(ov::Core& core) {
+ std::vector<std::string> devices;
+ try {
+ devices = core.get_available_devices();
+ } catch (...) {}
+ const bool has_gpu = std::any_of(devices.begin(), devices.end(),
+ [](const std::string& d) { return d.rfind("GPU", 0) == 0; });
+ const bool has_cpu = std::any_of(devices.begin(), devices.end(),
+ [](const std::string& d) { return d == "CPU"; });
+ return has_gpu && has_cpu;
+}
+
+// Host [1,2,8,6,10] bfzyx -> flattened to [1,2,48,10] bfyx (z=8,y=6 -> 48). Peer [1,pf,pz,py,px] stays
+// 5D unless fold_higher_rank_fused_peer() can fold it to the host shape; otherwise rank is preserved.
+struct collapse_mask_case {
+ int64_t pf, pz, py, px;
+ bool expect_rank_preserved;
+ const char* label;
+};
+
+// Builds host [1,2,8,6,10] + peer [1,pf,pz,py,px], Add (numpy broadcast), Reshape to 4D.
+std::shared_ptr<ov::Model> build_collapse_mask_model(const collapse_mask_case& c) {
+ using namespace ov;
+ auto make_branch = [](const std::shared_ptr<op::v0::Parameter>& param, int64_t f, int64_t z, int64_t y, int64_t x, const std::vector<float>& w) {
+ // pre-transpose logical [1,f,y,x,K] -> matmul(K,z) -> [1,f,y,x,z] -> transpose[0,1,4,2,3]
+ const int64_t K = 12;
+ auto to5d = op::v0::Constant::create(element::i64, Shape{5}, std::vector<int64_t>{1, f, y, x, K});
+ auto reshape5d = std::make_shared<op::v1::Reshape>(param, to5d, false);
+ std::vector<ov::float16> wz(static_cast<size_t>(K * z));
+ for (size_t i = 0; i < wz.size(); ++i)
+ wz[i] = static_cast<ov::float16>(w[i % w.size()]);
+ auto weights = std::make_shared<op::v0::Constant>(element::f16, Shape{static_cast<size_t>(K), static_cast<size_t>(z)}, wz);
+ auto matmul = std::make_shared<op::v0::MatMul>(reshape5d, weights, false, false);
+ auto order = op::v0::Constant::create(element::i64, Shape{5}, {0, 1, 4, 2, 3});
+ return std::make_shared<op::v1::Transpose>(matmul, order); // [1,f,z,y,x]
+ };
+
+ auto in1 = std::make_shared<op::v0::Parameter>(element::f16, PartialShape{1, 2, 60, 12});
+ auto in2 = std::make_shared<op::v0::Parameter>(element::f16, PartialShape{1, c.pf, c.py * c.px, 12});
+ in1->set_friendly_name("input1");
+ in2->set_friendly_name("input2");
+
+ auto t1 = make_branch(in1, 2, 8, 6, 10, kFusedPeerFoldWeights1); // host [1,2,8,6,10]
+ t1->set_friendly_name("Transpose_target");
+ auto t2 = make_branch(in2, c.pf, c.pz, c.py, c.px, kFusedPeerFoldWeights2); // peer [1,pf,pz,py,px]
+ t2->set_friendly_name("Transpose_peer");
+
+ auto add = std::make_shared<op::v1::Add>(t1, t2);
+ add->set_friendly_name("Add_target");
+
+ auto to4d = op::v0::Constant::create(element::i64, Shape{4}, {2, 8, 6, 10});
+ auto reshape4d = std::make_shared<op::v1::Reshape>(add, to4d, false);
+ reshape4d->set_friendly_name("Reshape_to4D");
+
+ auto result = std::make_shared<op::v0::Result>(reshape4d);
+ return std::make_shared<ov::Model>(ResultVector{result}, ParameterVector{in1, in2}, "collapse_mask");
+}
+
+std::pair<std::vector<float>, ov::CompiledModel> run_collapse_mask(ov::Core& core,
+ const std::string& device,
+ const ov::AnyMap& cfg,
+ const collapse_mask_case& c,
+ const ov::Tensor& in1,
+ const ov::Tensor& in2) {
+ return compile_and_infer(core, device, cfg, build_collapse_mask_model(c), in1, in2);
+}
+
+void fill_collapse_mask_inputs(const collapse_mask_case& c, ov::Tensor& in1, ov::Tensor& in2) {
+ tests::random_generator rg;
+ rg.set_seed(GET_SUITE_NAME);
+ auto rnd1 = rg.generate_random_1d<ov::float16>(in1.get_size(), -2, 2);
+ std::copy(rnd1.begin(), rnd1.end(), in1.data<ov::float16>());
+ auto rnd2 = rg.generate_random_1d<ov::float16>(in2.get_size(), -2, 2);
+ std::copy(rnd2.begin(), rnd2.end(), in2.data<ov::float16>());
+}
+
+class permute_fused_collapse_broadcast_matrix : public ::testing::TestWithParam<collapse_mask_case> {};
+
+} // namespace
+
+TEST_P(permute_fused_collapse_broadcast_matrix, compiles_finite_and_matches_cpu) {
+ const auto c = GetParam();
+ ov::Core core;
+ if (!discover_gpu_and_cpu(core)) {
+ GTEST_SKIP() << "Requires both GPU and CPU plugins discoverable via ov::Core.";
+ }
+
+ ov::Tensor in1(ov::element::f16, ov::Shape{1, 2, 60, 12});
+ ov::Tensor in2(ov::element::f16, ov::Shape{1, static_cast<size_t>(c.pf), static_cast<size_t>(c.py * c.px), 12});
+ fill_collapse_mask_inputs(c, in1, in2);
+
+ auto [cpu_vals, cpu_compiled] = run_collapse_mask(core, "CPU", {}, c, in1, in2);
+
+ std::vector<float> gpu_vals;
+ ov::CompiledModel gpu_compiled;
+ ASSERT_NO_THROW({
+ auto res = run_collapse_mask(core, "GPU", {}, c, in1, in2);
+ gpu_vals = res.first;
+ gpu_compiled = res.second;
+ }) << "Default GPU compilation must not fail for mask "
+ << c.label;
+
+ // Assert the intended runtime state: Add fused into Transpose_target, and the host permute rank
+ // matches the fix's decision (5D preserved for the inner-spatial masks, 4D flattened otherwise).
+ // Also require permute_ref (the fused-eltwise-rank-mismatch defect only manifests via that impl) and,
+ // when the host is expected to flatten to 4D, that the peer itself is still seen at its native 5D --
+ // confirming the rank-mismatch condition under test is actually present rather than avoided upstream.
+ auto rt = gpu_compiled.get_runtime_model();
+ auto target = probe_node(rt, {"Transpose_target", "Add_target"});
+ ASSERT_TRUE(target.found) << "Add_target not fused into Transpose_target for mask " << c.label;
+ EXPECT_TRUE(target.impl_type.find("permute_ref") != std::string::npos)
+ << "Target permute did not select permute_ref for mask " << c.label;
+ if (c.expect_rank_preserved) {
+ EXPECT_EQ(target.rank, 5) << "Inner-spatial mask " << c.label << " must keep the fused permute host at 5D (rank preserved).";
+ } else {
+ EXPECT_EQ(target.rank, 4) << "Representable mask " << c.label << " should keep the flattened 4D fused host.";
+ auto peer = probe_node(rt, {"Transpose_peer"}, {"Add_target"});
+ EXPECT_EQ(peer.rank, 5) << "Fused peer dependency was not 5D for mask " << c.label << "; rank-mismatch condition absent.";
+ }
+
+ ASSERT_EQ(gpu_vals.size(), cpu_vals.size());
+ for (float v : gpu_vals)
+ ASSERT_TRUE(std::isfinite(v)) << "Non-finite GPU output for mask " << c.label;
+ double max_ae = 0.0;
+ double mse = fused_peer_fold_mse(gpu_vals, cpu_vals, max_ae);
+ EXPECT_LT(mse, 1e-2) << "GPU vs CPU mismatch for mask " << c.label << " MSE=" << mse << " MaxAbsErr=" << max_ae;
+ // FP16 tolerance: correct path agrees with CPU to ~1e-3 MSE; the original defect produced MSE ~12-20.
+}
+
+// peer f,z,y,x extents (1 = broadcast), host [1,2,8,6,10]:
+// equal_total [2,8,6,10] -> folds (original defect shape)
+// feature_broadcast [1,8,6,10] -> folds (NumPy broadcast, not equal-total)
+// inner_y_broadcast [2,8,1,10] -> rank preserved
+// inner_y_and_x_broadcast [2,8,1,1] -> rank preserved
+INSTANTIATE_TEST_SUITE_P(collapse_broadcast_matrix,
+ permute_fused_collapse_broadcast_matrix,
+ ::testing::Values(
+ // host [1,2,8,6,10]; peer f,z,y,x extents (1 == broadcast).
+ collapse_mask_case{2, 8, 6, 10, false, "equal_total"},
+ collapse_mask_case{1, 8, 6, 10, false, "feature_broadcast"},
+ collapse_mask_case{2, 8, 1, 10, true, "inner_y_broadcast"},
+ collapse_mask_case{2, 8, 1, 1, true, "inner_y_and_x_broadcast"}),
+ [](const ::testing::TestParamInfo<collapse_mask_case>& info) {
+ return std::string(info.param.label);
+ });
+
+// New shape-infer: host stays 5D bfzyx -> peer and host are already rank-consistent. Must remain
+// correct independent of the flattening path exercised above.
+TEST(permute_fused_eltwise_rank_mismatch, new_shape_infer_5d_peer_and_5d_host) {
+ ov::Core core;
+ if (!discover_gpu_and_cpu(core)) {
+ GTEST_SKIP() << "Requires both GPU and CPU plugins discoverable via ov::Core.";
+ }
+
+ const collapse_mask_case c{2, 8, 6, 10, false, "equal_total"};
+ ov::Tensor in1(ov::element::f16, ov::Shape{1, 2, 60, 12});
+ ov::Tensor in2(ov::element::f16, ov::Shape{1, 2, 60, 12});
+ fill_collapse_mask_inputs(c, in1, in2);
+
+ auto [cpu_vals, cpu_compiled] = run_collapse_mask(core, "CPU", {}, c, in1, in2);
+
+ std::vector<float> gpu_vals;
+ ov::CompiledModel gpu_compiled;
+ {
+ // New shape-infer is RELEASE_INTERNAL: only settable via env var, not the public config.
+ scoped_env_var new_shape_infer_env("OV_GPU_ALLOW_NEW_SHAPE_INFER", "1");
+ ov::Core new_shape_infer_core;
+ auto res = run_collapse_mask(new_shape_infer_core, "GPU", {}, c, in1, in2);
+ gpu_vals = res.first;
+ gpu_compiled = res.second;
+ }
+
+ // Fused target permute output stays 5D (rank-consistent with the peer).
+ auto rt = gpu_compiled.get_runtime_model();
+ auto target = probe_node(rt, {"Transpose_target", "Add_target"});
+ ASSERT_TRUE(target.found) << "Add_target was not fused into Transpose_target under new shape-infer.";
+ ASSERT_EQ(target.rank, 5) << "Under new shape-infer the fused permute host output should remain 5D.";
+
+ ASSERT_EQ(gpu_vals.size(), cpu_vals.size());
+ double max_ae = 0.0;
+ double mse = fused_peer_fold_mse(gpu_vals, cpu_vals, max_ae);
+ EXPECT_LT(mse, 1e-2) << "GPU (new shape-infer) fused-permute output diverges from CPU reference. "
+ "MSE=" << mse << " MaxAbsErr=" << max_ae;
+}
+
+// -----------------------------------------------------------------------------
+// 6D-to-4D matrix: same as the 5D matrix above, but folds three spatial axes into
+// one (fold_count=2) instead of one. Two cases suffice: one folds, one preserves
+// rank. Decision logic itself is unit-tested in canonicalize_fused_shapes_test.cpp.
+namespace {
+
+struct collapse6d_case {
+ int64_t pf, px, pw, pz, py; // peer extents on x,w,z,y (1 => broadcast); host [1,2,2,4,3,5]
+ bool expect_rank_preserved;
+ const char* label;
+};
+
+std::shared_ptr<ov::Model> build_collapse6d_model(const collapse6d_case& c) {
+ using namespace ov;
+ const int64_t X = 2, K = 12;
+ auto make_branch =
+ [&](const std::shared_ptr<op::v0::Parameter>& param, int64_t f, int64_t x, int64_t w, int64_t z, int64_t y, const std::vector<float>& wsrc) {
+ // pre [1,f,w,z,y,K] -> matmul(K,x) -> [1,f,w,z,y,x] -> transpose[0,1,5,2,3,4] -> [1,f,x,w,z,y]
+ auto to6d = op::v0::Constant::create(element::i64, Shape{6}, std::vector<int64_t>{1, f, w, z, y, K});
+ auto reshape6d = std::make_shared<op::v1::Reshape>(param, to6d, false);
+ std::vector<ov::float16> wx(static_cast<size_t>(K * x));
+ for (size_t i = 0; i < wx.size(); ++i)
+ wx[i] = static_cast<ov::float16>(wsrc[i % wsrc.size()]);
+ auto weights = std::make_shared<op::v0::Constant>(element::f16, Shape{static_cast<size_t>(K), static_cast<size_t>(x)}, wx);
+ auto matmul = std::make_shared<op::v0::MatMul>(reshape6d, weights, false, false);
+ auto order = op::v0::Constant::create(element::i64, Shape{6}, {0, 1, 5, 2, 3, 4});
+ return std::make_shared<op::v1::Transpose>(matmul, order); // [1,f,x,w,z,y]
+ };
+
+ auto in1 = std::make_shared<op::v0::Parameter>(element::f16, PartialShape{1, 2, 4 * 3 * 5, K});
+ auto in2 = std::make_shared<op::v0::Parameter>(element::f16, PartialShape{1, c.pf, c.pw * c.pz * c.py, K});
+ in1->set_friendly_name("input1");
+ in2->set_friendly_name("input2");
+
+ auto t1 = make_branch(in1, 2, X, 4, 3, 5, kFusedPeerFoldWeights1); // host [1,2,X,4,3,5]
+ t1->set_friendly_name("Transpose_target");
+ auto t2 = make_branch(in2, c.pf, c.px, c.pw, c.pz, c.py, kFusedPeerFoldWeights2);
+ t2->set_friendly_name("Transpose_peer");
+
+ auto add = std::make_shared<op::v1::Add>(t1, t2);
+ add->set_friendly_name("Add_target");
+
+ // Flatten to 4D [2, X, W, Z*Y].
+ auto to4d = op::v0::Constant::create(element::i64, Shape{4}, std::vector<int64_t>{2, X, 4, 15});
+ auto reshape4d = std::make_shared<op::v1::Reshape>(add, to4d, false);
+ reshape4d->set_friendly_name("Reshape_to4D");
+
+ auto result = std::make_shared<op::v0::Result>(reshape4d);
+ return std::make_shared<ov::Model>(ResultVector{result}, ParameterVector{in1, in2}, "collapse6d");
+}
+
+std::pair<std::vector<float>, ov::CompiledModel> run_collapse6d(ov::Core& core,
+ const std::string& device,
+ const collapse6d_case& c,
+ const ov::Tensor& in1,
+ const ov::Tensor& in2) {
+ return compile_and_infer(core, device, {}, build_collapse6d_model(c), in1, in2);
+}
+
+class permute_fused_collapse6d_matrix : public ::testing::TestWithParam<collapse6d_case> {};
+
+} // namespace
+
+TEST_P(permute_fused_collapse6d_matrix, compiles_finite_and_matches_cpu) {
+ const auto c = GetParam();
+ ov::Core core;
+ if (!discover_gpu_and_cpu(core)) {
+ GTEST_SKIP() << "Requires both GPU and CPU plugins discoverable via ov::Core.";
+ }
+
+ tests::random_generator rg;
+ rg.set_seed(GET_SUITE_NAME);
+ ov::Tensor in1(ov::element::f16, ov::Shape{1, 2, 4 * 3 * 5, 12});
+ ov::Tensor in2(ov::element::f16, ov::Shape{1, static_cast<size_t>(c.pf), static_cast<size_t>(c.pw * c.pz * c.py), 12});
+ auto rnd1 = rg.generate_random_1d<ov::float16>(in1.get_size(), -2, 2);
+ std::copy(rnd1.begin(), rnd1.end(), in1.data<ov::float16>());
+ auto rnd2 = rg.generate_random_1d<ov::float16>(in2.get_size(), -2, 2);
+ std::copy(rnd2.begin(), rnd2.end(), in2.data<ov::float16>());
+
+ auto [cpu_vals, cpu_compiled] = run_collapse6d(core, "CPU", c, in1, in2);
+
+ std::vector<float> gpu_vals;
+ ov::CompiledModel gpu_compiled;
+ ASSERT_NO_THROW({
+ auto res = run_collapse6d(core, "GPU", c, in1, in2);
+ gpu_vals = res.first;
+ gpu_compiled = res.second;
+ }) << "Default GPU compilation must not fail for 6D mask "
+ << c.label;
+
+ auto rt = gpu_compiled.get_runtime_model();
+ auto target = probe_node(rt, {"Transpose_target", "Add_target"});
+ ASSERT_TRUE(target.found) << "Add_target not fused into Transpose_target for 6D mask " << c.label;
+ if (c.expect_rank_preserved) {
+ EXPECT_EQ(target.rank, 6) << "Inner-spatial 6D mask " << c.label << " must preserve 6D host rank.";
+ } else {
+ EXPECT_EQ(target.rank, 4) << "Representable 6D mask " << c.label << " should keep the 4D host.";
+ }
+
+ ASSERT_EQ(gpu_vals.size(), cpu_vals.size());
+ for (float v : gpu_vals)
+ ASSERT_TRUE(std::isfinite(v)) << "Non-finite GPU output for 6D mask " << c.label;
+ double max_ae = 0.0;
+ double mse = fused_peer_fold_mse(gpu_vals, cpu_vals, max_ae);
+ EXPECT_LT(mse, 1e-2) << "GPU vs CPU mismatch for 6D mask " << c.label << " MSE=" << mse << " MaxAbsErr=" << max_ae;
+}
+
+INSTANTIATE_TEST_SUITE_P(collapse6d_matrix,
+ permute_fused_collapse6d_matrix,
+ ::testing::Values(
+ // host [1,2,2,4,3,5]; peer f,x,w,z,y (1 = broadcast):
+ collapse6d_case{2, 2, 4, 3, 5, false, "equal_total_6d"}, // folds
+ collapse6d_case{2, 2, 4, 1, 5, true, "z_broadcast_6d"}), // preserved
+ [](const ::testing::TestParamInfo<collapse6d_case>& info) {
+ return std::string(info.param.label);
+ });
diff --git a/src/plugins/intel_gpu/tests/unit/module_tests/canonicalize_fused_shapes_test.cpp b/src/plugins/intel_gpu/tests/unit/module_tests/canonicalize_fused_shapes_test.cpp
new file mode 100644
index 00000000000..5d45cd552a4
--- /dev/null
+++ b/src/plugins/intel_gpu/tests/unit/module_tests/canonicalize_fused_shapes_test.cpp
@@ -0,0 +1,149 @@
+// Copyright (C) 2018-2026 Intel Corporation
+// SPDX-License-Identifier: Apache-2.0
+//
+
+#include <limits>
+
+#include "impls/ocl/kernel_selector_helper.h"
+#include "intel_gpu/runtime/layout.hpp"
+#include "test_utils.h"
+
+using namespace cldnn;
+using namespace ::tests;
+
+// Unit coverage for fold_higher_rank_fused_peer() (kernel_selector_helper.h):
+// higher-rank peer -> fold to host rank -> ov::PartialShape on success, std::nullopt otherwise
+// (falls back to the existing rank-extension path in canonicalize_fused_shapes()). Covers: valid
+// equal-total fold, valid broadcast fold, rejected unsafe/unprovable shapes, and overflow protection.
+
+namespace {
+
+layout make_layout(const ov::PartialShape& shape, format fmt, const padding& pad = padding()) {
+ return layout(shape, data_types::f16, fmt, pad);
+}
+
+} // namespace
+
+// A 5D bfzyx peer folds onto a 4D bfyx host of equal element count; the folded shape equals the host
+// shape exactly (equal-total reshape).
+TEST(canonicalize_fused_peer_fold, planar_5d_peer_equal_total_folds_to_host) {
+ auto peer = make_layout({1, 2, 8, 6, 10}, format::bfzyx); // 960 elements
+ auto host = make_layout({1, 2, 48, 10}, format::bfyx); // 960 elements (48 = 8 * 6)
+ auto folded = fold_higher_rank_fused_peer(peer, host);
+ ASSERT_TRUE(folded.has_value());
+ EXPECT_EQ(folded->to_shape(), (ov::Shape{1, 2, 48, 10}));
+
+ // Larger dims fold the same way.
+ auto peer_large = make_layout({1, 2, 96, 270, 270}, format::bfzyx);
+ auto host_large = make_layout({1, 2, 25920, 270}, format::bfyx); // 25920 = 96 * 270
+ auto folded_large = fold_higher_rank_fused_peer(peer_large, host_large);
+ ASSERT_TRUE(folded_large.has_value());
+ EXPECT_EQ(folded_large->to_shape(), (ov::Shape{1, 2, 25920, 270}));
+}
+
+// A 6D peer folding onto a 4D host (still contiguous planar, equal total) is valid; the outermost three
+// spatial axes (w,z,y) fold into the host's single first spatial axis.
+TEST(canonicalize_fused_peer_fold, planar_6d_peer_equal_total_folds_to_host) {
+ auto peer = make_layout({1, 2, 3, 4, 5, 6}, format::bfwzyx); // 720 elements
+ auto host = make_layout({1, 2, 60, 6}, format::bfyx); // 720 elements (60 = 3 * 4 * 5)
+ auto folded = fold_higher_rank_fused_peer(peer, host);
+ ASSERT_TRUE(folded.has_value());
+ EXPECT_EQ(folded->to_shape(), (ov::Shape{1, 2, 60, 6}));
+}
+
+// Peer [1,1,8,6,10] (480 elem) -> folds to [1,1,48,10], broadcast-compatible with host [1,2,48,10]
+// (960 elem) -- not equal to the host shape, unlike the equal-total case above.
+TEST(canonicalize_fused_peer_fold, planar_5d_broadcast_peer_folds_to_broadcast_shape) {
+ auto peer = make_layout({1, 1, 8, 6, 10}, format::bfzyx); // 480 elements
+ auto host = make_layout({1, 2, 48, 10}, format::bfyx); // 960 elements
+ auto folded = fold_higher_rank_fused_peer(peer, host);
+ ASSERT_TRUE(folded.has_value());
+ EXPECT_EQ(folded->to_shape(), (ov::Shape{1, 1, 48, 10}));
+}
+
+// A peer of the SAME rank as the host is not a higher-rank case; the existing extend path owns it.
+TEST(canonicalize_fused_peer_fold, equal_rank_rejected) {
+ auto peer = make_layout({1, 2, 48, 10}, format::bfyx);
+ auto host = make_layout({1, 2, 48, 10}, format::bfyx);
+ ASSERT_FALSE(fold_higher_rank_fused_peer(peer, host).has_value());
+}
+
+// A peer of LOWER rank than the host must not fold (right-aligned extension owns it).
+TEST(canonicalize_fused_peer_fold, lower_rank_rejected) {
+ auto peer = make_layout({48, 10}, format::bfyx);
+ auto host = make_layout({1, 2, 48, 10}, format::bfyx);
+ ASSERT_FALSE(fold_higher_rank_fused_peer(peer, host).has_value());
+}
+
+// Higher rank, unequal total, and NOT a legal broadcast (folded first spatial 48 != host 48 is fine but
+// the folded feature dim 2 vs host 3 differs and is not 1): must be rejected.
+TEST(canonicalize_fused_peer_fold, higher_rank_incompatible_broadcast_rejected) {
+ auto peer = make_layout({1, 2, 8, 6, 10}, format::bfzyx); // folds to [1,2,48,10]
+ auto host = make_layout({1, 3, 48, 10}, format::bfyx); // feature 2 vs 3, neither is 1
+ ASSERT_FALSE(fold_higher_rank_fused_peer(peer, host).has_value());
+}
+
+// Higher rank whose folded first spatial axis mismatches the host and is not 1: rejected.
+TEST(canonicalize_fused_peer_fold, higher_rank_spatial_mismatch_rejected) {
+ auto peer = make_layout({1, 2, 8, 6, 10}, format::bfzyx); // folds to [1,2,48,10]
+ auto host = make_layout({1, 2, 50, 10}, format::bfyx); // 48 vs 50, neither is 1
+ ASSERT_FALSE(fold_higher_rank_fused_peer(peer, host).has_value());
+}
+
+// Padding on either layout makes the physical layout non-contiguous, so folding is unsafe.
+TEST(canonicalize_fused_peer_fold, padded_peer_rejected) {
+ auto peer = make_layout({1, 2, 8, 6, 10}, format::bfzyx, padding({0, 0, 0, 1, 0}, {0, 0, 0, 1, 0}));
+ auto host = make_layout({1, 2, 48, 10}, format::bfyx);
+ ASSERT_FALSE(fold_higher_rank_fused_peer(peer, host).has_value());
+}
+
+TEST(canonicalize_fused_peer_fold, padded_host_rejected) {
+ auto peer = make_layout({1, 2, 8, 6, 10}, format::bfzyx);
+ auto host = make_layout({1, 2, 48, 10}, format::bfyx, padding({0, 0, 1, 0}, {0, 0, 1, 0}));
+ ASSERT_FALSE(fold_higher_rank_fused_peer(peer, host).has_value());
+}
+
+// A blocked peer format is not a plain row-major layout, so regrouping axes would change offsets.
+TEST(canonicalize_fused_peer_fold, blocked_peer_rejected) {
+ auto peer = make_layout({1, 32, 8, 6, 10}, format::b_fs_zyx_fsv16);
+ auto host = make_layout({1, 32, 48, 10}, format::bfyx);
+ ASSERT_FALSE(fold_higher_rank_fused_peer(peer, host).has_value());
+}
+
+// A blocked host format is likewise rejected.
+TEST(canonicalize_fused_peer_fold, blocked_host_rejected) {
+ auto peer = make_layout({1, 32, 8, 6, 10}, format::bfzyx);
+ auto host = make_layout({1, 32, 48, 10}, format::b_fs_yx_fsv16);
+ ASSERT_FALSE(fold_higher_rank_fused_peer(peer, host).has_value());
+}
+
+// A higher-rank peer whose host is a non-default planar format (byxf) does not describe the same
+// physical order after adjust_to_rank, so the fold is rejected.
+TEST(canonicalize_fused_peer_fold, non_default_host_rejected) {
+ auto peer = make_layout({1, 2, 8, 6, 10}, format::bfzyx); // 5D default
+ auto host = make_layout({1, 2, 48, 10}, format::byxf); // 4D non-default, equal total
+ ASSERT_FALSE(fold_higher_rank_fused_peer(peer, host).has_value());
+}
+
+// Dynamic shapes cannot be proven equal-total and must be rejected.
+TEST(canonicalize_fused_peer_fold, dynamic_peer_rejected) {
+ auto peer = make_layout(ov::PartialShape{1, 2, 8, 6, ov::Dimension::dynamic()}, format::bfzyx);
+ auto host = make_layout({1, 2, 48, 10}, format::bfyx);
+ ASSERT_FALSE(fold_higher_rank_fused_peer(peer, host).has_value());
+}
+
+// A host rank below 3 (no batch+feature+spatial to fold into) is rejected.
+TEST(canonicalize_fused_peer_fold, host_rank_below_three_rejected) {
+ auto peer = make_layout({2, 8, 6}, format::bfyx);
+ auto host = make_layout({16, 6}, format::bfyx);
+ ASSERT_FALSE(fold_higher_rank_fused_peer(peer, host).has_value());
+}
+
+// Overflow guard: folded spatial product (big^3) overflows size_t, so the fold must be rejected
+// rather than compared on a wrapped value.
+TEST(canonicalize_fused_peer_fold, overflow_rejected) {
+ const int64_t big = static_cast<int64_t>(3037000500LL); // big*big*big overflows size_t
+ auto peer = make_layout({1, 1, big, big, big}, format::bfzyx);
+ auto host = make_layout({1, 1, big, big}, format::bfyx);
+ ASSERT_FALSE(fold_higher_rank_fused_peer(peer, host).has_value());
+}