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] Make RoPe coefficients to be inputs in case of LongRope (#37532)
Alexander Kalistratove0afb7e49563
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 79d21ebd185..458ac111399 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@@ -1211,7 +1211,7 @@ ov::npuw::LLMCompiledModel::LLMCompiledModel(const std::shared_ptr<ov::Model>& m}m_longrope_context_limit =- ov::npuw::patterns::pre_compute::extract_phi_v5_longrope_context_limit(prefill_model).value_or(0u);+ ov::npuw::patterns::pre_compute::extract_longrope_context_limit(prefill_model).value_or(0u);if (m_longrope_context_limit > 0u) {LOG_INFO("Detected long-rope context limit: " << m_longrope_context_limit);}@@ -1222,12 +1222,26 @@ ov::npuw::LLMCompiledModel::LLMCompiledModel(const std::shared_ptr<ov::Model>& mconst bool is_best = (generate_hint == ::intel_npu::npuw::llm::GenerateHint::BEST_PERF);const bool force_rope_cache = m_longrope_context_limit > 0u;+ // Every variant derives its coefficients from the same model constants and+ // indexes them by absolute position, so the tables only differ in length -+ // keep one set covering the longest LUT.+ auto absorb_longrope_tables = [this](const auto& tables) {+ if (tables.rotary_ndims == 0) {+ return;+ }+ if (m_longrope_tables.rotary_ndims == 0) {+ m_longrope_tables = tables;+ } else {+ NPUW_ASSERT(m_longrope_tables.rotary_ndims == tables.rotary_ndims);+ m_longrope_tables.max_len = std::max(m_longrope_tables.max_len, tables.max_len);+ }+ };+if (!is_best || (max_prompt_len >= CACHE_ROPE_START || force_rope_cache)) {LOG_DEBUG("Enable RoPE Cache for prefill");- ov::npuw::patterns::pre_compute::RopeCache rope_prefill_cacher(- max_prompt_len,- ov::npuw::LLMInferRequest::layer_names::longrope_input);+ ov::npuw::patterns::pre_compute::RopeCache rope_prefill_cacher(max_prompt_len);rope_prefill_cacher.run_on_model(prefill_model);+ absorb_longrope_tables(rope_prefill_cacher.host_tables());}// Apply RoPE Cache to all generate variant models@@ -1235,12 +1249,22 @@ ov::npuw::LLMCompiledModel::LLMCompiledModel(const std::shared_ptr<ov::Model>& mconst uint32_t kv_size = m_kvcache_sizes[i];if (!is_best || (kv_size >= CACHE_ROPE_START || force_rope_cache)) {LOG_DEBUG("Enable RoPE Cache for generate variant with size: " << kv_size);- ov::npuw::patterns::pre_compute::RopeCache rope_cacher(- kv_size,- ov::npuw::LLMInferRequest::layer_names::longrope_input);+ ov::npuw::patterns::pre_compute::RopeCache rope_cacher(kv_size);rope_cacher.run_on_model(generate_model_variants[i]);+ absorb_longrope_tables(rope_cacher.host_tables());}}++ // 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.+ 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) {+ LOG_INFO("LongRoPE long factors are unreachable for this configuration - keeping the short ones only");+ }+ m_longrope_tables.rebuild_tables();}if (is_moe) {@@ -1468,6 +1492,13 @@ void ov::npuw::LLMCompiledModel::serialize(std::ostream& raw_stream, const ov::nm_longrope_context_limit & m_is_whisper & m_eos_token_id & m_decomposed_sdpa_size & m_is_eagle &m_is_embedding & m_is_block_kv_cache & m_is_encoder_embedding;+ // LongRoPE cos/sin tables: the transformed graphs have npuw_lr_cos/npuw_lr_sin+ // inputs the host must fill every call, but deserialization imports already-+ // compiled children and never re-runs RopeCache - so they have to travel with+ // the blob. Only the dimensions and the two inverse-frequency arrays are+ // written; LongRopeCosSin::serialize() rebuilds the tables on read.+ stream & m_longrope_tables;+// Write configstream & m_cfg;@@ -1695,6 +1726,9 @@ std::shared_ptr<ov::npuw::LLMCompiledModel> ov::npuw::LLMCompiledModel::deserialcompiled->m_decomposed_sdpa_size & compiled->m_is_eagle & compiled->m_is_embedding &compiled->m_is_block_kv_cache & compiled->m_is_encoder_embedding;+ // LongRoPE cos/sin tables - see the matching comment in serialize()+ stream & compiled->m_longrope_tables;+// Deserialize configstream & compiled->m_cfg;compiled->implement_properties();diff --git a/src/plugins/intel_npu/src/plugin/npuw/llm_compiled_model.hpp b/src/plugins/intel_npu/src/plugin/npuw/llm_compiled_model.hppindex 5eacbfd8d68..de1709078a4 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@@ -8,6 +8,7 @@#include "compiled_model.hpp"#include "npuw_transformations/kv_axes_position.hpp"+#include "partitioning/patterns/pre_compute.hpp"namespace ov {namespace test {@@ -141,6 +142,13 @@ private:uint64_t m_prefix_caching_max_num_blocks = 0;uint64_t m_longrope_context_limit = 0;+ // Host-side LongRoPE cos/sin coefficient tables used to fill the npuw_lr_cos/+ // npuw_lr_sin model inputs at runtime (see LongRopeCosSin, pre_compute.hpp) -+ // only valid (is_valid() == true) when the model matched LongRopePatternPhi_v5.+ // Sized to the longest LUT in the model; prefill and the smaller generate+ // variants take its leading rows. Part of the exported blob (see serialize()).+ ov::npuw::patterns::pre_compute::LongRopeCosSin m_longrope_tables;+// Continuous prefill support. Opted in via NPUW_LLM_ENABLE_CONTINUOUS_PREFILL and// mutually exclusive with hash prefix caching, which fails compilation.bool m_enable_continuous_prefill = false;diff --git a/src/plugins/intel_npu/src/plugin/npuw/llm_infer_base_request.hpp b/src/plugins/intel_npu/src/plugin/npuw/llm_infer_base_request.hppindex 7f6b382fc2d..6611cb84b23 100644--- a/src/plugins/intel_npu/src/plugin/npuw/llm_infer_base_request.hpp+++ b/src/plugins/intel_npu/src/plugin/npuw/llm_infer_base_request.hpp@@ -23,7 +23,6 @@ public:static constexpr const char* output_embeds = "npuw_output_embed";static constexpr const char* logits = "logits";static constexpr const char* token_type_ids = ov::npuw::util::kTokenTypeIdsParamName;- static constexpr const char* longrope_input = "npuw_longrope_input";static constexpr const char* per_layer_inputs = "per_layer_inputs";static constexpr const char* visual_pos_masks = ov::npuw::util::kVisualPosMasksParamName;static constexpr const char* deepstack_visual_embeds = ov::npuw::util::kDeepstackVisualEmbedsParamName;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 3464a1ad0df..ca09e59eb04 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@@ -15,6 +15,7 @@#include "logging.hpp"#include "openvino/core/parallel.hpp"#include "openvino/runtime/iasync_infer_request.hpp"+#include "openvino/runtime/make_tensor.hpp"#include "util.hpp"namespace {@@ -215,14 +216,47 @@ size_t scatter_deepstack_visual_embeds(const ov::SoPtr<ov::ITensor>& src,return k;}-void process_longrope(const std::shared_ptr<ov::IAsyncInferRequest>& infer_req,- const LLMInferRequest::PortsMap& ports,- const ov::SoPtr<ov::ITensor>& position_ids) {- if (auto longrope_port_it = ports.find(LLMInferRequest::layer_names::longrope_input);- longrope_port_it != ports.end()) {- auto longrope_input = infer_req->get_tensor(longrope_port_it->second);- longrope_input->data<int64_t>()[0] = get_max_position_id(position_ids);+// 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+// 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.+//+// 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,+ const LLMInferRequest::PortsMap& ports,+ ov::npuw::patterns::pre_compute::LongRopeCosSin& tables,+ const ov::SoPtr<ov::ITensor>& position_ids,+ uint64_t context_limit) {+ namespace pc = ov::npuw::patterns::pre_compute;++ const 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;}+ // 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+ // failed to come back.+ OPENVINO_ASSERT(tables.is_valid(),+ "NPUW: the compiled model has npuw_lr_cos/npuw_lr_sin inputs but no precomputed LongRoPE "+ "cos/sin table to bind them to.");++ const auto max_position_id = get_max_position_id(position_ids);+ const bool is_long = max_position_id >= 0 && static_cast<uint64_t>(max_position_id) >= context_limit;++ const auto& lut_shape = cos_port_it->second.get_shape();+ OPENVINO_ASSERT(lut_shape.size() == 3 && lut_shape.back() == tables.rotary_ndims,+ "NPUW: unexpected npuw_lr_cos/npuw_lr_sin shape, expected [1, lut_len, rotary_ndims]");+ const auto lut_len = lut_shape[1];++ infer_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)));}} // anonymous namespace@@ -1251,7 +1285,13 @@ void ov::npuw::LLMInferRequest::infer_prefill(ov::SoPtr<ov::ITensor> input_ids,}});- process_longrope(m_prefill_request, m_prefill_in_ports, position_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);m_llm_profile["1/prefill:2.apply_lora"].record([&]() {apply_lora();@@ -1452,7 +1492,11 @@ 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(m_kvcache_request, m_kvcache_in_ports, position_ids);+ 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);// 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/partitioning/patterns/pre_compute.cpp b/src/plugins/intel_npu/src/plugin/npuw/partitioning/patterns/pre_compute.cppindex 448ab9cdf7b..7ddbfd4a50d 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@@ -5,6 +5,7 @@#include "pre_compute.hpp"#include "../../logging.hpp"+#include "../../orc.hpp"#include "openvino/op/ops.hpp"#include "openvino/pass/manager.hpp"#include "openvino/pass/pattern/op/optional.hpp"@@ -17,19 +18,23 @@ namespace pre_compute = ov::npuw::patterns::pre_compute;namespace {// TODO: copied from common tests-// Builds a [1, max_position_embeddings, rotary_ndims] sin/cos LUT.-// When duplicate=true (LLama2-style rotate_half), rotary_ndims = inv_freq_size*2-// and the second half mirrors the first (torch.cat([freqs, freqs], dim=-1)).-// When duplicate=false (GPT-style), rotary_ndims = inv_freq_size with no mirroring.-static ov::OutputVector makeCosSinCache(const size_t max_position_embeddings,- const std::shared_ptr<ov::Node> inverse_frequencies,- bool duplicate = true) {- const auto inverse_freq_fp32 = ov::as_type_ptr<ov::op::v0::Constant>(inverse_frequencies)->cast_vector<float>();- const size_t inv_freq_size = ov::shape_size(inverse_frequencies->get_shape());- const size_t rotary_ndims = duplicate ? inv_freq_size * 2 : inv_freq_size;-- std::vector<ov::float16> lut_sin(max_position_embeddings * rotary_ndims, 0.0f);- std::vector<ov::float16> lut_cos(max_position_embeddings * rotary_ndims, 0.0f);+// Writes `rows` rows of a rotate_half-style sin/cos LUT, row i holding the+// coefficients for absolute position i.+// When duplicate=true (LLama2-style rotate_half), the row is inv_freq_size*2 wide and+// its second half mirrors the first (torch.cat([freqs, freqs], dim=-1)). When+// duplicate=false (GPT-style) the row is inv_freq_size wide with no mirroring.+//+// Coefficients are computed in f32 and stored as f16 - the precision the graph-side+// RoPE cache has always used.+static void writeCosSinRows(const std::vector<float>& inverse_freq_fp32,+ bool duplicate,+ size_t rows,+ ov::float16* pcos,+ ov::float16* psin) {+ const size_t inv_freq_size = inverse_freq_fp32.size();+ const size_t row_width = duplicate ? inv_freq_size * 2 : inv_freq_size;+ std::fill_n(pcos, rows * row_width, ov::float16{0.0f});+ std::fill_n(psin, rows * row_width, ov::float16{0.0f});// rotate_half style cos/sin table:// y1 = cos(m*xita_i) * x1 - sin(m*xita_i) * x2@@ -37,22 +42,39 @@ static ov::OutputVector makeCosSinCache(const size_t max_position_embeddings,//for (size_t k = 0; k < inv_freq_size; k++) {auto xita_i = inverse_freq_fp32[k];- ov::float16* psin = lut_sin.data();- ov::float16* pcos = lut_cos.data();- for (size_t m = 0; m < max_position_embeddings; m++, psin += rotary_ndims, pcos += rotary_ndims) {- pcos[k] = ov::float16{std::cos(xita_i * static_cast<float>(m))};- psin[k] = ov::float16{std::sin(xita_i * static_cast<float>(m))};+ ov::float16* row_sin = psin;+ ov::float16* row_cos = pcos;+ for (size_t m = 0; m < rows; m++, row_sin += row_width, row_cos += row_width) {+ row_cos[k] = ov::float16{std::cos(xita_i * static_cast<float>(m))};+ row_sin[k] = ov::float16{std::sin(xita_i * static_cast<float>(m))};if (duplicate) {- pcos[k + inv_freq_size] = pcos[k];- psin[k + inv_freq_size] = psin[k];+ row_cos[k + inv_freq_size] = row_cos[k];+ row_sin[k + inv_freq_size] = row_sin[k];}}}+}- auto Cos =- ov::op::v0::Constant::create(ov::element::f16, ov::Shape({1, max_position_embeddings, rotary_ndims}), lut_cos);- auto Sin =- ov::op::v0::Constant::create(ov::element::f16, ov::Shape({1, max_position_embeddings, rotary_ndims}), lut_sin);+// Builds a [1, max_position_embeddings, rotary_ndims] cos/sin LUT pair as graph+// Constants. Used by every RoPE flavour except LongRoPE, which gets host-fed model+// inputs instead.+static ov::OutputVector makeCosSinCache(const size_t max_position_embeddings,+ const std::shared_ptr<ov::Node> inverse_frequencies,+ bool duplicate = true) {+ const auto inverse_freq_fp32 = ov::as_type_ptr<ov::op::v0::Constant>(inverse_frequencies)->cast_vector<float>();+ const size_t rotary_ndims = duplicate ? inverse_freq_fp32.size() * 2 : inverse_freq_fp32.size();++ const ov::Shape table_shape{1, max_position_embeddings, rotary_ndims};+ ov::Tensor lut_cos(ov::element::f16, table_shape);+ ov::Tensor lut_sin(ov::element::f16, table_shape);+ writeCosSinRows(inverse_freq_fp32,+ duplicate,+ max_position_embeddings,+ lut_cos.data<ov::float16>(),+ lut_sin.data<ov::float16>());++ auto Cos = std::make_shared<ov::op::v0::Constant>(lut_cos);+ auto Sin = std::make_shared<ov::op::v0::Constant>(lut_sin);return {Cos, Sin};}@@ -181,9 +203,11 @@ ov::npuw::patterns::pre_compute::LongRopePatternPhi::LongRopePatternPhi() : matcconst std::shared_ptr<ov::Node>& inv_freq_short,const std::shared_ptr<ov::Node>& inv_freq_long) {auto red_max = opp::wrap_type<ov::op::v1::ReduceMax>({position_ids, MakeConstant()});- auto add = opp::wrap_type<ov::op::v1::Add>({red_max, MakeConstant()});+ auto cond_offset = MakeConstant();+ auto add = opp::wrap_type<ov::op::v1::Add>({red_max, cond_offset});+ auto context_limit = MakeConstant();// max(position_ids) + 1 <= original_max_position_embeddings- auto leq = opp::wrap_type<ov::op::v1::LessEqual>({add, MakeConstant()});+ auto leq = opp::wrap_type<ov::op::v1::LessEqual>({add, context_limit});auto inv_freq_short_conv = opp::optional<ov::op::v0::Convert>({inv_freq_short->output(0)});auto inv_freq_long_conv = opp::optional<ov::op::v0::Convert>({inv_freq_long->output(0)});@@ -193,7 +217,7 @@ ov::npuw::patterns::pre_compute::LongRopePatternPhi::LongRopePatternPhi() : matcauto unsqueeze = opp::optional<ov::op::v0::Unsqueeze>({select, MakeConstant()});auto unsqueeze_1 = opp::optional<ov::op::v0::Unsqueeze>({unsqueeze, MakeConstant()});- return std::make_tuple(unsqueeze_1, leq, red_max);+ return std::make_tuple(unsqueeze_1, leq, red_max, context_limit, cond_offset);};auto position_ids = opp::wrap_type<ov::op::v0::Parameter>();@@ -205,6 +229,8 @@ ov::npuw::patterns::pre_compute::LongRopePatternPhi::LongRopePatternPhi() : matcauto select = std::get<0>(select_cond_max_pos_id);auto cond = std::get<1>(select_cond_max_pos_id);auto max_pos_id = std::get<2>(select_cond_max_pos_id);+ auto context_limit = std::get<3>(select_cond_max_pos_id);+ auto cond_offset = std::get<4>(select_cond_max_pos_id);auto shape_of = opp::wrap_type<ov::op::v3::ShapeOf>({opp::any_input()});auto gather = opp::wrap_type<ov::op::v8::Gather>({shape_of, opp::any_input(), opp::any_input()});@@ -227,6 +253,8 @@ ov::npuw::patterns::pre_compute::LongRopePatternPhi::LongRopePatternPhi() : matcthis->matched_concat = map_sin.at(concat_1).get_node_shared_ptr();this->matched_inv_freq = map_sin.at(inv_freq_short).get_node_shared_ptr();this->matched_inv_freq_long = map_sin.at(inv_freq_long).get_node_shared_ptr();+ this->matched_context_limit = map_sin.at(context_limit).get_node_shared_ptr();+ this->matched_cond_offset = map_sin.at(cond_offset).get_node_shared_ptr();this->matched_cond = map_sin.at(cond).get_node_shared_ptr();this->max_pos_id = map_sin.at(max_pos_id).get_node_shared_ptr();@@ -252,7 +280,8 @@ ov::npuw::patterns::pre_compute::LongRopePatternPhi_v5::LongRopePatternPhi_v5()const std::shared_ptr<ov::Node>& multiply_const,const std::shared_ptr<ov::Node>& power_const) {auto red_max = opp::wrap_type<ov::op::v1::ReduceMax>({position_ids, MakeConstant()});- auto add = opp::wrap_type<ov::op::v1::Add>({red_max, MakeConstant()});+ auto cond_offset = MakeConstant();+ auto add = opp::wrap_type<ov::op::v1::Add>({red_max, cond_offset});auto context_limit = MakeConstant();// max(position_ids) + 1 > original_max_position_embeddingsauto greater = opp::wrap_type<ov::op::v1::Greater>({add, context_limit});@@ -267,7 +296,7 @@ ov::npuw::patterns::pre_compute::LongRopePatternPhi_v5::LongRopePatternPhi_v5()auto unsqueeze = opp::optional<ov::op::v0::Unsqueeze>({power, MakeConstant()});auto unsqueeze_1 = opp::optional<ov::op::v0::Unsqueeze>({unsqueeze, MakeConstant()});- return std::make_tuple(unsqueeze_1, greater, red_max, context_limit);+ return std::make_tuple(unsqueeze_1, greater, red_max, context_limit, cond_offset);};auto position_ids = opp::wrap_type<ov::op::v0::Parameter>();@@ -284,6 +313,7 @@ ov::npuw::patterns::pre_compute::LongRopePatternPhi_v5::LongRopePatternPhi_v5()auto cond = std::get<1>(select_cond_max_pos_id);auto max_pos_id = std::get<2>(select_cond_max_pos_id);auto context_limit = std::get<3>(select_cond_max_pos_id);+ auto cond_offset = std::get<4>(select_cond_max_pos_id);auto shape_of = opp::wrap_type<ov::op::v3::ShapeOf>({opp::any_input()});auto gather = opp::wrap_type<ov::op::v8::Gather>({shape_of, opp::any_input(), opp::any_input()});@@ -307,6 +337,7 @@ ov::npuw::patterns::pre_compute::LongRopePatternPhi_v5::LongRopePatternPhi_v5()this->matched_short_factor = map_sin.at(short_factor).get_node_shared_ptr();this->matched_long_factor = map_sin.at(long_factor).get_node_shared_ptr();this->matched_context_limit = map_sin.at(context_limit).get_node_shared_ptr();+ this->matched_cond_offset = map_sin.at(cond_offset).get_node_shared_ptr();this->matched_multiply_const = map_sin.at(multiply_const).get_node_shared_ptr();this->matched_power_const = map_sin.at(power_const).get_node_shared_ptr();this->matched_cond = map_sin.at(cond).get_node_shared_ptr();@@ -323,24 +354,42 @@ ov::npuw::patterns::pre_compute::LongRopePatternPhi_v5::LongRopePatternPhi_v5()matcher.register_patterns({output_sin, output_cos}, make_matcher_callback());}-std::optional<uint64_t> ov::npuw::patterns::pre_compute::extract_phi_v5_longrope_context_limit(- const std::shared_ptr<ov::Model>& model) {- auto long_rope = std::make_shared<ov::npuw::patterns::pre_compute::LongRopePatternPhi_v5>();- std::optional<uint64_t> context_limit;- long_rope->transform_cb = [&]() {- auto limit_const = ov::as_type_ptr<ov::op::v0::Constant>(long_rope->matched_context_limit);- OPENVINO_ASSERT(limit_const, "Invalid LongRopePatternPhi_v5 match, expected constant context limit");+namespace {+// Reads the original_max_position_embeddings constant captured by a LongRoPE pattern.+uint64_t read_context_limit(const std::shared_ptr<ov::Node>& limit_node) {+ auto limit_const = ov::as_type_ptr<ov::op::v0::Constant>(limit_node);+ OPENVINO_ASSERT(limit_const, "Invalid LongRoPE match, expected constant context limit");++ const auto limit_values = limit_const->cast_vector<int64_t>();+ OPENVINO_ASSERT(limit_values.size() == 1, "Invalid LongRoPE context limit, expected a single scalar value");+ OPENVINO_ASSERT(limit_values.front() >= 0, "Invalid LongRoPE context limit, expected a non-negative value");+ return static_cast<uint64_t>(limit_values.front());+}- const auto limit_values = limit_const->cast_vector<int64_t>();- OPENVINO_ASSERT(limit_values.size() == 1,- "Invalid LongRopePatternPhi_v5 context limit, expected a single scalar value");- OPENVINO_ASSERT(limit_values.front() >= 0,- "Invalid LongRopePatternPhi_v5 context limit, expected a non-negative value");+// The regime 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.+void check_cond_offset(const std::shared_ptr<ov::Node>& offset_node) {+ auto offset_const = ov::as_type_ptr<ov::op::v0::Constant>(offset_node);+ OPENVINO_ASSERT(offset_const, "Invalid LongRoPE match, expected a constant position-id offset");++ const auto offset_values = offset_const->cast_vector<int64_t>();+ OPENVINO_ASSERT(offset_values.size() == 1 && offset_values.front() == 1,+ "Unsupported LongRoPE model: the short/long factor switch is only supported in its "+ "max(position_ids) + 1 vs original_max_position_embeddings form");+}- const auto matched_limit = static_cast<uint64_t>(limit_values.front());+template <typename PatternT>+std::optional<uint64_t> extract_context_limit(const std::shared_ptr<ov::Model>& model) {+ auto long_rope = std::make_shared<PatternT>();+ std::optional<uint64_t> context_limit;+ long_rope->transform_cb = [&]() {+ check_cond_offset(long_rope->matched_cond_offset);+ const auto matched_limit = read_context_limit(long_rope->matched_context_limit);if (context_limit.has_value()) {OPENVINO_ASSERT(context_limit.value() == matched_limit,- "Inconsistent LongRopePatternPhi_v5 context limits detected in the model");+ "Inconsistent LongRoPE context limits detected in the model");} else {context_limit = matched_limit;}@@ -348,10 +397,19 @@ std::optional<uint64_t> ov::npuw::patterns::pre_compute::extract_phi_v5_longropelong_rope->run_on_model(model);return context_limit;}+} // namespace++std::optional<uint64_t> ov::npuw::patterns::pre_compute::extract_longrope_context_limit(+ const std::shared_ptr<ov::Model>& model) {+ if (auto limit = extract_context_limit<LongRopePatternPhi_v5>(model)) {+ return limit;+ }+ return extract_context_limit<LongRopePatternPhi>(model);+}ov::npuw::patterns::pre_compute::RopeCacheMatcher::RopeCacheMatcher(const uint32_t max_prompt_len,const std::shared_ptr<ov::Model>& model,- const std::string& longrope_input_name) {+ LongRopeCosSin* out_tables) {auto rpe = std::make_shared<RopePatternLLama2>();rpe->transform_cb = [&]() {@@ -360,57 +418,78 @@ ov::npuw::patterns::pre_compute::RopeCacheMatcher::RopeCacheMatcher(const uint32};rpe->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+ // 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;++ // Replaces the matched Sin/Cos with a Gather from two freshly created f16 model+ // inputs, and reports their layout plus both inverse-frequency sets to out_tables.+ auto make_lut_inputs = [&](const pre_compute::RopePatternDesc* rpe_desc,+ const std::vector<float>& inv_freq_short,+ const std::vector<float>& inv_freq_long) {+ const size_t rotary_ndims = inv_freq_short.size() * 2;+ OPENVINO_ASSERT(inv_freq_short.size() == inv_freq_long.size(),+ "Invalid LongRoPE match, expected same size for the short and long factors");++ const ov::Shape lut_shape{1, max_prompt_len, rotary_ndims};+ lr_cos_param = std::make_shared<ov::op::v0::Parameter>(ov::element::f16, lut_shape);+ lr_sin_param = std::make_shared<ov::op::v0::Parameter>(ov::element::f16, lut_shape);+ lr_cos_param->set_friendly_name(longrope_cos_input);+ lr_sin_param->set_friendly_name(longrope_sin_input);++ replaceSinCosByCache(max_prompt_len, {lr_cos_param, lr_sin_param}, rpe_desc);++ if (out_tables) {+ out_tables->max_len = max_prompt_len;+ out_tables->rotary_ndims = rotary_ndims;+ out_tables->inv_freq_short = inv_freq_short;+ out_tables->inv_freq_long = inv_freq_long;+ }+ };+auto long_rpe = std::make_shared<LongRopePatternPhi>();- std::shared_ptr<ov::op::v0::Parameter> max_pos_id_param;long_rpe->transform_cb = [&]() {- auto cache_short = makeCosSinCache(max_prompt_len, long_rpe->matched_inv_freq);- auto cache_long = makeCosSinCache(max_prompt_len, long_rpe->matched_inv_freq_long);-- auto select_cos = std::make_shared<ov::op::v1::Select>(long_rpe->matched_cond, cache_short[0], cache_long[0]);- auto select_sin = std::make_shared<ov::op::v1::Select>(long_rpe->matched_cond, cache_short[1], cache_long[1]);-- replaceSinCosByCache(max_prompt_len, {select_cos, select_sin}, long_rpe.get());-- auto max_pos_id_out = long_rpe->max_pos_id->output(0);- max_pos_id_param.reset(new ov::op::v0::Parameter(max_pos_id_out.get_element_type(), {1}));- max_pos_id_param->set_friendly_name(longrope_input_name);- max_pos_id_out.replace(max_pos_id_param->output(0));+ if (lr_cos_param) {+ return; // one cos/sin cache per model+ }+ check_cond_offset(long_rpe->matched_cond_offset);+ // Unlike v5, here the matched constants already are the inverse frequencies.+ make_lut_inputs(long_rpe.get(),+ ov::as_type_ptr<ov::op::v0::Constant>(long_rpe->matched_inv_freq)->cast_vector<float>(),+ ov::as_type_ptr<ov::op::v0::Constant>(long_rpe->matched_inv_freq_long)->cast_vector<float>());};long_rpe->run_on_model(model);auto long_rpe_v5 = std::make_shared<LongRopePatternPhi_v5>();long_rpe_v5->transform_cb = [&]() {+ if (lr_cos_param) {+ return; // one cos/sin cache per model+ }+ check_cond_offset(long_rpe_v5->matched_cond_offset);auto inv_freq = calculate_freq(long_rpe_v5->matched_short_factor,long_rpe_v5->matched_long_factor,long_rpe_v5->matched_multiply_const,long_rpe_v5->matched_power_const);- auto cache_short = makeCosSinCache(max_prompt_len, inv_freq[0]);- auto cache_long = makeCosSinCache(max_prompt_len, inv_freq[1]);-- auto select_cos =- std::make_shared<ov::op::v1::Select>(long_rpe_v5->matched_cond, cache_long[0], cache_short[0]);- auto select_sin =- std::make_shared<ov::op::v1::Select>(long_rpe_v5->matched_cond, cache_long[1], cache_short[1]);-// WA: to get correct sin-cos cache sizelong_rpe_v5->matched_inv_freq = inv_freq[0];- replaceSinCosByCache(max_prompt_len, {select_cos, select_sin}, long_rpe_v5.get());-- auto max_pos_id_out = long_rpe_v5->max_pos_id->output(0);- max_pos_id_param.reset(new ov::op::v0::Parameter(max_pos_id_out.get_element_type(), {1}));- max_pos_id_param->set_friendly_name(longrope_input_name);- max_pos_id_out.replace(max_pos_id_param->output(0));+ make_lut_inputs(long_rpe_v5.get(),+ ov::as_type_ptr<ov::op::v0::Constant>(inv_freq[0])->cast_vector<float>(),+ ov::as_type_ptr<ov::op::v0::Constant>(inv_freq[1])->cast_vector<float>());};long_rpe_v5->run_on_model(model);- if (max_pos_id_param) {- model->add_parameters({max_pos_id_param});+ if (lr_cos_param) {+ model->add_parameters({lr_cos_param, lr_sin_param});for (auto&& input : model->inputs()) {- if (input.get_node() == max_pos_id_param.get()) {- input.set_names({max_pos_id_param->get_friendly_name()});+ if (input.get_node() == lr_cos_param.get()) {+ input.set_names({lr_cos_param->get_friendly_name()});+ } else if (input.get_node() == lr_sin_param.get()) {+ input.set_names({lr_sin_param->get_friendly_name()});}}}@@ -434,6 +513,59 @@ ov::npuw::patterns::pre_compute::RopeInverseFreq::RopeInverseFreq(}bool ov::npuw::patterns::pre_compute::RopeCache::run_on_model(const std::shared_ptr<ov::Model>& model) {- ov::npuw::patterns::pre_compute::RopeCacheMatcher ropeCache(m_max_prompt_len, model, m_longrope_input_name);+ ov::npuw::patterns::pre_compute::RopeCacheMatcher ropeCache(m_max_prompt_len, model, &m_host_tables);return true;}++void ov::npuw::patterns::pre_compute::LongRopeCosSin::rebuild_tables() {+ cos = {};+ sin = {};+ 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};+ cos = ov::Tensor(ov::element::f16, shape);+ sin = ov::Tensor(ov::element::f16, shape);++ writeCosSinRows(inv_freq_short, true, max_len, cos.data<ov::float16>(), sin.data<ov::float16>());+ if (has_long) {+ writeCosSinRows(inv_freq_long,+ true,+ max_len,+ cos.data<ov::float16>() + max_len * rotary_ndims,+ sin.data<ov::float16>() + max_len * rotary_ndims);+ }+}++namespace {+ov::Tensor longrope_rows(ov::Tensor& table,+ size_t max_len,+ size_t rotary_ndims,+ bool has_long,+ size_t lut_len,+ bool is_long) {+ OPENVINO_ASSERT(table && lut_len <= max_len, "LongRoPE LUT does not cover the requested rows");+ const size_t row_offset = (is_long && has_long) ? max_len : 0u;+ auto* rows = table.data<ov::float16>() + row_offset * rotary_ndims;+ return ov::Tensor(ov::element::f16, ov::Shape{1, lut_len, rotary_ndims}, rows);+}+} // namespace++ov::Tensor ov::npuw::patterns::pre_compute::LongRopeCosSin::cos_rows(size_t lut_len, bool is_long) {+ return longrope_rows(cos, max_len, rotary_ndims, has_long, lut_len, is_long);+}++ov::Tensor ov::npuw::patterns::pre_compute::LongRopeCosSin::sin_rows(size_t lut_len, bool is_long) {+ return longrope_rows(sin, max_len, rotary_ndims, has_long, lut_len, is_long);+}++void ov::npuw::patterns::pre_compute::LongRopeCosSin::serialize(ov::npuw::orc::Stream& stream) {+ stream & max_len & rotary_ndims & has_long & inv_freq_short & inv_freq_long;+ if (stream.input()) {+ // Deserialization imports already-compiled child models, so RopeCache never runs+ // again - rebuild the tables here, otherwise the imported graph's npuw_lr_cos/sin+ // inputs would have nothing to bind to.+ rebuild_tables();+ }+}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 57840741663..9ce93c1b91b 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@@ -7,8 +7,15 @@#include <cstdint>#include <optional>#include <string>+#include <vector>#include "openvino/pass/pattern/multi_matcher.hpp"+#include "openvino/runtime/tensor.hpp"++// Forward declaration - LongRopeCosSin::serialize() below only needs the type name.+namespace ov ::npuw ::orc {+class Stream;+} // namespace ov::npuw::orcnamespace ov ::npuw ::patterns ::pre_compute {@@ -37,6 +44,9 @@ public:class LongRopePatternDesc : public RopePatternDesc {public:std::shared_ptr<ov::Node> matched_inv_freq_long;+ std::shared_ptr<ov::Node> matched_context_limit;+ // The constant added to max(position_ids) before comparing against the context limit.+ std::shared_ptr<ov::Node> matched_cond_offset;std::shared_ptr<ov::Node> matched_cond;std::shared_ptr<ov::Node> max_pos_id;};@@ -46,6 +56,8 @@ public:std::shared_ptr<ov::Node> matched_short_factor;std::shared_ptr<ov::Node> matched_long_factor;std::shared_ptr<ov::Node> matched_context_limit;+ // The constant added to max(position_ids) before comparing against the context limit.+ std::shared_ptr<ov::Node> matched_cond_offset;std::shared_ptr<ov::Node> matched_cond;std::shared_ptr<ov::Node> max_pos_id;std::shared_ptr<ov::Node> matched_multiply_const;@@ -85,16 +97,79 @@ public:}};-// Runs LongRopePatternPhi_v5 on the model and, if matched, extracts the-// original_max_position_embeddings context limit constant it captures.-// Returns std::nullopt if the pattern doesn't match.-std::optional<uint64_t> extract_phi_v5_longrope_context_limit(const std::shared_ptr<ov::Model>& model);+// Runs the LongRoPE patterns (LongRopePatternPhi_v5, then LongRopePatternPhi) on the+// model and, if one matches, extracts the original_max_position_embeddings context+// limit constant it captures. Returns std::nullopt if neither pattern matches.+std::optional<uint64_t> extract_longrope_context_limit(const std::shared_ptr<ov::Model>& model);++// Names of the two model inputs the LongRoPE RoPE-cache+// rewrite creates for the cos/sin coefficient tables - see RopeCacheMatcher.+constexpr const char* longrope_cos_input = "npuw_lr_cos";+constexpr const char* longrope_sin_input = "npuw_lr_sin";++// Host-side LongRoPE cos/sin coefficient tables, in the exact layout of the+// npuw_lr_cos/npuw_lr_sin model inputs (f16, row i == absolute position i), so a model+// input can be pointed straight at them with set_tensor - no per-inference copy.+//+// The graph itself holds no cos/sin values for such a model: these host-owned buffers+// are the only place they exist, and the short/long-factor choice the model used to+// make with an in-graph Select is made by the host when it picks which rows to bind.+// 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,+// 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+// 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+// 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 rotary_ndims = 0; // row width; 0 means "no LongRoPE in this model"+ bool has_long = false;++ std::vector<float> inv_freq_short; // rotary_ndims/2 entries+ std::vector<float> inv_freq_long; // rotary_ndims/2 entries++ // f16, [1, (has_long ? 2 : 1) * max_len, rotary_ndims]. Empty until rebuild_tables().+ ov::Tensor cos;+ ov::Tensor sin;++ bool is_valid() const {+ return max_len > 0 && rotary_ndims > 0 && static_cast<bool>(cos) && static_cast<bool>(sin);+ }++ // (Re)builds the two tensors from max_len/rotary_ndims/has_long and the inverse-+ // 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.+ // 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);+ ov::Tensor sin_rows(size_t lut_len, bool is_long);++ void serialize(ov::npuw::orc::Stream& stream);+};class RopeCacheMatcher {public:+ // On a LongRoPE match (either LongRopePatternPhi_v5 or LongRopePatternPhi) the+ // cos/sin LUTs are created as model inputs (npuw_lr_cos/npuw_lr_sin) instead of+ // Constants, and out_tables (if non-null) receives the layout and inverse+ // frequencies the runtime needs to fill them. The tensors themselves are not built+ // here - see LongRopeCosSin.RopeCacheMatcher(const uint32_t max_prompt_len,const std::shared_ptr<ov::Model>& m,- const std::string& longrope_input_name);+ LongRopeCosSin* out_tables = nullptr);};// TODO: not used - only in tests@@ -109,17 +184,21 @@ public:class RopeCache : public ov::pass::ModelPass {const uint32_t m_max_prompt_len = 0;- std::string m_longrope_input_name;+ LongRopeCosSin m_host_tables;public:OPENVINO_MODEL_PASS_RTTI("npuw::patterns::precompute::Rope");/** Rope cache is NPUW pass that removes sin/cos subgraph and replaces it with corresponding LUT/gather operations*/- explicit RopeCache(const uint32_t max_prompt_len, const std::string& longrope_input_name)- : m_max_prompt_len(max_prompt_len),- m_longrope_input_name(longrope_input_name) {}+ explicit RopeCache(const uint32_t max_prompt_len) : m_max_prompt_len(max_prompt_len) {}bool run_on_model(const std::shared_ptr<ov::Model>& m) override;++ // Layout and inverse frequencies of this model's LongRoPE LUT inputs; rotary_ndims+ // is 0 unless one of the LongRoPE patterns matched.+ const LongRopeCosSin& host_tables() const {+ return m_host_tables;+ }};// NOLINTNEXTLINE(readability/namespace)} // namespace ov::npuw::patterns::pre_computediff --git a/src/plugins/intel_npu/src/plugin/npuw/serialization.hpp b/src/plugins/intel_npu/src/plugin/npuw/serialization.hppindex b07fb1aa92b..228516f7588 100644--- a/src/plugins/intel_npu/src/plugin/npuw/serialization.hpp+++ b/src/plugins/intel_npu/src/plugin/npuw/serialization.hpp@@ -52,7 +52,7 @@ const constexpr ov::npuw::s11n::IndicatorType NPUW_GQA_COMPILED_MODEL_INDICATORconst constexpr ov::npuw::s11n::IndicatorType NPUW_FLUX2_COMPILED_MODEL_INDICATOR ={char{0x46}, char{0x4c}, char{0x32}, char{0x43}, char{0x4d}, char{0x4f}};-const constexpr char* NPUW_SERIALIZATION_VERSION = "0.29";+const constexpr char* NPUW_SERIALIZATION_VERSION = "0.30";// Forward declarationnamespace intel_npu {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 ff58e5a593b..3e0815f8a87 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@@ -7,19 +7,23 @@#include <gtest/gtest.h>#include <algorithm>+#include <cstring>#include <memory>+#include <sstream>#include <string>#include <vector>#include "openvino/core/except.hpp"#include "openvino/op/ops.hpp"+#include "orc.hpp"namespace {std::shared_ptr<ov::Model> make_longrope_v5_model(const std::vector<float>& short_factor_values,const std::vector<float>& long_factor_values,const std::vector<float>& multiply_values,- const std::vector<float>& power_values) {+ const std::vector<float>& power_values,+ int32_t cond_offset = 1) {auto data = std::make_shared<ov::op::v0::Parameter>(ov::element::f32, ov::Shape{1, 4, 2});auto position_ids = std::make_shared<ov::op::v0::Parameter>(ov::element::i32, ov::Shape{2, 1});@@ -33,8 +37,8 @@ std::shared_ptr<ov::Model> make_longrope_v5_model(const std::vector<float>& shorauto reduce_axes = ov::op::v0::Constant::create(ov::element::i64, ov::Shape{2}, {0, 1});auto red_max = std::make_shared<ov::op::v1::ReduceMax>(position_ids, reduce_axes, false);- auto one_i32 = ov::op::v0::Constant::create(ov::element::i32, ov::Shape{}, {1});- auto add = std::make_shared<ov::op::v1::Add>(red_max, one_i32);+ auto offset_i32 = ov::op::v0::Constant::create(ov::element::i32, ov::Shape{}, {cond_offset});+ auto add = std::make_shared<ov::op::v1::Add>(red_max, offset_i32);auto max_pos = ov::op::v0::Constant::create(ov::element::i32, ov::Shape{}, {4});auto greater = std::make_shared<ov::op::v1::Greater>(add, max_pos);@@ -77,6 +81,61 @@ std::shared_ptr<ov::Model> make_longrope_v5_model(const std::vector<float>& shor"longrope_v5_test_model");}+// Builds a minimal model matching the older LongRopePatternPhi: the Select picks+// between two ready-made inverse-frequency constants on+// max(position_ids) + 1 <= original_max_position_embeddings.+std::shared_ptr<ov::Model> make_longrope_phi_model(const std::vector<float>& inv_freq_short_values,+ const std::vector<float>& inv_freq_long_values,+ int32_t context_limit,+ int32_t cond_offset = 1) {+ auto data = std::make_shared<ov::op::v0::Parameter>(ov::element::f32, ov::Shape{1, 4, 2});+ auto position_ids = std::make_shared<ov::op::v0::Parameter>(ov::element::i32, ov::Shape{2, 1});++ auto inv_freq_short =+ ov::op::v0::Constant::create(ov::element::f32, ov::Shape{inv_freq_short_values.size()}, inv_freq_short_values);+ auto inv_freq_long =+ ov::op::v0::Constant::create(ov::element::f32, ov::Shape{inv_freq_long_values.size()}, inv_freq_long_values);++ auto reduce_axes = ov::op::v0::Constant::create(ov::element::i64, ov::Shape{2}, {0, 1});+ auto red_max = std::make_shared<ov::op::v1::ReduceMax>(position_ids, reduce_axes, false);+ auto offset_i32 = ov::op::v0::Constant::create(ov::element::i32, ov::Shape{}, {cond_offset});+ auto add = std::make_shared<ov::op::v1::Add>(red_max, offset_i32);+ auto limit = ov::op::v0::Constant::create(ov::element::i32, ov::Shape{}, {context_limit});+ auto leq = std::make_shared<ov::op::v1::LessEqual>(add, limit);++ auto select = std::make_shared<ov::op::v1::Select>(leq, inv_freq_short, inv_freq_long);++ auto unsqueeze_axis0 = ov::op::v0::Constant::create(ov::element::i64, ov::Shape{1}, {0});+ auto unsq0 = std::make_shared<ov::op::v0::Unsqueeze>(select, unsqueeze_axis0);+ auto unsq1 = std::make_shared<ov::op::v0::Unsqueeze>(unsq0, unsqueeze_axis0);++ auto shape_of = std::make_shared<ov::op::v3::ShapeOf>(data);+ auto gather_idx0 = ov::op::v0::Constant::create(ov::element::i64, ov::Shape{1}, {0});+ auto axis0 = ov::op::v0::Constant::create(ov::element::i64, ov::Shape{}, {0});+ auto gather = std::make_shared<ov::op::v8::Gather>(shape_of, gather_idx0, axis0);+ auto seq_len = ov::op::v0::Constant::create(ov::element::i64, ov::Shape{1}, {4});+ auto rotary_dims = ov::op::v0::Constant::create(ov::element::i64, ov::Shape{1}, {2});+ auto concat_1 = std::make_shared<ov::op::v0::Concat>(ov::OutputVector{gather, seq_len, rotary_dims}, 0);++ auto broadcast = std::make_shared<ov::op::v3::Broadcast>(unsq1, concat_1);+ auto pos_unsq = std::make_shared<ov::op::v0::Unsqueeze>(position_ids, unsqueeze_axis0);+ auto pos_fp32 = std::make_shared<ov::op::v0::Convert>(pos_unsq, ov::element::f32);+ auto matmul = std::make_shared<ov::op::v0::MatMul>(broadcast, pos_fp32);++ auto transpose_order = ov::op::v0::Constant::create(ov::element::i64, ov::Shape{3}, {0, 2, 1});+ auto transpose = std::make_shared<ov::op::v1::Transpose>(matmul, transpose_order);+ auto zeros = ov::op::v0::Constant::create(ov::element::f32, ov::Shape{1, 1, 4}, {0.0f, 0.0f, 0.0f, 0.0f});+ auto concat_2 = std::make_shared<ov::op::v0::Concat>(ov::OutputVector{transpose, zeros}, 1);++ auto sin = std::make_shared<ov::op::v0::Sin>(concat_2);+ auto cos = std::make_shared<ov::op::v0::Cos>(concat_2);++ return std::make_shared<ov::Model>(+ ov::ResultVector{std::make_shared<ov::op::v0::Result>(sin), std::make_shared<ov::op::v0::Result>(cos)},+ ov::ParameterVector{data, position_ids},+ "longrope_phi_test_model");+}+// Builds a minimal RoPE model matching RopePatternLLama2.// When with_concat2=true (LLama2 style): Transpose → Concat_2 → Sin/Cos, duplicate_freqs=true.// When with_concat2=false (GPT style): Transpose → Sin/Cos directly, duplicate_freqs=false.@@ -131,36 +190,197 @@ bool has_input_name(const std::shared_ptr<ov::Model>& model, const std::string&});}+size_t count_ops_of_type_sin_cos(const std::shared_ptr<ov::Model>& model) {+ const auto& ops = model->get_ops();+ return static_cast<size_t>(std::count_if(ops.begin(), ops.end(), [](const auto& op) {+ return ov::is_type<ov::op::v0::Sin>(op) || ov::is_type<ov::op::v0::Cos>(op);+ }));+}++// Every LongRoPE model, old or new pattern, must end up with the same shape of result:+// no Sin/Cos and no Select left, and two named cos/sin inputs instead.+void expect_longrope_lut_inputs(const std::shared_ptr<ov::Model>& model) {+ EXPECT_EQ(count_ops_of_type_sin_cos(model), 0u);+ const auto& ops = model->get_ops();+ EXPECT_EQ(std::count_if(ops.begin(),+ ops.end(),+ [](const auto& op) {+ return ov::is_type<ov::op::v1::Select>(op);+ }),+ 0)+ << "the short/long Select is decided on the host now";+ EXPECT_TRUE(has_input_name(model, ov::npuw::patterns::pre_compute::longrope_cos_input));+ EXPECT_TRUE(has_input_name(model, ov::npuw::patterns::pre_compute::longrope_sin_input));+ EXPECT_FALSE(has_input_name(model, "npuw_longrope_input"));+}+TEST(PreComputeTest, RopeCacheTransformsLongRopeV5Pattern) {auto model = make_longrope_v5_model({1.0f, 2.0f}, {4.0f, 5.0f}, {0.5f, 1.0f}, {2.0f});- ov::npuw::patterns::pre_compute::RopeCache pass(/*max_prompt_len=*/16, "longrope_input");+ ov::npuw::patterns::pre_compute::RopeCache pass(/*max_prompt_len=*/16);ASSERT_NO_THROW(pass.run_on_model(model));- const auto& ops = model->get_ops();- const auto sin_count = std::count_if(ops.begin(), ops.end(), [](const auto& op) {- return ov::is_type<ov::op::v0::Sin>(op);- });- const auto cos_count = std::count_if(ops.begin(), ops.end(), [](const auto& op) {- return ov::is_type<ov::op::v0::Cos>(op);- });+ expect_longrope_lut_inputs(model);++ const auto& tables = pass.host_tables();+ EXPECT_EQ(tables.max_len, 16u);+ EXPECT_EQ(tables.rotary_ndims, 4u); // 2 factors, mirrored+ // short = (factor * multiply) ^ power, long likewise+ EXPECT_EQ(tables.inv_freq_short, (std::vector<float>{0.25f, 4.0f}));+ EXPECT_EQ(tables.inv_freq_long, (std::vector<float>{4.0f, 25.0f}));+}++TEST(PreComputeTest, RopeCacheTransformsLongRopePhiPattern) {+ auto model = make_longrope_phi_model({0.5f, 0.25f}, {0.1f, 0.05f}, /*context_limit=*/4096);++ ov::npuw::patterns::pre_compute::RopeCache pass(/*max_prompt_len=*/16);+ ASSERT_NO_THROW(pass.run_on_model(model));++ expect_longrope_lut_inputs(model);++ const auto& tables = pass.host_tables();+ EXPECT_EQ(tables.max_len, 16u);+ EXPECT_EQ(tables.rotary_ndims, 4u);+ // The old pattern's constants already are the inverse frequencies.+ EXPECT_EQ(tables.inv_freq_short, (std::vector<float>{0.5f, 0.25f}));+ EXPECT_EQ(tables.inv_freq_long, (std::vector<float>{0.1f, 0.05f}));+}++TEST(PreComputeTest, ExtractLongRopeContextLimitFromBothPatterns) {+ namespace pc = ov::npuw::patterns::pre_compute;++ auto v5 = make_longrope_v5_model({1.0f, 2.0f}, {4.0f, 5.0f}, {0.5f, 1.0f}, {2.0f});+ EXPECT_EQ(pc::extract_longrope_context_limit(v5), std::optional<uint64_t>{4u});++ auto phi = make_longrope_phi_model({0.5f, 0.25f}, {0.1f, 0.05f}, /*context_limit=*/4096);+ EXPECT_EQ(pc::extract_longrope_context_limit(phi), std::optional<uint64_t>{4096u});++ auto plain = make_rope_model(/*with_concat2=*/true);+ 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.+TEST(PreComputeTest, LongRopeCosSinTableLayout) {+ ov::npuw::patterns::pre_compute::LongRopeCosSin tables;+ tables.max_len = 8;+ tables.rotary_ndims = 4;+ tables.inv_freq_short = {0.5f, 0.25f};+ tables.inv_freq_long = {0.1f, 0.05f};++ tables.has_long = true;+ tables.rebuild_tables();+ ASSERT_TRUE(tables.is_valid());+ EXPECT_EQ(tables.cos.get_shape(), (ov::Shape{1, 16, 4}));+ EXPECT_EQ(tables.sin.get_shape(), (ov::Shape{1, 16, 4}));++ auto short_rows = tables.cos_rows(/*lut_len=*/5, /*is_long=*/false);+ auto long_rows = tables.cos_rows(/*lut_len=*/5, /*is_long=*/true);+ EXPECT_EQ(short_rows.get_shape(), (ov::Shape{1, 5, 4}));+ EXPECT_TRUE(short_rows.is_continuous());+ 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.+ 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.+ tables.has_long = false;+ tables.rebuild_tables();+ ASSERT_TRUE(tables.is_valid());+ EXPECT_EQ(tables.cos.get_shape(), (ov::Shape{1, 8, 4}));+ 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+// 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) {+ namespace pc = ov::npuw::patterns::pre_compute;++ auto v5 = make_longrope_v5_model({1.0f, 2.0f}, {4.0f, 5.0f}, {0.5f, 1.0f}, {2.0f}, /*cond_offset=*/2);+ EXPECT_THROW(pc::extract_longrope_context_limit(v5), ov::AssertFailure);+ EXPECT_THROW(pc::RopeCache(/*max_prompt_len=*/16).run_on_model(v5), ov::AssertFailure);++ auto phi = make_longrope_phi_model({0.5f, 0.25f}, {0.1f, 0.05f}, /*context_limit=*/4096, /*cond_offset=*/0);+ EXPECT_THROW(pc::extract_longrope_context_limit(phi), ov::AssertFailure);+ EXPECT_THROW(pc::RopeCache(/*max_prompt_len=*/16).run_on_model(phi), ov::AssertFailure);+}++// The npuw_lr_cos/npuw_lr_sin inputs of an imported blob are bound to tables that are+// regenerated from the serialized metadata, so a round trip must reproduce them exactly.+TEST(PreComputeTest, LongRopeCosSinSerializationRoundTrip) {+ using ov::npuw::orc::Stream;++ for (bool has_long : {true, false}) {+ ov::npuw::patterns::pre_compute::LongRopeCosSin src;+ src.max_len = 12;+ src.rotary_ndims = 4;+ src.has_long = has_long;+ src.inv_freq_short = {0.5f, 0.25f};+ src.inv_freq_long = {0.1f, 0.05f};+ src.rebuild_tables();+ ASSERT_TRUE(src.is_valid());++ std::stringstream ss;+ auto writer = Stream::writer(ss);+ writer& src;++ ov::npuw::patterns::pre_compute::LongRopeCosSin dst;+ auto reader = Stream::reader(ss);+ reader& dst;++ EXPECT_EQ(dst.max_len, src.max_len);+ EXPECT_EQ(dst.rotary_ndims, src.rotary_ndims);+ EXPECT_EQ(dst.has_long, src.has_long);+ EXPECT_EQ(dst.inv_freq_short, src.inv_freq_short);+ EXPECT_EQ(dst.inv_freq_long, src.inv_freq_long);++ // serialize() rebuilds the tensors on read - they must come back byte-identical.+ ASSERT_TRUE(dst.is_valid()) << "imported tables must be usable without re-running RopeCache";+ ASSERT_EQ(dst.cos.get_shape(), src.cos.get_shape());+ ASSERT_EQ(dst.sin.get_shape(), src.sin.get_shape());+ EXPECT_EQ(std::memcmp(dst.cos.data(), src.cos.data(), src.cos.get_byte_size()), 0);+ EXPECT_EQ(std::memcmp(dst.sin.data(), src.sin.data(), src.sin.get_byte_size()), 0);++ EXPECT_EQ(dst.cos_rows(5, true).get_shape(), (ov::Shape{1, 5, 4}));+ EXPECT_EQ(dst.cos_rows(5, true).data<ov::float16>() == dst.cos_rows(5, false).data<ov::float16>(), !has_long);+ }+}- EXPECT_EQ(sin_count, 0);- EXPECT_EQ(cos_count, 0);- EXPECT_TRUE(has_input_name(model, "longrope_input"));+// A model with no LongRoPE leaves the tables empty; that must survive a round trip too,+// and must not fabricate tensors on import.+TEST(PreComputeTest, LongRopeCosSinSerializationRoundTripEmpty) {+ using ov::npuw::orc::Stream;++ ov::npuw::patterns::pre_compute::LongRopeCosSin src;+ std::stringstream ss;+ auto writer = Stream::writer(ss);+ writer& src;++ ov::npuw::patterns::pre_compute::LongRopeCosSin dst;+ dst.max_len = 7; // must be overwritten by the read+ auto reader = Stream::reader(ss);+ reader& dst;++ EXPECT_EQ(dst.max_len, 0u);+ EXPECT_EQ(dst.rotary_ndims, 0u);+ EXPECT_FALSE(dst.has_long);+ EXPECT_FALSE(dst.is_valid());}TEST(PreComputeTest, RopeCacheThrowsOnMismatchedFactorSizesInLongRopeV5) {// multiply has scalar shape {1}: graph is valid by broadcast, but calculate_freq requires exact size match.auto model = make_longrope_v5_model({1.0f, 2.0f}, {4.0f, 5.0f}, {1.0f}, {1.0f});- ov::npuw::patterns::pre_compute::RopeCache pass(/*max_prompt_len=*/16, "longrope_input");+ ov::npuw::patterns::pre_compute::RopeCache pass(/*max_prompt_len=*/16);EXPECT_THROW(pass.run_on_model(model), ov::AssertFailure);}TEST(PreComputeTest, RopeCacheThrowsOnNonScalarPowerInLongRopeV5) {auto model = make_longrope_v5_model({1.0f, 2.0f}, {4.0f, 5.0f}, {1.0f, 2.0f}, {1.0f, 2.0f});- ov::npuw::patterns::pre_compute::RopeCache pass(/*max_prompt_len=*/16, "longrope_input");+ ov::npuw::patterns::pre_compute::RopeCache pass(/*max_prompt_len=*/16);EXPECT_THROW(pass.run_on_model(model), ov::AssertFailure);}@@ -170,7 +390,7 @@ TEST(PreComputeTest, RopeCacheThrowsOnNonScalarPowerInLongRopeV5) {TEST(PreComputeTest, RopeCacheTransformsLLama2Pattern) {auto model = make_rope_model(/*with_concat2=*/true);- ov::npuw::patterns::pre_compute::RopeCache pass(/*max_prompt_len=*/16, /*longrope_input_name=*/{});+ ov::npuw::patterns::pre_compute::RopeCache pass(/*max_prompt_len=*/16);ASSERT_NO_THROW(pass.run_on_model(model));const auto& ops = model->get_ops();@@ -190,7 +410,7 @@ TEST(PreComputeTest, RopeCacheTransformsLLama2Pattern) {TEST(PreComputeTest, RopeCacheTransformsGPTPattern) {auto model = make_rope_model(/*with_concat2=*/false);- ov::npuw::patterns::pre_compute::RopeCache pass(/*max_prompt_len=*/16, /*longrope_input_name=*/{});+ ov::npuw::patterns::pre_compute::RopeCache pass(/*max_prompt_len=*/16);ASSERT_NO_THROW(pass.run_on_model(model));const auto& ops = model->get_ops();