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 ] shared vocab detection (#38233)
Eugene Smirnovef8403deb507
diff --git a/src/plugins/intel_npu/src/al/include/intel_npu/config/npuw_option_defs.inc b/src/plugins/intel_npu/src/al/include/intel_npu/config/npuw_option_defs.incindex fc561228c22..0efe3de5696 100644--- a/src/plugins/intel_npu/src/al/include/intel_npu/config/npuw_option_defs.inc+++ b/src/plugins/intel_npu/src/al/include/intel_npu/config/npuw_option_defs.inc@@ -91,7 +91,7 @@ INTEL_NPU_NPUW_ANYMAP_OPT(NPUW_LLM_ADDITIONAL_PREFILL_CONFIG, ov::intel_npu::npuINTEL_NPU_NPUW_ANYMAP_OPT(NPUW_LLM_GENERATE_CONFIG, ov::intel_npu::npuw::llm, generate_config, "NPUW_LLM_GENERATE_CONFIG", LLM, EXPOSED, CACHED, ALL)INTEL_NPU_NPUW_ANYMAP_OPT(NPUW_LLM_ADDITIONAL_GENERATE_CONFIG, ov::intel_npu::npuw::llm, additional_generate_config, "++NPUW_LLM_GENERATE_CONFIG", LLM, EXPOSED, CACHED, ALL)INTEL_NPU_NPUW_ANYMAP_OPT(NPUW_LLM_SHARED_LM_HEAD_CONFIG, ov::intel_npu::npuw::llm, shared_lm_head_config, "NPUW_LLM_SHARED_HEAD_CONFIG", LLM, EXPOSED, CACHED, ALL)-INTEL_NPU_NPUW_SIMPLE_OPT(NPUW_LLM_VOCAB_ASYM_SHARED, bool, false, ov::intel_npu::npuw::llm, vocab_asym_shared, "NPUW_LLM_VOCAB_ASYM_SHARED", LLM, EXPOSED, CACHED, ALL)+INTEL_NPU_NPUW_SIMPLE_OPT(NPUW_LLM_VOCAB_ASYM_SHARED, bool, true, ov::intel_npu::npuw::llm, vocab_asym_shared, "NPUW_LLM_VOCAB_ASYM_SHARED", LLM, EXPOSED, CACHED, ALL)INTEL_NPU_NPUW_ANYMAP_OPT(NPUW_LLM_ADDITIONAL_SHARED_LM_HEAD_CONFIG, ov::intel_npu::npuw::llm, additional_shared_lm_head_config, "++NPUW_LLM_SHARED_HEAD_CONFIG", LLM, EXPOSED, CACHED, ALL)INTEL_NPU_NPUW_SIMPLE_OPT(NPUW_WHISPER, bool, false, ov::intel_npu::npuw::whisper, enabled, "NPUW_WHISPER", LLM, EXPOSED, CACHED, ALL)INTEL_NPU_NPUW_SIMPLE_OPT(NPUW_WHISPER_EOS_TOKEN, uint64_t, 50257, ov::intel_npu::npuw::whisper, whisper_eos_token, "NPUW_WHISPER_EOS_TOKEN", LLM, EXPOSED, UNCACHED, ALL)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 59142406570..a0c71330585 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@@ -974,9 +974,15 @@ ov::npuw::LLMCompiledModel::LLMCompiledModel(const std::shared_ptr<ov::Model>& mauto kvcache_model = model->clone();if (m_cfg.get<::intel_npu::NPUW_LLM_VOCAB_ASYM_SHARED>()) {- ov::npuw::InsertVocabSub128 pass;- if (!pass.run_on_model(kvcache_model)) {- LOG_INFO("No asymmetric u8 vocab found - graph Sub128 insertion is skipped.");+ bool shared_vocab = false;+ ov::npuw::DetectVocabSharing detect_vocab_sharing(shared_vocab);+ detect_vocab_sharing.run_on_model(kvcache_model);+ if (shared_vocab) {+ ov::npuw::InsertVocabSub128 pass;+ if (!pass.run_on_model(kvcache_model)) {+ // Sharing was detected, but the shared vocabulary is not u8 asymmetric (e.g. f16 or i4).+ LOG_INFO("Shared vocabulary is not asymmetric u8 - graph Sub128 insertion is skipped.");+ }}}diff --git a/src/plugins/intel_npu/src/plugin/npuw/npuw_transformations/cut_lm_head.cpp b/src/plugins/intel_npu/src/plugin/npuw/npuw_transformations/cut_lm_head.cppindex 555b774cc6d..9535d136238 100644--- a/src/plugins/intel_npu/src/plugin/npuw/npuw_transformations/cut_lm_head.cpp+++ b/src/plugins/intel_npu/src/plugin/npuw/npuw_transformations/cut_lm_head.cpp@@ -39,28 +39,8 @@ public:explicit CutLMHeadMatcher(std::shared_ptr<ov::Model>& lm_head_model) {// The first input to MatMul is treated as the cut point.auto matmul = opp::wrap_type<ov::op::v0::MatMul>({opp::any_input(), opp::any_input()});-- // Several patterns for matmul are supported:- // Matmul -> Result- // Matmul -> Add -> Result- auto matmul_add = opp::wrap_type<ov::op::v1::Add>({matmul, opp::any_input()});- // Matmul -> Transpose -> Result- auto matmul_transpose = opp::wrap_type<ov::op::v1::Transpose>({matmul, opp::any_input()});- // Matmul -> Convert -> Result- auto matmul_convert = opp::wrap_type<ov::op::v0::Convert>({matmul});- // MatMul -> Divide -> Tanh -> Multiply -> Result- // MatMul -> Divide -> Result (Granite-4.0-h-micro)- auto matmul_divide = opp::wrap_type<ov::op::v1::Multiply, ov::op::v1::Divide>({matmul, opp::any_input()});- auto tanh = opp::wrap_type<ov::op::v0::Tanh>({matmul_divide});- auto matmul_multiply = opp::wrap_type<ov::op::v1::Multiply>({tanh, opp::any_input()});-- auto last_op = std::make_shared<opp::op::Or>(ov::OutputVector{matmul->output(0),- matmul_add->output(0),- matmul_transpose->output(0),- matmul_convert->output(0),- matmul_multiply->output(0),- matmul_divide->output(0)});- auto res = opp::wrap_type<ov::op::v0::Result>({last_op->output(0)});+ const ov::npuw::patterns::LMHeadTerminal terminal(matmul);+ auto res = opp::wrap_type<ov::op::v0::Result>({terminal.output});auto callback = [=, &lm_head_model](opp::Matcher& m) {auto& node_to_output = m.get_pattern_value_map();@@ -70,15 +50,7 @@ public:auto matched_result =std::static_pointer_cast<ov::op::v0::Result>(node_to_output.at(res).get_node_shared_ptr());- std::shared_ptr<ov::Node> matched_node_last_op = matched_matmul;- // matmul_divide must be checked after matmul_multiply, as divide is a part of the multiply chain too.- for (const auto& p : {matmul_add, matmul_transpose, matmul_convert, matmul_multiply, matmul_divide}) {- const auto it = node_to_output.find(p);- if (it != node_to_output.end()) {- matched_node_last_op = it->second.get_node_shared_ptr();- break;- }- }+ const auto matched_node_last_op = terminal.last_op(node_to_output);// Skip Result nodes that are not logits.// Note: checking that Result's output name is "logits" is a sufficiently@@ -155,6 +127,32 @@ public:namespace ov::npuw {+patterns::LMHeadTerminal::LMHeadTerminal(const std::shared_ptr<ov::Node>& matmul_pattern) : matmul(matmul_pattern) {+ add = opp::wrap_type<ov::op::v1::Add>({matmul, opp::any_input()});+ transpose = opp::wrap_type<ov::op::v1::Transpose>({matmul, opp::any_input()});+ convert = opp::wrap_type<ov::op::v0::Convert>({matmul});+ scale = opp::wrap_type<ov::op::v1::Multiply, ov::op::v1::Divide>({matmul, opp::any_input()});+ const auto tanh = opp::wrap_type<ov::op::v0::Tanh>({scale});+ softcap = opp::wrap_type<ov::op::v1::Multiply>({tanh, opp::any_input()});+ output = std::make_shared<opp::op::Or>(ov::OutputVector{matmul->output(0),+ add->output(0),+ transpose->output(0),+ convert->output(0),+ softcap->output(0),+ scale->output(0)});+}++std::shared_ptr<ov::Node> patterns::LMHeadTerminal::last_op(const ov::pass::pattern::PatternValueMap& values) const {+ // `scale` must be checked after `softcap`: the scale op is also a part of the softcap chain.+ for (const auto& p : {add, transpose, convert, softcap, scale}) {+ const auto it = values.find(p);+ if (it != values.end()) {+ return it->second.get_node_shared_ptr();+ }+ }+ return values.at(matmul).get_node_shared_ptr();+}+CutLMHead::CutLMHead(std::shared_ptr<ov::Model>& lm_head_model) : m_lm_head_model(lm_head_model) {}bool CutLMHead::run_on_model(const std::shared_ptr<ov::Model>& model) {diff --git a/src/plugins/intel_npu/src/plugin/npuw/npuw_transformations/cut_lm_head.hpp b/src/plugins/intel_npu/src/plugin/npuw/npuw_transformations/cut_lm_head.hppindex 288b806ae2c..00ab482bd0c 100644--- a/src/plugins/intel_npu/src/plugin/npuw/npuw_transformations/cut_lm_head.hpp+++ b/src/plugins/intel_npu/src/plugin/npuw/npuw_transformations/cut_lm_head.hpp@@ -7,9 +7,36 @@#include <memory>#include "openvino/pass/pass.hpp"+#include "openvino/pass/pattern/matcher.hpp"namespace ov::npuw {+namespace patterns {++// Ops that may follow the LM-head MatMul before the logits Result:+// MatMul -> Result+// MatMul -> Add | Transpose | Convert -> Result+// MatMul -> Multiply | Divide -> Result (logits scaling, Granite-4.0-h-micro)+// MatMul -> Multiply | Divide -> Tanh -> Multiply -> Result (logits softcapping)+// CutLMHead, InsertVocabSub128 and DetectVocabSharing use this one definition, so that all of+// them accept the same LM heads.+struct LMHeadTerminal {+ explicit LMHeadTerminal(const std::shared_ptr<ov::Node>& matmul);++ // The matched op that feeds the Result: the terminal op, or the MatMul if there is none.+ std::shared_ptr<ov::Node> last_op(const ov::pass::pattern::PatternValueMap& values) const;++ std::shared_ptr<ov::Node> matmul;+ std::shared_ptr<ov::Node> add;+ std::shared_ptr<ov::Node> transpose;+ std::shared_ptr<ov::Node> convert;+ std::shared_ptr<ov::Node> scale; // Multiply | Divide+ std::shared_ptr<ov::Node> softcap; // Multiply after Tanh(scale)+ std::shared_ptr<ov::Node> output; // Or of the MatMul and all terminal ops: the Result input+};++} // namespace patterns+// Splits the LM head (vocabulary MatMul) off the input model and returns// it as a separate one.// The cut point is the first input of the matched MatMul. The matched logitsdiff --git a/src/plugins/intel_npu/src/plugin/npuw/npuw_transformations/insert_vocab_sub128.cpp b/src/plugins/intel_npu/src/plugin/npuw/npuw_transformations/insert_vocab_sub128.cppindex 82a1d57fc03..f1e3397d34a 100644--- a/src/plugins/intel_npu/src/plugin/npuw/npuw_transformations/insert_vocab_sub128.cpp+++ b/src/plugins/intel_npu/src/plugin/npuw/npuw_transformations/insert_vocab_sub128.cpp@@ -5,18 +5,18 @@#include "insert_vocab_sub128.hpp"#include <memory>+#include <vector>+#include "../logging.hpp"+#include "cut_lm_head.hpp"#include "openvino/core/graph_util.hpp"-#include "openvino/op/add.hpp"#include "openvino/op/constant.hpp"#include "openvino/op/convert.hpp"-#include "openvino/op/divide.hpp"+#include "openvino/op/gather.hpp"#include "openvino/op/matmul.hpp"#include "openvino/op/multiply.hpp"#include "openvino/op/result.hpp"#include "openvino/op/subtract.hpp"-#include "openvino/op/tanh.hpp"-#include "openvino/op/transpose.hpp"#include "openvino/pass/matcher_pass.hpp"#include "openvino/pass/pattern/op/optional.hpp"#include "openvino/pass/pattern/op/or.hpp"@@ -27,6 +27,36 @@ namespace opp = ov::pass::pattern;namespace {+// `subtract` is the dequantization Subtract(Convert(W_u8), Convert(Z_u8)) of the LM head.+void insert_sub128_shifts(const std::shared_ptr<ov::op::v1::Subtract>& subtract) {+ const auto weight_convert = subtract->input_value(0);+ const auto zerop_convert = subtract->input_value(1);+ const auto is_u8_convert = [](const ov::Output<ov::Node>& value) {+ const auto convert = ov::as_type_ptr<ov::op::v0::Convert>(value.get_node_shared_ptr());+ return convert && convert->get_input_element_type(0) == ov::element::u8;+ };+ OPENVINO_ASSERT(is_u8_convert(weight_convert) && is_u8_convert(zerop_convert),+ "InsertVocabSub128: both inputs of '",+ subtract->get_friendly_name(),+ "' must be Convert ops from u8");+ OPENVINO_ASSERT(weight_convert.get_element_type() == zerop_convert.get_element_type(),+ "InsertVocabSub128: weight and zero point of '",+ subtract->get_friendly_name(),+ "' must be converted to one element type");+ const auto compute_type = weight_convert.get_element_type();+ const auto shift = ov::op::v0::Constant::create(compute_type, ov::Shape{}, {128});++ ov::mark_as_decompression(weight_convert.get_node_shared_ptr());+ ov::mark_as_decompression(zerop_convert.get_node_shared_ptr());++ const auto shifted_weight = std::make_shared<ov::op::v1::Subtract>(weight_convert, shift);+ const auto shifted_zerop = std::make_shared<ov::op::v1::Subtract>(zerop_convert, shift);+ shifted_weight->get_rt_info()[ov::npuw::NPUW_SUB128_SHIFT_RT_INFO] = true;+ shifted_zerop->get_rt_info()[ov::npuw::NPUW_SUB128_SHIFT_RT_INFO] = true;+ subtract->input(0).replace_source_output(shifted_weight);+ subtract->input(1).replace_source_output(shifted_zerop);+}+// diagnostics warnings on OPENVINO_MATCHER_PASS_RTTI() definition: visibility hidden#ifdef __GNUC__# pragma GCC diagnostic push@@ -49,28 +79,16 @@ public:const auto hidden = opp::any_input();const auto matmul = opp::wrap_type<ov::op::v0::MatMul>({hidden, qconvert});- // Keep this terminal pattern aligned with CutLMHead: only vocabulary MatMuls- // that form an LM-head result are eligible for Sub128 insertion.- const auto matmul_add = opp::wrap_type<ov::op::v1::Add>({matmul, opp::any_input()});- const auto matmul_transpose = opp::wrap_type<ov::op::v1::Transpose>({matmul, opp::any_input()});- const auto matmul_convert = opp::wrap_type<ov::op::v0::Convert>({matmul});- const auto matmul_divide = opp::wrap_type<ov::op::v1::Multiply, ov::op::v1::Divide>({matmul, opp::any_input()});- const auto tanh = opp::wrap_type<ov::op::v0::Tanh>({matmul_divide});- const auto matmul_multiply = opp::wrap_type<ov::op::v1::Multiply>({tanh, opp::any_input()});- const auto lm_head_output = std::make_shared<opp::op::Or>(ov::OutputVector{matmul->output(0),- matmul_add->output(0),- matmul_transpose->output(0),- matmul_convert->output(0),- matmul_multiply->output(0),- matmul_divide->output(0)});- const auto result = opp::wrap_type<ov::op::v0::Result>({lm_head_output->output(0)});+ // Only vocabulary MatMuls that form an LM-head result are eligible for Sub128 insertion.+ const ov::npuw::patterns::LMHeadTerminal terminal(matmul);+ const auto result = opp::wrap_type<ov::op::v0::Result>({terminal.output});auto callback = [=](opp::Matcher& matcher) {const auto& values = matcher.get_pattern_value_map();const auto weight = values.at(qweight).get_node_shared_ptr();const auto zerop = values.at(qzerop).get_node_shared_ptr();const auto scale = values.at(qcoeff).get_node_shared_ptr();- const auto subtract = values.at(qsub).get_node_shared_ptr();+ const auto subtract = std::static_pointer_cast<ov::op::v1::Subtract>(values.at(qsub).get_node_shared_ptr());const auto matched_matmul =std::static_pointer_cast<ov::op::v0::MatMul>(values.at(matmul).get_node_shared_ptr());const auto matched_result =@@ -80,32 +98,18 @@ public:return false;}+ // Only the [V, H] layout (transpose_b, scale [V, 1]) can share storage with the+ // embedding table, so DetectVocabSharing never opens the gate for another layout.const auto scale_shape = std::static_pointer_cast<ov::op::v0::Constant>(scale)->get_shape();- const bool standard_layout = scale_shape.size() == 2 && scale_shape[1] == 1 &&- !matched_matmul->get_transpose_a() && matched_matmul->get_transpose_b();- const bool pretransposed_layout = scale_shape.size() == 2 && scale_shape[0] == 1 &&- !matched_matmul->get_transpose_a() && !matched_matmul->get_transpose_b();+ const bool vocab_layout = scale_shape.size() == 2 && scale_shape[1] == 1 &&+ !matched_matmul->get_transpose_a() && matched_matmul->get_transpose_b();if (weight->get_element_type() != ov::element::u8 || zerop->get_element_type() != ov::element::u8 ||- weight->get_shape().size() != 2 || (!standard_layout && !pretransposed_layout)) {+ weight->get_shape().size() != 2 || !vocab_layout) {return false;}- const auto weight_convert = subtract->input_value(0);- const auto zerop_convert = subtract->input_value(1);- const auto compute_type = weight_convert.get_element_type();- const auto shift = ov::op::v0::Constant::create(compute_type, ov::Shape{}, {128});- // PPP may not recognize the DQ subgraph after Sub128 insertion. Mark the source- // converts as decompression to prevent PPP constant folding from materializing- // enormous vocabulary tensors during KV-cache precision conversion.- ov::mark_as_decompression(weight_convert.get_node_shared_ptr());- ov::mark_as_decompression(zerop_convert.get_node_shared_ptr());- const auto shifted_weight = std::make_shared<ov::op::v1::Subtract>(weight_convert, shift);- const auto shifted_zerop = std::make_shared<ov::op::v1::Subtract>(zerop_convert, shift);- shifted_weight->get_rt_info()[ov::npuw::NPUW_SUB128_SHIFT_RT_INFO] = true;- shifted_zerop->get_rt_info()[ov::npuw::NPUW_SUB128_SHIFT_RT_INFO] = true;- subtract->input(0).replace_source_output(shifted_weight);- subtract->input(1).replace_source_output(shifted_zerop);+ insert_sub128_shifts(subtract);return true;};@@ -122,3 +126,159 @@ public:ov::npuw::InsertVocabSub128::InsertVocabSub128() {add_matcher<InsertVocabSub128Matcher>();}++namespace {++struct Vocab {+ std::shared_ptr<ov::op::v0::Constant> weight;+ std::shared_ptr<ov::op::v0::Constant> zerop; // nullptr if absent+ std::shared_ptr<ov::op::v0::Constant> scale; // nullptr if absent+};++bool same_storage(const std::shared_ptr<ov::op::v0::Constant>& lhs, const std::shared_ptr<ov::op::v0::Constant>& rhs) {+ if (!lhs || !rhs) {+ return !lhs && !rhs;+ }+ return lhs->get_element_type() == rhs->get_element_type() && lhs->get_shape() == rhs->get_shape() &&+ lhs->get_data_ptr() == rhs->get_data_ptr();+}++class CollectVocabCandidates final : public ov::pass::MatcherPass {+public:+ // `matched` counts every matched root, also roots that are not stored as candidates.+ CollectVocabCandidates(std::vector<Vocab>& vocabs, std::size_t& matched, bool lm_head) {+ const auto asymmetric_weight = opp::wrap_type<ov::op::v0::Constant>([](const ov::Output<ov::Node>& output) {+ return output.get_element_type() == ov::element::u8 && output.get_shape().size() == 2;+ });+ const auto symmetric_weight = opp::wrap_type<ov::op::v0::Constant>([](const ov::Output<ov::Node>& output) {+ return (output.get_element_type() == ov::element::i8 || output.get_element_type() == ov::element::i4) &&+ output.get_shape().size() == 2;+ });+ const auto full_precision_weight = opp::wrap_type<ov::op::v0::Constant>([](const ov::Output<ov::Node>& output) {+ const auto type = output.get_element_type();+ return (type == ov::element::f16 || type == ov::element::f32 || type == ov::element::bf16) &&+ output.get_shape().size() == 2;+ });+ const auto zerop = opp::wrap_type<ov::op::v0::Constant>([](const ov::Output<ov::Node>& output) {+ return output.get_element_type() == ov::element::u8 && output.get_shape().size() == 2;+ });+ const auto scale = opp::wrap_type<ov::op::v0::Constant>();+ const auto asymmetric_convert = opp::wrap_type<ov::op::v0::Convert>({asymmetric_weight});+ const auto zerop_convert = opp::wrap_type<ov::op::v0::Convert>({zerop});+ const auto subtract = opp::wrap_type<ov::op::v1::Subtract>({asymmetric_convert, zerop_convert});+ const auto symmetric_convert = opp::wrap_type<ov::op::v0::Convert>({symmetric_weight});+ const auto dequantized = std::make_shared<opp::op::Or>(ov::OutputVector{subtract, symmetric_convert});+ const auto scaled = opp::wrap_type<ov::op::v1::Multiply>({dequantized, scale});+ const auto weight = std::make_shared<opp::op::Or>(ov::OutputVector{scaled, full_precision_weight});+ const auto converted = opp::optional<ov::op::v0::Convert>({weight});++ std::shared_ptr<ov::Node> root;+ std::shared_ptr<ov::Node> matmul;+ if (lm_head) {+ // Both weight layouts match here, so that each LM head that InsertVocabSub128 can mark+ // is counted. Only the [V, H] layout can share storage with the embedding table.+ matmul = opp::wrap_type<ov::op::v0::MatMul>(+ {opp::any_input(), converted},+ [](const ov::Output<ov::Node>& output) {+ const auto node = ov::as_type_ptr<ov::op::v0::MatMul>(output.get_node_shared_ptr());+ return !node->get_transpose_a();+ });+ const ov::npuw::patterns::LMHeadTerminal terminal(matmul);+ root = opp::wrap_type<ov::op::v0::Result>({terminal.output}, [](const ov::Output<ov::Node>& output) {+ return output.get_node_shared_ptr()->get_rt_info().count("manually_added_output") == 0;+ });+ } else {+ root = opp::wrap_type<ov::op::v8::Gather>({converted, opp::any_input(), opp::any_input()});+ }++ register_matcher(std::make_shared<opp::Matcher>(root, lm_head ? "CollectLmHeadVocab" : "CollectEmbeddingVocab"),+ [=, &vocabs, &matched](opp::Matcher& matcher) {+ const auto& values = matcher.get_pattern_value_map();+ ++matched;+ if (lm_head) {+ const auto matched_matmul =+ ov::as_type_ptr<ov::op::v0::MatMul>(values.at(matmul).get_node_shared_ptr());+ if (!matched_matmul->get_transpose_b()) {+ return false;+ }+ }+ const auto constant = [&values](const std::shared_ptr<ov::Node>& pattern) {+ return ov::as_type_ptr<ov::op::v0::Constant>(values.at(pattern).get_node_shared_ptr());+ };+ if (values.count(full_precision_weight)) {+ vocabs.push_back({constant(full_precision_weight), nullptr, nullptr});+ } else if (values.count(asymmetric_weight)) {+ const auto matched_weight = constant(asymmetric_weight);+ const auto matched_zerop = constant(zerop);+ if (matched_zerop->get_shape()[0] != matched_weight->get_shape()[0]) {+ return false;+ }+ vocabs.push_back({matched_weight, matched_zerop, constant(scale)});+ } else {+ vocabs.push_back({constant(symmetric_weight), nullptr, constant(scale)});+ }+ return false;+ });+ }+};++void log_vocab_names(const char* label, const Vocab& vocab) {+ LOG_WARN(label << " weight='" << vocab.weight->get_friendly_name() << "', zero_point='"+ << (vocab.zerop ? vocab.zerop->get_friendly_name() : "<none>") << "', scale='"+ << (vocab.scale ? vocab.scale->get_friendly_name() : "<none>") << "'");+}++} // namespace++ov::npuw::DetectVocabSharing::DetectVocabSharing(bool& shared) : m_shared(shared) {}++bool ov::npuw::DetectVocabSharing::run_on_model(const std::shared_ptr<ov::Model>& model) {+ m_shared = false;++ std::vector<Vocab> embedding_vocabs;+ std::vector<Vocab> lm_head_vocabs;+ std::size_t embedding_count = 0;+ std::size_t lm_head_count = 0;+ ov::pass::GraphRewrite rewrite;+ rewrite.add_matcher<CollectVocabCandidates>(embedding_vocabs, embedding_count, false);+ rewrite.add_matcher<CollectVocabCandidates>(lm_head_vocabs, lm_head_count, true);+ rewrite.run_on_model(model);++ // InsertVocabSub128 marks every LM head that it matches. With more than one LM head, a head+ // that does not share the embedding vocabulary would be marked too, so detection stops here.+ if (lm_head_count > 1) {+ LOG_WARN("NPUW_LLM_VOCAB_ASYM_SHARED is enabled, but the model has "+ << lm_head_count+ << " LM-head outputs. Only one LM head is supported. Sub128 graph transformations are skipped.");+ return false;+ }++ for (const auto& embedding : embedding_vocabs) {+ for (const auto& lm_head : lm_head_vocabs) {+ if (same_storage(embedding.weight, lm_head.weight) && same_storage(embedding.zerop, lm_head.zerop) &&+ same_storage(embedding.scale, lm_head.scale)) {+ m_shared = true;+ return false;+ }+ }+ }++ if (embedding_vocabs.empty() && lm_head_vocabs.empty()) {+ LOG_WARN("NPUW_LLM_VOCAB_ASYM_SHARED is enabled, but no embedding Gather or LM-head MatMul "+ "vocabulary was detected. Sub128 graph transformations are skipped.");+ } else if (embedding_vocabs.empty()) {+ LOG_WARN("NPUW_LLM_VOCAB_ASYM_SHARED is enabled, but no embedding Gather vocabulary was detected. "+ "Sub128 graph transformations are skipped.");+ log_vocab_names("LM-head candidate:", lm_head_vocabs.front());+ } else if (lm_head_vocabs.empty()) {+ LOG_WARN("NPUW_LLM_VOCAB_ASYM_SHARED is enabled, but no LM-head MatMul vocabulary was detected. "+ "Sub128 graph transformations are skipped.");+ log_vocab_names("Embedding candidate:", embedding_vocabs.front());+ } else {+ LOG_WARN("NPUW_LLM_VOCAB_ASYM_SHARED is enabled, but embedding and LM-head vocabularies are "+ "not backed by the same storage. Sub128 graph transformations are skipped.");+ log_vocab_names("Embedding candidate:", embedding_vocabs.front());+ log_vocab_names("LM-head candidate:", lm_head_vocabs.front());+ }+ return false;+}diff --git a/src/plugins/intel_npu/src/plugin/npuw/npuw_transformations/insert_vocab_sub128.hpp b/src/plugins/intel_npu/src/plugin/npuw/npuw_transformations/insert_vocab_sub128.hppindex a61e79d88d1..b5d3a6e87a9 100644--- a/src/plugins/intel_npu/src/plugin/npuw/npuw_transformations/insert_vocab_sub128.hpp+++ b/src/plugins/intel_npu/src/plugin/npuw/npuw_transformations/insert_vocab_sub128.hpp@@ -7,6 +7,7 @@#include <memory>#include "openvino/pass/graph_rewrite.hpp"+#include "openvino/pass/pass.hpp"namespace ov::npuw {@@ -18,4 +19,16 @@ public:InsertVocabSub128();};+class DetectVocabSharing : public ov::pass::ModelPass {+public:+ OPENVINO_MODEL_PASS_RTTI("ov::npuw::DetectVocabSharing");++ explicit DetectVocabSharing(bool& shared);++ bool run_on_model(const std::shared_ptr<ov::Model>& model) override;++private:+ bool& m_shared;+};+} // namespace ov::npuwdiff --git a/src/plugins/intel_npu/tests/unit/npuw/gather_sub128_matcher_test.cpp b/src/plugins/intel_npu/tests/unit/npuw/gather_sub128_matcher_test.cppindex 0efec67b5ed..7e3b0d83733 100644--- a/src/plugins/intel_npu/tests/unit/npuw/gather_sub128_matcher_test.cpp+++ b/src/plugins/intel_npu/tests/unit/npuw/gather_sub128_matcher_test.cpp@@ -10,6 +10,7 @@#include <map>#include <memory>#include <optional>+#include <set>#include <string>#include <tuple>#include <vector>@@ -21,6 +22,7 @@#include "openvino/core/preprocess/pre_post_process.hpp"#include "openvino/opsets/opset10.hpp"#include "openvino/pass/graph_rewrite.hpp"+#include "openvino/runtime/tensor.hpp"#include "partitioning/partitioning.hpp"#include "partitioning/patterns/opt.hpp"#include "transformations/rt_info/decompression.hpp"@@ -52,6 +54,93 @@ std::shared_ptr<ov::Model> make_gather_model(float shift_value) {return std::make_shared<ov::Model>(ov::ResultVector{result}, ov::ParameterVector{ids});}+std::shared_ptr<ov::Model> make_vocab_sharing_model(bool shared,+ bool symmetric = false,+ const ov::Shape& scale_shape = {4, 1}) {+ auto ids = std::make_shared<ov::opset10::Parameter>(ov::element::i32, ov::Shape{1, 1});+ auto hidden = std::make_shared<ov::opset10::Parameter>(ov::element::f32, ov::Shape{1, 1, 2});+ auto axis = ov::opset10::Constant::create(ov::element::i32, ov::Shape{}, {0});++ auto embedding_weights = symmetric+ ? ov::opset10::Constant::create(ov::element::i4, ov::Shape{4, 2},+ std::vector<int8_t>(8, 1))+ : ov::opset10::Constant::create(ov::element::u8, ov::Shape{4, 2},+ std::vector<uint8_t>(8, 200));+ auto embedding_zero_point = ov::opset10::Constant::create(ov::element::u8, ov::Shape{4, 1},+ std::vector<uint8_t>(4, 128));+ auto embedding_scale = ov::opset10::Constant::create(ov::element::f16, scale_shape,+ std::vector<float>(ov::shape_size(scale_shape), 1.0f));++ auto lm_head_weights = shared+ ? embedding_weights+ : (symmetric ? ov::opset10::Constant::create(ov::element::i4, ov::Shape{4, 2},+ std::vector<int8_t>(8, 1))+ : ov::opset10::Constant::create(ov::element::u8, ov::Shape{4, 2},+ std::vector<uint8_t>(8, 200)));+ auto lm_head_zero_point = shared+ ? embedding_zero_point+ : ov::opset10::Constant::create(ov::element::u8, ov::Shape{4, 1},+ std::vector<uint8_t>(4, 128));+ auto lm_head_scale = shared ? embedding_scale : ov::opset10::Constant::create(ov::element::f16,+ scale_shape,+ std::vector<float>(ov::shape_size(scale_shape), 1.0f));++ auto embedding_convert = std::make_shared<ov::opset10::Convert>(embedding_weights, ov::element::f16);+ ov::Output<ov::Node> embedding_dequantized = embedding_convert;+ if (!symmetric) {+ auto embedding_zero_point_convert =+ std::make_shared<ov::opset10::Convert>(embedding_zero_point, ov::element::f16);+ embedding_dequantized =+ std::make_shared<ov::opset10::Subtract>(embedding_convert, embedding_zero_point_convert);+ }+ auto embedding_scaled = std::make_shared<ov::opset10::Multiply>(embedding_dequantized, embedding_scale);+ auto embedding_gather = std::make_shared<ov::opset10::Gather>(+ std::make_shared<ov::opset10::Convert>(embedding_scaled, ov::element::f32), ids, axis);++ auto lm_head_convert = std::make_shared<ov::opset10::Convert>(lm_head_weights, ov::element::f16);+ ov::Output<ov::Node> lm_head_dequantized = lm_head_convert;+ if (!symmetric) {+ auto lm_head_zero_point_convert =+ std::make_shared<ov::opset10::Convert>(lm_head_zero_point, ov::element::f16);+ lm_head_dequantized = std::make_shared<ov::opset10::Subtract>(lm_head_convert, lm_head_zero_point_convert);+ }+ auto lm_head_scaled = std::make_shared<ov::opset10::Multiply>(lm_head_dequantized, lm_head_scale);+ auto lm_head_matmul = std::make_shared<ov::opset10::MatMul>(+ hidden,+ std::make_shared<ov::opset10::Convert>(lm_head_scaled, ov::element::f32),+ false,+ true);++ auto embedding_result = std::make_shared<ov::opset10::Result>(embedding_gather);+ auto lm_head_result = std::make_shared<ov::opset10::Result>(lm_head_matmul);+ return std::make_shared<ov::Model>(ov::ResultVector{embedding_result, lm_head_result},+ ov::ParameterVector{ids, hidden});+}++std::shared_ptr<ov::Model> make_full_precision_vocab_sharing_model(bool shared) {+ auto ids = std::make_shared<ov::opset10::Parameter>(ov::element::i32, ov::Shape{1, 1});+ auto hidden = std::make_shared<ov::opset10::Parameter>(ov::element::f32, ov::Shape{1, 1, 2});+ auto axis = ov::opset10::Constant::create(ov::element::i32, ov::Shape{}, {0});+ auto embedding_weights = ov::opset10::Constant::create(ov::element::f16,+ ov::Shape{4, 2},+ std::vector<float>(8, 1.0f));+ auto lm_head_weights = shared+ ? embedding_weights+ : ov::opset10::Constant::create(ov::element::f16,+ ov::Shape{4, 2},+ std::vector<float>(8, 1.0f));+ auto embedding = std::make_shared<ov::opset10::Gather>(+ std::make_shared<ov::opset10::Convert>(embedding_weights, ov::element::f32), ids, axis);+ auto lm_head = std::make_shared<ov::opset10::MatMul>(+ hidden,+ std::make_shared<ov::opset10::Convert>(lm_head_weights, ov::element::f32),+ false,+ true);+ return std::make_shared<ov::Model>(ov::ResultVector{std::make_shared<ov::opset10::Result>(embedding),+ std::make_shared<ov::opset10::Result>(lm_head)},+ ov::ParameterVector{ids, hidden});+}+std::size_t count_gathers(const std::shared_ptr<ov::Model>& model) {std::size_t count = 0;for (const auto& node : model->get_ordered_ops()) {@@ -248,6 +337,92 @@ bool contains_node(const std::shared_ptr<ov::Model>& model, const std::string& n});}+struct TwoLmHeadModel {+ std::shared_ptr<ov::Model> model;+ std::shared_ptr<ov::Node> tied_weight;+ std::shared_ptr<ov::Node> tied_zero_point; // nullptr for the f16 tied vocabulary+ std::shared_ptr<ov::Node> extra_weight;+ std::shared_ptr<ov::Node> extra_zero_point;+};++ov::Output<ov::Node> make_u8_dequantization(const std::shared_ptr<ov::Node>& weight,+ const std::shared_ptr<ov::Node>& zero_point,+ const std::shared_ptr<ov::Node>& scale) {+ auto weight_convert = std::make_shared<ov::opset10::Convert>(weight, ov::element::f32);+ auto zero_point_convert = std::make_shared<ov::opset10::Convert>(zero_point, ov::element::f32);+ auto dequantized = std::make_shared<ov::opset10::Subtract>(weight_convert, zero_point_convert);+ return std::make_shared<ov::opset10::Multiply>(dequantized, scale);+}++// Embedding Gather + main LM head share one vocabulary (tied). An extra LM head (for example an+// MTP or auxiliary head) has its own, separate u8 asymmetric vocabulary. As in a real IR, each+// consumer of the tied vocabulary has its own dequantization nodes over the same constants.+TwoLmHeadModel make_two_lm_head_model(bool tied_u8, bool extra_pretransposed = false) {+ auto ids = std::make_shared<ov::opset10::Parameter>(ov::element::i32, ov::Shape{1});+ auto hidden = std::make_shared<ov::opset10::Parameter>(ov::element::f32, ov::Shape{1, 2});+ auto axis = ov::opset10::Constant::create(ov::element::i32, ov::Shape{}, {0});++ std::shared_ptr<ov::Node> tied_weight;+ std::shared_ptr<ov::Node> tied_zero_point;+ ov::Output<ov::Node> embedding_vocab;+ ov::Output<ov::Node> main_head_vocab;+ if (tied_u8) {+ tied_weight = ov::opset10::Constant::create(ov::element::u8, ov::Shape{4, 2}, std::vector<uint8_t>(8, 200));+ tied_zero_point = ov::opset10::Constant::create(ov::element::u8, ov::Shape{4, 1}, std::vector<uint8_t>(4, 128));+ auto scale = ov::opset10::Constant::create(ov::element::f32, ov::Shape{4, 1}, std::vector<float>(4, 1.0f));+ embedding_vocab = make_u8_dequantization(tied_weight, tied_zero_point, scale);+ main_head_vocab = make_u8_dequantization(tied_weight, tied_zero_point, scale);+ } else {+ tied_weight = ov::opset10::Constant::create(ov::element::f16, ov::Shape{4, 2}, std::vector<float>(8, 1.0f));+ embedding_vocab = std::make_shared<ov::opset10::Convert>(tied_weight, ov::element::f32);+ main_head_vocab = std::make_shared<ov::opset10::Convert>(tied_weight, ov::element::f32);+ }++ // Pretransposed extra head: weight [H, V], zero point and scale [1, V], MatMul without transpose_b.+ const auto extra_weight_shape = extra_pretransposed ? ov::Shape{2, 4} : ov::Shape{4, 2};+ const auto extra_channel_shape = extra_pretransposed ? ov::Shape{1, 4} : ov::Shape{4, 1};+ auto extra_weight =+ ov::opset10::Constant::create(ov::element::u8, extra_weight_shape, std::vector<uint8_t>(8, 100));+ auto extra_zero_point =+ ov::opset10::Constant::create(ov::element::u8, extra_channel_shape, std::vector<uint8_t>(4, 120));+ auto extra_scale =+ ov::opset10::Constant::create(ov::element::f32, extra_channel_shape, std::vector<float>(4, 0.5f));+ auto extra_head_vocab = make_u8_dequantization(extra_weight, extra_zero_point, extra_scale);++ auto embedding = std::make_shared<ov::opset10::Gather>(embedding_vocab, ids, axis);+ auto main_head = std::make_shared<ov::opset10::MatMul>(hidden, main_head_vocab, false, true);+ auto extra_head = std::make_shared<ov::opset10::MatMul>(hidden, extra_head_vocab, false, !extra_pretransposed);+ auto model = std::make_shared<ov::Model>(ov::ResultVector{std::make_shared<ov::opset10::Result>(embedding),+ std::make_shared<ov::opset10::Result>(main_head),+ std::make_shared<ov::opset10::Result>(extra_head)},+ ov::ParameterVector{ids, hidden});+ return {model, tied_weight, tied_zero_point, extra_weight, extra_zero_point};+}++// Same gate as in LLMCompiledModel when NPUW_LLM_VOCAB_ASYM_SHARED=YES. Returns the detection result.+bool run_vocab_asym_shared_gate(const std::shared_ptr<ov::Model>& model) {+ bool shared = false;+ ov::npuw::DetectVocabSharing(shared).run_on_model(model);+ if (!shared) {+ return false;+ }+ ov::npuw::InsertVocabSub128().run_on_model(model);+ return true;+}++// Source constants (behind the Convert) of all Subtracts marked as Sub128 shifts.+std::set<std::shared_ptr<ov::Node>> sub128_shift_sources(const std::shared_ptr<ov::Model>& model) {+ std::set<std::shared_ptr<ov::Node>> sources;+ for (const auto& node : model->get_ordered_ops()) {+ if (ov::is_type<ov::opset10::Subtract>(node) &&+ node->get_rt_info().count(ov::npuw::NPUW_SUB128_SHIFT_RT_INFO) > 0) {+ const auto convert = node->input_value(0).get_node_shared_ptr();+ sources.insert(convert->input_value(0).get_node_shared_ptr());+ }+ }+ return sources;+}+} // namespaceTEST(DQLiftGatherAsymCWTest, LiftsPairedSub128Shifts) {@@ -257,6 +432,227 @@ TEST(DQLiftGatherAsymCWTest, LiftsPairedSub128Shifts) {EXPECT_EQ(count_gathers(model), 3);}+TEST(DetectVocabSharingTest, DetectsSharedQuantizedVocabulary) {+ bool shared = false;+ ov::npuw::DetectVocabSharing pass(shared);++ EXPECT_FALSE(pass.run_on_model(make_vocab_sharing_model(true)));+ EXPECT_TRUE(shared);+}++TEST(DetectVocabSharingTest, RejectsSeparateQuantizedVocabularies) {+ bool shared = true;+ ov::npuw::DetectVocabSharing pass(shared);++ EXPECT_FALSE(pass.run_on_model(make_vocab_sharing_model(false)));+ EXPECT_FALSE(shared);+}++TEST(DetectVocabSharingTest, DetectsDistinctConstantsOverOneBuffer) {+ // A tied vocabulary read from IR: the embedding and the LM head get two different Constant+ // nodes, which view one buffer.+ ov::Tensor weight(ov::element::u8, ov::Shape{4, 2});+ ov::Tensor zero_point(ov::element::u8, ov::Shape{4, 1});+ ov::Tensor scale(ov::element::f32, ov::Shape{4, 1});+ std::fill_n(weight.data<uint8_t>(), weight.get_size(), uint8_t{200});+ std::fill_n(zero_point.data<uint8_t>(), zero_point.get_size(), uint8_t{128});+ std::fill_n(scale.data<float>(), scale.get_size(), 1.0f);+ const auto embedding_weight = std::make_shared<ov::opset10::Constant>(weight);+ const auto lm_head_weight = std::make_shared<ov::opset10::Constant>(weight);+ ASSERT_NE(embedding_weight, lm_head_weight);+ ASSERT_EQ(embedding_weight->get_data_ptr(), lm_head_weight->get_data_ptr());+ const auto embedding_vocab = make_u8_dequantization(embedding_weight,+ std::make_shared<ov::opset10::Constant>(zero_point),+ std::make_shared<ov::opset10::Constant>(scale));+ const auto lm_head_vocab = make_u8_dequantization(lm_head_weight,+ std::make_shared<ov::opset10::Constant>(zero_point),+ std::make_shared<ov::opset10::Constant>(scale));++ auto ids = std::make_shared<ov::opset10::Parameter>(ov::element::i32, ov::Shape{1});+ auto hidden = std::make_shared<ov::opset10::Parameter>(ov::element::f32, ov::Shape{1, 2});+ auto axis = ov::opset10::Constant::create(ov::element::i32, ov::Shape{}, {0});+ auto embedding = std::make_shared<ov::opset10::Gather>(embedding_vocab, ids, axis);+ auto lm_head = std::make_shared<ov::opset10::MatMul>(hidden, lm_head_vocab, false, true);+ const auto model = std::make_shared<ov::Model>(ov::ResultVector{std::make_shared<ov::opset10::Result>(embedding),+ std::make_shared<ov::opset10::Result>(lm_head)},+ ov::ParameterVector{ids, hidden});+ bool shared = false;++ EXPECT_FALSE(ov::npuw::DetectVocabSharing(shared).run_on_model(model));+ EXPECT_TRUE(shared);+}++TEST(DetectVocabSharingTest, DetectsSharedSymmetricI4Vocabulary) {+ bool shared = false;+ ov::npuw::DetectVocabSharing pass(shared);++ EXPECT_FALSE(pass.run_on_model(make_vocab_sharing_model(true, true)));+ EXPECT_TRUE(shared);+}++TEST(DetectVocabSharingTest, RejectsSeparateSymmetricI4Vocabularies) {+ bool shared = true;+ ov::npuw::DetectVocabSharing pass(shared);++ EXPECT_FALSE(pass.run_on_model(make_vocab_sharing_model(false, true)));+ EXPECT_FALSE(shared);+}++TEST(DetectVocabSharingTest, DetectsSharedFullPrecisionVocabulary) {+ bool shared = false;+ ov::npuw::DetectVocabSharing pass(shared);++ EXPECT_FALSE(pass.run_on_model(make_full_precision_vocab_sharing_model(true)));+ EXPECT_TRUE(shared);+}++TEST(DetectVocabSharingTest, RejectsSeparateFullPrecisionVocabularies) {+ bool shared = true;+ ov::npuw::DetectVocabSharing pass(shared);++ EXPECT_FALSE(pass.run_on_model(make_full_precision_vocab_sharing_model(false)));+ EXPECT_FALSE(shared);+}++using VocabScaleTestParams = std::tuple<bool, bool, ov::Shape>;++class DetectVocabSharingScaleTest : public ::testing::TestWithParam<VocabScaleTestParams> {+public:+ static std::string getTestCaseName(const ::testing::TestParamInfo<VocabScaleTestParams>& info) {+ const auto& [shared, symmetric, shape] = info.param;+ std::string name = std::string(shared ? "Shared" : "Separate") + (symmetric ? "I4" : "U8") + "Scale";+ if (shape.empty()) {+ return name + "Scalar";+ }+ for (const auto dimension : shape) {+ name += "_" + std::to_string(dimension);+ }+ return name;+ }+};++TEST_P(DetectVocabSharingScaleTest, ComparesStorageWithoutRestrictingScaleShape) {+ const auto& [expected_shared, symmetric, scale_shape] = GetParam();+ const auto model = make_vocab_sharing_model(expected_shared, symmetric, scale_shape);+ const auto original_nodes = model->get_ordered_ops();+ bool shared = !expected_shared;+ ov::npuw::DetectVocabSharing pass(shared);++ EXPECT_FALSE(pass.run_on_model(model));+ EXPECT_EQ(shared, expected_shared);+ EXPECT_EQ(model->get_ordered_ops(), original_nodes);+}++INSTANTIATE_TEST_SUITE_P(+ ScaleLayouts,+ DetectVocabSharingScaleTest,+ ::testing::Combine(::testing::Bool(),+ ::testing::Bool(),+ ::testing::Values(ov::Shape{}, ov::Shape{1}, ov::Shape{2}, ov::Shape{1, 1},+ ov::Shape{1, 2}, ov::Shape{4, 1}, ov::Shape{4, 2})),+ DetectVocabSharingScaleTest::getTestCaseName);++TEST(DetectVocabSharingTest, RejectsMissingVocabularyBranchAndResetsState) {+ bool shared = false;+ ov::npuw::DetectVocabSharing pass(shared);+ const auto model = make_vocab_sharing_model(true);+ EXPECT_FALSE(pass.run_on_model(model));+ ASSERT_TRUE(shared);++ model->remove_result(model->get_results().back());+ EXPECT_FALSE(pass.run_on_model(model));+ EXPECT_FALSE(shared);++ const auto lm_head_only = make_vocab_sharing_model(true);+ lm_head_only->remove_result(lm_head_only->get_results().front());+ shared = true;+ EXPECT_FALSE(pass.run_on_model(lm_head_only));+ EXPECT_FALSE(shared);+}++TEST(DetectVocabSharingTest, RejectsNonTerminalMatMul) {+ const auto model = make_vocab_sharing_model(true);+ const auto result = model->get_results().back();+ const auto projection = ov::opset10::Constant::create(ov::element::f32, ov::Shape{4, 2}, {1.0f});+ const auto intermediate = std::make_shared<ov::opset10::MatMul>(result->input_value(0), projection, false, false);+ result->input(0).replace_source_output(intermediate);+ bool shared = true;++ EXPECT_FALSE(ov::npuw::DetectVocabSharing(shared).run_on_model(model));+ EXPECT_FALSE(shared);+}++TEST(DetectVocabSharingTest, RejectsManuallyAddedLmHeadOutput) {+ const auto model = make_vocab_sharing_model(true);+ model->get_results().back()->get_rt_info()["manually_added_output"] = true;+ bool shared = true;++ EXPECT_FALSE(ov::npuw::DetectVocabSharing(shared).run_on_model(model));+ EXPECT_FALSE(shared);+}++class DetectVocabSharingTerminalTest : public ::testing::TestWithParam<VocabMatMulTerminal> {};++TEST_P(DetectVocabSharingTerminalTest, DetectsSharedVocabularyThroughLmHeadTerminal) {+ const auto model = make_vocab_matmul_model(false, GetParam());+ const auto nodes = model->get_ordered_ops();+ const auto matmul = std::find_if(nodes.begin(), nodes.end(), [](const auto& node) {+ return ov::is_type<ov::opset10::MatMul>(node);+ });+ ASSERT_NE(matmul, nodes.end());+ const auto ids = std::make_shared<ov::opset10::Parameter>(ov::element::i32, ov::Shape{1});+ const auto axis = ov::opset10::Constant::create(ov::element::i32, ov::Shape{}, {0});+ const auto embedding = std::make_shared<ov::opset10::Gather>((*matmul)->input_value(1), ids, axis);+ model->add_parameters({ids});+ model->add_results({std::make_shared<ov::opset10::Result>(embedding)});+ bool shared = false;++ EXPECT_FALSE(ov::npuw::DetectVocabSharing(shared).run_on_model(model));+ EXPECT_TRUE(shared);+}++INSTANTIATE_TEST_SUITE_P(LmHeadTerminal,+ DetectVocabSharingTerminalTest,+ ::testing::Values(VocabMatMulTerminal::Add,+ VocabMatMulTerminal::Transpose,+ VocabMatMulTerminal::Convert,+ VocabMatMulTerminal::Divide,+ VocabMatMulTerminal::Gated));++// InsertVocabSub128 marks every LM head that it matches. Thus detection must stop for a model with+// more than one LM head, else an extra head with its own u8 vocabulary is marked too.+TEST(DetectVocabSharingTwoLmHeadsTest, AbortsWhenF16HeadIsTiedAndU8HeadIsSeparate) {+ const auto two_heads = make_two_lm_head_model(false);++ EXPECT_FALSE(run_vocab_asym_shared_gate(two_heads.model));+ EXPECT_EQ(count_sub128_shifts(two_heads.model), 0u);+}++TEST(DetectVocabSharingTwoLmHeadsTest, AbortsWhenU8HeadIsTiedAndU8HeadIsSeparate) {+ const auto two_heads = make_two_lm_head_model(true);++ EXPECT_FALSE(run_vocab_asym_shared_gate(two_heads.model));+ EXPECT_EQ(count_sub128_shifts(two_heads.model), 0u);+}++TEST(DetectVocabSharingTwoLmHeadsTest, CountsPretransposedSeparateHead) {+ // The pretransposed head cannot share the embedding storage, but InsertVocabSub128 marks it.+ const auto two_heads = make_two_lm_head_model(true, true);++ EXPECT_FALSE(run_vocab_asym_shared_gate(two_heads.model));+ EXPECT_EQ(count_sub128_shifts(two_heads.model), 0u);+}++TEST(DetectVocabSharingTwoLmHeadsTest, IgnoresManuallyAddedSecondHead) {+ // A manually added output (for example the Eagle-3 hidden state) is not an LM head.+ const auto two_heads = make_two_lm_head_model(true);+ two_heads.model->get_results().back()->get_rt_info()["manually_added_output"] = true;++ EXPECT_TRUE(run_vocab_asym_shared_gate(two_heads.model));+ const std::set<std::shared_ptr<ov::Node>> expected{two_heads.tied_weight, two_heads.tied_zero_point};+ EXPECT_EQ(sub128_shift_sources(two_heads.model), expected);+}+TEST(DQLiftGatherAsymCWTest, RejectsNon128Subtractions) {const auto model = make_gather_model(127.0f);@@ -375,21 +771,15 @@ TEST(ConvertDQVocabTest, ReplacesMarkedShiftsWithLazySources) {EXPECT_EQ(count_sub128_shifts(model), 0u);}-using VocabSub128TestParams = std::tuple<bool, bool>;--class InsertVocabSub128PrePostProcessingTest : public ::testing::TestWithParam<VocabSub128TestParams> {+class InsertVocabSub128PrePostProcessingTest : public ::testing::TestWithParam<bool> {public:- static std::string getTestCaseName(const ::testing::TestParamInfo<VocabSub128TestParams>& info) {- const auto [pretransposed_layout, convert_before_matmul] = info.param;- return std::string(pretransposed_layout ? "Pretransposed" : "Standard") +- (convert_before_matmul ? "WithConvert" : "DirectMatMul");+ static std::string getTestCaseName(const ::testing::TestParamInfo<bool>& info) {+ return info.param ? "WithConvert" : "DirectMatMul";}};TEST_P(InsertVocabSub128PrePostProcessingTest, PreservesVocabularyConverts) {- const auto [pretransposed_layout, convert_before_matmul] = GetParam();- const auto model = pretransposed_layout ? make_pretransposed_vocab_matmul_model(convert_before_matmul)- : make_vocab_matmul_model(convert_before_matmul);+ const auto model = make_vocab_matmul_model(GetParam());EXPECT_TRUE(ov::npuw::InsertVocabSub128().run_on_model(model));EXPECT_EQ(count_subtracts(model), 3u);EXPECT_EQ(count_sub128_shifts(model), 2u);@@ -412,14 +802,20 @@ TEST_P(InsertVocabSub128PrePostProcessingTest, PreservesVocabularyConverts) {EXPECT_TRUE(contains_node(model, "vocab_zero_point_convert"));}-INSTANTIATE_TEST_SUITE_P(LayoutAndConversion,+INSTANTIATE_TEST_SUITE_P(Conversion,InsertVocabSub128PrePostProcessingTest,- ::testing::Values(std::make_tuple(false, false),- std::make_tuple(false, true),- std::make_tuple(true, false),- std::make_tuple(true, true)),+ ::testing::Bool(),InsertVocabSub128PrePostProcessingTest::getTestCaseName);+TEST(InsertVocabSub128Test, SkipsPretransposedLayout) {+ // A [H, V] LM head cannot share storage with the [V, H] embedding table.+ for (const bool convert_before_matmul : {false, true}) {+ const auto model = make_pretransposed_vocab_matmul_model(convert_before_matmul);+ EXPECT_FALSE(ov::npuw::InsertVocabSub128().run_on_model(model));+ EXPECT_EQ(count_sub128_shifts(model), 0u);+ }+}+class InsertVocabSub128LmHeadTerminalTest : public ::testing::TestWithParam<VocabMatMulTerminal> {public:static std::string getTestCaseName(const ::testing::TestParamInfo<VocabMatMulTerminal>& info) {