Skip to content

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

[CORE] Propagate Slice/StridedSlice symbols only if the size is preserved (#37932)

Evgeny Kotovd0b636d394ed
diff --git a/src/common/transformations/tests/symbolic_transformations/symbol_optimization.cpp b/src/common/transformations/tests/symbolic_transformations/symbol_optimization.cpp
index a8f7459034f..885719e4b3c 100644
--- a/src/common/transformations/tests/symbolic_transformations/symbol_optimization.cpp
+++ b/src/common/transformations/tests/symbolic_transformations/symbol_optimization.cpp
@@ -14,7 +14,11 @@
#include "openvino/op/range.hpp"
#include "openvino/op/reshape.hpp"
#include "openvino/op/shape_of.hpp"
+#include "openvino/op/slice.hpp"
#include "openvino/op/squeeze.hpp"
+#include "openvino/op/strided_slice.hpp"
+#include "openvino/op/util/gather_base.hpp"
+#include "openvino/op/util/shape_of_base.hpp"
#include "openvino/pass/manager.hpp"
#include "openvino/pass/visualize_tree.hpp"
#include "transformations/common_optimizations/shared_ops_optimization.hpp"
@@ -252,3 +256,123 @@ TEST_F(TransformationTestsF, ValueOptimizationSymbolAndValue) {
}
comparator.enable(FunctionsComparator::CmpValues::CONST_VALUES);
}
+
+namespace {
+shared_ptr<v0::Parameter> make_bhw8_input() {
+ return make_shared<v0::Parameter>(element::f32, PartialShape{-1, Dimension(1, -1), Dimension(1, -1), 8});
+}
+
+// x[:, ::step, ::step, :] as Slice, or as StridedSlice with masked (full range) begin/end
+shared_ptr<Node> make_hw_slice(const Output<Node>& input, int64_t step, bool strided) {
+ if (strided) {
+ auto begin = v0::Constant::create(element::i64, {4}, {0, 0, 0, 0});
+ auto end = v0::Constant::create(element::i64, {4}, {0, 0, 0, 0});
+ auto stride = v0::Constant::create(element::i64, {4}, std::vector<int64_t>{1, step, step, 1});
+ auto mask = std::vector<int64_t>(4, 1);
+ return make_shared<v1::StridedSlice>(input, begin, end, stride, mask, mask);
+ }
+ auto start = v0::Constant::create(element::i64, {2}, {0, 0});
+ auto stop = v0::Constant::create(element::i64, {2}, {INT64_MAX, INT64_MAX});
+ auto steps = v0::Constant::create(element::i64, {2}, std::vector<int64_t>{step, step});
+ auto axes = v0::Constant::create(element::i64, {2}, {1, 2});
+ return make_shared<v8::Slice>(input, start, stop, steps, axes);
+}
+
+// Reshape(slice, [B from ShapeOf(input), H and W from ShapeOf(slice), 8])
+shared_ptr<Model> make_reshape_after_hw_slice(int64_t step, bool strided) {
+ auto input = make_bhw8_input();
+ auto batch = get_dim_by_idx(input, {0}); // ShapeOf(input) is the earliest shape source of every input dim
+ auto slice = make_hw_slice(input, step, strided);
+ auto pattern = make_shared<v0::Concat>(OutputVector{batch,
+ get_dim_by_idx(slice, {1}),
+ get_dim_by_idx(slice, {2}),
+ v0::Constant::create(element::i64, {1}, {8})->output(0)},
+ 0);
+ auto reshape = make_shared<v1::Reshape>(slice, pattern, false);
+ return make_shared<Model>(OutputVector{reshape}, ParameterVector{input});
+}
+} // namespace
+
+TEST_F(TransformationTestsF, ValueOptimizationKeepsSourceAcrossSliceStep2) {
+ // H and W are read from a step-2 Slice, so they differ from the input dims and OptimizeSymbolsUsedAsValues must
+ // not re-source them to ShapeOf(input); the pattern is the Slice output shape, hence the expected ShapeOf(slice).
+ model = make_reshape_after_hw_slice(2, /*strided=*/false);
+ manager.set_per_pass_validation(false);
+ manager.register_pass<pass::SymbolicPropagation>();
+ manager.register_pass<pass::OptimizeSymbolsUsedAsValues>();
+ manager.register_pass<pass::SharedOpOptimization>();
+ {
+ auto input = make_bhw8_input();
+ auto slice = make_hw_slice(input, 2, /*strided=*/false);
+ auto reshape = make_shared<v1::Reshape>(slice, make_shared<v3::ShapeOf>(slice, element::i64), false);
+ model_ref = make_shared<Model>(OutputVector{reshape}, ParameterVector{input});
+ }
+ comparator.enable(FunctionsComparator::CmpValues::CONST_VALUES);
+}
+
+TEST_F(TransformationTestsF, ValueOptimizationKeepsSourceAcrossStridedSliceStride2) {
+ // Same as above with the StridedSlice form (masked full range, stride 2 on H and W).
+ model = make_reshape_after_hw_slice(2, /*strided=*/true);
+ manager.set_per_pass_validation(false);
+ manager.register_pass<pass::SymbolicPropagation>();
+ manager.register_pass<pass::OptimizeSymbolsUsedAsValues>();
+ manager.register_pass<pass::SharedOpOptimization>();
+ {
+ auto input = make_bhw8_input();
+ auto slice = make_hw_slice(input, 2, /*strided=*/true);
+ auto reshape = make_shared<v1::Reshape>(slice, make_shared<v3::ShapeOf>(slice, element::i64), false);
+ model_ref = make_shared<Model>(OutputVector{reshape}, ParameterVector{input});
+ }
+ comparator.enable(FunctionsComparator::CmpValues::CONST_VALUES);
+}
+
+TEST(TransformationTests, ValueOptimizationReusesSourceAcrossIdentitySlice) {
+ // A step-1 full-range slice preserves H and W, so the values read from ShapeOf(slice) are legitimately re-sourced
+ // to the earliest shape source, ShapeOf(input).
+ auto model = make_reshape_after_hw_slice(1, /*strided=*/false);
+ const auto input = model->get_parameters()[0];
+ const auto pattern = model->get_result()->get_input_node_shared_ptr(0)->get_input_node_shared_ptr(1);
+
+ pass::Manager manager;
+ manager.set_per_pass_validation(false);
+ manager.register_pass<pass::SymbolicPropagation>();
+ manager.register_pass<pass::OptimizeSymbolsUsedAsValues>();
+ manager.run_passes(model);
+
+ for (size_t i = 1; i <= 2; ++i) {
+ const auto gather = pattern->get_input_node_shared_ptr(i);
+ ASSERT_TRUE(ov::is_type<ov::op::util::GatherBase>(gather)) << "pattern input " << i;
+ const auto shape_of = gather->get_input_node_shared_ptr(0);
+ ASSERT_TRUE(ov::is_type<ov::op::util::ShapeOfBase>(shape_of)) << "pattern input " << i;
+ EXPECT_EQ(shape_of->get_input_node_shared_ptr(0), input) << "pattern input " << i;
+ }
+}
+
+TEST(TransformationTests, SliceStep2ConcatDoesNotEquateInputDimSymbols) {
+ // Concat merges the symbols of its non-axis dimensions, so a step-2 slice output concatenated with another tensor
+ // must not make the slice input dimension equal to that tensor's dimension.
+ auto x = make_shared<v0::Parameter>(element::f32, PartialShape{-1, Dimension(1, -1), 4});
+ auto z = make_shared<v0::Parameter>(element::f32, PartialShape{-1, Dimension(1, -1), 6});
+
+ auto start = v0::Constant::create(element::i64, {1}, {0});
+ auto stop = v0::Constant::create(element::i64, {1}, {INT64_MAX});
+ auto step = v0::Constant::create(element::i64, {1}, {2});
+ auto axes = v0::Constant::create(element::i64, {1}, {1});
+ auto slice = make_shared<v8::Slice>(x, start, stop, step, axes);
+ auto concat = make_shared<v0::Concat>(OutputVector{slice, z}, 2);
+ auto model = make_shared<Model>(OutputVector{concat}, ParameterVector{x, z});
+
+ pass::Manager manager;
+ manager.set_per_pass_validation(false);
+ manager.register_pass<pass::SymbolicPropagation>();
+ manager.run_passes(model);
+
+ const auto x_dim = x->get_output_partial_shape(0)[1].get_symbol();
+ const auto z_dim = z->get_output_partial_shape(0)[1].get_symbol();
+ const auto concat_dim = concat->get_output_partial_shape(0)[1].get_symbol();
+ ASSERT_NE(x_dim, nullptr);
+ ASSERT_NE(z_dim, nullptr);
+ EXPECT_FALSE(symbol::are_equal(x_dim, z_dim));
+ EXPECT_FALSE(symbol::are_equal(x_dim, concat_dim));
+ EXPECT_TRUE(symbol::are_equal(z_dim, concat_dim));
+}
diff --git a/src/core/shape_inference/include/slice_shape_inference.hpp b/src/core/shape_inference/include/slice_shape_inference.hpp
index c77438dbeeb..fbd9a5978f2 100644
--- a/src/core/shape_inference/include/slice_shape_inference.hpp
+++ b/src/core/shape_inference/include/slice_shape_inference.hpp
@@ -132,16 +132,15 @@ std::vector<TRShape> shape_infer(const Slice* op,
const auto& step = (*steps)[i];
NODE_VALIDATION_CHECK(op, step != 0, "Step must be non-zero");
out.push_back(slice::make_dim(input_dim, (*start)[i], (*stop)[i], step));
+
+ if constexpr (std::is_same_v<DimType, ov::Dimension>) {
+ auto& last_dim = out[out.size() - 1];
+ slice::merge_symbol_if_size_preserved(last_dim, input_dim, (*start)[i], (*stop)[i], step);
+ }
} else {
+ // start, stop or step unknown: the size is not provably preserved, no symbol propagation
out.emplace_back(0, input_dim.get_max_length());
}
-
- auto& last_dim = out[out.size() - 1];
- if (std::is_same<DimType, ov::Dimension>::value &&
- (last_dim == input_dim && last_dim != Dimension::dynamic())) {
- // for equal ov::Dimension do merge to get input label (always success)
- DimType::merge(last_dim, last_dim, input_dim);
- }
++axis_it;
} else if (axes_map.is_valid) {
// dimension not on axes list, no change
diff --git a/src/core/shape_inference/include/slice_shape_inference_utils.hpp b/src/core/shape_inference/include/slice_shape_inference_utils.hpp
index a3820a8ffe5..a0f65006abe 100644
--- a/src/core/shape_inference/include/slice_shape_inference_utils.hpp
+++ b/src/core/shape_inference/include/slice_shape_inference_utils.hpp
@@ -164,6 +164,72 @@ TDim make_dim(const TDim& dim, const Bounds& start, const Bounds& stop, int64_t
return {lb, ub};
}
+/**
+ * \brief Check if the slice provably preserves the dimension size.
+ *
+ * True only if the step is +/-1 and start/stop cover the whole dimension for every length within `dim` and every
+ * start/stop value within their bounds; interval equality is not enough.
+ *
+ * \param dim Input dimension.
+ * \param start Slice start bounds.
+ * \param stop Slice stop bounds.
+ * \param step Slice step.
+ *
+ * \return True if the slice is size preserving, otherwise false.
+ */
+inline bool is_size_preserving_slice(const ov::Dimension& dim,
+ const Bounds& start,
+ const Bounds& stop,
+ const int64_t step) {
+ // The max length of an unbounded dimension is Interval::s_max (INT64_MAX), same normalization make_dim uses via
+ // value_convert; a negative start/stop bound b means index L + b for a length L within the dimension, so the
+ // worst case (start.second, the largest possible start; stop.second, the smallest magnitude negative stop) is
+ // the one that must still clip for every L up to max_length.
+ const auto max_length = dim.get_interval().get_max_val();
+ if (step == 1) {
+ // start clips to the first element for every L: start == 0, or start.second <= -max_length (so
+ // start.second + L <= -max_length + L <= 0 for every L <= max_length);
+ // stop clips to the last element (or past it) for every L: stop.first >= max_length.
+ const auto start_at_begin = start == Bounds{0, 0} || start.second <= -max_length;
+ const auto stop_at_end = stop.first >= max_length;
+ return start_at_begin && stop_at_end;
+ } else if (step == -1) {
+ // start clips to the last element for every L: start == -1, or start.first >= max_length - 1 (so
+ // start.first >= L - 1 for every L <= max_length);
+ // stop clips to before the first element for every L: stop.second <= -max_length - 1.
+ const auto start_at_last = start == Bounds{-1, -1} || start.first >= max_length - 1;
+ const auto stop_before_begin = stop.second <= -max_length - 1;
+ return start_at_last && stop_before_begin;
+ } else {
+ // |step| >= 2 gives ceil(L / |step|) < L for every length L >= 2, so the size can never be preserved
+ return false;
+ }
+}
+
+/**
+ * \brief Merge the input dimension symbol into the sliced dimension if the slice provably preserves its size.
+ *
+ * Equal intervals do not imply equal sizes (e.g. step 2 on `[1..inf]` stays `[1..inf]`), so the symbol is merged only
+ * if the sliced dimension equals the input one, is not fully dynamic, and the input is static or the slice is size
+ * preserving.
+ *
+ * \param sliced Sliced dimension (updated in place).
+ * \param dim Input dimension.
+ * \param start Slice start bounds.
+ * \param stop Slice stop bounds.
+ * \param step Slice step.
+ */
+inline void merge_symbol_if_size_preserved(ov::Dimension& sliced,
+ const ov::Dimension& dim,
+ const Bounds& start,
+ const Bounds& stop,
+ const int64_t step) {
+ if (sliced == dim && sliced != ov::Dimension::dynamic() &&
+ (dim.is_static() || is_size_preserving_slice(dim, start, stop, step))) {
+ ov::Dimension::merge(sliced, sliced, dim);
+ }
+}
+
/**
* \brief Computes the size of the default strides ([1, 1, ..., 1]) of a StridedSlice.
*
diff --git a/src/core/shape_inference/include/strided_slice_shape_inference.hpp b/src/core/shape_inference/include/strided_slice_shape_inference.hpp
index 5b840375ed2..b52b0a8680a 100644
--- a/src/core/shape_inference/include/strided_slice_shape_inference.hpp
+++ b/src/core/shape_inference/include/strided_slice_shape_inference.hpp
@@ -196,9 +196,8 @@ std::vector<TRShape> shape_infer(const StridedSlice* op,
auto sliced_dim =
start && stop ? slice::make_dim(input_dim, *start, *stop, stride) : last_dynamic_dim->second;
- // for equal ov::Dimension do merge to get input label (always success)
- if (sliced_dim == input_dim && sliced_dim != Dimension::dynamic()) {
- DimType::merge(sliced_dim, sliced_dim, input_dim);
+ if (start && stop) { // unknown begin/end cannot prove that the size is preserved
+ slice::merge_symbol_if_size_preserved(sliced_dim, input_dim, *start, *stop, stride);
}
out.push_back(std::move(sliced_dim));
diff --git a/src/core/tests/shape_inference_utils_test.cpp b/src/core/tests/shape_inference_utils_test.cpp
index 0348ebcd152..1ac6f60e9b1 100644
--- a/src/core/tests/shape_inference_utils_test.cpp
+++ b/src/core/tests/shape_inference_utils_test.cpp
@@ -4,7 +4,10 @@
#include <gtest/gtest.h>
+#include <limits>
+
#include "openvino/op/reverse.hpp"
+#include "slice_shape_inference_utils.hpp"
#include "utils.hpp"
TEST(shape_inference_utils_test, get_input_bounds_not_valid_port) {
@@ -14,4 +17,62 @@ TEST(shape_inference_utils_test, get_input_bounds_not_valid_port) {
const auto ret = ov::op::get_input_bounds<ov::PartialShape, int64_t>(&dummy_op, not_valid_port, ta);
ASSERT_FALSE(ret);
-}
\ No newline at end of file
+}
+
+using ov::op::slice::Bounds;
+
+// dim, start, stop, step, expected
+using IsSizePreservingSliceParams = std::tuple<ov::Dimension, Bounds, Bounds, int64_t, bool>;
+
+class IsSizePreservingSliceTest : public testing::TestWithParam<IsSizePreservingSliceParams> {};
+
+// True only if the slice yields exactly L elements for every length L within the dimension interval and every
+// start/stop value within the bounds.
+TEST_P(IsSizePreservingSliceTest, is_size_preserving_slice) {
+ const auto& [dim, start, stop, step, expected] = GetParam();
+
+ EXPECT_EQ(ov::op::slice::is_size_preserving_slice(dim, start, stop, step), expected);
+}
+
+namespace {
+constexpr auto i64_max = std::numeric_limits<int64_t>::max();
+constexpr auto i64_min = std::numeric_limits<int64_t>::min();
+} // namespace
+
+INSTANTIATE_TEST_SUITE_P(
+ shape_inference_utils_test,
+ IsSizePreservingSliceTest,
+ testing::Values(
+ IsSizePreservingSliceParams{ov::Dimension::dynamic(), {0, 0}, {i64_max, i64_max}, 1, true},
+ IsSizePreservingSliceParams{ov::Dimension::dynamic(), {0, 0}, {i64_max, i64_max}, 2, false},
+ IsSizePreservingSliceParams{ov::Dimension::dynamic(), {0, 0}, {i64_max, i64_max}, 3, false},
+ IsSizePreservingSliceParams{ov::Dimension::dynamic(), {0, 0}, {i64_max, i64_max}, -1, false},
+ IsSizePreservingSliceParams{ov::Dimension::dynamic(), {i64_min, i64_min}, {i64_max, i64_max}, 1, true},
+ IsSizePreservingSliceParams{ov::Dimension::dynamic(), {i64_max, i64_max}, {i64_min, i64_min}, -1, true},
+ IsSizePreservingSliceParams{ov::Dimension::dynamic(), {-1, -1}, {i64_min, i64_min}, -1, true},
+ IsSizePreservingSliceParams{ov::Dimension::dynamic(), {1, 1}, {i64_max, i64_max}, 1, false},
+ IsSizePreservingSliceParams{ov::Dimension::dynamic(), {0, 0}, {2147483647, 2147483647}, 1, false},
+ IsSizePreservingSliceParams{ov::Dimension::dynamic(), {i64_min, 0}, {i64_max, i64_max}, 1, false},
+ IsSizePreservingSliceParams{ov::Dimension::dynamic(), {0, 0}, {1, i64_max}, 1, false},
+ IsSizePreservingSliceParams{ov::Dimension(10), {0, 0}, {10, 10}, 1, true},
+ IsSizePreservingSliceParams{ov::Dimension(10), {0, 0}, {9, 9}, 1, false},
+ IsSizePreservingSliceParams{ov::Dimension(10), {-20, -20}, {20, 20}, 1, true},
+ IsSizePreservingSliceParams{ov::Dimension(10), {9, 9}, {-11, -11}, -1, true},
+ IsSizePreservingSliceParams{ov::Dimension(4, 8), {0, 0}, {8, 8}, 1, true},
+ IsSizePreservingSliceParams{ov::Dimension(4, 8), {0, 0}, {6, 6}, 1, false},
+ IsSizePreservingSliceParams{ov::Dimension(4, 8), {0, 0}, {4, 8}, 1, false},
+ IsSizePreservingSliceParams{ov::Dimension(2, 5), {-5, -5}, {5, 5}, 1, true},
+ IsSizePreservingSliceParams{ov::Dimension(2, 5), {-5, -3}, {5, 5}, 1, false},
+ IsSizePreservingSliceParams{ov::Dimension(2, 5), {0, 0}, {5, 5}, -1, false},
+ IsSizePreservingSliceParams{ov::Dimension(2, 5), {4, 4}, {-6, -6}, -1, true},
+ IsSizePreservingSliceParams{ov::Dimension(2, 5), {3, 3}, {-6, -6}, -1, false},
+ // lengths 0 and 1 are trivially preserved by any step: the predicate is conservative here
+ IsSizePreservingSliceParams{ov::Dimension(0, 1), {0, 0}, {i64_max, i64_max}, 2, false},
+ // a start/stop bound one away from the INT64_MIN/INT64_MAX sentinel still clips for every length up
+ // to max_length (max_length - 1 away from the sentinel in the opposite direction of the check)
+ IsSizePreservingSliceParams{ov::Dimension::dynamic(), {i64_min + 1, i64_min + 1}, {i64_max, i64_max}, 1, true},
+ IsSizePreservingSliceParams{ov::Dimension::dynamic(),
+ {i64_max - 1, i64_max - 1},
+ {i64_min, i64_min},
+ -1,
+ true}));
diff --git a/src/core/tests/type_prop/slice.cpp b/src/core/tests/type_prop/slice.cpp
index 950cd71e575..42897bd3f4a 100644
--- a/src/core/tests/type_prop/slice.cpp
+++ b/src/core/tests/type_prop/slice.cpp
@@ -4,11 +4,14 @@
#include "openvino/op/slice.hpp"
+#include <limits>
#include <numeric>
#include "common_test_utils/test_assertions.hpp"
#include "common_test_utils/type_prop.hpp"
#include "openvino/op/broadcast.hpp"
+#include "openvino/op/gather.hpp"
+#include "openvino/op/shape_of.hpp"
#include "openvino/op/subtract.hpp"
#include "sequence_generator.hpp"
@@ -253,9 +256,10 @@ TEST(type_prop, slice_v8_basic_param_inputs_default_axes_symbols_prop) {
EXPECT_EQ(op->get_element_type(), et);
EXPECT_EQ(op->get_output_partial_shape(0), expected_out_shape);
- EXPECT_THAT(
- get_shape_symbols(op->get_output_partial_shape(0)),
- ElementsAre(symbols[0], nullptr, nullptr, nullptr, nullptr, nullptr, symbols[6], symbols[7], symbols[8]));
+ // non-constant start/stop/step: no symbol is propagated on the sliced axes 0..6, even where the output interval
+ // equals the input one (dims 0 and 6)
+ EXPECT_THAT(get_shape_symbols(op->get_output_partial_shape(0)),
+ ElementsAre(nullptr, nullptr, nullptr, nullptr, nullptr, nullptr, nullptr, symbols[7], symbols[8]));
}
TEST(type_prop, slice_v8_sss_param_inputs_mixed_neg_const_axes) {
@@ -1261,3 +1265,143 @@ TEST_P(SliceV8IntervalTest, start_stop_as_interval) {
EXPECT_EQ(op->get_output_partial_shape(0), exp_shape);
}
+
+TEST(type_prop, slice_v8_step_2_on_unbounded_dims_does_not_propagate_symbols) {
+ // Step 2 on [1..inf] keeps the interval but changes the size (ceil(D/2)), so the symbols must not be propagated.
+ PartialShape data_shape{-1, Dimension(1, -1), Dimension(1, -1), 96};
+ PartialShape expected_out_shape{-1, Dimension(1, -1), Dimension(1, -1), 96};
+ auto symbols = set_shape_symbols(data_shape);
+
+ std::vector<int32_t> start_val{0, 0};
+ std::vector<int32_t> stop_val{std::numeric_limits<int32_t>::max(), std::numeric_limits<int32_t>::max()};
+ std::vector<int32_t> step_val{2, 2};
+ std::vector<int32_t> axes_val{1, 2};
+
+ constexpr auto et = element::i32;
+ std::vector<std::vector<int32_t>> input_vals{start_val, stop_val, step_val, axes_val};
+ const auto op = make_slice_op_const_inputs(input_vals, data_shape, et);
+
+ EXPECT_EQ(op->get_output_partial_shape(0), expected_out_shape);
+ EXPECT_THAT(get_shape_symbols(op->get_output_partial_shape(0)),
+ ElementsAre(symbols[0], nullptr, nullptr, symbols[3]));
+}
+
+TEST(type_prop, slice_v8_step_2_from_1_on_unbounded_dims_does_not_propagate_symbols) {
+ // Start 1 yields [0..inf] != [1..inf], so the interval check alone blocks the symbol propagation.
+ PartialShape data_shape{-1, Dimension(1, -1), Dimension(1, -1), 96};
+ PartialShape expected_out_shape{-1, Dimension(0, -1), Dimension(0, -1), 96};
+ auto symbols = set_shape_symbols(data_shape);
+
+ std::vector<int32_t> start_val{1, 1};
+ std::vector<int32_t> stop_val{std::numeric_limits<int32_t>::max(), std::numeric_limits<int32_t>::max()};
+ std::vector<int32_t> step_val{2, 2};
+ std::vector<int32_t> axes_val{1, 2};
+
+ constexpr auto et = element::i32;
+ std::vector<std::vector<int32_t>> input_vals{start_val, stop_val, step_val, axes_val};
+ const auto op = make_slice_op_const_inputs(input_vals, data_shape, et);
+
+ EXPECT_EQ(op->get_output_partial_shape(0), expected_out_shape);
+ EXPECT_THAT(get_shape_symbols(op->get_output_partial_shape(0)),
+ ElementsAre(symbols[0], nullptr, nullptr, symbols[3]));
+}
+
+TEST(type_prop, slice_v8_full_range_step_1_on_unbounded_dims_propagates_symbols) {
+ // An identity slice (start 0, stop max, step 1) preserves the size, so the symbols are kept.
+ PartialShape data_shape{-1, Dimension(1, -1), Dimension(1, -1), 96};
+ PartialShape expected_out_shape{-1, Dimension(1, -1), Dimension(1, -1), 96};
+ auto symbols = set_shape_symbols(data_shape);
+
+ std::vector<int32_t> start_val{0, 0};
+ std::vector<int32_t> stop_val{std::numeric_limits<int32_t>::max(), std::numeric_limits<int32_t>::max()};
+ std::vector<int32_t> step_val{1, 1};
+ std::vector<int32_t> axes_val{1, 2};
+
+ constexpr auto et = element::i32;
+ std::vector<std::vector<int32_t>> input_vals{start_val, stop_val, step_val, axes_val};
+ const auto op = make_slice_op_const_inputs(input_vals, data_shape, et);
+
+ EXPECT_EQ(op->get_output_partial_shape(0), expected_out_shape);
+ EXPECT_THAT(get_shape_symbols(op->get_output_partial_shape(0)),
+ ElementsAre(symbols[0], symbols[1], symbols[2], symbols[3]));
+}
+
+TEST(type_prop, slice_v8_bounded_dims_full_range_propagates_symbols_only_when_stop_covers_max) {
+ // start 0 (or <= -max) with stop >= max keeps the size for every length in [2..5]; stop 4 does not (5 -> 4).
+ PartialShape data_shape{Dimension(2, 5), Dimension(2, 5), Dimension(2, 5)};
+ PartialShape expected_out_shape{Dimension(2, 5), Dimension(2, 4), Dimension(2, 5)};
+ auto symbols = set_shape_symbols(data_shape);
+
+ std::vector<int64_t> start_val{0, 0, -5};
+ std::vector<int64_t> stop_val{5, 4, 5};
+ std::vector<int64_t> step_val{1, 1, 1};
+ std::vector<int64_t> axes_val{0, 1, 2};
+
+ constexpr auto et = element::i64;
+ std::vector<std::vector<int64_t>> input_vals{start_val, stop_val, step_val, axes_val};
+ const auto op = make_slice_op_const_inputs(input_vals, data_shape, et);
+
+ EXPECT_EQ(op->get_output_partial_shape(0), expected_out_shape);
+ EXPECT_THAT(get_shape_symbols(op->get_output_partial_shape(0)), ElementsAre(symbols[0], nullptr, symbols[2]));
+}
+
+TEST(type_prop, slice_v8_bounded_dims_full_reverse_propagates_symbols) {
+ // start >= max - 1 with stop <= -max - 1 and step -1 reverses the whole dimension for every length in [2..5];
+ // start 3 does not (5 -> 4).
+ PartialShape data_shape{Dimension(2, 5), Dimension(2, 5)};
+ PartialShape expected_out_shape{Dimension(2, 5), Dimension(2, 4)};
+ auto symbols = set_shape_symbols(data_shape);
+
+ std::vector<int64_t> start_val{4, 3};
+ std::vector<int64_t> stop_val{-6, -6};
+ std::vector<int64_t> step_val{-1, -1};
+ std::vector<int64_t> axes_val{0, 1};
+
+ constexpr auto et = element::i64;
+ std::vector<std::vector<int64_t>> input_vals{start_val, stop_val, step_val, axes_val};
+ const auto op = make_slice_op_const_inputs(input_vals, data_shape, et);
+
+ EXPECT_EQ(op->get_output_partial_shape(0), expected_out_shape);
+ EXPECT_THAT(get_shape_symbols(op->get_output_partial_shape(0)), ElementsAre(symbols[0], nullptr));
+}
+
+TEST(type_prop, slice_v8_negative_start_with_bounds_does_not_propagate_symbols) {
+ // x[-n:] with an unknown n >= 1 (start bounds (INT64_MIN + 1, -1): a genuine interval, not the INT64_MIN limit
+ // sentinel): the output interval equals the input [1..inf], but the bounds do not prove that the size is preserved.
+ PartialShape data_shape{-1, Dimension(1, -1), 8};
+ auto symbols = set_shape_symbols(data_shape);
+
+ const auto data = std::make_shared<op::v0::Parameter>(element::f32, data_shape);
+ const auto start = std::make_shared<op::v0::Parameter>(element::i64, PartialShape{1});
+ int64_t start_lower[] = {std::numeric_limits<int64_t>::min() + 1};
+ int64_t start_upper[] = {-1};
+ start->get_output_tensor(0).set_lower_value(ov::Tensor(element::i64, Shape{1}, start_lower));
+ start->get_output_tensor(0).set_upper_value(ov::Tensor(element::i64, Shape{1}, start_upper));
+ const auto stop = op::v0::Constant::create(element::i64, Shape{1}, {std::numeric_limits<int64_t>::max()});
+ const auto step = op::v0::Constant::create(element::i64, Shape{1}, {1});
+ const auto axes = op::v0::Constant::create(element::i64, Shape{1}, {1});
+ const auto op = std::make_shared<op::v8::Slice>(data, start, stop, step, axes);
+
+ EXPECT_EQ(op->get_output_partial_shape(0), data_shape);
+ EXPECT_THAT(get_shape_symbols(op->get_output_partial_shape(0)), ElementsAre(symbols[0], nullptr, symbols[2]));
+}
+
+TEST(type_prop, slice_v8_stop_is_shape_of_input_dim_on_unbounded_dims_does_not_propagate_symbols) {
+ // x[:, :ShapeOf(x)[1], :ShapeOf(x)[2]]: the stop bounds are (1, INT64_MAX) so the output interval equals the input,
+ // but the bounds alone do not prove the size is preserved; the symbols are not propagated.
+ PartialShape data_shape{-1, Dimension(1, -1), Dimension(1, -1), 96};
+ auto symbols = set_shape_symbols(data_shape);
+
+ const auto data = std::make_shared<op::v0::Parameter>(element::f32, data_shape);
+ const auto stop = std::make_shared<op::v8::Gather>(std::make_shared<op::v3::ShapeOf>(data),
+ op::v0::Constant::create(element::i64, Shape{2}, {1, 2}),
+ op::v0::Constant::create(element::i64, Shape{}, {0}));
+ const auto start = op::v0::Constant::create(element::i64, Shape{2}, {0, 0});
+ const auto step = op::v0::Constant::create(element::i64, Shape{2}, {1, 1});
+ const auto axes = op::v0::Constant::create(element::i64, Shape{2}, {1, 2});
+ const auto op = std::make_shared<op::v8::Slice>(data, start, stop, step, axes);
+
+ EXPECT_EQ(op->get_output_partial_shape(0), data_shape);
+ EXPECT_THAT(get_shape_symbols(op->get_output_partial_shape(0)),
+ ElementsAre(symbols[0], nullptr, nullptr, symbols[3]));
+}
diff --git a/src/core/tests/type_prop/strided_slice.cpp b/src/core/tests/type_prop/strided_slice.cpp
index ce811b4bb61..61aa1297e56 100644
--- a/src/core/tests/type_prop/strided_slice.cpp
+++ b/src/core/tests/type_prop/strided_slice.cpp
@@ -857,3 +857,124 @@ TEST_P(StridedSliceIntervalTest, begin_end_as_interval) {
EXPECT_EQ(op->get_output_partial_shape(0), exp_shape);
}
+
+TEST(type_prop, strided_slice_ignore_begin_end_masks_stride_2_on_unbounded_dims_does_not_propagate_symbols) {
+ // Stride 2 on [1..inf] keeps the interval but changes the size (ceil(D/2)), so the symbols must not be propagated.
+ auto shape = PartialShape{2, Dimension(1, -1), Dimension(1, -1), 96};
+ auto symbols = set_shape_symbols(shape);
+ auto data = std::make_shared<ov::op::v0::Parameter>(element::f32, shape);
+ auto begin = ov::op::v0::Constant::create(element::i64, Shape{4}, {0, 0, 0, 0});
+ auto end = ov::op::v0::Constant::create(element::i64, Shape{4}, {0, 0, 0, 0});
+ auto stride = ov::op::v0::Constant::create(element::i64, Shape{4}, {1, 2, 2, 1});
+ auto mask = std::vector<int64_t>(shape.size(), 1); // begin/end ignored -> full range on every axis
+
+ auto strided_slice = std::make_shared<op::v1::StridedSlice>(data, begin, end, stride, mask, mask);
+
+ EXPECT_EQ(strided_slice->get_output_partial_shape(0), PartialShape({2, Dimension(1, -1), Dimension(1, -1), 96}));
+ EXPECT_THAT(get_shape_symbols(strided_slice->get_output_partial_shape(0)),
+ ElementsAre(symbols[0], nullptr, nullptr, symbols[3]));
+}
+
+TEST(type_prop, strided_slice_ignore_begin_end_masks_stride_pos_1_on_unbounded_dims_propagates_symbols) {
+ // An identity slice preserves the size, so the symbols are kept.
+ auto shape = PartialShape{2, Dimension(1, -1), Dimension(1, -1), 96};
+ auto symbols = set_shape_symbols(shape);
+ auto data = std::make_shared<ov::op::v0::Parameter>(element::f32, shape);
+ auto begin = ov::op::v0::Constant::create(element::i64, Shape{4}, {0, 0, 0, 0});
+ auto end = ov::op::v0::Constant::create(element::i64, Shape{4}, {0, 0, 0, 0});
+ auto stride = ov::op::v0::Constant::create(element::i64, Shape{4}, {1, 1, 1, 1});
+ auto mask = std::vector<int64_t>(shape.size(), 1);
+
+ auto strided_slice = std::make_shared<op::v1::StridedSlice>(data, begin, end, stride, mask, mask);
+
+ EXPECT_EQ(strided_slice->get_output_partial_shape(0), PartialShape({2, Dimension(1, -1), Dimension(1, -1), 96}));
+ EXPECT_THAT(get_shape_symbols(strided_slice->get_output_partial_shape(0)),
+ ElementsAre(symbols[0], symbols[1], symbols[2], symbols[3]));
+}
+
+TEST(type_prop, strided_slice_converted_from_slice_keeps_symbols_on_masked_axes) {
+ // x[..., :5] after SliceToStridedSlice: the non-sliced axes are masked (full range, stride 1) and keep the symbols.
+ auto shape = PartialShape{2, Dimension(1, -1), Dimension(1, -1), 8};
+ auto symbols = set_shape_symbols(shape);
+ auto data = std::make_shared<ov::op::v0::Parameter>(element::f32, shape);
+ auto begin = ov::op::v0::Constant::create(element::i64, Shape{4}, {0, 0, 0, 0});
+ auto end = ov::op::v0::Constant::create(element::i64, Shape{4}, {0, 0, 0, 5});
+ auto stride = ov::op::v0::Constant::create(element::i64, Shape{4}, {1, 1, 1, 1});
+ auto mask = std::vector<int64_t>{1, 1, 1, 0};
+
+ auto strided_slice = std::make_shared<op::v1::StridedSlice>(data, begin, end, stride, mask, mask);
+
+ EXPECT_EQ(strided_slice->get_output_partial_shape(0), PartialShape({2, Dimension(1, -1), Dimension(1, -1), 5}));
+ EXPECT_THAT(get_shape_symbols(strided_slice->get_output_partial_shape(0)),
+ ElementsAre(symbols[0], symbols[1], symbols[2], nullptr));
+}
+
+TEST(type_prop, strided_slice_ignore_begin_end_masks_stride_pos_neg_1_on_bounded_dims_propagates_symbols) {
+ // Masked full range keeps the size for stride +1 and -1 on bounded dims, but not for stride 2.
+ auto shape = PartialShape{Dimension(2, 5), Dimension(2, 5), Dimension(2, 5)};
+ auto symbols = set_shape_symbols(shape);
+ auto data = std::make_shared<ov::op::v0::Parameter>(element::f32, shape);
+ auto begin = ov::op::v0::Constant::create(element::i64, Shape{3}, {0, 0, 0});
+ auto end = ov::op::v0::Constant::create(element::i64, Shape{3}, {0, 0, 0});
+ auto stride = ov::op::v0::Constant::create(element::i64, Shape{3}, {1, -1, 2});
+ auto mask = std::vector<int64_t>(shape.size(), 1);
+
+ auto strided_slice = std::make_shared<op::v1::StridedSlice>(data, begin, end, stride, mask, mask);
+
+ EXPECT_EQ(strided_slice->get_output_partial_shape(0),
+ PartialShape({Dimension(2, 5), Dimension(2, 5), Dimension(1, 3)}));
+ EXPECT_THAT(get_shape_symbols(strided_slice->get_output_partial_shape(0)),
+ ElementsAre(symbols[0], symbols[1], nullptr));
+}
+
+TEST(type_prop, strided_slice_ignore_begin_end_masks_stride_neg_1_on_unbounded_dims_propagates_symbols) {
+ // Masked full range with stride -1 reverses the whole dimension, so the size is preserved.
+ auto shape = PartialShape{2, Dimension(1, -1), Dimension(1, -1), 96};
+ auto symbols = set_shape_symbols(shape);
+ auto data = std::make_shared<ov::op::v0::Parameter>(element::f32, shape);
+ auto begin = ov::op::v0::Constant::create(element::i64, Shape{4}, {0, 0, 0, 0});
+ auto end = ov::op::v0::Constant::create(element::i64, Shape{4}, {0, 0, 0, 0});
+ auto stride = ov::op::v0::Constant::create(element::i64, Shape{4}, {1, -1, -1, 1});
+ auto mask = std::vector<int64_t>(shape.size(), 1);
+
+ auto strided_slice = std::make_shared<op::v1::StridedSlice>(data, begin, end, stride, mask, mask);
+
+ EXPECT_EQ(strided_slice->get_output_partial_shape(0), PartialShape({2, Dimension(1, -1), Dimension(1, -1), 96}));
+ EXPECT_THAT(get_shape_symbols(strided_slice->get_output_partial_shape(0)),
+ ElementsAre(symbols[0], symbols[1], symbols[2], symbols[3]));
+}
+
+TEST(type_prop, strided_slice_non_const_begin_end_on_bounded_dims_does_not_propagate_symbols) {
+ // Unknown begin/end give a [0..max] output, which equals a [0..max] input, but the size is not provably preserved.
+ auto shape = PartialShape{Dimension(0, 5), Dimension(0, 4)};
+ auto symbols = set_shape_symbols(shape);
+ auto data = std::make_shared<ov::op::v0::Parameter>(element::f32, shape);
+ auto begin = std::make_shared<ov::op::v0::Parameter>(element::i64, Shape{2});
+ auto end = std::make_shared<ov::op::v0::Parameter>(element::i64, Shape{2});
+ auto stride = ov::op::v0::Constant::create(element::i64, Shape{2}, {1, 1});
+ auto mask = std::vector<int64_t>(2, 0);
+
+ auto strided_slice = std::make_shared<op::v1::StridedSlice>(data, begin, end, stride, mask, mask);
+
+ EXPECT_EQ(strided_slice->get_output_partial_shape(0), PartialShape({Dimension(0, 5), Dimension(0, 4)}));
+ EXPECT_THAT(get_shape_symbols(strided_slice->get_output_partial_shape(0)), Each(nullptr));
+}
+
+TEST(type_prop, strided_slice_non_const_begin_end_keeps_symbols_on_masked_axes) {
+ // Axes ignored by begin_mask/end_mask take the full range whatever the unknown begin/end are, so stride +/-1 keeps
+ // the symbol and stride 2 drops it; the unmasked axis is [0..max] without a symbol.
+ auto shape = PartialShape{Dimension(1, -1), Dimension(1, -1), Dimension(1, -1), Dimension(1, -1)};
+ auto symbols = set_shape_symbols(shape);
+ auto data = std::make_shared<ov::op::v0::Parameter>(element::f32, shape);
+ auto begin = std::make_shared<ov::op::v0::Parameter>(element::i64, Shape{4});
+ auto end = std::make_shared<ov::op::v0::Parameter>(element::i64, Shape{4});
+ auto stride = ov::op::v0::Constant::create(element::i64, Shape{4}, {1, -1, 2, 1});
+ auto mask = std::vector<int64_t>{1, 1, 1, 0};
+
+ auto strided_slice = std::make_shared<op::v1::StridedSlice>(data, begin, end, stride, mask, mask);
+
+ EXPECT_EQ(strided_slice->get_output_partial_shape(0),
+ PartialShape({Dimension(1, -1), Dimension(1, -1), Dimension(1, -1), Dimension(0, -1)}));
+ EXPECT_THAT(get_shape_symbols(strided_slice->get_output_partial_shape(0)),
+ ElementsAre(symbols[0], symbols[1], nullptr, nullptr));
+}
diff --git a/tests/layer_tests/pytorch_tests/test_patch_merging.py b/tests/layer_tests/pytorch_tests/test_patch_merging.py
new file mode 100644
index 00000000000..90bc876ac64
--- /dev/null
+++ b/tests/layer_tests/pytorch_tests/test_patch_merging.py
@@ -0,0 +1,78 @@
+# Copyright (C) 2018-2026 Intel Corporation
+# SPDX-License-Identifier: Apache-2.0
+
+import pytest
+import torch
+import torch.nn.functional as F
+
+from pytorch_layer_test_class import PytorchLayerTest
+
+
+class TestPatchMerging(PytorchLayerTest):
+ """Swin-style PatchMerging followed by a window block that reads H and W from its output.
+
+ The merge is view -> four step-2 slices -> cat -> view. With dynamic input shapes the window
+ block's `view(B, H, W, C)` is a ShapeOf sub-graph of the concatenated tensor (H/2, W/2) that
+ the symbolic shape optimizations must not re-source to the tensor before the slices (H, W).
+ """
+
+ def _prepare_input(self, image_hw):
+ return (self.random.randn(1, 3, *image_hw),)
+
+ def create_model(self):
+ class patch_merging_block(torch.nn.Module):
+ def __init__(self, in_channels=3, embed_dim=8, window_size=4):
+ super().__init__()
+ self.window_size = window_size
+ self.proj = torch.nn.Conv2d(in_channels, embed_dim, kernel_size=4, stride=4)
+ self.norm = torch.nn.LayerNorm(4 * embed_dim)
+ self.reduction = torch.nn.Linear(4 * embed_dim, 2 * embed_dim, bias=False)
+ self.norm1 = torch.nn.LayerNorm(2 * embed_dim)
+ self.mix = torch.nn.Linear(2 * embed_dim, 2 * embed_dim)
+
+ def forward(self, image):
+ x = self.proj(image)
+ b, c, h, w = x.shape
+ x = x.flatten(2).transpose(1, 2)
+ # PatchMerging
+ x = x.view(b, h, w, c)
+ x0 = x[:, 0::2, 0::2, :]
+ x1 = x[:, 1::2, 0::2, :]
+ x2 = x[:, 0::2, 1::2, :]
+ x3 = x[:, 1::2, 1::2, :]
+ x = torch.cat([x0, x1, x2, x3], -1)
+ _, h, w, _ = x.shape
+ x = x.view(b, -1, 4 * c)
+ x = self.reduction(self.norm(x))
+ # window block of the next stage
+ b, _, c = x.shape
+ shortcut = x
+ x = self.norm1(x)
+ x = x.view(b, h, w, c)
+ ws = self.window_size
+ pad_r = (ws - w % ws) % ws
+ pad_b = (ws - h % ws) % ws
+ x = F.pad(x, (0, 0, 0, pad_r, 0, pad_b))
+ _, hp, wp, _ = x.shape
+ nh, nw = hp // ws, wp // ws
+ windows = x.view(b, nh, ws, nw, ws, c).permute(0, 1, 3, 2, 4, 5).contiguous()
+ windows = windows.view(-1, ws * ws, c)
+ windows = self.mix(windows)
+ x = windows.view(b, nh, nw, ws, ws, c).permute(0, 1, 3, 2, 4, 5).contiguous()
+ x = x.view(b, hp, wp, c)
+ if pad_r > 0 or pad_b > 0:
+ x = x[:, :h, :w, :].contiguous()
+ x = x.view(b, h * w, c)
+ x = shortcut + x
+ return x.view(b, h, w, c).permute(0, 3, 1, 2)
+
+ return patch_merging_block(), "aten::slice"
+
+ # merged H x W is 8x12 (multiple of the window, no padding) and 5x7 (padded)
+ @pytest.mark.parametrize("image_hw", [(64, 96), (40, 56)])
+ @pytest.mark.nightly
+ @pytest.mark.precommit
+ def test_patch_merging(self, image_hw, ie_device, precision, ir_version):
+ self._test(*self.create_model(), ie_device, precision, ir_version,
+ kwargs_to_prepare_input={"image_hw": image_hw},
+ use_convert_model=True, trace_model=True)