Skip to content

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

[NPUW] Support multiple outputs in LLMCompiledModel (#38754)

Guoliang Shi7bacd5ce28e1
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 1d3f9b6571c..a22845dd959 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
@@ -19,6 +19,7 @@
#include "moe_transformations/moe_topology.hpp"
#include "npuw_transformations/add_position_ids_param.hpp"
#include "npuw_transformations/convert_kvcache_to_precision.hpp"
+#include "npuw_transformations/cut_lm_head.hpp"
#include "npuw_transformations/detect_causal_mask.hpp"
#include "npuw_transformations/duplicate_shared_kv_concat.hpp"
#include "npuw_transformations/insert_vocab_sub128.hpp"
@@ -76,96 +77,10 @@ bool is_aligned_to(T value, T alignment) {
} // namespace
-class CutLMHead : public ov::pass::MatcherPass {
-public:
- OPENVINO_MATCHER_PASS_RTTI("ov::npuw::CutLMHead");
- explicit CutLMHead(std::shared_ptr<ov::Model>& lm_head_model) {
- // We are interested at first input to MatMul as a cut point
- auto matmul = opp::wrap_type<ov::op::v0::MatMul>({opp::any_input(), opp::any_input()});
-
- // There are several patterns for matmul we are looking for:
- // Matmul -> Result
- // Matmul -> Add -> Result
- auto matmul_add = opp::wrap_type<ov::op::v1::Add>({matmul, opp::any_input()});
- // Matmul -> Transpose -> Result
- auto matmul_transpose = opp::wrap_type<ov::op::v1::Transpose>({matmul, opp::any_input()});
- // Matmul -> Convert -> Result
- auto matmul_convert = opp::wrap_type<ov::op::v0::Convert>({matmul});
- // MatMul -> Divide -> Tanh -> Multiply -> Result
- auto div = opp::wrap_type<ov::op::v1::Multiply, ov::op::v1::Divide>({matmul, opp::any_input()});
- auto tanh = opp::wrap_type<ov::op::v0::Tanh>({div});
- auto matmul_multiply = opp::wrap_type<ov::op::v1::Multiply>({tanh, opp::any_input()});
-
- auto last_op = std::make_shared<opp::op::Or>(ov::OutputVector{matmul->output(0),
- matmul_add->output(0),
- matmul_transpose->output(0),
- matmul_convert->output(0),
- matmul_multiply->output(0)});
- auto res = opp::wrap_type<ov::op::v0::Result>({last_op->output(0)});
-
- auto callback = [=, &lm_head_model](opp::Matcher& m) {
- auto& node_to_output = m.get_pattern_value_map();
-
- auto matched_node_matmul = node_to_output.at(matmul).get_node_shared_ptr();
- std::shared_ptr<ov::Node> matched_node_last_op = nullptr;
- if (node_to_output.count(matmul_add)) {
- matched_node_last_op = node_to_output[matmul_add].get_node_shared_ptr();
- } else if (node_to_output.count(matmul_transpose)) {
- matched_node_last_op = node_to_output[matmul_transpose].get_node_shared_ptr();
- } else if (node_to_output.count(matmul_convert)) {
- matched_node_last_op = node_to_output[matmul_convert].get_node_shared_ptr();
- } else if (node_to_output.count(matmul_multiply)) {
- matched_node_last_op = node_to_output[matmul_multiply].get_node_shared_ptr();
- } else {
- matched_node_last_op = matched_node_matmul;
- }
- auto matched_node_result = node_to_output.at(res).get_node_shared_ptr();
-
- auto matched_matmul = std::static_pointer_cast<ov::op::v0::MatMul>(matched_node_matmul);
- auto matched_result = std::static_pointer_cast<ov::op::v0::Result>(matched_node_result);
-
- // Some LLMs add intermediate hidden state outputs that can interfere with LM head detection.
- // Skip Result nodes that were manually added (marked with "manually_added_output" in RT_INFO).
- // For example, Eagle-3 target/draft models add "last_hidden_state" output which should be skipped.
- const auto& rt_info = matched_result->get_rt_info();
- if (rt_info.count("manually_added_output")) {
- return false;
- }
-
- // Cut point:
- auto matmul_first_source = matched_matmul->input(0).get_source_output();
-
- // Cut original model:
- matched_result->input(0).replace_source_output(matmul_first_source);
- // FIXME: Somehow for KVCache model result output gets renamed in
- // ICompiledModel::ICompiledModel().
- // As a WA, setting the same name to output from MatMul
- // avoids the issue.
- matmul_first_source.set_names({ov::npuw::LLMCompiledModel::output_embeds});
- matched_result->output(0).set_names({ov::npuw::LLMCompiledModel::output_embeds});
- matched_result->validate_and_infer_types();
-
- // Create an additional model after cut point:
- auto new_param = std::make_shared<ov::op::v0::Parameter>(matmul_first_source.get_element_type(),
- matmul_first_source.get_partial_shape());
- new_param->output(0).add_names({ov::npuw::LLMCompiledModel::output_embeds});
- matched_matmul->input(0).replace_source_output(new_param);
- auto new_result = std::make_shared<ov::op::v0::Result>(matched_node_last_op);
- lm_head_model =
- std::make_shared<ov::Model>(ov::OutputVector{new_result->output(0)}, ov::ParameterVector{new_param});
-
- return true;
- };
- register_matcher(std::make_shared<opp::Matcher>(res, "CutLMHead"), std::move(callback));
- }
-};
-
namespace {
std::shared_ptr<ov::Model> cut_lm_head(const std::shared_ptr<ov::Model>& model) {
- ov::pass::GraphRewrite rewr;
std::shared_ptr<ov::Model> lm_head_model = nullptr;
- rewr.add_matcher<CutLMHead>(lm_head_model);
- rewr.run_on_model(model);
+ ov::npuw::CutLMHead(lm_head_model).run_on_model(model);
if (lm_head_model) {
lm_head_model->set_friendly_name(model->get_friendly_name() + "_lm_head");
}
@@ -648,6 +563,98 @@ std::shared_ptr<ov::Model> check_and_cut_lm_head(const std::shared_ptr<ov::Model
return lm_head_model;
}
+std::map<std::string, std::vector<std::size_t>> find_other_dynamic_outputs(const std::shared_ptr<ov::Model>& model) {
+ std::map<std::string, std::vector<std::size_t>> other_dynamic_outputs;
+ for (const auto& output : model->outputs()) {
+ // Filter logits, as we are collecting only "other" than logits outputs.
+ if (output.get_names().count(ov::npuw::LLMCompiledModel::layer_names::logits)) {
+ LOG_VERB("Skipping output port " << output.get_index() << " as it is identified as logits." << std::endl);
+ continue;
+ }
+
+ const auto& shape = output.get_partial_shape();
+ if (!shape.is_dynamic()) {
+ continue;
+ }
+
+ std::vector<std::size_t> dynamic_dims_ids;
+ for (auto dim_it = shape.begin(); dim_it != shape.end(); ++dim_it) {
+ if (dim_it->is_dynamic()) {
+ dynamic_dims_ids.push_back(std::distance(shape.begin(), dim_it));
+ }
+ }
+ OPENVINO_ASSERT(!dynamic_dims_ids.empty() && "Dynamic output should have at least one dynamic dimension");
+ const auto& output_name = output.get_any_name();
+ other_dynamic_outputs[output_name] = dynamic_dims_ids;
+ LOG_VERB("Find other dynamic output with name \"" << output_name << "\" at port: " << output << " with shape: "
+ << shape << " with dynamic dimension indices: ");
+ if ((ov::npuw::get_log_level() >= ov::npuw::LogLevel::Verbose)) {
+ for (const auto& dim_id : dynamic_dims_ids) {
+ LOG_VERB(" - " << dim_id);
+ }
+ }
+ }
+ return other_dynamic_outputs;
+}
+
+std::map<ov::Output<const ov::Node>, std::size_t> find_other_outputs_with_seqdim(
+ const std::shared_ptr<ov::npuw::ICompiledModel_v0>& compiled_model,
+ const std::map<std::string, std::vector<std::size_t>>& other_dynamic_outputs,
+ const std::size_t expected_seqdim_value) {
+ std::map<ov::Output<const ov::Node>, std::size_t> other_outputs_with_seqdim;
+ const auto& cm_outs = compiled_model->outputs();
+ for (const auto& [name, dynamic_dims] : other_dynamic_outputs) {
+ const auto& output_name = name;
+ if (auto it = std::find_if(cm_outs.begin(),
+ cm_outs.end(),
+ [&output_name](const ov::Output<const ov::Node>& output) {
+ return output.get_names().count(output_name) > 0;
+ });
+ it != cm_outs.end()) {
+ const auto& port = *it;
+ const auto& static_shape = port.get_partial_shape();
+ OPENVINO_ASSERT(static_shape.is_static() && "Model should have static shape at this point");
+
+ auto matched_dyn_dim = dynamic_dims.front();
+ std::size_t match_count = 0;
+ // NB: Only one previous dynamic dimension will be reshaped to the stated sequence length.
+ // Batch size has been also a dynamic dimension prevously, but it is expected to be
+ // reshaped to 1, so it won't be equal to the max sequence length in the prefill model.
+ for (const auto& dim : dynamic_dims) {
+ OPENVINO_ASSERT(dim < static_shape.size(),
+ "Dimension index " + std::to_string(dim) +
+ " is out of range for the static shape of output port: " + port.get_any_name());
+ if (static_shape[dim] == expected_seqdim_value) {
+ matched_dyn_dim = dim;
+ ++match_count;
+ }
+ }
+
+ if (match_count == 0) {
+ // NB: such an output is not accumulated across chunks, so in chunked prefill
+ // it will only hold the value computed from the last processed chunk.
+ LOG_WARN("No dynamic dimension matched the max sequence length for output port: "
+ << port.get_any_name()
+ << ", assuming that given output doesn't need accumulation. "
+ "Its value will reflect only the last processed prefill chunk.");
+ continue;
+ }
+
+ // Assert that only one match is found:
+ OPENVINO_ASSERT(match_count == 1,
+ "Only one dynamic dimension is expected to be reshaped to the max sequence length, but "
+ "found " +
+ std::to_string(match_count) + " matches for output port: " + port.get_any_name());
+ other_outputs_with_seqdim.emplace(port, matched_dyn_dim);
+ } else {
+ LOG_WARN("Output port with name: " << name
+ << " was marked as dynamic additional output to the \"logits\","
+ "but it wasn't found in outputs of prefill model!");
+ }
+ }
+ return other_outputs_with_seqdim;
+}
+
} // namespace
// Apply DEVICE_ROUTED MoE transformations to models
@@ -882,6 +889,17 @@ 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};
+ 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.");
+ other_dynamic_outputs = find_other_dynamic_outputs(model);
+ // Chunk size 1 makes the batch and sequence axes indistinguishable (both are 1),
+ // which breaks sequence-axis detection for non-logits outputs below.
+ OPENVINO_ASSERT(m_prefill_chunk_size != 1 || other_dynamic_outputs.empty(),
+ "NPUW_LLM_PREFILL_CHUNK_SIZE=1 is not supported together with non-logits outputs. "
+ "Please use a larger chunk size.");
+ }
+
LOG_DEBUG("Creating kvcache model as clone of passed one.");
auto kvcache_model = model->clone();
@@ -1241,6 +1259,13 @@ ov::npuw::LLMCompiledModel::LLMCompiledModel(const std::shared_ptr<ov::Model>& m
merge_config_with(prefill_config, other_props);
merge_config_with(generate_config, other_props);
merge_config_with(prefill_config, prefill_config_addition_value);
+ // If model has multiple outputs, only logits will be extracted to a separate model.
+ // Prefill will have all other outputs. It might be a wrong assumption that all of
+ // them need to be sliced for, for instance, 1 token.
+ if (lm_head_model) {
+ LOG_DEBUG("LM head model is present, erasing NPUW_SLICE_OUT from prefill config.");
+ prefill_config.erase("NPUW_SLICE_OUT");
+ }
merge_config_with(generate_config, generate_config_addition_value);
if (user_compilation_mode_params.has_value() && default_compilation_mode_params.has_value() &&
user_compilation_mode_params.value() != default_compilation_mode_params.value()) {
@@ -1512,6 +1537,11 @@ ov::npuw::LLMCompiledModel::LLMCompiledModel(const std::shared_ptr<ov::Model>& m
m_prefill_compiled = m_compiled_model_factory(prefill_model, plugin, prefill_config);
NPUW_ASSERT(m_prefill_compiled && "Can't create ov::npuw::CompiledModel for passed prefill "
"model and its config, please check passed config.");
+ if (m_use_chunk_prefill) {
+ LOG_VERB("Find all models outputs besides logits that have sequence dimension to handle in chunked prefill.");
+ m_prefill_other_outs_seqdims =
+ find_other_outputs_with_seqdim(m_prefill_compiled, other_dynamic_outputs, m_prefill_chunk_size);
+ }
if (lm_head_model) {
auto lm_head_config = get_default_lm_head_config(npudesc);
merge_config_with(lm_head_config, other_props);
@@ -1590,6 +1620,32 @@ void ov::npuw::LLMCompiledModel::export_model(std::ostream& stream) const {
}
}
+std::map<std::string, std::size_t> ov::npuw::LLMCompiledModel::serialize_prefill_other_outs_seqdims() const {
+ std::map<std::string, std::size_t> by_name;
+ for (const auto& [port, seqdim] : m_prefill_other_outs_seqdims) {
+ by_name.emplace(port.get_any_name(), seqdim);
+ }
+ return by_name;
+}
+
+void ov::npuw::LLMCompiledModel::deserialize_prefill_other_outs_seqdims(
+ const std::map<std::string, std::size_t>& by_name) {
+ m_prefill_other_outs_seqdims.clear();
+ const auto& prefill_outs = m_prefill_compiled->outputs();
+ for (const auto& [port_name, seqdim] : by_name) {
+ const auto& name = port_name;
+ auto it =
+ std::find_if(prefill_outs.begin(), prefill_outs.end(), [&name](const ov::Output<const ov::Node>& out) {
+ return out.get_names().count(name) > 0;
+ });
+ OPENVINO_ASSERT(it != prefill_outs.end(),
+ "NPUW blob: prefill output '",
+ port_name,
+ "' from the seq-dim table is missing after import.");
+ m_prefill_other_outs_seqdims.emplace(*it, seqdim);
+ }
+}
+
void ov::npuw::LLMCompiledModel::serialize(std::ostream& raw_stream, const ov::npuw::s11n::CompiledContext& ctx) const {
LOG_INFO("Serializing LLMCompiledModel...");
LOG_BLOCK();
@@ -1652,6 +1708,12 @@ void ov::npuw::LLMCompiledModel::serialize(std::ostream& raw_stream, const ov::n
if (is_shared_lm_head) {
m_lm_head_compiled->serialize(model_stream, enc_ctx);
}
+
+ // The chunked-prefill outputs' sequence-dimension table is keyed by model output ports,
+ // which cannot be serialized directly. Export it by tensor name instead, so it can be
+ // rebuilt against the restored prefill model on import.
+ auto other_outs_seqdims = serialize_prefill_other_outs_seqdims();
+ stream & other_outs_seqdims;
};
std::stringstream non_encrypted_stream;
@@ -1867,6 +1929,12 @@ std::shared_ptr<ov::npuw::LLMCompiledModel> ov::npuw::LLMCompiledModel::deserial
ov::npuw::CompiledModel::deserialize(model_stream, plugin, properties, enc_ctx);
}
+ // Rebuild the chunked-prefill outputs' sequence dimension table by matching tensor names
+ // against the restored prefill model (see the matching comment in serialize()).
+ std::map<std::string, std::size_t> other_outs_seqdims;
+ stream & other_outs_seqdims;
+ compiled->deserialize_prefill_other_outs_seqdims(other_outs_seqdims);
+
// Reject blobs whose KVCacheDesc::dim is not a valid axis for the restored KV tensors.
compiled->validate_imported_kvcache_dim();
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 ef0461b336e..ffe5ea4bf9d 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
@@ -36,7 +36,10 @@ class LLMCompiledModel : public ov::npuw::ICompiledModel {
std::map<std::string, std::tuple<ov::PropertyMutability, std::function<ov::Any(const ::intel_npu::Config&)>>>;
public:
- static constexpr const char* output_embeds = "npuw_output_embed";
+ struct layer_names {
+ static constexpr const char* output_embeds = "npuw_output_embed";
+ static constexpr const char* logits = "logits";
+ };
static constexpr uint32_t whisper_batch_dim = 0u;
static constexpr uint32_t whisper_seq_len_dim = 2u;
@@ -115,6 +118,9 @@ protected:
const ov::AnyMap& properties,
const ov::npuw::s11n::CompiledContext& ctx);
+ std::map<std::string, std::size_t> serialize_prefill_other_outs_seqdims() const;
+ void deserialize_prefill_other_outs_seqdims(const std::map<std::string, std::size_t>& by_name);
+
// Trust-boundary check for imported blobs: KVCacheDesc::dim and the V-transposed flags are read
// from the stream and select the axis used to subscript shape vectors in the KV-slice helpers.
// Reject them unless that axis is valid for every KV input/output of the restored prefill and
@@ -136,6 +142,7 @@ protected:
bool m_is_block_kv_cache = false;
std::shared_ptr<ov::npuw::ICompiledModel_v0> m_kvcache_compiled;
std::shared_ptr<ov::npuw::ICompiledModel_v0> m_prefill_compiled;
+ std::map<ov::Output<const ov::Node>, std::size_t> m_prefill_other_outs_seqdims;
// This model is optional, so can be null.
std::shared_ptr<ov::npuw::ICompiledModel_v0> m_lm_head_compiled;
diff --git a/src/plugins/intel_npu/src/plugin/npuw/llm_eagle3_extension.cpp b/src/plugins/intel_npu/src/plugin/npuw/llm_eagle3_extension.cpp
index 36c805a02fb..8b8f05c043b 100644
--- a/src/plugins/intel_npu/src/plugin/npuw/llm_eagle3_extension.cpp
+++ b/src/plugins/intel_npu/src/plugin/npuw/llm_eagle3_extension.cpp
@@ -231,85 +231,6 @@ void Eagle3Extension::prepare_inputs(const std::shared_ptr<ov::IAsyncInferReques
}
}
-void Eagle3Extension::update_last_hidden_state(
- const std::shared_ptr<ov::IAsyncInferRequest>& request,
- const std::unordered_map<std::string, ov::Output<const ov::Node>>& out_ports) {
- auto last_hidden_state_it = out_ports.find(Eagle3LayerNames::last_hidden_state);
- OPENVINO_ASSERT(last_hidden_state_it != out_ports.end(), "Eagle3 model must have last_hidden_state output port");
-
- m_last_hidden_state = request->get_tensor(last_hidden_state_it->second);
-
- LOG_VERB("Eagle3 " << (m_role == Eagle3ModelRole::Draft ? "Draft" : "Target")
- << ": Retrieved last_hidden_state output tensor");
-}
-
-void Eagle3Extension::accumulate_chunk_last_hidden_state(
- const std::shared_ptr<ov::IAsyncInferRequest>& request,
- const std::unordered_map<std::string, ov::Output<const ov::Node>>& out_ports,
- uint32_t chunk_token_count,
- uint32_t total_seq_len) {
- auto last_hidden_state_it = out_ports.find(Eagle3LayerNames::last_hidden_state);
- OPENVINO_ASSERT(last_hidden_state_it != out_ports.end(), "Eagle3 model must have last_hidden_state output port");
-
- auto chunk_output = request->get_tensor(last_hidden_state_it->second);
- const auto& chunk_shape = chunk_output->get_shape();
-
- OPENVINO_ASSERT(chunk_shape.size() == 3, "last_hidden_state must have 3 dimensions: [batch, seq_len, hidden_size]");
-
- constexpr size_t kBatchDim = 0;
- constexpr size_t kSeqDim = 1;
- constexpr size_t kHiddenDim = 2;
-
- const uint32_t batch_size = static_cast<uint32_t>(chunk_shape[kBatchDim]);
- const uint32_t chunk_seq_len = static_cast<uint32_t>(chunk_shape[kSeqDim]);
- const uint32_t hidden_size = static_cast<uint32_t>(chunk_shape[kHiddenDim]);
- OPENVINO_ASSERT(batch_size == 1, "Batch size must be 1 for Eagle3");
- OPENVINO_ASSERT(chunk_token_count <= chunk_seq_len, "chunk_token_count must be <= chunk_seq_len");
-
- // Pre-allocate tensor on first chunk
- if (!m_last_hidden_state) {
- m_last_hidden_state = ov::get_tensor_impl(
- ov::Tensor(chunk_output->get_element_type(), ov::Shape{batch_size, total_seq_len, hidden_size}));
- m_chunked_seq_offset = 0;
-
- LOG_VERB("Eagle3: Pre-allocated last_hidden_state tensor with shape=[" << batch_size << "," << total_seq_len
- << "," << hidden_size << "]");
- }
-
- const auto& target_shape = m_last_hidden_state->get_shape();
- const uint32_t target_total_len = static_cast<uint32_t>(target_shape[1]);
-
- OPENVINO_ASSERT(target_total_len == total_seq_len,
- "Pre-allocated tensor size (" + std::to_string(target_total_len) + ") must match total_seq_len (" +
- std::to_string(total_seq_len) + ")");
-
- OPENVINO_ASSERT(m_chunked_seq_offset + chunk_token_count <= target_total_len,
- "Can't write chunk by stored chunked sequence offset and requested number of tokens, as it will "
- "exceed pre-allocated size");
-
- // Extract only the rightmost chunk_token_count tokens from the output
- // The chunk_output is right-aligned with padding on the left
- constexpr uint32_t seq_dim = 1;
- const uint32_t chunk_start_offset = chunk_seq_len - chunk_token_count;
-
- auto chunk_output_slice = util::make_tensor_slice(chunk_output, seq_dim, chunk_start_offset, chunk_seq_len);
-
- auto target_slice = util::make_tensor_slice(m_last_hidden_state,
- seq_dim,
- m_chunked_seq_offset,
- m_chunked_seq_offset + chunk_token_count);
-
- NPUW_ASSERT(target_slice._ptr &&
- "null slice of last_hidden_state tensor — source tensor may be uninitialized or have wrong shape");
- chunk_output_slice->copy_to(target_slice._ptr);
-
- LOG_VERB("Eagle3: Copied chunk [" << chunk_start_offset << ":" << chunk_seq_len << "] to position ["
- << m_chunked_seq_offset << ":" << (m_chunked_seq_offset + chunk_token_count)
- << "], " << chunk_token_count << " tokens");
-
- m_chunked_seq_offset += chunk_token_count;
-}
-
void Eagle3Extension::prepare_inputs_for_chunk(
const std::shared_ptr<ov::IAsyncInferRequest>& request,
const std::unordered_map<std::string, ov::Output<const ov::Node>>& in_ports,
diff --git a/src/plugins/intel_npu/src/plugin/npuw/llm_eagle3_extension.hpp b/src/plugins/intel_npu/src/plugin/npuw/llm_eagle3_extension.hpp
index c7a979f2c3d..8a666ef63cf 100644
--- a/src/plugins/intel_npu/src/plugin/npuw/llm_eagle3_extension.hpp
+++ b/src/plugins/intel_npu/src/plugin/npuw/llm_eagle3_extension.hpp
@@ -187,31 +187,6 @@ public:
uint32_t chunk_start_token,
uint32_t chunk_token_count);
- // Retrieve and store last_hidden_state output tensor for draft and target models
- void update_last_hidden_state(const std::shared_ptr<ov::IAsyncInferRequest>& request,
- const std::unordered_map<std::string, ov::Output<const ov::Node>>& out_ports);
-
- // Accumulate last_hidden_state from current chunk during chunked prefill
- void accumulate_chunk_last_hidden_state(
- const std::shared_ptr<ov::IAsyncInferRequest>& request,
- const std::unordered_map<std::string, ov::Output<const ov::Node>>& out_ports,
- uint32_t chunk_token_count,
- uint32_t total_seq_len);
-
- // Reset chunked prefill state before starting a new chunked prefill session
- // NOTE: m_last_hidden_state holds tensors of different sizes in prefill vs generation phases
- // Must reset to avoid size mismatch when starting a new prefill after previous generations
- void reset_chunked_prefill_state() {
- m_last_hidden_state = {};
- m_chunked_seq_offset = 0;
- }
-
- // Returns the last_hidden_state tensor from the most recent inference.
- // For chunked prefill, this is the fully-assembled tensor across all chunks.
- ov::SoPtr<ov::ITensor> get_last_hidden_state() const {
- return m_last_hidden_state;
- }
-
// Returns the Eagle3SamplingState VariableState exposed via query_state().
// External pipelines write sampling results into this state; the plugin reads
// them back in process_sampling_result_from_state() before the next inference.
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 6e42104699d..d03ced2b535 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
@@ -415,6 +415,19 @@ ov::npuw::LLMInferRequest::LLMInferRequest(const std::shared_ptr<ov::npuw::LLMCo
m_lm_head_request->get_tensor(lm_head_embed_port));
}
}
+
+ if (compiled_model->m_use_chunk_prefill) {
+ m_prefill_other_outs_seqdims = compiled_model->m_prefill_other_outs_seqdims;
+ for (auto&& [out_port, out_dim] : m_prefill_other_outs_seqdims) {
+ const auto& chunked_shape = out_port.get_partial_shape();
+ auto full_max_len_shape = chunked_shape;
+ full_max_len_shape[out_dim] = m_npuw_llm_compiled_model->m_kvcache_desc.max_prompt_size;
+ m_prefill_other_outs_accum.emplace(
+ out_port,
+ ov::get_tensor_impl(ov::Tensor(out_port.get_element_type(), full_max_len_shape.get_shape())));
+ }
+ }
+
// FIXME: E-177589
// FIXME: "fixes"/workarounds caching import on CPU (also might be related to bf16 weights).
// Unclear how it's related. Previously fill_tensor()
@@ -978,8 +991,8 @@ void ov::npuw::LLMInferRequest::trim_kvcache_for_speculative_decoding(ov::SoPtr<
}
auto dirty_num = kvcache_desc.num_stored_tokens - position_id_u32;
if (dirty_num > 0) {
- LOG_DEBUG("Trim kv cache from " << kvcache_desc.num_stored_tokens << " length"
- << " to " << position_id_u32 << " length");
+ LOG_DEBUG("Trim kv cache from " << kvcache_desc.num_stored_tokens << " length" << " to " << position_id_u32
+ << " length");
}
kvcache_desc.num_stored_tokens -= dirty_num;
}
@@ -1000,6 +1013,58 @@ void ov::npuw::LLMInferRequest::clear_chunk_prefill_kv_cache() {
}
}
+void LLMInferRequest::accumulate_other_chunked_outputs(uint32_t start_offset,
+ uint32_t chunk_token_count,
+ uint32_t processed_token_count,
+ uint32_t max_seq_len) {
+ LOG_INFO("Accumulating other chunked outputs into full ones, chunk_token_count:"
+ << chunk_token_count << ", processed_token_count:" << processed_token_count
+ << ", max_seq_len:" << max_seq_len);
+ OPENVINO_ASSERT(
+ chunk_token_count + processed_token_count <= max_seq_len,
+ "Sanity check for input parameters: chunk_token_count + processed_token_count must be <= max_seq_len");
+
+ for (auto&& [port, dim] : m_prefill_other_outs_seqdims) {
+ LOG_BLOCK();
+ LOG_VERB("Processing chunked output tensor at index " << port << " with sequence dimension " << dim);
+ auto chunk_tensor = m_prefill_request->get_tensor(port);
+ const auto& chunk_shape = chunk_tensor->get_shape();
+
+ auto full_tensor = m_prefill_other_outs_accum[port];
+ const auto& full_shape = full_tensor->get_shape();
+ LOG_VERB("Its full counterpart has shape: " << full_shape);
+
+ OPENVINO_ASSERT(chunk_shape[dim] <= full_shape[dim],
+ "Sequence length of chunk tensor must be <= sequence length of full tensor.");
+
+ // The chunk_tensor is right-aligned with padding on the left.
+ const uint32_t chunk_seq_len = static_cast<uint32_t>(chunk_shape[dim]);
+ const uint32_t chunk_start_offset = chunk_seq_len - chunk_token_count;
+ auto chunk_tensor_slice =
+ util::make_tensor_slice(chunk_tensor, static_cast<uint32_t>(dim), chunk_start_offset, chunk_seq_len);
+
+ // Accumulating the full tensor preserving the left padding.
+ // Starting with the offset that is the max_seq_len - real input_prompt_len,
+ // accumulation is performed from the left to right.
+ const uint32_t full_seq_len = static_cast<uint32_t>(full_shape[dim]);
+ OPENVINO_ASSERT(full_seq_len == max_seq_len,
+ "Pre-allocated tensor size (" + std::to_string(full_seq_len) +
+ ") must match max sequence length (" + std::to_string(max_seq_len) + ")");
+ const auto full_tensor_slice_begin = start_offset + processed_token_count;
+ const auto full_tensor_slice_end = full_tensor_slice_begin + chunk_token_count;
+ auto full_tensor_slice = util::make_tensor_slice(full_tensor,
+ static_cast<uint32_t>(dim),
+ full_tensor_slice_begin,
+ full_tensor_slice_end);
+
+ chunk_tensor_slice->copy_to(full_tensor_slice._ptr);
+
+ LOG_VERB("Copied chunk [" << chunk_start_offset << ":" << chunk_seq_len << "] to position ["
+ << full_tensor_slice_begin << ":" << full_tensor_slice_end << "], "
+ << chunk_token_count << " tokens");
+ }
+}
+
void ov::npuw::LLMInferRequest::infer_chunked_prefill(ov::SoPtr<ov::ITensor> input_ids,
ov::SoPtr<ov::ITensor> attention_mask,
ov::SoPtr<ov::ITensor> position_ids,
@@ -1054,15 +1119,22 @@ void ov::npuw::LLMInferRequest::infer_chunked_prefill(ov::SoPtr<ov::ITensor> inp
remaining_prompts = cache_context.remaining_prompts;
}
- if (m_eagle3_ext.is_eagle3_model()) {
- m_eagle3_ext.reset_chunked_prefill_state();
- }
-
// DeepStack rows are consumed in visual-token order across chunks; track how many have
// already been scattered so each chunk continues where the previous one left off.
size_t visual_tokens_scattered =
has_deepstack ? count_visual_tokens_before(visual_pos_masks, kvcache_desc.num_stored_tokens) : 0u;
+ const uint32_t start_offset = kvcache_desc.max_prompt_size - static_cast<uint32_t>(remaining_prompts);
+ const uint32_t other_outs_accum_base = kvcache_desc.num_stored_tokens;
+ if (other_outs_accum_base == 0 && start_offset > 0) {
+ // Fresh prefill: zero the unwritten left-padding rows so stale data from a
+ // previous, longer prompt isn't exposed.
+ for (auto&& [port, dim] : m_prefill_other_outs_seqdims) {
+ auto pad_slice =
+ util::make_tensor_slice(m_prefill_other_outs_accum[port], static_cast<uint32_t>(dim), 0, start_offset);
+ util::fill_tensor_bytes(pad_slice, 0u);
+ }
+ }
while (remaining_prompts > 0) {
// NB: input_ids can be either fp32(VLM) or i64(LLM)
// The last chunk may not be completely filled if the actual length of the prompts is not evenly divisible by
@@ -1204,13 +1276,10 @@ void ov::npuw::LLMInferRequest::infer_chunked_prefill(ov::SoPtr<ov::ITensor> inp
});
m_llm_profile["1/prefill:3c.post_chunk"].record([&]() {
- // Accumulate Eagle3 last_hidden_state from this chunk
- if (m_eagle3_ext.is_eagle3_model()) {
- m_eagle3_ext.accumulate_chunk_last_hidden_state(m_prefill_request,
- m_prefill_out_ports,
- static_cast<uint32_t>(current_prompts_len),
- static_cast<uint32_t>(input_prompt_len));
- }
+ accumulate_other_chunked_outputs(start_offset,
+ static_cast<uint32_t>(current_prompts_len),
+ kvcache_desc.num_stored_tokens - other_outs_accum_base,
+ static_cast<uint32_t>(kvcache_desc.max_prompt_size));
if (enable_prefix_caching) {
prefix_caching_helper->store_computed_blocks(current_prompts_len,
@@ -1420,10 +1489,16 @@ void ov::npuw::LLMInferRequest::infer_prefill(ov::SoPtr<ov::ITensor> input_ids,
m_logits = m_prefill_request->get_tensor(m_prefill_out_ports.at(layer_names::logits));
}
- // Update last_hidden_state only for non-chunked prefill
- // For chunked prefill, accumulate_chunk_last_hidden_state() already set the tensor
- if (m_eagle3_ext.is_eagle3_model() && !use_chunk_prefill) {
- m_eagle3_ext.update_last_hidden_state(m_prefill_request, m_prefill_out_ports);
+ for (auto&& [name, port] : m_prefill_out_ports) {
+ if (name == layer_names::logits) {
+ continue;
+ }
+ if (!m_prefill_other_outs_accum.empty() &&
+ m_prefill_other_outs_accum.find(port) != m_prefill_other_outs_accum.end()) {
+ m_other_outputs[name] = m_prefill_other_outs_accum[port];
+ } else {
+ m_other_outputs[name] = m_prefill_request->get_tensor(port);
+ }
}
});
@@ -1675,8 +1750,11 @@ void ov::npuw::LLMInferRequest::infer_generate(ov::SoPtr<ov::ITensor> input_ids,
m_logits = m_kvcache_request->get_tensor(m_kvcache_out_ports.at(layer_names::logits));
}
- if (m_eagle3_ext.is_eagle3_model()) {
- m_eagle3_ext.update_last_hidden_state(m_kvcache_request, m_kvcache_out_ports);
+ for (auto&& [name, port] : m_kvcache_out_ports) {
+ if (name == layer_names::logits) {
+ continue;
+ }
+ m_other_outputs[name] = m_kvcache_request->get_tensor(port);
}
LOG_DEBUG("Done");
@@ -1862,15 +1940,14 @@ ov::SoPtr<ov::ITensor> ov::npuw::LLMInferRequest::get_tensor(const ov::Output<co
OPENVINO_THROW("Logits tensor is not available. Please run inference first.");
}
return m_logits;
- }
-
- if (m_eagle3_ext.is_eagle3_model()) {
- if (port_names.count(Eagle3LayerNames::last_hidden_state) > 0) {
- auto last_hidden_state = m_eagle3_ext.get_last_hidden_state();
- if (!last_hidden_state) {
- OPENVINO_THROW("Last hidden state tensor is not available. Please run inference first.");
+ } else {
+ for (auto&& [name, tensor] : m_other_outputs) {
+ if (port_names.count(name) > 0) {
+ if (!tensor) {
+ OPENVINO_THROW("Output tensor \"", name, "\" is not available. Please run inference first.");
+ }
+ return tensor;
}
- return last_hidden_state;
}
}
diff --git a/src/plugins/intel_npu/src/plugin/npuw/llm_infer_request.hpp b/src/plugins/intel_npu/src/plugin/npuw/llm_infer_request.hpp
index d1bc4d1f757..ba7e1616826 100644
--- a/src/plugins/intel_npu/src/plugin/npuw/llm_infer_request.hpp
+++ b/src/plugins/intel_npu/src/plugin/npuw/llm_infer_request.hpp
@@ -5,6 +5,7 @@
#pragma once
#include <memory>
+#include <unordered_map>
#include "base_sync_infer_request.hpp"
#include "llm_compiled_model.hpp"
@@ -19,6 +20,13 @@
#include "openvino/core/descriptor/output.hpp"
#include "perf.hpp"
+template <>
+struct std::hash<ov::Output<const ov::Node>> {
+ std::size_t operator()(const ov::Output<const ov::Node>& port) const {
+ return ((hash<string>()(port.get_node()->get_name())) ^ (hash<std::size_t>()(port.get_index()) << 1));
+ }
+};
+
namespace ov {
namespace test {
namespace npuw {
@@ -94,6 +102,11 @@ protected:
PrefixCachingHelper* get_prefix_caching_helper(const ov::SoPtr<ov::ITensor>& position_ids);
bool use_longrope_prefix_cache(const ov::SoPtr<ov::ITensor>& position_ids) const;
+ void accumulate_other_chunked_outputs(uint32_t start_offset,
+ uint32_t chunk_token_count,
+ uint32_t processed_token_count,
+ uint32_t max_seq_len);
+
void infer_whole_prefill(ov::SoPtr<ov::ITensor> input_ids,
ov::SoPtr<ov::ITensor> attention_mask,
ov::SoPtr<ov::ITensor> position_ids,
@@ -174,6 +187,9 @@ protected:
// This infer request is optional, so can be null.
std::shared_ptr<ov::IAsyncInferRequest> m_lm_head_request;
ov::SoPtr<ov::ITensor> m_logits;
+ std::unordered_map<std::string, ov::SoPtr<ov::ITensor>> m_other_outputs;
+ std::map<ov::Output<const ov::Node>, std::size_t> m_prefill_other_outs_seqdims;
+ std::unordered_map<ov::Output<const ov::Node>, ov::SoPtr<ov::ITensor>> m_prefill_other_outs_accum;
PortsMap m_prefill_in_ports;
PortsMap m_prefill_out_ports;
diff --git a/src/plugins/intel_npu/src/plugin/npuw/npuw_transformations/cut_lm_head.cpp b/src/plugins/intel_npu/src/plugin/npuw/npuw_transformations/cut_lm_head.cpp
new file mode 100644
index 00000000000..c3dcbdd63d9
--- /dev/null
+++ b/src/plugins/intel_npu/src/plugin/npuw/npuw_transformations/cut_lm_head.cpp
@@ -0,0 +1,159 @@
+// Copyright (C) 2018-2026 Intel Corporation
+// SPDX-License-Identifier: Apache-2.0
+//
+
+#include "cut_lm_head.hpp"
+
+#include <algorithm>
+#include <memory>
+
+#include "../llm_compiled_model.hpp"
+#include "openvino/core/rt_info.hpp"
+#include "openvino/op/add.hpp"
+#include "openvino/op/convert.hpp"
+#include "openvino/op/divide.hpp"
+#include "openvino/op/matmul.hpp"
+#include "openvino/op/multiply.hpp"
+#include "openvino/op/parameter.hpp"
+#include "openvino/op/result.hpp"
+#include "openvino/op/tanh.hpp"
+#include "openvino/op/transpose.hpp"
+#include "openvino/pass/graph_rewrite.hpp"
+#include "openvino/pass/matcher_pass.hpp"
+#include "openvino/pass/pattern/op/or.hpp"
+#include "openvino/pass/pattern/op/wrap_type.hpp"
+
+namespace opp = ov::pass::pattern;
+
+namespace {
+
+// diagnostics warnings on OPENVINO_MATCHER_PASS_RTTI() definition: visibility hidden
+#ifdef __GNUC__
+# pragma GCC diagnostic push
+# pragma GCC diagnostic ignored "-Wattributes"
+#endif
+
+class CutLMHeadMatcher : public ov::pass::MatcherPass {
+public:
+ OPENVINO_MATCHER_PASS_RTTI("ov::npuw::patterns::CutLMHeadMatcher");
+ explicit CutLMHeadMatcher(std::shared_ptr<ov::Model>& lm_head_model) {
+ // The first input to MatMul is treated as the cut point.
+ auto matmul = opp::wrap_type<ov::op::v0::MatMul>({opp::any_input(), opp::any_input()});
+
+ // Several patterns for matmul are supported:
+ // Matmul -> Result
+ // Matmul -> Add -> Result
+ auto matmul_add = opp::wrap_type<ov::op::v1::Add>({matmul, opp::any_input()});
+ // Matmul -> Transpose -> Result
+ auto matmul_transpose = opp::wrap_type<ov::op::v1::Transpose>({matmul, opp::any_input()});
+ // Matmul -> Convert -> Result
+ auto matmul_convert = opp::wrap_type<ov::op::v0::Convert>({matmul});
+ // MatMul -> Divide -> Tanh -> Multiply -> Result
+ auto div = opp::wrap_type<ov::op::v1::Multiply, ov::op::v1::Divide>({matmul, opp::any_input()});
+ auto tanh = opp::wrap_type<ov::op::v0::Tanh>({div});
+ auto matmul_multiply = opp::wrap_type<ov::op::v1::Multiply>({tanh, opp::any_input()});
+
+ auto last_op = std::make_shared<opp::op::Or>(ov::OutputVector{matmul->output(0),
+ matmul_add->output(0),
+ matmul_transpose->output(0),
+ matmul_convert->output(0),
+ matmul_multiply->output(0)});
+ auto res = opp::wrap_type<ov::op::v0::Result>({last_op->output(0)});
+
+ auto callback = [=, &lm_head_model](opp::Matcher& m) {
+ auto& node_to_output = m.get_pattern_value_map();
+
+ auto matched_matmul =
+ std::static_pointer_cast<ov::op::v0::MatMul>(node_to_output.at(matmul).get_node_shared_ptr());
+ auto matched_result =
+ std::static_pointer_cast<ov::op::v0::Result>(node_to_output.at(res).get_node_shared_ptr());
+
+ std::shared_ptr<ov::Node> matched_node_last_op = matched_matmul;
+ for (const auto& p : {matmul_add, matmul_transpose, matmul_convert, matmul_multiply}) {
+ const auto it = node_to_output.find(p);
+ if (it != node_to_output.end()) {
+ matched_node_last_op = it->second.get_node_shared_ptr();
+ break;
+ }
+ }
+
+ // Skip Result nodes that are not logits.
+ // Note: checking that Result's output name is "logits" is a sufficiently
+ // reliable check for finding exactly the logits output, because:
+ // 1. LLMInferRequest always relies on the "logits" name to get logits
+ // from prefill/kvcache models.
+ // 2. - Following Exporter configs: OnnxConfig, OnnxConfigWithPast,
+ // TextDecoderOnnxConfig and TextDecoderWithPositionIdsOnnxConfig
+ // from optimum-onnx name LLM output with "logits".
+ // - Most of optimum-intel OpenVINO Exporter configs are derived
+ // from the configs above.
+ // - optimum-intel `export()` function sets names for output tensors
+ // from Exporter config:
+ // https://github.com/huggingface/optimum-intel/blob/main/optimum/exporters/openvino/convert.py#L442-L445
+ if (matched_result->output(0).get_names().count(ov::npuw::LLMCompiledModel::layer_names::logits) == 0) {
+ return false;
+ }
+
+ // Cut point:
+ auto matmul_first_source = matched_matmul->input(0).get_source_output();
+
+ // If the cut-point tensor already feeds another Result (e.g. a hidden-states
+ // output), the embeddings Result must own a distinct tensor. Otherwise both
+ // Results share one descriptor and collapse to a single named port in
+ // ov::ICompiledModel::ICompiledModel(). A cheap pass-through Convert gives the
+ // embeddings its own tensor; NopElimination keeps it alive because dropping it
+ // would merge two Result-feeding outputs (see can_output_be_replaced()).
+ ov::Output<ov::Node> embeds_source = matmul_first_source;
+ const auto& cut_readers = matmul_first_source.get_target_inputs();
+ const bool producer_feeds_result =
+ std::any_of(cut_readers.begin(), cut_readers.end(), [](const ov::Input<ov::Node>& in) {
+ return ov::is_type<ov::op::v0::Result>(in.get_node());
+ });
+ if (producer_feeds_result) {
+ auto embeds_convert =
+ std::make_shared<ov::op::v0::Convert>(matmul_first_source, matmul_first_source.get_element_type());
+ ov::copy_runtime_info(matmul_first_source.get_node_shared_ptr(), embeds_convert);
+ embeds_source = embeds_convert->output(0);
+ }
+
+ // Cut original model: repurpose the logits Result as the embeddings output.
+ matched_result->input(0).replace_source_output(embeds_source);
+ // Name the producing tensor too, so the output name survives
+ // ov::ICompiledModel::ICompiledModel() reconstruction.
+ embeds_source.set_names({ov::npuw::LLMCompiledModel::layer_names::output_embeds});
+ matched_result->output(0).set_names({ov::npuw::LLMCompiledModel::layer_names::output_embeds});
+ matched_result->validate_and_infer_types();
+
+ // Create an additional model after cut point:
+ auto new_param = std::make_shared<ov::op::v0::Parameter>(matmul_first_source.get_element_type(),
+ matmul_first_source.get_partial_shape());
+ new_param->output(0).add_names({ov::npuw::LLMCompiledModel::layer_names::output_embeds});
+ matched_matmul->input(0).replace_source_output(new_param);
+ auto new_result = std::make_shared<ov::op::v0::Result>(matched_node_last_op);
+ lm_head_model =
+ std::make_shared<ov::Model>(ov::OutputVector{new_result->output(0)}, ov::ParameterVector{new_param});
+
+ return true;
+ };
+ register_matcher(std::make_shared<opp::Matcher>(res, "CutLMHeadMatcher"), std::move(callback));
+ }
+};
+
+#ifdef __GNUC__
+# pragma GCC diagnostic pop
+#endif
+
+} // namespace
+
+namespace ov::npuw {
+
+CutLMHead::CutLMHead(std::shared_ptr<ov::Model>& lm_head_model) : m_lm_head_model(lm_head_model) {}
+
+bool CutLMHead::run_on_model(const std::shared_ptr<ov::Model>& model) {
+ ov::pass::GraphRewrite rewr;
+ rewr.add_matcher<CutLMHeadMatcher>(m_lm_head_model);
+ rewr.run_on_model(model);
+ return m_lm_head_model != nullptr;
+}
+
+} // namespace ov::npuw
diff --git a/src/plugins/intel_npu/src/plugin/npuw/npuw_transformations/cut_lm_head.hpp b/src/plugins/intel_npu/src/plugin/npuw/npuw_transformations/cut_lm_head.hpp
new file mode 100644
index 00000000000..30c7502c7aa
--- /dev/null
+++ b/src/plugins/intel_npu/src/plugin/npuw/npuw_transformations/cut_lm_head.hpp
@@ -0,0 +1,27 @@
+// Copyright (C) 2018-2026 Intel Corporation
+// SPDX-License-Identifier: Apache-2.0
+//
+
+#pragma once
+
+#include <memory>
+
+#include "openvino/pass/pass.hpp"
+
+namespace ov::npuw {
+
+// Splits the LM head (vocabulary MatMul) off the input model and returns
+// it as a separate one.
+// The cut point is the first input of the matched MatMul. The matched logits
+// Result is repurposed as the output-embeddings Result of the original model.
+class CutLMHead : public ov::pass::ModelPass {
+public:
+ OPENVINO_MODEL_PASS_RTTI("ov::npuw::CutLMHead");
+ explicit CutLMHead(std::shared_ptr<ov::Model>& lm_head_model);
+ bool run_on_model(const std::shared_ptr<ov::Model>& model) override;
+
+private:
+ std::shared_ptr<ov::Model>& m_lm_head_model;
+};
+
+} // namespace ov::npuw
diff --git a/src/plugins/intel_npu/src/plugin/npuw/npuw_transformations/slice_out_embeds.cpp b/src/plugins/intel_npu/src/plugin/npuw/npuw_transformations/slice_out_embeds.cpp
index 146ec962976..f3dc59e68fd 100644
--- a/src/plugins/intel_npu/src/plugin/npuw/npuw_transformations/slice_out_embeds.cpp
+++ b/src/plugins/intel_npu/src/plugin/npuw/npuw_transformations/slice_out_embeds.cpp
@@ -14,7 +14,7 @@ void slice_out_embeds(std::shared_ptr<ov::Model> model,
std::size_t max_generation_token_len) {
std::shared_ptr<ov::Node> embed_result;
for (auto&& output : model->outputs()) {
- if (output.get_any_name() == ov::npuw::LLMCompiledModel::output_embeds) {
+ if (output.get_any_name() == ov::npuw::LLMCompiledModel::layer_names::output_embeds) {
embed_result = output.get_node_shared_ptr();
}
}
diff --git a/src/plugins/intel_npu/src/plugin/sources.cmake b/src/plugins/intel_npu/src/plugin/sources.cmake
index 57bbbca515b..a647ad08f97 100644
--- a/src/plugins/intel_npu/src/plugin/sources.cmake
+++ b/src/plugins/intel_npu/src/plugin/sources.cmake
@@ -126,6 +126,8 @@ set(NPUW_SOURCES
${CMAKE_CURRENT_SOURCE_DIR}/npuw/npuw_transformations/collapse_unqdq.hpp
${CMAKE_CURRENT_SOURCE_DIR}/npuw/npuw_transformations/convert_kvcache_to_precision.cpp
${CMAKE_CURRENT_SOURCE_DIR}/npuw/npuw_transformations/convert_kvcache_to_precision.hpp
+ ${CMAKE_CURRENT_SOURCE_DIR}/npuw/npuw_transformations/cut_lm_head.cpp
+ ${CMAKE_CURRENT_SOURCE_DIR}/npuw/npuw_transformations/cut_lm_head.hpp
${CMAKE_CURRENT_SOURCE_DIR}/npuw/npuw_transformations/insert_vocab_sub128.cpp
${CMAKE_CURRENT_SOURCE_DIR}/npuw/npuw_transformations/insert_vocab_sub128.hpp
${CMAKE_CURRENT_SOURCE_DIR}/npuw/npuw_transformations/conv_to_matmul.cpp
diff --git a/src/plugins/intel_npu/tests/functional/behavior/npuw/llm_smoke_behavior_tests.cpp b/src/plugins/intel_npu/tests/functional/behavior/npuw/llm_smoke_behavior_tests.cpp
new file mode 100644
index 00000000000..195dbf1338c
--- /dev/null
+++ b/src/plugins/intel_npu/tests/functional/behavior/npuw/llm_smoke_behavior_tests.cpp
@@ -0,0 +1,124 @@
+// Copyright (C) 2018-2026 Intel Corporation
+// SPDX-License-Identifier: Apache-2.0
+//
+
+#include <gtest/gtest.h>
+
+#include <numeric>
+
+#include "common_test_utils/ov_tensor_utils.hpp"
+#include "functional_test_utils/skip_tests_config.hpp"
+#include "npuw/test_engine/models/model_builder.hpp"
+#include "npuw/test_engine/simple_llm_pipeline.hpp"
+
+class MultiOutsLLMSmokeBehaviorNPUW : public ::testing::Test {
+public:
+ void SetUp() override {
+ SKIP_IF_CURRENT_TEST_IS_DISABLED();
+
+// Test will only work if CPU plugin is enabled.
+#if !defined(OPENVINO_STATIC_LIBRARY) && defined(WITH_CPU_PLUGIN) && \
+ (defined(OPENVINO_ARCH_X86) || defined(OPENVINO_ARCH_X86_64))
+ const char* cpu_plugin_file_name = "openvino_intel_cpu_plugin";
+ // Register CPU plugin in OpenVINO:
+ try {
+ core.register_plugin(std::string(cpu_plugin_file_name) + OV_BUILD_POSTFIX, "CPU");
+ } catch (ov::Exception& ex) {
+ if (std::string{ex.what()}.find("is already registered as device \"CPU\"") == std::string::npos) {
+ throw ex;
+ }
+ }
+#else
+ GTEST_SKIP() << "CPU plugin is not enabled or platform requirements are not met, skipping the test!";
+#endif // not OPENVINO_STATIC_LIBRARY && WITH_CPU_PLUGIN &&
+ // (defined(OPENVINO_ARCH_X86) || defined(OPENVINO_ARCH_X86_64));
+
+ chunked_prefill_props = {{"NPU_USE_NPUW", "YES"},
+ {"NPUW_LLM", "YES"},
+ {"NPUW_DEVICES", "CPU"},
+ {"NPUW_LLM_MAX_PROMPT_LEN", "128"},
+ {"NPUW_LLM_MIN_RESPONSE_LEN", "64"},
+ {"NPUW_LLM_PREFILL_CHUNK_SIZE", "32"}};
+
+ input_ids.resize(128);
+ std::iota(input_ids.begin(), input_ids.end(), 1);
+ }
+
+ const std::shared_ptr<ov::Model> build_multiouts_llm_model(const bool with_pooled_output) {
+ ov::test::npuw::LLMConfig cfg;
+ cfg.add_hidden_states_output = true;
+ cfg.hidden_states_output_name = "hidden_states";
+
+ if (with_pooled_output) {
+ cfg.add_pooled_output = true;
+ cfg.pooled_output_name = "pooled_hidden_state";
+ }
+
+ ov::test::npuw::ModelBuilder builder;
+ return builder.build_llm(cfg);
+ }
+
+protected:
+ ov::Core core;
+ SimpleLLMPipeline simple_llm;
+ ov::AnyMap chunked_prefill_props;
+ std::vector<int64_t> input_ids;
+};
+
+TEST_F(MultiOutsLLMSmokeBehaviorNPUW, NonLogitsOutputIsFullSizedAfterChunkedPrefill) {
+ SKIP_IF_CURRENT_TEST_IS_DISABLED();
+
+ const auto multiouts_llm = build_multiouts_llm_model(false);
+
+ // Prefill stage: non-logits output must be accumulated to the full prompt length.
+ simple_llm.initialize(multiouts_llm, core, chunked_prefill_props);
+ EXPECT_NO_THROW(simple_llm.prefill(input_ids));
+ const auto hidden_states = simple_llm.get_request()->get_tensor("hidden_states");
+ EXPECT_EQ(hidden_states.get_shape(), (ov::Shape{1, 128, 64}));
+
+ const auto prefill_logits = simple_llm.get_request()->get_tensor("logits");
+ EXPECT_EQ(prefill_logits.get_shape()[0], 1u);
+ EXPECT_EQ(prefill_logits.get_shape()[1], 1u);
+
+ // Chunked accumulation must produce values close to a whole (non-chunked) prefill.
+ // NB: not bit-exact due to floating point rounding from different reduction order.
+ auto whole_prefill_props = chunked_prefill_props;
+ whole_prefill_props.erase("NPUW_LLM_PREFILL_CHUNK_SIZE");
+ SimpleLLMPipeline whole_prefill_llm;
+ whole_prefill_llm.initialize(multiouts_llm, core, whole_prefill_props);
+ EXPECT_NO_THROW(whole_prefill_llm.prefill(input_ids));
+ const auto whole_hidden_states = whole_prefill_llm.get_request()->get_tensor("hidden_states");
+ EXPECT_EQ(hidden_states.get_shape(), whole_hidden_states.get_shape());
+ constexpr double abs_threshold = 1e-2;
+ constexpr double rel_threshold = 1e-2;
+ EXPECT_NO_THROW(
+ ov::test::utils::compare(whole_hidden_states, hidden_states, ov::element::f16, abs_threshold, rel_threshold));
+
+ // Generate stage: non-logits output reflects only the newly generated token, not the prompt.
+ SimpleLLMPipeline generate_llm;
+ generate_llm.initialize(multiouts_llm, core, chunked_prefill_props);
+ EXPECT_NO_THROW(generate_llm.generate(input_ids));
+ const auto generate_hidden_states = generate_llm.get_request()->get_tensor("hidden_states");
+ EXPECT_EQ(generate_hidden_states.get_shape(), (ov::Shape{1, 1, 64}));
+}
+
+TEST_F(MultiOutsLLMSmokeBehaviorNPUW, DifferentNonLogitsOutputs) {
+ SKIP_IF_CURRENT_TEST_IS_DISABLED();
+
+ const auto multi_different_outs_llm = build_multiouts_llm_model(true);
+ simple_llm.initialize(multi_different_outs_llm, core, chunked_prefill_props);
+ EXPECT_NO_THROW(simple_llm.prefill(input_ids));
+
+ const auto& llm_infer_request = simple_llm.get_request();
+ const auto hidden_states = llm_infer_request->get_tensor("hidden_states");
+ EXPECT_EQ(hidden_states.get_shape(), (ov::Shape{1, 128, 64}));
+
+ const auto logits = llm_infer_request->get_tensor("logits");
+ EXPECT_EQ(logits.get_shape()[0], 1u);
+ EXPECT_EQ(logits.get_shape()[1], 1u);
+
+ // NB: pooled_hidden_state has no sequence axis, so only its shape is checked here.
+ const auto pooled_hidden = llm_infer_request->get_tensor("pooled_hidden_state");
+ EXPECT_EQ(pooled_hidden.get_shape(), (ov::Shape{1, 64}));
+ EXPECT_EQ(pooled_hidden.get_shape().size(), 2u);
+}
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 954c1a31dfe..1314358cae2 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
@@ -768,15 +768,16 @@ std::shared_ptr<ov::Model> ModelBuilder::build_llm(const LLMConfig& config_in) {
if (!config.ffn) {
if (config.num_experts > 0) {
// Build the FFN from the config's MoE fields; moe_factory selects the topology (empty = GPT-OSS).
- size_t moe_inter = config.moe_intermediate_size > 0
- ? config.moe_intermediate_size
- : config.intermediate_size;
- size_t moe_k = config.num_experts_per_tok > 0
- ? config.num_experts_per_tok
- : std::min<size_t>(2, config.num_experts);
+ size_t moe_inter =
+ config.moe_intermediate_size > 0 ? config.moe_intermediate_size : config.intermediate_size;
+ size_t moe_k =
+ config.num_experts_per_tok > 0 ? config.num_experts_per_tok : std::min<size_t>(2, config.num_experts);
OPENVINO_ASSERT(moe_k >= 1 && moe_k <= config.num_experts,
"Invalid MoE config: num_experts_per_tok (",
- moe_k, ") must be in [1, num_experts (", config.num_experts, ")]");
+ moe_k,
+ ") must be in [1, num_experts (",
+ config.num_experts,
+ ")]");
if (!config.moe_factory) {
config.moe_factory = make_gptoss_moe_ffn;
}
@@ -934,10 +935,20 @@ std::shared_ptr<ov::Model> ModelBuilder::build_llm(const LLMConfig& config_in) {
const ov::Output<ov::Node>& v_proj,
size_t /*layer*/) {
auto idx_str = std::to_string(attn_idx);
- auto k_cache = make_kv_cache_concat(k_proj, seq_source, beam_idx_output, kv_heads, config.head_dim,
- make_cache_params_var_id("key", idx_str), prec);
- auto v_cache = make_kv_cache_concat(v_proj, seq_source, beam_idx_output, kv_heads, config.head_dim,
- make_cache_params_var_id("value", idx_str), prec);
+ auto k_cache = make_kv_cache_concat(k_proj,
+ seq_source,
+ beam_idx_output,
+ kv_heads,
+ config.head_dim,
+ make_cache_params_var_id("key", idx_str),
+ prec);
+ auto v_cache = make_kv_cache_concat(v_proj,
+ seq_source,
+ beam_idx_output,
+ kv_heads,
+ config.head_dim,
+ make_cache_params_var_id("value", idx_str),
+ prec);
m_sinks.push_back(std::dynamic_pointer_cast<ov::op::Sink>(k_cache.assign));
m_sinks.push_back(std::dynamic_pointer_cast<ov::op::Sink>(v_cache.assign));
return std::pair{k_cache.concatenated, v_cache.concatenated};
@@ -985,6 +996,33 @@ std::shared_ptr<ov::Model> ModelBuilder::build_llm(const LLMConfig& config_in) {
if (config.lm_head_weight) {
auto logits =
make_lm_head(final_norm, config.hidden_size, config.vocab_size, "lm_head", prec, config.lm_head_weight);
+ if (config.add_hidden_states_output || config.add_pooled_output) {
+ ov::OutputVector outputs;
+
+ auto logits_result = std::make_shared<ov::op::v0::Result>(logits);
+ logits_result->set_friendly_name("logits");
+ logits_result->output(0).set_names({"logits"});
+ outputs.push_back(logits_result->output(0));
+
+ if (config.add_hidden_states_output) {
+ auto hidden_states_result = std::make_shared<ov::op::v0::Result>(final_norm);
+ hidden_states_result->set_friendly_name(config.hidden_states_output_name);
+ hidden_states_result->output(0).set_names({config.hidden_states_output_name});
+ outputs.push_back(hidden_states_result->output(0));
+ }
+
+ if (config.add_pooled_output) {
+ auto seq_axis = ov::opset11::Constant::create(ov::element::i64, ov::Shape{1}, {1});
+ auto pooled = std::make_shared<ov::opset11::ReduceMean>(final_norm, seq_axis, false);
+ pooled->set_friendly_name(config.pooled_output_name + "_reduce");
+ auto pooled_result = std::make_shared<ov::op::v0::Result>(pooled);
+ pooled_result->set_friendly_name(config.pooled_output_name);
+ pooled_result->output(0).set_names({config.pooled_output_name});
+ outputs.push_back(pooled_result->output(0));
+ }
+
+ return std::make_shared<ov::Model>(outputs, m_sinks, model_name);
+ }
return make_model(logits, "logits", model_name);
}
return make_model(final_norm, "last_hidden_state", model_name);
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 d3fdf7e4751..de8db0512f6 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
@@ -165,10 +165,8 @@ struct BaseModelConfig {
/// for SDPA. Empty = default Gemma-4-style float construction; set to a builder
/// like make_sliding_window_mask_phi3 to test the older boolean Phi3 pattern.
/// Builder declarations live in model_builder_masks.hpp.
-using SlidingMaskFn = std::function<ov::Output<ov::Node>(const ov::Output<ov::Node>&,
- const ov::Output<ov::Node>&,
- ov::element::Type,
- size_t)>;
+using SlidingMaskFn = std::function<
+ ov::Output<ov::Node>(const ov::Output<ov::Node>&, const ov::Output<ov::Node>&, ov::element::Type, size_t)>;
/// Minimal standalone LoRA adapter model config (no attention/KV/RoPE).
struct LoRAConfig : public BaseModelConfig {
@@ -198,17 +196,18 @@ struct LLMConfig : public BaseModelConfig {
LongRopeSpec longrope;
// MoE configuration (num_experts=0 means dense, no MoE)
- size_t num_experts = 0; ///< Total experts. 0 = dense model.
- size_t num_experts_per_tok = 0; ///< Top-K. 0 = default to 2.
- size_t moe_intermediate_size = 0; ///< Expert FFN intermediate size. 0 = use intermediate_size.
- MoEFactoryFn moe_factory; ///< MoE topology (num_experts>0). Empty = GPT-OSS; make_qwen3_moe_ffn for Qwen3.
+ size_t num_experts = 0; ///< Total experts. 0 = dense model.
+ size_t num_experts_per_tok = 0; ///< Top-K. 0 = default to 2.
+ size_t moe_intermediate_size = 0; ///< Expert FFN intermediate size. 0 = use intermediate_size.
+ MoEFactoryFn moe_factory; ///< MoE topology (num_experts>0). Empty = GPT-OSS; make_qwen3_moe_ffn for Qwen3.
- size_t sliding_window_size = 0; ///< 0 = no sliding window. >0 = window size (Phi-3, Gemma 2/3)
+ size_t sliding_window_size = 0; ///< 0 = no sliding window. >0 = window size (Phi-3, Gemma 2/3)
/// 0 = uniform: every layer gets the same mask (all sliding if sliding_window_size > 0,
/// else all full causal). N > 0 = N sliding layers per 1 full, alternating (Gemma 2: 1, Gemma 3: 5).
size_t sliding_to_full_ratio = 0;
- bool use_token_type_ids = false; ///< Gemma 3 VLM: token_type_ids param (0=text/causal, 1=image/bidir)
- SlidingMaskFn sliding_mask_fn; ///< Empty = default float SWA (matches no NPUW pass; set make_sliding_window_mask_phi3 for Phi-3/Gemma-2/Gemma-3).
+ bool use_token_type_ids = false; ///< Gemma 3 VLM: token_type_ids param (0=text/causal, 1=image/bidir)
+ SlidingMaskFn sliding_mask_fn; ///< Empty = default float SWA (matches no NPUW pass; set
+ ///< make_sliding_window_mask_phi3 for Phi-3/Gemma-2/Gemma-3).
/// LoRA adapter support: inject low-rank A/B/alpha tensors per adapted linear layer.
/// 0 = no LoRA. >0 = inject LoRA with this max rank into adapted projections.
@@ -227,6 +226,12 @@ struct LLMConfig : public BaseModelConfig {
/// Token mixer for linear layers (e.g. GatedDeltaNetMixer or ShortConvMixer). build_llm wires
/// its seq_source/beam_idx. A new mixer type needs no build_llm change.
std::shared_ptr<LinearMixer> linear_mixer;
+
+ // Support of LLM with multiple outputs: OmniThinker
+ bool add_hidden_states_output = false;
+ std::string hidden_states_output_name = "hidden_states";
+ bool add_pooled_output = false;
+ std::string pooled_output_name = "pooled_hidden_state";
};
struct WhisperConfig : public BaseModelConfig {
diff --git a/src/plugins/intel_npu/tests/functional/behavior/npuw/test_engine/simple_llm_pipeline.cpp b/src/plugins/intel_npu/tests/functional/behavior/npuw/test_engine/simple_llm_pipeline.cpp
index 5fb8a855d1d..afe6d8d7d60 100644
--- a/src/plugins/intel_npu/tests/functional/behavior/npuw/test_engine/simple_llm_pipeline.cpp
+++ b/src/plugins/intel_npu/tests/functional/behavior/npuw/test_engine/simple_llm_pipeline.cpp
@@ -26,9 +26,9 @@ int64_t get_token_as_max_logit(ov::Tensor logits) {
int64_t out_token = std::max_element(logits_data, logits_data + vocab_size) - logits_data;
return out_token;
}
-} // anonymous namespace
+} // anonymous namespace
-void SimpleLLMPipeline::initialize(const std::string& model_path, ov::Core& core, const ov::AnyMap& config) {
+void SimpleLLMPipeline::initialize(const std::shared_ptr<ov::Model>& model, ov::Core& core, const ov::AnyMap& config) {
ov::AnyMap properties(config);
m_max_prompt_len = get_or_default(properties, "NPUW_LLM_MAX_PROMPT_LEN", 128);
m_min_response_len = get_or_default(properties, "NPUW_LLM_MIN_RESPONSE_LEN", 4);
@@ -37,22 +37,20 @@ void SimpleLLMPipeline::initialize(const std::string& model_path, ov::Core& core
update_config(properties, {"NPU_USE_NPUW", "YES"});
update_config(properties, {"NPUW_LLM", "YES"});
- std::shared_ptr<ov::Model> model = core.read_model(model_path);
- m_compiled_model =
- std::make_shared<ov::CompiledModel>(core.compile_model(model, "NPU",
- properties));
+ m_compiled_model = std::make_shared<ov::CompiledModel>(core.compile_model(model, "NPU", properties));
m_request = std::make_shared<ov::InferRequest>(m_compiled_model->create_infer_request());
}
-std::vector<int64_t> SimpleLLMPipeline::generate(const std::vector<int64_t>& input_ids_vec) {
- std::vector<int64_t> result;
+void SimpleLLMPipeline::initialize(const std::string& model_path, ov::Core& core, const ov::AnyMap& config) {
+ initialize(core.read_model(model_path), core, config);
+}
+int64_t SimpleLLMPipeline::prefill(const std::vector<int64_t>& input_ids_vec) {
// NB: Check if there is enough space in KV-cache to process input prompt
auto prompt_len = input_ids_vec.size();
if (prompt_len > m_max_prompt_len) {
- OPENVINO_THROW("Simple LLM pipeline may only process prompts up to "
- + std::to_string(m_max_prompt_len) + " tokens. "
- + "Set the \"MAX_PROMPT_LEN\" config option to increase the limit.");
+ OPENVINO_THROW("Simple LLM pipeline may only process prompts up to " + std::to_string(m_max_prompt_len) +
+ " tokens. " + "Set the \"MAX_PROMPT_LEN\" config option to increase the limit.");
}
std::vector<uint64_t> input_ids_vec_copy(input_ids_vec.begin(), input_ids_vec.end());
@@ -75,15 +73,24 @@ std::vector<int64_t> SimpleLLMPipeline::generate(const std::vector<int64_t>& inp
OPENVINO_ASSERT(logits.get_shape()[1] == 1);
// Get token with greedy search
- int64_t out_token = get_token_as_max_logit(logits);
+ return get_token_as_max_logit(logits);
+}
+
+std::vector<int64_t> SimpleLLMPipeline::generate(const std::vector<int64_t>& input_ids_vec) {
+ std::vector<int64_t> result;
+
+ auto prompt_len = input_ids_vec.size();
+ int64_t out_token = prefill(input_ids_vec);
result.push_back(out_token);
// Create variables for new input_ids and position_ids
int64_t input_ids_data = -1;
int64_t position_ids_data = prompt_len - 1;
std::vector<int64_t> attention_mask_data(prompt_len, 1);
- m_request->set_tensor("input_ids", ov::Tensor(ov::element::i64, ov::Shape{1,1}, reinterpret_cast<void*>(&input_ids_data)));
- m_request->set_tensor("position_ids", ov::Tensor(ov::element::i64, ov::Shape{1,1}, reinterpret_cast<void*>(&position_ids_data)));
+ m_request->set_tensor("input_ids",
+ ov::Tensor(ov::element::i64, ov::Shape{1, 1}, reinterpret_cast<void*>(&input_ids_data)));
+ m_request->set_tensor("position_ids",
+ ov::Tensor(ov::element::i64, ov::Shape{1, 1}, reinterpret_cast<void*>(&position_ids_data)));
std::size_t total_generated_tokens{1};
// Assume that we don't want to produce more than min response len in simple pipeline.
@@ -98,7 +105,9 @@ std::vector<int64_t> SimpleLLMPipeline::generate(const std::vector<int64_t>& inp
++position_ids_data;
// However, attention_mask changes its shape on each iteration, it should be re-set explicitly
attention_mask_data.push_back(1);
- m_request->set_tensor("attention_mask", ov::Tensor(ov::element::i64, ov::Shape{1,attention_mask_data.size()}, (void*)&attention_mask_data[0]));
+ m_request->set_tensor(
+ "attention_mask",
+ ov::Tensor(ov::element::i64, ov::Shape{1, attention_mask_data.size()}, (void*)&attention_mask_data[0]));
m_request->infer();
diff --git a/src/plugins/intel_npu/tests/functional/behavior/npuw/test_engine/simple_llm_pipeline.hpp b/src/plugins/intel_npu/tests/functional/behavior/npuw/test_engine/simple_llm_pipeline.hpp
index e5564b13fda..542b684bcb1 100644
--- a/src/plugins/intel_npu/tests/functional/behavior/npuw/test_engine/simple_llm_pipeline.hpp
+++ b/src/plugins/intel_npu/tests/functional/behavior/npuw/test_engine/simple_llm_pipeline.hpp
@@ -10,7 +10,18 @@
class SimpleLLMPipeline {
public:
void initialize(const std::string& model_path, ov::Core& core, const ov::AnyMap& config);
+ void initialize(const std::shared_ptr<ov::Model>& model, ov::Core& core, const ov::AnyMap& config);
+ int64_t prefill(const std::vector<int64_t>& input_ids_vec);
std::vector<int64_t> generate(const std::vector<int64_t>& input_ids_vec);
+
+ std::shared_ptr<ov::CompiledModel> get_compiled_model() const {
+ return m_compiled_model;
+ }
+
+ std::shared_ptr<ov::InferRequest> get_request() const {
+ return m_request;
+ }
+
private:
uint32_t m_max_prompt_len{std::numeric_limits<uint32_t>::max()};
uint32_t m_min_response_len{std::numeric_limits<uint32_t>::max()};
diff --git a/src/plugins/intel_npu/tests/unit/CMakeLists.txt b/src/plugins/intel_npu/tests/unit/CMakeLists.txt
index f9ca9a76d4f..dc8da851866 100644
--- a/src/plugins/intel_npu/tests/unit/CMakeLists.txt
+++ b/src/plugins/intel_npu/tests/unit/CMakeLists.txt
@@ -116,6 +116,7 @@ ov_add_test_target(
${OpenVINO_SOURCE_DIR}/src/plugins/intel_npu/src/plugin/npuw/npuw_transformations/collapse_unqdq.cpp
${OpenVINO_SOURCE_DIR}/src/plugins/intel_npu/src/plugin/npuw/npuw_transformations/conv_to_matmul.cpp
${OpenVINO_SOURCE_DIR}/src/plugins/intel_npu/src/plugin/npuw/npuw_transformations/convert_kvcache_to_precision.cpp
+ ${OpenVINO_SOURCE_DIR}/src/plugins/intel_npu/src/plugin/npuw/npuw_transformations/cut_lm_head.cpp
${OpenVINO_SOURCE_DIR}/src/plugins/intel_npu/src/plugin/npuw/npuw_transformations/drop_zp_subtract.cpp
${OpenVINO_SOURCE_DIR}/src/plugins/intel_npu/src/plugin/npuw/npuw_transformations/untangle_dq_scale.cpp
${OpenVINO_SOURCE_DIR}/src/plugins/intel_npu/src/plugin/npuw/npuw_transformations/lora_stateful_to_stateless.cpp
@@ -214,6 +215,7 @@ target_sources(${TARGET_NAME} PRIVATE
${CMAKE_CURRENT_SOURCE_DIR}/npuw/pipeline_passes/right_align_mask_slice_for_conv_test.cpp
${CMAKE_CURRENT_SOURCE_DIR}/npuw/pipeline_passes/collapse_unqdq_test.cpp
${CMAKE_CURRENT_SOURCE_DIR}/npuw/pipeline_passes/conv_to_matmul_test.cpp
+ ${CMAKE_CURRENT_SOURCE_DIR}/npuw/pipeline_passes/cut_lm_head_test.cpp
${CMAKE_CURRENT_SOURCE_DIR}/npuw/pipeline_passes/patch_sliding_mask_test.cpp
${CMAKE_CURRENT_SOURCE_DIR}/npuw/pipeline_passes/detect_causal_mask_test.cpp
${CMAKE_CURRENT_SOURCE_DIR}/npuw/pipeline_passes/shrink_sliding_window_kv_cache_test.cpp
diff --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.cpp
index 0b7b0b852e3..9925e934613 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
@@ -661,7 +661,8 @@ TEST_F(LLMCompiledModelFactoryOptionsTest, DefaultStageConfigsCarryBaselineNpuwO
EXPECT_FALSE(prop_string(call->props, "NPUW_WEIGHTS_BANK").empty());
}
- expect_prop(prefill.props, "NPUW_SLICE_OUT", "YES");
+ // In three-model pipeline, `slice_out_embeds()` handles the slicing for the prefill model.
+ expect_missing_prop(prefill.props, "NPUW_SLICE_OUT");
expect_prop(prefill.props, "NPUW_FUNCALL_ASYNC", "YES");
expect_prop(prefill.props, "NPUW_ATTN", "PYRAMID");
expect_prop(prefill.props, "NPUW_ONLINE_PIPELINE", "REP");
diff --git a/src/plugins/intel_npu/tests/unit/npuw/llm_compiled_model_graph_options_test.cpp b/src/plugins/intel_npu/tests/unit/npuw/llm_compiled_model_graph_options_test.cpp
index ba4b8b0c3bb..0a20680fde4 100644
--- a/src/plugins/intel_npu/tests/unit/npuw/llm_compiled_model_graph_options_test.cpp
+++ b/src/plugins/intel_npu/tests/unit/npuw/llm_compiled_model_graph_options_test.cpp
@@ -6,8 +6,8 @@
#include <gtest/gtest.h>
#include <algorithm>
-#include <optional>
#include <memory>
+#include <optional>
#include <string>
#include <string_view>
#include <vector>
@@ -129,9 +129,9 @@ TEST_F(LLMCompiledModelGraphOptionsTest, SharedHeadAddsHeadModelAndSlicesPrefill
RecordingFactory recorder;
std::unique_ptr<ov::npuw::LLMCompiledModel> compiled;
- ASSERT_NO_THROW(compiled = create_compiled_model({{"NPUW_LLM_SHARED_HEAD", "YES"},
- {"NPUW_LLM_MAX_GENERATION_TOKEN_LEN", "8"}},
- recorder));
+ ASSERT_NO_THROW(
+ compiled = create_compiled_model({{"NPUW_LLM_SHARED_HEAD", "YES"}, {"NPUW_LLM_MAX_GENERATION_TOKEN_LEN", "8"}},
+ recorder));
ASSERT_NE(compiled, nullptr);
const auto* prefill = recorder.find_suffix("_prefill");
@@ -139,7 +139,7 @@ TEST_F(LLMCompiledModelGraphOptionsTest, SharedHeadAddsHeadModelAndSlicesPrefill
ASSERT_NE(prefill, nullptr);
ASSERT_NE(lm_head, nullptr);
- const auto embeds = find_output(prefill->model, ov::npuw::LLMCompiledModel::output_embeds);
+ const auto embeds = find_output(prefill->model, ov::npuw::LLMCompiledModel::layer_names::output_embeds);
ASSERT_TRUE(embeds.has_value());
ASSERT_TRUE(embeds->get_partial_shape().is_static());
EXPECT_EQ(embeds->get_shape(), (ov::Shape{1, 8, 64}));
@@ -275,9 +275,9 @@ TEST_F(LLMCompiledModelGraphOptionsTest, ContinuousPrefillReportsOffForStaticPre
// Whole (STATIC) prefill has no continuation path, so even an explicit YES
// is reported as NO.
- ASSERT_NO_THROW(compiled = create_compiled_model({{"NPUW_LLM_ENABLE_CONTINUOUS_PREFILL", "YES"},
- {"NPUW_LLM_PREFILL_HINT", "STATIC"}},
- recorder));
+ ASSERT_NO_THROW(compiled = create_compiled_model(
+ {{"NPUW_LLM_ENABLE_CONTINUOUS_PREFILL", "YES"}, {"NPUW_LLM_PREFILL_HINT", "STATIC"}},
+ recorder));
ASSERT_NE(compiled, nullptr);
EXPECT_FALSE(compiled->get_property("NPUW_LLM_ENABLE_CONTINUOUS_PREFILL").as<bool>());
}
diff --git a/src/plugins/intel_npu/tests/unit/npuw/llm_infer_request_variant_switch_test.cpp b/src/plugins/intel_npu/tests/unit/npuw/llm_infer_request_variant_switch_test.cpp
index bb3689898c8..27cc4f71081 100644
--- a/src/plugins/intel_npu/tests/unit/npuw/llm_infer_request_variant_switch_test.cpp
+++ b/src/plugins/intel_npu/tests/unit/npuw/llm_infer_request_variant_switch_test.cpp
@@ -18,8 +18,8 @@
#include "executor.hpp"
#include "llm_block_kvcache_strategy.hpp"
-#include "llm_infer_request.hpp"
#include "llm_compiled_model.hpp"
+#include "llm_infer_request.hpp"
#include "llm_test_helpers.hpp"
#include "openvino/openvino.hpp"
#include "serialization.hpp"
@@ -42,7 +42,8 @@ struct LLMVariantSwitchTestAccess {
return compiled->m_is_block_kv_cache;
}
- static void set_num_stored_tokens(const std::shared_ptr<ov::npuw::LLMCompiledModel>& compiled, uint32_t num_tokens) {
+ static void set_num_stored_tokens(const std::shared_ptr<ov::npuw::LLMCompiledModel>& compiled,
+ uint32_t num_tokens) {
compiled->m_kvcache_desc.num_stored_tokens = num_tokens;
}
@@ -138,6 +139,31 @@ struct LLMVariantSwitchTestAccess {
req.m_kvcache_variant_idx = idx;
}
+ static std::shared_ptr<ov::npuw::ICompiledModel_v0> prefill_compiled(
+ const std::shared_ptr<ov::npuw::LLMCompiledModel>& compiled) {
+ return compiled->m_prefill_compiled;
+ }
+
+ static void set_prefill_other_outs_to_seqdims(const std::shared_ptr<ov::npuw::LLMCompiledModel>& compiled,
+ std::map<ov::Output<const ov::Node>, std::size_t> table) {
+ compiled->m_prefill_other_outs_seqdims = std::move(table);
+ }
+
+ static const std::map<ov::Output<const ov::Node>, std::size_t>& prefill_other_outs_to_seqdims(
+ const std::shared_ptr<ov::npuw::LLMCompiledModel>& compiled) {
+ return compiled->m_prefill_other_outs_seqdims;
+ }
+
+ static std::map<std::string, std::size_t> serialize_prefill_other_outs_seqdims(
+ const std::shared_ptr<ov::npuw::LLMCompiledModel>& compiled) {
+ return compiled->serialize_prefill_other_outs_seqdims();
+ }
+
+ static void deserialize_prefill_other_outs_seqdims(const std::shared_ptr<ov::npuw::LLMCompiledModel>& compiled,
+ const std::map<std::string, std::size_t>& by_name) {
+ compiled->deserialize_prefill_other_outs_seqdims(by_name);
+ }
+
// Re-serialize the model's metadata in the exact field order LLMCompiledModel::serialize() uses
// (write_model_meta), but write a forged trailing variant count instead of the real one. All
// fields except that count come straight from the real, valid compiled model, so the blob
@@ -269,8 +295,9 @@ FakeSubInferRequest::FakeSubInferRequest(std::shared_ptr<const FakeSubCompiledMo
ov::get_tensor_impl(ov::Tensor(input.get_element_type(), input.get_shape())));
}
for (const auto& output : get_compiled_model()->outputs()) {
- ov::ISyncInferRequest::set_tensor(output,
- ov::get_tensor_impl(ov::Tensor(output.get_element_type(), output.get_shape())));
+ ov::ISyncInferRequest::set_tensor(
+ output,
+ ov::get_tensor_impl(ov::Tensor(output.get_element_type(), output.get_shape())));
}
}
@@ -362,8 +389,10 @@ protected:
saw_aux = saw_aux || name.find("scale") != std::string::npos || name.find("zp") != std::string::npos;
auto src = LLMVariantSwitchTestAccess::kvcache_request(req)->get_tensor(
LLMVariantSwitchTestAccess::kvcache_in_ports(req).at(name));
- auto src_slice = ov::npuw::util::make_tensor_slice(
- src, LLMVariantSwitchTestAccess::kv_dim_for_name(req, name), 0u, stored_tokens);
+ auto src_slice = ov::npuw::util::make_tensor_slice(src,
+ LLMVariantSwitchTestAccess::kv_dim_for_name(req, name),
+ 0u,
+ stored_tokens);
fill_tensor_pattern(src_slice, seed);
expected_kv_bytes.emplace(name, materialize_bytes(src_slice));
seed = static_cast<uint8_t>(seed + 37u);
@@ -378,8 +407,10 @@ protected:
for (const auto& name : LLMVariantSwitchTestAccess::kvcache_past_names(req)) {
auto dst = LLMVariantSwitchTestAccess::kvcache_request(req)->get_tensor(
LLMVariantSwitchTestAccess::kvcache_in_ports(req).at(name));
- auto dst_slice = ov::npuw::util::make_tensor_slice(
- dst, LLMVariantSwitchTestAccess::kv_dim_for_name(req, name), 0u, stored_tokens);
+ auto dst_slice = ov::npuw::util::make_tensor_slice(dst,
+ LLMVariantSwitchTestAccess::kv_dim_for_name(req, name),
+ 0u,
+ stored_tokens);
EXPECT_EQ(materialize_bytes(dst_slice), expected_kv_bytes.at(name)) << name;
}
}
@@ -406,11 +437,11 @@ TEST_F(LLMInferRequestVariantSwitchTest, BlockKvVariantsExposeCompatibleBindings
ASSERT_NE(compiled, nullptr);
ASSERT_EQ(LLMVariantSwitchTestAccess::generate_variant_count(compiled), 2u);
ASSERT_TRUE(LLMVariantSwitchTestAccess::is_block_kv_cache(compiled));
- auto small_variant = std::dynamic_pointer_cast<FakeSubCompiledModel>(
- LLMVariantSwitchTestAccess::generate_variant(compiled, 0u));
- auto large_variant = std::dynamic_pointer_cast<FakeSubCompiledModel>(
- LLMVariantSwitchTestAccess::generate_variant(compiled,
- LLMVariantSwitchTestAccess::generate_variant_count(compiled) - 1u));
+ auto small_variant =
+ std::dynamic_pointer_cast<FakeSubCompiledModel>(LLMVariantSwitchTestAccess::generate_variant(compiled, 0u));
+ auto large_variant = std::dynamic_pointer_cast<FakeSubCompiledModel>(LLMVariantSwitchTestAccess::generate_variant(
+ compiled,
+ LLMVariantSwitchTestAccess::generate_variant_count(compiled) - 1u));
ASSERT_NE(small_variant, nullptr);
ASSERT_NE(large_variant, nullptr);
@@ -568,4 +599,55 @@ TEST_F(LLMInferRequestVariantSwitchTest, RejectsImportedKvcacheDimOutOfPrefillTe
EXPECT_THROW(LLMVariantSwitchTestAccess::validate_imported_kvcache_dim(compiled), ov::Exception);
}
+// m_prefill_other_outs_seqdims is keyed by prefill output ports, which can't be serialized
+// directly. serialize() exports the table by tensor name and deserialize() rebuilds the port keys
+// against the restored prefill model. This pins that name<->port round-trip through the real
+// production helpers.
+TEST_F(LLMInferRequestVariantSwitchTest, PrefillOtherOutsSeqDimTableRebuildsAgainstPrefillModel) {
+ VariantSwitchFactory factory;
+ auto compiled = create_compiled_model({}, factory);
+ ASSERT_NE(compiled, nullptr);
+
+ auto prefill = LLMVariantSwitchTestAccess::prefill_compiled(compiled);
+ ASSERT_NE(prefill, nullptr);
+ const auto& prefill_outs = prefill->outputs();
+ ASSERT_FALSE(prefill_outs.empty());
+
+ std::map<ov::Output<const ov::Node>, std::size_t> original;
+ std::size_t seqdim = 1u;
+ for (const auto& out : prefill_outs) {
+ original.emplace(out, seqdim++);
+ }
+ LLMVariantSwitchTestAccess::set_prefill_other_outs_to_seqdims(compiled, original);
+
+ // serialize side: the table is reduced to tensor names.
+ const auto by_name = LLMVariantSwitchTestAccess::serialize_prefill_other_outs_seqdims(compiled);
+ ASSERT_EQ(by_name.size(), original.size());
+
+ // deserialize side: rebuild the port keys from the restored prefill model.
+ LLMVariantSwitchTestAccess::set_prefill_other_outs_to_seqdims(compiled, {});
+ LLMVariantSwitchTestAccess::deserialize_prefill_other_outs_seqdims(compiled, by_name);
+
+ const auto& restored = LLMVariantSwitchTestAccess::prefill_other_outs_to_seqdims(compiled);
+ ASSERT_EQ(restored.size(), original.size());
+ for (const auto& [port, dim] : original) {
+ auto it = restored.find(port);
+ ASSERT_NE(it, restored.end()) << "Missing port " << port.get_any_name() << " after round-trip";
+ EXPECT_EQ(it->second, dim) << port.get_any_name();
+ }
+}
+
+// A seq-dim table entry naming a tensor absent from the prefill model must fault loudly instead of
+// silently dropping the output.
+TEST_F(LLMInferRequestVariantSwitchTest, PrefillOtherOutsSeqDimRejectsUnknownTensorName) {
+ VariantSwitchFactory factory;
+ auto compiled = create_compiled_model({}, factory);
+ ASSERT_NE(compiled, nullptr);
+
+ EXPECT_THROW(
+ LLMVariantSwitchTestAccess::deserialize_prefill_other_outs_seqdims(compiled,
+ {{"does_not_exist_in_prefill", 2u}}),
+ ov::Exception);
+}
+
} // namespace
diff --git a/src/plugins/intel_npu/tests/unit/npuw/partitioning_options_test.cpp b/src/plugins/intel_npu/tests/unit/npuw/partitioning_options_test.cpp
index f8eba7c76f2..240e9b5b668 100644
--- a/src/plugins/intel_npu/tests/unit/npuw/partitioning_options_test.cpp
+++ b/src/plugins/intel_npu/tests/unit/npuw/partitioning_options_test.cpp
@@ -23,8 +23,8 @@
#include "partitioning/partitioning.hpp"
#include "pyramid_attention.hpp"
-using ov::test::npuw::ModelBuilder;
using ov::test::npuw::LLMConfig;
+using ov::test::npuw::ModelBuilder;
namespace {
@@ -405,9 +405,10 @@ TEST(PartitioningOptionsTest, FuncallForAllPromotesUnaryGroupsToFunctions) {
auto cfg = make_cfg({{"NPUW_ONLINE_PIPELINE", "NONE"}, {"NPUW_FUNCALL_FOR_ALL", "YES"}});
auto partitioning = ov::npuw::getPartitioning(build_unary_chain_model(), cfg);
- EXPECT_TRUE(std::any_of(partitioning.subgraphs.begin(), partitioning.subgraphs.end(), [](const ov::npuw::Subgraph& sg) {
- return sg._forced_to_fcall || !sg._funcall.empty() || !sg._repeated_id.empty();
- }));
+ EXPECT_TRUE(
+ std::any_of(partitioning.subgraphs.begin(), partitioning.subgraphs.end(), [](const ov::npuw::Subgraph& sg) {
+ return sg._forced_to_fcall || !sg._funcall.empty() || !sg._repeated_id.empty();
+ }));
}
TEST(PartitioningOptionsTest, OptimizedOutForcedFunctionsAreNotMaterialized) {
@@ -443,9 +444,10 @@ TEST(PartitioningOptionsTest, FoldCreatesFunctionCallsForRepeatedBlocks) {
auto partitioning = ov::npuw::getPartitioning(build_repeated_model(10), cfg);
EXPECT_FALSE(partitioning.functions.empty());
- EXPECT_TRUE(std::any_of(partitioning.subgraphs.begin(), partitioning.subgraphs.end(), [](const ov::npuw::Subgraph& sg) {
- return !sg._funcall.empty();
- }));
+ EXPECT_TRUE(
+ std::any_of(partitioning.subgraphs.begin(), partitioning.subgraphs.end(), [](const ov::npuw::Subgraph& sg) {
+ return !sg._funcall.empty();
+ }));
}
TEST(PartitioningOptionsTest, CwaiCreatesFunctionCallsForRepeatedBlocks) {
@@ -453,9 +455,10 @@ TEST(PartitioningOptionsTest, CwaiCreatesFunctionCallsForRepeatedBlocks) {
auto partitioning = ov::npuw::getPartitioning(build_repeated_model(10), cfg);
EXPECT_FALSE(partitioning.functions.empty());
- EXPECT_TRUE(std::any_of(partitioning.subgraphs.begin(), partitioning.subgraphs.end(), [](const ov::npuw::Subgraph& sg) {
- return !sg._funcall.empty();
- }));
+ EXPECT_TRUE(
+ std::any_of(partitioning.subgraphs.begin(), partitioning.subgraphs.end(), [](const ov::npuw::Subgraph& sg) {
+ return !sg._funcall.empty();
+ }));
}
TEST(PartitioningOptionsTest, FoldOnlyProcessesTaggedRepeatedFamiliesWithoutCwai) {
@@ -468,9 +471,10 @@ TEST(PartitioningOptionsTest, FoldOnlyProcessesTaggedRepeatedFamiliesWithoutCwai
auto partitioning = ov::npuw::getPartitioning(build_static_attention_llm_model(), cfg);
EXPECT_FALSE(partitioning.functions.empty());
- EXPECT_TRUE(std::any_of(partitioning.subgraphs.begin(), partitioning.subgraphs.end(), [](const ov::npuw::Subgraph& sg) {
- return !sg._funcall.empty();
- }));
+ EXPECT_TRUE(
+ std::any_of(partitioning.subgraphs.begin(), partitioning.subgraphs.end(), [](const ov::npuw::Subgraph& sg) {
+ return !sg._funcall.empty();
+ }));
}
TEST(PartitioningOptionsTest, FoldOnlyAndCwaiProcessTaggedAndUntaggedRepeatedFamilies) {
@@ -488,9 +492,10 @@ TEST(PartitioningOptionsTest, FoldOnlyAndCwaiProcessTaggedAndUntaggedRepeatedFam
auto mixed_cfg_obj = make_cfg(mixed_cfg);
auto mixed_partitioning = ov::npuw::getPartitioning(build_static_attention_mixed_llm_model(), mixed_cfg_obj);
- EXPECT_TRUE(std::any_of(mixed_partitioning.functions.begin(), mixed_partitioning.functions.end(), [](const auto& func) {
- return func.second.gettag() == "attn";
- }));
+ EXPECT_TRUE(
+ std::any_of(mixed_partitioning.functions.begin(), mixed_partitioning.functions.end(), [](const auto& func) {
+ return func.second.gettag() == "attn";
+ }));
const auto has_cwai_function = [](const ov::npuw::Partitioning& partitioning) {
return std::any_of(partitioning.functions.begin(), partitioning.functions.end(), [](const auto& func) {
@@ -498,9 +503,11 @@ TEST(PartitioningOptionsTest, FoldOnlyAndCwaiProcessTaggedAndUntaggedRepeatedFam
});
};
const auto has_cwai_funcall = [](const ov::npuw::Partitioning& partitioning) {
- return std::any_of(partitioning.subgraphs.begin(), partitioning.subgraphs.end(), [](const ov::npuw::Subgraph& sg) {
- return sg._funcall.find("__") != std::string::npos;
- });
+ return std::any_of(partitioning.subgraphs.begin(),
+ partitioning.subgraphs.end(),
+ [](const ov::npuw::Subgraph& sg) {
+ return sg._funcall.find("__") != std::string::npos;
+ });
};
EXPECT_FALSE(has_cwai_function(fold_only_partitioning));
@@ -545,11 +552,10 @@ TEST(PartitioningOptionsTest, FoldOnlyWithIsolatedTagsProducesExpectedSubgraphCo
EXPECT_EQ(partitioning.subgraphs.size(), 3u * N);
- std::size_t folded = std::count_if(partitioning.subgraphs.begin(),
- partitioning.subgraphs.end(),
- [](const ov::npuw::Subgraph& sg) {
- return !sg._funcall.empty();
- });
+ std::size_t folded =
+ std::count_if(partitioning.subgraphs.begin(), partitioning.subgraphs.end(), [](const ov::npuw::Subgraph& sg) {
+ return !sg._funcall.empty();
+ });
EXPECT_EQ(folded, N);
}
@@ -566,11 +572,10 @@ TEST(PartitioningOptionsTest, OnlyAttnIsolatedFamiliesIgnoreKeepBlockSizeThresho
EXPECT_EQ(partitioning.subgraphs.size(), 2u * N);
- std::size_t folded = std::count_if(partitioning.subgraphs.begin(),
- partitioning.subgraphs.end(),
- [](const ov::npuw::Subgraph& sg) {
- return !sg._funcall.empty();
- });
+ std::size_t folded =
+ std::count_if(partitioning.subgraphs.begin(), partitioning.subgraphs.end(), [](const ov::npuw::Subgraph& sg) {
+ return !sg._funcall.empty();
+ });
EXPECT_EQ(folded, N);
}
@@ -675,11 +680,10 @@ TEST(PartitioningOptionsTest, FuseUnfoldedMergesNonFoldOnlyRepeatedBlocks) {
EXPECT_EQ(partitioning.subgraphs.size(), 2u * N);
- std::size_t folded = std::count_if(partitioning.subgraphs.begin(),
- partitioning.subgraphs.end(),
- [](const ov::npuw::Subgraph& sg) {
- return !sg._funcall.empty();
- });
+ std::size_t folded =
+ std::count_if(partitioning.subgraphs.begin(), partitioning.subgraphs.end(), [](const ov::npuw::Subgraph& sg) {
+ return !sg._funcall.empty();
+ });
EXPECT_EQ(folded, N);
}
diff --git a/src/plugins/intel_npu/tests/unit/npuw/pipeline_passes/cut_lm_head_test.cpp b/src/plugins/intel_npu/tests/unit/npuw/pipeline_passes/cut_lm_head_test.cpp
new file mode 100644
index 00000000000..418eefee4fa
--- /dev/null
+++ b/src/plugins/intel_npu/tests/unit/npuw/pipeline_passes/cut_lm_head_test.cpp
@@ -0,0 +1,171 @@
+// Copyright (C) 2018-2026 Intel Corporation
+// SPDX-License-Identifier: Apache-2.0
+//
+
+#include "npuw_transformations/cut_lm_head.hpp"
+
+#include <gtest/gtest.h>
+
+#include <memory>
+#include <string>
+#include <vector>
+
+#include "llm_compiled_model.hpp"
+#include "openvino/op/constant.hpp"
+#include "openvino/op/convert.hpp"
+#include "openvino/op/matmul.hpp"
+#include "openvino/op/parameter.hpp"
+#include "openvino/op/result.hpp"
+
+namespace {
+
+using ov::npuw::LLMCompiledModel;
+
+constexpr int64_t kSeq = 8;
+constexpr int64_t kHidden = 16;
+constexpr int64_t kVocab = 32;
+
+std::shared_ptr<ov::op::v0::Constant> make_weights() {
+ return ov::op::v0::Constant::create(ov::element::f32,
+ ov::Shape{static_cast<size_t>(kHidden), static_cast<size_t>(kVocab)},
+ std::vector<float>(kHidden * kVocab, 0.0f));
+}
+
+// Parameter(hidden) -> MatMul(hidden, weights) -> Result("logits").
+std::shared_ptr<ov::Model> build_simple_lm_head_model() {
+ auto hidden = std::make_shared<ov::op::v0::Parameter>(ov::element::f32, ov::PartialShape{1, kSeq, kHidden});
+ hidden->set_friendly_name("hidden");
+ hidden->output(0).set_names({"hidden"});
+
+ auto matmul = std::make_shared<ov::op::v0::MatMul>(hidden, make_weights());
+ auto result = std::make_shared<ov::op::v0::Result>(matmul);
+ result->set_friendly_name("logits");
+ result->output(0).set_names({LLMCompiledModel::layer_names::logits});
+
+ return std::make_shared<ov::Model>(ov::ResultVector{result}, ov::ParameterVector{hidden}, "simple_lm_head");
+}
+
+// Same, but hidden also feeds a second Result ("last_hidden_state"); mimics the
+// OmniThinker case where the pre-head embeddings are already a model output.
+std::shared_ptr<ov::Model> build_attached_result_model() {
+ auto hidden = std::make_shared<ov::op::v0::Parameter>(ov::element::f32, ov::PartialShape{1, kSeq, kHidden});
+ hidden->set_friendly_name("hidden");
+ hidden->output(0).set_names({"hidden"});
+
+ auto hidden_result = std::make_shared<ov::op::v0::Result>(hidden);
+ hidden_result->set_friendly_name("last_hidden_state");
+ hidden_result->output(0).set_names({"last_hidden_state"});
+
+ auto matmul = std::make_shared<ov::op::v0::MatMul>(hidden, make_weights());
+ auto logits_result = std::make_shared<ov::op::v0::Result>(matmul);
+ logits_result->set_friendly_name("logits");
+ logits_result->output(0).set_names({LLMCompiledModel::layer_names::logits});
+
+ return std::make_shared<ov::Model>(ov::ResultVector{hidden_result, logits_result},
+ ov::ParameterVector{hidden},
+ "attached_result_lm_head");
+}
+
+std::shared_ptr<ov::op::v0::Result> find_result_by_name(const std::shared_ptr<ov::Model>& model,
+ const std::string& name) {
+ for (const auto& r : model->get_results()) {
+ if (r->output(0).get_names().count(name)) {
+ return r;
+ }
+ }
+ return nullptr;
+}
+
+} // namespace
+
+// --- Test 1 -------------------------------------------------------------------
+// Basic cut: no Result attached at the MatMul input source. The logits Result is
+// repurposed as the output-embeddings Result, and the LM head MatMul is moved
+// into a dedicated sub-model.
+TEST(CutLMHeadTest, BasicCut) {
+ auto model = build_simple_lm_head_model();
+ ASSERT_EQ(model->get_results().size(), 1u);
+
+ std::shared_ptr<ov::Model> lm_head_model;
+ const bool changed = ov::npuw::CutLMHead(lm_head_model).run_on_model(model);
+
+ EXPECT_TRUE(changed);
+ ASSERT_NE(lm_head_model, nullptr);
+
+ // Original model: the logits Result is renamed to output_embeds and now reads
+ // directly from the hidden Parameter (the MatMul moved to the LM head sub-model).
+ ASSERT_EQ(model->get_results().size(), 1u);
+ const auto embeds = find_result_by_name(model, LLMCompiledModel::layer_names::output_embeds);
+ ASSERT_NE(embeds, nullptr);
+ EXPECT_EQ(embeds->output(0).get_names().count(LLMCompiledModel::layer_names::logits), 0u);
+ EXPECT_EQ(embeds->input_value(0).get_node(), model->get_parameters().front().get());
+
+ // LM head sub-model: single Parameter (named output_embeds) feeding the LM head MatMul.
+ ASSERT_EQ(lm_head_model->get_parameters().size(), 1u);
+ ASSERT_EQ(lm_head_model->get_results().size(), 1u);
+ const auto& head_param = lm_head_model->get_parameters().front();
+ EXPECT_GT(head_param->output(0).get_names().count(LLMCompiledModel::layer_names::output_embeds), 0u);
+}
+
+// --- Test 2 -------------------------------------------------------------------
+// Attached-Result case: a Result already exists on the MatMul input source (the
+// OmniThinker pre-head embeddings output). The pass repurposes the matched logits
+// Result as the output-embeddings Result and keeps the pre-existing Result. To keep
+// the two outputs distinct, the embeddings Result reads a pass-through Convert while
+// the pre-existing Result keeps reading the shared producer directly.
+TEST(CutLMHeadTest, AttachedResultKeepsBothOutputs) {
+ auto model = build_attached_result_model();
+ ASSERT_EQ(model->get_results().size(), 2u);
+
+ std::shared_ptr<ov::Model> lm_head_model;
+ const bool changed = ov::npuw::CutLMHead(lm_head_model).run_on_model(model);
+
+ EXPECT_TRUE(changed);
+ ASSERT_NE(lm_head_model, nullptr);
+
+ // Original model: the pre-existing Result stays and the logits Result is repurposed
+ // as the output-embeddings Result; logits is gone.
+ ASSERT_EQ(model->get_results().size(), 2u);
+ const auto hidden_result = find_result_by_name(model, "last_hidden_state");
+ const auto embeds_result = find_result_by_name(model, LLMCompiledModel::layer_names::output_embeds);
+ ASSERT_NE(hidden_result, nullptr);
+ ASSERT_NE(embeds_result, nullptr);
+ EXPECT_EQ(find_result_by_name(model, LLMCompiledModel::layer_names::logits), nullptr);
+
+ const auto& hidden_param = model->get_parameters().front();
+ // The pre-existing Result keeps reading the shared producer directly.
+ EXPECT_EQ(hidden_result->input_value(0).get_node(), hidden_param.get());
+ // The embeddings Result reads a distinct pass-through Convert over the same producer.
+ const auto embeds_src = embeds_result->input_value(0).get_node_shared_ptr();
+ EXPECT_NE(embeds_src.get(), hidden_param.get());
+ const auto embeds_convert = ov::as_type_ptr<ov::op::v0::Convert>(embeds_src);
+ ASSERT_NE(embeds_convert, nullptr);
+ EXPECT_EQ(embeds_convert->input_value(0).get_node(), hidden_param.get());
+
+ // LM head sub-model: single Parameter feeding the LM head MatMul.
+ ASSERT_EQ(lm_head_model->get_parameters().size(), 1u);
+ ASSERT_EQ(lm_head_model->get_results().size(), 1u);
+}
+
+// --- Test 3 -------------------------------------------------------------------
+// A model without a logits Result must not be touched; lm_head_model stays null.
+TEST(CutLMHeadTest, NoLogitsIsUntouched) {
+ auto hidden = std::make_shared<ov::op::v0::Parameter>(ov::element::f32, ov::PartialShape{1, kSeq, kHidden});
+ hidden->set_friendly_name("hidden");
+ hidden->output(0).set_names({"hidden"});
+
+ auto matmul = std::make_shared<ov::op::v0::MatMul>(hidden, make_weights());
+ auto result = std::make_shared<ov::op::v0::Result>(matmul);
+ result->set_friendly_name("not_logits");
+ result->output(0).set_names({"not_logits"});
+
+ auto model = std::make_shared<ov::Model>(ov::ResultVector{result}, ov::ParameterVector{hidden}, "no_logits_model");
+
+ std::shared_ptr<ov::Model> lm_head_model;
+ const bool changed = ov::npuw::CutLMHead(lm_head_model).run_on_model(model);
+
+ EXPECT_FALSE(changed);
+ EXPECT_EQ(lm_head_model, nullptr);
+ ASSERT_EQ(model->get_results().size(), 1u);
+ EXPECT_EQ(find_result_by_name(model, "not_logits"), result);
+}
diff --git a/src/plugins/intel_npu/tests/unit/npuw/pipeline_passes/slice_out_embeds_test.cpp b/src/plugins/intel_npu/tests/unit/npuw/pipeline_passes/slice_out_embeds_test.cpp
index 048c9a64da2..1907b443a90 100644
--- a/src/plugins/intel_npu/tests/unit/npuw/pipeline_passes/slice_out_embeds_test.cpp
+++ b/src/plugins/intel_npu/tests/unit/npuw/pipeline_passes/slice_out_embeds_test.cpp
@@ -21,7 +21,7 @@ protected:
static bool output_embeds_has_slice_producer(const std::shared_ptr<ov::Model>& model) {
for (const auto& output : model->outputs()) {
for (const auto& name : output.get_names()) {
- if (name.find(ov::npuw::LLMCompiledModel::output_embeds) != std::string::npos) {
+ if (name.find(ov::npuw::LLMCompiledModel::layer_names::output_embeds) != std::string::npos) {
// output is an Output<const Node> over the Result node
auto result_node = output.get_node_shared_ptr();
if (!result_node || result_node->inputs().empty())
@@ -54,7 +54,7 @@ TEST_F(SliceOutEmbedsPassTest, SliceIsInsertedWhenGenerationTokenLenIsLessThanPr
(void)lm_head; // asserted to exist; contents checked by reshape_sliced_head tests
// output_embeds must exist on the prefill model
- const auto embeds = find_output(prefill.model, ov::npuw::LLMCompiledModel::output_embeds);
+ const auto embeds = find_output(prefill.model, ov::npuw::LLMCompiledModel::layer_names::output_embeds);
ASSERT_TRUE(embeds.has_value()) << "output_embeds output not found on prefill model";
// Shape must be static and trimmed to generation token length
@@ -83,7 +83,7 @@ TEST_F(SliceOutEmbedsPassTest, SliceIsNotInsertedWhenGenerationTokenLenEqualsPro
const auto& prefill = require_sub_model(recorder, "_prefill");
// output_embeds must still be exported
- const auto embeds = find_output(prefill.model, ov::npuw::LLMCompiledModel::output_embeds);
+ const auto embeds = find_output(prefill.model, ov::npuw::LLMCompiledModel::layer_names::output_embeds);
ASSERT_TRUE(embeds.has_value()) << "output_embeds output not found on prefill model";
// Shape should be the full prompt-length shape, unmodified
@@ -115,7 +115,7 @@ TEST_F(SliceOutEmbedsPassTest, SliceNotAppliedWhenNoSharedHead) {
// prefill model must not export output_embeds
const auto& prefill = require_sub_model(recorder, "_prefill");
- const auto embeds = find_output(prefill.model, ov::npuw::LLMCompiledModel::output_embeds);
+ const auto embeds = find_output(prefill.model, ov::npuw::LLMCompiledModel::layer_names::output_embeds);
EXPECT_FALSE(embeds.has_value())
<< "output_embeds output should not exist in the prefill model when SHARED_HEAD=NO";
}