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: Precompute and store sin/cos ops in ROPE in fp32 (#31644)
Eugene Smirnovefcb061e61f1
diff --git a/src/plugins/intel_npu/src/al/include/intel_npu/config/npuw.hpp b/src/plugins/intel_npu/src/al/include/intel_npu/config/npuw.hppindex 61455f23d46..296eaef3d61 100644--- a/src/plugins/intel_npu/src/al/include/intel_npu/config/npuw.hpp+++ b/src/plugins/intel_npu/src/al/include/intel_npu/config/npuw.hpp@@ -109,6 +109,7 @@ DEFINE_OPT(NPUW_LLM_SEQ_LEN_DIM, uint32_t, 2, npuw::llm::seq_len_dim, RunTime);DEFINE_OPT(NPUW_LLM_MAX_PROMPT_LEN, uint32_t, 1024, npuw::llm::max_prompt_len, RunTime);DEFINE_OPT(NPUW_LLM_MIN_RESPONSE_LEN, uint32_t, 128, npuw::llm::min_response_len, RunTime);DEFINE_OPT(NPUW_LLM_OPTIMIZE_V_TENSORS, bool, true, npuw::llm::optimize_v_tensors, RunTime);+DEFINE_OPT(NPUW_LLM_CACHE_ROPE, bool, true, npuw::llm::cache_rope, CompileTime);DEFINE_OPT(NPUW_LLM_PREFILL_CHUNK_SIZE, uint64_t, 256, npuw::llm::prefill_chunk_size, RunTime);DEFINE_OPT(NPUW_LLM_SHARED_HEAD, bool, true, npuw::llm::shared_lm_head, CompileTime);DEFINE_OPT(NPUW_LLM_MAX_LORA_RANK, uint32_t, 32, npuw::llm::max_lora_rank, RunTime);diff --git a/src/plugins/intel_npu/src/al/include/intel_npu/npuw_private_properties.hpp b/src/plugins/intel_npu/src/al/include/intel_npu/npuw_private_properties.hppindex d68259b6949..972d98d753b 100644--- a/src/plugins/intel_npu/src/al/include/intel_npu/npuw_private_properties.hpp+++ b/src/plugins/intel_npu/src/al/include/intel_npu/npuw_private_properties.hpp@@ -448,6 +448,14 @@ static constexpr ov::Property<uint32_t> max_lora_rank{"NPUW_LLM_MAX_LORA_RANK"};*/static constexpr ov::Property<bool> optimize_v_tensors{"NPUW_LLM_OPTIMIZE_V_TENSORS"};+/**+ * @brief+ * Type: boolean+ * Substitute part of the RoPE with compile-time precalculation in higher precision+ * Default value: true.+ */+static constexpr ov::Property<bool> cache_rope{"NPUW_LLM_CACHE_ROPE"};+/*** @brief* Type: uint64_t.diff --git a/src/plugins/intel_npu/src/al/src/config/npuw.cpp b/src/plugins/intel_npu/src/al/src/config/npuw.cppindex 11e266fca25..359aff75225 100644--- a/src/plugins/intel_npu/src/al/src/config/npuw.cpp+++ b/src/plugins/intel_npu/src/al/src/config/npuw.cpp@@ -64,6 +64,7 @@ void intel_npu::registerNPUWLLMOptions(OptionsDesc& desc) {desc.add<NPUW_LLM_MIN_RESPONSE_LEN>();desc.add<NPUW_LLM_MAX_LORA_RANK>();desc.add<NPUW_LLM_OPTIMIZE_V_TENSORS>();+ desc.add<NPUW_LLM_CACHE_ROPE>();desc.add<NPUW_LLM_PREFILL_CHUNK_SIZE>();desc.add<NPUW_LLM_PREFILL_HINT>();desc.add<NPUW_LLM_GENERATE_HINT>();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 8bdef791454..2bf59de09af 100644--- a/src/plugins/intel_npu/src/plugin/npuw/llm_compiled_model.cpp+++ b/src/plugins/intel_npu/src/plugin/npuw/llm_compiled_model.cpp@@ -19,6 +19,7 @@#include "openvino/pass/validate.hpp"#include "openvino/runtime/iasync_infer_request.hpp"#include "openvino/runtime/properties.hpp"+#include "partitioning/patterns/pre_compute.hpp"#include "serialization.hpp"#include "transformations/convert_precision.hpp"#include "util.hpp"@@ -1219,6 +1220,15 @@ ov::npuw::LLMCompiledModel::LLMCompiledModel(const std::shared_ptr<ov::Model>& mLOG_DEBUG("Converting KV-cache in prefill model to FP16.");prefill_model = cvt_kvcache_to_fp16(prefill_model);+ if (m_cfg.get<::intel_npu::NPUW_LLM_CACHE_ROPE>()) {+ LOG_DEBUG("Caching preROPE ");+ ov::npuw::patterns::pre_compute::RopeCache rope_prefill_cacher(max_prompt_len);+ rope_prefill_cacher.run_on_model(prefill_model);++ ov::npuw::patterns::pre_compute::RopeCache rope_generate_cacher(max_prompt_len + min_response_len);+ rope_generate_cacher.run_on_model(kvcache_model);+ }+auto prefill_config =prefill_config_opt.value_or(get_default_prefill_config(prefill_model, npudesc)).as<ov::AnyMap>();diff --git a/src/plugins/intel_npu/src/plugin/npuw/partitioning/online/snapshot.cpp b/src/plugins/intel_npu/src/plugin/npuw/partitioning/online/snapshot.cppindex 23281ce6698..521b5ee578e 100644--- a/src/plugins/intel_npu/src/plugin/npuw/partitioning/online/snapshot.cpp+++ b/src/plugins/intel_npu/src/plugin/npuw/partitioning/online/snapshot.cpp@@ -88,7 +88,6 @@ void Snapshot::buildGraph() {if (!isOp(ov_node)) {continue;}-m_node_to_prod_cons->insert({ov_node, {}});auto nh = m_graph->create();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.cppnew file mode 100644index 00000000000..224b21d8ec6--- /dev/null+++ b/src/plugins/intel_npu/src/plugin/npuw/partitioning/patterns/pre_compute.cpp@@ -0,0 +1,163 @@+// Copyright (C) 2024 Intel Corporation+// SPDX-License-Identifier: Apache-2.0+//++#include "pre_compute.hpp"++#include "../../logging.hpp"+#include "openvino/op/ops.hpp"+#include "openvino/pass/manager.hpp"+#include "openvino/pass/pattern/op/optional.hpp"+#include "openvino/pass/pattern/op/wrap_type.hpp"+#include "ov_ops/rotary_positional_embeddings.hpp"+#include "transformations/common_optimizations/fuse_rotary_positional_embeddings.hpp"++namespace opp = ov::pass::pattern;++namespace {+template <typename T>+std::shared_ptr<ov::Node> makeConst(const ov::element::Type& type,+ const ov::Shape& shape,+ const std::vector<T>& values) {+ return std::make_shared<ov::op::v0::Constant>(type, shape, values);+}+// TODO: copied from common tests+static ov::OutputVector makeCosSinCache(const size_t max_position_embeddings,+ const std::shared_ptr<ov::Node> inverse_frequencies) {+ const auto inverse_freq_fp32 = ov::as_type_ptr<ov::op::v0::Constant>(inverse_frequencies)->cast_vector<float>();+ const size_t rotary_ndims = ov::shape_size(inverse_frequencies->get_shape()) * 2;++ 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);++ // rotate_half style cos/sin table:+ // y1 = cos(m*xita_i) * x1 - sin(m*xita_i) * x2+ // y2 = cos(m*xita_i) * x2 + sin(m*xita_i) * x1+ //+ for (size_t i = 0, k = 0; i < rotary_ndims; i += 2, k++) {+ auto xita_i = inverse_freq_fp32[i >> 1];+ 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) {+ auto vsin = std::sin(xita_i * m);+ auto vcos = std::cos(xita_i * m);+ pcos[k] = ov::float16{vcos};+ pcos[k + rotary_ndims / 2] = pcos[k];++ psin[k] = ov::float16{vsin};+ psin[k + rotary_ndims / 2] = psin[k];+ }+ }+ auto Cos = makeConst(ov::element::f16, ov::Shape({1, max_position_embeddings, rotary_ndims}), lut_cos);+ auto Sin = makeConst(ov::element::f16, ov::Shape({1, max_position_embeddings, rotary_ndims}), lut_sin);++ return {Cos, Sin};+}+} // namespace++ov::npuw::patterns::pre_compute::RopePatternLLama2::RopePatternLLama2() : matcher("sin-cos-matcher") {+ 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()});+ auto concat_1 = opp::wrap_type<ov::op::v0::Concat>({gather, opp::any_input(), opp::any_input()});+ // here we can seen inverse frequencies as a parameter or constant depending on partitioner passes+ auto inv_freq = opp::wrap_type<ov::op::v0::Constant>();+ auto inv_freq_convert = opp::optional<ov::op::v0::Convert>({inv_freq->output(0)});+ auto broadcast = opp::wrap_type<ov::op::v3::Broadcast>({inv_freq_convert, concat_1});+ auto position_ids = opp::wrap_type<ov::op::v0::Parameter>();+ auto unsqueeze = opp::wrap_type<ov::op::v0::Unsqueeze>({position_ids, opp::wrap_type<ov::op::v0::Constant>()});+ auto convert = opp::wrap_type<ov::op::v0::Convert>({unsqueeze});+ auto matmul = opp::wrap_type<ov::op::v0::MatMul>({broadcast, convert});+ auto transpose = opp::wrap_type<ov::op::v1::Transpose>({matmul, opp::any_input()});+ auto concat_2 = opp::wrap_type<ov::op::v0::Concat>({transpose, opp::any_input()});+ auto output_sin = opp::wrap_type<ov::op::v0::Sin>({concat_2});+ auto output_cos = opp::wrap_type<ov::op::v0::Cos>({concat_2});++ init_cb = [=](const auto& matches) {+ const auto& map_sin = matches.at(output_sin)[0];+ const auto& map_cos = matches.at(output_cos)[0];++ this->matched_position_ids = map_sin.at(position_ids).get_node_shared_ptr();+ this->matched_concat = map_sin.at(concat_1).get_node_shared_ptr();+ this->matched_inv_freq = map_sin.at(inv_freq).get_node_shared_ptr();++ this->matched_cos = map_cos.at(output_cos).get_node_shared_ptr();+ this->matched_sin = map_sin.at(output_sin).get_node_shared_ptr();++ LOG_VERB("Rope found : sin=" << matched_sin->get_name() << ", cos=" << matched_cos->get_name());++ return true;+ };++ matcher.register_patterns({output_sin, output_cos}, make_matcher_callback());+}++ov::npuw::patterns::pre_compute::RopeCacheMatcher::RopeCacheMatcher(const uint32_t max_prompt_len,+ const std::shared_ptr<ov::Model>& model) {+ auto rpe = std::make_shared<RopePatternLLama2>();++ rpe->transform_cb = [&]() {+ auto inv_freq_size = ov::shape_size(rpe->matched_inv_freq->get_shape());++ LOG_VERB("Making sin-cos cache of size: " << max_prompt_len << "x" << inv_freq_size);++ // shapes that matches max possible position+ auto cache = makeCosSinCache(max_prompt_len, rpe->matched_inv_freq);++ // Step 1: Define axis (gather along axis 1)+ auto axis = ov::op::v0::Constant::create(ov::element::i64, ov::Shape{1}, {1});++ // Step 2: Apply Gather for cos and sin+ auto gather_cos = std::make_shared<ov::op::v8::Gather>(cache[0], rpe->matched_position_ids, axis);+ auto gather_sin = std::make_shared<ov::op::v8::Gather>(cache[1], rpe->matched_position_ids, axis);+ LOG_VERB("Created gather op facilitate LUT search: " << gather_cos->get_name() << ", "+ << gather_cos->get_shape());++ // Step 2: convert fp16->fp32+ auto cos_fp32 = std::make_shared<ov::op::v0::Convert>(gather_cos, ov::element::f32);+ auto sin_fp32 = std::make_shared<ov::op::v0::Convert>(gather_sin, ov::element::f32);++ // Create the squeeze operation required after gather+ auto squeeze_cos = std::make_shared<ov::op::v0::Squeeze>(cos_fp32, axis);+ auto squeeze_sin = std::make_shared<ov::op::v0::Squeeze>(sin_fp32, axis);++ LOG_VERB("Created squeeze_cos op to reduce axis=1: " << squeeze_cos->get_name() << ", "+ << squeeze_cos->get_shape());+ LOG_VERB("Created squeeze_sin op to reduce axis=1: " << squeeze_sin->get_name() << ", "+ << squeeze_sin->get_shape());++ LOG_VERB("Rope cos detected at: " << rpe->matched_cos->get_name() << ", replacing by cache node: "+ << gather_cos->get_name() << ", " << gather_cos->get_shape());+ LOG_VERB("Rope sin detected at: " << rpe->matched_sin->get_name() << ", replacing by cache node: "+ << gather_sin->get_name() << ", " << gather_sin->get_shape());++ // replacing sin with gather op+ ov::replace_node(rpe->matched_cos, squeeze_cos);+ ov::replace_node(rpe->matched_sin, squeeze_sin);++ // disconnecting gather from rest or subgraph started from concat_1+ auto gather_input_to_concat = rpe->matched_concat->input(0);+ gather_input_to_concat.get_source_output().remove_target_input(gather_input_to_concat);+ };+ rpe->run_on_model(model);+}++ov::npuw::patterns::pre_compute::RopeInverseFreq::RopeInverseFreq(+ ov::npuw::patterns::pre_compute::RopeInverseFreq::Results need_freq_consts,+ const std::shared_ptr<ov::Model>& model) {+ auto rpe = std::make_shared<ov::npuw::patterns::pre_compute::RopePatternLLama2>();++ rpe->transform_cb = [&]() {+ if (auto inverse_freq_constant = ov::as_type_ptr<ov::op::v0::Constant>(rpe->matched_inv_freq)) {+ LOG_VERB("Inverse Frequences Constant found: " << inverse_freq_constant->get_name());+ need_freq_consts.get().push_back(inverse_freq_constant);+ return true;+ }+ return false; // root hasnt changed+ };+ rpe->run_on_model(model);+}++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);+ return true;+}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.hppnew file mode 100644index 00000000000..23882181f81--- /dev/null+++ b/src/plugins/intel_npu/src/plugin/npuw/partitioning/patterns/pre_compute.hpp@@ -0,0 +1,69 @@+// Copyright (C) 2025 Intel Corporation+// SPDX-License-Identifier: Apache-2.0+//++#pragma once++#include "openvino/pass/pattern/multi_matcher.hpp"+namespace ov ::npuw ::patterns ::pre_compute {++class RopePatternDesc {+protected:+ ov::pass::MultiMatcher::Callback init_cb;++public:+ std::shared_ptr<ov::Node> matched_inv_freq;+ std::shared_ptr<ov::Node> matched_position_ids;+ std::shared_ptr<ov::Node> matched_sin;+ std::shared_ptr<ov::Node> matched_cos;+ std::shared_ptr<ov::Node> matched_concat;++ std::function<void()> transform_cb;++ ov::pass::MultiMatcher::Callback make_matcher_callback() {+ return [this](const auto& matches) {+ init_cb(matches);+ transform_cb();+ };+ }+};++class RopePatternLLama2 : public RopePatternDesc {+ ov::pass::MultiMatcher matcher;++public:+ using RopePatternDesc::transform_cb;+ RopePatternLLama2();+ bool run_on_model(const std::shared_ptr<ov::Model>& m) {+ return matcher.run_on_model(m);+ }+};++class RopeCacheMatcher {+public:+ RopeCacheMatcher(const uint32_t max_prompt_len, const std::shared_ptr<ov::Model>& m);+};++// TODO: not used - only in tests+// matches inverse freq tensor+class RopeInverseFreq {+public:+ using CPtr = std::shared_ptr<ov::op::v0::Constant>;+ using Results = std::reference_wrapper<std::vector<CPtr>>;++ RopeInverseFreq(Results need_freq_consts, const std::shared_ptr<ov::Model>& m);+};++class RopeCache : public ov::pass::ModelPass {+ const uint32_t m_max_prompt_len = 0;++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) : m_max_prompt_len(max_prompt_len) {}+ bool run_on_model(const std::shared_ptr<ov::Model>& m) override;+};+// NOLINTNEXTLINE(readability/namespace)+} // namespace ov::npuw::patterns::pre_computediff --git a/src/plugins/intel_npu/src/plugin/src/plugin.cpp b/src/plugins/intel_npu/src/plugin/src/plugin.cppindex 94c6299388a..7313e309025 100644--- a/src/plugins/intel_npu/src/plugin/src/plugin.cpp+++ b/src/plugins/intel_npu/src/plugin/src/plugin.cpp@@ -331,6 +331,7 @@ void Plugin::init_options() {REGISTER_OPTION(NPUW_LLM_MAX_PROMPT_LEN);REGISTER_OPTION(NPUW_LLM_MIN_RESPONSE_LEN);REGISTER_OPTION(NPUW_LLM_OPTIMIZE_V_TENSORS);+ REGISTER_OPTION(NPUW_LLM_CACHE_ROPE);REGISTER_OPTION(NPUW_LLM_PREFILL_HINT);REGISTER_OPTION(NPUW_LLM_PREFILL_CONFIG);REGISTER_OPTION(NPUW_LLM_GENERATE_HINT);diff --git a/src/plugins/intel_npu/src/plugin/src/properties.cpp b/src/plugins/intel_npu/src/plugin/src/properties.cppindex 72c588ef0c2..507048ac090 100644--- a/src/plugins/intel_npu/src/plugin/src/properties.cpp+++ b/src/plugins/intel_npu/src/plugin/src/properties.cpp@@ -452,6 +452,7 @@ void Properties::registerPluginProperties() {TRY_REGISTER_SIMPLE_PROPERTY(ov::intel_npu::npuw::llm::prefill_config, NPUW_LLM_PREFILL_CONFIG);TRY_REGISTER_SIMPLE_PROPERTY(ov::intel_npu::npuw::llm::generate_hint, NPUW_LLM_GENERATE_HINT);TRY_REGISTER_SIMPLE_PROPERTY(ov::intel_npu::npuw::llm::generate_config, NPUW_LLM_GENERATE_CONFIG);+ TRY_REGISTER_SIMPLE_PROPERTY(ov::intel_npu::npuw::llm::cache_rope, NPUW_LLM_CACHE_ROPE);// 2. Metrics (static device and enviroment properties)// ========diff --git a/src/plugins/intel_npu/tests/unit/npuw/transpose_vt.cpp b/src/plugins/intel_npu/tests/unit/npuw/transpose_vt.cppindex 86af0520e94..5dc2000a05b 100644--- a/src/plugins/intel_npu/tests/unit/npuw/transpose_vt.cpp+++ b/src/plugins/intel_npu/tests/unit/npuw/transpose_vt.cpp@@ -66,9 +66,12 @@ public:std::string xml_path = test_case_name + ".xml";std::string bin_path = test_case_name + ".bin";++#ifdef ANALYZE_TEST// Save the modelov::pass::Serialize serialize_pass(xml_path, bin_path);serialize_pass.run_on_model(model);+#endif// validation of High Precision attention mask - implies enabling SDPA layer to be unrolled,