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
vtensors transpose for llama3 (#28338)
Eugene Smirnovf499bb005591
diff --git a/src/core/src/pattern/matcher.cpp b/src/core/src/pattern/matcher.cppindex 3681b933ceb..c6962366d0a 100644--- a/src/core/src/pattern/matcher.cpp+++ b/src/core/src/pattern/matcher.cpp@@ -139,7 +139,7 @@ bool Matcher::match_permutation(const OutputVector& pattern_args, const OutputVei," (",args.at(i).get_node()->get_friendly_name(),- ") mismatch");+ ") mismatch for pattern: ", pattern_args.at(i));return false;}}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 51b6b8ca9fe..c5c2e1b5886 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@@ -72,7 +72,7 @@ DEFINE_OPT(NPUW_LLM_BATCH_DIM, uint32_t, 0, npuw::llm::batch_dim, CompileTime);DEFINE_OPT(NPUW_LLM_SEQ_LEN_DIM, uint32_t, 2, npuw::llm::seq_len_dim, CompileTime);DEFINE_OPT(NPUW_LLM_MAX_PROMPT_LEN, uint32_t, 1024, npuw::llm::max_prompt_len, CompileTime);DEFINE_OPT(NPUW_LLM_MIN_RESPONSE_LEN, uint32_t, 128, npuw::llm::min_response_len, CompileTime);-DEFINE_OPT(NPUW_LLM_OPTIMIZE_V_TENSORS, bool, false, npuw::llm::optimize_v_tensors, CompileTime);+DEFINE_OPT(NPUW_LLM_OPTIMIZE_V_TENSORS, bool, true, npuw::llm::optimize_v_tensors, CompileTime);namespace npuw {namespace llm {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 4f0687757b6..c028c4d7eb2 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@@ -18,6 +18,7 @@#include "transformations/convert_precision.hpp"namespace opp = ov::pass::pattern;+class TransposeValueTensors : public ov::pass::MatcherPass {public:struct Context {@@ -26,8 +27,57 @@ public:using Ref = std::reference_wrapper<Context>;};- OPENVINO_MATCHER_PASS_RTTI("npuw::LLMCompiledModel::TransposeValueTensors");- TransposeValueTensors(Context::Ref ctx) {+protected:+ // generic part of matchers, to transpose v-tensors, and concat, and update matmul args+ void transpose_matmul_b(Context::Ref ctx,+ std::shared_ptr<ov::Node> node_param,+ std::shared_ptr<ov::Node> node_concat,+ std::shared_ptr<ov::Node> node_transpose,+ std::shared_ptr<ov::Node> node_matmul) {+ auto matched_param = std::static_pointer_cast<ov::op::v0::Parameter>(node_param);+ auto matched_concat = std::static_pointer_cast<ov::op::v0::Concat>(node_concat);+ auto matched_transpose = std::static_pointer_cast<ov::op::v1::Transpose>(node_transpose);+ auto matched_matmul = std::static_pointer_cast<ov::op::v0::MatMul>(node_matmul);++ auto param_shape = matched_param->get_partial_shape();+ OPENVINO_ASSERT(param_shape.size() == 4u);+ // NB: Transpose Parameter that correspond to V-tensor it will+ // speed-up its multiplication with attention scores+ std::swap(param_shape[2], param_shape[3]);+ auto new_param = std::make_shared<ov::opset13::Parameter>(matched_param->get_element_type(), param_shape);+ new_param->set_friendly_name(matched_param->get_friendly_name());+ new_param->outputs().begin()->get_tensor().set_names(+ matched_param->outputs().begin()->get_tensor().get_names());+ ov::replace_node(matched_param, new_param);+ // NB: Save in order to add/remove to the model later on+ ctx.get().new_params.push_back(new_param);+ ctx.get().old_params.push_back(matched_param);++ auto order_cst = ov::op::v0::Constant::create(ov::element::i32, ov::Shape{4}, {0, 2, 3, 1});+ auto new_transpose =+ std::make_shared<ov::opset13::Transpose>(matched_transpose->input_value(0), order_cst->output(0));+ new_transpose->set_friendly_name(matched_transpose->get_friendly_name());+ ov::replace_node(matched_transpose, new_transpose);++ auto new_concat =+ std::make_shared<ov::opset13::Concat>(ov::OutputVector{new_param->output(0), new_transpose->output(0)}, 3u);+ new_concat->set_friendly_name(matched_concat->get_friendly_name());+ ov::replace_node(matched_concat, new_concat);++ matched_matmul->set_transpose_b(true);+ }+};++// llama2 pattern for value tensor concate+class TransposeValueTensors_llama2 : public TransposeValueTensors {+public:+ OPENVINO_MATCHER_PASS_RTTI("npuw::LLMCompiledModel::TransposeValueTensors_llama2");+ TransposeValueTensors_llama2(Context::Ref ctx) {+ register_matcher_llama2(ctx);+ }++private:+ void register_matcher_llama2(Context::Ref ctx) {auto param = opp::wrap_type<ov::op::v0::Parameter>();auto transpose = opp::wrap_type<ov::op::v1::Transpose>({opp::any_input(), opp::any_input()});auto concat = opp::wrap_type<ov::op::v0::Concat>({param, transpose});@@ -42,42 +92,87 @@ public:auto matched_node_transpose = node_to_output.at(transpose).get_node_shared_ptr();auto matched_node_matmul = node_to_output.at(matmul).get_node_shared_ptr();+ transpose_matmul_b(ctx, matched_node_param, matched_node_concat, matched_node_transpose, matched_node_matmul);+ LOG_DEBUG("vtensors transposed: LLama2 pattern");+ return true;+ };+ register_matcher(std::make_shared<opp::Matcher>(matmul, "TransposeValueTensors_llama2"), std::move(callback));+ }+};++// llama3, phi3, mistral, etc, concate value tensors with broadcasting+class TransposeValueTensors_llama3 : public TransposeValueTensors {+public:+ OPENVINO_MATCHER_PASS_RTTI("npuw::LLMCompiledModel::TransposeValueTensors_llama3");+ TransposeValueTensors_llama3(Context::Ref ctx) {+ register_matcher_llama3(ctx);+ }++private:+ void register_matcher_llama3(Context::Ref ctx) {+ auto param = opp::wrap_type<ov::op::v0::Parameter>();+ auto transpose = opp::wrap_type<ov::op::v1::Transpose>({opp::any_input(), opp::any_input()});+ auto concat = opp::wrap_type<ov::op::v0::Concat>({param, transpose});++ // only difference is that broadcast wrapped into unsquese/reshape, while transposed tensor didn't change+ const auto unsqueeze_axes = opp::wrap_type<ov::op::v0::Constant>();+ auto unsqueeze = opp::wrap_type<ov::op::v0::Unsqueeze>({concat, unsqueeze_axes});+ auto broadcast = opp::wrap_type<ov::op::v1::Broadcast, ov::op::v3::Broadcast>({unsqueeze, opp::any_input()});+ auto reshape = opp::wrap_type<ov::op::v1::Reshape>({broadcast, opp::any_input()});++ auto softmax = opp::wrap_type<ov::op::v8::Softmax>({opp::any_input()});+ auto matmul = opp::wrap_type<ov::op::v0::MatMul>({softmax, reshape});++ auto callback = [=](ov::pass::pattern::Matcher& m) {+ auto& node_to_output = m.get_pattern_value_map();++ auto matched_node_param = node_to_output.at(param).get_node_shared_ptr();+ auto matched_node_concat = node_to_output.at(concat).get_node_shared_ptr();+ auto matched_node_transpose = node_to_output.at(transpose).get_node_shared_ptr();+ auto matched_node_matmul = node_to_output.at(matmul).get_node_shared_ptr();+ auto matched_node_unsqueeze = node_to_output.at(unsqueeze).get_node_shared_ptr();+ auto matched_node_unsqueeze_axes = node_to_output.at(unsqueeze_axes).get_node_shared_ptr();+ auto matched_node_broadcast = node_to_output.at(broadcast).get_node_shared_ptr();+ auto matched_node_reshape = node_to_output.at(reshape).get_node_shared_ptr();+auto matched_param = std::static_pointer_cast<ov::op::v0::Parameter>(matched_node_param);auto matched_concat = std::static_pointer_cast<ov::op::v0::Concat>(matched_node_concat);auto matched_transpose = std::static_pointer_cast<ov::op::v1::Transpose>(matched_node_transpose);auto matched_matmul = std::static_pointer_cast<ov::op::v0::MatMul>(matched_node_matmul);- auto shape = matched_param->get_partial_shape();- OPENVINO_ASSERT(shape.size() == 4u);- // NB: Transpose Parameter that correspond to V-tensor it will- // speed-up its multiplication with attention scores- std::swap(shape[2], shape[3]);- auto new_param = std::make_shared<ov::opset13::Parameter>(matched_param->get_element_type(), shape);- new_param->set_friendly_name(matched_param->get_friendly_name());- new_param->outputs().begin()->get_tensor().set_names(- matched_param->outputs().begin()->get_tensor().get_names());- ov::replace_node(matched_param, new_param);- // NB: Save in order to add/remove to the model later on- ctx.get().new_params.push_back(new_param);- ctx.get().old_params.push_back(matched_param);-- auto order_cst = ov::op::v0::Constant::create(ov::element::i32, ov::Shape{4}, {0, 2, 3, 1});- auto new_transpose =- std::make_shared<ov::opset13::Transpose>(matched_transpose->input_value(0), order_cst->output(0));- new_transpose->set_friendly_name(matched_transpose->get_friendly_name());- ov::replace_node(matched_transpose, new_transpose);-- auto new_concat =- std::make_shared<ov::opset13::Concat>(ov::OutputVector{new_param->output(0), new_transpose->output(0)},- 3u);- new_concat->set_friendly_name(matched_concat->get_friendly_name());- ov::replace_node(matched_concat, new_concat);-- matched_matmul->set_transpose_b(true);+ auto matched_unsqueeze = std::static_pointer_cast<ov::op::v0::Unsqueeze>(matched_node_unsqueeze);+ auto matched_broadcast = std::static_pointer_cast<ov::op::v3::Broadcast>(matched_node_broadcast);+ auto matched_reshape = std::static_pointer_cast<ov::op::v1::Reshape>(matched_node_reshape);+ auto shape_broadcast = matched_broadcast->get_output_shape(0);+ OPENVINO_ASSERT(shape_broadcast.size() == 5u);+ std::swap(shape_broadcast[3], shape_broadcast[4]);++ LOG_DEBUG("shape_broadcast for: "<< matched_broadcast->get_friendly_name() <<", shape=" << shape_broadcast);++ const auto broadcast_axes_node = std::make_shared<ov::op::v0::Constant>(ov::element::i32, ov::Shape{5}, shape_broadcast);+ broadcast_axes_node->set_friendly_name(matched_broadcast->get_friendly_name() + "/new_broadcast_shape");+ matched_broadcast->input(1).replace_source_output(broadcast_axes_node);++ auto shape_reshape = matched_reshape->get_output_shape(0);+ OPENVINO_ASSERT(shape_reshape.size() == 4u);+ std::swap(shape_reshape[2], shape_reshape[3]);++ LOG_DEBUG("shape_reshape for: "<< matched_reshape->get_friendly_name() <<", shape=" << shape_reshape);++ const auto reshape_axes_node = std::make_shared<ov::op::v0::Constant>(ov::element::i32, ov::Shape{4}, shape_reshape);+ reshape_axes_node->set_friendly_name(matched_reshape->get_friendly_name() + "/new_reshape_shape");+ matched_reshape->input(1).replace_source_output(reshape_axes_node);++ transpose_matmul_b(ctx,+ matched_node_param,+ matched_node_concat,+ matched_node_transpose,+ matched_node_matmul);+ LOG_DEBUG("vtensors transposed: LLama3 pattern");return true;};- register_matcher(std::make_shared<opp::Matcher>(matmul, "TransposeValueTensors"), std::move(callback));+ register_matcher(std::make_shared<opp::Matcher>(matmul, "TransposeValueTensors_llama3"), std::move(callback));}};@@ -239,7 +334,8 @@ bool optimize_value_tensors(std::shared_ptr<ov::Model> model) {ov::pass::GraphRewrite rewr;rewr.add_matcher<ScaledDotProductAttentionDecomposition>();TransposeValueTensors::Context ctx;- rewr.add_matcher<TransposeValueTensors>(std::ref(ctx));+ rewr.add_matcher<TransposeValueTensors_llama2>(std::ref(ctx));+ rewr.add_matcher<TransposeValueTensors_llama3>(std::ref(ctx));rewr.run_on_model(model);model->add_parameters(ctx.new_params);@@ -440,8 +536,8 @@ ov::npuw::LLMCompiledModel::LLMCompiledModel(const std::shared_ptr<ov::Model>& m::intel_npu::registerNPUWLLMOptions(*m_options_desc);- std::map<std::string, ov::Any> npuw_llm_props;- std::map<std::string, ov::Any> other_props;+ ov::AnyMap npuw_llm_props;+ ov::AnyMap other_props;split_llm_properties(properties, npuw_llm_props, other_props);// Remove "NPUW_LLM_PREFILL_CONFIG", "NPUW_LLM_GENERATE_CONFIG" from map,@@ -475,16 +571,19 @@ ov::npuw::LLMCompiledModel::LLMCompiledModel(const std::shared_ptr<ov::Model>& mreshape_to_static(prefill_model, m_kvcache_desc.max_prompt_size, m_kvcache_desc.max_prompt_size, axes);LOG_DEBUG("5. Make kvcache model with static shapes");reshape_to_static(kvcache_model, 1u, m_kvcache_desc.total_size, axes);- LOG_DEBUG("6.Check and apply opt layout if applicable.");const bool optimize_v_tensors = m_cfg.get<::intel_npu::NPUW_LLM_OPTIMIZE_V_TENSORS>();- // NB: Try to apply opt transpose only for Llama-2-7b-chat-hf modelif (optimize_v_tensors) {+ LOG_DEBUG("6. Check and apply opt layout");+ LOG_BLOCK();if (optimize_value_tensors(kvcache_model)) {- // NB: Check if TransposeValueTensors transformation was appliedm_kvcache_desc.v_tensors_transposed = true;prefill_model = cvt_value_tensors_layout(prefill_model);+ } else {+ LOG_DEBUG("vtensors optimisation not applied");}+ } else {+ LOG_DEBUG("6. Check and apply opt layout --- SKIPPED");}LOG_DEBUG("7. Optimize kvcache model to output key/values for new token.");kvcache_model = redirect_new_kv_to_output(kvcache_model);@@ -528,7 +627,6 @@ ov::npuw::LLMCompiledModel::LLMCompiledModel(const std::shared_ptr<ov::Model>& m"model and its config, please check passed config.");implement_properties();-LOG_DEBUG("Done");}diff --git a/src/plugins/intel_npu/src/plugin/npuw/partitioning/partitioning.cpp b/src/plugins/intel_npu/src/plugin/npuw/partitioning/partitioning.cppindex 73ea8f6b601..4abda6b3fa0 100644--- a/src/plugins/intel_npu/src/plugin/npuw/partitioning/partitioning.cpp+++ b/src/plugins/intel_npu/src/plugin/npuw/partitioning/partitioning.cpp@@ -1188,10 +1188,10 @@ void Partitioner::saveTinyConstants(const std::string& func_name) {auto total =std::accumulate(shape.begin(), shape.end(), std::size_t{1}, std::multiplies<std::size_t>());if ((shape.size() == 0 || (shape.size() == 1 && shape[0] <= 10)) || (total <= 10)) {- LOG_DEBUG("[KEEP] It is safe to keep this bank in function");+ LOG_DEBUG("[KEEP] " << node->get_friendly_name() << "/" << shape << ": It is safe to keep this bank in function");func_group.consts_to_keep.insert(std::static_pointer_cast<CT>(node));} else {- LOG_DEBUG("[CUT ] This group of Const ops will be cut-off from the function");+ LOG_DEBUG("[CUT ] " << node->get_friendly_name() << "/" << shape << ": This const op will be cut-off from the function");}}}@@ -1278,7 +1278,7 @@ void Partitioner::saveRepeatedConstants(const std::string& func_name) {}} // for(models)- // Now walk through through every Const bank and inspect the above properties+ // Now walk through every Const bank and inspect the above propertiesauto values_are_the_same = [](const CTPtr& node_a, const CTPtr& node_b) {switch (node_a->output(0).get_element_type()) {#define HANDLE_CASE(t, T) \@@ -1326,7 +1326,7 @@ void Partitioner::saveRepeatedConstants(const std::string& func_name) {func_group.consts_to_keep.insert(const_node);}} else {- LOG_DEBUG("[CUT ] This group of Const ops will be cut-off from the function");+ LOG_DEBUG("[CUT ] This group of Const ops will be cut-off from the function: " << proto_node->get_friendly_name());}};for (auto&& bank : rep_block.consts) {diff --git a/src/plugins/intel_npu/src/plugin/src/metrics.cpp b/src/plugins/intel_npu/src/plugin/src/metrics.cppindex 58bbd61e022..5361540e775 100644--- a/src/plugins/intel_npu/src/plugin/src/metrics.cpp+++ b/src/plugins/intel_npu/src/plugin/src/metrics.cpp@@ -171,13 +171,12 @@ uint64_t Metrics::GetDeviceTotalMemSize(const std::string& specifiedDeviceName)}std::string Metrics::getDeviceName(const std::string& specifiedDeviceName) const {- std::vector<std::string> devNames;- if (_backends == nullptr || (devNames = _backends->getAvailableDevicesNames()).empty()) {- OPENVINO_THROW("No available devices");- }-// In case of single device and empty input from user we should use the first element from the device listif (specifiedDeviceName.empty()) {+ std::vector<std::string> devNames;+ if (_backends == nullptr || (devNames = _backends->getAvailableDevicesNames()).empty()) {+ OPENVINO_THROW("No available devices");+ }if (devNames.size() == 1) {return devNames[0];} else {