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
Attributes matching in a pattern, Synth sugar (#29132)
Evgenya Nugmanova730630236dc3
diff --git a/src/bindings/python/src/openvino/passes/__init__.py b/src/bindings/python/src/openvino/passes/__init__.pyindex 75b2ed23d05..5187c68b8f6 100644--- a/src/bindings/python/src/openvino/passes/__init__.py+++ b/src/bindings/python/src/openvino/passes/__init__.py@@ -14,6 +14,7 @@ from openvino._pyopenvino.passes import (type_matches,type_matches_any,shape_matches,+ attrs_match,)from openvino._pyopenvino.passes import Serialize, ConstantFolding, VisualizeTree, MakeStateful, LowLatency2, ConvertFP32ToFP16, Versionfrom openvino.passes.manager import Managerdiff --git a/src/bindings/python/src/pyopenvino/graph/passes/pattern_ops.cpp b/src/bindings/python/src/pyopenvino/graph/passes/pattern_ops.cppindex 0f6681997bc..3cc58935bfa 100644--- a/src/bindings/python/src/pyopenvino/graph/passes/pattern_ops.cpp+++ b/src/bindings/python/src/pyopenvino/graph/passes/pattern_ops.cpp@@ -18,6 +18,7 @@#include "openvino/pass/pattern/op/pattern.hpp"#include "openvino/pass/pattern/op/wrap_type.hpp"#include "pyopenvino/core/common.hpp"+#include "pyopenvino/utils/utils.hpp"static ov::NodeTypeInfo get_type(const std::string& type_name) {// Supported types: opsetX.OpName or opsetX::OpName@@ -1014,6 +1015,9 @@ inline void reg_predicates(py::module m) {m.def("type_matches", &ov::pass::pattern::type_matches);m.def("type_matches_any", &ov::pass::pattern::type_matches_any);m.def("shape_matches", &ov::pass::pattern::shape_matches);+ m.def("attrs_match", [](py::object& attrs) {+ return ov::pass::pattern::attrs_match(Common::utils::py_object_to_unordered_any_map(attrs));+ });}void reg_passes_pattern_ops(py::module m) {diff --git a/src/bindings/python/src/pyopenvino/utils/utils.cpp b/src/bindings/python/src/pyopenvino/utils/utils.cppindex 8520a5781a8..aa19c20b81d 100644--- a/src/bindings/python/src/pyopenvino/utils/utils.cpp+++ b/src/bindings/python/src/pyopenvino/utils/utils.cpp@@ -411,6 +411,21 @@ ov::AnyMap py_object_to_any_map(const py::object& py_obj) {return return_value;}+std::unordered_map<std::string, ov::Any> py_object_to_unordered_any_map(const py::object& py_obj) {+ OPENVINO_ASSERT(py_object_is_any_map(py_obj), "Unsupported attribute type.");+ std::unordered_map<std::string, ov::Any> return_value = {};+ for (auto& item : py::cast<py::dict>(py_obj)) {+ std::string key = py::cast<std::string>(item.first);+ py::object value = py::cast<py::object>(item.second);+ if (py_object_is_any_map(value)) {+ return_value[key] = Common::utils::py_object_to_any_map(value);+ } else {+ return_value[key] = Common::utils::py_object_to_any(value);+ }+ }+ return return_value;+}+template <typename... Args, std::size_t... I>std::tuple<Args...> tuple_from_py_tuple_impl(const py::tuple& py_tuple, std::index_sequence<I...>) {return std::make_tuple(py_tuple[I].cast<Args>()...);diff --git a/src/bindings/python/src/pyopenvino/utils/utils.hpp b/src/bindings/python/src/pyopenvino/utils/utils.hppindex fc1dbb646ea..86d73d18d1c 100644--- a/src/bindings/python/src/pyopenvino/utils/utils.hpp+++ b/src/bindings/python/src/pyopenvino/utils/utils.hpp@@ -140,6 +140,8 @@ protected:ov::AnyMap py_object_to_any_map(const py::object& py_obj);+ std::unordered_map<std::string, ov::Any> py_object_to_unordered_any_map(const py::object& py_obj);+ov::Any py_object_to_any(const py::object& py_obj);ov::pass::Serialize::Version convert_to_version(const std::string& version);diff --git a/src/bindings/python/tests/test_transformations/test_pattern_ops.py b/src/bindings/python/tests/test_transformations/test_pattern_ops.pyindex 4ce8cadc876..6a381a749c1 100644--- a/src/bindings/python/tests/test_transformations/test_pattern_ops.py+++ b/src/bindings/python/tests/test_transformations/test_pattern_ops.py@@ -16,6 +16,7 @@ from openvino.passes import (type_matches,type_matches_any,shape_matches,+ attrs_match,)from openvino.utils.types import get_element_type@@ -278,6 +279,19 @@ def test_any_input_symbol_predicate():assert symbols["Six"] == 6, symbols+def test_attrs_match():+ param = ops.parameter([-1, -1])++ def test_shape_of_attribute(et: str):+ node = ops.shape_of(param, output_type=et)+ attr = {"output_type": et}+ matcher = Matcher(AnyInput(attrs_match(attr)), "Find shape_of with attribute")+ assert matcher.match(node), f"Match failed for {node} with attribute"++ test_shape_of_attribute("i64")+ test_shape_of_attribute("i32")++def test_optional_full_match():model_input = ops.parameter(PartialShape.dynamic())model_abs = ops.abs(model_input)diff --git a/src/common/transformations/src/transformations/symbolic_transformations/dereshape_matmul.cpp b/src/common/transformations/src/transformations/symbolic_transformations/dereshape_matmul.cppindex 778ab2dbfee..84ff6c2667d 100644--- a/src/common/transformations/src/transformations/symbolic_transformations/dereshape_matmul.cpp+++ b/src/common/transformations/src/transformations/symbolic_transformations/dereshape_matmul.cpp@@ -346,16 +346,12 @@ ov::pass::DeReshapeFullyConnected::DeReshapeFullyConnected() {using namespace ov::op;using namespace ov::pass::pattern;- auto transpose_a_false = [](const std::shared_ptr<Node>& node) -> bool {- auto mm = as_type_ptr<v0::MatMul>(node);- return mm && !mm->get_transpose_a();- };-auto input = wrap_type<v1::Reshape>({any_input(shape_matches("BATCHES_1...,Y")), any_input()},shape_matches("BATCHES_2...,Y"));auto converted = pattern::optional<v0::Convert>(input, consumers_count(1));auto mm_label = wrap_type<v0::MatMul>({converted, any_input(rank_equals(2))},- consumers_count(1) && transpose_a_false && shape_matches("BATCHES_2...,Z"));+ consumers_count(1) && shape_matches("BATCHES_2...,Z"),+ {{"transpose_a", false}});auto output = wrap_type<v1::Reshape>({mm_label, any_input()}, shape_matches("BATCHES_1...,Z"));ov::matcher_pass_callback matcher_pass_callback = [=](Matcher& m) {diff --git a/src/core/include/openvino/core/attribute_adapter.hpp b/src/core/include/openvino/core/attribute_adapter.hppindex ec1c8dd992a..240ddd056c2 100644--- a/src/core/include/openvino/core/attribute_adapter.hpp+++ b/src/core/include/openvino/core/attribute_adapter.hpp@@ -171,6 +171,7 @@ public:OPENVINO_THROW("Bad cast from: ", x.type_info().name(), " to: ", typeid(AT).name());}}+operator AT&() {return m_ref;}diff --git a/src/core/include/openvino/pass/pattern/op/label.hpp b/src/core/include/openvino/pass/pattern/op/label.hppindex c535c91ecf5..4e45fbb1130 100644--- a/src/core/include/openvino/pass/pattern/op/label.hpp+++ b/src/core/include/openvino/pass/pattern/op/label.hpp@@ -72,9 +72,11 @@ protected:};} // namespace op-OPENVINO_API std::shared_ptr<Node> any_input();+OPENVINO_API std::shared_ptr<Node> any_input(const Attributes& attrs = {});-template <typename TPredicate>+template <typename TPredicate,+ typename std::enable_if_t<std::is_constructible_v<op::Predicate, TPredicate> &&+ !std::is_constructible_v<Attributes, TPredicate>>* = nullptr>std::shared_ptr<Node> any_input(const TPredicate& pred) {return std::make_shared<pattern::op::Label>(element::dynamic, PartialShape::dynamic(), op::Predicate(pred));}diff --git a/src/core/include/openvino/pass/pattern/op/op.hpp b/src/core/include/openvino/pass/pattern/op/op.hppnew file mode 100644index 00000000000..361d4a75fb6--- /dev/null+++ b/src/core/include/openvino/pass/pattern/op/op.hpp@@ -0,0 +1,68 @@+// Copyright (C) 2018-2025 Intel Corporation+// SPDX-License-Identifier: Apache-2.0+//++#pragma once++#include "openvino/op/constant.hpp"+#include "openvino/pass/pattern/op/or.hpp"+#include "openvino/pass/pattern/op/predicate.hpp"++namespace ov::pass::pattern {+// A glue/syntax-sugar type which allows more types to be used as input to pattern operations+struct OPENVINO_API PatternOp {+private:+ std::shared_ptr<ov::Node> op;+ int64_t output_idx = -1;++public:+ operator ov::Output<ov::Node>() const;+ ov::Output<ov::Node> get_output() const;++ PatternOp(const Output<Node>& out);++ template <typename T, typename std::enable_if_t<std::is_base_of_v<ov::Node, T>>* = nullptr>+ PatternOp(const std::shared_ptr<T>& op) : op(std::dynamic_pointer_cast<ov::Node>(op)) {}++ PatternOp(const std::shared_ptr<Node>& op);+ PatternOp(ov::Rank rank);++ // Constant matching+ PatternOp(const char* value_notation);+ PatternOp(std::string value_notation);+ PatternOp(int v);+ PatternOp(float v);+ PatternOp(double v);+ PatternOp(long long v);++ PatternOp(std::initializer_list<const char*>&& v);+ PatternOp(std::initializer_list<const std::string>&& v);+ PatternOp(std::initializer_list<const int>&& v);+ PatternOp(std::initializer_list<const float>&& v);+ PatternOp(std::initializer_list<const double>&& v);+ PatternOp(std::initializer_list<const long long>&& v);+};++// Syntax-sugar type for pattern operators to consume all the different ways to pass containter of inputs with use of+// PatternOp+struct OPENVINO_API PatternOps {+private:+ std::vector<PatternOp> data;++public:+ PatternOps();++ // single element+ template <typename T, typename std::enable_if_t<std::is_constructible_v<PatternOp, T>>* = nullptr>+ PatternOps(const T& in) : data{PatternOp(in)} {};+ PatternOps(const std::shared_ptr<Node>&);+ PatternOps(const Output<Node>&);++ // multi-element+ PatternOps(const OutputVector&);+ PatternOps(std::initializer_list<pattern::PatternOp>&&);++ explicit operator ov::OutputVector() const;+};++} // namespace ov::pass::pattern\ No newline at end of filediff --git a/src/core/include/openvino/pass/pattern/op/optional.hpp b/src/core/include/openvino/pass/pattern/op/optional.hppindex 5491f3f6bbd..093ce793713 100644--- a/src/core/include/openvino/pass/pattern/op/optional.hpp+++ b/src/core/include/openvino/pass/pattern/op/optional.hpp@@ -4,6 +4,7 @@#pragma once+#include "openvino/pass/pattern/op/op.hpp"#include "openvino/pass/pattern/op/pattern.hpp"namespace ov::pass::pattern {@@ -84,37 +85,33 @@ void collect_type_info(std::vector<DiscreteTypeInfo>& type_info_vec) {collect_type_info<NodeTypeArgs...>(type_info_vec);}-template <class... NodeTypes, typename TPredicate>-std::shared_ptr<Node> optional(const OutputVector& inputs, const TPredicate& pred) {+template <class... NodeTypes,+ typename TPredicate,+ typename std::enable_if_t<std::is_constructible_v<op::Predicate, TPredicate>>* = nullptr>+std::shared_ptr<Node> optional(const PatternOps& inputs, const TPredicate& pred, const Attributes& attrs = {}) {std::vector<DiscreteTypeInfo> optional_type_info_vec;collect_type_info<NodeTypes...>(optional_type_info_vec);- return std::make_shared<op::Optional>(optional_type_info_vec, inputs, op::Predicate(pred));-}--template <class... NodeTypes, typename TPredicate>-std::shared_ptr<Node> optional(const Output<Node>& input, const TPredicate& pred) {- return optional<NodeTypes...>(OutputVector{input}, op::Predicate(pred));+ return std::make_shared<op::Optional>(+ optional_type_info_vec,+ ov::OutputVector(inputs),+ attrs.empty() ? op::Predicate(pred) : attrs_match(attrs) && op::Predicate(pred));}template <class... NodeTypes,typename TPredicate,- typename std::enable_if_t<std::is_constructible_v<op::Predicate, TPredicate>>* = nullptr>-std::shared_ptr<Node> optional(const TPredicate& pred) {- return optional<NodeTypes...>(OutputVector{}, op::Predicate(pred));-}--template <class... NodeTypes>-std::shared_ptr<Node> optional(const OutputVector& inputs) {- return optional<NodeTypes...>(inputs, op::Predicate());+ typename std::enable_if_t<std::is_constructible_v<op::Predicate, TPredicate> &&+ !std::is_constructible_v<std::vector<PatternOp>, TPredicate>>* = nullptr>+std::shared_ptr<Node> optional(const TPredicate& pred, const Attributes& attrs = {}) {+ return optional<NodeTypes...>(OutputVector{}, op::Predicate(pred), attrs);}template <class... NodeTypes>-std::shared_ptr<Node> optional(const Output<Node>& input) {- return optional<NodeTypes...>(OutputVector{input}, op::Predicate());+std::shared_ptr<Node> optional(const PatternOps& inputs = {}, const Attributes& attrs = {}) {+ return optional<NodeTypes...>(inputs, attrs.empty() ? op::Predicate() : attrs_match(attrs));}template <class... NodeTypes>-std::shared_ptr<Node> optional() {- return optional<NodeTypes...>(OutputVector{}, op::Predicate());+std::shared_ptr<Node> optional(std::initializer_list<std::pair<const std::string, ov::Any>>&& attrs) {+ return optional<NodeTypes...>(OutputVector{}, attrs);}} // namespace ov::pass::patterndiff --git a/src/core/include/openvino/pass/pattern/op/or.hpp b/src/core/include/openvino/pass/pattern/op/or.hppindex 4b6eeda9667..9ff8c68fd6a 100644--- a/src/core/include/openvino/pass/pattern/op/or.hpp+++ b/src/core/include/openvino/pass/pattern/op/or.hpp@@ -7,7 +7,8 @@#include "openvino/core/node.hpp"#include "openvino/pass/pattern/op/pattern.hpp"-namespace ov::pass::pattern::op {+namespace ov::pass {+namespace pattern::op {/// A submatch on the graph value is performed on each input to the Or; the match/// succeeds on the first match. Otherwise the match fails.class OPENVINO_API Or : public Pattern {@@ -22,4 +23,7 @@ public:const Output<Node>& pattern_value,const Output<Node>& graph_value) override;};-} // namespace ov::pass::pattern::op+} // namespace pattern::op+OPENVINO_API std::shared_ptr<Node> operator|(const Output<Node>& lhs, const Output<Node>& rhs);+OPENVINO_API std::shared_ptr<Node> operator|(const std::shared_ptr<Node>& lhs, const std::shared_ptr<Node>& rhs);+} // namespace ov::pass\ No newline at end of filediff --git a/src/core/include/openvino/pass/pattern/op/pattern.hpp b/src/core/include/openvino/pass/pattern/op/pattern.hppindex d76289408cf..97657729989 100644--- a/src/core/include/openvino/pass/pattern/op/pattern.hpp+++ b/src/core/include/openvino/pass/pattern/op/pattern.hpp@@ -22,6 +22,7 @@ using PatternValueMap = std::map<std::shared_ptr<Node>, Output<Node>>;using PatternValueMaps = std::vector<PatternValueMap>;using PatternMap = std::map<std::shared_ptr<Node>, std::shared_ptr<Node>>;+using Attributes = std::unordered_map<std::string, ov::Any>;PatternMap as_pattern_map(const PatternValueMap& pattern_value_map);PatternValueMap as_pattern_value_map(const PatternMap& pattern_map);@@ -61,7 +62,10 @@ OPENVINO_API op::Predicate type_matches_any(const std::vector<element::Type>& tyOPENVINO_API op::Predicate all_of(const std::vector<std::function<bool(Output<Node>)>>& predicates);+OPENVINO_API op::Predicate attrs_match(const Attributes& expected_attrs);+OPENVINO_API op::Predicate shape_matches(const std::string& shape_notation);+OPENVINO_API op::Predicate value_matches(const std::string& value_notation);namespace op {OPENVINO_DEPRECATED("This method is deprecated. Use constructor of ov::pass::pattern::Predicate instead")diff --git a/src/core/include/openvino/pass/pattern/op/predicate.hpp b/src/core/include/openvino/pass/pattern/op/predicate.hppindex 2ffd5844024..9f795e5e18f 100644--- a/src/core/include/openvino/pass/pattern/op/predicate.hpp+++ b/src/core/include/openvino/pass/pattern/op/predicate.hpp@@ -38,6 +38,12 @@ public:const std::vector<PatternSymbolValue>& g() const;bool operator==(const PatternSymbolValue& other) const;+ bool operator!=(const PatternSymbolValue& other) const;++ template <typename T, typename std::enable_if_t<std::is_constructible_v<PatternSymbolValue, T>>* = nullptr>+ static std::vector<PatternSymbolValue> make_value_vector(const std::vector<T>& v) {+ return {v.begin(), v.end()};+ }private:bool is_valid() const;diff --git a/src/core/include/openvino/pass/pattern/op/wrap_type.hpp b/src/core/include/openvino/pass/pattern/op/wrap_type.hppindex df3a6c6251e..eb6917afabd 100644--- a/src/core/include/openvino/pass/pattern/op/wrap_type.hpp+++ b/src/core/include/openvino/pass/pattern/op/wrap_type.hpp@@ -6,6 +6,7 @@#include "openvino/core/node.hpp"#include "openvino/op/constant.hpp"+#include "openvino/pass/pattern/op/op.hpp"#include "openvino/pass/pattern/op/pattern.hpp"namespace ov::pass::pattern {@@ -63,20 +64,33 @@ void collect_wrap_info(std::vector<DiscreteTypeInfo>& info) {collect_wrap_info<Targs...>(info);}-template <class... Args, typename TPredicate>-std::shared_ptr<Node> wrap_type(const OutputVector& inputs, const TPredicate& pred) {+template <class... Args,+ typename TPredicate,+ typename std::enable_if_t<std::is_constructible_v<op::Predicate, TPredicate>>* = nullptr>+std::shared_ptr<Node> wrap_type(const PatternOps& inputs, const TPredicate& pred, const Attributes& attrs = {}) {std::vector<DiscreteTypeInfo> info;collect_wrap_info<Args...>(info);- return std::make_shared<op::WrapType>(info, op::Predicate(pred), inputs);+ return std::make_shared<op::WrapType>(+ info,+ (attrs.empty() ? op::Predicate(pred) : attrs_match(attrs) && op::Predicate(pred)),+ ov::OutputVector(inputs));+}++template <class... Args,+ typename TPredicate,+ typename std::enable_if_t<std::is_constructible_v<op::Predicate, TPredicate> &&+ !std::is_constructible_v<PatternOps, TPredicate>>* = nullptr>+std::shared_ptr<Node> wrap_type(const TPredicate& pred, const Attributes& attrs = {}) {+ return wrap_type<Args...>(PatternOps{}, op::Predicate(pred), attrs);}template <class... Args>-std::shared_ptr<Node> wrap_type(const OutputVector& inputs = {}) {- return wrap_type<Args...>(inputs, op::Predicate());+std::shared_ptr<Node> wrap_type(const PatternOps& inputs = {}, const Attributes& attrs = {}) {+ return wrap_type<Args...>(inputs, (attrs.empty() ? op::Predicate() : attrs_match(attrs)));}-template <class... Args, typename TPredicate>-std::shared_ptr<Node> wrap_type(const TPredicate& pred) {- return wrap_type<Args...>({}, op::Predicate(pred));+template <class... Args>+std::shared_ptr<Node> wrap_type(std::initializer_list<std::pair<const std::string, ov::Any>>&& attrs) {+ return wrap_type<Args...>(PatternOps{}, Attributes(attrs));}} // namespace ov::pass::patterndiff --git a/src/core/src/pattern/op/label.cpp b/src/core/src/pattern/op/label.cppindex 3b4ec752276..6bb1bc02710 100644--- a/src/core/src/pattern/op/label.cpp+++ b/src/core/src/pattern/op/label.cpp@@ -54,6 +54,6 @@ bool ov::pass::pattern::op::Label::match_value(ov::pass::pattern::Matcher* matchreturn false;}-std::shared_ptr<ov::Node> ov::pass::pattern::any_input() {- return std::make_shared<pattern::op::Label>();+std::shared_ptr<ov::Node> ov::pass::pattern::any_input(const Attributes& attrs) {+ return attrs.empty() ? std::make_shared<pattern::op::Label>() : any_input(attrs_match(attrs));}diff --git a/src/core/src/pattern/op/op.cpp b/src/core/src/pattern/op/op.cppnew file mode 100644index 00000000000..89b9d688800--- /dev/null+++ b/src/core/src/pattern/op/op.cpp@@ -0,0 +1,62 @@+// Copyright (C) 2018-2025 Intel Corporation+// SPDX-License-Identifier: Apache-2.0+//++#include "openvino/pass/pattern/op/op.hpp"++#include "openvino/op/constant.hpp"+#include "openvino/pass/pattern/op/label.hpp"+#include "openvino/pass/pattern/op/wrap_type.hpp"+#include "openvino/util/common_util.hpp"++namespace ov::pass::pattern {+PatternOp::operator ov::Output<ov::Node>() const {+ return get_output();+}++ov::Output<ov::Node> PatternOp::get_output() const {+ if (output_idx >= 0)+ return op->output(output_idx);+ return op->get_default_output();+}++PatternOp::PatternOp(const Output<Node>& out) : op(out.get_node_shared_ptr()), output_idx(out.get_index()) {}++PatternOp::PatternOp(const std::shared_ptr<Node>& op) : op(op) {}++PatternOp::PatternOp(ov::Rank rank) {+ op = any_input(rank_equals(rank));+}++PatternOp::PatternOp(std::string value_notation) {+ op = wrap_type<ov::op::v0::Constant>(value_matches(value_notation));+}++PatternOp::PatternOp(const char* value_notation) : PatternOp(std::string(value_notation)) {}++PatternOp::PatternOp(int v) : PatternOp(std::to_string(v)) {}+PatternOp::PatternOp(float v) : PatternOp(std::to_string(v)) {}+PatternOp::PatternOp(double v) : PatternOp(std::to_string(v)) {}+PatternOp::PatternOp(long long v) : PatternOp(std::to_string(v)) {}++PatternOp::PatternOp(std::initializer_list<const char*>&& v) : PatternOp(ov::util::join(v)) {}+PatternOp::PatternOp(std::initializer_list<const std::string>&& v) : PatternOp(ov::util::join(v)) {}+PatternOp::PatternOp(std::initializer_list<const int>&& v) : PatternOp(ov::util::join(v)) {}+PatternOp::PatternOp(std::initializer_list<const float>&& v) : PatternOp(ov::util::join(v)) {}+PatternOp::PatternOp(std::initializer_list<const double>&& v) : PatternOp(ov::util::join(v)) {}+PatternOp::PatternOp(std::initializer_list<const long long>&& v) : PatternOp(ov::util::join(v)) {}++PatternOps::PatternOps() : data{} {}+PatternOps::PatternOps(const std::shared_ptr<Node>& op) : data{PatternOp(op)} {}+PatternOps::PatternOps(const Output<Node>& out) : data{PatternOp(out)} {}++PatternOps::PatternOps(const OutputVector& outputs) : data{outputs.begin(), outputs.end()} {}+PatternOps::PatternOps(std::initializer_list<PatternOp>&& outputs) : data(outputs) {}++PatternOps::operator ov::OutputVector() const {+ OutputVector args;+ for (auto& in : data)+ args.push_back(in.get_output());+ return args;+}+} // namespace ov::pass::pattern\ No newline at end of filediff --git a/src/core/src/pattern/op/or.cpp b/src/core/src/pattern/op/or.cppindex 81686c1ca58..86b6812015b 100644--- a/src/core/src/pattern/op/or.cpp+++ b/src/core/src/pattern/op/or.cpp@@ -27,3 +27,12 @@ bool ov::pass::pattern::op::Or::match_value(Matcher* matcher,OPENVINO_LOG_OR5(matcher);return false;}++std::shared_ptr<ov::Node> ov::pass::operator|(const ov::Output<ov::Node>& lhs, const ov::Output<ov::Node>& rhs) {+ return std::make_shared<ov::pass::pattern::op::Or>(ov::OutputVector{lhs, rhs});+}++std::shared_ptr<ov::Node> ov::pass::operator|(const std::shared_ptr<ov::Node>& lhs,+ const std::shared_ptr<ov::Node>& rhs) {+ return std::make_shared<pattern::op::Or>(OutputVector{lhs->get_default_output(), rhs->get_default_output()});+}diff --git a/src/core/src/pattern/op/pattern.cpp b/src/core/src/pattern/op/pattern.cppindex 2108d742b13..e1faf5cbaab 100644--- a/src/core/src/pattern/op/pattern.cpp+++ b/src/core/src/pattern/op/pattern.cpp@@ -5,9 +5,12 @@#include "openvino/pass/pattern/op/pattern.hpp"#include <algorithm>+#include <optional>#include <regex>+#include "openvino/op/constant.hpp"#include "openvino/util/common_util.hpp"+#include "openvino/util/log.hpp"namespace ov::pass::pattern {namespace op {@@ -181,6 +184,127 @@ op::Predicate all_of(const std::vector<std::function<bool(Output<Node>)>>& predi"all_of(...)");}+namespace {+#define ACCESSOR(type) \+ void on_adapter(const std::string& name, ValueAccessor<type>& adapter) override { match(name, {adapter.get()}); };++#define ACCESSOR_V(type) ACCESSOR(type) ACCESSOR(std::vector<type>)++class AttributeMatchingVisitor : public ov::AttributeVisitor {+public:+ explicit AttributeMatchingVisitor(const Attributes& expected_attrs)+ : ov::AttributeVisitor(),+ m_expected_attrs{expected_attrs} {+ OPENVINO_ASSERT(!expected_attrs.empty(), "Please remove trivial attribute matching check");+ for (const auto& [name, expected_value] : expected_attrs)+ m_matched_attributes[name] = false;+ }++ ACCESSOR(bool)+ ACCESSOR_V(std::string)+ ACCESSOR_V(int8_t)+ ACCESSOR_V(int16_t)+ ACCESSOR_V(int32_t)+ ACCESSOR_V(int64_t)+ ACCESSOR_V(uint8_t)+ ACCESSOR_V(uint16_t)+ ACCESSOR_V(uint32_t)+ ACCESSOR_V(uint64_t)+ ACCESSOR_V(float)+ ACCESSOR_V(double)++ void on_adapter(const std::string& name, ValueAccessor<void>& adapter) override {+ OPENVINO_THROW_NOT_IMPLEMENTED("Can not compare void");+ };+ void on_adapter(const std::string& name, ValueAccessor<void*>& adapter) override {+ OPENVINO_THROW_NOT_IMPLEMENTED("Can not compare void*");+ };+ void on_adapter(const std::string& name, ValueAccessor<std::shared_ptr<ov::Model>>& adapter) override {+ OPENVINO_THROW_NOT_IMPLEMENTED("Can not compare models");+ };++ void match(const std::string& name, const ov::Any& node_attribute) {+ if (m_expected_attrs.count(name)) {+ try {+ const auto& attribute_type_id = node_attribute.type_info();++ auto expected_attribute = m_expected_attrs.at(name);+ const auto& expected_type_id = expected_attribute.type_info();++ if (attribute_type_id != expected_type_id) { // type conversions for developer convenience+ if (attribute_type_id == typeid(int64_t) && expected_type_id == typeid(int))+ expected_attribute = ov::Any(static_cast<int64_t>(expected_attribute.as<int>()));+ if (attribute_type_id == typeid(std::string) && expected_type_id == typeid(const char*))+ expected_attribute = ov::Any(std::string(expected_attribute.as<const char*>()));+ if (attribute_type_id == typeid(bool) && expected_type_id == typeid(int))+ expected_attribute = ov::Any(static_cast<bool>(expected_attribute.as<int>()));+ if (attribute_type_id == typeid(double) && expected_type_id == typeid(int))+ expected_attribute = ov::Any(static_cast<double>(expected_attribute.as<int>()));+ if (attribute_type_id == typeid(double) && expected_type_id == typeid(float))+ expected_attribute = ov::Any(static_cast<double>(expected_attribute.as<float>()));+ }++ if (node_attribute.type_info() != expected_attribute.type_info())+ OPENVINO_DEBUG(" Attribute `",+ name,+ "` -- data type does not match. Node attribute type: ",+ node_attribute.type_info().name(),+ ". Expected attribute type: ",+ expected_attribute.type_info().name());+ bool status = node_attribute == expected_attribute;+ if (!status)+ OPENVINO_DEBUG(" Attribute `", name, "` -- value does not match. ", [&]() {+ std::stringstream ss;+ node_attribute.print(ss);+ ss << " vs ";+ expected_attribute.print(ss);+ return ss.str();+ }());+ m_matched_attributes[name] = status;+ } catch (...) {+ OPENVINO_DEBUG(" Attribute `", name, "` matching went wrong");+ m_matched_attributes[name] = false;+ }+ } else {+ OPENVINO_DEBUG(" Node attribute `", name, "` is not being compared");+ }+ }++ bool get_match_status() const {+ // TODO: provide additional logging in case of failure; however the on_adapter method is already logging a lot+ return std::all_of(m_matched_attributes.begin(), m_matched_attributes.end(), [](const auto& name_to_val) {+ return name_to_val.second == true;+ });+ }++private:+ const Attributes& m_expected_attrs;+ std::unordered_map<std::string, bool> m_matched_attributes;+};+} // namespace++op::Predicate attrs_match(const Attributes& expected_attrs) {+ std::stringstream ss;+ ss << "{ ";+ bool first = true;+ for (const auto& [key, value] : expected_attrs) {+ if (!first)+ ss << ", ";+ first = false;+ ss << key << ": ";+ value.print(ss);+ }+ ss << " }";+ return op::Predicate(+ [expected_attrs](PatternSymbolMap&, const Output<Node>& output) -> bool {+ const auto& node = output.get_node_shared_ptr();+ AttributeMatchingVisitor visitor(expected_attrs);+ node->visit_attributes(visitor);+ return visitor.get_match_status();+ },+ "attrs_match(" + ss.str() + ")");+}+namespace {bool ends_with(std::string_view str, std::string_view suffix) {return str.size() >= suffix.size() && str.compare(str.size() - suffix.size(), suffix.size(), suffix) == 0;@@ -231,14 +355,24 @@ std::pair<std::vector<std::pair<int64_t, std::string>>, int64_t> parse_notation(return {idx_to_name, (ellipsis_visited ? -2 : idx_to_name.size())};}-std::pair<bool, int64_t> str2int(const std::string& str) {+std::optional<int64_t> str2int(const std::string& str) {auto s = str.c_str();char* end;int64_t l;l = strtol(s, &end, 10);if (*s == '\0' || *end != '\0')- return {1, 0};- return {0, l};+ return {};+ return {l};+}++std::optional<double> str2double(const std::string& str) {+ auto s = str.c_str();+ char* end;+ double d;+ d = strtod(s, &end);+ if (*s == '\0' || *end != '\0')+ return {};+ return {d};}struct GroupDetails {@@ -250,6 +384,14 @@ struct GroupDetails {}};+const PatternSymbolValue& get_element(const std::vector<PatternSymbolValue>& values, int64_t idx) {+ auto size = static_cast<int64_t>(values.size());+ if (idx < 0)+ idx += size;+ OPENVINO_ASSERT(idx < size, "Unexpected index");+ return values[static_cast<size_t>(idx)];+}+} // namespace/**@@ -279,99 +421,93 @@ struct GroupDetails {*/op::Predicate shape_matches(const std::string& shape_notation) {auto item = parse_notation(shape_notation);- const auto& idx_to_name = item.first;+ const auto& position_to_name = item.first;const auto& rank_restrictions = item.second;return op::Predicate(- [idx_to_name, rank_restrictions](PatternSymbolMap& m, const Output<Node>& output) -> bool {+ [position_to_name, rank_restrictions](PatternSymbolMap& m, const Output<Node>& output) -> bool {const auto& shape = output.get_partial_shape();if (rank_restrictions == 0) // scalarreturn shape.is_static() && shape.size() == 0;if (rank_restrictions == -1) // fully dynamicreturn shape.rank().is_dynamic();- if (rank_restrictions == -2 && (shape.rank().is_dynamic() || shape.size() + 1 < idx_to_name.size()))- // minimum rank check; checking shape.size() + 1 because idx_to_name contains a record with group that- // may match to an empty set of dimensions+ if (rank_restrictions == -2 && (shape.rank().is_dynamic() || shape.size() + 1 < position_to_name.size()))+ // minimum rank check; checking shape.size() + 1 because position_to_name contains a record with group+ // that may match to an empty set of dimensionsreturn false;if (rank_restrictions > 0 &&(shape.rank().is_dynamic() || static_cast<int64_t>(shape.size()) != rank_restrictions))return false;PatternSymbolMap local_m;GroupDetails group;- for (const auto& [this_dim_idx, name] : idx_to_name) {- if (name == "?" || name == "...")+ for (const auto& [position, expected_as_string] : position_to_name) {+ if (!group.name.empty() && position < group.end)+ // placement is intentional -- record end of the group even if ? is placed after the group+ // after epsilon all positions are negative (python style)+ group.end = position;+ if (expected_as_string == "?" || expected_as_string == "...")continue;- if (ends_with(name, "...")) { // named group detected- group.name = {name.substr(0, name.size() - 3)};- group.begin = this_dim_idx;+ if (ends_with(expected_as_string, "...")) { // named group detected+ group.name = {expected_as_string.substr(0, expected_as_string.size() - 3)};+ group.begin = position;continue;}- if (!group.name.empty() && this_dim_idx < group.end)- group.end = this_dim_idx;- const auto& this_dim = shape[this_dim_idx];- const auto& [conversion_failed, converted_int] = str2int(name);- if (conversion_failed) { // failed the conversion -- this is a name++ const auto& actual_dim = shape[position];+ const auto& actual_value = actual_dim.is_static() ? PatternSymbolValue(actual_dim.get_length())+ : PatternSymbolValue(actual_dim.get_symbol());+ const auto& converted_int = str2int(expected_as_string);+ if (!converted_int) { // failed the conversion -- this is a name+ const auto& name = expected_as_string;if (m.count(name) || local_m.count(name)) {const auto& recorded_value = m.count(name) ? m.at(name) : local_m.at(name);- if (recorded_value.is_dynamic()) {- const auto& recorded_symbol = recorded_value.s();- if (!ov::symbol::are_equal(recorded_symbol, this_dim.get_symbol()))- return false;- } else if (recorded_value.is_integer()) {- if (this_dim.is_dynamic() || this_dim.get_length() != recorded_value.i())- return false;- } else {+ if (actual_value != recorded_value)return false;- }} else {- if (this_dim.is_static())- local_m[name] = {static_cast<int64_t>(this_dim.get_length())};- else if (auto symbol = this_dim.get_symbol())- local_m[name] = {symbol};+ if (actual_dim.is_static() || actual_dim.get_symbol() != nullptr)+ local_m[name] = actual_value;elsereturn false;}} else { // this_dim is not a name, but an integer- if (this_dim.is_dynamic() || this_dim.get_length() != converted_int)+ if (actual_dim.is_dynamic() || actual_dim.get_length() != converted_int.value())return false;}}- if (!group.name.empty()) {+ if (!group.name.empty()) { // named group functionality used+ OPENVINO_ASSERT(group.end <= 0);+ // after epsilon all positions are negative (python style)+ // end == 0 means group is placed at the end of the notationconst auto& shape_rank = shape.rank().get_length();- OPENVINO_ASSERT(group.end <= 0); // end == 0 means group is placed at the end of the notationgroup.end = group.end + shape_rank;if (m.count(group.name) || local_m.count(group.name)) {const auto& recorded_value = m.count(group.name) ? m.at(group.name) : local_m.at(group.name);OPENVINO_ASSERT(recorded_value.is_group(),- "Mixing group and non group symbolic predicate notation");+ "Mixing group and non-group symbolic predicate notation");+ // group notation -- "Name..." and non-group notation "Name" are mutually exclusive+ // group and non-group namespace is intentionally sharedconst auto& recorded_group = recorded_value.g();if (recorded_group.size() != group.size())return false;for (size_t i = 0; i < recorded_group.size(); ++i) {- const auto& recorded_i = recorded_group[i];- const auto& this_dim = shape[static_cast<std::ptrdiff_t>(group.begin + i)];- if (recorded_i.is_dynamic()) {- const auto& recorded_symbol = recorded_i.s();- if (!ov::symbol::are_equal(recorded_symbol, this_dim.get_symbol()))- return false;- } else if (recorded_i.is_integer()) {- if (this_dim.is_dynamic() || this_dim.get_length() != recorded_i.i())- return false;- } else {+ const auto& actual_dim = shape[static_cast<std::ptrdiff_t>(group.begin + i)];+ if (actual_dim.is_dynamic() && !actual_dim.get_symbol())+ return false;+ const auto& actual_value = actual_dim.is_static() ? PatternSymbolValue(actual_dim.get_length())+ : PatternSymbolValue(actual_dim.get_symbol());+ if (recorded_group[i] != actual_value)return false;- }}} else {std::vector<PatternSymbolValue> group_value;for (size_t i = 0; i < group.size(); ++i) {- const auto& this_dim = shape[static_cast<std::ptrdiff_t>(group.begin + i)];- if (this_dim.is_static())- group_value.emplace_back(static_cast<int64_t>(this_dim.get_length()));- else if (auto symbol = this_dim.get_symbol())- group_value.emplace_back(symbol);- else+ const auto& actual_dim = shape[static_cast<std::ptrdiff_t>(group.begin + i)];+ if (actual_dim.is_dynamic() && !actual_dim.get_symbol())return false;+ const auto& actual_value = actual_dim.is_static() ? PatternSymbolValue(actual_dim.get_length())+ : PatternSymbolValue(actual_dim.get_symbol());+ group_value.emplace_back(actual_value);}local_m[group.name] = group_value;}@@ -384,4 +520,105 @@ op::Predicate shape_matches(const std::string& shape_notation) {},"shape_matches('" + shape_notation + "')");}++op::Predicate value_matches(const std::string& value_notation) {+ auto item = parse_notation(value_notation);+ const auto& position_to_name = item.first;+ const auto& element_count_restrictions = item.second;+ return op::Predicate(+ [position_to_name, element_count_restrictions](PatternSymbolMap& m, const Output<Node>& output) -> bool {+ 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();+ const auto& element_count = shape_size(shape);+ if (element_count_restrictions == 0) // empty+ return element_count == 0;+ if (element_count_restrictions == -1) // fully dynamic (impossible to have dynamic number of elements)+ return false;+ if (element_count_restrictions == -2 && element_count + 1 < position_to_name.size())+ // minimum num element check; checking element_count + 1 because idx_to_name contains a record with+ // group that may match to an empty set of elements+ return false;+ if (element_count_restrictions > 0 && static_cast<int64_t>(element_count) != element_count_restrictions)+ return false;++ const auto& et = constant->get_element_type();+ if (!et.is_integral() && !et.is_real())+ return false;+ bool is_integral = constant->get_element_type().is_integral();+ const auto& values = is_integral ? PatternSymbolValue::make_value_vector(constant->cast_vector<int64_t>())+ : PatternSymbolValue::make_value_vector(constant->cast_vector<double>());++ PatternSymbolMap local_m;+ GroupDetails group;+ for (const auto& [position, expected_as_string] : position_to_name) {+ if (!group.name.empty() && position < group.end)+ // placement is intentional -- record end of the group even if ? is placed after the group+ // after epsilon all positions are negative (python style)+ group.end = position;+ if (expected_as_string == "?" || expected_as_string == "...")+ continue;+ if (ends_with(expected_as_string, "...")) { // named group detected+ group.name = {expected_as_string.substr(0, expected_as_string.size() - 3)};+ group.begin = position;+ continue;+ }+ const auto& actual_value = get_element(values, position);+ const auto& converted_int = str2int(expected_as_string);+ const auto& converted_double = str2double(expected_as_string);+ if (!converted_int && !converted_double) { // failed the conversion -- this is a name+ const auto& name = expected_as_string;+ if (m.count(name) || local_m.count(name)) {+ // we have encountered the value under same name -- comparing it with the actual value+ const auto& recorded_value = m.count(name) ? m.at(name) : local_m.at(name);+ if (recorded_value != actual_value)+ return false;+ } else {+ OPENVINO_ASSERT(actual_value.is_integer() || actual_value.is_double());+ local_m[name] = actual_value;+ }+ } else if (converted_int) { // comparison to static integer value was requested+ if (actual_value != PatternSymbolValue(converted_int.value()))+ return false;+ } else if (converted_double) { // comparison to static double value was requested+ if (actual_value != PatternSymbolValue(converted_double.value()))+ return false;+ }+ }++ if (!group.name.empty()) { // named group functionality used+ OPENVINO_ASSERT(group.end <= 0);+ // after epsilon all positions are negative (python style)+ // end == 0 means group is placed last in the notation string+ group.end = group.end + element_count;++ if (m.count(group.name) || local_m.count(group.name)) {+ const auto& recorded_value = m.count(group.name) ? m.at(group.name) : local_m.at(group.name);+ OPENVINO_ASSERT(recorded_value.is_group(),+ "Mixing group and non-group symbolic predicate notation");+ // group notation -- "Name..." and non-group notation "Name" are mutually exclusive+ // group and non-group namespace is shared+ const auto& recorded_group = recorded_value.g();+ if (recorded_group.size() != group.size())+ return false;+ for (size_t i = 0; i < recorded_group.size(); ++i)+ if (get_element(values, group.begin + i) != recorded_group[i])+ return false;+ } else {+ std::vector<PatternSymbolValue> group_value;+ for (size_t i = 0; i < group.size(); ++i)+ group_value.emplace_back(get_element(values, group.begin + i));+ local_m[group.name] = group_value;+ }+ }++ // only write locally collected data to the global map when the match is complete to avoid partially+ // collected data for the case when Predicate::operator|| was used+ m.insert(local_m.begin(), local_m.end());+ return true;+ },+ "value_matches('" + value_notation + "')");+}} // namespace ov::pass::patterndiff --git a/src/core/src/pattern/op/predicate.cpp b/src/core/src/pattern/op/predicate.cppindex 2044fef377c..20d55a54c27 100644--- a/src/core/src/pattern/op/predicate.cpp+++ b/src/core/src/pattern/op/predicate.cpp@@ -59,7 +59,21 @@ bool PatternSymbolValue::is_valid() const {}bool PatternSymbolValue::operator==(const ov::pass::pattern::PatternSymbolValue& other) const {- return m_value == other.m_value;+ if (is_integer() && other.is_double()) {+ return std::fabs(static_cast<double>(i()) - other.d()) < 1e-5;+ } else if (is_double() && other.is_integer()) {+ return std::fabs(d() - static_cast<double>(other.i())) < 1e-5;+ } else if (is_double() && other.is_double()) {+ return std::fabs(d() - other.d()) < 1e-5;+ } else if (is_dynamic() && other.is_dynamic()) {+ return ov::symbol::are_equal(s(), other.s());+ } else {+ return m_value == other.m_value;+ }+}++bool PatternSymbolValue::operator!=(const ov::pass::pattern::PatternSymbolValue& other) const {+ return !(*this == other);}namespace op {@@ -70,7 +84,7 @@ constexpr bool symbol_true_predicate(pass::pattern::PatternSymbolMap&, const Out}} // namespace-Predicate::Predicate() : m_pred(symbol_true_predicate) {}+Predicate::Predicate() : m_name("always_true"), m_pred(symbol_true_predicate) {}Predicate::Predicate(std::nullptr_t) : Predicate() {}bool Predicate::operator()(pass::pattern::PatternSymbolMap& m, const Output<Node>& output) const {diff --git a/src/core/tests/pattern.cpp b/src/core/tests/pattern.cppindex 77a49cb3a85..1a0defc40e4 100644--- a/src/core/tests/pattern.cpp+++ b/src/core/tests/pattern.cpp@@ -32,11 +32,15 @@#include "openvino/op/reduce_sum.hpp"#include "openvino/op/relu.hpp"#include "openvino/op/reshape.hpp"+#include "openvino/op/shape_of.hpp"#include "openvino/op/sigmoid.hpp"+#include "openvino/op/split.hpp"#include "openvino/op/strided_slice.hpp"#include "openvino/op/subtract.hpp"#include "openvino/op/transpose.hpp"+#include "openvino/op/util/attr_types.hpp"#include "openvino/op/util/op_types.hpp"+#include "openvino/op/variadic_split.hpp"#include "openvino/pass/graph_rewrite.hpp"#include "openvino/pass/manager.hpp"#include "openvino/pass/pattern/matcher.hpp"@@ -538,7 +542,7 @@ TEST(pattern, or_pattern_points_the_selected_branch) {// Pattern:auto option_1 = wrap_type<v0::Parameter>();auto option_2 = wrap_type<v0::Sigmoid>();- auto or_pattern = std::make_shared<pattern::op::Or>(ov::OutputVector{option_1, option_2});+ auto or_pattern = option_1 | option_2;// Test:TestMatcher matcher;@@ -1467,3 +1471,111 @@ TEST(pattern, pattern_symbol_predicate_and_operators) {ASSERT_NO_THROW(predicate_and(m, input));}}++TEST(pattern, predicate_attr_match) {+ TestMatcher tm;+ auto input = std::make_shared<op::v0::Parameter>(element::dynamic, PartialShape::dynamic());+ auto constant = op::v0::Constant::create(element::i64, {4}, {0, 0, 0, 20});++ // boolean attr check+ auto pattern_true = pattern::any_input(pattern::attrs_match({{"special_zero", true}}));+ auto pattern_false = pattern::any_input(pattern::attrs_match({{"special_zero", false}}));++ auto reshape_true = std::make_shared<op::v1::Reshape>(input, constant, true);+ auto reshape_false = std::make_shared<op::v1::Reshape>(input, constant, false);++ ASSERT_TRUE(tm.match(pattern_true, reshape_true));+ ASSERT_FALSE(tm.match(pattern_true, reshape_false));+ ASSERT_TRUE(tm.match(pattern_false, reshape_false));+ ASSERT_FALSE(tm.match(pattern_false, reshape_true));++ // element type check+ auto pattern_i64 =+ pattern::wrap_type<op::v0::ShapeOf, op::v3::ShapeOf>(pattern::attrs_match({{"output_type", "i64"}}));+ auto pattern_i32 = pattern::wrap_type<op::v0::ShapeOf, op::v3::ShapeOf>({{"output_type", "i32"}});++ auto shape_of_i64 = std::make_shared<op::v3::ShapeOf>(input, element::i64);+ auto shape_of_i32 = std::make_shared<op::v3::ShapeOf>(input, element::i32);++ ASSERT_TRUE(tm.match(pattern_i64, shape_of_i64));+ ASSERT_FALSE(tm.match(pattern_i64, shape_of_i32));+ ASSERT_FALSE(tm.match(pattern_i32, shape_of_i64));+ ASSERT_TRUE(tm.match(pattern_i32, shape_of_i32));++ // broadcasting check+ auto pattern_numpy = pattern::any_input({{"auto_broadcast", "numpy"}});+ auto pattern_pdpd = pattern::optional<op::v1::Multiply>({{"auto_broadcast", "pdpd"}});+ auto pattern_numpy_or_pdpd = pattern::any_input(pattern::attrs_match({{"auto_broadcast", "numpy"}}) ||+ pattern::attrs_match({{"auto_broadcast", "pdpd"}}));++ auto mul_numpy = std::make_shared<op::v1::Multiply>(input, input, op::AutoBroadcastType::NUMPY);+ auto mul_pdpd = std::make_shared<op::v1::Multiply>(input, input, op::AutoBroadcastType::PDPD);+ auto mul_none = std::make_shared<op::v1::Multiply>(input, input, op::AutoBroadcastType::NONE);++ ASSERT_TRUE(tm.match(pattern_numpy, mul_numpy));+ ASSERT_FALSE(tm.match(pattern_numpy, mul_pdpd));+ ASSERT_FALSE(tm.match(pattern_pdpd, mul_numpy));+ ASSERT_TRUE(tm.match(pattern_pdpd, mul_pdpd));++ ASSERT_TRUE(tm.match(pattern_numpy_or_pdpd, mul_numpy));+ ASSERT_TRUE(tm.match(pattern_numpy_or_pdpd, mul_pdpd));+ ASSERT_FALSE(tm.match(pattern_numpy_or_pdpd, mul_none));++ auto num_splits_pattern = pattern::any_input({{"num_splits", 3}});+ auto split = std::make_shared<op::v1::Split>(input, op::v0::Constant::create(element::i64, {}, {0}), 3);+ ASSERT_TRUE(tm.match(num_splits_pattern, split));++ auto ss = std::make_shared<op::v1::StridedSlice>(input,+ op::v0::Constant::create(element::i64, {1}, {0}),+ op::v0::Constant::create(element::i64, {1}, {-1}),+ op::v0::Constant::create(element::i64, {1}, {1}),+ std::vector<int64_t>{0, 1},+ std::vector<int64_t>{1, 0});++ auto ss_pattern = pattern::any_input({{"begin_mask", std::vector<int64_t>{0, 1}}});+ // TODO: to allow initializer list as attribute value -- need to update ov::Attribute value type -- wrap ov::Any and+ // allow implicit conversion from initializer lists of different types.+ // For now it seems excessive as it impacts quality of life of limited number of developers aka there is a WA+ ASSERT_TRUE(tm.match(ss_pattern, ss));+}++TEST(pattern, predicate_value_match) {+ TestMatcher tm;+ auto constant_i = op::v0::Constant::create(element::i64, {4}, vector<int8_t>{-1, 0, 1, 2});+ auto constant_d = op::v0::Constant::create(element::f64, {4}, vector<float>{-1.5f, 0.f, 1.3f, 2.75f});++ // actual value check+ auto pattern_i = pattern::any_input(pattern::value_matches("[-1, 0, 1, 2]"));+ auto pattern_d = pattern::any_input(pattern::value_matches("[-1.5, 0, 1.3, 2.75]"));++ ASSERT_TRUE(tm.match(pattern_i, constant_i));+ ASSERT_FALSE(tm.match(pattern_i, constant_d));+ ASSERT_TRUE(tm.match(pattern_d, constant_d));+ ASSERT_FALSE(tm.match(pattern_d, constant_i));++ auto pattern_neg_i = pattern::any_input(pattern::value_matches("[-1, ..., 1, 3]"));+ ASSERT_FALSE(tm.match(pattern_neg_i, constant_i));++ auto pattern_neg_d = pattern::any_input(pattern::value_matches("[-1.5, -0.1, 1.25, 2.65]"));+ ASSERT_FALSE(tm.match(pattern_neg_d, constant_d));+}++TEST(pattern, predicate_syntactic_sugar) {+ TestMatcher tm;+ auto pattern_with_constant_inputs =+ pattern::wrap_type<op::v1::VariadicSplit>({pattern::any_input(), 3, {"count", "-1"}});++ auto vsplit = std::make_shared<op::v1::VariadicSplit>(+ std::make_shared<op::v0::Parameter>(element::dynamic, PartialShape{1, -1, -1, 10}),+ op::v0::Constant::create(element::i64, {}, vector<int8_t>{3}),+ op::v0::Constant::create(element::i64, {2}, vector<int8_t>{4, -1}));+ vsplit->set_output_size(2);+ ASSERT_TRUE(tm.match_value(pattern_with_constant_inputs, vsplit->output(0)));+ const auto& symbols = tm.get_symbols();+ ASSERT_TRUE(symbols.count("count") && symbols.at("count").i() == 4);++ // different ways to pass single input to the pattern op+ ASSERT_NO_THROW(pattern::wrap_type<op::v0::Relu>(pattern::any_input()));+ ASSERT_NO_THROW(pattern::wrap_type<op::v0::Relu>(pattern::wrap_type<op::v0::Relu>()));+ ASSERT_NO_THROW(pattern::wrap_type<op::v0::Relu>("[-1,0,1]"));+}