Skip to content

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

[ONNX FE] Lower loop-carried sequence patterns: SequenceIfReplacer + SequenceArrayLowering (#36445)

Maxim Vafin4a1870723b4b
diff --git a/src/frontends/common/include/openvino/frontend/sequence_mark.hpp b/src/frontends/common/include/openvino/frontend/sequence_mark.hpp
index 6132176c98f..1b966f5e8d6 100644
--- a/src/frontends/common/include/openvino/frontend/sequence_mark.hpp
+++ b/src/frontends/common/include/openvino/frontend/sequence_mark.hpp
@@ -26,8 +26,13 @@ public:
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.
+ /// \brief Returns all sequence elements of this SequenceMark, flattening any
+ /// SequenceInsert / SequenceErase chain (with statically known positions)
+ /// and unwrapping Identity passthrough. A directly nested SequenceMark input
+ /// is kept as a single opaque element, preserving the index->element mapping
+ /// expected by tuple/list unpack and getitem. An Insert/Erase with a
+ /// non-constant position, or a producer that carries a sequence across a
+ /// Loop/If boundary, is also treated as a single opaque element.
ov::OutputVector get_sequence() const;
};
diff --git a/src/frontends/common/src/sequence_mark.cpp b/src/frontends/common/src/sequence_mark.cpp
index dd7c3cfffc9..0eb6576991c 100644
--- a/src/frontends/common/src/sequence_mark.cpp
+++ b/src/frontends/common/src/sequence_mark.cpp
@@ -4,11 +4,127 @@
#include "openvino/frontend/sequence_mark.hpp"
+#include <optional>
+
+#include "openvino/core/validation_util.hpp"
+#include "openvino/frontend/sequence_erase.hpp"
#include "openvino/frontend/sequence_insert.hpp"
+#include "openvino/op/identity.hpp"
+#include "openvino/util/log.hpp"
namespace ov {
namespace frontend {
+namespace {
+
+ov::Output<ov::Node> unwrap_identity(const ov::Output<ov::Node>& value) {
+ ov::Output<ov::Node> cur = value;
+ while (auto identity = ov::as_type_ptr<ov::op::v16::Identity>(cur.get_node_shared_ptr())) {
+ cur = identity->input_value(0);
+ }
+ return cur;
+}
+
+// Resolve a statically known sequence position into an index. A negative
+// position counts from the back (Python list semantics): index == size + pos.
+// `size_bias` is 1 for insert (append at index == size is valid) and 0 for
+// erase. Returns nullopt when the position is dynamic or out of range.
+std::optional<size_t> static_position(const ov::Output<ov::Node>& position, size_t size, int64_t size_bias) {
+ auto pc = ov::util::get_constant_from_source(position);
+ if (!pc) {
+ return std::nullopt;
+ }
+ const auto values = pc->cast_vector<int64_t>();
+ if (values.size() != 1) {
+ return std::nullopt;
+ }
+ int64_t pos = values[0];
+ if (pos < 0) {
+ pos += static_cast<int64_t>(size);
+ }
+ if (pos < 0 || pos >= static_cast<int64_t>(size) + size_bias) {
+ return std::nullopt;
+ }
+ return static_cast<size_t>(pos);
+}
+
+void enumerate_sequence(const ov::Output<ov::Node>& value, ov::OutputVector& out, int depth) {
+ if (depth > 256) {
+ // Recursion guard against pathological chains. Collapsing to one opaque
+ // slot here undercounts a genuinely long Insert/Erase chain, so surface
+ // it: a >256-deep sequence chain points at an unhandled pattern rather
+ // than a real stack-depth risk.
+ OPENVINO_DEBUG("SequenceMark::get_sequence: sequence chain exceeds depth 256; element count may be "
+ "undercounted.");
+ out.push_back(value);
+ return;
+ }
+ const auto v = unwrap_identity(value);
+ const auto node = v.get_node_shared_ptr();
+ if (auto mark = ov::as_type_ptr<SequenceMark>(node)) {
+ for (size_t i = 0; i < mark->get_input_size(); ++i) {
+ const auto in = mark->input_value(i);
+ const auto in_node = unwrap_identity(in).get_node_shared_ptr();
+ // Flatten only SequenceInsert/SequenceErase chains. A directly
+ // nested SequenceMark represents an inline nested list/tuple
+ // construct (e.g. PyTorch builds nested SequenceMarks); it must stay
+ // a single opaque element so the returned element count and
+ // index->element mapping keep matching context.get_output_size().
+ if (ov::is_type<SequenceInsert>(in_node) || ov::is_type<SequenceErase>(in_node)) {
+ enumerate_sequence(in, out, depth + 1);
+ } else {
+ out.push_back(in);
+ }
+ }
+ return;
+ }
+ if (auto ins = ov::as_type_ptr<SequenceInsert>(node)) {
+ ov::OutputVector base;
+ enumerate_sequence(ins->get_input_sequence(), base, depth + 1);
+ size_t pos = base.size(); // default (no position): append at end
+ if (ins->has_position()) {
+ auto resolved = static_position(ins->get_position(), base.size(), /*size_bias=*/1);
+ if (!resolved) {
+ // Non-constant (or out-of-range) position: the spliced index is
+ // not statically known, so keep the whole SequenceInsert as a
+ // single opaque element (documented contract). Downstream passes
+ // resolve such dynamic positions structurally (Select chains) or
+ // leave the reader unconverted.
+ out.push_back(v);
+ return;
+ }
+ pos = *resolved;
+ }
+ base.insert(base.begin() + static_cast<long>(pos), ins->get_tensor());
+ out.insert(out.end(), base.begin(), base.end());
+ return;
+ }
+ if (auto era = ov::as_type_ptr<SequenceErase>(node)) {
+ ov::OutputVector base;
+ enumerate_sequence(era->get_input_sequence(), base, depth + 1);
+ if (!base.empty()) {
+ size_t pos = base.size() - 1; // default (no position): erase last
+ if (era->has_position()) {
+ auto resolved = static_position(era->get_position(), base.size(), /*size_bias=*/0);
+ if (!resolved) {
+ // Non-constant (or out-of-range) position: keep the whole
+ // SequenceErase as a single opaque element (documented
+ // contract) rather than guessing erase-last.
+ out.push_back(v);
+ return;
+ }
+ pos = *resolved;
+ }
+ base.erase(base.begin() + static_cast<long>(pos));
+ }
+ out.insert(out.end(), base.begin(), base.end());
+ return;
+ }
+ out.push_back(v);
+}
+
+} // namespace
+
SequenceMark::SequenceMark(const ov::OutputVector& inputs) : ov::op::util::FrameworkNode(inputs, 1) {
validate_and_infer_types();
}
@@ -63,28 +179,10 @@ ov::Output<ov::Node> SequenceMark::get_element(size_t index) const {
}
ov::OutputVector SequenceMark::get_sequence() const {
- // 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());
+ ov::OutputVector result;
+ // Enumeration is read-only; const_pointer_cast just adapts shared_from_this()
+ // to the Output<Node> the enumerator expects.
+ enumerate_sequence({std::const_pointer_cast<ov::Node>(shared_from_this()), 0}, result, 0);
return result;
}
diff --git a/src/frontends/common_translators/include/sequence_array_lowering.hpp b/src/frontends/common_translators/include/sequence_array_lowering.hpp
new file mode 100644
index 00000000000..9cf01b0e883
--- /dev/null
+++ b/src/frontends/common_translators/include/sequence_array_lowering.hpp
@@ -0,0 +1,47 @@
+// Copyright (C) 2018-2026 Intel Corporation
+// SPDX-License-Identifier: Apache-2.0
+//
+
+#pragma once
+
+#include "openvino/pass/pass.hpp"
+
+namespace ov {
+namespace frontend {
+namespace pass {
+
+/// \brief Lowers loop-carried "sequence-of-N" patterns into N parallel tensors.
+///
+/// This pass complements SequenceIfReplacer by handling the cases that
+/// SequenceIfReplacer cannot resolve directly — typically a loop-carried
+/// sequence seeded from an empty SequenceMark and built/passed through on the
+/// first iteration via an If(first_iter) branch. The classic instance is a
+/// past-key/value cache: an outer empty sequence flows into a Loop body whose
+/// body uses an If to either build a fresh length-N SequenceMark (iter 0) or
+/// pass through the loop-carried Parameter (iter > 0).
+///
+/// Lowering principle: when a sequence has statically discoverable length N
+/// and uniform per-slot shape/dtype, and all index/position operands of the
+/// SequenceAt / SequenceInsert / SequenceErase helpers in its def-use closure
+/// are compile-time constants, the sequence is rewritten as N parallel
+/// tensor edges. Helper ops become slot-level operations:
+/// SequenceMark(t_0..t_{N-1}) -> the N tensors
+/// SequenceAt(seq, k) -> seq.slots[k]
+/// SequenceInsert(seq, v, pos)-> slots[:pos] + [v] + slots[pos:]
+/// SequenceErase(seq, pos) -> slots with element pos removed
+/// SequenceLength(seq) -> Constant<i64>(N)
+/// MultiSubGraphOp (Loop / If) inputs and outputs carrying a sequence are
+/// replaced with N parallel tensor inputs/outputs.
+///
+/// Conservative by design: any candidate that fails a precondition is left
+/// unmodified so the universal unconverted-ops report can flag it.
+class SequenceArrayLowering : public ov::pass::ModelPass {
+public:
+ OPENVINO_MODEL_PASS_RTTI("ov::frontend::pass::SequenceArrayLowering");
+
+ bool run_on_model(const std::shared_ptr<ov::Model>& model) override;
+};
+
+} // namespace pass
+} // namespace frontend
+} // namespace ov
diff --git a/src/frontends/common_translators/include/sequence_if_replacer.hpp b/src/frontends/common_translators/include/sequence_if_replacer.hpp
new file mode 100644
index 00000000000..185e2fad054
--- /dev/null
+++ b/src/frontends/common_translators/include/sequence_if_replacer.hpp
@@ -0,0 +1,31 @@
+// Copyright (C) 2018-2026 Intel Corporation
+// SPDX-License-Identifier: Apache-2.0
+//
+
+#pragma once
+
+#include "openvino/pass/pass.hpp"
+
+namespace ov {
+namespace frontend {
+namespace pass {
+
+/// \brief Resolves SequenceAt / SequenceLength / SequenceErase helper operations.
+///
+/// Handles two patterns:
+/// 1. Helper applied directly to a SequenceMark / SequenceInsert chain - resolved
+/// by indexing / counting / removing from the chain.
+/// 2. Helper applied to an output of an ov::op::v8::If whose corresponding Result
+/// in both branches feeds from a SequenceMark / SequenceInsert chain - the
+/// helper is pushed into the If by adding new tensor-typed outputs.
+///
+/// Iterates to fixpoint to handle nested If patterns.
+class SequenceIfReplacer : public ov::pass::ModelPass {
+public:
+ OPENVINO_MODEL_PASS_RTTI("ov::frontend::pass::SequenceIfReplacer");
+ bool run_on_model(const std::shared_ptr<ov::Model>& model) override;
+};
+
+} // namespace pass
+} // namespace frontend
+} // namespace ov
diff --git a/src/frontends/common_translators/src/sequence_array_lowering.cpp b/src/frontends/common_translators/src/sequence_array_lowering.cpp
new file mode 100644
index 00000000000..1b778890493
--- /dev/null
+++ b/src/frontends/common_translators/src/sequence_array_lowering.cpp
@@ -0,0 +1,593 @@
+// Copyright (C) 2018-2026 Intel Corporation
+// SPDX-License-Identifier: Apache-2.0
+//
+
+#include "sequence_array_lowering.hpp"
+
+#include <functional>
+#include <map>
+#include <numeric>
+#include <vector>
+
+#include "openvino/core/model.hpp"
+#include "openvino/core/validation_util.hpp"
+#include "openvino/frontend/sequence_at.hpp"
+#include "openvino/frontend/sequence_erase.hpp"
+#include "openvino/frontend/sequence_insert.hpp"
+#include "openvino/frontend/sequence_length.hpp"
+#include "openvino/frontend/sequence_mark.hpp"
+#include "openvino/op/concat.hpp"
+#include "openvino/op/constant.hpp"
+#include "openvino/op/convert.hpp"
+#include "openvino/op/equal.hpp"
+#include "openvino/op/gather.hpp"
+#include "openvino/op/identity.hpp"
+#include "openvino/op/if.hpp"
+#include "openvino/op/less.hpp"
+#include "openvino/op/loop.hpp"
+#include "openvino/op/parameter.hpp"
+#include "openvino/op/reduce_prod.hpp"
+#include "openvino/op/reshape.hpp"
+#include "openvino/op/result.hpp"
+#include "openvino/op/select.hpp"
+#include "openvino/op/shape_of.hpp"
+#include "openvino/op/squeeze.hpp"
+#include "openvino/op/unsqueeze.hpp"
+#include "openvino/op/util/multi_subgraph_base.hpp"
+#include "openvino/op/util/sub_graph_base.hpp"
+#include "openvino/util/log.hpp"
+#include "slot_resolver.hpp"
+
+using namespace ov::op;
+
+namespace ov {
+namespace frontend {
+namespace pass {
+namespace sal_detail {
+
+namespace {
+
+bool is_sequence_helper(const std::shared_ptr<ov::Node>& node) {
+ return ov::is_type<ov::frontend::SequenceMark>(node) || ov::is_type<ov::frontend::SequenceInsert>(node) ||
+ ov::is_type<ov::frontend::SequenceErase>(node) || ov::is_type<ov::frontend::SequenceAt>(node) ||
+ ov::is_type<ov::frontend::SequenceLength>(node);
+}
+
+void collect_helpers_recursive(const std::shared_ptr<ov::Model>& m, std::vector<std::shared_ptr<ov::Node>>& out) {
+ if (!m) {
+ return;
+ }
+ for (const auto& n : m->get_ordered_ops()) {
+ if (is_sequence_helper(n)) {
+ out.push_back(n);
+ }
+ if (auto msg = ov::as_type_ptr<ov::op::util::MultiSubGraphOp>(n)) {
+ for (size_t i = 0; i < msg->get_internal_subgraphs_size(); ++i) {
+ collect_helpers_recursive(msg->get_function(i), out);
+ }
+ }
+ }
+}
+
+// True if model (recursively) contains SequenceAt or SequenceLength.
+bool model_has_sequence_reader(const std::shared_ptr<ov::Model>& m) {
+ if (!m) {
+ return false;
+ }
+ for (const auto& n : m->get_ordered_ops()) {
+ if (ov::is_type<ov::frontend::SequenceAt>(n) || ov::is_type<ov::frontend::SequenceLength>(n)) {
+ return true;
+ }
+ if (auto msg = ov::as_type_ptr<ov::op::util::MultiSubGraphOp>(n)) {
+ for (size_t i = 0; i < msg->get_internal_subgraphs_size(); ++i) {
+ if (model_has_sequence_reader(msg->get_function(i))) {
+ return true;
+ }
+ }
+ }
+ }
+ return false;
+}
+
+bool produces_sequence_helper_value(const ov::Output<ov::Node>& value) {
+ auto u = unwrap_identity(value);
+ auto n = u.get_node_shared_ptr();
+ return ov::is_type<ov::frontend::SequenceMark>(n) || ov::is_type<ov::frontend::SequenceInsert>(n) ||
+ ov::is_type<ov::frontend::SequenceErase>(n);
+}
+
+// Apply fn(model) to every model in the subgraph tree, post-order (children before parent).
+template <typename Fn>
+void for_each_model_postorder(const std::shared_ptr<ov::Model>& m, Fn&& fn) {
+ if (!m) {
+ return;
+ }
+ for (const auto& n : m->get_ordered_ops()) {
+ if (auto msg = ov::as_type_ptr<ov::op::util::MultiSubGraphOp>(n)) {
+ for (size_t i = 0; i < msg->get_internal_subgraphs_size(); ++i) {
+ for_each_model_postorder(msg->get_function(i), fn);
+ }
+ }
+ }
+ fn(m);
+}
+
+// Disconnect body Results that still source sequence helpers from back-edges.
+void disconnect_dead_sequence_back_edges(const std::shared_ptr<ov::Model>& root) {
+ for_each_model_postorder(root, [&](const std::shared_ptr<ov::Model>& m) {
+ for (const auto& n : m->get_ordered_ops()) {
+ auto msg = ov::as_type_ptr<ov::op::util::MultiSubGraphOp>(n);
+ if (!msg) {
+ continue;
+ }
+ for (size_t b = 0; b < msg->get_internal_subgraphs_size(); ++b) {
+ auto body = msg->get_function(b);
+ if (!body) {
+ continue;
+ }
+ const auto& body_results = body->get_results();
+ std::map<size_t, std::shared_ptr<v0::Parameter>> merged_result_to_param;
+ for (const auto& d : msg->get_input_descriptions(static_cast<int>(b))) {
+ if (auto merged = ov::as_type_ptr<ov::op::util::MultiSubGraphOp::MergedInputDescription>(d)) {
+ if (merged->m_body_value_index < body_results.size() &&
+ merged->m_body_parameter_index < body->get_parameters().size()) {
+ merged_result_to_param[merged->m_body_value_index] =
+ body->get_parameters()[merged->m_body_parameter_index];
+ }
+ }
+ }
+ for (size_t r_idx = 0; r_idx < body_results.size(); ++r_idx) {
+ auto& result = body_results[r_idx];
+ auto src = result->input_value(0);
+ if (!produces_sequence_helper_value(src)) {
+ continue;
+ }
+ auto merged_it = merged_result_to_param.find(r_idx);
+ if (merged_it != merged_result_to_param.end()) {
+ // Skip if the merged Parameter still has live (non-Result) consumers.
+ const auto& param_out = merged_it->second->output(0);
+ size_t live_consumers = 0;
+ for (const auto& tgt : param_out.get_target_inputs()) {
+ if (!ov::is_type<v0::Result>(tgt.get_node())) {
+ ++live_consumers;
+ }
+ }
+ if (live_consumers > 0) {
+ continue; // back-edge is live; leave in place
+ }
+ result->input(0).replace_source_output(param_out);
+ continue;
+ }
+ // For a BodyOutput (non-merged), replace with a shape-compatible
+ // zero seed derived from the sibling branch's result.
+ int64_t out_idx_for_r = -1;
+ for (const auto& d : msg->get_output_descriptions(static_cast<int>(b))) {
+ if (d->m_body_value_index == r_idx) {
+ out_idx_for_r = static_cast<int64_t>(d->m_output_index);
+ break;
+ }
+ }
+ ov::Output<ov::Node> sibling_src;
+ if (out_idx_for_r >= 0) {
+ for (size_t bb = 0; bb < msg->get_internal_subgraphs_size(); ++bb) {
+ if (bb == b) {
+ continue;
+ }
+ auto sib_body = msg->get_function(bb);
+ if (!sib_body) {
+ continue;
+ }
+ for (const auto& d : msg->get_output_descriptions(static_cast<int>(bb))) {
+ if (static_cast<int64_t>(d->m_output_index) != out_idx_for_r) {
+ continue;
+ }
+ const auto& sib_results = sib_body->get_results();
+ if (d->m_body_value_index >= sib_results.size()) {
+ continue;
+ }
+ auto candidate = sib_results[d->m_body_value_index]->input_value(0);
+ if (produces_sequence_helper_value(candidate)) {
+ continue;
+ }
+ sibling_src = candidate;
+ break;
+ }
+ if (sibling_src.get_node_shared_ptr()) {
+ break;
+ }
+ }
+ }
+ ov::Output<ov::Node> dummy;
+ if (sibling_src.get_node_shared_ptr()) {
+ const auto& tps = sibling_src.get_partial_shape();
+ auto et = sibling_src.get_element_type();
+ if (et == ov::element::dynamic) {
+ et = src.get_element_type();
+ }
+ if (et == ov::element::dynamic && out_idx_for_r >= 0) {
+ et = msg->output(static_cast<size_t>(out_idx_for_r)).get_element_type();
+ }
+ if (et == ov::element::dynamic) {
+ et = ov::element::f32;
+ }
+ dummy = make_growable_seed(tps, et);
+ } else {
+ dummy = v0::Constant::create(ov::element::f32, ov::Shape{}, {0.0f})->output(0);
+ }
+ result->input(0).replace_source_output(dummy);
+ }
+ }
+ }
+ });
+}
+
+// Detach dead sequence helpers by replacing their inputs with Constants.
+void disconnect_dead_sequence_helpers(const std::shared_ptr<ov::Model>& root) {
+ for_each_model_postorder(root, [&](const std::shared_ptr<ov::Model>& m) {
+ bool progress = true;
+ while (progress) {
+ progress = false;
+ for (const auto& n : m->get_ordered_ops()) {
+ if (!is_sequence_helper(n)) {
+ continue;
+ }
+ if (!n->output(0).get_target_inputs().empty()) {
+ continue;
+ }
+ if (n->get_input_size() == 0) {
+ continue;
+ }
+ for (size_t i = 0; i < n->get_input_size(); ++i) {
+ auto src = n->input_value(i);
+ if (ov::is_type<v0::Constant>(src.get_node_shared_ptr())) {
+ continue;
+ }
+ auto et = src.get_element_type();
+ if (et.is_dynamic()) {
+ et = ov::element::i64;
+ }
+ auto c = v0::Constant::create(et, ov::Shape{}, std::vector<int64_t>{0});
+ n->input(i).replace_source_output(c);
+ progress = true;
+ }
+ }
+ }
+ });
+}
+
+// Fix If branches where one returns rank-0 and another returns rank-N for the same output.
+void align_if_branch_result_ranks(const std::shared_ptr<ov::Model>& root) {
+ for_each_model_postorder(root, [&](const std::shared_ptr<ov::Model>& m) {
+ for (const auto& n : m->get_ordered_ops()) {
+ auto if_op = ov::as_type_ptr<v8::If>(n);
+ if (!if_op) {
+ continue;
+ }
+ auto then_body = if_op->get_then_body();
+ auto else_body = if_op->get_else_body();
+ if (!then_body || !else_body) {
+ continue;
+ }
+ struct PerOut {
+ int then_r = -1;
+ int else_r = -1;
+ };
+ std::map<int64_t, PerOut> per_out;
+ for (const auto& d : if_op->get_output_descriptions(0)) {
+ per_out[static_cast<int64_t>(d->m_output_index)].then_r = static_cast<int>(d->m_body_value_index);
+ }
+ for (const auto& d : if_op->get_output_descriptions(1)) {
+ per_out[static_cast<int64_t>(d->m_output_index)].else_r = static_cast<int>(d->m_body_value_index);
+ }
+ for (const auto& kv : per_out) {
+ int t_r = kv.second.then_r;
+ int e_r = kv.second.else_r;
+ if (t_r < 0 || e_r < 0) {
+ continue;
+ }
+ auto t_res = then_body->get_results()[t_r];
+ auto e_res = else_body->get_results()[e_r];
+ auto t_src = t_res->input_value(0);
+ auto e_src = e_res->input_value(0);
+ auto t_ps = t_src.get_partial_shape();
+ auto e_ps = e_src.get_partial_shape();
+ if (t_ps.rank().is_dynamic() || e_ps.rank().is_dynamic()) {
+ continue;
+ }
+ if (t_ps.rank().get_length() == e_ps.rank().get_length()) {
+ continue;
+ }
+ bool then_is_smaller = t_ps.rank().get_length() < e_ps.rank().get_length();
+ auto& placeholder_res = then_is_smaller ? t_res : e_res;
+ auto placeholder_body = then_is_smaller ? then_body : else_body;
+ auto template_src = then_is_smaller ? e_src : t_src;
+ const auto tmpl_ps = template_src.get_partial_shape();
+ const auto tmpl_et = template_src.get_element_type();
+
+ // Hoist the live branch's source into the parent scope by cloning its
+ // def-chain, route it as a new If input into the placeholder branch,
+ // so the placeholder produces the same runtime value.
+ ov::Output<ov::Node> replacement;
+ {
+ const bool template_is_then = !then_is_smaller;
+ const int tmpl_branch_idx = template_is_then ? 0 : 1;
+ auto template_body = template_is_then ? then_body : else_body;
+
+ std::function<ov::Output<ov::Node>(const ov::Output<ov::Node>&, int)> hoist;
+ hoist = [&](const ov::Output<ov::Node>& v, int depth_left) -> ov::Output<ov::Node> {
+ if (depth_left <= 0) {
+ return {};
+ }
+ auto nd = v.get_node_shared_ptr();
+ if (auto p = ov::as_type_ptr<v0::Parameter>(nd)) {
+ const int64_t param_idx = template_body->get_parameter_index(p);
+ if (param_idx < 0) {
+ return {};
+ }
+ for (const auto& d : if_op->get_input_descriptions(tmpl_branch_idx)) {
+ if (d->m_body_parameter_index == static_cast<size_t>(param_idx)) {
+ return if_op->input_value(static_cast<int>(d->m_input_index));
+ }
+ }
+ return {};
+ }
+ if (auto c = ov::as_type_ptr<v0::Constant>(nd)) {
+ return c->clone_with_new_inputs({})->output(0);
+ }
+ if (ov::as_type<ov::op::util::MultiSubGraphOp>(nd.get())) {
+ return {};
+ }
+ ov::OutputVector new_inputs;
+ new_inputs.reserve(nd->get_input_size());
+ for (size_t i = 0; i < nd->get_input_size(); ++i) {
+ auto h = hoist(nd->input_value(i), depth_left - 1);
+ if (!h.get_node_shared_ptr()) {
+ return {};
+ }
+ new_inputs.push_back(h);
+ }
+ auto cloned = nd->clone_with_new_inputs(new_inputs);
+ return cloned->output(v.get_index());
+ };
+
+ auto hoisted = hoist(template_src, /*depth_left=*/32);
+ // Unwrap any cloned Identity to avoid orphaned cross-scope edges.
+ hoisted = unwrap_identity(hoisted);
+ if (hoisted.get_node_shared_ptr()) {
+ auto new_param =
+ std::make_shared<v0::Parameter>(hoisted.get_element_type(), hoisted.get_partial_shape());
+ new_param->set_friendly_name(placeholder_res->get_friendly_name() + "/hoist");
+ placeholder_body->add_parameters({new_param});
+ std::shared_ptr<v0::Parameter> then_p = then_is_smaller ? new_param : nullptr;
+ std::shared_ptr<v0::Parameter> else_p = then_is_smaller ? nullptr : new_param;
+ if_op->set_input(hoisted, then_p, else_p);
+ if_op->input(if_op->get_input_size() - 1).replace_source_output(hoisted);
+ placeholder_res->input(0).replace_source_output(new_param->output(0));
+ continue;
+ }
+ }
+
+ // Fallback: use a matching body Parameter as a pass-through
+ // when hoisting is not viable.
+ for (const auto& p : placeholder_body->get_parameters()) {
+ if (p->get_element_type() != tmpl_et) {
+ continue;
+ }
+ const auto p_ps = p->get_partial_shape();
+ if (p_ps.rank().is_dynamic() || p_ps.rank().get_length() != tmpl_ps.rank().get_length()) {
+ continue;
+ }
+ bool ok = true;
+ for (size_t k = 0; k < p_ps.size(); ++k) {
+ // Reject zero-sized dims (placeholder dummies, not live state).
+ if (p_ps[k].is_static() && p_ps[k].get_length() == 0) {
+ ok = false;
+ break;
+ }
+ if (!p_ps[k].compatible(tmpl_ps[k])) {
+ ok = false;
+ break;
+ }
+ }
+ if (ok) {
+ replacement = p->output(0);
+ break;
+ }
+ }
+ if (!replacement.get_node_shared_ptr()) {
+ // Zero constant matching template shape (dynamic dims -> 1).
+ if (tmpl_et.is_real() || tmpl_et.is_integral()) {
+ ov::Shape placeholder_shape;
+ placeholder_shape.reserve(tmpl_ps.size());
+ for (size_t k = 0; k < tmpl_ps.size(); ++k) {
+ placeholder_shape.push_back(
+ tmpl_ps[k].is_static() ? static_cast<size_t>(tmpl_ps[k].get_length()) : size_t{1});
+ }
+ replacement = v0::Constant::create(tmpl_et, placeholder_shape, {0.0f})->output(0);
+ } else {
+ replacement = make_zero_dummy(template_src);
+ }
+ }
+ placeholder_res->input(0).replace_source_output(replacement);
+ }
+ }
+ });
+}
+
+// Lower SequenceAt to a value picked from the resolved per-slot tensors.
+//
+// slots = [s0, s1, s2]
+// At(idx=1) ==> s1 (static index)
+// At(idx=dynamic) ==> If(idx==0, s0, If(idx==1, s1, s2)) (shape-preserving)
+bool lower_sequence_at(const std::shared_ptr<ov::frontend::SequenceAt>& at, SlotResolver& resolver) {
+ auto slots = resolver.slots_of(at->input_value(0));
+ if (!slots || slots->empty()) {
+ return false;
+ }
+ auto idx_c = ov::util::get_constant_from_source(at->input_value(1));
+ if (idx_c) {
+ const auto iv = idx_c->cast_vector<int64_t>();
+ if (iv.size() != 1) {
+ return false;
+ }
+ int64_t k = iv[0];
+ if (k < 0) {
+ k += static_cast<int64_t>(slots->size());
+ }
+ if (k < 0 || static_cast<size_t>(k) >= slots->size()) {
+ return false;
+ }
+ at->output(0).replace((*slots)[static_cast<size_t>(k)]);
+ return true;
+ }
+ // Dynamic index: out = slots[N-1]; for j=N-2..0: out = If(idx==j, slots[j], out)
+ auto idx_in = at->input_value(1);
+ auto idx_i64 = std::make_shared<v0::Convert>(idx_in, ov::element::i64)->output(0);
+ if (idx_i64.get_partial_shape().rank().is_static() && idx_i64.get_partial_shape().rank().get_length() > 0) {
+ const auto rank = idx_i64.get_partial_shape().rank().get_length();
+ std::vector<int64_t> axes_vec(rank);
+ std::iota(axes_vec.begin(), axes_vec.end(), int64_t{0});
+ auto axes = v0::Constant::create(ov::element::i64, ov::Shape{static_cast<size_t>(rank)}, axes_vec);
+ idx_i64 = std::make_shared<v0::Squeeze>(idx_i64, axes)->output(0);
+ }
+ ov::Output<ov::Node> out = slots->back();
+ for (int64_t j = static_cast<int64_t>(slots->size()) - 2; j >= 0; --j) {
+ auto j_const = v0::Constant::create(ov::element::i64, ov::Shape{}, {j});
+ auto eq = std::make_shared<v1::Equal>(idx_i64, j_const)->output(0);
+ out = make_shape_preserving_select(eq, (*slots)[static_cast<size_t>(j)], out);
+ }
+ at->output(0).replace(out);
+ return true;
+}
+
+// Lower SequenceLength to the element count of the resolved slots. Returns
+// false (leaves the reader as-is) when the accumulation axis is ambiguous.
+//
+// slots grow on a dynamic axis ==> ShapeOf(s0)[axis] (runtime length)
+// slots fully static ==> Const(N) (slot count)
+bool lower_sequence_length(const std::shared_ptr<ov::frontend::SequenceLength>& len, SlotResolver& resolver) {
+ auto slots = resolver.slots_of(len->input_value(0));
+ if (!slots) {
+ return false;
+ }
+ // Loop-carried sequence from SequenceEmpty: count is a runtime property.
+ // Emit (ReduceProd(shape(s0)) == 0) ? 0 : N rather than static N.
+ if (resolver.is_loop_carried_empty_seed(len->input_value(0)) && !slots->empty()) {
+ const auto& s0 = (*slots)[0];
+ const auto n = static_cast<int64_t>(slots->size());
+ auto shape_of = std::make_shared<v3::ShapeOf>(s0, ov::element::i64);
+ auto all_axes = v0::Constant::create(ov::element::i64, ov::Shape{1}, {0});
+ auto num_elems = std::make_shared<ov::op::v1::ReduceProd>(shape_of, all_axes, /*keep_dims=*/false);
+ auto zero = v0::Constant::create(ov::element::i64, ov::Shape{}, {0});
+ auto is_empty = std::make_shared<v1::Equal>(num_elems, zero);
+ auto n_const = v0::Constant::create(ov::element::i64, ov::Shape{}, {n});
+ auto count = std::make_shared<v1::Select>(is_empty, zero, n_const)->output(0);
+ len->output(0).replace(count);
+ return true;
+ }
+ ov::Output<ov::Node> length_value;
+ bool axis_ambiguous = false;
+ if (!slots->empty()) {
+ const auto& s0 = (*slots)[0];
+ const auto& ps = s0.get_partial_shape();
+ int dyn_axis = -1;
+ if (ps.rank().is_static()) {
+ std::vector<int> candidates;
+ for (size_t d = 0; d < ps.size(); ++d) {
+ const bool axis_growable = ps[d].is_dynamic() || (ps[d].is_static() && ps[d].get_length() == 0);
+ if (axis_growable) {
+ candidates.push_back(static_cast<int>(d));
+ }
+ }
+ if (candidates.size() == 1) {
+ dyn_axis = candidates[0];
+ } else if (candidates.size() > 1) {
+ // Prefer unique non-batch axis (KV-cache layout: [batch, heads, seq, dim]).
+ int non_batch = 0;
+ int picked = -1;
+ for (int c : candidates) {
+ if (c != 0) {
+ ++non_batch;
+ picked = c;
+ }
+ }
+ if (non_batch == 1) {
+ dyn_axis = picked;
+ } else {
+ axis_ambiguous = true; // multiple non-batch candidates
+ }
+ }
+ }
+ if (dyn_axis >= 0) {
+ auto shape_of = std::make_shared<v3::ShapeOf>(s0, ov::element::i64);
+ auto idx = v0::Constant::create(ov::element::i64, ov::Shape{1}, {dyn_axis});
+ auto gather_axis = v0::Constant::create(ov::element::i64, ov::Shape{}, {0});
+ auto gather = std::make_shared<ov::op::v8::Gather>(shape_of, idx, gather_axis);
+ auto squeeze_axis = v0::Constant::create(ov::element::i64, ov::Shape{1}, {0});
+ length_value = std::make_shared<ov::op::v0::Squeeze>(gather, squeeze_axis)->output(0);
+ }
+ }
+ if (!length_value.get_node_shared_ptr()) {
+ if (axis_ambiguous) {
+ return false; // ambiguous accumulation axis — leave unresolved
+ }
+ // Fully-static slot chain: length == slot count.
+ const auto n = static_cast<int64_t>(slots->size());
+ length_value = v0::Constant::create(ov::element::i64, ov::Shape{}, {n})->output(0);
+ }
+ len->output(0).replace(length_value);
+ return true;
+}
+
+void finalize_lowering(const std::shared_ptr<ov::Model>& model) {
+ disconnect_dead_sequence_back_edges(model);
+ disconnect_dead_sequence_helpers(model);
+ align_if_branch_result_ranks(model);
+ model->validate_nodes_and_infer_types();
+}
+
+} // namespace
+
+} // namespace sal_detail
+
+bool SequenceArrayLowering::run_on_model(const std::shared_ptr<ov::Model>& model) {
+ if (!model) {
+ return false;
+ }
+ // Skip: ConcatFromSequence patterns don't use slot-based lowering.
+ if (!sal_detail::model_has_sequence_reader(model)) {
+ return false;
+ }
+ sal_detail::SlotResolver resolver(model);
+
+ bool overall_changed = false;
+ bool iter_changed = true;
+ while (iter_changed) {
+ std::vector<std::shared_ptr<ov::Node>> helpers;
+ sal_detail::collect_helpers_recursive(model, helpers);
+
+ iter_changed = false;
+ for (const auto& h : helpers) {
+ if (h->output(0).get_target_inputs().empty()) {
+ continue;
+ }
+ if (auto at = ov::as_type_ptr<ov::frontend::SequenceAt>(h)) {
+ iter_changed |= sal_detail::lower_sequence_at(at, resolver);
+ } else if (auto len = ov::as_type_ptr<ov::frontend::SequenceLength>(h)) {
+ iter_changed |= sal_detail::lower_sequence_length(len, resolver);
+ }
+ }
+ overall_changed |= iter_changed;
+ }
+
+ resolver.finalize_pending_wiring();
+
+ if (overall_changed || resolver.changed()) {
+ sal_detail::finalize_lowering(model);
+ }
+ return overall_changed || resolver.changed();
+}
+
+} // namespace pass
+} // namespace frontend
+} // namespace ov
diff --git a/src/frontends/common_translators/src/sequence_if_replacer.cpp b/src/frontends/common_translators/src/sequence_if_replacer.cpp
new file mode 100644
index 00000000000..eeb4364c5c9
--- /dev/null
+++ b/src/frontends/common_translators/src/sequence_if_replacer.cpp
@@ -0,0 +1,302 @@
+// Copyright (C) 2018-2026 Intel Corporation
+// SPDX-License-Identifier: Apache-2.0
+//
+
+#include "sequence_if_replacer.hpp"
+
+#include "openvino/core/graph_util.hpp"
+#include "openvino/core/rt_info.hpp"
+#include "openvino/core/validation_util.hpp"
+#include "openvino/frontend/sequence_at.hpp"
+#include "openvino/frontend/sequence_erase.hpp"
+#include "openvino/frontend/sequence_insert.hpp"
+#include "openvino/frontend/sequence_length.hpp"
+#include "openvino/frontend/sequence_mark.hpp"
+#include "openvino/op/constant.hpp"
+#include "openvino/op/identity.hpp"
+#include "openvino/op/if.hpp"
+#include "openvino/op/loop.hpp"
+#include "openvino/op/result.hpp"
+#include "openvino/op/util/multi_subgraph_base.hpp"
+#include "openvino/pass/graph_rewrite.hpp"
+#include "openvino/pass/pattern/matcher.hpp"
+#include "openvino/pass/pattern/op/wrap_type.hpp"
+#include "slot_resolver.hpp"
+
+using namespace ov::op;
+
+namespace ov {
+namespace frontend {
+namespace pass {
+namespace {
+
+// Strip v16::Identity wrappers to expose the underlying node.
+using sal_detail::unwrap_identity;
+
+// Try to extract the concrete sequence elements behind an Output.
+// Handles SequenceMark and Identity-of-SequenceMark.
+bool try_extract_sequence(const ov::Output<ov::Node>& value, ov::OutputVector& out) {
+ const auto unwrapped = unwrap_identity(value);
+ auto node = unwrapped.get_node_shared_ptr();
+ if (auto seq_mark = ov::as_type_ptr<ov::frontend::SequenceMark>(node)) {
+ out = seq_mark->get_sequence();
+ return true;
+ }
+ return false;
+}
+
+bool try_resolve_via_sequence_mark(const std::shared_ptr<ov::Node>& helper) {
+ ov::OutputVector seq;
+ if (!try_extract_sequence(helper->input_value(0), seq))
+ return false;
+ const auto length = static_cast<int64_t>(seq.size());
+
+ if (auto at = ov::as_type_ptr<ov::frontend::SequenceAt>(helper)) {
+ const auto pos_const = ov::util::get_constant_from_source(at->input_value(1));
+ if (!pos_const)
+ return false;
+ const auto pv = pos_const->cast_vector<int64_t>();
+ if (pv.size() != 1)
+ return false;
+ auto idx = pv[0];
+ if (idx < 0)
+ idx += length;
+ if (idx < 0 || idx >= length)
+ return false;
+ helper->output(0).replace(seq[idx]);
+ return true;
+ }
+ if (ov::is_type<ov::frontend::SequenceLength>(helper)) {
+ auto c = v0::Constant::create(ov::element::i64, ov::Shape{}, {length});
+ c->set_friendly_name(helper->get_friendly_name());
+ ov::copy_runtime_info(helper, c);
+ helper->output(0).replace(c->output(0));
+ return true;
+ }
+ if (auto er = ov::as_type_ptr<ov::frontend::SequenceErase>(helper)) {
+ int64_t idx = length - 1;
+ if (er->has_position()) {
+ const auto pos_const = ov::util::get_constant_from_source(er->get_position());
+ if (!pos_const)
+ return false;
+ const auto pv_er = pos_const->cast_vector<int64_t>();
+ if (pv_er.size() != 1)
+ return false;
+ idx = pv_er[0];
+ if (idx < 0)
+ idx += length;
+ }
+ if (idx < 0 || idx >= length)
+ return false;
+ seq.erase(seq.begin() + idx);
+ auto new_mark = std::make_shared<ov::frontend::SequenceMark>(seq);
+ new_mark->set_friendly_name(er->get_friendly_name());
+ ov::copy_runtime_info(er, new_mark);
+ helper->output(0).replace(new_mark->output(0));
+ return true;
+ }
+ return false;
+}
+
+// Push a SequenceAt / SequenceLength helper into both branches of an If whose
+// outputs feed from a SequenceMark in both branches.
+bool try_resolve_via_if(const std::shared_ptr<ov::Node>& helper) {
+ const auto seq_input = helper->input_value(0);
+ const auto if_node = ov::as_type_ptr<v8::If>(seq_input.get_node_shared_ptr());
+ if (!if_node)
+ return false;
+
+ const auto out_index = seq_input.get_index();
+ const auto then_body = if_node->get_then_body();
+ const auto else_body = if_node->get_else_body();
+
+ // Locate the Result in each branch that feeds this If output.
+ std::shared_ptr<v0::Result> then_result, else_result;
+ for (const auto& desc : if_node->get_output_descriptions(v8::If::THEN_BODY_INDEX)) {
+ if (desc->m_output_index == out_index) {
+ then_result = then_body->get_results().at(desc->m_body_value_index);
+ break;
+ }
+ }
+ for (const auto& desc : if_node->get_output_descriptions(v8::If::ELSE_BODY_INDEX)) {
+ if (desc->m_output_index == out_index) {
+ else_result = else_body->get_results().at(desc->m_body_value_index);
+ break;
+ }
+ }
+ if (!then_result || !else_result)
+ return false;
+
+ ov::OutputVector then_seq, else_seq;
+ if (!try_extract_sequence(then_result->input_value(0), then_seq))
+ return false;
+ if (!try_extract_sequence(else_result->input_value(0), else_seq))
+ return false;
+ if (then_seq.size() != else_seq.size())
+ return false;
+ const auto length = static_cast<int64_t>(then_seq.size());
+
+ if (auto at = ov::as_type_ptr<ov::frontend::SequenceAt>(helper)) {
+ const auto pos_const = ov::util::get_constant_from_source(at->input_value(1));
+ if (!pos_const)
+ return false;
+ const auto pv_at = pos_const->cast_vector<int64_t>();
+ if (pv_at.size() != 1)
+ return false;
+ auto idx = pv_at[0];
+ if (idx < 0)
+ idx += length;
+ if (idx < 0 || idx >= length)
+ return false;
+
+ // Add new tensor-typed outputs to the If: element[idx] from each branch.
+ auto then_new_result = std::make_shared<v0::Result>(then_seq[idx]);
+ auto else_new_result = std::make_shared<v0::Result>(else_seq[idx]);
+ then_body->add_results({then_new_result});
+ else_body->add_results({else_new_result});
+ auto new_out = if_node->set_output(then_new_result, else_new_result);
+ if_node->validate_and_infer_types();
+ ov::copy_runtime_info(helper, {then_new_result, else_new_result});
+ helper->output(0).replace(new_out);
+ return true;
+ }
+ if (ov::is_type<ov::frontend::SequenceLength>(helper)) {
+ auto c = v0::Constant::create(ov::element::i64, ov::Shape{}, {length});
+ c->set_friendly_name(helper->get_friendly_name());
+ ov::copy_runtime_info(helper, c);
+ helper->output(0).replace(c->output(0));
+ return true;
+ }
+ return false;
+}
+
+// After helpers are resolved, dangling sequence-typed If outputs may still
+// exist (we add new outputs rather than remove old ones). For an If output
+// that has no external consumers and whose body Results' inputs come from a
+// frontend sequence helper (SequenceMark / SequenceInsert), redirect those
+// Result inputs to a dummy scalar Constant so the helpers become DCE-able.
+bool cleanup_dead_if_sequence_output(const std::shared_ptr<v8::If>& if_node) {
+ bool changed = false;
+ for (size_t out_idx = 0; out_idx < if_node->get_output_size(); ++out_idx) {
+ if (!if_node->output(out_idx).get_target_inputs().empty())
+ continue;
+ std::shared_ptr<v0::Result> then_result, else_result;
+ for (const auto& desc : if_node->get_output_descriptions(v8::If::THEN_BODY_INDEX)) {
+ if (desc->m_output_index == out_idx) {
+ then_result = if_node->get_then_body()->get_results().at(desc->m_body_value_index);
+ break;
+ }
+ }
+ for (const auto& desc : if_node->get_output_descriptions(v8::If::ELSE_BODY_INDEX)) {
+ if (desc->m_output_index == out_idx) {
+ else_result = if_node->get_else_body()->get_results().at(desc->m_body_value_index);
+ break;
+ }
+ }
+ auto is_seq_helper = [](const ov::Output<ov::Node>& v) {
+ auto n = unwrap_identity(v).get_node_shared_ptr();
+ return ov::is_type<ov::frontend::SequenceMark>(n) || ov::is_type<ov::frontend::SequenceInsert>(n) ||
+ ov::is_type<ov::frontend::SequenceErase>(n);
+ };
+ if (then_result && is_seq_helper(then_result->input_value(0))) {
+ auto dummy = v0::Constant::create(ov::element::i64, ov::Shape{}, {0});
+ then_result->input(0).replace_source_output(dummy->output(0));
+ changed = true;
+ }
+ if (else_result && is_seq_helper(else_result->input_value(0))) {
+ auto dummy = v0::Constant::create(ov::element::i64, ov::Shape{}, {0});
+ else_result->input(0).replace_source_output(dummy->output(0));
+ changed = true;
+ }
+ }
+ return changed;
+}
+
+} // namespace
+
+// The MatcherPass classes below use OPENVINO_MATCHER_PASS_RTTI, which marks the type with a
+// visibility attribute; that requires external linkage, so they must live in a named namespace
+// (an anonymous-namespace type has internal linkage and GCC errors with -Werror=attributes).
+
+// MatcherPass (pattern 1): resolve a reader consuming a statically-known
+// sequence. The sequence input may be an Identity-wrapped Mark/Insert chain.
+//
+// SequenceMark[a,b,c] -> SequenceAt(1) ==> b
+// SequenceMark[a,b,c] -> SequenceLength ==> Const(3)
+// SequenceMark[a,b,c] -> SequenceErase(1) ==> SequenceMark[a,c]
+class ResolveSequenceMarkHelper : public ov::pass::MatcherPass {
+public:
+ OPENVINO_MATCHER_PASS_RTTI("ov::frontend::pass::ResolveSequenceMarkHelper");
+ ResolveSequenceMarkHelper() {
+ auto helper = ov::pass::pattern::
+ wrap_type<ov::frontend::SequenceAt, ov::frontend::SequenceLength, ov::frontend::SequenceErase>();
+ ov::matcher_pass_callback callback = [](ov::pass::pattern::Matcher& m) {
+ return try_resolve_via_sequence_mark(m.get_match_root());
+ };
+ register_matcher(std::make_shared<ov::pass::pattern::Matcher>(helper, get_type_info().name), callback);
+ }
+};
+
+// MatcherPass (pattern 2): sink a reader into both branches of an If whose
+// corresponding Result yields a statically-known sequence, so the read runs
+// per-branch on a plain tensor and the If returns the selected element:
+//
+// then: SequenceMark[a0,b0] then: a0
+// If <{ } -> At(0) ==> If <{ } -> elem
+// else: SequenceMark[a1,b1] else: a1
+class PushSequenceHelperIntoIf : public ov::pass::MatcherPass {
+public:
+ OPENVINO_MATCHER_PASS_RTTI("ov::frontend::pass::PushSequenceHelperIntoIf");
+ PushSequenceHelperIntoIf() {
+ auto helper = ov::pass::pattern::wrap_type<ov::frontend::SequenceAt, ov::frontend::SequenceLength>();
+ ov::matcher_pass_callback callback = [](ov::pass::pattern::Matcher& m) {
+ return try_resolve_via_if(m.get_match_root());
+ };
+ register_matcher(std::make_shared<ov::pass::pattern::Matcher>(helper, get_type_info().name), callback);
+ }
+};
+
+// MatcherPass: after readers resolve, sequence-typed If outputs can be left
+// without consumers. Redirect their body Results to a dummy Constant so the
+// orphaned SequenceMark/Insert/Erase chains become dead-code-eliminable.
+//
+// If output (no consumers): Result <- SequenceMark ==> Result <- Const(0)
+class CleanupDeadIfSequenceOutputs : public ov::pass::MatcherPass {
+public:
+ OPENVINO_MATCHER_PASS_RTTI("ov::frontend::pass::CleanupDeadIfSequenceOutputs");
+ CleanupDeadIfSequenceOutputs() {
+ auto if_pattern = ov::pass::pattern::wrap_type<v8::If>();
+ ov::matcher_pass_callback callback = [](ov::pass::pattern::Matcher& m) {
+ auto if_node = ov::as_type_ptr<v8::If>(m.get_match_root());
+ return if_node && cleanup_dead_if_sequence_output(if_node);
+ };
+ register_matcher(std::make_shared<ov::pass::pattern::Matcher>(if_pattern, get_type_info().name), callback);
+ }
+};
+
+bool SequenceIfReplacer::run_on_model(const std::shared_ptr<ov::Model>& model) {
+ // The two phases must alternate to a fixpoint: resolving a helper can expose a
+ // newly dead If output for cleanup, and cleanup can detach a helper that then
+ // lets another resolve. GraphRewrite recurses into nested Loop/If bodies and
+ // requeues new nodes, so each phase fully converges over the whole model.
+ bool overall_changed = false;
+ bool changed = true;
+ while (changed) {
+ ov::pass::GraphRewrite resolve;
+ resolve.add_matcher<ResolveSequenceMarkHelper>();
+ resolve.add_matcher<PushSequenceHelperIntoIf>();
+ const bool resolved = resolve.run_on_model(model);
+
+ ov::pass::GraphRewrite cleanup;
+ cleanup.add_matcher<CleanupDeadIfSequenceOutputs>();
+ const bool cleaned = cleanup.run_on_model(model);
+
+ changed = resolved || cleaned;
+ overall_changed |= changed;
+ }
+ return overall_changed;
+}
+
+} // namespace pass
+} // namespace frontend
+} // namespace ov
diff --git a/src/frontends/common_translators/src/slot_resolver.cpp b/src/frontends/common_translators/src/slot_resolver.cpp
new file mode 100644
index 00000000000..d5b44bf0961
--- /dev/null
+++ b/src/frontends/common_translators/src/slot_resolver.cpp
@@ -0,0 +1,971 @@
+// Copyright (C) 2018-2026 Intel Corporation
+// SPDX-License-Identifier: Apache-2.0
+//
+
+#include "slot_resolver.hpp"
+
+#include <algorithm>
+#include <deque>
+#include <limits>
+#include <map>
+#include <numeric>
+#include <optional>
+#include <set>
+#include <vector>
+
+#include "openvino/core/except.hpp"
+#include "openvino/core/model.hpp"
+#include "openvino/core/validation_util.hpp"
+#include "openvino/frontend/sequence_at.hpp"
+#include "openvino/frontend/sequence_erase.hpp"
+#include "openvino/frontend/sequence_insert.hpp"
+#include "openvino/frontend/sequence_length.hpp"
+#include "openvino/frontend/sequence_mark.hpp"
+#include "openvino/op/concat.hpp"
+#include "openvino/op/constant.hpp"
+#include "openvino/op/convert.hpp"
+#include "openvino/op/equal.hpp"
+#include "openvino/op/gather.hpp"
+#include "openvino/op/identity.hpp"
+#include "openvino/op/if.hpp"
+#include "openvino/op/less.hpp"
+#include "openvino/op/loop.hpp"
+#include "openvino/op/parameter.hpp"
+#include "openvino/op/reshape.hpp"
+#include "openvino/op/result.hpp"
+#include "openvino/op/select.hpp"
+#include "openvino/op/shape_of.hpp"
+#include "openvino/op/squeeze.hpp"
+#include "openvino/op/unsqueeze.hpp"
+#include "openvino/op/util/multi_subgraph_base.hpp"
+#include "openvino/op/util/sub_graph_base.hpp"
+#include "openvino/util/log.hpp"
+
+using namespace ov::op;
+
+namespace ov {
+namespace frontend {
+namespace pass {
+namespace sal_detail {
+
+// Shape-preserving select using v8::If; unlike v1::Select, does not broadcast inputs.
+ov::Output<ov::Node> make_shape_preserving_select(const ov::Output<ov::Node>& cond_in,
+ const ov::Output<ov::Node>& then_val,
+ const ov::Output<ov::Node>& else_val) {
+ ov::Output<ov::Node> cond = cond_in;
+ if (cond.get_element_type() != ov::element::boolean) {
+ cond = std::make_shared<v0::Convert>(cond, ov::element::boolean)->output(0);
+ }
+ if (cond.get_partial_shape().rank().is_static() && cond.get_partial_shape().rank().get_length() > 0) {
+ std::vector<int64_t> axes(cond.get_partial_shape().rank().get_length());
+ std::iota(axes.begin(), axes.end(), 0);
+ auto axes_c = v0::Constant::create(ov::element::i64, ov::Shape{axes.size()}, axes);
+ cond = std::make_shared<v0::Squeeze>(cond, axes_c)->output(0);
+ }
+ auto then_param = std::make_shared<v0::Parameter>(then_val.get_element_type(), then_val.get_partial_shape());
+ auto else_param = std::make_shared<v0::Parameter>(else_val.get_element_type(), else_val.get_partial_shape());
+ auto then_result = std::make_shared<v0::Result>(then_param);
+ auto else_result = std::make_shared<v0::Result>(else_param);
+ auto then_body = std::make_shared<ov::Model>(ov::ResultVector{then_result}, ov::ParameterVector{then_param});
+ auto else_body = std::make_shared<ov::Model>(ov::ResultVector{else_result}, ov::ParameterVector{else_param});
+ auto if_node = std::make_shared<v8::If>(cond);
+ if_node->set_then_body(then_body);
+ if_node->set_else_body(else_body);
+ if_node->set_input(then_val, then_param, nullptr);
+ if_node->set_input(else_val, nullptr, else_param);
+ if_node->set_output(then_result, else_result);
+ return if_node->output(0);
+}
+
+ov::Output<ov::Node> unwrap_identity(const ov::Output<ov::Node>& value) {
+ ov::Output<ov::Node> cur = value;
+ while (auto identity = ov::as_type_ptr<v16::Identity>(cur.get_node_shared_ptr())) {
+ cur = identity->input_value(0);
+ }
+ return cur;
+}
+
+ov::Output<ov::Node> make_zero_dummy(const ov::Output<ov::Node>& tmpl) {
+ auto et = tmpl.get_element_type();
+ auto ps = tmpl.get_partial_shape();
+ if (et == ov::element::dynamic) {
+ et = ov::element::i64;
+ }
+ std::vector<int64_t> dims;
+ if (!ps.rank().is_dynamic()) {
+ for (const auto& d : ps) {
+ dims.push_back(d.is_dynamic() ? 0 : d.get_length());
+ }
+ }
+ ov::Shape shape(dims.begin(), dims.end());
+ return std::make_shared<v0::Constant>(et, shape, std::vector<std::string>{"0"});
+}
+
+// Seed constant with static dims preserved, last dynamic axis set to 0
+// (growable concat axis), all other dynamic axes set to 1.
+ov::Output<ov::Node> make_growable_seed(const ov::PartialShape& ps, ov::element::Type et) {
+ if (et == ov::element::dynamic) {
+ et = ov::element::i64;
+ }
+ if (!ps.rank().is_static()) {
+ return std::make_shared<v0::Constant>(et, ov::Shape{}, std::vector<std::string>{"0"})->output(0);
+ }
+ const auto rl = ps.rank().get_length();
+ int64_t last_dyn = -1;
+ for (int64_t j = rl - 1; j >= 0; --j) {
+ if (ps[j].is_dynamic()) {
+ last_dyn = j;
+ break;
+ }
+ }
+ ov::Shape seed_shape;
+ seed_shape.reserve(static_cast<size_t>(rl));
+ for (int64_t j = 0; j < rl; ++j) {
+ if (ps[j].is_static()) {
+ seed_shape.push_back(static_cast<size_t>(ps[j].get_length()));
+ } else if (j == last_dyn) {
+ seed_shape.push_back(0);
+ } else {
+ seed_shape.push_back(1);
+ }
+ }
+ // Single-value literal broadcasts to fill the shape.
+ return std::make_shared<v0::Constant>(et, seed_shape, std::vector<std::string>{"0"})->output(0);
+}
+
+namespace {
+
+bool depends_on_node(const ov::Output<ov::Node>& value, ov::Node* target, std::set<ov::Node*>& visited) {
+ auto node = value.get_node();
+ if (node == target) {
+ return true;
+ }
+ if (!visited.insert(node).second) {
+ return false;
+ }
+ for (size_t i = 0; i < node->get_input_size(); ++i) {
+ if (depends_on_node(node->input_value(i), target, visited)) {
+ return true;
+ }
+ }
+ return false;
+}
+
+// Returns index of value's Result in body, adding one if absent.
+int64_t ensure_body_result(const std::shared_ptr<ov::Model>& body, const ov::Output<ov::Node>& value) {
+ int64_t idx = body->get_result_index(value);
+ if (idx < 0) {
+ auto r = std::make_shared<v0::Result>(value);
+ body->add_results({r});
+ idx = static_cast<int64_t>(body->get_results().size()) - 1;
+ }
+ return idx;
+}
+
+struct InputBinding {
+ int outer_input = -1;
+ int back_edge_result_idx = -1; // >= 0 only for MergedInputDescription
+};
+
+bool find_input_binding(const std::shared_ptr<ov::op::util::MultiSubGraphOp>& msg,
+ int body_idx,
+ size_t param_idx,
+ InputBinding& out) {
+ for (const auto& d : msg->get_input_descriptions(body_idx)) {
+ if (d->m_body_parameter_index != param_idx) {
+ continue;
+ }
+ out.outer_input = static_cast<int>(d->m_input_index);
+ if (auto merged = ov::as_type_ptr<ov::op::util::MultiSubGraphOp::MergedInputDescription>(d)) {
+ out.back_edge_result_idx = static_cast<int>(merged->m_body_value_index);
+ }
+ return true;
+ }
+ return false;
+}
+
+} // namespace
+
+void SlotResolver::build_maps(const std::shared_ptr<ov::Model>& m) {
+ if (!m) {
+ return;
+ }
+ for (const auto& p : m->get_parameters()) {
+ param_to_model_[p.get()] = m;
+ }
+ for (const auto& node : m->get_ordered_ops()) {
+ if (auto msg = ov::as_type_ptr<ov::op::util::MultiSubGraphOp>(node)) {
+ for (size_t i = 0; i < msg->get_internal_subgraphs_size(); ++i) {
+ auto body = msg->get_function(i);
+ if (body) {
+ body_owner_[body.get()] = {msg, static_cast<int>(i)};
+ build_maps(body);
+ }
+ }
+ }
+ }
+}
+
+// True when the Loop merged input carries a sequence (outer source or back-edge is
+// a sequence helper, or the body Parameter feeds one).
+bool SlotResolver::is_sequence_merged_input(const std::shared_ptr<v5::Loop>& loop,
+ const std::shared_ptr<ov::Model>& body,
+ size_t p_idx,
+ size_t back_value_idx) {
+ InputBinding binding;
+ const int outer_input = find_input_binding(loop, 0, p_idx, binding) ? binding.outer_input : -1;
+ if (outer_input >= 0) {
+ auto src = unwrap_identity(loop->input_value(outer_input));
+ auto node = src.get_node_shared_ptr();
+ if (ov::is_type<ov::frontend::SequenceMark>(node) || ov::is_type<ov::frontend::SequenceInsert>(node) ||
+ ov::is_type<ov::frontend::SequenceErase>(node)) {
+ return true;
+ }
+ }
+ if (back_value_idx < body->get_results().size()) {
+ auto back_src = unwrap_identity(body->get_results()[back_value_idx]->input_value(0));
+ auto back_node = back_src.get_node_shared_ptr();
+ if (ov::is_type<ov::frontend::SequenceMark>(back_node) ||
+ ov::is_type<ov::frontend::SequenceInsert>(back_node) ||
+ ov::is_type<ov::frontend::SequenceErase>(back_node)) {
+ return true;
+ }
+ }
+ const auto& body_param = body->get_parameters()[p_idx];
+ std::deque<ov::Output<ov::Node>> q;
+ std::set<ov::Node*> visited;
+ q.push_back(body_param->output(0));
+ while (!q.empty()) {
+ auto v = q.front();
+ q.pop_front();
+ for (const auto& tin : v.get_target_inputs()) {
+ auto consumer = tin.get_node();
+ if (!visited.insert(consumer).second) {
+ continue;
+ }
+ if (ov::is_type<v16::Identity>(consumer)) {
+ q.push_back(consumer->output(0));
+ continue;
+ }
+ if (ov::is_type<ov::frontend::SequenceAt>(consumer) ||
+ ov::is_type<ov::frontend::SequenceInsert>(consumer) ||
+ ov::is_type<ov::frontend::SequenceErase>(consumer) ||
+ ov::is_type<ov::frontend::SequenceLength>(consumer)) {
+ return true;
+ }
+ }
+ }
+ return false;
+}
+
+// Pre-allocate N per-slot merged inputs for every Loop whose merged input carries
+// a sequence. Defers actual wiring to finalize_pending_wiring().
+//
+// merged( seqParam <- seqResult ) ==> merged( s0Param <- s0Result )
+// merged( s1Param <- s1Result ) ...
+void SlotResolver::preallocate_loop_merged_params(const std::shared_ptr<ov::Model>& m) {
+ if (!m) {
+ return;
+ }
+ for (const auto& node : m->get_ordered_ops()) {
+ if (auto msg = ov::as_type_ptr<ov::op::util::MultiSubGraphOp>(node)) {
+ for (size_t i = 0; i < msg->get_internal_subgraphs_size(); ++i) {
+ preallocate_loop_merged_params(msg->get_function(i));
+ }
+ }
+ }
+ for (const auto& node : m->get_ordered_ops()) {
+ auto loop = ov::as_type_ptr<v5::Loop>(node);
+ if (!loop) {
+ continue;
+ }
+ auto body = loop->get_function();
+ if (!body) {
+ continue;
+ }
+ // Snapshot descriptors so set_merged_input mutations don't race with later iterations.
+ auto descriptors = loop->get_input_descriptions();
+ for (const auto& d : descriptors) {
+ auto merged = ov::as_type_ptr<ov::op::util::MultiSubGraphOp::MergedInputDescription>(d);
+ if (!merged) {
+ continue;
+ }
+ const size_t p_idx = merged->m_body_parameter_index;
+ const size_t back_idx = merged->m_body_value_index;
+ if (p_idx >= body->get_parameters().size() || back_idx >= body->get_results().size()) {
+ continue;
+ }
+ if (!is_sequence_merged_input(loop, body, p_idx, back_idx)) {
+ continue;
+ }
+ auto old_param = body->get_parameters()[p_idx];
+ if (cache_.count(old_param->output(0))) {
+ continue; // already pre-allocated
+ }
+
+ const int outer_in = static_cast<int>(merged->m_input_index);
+ auto outer_src = unwrap_identity(loop->input_value(outer_in));
+ auto outer_mark = ov::as_type_ptr<ov::frontend::SequenceMark>(outer_src.get_node_shared_ptr());
+
+ std::vector<ov::Output<ov::Node>> slot_templates;
+ Slots outer_seed_slots;
+ PendingMerged::SeedKind seed_kind = PendingMerged::SeedKind::DEFERRED;
+
+ if (outer_mark && outer_mark->get_input_size() > 0) {
+ for (size_t k = 0; k < outer_mark->get_input_size(); ++k) {
+ slot_templates.push_back(outer_mark->input_value(k));
+ outer_seed_slots.push_back(outer_mark->input_value(k));
+ }
+ seed_kind = PendingMerged::SeedKind::KNOWN;
+ } else if (auto os = slots_of(outer_src); os && !os->empty()) {
+ // Outer source has priority for slot count (inner back-edge may undercount).
+ slot_templates.assign(os->begin(), os->end());
+ outer_seed_slots = *os;
+ seed_kind = PendingMerged::SeedKind::KNOWN;
+ } else {
+ auto back_value = body->get_results()[back_idx]->input_value(0);
+
+ if (auto bs = slots_of(back_value)) {
+ slot_templates = *bs;
+ } else if (auto tmpl = find_template_via_chain(back_value, old_param.get())) {
+ slot_templates = tmpl->slot_templates;
+ } else {
+ continue; // cannot infer N -- skip
+ }
+ if (outer_mark && outer_mark->get_input_size() == 0) {
+ for (const auto& t : slot_templates) {
+ outer_seed_slots.push_back(make_growable_seed(t.get_partial_shape(), t.get_element_type()));
+ }
+ seed_kind = PendingMerged::SeedKind::SYNTHETIC;
+ }
+ }
+
+ const size_t N = slot_templates.size();
+
+ // Fallback element type: first resolved type across all slots.
+ ov::element::Type merged_et = ov::element::dynamic;
+ for (const auto& t : slot_templates) {
+ if (merged_et == ov::element::dynamic) {
+ merged_et = t.get_element_type();
+ }
+ }
+
+ std::vector<std::shared_ptr<v0::Parameter>> new_params;
+ new_params.reserve(N);
+ Slots param_outputs;
+ param_outputs.reserve(N);
+ for (size_t k = 0; k < N; ++k) {
+ auto et = slot_templates[k].get_element_type();
+ if (et == ov::element::dynamic) {
+ et = merged_et;
+ }
+ // Widen zero dims to dynamic to avoid clamping the back-edge at runtime.
+ ov::PartialShape pshape = slot_templates[k].get_partial_shape();
+ if (pshape.rank().is_static()) {
+ for (size_t d = 0; d < pshape.size(); ++d) {
+ if (pshape[d].is_static() && pshape[d].get_length() == 0) {
+ pshape[d] = ov::Dimension::dynamic();
+ }
+ }
+ }
+ auto np = std::make_shared<v0::Parameter>(et, pshape);
+ body->add_parameters({np});
+ param_to_model_[np.get()] = body;
+ if (seed_kind == PendingMerged::SeedKind::SYNTHETIC) {
+ // Mark as empty-seed so SequenceLength lowers to runtime ShapeOf.
+ np->get_rt_info()["sal_empty_seed_slot"] = true;
+ }
+ new_params.push_back(np);
+ param_outputs.push_back(np->output(0));
+ }
+ cache_[old_param->output(0)] = param_outputs;
+
+ PendingMerged pm;
+ pm.loop = loop;
+ pm.body = body;
+ pm.back_edge_result_idx = static_cast<int>(back_idx);
+ pm.outer_input = outer_in;
+ pm.old_param = old_param;
+ pm.new_params = std::move(new_params);
+ pm.outer_seed_slots = std::move(outer_seed_slots);
+ pm.seed_kind = seed_kind;
+ pending_merged_.push_back(std::move(pm));
+ }
+ }
+}
+
+void SlotResolver::finalize_pending_wiring() {
+ for (auto& pm : pending_merged_) {
+ const size_t N = pm.new_params.size();
+ if (N == 0) {
+ continue;
+ }
+ // Resolve outer seed slots deferred from pre-allocation time.
+ if (pm.seed_kind == PendingMerged::SeedKind::DEFERRED) {
+ auto outer_src = pm.loop->input_value(pm.outer_input);
+ auto src_slots = slots_of(outer_src);
+ OPENVINO_ASSERT(src_slots && src_slots->size() == N,
+ "SequenceArrayLowering: could not reconcile the loop-carried sequence outer seed to ",
+ N,
+ " slots; the loop-carried sequence pattern is not supported.");
+ pm.outer_seed_slots = *src_slots;
+ pm.seed_kind = PendingMerged::SeedKind::KNOWN;
+ }
+ auto back_value = pm.body->get_results()[pm.back_edge_result_idx]->input_value(0);
+ auto back_slots = slots_of(back_value);
+ OPENVINO_ASSERT(back_slots && back_slots->size() == N,
+ "SequenceArrayLowering: could not reconcile the loop-carried sequence back-edge to ",
+ N,
+ " slots; the loop-carried sequence pattern is not supported.");
+ // Synthetic seed was built from pre-lowering templates (may be scalar);
+ // rebuild from resolved back-edge shape so the carried tensor keeps its true rank.
+ if (pm.seed_kind == PendingMerged::SeedKind::SYNTHETIC) {
+ for (size_t k = 0; k < N; ++k) {
+ const auto& resolved = (*back_slots)[k];
+ if (resolved.get_partial_shape().rank().is_dynamic()) {
+ if (auto producer = resolved.get_node_shared_ptr()) {
+ producer->validate_and_infer_types();
+ }
+ }
+ pm.outer_seed_slots[k] = make_growable_seed(resolved.get_partial_shape(), resolved.get_element_type());
+ }
+ }
+ for (size_t k = 0; k < N; ++k) {
+ ov::Output<ov::Node> back_value = (*back_slots)[k];
+ ensure_body_result(pm.body, back_value);
+ pm.loop->set_merged_input(pm.new_params[k], pm.outer_seed_slots[k], back_value);
+ }
+ pm.loop->input(pm.outer_input).replace_source_output(pm.outer_seed_slots[0]);
+ changed_ = true;
+ }
+}
+
+std::optional<LengthTemplate> SlotResolver::find_template_via_chain(const ov::Output<ov::Node>& root_value,
+ ov::Node* exclude_p) {
+ std::deque<ov::Output<ov::Node>> q;
+ std::set<ov::Output<ov::Node>> visited;
+ q.push_back(root_value);
+ while (!q.empty()) {
+ auto v = q.front();
+ q.pop_front();
+ if (!visited.insert(v).second) {
+ continue;
+ }
+ auto n = v.get_node_shared_ptr();
+ if (auto mark = ov::as_type_ptr<ov::frontend::SequenceMark>(n)) {
+ if (n.get() != exclude_p && mark->get_input_size() > 0) {
+ bool deps = false;
+ for (size_t i = 0; i < mark->get_input_size(); ++i) {
+ std::set<ov::Node*> vis;
+ if (depends_on_node(mark->input_value(i), exclude_p, vis)) {
+ deps = true;
+ break;
+ }
+ }
+ if (!deps) {
+ // Enumerate structurally (not via slots_of()) to avoid cyclic dependency.
+ LengthTemplate t;
+ t.slot_templates = mark->get_sequence();
+ return t;
+ }
+ }
+ continue;
+ }
+ if (auto msg = ov::as_type_ptr<ov::op::util::MultiSubGraphOp>(n)) {
+ for (size_t b = 0; b < msg->get_internal_subgraphs_size(); ++b) {
+ for (const auto& d : msg->get_output_descriptions(static_cast<int>(b))) {
+ if (d->m_output_index == v.get_index()) {
+ auto body = msg->get_function(b);
+ if (body) {
+ q.push_back(body->get_results()[d->m_body_value_index]->input_value(0));
+ }
+ }
+ }
+ }
+ continue;
+ }
+ if (auto param = ov::as_type_ptr<v0::Parameter>(n)) {
+ auto it = param_to_model_.find(param.get());
+ if (it == param_to_model_.end()) {
+ continue;
+ }
+ auto body = it->second;
+ auto own_it = body_owner_.find(body.get());
+ if (own_it == body_owner_.end()) {
+ continue;
+ }
+ auto owner_msg = own_it->second.first;
+ int body_idx = own_it->second.second;
+ const int64_t pi_signed = it->second->get_parameter_index(param);
+ if (pi_signed < 0) {
+ continue;
+ }
+ InputBinding binding;
+ if (find_input_binding(owner_msg, body_idx, static_cast<size_t>(pi_signed), binding)) {
+ q.push_back(owner_msg->input_value(binding.outer_input));
+ if (n.get() != exclude_p && binding.back_edge_result_idx >= 0) {
+ q.push_back(it->second->get_results()[binding.back_edge_result_idx]->input_value(0));
+ }
+ }
+ continue;
+ }
+ if (ov::as_type_ptr<ov::frontend::SequenceInsert>(n) || ov::as_type_ptr<ov::frontend::SequenceErase>(n)) {
+ q.push_back(n->input_value(0));
+ continue;
+ }
+ for (size_t i = 0; i < n->get_input_size(); ++i) {
+ q.push_back(n->input_value(i));
+ }
+ }
+ return std::nullopt;
+}
+
+std::optional<Slots> SlotResolver::slots_of(const ov::Output<ov::Node>& value_in) {
+ auto value = unwrap_identity(value_in);
+ auto it = cache_.find(value);
+ if (it != cache_.end()) {
+ return it->second;
+ }
+ if (!in_progress_.insert(value).second) {
+ return std::nullopt; // cycle - cannot resolve via this path
+ }
+ struct Guard {
+ std::set<ov::Output<ov::Node>>* set;
+ ov::Output<ov::Node> v;
+ ~Guard() {
+ set->erase(v);
+ }
+ } guard{&in_progress_, value};
+
+ auto node = value.get_node_shared_ptr();
+ std::optional<Slots> result;
+
+ if (auto mark = ov::as_type_ptr<ov::frontend::SequenceMark>(node)) {
+ Slots s;
+ s.reserve(mark->get_input_size());
+ for (size_t i = 0; i < mark->get_input_size(); ++i) {
+ auto in = mark->input_value(i);
+ auto in_node = in.get_node_shared_ptr();
+ const bool seq_typed = ov::as_type_ptr<ov::frontend::SequenceInsert>(in_node) ||
+ ov::as_type_ptr<ov::frontend::SequenceErase>(in_node) ||
+ ov::as_type_ptr<ov::frontend::SequenceMark>(in_node);
+ if (seq_typed) {
+ if (auto inner = slots_of(in)) {
+ s.insert(s.end(), inner->begin(), inner->end());
+ continue;
+ }
+ }
+ s.push_back(in);
+ }
+ result = std::move(s);
+ } else if (auto ins = ov::as_type_ptr<ov::frontend::SequenceInsert>(node)) {
+ auto base = slots_of(ins->input_value(0));
+ if (!base) {
+ return std::nullopt;
+ }
+ Slots s = *base;
+ if (!ins->has_position()) {
+ s.push_back(ins->input_value(1));
+ result = std::move(s);
+ } else {
+ auto pos_c = ov::util::get_constant_from_source(ins->input_value(2));
+ if (!pos_c) {
+ // out_j = (j < pos) ? base[j] : (j == pos) ? value : base[j-1]
+ const auto& val = ins->input_value(1);
+ const auto& pos_in = ins->input_value(2);
+ auto pos_i64 = std::make_shared<v0::Convert>(pos_in, element::i64);
+ Slots s_new;
+ s_new.reserve(base->size() + 1);
+ for (size_t j = 0; j <= base->size(); ++j) {
+ auto jc = v0::Constant::create(element::i64, ov::Shape{}, {static_cast<int64_t>(j)});
+ auto less = std::make_shared<v1::Less>(jc, pos_i64);
+ auto eq = std::make_shared<v1::Equal>(jc, pos_i64);
+ ov::Output<ov::Node> from_lo =
+ base->empty() ? val : (j < base->size() ? base->at(j) : base->at(base->size() - 1));
+ ov::Output<ov::Node> from_hi = base->empty() ? val : ((j > 0) ? base->at(j - 1) : base->at(0));
+ auto inner = make_shape_preserving_select(eq, val, from_hi);
+ auto outer = make_shape_preserving_select(less, from_lo, inner);
+ s_new.push_back(outer);
+ }
+ result = std::move(s_new);
+ } else {
+ const auto pv = pos_c->cast_vector<int64_t>();
+ if (pv.size() != 1) {
+ return std::nullopt;
+ }
+ int64_t pos = pv[0];
+ if (pos < 0) {
+ // Negative index wraps: pos += size.
+ pos += static_cast<int64_t>(base->size());
+ }
+ if (pos < 0 || static_cast<size_t>(pos) > base->size()) {
+ return std::nullopt;
+ }
+ s.insert(s.begin() + pos, ins->input_value(1));
+ result = std::move(s);
+ }
+ }
+ } else if (auto era = ov::as_type_ptr<ov::frontend::SequenceErase>(node)) {
+ auto base = slots_of(era->input_value(0));
+ if (!base) {
+ return std::nullopt;
+ }
+ Slots s = *base;
+ if (s.empty()) {
+ return std::nullopt;
+ }
+ if (!era->has_position()) {
+ s.pop_back();
+ result = std::move(s);
+ } else {
+ auto pos_c = ov::util::get_constant_from_source(era->input_value(1));
+ if (!pos_c) {
+ // Dynamic position: synthesize each output slot via Select.
+ // out_j = (j < pos) ? base[j] : base[j + 1]
+ const auto& pos_in = era->input_value(1);
+ auto pos_i64 = std::make_shared<v0::Convert>(pos_in, element::i64);
+ Slots s_new;
+ s_new.reserve(base->size() - 1);
+ for (size_t j = 0; j + 1 < base->size(); ++j) {
+ auto jc = v0::Constant::create(element::i64, ov::Shape{}, {static_cast<int64_t>(j)});
+ auto less = std::make_shared<v1::Less>(jc, pos_i64);
+ auto sel = make_shape_preserving_select(less, base->at(j), base->at(j + 1));
+ s_new.push_back(sel);
+ }
+ result = std::move(s_new);
+ } else {
+ const auto pv = pos_c->cast_vector<int64_t>();
+ if (pv.size() != 1) {
+ return std::nullopt;
+ }
+ int64_t pos = pv[0];
+ if (pos < 0) {
+ pos += static_cast<int64_t>(base->size());
+ }
+ if (pos < 0 || static_cast<size_t>(pos) >= base->size()) {
+ return std::nullopt;
+ }
+ s.erase(s.begin() + pos);
+ result = std::move(s);
+ }
+ }
+ } else if (auto p = ov::as_type_ptr<v0::Parameter>(node)) {
+ result = slots_of_param(p);
+ } else if (auto msg = ov::as_type_ptr<ov::op::util::MultiSubGraphOp>(node)) {
+ result = slots_of_msg_output(msg, value.get_index());
+ }
+
+ if (result) {
+ cache_[value] = *result;
+ }
+ return result;
+}
+
+bool SlotResolver::is_loop_carried_empty_seed(const ov::Output<ov::Node>& value) {
+ auto s = slots_of(value);
+ if (!s) {
+ return false;
+ }
+ for (const auto& slot : *s) {
+ if (unwrap_identity(slot).get_node()->get_rt_info().count("sal_empty_seed_slot")) {
+ return true;
+ }
+ }
+ return false;
+}
+
+std::optional<Slots> SlotResolver::slots_of_param(const std::shared_ptr<v0::Parameter>& p) {
+ auto body_it = param_to_model_.find(p.get());
+ if (body_it == param_to_model_.end()) {
+ return std::nullopt; // not in any tracked body - top-level Parameter
+ }
+ auto body = body_it->second;
+ auto owner_it = body_owner_.find(body.get());
+ if (owner_it == body_owner_.end()) {
+ return std::nullopt;
+ }
+ auto owner = owner_it->second.first;
+ const int body_idx = owner_it->second.second;
+
+ const int64_t p_idx_signed = body->get_parameter_index(p);
+ if (p_idx_signed < 0) {
+ return std::nullopt;
+ }
+ const size_t p_idx = static_cast<size_t>(p_idx_signed);
+
+ InputBinding binding;
+ if (!find_input_binding(owner, body_idx, p_idx, binding)) {
+ return std::nullopt;
+ }
+ const int outer_input = binding.outer_input;
+ const int back_edge_result_idx = binding.back_edge_result_idx;
+
+ auto outer_source = owner->input_value(outer_input);
+ auto loop = ov::as_type_ptr<v5::Loop>(owner);
+
+ if (loop && back_edge_result_idx >= 0) {
+ // Merged inputs are pre-allocated; bail out to avoid cyclic back-edge resolution.
+ return std::nullopt;
+ }
+
+ auto src_slots = slots_of(outer_source);
+ if (!src_slots) {
+ return std::nullopt;
+ }
+ const size_t N = src_slots->size();
+ Slots param_outputs;
+ param_outputs.reserve(N);
+
+ if (auto subgraph_op = ov::as_type_ptr<ov::op::util::SubGraphOp>(owner)) {
+ for (size_t k = 0; k < N; ++k) {
+ auto new_param = std::make_shared<v0::Parameter>((*src_slots)[k].get_element_type(),
+ (*src_slots)[k].get_partial_shape());
+ body->add_parameters({new_param});
+ param_to_model_[new_param.get()] = body;
+ if ((*src_slots)[k].get_node()->get_rt_info().count("sal_empty_seed_slot")) {
+ new_param->get_rt_info()["sal_empty_seed_slot"] = true;
+ }
+ subgraph_op->set_invariant_input(new_param, (*src_slots)[k]);
+ param_outputs.push_back(new_param->output(0));
+ }
+ owner->input(outer_input).replace_source_output((*src_slots)[0]);
+ changed_ = true;
+ return param_outputs;
+ }
+
+ const size_t num_bodies = owner->get_internal_subgraphs_size();
+ std::vector<std::shared_ptr<ov::Model>> bodies(num_bodies);
+ std::vector<int> other_param_idx(num_bodies, -1);
+ for (size_t bb = 0; bb < num_bodies; ++bb) {
+ bodies[bb] = owner->get_function(bb);
+ if (!bodies[bb]) {
+ return std::nullopt;
+ }
+ if (static_cast<int>(bb) == body_idx) {
+ other_param_idx[bb] = static_cast<int>(p_idx);
+ continue;
+ }
+ for (const auto& d : owner->get_input_descriptions(static_cast<int>(bb))) {
+ if (static_cast<int>(d->m_input_index) == outer_input) {
+ other_param_idx[bb] = static_cast<int>(d->m_body_parameter_index);
+ break;
+ }
+ }
+ }
+
+ std::vector<Slots> per_body_outputs(num_bodies);
+ for (size_t k = 0; k < N; ++k) {
+ ov::ParameterVector pv;
+ for (size_t bb = 0; bb < num_bodies; ++bb) {
+ if (other_param_idx[bb] < 0) {
+ continue;
+ }
+ auto new_param = std::make_shared<v0::Parameter>((*src_slots)[k].get_element_type(),
+ (*src_slots)[k].get_partial_shape());
+ bodies[bb]->add_parameters({new_param});
+ param_to_model_[new_param.get()] = bodies[bb];
+ if ((*src_slots)[k].get_node()->get_rt_info().count("sal_empty_seed_slot")) {
+ new_param->get_rt_info()["sal_empty_seed_slot"] = true;
+ }
+ pv.push_back(new_param);
+ per_body_outputs[bb].push_back(new_param->output(0));
+ }
+ owner->set_invariant_inputs((*src_slots)[k], pv);
+ }
+ for (size_t bb = 0; bb < num_bodies; ++bb) {
+ if (static_cast<int>(bb) == body_idx || other_param_idx[bb] < 0) {
+ continue;
+ }
+ const auto& other_param = bodies[bb]->get_parameters()[other_param_idx[bb]];
+ cache_[other_param->output(0)] = per_body_outputs[bb];
+ }
+ owner->input(outer_input).replace_source_output((*src_slots)[0]);
+ changed_ = true;
+ return per_body_outputs[body_idx];
+}
+
+bool SlotResolver::expand_branch_to_n_slots(const std::shared_ptr<ov::op::util::MultiSubGraphOp>& msg,
+ size_t b,
+ size_t ref,
+ size_t N,
+ std::vector<Slots>& per_body_slots) {
+ const size_t orig_branch_size = per_body_slots[b].size();
+ auto ref_body = msg->get_function(static_cast<int>(ref));
+ auto cur_body = msg->get_function(static_cast<int>(b));
+ per_body_slots[b].clear();
+ per_body_slots[b].reserve(N);
+ std::vector<size_t> live_param_indices;
+ if (ref_body && cur_body && !per_body_slots[ref].empty()) {
+ const auto ref_et = per_body_slots[ref][0].get_element_type();
+ const auto ref_ps = per_body_slots[ref][0].get_partial_shape();
+ const auto& ref_params = ref_body->get_parameters();
+ for (size_t i = 0; i < ref_params.size(); ++i) {
+ const auto& p = ref_params[i];
+ if (p->get_element_type() != ref_et) {
+ continue;
+ }
+ if (p->get_partial_shape().rank() != ref_ps.rank()) {
+ continue;
+ }
+ bool compatible = true;
+ if (!ref_ps.rank().is_dynamic()) {
+ const auto& pps = p->get_partial_shape();
+ for (size_t d = 0; d < ref_ps.size(); ++d) {
+ const auto& rd = ref_ps[d];
+ const auto& pd = pps[d];
+ if (rd.is_static() && pd.is_static() && rd.get_length() != pd.get_length()) {
+ compatible = false;
+ break;
+ }
+ }
+ }
+ if (compatible) {
+ live_param_indices.push_back(i);
+ }
+ }
+ }
+ // Prefer the last N (SAL-appended Parameters are at the tail).
+ bool use_mirror = false;
+ std::vector<size_t> mirror_live_param_indices;
+ std::vector<int64_t> mirror_outer_input_index;
+ if (live_param_indices.size() >= N) {
+ mirror_live_param_indices.assign(live_param_indices.end() - static_cast<long>(N), live_param_indices.end());
+ mirror_outer_input_index.assign(N, -1);
+ auto live_descs = msg->get_input_descriptions(static_cast<int>(ref));
+ for (size_t k = 0; k < N; ++k) {
+ for (const auto& d : live_descs) {
+ if (d->m_body_parameter_index == mirror_live_param_indices[k]) {
+ mirror_outer_input_index[k] = static_cast<int64_t>(d->m_input_index);
+ break;
+ }
+ }
+ if (mirror_outer_input_index[k] < 0) {
+ mirror_outer_input_index.clear();
+ break;
+ }
+ }
+ use_mirror = !mirror_outer_input_index.empty();
+ }
+ if (use_mirror) {
+ auto cur_descs = msg->get_input_descriptions(static_cast<int>(b));
+ for (size_t k = 0; k < N; ++k) {
+ const auto& live_param = ref_body->get_parameters()[mirror_live_param_indices[k]];
+ auto new_param =
+ std::make_shared<v0::Parameter>(live_param->get_element_type(), live_param->get_partial_shape());
+ cur_body->add_parameters({new_param});
+ param_to_model_[new_param.get()] = cur_body;
+ if (live_param->get_rt_info().count("sal_empty_seed_slot")) {
+ new_param->get_rt_info()["sal_empty_seed_slot"] = true;
+ }
+ const size_t new_body_param_idx = cur_body->get_parameters().size() - 1;
+ cur_descs.push_back(std::make_shared<ov::op::util::MultiSubGraphOp::InvariantInputDescription>(
+ static_cast<uint64_t>(mirror_outer_input_index[k]),
+ static_cast<uint64_t>(new_body_param_idx)));
+ per_body_slots[b].push_back(new_param->output(0));
+ }
+ msg->set_input_descriptions(static_cast<int>(b), cur_descs);
+ return true;
+ }
+ // Opaque-forward branch (size 1): filling with zeros would corrupt a live KV cache. Leave unlowered.
+ // Empty branch (size 0) is safe to expand with zeros.
+ if (orig_branch_size == 1) {
+ return false;
+ }
+ for (size_t k = 0; k < N; ++k) {
+ auto dummy = make_zero_dummy(per_body_slots[ref][k]);
+ (void)cur_body;
+ per_body_slots[b].push_back(dummy);
+ }
+ return true;
+}
+
+std::optional<Slots> SlotResolver::slots_of_msg_output(const std::shared_ptr<ov::op::util::MultiSubGraphOp>& msg,
+ size_t out_idx) {
+ const size_t num_bodies = msg->get_internal_subgraphs_size();
+ std::vector<Slots> per_body_slots;
+ per_body_slots.reserve(num_bodies);
+ for (size_t b = 0; b < num_bodies; ++b) {
+ int result_idx = -1;
+ for (const auto& d : msg->get_output_descriptions(static_cast<int>(b))) {
+ if (d->m_output_index == out_idx) {
+ result_idx = static_cast<int>(d->m_body_value_index);
+ break;
+ }
+ }
+ if (result_idx < 0) {
+ return std::nullopt;
+ }
+ auto body = msg->get_function(b);
+ if (!body) {
+ return std::nullopt;
+ }
+ auto body_value = body->get_results()[result_idx]->input_value(0);
+ auto s = slots_of(body_value);
+ if (!s) {
+ return std::nullopt;
+ }
+ per_body_slots.push_back(std::move(*s));
+ }
+ if (per_body_slots.empty()) {
+ return std::nullopt;
+ }
+ // Reconcile slot counts across branches.
+ size_t N = 0;
+ for (const auto& s : per_body_slots) {
+ N = std::max(N, s.size());
+ }
+ if (N == 0) {
+ return std::nullopt;
+ }
+ for (size_t b = 0; b < per_body_slots.size(); ++b) {
+ if (per_body_slots[b].size() == N) {
+ continue;
+ }
+ // size 1: opaque-forward; size > 1 and < N: genuine cross-branch length mismatch.
+ if (per_body_slots[b].size() > 1 && per_body_slots[b].size() != N) {
+ return std::nullopt;
+ }
+ size_t ref = 0;
+ for (size_t bb = 0; bb < per_body_slots.size(); ++bb) {
+ if (per_body_slots[bb].size() == N) {
+ ref = bb;
+ break;
+ }
+ }
+ if (!expand_branch_to_n_slots(msg, b, ref, N, per_body_slots)) {
+ return std::nullopt;
+ }
+ }
+ for (const auto& s : per_body_slots) {
+ if (s.size() != N) {
+ return std::nullopt;
+ }
+ }
+
+ Slots outer_outputs;
+ outer_outputs.reserve(N);
+ if (auto if_op = ov::as_type_ptr<v8::If>(msg)) {
+ for (size_t k = 0; k < N; ++k) {
+ auto then_r = std::make_shared<v0::Result>(per_body_slots[0][k]);
+ auto else_r = std::make_shared<v0::Result>(per_body_slots[1][k]);
+ if_op->get_then_body()->add_results({then_r});
+ if_op->get_else_body()->add_results({else_r});
+ auto new_out = if_op->set_output(then_r, else_r);
+ outer_outputs.push_back(new_out);
+ }
+ } else if (auto loop = ov::as_type_ptr<v5::Loop>(msg)) {
+ for (size_t k = 0; k < N; ++k) {
+ ensure_body_result(loop->get_function(), per_body_slots[0][k]);
+ outer_outputs.push_back(loop->get_iter_value(per_body_slots[0][k]));
+ }
+ } else {
+ return std::nullopt;
+ }
+ changed_ = true;
+ return outer_outputs;
+}
+
+} // namespace sal_detail
+} // namespace pass
+} // namespace frontend
+} // namespace ov
diff --git a/src/frontends/common_translators/src/slot_resolver.hpp b/src/frontends/common_translators/src/slot_resolver.hpp
new file mode 100644
index 00000000000..5ecba6cd823
--- /dev/null
+++ b/src/frontends/common_translators/src/slot_resolver.hpp
@@ -0,0 +1,139 @@
+// Copyright (C) 2018-2026 Intel Corporation
+// SPDX-License-Identifier: Apache-2.0
+//
+
+#pragma once
+
+#include <map>
+#include <memory>
+#include <optional>
+#include <set>
+#include <utility>
+#include <vector>
+
+#include "openvino/core/model.hpp"
+#include "openvino/core/node.hpp"
+#include "openvino/core/partial_shape.hpp"
+#include "openvino/core/type/element_type.hpp"
+#include "openvino/op/loop.hpp"
+#include "openvino/op/parameter.hpp"
+#include "openvino/op/util/multi_subgraph_base.hpp"
+
+namespace ov {
+namespace frontend {
+namespace pass {
+namespace sal_detail {
+
+using Slots = std::vector<ov::Output<ov::Node>>;
+
+struct LengthTemplate {
+ std::vector<ov::Output<ov::Node>> slot_templates;
+};
+
+// Shape-preserving If-based select. Unlike v1::Select, does not broadcast branch
+// inputs - used when branches may have legitimately different shapes.
+ov::Output<ov::Node> make_shape_preserving_select(const ov::Output<ov::Node>& cond_in,
+ const ov::Output<ov::Node>& then_val,
+ const ov::Output<ov::Node>& else_val);
+
+// Strip a chain of v16::Identity wrappers, returning the underlying value.
+ov::Output<ov::Node> unwrap_identity(const ov::Output<ov::Node>& value);
+
+// Build a zero-filled Constant whose static dims match the template (dynamic dims -> 0).
+ov::Output<ov::Node> make_zero_dummy(const ov::Output<ov::Node>& tmpl);
+
+// Seed constant with static dims preserved, last dynamic axis set to 0
+// (growable concat axis), all other dynamic axes set to 1.
+ov::Output<ov::Node> make_growable_seed(const ov::PartialShape& ps, ov::element::Type et);
+
+// Maps each sequence-typed value to its vector of per-element "slot" tensors.
+// Crossing a MultiSubGraphOp (Loop/If) boundary, a sequence carried across
+// iterations is expanded into N parallel tensor back-edges:
+//
+// Loop( seqParam --..append..-- seqResult ) 1 sequence carrier
+// ||
+// vv
+// Loop( s0Param --..-- s0Result ) N tensor carriers
+// ( s1Param --..-- s1Result )
+// ( ... )
+class SlotResolver {
+public:
+ explicit SlotResolver(const std::shared_ptr<ov::Model>& root) : root_(root) {
+ build_maps(root_);
+ preallocate_loop_merged_params(root_);
+ }
+
+ bool changed() const {
+ return changed_;
+ }
+
+ std::optional<Slots> slots_of(const ov::Output<ov::Node>& value_in);
+
+ // True when `value` resolves to the per-element slots of a Loop merged
+ // input that was seeded from an empty sequence (SequenceEmpty). Such a
+ // sequence is loop-carried: its element count is a runtime property (0
+ // before the cache is first populated, N afterwards), not the compile-time
+ // slot count. SequenceLength over such a sequence must therefore lower to a
+ // runtime ShapeOf, not a static Constant — a static count freezes a
+ // `SequenceLength(cache) > 0` populated-ness gate to always-true and leaks
+ // the empty seed into the first iteration. See lower_sequence_length.
+ bool is_loop_carried_empty_seed(const ov::Output<ov::Node>& value);
+
+ // Resolve outer-seed and back-edge slots for every pre-allocated Loop
+ // merged-input entry and call set_merged_input. Must be invoked after
+ // all helper replacements have been performed (so the chains are stable)
+ // and before the final graph cleanup.
+ void finalize_pending_wiring();
+
+private:
+ struct PendingMerged {
+ // Known: outer seed is already the correct tensors.
+ // Deferred: outer seed will be resolved from the loop's outer input in finalize.
+ // Synthetic: outer seed is a zero-shape placeholder built from slot templates at
+ // pre-allocation time (SequenceEmpty source); must be rebuilt from the
+ // resolved back-edge slot shapes in finalize so the merged Parameter
+ // gets the correct rank.
+ enum class SeedKind { KNOWN, DEFERRED, SYNTHETIC };
+
+ std::shared_ptr<ov::op::v5::Loop> loop;
+ std::shared_ptr<ov::Model> body;
+ int back_edge_result_idx{-1};
+ int outer_input{-1};
+ std::shared_ptr<ov::op::v0::Parameter> old_param;
+ std::vector<std::shared_ptr<ov::op::v0::Parameter>> new_params;
+ Slots outer_seed_slots; // pre-resolved seed slots when SeedKind::KNOWN/SYNTHETIC
+ SeedKind seed_kind{SeedKind::KNOWN};
+ };
+
+ void build_maps(const std::shared_ptr<ov::Model>& m);
+ void preallocate_loop_merged_params(const std::shared_ptr<ov::Model>& m);
+ bool is_sequence_merged_input(const std::shared_ptr<ov::op::v5::Loop>& loop,
+ const std::shared_ptr<ov::Model>& body,
+ size_t p_idx,
+ size_t back_value_idx);
+ std::optional<Slots> slots_of_param(const std::shared_ptr<ov::op::v0::Parameter>& p);
+ std::optional<Slots> slots_of_msg_output(const std::shared_ptr<ov::op::util::MultiSubGraphOp>& msg, size_t out_idx);
+ // Expand branch `b` of `msg` from its current slot count (0 or 1) up to N
+ // slots, mirroring invariant Parameters from the reference branch when
+ // possible. Returns false when the branch cannot be safely expanded (opaque-
+ // forward with no mirrorable Parameters).
+ bool expand_branch_to_n_slots(const std::shared_ptr<ov::op::util::MultiSubGraphOp>& msg,
+ size_t b,
+ size_t ref,
+ size_t N,
+ std::vector<Slots>& per_body_slots);
+ std::optional<LengthTemplate> find_template_via_chain(const ov::Output<ov::Node>& root_value, ov::Node* exclude_p);
+
+ std::shared_ptr<ov::Model> root_;
+ std::vector<PendingMerged> pending_merged_;
+ std::map<ov::Output<ov::Node>, Slots> cache_;
+ std::set<ov::Output<ov::Node>> in_progress_;
+ std::map<ov::op::v0::Parameter*, std::shared_ptr<ov::Model>> param_to_model_;
+ std::map<ov::Model*, std::pair<std::shared_ptr<ov::op::util::MultiSubGraphOp>, int>> body_owner_;
+ bool changed_ = false;
+};
+
+} // namespace sal_detail
+} // namespace pass
+} // namespace frontend
+} // namespace ov
diff --git a/src/frontends/onnx/frontend/src/frontend.cpp b/src/frontends/onnx/frontend/src/frontend.cpp
index 0f77da433eb..56996cb8399 100644
--- a/src/frontends/onnx/frontend/src/frontend.cpp
+++ b/src/frontends/onnx/frontend/src/frontend.cpp
@@ -42,7 +42,9 @@
#include "openvino/op/result.hpp"
#include "openvino/util/log.hpp"
#include "ops_bridge.hpp"
+#include "sequence_array_lowering.hpp"
#include "sequence_concat_replacer.hpp"
+#include "sequence_if_replacer.hpp"
#include "transformations/resolve_names_collisions.hpp"
#include "translate_session.hpp"
#include "unconverted_ops_report.hpp"
@@ -269,6 +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<ov::frontend::pass::SequenceIfReplacer>();
+ manager.register_pass<ov::frontend::pass::SequenceArrayLowering>();
manager.register_pass<ov::frontend::pass::SequenceConcatReplacer>();
manager.register_pass<ov::pass::ResolveNameCollisions>(true);
manager.run_passes(model);
diff --git a/src/frontends/onnx/frontend/src/op/sequence_at.cpp b/src/frontends/onnx/frontend/src/op/sequence_at.cpp
index ba7cbd00824..b5ddece6bae 100644
--- a/src/frontends/onnx/frontend/src/op/sequence_at.cpp
+++ b/src/frontends/onnx/frontend/src/op/sequence_at.cpp
@@ -11,6 +11,8 @@
#include "openvino/core/type.hpp"
#include "openvino/core/validation_util.hpp"
#include "openvino/frontend/exception.hpp"
+#include "openvino/frontend/sequence_erase.hpp"
+#include "openvino/frontend/sequence_insert.hpp"
#include "openvino/frontend/sequence_mark.hpp"
#include "openvino/op/add.hpp"
#include "openvino/op/constant.hpp"
@@ -47,7 +49,20 @@ ov::OutputVector sequence_at(const ov::frontend::onnx::Node& node) {
position_value < 0 ? position_value + input_sequence_length : position_value;
OPENVINO_ASSERT(position_value_normalized >= 0 && position_value_normalized < input_sequence_length,
"SequenceAt: 'position' is out of bounds");
- return {seq.at(position_value_normalized)};
+ const auto& element = seq.at(position_value_normalized);
+ // get_sequence() keeps an Insert/Erase with a non-constant position
+ // (and a directly nested SequenceMark) as a single opaque element,
+ // i.e. a still-sequence-typed value rather than a resolved tensor.
+ // Selecting such an element here would return a sequence as if it
+ // were a tensor, so fall back to the deferred path, which resolves
+ // dynamic positions structurally.
+ const auto element_node = element.get_node_shared_ptr();
+ const bool element_is_opaque_sequence = ov::is_type<SequenceMark>(element_node) ||
+ ov::is_type<ov::frontend::SequenceInsert>(element_node) ||
+ ov::is_type<ov::frontend::SequenceErase>(element_node);
+ if (!element_is_opaque_sequence) {
+ return {element};
+ }
}
}
diff --git a/src/frontends/onnx/tests/models/controlflow/loop_if_kv_erase_insert.prototxt b/src/frontends/onnx/tests/models/controlflow/loop_if_kv_erase_insert.prototxt
new file mode 100644
index 00000000000..cfaba53ce8c
--- /dev/null
+++ b/src/frontends/onnx/tests/models/controlflow/loop_if_kv_erase_insert.prototxt
@@ -0,0 +1,278 @@
+ir_version: 7
+producer_name: "OpenVINO ONNX Frontend"
+graph {
+ node {
+ input: "init0"
+ input: "init1"
+ output: "seq_init"
+ op_type: "SequenceConstruct"
+ }
+ node {
+ input: "trip_count"
+ input: "cond_init"
+ input: "seq_init"
+ output: "seq_final"
+ op_type: "Loop"
+ attribute {
+ name: "body"
+ g {
+ node {
+ input: "cond_in"
+ output: "cond_out"
+ op_type: "Identity"
+ }
+ node {
+ input: "iter"
+ output: "iter_f"
+ op_type: "Cast"
+ attribute {
+ name: "to"
+ i: 1
+ type: INT
+ }
+ }
+ node {
+ input: "iter"
+ input: "two"
+ output: "iter_mod"
+ op_type: "Mod"
+ }
+ node {
+ input: "iter_mod"
+ input: "zero"
+ output: "pred"
+ op_type: "Equal"
+ }
+ node {
+ input: "pred"
+ output: "seq_out"
+ op_type: "If"
+ attribute {
+ name: "else_branch"
+ g {
+ node {
+ input: "seq_in"
+ output: "seq_else"
+ op_type: "Identity"
+ }
+ name: "else_body"
+ output {
+ name: "seq_else"
+ type {
+ sequence_type {
+ elem_type {
+ tensor_type {
+ elem_type: 1
+ }
+ }
+ }
+ }
+ }
+ }
+ type: GRAPH
+ }
+ attribute {
+ name: "then_branch"
+ g {
+ node {
+ input: "iter_f"
+ input: "shape_1d"
+ output: "val"
+ op_type: "Reshape"
+ }
+ node {
+ input: "seq_in"
+ output: "seq_short"
+ op_type: "SequenceErase"
+ }
+ node {
+ input: "seq_short"
+ input: "val"
+ output: "seq_then"
+ op_type: "SequenceInsert"
+ }
+ name: "then_body"
+ output {
+ name: "seq_then"
+ type {
+ sequence_type {
+ elem_type {
+ tensor_type {
+ elem_type: 1
+ }
+ }
+ }
+ }
+ }
+ }
+ type: GRAPH
+ }
+ }
+ name: "loop_body"
+ initializer {
+ dims: 1
+ data_type: 7
+ int64_data: 1
+ name: "shape_1d"
+ }
+ initializer {
+ data_type: 7
+ int64_data: 2
+ name: "two"
+ }
+ initializer {
+ data_type: 7
+ int64_data: 0
+ name: "zero"
+ }
+ 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
+ }
+ }
+ }
+ }
+ }
+ 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
+ }
+ }
+ }
+ }
+ }
+ }
+ type: GRAPH
+ }
+ }
+ node {
+ input: "seq_final"
+ input: "idx0"
+ output: "slot0"
+ op_type: "SequenceAt"
+ }
+ node {
+ input: "seq_final"
+ input: "idx1"
+ output: "slot1"
+ op_type: "SequenceAt"
+ }
+ node {
+ input: "slot0"
+ input: "slot1"
+ output: "output"
+ op_type: "Add"
+ }
+ name: "loop_if_kv_erase_insert"
+ initializer {
+ data_type: 7
+ int64_data: 0
+ name: "idx0"
+ }
+ initializer {
+ data_type: 7
+ int64_data: 1
+ name: "idx1"
+ }
+ input {
+ name: "trip_count"
+ type {
+ tensor_type {
+ elem_type: 7
+ shape {
+ }
+ }
+ }
+ }
+ input {
+ name: "cond_init"
+ type {
+ tensor_type {
+ elem_type: 9
+ shape {
+ }
+ }
+ }
+ }
+ input {
+ name: "init0"
+ type {
+ tensor_type {
+ elem_type: 1
+ shape {
+ dim {
+ dim_value: 1
+ }
+ }
+ }
+ }
+ }
+ input {
+ name: "init1"
+ type {
+ tensor_type {
+ elem_type: 1
+ shape {
+ dim {
+ dim_value: 1
+ }
+ }
+ }
+ }
+ }
+ output {
+ name: "output"
+ type {
+ tensor_type {
+ elem_type: 1
+ shape {
+ dim {
+ dim_value: 1
+ }
+ }
+ }
+ }
+ }
+}
+opset_import {
+ domain: ""
+ version: 14
+}
diff --git a/src/frontends/onnx/tests/models/controlflow/loop_if_multi_slot_kv_update.prototxt b/src/frontends/onnx/tests/models/controlflow/loop_if_multi_slot_kv_update.prototxt
new file mode 100644
index 00000000000..f0502ed3b14
--- /dev/null
+++ b/src/frontends/onnx/tests/models/controlflow/loop_if_multi_slot_kv_update.prototxt
@@ -0,0 +1,295 @@
+ir_version: 7
+producer_name: "OpenVINO ONNX Frontend"
+graph {
+ node {
+ input: "init0"
+ input: "init1"
+ output: "seq_init"
+ op_type: "SequenceConstruct"
+ }
+ node {
+ input: "trip_count"
+ input: "cond_init"
+ input: "seq_init"
+ output: "seq_final"
+ op_type: "Loop"
+ attribute {
+ name: "body"
+ g {
+ node {
+ input: "cond_in"
+ output: "cond_out"
+ op_type: "Identity"
+ }
+ node {
+ input: "iter"
+ output: "iter_f"
+ op_type: "Cast"
+ attribute {
+ name: "to"
+ i: 1
+ type: INT
+ }
+ }
+ node {
+ input: "iter_f"
+ input: "shape_1d"
+ output: "val_a"
+ op_type: "Reshape"
+ }
+ node {
+ input: "val_a"
+ input: "one_f"
+ output: "val_b"
+ op_type: "Add"
+ }
+ node {
+ input: "iter"
+ input: "two"
+ output: "iter_mod"
+ op_type: "Mod"
+ }
+ node {
+ input: "iter_mod"
+ input: "zero"
+ output: "pred"
+ op_type: "Equal"
+ }
+ node {
+ input: "pred"
+ output: "seq_out"
+ op_type: "If"
+ attribute {
+ name: "else_branch"
+ g {
+ node {
+ input: "seq_in"
+ output: "seq_else"
+ op_type: "Identity"
+ }
+ name: "else_body"
+ output {
+ name: "seq_else"
+ type {
+ sequence_type {
+ elem_type {
+ tensor_type {
+ elem_type: 1
+ }
+ }
+ }
+ }
+ }
+ }
+ type: GRAPH
+ }
+ attribute {
+ name: "then_branch"
+ g {
+ node {
+ input: "val_a"
+ output: "new0"
+ op_type: "Identity"
+ }
+ node {
+ input: "val_b"
+ output: "new1"
+ op_type: "Identity"
+ }
+ node {
+ input: "new0"
+ input: "new1"
+ output: "seq_then"
+ op_type: "SequenceConstruct"
+ }
+ name: "then_body"
+ output {
+ name: "seq_then"
+ type {
+ sequence_type {
+ elem_type {
+ tensor_type {
+ elem_type: 1
+ }
+ }
+ }
+ }
+ }
+ }
+ type: GRAPH
+ }
+ }
+ name: "loop_body"
+ initializer {
+ dims: 1
+ data_type: 7
+ int64_data: 1
+ name: "shape_1d"
+ }
+ initializer {
+ dims: 1
+ data_type: 1
+ float_data: 1.0
+ name: "one_f"
+ }
+ initializer {
+ data_type: 7
+ int64_data: 2
+ name: "two"
+ }
+ initializer {
+ data_type: 7
+ int64_data: 0
+ name: "zero"
+ }
+ 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
+ }
+ }
+ }
+ }
+ }
+ 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
+ }
+ }
+ }
+ }
+ }
+ }
+ type: GRAPH
+ }
+ }
+ node {
+ input: "seq_final"
+ input: "idx0"
+ output: "slot0"
+ op_type: "SequenceAt"
+ }
+ node {
+ input: "seq_final"
+ input: "idx1"
+ output: "slot1"
+ op_type: "SequenceAt"
+ }
+ node {
+ input: "slot0"
+ input: "slot1"
+ output: "output"
+ op_type: "Add"
+ }
+ name: "loop_if_multi_slot_kv_update"
+ initializer {
+ data_type: 7
+ int64_data: 0
+ name: "idx0"
+ }
+ initializer {
+ data_type: 7
+ int64_data: 1
+ name: "idx1"
+ }
+ input {
+ name: "trip_count"
+ type {
+ tensor_type {
+ elem_type: 7
+ shape {
+ }
+ }
+ }
+ }
+ input {
+ name: "cond_init"
+ type {
+ tensor_type {
+ elem_type: 9
+ shape {
+ }
+ }
+ }
+ }
+ input {
+ name: "init0"
+ type {
+ tensor_type {
+ elem_type: 1
+ shape {
+ dim {
+ dim_value: 1
+ }
+ }
+ }
+ }
+ }
+ input {
+ name: "init1"
+ type {
+ tensor_type {
+ elem_type: 1
+ shape {
+ dim {
+ dim_value: 1
+ }
+ }
+ }
+ }
+ }
+ output {
+ name: "output"
+ type {
+ tensor_type {
+ elem_type: 1
+ shape {
+ dim {
+ dim_value: 1
+ }
+ }
+ }
+ }
+ }
+}
+opset_import {
+ domain: ""
+ version: 14
+}
diff --git a/src/frontends/onnx/tests/models/controlflow/sal_if_rank_mismatch_repair.prototxt b/src/frontends/onnx/tests/models/controlflow/sal_if_rank_mismatch_repair.prototxt
new file mode 100644
index 00000000000..f213ccc3022
--- /dev/null
+++ b/src/frontends/onnx/tests/models/controlflow/sal_if_rank_mismatch_repair.prototxt
@@ -0,0 +1,147 @@
+ir_version: 7
+graph {
+ node {
+ input: "seq_a"
+ input: "seq_b"
+ output: "seq"
+ op_type: "SequenceConstruct"
+ }
+ node {
+ input: "seq"
+ output: "len"
+ op_type: "SequenceLength"
+ }
+ node {
+ input: "cond"
+ output: "if_out"
+ op_type: "If"
+ attribute {
+ name: "else_branch"
+ g {
+ node {
+ output: "else_val"
+ op_type: "Constant"
+ attribute {
+ name: "value"
+ t {
+ data_type: 1
+ float_data: 0
+ name: "else_val"
+ }
+ type: TENSOR
+ }
+ }
+ name: "else_body"
+ output {
+ name: "else_val"
+ type {
+ tensor_type {
+ elem_type: 1
+ shape {
+ }
+ }
+ }
+ }
+ }
+ type: GRAPH
+ }
+ attribute {
+ name: "then_branch"
+ g {
+ node {
+ output: "then_val"
+ op_type: "Constant"
+ attribute {
+ name: "value"
+ t {
+ dims: 2
+ data_type: 1
+ float_data: 1
+ float_data: 2
+ name: "then_val"
+ }
+ type: TENSOR
+ }
+ }
+ name: "then_body"
+ output {
+ name: "then_val"
+ type {
+ tensor_type {
+ elem_type: 1
+ shape {
+ dim {
+ dim_value: 2
+ }
+ }
+ }
+ }
+ }
+ }
+ type: GRAPH
+ }
+ }
+ name: "sal_if_rank_mismatch_repair"
+ input {
+ name: "cond"
+ type {
+ tensor_type {
+ elem_type: 9
+ shape {
+ }
+ }
+ }
+ }
+ input {
+ name: "seq_a"
+ type {
+ tensor_type {
+ elem_type: 1
+ shape {
+ dim {
+ dim_value: 2
+ }
+ }
+ }
+ }
+ }
+ input {
+ name: "seq_b"
+ type {
+ tensor_type {
+ elem_type: 1
+ shape {
+ dim {
+ dim_value: 2
+ }
+ }
+ }
+ }
+ }
+ output {
+ name: "if_out"
+ type {
+ tensor_type {
+ elem_type: 1
+ shape {
+ dim {
+ }
+ }
+ }
+ }
+ }
+ output {
+ name: "len"
+ type {
+ tensor_type {
+ elem_type: 7
+ shape {
+ }
+ }
+ }
+ }
+}
+opset_import {
+ domain: ""
+ version: 15
+}
diff --git a/src/frontends/onnx/tests/models/controlflow/sal_sequence_length_runtime_gate.prototxt b/src/frontends/onnx/tests/models/controlflow/sal_sequence_length_runtime_gate.prototxt
new file mode 100644
index 00000000000..656a90fc0c9
--- /dev/null
+++ b/src/frontends/onnx/tests/models/controlflow/sal_sequence_length_runtime_gate.prototxt
@@ -0,0 +1,327 @@
+ir_version: 9
+graph {
+ node {
+ output: "empty_cache"
+ op_type: "SequenceEmpty"
+ }
+ node {
+ input: "trip_count"
+ input: "cond_init"
+ input: "empty_cache"
+ input: "acc_init"
+ output: "cache_final"
+ output: "acc_final"
+ op_type: "Loop"
+ attribute {
+ name: "body"
+ g {
+ node {
+ input: "cache_in"
+ output: "cache_len"
+ op_type: "SequenceLength"
+ }
+ node {
+ output: "zero_i64"
+ op_type: "Constant"
+ attribute {
+ name: "value"
+ t {
+ data_type: 7
+ int64_data: 0
+ name: "z"
+ }
+ type: TENSOR
+ }
+ }
+ node {
+ input: "cache_len"
+ input: "zero_i64"
+ output: "is_populated"
+ op_type: "Greater"
+ }
+ node {
+ input: "is_populated"
+ output: "cache_out"
+ op_type: "If"
+ attribute {
+ name: "else_branch"
+ g {
+ node {
+ input: "v0"
+ input: "v1"
+ output: "cache_sel"
+ op_type: "SequenceConstruct"
+ }
+ name: "else_build"
+ output {
+ name: "cache_sel"
+ type {
+ sequence_type {
+ elem_type {
+ tensor_type {
+ elem_type: 1
+ }
+ }
+ }
+ }
+ }
+ }
+ type: GRAPH
+ }
+ attribute {
+ name: "then_branch"
+ g {
+ node {
+ output: "t_i0"
+ op_type: "Constant"
+ attribute {
+ name: "value"
+ t {
+ data_type: 7
+ int64_data: 0
+ name: "ti0"
+ }
+ type: TENSOR
+ }
+ }
+ node {
+ output: "t_i1"
+ op_type: "Constant"
+ attribute {
+ name: "value"
+ t {
+ data_type: 7
+ int64_data: 1
+ name: "ti1"
+ }
+ type: TENSOR
+ }
+ }
+ node {
+ input: "cache_in"
+ input: "t_i0"
+ output: "t_s0"
+ op_type: "SequenceAt"
+ }
+ node {
+ input: "cache_in"
+ input: "t_i1"
+ output: "t_s1"
+ op_type: "SequenceAt"
+ }
+ node {
+ input: "t_s0"
+ input: "t_s1"
+ output: "cache_sel"
+ op_type: "SequenceConstruct"
+ }
+ name: "then_forward"
+ output {
+ name: "cache_sel"
+ type {
+ sequence_type {
+ elem_type {
+ tensor_type {
+ elem_type: 1
+ }
+ }
+ }
+ }
+ }
+ }
+ type: GRAPH
+ }
+ }
+ node {
+ output: "idx0"
+ op_type: "Constant"
+ attribute {
+ name: "value"
+ t {
+ data_type: 7
+ int64_data: 0
+ name: "i0"
+ }
+ type: TENSOR
+ }
+ }
+ node {
+ input: "cache_out"
+ input: "idx0"
+ output: "slot0"
+ op_type: "SequenceAt"
+ }
+ node {
+ input: "acc_in"
+ input: "slot0"
+ output: "acc_out"
+ op_type: "Add"
+ }
+ node {
+ input: "cond_in"
+ output: "cond_out"
+ op_type: "Identity"
+ }
+ name: "loop_body"
+ input {
+ name: "iter_num"
+ type {
+ tensor_type {
+ elem_type: 7
+ shape {
+ }
+ }
+ }
+ }
+ input {
+ name: "cond_in"
+ type {
+ tensor_type {
+ elem_type: 9
+ shape {
+ }
+ }
+ }
+ }
+ input {
+ name: "cache_in"
+ type {
+ sequence_type {
+ elem_type {
+ tensor_type {
+ elem_type: 1
+ }
+ }
+ }
+ }
+ }
+ input {
+ name: "acc_in"
+ type {
+ tensor_type {
+ elem_type: 1
+ shape {
+ dim {
+ dim_value: 1
+ }
+ }
+ }
+ }
+ }
+ output {
+ name: "cond_out"
+ type {
+ tensor_type {
+ elem_type: 9
+ shape {
+ }
+ }
+ }
+ }
+ output {
+ name: "cache_out"
+ type {
+ sequence_type {
+ elem_type {
+ tensor_type {
+ elem_type: 1
+ }
+ }
+ }
+ }
+ }
+ output {
+ name: "acc_out"
+ type {
+ tensor_type {
+ elem_type: 1
+ shape {
+ dim {
+ dim_value: 1
+ }
+ }
+ }
+ }
+ }
+ }
+ type: GRAPH
+ }
+ }
+ name: "sal_seqlen_gate"
+ input {
+ name: "trip_count"
+ type {
+ tensor_type {
+ elem_type: 7
+ shape {
+ }
+ }
+ }
+ }
+ input {
+ name: "cond_init"
+ type {
+ tensor_type {
+ elem_type: 9
+ shape {
+ }
+ }
+ }
+ }
+ input {
+ name: "v0"
+ type {
+ tensor_type {
+ elem_type: 1
+ shape {
+ dim {
+ dim_value: 1
+ }
+ }
+ }
+ }
+ }
+ input {
+ name: "v1"
+ type {
+ tensor_type {
+ elem_type: 1
+ shape {
+ dim {
+ dim_value: 1
+ }
+ }
+ }
+ }
+ }
+ input {
+ name: "acc_init"
+ type {
+ tensor_type {
+ elem_type: 1
+ shape {
+ dim {
+ dim_value: 1
+ }
+ }
+ }
+ }
+ }
+ output {
+ name: "acc_final"
+ type {
+ tensor_type {
+ elem_type: 1
+ shape {
+ dim {
+ dim_value: 1
+ }
+ }
+ }
+ }
+ }
+}
+opset_import {
+ domain: ""
+ version: 13
+}
diff --git a/src/frontends/onnx/tests/models/controlflow/sal_sequence_length_static_n.prototxt b/src/frontends/onnx/tests/models/controlflow/sal_sequence_length_static_n.prototxt
new file mode 100644
index 00000000000..b64c1b502da
--- /dev/null
+++ b/src/frontends/onnx/tests/models/controlflow/sal_sequence_length_static_n.prototxt
@@ -0,0 +1,69 @@
+ir_version: 7
+graph {
+ node {
+ input: "a"
+ input: "b"
+ input: "c"
+ output: "seq"
+ op_type: "SequenceConstruct"
+ }
+ node {
+ input: "seq"
+ output: "len"
+ op_type: "SequenceLength"
+ }
+ name: "sal_sequence_length_static_n"
+ input {
+ name: "a"
+ type {
+ tensor_type {
+ elem_type: 1
+ shape {
+ dim {
+ dim_value: 2
+ }
+ }
+ }
+ }
+ }
+ input {
+ name: "b"
+ type {
+ tensor_type {
+ elem_type: 1
+ shape {
+ dim {
+ dim_value: 2
+ }
+ }
+ }
+ }
+ }
+ input {
+ name: "c"
+ type {
+ tensor_type {
+ elem_type: 1
+ shape {
+ dim {
+ dim_value: 2
+ }
+ }
+ }
+ }
+ }
+ output {
+ name: "len"
+ type {
+ tensor_type {
+ elem_type: 7
+ shape {
+ }
+ }
+ }
+ }
+}
+opset_import {
+ domain: ""
+ version: 15
+}
diff --git a/src/frontends/onnx/tests/onnx_import_controlflow.in.cpp b/src/frontends/onnx/tests/onnx_import_controlflow.in.cpp
index 6cf3ac87243..86adba998a9 100644
--- a/src/frontends/onnx/tests/onnx_import_controlflow.in.cpp
+++ b/src/frontends/onnx/tests/onnx_import_controlflow.in.cpp
@@ -941,3 +941,136 @@ OPENVINO_TEST(${BACKEND_NAME}, onnx_sequence_insert_chain_new_axis) {
test_case.add_expected_output<float>(Shape{3, 2}, {1.f, 2.f, 3.f, 4.f, 5.f, 6.f});
test_case.run();
}
+
+/// @brief Regression: fixed-N multi-slot sequence carried through a Loop and
+/// conditionally updated by an inner If, then read back via SequenceAt.
+///
+/// The else branch forwards the incoming sequence unchanged (resolving to a
+/// single opaque slot) while the then branch rebuilds the N=2 slot sequence.
+/// This is the SAL slot-resolution case that previously mis-counted the
+/// Loop merged-input slots (1-vs-N reconcile + back-edge undercount), leaving
+/// the SequenceAt consumers unconverted. With the fix the model must lower to
+/// native ops and produce the correct per-slot values.
+OPENVINO_TEST(${BACKEND_NAME}, onnx_loop_if_multi_slot_kv_update) {
+ const auto model = convert_model("controlflow/loop_if_multi_slot_kv_update.onnx");
+
+ auto test_case = ov::test::TestCase(model, s_device);
+ test_case.add_input<int64_t>({3}); // trip_count
+ test_case.add_input<bool>({true}); // cond_init
+ test_case.add_input<float>({10.f}); // init0
+ test_case.add_input<float>({20.f}); // init1
+
+ // Even iterations (0, 2) rebuild the 2-slot cache to [iter], [iter+1];
+ // odd iteration (1) forwards the cache. After 3 iterations the slots are
+ // [2] and [3], and the model returns slot0 + slot1 = [5].
+ test_case.add_expected_output<float>(Shape{1}, {5.f});
+ test_case.run();
+}
+
+/// @brief Regression: same Loop+If KV-cache pattern, but the then branch
+/// evicts the last slot (SequenceErase) and appends a fresh value
+/// (SequenceInsert) on the live sequence instead of rebuilding it.
+///
+/// Exercises the SequenceErase lowering and SequenceInsert-on-resolved-base
+/// slot reconciliation together with the else-branch passthrough, ensuring the
+/// element type and slot templates of the disconnected back-edge are preserved.
+OPENVINO_TEST(${BACKEND_NAME}, onnx_loop_if_kv_erase_insert) {
+ const auto model = convert_model("controlflow/loop_if_kv_erase_insert.onnx");
+
+ auto test_case = ov::test::TestCase(model, s_device);
+ test_case.add_input<int64_t>({3}); // trip_count
+ test_case.add_input<bool>({true}); // cond_init
+ test_case.add_input<float>({10.f}); // init0
+ test_case.add_input<float>({20.f}); // init1
+
+ // init [10, 20]; iter0 (even): erase last -> [10], insert 0 -> [10, 0];
+ // iter1 (odd): passthrough [10, 0]; iter2 (even): erase last -> [10],
+ // insert 2 -> [10, 2]. Result slot0 + slot1 = 10 + 2 = [12].
+ test_case.add_expected_output<float>(Shape{1}, {12.f});
+ test_case.run();
+}
+
+/// @brief SAL SequenceLength static-slot-count fallback.
+///
+/// SequenceConstruct(a, b, c) → SequenceLength. The ONNX FE resolves the
+/// length directly to a compile-time Constant (3) via the SequenceMark fast
+/// path. This test guards against regressions in SequenceLength resolution for
+/// fully-static sequences.
+OPENVINO_TEST(${BACKEND_NAME}, onnx_sal_sequence_length_static_n_fallback) {
+ const auto model = convert_model("controlflow/sal_sequence_length_static_n.onnx");
+
+ auto test_case = ov::test::TestCase(model, s_device);
+ test_case.add_input<float>({1.f, 2.f}); // a
+ test_case.add_input<float>({3.f, 4.f}); // b
+ test_case.add_input<float>({5.f, 6.f}); // c
+
+ // SequenceLength of a 3-element sequence must be the scalar int64 value 3.
+ test_case.add_expected_output<int64_t>(Shape{}, {3});
+ test_case.run();
+}
+
+/// @brief If with rank-mismatched branches: read, clone, and run.
+///
+/// The If node has an intentional rank mismatch: the then-branch returns a
+/// rank-1 Constant [1.0, 2.0] (shape [2]) while the else-branch returns a
+/// rank-0 scalar placeholder 0.0 (shape []).
+///
+/// ONNX FE converts this as-is; the model output has a static rank of 1 but
+/// an unknown extent (declared as float[?] in the ONNX graph). The test
+/// verifies that:
+/// 1. read_model() succeeds without an exception.
+/// 2. model->clone() succeeds (guards against stale topological-cache bugs
+/// that would cause std::out_of_range in clone_ov_nodes).
+/// 3. Inference with cond=true produces [1.0, 2.0] (then-branch value) and
+/// len=2 (SequenceLength of the 2-element float sequence).
+OPENVINO_TEST(${BACKEND_NAME}, onnx_sal_if_rank_mismatch_repair) {
+ const auto model = convert_model("controlflow/sal_if_rank_mismatch_repair.onnx");
+
+ // The declared ONNX output type is float[?] (rank-1, unknown extent).
+ EXPECT_TRUE(model->get_output_partial_shape(0).rank().is_static());
+ EXPECT_EQ(model->get_output_partial_shape(0).rank().get_length(), 1);
+ // SequenceLength output is a scalar int64.
+ EXPECT_EQ(model->get_output_partial_shape(1), ov::PartialShape{});
+
+ // Model::clone() must succeed.
+ EXPECT_NO_THROW(model->clone());
+
+ auto test_case = ov::test::TestCase(model, s_device);
+ // cond=true: then-branch fires, if_out = [1.0, 2.0] (the then-branch Constant).
+ test_case.add_input<bool>({true}); // cond
+ test_case.add_input<float>({7.f, 8.f}); // seq_a (feeds SequenceLength only)
+ test_case.add_input<float>({9.f, 0.f}); // seq_b
+ test_case.add_expected_output<float>(Shape{2}, {1.f, 2.f}); // if_out
+ test_case.add_expected_output<int64_t>(Shape{}, {2}); // len
+ test_case.run();
+}
+
+/// @brief SAL SequenceLength over a loop-carried (empty-seeded) cache must lower
+/// to a RUNTIME length, not the static slot count.
+///
+/// An outer Loop carries a sequence cache seeded from SequenceEmpty. Each body
+/// iteration gates on `SequenceLength(cache) > 0`: iteration 0 (empty cache,
+/// length 0) builds a fresh 2-element sequence [v0, v1]; later iterations
+/// (length 2) forward the carried cache. The body reads slot 0 and accumulates.
+///
+/// SAL lowers the cache to a fixed 2 slots. If SequenceLength were lowered to
+/// the static slot count (2), `Greater(2, 0)` would fold to always-true, the
+/// build branch would become dead, and the empty seed would leak into iteration
+/// 0 — yielding a wrong result (and, on real KV-cache models, a runtime shape
+/// mismatch). The correct lowering reports 0 on the empty iteration and 2 once
+/// the cache is populated, so the gate behaves as in ONNX Runtime.
+///
+/// With trip_count=3, v0=10, v1=20, acc_init=0: build [10, 20] on iter 0, then
+/// forward; slot 0 (=10) is accumulated on all 3 iterations -> 30.
+OPENVINO_TEST(${BACKEND_NAME}, onnx_sal_sequence_length_runtime_gate) {
+ const auto model = convert_model("controlflow/sal_sequence_length_runtime_gate.onnx");
+
+ auto test_case = ov::test::TestCase(model, s_device);
+ test_case.add_input<int64_t>({3}); // trip_count
+ test_case.add_input<bool>({true}); // cond_init
+ test_case.add_input<float>({10.f}); // v0
+ test_case.add_input<float>({20.f}); // v1
+ test_case.add_input<float>({0.f}); // acc_init
+ test_case.add_expected_output<float>(Shape{1}, {30.f});
+ test_case.run();
+}
diff --git a/src/frontends/onnx/tests/runtime/interpreter/unit_test.manifest b/src/frontends/onnx/tests/runtime/interpreter/unit_test.manifest
index 82fa651aaf6..fa44b24c8a9 100644
--- a/src/frontends/onnx/tests/runtime/interpreter/unit_test.manifest
+++ b/src/frontends/onnx/tests/runtime/interpreter/unit_test.manifest
@@ -17,6 +17,9 @@ onnx_dyn_model_hardmax
INTERPRETER.onnx_if_inside_if
INTERPRETER.onnx_if_inside_loop
INTERPRETER.onnx_if_inside_if_inside_loop
+INTERPRETER.onnx_loop_if_multi_slot_kv_update
+INTERPRETER.onnx_loop_if_kv_erase_insert
+INTERPRETER.onnx_sal_sequence_length_runtime_gate
# Activation function hardsigmoid unsupported
onnx_model_gru_fwd_activations_relu_hardsigmoid
diff --git a/src/frontends/onnx/tests/tests_python/test_backend.py b/src/frontends/onnx/tests/tests_python/test_backend.py
index c461c2957b8..30a9fc5c449 100644
--- a/src/frontends/onnx/tests/tests_python/test_backend.py
+++ b/src/frontends/onnx/tests/tests_python/test_backend.py
@@ -147,8 +147,6 @@ tests_expected_to_fail = [
),
(
xfail_issue_33596,
- "OnnxBackendSimpleModelTest.test_sequence_model1_cpu",
- "OnnxBackendSimpleModelTest.test_sequence_model3_cpu",
"OnnxBackendNodeModelTest.test_identity_sequence_cpu",
"OnnxBackendNodeModelTest.test_if_seq_cpu",
"OnnxBackendNodeModelTest.test_if_opt_cpu", # Optional, SequenceConstruct