Skip to content

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

[NPUW]: Fix RopeCache pattern to match pre-broadcast inv_freq constants (#38821)

intelgaoxiong71de56165425
diff --git a/src/plugins/intel_npu/src/plugin/npuw/partitioning/patterns/pre_compute.cpp b/src/plugins/intel_npu/src/plugin/npuw/partitioning/patterns/pre_compute.cpp
index 6e7f533d643..dc8b061bf07 100644
--- a/src/plugins/intel_npu/src/plugin/npuw/partitioning/patterns/pre_compute.cpp
+++ b/src/plugins/intel_npu/src/plugin/npuw/partitioning/patterns/pre_compute.cpp
@@ -4,6 +4,8 @@
#include "pre_compute.hpp"
+#include <algorithm>
+
#include "../../logging.hpp"
#include "../../orc.hpp"
#include "openvino/op/ops.hpp"
@@ -143,13 +145,43 @@ void replaceSinCosByCache(int max_prompt_len, const ov::OutputVector& cache, con
ov::replace_node(rpe->matched_cos, squeeze_cos);
ov::replace_node(rpe->matched_sin, squeeze_sin);
- // disconnecting gather from rest or subgraph started from concat_1
- auto gather_input_to_concat = rpe->matched_concat->input(0);
- gather_input_to_concat.get_source_output().remove_target_input(gather_input_to_concat);
+ // disconnecting gather from rest or subgraph started from concat_1 - only present when the
+ // Broadcast node (and its ShapeOf->Gather->Concat shape-compute chain) actually matched.
+ if (rpe->matched_concat) {
+ auto gather_input_to_concat = rpe->matched_concat->input(0);
+ gather_input_to_concat.get_source_output().remove_target_input(gather_input_to_concat);
+ }
}
} // namespace
+bool ov::npuw::patterns::pre_compute::RopePatternLLama2::is_valid_match(
+ const std::shared_ptr<ov::Node>& sin_input) const {
+ // When the Broadcast was bypassed (optional `broadcast` matched directly on inv_freq),
+ // matched_inv_freq is used as-is with no reshaping, so any extra non-singleton dim (e.g. a
+ // real batch dim) would be silently flattened into the frequency axis by makeCosSinCache,
+ // corrupting the LUT's shape. Only a singleton-batch direct constant is supported there.
+ if (!matched_concat) {
+ const auto& inv_freq_shape = matched_inv_freq->get_shape();
+ const auto non_unit_dims = std::count_if(inv_freq_shape.begin(), inv_freq_shape.end(), [](size_t dim) {
+ return dim != 1;
+ });
+ if (non_unit_dims > 1) {
+ return false;
+ }
+ }
+
+ // concat_2 matches any Concat following Transpose (2nd input unconstrained), but only
+ // torch.cat([freqs, freqs], dim=-1) - both inputs being the exact same tensor - actually
+ // duplicates the frequencies. Anything else (e.g. padding with zeros for partial-rotary
+ // models) must not be treated as duplication, or the cached LUT's second half would be wrong.
+ if (duplicate_freqs && sin_input->input_value(0) != sin_input->input_value(1)) {
+ return false;
+ }
+
+ return true;
+}
+
ov::npuw::patterns::pre_compute::RopePatternLLama2::RopePatternLLama2() : matcher("sin-cos-matcher") {
auto shape_of = opp::wrap_type<ov::op::v3::ShapeOf>({opp::any_input()});
auto gather = opp::wrap_type<ov::op::v8::Gather>({shape_of, opp::any_input(), opp::any_input()});
@@ -157,7 +189,12 @@ ov::npuw::patterns::pre_compute::RopePatternLLama2::RopePatternLLama2() : matche
// here we can seen inverse frequencies as a parameter or constant depending on partitioner passes
auto inv_freq = opp::wrap_type<ov::op::v0::Constant>();
auto inv_freq_convert = opp::optional<ov::op::v0::Convert>({inv_freq->output(0)});
- auto broadcast = opp::wrap_type<ov::op::v3::Broadcast>({inv_freq_convert, concat_1});
+ // Normally inv_freq is dynamically broadcast to the position_ids-derived shape via a
+ // ShapeOf->Gather->Concat->Broadcast chain. Some models (e.g. Qwen3) export this already
+ // folded into a plain (already-broadcast-shaped) Constant/Convert with no live Broadcast op -
+ // make the Broadcast optional so the matcher still finds the pattern in that case (falls
+ // back to matching inv_freq_convert's output directly, see Optional's "match by 1st input").
+ auto broadcast = opp::optional<ov::op::v3::Broadcast>({inv_freq_convert, concat_1});
auto position_ids = opp::wrap_type<ov::op::v0::Parameter>();
auto unsqueeze = opp::wrap_type<ov::op::v0::Unsqueeze>({position_ids, opp::wrap_type<ov::op::v0::Constant>()});
auto convert = opp::wrap_type<ov::op::v0::Convert>({unsqueeze});
@@ -171,9 +208,12 @@ ov::npuw::patterns::pre_compute::RopePatternLLama2::RopePatternLLama2() : matche
bind_match = [=](const auto& map_sin, const auto& map_cos) {
this->matched_position_ids = map_sin.at(position_ids).get_node_shared_ptr();
- this->matched_concat = map_sin.at(concat_1).get_node_shared_ptr();
+ // concat_1 only participates in the match when the Broadcast node is actually present -
+ // when it was folded away (see comment above `broadcast`), concat_1 is left unmatched.
+ if (const auto it = map_sin.find(concat_1); it != map_sin.end()) {
+ this->matched_concat = it->second.get_node_shared_ptr();
+ }
this->matched_inv_freq = map_sin.at(inv_freq).get_node_shared_ptr();
-
this->matched_cos = map_cos.at(output_cos).get_node_shared_ptr();
this->matched_sin = map_sin.at(output_sin).get_node_shared_ptr();
@@ -182,6 +222,14 @@ ov::npuw::patterns::pre_compute::RopePatternLLama2::RopePatternLLama2() : matche
auto sin_input = this->matched_sin->input_value(0).get_node_shared_ptr();
this->duplicate_freqs = ov::is_type<ov::op::v0::Concat>(sin_input);
+ // The optional nodes above (`broadcast`, `concat_2`) make the pattern match graph shapes
+ // it can't actually handle correctly; reject those rather than silently miscomputing the
+ // LUT. is_valid_match() below holds both checks together to keep the vetoes in one place.
+ if (!is_valid_match(sin_input)) {
+ this->accept_match = false;
+ return;
+ }
+
LOG_VERB("Rope found : sin=" << matched_sin->get_name() << ", cos=" << matched_cos->get_name()
<< " (duplicate_freqs=" << duplicate_freqs << ")");
};
diff --git a/src/plugins/intel_npu/src/plugin/npuw/partitioning/patterns/pre_compute.hpp b/src/plugins/intel_npu/src/plugin/npuw/partitioning/patterns/pre_compute.hpp
index c616cbbfe4b..771351bf56a 100644
--- a/src/plugins/intel_npu/src/plugin/npuw/partitioning/patterns/pre_compute.hpp
+++ b/src/plugins/intel_npu/src/plugin/npuw/partitioning/patterns/pre_compute.hpp
@@ -33,6 +33,10 @@ public:
std::shared_ptr<ov::Node> matched_cos;
std::shared_ptr<ov::Node> matched_concat;
bool duplicate_freqs = false;
+ // bind_match can set this to false to veto a structurally-matched but semantically
+ // invalid subgraph (e.g. a non-duplicating Concat) - MultiMatcher::Callback
+ // returns void, so this is the only way to stop transform_cb from running.
+ bool accept_match = true;
std::function<void()> transform_cb;
@@ -55,8 +59,11 @@ public:
if (it == cos_by_shared_input.end()) {
continue; // no matching Cos for this Sin - leave it untouched
}
+ accept_match = true;
bind_match(sin_match, *it->second);
- transform_cb();
+ if (accept_match) {
+ transform_cb();
+ }
}
};
}
@@ -88,6 +95,11 @@ public:
class RopePatternLLama2 : public RopePatternDesc {
ov::pass::MultiMatcher matcher;
+ // Rejects matches that structurally fit the pattern but whose optional nodes (`broadcast`,
+ // `concat_2`) carry a shape/semantics the rest of the pass can't handle correctly - see
+ // RopePatternLLama2() for the specific cases. `sin_input` is matched_sin's direct input.
+ bool is_valid_match(const std::shared_ptr<ov::Node>& sin_input) const;
+
public:
using RopePatternDesc::transform_cb;
RopePatternLLama2();
diff --git a/src/plugins/intel_npu/tests/unit/npuw/pre_compute_test.cpp b/src/plugins/intel_npu/tests/unit/npuw/pre_compute_test.cpp
index 0a841903678..18bc475a755 100644
--- a/src/plugins/intel_npu/tests/unit/npuw/pre_compute_test.cpp
+++ b/src/plugins/intel_npu/tests/unit/npuw/pre_compute_test.cpp
@@ -164,11 +164,11 @@ std::shared_ptr<ov::Model> make_rope_model(bool with_concat2) {
auto perm = ov::op::v0::Constant::create(ov::element::i64, ov::Shape{3}, std::vector<int64_t>{0, 2, 1});
auto transpose = std::make_shared<ov::op::v1::Transpose>(matmul, perm); // [1,4,2]
- // Sin/Cos either via Concat_2 (LLama2) or directly (GPT)
+ // Sin/Cos either via Concat_2 (LLama2's torch.cat([freqs, freqs], -1), i.e. transpose
+ // concatenated with itself) or directly (GPT)
ov::Output<ov::Node> sin_cos_input = transpose->output(0);
if (with_concat2) {
- auto zeros = ov::op::v0::Constant::create(ov::element::f32, ov::Shape{1, 4, 2}, std::vector<float>(8, 0.f));
- sin_cos_input = std::make_shared<ov::op::v0::Concat>(ov::OutputVector{transpose, zeros}, -1)->output(0);
+ sin_cos_input = std::make_shared<ov::op::v0::Concat>(ov::OutputVector{transpose, transpose}, -1)->output(0);
}
auto sin = std::make_shared<ov::op::v0::Sin>(sin_cos_input);
@@ -213,10 +213,7 @@ std::shared_ptr<ov::Model> make_multi_rope_model(const std::vector<std::vector<f
auto perm = ov::op::v0::Constant::create(ov::element::i64, ov::Shape{3}, std::vector<int64_t>{0, 2, 1});
auto transpose = std::make_shared<ov::op::v1::Transpose>(matmul, perm); // [1, 4, freqs.size()]
- auto zeros = ov::op::v0::Constant::create(ov::element::f32,
- ov::Shape{1, 4, freqs.size()},
- std::vector<float>(4 * freqs.size(), 0.f));
- auto concat_2 = std::make_shared<ov::op::v0::Concat>(ov::OutputVector{transpose, zeros}, -1);
+ auto concat_2 = std::make_shared<ov::op::v0::Concat>(ov::OutputVector{transpose, transpose}, -1);
auto sin = std::make_shared<ov::op::v0::Sin>(concat_2);
auto cos = std::make_shared<ov::op::v0::Cos>(concat_2);
@@ -254,6 +251,102 @@ std::shared_ptr<ov::Model> make_rope_model_with_lone_cos(const std::vector<float
return model;
}
+// Same as make_rope_model(/*with_concat2=*/true), but the Concat's 2nd input is zeros instead
+// of a duplicate of the transpose output - e.g. partial-rotary models that pad rather than
+// duplicate. The matcher must not mistake this for freq duplication.
+std::shared_ptr<ov::Model> make_rope_model_non_duplicating_concat() {
+ auto data = std::make_shared<ov::op::v0::Parameter>(ov::element::f32, ov::Shape{1, 4, 4});
+ auto position_ids = std::make_shared<ov::op::v0::Parameter>(ov::element::i64, ov::Shape{1, 4});
+
+ auto inv_freq = ov::op::v0::Constant::create(ov::element::f32, ov::Shape{1, 2, 1}, {0.5f, 0.1f});
+
+ auto shape_of = std::make_shared<ov::op::v3::ShapeOf>(data);
+ auto gather_idx = ov::op::v0::Constant::create(ov::element::i64, ov::Shape{1}, {0});
+ auto gather_axis = ov::op::v0::Constant::create(ov::element::i64, ov::Shape{}, {0});
+ auto gather = std::make_shared<ov::op::v8::Gather>(shape_of, gather_idx, gather_axis);
+ auto ndims_const = ov::op::v0::Constant::create(ov::element::i64, ov::Shape{1}, {2});
+ auto one_const = ov::op::v0::Constant::create(ov::element::i64, ov::Shape{1}, {1});
+ auto concat_1 = std::make_shared<ov::op::v0::Concat>(ov::OutputVector{gather, ndims_const, one_const}, 0);
+
+ auto broadcast = std::make_shared<ov::op::v3::Broadcast>(inv_freq, concat_1);
+ auto unsq_axis = ov::op::v0::Constant::create(ov::element::i64, ov::Shape{1}, {1});
+ auto unsqueeze = std::make_shared<ov::op::v0::Unsqueeze>(position_ids, unsq_axis);
+ auto convert = std::make_shared<ov::op::v0::Convert>(unsqueeze, ov::element::f32);
+ auto matmul = std::make_shared<ov::op::v0::MatMul>(broadcast, convert);
+ auto perm = ov::op::v0::Constant::create(ov::element::i64, ov::Shape{3}, std::vector<int64_t>{0, 2, 1});
+ auto transpose = std::make_shared<ov::op::v1::Transpose>(matmul, perm);
+
+ auto zeros = ov::op::v0::Constant::create(ov::element::f32, ov::Shape{1, 4, 2}, std::vector<float>(8, 0.f));
+ auto concat_2 = std::make_shared<ov::op::v0::Concat>(ov::OutputVector{transpose, zeros}, -1);
+
+ auto sin = std::make_shared<ov::op::v0::Sin>(concat_2);
+ auto cos = std::make_shared<ov::op::v0::Cos>(concat_2);
+
+ return std::make_shared<ov::Model>(
+ ov::ResultVector{std::make_shared<ov::op::v0::Result>(sin), std::make_shared<ov::op::v0::Result>(cos)},
+ ov::ParameterVector{data, position_ids},
+ "non_duplicating_concat_rope_test_model");
+}
+
+// Builds a RoPE model matching make_rope_model's two flavours, but where inv_freq is
+// already exported pre-broadcast to its final [1, half_dim, 1] shape, with no live
+// Broadcast node (and no ShapeOf->Gather->Concat shape-compute chain feeding it) - as
+// seen e.g. on Qwen3, where the exporter folds the broadcast away.
+std::shared_ptr<ov::Model> make_rope_model_no_broadcast(bool with_concat2) {
+ auto position_ids = std::make_shared<ov::op::v0::Parameter>(ov::element::i64, ov::Shape{1, 4});
+
+ // inv_freq already shaped as if Broadcast had run: [1, half_dim=2, 1]
+ auto inv_freq = ov::op::v0::Constant::create(ov::element::f32, ov::Shape{1, 2, 1}, {0.5f, 0.1f});
+
+ auto unsq_axis = ov::op::v0::Constant::create(ov::element::i64, ov::Shape{1}, {1});
+ auto unsqueeze = std::make_shared<ov::op::v0::Unsqueeze>(position_ids, unsq_axis);
+ auto convert = std::make_shared<ov::op::v0::Convert>(unsqueeze, ov::element::f32);
+ auto matmul = std::make_shared<ov::op::v0::MatMul>(inv_freq, convert); // [1,2,4]
+ auto perm = ov::op::v0::Constant::create(ov::element::i64, ov::Shape{3}, std::vector<int64_t>{0, 2, 1});
+ auto transpose = std::make_shared<ov::op::v1::Transpose>(matmul, perm); // [1,4,2]
+
+ ov::Output<ov::Node> sin_cos_input = transpose->output(0);
+ if (with_concat2) {
+ sin_cos_input = std::make_shared<ov::op::v0::Concat>(ov::OutputVector{transpose, transpose}, -1)->output(0);
+ }
+
+ auto sin = std::make_shared<ov::op::v0::Sin>(sin_cos_input);
+ auto cos = std::make_shared<ov::op::v0::Cos>(sin_cos_input);
+
+ return std::make_shared<ov::Model>(
+ ov::ResultVector{std::make_shared<ov::op::v0::Result>(sin), std::make_shared<ov::op::v0::Result>(cos)},
+ ov::ParameterVector{position_ids},
+ with_concat2 ? "llama2_rope_no_broadcast_test_model" : "gpt_rope_no_broadcast_test_model");
+}
+
+// Same as make_rope_model_no_broadcast(/*with_concat2=*/true), but inv_freq has a real (non-
+// singleton) leading batch dim - a shape the "no live Broadcast" fallback never validates.
+// Without a validity check, makeCosSinCache would flatten this into the frequency axis and
+// silently corrupt the LUT's shape, so the matcher must leave Sin/Cos untouched instead.
+std::shared_ptr<ov::Model> make_rope_model_no_broadcast_extra_batch_dim() {
+ auto position_ids = std::make_shared<ov::op::v0::Parameter>(ov::element::i64, ov::Shape{1, 4});
+
+ // inv_freq shaped [2, 2, 1] - batch=2, not the expected singleton batch dim.
+ auto inv_freq = ov::op::v0::Constant::create(ov::element::f32, ov::Shape{2, 2, 1}, {0.5f, 0.1f, 0.5f, 0.1f});
+
+ auto unsq_axis = ov::op::v0::Constant::create(ov::element::i64, ov::Shape{1}, {1});
+ auto unsqueeze = std::make_shared<ov::op::v0::Unsqueeze>(position_ids, unsq_axis);
+ auto convert = std::make_shared<ov::op::v0::Convert>(unsqueeze, ov::element::f32);
+ auto matmul = std::make_shared<ov::op::v0::MatMul>(inv_freq, convert); // [2,2,4]
+ auto perm = ov::op::v0::Constant::create(ov::element::i64, ov::Shape{3}, std::vector<int64_t>{0, 2, 1});
+ auto transpose = std::make_shared<ov::op::v1::Transpose>(matmul, perm); // [2,4,2]
+
+ auto concat_2 = std::make_shared<ov::op::v0::Concat>(ov::OutputVector{transpose, transpose}, -1);
+
+ auto sin = std::make_shared<ov::op::v0::Sin>(concat_2);
+ auto cos = std::make_shared<ov::op::v0::Cos>(concat_2);
+
+ return std::make_shared<ov::Model>(
+ ov::ResultVector{std::make_shared<ov::op::v0::Result>(sin), std::make_shared<ov::op::v0::Result>(cos)},
+ ov::ParameterVector{position_ids},
+ "llama2_rope_no_broadcast_extra_batch_dim_test_model");
+}
+
bool has_input_name(const std::shared_ptr<ov::Model>& model, const std::string& name) {
const auto inputs = model->inputs();
return std::any_of(inputs.begin(), inputs.end(), [&name](const auto& input) {
@@ -399,11 +492,11 @@ TEST(PreComputeTest, LongRopeCosSinSerializationRoundTrip) {
std::stringstream ss;
auto writer = Stream::writer(ss);
- writer& src;
+ writer & src;
ov::npuw::patterns::pre_compute::LongRopeCosSin dst;
auto reader = Stream::reader(ss);
- reader& dst;
+ reader & dst;
EXPECT_EQ(dst.max_len, src.max_len);
EXPECT_EQ(dst.rotary_ndims, src.rotary_ndims);
@@ -431,12 +524,12 @@ TEST(PreComputeTest, LongRopeCosSinSerializationRoundTripEmpty) {
ov::npuw::patterns::pre_compute::LongRopeCosSin src;
std::stringstream ss;
auto writer = Stream::writer(ss);
- writer& src;
+ writer & src;
ov::npuw::patterns::pre_compute::LongRopeCosSin dst;
dst.max_len = 7; // must be overwritten by the read
auto reader = Stream::reader(ss);
- reader& dst;
+ reader & dst;
EXPECT_EQ(dst.max_len, 0u);
EXPECT_EQ(dst.rotary_ndims, 0u);
@@ -596,4 +689,50 @@ TEST(PreComputeTest, RopeCacheLeavesUnpairedCosUntouched) {
<< "only the lone, unpaired Cos should remain";
}
+// Qwen3-style export: inv_freq is already a pre-broadcast Constant, no live Broadcast
+// node and no ShapeOf->Gather->Concat chain feeding it. The matcher must still fire via
+// the optional Broadcast's fallback to matching inv_freq's output directly.
+TEST(PreComputeTest, RopeCacheTransformsLLama2PatternWithoutBroadcastChain) {
+ auto model = make_rope_model_no_broadcast(/*with_concat2=*/true);
+
+ ov::npuw::patterns::pre_compute::RopeCache pass(/*max_prompt_len=*/16);
+ ASSERT_NO_THROW(pass.run_on_model(model));
+
+ EXPECT_EQ(count_ops_of_type_sin_cos(model), 0u) << "Sin/Cos should be replaced by Gather from the LUT";
+}
+
+TEST(PreComputeTest, RopeCacheTransformsGPTPatternWithoutBroadcastChain) {
+ auto model = make_rope_model_no_broadcast(/*with_concat2=*/false);
+
+ ov::npuw::patterns::pre_compute::RopeCache pass(/*max_prompt_len=*/16);
+ ASSERT_NO_THROW(pass.run_on_model(model));
+
+ EXPECT_EQ(count_ops_of_type_sin_cos(model), 0u) << "Sin/Cos should be replaced by Gather from the LUT";
+}
+
+// When the Broadcast is bypassed, inv_freq must still have only the supported singleton
+// batch dim - anything else (e.g. a real batch dim) would be silently flattened into the
+// frequency axis by makeCosSinCache, corrupting the LUT's shape. The matcher must leave
+// Sin/Cos untouched rather than misfire on such a constant.
+TEST(PreComputeTest, RopeCacheLeavesNonSingletonBatchInvFreqUntouched) {
+ auto model = make_rope_model_no_broadcast_extra_batch_dim();
+
+ ov::npuw::patterns::pre_compute::RopeCache pass(/*max_prompt_len=*/16);
+ ASSERT_NO_THROW(pass.run_on_model(model));
+
+ EXPECT_EQ(count_ops_of_type_sin_cos(model), 2u) << "Sin/Cos must stay as-is, not be wrongly replaced by the LUT";
+}
+
+// A Concat following Transpose whose 2nd input isn't the same tensor (e.g. zero-padding for
+// partial-rotary models) must not be mistaken for freq duplication - the LUT's second half
+// would otherwise be wrong. The matcher must leave Sin/Cos untouched rather than misfire.
+TEST(PreComputeTest, RopeCacheLeavesNonDuplicatingConcatUntouched) {
+ auto model = make_rope_model_non_duplicating_concat();
+
+ ov::npuw::patterns::pre_compute::RopeCache pass(/*max_prompt_len=*/16);
+ ASSERT_NO_THROW(pass.run_on_model(model));
+
+ EXPECT_EQ(count_ops_of_type_sin_cos(model), 2u) << "Sin/Cos must stay as-is, not be wrongly replaced by the LUT";
+}
+
} // namespace