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] Fix LFM3 sliding-attention RoPE positions and sliding window mask (#39793)
Pengqiang Li442b3aca319c
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 f8f63200b2c..238f09b4f67 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@@ -6,6 +6,7 @@#include <unordered_set>+#include "openvino/core/rt_info.hpp"#include "openvino/op/ops.hpp"#include "openvino/openvino.hpp"#include "openvino/pass/manager.hpp"@@ -91,31 +92,54 @@ public:// from the left till the real current positions in the sequence (inclusively), while our current// items are lied at the right end of the static `input_ids` after a whole window of padding. Thus,// the Range should be preserved for Causal Mask creation.- auto& pattern_to_output = m.at(cos).front();-- auto range_node = pattern_to_output.at(range).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();-- // Create `position_ids` parameter+ //+ // Hybrid models can have independent RoPE branches for full and sliding+ // attention. Every branch must use actual positions rather than the+ // static cache capacity. Share one parameter across all matched paths.auto [position_ids, position_ids_squeezed] = make_position_ids();-- // Create new Unsqueeze node for point of branching- auto unsqueeze1_node_copy =- unsqueeze1_node->clone_with_new_inputs({position_ids, unsqueeze1_node->input_value(1)});- convert_node->input(0).replace_source_output(unsqueeze1_node_copy->output(0));-- // FIXME: For Gated Short Convolution Block, there is ScatterNDUpdate that also consumes generated- // positions in old IRs.- // It seems to right to use the newly created `position_ids` for it as well, however, real tests show- // no difference against usage of hardcoded QRange: both are similarly accurate.- 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) {- // Only the Clamp path is remained to rewire.- if (consumer.get_node()->get_type_name() == std::string("Clamp")) {- consumer.replace_source_output(position_ids_squeezed->output(0));+ std::unordered_set<ov::Node*> handled_converts;+ // All the branches unsqueeze the positions the same way: share one copy when the axes match.+ std::shared_ptr<ov::Node> position_ids_unsqueezed;+ const auto same_axes = [](const ov::Output<ov::Node>& lhs, const ov::Output<ov::Node>& rhs) {+ const auto lhs_const = ov::as_type_ptr<ov::op::v0::Constant>(lhs.get_node_shared_ptr());+ const auto rhs_const = ov::as_type_ptr<ov::op::v0::Constant>(rhs.get_node_shared_ptr());+ return lhs_const && rhs_const && lhs_const->cast_vector<int64_t>() == rhs_const->cast_vector<int64_t>();+ };+ for (const auto& root : {cos, sin}) {+ const auto matches = m.find(root);+ if (matches == m.end()) {+ continue;+ }+ for (const auto& pattern_to_output : matches->second) {+ auto convert_node = pattern_to_output.at(convert).get_node_shared_ptr();+ if (!handled_converts.insert(convert_node.get()).second) {+ continue;+ }+ auto range_node = pattern_to_output.at(range).get_node_shared_ptr();+ auto unsqueeze1_node = pattern_to_output.at(unsqueeze1).get_node_shared_ptr();+ // position_ids replaces the positions computed from the Range.+ ov::copy_runtime_info(+ range_node,+ {position_ids, position_ids_squeezed, position_ids_squeezed->get_input_node_shared_ptr(1)});++ // Clone only the RoPE side of the branch, preserving Range-based+ // causal-mask indexing and each branch's inverse frequencies.+ if (!position_ids_unsqueezed ||+ !same_axes(position_ids_unsqueezed->input_value(1), unsqueeze1_node->input_value(1))) {+ position_ids_unsqueezed =+ unsqueeze1_node->clone_with_new_inputs({position_ids, unsqueeze1_node->input_value(1)});+ ov::copy_runtime_info(unsqueeze1_node, position_ids_unsqueezed);+ }+ convert_node->input(0).replace_source_output(position_ids_unsqueezed->output(0));++ // Preserve the existing rewrite of legacy short-convolution indexing.+ 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("Clamp")) {+ consumer.replace_source_output(position_ids_squeezed->output(0));+ }+ }}}diff --git a/src/plugins/intel_npu/src/plugin/npuw/npuw_transformations/sliding_window_mask.cpp b/src/plugins/intel_npu/src/plugin/npuw/npuw_transformations/sliding_window_mask.cppindex 510d1076382..b1d92da7569 100644--- a/src/plugins/intel_npu/src/plugin/npuw/npuw_transformations/sliding_window_mask.cpp+++ b/src/plugins/intel_npu/src/plugin/npuw/npuw_transformations/sliding_window_mask.cpp@@ -5,12 +5,15 @@#include "sliding_window_mask.hpp"#include "../logging.hpp"+#include "openvino/core/rt_info.hpp"#include "openvino/op/ops.hpp"#include "openvino/pass/graph_rewrite.hpp"#include "openvino/pass/manager.hpp"#include "openvino/pass/matcher_pass.hpp"#include "openvino/pass/pattern/op/optional.hpp"+#include "openvino/pass/pattern/op/pattern.hpp"#include "openvino/pass/pattern/op/wrap_type.hpp"+#include "openvino/util/pp.hpp"namespace opp = ov::pass::pattern;@@ -145,6 +148,122 @@ bool is_zero_scalar_constant(const ov::Output<ov::Node>& output) {return !values.empty() && values.front() == 0;}+class DistanceSlidingMaskMatcher : public ov::pass::MatcherPass {+public:+ OPENVINO_MATCHER_PASS_RTTI("ov::npuw::patterns::DistanceSlidingMaskMatcher");++ explicit DistanceSlidingMaskMatcher(const std::shared_ptr<ov::Node>& attention_mask) {+ // Sliding window mask built from the query-key distance, nested in the causal/padding mask, as+ // emitted by optimum-intel exports that keep the window extractable for SDPAToPagedAttention+ // (ex.: LFM3):+ //+ // Q = Range(past_kv_len, past_kv_len + seq_len) as [seq, 1], K = Range(0, total_seq) as [1, total_seq]+ // Select(!(K <= Q && key_valid), fill, Select(Q - K >= window, fill, 0))+ //+ // With static KV buffers Q is a physical cache position. Past tokens are left-aligned in the buffer,+ // so all of them end up out of the window and SWA layers drop the whole history. Measure the distance+ // to past keys from the position of the query among the valid tokens instead. Keep Q for the causal+ // bound and for keys of the current chunk, which is contiguous at the right end of the buffer.+ auto integer = [](int64_t value) {+ return opp::wrap_type<ov::op::v0::Constant>([value](const ov::Output<ov::Node>& output) {+ auto c = ov::as_type_ptr<ov::op::v0::Constant>(output.get_node_shared_ptr());+ return c && c->get_element_type().is_integral_number() && ov::shape_size(c->get_shape()) == 1 &&+ c->cast_vector<int64_t>().front() == value;+ });+ };+ auto past_shape = opp::wrap_type<ov::op::v3::ShapeOf>({opp::any_input()});+ auto past_len = opp::wrap_type<ov::op::v8::Gather>({past_shape, integer(2), integer(0)});+ auto full_len = opp::wrap_type<ov::op::v1::Add>({past_len, opp::any_input()});+ auto query_range =+ opp::wrap_type<ov::op::v4::Range>({past_len, full_len, integer(1)}, opp::type_matches(ov::element::i64));+ auto query_col = opp::wrap_type<ov::op::v0::Unsqueeze>({query_range, integer(1)});+ // The attention mask of the model itself, [batch, total_seq].+ auto mask_param = opp::wrap_type<ov::op::v0::Parameter>([attention_mask](const ov::Output<ov::Node>& output) {+ return output.get_node() == attention_mask.get() && output.get_partial_shape().rank() == 2;+ });+ auto mask_shape = opp::wrap_type<ov::op::v3::ShapeOf>({mask_param});+ auto mask_len = opp::wrap_type<ov::op::v8::Gather>({mask_shape, integer(1), integer(0)});+ auto key_range =+ opp::wrap_type<ov::op::v4::Range>({integer(0), mask_len, integer(1)}, opp::type_matches(ov::element::i64));+ auto key_row = opp::wrap_type<ov::op::v0::Unsqueeze>({key_range, integer(0)});+ auto distance = opp::wrap_type<ov::op::v1::Subtract>({query_col, key_row});+ // A positive scalar-broadcast window. The distance is a signed i64, so is the window.+ auto window = opp::wrap_type<ov::op::v0::Constant>([](const ov::Output<ov::Node>& output) {+ auto c = ov::as_type_ptr<ov::op::v0::Constant>(output.get_node_shared_ptr());+ return c && c->get_element_type() == ov::element::i64 && ov::shape_size(c->get_shape()) == 1 &&+ c->get_shape().size() <= 2 && c->cast_vector<int64_t>().front() > 0;+ });+ auto forget = opp::wrap_type<ov::op::v1::GreaterEqual>({distance, window});+ auto expand_mask = [&](const std::shared_ptr<ov::Node>& mask) {+ auto batch = opp::wrap_type<ov::op::v0::Unsqueeze>({mask, integer(0)});+ return opp::wrap_type<ov::op::v0::Unsqueeze>({batch, integer(1)});+ };+ auto causal = opp::wrap_type<ov::op::v1::LessEqual>({key_row, query_col});+ auto valid = opp::wrap_type<ov::op::v13::BitwiseAnd>({expand_mask(causal), opp::any_input()});+ auto invalid = opp::wrap_type<ov::op::v13::BitwiseNot>({valid});+ auto sliding_select =+ opp::wrap_type<ov::op::v1::Select>({expand_mask(forget), opp::any_input(), opp::any_input()});+ auto mask_select = opp::wrap_type<ov::op::v1::Select>({invalid, opp::any_input(), sliding_select});++ auto callback = [OV_CAPTURE_CPY_AND_THIS](opp::Matcher& m) {+ const auto& values = m.get_pattern_value_map();+ const auto mask = values.at(mask_param);+ const auto k = values.at(key_row);++ auto zero = ov::op::v0::Constant::create(ov::element::i64, ov::Shape{}, {0});+ auto one = ov::op::v0::Constant::create(ov::element::i64, ov::Shape{}, {1});+ auto one_1d = ov::op::v0::Constant::create(ov::element::i64, ov::Shape{1}, {1});+ auto column = ov::op::v0::Constant::create(ov::element::i64, ov::Shape{2}, {-1, 1});+ auto past_len_1d = std::make_shared<ov::op::v1::Reshape>(values.at(past_len), one_1d, false);+ auto mask_len_1d = std::make_shared<ov::op::v1::Reshape>(values.at(mask_len), one_1d, false);++ // Query positions in the cache coordinates of the left-aligned history, where slot k holds the k-th+ // valid token. The invalid slots are the tail of the history buffer and the left padding of the+ // current chunk, all of them before the valid tokens of the chunk, so:+ // q_cache = Q - (total_seq - ReduceSum(attention_mask))+ // Derived from the attention mask only, it does not depend on the baseline of the RoPE positions.+ auto num_valid = std::make_shared<ov::op::v1::ReduceSum>(mask, one_1d, false);+ auto num_invalid = std::make_shared<ov::op::v1::Subtract>(values.at(mask_len), num_valid);+ auto query_cache_col = std::make_shared<ov::op::v1::Subtract>(values.at(query_col), num_invalid);++ // History keys: distance in the cache coordinates. Keys of the current chunk are contiguous at the+ // right end of the buffer: keep Q - K there, including for chunks longer than a window. The shared+ // Q/K ranges are not replaced.+ auto history_distance = std::make_shared<ov::op::v1::Subtract>(query_cache_col, k);+ auto forget_history = std::make_shared<ov::op::v1::GreaterEqual>(history_distance, values.at(window));+ auto is_history = std::make_shared<ov::op::v1::Less>(k, values.at(past_len));+ auto mapped_forget = std::make_shared<ov::op::v1::Select>(is_history, forget_history, values.at(forget));++ // The outputs of padded query rows are discarded. Mask them out fully, so that they do not depend on+ // the positions computed for the padding.+ auto query_valid = std::make_shared<ov::op::v8::Slice>(mask, past_len_1d, mask_len_1d, one_1d, one_1d);+ auto query_valid_bool = std::make_shared<ov::op::v0::Convert>(query_valid, ov::element::boolean);+ auto query_valid_col = std::make_shared<ov::op::v1::Reshape>(query_valid_bool, column, false);+ auto query_invalid = std::make_shared<ov::op::v1::LogicalNot>(query_valid_col);+ auto clean_forget = std::make_shared<ov::op::v1::LogicalOr>(mapped_forget, query_invalid);+ auto batch = std::make_shared<ov::op::v0::Unsqueeze>(clean_forget, zero);+ auto heads = std::make_shared<ov::op::v0::Unsqueeze>(batch, one);++ // Change only the inner condition; preserve both fill values and the outer causal/key-padding+ // Select, which is shared with the full attention layers.+ auto sliding_select_node = values.at(sliding_select).get_node_shared_ptr();+ const auto old_condition = sliding_select_node->get_input_node_shared_ptr(0);+ ov::copy_runtime_info(+ old_condition,+ {zero, one, one_1d, column, past_len_1d, mask_len_1d,+ num_valid, num_invalid, query_cache_col, query_valid, history_distance, forget_history,+ is_history, mapped_forget, query_valid_bool, query_valid_col, query_invalid, clean_forget,+ batch, heads});+ heads->set_friendly_name(old_condition->get_friendly_name());+ sliding_select_node->input(0).replace_source_output(heads);+ LOG_INFO("Distance-based sliding window attention mask pattern found and patched.");+ return true;+ };+ register_matcher(std::make_shared<opp::Matcher>(mask_select, "DistanceSlidingMaskMatcher"),+ std::move(callback));+ }+};+class OldPhi3SlidingMaskMatcher : public ov::pass::MatcherPass {public:OPENVINO_MATCHER_PASS_RTTI("ov::npuw::patterns::OldPhi3SlidingMaskMatcher");@@ -678,6 +797,7 @@ bool SlidingWindowMask::run_on_model(const std::shared_ptr<ov::Model>& model) {ov::pass::Manager manager;manager.set_per_pass_validation(true);const auto rewriter = manager.register_pass<ov::pass::GraphRewrite>();+ rewriter->add_matcher<DistanceSlidingMaskMatcher>(attention_mask_node_ptr);rewriter->add_matcher<Gemma4SlidingMaskMatcher>(attention_mask_node_ptr, position_ids_node_ptr);rewriter->add_matcher<Gemma4UnifiedSlidingMaskMatcher>(attention_mask_node_ptr, position_ids_node_ptr);rewriter->add_matcher<Phi3SlidingMaskMatcher>(attention_mask_node_ptr, position_ids_node_ptr);diff --git a/src/plugins/intel_npu/tests/unit/CMakeLists.txt b/src/plugins/intel_npu/tests/unit/CMakeLists.txtindex 42c0cd7d8f7..16eeddb1b26 100644--- a/src/plugins/intel_npu/tests/unit/CMakeLists.txt+++ b/src/plugins/intel_npu/tests/unit/CMakeLists.txt@@ -232,6 +232,7 @@ target_sources(${TARGET_NAME} PRIVATE${CMAKE_CURRENT_SOURCE_DIR}/npuw/pipeline_passes/fold_scalar_dq_test.cpp${CMAKE_CURRENT_SOURCE_DIR}/npuw/pipeline_passes/cut_lm_head_test.cpp${CMAKE_CURRENT_SOURCE_DIR}/npuw/pipeline_passes/patch_sliding_mask_test.cpp+ ${CMAKE_CURRENT_SOURCE_DIR}/npuw/pipeline_passes/distance_sliding_mask_test.cpp${CMAKE_CURRENT_SOURCE_DIR}/npuw/pipeline_passes/detect_causal_mask_test.cpp${CMAKE_CURRENT_SOURCE_DIR}/npuw/pipeline_passes/shrink_sliding_window_kv_cache_test.cpp${CMAKE_CURRENT_SOURCE_DIR}/npuw/pipeline_passes/remove_empty_kv_inputs_test.cppdiff --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 e81809f2131..7f8f11f45d8 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@@ -2,14 +2,20 @@// SPDX-License-Identifier: Apache-2.0//+#include "npuw_transformations/add_position_ids_param.hpp"+#include <gtest/gtest.h>+#include <cmath>+#include <cstdint>#include <queue>#include <set>#include <string>+#include <tuple>+#include <utility>#include <vector>-#include "npuw_transformations/add_position_ids_param.hpp"+#include "common_test_utils/ov_test_utils.hpp"#include "openvino/op/add.hpp"#include "openvino/op/clamp.hpp"#include "openvino/op/concat.hpp"@@ -281,6 +287,162 @@ bool gather_index_fed_by_position_ids(const std::shared_ptr<ov::Node>& gather) {return false;}+// LFM3 has independent RoPE frequency branches, not just Cos/Sin sharing one Convert.+// Reuse the existing builder so each branch also has its own Range-based causal mask.+std::shared_ptr<ov::Model> build_model_with_independent_rope_patterns(bool offset_positions,+ bool with_range_clamp_consumer) {+ ov::ResultVector results;+ ov::ParameterVector params;+ for (size_t branch = 0; branch < 2; ++branch) {+ auto model = build_model_with_lfm2_like_pattern(offset_positions, with_range_clamp_consumer);+ const auto prefix = "branch_" + std::to_string(branch) + "_";+ for (const auto& op : model->get_ops()) {+ op->set_friendly_name(prefix + op->get_friendly_name());+ if (ov::is_type<ov::op::v1::LessEqual>(op)) {+ // A nonzero key index makes accidental mask rewiring numerically visible.+ op->input(0).replace_source_output(+ ov::op::v0::Constant::create(ov::element::i64, ov::Shape{1, 1, 1}, {64})->output(0));+ }+ }+ model->get_parameters().front()->output(0).set_names({prefix + "inv_freq"});+ results.insert(results.end(), model->get_results().begin(), model->get_results().end());+ params.insert(params.end(), model->get_parameters().begin(), model->get_parameters().end());+ }+ return std::make_shared<ov::Model>(results, params, "independent_rope_patterns");+}++// What AddPositionIdsParam is expected to produce: the Convert of every RoPE branch reads one shared+// Unsqueeze(position_ids), legacy Clamp consumers read Squeeze(position_ids), and the Range-based causal masks+// are left as they are. position_ids is appended to the parameters.+std::shared_ptr<ov::Model> build_reference_with_independent_rope_patterns(bool offset_positions,+ bool with_range_clamp_consumer) {+ auto model = build_model_with_independent_rope_patterns(offset_positions, with_range_clamp_consumer);+ auto position_ids = std::make_shared<ov::op::v0::Parameter>(ov::element::i64, ov::PartialShape{-1, -1});+ position_ids->set_friendly_name("position_ids");+ position_ids->output(0).set_names({"position_ids"});+ auto unsqueezed =+ std::make_shared<ov::op::v0::Unsqueeze>(position_ids,+ ov::op::v0::Constant::create(ov::element::i64, ov::Shape{1}, {1}));+ auto squeezed =+ std::make_shared<ov::op::v0::Squeeze>(position_ids,+ ov::op::v0::Constant::create(ov::element::i64, ov::Shape{1}, {0}));+ for (const auto& op : model->get_ops()) {+ if (ov::is_type<ov::op::v0::Convert>(op)) {+ op->input(0).replace_source_output(unsqueezed);+ } else if (ov::is_type<ov::op::v0::Clamp>(op)) {+ op->input(0).replace_source_output(squeezed);+ }+ }+ auto params = model->get_parameters();+ params.push_back(position_ids);+ auto reference = std::make_shared<ov::Model>(model->get_results(), params, "independent_rope_patterns");+ reference->validate_nodes_and_infer_types();+ return reference;+}++class AddPositionIdsParamIndependentRopeTransformationTest+ : public TransformationTestsF,+ public testing::WithParamInterface<std::tuple<bool, bool>> {+protected:+ void SetUp() override {+ TransformationTestsF::SetUp();+ const auto& [offset_positions, with_range_clamp_consumer] = GetParam();+ model = build_model_with_independent_rope_patterns(offset_positions, with_range_clamp_consumer);+ model_ref = build_reference_with_independent_rope_patterns(offset_positions, with_range_clamp_consumer);+ manager.register_pass<ov::npuw::AddPositionIdsParam>();+ }+};++TEST_P(AddPositionIdsParamIndependentRopeTransformationTest, RewiresEveryBranchToSharedPositionIds) {}++TEST_P(AddPositionIdsParamIndependentRopeTransformationTest, SecondRunLeavesTheGraphUnchanged) {+ manager.register_pass<ov::npuw::AddPositionIdsParam>();+}++INSTANTIATE_TEST_SUITE_P(OffsetAndLegacyClamp,+ AddPositionIdsParamIndependentRopeTransformationTest,+ testing::Combine(testing::Bool(), testing::Bool()));++class AddPositionIdsParamIndependentRopeTest : public testing::TestWithParam<std::tuple<bool, bool>> {+protected:+ void SetUp() override {+ model = build_model_with_independent_rope_patterns(std::get<0>(GetParam()), std::get<1>(GetParam()));+ }++ std::shared_ptr<ov::Model> model;+};++TEST_P(AddPositionIdsParamIndependentRopeTest, BranchesShareOneUnsqueezeOfPositionIds) {+ ASSERT_NO_THROW(ov::npuw::AddPositionIdsParam().run_on_model(model));+ ov::NodeVector converts;+ for (const auto& op : model->get_ops()) {+ if (ov::is_type<ov::op::v0::Convert>(op)) {+ converts.push_back(op);+ }+ }+ ASSERT_EQ(converts.size(), 2u);+ EXPECT_EQ(converts[0]->get_input_node_ptr(0), converts[1]->get_input_node_ptr(0));+}++TEST_P(AddPositionIdsParamIndependentRopeTest, EvaluatesBothFrequencyTablesUsingExternalPositions) {+ ASSERT_NO_THROW(ov::npuw::AddPositionIdsParam().run_on_model(model));+ ASSERT_EQ(count_parameters_named(model, "position_ids"), 1u);+ ASSERT_EQ(model->get_parameters().size(), 3u);++ ov::TensorVector inputs;+ for (const auto& param : model->get_parameters()) {+ const auto& names = param->output(0).get_names();+ if (names.count("position_ids")) {+ ov::Tensor positions(ov::element::i64, ov::Shape{1, 128});+ for (size_t i = 0; i < 128; ++i) {+ // Padding and nonconsecutive absolute positions differ from both Range and Range + 8.+ positions.data<int64_t>()[i] = i % 5 == 0 ? 0 : 37 + 2 * static_cast<int64_t>(i);+ }+ inputs.push_back(positions);+ } else {+ ASSERT_TRUE(names.count("branch_0_inv_freq") || names.count("branch_1_inv_freq"));+ const float scale = names.count("branch_0_inv_freq") ? 0.01f : 0.03f;+ ov::Tensor frequencies(ov::element::f32, ov::Shape{1, 8, 1});+ for (size_t i = 0; i < 8; ++i) {+ frequencies.data<float>()[i] = scale * static_cast<float>(i + 1);+ }+ inputs.push_back(frequencies);+ }+ }+ ov::TensorVector outputs;+ for (const auto& result : model->get_results()) {+ outputs.emplace_back(result->get_element_type(), ov::Shape{});+ }+ ASSERT_TRUE(model->evaluate(outputs, inputs));++ const size_t results_per_branch = std::get<1>(GetParam()) ? 4 : 3;+ for (size_t branch = 0; branch < 2; ++branch) {+ SCOPED_TRACE(branch);+ const auto& cos = outputs[branch * results_per_branch];+ const auto& sin = outputs[branch * results_per_branch + 1];+ const auto& mask = outputs[branch * results_per_branch + 2];+ ASSERT_EQ(cos.get_shape(), (ov::Shape{1, 128, 16}));+ ASSERT_EQ(sin.get_shape(), cos.get_shape());+ ASSERT_EQ(mask.get_shape(), (ov::Shape{1, 1, 1, 128}));+ const float scale = branch == 0 ? 0.01f : 0.03f;+ for (size_t i = 0; i < 128; ++i) {+ SCOPED_TRACE(i);+ const int64_t position = i % 5 == 0 ? 0 : 37 + 2 * static_cast<int64_t>(i);+ for (size_t j = 0; j < 16; ++j) {+ const float angle = (scale * static_cast<float>(j % 8 + 1)) * static_cast<float>(position);+ EXPECT_NEAR(cos.data<const float>()[i * 16 + j], std::cos(angle), 1e-5f);+ EXPECT_NEAR(sin.data<const float>()[i * 16 + j], std::sin(angle), 1e-5f);+ }+ const auto original_position = static_cast<int64_t>(i) + (std::get<0>(GetParam()) ? 8 : 0);+ EXPECT_EQ(mask.data<const char>()[i] != 0, 64 <= original_position);+ }+ }+}++INSTANTIATE_TEST_SUITE_P(OffsetAndLegacyClamp,+ AddPositionIdsParamIndependentRopeTest,+ testing::Combine(testing::Bool(), testing::Bool()));+// ===================== TESTS =====================TEST(AddPositionIdsParamTest, AddsPositionIdsParameter) {auto model = build_model_with_lfm2_like_pattern();diff --git a/src/plugins/intel_npu/tests/unit/npuw/pipeline_passes/distance_sliding_mask_test.cpp b/src/plugins/intel_npu/tests/unit/npuw/pipeline_passes/distance_sliding_mask_test.cppnew file mode 100644index 00000000000..e9acf0dcd71--- /dev/null+++ b/src/plugins/intel_npu/tests/unit/npuw/pipeline_passes/distance_sliding_mask_test.cpp@@ -0,0 +1,359 @@+// Copyright (C) 2018-2026 Intel Corporation+// SPDX-License-Identifier: Apache-2.0+//++#include <gtest/gtest.h>++#include <cstdint>+#include <map>+#include <vector>++#include "common_test_utils/ov_test_utils.hpp"+#include "npuw_transformations/patch_sliding_window_mask.hpp"+#include "openvino/op/add.hpp"+#include "openvino/op/bitwise_and.hpp"+#include "openvino/op/bitwise_not.hpp"+#include "openvino/op/constant.hpp"+#include "openvino/op/convert.hpp"+#include "openvino/op/gather.hpp"+#include "openvino/op/greater_eq.hpp"+#include "openvino/op/less.hpp"+#include "openvino/op/less_eq.hpp"+#include "openvino/op/logical_and.hpp"+#include "openvino/op/logical_not.hpp"+#include "openvino/op/logical_or.hpp"+#include "openvino/op/parameter.hpp"+#include "openvino/op/range.hpp"+#include "openvino/op/reduce_sum.hpp"+#include "openvino/op/reshape.hpp"+#include "openvino/op/result.hpp"+#include "openvino/op/select.hpp"+#include "openvino/op/shape_of.hpp"+#include "openvino/op/slice.hpp"+#include "openvino/op/subtract.hpp"+#include "openvino/op/unsqueeze.hpp"+#include "openvino/openvino.hpp"++namespace {++constexpr int64_t kWindow = 4;+constexpr float kFill = -65504.0f;++std::shared_ptr<ov::op::v0::Constant> i64_scalar(int64_t value) {+ return ov::op::v0::Constant::create(ov::element::i64, ov::Shape{}, {value});+}++std::shared_ptr<ov::Node> expand_mask(const ov::Output<ov::Node>& mask) {+ auto batch = std::make_shared<ov::op::v0::Unsqueeze>(mask, i64_scalar(0));+ return std::make_shared<ov::op::v0::Unsqueeze>(batch, i64_scalar(1));+}++// Distance-based attention masks, as exported for LFM3 (optimum-intel, transformers 5.20) and shared by all+// layers:+//+// Q = Range(past_kv_len, past_kv_len + seq_len) as [seq, 1], K = Range(0, total_seq) as [1, total_seq]+// full = Select(!(K <= Q && key_valid), fill, 0)+// sliding = Select(!(K <= Q && key_valid), fill, Select(Q - K >= window, fill, 0))+//+// Q is a position in the static KV buffer: past tokens are left-aligned at [0, past_kv_len), the current+// chunk is right-aligned after them. past_kv_len is taken from the shape of the past key.+struct MaskParts {+ ov::ParameterVector params; // input_ids, attention_mask, past_key, position_ids[, length_mask]+ std::shared_ptr<ov::Node> length_mask;+ std::shared_ptr<ov::Node> past_len;+ std::shared_ptr<ov::Node> mask_len;+ std::shared_ptr<ov::Node> q_col;+ std::shared_ptr<ov::Node> k_row;+ std::shared_ptr<ov::Node> invalid;+ std::shared_ptr<ov::Node> window;+ std::shared_ptr<ov::Node> forget;+};++std::shared_ptr<ov::op::v0::Parameter> make_param(ov::element::Type type,+ const ov::PartialShape& shape,+ const std::string& name) {+ auto param = std::make_shared<ov::op::v0::Parameter>(type, shape);+ param->set_friendly_name(name);+ param->output(0).set_names({name});+ return param;+}++// `separate_length_mask` takes the K range and the window from another mask than the model's attention_mask.+MaskParts build_mask_parts(int64_t window = kWindow, bool separate_length_mask = false) {+ MaskParts r;+ auto input_ids = make_param(ov::element::i64, ov::PartialShape{1, -1}, "input_ids");+ auto attention_mask = make_param(ov::element::i64, ov::PartialShape{1, -1}, "attention_mask");+ auto past_key = make_param(ov::element::f32, ov::PartialShape{1, 4, -1, 8}, "past_key_values.0.key");+ auto position_ids = make_param(ov::element::i64, ov::PartialShape{1, -1}, "position_ids");+ r.params = {input_ids, attention_mask, past_key, position_ids};+ r.length_mask = attention_mask;+ if (separate_length_mask) {+ auto length_mask = make_param(ov::element::i64, ov::PartialShape{1, -1}, "length_mask");+ r.params.push_back(length_mask);+ r.length_mask = length_mask;+ }++ auto seq_len = std::make_shared<ov::op::v8::Gather>(std::make_shared<ov::op::v3::ShapeOf>(input_ids),+ i64_scalar(1),+ i64_scalar(0));+ r.past_len = std::make_shared<ov::op::v8::Gather>(std::make_shared<ov::op::v3::ShapeOf>(past_key),+ i64_scalar(2),+ i64_scalar(0));+ auto full_len = std::make_shared<ov::op::v1::Add>(r.past_len, seq_len);+ auto q_range = std::make_shared<ov::op::v4::Range>(r.past_len, full_len, i64_scalar(1), ov::element::i64);+ r.q_col = std::make_shared<ov::op::v0::Unsqueeze>(q_range, i64_scalar(1));++ r.mask_len = std::make_shared<ov::op::v8::Gather>(std::make_shared<ov::op::v3::ShapeOf>(r.length_mask),+ i64_scalar(1),+ i64_scalar(0));+ auto k_range = std::make_shared<ov::op::v4::Range>(i64_scalar(0), r.mask_len, i64_scalar(1), ov::element::i64);+ r.k_row = std::make_shared<ov::op::v0::Unsqueeze>(k_range, i64_scalar(0));++ auto causal = std::make_shared<ov::op::v1::LessEqual>(r.k_row, r.q_col);+ auto key_valid_2d = std::make_shared<ov::op::v0::Unsqueeze>(attention_mask, i64_scalar(1));+ auto key_valid =+ std::make_shared<ov::op::v0::Convert>(std::make_shared<ov::op::v0::Unsqueeze>(key_valid_2d, i64_scalar(2)),+ ov::element::boolean);+ auto valid = std::make_shared<ov::op::v13::BitwiseAnd>(expand_mask(causal), key_valid);+ r.invalid = std::make_shared<ov::op::v13::BitwiseNot>(valid);++ auto distance = std::make_shared<ov::op::v1::Subtract>(r.q_col, r.k_row);+ r.window = ov::op::v0::Constant::create(ov::element::i64, ov::Shape{1, 1}, {window});+ r.forget = std::make_shared<ov::op::v1::GreaterEqual>(distance, r.window);+ return r;+}++std::shared_ptr<ov::Model> make_mask_model(const MaskParts& parts, const ov::Output<ov::Node>& window_condition) {+ auto fill = ov::op::v0::Constant::create(ov::element::f32, ov::Shape{}, {kFill});+ auto zero = ov::op::v0::Constant::create(ov::element::f32, ov::Shape{}, {0.0f});+ auto window_mask = std::make_shared<ov::op::v1::Select>(window_condition, fill, zero);+ auto sliding_mask = std::make_shared<ov::op::v1::Select>(parts.invalid, fill, window_mask);+ auto full_mask = std::make_shared<ov::op::v1::Select>(parts.invalid, fill, zero);+ auto sliding_result = std::make_shared<ov::op::v0::Result>(sliding_mask);+ sliding_result->set_friendly_name("sliding_mask");+ auto full_result = std::make_shared<ov::op::v0::Result>(full_mask);+ full_result->set_friendly_name("full_mask");+ return std::make_shared<ov::Model>(ov::ResultVector{sliding_result, full_result}, parts.params, "distance_mask");+}++std::shared_ptr<ov::Model> getModel(int64_t window = kWindow, bool separate_length_mask = false) {+ const auto parts = build_mask_parts(window, separate_length_mask);+ return make_mask_model(parts, expand_mask(parts.forget));+}++// The window condition after the patch: past keys measure the distance from the query position among the valid+// tokens, keys of the current chunk keep Q - K, and padded query rows are fully masked.+std::shared_ptr<ov::Model> getModelRef() {+ const auto parts = build_mask_parts();+ const auto& mask = parts.length_mask;+ auto one_1d = ov::op::v0::Constant::create(ov::element::i64, ov::Shape{1}, {1});+ auto column = ov::op::v0::Constant::create(ov::element::i64, ov::Shape{2}, {-1, 1});+ auto past_len_1d = std::make_shared<ov::op::v1::Reshape>(parts.past_len, one_1d, false);+ auto mask_len_1d = std::make_shared<ov::op::v1::Reshape>(parts.mask_len, one_1d, false);++ auto num_valid = std::make_shared<ov::op::v1::ReduceSum>(mask, one_1d, false);+ auto num_invalid = std::make_shared<ov::op::v1::Subtract>(parts.mask_len, num_valid);+ auto query_cache_col = std::make_shared<ov::op::v1::Subtract>(parts.q_col, num_invalid);+ auto history_distance = std::make_shared<ov::op::v1::Subtract>(query_cache_col, parts.k_row);+ auto forget_history = std::make_shared<ov::op::v1::GreaterEqual>(history_distance, parts.window);+ auto is_history = std::make_shared<ov::op::v1::Less>(parts.k_row, parts.past_len);+ auto mapped_forget = std::make_shared<ov::op::v1::Select>(is_history, forget_history, parts.forget);++ auto query_valid = std::make_shared<ov::op::v8::Slice>(mask, past_len_1d, mask_len_1d, one_1d, one_1d);+ auto query_valid_bool = std::make_shared<ov::op::v0::Convert>(query_valid, ov::element::boolean);+ auto query_valid_col = std::make_shared<ov::op::v1::Reshape>(query_valid_bool, column, false);+ auto query_invalid = std::make_shared<ov::op::v1::LogicalNot>(query_valid_col);+ auto clean_forget = std::make_shared<ov::op::v1::LogicalOr>(mapped_forget, query_invalid);+ return make_mask_model(parts, expand_mask(clean_forget));+}++struct StaticInputs {+ size_t past_capacity; // static past KV length+ std::vector<int64_t> attention_mask; // [past_capacity + seq_len]+ std::vector<int64_t> position_ids; // [seq_len]+};++// Evaluates {sliding, full} masks, each flattened [seq_len, total_seq].+std::vector<std::vector<float>> evaluate(const std::shared_ptr<ov::Model>& original, const StaticInputs& in) {+ const size_t seq_len = in.position_ids.size();+ const size_t total = in.attention_mask.size();+ ov::Tensor input_ids(ov::element::i64, ov::Shape{1, seq_len});+ std::fill_n(input_ids.data<int64_t>(), seq_len, 0);+ ov::Tensor attention_mask(ov::element::i64, ov::Shape{1, total});+ std::copy(in.attention_mask.begin(), in.attention_mask.end(), attention_mask.data<int64_t>());+ ov::Tensor past_key(ov::element::f32, ov::Shape{1, 4, in.past_capacity, 8});+ ov::Tensor position_ids(ov::element::i64, ov::Shape{1, seq_len});+ std::copy(in.position_ids.begin(), in.position_ids.end(), position_ids.data<int64_t>());++ // Evaluate with static shapes, as NPUW compiles the prefill and generate models.+ auto model = original->clone();+ std::map<ov::Output<ov::Node>, ov::PartialShape> shapes;+ const ov::TensorVector inputs{input_ids, attention_mask, past_key, position_ids};+ const auto params = model->get_parameters();+ for (size_t i = 0; i < params.size(); ++i) {+ shapes[params[i]->output(0)] = inputs.at(i).get_shape();+ }+ model->reshape(shapes);+ // Core has no reference evaluation of the Bitwise ops; on booleans they are the Logical ones.+ for (const auto& op : model->get_ordered_ops()) {+ std::shared_ptr<ov::Node> logical;+ if (ov::is_type<ov::op::v13::BitwiseAnd>(op)) {+ logical = std::make_shared<ov::op::v1::LogicalAnd>(op->input_value(0), op->input_value(1));+ } else if (ov::is_type<ov::op::v13::BitwiseNot>(op)) {+ logical = std::make_shared<ov::op::v1::LogicalNot>(op->input_value(0));+ }+ if (logical) {+ OPENVINO_ASSERT(op->get_output_element_type(0) == ov::element::boolean);+ ov::replace_node(op, logical);+ }+ }++ ov::TensorVector outputs;+ for (const auto& result : model->get_results()) {+ outputs.emplace_back(result->get_element_type(), result->get_output_shape(0));+ }+ OPENVINO_ASSERT(model->evaluate(outputs, inputs));++ std::vector<std::vector<float>> masks;+ for (const auto& out : outputs) {+ OPENVINO_ASSERT(out.get_shape() == (ov::Shape{1, 1, seq_len, total}));+ masks.emplace_back(out.data<const float>(), out.data<const float>() + seq_len * total);+ }+ return masks;+}++// Reference sliding mask in cache coordinates: the history keeps the k-th valid token in slot k, and the+// valid tokens of the current chunk follow it. A key is visible if it is valid, not in the future and within+// the window. Padded query rows see nothing. position_ids are not used: the window does not depend on their+// baseline.+std::vector<float> reference_sliding_mask(const StaticInputs& in) {+ const size_t seq_len = in.position_ids.size();+ const size_t total = in.attention_mask.size();+ int64_t num_invalid = 0;+ for (const auto valid : in.attention_mask) {+ num_invalid += valid == 0 ? 1 : 0;+ }+ std::vector<float> mask(seq_len * total, kFill);+ for (size_t q = 0; q < seq_len; ++q) {+ const size_t q_slot = in.past_capacity + q;+ if (in.attention_mask[q_slot] == 0) {+ continue;+ }+ const int64_t q_pos = static_cast<int64_t>(q_slot) - num_invalid;+ for (size_t k = 0; k < total; ++k) {+ const bool is_past = k < in.past_capacity;+ const int64_t distance = is_past ? q_pos - static_cast<int64_t>(k) : static_cast<int64_t>(q_slot - k);+ const bool visible = in.attention_mask[k] != 0 && k <= q_slot && distance < kWindow;+ mask[q * total + k] = visible ? 0.0f : kFill;+ }+ }+ return mask;+}++// Generate step: 6 past tokens left-aligned in a 12-slot past buffer, one new token at position 6.+StaticInputs generate_step() {+ return {12, {1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 1}, {6}};+}++// Second prefill chunk: 5 past tokens in an 8-slot past buffer, a 4-token chunk with one left pad.+StaticInputs prefill_chunk() {+ return {8, {1, 1, 1, 1, 1, 0, 0, 0, 0, 1, 1, 1}, {0, 5, 6, 7}};+}++// The same steps when the request's positions start at 37 instead of 0.+StaticInputs generate_step_with_position_baseline() {+ return {12, {1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 1}, {43}};+}++StaticInputs prefill_chunk_with_position_baseline() {+ return {8, {1, 1, 1, 1, 1, 0, 0, 0, 0, 1, 1, 1}, {0, 42, 43, 44}};+}++void expect_rows_eq(const std::vector<float>& actual,+ const std::vector<float>& expected,+ const StaticInputs& in,+ bool only_valid_rows) {+ const size_t total = in.attention_mask.size();+ for (size_t q = 0; q < in.position_ids.size(); ++q) {+ if (only_valid_rows && in.attention_mask[in.past_capacity + q] == 0) {+ continue;+ }+ for (size_t k = 0; k < total; ++k) {+ EXPECT_EQ(actual[q * total + k], expected[q * total + k]) << "query " << q << ", key " << k;+ }+ }+}++class DistanceSlidingMaskTransformationTest : public TransformationTestsF {+protected:+ void SetUp() override {+ TransformationTestsF::SetUp();+ manager.register_pass<ov::npuw::PatchSlidingWindowMask>();+ }+};++std::shared_ptr<ov::Model> patched(std::shared_ptr<ov::Model> model) {+ ov::npuw::PatchSlidingWindowMask().run_on_model(model);+ return model;+}++} // namespace++TEST_F(DistanceSlidingMaskTransformationTest, RewritesOnlyTheWindowCondition) {+ model = getModel();+ model_ref = getModelRef();+}++TEST_F(DistanceSlidingMaskTransformationTest, SecondRunLeavesTheGraphUnchanged) {+ model = getModel();+ model_ref = getModelRef();+ manager.register_pass<ov::npuw::PatchSlidingWindowMask>();+}++// A non-positive window is not a sliding window.+TEST_F(DistanceSlidingMaskTransformationTest, NotAppliedForNonPositiveWindow) {+ model = getModel(/*window=*/0);+}++// The ranges must be built from the model's own attention mask.+TEST_F(DistanceSlidingMaskTransformationTest, NotAppliedForAnotherMask) {+ model = getModel(kWindow, /*separate_length_mask=*/true);+}++// Without the patch, Q is the static past length: every left-aligned past token is out of the window.+TEST(DistanceSlidingMaskTest, UnpatchedMaskDropsHistory) {+ const auto sliding = evaluate(getModel(), generate_step())[0];+ for (size_t k = 0; k < 6; ++k) {+ EXPECT_EQ(sliding[k], kFill) << "key " << k;+ }+}++TEST(DistanceSlidingMaskTest, GenerateStepKeepsHistoryWithinWindow) {+ const auto in = generate_step();+ expect_rows_eq(evaluate(patched(getModel()), in)[0], reference_sliding_mask(in), in, /*only_valid_rows=*/false);+}++TEST(DistanceSlidingMaskTest, PrefillChunkKeepsHistoryWithinWindow) {+ const auto in = prefill_chunk();+ expect_rows_eq(evaluate(patched(getModel()), in)[0], reference_sliding_mask(in), in, /*only_valid_rows=*/false);+}++// The window is measured between cache slots, so a nonzero baseline of the positions changes nothing.+TEST(DistanceSlidingMaskTest, IndependentOfPositionBaseline) {+ for (const auto& in : {generate_step_with_position_baseline(), prefill_chunk_with_position_baseline()}) {+ expect_rows_eq(evaluate(patched(getModel()), in)[0],+ reference_sliding_mask(in),+ in,+ /*only_valid_rows=*/false);+ }+}++// The full attention mask shares the causal/padding Select with the sliding one and must stay as it is.+TEST(DistanceSlidingMaskTest, FullAttentionMaskIsUnchanged) {+ for (const auto& in : {generate_step(), prefill_chunk()}) {+ expect_rows_eq(evaluate(patched(getModel()), in)[1],+ evaluate(getModel(), in)[1],+ in,+ /*only_valid_rows=*/false);+ }+}