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] Native bidirectional-encoder text-embedding path on NPU (#36189)
Dylan Neveda6f6a5d61fb
diff --git a/src/plugins/intel_npu/src/plugin/npuw/embedding/encoder_embedding_infer_request.cpp b/src/plugins/intel_npu/src/plugin/npuw/embedding/encoder_embedding_infer_request.cppnew file mode 100644index 00000000000..085bf85bbba--- /dev/null+++ b/src/plugins/intel_npu/src/plugin/npuw/embedding/encoder_embedding_infer_request.cpp@@ -0,0 +1,124 @@+// Copyright (C) 2018-2026 Intel Corporation+// SPDX-License-Identifier: Apache-2.0+//++#include "encoder_embedding_infer_request.hpp"++#include "../infer_request_utils.hpp"+#include "../logging.hpp"+#include "../util.hpp"++ov::npuw::EncoderEmbeddingInferRequest::EncoderEmbeddingInferRequest(+ const std::shared_ptr<LLMCompiledModel>& compiled_model)+ : ov::npuw::LLMInferBaseRequest(compiled_model) {+ init_ports();++ m_prefill_request = m_npuw_llm_compiled_model->m_prefill_compiled->create_infer_request();+ for (const auto& input_port : m_prefill_request->get_compiled_model()->inputs()) {+ m_prefill_in_ports.emplace(input_port.get_any_name(), input_port);+ }++ m_prefill_out_tensor = m_prefill_request->get_tensor(m_prefill_request->get_outputs()[0]);++ // The encoder is compiled as one static forward over the whole padded sequence, so its own+ // output tensor already has the shape the caller expects and is handed back as-is. That, and+ // zeroing the padding in infer(), both rely on the hidden state being [1, L, hidden].+ const auto& out_shape = m_prefill_out_tensor->get_shape();+ const auto max_prompt_size = m_npuw_llm_compiled_model->m_kvcache_desc.max_prompt_size;+ OPENVINO_ASSERT(+ out_shape.size() == 3u && out_shape[0] == 1u && out_shape[layer_ids::INPUT_IDS_SEQ_LEN_DIM] == max_prompt_size,+ "Encoder embedding model must produce a [1, ",+ max_prompt_size,+ ", hidden] hidden state, got ",+ out_shape);+}++void ov::npuw::EncoderEmbeddingInferRequest::infer() {+ namespace uu = ov::npuw::util;+ LOG_DEBUG("Calling inference for encoder embedding model.");+ LOG_BLOCK();++ const auto& inputs = get_inputs();+ auto input_ids = get_tensor(uu::find_port_by_name(inputs, layer_names::input_ids).value());+ auto attention_mask = get_tensor(uu::find_port_by_name(inputs, layer_names::attention_mask).value());++ OPENVINO_ASSERT(ov::element::i64 == input_ids->get_element_type());+ OPENVINO_ASSERT(ov::element::i64 == attention_mask->get_element_type());+ // The compiled encoder is static [1, L], so reject batched inputs and mask/ids disagreements+ // up front. The raw copies below would otherwise write past the static input tensors.+ OPENVINO_ASSERT(input_ids->get_shape()[0] == 1,+ "Encoder embedding model expects batch size 1, got shape ",+ input_ids->get_shape());+ OPENVINO_ASSERT(attention_mask->get_shape() == input_ids->get_shape(),+ "attention_mask shape ",+ attention_mask->get_shape(),+ " must match input_ids shape ",+ input_ids->get_shape());++ const auto prompt_len = static_cast<uint32_t>(input_ids->get_shape()[layer_ids::INPUT_IDS_SEQ_LEN_DIM]);+ auto& kvcache_desc = m_npuw_llm_compiled_model->m_kvcache_desc;+ if (prompt_len > kvcache_desc.max_prompt_size) {+ OPENVINO_THROW("Input prompt is longer than configured \"NPUW_LLM_MAX_PROMPT_LEN\": ",+ kvcache_desc.max_prompt_size,+ ".\nPlease either setup bigger \"NPUW_LLM_MAX_PROMPT_LEN\" or shorten the prompt. "+ "Note: it must not exceed the model's max_position_embeddings.");+ }++ // Static input tensors of the compiled (reshaped to [1, L]) encoder model.+ auto input_ids_in = m_prefill_request->get_tensor(m_prefill_in_ports.at(layer_names::input_ids));+ auto attn_mask_in = m_prefill_request->get_tensor(m_prefill_in_ports.at(layer_names::attention_mask));++ // An encoder derives each token's position from where it sits in the sequence, so valid tokens+ // have to be at the front (right-padding): token i keeps position i, and CLS or mean pooling+ // sees the real tokens first.+ uu::fill_tensor_bytes(input_ids_in, 0u);+ uu::fill_tensor<int64_t>(attn_mask_in, 0);++ std::copy_n(reinterpret_cast<uint8_t*>(input_ids->data()),+ input_ids->get_byte_size(),+ reinterpret_cast<uint8_t*>(input_ids_in->data()));+ std::copy_n(attention_mask->data<int64_t>(), attention_mask->get_size(), attn_mask_in->data<int64_t>());++ // token_type_ids: pad with zeros and pass the user's segment ids through (right-padded, like+ // input_ids), so sentence-pair inputs keep their segment assignment. Single-segment callers+ // pass all zeros anyway.+ if (auto it = m_prefill_in_ports.find(layer_names::token_type_ids); it != m_prefill_in_ports.end()) {+ auto token_type_ids_in = m_prefill_request->get_tensor(it->second);+ uu::fill_tensor<int64_t>(token_type_ids_in, 0);+ if (auto port = uu::find_port_by_name(inputs, layer_names::token_type_ids)) {+ auto token_type_ids = get_tensor(port.value());+ OPENVINO_ASSERT(ov::element::i64 == token_type_ids->get_element_type());+ OPENVINO_ASSERT(token_type_ids->get_shape() == input_ids->get_shape(),+ "token_type_ids shape ",+ token_type_ids->get_shape(),+ " must match input_ids shape ",+ input_ids->get_shape());+ std::copy_n(token_type_ids->data<int64_t>(),+ token_type_ids->get_size(),+ token_type_ids_in->data<int64_t>());+ }+ }++ m_prefill_request->infer();++ // The caller reads the compiled model's output tensor directly, so only the padding needs+ // attention: zero the trailing rows so they cannot reach a consumer that pools without+ // applying attention_mask. Batch is 1, so those rows are contiguous and a byte fill is enough.+ if (prompt_len < kvcache_desc.max_prompt_size) {+ auto padding = uu::make_tensor_slice(m_prefill_out_tensor,+ layer_ids::INPUT_IDS_SEQ_LEN_DIM,+ prompt_len,+ kvcache_desc.max_prompt_size);+ uu::fill_tensor_bytes(padding, 0u);+ }++ LOG_DEBUG("Done");+}++ov::SoPtr<ov::ITensor> ov::npuw::EncoderEmbeddingInferRequest::get_tensor(+ const ov::Output<const ov::Node>& port) const {+ if (port == get_outputs()[0]) {+ return m_prefill_out_tensor;+ }+ return ov::ISyncInferRequest::get_tensor(port);+}diff --git a/src/plugins/intel_npu/src/plugin/npuw/embedding/encoder_embedding_infer_request.hpp b/src/plugins/intel_npu/src/plugin/npuw/embedding/encoder_embedding_infer_request.hppnew file mode 100644index 00000000000..3d12d5efa8f--- /dev/null+++ b/src/plugins/intel_npu/src/plugin/npuw/embedding/encoder_embedding_infer_request.hpp@@ -0,0 +1,39 @@+// Copyright (C) 2018-2026 Intel Corporation+// SPDX-License-Identifier: Apache-2.0+//++#pragma once++#include "../base_sync_infer_request.hpp"+#include "../llm_compiled_model.hpp"+#include "../llm_infer_base_request.hpp"+#include "openvino/core/descriptor/output.hpp"++namespace ov {+namespace npuw {++// Infer request for non-autoregressive bidirectional encoder (e.g. BERT) text-embedding models.+// A single static forward over the whole (right-padded) sequence, with no KV cache and no+// chunking. No position_ids are injected: the encoder works out its own positions, so this path+// does not care whether they are the learned absolute ones that BERT, RoBERTa and XLM-R use or+// the RoPE and ALiBi schemes some newer encoders have moved to. Compare EmbeddingInferRequest,+// which targets the autoregressive (Qwen3-Embedding-style) reconstructed prefill model.+class EncoderEmbeddingInferRequest : public ov::npuw::LLMInferBaseRequest {+public:+ explicit EncoderEmbeddingInferRequest(const std::shared_ptr<LLMCompiledModel>& compiled_model);++ void infer() override;+ ov::SoPtr<ov::ITensor> get_tensor(const ov::Output<const ov::Node>& port) const override;++private:+ std::unordered_map<std::string, ov::Output<const ov::Node>> m_prefill_in_ports;++ std::shared_ptr<ov::IAsyncInferRequest> m_prefill_request;++ // The compiled encoder's own output tensor, returned to the caller unchanged: it is already+ // sized [1, max_prompt_size, hidden], so there is nothing to copy it into.+ ov::SoPtr<ov::ITensor> m_prefill_out_tensor;+};++} // namespace npuw+} // namespace ovdiff --git a/src/plugins/intel_npu/src/plugin/npuw/embedding/prepare_embedding_model.cpp b/src/plugins/intel_npu/src/plugin/npuw/embedding/prepare_embedding_model.cppindex 34db293875f..2bcd567f8c5 100644--- a/src/plugins/intel_npu/src/plugin/npuw/embedding/prepare_embedding_model.cpp+++ b/src/plugins/intel_npu/src/plugin/npuw/embedding/prepare_embedding_model.cpp@@ -8,6 +8,7 @@#include <optional>#include <regex>+#include "../llm_compiled_model_utils.hpp"#include "../logging.hpp"#include "openvino/op/ops.hpp"#include "openvino/openvino.hpp"@@ -237,27 +238,6 @@ public:explicit ReConstructEmbeddingModel(uint32_t seq_len_dim) : m_seq_len_dim(seq_len_dim) {}- std::optional<std::shared_ptr<ov::Node>> check_kv_concat_nodes(std::shared_ptr<ov::Node> sdpa_node) {- // Key input is at index 1- // Concat->Broadcast->Reshape->SDPA- auto reshape_node = sdpa_node->input(1).get_source_output().get_node();- if (strstr(reshape_node->get_type_name(), "Reshape") == nullptr) {- return std::nullopt;- }-- auto broadcast_node = reshape_node->input(0).get_source_output().get_node();- if (strstr(broadcast_node->get_type_name(), "Broadcast") == nullptr) {- return std::nullopt;- }-- auto concat_node = broadcast_node->input(1).get_source_output().get_node();- if (strstr(concat_node->get_type_name(), "Concat") == nullptr) {- return std::nullopt;- }-- return concat_node->shared_from_this();- }-bool check_sdpa_nodes(const std::shared_ptr<ov::Model> model) {for (const auto& op : model->get_ops()) {if (ov::is_type<ov::op::v13::ScaledDotProductAttention>(op)) {@@ -274,13 +254,13 @@ public:}// Check all SDPA nodes share the same kv concat node- auto concat_node = check_kv_concat_nodes(sdpa);- if (!concat_node.has_value()) {+ auto concat_node = ov::npuw::util::find_kv_cache_concat(sdpa);+ if (!concat_node) {return false;}if (!m_kv_concat.has_value()) {- m_kv_concat = concat_node.value();- } else if (m_kv_concat.value() != concat_node.value()) {+ m_kv_concat = concat_node;+ } else if (m_kv_concat.value() != concat_node) {return false;}}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 7a3f938b18a..9d885babfd4 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@@ -4,6 +4,7 @@#include "llm_compiled_model.hpp"#include "embedding/embedding_infer_request.hpp"+#include "embedding/encoder_embedding_infer_request.hpp"#include "embedding/prepare_embedding_model.hpp"#include "embedding/redirect_new_kv_to_output.hpp"#include "embedding/remove_empty_kv_inputs.hpp"@@ -672,8 +673,11 @@ void ov::npuw::LLMCompiledModel::compile_generate_model_variants(LOG_DEBUG("Successfully compiled generate variant with size: " << kv_size);}- // Keep the original compiled model for backward compatibility (using the largest size)- m_kvcache_compiled = m_generate_compiled_variants.back();+ // Keep the original compiled model for backward compatibility (using the largest size).+ // Encoder embedding models have no generate variants (prefill-only); leave it null.+ if (!m_generate_compiled_variants.empty()) {+ m_kvcache_compiled = m_generate_compiled_variants.back();+ }}ov::npuw::LLMCompiledModel::LLMCompiledModel(const std::shared_ptr<ov::Model>& model,@@ -797,10 +801,6 @@ ov::npuw::LLMCompiledModel::LLMCompiledModel(const std::shared_ptr<ov::Model>& m}}- LOG_VERB("Enabled prefill chunking: " << m_use_chunk_prefill);- LOG_VERB("Prefill chunk size: " << m_prefill_chunk_size);- LOG_VERB("Maximum prompt length: " << max_prompt_len);-const uint32_t batch_dim = m_cfg.get<::intel_npu::NPUW_LLM_BATCH_DIM>();const uint32_t seq_len_dim = m_cfg.get<::intel_npu::NPUW_LLM_SEQ_LEN_DIM>();KVAxesPosition axes{batch_dim, seq_len_dim};@@ -812,8 +812,45 @@ ov::npuw::LLMCompiledModel::LLMCompiledModel(const std::shared_ptr<ov::Model>& mm_is_embedding = use_text_embed_key.value_or(false).as<bool>() == true;if (m_is_embedding) {- LOG_DEBUG("Text-embedding model rebuild");- ov::npuw::util::PrepareTextEmbeddingModel(seq_len_dim).run_on_model(kvcache_model);+ // 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:+ // xiaobu, bge, Conan) attends over the whole sequence at once and has no KV cache to+ // rebuild, so it runs as a single static forward instead. The check keys on the KV-cache+ // concat on the SDPA key input; log the verdict at INFO so a model that lands on the wrong+ // side of it (an unusual decoder topology, say) is diagnosable from the logs.+ m_is_encoder_embedding = ov::npuw::util::is_encoder_embedding_model(kvcache_model);+ LOG_INFO("Text-embedding model classified as "+ << (m_is_encoder_embedding ? "bidirectional encoder: whole-sequence forward, no KV cache"+ : "autoregressive decoder: causal mask and reconstructed KV cache"));+ if (m_is_encoder_embedding) {+ LOG_DEBUG("Encoder (bidirectional) text-embedding model: no graph rebuild needed");+ // A bidirectional encoder attends over the whole sequence at once; chunked prefill is+ // semantically invalid for it. Force a single whole-sequence forward.+ m_use_chunk_prefill = false;+ // The encoder uses a learned absolute position table of size max_position_embeddings.+ // The static sequence length must not exceed it, otherwise the position embedding+ // (clamped to the table) won't broadcast against the token embedding and compilation+ // fails. Clamp here so the default NPUW_LLM_MAX_PROMPT_LEN (which is sized for LLMs and+ // is typically larger, e.g. 1024) does not break a 512-position BERT out of the box.+ if (auto max_pos = ov::npuw::util::get_max_position_embeddings(kvcache_model)) {+ if (max_prompt_len > *max_pos) {+ LOG_WARN("NPUW_LLM_MAX_PROMPT_LEN ("+ << max_prompt_len << ") exceeds the model's max_position_embeddings (" << *max_pos+ << "); clamping the static sequence length to " << *max_pos << ".");+ max_prompt_len = *max_pos;+ // Write the clamp back so the reported property matches what actually got+ // compiled. GenAI reads NPUW_LLM_MAX_PROMPT_LEN off the compiled model to+ // decide how long a prompt it may submit, and a stale larger value would let+ // it send one this model cannot take, failing at infer time instead of here.+ m_cfg.update({{"NPUW_LLM_MAX_PROMPT_LEN", std::to_string(max_prompt_len)}});+ }+ }+ ov::npuw::util::validate_encoder_embedding_model(kvcache_model);+ } else {+ LOG_DEBUG("Text-embedding model rebuild");+ ov::npuw::util::PrepareTextEmbeddingModel(seq_len_dim).run_on_model(kvcache_model);+ }} 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);@@ -823,6 +860,12 @@ ov::npuw::LLMCompiledModel::LLMCompiledModel(const std::shared_ptr<ov::Model>& mov::pass::StatefulToStateless().run_on_model(kvcache_model);}+ // Reported after the embedding branch, since an encoder embedding model turns chunking off and+ // may clamp the prompt length. Logging earlier would print values that never took effect.+ LOG_VERB("Enabled prefill chunking: " << m_use_chunk_prefill);+ LOG_VERB("Prefill chunk size: " << m_prefill_chunk_size);+ LOG_VERB("Maximum prompt length: " << max_prompt_len);+ov::npuw::LoraStatefulToStatelessPass().run_on_model(kvcache_model);LOG_DEBUG(" ...also convert BF16 to FP16");@@ -902,8 +945,16 @@ ov::npuw::LLMCompiledModel::LLMCompiledModel(const std::shared_ptr<ov::Model>& m}LOG_DEBUG("Make kvcache model with static shapes");- // Create generate model variants with different sizes- auto generate_model_variants = create_generate_model_variants(kvcache_model, axes, whisper_lhs_seq_size);+ // Create generate model variants with different sizes.+ // A bidirectional encoder embedding model has no autoregressive generate step (no KV cache,+ // no single-token decode), so the seq_len=1 generate graph is invalid for it and must not be+ // built/compiled. Only the (whole-sequence) prefill model is used at inference time.+ std::vector<std::shared_ptr<ov::Model>> generate_model_variants;+ if (!m_is_encoder_embedding) {+ generate_model_variants = create_generate_model_variants(kvcache_model, axes, whisper_lhs_seq_size);+ } else {+ LOG_DEBUG("Encoder embedding model: skipping generate model variants (prefill-only).");+ }if (lm_head_model) {LOG_DEBUG("Shared LM head: slice the prefill output");@@ -1317,7 +1368,7 @@ void ov::npuw::LLMCompiledModel::serialize(std::ostream& raw_stream, const ov::nm_kvcache_desc.v_tensors_transposed_gen & m_prefill_chunk_size & m_use_chunk_prefill & m_max_lora_rank &m_enable_prefix_caching & m_prefix_caching_block_size & m_prefix_caching_max_num_blocks &m_longrope_context_limit & m_is_whisper & m_eos_token_id & m_decomposed_sdpa_size & m_is_eagle &- m_is_embedding & m_is_block_kv_cache;+ m_is_embedding & m_is_block_kv_cache & m_is_encoder_embedding;// Write configstream & m_cfg;@@ -1357,16 +1408,19 @@ void ov::npuw::LLMCompiledModel::serialize(std::ostream& raw_stream, const ov::nwrite_model_meta(raw_stream);}- // Serialize bank name- const auto& kv_bank = m_kvcache_compiled->get_weights_bank();- const auto& p_bank = m_prefill_compiled->get_weights_bank();- NPUW_ASSERT(kv_bank && p_bank && kv_bank == p_bank && "Prefill and KVCache models' weight bank should be shared!");+ // Serialize bank name. Prefill and kvcache have to share a bank, so either one names it. An+ // encoder embedding model is prefill-only, and then there is no kvcache model to compare+ // against and the prefill bank is simply the only one.+ const auto& bank = m_prefill_compiled->get_weights_bank();+ NPUW_ASSERT(bank && "Prefill model should have a weights bank!");+ NPUW_ASSERT((!m_kvcache_compiled || m_kvcache_compiled->get_weights_bank() == bank) &&+ "Prefill and KVCache models' weight bank should be shared!");auto stream = Stream::writer(raw_stream);- auto bank_name = kv_bank->get_name();+ auto bank_name = bank->get_name();stream & bank_name;if (!is_weightless) {- stream&* kv_bank;+ stream&* bank;}LOG_INFO("Done.");@@ -1450,7 +1504,10 @@ std::shared_ptr<ov::npuw::LLMCompiledModel> ov::npuw::LLMCompiledModel::import_mauto bank = ov::npuw::weights::bank(bank_name, compiled->get_plugin()->get_core(), "");stream&* bank;- compiled->m_kvcache_compiled->set_weights_bank(bank);+ // Encoder embedding models are prefill-only: no kvcache/generate compiled models.+ if (compiled->m_kvcache_compiled) {+ compiled->m_kvcache_compiled->set_weights_bank(bank);+ }for (const auto& compiled_variant : compiled->m_generate_compiled_variants) {compiled_variant->set_weights_bank(bank);compiled_variant->reconstruct_closure();@@ -1538,7 +1595,7 @@ std::shared_ptr<ov::npuw::LLMCompiledModel> ov::npuw::LLMCompiledModel::deserialcompiled->m_prefix_caching_block_size & compiled->m_prefix_caching_max_num_blocks &compiled->m_longrope_context_limit & compiled->m_is_whisper & compiled->m_eos_token_id &compiled->m_decomposed_sdpa_size & compiled->m_is_eagle & compiled->m_is_embedding &- compiled->m_is_block_kv_cache;+ compiled->m_is_block_kv_cache & compiled->m_is_encoder_embedding;// Deserialize configstream & compiled->m_cfg;@@ -1621,7 +1678,8 @@ std::shared_ptr<ov::ISyncInferRequest> ov::npuw::LLMCompiledModel::create_sync_iif (m_is_whisper) {return non_const_this->create_whisper_infer_request();} else if (m_is_embedding) {- return non_const_this->create_embedding_infer_request();+ return m_is_encoder_embedding ? non_const_this->create_encoder_embedding_infer_request()+ : non_const_this->create_embedding_infer_request();} else {return non_const_this->create_llm_infer_request();}@@ -1642,6 +1700,11 @@ std::shared_ptr<ov::ISyncInferRequest> ov::npuw::LLMCompiledModel::create_embeddreturn std::make_shared<ov::npuw::EmbeddingInferRequest>(this_sptr);}+std::shared_ptr<ov::ISyncInferRequest> ov::npuw::LLMCompiledModel::create_encoder_embedding_infer_request() {+ auto this_sptr = std::static_pointer_cast<ov::npuw::LLMCompiledModel>(shared_from_this());+ return std::make_shared<ov::npuw::EncoderEmbeddingInferRequest>(this_sptr);+}+void ov::npuw::LLMCompiledModel::implement_properties() {#define BIND(N, T, GETTER) \{ \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.hppindex d9796d2d444..c903dd94ae4 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@@ -88,10 +88,12 @@ private:friend class LLMBlockKVCacheStrategy;friend class LLMContinuousKVCacheStrategy;friend struct ov::test::npuw::LLMVariantSwitchTestAccess;+ friend class EncoderEmbeddingInferRequest;std::shared_ptr<ov::ISyncInferRequest> create_llm_infer_request();std::shared_ptr<ov::ISyncInferRequest> create_whisper_infer_request();std::shared_ptr<ov::ISyncInferRequest> create_embedding_infer_request();+ std::shared_ptr<ov::ISyncInferRequest> create_encoder_embedding_infer_request();std::shared_ptr<ov::ISyncInferRequest> create_sync_infer_request() const override;void implement_properties();@@ -142,6 +144,9 @@ private:size_t m_decomposed_sdpa_size = 0;bool m_is_embedding = 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;// Create generate model variants with different sizesstd::vector<std::shared_ptr<ov::Model>> create_generate_model_variants(diff --git a/src/plugins/intel_npu/src/plugin/npuw/llm_compiled_model_utils.cpp b/src/plugins/intel_npu/src/plugin/npuw/llm_compiled_model_utils.cppindex a68560972ed..b992677e8c4 100644--- a/src/plugins/intel_npu/src/plugin/npuw/llm_compiled_model_utils.cpp+++ b/src/plugins/intel_npu/src/plugin/npuw/llm_compiled_model_utils.cpp@@ -4,6 +4,18 @@#include "llm_compiled_model_utils.hpp"+#include <cstring>++#include "openvino/op/constant.hpp"+#include "openvino/op/convert.hpp"+#include "openvino/op/gather.hpp"+#include "openvino/op/multiply.hpp"+#include "openvino/op/scaled_dot_product_attention.hpp"+#include "openvino/op/subtract.hpp"+#include "openvino/pass/pattern/matcher.hpp"+#include "openvino/pass/pattern/op/optional.hpp"+#include "openvino/pass/pattern/op/wrap_type.hpp"+bool ov::npuw::util::has_input(const std::shared_ptr<ov::Model>& model, const std::string& name) {auto inputs = model->inputs();auto it = std::find_if(inputs.begin(), inputs.end(), [&](const auto& port) {@@ -11,3 +23,88 @@ bool ov::npuw::util::has_input(const std::shared_ptr<ov::Model>& model, const st});return it != inputs.end();}++std::shared_ptr<ov::Node> ov::npuw::util::find_kv_cache_concat(const std::shared_ptr<ov::Node>& sdpa) {+ // The key is SDPA input 1, reached as Concat -> Broadcast -> Reshape -> SDPA when the model+ // carries a GQA KV cache.+ auto* reshape_node = sdpa->input(1).get_source_output().get_node();+ if (reshape_node == nullptr || strstr(reshape_node->get_type_name(), "Reshape") == nullptr) {+ return nullptr;+ }+ auto* broadcast_node = reshape_node->input(0).get_source_output().get_node();+ if (broadcast_node == nullptr || strstr(broadcast_node->get_type_name(), "Broadcast") == nullptr) {+ return nullptr;+ }+ auto* concat_node = broadcast_node->input(1).get_source_output().get_node();+ if (concat_node == nullptr || strstr(concat_node->get_type_name(), "Concat") == nullptr) {+ return nullptr;+ }+ return concat_node->shared_from_this();+}++bool ov::npuw::util::is_encoder_embedding_model(const std::shared_ptr<ov::Model>& model) {+ // The autoregressive embedding path reconstructs a prefill/KV model out of the KV-cache+ // concat feeding each SDPA key. A bidirectional encoder (BERT) has SDPA but no such concat,+ // so there is nothing to reconstruct and it has to run as a single forward instead. Routing+ // on the same predicate the reconstruction uses keeps the two from ever disagreeing.+ bool has_sdpa = false;+ for (const auto& op : model->get_ops()) {+ if (ov::is_type<ov::op::v13::ScaledDotProductAttention>(op)) {+ has_sdpa = true;+ if (find_kv_cache_concat(op)) {+ // Autoregressive (Qwen3-Embedding-style), handled by PrepareTextEmbeddingModel.+ return false;+ }+ }+ }+ return has_sdpa;+}++void ov::npuw::util::validate_encoder_embedding_model(const std::shared_ptr<ov::Model>& model) {+ for (const auto& param : model->get_parameters()) {+ for (const auto& name : param->get_output_tensor(0).get_names()) {+ OPENVINO_ASSERT(name.find("past_key_values") == std::string::npos,+ "Encoder embedding model has an unexpected autoregressive KV-cache input '",+ name,+ "'.");+ }+ }+}++std::optional<uint32_t> ov::npuw::util::get_max_position_embeddings(const std::shared_ptr<ov::Model>& model) {+ namespace opp = ov::pass::pattern;++ // Every embedding table in a BERT-like encoder is read by the same shape of subgraph: a rank-2+ // constant [rows, hidden] behind a Gather, with whatever Convert (and, for compressed weights,+ // Subtract and Multiply) decompression left in place. Spell those intermediates out rather+ // than walking a fixed number of hops through whatever happens to sit above the Gather.+ // int4 and nf4 exports also convert back up to the activation type after scaling, so allow a+ // Convert on either side of the dequantization.+ auto table = opp::wrap_type<ov::op::v0::Constant>();+ auto converted = opp::optional<ov::op::v0::Convert>({table->output(0)});+ auto unzeroed = opp::optional<ov::op::v1::Subtract>({converted->output(0), opp::any_input()});+ auto scaled = opp::optional<ov::op::v1::Multiply>({unzeroed->output(0), opp::any_input()});+ auto upcast = opp::optional<ov::op::v0::Convert>({scaled->output(0)});+ auto lookup = opp::wrap_type<ov::op::v8::Gather>({upcast->output(0), opp::any_input(), opp::any_input()});++ // The word, token-type and position tables are all the same lookup, so the topology on its own+ // cannot tell them apart and the exported name has to do it. It now chooses among candidates+ // the pattern has already established are embedding tables, instead of being the only thing+ // between us and an unrelated Gather. Picking the wrong table here would be expensive: the+ // token-type one has two rows and would clamp the sequence length to nothing.+ opp::Matcher matcher(lookup, "npuw::PositionEmbeddingTable");+ for (const auto& op : model->get_ops()) {+ if (!ov::is_type<ov::op::v8::Gather>(op) ||+ op->get_friendly_name().find("position_embeddings") == std::string::npos) {+ continue;+ }+ if (!matcher.match(op->output(0))) {+ continue;+ }+ const auto& table_shape = matcher.get_pattern_value_map().at(table).get_partial_shape();+ if (table_shape.rank().is_static() && table_shape.size() == 2 && table_shape[0].is_static()) {+ return static_cast<uint32_t>(table_shape[0].get_length());+ }+ }+ return std::nullopt;+}diff --git a/src/plugins/intel_npu/src/plugin/npuw/llm_compiled_model_utils.hpp b/src/plugins/intel_npu/src/plugin/npuw/llm_compiled_model_utils.hppindex 13e97fbf64e..199fc320522 100644--- a/src/plugins/intel_npu/src/plugin/npuw/llm_compiled_model_utils.hpp+++ b/src/plugins/intel_npu/src/plugin/npuw/llm_compiled_model_utils.hpp@@ -4,6 +4,7 @@#pragma once#include <memory>+#include <optional>#include "openvino/openvino.hpp"@@ -28,6 +29,32 @@ constexpr const char* kDeepstackVisualEmbedsParamName = "deepstack_visual_embedsbool has_input(const std::shared_ptr<ov::Model>& model, const std::string& name);+// Returns the KV-cache Concat that feeds an SDPA's key input through the autoregressive+// Concat->Broadcast->Reshape chain, or nullptr if the key input does not have that shape.+// Classification and reconstruction both key on this pattern, so they share one predicate+// instead of two that have to be kept in step by hand.+std::shared_ptr<ov::Node> find_kv_cache_concat(const std::shared_ptr<ov::Node>& sdpa);++// Returns true for a non-autoregressive (bidirectional encoder, e.g. BERT) text-embedding+// model: one that has ScaledDotProductAttention but none of the KV-cache concat pattern that+// the Qwen3-Embedding-style path needs in order to reconstruct a prefill/KV model.+// Used to route encoder embedders to the dedicated, KV/RoPE-free embedding path.+bool is_encoder_embedding_model(const std::shared_ptr<ov::Model>& model);++// Sanity-checks a model routed to the encoder embedding path. A bidirectional encoder is+// self-contained: it builds its own non-causal mask from `attention_mask`, works out its own+// positions and has no KV cache. Unlike the autoregressive path there is nothing to inject into+// the graph, so the only thing left to establish is that no autoregressive KV-cache input slipped+// through the classification. Throws if one did.+void validate_encoder_embedding_model(const std::shared_ptr<ov::Model>& model);++// Returns the learned absolute position-embedding table size (max_position_embeddings) of an+// encoder embedding model, found from the position_embeddings Gather's weight constant+// ([max_position_embeddings, hidden]). Returns nullopt if it can't be determined (e.g. the model+// uses a different positional scheme). The static sequence length must not exceed this, or the+// position embedding (clamped to the table) won't broadcast against the token embedding.+std::optional<uint32_t> get_max_position_embeddings(const std::shared_ptr<ov::Model>& model);+// clang-format off} // namespace ov// clang-format ondiff --git a/src/plugins/intel_npu/src/plugin/npuw/serialization.hpp b/src/plugins/intel_npu/src/plugin/npuw/serialization.hppindex c4f613a7ed7..91aa6c9da80 100644--- a/src/plugins/intel_npu/src/plugin/npuw/serialization.hpp+++ b/src/plugins/intel_npu/src/plugin/npuw/serialization.hpp@@ -48,7 +48,7 @@ const constexpr ov::npuw::s11n::IndicatorType NPUW_LLM_COMPILED_MODEL_INDICATORconst constexpr ov::npuw::s11n::IndicatorType NPUW_GQA_COMPILED_MODEL_INDICATOR ={char{0x47}, char{0x51}, char{0x41}, char{0x43}, char{0x4d}, char{0x4f}};-const constexpr char* NPUW_SERIALIZATION_VERSION = "0.28";+const constexpr char* NPUW_SERIALIZATION_VERSION = "0.29";// Forward declarationnamespace intel_npu {diff --git a/src/plugins/intel_npu/src/plugin/sources.cmake b/src/plugins/intel_npu/src/plugin/sources.cmakeindex d4eec6fdc49..999b64b593c 100644--- a/src/plugins/intel_npu/src/plugin/sources.cmake+++ b/src/plugins/intel_npu/src/plugin/sources.cmake@@ -43,6 +43,8 @@ set(NPUW_SOURCES${CMAKE_CURRENT_SOURCE_DIR}/npuw/compiled_model.hpp${CMAKE_CURRENT_SOURCE_DIR}/npuw/embedding/embedding_infer_request.cpp${CMAKE_CURRENT_SOURCE_DIR}/npuw/embedding/embedding_infer_request.hpp+ ${CMAKE_CURRENT_SOURCE_DIR}/npuw/embedding/encoder_embedding_infer_request.cpp+ ${CMAKE_CURRENT_SOURCE_DIR}/npuw/embedding/encoder_embedding_infer_request.hpp${CMAKE_CURRENT_SOURCE_DIR}/npuw/embedding/prepare_embedding_model.cpp${CMAKE_CURRENT_SOURCE_DIR}/npuw/embedding/prepare_embedding_model.hpp${CMAKE_CURRENT_SOURCE_DIR}/npuw/embedding/redirect_new_kv_to_output.cppdiff --git a/src/plugins/intel_npu/tests/unit/CMakeLists.txt b/src/plugins/intel_npu/tests/unit/CMakeLists.txtindex f190e23153c..a910468ec5a 100644--- a/src/plugins/intel_npu/tests/unit/CMakeLists.txt+++ b/src/plugins/intel_npu/tests/unit/CMakeLists.txt@@ -58,6 +58,7 @@ ov_add_test_target(${OpenVINO_SOURCE_DIR}/src/plugins/intel_npu/src/plugin/npuw/whisper/whisper_infer_request.cpp${OpenVINO_SOURCE_DIR}/src/plugins/intel_npu/src/plugin/npuw/whisper/prepare_whisper_model.cpp${OpenVINO_SOURCE_DIR}/src/plugins/intel_npu/src/plugin/npuw/embedding/embedding_infer_request.cpp+ ${OpenVINO_SOURCE_DIR}/src/plugins/intel_npu/src/plugin/npuw/embedding/encoder_embedding_infer_request.cpp${OpenVINO_SOURCE_DIR}/src/plugins/intel_npu/src/plugin/npuw/embedding/prepare_embedding_model.cpp${OpenVINO_SOURCE_DIR}/src/plugins/intel_npu/src/plugin/npuw/embedding/redirect_new_kv_to_output.cpp${OpenVINO_SOURCE_DIR}/src/plugins/intel_npu/src/plugin/npuw/embedding/remove_empty_kv_inputs.cppdiff --git a/src/plugins/intel_npu/tests/unit/npuw/llm_compiled_model_factory_options_test.cpp b/src/plugins/intel_npu/tests/unit/npuw/llm_compiled_model_factory_options_test.cppindex 2ea20aeb9bc..9e7628456a7 100644--- a/src/plugins/intel_npu/tests/unit/npuw/llm_compiled_model_factory_options_test.cpp+++ b/src/plugins/intel_npu/tests/unit/npuw/llm_compiled_model_factory_options_test.cpp@@ -12,7 +12,14 @@#include <utility>#include <vector>+#include "llm_compiled_model_utils.hpp"#include "llm_test_helpers.hpp"+#include "openvino/op/constant.hpp"+#include "openvino/op/convert.hpp"+#include "openvino/op/gather.hpp"+#include "openvino/op/multiply.hpp"+#include "openvino/op/parameter.hpp"+#include "openvino/op/subtract.hpp"#include "openvino/pass/stateful_to_stateless.hpp"#include "openvino/runtime/intel_npu/properties.hpp"#include "unit_test_utils/mocks/openvino/runtime/mock_icore.hpp"@@ -869,4 +876,130 @@ TEST_F(LLMCompiledModelFactoryOptionsTest, Gemma4MoEModelWithInputsEmbedsAndTokeEXPECT_NE(recorder.find_suffix("_prefill"), nullptr);}+// is_encoder_embedding_model: a bidirectional encoder (BERT) embedding model has SDPA but no+// autoregressive KV-cache concat pattern, so it must be classified as an encoder. The+// autoregressive embedding decoder must NOT be classified as an encoder.+TEST_F(LLMCompiledModelFactoryOptionsTest, IsEncoderEmbeddingModelDistinguishesBertFromDecoder) {+ EXPECT_TRUE(ov::npuw::util::is_encoder_embedding_model(build_embedding_model()));+ EXPECT_FALSE(ov::npuw::util::is_encoder_embedding_model(build_embedding_decoder_model()));+}++// get_max_position_embeddings: the BERT test config uses a learned absolute position table of+// size 512; the helper must read it back from the position_embeddings Gather weight.+TEST_F(LLMCompiledModelFactoryOptionsTest, GetMaxPositionEmbeddingsReadsBertTableSize) {+ const auto max_pos = ov::npuw::util::get_max_position_embeddings(build_embedding_model());+ ASSERT_TRUE(max_pos.has_value());+ EXPECT_EQ(*max_pos, 512u);+}++// A bare embedding lookup: Gather(table[rows, hidden], indices, axis=0). `behind_convert` adds+// the Convert that a compressed weight leaves between the table and the Gather.+std::shared_ptr<ov::Model> build_embedding_lookup_model(const std::string& name, size_t rows, bool behind_convert) {+ constexpr size_t hidden = 4u;+ const std::vector<float> values(rows * hidden, 0.1f);++ auto indices = std::make_shared<ov::op::v0::Parameter>(ov::element::i64, ov::PartialShape{-1, -1});+ indices->set_friendly_name("input_ids");++ const auto weight_type = behind_convert ? ov::element::f16 : ov::element::f32;+ auto weight = ov::op::v0::Constant::create(weight_type, ov::Shape{rows, hidden}, values);+ weight->set_friendly_name(name + ".weight");++ std::shared_ptr<ov::Node> table = weight;+ if (behind_convert) {+ table = std::make_shared<ov::op::v0::Convert>(weight, ov::element::f32);+ }++ auto axis = ov::op::v0::Constant::create(ov::element::i64, ov::Shape{}, {0});+ auto gather = std::make_shared<ov::op::v8::Gather>(table, indices, axis);+ gather->set_friendly_name(name);++ return std::make_shared<ov::Model>(ov::OutputVector{gather->output(0)}, ov::ParameterVector{indices});+}++// A compressed position table sits behind the Convert that decompression leaves in place, so the+// table size has to be read through it rather than off the Gather's immediate input.+TEST_F(LLMCompiledModelFactoryOptionsTest, GetMaxPositionEmbeddingsReadsTableBehindConvert) {+ const auto model = build_embedding_lookup_model("embeddings.position_embeddings", 256u, true);+ const auto max_pos = ov::npuw::util::get_max_position_embeddings(model);+ ASSERT_TRUE(max_pos.has_value());+ EXPECT_EQ(*max_pos, 256u);+}++// What optimum leaves above the Gather for an int4 or nf4 table: the weight is dequantized in the+// compressed type and only then converted up, so there is a Convert on both sides of the+// Subtract/Multiply. Missing this leaves the prompt length unclamped and the model fails to+// compile on NPU with a position/token embedding broadcast mismatch.+TEST_F(LLMCompiledModelFactoryOptionsTest, GetMaxPositionEmbeddingsReadsCompressedTable) {+ constexpr size_t rows = 256u;+ constexpr size_t hidden = 4u;++ auto indices = std::make_shared<ov::op::v0::Parameter>(ov::element::i64, ov::PartialShape{-1, -1});+ auto weight =+ ov::op::v0::Constant::create(ov::element::u4, ov::Shape{rows, hidden}, std::vector<int32_t>(rows * hidden, 1));+ weight->set_friendly_name("embeddings.position_embeddings.weight");+ auto zero_point =+ ov::op::v0::Constant::create(ov::element::u4, ov::Shape{rows, hidden}, std::vector<int32_t>(rows * hidden, 0));+ auto scale = ov::op::v0::Constant::create(ov::element::f16, ov::Shape{rows, 1u}, std::vector<float>(rows, 0.1f));++ std::shared_ptr<ov::Node> table = std::make_shared<ov::op::v0::Convert>(weight, ov::element::f16);+ table = std::make_shared<ov::op::v1::Subtract>(table,+ std::make_shared<ov::op::v0::Convert>(zero_point, ov::element::f16));+ table = std::make_shared<ov::op::v1::Multiply>(table, scale);+ table = std::make_shared<ov::op::v0::Convert>(table, ov::element::f32);++ auto axis = ov::op::v0::Constant::create(ov::element::i64, ov::Shape{}, {0});+ auto gather = std::make_shared<ov::op::v8::Gather>(table, indices, axis);+ gather->set_friendly_name("embeddings.position_embeddings");+ const auto model = std::make_shared<ov::Model>(ov::OutputVector{gather->output(0)}, ov::ParameterVector{indices});++ const auto max_pos = ov::npuw::util::get_max_position_embeddings(model);+ ASSERT_TRUE(max_pos.has_value());+ EXPECT_EQ(*max_pos, rows);+}++// The word and token-type tables are the same shape of lookup as the position table. Reading one+// of those by mistake would be worse than reading nothing: the token-type table has two rows and+// would clamp the sequence length to nothing at all.+TEST_F(LLMCompiledModelFactoryOptionsTest, GetMaxPositionEmbeddingsIgnoresOtherEmbeddingTables) {+ const auto words = build_embedding_lookup_model("embeddings.word_embeddings", 30522u, false);+ EXPECT_FALSE(ov::npuw::util::get_max_position_embeddings(words).has_value());++ const auto types = build_embedding_lookup_model("embeddings.token_type_embeddings", 2u, false);+ EXPECT_FALSE(ov::npuw::util::get_max_position_embeddings(types).has_value());+}++// A bidirectional encoder embedding model has no autoregressive generate step. It must compile+// the prefill (whole-sequence) model only and skip the generate/KV-cache variants entirely.+TEST_F(LLMCompiledModelFactoryOptionsTest, TextEmbedEncoderCompilesPrefillOnly) {+ RecordingFactory recorder;+ std::unique_ptr<ov::npuw::LLMCompiledModel> compiled;++ ASSERT_NO_THROW(compiled = create_compiled_model(build_embedding_model(), {{"NPUW_TEXT_EMBED", "YES"}}, recorder));+ ASSERT_NE(compiled, nullptr);+ EXPECT_NE(recorder.find_suffix("_prefill"), nullptr);+ // No generate variant should be produced for an encoder embedding model.+ EXPECT_EQ(recorder.count_suffix("_generate"), 0u);+}++// The default NPUW_LLM_MAX_PROMPT_LEN is sized for LLMs and can exceed a BERT encoder's+// max_position_embeddings (512). The encoder path must clamp the static sequence length to the+// position table size so the model compiles out of the box instead of failing with a+// position/token embedding shape mismatch.+TEST_F(LLMCompiledModelFactoryOptionsTest, TextEmbedEncoderClampsPromptLenToMaxPositionEmbeddings) {+ RecordingFactory recorder;+ std::unique_ptr<ov::npuw::LLMCompiledModel> compiled;++ // 1024 > BERT max_position_embeddings (512): must not throw, must clamp.+ ASSERT_NO_THROW(compiled = create_compiled_model(build_embedding_model(),+ {{"NPUW_TEXT_EMBED", "YES"}, {"NPUW_LLM_MAX_PROMPT_LEN", "1024"}},+ recorder));+ ASSERT_NE(compiled, nullptr);+ EXPECT_NE(recorder.find_suffix("_prefill"), nullptr);++ // The clamped length is what got compiled, so it has to be what the property reports. GenAI+ // reads this back to decide how long a prompt it may submit.+ EXPECT_EQ(compiled->get_property("NPUW_LLM_MAX_PROMPT_LEN").as<uint32_t>(), 512u);+}+} // namespace