Skip to content

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

[ONNX FE] Add lazy load for GraphIterator ONNX frontend (#36564)

Preetha Veeramalaidcb05aba1ace
diff --git a/src/frontends/onnx/frontend/src/core/node.cpp b/src/frontends/onnx/frontend/src/core/node.cpp
index 5f176d04701..3b6e24d3007 100644
--- a/src/frontends/onnx/frontend/src/core/node.cpp
+++ b/src/frontends/onnx/frontend/src/core/node.cpp
@@ -8,6 +8,7 @@
#include "core/attribute.hpp"
#include "core/graph.hpp"
+#include "core/graph_iterator_proto.hpp"
#include "core/null_node.hpp"
#include "core/tensor.hpp"
#include "input_model.hpp"
@@ -990,7 +991,14 @@ std::shared_ptr<ov::Model> Node::get_attribute_value(const std::string& name) co
auto graph_iterator = m_decoder->get_attribute(name).as<const ov::frontend::onnx::GraphIterator::Ptr>();
FRONT_END_GENERAL_CHECK(graph_iterator != nullptr,
"GraphIterator attribute is missing or of wrong type for attribute: " + name);
- graph_iterator->reset();
+ // GraphIteratorProto builds its decoders lazily inside reset(): a freshly constructed
+ // subgraph proto iterator has an empty decoder list, so reset() is required there. Other
+ // GraphIterator implementations (e.g. the ORT EP delegate) construct already positioned at
+ // their first node and build decoders on demand, so reset() is unnecessary for them; skip
+ // it to mirror the top-level EP flow in FrontEnd::load_impl(), which likewise never resets.
+ if (std::dynamic_pointer_cast<ov::frontend::onnx::GraphIteratorProto>(graph_iterator)) {
+ graph_iterator->reset();
+ }
auto parent_model = std::dynamic_pointer_cast<onnx::unify::InputModel>(m_translate_session->get_input_model());
FRONT_END_GENERAL_CHECK(parent_model != nullptr, "Parent model is expected to be of onnx InputModel type.");
auto input_model = std::make_shared<onnx::unify::InputModel>(graph_iterator, parent_model);
diff --git a/src/frontends/onnx/frontend/src/input_model.cpp b/src/frontends/onnx/frontend/src/input_model.cpp
index 81c27795915..b2a8b8f7560 100644
--- a/src/frontends/onnx/frontend/src/input_model.cpp
+++ b/src/frontends/onnx/frontend/src/input_model.cpp
@@ -565,15 +565,34 @@ public:
const ov::frontend::InputModel& input_model,
unify::InputModel::Ptr parent_model);
+ // Returns the raw iterator so the single-pass converter can translate directly from
+ // decoders, bypassing the Place graph built by load_model().
+ GraphIterator::Ptr get_graph_iterator() const {
+ return m_graph_iterator;
+ }
+
+ bool is_loaded() const {
+ return m_loaded;
+ }
+
+ // Whether constant data may be wrapped zero-copy (vs. deep-copied). The single-pass converter
+ // needs this because it materializes Constants directly, bypassing the Place graph that would
+ // otherwise carry the flag.
+ bool is_const_data_reusable() const {
+ return m_reuse_const_data;
+ }
+
std::vector<ov::frontend::Place::Ptr> get_inputs() const;
std::vector<ov::frontend::Place::Ptr> get_outputs() const;
ov::frontend::Place::Ptr get_place_by_tensor_name(const std::string& tensorName) const;
///// Searching for places /////
std::vector<std::shared_ptr<OpPlace>>& get_op_places() {
+ ensure_loaded();
return m_op_places;
}
std::map<std::string, std::shared_ptr<TensorONNXPlace>>& get_tensor_places() {
+ ensure_loaded();
return m_tensor_places;
}
@@ -596,7 +615,7 @@ public:
const std::vector<ov::frontend::Place::Ptr>& outputs);
std::map<std::string, std::string> get_metadata() const {
- return m_metadata;
+ return m_loaded ? m_metadata : m_graph_iterator->get_metadata();
}
std::shared_ptr<TelemetryExtension> get_telemetry_extension() const {
@@ -622,7 +641,15 @@ public:
private:
void load_model();
void clean_up();
+ // Builds the Place graph on first access when construction deferred it.
+ void ensure_loaded() {
+ if (!m_loaded) {
+ load_model();
+ m_loaded = true;
+ }
+ }
+ bool m_loaded = false;
std::vector<std::shared_ptr<OpPlace>> m_op_places;
std::map<std::string, std::shared_ptr<OpPlace>> m_op_places_map;
std::map<std::string, std::shared_ptr<TensorONNXPlace>> m_tensor_places;
@@ -868,7 +895,9 @@ InputModel::InputModelONNXImpl::InputModelONNXImpl(const GraphIterator::Ptr& gra
m_mmap_cache = nullptr;
m_stream_cache = std::make_shared<std::map<std::filesystem::path, std::shared_ptr<std::ifstream>>>();
}
- load_model();
+ // The single-pass converter translates straight from the GraphIterator decoders and never reads
+ // the Place graph, so building it at construction is pure overhead. The Place graph is always
+ // deferred; any Place-graph accessor (editor API, decode, fallback convert) lazily builds it.
}
InputModel::InputModelONNXImpl::InputModelONNXImpl(const GraphIterator::Ptr& graph_iterator,
@@ -888,13 +917,16 @@ InputModel::InputModelONNXImpl::InputModelONNXImpl(const GraphIterator::Ptr& gra
m_model_dir = parent_model->_impl->m_model_dir;
}
load_model();
+ m_loaded = true;
}
std::vector<ov::frontend::Place::Ptr> InputModel::InputModelONNXImpl::get_inputs() const {
+ const_cast<InputModelONNXImpl*>(this)->ensure_loaded();
return m_inputs;
}
std::vector<ov::frontend::Place::Ptr> InputModel::InputModelONNXImpl::get_outputs() const {
+ const_cast<InputModelONNXImpl*>(this)->ensure_loaded();
return m_outputs;
}
@@ -906,6 +938,7 @@ std::shared_ptr<TensorPlace> castToTensorPlace(const ov::frontend::Place::Ptr& p
}
ov::frontend::Place::Ptr InputModel::InputModelONNXImpl::get_place_by_tensor_name(const std::string& tensorName) const {
+ const_cast<InputModelONNXImpl*>(this)->ensure_loaded();
if (m_tensor_places.find(tensorName) != m_tensor_places.end())
return castToTensorPlace(m_tensor_places.at(tensorName));
else
@@ -1011,6 +1044,18 @@ InputModel::InputModel(const GraphIterator::Ptr& graph_iterator,
const bool reuse_const_data)
: _impl{std::make_shared<InputModelONNXImpl>(graph_iterator, *this, telemetry, enable_mmap, reuse_const_data)} {}
+ov::frontend::onnx::GraphIterator::Ptr InputModel::get_graph_iterator() const {
+ return _impl->get_graph_iterator();
+}
+
+bool InputModel::is_loaded() const {
+ return _impl->is_loaded();
+}
+
+bool InputModel::is_const_data_reusable() const {
+ return _impl->is_const_data_reusable();
+}
+
InputModel::InputModel(const GraphIterator::Ptr& graph_iterator,
ov::frontend::onnx::unify::InputModel::Ptr parent_model)
: _impl{std::make_shared<InputModelONNXImpl>(graph_iterator, *this, parent_model)} {}
diff --git a/src/frontends/onnx/frontend/src/input_model.hpp b/src/frontends/onnx/frontend/src/input_model.hpp
index 20ebcc7cee0..53e500218bb 100644
--- a/src/frontends/onnx/frontend/src/input_model.hpp
+++ b/src/frontends/onnx/frontend/src/input_model.hpp
@@ -117,6 +117,17 @@ public:
explicit InputModel(const ov::frontend::onnx::GraphIterator::Ptr& graph_iterator,
unify::InputModel::Ptr parent_model);
+ /// \brief Returns the underlying GraphIterator without forcing the Place graph to be built.
+ /// Used by the single-pass converter to translate directly from decoders.
+ ov::frontend::onnx::GraphIterator::Ptr get_graph_iterator() const;
+
+ /// \brief True when load_model() has run and the Place graph is available.
+ bool is_loaded() const;
+
+ /// \brief True when constant data may be wrapped zero-copy rather than deep-copied.
+ /// Used by the single-pass converter, which materializes Constants without the Place graph.
+ bool is_const_data_reusable() const;
+
///// Searching for places /////
std::vector<ov::frontend::Place::Ptr> get_inputs() const override;
std::vector<ov::frontend::Place::Ptr> get_outputs() const override;
diff --git a/src/frontends/onnx/frontend/src/translate_session.cpp b/src/frontends/onnx/frontend/src/translate_session.cpp
index 3c015c034f9..079055deb43 100644
--- a/src/frontends/onnx/frontend/src/translate_session.cpp
+++ b/src/frontends/onnx/frontend/src/translate_session.cpp
@@ -5,6 +5,7 @@
#include "translate_session.hpp"
#include "core/null_node.hpp"
+#include "core/tensor.hpp"
#include "input_model.hpp"
#include "onnx_framework_node.hpp"
#include "openvino/frontend/onnx/decoder.hpp"
@@ -67,181 +68,338 @@ std::shared_ptr<ov::Model> TranslateSession::get_converted_model() {
return m_ov_model;
}
-void TranslateSession::translate_graph(const ov::frontend::InputModel::Ptr& input_model,
- std::shared_ptr<ov::Model>& ov_model) {
- const auto model_onnx = std::dynamic_pointer_cast<unify::InputModel>(input_model);
-
- auto& all_tensor_places = model_onnx->get_tensor_places();
-
- // inputs
- m_parameters.reserve(model_onnx->get_inputs().size());
-
- // Lambda detects type of input_tensor and creates correct node: constant or parameter
- auto create_const_or_param = [&](const std::string& name,
- const std::shared_ptr<ov::frontend::onnx::TensorONNXPlace>& input_tensor) {
- std::shared_ptr<ov::Node> node;
- if (input_tensor->get_data_location() != nullptr || input_tensor->get_data() != nullptr) {
- Tensor tensor = Tensor(input_tensor);
- node = tensor.get_ov_constant();
- } else if (input_tensor->get_partial_shape() == PartialShape{0}) { // empty constant
- node = ov::op::v0::Constant::create(input_tensor->get_element_type(),
- input_tensor->get_partial_shape().to_shape(),
- {});
+ov::OutputVector TranslateSession::apply_op_translator(const std::shared_ptr<DecoderBaseOperation>& decoder,
+ const std::shared_ptr<TelemetryExtension>& telemetry) {
+ const auto out_size = decoder->get_output_size();
+ ov::OutputVector ov_outputs(out_size);
+ const Operator* translator =
+ m_translator_map->get_operator(decoder->get_domain(), decoder->get_op_type(), decoder->get_op_set());
+ ov::frontend::onnx::Node node_context(decoder, this);
+ std::string error_message{};
+ try {
+ if (translator == nullptr) {
+ ov_outputs = std::make_shared<ov::frontend::onnx::ONNXFrameworkNode>(node_context)->outputs();
+ } else {
+ ov_outputs = (*translator)(node_context);
+ }
+ auto name = node_context.get_name();
+ for (size_t idx = 0; idx < ov_outputs.size() && idx < out_size; ++idx) {
+ const std::string& out_name = node_context.output(static_cast<int>(idx));
+ if (is_optimized_out(ov_outputs[idx])) {
+ ov_outputs[idx].add_names({out_name});
+ } else {
+ ov_outputs[idx].set_names({out_name});
+ ov_outputs[idx].get_node()->set_friendly_name(!name.empty() ? name : out_name);
+ }
+ }
+ } catch (const ::ov::frontend::onnx::error::OnnxNodeValidationFailure& e) {
+ error_message = e.what();
+ } catch (const std::exception& exc) {
+ error_message = error::detail::get_error_msg_prefix(node_context);
+ error_message += ": " + std::string{exc.what()};
+ } catch (...) {
+ error_message = error::detail::get_error_msg_prefix(node_context);
+ // Unknown exception type; notify the user generically.
+ error_message += "Unhandled exception type. \n";
+ }
+ if (!error_message.empty()) {
+ std::string onnx_domain = decoder->get_domain();
+ uint64_t opset_version = decoder->get_op_set();
+ if (m_fail_fast) {
+ if (telemetry && translator == nullptr) {
+ telemetry->send_event("error_cause", "onnx_" + decoder->get_op_type());
+ }
+ FRONT_END_THROW(error_message);
} else {
- node = std::make_shared<ov::op::v0::Parameter>(input_tensor->get_element_type(),
- input_tensor->get_partial_shape());
- m_parameters.push_back(std::dynamic_pointer_cast<ov::op::v0::Parameter>(node));
+ if (telemetry) {
+ error_message = "[ONNX Frontend] Conversion failed for " +
+ (onnx_domain != "" ? "***." + decoder->get_op_type() + "-X"
+ : decoder->get_op_type() + "-" + std::to_string(opset_version)) +
+ "\n" + error_message;
+ }
+ auto operation =
+ std::make_shared<ov::frontend::onnx::NotSupportedONNXNode>(node_context.get_ov_inputs(),
+ decoder->get_output_size(),
+ onnx_domain,
+ decoder->get_op_type(),
+ static_cast<int64_t>(opset_version),
+ error_message);
+ operation->set_friendly_name(decoder->get_op_name());
+ ov_outputs = operation->outputs();
}
- node->set_friendly_name(name);
- m_tensor_values[name] = node->get_default_output();
+ }
+ return ov_outputs;
+}
+
+std::shared_ptr<ov::Node> TranslateSession::create_const_or_param(
+ const std::string& name,
+ const std::shared_ptr<ov::frontend::onnx::TensorONNXPlace>& input_tensor) {
+ std::shared_ptr<ov::Node> node;
+ // STRING initializers carry data in get_data_any() with get_data()==nullptr; treat as Constants.
+ if (input_tensor->get_data_location() != nullptr || input_tensor->get_data() != nullptr ||
+ !input_tensor->get_data_any().empty()) {
+ node = Tensor(input_tensor).get_ov_constant();
+ } else if (input_tensor->get_partial_shape() == PartialShape{0}) { // empty constant
+ node = ov::op::v0::Constant::create(input_tensor->get_element_type(),
+ input_tensor->get_partial_shape().to_shape(),
+ {});
+ } else {
+ node = std::make_shared<ov::op::v0::Parameter>(input_tensor->get_element_type(),
+ input_tensor->get_partial_shape());
+ m_parameters.push_back(std::dynamic_pointer_cast<ov::op::v0::Parameter>(node));
+ }
+ node->set_friendly_name(name);
+ m_tensor_values[name] = node->get_default_output();
+ // Copy the ONNX tensor name into the output's name set; skip empty (unnamed) tensors.
+ if (!name.empty()) {
input_tensor->translate(m_tensor_values[name]);
- };
+ }
+ return node;
+}
+
+void TranslateSession::send_op_count_telemetry(const std::shared_ptr<TelemetryExtension>& telemetry,
+ const std::map<std::string, uint64_t>& op_statistics) const {
+ if (!telemetry) {
+ return;
+ }
+ for (const auto& op : op_statistics) {
+ telemetry->send_event("op_count", "onnx_" + op.first, static_cast<int>(op.second));
+ }
+}
+
+namespace {
+// Build a transient TensorONNXPlace from a TensorMetaInfo, registered in no Place map.
+std::shared_ptr<ov::frontend::onnx::TensorONNXPlace> make_transient_tensor_place(
+ const ov::frontend::onnx::TensorMetaInfo& info,
+ const ov::frontend::InputModel& model,
+ const bool reuse_const_data) {
+ return std::make_shared<ov::frontend::onnx::TensorONNXPlace>(
+ model,
+ info.m_partial_shape,
+ info.m_element_type,
+ std::vector<std::string>{info.m_tensor_name ? *info.m_tensor_name : std::string{}},
+ info.m_tensor_data,
+ info.m_tensor_data_size,
+ info.m_tensor_data_any,
+ info.m_external_location,
+ info.m_is_raw,
+ reuse_const_data);
+}
+
+// A tensor is a Constant iff it carries inline data, external data, or STRING data.
+bool tensor_has_data(const ov::frontend::onnx::TensorMetaInfo& info) {
+ return info.m_tensor_data != nullptr || info.m_external_location != nullptr || !info.m_tensor_data_any.empty();
+}
+
+// Same predicate as tensor_has_data(), expressed over a materialized TensorONNXPlace.
+bool place_has_data(const ov::frontend::onnx::TensorONNXPlace& place) {
+ return place.get_data() != nullptr || place.get_data_location() != nullptr || !place.get_data_any().empty();
+}
+
+struct DiscoveredOutput {
+ int64_t model_output_index;
+ std::string tensor_name;
+ std::shared_ptr<ov::frontend::onnx::DecoderBaseTensor> tensor_decoder;
+};
- for (const auto& input : model_onnx->get_inputs()) {
- const auto input_tensor = std::dynamic_pointer_cast<ov::frontend::onnx::TensorONNXPlace>(input);
- FRONT_END_GENERAL_CHECK(input_tensor != nullptr,
- "Inputs of ov::frontend::onnx::InputModel must be TensorONNXPlace instances");
- const auto name = input_tensor->get_names()[0];
- create_const_or_param(name, input_tensor);
+// Stable sort by the model index projected from each element by key_of.
+template <typename T, typename KeyFn>
+void sort_by_model_index(std::vector<T>& items, KeyFn key_of) {
+ std::stable_sort(items.begin(), items.end(), [&](const T& a, const T& b) {
+ return key_of(a) < key_of(b);
+ });
+}
+} // namespace
+
+void TranslateSession::add_result(const std::string& name,
+ const ov::Output<ov::Node>& output_value,
+ ResultVector& results) {
+ const auto result = std::make_shared<ov::op::v0::Result>(output_value);
+ auto result_input = result->output(0);
+ if (!name.empty()) {
+ result_input.add_names({name});
+ }
+ result->set_friendly_name(name + "/sink_port_0");
+ results.push_back(result);
+ const auto& previous_operation = result->get_input_node_shared_ptr(0);
+ if (!ov::as_type_ptr<ov::op::v0::Parameter>(previous_operation)) {
+ previous_operation->set_friendly_name(name);
+ }
+}
+
+void TranslateSession::translate_op_and_store_outputs(const std::shared_ptr<DecoderBaseOperation>& op_decoder,
+ const std::shared_ptr<TelemetryExtension>& telemetry) {
+ const auto out_size = op_decoder->get_output_size();
+ ov::OutputVector ov_outputs = apply_op_translator(op_decoder, telemetry);
+ for (size_t i = 0; i < ov_outputs.size() && i < out_size; ++i) {
+ const auto& name = op_decoder->get_output_tensor_name(i);
+ if (name.empty()) { // not connected
+ continue;
+ }
+ ov_outputs[i].add_names({name});
+ m_tensor_values[name] = ov_outputs[i];
}
+}
+
+void TranslateSession::translate_graph(const ov::frontend::InputModel::Ptr& input_model,
+ std::shared_ptr<ov::Model>& ov_model) {
+ const auto model_onnx = std::dynamic_pointer_cast<unify::InputModel>(input_model);
+ FRONT_END_GENERAL_CHECK(model_onnx != nullptr, "Invalid input model");
+
+ const auto telemetry = model_onnx->get_telemetry_extension();
+ ResultVector results;
+
+ std::vector<std::pair<std::string, std::shared_ptr<ov::frontend::onnx::TensorONNXPlace>>> graph_outputs;
- // operations
- for (const auto& op_place : model_onnx->get_op_places()) {
- const auto decoder = std::dynamic_pointer_cast<onnx::DecoderBaseOperation>(op_place->get_decoder());
- FRONT_END_GENERAL_CHECK(decoder != nullptr, "Decoder must be onnx::DecoderBase or its child");
- for (size_t i = 0; i < decoder->get_input_size(); ++i) {
- const auto& name = decoder->get_input_tensor_name(i);
- if (name == "") {
+ auto materialize_inputs_and_translate = [&](const std::shared_ptr<onnx::DecoderBaseOperation>& op_decoder,
+ auto&& resolve_input_place) {
+ FRONT_END_GENERAL_CHECK(op_decoder != nullptr, "Decoder must be onnx::DecoderBaseOperation or its child");
+ for (size_t i = 0; i < op_decoder->get_input_size(); ++i) {
+ const auto& name = op_decoder->get_input_tensor_name(i);
+ // lookup_tensor() also checks m_tensor_values; materialize only on a full miss.
+ if (name.empty() || lookup_tensor(name).get_node() != nullptr) {
continue;
}
- auto node = lookup_tensor(name);
- if (node.get_node() == nullptr) {
- auto place_it = all_tensor_places.find(name);
- FRONT_END_GENERAL_CHECK(place_it != all_tensor_places.end(), "Tensor place not found in a graph");
- create_const_or_param(name, place_it->second);
- }
+ create_const_or_param(name, resolve_input_place(name, i));
}
+ translate_op_and_store_outputs(op_decoder, telemetry);
+ };
- const auto out_size = decoder->get_output_size();
- ov::OutputVector ov_outputs(out_size);
- const Operator* translator =
- m_translator_map->get_operator(decoder->get_domain(), decoder->get_op_type(), decoder->get_op_set());
- ov::frontend::onnx::Node node_context(decoder, this);
- std::string error_message{};
- try {
- if (translator == nullptr) {
- ov_outputs = std::make_shared<ov::frontend::onnx::ONNXFrameworkNode>(node_context)->outputs();
- } else {
- ov_outputs = (*translator)(node_context);
- }
- auto name = node_context.get_name();
- for (size_t idx = 0; idx < ov_outputs.size() && idx < out_size; ++idx) {
- const std::string& out_name = node_context.output(static_cast<int>(idx));
- if (is_optimized_out(ov_outputs[idx])) {
- ov_outputs[idx].add_names({out_name});
- } else {
- ov_outputs[idx].set_names({out_name});
- ov_outputs[idx].get_node()->set_friendly_name(!name.empty() ? name : out_name);
+ // Record a declared output as (name, data_place); keep the place only if it carries initializer data.
+ auto collect_graph_output = [&](const std::string& name,
+ const std::shared_ptr<ov::frontend::onnx::TensorONNXPlace>& data_place) {
+ graph_outputs.emplace_back(name, data_place && place_has_data(*data_place) ? data_place : nullptr);
+ };
+
+ if (!model_onnx->is_loaded()) {
+ // Not loaded to a Place-graph: walk the GraphIterator decoders directly (skips load_model()).
+ const auto graph_iterator =
+ std::dynamic_pointer_cast<ov::frontend::onnx::GraphIterator>(model_onnx->get_graph_iterator());
+ FRONT_END_GENERAL_CHECK(graph_iterator != nullptr, "Invalid graph iterator for single-pass conversion");
+
+ // Preserve zero-copy constant wrapping when the iterator's owner allows it.
+ const bool reuse_const_data = model_onnx->is_const_data_reusable();
+ static const std::string empty_tensor_name;
+
+ auto make_transient_place = [&](const ov::frontend::onnx::TensorMetaInfo& info) {
+ return make_transient_tensor_place(info, *model_onnx, reuse_const_data);
+ };
+
+ std::vector<DiscoveredOutput> discovered_outputs;
+ // Model input index per graph-input Parameter, for reordering m_parameters after the walk.
+ std::unordered_map<const ov::Node*, int64_t> input_indices;
+ std::map<std::string, uint64_t> op_statistics; // op_count telemetry, keyed to match load_model()
+
+ for (; !graph_iterator->is_end(); graph_iterator->next()) {
+ const auto& decoder = graph_iterator->get_decoder();
+
+ if (const auto tensor_decoder = std::dynamic_pointer_cast<onnx::DecoderBaseTensor>(decoder)) {
+ const auto& info = tensor_decoder->get_tensor_info();
+ const auto input_idx = tensor_decoder->get_input_idx();
+ const auto output_idx = tensor_decoder->get_output_idx();
+ const bool has_data = tensor_has_data(info);
+
+ // Pure constant/initializer (not a graph output): materialized on demand by ops.
+ if (has_data && output_idx < 0) {
+ continue;
}
- }
- } catch (const ::ov::frontend::onnx::error::OnnxNodeValidationFailure& e) {
- error_message = e.what();
- } catch (const std::exception& exc) {
- error_message = error::detail::get_error_msg_prefix(node_context);
- error_message += ": " + std::string{exc.what()};
- } catch (...) {
- error_message = error::detail::get_error_msg_prefix(node_context);
- // Since we do not know anything about current exception data type we can only
- // notify user in this way.
- error_message += "Unhandled exception type. \n";
- }
- if (!error_message.empty()) {
- auto telemetry = model_onnx->get_telemetry_extension();
- std::string onnx_domain = decoder->get_domain();
- uint64_t opset_version = decoder->get_op_set();
- if (m_fail_fast) {
- if (telemetry && translator == nullptr) {
- telemetry->send_event("error_cause", "onnx_" + decoder->get_op_type());
+ const std::string& name = info.m_tensor_name ? *info.m_tensor_name : empty_tensor_name;
+ if (input_idx >= 0 && !has_data) {
+ const auto node = create_const_or_param(name, make_transient_place(info));
+ // A no-data graph input is a Parameter unless it is the empty-constant special case.
+ if (ov::as_type_ptr<ov::op::v0::Parameter>(node)) {
+ input_indices[node.get()] = input_idx;
+ }
}
- FRONT_END_THROW(error_message);
- } else {
- if (telemetry && !error_message.empty()) {
- error_message = "[ONNX Frontend] Conversion failed for " +
- (onnx_domain != "" ? "***." + decoder->get_op_type() + "-X"
- : decoder->get_op_type() + "-" + std::to_string(opset_version)) +
- "\n" + error_message;
+ if (output_idx >= 0) {
+ discovered_outputs.push_back({output_idx, name, tensor_decoder});
}
- auto operation =
- std::make_shared<ov::frontend::onnx::NotSupportedONNXNode>(node_context.get_ov_inputs(),
- decoder->get_output_size(),
- onnx_domain,
- decoder->get_op_type(),
- static_cast<int64_t>(opset_version),
- error_message);
- operation->set_friendly_name(decoder->get_op_name());
- ov_outputs = operation->outputs();
- }
- }
- for (size_t i = 0; i < ov_outputs.size() && i < decoder->get_output_size(); ++i) {
- const auto& name = decoder->get_output_tensor_name(i);
- if (name == "") {
- // Means - not connected
continue;
}
- m_tensor_values[name] = ov_outputs[i];
- all_tensor_places[name]->translate(m_tensor_values[name]);
+
+ const auto op_decoder = std::dynamic_pointer_cast<onnx::DecoderBaseOperation>(decoder);
+ materialize_inputs_and_translate(op_decoder, [&](const std::string&, size_t i) {
+ return make_transient_place(op_decoder->get_input_tensor_info(i));
+ });
+ if (telemetry) {
+ // Key by the iterator's resolved opset so op_count events match load_model()'s.
+ op_statistics[op_decoder->get_op_type() + "-" +
+ std::to_string(graph_iterator->get_opset_version(op_decoder->get_domain()))]++;
+ }
+ }
+
+ send_op_count_telemetry(telemetry, op_statistics);
+
+ sort_by_model_index(m_parameters, [&](const std::shared_ptr<ov::op::v0::Parameter>& p) {
+ const auto it = input_indices.find(p.get());
+ return it != input_indices.end() ? it->second : std::numeric_limits<int64_t>::max();
+ });
+
+ sort_by_model_index(discovered_outputs, [](const DiscoveredOutput& o) {
+ return o.model_output_index;
+ });
+ graph_outputs.reserve(discovered_outputs.size());
+ for (const auto& discovered : discovered_outputs) {
+ // Re-fetch from the still-alive decoder; the loop may have advanced (and freed) other decoders.
+ const auto& info = discovered.tensor_decoder->get_tensor_info();
+ collect_graph_output(discovered.tensor_name, tensor_has_data(info) ? make_transient_place(info) : nullptr);
+ }
+ } else {
+ auto& all_tensor_places = model_onnx->get_tensor_places();
+
+ // inputs
+ m_parameters.reserve(model_onnx->get_inputs().size());
+ for (const auto& input : model_onnx->get_inputs()) {
+ const auto input_tensor = std::dynamic_pointer_cast<ov::frontend::onnx::TensorONNXPlace>(input);
+ FRONT_END_GENERAL_CHECK(input_tensor != nullptr,
+ "Inputs of ov::frontend::onnx::InputModel must be TensorONNXPlace instances");
+ create_const_or_param(input_tensor->get_names()[0], input_tensor);
+ }
+
+ // operations
+ for (const auto& op_place : model_onnx->get_op_places()) {
+ const auto op_decoder = std::dynamic_pointer_cast<onnx::DecoderBaseOperation>(op_place->get_decoder());
+ materialize_inputs_and_translate(op_decoder, [&](const std::string& name, size_t) {
+ const auto place_it = all_tensor_places.find(name);
+ FRONT_END_GENERAL_CHECK(place_it != all_tensor_places.end(), "Tensor place not found in a graph");
+ return place_it->second;
+ });
+ }
+
+ graph_outputs.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,
+ "Outputs of ov::frontend::onnx::InputModel must be TensorONNXPlace instances");
+ const auto name = tensor->get_names()[0];
+ const auto place_it = all_tensor_places.find(name);
+ collect_graph_output(name, place_it != all_tensor_places.end() ? place_it->second : nullptr);
}
}
- // 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,
- "Outputs of ov::frontend::onnx::InputModel must be TensorONNXPlace instances");
- const auto name = tensor->get_names()[0];
+ results.reserve(graph_outputs.size());
+ for (const auto& graph_output : graph_outputs) {
+ const auto& name = graph_output.first;
+ const auto& data_place = graph_output.second;
if (!m_tensor_values.count(name)) {
- 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);
+ if (data_place) {
+ create_const_or_param(name, data_place);
} else {
- FRONT_END_GENERAL_CHECK(false,
+ const auto parent_value = lookup_tensor(name);
+ FRONT_END_GENERAL_CHECK(parent_value.get_node() != nullptr,
"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.");
+ m_tensor_values.emplace(name, parent_value);
}
}
- const auto& output_value = m_tensor_values[name];
- const auto result = std::make_shared<ov::op::v0::Result>(output_value);
- auto input = result->output(0);
- tensor->translate(input);
- result->set_friendly_name(name + "/sink_port_0");
- results.push_back(result);
- const auto& previous_operation = result->get_input_node_shared_ptr(0);
- if (!ov::as_type_ptr<ov::op::v0::Parameter>(previous_operation)) {
- previous_operation->set_friendly_name(name);
- }
+ add_result(name, m_tensor_values[name], results);
}
- auto model_name = "onnx_Frontend_IR";
- ov_model = std::make_shared<ov::Model>(results, m_parameters, model_name);
+ ov_model = std::make_shared<ov::Model>(results, m_parameters, "onnx_Frontend_IR");
- const auto& metadata = model_onnx->get_metadata();
+ const auto metadata = model_onnx->get_metadata();
const std::string framework_section = "framework";
for (const auto& pair : metadata) {
ov_model->set_rt_info(pair.second, framework_section, pair.first);
diff --git a/src/frontends/onnx/frontend/src/translate_session.hpp b/src/frontends/onnx/frontend/src/translate_session.hpp
index 264a0090d52..66ffbde0076 100644
--- a/src/frontends/onnx/frontend/src/translate_session.hpp
+++ b/src/frontends/onnx/frontend/src/translate_session.hpp
@@ -4,14 +4,22 @@
#pragma once
+#include <map>
+#include <unordered_map>
+
#include "openvino/frontend/input_model.hpp"
#include "openvino/op/parameter.hpp"
namespace ov {
namespace frontend {
+
+class TelemetryExtension;
+
namespace onnx {
class OperatorsBridge;
+class DecoderBaseOperation;
+class TensorONNXPlace;
/// For one call of convert and decode method of Frontend, it creates one TranslateSession object to save data for the
/// translation session: telemetry statistics, cache of converted body graph models, operation translators (including
@@ -27,13 +35,14 @@ public:
std::shared_ptr<ov::Model> get_converted_model();
+ /// \brief Converts the input model to an ov::Model.
void translate_graph(const ov::frontend::InputModel::Ptr& input_model, std::shared_ptr<ov::Model>& ov_model);
ov::frontend::InputModel::Ptr get_input_model(void) const {
return m_input_model;
}
- std::map<std::string, Output<ov::Node>>& get_tensor_values() {
+ std::unordered_map<std::string, Output<ov::Node>>& get_tensor_values() {
return m_tensor_values;
}
@@ -52,11 +61,35 @@ public:
ov::Output<ov::Node> lookup_tensor(const std::string& name);
private:
+ /// \brief Build a Result for a graph output (name carried onto the port, sink/friendly names set)
+ /// and append it to results. Shared by both conversion paths.
+ void add_result(const std::string& name, const ov::Output<ov::Node>& output_value, ResultVector& results);
+
+ /// \brief Apply the registered operator translator (or the not-supported fallback) to one op
+ /// decoder and return its OpenVINO outputs. Shared by both conversion paths.
+ ov::OutputVector apply_op_translator(const std::shared_ptr<DecoderBaseOperation>& decoder,
+ const std::shared_ptr<TelemetryExtension>& telemetry);
+
+ /// \brief Translate an operation decoder and store its named outputs in m_tensor_values. Shared by
+ /// both conversion paths (the op body is identical once inputs are materialized).
+ void translate_op_and_store_outputs(const std::shared_ptr<DecoderBaseOperation>& op_decoder,
+ const std::shared_ptr<TelemetryExtension>& telemetry);
+
+ /// \brief Materialize a graph tensor as a Constant (data) or Parameter (no data), register it in
+ /// m_tensor_values, append a created Parameter to m_parameters, and return the node.
+ std::shared_ptr<ov::Node> create_const_or_param(const std::string& name,
+ const std::shared_ptr<TensorONNXPlace>& input_tensor);
+
+ /// \brief Emit per-op "op_count" telemetry accumulated during the single-pass walk (the two-pass
+ /// path emits it from load_model()). No-op when telemetry is null.
+ void send_op_count_telemetry(const std::shared_ptr<TelemetryExtension>& telemetry,
+ const std::map<std::string, uint64_t>& op_statistics) const;
+
const ov::frontend::InputModel::Ptr m_input_model;
const std::shared_ptr<OperatorsBridge> m_translator_map;
const std::string m_model_name;
std::shared_ptr<ov::Model> m_ov_model;
- std::map<std::string, Output<ov::Node>> m_tensor_values;
+ std::unordered_map<std::string, Output<ov::Node>> m_tensor_values;
bool m_fail_fast;
TranslateSession* m_parent_session;
ParameterVector m_parameters;
diff --git a/src/frontends/onnx/tests/graph_iterator.cpp b/src/frontends/onnx/tests/graph_iterator.cpp
index 77fb38df93b..21d7e39099a 100644
--- a/src/frontends/onnx/tests/graph_iterator.cpp
+++ b/src/frontends/onnx/tests/graph_iterator.cpp
@@ -6,6 +6,8 @@
#include <onnx/onnx_pb.h>
#include <algorithm>
+#include <cctype>
+#include <cstring>
#include <filesystem>
#include <map>
#include <openvino/frontend/exception.hpp>
@@ -18,9 +20,11 @@
#include "../frontend/src/core/decoder_proto.hpp"
#include "../frontend/src/core/graph_iterator_proto.hpp"
#include "common_test_utils/common_utils.hpp"
+#include "common_test_utils/graph_comparator.hpp"
#include "common_test_utils/test_case.hpp"
#include "load_from.hpp"
#include "onnx_utils.hpp"
+#include "openvino/op/constant.hpp"
#include "utils.hpp"
class SimpleIterator : public ov::frontend::onnx::GraphIterator {
@@ -588,3 +592,155 @@ TEST(FrontEndGraphIteratorTest, loads_programmatic_empty_shape_initializer_graph
}
}
}
+
+// =====================================================================================================
+// Accuracy / structural equivalence of the deferred-InputModel single-pass converter (translate
+// straight from the GraphIterator decoders, skipping load_model()) against the InputModel-backed
+// two-pass (Place-graph) converter, for the same .onnx model.
+//
+// REFERENCE: load an InputModel, force its Place graph to build (get_inputs() triggers load_model()),
+// then convert it via the two-pass translate_graph path.
+// NEW: load the same file (the iterator-backed InputModel is created deferred, i.e. not loaded)
+// and convert it WITHOUT touching any Place accessor, so convert() takes the single-pass
+// translate_graph_from_iterator branch.
+//
+// The two ov::Models must be structurally identical (ops, precisions, attributes, tensor names) and
+// carry bitwise-identical Constant data.
+// =====================================================================================================
+namespace {
+// Build the reference model through the InputModel-backed two-pass converter. Touching get_inputs()
+// forces load_model() so unify::InputModel::is_loaded() is true and convert() takes the Place-graph
+// path rather than the single-pass branch.
+std::shared_ptr<ov::Model> convert_reference_two_pass(const std::filesystem::path& path,
+ ov::frontend::FrontEnd::Ptr& fe) {
+ auto input_model = fe->load(path);
+ EXPECT_NE(input_model, nullptr);
+ (void)input_model->get_inputs(); // force Place-graph build -> two-pass converter
+ return fe->convert(input_model);
+}
+
+// Build the model under test through the deferred-InputModel single-pass converter: load() returns a
+// not-yet-loaded iterator-backed InputModel, and convert() (with no prior Place accessor) translates
+// straight from the iterator's decoders. enable_mmap is forwarded as the load mmap hint.
+std::shared_ptr<ov::Model> convert_new_from_iterator(const std::filesystem::path& path,
+ ov::frontend::FrontEnd::Ptr& fe,
+ bool enable_mmap) {
+ auto input_model = fe->load(path, enable_mmap);
+ EXPECT_NE(input_model, nullptr);
+ return fe->convert(input_model);
+}
+
+// Collect all Constant nodes of a model.
+std::vector<std::shared_ptr<ov::op::v0::Constant>> collect_constants(const std::shared_ptr<ov::Model>& model) {
+ std::vector<std::shared_ptr<ov::op::v0::Constant>> out;
+ for (const auto& op : model->get_ordered_ops()) {
+ if (auto c = ov::as_type_ptr<ov::op::v0::Constant>(op)) {
+ out.push_back(c);
+ }
+ }
+ return out;
+}
+
+// Two Constants are equivalent when their element type, shape and raw bytes are identical.
+bool constants_bitwise_equal(const std::shared_ptr<ov::op::v0::Constant>& a,
+ const std::shared_ptr<ov::op::v0::Constant>& b) {
+ if (a->get_element_type() != b->get_element_type() || a->get_shape() != b->get_shape() ||
+ a->get_byte_size() != b->get_byte_size()) {
+ return false;
+ }
+ return a->get_byte_size() == 0 || std::memcmp(a->get_data_ptr(), b->get_data_ptr(), a->get_byte_size()) == 0;
+}
+
+// Verify the two models carry the same multiset of Constant data, matched by value rather than by name.
+//
+// Friendly names cannot be used as the key here: translators synthesize anonymous internal Constants
+// (e.g. Gemm's alpha/beta, Split's axis, Gather's axis), which OV names "Constant_<instance_id>" from a
+// global counter that keeps advancing. The two reference/test conversions run sequentially, so the same
+// logical Constant gets a different id in each model. Matching by element type + shape + raw bytes is the
+// stable, name-independent expression of "bitwise-identical constant data".
+void check_constants_bitwise_identical(const std::shared_ptr<ov::Model>& ref, const std::shared_ptr<ov::Model>& test) {
+ auto ref_consts = collect_constants(ref);
+ auto test_consts = collect_constants(test);
+ ASSERT_EQ(ref_consts.size(), test_consts.size()) << "Different number of Constant nodes";
+
+ std::vector<bool> matched(test_consts.size(), false);
+ for (const auto& ref_c : ref_consts) {
+ bool found = false;
+ for (size_t i = 0; i < test_consts.size(); ++i) {
+ if (!matched[i] && constants_bitwise_equal(ref_c, test_consts[i])) {
+ matched[i] = true;
+ found = true;
+ break;
+ }
+ }
+ EXPECT_TRUE(found) << "No bitwise-identical counterpart in the iterator-converted model for Constant '"
+ << ref_c->get_friendly_name() << "' (" << ref_c->get_element_type() << " "
+ << ref_c->get_shape() << ")";
+ }
+}
+
+// Compare structure (ops/precisions/attributes/tensor names) and bitwise constant data.
+void expect_equivalent(const std::shared_ptr<ov::Model>& ref, const std::shared_ptr<ov::Model>& test) {
+ ASSERT_NE(ref, nullptr);
+ ASSERT_NE(test, nullptr);
+ auto fc = FunctionsComparator::no_default()
+ .enable(FunctionsComparator::NODES)
+ .enable(FunctionsComparator::PRECISIONS)
+ .enable(FunctionsComparator::CONST_VALUES)
+ .enable(FunctionsComparator::ATTRIBUTES)
+ .enable(FunctionsComparator::TENSOR_NAMES);
+ const auto res = fc.compare(test, ref);
+ EXPECT_TRUE(res.valid) << res.message;
+ check_constants_bitwise_identical(ref, test);
+}
+} // namespace
+
+class FrontEndConvertIteratorEquivalence : public ::testing::TestWithParam<std::string> {
+protected:
+ ov::frontend::FrontEnd::Ptr m_fe;
+ void SetUp() override {
+ m_fe = ov::frontend::FrontEndManager().load_by_framework("onnx");
+ ASSERT_NE(m_fe, nullptr);
+ }
+};
+
+TEST_P(FrontEndConvertIteratorEquivalence, matches_two_pass_place_graph) {
+ if (!ov::frontend::onnx::tests::is_graph_iterator_enabled()) {
+ GTEST_SKIP() << "This test requires GraphIterator (ONNX_ITERATOR=1)";
+ }
+ const auto path =
+ ov::util::path_join({ov::test::utils::getExecutableDirectory(), TEST_ONNX_MODELS_DIRNAME, GetParam()});
+
+ auto ref = convert_reference_two_pass(path, m_fe);
+ auto test = convert_new_from_iterator(path, m_fe, /*enable_mmap=*/true);
+ expect_equivalent(ref, test);
+}
+
+// A curated set covering: plain ops, initializers, broadcast, multi-output, control-flow-free
+// transformer/CV-style graphs, raw + typed initializers, and external data.
+INSTANTIATE_TEST_SUITE_P(OnnxConvertEquivalence,
+ FrontEndConvertIteratorEquivalence,
+ ::testing::Values("add_abc.onnx",
+ "add_abc_initializers.onnx",
+ "addmul_abc.onnx",
+ "matmul.onnx",
+ "gemm_abc.onnx",
+ "conv2d_dilation_assym_pads_strides.onnx",
+ "batchnorm_default.onnx",
+ "relu.onnx",
+ "softmax_axis_1.onnx",
+ "split_equal_parts_default.onnx",
+ "reshape_negative_dim.onnx",
+ "conv_transpose_1x3x8x8.onnx",
+ "gather_float_1D.onnx",
+ "uint16_raw_initializer.onnx",
+ "bfloat16_raw_initializer.onnx",
+ "external_data/external_data.onnx"),
+ [](const ::testing::TestParamInfo<std::string>& info) {
+ std::string n = info.param;
+ for (auto& ch : n) {
+ if (!std::isalnum(static_cast<unsigned char>(ch)))
+ ch = '_';
+ }
+ return n;
+ });