Skip to content

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

NPUW: Three-model pipeline (#31460)

Anastasiya(Asya) Pronina9813b4e5b579
diff --git a/src/plugins/intel_npu/src/al/include/intel_npu/config/npuw.hpp b/src/plugins/intel_npu/src/al/include/intel_npu/config/npuw.hpp
index c17376f2eb7..efd5975095d 100644
--- a/src/plugins/intel_npu/src/al/include/intel_npu/config/npuw.hpp
+++ b/src/plugins/intel_npu/src/al/include/intel_npu/config/npuw.hpp
@@ -111,6 +111,7 @@ DEFINE_OPT(NPUW_LLM_MAX_PROMPT_LEN, uint32_t, 1024, npuw::llm::max_prompt_len, R
DEFINE_OPT(NPUW_LLM_MIN_RESPONSE_LEN, uint32_t, 128, npuw::llm::min_response_len, RunTime);
DEFINE_OPT(NPUW_LLM_OPTIMIZE_V_TENSORS, bool, true, npuw::llm::optimize_v_tensors, RunTime);
DEFINE_OPT(NPUW_LLM_PREFILL_CHUNK_SIZE, uint64_t, 0, npuw::llm::prefill_chunk_size, RunTime);
+DEFINE_OPT(NPUW_LLM_SHARED_HEAD, bool, false, npuw::llm::shared_lm_head, CompileTime);
namespace npuw {
namespace llm {
diff --git a/src/plugins/intel_npu/src/al/include/intel_npu/npuw_private_properties.hpp b/src/plugins/intel_npu/src/al/include/intel_npu/npuw_private_properties.hpp
index 54db62b46d3..51e0ecfb3ee 100644
--- a/src/plugins/intel_npu/src/al/include/intel_npu/npuw_private_properties.hpp
+++ b/src/plugins/intel_npu/src/al/include/intel_npu/npuw_private_properties.hpp
@@ -439,6 +439,15 @@ static constexpr ov::Property<uint32_t> max_prompt_len{"NPUW_LLM_MAX_PROMPT_LEN"
*/
static constexpr ov::Property<uint32_t> min_response_len{"NPUW_LLM_MIN_RESPONSE_LEN"};
+/**
+ * @brief
+ * FIXME: Should be removed.
+ * Type: bool.
+ * Tell NPUW to apply values transpose optimization for the model.
+ * Default value: false.
+ */
+static constexpr ov::Property<bool> optimize_v_tensors{"NPUW_LLM_OPTIMIZE_V_TENSORS"};
+
/**
* @brief
* Type: uint64_t.
@@ -449,15 +458,6 @@ static constexpr ov::Property<uint32_t> min_response_len{"NPUW_LLM_MIN_RESPONSE_
*/
static constexpr ov::Property<uint64_t> prefill_chunk_size{"NPUW_LLM_PREFILL_CHUNK_SIZE"};
-/**
- * @brief
- * FIXME: Should be removed.
- * Type: bool.
- * Tell NPUW to apply values transpose optimization for the model.
- * Default value: false.
- */
-static constexpr ov::Property<bool> optimize_v_tensors{"NPUW_LLM_OPTIMIZE_V_TENSORS"};
-
/**
* @brief
* Type: std::string.
@@ -471,11 +471,24 @@ static constexpr ov::Property<std::string> prefill_hint{"NPUW_LLM_PREFILL_HINT"}
/**
* @brief
* Type: ov::AnyMap.
- * Configuration for compilation of prefill model.
+ * Configuration for compilation/execution of prefill model. If specified, it will override default
+ * config, prepared by NPUW specifically for this model.
+ *
* NOTE: !! Write-only !!
*/
static constexpr ov::Property<ov::AnyMap> prefill_config{"NPUW_LLM_PREFILL_CONFIG"};
+/**
+ * @brief
+ * Type: ov::AnyMap.
+ * Additional configuration for compilation/execution of prefill model. If specified, it
+ * will be appended to the default configuration, prepared by NPUW.
+ * For duplicated options, preference will be given to values from given map.
+ *
+ * NOTE: !! Write-only !!
+ */
+static constexpr ov::Property<ov::AnyMap> additional_prefill_config{"++NPUW_LLM_PREFILL_CONFIG"};
+
/**
* @brief
* Type: std::string.
@@ -489,10 +502,53 @@ static constexpr ov::Property<std::string> generate_hint{"NPUW_LLM_GENERATE_HINT
/**
* @brief
* Type: ov::AnyMap.
- * Configuration for compilation of generate model.
+ * Configuration for compilation/execution of generate model. If specified, it will override default
+ * config, prepared by NPUW specifically for this model.
+ *
* NOTE: !! Write-only !!
*/
static constexpr ov::Property<ov::AnyMap> generate_config{"NPUW_LLM_GENERATE_CONFIG"};
+
+/**
+ * @brief
+ * Type: ov::AnyMap.
+ * Configuration for compilation/execution of generate model. If specified, it
+ * will be appended to the default configuration, prepared by NPUW.
+ * For duplicated options, preference will be given to values from given map.
+ *
+ * NOTE: !! Write-only !!
+ */
+static constexpr ov::Property<ov::AnyMap> additional_generate_config{"++NPUW_LLM_GENERATE_CONFIG"};
+
+/**
+ * @brief
+ * Type: bool.
+ * Tell NPUW to separate LM head into the 3rd model, that will be shared between
+ * prefill and generate.
+ * Default value: false.
+ */
+static constexpr ov::Property<bool> shared_lm_head{"NPUW_LLM_SHARED_HEAD"};
+
+/**
+ * @brief
+ * Type: ov::AnyMap.
+ * Configuration for compilation/execution of shared LM head model. If specified, it will override
+ * default config, prepared by NPUW specifically for this model.
+ *
+ * NOTE: !! Write-only !!
+ */
+static constexpr ov::Property<ov::AnyMap> shared_lm_head_config{"NPUW_LLM_SHARED_HEAD_CONFIG"};
+
+/**
+ * @brief
+ * Type: ov::AnyMap.
+ * Configuration for compilation/execution of shared LM head model. If specified, it
+ * will be appended to the default configuration, prepared by NPUW.
+ * For duplicated options, preference will be given to values from given map.
+ *
+ * NOTE: !! Write-only !!
+ */
+static constexpr ov::Property<ov::AnyMap> additional_shared_lm_head_config{"++NPUW_LLM_SHARED_HEAD_CONFIG"};
} // namespace llm
} // namespace npuw
diff --git a/src/plugins/intel_npu/src/al/src/config/npuw.cpp b/src/plugins/intel_npu/src/al/src/config/npuw.cpp
index 11986a28b6a..cd7131cc238 100644
--- a/src/plugins/intel_npu/src/al/src/config/npuw.cpp
+++ b/src/plugins/intel_npu/src/al/src/config/npuw.cpp
@@ -63,10 +63,11 @@ void intel_npu::registerNPUWLLMOptions(OptionsDesc& desc) {
desc.add<NPUW_LLM_SEQ_LEN_DIM>();
desc.add<NPUW_LLM_MAX_PROMPT_LEN>();
desc.add<NPUW_LLM_MIN_RESPONSE_LEN>();
- desc.add<NPUW_LLM_PREFILL_CHUNK_SIZE>();
desc.add<NPUW_LLM_OPTIMIZE_V_TENSORS>();
+ desc.add<NPUW_LLM_PREFILL_CHUNK_SIZE>();
desc.add<NPUW_LLM_PREFILL_HINT>();
desc.add<NPUW_LLM_GENERATE_HINT>();
+ desc.add<NPUW_LLM_SHARED_HEAD>();
}
std::string ov::npuw::s11n::anyToString(const ov::Any& var) {
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 1437c0dbec8..a96e594e948 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
@@ -12,6 +12,7 @@
#include "openvino/pass/graph_rewrite.hpp"
#include "openvino/pass/matcher_pass.hpp"
#include "openvino/pass/pattern/op/optional.hpp"
+#include "openvino/pass/pattern/op/or.hpp"
#include "openvino/pass/pattern/op/wrap_type.hpp"
#include "openvino/pass/stateful_to_stateless.hpp"
#include "openvino/pass/validate.hpp"
@@ -646,6 +647,95 @@ struct KVAxesPosition {
uint32_t batch;
uint32_t seq_len;
};
+} // anonymous namespace
+
+class CutLMHead : public ov::pass::MatcherPass {
+public:
+ OPENVINO_MATCHER_PASS_RTTI("npuw::patterns::CutLMHead");
+ 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<ov::pass::pattern::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](ov::pass::pattern::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);
+
+ // 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},
+ "NPUW_LMHead");
+
+ return true;
+ };
+ register_matcher(std::make_shared<opp::Matcher>(res, "CutLMHead"), std::move(callback));
+ }
+};
+
+namespace {
+std::shared_ptr<ov::Model> cut_lm_head(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);
+ model->validate_nodes_and_infer_types();
+
+ return lm_head_model;
+}
void reshape_to_static(std::shared_ptr<ov::Model> model,
const uint32_t input_size,
@@ -683,6 +773,68 @@ void reshape_to_static(std::shared_ptr<ov::Model> model,
model->reshape(new_shapes);
}
+void reshape_sliced_head_to_static(std::shared_ptr<ov::Model> lm_head_model, const uint32_t& batch_dim) {
+ // We have only one input with dynamic shapes: output of Slice operation, and this output
+ // should have "1" for dimension representing number of embeddings to send to the matmul.
+ // Batch size should be also equal "1" for NPU.
+ const auto& input = lm_head_model->input(0);
+ const auto& partial_shape = input.get_partial_shape();
+ NPUW_ASSERT(partial_shape.size() == 3);
+
+ ov::PartialShape new_shape = partial_shape;
+ new_shape[batch_dim] = 1;
+ // Left dynamic axis will be for number of embeddings
+ for (auto i = 0; i < new_shape.rank().get_length(); i++) {
+ if (new_shape[i].is_dynamic()) {
+ new_shape[i] = 1;
+ // Sanity check that only one left dimension is dynamic, as
+ // another one should contain embedding space rank
+ break;
+ }
+ }
+
+ lm_head_model->reshape(new_shape);
+}
+
+void slice_out_embeds(std::shared_ptr<ov::Model> model, const uint32_t& batch_dim) {
+ std::shared_ptr<ov::Node> embed_result;
+ for (auto&& output : model->outputs()) {
+ if (output.get_any_name() == ov::npuw::LLMCompiledModel::output_embeds) {
+ embed_result = output.get_node_shared_ptr();
+ }
+ }
+
+ if (embed_result) {
+ auto shape = embed_result->input(0).get_shape();
+ // If shape.size() is 3, then last axis should be the Vocab size.
+ // But 1st and 2nd axis can mean different things.
+ // 1st axis can represent the batch size, while 2nd - the number of embeddings,
+ // or vice-versa (in chatglm)
+ if (shape.size() == 3) {
+ uint32_t num_embeds_dim = 1 - batch_dim;
+ if (shape[num_embeds_dim] > 1) {
+ std::vector<int32_t> start_pos{static_cast<int32_t>(batch_dim * (shape[num_embeds_dim] - 1)),
+ static_cast<int32_t>(num_embeds_dim * (shape[num_embeds_dim] - 1)),
+ 0};
+ std::vector<int32_t> stop_pos{static_cast<int32_t>(batch_dim * (shape[num_embeds_dim] - 1)) + 1,
+ static_cast<int32_t>(num_embeds_dim * (shape[num_embeds_dim] - 1)) + 1,
+ static_cast<int32_t>(shape[2])};
+ auto start = std::make_shared<ov::op::v0::Constant>(ov::element::i32, ov::Shape{3}, start_pos);
+ auto stop = std::make_shared<ov::op::v0::Constant>(ov::element::i32, ov::Shape{3}, stop_pos);
+ auto step = std::make_shared<ov::op::v0::Constant>(ov::element::i32,
+ ov::Shape{3},
+ std::vector<int32_t>{1, 1, 1});
+
+ auto slice = std::make_shared<ov::op::v8::Slice>(embed_result->input_value(0), start, stop, step);
+
+ embed_result->input(0).replace_source_output(slice);
+ embed_result->validate_and_infer_types();
+ model->validate_nodes_and_infer_types();
+ }
+ }
+ }
+}
+
bool is_cw_compressed(const std::shared_ptr<ov::Model>& model) {
std::vector<std::string> rt_info_path = {"nncf", "weight_compression", "group_size"};
if (!model->has_rt_info(rt_info_path)) {
@@ -753,7 +905,8 @@ ov::AnyMap get_baseline_common_config(const std::optional<NPUDesc>& npudesc) {
return config;
}
-ov::AnyMap get_default_common_config(const std::shared_ptr<ov::Model>& model, const std::optional<NPUDesc>& npudesc) {
+ov::AnyMap get_default_common_config(const std::optional<NPUDesc>& npudesc) {
+ // FIXME: add `if_model_contain_slice()` condition for `SLICE_OUT` option.
auto config = get_baseline_common_config(npudesc);
const char* npu_l0 = std::getenv("DISABLE_OPENVINO_GENAI_NPU_L0");
if (npu_l0 && std::atoi(npu_l0) == 1) {
@@ -767,7 +920,7 @@ ov::AnyMap get_default_common_config(const std::shared_ptr<ov::Model>& model, co
ov::AnyMap get_default_prefill_config(const std::shared_ptr<ov::Model>& model,
const std::optional<NPUDesc>& npudesc,
const ::intel_npu::npuw::llm::PrefillHint hint) {
- auto config = get_default_common_config(model, npudesc);
+ auto config = get_default_common_config(npudesc);
if (hint == ::intel_npu::npuw::llm::PrefillHint::DYNAMIC) {
if (is_cw_compressed(model)) {
// NB: These two ifs are not combined into one with && deliberately
@@ -789,23 +942,23 @@ ov::AnyMap get_default_prefill_config(const std::shared_ptr<ov::Model>& model,
return config;
}
-ov::AnyMap get_default_generate_config(const std::shared_ptr<ov::Model>& model,
- const std::optional<NPUDesc>& npudesc,
+ov::AnyMap get_default_generate_config(const std::optional<NPUDesc>& npudesc,
const ::intel_npu::npuw::llm::GenerateHint hint) {
- auto config = get_default_common_config(model, npudesc);
+ auto config = get_default_common_config(npudesc);
if (hint == ::intel_npu::npuw::llm::GenerateHint::BEST_PERF) {
config.emplace("NPUW_ONLINE_PIPELINE", "NONE");
}
- if (npudesc.has_value() && npudesc->arch == "4000") {
- config.emplace("NPU_TILES", 4);
- }
if (hint == ::intel_npu::npuw::llm::GenerateHint::FAST_COMPILE) {
config.emplace("NPUW_UNFOLD_IREQS", "YES");
}
- // Specify NPUW DQ if Compiler DQ is not enabled
- if (!npudesc.has_value() || !npudesc->compiler_dq) {
- config.emplace("NPUW_DQ", "YES");
- }
+ return config;
+}
+
+ov::AnyMap get_default_lm_head_config(const std::optional<NPUDesc>& npudesc) {
+ auto config = get_default_common_config(npudesc);
+ config.erase("NPUW_SLICE_OUT");
+ config.erase("NPUW_FUNCALL_ASYNC");
+ config.emplace("NPUW_ONLINE_PIPELINE", "NONE");
return config;
}
@@ -864,19 +1017,38 @@ ov::npuw::LLMCompiledModel::LLMCompiledModel(const std::shared_ptr<ov::Model>& m
auto generate_config_opt = pop_option(npuw_llm_props, std::string("NPUW_LLM_GENERATE_CONFIG"));
auto prefill_config_addition = pop_option(npuw_llm_props, std::string("++NPUW_LLM_PREFILL_CONFIG"));
auto generate_config_addition = pop_option(npuw_llm_props, std::string("++NPUW_LLM_GENERATE_CONFIG"));
+ // Also make these maps for third: lm head model, in case it will be created:
+ auto lm_head_config_opt = pop_option(npuw_llm_props, std::string("NPUW_LLM_SHARED_HEAD_CONFIG"));
+ auto lm_head_config_addition = pop_option(npuw_llm_props, std::string("++NPUW_LLM_SHARED_HEAD_CONFIG"));
m_cfg.update(any_copy(npuw_llm_props));
- LOG_DEBUG("1. Creating kvcache model as clone of passed one.");
+ LOG_DEBUG("Creating kvcache model as clone of passed one.");
auto kvcache_model = model->clone();
- LOG_DEBUG("2. Transform kvcache model from stateful to stateless.");
+ LOG_DEBUG("Transform kvcache model from stateful to stateless.");
ov::pass::StatefulToStateless().run_on_model(kvcache_model);
LOG_DEBUG(" ...also convert BF16 to FP16");
// Note: we need to identify original bf16 constants for potential weightless deserialization later
// And only then do bf16 to f16 transformation
m_bf16_consts = ov::npuw::s11n::get_bf16_consts(model);
ov::pass::ConvertPrecision(ov::element::bf16, ov::element::f16).run_on_model(kvcache_model);
- LOG_DEBUG("3. Creating prefill model as clone of transformed kvcache one.");
+
+ bool shared_head_enabled = m_cfg.get<::intel_npu::NPUW_LLM_SHARED_HEAD>();
+ std::shared_ptr<ov::Model> lm_head_model = nullptr;
+ if (shared_head_enabled) {
+ LOG_DEBUG("Trying to separate Vocabulary matrix multiplication op into additional model...");
+ lm_head_model = cut_lm_head(kvcache_model);
+ if (lm_head_model) {
+ LOG_INFO("Three-model pipeline will be created: LM head will be shared between prefill and generate.");
+ } else {
+ LOG_WARN("Three-model pipeline is requested, but LM head cutting is failed,"
+ " two-model pipeline will be created!");
+ }
+ } else {
+ LOG_INFO("Two-model pipeline will be created.");
+ }
+
+ LOG_DEBUG("Creating prefill model as clone of transformed kvcache one.");
auto prefill_model = kvcache_model->clone();
prefill_model->set_friendly_name(kvcache_model->get_friendly_name() + "_prefill");
@@ -912,7 +1084,7 @@ ov::npuw::LLMCompiledModel::LLMCompiledModel(const std::shared_ptr<ov::Model>& m
}
m_kvcache_desc = KVCacheDesc{max_prompt_len, max_prompt_len + min_response_len, 0u, seq_len_dim};
- LOG_DEBUG("4. Make prefill model with static shapes");
+ LOG_DEBUG("Make prefill model with static shapes");
if (use_chunk_prefill) {
reshape_to_static(prefill_model,
static_cast<uint32_t>(m_prefill_chunk_size),
@@ -921,8 +1093,16 @@ ov::npuw::LLMCompiledModel::LLMCompiledModel(const std::shared_ptr<ov::Model>& m
} else {
reshape_to_static(prefill_model, m_kvcache_desc.max_prompt_size, m_kvcache_desc.max_prompt_size, axes);
}
- LOG_DEBUG("5. Make kvcache model with static shapes");
+ LOG_DEBUG("Make kvcache model with static shapes");
reshape_to_static(kvcache_model, 1u, m_kvcache_desc.total_size, axes);
+ if (lm_head_model) {
+ LOG_DEBUG("Shared LM head: slice the prefill output");
+ // KVCache model is already reshaped to [1, 1, embed size], so only apply slice to
+ // the Prefill model:
+ slice_out_embeds(prefill_model, axes.batch);
+ LOG_DEBUG("Make LM head model with static shapes");
+ reshape_sliced_head_to_static(lm_head_model, axes.batch);
+ }
LOG_DEBUG("5.1, decompose GroupQueryAttention OP");
decompose_GQA(prefill_model, true);
@@ -930,7 +1110,7 @@ ov::npuw::LLMCompiledModel::LLMCompiledModel(const std::shared_ptr<ov::Model>& m
const bool optimize_v_tensors = m_cfg.get<::intel_npu::NPUW_LLM_OPTIMIZE_V_TENSORS>();
if (optimize_v_tensors) {
- LOG_DEBUG("6. Check and apply opt layout");
+ LOG_DEBUG("Check and apply opt layout");
LOG_BLOCK();
if (ov::npuw::util::optimize_value_tensors(kvcache_model, false)) {
NPUW_ASSERT(ov::npuw::util::optimize_value_tensors(prefill_model, true));
@@ -939,19 +1119,22 @@ ov::npuw::LLMCompiledModel::LLMCompiledModel(const std::shared_ptr<ov::Model>& m
LOG_DEBUG("vtensors optimisation not applied");
}
} else {
- LOG_DEBUG("6. Check and apply opt layout --- SKIPPED");
+ LOG_DEBUG("Check and apply opt layout --- SKIPPED");
}
if (!use_chunk_prefill) {
NPUW_ASSERT(remove_empty_kv_inputs(prefill_model));
} else {
+ LOG_DEBUG("Don't remove input key/values from prefill model.");
+ LOG_DEBUG("Ask prefill model to output key/values for prefill chunk size tokens.");
prefill_model = redirect_new_kv_to_output(prefill_model);
}
- LOG_DEBUG("7. Optimize kvcache model to output key/values for new token.");
+
+ LOG_DEBUG("Optimize kvcache model to output key/values for new token.");
kvcache_model = redirect_new_kv_to_output(kvcache_model);
- LOG_DEBUG("8. Converting KV-cache in kvcache model to FP16.");
+ LOG_DEBUG("Converting KV-cache in kvcache model to FP16.");
kvcache_model = cvt_kvcache_to_fp16(kvcache_model);
- LOG_DEBUG("9. Converting KV-cache in prefill model to FP16.");
+ LOG_DEBUG("Converting KV-cache in prefill model to FP16.");
prefill_model = cvt_kvcache_to_fp16(prefill_model);
auto npudesc = extract_npu_descriptor(plugin);
@@ -970,12 +1153,11 @@ ov::npuw::LLMCompiledModel::LLMCompiledModel(const std::shared_ptr<ov::Model>& m
}
const ::intel_npu::npuw::llm::GenerateHint generate_hint = m_cfg.get<::intel_npu::NPUW_LLM_GENERATE_HINT>();
auto generate_config =
- generate_config_opt.value_or(get_default_generate_config(kvcache_model, npudesc, generate_hint))
- .as<ov::AnyMap>();
+ generate_config_opt.value_or(get_default_generate_config(npudesc, generate_hint)).as<ov::AnyMap>();
- const auto& prefill_config_addition_value =
+ auto prefill_config_addition_value =
prefill_config_addition.has_value() ? prefill_config_addition.value().as<ov::AnyMap>() : ov::AnyMap{};
- const auto& generate_config_addition_value =
+ auto generate_config_addition_value =
generate_config_addition.has_value() ? generate_config_addition.value().as<ov::AnyMap>() : ov::AnyMap{};
merge_config_with(prefill_config, other_props);
@@ -991,6 +1173,16 @@ ov::npuw::LLMCompiledModel::LLMCompiledModel(const std::shared_ptr<ov::Model>& m
ov::npuw::ICompiledModel::create(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 (lm_head_model) {
+ auto lm_head_config = get_default_lm_head_config(npudesc);
+ merge_config_with(lm_head_config, other_props);
+ auto lm_head_config_addition_value = lm_head_config_addition.value_or(ov::AnyMap{}).as<ov::AnyMap>();
+
+ merge_config_with(lm_head_config, lm_head_config_addition_value);
+ m_lm_head_compiled = std::dynamic_pointer_cast<ov::npuw::CompiledModel>(
+ ov::npuw::ICompiledModel::create(lm_head_model, plugin, lm_head_config));
+ NPUW_ASSERT(m_lm_head_compiled);
+ }
implement_properties();
LOG_DEBUG("Done");
@@ -1101,6 +1293,11 @@ void ov::npuw::LLMCompiledModel::serialize(std::ostream& stream, const ov::npuw:
CompiledContext enc_ctx(false, nullptr, nullptr, m_bf16_consts);
m_kvcache_compiled->serialize(model_stream, enc_ctx);
m_prefill_compiled->serialize(model_stream, enc_ctx);
+ const bool is_shared_lm_head = m_lm_head_compiled != nullptr;
+ write(model_stream, is_shared_lm_head);
+ if (is_shared_lm_head) {
+ m_lm_head_compiled->serialize(model_stream, enc_ctx);
+ }
};
std::stringstream non_encrypted_stream;
@@ -1287,7 +1484,12 @@ std::shared_ptr<ov::npuw::LLMCompiledModel> ov::npuw::LLMCompiledModel::deserial
CompiledContext enc_ctx(false, nullptr, nullptr);
compiled->m_kvcache_compiled = ov::npuw::CompiledModel::deserialize(model_stream, plugin, properties, enc_ctx);
compiled->m_prefill_compiled = ov::npuw::CompiledModel::deserialize(model_stream, plugin, properties, enc_ctx);
-
+ bool is_shared_lm_head = false;
+ read(model_stream, is_shared_lm_head);
+ if (is_shared_lm_head) {
+ compiled->m_lm_head_compiled =
+ ov::npuw::CompiledModel::deserialize(model_stream, plugin, properties, enc_ctx);
+ }
return compiled;
};
@@ -1352,11 +1554,13 @@ void ov::npuw::LLMCompiledModel::implement_properties() {
m_prop_to_opt.insert({BIND(npuw::llm::enabled, NPUW_LLM, get),
BIND(npuw::llm::batch_dim, NPUW_LLM_BATCH_DIM, get),
- BIND(npuw::llm::batch_dim, NPUW_LLM_SEQ_LEN_DIM, get),
+ BIND(npuw::llm::seq_len_dim, NPUW_LLM_SEQ_LEN_DIM, get),
BIND(npuw::llm::max_prompt_len, NPUW_LLM_MAX_PROMPT_LEN, get),
BIND(npuw::llm::min_response_len, NPUW_LLM_MIN_RESPONSE_LEN, get),
BIND(npuw::llm::optimize_v_tensors, NPUW_LLM_OPTIMIZE_V_TENSORS, get),
+ BIND(npuw::llm::prefill_chunk_size, NPUW_LLM_PREFILL_CHUNK_SIZE, get),
BIND(npuw::llm::prefill_hint, NPUW_LLM_PREFILL_HINT, getString),
- BIND(npuw::llm::generate_hint, NPUW_LLM_GENERATE_HINT, getString)});
+ BIND(npuw::llm::generate_hint, NPUW_LLM_GENERATE_HINT, getString),
+ BIND(npuw::llm::shared_lm_head, NPUW_LLM_SHARED_HEAD, get)});
#undef BIND
}
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 0b32857dea4..0690da6e9b9 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
@@ -17,6 +17,8 @@ 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 KVCacheDesc {
uint32_t max_prompt_size = 0u;
uint32_t total_size = 0u;
@@ -66,10 +68,11 @@ private:
ov::npuw::s11n::BF16Cache m_bf16_consts;
KVCacheDesc m_kvcache_desc;
+ uint64_t m_prefill_chunk_size;
std::shared_ptr<ov::npuw::CompiledModel> m_kvcache_compiled;
std::shared_ptr<ov::npuw::CompiledModel> m_prefill_compiled;
-
- uint64_t m_prefill_chunk_size;
+ // This model is optional, so can be null.
+ std::shared_ptr<ov::npuw::CompiledModel> m_lm_head_compiled;
};
} // namespace npuw
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 b80566f3587..2f000cfb6cf 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
@@ -1,4 +1,4 @@
-// Copyright (C) 2024 Intel Corporation
+// Copyright (C) 2024-2025 Intel Corporation
// SPDX-License-Identifier: Apache-2.0
//
@@ -107,9 +107,21 @@ void copy_columns_by_row_chunks(ov::SoPtr<ov::ITensor> src, ov::SoPtr<ov::ITenso
}
}
-void update_tensor_by_dim(ov::SoPtr<ov::ITensor> src_tensor, ov::SoPtr<ov::ITensor> dst_tensor, uint32_t kv_dim) {
+void copy_tensor_by_dim(ov::SoPtr<ov::ITensor> src_tensor, ov::SoPtr<ov::ITensor> dst_tensor, uint32_t kv_dim) {
if (kv_dim == 3u) {
- copy_columns_by_row_chunks(src_tensor, dst_tensor);
+ // Asserting that we work with last dimenston here:
+ const auto& src_shape = src_tensor->get_shape();
+ OPENVINO_ASSERT(src_shape.size() == 4);
+ // If last dimenstion of src_tensor is equal to 1, then we can squeeze
+ // src_shape from [1, heads, d_v, seq_len=1] to [heads, d_v].
+ // We can then treat src_tensor as a continuous tensor of row value vectors
+ // for multiple heads, while dst_tensor will still have [1, heads, d_v, seq_len!=1],
+ // shape, awaiting updates at column dimension, as value vectors are columns now.
+ if (src_shape[kv_dim] == 1 && src_tensor->is_continuous()) {
+ ov::npuw::util::XARCH::copy_row_as_column(src_tensor, dst_tensor);
+ } else {
+ copy_columns_by_row_chunks(src_tensor, dst_tensor);
+ }
} else if (kv_dim == 2u) {
copy_by_planes(src_tensor, dst_tensor);
} else {
@@ -182,12 +194,13 @@ ov::npuw::LLMInferRequest::LLMInferRequest(const std::shared_ptr<ov::npuw::LLMCo
init_tensor(output_port);
}
- auto input_ids_port = find_port_by_name(compiled_model->m_prefill_compiled->inputs(), "input_ids");
+ auto input_ids_port = find_port_by_name(compiled_model->m_prefill_compiled->inputs(), layer_names::input_ids);
if (input_ids_port.has_value()) {
- m_input_ids_name = "input_ids";
+ m_input_ids_name = layer_names::input_ids;
} else {
- OPENVINO_ASSERT(find_port_by_name(compiled_model->m_prefill_compiled->inputs(), "inputs_embeds").has_value());
- m_input_ids_name = "inputs_embeds";
+ OPENVINO_ASSERT(
+ find_port_by_name(compiled_model->m_prefill_compiled->inputs(), layer_names::inputs_embeds).has_value());
+ m_input_ids_name = layer_names::inputs_embeds;
}
m_kvcache_request = compiled_model->m_kvcache_compiled->create_infer_request();
@@ -212,6 +225,19 @@ ov::npuw::LLMInferRequest::LLMInferRequest(const std::shared_ptr<ov::npuw::LLMCo
if (use_chunk_prefill) {
clear_chunk_prefill_kv_cache();
}
+
+ if (compiled_model->m_lm_head_compiled) {
+ m_lm_head_request = compiled_model->m_lm_head_compiled->create_infer_request();
+ OPENVINO_ASSERT(m_lm_head_request);
+ const ov::Output<const ov::Node> lm_head_embed_port = m_lm_head_request->get_inputs()[0];
+ m_lm_head_logits_port = m_lm_head_request->get_outputs()[0];
+ m_prefill_request->set_tensor(m_prefill_out_ports.at(layer_names::output_embeds),
+ m_lm_head_request->get_tensor(lm_head_embed_port));
+ m_kvcache_request->set_tensor(m_kvcache_out_ports.at(layer_names::output_embeds),
+ m_lm_head_request->get_tensor(lm_head_embed_port));
+ }
+
+ m_generate_initialized = false;
}
void ov::npuw::LLMInferRequest::init_tensor(const ov::Output<const ov::Node>& port) {
@@ -237,12 +263,118 @@ void ov::npuw::LLMInferRequest::init_tensor(const ov::Output<const ov::Node>& po
void ov::npuw::LLMInferRequest::prepare_for_new_conversation() {
fill_tensor_bytes(m_prefill_request->get_tensor(m_prefill_in_ports.at(m_input_ids_name)), 0u);
- fill_tensor<int64_t>(m_prefill_request->get_tensor(m_prefill_in_ports.at("attention_mask")), 0);
- fill_tensor<int64_t>(m_prefill_request->get_tensor(m_prefill_in_ports.at("position_ids")), 0);
- fill_tensor<int64_t>(m_kvcache_request->get_tensor(m_kvcache_in_ports.at("attention_mask")), 0);
+ fill_tensor<int64_t>(m_prefill_request->get_tensor(m_prefill_in_ports.at(layer_names::attention_mask)), 0);
+ fill_tensor<int64_t>(m_prefill_request->get_tensor(m_prefill_in_ports.at(layer_names::position_ids)), 0);
m_npuw_llm_compiled_model->m_kvcache_desc.num_stored_tokens = 0u;
}
+void ov::npuw::LLMInferRequest::copy_kvcache() {
+ LOG_DEBUG("Copying kv-cache from prefill to generate model.");
+ LOG_BLOCK();
+ auto& kvcache_desc = m_npuw_llm_compiled_model->m_kvcache_desc;
+ const auto& kvcache_compiled = m_kvcache_request->get_compiled_model();
+ // FIXME: Find only matching by names outputs and copy them, having previously checked that such inputs exist
+ for (std::size_t i = kStartOutputKVCacheLayers; i < kvcache_compiled->outputs().size(); ++i) {
+ const auto& output_name = kvcache_compiled->outputs()[i].get_any_name();
+ auto prefill_out_tensor = m_prefill_request->get_tensor(m_prefill_out_ports.at(output_name));
+
+ const auto& input_name = std::regex_replace(output_name, std::regex("present"), layer_names::past_key_values);
+ if (m_kvcache_in_ports.find(input_name) == m_kvcache_in_ports.end()) {
+ // FIXME: Totally wrong debug message. input_name is an invalid name of input layer.
+ LOG_DEBUG("Input name " << input_name << " doesn't contain kv cache. Skipping.");
+ continue;
+ }
+ auto kvcache_in_tensor = m_kvcache_request->get_tensor(m_kvcache_in_ports.at(input_name));
+
+ const auto& kv_dim = (output_name.find("value") != std::string::npos && kvcache_desc.v_tensors_transposed)
+ ? 3u
+ : kvcache_desc.dim;
+
+ const auto prefill_chunk_size = m_npuw_llm_compiled_model->m_prefill_chunk_size;
+ const bool use_chunk_prefill = prefill_chunk_size > 0;
+ if (use_chunk_prefill) {
+ // The chunk prefilled KV results are divided into two parts:
+ // Part 1: The KV results from loops 1 to n-1 have been copied into the 'past' KV input tensor
+ // Part 2: The kv results from the last loop remain in the 'present' KV output tensor
+ // The task is to copy both parts into the KV-cache input tensor for the decoding process
+
+ // Copy part 1 KV results
+ auto tokens_in_present_chunk = kvcache_desc.num_stored_tokens % prefill_chunk_size;
+ tokens_in_present_chunk = tokens_in_present_chunk ? tokens_in_present_chunk : prefill_chunk_size;
+
+ // tokens_in_past_chunks may be 0 in case short prompts are prefilled in single chunk
+ auto tokens_in_past_chunks = kvcache_desc.num_stored_tokens - tokens_in_present_chunk;
+ if (tokens_in_past_chunks > 0) {
+ auto prefill_past_kv = m_prefill_request->get_tensor(m_prefill_in_ports.at(input_name));
+ auto prefill_past_kv_chunks =
+ make_tensor_slice(prefill_past_kv, kv_dim, 0u, static_cast<uint32_t>(tokens_in_past_chunks));
+
+ auto kvcache_past_kv_chunks =
+ make_tensor_slice(kvcache_in_tensor, kv_dim, 0u, static_cast<uint32_t>(tokens_in_past_chunks));
+
+ copy_tensor_by_dim(prefill_past_kv_chunks, kvcache_past_kv_chunks, kv_dim);
+ }
+
+ // Copy part 2 KV results
+ auto prefill_present_kv_chunk =
+ make_tensor_slice(prefill_out_tensor,
+ kv_dim,
+ static_cast<uint32_t>(prefill_chunk_size - tokens_in_present_chunk),
+ static_cast<uint32_t>(prefill_chunk_size));
+
+ auto kvcache_last_kv_chunk = make_tensor_slice(kvcache_in_tensor,
+ kv_dim,
+ static_cast<uint32_t>(tokens_in_past_chunks),
+ kvcache_desc.num_stored_tokens);
+
+ copy_tensor_by_dim(prefill_present_kv_chunk, kvcache_last_kv_chunk, kv_dim);
+ } else {
+ auto prefill_out_slice = make_tensor_slice(prefill_out_tensor,
+ kv_dim,
+ kvcache_desc.max_prompt_size - kvcache_desc.num_stored_tokens,
+ kvcache_desc.max_prompt_size);
+
+ auto kvcache_in_slice = make_tensor_slice(kvcache_in_tensor, kv_dim, 0u, kvcache_desc.num_stored_tokens);
+
+ copy_tensor_by_dim(prefill_out_slice, kvcache_in_slice, kv_dim);
+ }
+ }
+ LOG_DEBUG("Done.");
+}
+
+void ov::npuw::LLMInferRequest::update_kvcache_for(
+ std::shared_ptr<ov::IAsyncInferRequest> request,
+ std::unordered_map<std::string, ov::Output<const ov::Node>> in_ports,
+ std::unordered_map<std::string, ov::Output<const ov::Node>> out_ports,
+ uint32_t num_tokens) {
+ LOG_DEBUG("Store computed key and values for passed number of tokens in the input kv-cache"
+ " layers.");
+ LOG_BLOCK();
+ auto& kvcache_desc = m_npuw_llm_compiled_model->m_kvcache_desc;
+ auto& compiled = request->get_compiled_model();
+ // FIXME: Find only matching by names outputs and copy them, having previously checked that such inputs exist
+ for (std::size_t i = kStartOutputKVCacheLayers; i < compiled->outputs().size(); ++i) {
+ const auto& output_name = compiled->outputs()[i].get_any_name();
+ const auto& input_name = std::regex_replace(output_name, std::regex("present"), layer_names::past_key_values);
+ if (in_ports.find(input_name) == in_ports.end()) {
+ // FIXME: Totally wrong debug message. input_name is an invalid name of input layer.
+ LOG_DEBUG("Input name " << input_name << " doesn't contain kv cache. Skipping.");
+ continue;
+ }
+ auto dst_tensor = request->get_tensor(in_ports.at(input_name));
+ const auto& kv_dim = (output_name.find("value") != std::string::npos && kvcache_desc.v_tensors_transposed)
+ ? 3u
+ : kvcache_desc.dim;
+ auto dst_slice = make_tensor_slice(dst_tensor,
+ kv_dim,
+ kvcache_desc.num_stored_tokens - num_tokens,
+ kvcache_desc.num_stored_tokens);
+ auto src_tensor = request->get_tensor(out_ports.at(output_name));
+ copy_tensor_by_dim(src_tensor, dst_slice, kv_dim);
+ }
+ LOG_DEBUG("Done.");
+}
+
void ov::npuw::LLMInferRequest::clear_chunk_prefill_kv_cache() {
const auto& prefill_compiled = m_prefill_request->get_compiled_model();
@@ -250,6 +382,7 @@ void ov::npuw::LLMInferRequest::clear_chunk_prefill_kv_cache() {
const auto& output_name = prefill_compiled->outputs()[i].get_any_name();
const auto& input_name = std::regex_replace(output_name, std::regex("present"), "past_key_values");
if (m_prefill_in_ports.find(input_name) == m_prefill_in_ports.end()) {
+ // FIXME: Totally wrong debug message. input_name is an invalid name of input layer.
LOG_DEBUG("Input name " << input_name << " doesn't contain kv cache. Skipping.");
continue;
}
@@ -260,28 +393,23 @@ void ov::npuw::LLMInferRequest::clear_chunk_prefill_kv_cache() {
}
}
-void ov::npuw::LLMInferRequest::infer_prefill_in_chunk(ov::SoPtr<ov::ITensor> input_ids,
- ov::SoPtr<ov::ITensor> attention_mask,
- ov::SoPtr<ov::ITensor> position_ids) {
- LOG_DEBUG("Calling chunked inference for prefill model...");
+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) {
+ LOG_DEBUG("Calling chunked inference for prefill model.");
LOG_BLOCK();
- prepare_for_new_conversation();
-
- auto& kvcache_desc = m_npuw_llm_compiled_model->m_kvcache_desc;
const auto input_prompt_len = input_ids->get_shape()[INPUT_IDS_SEQ_LEN_DIM];
const auto input_ids_elem_size = input_ids->get_element_type().size();
auto input_ids_in_tensor = m_prefill_request->get_tensor(m_prefill_in_ports.at(m_input_ids_name));
const int64_t chunk_prompt_len = m_npuw_llm_compiled_model->m_prefill_chunk_size;
- auto attn_mask_in_tensor = m_prefill_request->get_tensor(m_prefill_in_ports.at("attention_mask"));
- auto pos_ids_in_tensor = m_prefill_request->get_tensor(m_prefill_in_ports.at("position_ids"));
+ auto attn_mask_in_tensor = m_prefill_request->get_tensor(m_prefill_in_ports.at(layer_names::attention_mask));
+ auto pos_ids_in_tensor = m_prefill_request->get_tensor(m_prefill_in_ports.at(layer_names::position_ids));
+
+ auto& kvcache_desc = m_npuw_llm_compiled_model->m_kvcache_desc;
int64_t remaining_prompts = input_prompt_len;
- if (input_prompt_len >= kvcache_desc.total_size) {
- OPENVINO_THROW("Input prompt length (" + std::to_string(input_prompt_len) +
- ") exceeds maximum kv-cache size (" + std::to_string(kvcache_desc.total_size) + ")");
- }
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
@@ -324,34 +452,17 @@ void ov::npuw::LLMInferRequest::infer_prefill_in_chunk(ov::SoPtr<ov::ITensor> in
remaining_prompts -= current_prompts_len;
kvcache_desc.num_stored_tokens += static_cast<uint32_t>(current_prompts_len);
+ // Do not copy last computed chunk and preserve it in present k/v layer
if (remaining_prompts <= 0) {
LOG_DEBUG("All prompts have been prefilled in chunks");
break;
}
- const auto& prefill_compiled = m_prefill_request->get_compiled_model();
- // FIXME: Find only matching by names outputs and copy them, having previously checked that such inputs exist
- for (std::size_t i = kStartOutputKVCacheLayers; i < prefill_compiled->outputs().size(); ++i) {
- const auto& output_name = prefill_compiled->outputs()[i].get_any_name();
- const auto& input_name = std::regex_replace(output_name, std::regex("present"), "past_key_values");
- if (m_prefill_in_ports.find(input_name) == m_prefill_in_ports.end()) {
- LOG_DEBUG("Input name " << input_name << " doesn't contain kv cache. Skipping.");
- continue;
- }
-
- auto chunk_prefill_past_kv_in_tensor = m_prefill_request->get_tensor(m_prefill_in_ports.at(input_name));
- const auto& kv_dim = (output_name.find("value") != std::string::npos && kvcache_desc.v_tensors_transposed)
- ? 3u
- : kvcache_desc.dim;
- auto chunk_prefill_past_kv_in_slice =
- make_tensor_slice(chunk_prefill_past_kv_in_tensor,
- kv_dim,
- kvcache_desc.num_stored_tokens - static_cast<uint32_t>(current_prompts_len),
- kvcache_desc.num_stored_tokens);
- auto chunk_prefill_present_kv_out_tensor =
- m_prefill_request->get_tensor(m_prefill_out_ports.at(output_name));
- update_tensor_by_dim(chunk_prefill_present_kv_out_tensor, chunk_prefill_past_kv_in_slice, kv_dim);
- }
+ // Copy calculated key/values chunk from present k/v layer to past k/v layer for storage
+ update_kvcache_for(m_prefill_request,
+ m_prefill_in_ports,
+ m_prefill_out_ports,
+ static_cast<uint32_t>(current_prompts_len));
// Update attention mask for the next iteration
std::copy_n(attn_mask_in_tensor->data<int64_t>() + attn_mask_in_tensor->get_size() - current_prompts_len,
@@ -359,15 +470,13 @@ void ov::npuw::LLMInferRequest::infer_prefill_in_chunk(ov::SoPtr<ov::ITensor> in
attn_mask_in_tensor->data<int64_t>() + kvcache_desc.num_stored_tokens - current_prompts_len);
}
- m_need_copy_kvcache = true;
-
- m_logits = m_prefill_request->get_tensor(m_prefill_out_ports.at("logits"));
+ LOG_DEBUG("Done.");
}
-void ov::npuw::LLMInferRequest::infer_prefill(ov::SoPtr<ov::ITensor> input_ids,
- ov::SoPtr<ov::ITensor> attention_mask,
- ov::SoPtr<ov::ITensor> position_ids) {
- LOG_DEBUG("Calling inference for prefill model...");
+void ov::npuw::LLMInferRequest::infer_whole_prefill(ov::SoPtr<ov::ITensor> input_ids,
+ ov::SoPtr<ov::ITensor> attention_mask,
+ ov::SoPtr<ov::ITensor> position_ids) {
+ LOG_DEBUG("Calling inference for prefill model in a single launch.");
LOG_BLOCK();
prepare_for_new_conversation();
@@ -379,22 +488,55 @@ void ov::npuw::LLMInferRequest::infer_prefill(ov::SoPtr<ov::ITensor> input_ids,
input_ids->get_byte_size(),
reinterpret_cast<uint8_t*>(padded_input->data()) + padded_input->get_byte_size() - input_ids->get_byte_size());
- auto padded_attention_mask = m_prefill_request->get_tensor(m_prefill_in_ports.at("attention_mask"));
+ auto padded_attention_mask = m_prefill_request->get_tensor(m_prefill_in_ports.at(layer_names::attention_mask));
std::copy_n(
attention_mask->data<int64_t>(),
attention_mask->get_size(),
padded_attention_mask->data<int64_t>() + padded_attention_mask->get_size() - attention_mask->get_size());
- auto padded_position_ids = m_prefill_request->get_tensor(m_prefill_in_ports.at("position_ids"));
+ auto padded_position_ids = m_prefill_request->get_tensor(m_prefill_in_ports.at(layer_names::position_ids));
pad_position_ids(padded_position_ids, position_ids);
m_prefill_request->infer();
+ auto& kvcache_desc = m_npuw_llm_compiled_model->m_kvcache_desc;
+ kvcache_desc.num_stored_tokens += static_cast<uint32_t>(input_ids->get_shape()[INPUT_IDS_SEQ_LEN_DIM]);
+
+ LOG_DEBUG("Done");
+}
+
+void ov::npuw::LLMInferRequest::infer_prefill(ov::SoPtr<ov::ITensor> input_ids,
+ ov::SoPtr<ov::ITensor> attention_mask,
+ ov::SoPtr<ov::ITensor> position_ids) {
+ LOG_DEBUG("Calling inference for prefill model...");
+ LOG_BLOCK();
- m_npuw_llm_compiled_model->m_kvcache_desc.num_stored_tokens +=
- static_cast<uint32_t>(input_ids->get_shape()[INPUT_IDS_SEQ_LEN_DIM]);
- m_need_copy_kvcache = true;
+ auto& kvcache_desc = m_npuw_llm_compiled_model->m_kvcache_desc;
+ if (input_ids->get_shape()[INPUT_IDS_SEQ_LEN_DIM] > 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.");
+ }
- m_logits = m_prefill_request->get_tensor(m_prefill_out_ports.at("logits"));
+ prepare_for_new_conversation();
+
+ const auto prefill_chunk_size = m_npuw_llm_compiled_model->m_prefill_chunk_size;
+ const bool use_chunk_prefill = prefill_chunk_size > 0;
+ if (use_chunk_prefill) {
+ infer_chunked_prefill(input_ids, attention_mask, position_ids);
+ } else {
+ infer_whole_prefill(input_ids, attention_mask, position_ids);
+ }
+
+ if (m_lm_head_request) {
+ LOG_DEBUG("Calling inference for LM head model.");
+ m_lm_head_request->infer();
+ m_logits = m_lm_head_request->get_tensor(m_lm_head_logits_port);
+ } else {
+ m_logits = m_prefill_request->get_tensor(m_prefill_out_ports.at(layer_names::logits));
+ }
+
+ m_generate_initialized = false;
LOG_DEBUG("Done");
}
@@ -405,96 +547,26 @@ void ov::npuw::LLMInferRequest::infer_generate(ov::SoPtr<ov::ITensor> input_ids,
LOG_DEBUG("Calling inference for generate model...");
LOG_BLOCK();
+ if (!m_generate_initialized) {
+ LOG_DEBUG("Copy kv-cache from prefill to generate model.");
+ copy_kvcache();
+
+ LOG_DEBUG("Prepare attention mask pattern.");
+ auto kv_attn_mask = m_kvcache_request->get_tensor(m_kvcache_in_ports.at(layer_names::attention_mask));
+ fill_tensor<int64_t>(kv_attn_mask, 0);
+ // NOTE: Attention mask pattern for generate model requires last "1" to be in the end of the mask.
+ // We can safely set this "1" once and then copy on one "1" less in the infer_generate().
+ kv_attn_mask->data<int64_t>()[m_npuw_llm_compiled_model->m_kvcache_desc.total_size - 1] = 1;
+
+ m_generate_initialized = true;
+ }
+
auto& kvcache_desc = m_npuw_llm_compiled_model->m_kvcache_desc;
// NB: KV-cache is full, further generation is impossible
if (kvcache_desc.num_stored_tokens == kvcache_desc.total_size) {
OPENVINO_THROW("KV-Cache is full.");
}
- if (m_need_copy_kvcache) {
- LOG_DEBUG("Copying kv-cache from prefill to generate model.");
- const auto& kvcache_compiled = m_kvcache_request->get_compiled_model();
- // FIXME: Find only matching by names outputs and copy them, having previously checked that such inputs exist
- for (std::size_t i = kStartOutputKVCacheLayers; i < kvcache_compiled->outputs().size(); ++i) {
- const auto& output_name = kvcache_compiled->outputs()[i].get_any_name();
- auto prefill_out_tensor = m_prefill_request->get_tensor(m_prefill_out_ports.at(output_name));
-
- const auto& input_name = std::regex_replace(output_name, std::regex("present"), "past_key_values");
- if (m_kvcache_in_ports.find(input_name) == m_kvcache_in_ports.end()) {
- LOG_DEBUG("Input name " << input_name << " doesn't contain kv cache. Skipping.");
- continue;
- }
-
- auto kvcache_in_tensor = m_kvcache_request->get_tensor(m_kvcache_in_ports.at(input_name));
-
- // FIXME: We don't need to fill whole tensor with 0s, but only tensor.size() - num_stored_tokens
- // taking into account kvcache dimension.
- fill_tensor<ov::float16>(kvcache_in_tensor, 0);
-
- const auto& kv_dim = (output_name.find("value") != std::string::npos && kvcache_desc.v_tensors_transposed)
- ? 3u
- : kvcache_desc.dim;
-
- const auto prefill_chunk_size = m_npuw_llm_compiled_model->m_prefill_chunk_size;
- const bool use_chunk_prefill = prefill_chunk_size > 0;
- if (use_chunk_prefill) {
- // The chunk prefilled KV results are divided into two parts:
- // Part 1: The KV results from loops 1 to n-1 have been copied into the 'past' KV input tensor
- // Part 2: The kv results from the last loop remain in the 'present' KV output tensor
- // The task is to copy both parts into the KV-cache input tensor for the decoding process
-
- // Copy part 1 KV results
- auto tokens_in_present_chunk = kvcache_desc.num_stored_tokens % prefill_chunk_size;
- tokens_in_present_chunk = tokens_in_present_chunk ? tokens_in_present_chunk : prefill_chunk_size;
-
- // tokens_in_past_chunks may be 0 in case short prompts are prefilled in single chunk
- auto tokens_in_past_chunks = kvcache_desc.num_stored_tokens - tokens_in_present_chunk;
- if (tokens_in_past_chunks > 0) {
- auto prefill_past_kv = m_prefill_request->get_tensor(m_prefill_in_ports.at(input_name));
- auto prefill_past_kv_chunks =
- make_tensor_slice(prefill_past_kv, kv_dim, 0u, static_cast<uint32_t>(tokens_in_past_chunks));
-
- auto kvcache_past_kv_chunks =
- make_tensor_slice(kvcache_in_tensor, kv_dim, 0u, static_cast<uint32_t>(tokens_in_past_chunks));
-
- update_tensor_by_dim(prefill_past_kv_chunks, kvcache_past_kv_chunks, kv_dim);
- }
-
- // Copy part 2 KV results
- auto prefill_present_kv_chunk =
- make_tensor_slice(prefill_out_tensor,
- kv_dim,
- static_cast<uint32_t>(prefill_chunk_size - tokens_in_present_chunk),
- static_cast<uint32_t>(prefill_chunk_size));
-
- auto kvcache_last_kv_chunk = make_tensor_slice(kvcache_in_tensor,
- kv_dim,
- static_cast<uint32_t>(tokens_in_past_chunks),
- kvcache_desc.num_stored_tokens);
-
- update_tensor_by_dim(prefill_present_kv_chunk, kvcache_last_kv_chunk, kv_dim);
- } else {
- auto prefill_out_slice =
- make_tensor_slice(prefill_out_tensor,
- kv_dim,
- kvcache_desc.max_prompt_size - kvcache_desc.num_stored_tokens,
- kvcache_desc.max_prompt_size);
-
- auto kvcache_in_slice =
- make_tensor_slice(kvcache_in_tensor, kv_dim, 0u, kvcache_desc.num_stored_tokens);
-
- update_tensor_by_dim(prefill_out_slice, kvcache_in_slice, kv_dim);
- }
- }
-
- LOG_DEBUG("Prepare attention mask pattern.");
- auto* attention_mask_data =
- m_kvcache_request->get_tensor(m_kvcache_in_ports.at("attention_mask"))->data<int64_t>();
- attention_mask_data[kvcache_desc.total_size - 1] = 1;
-
- m_need_copy_kvcache = false;
- }
-
// FIXME: these tensors should be shared between the parent & child models
auto kv_input_ids = m_kvcache_request->get_tensor(m_kvcache_in_ports.at(m_input_ids_name));
// NB: input_ids can be either fp32(VLM) or i64(LLM)
@@ -502,48 +574,35 @@ void ov::npuw::LLMInferRequest::infer_generate(ov::SoPtr<ov::ITensor> input_ids,
input_ids->get_byte_size(),
reinterpret_cast<uint8_t*>(kv_input_ids->data()));
- auto kv_attn_mask = m_kvcache_request->get_tensor(m_kvcache_in_ports.at("attention_mask"));
+ // NOTE: Attention mask pattern for generate model requires last "1" to be in the end of the mask.
+ // As it is already set above, here we copy on one "1" unit less.
+ auto kv_attn_mask = m_kvcache_request->get_tensor(m_kvcache_in_ports.at(layer_names::attention_mask));
std::copy_n(attention_mask->data<int64_t>(), attention_mask->get_size() - 1, kv_attn_mask->data<int64_t>());
- auto kv_pos_ids = m_kvcache_request->get_tensor(m_kvcache_in_ports.at("position_ids"));
+ auto kv_pos_ids = m_kvcache_request->get_tensor(m_kvcache_in_ports.at(layer_names::position_ids));
std::copy_n(position_ids->data<int64_t>(), position_ids->get_size(), kv_pos_ids->data<int64_t>());
m_kvcache_request->infer();
- m_logits = m_kvcache_request->get_tensor(m_kvcache_out_ports.at("logits"));
kvcache_desc.num_stored_tokens += 1;
- if (kvcache_desc.num_stored_tokens == kvcache_desc.total_size) {
- return;
- }
-
- LOG_DEBUG("Write KV-cache for the new token to the correct input position for next iteration.");
- const auto& kvcache_compiled = m_kvcache_request->get_compiled_model();
- // FIXME: Find only matching by names outputs and copy them, having previously checked that such inputs exist
- for (std::size_t i = kStartOutputKVCacheLayers; i < kvcache_compiled->outputs().size(); ++i) {
- const auto& output_name = kvcache_compiled->outputs()[i].get_any_name();
- const auto& input_name = std::regex_replace(output_name, std::regex("present"), "past_key_values");
- if (m_kvcache_in_ports.find(input_name) == m_kvcache_in_ports.end()) {
- LOG_DEBUG("Input name " << input_name << " doesn't contain kv cache. Skipping.");
- continue;
+ if (m_lm_head_request) {
+ LOG_DEBUG("Calling inference for LM head model asynchronously");
+ m_lm_head_request->start_async();
+ if (kvcache_desc.num_stored_tokens < kvcache_desc.total_size) {
+ update_kvcache_for(m_kvcache_request, m_kvcache_in_ports, m_kvcache_out_ports, 1);
}
+ m_lm_head_request->wait();
+ LOG_DEBUG("Calling inference for LM head model -- done.");
- auto kvcache_in_tensor = m_kvcache_request->get_tensor(m_kvcache_in_ports.at(input_name));
- const auto& kv_dim = (output_name.find("value") != std::string::npos && kvcache_desc.v_tensors_transposed)
- ? 3u
- : kvcache_desc.dim;
- auto kvcache_in_slice = make_tensor_slice(kvcache_in_tensor,
- kv_dim,
- kvcache_desc.num_stored_tokens - 1,
- kvcache_desc.num_stored_tokens);
- auto kvcache_out_tensor = m_kvcache_request->get_tensor(m_kvcache_out_ports.at(output_name));
- if (kv_dim == 3u) {
- ov::npuw::util::XARCH::copy_row_as_column(kvcache_out_tensor, kvcache_in_slice);
- } else if (kv_dim == 2u) {
- copy_by_planes(kvcache_out_tensor, kvcache_in_slice);
- } else {
- kvcache_out_tensor->copy_to(kvcache_in_slice._ptr);
+ m_logits = m_lm_head_request->get_tensor(m_lm_head_logits_port);
+ } else {
+ if (kvcache_desc.num_stored_tokens < kvcache_desc.total_size) {
+ update_kvcache_for(m_kvcache_request, m_kvcache_in_ports, m_kvcache_out_ports, 1);
}
+
+ m_logits = m_kvcache_request->get_tensor(m_kvcache_out_ports.at(layer_names::logits));
}
+
LOG_DEBUG("Done");
}
@@ -551,9 +610,9 @@ void ov::npuw::LLMInferRequest::infer() {
const auto& inputs = get_inputs();
auto input_ids = get_tensor(find_port_by_name(inputs, m_input_ids_name).value());
- auto attention_mask = get_tensor(find_port_by_name(inputs, "attention_mask").value());
+ auto attention_mask = get_tensor(find_port_by_name(inputs, layer_names::attention_mask).value());
// FIXME: position_ids might be optional for some models!
- auto position_ids = get_tensor(find_port_by_name(inputs, "position_ids").value());
+ auto position_ids = get_tensor(find_port_by_name(inputs, layer_names::position_ids).value());
// NB: For VLM, the "inputs_embeds" contains float values (embeddings)
OPENVINO_ASSERT(ov::element::f32 == input_ids->get_element_type() ||
@@ -564,13 +623,7 @@ void ov::npuw::LLMInferRequest::infer() {
// NB: Check the sequence length provided for input_ids
// in order to distinguish prefill / generate stages
if (input_ids->get_shape()[INPUT_IDS_SEQ_LEN_DIM] != 1) {
- const auto prefill_chunk_size = m_npuw_llm_compiled_model->m_prefill_chunk_size;
- const bool use_chunk_prefill = prefill_chunk_size > 0;
- if (use_chunk_prefill) {
- infer_prefill_in_chunk(input_ids, attention_mask, position_ids);
- } else {
- infer_prefill(input_ids, attention_mask, position_ids);
- }
+ infer_prefill(input_ids, attention_mask, position_ids);
} else {
infer_generate(input_ids, attention_mask, position_ids);
}
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 94786147f41..5b9fcb7b572 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
@@ -1,4 +1,4 @@
-// Copyright (C) 2024 Intel Corporation
+// Copyright (C) 2024-2025 Intel Corporation
// SPDX-License-Identifier: Apache-2.0
//
@@ -15,6 +15,16 @@ namespace npuw {
class LLMInferRequest final : public ov::ISyncInferRequest {
public:
+ struct layer_names {
+ static constexpr const char* input_ids = "input_ids";
+ static constexpr const char* inputs_embeds = "inputs_embeds";
+ static constexpr const char* attention_mask = "attention_mask";
+ static constexpr const char* position_ids = "position_ids";
+ static constexpr const char* past_key_values = "past_key_values";
+ static constexpr const char* output_embeds = "npuw_output_embed";
+ static constexpr const char* logits = "logits";
+ };
+
explicit LLMInferRequest(const std::shared_ptr<ov::npuw::LLMCompiledModel>& compiled_model);
void infer() override;
@@ -36,32 +46,45 @@ private:
void clear_chunk_prefill_kv_cache();
void init_tensor(const ov::Output<const ov::Node>& port);
+ void copy_kvcache();
+ void update_kvcache_for(std::shared_ptr<ov::IAsyncInferRequest> request,
+ std::unordered_map<std::string, ov::Output<const ov::Node>> in_ports,
+ std::unordered_map<std::string, ov::Output<const ov::Node>> out_ports,
+ uint32_t tokens);
+
+ void infer_chunked_prefill(ov::SoPtr<ov::ITensor> input_ids,
+ ov::SoPtr<ov::ITensor> attention_mask,
+ ov::SoPtr<ov::ITensor> position_ids);
+
+ void infer_whole_prefill(ov::SoPtr<ov::ITensor> input_ids,
+ ov::SoPtr<ov::ITensor> attention_mask,
+ ov::SoPtr<ov::ITensor> position_ids);
void infer_prefill(ov::SoPtr<ov::ITensor> input_ids,
ov::SoPtr<ov::ITensor> attention_mask,
ov::SoPtr<ov::ITensor> position_ids);
- void infer_prefill_in_chunk(ov::SoPtr<ov::ITensor> input_ids,
- ov::SoPtr<ov::ITensor> attention_mask,
- ov::SoPtr<ov::ITensor> position_ids);
-
void infer_generate(ov::SoPtr<ov::ITensor> input_ids,
ov::SoPtr<ov::ITensor> attention_mask,
ov::SoPtr<ov::ITensor> position_ids);
std::shared_ptr<ov::IAsyncInferRequest> m_kvcache_request;
std::shared_ptr<ov::IAsyncInferRequest> m_prefill_request;
+ // This infer request is optional, so can be null.
+ std::shared_ptr<ov::IAsyncInferRequest> m_lm_head_request;
std::shared_ptr<LLMCompiledModel> m_npuw_llm_compiled_model;
ov::SoPtr<ov::ITensor> m_logits;
- bool m_need_copy_kvcache = false;
std::unordered_map<std::string, ov::Output<const ov::Node>> m_prefill_in_ports;
std::unordered_map<std::string, ov::Output<const ov::Node>> m_prefill_out_ports;
std::unordered_map<std::string, ov::Output<const ov::Node>> m_kvcache_in_ports;
std::unordered_map<std::string, ov::Output<const ov::Node>> m_kvcache_out_ports;
+ ov::Output<const ov::Node> m_lm_head_logits_port;
// NB: It can be either input_ids(LLM) or inputs_embeds(VLM)
std::string m_input_ids_name;
+
+ bool m_generate_initialized = false;
};
} // namespace npuw
diff --git a/src/plugins/intel_npu/src/plugin/npuw/serialization.hpp b/src/plugins/intel_npu/src/plugin/npuw/serialization.hpp
index 340f12f135f..ec7745b5b68 100644
--- a/src/plugins/intel_npu/src/plugin/npuw/serialization.hpp
+++ b/src/plugins/intel_npu/src/plugin/npuw/serialization.hpp
@@ -34,7 +34,7 @@ const constexpr ov::npuw::s11n::IndicatorType NPUW_COMPILED_MODEL_INDICATOR =
const constexpr ov::npuw::s11n::IndicatorType NPUW_LLM_COMPILED_MODEL_INDICATOR =
{char{0x4c}, char{0x4c}, char{0x4d}, char{0x43}, char{0x4d}, char{0x4f}};
-const constexpr char* NPUW_SERIALIZATION_VERSION = "0.4";
+const constexpr char* NPUW_SERIALIZATION_VERSION = "0.5";
// Forward declaration
namespace intel_npu {