Skip to content

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

[Transformations] Restore traced batch dimension (#38389)

Mikhail Ryzhovf260f670590a
diff --git a/src/common/transformations/include/sources.cmake b/src/common/transformations/include/sources.cmake
index 0ba6da35066..1435b13074d 100644
--- a/src/common/transformations/include/sources.cmake
+++ b/src/common/transformations/include/sources.cmake
@@ -325,6 +325,7 @@ set(SMART_RESHAPE_HEADERS
${CMAKE_CURRENT_LIST_DIR}/transformations/smart_reshape/proposal_scales_stridedslice.hpp
${CMAKE_CURRENT_LIST_DIR}/transformations/smart_reshape/reshape_sinking.hpp
${CMAKE_CURRENT_LIST_DIR}/transformations/smart_reshape/reshape_to_1D.hpp
+ ${CMAKE_CURRENT_LIST_DIR}/transformations/smart_reshape/restore_traced_batch.hpp
${CMAKE_CURRENT_LIST_DIR}/transformations/smart_reshape/shape_of_const_folding.hpp
${CMAKE_CURRENT_LIST_DIR}/transformations/smart_reshape/smart_reshape.hpp
${CMAKE_CURRENT_LIST_DIR}/transformations/smart_reshape/strided_slice_squeeze.hpp
diff --git a/src/common/transformations/include/transformations/smart_reshape/restore_traced_batch.hpp b/src/common/transformations/include/transformations/smart_reshape/restore_traced_batch.hpp
new file mode 100644
index 00000000000..fde1957e0af
--- /dev/null
+++ b/src/common/transformations/include/transformations/smart_reshape/restore_traced_batch.hpp
@@ -0,0 +1,65 @@
+// Copyright (C) 2018-2026 Intel Corporation
+// SPDX-License-Identifier: Apache-2.0
+//
+
+#pragma once
+
+#include "openvino/pass/matcher_pass.hpp"
+#include "transformations_visibility.hpp"
+
+namespace ov {
+namespace pass {
+
+class TRANSFORMATIONS_API RestoreTracedBatch;
+
+} // namespace pass
+} // namespace ov
+
+/**
+ * @ingroup ov_transformation_common_api
+ * @brief Restores the batch that tracing froze to one in a `window_reverse` subgraph.
+ *
+ * A traced `window_reverse` may compute its batch as `int(windows.shape[0] / (H * W / ws / ws))`, which tracing with
+ * batch one turns into a constant. Only this subgraph is matched: a leading constant one cannot be told apart from an
+ * intentional collapse in general, so the pass is not a generic batch restoration.
+ *
+ * In both pinned targets the baked constant one is replaced with the batch read from the `Parameter` shape, reusing
+ * the `Gather(ShapeOf(Parameter), 0)` that the last `Reshape` already takes it from, optionally through a `Convert`.
+ * The targets are edited in place: the baked dimension belongs to the shape tensor, so every `Reshape` reading it
+ * needs the same restored batch.
+ *
+ * ## Before
+ *
+ * windows [B * nW, ws, ws, C]
+ * |
+ * Reshape(Concat(1, H / ws, W / ws, ws, ws, -1)) (batch pinned by tracing)
+ * |
+ * Transpose(axis 0 preserved)
+ * |
+ * Reshape(Concat(1, H, W, -1)) (batch pinned by tracing)
+ * |
+ * Roll(non-leading axes) (optional, shifted windows)
+ * |
+ * Reshape(Concat(Gather(ShapeOf(Parameter), 0), H * W, C))
+ *
+ * Every node between the two pinned `Reshape`s and the last one must have a single consumer.
+ *
+ * ## After
+ *
+ * windows [B * nW, ws, ws, C]
+ * |
+ * Reshape(Concat(Gather(ShapeOf(Parameter), 0), H / ws, W / ws, ws, ws, -1))
+ * |
+ * Transpose(axis 0 preserved)
+ * |
+ * Reshape(Concat(Gather(ShapeOf(Parameter), 0), H, W, -1))
+ * |
+ * Roll(non-leading axes)
+ * |
+ * Reshape(Concat(Gather(ShapeOf(Parameter), 0), H * W, C))
+ */
+class ov::pass::RestoreTracedBatch : public ov::pass::MatcherPass {
+public:
+ OPENVINO_MATCHER_PASS_RTTI("RestoreTracedBatch");
+ RestoreTracedBatch();
+};
diff --git a/src/common/transformations/src/sources.cmake b/src/common/transformations/src/sources.cmake
index a5ba00a8166..0f6aa80888e 100644
--- a/src/common/transformations/src/sources.cmake
+++ b/src/common/transformations/src/sources.cmake
@@ -288,6 +288,7 @@ set(SMART_RESHAPE_SOURCES
${CMAKE_CURRENT_LIST_DIR}/transformations/smart_reshape/proposal_scales_stridedslice.cpp
${CMAKE_CURRENT_LIST_DIR}/transformations/smart_reshape/reshape_sinking.cpp
${CMAKE_CURRENT_LIST_DIR}/transformations/smart_reshape/reshape_to_1D.cpp
+ ${CMAKE_CURRENT_LIST_DIR}/transformations/smart_reshape/restore_traced_batch.cpp
${CMAKE_CURRENT_LIST_DIR}/transformations/smart_reshape/shape_of_const_folding.cpp
${CMAKE_CURRENT_LIST_DIR}/transformations/smart_reshape/smart_reshape.cpp
${CMAKE_CURRENT_LIST_DIR}/transformations/smart_reshape/strided_slice_squeeze.cpp
diff --git a/src/common/transformations/src/transformations/smart_reshape/restore_traced_batch.cpp b/src/common/transformations/src/transformations/smart_reshape/restore_traced_batch.cpp
new file mode 100644
index 00000000000..7e23375d72a
--- /dev/null
+++ b/src/common/transformations/src/transformations/smart_reshape/restore_traced_batch.cpp
@@ -0,0 +1,116 @@
+// Copyright (C) 2018-2026 Intel Corporation
+// SPDX-License-Identifier: Apache-2.0
+//
+
+#include "transformations/smart_reshape/restore_traced_batch.hpp"
+
+#include <algorithm>
+#include <memory>
+
+#include "itt.hpp"
+#include "openvino/core/validation_util.hpp"
+#include "openvino/op/concat.hpp"
+#include "openvino/op/constant.hpp"
+#include "openvino/op/convert.hpp"
+#include "openvino/op/parameter.hpp"
+#include "openvino/op/reshape.hpp"
+#include "openvino/op/roll.hpp"
+#include "openvino/op/transpose.hpp"
+#include "openvino/op/util/gather_base.hpp"
+#include "openvino/op/util/shape_of_base.hpp"
+#include "openvino/pass/pattern/matcher.hpp"
+#include "openvino/pass/pattern/op/optional.hpp"
+#include "openvino/pass/pattern/op/wrap_type.hpp"
+#include "openvino/util/pp.hpp"
+
+namespace v0 = ov::op::v0;
+namespace v1 = ov::op::v1;
+namespace v7 = ov::op::v7;
+
+namespace {
+
+// The restored batch must stay the leading axis; otherwise it was not the traced batch.
+bool transpose_keeps_batch_leading(const ov::Output<ov::Node>& order) {
+ const auto values = ov::as_type<v0::Constant>(order.get_node())->cast_vector<int64_t>();
+ return !values.empty() && values.front() == 0;
+}
+
+// Rolling over the traced batch of one is a no-op, but over a restored batch it would mix samples.
+bool roll_skips_batch(const ov::Output<ov::Node>& roll) {
+ const auto rank = roll.get_partial_shape().rank();
+ const auto axes = ov::as_type<v0::Constant>(roll.get_node()->get_input_node_ptr(2));
+ if (rank.is_dynamic() || !axes) {
+ return false;
+ }
+ const auto values = axes->cast_vector<int64_t>();
+ return std::none_of(values.begin(), values.end(), [&](int64_t axis) {
+ return ov::util::normalize_axis(axis, rank.get_length()) == 0;
+ });
+}
+
+} // namespace
+
+ov::pass::RestoreTracedBatch::RestoreTracedBatch() {
+ MATCHER_SCOPE(RestoreTracedBatch);
+
+ using ov::pass::pattern::any_input;
+ using ov::pass::pattern::attrs_match;
+ using ov::pass::pattern::consumers_count;
+ using ov::pass::pattern::value_matches;
+ using ov::pass::pattern::wrap_type;
+
+ const auto axis_zero = attrs_match({{"axis", 0}});
+
+ // window_reverse: view(B, H / ws, W / ws, ws, ws, -1) with B traced to one.
+ const auto p_window_split_target = wrap_type<v0::Concat>({wrap_type<v0::Constant>(value_matches("1")),
+ any_input(),
+ any_input(),
+ any_input(),
+ any_input(),
+ wrap_type<v0::Constant>(value_matches("-1"))},
+ axis_zero);
+ const auto p_window_split_reshape =
+ wrap_type<v1::Reshape>({any_input(), p_window_split_target}, consumers_count(1));
+ const auto p_permute =
+ wrap_type<v1::Transpose>({p_window_split_reshape, wrap_type<v0::Constant>(transpose_keeps_batch_leading)},
+ consumers_count(1));
+
+ // window_reverse: view(B, H, W, -1) with B traced to one.
+ const auto p_window_merge_target = wrap_type<v0::Concat>({wrap_type<v0::Constant>(value_matches("1")),
+ any_input(),
+ any_input(),
+ wrap_type<v0::Constant>(value_matches("-1"))},
+ axis_zero);
+ const auto p_window_merge_reshape = wrap_type<v1::Reshape>({p_permute, p_window_merge_target}, consumers_count(1));
+
+ // Reverse cyclic shift of shifted windows.
+ const auto p_shift =
+ ov::pass::pattern::optional<v7::Roll>({p_window_merge_reshape, any_input(), wrap_type<v0::Constant>()},
+ consumers_count(1) && roll_skips_batch);
+
+ // view(B, H * W, C) taking B from the input shape.
+ const auto p_input_batch = ov::pass::pattern::optional<v0::Convert>(
+ {wrap_type<ov::op::util::GatherBase>({wrap_type<ov::op::util::ShapeOfBase>({wrap_type<v0::Parameter>()}),
+ wrap_type<v0::Constant>(value_matches("0")),
+ any_input()})});
+ const auto p_rebuild_target = wrap_type<v0::Concat>({p_input_batch, any_input(), any_input()}, axis_zero);
+ const auto p_rebuild = wrap_type<v1::Reshape>({p_shift, p_rebuild_target});
+
+ ov::matcher_pass_callback callback = [OV_CAPTURE_CPY_AND_THIS](ov::pass::pattern::Matcher& matcher) {
+ const auto& pattern_map = matcher.get_pattern_value_map();
+ // An absent optional Convert leaves no record, so the batch is read from the matched target.
+ const auto batch = pattern_map.at(p_rebuild_target).get_node()->input_value(0);
+ const auto split_target = pattern_map.at(p_window_split_target);
+ const auto merge_target = pattern_map.at(p_window_merge_target);
+ if (split_target.get_element_type() != batch.get_element_type() ||
+ merge_target.get_element_type() != batch.get_element_type()) {
+ return false;
+ }
+
+ split_target.get_node()->input(0).replace_source_output(batch);
+ merge_target.get_node()->input(0).replace_source_output(batch);
+ return true;
+ };
+
+ register_matcher(std::make_shared<ov::pass::pattern::Matcher>(p_rebuild, matcher_name), callback);
+}
diff --git a/src/common/transformations/src/transformations/smart_reshape/smart_reshape.cpp b/src/common/transformations/src/transformations/smart_reshape/smart_reshape.cpp
index 298d85289ce..f8f5e589ee4 100644
--- a/src/common/transformations/src/transformations/smart_reshape/smart_reshape.cpp
+++ b/src/common/transformations/src/transformations/smart_reshape/smart_reshape.cpp
@@ -16,6 +16,7 @@
#include "transformations/smart_reshape/proposal_scales_stridedslice.hpp"
#include "transformations/smart_reshape/reshape_sinking.hpp"
#include "transformations/smart_reshape/reshape_to_1D.hpp"
+#include "transformations/smart_reshape/restore_traced_batch.hpp"
#include "transformations/smart_reshape/shape_of_const_folding.hpp"
#include "transformations/smart_reshape/strided_slice_squeeze.hpp"
@@ -24,6 +25,7 @@ bool ov::pass::SmartReshape::run_on_model(const std::shared_ptr<ov::Model>& f) {
ov::pass::Manager static_manager("SmartReshape:static");
// This pass must be called first in pipeline
static_manager.register_pass<ov::pass::InitNodeInfo>();
+ static_manager.register_pass<ov::pass::RestoreTracedBatch>();
static_manager.register_pass<ov::pass::ReshapeTo1D>();
static_manager.register_pass<ov::pass::Proposal1Scales>();
static_manager.register_pass<ov::pass::Proposal4Scales>();
diff --git a/src/common/transformations/tests/smart_reshape/restore_traced_batch.cpp b/src/common/transformations/tests/smart_reshape/restore_traced_batch.cpp
new file mode 100644
index 00000000000..331c4219510
--- /dev/null
+++ b/src/common/transformations/tests/smart_reshape/restore_traced_batch.cpp
@@ -0,0 +1,238 @@
+// Copyright (C) 2018-2026 Intel Corporation
+// SPDX-License-Identifier: Apache-2.0
+//
+
+#include "transformations/smart_reshape/restore_traced_batch.hpp"
+
+#include <gtest/gtest.h>
+
+#include <set>
+#include <string>
+
+#include "common_test_utils/ov_test_utils.hpp"
+#include "openvino/op/concat.hpp"
+#include "openvino/op/constant.hpp"
+#include "openvino/op/convert.hpp"
+#include "openvino/op/gather.hpp"
+#include "openvino/op/parameter.hpp"
+#include "openvino/op/reshape.hpp"
+#include "openvino/op/result.hpp"
+#include "openvino/op/roll.hpp"
+#include "openvino/op/shape_of.hpp"
+#include "openvino/op/transpose.hpp"
+
+using namespace ov;
+
+namespace {
+
+Output<Node> i64(const std::vector<int64_t>& values) {
+ return op::v0::Constant::create(element::i64, Shape{values.size()}, values);
+}
+
+Output<Node> concat(const OutputVector& inputs) {
+ return std::make_shared<op::v0::Concat>(inputs, 0);
+}
+
+struct WindowReverse {
+ bool restored = false;
+ bool shifted = false;
+ bool rebuilds_batch = true;
+ bool merge_shared = false;
+ bool roll_shared = false;
+ bool split_target_shared = false;
+ bool converted_batch = false;
+ bool rank5_merge = false;
+ bool static_trailing_dim = false;
+ std::vector<int64_t> permutation{0, 1, 3, 2, 4, 5};
+ std::vector<int64_t> roll_axes{1, 2};
+};
+
+// SwinIR's window_reverse for a 16x16 image split into 8x8 windows, as traced with batch one.
+std::shared_ptr<Model> make_window_reverse_model(const WindowReverse& options) {
+ const auto x = std::make_shared<op::v0::Parameter>(element::f32, PartialShape{-1, 16, 16, 4});
+ const auto shape_of = std::make_shared<op::v3::ShapeOf>(x, options.converted_batch ? element::i32 : element::i64);
+ const Output<Node> gathered_batch = std::make_shared<op::v8::Gather>(shape_of, i64({0}), i64({0}));
+ const Output<Node> batch =
+ options.converted_batch ? std::make_shared<op::v0::Convert>(gathered_batch, element::i64) : gathered_batch;
+ const auto one = i64({1});
+ const Output<Node> pinned = options.restored ? batch : one;
+
+ const auto windows = std::make_shared<op::v1::Reshape>(x, i64({-1, 8, 8, 4}), false);
+ const int64_t trailing = options.static_trailing_dim ? 4 : -1;
+ const auto make_split_target = [&](const Output<Node>& leading) {
+ return concat({leading, i64({2}), i64({2}), i64({8}), i64({8}), i64({trailing})});
+ };
+ const auto split_target = make_split_target(pinned);
+ const auto split = std::make_shared<op::v1::Reshape>(windows, split_target, false);
+ const auto permute = std::make_shared<op::v1::Transpose>(split, i64(options.permutation));
+ const auto merge_target = options.rank5_merge ? concat({pinned, i64({16, 1}), i64({16}), i64({-1})})
+ : concat({pinned, i64({16}), i64({16}), i64({trailing})});
+ const auto merge = std::make_shared<op::v1::Reshape>(permute, merge_target, false);
+ std::shared_ptr<Node> merged = merge;
+ if (options.shifted) {
+ merged = std::make_shared<op::v7::Roll>(merge,
+ i64(std::vector<int64_t>(options.roll_axes.size(), 4)),
+ i64(options.roll_axes));
+ }
+ const Output<Node> rebuilt_batch = options.rebuilds_batch ? batch : one;
+ const auto rebuild_target = concat({rebuilt_batch, i64({256}), i64({4})});
+ const auto rebuilt = std::make_shared<op::v1::Reshape>(merged, rebuild_target, false);
+
+ ResultVector results{std::make_shared<op::v0::Result>(rebuilt)};
+ if (options.merge_shared) {
+ results.push_back(std::make_shared<op::v0::Result>(merge));
+ }
+ if (options.roll_shared) {
+ results.push_back(std::make_shared<op::v0::Result>(merged));
+ }
+ if (options.split_target_shared) {
+ // Another Reshape reads the same traced target.
+ results.push_back(
+ std::make_shared<op::v0::Result>(std::make_shared<op::v1::Reshape>(windows, split_target, false)));
+ }
+ return std::make_shared<Model>(results, ParameterVector{x});
+}
+
+} // namespace
+
+class RestoreTracedBatchTests : public TransformationTestsF {
+protected:
+ void SetUp() override {
+ TransformationTestsF::SetUp();
+ manager.register_pass<pass::RestoreTracedBatch>();
+ }
+};
+
+TEST_F(RestoreTracedBatchTests, WindowReverseTakesBatchFromInputShape) {
+ WindowReverse traced;
+ WindowReverse restored;
+ restored.restored = true;
+ model = make_window_reverse_model(traced);
+ model_ref = make_window_reverse_model(restored);
+}
+
+TEST_F(RestoreTracedBatchTests, ShiftedWindowReverseTakesBatchFromInputShape) {
+ WindowReverse traced;
+ traced.shifted = true;
+ WindowReverse restored = traced;
+ restored.restored = true;
+ model = make_window_reverse_model(traced);
+ model_ref = make_window_reverse_model(restored);
+}
+
+TEST_F(RestoreTracedBatchTests, TargetsWithoutFlattenedTailAreLeftAlone) {
+ WindowReverse other;
+ other.static_trailing_dim = true;
+ model = make_window_reverse_model(other);
+}
+
+TEST_F(RestoreTracedBatchTests, RestoredWindowReverseIsLeftAlone) {
+ WindowReverse restored;
+ restored.restored = true;
+ model = make_window_reverse_model(restored);
+}
+
+TEST_F(RestoreTracedBatchTests, WindowReverseWithoutBatchFromInputShapeIsLeftAlone) {
+ WindowReverse collapsed;
+ collapsed.rebuilds_batch = false;
+ model = make_window_reverse_model(collapsed);
+}
+
+TEST_F(RestoreTracedBatchTests, OtherLeadingAxisPermutationTakesBatchFromInputShape) {
+ WindowReverse traced;
+ traced.permutation = {0, 2, 1, 3, 4, 5};
+ WindowReverse restored = traced;
+ restored.restored = true;
+ model = make_window_reverse_model(traced);
+ model_ref = make_window_reverse_model(restored);
+}
+
+TEST_F(RestoreTracedBatchTests, PermutationMovingLeadingAxisIsLeftAlone) {
+ WindowReverse other;
+ other.permutation = {1, 0, 2, 3, 4, 5};
+ model = make_window_reverse_model(other);
+}
+
+TEST_F(RestoreTracedBatchTests, OtherNonLeadingRollAxesTakeBatchFromInputShape) {
+ WindowReverse traced;
+ traced.shifted = true;
+ traced.roll_axes = {2, 3};
+ WindowReverse restored = traced;
+ restored.restored = true;
+ model = make_window_reverse_model(traced);
+ model_ref = make_window_reverse_model(restored);
+}
+
+TEST_F(RestoreTracedBatchTests, RollOnLeadingAxisIsLeftAlone) {
+ WindowReverse other;
+ other.shifted = true;
+ other.roll_axes = {0, 2};
+ model = make_window_reverse_model(other);
+}
+
+TEST_F(RestoreTracedBatchTests, WindowMergeWithOtherConsumersIsLeftAlone) {
+ WindowReverse shared;
+ shared.merge_shared = true;
+ model = make_window_reverse_model(shared);
+}
+
+TEST_F(RestoreTracedBatchTests, RollWithOtherConsumersIsLeftAlone) {
+ WindowReverse shared;
+ shared.shifted = true;
+ shared.roll_shared = true;
+ model = make_window_reverse_model(shared);
+}
+
+TEST_F(RestoreTracedBatchTests, RollOnNegativeLeadingAxisOfOtherRankIsLeftAlone) {
+ WindowReverse other;
+ other.rank5_merge = true;
+ other.shifted = true;
+ other.roll_axes = {-5};
+ model = make_window_reverse_model(other);
+}
+
+TEST_F(RestoreTracedBatchTests, SharedSplitTargetIsRestoredForAllConsumers) {
+ WindowReverse traced;
+ traced.split_target_shared = true;
+ WindowReverse restored = traced;
+ restored.restored = true;
+ model = make_window_reverse_model(traced);
+ model_ref = make_window_reverse_model(restored);
+}
+
+TEST_F(RestoreTracedBatchTests, ConvertedBatchIsTakenFromInputShape) {
+ WindowReverse traced;
+ traced.converted_batch = true;
+ WindowReverse restored = traced;
+ restored.restored = true;
+ model = make_window_reverse_model(traced);
+ model_ref = make_window_reverse_model(restored);
+}
+
+TEST(RestoreTracedBatch, TargetsKeepNames) {
+ const auto model = make_window_reverse_model({});
+ const auto concat_names = [&] {
+ std::set<std::string> names;
+ for (const auto& node : model->get_ops()) {
+ if (ov::is_type<op::v0::Concat>(node)) {
+ names.insert(node->get_friendly_name());
+ }
+ }
+ return names;
+ };
+ const auto names_before = concat_names();
+
+ pass::Manager manager;
+ manager.register_pass<pass::RestoreTracedBatch>();
+ ASSERT_TRUE(manager.run_passes(model));
+
+ EXPECT_EQ(concat_names(), names_before);
+}
+
+TEST(SmartReshapeTests, ReshapeRestoresWindowReverseBatch) {
+ const auto model = make_window_reverse_model({});
+
+ model->reshape(PartialShape{2, 16, 16, 4});
+
+ EXPECT_EQ(model->get_results()[0]->get_input_partial_shape(0), (PartialShape{2, 256, 4}));
+}
diff --git a/src/common/transformations/tests/sources.cmake b/src/common/transformations/tests/sources.cmake
index d3ee08ce9bc..fabd6ddb535 100644
--- a/src/common/transformations/tests/sources.cmake
+++ b/src/common/transformations/tests/sources.cmake
@@ -250,6 +250,7 @@ set(SMART_RESHAPE_TESTS_SRCS
${CMAKE_CURRENT_LIST_DIR}/smart_reshape/broadcast_const_range_replacement.cpp
${CMAKE_CURRENT_LIST_DIR}/smart_reshape/lstm_states_broadcast.cpp
${CMAKE_CURRENT_LIST_DIR}/smart_reshape/reshape_sinking.cpp
+ ${CMAKE_CURRENT_LIST_DIR}/smart_reshape/restore_traced_batch.cpp
${CMAKE_CURRENT_LIST_DIR}/smart_reshape/shape_of_const_folding.cpp
${CMAKE_CURRENT_LIST_DIR}/smart_reshape/sr_mimicking_sbs.cpp
${CMAKE_CURRENT_LIST_DIR}/smart_reshape/sr_proposal_scales.cpp