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] Mask linear-attention padding in chunked prefill (#39125)
Weiguo Meng41e0f2d7a21e
diff --git a/src/plugins/intel_npu/src/plugin/npuw/llm_compiled_model.cpp b/src/plugins/intel_npu/src/plugin/npuw/llm_compiled_model.cppindex a22845dd959..94407598eb3 100644--- a/src/plugins/intel_npu/src/plugin/npuw/llm_compiled_model.cpp+++ b/src/plugins/intel_npu/src/plugin/npuw/llm_compiled_model.cpp@@ -24,6 +24,7 @@#include "npuw_transformations/duplicate_shared_kv_concat.hpp"#include "npuw_transformations/insert_vocab_sub128.hpp"#include "npuw_transformations/lora_stateful_to_stateless.hpp"+#include "npuw_transformations/mask_linear_attention_padding.hpp"#include "npuw_transformations/optimize_lincache_layout.hpp"#include "npuw_transformations/optimize_value_tensors.hpp"#include "npuw_transformations/patch_sliding_window_mask.hpp"@@ -1085,6 +1086,10 @@ ov::npuw::LLMCompiledModel::LLMCompiledModel(const std::shared_ptr<ov::Model>& m0,true).run_on_model(prefill_model);++ // A partial chunk is left-padded. Keep the conv/ssm state of linear-attention layers+ // (hybrid models) unaffected by the padding that sits between two real chunks.+ ov::npuw::MaskLinearAttentionPadding().run_on_model(prefill_model);} else {ov::npuw::ReshapeToStatic(m_kvcache_desc.max_prompt_size,m_kvcache_desc.max_prompt_size,diff --git a/src/plugins/intel_npu/src/plugin/npuw/npuw_transformations/mask_linear_attention_padding.cpp b/src/plugins/intel_npu/src/plugin/npuw/npuw_transformations/mask_linear_attention_padding.cppnew file mode 100644index 00000000000..f568b9afe33--- /dev/null+++ b/src/plugins/intel_npu/src/plugin/npuw/npuw_transformations/mask_linear_attention_padding.cpp@@ -0,0 +1,411 @@+// Copyright (C) 2018-2026 Intel Corporation+// SPDX-License-Identifier: Apache-2.0+//++#include "mask_linear_attention_padding.hpp"++#include <algorithm>+#include <map>+#include <optional>+#include <set>+#include <string>+#include <utility>+#include <vector>++#include "../logging.hpp"+#include "../util.hpp"+#include "openvino/core/validation_util.hpp"+#include "openvino/op/add.hpp"+#include "openvino/op/concat.hpp"+#include "openvino/op/constant.hpp"+#include "openvino/op/convert.hpp"+#include "openvino/op/exp.hpp"+#include "openvino/op/loop.hpp"+#include "openvino/op/multiply.hpp"+#include "openvino/op/parameter.hpp"+#include "openvino/op/reduce_sum.hpp"+#include "openvino/op/scatter_update.hpp"+#include "openvino/op/slice.hpp"+#include "openvino/op/subtract.hpp"+#include "openvino/op/transpose.hpp"+#include "openvino/op/unsqueeze.hpp"+#include "right_align_mask_slice_for_conv.hpp"++namespace {++namespace opv0 = ov::op::v0;+namespace opv1 = ov::op::v1;+namespace opv8 = ov::op::v8;++constexpr size_t kSeqAxis = 2;++struct ConvSite {+ std::shared_ptr<opv0::Concat> concat; // Concat(past [B,C,K], x [B,C,L]) along the sequence axis+ size_t kernel; // K, the width of the carried history+ size_t seq_len; // L, the number of tokens of the chunk+ std::shared_ptr<opv0::Parameter> state; // the past conv state parameter the history comes from+};++struct SsmSite {+ std::shared_ptr<ov::op::v5::Loop> loop;+ size_t gate_input; // Loop input index of the per-token decay g+ size_t beta_input; // Loop input index of the per-token update gate beta+ size_t seq_len; // L, the number of tokens of the chunk+ std::shared_ptr<opv0::Parameter> state; // the past ssm state parameter the recurrence starts from+};++bool has_name(const ov::descriptor::Tensor& tensor, const char* kind, const std::string& past_or_present) {+ const std::string needle = std::string(".") + kind + ".";+ return std::any_of(tensor.get_names().begin(), tensor.get_names().end(), [&](const std::string& name) {+ return name.find(needle) != std::string::npos && ov::npuw::util::matchLinCacheString(name, past_or_present);+ });+}++bool is_past_state(const ov::Output<ov::Node>& output, const char* kind) {+ const auto param = ov::as_type_ptr<opv0::Parameter>(output.get_node_shared_ptr());+ return param && has_name(param->get_output_tensor(0), kind, "past");+}++// Concat(past conv state, x) along the last axis. The state may reach the Concat directly or through a+// Transpose which re-lays it out.+std::optional<ConvSite> match_conv(const std::shared_ptr<ov::Node>& node) {+ const auto concat = ov::as_type_ptr<opv0::Concat>(node);+ if (!concat || concat->get_input_size() != 2) {+ return std::nullopt;+ }+ const auto& out_shape = concat->get_output_partial_shape(0);+ if (out_shape.rank().is_dynamic() || out_shape.size() != 3 ||+ ov::util::normalize_axis(concat->get_axis(), 3) != static_cast<int64_t>(kSeqAxis)) {+ return std::nullopt;+ }++ auto state = concat->input_value(0);+ if (const auto transpose = ov::as_type_ptr<opv1::Transpose>(state.get_node_shared_ptr())) {+ state = transpose->input_value(0);+ }+ if (!is_past_state(state, "conv")) {+ return std::nullopt;+ }+ const auto state_param = ov::as_type_ptr<opv0::Parameter>(state.get_node_shared_ptr());++ // The output rank does not prove the input ranks: one rank-dynamic input is enough to infer it.+ const auto& history = concat->get_input_partial_shape(0);+ const auto& tokens = concat->get_input_partial_shape(1);+ for (const auto& shape : {history, tokens}) {+ if (shape.rank().is_dynamic() || shape.size() != 3 || shape[kSeqAxis].is_dynamic()) {+ return std::nullopt;+ }+ }+ return ConvSite{concat,+ static_cast<size_t>(history[kSeqAxis].get_length()),+ static_cast<size_t>(tokens[kSeqAxis].get_length()),+ state_param};+}++// The only consumer of `output`, when it is of type T.+template <class T>+std::shared_ptr<ov::Node> sole_consumer(const ov::Output<ov::Node>& output) {+ const auto targets = output.get_target_inputs();+ if (targets.size() != 1 || !ov::is_type<T>(targets.begin()->get_node())) {+ return nullptr;+ }+ return targets.begin()->get_node()->shared_from_this();+}++// Skips an optional Convert (e.g. f16 -> f32) that is the only consumer of the node.+std::shared_ptr<ov::Node> skip_convert(const std::shared_ptr<ov::Node>& node) {+ if (const auto convert = sole_consumer<opv0::Convert>(node->output(0))) {+ return convert;+ }+ return node;+}++// Skips an optional Convert that produces the value, looking at the node that feeds it.+std::shared_ptr<ov::Node> skip_convert_producer(const std::shared_ptr<ov::Node>& node) {+ return ov::is_type<opv0::Convert>(node) ? node->input_value(0).get_node_shared_ptr() : node;+}++// g: [Convert] -> Exp -> Unsqueeze -> Multiply(state, .). Returns that Multiply, the decayed state.+std::shared_ptr<ov::Node> match_gate(const std::shared_ptr<opv0::Parameter>& gate) {+ auto node = sole_consumer<opv0::Exp>(skip_convert(gate)->output(0));+ node = node ? sole_consumer<opv0::Unsqueeze>(node->output(0)) : nullptr;+ return node ? sole_consumer<opv1::Multiply>(node->output(0)) : nullptr;+}++// beta: [Convert] -> Multiply(delta, .) -> Unsqueeze -> Multiply(key, .) -> Add(decayed_state, .).+// Returns that Add, the updated state.+std::shared_ptr<ov::Node> match_beta(const std::shared_ptr<opv0::Parameter>& beta,+ const std::shared_ptr<ov::Node>& decayed_state) {+ auto node = sole_consumer<opv1::Multiply>(skip_convert(beta)->output(0));+ node = node ? sole_consumer<opv0::Unsqueeze>(node->output(0)) : nullptr;+ node = node ? sole_consumer<opv1::Multiply>(node->output(0)) : nullptr;+ node = node ? sole_consumer<opv1::Add>(node->output(0)) : nullptr;+ const bool adds_to_decayed_state = node && (node->input_value(0).get_node() == decayed_state.get() ||+ node->input_value(1).get_node() == decayed_state.get());+ return adds_to_decayed_state ? node : nullptr;+}++// The recurrence Loop of GatedDeltaNet: q, k, v are sliced as [B,H,L,D] and the two per-token scalars+// g and beta as [B,H,L]. g and beta are identified by the body, see match_gate and match_beta.+std::optional<SsmSite> match_ssm(const std::shared_ptr<ov::Node>& node) {+ const auto loop = ov::as_type_ptr<ov::op::v5::Loop>(node);+ if (!loop) {+ return std::nullopt;+ }+ const auto body = loop->get_function();+ std::vector<std::pair<size_t, std::shared_ptr<opv0::Parameter>>> per_token_scalars;+ for (const auto& desc : loop->get_input_descriptions()) {+ const auto slice = ov::as_type_ptr<ov::op::util::SubGraphOp::SliceInputDescription>(desc);+ if (!slice || slice->m_axis != static_cast<int64_t>(kSeqAxis)) {+ continue;+ }+ const auto& shape = loop->get_input_partial_shape(slice->m_input_index);+ if (shape.rank().is_dynamic() || shape.size() != 3) {+ continue;+ }+ per_token_scalars.emplace_back(slice->m_input_index, body->get_parameters().at(slice->m_body_parameter_index));+ }+ if (per_token_scalars.size() != 2) {+ return std::nullopt;+ }++ // The scalars are told apart by how the body uses them, not by elimination: g decays the state and beta+ // scales the delta that is added to the decayed state, so a zero g / beta is an identity step.+ size_t gate = 0;+ size_t beta = 0;+ std::shared_ptr<ov::Node> decayed_state;+ std::shared_ptr<ov::Node> updated_state;+ bool found = false;+ for (const auto& [gate_candidate, beta_candidate] : {std::pair{0u, 1u}, std::pair{1u, 0u}}) {+ decayed_state = match_gate(per_token_scalars[gate_candidate].second);+ updated_state = decayed_state ? match_beta(per_token_scalars[beta_candidate].second, decayed_state) : nullptr;+ if (updated_state) {+ gate = per_token_scalars[gate_candidate].first;+ beta = per_token_scalars[beta_candidate].first;+ found = true;+ break;+ }+ }+ if (!found) {+ return std::nullopt;+ }+ const auto& seq_dim = loop->get_input_partial_shape(gate)[kSeqAxis];+ if (seq_dim.is_dynamic()) {+ return std::nullopt;+ }++ std::shared_ptr<opv0::Parameter> state;+ std::shared_ptr<opv0::Parameter> state_in;+ std::shared_ptr<ov::op::util::SubGraphOp::MergedInputDescription> state_merge;+ for (const auto& desc : loop->get_input_descriptions()) {+ auto source = loop->input_value(desc->m_input_index);+ if (ov::is_type<opv0::Convert>(source.get_node())) {+ source = source.get_node()->input_value(0);+ }+ if (is_past_state(source, "ssm")) {+ if (state) {+ return std::nullopt;+ }+ state = ov::as_type_ptr<opv0::Parameter>(source.get_node_shared_ptr());+ state_in = body->get_parameters().at(desc->m_body_parameter_index);+ state_merge = ov::as_type_ptr<ov::op::util::SubGraphOp::MergedInputDescription>(desc);+ }+ }+ if (!state || !state_merge) {+ return std::nullopt;+ }++ // Nothing else updates the state after the delta is added: the Add (optionally converted back) is+ // what the next iteration starts from.+ const auto carried = body->get_results().at(state_merge->m_body_value_index)->input_value(0).get_node_shared_ptr();+ if (skip_convert_producer(carried) != updated_state) {+ return std::nullopt;+ }++ // The decay is applied to the state the recurrence carries, not to some other tensor.+ const auto is_state_in = [&](const ov::Output<ov::Node>& value) {+ const auto node = ov::is_type<opv0::Convert>(value.get_node()) ? value.get_node()->input_value(0).get_node()+ : value.get_node();+ return node == state_in.get();+ };+ if (!is_state_in(decayed_state->input_value(0)) && !is_state_in(decayed_state->input_value(1))) {+ return std::nullopt;+ }+ return SsmSite{loop, gate, beta, static_cast<size_t>(seq_dim.get_length()), state};+}++// True when the sites together consume every past state parameter of the given kind.+template <class Sites>+bool covers_all_states(const std::shared_ptr<ov::Model>& model, const char* kind, const Sites& sites) {+ std::set<const ov::Node*> covered;+ for (const auto& site : sites) {+ covered.insert(site.state.get());+ }+ for (const auto& param : model->get_parameters()) {+ if (has_name(param->get_output_tensor(0), kind, "past") && covered.count(param.get()) == 0) {+ return false;+ }+ }+ return true;+}++std::shared_ptr<opv0::Parameter> find_attention_mask(const std::shared_ptr<ov::Model>& model) {+ for (const auto& param : model->get_parameters()) {+ const auto& names = param->get_output_tensor(0).get_names();+ if (names.count(ov::npuw::attention_mask_name) != 0 ||+ param->get_friendly_name() == ov::npuw::attention_mask_name) {+ return param;+ }+ }+ return nullptr;+}++std::shared_ptr<opv0::Constant> i64_const(const std::vector<int64_t>& values, const ov::Shape& shape) {+ return opv0::Constant::create(ov::element::i64, shape, values);+}++std::shared_ptr<opv0::Constant> i64_scalar(int64_t value) {+ return i64_const({value}, ov::Shape{});+}++std::shared_ptr<opv0::Constant> i64_vector(int64_t value) {+ return i64_const({value}, ov::Shape{1});+}++// Columns of the conv input that receive the history: pad + [0, K). The real tokens of the chunk start at+// column K + pad of the Concat, so writing the history there puts it right in front of them:+// [h0 h1 h2 h3 | 0 0 x2 x3] -> [h0 h1 h0 h1 h2 h3 x2 x3] (K = 4, L = 4, pad = 2).+// The leading `pad` columns keep whatever they held: they only reach the convolution outputs of the padded+// positions, which are identity steps for the ssm state and are masked out everywhere else.+ov::Output<ov::Node> make_history_columns(const ov::Output<ov::Node>& pad, size_t kernel) {+ std::vector<int64_t> offsets(kernel);+ for (size_t i = 0; i < kernel; ++i) {+ offsets[i] = static_cast<int64_t>(i);+ }+ return std::make_shared<opv1::Add>(pad, i64_const(offsets, ov::Shape{kernel}))->output(0);+}++} // namespace++bool ov::npuw::MaskLinearAttentionPadding::run_on_model(const std::shared_ptr<ov::Model>& model) {+ size_t past_conv_count = 0;+ size_t past_ssm_count = 0;+ for (const auto& param : model->get_parameters()) {+ past_conv_count += has_name(param->get_output_tensor(0), "conv", "past") ? 1u : 0u;+ past_ssm_count += has_name(param->get_output_tensor(0), "ssm", "past") ? 1u : 0u;+ }+ if (past_conv_count == 0 && past_ssm_count == 0) {+ return false;+ }++ std::vector<ConvSite> conv_sites;+ std::vector<SsmSite> ssm_sites;+ for (const auto& node : model->get_ordered_ops()) {+ if (auto conv = match_conv(node)) {+ conv_sites.push_back(*conv);+ } else if (auto ssm = match_ssm(node)) {+ ssm_sites.push_back(*ssm);+ }+ }+ if (!covers_all_states(model, "conv", conv_sites) || !covers_all_states(model, "ssm", ssm_sites)) {+ LOG_WARN("MaskLinearAttentionPadding: "+ << conv_sites.size() << " conv and " << ssm_sites.size() << " ssm sites do not cover all "+ << past_conv_count << " conv and " << past_ssm_count+ << " ssm states, model left unchanged: a partial prefill chunk may corrupt them");+ return false;+ }++ // The sequence length of the chunk must be the same for all states.+ std::optional<size_t> seq_len;+ auto accept_seq_len = [&](size_t length) {+ if (seq_len && *seq_len != length) {+ return false;+ }+ seq_len = length;+ return true;+ };+ for (const auto& site : conv_sites) {+ if (!accept_seq_len(site.seq_len)) {+ LOG_WARN("MaskLinearAttentionPadding: conv sequence length differs between layers, model left unchanged: a "+ "partial prefill chunk may corrupt the states");+ return false;+ }+ }+ for (const auto& site : ssm_sites) {+ if (!accept_seq_len(site.seq_len)) {+ LOG_WARN("MaskLinearAttentionPadding: ssm sequence length differs between layers, model left unchanged: a "+ "partial prefill chunk may corrupt the states");+ return false;+ }+ }++ const auto attention_mask = find_attention_mask(model);+ if (!attention_mask || attention_mask->get_partial_shape().is_dynamic() ||+ attention_mask->get_partial_shape().size() != 2 ||+ static_cast<size_t>(attention_mask->get_partial_shape()[1].get_length()) < *seq_len) {+ LOG_WARN(+ "MaskLinearAttentionPadding: static rank-2 attention_mask is not found, model left unchanged: a partial "+ "prefill chunk may corrupt the states");+ return false;+ }++ // Mask of the chunk: the last L columns of the attention mask. The padding is at its beginning.+ const int64_t total = attention_mask->get_partial_shape()[1].get_length();+ const int64_t len = static_cast<int64_t>(*seq_len);+ const auto chunk_mask = std::make_shared<opv8::Slice>(attention_mask,+ i64_vector(total - len),+ i64_vector(total),+ i64_vector(1),+ i64_vector(1));+ chunk_mask->set_friendly_name("lincache_chunk_mask");+ const auto valid_tokens = std::make_shared<opv1::ReduceSum>(chunk_mask, i64_const({0, 1}, ov::Shape{2}), false);+ const auto pad = std::make_shared<opv1::Subtract>(i64_scalar(len), valid_tokens);++ std::map<size_t, ov::Output<ov::Node>> columns_by_kernel;+ const auto seq_axis = i64_scalar(static_cast<int64_t>(kSeqAxis));+ for (const auto& site : conv_sites) {+ auto columns_it = columns_by_kernel.find(site.kernel);+ if (columns_it == columns_by_kernel.end()) {+ columns_it = columns_by_kernel.emplace(site.kernel, make_history_columns(pad, site.kernel)).first;+ }++ // The history [B, C, K] is written over K columns of the Concat, nothing else of it is touched.+ const auto consumers = site.concat->output(0).get_target_inputs();+ const auto reordered = std::make_shared<ov::op::v3::ScatterUpdate>(site.concat,+ columns_it->second,+ site.concat->input_value(0),+ seq_axis);+ reordered->set_friendly_name(site.concat->get_friendly_name() + "/pad_aware");+ for (auto consumer : consumers) {+ consumer.replace_source_output(reordered);+ }+ }++ if (!ssm_sites.empty()) {+ // [B, 1, L], broadcast over the heads of the per-token [B, H, L] scalars.+ const auto mask_per_token = std::make_shared<opv0::Unsqueeze>(chunk_mask, i64_vector(1));+ // One mask per precision, shared by all the gates and betas of that precision.+ std::map<ov::element::Type_t, ov::Output<ov::Node>> mask_by_type;+ for (const auto& site : ssm_sites) {+ for (const auto input_idx : {site.gate_input, site.beta_input}) {+ const auto source = site.loop->input_value(input_idx);+ const auto type = source.get_element_type();+ auto mask_it = mask_by_type.find(type);+ if (mask_it == mask_by_type.end()) {+ ov::Output<ov::Node> mask = mask_per_token;+ if (type != mask.get_element_type()) {+ mask = std::make_shared<opv0::Convert>(mask, type);+ }+ mask_it = mask_by_type.emplace(type, mask).first;+ }+ const auto masked = std::make_shared<opv1::Multiply>(source, mask_it->second);+ site.loop->input(input_idx).replace_source_output(masked);+ }+ }+ }++ model->validate_nodes_and_infer_types();+ LOG_DEBUG("MaskLinearAttentionPadding: " << conv_sites.size() << " conv and " << ssm_sites.size()+ << " ssm states are padding-safe (chunk length " << len << ")");+ return true;+}diff --git a/src/plugins/intel_npu/src/plugin/npuw/npuw_transformations/mask_linear_attention_padding.hpp b/src/plugins/intel_npu/src/plugin/npuw/npuw_transformations/mask_linear_attention_padding.hppnew file mode 100644index 00000000000..997d26350f4--- /dev/null+++ b/src/plugins/intel_npu/src/plugin/npuw/npuw_transformations/mask_linear_attention_padding.hpp@@ -0,0 +1,54 @@+// Copyright (C) 2018-2026 Intel Corporation+// SPDX-License-Identifier: Apache-2.0+//++#pragma once++#include "openvino/pass/pass.hpp"++namespace ov {+namespace npuw {++// Makes the recurrent state of linear-attention layers (GatedDeltaNet / Mamba-style /+// LFM2 short-conv mixers) insensitive to the left padding of a static-shape prefill chunk.+//+// NPUW feeds a partial prefill chunk left-padded: [pad ... pad | real tokens]. The model+// only zeroes the hidden states of the padded positions through the attention mask, which is+// not enough once a non-zero state is carried in from the previous chunk:+// * conv: Concat(past_conv, x) puts the padded positions between the carried history+// and the first real token, so the first real tokens convolve over zeros instead+// of the history, and the present conv state is built from the wrong columns.+// * ssm: a padded position still decays the state (g = -exp(A) * softplus(dt_bias) != 0)+// and still updates it (beta = sigmoid(0) = 0.5, k and v can be non-zero where the+// conv window overlaps the history).+//+// The pass requires static shapes (it runs after ReshapeToStatic) and a prefill batch of 1.+// All sequence lengths are read from the model, nothing is specific to a chunk size.+//+// conv: the Concat(past [B,C,K], x [B,C,L]) is followed by a ScatterUpdate that writes the history+// over the K columns right in front of the first real token, pad + [0, K):+// [h0 h1 h2 h3 0 0 x2 x3] -> [h0 h1 h0 h1 h2 h3 x2 x3] (K=4, L=4, pad=2).+// Only K columns are written, no second tensor of the Concat's size is computed. The leading `pad`+// columns are left as they are: they only feed the outputs of padded positions.+// `pad = L - sum(attention_mask[:, -L:])` is computed in the graph, so the chunk+// may be full (pad = 0, identity) or partial. Both the convolution and the present+// state, which is the last K columns of the Concat, consume the re-ordered tensor.+// ssm: the per-token decay `g` and update gate `beta` feeding the recurrence Loop are+// multiplied by the mask of the chunk, so a padded position is an identity step+// (exp(0) * state, no update).+//+// The pass is all-or-nothing: if any conv or ssm state of the model is not recognized, the model+// is left unchanged and false is returned. A recurrence Loop is recognized by its body: g feeds+// [Convert] -> Exp -> Unsqueeze -> Multiply with the carried state, beta only scales the delta that is+// added to that decayed state, and the sum (optionally converted) is what the next iteration starts from+// (the GatedDeltaNet layout), so a zero g and beta is an identity step.+class MaskLinearAttentionPadding : public ov::pass::ModelPass {+public:+ OPENVINO_MODEL_PASS_RTTI("ov::npuw::MaskLinearAttentionPadding");++ // Returns true when every conv/ssm state of the model has been made padding-safe.+ bool run_on_model(const std::shared_ptr<ov::Model>& model) override;+};++} // namespace npuw+} // namespace ovdiff --git a/src/plugins/intel_npu/src/plugin/sources.cmake b/src/plugins/intel_npu/src/plugin/sources.cmakeindex a647ad08f97..54c31d13bd2 100644--- a/src/plugins/intel_npu/src/plugin/sources.cmake+++ b/src/plugins/intel_npu/src/plugin/sources.cmake@@ -143,6 +143,8 @@ set(NPUW_SOURCES${CMAKE_CURRENT_SOURCE_DIR}/npuw/npuw_transformations/kv_cache_compressed.hpp${CMAKE_CURRENT_SOURCE_DIR}/npuw/npuw_transformations/lora_stateful_to_stateless.cpp${CMAKE_CURRENT_SOURCE_DIR}/npuw/npuw_transformations/lora_stateful_to_stateless.hpp+ ${CMAKE_CURRENT_SOURCE_DIR}/npuw/npuw_transformations/mask_linear_attention_padding.cpp+ ${CMAKE_CURRENT_SOURCE_DIR}/npuw/npuw_transformations/mask_linear_attention_padding.hpp${CMAKE_CURRENT_SOURCE_DIR}/npuw/npuw_transformations/optimize_lincache_layout.cpp${CMAKE_CURRENT_SOURCE_DIR}/npuw/npuw_transformations/optimize_lincache_layout.hpp${CMAKE_CURRENT_SOURCE_DIR}/npuw/npuw_transformations/optimize_value_tensors.cppdiff --git a/src/plugins/intel_npu/tests/unit/CMakeLists.txt b/src/plugins/intel_npu/tests/unit/CMakeLists.txtindex fec89e8b8e5..ce0a586b323 100644--- a/src/plugins/intel_npu/tests/unit/CMakeLists.txt+++ b/src/plugins/intel_npu/tests/unit/CMakeLists.txt@@ -120,6 +120,7 @@ ov_add_test_target(${OpenVINO_SOURCE_DIR}/src/plugins/intel_npu/src/plugin/npuw/npuw_transformations/drop_zp_subtract.cpp${OpenVINO_SOURCE_DIR}/src/plugins/intel_npu/src/plugin/npuw/npuw_transformations/untangle_dq_scale.cpp${OpenVINO_SOURCE_DIR}/src/plugins/intel_npu/src/plugin/npuw/npuw_transformations/lora_stateful_to_stateless.cpp+ ${OpenVINO_SOURCE_DIR}/src/plugins/intel_npu/src/plugin/npuw/npuw_transformations/mask_linear_attention_padding.cpp${OpenVINO_SOURCE_DIR}/src/plugins/intel_npu/src/plugin/npuw/npuw_transformations/optimize_lincache_layout.cpp${OpenVINO_SOURCE_DIR}/src/plugins/intel_npu/src/plugin/npuw/npuw_transformations/optimize_value_tensors.cpp${OpenVINO_SOURCE_DIR}/src/plugins/intel_npu/src/plugin/npuw/npuw_transformations/shrink_sliding_window_kv_cache.cpp@@ -213,6 +214,7 @@ target_sources(${TARGET_NAME} PRIVATE${CMAKE_CURRENT_SOURCE_DIR}/npuw/preserve_const_matmul_pattern_test.cpp${CMAKE_CURRENT_SOURCE_DIR}/npuw/compress_dict_matmul_f32_test.cpp${CMAKE_CURRENT_SOURCE_DIR}/npuw/pipeline_passes/add_position_ids_param_test.cpp+ ${CMAKE_CURRENT_SOURCE_DIR}/npuw/pipeline_passes/mask_linear_attention_padding_test.cpp${CMAKE_CURRENT_SOURCE_DIR}/npuw/pipeline_passes/right_align_mask_slice_for_conv_test.cpp${CMAKE_CURRENT_SOURCE_DIR}/npuw/pipeline_passes/collapse_unqdq_test.cpp${CMAKE_CURRENT_SOURCE_DIR}/npuw/pipeline_passes/conv_to_matmul_test.cppdiff --git a/src/plugins/intel_npu/tests/unit/npuw/pipeline_passes/mask_linear_attention_padding_test.cpp b/src/plugins/intel_npu/tests/unit/npuw/pipeline_passes/mask_linear_attention_padding_test.cppnew file mode 100644index 00000000000..becde3995a8--- /dev/null+++ b/src/plugins/intel_npu/tests/unit/npuw/pipeline_passes/mask_linear_attention_padding_test.cpp@@ -0,0 +1,561 @@+// Copyright (C) 2018-2026 Intel Corporation+// SPDX-License-Identifier: Apache-2.0+//++#include "npuw_transformations/mask_linear_attention_padding.hpp"++#include <gtest/gtest.h>++#include <algorithm>+#include <cmath>+#include <cstring>+#include <functional>+#include <limits>+#include <map>+#include <set>+#include <string>+#include <tuple>+#include <vector>++#include "llm_pass_test_fixture.hpp"+#include "npuw_transformations/kv_axes_position.hpp"+#include "npuw_transformations/optimize_lincache_layout.hpp"+#include "npuw_transformations/reshape_to_static.hpp"+#include "openvino/op/constant.hpp"+#include "openvino/op/convert.hpp"+#include "openvino/op/exp.hpp"+#include "openvino/op/loop.hpp"+#include "openvino/op/multiply.hpp"+#include "openvino/op/negative.hpp"+#include "openvino/op/scatter_update.hpp"+#include "openvino/op/transpose.hpp"+#include "openvino/openvino.hpp"+#include "openvino/pass/stateful_to_stateless.hpp"++namespace {++using ov::test::npuw::RecordingFactory;++constexpr uint32_t kTotal = 32; // static attention_mask length of the prefill model+constexpr uint32_t kStored = 8; // tokens already processed by the previous chunks++class MaskLinearAttentionPaddingTest : public ov::test::npuw::LLMPassTestFixture {+protected:+ static std::shared_ptr<ov::Model> stateless(std::shared_ptr<ov::Model> model) {+ ov::pass::StatefulToStateless().run_on_model(model);+ return model;+ }++ // Static prefill model as NPUW builds it for a chunked prefill with the given chunk size.+ static std::shared_ptr<ov::Model> make_static(const std::shared_ptr<ov::Model>& stateless_model, uint32_t chunk) {+ auto model = stateless_model->clone();+ ov::npuw::ReshapeToStatic(chunk, kTotal, ov::npuw::KVAxesPosition{0u, 2u}, 0u, 0u, true).run_on_model(model);+ return model;+ }++ static std::map<std::string, ov::Tensor> run(const std::shared_ptr<ov::Model>& model,+ uint32_t chunk,+ uint32_t padding,+ const std::map<std::string, ov::Tensor>& lincache_past) {+ ov::Core core;+ auto compiled = core.compile_model(model, "CPU", ov::hint::inference_precision(ov::element::f32));+ auto request = compiled.create_infer_request();++ for (const auto& input : compiled.inputs()) {+ const auto name = input.get_any_name();+ auto tensor = request.get_tensor(input);+ std::memset(tensor.data(), 0, tensor.get_byte_size());+ if (name == "input_ids") {+ auto* ids = tensor.data<int64_t>();+ // Real tokens right-aligned, `padding` pad tokens in front of them.+ for (uint32_t i = padding; i < chunk; ++i) {+ ids[i] = 3 + 7 * (i - padding);+ }+ } else if (name == "attention_mask") {+ auto* mask = tensor.data<int64_t>();+ for (uint32_t i = 0; i < kStored; ++i) {+ mask[i] = 1;+ }+ for (uint32_t i = kTotal - chunk + padding; i < kTotal; ++i) {+ mask[i] = 1;+ }+ } else if (name == "position_ids") {+ auto* pos = tensor.data<int64_t>();+ for (uint32_t i = padding; i < chunk; ++i) {+ pos[i] = kStored + i - padding;+ }+ } else if (lincache_past.count(name)) {+ lincache_past.at(name).copy_to(tensor);+ }+ }+ request.infer();++ std::map<std::string, ov::Tensor> outputs;+ for (const auto& output : compiled.outputs()) {+ const auto name = output.get_any_name();+ if (name.find("cache_params.present") != std::string::npos || name == "logits") {+ ov::Tensor copy(output.get_element_type(), output.get_shape());+ request.get_tensor(output).copy_to(copy);+ outputs[name] = copy;+ }+ }+ return outputs;+ }++ static std::map<std::string, ov::Tensor> make_lincache_past(const std::shared_ptr<ov::Model>& model) {+ std::map<std::string, ov::Tensor> past;+ size_t seed = 1;+ for (const auto& input : model->inputs()) {+ const auto name = input.get_any_name();+ if (name.find("cache_params.past") == std::string::npos) {+ continue;+ }+ ov::Tensor tensor(input.get_element_type(), input.get_shape());+ auto* data = tensor.data<float>();+ for (size_t i = 0; i < tensor.get_size(); ++i) {+ data[i] = 0.5f * std::sin(0.37f * static_cast<float>(i + 11 * seed));+ }+ ++seed;+ past[name] = tensor;+ }+ return past;+ }++ // Number of Loop inputs (summed over all Loops) that are fed by a Multiply, i.e. masked g / beta.+ static size_t count_masked_loop_inputs(const std::shared_ptr<ov::Model>& model) {+ size_t masked = 0;+ for (const auto& node : model->get_ordered_ops()) {+ if (auto loop = ov::as_type_ptr<ov::op::v5::Loop>(node)) {+ for (const auto& desc : loop->get_input_descriptions()) {+ masked += ov::is_type<ov::op::v1::Multiply>(loop->input_value(desc->m_input_index).get_node());+ }+ }+ }+ return masked;+ }++ // Feeds the gate of every recurrence Loop in f16 and converts it back in the body right before Exp,+ // the mixed-precision layout FuseGatedDeltaNet also accepts.+ static void convert_gate_before_exp(const std::shared_ptr<ov::Model>& model) {+ for (const auto& node : model->get_ordered_ops()) {+ const auto loop = ov::as_type_ptr<ov::op::v5::Loop>(node);+ if (!loop) {+ continue;+ }+ const auto body = loop->get_function();+ for (const auto& desc : loop->get_input_descriptions()) {+ const auto param = body->get_parameters().at(desc->m_body_parameter_index);+ const auto targets = param->output(0).get_target_inputs();+ const bool is_gate = std::any_of(targets.begin(), targets.end(), [](const ov::Input<ov::Node>& t) {+ return ov::is_type<ov::op::v0::Exp>(t.get_node());+ });+ if (!is_gate) {+ continue;+ }+ const auto type = param->get_element_type();+ param->set_element_type(ov::element::f16);+ const auto back = std::make_shared<ov::op::v0::Convert>(param, type);+ for (auto target : targets) {+ target.replace_source_output(back);+ }+ const auto source = loop->input_value(desc->m_input_index);+ loop->input(desc->m_input_index)+ .replace_source_output(std::make_shared<ov::op::v0::Convert>(source, ov::element::f16));+ }+ body->validate_nodes_and_infer_types();+ }+ model->validate_nodes_and_infer_types();+ }++ // Applies `edit` to the body of every recurrence Loop together with its per-token g and beta parameters.+ template <class Edit>+ static void edit_loop_bodies(const std::shared_ptr<ov::Model>& model, const Edit& edit) {+ for (const auto& node : model->get_ordered_ops()) {+ const auto loop = ov::as_type_ptr<ov::op::v5::Loop>(node);+ if (!loop) {+ continue;+ }+ const auto body = loop->get_function();+ std::shared_ptr<ov::op::v0::Parameter> gate;+ std::shared_ptr<ov::op::v0::Parameter> beta;+ for (const auto& desc : loop->get_input_descriptions()) {+ if (!ov::is_type<ov::op::util::SubGraphOp::SliceInputDescription>(desc) ||+ loop->get_input_partial_shape(desc->m_input_index).size() != 3) {+ continue;+ }+ const auto param = body->get_parameters().at(desc->m_body_parameter_index);+ const auto targets = param->output(0).get_target_inputs();+ const bool feeds_exp = std::any_of(targets.begin(), targets.end(), [](const ov::Input<ov::Node>& t) {+ return ov::is_type<ov::op::v0::Exp>(t.get_node());+ });+ (feeds_exp ? gate : beta) = param;+ }+ ASSERT_TRUE(gate && beta);+ edit(body, gate, beta);+ body->validate_nodes_and_infer_types();+ }+ model->validate_nodes_and_infer_types();+ }++ // beta is not consumed by the Multiply scaling the delta anymore, but by an unrelated operation.+ static void insert_op_after_beta(const std::shared_ptr<ov::Model>& model) {+ edit_loop_bodies(model, [](const auto&, const auto&, const auto& beta) {+ const auto targets = beta->output(0).get_target_inputs();+ const auto negated = std::make_shared<ov::op::v0::Negative>(beta);+ for (auto target : targets) {+ target.replace_source_output(negated);+ }+ });+ }++ // Inserts the node made by `make` between the updated state and the back edge of every recurrence Loop.+ template <class Make>+ static void insert_op_before_back_edge(const std::shared_ptr<ov::Model>& model, const Make& make) {+ for (const auto& node : model->get_ordered_ops()) {+ const auto loop = ov::as_type_ptr<ov::op::v5::Loop>(node);+ if (!loop) {+ continue;+ }+ const auto body = loop->get_function();+ for (const auto& desc : loop->get_input_descriptions()) {+ const auto merged = ov::as_type_ptr<ov::op::util::SubGraphOp::MergedInputDescription>(desc);+ if (!merged || loop->get_input_partial_shape(desc->m_input_index).size() != 4) {+ continue;+ }+ const auto result = body->get_results().at(merged->m_body_value_index);+ result->input(0).replace_source_output(make(result->input_value(0)));+ }+ body->validate_nodes_and_infer_types();+ }+ model->validate_nodes_and_infer_types();+ }++ // Number of distinct tensors the masked g / beta Loop inputs are multiplied with.+ static size_t count_ssm_masks(const std::shared_ptr<ov::Model>& model) {+ std::set<ov::Output<ov::Node>> masks;+ for (const auto& node : model->get_ordered_ops()) {+ if (auto loop = ov::as_type_ptr<ov::op::v5::Loop>(node)) {+ for (const auto& desc : loop->get_input_descriptions()) {+ const auto source = loop->input_value(desc->m_input_index).get_node_shared_ptr();+ if (ov::is_type<ov::op::v1::Multiply>(source)) {+ masks.insert(source->input_value(1));+ }+ }+ }+ }+ return masks.size();+ }++ // std::max(diff, NaN) keeps diff, so a non-finite output must fail the test explicitly.+ static float max_abs_diff(const ov::Tensor& a, const ov::Tensor& b) {+ EXPECT_EQ(a.get_shape(), b.get_shape());+ float diff = 0.f;+ for (size_t i = 0; i < a.get_size(); ++i) {+ const float delta = std::abs(a.data<float>()[i] - b.data<float>()[i]);+ if (!std::isfinite(delta)) {+ ADD_FAILURE() << "non-finite value at element " << i << ": " << a.data<float>()[i] << " vs "+ << b.data<float>()[i];+ return std::numeric_limits<float>::infinity();+ }+ diff = std::max(diff, delta);+ }+ return diff;+ }++ static bool cpu_available() {+ const auto devices = ov::Core().get_available_devices();+ return std::find(devices.begin(), devices.end(), "CPU") != devices.end();+ }++ static std::shared_ptr<ov::op::v0::Parameter> find_param(const std::shared_ptr<ov::Model>& model,+ const std::string& name) {+ for (const auto& param : model->get_parameters()) {+ if (param->get_output_tensor(0).get_names().count(name)) {+ return param;+ }+ }+ return nullptr;+ }++ // First consumer of the given type of a state parameter, looking through a single Transpose.+ template <class T>+ static ov::Input<ov::Node> state_consumer(const std::shared_ptr<ov::op::v0::Parameter>& param) {+ for (const auto& target : param->output(0).get_target_inputs()) {+ if (ov::is_type<T>(target.get_node())) {+ return target;+ }+ if (ov::is_type<ov::op::v1::Transpose>(target.get_node())) {+ for (const auto& next : target.get_node()->output(0).get_target_inputs()) {+ if (ov::is_type<T>(next.get_node())) {+ return next;+ }+ }+ }+ }+ throw std::runtime_error("no consumer of " + param->get_friendly_name());+ }+};++TEST_F(MaskLinearAttentionPaddingTest, HybridModelIsRewrittenForAnyChunkLength) {+ const auto base = stateless(ov::test::npuw::build_hybrid_llm_test_model());+ const auto n_conv = count_inputs(base, "cache_params.past.conv");+ const auto n_ssm = count_inputs(base, "cache_params.past.ssm");+ ASSERT_GT(n_conv, 0u);+ ASSERT_EQ(n_conv, n_ssm);++ for (const uint32_t chunk : {4u, 8u, 16u}) {+ auto model = make_static(base, chunk);+ const auto scatters_before = count_ops<ov::op::v3::ScatterUpdate>(model);++ ASSERT_TRUE(ov::npuw::MaskLinearAttentionPadding().run_on_model(model)) << "chunk " << chunk;+ ASSERT_NO_THROW(model->validate_nodes_and_infer_types());++ // One ScatterUpdate writing the history per conv state.+ EXPECT_EQ(count_ops<ov::op::v3::ScatterUpdate>(model) - scatters_before, n_conv) << "chunk " << chunk;++ // g and beta of every recurrence Loop are masked.+ EXPECT_EQ(count_masked_loop_inputs(model), 2u * n_ssm) << "chunk " << chunk;+ EXPECT_EQ(count_ssm_masks(model), 1u) << "chunk " << chunk;+ }+}++TEST_F(MaskLinearAttentionPaddingTest, GateConvertedBeforeExpIsRecognized) {+ auto base = stateless(ov::test::npuw::build_hybrid_llm_test_model());+ convert_gate_before_exp(base);+ auto model = make_static(base, 8u);+ const auto n_ssm = count_inputs(model, "cache_params.past.ssm");+ ASSERT_GT(n_ssm, 0u);++ ASSERT_TRUE(ov::npuw::MaskLinearAttentionPadding().run_on_model(model));+ EXPECT_EQ(count_masked_loop_inputs(model), 2u * n_ssm);+}++TEST_F(MaskLinearAttentionPaddingTest, ShortConvModelWithoutSsmIsRewritten) {+ const auto base = stateless(ov::test::npuw::build_lfm2_llm_test_model());+ auto model = make_static(base, 8u);+ const auto n_conv = count_inputs(model, "cache_params.past.conv");+ ASSERT_GT(n_conv, 0u);+ ASSERT_EQ(count_inputs(model, "cache_params.past.ssm"), 0u);++ const auto scatters_before = count_ops<ov::op::v3::ScatterUpdate>(model);+ ASSERT_TRUE(ov::npuw::MaskLinearAttentionPadding().run_on_model(model));+ EXPECT_EQ(count_ops<ov::op::v3::ScatterUpdate>(model) - scatters_before, n_conv);+}++TEST_F(MaskLinearAttentionPaddingTest, ModelWithoutLinearAttentionIsUntouched) {+ auto model = make_static(stateless(ov::test::npuw::build_llm_test_model()), 8u);+ const auto ops_before = model->get_ops().size();+ EXPECT_FALSE(ov::npuw::MaskLinearAttentionPadding().run_on_model(model));+ EXPECT_EQ(model->get_ops().size(), ops_before);+}++// Two Concats consuming the same past conv state and none consuming the other one: the number of+// recognized sites matches the number of states, but a state is not covered.+TEST_F(MaskLinearAttentionPaddingTest, ConvStateWithoutRecognizedSiteLeavesModelUntouched) {+ auto model = make_static(stateless(ov::test::npuw::build_hybrid_llm_test_model()), 8u);+ const auto first = find_param(model, "cache_params.past.conv.0");+ const auto second = find_param(model, "cache_params.past.conv.1");+ ASSERT_TRUE(first && second);+ ASSERT_EQ(first->get_partial_shape(), second->get_partial_shape());++ state_consumer<ov::op::v0::Concat>(second).replace_source_output(first->output(0));+ ASSERT_NO_THROW(model->validate_nodes_and_infer_types());++ const auto ops_before = model->get_ops().size();+ EXPECT_FALSE(ov::npuw::MaskLinearAttentionPadding().run_on_model(model));+ EXPECT_EQ(model->get_ops().size(), ops_before);+}++TEST_F(MaskLinearAttentionPaddingTest, SsmStateWithoutRecognizedSiteLeavesModelUntouched) {+ auto model = make_static(stateless(ov::test::npuw::build_hybrid_llm_test_model()), 8u);+ const auto first = find_param(model, "cache_params.past.ssm.0");+ const auto second = find_param(model, "cache_params.past.ssm.1");+ ASSERT_TRUE(first && second);+ ASSERT_EQ(first->get_partial_shape(), second->get_partial_shape());++ state_consumer<ov::op::v5::Loop>(second).replace_source_output(first->output(0));+ ASSERT_NO_THROW(model->validate_nodes_and_infer_types());++ const auto ops_before = model->get_ops().size();+ EXPECT_FALSE(ov::npuw::MaskLinearAttentionPadding().run_on_model(model));+ EXPECT_EQ(model->get_ops().size(), ops_before);+}++TEST_F(MaskLinearAttentionPaddingTest, BetaNotScalingTheDeltaLeavesModelUntouched) {+ auto model = make_static(stateless(ov::test::npuw::build_hybrid_llm_test_model()), 8u);+ insert_op_after_beta(model);++ const auto ops_before = model->get_ops().size();+ EXPECT_FALSE(ov::npuw::MaskLinearAttentionPadding().run_on_model(model));+ EXPECT_EQ(model->get_ops().size(), ops_before);+}++// The decay is applied to a tensor which is not the state carried by the Loop.+TEST_F(MaskLinearAttentionPaddingTest, DecayNotAppliedToCarriedStateLeavesModelUntouched) {+ auto model = make_static(stateless(ov::test::npuw::build_hybrid_llm_test_model()), 8u);+ edit_loop_bodies(model, [](const auto&, const auto& gate, const auto&) {+ const auto exp = (*gate->output(0).get_target_inputs().begin()).get_node();+ const auto unsqueeze = (*exp->output(0).get_target_inputs().begin()).get_node();+ const auto decay = (*unsqueeze->output(0).get_target_inputs().begin()).get_node();+ const size_t state_idx = decay->input_value(0).get_node() == unsqueeze ? 1 : 0;+ const auto& state = decay->input_value(state_idx);+ decay->input(state_idx).replace_source_output(+ ov::op::v0::Constant::create(state.get_element_type(),+ state.get_shape(),+ std::vector<float>(ov::shape_size(state.get_shape()), 0.f)));+ });++ const auto ops_before = model->get_ops().size();+ EXPECT_FALSE(ov::npuw::MaskLinearAttentionPadding().run_on_model(model));+ EXPECT_EQ(model->get_ops().size(), ops_before);+}++// Something else updates the state after the delta is added.+TEST_F(MaskLinearAttentionPaddingTest, UpdateAfterTheDeltaAddLeavesModelUntouched) {+ auto model = make_static(stateless(ov::test::npuw::build_hybrid_llm_test_model()), 8u);+ insert_op_before_back_edge(model, [](const ov::Output<ov::Node>& state) {+ return std::make_shared<ov::op::v0::Negative>(state);+ });++ const auto ops_before = model->get_ops().size();+ EXPECT_FALSE(ov::npuw::MaskLinearAttentionPadding().run_on_model(model));+ EXPECT_EQ(model->get_ops().size(), ops_before);+}++TEST_F(MaskLinearAttentionPaddingTest, ConvertOnTheBackEdgeIsRecognized) {+ auto model = make_static(stateless(ov::test::npuw::build_hybrid_llm_test_model()), 8u);+ const auto n_ssm = count_inputs(model, "cache_params.past.ssm");+ insert_op_before_back_edge(model, [](const ov::Output<ov::Node>& state) {+ return std::make_shared<ov::op::v0::Convert>(state, state.get_element_type());+ });++ ASSERT_TRUE(ov::npuw::MaskLinearAttentionPadding().run_on_model(model));+ EXPECT_EQ(count_masked_loop_inputs(model), 2u * n_ssm);+}++TEST_F(MaskLinearAttentionPaddingTest, DynamicShapesAreLeftUntouched) {+ auto model = stateless(ov::test::npuw::build_hybrid_llm_test_model());+ const auto ops_before = model->get_ops().size();+ EXPECT_FALSE(ov::npuw::MaskLinearAttentionPadding().run_on_model(model));+ EXPECT_EQ(model->get_ops().size(), ops_before);+}++// The Concat infers a rank-3 output from x alone when the past conv state has a dynamic rank.+TEST_F(MaskLinearAttentionPaddingTest, RankDynamicConvStateLeavesModelUntouched) {+ auto model = make_static(stateless(ov::test::npuw::build_hybrid_llm_test_model()), 8u);+ const auto past = find_param(model, "cache_params.past.conv.0");+ ASSERT_TRUE(past);+ past->set_partial_shape(ov::PartialShape::dynamic());+ ASSERT_NO_THROW(model->validate_nodes_and_infer_types());+ ASSERT_EQ(state_consumer<ov::op::v0::Concat>(past).get_node()->get_output_partial_shape(0).size(), 3u);++ const auto ops_before = model->get_ops().size();+ bool rewritten = true;+ ASSERT_NO_THROW(rewritten = ov::npuw::MaskLinearAttentionPadding().run_on_model(model));+ EXPECT_FALSE(rewritten);+ EXPECT_EQ(model->get_ops().size(), ops_before);+}++// A partial chunk padded on the left must leave exactly the same conv/ssm state and the same+// logits as the same tokens processed in a chunk of their own length, for a non-zero carried state.+// The conv state is checked both in its original [B, C, K] layout and re-laid out as [B, K, C], and the+// gate both in the precision of the model and converted from f16 right before Exp.+class MaskLinearAttentionPaddingNumericsTest : public MaskLinearAttentionPaddingTest,+ public ::testing::WithParamInterface<std::tuple<uint32_t, bool, bool>> {+};++TEST_P(MaskLinearAttentionPaddingNumericsTest, PaddedChunkMatchesUnpaddedChunk) {+ if (!cpu_available()) {+ GTEST_SKIP() << "CPU plugin is required to execute the models";+ }+ const uint32_t chunk = 8u;+ const auto [padding, relayout_conv, f16_gate] = GetParam();+ ASSERT_LT(padding, chunk);++ auto base = stateless(ov::test::npuw::build_hybrid_llm_test_model());+ if (relayout_conv) {+ ASSERT_TRUE(ov::npuw::util::OptimizeLinCacheLayout().run_on_model(base));+ }+ if (f16_gate) {+ convert_gate_before_exp(base);+ }+ const auto past = make_lincache_past(make_static(base, chunk));++ const auto reference_model = make_static(base, chunk - padding);+ const auto reference = run(reference_model, chunk - padding, 0u, past);++ auto padded_model = make_static(base, chunk);+ const auto padded_without_pass = run(padded_model, chunk, padding, past);+ ASSERT_TRUE(ov::npuw::MaskLinearAttentionPadding().run_on_model(padded_model));+ const auto padded = run(padded_model, chunk, padding, past);++ ASSERT_FALSE(reference.empty());+ float diff_with_pass = 0.f;+ float diff_without_pass = 0.f;+ for (const auto& [name, expected] : reference) {+ ASSERT_TRUE(padded.count(name)) << name;+ if (name == "logits") {+ // Compare the last position only: the earlier ones belong to different chunk layouts.+ const auto vocab = expected.get_shape().back();+ const auto last = [&](const ov::Tensor& t) {+ return ov::Tensor(t,+ ov::Coordinate{0, t.get_shape()[1] - 1, 0},+ ov::Coordinate{1, t.get_shape()[1], vocab});+ };+ diff_with_pass = std::max(diff_with_pass, max_abs_diff(last(expected), last(padded.at(name))));+ diff_without_pass =+ std::max(diff_without_pass, max_abs_diff(last(expected), last(padded_without_pass.at(name))));+ } else {+ EXPECT_LT(max_abs_diff(expected, padded.at(name)), 1e-4f) << name;+ diff_without_pass = std::max(diff_without_pass, max_abs_diff(expected, padded_without_pass.at(name)));+ }+ }+ EXPECT_LT(diff_with_pass, 1e-4f);+ // The comparison is only meaningful if the unmasked model is actually wrong.+ EXPECT_GT(diff_without_pass, 1e-3f);+}++INSTANTIATE_TEST_SUITE_P(PaddingLength,+ MaskLinearAttentionPaddingNumericsTest,+ ::testing::Combine(::testing::Values(1u, 3u, 7u), ::testing::Bool(), ::testing::Bool()));++TEST_F(MaskLinearAttentionPaddingTest, FullChunkIsUnchanged) {+ if (!cpu_available()) {+ GTEST_SKIP() << "CPU plugin is required to execute the models";+ }+ const uint32_t chunk = 8u;+ const auto base = stateless(ov::test::npuw::build_hybrid_llm_test_model());+ const auto past = make_lincache_past(make_static(base, chunk));++ auto model = make_static(base, chunk);+ const auto reference = run(model, chunk, 0u, past);+ ASSERT_TRUE(ov::npuw::MaskLinearAttentionPadding().run_on_model(model));+ const auto masked = run(model, chunk, 0u, past);++ for (const auto& [name, expected] : reference) {+ EXPECT_LT(max_abs_diff(expected, masked.at(name)), 1e-5f) << name;+ }+}++TEST_F(MaskLinearAttentionPaddingTest, ChunkedPrefillPipelineAppliesThePass) {+ RecordingFactory recorder;+ std::unique_ptr<ov::npuw::LLMCompiledModel> compiled;+ ASSERT_NO_THROW(compiled = create_compiled_model(ov::test::npuw::build_hybrid_llm_test_model(),+ {{"NPUW_LLM_PREFILL_CHUNK_SIZE", "64"}},+ recorder));++ const auto& prefill = require_sub_model(recorder, "_prefill");+ EXPECT_EQ(count_masked_loop_inputs(prefill.model), 2u * count_inputs(prefill.model, "cache_params.past.ssm"));+}++TEST_F(MaskLinearAttentionPaddingTest, WholePrefillDoesNotApplyThePass) {+ RecordingFactory recorder;+ std::unique_ptr<ov::npuw::LLMCompiledModel> compiled;+ ASSERT_NO_THROW(compiled = create_compiled_model(ov::test::npuw::build_hybrid_llm_test_model(),+ {{"NPUW_LLM_PREFILL_CHUNK_SIZE", "0"}},+ recorder));+ const auto& prefill = require_sub_model(recorder, "_prefill");+ EXPECT_EQ(count_masked_loop_inputs(prefill.model), 0u);+}++} // namespace