Skip to content

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

[ONNX] Support sequence concatenation in Loop (#33903)

Maxim Vafinefe19a11a095
diff --git a/src/frontends/common/include/openvino/frontend/concat_from_sequence.hpp b/src/frontends/common/include/openvino/frontend/concat_from_sequence.hpp
new file mode 100644
index 00000000000..e12f578cdb3
--- /dev/null
+++ b/src/frontends/common/include/openvino/frontend/concat_from_sequence.hpp
@@ -0,0 +1,71 @@
+// Copyright (C) 2018-2026 Intel Corporation
+// SPDX-License-Identifier: Apache-2.0
+//
+
+#pragma once
+
+#include "openvino/frontend/visibility.hpp"
+#include "openvino/op/util/framework_node.hpp"
+
+namespace ov {
+namespace frontend {
+
+/// \brief ConcatFromSequence is a helper operation that represents concatenating
+/// all tensors in a sequence along a specified axis.
+/// This operation is used during frontend conversion to mark concat-from-sequence operations
+/// that will be later transformed by SequenceConcatReplacer.
+///
+/// Inputs:
+/// - input_sequence: The input sequence (SequenceMark, SequenceInsert, or Loop output)
+///
+/// Attributes:
+/// - axis: The axis along which to concatenate (default: 0)
+/// - new_axis: If true, creates a new axis for concatenation (like stack), otherwise
+/// concatenates along existing axis (default: false)
+///
+/// Output:
+/// - The concatenated tensor
+class FRONTEND_API ConcatFromSequence : public ov::op::util::FrameworkNode {
+public:
+ OPENVINO_OP("ConcatFromSequence", "util", ov::op::util::FrameworkNode);
+
+ /// \brief Constructs ConcatFromSequence
+ /// \param input_sequence The input sequence
+ /// \param axis The axis along which to concatenate
+ /// \param new_axis If true, creates a new axis for concatenation
+ ConcatFromSequence(const Output<Node>& input_sequence, int64_t axis, bool new_axis = false);
+
+ std::shared_ptr<Node> clone_with_new_inputs(const OutputVector& inputs) const override;
+
+ /// \brief Get the input sequence
+ Output<Node> get_input_sequence() const {
+ return input_value(0);
+ }
+
+ /// \brief Get the concatenation axis
+ int64_t get_axis() const {
+ return m_axis;
+ }
+
+ /// \brief Set the concatenation axis
+ void set_axis(int64_t axis) {
+ m_axis = axis;
+ }
+
+ /// \brief Check if new_axis mode is enabled
+ bool get_new_axis() const {
+ return m_new_axis;
+ }
+
+ /// \brief Set new_axis mode
+ void set_new_axis(bool new_axis) {
+ m_new_axis = new_axis;
+ }
+
+private:
+ int64_t m_axis = 0;
+ bool m_new_axis = false;
+};
+
+} // namespace frontend
+} // namespace ov
diff --git a/src/frontends/common/include/openvino/frontend/sequence_insert.hpp b/src/frontends/common/include/openvino/frontend/sequence_insert.hpp
new file mode 100644
index 00000000000..6c8757c14e4
--- /dev/null
+++ b/src/frontends/common/include/openvino/frontend/sequence_insert.hpp
@@ -0,0 +1,63 @@
+// Copyright (C) 2018-2026 Intel Corporation
+// SPDX-License-Identifier: Apache-2.0
+//
+
+#pragma once
+
+#include "openvino/frontend/visibility.hpp"
+#include "openvino/op/util/framework_node.hpp"
+
+namespace ov {
+namespace frontend {
+
+/// \brief SequenceInsert is a helper operation that represents inserting a tensor into a sequence.
+/// This operation is used during frontend conversion to mark sequence insert operations
+/// that will be later transformed by SequenceConcatReplacer.
+///
+/// Inputs:
+/// - input_sequence: The input sequence (can be SequenceMark or another SequenceInsert)
+/// - tensor: The tensor to insert into the sequence
+/// - position (optional): The position at which to insert the tensor
+///
+/// Output:
+/// - The updated sequence with the tensor inserted
+class FRONTEND_API SequenceInsert : public ov::op::util::FrameworkNode {
+public:
+ OPENVINO_OP("SequenceInsert", "util", ov::op::util::FrameworkNode);
+
+ /// \brief Constructs SequenceInsert with sequence and tensor inputs
+ /// \param input_sequence The input sequence
+ /// \param tensor The tensor to insert
+ SequenceInsert(const Output<Node>& input_sequence, const Output<Node>& tensor);
+
+ /// \brief Constructs SequenceInsert with sequence, tensor, and position inputs
+ /// \param input_sequence The input sequence
+ /// \param tensor The tensor to insert
+ /// \param position The position at which to insert
+ SequenceInsert(const Output<Node>& input_sequence, const Output<Node>& tensor, const Output<Node>& position);
+
+ std::shared_ptr<Node> clone_with_new_inputs(const OutputVector& inputs) const override;
+
+ /// \brief Get the input sequence
+ Output<Node> get_input_sequence() const {
+ return input_value(0);
+ }
+
+ /// \brief Get the tensor being inserted
+ Output<Node> get_tensor() const {
+ return input_value(1);
+ }
+
+ /// \brief Check if position input is provided
+ bool has_position() const {
+ return get_input_size() > 2;
+ }
+
+ /// \brief Get the position input (if provided)
+ Output<Node> get_position() const {
+ return has_position() ? input_value(2) : Output<Node>{};
+ }
+};
+
+} // namespace frontend
+} // namespace ov
diff --git a/src/frontends/common/include/openvino/frontend/sequence_mark.hpp b/src/frontends/common/include/openvino/frontend/sequence_mark.hpp
index f012c22297e..6132176c98f 100644
--- a/src/frontends/common/include/openvino/frontend/sequence_mark.hpp
+++ b/src/frontends/common/include/openvino/frontend/sequence_mark.hpp
@@ -25,6 +25,9 @@ public:
size_t size() const;
bool empty() const;
ov::Output<ov::Node> get_element(size_t index) const;
+
+ /// \brief Returns all sequence elements by walking backward through any
+ /// SequenceInsert chain wrapping this SequenceMark.
ov::OutputVector get_sequence() const;
};
diff --git a/src/frontends/common/src/concat_from_sequence.cpp b/src/frontends/common/src/concat_from_sequence.cpp
new file mode 100644
index 00000000000..3eddc8f80df
--- /dev/null
+++ b/src/frontends/common/src/concat_from_sequence.cpp
@@ -0,0 +1,21 @@
+// Copyright (C) 2018-2026 Intel Corporation
+// SPDX-License-Identifier: Apache-2.0
+//
+
+#include "openvino/frontend/concat_from_sequence.hpp"
+
+namespace ov {
+namespace frontend {
+
+ConcatFromSequence::ConcatFromSequence(const Output<Node>& input_sequence, int64_t axis, bool new_axis)
+ : FrameworkNode({input_sequence}, 1),
+ m_axis(axis),
+ m_new_axis(new_axis) {}
+
+std::shared_ptr<Node> ConcatFromSequence::clone_with_new_inputs(const OutputVector& inputs) const {
+ OPENVINO_ASSERT(inputs.size() == 1, "ConcatFromSequence requires exactly 1 input");
+ return std::make_shared<ConcatFromSequence>(inputs[0], m_axis, m_new_axis);
+}
+
+} // namespace frontend
+} // namespace ov
diff --git a/src/frontends/common/src/sequence_insert.cpp b/src/frontends/common/src/sequence_insert.cpp
new file mode 100644
index 00000000000..842c993964d
--- /dev/null
+++ b/src/frontends/common/src/sequence_insert.cpp
@@ -0,0 +1,28 @@
+// Copyright (C) 2018-2026 Intel Corporation
+// SPDX-License-Identifier: Apache-2.0
+//
+
+#include "openvino/frontend/sequence_insert.hpp"
+
+namespace ov {
+namespace frontend {
+
+SequenceInsert::SequenceInsert(const Output<Node>& input_sequence, const Output<Node>& tensor)
+ : FrameworkNode({input_sequence, tensor}, 1) {}
+
+SequenceInsert::SequenceInsert(const Output<Node>& input_sequence,
+ const Output<Node>& tensor,
+ const Output<Node>& position)
+ : FrameworkNode({input_sequence, tensor, position}, 1) {}
+
+std::shared_ptr<Node> SequenceInsert::clone_with_new_inputs(const OutputVector& inputs) const {
+ if (inputs.size() == 2) {
+ return std::make_shared<SequenceInsert>(inputs[0], inputs[1]);
+ } else if (inputs.size() == 3) {
+ return std::make_shared<SequenceInsert>(inputs[0], inputs[1], inputs[2]);
+ }
+ OPENVINO_THROW("SequenceInsert requires 2 or 3 inputs");
+}
+
+} // namespace frontend
+} // namespace ov
diff --git a/src/frontends/common/src/sequence_mark.cpp b/src/frontends/common/src/sequence_mark.cpp
index ce88b15a1b6..dd7c3cfffc9 100644
--- a/src/frontends/common/src/sequence_mark.cpp
+++ b/src/frontends/common/src/sequence_mark.cpp
@@ -4,6 +4,8 @@
#include "openvino/frontend/sequence_mark.hpp"
+#include "openvino/frontend/sequence_insert.hpp"
+
namespace ov {
namespace frontend {
@@ -61,7 +63,29 @@ ov::Output<ov::Node> SequenceMark::get_element(size_t index) const {
}
ov::OutputVector SequenceMark::get_sequence() const {
- return input_values();
+ // Walk backward through SequenceInsert chain.
+ // Pattern: SM(a,b) -> SI(SM,c) -> SM -> SI(SM,d) -> SM (this)
+ // Each aten::append wraps SequenceInsert output in a new SequenceMark.
+ OutputVector appended;
+ std::shared_ptr<const ov::Node> current = shared_from_this();
+
+ while (auto mark = ov::as_type_ptr<const SequenceMark>(current)) {
+ if (mark->get_input_size() != 1)
+ break;
+ auto si = ov::as_type_ptr<const SequenceInsert>(mark->input_value(0).get_node_shared_ptr());
+ if (!si)
+ break;
+ appended.push_back(si->get_tensor());
+ current = si->get_input_sequence().get_node_shared_ptr();
+ }
+
+ // current is the base SequenceMark with direct element inputs
+ OutputVector result;
+ if (auto mark = ov::as_type_ptr<const SequenceMark>(current)) {
+ result = mark->input_values();
+ }
+ result.insert(result.end(), appended.rbegin(), appended.rend());
+ return result;
}
} // namespace frontend
diff --git a/src/frontends/common_translators/include/sequence_concat_replacer.hpp b/src/frontends/common_translators/include/sequence_concat_replacer.hpp
new file mode 100644
index 00000000000..c06d76b4122
--- /dev/null
+++ b/src/frontends/common_translators/include/sequence_concat_replacer.hpp
@@ -0,0 +1,28 @@
+// Copyright (C) 2018-2026 Intel Corporation
+// SPDX-License-Identifier: Apache-2.0
+//
+
+#pragma once
+
+#include "openvino/pass/matcher_pass.hpp"
+
+namespace ov {
+namespace frontend {
+namespace pass {
+
+/// \brief Replaces ConcatFromSequence operations with standard OpenVINO ops.
+///
+/// This transformation handles two patterns:
+/// 1. SequenceMark -> ConcatFromSequence: Replaced with Concat (with optional Unsqueeze for new_axis mode)
+/// 2. Loop(SequenceInsert) -> ConcatFromSequence: The Loop is rewritten to use ConcatOutputDescription
+///
+/// Used by both ONNX and PyTorch frontends.
+class SequenceConcatReplacer : public ov::pass::MatcherPass {
+public:
+ OPENVINO_MATCHER_PASS_RTTI("ov::frontend::pass::SequenceConcatReplacer");
+ SequenceConcatReplacer();
+};
+
+} // namespace pass
+} // namespace frontend
+} // namespace ov
diff --git a/src/frontends/common_translators/src/sequence_concat_replacer.cpp b/src/frontends/common_translators/src/sequence_concat_replacer.cpp
new file mode 100644
index 00000000000..1f92bbb2bcf
--- /dev/null
+++ b/src/frontends/common_translators/src/sequence_concat_replacer.cpp
@@ -0,0 +1,307 @@
+// Copyright (C) 2018-2026 Intel Corporation
+// SPDX-License-Identifier: Apache-2.0
+//
+
+#include "sequence_concat_replacer.hpp"
+
+#include <limits>
+#include <vector>
+
+#include "openvino/core/graph_util.hpp"
+#include "openvino/core/rt_info.hpp"
+#include "openvino/core/validation_util.hpp"
+#include "openvino/frontend/concat_from_sequence.hpp"
+#include "openvino/frontend/sequence_insert.hpp"
+#include "openvino/frontend/sequence_mark.hpp"
+#include "openvino/op/concat.hpp"
+#include "openvino/op/constant.hpp"
+#include "openvino/op/loop.hpp"
+#include "openvino/op/reshape.hpp"
+#include "openvino/op/result.hpp"
+#include "openvino/op/shape_of.hpp"
+#include "openvino/op/slice.hpp"
+#include "openvino/op/unsqueeze.hpp"
+#include "openvino/pass/pattern/matcher.hpp"
+#include "openvino/pass/pattern/op/wrap_type.hpp"
+
+using namespace ov::op;
+
+namespace ov {
+namespace frontend {
+namespace pass {
+namespace {
+
+constexpr size_t INVALID_INDEX = std::numeric_limits<size_t>::max();
+
+bool is_append_only_sequence_insert(const std::shared_ptr<ov::frontend::SequenceInsert>& seq_insert) {
+ if (!seq_insert || !seq_insert->has_position()) {
+ return true;
+ }
+
+ const auto pos_const = ov::as_type_ptr<v0::Constant>(seq_insert->get_position().get_node_shared_ptr());
+ if (!pos_const) {
+ return false;
+ }
+
+ const auto pos_values = pos_const->cast_vector<int64_t>();
+ return pos_values.size() == 1 && pos_values[0] == -1;
+}
+
+int64_t normalize_axis(const ov::Output<ov::Node>& sample, int64_t axis, bool new_axis) {
+ const auto rank = sample.get_partial_shape().rank();
+ if (!rank.is_static())
+ return axis;
+ const auto full_rank = rank.get_length() + (new_axis ? 1 : 0);
+ OPENVINO_ASSERT(ov::util::is_axis_valid(axis, full_rank),
+ "ConcatFromSequence: axis ",
+ axis,
+ " out of range for rank ",
+ full_rank);
+ return ov::util::normalize(axis, full_rank);
+}
+
+// Trace through SequenceMark/Unsqueeze/SequenceInsert to find the inserted tensor
+ov::Output<ov::Node> find_inserted_tensor(const ov::Output<ov::Node>& seq_output) {
+ auto node = seq_output.get_node_shared_ptr();
+ if (auto unsqueeze = std::dynamic_pointer_cast<v0::Unsqueeze>(node))
+ node = unsqueeze->input_value(0).get_node_shared_ptr();
+ // aten::append wraps SequenceInsert in SequenceMark — unwrap it
+ if (auto seq_mark = std::dynamic_pointer_cast<ov::frontend::SequenceMark>(node))
+ if (seq_mark->get_input_size() == 1)
+ node = seq_mark->input_value(0).get_node_shared_ptr();
+ if (auto seq_insert = std::dynamic_pointer_cast<ov::frontend::SequenceInsert>(node)) {
+ if (!is_append_only_sequence_insert(seq_insert)) {
+ return {};
+ }
+ return seq_insert->get_tensor();
+ }
+ return {};
+}
+
+// Find body result index for a sequence output with SequenceInsert
+int64_t find_sequence_body_result_index(const std::shared_ptr<v5::Loop>& loop, size_t output_index) {
+ const auto& body_results = loop->get_function()->get_results();
+ for (const auto& desc : loop->get_output_descriptions()) {
+ if (desc->m_output_index != output_index)
+ continue;
+ if (desc->m_body_value_index < body_results.size()) {
+ if (find_inserted_tensor(body_results[desc->m_body_value_index]->input_value(0)).get_node())
+ return static_cast<int64_t>(desc->m_body_value_index);
+ }
+ }
+ return -1;
+}
+
+// Rewrite Loop that builds sequence via SequenceInsert to use ConcatOutputDescription
+bool rewrite_loop_concat(const std::shared_ptr<ov::frontend::ConcatFromSequence>& concat_fw,
+ const ov::Output<ov::Node>& sequence_output,
+ int64_t axis,
+ bool new_axis) {
+ const auto loop = ov::as_type_ptr<v5::Loop>(sequence_output.get_node_shared_ptr());
+ if (!loop)
+ return false;
+
+ const auto output_index = sequence_output.get_index();
+ const auto seq_result_idx = find_sequence_body_result_index(loop, output_index);
+ if (seq_result_idx < 0)
+ return false;
+
+ auto body = loop->get_function();
+ auto special_ports = loop->get_special_body_ports();
+ const auto& body_results = body->get_results();
+
+ auto data_value = find_inserted_tensor(body_results[seq_result_idx]->input_value(0));
+ if (!data_value.get_node())
+ return false;
+
+ const auto norm_axis = normalize_axis(data_value, axis, new_axis);
+
+ // Find sequence merged input (for potential removal)
+ size_t seq_param_idx = INVALID_INDEX, seq_input_idx = INVALID_INDEX;
+ for (const auto& desc : loop->get_input_descriptions()) {
+ if (auto merged = std::dynamic_pointer_cast<v5::Loop::MergedInputDescription>(desc)) {
+ if (merged->m_body_value_index == static_cast<size_t>(seq_result_idx)) {
+ seq_param_idx = merged->m_body_parameter_index;
+ seq_input_idx = merged->m_input_index;
+ break;
+ }
+ }
+ }
+
+ // Build new body: replace sequence result with tensor for Loop concatenation
+ auto new_results = body_results;
+ new_results.erase(new_results.begin() + seq_result_idx);
+
+ // Always unsqueeze at norm_axis so the concat dimension has size 1 and
+ // ConcatOutputDescription can use stride=1. For !new_axis the extra
+ // dimension is flattened back with a Reshape after the loop.
+ auto unsqueeze_axis = v0::Constant::create(ov::element::i64, ov::Shape{}, {norm_axis});
+ ov::Output<ov::Node> body_output = std::make_shared<v0::Unsqueeze>(data_value, unsqueeze_axis);
+ new_results.push_back(std::make_shared<v0::Result>(body_output));
+ const size_t concat_result_idx = new_results.size() - 1;
+
+ // Remove sequence parameter — its only consumer is the old SequenceInsert chain
+ // that we are replacing with ConcatOutputDescription. The old chain nodes still hold
+ // live edges to the parameter (get_target_inputs() is non-empty) but none of them
+ // appear in new_results, so the new body will not reference this parameter.
+ auto body_params = body->get_parameters();
+ bool remove_seq_input = seq_param_idx != INVALID_INDEX && seq_param_idx < body_params.size();
+ if (remove_seq_input) {
+ body_params.erase(body_params.begin() + seq_param_idx);
+ }
+
+ auto new_body = std::make_shared<ov::Model>(new_results, body_params);
+
+ // Adjust current_iteration port if parameter was removed before it
+ if (remove_seq_input && special_ports.current_iteration_input_idx >= 0 &&
+ static_cast<size_t>(special_ports.current_iteration_input_idx) > seq_param_idx)
+ --special_ports.current_iteration_input_idx;
+
+ // Adjust body_condition_output port if body results were shifted.
+ if (special_ports.body_condition_output_idx >= 0 &&
+ static_cast<size_t>(special_ports.body_condition_output_idx) > static_cast<size_t>(seq_result_idx)) {
+ --special_ports.body_condition_output_idx;
+ }
+
+ // Fix output descriptions: adjust indices and convert sequence output to ConcatOutputDescription.
+ // Body output is always unsqueezed at norm_axis (dim=1), so stride=1, part_size=1.
+ std::vector<std::shared_ptr<v5::Loop::OutputDescription>> out_descs;
+ for (const auto& desc : loop->get_output_descriptions()) {
+ auto d = desc->copy();
+ if (d->m_body_value_index > static_cast<size_t>(seq_result_idx))
+ d->m_body_value_index--;
+ if (d->m_output_index == output_index)
+ d = std::make_shared<v5::Loop::ConcatOutputDescription>(concat_result_idx,
+ output_index,
+ 0,
+ 1,
+ 1,
+ -1,
+ norm_axis);
+ out_descs.push_back(d);
+ }
+
+ // Fix inputs: remove sequence input if unused
+ ov::OutputVector new_inputs;
+ if (remove_seq_input && seq_input_idx != INVALID_INDEX) {
+ for (size_t i = 0; i < loop->get_input_size(); ++i)
+ if (i != seq_input_idx)
+ new_inputs.push_back(loop->input_value(i));
+ } else {
+ new_inputs = loop->input_values();
+ }
+
+ // Fix input descriptions: adjust indices for removed parameter/input
+ std::vector<std::shared_ptr<v5::Loop::InputDescription>> in_descs;
+ for (const auto& desc : loop->get_input_descriptions()) {
+ auto d = desc->copy();
+ if (remove_seq_input && d->m_input_index == seq_input_idx)
+ continue;
+ if (remove_seq_input && d->m_input_index > seq_input_idx)
+ d->m_input_index--;
+ if (auto merged = std::dynamic_pointer_cast<v5::Loop::MergedInputDescription>(d))
+ if (merged->m_body_value_index > static_cast<size_t>(seq_result_idx))
+ merged->m_body_value_index--;
+ if (remove_seq_input) {
+ if (d->m_body_parameter_index == seq_param_idx)
+ continue;
+ if (d->m_body_parameter_index > seq_param_idx)
+ d->m_body_parameter_index--;
+ }
+ in_descs.push_back(d);
+ }
+
+ // Create new Loop
+ const auto new_loop = std::make_shared<v5::Loop>();
+ new_loop->set_special_body_ports(special_ports);
+ new_loop->set_arguments(new_inputs);
+ new_loop->set_friendly_name(loop->get_friendly_name());
+ new_loop->set_function(new_body);
+ new_loop->set_input_descriptions(0, in_descs);
+ new_loop->set_output_descriptions(0, out_descs);
+ new_loop->set_output_size(loop->get_output_size());
+ new_loop->validate_and_infer_types();
+ ov::copy_runtime_info({loop, concat_fw}, new_loop);
+
+ // Replace Loop outputs
+ for (size_t i = 0; i < loop->get_output_size(); ++i) {
+ if (i == output_index) {
+ ov::Output<ov::Node> out = new_loop->output(i);
+ if (!new_axis) {
+ // Flatten the unsqueeze dimension: merge dims [norm_axis, norm_axis+1]
+ // into one, recovering the original concatenation semantics.
+ // Use Slice-based shape computation that works with dynamic rank.
+ auto shape = std::make_shared<v3::ShapeOf>(out, ov::element::i64);
+ auto zero = v0::Constant::create(ov::element::i64, ov::Shape{1}, {0});
+ auto step = v0::Constant::create(ov::element::i64, ov::Shape{1}, {1});
+ auto neg_one = v0::Constant::create(ov::element::i64, ov::Shape{1}, {-1});
+ ov::OutputVector parts;
+ if (norm_axis > 0) {
+ auto stop = v0::Constant::create(ov::element::i64, ov::Shape{1}, {norm_axis});
+ parts.push_back(std::make_shared<v8::Slice>(shape, zero, stop, step));
+ }
+ parts.push_back(neg_one);
+ auto start_suffix = v0::Constant::create(ov::element::i64, ov::Shape{1}, {norm_axis + 2});
+ auto max_stop =
+ v0::Constant::create(ov::element::i64, ov::Shape{1}, {std::numeric_limits<int64_t>::max()});
+ parts.push_back(std::make_shared<v8::Slice>(shape, start_suffix, max_stop, step));
+ auto target = parts.size() == 1 ? parts[0] : std::make_shared<v0::Concat>(parts, 0)->output(0);
+ auto reshape = std::make_shared<v1::Reshape>(out, target, false);
+ ov::copy_runtime_info({loop, concat_fw}, reshape);
+ out = reshape;
+ }
+ concat_fw->output(0).replace(out);
+ } else {
+ loop->output(i).replace(new_loop->output(i));
+ }
+ }
+ return true;
+}
+
+} // namespace
+
+SequenceConcatReplacer::SequenceConcatReplacer() {
+ auto concat_pattern = ov::pass::pattern::wrap_type<ov::frontend::ConcatFromSequence>();
+
+ matcher_pass_callback callback = [=](ov::pass::pattern::Matcher& m) {
+ const auto concat_fw = std::dynamic_pointer_cast<ov::frontend::ConcatFromSequence>(m.get_match_root());
+ if (!concat_fw)
+ return false;
+
+ const auto axis = concat_fw->get_axis();
+ const auto new_axis = concat_fw->get_new_axis();
+ const auto& seq_input = concat_fw->input_value(0);
+
+ // Case 1: SequenceMark / SequenceInsert chain (known sequence elements)
+ if (const auto seq_mark = ov::as_type_ptr<ov::frontend::SequenceMark>(seq_input.get_node_shared_ptr())) {
+ const auto& data = seq_mark->get_sequence();
+ if (data.empty())
+ return false;
+ const auto norm_axis = normalize_axis(data.front(), axis, new_axis);
+ ov::OutputVector inputs;
+ if (new_axis) {
+ auto axis_const = v0::Constant::create(ov::element::i64, ov::Shape{}, {norm_axis});
+ for (const auto& d : data)
+ inputs.push_back(std::make_shared<v0::Unsqueeze>(d, axis_const));
+ } else {
+ inputs = data;
+ }
+
+ auto concat = std::make_shared<v0::Concat>(inputs, norm_axis);
+ concat->set_friendly_name(concat_fw->get_friendly_name());
+ ov::copy_runtime_info(concat_fw, concat);
+ ov::replace_node(concat_fw, concat);
+ return true;
+ }
+
+ // Case 2: Loop output (sequence built via iterations)
+ return rewrite_loop_concat(concat_fw, seq_input, axis, new_axis);
+ };
+
+ auto m = std::make_shared<ov::pass::pattern::Matcher>(concat_pattern, "ov::frontend::pass::SequenceConcatReplacer");
+ register_matcher(m, callback);
+}
+
+} // namespace pass
+} // namespace frontend
+} // namespace ov
diff --git a/src/frontends/onnx/docs/supported_ops.md b/src/frontends/onnx/docs/supported_ops.md
index 8a689d32716..9c546ed48cf 100644
--- a/src/frontends/onnx/docs/supported_ops.md
+++ b/src/frontends/onnx/docs/supported_ops.md
@@ -38,7 +38,7 @@ OpenVINO provides support for operations of Default Opset (empty in table below)
| |Col2Im | |18 | |
| |Compress |9 |11, 9 | |
| |Concat |1 |13, 11, 4, 1 | |
-| |ConcatFromSequence | |11 | |
+| |ConcatFromSequence |11 |11 |Supported only in certain patterns|
| |Constant |13, 1 |21, 19, 13, 12, 11, 9, 1 | |
| |ConstantFill |1 | | |
| |ConstantOfShape |9 |21, 20, 9 | |
@@ -163,11 +163,11 @@ OpenVINO provides support for operations of Default Opset (empty in table below)
| |ScatterElements |11 |18, 16, 13, 11 | |
| |ScatterND |11 |18, 16, 13, 11 | |
| |Selu |1 |22, 6, 1 | |
-| |SequenceAt |11 |11 | |
-| |SequenceConstruct | |11 | |
-| |SequenceEmpty | |11 | |
+| |SequenceAt |11 |11 |Supported only in certain patterns|
+| |SequenceConstruct |11 |11 |Supported only in certain patterns|
+| |SequenceEmpty |11 |11 |Supported only in certain patterns|
| |SequenceErase | |11 | |
-| |SequenceInsert | |11 | |
+| |SequenceInsert |11 |11 |Supported only in certain patterns|
| |SequenceLength | |11 | |
| |SequenceMap | |17 | |
| |Shape |15, 1 |21, 19, 15, 13, 1 | |
diff --git a/src/frontends/onnx/frontend/src/core/graph.cpp b/src/frontends/onnx/frontend/src/core/graph.cpp
index ef62c58a066..6e19ff9f431 100644
--- a/src/frontends/onnx/frontend/src/core/graph.cpp
+++ b/src/frontends/onnx/frontend/src/core/graph.cpp
@@ -458,6 +458,9 @@ Output<ov::Node> Subgraph::get_ov_node_from_cache(const std::string& name) {
return from_parent_node;
auto new_param = std::make_shared<ov::op::v0::Parameter>(from_parent_node.get_element_type(),
from_parent_node.get_partial_shape());
+ // Set the original tensor name on the parameter output so that partition_body_parameters
+ // in Loop conversion can look it up via translate_session->lookup_tensor().
+ new_param->output(0).set_names({name});
m_parameter_to_parent_node_map.insert({new_param, name});
m_cache->emplace_node(name, new_param);
m_parameters.push_back(new_param);
diff --git a/src/frontends/onnx/frontend/src/core/graph_iterator_proto.cpp b/src/frontends/onnx/frontend/src/core/graph_iterator_proto.cpp
index f48bec9273d..a6003ab2570 100644
--- a/src/frontends/onnx/frontend/src/core/graph_iterator_proto.cpp
+++ b/src/frontends/onnx/frontend/src/core/graph_iterator_proto.cpp
@@ -12,6 +12,7 @@
#include <exception>
#include <fstream>
#include <map>
+#include <queue>
#include <unordered_map>
#include <unordered_set>
#include <vector>
@@ -102,6 +103,142 @@ void fixup_legacy_nodes(::ONNX_NAMESPACE::ModelProto& model_proto) {
}
}
}
+
+/// \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
+ for (const auto& inp : node.input()) {
+ if (!inp.empty()) {
+ deps.insert(inp);
+ }
+ }
+ // Subgraph external references (for Loop/If/Scan bodies referencing outer tensors)
+ for (const auto& attr : node.attribute()) {
+ if (!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);
+ }
+ }
+ }
+ }
+}
+
+/// \brief Topologically sort graph nodes, considering subgraph dependencies.
+void topological_sort_graph(GraphProto* graph) {
+ const int num_nodes = graph->node_size();
+ if (num_nodes == 0) {
+ return;
+ }
+
+ // Known tensors: graph inputs and initializers
+ std::unordered_set<std::string> known_tensors;
+ for (const auto& input : graph->input()) {
+ known_tensors.insert(input.name());
+ }
+ for (const auto& init : graph->initializer()) {
+ known_tensors.insert(init.name());
+ }
+
+ // Precompute dependencies for each node
+ std::vector<std::unordered_set<std::string>> node_deps(num_nodes);
+ for (int i = 0; i < num_nodes; ++i) {
+ collect_node_dependencies(graph->node(i), node_deps[i]);
+ }
+
+ // Build producer map for node outputs
+ std::unordered_map<std::string, int> producer_by_tensor;
+ producer_by_tensor.reserve(num_nodes * 2);
+ for (int i = 0; i < num_nodes; ++i) {
+ for (const auto& out : graph->node(i).output()) {
+ if (!out.empty()) {
+ producer_by_tensor.emplace(out, i);
+ }
+ }
+ }
+
+ // Build dependency graph: producer -> consumer and indegree per consumer.
+ // Also track dependencies that are neither known graph inputs/initializers
+ // nor produced by any node in this graph.
+ std::vector<std::vector<int>> adjacency(num_nodes);
+ std::vector<int> indegree(num_nodes, 0);
+ std::vector<int> unresolved_external(num_nodes, 0);
+ std::unordered_set<uint64_t> unique_edges;
+ unique_edges.reserve(static_cast<size_t>(num_nodes) * 2);
+ for (int i = 0; i < num_nodes; ++i) {
+ for (const auto& dep : node_deps[i]) {
+ if (known_tensors.count(dep) > 0) {
+ continue;
+ }
+ if (const auto producer_it = producer_by_tensor.find(dep); producer_it != producer_by_tensor.end()) {
+ const int producer_idx = producer_it->second;
+ const auto edge_key =
+ (static_cast<uint64_t>(static_cast<uint32_t>(producer_idx)) << 32) | static_cast<uint32_t>(i);
+ if (unique_edges.insert(edge_key).second) {
+ adjacency[producer_idx].push_back(i);
+ ++indegree[i];
+ }
+ } else {
+ ++unresolved_external[i];
+ }
+ }
+ }
+
+ // Kahn's algorithm: queue nodes with all dependencies satisfied
+ std::queue<int> ready_nodes;
+ for (int i = 0; i < num_nodes; ++i) {
+ if (indegree[i] == 0 && unresolved_external[i] == 0) {
+ ready_nodes.push(i);
+ }
+ }
+
+ std::vector<NodeProto> sorted_nodes;
+ sorted_nodes.reserve(num_nodes);
+ int processed_nodes = 0;
+
+ while (!ready_nodes.empty()) {
+ const int node_idx = ready_nodes.front();
+ ready_nodes.pop();
+
+ sorted_nodes.push_back(graph->node(node_idx));
+ ++processed_nodes;
+
+ for (const auto consumer_idx : adjacency[node_idx]) {
+ --indegree[consumer_idx];
+ if (indegree[consumer_idx] == 0 && unresolved_external[consumer_idx] == 0) {
+ ready_nodes.push(consumer_idx);
+ }
+ }
+ }
+
+ if (processed_nodes != num_nodes) {
+ return; // Cycle detected or missing input - keep original order
+ }
+
+ // Replace graph nodes with sorted order
+ graph->mutable_node()->Clear();
+ for (auto& node : sorted_nodes) {
+ *graph->add_node() = std::move(node);
+ }
+}
} // namespace
namespace ov {
@@ -348,6 +485,7 @@ void GraphIteratorProto::initialize(const std::filesystem::path& path) {
model_file.close();
if (m_model->has_graph()) {
fixup_legacy_nodes(*m_model);
+ topological_sort_graph(m_model->mutable_graph());
m_graph = &m_model->graph();
} else {
m_graph = nullptr;
diff --git a/src/frontends/onnx/frontend/src/frontend.cpp b/src/frontends/onnx/frontend/src/frontend.cpp
index e6e5338fc1d..364cbd4c405 100644
--- a/src/frontends/onnx/frontend/src/frontend.cpp
+++ b/src/frontends/onnx/frontend/src/frontend.cpp
@@ -41,6 +41,7 @@
#include "openvino/op/result.hpp"
#include "openvino/util/log.hpp"
#include "ops_bridge.hpp"
+#include "sequence_concat_replacer.hpp"
#include "transformations/resolve_names_collisions.hpp"
#include "translate_session.hpp"
#include "unconverted_ops_report.hpp"
@@ -253,11 +254,12 @@ std::shared_ptr<ov::Model> FrontEnd::convert_partially(const ov::frontend::Input
const auto& converted_model = model_onnx->convert();
+ normalize(converted_model);
+
// For convert_partially, we don't throw on unconverted ops but still send telemetry
const auto report = ov::frontend::collect_unconverted_ops(converted_model, make_onnx_extractor());
ov::frontend::check_unconverted_ops(report, m_extensions.telemetry, "onnx", "[ONNX Frontend] ", "", nullptr, false);
- normalize(converted_model);
return converted_model;
}
@@ -269,7 +271,8 @@ void FrontEnd::normalize(const std::shared_ptr<ov::Model>& model) const {
// Here, you can register transformations as a second step of importing process
// In particular, you can operate on not supported ops (it allows to N:N ONNX->OV mapping).
ov::pass::Manager manager("Frontend:ONNX:normalize");
- manager.register_pass<pass::ResolveNameCollisions>(true);
+ manager.register_pass<ov::frontend::pass::SequenceConcatReplacer>();
+ manager.register_pass<ov::pass::ResolveNameCollisions>(true);
manager.run_passes(model);
}
@@ -294,12 +297,13 @@ std::shared_ptr<ov::Model> FrontEnd::convert(const InputModel::Ptr& input_model)
return model;
}
- const auto& converted_model = model_onnx->convert();
+ auto converted_model = model_onnx->convert();
+
+ normalize(converted_model);
const auto report = ov::frontend::collect_unconverted_ops(converted_model, make_onnx_extractor());
ov::frontend::check_unconverted_ops(report, m_extensions.telemetry, "onnx", "[ONNX Frontend] ");
- normalize(converted_model);
return converted_model;
}
@@ -411,10 +415,11 @@ std::shared_ptr<ov::Model> FrontEnd::convert_unify(const InputModel::Ptr& input_
translate_graph(input_model, false, false, ov_model);
+ normalize(ov_model);
+
const auto report = ov::frontend::collect_unconverted_ops(ov_model, make_onnx_extractor());
ov::frontend::check_unconverted_ops(report, m_extensions.telemetry, "onnx", "[ONNX Frontend] ");
- normalize(ov_model);
return ov_model;
}
@@ -433,11 +438,12 @@ std::shared_ptr<ov::Model> FrontEnd::convert_partially_unify(const InputModel::P
std::shared_ptr<ov::Model> ov_model;
translate_graph(input_model, false, false, ov_model);
+ normalize(ov_model);
+
// For convert_partially, we don't throw on unconverted ops but still send telemetry
const auto report = ov::frontend::collect_unconverted_ops(ov_model, make_onnx_extractor());
ov::frontend::check_unconverted_ops(report, m_extensions.telemetry, "onnx", "[ONNX Frontend] ", "", nullptr, false);
- normalize(ov_model);
return ov_model;
}
void FrontEnd::translate_graph(const InputModel::Ptr& input_model,
diff --git a/src/frontends/onnx/frontend/src/input_model.cpp b/src/frontends/onnx/frontend/src/input_model.cpp
index 78b220d7803..eb578c51fed 100644
--- a/src/frontends/onnx/frontend/src/input_model.cpp
+++ b/src/frontends/onnx/frontend/src/input_model.cpp
@@ -683,6 +683,9 @@ std::shared_ptr<ov::frontend::onnx::TensorONNXPlace> decode_tensor_place(
void InputModel::InputModelONNXImpl::load_model() {
std::map<std::string, uint64_t> op_statistics; // for telemetry
+ // Track output indices separately from TensorPlace (handles duplicate output names correctly)
+ std::vector<int64_t> output_indices;
+
m_op_places.reserve(m_graph_iterator->size());
for (; !m_graph_iterator->is_end(); m_graph_iterator->next()) {
const auto& decoder = m_graph_iterator->get_decoder();
@@ -702,8 +705,10 @@ void InputModel::InputModelONNXImpl::load_model() {
if (tensor_place_registered->is_input())
m_inputs.push_back(tensor_place_registered);
- if (tensor_place_registered->is_output())
+ if (tensor_decoder->get_output_idx() >= 0) {
m_outputs.push_back(tensor_place_registered);
+ output_indices.push_back(tensor_decoder->get_output_idx());
+ }
} else {
auto op_place = std::make_shared<OpPlace>(m_input_model, decoder);
m_op_places.push_back(op_place);
@@ -748,6 +753,20 @@ void InputModel::InputModelONNXImpl::load_model() {
};
std::sort(m_inputs.begin(), m_inputs.end(), sorting_places_by_idx(true));
+ // Sort outputs using the separately tracked indices (handles duplicate names correctly)
+ if (!m_outputs.empty() && m_outputs.size() == output_indices.size()) {
+ std::vector<std::pair<int64_t, ov::frontend::Place::Ptr>> indexed(m_outputs.size());
+ for (size_t i = 0; i < m_outputs.size(); ++i) {
+ indexed[i] = {output_indices[i], std::move(m_outputs[i])};
+ }
+ std::stable_sort(indexed.begin(), indexed.end(), [](const auto& a, const auto& b) {
+ return a.first < b.first;
+ });
+ for (size_t i = 0; i < indexed.size(); ++i) {
+ m_outputs[i] = std::move(indexed[i].second);
+ }
+ }
+
if (m_telemetry) {
for (const auto& op : op_statistics) {
m_telemetry->send_event("op_count", "onnx_" + op.first, static_cast<int>(op.second));
diff --git a/src/frontends/onnx/frontend/src/op/concat_from_sequence.cpp b/src/frontends/onnx/frontend/src/op/concat_from_sequence.cpp
new file mode 100644
index 00000000000..716c01e1b6e
--- /dev/null
+++ b/src/frontends/onnx/frontend/src/op/concat_from_sequence.cpp
@@ -0,0 +1,40 @@
+// Copyright (C) 2018-2026 Intel Corporation
+// SPDX-License-Identifier: Apache-2.0
+//
+
+#include "openvino/frontend/concat_from_sequence.hpp"
+
+#include <cstdint>
+#include <memory>
+
+#include "core/operator_set.hpp"
+#include "exceptions.hpp"
+#include "utils/common.hpp"
+
+namespace ov {
+namespace frontend {
+namespace onnx {
+namespace ai_onnx {
+namespace opset_11 {
+
+ov::OutputVector concat_from_sequence(const ov::frontend::onnx::Node& node) {
+ constexpr auto input_only = 1;
+ common::default_op_checks(node, input_only, input_only);
+
+ const auto axis = node.get_attribute_value<int64_t>("axis", 0);
+ const auto new_axis = node.get_attribute_value<int64_t>("new_axis", 0) != 0;
+
+ const auto& inputs = node.get_ov_inputs();
+ const auto& sequence_input = inputs.front();
+
+ // Create a ConcatFromSequence helper op that will be resolved by a transformation pass
+ return {std::make_shared<ov::frontend::ConcatFromSequence>(sequence_input, axis, new_axis)};
+}
+
+ONNX_OP("ConcatFromSequence", OPSET_SINCE(1), ai_onnx::opset_11::concat_from_sequence);
+
+} // namespace opset_11
+} // namespace ai_onnx
+} // namespace onnx
+} // namespace frontend
+} // namespace ov
diff --git a/src/frontends/onnx/frontend/src/op/loop.cpp b/src/frontends/onnx/frontend/src/op/loop.cpp
index 9a284b914ec..31570e6c8c1 100644
--- a/src/frontends/onnx/frontend/src/op/loop.cpp
+++ b/src/frontends/onnx/frontend/src/op/loop.cpp
@@ -4,6 +4,7 @@
#include "openvino/op/loop.hpp"
+#include <unordered_set>
#include <utility>
#include "core/graph.hpp"
@@ -15,9 +16,11 @@
#include "openvino/core/type.hpp"
#include "openvino/frontend/exception.hpp"
#include "openvino/op/constant.hpp"
+#include "openvino/op/convert.hpp"
#include "openvino/op/identity.hpp"
#include "openvino/op/unsqueeze.hpp"
#include "openvino/op/util/op_types.hpp"
+#include "openvino/util/log.hpp"
#include "translate_session.hpp"
#include "utils/reshape.hpp"
@@ -68,6 +71,7 @@ std::pair<ov::ParameterVector, std::vector<InvariantInput>> partition_body_param
"Translate session is required to partition Loop body parameters");
for (const auto& param : params) {
ov::Output<ov::Node> known_input;
+ // First try to look up by output names
const auto& names = param->output(0).get_names();
for (const auto& name : names) {
known_input = translate_session->lookup_tensor(name);
@@ -75,6 +79,12 @@ std::pair<ov::ParameterVector, std::vector<InvariantInput>> partition_body_param
break;
}
}
+ // If not found by output names, try to look up by friendly name.
+ // This handles the case where Model validation adds suffixes to tensor names
+ // but the friendly name remains unchanged.
+ if (known_input.get_node() == nullptr) {
+ known_input = translate_session->lookup_tensor(param->get_friendly_name());
+ }
if (known_input.get_node() != nullptr) {
invariants.emplace_back(param, known_input);
} else {
@@ -249,6 +259,23 @@ ov::OutputVector loop(const ov::frontend::onnx::Node& node) {
auto [canonical_inputs, invariant_inputs] = partition_body_parameters(node, body_inputs);
+ // Filter out body outputs that are just passthrough of invariant parameters.
+ // These can occur when the body model was translated with extra outputs for
+ // tensors that are invariant inputs from the parent graph.
+ std::unordered_set<ov::Node*> invariant_param_nodes;
+ for (const auto& [param, _] : invariant_inputs) {
+ invariant_param_nodes.insert(param.get());
+ }
+ ov::OutputVector filtered_body_outputs;
+ filtered_body_outputs.reserve(body_outputs.size());
+ for (const auto& out : body_outputs) {
+ // Keep the output unless it's a direct passthrough of an invariant parameter
+ if (invariant_param_nodes.count(out.get_node()) == 0) {
+ filtered_body_outputs.push_back(out);
+ }
+ }
+ body_outputs = std::move(filtered_body_outputs);
+
CHECK_VALID_NODE(node,
canonical_inputs.size() >= 2,
"The provided loop body graph inputs size (",
@@ -313,24 +340,26 @@ ov::OutputVector loop(const ov::frontend::onnx::Node& node) {
CHECK_VALID_NODE(node,
state_parameters.size() == loop_carried_dependencies.size(),
- "Number of loop body state parameters (",
+ "The provided loop body state parameters size (",
state_parameters.size(),
- ") does not match number of loop carried dependencies (",
+ ") must match the number of loop carried dependencies (",
loop_carried_dependencies.size(),
")");
+ const auto mapped = loop_carried_dependencies.size();
+
// Infer loop body inputs' element type based on carried dependencies
- for (size_t i = 0; i < loop_carried_dependencies.size(); i++) {
+ for (size_t i = 0; i < mapped; i++) {
state_parameters[i]->set_element_type(loop_carried_dependencies[i].get_element_type());
state_parameters[i]->set_partial_shape(loop_carried_dependencies[i].get_partial_shape());
}
CHECK_VALID_NODE(node,
- body_outputs.size() >= loop_carried_dependencies.size() + 1,
+ body_outputs.size() >= state_parameters.size() + 1,
"The provided loop body graph outputs size (",
body_outputs.size(),
") is not greater than number of outputs. Required at least: ",
- loop_carried_dependencies.size() + 1);
+ state_parameters.size() + 1);
ov::ParameterVector body_params;
body_params.push_back(iteration_param);
@@ -357,11 +386,10 @@ ov::OutputVector loop(const ov::frontend::onnx::Node& node) {
// Set-up loop carried dependencies and final output values
ov::OutputVector final_values;
- for (const auto& dep : loop_carried_dependencies) {
- loop->set_merged_input(*body_inputs_it++, dep, *body_outputs_it);
+ for (size_t i = 0; i < mapped; ++i) {
+ loop->set_merged_input(*body_inputs_it++, loop_carried_dependencies[i], *body_outputs_it);
final_values.push_back(loop->get_iter_value(*body_outputs_it++, -1));
}
-
for (const auto& [param, value] : invariant_inputs) {
FRONT_END_GENERAL_CHECK(value.get_node() != nullptr,
"Non-existent connection in body-graph to " + param->get_friendly_name());
diff --git a/src/frontends/onnx/frontend/src/op/sequence_construct.cpp b/src/frontends/onnx/frontend/src/op/sequence_construct.cpp
new file mode 100644
index 00000000000..56f1568aec7
--- /dev/null
+++ b/src/frontends/onnx/frontend/src/op/sequence_construct.cpp
@@ -0,0 +1,36 @@
+// Copyright (C) 2018-2026 Intel Corporation
+// SPDX-License-Identifier: Apache-2.0
+//
+
+#include <memory>
+
+#include "core/operator_set.hpp"
+#include "exceptions.hpp"
+#include "openvino/frontend/sequence_mark.hpp"
+#include "utils/common.hpp"
+
+namespace ov {
+namespace frontend {
+namespace onnx {
+namespace ai_onnx {
+namespace opset_11 {
+
+ov::OutputVector sequence_construct(const ov::frontend::onnx::Node& node) {
+ common::default_op_checks(node, 1);
+ const auto& inputs = node.get_ov_inputs();
+
+ // Create SequenceMark from inputs
+ auto sequence = std::make_shared<ov::frontend::SequenceMark>(inputs);
+ ov::op::util::FrameworkNodeAttrs attrs;
+ attrs.set_type_name("SequenceConstruct");
+ sequence->set_attrs(attrs);
+ return {sequence};
+}
+
+ONNX_OP("SequenceConstruct", OPSET_SINCE(1), ai_onnx::opset_11::sequence_construct);
+
+} // namespace opset_11
+} // namespace ai_onnx
+} // namespace onnx
+} // namespace frontend
+} // namespace ov
diff --git a/src/frontends/onnx/frontend/src/op/sequence_empty.cpp b/src/frontends/onnx/frontend/src/op/sequence_empty.cpp
new file mode 100644
index 00000000000..fd86fa984a4
--- /dev/null
+++ b/src/frontends/onnx/frontend/src/op/sequence_empty.cpp
@@ -0,0 +1,33 @@
+// Copyright (C) 2018-2026 Intel Corporation
+// SPDX-License-Identifier: Apache-2.0
+//
+
+#include <memory>
+
+#include "core/operator_set.hpp"
+#include "exceptions.hpp"
+#include "openvino/frontend/sequence_mark.hpp"
+#include "utils/common.hpp"
+
+namespace ov {
+namespace frontend {
+namespace onnx {
+namespace ai_onnx {
+namespace opset_11 {
+
+ov::OutputVector sequence_empty(const ov::frontend::onnx::Node& node) {
+ common::default_op_checks(node, 0, 0);
+ auto sequence = std::make_shared<ov::frontend::SequenceMark>(ov::OutputVector{});
+ ov::op::util::FrameworkNodeAttrs attrs;
+ attrs.set_type_name("SequenceEmpty");
+ sequence->set_attrs(attrs);
+ return {sequence};
+}
+
+ONNX_OP("SequenceEmpty", OPSET_SINCE(1), ai_onnx::opset_11::sequence_empty);
+
+} // namespace opset_11
+} // namespace ai_onnx
+} // namespace onnx
+} // namespace frontend
+} // namespace ov
diff --git a/src/frontends/onnx/frontend/src/op/sequence_insert.cpp b/src/frontends/onnx/frontend/src/op/sequence_insert.cpp
new file mode 100644
index 00000000000..902fcde7216
--- /dev/null
+++ b/src/frontends/onnx/frontend/src/op/sequence_insert.cpp
@@ -0,0 +1,44 @@
+// Copyright (C) 2018-2026 Intel Corporation
+// SPDX-License-Identifier: Apache-2.0
+//
+
+#include "openvino/frontend/sequence_insert.hpp"
+
+#include <memory>
+
+#include "core/operator_set.hpp"
+#include "exceptions.hpp"
+#include "openvino/core/validation_util.hpp"
+#include "openvino/frontend/sequence_mark.hpp"
+#include "openvino/op/constant.hpp"
+#include "utils/common.hpp"
+
+namespace ov {
+namespace frontend {
+namespace onnx {
+namespace ai_onnx {
+namespace opset_11 {
+
+ov::OutputVector sequence_insert(const ov::frontend::onnx::Node& node) {
+ constexpr auto min_inputs = 2;
+ constexpr auto max_inputs = 3;
+ common::default_op_checks(node, min_inputs, max_inputs);
+
+ const auto& inputs = node.get_ov_inputs();
+ const auto& sequence_input = inputs[0];
+ const auto& to_insert = inputs[1];
+
+ // Create a SequenceInsert helper op that will be resolved by a transformation pass
+ if (inputs.size() == 3) {
+ return {std::make_shared<ov::frontend::SequenceInsert>(sequence_input, to_insert, inputs[2])};
+ }
+ return {std::make_shared<ov::frontend::SequenceInsert>(sequence_input, to_insert)};
+}
+
+ONNX_OP("SequenceInsert", OPSET_SINCE(1), ai_onnx::opset_11::sequence_insert);
+
+} // namespace opset_11
+} // namespace ai_onnx
+} // namespace onnx
+} // namespace frontend
+} // namespace ov
diff --git a/src/frontends/onnx/tests/graph_iterator.cpp b/src/frontends/onnx/tests/graph_iterator.cpp
index b6ee2372442..85f99e85ac0 100644
--- a/src/frontends/onnx/tests/graph_iterator.cpp
+++ b/src/frontends/onnx/tests/graph_iterator.cpp
@@ -291,3 +291,99 @@ TEST(FrontEndGraphIteratorTest, handles_sequence_value_info) {
EXPECT_EQ(output_info.m_element_type, ov::element::i64);
EXPECT_EQ(output_info.m_partial_shape, ov::PartialShape({4}));
}
+
+// Test that GraphIteratorProto correctly performs topological sorting when
+// nodes are not in topological order. This tests the case where a Loop node
+// references an outer tensor that is produced by a node defined after the Loop.
+TEST(FrontEndGraphIteratorTest, topological_sort_loop_with_unsorted_graph) {
+ if (!ov::frontend::onnx::tests::is_graph_iterator_enabled()) {
+ GTEST_SKIP() << "This test requires GraphIterator (ONNX_ITERATOR=1)";
+ }
+ const std::string model_name = "controlflow/loop_with_unsorted_graph.onnx";
+ const auto model_path =
+ ov::util::path_join({ov::test::utils::getExecutableDirectory(), TEST_ONNX_MODELS_DIRNAME, model_name});
+
+ // Load and convert the model - this should succeed due to topological sorting
+ auto frontend = ov::frontend::FrontEndManager().load_by_framework("onnx");
+ ASSERT_NE(frontend, nullptr);
+
+ auto input_model = frontend->load(model_path);
+ ASSERT_NE(input_model, nullptr);
+
+ std::shared_ptr<ov::Model> model;
+ ASSERT_NO_THROW(model = frontend->convert(input_model))
+ << "Model conversion failed - topological sort may not be working correctly";
+ ASSERT_NE(model, nullptr);
+
+ // Verify the model produces correct results
+ // The model computes: a_final = a_init + outer_value * 3 iterations
+ // where outer_value = scale * scale = 2 * 2 = 4
+ // So a_final = [0, 0] + [4, 4] + [4, 4] + [4, 4] = [12, 12]
+ ov::test::TestCase test_case(model);
+ test_case.add_input<float>({0.f, 0.f}); // a_init
+ test_case.add_expected_output<float>(ov::Shape{1, 2}, {12.f, 12.f}); // a_final
+ test_case.add_expected_output<float>(ov::Shape{3, 1, 2}, {4.f, 4.f, 8.f, 8.f, 12.f, 12.f}); // a_values
+ test_case.run();
+}
+
+// Helper to load and convert an ONNX model via the graph iterator path.
+static std::shared_ptr<ov::Model> load_and_convert(const std::string& rel_model_path) {
+ const auto model_path =
+ ov::util::path_join({ov::test::utils::getExecutableDirectory(), TEST_ONNX_MODELS_DIRNAME, rel_model_path});
+ auto frontend = ov::frontend::FrontEndManager().load_by_framework("onnx");
+ auto input_model = frontend->load(model_path);
+ return frontend->convert(input_model);
+}
+
+// --- Topological sort edge-case tests ---
+
+// Linear chain in reverse order — sort must completely reorder.
+TEST(FrontEndGraphIteratorTest, topological_sort_reverse_chain) {
+ if (!ov::frontend::onnx::tests::is_graph_iterator_enabled()) {
+ GTEST_SKIP() << "This test requires GraphIterator (ONNX_ITERATOR=1)";
+ }
+ std::shared_ptr<ov::Model> model;
+ ASSERT_NO_THROW(model = load_and_convert("topological_sort/reverse_chain.onnx"));
+ ASSERT_NE(model, nullptr);
+
+ // Y = Neg(Abs(Relu(X))). With X=[-2, 3, -1]:
+ // Relu -> [0, 3, 0], Abs -> [0, 3, 0], Neg -> [0, -3, 0]
+ ov::test::TestCase test_case(model);
+ test_case.add_input<float>({-2.f, 3.f, -1.f});
+ test_case.add_expected_output<float>(ov::Shape{3}, {0.f, -3.f, 0.f});
+ test_case.run();
+}
+
+// Diamond pattern (unsorted) — multiple valid orderings exist.
+TEST(FrontEndGraphIteratorTest, topological_sort_diamond_unsorted) {
+ if (!ov::frontend::onnx::tests::is_graph_iterator_enabled()) {
+ GTEST_SKIP() << "This test requires GraphIterator (ONNX_ITERATOR=1)";
+ }
+ std::shared_ptr<ov::Model> model;
+ ASSERT_NO_THROW(model = load_and_convert("topological_sort/diamond_unsorted.onnx"));
+ ASSERT_NE(model, nullptr);
+
+ // Y = Relu(X) + Abs(X). With X=[-2, 3, -1]:
+ // R1=Relu -> [0, 3, 0], R2=Abs -> [2, 3, 1], Y = R1+R2 = [2, 6, 1]
+ ov::test::TestCase test_case(model);
+ test_case.add_input<float>({-2.f, 3.f, -1.f});
+ test_case.add_expected_output<float>(ov::Shape{3}, {2.f, 6.f, 1.f});
+ test_case.run();
+}
+
+// Unsorted node depends on initializer — initializers must be treated as known.
+TEST(FrontEndGraphIteratorTest, topological_sort_initializer_dependency) {
+ if (!ov::frontend::onnx::tests::is_graph_iterator_enabled()) {
+ GTEST_SKIP() << "This test requires GraphIterator (ONNX_ITERATOR=1)";
+ }
+ std::shared_ptr<ov::Model> model;
+ ASSERT_NO_THROW(model = load_and_convert("topological_sort/initializer_dep_unsorted.onnx"));
+ ASSERT_NE(model, nullptr);
+
+ // Y = Relu(X + init_val). init_val=[1,2,3], X=[-5,0,2]:
+ // T = X+init = [-4,2,5], Y = Relu(T) = [0,2,5]
+ ov::test::TestCase test_case(model);
+ test_case.add_input<float>({-5.f, 0.f, 2.f});
+ test_case.add_expected_output<float>(ov::Shape{3}, {0.f, 2.f, 5.f});
+ test_case.run();
+}
diff --git a/src/frontends/onnx/tests/models/controlflow/loop_sequence_concat_no_new_axis.prototxt b/src/frontends/onnx/tests/models/controlflow/loop_sequence_concat_no_new_axis.prototxt
new file mode 100644
index 00000000000..6a97ad6bb08
--- /dev/null
+++ b/src/frontends/onnx/tests/models/controlflow/loop_sequence_concat_no_new_axis.prototxt
@@ -0,0 +1,210 @@
+ir_version: 7
+producer_name: "OpenVINO ONNX Frontend"
+graph {
+ name: "loop_seq_concat_no_new_axis"
+ node {
+ output: "seq_empty"
+ op_type: "SequenceEmpty"
+ attribute {
+ name: "dtype"
+ i: 1
+ type: INT
+ }
+ }
+ node {
+ input: "trip_count"
+ input: "cond_init"
+ input: "seq_empty"
+ output: "seq_output"
+ op_type: "Loop"
+ attribute {
+ name: "body"
+ g {
+ name: "loop_body"
+ node {
+ input: "cond_in"
+ output: "cond_out"
+ op_type: "Identity"
+ }
+ node {
+ input: "iter"
+ output: "iter_f32"
+ op_type: "Cast"
+ attribute {
+ name: "to"
+ i: 1
+ type: INT
+ }
+ }
+ node {
+ output: "half"
+ op_type: "Constant"
+ attribute {
+ name: "value"
+ t {
+ dims: 1
+ data_type: 1
+ float_data: 0.5
+ name: "half_value"
+ }
+ type: TENSOR
+ }
+ }
+ node {
+ input: "iter_f32"
+ input: "half"
+ output: "iter_plus_half"
+ op_type: "Add"
+ }
+ node {
+ input: "iter_f32"
+ input: "shape_1d"
+ output: "tensor_iter"
+ op_type: "Reshape"
+ }
+ node {
+ input: "iter_plus_half"
+ input: "shape_1d"
+ output: "tensor_half"
+ op_type: "Reshape"
+ }
+ node {
+ input: "tensor_iter"
+ input: "tensor_half"
+ output: "tensor_2d"
+ op_type: "Concat"
+ attribute {
+ name: "axis"
+ i: 0
+ type: INT
+ }
+ }
+ node {
+ input: "seq_in"
+ input: "tensor_2d"
+ output: "seq_out"
+ op_type: "SequenceInsert"
+ }
+ initializer {
+ dims: 1
+ data_type: 7
+ int64_data: 1
+ name: "shape_1d"
+ }
+ input {
+ name: "iter"
+ type {
+ tensor_type {
+ elem_type: 7
+ shape {
+ }
+ }
+ }
+ }
+ input {
+ name: "cond_in"
+ type {
+ tensor_type {
+ elem_type: 9
+ shape {
+ }
+ }
+ }
+ }
+ input {
+ name: "seq_in"
+ type {
+ sequence_type {
+ elem_type {
+ tensor_type {
+ elem_type: 1
+ shape {
+ dim {
+ dim_value: 2
+ }
+ }
+ }
+ }
+ }
+ }
+ }
+ output {
+ name: "cond_out"
+ type {
+ tensor_type {
+ elem_type: 9
+ shape {
+ }
+ }
+ }
+ }
+ output {
+ name: "seq_out"
+ type {
+ sequence_type {
+ elem_type {
+ tensor_type {
+ elem_type: 1
+ shape {
+ dim {
+ dim_value: 2
+ }
+ }
+ }
+ }
+ }
+ }
+ }
+ }
+ type: GRAPH
+ }
+ }
+ input {
+ name: "trip_count"
+ type {
+ tensor_type {
+ elem_type: 7
+ shape {
+ }
+ }
+ }
+ }
+ input {
+ name: "cond_init"
+ type {
+ tensor_type {
+ elem_type: 9
+ shape {
+ }
+ }
+ }
+ }
+ node {
+ input: "seq_output"
+ output: "output"
+ op_type: "ConcatFromSequence"
+ attribute {
+ name: "axis"
+ i: 0
+ type: INT
+ }
+ attribute {
+ name: "new_axis"
+ i: 0
+ type: INT
+ }
+ }
+ output {
+ name: "output"
+ type {
+ tensor_type {
+ elem_type: 1
+ shape {
+ }
+ }
+ }
+ }
+}
+opset_import {
+ version: 14
+}
diff --git a/src/frontends/onnx/tests/models/controlflow/loop_sequence_insert_direct.prototxt b/src/frontends/onnx/tests/models/controlflow/loop_sequence_insert_direct.prototxt
new file mode 100644
index 00000000000..2c43a13d1fa
--- /dev/null
+++ b/src/frontends/onnx/tests/models/controlflow/loop_sequence_insert_direct.prototxt
@@ -0,0 +1,221 @@
+ir_version: 7
+producer_name: "OpenVINO ONNX Frontend"
+graph {
+ name: "loop_seq_concat"
+ node {
+ output: "accum_init"
+ op_type: "Constant"
+ attribute {
+ name: "value"
+ t {
+ dims: 1
+ data_type: 1
+ float_data: 0
+ name: "accum_init_value"
+ }
+ type: TENSOR
+ }
+ }
+ node {
+ output: "seq_empty"
+ op_type: "SequenceEmpty"
+ attribute {
+ name: "dtype"
+ i: 1
+ type: INT
+ }
+ }
+ node {
+ input: "trip_count"
+ input: "cond_init"
+ input: "accum_init"
+ input: "seq_empty"
+ output: "accum_final"
+ output: "seq_output"
+ op_type: "Loop"
+ attribute {
+ name: "body"
+ g {
+ name: "loop_body"
+ node {
+ input: "cond_in"
+ output: "cond_out"
+ op_type: "Identity"
+ }
+ node {
+ input: "iter"
+ output: "iter_f32"
+ op_type: "Cast"
+ attribute {
+ name: "to"
+ i: 1
+ type: INT
+ }
+ }
+ node {
+ input: "iter_f32"
+ input: "shape_1d"
+ output: "tensor_1d"
+ op_type: "Reshape"
+ }
+ node {
+ input: "accum_in"
+ input: "tensor_1d"
+ output: "accum_out"
+ op_type: "Add"
+ }
+ node {
+ input: "seq_in"
+ input: "tensor_1d"
+ output: "seq_out"
+ op_type: "SequenceInsert"
+ }
+ initializer {
+ dims: 1
+ data_type: 7
+ int64_data: 1
+ name: "shape_1d"
+ }
+ input {
+ name: "iter"
+ type {
+ tensor_type {
+ elem_type: 7
+ shape {
+ }
+ }
+ }
+ }
+ input {
+ name: "cond_in"
+ type {
+ tensor_type {
+ elem_type: 9
+ shape {
+ }
+ }
+ }
+ }
+ input {
+ name: "accum_in"
+ type {
+ tensor_type {
+ elem_type: 1
+ shape {
+ dim {
+ dim_value: 1
+ }
+ }
+ }
+ }
+ }
+ input {
+ name: "seq_in"
+ type {
+ sequence_type {
+ elem_type {
+ tensor_type {
+ elem_type: 1
+ shape {
+ dim {
+ dim_value: 1
+ }
+ }
+ }
+ }
+ }
+ }
+ }
+ output {
+ name: "cond_out"
+ type {
+ tensor_type {
+ elem_type: 9
+ shape {
+ }
+ }
+ }
+ }
+ output {
+ name: "accum_out"
+ type {
+ tensor_type {
+ elem_type: 1
+ shape {
+ dim {
+ dim_value: 1
+ }
+ }
+ }
+ }
+ }
+ output {
+ name: "seq_out"
+ type {
+ sequence_type {
+ elem_type {
+ tensor_type {
+ elem_type: 1
+ shape {
+ dim {
+ dim_value: 1
+ }
+ }
+ }
+ }
+ }
+ }
+ }
+ }
+ type: GRAPH
+ }
+ }
+ input {
+ name: "trip_count"
+ type {
+ tensor_type {
+ elem_type: 7
+ shape {
+ }
+ }
+ }
+ }
+ input {
+ name: "cond_init"
+ type {
+ tensor_type {
+ elem_type: 9
+ shape {
+ }
+ }
+ }
+ }
+ node {
+ input: "seq_output"
+ output: "output"
+ op_type: "ConcatFromSequence"
+ attribute {
+ name: "axis"
+ i: 1
+ type: INT
+ }
+ attribute {
+ name: "new_axis"
+ i: 1
+ type: INT
+ }
+ }
+ output {
+ name: "output"
+ type {
+ tensor_type {
+ elem_type: 1
+ shape {
+ }
+ }
+ }
+ }
+}
+opset_import {
+ version: 14
+}
diff --git a/src/frontends/onnx/tests/models/controlflow/loop_with_unsorted_graph.prototxt b/src/frontends/onnx/tests/models/controlflow/loop_with_unsorted_graph.prototxt
new file mode 100644
index 00000000000..16ab59b378f
--- /dev/null
+++ b/src/frontends/onnx/tests/models/controlflow/loop_with_unsorted_graph.prototxt
@@ -0,0 +1,155 @@
+ir_version: 6
+producer_name: "OpenVINO ONNX Frontend"
+# Test model for topological sort in GraphIteratorProto.
+# This model has a Loop node that references "outer_value" in its body,
+# but "outer_value" is produced by a node defined AFTER the Loop node.
+# Without topological sorting, this model would fail to load.
+graph {
+ name: "unsorted_loop_test"
+ # Loop node comes FIRST but references "outer_value" which is produced LATER
+ node {
+ input: "trip_count"
+ input: ""
+ input: "a_init"
+ output: "a_final"
+ output: "a_values"
+ op_type: "Loop"
+ name: "loop_node"
+ attribute {
+ name: "body"
+ g {
+ name: "loop_body"
+ # This node references "outer_value" from parent scope
+ node {
+ input: "a_in"
+ input: "outer_value"
+ output: "current_a"
+ name: "loop_body_add"
+ op_type: "Add"
+ }
+ node {
+ input: "cond"
+ output: "cond_out"
+ name: "cond_identity"
+ op_type: "Identity"
+ }
+ node {
+ input: "current_a"
+ output: "a_out"
+ name: "output_accumulator"
+ op_type: "Identity"
+ }
+ input {
+ name: "i"
+ type {
+ tensor_type {
+ elem_type: 7
+ shape {
+ dim {
+ dim_value: 1
+ }
+ }
+ }
+ }
+ }
+ input {
+ name: "cond"
+ type {
+ tensor_type {
+ elem_type: 9
+ }
+ }
+ }
+ input {
+ name: "a_in"
+ type {
+ tensor_type {
+ elem_type: 1
+ }
+ }
+ }
+ output {
+ name: "cond_out"
+ type {
+ tensor_type {
+ elem_type: 9
+ }
+ }
+ }
+ output {
+ name: "current_a"
+ type {
+ tensor_type {
+ elem_type: 1
+ }
+ }
+ }
+ output {
+ name: "a_out"
+ type {
+ tensor_type {
+ elem_type: 1
+ }
+ }
+ }
+ }
+ type: GRAPH
+ }
+ }
+ # This node produces "outer_value" but is defined AFTER the Loop
+ # The topological sort should reorder this to come before the Loop
+ node {
+ input: "scale"
+ input: "scale"
+ name: "mul_node"
+ op_type: "Mul"
+ output: "outer_value"
+ }
+ initializer {
+ dims: 1
+ data_type: 7
+ int64_data: 3
+ name: "trip_count"
+ }
+ initializer {
+ dims: 1
+ data_type: 1
+ float_data: 2
+ name: "scale"
+ }
+ input {
+ name: "a_init"
+ type {
+ tensor_type {
+ elem_type: 1
+ shape {
+ dim {
+ dim_value: 1
+ }
+ dim {
+ dim_value: 2
+ }
+ }
+ }
+ }
+ }
+ output {
+ name: "a_final"
+ type {
+ tensor_type {
+ elem_type: 1
+ }
+ }
+ }
+ output {
+ name: "a_values"
+ type {
+ tensor_type {
+ elem_type: 1
+ }
+ }
+ }
+}
+opset_import {
+ version: 11
+}
diff --git a/src/frontends/onnx/tests/models/controlflow/sequence_construct_concat.prototxt b/src/frontends/onnx/tests/models/controlflow/sequence_construct_concat.prototxt
new file mode 100644
index 00000000000..c3f04ddcc8c
--- /dev/null
+++ b/src/frontends/onnx/tests/models/controlflow/sequence_construct_concat.prototxt
@@ -0,0 +1,79 @@
+ir_version: 7
+producer_name: "OpenVINO ONNX Frontend"
+graph {
+ name: "sequence_construct_concat"
+ node {
+ input: "input_a"
+ input: "input_b"
+ input: "input_c"
+ output: "sequence"
+ op_type: "SequenceConstruct"
+ }
+ node {
+ input: "sequence"
+ output: "output"
+ op_type: "ConcatFromSequence"
+ attribute {
+ name: "axis"
+ i: 0
+ type: INT
+ }
+ attribute {
+ name: "new_axis"
+ i: 1
+ type: INT
+ }
+ }
+ input {
+ name: "input_a"
+ type {
+ tensor_type {
+ elem_type: 1
+ shape {
+ dim {
+ dim_value: 2
+ }
+ }
+ }
+ }
+ }
+ input {
+ name: "input_b"
+ type {
+ tensor_type {
+ elem_type: 1
+ shape {
+ dim {
+ dim_value: 2
+ }
+ }
+ }
+ }
+ }
+ input {
+ name: "input_c"
+ type {
+ tensor_type {
+ elem_type: 1
+ shape {
+ dim {
+ dim_value: 2
+ }
+ }
+ }
+ }
+ }
+ output {
+ name: "output"
+ type {
+ tensor_type {
+ elem_type: 1
+ shape {
+ }
+ }
+ }
+ }
+}
+opset_import {
+ version: 14
+}
diff --git a/src/frontends/onnx/tests/models/topological_sort/diamond_unsorted.prototxt b/src/frontends/onnx/tests/models/topological_sort/diamond_unsorted.prototxt
new file mode 100644
index 00000000000..9d4edbfef2d
--- /dev/null
+++ b/src/frontends/onnx/tests/models/topological_sort/diamond_unsorted.prototxt
@@ -0,0 +1,56 @@
+ir_version: 8
+producer_name: "OpenVINO ONNX Frontend"
+# Diamond dependency pattern (unsorted):
+# X -> Relu -> R1 (node index 0 in sorted)
+# X -> Abs -> R2 (node index 1 in sorted)
+# R1 + R2 -> Y (node index 2 in sorted)
+# Nodes given in order: Add(R1,R2->Y), Abs(X->R2), Relu(X->R1)
+# Multiple valid orderings exist: {Relu, Abs, Add} or {Abs, Relu, Add}.
+graph {
+ name: "diamond_unsorted_graph"
+ node {
+ input: "R1"
+ input: "R2"
+ output: "Y"
+ op_type: "Add"
+ }
+ node {
+ input: "X"
+ output: "R2"
+ op_type: "Abs"
+ }
+ node {
+ input: "X"
+ output: "R1"
+ op_type: "Relu"
+ }
+ input {
+ name: "X"
+ type {
+ tensor_type {
+ elem_type: 1
+ shape {
+ dim {
+ dim_value: 3
+ }
+ }
+ }
+ }
+ }
+ output {
+ name: "Y"
+ type {
+ tensor_type {
+ elem_type: 1
+ shape {
+ dim {
+ dim_value: 3
+ }
+ }
+ }
+ }
+ }
+}
+opset_import {
+ version: 13
+}
diff --git a/src/frontends/onnx/tests/models/topological_sort/initializer_dep_unsorted.prototxt b/src/frontends/onnx/tests/models/topological_sort/initializer_dep_unsorted.prototxt
new file mode 100644
index 00000000000..710b6ee2420
--- /dev/null
+++ b/src/frontends/onnx/tests/models/topological_sort/initializer_dep_unsorted.prototxt
@@ -0,0 +1,69 @@
+ir_version: 8
+producer_name: "OpenVINO ONNX Frontend"
+# Node depends on an initializer. Given in wrong order:
+# Second node (Add of X and init_val -> T) should come before first node (Relu of T -> Y).
+# Tests that initializers are treated as known tensors.
+graph {
+ name: "initializer_dep_graph"
+ node {
+ input: "T"
+ output: "Y"
+ op_type: "Relu"
+ }
+ node {
+ input: "X"
+ input: "init_val"
+ output: "T"
+ op_type: "Add"
+ }
+ initializer {
+ dims: 3
+ data_type: 1
+ float_data: 1.0
+ float_data: 2.0
+ float_data: 3.0
+ name: "init_val"
+ }
+ input {
+ name: "X"
+ type {
+ tensor_type {
+ elem_type: 1
+ shape {
+ dim {
+ dim_value: 3
+ }
+ }
+ }
+ }
+ }
+ input {
+ name: "init_val"
+ type {
+ tensor_type {
+ elem_type: 1
+ shape {
+ dim {
+ dim_value: 3
+ }
+ }
+ }
+ }
+ }
+ output {
+ name: "Y"
+ type {
+ tensor_type {
+ elem_type: 1
+ shape {
+ dim {
+ dim_value: 3
+ }
+ }
+ }
+ }
+ }
+}
+opset_import {
+ version: 13
+}
diff --git a/src/frontends/onnx/tests/models/topological_sort/reverse_chain.prototxt b/src/frontends/onnx/tests/models/topological_sort/reverse_chain.prototxt
new file mode 100644
index 00000000000..bf6f76edfb3
--- /dev/null
+++ b/src/frontends/onnx/tests/models/topological_sort/reverse_chain.prototxt
@@ -0,0 +1,53 @@
+ir_version: 8
+producer_name: "OpenVINO ONNX Frontend"
+# Linear chain given in reverse order:
+# Correct order: X -> Relu -> R1, R1 -> Abs -> R2, R2 -> Neg -> Y
+# Given order: Neg(R2->Y), Abs(R1->R2), Relu(X->R1)
+# Topological sort must reorder completely.
+graph {
+ name: "reverse_chain_graph"
+ node {
+ input: "R2"
+ output: "Y"
+ op_type: "Neg"
+ }
+ node {
+ input: "R1"
+ output: "R2"
+ op_type: "Abs"
+ }
+ node {
+ input: "X"
+ output: "R1"
+ op_type: "Relu"
+ }
+ input {
+ name: "X"
+ type {
+ tensor_type {
+ elem_type: 1
+ shape {
+ dim {
+ dim_value: 3
+ }
+ }
+ }
+ }
+ }
+ output {
+ name: "Y"
+ type {
+ tensor_type {
+ elem_type: 1
+ shape {
+ dim {
+ dim_value: 3
+ }
+ }
+ }
+ }
+ }
+}
+opset_import {
+ version: 13
+}
diff --git a/src/frontends/onnx/tests/onnx_import_controlflow.in.cpp b/src/frontends/onnx/tests/onnx_import_controlflow.in.cpp
index cea9f3d372b..e8c2c752111 100644
--- a/src/frontends/onnx/tests/onnx_import_controlflow.in.cpp
+++ b/src/frontends/onnx/tests/onnx_import_controlflow.in.cpp
@@ -769,3 +769,59 @@ OPENVINO_TEST(${BACKEND_NAME}, onnx_if_negative_mismatch_between_branches_output
FAIL() << "Model import failed for unexpected reason";
}
}
+
+// ~~~~~~~~SEQUENCE PATTERN TESTS:~~~~~~~~
+// Tests for SequenceEmpty -> Loop(SequenceInsert) -> ConcatFromSequence pattern
+
+/// @brief Test SequenceEmpty -> Loop(SequenceInsert) -> ConcatFromSequence pattern with axis=1
+/// This tests the full sequence pattern where:
+/// 1. SequenceEmpty creates an empty sequence
+/// 2. Loop accumulates iteration indices (cast to float, reshaped to [1]) via SequenceInsert
+/// 3. ConcatFromSequence concatenates the sequence elements into a single tensor along axis=1
+/// The transformation rewrites the pattern: SequenceMark -> Loop(SequenceInsert) -> ConcatFromSequence
+/// into native OpenVINO operations using Loop's built-in concatenation mechanism
+OPENVINO_TEST(${BACKEND_NAME}, onnx_loop_sequence_insert_concat) {
+ const auto model = convert_model("controlflow/loop_sequence_insert_direct.onnx");
+
+ auto test_case = ov::test::TestCase(model, s_device);
+ // trip_count = 5
+ test_case.add_input<int64_t>({5});
+ // cond_init = true
+ test_case.add_input<bool>({true});
+
+ // Expected output: [[0, 1, 2, 3, 4]] as float tensor of shape [1, 5]
+ test_case.add_expected_output<float>(Shape{1, 5}, {0.f, 1.f, 2.f, 3.f, 4.f});
+ test_case.run();
+}
+
+/// @brief Test ConcatFromSequence with new_axis=false
+/// Loop accumulates [2] tensors, ConcatFromSequence concatenates without adding new axis
+OPENVINO_TEST(${BACKEND_NAME}, onnx_loop_sequence_concat_no_new_axis) {
+ const auto model = convert_model("controlflow/loop_sequence_concat_no_new_axis.onnx");
+
+ auto test_case = ov::test::TestCase(model, s_device);
+ // trip_count = 3
+ test_case.add_input<int64_t>({3});
+ // cond_init = true
+ test_case.add_input<bool>({true});
+
+ // Each iteration produces [i, i+0.5], concatenated: [0, 0.5, 1, 1.5, 2, 2.5]
+ test_case.add_expected_output<float>(Shape{6}, {0.f, 0.5f, 1.f, 1.5f, 2.f, 2.5f});
+ test_case.run();
+}
+
+/// @brief Test SequenceConstruct -> ConcatFromSequence pattern
+/// SequenceConstruct creates a sequence from input tensors, ConcatFromSequence concatenates them
+OPENVINO_TEST(${BACKEND_NAME}, onnx_sequence_construct_concat) {
+ const auto model = convert_model("controlflow/sequence_construct_concat.onnx");
+
+ auto test_case = ov::test::TestCase(model, s_device);
+ // Three input tensors of shape [2]
+ test_case.add_input<float>({1.f, 2.f}); // input_a
+ test_case.add_input<float>({3.f, 4.f}); // input_b
+ test_case.add_input<float>({5.f, 6.f}); // input_c
+
+ // With axis=0, new_axis=1: stack three [2] tensors -> [3, 2]
+ test_case.add_expected_output<float>(Shape{3, 2}, {1.f, 2.f, 3.f, 4.f, 5.f, 6.f});
+ test_case.run();
+}
diff --git a/src/frontends/onnx/tests/tests_python/test_backend.py b/src/frontends/onnx/tests/tests_python/test_backend.py
index 7beaf5c5e89..1ca9486cbcd 100644
--- a/src/frontends/onnx/tests/tests_python/test_backend.py
+++ b/src/frontends/onnx/tests/tests_python/test_backend.py
@@ -153,12 +153,10 @@ tests_expected_to_fail = [
),
(
xfail_issue_33596,
- "OnnxBackendSimpleModelTest.test_sequence_model5_cpu",
"OnnxBackendSimpleModelTest.test_sequence_model1_cpu",
"OnnxBackendSimpleModelTest.test_sequence_model3_cpu",
"OnnxBackendSimpleModelTest.test_sequence_model6_cpu",
"OnnxBackendSimpleModelTest.test_sequence_model8_cpu",
- "OnnxBackendSimpleModelTest.test_sequence_model4_cpu",
"OnnxBackendSimpleModelTest.test_sequence_model2_cpu",
"OnnxBackendNodeModelTest.test_identity_sequence_cpu",
"OnnxBackendNodeModelTest.test_if_seq_cpu",
diff --git a/src/frontends/pytorch/src/frontend.cpp b/src/frontends/pytorch/src/frontend.cpp
index 73224068645..c9341b44df1 100644
--- a/src/frontends/pytorch/src/frontend.cpp
+++ b/src/frontends/pytorch/src/frontend.cpp
@@ -12,6 +12,7 @@
#include "openvino/util/log.hpp"
#include "place.hpp"
#include "pt_framework_node.hpp"
+#include "sequence_concat_replacer.hpp"
#include "transformations/common_optimizations/push_constant_to_subgraph.hpp"
#include "transformations/common_optimizations/remove_multi_subgraph_op_dangling_params.hpp"
#include "transformations/common_optimizations/reverse_shape_and_type_infer.hpp"
@@ -21,7 +22,6 @@
#include "transformations/op_conversions/convert_convertpromotetypes.hpp"
#include "transformations/resolve_names_collisions.hpp"
#include "transforms/append_list_unpack_replacer.hpp"
-#include "transforms/aten_cat_replacer.hpp"
#include "transforms/aten_getitem_replacer.hpp"
#include "transforms/aten_index_put_replacer.hpp"
#include "transforms/aten_index_replacer.hpp"
@@ -230,7 +230,7 @@ void FrontEnd::normalize(const std::shared_ptr<ov::Model>& model) const {
manager.register_pass<ov::pass::ConvertConvertPromoteTypes>();
manager.register_pass<ov::pass::PushConstantToSubgraph>();
manager.register_pass<ov::frontend::pytorch::pass::TupleUnpackInBodyReplacer>();
- manager.register_pass<ov::frontend::pytorch::pass::AtenCatToConcat>();
+ manager.register_pass<ov::frontend::pass::SequenceConcatReplacer>();
manager.register_pass<ov::frontend::pytorch::pass::AppendListUnpackReplacer>();
manager.register_pass<ov::frontend::pytorch::pass::AtenEinsumListConstructReplacer>();
manager.register_pass<ov::frontend::pytorch::pass::MinMaxPrimListConstructReplacer>();
diff --git a/src/frontends/pytorch/src/op/append.cpp b/src/frontends/pytorch/src/op/append.cpp
new file mode 100644
index 00000000000..4136cb24ca9
--- /dev/null
+++ b/src/frontends/pytorch/src/op/append.cpp
@@ -0,0 +1,35 @@
+// Copyright (C) 2018-2026 Intel Corporation
+// SPDX-License-Identifier: Apache-2.0
+//
+
+#include "openvino/frontend/pytorch/node_context.hpp"
+#include "openvino/frontend/sequence_insert.hpp"
+#include "openvino/frontend/sequence_mark.hpp"
+#include "utils.hpp"
+
+namespace ov {
+namespace frontend {
+namespace pytorch {
+namespace op {
+
+OutputVector translate_append(const NodeContext& context) {
+ num_inputs_check(context, 2, 2);
+ auto seq = context.get_input(0);
+ auto tensor = context.get_input(1);
+ auto seq_insert = std::make_shared<ov::frontend::SequenceInsert>(seq, tensor);
+ context.mark_node(seq_insert);
+ auto result = context.mark_node(std::make_shared<ov::frontend::SequenceMark>(OutputVector{seq_insert}));
+ // aten::append mutates input list in-place. Update the tensor map so that
+ // subsequent reads of the same tensor ID (e.g. by aten::cat) see the
+ // chained SequenceInsert rather than the original SequenceMark.
+ // Inside a Loop body this also causes an extra Result to be created,
+ // turning the list into a carried (merged) value that SequenceConcatReplacer
+ // can rewrite.
+ context.mutate_input(0, result);
+ return {result};
+}
+
+} // namespace op
+} // namespace pytorch
+} // namespace frontend
+} // namespace ov
diff --git a/src/frontends/pytorch/src/op/cat.cpp b/src/frontends/pytorch/src/op/cat.cpp
index 60e0f3694e5..45d48c9db1a 100644
--- a/src/frontends/pytorch/src/op/cat.cpp
+++ b/src/frontends/pytorch/src/op/cat.cpp
@@ -3,10 +3,12 @@
//
#include "openvino/frontend/complex_type_mark.hpp"
+#include "openvino/frontend/concat_from_sequence.hpp"
#include "openvino/frontend/pytorch/node_context.hpp"
#include "openvino/op/concat.hpp"
#include "openvino/op/convert_like.hpp"
#include "openvino/op/convert_promote_types.hpp"
+#include "openvino/op/loop.hpp"
#include "openvino/op/parameter.hpp"
#include "openvino/op/reshape.hpp"
#include "openvino/op/scatter_elements_update.hpp"
@@ -29,20 +31,11 @@ OutputVector translate_cat_common(const NodeContext& context,
int64_t axis,
bool is_fx) {
if (list_elems.empty()) {
- // couldn't get list elements
- auto fw_node = std::make_shared<PtFrameworkNode>(context.get_decoder(), OutputVector{context.get_input(0)}, 1);
- auto attrs = fw_node->get_attrs();
- // If this fails it means axis is dynamic and <aten/quantized>::cat will be converted to fw node in regular
- // pipeline
- attrs["axis"] = std::to_string(axis);
- fw_node->set_attrs(attrs);
- return {context.mark_node(fw_node)};
+ // couldn't get list elements - create ConcatFromSequence for SequenceConcatReplacer to handle
+ auto concat_from_seq = std::make_shared<ov::frontend::ConcatFromSequence>(context.get_input(0), axis, false);
+ return {context.mark_node(concat_from_seq)};
}
auto first_node = list_elems.front().get_node_shared_ptr();
- PYTORCH_OP_CONVERSION_CHECK(
- list_elems.size() > 1 || !ov::as_type_ptr<v0::Parameter>(first_node),
- "<aten/quantized>::cat is located inside body while inputs are located outside of the body. "
- "This case is not supported.");
if (list_elems.size() == 1 && !is_fx) {
// Case when list was merged into tensor. // This case doesn't work with torchfx
@@ -126,8 +119,18 @@ OutputVector translate_cat_common(const NodeContext& context,
OutputVector translate_cat(const NodeContext& context) {
// This translator is only needed to get axis as constant from external scope
num_inputs_check(context, 2, 3);
- const auto&& list_elems = get_list_as_outputs(context.get_input(0));
+ auto input = context.get_input(0);
auto axis = context.const_input<int64_t>(1);
+ // If input comes from a Loop, create ConcatFromSequence - SequenceConcatReplacer will handle it
+ if (ov::as_type_ptr<v5::Loop>(input.get_node_shared_ptr())) {
+ auto concat_from_seq =
+ context.mark_node(std::make_shared<ov::frontend::ConcatFromSequence>(input, axis, false));
+ if (!context.input_is_none(2)) {
+ context.mutate_input(2, concat_from_seq);
+ }
+ return {concat_from_seq};
+ }
+ const auto&& list_elems = get_list_as_outputs(input);
auto out = translate_cat_common(context, list_elems, axis, false);
if (!context.input_is_none(2)) {
context.mutate_input(2, out[0]);
@@ -137,18 +140,28 @@ OutputVector translate_cat(const NodeContext& context) {
OutputVector translate_cat_fx(const NodeContext& context) {
num_inputs_check(context, 1, 2);
- const auto&& list_elems = get_list_as_outputs(context.get_input(0));
+ auto input = context.get_input(0);
int64_t axis = 0;
if (!context.input_is_none(1)) {
axis = context.const_input<int64_t>(1);
}
+ if (ov::as_type_ptr<v5::Loop>(input.get_node_shared_ptr())) {
+ return {context.mark_node(std::make_shared<ov::frontend::ConcatFromSequence>(input, axis, false))};
+ }
+ const auto&& list_elems = get_list_as_outputs(input);
return translate_cat_common(context, list_elems, axis, true);
};
OutputVector translate_quantized_cat(const NodeContext& context) {
num_inputs_check(context, 4, 4);
- const auto&& list_elems = get_list_as_outputs(context.get_input(0));
+ auto input = context.get_input(0);
auto axis = context.const_input<int64_t>(1);
+ if (ov::as_type_ptr<v5::Loop>(input.get_node_shared_ptr())) {
+ auto concat_from_seq =
+ context.mark_node(std::make_shared<ov::frontend::ConcatFromSequence>(input, axis, false));
+ return {quantize(context, concat_from_seq, context.get_input(2), context.get_input(3), input)};
+ }
+ const auto&& list_elems = get_list_as_outputs(input);
PYTORCH_OP_CONVERSION_CHECK(!list_elems.empty(), "Couldn't find quantized input for quantized::cat operation.");
return {quantize(context,
translate_cat_common(context, list_elems, axis, false)[0],
@@ -157,6 +170,36 @@ OutputVector translate_quantized_cat(const NodeContext& context) {
list_elems.front())};
};
+OutputVector translate_stack(const NodeContext& context) {
+ num_inputs_check(context, 2, 3);
+ auto input = context.get_input(0);
+ auto axis = context.const_input<int64_t>(1);
+ // Loop case: create ConcatFromSequence with new_axis=true (stack semantics)
+ if (ov::as_type_ptr<v5::Loop>(input.get_node_shared_ptr())) {
+ auto concat_from_seq = context.mark_node(std::make_shared<ov::frontend::ConcatFromSequence>(input, axis, true));
+ if (!context.input_is_none(2)) {
+ context.mutate_input(2, concat_from_seq);
+ }
+ return {concat_from_seq};
+ }
+ const auto&& list_elems = get_list_as_outputs(input);
+ OutputVector stack_inputs(list_elems.begin(), list_elems.end());
+ // GPTQ u4 decompression pattern
+ if (const auto& u4_const = u4_compression_stack(stack_inputs, axis))
+ return {u4_const};
+ // Direct case: unsqueeze each element then concatenate
+ auto dim = context.mark_node(v0::Constant::create(element::i32, Shape{}, {axis}));
+ std::deque<Output<Node>> unsqueezed;
+ for (const auto& elem : list_elems) {
+ unsqueezed.push_back(context.mark_node(std::make_shared<v0::Unsqueeze>(elem, dim)));
+ }
+ auto out = translate_cat_common(context, unsqueezed, axis, false);
+ if (!context.input_is_none(2)) {
+ context.mutate_input(2, out[0]);
+ }
+ return out;
+}
+
OutputVector translate_stack_fx(const NodeContext& context) {
num_inputs_check(context, 1, context.get_input_size());
int64_t axis = 0;
@@ -167,9 +210,14 @@ OutputVector translate_stack_fx(const NodeContext& context) {
axis = context.const_input<int64_t>(num_elements - 1);
}
+ auto input = context.get_input(0);
+ if (ov::as_type_ptr<v5::Loop>(input.get_node_shared_ptr())) {
+ return {context.mark_node(std::make_shared<ov::frontend::ConcatFromSequence>(input, axis, true))};
+ }
+
auto dim = context.mark_node(v0::Constant::create(element::i32, Shape{}, {axis}));
- list_elems = get_list_as_outputs(context.get_input(0));
+ list_elems = get_list_as_outputs(input);
OutputVector stack_inputs(list_elems.begin(), list_elems.end());
@@ -188,8 +236,17 @@ OutputVector translate_stack_fx(const NodeContext& context) {
OutputVector translate_hstack(const NodeContext& context) {
num_inputs_check(context, 1, 2);
- const auto&& list_elems = get_list_as_outputs(context.get_input(0));
+ auto input = context.get_input(0);
int64_t axis = 1;
+ if (ov::as_type_ptr<v5::Loop>(input.get_node_shared_ptr())) {
+ auto concat_from_seq =
+ context.mark_node(std::make_shared<ov::frontend::ConcatFromSequence>(input, axis, false));
+ if (!context.input_is_none(1)) {
+ context.mutate_input(1, concat_from_seq);
+ }
+ return {concat_from_seq};
+ }
+ const auto&& list_elems = get_list_as_outputs(input);
auto out = translate_cat_common(context, list_elems, axis, false);
if (!context.input_is_none(1)) {
context.mutate_input(1, out[0]);
@@ -199,8 +256,17 @@ OutputVector translate_hstack(const NodeContext& context) {
OutputVector translate_vstack(const NodeContext& context) {
num_inputs_check(context, 1, 2);
- const auto&& list_elems = get_list_as_outputs(context.get_input(0));
+ auto input = context.get_input(0);
int64_t axis = 0;
+ if (ov::as_type_ptr<v5::Loop>(input.get_node_shared_ptr())) {
+ auto concat_from_seq =
+ context.mark_node(std::make_shared<ov::frontend::ConcatFromSequence>(input, axis, false));
+ if (!context.input_is_none(1)) {
+ context.mutate_input(1, concat_from_seq);
+ }
+ return {concat_from_seq};
+ }
+ const auto&& list_elems = get_list_as_outputs(input);
auto out = translate_cat_common(context, list_elems, axis, false);
if (!context.input_is_none(1)) {
context.mutate_input(1, out[0]);
diff --git a/src/frontends/pytorch/src/op/list_unpack.cpp b/src/frontends/pytorch/src/op/list_unpack.cpp
index c87187bbe66..cb520bd026f 100644
--- a/src/frontends/pytorch/src/op/list_unpack.cpp
+++ b/src/frontends/pytorch/src/op/list_unpack.cpp
@@ -21,12 +21,11 @@ OutputVector translate_list_unpack(const NodeContext& context) {
// wrap outputs. This ensures transformations see clean graph without ComplexTypeMark.
auto [input, complex] = unwrap_complex(context.get_input(0));
- // Check for SequenceMark first (new list/tuple construct mechanism)
- if (const auto& seq_mark = ov::as_type_ptr<SequenceMark>(input.get_node_shared_ptr())) {
- // SequenceMark -> ListUnpack can be annihilated
- auto res = seq_mark->get_sequence();
- return wrap_complex(context, res, complex);
- } else {
+ if (auto seq_mark = ov::as_type_ptr<SequenceMark>(input.get_node_shared_ptr())) {
+ return wrap_complex(context, seq_mark->get_sequence(), complex);
+ }
+
+ {
// Create FrameworkNode with UNWRAPPED input (transformations will see clean graph)
auto list_unpack_fw = std::make_shared<PtFrameworkNode>(context.get_decoder(),
OutputVector{input}, // unwrapped!
diff --git a/src/frontends/pytorch/src/op/tuple_unpack.cpp b/src/frontends/pytorch/src/op/tuple_unpack.cpp
index 283392e8c74..ef4c0952d79 100644
--- a/src/frontends/pytorch/src/op/tuple_unpack.cpp
+++ b/src/frontends/pytorch/src/op/tuple_unpack.cpp
@@ -20,10 +20,8 @@ OutputVector translate_tuple_unpack(const NodeContext& context) {
// wrap outputs. This ensures transformations see clean graph without ComplexTypeMark.
auto [input, complex] = unwrap_complex(context.get_input(0));
- if (const auto& seq_mark = ov::as_type_ptr<SequenceMark>(input.get_node_shared_ptr())) {
- // SequenceMark -> TupleUnpack can be annihilated
- auto res = seq_mark->get_sequence();
- return wrap_complex(context, res, complex);
+ if (auto seq_mark = ov::as_type_ptr<SequenceMark>(input.get_node_shared_ptr())) {
+ return wrap_complex(context, seq_mark->get_sequence(), complex);
} else {
// Create FrameworkNode with UNWRAPPED input (transformations will see clean graph)
auto tuple_unpack_fw = std::make_shared<PtFrameworkNode>(context.get_decoder(),
diff --git a/src/frontends/pytorch/src/op_table.cpp b/src/frontends/pytorch/src/op_table.cpp
index 949cef046a1..421cc603b6a 100644
--- a/src/frontends/pytorch/src/op_table.cpp
+++ b/src/frontends/pytorch/src/op_table.cpp
@@ -40,7 +40,7 @@ OP_CONVERTER(translate_amax);
OP_CONVERTER(translate_amin);
OP_CONVERTER(translate_and);
OP_CONVERTER(translate_arange);
-OP_CONVERTER(translate_argmax);
+OP_CONVERTER(translate_append);
OP_CONVERTER(translate_argsort);
OP_CONVERTER(translate_argmax);
OP_CONVERTER(translate_argmin);
@@ -253,6 +253,7 @@ OP_CONVERTER(translate_sort);
OP_CONVERTER(translate_split_with_sizes);
OP_CONVERTER(translate_square);
OP_CONVERTER(translate_squeeze);
+OP_CONVERTER(translate_stack);
OP_CONVERTER(translate_std);
OP_CONVERTER(translate_std_mean);
OP_CONVERTER(translate_stft);
@@ -420,7 +421,7 @@ const std::unordered_map<std::string, CreatorFunction> get_supported_ops_ts() {
{"aten::aminmax", op::translate_aminmax},
{"aten::angle", common_translators::translate_angle},
{"aten::any", op::translate_any},
- // aten::append - Supported in limited set of patterns
+ {"aten::append", op::translate_append},
{"aten::arange", op::translate_arange},
{"aten::argmax", op::translate_argmax},
{"aten::argmin", op::translate_argmin},
@@ -734,7 +735,7 @@ const std::unordered_map<std::string, CreatorFunction> get_supported_ops_ts() {
{"aten::sqrt_", op::inplace_op<op::translate_1to1_match_1_inputs_with_fp32_type_alignment<opset10::Sqrt>>},
{"aten::square", op::translate_square},
{"aten::squeeze", op::quantizable_op<op::translate_squeeze>},
- // aten::stack - Supported in limited set of patterns
+ {"aten::stack", op::translate_stack},
{"aten::std", op::translate_std},
{"aten::std_mean", op::translate_std_mean},
{"aten::stft", op::translate_stft},
diff --git a/src/frontends/pytorch/src/transforms/append_list_unpack_replacer.cpp b/src/frontends/pytorch/src/transforms/append_list_unpack_replacer.cpp
index ba9aaf84401..7bfec85159e 100644
--- a/src/frontends/pytorch/src/transforms/append_list_unpack_replacer.cpp
+++ b/src/frontends/pytorch/src/transforms/append_list_unpack_replacer.cpp
@@ -33,7 +33,6 @@ AppendListUnpackReplacer::AppendListUnpackReplacer() {
ov::matcher_pass_callback callback = [](ov::pass::pattern::Matcher& m) {
auto list_unpack = m.get_match_root();
- OutputVector tmp_inputs;
NodeVector rt_copy_from;
auto input_node = list_unpack->input_value(0).get_node_shared_ptr();
@@ -44,25 +43,11 @@ AppendListUnpackReplacer::AppendListUnpackReplacer() {
input_node = getitem_node->input(0).get_source_output().get_node_shared_ptr();
}
- while (auto append_node = cast_fw_node(input_node, "aten::append")) {
- rt_copy_from.push_back(append_node);
- tmp_inputs.emplace_back(append_node->input(1).get_source_output());
- input_node = append_node->input(0).get_source_output().get_node_shared_ptr();
- }
- OutputVector inputs;
auto seq_mark = ov::as_type_ptr<SequenceMark>(input_node);
if (!seq_mark) {
return false;
}
- inputs.reserve(seq_mark->inputs().size() + tmp_inputs.size());
- rt_copy_from.push_back(seq_mark);
- for (auto& input : seq_mark->inputs()) {
- inputs.push_back(input.get_source_output());
- }
-
- inputs.insert(inputs.end(),
- std::make_move_iterator(tmp_inputs.rbegin()),
- std::make_move_iterator(tmp_inputs.rend()));
+ auto inputs = seq_mark->get_sequence();
if (getitem_node) {
// If aten::__getitem__, expect inputs to be equivalent of pytorch Tensor[][].
// Tensor selected by aten::__getitem__ index needs to be split along axis 0.
diff --git a/src/frontends/pytorch/src/transforms/aten_cat_replacer.cpp b/src/frontends/pytorch/src/transforms/aten_cat_replacer.cpp
deleted file mode 100644
index d1c8075c942..00000000000
--- a/src/frontends/pytorch/src/transforms/aten_cat_replacer.cpp
+++ /dev/null
@@ -1,244 +0,0 @@
-// Copyright (C) 2018-2026 Intel Corporation
-// SPDX-License-Identifier: Apache-2.0
-//
-
-#include "aten_cat_replacer.hpp"
-
-#include <memory>
-#include <utility>
-
-#include "openvino/core/graph_util.hpp"
-#include "openvino/core/rt_info.hpp"
-#include "openvino/core/validation_util.hpp"
-#include "openvino/frontend/sequence_mark.hpp"
-#include "openvino/op/concat.hpp"
-#include "openvino/op/constant.hpp"
-#include "openvino/op/loop.hpp"
-#include "openvino/op/unsqueeze.hpp"
-#include "openvino/op/util/framework_node.hpp"
-#include "openvino/pass/pattern/matcher.hpp"
-#include "openvino/pass/pattern/op/wrap_type.hpp"
-#include "utils.hpp"
-#include "utils_quantize.hpp"
-
-namespace ov {
-namespace frontend {
-namespace pytorch {
-namespace pass {
-
-using namespace ov::op;
-
-namespace {
-bool process_loop_case(std::shared_ptr<Node> cat, std::shared_ptr<v5::Loop> loop, int64_t axis, bool is_stack) {
- // Concatenation of the list happens inside Loop operation
- // prim::ListConstruct -> Loop [Parameter -> prim::append -> Result] -> aten::cat
- // We recreate the Loop to remove the original merged output and create new output using get_concatenated_slices
- // Also we remove original input which was prim::ListConstruct
- auto body = loop->get_function();
- auto output_index = cat->input(0).get_source_output().get_index();
-
- int64_t body_result_index = -1;
- for (const auto& desc : loop->get_output_descriptions()) {
- if (desc->m_output_index == output_index) {
- body_result_index = static_cast<int64_t>(desc->m_body_value_index);
- break;
- }
- }
- FRONT_END_GENERAL_CHECK(body_result_index >= 0, "Couldn't find descriptor for output.");
-
- auto body_result = body->get_results()[body_result_index];
- auto append = cast_fw_node(body_result->get_input_node_shared_ptr(0), "aten::append");
- if (!append) {
- add_exception_to_fw_node(cat, "<aten/quantized>::cat unsupported case: aten::append not found in Loop body.");
- return false;
- }
-
- auto param = ov::as_type_ptr<v0::Parameter>(append->get_input_node_shared_ptr(0));
- if (!param) {
- add_exception_to_fw_node(cat,
- "<aten/quantized>::cat unsupported case: aten::append input is not a body parameter.");
- return false;
- }
-
- auto body_param_index = body->get_parameter_index(param);
- FRONT_END_GENERAL_CHECK(body_param_index >= 0, "Couldn't find parameter in body parameters.");
-
- int64_t input_index = -1;
- for (const auto& desc : loop->get_input_descriptions()) {
- if (desc->m_body_parameter_index == static_cast<size_t>(body_param_index)) {
- input_index = static_cast<int64_t>(desc->m_input_index);
- break;
- }
- }
- FRONT_END_GENERAL_CHECK(input_index >= 0, "Couldn't find descriptor for input.");
-
- auto input_node = loop->get_input_node_shared_ptr(input_index);
- // Check for SequenceMark - it should be empty as the list is built inside the loop via append
- auto seq_mark_list = ov::as_type_ptr<SequenceMark>(input_node);
-
- if (!seq_mark_list || !seq_mark_list->empty()) {
- add_exception_to_fw_node(cat, "<aten/quantized>::cat unsupported case: expected empty SequenceMark.");
- return false;
- }
-
- // Filter output descriptions
- std::vector<std::shared_ptr<ov::op::util::MultiSubGraphOp::OutputDescription>> new_output_descs;
- for (const auto& desc : loop->get_output_descriptions()) {
- if (desc->m_body_value_index != static_cast<size_t>(body_result_index)) {
- new_output_descs.push_back(desc);
- }
- }
-
- // Filter input descriptions
- std::vector<std::shared_ptr<ov::op::util::MultiSubGraphOp::InputDescription>> new_input_descs;
- int64_t input_idx = -1;
- for (const auto& desc : loop->get_input_descriptions()) {
- if (desc->m_body_parameter_index != static_cast<size_t>(body_param_index)) {
- new_input_descs.push_back(desc);
- } else {
- input_idx = static_cast<int64_t>(desc->m_input_index);
- }
- }
- FRONT_END_GENERAL_CHECK(input_idx >= 0, "Input description for body parameter not found.");
-
- // Update inputs
- OutputVector new_inputs;
- for (size_t i = 0; i < loop->get_input_size(); ++i) {
- if (static_cast<int64_t>(i) != input_idx) {
- new_inputs.push_back(loop->input_value(i));
- }
- }
-
- // Update body
- body->remove_result(body_result);
- for (auto& desc : new_output_descs) {
- if (desc->m_body_value_index > static_cast<size_t>(body_result_index))
- desc->m_body_value_index--;
- if (desc->m_output_index > output_index)
- desc->m_output_index--;
- }
- body->remove_parameter(param);
- for (auto& desc : new_input_descs) {
- if (desc->m_body_parameter_index > static_cast<size_t>(body_param_index))
- desc->m_body_parameter_index--;
- if (desc->m_input_index > static_cast<size_t>(input_index))
- desc->m_input_index--;
- }
-
- // Create new loop
- auto new_loop = std::make_shared<v5::Loop>();
- new_loop->set_special_body_ports(loop->get_special_body_ports());
- new_loop->set_arguments(new_inputs);
- new_loop->set_friendly_name(loop->get_friendly_name());
- new_loop->set_function(loop->get_function());
- new_loop->set_input_descriptions(0, new_input_descs);
- new_loop->set_output_descriptions(0, new_output_descs);
- new_loop->set_output_size(loop->get_output_size() - 1);
-
- // Update output mappings
- for (size_t i = 0; i < loop->get_output_size() - 1; ++i) {
- if (i < output_index) {
- replace_output_update_name(loop->output(i), new_loop->output(i));
- } else if (i > output_index) {
- replace_output_update_name(loop->output(i + 1), new_loop->output(i));
- }
- }
-
- // Handle stack case and create new result
- auto to_append = append->input_value(1);
- if (is_stack) {
- auto axis_constant = v0::Constant::create(element::i32, Shape{}, {axis});
- to_append = std::make_shared<v0::Unsqueeze>(to_append, axis_constant);
- }
- auto new_result = std::make_shared<v0::Result>(to_append);
- body->add_results({new_result});
- auto new_output = new_loop->get_concatenated_slices(new_result, 0, 1, 1, -1, axis);
- copy_runtime_info({loop, cat}, new_loop);
- cat->output(0).replace(new_output);
-
- return true;
-}
-} // namespace
-
-// aten::cat needs a special handling since it takes a Tensor[] as input. We set the inputs of ListConstruct as the
-// inputs of cat.
-//
-// Pytorch IR: OV model:
-// %a %b %c %dim %a %b %c
-// \ | / | \ | /
-// prim::ListConstruct prim::Constant Concat[axis=%dim]
-// \ /
-// aten::cat
-AtenCatToConcat::AtenCatToConcat() {
- auto aten_cat = ov::pass::pattern::wrap_type<ov::op::util::FrameworkNode>(
- fw_node_predicate({"aten::cat", "aten::concat", "aten::concatenate", "quantized::cat", "aten::stack"}));
-
- ov::matcher_pass_callback callback = [](ov::pass::pattern::Matcher& m) {
- const auto root = m.get_match_root();
- bool is_stack = cast_fw_node(root, "aten::stack") != nullptr;
- auto cat = ov::as_type_ptr<ov::op::util::FrameworkNode>(root);
- if (!cat)
- return false;
-
- int64_t axis;
- if (cat->get_input_size() > 1) {
- auto axis_const = ov::util::get_constant_from_source(cat->input_value(1));
- if (!axis_const) {
- add_exception_to_fw_node(cat, "<aten/quantized>::cat unsupported case: axis is not a constant.");
- return false;
- }
- auto _axis = axis_const->cast_vector<int64_t>();
- if (_axis.size() != 1) {
- add_exception_to_fw_node(cat, "<aten/quantized>::cat unsupported case: axis is not a scalar.");
- return false;
- }
- axis = _axis[0];
- } else {
- const auto& attrs = cat->get_attrs();
- if (attrs.find("axis") == attrs.end()) {
- add_exception_to_fw_node(cat, "<aten/quantized>::cat unsupported case: axis not found in attributes.");
- return false;
- }
- axis = std::stoll(attrs.at("axis"));
- }
-
- std::shared_ptr<Node> input_node = cat->get_input_node_shared_ptr(0);
- if (auto loop = ov::as_type_ptr<v5::Loop>(input_node)) {
- return process_loop_case(cat, loop, axis, is_stack);
- }
-
- if (is_stack) {
- // Special case for GPTQ pattern
- if (const auto& compression = u4_compression_stack(input_node->input_values(), axis)) {
- copy_runtime_info_and_name(cat, {compression}, {input_node});
- replace_node(cat, compression);
- return true;
- }
- }
-
- const auto&& tmp_inputs = get_list_as_outputs(cat->get_input_source_output(0));
- OutputVector concat_inputs;
- if (is_stack) {
- auto axis_to_unsqueeze = v0::Constant::create(element::i32, Shape{}, {axis});
- for (const auto& list_input : tmp_inputs) {
- auto unsqueezed_node = std::make_shared<v0::Unsqueeze>(list_input, axis_to_unsqueeze);
- concat_inputs.push_back(unsqueezed_node);
- }
- } else {
- concat_inputs = OutputVector(tmp_inputs.begin(), tmp_inputs.end());
- }
- auto result = std::make_shared<v0::Concat>(concat_inputs, axis);
- copy_runtime_info_and_name(cat, {result});
- replace_node(cat, result);
-
- return true;
- };
-
- auto m = std::make_shared<ov::pass::pattern::Matcher>(aten_cat, "ov::frontend::pytorch::pass::AtenCatToConcat");
- this->register_matcher(m, callback);
-};
-
-} // namespace pass
-} // namespace pytorch
-} // namespace frontend
-} // namespace ov
diff --git a/src/frontends/pytorch/src/transforms/aten_cat_replacer.hpp b/src/frontends/pytorch/src/transforms/aten_cat_replacer.hpp
deleted file mode 100644
index b8f3c90a0e6..00000000000
--- a/src/frontends/pytorch/src/transforms/aten_cat_replacer.hpp
+++ /dev/null
@@ -1,25 +0,0 @@
-// Copyright (C) 2018-2026 Intel Corporation
-// SPDX-License-Identifier: Apache-2.0
-//
-
-#pragma once
-
-#include "openvino/pass/graph_rewrite.hpp"
-#include "openvino/pass/pass.hpp"
-
-namespace ov {
-namespace frontend {
-namespace pytorch {
-namespace pass {
-
-// This transformation replaces pattern prim::ListConstruct->aten::append{none or many}->aten::cat
-class AtenCatToConcat : public ov::pass::MatcherPass {
-public:
- OPENVINO_MATCHER_PASS_RTTI("ov::frontend::pytorch::pass::AtenCatToConcat");
- AtenCatToConcat();
-};
-
-} // namespace pass
-} // namespace pytorch
-} // namespace frontend
-} // namespace ov
diff --git a/src/frontends/pytorch/src/transforms/prim_list_unpack_replacer.cpp b/src/frontends/pytorch/src/transforms/prim_list_unpack_replacer.cpp
index 83a4d7746d9..6c2080b7683 100644
--- a/src/frontends/pytorch/src/transforms/prim_list_unpack_replacer.cpp
+++ b/src/frontends/pytorch/src/transforms/prim_list_unpack_replacer.cpp
@@ -332,10 +332,8 @@ PrimListUnpackReplacer::PrimListUnpackReplacer() {
return true;
}
- // Check for SequenceMark - if it is, we can directly use its elements
if (auto seq_mark = ov::as_type_ptr<SequenceMark>(input_node)) {
auto outputs = seq_mark->get_sequence();
- copy_runtime_info_and_name(list_unpack, {seq_mark}, {input_node});
replace_node(list_unpack, outputs);
return true;
}
diff --git a/src/frontends/pytorch/src/transforms/sequence_mark_replacer.cpp b/src/frontends/pytorch/src/transforms/sequence_mark_replacer.cpp
index 79878788c41..9ce7579ecd3 100644
--- a/src/frontends/pytorch/src/transforms/sequence_mark_replacer.cpp
+++ b/src/frontends/pytorch/src/transforms/sequence_mark_replacer.cpp
@@ -31,7 +31,9 @@ SequenceMarkReplacer::SequenceMarkReplacer() {
return false;
}
- if (seq_mark_node->get_input_size() == 0) {
+ const auto inputs = seq_mark_node->get_sequence();
+
+ if (inputs.empty()) {
return false;
}
@@ -41,7 +43,7 @@ SequenceMarkReplacer::SequenceMarkReplacer() {
// Concatenate all inputs reshaped to 1D
OutputVector inputs_to_concat;
- for (const auto& input : seq_mark_node->input_values()) {
+ for (const auto& input : inputs) {
const auto& input_rank = input.get_partial_shape().rank();
if (input_rank.is_static() && input_rank.get_length() > 1) {
diff --git a/src/frontends/pytorch/src/utils.cpp b/src/frontends/pytorch/src/utils.cpp
index ad7d0ef8673..f081c045eaf 100644
--- a/src/frontends/pytorch/src/utils.cpp
+++ b/src/frontends/pytorch/src/utils.cpp
@@ -651,32 +651,18 @@ std::deque<Output<Node>> get_list_as_outputs(const Output<Node>& start, bool uns
!ov::as_type_ptr<v5::Loop>(current_output.get_node_shared_ptr()),
"List is concatenated using loop. This case should be handled by a specific transformation.");
- // Helper to prepend SequenceMark inputs - iterate in reverse with push_front to preserve order
- auto prepend_seq_mark_inputs = [&res, &zero, unsqueeze_for_concat](const std::shared_ptr<SequenceMark>& seq_mark) {
- const auto& inputs = seq_mark->inputs();
- for (auto it = inputs.rbegin(); it != inputs.rend(); ++it) {
- auto elem = it->get_source_output();
- if (unsqueeze_for_concat) {
- elem = std::make_shared<v0::Unsqueeze>(elem, zero);
- }
- res.push_front(elem);
- }
- };
-
- // First check if it's a SequenceMark - just return its inputs in order
+ // Fast path: SequenceMark with get_sequence() handles SequenceInsert chains internally
if (auto seq_mark = ov::as_type_ptr<SequenceMark>(current_output.get_node_shared_ptr())) {
- // For direct SequenceMark, iterate in reverse with push_front to preserve order
- const auto& inputs = seq_mark->inputs();
- for (auto it = inputs.rbegin(); it != inputs.rend(); ++it) {
- auto elem = it->get_source_output();
+ for (auto& elem : seq_mark->get_sequence()) {
if (unsqueeze_for_concat) {
elem = std::make_shared<v0::Unsqueeze>(elem, zero);
}
- res.push_front(elem);
+ res.push_back(elem);
}
return res;
}
+ // Legacy path: walk aten::append / aten::add FrameworkNodes
while (const auto& fw_node = ov::as_type_ptr<ov::op::util::FrameworkNode>(current_output.get_node_shared_ptr())) {
const auto& attrs = fw_node->get_attrs();
const auto op_type_it = attrs.find(PtFrameworkNode::op_type_key);
@@ -704,7 +690,14 @@ std::deque<Output<Node>> get_list_as_outputs(const Output<Node>& start, bool uns
// Check for SequenceMark at the end of chain - prepend its elements
if (auto seq_mark = ov::as_type_ptr<SequenceMark>(current_output.get_node_shared_ptr())) {
- prepend_seq_mark_inputs(seq_mark);
+ const auto& inputs = seq_mark->inputs();
+ for (auto it = inputs.rbegin(); it != inputs.rend(); ++it) {
+ auto elem = it->get_source_output();
+ if (unsqueeze_for_concat) {
+ elem = std::make_shared<v0::Unsqueeze>(elem, zero);
+ }
+ res.push_front(elem);
+ }
} else {
res.push_front(current_output);
}
diff --git a/tests/layer_tests/pytorch_tests/test_cat.py b/tests/layer_tests/pytorch_tests/test_cat.py
index c427147aa84..8d23fdb465a 100644
--- a/tests/layer_tests/pytorch_tests/test_cat.py
+++ b/tests/layer_tests/pytorch_tests/test_cat.py
@@ -122,7 +122,7 @@ class TestCat(PytorchLayerTest):
@pytest.mark.nightly
@pytest.mark.precommit
- @pytest.mark.parametrize("out", [False, pytest.param(True, marks=pytest.mark.xfail(reason="out case is not supported"))])
+ @pytest.mark.parametrize("out", [False, True])
def test_loop_append_cat(self, out, ie_device, precision, ir_version):
model = aten_loop_append_cat() if not out else aten_loop_append_cat_out()
self._test(model, ["aten::cat", "aten::append", "prim::ListConstruct", "prim::Loop"],