OpenVINO™ is an open source toolkit for optimizing and deploying AI inference
C++ aicomputer-visiondeep-learningdeploy-aidiffusion-modelsgenerative-aigood-first-issueinferencellm-inferencenatural-language-processingnlpopenvinooptimize-aiperformance-boostrecommendation-systemspeech-recognitionstable-diffusiontransformersyolo
[NPUW] Support newer transformers position lowering in Whisper and LFM2 (#37166)
Dylan Neve37b16ecc6b5f
diff --git a/src/plugins/intel_npu/src/plugin/npuw/npuw_transformations/add_position_ids_param.cpp b/src/plugins/intel_npu/src/plugin/npuw/npuw_transformations/add_position_ids_param.cppindex 79d06af7574..9604baf8408 100644--- a/src/plugins/intel_npu/src/plugin/npuw/npuw_transformations/add_position_ids_param.cpp+++ b/src/plugins/intel_npu/src/plugin/npuw/npuw_transformations/add_position_ids_param.cpp@@ -34,9 +34,27 @@ class HardcodedPositionIdsMatcher : public ov::pass::MultiMatcher {public:OPENVINO_MATCHER_PASS_RTTI("ov::npuw::HardcodedPositionIdsMatcher");explicit HardcodedPositionIdsMatcher(ov::ParameterVector& new_params) {+ // The oldest exports shared one Range between RoPE, Causal Mask and the Gated Short+ // Convolution Block, and offset it inside Range itself:+ //+ // -> Convert -> RoPE+ // |+ // -> Unsqueeze -> Unsqueeze+ // | |+ // Range -------- -> Unsqueeze -> LessEqual (Causal Mask)+ // |+ // -> Clamp -> ScatterNDUpdate (Gated Short Convolution Block)+ //+ // transformers>=5.4 aranges from zero and adds the past length on top of it instead, gives+ // RoPE and Causal Mask a Range each, and drops the Clamp path altogether, leaving no+ // branching at all:+ //+ // Range -> Add -> Unsqueeze -> Unsqueeze -> Convert -> RoPE+ //auto range = opp::wrap_type<ov::op::v4::Range>();+ auto position = opp::optional<ov::op::v1::Add>({range->output(0), opp::any_input()});auto unsqueeze_axes = opp::wrap_type<ov::op::v0::Constant>();- auto unsqueeze = opp::wrap_type<ov::op::v0::Unsqueeze>({range, unsqueeze_axes});+ auto unsqueeze = opp::wrap_type<ov::op::v0::Unsqueeze>({position, unsqueeze_axes});auto unsqueeze1_axes = opp::wrap_type<ov::op::v0::Constant>();auto unsqueeze1 = opp::wrap_type<ov::op::v0::Unsqueeze>({unsqueeze, unsqueeze1_axes});@@ -63,7 +81,6 @@ public:auto& pattern_to_output = m.at(cos).front();auto range_node = pattern_to_output.at(range).get_node_shared_ptr();- auto unsqueeze_node = pattern_to_output.at(unsqueeze).get_node_shared_ptr();// Point of branching:auto unsqueeze1_node = pattern_to_output.at(unsqueeze1).get_node_shared_ptr();auto convert_node = pattern_to_output.at(convert).get_node_shared_ptr();@@ -87,12 +104,11 @@ public:OPENVINO_ASSERT(range_node->get_output_size() == 1, "Range node should have exactly one output");auto range_consumers = range_node->get_output_target_inputs(0);for (auto&& consumer : range_consumers) {- if (consumer.get_node()->get_type_name() == std::string("Unsqueeze") &&- consumer.get_node() == unsqueeze_node.get()) {- // Preserve original Range for Causal Mask creation- continue;+ // Only the Clamp path is rewired: the Range is preserved for Causal Mask creation,+ // and newer models have no Clamp to begin with.+ if (consumer.get_node()->get_type_name() == std::string("Clamp")) {+ consumer.replace_source_output(position_ids_squeezed->output(0));}- consumer.replace_source_output(position_ids_squeezed->output(0));}new_params.push_back(position_ids);diff --git a/src/plugins/intel_npu/src/plugin/npuw/whisper/prepare_whisper_model.cpp b/src/plugins/intel_npu/src/plugin/npuw/whisper/prepare_whisper_model.cppindex 537c5af72d9..49409b1c863 100644--- a/src/plugins/intel_npu/src/plugin/npuw/whisper/prepare_whisper_model.cpp+++ b/src/plugins/intel_npu/src/plugin/npuw/whisper/prepare_whisper_model.cpp@@ -200,6 +200,12 @@ public:OPENVINO_MATCHER_PASS_RTTI("npuw::LLMCompiledModel::CachePositionInput");CachePositionInput(std::shared_ptr<ov::Model> model) {+ // Here the past length is folded into Range's start:+ //+ // Gather ---------------++ // \ +-> Range -> Unsqueeze -> Tile+ // -> Add -------++ //auto gather = opp::wrap_type<ov::op::v8::Gather>({opp::any_input(), opp::any_input(), opp::any_input()});auto add = opp::wrap_type<ov::op::v1::Add>({gather, opp::any_input()});auto range = opp::wrap_type<ov::op::v4::Range>({gather, add, opp::any_input()});@@ -230,6 +236,54 @@ public:}};+class CachePositionInput_2 : public ov::pass::MatcherPass {+public:+ OPENVINO_MATCHER_PASS_RTTI("npuw::LLMCompiledModel::CachePositionInput_2");++ CachePositionInput_2(std::shared_ptr<ov::Model> model) {+ // transformers>=5.4 aranges from zero and adds the past length on top of it instead of+ // folding it into Range's start as CachePositionInput above expects:+ //+ // Range -> Add -> Unsqueeze -> Tile+ //+ auto range = opp::wrap_type<ov::op::v4::Range>();+ auto add = opp::wrap_type<ov::op::v1::Add>({range, opp::any_input()});+ auto unsqueeze = opp::wrap_type<ov::op::v0::Unsqueeze>({add, opp::any_input()});+ auto tile = opp::wrap_type<ov::op::v0::Tile>({unsqueeze, opp::any_input()});++ register_matcher(+ std::make_shared<opp::Matcher>(tile, this->get_type_info().name),+ [model, unsqueeze](opp::Matcher& m) {+ // Both patterns are rooted at Tile and neither claims the node it matched, so+ // GraphRewrite offers every Tile to both. Exactly one matches per model, but a+ // second match would add a second parameter named cache_position, of which only+ // the first would ever be found again.+ OPENVINO_ASSERT(!ov::npuw::util::has_input(model, "cache_position"),+ "More than one subgraph matched a cache position pattern");++ auto& node_to_output = m.get_pattern_value_map();+ auto unsqueeze_node = node_to_output.at(unsqueeze).get_node_shared_ptr();+ auto matched_unsqueeze = std::static_pointer_cast<ov::op::v0::Unsqueeze>(unsqueeze_node);++ auto cache_position = std::make_shared<ov::op::v0::Parameter>(ov::element::i64, ov::Shape{1});+ cache_position->get_output_tensor(0).set_names({"cache_position"});+ cache_position->set_friendly_name("cache_position");+ model->add_parameters({cache_position});+ std::shared_ptr<ov::Node> cache_pos_unsqueeze_arg;+ if (matched_unsqueeze->input(0).get_element_type() == ov::element::f32) {+ cache_pos_unsqueeze_arg = std::make_shared<ov::op::v0::Convert>(cache_position, ov::element::f32);+ } else {+ cache_pos_unsqueeze_arg = cache_position;+ }++ // cache_position is already absolute, so the matched Add is dropped with the+ // rest of the replaced subgraph.+ matched_unsqueeze->input(0).replace_source_output(cache_pos_unsqueeze_arg->output(0));+ return false;+ });+ }+};+bool can_move_scale_after_matmul(const ov::Output<ov::Node>& query,const ov::Output<ov::Node>& kT,const ov::Output<ov::Node>& scale) {@@ -655,6 +709,7 @@ void add_attention_mask_input(const std::shared_ptr<ov::Model>& model,void add_cache_position_input(const std::shared_ptr<ov::Model>& model) {ov::pass::GraphRewrite rewr;rewr.add_matcher<CachePositionInput>(model);+ rewr.add_matcher<CachePositionInput_2>(model); // transformers>=5.4rewr.run_on_model(model);ov::pass::Validate().run_on_model(model);diff --git a/src/plugins/intel_npu/tests/unit/npuw/pipeline_passes/add_position_ids_param_test.cpp b/src/plugins/intel_npu/tests/unit/npuw/pipeline_passes/add_position_ids_param_test.cppindex 69cbc43778a..78cbc1f7170 100644--- a/src/plugins/intel_npu/tests/unit/npuw/pipeline_passes/add_position_ids_param_test.cpp+++ b/src/plugins/intel_npu/tests/unit/npuw/pipeline_passes/add_position_ids_param_test.cpp@@ -10,6 +10,7 @@#include <vector>#include "npuw_transformations/add_position_ids_param.hpp"+#include "openvino/op/add.hpp"#include "openvino/op/clamp.hpp"#include "openvino/op/concat.hpp"#include "openvino/op/constant.hpp"@@ -26,7 +27,11 @@#include "openvino/op/unsqueeze.hpp"namespace {-std::shared_ptr<ov::Model> build_model_with_lfm2_like_pattern() {+// offset_positions selects the transformers>=5.4 shape, where Range starts from zero and the past+// length is added on top of it rather than being folded into Range's start.+// with_clamp controls the Gated Short Convolution Block's Clamp consumer on Range, which newer+// exports drop altogether.+std::shared_ptr<ov::Model> build_model_with_lfm2_like_pattern(bool offset_positions = false, bool with_clamp = true) {// Range: start=0, stop=seq_len, step=1 (mimics position_ids generation)auto start = ov::op::v0::Constant::create(ov::element::i64, ov::Shape{}, {0});auto stop = ov::op::v0::Constant::create(ov::element::i64, ov::Shape{}, {128});@@ -34,9 +39,18 @@ std::shared_ptr<ov::Model> build_model_with_lfm2_like_pattern() {auto range = std::make_shared<ov::op::v4::Range>(start, stop, step, ov::element::i64);range->set_friendly_name("range");+ // transformers>=5.4: past length added after the Range instead of folded into its start+ ov::Output<ov::Node> positions = range->output(0);+ if (offset_positions) {+ auto past_len = ov::op::v0::Constant::create(ov::element::i64, ov::Shape{}, {8});+ auto offset_add = std::make_shared<ov::op::v1::Add>(range, past_len);+ offset_add->set_friendly_name("positions_offset_add");+ positions = offset_add->output(0);+ }+// Unsqueeze: add batch dim [seq_len] → [1, seq_len]auto unsqueeze_axes = ov::op::v0::Constant::create(ov::element::i64, ov::Shape{1}, {0});- auto unsqueeze = std::make_shared<ov::op::v0::Unsqueeze>(range, unsqueeze_axes);+ auto unsqueeze = std::make_shared<ov::op::v0::Unsqueeze>(positions, unsqueeze_axes);unsqueeze->set_friendly_name("unsqueeze_batch");// Unsqueeze1: add feature dim [1, seq_len] → [1, 1, seq_len]@@ -94,11 +108,13 @@ std::shared_ptr<ov::Model> build_model_with_lfm2_like_pattern() {// Optional Clamp consumer on Range (simulates Gated Short Convolution indexing in LFM2).// Real LFM2 path: Range -> Clamp -> Add -> Mod -> Unsqueeze -> ScatterNDUpdate- auto clamp = std::make_shared<ov::op::v0::Clamp>(range, 0, 2);- clamp->set_friendly_name("conv_clamp");- auto clamp_result = std::make_shared<ov::op::v0::Result>(clamp);- clamp_result->set_friendly_name("clamp_result");- results.push_back(clamp_result);+ if (with_clamp) {+ auto clamp = std::make_shared<ov::op::v0::Clamp>(range, 0, 2);+ clamp->set_friendly_name("conv_clamp");+ auto clamp_result = std::make_shared<ov::op::v0::Result>(clamp);+ clamp_result->set_friendly_name("clamp_result");+ results.push_back(clamp_result);+ }return std::make_shared<ov::Model>(results, params, "model_with_lfm2_like_pattern");}@@ -282,4 +298,99 @@ TEST(AddPositionIdsParamTest, ReapplyDoesNotModifyGraph) {EXPECT_EQ(model->get_ops().size(), ops_after_first)<< "Second pass should not add duplicate operations";}++// --- transformers>=5.4: Range -> Add(past_len) -> Unsqueeze -> Unsqueeze -> Convert -> RoPE ---+// The offset moved out of Range, so the pass matches through an optional Add. These models also+// give the causal mask its own Range and have no Clamp path.+TEST(AddPositionIdsParamTest, OffsetAddRopePathUsesPositionIds) {+ auto model = build_model_with_lfm2_like_pattern(true /*offset_positions*/, false /*with_clamp*/);++ EXPECT_FALSE(has_parameter_named(model, "position_ids"));+ ASSERT_NO_THROW(ov::npuw::AddPositionIdsParam().run_on_model(model));+ EXPECT_TRUE(has_parameter_named(model, "position_ids"));++ // Walk back from MatMul: position_ids → Unsqueeze → Convert → MatMul, no Add in between+ std::shared_ptr<ov::Node> matmul_node;+ for (const auto& op : model->get_ops()) {+ if (op->get_type_name() == std::string("MatMul")) {+ matmul_node = op;+ break;+ }+ }+ ASSERT_NE(matmul_node, nullptr) << "MatMul not found in model";++ auto walk = matmul_node->input_value(1).get_node_shared_ptr();+ bool found_position_ids = false;+ for (int depth = 0; depth < 5; ++depth) { // limit walk depth+ if (walk->get_type_name() == std::string("Parameter")) {+ found_position_ids = walk->output(0).get_names().count("position_ids") > 0;+ break;+ }+ if (walk->get_input_size() == 0) {+ break;+ }+ walk = walk->input_value(0).get_node_shared_ptr();+ }+ EXPECT_TRUE(found_position_ids) << "MatMul (RoPE path) should be fed by position_ids, not Add(Range, past_len)";+}++// The Range must survive for Causal Mask creation even though the RoPE consumer it used to be+// identified by is now the Add rather than the Unsqueeze.+TEST(AddPositionIdsParamTest, OffsetAddPreservesRangeForCausalMask) {+ auto model = build_model_with_lfm2_like_pattern(true /*offset_positions*/, false /*with_clamp*/);+ ASSERT_NO_THROW(ov::npuw::AddPositionIdsParam().run_on_model(model));++ EXPECT_GE(count_ops_of_type(model, "Range"), 1u) << "Range node should be preserved for causal mask";++ bool found_range_as_le_input = false;+ for (const auto& op : model->get_ops()) {+ if (op->get_type_name() != std::string("LessEqual")) {+ continue;+ }+ std::set<ov::Node*> visited;+ std::queue<ov::Node*> to_visit;+ for (size_t inp = 0; inp < op->get_input_size(); ++inp) {+ to_visit.push(op->input_value(inp).get_node());+ }+ while (!to_visit.empty()) {+ auto* n = to_visit.front();+ to_visit.pop();+ if (!visited.insert(n).second) {+ continue;+ }+ if (std::string(n->get_type_name()) == "Range") {+ found_range_as_le_input = true;+ break;+ }+ for (size_t i = 0; i < n->get_input_size(); ++i) {+ to_visit.push(n->input_value(i).get_node());+ }+ }+ }+ EXPECT_TRUE(found_range_as_le_input) << "Range should still feed the causal mask LessEqual";+}++// Clamp rewiring now keys off the Clamp itself rather than off skipping the RoPE consumer, so it+// has to keep working when the positions reach RoPE through an Add.+TEST(AddPositionIdsParamTest, OffsetAddWithClampReplacesClampInput) {+ auto model = build_model_with_lfm2_like_pattern(true /*offset_positions*/, true /*with_clamp*/);++ ASSERT_NO_THROW(ov::npuw::AddPositionIdsParam().run_on_model(model));+ EXPECT_TRUE(has_parameter_named(model, "position_ids"));+ ASSERT_EQ(count_ops_of_type(model, "Clamp"), 1u) << "Test model should have a Clamp to rewire";++ for (const auto& op : model->get_ops()) {+ if (op->get_type_name() != std::string("Clamp")) {+ continue;+ }+ auto producer = op->input_value(0).get_node_shared_ptr();+ ASSERT_EQ(std::string(producer->get_type_name()), "Squeeze")+ << "Clamp should be fed by Squeeze(position_ids), not " << producer->get_type_name();++ auto squeeze_input = producer->input_value(0).get_node_shared_ptr();+ ASSERT_EQ(std::string(squeeze_input->get_type_name()), "Parameter");+ EXPECT_TRUE(squeeze_input->output(0).get_names().count("position_ids") > 0)+ << "Squeeze should be fed by position_ids parameter";+ }+}} // namespace