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
[TF FE] Fix memory leak from Switch self-reference in rt_info (#36957)
Evgeny Kotovd840f45f7836
diff --git a/src/frontends/tensorflow/src/tf_utils.cpp b/src/frontends/tensorflow/src/tf_utils.cppindex 858235605e9..800699ba62b 100644--- a/src/frontends/tensorflow/src/tf_utils.cpp+++ b/src/frontends/tensorflow/src/tf_utils.cpp@@ -424,7 +424,7 @@ bool propagate_conditional_flow(const OutputVector& ov_inputs,} else if (const auto& switch_node = as_type_ptr<Switch>(node)) {// update conditional flow marker with new marker for the current Switch nodeauto switch_marker = switch_node->get_switch_marker();- resulted_cf_marker.new_markers[switch_marker] = {switch_node};+ resulted_cf_marker.new_markers[switch_marker].insert(switch_node);resulted_cf_marker.existing_markers_with_branches = combined_markers_with_branches;resulted_cf_marker.existing_markers_with_switches = combined_markers_with_switches;} else {diff --git a/src/frontends/tensorflow/src/tf_utils.hpp b/src/frontends/tensorflow/src/tf_utils.hppindex 54bf0e03a0e..148310663df 100644--- a/src/frontends/tensorflow/src/tf_utils.hpp+++ b/src/frontends/tensorflow/src/tf_utils.hpp@@ -4,6 +4,11 @@#pragma once+#include <memory>+#include <set>+#include <unordered_map>+#include <unordered_set>+#include "openvino/core/node.hpp"#include "openvino/core/partial_shape.hpp"#include "openvino/core/runtime_attribute.hpp"@@ -33,7 +38,10 @@ ov::Any unpack_tensor_proto(const ::tensorflow::TensorProto& tensor_proto,const ::tensorflow::DataType& tensor_type);class Switch;-using SetOfSwitchNodes = std::unordered_set<std::shared_ptr<Switch>>;+// Hold Switch nodes via weak_ptr so a Switch marker stored in the node's own rt_info does not+// create a shared_ptr self-cycle (which would keep the node - and the TF GraphDef it pins via its+// decoder - alive forever). owner_less gives stable identity-based ordering for the set.+using SetOfSwitchNodes = std::set<std::weak_ptr<Switch>, std::owner_less<std::weak_ptr<Switch>>>;using SetOfBranchIndices = std::unordered_set<uint32_t>;// structure to save conditional flow marker@@ -47,7 +55,6 @@ public:// new_markers serves to mark Switch node and saves its own marker id// Switch node contains only one marker// for other type of nodes, new_markers vector is empty- // std::vector<std::pair<uint32_t, std::shared_ptr<ov::Node>>> new_markers;std::unordered_map<uint32_t, SetOfSwitchNodes> new_markers;// existing_markers contains Switch node markers collected so far@@ -60,14 +67,7 @@ public:// are merging by this Merge node// for example, if existing_markers contains element with a key = 4 (it means the fourth conditional flow)// and value {0, 1}, it means Merge node eliminates this conditional flow with marker = 4- // std::vector<std::pair<uint32_t, SetOfSwitchNodes>> merge_eliminated_markers;std::unordered_map<uint32_t, SetOfSwitchNodes> merge_eliminated_markers;-- // a container with already eliminated markers for nodes going after Merge nodes- // that eliminated conditional flow with these markers- // this container is needed do not duplicate markers for If sub-graphs that goes after other If- // sub-graphs with common condition- // std::unordered_set<uint32_t> already_eliminated_markers;};// a map type to save data/control edges from which the node is dependentdiff --git a/src/frontends/tensorflow/src/transformations/switch_merge_resolve.cpp b/src/frontends/tensorflow/src/transformations/switch_merge_resolve.cppindex 95e7e66cdd7..9c6354ea237 100644--- a/src/frontends/tensorflow/src/transformations/switch_merge_resolve.cpp+++ b/src/frontends/tensorflow/src/transformations/switch_merge_resolve.cpp@@ -58,7 +58,7 @@ void generate_if_clusters(const shared_ptr<Model>& ov_model,// combine all Switch nodes for which conditional flow is resolved// by the current Merge node- SetOfSwitchNodes switch_nodes;+ unordered_set<shared_ptr<Switch>> switch_nodes;for (const auto& eliminated_marker : eliminated_markers) {auto curr_switch_nodes = merge_node->get_switch_nodes_set_by_cond_index(eliminated_marker);switch_nodes.insert(curr_switch_nodes.begin(), curr_switch_nodes.end());diff --git a/src/frontends/tensorflow/tests/convert_tricky_models.cpp b/src/frontends/tensorflow/tests/convert_tricky_models.cppindex 100165a4b07..d4a98f81581 100644--- a/src/frontends/tensorflow/tests/convert_tricky_models.cpp+++ b/src/frontends/tensorflow/tests/convert_tricky_models.cpp@@ -2,6 +2,8 @@// SPDX-License-Identifier: Apache-2.0//+#include <functional>+#include "common_test_utils/test_common.hpp"#include "conversion_with_reference.hpp"#include "gtest/gtest.h"@@ -38,6 +40,8 @@#include "openvino/op/transpose.hpp"#include "openvino/op/unique.hpp"#include "openvino/op/unsqueeze.hpp"+#include "openvino/op/util/framework_node.hpp"+#include "openvino/op/util/multi_subgraph_base.hpp"#include "tf_utils.hpp"#include "transformations/common_optimizations/moc_transformations.hpp"#include "utils.hpp"@@ -884,3 +888,44 @@ TEST(FrontEndConvertTrickyModels, dynpart_overflow_num_partitions) {FAIL() << "DynamicPartition with overflowing num_partitions failed with unexpected exception type.";}}++namespace {+// Recursively walk all operations of a model and its sub-graphs (If/Loop bodies).+void for_each_op_recursive(const std::shared_ptr<Model>& model,+ const std::function<void(const shared_ptr<Node>&)>& fn) {+ for (const auto& op : model->get_ordered_ops()) {+ fn(op);+ if (auto multisubgraph_op = as_type_ptr<ov::op::util::MultiSubGraphOp>(op)) {+ for (size_t i = 0; i < multisubgraph_op->get_internal_subgraphs_size(); ++i) {+ for_each_op_recursive(multisubgraph_op->get_function(static_cast<int>(i)), fn);+ }+ }+ }+}+} // namespace++// A TF1 While loop must fuse fully into a Loop, leaving no control-flow helper op (Switch/Merge/+// Enter/Exit/NextIteration/LoopCond, all FrameworkNode subclasses); a surviving helper pins the TF+// GraphDef alive (the memory leak). Checks helper-op absence, not marker absence - weak_ptr markers+// may legitimately remain in rt_info without owning anything.+TEST(FrontEndConvertTrickyModels, ModelTF1WhileNoLeftoverControlFlow) {+ shared_ptr<Model> model = nullptr;+ ASSERT_NO_THROW(model = convert_model("model_tf1_while/model_tf1_while.pbtxt"));+ ASSERT_NE(model, nullptr);++ for_each_op_recursive(model, [](const shared_ptr<Node>& op) {+ EXPECT_FALSE(ov::as_type_ptr<ov::op::util::FrameworkNode>(op))+ << "unconverted framework/helper node survived: '" << op->get_friendly_name()+ << "' type=" << op->get_type_name();+ });+}++// A Switch consumed only through control dependencies is pruned and freed before Switch/Merge+// resolution, so its weak_ptr in a Merge conditional-flow marker legitimately expires. Conversion+// must skip such expired entries, not fail. Guards against re-introducing a fail-fast that aborts.+TEST(FrontEndConvertTrickyModels, ModelSwitchMergeSeveralCondFlows) {+ shared_ptr<Model> model = nullptr;+ ASSERT_NO_THROW(+ model = convert_model("model_switch_merge_several_cond_flows/model_switch_merge_several_cond_flows.pbtxt"));+ ASSERT_NE(model, nullptr);+}diff --git a/src/frontends/tensorflow/tests/test_models/models_pbtxt/model_switch_merge_several_cond_flows.pbtxt b/src/frontends/tensorflow/tests/test_models/models_pbtxt/model_switch_merge_several_cond_flows.pbtxtnew file mode 100644index 00000000000..ae14cf2718a--- /dev/null+++ b/src/frontends/tensorflow/tests/test_models/models_pbtxt/model_switch_merge_several_cond_flows.pbtxt@@ -0,0 +1,218 @@+node {+ name: "x"+ op: "Placeholder"+ attr {+ key: "dtype"+ value {+ type: DT_FLOAT+ }+ }+ attr {+ key: "shape"+ value {+ shape {+ dim {+ size: 2+ }+ }+ }+ }+}+node {+ name: "Const"+ op: "Const"+ attr {+ key: "dtype"+ value {+ type: DT_BOOL+ }+ }+ attr {+ key: "value"+ value {+ tensor {+ dtype: DT_BOOL+ tensor_shape {+ }+ bool_val: true+ }+ }+ }+}+node {+ name: "Switch"+ op: "Switch"+ input: "x"+ input: "Const"+ attr {+ key: "T"+ value {+ type: DT_FLOAT+ }+ }+}+node {+ name: "Const_1"+ op: "Const"+ attr {+ key: "dtype"+ value {+ type: DT_BOOL+ }+ }+ attr {+ key: "value"+ value {+ tensor {+ dtype: DT_BOOL+ tensor_shape {+ }+ bool_val: true+ }+ }+ }+}+node {+ name: "Switch_1"+ op: "Switch"+ input: "Const_1"+ input: "Const_1"+ attr {+ key: "T"+ value {+ type: DT_BOOL+ }+ }+ attr {+ key: "_has_manual_control_dependencies"+ value {+ b: true+ }+ }+}+node {+ name: "Const_2"+ op: "Const"+ input: "^Switch_1"+ attr {+ key: "dtype"+ value {+ type: DT_FLOAT+ }+ }+ attr {+ key: "value"+ value {+ tensor {+ dtype: DT_FLOAT+ tensor_shape {+ }+ float_val: 5.0+ }+ }+ }+}+node {+ name: "Const_3"+ op: "Const"+ input: "^Switch_1"+ attr {+ key: "dtype"+ value {+ type: DT_FLOAT+ }+ }+ attr {+ key: "value"+ value {+ tensor {+ dtype: DT_FLOAT+ tensor_shape {+ }+ float_val: 2.0+ }+ }+ }+}+node {+ name: "AddV2"+ op: "AddV2"+ input: "Switch"+ input: "Const_3"+ attr {+ key: "T"+ value {+ type: DT_FLOAT+ }+ }+}+node {+ name: "Sub"+ op: "Sub"+ input: "Switch:1"+ input: "Const_2"+ attr {+ key: "T"+ value {+ type: DT_FLOAT+ }+ }+}+node {+ name: "Merge"+ op: "Merge"+ input: "AddV2"+ input: "Sub"+ attr {+ key: "N"+ value {+ i: 2+ }+ }+ attr {+ key: "T"+ value {+ type: DT_FLOAT+ }+ }+}+node {+ name: "Const_4"+ op: "Const"+ attr {+ key: "dtype"+ value {+ type: DT_FLOAT+ }+ }+ attr {+ key: "value"+ value {+ tensor {+ dtype: DT_FLOAT+ tensor_shape {+ }+ float_val: 1.0+ }+ }+ }+}+node {+ name: "AddV2_1"+ op: "AddV2"+ input: "Merge"+ input: "Const_4"+ attr {+ key: "T"+ value {+ type: DT_FLOAT+ }+ }+}+node {+ name: "init"+ op: "NoOp"+}+versions {+ producer: 2288+}diff --git a/src/frontends/tensorflow/tests/test_models/models_pbtxt/model_switch_merge_several_cond_flows.py b/src/frontends/tensorflow/tests/test_models/models_pbtxt/model_switch_merge_several_cond_flows.pynew file mode 100644index 00000000000..4aecbd5ed38--- /dev/null+++ b/src/frontends/tensorflow/tests/test_models/models_pbtxt/model_switch_merge_several_cond_flows.py@@ -0,0 +1,35 @@+# Copyright (C) 2018-2026 Intel Corporation+# SPDX-License-Identifier: Apache-2.0++# Documents how model_switch_merge_several_cond_flows.pbtxt was produced.+# Two Switch nodes: `Switch` feeds real data (AddV2/Sub -> Merge); `Switch_1` is consumed only+# through control dependencies, so the frontend prunes and frees it before Switch/Merge resolution+# and its weak_ptr in the Merge conditional-flow marker legitimately expires. Regenerate by running+# this in a TensorFlow environment.++import numpy as np+import tensorflow.compat.v1 as tf++tf.reset_default_graph()++with tf.Session() as sess:+ x = tf.placeholder(np.float32, [2], 'x')+ cond = tf.constant(True, dtype=tf.bool)+ switch_false, switch_true = tf.raw_ops.Switch(data=x, pred=cond)++ cond2 = tf.constant(True, dtype=tf.bool)+ switch2_false, switch2_true = tf.raw_ops.Switch(data=cond2, pred=cond2)+ with tf.control_dependencies([switch2_true]):+ const_sub = tf.constant(5, dtype=np.float32)+ with tf.control_dependencies([switch2_false]):+ const_add = tf.constant(2, dtype=np.float32)++ add = tf.raw_ops.AddV2(x=switch_false, y=const_add)+ sub = tf.raw_ops.Sub(x=switch_true, y=const_sub)+ merge = tf.raw_ops.Merge(inputs=[add, sub])+ const_main = tf.constant(1, dtype=np.float32)+ tf.raw_ops.AddV2(x=merge[0], y=const_main)+ tf.global_variables_initializer()+ tf_net = sess.graph_def++tf.io.write_graph(tf_net, './', 'model_switch_merge_several_cond_flows.pbtxt', True)diff --git a/src/frontends/tensorflow_common/include/helper_ops/merge.hpp b/src/frontends/tensorflow_common/include/helper_ops/merge.hppindex e2abd1e5ac6..77d9c8d7bc5 100644--- a/src/frontends/tensorflow_common/include/helper_ops/merge.hpp+++ b/src/frontends/tensorflow_common/include/helper_ops/merge.hpp@@ -98,8 +98,18 @@ public:auto cf_marker = get_cf_marker(this_node);FRONT_END_GENERAL_CHECK(cf_marker.merge_eliminated_markers.count(switch_marker) > 0,- "[TensorFlow Frontend] internal error: no Switch node with requiested conditional flow marker");- return cf_marker.merge_eliminated_markers[switch_marker];+ "[TensorFlow Frontend] internal error: no Switch node with requested conditional flow marker");+ // Markers store Switch nodes as weak_ptr (see SetOfSwitchNodes). A Switch that only fed+ // control dependencies can be pruned and freed before this pass runs, so its weak_ptr is+ // legitimately expired; skip such entries - a freed Switch is not part of any surviving+ // Switch/Merge cluster to fuse.+ std::unordered_set<std::shared_ptr<Switch>> switch_nodes;+ for (const auto& weak_switch : cf_marker.merge_eliminated_markers.at(switch_marker)) {+ if (auto switch_node = weak_switch.lock()) {+ switch_nodes.insert(std::move(switch_node));+ }+ }+ return switch_nodes;}std::shared_ptr<Node> clone_with_new_inputs(const OutputVector& inputs) const override {