Skip to content

OpenVINO™ is an open source toolkit for optimizing and deploying AI inference

Symbol: operator+; operator-; (#25360)

Evgenya Nugmanova1de23c3c0cfd
diff --git a/src/bindings/python/src/pyopenvino/graph/symbol.cpp b/src/bindings/python/src/pyopenvino/graph/symbol.cpp
index 5ed06c35061..339284de8dc 100644
--- a/src/bindings/python/src/pyopenvino/graph/symbol.cpp
+++ b/src/bindings/python/src/pyopenvino/graph/symbol.cpp
@@ -25,6 +25,20 @@ void regclass_graph_Symbol(py::module m) {
},
py::is_operator());
+ symbol.def(
+ "__add__",
+ [](const std::shared_ptr<ov::Symbol>& a, const std::shared_ptr<ov::Symbol>& b) {
+ return a + b;
+ },
+ py::is_operator());
+
+ symbol.def(
+ "__sub__",
+ [](const std::shared_ptr<ov::Symbol>& a, const std::shared_ptr<ov::Symbol>& b) {
+ return a - b;
+ },
+ py::is_operator());
+
symbol.def(
"__bool__",
[](const std::shared_ptr<ov::Symbol>& self) -> bool {
diff --git a/src/bindings/python/tests/test_runtime/test_dimension.py b/src/bindings/python/tests/test_runtime/test_dimension.py
index cd20accc14b..d3a87a606ad 100644
--- a/src/bindings/python/tests/test_runtime/test_dimension.py
+++ b/src/bindings/python/tests/test_runtime/test_dimension.py
@@ -80,6 +80,15 @@ def test_symbol():
assert dimension.get_symbol() == new_dimension.get_symbol(), "Check: Two symbols are equal: Symbol.__eq__"
+def test_symbol_operators():
+ symbol_a, symbol_b = Symbol(), Symbol()
+ assert symbol_a + symbol_b == symbol_b + symbol_a
+
+ symbol_c, symbol_d = Symbol(), Symbol()
+ assert symbol_c + symbol_d - symbol_d == symbol_c
+ assert symbol_c + symbol_d - symbol_c == symbol_d
+
+
def test_symbol_hash():
symbol = Symbol()
assert isinstance(hash(symbol), int)
diff --git a/src/common/transformations/src/transformations/symbolic_transformations/symbolic_optimizations.cpp b/src/common/transformations/src/transformations/symbolic_transformations/symbolic_optimizations.cpp
index d6629f326a2..e0a057ef74e 100644
--- a/src/common/transformations/src/transformations/symbolic_transformations/symbolic_optimizations.cpp
+++ b/src/common/transformations/src/transformations/symbolic_transformations/symbolic_optimizations.cpp
@@ -46,50 +46,6 @@ void symbolic_set_up_for_shape(ov::PartialShape& shape) {
d.set_symbol(std::make_shared<ov::Symbol>());
}
}
-
-void special_case_range_symbol_propagation(const std::shared_ptr<ov::Node>& node) {
- /* Symbol propagation through specific Range operation
- start shift
- | \ /
- | Add step == 1
- \ / /
- Range
- */
- if (!ov::is_type<ov::op::v0::Range>(node) && !ov::is_type<ov::op::v4::Range>(node))
- return;
-
- auto output_shape = node->get_output_partial_shape(0);
- if (output_shape.rank().is_dynamic() || output_shape.size() != 1)
- return;
-
- auto step_value = ov::util::get_constant_from_source(node->input_value(2));
- if (!step_value || step_value->cast_vector<int64_t>()[0] != 1)
- return;
-
- auto start_symbols = node->get_input_tensor(0).get_value_symbol();
- if (start_symbols.size() != 1 || start_symbols[0] == nullptr)
- return;
- auto start_symbol = start_symbols[0];
-
- auto stop_node = node->input_value(1).get_node_shared_ptr();
- if (!ov::is_type<ov::op::v1::Add>(stop_node))
- return;
- auto add_in0_symbols = stop_node->get_input_tensor(0).get_value_symbol();
- if (add_in0_symbols.size() != 1 || add_in0_symbols[0] == nullptr)
- return;
- auto add_in0_symbol = add_in0_symbols[0];
-
- auto add_in1_symbols = stop_node->get_input_tensor(1).get_value_symbol();
- if (add_in1_symbols.size() != 1 || add_in1_symbols[0] == nullptr)
- return;
- auto add_in1_symbol = add_in1_symbols[0];
-
- if (add_in0_symbol == start_symbol)
- output_shape[0].set_symbol(add_in1_symbol);
- else if (add_in1_symbol == start_symbol)
- output_shape[0].set_symbol(add_in0_symbol);
- node->set_output_type(0, node->get_output_element_type(0), output_shape);
-}
} // namespace
bool ov::pass::SymbolicPropagation::run_on_model(const std::shared_ptr<ov::Model>& m) {
@@ -104,10 +60,6 @@ bool ov::pass::SymbolicPropagation::run_on_model(const std::shared_ptr<ov::Model
// Recursively apply transformation for sub-graph based operations
ov::op::util::process_subgraph(*this, op);
- // additional symbol propagation rules must be triggered here
- special_case_range_symbol_propagation(op);
- // additional symbol propagation rules must be triggered here
-
for (auto& output : op->outputs()) {
auto shape = output.get_partial_shape();
symbolic_set_up_for_shape(shape);
diff --git a/src/core/include/openvino/core/symbol.hpp b/src/core/include/openvino/core/symbol.hpp
index 48a733e0d5c..6eb52692553 100644
--- a/src/core/include/openvino/core/symbol.hpp
+++ b/src/core/include/openvino/core/symbol.hpp
@@ -3,37 +3,46 @@
//
#pragma once
-
#include <memory>
+#include <unordered_map>
+#include <vector>
#include "openvino/core/core_visibility.hpp"
namespace ov {
-
class Symbol;
+using SymbolPtr = std::shared_ptr<ov::Symbol>;
namespace symbol {
/// \brief If both symbols are valid, sets them as equal
-void OPENVINO_API set_equal(const std::shared_ptr<Symbol>& lhs, const std::shared_ptr<Symbol>& rhs);
+void OPENVINO_API set_equal(const SymbolPtr& lhs, const SymbolPtr& rhs);
/// \brief Returns true if both symbols are valid and are equal otherwise returns false
-bool OPENVINO_API are_equal(const std::shared_ptr<Symbol>& lhs, const std::shared_ptr<Symbol>& rhs);
+bool OPENVINO_API are_equal(const SymbolPtr& lhs, const SymbolPtr& rhs);
/// \brief Returns a representative (the most distant parent) of an equality group of this symbol
-std::shared_ptr<Symbol> OPENVINO_API ancestor_of(const std::shared_ptr<Symbol>& x);
+std::shared_ptr<Symbol> OPENVINO_API ancestor_of(const SymbolPtr& x);
} // namespace symbol
-/// \brief Class representing unique symbol for the purpose of symbolic shape inference. Equality of symbols is being
-/// tracked by Disjoint-set data structure
+SymbolPtr OPENVINO_API operator+(const SymbolPtr& lhs, const SymbolPtr& rhs);
+SymbolPtr OPENVINO_API operator-(const SymbolPtr& lhs, const SymbolPtr& rhs);
+
+/// \brief Class representing unique symbol for the purpose of symbolic shape inference
/// \ingroup ov_model_cpp_api
class OPENVINO_API Symbol {
public:
/// \brief Default constructs a unique symbol
- Symbol() = default;
+ Symbol();
+ /// @brief Destructor ensures shared MathMaps are cleared from the expired symbols
+ ~Symbol();
private:
- friend std::shared_ptr<Symbol> ov::symbol::ancestor_of(const std::shared_ptr<Symbol>& x);
- friend void ov::symbol::set_equal(const std::shared_ptr<Symbol>& lhs, const std::shared_ptr<Symbol>& rhs);
+ friend SymbolPtr ov::symbol::ancestor_of(const SymbolPtr& x);
+ friend void ov::symbol::set_equal(const SymbolPtr& lhs, const SymbolPtr& rhs);
+
+ friend SymbolPtr ov::operator+(const SymbolPtr& lhs, const SymbolPtr& rhs);
+ friend SymbolPtr ov::operator-(const SymbolPtr& lhs, const SymbolPtr& rhs);
- std::shared_ptr<Symbol> m_parent = nullptr;
+ class Impl;
+ std::unique_ptr<Impl> pimpl;
};
} // namespace ov
diff --git a/src/core/include/openvino/op/add.hpp b/src/core/include/openvino/op/add.hpp
index 0691cdfed29..ebc21fe089a 100644
--- a/src/core/include/openvino/op/add.hpp
+++ b/src/core/include/openvino/op/add.hpp
@@ -39,6 +39,7 @@ public:
std::shared_ptr<Node> clone_with_new_inputs(const OutputVector& new_args) const override;
bool evaluate(TensorVector& outputs, const TensorVector& inputs) const override;
+ bool evaluate_symbol(ov::TensorSymbolVector& output_symbols) const override;
bool has_evaluate() const override;
};
} // namespace v1
diff --git a/src/core/include/openvino/op/subtract.hpp b/src/core/include/openvino/op/subtract.hpp
index 35ed4e33282..181b05d5566 100644
--- a/src/core/include/openvino/op/subtract.hpp
+++ b/src/core/include/openvino/op/subtract.hpp
@@ -28,6 +28,7 @@ public:
std::shared_ptr<Node> clone_with_new_inputs(const OutputVector& new_args) const override;
bool evaluate(TensorVector& outputs, const TensorVector& inputs) const override;
+ bool evaluate_symbol(ov::TensorSymbolVector& output_symbols) const override;
bool has_evaluate() const override;
};
} // namespace v1
diff --git a/src/core/shape_inference/include/range_shape_inference.hpp b/src/core/shape_inference/include/range_shape_inference.hpp
index 3be56a4543a..e82bd5f5d1f 100644
--- a/src/core/shape_inference/include/range_shape_inference.hpp
+++ b/src/core/shape_inference/include/range_shape_inference.hpp
@@ -11,6 +11,33 @@ namespace op {
namespace ShapeInferRange {
+template <class TRShape, typename std::enable_if<std::is_same<TRShape, PartialShape>::value>::type* = nullptr>
+void dynamic_case(const Node* op,
+ std::vector<TRShape>& output_shapes,
+ const double& start,
+ const double& step,
+ bool start_val,
+ bool step_val) {
+ output_shapes[0] = ov::PartialShape::dynamic(1);
+ if (op->get_input_size() == 3 && step_val && step == 1) {
+ auto start_symbol = op->input_value(0).get_tensor().get_value_symbol();
+ auto stop_symbol = op->input_value(1).get_tensor().get_value_symbol();
+ if (start_val && start == 0 && !stop_symbol.empty()) {
+ output_shapes[0][0].set_symbol(stop_symbol[0]);
+ } else if (!start_symbol.empty() && !stop_symbol.empty()) {
+ output_shapes[0][0].set_symbol(stop_symbol[0] - start_symbol[0]);
+ }
+ }
+}
+
+template <class TRShape, typename std::enable_if<!std::is_same<TRShape, PartialShape>::value>::type* = nullptr>
+void dynamic_case(const Node* op,
+ std::vector<TRShape>& output_shapes,
+ const double& start,
+ const double& step,
+ bool start_val,
+ bool step_val) {}
+
template <class T, class TRShape = result_shape_t<T>>
std::vector<TRShape> range_shape_infer(const Node* op,
const std::vector<T>& input_shapes,
@@ -35,12 +62,18 @@ std::vector<TRShape> range_shape_infer(const Node* op,
NODE_VALIDATION_CHECK(op, start_val->size() == 1);
start = (*start_val)[0];
NODE_VALIDATION_CHECK(op, std::isfinite(start) && !std::isnan(start), "'start' cannot be nan or infinite.");
+ if (output_is_integral)
+ // all inputs must be casted to output_type before the rounding for casting values are done towards zero
+ start = std::trunc(start);
}
if (stop_val) {
NODE_VALIDATION_CHECK(op, stop_val->size() == 1);
stop = (*stop_val)[0];
NODE_VALIDATION_CHECK(op, std::isfinite(stop) && !std::isnan(stop), "'stop' cannot be nan or infinite.");
+ if (output_is_integral)
+ // all inputs must be casted to output_type before the rounding for casting values are done towards zero
+ stop = std::trunc(stop);
}
if (step_val) {
@@ -52,18 +85,13 @@ std::vector<TRShape> range_shape_infer(const Node* op,
NODE_VALIDATION_CHECK(op,
std::isfinite(step) && !std::isnan(step) && step != 0,
"'step' cannot be zero, nan, or infinite.");
+ if (output_is_integral)
+ // all inputs must be casted to output_type before the rounding for casting values are done towards zero
+ step = std::trunc(step);
}
auto output_shapes = std::vector<TRShape>(1);
if (start_val && stop_val && step_val) {
- // all inputs must be casted to output_type before
- // the rounding for casting values are done towards zero
- if (output_is_integral) {
- start = std::trunc(start);
- stop = std::trunc(stop);
- step = std::trunc(step);
- }
-
// the number of elements is: max(ceil((stop − start) / step), 0)
double span;
if ((step > 0 && start >= stop) || (step < 0 && start <= stop)) {
@@ -76,7 +104,7 @@ std::vector<TRShape> range_shape_infer(const Node* op,
output_shapes[0] = TRShape{static_cast<uint32_t>(strided)};
} else {
- output_shapes[0] = ov::PartialShape::dynamic(1);
+ dynamic_case(op, output_shapes, start, step, start_val, step_val);
}
return output_shapes;
}
diff --git a/src/core/src/dimension.cpp b/src/core/src/dimension.cpp
index 454207c2437..78e7f2c7cff 100644
--- a/src/core/src/dimension.cpp
+++ b/src/core/src/dimension.cpp
@@ -132,13 +132,17 @@ Dimension Dimension::operator+(const Dimension& dim) const {
return *this;
else if (m_dimension == 0)
return dim;
- return Dimension(m_dimension + dim.m_dimension);
+ auto result = Dimension(m_dimension + dim.m_dimension);
+ result.m_symbol = m_symbol + dim.m_symbol;
+ return result;
}
Dimension Dimension::operator-(const Dimension& dim) const {
if (dim.m_dimension == 0)
return *this;
- return Dimension(m_dimension - dim.m_dimension);
+ auto result = Dimension(m_dimension - dim.m_dimension);
+ result.m_symbol = m_symbol - dim.m_symbol;
+ return result;
}
Dimension Dimension::operator/(const value_type divisor) const {
diff --git a/src/core/src/op/add.cpp b/src/core/src/op/add.cpp
index 6b4680fed57..7e7748beccc 100644
--- a/src/core/src/op/add.cpp
+++ b/src/core/src/op/add.cpp
@@ -63,6 +63,21 @@ bool Add::evaluate(ov::TensorVector& outputs, const ov::TensorVector& inputs) co
get_autob());
}
+bool Add::evaluate_symbol(ov::TensorSymbolVector& output_symbols) const {
+ const auto &lhs_pshape = input(0).get_tensor().get_partial_shape(),
+ &rhs_pshape = input(1).get_tensor().get_partial_shape();
+ const auto &lhs_symbols = input(0).get_tensor().get_value_symbol(),
+ &rhs_symbols = input(1).get_tensor().get_value_symbol();
+ if (lhs_pshape.is_dynamic() || rhs_pshape.is_dynamic() || lhs_pshape != rhs_pshape || lhs_symbols.empty() ||
+ lhs_symbols.size() != rhs_symbols.size())
+ return false; // broadcasting is not supported here yet
+ output_symbols.resize(1);
+ output_symbols[0].resize(shape_size(lhs_pshape.to_shape()));
+ for (size_t i = 0; i < output_symbols[0].size(); ++i)
+ output_symbols[0][i] = lhs_symbols[i] + rhs_symbols[i];
+ return true;
+}
+
bool Add::has_evaluate() const {
OV_OP_SCOPE(v1_Add_has_evaluate);
switch (get_input_element_type(0)) {
diff --git a/src/core/src/op/subtract.cpp b/src/core/src/op/subtract.cpp
index f8f0bb93d03..3695f36110e 100644
--- a/src/core/src/op/subtract.cpp
+++ b/src/core/src/op/subtract.cpp
@@ -63,6 +63,21 @@ bool Subtract::evaluate(TensorVector& outputs, const TensorVector& inputs) const
get_autob());
}
+bool Subtract::evaluate_symbol(ov::TensorSymbolVector& output_symbols) const {
+ const auto &lhs_pshape = input(0).get_tensor().get_partial_shape(),
+ &rhs_pshape = input(1).get_tensor().get_partial_shape();
+ const auto &lhs_symbols = input(0).get_tensor().get_value_symbol(),
+ &rhs_symbols = input(1).get_tensor().get_value_symbol();
+ if (lhs_pshape.is_dynamic() || rhs_pshape.is_dynamic() || lhs_pshape != rhs_pshape || lhs_symbols.empty() ||
+ lhs_symbols.size() != rhs_symbols.size())
+ return false; // broadcasting is not supported here yet
+ output_symbols.resize(1);
+ output_symbols[0].resize(shape_size(lhs_pshape.to_shape()));
+ for (size_t i = 0; i < output_symbols[0].size(); ++i)
+ output_symbols[0][i] = lhs_symbols[i] - rhs_symbols[i];
+ return true;
+}
+
bool Subtract::has_evaluate() const {
OV_OP_SCOPE(v1_Subtract_has_evaluate);
switch (get_input_element_type(0)) {
diff --git a/src/core/src/symbol.cpp b/src/core/src/symbol.cpp
index 48c913bfb53..d6037b6c004 100644
--- a/src/core/src/symbol.cpp
+++ b/src/core/src/symbol.cpp
@@ -4,27 +4,432 @@
#include "openvino/core/symbol.hpp"
-std::shared_ptr<ov::Symbol> ov::symbol::ancestor_of(const std::shared_ptr<Symbol>& symbol) {
+#include <algorithm>
+#include <map>
+#include <queue>
+
+namespace ov {
+using WeakSymbol = std::weak_ptr<ov::Symbol>;
+using WeakSymbolVector = std::vector<WeakSymbol>;
+
+inline bool operator==(const WeakSymbol& lhs, const WeakSymbol& rhs) {
+ if (lhs.expired() && rhs.expired())
+ return true;
+ if (lhs.expired() || rhs.expired())
+ return false;
+ return lhs.lock().get() == rhs.lock().get();
+}
+
+inline bool operator!=(const WeakSymbol& lhs, const WeakSymbol& rhs) {
+ return !(lhs == rhs);
+}
+
+inline bool operator<(const WeakSymbol& lhs, const WeakSymbol& rhs) {
+ return std::owner_less<ov::SymbolPtr>()(lhs.lock(), rhs.lock());
+}
+
+struct WeakSymbolVectorHash {
+ std::size_t operator()(const WeakSymbolVector& v) const {
+ size_t seed = 0;
+ for (const auto& element : v) {
+ const auto& el_hash = element.expired() ? 0 : std::hash<ov::SymbolPtr>()(element.lock());
+ seed ^= el_hash + 0x9e3779b9 + (seed << 6) + (seed >> 2);
+ }
+ return seed;
+ }
+};
+
+using MathMap = std::map<WeakSymbolVector, WeakSymbol>;
+
+class ov::Symbol::Impl {
+public:
+ Impl() = default;
+ ~Impl() = default;
+
+private:
+ /*
+ * Equality relations between symbols are managed by the Disjoint-set data structure.
+ * m_parent field gives access to a parent tree. Parent tree grows when we use set_equal routine.
+ *
+ * The root of parent tree is called ancestor -- a representative of a group of equal symbols.
+ * To get an ancestor of any symbol, call ancestor_of routine. If current symbol is an ancestor, then its m_parent
+ * field is nullptr and ancestor_of would return current symbol.
+ * */
+ SymbolPtr m_parent = nullptr;
+
+ /*
+ * Shared MathMap represents mathematical relations between symbols. Rules:
+ * - map stores only ancestor symbols
+ * - all the Symbols in the map must share the same map as their respective field
+ *
+ * To ensure rules, set_equal routine and operators are managing maps of both symbols.
+ *
+ * MathMap m_add reflects addition and subtraction. Given symbols A, B, C and D
+ * - relation A + B = C would be reflected as key={A, B} value=C in the map
+ * - relation A - B = C would be reflected as key={B, C} value=A in the map
+ * - relation A + B + C = D would be reflected as key={A, B, C} value=D in the map
+ *
+ * During destruction of a symbol, m_add map is being cleared from the records with expired symbols
+ */
+ std::shared_ptr<MathMap> m_add = nullptr;
+
+public:
+ const SymbolPtr& get_parent() const {
+ return m_parent;
+ }
+
+ void set_parent(const SymbolPtr& new_parent) {
+ m_parent = new_parent;
+ }
+
+ const std::shared_ptr<MathMap>& get_add_map() const {
+ return m_add;
+ }
+
+ void set_add_map(const std::shared_ptr<MathMap>& new_map) {
+ m_add = new_map;
+ }
+};
+} // namespace ov
+
+ov::SymbolPtr ov::symbol::ancestor_of(const SymbolPtr& symbol) {
auto x = symbol;
- while (x->m_parent) {
- if (x->m_parent->m_parent)
- x->m_parent = x->m_parent->m_parent;
- x = x->m_parent;
+ while (const auto& parent = x->pimpl->get_parent()) {
+ const auto& grand_parent = parent->pimpl->get_parent();
+ if (grand_parent)
+ x->pimpl->set_parent(grand_parent);
+ x = x->pimpl->get_parent();
}
return x;
}
-bool ov::symbol::are_equal(const std::shared_ptr<Symbol>& lhs, const std::shared_ptr<Symbol>& rhs) {
+bool ov::symbol::are_equal(const SymbolPtr& lhs, const SymbolPtr& rhs) {
if (lhs == nullptr || rhs == nullptr)
return false;
- return ov::symbol::ancestor_of(lhs).get() == ov::symbol::ancestor_of(rhs).get();
+ return ancestor_of(lhs).get() == ancestor_of(rhs).get();
}
-void ov::symbol::set_equal(const std::shared_ptr<Symbol>& lhs, const std::shared_ptr<Symbol>& rhs) {
- if (lhs == nullptr || rhs == nullptr)
+namespace { // helpers to work with shared math maps in symbols
+bool contains(const ov::WeakSymbolVector& vec, const ov::WeakSymbol& s) {
+ return std::find(vec.cbegin(), vec.cend(), s) != vec.cend();
+}
+
+bool contains(const ov::WeakSymbolVector& vec, const ov::Symbol* s) {
+ return std::any_of(vec.begin(), vec.end(), [&s](const ov::WeakSymbol& i) {
+ if (i.lock() == nullptr)
+ return s == nullptr;
+ return i.lock().get() == s;
+ });
+}
+
+void sort(ov::WeakSymbolVector& vec) {
+ std::sort(vec.begin(), vec.end());
+}
+
+void replace(ov::WeakSymbolVector& vec, const ov::WeakSymbol& old_s, const ov::WeakSymbol& new_s) {
+ std::replace_if(
+ vec.begin(),
+ vec.end(),
+ [&old_s](const ov::WeakSymbol& s) {
+ return s == old_s;
+ },
+ new_s);
+ sort(vec);
+}
+
+void replace_no_check(ov::SymbolPtr old_symbol, ov::SymbolPtr new_symbol, ov::MathMap& m) {
+ ov::MathMap map_with_old;
+ for (const auto& item : m)
+ if (item.second == ov::WeakSymbol(old_symbol) || contains(item.first, old_symbol.get()))
+ map_with_old.insert(item);
+ for (const auto& item : map_with_old)
+ m.erase(item.first);
+ for (const auto& item : map_with_old) {
+ auto new_key = item.first;
+ replace(new_key, old_symbol, new_symbol);
+ m.insert({new_key, item.second == old_symbol ? new_symbol : item.second});
+ }
+}
+
+void remove_same_elements(ov::WeakSymbolVector& lhs, ov::WeakSymbolVector& rhs) {
+ for (auto lhs_it = lhs.begin(); lhs_it != lhs.end();) {
+ if (lhs_it->expired())
+ continue;
+ auto rhs_it = std::find(rhs.cbegin(), rhs.cend(), *lhs_it);
+ if (rhs_it != rhs.end()) {
+ rhs.erase(rhs_it);
+ lhs_it = lhs.erase(lhs_it);
+ } else {
+ ++lhs_it;
+ }
+ }
+}
+
+void insert_with_check(const ov::WeakSymbolVector& key,
+ const ov::WeakSymbol& value,
+ ov::MathMap& m,
+ std::queue<std::pair<ov::WeakSymbol, ov::WeakSymbol>>& to_equalize) {
+ bool insert = true;
+ auto it = m.find(key);
+ if (it != m.end()) {
+ // map m already contains the record with same key, no need to insert new record into the map m
+ insert = false;
+ if (it->second != value)
+ // if the record had different value, then we need to equalize original and new key
+ to_equalize.emplace(it->second, value);
+ } else {
+ // map m doesn't have records with the key, however we are in a search for new equality rules
+ for (const auto& item : m) {
+ if (item.second == value) { // map_ker
+ if (item.first.size() == key.size()) {
+ auto item_diff = item.first, key_diff = key;
+ remove_same_elements(item_diff, key_diff);
+ if (item_diff.size() == 1 && key_diff.size() == 1) {
+ to_equalize.emplace(item_diff[0], key_diff[0]);
+ insert = false;
+ }
+ }
+ }
+ }
+ }
+ if (insert)
+ m.insert({key, value});
+}
+
+void replace_inplace_with_check(ov::SymbolPtr old_symbol,
+ ov::SymbolPtr new_symbol,
+ ov::MathMap& m,
+ std::queue<std::pair<ov::WeakSymbol, ov::WeakSymbol>>& to_equalize) {
+ ov::MathMap with_old;
+ for (const auto& item : m)
+ if (item.second == old_symbol || contains(item.first, old_symbol))
+ with_old.insert({item.first, item.second});
+ for (const auto& item : with_old)
+ m.erase(item.first);
+ for (const auto& item : with_old) {
+ auto new_key = item.first;
+ replace(new_key, old_symbol, new_symbol);
+ insert_with_check(new_key, (item.second == old_symbol ? new_symbol : item.second), m, to_equalize);
+ }
+}
+
+void replace_with_check(ov::SymbolPtr old_symbol,
+ ov::SymbolPtr new_symbol,
+ ov::MathMap& old_map,
+ ov::MathMap& new_map,
+ std::queue<std::pair<ov::WeakSymbol, ov::WeakSymbol>>& to_equalize) {
+ ov::MathMap with_new;
+ for (const auto& item : new_map)
+ if (item.second == new_symbol || contains(item.first, new_symbol))
+ with_new.insert({item.first, item.second});
+ for (const auto& item : with_new)
+ new_map.erase(item.first);
+ // new_map contains only independent records, with_new contains records with new_symbol
+ ov::MathMap with_old;
+ for (const auto& item : old_map) {
+ if (item.second == old_symbol || contains(item.first, old_symbol)) {
+ auto new_key = item.first;
+ replace(new_key, old_symbol, new_symbol);
+ with_old.insert({new_key, item.second});
+ } else {
+ new_map.insert({item.first, item.second});
+ }
+ }
+ // new_map contains independent records from new and from old map; old_map won't be used further
+ old_map.clear();
+ // with_old contains records from old_map that had old_symbol, old_symbol was replaced with new_symbol
+
+ // merging with_new and with_old, performing necessary checks to figure out if we have more equality rules
+ for (const auto& item : with_old)
+ insert_with_check(item.first, (item.second == old_symbol ? new_symbol : item.second), with_new, to_equalize);
+ // with_old is merged into the with_new; necessary checks were made to ensure all new equality rules are collected
+
+ for (const auto& item : with_new)
+ new_map.insert({item.first, item.second});
+}
+
+void collect_records_with_result(ov::SymbolPtr result,
+ const std::shared_ptr<ov::MathMap>& map,
+ std::vector<ov::WeakSymbolVector>& records) {
+ if (map)
+ for (const auto& item : *map)
+ if (item.second.lock() && item.second.lock().get() == result.get())
+ records.push_back(item.first);
+}
+
+void share_map(std::shared_ptr<ov::MathMap> shared_map,
+ std::shared_ptr<ov::MathMap> donor_map,
+ void (*set_map)(const ov::WeakSymbol&, std::shared_ptr<ov::MathMap>)) {
+ if (!donor_map || donor_map->empty())
return;
- auto lhs_root = ov::symbol::ancestor_of(lhs), rhs_root = ov::symbol::ancestor_of(rhs);
- if (lhs_root.get() == rhs_root.get())
- return; // already are equal
- lhs_root->m_parent = std::move(rhs_root);
+ for (const auto& item : *donor_map) {
+ auto key = item.first;
+ for (const auto& key_element : key)
+ set_map(key_element, shared_map);
+ auto value = item.second;
+ set_map(value, shared_map);
+ shared_map->insert({key, value});
+ }
+}
+} // namespace
+
+void ov::symbol::set_equal(const SymbolPtr& l, const SymbolPtr& r) {
+ std::queue<std::pair<ov::WeakSymbol, ov::WeakSymbol>> to_equalize;
+ to_equalize.emplace(l, r);
+
+ do {
+ auto item = to_equalize.front();
+ to_equalize.pop();
+ auto lhs = item.first.lock(), rhs = item.second.lock();
+ if (!lhs || !rhs || ov::symbol::are_equal(lhs, rhs))
+ continue; // invalid or already are equal
+ auto A = ancestor_of(lhs), B = ancestor_of(rhs);
+ A->pimpl->set_parent(B);
+
+ // m_add unification
+ auto A_map = A->pimpl->get_add_map();
+ auto B_map = B->pimpl->get_add_map();
+
+ if (A_map && !B_map) {
+ replace_no_check(A, B, *A_map);
+ B->pimpl->set_add_map(A_map); // rhs is the root of lhs now
+ A->pimpl->set_add_map(nullptr);
+ } else if (A_map && B_map && A_map.get() == B_map.get()) {
+ replace_inplace_with_check(A, B, *B_map, to_equalize);
+ A->pimpl->set_add_map(nullptr); // rhs is the root of lhs now
+ } else if (A_map && B_map) {
+ replace_with_check(A, B, *A_map, *B_map, to_equalize);
+ for (auto& i : *B_map) {
+ for (auto& j : i.first) {
+ if (!j.expired())
+ j.lock()->pimpl->set_add_map(B_map);
+ }
+ if (!i.second.expired())
+ i.second.lock()->pimpl->set_add_map(B_map);
+ }
+ A->pimpl->set_add_map(nullptr);
+ }
+ } while (!to_equalize.empty());
+}
+
+ov::Symbol::Symbol() : pimpl(new Impl()) {}
+
+ov::Symbol::~Symbol() {
+ if (pimpl->get_add_map()) {
+ for (auto item = pimpl->get_add_map()->begin(), last = pimpl->get_add_map()->end(); item != last;) {
+ if (contains(item->first, nullptr) || contains(item->first, this) || item->second.expired() ||
+ item->second.lock().get() == this) {
+ item = pimpl->get_add_map()->erase(item);
+ } else {
+ ++item;
+ }
+ }
+ pimpl->set_add_map(nullptr);
+ }
+}
+
+ov::SymbolPtr ov::operator+(const SymbolPtr& lhs, const SymbolPtr& rhs) {
+ if (lhs == nullptr || rhs == nullptr)
+ return nullptr; // should we create a new shared_ptr to a symbol here?
+ // A + B = C
+ auto A = symbol::ancestor_of(lhs);
+ auto B = symbol::ancestor_of(rhs);
+ auto new_key = ov::WeakSymbolVector({A, B});
+ sort(new_key);
+ std::shared_ptr<ov::MathMap> shared_map = nullptr;
+ if (A->pimpl->get_add_map() && B->pimpl->get_add_map() &&
+ A->pimpl->get_add_map().get() == B->pimpl->get_add_map().get() &&
+ !A->pimpl->get_add_map()->empty()) { // maps are shared
+ auto it = A->pimpl->get_add_map()->find(new_key);
+ if (it != A->pimpl->get_add_map()->end() && it->second.lock()) { // elements were summed before
+ return it->second.lock();
+ }
+ shared_map = A->pimpl->get_add_map();
+ } else {
+ // share maps (if any) between A and B
+ shared_map = std::make_shared<ov::MathMap>();
+ auto set_m_add = [](const ov::WeakSymbol& s, std::shared_ptr<ov::MathMap> m) -> void {
+ if (!s.expired())
+ s.lock()->pimpl->set_add_map(m);
+ };
+ share_map(shared_map, A->pimpl->get_add_map(), set_m_add);
+ share_map(shared_map, B->pimpl->get_add_map(), set_m_add);
+ A->pimpl->set_add_map(shared_map);
+ B->pimpl->set_add_map(shared_map);
+ }
+ auto C = std::make_shared<ov::Symbol>();
+ C->pimpl->set_add_map(shared_map);
+
+ // add L + R = result to the shared map
+ // search for X + Y = L and W + Z = R records to make X + Y + W + Z = result records
+ std::vector<ov::WeakSymbolVector> this_components{{A}}, other_components{{B}};
+ collect_records_with_result(A, shared_map, this_components);
+ collect_records_with_result(B, shared_map, other_components);
+ for (const auto& this_element : this_components) {
+ for (const auto& other_element : other_components) {
+ ov::WeakSymbolVector new_key = this_element;
+ new_key.insert(new_key.begin(), other_element.begin(), other_element.end());
+ sort(new_key);
+ shared_map->insert({new_key, C});
+ }
+ }
+ return C;
+}
+
+ov::SymbolPtr ov::operator-(const SymbolPtr& lhs, const SymbolPtr& rhs) {
+ if (lhs == nullptr || rhs == nullptr)
+ return nullptr; // should we create a new shared_ptr<Symbol> here?
+ // A - B = C => B + C = A
+ auto A = symbol::ancestor_of(lhs);
+ auto B = symbol::ancestor_of(rhs);
+ const auto bw = ov::WeakSymbol(B);
+
+ std::shared_ptr<ov::MathMap> shared_map = nullptr;
+
+ if (A->pimpl->get_add_map() && B->pimpl->get_add_map() &&
+ A->pimpl->get_add_map().get() == B->pimpl->get_add_map().get() &&
+ !A->pimpl->get_add_map()->empty()) { // maps are shared
+ std::vector<ov::WeakSymbolVector> A_components{}, B_components{};
+ collect_records_with_result(A, A->pimpl->get_add_map(), A_components);
+ for (const auto& item : A_components) {
+ if (item.size() == 2 && item[0] == bw && !item[1].expired()) {
+ return item[1].lock();
+ }
+ if (item.size() == 2 && item[1] == bw && !item[0].expired()) {
+ return item[0].lock();
+ }
+ }
+ collect_records_with_result(B, B->pimpl->get_add_map(), B_components);
+ for (auto A_equation : A_components) {
+ for (auto B_equation : B_components) {
+ remove_same_elements(A_equation, B_equation);
+ if (A_equation.size() == 1 && B_equation.empty() && !A_equation[0].expired()) {
+ return A_equation[0].lock();
+ }
+ }
+ }
+ shared_map = A->pimpl->get_add_map();
+ } else {
+ // share maps (if any) between A and B
+ shared_map = std::make_shared<ov::MathMap>();
+ auto set_m_add = [](const ov::WeakSymbol& s, std::shared_ptr<ov::MathMap> m) -> void {
+ if (!s.expired())
+ s.lock()->pimpl->set_add_map(m);
+ };
+ share_map(shared_map, A->pimpl->get_add_map(), set_m_add);
+ share_map(shared_map, B->pimpl->get_add_map(), set_m_add);
+ A->pimpl->set_add_map(shared_map);
+ B->pimpl->set_add_map(shared_map);
+ }
+ auto C = std::make_shared<ov::Symbol>();
+ C->pimpl->set_add_map(shared_map);
+
+ std::vector<ov::WeakSymbolVector> B_components{{B}};
+ collect_records_with_result(B, B->pimpl->get_add_map(), B_components);
+ for (auto& new_key : B_components) {
+ new_key.insert(new_key.begin(), C);
+ sort(new_key);
+ shared_map->insert({new_key, A});
+ }
+ return C;
}
diff --git a/src/core/tests/symbol.cpp b/src/core/tests/symbol.cpp
new file mode 100644
index 00000000000..9303078c03f
--- /dev/null
+++ b/src/core/tests/symbol.cpp
@@ -0,0 +1,71 @@
+// Copyright (C) 2018-2024 Intel Corporation
+// SPDX-License-Identifier: Apache-2.0
+//
+
+#include "openvino/core/symbol.hpp"
+
+#include <gtest/gtest.h>
+
+#include <memory>
+
+TEST(shape, test_symbol_add) {
+ auto A = std::make_shared<ov::Symbol>();
+ auto B = std::make_shared<ov::Symbol>();
+
+ ASSERT_TRUE(ov::symbol::are_equal(A + B, B + A));
+
+ auto C = std::make_shared<ov::Symbol>();
+ auto D = std::make_shared<ov::Symbol>();
+
+ auto E = A + B;
+ auto F = C + D;
+
+ ASSERT_FALSE(ov::symbol::are_equal(E, F));
+
+ ov::symbol::set_equal(A, C);
+ ov::symbol::set_equal(B, D);
+
+ ASSERT_TRUE(ov::symbol::are_equal(E, F));
+}
+
+TEST(shape, test_symbol_sub) {
+ auto A = std::make_shared<ov::Symbol>();
+ auto B = std::make_shared<ov::Symbol>();
+
+ ASSERT_FALSE(ov::symbol::are_equal(A - B, B - A));
+
+ auto C = std::make_shared<ov::Symbol>();
+ auto D = std::make_shared<ov::Symbol>();
+
+ auto E = A - B;
+ auto F = C - D;
+
+ ASSERT_FALSE(ov::symbol::are_equal(E, F));
+
+ ov::symbol::set_equal(A, C);
+ ov::symbol::set_equal(B, D);
+
+ ASSERT_TRUE(ov::symbol::are_equal(E, F));
+}
+
+TEST(shape, test_symbol_add_sub) {
+ auto A = std::make_shared<ov::Symbol>();
+ auto B = std::make_shared<ov::Symbol>();
+ auto C = std::make_shared<ov::Symbol>();
+
+ auto D = A + B;
+ auto E = D + C; // E = A + B + C
+ auto F = B + C;
+
+ auto G = E - F; // G = A + B + C - B - C = A
+ ASSERT_TRUE(ov::symbol::are_equal(A, G));
+}
+
+TEST(shape, test_symbol_null) {
+ auto A = std::make_shared<ov::Symbol>();
+ std::shared_ptr<ov::Symbol> B = nullptr;
+ ASSERT_EQ(A + B, nullptr);
+ ASSERT_EQ(nullptr, A + B);
+ ASSERT_EQ(A - B, nullptr);
+ ASSERT_EQ(nullptr, A - B);
+}
diff --git a/src/core/tests/type_prop/range.cpp b/src/core/tests/type_prop/range.cpp
index c37f5987047..5298112fdfe 100644
--- a/src/core/tests/type_prop/range.cpp
+++ b/src/core/tests/type_prop/range.cpp
@@ -6,6 +6,8 @@
#include "common_test_utils/type_prop.hpp"
#include "openvino/op/constant.hpp"
+#include "openvino/op/gather.hpp"
+#include "openvino/op/shape_of.hpp"
using namespace std;
using namespace ov;
@@ -895,3 +897,45 @@ INSTANTIATE_TEST_SUITE_P(type_prop,
RangeParams{-1, 1, 0.25, PartialShape{8}},
RangeParams{-1, 0.875, 0.25, PartialShape{8}}),
PrintToDummyParamName());
+
+TEST(type_prop, range_symbol_start_0_stop_A_step_1) {
+ auto stop_symbol = std::make_shared<ov::Symbol>();
+ auto source_shape = PartialShape::dynamic(1);
+ source_shape[0].set_symbol(stop_symbol);
+ auto symbol_source =
+ make_shared<ov::op::v0::ShapeOf>(make_shared<ov::op::v0::Parameter>(element::i64, source_shape));
+
+ auto start = make_shared<ov::op::v0::Constant>(element::i64, Shape{}, 0);
+ auto stop = make_shared<ov::op::v8::Gather>(symbol_source,
+ make_shared<ov::op::v0::Constant>(element::i64, Shape{}, 0),
+ make_shared<ov::op::v0::Constant>(element::i64, Shape{}, 0));
+ auto step = make_shared<ov::op::v0::Constant>(element::i64, Shape{}, 1);
+
+ auto range = make_shared<op::v0::Range>(start, stop, step);
+
+ ASSERT_TRUE(ov::symbol::are_equal(range->get_output_partial_shape(0)[0].get_symbol(), stop_symbol));
+}
+
+TEST(type_prop, range_symbol_start_A_stop_A_plus_B_step_1) {
+ auto start_symbol = std::make_shared<ov::Symbol>();
+ auto output_symbol = std::make_shared<ov::Symbol>();
+ auto stop_symbol = start_symbol + output_symbol;
+
+ auto source_shape = PartialShape::dynamic(2);
+ source_shape[0].set_symbol(start_symbol);
+ source_shape[1].set_symbol(stop_symbol);
+ auto symbol_source =
+ make_shared<ov::op::v0::ShapeOf>(make_shared<ov::op::v0::Parameter>(element::i64, source_shape));
+
+ auto start = make_shared<ov::op::v8::Gather>(symbol_source,
+ make_shared<ov::op::v0::Constant>(element::i64, Shape{}, 0),
+ make_shared<ov::op::v0::Constant>(element::i64, Shape{}, 0));
+ auto stop = make_shared<ov::op::v8::Gather>(symbol_source,
+ make_shared<ov::op::v0::Constant>(element::i64, Shape{}, 1),
+ make_shared<ov::op::v0::Constant>(element::i64, Shape{}, 0));
+ auto step = make_shared<ov::op::v0::Constant>(element::i64, Shape{}, 1);
+
+ auto range = make_shared<op::v0::Range>(start, stop, step);
+
+ ASSERT_TRUE(ov::symbol::are_equal(range->get_output_partial_shape(0)[0].get_symbol(), output_symbol));
+}