OpenVINO™ is an open source toolkit for optimizing and deploying AI inference
C++ aicomputer-visiondeep-learningdeploy-aidiffusion-modelsgenerative-aigood-first-issueinferencellm-inferencenatural-language-processingnlpopenvinooptimize-aiperformance-boostrecommendation-systemspeech-recognitionstable-diffusiontransformersyolo
[NPUW] Continuous prefill: contiguous KV strategy and delta prefill path (#37148)
Dylan Neve60c634d717eb
diff --git a/src/plugins/intel_npu/src/plugin/npuw/llm_compiled_model.cpp b/src/plugins/intel_npu/src/plugin/npuw/llm_compiled_model.cppindex 29bb38dd93b..a66a3b7d1fd 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@@ -1801,24 +1801,34 @@ bool ov::npuw::LLMCompiledModel::compute_continuous_prefill_supported() const {}}}- // Position ids must form a single linear sequence: 3-D M-RoPE cannot be validated- // as a contiguous continuation and is excluded statically. A read-only property- // must never throw, so a dynamic rank is treated as unsupported rather than- // queried through PartialShape::size(), which asserts a static rank.+ // The request-level API must carry position ids: the prefill submodel gains them+ // from AddPositionIdsParam even when the original model has none, and a+ // synthesized sequence cannot express a continuation start.+ if (!ov::npuw::util::find_port_by_name(inputs(), ov::npuw::LLMInferRequest::layer_names::position_ids)+ .has_value()) {+ return false;+ }+ // Position ids must be the exact [batch, seq] sequence the runtime validation+ // accepts: 3-D M-RoPE cannot be validated as a contiguous continuation. A+ // read-only property must never throw, so a dynamic rank is treated as+ // unsupported rather than queried through PartialShape::size(), which asserts+ // a static rank.const auto position_ids_port =ov::npuw::util::find_port_by_name(prefill_inputs, ov::npuw::LLMInferRequest::layer_names::position_ids);if (!position_ids_port.has_value()) {return false;}const auto& position_ids_rank = position_ids_port.value().get_partial_shape().rank();- if (position_ids_rank.is_dynamic() || position_ids_rank.get_length() >= 3) {+ if (position_ids_rank.is_dynamic() || position_ids_rank.get_length() != 2) {return false;}- // Every static exclusion above passed, but this change carries the protocol only:- // nothing attaches the coordinator to the variable state yet, so a proposal would- // throw. A capability the request cannot honour must never be advertised, so the- // answer stays false until the delta prefill path lands and lifts this.- return false;+ if (m_is_block_kv_cache) {+ // Only the contiguous strategy can plan a continuation so far, and the block+ // strategy would raise from the base class in preflight. Block support lands+ // in the follow-up change.+ return false;+ }+ return true;}ov::Any ov::npuw::LLMCompiledModel::get_property(const std::string& name) const {diff --git a/src/plugins/intel_npu/src/plugin/npuw/llm_compiled_model.hpp b/src/plugins/intel_npu/src/plugin/npuw/llm_compiled_model.hppindex 3b7030c50fd..5eacbfd8d68 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@@ -14,6 +14,7 @@ namespace test {namespace npuw {struct LLMVariantSwitchTestAccess;struct LLMTrimKVCacheTestAccess;+struct LLMContinuedPrefillTestAccess;} // namespace npuw} // namespace test} // namespace ov@@ -91,6 +92,7 @@ private:friend class LLMContinuousKVCacheStrategy;friend struct ov::test::npuw::LLMVariantSwitchTestAccess;friend struct ov::test::npuw::LLMTrimKVCacheTestAccess;+ friend struct ov::test::npuw::LLMContinuedPrefillTestAccess;friend class EncoderEmbeddingInferRequest;std::shared_ptr<ov::ISyncInferRequest> create_llm_infer_request();diff --git a/src/plugins/intel_npu/src/plugin/npuw/llm_continuation.hpp b/src/plugins/intel_npu/src/plugin/npuw/llm_continuation.hppindex 5302b3b923a..202266df44c 100644--- a/src/plugins/intel_npu/src/plugin/npuw/llm_continuation.hpp+++ b/src/plugins/intel_npu/src/plugin/npuw/llm_continuation.hpp@@ -23,18 +23,20 @@ namespace npuw {* limit the plugin owns and grants an effective keep K. A granted keep is a* command, so the next inference must be the matching delta-only prefill.*- * Three states. While IDLE the state reports the committed live token count- * and accepts one proposal, a reset, or ordinary inference. PENDING means a- * command is armed or executing: a positive keep demands the delta-only- * prefill, a zero keep demands a full prefill from position zero. Any failure- * after mutation started poisons the request as POISONED, where only reset()- * is accepted: the caller sent only the delta, so recovering by falling back- * to an ordinary prefill would treat the delta as the whole conversation.+ * Two states. While IDLE the state reports the committed live token count and+ * accepts one proposal, a reset, or ordinary inference. PENDING means a+ * command is armed: a positive keep demands the delta-only prefill, a zero+ * keep demands a full prefill from position zero. A failing inference leaves+ * the command pending and the cache in an unspecified state; the caller+ * recovers with reset() and the full history, the same recovery every failing+ * inference requires.** The keep rule is K = C * floor(min(K_common, K_max, W) / C), where C is the* prefill chunk size, K_max is how many past tokens the chunked prefill can- * represent, and W is the prefill-produced watermark. The rule is evaluated- * here at propose time and nowhere else.+ * represent, and W is the prefill-produced watermark. A proposal arriving after+ * a prompt-only turn is granted zero: the live prefix is then split between the+ * prefill model's past inputs and its present outputs, where no continuation+ * source exists. The rule is evaluated here at propose time and nowhere else.** Note for callers of the variable state: a write is not idempotent. You write* X and read back Y <= X, and must always slice at the granted value.@@ -44,7 +46,6 @@ public:enum class Stage : uint8_t {IDLE,PENDING,- POISONED,};ContinuationCoordinator() = default;@@ -90,7 +91,10 @@ public:m_live_tokens,"). Growth is an error.");- const uint32_t clamped = std::min({static_cast<uint32_t>(k_common), m_k_max, m_watermark});+ // Only the generate-side KV can serve as a continuation source, so a+ // proposal after a prompt-only turn is granted zero, which arms an+ // ordinary full-history reset.+ const uint32_t clamped = m_continuable ? std::min({static_cast<uint32_t>(k_common), m_k_max, m_watermark}) : 0u;const uint32_t granted = m_chunk_size * (clamped / m_chunk_size);m_pending_keep = granted;@@ -102,20 +106,12 @@ public:// The grant returned by get_state(), meaning the prefix the plugin will honour.int64_t query() const {- switch (m_stage) {- case Stage::IDLE:- return static_cast<int64_t>(m_live_tokens);- case Stage::PENDING:- return static_cast<int64_t>(m_pending_keep);- case Stage::POISONED:- return 0;- }- return 0;+ return m_stage == Stage::PENDING ? static_cast<int64_t>(m_pending_keep) : static_cast<int64_t>(m_live_tokens);}// reset() is a control operation rather than a proposal. It discards any pending// keep and arms a zero keep, idempotently. The physical reset happens on the- // next validated full prefill. This is also the only recovery from POISONED.+ // next validated full prefill.void request_reset() {m_pending_keep = 0u;m_stage = Stage::PENDING;@@ -125,45 +121,25 @@ public:// What the next inference must be: no value means ordinary inference, zero// means the pending reset's full prefill, positive means the delta-only- // prefill at exactly that keep. Throws if the request is poisoned.+ // prefill at exactly that keep.std::optional<uint32_t> pending() const {if (!m_enabled) {return std::nullopt;}- OPENVINO_ASSERT(m_stage != Stage::POISONED,- "Continuous prefill: the request is poisoned by a previous failure. "- "Call reset() on npuw_stored_tokens_state and re-send the full history.");return m_stage == Stage::PENDING ? std::optional<uint32_t>(m_pending_keep) : std::nullopt;}- // Preflight failed before any mutation. Consume the command and return to IDLE- // with the last committed counters intact. Only a pending keep may be aborted:- // a pending reset deliberately stays pending until the full prompt arrives.- void abort_preflight() {- OPENVINO_ASSERT(m_stage == Stage::PENDING && m_pending_keep > 0u,- "Continuous prefill: abort_preflight() without a pending keep command.");- m_pending_keep = 0u;- m_stage = Stage::IDLE;- }-- // An exception after live state mutation began poisons the request. No new- // count is published and only reset() can start recovery. Runs on exception- // paths, so it must never throw.- void poison() {- m_pending_keep = 0u;- m_stage = Stage::POISONED;- }-// Publish a committed prefill, full or continued. The new live count is also- // the new prefill-produced watermark. Legal for an ordinary idle prefill or- // a pending command that just executed; a commit must never clear the- // poisoning that only reset() owns.+ // the new prefill-produced watermark.void commit_prefill(uint32_t live_tokens) {- OPENVINO_ASSERT(m_stage != Stage::POISONED, "Continuous prefill: commit_prefill() on a poisoned request.");m_live_tokens = live_tokens;m_watermark = live_tokens;m_pending_keep = 0u;m_stage = Stage::IDLE;+ // The freshly prefilled prefix is split with the last chunk still in the+ // present outputs; it becomes a continuation source only after a generate+ // step consolidates it into the generate past KV.+ m_continuable = false;}// Publish the result of an ordinary generate step. Generate-produced KV must@@ -174,6 +150,7 @@ public:OPENVINO_ASSERT(m_stage == Stage::IDLE, "Continuous prefill: publish_generate() outside the idle state.");m_live_tokens = live_tokens;m_watermark = std::min(m_watermark, live_tokens);+ m_continuable = true;}uint32_t live_tokens() const {@@ -202,6 +179,9 @@ private:uint32_t m_watermark = 0u;uint32_t m_chunk_size = 0u;uint32_t m_k_max = 0u;+ // Whether the live prefix sits in the generate past KV, the only layout a+ // continuation can be sourced from. Prefills clear it, generate steps set it.+ bool m_continuable = false;};} // namespace npuwdiff --git a/src/plugins/intel_npu/src/plugin/npuw/llm_continuous_kvcache_strategy.cpp b/src/plugins/intel_npu/src/plugin/npuw/llm_continuous_kvcache_strategy.cppindex 4b54a4694dd..9eb7a8aeb47 100644--- a/src/plugins/intel_npu/src/plugin/npuw/llm_continuous_kvcache_strategy.cpp+++ b/src/plugins/intel_npu/src/plugin/npuw/llm_continuous_kvcache_strategy.cpp@@ -4,8 +4,12 @@#include "llm_continuous_kvcache_strategy.hpp"+#include <unordered_map>+#include "infer_request_utils.hpp"#include "llm_infer_request.hpp"+#include "logging.hpp"+#include "openvino/core/parallel.hpp"#include "util.hpp"namespace ov {@@ -18,6 +22,13 @@ namespace npuw {// 3. Zero-fill the shared KV buffer so the first chunk sees clean state.// Steps 2–3 are only applicable when chunk prefill is enabled.void LLMContinuousKVCacheStrategy::on_initialize() {+ // Classify every KV tensor once instead of on each use.+ m_kv_pairs.clear();+ m_kv_pairs.reserve(m_req.m_kvcache_past_names.size());+ for (const auto& name : m_req.m_kvcache_past_names) {+ m_kv_pairs.push_back({name, ov::npuw::util::isPastValueParam(name)});+ }+// Step 1: share past KV buffers across generate variants.// Collect the largest variant's KV tensors into a lookup map (one pass).auto& generate_requests = m_req.m_generate_requests;@@ -113,19 +124,11 @@ void LLMContinuousKVCacheStrategy::on_generate_variant_switch(const std::shared_LOG_DEBUG("Migrating " << num_stored << " KV tokens to new generate variant.");- for (const auto& name : m_req.m_kvcache_past_names) {- auto src = old_req->get_tensor(old_in_ports.at(name));- auto dst = new_req->get_tensor(new_in_ports.at(name));-- // Use the "present" name to distinguish key vs value — same pattern as- // update_kvcache_for. Direct find("value") on the input name is unreliable- // because "past_key_values.N.key" contains "value" via "key_values".- const auto present_name =- std::regex_replace(name, std::regex(ov::npuw::LLMInferRequest::layer_names::past_key_values), "present");- const uint32_t kv_dim =- (present_name.find("value") != std::string::npos && kvcache_desc.v_tensors_transposed_gen)- ? 3u- : kvcache_desc.dim;+ for (const auto& pair : m_kv_pairs) {+ auto src = old_req->get_tensor(old_in_ports.at(pair.past));+ auto dst = new_req->get_tensor(new_in_ports.at(pair.past));++ const uint32_t kv_dim = (pair.is_value && kvcache_desc.v_tensors_transposed_gen) ? 3u : kvcache_desc.dim;auto src_slice = uu::make_tensor_slice(src, kv_dim, 0u, num_stored);auto dst_slice = uu::make_tensor_slice(dst, kv_dim, 0u, num_stored);@@ -148,5 +151,123 @@ void LLMContinuousKVCacheStrategy::on_generate_step_done(uint32_t input_tokens_lv_transposed);}+namespace {++// Per-tensor repack geometry, analyzed during validation so the parallel copy+// below only moves bytes.+struct RepackEntry {+ uint32_t src_dim = 0u;+ uint32_t dst_dim = 0u;+ bool aliased = false;+ bool same_layout = false;+};++// The complete repack geometry for one src/dst tensor pair. The sequence axes+// come from the same global V-transposition flags every other KV movement path+// uses; a per-layer sequence-axis map can replace them for heterogeneous+// attention models once one is available at compile time. Aliasing means the+// two views share backing memory; identical layouts on shared memory need no+// copy at all, while different layouts on shared memory must stage through a+// temporary.+RepackEntry make_repack_entry(const ov::SoPtr<ov::ITensor>& src,+ const ov::SoPtr<ov::ITensor>& dst,+ uint32_t src_dim,+ uint32_t dst_dim) {+ RepackEntry entry;+ entry.src_dim = src_dim;+ entry.dst_dim = dst_dim;+ entry.aliased = src->data() == dst->data();+ entry.same_layout = entry.aliased && src->get_shape() == dst->get_shape() && src_dim == dst_dim;+ return entry;+}++} // anonymous namespace++// The preserved prefix always lives in the generate model's past inputs and is+// repacked into the prefill layout: the coordinator grants a keep only after a+// generate step consolidated the prefix there, and grants zero after a+// prompt-only turn. Every precondition is validated before any byte moves.+void LLMContinuousKVCacheStrategy::continue_prefill(uint32_t keep, uint32_t delta_len) {+ namespace uu = ov::npuw::util;+ const auto& compiled = m_req.m_npuw_llm_compiled_model;+ const auto& kvcache_desc = compiled->m_kvcache_desc;++ OPENVINO_ASSERT(compiled->m_use_chunk_prefill, "Continued prefill requires chunked prefill.");+ OPENVINO_ASSERT(keep > 0u && keep + delta_len <= kvcache_desc.max_prompt_size,+ "Continued prefill: keep (",+ keep,+ ") plus delta (",+ delta_len,+ ") must fit into the maximum prompt size (",+ kvcache_desc.max_prompt_size,+ ").");+ OPENVINO_ASSERT(keep <= kvcache_desc.max_prompt_size - compiled->m_prefill_chunk_size,+ "Continued prefill: keep exceeds the prefill past KV view capacity.");++ OPENVINO_ASSERT(m_kv_pairs.size() == m_req.m_kvcache_past_names.size(),+ "Continued prefill: the KV pair table was not initialized.");+ OPENVINO_ASSERT(m_req.m_generate_initialized,+ "Continued prefill: the preserved prefix must be sourced from the generate-phase KV; "+ "the coordinator grants zero after a prompt-only turn.");++ // Validate every layer and analyze its repack geometry before touching+ // any of them.+ std::vector<RepackEntry> entries;+ entries.reserve(m_kv_pairs.size());+ for (const auto& pair : m_kv_pairs) {+ OPENVINO_ASSERT(m_req.m_kvcache_in_ports.count(pair.past) && m_req.m_prefill_in_ports.count(pair.past),+ "Continued prefill: KV input ",+ pair.past,+ " is missing from the generate or prefill port map.");+ auto src = m_req.m_kvcache_request->get_tensor(m_req.m_kvcache_in_ports.at(pair.past));+ auto dst = m_req.m_prefill_request->get_tensor(m_req.m_prefill_in_ports.at(pair.past));+ OPENVINO_ASSERT(src->get_element_type() == dst->get_element_type(),+ "Continued prefill: element type mismatch for ",+ pair.past);++ const uint32_t src_dim = (pair.is_value && kvcache_desc.v_tensors_transposed_gen) ? 3u : kvcache_desc.dim;+ const uint32_t dst_dim = (pair.is_value && kvcache_desc.v_tensors_transposed_pre) ? 3u : kvcache_desc.dim;+ const auto entry = make_repack_entry(src, dst, src_dim, dst_dim);+ OPENVINO_ASSERT(src->get_shape()[entry.src_dim] >= keep && dst->get_shape()[entry.dst_dim] >= keep,+ "Continued prefill: KV extent of ",+ pair.past,+ " cannot cover the granted keep.");+ entries.push_back(entry);+ }++ LOG_DEBUG("Continued prefill: repacking " << keep << " tokens from generate past KV into prefill layout.");+ // Every tensor is independent, so repack them in parallel like copy_kvcache does.+ ov::parallel_for(m_kv_pairs.size(), [&](size_t idx) {+ const auto& pair = m_kv_pairs[idx];+ const auto& entry = entries[idx];+ if (entry.same_layout) {+ // The bytes already sit where the prefill will read them.+ return;+ }+ auto src = m_req.m_kvcache_request->get_tensor(m_req.m_kvcache_in_ports.at(pair.past));+ auto dst = m_req.m_prefill_request->get_tensor(m_req.m_prefill_in_ports.at(pair.past));++ // Both slices start at zero. Chunked prefill accumulates past KV+ // left-aligned from position zero and copy_kvcache() fills the generate+ // cache the same way; the right-aligned KV layout exists only in the+ // non-chunked prefill path, which continued prefill excludes.+ auto src_slice = uu::make_tensor_slice(src, entry.src_dim, 0u, keep);+ auto dst_slice = uu::make_tensor_slice(dst, entry.dst_dim, 0u, keep);+ if (entry.aliased) {+ // Shared backing memory is an aliasing hazard, not layout compatibility.+ // Identical bytes are addressed with different per-head strides whenever+ // the sequence extents differ, so the repack stages through a temporary.+ // The temporary lives inside the loop body, so only the tensors in+ // flight hold staging memory at any moment rather than the whole+ // preserved prefix at once.+ auto temp = uu::allocMem(src->get_element_type(), src_slice->get_shape(), "CPU", nullptr);+ src_slice->copy_to(temp._ptr);+ uu::copy_tensor_by_dim(temp, dst_slice, entry.src_dim, entry.dst_dim);+ } else {+ uu::copy_tensor_by_dim(src_slice, dst_slice, entry.src_dim, entry.dst_dim);+ }+ });+}+} // namespace npuw} // namespace ovdiff --git a/src/plugins/intel_npu/src/plugin/npuw/llm_continuous_kvcache_strategy.hpp b/src/plugins/intel_npu/src/plugin/npuw/llm_continuous_kvcache_strategy.hppindex e0a351a8f66..af3ed2d7846 100644--- a/src/plugins/intel_npu/src/plugin/npuw/llm_continuous_kvcache_strategy.hpp+++ b/src/plugins/intel_npu/src/plugin/npuw/llm_continuous_kvcache_strategy.hpp@@ -4,6 +4,9 @@#pragma once+#include <string>+#include <vector>+#include "llm_kvcache_strategy.hpp"namespace ov {@@ -35,6 +38,19 @@ public:const std::shared_ptr<ov::IAsyncInferRequest>& new_req,const PortsMap& new_in_ports) override;void on_generate_step_done(uint32_t input_tokens_len) override;++ // Continuous prefill. Repack the preserved KV prefix [0, keep) into the prefill+ // model's past KV layout so the chunked prefill can resume from `keep`.+ void continue_prefill(uint32_t keep, uint32_t delta_len) override;++private:+ // Static per-tensor facts, derived once in on_initialize() so the+ // continuation paths do not reclassify tensors on every call.+ struct KVPairInfo {+ std::string past;+ bool is_value = false;+ };+ std::vector<KVPairInfo> m_kv_pairs;};} // namespace npuwdiff --git a/src/plugins/intel_npu/src/plugin/npuw/llm_infer_request.cpp b/src/plugins/intel_npu/src/plugin/npuw/llm_infer_request.cppindex 2af2e2941c5..97f06795b3f 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@@ -307,6 +307,16 @@ ov::npuw::LLMInferRequest::LLMInferRequest(const std::shared_ptr<ov::npuw::LLMCom_stored_tokens_state = std::make_shared<ov::npuw::StoredTokensState>();init_lora_states();+ // Wire the continuous prefill negotiation channel when the compiled model+ // reports the capability. Without it the stored tokens state keeps its+ // legacy contract untouched.+ if (compiled_model->compute_continuous_prefill_supported()) {+ m_continuation.enable(static_cast<uint32_t>(compiled_model->m_prefill_chunk_size),+ compiled_model->m_kvcache_desc.max_prompt_size);+ m_stored_tokens_state->attach_continuation(&m_continuation);+ LOG_INFO("Continuous prefill is active for this infer request.");+ }+m_eagle3_ext.initialize(m_npuw_llm_compiled_model->m_is_eagle, m_prefill_in_ports, m_prefill_out_ports);// Instantiate the KV cache strategy and run one-time initialization.@@ -572,7 +582,7 @@ void ov::npuw::LLMInferRequest::prepare_for_new_conversation() {prepare_for_new_conversation(0);}-void ov::npuw::LLMInferRequest::prepare_for_new_conversation(int64_t prompt_length) {+void ov::npuw::LLMInferRequest::zero_prefill_staging() {namespace uu = ov::npuw::util;uu::fill_tensor_bytes(m_prefill_request->get_tensor(m_prefill_in_ports.at(m_input_ids_name)), 0u);@@ -588,6 +598,27 @@ void ov::npuw::LLMInferRequest::prepare_for_new_conversation(int64_t prompt_lengper_layer_port != m_prefill_in_ports.end()) {uu::fill_tensor_bytes(m_prefill_request->get_tensor(per_layer_port->second), 0u);}+}++void ov::npuw::LLMInferRequest::bind_generate_variant(int64_t prompt_length) {+ // The function internally calculates expected total tokens (prompt + min_response_len)+ m_kvcache_request = select_generate_request(prompt_length);+ m_kvcache_in_ports = m_generate_variant_in_ports.at(m_kvcache_request);+ m_kvcache_out_ports = m_generate_variant_out_ports.at(m_kvcache_request);+ // Record the selected variant index for O(1) capacity queries and mid-decode switching.+ const auto& reqs = m_generate_requests;+ m_kvcache_variant_idx =+ static_cast<size_t>(std::distance(reqs.begin(), std::find(reqs.begin(), reqs.end(), m_kvcache_request)));+}++void ov::npuw::LLMInferRequest::prepare_for_new_conversation(int64_t prompt_length) {+ namespace uu = ov::npuw::util;++ // A continued prefill that failed mid-way may leave its delta base behind;+ // a full prefill always addresses the caller tensors from zero.+ m_continued_prefill_base = 0u;++ zero_prefill_staging();m_kvcache_strategy->on_reset(prompt_length > 0 ? static_cast<uint32_t>(prompt_length) : 0u);@@ -600,14 +631,7 @@ void ov::npuw::LLMInferRequest::prepare_for_new_conversation(int64_t prompt_lengm_npuw_llm_compiled_model->m_kvcache_desc.num_stored_tokens = 0u;// Select the appropriate generate inference request variant based on prompt length- // The function internally calculates expected total tokens (prompt + min_response_len)- m_kvcache_request = select_generate_request(prompt_length);- m_kvcache_in_ports = m_generate_variant_in_ports.at(m_kvcache_request);- m_kvcache_out_ports = m_generate_variant_out_ports.at(m_kvcache_request);- // Record the selected variant index for O(1) capacity queries and mid-decode switching.- const auto& reqs = m_generate_requests;- m_kvcache_variant_idx =- static_cast<size_t>(std::distance(reqs.begin(), std::find(reqs.begin(), reqs.end(), m_kvcache_request)));+ bind_generate_variant(prompt_length);}void ov::npuw::LLMInferRequest::copy_kvcache() {@@ -957,8 +981,11 @@ void ov::npuw::LLMInferRequest::infer_chunked_prefill(ov::SoPtr<ov::ITensor> inpcurrent_prompts_len,attn_mask_in_tensor->data<int64_t>() + attn_mask_in_tensor->get_size() - current_prompts_len);+ // Caller tensors hold only the delta during a continued prefill, so they are+ // indexed relative to the absolute base the continuation started at. The+ // base is zero for an ordinary prefill, keeping this the absolute position.auto current_prefill_bytes = current_prompts_len * input_ids_elem_size;- auto prefilled_bytes = kvcache_desc.num_stored_tokens * input_ids_elem_size;+ auto prefilled_bytes = (kvcache_desc.num_stored_tokens - m_continued_prefill_base) * input_ids_elem_size;if (is_input_embeds) {current_prefill_bytes *= input_ids->get_shape().back();prefilled_bytes *= input_ids->get_shape().back();@@ -973,12 +1000,14 @@ void ov::npuw::LLMInferRequest::infer_chunked_prefill(ov::SoPtr<ov::ITensor> inp// NB: Regular LLM uses 2D position_ids [BATCH, SEQ_LEN], Qwen2.5 VL/Omni, Qwen3.5 VL use 3D position_ids// [3, BATCH, SEQ_LEN]// Copy postion ids with considering the 3D position_ids+ // The caller tensor is delta-relative during a continued prefill.auto last_dim = position_ids->get_shape().size() - 1;- auto actual_position_ids_slice = ov::npuw::util::make_tensor_slice(- position_ids,- static_cast<uint32_t>(last_dim),- kvcache_desc.num_stored_tokens,- kvcache_desc.num_stored_tokens + static_cast<uint32_t>(current_prompts_len));+ const uint32_t pos_src_offset = kvcache_desc.num_stored_tokens - m_continued_prefill_base;+ auto actual_position_ids_slice =+ ov::npuw::util::make_tensor_slice(position_ids,+ static_cast<uint32_t>(last_dim),+ pos_src_offset,+ pos_src_offset + static_cast<uint32_t>(current_prompts_len));auto pos_ids_slice =ov::npuw::util::make_tensor_slice(pos_ids_in_tensor,@@ -1015,17 +1044,21 @@ void ov::npuw::LLMInferRequest::infer_chunked_prefill(ov::SoPtr<ov::ITensor> inp// Update history size for dynamic context:// dynamic attention selector needs history size to determin the past KV shape and attention mask shape- m_prefill_base_request->update_history_size(kvcache_desc.num_stored_tokens);+ // The base request is absent when a test factory builds plain sub-requests.+ if (m_prefill_base_request) {+ m_prefill_base_request->update_history_size(kvcache_desc.num_stored_tokens);+ }// Gemma4 E2B/E4B: copy the current chunk of per_layer_inputs right-aligned on seq_len dim.// Source shape: [1, input_prompt_len, num_layers, proj_dim]// Dest shape: [1, chunk_prompt_len, num_layers, proj_dim] (static)if (per_layer_inputs) {auto dst = m_prefill_request->get_tensor(m_prefill_in_ports.at(layer_names::per_layer_inputs));- ov::npuw::util::copy_per_layer_inputs_chunk_to_right(per_layer_inputs,- dst,- kvcache_desc.num_stored_tokens,- static_cast<uint32_t>(current_prompts_len));+ ov::npuw::util::copy_per_layer_inputs_chunk_to_right(+ per_layer_inputs,+ dst,+ kvcache_desc.num_stored_tokens - m_continued_prefill_base,+ static_cast<uint32_t>(current_prompts_len));}// Gemma4-26B-A4B MoE: token_type_ids is [BATCH, SEQ_LEN].@@ -1177,7 +1210,9 @@ void ov::npuw::LLMInferRequest::infer_prefill(ov::SoPtr<ov::ITensor> input_ids,const auto prompt_length = input_ids->get_shape()[layer_ids::INPUT_IDS_SEQ_LEN_DIM];auto& kvcache_desc = m_npuw_llm_compiled_model->m_kvcache_desc;- if (prompt_length > kvcache_desc.max_prompt_size) {+ // In continuation mode the caller tensors hold only the delta; the combined+ // keep plus delta budget is validated by prepare_for_continued_prefill().+ if (m_continued_prefill_base == 0u && prompt_length > 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 "@@ -1185,7 +1220,11 @@ void ov::npuw::LLMInferRequest::infer_prefill(ov::SoPtr<ov::ITensor> input_ids,}m_llm_profile["1/prefill:1.prepare_for_new_conversation"].record([&]() {- prepare_for_new_conversation(prompt_length);+ if (m_continued_prefill_base > 0u) {+ prepare_for_continued_prefill(m_continued_prefill_base, input_ids, attention_mask, position_ids);+ } else {+ prepare_for_new_conversation(prompt_length);+ }});process_longrope(m_prefill_request, m_prefill_in_ports, position_ids);@@ -1236,6 +1275,93 @@ void ov::npuw::LLMInferRequest::infer_prefill(ov::SoPtr<ov::ITensor> input_ids,LOG_DEBUG("Done");}+void ov::npuw::LLMInferRequest::validate_continued_position_ids(const ov::SoPtr<ov::ITensor>& position_ids,+ uint32_t keep,+ uint32_t delta_len) const {+ // A continued prefill is validated from the whole position id sequence, never from+ // a single scalar equality, which would become a second routing heuristic.+ OPENVINO_ASSERT(position_ids->get_shape().size() == 2u,+ "Continued prefill: 3-D position ids cannot be validated as a linear sequence.");+ const auto* data = position_ids->data<int64_t>();+ const size_t count = position_ids->get_size();+ // A length mismatch must be a preflight rejection: it would otherwise only+ // surface inside the chunk loop, after the repack mutated the cache.+ OPENVINO_ASSERT(count == delta_len,+ "Continued prefill: position ids must cover exactly the delta. Expected ",+ delta_len,+ " entries, got ",+ count,+ ".");+ const int64_t expected_start = m_first_position_id + static_cast<int64_t>(keep);+ OPENVINO_ASSERT(data[0] == expected_start,+ "Continued prefill: position ids must start at the granted keep. Expected ",+ expected_start,+ ", got ",+ data[0],+ ".");+ for (size_t i = 1; i < count; ++i) {+ OPENVINO_ASSERT(data[i] == expected_start + static_cast<int64_t>(i),+ "Continued prefill: position ids must be contiguous and strictly increasing.");+ }+}++void ov::npuw::LLMInferRequest::prepare_for_continued_prefill(uint32_t keep,+ ov::SoPtr<ov::ITensor> input_ids,+ ov::SoPtr<ov::ITensor> attention_mask,+ ov::SoPtr<ov::ITensor> position_ids) {+ LOG_DEBUG("Continuing the conversation, keep=" << keep);++ auto& kvcache_desc = m_npuw_llm_compiled_model->m_kvcache_desc;+ const uint32_t delta_len = static_cast<uint32_t>(input_ids->get_shape()[layer_ids::INPUT_IDS_SEQ_LEN_DIM]);++ // Validation first. Nothing here touches live tensors, bindings or counters,+ // and the command stays pending on failure, so a corrected retry may still+ // succeed.+ OPENVINO_ASSERT(m_npuw_llm_compiled_model->m_use_chunk_prefill, "Continued prefill requires chunked prefill.");+ OPENVINO_ASSERT(input_ids->get_shape()[layer_ids::INPUT_IDS_SEQ_LEN_DIM] == delta_len,+ "Continued prefill: the delta length does not fit the 32-bit token counters.");+ OPENVINO_ASSERT(delta_len >= 1u, "Continued prefill: the delta must not be empty.");+ const uint64_t total = static_cast<uint64_t>(keep) + delta_len;+ OPENVINO_ASSERT(total <= kvcache_desc.max_prompt_size,+ "Continued prefill: keep (",+ keep,+ ") plus delta (",+ delta_len,+ ") exceeds NPUW_LLM_MAX_PROMPT_LEN (",+ kvcache_desc.max_prompt_size,+ ").");+ OPENVINO_ASSERT(attention_mask->get_size() == total,+ "Continued prefill: attention mask must cover the whole history. Expected ",+ total,+ " entries, got ",+ attention_mask->get_size(),+ ".");+ validate_continued_position_ids(position_ids, keep, delta_len);++ // The strategy validates its own preconditions before moving any byte, so+ // mutation starts inside this call. An exception past that leaves the cache+ // in an unspecified state with the command still pending; the caller+ // recovers with reset() and the full history, the same recovery every+ // failing inference requires.+ m_kvcache_strategy->continue_prefill(keep, delta_len);++ // Zero only the prefill staging tensors. The KV state, the strategy and the+ // lincache are deliberately left alone, unlike prepare_for_new_conversation.+ zero_prefill_staging();++ // Restore the preserved prefix attention mask. Nothing else populates the first+ // keep positions before the first continued chunk, and without them the new tokens+ // could not attend to the preserved conversation at all.+ auto attn_mask_in_tensor = m_prefill_request->get_tensor(m_prefill_in_ports.at(layer_names::attention_mask));+ std::copy_n(attention_mask->data<int64_t>(), keep, attn_mask_in_tensor->data<int64_t>());++ m_npuw_llm_compiled_model->m_kvcache_desc.num_stored_tokens = keep;++ // Select the generate variant for the full logical prompt, matching what a fresh+ // full-history run of the same conversation would have chosen.+ bind_generate_variant(static_cast<int64_t>(total));+}+void ov::npuw::LLMInferRequest::infer_generate(ov::SoPtr<ov::ITensor> input_ids,ov::SoPtr<ov::ITensor> attention_mask,ov::SoPtr<ov::ITensor> position_ids,@@ -1466,6 +1592,38 @@ void ov::npuw::LLMInferRequest::infer() {m_first_run = false;}+ // Continuous prefill routing comes first. A granted keep is an explicit command, so+ // it must never be re-derived from position ids. A delta continuation starts at+ // exactly the cache end, which the legacy heuristic below would misroute to the+ // generate path with a speculative-decoding trim. The delta base doubles as the+ // continuation flag for infer_prefill and must not survive a failed turn, so it+ // is assigned on every inference.+ const auto continuation_cmd = m_continuation.pending();+ m_continued_prefill_base = continuation_cmd.value_or(0u);++ bool run_prefill = m_continued_prefill_base > 0u;+ if (!run_prefill && continuation_cmd.has_value()) {+ // A pending reset accepts only a complete prompt at cache position zero. A+ // mismatch raises and the reset stays pending, so no ordinary inference can+ // run until the caller supplies the required full prompt.+ const auto prompt_len = input_ids->get_shape()[layer_ids::INPUT_IDS_SEQ_LEN_DIM];+ OPENVINO_ASSERT(attention_mask->get_size() == prompt_len,+ "Continuous prefill reset: the attention mask must cover exactly the full "+ "prompt. Expected ",+ prompt_len,+ " entries, got ",+ attention_mask->get_size(),+ ".");+ OPENVINO_ASSERT(position_ids->data<int64_t>()[0] == m_first_position_id,+ "Continuous prefill reset: position ids must start at the request's "+ "first-position baseline (",+ m_first_position_id,+ "), got ",+ position_ids->data<int64_t>()[0],+ ".");+ run_prefill = true;+ }+// NB: Check the sequence length provided for input_ids// and start position idx in order to distinguish prefill// and generate stages.@@ -1488,8 +1646,12 @@ void ov::npuw::LLMInferRequest::infer() {// The outcome of two items is that prefill and generate stages// can be safely differentiated by start position id for// both main and draft models for most of LLMs.- if (input_ids->get_shape()[layer_ids::INPUT_IDS_SEQ_LEN_DIM] > 1 &&- position_ids->data<int64_t>()[0] == m_first_position_id) {+ if (!continuation_cmd.has_value()) {+ run_prefill = input_ids->get_shape()[layer_ids::INPUT_IDS_SEQ_LEN_DIM] > 1 &&+ position_ids->data<int64_t>()[0] == m_first_position_id;+ }++ if (run_prefill) {infer_prefill(input_ids,attention_mask,position_ids,@@ -1497,6 +1659,13 @@ void ov::npuw::LLMInferRequest::infer() {per_layer_inputs,visual_pos_masks,deepstack_visual_embeds);+ if (m_continuation.enabled()) {+ // Every committed prefill, fresh, reset or continued, publishes the new+ // history so the next proposal negotiates against it. The coordinator+ // answers get_state() while attached, so the legacy stored-tokens+ // mirror needs no update here.+ m_continuation.commit_prefill(m_npuw_llm_compiled_model->m_kvcache_desc.num_stored_tokens);+ }} else {// FIXME: Need to make the solution smarter.// Qwen2.5VL uses 3D position_ids but current `trim_kvcache_for_speculative_decoding`@@ -1506,6 +1675,10 @@ void ov::npuw::LLMInferRequest::infer() {trim_kvcache_for_speculative_decoding(position_ids);}infer_generate(input_ids, attention_mask, position_ids, per_layer_inputs);+ if (m_continuation.enabled()) {+ // Generate-produced KV never advances the prefill watermark.+ m_continuation.publish_generate(m_npuw_llm_compiled_model->m_kvcache_desc.num_stored_tokens);+ }}if (!position_ids_opt.has_value()) {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.hppindex dfcfb173677..cefc6a631c3 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@@ -8,6 +8,7 @@#include "base_sync_infer_request.hpp"#include "llm_compiled_model.hpp"+#include "llm_continuation.hpp"#include "llm_eagle3_extension.hpp"#include "llm_infer_base_request.hpp"#include "llm_kvcache_strategy.hpp"@@ -22,6 +23,7 @@ namespace test {namespace npuw {struct LLMVariantSwitchTestAccess;struct LLMTrimKVCacheTestAccess;+struct LLMContinuedPrefillTestAccess;} // namespace npuw} // namespace test} // namespace ov@@ -103,6 +105,28 @@ protected:ov::SoPtr<ov::ITensor> position_ids,ov::SoPtr<ov::ITensor> per_layer_inputs);+ // Continuation counterpart of prepare_for_new_conversation(), run by+ // infer_prefill() when a granted keep is armed. Validates the delta inputs,+ // repacks the preserved prefix through the strategy, restores the history+ // attention mask and selects the generate variant. The KV state and the+ // lincache are left alone.+ void prepare_for_continued_prefill(uint32_t keep,+ ov::SoPtr<ov::ITensor> input_ids,+ ov::SoPtr<ov::ITensor> attention_mask,+ ov::SoPtr<ov::ITensor> position_ids);+ // Validates the delta position ids as a sequence against the latched baseline+ // and the delta length.+ void validate_continued_position_ids(const ov::SoPtr<ov::ITensor>& position_ids,+ uint32_t keep,+ uint32_t delta_len) const;++ // Zeroes the prefill model's staging inputs (input ids, token type ids,+ // attention mask, position ids, per-layer inputs), leaving KV state alone.+ void zero_prefill_staging();+ // Selects the generate variant for the given prompt length and rebinds the+ // request, its port maps and the variant index together.+ void bind_generate_variant(int64_t prompt_length);+// Multiple generate inference request variants, each with a different KV cache sizestd::vector<std::shared_ptr<ov::IAsyncInferRequest>> m_generate_requests;@@ -161,6 +185,14 @@ protected:// Support reset of stored tokens to 0 from external pipelineov::SoPtr<ov::npuw::StoredTokensState> m_stored_tokens_state;+ // Continuous prefill transaction coordinator, disabled unless the compiled model+ // reports the capability.+ ContinuationCoordinator m_continuation;+ // Absolute KV position the current chunked prefill started at. Non-zero only while+ // a continued prefill is running, where the caller tensors hold just the delta and+ // must be indexed relative to this base.+ uint32_t m_continued_prefill_base = 0u;+// Support LoRAstd::vector<ov::SoPtr<ov::IVariableState>> m_variableStates;void init_lora_states();@@ -188,6 +220,7 @@ protected:friend class PrefixCachingHelper;friend struct ov::test::npuw::LLMVariantSwitchTestAccess;friend struct ov::test::npuw::LLMTrimKVCacheTestAccess;+ friend struct ov::test::npuw::LLMContinuedPrefillTestAccess;};} // namespace npuwdiff --git a/src/plugins/intel_npu/src/plugin/npuw/llm_kvcache_strategy.hpp b/src/plugins/intel_npu/src/plugin/npuw/llm_kvcache_strategy.hppindex 4f1b0690c83..0a5f2628fb5 100644--- a/src/plugins/intel_npu/src/plugin/npuw/llm_kvcache_strategy.hpp+++ b/src/plugins/intel_npu/src/plugin/npuw/llm_kvcache_strategy.hpp@@ -87,6 +87,21 @@ public:// Called after each generate step's infer(): persist new token KV and update bindingsvirtual void on_generate_step_done(uint32_t input_tokens_len) = 0;+ // Continuous prefill support.++ // Continue a prefill that keeps the first `keep` tokens and will prefill+ // `delta_len` new ones. The strategy validates every dynamic precondition+ // without touching live state, so a validation failure leaves the cache+ // exactly as it was and a corrected retry may still succeed; it then moves+ // the preserved prefix into the prefill-side layout. An exception past+ // validation leaves the cache in an unspecified state and the caller must+ // recover with reset() and a full prefill.+ virtual void continue_prefill(uint32_t keep, uint32_t delta_len) {+ (void)keep;+ (void)delta_len;+ OPENVINO_THROW("Continuous prefill is not supported by this KV cache strategy.");+ }+protected:LLMInferRequest& m_req;};diff --git a/src/plugins/intel_npu/tests/unit/CMakeLists.txt b/src/plugins/intel_npu/tests/unit/CMakeLists.txtindex e12db008469..4cfad627c8c 100644--- a/src/plugins/intel_npu/tests/unit/CMakeLists.txt+++ b/src/plugins/intel_npu/tests/unit/CMakeLists.txt@@ -161,6 +161,7 @@ target_sources(${TARGET_NAME} PRIVATE${CMAKE_CURRENT_SOURCE_DIR}/npuw/flux2_compiled_model_test.cpp${CMAKE_CURRENT_SOURCE_DIR}/npuw/gqa_compiled_model_test.cpp${CMAKE_CURRENT_SOURCE_DIR}/npuw/llm_continuation_test.cpp+ ${CMAKE_CURRENT_SOURCE_DIR}/npuw/llm_continued_prefill_test.cpp${CMAKE_CURRENT_SOURCE_DIR}/npuw/stored_tokens_state_test.cpp${CMAKE_CURRENT_SOURCE_DIR}/npuw/llm_infer_request_variant_switch_test.cpp${CMAKE_CURRENT_SOURCE_DIR}/npuw/llm_trim_kvcache_test.cppdiff --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.cppindex 7ace85679d0..1d3822474fe 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@@ -241,8 +241,24 @@ TEST_F(LLMCompiledModelGraphOptionsTest, ContinuousPrefillOptionAndCapabilitySurASSERT_NE(compiled, nullptr);EXPECT_TRUE(compiled->get_property("NPUW_LLM_ENABLE_CONTINUOUS_PREFILL").as<bool>());- // The capability read must never throw. This change carries the protocol- // only, so it reports false even for an otherwise eligible model.+ // The capability read must never throw. With the contiguous delta prefill+ // path in place, an eligible chunked model advertises support.+ ov::Any supported;+ ASSERT_NO_THROW(supported = compiled->get_property("NPUW_LLM_CONTINUOUS_PREFILL_SUPPORTED"));+ EXPECT_TRUE(supported.as<bool>());+}++TEST_F(LLMCompiledModelGraphOptionsTest, ContinuousPrefillUnsupportedForStaticPrefill) {+ RecordingFactory recorder;+ std::unique_ptr<ov::npuw::LLMCompiledModel> compiled;++ // Whole (STATIC) prefill has no continuation path, so the option is accepted+ // but the capability reports false.+ ASSERT_NO_THROW(compiled = create_compiled_model({{"NPUW_LLM_ENABLE_CONTINUOUS_PREFILL", "YES"},+ {"NPUW_LLM_PREFILL_HINT", "STATIC"}},+ recorder));+ ASSERT_NE(compiled, nullptr);+ov::Any supported;ASSERT_NO_THROW(supported = compiled->get_property("NPUW_LLM_CONTINUOUS_PREFILL_SUPPORTED"));EXPECT_FALSE(supported.as<bool>());diff --git a/src/plugins/intel_npu/tests/unit/npuw/llm_continuation_test.cpp b/src/plugins/intel_npu/tests/unit/npuw/llm_continuation_test.cppindex 4699022a379..110fa8dceee 100644--- a/src/plugins/intel_npu/tests/unit/npuw/llm_continuation_test.cpp+++ b/src/plugins/intel_npu/tests/unit/npuw/llm_continuation_test.cpp@@ -63,18 +63,19 @@ TEST(NPUWContinuation, KeepRuleClampsToWatermark) {TEST(NPUWContinuation, KeepRuleClampsToCapacity) {ContinuationCoordinator c;c.enable(1024u, 4096u);- c.commit_prefill(4000u);+ c.commit_prefill(3999u);+ c.publish_generate(4000u);// K_max = 4096 - 1024 = 3072, rounded stays 3072.EXPECT_EQ(c.propose(4000), 3072u);}TEST(NPUWContinuation, KeepRuleRoundsDownToChunk) {- auto c = make_after_prefill(1500u);+ auto c = make_after_prefill(1500u, 1u);EXPECT_EQ(c.propose(1500), 1024u);}TEST(NPUWContinuation, SubChunkHistoryGrantsZeroAndArmsReset) {- auto c = make_after_prefill(1000u);+ auto c = make_after_prefill(1000u, 1u);EXPECT_EQ(c.propose(1000), 0u);// A zero keep is a full reset, not a continuation with an empty prefix.EXPECT_EQ(c.stage(), Stage::PENDING);@@ -82,6 +83,22 @@ TEST(NPUWContinuation, SubChunkHistoryGrantsZeroAndArmsReset) {EXPECT_EQ(c.query(), 0);}+TEST(NPUWContinuation, PromptOnlyTurnGrantsZeroAndArmsReset) {+ // Without a generate step the live prefix is split between the prefill past+ // inputs and the present outputs, where no continuation source exists.+ auto c = make_after_prefill(3000u);+ EXPECT_EQ(c.propose(3000), 0u);+ EXPECT_EQ(c.stage(), Stage::PENDING);+ EXPECT_EQ(c.pending(), 0u);+}++TEST(NPUWContinuation, ContinuationReopensAfterGenerateStep) {+ auto c = make_after_prefill(3000u);+ c.commit_prefill(3000u);+ c.publish_generate(3001u);+ EXPECT_EQ(c.propose(3001), 2048u);+}+TEST(NPUWContinuation, GrowthIsRejected) {auto c = make_after_prefill(2048u);EXPECT_THROW(c.propose(2049), ov::Exception);@@ -96,7 +113,7 @@ TEST(NPUWContinuation, NegativeProposalIsRejected) {}TEST(NPUWContinuation, SecondProposalWhilePendingIsRejected) {- auto c = make_after_prefill(3072u);+ auto c = make_after_prefill(3072u, 1u);EXPECT_EQ(c.propose(3072), 3072u);EXPECT_THROW(c.propose(2048), ov::Exception);}@@ -115,13 +132,13 @@ TEST(NPUWContinuation, QueryReturnsLiveTokensWhileIdle) {}TEST(NPUWContinuation, QueryReturnsGrantWhilePending) {- auto c = make_after_prefill(3000u);+ auto c = make_after_prefill(3000u, 1u);c.propose(3000);EXPECT_EQ(c.query(), 2048);}TEST(NPUWContinuation, PublishingLiveCountDoesNotReArmCommand) {- auto c = make_after_prefill(2048u);+ auto c = make_after_prefill(2048u, 1u);c.propose(2048);c.commit_prefill(2500u);// After the commit there is no pending command, only the published count.@@ -132,60 +149,8 @@ TEST(NPUWContinuation, PublishingLiveCountDoesNotReArmCommand) {// The transaction state machine.-TEST(NPUWContinuation, PreflightAbortConsumesCommandAndKeepsCounters) {- auto c = make_after_prefill(3000u, 20u);- c.propose(3000);- c.abort_preflight();- EXPECT_EQ(c.stage(), Stage::IDLE);- EXPECT_EQ(c.query(), 3020);- EXPECT_FALSE(c.pending().has_value());-}--TEST(NPUWContinuation, PreflightAbortRequiresAPendingKeep) {- // Only a pending keep may be aborted. A pending reset stays pending until the- // full prompt arrives, and aborting a poisoned request must not clear the- // poisoning that only reset() owns.- auto idle = make_after_prefill(3000u);- EXPECT_THROW(idle.abort_preflight(), ov::Exception);-- auto reset_pending = make_after_prefill(3000u);- reset_pending.request_reset();- EXPECT_THROW(reset_pending.abort_preflight(), ov::Exception);- EXPECT_EQ(reset_pending.stage(), Stage::PENDING);- EXPECT_EQ(reset_pending.pending(), 0u);-- auto poisoned = make_after_prefill(3000u);- poisoned.propose(3000);- poisoned.poison();- EXPECT_THROW(poisoned.abort_preflight(), ov::Exception);- EXPECT_EQ(poisoned.stage(), Stage::POISONED);-}--TEST(NPUWContinuation, FailureDuringInferencePoisonsTheRequest) {- auto c = make_after_prefill(3000u);- c.propose(3000);- c.poison();- EXPECT_EQ(c.stage(), Stage::POISONED);- EXPECT_EQ(c.query(), 0);- // Poisoned requests reject inference until reset() is called.- EXPECT_THROW(c.pending(), ov::Exception);-}--TEST(NPUWContinuation, ResetRecoversAPoisonedRequest) {- auto c = make_after_prefill(3000u);- c.propose(3000);- c.poison();- c.request_reset();- EXPECT_EQ(c.stage(), Stage::PENDING);- EXPECT_EQ(c.pending(), 0u);- // Idempotent while already pending.- c.request_reset();- EXPECT_EQ(c.stage(), Stage::PENDING);- EXPECT_EQ(c.pending(), 0u);-}-TEST(NPUWContinuation, ResetDiscardsAPendingKeep) {- auto c = make_after_prefill(3000u);+ auto c = make_after_prefill(3000u, 1u);c.propose(3000);c.request_reset();EXPECT_EQ(c.pending(), 0u);@@ -201,25 +166,26 @@ TEST(NPUWContinuation, CommitAfterResetPrefillReturnsToIdle) {EXPECT_EQ(c.watermark(), 500u);}-TEST(NPUWContinuation, CommitAndPublishRejectInvalidStates) {- // A commit must never clear the poisoning that only reset() owns.- auto poisoned = make_after_prefill(3000u);- poisoned.propose(3000);- poisoned.poison();- EXPECT_THROW(poisoned.commit_prefill(3000u), ov::Exception);- EXPECT_THROW(poisoned.publish_generate(3000u), ov::Exception);- EXPECT_EQ(poisoned.stage(), Stage::POISONED);-+TEST(NPUWContinuation, PublishWithArmedCommandIsRejected) {// Generate only runs when no command is pending, so a publish with an armed// command is a sequencing error. A commit from PENDING is the ordinary- // transaction commit and stays legal.- auto armed = make_after_prefill(3000u);+ // command completion and stays legal.+ auto armed = make_after_prefill(3000u, 1u);armed.propose(3000);EXPECT_THROW(armed.publish_generate(3100u), ov::Exception);EXPECT_EQ(armed.stage(), Stage::PENDING);EXPECT_EQ(armed.pending(), 2048u);}+TEST(NPUWContinuation, ResetIsIdempotentWhilePending) {+ auto c = make_after_prefill(3000u, 1u);+ c.propose(3000);+ c.request_reset();+ c.request_reset();+ EXPECT_EQ(c.stage(), Stage::PENDING);+ EXPECT_EQ(c.pending(), 0u);+}+// Watermark accounting.TEST(NPUWContinuation, WatermarkFollowsPrefillOnly) {diff --git a/src/plugins/intel_npu/tests/unit/npuw/llm_continued_prefill_test.cpp b/src/plugins/intel_npu/tests/unit/npuw/llm_continued_prefill_test.cppnew file mode 100644index 00000000000..426303ceb88--- /dev/null+++ b/src/plugins/intel_npu/tests/unit/npuw/llm_continued_prefill_test.cpp@@ -0,0 +1,497 @@+// Copyright (C) 2018-2026 Intel Corporation+// SPDX-License-Identifier: Apache-2.0+//++// Request-level regression tests for continuous prefill on the contiguous KV+// strategy. The tests drive the public LLMInferRequest surface: infer() for+// routing and the npuw_stored_tokens_state variable state for the propose/grant+// negotiation. Submodels are compiled through a factory that returns fake+// sub-requests whose infer() only zeroes outputs, so every byte that the tests+// observe in a KV tensor was moved there by the plugin's own KV plumbing.++#include <gtest/gtest.h>++#include <algorithm>+#include <cstdint>+#include <cstring>+#include <memory>+#include <numeric>+#include <string>+#include <unordered_map>+#include <utility>+#include <vector>++#include "executor.hpp"+#include "llm_compiled_model.hpp"+#include "llm_infer_request.hpp"+#include "llm_kvcache_strategy.hpp"+#include "llm_test_helpers.hpp"+#include "openvino/openvino.hpp"+#include "util.hpp"++namespace ov::test::npuw {++struct LLMContinuedPrefillTestAccess {+ using Request = ov::npuw::LLMInferRequest;++ static const ov::npuw::LLMCompiledModel::KVCacheDesc& desc(Request& req) {+ return req.m_npuw_llm_compiled_model->m_kvcache_desc;+ }++ static const std::vector<std::string>& past_names(Request& req) {+ return req.m_kvcache_past_names;+ }++ static ov::SoPtr<ov::ITensor> generate_past(Request& req, const std::string& name) {+ return req.m_kvcache_request->get_tensor(req.m_kvcache_in_ports.at(name));+ }++ static ov::SoPtr<ov::ITensor> prefill_past(Request& req, const std::string& name) {+ return req.m_prefill_request->get_tensor(req.m_prefill_in_ports.at(name));+ }++ static ov::SoPtr<ov::ITensor> prefill_attention_mask(Request& req) {+ return req.m_prefill_request->get_tensor(req.m_prefill_in_ports.at(Request::layer_names::attention_mask));+ }++ static bool generate_initialized(Request& req) {+ return req.m_generate_initialized;+ }++ static std::unique_ptr<ov::npuw::LLMKVCacheStrategy> take_strategy(Request& req) {+ return std::move(req.m_kvcache_strategy);+ }++ static void set_strategy(Request& req, std::unique_ptr<ov::npuw::LLMKVCacheStrategy> strategy) {+ req.m_kvcache_strategy = std::move(strategy);+ }+};++} // namespace ov::test::npuw++namespace {++using ov::test::npuw::build_llm_test_model;+using ov::test::npuw::LLMContinuedPrefillTestAccess;+using ov::test::npuw::NullPlugin;+class FakeSubCompiledModel;++class FakeSubInferRequest final : public ov::ISyncInferRequest {+public:+ explicit FakeSubInferRequest(std::shared_ptr<const FakeSubCompiledModel> compiled_model);++ void infer() override;+ ov::SoPtr<ov::ITensor> get_tensor(const ov::Output<const ov::Node>& port) const override {+ return ov::ISyncInferRequest::get_tensor(port);+ }+ void set_tensor(const ov::Output<const ov::Node>& port, const ov::SoPtr<ov::ITensor>& tensor) override {+ ov::ISyncInferRequest::set_tensor(port, tensor);+ }+ void check_tensors() const override {}+ std::vector<ov::SoPtr<ov::IVariableState>> query_state() const override {+ return {};+ }+ std::vector<ov::ProfilingInfo> get_profiling_info() const override {+ return {};+ }+};++class FakeSubCompiledModel final : public ov::npuw::ICompiledModel_v0 {+public:+ FakeSubCompiledModel(const std::shared_ptr<ov::Model>& model,+ const std::shared_ptr<const ov::IPlugin>& plugin,+ const ov::AnyMap&)+ : ov::npuw::ICompiledModel_v0(model, plugin),+ m_model(model) {}++ void export_model(std::ostream&) const override {}+ std::shared_ptr<const ov::Model> get_runtime_model() const override {+ return m_model;+ }+ void set_property(const ov::AnyMap&) override {}+ ov::Any get_property(const std::string&) const override {+ return {};+ }+ std::shared_ptr<ov::ISyncInferRequest> create_sync_infer_request() const override {+ auto self = std::static_pointer_cast<const FakeSubCompiledModel>(shared_from_this());+ return std::make_shared<FakeSubInferRequest>(std::move(self));+ }+ std::shared_ptr<ov::npuw::IBaseInferRequest> create_base_infer_request() const override {+ return {};+ }+ std::shared_ptr<ov::IAsyncInferRequest> wrap_async_infer_request(+ std::shared_ptr<ov::npuw::IBaseInferRequest>) const override {+ return std::make_shared<ov::IAsyncInferRequest>(create_sync_infer_request(),+ intel_npu::make_executor("continued_prefill_task", 1),+ intel_npu::make_executor("continued_prefill_callback", 1));+ }+ std::string submodel_device(std::size_t) const override {+ return "CPU";+ }+ std::size_t num_submodels() const override {+ // One CPU submodel, so init_pre_alloc_device() resolves to CPU staging+ // instead of requesting NPU remote tensors from the stub plugin.+ return 1;+ }+ std::shared_ptr<ov::npuw::weights::Bank> get_weights_bank() const override {+ return {};+ }+ void set_weights_bank(std::shared_ptr<ov::npuw::weights::Bank>) override {}+ void finalize_weights_bank() override {}+ void reconstruct_closure() override {}+ void serialize(std::ostream&, const ov::npuw::s11n::CompiledContext&) const override {}++private:+ std::shared_ptr<ov::Model> m_model;+};++FakeSubInferRequest::FakeSubInferRequest(std::shared_ptr<const FakeSubCompiledModel> compiled_model)+ : ov::ISyncInferRequest(std::move(compiled_model)) {+ for (const auto& input : get_compiled_model()->inputs()) {+ ov::ISyncInferRequest::set_tensor(input,+ 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())));+ }+}++void FakeSubInferRequest::infer() {+ for (const auto& output : get_compiled_model()->outputs()) {+ auto tensor = ov::ISyncInferRequest::get_tensor(output);+ std::memset(tensor->data(), 0, tensor->get_byte_size());+ }+}++class ContinuedPrefillFactory {+public:+ ov::npuw::LLMCompiledModel::CompiledModelFactory make_factory() {+ return [](const std::shared_ptr<ov::Model>& model,+ const std::shared_ptr<const ov::IPlugin>& plugin,+ const ov::AnyMap& props) -> std::shared_ptr<ov::npuw::ICompiledModel_v0> {+ return std::make_shared<FakeSubCompiledModel>(model, plugin, props);+ };+ }+};++// Delegates every strategy call to the real contiguous strategy but fails the+// continuation, modelling a failure inside the strategy.+class ThrowingContinuationStrategy final : public ov::npuw::LLMKVCacheStrategy {+public:+ ThrowingContinuationStrategy(ov::npuw::LLMInferRequest& req, std::unique_ptr<ov::npuw::LLMKVCacheStrategy> inner)+ : LLMKVCacheStrategy(req),+ m_inner(std::move(inner)) {}++ void on_initialize() override {+ m_inner->on_initialize();+ }+ void on_reset(uint32_t next_prompt_length) override {+ m_inner->on_reset(next_prompt_length);+ }+ void on_prefill_chunk_begin(uint32_t current_prompts_len) override {+ m_inner->on_prefill_chunk_begin(current_prompts_len);+ }+ void on_prefill_chunk_done(uint32_t current_prompts_len, bool is_last) override {+ m_inner->on_prefill_chunk_done(current_prompts_len, is_last);+ }+ void on_generate_kv_init() override {+ m_inner->on_generate_kv_init();+ }+ void on_generate_variant_switch(const std::shared_ptr<ov::IAsyncInferRequest>& old_req,+ const PortsMap& old_in_ports,+ const std::shared_ptr<ov::IAsyncInferRequest>& new_req,+ const PortsMap& new_in_ports) override {+ m_inner->on_generate_variant_switch(old_req, old_in_ports, new_req, new_in_ports);+ }+ void on_generate_step_done(uint32_t input_tokens_len) override {+ m_inner->on_generate_step_done(input_tokens_len);+ }+ void continue_prefill(uint32_t, uint32_t) override {+ OPENVINO_THROW("Injected continued-prefill failure.");+ }++private:+ std::unique_ptr<ov::npuw::LLMKVCacheStrategy> m_inner;+};++std::vector<uint8_t> materialize_bytes(const ov::SoPtr<ov::ITensor>& tensor) {+ ov::Tensor copy(tensor->get_element_type(), tensor->get_shape());+ tensor->copy_to(ov::get_tensor_impl(copy)._ptr);+ auto* data = static_cast<uint8_t*>(copy.data());+ return std::vector<uint8_t>(data, data + copy.get_byte_size());+}++void fill_tensor_pattern(const ov::SoPtr<ov::ITensor>& tensor, uint8_t seed) {+ ov::Tensor dense(tensor->get_element_type(), tensor->get_shape());+ auto* data = static_cast<uint8_t*>(dense.data());+ for (size_t i = 0; i < dense.get_byte_size(); ++i) {+ data[i] = static_cast<uint8_t>(seed + (i % 251));+ }+ ov::get_tensor_impl(dense)->copy_to(tensor._ptr);+}++ov::Tensor make_i64(std::initializer_list<size_t> shape, int64_t fill_value) {+ ov::Tensor tensor(ov::element::i64, ov::Shape(shape));+ std::fill_n(tensor.data<int64_t>(), tensor.get_size(), fill_value);+ return tensor;+}++ov::Tensor make_i64_iota(std::initializer_list<size_t> shape, int64_t start) {+ ov::Tensor tensor(ov::element::i64, ov::Shape(shape));+ std::iota(tensor.data<int64_t>(), tensor.data<int64_t>() + tensor.get_size(), start);+ return tensor;+}++class LLMContinuedPrefillTest : public ::testing::Test {+protected:+ void SetUp() override {+ m_plugin = std::make_shared<NullPlugin>();+ ContinuedPrefillFactory factory;+ m_compiled =+ std::make_shared<ov::npuw::LLMCompiledModel>(build_llm_test_model(),+ m_plugin,+ ov::AnyMap{{"NPUW_LLM", "YES"},+ {"NPUW_DEVICES", "CPU"},+ {"NPUW_LLM_MAX_PROMPT_LEN", "256"},+ {"NPUW_LLM_MIN_RESPONSE_LEN", "64"},+ {"NPUW_LLM_PREFILL_HINT", "DYNAMIC"},+ {"NPUW_LLM_PREFILL_CHUNK_SIZE", "32"},+ {"NPUW_LLM_ENABLE_CONTINUOUS_PREFILL", "YES"}},+ factory.make_factory());+ ASSERT_NE(m_compiled, nullptr);+ ASSERT_TRUE(m_compiled->get_property("NPUW_LLM_CONTINUOUS_PREFILL_SUPPORTED").as<bool>());++ m_request = std::make_unique<ov::npuw::LLMInferRequest>(m_compiled);++ // The byte-level comparisons below materialize a source and a destination+ // slice and compare them directly, which is valid only while the prefill+ // and generate KV layouts agree on the V orientation. This holds for the+ // test model; a mismatch would also disable KV buffer sharing entirely.+ const auto& desc = LLMContinuedPrefillTestAccess::desc(*m_request);+ ASSERT_EQ(desc.v_tensors_transposed_pre, desc.v_tensors_transposed_gen);+ }++ ov::npuw::LLMInferRequest& request() {+ return *m_request;+ }++ ov::SoPtr<ov::IVariableState> stored_tokens_state() {+ for (const auto& state : m_request->query_state()) {+ if (state->get_name() == "npuw_stored_tokens_state") {+ return state;+ }+ }+ ADD_FAILURE() << "npuw_stored_tokens_state is not exposed by the request";+ return {};+ }++ int64_t stored_tokens() {+ return stored_tokens_state()->get_state()->data<int64_t>()[0];+ }++ void propose(int64_t k_common) {+ auto proposal = ov::Tensor(ov::element::i64, ov::Shape{1});+ proposal.data<int64_t>()[0] = k_common;+ stored_tokens_state()->set_state(ov::get_tensor_impl(proposal));+ }++ void set_inputs(const ov::Tensor& input_ids, const ov::Tensor& attention_mask, const ov::Tensor& position_ids) {+ const auto& inputs = m_request->get_inputs();+ m_request->set_tensor(ov::npuw::util::find_port_by_name(inputs, "input_ids").value(),+ ov::get_tensor_impl(input_ids));+ m_request->set_tensor(ov::npuw::util::find_port_by_name(inputs, "attention_mask").value(),+ ov::get_tensor_impl(attention_mask));+ m_request->set_tensor(ov::npuw::util::find_port_by_name(inputs, "position_ids").value(),+ ov::get_tensor_impl(position_ids));+ }++ void run_full_prefill(size_t prompt_len) {+ set_inputs(make_i64({1, prompt_len}, 1), make_i64({1, prompt_len}, 1), make_i64_iota({1, prompt_len}, 0));+ m_request->infer();+ }++ void run_generate_step(size_t live_tokens) {+ set_inputs(make_i64({1, 1}, 1),+ make_i64({1, live_tokens + 1}, 1),+ make_i64({1, 1}, static_cast<int64_t>(live_tokens)));+ m_request->infer();+ }++ void run_delta_prefill(size_t keep, size_t delta_len) {+ set_inputs(make_i64({1, delta_len}, 1),+ make_i64({1, keep + delta_len}, 1),+ make_i64_iota({1, delta_len}, static_cast<int64_t>(keep)));+ m_request->infer();+ }++ uint32_t generate_seq_dim(const std::string& past_name) {+ const auto& desc = LLMContinuedPrefillTestAccess::desc(*m_request);+ const bool is_value = ov::npuw::util::isPastValueParam(past_name);+ return (is_value && desc.v_tensors_transposed_gen) ? 3u : desc.dim;+ }++ uint32_t prefill_seq_dim(const std::string& past_name) {+ const auto& desc = LLMContinuedPrefillTestAccess::desc(*m_request);+ const bool is_value = ov::npuw::util::isPastValueParam(past_name);+ return (is_value && desc.v_tensors_transposed_pre) ? 3u : desc.dim;+ }++ std::shared_ptr<ov::IPlugin> m_plugin;+ std::shared_ptr<ov::npuw::LLMCompiledModel> m_compiled;+ std::unique_ptr<ov::npuw::LLMInferRequest> m_request;+};++// A granted keep routes the next infer through the delta-only prefill: the+// preserved prefix is repacked from the generate past KV into the prefill+// layout (through the alias-safe staging path, as both views share one backing+// buffer), the restored attention mask exposes the history, and a multi-chunk+// delta lands after the preserved region without disturbing it.+TEST_F(LLMContinuedPrefillTest, GrantedContinuationRepacksGenerateKvAndRunsDeltaOnly) {+ auto& req = request();+ run_full_prefill(72);+ EXPECT_EQ(stored_tokens(), 72);+ run_generate_step(72);+ run_generate_step(73);+ EXPECT_EQ(stored_tokens(), 74);+ ASSERT_TRUE(LLMContinuedPrefillTestAccess::generate_initialized(req));++ // The live prefix sits in the generate past KV. Stamp the preserved region+ // with a per-tensor pattern and remember its logical content.+ constexpr uint32_t kKeep = 64u;+ std::unordered_map<std::string, std::vector<uint8_t>> expected_kv_bytes;+ uint8_t seed = 23u;+ for (const auto& name : LLMContinuedPrefillTestAccess::past_names(req)) {+ auto src = LLMContinuedPrefillTestAccess::generate_past(req, name);+ auto src_slice = ov::npuw::util::make_tensor_slice(src, generate_seq_dim(name), 0u, kKeep);+ fill_tensor_pattern(src_slice, seed);+ expected_kv_bytes.emplace(name, materialize_bytes(src_slice));+ seed = static_cast<uint8_t>(seed + 41u);+ }++ // Propose the whole live history. The watermark is the prefill-produced 72,+ // so the grant rounds down to the chunk-aligned 64.+ propose(74);+ EXPECT_EQ(stored_tokens(), 64);++ // Second turn: 40 delta tokens (two chunks) on top of the granted keep.+ run_delta_prefill(kKeep, 40);+ EXPECT_EQ(stored_tokens(), 104);+ EXPECT_FALSE(LLMContinuedPrefillTestAccess::generate_initialized(req));++ // The preserved prefix must now sit in the prefill past KV, repacked into+ // the prefill layout, and must have survived the delta chunk loop.+ for (const auto& name : LLMContinuedPrefillTestAccess::past_names(req)) {+ auto dst = LLMContinuedPrefillTestAccess::prefill_past(req, name);+ auto dst_slice = ov::npuw::util::make_tensor_slice(dst, prefill_seq_dim(name), 0u, kKeep);+ EXPECT_EQ(materialize_bytes(dst_slice), expected_kv_bytes.at(name)) << name;+ }++ // Without the restored history mask the delta could not attend to the+ // preserved conversation at all.+ auto mask = LLMContinuedPrefillTestAccess::prefill_attention_mask(req);+ const auto* mask_data = mask->data<int64_t>();+ EXPECT_TRUE(std::all_of(mask_data, mask_data + kKeep, [](int64_t v) {+ return v == 1;+ }));++ // The continuation hands over to an ordinary generate step.+ run_generate_step(104);+ EXPECT_EQ(stored_tokens(), 105);+}++// A conversation that ends on its prompt logits never runs a generate step, so+// the live prefix stays split between the prefill past inputs and the present+// outputs, where no continuation source exists. The coordinator grants zero+// and the caller re-sends the full history as an ordinary reset prefill.+TEST_F(LLMContinuedPrefillTest, PromptOnlyTurnGrantsZeroAndFullHistoryRecovers) {+ auto& req = request();+ run_full_prefill(96);+ EXPECT_EQ(stored_tokens(), 96);+ ASSERT_FALSE(LLMContinuedPrefillTestAccess::generate_initialized(req));++ propose(96);+ EXPECT_EQ(stored_tokens(), 0);++ // The full 112-token history at position zero satisfies the armed reset.+ run_full_prefill(112);+ EXPECT_EQ(stored_tokens(), 112);++ // Once a generate step consolidates the prefix into the generate KV, the+ // next turn negotiates a real keep again.+ run_generate_step(112);+ EXPECT_EQ(stored_tokens(), 113);+ propose(113);+ EXPECT_EQ(stored_tokens(), 96);+}++// A one-token delta must route through the granted continuation. The legacy+// length heuristic would classify it as a generate step, so the explicit+// command has to stay ahead of that heuristic.+TEST_F(LLMContinuedPrefillTest, SingleTokenDeltaRoutesToContinuedPrefill) {+ auto& req = request();+ run_full_prefill(64);+ run_generate_step(64);+ EXPECT_EQ(stored_tokens(), 65);++ propose(65);+ EXPECT_EQ(stored_tokens(), 64);++ run_delta_prefill(64, 1);+ EXPECT_EQ(stored_tokens(), 65);+ // The delta ran as a prefill, so the generate phase re-initializes next.+ EXPECT_FALSE(LLMContinuedPrefillTestAccess::generate_initialized(req));+}++// A preflight rejection mutates nothing and leaves the command pending, so a+// corrected delta still completes the continuation.+TEST_F(LLMContinuedPrefillTest, PreflightRejectionKeepsCommandRetryable) {+ auto& req = request();+ run_full_prefill(72);+ run_generate_step(72);+ EXPECT_EQ(stored_tokens(), 73);++ propose(73);+ EXPECT_EQ(stored_tokens(), 64);++ // Position ids starting at the conversation base instead of the granted+ // keep must be rejected by the sequence validation.+ set_inputs(make_i64({1, 40}, 1), make_i64({1, 104}, 1), make_i64_iota({1, 40}, 0));+ EXPECT_THROW(req.infer(), ov::Exception);++ // The grant stays armed and the corrected delta succeeds.+ EXPECT_EQ(stored_tokens(), 64);+ run_delta_prefill(64, 40);+ EXPECT_EQ(stored_tokens(), 104);+}++// A failing continuation leaves the command pending and the cache unspecified.+// The caller's recovery is reset() plus the full history, after which the+// request works again.+TEST_F(LLMContinuedPrefillTest, InjectedApplyFailureRecoversAfterReset) {+ auto& req = request();+ run_full_prefill(72);+ run_generate_step(72);+ EXPECT_EQ(stored_tokens(), 73);++ auto inner = LLMContinuedPrefillTestAccess::take_strategy(req);+ ASSERT_NE(inner, nullptr);+ LLMContinuedPrefillTestAccess::set_strategy(req,+ std::make_unique<ThrowingContinuationStrategy>(req, std::move(inner)));++ propose(73);+ set_inputs(make_i64({1, 40}, 1), make_i64({1, 104}, 1), make_i64_iota({1, 40}, 64));+ EXPECT_THROW(req.infer(), ov::Exception);++ // The command is still armed; the caller gives up on it with reset() and+ // re-establishes the conversation with a full prefill from position zero.+ EXPECT_EQ(stored_tokens(), 64);+ stored_tokens_state()->reset();+ run_full_prefill(80);+ EXPECT_EQ(stored_tokens(), 80);+ run_generate_step(80);+ EXPECT_EQ(stored_tokens(), 81);+}++} // namespace