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
Add NGramHashFunction internal operation, fusion pass and CPU plugin implementation (#38762)
Mateusz Mikolajczyk333164412c82
diff --git a/docs/articles_en/documentation/openvino-ir-format/operation-sets/operation-specs/internal/ngram-hash-function.rst b/docs/articles_en/documentation/openvino-ir-format/operation-sets/operation-specs/internal/ngram-hash-function.rstnew file mode 100644index 00000000000..acc0bb96138--- /dev/null+++ b/docs/articles_en/documentation/openvino-ir-format/operation-sets/operation-specs/internal/ngram-hash-function.rst@@ -0,0 +1,125 @@+.. {#openvino_docs_ops_internal_NGramHashFunction}++NGramHashFunction+=================+++.. meta::+ :description: Learn about NGramHashFunction, which hashes prepared n-gram windows into embedding table row indices.++**Versioned name**: *NGramHashFunction*++**Category**: *Sequence processing*++**Short description**: Computes embedding table row indices for each n-gram window and hash head.++**Detailed description**++The largest n-gram order ``ngram_size`` is the number of ``multipliers`` and must be at least ``2``.+The last input dimension contains ``ngram_size`` token IDs, oldest first. For each window, let+``x[k] = ngrams[..., ngram_size - 1 - k]``, so ``x[0]`` is the current token.++Orders ``2 .. ngram_size`` are hashed independently for each window. Output heads are grouped by+ascending order, with ``heads_per_order[o - 2]`` heads for order ``o``:++.. code-block:: py++ mixed = x[0] * multipliers[0]+ h = 0+ for k in range(1, ngram_size):+ mixed ^= x[k] * multipliers[k]+ for _ in range(heads_per_order[k - 1]):+ row_ids[..., h] = floor_mod(mixed, head_vocab_sizes[h]) + head_offsets[h]+ h += 1++Arithmetic uses signed 64-bit two's complement values, with multiplication wrapping modulo ``2^64``.+An int32 input is sign-extended before hashing. ``floor_mod`` returns a non-negative remainder for the+positive divisor, including when ``mixed`` is negative.++The operation is stateless and applies independently over all leading dimensions. Window preparation,+padding and sequence boundaries are handled outside the operation.+++**Attributes**++* *heads_per_order*++ * **Description**: the number of hashed heads of every n-gram order ``2 .. ngram_size``,+ ``ngram_size - 1`` values, where element ``heads_per_order[o - 2]`` is the head count for order ``o``.+ A value of ``0`` skips that order. ``H = sum(heads_per_order)`` must be positive.+ * **Range of values**: non-negative integers+ * **Type**: ``int64[]``+ * **Required**: *yes*++* *multipliers*++ * **Description**: the ``ngram_size`` hash multipliers; ``multipliers[k]`` applies to the token ``k``+ steps back (``multipliers[0]`` to the current token). Their count defines ``ngram_size``, the largest+ hashed order and the size of the last dimension of ``ngrams``.+ * **Range of values**: any ``int64``, at least ``2`` values+ * **Type**: ``int64[]``+ * **Required**: *yes*++* *head_vocab_sizes*++ * **Description**: the vocabulary size (modulus) of every hashed head, ``H`` values, grouped by order.+ * **Range of values**: integers in ``[1, 2^31]``, with+ ``head_offsets[h] + head_vocab_sizes[h] - 1 <= 2^31 - 1``+ * **Type**: ``int64[]``+ * **Required**: *yes*++* *head_offsets*++ * **Description**: the first row of every hashed head in the packed table, ``H`` values.+ * **Range of values**: non-negative integers, ``head_offsets[h] + head_vocab_sizes[h] - 1 <= 2^31 - 1``+ * **Type**: ``int64[]``+ * **Required**: *yes*+++**Inputs**++* **1**: ``ngrams`` - tensor of type *T_IND* and shape ``[..., ngram_size]``: the n-gram window of+ every token, oldest first, the current token last. The rank is at least 1. **Required.**+++**Outputs**++* **1**: ``row_ids`` - tensor of type ``int32`` and shape ``[..., H]``: the row of the packed n-gram+ table for every token and hashed head.+++**Types**++* *T_IND*: ``int32`` or ``int64``.+++**Dimensions**++* ``...`` - arbitrary leading dimensions, preserved in the output.++* ``H`` - number of hashed heads, ``sum(heads_per_order)``.+++**Example**++For ``ngrams = [[1, 2, 3], [4, 5, 6]]``, the following configuration produces+``row_ids = [[3, 15], [0, 21]]``.++.. code-block:: xml+ :force:++ <layer id="1" name="ngram_hash" type="NGramHashFunction" version="extension">+ <data heads_per_order="1,1" multipliers="3,5,7" head_vocab_sizes="11,13" head_offsets="0,11"/>+ <input>+ <port id="0" precision="I64">+ <dim>2</dim>+ <dim>3</dim>+ </port>+ </input>+ <output>+ <port id="1" precision="I32">+ <dim>2</dim>+ <dim>2</dim>+ </port>+ </output>+ </layer>diff --git a/src/common/transformations/include/sources.cmake b/src/common/transformations/include/sources.cmakeindex eab7bbafaf0..a2ce139028b 100644--- a/src/common/transformations/include/sources.cmake+++ b/src/common/transformations/include/sources.cmake@@ -118,6 +118,7 @@ set(COMMON_OPTIMIZATIONS_HEADERS${CMAKE_CURRENT_LIST_DIR}/transformations/common_optimizations/multi_scale_deformable_attn_grid_sample_fusion.hpp${CMAKE_CURRENT_LIST_DIR}/transformations/common_optimizations/mvn_fusion.hpp${CMAKE_CURRENT_LIST_DIR}/transformations/common_optimizations/nearest_neighbor_upsampling_fusion.hpp+ ${CMAKE_CURRENT_LIST_DIR}/transformations/common_optimizations/ngram_hash_function_fusion.hpp${CMAKE_CURRENT_LIST_DIR}/transformations/common_optimizations/nonzero_horizontal_fusion.hpp${CMAKE_CURRENT_LIST_DIR}/transformations/common_optimizations/nop_elimination.hpp${CMAKE_CURRENT_LIST_DIR}/transformations/common_optimizations/normalize_l2_fusion.hppdiff --git a/src/common/transformations/include/transformations/common_optimizations/ngram_hash_function_fusion.hpp b/src/common/transformations/include/transformations/common_optimizations/ngram_hash_function_fusion.hppnew file mode 100644index 00000000000..c917e566613--- /dev/null+++ b/src/common/transformations/include/transformations/common_optimizations/ngram_hash_function_fusion.hpp@@ -0,0 +1,79 @@+// Copyright (C) 2018-2026 Intel Corporation+// SPDX-License-Identifier: Apache-2.0+//++#pragma once++#include "openvino/pass/graph_rewrite.hpp"+#include "openvino/pass/matcher_pass.hpp"+#include "transformations_visibility.hpp"++namespace ov {+namespace pass {++class TRANSFORMATIONS_API NGramHashBlockFusion;+class TRANSFORMATIONS_API NGramHashConcatFusion;+class TRANSFORMATIONS_API NGramHashFunctionFusion;++} // namespace pass+} // namespace ov++/**+ * @ingroup ov_transformation_common_api+ * @brief Fuses one n-gram order's hash-and-modulo block into an NGramHashFunction.+ *+ * Matches an int64 subgraph for one order, such as the Qwen3.8-Flash-Next PLE or DeepSeek Engram hash:+ * mix = (x[0] * m[0]) ^ (x[1] * m[1]) ^ ... ^ (x[o-1] * m[o-1])+ * block = FloorMod(Unsqueeze(mix, -1), vocab) + offsets+ * and replaces it with Convert(NGramHashFunction(Concat(Unsqueeze(x[o-1]), ..., Unsqueeze(x[0])))). The generated+ * hash has heads only for this order; its leading heads_per_order entries are zero. The Convert preserves the+ * original i64 result type while keeping wrapping 64-bit multiplication and modulo inside the operation, before a+ * plugin can lower surrounding i64 arithmetic to i32.+ *+ * This pass handles each order independently, including blocks that are not part of a Concat. A later+ * NGramHashConcatFusion may merge compatible single-order results into one multi-order operation.+ * Requires NUMPY broadcasting and a proven trailing-unit append. Token terms are packed without broadcasting:+ * statically different token shapes are not fused, and dynamic ones that differ at runtime make inference fail.+ * This pass does not prevent subsequent backend precision conversion from narrowing token inputs.+ */+class ov::pass::NGramHashBlockFusion : public ov::pass::MatcherPass {+public:+ OPENVINO_MATCHER_PASS_RTTI("NGramHashBlockFusion");+ NGramHashBlockFusion();+};++/**+ * @ingroup ov_transformation_common_api+ * @brief Merges compatible single-order hash operations under an i64 Concat into one multi-order operation.+ *+ * Expects inputs produced by NGramHashBlockFusion: Convert(NGramHashFunction(...)) for strictly increasing n-gram+ * orders, concatenated on the last axis. Each order's token-and-multiplier terms must extend the previous order's+ * terms, so all heads can be computed from one packed token window. On success, replaces the Concat with+ * Convert(NGramHashFunction(...)) whose heads_per_order describes all concatenated orders.+ *+ * If the orders are out of order or do not share the required prefix terms, this pass leaves the Concat in place;+ * independent block fusions performed earlier remain valid.+ */+class ov::pass::NGramHashConcatFusion : public ov::pass::MatcherPass {+public:+ OPENVINO_MATCHER_PASS_RTTI("NGramHashConcatFusion");+ NGramHashConcatFusion();+};++/**+ * @ingroup ov_transformation_common_api+ * @brief Fuses an int64 hashed n-gram graph into NGramHashFunction operation(s).+ *+ * Runs NGramHashBlockFusion first to replace each recognized order's hash-and-modulo block, then runs+ * NGramHashConcatFusion to combine compatible ascending orders that use the same extending token window. A graph+ * without a compatible multi-order Concat can still receive independent single-order fusions; unmatched or+ * incompatible subgraphs are left unchanged.+ */+class ov::pass::NGramHashFunctionFusion : public ov::pass::GraphRewrite {+public:+ OPENVINO_GRAPH_REWRITE_RTTI("NGramHashFunctionFusion");+ NGramHashFunctionFusion() {+ add_matcher<NGramHashBlockFusion>();+ add_matcher<NGramHashConcatFusion>();+ }+};diff --git a/src/common/transformations/src/sources.cmake b/src/common/transformations/src/sources.cmakeindex 92a81d136aa..2ee69a0dc4b 100644--- a/src/common/transformations/src/sources.cmake+++ b/src/common/transformations/src/sources.cmake@@ -79,6 +79,7 @@ set(COMMON_OPTIMIZATIONS_SOURCES${CMAKE_CURRENT_LIST_DIR}/transformations/common_optimizations/multi_scale_deformable_attn_grid_sample_fusion.cpp${CMAKE_CURRENT_LIST_DIR}/transformations/common_optimizations/mvn_fusion.cpp${CMAKE_CURRENT_LIST_DIR}/transformations/common_optimizations/nearest_neighbor_upsampling_fusion.cpp+ ${CMAKE_CURRENT_LIST_DIR}/transformations/common_optimizations/ngram_hash_function_fusion.cpp${CMAKE_CURRENT_LIST_DIR}/transformations/common_optimizations/nonzero_horizontal_fusion.cpp${CMAKE_CURRENT_LIST_DIR}/transformations/common_optimizations/nop_elimination.cpp${CMAKE_CURRENT_LIST_DIR}/transformations/common_optimizations/normalize_l2_fusion.cppdiff --git a/src/common/transformations/src/transformations/common_optimizations/ngram_hash_function_fusion.cpp b/src/common/transformations/src/transformations/common_optimizations/ngram_hash_function_fusion.cppnew file mode 100644index 00000000000..8db1e7cf2cf--- /dev/null+++ b/src/common/transformations/src/transformations/common_optimizations/ngram_hash_function_fusion.cpp@@ -0,0 +1,376 @@+// Copyright (C) 2018-2026 Intel Corporation+// SPDX-License-Identifier: Apache-2.0+//++#include "transformations/common_optimizations/ngram_hash_function_fusion.hpp"++#include <algorithm>+#include <cstdint>+#include <functional>+#include <limits>+#include <memory>+#include <optional>+#include <utility>+#include <vector>++#include "itt.hpp"+#include "openvino/core/graph_util.hpp"+#include "openvino/core/rt_info.hpp"+#include "openvino/op/add.hpp"+#include "openvino/op/bitwise_xor.hpp"+#include "openvino/op/concat.hpp"+#include "openvino/op/constant.hpp"+#include "openvino/op/convert.hpp"+#include "openvino/op/floor_mod.hpp"+#include "openvino/op/multiply.hpp"+#include "openvino/op/ngram_hash_function.hpp"+#include "openvino/op/reshape.hpp"+#include "openvino/op/unsqueeze.hpp"+#include "openvino/pass/pattern/matcher.hpp"+#include "openvino/pass/pattern/op/or.hpp"+#include "openvino/pass/pattern/op/pattern.hpp"+#include "openvino/pass/pattern/op/wrap_type.hpp"+#include "transformations/utils/utils.hpp"++// A named enclosing namespace keeps these generic helper names unique when UNITY_BUILD combines sources.+namespace ov::pass::ngram_hash_function_fusion {+namespace {++// One (token, multiplier) term of the XOR mix.+struct Term {+ ov::Output<ov::Node> token;+ int64_t multiplier;+ bool operator==(const Term& other) const {+ return token == other.token && multiplier == other.multiplier;+ }+};++// A constant broadcast along the last axis only: scalar, [H] or [1, ..., 1, H].+bool is_last_axis_constant(const ov::Output<ov::Node>& output) {+ const auto constant = ov::as_type_ptr<ov::op::v0::Constant>(output.get_node_shared_ptr());+ if (!constant) {+ return false;+ }+ const auto& shape = constant->get_shape();+ return shape.empty() || ov::shape_size(shape) == shape.back();+}++std::vector<int64_t> constant_values(const ov::Output<ov::Node>& output) {+ return ov::as_type_ptr<ov::op::v0::Constant>(output.get_node_shared_ptr())->cast_vector<int64_t>();+}++// Unsqueeze(x, -1), or a Reshape doing the same, e.g. the one NopElimination makes from such an Unsqueeze.+bool appends_unit_last_dim(const ov::Output<ov::Node>& output) {+ const auto node = output.get_node_shared_ptr();+ const auto& in_shape = node->get_input_partial_shape(0);+ const auto& out_shape = output.get_partial_shape();+ if (in_shape.rank().is_dynamic() || out_shape.rank().is_dynamic() ||+ ov::op::util::get_unsqueeze_axes(in_shape, out_shape) != std::vector<int64_t>{in_shape.rank().get_length()}) {+ return false;+ }+ auto expected_shape = in_shape;+ expected_shape.push_back(1);+ if (!out_shape.same_scheme(expected_shape)) {+ return false;+ }+ const auto reshape = ov::as_type_ptr<ov::op::v1::Reshape>(node);+ if (!reshape) {+ return true; // Unsqueeze passes every input dimension through+ }+ // With special_zero, Reshape(x, [0, ..., 0, 1]) copies every input dimension.+ const auto target = ov::as_type_ptr<ov::op::v0::Constant>(reshape->get_input_node_shared_ptr(1));+ std::vector<int64_t> copy_all(in_shape.size(), 0);+ copy_all.push_back(1);+ if (reshape->get_special_zero() && target && target->cast_vector<int64_t>() == copy_all) {+ return true;+ }+ // Reshape keeps the element count, so it can't reinterpret a single dynamic dimension, but may reorder several.+ // A static 0 makes the element count 0, so it no longer pins the dynamic dimension either.+ const auto is_dynamic = [](const ov::Dimension& dim) {+ return dim.is_dynamic();+ };+ return std::count_if(in_shape.begin(), in_shape.end(), is_dynamic) <= 1 &&+ std::find(in_shape.begin(), in_shape.end(), ov::Dimension(0)) == in_shape.end();+}++bool is_last_axis(int64_t axis, const ov::Rank& rank) {+ return axis == -1 || (rank.is_static() && axis == rank.get_length() - 1);+}++using MultiplierPredicate = std::function<bool(const ov::Output<ov::Node>&)>;++// Walks the XOR tree of the mix; its depth depends on the n-gram order, so it cannot be a fixed pattern.+bool collect_terms(const ov::Output<ov::Node>& output,+ const MultiplierPredicate& is_multiplier,+ std::vector<Term>& terms,+ ov::NodeVector& nodes) {+ const auto node = output.get_node_shared_ptr();+ if (const auto xor_node = ov::as_type_ptr<ov::op::v13::BitwiseXor>(node)) {+ if (xor_node->get_autob().m_type != ov::op::AutoBroadcastType::NUMPY) {+ return false;+ }+ nodes.push_back(xor_node);+ return collect_terms(xor_node->input_value(0), is_multiplier, terms, nodes) &&+ collect_terms(xor_node->input_value(1), is_multiplier, terms, nodes);+ }+ const auto mul_node = ov::as_type_ptr<ov::op::v1::Multiply>(node);+ if (!mul_node || mul_node->get_autob().m_type != ov::op::AutoBroadcastType::NUMPY) {+ return false;+ }+ const bool lhs_const = is_multiplier(mul_node->input_value(0));+ if (lhs_const == is_multiplier(mul_node->input_value(1))) {+ return false; // exactly one scalar constant side+ }+ Term term{mul_node->input_value(lhs_const ? 1 : 0), constant_values(mul_node->input_value(lhs_const ? 0 : 1))[0]};+ const auto& token_rank = term.token.get_partial_shape().rank();+ const auto multiplier_rank = mul_node->get_input_shape(lhs_const ? 0 : 1).size();+ if (token_rank.is_dynamic() || multiplier_rank > static_cast<size_t>(token_rank.get_length())) {+ return false;+ }+ if (term.token.get_element_type() != ov::element::i64 ||+ std::find(terms.begin(), terms.end(), term) != terms.end()) {+ return false; // x ^ x cancels out, not an n-gram hash+ }+ nodes.push_back(mul_node);+ terms.push_back(std::move(term));+ return true;+}++bool rows_fit_int32(const std::vector<int64_t>& vocab_sizes, const std::vector<int64_t>& offsets) {+ for (size_t h = 0; h < vocab_sizes.size(); ++h) {+ if (vocab_sizes[h] <= 0 || offsets[h] < 0 ||+ offsets[h] > std::numeric_limits<int32_t>::max() - (vocab_sizes[h] - 1)) {+ return false;+ }+ }+ return true;+}++// Replaces `root` by Convert(NGramHashFunction(Concat(Unsqueeze(x[n-1]), ..., Unsqueeze(x[0])))).+bool replace_with_hash(const std::shared_ptr<ov::Node>& root,+ const std::vector<Term>& terms,+ const std::vector<int64_t>& heads_per_order,+ const std::vector<int64_t>& vocab_sizes,+ const std::vector<int64_t>& offsets,+ const ov::NodeVector& matched_nodes) {+ // Tokens are packed without broadcasting: tokens that only broadcast to a common shape are rejected here when+ // static, and make the packing Concat fail at runtime when dynamic, instead of silently changing results.+ auto token_shape = terms[0].token.get_partial_shape();+ for (const auto& term : terms) {+ if (!ov::PartialShape::merge_into(token_shape, term.token.get_partial_shape())) {+ return false;+ }+ }+ const auto axis = ov::op::v0::Constant::create(ov::element::i64, ov::Shape{1}, {-1});+ ov::NodeVector new_nodes{axis};+ ov::OutputVector window;+ for (auto it = terms.rbegin(); it != terms.rend(); ++it) {+ window.push_back(std::make_shared<ov::op::v0::Unsqueeze>(it->token, axis));+ }+ std::vector<int64_t> multipliers;+ for (const auto& term : terms) {+ multipliers.push_back(term.multiplier);+ }+ const auto ngrams = std::make_shared<ov::op::v0::Concat>(window, -1);+ const auto hash = std::make_shared<ov::op::internal::NGramHashFunction>(ngrams,+ heads_per_order,+ multipliers,+ vocab_sizes,+ offsets);+ if (!hash->get_output_partial_shape(0).compatible(root->get_output_partial_shape(0))) {+ return false;+ }+ const auto convert = std::make_shared<ov::op::v0::Convert>(hash, root->get_output_element_type(0));+ hash->set_friendly_name(root->get_friendly_name() + "/NGramHashFunction");+ convert->set_friendly_name(root->get_friendly_name());+ new_nodes.insert(new_nodes.end(), {ngrams, hash, convert});+ for (const auto& w : window) {+ new_nodes.push_back(w.get_node_shared_ptr());+ }+ ov::copy_runtime_info(matched_nodes, new_nodes);+ ov::replace_node(root, convert);+ return true;+}++// A single-order NGramHashFunction produced by NGramHashBlockFusion, behind its i64 Convert.+std::shared_ptr<ov::op::internal::NGramHashFunction> get_single_order_hash(const ov::Output<ov::Node>& output) {+ const auto convert = ov::as_type_ptr<ov::op::v0::Convert>(output.get_node_shared_ptr());+ if (!convert || convert->get_output_element_type(0) != ov::element::i64) {+ return nullptr;+ }+ const auto hash = ov::as_type_ptr<ov::op::internal::NGramHashFunction>(convert->get_input_node_shared_ptr(0));+ if (!hash) {+ return nullptr;+ }+ const auto& heads = hash->get_heads_per_order();+ const bool single_order = std::all_of(heads.begin(), heads.end() - 1, [](int64_t h) {+ return h == 0;+ });+ return single_order ? hash : nullptr;+}++// The (token, multiplier) terms of a packed window Concat(Unsqueeze(x[n-1]), ..., Unsqueeze(x[0])).+std::optional<std::vector<Term>> get_terms(const ov::op::internal::NGramHashFunction& hash) {+ const auto window = ov::as_type_ptr<ov::op::v0::Concat>(hash.get_input_node_shared_ptr(0));+ const auto n = static_cast<size_t>(hash.get_ngram_size());+ if (!window || window->get_input_size() != n ||+ !is_last_axis(window->get_axis(), window->get_output_partial_shape(0).rank())) {+ return std::nullopt;+ }+ std::vector<Term> terms;+ for (size_t k = 0; k < n; ++k) {+ const auto unsqueeze = window->input_value(n - 1 - k);+ if (!ov::as_type_ptr<ov::op::v0::Unsqueeze>(unsqueeze.get_node_shared_ptr()) ||+ !appends_unit_last_dim(unsqueeze)) {+ return std::nullopt;+ }+ Term term{unsqueeze.get_node()->input_value(0), hash.get_multipliers()[k]};+ if (std::find(terms.begin(), terms.end(), term) != terms.end()) {+ return std::nullopt; // x ^ x cancels out; the concat merge treats terms as a set+ }+ terms.push_back(std::move(term));+ }+ return terms;+}++} // namespace+} // namespace ov::pass::ngram_hash_function_fusion++ov::pass::NGramHashBlockFusion::NGramHashBlockFusion() {+ MATCHER_SCOPE(NGramHashBlockFusion);+ // Exporters keep the hash multipliers as scalars or as [1] / [1, 1] constants.+ const auto scalar_multiplier = ov::pass::pattern::shape_matches("[]") || ov::pass::pattern::shape_matches("[1]") ||+ ov::pass::pattern::shape_matches("[1, 1]");++ // mix = ... ^ (token * multiplier): the top XOR has at least one Multiply-by-scalar operand.+ auto term_m = ov::pass::pattern::wrap_type<ov::op::v1::Multiply>(+ {ov::pass::pattern::any_input(ov::pass::pattern::type_matches(ov::element::i64)),+ ov::pass::pattern::wrap_type<ov::op::v0::Constant>(scalar_multiplier)},+ ov::pass::pattern::type_matches(ov::element::i64),+ {{"auto_broadcast", "numpy"}});+ // BitwiseXor is not commutative for the matcher (ov::op::util::is_commutative), so both operand orders are listed.+ auto xor_m =+ ov::pass::pattern::wrap_type<ov::op::v13::BitwiseXor>({ov::pass::pattern::any_input(), term_m},+ ov::pass::pattern::type_matches(ov::element::i64),+ {{"auto_broadcast", "numpy"}}) |+ ov::pass::pattern::wrap_type<ov::op::v13::BitwiseXor>({term_m, ov::pass::pattern::any_input()},+ ov::pass::pattern::type_matches(ov::element::i64),+ {{"auto_broadcast", "numpy"}});+ auto unsqueeze_m = ov::pass::pattern::wrap_type<ov::op::v0::Unsqueeze, ov::op::v1::Reshape>(+ {xor_m, ov::pass::pattern::any_input()},+ ngram_hash_function_fusion::appends_unit_last_dim);+ auto vocab_m =+ ov::pass::pattern::wrap_type<ov::op::v0::Constant>(ngram_hash_function_fusion::is_last_axis_constant);+ auto mod_m = ov::pass::pattern::wrap_type<ov::op::v1::FloorMod>({unsqueeze_m, vocab_m},+ ov::pass::pattern::type_matches(ov::element::i64),+ {{"auto_broadcast", "numpy"}});+ auto offsets_m =+ ov::pass::pattern::wrap_type<ov::op::v0::Constant>(ngram_hash_function_fusion::is_last_axis_constant);+ auto add_m = ov::pass::pattern::wrap_type<ov::op::v1::Add>({mod_m, offsets_m},+ ov::pass::pattern::type_matches(ov::element::i64),+ {{"auto_broadcast", "numpy"}});++ ov::matcher_pass_callback callback = [OV_CAPTURE_CPY_AND_THIS](ov::pass::pattern::Matcher& m) {+ const auto& pm = m.get_pattern_value_map();+ const auto root = m.get_match_root();+ if (transformation_callback(root)) {+ return false;+ }+ const auto unsqueeze = pm.at(unsqueeze_m).get_node_shared_ptr();++ auto vocab_sizes = ngram_hash_function_fusion::constant_values(pm.at(vocab_m));+ auto offsets = ngram_hash_function_fusion::constant_values(pm.at(offsets_m));+ if (offsets.size() == 1) {+ offsets.resize(vocab_sizes.size(), offsets[0]);+ }+ if (vocab_sizes.empty() || offsets.size() != vocab_sizes.size() ||+ !ngram_hash_function_fusion::rows_fit_int32(vocab_sizes, offsets)) {+ return false;+ }++ // The deeper XOR levels are walked manually, so their multipliers are checked with the same shape predicate.+ const auto is_multiplier = [&](const ov::Output<ov::Node>& output) {+ return ov::as_type_ptr<ov::op::v0::Constant>(output.get_node_shared_ptr()) && scalar_multiplier(&m, output);+ };+ std::vector<ngram_hash_function_fusion::Term> terms;+ ov::NodeVector matched_nodes{root, pm.at(mod_m).get_node_shared_ptr(), unsqueeze};+ if (!ngram_hash_function_fusion::collect_terms(unsqueeze->input_value(0),+ is_multiplier,+ terms,+ matched_nodes) ||+ terms.size() < 2) {+ return false;+ }+ std::vector<int64_t> heads_per_order(terms.size() - 1, 0);+ heads_per_order.back() = static_cast<int64_t>(vocab_sizes.size());+ return ngram_hash_function_fusion::replace_with_hash(root,+ terms,+ heads_per_order,+ vocab_sizes,+ offsets,+ matched_nodes);+ };++ auto m = std::make_shared<ov::pass::pattern::Matcher>(add_m, matcher_name);+ register_matcher(m, callback);+}++ov::pass::NGramHashConcatFusion::NGramHashConcatFusion() {+ MATCHER_SCOPE(NGramHashConcatFusion);+ auto concat_m = ov::pass::pattern::wrap_type<ov::op::v0::Concat>([](const ov::Output<ov::Node>& output) {+ const auto concat = ov::as_type_ptr<ov::op::v0::Concat>(output.get_node_shared_ptr());+ const auto& inputs = concat->input_values();+ return output.get_element_type() == ov::element::i64 && inputs.size() > 1 &&+ ngram_hash_function_fusion::is_last_axis(concat->get_axis(), output.get_partial_shape().rank()) &&+ std::all_of(inputs.begin(), inputs.end(), [](const ov::Output<ov::Node>& input) {+ return ngram_hash_function_fusion::get_single_order_hash(input) != nullptr;+ });+ });++ ov::matcher_pass_callback callback = [OV_CAPTURE_CPY_AND_THIS](ov::pass::pattern::Matcher& m) {+ const auto root = m.get_match_root();+ if (transformation_callback(root)) {+ return false;+ }+ // Every order must extend the terms of the previous one; XOR is commutative, so only the sets matter.+ std::vector<ngram_hash_function_fusion::Term> terms;+ std::vector<int64_t> heads_per_order;+ std::vector<int64_t> vocab_sizes;+ std::vector<int64_t> offsets;+ ov::NodeVector matched_nodes{root};+ for (const auto& input : root->input_values()) {+ const auto hash = ngram_hash_function_fusion::get_single_order_hash(input);+ const auto order_terms = ngram_hash_function_fusion::get_terms(*hash);+ if (!order_terms || order_terms->size() <= terms.size()) {+ return false; // orders must be strictly increasing along the concatenated heads+ }+ for (const auto& term : terms) {+ if (std::find(order_terms->begin(), order_terms->end(), term) == order_terms->end()) {+ return false;+ }+ }+ for (const auto& term : *order_terms) {+ if (std::find(terms.begin(), terms.end(), term) == terms.end()) {+ terms.push_back(term);+ }+ }+ heads_per_order.resize(terms.size() - 1, 0);+ heads_per_order.back() = hash->get_heads_per_order().back();+ vocab_sizes.insert(vocab_sizes.end(),+ hash->get_head_vocab_sizes().begin(),+ hash->get_head_vocab_sizes().end());+ offsets.insert(offsets.end(), hash->get_head_offsets().begin(), hash->get_head_offsets().end());+ matched_nodes.insert(matched_nodes.end(),+ {input.get_node_shared_ptr(), hash, hash->get_input_node_shared_ptr(0)});+ }+ return ngram_hash_function_fusion::replace_with_hash(root,+ terms,+ heads_per_order,+ vocab_sizes,+ offsets,+ matched_nodes);+ };++ auto m = std::make_shared<ov::pass::pattern::Matcher>(concat_m, matcher_name);+ register_matcher(m, callback);+}diff --git a/src/common/transformations/tests/common_optimizations/ngram_hash_function_fusion_test.cpp b/src/common/transformations/tests/common_optimizations/ngram_hash_function_fusion_test.cppnew file mode 100644index 00000000000..345637b738a--- /dev/null+++ b/src/common/transformations/tests/common_optimizations/ngram_hash_function_fusion_test.cpp@@ -0,0 +1,663 @@+// Copyright (C) 2018-2026 Intel Corporation+// SPDX-License-Identifier: Apache-2.0+//++#include "transformations/common_optimizations/ngram_hash_function_fusion.hpp"++#include <gtest/gtest.h>++#include <algorithm>+#include <cstdint>+#include <limits>+#include <memory>+#include <string>+#include <vector>++#include "common_test_utils/ov_test_utils.hpp"+#include "openvino/core/graph_util.hpp"+#include "openvino/core/model.hpp"+#include "openvino/op/add.hpp"+#include "openvino/op/bitwise_xor.hpp"+#include "openvino/op/concat.hpp"+#include "openvino/op/constant.hpp"+#include "openvino/op/convert.hpp"+#include "openvino/op/floor_mod.hpp"+#include "openvino/op/gather.hpp"+#include "openvino/op/multiply.hpp"+#include "openvino/op/ngram_hash_function.hpp"+#include "openvino/op/parameter.hpp"+#include "openvino/op/reshape.hpp"+#include "openvino/op/shape_of.hpp"+#include "openvino/op/unsqueeze.hpp"+#include "openvino/pass/manager.hpp"++using namespace ov;+using namespace ov::op;++namespace {++const std::vector<int64_t> kQwenMultipliers{23703573157769, 20109073645365, 8052911324071, 3000000019};+const std::vector<int64_t> kWrapMultipliers{0x3BF58476D1CE4E5B,+ static_cast<int64_t>(0x9E3779B97F4A7C15ULL),+ 1234567891011,+ static_cast<int64_t>(0xD6E8FEB86659FD93ULL)};++struct HashGraphConfig {+ std::string name;+ std::vector<int64_t> multipliers; // multipliers[k] for the token k steps back+ std::vector<int64_t> heads_per_order; // orders 2 .. multipliers.size(), 0 = order not emitted+ PartialShape token_shape;+ bool share_mix = true; // reuse the Xor of the previous order (HF) or recompute every order+};++struct HashTables {+ std::vector<int64_t> vocab_sizes;+ std::vector<int64_t> offsets;+};++HashTables make_tables(const std::vector<int64_t>& heads_per_order, int64_t base_vocab = 20000003) {+ HashTables t;+ int64_t offset = 0;+ for (const auto heads : heads_per_order) {+ for (int64_t e = 0; e < heads; ++e) {+ const int64_t vocab = base_vocab + static_cast<int64_t>(t.vocab_sizes.size()) * 20;+ t.vocab_sizes.push_back(vocab);+ t.offsets.push_back(offset);+ offset += vocab;+ }+ }+ return t;+}++ParameterVector make_tokens(const HashGraphConfig& c, element::Type type = element::i64) {+ ParameterVector tokens;+ for (size_t k = 0; k < c.multipliers.size(); ++k) {+ tokens.push_back(std::make_shared<v0::Parameter>(type, c.token_shape));+ tokens.back()->set_friendly_name("token_back_" + std::to_string(k));+ }+ return tokens;+}++// The traced Qwen4ExpTextNGramEmbedding / Engram hash: per order an XOR chain, FloorMod by the head vocab sizes,+// offsets, and a Concat of all orders on the last axis.+std::shared_ptr<Model> make_hash_model(const HashGraphConfig& c,+ const HashTables& t,+ element::Type type = element::i64,+ int64_t unsqueeze_axis = -1,+ bool reverse_concat = false) {+ const auto tokens = make_tokens(c, type);+ auto term = [&](size_t k) {+ return std::make_shared<v1::Multiply>(tokens[k], v0::Constant::create(type, Shape{}, {c.multipliers[k]}));+ };+ OutputVector blocks;+ Output<Node> mix = term(0);+ size_t h = 0;+ for (size_t k = 1; k < c.multipliers.size(); ++k) {+ if (c.share_mix) {+ mix = std::make_shared<v13::BitwiseXor>(mix, term(k));+ } else {+ // Recompute from scratch, newest term first.+ mix = term(k);+ for (size_t j = 0; j < k; ++j) {+ mix = std::make_shared<v13::BitwiseXor>(term(j), mix);+ }+ }+ const auto heads = static_cast<size_t>(c.heads_per_order[k - 1]);+ if (heads == 0) {+ continue;+ }+ const std::vector<int64_t> vocab(t.vocab_sizes.begin() + h, t.vocab_sizes.begin() + h + heads);+ const std::vector<int64_t> offs(t.offsets.begin() + h, t.offsets.begin() + h + heads);+ h += heads;+ auto unsq = std::make_shared<v0::Unsqueeze>(mix, v0::Constant::create(element::i64, Shape{}, {unsqueeze_axis}));+ // Like head_vocab_sizes.view(1, 1, -1): broadcast along the last axis only.+ Shape vocab_shape(c.token_shape.size() + 1, 1);+ vocab_shape.back() = heads;+ auto mod = std::make_shared<v1::FloorMod>(unsq, v0::Constant::create(type, vocab_shape, vocab));+ blocks.push_back(std::make_shared<v1::Add>(mod, v0::Constant::create(type, Shape{heads}, offs)));+ }+ if (reverse_concat) {+ std::reverse(blocks.begin(), blocks.end());+ }+ Output<Node> out = blocks.size() == 1 ? blocks[0] : std::make_shared<v0::Concat>(blocks, -1)->output(0);+ return std::make_shared<Model>(OutputVector{out}, tokens);+}++// The expected rewrite: Convert(NGramHashFunction(Concat(Unsqueeze(x[n-1]), ..., Unsqueeze(x[0])))).+Output<Node> make_fused_hash(const OutputVector& tokens,+ const std::vector<int64_t>& multipliers,+ const std::vector<int64_t>& heads_per_order,+ const std::vector<int64_t>& vocab_sizes,+ const std::vector<int64_t>& offsets) {+ const auto axis = v0::Constant::create(element::i64, Shape{1}, {-1});+ OutputVector window;+ for (auto it = tokens.rbegin(); it != tokens.rend(); ++it) {+ window.push_back(std::make_shared<v0::Unsqueeze>(*it, axis));+ }+ const auto hash = std::make_shared<ov::op::internal::NGramHashFunction>(std::make_shared<v0::Concat>(window, -1),+ heads_per_order,+ multipliers,+ vocab_sizes,+ offsets);+ return std::make_shared<v0::Convert>(hash, element::i64);+}++std::shared_ptr<Model> make_fused_model(const HashGraphConfig& c, const HashTables& t) {+ const auto tokens = make_tokens(c);+ const auto out = make_fused_hash(OutputVector(tokens.begin(), tokens.end()),+ c.multipliers,+ c.heads_per_order,+ t.vocab_sizes,+ t.offsets);+ return std::make_shared<Model>(OutputVector{out}, tokens);+}++// A single-order hash as produced by NGramHashBlockFusion: heads only for the last order.+Output<Node> make_fused_order(const OutputVector& tokens,+ const std::vector<int64_t>& multipliers,+ const std::vector<int64_t>& vocab_sizes,+ const std::vector<int64_t>& offsets) {+ std::vector<int64_t> heads_per_order(tokens.size() - 1, 0);+ heads_per_order.back() = static_cast<int64_t>(vocab_sizes.size());+ return make_fused_hash(tokens, multipliers, heads_per_order, vocab_sizes, offsets);+}++std::vector<int64_t> head_range(const std::vector<int64_t>& values, size_t begin, size_t end) {+ return {values.begin() + begin, values.begin() + end};+}++// Compares both models on inputs that wrap the 64-bit products and produce negative mixes.+void expect_same_outputs(const std::shared_ptr<Model>& actual, const std::shared_ptr<Model>& expected) {+ ov::TensorVector inputs;+ for (const auto& parameter : actual->get_parameters()) {+ Shape shape;+ for (const auto& dimension : parameter->get_partial_shape()) {+ shape.push_back(dimension.is_static() ? dimension.get_length() : 2);+ }+ Tensor tensor(element::i64, shape);+ const auto values = tensor.data<int64_t>();+ for (size_t i = 0; i < tensor.get_size(); ++i) {+ values[i] = i % 2 ? std::numeric_limits<int64_t>::min() : 3000000000LL + static_cast<int64_t>(i);+ }+ inputs.push_back(tensor);+ }+ const auto lhs = ov::test::utils::infer_on_template(actual->clone(), inputs);+ const auto rhs = ov::test::utils::infer_on_template(expected->clone(), inputs);+ ASSERT_EQ(lhs.size(), rhs.size());+ for (size_t i = 0; i < lhs.size(); ++i) {+ ASSERT_EQ(lhs[i].get_shape(), rhs[i].get_shape());+ ASSERT_EQ(lhs[i].get_element_type(), element::i64);+ EXPECT_EQ(std::vector<int64_t>(lhs[i].data<int64_t>(), lhs[i].data<int64_t>() + lhs[i].get_size()),+ std::vector<int64_t>(rhs[i].data<int64_t>(), rhs[i].data<int64_t>() + rhs[i].get_size()));+ }+}++// Replaces every Unsqueeze with Reshape(x, pattern).+void replace_unsqueeze_with_reshape(const std::shared_ptr<Model>& model,+ const std::vector<int64_t>& pattern,+ bool special_zero) {+ for (const auto& node : model->get_ordered_ops()) {+ if (const auto unsqueeze = ov::as_type_ptr<v0::Unsqueeze>(node)) {+ ov::replace_node(+ unsqueeze,+ std::make_shared<v1::Reshape>(unsqueeze->input_value(0),+ v0::Constant::create(element::i64, Shape{pattern.size()}, pattern),+ special_zero));+ }+ }+ model->validate_nodes_and_infer_types();+}++const std::vector<HashGraphConfig> kPositiveCases{+ {"Qwen3_8FlashNext_Bigram", {kQwenMultipliers[0], kQwenMultipliers[1]}, {8}, {-1, -1}},+ {"Qwen3_8FlashNext_Trigram", {kQwenMultipliers.begin(), kQwenMultipliers.begin() + 3}, {8, 8}, {-1, -1}},+ {"Qwen3_8FlashNext_Trigram_ContinuousBatching",+ {kQwenMultipliers.begin(), kQwenMultipliers.begin() + 3},+ {8, 8},+ {-1}},+ {"DeepSeekV4_1Flash_Bigram", {kWrapMultipliers[0], kWrapMultipliers[1]}, {4}, {-1}},+ {"DeepSeekV4_1Flash_Trigram", {kWrapMultipliers.begin(), kWrapMultipliers.begin() + 3}, {4, 4}, {-1}},+ {"DeepSeekV4_1Flash_Trigram_RecomputedMix",+ {kWrapMultipliers.begin(), kWrapMultipliers.begin() + 3},+ {4, 4},+ {-1},+ false},+ {"Fourgram_PerOrderHeads", kWrapMultipliers, {2, 3, 1}, {-1, 7}},+ {"Fourgram_SkippedTrigram", kQwenMultipliers, {2, 0, 3}, {-1}},+};++const HashGraphConfig kBigram{"Bigram", {11, 13}, {2}, {-1, -1}};+const HashGraphConfig kTrigram{"Trigram", {kWrapMultipliers.begin(), kWrapMultipliers.begin() + 3}, {4, 4}, {-1, -1}};++} // namespace++class NGramHashFunctionFusionTests : public TransformationTestsF {+public:+ NGramHashFunctionFusionTests() {+ comparator.enable(FunctionsComparator::CONST_VALUES);+ comparator.enable(FunctionsComparator::ATTRIBUTES);+ }++protected:+ void SetUp() override {+ TransformationTestsF::SetUp();+ manager.register_pass<ov::pass::NGramHashFunctionFusion>();+ }+};++class NGramHashFunctionFusionParamTests : public NGramHashFunctionFusionTests,+ public testing::WithParamInterface<HashGraphConfig> {+public:+ static std::string get_test_case_name(const testing::TestParamInfo<HashGraphConfig>& info) {+ return info.param.name;+ }+};++TEST_P(NGramHashFunctionFusionParamTests, FusesAllOrdersIntoOneOp) {+ const auto& c = GetParam();+ const auto t = make_tables(c.heads_per_order);+ model = make_hash_model(c, t);+ model_ref = make_fused_model(c, t);+ expect_same_outputs(model, model_ref);+}++INSTANTIATE_TEST_SUITE_P(TransformationTests,+ NGramHashFunctionFusionParamTests,+ testing::ValuesIn(kPositiveCases),+ NGramHashFunctionFusionParamTests::get_test_case_name);++TEST_F(NGramHashFunctionFusionTests, DoesNotFuseI32) {+ const HashGraphConfig i32_trigram{"I32Trigram", {1000003, 999983, 7}, {4, 4}, {-1, -1}};+ model = make_hash_model(i32_trigram, make_tables(i32_trigram.heads_per_order, 1000003), element::i32);+}++TEST_F(NGramHashFunctionFusionTests, DoesNotFuseConcatWhenRowsOverflowInt32) {+ // Only the bigram block, whose rows fit int32, becomes an op; the trigram block and the Concat stay.+ auto t = make_tables(kTrigram.heads_per_order);+ t.offsets.back() = std::numeric_limits<int32_t>::max() - t.vocab_sizes.back() + 2;+ model = make_hash_model(kTrigram, t);+ {+ const auto tokens = make_tokens(kTrigram);+ const auto& m = kTrigram.multipliers;+ auto term = [&](size_t k) {+ return std::make_shared<v1::Multiply>(tokens[k], v0::Constant::create(element::i64, Shape{}, {m[k]}));+ };+ const auto bigram = make_fused_order({tokens[0], tokens[1]},+ head_range(m, 0, 2),+ head_range(t.vocab_sizes, 0, 4),+ head_range(t.offsets, 0, 4));+ const auto mix =+ std::make_shared<v13::BitwiseXor>(std::make_shared<v13::BitwiseXor>(term(0), term(1)), term(2));+ const auto unsq = std::make_shared<v0::Unsqueeze>(mix, v0::Constant::create(element::i64, Shape{}, {-1}));+ const auto mod = std::make_shared<v1::FloorMod>(+ unsq,+ v0::Constant::create(element::i64, Shape{1, 1, 4}, head_range(t.vocab_sizes, 4, 8)));+ const auto trigram =+ std::make_shared<v1::Add>(mod, v0::Constant::create(element::i64, Shape{4}, head_range(t.offsets, 4, 8)));+ model_ref =+ std::make_shared<Model>(OutputVector{std::make_shared<v0::Concat>(OutputVector{bigram, trigram}, -1)},+ tokens);+ }+}++TEST_F(NGramHashFunctionFusionTests, DoesNotFuseUnsqueezeOnOtherAxis) {+ model = make_hash_model(kTrigram, make_tables(kTrigram.heads_per_order), element::i64, 0);+}++TEST_F(NGramHashFunctionFusionTests, FusesEveryOrderOnItsOwnWhenConcatOrderIsDescending) {+ // Heads must be grouped by ascending order to fit one op; otherwise every block is fused separately.+ const auto t = make_tables(kTrigram.heads_per_order);+ model = make_hash_model(kTrigram, t, element::i64, -1, true);+ {+ const auto tokens = make_tokens(kTrigram);+ const auto& m = kTrigram.multipliers;+ const auto trigram = make_fused_order({tokens[0], tokens[1], tokens[2]},+ m,+ head_range(t.vocab_sizes, 4, 8),+ head_range(t.offsets, 4, 8));+ const auto bigram = make_fused_order({tokens[0], tokens[1]},+ head_range(m, 0, 2),+ head_range(t.vocab_sizes, 0, 4),+ head_range(t.offsets, 0, 4));+ model_ref =+ std::make_shared<Model>(OutputVector{std::make_shared<v0::Concat>(OutputVector{trigram, bigram}, -1)},+ tokens);+ }+}++TEST_F(NGramHashFunctionFusionTests, DoesNotFuseConcatWhenHigherOrderDoesNotExtendLowerOrder) {+ // The trigram uses a different second token than the bigram: not one n-gram window, so the blocks are fused+ // on their own.+ const auto& m = kTrigram.multipliers;+ {+ auto tokens = make_tokens(kTrigram);+ auto extra = std::make_shared<v0::Parameter>(element::i64, kTrigram.token_shape);+ tokens.push_back(extra);+ auto mul = [](const Output<Node>& x, int64_t multiplier) {+ return std::make_shared<v1::Multiply>(x, v0::Constant::create(element::i64, Shape{}, {multiplier}));+ };+ auto block = [](const Output<Node>& mix, int64_t vocab, int64_t offset) {+ auto unsq = std::make_shared<v0::Unsqueeze>(mix, v0::Constant::create(element::i64, Shape{}, {-1}));+ auto mod = std::make_shared<v1::FloorMod>(unsq, v0::Constant::create(element::i64, Shape{1}, {vocab}));+ return std::make_shared<v1::Add>(mod, v0::Constant::create(element::i64, Shape{1}, {offset}));+ };+ auto bigram = std::make_shared<v13::BitwiseXor>(mul(tokens[0], m[0]), mul(tokens[1], m[1]));+ auto trigram =+ std::make_shared<v13::BitwiseXor>(std::make_shared<v13::BitwiseXor>(mul(tokens[0], m[0]), mul(extra, m[1])),+ mul(tokens[2], m[2]));+ auto concat =+ std::make_shared<v0::Concat>(OutputVector{block(bigram, 1000003, 0), block(trigram, 1000033, 1000003)}, -1);+ model = std::make_shared<Model>(OutputVector{concat}, tokens);+ }+ {+ auto tokens = make_tokens(kTrigram);+ auto extra = std::make_shared<v0::Parameter>(element::i64, kTrigram.token_shape);+ tokens.push_back(extra);+ const auto bigram = make_fused_order({tokens[0], tokens[1]}, head_range(m, 0, 2), {1000003}, {0});+ const auto trigram = make_fused_order({tokens[0], extra, tokens[2]}, m, {1000033}, {1000003});+ model_ref =+ std::make_shared<Model>(OutputVector{std::make_shared<v0::Concat>(OutputVector{bigram, trigram}, -1)},+ tokens);+ }+}++TEST_F(NGramHashFunctionFusionTests, DoesNotTouchUnrelatedI64AddAndConcat) {+ // Generic i64 Add / FloorMod + Add / Concat without the hashed XOR mix must not match.+ auto x = std::make_shared<v0::Parameter>(element::i64, PartialShape{-1, -1});+ auto y = std::make_shared<v0::Parameter>(element::i64, PartialShape{-1, -1});+ auto add = std::make_shared<v1::Add>(x, y);+ auto unsq = std::make_shared<v0::Unsqueeze>(add, v0::Constant::create(element::i64, Shape{}, {-1}));+ auto mod = std::make_shared<v1::FloorMod>(unsq, v0::Constant::create(element::i64, Shape{4}, {7, 11, 13, 17}));+ auto offset = std::make_shared<v1::Add>(mod, v0::Constant::create(element::i64, Shape{4}, {0, 7, 18, 31}));+ // A single Multiply term instead of an XOR mix.+ auto mul = std::make_shared<v1::Multiply>(x, v0::Constant::create(element::i64, Shape{}, {kWrapMultipliers[0]}));+ auto unsq_mul = std::make_shared<v0::Unsqueeze>(mul, v0::Constant::create(element::i64, Shape{}, {-1}));+ auto mod_mul = std::make_shared<v1::FloorMod>(unsq_mul, v0::Constant::create(element::i64, Shape{1}, {7}));+ auto offset_mul = std::make_shared<v1::Add>(mod_mul, v0::Constant::create(element::i64, Shape{1}, {0}));+ auto concat = std::make_shared<v0::Concat>(OutputVector{offset, offset_mul}, -1);+ model = std::make_shared<Model>(OutputVector{concat}, ParameterVector{x, y});+}++TEST_F(NGramHashFunctionFusionTests, DoesNotFuseXorWithNonConstantMultiplier) {+ const auto tokens = make_tokens(kTrigram);+ auto term0 = std::make_shared<v1::Multiply>(tokens[0], tokens[1]);+ auto term1 =+ std::make_shared<v1::Multiply>(tokens[1], v0::Constant::create(element::i64, Shape{}, {kWrapMultipliers[1]}));+ auto mix = std::make_shared<v13::BitwiseXor>(term0, term1);+ auto unsq = std::make_shared<v0::Unsqueeze>(mix, v0::Constant::create(element::i64, Shape{}, {-1}));+ auto mod = std::make_shared<v1::FloorMod>(unsq, v0::Constant::create(element::i64, Shape{1}, {1000003}));+ auto add = std::make_shared<v1::Add>(mod, v0::Constant::create(element::i64, Shape{1}, {0}));+ model = std::make_shared<Model>(OutputVector{add}, tokens);+}++TEST_F(NGramHashFunctionFusionTests, DoesNotDiscardUnprovenReshape) {+ model = make_hash_model(kBigram, make_tables(kBigram.heads_per_order));+ replace_unsqueeze_with_reshape(model, {-1, 2, 1}, false);+}++TEST_F(NGramHashFunctionFusionTests, DoesNotFuseInferredReshapeWithZeroInputDimension) {+ // Reshape([-1, 0, 1]) maps a [2, 0] input to [1, 0, 1], so removing it would change the output batch dimension.+ const HashGraphConfig config{"EmptyTokens", {11, 13}, {2}, {2, 0}};+ model = make_hash_model(config, make_tables(config.heads_per_order));+ replace_unsqueeze_with_reshape(model, {-1, 0, 1}, false);+ EXPECT_EQ(model->output(0).get_partial_shape(), PartialShape({1, 0, 2}));+}++TEST_F(NGramHashFunctionFusionTests, FusesProvenStaticReshapeAppend) {+ const HashGraphConfig config{"Reshape", {11, 13}, {2}, {2, 3}};+ const auto t = make_tables(config.heads_per_order);+ model = make_hash_model(config, t);+ replace_unsqueeze_with_reshape(model, {2, 3, 1}, false);+ model_ref = make_fused_model(config, t);+}++TEST_F(NGramHashFunctionFusionTests, FusesProvenSpecialZeroReshapeAppend) {+ const auto t = make_tables(kBigram.heads_per_order);+ model = make_hash_model(kBigram, t);+ replace_unsqueeze_with_reshape(model, {0, 0, 1}, true);+ model_ref = make_fused_model(kBigram, t);+}++TEST_F(NGramHashFunctionFusionTests, FusesSingleInferredPrefixDimension) {+ const HashGraphConfig config{"Reshape", {11, 13}, {2}, {-1}};+ const auto t = make_tables(config.heads_per_order);+ model = make_hash_model(config, t);+ replace_unsqueeze_with_reshape(model, {-1, 1}, false);+ model_ref = make_fused_model(config, t);+}++TEST_F(NGramHashFunctionFusionTests, FusesReshapeWithSingleDynamicDimension) {+ // NopElimination turns an Unsqueeze with one dynamic dimension into this Reshape.+ const HashGraphConfig config{"Reshape", {11, 13}, {2}, {-1, 3}};+ const auto t = make_tables(config.heads_per_order);+ model = make_hash_model(config, t);+ replace_unsqueeze_with_reshape(model, {-1, 3, 1}, false);+ model_ref = make_fused_model(config, t);+}++TEST_F(NGramHashFunctionFusionTests, DoesNotFuseReshapeWithDynamicAndZeroDimensions) {+ // The shapes match ([?, 0] -> [?, 0, 1]), but Reshape([-1, 0, 1]) maps a [2, 0] input to [0, 0, 1].+ const HashGraphConfig config{"EmptyTokens", {11, 13}, {2}, {-1, 0}};+ model = make_hash_model(config, make_tables(config.heads_per_order));+ replace_unsqueeze_with_reshape(model, {-1, 0, 1}, false);+ for (const auto& node : model->get_ordered_ops()) {+ if (ov::is_type<v1::Reshape>(node)) {+ EXPECT_EQ(node->get_output_partial_shape(0), PartialShape({-1, 0, 1}));+ }+ }+}++TEST_F(NGramHashFunctionFusionTests, DoesNotFuseReshapeThatSwapsDynamicDimensions) {+ // The shapes match ([?, ?] -> [?, ?, 1]), but the target shape swaps the two input dimensions.+ model = make_hash_model(kBigram, make_tables(kBigram.heads_per_order));+ for (const auto& node : model->get_ordered_ops()) {+ if (const auto unsqueeze = ov::as_type_ptr<v0::Unsqueeze>(node)) {+ const auto x = unsqueeze->input_value(0);+ const auto swapped = std::make_shared<v8::Gather>(std::make_shared<v3::ShapeOf>(x),+ v0::Constant::create(element::i64, Shape{2}, {1, 0}),+ v0::Constant::create(element::i64, Shape{}, {0}));+ const auto target =+ std::make_shared<v0::Concat>(OutputVector{swapped, v0::Constant::create(element::i64, Shape{1}, {1})},+ 0);+ const auto reshape = std::make_shared<v1::Reshape>(x, target, false);+ EXPECT_EQ(reshape->get_output_partial_shape(0), PartialShape({-1, -1, 1}));+ ov::replace_node(unsqueeze, reshape);+ }+ }+ model->validate_nodes_and_infer_types();+}++// A single trigram block whose top XOR has the newest term on the given side; collect order follows the XOR inputs.+struct TrigramBlock {+ std::shared_ptr<Model> model;+ std::shared_ptr<Model> fused;+};++TrigramBlock make_trigram_block(const Shape& multiplier_shape,+ bool term_first,+ const PartialShape& token_shape = {-1, -1}) {+ const HashGraphConfig c{"TrigramBlock", {11, 13, 17}, {0, 4}, token_shape};+ const auto t = make_tables(c.heads_per_order);+ const auto tokens = make_tokens(c);+ auto term = [&](size_t k) {+ return std::make_shared<v1::Multiply>(tokens[k],+ v0::Constant::create(element::i64, multiplier_shape, {c.multipliers[k]}));+ };+ const auto inner = std::make_shared<v13::BitwiseXor>(term(0), term(1));+ const auto mix = term_first ? std::make_shared<v13::BitwiseXor>(term(2), inner)+ : std::make_shared<v13::BitwiseXor>(inner, term(2));+ const auto unsq = std::make_shared<v0::Unsqueeze>(mix, v0::Constant::create(element::i64, Shape{}, {-1}));+ Shape vocab_shape(token_shape.size() + 1, 1);+ vocab_shape.back() = t.vocab_sizes.size();+ const auto mod =+ std::make_shared<v1::FloorMod>(unsq, v0::Constant::create(element::i64, vocab_shape, t.vocab_sizes));+ const auto add =+ std::make_shared<v1::Add>(mod, v0::Constant::create(element::i64, Shape{t.offsets.size()}, t.offsets));++ const std::vector<size_t> order = term_first ? std::vector<size_t>{2, 0, 1} : std::vector<size_t>{0, 1, 2};+ const auto ref_tokens = make_tokens(c);+ OutputVector fused_tokens;+ std::vector<int64_t> fused_multipliers;+ for (const auto k : order) {+ fused_tokens.push_back(ref_tokens[k]);+ fused_multipliers.push_back(c.multipliers[k]);+ }+ const auto fused = make_fused_order(fused_tokens, fused_multipliers, t.vocab_sizes, t.offsets);+ return {std::make_shared<Model>(OutputVector{add}, tokens),+ std::make_shared<Model>(OutputVector{fused}, ref_tokens)};+}++class NGramHashFunctionFusionXorOrderTests : public NGramHashFunctionFusionTests,+ public testing::WithParamInterface<bool> {};++// BitwiseXor is not commutative for the pattern matcher, so the term must be found on either XOR input.+TEST_P(NGramHashFunctionFusionXorOrderTests, FusesTermOnEitherXorInput) {+ auto block = make_trigram_block(Shape{}, GetParam());+ model = block.model;+ model_ref = block.fused;+ expect_same_outputs(model, model_ref);+}++INSTANTIATE_TEST_SUITE_P(TransformationTests,+ NGramHashFunctionFusionXorOrderTests,+ testing::Bool(),+ [](const testing::TestParamInfo<bool>& info) {+ return info.param ? std::string("TermFirst") : std::string("TermLast");+ });++class NGramHashFunctionFusionMultiplierShapeTests : public NGramHashFunctionFusionTests,+ public testing::WithParamInterface<Shape> {};++TEST_P(NGramHashFunctionFusionMultiplierShapeTests, FusesScalarLikeMultipliers) {+ auto block = make_trigram_block(GetParam(), false);+ model = block.model;+ model_ref = block.fused;+ expect_same_outputs(model, model_ref);+}++INSTANTIATE_TEST_SUITE_P(TransformationTests,+ NGramHashFunctionFusionMultiplierShapeTests,+ testing::Values(Shape{}, Shape{1}, Shape{1, 1}),+ [](const testing::TestParamInfo<Shape>& info) {+ return "Rank" + std::to_string(info.param.size());+ });++TEST_F(NGramHashFunctionFusionTests, DoesNotFuseOtherMultiplierShape) {+ model = make_trigram_block(Shape{1, 1, 1}, false, {-1, -1, -1}).model;+}++// A [1, 1] multiplier broadcasts rank-1 tokens to rank 2, which packing the tokens would not.+TEST_F(NGramHashFunctionFusionTests, DoesNotFuseMultiplierThatRaisesDynamicTokenRank) {+ model = make_trigram_block(Shape{1, 1}, false, {-1}).model;+}++TEST_F(NGramHashFunctionFusionTests, DoesNotFuseMultiplierThatRaisesStaticTokenRank) {+ model = make_trigram_block(Shape{1, 1}, true, {5}).model;+}++class NGramHashFunctionFusionNonConstantMultiplierTests : public NGramHashFunctionFusionTests,+ public testing::WithParamInterface<size_t> {};++// A scalar-shaped multiplier whose value isn't known when fusing, either on the top term matched by the pattern (2)+// or on a term found by the manual XOR walk (0).+TEST_P(NGramHashFunctionFusionNonConstantMultiplierTests, DoesNotFuseScalarParameterMultiplier) {+ const auto tokens = make_tokens(kTrigram);+ const auto multiplier = std::make_shared<v0::Parameter>(element::i64, PartialShape{});+ auto term = [&](size_t k) {+ const Output<Node> factor =+ k == GetParam() ? Output<Node>(multiplier)+ : v0::Constant::create(element::i64, Shape{}, {kTrigram.multipliers[k]})->output(0);+ return std::make_shared<v1::Multiply>(tokens[k], factor);+ };+ const auto mix = std::make_shared<v13::BitwiseXor>(std::make_shared<v13::BitwiseXor>(term(0), term(1)), term(2));+ const auto unsq = std::make_shared<v0::Unsqueeze>(mix, v0::Constant::create(element::i64, Shape{}, {-1}));+ const auto mod = std::make_shared<v1::FloorMod>(unsq, v0::Constant::create(element::i64, Shape{1}, {1000003}));+ const auto add = std::make_shared<v1::Add>(mod, v0::Constant::create(element::i64, Shape{1}, {0}));+ auto params = tokens;+ params.push_back(multiplier);+ model = std::make_shared<Model>(OutputVector{add}, params);+}++INSTANTIATE_TEST_SUITE_P(TransformationTests,+ NGramHashFunctionFusionNonConstantMultiplierTests,+ testing::Values(size_t{2}, size_t{0}),+ [](const testing::TestParamInfo<size_t>& info) {+ return info.param == 2 ? std::string("MatchedTerm") : std::string("WalkedTerm");+ });++class NGramHashFunctionFusionNonNumpyTests : public NGramHashFunctionFusionTests,+ public testing::WithParamInterface<std::string> {};++TEST_P(NGramHashFunctionFusionNonNumpyTests, DoesNotFuseNonNumpyHeadBroadcasts) {+ const HashGraphConfig config{"Broadcast", {11, 13}, {2}, {2}};+ model = make_hash_model(config, make_tables(config.heads_per_order));+ for (const auto& node : model->get_ordered_ops()) {+ if (node->get_type_name() == GetParam()) {+ const auto arithmetic = ov::as_type_ptr<ov::op::util::BinaryElementwiseArithmetic>(node);+ const auto constant = ov::as_type_ptr<v0::Constant>(arithmetic->get_input_node_shared_ptr(1));+ arithmetic->input(1).replace_source_output(+ v0::Constant::create(element::i64, Shape{2}, constant->cast_vector<int64_t>()));+ arithmetic->set_autob(ov::op::AutoBroadcastSpec(ov::op::AutoBroadcastType::PDPD, 0));+ }+ }+ model->validate_nodes_and_infer_types();+}++INSTANTIATE_TEST_SUITE_P(TransformationTests,+ NGramHashFunctionFusionNonNumpyTests,+ testing::Values("FloorMod", "Add"),+ [](const testing::TestParamInfo<std::string>& info) {+ return info.param;+ });++TEST_F(NGramHashFunctionFusionTests, DoesNotFuseStaticallyBroadcastTokens) {+ const HashGraphConfig config{"Bigram", {11, 13}, {2}, {3}};+ model = make_hash_model(config, make_tables(config.heads_per_order));+ model->get_parameters()[0]->set_partial_shape({1});+ model->validate_nodes_and_infer_types();+}++TEST_F(NGramHashFunctionFusionTests, FusesInt32RowBoundary) {+ const HashGraphConfig config{"RowBoundary", {11, 13}, {1}, {2}};+ const HashTables t{{2147483648LL}, {0}};+ model = make_hash_model(config, t);+ model_ref = make_fused_model(config, t);+}++TEST_F(NGramHashFunctionFusionTests, DoesNotMergeExistingHashWithRepeatedTerm) {+ // x * 11 ^ x * 11 cancels out; merging it as a set of terms would change the result.+ const auto x = std::make_shared<v0::Parameter>(element::i64, PartialShape{-1, -1});+ const auto y = std::make_shared<v0::Parameter>(element::i64, PartialShape{-1, -1});+ model = std::make_shared<Model>(OutputVector{std::make_shared<v0::Concat>(+ OutputVector{make_fused_order({x, x}, {11, 11}, {1000003}, {0}),+ make_fused_order({x, y, y}, {11, 13, 17}, {1000033}, {1000003})},+ -1)},+ ParameterVector{x, y});+}++TEST_F(NGramHashFunctionFusionTests, CallbackSkipsBlockFusion) {+ model = make_hash_model(kTrigram, make_tables(kTrigram.heads_per_order));+ manager.get_pass_config()->set_callback<ov::pass::NGramHashBlockFusion>([](const std::shared_ptr<const Node>&) {+ return true;+ });+}++TEST_F(NGramHashFunctionFusionTests, CallbackSkipsConcatFusion) {+ const auto t = make_tables(kTrigram.heads_per_order);+ model = make_hash_model(kTrigram, t);+ manager.get_pass_config()->set_callback<ov::pass::NGramHashConcatFusion>([](const std::shared_ptr<const Node>&) {+ return true;+ });+ const auto tokens = make_tokens(kTrigram);+ const auto& m = kTrigram.multipliers;+ const auto bigram = make_fused_order({tokens[0], tokens[1]},+ head_range(m, 0, 2),+ head_range(t.vocab_sizes, 0, 4),+ head_range(t.offsets, 0, 4));+ const auto trigram = make_fused_order({tokens[0], tokens[1], tokens[2]},+ m,+ head_range(t.vocab_sizes, 4, 8),+ head_range(t.offsets, 4, 8));+ model_ref =+ std::make_shared<Model>(OutputVector{std::make_shared<v0::Concat>(OutputVector{bigram, trigram}, -1)}, tokens);+}diff --git a/src/common/transformations/tests/sources.cmake b/src/common/transformations/tests/sources.cmakeindex 88fc83610c2..bd9e0370cca 100644--- a/src/common/transformations/tests/sources.cmake+++ b/src/common/transformations/tests/sources.cmake@@ -97,6 +97,7 @@ set(COMMON_OPTIMIZATIONS_TESTS_SRCS${CMAKE_CURRENT_LIST_DIR}/common_optimizations/mvn_fusion_test.cpp${CMAKE_CURRENT_LIST_DIR}/common_optimizations/nearest_neighbor_upsampling_fusion_test.cpp${CMAKE_CURRENT_LIST_DIR}/common_optimizations/ngraph_fq_transpose_test.cpp+ ${CMAKE_CURRENT_LIST_DIR}/common_optimizations/ngram_hash_function_fusion_test.cpp${CMAKE_CURRENT_LIST_DIR}/common_optimizations/nonzero_horizontal_fusion_test.cpp${CMAKE_CURRENT_LIST_DIR}/common_optimizations/nop_elimination.cpp${CMAKE_CURRENT_LIST_DIR}/common_optimizations/normalize_l2_fusion_test.cppdiff --git a/src/core/dev_api/dev_headers.cmake b/src/core/dev_api/dev_headers.cmakeindex 65ff67416f6..abd1e685ec0 100644--- a/src/core/dev_api/dev_headers.cmake+++ b/src/core/dev_api/dev_headers.cmake@@ -24,6 +24,7 @@ set(DEV_HEADERS${CMAKE_CURRENT_LIST_DIR}/openvino/op/gated_delta_net.hpp${CMAKE_CURRENT_LIST_DIR}/openvino/op/group_query_attention.hpp${CMAKE_CURRENT_LIST_DIR}/openvino/op/moe.hpp+ ${CMAKE_CURRENT_LIST_DIR}/openvino/op/ngram_hash_function.hpp${CMAKE_CURRENT_LIST_DIR}/openvino/op/ops_decl.hpp${CMAKE_CURRENT_LIST_DIR}/openvino/op/pa_kv_reorder.hpp${CMAKE_CURRENT_LIST_DIR}/openvino/op/paged_attention.hppdiff --git a/src/core/dev_api/openvino/op/ngram_hash_function.hpp b/src/core/dev_api/openvino/op/ngram_hash_function.hppnew file mode 100644index 00000000000..b65b594400a--- /dev/null+++ b/src/core/dev_api/openvino/op/ngram_hash_function.hpp@@ -0,0 +1,85 @@+// Copyright (C) 2018-2026 Intel Corporation+// SPDX-License-Identifier: Apache-2.0+//++#pragma once++#include <cstdint>+#include <vector>++#include "openvino/op/op.hpp"++namespace ov {+namespace op {+namespace internal {+/// \note NGramHashFunction op class is under development and subject to change+///+/// \brief Hashes all n-grams (orders 2 .. ngram_size) that end at every token into row indices of a packed,+/// hashed n-gram embedding table, keeping the 64-bit integer arithmetic inside the operation.+///+/// For a token with window `w` (oldest first, `w[ngram_size - 1]` is the token itself) and `x[k] = w[ngram_size-1-k]`+/// (the token k steps back), the n-gram of order `o` is mixed as+/// mix_o = (x[0] * multipliers[0]) ^ ... ^ (x[o-1] * multipliers[o-1]) (wrapping 64-bit arithmetic)+/// and every head `h` of order `o` produces+/// row_ids[..., h] = floor_mod(mix_o, head_vocab_sizes[h]) + head_offsets[h]+/// Heads are grouped by order: first heads_per_order[0] heads of the bigram, then heads_per_order[1] heads of the+/// trigram, and so on.+///+/// Input 0: ngrams [..., ngram_size] of type i32 or i64. Output 0: row_ids [..., H] of type i32,+/// H = sum(heads_per_order).+/// The head count must fit both int64 shape dimensions and size_t. Every possible row+/// (head_offsets[h] + head_vocab_sizes[h] - 1) must fit int32; a modulus of 2^31 is valid with offset zero.+/// A dynamic input window dimension must equal ngram_size at execution.+/// \ingroup ov_ops_cpp_api+class OPENVINO_API NGramHashFunction : public ov::op::Op {+public:+ OPENVINO_OP("NGramHashFunction");++ NGramHashFunction() = default;+ /// \brief Constructs an NGramHashFunction operation.+ ///+ /// \param ngrams Windows of ngram_size token ids for every token, oldest first.+ /// \param heads_per_order Number of hashed heads of every order 2 .. ngram_size (ngram_size - 1 values).+ /// \param multipliers Hash multipliers of the token itself, the previous token, ... (ngram_size values,+ /// ngram_size >= 2). The largest n-gram order is ngram_size = multipliers.size().+ /// \param head_vocab_sizes Vocabulary size (modulus) of every head (H values).+ /// \param head_offsets First row of every head in the packed table (H values).+ NGramHashFunction(const Output<Node>& ngrams,+ std::vector<int64_t> heads_per_order,+ std::vector<int64_t> multipliers,+ std::vector<int64_t> head_vocab_sizes,+ std::vector<int64_t> head_offsets);++ bool visit_attributes(ov::AttributeVisitor& visitor) override;+ void validate_and_infer_types() override;+ std::shared_ptr<Node> clone_with_new_inputs(const ov::OutputVector& new_args) const override;++ /// \brief The largest n-gram order, equal to the number of multipliers.+ int64_t get_ngram_size() const {+ return static_cast<int64_t>(m_multipliers.size());+ }+ const std::vector<int64_t>& get_heads_per_order() const {+ return m_heads_per_order;+ }+ const std::vector<int64_t>& get_multipliers() const {+ return m_multipliers;+ }+ const std::vector<int64_t>& get_head_vocab_sizes() const {+ return m_head_vocab_sizes;+ }+ const std::vector<int64_t>& get_head_offsets() const {+ return m_head_offsets;+ }+ /// \brief Total number of hashed heads H = sum(heads_per_order).+ size_t get_num_heads() const;++private:+ std::vector<int64_t> m_heads_per_order;+ std::vector<int64_t> m_multipliers;+ std::vector<int64_t> m_head_vocab_sizes;+ std::vector<int64_t> m_head_offsets;+};++} // namespace internal+} // namespace op+} // namespace ovdiff --git a/src/core/reference/include/openvino/reference/ngram_hash_function.hpp b/src/core/reference/include/openvino/reference/ngram_hash_function.hppnew file mode 100644index 00000000000..5af860237ab--- /dev/null+++ b/src/core/reference/include/openvino/reference/ngram_hash_function.hpp@@ -0,0 +1,80 @@+// Copyright (C) 2018-2026 Intel Corporation+// SPDX-License-Identifier: Apache-2.0+//++#pragma once++#include <cstddef>+#include <cstdint>++namespace ov {+namespace reference {+/// \brief Computes NGramHashFunction rows for tokens [token_begin, token_end).+///+/// \param ngrams Windows [num_tokens, ngram_size], oldest first (the token itself last).+/// \param row_ids Output [num_tokens, num_heads].+/// \param heads_per_order ngram_size - 1 values, heads of the bigram, trigram, ...+/// \param multipliers ngram_size values, multipliers[k] applies to the token k steps back.+/// \param head_vocab_sizes num_heads positive moduli.+/// \param head_offsets num_heads offsets.+///+/// The multiply/xor wrap around modulo 2^64 (two's complement int64) and the modulo is a floor modulo (the sign of+/// the divisor), which matches the int64 Multiply/BitwiseXor/FloorMod graph and torch.remainder.+template <typename T>+void ngram_hash_function(const T* ngrams,+ int32_t* row_ids,+ size_t token_begin,+ size_t token_end,+ size_t ngram_size,+ const int64_t* heads_per_order,+ const int64_t* multipliers,+ const int64_t* head_vocab_sizes,+ const int64_t* head_offsets,+ size_t num_heads) {+ for (size_t t = token_begin; t < token_end; ++t) {+ const T* window = ngrams + t * ngram_size;+ int32_t* out = row_ids + t * num_heads;+ // The token itself (x[0]) is the last element of the window.+ uint64_t mix =+ static_cast<uint64_t>(static_cast<int64_t>(window[ngram_size - 1])) * static_cast<uint64_t>(multipliers[0]);+ size_t h = 0;+ for (size_t k = 1; k < ngram_size; ++k) {+ mix ^= static_cast<uint64_t>(static_cast<int64_t>(window[ngram_size - 1 - k])) *+ static_cast<uint64_t>(multipliers[k]);+ const auto value = static_cast<int64_t>(mix);+ for (int64_t e = 0; e < heads_per_order[k - 1]; ++e, ++h) {+ const int64_t vocab = head_vocab_sizes[h];+ int64_t r = value % vocab;+ if (r < 0) {+ r += vocab;+ }+ out[h] = static_cast<int32_t>(r + head_offsets[h]);+ }+ }+ }+}++/// \brief Computes NGramHashFunction rows for all num_tokens tokens.+template <typename T>+void ngram_hash_function(const T* ngrams,+ int32_t* row_ids,+ size_t num_tokens,+ size_t ngram_size,+ const int64_t* heads_per_order,+ const int64_t* multipliers,+ const int64_t* head_vocab_sizes,+ const int64_t* head_offsets,+ size_t num_heads) {+ ngram_hash_function(ngrams,+ row_ids,+ 0,+ num_tokens,+ ngram_size,+ heads_per_order,+ multipliers,+ head_vocab_sizes,+ head_offsets,+ num_heads);+}+} // namespace reference+} // namespace ovdiff --git a/src/core/reference/sources.cmake b/src/core/reference/sources.cmakeindex f489f3a685d..a0205d8ccf6 100644--- a/src/core/reference/sources.cmake+++ b/src/core/reference/sources.cmake@@ -178,6 +178,7 @@ set(REFERENCE_HEADERS${CMAKE_CURRENT_LIST_DIR}/include/openvino/reference/multiply.hpp${CMAKE_CURRENT_LIST_DIR}/include/openvino/reference/mvn.hpp${CMAKE_CURRENT_LIST_DIR}/include/openvino/reference/negate.hpp+ ${CMAKE_CURRENT_LIST_DIR}/include/openvino/reference/ngram_hash_function.hpp${CMAKE_CURRENT_LIST_DIR}/include/openvino/reference/nms_rotated.hpp${CMAKE_CURRENT_LIST_DIR}/include/openvino/reference/nms_rotated_util.hpp${CMAKE_CURRENT_LIST_DIR}/include/openvino/reference/non_max_suppression.hppdiff --git a/src/core/shape_inference/CMakeLists.txt b/src/core/shape_inference/CMakeLists.txtindex b907b879e37..9d16b0489ad 100644--- a/src/core/shape_inference/CMakeLists.txt+++ b/src/core/shape_inference/CMakeLists.txt@@ -93,6 +93,7 @@ target_sources(${TARGET_NAME}${SHAPE_INFER_INCLUDE_DIR}/max_pool_shape_inference.hpp${SHAPE_INFER_INCLUDE_DIR}/multiclass_nms_shape_inference.hpp${SHAPE_INFER_INCLUDE_DIR}/multinomial_shape_inference.hpp+ ${SHAPE_INFER_INCLUDE_DIR}/ngram_hash_function_shape_inference.hpp${SHAPE_INFER_INCLUDE_DIR}/nms_shape_inference.hpp${SHAPE_INFER_INCLUDE_DIR}/nv12_shape_inference.hpp${SHAPE_INFER_INCLUDE_DIR}/one_hot_shape_inference.hppdiff --git a/src/core/shape_inference/include/ngram_hash_function_shape_inference.hpp b/src/core/shape_inference/include/ngram_hash_function_shape_inference.hppnew file mode 100644index 00000000000..110f9d20bd8--- /dev/null+++ b/src/core/shape_inference/include/ngram_hash_function_shape_inference.hpp@@ -0,0 +1,44 @@+// Copyright (C) 2018-2026 Intel Corporation+// SPDX-License-Identifier: Apache-2.0+//++#pragma once++#include "openvino/op/ngram_hash_function.hpp"+#include "utils.hpp"++namespace ov {+namespace op {+namespace internal {+template <class TShape, class TRShape = result_shape_t<TShape>>+std::vector<TRShape> shape_infer(const NGramHashFunction* op, const std::vector<TShape>& input_shapes) {+ NODE_SHAPE_INFER_CHECK(op, input_shapes, input_shapes.size() == 1);++ const auto& ngrams_shape = input_shapes[0];+ const auto& ngrams_rank = ngrams_shape.rank();+ const auto num_heads = static_cast<typename TRShape::value_type::value_type>(op->get_num_heads());++ if (ngrams_rank.is_dynamic()) {+ return {TRShape(ngrams_shape)};+ }+ NODE_SHAPE_INFER_CHECK(op,+ input_shapes,+ ngrams_rank.get_length() >= 1,+ "The ngrams input must have rank >= 1. Got: ",+ ngrams_shape);+ const auto& last_dim = ngrams_shape[ngrams_rank.get_length() - 1];+ NODE_SHAPE_INFER_CHECK(op,+ input_shapes,+ last_dim.compatible(op->get_ngram_size()),+ "The last dimension of the ngrams input must be equal to ngram_size (",+ op->get_ngram_size(),+ "). Got: ",+ ngrams_shape);++ auto output_shape = TRShape(ngrams_shape);+ output_shape[output_shape.size() - 1] = num_heads;+ return {std::move(output_shape)};+}+} // namespace internal+} // namespace op+} // namespace ovdiff --git a/src/core/src/op/ngram_hash_function.cpp b/src/core/src/op/ngram_hash_function.cppnew file mode 100644index 00000000000..9bbe7aaa46f--- /dev/null+++ b/src/core/src/op/ngram_hash_function.cpp@@ -0,0 +1,112 @@+// Copyright (C) 2018-2026 Intel Corporation+// SPDX-License-Identifier: Apache-2.0+//++#include "openvino/op/ngram_hash_function.hpp"++#include <algorithm>+#include <limits>++#include "itt.hpp"+#include "ngram_hash_function_shape_inference.hpp"+#include "openvino/core/validation_util.hpp"++namespace ov {+namespace op {+namespace internal {++NGramHashFunction::NGramHashFunction(const Output<Node>& ngrams,+ std::vector<int64_t> heads_per_order,+ std::vector<int64_t> multipliers,+ std::vector<int64_t> head_vocab_sizes,+ std::vector<int64_t> head_offsets)+ : Op({ngrams}),+ m_heads_per_order(std::move(heads_per_order)),+ m_multipliers(std::move(multipliers)),+ m_head_vocab_sizes(std::move(head_vocab_sizes)),+ m_head_offsets(std::move(head_offsets)) {+ constructor_validate_and_infer_types();+}++bool NGramHashFunction::visit_attributes(ov::AttributeVisitor& visitor) {+ OV_OP_SCOPE(internal_NGramHashFunction_visit_attributes);+ visitor.on_attribute("heads_per_order", m_heads_per_order);+ visitor.on_attribute("multipliers", m_multipliers);+ visitor.on_attribute("head_vocab_sizes", m_head_vocab_sizes);+ visitor.on_attribute("head_offsets", m_head_offsets);+ return true;+}++size_t NGramHashFunction::get_num_heads() const {+ size_t heads = 0;+ constexpr auto max_heads =+ std::min<uint64_t>(std::numeric_limits<int64_t>::max(), std::numeric_limits<size_t>::max());+ for (const auto h : m_heads_per_order) {+ NODE_VALIDATION_CHECK(this, h >= 0, "heads_per_order values must be non-negative. Got: ", h);+ NODE_VALIDATION_CHECK(this,+ static_cast<uint64_t>(h) <= max_heads - heads,+ "sum(heads_per_order) must fit int64 and size_t.");+ heads += static_cast<size_t>(h);+ }+ return heads;+}++void NGramHashFunction::validate_and_infer_types() {+ OV_OP_SCOPE(internal_NGramHashFunction_validate_and_infer_types);++ NODE_VALIDATION_CHECK(this,+ m_multipliers.size() >= 2,+ "multipliers must have ngram_size >= 2 values. Got: ",+ m_multipliers.size());+ NODE_VALIDATION_CHECK(this,+ m_heads_per_order.size() == m_multipliers.size() - 1,+ "heads_per_order must have ngram_size - 1 (",+ m_multipliers.size() - 1,+ ") values. Got: ",+ m_heads_per_order.size());+ const auto num_heads = get_num_heads();+ NODE_VALIDATION_CHECK(this, num_heads > 0, "NGramHashFunction must have at least one head.");+ NODE_VALIDATION_CHECK(this,+ m_head_vocab_sizes.size() == num_heads && m_head_offsets.size() == num_heads,+ "head_vocab_sizes and head_offsets must have H = sum(heads_per_order) (",+ num_heads,+ ") values. Got: ",+ m_head_vocab_sizes.size(),+ " and ",+ m_head_offsets.size());+ constexpr auto int32_max = static_cast<int64_t>(std::numeric_limits<int32_t>::max());+ for (size_t h = 0; h < num_heads; ++h) {+ const auto vocab = m_head_vocab_sizes[h];+ const auto offset = m_head_offsets[h];+ NODE_VALIDATION_CHECK(this, vocab > 0, "head_vocab_sizes values must be positive. Got: ", vocab);+ NODE_VALIDATION_CHECK(this, offset >= 0, "head_offsets values must be non-negative. Got: ", offset);+ NODE_VALIDATION_CHECK(this,+ vocab - 1 <= int32_max && offset <= int32_max - (vocab - 1),+ "The rows of head ",+ h,+ " (head_offsets + head_vocab_sizes - 1) must fit int32.");+ }++ const auto& ngrams_type = get_input_element_type(0);+ NODE_VALIDATION_CHECK(this,+ ngrams_type.is_dynamic() || ngrams_type == element::i32 || ngrams_type == element::i64,+ "The element type of the ngrams input must be i32 or i64. Got: ",+ ngrams_type);++ const auto output_shapes = shape_infer(this, ov::util::get_node_input_partial_shapes(*this));+ set_output_type(0, element::i32, output_shapes[0]);+}++std::shared_ptr<Node> NGramHashFunction::clone_with_new_inputs(const ov::OutputVector& new_args) const {+ OV_OP_SCOPE(internal_NGramHashFunction_clone_with_new_inputs);+ check_new_args_count(this, new_args);+ return std::make_shared<NGramHashFunction>(new_args.at(0),+ m_heads_per_order,+ m_multipliers,+ m_head_vocab_sizes,+ m_head_offsets);+}++} // namespace internal+} // namespace op+} // namespace ovdiff --git a/src/core/src/sources.cmake b/src/core/src/sources.cmakeindex ed6837da0ee..d0642b41dc1 100644--- a/src/core/src/sources.cmake+++ b/src/core/src/sources.cmake@@ -176,6 +176,7 @@ set(LIBRARY_SRC${CMAKE_CURRENT_LIST_DIR}/op/multiply.cpp${CMAKE_CURRENT_LIST_DIR}/op/mvn.cpp${CMAKE_CURRENT_LIST_DIR}/op/negative.cpp+ ${CMAKE_CURRENT_LIST_DIR}/op/ngram_hash_function.cpp${CMAKE_CURRENT_LIST_DIR}/op/nms_rotated.cpp${CMAKE_CURRENT_LIST_DIR}/op/non_max_suppression.cpp${CMAKE_CURRENT_LIST_DIR}/op/non_zero.cppdiff --git a/src/core/tests/type_prop/ngram_hash_function.cpp b/src/core/tests/type_prop/ngram_hash_function.cppnew file mode 100644index 00000000000..4517ec61bde--- /dev/null+++ b/src/core/tests/type_prop/ngram_hash_function.cpp@@ -0,0 +1,161 @@+// Copyright (C) 2018-2026 Intel Corporation+// SPDX-License-Identifier: Apache-2.0+//++#include "openvino/op/ngram_hash_function.hpp"++#include <gtest/gtest.h>++#include <cstdint>+#include <limits>++#include "common_test_utils/test_assertions.hpp"+#include "common_test_utils/type_prop.hpp"+#include "openvino/op/parameter.hpp"++namespace ov {+namespace test {++using ov::op::internal::NGramHashFunction;+using ov::op::v0::Parameter;+using testing::HasSubstr;++namespace {+// Qwen3.8-Flash-Next style: trigram, 8 heads per order (vocab sizes shortened).+const std::vector<int64_t> kQwenMultipliers{23703573157769, 20109073645365, 8052911324071};+struct HashConfig {+ std::vector<int64_t> heads_per_order;+ std::vector<int64_t> multipliers;+ std::vector<int64_t> vocab_sizes;+ std::vector<int64_t> offsets;+};++HashConfig make_config(std::vector<int64_t> heads_per_order, std::vector<int64_t> multipliers) {+ HashConfig c{std::move(heads_per_order), std::move(multipliers), {}, {}};+ int64_t offset = 0;+ int64_t vocab = 1000003;+ for (const auto heads : c.heads_per_order) {+ for (int64_t e = 0; e < heads; ++e) {+ c.vocab_sizes.push_back(vocab);+ c.offsets.push_back(offset);+ offset += vocab;+ vocab += 30;+ }+ }+ return c;+}++std::shared_ptr<NGramHashFunction> make_hash(const Output<Node>& ngrams, const HashConfig& c) {+ return std::make_shared<NGramHashFunction>(ngrams, c.heads_per_order, c.multipliers, c.vocab_sizes, c.offsets);+}++} // namespace++class TypePropNGramHashFunctionTest : public TypePropOpTest<NGramHashFunction> {};++TEST_F(TypePropNGramHashFunctionTest, qwen_trigram) {+ const auto c = make_config({8, 8}, kQwenMultipliers);+ const auto op = make_hash(std::make_shared<Parameter>(element::i64, PartialShape{2, 5, 3}), c);++ EXPECT_EQ(op->get_input_size(), 1);+ EXPECT_EQ(op->get_output_size(), 1);+ EXPECT_EQ(op->get_output_element_type(0), element::i32);+ EXPECT_EQ(op->get_output_partial_shape(0), (PartialShape{2, 5, 16}));+ EXPECT_EQ(op->get_num_heads(), 16);+}++TEST_F(TypePropNGramHashFunctionTest, shapes_sdpa_paged_and_dynamic) {+ const auto c = make_config({8, 8}, kQwenMultipliers);+ for (const auto& [in, out] :+ std::vector<std::pair<PartialShape, PartialShape>>{{{1, 300, 3}, {1, 300, 16}},+ {{-1, -1, 3}, {-1, -1, 16}},+ {{-1, 3}, {-1, 16}}, // continuous batching [T, ngram_size]+ {{-1, -1}, {-1, 16}},+ {{3}, {16}},+ {PartialShape::dynamic(), PartialShape::dynamic()}}) {+ for (const auto type : {element::i32, element::i64}) {+ const auto op = make_hash(std::make_shared<Parameter>(type, in), c);+ EXPECT_EQ(op->get_output_element_type(0), element::i32);+ EXPECT_EQ(op->get_output_partial_shape(0), out) << in;+ }+ }+}++TEST_F(TypePropNGramHashFunctionTest, per_order_heads) {+ const auto c = make_config({4, 2, 6}, {11, 13, 17, 19});+ const auto op = make_hash(std::make_shared<Parameter>(element::i64, PartialShape{-1, 4}), c);+ EXPECT_EQ(op->get_output_partial_shape(0), (PartialShape{-1, 12}));+}++TEST_F(TypePropNGramHashFunctionTest, invalid_inputs_and_attributes) {+ const auto c = make_config({8, 8}, kQwenMultipliers);+ const auto ngrams = std::make_shared<Parameter>(element::i64, PartialShape{-1, 3});++ OV_EXPECT_THROW(make_hash(std::make_shared<Parameter>(element::i64, PartialShape{-1, 4}), c),+ NodeValidationFailure,+ HasSubstr("last dimension of the ngrams input must be equal to ngram_size"));+ OV_EXPECT_THROW(make_hash(std::make_shared<Parameter>(element::f32, PartialShape{-1, 3}), c),+ NodeValidationFailure,+ HasSubstr("must be i32 or i64"));+ OV_EXPECT_THROW(make_hash(ngrams, {{}, {1}, {1}, {0}}),+ NodeValidationFailure,+ HasSubstr("multipliers must have ngram_size >= 2 values"));++ auto bad = c;+ bad.multipliers.pop_back();+ OV_EXPECT_THROW(make_hash(ngrams, bad), NodeValidationFailure, HasSubstr("heads_per_order must have"));++ bad = c;+ bad.heads_per_order = {8};+ OV_EXPECT_THROW(make_hash(ngrams, bad), NodeValidationFailure, HasSubstr("heads_per_order must have"));++ bad = c;+ bad.offsets.pop_back();+ OV_EXPECT_THROW(make_hash(ngrams, bad), NodeValidationFailure, HasSubstr("head_vocab_sizes and head_offsets"));++ bad = c;+ bad.vocab_sizes[3] = 0;+ OV_EXPECT_THROW(make_hash(ngrams, bad), NodeValidationFailure, HasSubstr("must be positive"));++ bad = c;+ bad.offsets[3] = -1;+ OV_EXPECT_THROW(make_hash(ngrams, bad), NodeValidationFailure, HasSubstr("must be non-negative"));++ bad = c;+ bad.offsets.back() = std::numeric_limits<int32_t>::max() - bad.vocab_sizes.back() + 2;+ OV_EXPECT_THROW(make_hash(ngrams, bad), NodeValidationFailure, HasSubstr("must fit int32"));+}++TEST_F(TypePropNGramHashFunctionTest, rejects_overflowing_head_totals) {+ const auto input = std::make_shared<Parameter>(element::i64, PartialShape{-1, 4});+ const auto max = std::numeric_limits<int64_t>::max();+ for (const auto& heads : std::vector<std::vector<int64_t>>{{max, max, 3}, {max, 1, 0}}) {+ OV_EXPECT_THROW(make_hash(input, {heads, {1, 2, 3, 4}, {7}, {0}}),+ NodeValidationFailure,+ HasSubstr("sum(heads_per_order)"));+ }+}++TEST_F(TypePropNGramHashFunctionTest, rejects_negative_and_zero_head_totals) {+ const auto input = std::make_shared<Parameter>(element::i64, PartialShape{-1, 3});+ OV_EXPECT_THROW(make_hash(input, {{-1, 1}, {1, 2, 3}, {7}, {0}}), NodeValidationFailure, HasSubstr("non-negative"));+ OV_EXPECT_THROW(make_hash(input, {{0, 0}, {1, 2, 3}, {}, {}}),+ NodeValidationFailure,+ HasSubstr("at least one head"));+}++TEST_F(TypePropNGramHashFunctionTest, accepts_largest_int32_row) {+ const auto input = std::make_shared<Parameter>(element::i64, PartialShape{-1, 2});+ const auto max = static_cast<int64_t>(std::numeric_limits<int32_t>::max());+ EXPECT_NO_THROW(make_hash(input, {{1}, {11, 13}, {max + 1}, {0}}));+ EXPECT_NO_THROW(make_hash(input, {{1}, {11, 13}, {1}, {max}}));+ for (const auto& [vocab, offset] :+ std::vector<std::pair<int64_t, int64_t>>{{max + 2, 0}, {max + 1, 1}, {1, max + 1}}) {+ OV_EXPECT_THROW(make_hash(input, {{1}, {11, 13}, {vocab}, {offset}}),+ NodeValidationFailure,+ HasSubstr("must fit int32"));+ }+}++} // namespace test+} // namespace ovdiff --git a/src/core/tests/type_prop/sources.cmake b/src/core/tests/type_prop/sources.cmakeindex dc2f17f0e65..9ab162702ec 100644--- a/src/core/tests/type_prop/sources.cmake+++ b/src/core/tests/type_prop/sources.cmake@@ -131,6 +131,7 @@ set(OV_CORE_TESTS_TYPE_PROP_SRCS${CMAKE_CURRENT_LIST_DIR}/multiply.cpp${CMAKE_CURRENT_LIST_DIR}/mvn.cpp${CMAKE_CURRENT_LIST_DIR}/negative.cpp+ ${CMAKE_CURRENT_LIST_DIR}/ngram_hash_function.cpp${CMAKE_CURRENT_LIST_DIR}/nms_rotated.cpp${CMAKE_CURRENT_LIST_DIR}/non_max_suppression.cpp${CMAKE_CURRENT_LIST_DIR}/non_zero.cppdiff --git a/src/core/tests/visitors/op/ngram_hash_function.cpp b/src/core/tests/visitors/op/ngram_hash_function.cppnew file mode 100644index 00000000000..1d3b8fe8452--- /dev/null+++ b/src/core/tests/visitors/op/ngram_hash_function.cpp@@ -0,0 +1,40 @@+// Copyright (C) 2018-2026 Intel Corporation+// SPDX-License-Identifier: Apache-2.0+//++#include "openvino/op/ngram_hash_function.hpp"++#include <gtest/gtest.h>++#include "visitors/visitors.hpp"++using ov::PartialShape;+using ov::op::v0::Parameter;+using ov::test::NodeBuilder;++TEST(attributes, ngram_hash_function) {+ using ov::op::internal::NGramHashFunction;+ NodeBuilder::opset().insert<NGramHashFunction>();++ const auto ngrams = std::make_shared<Parameter>(ov::element::i64, PartialShape{-1, 3});+ const auto op = std::make_shared<NGramHashFunction>(+ ngrams,+ std::vector<int64_t>{2, 1},+ std::vector<int64_t>{23703573157769, 20109073645365, static_cast<int64_t>(0x9E3779B97F4A7C15ULL)},+ std::vector<int64_t>{20000003, 20000023, 20000033},+ std::vector<int64_t>{0, 20000003, 40000026});++ NodeBuilder builder(op, {ngrams});+ auto g_op = ov::as_type_ptr<NGramHashFunction>(builder.create());+ ASSERT_NE(g_op, nullptr);++ constexpr auto expected_attr_count = 4;+ EXPECT_EQ(builder.get_value_map_size(), expected_attr_count);+ EXPECT_EQ(g_op->get_ngram_size(), op->get_ngram_size());+ EXPECT_EQ(g_op->get_heads_per_order(), op->get_heads_per_order());+ EXPECT_EQ(g_op->get_multipliers(), op->get_multipliers());+ EXPECT_EQ(g_op->get_head_vocab_sizes(), op->get_head_vocab_sizes());+ EXPECT_EQ(g_op->get_head_offsets(), op->get_head_offsets());+ EXPECT_EQ(g_op->get_output_element_type(0), op->get_output_element_type(0));+ EXPECT_EQ(g_op->get_output_partial_shape(0), op->get_output_partial_shape(0));+}diff --git a/src/core/tests/visitors/sources.cmake b/src/core/tests/visitors/sources.cmakeindex 5aae4be3204..bedca80c11a 100644--- a/src/core/tests/visitors/sources.cmake+++ b/src/core/tests/visitors/sources.cmake@@ -133,6 +133,7 @@ set(OV_CORE_TESTS_VISITORS_SRCS${CMAKE_CURRENT_LIST_DIR}/op/multiply.cpp${CMAKE_CURRENT_LIST_DIR}/op/mvn.cpp${CMAKE_CURRENT_LIST_DIR}/op/negative.cpp+ ${CMAKE_CURRENT_LIST_DIR}/op/ngram_hash_function.cpp${CMAKE_CURRENT_LIST_DIR}/op/nms_rotated.cpp${CMAKE_CURRENT_LIST_DIR}/op/non_max_suppression.cpp${CMAKE_CURRENT_LIST_DIR}/op/non_zero.cppdiff --git a/src/plugins/intel_cpu/sources.cmake b/src/plugins/intel_cpu/sources.cmakeindex a68e247229b..8ab9483fa34 100644--- a/src/plugins/intel_cpu/sources.cmake+++ b/src/plugins/intel_cpu/sources.cmake@@ -399,6 +399,8 @@ set(CPU_PLUGIN_SRCS${CPU_SRC_DIR}/nodes/mvn.h${CPU_SRC_DIR}/nodes/ngram.cpp${CPU_SRC_DIR}/nodes/ngram.h+ ${CPU_SRC_DIR}/nodes/ngram_hash.cpp+ ${CPU_SRC_DIR}/nodes/ngram_hash.h${CPU_SRC_DIR}/nodes/node_config.h${CPU_SRC_DIR}/nodes/non_max_suppression.cpp${CPU_SRC_DIR}/nodes/non_max_suppression.hdiff --git a/src/plugins/intel_cpu/src/cpu_types.cpp b/src/plugins/intel_cpu/src/cpu_types.cppindex 9dc1cd21ce2..81b03ba7cd8 100644--- a/src/plugins/intel_cpu/src/cpu_types.cpp+++ b/src/plugins/intel_cpu/src/cpu_types.cpp@@ -249,6 +249,7 @@ static const TypeToNameMap& get_type_to_name_tbl() {{"Interaction", Type::Interaction},{"Unique", Type::Unique},{"Ngram", Type::Ngram},+ {"NGramHashFunction", Type::NgramHash},{"ScaledDotProductAttention", Type::ScaledDotProductAttention},{"ScaledDotProductAttentionWithKVCache", Type::ScaledDotProductAttention},{"SDPAWithTransposeReshape", Type::ScaledDotProductAttention},@@ -400,6 +401,7 @@ std::string NameFromType(const Type type) {CASE(RandomUniform);CASE(Unique);CASE(Ngram);+ CASE(NgramHash);CASE(ScaledDotProductAttention);CASE(PagedAttention);CASE(PaKVReorder);diff --git a/src/plugins/intel_cpu/src/cpu_types.h b/src/plugins/intel_cpu/src/cpu_types.hindex e25c559526c..4d694eaeb2a 100644--- a/src/plugins/intel_cpu/src/cpu_types.h+++ b/src/plugins/intel_cpu/src/cpu_types.h@@ -128,6 +128,7 @@ enum class Type : uint8_t {RandomUniform,Unique,Ngram,+ NgramHash,ScaledDotProductAttention,PagedAttention,PaKVReorder,diff --git a/src/plugins/intel_cpu/src/extension.cpp b/src/plugins/intel_cpu/src/extension.cppindex a221dc1da97..ff3510904b4 100644--- a/src/plugins/intel_cpu/src/extension.cpp+++ b/src/plugins/intel_cpu/src/extension.cpp@@ -39,6 +39,7 @@#include "openvino/op/max_pool.hpp"#include "openvino/op/multiply.hpp"#include "openvino/op/mvn.hpp"+#include "openvino/op/ngram_hash_function.hpp"#include "openvino/op/nms_rotated.hpp"#include "openvino/op/non_max_suppression.hpp"#include "openvino/op/normalize_l2.hpp"@@ -224,6 +225,7 @@ OPENVINO_CREATE_EXTENSIONS(std::vector<ov::Extension::Ptr>({std::make_shared<ov::OpExtension<ov::op::internal::PagedCausalConv1D>>(),std::make_shared<ov::OpExtension<ov::op::internal::PagedQSAIndexer>>(),std::make_shared<ov::OpExtension<ov::op::internal::PagedSparseAttention>>(),+ std::make_shared<ov::OpExtension<ov::op::internal::NGramHashFunction>>(),// clang-format offOP_EXTENSION_X64(std::make_shared<ov::OpExtension<ov::intel_cpu::InteractionNode>>())OP_EXTENSION_X64(std::make_shared<ov::OpExtension<ov::intel_cpu::LLMMLPNode>>())diff --git a/src/plugins/intel_cpu/src/nodes/ngram_hash.cpp b/src/plugins/intel_cpu/src/nodes/ngram_hash.cppnew file mode 100644index 00000000000..9c937f99775--- /dev/null+++ b/src/plugins/intel_cpu/src/nodes/ngram_hash.cpp@@ -0,0 +1,140 @@+// Copyright (C) 2018-2026 Intel Corporation+// SPDX-License-Identifier: Apache-2.0+//++#include "ngram_hash.h"++#include <algorithm>+#include <cstddef>+#include <cstdint>+#include <memory>+#include <oneapi/dnnl/dnnl_common.hpp>+#include <string>++#include "cpu_types.h"+#include "graph_context.h"+#include "memory_desc/cpu_memory_desc.h"+#include "node.h"+#include "onednn/iml_type_mapper.h"+#include "openvino/core/except.hpp"+#include "openvino/core/node.hpp"+#include "openvino/core/parallel.hpp"+#include "openvino/core/shape.hpp"+#include "openvino/core/type.hpp"+#include "openvino/core/type/element_type.hpp"+#include "openvino/op/ngram_hash_function.hpp"+#include "openvino/reference/ngram_hash_function.hpp"+#include "selective_build.h"+#include "shape_inference/shape_inference_cpu.hpp"+#include "utils/general_utils.h"++namespace ov::intel_cpu::node {++bool NgramHash::isSupportedOperation(const std::shared_ptr<const ov::Node>& op, std::string& errorMessage) noexcept {+ try {+ if (!ov::as_type_ptr<const ov::op::internal::NGramHashFunction>(op)) {+ errorMessage = "Only internal NGramHashFunction operation is supported";+ return false;+ }+ } catch (...) {+ return false;+ }+ return true;+}++NgramHash::NgramHash(const std::shared_ptr<ov::Node>& op, const GraphContext::CPtr& context)+ : Node(op, context, NgraphShapeInferFactory(op)) {+ std::string errorMessage;+ if (!isSupportedOperation(op, errorMessage)) {+ OPENVINO_THROW_NOT_IMPLEMENTED(errorMessage);+ }+ const auto ngram_hash = ov::as_type_ptr<const ov::op::internal::NGramHashFunction>(op);+ m_ngram_size = static_cast<size_t>(ngram_hash->get_ngram_size());+ m_heads_per_order = ngram_hash->get_heads_per_order();+ m_multipliers = ngram_hash->get_multipliers();+ m_head_vocab_sizes = ngram_hash->get_head_vocab_sizes();+ m_head_offsets = ngram_hash->get_head_offsets();+}++void NgramHash::initSupportedPrimitiveDescriptors() {+ if (!supportedPrimitiveDescriptors.empty()) {+ return;+ }+ m_precision = getOriginalInputPrecisionAtPort(0);+ if (none_of(m_precision, ov::element::i32, ov::element::i64)) {+ m_precision = ov::element::i32;+ }+ addSupportedPrimDesc({{LayoutType::ncsp, m_precision}},+ {{LayoutType::ncsp, ov::element::i32}},+ impl_desc_type::ref_any);+}++template <typename T>+void NgramHash::executeImpl() {+ const auto* ngrams = getSrcDataAtPortAs<const T>(0);+ auto* row_ids = getDstDataAtPortAs<int32_t>(0);+ const size_t num_tokens = ov::shape_size(getSrcMemoryAtPort(0)->getStaticDims()) / m_ngram_size;+ const size_t num_heads = m_head_vocab_sizes.size();++ // The reference kernel (plain % modulo) is enough here: the Gather from the n-gram embedding table that follows+ // the hash dominates the n-gram subgraph, so the hash is a marginal part of it even when its own cost grows.+ auto hash_range = [&](size_t begin, size_t end) {+ ov::reference::ngram_hash_function(ngrams,+ row_ids,+ begin,+ end,+ m_ngram_size,+ m_heads_per_order.data(),+ m_multipliers.data(),+ m_head_vocab_sizes.data(),+ m_head_offsets.data(),+ num_heads);+ };++ constexpr size_t serial_window_limit = 256;+ if (num_tokens <= serial_window_limit) {+ hash_range(0, num_tokens);+ return;+ }+ const auto num_threads = static_cast<int>(+ std::min(static_cast<size_t>(context->getCpuParallel()->get_num_worker_threads()), num_tokens));+ parallel_nt_static(num_threads, [&](const int ithr, const int nthr) {+ size_t begin = 0;+ size_t end = 0;+ splitter(num_tokens, nthr, ithr, begin, end);+ hash_range(begin, end);+ });+}++namespace {+struct NgramHashContext {+ NgramHash& node;+};+} // namespace++template <typename T>+struct NgramHash::NgramHashExecute {+ void operator()(NgramHashContext& ctx) {+ ctx.node.executeImpl<T>();+ }+};++void NgramHash::execute([[maybe_unused]] const dnnl::stream& strm) {+ NgramHashContext ctx = {*this};+ OV_SWITCH(intel_cpu,+ NgramHashExecute,+ ctx,+ m_precision,+ OV_CASE(ov::element::i32, int32_t),+ OV_CASE(ov::element::i64, int64_t))+}++void NgramHash::executeDynamicImpl(const dnnl::stream& strm) {+ execute(strm);+}++bool NgramHash::created() const {+ return getType() == Type::NgramHash;+}++} // namespace ov::intel_cpu::nodediff --git a/src/plugins/intel_cpu/src/nodes/ngram_hash.h b/src/plugins/intel_cpu/src/nodes/ngram_hash.hnew file mode 100644index 00000000000..95f7a1d0638--- /dev/null+++ b/src/plugins/intel_cpu/src/nodes/ngram_hash.h@@ -0,0 +1,54 @@+// Copyright (C) 2018-2026 Intel Corporation+// SPDX-License-Identifier: Apache-2.0+//++#pragma once++#include <node.h>++#include <cstdint>+#include <memory>+#include <oneapi/dnnl/dnnl_common.hpp>+#include <string>+#include <vector>++#include "graph_context.h"+#include "openvino/core/node.hpp"+#include "openvino/core/type/element_type.hpp"++namespace ov::intel_cpu::node {++// Executes ov::op::internal::NGramHashFunction.+class NgramHash : public Node {+public:+ NgramHash(const std::shared_ptr<ov::Node>& op, const GraphContext::CPtr& context);++ void getSupportedDescriptors() override {};+ void initSupportedPrimitiveDescriptors() override;+ void execute(const dnnl::stream& strm) override;+ bool created() const override;+ bool needPrepareParams() const override {+ return false;+ }++ static bool isSupportedOperation(const std::shared_ptr<const ov::Node>& op, std::string& errorMessage) noexcept;++protected:+ void executeDynamicImpl(const dnnl::stream& strm) override;++private:+ template <typename T>+ void executeImpl();++ template <typename T>+ struct NgramHashExecute;++ size_t m_ngram_size = 0;+ std::vector<int64_t> m_heads_per_order;+ std::vector<int64_t> m_multipliers;+ std::vector<int64_t> m_head_vocab_sizes;+ std::vector<int64_t> m_head_offsets;+ ov::element::Type m_precision;+};++} // namespace ov::intel_cpu::nodediff --git a/src/plugins/intel_cpu/src/nodes_factory.cpp b/src/plugins/intel_cpu/src/nodes_factory.cppindex 35a5a88f26b..3a9a828deef 100644--- a/src/plugins/intel_cpu/src/nodes_factory.cpp+++ b/src/plugins/intel_cpu/src/nodes_factory.cpp@@ -63,6 +63,7 @@#include "nodes/multinomial.hpp"#include "nodes/mvn.h"#include "nodes/ngram.h"+#include "nodes/ngram_hash.h"#include "nodes/non_max_suppression.h"#include "nodes/non_zero.h"#include "nodes/normalize.h"@@ -226,6 +227,7 @@ Node::NodesFactory::NodesFactory() : Factory("NodesFactory") {INTEL_CPU_NODE(Eye, Type::Eye);INTEL_CPU_NODE(Unique, Type::Unique);INTEL_CPU_NODE(Ngram, Type::Ngram);+ INTEL_CPU_NODE(NgramHash, Type::NgramHash);INTEL_CPU_NODE(RoPE, Type::RoPE);INTEL_CPU_NODE(CausalMaskPreprocess, Type::CausalMaskPreprocess);INTEL_CPU_NODE(Identity, Type::Identity);diff --git a/src/plugins/intel_cpu/src/shape_inference/shape_inference.cpp b/src/plugins/intel_cpu/src/shape_inference/shape_inference.cppindex be70aaab375..8a80c97691f 100644--- a/src/plugins/intel_cpu/src/shape_inference/shape_inference.cpp+++ b/src/plugins/intel_cpu/src/shape_inference/shape_inference.cpp@@ -80,6 +80,7 @@#include "max_pool_shape_inference.hpp"#include "memory_accessor.hpp"#include "multinomial_shape_inference.hpp"+#include "ngram_hash_function_shape_inference.hpp"#include "nms_shape_inference.hpp"#include "nv12_shape_inference.hpp"#include "one_hot_shape_inference.hpp"@@ -151,6 +152,7 @@#include "openvino/op/max_pool.hpp"#include "openvino/op/multinomial.hpp"#include "openvino/op/mvn.hpp"+#include "openvino/op/ngram_hash_function.hpp"#include "openvino/op/non_max_suppression.hpp"#include "openvino/op/normalize_l2.hpp"#include "openvino/op/nv12_to_bgr.hpp"@@ -759,6 +761,7 @@ const IStaticShapeInferFactory::TRegistry IStaticShapeInferFactory::registry{//OV_OP_SHAPE_INFER_MASK_REG(ov::op::internal::AUGRUCell, ShapeInferTA, util::bit::mask()),OV_OP_SHAPE_INFER_MASK_REG(ov::op::internal::AUGRUSequence, ShapeInferTA, util::bit::mask()),+ OV_OP_SHAPE_INFER_MASK_REG(ov::op::internal::NGramHashFunction, ShapeInferTA, util::bit::mask()),OV_OP_SHAPE_INFER_MASK_REG(ov::op::internal::RMSNorm, ShapeInferTA, util::bit::mask(1)),OV_OP_SHAPE_INFER_MASK_REG(ov::op::internal::GLU, ShapeInferTA, util::bit::mask()),OV_OP_SHAPE_INFER_MASK_REG(ov::op::internal::SelectiveSSM, ShapeInferTA, util::bit::mask()),diff --git a/src/plugins/intel_cpu/src/transformations/transformation_pipeline.cpp b/src/plugins/intel_cpu/src/transformations/transformation_pipeline.cppindex 2d458804bf2..a88ee201659 100644--- a/src/plugins/intel_cpu/src/transformations/transformation_pipeline.cpp+++ b/src/plugins/intel_cpu/src/transformations/transformation_pipeline.cpp@@ -78,6 +78,7 @@#include "transformations/common_optimizations/matmul_const_transposes_extraction.hpp"#include "transformations/common_optimizations/move_eltwise_up_data_movement.hpp"#include "transformations/common_optimizations/mul_fake_quantize_fusion.hpp"+#include "transformations/common_optimizations/ngram_hash_function_fusion.hpp"#include "transformations/common_optimizations/nop_elimination.hpp"#include "transformations/common_optimizations/reshape_prelu.hpp"#include "transformations/common_optimizations/sdpa_fusion.hpp"@@ -474,6 +475,8 @@ void Transformations::PreLpt(const std::vector<ov::element::Type>& defaultPrecisov::pass::Manager decompression_handling_manager("CPU:DecompressionHandling");decompression_handling_manager.set_per_pass_validation(false);CPU_REGISTER_PASS_COMMON(decompression_handling_manager, ov::pass::InitNodeInfo);+ // Match before no-op elimination can remove a zero-offset Add from a valid hash block.+ CPU_REGISTER_PASS_COMMON(decompression_handling_manager, ov::pass::NGramHashFunctionFusion);const bool useLpt = !defaultPrecisions.empty();CPU_REGISTER_PASS_COMMON(decompression_handling_manager, ov::pass::CompressedGatherTransformation);CPU_REGISTER_PASS_COMMON(decompression_handling_manager, ov::pass::MarkShapeOfSubgraphs);@@ -622,6 +625,10 @@ void Transformations::PreLpt(const std::vector<ov::element::Type>& defaultPrecisCPU_REGISTER_PASS_COMMON(manager, ov::pass::ConstantFolding);CPU_REGISTER_PASS_ARM64(manager, ov::pass::HardSigmoidDecomposition);+ // Fuses int64 n-gram hashes (all orders) into one NGramHashFunction that keeps the int64 math inside its kernel,+ // before ConvertPrecision would otherwise downcast the products/xors to i32.+ CPU_REGISTER_PASS_COMMON(manager, ov::pass::NGramHashFunctionFusion);+if (useLpt) {CPU_LPT_SCOPE(LowPrecisionTransformations_Part2);CPU_REGISTER_PASS_COMMON(manager, ov::pass::low_precision::ConvertSubtractConstant, defaultPrecisions);diff --git a/src/plugins/intel_cpu/tests/functional/custom/subgraph_tests/src/common/ngram_hash.cpp b/src/plugins/intel_cpu/tests/functional/custom/subgraph_tests/src/common/ngram_hash.cppnew file mode 100644index 00000000000..de294c66f2e--- /dev/null+++ b/src/plugins/intel_cpu/tests/functional/custom/subgraph_tests/src/common/ngram_hash.cpp@@ -0,0 +1,314 @@+// Copyright (C) 2018-2026 Intel Corporation+// SPDX-License-Identifier: Apache-2.0+//++#include <gtest/gtest.h>++#include <algorithm>+#include <cstdint>+#include <limits>+#include <memory>+#include <random>+#include <string>+#include <tuple>+#include <vector>++#include "openvino/op/add.hpp"+#include "openvino/op/bitwise_xor.hpp"+#include "openvino/op/concat.hpp"+#include "openvino/op/constant.hpp"+#include "openvino/op/convert.hpp"+#include "openvino/op/floor_mod.hpp"+#include "openvino/op/multiply.hpp"+#include "openvino/op/ngram_hash_function.hpp"+#include "openvino/op/parameter.hpp"+#include "openvino/op/unsqueeze.hpp"+#include "openvino/runtime/core.hpp"+#include "openvino/runtime/exec_model_info.hpp"+#include "shared_test_classes/base/ov_subgraph.hpp"++namespace ov::test {+namespace {+struct NGramHashCase {+ std::string name;+ std::vector<int64_t> multipliers;+ std::vector<int64_t> heads_per_order;+ int64_t num_engram;+ std::vector<int64_t> vocab_sizes = {};+};++const std::vector<int64_t> qwen_multipliers{23703573157769, 20109073645365, 8052911324071, 3000000019};+const std::vector<int64_t> deepseek_multipliers{0x3BF58476D1CE4E5B,+ static_cast<int64_t>(0x9E3779B97F4A7C15ULL),+ 1234567891011,+ static_cast<int64_t>(0xD6E8FEB86659FD93ULL)};++const std::vector<NGramHashCase> cases{+ {"Qwen3_8FlashNext_Bigram", {qwen_multipliers[0], qwen_multipliers[1]}, {8}, 0},+ {"Qwen3_8FlashNext_Trigram", {qwen_multipliers.begin(), qwen_multipliers.begin() + 3}, {8, 8}, 0},+ {"Qwen3_8FlashNext_Fourgram", qwen_multipliers, {8, 8, 8}, 0},+ {"DeepSeekV4_1Flash_Bigram", {deepseek_multipliers[0], deepseek_multipliers[1]}, {4}, 8},+ {"DeepSeekV4_1Flash_Trigram", {deepseek_multipliers.begin(), deepseek_multipliers.begin() + 3}, {4, 4}, 8},+ {"DeepSeekV4_1Flash_Fourgram_PerOrderHeads", deepseek_multipliers, {2, 4, 3}, 8},+ {"Modulo_UnitAndPowerOfTwo",+ {0, std::numeric_limits<int64_t>::min(), -1, std::numeric_limits<int64_t>::max()},+ {0, 2, 1},+ 0,+ {1, 2, 1073741824}},+ {"Modulo_MaxDivisor",+ {std::numeric_limits<int64_t>::max(), std::numeric_limits<int64_t>::min()},+ {2},+ 0,+ {std::numeric_limits<int32_t>::max(), 1}},+ {"Modulo_NearPowerOfTwo",+ {qwen_multipliers.begin(), qwen_multipliers.begin() + 3},+ {2, 1},+ 0,+ {536870911, 536870913, 536870923}},+ {"Modulo_Int32RowBoundary", {11, 13}, {1}, 0, {2147483648LL}},+ {"ManyHeads", {11, 13}, {129}, 0, std::vector<int64_t>(129, 1)},+};++enum class HashInputKind { direct_i32, direct_i64, traced_i64 };+using NGramHashParams = std::tuple<NGramHashCase, HashInputKind>;++std::vector<int64_t> make_vocab_sizes(const NGramHashCase& config) {+ if (!config.vocab_sizes.empty()) {+ return config.vocab_sizes;+ }+ std::vector<int64_t> vocab;+ for (const auto heads : config.heads_per_order) {+ for (int64_t head = 0; head < heads; ++head) {+ vocab.push_back(20000003 + static_cast<int64_t>(vocab.size()) * 20);+ }+ }+ return vocab;+}++std::vector<int64_t> make_offsets(const std::vector<int64_t>& vocab) {+ std::vector<int64_t> offsets;+ int64_t offset = 0;+ for (const auto size : vocab) {+ offsets.push_back(offset);+ offset += size;+ }+ return offsets;+}++std::shared_ptr<Node> make_hash(const Output<Node>& windows, const NGramHashCase& config) {+ const auto vocab = make_vocab_sizes(config);+ return std::make_shared<op::internal::NGramHashFunction>(windows,+ config.heads_per_order,+ config.multipliers,+ vocab,+ make_offsets(vocab));+}++std::shared_ptr<Model> make_direct_model(const NGramHashCase& config, const element::Type& type) {+ PartialShape shape{-1};+ if (config.num_engram) {+ shape.push_back(config.num_engram);+ }+ shape.push_back(config.multipliers.size());+ const auto windows = std::make_shared<op::v0::Parameter>(type, shape);+ windows->set_friendly_name("ngrams");+ return std::make_shared<Model>(OutputVector{make_hash(windows, config)}, ParameterVector{windows});+}++std::shared_ptr<Model> make_traced_model(const NGramHashCase& config, bool reference) {+ PartialShape shape{-1};+ if (config.num_engram) {+ shape.push_back(config.num_engram);+ }+ ParameterVector tokens;+ for (size_t back = 0; back < config.multipliers.size(); ++back) {+ const auto token = std::make_shared<op::v0::Parameter>(element::i64, shape);+ token->set_friendly_name("token_back_" + std::to_string(back));+ tokens.push_back(token);+ }+ const auto axis = op::v0::Constant::create(element::i64, Shape{1}, {-1});+ if (reference) {+ OutputVector window;+ for (auto token = tokens.rbegin(); token != tokens.rend(); ++token) {+ window.push_back(std::make_shared<op::v0::Unsqueeze>(*token, axis));+ }+ const auto windows = std::make_shared<op::v0::Concat>(window, -1);+ const auto output = std::make_shared<op::v0::Convert>(make_hash(windows, config), element::i64);+ return std::make_shared<Model>(OutputVector{output}, tokens);+ }+ const auto vocab = make_vocab_sizes(config);+ const auto offsets = make_offsets(vocab);+ const auto term = [&](size_t back) {+ return std::make_shared<op::v1::Multiply>(+ tokens[back],+ op::v0::Constant::create(element::i64, Shape{}, {config.multipliers[back]}));+ };+ Output<Node> mix = term(0);+ OutputVector blocks;+ size_t head_offset = 0;+ for (size_t back = 1; back < config.multipliers.size(); ++back) {+ mix = std::make_shared<op::v13::BitwiseXor>(mix, term(back));+ const auto heads = static_cast<size_t>(config.heads_per_order[back - 1]);+ if (heads == 0) {+ continue;+ }+ const std::vector<int64_t> sizes(vocab.begin() + head_offset, vocab.begin() + head_offset + heads);+ const std::vector<int64_t> starts(offsets.begin() + head_offset, offsets.begin() + head_offset + heads);+ head_offset += heads;+ const auto expanded = std::make_shared<op::v0::Unsqueeze>(mix, axis);+ const auto mod =+ std::make_shared<op::v1::FloorMod>(expanded, op::v0::Constant::create(element::i64, Shape{heads}, sizes));+ blocks.push_back(+ std::make_shared<op::v1::Add>(mod, op::v0::Constant::create(element::i64, Shape{heads}, starts)));+ }+ const Output<Node> output =+ blocks.size() == 1 ? blocks[0] : std::make_shared<op::v0::Concat>(blocks, -1)->output(0);+ return std::make_shared<Model>(OutputVector{output}, tokens);+}+} // namespace++class NGramHashFunctionCPUTest : public testing::WithParamInterface<NGramHashParams>, public SubgraphBaseTest {+public:+ static std::string getTestCaseName(const testing::TestParamInfo<NGramHashParams>& info) {+ const auto& [config, kind] = info.param;+ const std::string mode = kind == HashInputKind::traced_i64 ? "TracedI64"+ : kind == HashInputKind::direct_i64 ? "DirectI64"+ : "DirectI32";+ return config.name + "_" + mode;+ }++protected:+ void SetUp() override {+ const auto& [config, kind] = GetParam();+ targetDevice = ov::test::utils::DEVICE_CPU;+ const auto type = kind == HashInputKind::direct_i32 ? element::i32 : element::i64;+ if (kind == HashInputKind::traced_i64) {+ function = make_traced_model(config, false);+ functionRefs = make_traced_model(config, true);+ } else {+ function = make_direct_model(config, type);+ }+ std::vector<InputShape> shapes;+ for (const auto& parameter : function->get_parameters()) {+ std::vector<Shape> static_shapes;+ for (const size_t tokens : {1, 3, 256, 257, 2}) {+ Shape shape{tokens};+ if (config.num_engram) {+ shape.push_back(config.num_engram);+ }+ if (kind != HashInputKind::traced_i64) {+ shape.push_back(config.multipliers.size());+ }+ static_shapes.push_back(shape);+ }+ shapes.emplace_back(parameter->get_partial_shape(), static_shapes);+ }+ init_input_shapes(shapes);+ }++ void generate_inputs(const std::vector<Shape>& shapes) override {+ inputs.clear();+ std::mt19937 generator(static_cast<uint32_t>(shape_size(shapes[0])));+ const auto low = std::get<1>(GetParam()) == HashInputKind::traced_i64 ? 0 : std::numeric_limits<int32_t>::min();+ std::uniform_int_distribution<int64_t> distribution(low, std::numeric_limits<int32_t>::max());+ const auto& parameters = function->get_parameters();+ for (size_t input = 0; input < parameters.size(); ++input) {+ Tensor tensor(parameters[input]->get_element_type(), shapes[input]);+ for (size_t index = 0; index < tensor.get_size(); ++index) {+ const auto value = distribution(generator);+ if (tensor.get_element_type() == element::i32) {+ tensor.data<int32_t>()[index] = static_cast<int32_t>(value);+ } else {+ tensor.data<int64_t>()[index] = value;+ }+ }+ inputs.emplace(parameters[input], tensor);+ }+ }++ void init_thresholds() override {+ abs_threshold = 0;+ rel_threshold = 0;+ }+};++TEST_P(NGramHashFunctionCPUTest, CompareWithRefs) {+ run();+ CheckNumberOfNodesWithType(compiledModel, "NgramHash", 1);+}++TEST(NGramHashFunctionCPUValidationTest, RejectsInvalidDynamicWindow) {+ const auto input = std::make_shared<op::v0::Parameter>(element::i64, PartialShape{-1, -1});+ const auto hash = make_hash(input, cases[1]);+ const auto model = std::make_shared<Model>(OutputVector{hash}, ParameterVector{input});+ ov::Core core;+ auto request = core.compile_model(model, "CPU").create_infer_request();+ request.set_input_tensor(Tensor(element::i64, Shape{2, 6}));+ EXPECT_THROW(request.infer(), ov::Exception);+ Tensor valid(element::i64, Shape{2, 3});+ std::fill_n(valid.data<int64_t>(), valid.get_size(), 0);+ request.set_input_tensor(valid);+ EXPECT_NO_THROW(request.infer());+ EXPECT_EQ(request.get_output_tensor().get_shape(), (Shape{2, 16}));+}++TEST(NGramHashFunctionCPUValidationTest, RejectsDifferentOrderPrefixShapes) {+ ov::Core core;+ auto request = core.compile_model(make_traced_model(cases[1], false), "CPU").create_infer_request();+ for (size_t i = 0; i < 3; ++i) {+ Tensor input(element::i64, Shape{i == 2 ? size_t{3} : size_t{1}});+ std::fill_n(input.data<int64_t>(), input.get_size(), 1);+ request.set_input_tensor(i, input);+ }+ EXPECT_THROW(request.infer(), ov::Exception);+}++TEST(NGramHashFunctionCPUValidationTest, RejectsIncompatibleBroadcast) {+ ov::Core core;+ auto request = core.compile_model(make_traced_model(cases[1], false), "CPU").create_infer_request();+ for (size_t i = 0; i < 3; ++i) {+ Tensor input(element::i64, Shape{i == 0 ? size_t{2} : size_t{3}});+ std::fill_n(input.data<int64_t>(), input.get_size(), 1);+ request.set_input_tensor(i, input);+ }+ EXPECT_THROW(request.infer(), ov::Exception);+}++// The fused hash packs token terms without broadcasting, so differently shaped dynamic tokens fail loudly.+class NGramHashFunctionBroadcastCPUTest : public testing::TestWithParam<size_t> {};++TEST_P(NGramHashFunctionBroadcastCPUTest, RejectsBroadcastAfterFusion) {+ const auto model = make_traced_model(cases[1], false);+ for (const auto& parameter : model->get_parameters()) {+ parameter->set_partial_shape(PartialShape::dynamic(GetParam()));+ }+ model->validate_nodes_and_infer_types();+ ov::Core core;+ auto compiled = core.compile_model(model, "CPU");+ size_t hashes = 0;+ for (const auto& node : compiled.get_runtime_model()->get_ordered_ops()) {+ hashes += node->get_rt_info().at(ov::exec_model_info::LAYER_TYPE).as<std::string>() == "NgramHash";+ }+ ASSERT_EQ(hashes, 1);+ auto request = compiled.create_infer_request();+ const std::vector<Shape> concrete =+ GetParam() == 1 ? std::vector<Shape>{{1}, {3}, {3}} : std::vector<Shape>{{2, 1}, {1, 3}, {2, 3}};+ for (size_t i = 0; i < concrete.size(); ++i) {+ Tensor input(element::i64, concrete[i]);+ std::fill_n(input.data<int64_t>(), input.get_size(), 1);+ request.set_input_tensor(i, input);+ }+ EXPECT_THROW(request.infer(), ov::Exception);+}++INSTANTIATE_TEST_SUITE_P(smoke_NGramHashFunction,+ NGramHashFunctionBroadcastCPUTest,+ testing::Values(size_t{1}, size_t{2}));++INSTANTIATE_TEST_SUITE_P(+ smoke_NGramHashFunction,+ NGramHashFunctionCPUTest,+ testing::Combine(testing::ValuesIn(cases),+ testing::Values(HashInputKind::direct_i32, HashInputKind::direct_i64, HashInputKind::traced_i64)),+ NGramHashFunctionCPUTest::getTestCaseName);+} // namespace ov::test\ No newline at end of filediff --git a/src/plugins/intel_cpu/tests/functional/sources.cmake b/src/plugins/intel_cpu/tests/functional/sources.cmakeindex 183fa4dce27..21a614222d3 100644--- a/src/plugins/intel_cpu/tests/functional/sources.cmake+++ b/src/plugins/intel_cpu/tests/functional/sources.cmake@@ -253,6 +253,7 @@ set(CPU_FUNC_TESTS_CUSTOM_SRCS${CMAKE_CURRENT_LIST_DIR}/custom/subgraph_tests/src/common/matrix_nms_zero_boxes.cpp${CMAKE_CURRENT_LIST_DIR}/custom/subgraph_tests/src/common/merge_transpose_reorder.cpp${CMAKE_CURRENT_LIST_DIR}/custom/subgraph_tests/src/common/ngram.cpp+ ${CMAKE_CURRENT_LIST_DIR}/custom/subgraph_tests/src/common/ngram_hash.cpp${CMAKE_CURRENT_LIST_DIR}/custom/subgraph_tests/src/common/not_fused_conv_simple_op.cpp${CMAKE_CURRENT_LIST_DIR}/custom/subgraph_tests/src/common/read_value_assign.cpp${CMAKE_CURRENT_LIST_DIR}/custom/subgraph_tests/src/common/remove_convert.cpp@@ -813,6 +814,7 @@ set(TMP_LIST_OF_COMMON_SUBGRAPH_TESTS${CMAKE_CURRENT_LIST_DIR}/custom/subgraph_tests/src/common/matrix_nms_zero_boxes.cpp${CMAKE_CURRENT_LIST_DIR}/custom/subgraph_tests/src/common/merge_transpose_reorder.cpp${CMAKE_CURRENT_LIST_DIR}/custom/subgraph_tests/src/common/ngram.cpp+ ${CMAKE_CURRENT_LIST_DIR}/custom/subgraph_tests/src/common/ngram_hash.cpp${CMAKE_CURRENT_LIST_DIR}/custom/subgraph_tests/src/common/not_fused_conv_simple_op.cpp${CMAKE_CURRENT_LIST_DIR}/custom/subgraph_tests/src/common/read_value_assign.cpp${CMAKE_CURRENT_LIST_DIR}/custom/subgraph_tests/src/common/remove_convert.cppdiff --git a/src/plugins/template/backend/ops/ngram_hash_function.cpp b/src/plugins/template/backend/ops/ngram_hash_function.cppnew file mode 100644index 00000000000..f095390e1c4--- /dev/null+++ b/src/plugins/template/backend/ops/ngram_hash_function.cpp@@ -0,0 +1,47 @@+// Copyright (C) 2018-2026 Intel Corporation+// SPDX-License-Identifier: Apache-2.0+//++#include "openvino/op/ngram_hash_function.hpp"++#include "evaluate_node.hpp"+#include "ngram_hash_function_shape_inference.hpp"+#include "openvino/core/validation_util.hpp"+#include "openvino/reference/ngram_hash_function.hpp"++namespace {+template <typename T>+bool evaluate(const ov::op::internal::NGramHashFunction& op,+ ov::TensorVector& outputs,+ const ov::TensorVector& inputs) {+ const auto ngram_size = static_cast<size_t>(op.get_ngram_size());+ ov::reference::ngram_hash_function(inputs[0].data<const T>(),+ outputs[0].data<int32_t>(),+ inputs[0].get_size() / ngram_size,+ ngram_size,+ op.get_heads_per_order().data(),+ op.get_multipliers().data(),+ op.get_head_vocab_sizes().data(),+ op.get_head_offsets().data(),+ op.get_num_heads());+ return true;+}+} // namespace++template <>+bool evaluate_node<ov::op::internal::NGramHashFunction>(std::shared_ptr<ov::Node> node,+ ov::TensorVector& outputs,+ const ov::TensorVector& inputs) {+ OPENVINO_ASSERT(inputs.size() == 1 && outputs.size() == 1);+ const auto op = ov::as_type_ptr<ov::op::internal::NGramHashFunction>(node);+ const auto shapes = ov::op::internal::shape_infer(op.get(), ov::util::get_tensors_partial_shapes(inputs));+ outputs[0].set_shape(shapes[0].to_shape());+ switch (inputs[0].get_element_type()) {+ case ov::element::i32:+ return evaluate<int32_t>(*op, outputs, inputs);+ case ov::element::i64:+ return evaluate<int64_t>(*op, outputs, inputs);+ default:+ return false;+ }+}\ No newline at end of filediff --git a/src/plugins/template/backend/ops/ops_evaluates.hpp b/src/plugins/template/backend/ops/ops_evaluates.hppindex c9c8d5f2a90..2518bed0fad 100644--- a/src/plugins/template/backend/ops/ops_evaluates.hpp+++ b/src/plugins/template/backend/ops/ops_evaluates.hpp@@ -5,6 +5,7 @@#pragma once#include "evaluate_node.hpp"#include "openvino/op/gated_delta_net.hpp"+#include "openvino/op/ngram_hash_function.hpp"#include "openvino/op/ops.hpp"#include "openvino/op/paged_attention.hpp"#include "openvino/op/rms_norm.hpp"@@ -12,6 +13,10 @@#include "ov_ops/augru_sequence.hpp"#include "ov_ops/rms.hpp"+extern template bool evaluate_node<ov::op::internal::NGramHashFunction>(std::shared_ptr<ov::Node> node,+ ov::TensorVector& outputs,+ const ov::TensorVector& inputs);+extern template bool evaluate_node<ov::op::v0::Abs>(std::shared_ptr<ov::Node> node,ov::TensorVector& outputs,const ov::TensorVector& inputs);diff --git a/src/plugins/template/backend/opset_int_tbl.hpp b/src/plugins/template/backend/opset_int_tbl.hppindex a76b0a24186..000b41a63e2 100644--- a/src/plugins/template/backend/opset_int_tbl.hpp+++ b/src/plugins/template/backend/opset_int_tbl.hpp@@ -193,6 +193,7 @@ _OPENVINO_OP_REG(BGRtoNV12, ov::op::v17)_OPENVINO_OP_REG(AUGRUCell, ov::op::internal)_OPENVINO_OP_REG(AUGRUSequence, ov::op::internal)_OPENVINO_OP_REG(GatedDeltaNet, ov::op::internal)+_OPENVINO_OP_REG(NGramHashFunction, ov::op::internal)_OPENVINO_OP_REG(RMS, ov::op::internal)_OPENVINO_OP_REG(RMSNorm, ov::op::internal)_OPENVINO_OP_REG(PagedAttentionExtension, ov::op)diff --git a/src/plugins/template/backend/sources.cmake b/src/plugins/template/backend/sources.cmakeindex c22b3936928..49f94f72018 100644--- a/src/plugins/template/backend/sources.cmake+++ b/src/plugins/template/backend/sources.cmake@@ -85,6 +85,7 @@ set(OPS_SRC${CMAKE_CURRENT_LIST_DIR}/ops/multinomial.cpp${CMAKE_CURRENT_LIST_DIR}/ops/multiply.cpp${CMAKE_CURRENT_LIST_DIR}/ops/mvn.cpp+ ${CMAKE_CURRENT_LIST_DIR}/ops/ngram_hash_function.cpp${CMAKE_CURRENT_LIST_DIR}/ops/nms_rotated.cpp${CMAKE_CURRENT_LIST_DIR}/ops/non_max_suppression.cpp${CMAKE_CURRENT_LIST_DIR}/ops/normalize_l2.cppdiff --git a/src/plugins/template/tests/functional/op_reference/ngram_hash_function.cpp b/src/plugins/template/tests/functional/op_reference/ngram_hash_function.cppnew file mode 100644index 00000000000..7eb1287d2be--- /dev/null+++ b/src/plugins/template/tests/functional/op_reference/ngram_hash_function.cpp@@ -0,0 +1,139 @@+// Copyright (C) 2018-2026 Intel Corporation+// SPDX-License-Identifier: Apache-2.0+//++#include "openvino/op/ngram_hash_function.hpp"++#include <gtest/gtest.h>++#include <cstdint>+#include <limits>+#include <string>+#include <vector>++#include "base_reference_test.hpp"+#include "openvino/op/parameter.hpp"++namespace {+struct NGramHashFunctionParams {+ std::string name;+ reference_tests::Tensor input;+ std::vector<int64_t> heads_per_order;+ std::vector<int64_t> multipliers;+ std::vector<int64_t> vocab_sizes;+ std::vector<int64_t> offsets;+ reference_tests::Tensor expected;+};++class ReferenceNGramHashFunctionTest : public testing::TestWithParam<NGramHashFunctionParams>,+ public reference_tests::CommonReferenceTest {+public:+ void SetUp() override {+ const auto& params = GetParam();+ const auto input = std::make_shared<ov::op::v0::Parameter>(params.input.type, params.input.shape);+ const auto hash = std::make_shared<ov::op::internal::NGramHashFunction>(input,+ params.heads_per_order,+ params.multipliers,+ params.vocab_sizes,+ params.offsets);+ function = std::make_shared<ov::Model>(ov::OutputVector{hash}, ov::ParameterVector{input});+ inputData = {params.input.data};+ refOutData = {params.expected.data};+ threshold = 0;+ abs_threshold = 0;+ }+};++TEST_P(ReferenceNGramHashFunctionTest, CompareWithHardcodedRefs) {+ Exec();+}++std::vector<NGramHashFunctionParams> generate_params() {+ std::vector<NGramHashFunctionParams> params;+ for (const auto type : {ov::element::i32, ov::element::i64}) {+ const auto add_case = [&](const std::string& name,+ const ov::Shape& shape,+ const std::vector<int64_t>& tokens,+ const std::vector<int64_t>& heads,+ const std::vector<int64_t>& multipliers,+ const std::vector<int64_t>& vocab,+ const std::vector<int64_t>& offsets,+ const std::vector<int32_t>& expected) {+ const auto input =+ type == ov::element::i32+ ? reference_tests::Tensor{shape, type, std::vector<int32_t>(tokens.begin(), tokens.end())}+ : reference_tests::Tensor{shape, type, tokens};+ auto output_shape = shape;+ output_shape.back() = vocab.size();+ params.push_back({name + "_" + type.get_type_name(),+ input,+ heads,+ multipliers,+ vocab,+ offsets,+ reference_tests::Tensor{output_shape, ov::element::i32, expected}});+ };+ add_case("Bigram", {2}, {2, 3}, {2}, {3, 5}, {7, 11}, {0, 7}, {3, 10});+ add_case("TrigramSigned",+ {2, 3},+ {1, 2, 3, -1, -2, -3},+ {2, 1},+ {11, 13, 17},+ {7, 11, 13},+ {0, 7, 18},+ {3, 11, 21, 1, 9, 28});+ add_case("WrappingProducts",+ {1, 2, 3},+ {-2147483648LL, 2147483647, -1, 0, 2000000000, -2000000000},+ {1, 2},+ {0x3BF58476D1CE4E5B, static_cast<int64_t>(0x9E3779B97F4A7C15ULL), 1234567891011},+ {1000003, 1000033, 1},+ {0, 1000003, 2147483647},+ {696524, 1505995, 2147483647, 119144, 1949394, 2147483647});+ add_case("FourgramPerOrderHeads",+ {1, 4},+ {1, 2, 3, 4},+ {2, 1, 2},+ {11, 13, 17, 19},+ {7, 11, 13, 17, 19},+ {0, 7, 18, 31, 48},+ {4, 7, 20, 38, 49});+ add_case("FivegramSkippedOrder",+ {1, 5},+ {1, 2, 3, 4, 5},+ {1, 0, 1, 2},+ {11, 13, 17, 19, 23},+ {7, 11, 13, 17},+ {0, 7, 18, 31},+ {3, 7, 19, 32});+ add_case("ZeroTokens", {1, 3}, {0, 0, 0}, {1, 1}, {11, 13, 17}, {7, 11}, {0, 7}, {0, 7});+ add_case("Empty", {0, 3}, {}, {1, 1}, {11, 13, 17}, {7, 11}, {0, 7}, {});+ if (type == ov::element::i64) {+ add_case("Int32RowBoundary",+ {2, 2},+ {0, -1, 0, 2147483647},+ {1},+ {1, 1},+ {2147483648LL},+ {0},+ {2147483647, 2147483647});+ add_case("FullInt64Range",+ {1, 3},+ {std::numeric_limits<int64_t>::min(), std::numeric_limits<int64_t>::max(), 3000000000LL},+ {1, 1},+ {23703573157769, 20109073645365, 8052911324071},+ {1000003, 1000033},+ {0, 1000003},+ {685983, 1927332});+ }+ }+ return params;+}++INSTANTIATE_TEST_SUITE_P(smoke_NGramHashFunction,+ ReferenceNGramHashFunctionTest,+ testing::ValuesIn(generate_params()),+ [](const testing::TestParamInfo<NGramHashFunctionParams>& info) {+ return info.param.name;+ });+} // namespace\ No newline at end of filediff --git a/src/plugins/template/tests/functional/op_reference/sources.cmake b/src/plugins/template/tests/functional/op_reference/sources.cmakeindex e302d8ec7ba..8fd640a01c5 100644--- a/src/plugins/template/tests/functional/op_reference/sources.cmake+++ b/src/plugins/template/tests/functional/op_reference/sources.cmake@@ -138,6 +138,7 @@ set(OV_TEMPLATE_TESTS_OP_REFERENCE_SRCS${CMAKE_CURRENT_LIST_DIR}/multiply.cpp${CMAKE_CURRENT_LIST_DIR}/mvn.cpp${CMAKE_CURRENT_LIST_DIR}/negative.cpp+ ${CMAKE_CURRENT_LIST_DIR}/ngram_hash_function.cpp${CMAKE_CURRENT_LIST_DIR}/nms_rotated.cpp${CMAKE_CURRENT_LIST_DIR}/non_max_suppression.cpp${CMAKE_CURRENT_LIST_DIR}/nonzero.cppdiff --git a/src/tests/functional/base_func_tests/src/base/utils/compare_results.cpp b/src/tests/functional/base_func_tests/src/base/utils/compare_results.cppindex 4cd149451bd..a1ac378381b 100644--- a/src/tests/functional/base_func_tests/src/base/utils/compare_results.cpp+++ b/src/tests/functional/base_func_tests/src/base/utils/compare_results.cpp@@ -4,6 +4,7 @@#include <gtest/gtest.h>+#include "openvino/op/ngram_hash_function.hpp"#include "openvino/op/ops.hpp"#include "ov_ops/augru_cell.hpp"#include "ov_ops/augru_sequence.hpp"@@ -211,6 +212,7 @@ OPENVINO_SUPPRESS_DEPRECATED_START#include "openvino/opsets/opset17_tbl.hpp"#include "ov_ops/opset_private_tbl.hpp"+_OPENVINO_OP_REG(NGramHashFunction, ov::op::internal)#undef _OPENVINO_OP_REG};OPENVINO_SUPPRESS_DEPRECATED_END