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] Rerotate K cache for LongRope (#37682)
Alexander Kalistratov20360a64d3c5
diff --git a/src/plugins/intel_npu/src/plugin/CMakeLists.txt b/src/plugins/intel_npu/src/plugin/CMakeLists.txtindex 224abea19db..f3f3c9de55b 100644--- a/src/plugins/intel_npu/src/plugin/CMakeLists.txt+++ b/src/plugins/intel_npu/src/plugin/CMakeLists.txt@@ -57,7 +57,7 @@ cross_compiled_file(${TARGET_NAME}ARCH AVX2 ANYnpuw/util_xarch.cppAPI npuw/util_xarch.hpp- NAME unpack_i4i8 unpack_u4i8 unpack_i4f16 unpack_i4f16_scale unpack_i4f16_z unpack_u4f16 unpack_u4f16_scale_zp unpack_u4f16_asymm_zp unpack_u4f16_z unpack_u4f32 unpack_i8f16 unpack_i8f16_scale unpack_i8f16_zp unpack_u8f16 to_f16 copy_row_as_column transpose_i4 transpose_f16 transpose_f32 unpack_f8f16_scale subtract_128+ NAME unpack_i4i8 unpack_u4i8 unpack_i4f16 unpack_i4f16_scale unpack_i4f16_z unpack_u4f16 unpack_u4f16_scale_zp unpack_u4f16_asymm_zp unpack_u4f16_z unpack_u4f32 unpack_i8f16 unpack_i8f16_scale unpack_i8f16_zp unpack_u8f16 to_f16 copy_row_as_column transpose_i4 transpose_f16 transpose_f32 unpack_f8f16_scale subtract_128 rerotate_f16_rowsNAMESPACE ov::npuw::util::XARCH)diff --git a/src/plugins/intel_npu/src/plugin/npuw/llm_block_kvcache_strategy.cpp b/src/plugins/intel_npu/src/plugin/npuw/llm_block_kvcache_strategy.cppindex 5d3d02c72a2..ef49cd0ac8a 100644--- a/src/plugins/intel_npu/src/plugin/npuw/llm_block_kvcache_strategy.cpp+++ b/src/plugins/intel_npu/src/plugin/npuw/llm_block_kvcache_strategy.cpp@@ -11,6 +11,7 @@#include "llm_compiled_model.hpp"#include "llm_infer_base_request.hpp"#include "llm_infer_request.hpp"+#include "llm_longrope_kv.hpp"#include "logging.hpp"#include "util.hpp"@@ -488,6 +489,60 @@ void LLMBlockKVCacheStrategy::on_generate_step_done(uint32_t input_tokens_len) {update_generate_bindings(tokens_before, tokens_after, m_req.m_kvcache_request);}+// The pool, not the request's ports, is where each cached key exists exactly once: a+// numbered port is a zero-copy view of a block, the tail port is a copy of one, and a+// port backing no token holds a dummy tensor shared with every other such port. So the+// blocks are turned directly and the tail copy is re-issued afterwards.+void LLMBlockKVCacheStrategy::rerotate_longrope_keys(const std::shared_ptr<ov::IAsyncInferRequest>& request,+ const PortsMap& /*in_ports*/,+ uint32_t num_cached_tokens,+ bool to_long) {+ OPENVINO_ASSERT(!m_kv_cache_block_managers.empty() && m_block_size > 0u,+ "NPUW: the LongRoPE mode changed but the block KV cache is not initialized.");++ std::vector<ov::npuw::longrope::KeyBlock> blocks;+ for (const auto& [layer_idx, layer_managers] : m_kv_cache_block_managers) {+ auto& manager = layer_managers.key_manager;+ if (!manager) {+ continue;+ }+ const auto allocated = manager->get_allocated_blocks();+ for (uint32_t first = 0u; first < num_cached_tokens; first += m_block_size) {+ const uint32_t block_idx = first / m_block_size;+ OPENVINO_ASSERT(block_idx < allocated.size(),+ "NPUW: the LongRoPE mode changed with ",+ num_cached_tokens,+ " cached tokens, but layer ",+ layer_idx,+ " holds only ",+ allocated.size(),+ " key blocks.");+ const uint32_t block_id = allocated[block_idx];+ const uint32_t live = std::min(num_cached_tokens - first, m_block_size);+ OPENVINO_ASSERT(manager->get_block_tokens(block_id) >= live,+ "NPUW: key block ",+ block_idx,+ " of layer ",+ layer_idx,+ " holds ",+ manager->get_block_tokens(block_id),+ " tokens where the LongRoPE mode change expects at least ",+ live,+ ".");+ blocks.push_back({manager->get_block_tensor(block_id), first, live});+ }+ }++ const auto& compiled = m_req.m_npuw_llm_compiled_model;+ ov::npuw::longrope::rerotate_cached_key_blocks(blocks,+ compiled->m_longrope_tables,+ compiled->m_kvcache_desc.dim,+ num_cached_tokens,+ m_req.m_first_position_id,+ to_long);+ refresh_key_tail_bindings(request);+}+// Continuing a prefill on the block pool truncates metadata only, since blocks// need no KV movement. Every manager in every layer is validated before any of// them changes.@@ -846,6 +901,37 @@ void LLMBlockKVCacheStrategy::update_generate_bindings(uint32_t old_num_tokens,// Private: KV copy engine// ============================================================================+void LLMBlockKVCacheStrategy::refresh_key_tail_bindings(const std::shared_ptr<ov::IAsyncInferRequest>& request) {+ const auto helpers_it = m_variant_block_binding_helpers.find(request);+ if (helpers_it == m_variant_block_binding_helpers.end()) {+ // The prefill request binds numbered blocks only, and does so at the next chunk+ // begin, so it reads the turned pool with nothing left to refresh.+ return;+ }+ const uint32_t kv_dim = m_req.m_npuw_llm_compiled_model->m_kvcache_desc.dim;+ for (const auto& [layer_idx, layer_managers] : m_kv_cache_block_managers) {+ auto& manager = layer_managers.key_manager;+ if (!manager) {+ continue;+ }+ const auto& helper = helpers_it->second.at(layer_idx).key_helper;+ if (!helper.has_tail_input()) {+ continue;+ }+ const auto allocated = manager->get_allocated_blocks();+ for (size_t block_idx = helper.numbered_input_ports.size(); block_idx < allocated.size(); ++block_idx) {+ const uint32_t block_id = allocated[block_idx];+ copy_block_to_tail_input(manager->get_block_tensor(block_id),+ 0u,+ manager->get_block_tokens(block_id),+ kv_dim,+ helper.tail_input_port.value(),+ request);+ LOG_VERB("Refreshed tail key layer_" << layer_idx << " block_" << block_idx << " after a LongRoPE turn");+ }+ }+}+void LLMBlockKVCacheStrategy::copy_outputs_to_blocks(const std::shared_ptr<ov::IAsyncInferRequest>& request,const PortsMap& src_ports,uint32_t num_tokens,diff --git a/src/plugins/intel_npu/src/plugin/npuw/llm_block_kvcache_strategy.hpp b/src/plugins/intel_npu/src/plugin/npuw/llm_block_kvcache_strategy.hppindex 4621fb6880c..a6af4506485 100644--- a/src/plugins/intel_npu/src/plugin/npuw/llm_block_kvcache_strategy.hpp+++ b/src/plugins/intel_npu/src/plugin/npuw/llm_block_kvcache_strategy.hpp@@ -20,6 +20,7 @@ namespace ov {namespace test {namespace npuw {struct LLMContinuedPrefillTestAccess;+struct LLMLongRopeModeTestAccess;} // namespace npuw} // namespace test} // namespace ov@@ -130,6 +131,11 @@ public:const PortsMap& new_in_ports) override;void on_generate_step_done(uint32_t input_tokens_len) override;+ void rerotate_longrope_keys(const std::shared_ptr<ov::IAsyncInferRequest>& request,+ const PortsMap& in_ports,+ uint32_t num_cached_tokens,+ bool to_long) override;+// Continuous prefill. Blocks need no KV movement, so the plan validates that the// retained prefix is fully covered by allocated blocks and the apply truncates the// block pool to it, releasing all suffix bindings.@@ -137,6 +143,7 @@ public:private:friend struct ov::test::npuw::LLMContinuedPrefillTestAccess;+ friend struct ov::test::npuw::LLMLongRopeModeTestAccess;// -------------------------------------------------------------------------// Private helper structs (used only during initialize())@@ -173,6 +180,12 @@ private:uint32_t new_num_tokens,const std::shared_ptr<ov::IAsyncInferRequest>& kvcache_request);+ // Re-issue the key tail copies of one generate variant. Unlike the numbered blocks,+ // which the request reads straight out of the pool, the tail port holds a copy that+ // an in-place rewrite of the pool would otherwise leave behind. A no-op for the+ // prefill request, which never fills its tail.+ void refresh_key_tail_bindings(const std::shared_ptr<ov::IAsyncInferRequest>& request);+// -------------------------------------------------------------------------// Prefill path primitives// -------------------------------------------------------------------------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 57ec02e1d73..150af1fa337 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@@ -1342,7 +1342,7 @@ ov::npuw::LLMCompiledModel::LLMCompiledModel(const std::shared_ptr<ov::Model>& m// The long factors are only worth materializing if a position can actually reach// the context limit and they differ from the short ones - models that declare// LongRoPE but set the limit at (or beyond) their whole context, or repeat the- // same factors twice, always run in the short regime.+ // same factors twice, always run in the short mode.m_longrope_tables.has_long = m_longrope_context_limit < m_longrope_tables.max_len &&m_longrope_tables.inv_freq_long != m_longrope_tables.inv_freq_short;if (m_longrope_tables.rotary_ndims > 0 && !m_longrope_tables.has_long) {@@ -1441,6 +1441,20 @@ ov::npuw::LLMCompiledModel::LLMCompiledModel(const std::shared_ptr<ov::Model>& m}}+ // A LongRoPE model can flip between its short- and its long-factor coefficients in+ // the middle of a conversation, and NPUW repairs that by re-rotating the cached keys+ // in place (llm_longrope_kv.hpp). That rewrite needs a non-quantized key cache.+ // Where it cannot run there is no correct fallback - the cache would stay in the old+ // rotation frame and every answer past the crossing would be garbage - so refuse the+ // combination here rather than at the crossing token.+ if (m_longrope_tables.has_long) {+ OPENVINO_ASSERT(kv_kache_storage_type == ov::element::f16 || kv_kache_storage_type == ov::element::f32,+ "NPUW: a ",+ kv_kache_storage_type,+ " KV cache cannot be re-rotated when the LongRoPE mode changes. "+ "Use an f16 or f32 KV cache for this model.");+ }+// Duplicate shared K/V broadcast chains in the prefill model so that each downstream// SDPA gets its own independent Concat chain. This enables TagSDPA/SDPADecomposed to// isolate and convert each SDPA to HFA independently (e.g. Gemma-4 L15–L34 reusediff --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 f01a359ee46..ef0461b336e 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,7 @@ namespace npuw {struct LLMVariantSwitchTestAccess;struct LLMTrimKVCacheTestAccess;struct LLMContinuedPrefillTestAccess;+struct LLMLongRopeModeTestAccess;struct LLMSwaCacheTestAccess;} // namespace npuw} // namespace test@@ -97,6 +98,7 @@ protected:friend struct ov::test::npuw::LLMVariantSwitchTestAccess;friend struct ov::test::npuw::LLMTrimKVCacheTestAccess;friend struct ov::test::npuw::LLMContinuedPrefillTestAccess;+ friend struct ov::test::npuw::LLMLongRopeModeTestAccess;friend struct ov::test::npuw::LLMSwaCacheTestAccess;friend class EncoderEmbeddingInferRequest;diff --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 ae1a051ca90..9aa95454c03 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@@ -8,6 +8,7 @@#include "infer_request_utils.hpp"#include "llm_infer_request.hpp"+#include "llm_longrope_kv.hpp"#include "logging.hpp"#include "openvino/core/parallel.hpp"#include "util.hpp"@@ -153,6 +154,23 @@ void LLMContinuousKVCacheStrategy::on_generate_step_done(uint32_t input_tokens_lv_transposed);}+// Each layer keeps its whole past in one tensor whose row r is the key of position+// first_position_id + r, which is exactly the shape the flat rewrite expects.+void LLMContinuousKVCacheStrategy::rerotate_longrope_keys(const std::shared_ptr<ov::IAsyncInferRequest>& request,+ const PortsMap& in_ports,+ uint32_t num_cached_tokens,+ bool to_long) {+ const auto& compiled = m_req.m_npuw_llm_compiled_model;+ ov::npuw::longrope::rerotate_cached_keys(request,+ in_ports,+ m_req.m_kvcache_past_names,+ compiled->m_longrope_tables,+ compiled->m_kvcache_desc.dim,+ num_cached_tokens,+ m_req.m_first_position_id,+ to_long);+}+namespace {// Per-tensor repack geometry, analyzed during validation so the parallel copydiff --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 af3ed2d7846..de1c5775c13 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@@ -39,6 +39,11 @@ public:const PortsMap& new_in_ports) override;void on_generate_step_done(uint32_t input_tokens_len) override;+ void rerotate_longrope_keys(const std::shared_ptr<ov::IAsyncInferRequest>& request,+ const PortsMap& in_ports,+ uint32_t num_cached_tokens,+ bool to_long) 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;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.cppindex 0eb425249d5..40d43592015 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@@ -227,7 +227,7 @@ size_t scatter_deepstack_visual_embeds(const ov::SoPtr<ov::ITensor>& src,// Points the npuw_lr_cos/npuw_lr_sin model inputs the LongRoPE RoPE-cache rewrite// created (see RopeCacheMatcher, pre_compute.cpp) at the precomputed coefficient rows-// of the applicable regime. Those inputs are the model's only source of RoPE+// of the applicable mode. Those inputs are the model's only source of RoPE// coefficients, so the short/long-factor choice the graph used to make with an in-graph// Select is made here instead - by the same criterion:// max(position_ids) + 1 > original_max_position_embeddings.@@ -235,9 +235,10 @@ size_t scatter_deepstack_visual_embeds(const ov::SoPtr<ov::ITensor>& src,// Binding is by pointer into the compiled model's own tables, which outlive this// request - no coefficients are copied per inference.//-// A no-op for models without those inputs (not a LongRoPE model, or the RoPE cache pass-// didn't run).-void process_longrope_tables(const std::shared_ptr<ov::IAsyncInferRequest>& infer_req,+// Returns the mode picked for this call, so the caller can notice a flip against the+// one the cached keys were rotated with. A no-op returning false for models without+// those inputs (not a LongRoPE model, or the RoPE cache pass didn't run).+bool process_longrope_tables(const std::shared_ptr<ov::IAsyncInferRequest>& infer_req,const LLMInferRequest::PortsMap& ports,ov::npuw::patterns::pre_compute::LongRopeCosSin& tables,const ov::SoPtr<ov::ITensor>& position_ids,@@ -247,7 +248,7 @@ void process_longrope_tables(const std::shared_ptr<ov::IAsyncInferRequest>& infeconst auto cos_port_it = ports.find(pc::longrope_cos_input);const auto sin_port_it = ports.find(pc::longrope_sin_input);if (cos_port_it == ports.end() || sin_port_it == ports.end()) {- return;+ return false;}// The graph has no other cos/sin source, so missing tables would silently produce// garbage instead of failing. This guards an imported blob whose LongRoPE metadata@@ -266,6 +267,7 @@ void process_longrope_tables(const std::shared_ptr<ov::IAsyncInferRequest>& infeinfer_req->set_tensor(cos_port_it->second, ov::get_tensor_impl(tables.cos_rows(lut_len, is_long)));infer_req->set_tensor(sin_port_it->second, ov::get_tensor_impl(tables.sin_rows(lut_len, is_long)));+ return is_long;}} // anonymous namespace@@ -1322,6 +1324,33 @@ void ov::npuw::LLMInferRequest::infer_whole_prefill(ov::SoPtr<ov::ITensor> inputLOG_DEBUG("Done");}+void ov::npuw::LLMInferRequest::sync_longrope_mode(const std::shared_ptr<ov::IAsyncInferRequest>& request,+ const PortsMap& in_ports,+ const ov::SoPtr<ov::ITensor>& position_ids,+ uint32_t num_cached_tokens) {+ const bool is_long = process_longrope_tables(request,+ in_ports,+ m_npuw_llm_compiled_model->m_longrope_tables,+ position_ids,+ m_npuw_llm_compiled_model->m_longrope_context_limit);+ if (is_long == m_longrope_long_mode) {+ return;+ }++ if (num_cached_tokens > 0u && m_npuw_llm_compiled_model->m_longrope_tables.has_long) {+ // The KV layouts this rewrite cannot turn are rejected when the model is+ // compiled (see LLMCompiledModel), so a crossing that gets this far has to+ // succeed for every live key: the strategy throws rather than leave the cache+ // half-turned, and m_longrope_long_mode below is only reached once it did not.+ m_llm_profile["longrope:rerotate_kv"].record([&]() {+ m_kvcache_strategy->rerotate_longrope_keys(request, in_ports, num_cached_tokens, is_long);+ });+ }++ // Only now do the cached keys really belong to this mode.+ m_longrope_long_mode = is_long;+}+void ov::npuw::LLMInferRequest::infer_prefill(ov::SoPtr<ov::ITensor> input_ids,ov::SoPtr<ov::ITensor> attention_mask,ov::SoPtr<ov::ITensor> position_ids,@@ -1351,13 +1380,11 @@ void ov::npuw::LLMInferRequest::infer_prefill(ov::SoPtr<ov::ITensor> input_ids,}});- // One regime decision for the whole logical prompt - chunked prefill reuses it, as- // the in-graph Select did when it was fed from these same position_ids.- process_longrope_tables(m_prefill_request,- m_prefill_in_ports,- m_npuw_llm_compiled_model->m_longrope_tables,- position_ids,- m_npuw_llm_compiled_model->m_longrope_context_limit);+ // One mode decision for the whole logical prompt - chunked prefill reuses it, as+ // the in-graph Select did when it was fed from these same position_ids. A fresh+ // conversation starts with a zeroed cache, so only a continued prefill can carry+ // keys rotated under the other mode into this call.+ sync_longrope_mode(m_prefill_request, m_prefill_in_ports, position_ids, m_continued_prefill_base);m_llm_profile["1/prefill:2.apply_lora"].record([&]() {apply_lora();@@ -1559,11 +1586,10 @@ void ov::npuw::LLMInferRequest::infer_generate(ov::SoPtr<ov::ITensor> input_ids,// No visual tokens are generated during the generate stagestd::fill_n(reinterpret_cast<uint8_t*>(deepstack_local->data()), deepstack_local->get_byte_size(), 0);}- process_longrope_tables(m_kvcache_request,- m_kvcache_in_ports,- m_npuw_llm_compiled_model->m_longrope_tables,- position_ids,- m_npuw_llm_compiled_model->m_longrope_context_limit);+ // The generate model's past-key inputs already hold the whole conversation at+ // this point, so a crossing of the context limit is repaired here rather than+ // leaving the cache rotated with coefficients this step no longer uses.+ sync_longrope_mode(m_kvcache_request, m_kvcache_in_ports, position_ids, kvcache_desc.num_stored_tokens);// FIXME: these tensors should be shared between the parent & child models// NB: input_ids can be either fp32(VLM) or i64(LLM)auto kv_input_ids = m_kvcache_request->get_tensor(m_kvcache_in_ports.at(m_input_ids_name));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 43405358d00..d1bc4d1f757 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@@ -26,6 +26,7 @@ struct LLMVariantSwitchTestAccess;struct LLMTrimKVCacheTestAccess;struct LLMPortNameRegistrationTestAccess;struct LLMContinuedPrefillTestAccess;+struct LLMLongRopeModeTestAccess;struct LLMSwaCacheTestAccess;} // namespace npuw} // namespace test@@ -114,6 +115,24 @@ protected:ov::SoPtr<ov::ITensor> position_ids,ov::SoPtr<ov::ITensor> per_layer_inputs);+ // Picks the LongRoPE mode for this call from position_ids, points the stage's+ // npuw_lr_cos/npuw_lr_sin inputs at that mode's coefficients, and - when the choice+ // flipped mid-conversation - turns the num_cached_tokens keys already in `request` by+ // the angle difference between the modes instead of dropping them; see+ // llm_longrope_kv.hpp. A no-op for models without those inputs.+ //+ // The two halves are never done separately: coefficients bound without the cache+ // turned to match is exactly the corruption this path exists to prevent. That also+ // fixes where it can be called from - each stage must first have the conversation's+ // KV in `request`, which only happens inside infer_prefill()/infer_generate().+ //+ // Throws if the flip cannot be carried out in full, leaving m_longrope_long_mode+ // describing the mode the cache is actually in.+ void sync_longrope_mode(const std::shared_ptr<ov::IAsyncInferRequest>& request,+ const PortsMap& in_ports,+ const ov::SoPtr<ov::ITensor>& position_ids,+ uint32_t num_cached_tokens);+// 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@@ -185,6 +204,10 @@ protected:bool m_first_run = true;+ // Whether the currently cached keys were rotated with the long-factor LongRoPE+ // coefficients. Meaningless for models without LongRoPE, where it stays false.+ bool m_longrope_long_mode = false;+int64_t m_first_position_id = 0;uint64_t m_tokens_in_present_chunk = 0;@@ -237,6 +260,7 @@ protected:friend struct ov::test::npuw::LLMTrimKVCacheTestAccess;friend struct ov::test::npuw::LLMPortNameRegistrationTestAccess;friend struct ov::test::npuw::LLMContinuedPrefillTestAccess;+ friend struct ov::test::npuw::LLMLongRopeModeTestAccess;friend struct ov::test::npuw::LLMSwaCacheTestAccess;};diff --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 0a5f2628fb5..d4ec031cd71 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,18 @@ 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;+ // Turn the keys already in the cache into the LongRoPE mode the next infer() will+ // rotate its queries and its new keys with, after that choice flipped mid-conversation.+ // `num_cached_tokens` rows are rewritten in place; where those rows live is what the+ // two strategies disagree on, hence the dispatch. See llm_longrope_kv.hpp.+ //+ // All or nothing: an implementation that cannot complete the turn throws having+ // written nothing, so the caller's record of which mode the cache is in stays true.+ virtual void rerotate_longrope_keys(const std::shared_ptr<ov::IAsyncInferRequest>& request,+ const PortsMap& in_ports,+ uint32_t num_cached_tokens,+ bool to_long) = 0;+// Continuous prefill support.// Continue a prefill that keeps the first `keep` tokens and will prefilldiff --git a/src/plugins/intel_npu/src/plugin/npuw/llm_longrope_kv.cpp b/src/plugins/intel_npu/src/plugin/npuw/llm_longrope_kv.cppnew file mode 100644index 00000000000..f0d58e5373d--- /dev/null+++ b/src/plugins/intel_npu/src/plugin/npuw/llm_longrope_kv.cpp@@ -0,0 +1,306 @@+// Copyright (C) 2018-2026 Intel Corporation+// SPDX-License-Identifier: Apache-2.0+//++#include "llm_longrope_kv.hpp"++#include "logging.hpp"+#include "openvino/core/parallel.hpp"+#include "openvino/core/type/float16.hpp"+#include "util.hpp"+#include "util_xarch.hpp"++namespace {++// Turns one rotate_half key row: components j and j + half belong to the same plane.+template <typename T>+void rerotate_row(T* row, const float* delta_cos, const float* delta_sin, size_t half) {+ for (size_t j = 0; j < half; ++j) {+ const float a = static_cast<float>(row[j]);+ const float b = static_cast<float>(row[j + half]);+ row[j] = static_cast<T>(a * delta_cos[j] - b * delta_sin[j]);+ row[j + half] = static_cast<T>(b * delta_cos[j] + a * delta_sin[j]);+ }+}++template <typename T>+void rerotate_planes(T* data,+ size_t outer,+ size_t seq_len,+ size_t seq_stride,+ size_t rows_per_token,+ size_t head_dim,+ size_t num_tokens,+ const float* delta_cos,+ const float* delta_sin,+ size_t half) {+ for (size_t o = 0; o < outer; ++o) {+ T* plane = data + o * seq_len * seq_stride;+ for (size_t t = 0; t < num_tokens; ++t) {+ const float* dcos = delta_cos + t * half;+ const float* dsin = delta_sin + t * half;+ T* token = plane + t * seq_stride;+ for (size_t r = 0; r < rows_per_token; ++r) {+ rerotate_row(token + r * head_dim, dcos, dsin, half);+ }+ }+ }+}++} // anonymous namespace++ov::npuw::longrope::ModeDelta ov::npuw::longrope::make_mode_delta(+ ov::npuw::patterns::pre_compute::LongRopeCosSin& tables,+ int64_t first_position_id,+ uint32_t num_tokens,+ bool to_long) {+ ModeDelta delta;+ if (num_tokens == 0u || !tables.has_long) {+ // Without a distinct long-factor set both modes share the same coefficients,+ // so a flip changes nothing about the cached keys.+ return delta;+ }+ OPENVINO_ASSERT(tables.is_valid(), "NPUW: LongRoPE mode flipped but the cos/sin tables are missing.");++ const size_t rotary_ndims = tables.rotary_ndims;+ OPENVINO_ASSERT(rotary_ndims % 2u == 0u, "NPUW: LongRoPE rotary dimension must be even.");+ OPENVINO_ASSERT(first_position_id >= 0 && static_cast<size_t>(first_position_id) + num_tokens <= tables.max_len,+ "NPUW: cached LongRoPE positions [",+ first_position_id,+ ", ",+ first_position_id + num_tokens,+ ") fall outside the coefficient tables (",+ tables.max_len,+ " rows).");++ delta.half = rotary_ndims / 2u;+ delta.cos.resize(static_cast<size_t>(num_tokens) * delta.half);+ delta.sin.resize(static_cast<size_t>(num_tokens) * delta.half);++ // Row p of either mode holds the coefficients of absolute position p.+ auto cos_old = tables.cos_rows(tables.max_len, !to_long);+ auto sin_old = tables.sin_rows(tables.max_len, !to_long);+ auto cos_new = tables.cos_rows(tables.max_len, to_long);+ auto sin_new = tables.sin_rows(tables.max_len, to_long);++ const size_t skip = static_cast<size_t>(first_position_id) * rotary_ndims;+ const auto* co = cos_old.data<ov::float16>() + skip;+ const auto* so = sin_old.data<ov::float16>() + skip;+ const auto* cn = cos_new.data<ov::float16>() + skip;+ const auto* sn = sin_new.data<ov::float16>() + skip;++ // Rows are independent; at the context limit this is ~200K of them.+ ov::parallel_for(num_tokens, [&](size_t t) {+ for (size_t j = 0; j < delta.half; ++j) {+ const float c_old = static_cast<float>(co[t * rotary_ndims + j]);+ const float s_old = static_cast<float>(so[t * rotary_ndims + j]);+ const float c_new = static_cast<float>(cn[t * rotary_ndims + j]);+ const float s_new = static_cast<float>(sn[t * rotary_ndims + j]);+ const float norm = c_old * c_old + s_old * s_old;+ delta.cos[t * delta.half + j] = (c_new * c_old + s_new * s_old) / norm;+ delta.sin[t * delta.half + j] = (s_new * c_old - c_new * s_old) / norm;+ }+ });+ return delta;+}++void ov::npuw::longrope::rerotate_keys(const KeyTensorLayout& layout,+ uint32_t num_tokens,+ const ModeDelta& delta,+ size_t delta_row_offset) {+ if (delta.half == 0u || num_tokens == 0u) {+ return;+ }+ OPENVINO_ASSERT((delta_row_offset + num_tokens) * delta.half <= delta.cos.size(),+ "NPUW: LongRoPE delta rows [",+ delta_row_offset,+ ", ",+ delta_row_offset + num_tokens,+ ") fall outside the delta built for this transition.");+ const float* delta_cos = delta.cos.data() + delta_row_offset * delta.half;+ const float* delta_sin = delta.sin.data() + delta_row_offset * delta.half;+ if (layout.type == ov::element::f16) {+ // f16 goes through the SIMD kernel: expressed with ov::float16 the loop would+ // spend all its time in that class's out-of-line float conversions.+ auto* data = static_cast<uint16_t*>(layout.data);+ for (size_t o = 0; o < layout.outer; ++o) {+ ov::npuw::util::XARCH::rerotate_f16_rows(data + o * layout.seq_len * layout.seq_stride,+ num_tokens,+ layout.seq_stride,+ layout.rows_per_token,+ layout.head_dim,+ delta_cos,+ delta_sin,+ delta.half);+ }+ } else {+ rerotate_planes(static_cast<float*>(layout.data),+ layout.outer,+ layout.seq_len,+ layout.seq_stride,+ layout.rows_per_token,+ layout.head_dim,+ num_tokens,+ delta_cos,+ delta_sin,+ delta.half);+ }+}++ov::npuw::longrope::KeyTensorLayout ov::npuw::longrope::check_key_tensor(const ov::SoPtr<ov::ITensor>& tensor,+ uint32_t seq_dim,+ uint32_t num_tokens,+ const ModeDelta& delta) {+ OPENVINO_ASSERT(tensor, "NPUW: a past-key input of a LongRoPE model has no tensor bound to it.");++ const auto type = tensor->get_element_type();+ // A quantized cache cannot be turned without dequantizing it first, and no other+ // element type reaches the kernels below.+ OPENVINO_ASSERT(type == ov::element::f16 || type == ov::element::f32,+ "NPUW: a LongRoPE mode change cannot re-rotate a KV cache of element type ",+ type,+ "; only f16 and f32 caches can be turned in place.");++ const auto& shape = tensor->get_shape();+ const size_t rank = shape.size();+ OPENVINO_ASSERT(rank >= 2u && seq_dim + 1u < rank,+ "NPUW: unexpected past-key layout for LongRoPE re-rotation: sequence axis ",+ seq_dim,+ " of a rank-",+ rank,+ " tensor.");+ const size_t head_dim = shape[rank - 1];+ OPENVINO_ASSERT(head_dim >= delta.half * 2u,+ "NPUW: past-key head dimension ",+ head_dim,+ " is smaller than the rotary dimension ",+ delta.half * 2u,+ ".");+ const size_t seq_len = shape[seq_dim];+ OPENVINO_ASSERT(num_tokens <= seq_len, "NPUW: more cached tokens than the past-key tensor can hold.");++ // Rows are addressed arithmetically from a single base pointer, which holds only+ // for a canonically packed tensor. Checking the sequence stride alone is not+ // enough: a view that crops the sequence axis keeps its parent's outer strides, so+ // every plane past the first would be read at the wrong offset. Demand the whole+ // row-major stride vector instead.+ const auto& strides = tensor->get_strides();+ OPENVINO_ASSERT(strides.size() == rank,+ "NPUW: past-key tensor reports ",+ strides.size(),+ " strides for rank ",+ rank,+ ".");+ size_t dense_stride = type.size();+ for (size_t d = rank; d-- > 0;) {+ OPENVINO_ASSERT(strides[d] == dense_stride,+ "NPUW: past-key tensor is not densely packed (stride ",+ strides[d],+ " at axis ",+ d,+ ", expected ",+ dense_stride,+ "), cannot re-rotate in place.");+ dense_stride *= shape[d];+ }++ size_t seq_stride = 1u;+ for (size_t d = seq_dim + 1u; d < rank; ++d) {+ seq_stride *= shape[d];+ }++ KeyTensorLayout layout;+ // Resolving the pointer here is itself a check: a device-side tensor that cannot be+ // mapped to the host throws, and it does so before any other layer was touched.+ layout.data = tensor->data();+ layout.type = type;+ layout.outer = tensor->get_size() / (seq_len * seq_stride);+ layout.seq_len = seq_len;+ layout.seq_stride = seq_stride;+ layout.rows_per_token = seq_stride / head_dim;+ layout.head_dim = head_dim;+ return layout;+}++void ov::npuw::longrope::rerotate_keys(const ov::SoPtr<ov::ITensor>& tensor,+ uint32_t seq_dim,+ uint32_t num_tokens,+ const ModeDelta& delta) {+ if (delta.half == 0u || num_tokens == 0u) {+ return;+ }+ rerotate_keys(check_key_tensor(tensor, seq_dim, num_tokens, delta), num_tokens, delta);+}++void ov::npuw::longrope::rerotate_cached_keys(const std::shared_ptr<ov::IAsyncInferRequest>& request,+ const PortsMap& in_ports,+ const std::vector<std::string>& past_kv_names,+ ov::npuw::patterns::pre_compute::LongRopeCosSin& tables,+ uint32_t seq_dim,+ uint32_t num_tokens,+ int64_t first_position_id,+ bool to_long) {+ const auto delta = make_mode_delta(tables, first_position_id, num_tokens, to_long);+ if (delta.half == 0u) {+ return;+ }++ // Resolve and check every live key first. Anything that throws does so here, with+ // the cache still wholly in the previous mode and the caller's mode flag not+ // yet advanced.+ std::vector<KeyTensorLayout> layouts;+ layouts.reserve(past_kv_names.size());+ for (const auto& name : past_kv_names) {+ if (!ov::npuw::util::isPastKeyParam(name)) {+ continue;+ }+ const auto port_it = in_ports.find(name);+ OPENVINO_ASSERT(port_it != in_ports.end(),+ "NPUW: past-key input ",+ name,+ " is missing from the request the LongRoPE mode change has to re-rotate.");+ layouts.push_back(check_key_tensor(request->get_tensor(port_it->second), seq_dim, num_tokens, delta));+ }++ LOG_DEBUG("Re-rotating " << num_tokens << " cached keys of " << layouts.size() << " layers into the "+ << (to_long ? "long" : "short") << "-factor LongRoPE mode.");++ ov::parallel_for(layouts.size(), [&](size_t idx) {+ rerotate_keys(layouts[idx], num_tokens, delta);+ });+}++void ov::npuw::longrope::rerotate_cached_key_blocks(const std::vector<KeyBlock>& blocks,+ ov::npuw::patterns::pre_compute::LongRopeCosSin& tables,+ uint32_t seq_dim,+ uint32_t num_cached_tokens,+ int64_t first_position_id,+ bool to_long) {+ // One delta for the whole conversation; each block reads the rows its own positions+ // land on, so the blocks need not be contiguous or in any particular order.+ const auto delta = make_mode_delta(tables, first_position_id, num_cached_tokens, to_long);+ if (delta.half == 0u) {+ return;+ }++ std::vector<KeyTensorLayout> layouts;+ layouts.reserve(blocks.size());+ for (const auto& block : blocks) {+ OPENVINO_ASSERT(static_cast<size_t>(block.first_token) + block.num_tokens <= num_cached_tokens,+ "NPUW: a key block covering tokens [",+ block.first_token,+ ", ",+ block.first_token + block.num_tokens,+ ") reaches past the ",+ num_cached_tokens,+ " tokens the LongRoPE mode change was given.");+ layouts.push_back(check_key_tensor(block.tensor, seq_dim, block.num_tokens, delta));+ }++ LOG_DEBUG("Re-rotating " << num_cached_tokens << " cached keys held in " << layouts.size() << " blocks into the "+ << (to_long ? "long" : "short") << "-factor LongRoPE mode.");++ ov::parallel_for(layouts.size(), [&](size_t idx) {+ rerotate_keys(layouts[idx], blocks[idx].num_tokens, delta, blocks[idx].first_token);+ });+}diff --git a/src/plugins/intel_npu/src/plugin/npuw/llm_longrope_kv.hpp b/src/plugins/intel_npu/src/plugin/npuw/llm_longrope_kv.hppnew file mode 100644index 00000000000..f5df4f37836--- /dev/null+++ b/src/plugins/intel_npu/src/plugin/npuw/llm_longrope_kv.hpp@@ -0,0 +1,140 @@+// Copyright (C) 2018-2026 Intel Corporation+// SPDX-License-Identifier: Apache-2.0+//++#pragma once++#include <cstdint>+#include <memory>+#include <string>+#include <unordered_map>+#include <vector>++#include "openvino/core/descriptor/output.hpp"+#include "openvino/core/type/element_type.hpp"+#include "openvino/runtime/iasync_infer_request.hpp"+#include "openvino/runtime/itensor.hpp"+#include "openvino/runtime/so_ptr.hpp"+#include "partitioning/patterns/pre_compute.hpp"++namespace ov {+namespace npuw {+namespace longrope {++using PortsMap = std::unordered_map<std::string, ov::Output<const ov::Node>>;++// The rotation that carries a key already rotated under one LongRoPE mode to the one+// it would have had under the other. Laid out as num_tokens rows of rotary_ndims/2+// planes, row r belonging to the key cached at row r.+struct ModeDelta {+ std::vector<float> cos;+ std::vector<float> sin;+ size_t half = 0; // planes per row; 0 means "nothing to do"+};++// Builds the delta for cached rows [0, num_tokens), whose absolute positions start at+// first_position_id.+//+// The rotation is the complex quotient of the two modes' coefficients:+//+// k' = k * (cos_new + i*sin_new) / (cos_old + i*sin_old)+//+// The quotient - rather than the plain difference of the two angles - is what inverts+// the f16 table values the graph actually used, whose magnitude is only approximately+// one.+//+// Returns an empty delta (half == 0) when the two modes share their coefficients.+ModeDelta make_mode_delta(patterns::pre_compute::LongRopeCosSin& tables,+ int64_t first_position_id,+ uint32_t num_tokens,+ bool to_long);++// One past-key tensor resolved down to what the rewrite actually walks: a host pointer+// plus the plane/row geometry derived from its shape. Produced by check_key_tensor(),+// which is the only place that may reject a tensor - once a layout exists the rewrite+// is pure arithmetic and cannot fail.+struct KeyTensorLayout {+ void* data = nullptr;+ ov::element::Type type;+ size_t outer = 0; // planes before the sequence axis+ size_t seq_len = 0; // entries along the sequence axis+ size_t seq_stride = 0; // elements per sequence entry+ size_t rows_per_token = 0; // head rows inside one sequence entry+ size_t head_dim = 0;+};++// Resolves one past-key tensor and throws unless the delta can be applied to it in+// place. Checks the element type, host accessibility, that the tensor is long enough,+// and that it is fully densely packed - rerotate_keys() addresses rows by plain+// pointer arithmetic, which a strided or padded tensor would silently send to the+// wrong offsets.+KeyTensorLayout check_key_tensor(const ov::SoPtr<ov::ITensor>& tensor,+ uint32_t seq_dim,+ uint32_t num_tokens,+ const ModeDelta& delta);++// Applies the delta in place to the leading num_tokens sequence entries of one densely+// packed past-key tensor, turning the rotate_half pair (j, j + half) of every head.+// Channels beyond 2 * delta.half are pass-through in a partial-rotary model and were+// never rotated, so they are left alone.+//+// delta_row_offset says which delta row the tensor's row 0 holds: zero for a cache that+// starts at the beginning of the conversation, the block's own offset for one block of a+// block-based cache.+void rerotate_keys(const KeyTensorLayout& layout,+ uint32_t num_tokens,+ const ModeDelta& delta,+ size_t delta_row_offset = 0u);++// check_key_tensor() + rerotate_keys() for a single tensor.+void rerotate_keys(const ov::SoPtr<ov::ITensor>& tensor, uint32_t seq_dim, uint32_t num_tokens, const ModeDelta& delta);++// Rewrites every past-key input of the request into the requested mode.+//+// A LongRoPE model rotates with the short- or the long-factor coefficients depending on+// the current maximum position, so a cache filled under one mode stops matching the+// queries the moment that choice flips mid-conversation. Instead of dropping the cache,+// its keys are turned by the difference between the two modes - see make_mode_delta.+// Values carry no rotation and are left alone.+//+// All or nothing: every past-key port is resolved and checked before the first byte is+// written, and anything that cannot be rewritten throws. A cache turned only in part+// would leave the model comparing queries and keys in two different rotation frames -+// exactly the corruption this path exists to prevent - so there is no useful weaker+// outcome to report.+void rerotate_cached_keys(const std::shared_ptr<ov::IAsyncInferRequest>& request,+ const PortsMap& in_ports,+ const std::vector<std::string>& past_kv_names,+ patterns::pre_compute::LongRopeCosSin& tables,+ uint32_t seq_dim,+ uint32_t num_tokens,+ int64_t first_position_id,+ bool to_long);++// One key block of a block-based cache: the block's own tensor, plus where its rows sit+// in the conversation. first_token is the index within the cache of the block's row 0,+// num_tokens the number of live rows it holds.+struct KeyBlock {+ ov::SoPtr<ov::ITensor> tensor;+ uint32_t first_token = 0;+ uint32_t num_tokens = 0;+};++// rerotate_cached_keys() for a block-based cache, whose keys live in a pool of+// fixed-size blocks rather than in one tensor per layer.+//+// Takes the blocks themselves rather than the request's ports: in block mode a port is+// either a zero-copy view of a pooled block, a copy of one, or a dummy tensor shared by+// every port that currently backs no token, so the pool is the only place where each+// cached key exists exactly once. Every block is resolved and checked before the first+// byte is written, as in the flat case.+void rerotate_cached_key_blocks(const std::vector<KeyBlock>& blocks,+ patterns::pre_compute::LongRopeCosSin& tables,+ uint32_t seq_dim,+ uint32_t num_cached_tokens,+ int64_t first_position_id,+ bool to_long);++} // namespace longrope+} // namespace npuw+} // namespace ovdiff --git a/src/plugins/intel_npu/src/plugin/npuw/partitioning/patterns/pre_compute.cpp b/src/plugins/intel_npu/src/plugin/npuw/partitioning/patterns/pre_compute.cppindex 7ddbfd4a50d..bc01a6b17fe 100644--- a/src/plugins/intel_npu/src/plugin/npuw/partitioning/patterns/pre_compute.cpp+++ b/src/plugins/intel_npu/src/plugin/npuw/partitioning/patterns/pre_compute.cpp@@ -366,7 +366,7 @@ uint64_t read_context_limit(const std::shared_ptr<ov::Node>& limit_node) {return static_cast<uint64_t>(limit_values.front());}-// The regime switch is re-evaluated on the host as max(position_ids) >= context_limit,+// The mode switch is re-evaluated on the host as max(position_ids) >= context_limit,// which only reproduces the graph's `max(position_ids) + offset` comparison for an// offset of exactly 1. The matchers accept any constant there, so refuse to rewrite a// model whose offset differs rather than silently binding the wrong coefficients.@@ -419,7 +419,7 @@ ov::npuw::patterns::pre_compute::RopeCacheMatcher::RopeCacheMatcher(const uint32rpe->run_on_model(model);// LongRoPE cos/sin LUTs are model inputs, not Constants: the host picks the- // short/long factor regime and binds the matching rows, so no in-graph Select - and+ // short/long factor mode and binds the matching rows, so no in-graph Select - and// hence no npuw_longrope_input scalar - is created for either LongRoPE pattern.std::shared_ptr<ov::op::v0::Parameter> lr_cos_param;std::shared_ptr<ov::op::v0::Parameter> lr_sin_param;@@ -523,8 +523,8 @@ void ov::npuw::patterns::pre_compute::LongRopeCosSin::rebuild_tables() {if (max_len == 0 || rotary_ndims == 0 || inv_freq_short.empty()) {return;}- const size_t regimes = has_long ? 2u : 1u;- const ov::Shape shape{1, regimes * max_len, rotary_ndims};+ const size_t modes = has_long ? 2u : 1u;+ const ov::Shape shape{1, modes * max_len, rotary_ndims};cos = ov::Tensor(ov::element::f16, shape);sin = ov::Tensor(ov::element::f16, shape);diff --git a/src/plugins/intel_npu/src/plugin/npuw/partitioning/patterns/pre_compute.hpp b/src/plugins/intel_npu/src/plugin/npuw/partitioning/patterns/pre_compute.hppindex 9ce93c1b91b..e365a881649 100644--- a/src/plugins/intel_npu/src/plugin/npuw/partitioning/patterns/pre_compute.hpp+++ b/src/plugins/intel_npu/src/plugin/npuw/partitioning/patterns/pre_compute.hpp@@ -117,22 +117,22 @@ constexpr const char* longrope_sin_input = "npuw_lr_sin";// Nothing here aliases compiled-blob memory - a driver is free to repack the constants// it is given, so host data must never be assumed to still match them.//-// Both regimes live in ONE tensor per trig function, [1, regimes * max_len,+// Both modes live in ONE tensor per trig function, [1, modes * max_len,// rotary_ndims]: the short-factor rows first, the long-factor rows after. Because row i// means position i regardless of the variant, a leading slice of either half serves// prefill and every generate variant, whatever their individual LUT lengths - so// LLMCompiledModel keeps a single instance sized to the longest LUT in the model.//-// The long half is omitted altogether (has_long == false) when the long regime cannot+// The long half is omitted altogether (has_long == false) when the long mode cannot// be reached - the context limit is at or beyond the longest LUT - or when the two// factor sets are numerically identical, which is the case for models that declare-// LongRoPE but never actually switch (e.g. MiniCPM). Both regimes then bind the same+// LongRoPE but never actually switch (e.g. MiniCPM). Both modes then bind the same// rows.//// Only max_len/rotary_ndims/has_long and the two inverse-frequency arrays go to the// blob; rebuild_tables() regenerates the tensors on import.struct LongRopeCosSin {- size_t max_len = 0; // rows per regime; == the longest sin/cos LUT in the model+ size_t max_len = 0; // rows per mode; == the longest sin/cos LUT in the modelsize_t rotary_ndims = 0; // row width; 0 means "no LongRoPE in this model"bool has_long = false;@@ -151,7 +151,7 @@ struct LongRopeCosSin {// frequency arrays. Used both at compile time and on blob import.void rebuild_tables();- // Dense, non-owning views over the first lut_len rows of the requested regime.+ // Dense, non-owning views over the first lut_len rows of the requested mode.// The backing tensors must outlive them. Non-const because NPUW's input binding// path reaches for a writable data pointer.ov::Tensor cos_rows(size_t lut_len, bool is_long);diff --git a/src/plugins/intel_npu/src/plugin/npuw/util_xarch.cpp b/src/plugins/intel_npu/src/plugin/npuw/util_xarch.cppindex 40450055758..457350b8615 100644--- a/src/plugins/intel_npu/src/plugin/npuw/util_xarch.cpp+++ b/src/plugins/intel_npu/src/plugin/npuw/util_xarch.cpp@@ -8,6 +8,7 @@#include <openvino/core/parallel.hpp>+#include "openvino/core/type/float16.hpp"#include "util.hpp"#include "util_xarch.hpp"@@ -2035,3 +2036,44 @@ void ov::npuw::util::XARCH::unpack_f8f16_scale(const ov::SoPtr<ov::ITensor>& froOPENVINO_THROW("AVX2 support is necessary but it's not enabled!");#endif}++void ov::npuw::util::XARCH::rerotate_f16_rows(uint16_t* plane,+ size_t num_tokens,+ size_t seq_stride,+ size_t rows_per_token,+ size_t head_dim,+ const float* delta_cos,+ const float* delta_sin,+ size_t half) {+ for (size_t t = 0; t < num_tokens; ++t) {+ const float* dcos = delta_cos + t * half;+ const float* dsin = delta_sin + t * half;+ uint16_t* token = plane + t * seq_stride;+ for (size_t r = 0; r < rows_per_token; ++r) {+ uint16_t* row = token + r * head_dim;+ size_t j = 0;+#if defined(HAVE_AVX2)+ for (; j + 8 <= half; j += 8) {+ const __m256 a = _mm256_cvtph_ps(_mm_loadu_si128(reinterpret_cast<const __m128i*>(row + j)));+ const __m256 b = _mm256_cvtph_ps(_mm_loadu_si128(reinterpret_cast<const __m128i*>(row + j + half)));+ const __m256 c = _mm256_loadu_ps(dcos + j);+ const __m256 s = _mm256_loadu_ps(dsin + j);+ // The compiler contracts these into FMAs, so a value here can land one+ // f16 ULP away from what the scalar tail below would produce. Harmless+ // for an f16 cache, but it does mean the two paths are not bit-equal.+ const __m256 lo = _mm256_sub_ps(_mm256_mul_ps(a, c), _mm256_mul_ps(b, s));+ const __m256 hi = _mm256_add_ps(_mm256_mul_ps(b, c), _mm256_mul_ps(a, s));+ _mm_storeu_si128(reinterpret_cast<__m128i*>(row + j), _mm256_cvtps_ph(lo, _MM_FROUND_TO_NEAREST_INT));+ _mm_storeu_si128(reinterpret_cast<__m128i*>(row + j + half),+ _mm256_cvtps_ph(hi, _MM_FROUND_TO_NEAREST_INT));+ }+#endif+ for (; j < half; ++j) {+ const float a = static_cast<float>(ov::float16::from_bits(row[j]));+ const float b = static_cast<float>(ov::float16::from_bits(row[j + half]));+ row[j] = ov::float16(a * dcos[j] - b * dsin[j]).to_bits();+ row[j + half] = ov::float16(b * dcos[j] + a * dsin[j]).to_bits();+ }+ }+ }+}diff --git a/src/plugins/intel_npu/src/plugin/npuw/util_xarch.hpp b/src/plugins/intel_npu/src/plugin/npuw/util_xarch.hppindex c1c8d057d92..12fac635922 100644--- a/src/plugins/intel_npu/src/plugin/npuw/util_xarch.hpp+++ b/src/plugins/intel_npu/src/plugin/npuw/util_xarch.hpp@@ -101,6 +101,21 @@ void unpack_f8f16_scale(const ov::SoPtr<ov::ITensor>& from,const ov::SoPtr<ov::ITensor>& to,const ov::npuw::util::UnpackOptions& unpack_options);+// Turns the leading num_tokens rows of one densely packed f16 key plane by a per-token+// rotation, in rotate_half layout: components j and j + half of every head_dim-wide row+// become (a * cos - b * sin, b * cos + a * sin), with (cos, sin) taken from row t of+// delta_cos/delta_sin. Channels at and beyond 2 * half are left untouched.+//+// Sequence entry t starts at plane[t * seq_stride] and spans rows_per_token rows.+void rerotate_f16_rows(uint16_t* plane,+ size_t num_tokens,+ size_t seq_stride,+ size_t rows_per_token,+ size_t head_dim,+ const float* delta_cos,+ const float* delta_sin,+ size_t half);+} // namespace XARCH} // namespace util} // namespace npuwdiff --git a/src/plugins/intel_npu/src/plugin/sources.cmake b/src/plugins/intel_npu/src/plugin/sources.cmakeindex b4ee6530459..465480e169b 100644--- a/src/plugins/intel_npu/src/plugin/sources.cmake+++ b/src/plugins/intel_npu/src/plugin/sources.cmake@@ -87,6 +87,8 @@ set(NPUW_SOURCES${CMAKE_CURRENT_SOURCE_DIR}/npuw/llm_infer_request.cpp${CMAKE_CURRENT_SOURCE_DIR}/npuw/llm_infer_request.hpp${CMAKE_CURRENT_SOURCE_DIR}/npuw/llm_kvcache_strategy.hpp+ ${CMAKE_CURRENT_SOURCE_DIR}/npuw/llm_longrope_kv.cpp+ ${CMAKE_CURRENT_SOURCE_DIR}/npuw/llm_longrope_kv.hpp${CMAKE_CURRENT_SOURCE_DIR}/npuw/llm_lora_states.hpp${CMAKE_CURRENT_SOURCE_DIR}/npuw/llm_prefix_caching.cpp${CMAKE_CURRENT_SOURCE_DIR}/npuw/llm_prefix_caching.hppdiff --git a/src/plugins/intel_npu/tests/functional/behavior/npuw/test_engine/models/model_builder.cpp b/src/plugins/intel_npu/tests/functional/behavior/npuw/test_engine/models/model_builder.cppindex 131258108b2..66b04bc6ea5 100644--- a/src/plugins/intel_npu/tests/functional/behavior/npuw/test_engine/models/model_builder.cpp+++ b/src/plugins/intel_npu/tests/functional/behavior/npuw/test_engine/models/model_builder.cpp@@ -724,7 +724,8 @@ ov::Output<ov::Node> ModelBuilder::setup_position_ids(LLMConfig& config, const oconfig.rope =PartialRotationRoPE(config.head_dim, config.rotary_dim, config.precision, position_ids_output);} else {- config.rope = HalfRotationRoPE(config.head_dim, config.precision, position_ids_output);+ config.rope =+ HalfRotationRoPE(config.head_dim, config.precision, position_ids_output, {}, config.longrope);}}diff --git a/src/plugins/intel_npu/tests/functional/behavior/npuw/test_engine/models/model_builder.hpp b/src/plugins/intel_npu/tests/functional/behavior/npuw/test_engine/models/model_builder.hppindex 7d0043c2d92..7cdd07a85f8 100644--- a/src/plugins/intel_npu/tests/functional/behavior/npuw/test_engine/models/model_builder.hpp+++ b/src/plugins/intel_npu/tests/functional/behavior/npuw/test_engine/models/model_builder.hpp@@ -192,6 +192,10 @@ struct LLMConfig : public BaseModelConfig {/// Only applies when build_llm auto-creates the RoPE functor.size_t rotary_dim = 0;+ /// Phi-style LongRoPE inverse frequencies. Only applies when build_llm auto-creates+ /// a full-width HalfRotationRoPE functor.+ LongRopeSpec longrope;+// MoE configuration (num_experts=0 means dense, no MoE)size_t num_experts = 0; ///< Total experts. 0 = dense model.size_t num_experts_per_tok = 0; ///< Top-K. 0 = default to 2.diff --git a/src/plugins/intel_npu/tests/functional/behavior/npuw/test_engine/models/model_builder_rope.cpp b/src/plugins/intel_npu/tests/functional/behavior/npuw/test_engine/models/model_builder_rope.cppindex 98c01af6819..b9493705d6b 100644--- a/src/plugins/intel_npu/tests/functional/behavior/npuw/test_engine/models/model_builder_rope.cpp+++ b/src/plugins/intel_npu/tests/functional/behavior/npuw/test_engine/models/model_builder_rope.cpp@@ -26,7 +26,8 @@ RoPEFrequencies build_rope_frequencies(size_t head_dim,ov::element::Type precision,const ov::Output<ov::Node>& position_ids,const ov::Output<ov::Node>& shape_source = {},- const std::string& prefix = "model.rope") {+ const std::string& prefix = "model.rope",+ const LongRopeSpec& longrope = {}) {const size_t half_dim = head_dim / 2;std::vector<float> inv_freq_data(half_dim);@@ -34,8 +35,35 @@ RoPEFrequencies build_rope_frequencies(size_t head_dim,inv_freq_data[i] =1.0f / std::pow(kRoPEBaseFrequency, static_cast<float>(2 * i) / static_cast<float>(head_dim));}- auto inv_freq = ov::opset11::Constant::create(ov::element::f32, ov::Shape{1, half_dim, 1}, inv_freq_data);- inv_freq->set_friendly_name(prefix + ".inv_freq");+ ov::Output<ov::Node> inv_freq;+ if (longrope.enabled()) {+ OPENVINO_ASSERT(longrope.inv_freq_short.size() == half_dim && longrope.inv_freq_long.size() == half_dim,+ "LongRopeSpec needs head_dim / 2 inverse frequencies per mode");+ auto short_factor =+ ov::opset11::Constant::create(ov::element::f32, ov::Shape{1, half_dim, 1}, longrope.inv_freq_short);+ short_factor->set_friendly_name(prefix + ".inv_freq_short");+ auto long_factor =+ ov::opset11::Constant::create(ov::element::f32, ov::Shape{1, half_dim, 1}, longrope.inv_freq_long);+ long_factor->set_friendly_name(prefix + ".inv_freq_long");++ // max(position_ids) + 1 <= original_max_position_embeddings ? short : long.+ // The offset has to be exactly 1 - NPUW rejects any other one.+ const auto pos_type = position_ids.get_element_type();+ auto reduce_axes = ov::opset11::Constant::create(ov::element::i64, ov::Shape{2}, {0, 1});+ auto max_pos = std::make_shared<ov::op::v1::ReduceMax>(position_ids, reduce_axes, false);+ auto one = ov::opset11::Constant::create(pos_type, ov::Shape{}, {1});+ auto shifted = std::make_shared<ov::op::v1::Add>(max_pos, one);+ auto limit = ov::opset11::Constant::create(pos_type, ov::Shape{}, {longrope.context_limit});+ auto is_short = std::make_shared<ov::op::v1::LessEqual>(shifted, limit);+ auto select = std::make_shared<ov::op::v1::Select>(is_short, short_factor, long_factor);+ select->set_friendly_name(prefix + ".inv_freq_select");+ inv_freq = select->output(0);+ } else {+ auto inv_freq_const =+ ov::opset11::Constant::create(ov::element::f32, ov::Shape{1, half_dim, 1}, inv_freq_data);+ inv_freq_const->set_friendly_name(prefix + ".inv_freq");+ inv_freq = inv_freq_const->output(0);+ }// Broadcast inv_freq to [batch, half_dim, 1] using batch dim from shape_source.// This ShapeOf -> Gather -> Concat -> Broadcast chain matches NPUW's RopePatternLLama2.@@ -111,9 +139,10 @@ RoPEFrequencies build_rope_frequencies(size_t head_dim,HalfRotationRoPE::HalfRotationRoPE(size_t hd,ov::element::Type precision,const ov::Output<ov::Node>& position_ids,- const ov::Output<ov::Node>& shape_source)+ const ov::Output<ov::Node>& shape_source,+ const LongRopeSpec& longrope): head_dim(hd) {- auto freq = build_rope_frequencies(hd, precision, position_ids, shape_source);+ auto freq = build_rope_frequencies(hd, precision, position_ids, shape_source, "model.rope", longrope);cos_freq = freq.cos;sin_freq = freq.sin;}diff --git a/src/plugins/intel_npu/tests/functional/behavior/npuw/test_engine/models/model_builder_rope.hpp b/src/plugins/intel_npu/tests/functional/behavior/npuw/test_engine/models/model_builder_rope.hppindex f9481a3b272..e637b845bbb 100644--- a/src/plugins/intel_npu/tests/functional/behavior/npuw/test_engine/models/model_builder_rope.hpp+++ b/src/plugins/intel_npu/tests/functional/behavior/npuw/test_engine/models/model_builder_rope.hpp@@ -5,6 +5,7 @@#pragma once#include <string>+#include <vector>#include "openvino/core/node.hpp"#include "openvino/core/type/element_type.hpp"@@ -13,6 +14,21 @@ namespace ov {namespace test {namespace npuw {+/// Phi-style LongRoPE inverse frequencies. When enabled, the inv_freq Constant of the+/// RoPE chain is replaced by+/// max(position_ids) + 1 <= context_limit ? inv_freq_short : inv_freq_long+/// which is what NPUW's LongRopePatternPhi matches and RopeCache rewrites into the+/// host-fed npuw_lr_cos / npuw_lr_sin model inputs.+struct LongRopeSpec {+ std::vector<float> inv_freq_short; ///< head_dim / 2 entries+ std::vector<float> inv_freq_long; ///< head_dim / 2 entries+ int64_t context_limit = 0; ///< original_max_position_embeddings; 0 = plain RoPE++ bool enabled() const {+ return context_limit > 0 && !inv_freq_short.empty();+ }+};+/// Position IDs baked in at construction, cos/sin shared across layers./// shape_source provides batch dim for inv_freq Broadcast (matches NPUW RopeCache pattern)./// Defaults to position_ids when not specified.@@ -23,7 +39,8 @@ struct HalfRotationRoPE {HalfRotationRoPE(size_t head_dim,ov::element::Type precision,const ov::Output<ov::Node>& position_ids,- const ov::Output<ov::Node>& shape_source = {});+ const ov::Output<ov::Node>& shape_source = {},+ const LongRopeSpec& longrope = {});ov::Output<ov::Node> operator()(const ov::Output<ov::Node>& input, const std::string& name) const;};diff --git a/src/plugins/intel_npu/tests/unit/CMakeLists.txt b/src/plugins/intel_npu/tests/unit/CMakeLists.txtindex b4dc6836a87..700f0318aa7 100644--- a/src/plugins/intel_npu/tests/unit/CMakeLists.txt+++ b/src/plugins/intel_npu/tests/unit/CMakeLists.txt@@ -56,6 +56,7 @@ ov_add_test_target(${OpenVINO_SOURCE_DIR}/src/plugins/intel_npu/src/plugin/npuw/llm_compiled_model.cpp${OpenVINO_SOURCE_DIR}/src/plugins/intel_npu/src/plugin/npuw/llm_compiled_model_utils.cpp${OpenVINO_SOURCE_DIR}/src/plugins/intel_npu/src/plugin/npuw/llm_infer_request.cpp+ ${OpenVINO_SOURCE_DIR}/src/plugins/intel_npu/src/plugin/npuw/llm_longrope_kv.cpp${OpenVINO_SOURCE_DIR}/src/plugins/intel_npu/src/plugin/npuw/llm_swa_cache.cpp${OpenVINO_SOURCE_DIR}/src/plugins/intel_npu/src/plugin/npuw/llm_block_kvcache_strategy.cpp${OpenVINO_SOURCE_DIR}/src/plugins/intel_npu/src/plugin/npuw/llm_continuous_kvcache_strategy.cppdiff --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.cppindex 285c646fd24..cf891158c16 100644--- 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.cpp@@ -226,6 +226,12 @@ public:void on_generate_step_done(uint32_t input_tokens_len) override {m_inner->on_generate_step_done(input_tokens_len);}+ void rerotate_longrope_keys(const std::shared_ptr<ov::IAsyncInferRequest>& request,+ const PortsMap& in_ports,+ uint32_t num_cached_tokens,+ bool to_long) override {+ m_inner->rerotate_longrope_keys(request, in_ports, num_cached_tokens, to_long);+ }void continue_prefill(uint32_t, uint32_t) override {OPENVINO_THROW("Injected continued-prefill failure.");}diff --git a/src/plugins/intel_npu/tests/unit/npuw/llm_longrope_kv_test.cpp b/src/plugins/intel_npu/tests/unit/npuw/llm_longrope_kv_test.cppnew file mode 100644index 00000000000..05b7cb80231--- /dev/null+++ b/src/plugins/intel_npu/tests/unit/npuw/llm_longrope_kv_test.cpp@@ -0,0 +1,274 @@+// Copyright (C) 2018-2026 Intel Corporation+// SPDX-License-Identifier: Apache-2.0+//++#include "llm_longrope_kv.hpp"++#include <gtest/gtest.h>++#include <cmath>+#include <vector>++#include "openvino/runtime/make_tensor.hpp"++namespace {++namespace lr = ov::npuw::longrope;++constexpr size_t kInvFreq = 4; // planes per rotate_half row+constexpr size_t kRotaryNdims = kInvFreq * 2; // rotated channels+constexpr size_t kHeadDim = kRotaryNdims + 2; // two pass-through channels on top+constexpr size_t kHeads = 2;+constexpr size_t kSeqLen = 16;+constexpr uint32_t kSeqDim = 2; // [batch, heads, seq, head_dim]++ov::npuw::patterns::pre_compute::LongRopeCosSin make_tables(bool has_long) {+ ov::npuw::patterns::pre_compute::LongRopeCosSin tables;+ tables.max_len = kSeqLen;+ tables.rotary_ndims = kRotaryNdims;+ tables.has_long = has_long;+ tables.inv_freq_short = {1.0f, 0.31f, 0.09f, 0.027f};+ tables.inv_freq_long = has_long ? std::vector<float>{0.7f, 0.2f, 0.05f, 0.013f} : tables.inv_freq_short;+ tables.rebuild_tables();+ return tables;+}++// A deterministic, non-degenerate raw (pre-RoPE) key cache.+std::vector<float> make_raw_keys() {+ std::vector<float> raw(kHeads * kSeqLen * kHeadDim);+ for (size_t i = 0; i < raw.size(); ++i) {+ raw[i] = std::sin(static_cast<float>(i) * 0.37f) * 1.5f + 0.25f;+ }+ return raw;+}++// Rotates raw keys the way the graph does: rotate_half over the rotary channels only,+// with the f16 coefficients of the requested mode.+std::vector<float> rotate(const std::vector<float>& raw,+ ov::npuw::patterns::pre_compute::LongRopeCosSin& tables,+ bool is_long) {+ auto cos = tables.cos_rows(tables.max_len, is_long);+ auto sin = tables.sin_rows(tables.max_len, is_long);+ const auto* pcos = cos.data<ov::float16>();+ const auto* psin = sin.data<ov::float16>();++ std::vector<float> out = raw;+ for (size_t h = 0; h < kHeads; ++h) {+ for (size_t p = 0; p < kSeqLen; ++p) {+ float* row = out.data() + (h * kSeqLen + p) * kHeadDim;+ const float* src = raw.data() + (h * kSeqLen + p) * kHeadDim;+ for (size_t j = 0; j < kInvFreq; ++j) {+ const float c = static_cast<float>(pcos[p * kRotaryNdims + j]);+ const float s = static_cast<float>(psin[p * kRotaryNdims + j]);+ row[j] = src[j] * c - src[j + kInvFreq] * s;+ row[j + kInvFreq] = src[j + kInvFreq] * c + src[j] * s;+ }+ }+ }+ return out;+}++ov::SoPtr<ov::ITensor> as_tensor(std::vector<float>& data) {+ return ov::get_tensor_impl(+ ov::Tensor(ov::element::f32, ov::Shape{1, kHeads, kSeqLen, kHeadDim}, data.data()));+}++void expect_close(const std::vector<float>& actual, const std::vector<float>& expected, float tol) {+ ASSERT_EQ(actual.size(), expected.size());+ for (size_t i = 0; i < actual.size(); ++i) {+ EXPECT_NEAR(actual[i], expected[i], tol) << "at element " << i;+ }+}++} // anonymous namespace++// Re-rotating a short-mode cache must land on the same keys the graph would have+// produced had it rotated the raw keys with the long factors from the start.+TEST(LongRopeRerotate, ShortCacheBecomesLongCache) {+ auto tables = make_tables(true);+ const auto raw = make_raw_keys();+ auto cache = rotate(raw, tables, false);+ const auto expected = rotate(raw, tables, true);++ const auto delta = lr::make_mode_delta(tables, 0, kSeqLen, true);+ ASSERT_EQ(delta.half, kInvFreq);++ auto tensor = as_tensor(cache);+ lr::rerotate_keys(tensor, kSeqDim, kSeqLen, delta);++ expect_close(cache, expected, 2e-3f);+}++// The pass-through channels of a partial-rotary model were never rotated.+TEST(LongRopeRerotate, PassThroughChannelsUntouched) {+ auto tables = make_tables(true);+ const auto raw = make_raw_keys();+ auto cache = rotate(raw, tables, false);+ const auto before = cache;++ auto tensor = as_tensor(cache);+ lr::rerotate_keys(tensor, kSeqDim, kSeqLen, lr::make_mode_delta(tables, 0, kSeqLen, true));++ for (size_t h = 0; h < kHeads; ++h) {+ for (size_t p = 0; p < kSeqLen; ++p) {+ for (size_t d = kRotaryNdims; d < kHeadDim; ++d) {+ const size_t idx = (h * kSeqLen + p) * kHeadDim + d;+ EXPECT_FLOAT_EQ(cache[idx], before[idx]) << "at head " << h << " pos " << p << " ch " << d;+ }+ }+ }+}++// Rows beyond the cached token count belong to no position and must stay as they are.+TEST(LongRopeRerotate, RowsBeyondCachedTokensUntouched) {+ constexpr uint32_t kCached = 5;+ auto tables = make_tables(true);+ const auto raw = make_raw_keys();+ auto cache = rotate(raw, tables, false);+ const auto before = cache;++ auto tensor = as_tensor(cache);+ lr::rerotate_keys(tensor, kSeqDim, kCached, lr::make_mode_delta(tables, 0, kCached, true));++ for (size_t h = 0; h < kHeads; ++h) {+ for (size_t p = kCached; p < kSeqLen; ++p) {+ for (size_t d = 0; d < kHeadDim; ++d) {+ const size_t idx = (h * kSeqLen + p) * kHeadDim + d;+ EXPECT_FLOAT_EQ(cache[idx], before[idx]) << "at head " << h << " pos " << p;+ }+ }+ }+}++// Going long and back must return the cache to where it started.+TEST(LongRopeRerotate, RoundTripRestoresTheCache) {+ auto tables = make_tables(true);+ const auto raw = make_raw_keys();+ auto cache = rotate(raw, tables, false);+ const auto before = cache;++ auto tensor = as_tensor(cache);+ lr::rerotate_keys(tensor, kSeqDim, kSeqLen, lr::make_mode_delta(tables, 0, kSeqLen, true));+ lr::rerotate_keys(tensor, kSeqDim, kSeqLen, lr::make_mode_delta(tables, 0, kSeqLen, false));++ expect_close(cache, before, 2e-3f);+}++// Cached rows do not have to start at position zero.+TEST(LongRopeRerotate, DeltaFollowsTheFirstPositionId) {+ constexpr int64_t kFirstPos = 3;+ auto tables = make_tables(true);++ const auto from_zero = lr::make_mode_delta(tables, 0, kSeqLen, true);+ const auto shifted = lr::make_mode_delta(tables, kFirstPos, kSeqLen - kFirstPos, true);++ ASSERT_EQ(shifted.cos.size(), (kSeqLen - kFirstPos) * kInvFreq);+ for (size_t i = 0; i < shifted.cos.size(); ++i) {+ EXPECT_FLOAT_EQ(shifted.cos[i], from_zero.cos[kFirstPos * kInvFreq + i]);+ EXPECT_FLOAT_EQ(shifted.sin[i], from_zero.sin[kFirstPos * kInvFreq + i]);+ }+}++// A model whose two factor sets coincide never needs a re-rotation.+TEST(LongRopeRerotate, NoLongModeYieldsEmptyDelta) {+ auto tables = make_tables(false);+ const auto delta = lr::make_mode_delta(tables, 0, kSeqLen, true);+ EXPECT_EQ(delta.half, 0u);++ const auto raw = make_raw_keys();+ auto cache = rotate(raw, tables, false);+ const auto before = cache;++ auto tensor = as_tensor(cache);+ lr::rerotate_keys(tensor, kSeqDim, kSeqLen, delta);+ expect_close(cache, before, 0.0f);+}++// Positions the coefficient tables do not cover must be rejected, not silently wrapped.+TEST(LongRopeRerotate, PositionsOutsideTheTablesThrow) {+ auto tables = make_tables(true);+ EXPECT_THROW(lr::make_mode_delta(tables, 1, kSeqLen, true), ov::Exception);+}++// A quantized cache cannot be turned without dequantizing it, and a half-turned cache is+// worse than none - so it is refused rather than warned about and skipped.+TEST(LongRopeRerotate, UnsupportedElementTypeThrows) {+ auto tables = make_tables(true);+ const auto delta = lr::make_mode_delta(tables, 0, kSeqLen, true);++ std::vector<int8_t> quantized(kHeads * kSeqLen * kHeadDim, 1);+ auto tensor = ov::get_tensor_impl(+ ov::Tensor(ov::element::i8, ov::Shape{1, kHeads, kSeqLen, kHeadDim}, quantized.data()));++ EXPECT_THROW(lr::rerotate_keys(tensor, kSeqDim, kSeqLen, delta), ov::Exception);+}++// Rows are addressed from one base pointer, so anything but a canonically packed tensor+// has to be refused. A view that crops only the sequence axis is the trap: its own+// sequence stride still looks dense while every plane after the first sits elsewhere.+TEST(LongRopeRerotate, StridedTensorThrows) {+ auto tables = make_tables(true);+ const auto delta = lr::make_mode_delta(tables, 0, kSeqLen, true);++ ov::Tensor parent(ov::element::f32, ov::Shape{1, kHeads, kSeqLen * 2, kHeadDim});+ std::fill_n(parent.data<float>(), parent.get_size(), 0.5f);+ ov::Tensor cropped(parent,+ ov::Coordinate{0, 0, 0, 0},+ ov::Coordinate{1, kHeads, kSeqLen, kHeadDim});+ ASSERT_EQ(cropped.get_shape(), (ov::Shape{1, kHeads, kSeqLen, kHeadDim}));++ auto tensor = ov::get_tensor_impl(cropped);+ EXPECT_THROW(lr::rerotate_keys(tensor, kSeqDim, kSeqLen, delta), ov::Exception);+}++// An f16 cache is rewritten by the SIMD kernel in util_xarch, an f32 one by the scalar+// loop; the two must agree. A rotary width of 20 gives 10 planes per row, which covers+// both the 8-wide vector body and the 2-plane scalar tail of the SIMD path.+TEST(LongRopeRerotate, F16PathMatchesTheF32Path) {+ constexpr size_t kWideInvFreq = 10;+ constexpr size_t kWideRotary = kWideInvFreq * 2;+ constexpr size_t kWideHeadDim = kWideRotary + 4;+ const ov::Shape shape{1, kHeads, kSeqLen, kWideHeadDim};++ ov::npuw::patterns::pre_compute::LongRopeCosSin tables;+ tables.max_len = kSeqLen;+ tables.rotary_ndims = kWideRotary;+ tables.has_long = true;+ for (size_t i = 0; i < kWideInvFreq; ++i) {+ tables.inv_freq_short.push_back(1.0f / std::pow(3.0f, static_cast<float>(i)));+ tables.inv_freq_long.push_back(0.7f / std::pow(3.1f, static_cast<float>(i)));+ }+ tables.rebuild_tables();++ // Both caches start from the very same values, exactly representable in f16.+ std::vector<ov::float16> f16_cache(kHeads * kSeqLen * kWideHeadDim);+ std::vector<float> f32_cache(f16_cache.size());+ for (size_t i = 0; i < f16_cache.size(); ++i) {+ f16_cache[i] = ov::float16(std::sin(static_cast<float>(i) * 0.23f) * 1.5f);+ f32_cache[i] = static_cast<float>(f16_cache[i]);+ }+ const auto before = f16_cache;++ const auto delta = lr::make_mode_delta(tables, 0, kSeqLen, true);+ ASSERT_EQ(delta.half, kWideInvFreq);++ auto f16_tensor = ov::get_tensor_impl(ov::Tensor(ov::element::f16, shape, f16_cache.data()));+ auto f32_tensor = ov::get_tensor_impl(ov::Tensor(ov::element::f32, shape, f32_cache.data()));+ lr::rerotate_keys(f16_tensor, kSeqDim, kSeqLen, delta);+ lr::rerotate_keys(f32_tensor, kSeqDim, kSeqLen, delta);++ for (size_t h = 0; h < kHeads; ++h) {+ for (size_t p = 0; p < kSeqLen; ++p) {+ for (size_t d = 0; d < kWideHeadDim; ++d) {+ const size_t idx = (h * kSeqLen + p) * kWideHeadDim + d;+ if (d < kWideRotary) {+ EXPECT_NEAR(static_cast<float>(f16_cache[idx]), f32_cache[idx], 2e-3f)+ << "at head " << h << " pos " << p << " ch " << d;+ } else {+ EXPECT_EQ(f16_cache[idx].to_bits(), before[idx].to_bits())+ << "pass-through channel " << d << " was touched";+ }+ }+ }+ }+}diff --git a/src/plugins/intel_npu/tests/unit/npuw/llm_longrope_mode_test.cpp b/src/plugins/intel_npu/tests/unit/npuw/llm_longrope_mode_test.cppnew file mode 100644index 00000000000..19d0c073a29--- /dev/null+++ b/src/plugins/intel_npu/tests/unit/npuw/llm_longrope_mode_test.cpp@@ -0,0 +1,721 @@+// Copyright (C) 2018-2026 Intel Corporation+// SPDX-License-Identifier: Apache-2.0+//++// Request-level tests for the LongRoPE short/long mode state machine.+//+// llm_longrope_kv_test.cpp proves the coefficient math against an independent+// reference; what is left, and what these tests cover, is everything around it: when a+// crossing is detected, that the rewrite runs after the KV of the previous stage has+// been migrated into the request being rewritten, which rows it touches, and that a+// transition which cannot be completed leaves the recorded mode describing the cache+// as it really is.+//+// The observation trick is a second, "control" model that is identical except for a+// context limit no position in the test can reach. Both models are driven with the same+// inputs through fake sub-requests whose outputs depend only on the port name, so their+// KV caches agree byte for byte up to the re-rotation - which is then the only thing the+// comparison can be measuring.++#include <gtest/gtest.h>++#include <algorithm>+#include <cmath>+#include <cstdint>+#include <cstring>+#include <memory>+#include <numeric>+#include <string>+#include <vector>++#include "executor.hpp"+#include "llm_block_kvcache_strategy.hpp"+#include "llm_compiled_model.hpp"+#include "llm_infer_request.hpp"+#include "llm_longrope_kv.hpp"+#include "llm_test_helpers.hpp"+#include "openvino/openvino.hpp"+#include "openvino/runtime/make_tensor.hpp"+#include "util.hpp"++namespace ov::test::npuw {++struct LLMLongRopeModeTestAccess {+ using Request = ov::npuw::LLMInferRequest;++ static bool long_mode(Request& req) {+ return req.m_longrope_long_mode;+ }++ 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 uint32_t stored_tokens(Request& req) {+ return req.m_npuw_llm_compiled_model->m_kvcache_desc.num_stored_tokens;+ }++ static uint32_t seq_dim(Request& req) {+ return req.m_npuw_llm_compiled_model->m_kvcache_desc.dim;+ }++ static ov::npuw::patterns::pre_compute::LongRopeCosSin& tables(Request& req) {+ return req.m_npuw_llm_compiled_model->m_longrope_tables;+ }++ static bool has_long(const ov::npuw::LLMCompiledModel& compiled) {+ return compiled.m_longrope_tables.has_long;+ }++ // Drives the transition directly, which is the only way to reach the rejection+ // paths - a real request always hands over its own, well-formed port map.+ static void sync_mode(Request& req,+ const ov::npuw::LLMInferRequest::PortsMap& in_ports,+ const ov::SoPtr<ov::ITensor>& position_ids,+ uint32_t num_cached_tokens) {+ req.sync_longrope_mode(req.m_kvcache_request, in_ports, position_ids, num_cached_tokens);+ }++ static const ov::npuw::LLMInferRequest::PortsMap& generate_in_ports(Request& req) {+ return req.m_kvcache_in_ports;+ }++ static ov::npuw::LLMBlockKVCacheStrategy& block_strategy(Request& req) {+ auto* strategy = dynamic_cast<ov::npuw::LLMBlockKVCacheStrategy*>(req.m_kvcache_strategy.get());+ OPENVINO_ASSERT(strategy != nullptr, "the request does not run on the block KV strategy");+ return *strategy;+ }++ static const std::unordered_map<uint32_t, ov::npuw::LayerBlockManagers>& block_managers(+ const ov::npuw::LLMBlockKVCacheStrategy& strategy) {+ return strategy.m_kv_cache_block_managers;+ }++ static uint32_t block_size(const ov::npuw::LLMBlockKVCacheStrategy& strategy) {+ return strategy.m_block_size;+ }+};++} // namespace ov::test::npuw++namespace {++using ov::test::npuw::build_longrope_llm_test_model;+using ov::test::npuw::LLMLongRopeModeTestAccess;+using ov::test::npuw::NullPlugin;+class FakeSubCompiledModel;++// A position no prompt in this file reaches, so the model never leaves the short+// mode and its KV cache is never re-rotated.+constexpr int64_t kUnreachableLimit = 4096;+// Crossed by generated token 16 of a 16-token prompt.+constexpr int64_t kCrossingLimit = 16;++// Deterministic, finite, port-dependent contents so two models with the same port names+// produce the same KV bytes.+void fill_pattern(const ov::SoPtr<ov::ITensor>& tensor, size_t seed) {+ const size_t count = tensor->get_size();+ const auto type = tensor->get_element_type();+ if (type == ov::element::f16) {+ auto* data = tensor->data<ov::float16>();+ for (size_t i = 0; i < count; ++i) {+ data[i] = ov::float16(std::sin(static_cast<float>(i + seed) * 0.137f) * 1.25f);+ }+ } else if (type == ov::element::f32) {+ auto* data = tensor->data<float>();+ for (size_t i = 0; i < count; ++i) {+ data[i] = std::sin(static_cast<float>(i + seed) * 0.137f) * 1.25f;+ }+ } else {+ std::memset(tensor->data(), 0, tensor->get_byte_size());+ }+}++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("longrope_mode_task", 1),+ intel_npu::make_executor("longrope_mode_callback", 1));+ }+ std::string submodel_device(std::size_t) const override {+ return "CPU";+ }+ std::size_t num_submodels() const override {+ 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()) {+ fill_pattern(ov::ISyncInferRequest::get_tensor(output), std::hash<std::string>{}(output.get_any_name()));+ }+}++ov::npuw::LLMCompiledModel::CompiledModelFactory make_fake_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);+ };+}++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;+}++std::vector<float> to_floats(const ov::SoPtr<ov::ITensor>& tensor) {+ ov::Tensor dense(tensor->get_element_type(), tensor->get_shape());+ tensor->copy_to(ov::get_tensor_impl(dense)._ptr);+ std::vector<float> out(dense.get_size());+ if (dense.get_element_type() == ov::element::f16) {+ const auto* data = dense.data<ov::float16>();+ for (size_t i = 0; i < out.size(); ++i) {+ out[i] = static_cast<float>(data[i]);+ }+ } else {+ const auto* data = dense.data<float>();+ std::copy_n(data, out.size(), out.begin());+ }+ return out;+}++// One conversation driver over a freshly compiled model with the given context limit.+class LongRopePipeline {+public:+ explicit LongRopePipeline(int64_t context_limit, const ov::AnyMap& extra_props = {}) {+ m_plugin = std::make_shared<NullPlugin>();+ ov::AnyMap props{{"NPUW_LLM", "YES"},+ {"NPUW_DEVICES", "CPU"},+ {"NPUW_LLM_MAX_PROMPT_LEN", "64"},+ {"NPUW_LLM_MIN_RESPONSE_LEN", "32"},+ {"NPUW_LLM_CACHE_ROPE", "YES"}};+ for (const auto& [key, value] : extra_props) {+ props[key] = value;+ }+ m_compiled = std::make_shared<ov::npuw::LLMCompiledModel>(build_longrope_llm_test_model(context_limit),+ m_plugin,+ props,+ make_fake_factory());+ m_request = std::make_unique<ov::npuw::LLMInferRequest>(m_compiled);+ }++ ov::npuw::LLMInferRequest& request() {+ return *m_request;+ }++ const ov::npuw::LLMCompiledModel& compiled() const {+ return *m_compiled;+ }++ void prefill(size_t prompt_len, int64_t first_position) {+ set_inputs(make_i64({1, prompt_len}, 1),+ make_i64({1, prompt_len}, 1),+ make_i64_iota({1, prompt_len}, first_position));+ m_request->infer();+ }++ void generate_step(size_t live_tokens, int64_t position) {+ set_inputs(make_i64({1, 1}, 1), make_i64({1, live_tokens + 1}, 1), make_i64({1, 1}, position));+ m_request->infer();+ }++ // The past keys of every layer, flattened, in m_kvcache_past_names order.+ std::vector<std::vector<float>> generate_keys() {+ std::vector<std::vector<float>> out;+ for (const auto& name : LLMLongRopeModeTestAccess::past_names(*m_request)) {+ if (ov::npuw::util::isPastKeyParam(name)) {+ out.push_back(to_floats(LLMLongRopeModeTestAccess::generate_past(*m_request, name)));+ }+ }+ return out;+ }++ ov::Shape generate_key_shape() {+ for (const auto& name : LLMLongRopeModeTestAccess::past_names(*m_request)) {+ if (ov::npuw::util::isPastKeyParam(name)) {+ return LLMLongRopeModeTestAccess::generate_past(*m_request, name)->get_shape();+ }+ }+ return {};+ }++private:+ 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));+ }++ std::shared_ptr<ov::IPlugin> m_plugin;+ std::shared_ptr<ov::npuw::LLMCompiledModel> m_compiled;+ std::unique_ptr<ov::npuw::LLMInferRequest> m_request;+};++// Applies the same turn the request is expected to have applied, to a copy of the+// control run's keys. The coefficient math itself is validated independently in+// llm_longrope_kv_test.cpp; here it is the reference for placement and row range.+std::vector<std::vector<float>> expected_turn(std::vector<std::vector<float>> keys,+ const ov::Shape& shape,+ uint32_t seq_dim,+ ov::npuw::patterns::pre_compute::LongRopeCosSin& tables,+ uint32_t num_tokens,+ bool to_long) {+ const auto delta = ov::npuw::longrope::make_mode_delta(tables, 0, num_tokens, to_long);+ for (auto& layer : keys) {+ auto tensor = ov::get_tensor_impl(ov::Tensor(ov::element::f32, shape, layer.data()));+ ov::npuw::longrope::rerotate_keys(tensor, seq_dim, num_tokens, delta);+ }+ return keys;+}++void expect_keys_near(const std::vector<std::vector<float>>& actual,+ const std::vector<std::vector<float>>& expected,+ float tol) {+ ASSERT_EQ(actual.size(), expected.size());+ ASSERT_FALSE(actual.empty());+ for (size_t layer = 0; layer < actual.size(); ++layer) {+ ASSERT_EQ(actual[layer].size(), expected[layer].size());+ for (size_t i = 0; i < actual[layer].size(); ++i) {+ ASSERT_NEAR(actual[layer][i], expected[layer][i], tol) << "layer " << layer << " element " << i;+ }+ }+}++// The models this file relies on must actually reach the LongRoPE path, otherwise every+// comparison below would pass on two untransformed graphs.+TEST(LLMLongRopeMode, ModelsReachTheLongRopePath) {+ LongRopePipeline crossing(kCrossingLimit);+ LongRopePipeline control(kUnreachableLimit);++ EXPECT_TRUE(LLMLongRopeModeTestAccess::has_long(crossing.compiled()));+ // Its limit sits past the whole context, so it can only ever run short.+ EXPECT_FALSE(LLMLongRopeModeTestAccess::has_long(control.compiled()));+ EXPECT_TRUE(LLMLongRopeModeTestAccess::tables(crossing.request()).is_valid());+}++// The first generate step past the limit turns exactly the cached rows, and it does so+// after the prefill KV has been migrated into the generate request - had it run before,+// the migration would have overwritten the turned keys with the untouched ones and the+// two runs would agree.+TEST(LLMLongRopeMode, CrossingTurnsTheMigratedCache) {+ constexpr size_t kPrompt = 16;++ LongRopePipeline control(kUnreachableLimit);+ control.prefill(kPrompt, 0);+ control.generate_step(kPrompt, static_cast<int64_t>(kPrompt));+ EXPECT_FALSE(LLMLongRopeModeTestAccess::long_mode(control.request()));+ const auto control_keys = control.generate_keys();++ LongRopePipeline crossing(kCrossingLimit);+ crossing.prefill(kPrompt, 0);+ EXPECT_FALSE(LLMLongRopeModeTestAccess::long_mode(crossing.request()));+ crossing.generate_step(kPrompt, static_cast<int64_t>(kPrompt));+ EXPECT_TRUE(LLMLongRopeModeTestAccess::long_mode(crossing.request()));++ const auto expected = expected_turn(control_keys,+ crossing.generate_key_shape(),+ LLMLongRopeModeTestAccess::seq_dim(crossing.request()),+ LLMLongRopeModeTestAccess::tables(crossing.request()),+ kPrompt,+ true);+ expect_keys_near(crossing.generate_keys(), expected, 2e-3f);+ // A turn that did nothing would trivially satisfy the comparison above.+ EXPECT_NE(control_keys, crossing.generate_keys());+}++// A prompt that is already past the limit finds an empty cache: the mode is recorded,+// nothing is rewritten, and the following steps do not cross again.+TEST(LLMLongRopeMode, FreshLongPromptRecordsTheModeWithoutTouchingTheCache) {+ constexpr size_t kPrompt = 20; // positions 0..19, so the prompt itself is long++ LongRopePipeline control(kUnreachableLimit);+ control.prefill(kPrompt, 0);+ control.generate_step(kPrompt, static_cast<int64_t>(kPrompt));+ const auto control_keys = control.generate_keys();++ LongRopePipeline crossing(kCrossingLimit);+ crossing.prefill(kPrompt, 0);+ EXPECT_TRUE(LLMLongRopeModeTestAccess::long_mode(crossing.request()));+ crossing.generate_step(kPrompt, static_cast<int64_t>(kPrompt));+ EXPECT_TRUE(LLMLongRopeModeTestAccess::long_mode(crossing.request()));++ expect_keys_near(crossing.generate_keys(), control_keys, 0.0f);+}++// Trimming the cache back below the limit - what speculative decoding does when its+// proposal is rejected - flips the mode back and returns the keys to where they were.+TEST(LLMLongRopeMode, TrimmingBackBelowTheLimitTurnsTheCacheBack) {+ constexpr size_t kPrompt = 16;+ constexpr uint32_t kTrimTo = 10;++ LongRopePipeline control(kUnreachableLimit);+ control.prefill(kPrompt, 0);+ control.generate_step(kPrompt, static_cast<int64_t>(kPrompt));+ const auto control_keys = control.generate_keys();++ LongRopePipeline crossing(kCrossingLimit);+ crossing.prefill(kPrompt, 0);+ crossing.generate_step(kPrompt, static_cast<int64_t>(kPrompt));+ ASSERT_TRUE(LLMLongRopeModeTestAccess::long_mode(crossing.request()));++ crossing.generate_step(kTrimTo, kTrimTo);+ EXPECT_FALSE(LLMLongRopeModeTestAccess::long_mode(crossing.request()));+ EXPECT_EQ(LLMLongRopeModeTestAccess::stored_tokens(crossing.request()), kTrimTo + 1u);++ // Only the rows that survived the trim were turned twice; compare just those.+ const auto keys = crossing.generate_keys();+ const auto shape = crossing.generate_key_shape();+ const size_t head_dim = shape.back();+ const size_t row_stride = head_dim; // [batch, kv_heads, seq, head_dim]+ const size_t seq_len = shape[LLMLongRopeModeTestAccess::seq_dim(crossing.request())];+ ASSERT_EQ(keys.size(), control_keys.size());+ for (size_t layer = 0; layer < keys.size(); ++layer) {+ for (size_t plane = 0; plane * seq_len * row_stride < keys[layer].size(); ++plane) {+ for (size_t token = 0; token < kTrimTo; ++token) {+ for (size_t ch = 0; ch < head_dim; ++ch) {+ const size_t idx = (plane * seq_len + token) * row_stride + ch;+ ASSERT_NEAR(keys[layer][idx], control_keys[layer][idx], 4e-3f)+ << "layer " << layer << " token " << token << " channel " << ch;+ }+ }+ }+ }+}++// A transition that cannot be carried out must fail before it writes anything and must+// leave the recorded mode describing the cache as it really is - otherwise the next+// call would see no flip and run against keys from the other rotation frame.+TEST(LLMLongRopeMode, RejectedTransitionLeavesTheCacheAndTheModeAlone) {+ constexpr size_t kPrompt = 8;+ constexpr uint32_t kCached = kPrompt + 1; // the prompt plus the token just generated++ LongRopePipeline crossing(kCrossingLimit);+ crossing.prefill(kPrompt, 0);+ crossing.generate_step(kPrompt, static_cast<int64_t>(kPrompt)); // position 8, still short+ auto& req = crossing.request();+ ASSERT_FALSE(LLMLongRopeModeTestAccess::long_mode(req));+ ASSERT_EQ(LLMLongRopeModeTestAccess::stored_tokens(req), kCached);+ const auto before = crossing.generate_keys();++ // A port map without the past-key inputs: the same shape of failure as a KV layout+ // the rewrite does not support.+ ov::npuw::LLMInferRequest::PortsMap broken;+ for (const auto& [name, port] : LLMLongRopeModeTestAccess::generate_in_ports(req)) {+ if (!ov::npuw::util::isPastKeyParam(name)) {+ broken.emplace(name, port);+ }+ }++ // A position past the limit, so the transition to long is the one being attempted.+ auto long_position = make_i64({1, 1}, kCrossingLimit);+ const auto position_ids = ov::get_tensor_impl(long_position);++ EXPECT_THROW(LLMLongRopeModeTestAccess::sync_mode(req, broken, position_ids, kCached), ov::Exception);+ EXPECT_FALSE(LLMLongRopeModeTestAccess::long_mode(req));+ expect_keys_near(crossing.generate_keys(), before, 0.0f);++ // The flip is still pending, so a well-formed retry performs it in full.+ LLMLongRopeModeTestAccess::sync_mode(req,+ LLMLongRopeModeTestAccess::generate_in_ports(req),+ position_ids,+ kCached);+ EXPECT_TRUE(LLMLongRopeModeTestAccess::long_mode(req));+ EXPECT_NE(crossing.generate_keys(), before);+}++// A block-based cache holds the same keys in a pool of fixed-size blocks, so the turn has+// to find them there instead of in one tensor per layer. Same observation trick as above,+// but read out of the pool: a request port is either a view of a block, a copy of one, or+// a dummy tensor shared by every port that currently backs no token.+class LongRopeBlockCache : public ::testing::Test {+protected:+ // Block size follows the chunk size. The generate model's past KV is 95 rows, so two+ // numbered blocks cover positions 0..63 and a tail block covers the rest - the prompt+ // and crossing below are picked to populate the tail as well.+ static ov::AnyMap block_props() {+ return {{"NPUW_LLM_PREFILL_HINT", "DYNAMIC"},+ {"NPUW_LLM_PREFILL_CHUNK_SIZE", "32"},+ {"NPUW_LLM_PREFILL_ATTENTION_HINT", "PYRAMID"},+ {"NPUW_LLM_GENERATE_ATTENTION_HINT", "PYRAMID"},+ {"NPUW_LLM_ENABLE_BLOCK_BASED_KV_CACHE", "YES"}};+ }++ struct PooledKeys {+ ov::Shape block_shape;+ std::vector<uint32_t> layer;+ std::vector<uint32_t> first_token; // where each block's row 0 sits in the cache+ std::vector<uint32_t> live_tokens;+ std::vector<std::vector<float>> data;+ };++ // Every live key block of every layer, layer-major and in block order.+ static PooledKeys pooled_keys(ov::npuw::LLMInferRequest& req, uint32_t num_cached) {+ auto& strategy = LLMLongRopeModeTestAccess::block_strategy(req);+ const auto& managers = LLMLongRopeModeTestAccess::block_managers(strategy);+ const uint32_t block_size = LLMLongRopeModeTestAccess::block_size(strategy);++ std::vector<uint32_t> layers;+ for (const auto& [layer_idx, unused] : managers) {+ layers.push_back(layer_idx);+ }+ std::sort(layers.begin(), layers.end());++ PooledKeys out;+ for (const uint32_t layer_idx : layers) {+ auto* manager = managers.at(layer_idx).key_manager.get();+ EXPECT_NE(manager, nullptr);+ const auto allocated = manager->get_allocated_blocks();+ for (uint32_t first = 0u; first < num_cached; first += block_size) {+ EXPECT_LT(first / block_size, allocated.size());+ const auto tensor = manager->get_block_tensor(allocated[first / block_size]);+ out.block_shape = tensor->get_shape();+ out.layer.push_back(layer_idx);+ out.first_token.push_back(first);+ out.live_tokens.push_back(std::min(num_cached - first, block_size));+ out.data.push_back(to_floats(tensor));+ }+ }+ return out;+ }++ // The turn the request is expected to have applied, block by block: each block reads+ // the delta rows its own positions land on.+ static PooledKeys expected_turn(PooledKeys keys,+ uint32_t seq_dim,+ ov::npuw::patterns::pre_compute::LongRopeCosSin& tables,+ uint32_t num_cached,+ bool to_long) {+ const auto delta = ov::npuw::longrope::make_mode_delta(tables, 0, num_cached, to_long);+ for (size_t i = 0; i < keys.data.size(); ++i) {+ auto tensor = ov::get_tensor_impl(+ ov::Tensor(ov::element::f32, keys.block_shape, keys.data[i].data()));+ const auto layout = ov::npuw::longrope::check_key_tensor(tensor, seq_dim, keys.live_tokens[i], delta);+ ov::npuw::longrope::rerotate_keys(layout, keys.live_tokens[i], delta, keys.first_token[i]);+ }+ return keys;+ }++ static void run(LongRopePipeline& pipeline, size_t prompt, int64_t last_position) {+ pipeline.prefill(prompt, 0);+ for (int64_t position = static_cast<int64_t>(prompt); position <= last_position; ++position) {+ pipeline.generate_step(static_cast<size_t>(position), position);+ }+ }++ // Flat element indices of the rows a block actually holds a key in. The rows past+ // them are never written, so two runs need not agree there.+ static std::vector<size_t> live_elements(const ov::Shape& shape, uint32_t seq_dim, uint32_t live_tokens) {+ size_t seq_stride = 1;+ for (size_t d = seq_dim + 1; d < shape.size(); ++d) {+ seq_stride *= shape[d];+ }+ const size_t seq_len = shape[seq_dim];+ const size_t outer = ov::shape_size(shape) / (seq_len * seq_stride);+ std::vector<size_t> indices;+ indices.reserve(outer * live_tokens * seq_stride);+ for (size_t o = 0; o < outer; ++o) {+ for (size_t t = 0; t < live_tokens; ++t) {+ for (size_t k = 0; k < seq_stride; ++k) {+ indices.push_back((o * seq_len + t) * seq_stride + k);+ }+ }+ }+ return indices;+ }+};++// The crossing turns every cached key held in the pool, across both the numbered blocks+// and the tail one, and leaves the tail port - which holds a copy of its block rather than+// a view of it - agreeing with the block it was copied from.+TEST_F(LongRopeBlockCache, CrossingTurnsEveryBlockOfThePool) {+ constexpr size_t kPrompt = 64; // two full blocks+ constexpr int64_t kLimit = 100; // crossed by the generate step at position 100+ constexpr uint32_t kCached = 100; // rows in the cache when that step re-rotates, three+ // full blocks plus four rows of the tail one++ LongRopePipeline control(kUnreachableLimit, block_props());+ run(control, kPrompt, kLimit);+ ASSERT_FALSE(LLMLongRopeModeTestAccess::long_mode(control.request()));+ const auto control_keys = pooled_keys(control.request(), kCached);+ // The prompt must have reached past the numbered blocks, or the tail path goes untested.+ ASSERT_GT(control_keys.first_token.back(), 0u);++ LongRopePipeline crossing(kLimit, block_props());+ run(crossing, kPrompt, kLimit);+ EXPECT_TRUE(LLMLongRopeModeTestAccess::long_mode(crossing.request()));++ const auto expected = expected_turn(control_keys,+ LLMLongRopeModeTestAccess::seq_dim(crossing.request()),+ LLMLongRopeModeTestAccess::tables(crossing.request()),+ kCached,+ true);+ const auto actual = pooled_keys(crossing.request(), kCached);+ const uint32_t seq_dim = LLMLongRopeModeTestAccess::seq_dim(crossing.request());+ ASSERT_EQ(actual.data.size(), expected.data.size());+ bool any_difference = false;+ for (size_t i = 0; i < actual.data.size(); ++i) {+ ASSERT_EQ(actual.data[i].size(), expected.data[i].size());+ for (const size_t e : live_elements(actual.block_shape, seq_dim, actual.live_tokens[i])) {+ ASSERT_NEAR(actual.data[i][e], expected.data[i][e], 2e-3f) << "block " << i << " element " << e;+ any_difference = any_difference || actual.data[i][e] != control_keys.data[i][e];+ }+ }+ // A turn that did nothing would trivially satisfy the comparison above.+ EXPECT_TRUE(any_difference);++ // The tail port is a copy, so an in-place turn of the pool alone would leave it stale.+ size_t tails_checked = 0;+ for (const auto& entry : LLMLongRopeModeTestAccess::generate_in_ports(crossing.request())) {+ const auto& name = entry.first;+ if (!ov::npuw::util::isPastKeyParam(name) || name.find("block_tail") == std::string::npos) {+ continue;+ }+ const uint32_t layer = static_cast<uint32_t>(std::stoi(name.substr(name.find('.') + 1)));+ // The tail port of a layer holds that layer's last block, the one whose rows sit+ // past the numbered ports.+ size_t block = actual.data.size();+ for (size_t i = 0; i < actual.data.size(); ++i) {+ if (actual.layer[i] != layer) {+ continue;+ }+ if (block == actual.data.size() || actual.first_token[i] > actual.first_token[block]) {+ block = i;+ }+ }+ ASSERT_LT(block, actual.data.size()) << "no pooled block for " << name;++ const auto tail_tensor = LLMLongRopeModeTestAccess::generate_past(crossing.request(), name);+ const auto tail = to_floats(tail_tensor);+ // The tail is a shorter tensor than a block, so each side is indexed through its+ // own shape.+ const auto tail_idx = live_elements(tail_tensor->get_shape(), seq_dim, actual.live_tokens[block]);+ const auto block_idx = live_elements(actual.block_shape, seq_dim, actual.live_tokens[block]);+ ASSERT_EQ(tail_idx.size(), block_idx.size());+ for (size_t i = 0; i < tail_idx.size(); ++i) {+ ASSERT_FLOAT_EQ(tail[tail_idx[i]], actual.data[block][block_idx[i]]) << "tail " << name << " row " << i;+ }+ ++tails_checked;+ }+ EXPECT_GT(tails_checked, 0u);+}++// A KV layout the rewrite cannot turn is refused when the model is compiled, not at the+// crossing token: by then there is no correct thing left to do.+class LongRopeCompileRejection : public ::testing::Test {+protected:+ static ov::AnyMap base_props() {+ return {{"NPUW_LLM", "YES"},+ {"NPUW_DEVICES", "CPU"},+ {"NPUW_LLM_MAX_PROMPT_LEN", "64"},+ {"NPUW_LLM_MIN_RESPONSE_LEN", "32"},+ {"NPUW_LLM_CACHE_ROPE", "YES"}};+ }++ void compile(int64_t context_limit, const ov::AnyMap& extra) {+ auto props = base_props();+ for (const auto& [key, value] : extra) {+ props[key] = value;+ }+ ov::npuw::LLMCompiledModel(build_longrope_llm_test_model(context_limit),+ std::make_shared<NullPlugin>(),+ props,+ make_fake_factory());+ }++ void expect_longrope_rejection(int64_t context_limit, const ov::AnyMap& extra) {+ try {+ compile(context_limit, extra);+ FAIL() << "compilation was expected to be rejected";+ } catch (const ov::Exception& e) {+ EXPECT_NE(std::string(e.what()).find("LongRoPE mode changes"), std::string::npos) << e.what();+ }+ }+};++TEST_F(LongRopeCompileRejection, QuantizedKvCache) {+ expect_longrope_rejection(kCrossingLimit, {{ov::hint::kv_cache_precision.name(), ov::element::i8}});+}++} // anonymous namespacediff --git a/src/plugins/intel_npu/tests/unit/npuw/llm_test_helpers.hpp b/src/plugins/intel_npu/tests/unit/npuw/llm_test_helpers.hppindex 34d4b8547e1..fcc7179fcd4 100644--- a/src/plugins/intel_npu/tests/unit/npuw/llm_test_helpers.hpp+++ b/src/plugins/intel_npu/tests/unit/npuw/llm_test_helpers.hpp@@ -5,6 +5,7 @@#pragma once#include <algorithm>+#include <cmath>#include <cstring>#include <memory>#include <string>@@ -47,6 +48,21 @@ inline std::shared_ptr<ov::Model> build_llm_test_model() {return mb.build_llm(make_test_model_config());}+/// Phi-style LongRoPE LLM: the RoPE inverse frequencies are picked from+/// max(position_ids) + 1 <= context_limit, so extract_longrope_context_limit() finds the+/// limit and RopeCache rewrites the chain into the host-fed npuw_lr_cos / npuw_lr_sin+/// model inputs. Compile it with NPUW_LLM_CACHE_ROPE=YES to get that rewrite.+inline std::shared_ptr<ov::Model> build_longrope_llm_test_model(int64_t context_limit) {+ auto cfg = make_test_model_config();+ for (size_t i = 0; i < cfg.head_dim / 2; ++i) {+ cfg.longrope.inv_freq_short.push_back(1.0f / std::pow(3.0f, static_cast<float>(i)));+ cfg.longrope.inv_freq_long.push_back(0.6f / std::pow(3.4f, static_cast<float>(i)));+ }+ cfg.longrope.context_limit = context_limit;+ ModelBuilder mb;+ return mb.build_llm(cfg);+}+/// Build an LLM test model configured so that Attention::from() can unambiguously/// identify the past-KV dimension in the isolated attention function body.///diff --git a/src/plugins/intel_npu/tests/unit/npuw/pre_compute_test.cpp b/src/plugins/intel_npu/tests/unit/npuw/pre_compute_test.cppindex 3e0815f8a87..2d52493121d 100644--- a/src/plugins/intel_npu/tests/unit/npuw/pre_compute_test.cpp+++ b/src/plugins/intel_npu/tests/unit/npuw/pre_compute_test.cpp@@ -259,8 +259,8 @@ TEST(PreComputeTest, ExtractLongRopeContextLimitFromBothPatterns) {EXPECT_FALSE(pc::extract_longrope_context_limit(plain).has_value());}-// Both regimes live in one tensor, short rows first. Views must be dense and, when the-// long half is absent, both regimes must resolve to the same rows.+// Both modes live in one tensor, short rows first. Views must be dense and, when the+// long half is absent, both modes must resolve to the same rows.TEST(PreComputeTest, LongRopeCosSinTableLayout) {ov::npuw::patterns::pre_compute::LongRopeCosSin tables;tables.max_len = 8;@@ -281,11 +281,11 @@ TEST(PreComputeTest, LongRopeCosSinTableLayout) {EXPECT_TRUE(long_rows.is_continuous());EXPECT_EQ(short_rows.data<ov::float16>(), tables.cos.data<ov::float16>());EXPECT_EQ(long_rows.data<ov::float16>(), tables.cos.data<ov::float16>() + 8 * 4);- // Row 1 differs between regimes because the frequencies do.+ // Row 1 differs between modes because the frequencies do.EXPECT_NE(static_cast<float>(short_rows.data<ov::float16>()[4]),static_cast<float>(long_rows.data<ov::float16>()[4]));- // Long half dropped: half the memory, and both regimes bind the short rows.+ // Long half dropped: half the memory, and both modes bind the short rows.tables.has_long = false;tables.rebuild_tables();ASSERT_TRUE(tables.is_valid());@@ -293,7 +293,7 @@ TEST(PreComputeTest, LongRopeCosSinTableLayout) {EXPECT_EQ(tables.cos_rows(5, true).data<ov::float16>(), tables.cos_rows(5, false).data<ov::float16>());}-// The host re-evaluates the regime as max(position_ids) >= context_limit, which only+// The host re-evaluates the mode as max(position_ids) >= context_limit, which only// matches the graph when the compared sum adds exactly 1. Anything else must be// refused instead of silently binding the wrong coefficients.TEST(PreComputeTest, RopeCacheRejectsUnexpectedConditionOffset) {