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
[ONNX] Support subgraphs with initializers as outputs (#35261)
Maxim Vafin51ac1b94f89e
diff --git a/src/frontends/onnx/frontend/src/core/graph_iterator_proto.cpp b/src/frontends/onnx/frontend/src/core/graph_iterator_proto.cppindex e70d02a1387..9eeff6d10ef 100644--- a/src/frontends/onnx/frontend/src/core/graph_iterator_proto.cpp+++ b/src/frontends/onnx/frontend/src/core/graph_iterator_proto.cpp@@ -103,6 +103,54 @@ void fixup_legacy_nodes(::ONNX_NAMESPACE::ModelProto& model_proto) {}}+/// \brief Collect all external references from a subgraph, recursing into nested subgraphs.+/// Returns all tensor names referenced by the subgraph (directly or via nested subgraphs)+/// that are not defined within the subgraph itself.+void collect_subgraph_external_refs(const GraphProto& subgraph, std::unordered_set<std::string>& deps) {+ // Build set of names defined within this subgraph+ std::unordered_set<std::string> subgraph_defined;+ for (const auto& input : subgraph.input()) {+ subgraph_defined.insert(input.name());+ }+ for (const auto& init : subgraph.initializer()) {+ subgraph_defined.insert(init.name());+ }+ for (const auto& sub_node : subgraph.node()) {+ for (const auto& out : sub_node.output()) {+ subgraph_defined.insert(out);+ }+ }+ // Collect direct references to outer graph tensors+ for (const auto& sub_node : subgraph.node()) {+ for (const auto& inp : sub_node.input()) {+ if (!inp.empty() && subgraph_defined.count(inp) == 0) {+ deps.insert(inp);+ }+ }+ // Recurse into nested subgraphs+ for (const auto& attr : sub_node.attribute()) {+ if (attr.has_g()) {+ std::unordered_set<std::string> nested_deps;+ collect_subgraph_external_refs(attr.g(), nested_deps);+ // Nested external refs that are also external to this subgraph+ for (const auto& dep : nested_deps) {+ if (subgraph_defined.count(dep) == 0) {+ deps.insert(dep);+ }+ }+ }+ }+ }+ // Subgraph outputs may directly reference outer-scope tensors when the body+ // has no node producing them (e.g., an If branch returning a parent value).+ for (const auto& output : subgraph.output()) {+ const auto& name = output.name();+ if (!name.empty() && subgraph_defined.count(name) == 0) {+ deps.insert(name);+ }+ }+}+/// \brief Collect all dependencies for a node (direct inputs + subgraph external references).void collect_node_dependencies(const NodeProto& node, std::unordered_set<std::string>& deps) {// Direct inputs@@ -116,28 +164,7 @@ void collect_node_dependencies(const NodeProto& node, std::unordered_set<std::stif (!attr.has_g()) {continue;}- const auto& subgraph = attr.g();- // Build set of names defined within the subgraph- std::unordered_set<std::string> subgraph_defined;- for (const auto& input : subgraph.input()) {- subgraph_defined.insert(input.name());- }- for (const auto& init : subgraph.initializer()) {- subgraph_defined.insert(init.name());- }- for (const auto& sub_node : subgraph.node()) {- for (const auto& out : sub_node.output()) {- subgraph_defined.insert(out);- }- }- // Find references to outer graph tensors- for (const auto& sub_node : subgraph.node()) {- for (const auto& inp : sub_node.input()) {- if (!inp.empty() && subgraph_defined.count(inp) == 0) {- deps.insert(inp);- }- }- }+ collect_subgraph_external_refs(attr.g(), deps);}}diff --git a/src/frontends/onnx/frontend/src/input_model.cpp b/src/frontends/onnx/frontend/src/input_model.cppindex a8ddb06a5f7..81c27795915 100644--- a/src/frontends/onnx/frontend/src/input_model.cpp+++ b/src/frontends/onnx/frontend/src/input_model.cpp@@ -685,22 +685,24 @@ void InputModel::InputModelONNXImpl::load_model() {if (auto tensor_decoder = std::dynamic_pointer_cast<DecoderBaseTensor>(decoder)) {auto tensor_place =decode_tensor_place(tensor_decoder->get_tensor_info(), m_input_model, m_reuse_const_data);+ const auto output_idx = tensor_decoder->get_output_idx();tensor_place->set_input_index(tensor_decoder->get_input_idx());- tensor_place->set_output_index(tensor_decoder->get_output_idx());+ tensor_place->set_output_index(output_idx);- // Constant with data has been found- if (tensor_place->get_data() != nullptr)+ const bool has_data = tensor_place->get_data() != nullptr || tensor_place->get_data_location() != nullptr;+ // Skip constants that are not graph outputs — they don't contribute to the model graph.+ if (has_data && output_idx < 0)continue;auto tensor_place_registered = register_tensor_place(tensor_place);if (!tensor_place_registered)continue;- if (tensor_place_registered->is_input())+ if (!has_data && tensor_place_registered->is_input())m_inputs.push_back(tensor_place_registered);- if (tensor_decoder->get_output_idx() >= 0) {+ if (output_idx >= 0) {m_outputs.push_back(tensor_place_registered);- output_indices.push_back(tensor_decoder->get_output_idx());+ output_indices.push_back(output_idx);}} else {auto op_place = std::make_shared<OpPlace>(m_input_model, decoder);diff --git a/src/frontends/onnx/frontend/src/op/if.cpp b/src/frontends/onnx/frontend/src/op/if.cppindex f38f6c2412f..4854f904e81 100644--- a/src/frontends/onnx/frontend/src/op/if.cpp+++ b/src/frontends/onnx/frontend/src/op/if.cpp@@ -8,6 +8,8 @@#include "core/operator_set.hpp"#include "openvino/core/model.hpp"#include "openvino/frontend/exception.hpp"+#include "openvino/op/constant.hpp"+#include "openvino/op/parameter.hpp"#include "translate_session.hpp"using namespace ov::op;@@ -123,6 +125,31 @@ ov::OutputVector if_op(const ov::frontend::onnx::Node& node) {auto then_results = then_branch->get_results();auto else_results = else_branch->get_results();++ // The InputModel for subgraphs may register parent-scope tensors (that are+ // also outputs of the parent graph) as additional subgraph outputs. Trim+ // branches to the ONNX node's declared output count, but only trim results+ // that are parent-scope pass-throughs (Parameter → Result chains), not+ // genuine computation outputs.+ const size_t expected_outputs = node.get_outputs_size();+ auto trim_parent_scope_results = [](ov::ResultVector& branch_results, size_t target) {+ while (branch_results.size() > target) {+ auto last = branch_results.back();+ auto src = last->input_value(0).get_node_shared_ptr();+ // Accept: Parameter, Constant, or single-input node wrapping Parameter/Constant+ bool is_passthrough = ov::is_type<v0::Parameter>(src) || ov::is_type<v0::Constant>(src);+ if (!is_passthrough && src->get_input_size() == 1 && src->get_output_size() == 1) {+ auto inner = src->input_value(0).get_node_shared_ptr();+ is_passthrough = ov::is_type<v0::Parameter>(inner) || ov::is_type<v0::Constant>(inner);+ }+ if (!is_passthrough)+ break;+ branch_results.pop_back();+ }+ };+ trim_parent_scope_results(then_results, expected_outputs);+ trim_parent_scope_results(else_results, expected_outputs);+FRONT_END_GENERAL_CHECK(then_results.size() == else_results.size(),"'then' and 'else' branches have to have the same number of outputs");int output_size = static_cast<int>(then_results.size());diff --git a/src/frontends/onnx/frontend/src/op/loop.cpp b/src/frontends/onnx/frontend/src/op/loop.cppindex 8c497c1d528..0de92ceeb10 100644--- a/src/frontends/onnx/frontend/src/op/loop.cpp+++ b/src/frontends/onnx/frontend/src/op/loop.cpp@@ -295,6 +295,18 @@ ov::OutputVector loop(const ov::frontend::onnx::Node& node) {}body_outputs = std::move(filtered_body_outputs);+ // The InputModel for subgraphs may register parent-scope constants that are+ // also outputs of the parent graph as additional body outputs (initializer+ // declared as a body graph output without being consumed by any node).+ // The Loop body must have exactly 1 (termination cond) + node.get_outputs_size()+ // outputs, so trim trailing pass-through Constants that are not real loop+ // outputs.+ const size_t expected_body_outputs = 1 + node.get_outputs_size();+ while (body_outputs.size() > expected_body_outputs &&+ ov::is_type<v0::Constant>(body_outputs.back().get_node_shared_ptr())) {+ body_outputs.pop_back();+ }+CHECK_VALID_NODE(node,canonical_inputs.size() >= control_inputs_count &&canonical_inputs.size() - control_inputs_count == loop_carried_dependencies.size(),diff --git a/src/frontends/onnx/frontend/src/op/scan.cpp b/src/frontends/onnx/frontend/src/op/scan.cppindex d1acf633b3c..635be82b598 100644--- a/src/frontends/onnx/frontend/src/op/scan.cpp+++ b/src/frontends/onnx/frontend/src/op/scan.cpp@@ -6,6 +6,7 @@#include "core/null_node.hpp"#include "core/operator_set.hpp"#include "exceptions.hpp"+#include "openvino/core/type.hpp"#include "openvino/frontend/exception.hpp"#include "openvino/op/constant.hpp"#include "openvino/op/squeeze.hpp"@@ -156,6 +157,17 @@ ov::OutputVector import_onnx_scan(const ov::frontend::onnx::Node& node,body_outputs.push_back(res->get_input_source_output(0));}body_inputs = body_graph->get_parameters();++ // The InputModel for subgraphs may register parent-scope constants that+ // are also declared as body graph outputs (initializer-as-output) as+ // additional body outputs. Trim trailing pass-through Constants beyond+ // the Scan node's declared output count so num_scan_outputs is computed+ // correctly below.+ const size_t expected_body_outputs = node.get_outputs_size();+ while (body_outputs.size() > expected_body_outputs &&+ ov::is_type<v0::Constant>(body_outputs.back().get_node_shared_ptr())) {+ body_outputs.pop_back();+ }}const int64_t num_scan_inputs_signed = node.get_attribute_value<int64_t>("num_scan_inputs");diff --git a/src/frontends/onnx/frontend/src/translate_session.cpp b/src/frontends/onnx/frontend/src/translate_session.cppindex 99584f7191e..46ba183366e 100644--- a/src/frontends/onnx/frontend/src/translate_session.cpp+++ b/src/frontends/onnx/frontend/src/translate_session.cpp@@ -194,15 +194,37 @@ void TranslateSession::translate_graph(const ov::frontend::InputModel::Ptr& inpu}// outputs+ // Materialize any output tensors that are direct constants (initializers used as graph+ // outputs without being consumed by any op). These are not created during the inputs or+ // operations loops because they have data but are not referenced as op inputs.+ // Also handle subgraph outputs that reference parent scope tensors — lookup_tensor()+ // will create a Parameter for any parent-scope non-constant value.ResultVector results;results.reserve(model_onnx->get_outputs().size());for (const auto& output : model_onnx->get_outputs()) {const auto tensor = std::dynamic_pointer_cast<ov::frontend::onnx::TensorONNXPlace>(output);FRONT_END_GENERAL_CHECK(tensor != nullptr,- "Inputs of ov::frontend::onnx::InputModel must be TensorONNXPlace instances");+ "Outputs of ov::frontend::onnx::InputModel must be TensorONNXPlace instances");const auto name = tensor->get_names()[0];if (!m_tensor_values.count(name)) {- continue;+ auto place_it = all_tensor_places.find(name);+ if (place_it != all_tensor_places.end() &&+ (place_it->second->get_data() != nullptr || place_it->second->get_data_location() != nullptr)) {+ create_const_or_param(name, place_it->second);+ } else if (auto parent_value = lookup_tensor(name); parent_value.get_node() != nullptr) {+ // lookup_tensor() resolved the name from a parent scope. For non-constant+ // parent values it already cached a Parameter in m_tensor_values; for+ // parent-scope Constants it returns the Constant directly without caching,+ // so insert it here to make the subsequent m_tensor_values[name] lookup+ // safe.+ m_tensor_values.emplace(name, parent_value);+ } else {+ FRONT_END_GENERAL_CHECK(false,+ "Output tensor \"",+ name,+ "\" was declared as a graph output but is not produced by any operation, "+ "is not an initializer, and cannot be resolved from a parent scope.");+ }}const auto& output_value = m_tensor_values[name];const auto result = std::make_shared<ov::op::v0::Result>(output_value);diff --git a/src/frontends/onnx/tests/models/controlflow/if_with_initializer_as_output.prototxt b/src/frontends/onnx/tests/models/controlflow/if_with_initializer_as_output.prototxtnew file mode 100644index 00000000000..b931a8c08e1--- /dev/null+++ b/src/frontends/onnx/tests/models/controlflow/if_with_initializer_as_output.prototxt@@ -0,0 +1,104 @@+ir_version: 7+producer_name: "OpenVINO ONNX Frontend"+graph {+ name: "if_with_initializer_output"+ node {+ input: "condition"+ output: "result"+ name: "if_node"+ op_type: "If"+ attribute {+ name: "then_branch"+ type: GRAPH+ g {+ name: "then_branch"+ node {+ input: "x"+ output: "then_out"+ name: "then_identity"+ op_type: "Identity"+ }+ output {+ name: "then_out"+ type {+ tensor_type {+ elem_type: 1+ shape {+ dim {+ dim_value: 3+ }+ }+ }+ }+ }+ }+ }+ attribute {+ name: "else_branch"+ type: GRAPH+ g {+ name: "else_branch"+ initializer {+ dims: 3+ data_type: 1+ float_data: 0.0+ float_data: 0.0+ float_data: 0.0+ name: "else_const"+ }+ output {+ name: "else_const"+ type {+ tensor_type {+ elem_type: 1+ shape {+ dim {+ dim_value: 3+ }+ }+ }+ }+ }+ }+ }+ }+ input {+ name: "condition"+ type {+ tensor_type {+ elem_type: 9+ shape {+ }+ }+ }+ }+ input {+ name: "x"+ type {+ tensor_type {+ elem_type: 1+ shape {+ dim {+ dim_value: 3+ }+ }+ }+ }+ }+ output {+ name: "result"+ type {+ tensor_type {+ elem_type: 1+ shape {+ dim {+ dim_value: 3+ }+ }+ }+ }+ }+}+opset_import {+ version: 14+}diff --git a/src/frontends/onnx/tests/models/controlflow/loop_with_initializer_as_output.prototxt b/src/frontends/onnx/tests/models/controlflow/loop_with_initializer_as_output.prototxtnew file mode 100644index 00000000000..22d26cdae35--- /dev/null+++ b/src/frontends/onnx/tests/models/controlflow/loop_with_initializer_as_output.prototxt@@ -0,0 +1,157 @@+ir_version: 7+producer_name: "OpenVINO ONNX Frontend"+graph {+ name: "loop_with_initializer_output"+ node {+ input: "trip_count"+ input: "cond_in"+ input: "x_init"+ output: "x_final"+ name: "loop_node"+ op_type: "Loop"+ attribute {+ name: "body"+ type: GRAPH+ g {+ name: "loop_body"+ initializer {+ dims: 1+ data_type: 1+ float_data: 1.0+ name: "step"+ }+ node {+ input: "x_in"+ input: "step"+ output: "x_out"+ name: "add_step"+ op_type: "Add"+ }+ node {+ input: "cond_body_in"+ output: "cond_body_out"+ name: "cond_passthrough"+ op_type: "Identity"+ }+ input {+ name: "iter"+ type {+ tensor_type {+ elem_type: 7+ shape {+ }+ }+ }+ }+ input {+ name: "cond_body_in"+ type {+ tensor_type {+ elem_type: 9+ shape {+ }+ }+ }+ }+ input {+ name: "x_in"+ type {+ tensor_type {+ elem_type: 1+ shape {+ dim {+ dim_value: 1+ }+ }+ }+ }+ }+ output {+ name: "cond_body_out"+ type {+ tensor_type {+ elem_type: 9+ shape {+ }+ }+ }+ }+ output {+ name: "x_out"+ type {+ tensor_type {+ elem_type: 1+ shape {+ dim {+ dim_value: 1+ }+ }+ }+ }+ }+ output {+ name: "step"+ type {+ tensor_type {+ elem_type: 1+ shape {+ dim {+ dim_value: 1+ }+ }+ }+ }+ }+ }+ }+ }+ input {+ name: "trip_count"+ type {+ tensor_type {+ elem_type: 7+ shape {+ }+ }+ }+ }+ input {+ name: "cond_in"+ type {+ tensor_type {+ elem_type: 9+ shape {+ }+ }+ }+ }+ input {+ name: "x_init"+ type {+ tensor_type {+ elem_type: 1+ shape {+ dim {+ dim_value: 1+ }+ }+ }+ }+ }+ output {+ name: "x_final"+ type {+ tensor_type {+ elem_type: 1+ shape {+ dim {+ dim_value: 1+ }+ }+ }+ }+ }+}+opset_import {+ version: 14+}diff --git a/src/frontends/onnx/tests/models/controlflow/scan_with_initializer_as_output.prototxt b/src/frontends/onnx/tests/models/controlflow/scan_with_initializer_as_output.prototxtnew file mode 100644index 00000000000..48d88d2e128--- /dev/null+++ b/src/frontends/onnx/tests/models/controlflow/scan_with_initializer_as_output.prototxt@@ -0,0 +1,170 @@+ir_version: 7+producer_name: "OpenVINO ONNX Frontend"+graph {+ name: "scan_with_initializer_output"+ node {+ input: "init_state"+ input: "seq"+ output: "final_state"+ output: "scan_out"+ name: "scan_node"+ op_type: "Scan"+ attribute {+ name: "num_scan_inputs"+ type: INT+ i: 1+ }+ attribute {+ name: "body"+ type: GRAPH+ g {+ name: "scan_body"+ initializer {+ dims: 1+ data_type: 1+ float_data: 7.0+ name: "leak"+ }+ node {+ input: "state_in"+ input: "seq_in"+ output: "state_next"+ name: "add"+ op_type: "Add"+ }+ node {+ input: "state_next"+ output: "state_copy"+ name: "ident"+ op_type: "Identity"+ }+ input {+ name: "state_in"+ type {+ tensor_type {+ elem_type: 1+ shape {+ dim {+ dim_value: 1+ }+ }+ }+ }+ }+ input {+ name: "seq_in"+ type {+ tensor_type {+ elem_type: 1+ shape {+ dim {+ dim_value: 1+ }+ }+ }+ }+ }+ output {+ name: "state_next"+ type {+ tensor_type {+ elem_type: 1+ shape {+ dim {+ dim_value: 1+ }+ }+ }+ }+ }+ output {+ name: "state_copy"+ type {+ tensor_type {+ elem_type: 1+ shape {+ dim {+ dim_value: 1+ }+ }+ }+ }+ }+ output {+ name: "leak"+ type {+ tensor_type {+ elem_type: 1+ shape {+ dim {+ dim_value: 1+ }+ }+ }+ }+ }+ }+ }+ }+ input {+ name: "init_state"+ type {+ tensor_type {+ elem_type: 1+ shape {+ dim {+ dim_value: 1+ }+ }+ }+ }+ }+ input {+ name: "seq"+ type {+ tensor_type {+ elem_type: 1+ shape {+ dim {+ dim_value: 3+ }+ dim {+ dim_value: 1+ }+ }+ }+ }+ }+ output {+ name: "final_state"+ type {+ tensor_type {+ elem_type: 1+ shape {+ dim {+ dim_value: 1+ }+ }+ }+ }+ }+ output {+ name: "scan_out"+ type {+ tensor_type {+ elem_type: 1+ shape {+ dim {+ dim_value: 3+ }+ dim {+ dim_value: 1+ }+ }+ }+ }+ }+}+opset_import {+ version: 11+}diff --git a/src/frontends/onnx/tests/onnx_import_controlflow.in.cpp b/src/frontends/onnx/tests/onnx_import_controlflow.in.cppindex 14e3d3f931d..1a4a0d40d68 100644--- a/src/frontends/onnx/tests/onnx_import_controlflow.in.cpp+++ b/src/frontends/onnx/tests/onnx_import_controlflow.in.cpp@@ -776,6 +776,69 @@ OPENVINO_TEST(${BACKEND_NAME}, onnx_if_negative_missing_branches) {}}+OPENVINO_TEST(${BACKEND_NAME}, onnx_if_with_initializer_as_output) {+ /*+ if (condition) {+ return identity(x)+ } else {+ return initializer constant [0, 0, 0]+ }+ Tests that an If branch whose output is directly an initializer+ (no compute nodes, no graph inputs) converts correctly.+ */+ const auto model = convert_model("controlflow/if_with_initializer_as_output.onnx");++ auto test_case = ov::test::TestCase(model, s_device);++ // condition == true => return x+ test_case.add_input<bool>({true});+ test_case.add_input<float>({1.0f, 2.0f, 3.0f});+ test_case.add_expected_output<float>({1.0f, 2.0f, 3.0f});+ test_case.run();++ // condition == false => return initializer [0, 0, 0]+ test_case.add_input<bool>({false});+ test_case.add_input<float>({1.0f, 2.0f, 3.0f});+ test_case.add_expected_output<float>({0.0f, 0.0f, 0.0f});+ test_case.run();+}++OPENVINO_TEST(${BACKEND_NAME}, onnx_loop_with_initializer_as_output) {+ /*+ Loop body declares an initializer ("step") as one of its graph outputs+ in addition to the canonical [cond_out, loop_carried_out].+ The body output count therefore exceeds 1 + node.get_outputs_size(); the+ trailing Constant pass-through must be trimmed so num_scan_outputs is 0+ and the Loop converts correctly.+ */+ const auto model = convert_model("controlflow/loop_with_initializer_as_output.onnx");++ auto test_case = ov::test::TestCase(model, s_device);+ test_case.add_input<int64_t>({3}); // trip_count+ test_case.add_input<bool>({true}); // cond_in+ test_case.add_input<float>({0.0f}); // x_init+ test_case.add_expected_output<float>(Shape{1}, {3.0f});+ test_case.run();+}++OPENVINO_TEST(${BACKEND_NAME}, onnx_scan_with_initializer_as_output) {+ /*+ Scan body declares an initializer ("leak") as a trailing graph output.+ The body output count would otherwise be miscounted as an extra scan+ output; the trailing Constant pass-through must be trimmed so the+ Scan converts with num_scan_outputs equal to node.get_outputs_size() -+ num_initial_values.+ */+ const auto model = convert_model("controlflow/scan_with_initializer_as_output.onnx");++ auto test_case = ov::test::TestCase(model, s_device);+ test_case.add_input<float>(Shape{1}, {0.0f}); // init_state+ test_case.add_input<float>(Shape{3, 1}, {1.0f, 2.0f, 3.0f}); // seq+ test_case.add_expected_output<float>(Shape{1}, {6.0f}); // final_state = 0+1+2+3+ test_case.add_expected_output<float>(Shape{3, 1}, {1.0f, 3.0f, 6.0f}); // scan outputs+ test_case.run();+}+OPENVINO_TEST(${BACKEND_NAME}, onnx_if_negative_mismatch_between_branches_output) {try {const auto model = convert_model("controlflow/if_negative_mismatch_between_branches_output.onnx");