Skip to content

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

[NPUW] Suppport 4d float attention_mask (#38932)

Orest Churacd202900e453
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.cpp
index 5c4396eb55b..59142406570 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
@@ -77,9 +77,46 @@ bool is_aligned_to(T value, T alignment) {
return value % alignment == 0;
}
-} // namespace
+bool is_4d_float_attention_mask(const std::shared_ptr<const ov::Model>& model) {
+ const auto attention_mask =
+ ov::npuw::util::find_port_by_name(model->inputs(), ov::npuw::LLMInferRequest::layer_names::attention_mask);
+
+ // Models without an attention_mask input (e.g. the Whisper decoder) keep the binary-mask flow.
+ if (!attention_mask) {
+ return false;
+ }
+
+ const auto elem_type = attention_mask->get_element_type();
+ const auto pshape = attention_mask->get_partial_shape();
+ const bool is_int_or_bool = elem_type == ov::element::i64 || elem_type == ov::element::i32 ||
+ elem_type == ov::element::u64 || elem_type == ov::element::u32 ||
+ elem_type == ov::element::boolean;
+ const bool is_float = elem_type.is_real();
+
+ if (!pshape.rank().is_static()) {
+ OPENVINO_ASSERT(is_int_or_bool,
+ "NPUW LLM only supports dynamic-rank attention_mask for integer/bool masks. "
+ "Got floating attention_mask with dynamic rank.");
+ return false;
+ }
+
+ const auto rank = pshape.rank().get_length();
+ // A 2D mask keeps the binary-mask flow whatever its element type; the infer request validates the type.
+ if (rank == 2) {
+ return false;
+ }
+ if (rank == 4 && is_float) {
+ return true;
+ }
+
+ OPENVINO_THROW("Unsupported attention_mask contract for NPUW LLM. Expected either 2D attention_mask "
+ "or 4D float attention_mask, but got rank=",
+ rank,
+ ", element type=",
+ elem_type,
+ ".");
+}
-namespace {
std::shared_ptr<ov::Model> cut_lm_head(const std::shared_ptr<ov::Model>& model) {
std::shared_ptr<ov::Model> lm_head_model = nullptr;
ov::npuw::CutLMHead(lm_head_model).run_on_model(model);
@@ -729,7 +766,10 @@ std::vector<std::shared_ptr<ov::Model>> ov::npuw::LLMCompiledModel::create_gener
ov::npuw::ReshapeToStatic(max_generation_token_len, kv_size, axes, m_max_lora_rank, whisper_lhs_seq_size)
.run_on_model(generate_variant);
- ov::npuw::RewriteGQAAttentionMask().run_on_model(generate_variant);
+ // The pass treats attention_mask as a 2D 0/1 mask, which an additive 4D float mask is not.
+ if (!m_attention_mask_is_4d_float) {
+ ov::npuw::RewriteGQAAttentionMask().run_on_model(generate_variant);
+ }
if (m_cfg.get<::intel_npu::NPUW_LLM_ENABLE_SWA_KV_CACHE_SHRINK>()) {
// Must run after ReshapeToStatic, before OptimizeValueTensors (V-tensor optimization).
@@ -901,6 +941,24 @@ ov::npuw::LLMCompiledModel::LLMCompiledModel(const std::shared_ptr<ov::Model>& m
const uint32_t seq_len_dim = m_cfg.get<::intel_npu::NPUW_LLM_SEQ_LEN_DIM>();
KVAxesPosition axes{batch_dim, seq_len_dim};
+ m_attention_mask_is_4d_float = is_4d_float_attention_mask(model);
+ if (m_attention_mask_is_4d_float) {
+ LOG_INFO("Detected 4D float attention_mask contract [B, 1, Q, K] for NPUW LLM path.");
+ if (m_use_chunk_prefill) {
+ OPENVINO_THROW_NOT_IMPLEMENTED("4D float attention_mask mode does not support chunked prefill yet. "
+ "Please disable chunked prefill by setting NPUW_LLM_PREFILL_CHUNK_SIZE >= "
+ "NPUW_LLM_MAX_PROMPT_LEN or by using NPUW_LLM_PREFILL_HINT=STATIC.");
+ }
+ if (m_cfg.get<::intel_npu::NPUW_LLM_ENABLE_PREFIX_CACHING>()) {
+ OPENVINO_THROW_NOT_IMPLEMENTED(
+ "4D float attention_mask mode does not support NPUW_LLM_ENABLE_PREFIX_CACHING yet.");
+ }
+ if (m_cfg.get<::intel_npu::NPUW_LLM_ENABLE_SWA_KV_CACHE_SHRINK>()) {
+ OPENVINO_THROW_NOT_IMPLEMENTED(
+ "4D float attention_mask mode does not support NPUW_LLM_ENABLE_SWA_KV_CACHE_SHRINK yet.");
+ }
+ }
+
std::map<std::string, std::vector<std::size_t>> other_dynamic_outputs;
if (m_use_chunk_prefill) {
LOG_VERB("Find all models outputs besides logits that also have dynamic shapes to handle in chunked prefill.");
@@ -930,6 +988,9 @@ ov::npuw::LLMCompiledModel::LLMCompiledModel(const std::shared_ptr<ov::Model>& m
pop_option(other_props, std::string("NPUW_TEXT_RERANK"));
if (m_is_embedding) {
+ if (m_attention_mask_is_4d_float) {
+ OPENVINO_THROW_NOT_IMPLEMENTED("4D float attention_mask mode does not support text-embedding models yet.");
+ }
// Both embedding flavours only ever prefill; what differs is how they attend. An
// autoregressive embedder (Qwen3-Embedding-style) has a causal mask and a KV cache to
// reconstruct, which is what lets it prefill in chunks. A bidirectional encoder (BERT:
@@ -972,8 +1033,12 @@ ov::npuw::LLMCompiledModel::LLMCompiledModel(const std::shared_ptr<ov::Model>& m
} else {
LOG_DEBUG("Adding position_ids input in case it doesn't exist in model: LFM-2 case.");
ov::npuw::AddPositionIdsParam().run_on_model(kvcache_model);
- LOG_DEBUG("Right-align attention_mask slice for Conv operations: LFM-2 case.");
- ov::npuw::RightAlignMaskSliceForConv().run_on_model(kvcache_model);
+ if (!m_attention_mask_is_4d_float) {
+ LOG_DEBUG("Right-align attention_mask slice for Conv operations: LFM-2 case.");
+ ov::npuw::RightAlignMaskSliceForConv().run_on_model(kvcache_model);
+ } else {
+ LOG_DEBUG("Skipping RightAlignMaskSliceForConv for 4D float attention_mask mode.");
+ }
LOG_DEBUG("Transform kvcache model from stateful to stateless.");
ov::pass::StatefulToStateless().run_on_model(kvcache_model);
}
@@ -1009,8 +1074,10 @@ ov::npuw::LLMCompiledModel::LLMCompiledModel(const std::shared_ptr<ov::Model>& m
bool propagate_slice_up = m_cfg.get<::intel_npu::NPUW_LLM_PROPAGATE_SLICE_UP>();
if (is_per_layer_inputs_model) {
// SWA shrink is incompatible with prefix caching and multi-token generation (e.g.
- // speculative decoding). When it applies, continuous prefill is resolved off.
- const bool swa_shrink_compatible = !m_enable_prefix_caching && max_generation_token_len == 1;
+ // speculative decoding) and with the 4D float attention_mask. When it applies, continuous
+ // prefill is resolved off.
+ const bool swa_shrink_compatible =
+ !m_enable_prefix_caching && max_generation_token_len == 1 && !m_attention_mask_is_4d_float;
if (swa_shrink_compatible && !m_cfg.has<::intel_npu::NPUW_LLM_ENABLE_SWA_KV_CACHE_SHRINK>()) {
m_cfg.update({{"NPUW_LLM_ENABLE_SWA_KV_CACHE_SHRINK", "YES"}});
LOG_INFO("Gemma-4 cross-group KV model: auto-enabling NPUW_LLM_ENABLE_SWA_KV_CACHE_SHRINK");
@@ -1027,9 +1094,12 @@ ov::npuw::LLMCompiledModel::LLMCompiledModel(const std::shared_ptr<ov::Model>& m
// the KV cache still keeps the full context (no memory/perf savings).
// - ShrinkSlidingWindowKVCache: shrinks the KV cache to the window size and
// manages it as a sliding buffer at runtime for better memory/perf.
- if (!m_is_whisper && !m_cfg.get<::intel_npu::NPUW_LLM_ENABLE_SWA_KV_CACHE_SHRINK>()) {
+ if (!m_is_whisper && !m_attention_mask_is_4d_float &&
+ !m_cfg.get<::intel_npu::NPUW_LLM_ENABLE_SWA_KV_CACHE_SHRINK>()) {
LOG_DEBUG("Try patch sliding window attention mask (Phi-3, Gemma-2, Gemma-3, Gemma-4), if it exists.");
ov::npuw::PatchSlidingWindowMask().run_on_model(kvcache_model);
+ } else if (m_attention_mask_is_4d_float) {
+ LOG_DEBUG("Skipping PatchSlidingWindowMask for 4D float attention_mask mode.");
}
if (m_cfg.get<::intel_npu::NPUW_LLM_OPTIMIZE_LINCACHE_LAYOUT>()) {
@@ -1110,7 +1180,9 @@ ov::npuw::LLMCompiledModel::LLMCompiledModel(const std::shared_ptr<ov::Model>& m
true)
.run_on_model(prefill_model);
}
- ov::npuw::RewriteGQAAttentionMask().run_on_model(prefill_model);
+ if (!m_attention_mask_is_4d_float) {
+ ov::npuw::RewriteGQAAttentionMask().run_on_model(prefill_model);
+ }
LOG_DEBUG("Make kvcache model with static shapes");
if (m_cfg.get<::intel_npu::NPUW_LLM_ENABLE_SWA_KV_CACHE_SHRINK>()) {
@@ -1479,6 +1551,10 @@ ov::npuw::LLMCompiledModel::LLMCompiledModel(const std::shared_ptr<ov::Model>& m
kv_kache_storage_type == ov::element::i8 || kv_kache_storage_type == ov::element::u8;
OPENVINO_ASSERT(!integer_kv_cache,
"NPUW_LLM_ENABLE_BLOCK_BASED_KV_CACHE cannot be combined with integer KV-cache precision.");
+ if (m_attention_mask_is_4d_float) {
+ OPENVINO_THROW_NOT_IMPLEMENTED("4D float attention_mask mode does not support "
+ "NPUW_LLM_ENABLE_BLOCK_BASED_KV_CACHE yet.");
+ }
OPENVINO_ASSERT(!m_enable_prefix_caching,
"NPUW_LLM_ENABLE_BLOCK_BASED_KV_CACHE and NPUW_LLM_ENABLE_PREFIX_CACHING "
"cannot be enabled simultaneously — this combination is not yet supported. "
@@ -1899,6 +1975,9 @@ std::shared_ptr<ov::npuw::LLMCompiledModel> ov::npuw::LLMCompiledModel::deserial
compiled->m_decomposed_sdpa_size & compiled->m_is_eagle & compiled->m_is_embedding &
compiled->m_is_block_kv_cache & compiled->m_is_encoder_embedding & compiled->m_swa_window_size;
+ // Not serialized: derived from the restored inputs, the same way as at compile time.
+ compiled->m_attention_mask_is_4d_float = is_4d_float_attention_mask(ov_model);
+
// LongRoPE cos/sin tables - see the matching comment in serialize()
stream & compiled->m_longrope_tables;
@@ -2065,6 +2144,9 @@ bool ov::npuw::LLMCompiledModel::can_continue_prefill() const {
if (m_is_whisper || m_is_embedding || m_is_eagle) {
return false; // out of scope pipelines
}
+ if (m_attention_mask_is_4d_float) {
+ return false; // a continued prefill stages only the 2D int64 attention_mask
+ }
if (m_longrope_context_limit > 0u) {
return false; // LongRoPE threshold can be crossed mid-generation
}
diff --git a/src/plugins/intel_npu/src/plugin/npuw/llm_compiled_model.hpp b/src/plugins/intel_npu/src/plugin/npuw/llm_compiled_model.hpp
index ffe5ea4bf9d..272beac72ad 100644
--- a/src/plugins/intel_npu/src/plugin/npuw/llm_compiled_model.hpp
+++ b/src/plugins/intel_npu/src/plugin/npuw/llm_compiled_model.hpp
@@ -187,6 +187,8 @@ protected:
size_t m_decomposed_sdpa_size = 0;
bool m_is_embedding = false;
+ // True when the model expects additive attention_mask in [B, 1, Q, K] float layout.
+ bool m_attention_mask_is_4d_float = false;
// True when the embedding model is a non-autoregressive bidirectional encoder (e.g. BERT):
// routed to the dedicated KV/RoPE-free encoder embedding path.
bool m_is_encoder_embedding = false;
diff --git a/src/plugins/intel_npu/src/plugin/npuw/llm_infer_request.cpp b/src/plugins/intel_npu/src/plugin/npuw/llm_infer_request.cpp
index 822c0162e13..8569a6a2a94 100644
--- a/src/plugins/intel_npu/src/plugin/npuw/llm_infer_request.cpp
+++ b/src/plugins/intel_npu/src/plugin/npuw/llm_infer_request.cpp
@@ -6,6 +6,8 @@
#include <algorithm>
#include <cmath>
+#include <cstring>
+#include <limits>
#include <regex>
#include "infer_request_utils.hpp"
@@ -65,6 +67,253 @@ void copy_columns_by_row_chunks_2d(ov::SoPtr<ov::ITensor> src, ov::SoPtr<ov::ITe
}
}
+template <typename T>
+void fill_fully_masked(const ov::SoPtr<ov::ITensor>& tensor) {
+ // The lowest finite f16 value, to mitigate risk of having -inf for f16 and bf16 CPU sub-models,
+ // and then a fully masked padding row of -inf giving NaN in Softmax.
+ // Still masks fully for f32.
+ const auto value = static_cast<T>(std::numeric_limits<ov::float16>::lowest());
+ std::fill_n(tensor->data<T>(), tensor->get_size(), value);
+}
+
+void fill_additive_attention_mask(const ov::SoPtr<ov::ITensor>& tensor) {
+ switch (tensor->get_element_type()) {
+ case ov::element::f32:
+ fill_fully_masked<float>(tensor);
+ break;
+ case ov::element::f16:
+ fill_fully_masked<ov::float16>(tensor);
+ break;
+ case ov::element::bf16:
+ fill_fully_masked<ov::bfloat16>(tensor);
+ break;
+ default:
+ OPENVINO_THROW("Unsupported additive attention_mask element type: ", tensor->get_element_type());
+ }
+}
+
+void copy_additive_attention_block(const ov::SoPtr<ov::ITensor>& src,
+ const ov::SoPtr<ov::ITensor>& dst,
+ size_t src_q_offset,
+ size_t src_k_offset,
+ size_t dst_q_offset,
+ size_t dst_k_offset,
+ size_t rows,
+ size_t cols) {
+ const auto& src_shape = src->get_shape();
+ const auto& dst_shape = dst->get_shape();
+ OPENVINO_ASSERT(src_shape.size() == 4u && dst_shape.size() == 4u,
+ "Additive attention_mask tensors must be rank 4.");
+ OPENVINO_ASSERT(src_shape[0] == dst_shape[0],
+ "Additive attention_mask batch dimension must match the destination: got ",
+ src_shape[0],
+ ", expected ",
+ dst_shape[0],
+ ".");
+ OPENVINO_ASSERT(src_shape[1] == dst_shape[1],
+ "Additive attention_mask head dimension must match the destination: got ",
+ src_shape[1],
+ ", expected ",
+ dst_shape[1],
+ ".");
+
+ OPENVINO_ASSERT(src->get_element_type() == dst->get_element_type(),
+ "Additive attention_mask element types must match the destination: got ",
+ src->get_element_type(),
+ ", expected ",
+ dst->get_element_type(),
+ ".");
+ OPENVINO_ASSERT(src_q_offset + rows <= src_shape[2] && src_k_offset + cols <= src_shape[3],
+ "Additive attention_mask block of ",
+ rows,
+ " rows and ",
+ cols,
+ " columns at offset [",
+ src_q_offset,
+ ", ",
+ src_k_offset,
+ "] does not fit the source shape ",
+ src_shape,
+ ".");
+ OPENVINO_ASSERT(dst_q_offset + rows <= dst_shape[2] && dst_k_offset + cols <= dst_shape[3],
+ "Additive attention_mask block of ",
+ rows,
+ " rows and ",
+ cols,
+ " columns at offset [",
+ dst_q_offset,
+ ", ",
+ dst_k_offset,
+ "] does not fit the destination shape ",
+ dst_shape,
+ ".");
+
+ const size_t elem_size = src->get_element_type().size();
+ const auto& src_strides = src->get_strides();
+ const auto& dst_strides = dst->get_strides();
+ // Ensure a block row is one contiguous run, so each row is a single memcpy
+ OPENVINO_ASSERT(src_strides[3] == elem_size && dst_strides[3] == elem_size,
+ "Additive attention_mask rows must be contiguous.");
+
+ const size_t src_offset = src_q_offset * src_strides[2] + src_k_offset * elem_size;
+ const size_t dst_offset = dst_q_offset * dst_strides[2] + dst_k_offset * elem_size;
+ const auto* src_data = static_cast<const uint8_t*>(src->data()) + src_offset;
+ auto* dst_data = static_cast<uint8_t*>(dst->data()) + dst_offset;
+ for (size_t b = 0; b < src_shape[0]; ++b) {
+ for (size_t h = 0; h < src_shape[1]; ++h) {
+ const auto* src_block = src_data + b * src_strides[0] + h * src_strides[1];
+ auto* dst_block = dst_data + b * dst_strides[0] + h * dst_strides[1];
+ for (size_t r = 0; r < rows; ++r) {
+ std::memcpy(dst_block + r * dst_strides[2], src_block + r * src_strides[2], cols * elem_size);
+ }
+ }
+ }
+}
+
+void stage_additive_attention_mask_for_prefill(const ov::SoPtr<ov::ITensor>& src,
+ const ov::SoPtr<ov::ITensor>& dst,
+ size_t prompt_len) {
+ const auto& src_shape = src->get_shape();
+ const auto& dst_shape = dst->get_shape();
+ OPENVINO_ASSERT(src_shape.size() == 4u && dst_shape.size() == 4u,
+ "Additive attention_mask tensors must be rank 4.");
+ const size_t query_len = src_shape[2];
+ const size_t key_len = src_shape[3];
+ // Only a full [prompt, prompt] mask is staged. A broadcast or shifted mask would leave some of the
+ // prompt query rows fully masked.
+ OPENVINO_ASSERT(query_len == prompt_len && key_len == prompt_len,
+ "Additive prefill attention_mask must cover exactly the prompt: expected Q=K=",
+ prompt_len,
+ ", got Q=",
+ query_len,
+ ", K=",
+ key_len,
+ ".");
+ OPENVINO_ASSERT(query_len <= dst_shape[2] && key_len <= dst_shape[3],
+ "Additive prefill attention_mask shape ",
+ src_shape,
+ " does not fit static destination shape ",
+ dst_shape,
+ ".");
+
+ fill_additive_attention_mask(dst);
+ copy_additive_attention_block(src, dst, 0, 0, dst_shape[2] - query_len, dst_shape[3] - key_len, query_len, key_len);
+}
+
+// Stages the additive attention mask of shape [1, 1, current, past + current] into the generate request.
+void stage_additive_attention_mask_for_generate(const ov::SoPtr<ov::ITensor>& attention_mask,
+ const ov::SoPtr<ov::ITensor>& kv_attn_mask,
+ size_t past_len,
+ size_t input_tokens_len,
+ size_t max_generation_token_len) {
+ const auto& attention_mask_shape = attention_mask->get_shape();
+ const auto& kv_attn_mask_shape = kv_attn_mask->get_shape();
+ OPENVINO_ASSERT(attention_mask_shape.size() == 4u && kv_attn_mask_shape.size() == 4u,
+ "Additive attention_mask tensors must be rank 4.");
+ OPENVINO_ASSERT(attention_mask_shape[2] == input_tokens_len,
+ "Additive generate attention_mask query dimension must match input length. Got Q=",
+ attention_mask_shape[2],
+ ", input length=",
+ input_tokens_len,
+ ".");
+ // Past length comes from the tracked KV-cache; the caller mask has to be consistent with it.
+ OPENVINO_ASSERT(attention_mask_shape[3] == past_len + input_tokens_len,
+ "Additive generate attention_mask key dimension must be the stored past plus the current "
+ "tokens: expected ",
+ past_len + input_tokens_len,
+ ", got ",
+ attention_mask_shape[3],
+ ".");
+ OPENVINO_ASSERT(kv_attn_mask_shape[3] >= max_generation_token_len,
+ "Generate attention mask is smaller than the configured generation window.");
+ const size_t dest_past_capacity = kv_attn_mask_shape[3] - max_generation_token_len;
+ OPENVINO_ASSERT(past_len <= dest_past_capacity,
+ "Selected generate variant cannot hold the stored attention context: ",
+ past_len,
+ " past tokens exceed capacity ",
+ dest_past_capacity,
+ ".");
+
+ const size_t query_len = attention_mask_shape[2];
+ OPENVINO_ASSERT(query_len <= kv_attn_mask_shape[2] && past_len + query_len <= kv_attn_mask_shape[3],
+ "Additive generate attention_mask shape ",
+ attention_mask_shape,
+ " does not fit static destination shape ",
+ kv_attn_mask_shape,
+ ".");
+
+ fill_additive_attention_mask(kv_attn_mask);
+ const size_t dest_query_offset = kv_attn_mask_shape[2] - query_len;
+ if (past_len > 0) {
+ copy_additive_attention_block(attention_mask, kv_attn_mask, 0, 0, dest_query_offset, 0, query_len, past_len);
+ }
+ copy_additive_attention_block(attention_mask,
+ kv_attn_mask,
+ 0,
+ past_len,
+ dest_query_offset,
+ kv_attn_mask_shape[3] - query_len,
+ query_len,
+ query_len);
+}
+
+// Stages the binary (0/1, int64) attention mask of shape [1, >= past + current] into the generate request.
+// NB: Past length comes from the tracked KV-cache, not the caller mask size: the caller mask
+// may be a static max-length buffer (e.g. WebNN) rather than past_len + input_tokens_len.
+void stage_binary_attention_mask_for_generate(const ov::SoPtr<ov::ITensor>& attention_mask,
+ const ov::SoPtr<ov::ITensor>& kv_attn_mask,
+ size_t past_len,
+ size_t input_tokens_len,
+ size_t max_generation_token_len) {
+ OPENVINO_ASSERT(kv_attn_mask->get_size() >= max_generation_token_len,
+ "Generate attention mask is smaller than the configured generation window.");
+ const size_t dest_past_capacity = kv_attn_mask->get_size() - max_generation_token_len;
+ OPENVINO_ASSERT(past_len <= dest_past_capacity,
+ "Selected generate variant cannot hold the stored attention context: ",
+ past_len,
+ " past tokens exceed capacity ",
+ dest_past_capacity,
+ ".");
+ OPENVINO_ASSERT(attention_mask->get_size() >= past_len,
+ "Attention mask does not cover the stored past: expected at least ",
+ past_len,
+ " entries, got ",
+ attention_mask->get_size(),
+ ".");
+ const size_t used_mask_len = past_len + input_tokens_len;
+ if (attention_mask->get_size() > used_mask_len) {
+ // Static max-length caller mask (e.g. WebNN): layout is [past][current][padding],
+ // so the ignored tail must not carry any valid context.
+ const auto* mask_data = attention_mask->data<int64_t>();
+ const auto tail_begin = mask_data + used_mask_len;
+ const auto tail_end = mask_data + attention_mask->get_size();
+ const auto valid_it = std::find_if(tail_begin, tail_end, [](int64_t v) {
+ return v != 0;
+ });
+ OPENVINO_ASSERT(valid_it == tail_end,
+ "Static attention mask has a valid entry at position ",
+ static_cast<size_t>(valid_it - mask_data),
+ " beyond the tracked context of ",
+ used_mask_len,
+ " tokens (",
+ past_len,
+ " past + ",
+ input_tokens_len,
+ " current); truncating it would drop context.");
+ }
+ std::copy_n(attention_mask->data<int64_t>(), past_len, kv_attn_mask->data<int64_t>());
+ // Clear stale entries left by a larger past (e.g. after speculative-decoding trim).
+ if (past_len < dest_past_capacity) {
+ std::fill_n(kv_attn_mask->data<int64_t>() + past_len, dest_past_capacity - past_len, 0);
+ }
+ if (input_tokens_len < max_generation_token_len) {
+ std::fill_n(kv_attn_mask->data<int64_t>() + kv_attn_mask->get_size() - max_generation_token_len,
+ max_generation_token_len - input_tokens_len,
+ 0);
+ }
+ std::fill_n(kv_attn_mask->data<int64_t>() + kv_attn_mask->get_size() - input_tokens_len, input_tokens_len, 1);
+}
+
void check_tensor_shape_compatibility(const ov::Shape& state_tensor_shape,
const ov::Shape& infer_tensor_shape,
size_t full_rank_dim,
@@ -713,7 +962,12 @@ void ov::npuw::LLMInferRequest::zero_prefill_staging() {
type_ids_port != m_prefill_in_ports.end()) {
uu::fill_tensor_bytes(m_prefill_request->get_tensor(type_ids_port->second), 0u);
}
- uu::fill_tensor<int64_t>(m_prefill_request->get_tensor(m_prefill_in_ports.at(layer_names::attention_mask)), 0);
+ auto prefill_attention_mask = m_prefill_request->get_tensor(m_prefill_in_ports.at(layer_names::attention_mask));
+ if (m_npuw_llm_compiled_model->m_attention_mask_is_4d_float) {
+ fill_additive_attention_mask(prefill_attention_mask);
+ } else {
+ uu::fill_tensor<int64_t>(prefill_attention_mask, 0);
+ }
if (m_position_ids_present) {
uu::fill_tensor<int64_t>(m_prefill_request->get_tensor(m_prefill_in_ports.at(layer_names::position_ids)), 0);
@@ -1359,10 +1613,16 @@ void ov::npuw::LLMInferRequest::infer_whole_prefill(ov::SoPtr<ov::ITensor> input
input_ids->get_byte_size());
auto padded_attention_mask = m_prefill_request->get_tensor(m_prefill_in_ports.at(layer_names::attention_mask));
- std::copy_n(
- attention_mask->data<int64_t>(),
- attention_mask->get_size(),
- padded_attention_mask->data<int64_t>() + padded_attention_mask->get_size() - attention_mask->get_size());
+ if (m_npuw_llm_compiled_model->m_attention_mask_is_4d_float) {
+ stage_additive_attention_mask_for_prefill(attention_mask,
+ padded_attention_mask,
+ input_ids->get_shape()[layer_ids::INPUT_IDS_SEQ_LEN_DIM]);
+ } else {
+ std::copy_n(attention_mask->data<int64_t>(),
+ attention_mask->get_size(),
+ padded_attention_mask->data<int64_t>() + padded_attention_mask->get_size() -
+ attention_mask->get_size());
+ }
if (token_type_ids) {
auto padded_token_type_ids =
@@ -1662,8 +1922,13 @@ void ov::npuw::LLMInferRequest::infer_generate(ov::SoPtr<ov::ITensor> input_ids,
LOG_DEBUG("Prepare inputs.");
namespace uu = ov::npuw::util;
uu::fill_tensor_bytes(m_kvcache_request->get_tensor(m_kvcache_in_ports.at(m_input_ids_name)), 0u);
- uu::fill_tensor<int64_t>(m_kvcache_request->get_tensor(m_kvcache_in_ports.at(layer_names::attention_mask)),
- 0);
+ auto generate_attention_mask =
+ m_kvcache_request->get_tensor(m_kvcache_in_ports.at(layer_names::attention_mask));
+ if (m_npuw_llm_compiled_model->m_attention_mask_is_4d_float) {
+ fill_additive_attention_mask(generate_attention_mask);
+ } else {
+ uu::fill_tensor<int64_t>(generate_attention_mask, 0);
+ }
if (m_position_ids_present) {
uu::fill_tensor<int64_t>(
m_kvcache_request->get_tensor(m_kvcache_in_ports.at(layer_names::position_ids)),
@@ -1705,57 +1970,19 @@ void ov::npuw::LLMInferRequest::infer_generate(ov::SoPtr<ov::ITensor> input_ids,
// kv layers) and the set of "1" units of number of previously calculated
// tokens on the left (for past kv layers).
auto kv_attn_mask = m_kvcache_request->get_tensor(m_kvcache_in_ports.at(layer_names::attention_mask));
- // NB: Past length comes from the tracked KV-cache, not the caller mask size: the caller mask
- // may be a static max-length buffer (e.g. WebNN) rather than past_len + input_tokens_len.
- OPENVINO_ASSERT(kv_attn_mask->get_size() >= kvcache_desc.max_generation_token_len,
- "Generate attention mask is smaller than the configured generation window.");
- const size_t past_len = kvcache_desc.num_stored_tokens;
- const size_t dest_past_capacity = kv_attn_mask->get_size() - kvcache_desc.max_generation_token_len;
- OPENVINO_ASSERT(past_len <= dest_past_capacity,
- "Selected generate variant cannot hold the stored attention context: ",
- past_len,
- " past tokens exceed capacity ",
- dest_past_capacity,
- ".");
- OPENVINO_ASSERT(attention_mask->get_size() >= past_len,
- "Attention mask does not cover the stored past: expected at least ",
- past_len,
- " entries, got ",
- attention_mask->get_size(),
- ".");
- const size_t used_mask_len = past_len + input_tokens_len;
- if (attention_mask->get_size() > used_mask_len) {
- // Static max-length caller mask (e.g. WebNN): layout is [past][current][padding],
- // so the ignored tail must not carry any valid context.
- const auto* mask_data = attention_mask->data<int64_t>();
- const auto tail_begin = mask_data + used_mask_len;
- const auto tail_end = mask_data + attention_mask->get_size();
- const auto valid_it = std::find_if(tail_begin, tail_end, [](int64_t v) {
- return v != 0;
- });
- OPENVINO_ASSERT(valid_it == tail_end,
- "Static attention mask has a valid entry at position ",
- static_cast<size_t>(valid_it - mask_data),
- " beyond the tracked context of ",
- used_mask_len,
- " tokens (",
- past_len,
- " past + ",
- input_tokens_len,
- " current); truncating it would drop context.");
- }
- std::copy_n(attention_mask->data<int64_t>(), past_len, kv_attn_mask->data<int64_t>());
- // Clear stale entries left by a larger past (e.g. after speculative-decoding trim).
- if (past_len < dest_past_capacity) {
- std::fill_n(kv_attn_mask->data<int64_t>() + past_len, dest_past_capacity - past_len, 0);
- }
- if (input_tokens_len < kvcache_desc.max_generation_token_len) {
- std::fill_n(
- kv_attn_mask->data<int64_t>() + kv_attn_mask->get_size() - kvcache_desc.max_generation_token_len,
- kvcache_desc.max_generation_token_len - input_tokens_len,
- 0);
+ if (m_npuw_llm_compiled_model->m_attention_mask_is_4d_float) {
+ stage_additive_attention_mask_for_generate(attention_mask,
+ kv_attn_mask,
+ kvcache_desc.num_stored_tokens,
+ input_tokens_len,
+ kvcache_desc.max_generation_token_len);
+ } else {
+ stage_binary_attention_mask_for_generate(attention_mask,
+ kv_attn_mask,
+ kvcache_desc.num_stored_tokens,
+ input_tokens_len,
+ kvcache_desc.max_generation_token_len);
}
- std::fill_n(kv_attn_mask->data<int64_t>() + kv_attn_mask->get_size() - input_tokens_len, input_tokens_len, 1);
if (m_position_ids_present) {
auto kv_pos_ids = m_kvcache_request->get_tensor(m_kvcache_in_ports.at(layer_names::position_ids));
@@ -1885,7 +2112,13 @@ void ov::npuw::LLMInferRequest::infer() {
// NB: For VLM, the "inputs_embeds" contains float values (embeddings)
OPENVINO_ASSERT(ov::element::f32 == input_ids->get_element_type() ||
ov::element::i64 == input_ids->get_element_type());
- OPENVINO_ASSERT(ov::element::i64 == attention_mask->get_element_type());
+ if (m_npuw_llm_compiled_model->m_attention_mask_is_4d_float) {
+ OPENVINO_ASSERT(attention_mask->get_element_type().is_real(),
+ "4D additive attention_mask must use a floating-point element type.");
+ OPENVINO_ASSERT(attention_mask->get_shape().size() == 4u, "4D additive attention_mask must be rank 4.");
+ } else {
+ OPENVINO_ASSERT(ov::element::i64 == attention_mask->get_element_type());
+ }
OPENVINO_ASSERT(ov::element::i64 == position_ids->get_element_type());
// Eagle3: Store Eagle3 specific inputs with pre-validation
diff --git a/src/plugins/intel_npu/src/plugin/npuw/npuw_transformations/reshape_to_static.cpp b/src/plugins/intel_npu/src/plugin/npuw/npuw_transformations/reshape_to_static.cpp
index 97cbd588ee7..eb2a336bb77 100644
--- a/src/plugins/intel_npu/src/plugin/npuw/npuw_transformations/reshape_to_static.cpp
+++ b/src/plugins/intel_npu/src/plugin/npuw/npuw_transformations/reshape_to_static.cpp
@@ -56,10 +56,16 @@ void reshape_to_static(std::shared_ptr<ov::Model> model,
NPUW_ASSERT(num_layers.is_static()); // num_deepstack_layers must be resolved
new_shape = ov::PartialShape({num_layers, input_size, partial_shape[2]});
} else if (input_name.find("attention_mask") != std::string::npos) {
- new_shape = ov::PartialShape({1, kvcache_size});
- if (lhs_seq_size && !is_prefill)
- // NB: for whisper kvcache model attn mask should be size + 1
- new_shape = ov::PartialShape({1, kvcache_size + 1});
+ const auto& mask_shape = input.get_partial_shape();
+ if (mask_shape.rank().is_static() && mask_shape.size() == 4u && input.get_element_type().is_real()) {
+ // 4D float additive mask layout: [B, 1, Q, K].
+ new_shape = ov::PartialShape({1, 1, input_size, kvcache_size});
+ } else {
+ new_shape = ov::PartialShape({1, kvcache_size});
+ if (lhs_seq_size && !is_prefill)
+ // NB: for whisper kvcache model attn mask should be size + 1
+ new_shape = ov::PartialShape({1, kvcache_size + 1});
+ }
} else if (input_name.find(ov::npuw::util::kVisualPosMasksParamName) != std::string::npos) {
new_shape = ov::PartialShape({1, input_size});
} else if (input_name.find("position_ids") != std::string::npos) {
diff --git a/src/plugins/intel_npu/tests/functional/behavior/npuw/test_engine/models/model_builder.cpp b/src/plugins/intel_npu/tests/functional/behavior/npuw/test_engine/models/model_builder.cpp
index 1314358cae2..863dfb8d62c 100644
--- a/src/plugins/intel_npu/tests/functional/behavior/npuw/test_engine/models/model_builder.cpp
+++ b/src/plugins/intel_npu/tests/functional/behavior/npuw/test_engine/models/model_builder.cpp
@@ -788,7 +788,13 @@ std::shared_ptr<ov::Model> ModelBuilder::build_llm(const LLMConfig& config_in) {
}
const auto prec = config.precision;
- auto attention_mask = parameter(ov::element::i64, ov::PartialShape{-1, -1}, "attention_mask");
+ auto attention_mask = parameter(config.attention_mask_type, config.attention_mask_shape, "attention_mask");
+ const bool mask_is_2d =
+ config.attention_mask_shape.rank().is_static() && config.attention_mask_shape.rank().get_length() == 2;
+ OPENVINO_ASSERT(mask_is_2d || (config.sliding_window_size == 0 && !config.use_token_type_ids),
+ "A ready attention_mask cannot be combined with sliding_window_size or use_token_type_ids");
+ OPENVINO_ASSERT(mask_is_2d || !config.force_gqa_broadcast,
+ "A ready attention_mask cannot be combined with force_gqa_broadcast");
ov::Output<ov::Node> hidden_states;
ov::Output<ov::Node> seq_source;
@@ -825,7 +831,13 @@ std::shared_ptr<ov::Model> ModelBuilder::build_llm(const LLMConfig& config_in) {
ov::Output<ov::Node> full_mask;
ov::Output<ov::Node> sliding_mask;
- if (has_full_layers) {
+ if (!mask_is_2d) {
+ full_mask = attention_mask->output(0);
+ if (full_mask.get_element_type().is_real() && full_mask.get_element_type() != prec) {
+ full_mask = std::make_shared<ov::opset11::Convert>(full_mask, prec);
+ }
+ }
+ if (mask_is_2d && has_full_layers) {
full_mask = config.boolean_causal_mask ? make_causal_mask_boolean(seq_source, attention_mask->output(0), prec)
: make_causal_mask(seq_source, attention_mask->output(0), prec);
}
@@ -846,7 +858,8 @@ std::shared_ptr<ov::Model> ModelBuilder::build_llm(const LLMConfig& config_in) {
// Shared GQA broadcast shape (embedding models only)
ov::Output<ov::Node> shared_broadcast;
- if ((!config.use_kv_cache && !config.lm_head_weight) || config.force_gqa_broadcast) {
+ if (mask_is_2d && ((!config.use_kv_cache && !config.lm_head_weight) || config.force_gqa_broadcast)) {
+ // The shared broadcast reads the batch and the key length from dims 0 and 1 of a 2D mask.
shared_broadcast = make_shared_gqa_broadcast(attention_mask->output(0),
config.get_kv_heads(),
config.num_heads,
diff --git a/src/plugins/intel_npu/tests/functional/behavior/npuw/test_engine/models/model_builder.hpp b/src/plugins/intel_npu/tests/functional/behavior/npuw/test_engine/models/model_builder.hpp
index de8db0512f6..173c04a0fbb 100644
--- a/src/plugins/intel_npu/tests/functional/behavior/npuw/test_engine/models/model_builder.hpp
+++ b/src/plugins/intel_npu/tests/functional/behavior/npuw/test_engine/models/model_builder.hpp
@@ -180,6 +180,13 @@ struct LLMConfig : public BaseModelConfig {
bool use_kv_cache = true;
bool use_inputs_embeds = false;
bool internal_position_ids = false; ///< embedding model
+
+ /// attention_mask input. The default 2D int64 mask is turned into the causal mask for SDPA. A mask of any other
+ /// rank (e.g. 4D float [B, 1, Q, K]) is a ready SDPA mask and replaces the causal mask; it cannot be combined
+ /// with sliding_window_size or use_token_type_ids, which build on the 2D mask.
+ ov::element::Type attention_mask_type = ov::element::i64;
+ ov::PartialShape attention_mask_shape = ov::PartialShape{-1, -1};
+
bool pre_norm = true;
bool force_gqa_broadcast = false; ///< force 5-input SDPA (needed for SDPA isolation pattern matching)
diff --git a/src/plugins/intel_npu/tests/unit/CMakeLists.txt b/src/plugins/intel_npu/tests/unit/CMakeLists.txt
index 0be0744a202..bc1339cca73 100644
--- a/src/plugins/intel_npu/tests/unit/CMakeLists.txt
+++ b/src/plugins/intel_npu/tests/unit/CMakeLists.txt
@@ -186,6 +186,7 @@ target_sources(${TARGET_NAME} PRIVATE
${CMAKE_CURRENT_SOURCE_DIR}/npu/zero_extension_query_test.cpp
${CMAKE_CURRENT_SOURCE_DIR}/npuw/llm_compiled_model_graph_options_test.cpp
${CMAKE_CURRENT_SOURCE_DIR}/npuw/llm_compiled_model_set_property_test.cpp
+ ${CMAKE_CURRENT_SOURCE_DIR}/npuw/llm_4d_float_attention_mask_test.cpp
${CMAKE_CURRENT_SOURCE_DIR}/npuw/flux2_compiled_model_test.cpp
${CMAKE_CURRENT_SOURCE_DIR}/npuw/gqa_compiled_model_test.cpp
${CMAKE_CURRENT_SOURCE_DIR}/npuw/gather_sub128_matcher_test.cpp
diff --git a/src/plugins/intel_npu/tests/unit/npuw/llm_4d_float_attention_mask_test.cpp b/src/plugins/intel_npu/tests/unit/npuw/llm_4d_float_attention_mask_test.cpp
new file mode 100644
index 00000000000..6548f420df7
--- /dev/null
+++ b/src/plugins/intel_npu/tests/unit/npuw/llm_4d_float_attention_mask_test.cpp
@@ -0,0 +1,572 @@
+// Copyright (C) 2018-2026 Intel Corporation
+// SPDX-License-Identifier: Apache-2.0
+//
+
+// Tests for the 4D float (additive) attention_mask contract of the NPUW LLM pipeline: how the mask is detected,
+// which options reject it, how its shape is made static, how the infer request stages it for prefill and
+// generate, and that an exported and imported model keeps the contract.
+
+#include <gtest/gtest.h>
+
+#include <algorithm>
+#include <filesystem>
+#include <functional>
+#include <limits>
+#include <memory>
+#include <numeric>
+#include <sstream>
+#include <string>
+#include <utility>
+#include <vector>
+
+#include "common_test_utils/data_utils.hpp"
+#include "llm_compiled_model.hpp"
+#include "llm_infer_request.hpp"
+#include "llm_test_helpers.hpp"
+#include "openvino/core/type/float16.hpp"
+#include "openvino/pass/serialize.hpp"
+#include "openvino/runtime/core.hpp"
+#include "openvino/runtime/properties.hpp"
+#include "util.hpp"
+
+namespace {
+
+using ov::npuw::util::find_port_by_name;
+using ov::test::npuw::build_llm_test_model;
+using ov::test::npuw::build_whisper_decoder_test_model;
+using ov::test::npuw::LLMConfig;
+using ov::test::npuw::make_test_model_config;
+using ov::test::npuw::NullPlugin;
+using ov::test::npuw::RecordingFactory;
+using ov::test::utils::make_tensor_with_precision_convert;
+
+class TestableLLMCompiledModel final : public ov::npuw::LLMCompiledModel {
+public:
+ using ov::npuw::LLMCompiledModel::LLMCompiledModel;
+
+ bool attention_mask_is_4d_float() const {
+ return m_attention_mask_is_4d_float;
+ }
+};
+
+// The test model config with a 4D float [B, 1, Q, K] attention_mask of the given type.
+LLMConfig make_4d_float_mask_config(const ov::element::Type& type) {
+ auto config = make_test_model_config();
+ config.attention_mask_type = type;
+ config.attention_mask_shape = ov::PartialShape{-1, 1, -1, -1};
+ return config;
+}
+
+constexpr size_t kMaxPromptLen = 128;
+constexpr size_t kMinResponseLen = 64;
+
+ov::AnyMap make_props(const ov::AnyMap& extra = {}) {
+ ov::AnyMap props{{"NPUW_LLM", "YES"},
+ {"NPUW_DEVICES", "CPU"},
+ {"NPUW_LLM_MAX_PROMPT_LEN", std::to_string(kMaxPromptLen)},
+ {"NPUW_LLM_MIN_RESPONSE_LEN", std::to_string(kMinResponseLen)},
+ {"NPUW_LLM_PREFILL_HINT", "STATIC"}};
+ for (const auto& [key, value] : extra) {
+ props[key] = value;
+ }
+ return props;
+}
+
+class LLM4DFloatAttentionMaskTest : public ::testing::Test {
+protected:
+ void SetUp() override {
+ m_plugin = std::make_shared<NullPlugin>();
+ }
+
+ std::unique_ptr<TestableLLMCompiledModel> compile(const std::shared_ptr<ov::Model>& model,
+ const ov::AnyMap& props) {
+ return std::make_unique<TestableLLMCompiledModel>(model, m_plugin, props, m_recorder.make_factory());
+ }
+
+ std::shared_ptr<ov::IPlugin> m_plugin;
+ RecordingFactory m_recorder;
+};
+
+TEST_F(LLM4DFloatAttentionMaskTest, Binary2DMaskIsNotDetected) {
+ std::unique_ptr<TestableLLMCompiledModel> compiled;
+ ASSERT_NO_THROW(compiled = compile(build_llm_test_model(), make_props()));
+ EXPECT_FALSE(compiled->attention_mask_is_4d_float());
+}
+
+TEST_F(LLM4DFloatAttentionMaskTest, Rank2MaskIsNotDetectedWhateverItsElementType) {
+ auto config = make_test_model_config();
+ config.attention_mask_type = ov::element::f32;
+
+ std::unique_ptr<TestableLLMCompiledModel> compiled;
+ ASSERT_NO_THROW(compiled = compile(build_llm_test_model(config), make_props()));
+ EXPECT_FALSE(compiled->attention_mask_is_4d_float());
+}
+
+TEST_F(LLM4DFloatAttentionMaskTest, ModelWithoutAttentionMaskIsNotDetected) {
+ std::unique_ptr<TestableLLMCompiledModel> compiled;
+ ASSERT_NO_THROW(compiled = compile(build_whisper_decoder_test_model(),
+ {{"NPUW_LLM", "YES"},
+ {"NPUW_LLM_MAX_PROMPT_LEN", std::to_string(kMaxPromptLen)},
+ {"NPUW_LLM_MIN_RESPONSE_LEN", std::to_string(kMinResponseLen)},
+ {"NPUW_WHISPER", "YES"},
+ {"NPUW_WHISPER_EOS_TOKEN", "42"}}));
+ EXPECT_FALSE(compiled->attention_mask_is_4d_float());
+}
+
+TEST_F(LLM4DFloatAttentionMaskTest, RejectsMaskContractsOtherThanRank2OrFloatRank4) {
+ struct Case {
+ const char* what;
+ ov::element::Type type;
+ ov::PartialShape shape;
+ };
+ const std::vector<Case> cases = {
+ {"rank 3 float", ov::element::f32, ov::PartialShape{-1, -1, -1}},
+ {"rank 4 boolean", ov::element::boolean, ov::PartialShape{-1, 1, -1, -1}},
+ {"dynamic rank float", ov::element::f32, ov::PartialShape::dynamic()},
+ };
+ for (const auto& test_case : cases) {
+ SCOPED_TRACE(test_case.what);
+ auto config = make_4d_float_mask_config(test_case.type);
+ config.attention_mask_shape = test_case.shape;
+ EXPECT_THROW(compile(build_llm_test_model(config), make_props()), ov::Exception);
+ }
+}
+
+// Each option below is accepted with the 2D int64 mask and rejected with NotImplemented for 4D float.
+// Change when 4d float is supported for these features
+TEST_F(LLM4DFloatAttentionMaskTest, ChunkedPrefillIsRejected) {
+ const auto props = make_props({{"NPUW_LLM_PREFILL_HINT", "DYNAMIC"}, {"NPUW_LLM_PREFILL_CHUNK_SIZE", "32"}});
+ EXPECT_NO_THROW(compile(build_llm_test_model(), props));
+ EXPECT_THROW(compile(build_llm_test_model(make_4d_float_mask_config(ov::element::f32)), props), ov::NotImplemented);
+}
+
+TEST_F(LLM4DFloatAttentionMaskTest, PrefixCachingIsRejected) {
+ const auto props = make_props({{"NPUW_LLM_ENABLE_PREFIX_CACHING", "YES"}});
+ EXPECT_NO_THROW(compile(build_llm_test_model(), props));
+ EXPECT_THROW(compile(build_llm_test_model(make_4d_float_mask_config(ov::element::f32)), props), ov::NotImplemented);
+}
+
+TEST_F(LLM4DFloatAttentionMaskTest, SwaKVCacheShrinkIsRejected) {
+ const auto props = make_props({{"NPUW_LLM_ENABLE_SWA_KV_CACHE_SHRINK", "YES"}});
+ EXPECT_NO_THROW(compile(build_llm_test_model(), props));
+ EXPECT_THROW(compile(build_llm_test_model(make_4d_float_mask_config(ov::element::f32)), props), ov::NotImplemented);
+}
+
+TEST_F(LLM4DFloatAttentionMaskTest, BlockBasedKVCacheIsRejected) {
+ const auto props = make_props({{"NPUW_LLM_ENABLE_BLOCK_BASED_KV_CACHE", "YES"}});
+ EXPECT_NO_THROW(compile(build_llm_test_model(), props));
+ EXPECT_THROW(compile(build_llm_test_model(make_4d_float_mask_config(ov::element::f32)), props), ov::NotImplemented);
+}
+
+TEST_F(LLM4DFloatAttentionMaskTest, TextEmbeddingIsRejected) {
+ const auto props = make_props({{"NPUW_TEXT_EMBED", "YES"}});
+ auto config = make_test_model_config();
+ config.use_kv_cache = false;
+ config.internal_position_ids = true;
+ config.lm_head_weight = {};
+ EXPECT_NO_THROW(compile(build_llm_test_model(config), props));
+
+ config.attention_mask_type = ov::element::f32;
+ config.attention_mask_shape = ov::PartialShape{-1, 1, -1, -1};
+ EXPECT_THROW(compile(build_llm_test_model(config), props), ov::NotImplemented);
+}
+
+class TestableLLMInferRequest final : public ov::npuw::LLMInferRequest {
+public:
+ explicit TestableLLMInferRequest(const std::shared_ptr<ov::npuw::LLMCompiledModel>& compiled_model)
+ : ov::npuw::LLMInferRequest(compiled_model) {}
+
+ ov::SoPtr<ov::ITensor> prefill_attention_mask() const {
+ return m_prefill_request->get_tensor(m_prefill_in_ports.at(layer_names::attention_mask));
+ }
+
+ ov::SoPtr<ov::ITensor> generate_attention_mask() const {
+ return m_kvcache_request->get_tensor(m_kvcache_in_ports.at(layer_names::attention_mask));
+ }
+};
+
+constexpr size_t kMarkerSize = 16;
+
+// A distinct, negative value for every (row, column) of a mask up to kMarkerSize x kMarkerSize. The largest
+// magnitude is 256, which f32, f16 and bf16 all represent exactly. The masks in these tests are small on purpose.
+float marker(size_t row, size_t column) {
+ return -static_cast<float>(1 + row * kMarkerSize + column);
+}
+
+// An f32 tensor [1, 1, rows, columns] with value(row, column) in every position.
+ov::Tensor make_tensor_values(size_t rows, size_t columns, const std::function<float(size_t, size_t)>& value) {
+ ov::Tensor values(ov::element::f32, ov::Shape{1, 1, rows, columns});
+ for (size_t row = 0; row < rows; ++row) {
+ for (size_t column = 0; column < columns; ++column) {
+ values.data<float>()[row * columns + column] = value(row, column);
+ }
+ }
+ return values;
+}
+
+ov::Tensor make_marker_mask(const ov::element::Type& type, size_t rows, size_t columns) {
+ OPENVINO_ASSERT(rows <= kMarkerSize && columns <= kMarkerSize,
+ "marker() values are distinct and exact only for masks up to ",
+ kMarkerSize,
+ " x ",
+ kMarkerSize);
+ return make_tensor_with_precision_convert(make_tensor_values(rows, columns, marker), type);
+}
+
+ov::Tensor make_i64(std::initializer_list<size_t> shape, int64_t fill_value) {
+ ov::Tensor tensor(ov::element::i64, ov::Shape(shape));
+ std::fill_n(tensor.data<int64_t>(), tensor.get_size(), fill_value);
+ return tensor;
+}
+
+ov::Tensor make_i64_iota(std::initializer_list<size_t> shape, int64_t start) {
+ ov::Tensor tensor(ov::element::i64, ov::Shape(shape));
+ std::iota(tensor.data<int64_t>(), tensor.data<int64_t>() + tensor.get_size(), start);
+ return tensor;
+}
+
+class LLM4DFloatAttentionMaskStagingTest : public LLM4DFloatAttentionMaskTest {
+protected:
+ void compile_with_mask_type(const ov::element::Type& type, const ov::AnyMap& extra_props = {}) {
+ m_type = type;
+ m_compiled = compile(build_llm_test_model(make_4d_float_mask_config(type)), make_props(extra_props));
+ }
+
+ TestableLLMInferRequest& request() {
+ if (!m_request) {
+ m_request = std::make_unique<TestableLLMInferRequest>(m_compiled);
+ }
+ return *m_request;
+ }
+
+ void set_inputs(const ov::Tensor& input_ids, const ov::Tensor& attention_mask, const ov::Tensor& position_ids) {
+ const auto& inputs = request().get_inputs();
+ request().set_tensor(find_port_by_name(inputs, "input_ids").value(), ov::get_tensor_impl(input_ids));
+ request().set_tensor(find_port_by_name(inputs, "attention_mask").value(), ov::get_tensor_impl(attention_mask));
+ request().set_tensor(find_port_by_name(inputs, "position_ids").value(), ov::get_tensor_impl(position_ids));
+ }
+
+ void run_prefill(size_t prompt_len) {
+ run_prefill(prompt_len, prompt_len, prompt_len);
+ }
+
+ void run_prefill(size_t prompt_len, size_t mask_queries, size_t mask_keys) {
+ set_inputs(make_i64({1, prompt_len}, 1), // just a filler
+ make_marker_mask(m_type, mask_queries, mask_keys),
+ make_i64_iota({1, prompt_len}, 0)); // filled [0..prompt_len-1]
+ request().infer();
+ }
+
+ // The caller mask covers the stored past and the current token: [1, 1, 1, past + 1].
+ void run_generate_step(size_t past_len, size_t mask_keys) {
+ set_inputs(make_i64({1, 1}, 1), // just a filler
+ make_marker_mask(m_type, 1, mask_keys),
+ make_i64({1, 1}, static_cast<int64_t>(past_len))); // filled with the next value
+ request().infer();
+ }
+
+ // The caller mask covers the stored past and the `tokens` current ones: [1, 1, tokens, past + tokens].
+ void run_generate_tokens(size_t past_len, size_t tokens) {
+ set_inputs(make_i64({1, tokens}, 1), // just a filler
+ make_marker_mask(m_type, tokens, past_len + tokens),
+ make_i64_iota({1, tokens}, static_cast<int64_t>(past_len))); // filled [past..past+tokens-1]
+ request().infer();
+ }
+
+ ov::element::Type m_type;
+ std::shared_ptr<TestableLLMCompiledModel> m_compiled;
+ std::unique_ptr<TestableLLMInferRequest> m_request;
+};
+
+float padding_value() {
+ return static_cast<float>(std::numeric_limits<ov::float16>::lowest());
+}
+
+// Checks every cell of the staged mask and reports the first one that differs from expected(row, column).
+void expect_cells(const ov::SoPtr<ov::ITensor>& staged, const std::function<float(size_t, size_t)>& expected) {
+ const auto& shape = staged->get_shape();
+ ASSERT_EQ(shape.size(), 4u);
+ ASSERT_TRUE(staged->is_continuous()); // the conversion to f32 below reads the data linearly
+ const auto actual = make_tensor_with_precision_convert(ov::make_tensor(staged), ov::element::f32);
+ const auto wanted = make_tensor_values(shape[2], shape[3], expected);
+
+ const float* wanted_begin = wanted.data<float>();
+ const float* wanted_end = wanted_begin + wanted.get_size();
+ const float* actual_begin = actual.data<float>();
+ const auto [wanted_diff, actual_diff] = std::mismatch(wanted_begin, wanted_end, actual_begin);
+ if (wanted_diff != wanted_end) {
+ const size_t index = wanted_diff - wanted_begin;
+ ADD_FAILURE() << "first mismatch at [" << index / shape[3] << ", " << index % shape[3] << "]: got "
+ << *actual_diff << ", expected " << *wanted_diff;
+ }
+}
+
+class LLM4DFloatAttentionMaskByTypeTest : public LLM4DFloatAttentionMaskStagingTest,
+ public ::testing::WithParamInterface<ov::element::Type> {
+protected:
+ void SetUp() override {
+ LLM4DFloatAttentionMaskStagingTest::SetUp();
+ compile_with_mask_type(GetParam());
+ }
+};
+
+TEST_P(LLM4DFloatAttentionMaskByTypeTest, MaskIsDetectedAndMadeStatic) {
+ EXPECT_TRUE(m_compiled->attention_mask_is_4d_float());
+
+ const auto* prefill = m_recorder.find_contains("_prefill");
+ const auto* generate = m_recorder.find_contains("_kv");
+ ASSERT_NE(prefill, nullptr);
+ ASSERT_NE(generate, nullptr);
+
+ const auto prefill_mask = find_port_by_name(std::as_const(*prefill->model).inputs(), "attention_mask").value();
+ const auto generate_mask = find_port_by_name(std::as_const(*generate->model).inputs(), "attention_mask").value();
+ EXPECT_EQ(prefill_mask.get_partial_shape(), (ov::PartialShape{1, 1, kMaxPromptLen, kMaxPromptLen}));
+ EXPECT_EQ(generate_mask.get_partial_shape(), (ov::PartialShape{1, 1, 1, kMaxPromptLen + kMinResponseLen}));
+ EXPECT_EQ(prefill_mask.get_element_type(), GetParam());
+ EXPECT_EQ(generate_mask.get_element_type(), GetParam());
+}
+
+// Prefill puts the caller mask's [Q, Q] block at the bottom-right corner of the static [P, P] mask;
+// every padded position is fully masked.
+TEST_P(LLM4DFloatAttentionMaskByTypeTest, PrefillPutsTheMaskIntoTheBottomRightCorner) {
+ constexpr size_t kPromptLen = 5;
+ run_prefill(kPromptLen);
+
+ const auto staged = request().prefill_attention_mask();
+ const size_t size = staged->get_shape()[2];
+ ASSERT_EQ(staged->get_shape(), (ov::Shape{1, 1, size, size}));
+ const size_t offset = size - kPromptLen;
+ const float masked = padding_value();
+ expect_cells(staged, [&](size_t row, size_t column) {
+ return (row >= offset && column >= offset) ? marker(row - offset, column - offset) : masked;
+ });
+}
+
+// Prefill does not expand or realign the caller mask, so it should be [prompt, prompt],
+// else it would leave real tokens fully masked or shifted.
+TEST_P(LLM4DFloatAttentionMaskByTypeTest, PrefillRejectsMaskThatDoesNotCoverThePrompt) {
+ constexpr size_t kPromptLen = 5;
+ const std::vector<std::pair<size_t, size_t>> mask_shapes = {{1, kPromptLen}, // broadcast over the queries
+ {kPromptLen, 1}, // broadcast over the keys
+ {kPromptLen, kPromptLen - 1},
+ {kPromptLen, kPromptLen + 1},
+ {kPromptLen - 1, kPromptLen},
+ {kPromptLen + 1, kPromptLen}};
+ for (const auto& [queries, keys] : mask_shapes) {
+ SCOPED_TRACE("mask [" + std::to_string(queries) + ", " + std::to_string(keys) + "]");
+ EXPECT_THROW(run_prefill(kPromptLen, queries, keys), ov::Exception);
+ }
+}
+
+// Generate puts the stored past on the left and the current token in the last column
+TEST_P(LLM4DFloatAttentionMaskByTypeTest, GenerateSplitsTheMaskIntoPastAndCurrentColumns) {
+ constexpr size_t kPromptLen = 5;
+ run_prefill(kPromptLen);
+
+ const float masked = padding_value();
+ for (size_t step = 0; step < 2; ++step) {
+ SCOPED_TRACE("generate step " + std::to_string(step));
+ const size_t past_len = kPromptLen + step;
+ run_generate_step(past_len, past_len + 1);
+
+ const auto staged = request().generate_attention_mask();
+ const size_t width = staged->get_shape()[3];
+ ASSERT_EQ(staged->get_shape(), (ov::Shape{1, 1, 1, width}));
+ expect_cells(staged, [&](size_t, size_t column) {
+ if (column < past_len) {
+ return marker(0, column);
+ }
+ return column == width - 1 ? marker(0, past_len) : masked;
+ });
+ }
+}
+
+// With several current tokens, each row has its own past and current columns,
+// and the rows above them stay fully masked.
+TEST_P(LLM4DFloatAttentionMaskByTypeTest, GenerateStagesEveryRowOfAWindowOfSeveralTokens) {
+ // NPUW rounds a generation window above 1 up to a multiple of 8.
+ constexpr size_t kWindow = 8;
+ compile_with_mask_type(GetParam(), {{"NPUW_LLM_MAX_GENERATION_TOKEN_LEN", std::to_string(kWindow)}});
+ constexpr size_t kPromptLen = 5;
+ run_prefill(kPromptLen);
+
+ // The second step trims the KV cache back to the prompt, so the shorter window sits over rows the first one used.
+ const float masked = padding_value();
+ for (const size_t tokens : {kWindow, size_t{2}}) {
+ SCOPED_TRACE("tokens " + std::to_string(tokens));
+ run_generate_tokens(kPromptLen, tokens);
+
+ const auto staged = request().generate_attention_mask();
+ const size_t width = staged->get_shape()[3];
+ ASSERT_EQ(staged->get_shape(), (ov::Shape{1, 1, kWindow, width}));
+ const size_t first_row = kWindow - tokens;
+ expect_cells(staged, [&](size_t row, size_t column) {
+ if (row < first_row) {
+ return masked;
+ }
+ if (column < kPromptLen) {
+ return marker(row - first_row, column);
+ }
+ return column >= width - tokens ? marker(row - first_row, kPromptLen + column - (width - tokens)) : masked;
+ });
+ }
+}
+
+TEST_P(LLM4DFloatAttentionMaskByTypeTest, GenerateRejectsMaskThatDisagreesWithTheStoredPast) {
+ constexpr size_t kPromptLen = 5;
+ run_prefill(kPromptLen);
+
+ EXPECT_THROW(run_generate_step(kPromptLen, kPromptLen + 3), ov::Exception);
+}
+
+INSTANTIATE_TEST_SUITE_P(AdditiveMaskTypes,
+ LLM4DFloatAttentionMaskByTypeTest,
+ ::testing::Values(ov::element::f32, ov::element::f16),
+ [](const ::testing::TestParamInfo<ov::element::Type>& info) {
+ return info.param.to_string();
+ });
+
+// The NPUW LLM pipeline converts bf16 to f16 for its sub-models,
+// so the staged mask is f16 while the caller's is bf16, and the request rejects the mismatch on the first infer.
+// Update this test when bf16 masks get supported.
+TEST_F(LLM4DFloatAttentionMaskStagingTest, Bf16MaskIsRejectedAtInferBecauseSubmodelsUseF16) {
+ compile_with_mask_type(ov::element::bf16);
+ EXPECT_TRUE(m_compiled->attention_mask_is_4d_float());
+
+ const auto* prefill = m_recorder.find_contains("_prefill");
+ ASSERT_NE(prefill, nullptr);
+ const auto prefill_mask = find_port_by_name(std::as_const(*prefill->model).inputs(), "attention_mask").value();
+ EXPECT_EQ(prefill_mask.get_element_type(), ov::element::f16);
+
+ EXPECT_THROW(run_prefill(5), ov::Exception);
+}
+
+// An additive causal mask [1, 1, rows, columns] for `rows` new tokens that follow `columns - rows` stored ones.
+ov::Tensor make_causal_mask(size_t rows, size_t columns) {
+ ov::Tensor mask(ov::element::f32, ov::Shape{1, 1, rows, columns});
+ const size_t past_len = columns - rows;
+ for (size_t row = 0; row < rows; ++row) {
+ for (size_t column = 0; column < columns; ++column) {
+ mask.data<float>()[row * columns + column] =
+ column <= row + past_len ? 0.0f : std::numeric_limits<float>::lowest();
+ }
+ }
+ return mask;
+}
+
+// Runs the prompt as one prefill, then single-token generate steps, and returns the logits of every step.
+std::vector<ov::Tensor> run_prefill_and_generate_logits(ov::CompiledModel& compiled,
+ size_t prompt_len,
+ size_t generate_steps) {
+ auto request = compiled.create_infer_request();
+ ov::Tensor beam_idx(ov::element::i32, ov::Shape{1});
+ beam_idx.data<int32_t>()[0] = 0;
+ std::vector<ov::Tensor> logits;
+ const auto step = [&](size_t past_len, size_t new_tokens) {
+ request.set_tensor("input_ids", make_i64_iota({1, new_tokens}, static_cast<int64_t>(1 + past_len)));
+ request.set_tensor("attention_mask", make_causal_mask(new_tokens, past_len + new_tokens));
+ request.set_tensor("position_ids", make_i64_iota({1, new_tokens}, static_cast<int64_t>(past_len)));
+ request.set_tensor("beam_idx", beam_idx);
+ request.infer();
+ auto output = request.get_output_tensor(0);
+ ov::Tensor copy(output.get_element_type(), output.get_shape());
+ output.copy_to(copy);
+ logits.push_back(make_tensor_with_precision_convert(copy, ov::element::f32));
+ };
+ step(0, prompt_len);
+ for (size_t i = 0; i < generate_steps; ++i) {
+ step(prompt_len + i, 1);
+ }
+ return logits;
+}
+
+class LLM4DFloatAttentionMaskRoundTrip : public ::testing::Test {
+protected:
+ void SetUp() override {
+ m_dir = std::filesystem::temp_directory_path() / "npuw_4d_float_mask_round_trip";
+ std::filesystem::create_directories(m_dir);
+ }
+
+ void TearDown() override {
+ std::error_code ec;
+ std::filesystem::remove_all(m_dir, ec);
+ }
+
+ std::filesystem::path m_dir;
+};
+
+// Check that the imported model gives the same logits as the compiled one
+TEST_F(LLM4DFloatAttentionMaskRoundTrip, ImportedModelRunsLikeTheCompiledOne) {
+ constexpr size_t kGenerateSteps = 2;
+
+ ov::Core core;
+ const auto xml = m_dir / "model.xml";
+ const auto bin = m_dir / "model.bin";
+ ov::serialize(build_llm_test_model(make_4d_float_mask_config(ov::element::f32)), xml.string(), bin.string());
+ const auto model = core.read_model(xml.string(), bin.string());
+
+ // compiling with NPUW_ONLINE_PIPELINE=NONE because of the synthetic model
+ const auto props = make_props({{"NPU_USE_NPUW", "YES"}, {"NPUW_ONLINE_PIPELINE", "NONE"}});
+ const auto prompt_len = props.at("NPUW_LLM_MAX_PROMPT_LEN").as<size_t>();
+ auto compiled = core.compile_model(model, "NPU", props);
+
+ std::stringstream blob;
+ compiled.export_model(blob);
+ auto import_props = props;
+ import_props[ov::weights_path.name()] = bin.string();
+ auto imported = core.import_model(blob, "NPU", import_props);
+
+ const auto expected = run_prefill_and_generate_logits(compiled, prompt_len, kGenerateSteps);
+ const auto actual = run_prefill_and_generate_logits(imported, prompt_len, kGenerateSteps);
+ ASSERT_EQ(actual.size(), expected.size());
+ for (size_t step = 0; step < expected.size(); ++step) {
+ SCOPED_TRACE("step " + std::to_string(step));
+ ASSERT_EQ(actual[step].get_shape(), expected[step].get_shape());
+ for (size_t i = 0; i < expected[step].get_size(); ++i) {
+ ASSERT_NEAR(actual[step].data<float>()[i], expected[step].data<float>()[i], 1e-5f) << "element " << i;
+ }
+ }
+}
+
+class LLM4DFloatAttentionMaskPrecisionTest : public ::testing::TestWithParam<ov::element::Type> {};
+
+TEST_P(LLM4DFloatAttentionMaskPrecisionTest, ShortPromptGivesTheF32Logits) {
+ constexpr size_t kPromptLen = 5;
+ constexpr size_t kGenerateSteps = 2;
+ constexpr float kTolerance = 0.05f;
+
+ ov::Core core;
+ const std::string capability = GetParam() == ov::element::bf16 ? "BF16" : "FP16";
+ const auto capabilities = core.get_property("CPU", ov::device::capabilities);
+ if (std::find(capabilities.begin(), capabilities.end(), capability) == capabilities.end()) {
+ GTEST_SKIP() << "The CPU does not support " << capability;
+ }
+
+ const auto compile = [&](const ov::element::Type& precision) {
+ auto props = make_props({{"NPU_USE_NPUW", "YES"}, {"NPUW_ONLINE_PIPELINE", "NONE"}});
+ props[ov::hint::inference_precision.name()] = precision;
+ return core.compile_model(build_llm_test_model(make_4d_float_mask_config(ov::element::f32)), "NPU", props);
+ };
+ auto reference_model = compile(ov::element::f32);
+ auto model_under_test = compile(GetParam());
+
+ const auto expected = run_prefill_and_generate_logits(reference_model, kPromptLen, kGenerateSteps);
+ const auto actual = run_prefill_and_generate_logits(model_under_test, kPromptLen, kGenerateSteps);
+ ASSERT_EQ(actual.size(), expected.size());
+ for (size_t step = 0; step < expected.size(); ++step) {
+ SCOPED_TRACE("step " + std::to_string(step));
+ ASSERT_EQ(actual[step].get_shape(), expected[step].get_shape());
+ for (size_t i = 0; i < expected[step].get_size(); ++i) {
+ ASSERT_NEAR(actual[step].data<float>()[i], expected[step].data<float>()[i], kTolerance) << "element " << i;
+ }
+ }
+}
+
+INSTANTIATE_TEST_SUITE_P(CpuPrecisions,
+ LLM4DFloatAttentionMaskPrecisionTest,
+ ::testing::Values(ov::element::bf16, ov::element::f16),
+ [](const ::testing::TestParamInfo<ov::element::Type>& info) {
+ return info.param.to_string();
+ });
+
+} // namespace
diff --git a/src/plugins/intel_npu/tests/unit/npuw/llm_test_helpers.hpp b/src/plugins/intel_npu/tests/unit/npuw/llm_test_helpers.hpp
index 1daf9df4704..1b53151ad49 100644
--- a/src/plugins/intel_npu/tests/unit/npuw/llm_test_helpers.hpp
+++ b/src/plugins/intel_npu/tests/unit/npuw/llm_test_helpers.hpp
@@ -43,9 +43,13 @@ inline Config make_test_model_config() {
return cfg;
}
-inline std::shared_ptr<ov::Model> build_llm_test_model() {
+inline std::shared_ptr<ov::Model> build_llm_test_model(const LLMConfig& cfg) {
ModelBuilder mb;
- return mb.build_llm(make_test_model_config());
+ return mb.build_llm(cfg);
+}
+
+inline std::shared_ptr<ov::Model> build_llm_test_model() {
+ return build_llm_test_model(make_test_model_config());
}
/// Phi-style LongRoPE LLM: the RoPE inverse frequencies are picked from
diff --git a/src/plugins/intel_npu/tests/unit/npuw/pipeline_passes/reshape_to_static_test.cpp b/src/plugins/intel_npu/tests/unit/npuw/pipeline_passes/reshape_to_static_test.cpp
index 529a5c6e263..635bd575096 100644
--- a/src/plugins/intel_npu/tests/unit/npuw/pipeline_passes/reshape_to_static_test.cpp
+++ b/src/plugins/intel_npu/tests/unit/npuw/pipeline_passes/reshape_to_static_test.cpp
@@ -383,4 +383,21 @@ TEST(ReshapeToStaticVLMTest, AttentionMaskIsAffectedByWhisperPath) {
EXPECT_TRUE(found) << "attention_mask input not found in model";
}
+TEST(ReshapeToStaticVLMTest, FourDimensionalFloatAttentionMaskHasStaticQueryAndKeyDimensions) {
+ auto attention_mask = std::make_shared<ov::op::v0::Parameter>(ov::element::f32, ov::PartialShape{1, 1, -1, -1});
+ attention_mask->output(0).set_names({"attention_mask"});
+ auto model = std::make_shared<ov::Model>(ov::ResultVector{std::make_shared<ov::op::v0::Result>(attention_mask)},
+ ov::ParameterVector{attention_mask});
+ auto generate_model = model->clone();
+ KVAxesPosition kv_axes{0, 1};
+
+ ReshapeToStatic prefill(128, 128, kv_axes, 0, 0, true);
+ ASSERT_TRUE(prefill.run_on_model(model));
+ EXPECT_EQ(model->input("attention_mask").get_shape(), (ov::Shape{1, 1, 128, 128}));
+
+ ReshapeToStatic generate(1, 192, kv_axes, 0, 0, false);
+ ASSERT_TRUE(generate.run_on_model(generate_model));
+ EXPECT_EQ(generate_model->input("attention_mask").get_shape(), (ov::Shape{1, 1, 1, 192}));
+}
+
} // namespace