Skip to content

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

[NPUW]Introduce in PropagateSliceUp to reduce TTFT. (#37609)

intelgaoxiongd903dc909e2f
diff --git a/src/plugins/intel_npu/src/al/include/intel_npu/config/npuw_option_defs.inc b/src/plugins/intel_npu/src/al/include/intel_npu/config/npuw_option_defs.inc
index 8bfec8f005d..e844d18cd39 100644
--- a/src/plugins/intel_npu/src/al/include/intel_npu/config/npuw_option_defs.inc
+++ b/src/plugins/intel_npu/src/al/include/intel_npu/config/npuw_option_defs.inc
@@ -66,6 +66,7 @@ INTEL_NPU_NPUW_SIMPLE_OPT(NPUW_LLM_OPTIMIZE_V_TENSORS, bool, true, ov::intel_npu
INTEL_NPU_NPUW_SIMPLE_OPT(NPUW_LLM_GENERATE_PYRAMID, bool, true, ov::intel_npu::npuw::llm, generate_pyramid, "NPUW_LLM_GENERATE_PYRAMID", LLM, EXPOSED, CACHED, ALL)
INTEL_NPU_NPUW_SIMPLE_OPT(NPUW_LLM_PREFILL_CHUNK_SIZE, uint64_t, 1024, ov::intel_npu::npuw::llm, prefill_chunk_size, "NPUW_LLM_PREFILL_CHUNK_SIZE", LLM, EXPOSED, CACHED, ALL)
INTEL_NPU_NPUW_SIMPLE_OPT(NPUW_LLM_SHARED_HEAD, bool, true, ov::intel_npu::npuw::llm, shared_lm_head, "NPUW_LLM_SHARED_HEAD", LLM, EXPOSED, CACHED, ALL)
+INTEL_NPU_NPUW_SIMPLE_OPT(NPUW_LLM_PROPAGATE_SLICE_UP, bool, false, ov::intel_npu::npuw::llm, propagate_slice_up, "NPUW_LLM_PROPAGATE_SLICE_UP", LLM, EXPOSED, CACHED, ALL)
INTEL_NPU_NPUW_SIMPLE_OPT(NPUW_LLM_MAX_LORA_RANK, uint32_t, 32, ov::intel_npu::npuw::llm, max_lora_rank, "NPUW_LLM_MAX_LORA_RANK", LLM, EXPOSED, CACHED, ALL)
INTEL_NPU_NPUW_SIMPLE_OPT(NPUW_LLM_OPTIMIZE_FP8, bool, false, ov::intel_npu::npuw::llm, optimize_fp8, "NPUW_LLM_OPTIMIZE_FP8", LLM, EXPOSED, CACHED, ALL)
INTEL_NPU_NPUW_SIMPLE_OPT(NPUW_LLM_ENABLE_PREFIX_CACHING, bool, false, ov::intel_npu::npuw::llm, enable_prefix_caching, "NPUW_LLM_ENABLE_PREFIX_CACHING", LLM, EXPOSED, CACHED, ALL)
diff --git a/src/plugins/intel_npu/src/plugin/CMakeLists.txt b/src/plugins/intel_npu/src/plugin/CMakeLists.txt
index 1e9e219aebe..1ca850a1b0e 100644
--- a/src/plugins/intel_npu/src/plugin/CMakeLists.txt
+++ b/src/plugins/intel_npu/src/plugin/CMakeLists.txt
@@ -21,6 +21,13 @@ ov_add_plugin(NAME ${NPU_PLUGIN_TARGET}
set_target_properties(${TARGET_NAME} PROPERTIES INTERPROCEDURAL_OPTIMIZATION_RELEASE ${ENABLE_LTO})
ov_add_clang_format_target(${TARGET_NAME}_clang FOR_TARGETS ${TARGET_NAME})
+# rtti.hpp applies __attribute__((visibility("hidden"))) to static member functions.
+# GCC 13+ warns about this with -Wattributes. All transformation files are affected;
+# existing ones escape only because incremental CI caches their .o files.
+if(CMAKE_CXX_COMPILER_ID STREQUAL "GNU")
+ target_compile_options(${TARGET_NAME} PRIVATE -Wno-attributes)
+endif()
+
target_link_libraries(${TARGET_NAME}
PRIVATE
openvino_npu_common
diff --git a/src/plugins/intel_npu/src/plugin/npuw/attn/attn_subgraph.cpp b/src/plugins/intel_npu/src/plugin/npuw/attn/attn_subgraph.cpp
index abfac7f743c..a55a727aba5 100644
--- a/src/plugins/intel_npu/src/plugin/npuw/attn/attn_subgraph.cpp
+++ b/src/plugins/intel_npu/src/plugin/npuw/attn/attn_subgraph.cpp
@@ -187,8 +187,8 @@ void ensure_hfa_selector(ov::npuw::v1::subgraphs::InferContext& ctx, RuntimeStat
OPENVINO_ASSERT(hfa != nullptr, "Missing compiled HFA state");
auto& request = get_request(ctx);
- const size_t query_size = hfa->_sdpa_attention_info._query_size;
- state.hfa_selector = runtime::host_flash_attention::PositionIDs::find(query_size, request);
+ const size_t original_query_length = hfa->_sdpa_attention_info._query_size;
+ state.hfa_selector = runtime::host_flash_attention::PositionIDs::find(original_query_length, request);
if (!state.hfa_selector) {
OPENVINO_THROW("HFA dynamic capability is enabled, but no run-time features were found.");
}
diff --git a/src/plugins/intel_npu/src/plugin/npuw/host_flash_attention.cpp b/src/plugins/intel_npu/src/plugin/npuw/host_flash_attention.cpp
index 56480e8a5f8..21cac3632ca 100644
--- a/src/plugins/intel_npu/src/plugin/npuw/host_flash_attention.cpp
+++ b/src/plugins/intel_npu/src/plugin/npuw/host_flash_attention.cpp
@@ -12,6 +12,7 @@
#include "intel_npu/ops/flash_attention_tile.hpp"
#include "logging.hpp"
#include "npuw_transformations/detect_causal_mask.hpp"
+#include "npuw_transformations/propagate_slice.hpp"
#include "openvino/core/validation_util.hpp"
#include "openvino/op/ops.hpp"
#include "openvino/openvino.hpp"
@@ -127,7 +128,9 @@ static HFATileInputs create_hfa_tile_inputs(const ov::Shape& q_shape,
inputs.q = std::make_shared<ov::op::v0::Parameter>(q_dtype, ov::Shape{batch, num_heads, seq_len, head_dim});
set_param_name(inputs.q, HFATileInputId::Q);
- // mask_tile: [batch, 1, seq_len, tile_size] - use mask's original dtype
+ // mask_tile: [batch, 1, seq_len, tile_size]
+ // - seq_len (dim 2): Q sequence length (actual, may be 1 after PropagateSliceUp)
+ // - tile_size (dim 3): KV tile length (original query_length, e.g., 1024)
inputs.mask_tile =
std::make_shared<ov::op::v0::Parameter>(mask_dtype,
ov::Shape{batch, 1, seq_len, static_cast<size_t>(tile_size)});
@@ -1032,8 +1035,12 @@ std::optional<HostFlashAttention> HostFlashAttention::from(const std::shared_ptr
LOG_WARN("Q shape must be 4D, got " << q_shape_static.size() << "D shape");
return std::nullopt;
}
- std::size_t query_size = q_shape_static[2]; // seq_len at index 2
- LOG_DEBUG("Extracted query_size (seq_len) from Q shape: " << query_size);
+
+ // query_size: original (pre-slice) query length used for tile_size/PREFILL-GENERATE/context_length
+ // logic. Defaults to the actual Q shape value, but PropagateSliceUp may have sliced Q's seq_len
+ // down to 1, in which case actual_query_size below no longer reflects the original chunk size.
+ std::size_t actual_query_size = q_shape_static[2]; // Actual Q seq_len (may be sliced to 1)
+ std::size_t query_size = ov::npuw::resolve_original_query_length(actual_query_size, pattern_nodes.matmul2_node);
auto mask_param = ov::npuw::util::find_mask_parameter(pattern_nodes.add_node);
if (!mask_param) {
@@ -1093,8 +1100,13 @@ std::optional<HostFlashAttention> HostFlashAttention::from(const std::shared_ptr
return std::nullopt;
}
+ // tile_size: shared by regular and final tiles. The final tile's actual present-KV
+ // length is asserted equal to it at runtime (attn_subgraph.cpp), so they can't differ
+ // yet anyway (e.g. SWA); revisit as a separate variable if that changes.
+ const std::size_t tile_size = query_size;
+
// ========================================================================
- // Step 5: Create tile models using query_size as tile_size
+ // Step 5: Create tile models
// ========================================================================
// V tensors are pre-transposed (stored as [B,H,head_dim,seq]) only when OptimizeValueTensors
// succeeded, which is reflected by the V-concat axis being 3 instead of the default 2.
@@ -1104,7 +1116,7 @@ std::optional<HostFlashAttention> HostFlashAttention::from(const std::shared_ptr
// Final tile: state still uses block_kv_dtype (f16) for zero-copy with regular
// tile outputs; KV-tile uses present_kv_dtype (f32) matching the upstream graph.
// past_acc/max/d: f16 k_tile/v_tile: f32 (present-KV from upstream)
- LOG_INFO("Creating HFA tile models: tile_size=" << query_size << ", v_transposed=" << v_transposed
+ LOG_INFO("Creating HFA tile models: tile_size=" << tile_size << ", v_transposed=" << v_transposed
<< ", block_kv=" << block_kv_dtype
<< ", present_kv=" << present_kv_dtype << ", q=" << q_dtype);
@@ -1156,7 +1168,7 @@ std::optional<HostFlashAttention> HostFlashAttention::from(const std::shared_ptr
block_kv_dtype, // kv_tile_dtype (past blocks)
q_dtype,
mask_dtype,
- query_size,
+ tile_size,
kv_num_heads,
false,
fused_flash_attention,
@@ -1172,7 +1184,7 @@ std::optional<HostFlashAttention> HostFlashAttention::from(const std::shared_ptr
present_kv_dtype, // kv_tile_dtype (present-KV, f32)
q_dtype,
mask_dtype,
- query_size,
+ tile_size,
kv_num_heads,
true,
fused_flash_attention,
@@ -1190,9 +1202,9 @@ std::optional<HostFlashAttention> HostFlashAttention::from(const std::shared_ptr
HostFlashAttention hfa;
hfa._tile_model = tile_model;
hfa._final_tile_model = final_tile_model;
- hfa._query_size = query_size;
+ hfa._query_size = query_size; // Query length for PREFILL/GENERATE logic and context_length
hfa._context_size = context_size;
- hfa._tile_size = query_size;
+ hfa._tile_size = tile_size; // KV tile size, used for runtime tile-count math
hfa._k_seq_dim = k_seq_dim;
hfa._v_seq_dim = v_seq_dim;
@@ -1213,8 +1225,8 @@ std::optional<HostFlashAttention> HostFlashAttention::from(const std::shared_ptr
// ========================================================================
build_tile_output_mapping(hfa, tile_model);
- LOG_INFO("Successfully created HostFlashAttention with query_size="
- << query_size << ", context_size=" << context_size << ", tile_size=" << query_size);
+ LOG_INFO("Successfully created HostFlashAttention with query_size=" << query_size << ", context_size="
+ << context_size << ", tile_size=" << tile_size);
return hfa;
}
@@ -1316,15 +1328,16 @@ namespace runtime {
namespace host_flash_attention {
// PositionIDs constructor
-PositionIDs::PositionIDs(std::size_t param_idx, std::size_t query_size, const ov::ISyncInferRequest& rq)
+PositionIDs::PositionIDs(std::size_t param_idx, std::size_t original_query_length, const ov::ISyncInferRequest& rq)
: _position_ids_idx(param_idx),
- _query_size(query_size),
+ _original_query_length(original_query_length),
_rq(rq) {
- // FIXME: speculative decode is indistinguishable at this point!
- _case = _query_size == 1 ? Case::GENERATE : Case::PREFILL;
+ // Use original_query_length to determine PREFILL vs GENERATE
+ // (query_size may be 1 after PropagateSliceUp, but that doesn't mean it's GENERATE)
+ _case = _original_query_length == 1 ? Case::GENERATE : Case::PREFILL;
}
-Selector::Ptr PositionIDs::find(std::size_t query_size, const ov::ISyncInferRequest& rq) {
+Selector::Ptr PositionIDs::find(std::size_t original_query_length, const ov::ISyncInferRequest& rq) {
auto is_position_ids = [](const ov::Output<const ov::Node>& p) {
const auto& shape = p.get_shape();
// FIXME: 2D/3D position IDs are not supported here YET
@@ -1336,7 +1349,7 @@ Selector::Ptr PositionIDs::find(std::size_t query_size, const ov::ISyncInferRequ
auto pos_ids_iter = std::find_if(inputs.begin(), inputs.end(), is_position_ids);
if (pos_ids_iter != inputs.end()) {
const auto param_idx = std::distance(inputs.begin(), pos_ids_iter);
- return Selector::Ptr{new PositionIDs(param_idx, query_size, rq)};
+ return Selector::Ptr{new PositionIDs(param_idx, original_query_length, rq)};
}
return Selector::Ptr{};
}
@@ -1360,7 +1373,8 @@ void PositionIDs::prepare(int64_t past_len) {
case Case::PREFILL:
// chunked prefill case. calculate the past_length in full chunks
// FIXME: We know too much about chunking here
- _past_length = ((past_len + _query_size - 1) / _query_size) * _query_size;
+ _past_length =
+ ((past_len + _original_query_length - 1) / _original_query_length) * _original_query_length;
break;
default:
NPUW_ASSERT(false && "Reached the unreachable code");
@@ -1373,7 +1387,8 @@ void PositionIDs::prepare(int64_t past_len) {
}
int64_t PositionIDs::context_length() const {
- return _query_size + _past_length;
+ // Use original_query_length for context calculation (not query_size which may be sliced to 1)
+ return _original_query_length + _past_length;
}
// ============================================================================
diff --git a/src/plugins/intel_npu/src/plugin/npuw/host_flash_attention.hpp b/src/plugins/intel_npu/src/plugin/npuw/host_flash_attention.hpp
index 76c4694e169..dee0eef8059 100644
--- a/src/plugins/intel_npu/src/plugin/npuw/host_flash_attention.hpp
+++ b/src/plugins/intel_npu/src/plugin/npuw/host_flash_attention.hpp
@@ -93,8 +93,13 @@ struct HostFlashAttention {
// Tile configuration
int64_t _tile_size = 0; // K/V tile size for flash attention chunking
- // Query sequence length (extracted from Q shape[2])
- // Used for selector compatibility and runtime decision-making
+ // Query length used for tile_size/PREFILL-GENERATE/context_length logic.
+ // Equal to Q shape[2] when PropagateSliceUp did not touch this SDPA (in which
+ // case it may legitimately be 1 for a true single-token GENERATE model).
+ // When PropagateSliceUp DID fire, this holds the original (pre-slice) query
+ // length recovered from rt_info, not the sliced-down physical shape[2] — the
+ // PREFILL/chunk-rounding math must keep using the original chunk size even
+ // though the actual per-call Q is now physically 1.
std::size_t _query_size = 0;
// Context size (extracted from K concat output shape - kv_cache_size dimension)
@@ -153,7 +158,8 @@ namespace compiled {
// Simplified host flash attention parameter info
// Contains parameter indices from the original SDPA model
struct HostFlashAttentionInfo {
- std::size_t _query_size = 0u; // query size for selector compatibility
+ std::size_t _query_size = 0u; // query length for tile_size/PREFILL-GENERATE/context_length logic
+ // (original, pre-slice length if PropagateSliceUp touched this SDPA)
std::size_t _context_size = 0u;
// Sequence dimension indices for K and V tensors in the original SDPA model
@@ -311,17 +317,17 @@ struct HFARuntimeContext {
const auto mask_shape = mask_port.get_shape();
const auto mask_dtype = mask_port.get_element_type();
- // Calculate maximum number of tiles based on context size
+ // Calculate maximum number of tiles based on context size.
const size_t context_size = hfa_desc._sdpa_attention_info._context_size;
- const size_t query_size = hfa_desc._sdpa_attention_info._query_size;
+ const size_t tile_size = hfa_desc._sdpa_attention_info._query_size;
// Validate configuration
- if (context_size % query_size != 0) {
+ if (context_size % tile_size != 0) {
throw std::runtime_error("HFA: context_size (" + std::to_string(context_size) +
- ") must be divisible by query_size (" + std::to_string(query_size) + ")");
+ ") must be divisible by tile_size (" + std::to_string(tile_size) + ")");
}
- const size_t max_num_tiles = context_size / query_size;
+ const size_t max_num_tiles = context_size / tile_size;
// Allocate temporary buffers for mask tile extraction
m_mask_tile_buffers.clear();
@@ -464,16 +470,16 @@ class PositionIDs final : public Selector {
std::size_t _position_ids_idx = 0u;
int64_t _current_length = 0;
int64_t _past_length = 0;
- std::size_t _query_size = 0u;
+ std::size_t _original_query_length = 0u; // original query length before PropagateSliceUp
std::reference_wrapper<const ov::ISyncInferRequest> _rq;
- PositionIDs(std::size_t param_idx, std::size_t query_size, const ov::ISyncInferRequest& rq);
+ PositionIDs(std::size_t param_idx, std::size_t original_query_length, const ov::ISyncInferRequest& rq);
void prepare(int64_t past_len) override;
int64_t context_length() const override;
public:
- static Selector::Ptr find(std::size_t query_size, const ov::ISyncInferRequest& rq);
+ static Selector::Ptr find(std::size_t original_query_length, const ov::ISyncInferRequest& rq);
};
} // namespace host_flash_attention
diff --git a/src/plugins/intel_npu/src/plugin/npuw/llm_compiled_model.cpp b/src/plugins/intel_npu/src/plugin/npuw/llm_compiled_model.cpp
index 2c5883ccb26..7f0332ad940 100644
--- a/src/plugins/intel_npu/src/plugin/npuw/llm_compiled_model.cpp
+++ b/src/plugins/intel_npu/src/plugin/npuw/llm_compiled_model.cpp
@@ -22,6 +22,7 @@
#include "npuw_transformations/lora_stateful_to_stateless.hpp"
#include "npuw_transformations/optimize_value_tensors.hpp"
#include "npuw_transformations/patch_sliding_window_mask.hpp"
+#include "npuw_transformations/propagate_slice.hpp"
#include "npuw_transformations/remove_token_type_ids.hpp"
#include "npuw_transformations/replace_deepstack_scatter_with_add.hpp"
#include "npuw_transformations/reshape_sliced_head_to_static.hpp"
@@ -1047,11 +1048,25 @@ ov::npuw::LLMCompiledModel::LLMCompiledModel(const std::shared_ptr<ov::Model>& m
LOG_DEBUG("Encoder embedding model: skipping generate model variants (prefill-only).");
}
+ const bool is_per_layer_inputs_model = has_per_layer_inputs(prefill_model);
+ bool propagate_slice_up = m_cfg.get<::intel_npu::NPUW_LLM_PROPAGATE_SLICE_UP>();
+
if (lm_head_model) {
LOG_DEBUG("Shared LM head: slice the prefill output");
// KVCache model is already reshaped to [1, max_generation_token_len, embed size],
// so only apply slice to the Prefill model:
ov::npuw::SliceOutEmbeds(axes.batch, m_kvcache_desc.max_generation_token_len).run_on_model(prefill_model);
+ // Gemma-4 E2B/E4B cross-group KV sharing models benefit the most from hoisting the slice
+ // through the SWA/Global boundary, so auto-enable this option for them unless the user
+ // explicitly configured it.
+ if (is_per_layer_inputs_model && !m_cfg.has<::intel_npu::NPUW_LLM_PROPAGATE_SLICE_UP>()) {
+ m_cfg.update({{"NPUW_LLM_PROPAGATE_SLICE_UP", "YES"}});
+ propagate_slice_up = true;
+ LOG_INFO("Gemma-4 cross-group KV model: auto-enabling NPUW_LLM_PROPAGATE_SLICE_UP");
+ }
+ if (propagate_slice_up) {
+ ov::npuw::PropagateSliceUp().run_on_model(prefill_model);
+ }
LOG_DEBUG("Make LM head model with static shapes");
ov::npuw::ReshapeSlicedHeadToStatic(axes.batch, m_kvcache_desc.max_generation_token_len)
.run_on_model(lm_head_model);
@@ -1205,8 +1220,11 @@ ov::npuw::LLMCompiledModel::LLMCompiledModel(const std::shared_ptr<ov::Model>& m
// Both variants fall below the default keep_blocks=5 threshold and remain as
// separate FCE compile units. Lower to 3 so both are folded into REP and
// reused across their respective instances.
- if (has_per_layer_inputs(prefill_model)) {
+ if (is_per_layer_inputs_model) {
prefill_config["NPUW_ONLINE_KEEP_BLOCKS"] = "3";
+ if (propagate_slice_up) {
+ prefill_config["NPUW_ONLINE_KEEP_BLOCKS_TAGGED"] = "attn";
+ }
LOG_INFO("Gemma-4 cross-group KV model: setting NPUW_ONLINE_KEEP_BLOCKS=3 for prefill");
}
}
@@ -1963,6 +1981,7 @@ void ov::npuw::LLMCompiledModel::implement_properties() {
BIND(npuw::llm::prefill_attn_hint, NPUW_LLM_PREFILL_ATTENTION_HINT, getString),
BIND(npuw::llm::generate_attn_hint, NPUW_LLM_GENERATE_ATTENTION_HINT, getString),
BIND(npuw::llm::shared_lm_head, NPUW_LLM_SHARED_HEAD, get),
+ BIND(npuw::llm::propagate_slice_up, NPUW_LLM_PROPAGATE_SLICE_UP, get),
BIND(npuw::whisper::enabled, NPUW_WHISPER, get),
BIND(npuw::whisper::whisper_eos_token, NPUW_WHISPER_EOS_TOKEN, get),
BIND(npuw::whisper::whisper_decompose_sdpa, NPUW_WHISPER_DECOMPOSE_SDPA, get),
diff --git a/src/plugins/intel_npu/src/plugin/npuw/npuw_transformations/propagate_slice.cpp b/src/plugins/intel_npu/src/plugin/npuw/npuw_transformations/propagate_slice.cpp
new file mode 100644
index 00000000000..8a3cf4cbe28
--- /dev/null
+++ b/src/plugins/intel_npu/src/plugin/npuw/npuw_transformations/propagate_slice.cpp
@@ -0,0 +1,2332 @@
+// Copyright (C) 2018-2026 Intel Corporation
+// SPDX-License-Identifier: Apache-2.0
+//
+
+#include "propagate_slice.hpp"
+
+#include <cstring>
+#include <map>
+#include <optional>
+#include <tuple>
+#include <vector>
+
+#include "../logging.hpp"
+#include "openvino/core/graph_util.hpp"
+#include "openvino/core/validation_util.hpp"
+#include "openvino/op/ops.hpp"
+#include "openvino/op/util/op_types.hpp"
+#include "openvino/pass/graph_rewrite.hpp"
+#include "openvino/pass/manager.hpp"
+#include "openvino/pass/pattern/matcher.hpp"
+#include "openvino/pass/pattern/op/wrap_type.hpp"
+
+namespace ov::npuw {
+
+std::optional<std::size_t> find_propagated_original_query_length(const std::shared_ptr<ov::Node>& matmul2_node) {
+ if (!matmul2_node) {
+ return std::nullopt;
+ }
+ const auto& rt_info = matmul2_node->get_rt_info();
+ if (!rt_info.count(NPUW_ORIGINAL_QUERY_LENGTH_RT_KEY)) {
+ return std::nullopt;
+ }
+ try {
+ return rt_info.at(NPUW_ORIGINAL_QUERY_LENGTH_RT_KEY).as<std::size_t>();
+ } catch (...) {
+ LOG_WARN("Failed to read " << NPUW_ORIGINAL_QUERY_LENGTH_RT_KEY << " from rt_info");
+ return std::nullopt;
+ }
+}
+
+std::size_t resolve_original_query_length(std::size_t fallback_length, const std::shared_ptr<ov::Node>& matmul2_node) {
+ const auto propagated_query_length = find_propagated_original_query_length(matmul2_node);
+ if (propagated_query_length) {
+ LOG_INFO("PropagateSliceUp detected: original query length="
+ << *propagated_query_length << " (shape-derived fallback was " << fallback_length << ")");
+ return *propagated_query_length;
+ }
+ LOG_DEBUG("No PropagateSliceUp rt_info found, using shape-derived query length: " << fallback_length);
+ return fallback_length;
+}
+
+} // namespace ov::npuw
+
+namespace {
+
+using namespace ov::pass::pattern;
+
+// ---------------------------------------------------------------------------
+// Helpers
+// ---------------------------------------------------------------------------
+
+// Returns true when the Slice actually reduces the tensor on its sliced axis
+// (i.e. output size < input size) and all shapes are static.
+static bool is_reducing_slice(const std::shared_ptr<ov::op::v8::Slice>& slice) {
+ const auto& in_shape = slice->get_input_partial_shape(0);
+ const auto& out_shape = slice->get_output_partial_shape(0);
+ if (in_shape.is_dynamic() || out_shape.is_dynamic()) {
+ return false;
+ }
+ // At least one dimension must be strictly smaller.
+ for (size_t i = 0; i < in_shape.size(); ++i) {
+ if (out_shape[i].get_length() < in_shape[i].get_length()) {
+ return true;
+ }
+ }
+ return false;
+}
+
+// Extract the full axis -> (start, stop, step) mapping of a (possibly multi-axis) Slice.
+// Returns false if the Slice's start/stop/step/axes inputs aren't foldable constants, or if
+// their sizes are inconsistent.
+static bool get_slice_all_axis_params(const std::shared_ptr<ov::op::v8::Slice>& slice,
+ std::map<int64_t, std::tuple<int64_t, int64_t, int64_t>>& out_params) {
+ auto axes_const = std::dynamic_pointer_cast<ov::op::v0::Constant>(slice->input_value(4).get_node_shared_ptr());
+ auto start_const = std::dynamic_pointer_cast<ov::op::v0::Constant>(slice->input_value(1).get_node_shared_ptr());
+ auto stop_const = std::dynamic_pointer_cast<ov::op::v0::Constant>(slice->input_value(2).get_node_shared_ptr());
+ auto step_const = std::dynamic_pointer_cast<ov::op::v0::Constant>(slice->input_value(3).get_node_shared_ptr());
+ if (!axes_const || !start_const || !stop_const || !step_const) {
+ return false;
+ }
+
+ auto axes = axes_const->cast_vector<int64_t>();
+ auto starts = start_const->cast_vector<int64_t>();
+ auto stops = stop_const->cast_vector<int64_t>();
+ auto steps = step_const->cast_vector<int64_t>();
+ if (axes.size() != starts.size() || axes.size() != stops.size() || axes.size() != steps.size()) {
+ return false;
+ }
+
+ out_params.clear();
+ const size_t rank = slice->get_input_shape(0).size();
+ for (size_t i = 0; i < axes.size(); ++i) {
+ out_params[static_cast<int64_t>(ov::util::normalize_axis(axes[i], static_cast<int64_t>(rank)))] = {starts[i],
+ stops[i],
+ steps[i]};
+ }
+ return true;
+}
+
+// Returns true when (start, stop, step) is an identity range on an axis of size `dim`, i.e. it
+// keeps every element in its original order (step=1, effective start=0, effective stop>=dim). A
+// non-identity range on a same-size axis (e.g. a negative-step reversal, or a reordering) has a
+// real effect that single-axis rebuilding (get_slice_axis_params + create_slice_with_params)
+// would silently drop. `start` only resolves to 0 when it's literally 0 or negative enough to
+// wrap around to (or past) index 0 (start <= -dim); a small negative start like -1 wraps to
+// dim-1, which is NOT the beginning of the axis.
+static bool is_identity_range(int64_t start, int64_t stop, int64_t step, int64_t dim) {
+ bool start_is_zero = (start == 0) || (start <= -dim);
+ return step == 1 && start_is_zero && stop >= dim;
+}
+
+// Returns the single axis that is sliced (where output dim < input dim), or -1 if the Slice is
+// not safely treatable as single-axis: zero or more than one axis reduced, dynamic shapes, or any
+// *other* axis named in the Slice's own axes/start/stop/step constants has a non-identity range
+// (e.g. a same-size reversal) that would be silently dropped when a rule rebuilds only this axis.
+static int64_t get_single_sliced_axis(const std::shared_ptr<ov::op::v8::Slice>& slice) {
+ const auto& in_shape = slice->get_input_partial_shape(0);
+ const auto& out_shape = slice->get_output_partial_shape(0);
+ if (in_shape.is_dynamic() || out_shape.is_dynamic()) {
+ return -1;
+ }
+
+ int64_t axis = -1;
+ for (size_t i = 0; i < in_shape.size(); ++i) {
+ if (out_shape[i].get_length() < in_shape[i].get_length()) {
+ if (axis != -1) {
+ return -1; // more than one axis sliced
+ }
+ axis = static_cast<int64_t>(i);
+ }
+ }
+ if (axis == -1) {
+ return -1;
+ }
+
+ std::map<int64_t, std::tuple<int64_t, int64_t, int64_t>> all_params;
+ if (!get_slice_all_axis_params(slice, all_params)) {
+ return -1; // can't verify the other axes are identity -> reject conservatively
+ }
+ const auto& in_shape_static = slice->get_input_shape(0);
+ for (const auto& [other_axis, params] : all_params) {
+ if (other_axis == axis) {
+ continue;
+ }
+ auto [start, stop, step] = params;
+ if (!is_identity_range(start, stop, step, static_cast<int64_t>(in_shape_static[other_axis]))) {
+ return -1; // non-identity op on a non-reducing axis - unsafe to treat as single-axis
+ }
+ }
+ return axis;
+}
+
+// Returns the consumers of a node's output, excluding ones that are themselves already
+// disconnected from the rest of the model (no consumers of their own). Such stale edges are
+// left behind by rules that redirect a Slice's consumers via replace_node() without touching
+// the Slice's own inputs; treating them as live would make a rule refire on them forever.
+static std::vector<ov::Input<ov::Node>> get_live_consumers(const std::shared_ptr<ov::Node>& node,
+ size_t output_index = 0) {
+ std::vector<ov::Input<ov::Node>> live;
+ for (const auto& input : node->get_output_target_inputs(output_index)) {
+ auto consumer = input.get_node();
+ // A node is "dead" only if none of its outputs have any consumers left.
+ bool has_any_consumer = false;
+ for (size_t o = 0; o < consumer->get_output_size(); ++o) {
+ if (!consumer->get_output_target_inputs(o).empty()) {
+ has_any_consumer = true;
+ break;
+ }
+ }
+ if (has_any_consumer || ov::op::util::is_output(consumer)) {
+ live.push_back(input);
+ }
+ }
+ return live;
+}
+
+// Returns true when the parent op has exactly one live consumer (the Slice).
+static bool single_consumer(const std::shared_ptr<ov::Node>& parent) {
+ for (size_t p = 0; p < parent->get_output_size(); ++p) {
+ if (get_live_consumers(parent, p).size() != 1) {
+ return false;
+ }
+ }
+ return true;
+}
+
+// Returns the sliced axis when propagation through `parent` is safe (the Slice actually
+// reduces the tensor, operates on a single axis, and `parent` has no other consumers -
+// otherwise moving the Slice upstream would change other users' inputs), or -1 otherwise.
+static int64_t get_propagation_axis(const std::shared_ptr<ov::op::v8::Slice>& slice,
+ const std::shared_ptr<ov::Node>& parent) {
+ if (!single_consumer(parent)) {
+ return -1;
+ }
+ return get_single_sliced_axis(slice);
+}
+
+// Extract the start/stop/step params that a (possibly multi-axis) Slice applies to a specific
+// axis of its own input/output (axis positions and rank are unaffected by Slice itself).
+// Returns false if the Slice's params aren't foldable constants or don't cover that axis.
+// Delegates to get_slice_all_axis_params() to avoid duplicating constant-extraction logic.
+static bool get_slice_axis_params(const std::shared_ptr<ov::op::v8::Slice>& slice_node,
+ int64_t axis,
+ int64_t& start,
+ int64_t& stop,
+ int64_t& step) {
+ std::map<int64_t, std::tuple<int64_t, int64_t, int64_t>> all_params;
+ if (!get_slice_all_axis_params(slice_node, all_params)) {
+ return false;
+ }
+ auto it = all_params.find(axis);
+ if (it == all_params.end()) {
+ return false;
+ }
+ std::tie(start, stop, step) = it->second;
+ return true;
+}
+
+// Clone a Slice onto a new data input, keeping start/stop/step/axes constants.
+static std::shared_ptr<ov::op::v8::Slice> clone_slice(const std::shared_ptr<ov::op::v8::Slice>& orig,
+ const ov::Output<ov::Node>& new_data) {
+ auto new_slice = std::make_shared<ov::op::v8::Slice>(new_data,
+ orig->input_value(1),
+ orig->input_value(2),
+ orig->input_value(3),
+ orig->input_value(4));
+ new_slice->validate_and_infer_types();
+ return new_slice;
+}
+
+// Create a new Slice with explicit parameters (for cases where we don't have an original Slice to extract from).
+static std::shared_ptr<ov::op::v8::Slice> create_slice_with_params(const ov::Output<ov::Node>& data,
+ int64_t axis,
+ int64_t start,
+ int64_t stop,
+ int64_t step) {
+ auto start_const = ov::op::v0::Constant::create(ov::element::i64, {1}, {start});
+ auto stop_const = ov::op::v0::Constant::create(ov::element::i64, {1}, {stop});
+ auto step_const = ov::op::v0::Constant::create(ov::element::i64, {1}, {step});
+ auto axes_const = ov::op::v0::Constant::create(ov::element::i64, {1}, {axis});
+
+ auto new_slice = std::make_shared<ov::op::v8::Slice>(data, start_const, stop_const, step_const, axes_const);
+ new_slice->validate_and_infer_types();
+ return new_slice;
+}
+
+// Create a new Slice with explicit multi-axis parameters (vector overload of create_slice_with_params(),
+// for merge/extraction rules that build a Slice spanning several axes at once).
+static std::shared_ptr<ov::op::v8::Slice> create_slice_with_params(const ov::Output<ov::Node>& data,
+ const std::vector<int64_t>& axes,
+ const std::vector<int64_t>& start,
+ const std::vector<int64_t>& stop,
+ const std::vector<int64_t>& step) {
+ auto start_const = ov::op::v0::Constant::create(ov::element::i64, {start.size()}, start);
+ auto stop_const = ov::op::v0::Constant::create(ov::element::i64, {stop.size()}, stop);
+ auto step_const = ov::op::v0::Constant::create(ov::element::i64, {step.size()}, step);
+ auto axes_const = ov::op::v0::Constant::create(ov::element::i64, {axes.size()}, axes);
+
+ auto new_slice = std::make_shared<ov::op::v8::Slice>(data, start_const, stop_const, step_const, axes_const);
+ new_slice->validate_and_infer_types();
+ return new_slice;
+}
+
+// Given the per-consumer axis->(start,stop,step) maps of several Slice nodes that all consume
+// the same producer, find the axes that are sliced identically (same start/stop/step) across
+// every consumer. Shared by ExtractCommonSliceBeforeFanout.
+static std::map<int64_t, std::tuple<int64_t, int64_t, int64_t>> find_common_slice_axes(
+ const std::vector<std::map<int64_t, std::tuple<int64_t, int64_t, int64_t>>>& per_slice_axis_params) {
+ std::map<int64_t, std::tuple<int64_t, int64_t, int64_t>> common;
+ if (per_slice_axis_params.empty()) {
+ return common;
+ }
+
+ for (const auto& [axis, params] : per_slice_axis_params[0]) {
+ bool is_common = true;
+ for (size_t i = 1; i < per_slice_axis_params.size(); ++i) {
+ auto it = per_slice_axis_params[i].find(axis);
+ if (it == per_slice_axis_params[i].end() || it->second != params) {
+ is_common = false;
+ break;
+ }
+ }
+ if (is_common) {
+ common[axis] = params;
+ }
+ }
+ return common;
+}
+
+// ---------------------------------------------------------------------------
+// R1 – Slice(Eltwise1(X)) -> Eltwise1(Slice(X))
+// Single-input elementwise ops.
+// ---------------------------------------------------------------------------
+class PropagateSliceThroughUnary : public ov::pass::MatcherPass {
+public:
+ OPENVINO_MATCHER_PASS_RTTI("PropagateSliceThroughUnary");
+
+ PropagateSliceThroughUnary() {
+ // Match any unary elementwise followed by a Slice.
+ auto data = any_input();
+ auto unary = wrap_type<ov::op::v0::Gelu,
+ ov::op::v7::Gelu,
+ ov::op::v0::Relu,
+ ov::op::v0::Sqrt,
+ ov::op::v0::Tanh,
+ ov::op::v0::Sigmoid,
+ ov::op::v0::Erf,
+ ov::op::v4::Swish,
+ ov::op::v0::Exp,
+ ov::op::v0::Log,
+ ov::op::v0::Abs,
+ ov::op::v0::Negative,
+ ov::op::v1::LogicalNot,
+ ov::op::v0::HardSigmoid,
+ ov::op::v0::Selu,
+ ov::op::v0::Convert>({data});
+ auto slice = wrap_type<ov::op::v8::Slice>({unary, any_input(), any_input(), any_input(), any_input()});
+
+ register_matcher(std::make_shared<Matcher>(slice, "PropagateSliceThroughUnary"), [=](Matcher& m) {
+ auto& map = m.get_pattern_value_map();
+ auto slice_node = std::dynamic_pointer_cast<ov::op::v8::Slice>(map[slice].get_node_shared_ptr());
+ auto unary_node = map[unary].get_node_shared_ptr();
+
+ if (get_propagation_axis(slice_node, unary_node) == -1) {
+ return false;
+ }
+
+ // Slice(Unary(X)) -> Unary(Slice(X))
+ auto new_slice = clone_slice(slice_node, unary_node->input_value(0));
+ auto new_unary = unary_node->clone_with_new_inputs({new_slice});
+ new_unary->set_friendly_name(unary_node->get_friendly_name());
+ new_unary->validate_and_infer_types();
+
+ ov::replace_node(slice_node, new_unary);
+ return true;
+ });
+ }
+};
+
+// ---------------------------------------------------------------------------
+// R2 – Slice(Eltwise2(A, B)) -> Eltwise2(Slice(A), Slice(B))
+// or Eltwise2(Slice(A), B) when B broadcasts on the sliced axis.
+// ---------------------------------------------------------------------------
+class PropagateSliceThroughBinary : public ov::pass::MatcherPass {
+public:
+ OPENVINO_MATCHER_PASS_RTTI("PropagateSliceThroughBinary");
+
+ PropagateSliceThroughBinary() {
+ auto input_a = any_input();
+ auto input_b = any_input();
+ auto binary = wrap_type<ov::op::v1::Add,
+ ov::op::v1::Subtract,
+ ov::op::v1::Multiply,
+ ov::op::v1::Divide,
+ ov::op::v1::Maximum,
+ ov::op::v1::Minimum,
+ ov::op::v1::Power,
+ ov::op::v1::Equal,
+ ov::op::v1::Less,
+ ov::op::v1::Greater,
+ ov::op::v1::LessEqual,
+ ov::op::v1::GreaterEqual>({input_a, input_b});
+ auto slice = wrap_type<ov::op::v8::Slice>({binary, any_input(), any_input(), any_input(), any_input()});
+
+ register_matcher(std::make_shared<Matcher>(slice, "PropagateSliceThroughBinary"), [=](Matcher& m) {
+ auto& map = m.get_pattern_value_map();
+ auto slice_node = std::dynamic_pointer_cast<ov::op::v8::Slice>(map[slice].get_node_shared_ptr());
+ auto binary_node = map[binary].get_node_shared_ptr();
+
+ int64_t slice_axis = get_propagation_axis(slice_node, binary_node);
+ if (slice_axis == -1) {
+ return false;
+ }
+
+ const auto& shape_a = binary_node->get_input_partial_shape(0);
+ const auto& shape_b = binary_node->get_input_partial_shape(1);
+ if (shape_a.is_dynamic() || shape_b.is_dynamic())
+ return false;
+
+ // Determine which inputs need a Slice and which can stay as-is.
+ // An input can stay if the sliced axis has size 1 in that input
+ // (it will be broadcast to match the other input after slicing).
+ auto needs_slice = [&](const ov::PartialShape& shape) -> bool {
+ auto s = shape.to_shape();
+ // Rank-align: leading dims may be absent for lower-rank tensors
+ int64_t rank_diff =
+ static_cast<int64_t>(slice_node->get_output_shape(0).size()) - static_cast<int64_t>(s.size());
+ int64_t local_ax = slice_axis - rank_diff;
+ if (local_ax < 0)
+ return false; // dimension does not exist -> broadcast (size-1 implied)
+ if (s[static_cast<size_t>(local_ax)] != 1) {
+ return true; // real data on this axis, must slice
+ }
+ return false; // sliced axis is broadcast dim, no slice needed
+ };
+
+ bool slice_a = needs_slice(shape_a);
+ bool slice_b = needs_slice(shape_b);
+
+ if (!slice_a && !slice_b) {
+ // Neither operand is affected – shouldn't happen for a reducing slice
+ return false;
+ }
+
+ // Check if both inputs come from the same output (same node AND same output port -
+ // e.g. Add(split->output(0), split->output(1)) must NOT be treated as same_input,
+ // otherwise a Slice of output 0 would be wrongly reused for output 1 as well).
+ bool same_input = (binary_node->input_value(0) == binary_node->input_value(1));
+
+ ov::Output<ov::Node> new_a, new_b;
+
+ if (same_input && slice_a && slice_b) {
+ // Both inputs are the same node and both need slicing
+ // Create only ONE slice and reuse it for both inputs to avoid duplicates
+ auto shared_slice = clone_slice(slice_node, binary_node->input_value(0));
+ new_a = shared_slice;
+ new_b = shared_slice;
+ } else {
+ // Different inputs or only one needs slicing
+ new_a = slice_a ? clone_slice(slice_node, binary_node->input_value(0)) : binary_node->input_value(0);
+ new_b = slice_b ? clone_slice(slice_node, binary_node->input_value(1)) : binary_node->input_value(1);
+ }
+
+ auto new_binary = binary_node->clone_with_new_inputs({new_a, new_b});
+ new_binary->set_friendly_name(binary_node->get_friendly_name());
+ new_binary->validate_and_infer_types();
+
+ ov::replace_node(slice_node, new_binary);
+ return true;
+ });
+ }
+};
+
+// ---------------------------------------------------------------------------
+// R3 – Slice(SDPA(Q,K,V,mask,...)) -> SDPA(Slice(Q),K,V,Slice(mask),...)
+// when the sliced axis is the Q sequence dimension.
+// ---------------------------------------------------------------------------
+class PropagateSliceThroughSDPA : public ov::pass::MatcherPass {
+public:
+ OPENVINO_MATCHER_PASS_RTTI("PropagateSliceThroughSDPA");
+
+ PropagateSliceThroughSDPA() {
+ // SDPA output shape: [B, num_heads, seq_q, head_size] or [B, seq_q, hidden]
+ auto sdpa = wrap_type<ov::op::v13::ScaledDotProductAttention>();
+ auto slice = wrap_type<ov::op::v8::Slice>({sdpa, any_input(), any_input(), any_input(), any_input()});
+
+ register_matcher(std::make_shared<Matcher>(slice, "PropagateSliceThroughSDPA"), [=](Matcher& m) {
+ auto& map = m.get_pattern_value_map();
+ auto slice_node = std::dynamic_pointer_cast<ov::op::v8::Slice>(map[slice].get_node_shared_ptr());
+ auto sdpa_node = map[sdpa].get_node_shared_ptr();
+
+ // SDPA output: [B, num_heads, seq_q, head_size] (4-D after DecomposeGQA)
+ // Q input: [B, num_heads, seq_q, head_size]
+ // The sequence axis for Q is typically dim 2 (after head split).
+ // Before DecomposeGQA, output may be [B, seq_q, hidden] – seq axis is 1.
+ const auto& out_shape = slice_node->get_input_shape(0); // SDPA output shape
+
+ int64_t seq_axis = get_propagation_axis(slice_node, sdpa_node);
+ if (seq_axis == -1) {
+ return false;
+ }
+
+ // Guard: seq_axis must be the canonical Q-sequence axis, i.e. the second-to-last
+ // axis of the SDPA output ([B,H,Sq,D] -> axis=2, or [B,Sq,hidden] -> axis=1).
+ // Unlike Reshape, SDPA has no "total element count" invariant to fall back on:
+ // the check below only compares dimension *values*, not axis *semantics*. Without
+ // this guard, a Slice that happens to reduce some other axis (e.g. head_size or
+ // num_heads) whose size coincidentally matches Q's dimension at the same axis index
+ // would be silently mistreated as a sequence-dimension slice.
+ if (seq_axis != static_cast<int64_t>(out_shape.size()) - 2) {
+ return false;
+ }
+
+ // Check Q input shape
+ const auto& q_shape = sdpa_node->get_input_partial_shape(0);
+ if (q_shape.is_dynamic()) {
+ return false;
+ }
+
+ auto q_shape_static = q_shape.to_shape();
+
+ // The SDPA output seq dim and Q seq dim must match
+ if (q_shape[seq_axis].get_length() != static_cast<int64_t>(out_shape[static_cast<size_t>(seq_axis)])) {
+ return false;
+ }
+
+ // Slice Q
+ auto new_q = clone_slice(slice_node, sdpa_node->input_value(0));
+
+ // Validate that the mask is either a broadcast dim on the sequence axis or matches the
+ // sliced sequence length, then report whether it actually needs slicing. Requires the
+ // mask to have the SAME rank as the SDPA output: rank-aligning a lower-rank mask (e.g.
+ // [B,Sq,Sk] vs a 4-D [B,H,Sq,D] output) would need to remap seq_axis onto the mask's own
+ // axes, and cloning the original (output-indexed) Slice unchanged onto such a mask would
+ // silently slice the wrong axis. Rejecting rank mismatches keeps the mapping trivial and
+ // correct instead of guessing; returns nullopt to abort propagation in that case.
+ auto mask_needs_slice = [&](size_t input_idx) -> std::optional<bool> {
+ const auto& shape = sdpa_node->get_input_partial_shape(input_idx);
+ if (shape.is_dynamic()) {
+ return std::nullopt;
+ }
+ auto s = shape.to_shape();
+
+ if (s.size() != out_shape.size()) {
+ return std::nullopt; // rank mismatch -> axis mapping unreliable, don't propagate
+ }
+ if (s[static_cast<size_t>(seq_axis)] == 1) {
+ return false; // broadcast dim -> no slice needed
+ }
+ if (s[static_cast<size_t>(seq_axis)] != out_shape[static_cast<size_t>(seq_axis)]) {
+ return std::nullopt; // neither broadcast nor a length match -> unsafe to propagate
+ }
+ return true; // real data on this axis, must slice
+ };
+
+ const bool has_mask = sdpa_node->get_input_size() > 3;
+ bool mask_needs_slicing = false;
+ if (has_mask) {
+ auto decision = mask_needs_slice(3);
+ if (!decision.has_value()) {
+ return false;
+ }
+ mask_needs_slicing = *decision;
+ }
+
+ // Build new inputs: Q always sliced, K/V unchanged, mask conditionally sliced
+ ov::OutputVector new_inputs;
+ for (size_t i = 0; i < sdpa_node->get_input_size(); ++i) {
+ if (i == 0) {
+ // Q: always slice
+ new_inputs.push_back(new_q);
+ } else if (i == 3 && has_mask) {
+ // attention mask (optional input 3)
+ if (mask_needs_slicing) {
+ auto new_mask = clone_slice(slice_node, sdpa_node->input_value(3));
+ new_inputs.push_back(new_mask);
+ } else {
+ new_inputs.push_back(sdpa_node->input_value(3));
+ }
+ } else {
+ // K, V, scale, or other inputs: unchanged
+ new_inputs.push_back(sdpa_node->input_value(i));
+ }
+ }
+
+ auto new_sdpa = sdpa_node->clone_with_new_inputs(new_inputs);
+ new_sdpa->set_friendly_name(sdpa_node->get_friendly_name());
+ new_sdpa->validate_and_infer_types();
+
+ // Store metadata for downstream passes (e.g., pyramid attention):
+ // Although Q's sequence length is now sliced, K/V still contain the original sequence length.
+ // Record the original query_length so pyramid attention can correctly identify prefill vs. generate.
+ auto& rt_info = new_sdpa->get_rt_info();
+ rt_info[ov::npuw::NPUW_ORIGINAL_QUERY_LENGTH_RT_KEY] = q_shape_static[static_cast<size_t>(seq_axis)];
+
+ ov::replace_node(slice_node, new_sdpa);
+ return true;
+ });
+ }
+};
+
+// ---------------------------------------------------------------------------
+// R4 – Slice(Reduce*(X, axis)) -> Reduce*(Slice(X), axis)
+// when the sliced axis is different from the reduction axis.
+// Supports ReduceMean, ReduceSum, ReduceMax, ReduceMin, ReduceProd, etc.
+// ---------------------------------------------------------------------------
+class PropagateSliceThroughReduce : public ov::pass::MatcherPass {
+public:
+ OPENVINO_MATCHER_PASS_RTTI("PropagateSliceThroughReduce");
+
+ PropagateSliceThroughReduce() {
+ auto data = any_input();
+ auto axes = any_input();
+ // Match any Reduce operation
+ auto reduce =
+ wrap_type<ov::op::util::ArithmeticReductionKeepDims, ov::op::util::LogicalReductionKeepDims>({data, axes});
+ auto slice = wrap_type<ov::op::v8::Slice>({reduce, any_input(), any_input(), any_input(), any_input()});
+
+ register_matcher(std::make_shared<Matcher>(slice, "PropagateSliceThroughReduce"), [=](Matcher& m) {
+ auto& map = m.get_pattern_value_map();
+ auto slice_node = std::dynamic_pointer_cast<ov::op::v8::Slice>(map[slice].get_node_shared_ptr());
+ auto reduce_node = map[reduce].get_node_shared_ptr();
+
+ int64_t output_slice_axis = get_propagation_axis(slice_node, reduce_node);
+ if (output_slice_axis == -1) {
+ return false;
+ }
+
+ // Get reduction axes
+ auto reduce_axes_const =
+ std::dynamic_pointer_cast<ov::op::v0::Constant>(reduce_node->get_input_node_shared_ptr(1));
+ if (!reduce_axes_const) {
+ return false;
+ }
+
+ auto reduce_axes_vec = reduce_axes_const->cast_vector<int64_t>();
+ const auto& input_shape = reduce_node->get_input_shape(0);
+ const auto& output_shape = reduce_node->get_output_shape(0);
+
+ // Normalize reduction axes to positive indices
+ std::vector<int64_t> normalized_reduce_axes;
+ for (int64_t ax : reduce_axes_vec) {
+ normalized_reduce_axes.push_back(
+ static_cast<int64_t>(ov::util::normalize_axis(ax, static_cast<int64_t>(input_shape.size()))));
+ }
+
+ // Map output slice axis to input axis, accounting for reduced dimensions
+ // If keep_dims=False, reduced axes are removed, so we need to adjust
+ bool keep_dims = (input_shape.size() == output_shape.size());
+ int64_t input_slice_axis = output_slice_axis;
+
+ if (!keep_dims) {
+ // Count how many reduction axes are before the output slice axis
+ int64_t reduced_before = 0;
+ for (int64_t reduce_ax : normalized_reduce_axes) {
+ if (reduce_ax <= output_slice_axis + reduced_before) {
+ reduced_before++;
+ }
+ }
+ input_slice_axis = output_slice_axis + reduced_before;
+ }
+
+ // Check if the input slice axis conflicts with any reduction axis
+ for (int64_t reduce_ax : normalized_reduce_axes) {
+ if (input_slice_axis == reduce_ax) {
+ return false;
+ }
+ }
+
+ // Safe to propagate: Slice(Reduce(X, axis)) -> Reduce(Slice(X), axis)
+ int64_t start = 0, stop = 0, step = 0;
+ if (!get_slice_axis_params(slice_node, output_slice_axis, start, stop, step)) {
+ return false;
+ }
+
+ // Create new slice on input with mapped axis
+ auto new_slice = create_slice_with_params(reduce_node->input_value(0), input_slice_axis, start, stop, step);
+ new_slice->set_friendly_name(slice_node->get_friendly_name() + "_propagated");
+
+ auto new_reduce = reduce_node->clone_with_new_inputs({new_slice, reduce_node->input_value(1)});
+ new_reduce->set_friendly_name(reduce_node->get_friendly_name());
+ new_reduce->validate_and_infer_types();
+ ov::replace_node(slice_node, new_reduce);
+ return true;
+ });
+ }
+};
+
+// ---------------------------------------------------------------------------
+// R5 – Slice(MatMul(X, W)) -> MatMul(Slice(X), W)
+// when the sliced axis is not the feature (last) dimension.
+// ---------------------------------------------------------------------------
+class PropagateSliceThroughMatMul : public ov::pass::MatcherPass {
+public:
+ OPENVINO_MATCHER_PASS_RTTI("PropagateSliceThroughMatMul");
+
+ PropagateSliceThroughMatMul() {
+ auto data = any_input();
+ auto weight = any_input();
+ auto matmul = wrap_type<ov::op::v0::MatMul>({data, weight});
+ auto slice = wrap_type<ov::op::v8::Slice>({matmul, any_input(), any_input(), any_input(), any_input()});
+
+ register_matcher(std::make_shared<Matcher>(slice, "PropagateSliceThroughMatMul"), [=](Matcher& m) {
+ auto& map = m.get_pattern_value_map();
+ auto slice_node = std::dynamic_pointer_cast<ov::op::v8::Slice>(map[slice].get_node_shared_ptr());
+ auto matmul_node = std::dynamic_pointer_cast<ov::op::v0::MatMul>(map[matmul].get_node_shared_ptr());
+
+ int64_t slice_axis = get_propagation_axis(slice_node, matmul_node);
+ if (slice_axis == -1) {
+ return false;
+ }
+
+ const auto& input_shape = matmul_node->get_input_shape(0);
+ if (input_shape.size() < 2) {
+ return false;
+ }
+ const int64_t rank = static_cast<int64_t>(input_shape.size());
+
+ // The MatMul output's last axis is the "column" dimension contributed by the weight
+ // input (input 1) - it has no corresponding axis in the data input (input 0) at all,
+ // so we can never propagate a Slice on that axis onto the data input.
+ if (slice_axis == rank - 1) {
+ return false;
+ }
+
+ // Map the sliced output axis to the corresponding axis of the data input.
+ // Without transpose_a, MatMul contracts on the data input's last axis, and all other
+ // axes (batch dims + the "row" dim at rank-2) keep the same position in input and output.
+ // With transpose_a, the data input's last two axes are swapped before the multiply:
+ // the row dim (free, safe to slice) ends up at output axis rank-2 but lives on the raw
+ // (untransposed) data input's LAST axis, while the contracted axis is the input's
+ // second-to-last axis instead.
+ int64_t input_axis = slice_axis;
+ if (matmul_node->get_transpose_a() && slice_axis == rank - 2) {
+ input_axis = rank - 1;
+ }
+
+ // Safe to propagate: Slice(MatMul(X, W)) -> MatMul(Slice(X), W)
+ // Extract params for slice_axis only, to avoid copying unrelated axes from the original Slice
+ int64_t start = 0, stop = 0, step = 0;
+ if (!get_slice_axis_params(slice_node, slice_axis, start, stop, step)) {
+ return false;
+ }
+ auto new_slice = create_slice_with_params(matmul_node->input_value(0), input_axis, start, stop, step);
+
+ auto new_matmul = matmul_node->clone_with_new_inputs({new_slice, matmul_node->input_value(1)});
+ new_matmul->set_friendly_name(matmul_node->get_friendly_name());
+ new_matmul->validate_and_infer_types();
+ ov::replace_node(slice_node, new_matmul);
+ return true;
+ });
+ }
+};
+
+// ---------------------------------------------------------------------------
+// R6 – Slice(Reshape(X)) -> Reshape(Slice(X))
+// when the sliced axis structure is preserved by Reshape.
+// ---------------------------------------------------------------------------
+class PropagateSliceThroughReshape : public ov::pass::MatcherPass {
+public:
+ OPENVINO_MATCHER_PASS_RTTI("PropagateSliceThroughReshape");
+
+ PropagateSliceThroughReshape() {
+ auto reshape = wrap_type<ov::op::v1::Reshape>();
+ auto slice = wrap_type<ov::op::v8::Slice>({reshape, any_input(), any_input(), any_input(), any_input()});
+
+ register_matcher(std::make_shared<Matcher>(slice, "PropagateSliceThroughReshape"), [=](Matcher& m) {
+ auto& map = m.get_pattern_value_map();
+ auto slice_node = std::dynamic_pointer_cast<ov::op::v8::Slice>(map[slice].get_node_shared_ptr());
+ auto reshape_node = std::dynamic_pointer_cast<ov::op::v1::Reshape>(map[reshape].get_node_shared_ptr());
+
+ int64_t output_slice_axis = get_propagation_axis(slice_node, reshape_node);
+ if (output_slice_axis == -1) {
+ return false;
+ }
+
+ const auto& input_shape = reshape_node->get_input_shape(0);
+ const auto& output_shape = reshape_node->get_output_shape(0);
+ const auto& sliced_output_shape = slice_node->get_output_shape(0);
+
+ // Check if Reshape is squeeze-like (only inserts/removes dims of size 1)
+ // If so, we can use Unsqueeze/Squeeze after propagating Slice instead of updating pattern
+ size_t input_elements = 1;
+ for (auto d : input_shape)
+ input_elements *= d;
+ size_t output_elements = 1;
+ for (auto d : output_shape)
+ output_elements *= d;
+
+ bool is_squeeze_like = (input_elements == output_elements);
+
+ // Find which input axis corresponds to the sliced output axis
+ // Strategy: find the input axis where the dimension value matches
+ size_t sliced_dim_value = output_shape[output_slice_axis];
+ int64_t input_slice_axis = -1;
+
+ // Try to find matching dimension in input
+ for (size_t i = 0; i < input_shape.size(); ++i) {
+ if (input_shape[i] == sliced_dim_value) {
+ // Verify this is a valid mapping by checking cumulative products.
+ // Calculate how many elements are "before" this dimension (prefix product)
+ // and "after" this dimension (suffix product) on both sides.
+ size_t input_prefix_prod = 1;
+ for (size_t j = 0; j < i; ++j) {
+ input_prefix_prod *= input_shape[j];
+ }
+
+ size_t output_prefix_prod = 1;
+ for (int64_t j = 0; j < output_slice_axis; ++j) {
+ output_prefix_prod *= output_shape[j];
+ }
+
+ // NOTE: because a valid Reshape always preserves the total element count
+ // (input_elements == output_elements), prefix_in == prefix_out already implies
+ // suffix_in == suffix_out. We still check the suffix explicitly as a defensive,
+ // self-documenting guard rather than relying on that implication silently.
+ size_t input_suffix_prod = 1;
+ for (size_t j = i + 1; j < input_shape.size(); ++j) {
+ input_suffix_prod *= input_shape[j];
+ }
+
+ size_t output_suffix_prod = 1;
+ for (size_t j = static_cast<size_t>(output_slice_axis) + 1; j < output_shape.size(); ++j) {
+ output_suffix_prod *= output_shape[j];
+ }
+
+ if (input_prefix_prod == output_prefix_prod && input_suffix_prod == output_suffix_prod) {
+ input_slice_axis = static_cast<int64_t>(i);
+ break;
+ }
+ }
+ }
+
+ if (input_slice_axis == -1) {
+ return false;
+ }
+
+ int64_t start = 0, stop = 0, step = 0;
+ if (!get_slice_axis_params(slice_node, output_slice_axis, start, stop, step)) {
+ return false;
+ }
+
+ // Create new slice on input with mapped axis
+ auto new_slice =
+ create_slice_with_params(reshape_node->input_value(0), input_slice_axis, start, stop, step);
+ new_slice->set_friendly_name(slice_node->get_friendly_name() + "_propagated");
+
+ ov::Output<ov::Node> final_output;
+
+ // If Reshape is squeeze-like, use Unsqueeze to restore dimension structure
+ if (is_squeeze_like) {
+ // Find which axes were inserted (dims that are 1 in output but don't exist in sliced input)
+ auto sliced_input_shape = new_slice->get_output_shape(0);
+
+ // Compute which axes need to be unsqueezed to match sliced_output_shape
+ std::vector<int64_t> unsqueeze_axes;
+ size_t input_idx = 0;
+ for (size_t output_idx = 0; output_idx < sliced_output_shape.size(); ++output_idx) {
+ if (input_idx < sliced_input_shape.size() &&
+ sliced_input_shape[input_idx] == sliced_output_shape[output_idx]) {
+ // Dimension matches, continue
+ input_idx++;
+ } else if (sliced_output_shape[output_idx] == 1) {
+ // Output has size-1 dim that input doesn't have - need unsqueeze
+ unsqueeze_axes.push_back(static_cast<int64_t>(output_idx));
+ } else {
+ // Dimension mismatch that's not size-1 - can't use simple unsqueeze
+ unsqueeze_axes.clear();
+ break;
+ }
+ }
+
+ if (!unsqueeze_axes.empty()) {
+ auto unsqueeze_axes_const = ov::op::v0::Constant::create(ov::element::i64,
+ ov::Shape{unsqueeze_axes.size()},
+ unsqueeze_axes);
+ auto unsqueeze = std::make_shared<ov::op::v0::Unsqueeze>(new_slice, unsqueeze_axes_const);
+ unsqueeze->set_friendly_name(reshape_node->get_friendly_name() + "_unsqueeze");
+ unsqueeze->validate_and_infer_types();
+ final_output = unsqueeze;
+ } else {
+ // Fall through to dynamic pattern approach
+ }
+ }
+
+ // If not squeeze-like or unsqueeze failed, update Reshape pattern
+ if (!final_output.get_node_shared_ptr()) {
+ // Check if Reshape pattern is constant - we can directly update it
+ auto pattern_const =
+ std::dynamic_pointer_cast<ov::op::v0::Constant>(reshape_node->get_input_node_shared_ptr(1));
+
+ if (!pattern_const) {
+ // Dynamic pattern and not squeeze-like - too complex, skip
+ return false;
+ }
+
+ // Static pattern: compute new pattern directly
+ auto original_pattern = pattern_const->cast_vector<int64_t>();
+
+ // Compute new pattern: same structure but with sliced dimension
+ std::vector<int64_t> new_pattern = original_pattern;
+ new_pattern[output_slice_axis] = sliced_output_shape[output_slice_axis];
+
+ auto new_pattern_const =
+ ov::op::v0::Constant::create(ov::element::i64, ov::Shape{new_pattern.size()}, new_pattern);
+
+ auto new_reshape = reshape_node->clone_with_new_inputs({new_slice, new_pattern_const});
+ new_reshape->set_friendly_name(reshape_node->get_friendly_name());
+ new_reshape->validate_and_infer_types();
+ final_output = new_reshape;
+ }
+
+ // Replace original Slice with the final output (either Unsqueeze or updated Reshape)
+ ov::replace_node(slice_node, final_output.get_node_shared_ptr());
+ return true;
+ });
+ }
+};
+
+// ---------------------------------------------------------------------------
+// R7 – Slice(Transpose(X)) -> Transpose(Slice(X))
+// mapping slice axis through the permutation.
+// ---------------------------------------------------------------------------
+class PropagateSliceThroughTranspose : public ov::pass::MatcherPass {
+public:
+ OPENVINO_MATCHER_PASS_RTTI("PropagateSliceThroughTranspose");
+
+ PropagateSliceThroughTranspose() {
+ auto transpose = wrap_type<ov::op::v1::Transpose>();
+ auto slice = wrap_type<ov::op::v8::Slice>({transpose, any_input(), any_input(), any_input(), any_input()});
+
+ register_matcher(std::make_shared<Matcher>(slice, "PropagateSliceThroughTranspose"), [=](Matcher& m) {
+ auto& map = m.get_pattern_value_map();
+ auto slice_node = std::dynamic_pointer_cast<ov::op::v8::Slice>(map[slice].get_node_shared_ptr());
+ auto transpose_node =
+ std::dynamic_pointer_cast<ov::op::v1::Transpose>(map[transpose].get_node_shared_ptr());
+
+ int64_t output_slice_axis = get_propagation_axis(slice_node, transpose_node);
+ if (output_slice_axis == -1) {
+ return false;
+ }
+
+ // Get the permutation
+ auto perm_const =
+ std::dynamic_pointer_cast<ov::op::v0::Constant>(transpose_node->get_input_node_shared_ptr(1));
+ if (!perm_const) {
+ return false;
+ }
+
+ auto perm = perm_const->cast_vector<int64_t>();
+
+ // OpenVINO Transpose semantics: output[i] = input[order[i]], so the input axis that
+ // ends up at output axis `output_slice_axis` is simply order[output_slice_axis]
+ if (output_slice_axis < 0 || static_cast<size_t>(output_slice_axis) >= perm.size()) {
+ return false;
+ }
+ int64_t input_slice_axis = perm[static_cast<size_t>(output_slice_axis)];
+
+ // Safe to propagate: Slice(Transpose(X)) -> Transpose(Slice(X))
+ // We need to extract the slice parameters from output_slice_axis and apply them to input_slice_axis
+ int64_t start = 0, stop = 0, step = 0;
+ if (!get_slice_axis_params(slice_node, output_slice_axis, start, stop, step)) {
+ return false;
+ }
+
+ // Create new slice parameters for the input axis
+ auto new_slice =
+ create_slice_with_params(transpose_node->input_value(0), input_slice_axis, start, stop, step);
+ new_slice->set_friendly_name(slice_node->get_friendly_name() + "_propagated");
+
+ auto new_transpose = transpose_node->clone_with_new_inputs({new_slice, transpose_node->input_value(1)});
+ new_transpose->set_friendly_name(transpose_node->get_friendly_name());
+ new_transpose->validate_and_infer_types();
+ ov::replace_node(slice_node, new_transpose);
+ return true;
+ });
+ }
+};
+
+// ---------------------------------------------------------------------------
+// R8 – Slice(VariadicSplit(X)[i]) for all i -> VariadicSplit(Slice(X))
+//
+// Pattern visualization:
+// BEFORE:
+// Input[1,1024,3072]
+// |
+// VariadicSplit(axis=2, split_lengths=[1024,1024,1024]) // Split into 3 parts on last dim
+// |
+// +--+--+
+// | | |
+// out0 out1 out2
+// [1,1024,1024] [1,1024,1024] [1,1024,1024]
+// | | |
+// Slice Slice Slice (all have IDENTICAL slice params: axis=1, 0:1)
+// | | |
+// [1,1,1024] [1,1,1024] [1,1,1024]
+//
+// AFTER:
+// Input[1,1024,3072]
+// |
+// Slice(axis=1: 0:1) // Apply common slice BEFORE split
+// |
+// [1,1,3072]
+// |
+// VariadicSplit(axis=2, split_lengths=[1024,1024,1024])
+// |
+// +--+--+
+// | | |
+// [1,1,1024] [1,1,1024] [1,1,1024]
+//
+// when all outputs have identical Slice consumers on the non-split axis.
+// ---------------------------------------------------------------------------
+class PropagateSliceThroughVariadicSplit : public ov::pass::MatcherPass {
+public:
+ OPENVINO_MATCHER_PASS_RTTI("PropagateSliceThroughVariadicSplit");
+
+ PropagateSliceThroughVariadicSplit() {
+ auto vsplit = wrap_type<ov::op::v1::VariadicSplit>();
+ auto slice = wrap_type<ov::op::v8::Slice>({vsplit, any_input(), any_input(), any_input(), any_input()});
+
+ register_matcher(std::make_shared<Matcher>(slice, "PropagateSliceThroughVariadicSplit"), [=](Matcher& m) {
+ auto& map = m.get_pattern_value_map();
+ auto slice_node = std::dynamic_pointer_cast<ov::op::v8::Slice>(map[slice].get_node_shared_ptr());
+ auto vsplit_node = std::dynamic_pointer_cast<ov::op::v1::VariadicSplit>(map[vsplit].get_node_shared_ptr());
+
+ // Get the split axis first (cheap check before the more expensive consumer scan below)
+ auto split_axis_const =
+ std::dynamic_pointer_cast<ov::op::v0::Constant>(vsplit_node->get_input_node_shared_ptr(1));
+ if (!split_axis_const) {
+ return false;
+ }
+
+ int64_t split_axis = split_axis_const->cast_vector<int64_t>()[0];
+ split_axis = static_cast<int64_t>(
+ ov::util::normalize_axis(split_axis, static_cast<int64_t>(vsplit_node->get_input_shape(0).size())));
+
+ // Get the sliced axis; also verifies vsplit_node has exactly one live consumer per output
+ int64_t slice_axis = get_propagation_axis(slice_node, vsplit_node);
+ if (slice_axis == -1) {
+ return false;
+ }
+
+ // Cannot propagate if slicing the split axis
+ if (slice_axis == split_axis) {
+ return false;
+ }
+
+ std::vector<std::shared_ptr<ov::op::v8::Slice>> slice_consumers;
+ for (size_t out_idx = 0; out_idx < vsplit_node->get_output_size(); ++out_idx) {
+ auto consumer =
+ vsplit_node->output(out_idx).get_target_inputs().begin()->get_node()->shared_from_this();
+ auto consumer_slice = std::dynamic_pointer_cast<ov::op::v8::Slice>(consumer);
+ if (!consumer_slice) {
+ return false;
+ }
+ slice_consumers.push_back(consumer_slice);
+ }
+
+ if (slice_consumers.empty()) {
+ return false;
+ }
+
+ // Check if all Slice nodes have the same parameters (on the non-split axis).
+ // Extract the first Slice's axis/params once - they are invariant across the loop below.
+ auto first_slice = slice_consumers[0];
+ int64_t first_slice_axis = get_single_sliced_axis(first_slice);
+ int64_t first_start = 0, first_stop = 0, first_step = 0;
+ if (first_slice_axis == -1 ||
+ !get_slice_axis_params(first_slice, first_slice_axis, first_start, first_stop, first_step)) {
+ return false;
+ }
+
+ for (size_t i = 1; i < slice_consumers.size(); ++i) {
+ auto other_slice = slice_consumers[i];
+ int64_t other_slice_axis = get_single_sliced_axis(other_slice);
+
+ if (other_slice_axis == -1 || first_slice_axis != other_slice_axis) {
+ return false;
+ }
+
+ int64_t other_start = 0, other_stop = 0, other_step = 0;
+ if (!get_slice_axis_params(other_slice, other_slice_axis, other_start, other_stop, other_step)) {
+ return false;
+ }
+
+ if (first_start != other_start || first_stop != other_stop || first_step != other_step) {
+ return false;
+ }
+ }
+
+ // Propagate: Slice(VariadicSplit(X)) -> VariadicSplit(Slice(X))
+ auto new_slice = create_slice_with_params(vsplit_node->input_value(0),
+ first_slice_axis,
+ first_start,
+ first_stop,
+ first_step);
+
+ auto new_vsplit = vsplit_node->clone_with_new_inputs({
+ new_slice,
+ vsplit_node->input_value(1), // axis
+ vsplit_node->input_value(2) // split_lengths
+ });
+ new_vsplit->set_friendly_name(vsplit_node->get_friendly_name());
+ new_vsplit->validate_and_infer_types();
+
+ // Replace each old Slice with the corresponding output of new VariadicSplit
+ for (size_t i = 0; i < slice_consumers.size(); ++i) {
+ slice_consumers[i]->output(0).replace(new_vsplit->output(i));
+ }
+
+ return true;
+ });
+ }
+};
+
+// ---------------------------------------------------------------------------
+// R9 – Merge duplicate Slice nodes with identical inputs and parameters
+// ---------------------------------------------------------------------------
+class MergeDuplicateSlices : public ov::pass::MatcherPass {
+public:
+ OPENVINO_MATCHER_PASS_RTTI("MergeDuplicateSlices");
+
+ MergeDuplicateSlices() {
+ // Match any Slice node
+ auto slice_pattern = wrap_type<ov::op::v8::Slice>();
+
+ register_matcher(std::make_shared<Matcher>(slice_pattern, "MergeDuplicateSlices"), [](Matcher& m) {
+ auto slice = std::dynamic_pointer_cast<ov::op::v8::Slice>(m.get_match_root());
+ if (!slice)
+ return false;
+
+ // Get the data input (includes both node and output port)
+ auto data_input = slice->input_value(0);
+ auto parent_node = data_input.get_node_shared_ptr();
+ size_t parent_output_port = data_input.get_index();
+
+ // Collect all Slice consumers of the SAME output port
+ // This prevents merging slices from different TopK outputs (values vs indices)
+ std::vector<std::shared_ptr<ov::op::v8::Slice>> slice_consumers;
+ for (const auto& consumer_input : parent_node->get_output_target_inputs(parent_output_port)) {
+ auto consumer = consumer_input.get_node()->shared_from_this();
+ auto other_slice = std::dynamic_pointer_cast<ov::op::v8::Slice>(consumer);
+ if (other_slice) {
+ slice_consumers.push_back(other_slice);
+ }
+ }
+
+ if (slice_consumers.size() <= 1) {
+ return false; // Only one or zero Slice consumers, nothing to merge
+ }
+
+ // Helper to get constant values as vector
+ auto get_const_values = [](const std::shared_ptr<ov::Node>& node) -> std::vector<int64_t> {
+ auto const_node = std::dynamic_pointer_cast<ov::op::v0::Constant>(node);
+ if (!const_node)
+ return {};
+ return const_node->cast_vector<int64_t>();
+ };
+
+ const auto& input_shape = slice->get_input_shape(0);
+ size_t rank = input_shape.size();
+
+ // Normalize axes to positive indices and create a map: axis -> (start, stop, step)
+ auto build_slice_map =
+ [&](const std::vector<int64_t>& axes,
+ const std::vector<int64_t>& starts,
+ const std::vector<int64_t>& stops,
+ const std::vector<int64_t>& steps,
+ const ov::Shape& in_shape,
+ const ov::Shape& out_shape) -> std::map<int64_t, std::tuple<int64_t, int64_t, int64_t>> {
+ std::map<int64_t, std::tuple<int64_t, int64_t, int64_t>> result;
+ for (size_t i = 0; i < axes.size(); ++i) {
+ int64_t axis = static_cast<int64_t>(ov::util::normalize_axis(axes[i], static_cast<int64_t>(rank)));
+ // Only include axes that actually reduce the dimension
+ if (out_shape[axis] < in_shape[axis]) {
+ result[axis] = {starts[i], stops[i], steps[i]};
+ }
+ }
+ return result;
+ };
+
+ // Extract this Slice's own parameters once - they are invariant across the
+ // comparison loop below (only `other_slice`'s parameters change per iteration).
+ auto start1 = get_const_values(slice->get_input_node_shared_ptr(1));
+ auto stop1 = get_const_values(slice->get_input_node_shared_ptr(2));
+ auto step1 = get_const_values(slice->get_input_node_shared_ptr(3));
+ auto axes1 = get_const_values(slice->get_input_node_shared_ptr(4));
+
+ if (start1.empty() || stop1.empty() || step1.empty() || axes1.empty()) {
+ return false;
+ }
+
+ auto map1 = build_slice_map(axes1, start1, stop1, step1, input_shape, slice->get_output_shape(0));
+
+ // Check all consumers of the same output port for duplicate Slices
+ for (const auto& other_slice : slice_consumers) {
+ if (other_slice == slice)
+ continue; // Skip self
+
+ // For semantic equivalence, we need:
+ // 1. Same output shape
+ // 2. Same slice parameters (start, stop, step, axes values)
+ // Note: element_type is implicitly same since they consume the same output port
+
+ if (slice->get_output_shape(0) != other_slice->get_output_shape(0)) {
+ continue;
+ }
+
+ auto start2 = get_const_values(other_slice->get_input_node_shared_ptr(1));
+ auto stop2 = get_const_values(other_slice->get_input_node_shared_ptr(2));
+ auto step2 = get_const_values(other_slice->get_input_node_shared_ptr(3));
+ auto axes2 = get_const_values(other_slice->get_input_node_shared_ptr(4));
+
+ if (start2.empty() || stop2.empty() || step2.empty() || axes2.empty()) {
+ continue;
+ }
+
+ auto map2 = build_slice_map(axes2, start2, stop2, step2, input_shape, other_slice->get_output_shape(0));
+
+ if (map1 == map2) {
+ ov::replace_node(other_slice, slice);
+ return true; // Made a change, will re-run
+ }
+ }
+
+ return false; // No duplicate found
+ });
+ }
+};
+
+// ---------------------------------------------------------------------------
+// R10 – Slice(Reshape(Tile(X))) -> Reshape(Tile(Slice(X)))
+//
+// Pattern visualization:
+// BEFORE:
+// Input[1024,2048]
+// |
+// Tile(repeats=[128,1]) // Repeat first dim 128 times
+// |
+// [131072,2048] // 1024*128 = 131072
+// |
+// Reshape(pattern=[128,1024,2048]) // Reshape to split the repeated dimension
+// |
+// [128,1024,2048]
+// |
+// Slice(axis=1: -1:) // Take last element on middle dimension
+// |
+// [128,1,2048]
+//
+// AFTER:
+// Input[1024,2048]
+// |
+// Slice(axis=0: -1:) // Slice BEFORE Tile (maps back through reshape+tile)
+// |
+// [1,2048]
+// |
+// Tile(repeats=[128,1])
+// |
+// [128,2048]
+// |
+// Reshape(pattern=[128,1,2048])
+// |
+// [128,1,2048]
+//
+// Special case: when Tile expands a dimension that Reshape then splits,
+// and Slice operates on the split dimension.
+// Example: Tile([1024,2048], [128,1]) -> [131072,2048]
+// Reshape([131072,2048]) -> [128,1024,2048]
+// Slice([128,1024,2048], axis=1, -1:) -> [128,1,2048]
+// Transforms to:
+// Slice([1024,2048], axis=0, -1:) -> [1,2048]
+// Tile([1,2048], [128,1]) -> [128,2048]
+// Reshape([128,2048]) -> [128,1,2048]
+// ---------------------------------------------------------------------------
+class PropagateSliceThroughTileReshape : public ov::pass::MatcherPass {
+public:
+ OPENVINO_MATCHER_PASS_RTTI("PropagateSliceThroughTileReshape");
+
+ PropagateSliceThroughTileReshape() {
+ auto data = any_input();
+ auto repeats = any_input();
+ auto tile = wrap_type<ov::op::v0::Tile>({data, repeats});
+ auto pattern = any_input();
+ auto reshape = wrap_type<ov::op::v1::Reshape>({tile, pattern});
+ auto slice = wrap_type<ov::op::v8::Slice>({reshape, any_input(), any_input(), any_input(), any_input()});
+
+ register_matcher(std::make_shared<Matcher>(slice, "PropagateSliceThroughTileReshape"), [=](Matcher& m) {
+ auto& map = m.get_pattern_value_map();
+ auto slice_node = std::dynamic_pointer_cast<ov::op::v8::Slice>(map.at(slice).get_node_shared_ptr());
+ auto reshape_node = std::dynamic_pointer_cast<ov::op::v1::Reshape>(map.at(reshape).get_node_shared_ptr());
+ auto tile_node = std::dynamic_pointer_cast<ov::op::v0::Tile>(map.at(tile).get_node_shared_ptr());
+
+ if (!slice_node || !reshape_node || !tile_node) {
+ return false;
+ }
+
+ // Basic checks (reshape_node's single-consumer status is verified by get_propagation_axis below)
+ if (!single_consumer(tile_node)) {
+ return false;
+ }
+
+ // Get shapes
+ const auto& tile_input_shape = tile_node->get_input_shape(0);
+ const auto& tile_output_shape = tile_node->get_output_shape(0);
+ const auto& reshape_output_shape = reshape_node->get_output_shape(0);
+ const auto& slice_output_shape = slice_node->get_output_shape(0);
+ int64_t output_slice_axis = get_propagation_axis(slice_node, reshape_node);
+ if (output_slice_axis == -1) {
+ return false;
+ }
+
+ // Get Tile repeats (must be constant)
+ auto repeats_const =
+ std::dynamic_pointer_cast<ov::op::v0::Constant>(tile_node->get_input_node_shared_ptr(1));
+ if (!repeats_const) {
+ return false;
+ }
+ auto repeats_vec = repeats_const->cast_vector<int64_t>();
+ // Get Reshape pattern (must be constant)
+ auto pattern_const =
+ std::dynamic_pointer_cast<ov::op::v0::Constant>(reshape_node->get_input_node_shared_ptr(1));
+ if (!pattern_const) {
+ return false;
+ }
+
+ // Check if this is the expected pattern:
+ // Tile expands dimension 0: [A, B] with repeats [R, 1] -> [A*R, B]
+ // Reshape splits dimension 0: [A*R, B] -> [R, A, B]
+ // Slice operates on dimension 1 (the A dimension)
+
+ if (tile_input_shape.size() != 2 || tile_output_shape.size() != 2) {
+ return false;
+ }
+
+ if (reshape_output_shape.size() != 3) {
+ return false;
+ }
+
+ if (output_slice_axis != 1) {
+ return false;
+ }
+
+ // Verify the relationship:
+ // tile_input[0] * repeats[0] = tile_output[0] = reshape_output[0] * reshape_output[1]
+ // tile_input[1] * repeats[1] = tile_output[1] = reshape_output[2]
+
+ const size_t tile_repeat_factor = static_cast<size_t>(repeats_vec[0]);
+ const size_t expected_tile_output_dim0 = tile_input_shape[0] * tile_repeat_factor;
+
+ if (tile_output_shape[0] != expected_tile_output_dim0) {
+ return false;
+ }
+
+ // reshape_output[0] and reshape_output[1] must independently match the repeat factor R
+ // and the original (pre-tile) dimension A respectively - checking only that their
+ // product equals tile_output[0] is not sufficient, since the split could land on the
+ // wrong axis order (e.g. [8,3] instead of [6,4] when A*R == 3*8 == 24), which would
+ // silently propagate the Slice onto the wrong logical dimension.
+ if (reshape_output_shape[0] != tile_repeat_factor || reshape_output_shape[1] != tile_input_shape[0]) {
+ return false;
+ }
+
+ if (tile_output_shape[1] != reshape_output_shape[2]) {
+ return false;
+ }
+
+ // Now we know the pattern is correct. Transform:
+ // Original: Tile([A,B], [R,1]) -> [A*R,B] -> Reshape -> [R,A,B] -> Slice(axis=1) -> [R,1,B]
+ // New: Slice([A,B], axis=0) -> [1,B] -> Tile([1,B], [R,1]) -> [R,B] -> Reshape -> [R,1,B]
+
+ // Extract slice parameters
+ int64_t start = 0, stop = 0, step = 0;
+ if (!get_slice_axis_params(slice_node, output_slice_axis, start, stop, step)) {
+ return false;
+ }
+
+ // Create new slice on Tile input, axis 0
+ auto new_slice = create_slice_with_params(tile_node->input_value(0), /*axis=*/0, start, stop, step);
+ new_slice->set_friendly_name(slice_node->get_friendly_name() + "_propagated_to_tile_input");
+
+ // New Tile with same repeats
+ auto new_tile = std::make_shared<ov::op::v0::Tile>(new_slice, tile_node->input_value(1));
+ new_tile->set_friendly_name(tile_node->get_friendly_name());
+ new_tile->validate_and_infer_types();
+
+ // New Reshape pattern: [R, B] -> [R, 1, B]
+ auto new_shape = reshape_output_shape;
+ new_shape[1] = slice_output_shape[output_slice_axis]; // Update the sliced dimension
+ auto new_pattern = ov::op::v0::Constant::create(ov::element::i64,
+ ov::Shape{new_shape.size()},
+ std::vector<int64_t>(new_shape.begin(), new_shape.end()));
+
+ auto new_reshape = std::make_shared<ov::op::v1::Reshape>(new_tile, new_pattern, false);
+ new_reshape->set_friendly_name(reshape_node->get_friendly_name());
+ new_reshape->validate_and_infer_types();
+
+ // Verify the output shape matches
+ if (new_reshape->get_output_shape(0) != slice_output_shape) {
+ return false;
+ }
+
+ // Replace the original Slice with the new Reshape
+ ov::replace_node(slice_node, new_reshape);
+ return true;
+ });
+ }
+};
+
+// ---------------------------------------------------------------------------
+// R11 – Slice(Unsqueeze(X)) -> Unsqueeze(Slice(X))
+// Map the slice axis accounting for inserted dimensions
+// ---------------------------------------------------------------------------
+class PropagateSliceThroughUnsqueeze : public ov::pass::MatcherPass {
+public:
+ OPENVINO_MATCHER_PASS_RTTI("PropagateSliceThroughUnsqueeze");
+
+ PropagateSliceThroughUnsqueeze() {
+ auto data = any_input();
+ auto axes = any_input();
+ auto unsqueeze = wrap_type<ov::op::v0::Unsqueeze>({data, axes});
+ auto slice = wrap_type<ov::op::v8::Slice>({unsqueeze, any_input(), any_input(), any_input(), any_input()});
+
+ register_matcher(std::make_shared<Matcher>(slice, "PropagateSliceThroughUnsqueeze"), [=](Matcher& m) {
+ auto& map = m.get_pattern_value_map();
+ auto slice_node = std::dynamic_pointer_cast<ov::op::v8::Slice>(map.at(slice).get_node_shared_ptr());
+ auto unsqueeze_node =
+ std::dynamic_pointer_cast<ov::op::v0::Unsqueeze>(map.at(unsqueeze).get_node_shared_ptr());
+
+ if (!slice_node || !unsqueeze_node) {
+ return false;
+ }
+
+ int64_t output_slice_axis = get_propagation_axis(slice_node, unsqueeze_node);
+ if (output_slice_axis == -1) {
+ return false;
+ }
+
+ const auto& input_shape = unsqueeze_node->get_input_shape(0);
+ const auto& output_shape = unsqueeze_node->get_output_shape(0);
+
+ // Get Unsqueeze axes (must be constant)
+ auto unsqueeze_axes_const =
+ std::dynamic_pointer_cast<ov::op::v0::Constant>(unsqueeze_node->get_input_node_shared_ptr(1));
+ if (!unsqueeze_axes_const) {
+ return false;
+ }
+
+ auto unsqueeze_axes = unsqueeze_axes_const->cast_vector<int64_t>();
+ // Normalize unsqueeze axes to positive indices
+ std::vector<int64_t> normalized_unsqueeze_axes;
+ for (auto ax : unsqueeze_axes) {
+ normalized_unsqueeze_axes.push_back(
+ static_cast<int64_t>(ov::util::normalize_axis(ax, static_cast<int64_t>(output_shape.size()))));
+ }
+ std::sort(normalized_unsqueeze_axes.begin(), normalized_unsqueeze_axes.end());
+
+ // Check if the slice axis is on an unsqueezed dimension (size=1 in output)
+ if (output_shape[output_slice_axis] == 1) {
+ // Check if this dimension was inserted by Unsqueeze
+ bool is_unsqueezed_dim =
+ std::find(normalized_unsqueeze_axes.begin(), normalized_unsqueeze_axes.end(), output_slice_axis) !=
+ normalized_unsqueeze_axes.end();
+ if (is_unsqueezed_dim) {
+ return false;
+ }
+ }
+
+ // Map output_slice_axis to input_slice_axis
+ // Input axis = output axis - count(unsqueeze_axes < output_slice_axis)
+ int64_t axes_before = 0;
+ for (auto ax : normalized_unsqueeze_axes) {
+ if (ax < output_slice_axis) {
+ axes_before++;
+ }
+ }
+ int64_t input_slice_axis = output_slice_axis - axes_before;
+
+ if (input_slice_axis < 0 || input_slice_axis >= static_cast<int64_t>(input_shape.size())) {
+ return false;
+ }
+
+ // Extract slice parameters
+ int64_t start = 0, stop = 0, step = 0;
+ if (!get_slice_axis_params(slice_node, output_slice_axis, start, stop, step)) {
+ return false;
+ }
+
+ // Create new slice on Unsqueeze input with mapped axis
+ auto new_slice =
+ create_slice_with_params(unsqueeze_node->input_value(0), input_slice_axis, start, stop, step);
+ new_slice->set_friendly_name(slice_node->get_friendly_name() + "_propagated");
+
+ // Create new Unsqueeze with same axes
+ auto new_unsqueeze = std::make_shared<ov::op::v0::Unsqueeze>(new_slice, unsqueeze_node->input_value(1));
+ new_unsqueeze->set_friendly_name(unsqueeze_node->get_friendly_name());
+ new_unsqueeze->validate_and_infer_types();
+
+ // Verify the output shape matches
+ if (new_unsqueeze->get_output_shape(0) != slice_node->get_output_shape(0)) {
+ return false;
+ }
+
+ // Replace the original Slice with the new Unsqueeze
+ ov::replace_node(slice_node, new_unsqueeze);
+ return true;
+ });
+ }
+};
+
+// ---------------------------------------------------------------------------
+// R12 – Slice(ScatterElementsUpdate(data, indices, updates)) ->
+// ScatterElementsUpdate(Slice(data), Slice(indices), Slice(updates))
+// when the sliced axis is not the scatter axis
+// ---------------------------------------------------------------------------
+class PropagateSliceThroughScatterElementsUpdate : public ov::pass::MatcherPass {
+public:
+ OPENVINO_MATCHER_PASS_RTTI("PropagateSliceThroughScatterElementsUpdate");
+
+ PropagateSliceThroughScatterElementsUpdate() {
+ auto data = any_input();
+ auto indices = any_input();
+ auto updates = any_input();
+ auto axis = any_input();
+ auto scatter = wrap_type<ov::op::v12::ScatterElementsUpdate>({data, indices, updates, axis});
+ auto slice = wrap_type<ov::op::v8::Slice>({scatter, any_input(), any_input(), any_input(), any_input()});
+
+ register_matcher(
+ std::make_shared<Matcher>(slice, "PropagateSliceThroughScatterElementsUpdate"),
+ [=](Matcher& m) {
+ auto& map = m.get_pattern_value_map();
+ auto slice_node = std::dynamic_pointer_cast<ov::op::v8::Slice>(map.at(slice).get_node_shared_ptr());
+ auto scatter_node = std::dynamic_pointer_cast<ov::op::v12::ScatterElementsUpdate>(
+ map.at(scatter).get_node_shared_ptr());
+
+ if (!slice_node || !scatter_node) {
+ return false;
+ }
+
+ int64_t slice_axis = get_propagation_axis(slice_node, scatter_node);
+ if (slice_axis == -1) {
+ return false;
+ }
+
+ const auto& data_shape = scatter_node->get_input_shape(0);
+ const auto& indices_shape = scatter_node->get_input_shape(1);
+ const auto& updates_shape = scatter_node->get_input_shape(2);
+ const auto& output_shape = scatter_node->get_output_shape(0);
+
+ // Get scatter axis (must be constant)
+ auto scatter_axis_const =
+ std::dynamic_pointer_cast<ov::op::v0::Constant>(scatter_node->get_input_node_shared_ptr(3));
+ if (!scatter_axis_const) {
+ return false;
+ }
+
+ auto scatter_axis_vec = scatter_axis_const->cast_vector<int64_t>();
+ if (scatter_axis_vec.size() != 1) {
+ return false;
+ }
+
+ int64_t scatter_axis = static_cast<int64_t>(
+ ov::util::normalize_axis(scatter_axis_vec[0], static_cast<int64_t>(output_shape.size())));
+
+ // Check if slice axis conflicts with scatter axis
+ if (slice_axis == scatter_axis) {
+ return false;
+ }
+
+ // Check that all inputs have the same dimension at slice_axis
+ if (data_shape.size() <= static_cast<size_t>(slice_axis) ||
+ indices_shape.size() <= static_cast<size_t>(slice_axis) ||
+ updates_shape.size() <= static_cast<size_t>(slice_axis)) {
+ return false;
+ }
+
+ size_t data_dim = data_shape[slice_axis];
+ size_t indices_dim = indices_shape[slice_axis];
+ size_t updates_dim = updates_shape[slice_axis];
+
+ // All must have the same dimension at slice_axis for safe propagation
+ if (data_dim != indices_dim || data_dim != updates_dim) {
+ return false;
+ }
+
+ // Create slices on all three inputs
+ auto new_data_slice = clone_slice(slice_node, scatter_node->input_value(0));
+ auto new_indices_slice = clone_slice(slice_node, scatter_node->input_value(1));
+ auto new_updates_slice = clone_slice(slice_node, scatter_node->input_value(2));
+
+ // Create new ScatterElementsUpdate with sliced inputs
+ auto new_scatter =
+ scatter_node->clone_with_new_inputs({new_data_slice->output(0),
+ new_indices_slice->output(0),
+ new_updates_slice->output(0),
+ scatter_node->input_value(3)}); // axis unchanged
+ new_scatter->set_friendly_name(scatter_node->get_friendly_name());
+ new_scatter->validate_and_infer_types();
+
+ // Verify the output shape matches
+ if (new_scatter->get_output_shape(0) != slice_node->get_output_shape(0)) {
+ return false;
+ }
+
+ // Replace the original Slice with the new ScatterElementsUpdate
+ ov::replace_node(slice_node, new_scatter);
+ return true;
+ });
+ }
+};
+
+// ---------------------------------------------------------------------------
+// R13 – Slice(Broadcast(X)) -> Broadcast(X) with adjusted target_shape
+// or just X if X already matches the slice output shape
+// ---------------------------------------------------------------------------
+class PropagateSliceThroughBroadcast : public ov::pass::MatcherPass {
+public:
+ OPENVINO_MATCHER_PASS_RTTI("PropagateSliceThroughBroadcast");
+
+ PropagateSliceThroughBroadcast() {
+ auto data = any_input();
+ auto target_shape = any_input();
+ auto broadcast = wrap_type<ov::op::v3::Broadcast>({data, target_shape, any_input()});
+ auto slice = wrap_type<ov::op::v8::Slice>({broadcast, any_input(), any_input(), any_input(), any_input()});
+
+ register_matcher(std::make_shared<Matcher>(slice, "PropagateSliceThroughBroadcast"), [=](Matcher& m) {
+ auto& map = m.get_pattern_value_map();
+ auto slice_node = std::dynamic_pointer_cast<ov::op::v8::Slice>(map.at(slice).get_node_shared_ptr());
+ auto broadcast_node =
+ std::dynamic_pointer_cast<ov::op::v3::Broadcast>(map.at(broadcast).get_node_shared_ptr());
+
+ if (!slice_node || !broadcast_node) {
+ return false;
+ }
+
+ int64_t slice_axis = get_propagation_axis(slice_node, broadcast_node);
+ if (slice_axis == -1) {
+ return false;
+ }
+
+ const auto& input_shape = broadcast_node->get_input_shape(0);
+ const auto& slice_shape = slice_node->get_output_shape(0);
+
+ // Check if input already matches the slice output shape on the slice axis
+ // Broadcast may have expanded a scalar or added dimensions
+ if (input_shape.size() != slice_shape.size() || input_shape[slice_axis] != slice_shape[slice_axis]) {
+ return false;
+ }
+
+ // Check if all other dimensions also match
+ for (size_t i = 0; i < input_shape.size(); ++i) {
+ if (input_shape[i] != slice_shape[i] && input_shape[i] != 1) {
+ return false;
+ }
+ }
+
+ // Create new broadcast with slice output shape as target
+ auto new_target_shape =
+ ov::op::v0::Constant::create(ov::element::i64,
+ ov::Shape{slice_shape.size()},
+ std::vector<int64_t>(slice_shape.begin(), slice_shape.end()));
+
+ auto new_broadcast = std::make_shared<ov::op::v3::Broadcast>(broadcast_node->input_value(0),
+ new_target_shape,
+ broadcast_node->input_value(2));
+ new_broadcast->set_friendly_name(broadcast_node->get_friendly_name());
+ new_broadcast->validate_and_infer_types();
+
+ if (new_broadcast->get_output_shape(0) != slice_shape) {
+ return false;
+ }
+
+ ov::replace_node(slice_node, new_broadcast);
+ return true;
+ });
+ }
+};
+
+// ---------------------------------------------------------------------------
+// R14 – Remove no-op Slice nodes (input_shape == output_shape)
+// ---------------------------------------------------------------------------
+class RemoveNoOpSlice : public ov::pass::MatcherPass {
+public:
+ OPENVINO_MATCHER_PASS_RTTI("RemoveNoOpSlice");
+
+ RemoveNoOpSlice() {
+ auto data = any_input();
+ auto slice = wrap_type<ov::op::v8::Slice>({data, any_input(), any_input(), any_input(), any_input()});
+
+ register_matcher(std::make_shared<Matcher>(slice, "RemoveNoOpSlice"), [=](Matcher& m) {
+ auto& map = m.get_pattern_value_map();
+ auto slice_node = std::dynamic_pointer_cast<ov::op::v8::Slice>(map.at(slice).get_node_shared_ptr());
+
+ if (!slice_node) {
+ return false;
+ }
+
+ // A Slice is only a no-op when every named axis is an identity range - matching
+ // input/output shape is not sufficient, e.g. a full-range step=-1 Slice reverses
+ // data while preserving shape.
+ if (slice_node->get_input_shape(0) != slice_node->get_output_shape(0)) {
+ return false;
+ }
+
+ std::map<int64_t, std::tuple<int64_t, int64_t, int64_t>> all_params;
+ if (!get_slice_all_axis_params(slice_node, all_params)) {
+ return false; // can't verify identity -> don't remove
+ }
+
+ const auto& in_shape = slice_node->get_input_shape(0);
+ for (const auto& [axis, params] : all_params) {
+ auto [start, stop, step] = params;
+ if (!is_identity_range(start, stop, step, static_cast<int64_t>(in_shape[axis]))) {
+ return false;
+ }
+ }
+
+ // Replace the no-op Slice with its input
+ ov::replace_node(slice_node, slice_node->input_value(0).get_node_shared_ptr());
+ return true;
+ });
+ }
+};
+
+// ---------------------------------------------------------------------------
+// R15 – Propagate Slice through TopK
+//
+// Pattern visualization:
+// BEFORE:
+// Input[1024,128]
+// |
+// TopK(axis=1, k=8) // Select top-8 on last dimension
+// |
+// +------+
+// | |
+// values indices
+// [1024,8] [1024,8]
+// | |
+// Slice Slice (both: axis=0, 0:1)
+// | |
+// [1,8] [1,8]
+//
+// AFTER:
+// Input[1024,128]
+// |
+// Slice(axis=0: 0:1) // Slice BEFORE TopK
+// |
+// [1,128]
+// |
+// TopK(axis=1, k=8)
+// |
+// +------+
+// | |
+// values indices
+// [1,8] [1,8]
+//
+// Pattern: TopK -> [values, indices] -> [Slice, Slice]
+// Result: Slice -> TopK -> [values, indices]
+// Constraint: Slice axis != TopK axis (otherwise would change TopK result)
+// ---------------------------------------------------------------------------
+class PropagateSliceThroughTopK : public ov::pass::MatcherPass {
+public:
+ OPENVINO_MATCHER_PASS_RTTI("PropagateSliceThroughTopK");
+
+ PropagateSliceThroughTopK() {
+ auto data = any_input();
+ auto k = any_input();
+ auto topk = wrap_type<ov::op::v1::TopK, ov::op::v3::TopK, ov::op::v11::TopK>({data, k});
+
+ register_matcher(std::make_shared<Matcher>(topk, "PropagateSliceThroughTopK"), [=](Matcher& m) {
+ auto& map = m.get_pattern_value_map();
+ auto topk_node = map.at(topk).get_node_shared_ptr();
+
+ if (!topk_node) {
+ return false;
+ }
+
+ // TopK has two outputs: values (output 0) and indices (output 1)
+ if (topk_node->get_output_size() != 2) {
+ return false;
+ }
+
+ // Check if both outputs are consumed by exactly one live consumer each
+ auto values_live = get_live_consumers(topk_node, 0);
+ auto indices_live = get_live_consumers(topk_node, 1);
+ if (values_live.size() != 1 || indices_live.size() != 1) {
+ return false;
+ }
+
+ auto values_consumer = values_live[0].get_node()->shared_from_this();
+ auto indices_consumer = indices_live[0].get_node()->shared_from_this();
+
+ auto values_slice = std::dynamic_pointer_cast<ov::op::v8::Slice>(values_consumer);
+ auto indices_slice = std::dynamic_pointer_cast<ov::op::v8::Slice>(indices_consumer);
+
+ if (!values_slice || !indices_slice) {
+ return false;
+ }
+
+ // Get slice axes
+ int64_t values_slice_axis = get_single_sliced_axis(values_slice);
+ int64_t indices_slice_axis = get_single_sliced_axis(indices_slice);
+ if (values_slice_axis == -1 || indices_slice_axis == -1) {
+ return false;
+ }
+
+ // Check if both slices are on the same axis
+ if (values_slice_axis != indices_slice_axis) {
+ return false;
+ }
+
+ // Check semantic equivalence of slice parameters
+ int64_t v_start = 0, v_stop = 0, v_step = 0;
+ int64_t i_start = 0, i_stop = 0, i_step = 0;
+ bool v_found = get_slice_axis_params(values_slice, values_slice_axis, v_start, v_stop, v_step);
+ bool i_found = get_slice_axis_params(indices_slice, indices_slice_axis, i_start, i_stop, i_step);
+
+ if (!v_found || !i_found) {
+ return false;
+ }
+
+ if (v_start != i_start || v_stop != i_stop || v_step != i_step) {
+ return false;
+ }
+
+ // Get TopK axis parameter. All TopK versions (v1/v3/v11) derive from TopKBase,
+ // which already exposes the resolved axis regardless of opset version.
+ auto topk_base = std::dynamic_pointer_cast<ov::op::util::TopKBase>(topk_node);
+ if (!topk_base) {
+ return false;
+ }
+ int64_t topk_axis = static_cast<int64_t>(topk_base->get_axis());
+
+ // Normalize TopK axis
+ topk_axis = static_cast<int64_t>(
+ ov::util::normalize_axis(topk_axis, static_cast<int64_t>(topk_node->get_input_shape(0).size())));
+
+ // Check if slice axis == topk axis (would change TopK result, not safe)
+ if (values_slice_axis == topk_axis) {
+ return false;
+ }
+
+ // Safe to propagate: insert Slice before TopK
+
+ // Create new Slice on TopK input
+ auto new_slice =
+ create_slice_with_params(topk_node->input_value(0), values_slice_axis, v_start, v_stop, v_step);
+ new_slice->set_friendly_name(topk_node->get_friendly_name() + "/slice_input");
+
+ // Create new TopK with sliced input, preserving all other attributes
+ auto new_topk = topk_node->clone_with_new_inputs({new_slice->output(0), topk_node->input_value(1)});
+ new_topk->set_friendly_name(topk_node->get_friendly_name());
+ new_topk->validate_and_infer_types();
+
+ // Replace original Slices' outputs with new TopK outputs
+ // Note: Cannot use replace_node because TopK has 2 outputs while Slice has 1
+ values_slice->output(0).replace(new_topk->output(0));
+ indices_slice->output(0).replace(new_topk->output(1));
+
+ return true;
+ });
+ }
+};
+
+// ---------------------------------------------------------------------------
+// R16 – Propagate Slice through Softmax
+// Pattern: Softmax(X, axis=A) -> Slice(axis=B) where A != B
+// Result: Slice(X, axis=B) -> Softmax(axis=A)
+// ---------------------------------------------------------------------------
+class PropagateSliceThroughSoftmax : public ov::pass::MatcherPass {
+public:
+ OPENVINO_MATCHER_PASS_RTTI("PropagateSliceThroughSoftmax");
+
+ PropagateSliceThroughSoftmax() {
+ auto data = any_input();
+ auto softmax = wrap_type<ov::op::v1::Softmax, ov::op::v8::Softmax>({data});
+ auto slice = wrap_type<ov::op::v8::Slice>({softmax, any_input(), any_input(), any_input(), any_input()});
+
+ register_matcher(std::make_shared<Matcher>(slice, "PropagateSliceThroughSoftmax"), [=](Matcher& m) {
+ auto& map = m.get_pattern_value_map();
+ auto slice_node = std::dynamic_pointer_cast<ov::op::v8::Slice>(map.at(slice).get_node_shared_ptr());
+ auto softmax_node = map.at(softmax).get_node_shared_ptr();
+
+ if (!slice_node || !softmax_node) {
+ return false;
+ }
+
+ int64_t slice_axis = get_propagation_axis(slice_node, softmax_node);
+ if (slice_axis == -1) {
+ return false;
+ }
+
+ // Get Softmax axis
+ int64_t softmax_axis = -1;
+ if (auto v1_softmax = std::dynamic_pointer_cast<ov::op::v1::Softmax>(softmax_node)) {
+ softmax_axis = v1_softmax->get_axis();
+ } else if (auto v8_softmax = std::dynamic_pointer_cast<ov::op::v8::Softmax>(softmax_node)) {
+ softmax_axis = v8_softmax->get_axis();
+ }
+
+ // Normalize Softmax axis
+ softmax_axis = static_cast<int64_t>(
+ ov::util::normalize_axis(softmax_axis, static_cast<int64_t>(softmax_node->get_input_shape(0).size())));
+
+ // Check if slice axis == softmax axis (would change Softmax result)
+ if (slice_axis == softmax_axis) {
+ return false;
+ }
+
+ // Safe to propagate: insert Slice before Softmax
+
+ auto new_slice = clone_slice(slice_node, softmax_node->input_value(0));
+ new_slice->set_friendly_name(softmax_node->get_friendly_name() + "/slice_input");
+
+ // Create new Softmax with sliced input, preserving the axis attribute
+ auto new_softmax = softmax_node->clone_with_new_inputs({new_slice->output(0)});
+ new_softmax->set_friendly_name(softmax_node->get_friendly_name());
+ new_softmax->validate_and_infer_types();
+
+ ov::replace_node(slice_node, new_softmax);
+ return true;
+ });
+ }
+};
+
+// ---------------------------------------------------------------------------
+// R17 – Propagate Slice through Concat
+// Pattern: Concat(X1, X2, ..., axis=A) -> Slice(axis=B) where A != B
+// Result: Concat(Slice(X1, axis=B), Slice(X2, axis=B), ..., axis=A)
+// ---------------------------------------------------------------------------
+class PropagateSliceThroughConcat : public ov::pass::MatcherPass {
+public:
+ OPENVINO_MATCHER_PASS_RTTI("PropagateSliceThroughConcat");
+
+ PropagateSliceThroughConcat() {
+ auto concat = wrap_type<ov::op::v0::Concat>();
+ auto slice = wrap_type<ov::op::v8::Slice>({concat, any_input(), any_input(), any_input(), any_input()});
+
+ register_matcher(std::make_shared<Matcher>(slice, "PropagateSliceThroughConcat"), [=](Matcher& m) {
+ auto& map = m.get_pattern_value_map();
+ auto slice_node = std::dynamic_pointer_cast<ov::op::v8::Slice>(map.at(slice).get_node_shared_ptr());
+ auto concat_node = std::dynamic_pointer_cast<ov::op::v0::Concat>(map.at(concat).get_node_shared_ptr());
+
+ if (!slice_node || !concat_node) {
+ return false;
+ }
+
+ int64_t slice_axis = get_propagation_axis(slice_node, concat_node);
+ if (slice_axis == -1) {
+ return false;
+ }
+
+ int64_t concat_axis = concat_node->get_axis();
+
+ // Normalize concat axis
+ concat_axis = static_cast<int64_t>(
+ ov::util::normalize_axis(concat_axis, static_cast<int64_t>(concat_node->get_input_shape(0).size())));
+
+ // Check if slice axis == concat axis (would change Concat result)
+ if (slice_axis == concat_axis) {
+ return false;
+ }
+
+ // Safe to propagate: insert Slice before each Concat input
+
+ ov::OutputVector new_concat_inputs;
+ for (size_t i = 0; i < concat_node->get_input_size(); ++i) {
+ auto input = concat_node->input_value(i);
+ auto new_slice = clone_slice(slice_node, input);
+ new_slice->set_friendly_name(concat_node->get_friendly_name() + "/slice_input_" + std::to_string(i));
+ new_concat_inputs.push_back(new_slice->output(0));
+ }
+
+ // Create new Concat with sliced inputs
+ auto new_concat = std::make_shared<ov::op::v0::Concat>(new_concat_inputs, concat_node->get_axis());
+ new_concat->set_friendly_name(concat_node->get_friendly_name());
+ new_concat->validate_and_infer_types();
+
+ ov::replace_node(slice_node, new_concat);
+ return true;
+ });
+ }
+};
+
+// ---------------------------------------------------------------------------
+// R17a – Propagate Slice through Gather
+//
+// Pattern visualization:
+// BEFORE:
+// Input[1,1024,35,256]
+// |
+// Gather(axis=2, indices) // Select from axis=2
+// |
+// [1,1024,256]
+// |
+// Slice(axis=1: 0:1) // Slice on different axis
+// |
+// [1,1,256]
+//
+// AFTER:
+// Input[1,1024,35,256]
+// |
+// Slice(axis=1: 0:1) // Slice first
+// |
+// [1,1,35,256]
+// |
+// Gather(axis=2, indices) // Gather unchanged axis
+// |
+// [1,1,256]
+//
+// Pattern: Gather -> Slice, where Slice axis != Gather axis
+// Result: Slice -> Gather
+// Constraint: Slice and Gather must operate on different axes
+// ---------------------------------------------------------------------------
+class PropagateSliceThroughGather : public ov::pass::MatcherPass {
+public:
+ OPENVINO_MATCHER_PASS_RTTI("PropagateSliceThroughGather");
+
+ PropagateSliceThroughGather() {
+ auto data = any_input();
+ auto indices = any_input();
+ auto gather =
+ wrap_type<ov::op::v1::Gather, ov::op::v7::Gather, ov::op::v8::Gather>({data, indices, any_input()});
+ auto slice = wrap_type<ov::op::v8::Slice>({gather, any_input(), any_input(), any_input(), any_input()});
+
+ register_matcher(std::make_shared<Matcher>(slice, "PropagateSliceThroughGather"), [=](Matcher& m) {
+ auto& map = m.get_pattern_value_map();
+ auto slice_node = std::dynamic_pointer_cast<ov::op::v8::Slice>(map[slice].get_node_shared_ptr());
+ auto gather_node = map[gather].get_node_shared_ptr();
+
+ int64_t slice_axis = get_propagation_axis(slice_node, gather_node);
+ if (slice_axis == -1) {
+ return false;
+ }
+
+ // Get Gather axis. All Gather versions (v1/v7/v8) derive from GatherBase, which
+ // already exposes the resolved axis regardless of opset version.
+ auto gather_base = std::dynamic_pointer_cast<ov::op::util::GatherBase>(gather_node);
+ if (!gather_base) {
+ return false;
+ }
+ int64_t gather_axis = gather_base->get_axis();
+
+ // Normalize axes
+ const auto& gather_input_shape = gather_node->get_input_shape(0);
+ gather_axis = static_cast<int64_t>(
+ ov::util::normalize_axis(gather_axis, static_cast<int64_t>(gather_input_shape.size())));
+ slice_axis = static_cast<int64_t>(
+ ov::util::normalize_axis(slice_axis, static_cast<int64_t>(slice_node->get_input_shape(0).size())));
+
+ // Check if Slice and Gather operate on different axes. The Gather output has the
+ // same rank as its input, so slice_axis on the Gather output maps to the same axis
+ // on the Gather input.
+ if (slice_axis == gather_axis) {
+ return false; // Cannot safely propagate - axes conflict
+ }
+
+ // Slice(Gather(X)) -> Gather(Slice(X))
+ // Create new Slice on the Gather input
+ auto new_slice = clone_slice(slice_node, gather_node->input_value(0));
+
+ // Create new Gather with sliced input
+ auto new_gather = gather_node->clone_with_new_inputs(
+ {new_slice, gather_node->input_value(1), gather_node->input_value(2)});
+ new_gather->set_friendly_name(gather_node->get_friendly_name());
+ new_gather->validate_and_infer_types();
+
+ ov::replace_node(slice_node, new_gather);
+ return true;
+ });
+ }
+};
+
+// ---------------------------------------------------------------------------
+// R18 – Merge consecutive Slices
+// Pattern: Slice(Slice(X))
+// Result: Single Slice with merged parameters
+// ---------------------------------------------------------------------------
+class MergeConsecutiveSlices : public ov::pass::MatcherPass {
+public:
+ OPENVINO_MATCHER_PASS_RTTI("MergeConsecutiveSlices");
+
+ MergeConsecutiveSlices() {
+ auto data = any_input();
+ auto slice1 = wrap_type<ov::op::v8::Slice>({data, any_input(), any_input(), any_input(), any_input()});
+ auto slice2 = wrap_type<ov::op::v8::Slice>({slice1, any_input(), any_input(), any_input(), any_input()});
+
+ register_matcher(std::make_shared<Matcher>(slice2, "MergeConsecutiveSlices"), [=](Matcher& m) {
+ auto& map = m.get_pattern_value_map();
+ auto child_slice = std::dynamic_pointer_cast<ov::op::v8::Slice>(map.at(slice2).get_node_shared_ptr());
+ auto parent_slice = std::dynamic_pointer_cast<ov::op::v8::Slice>(map.at(slice1).get_node_shared_ptr());
+
+ if (!child_slice || !parent_slice) {
+ return false;
+ }
+
+ // Check single consumer for parent slice
+ if (!single_consumer(parent_slice)) {
+ return false;
+ }
+
+ // Get parameters from both slices (axes already normalized to their own input rank)
+ std::map<int64_t, std::tuple<int64_t, int64_t, int64_t>> parent_params, child_params;
+ if (!get_slice_all_axis_params(parent_slice, parent_params) ||
+ !get_slice_all_axis_params(child_slice, child_params)) {
+ return false;
+ }
+
+ // Build merged parameters: start with parent slice params, then merge in child's
+ std::map<int64_t, std::tuple<int64_t, int64_t, int64_t>> merged_params = parent_params;
+ for (const auto& [axis, params] : child_params) {
+ if (merged_params.count(axis)) {
+ // Same axis - need to compose the slicing operations
+ // This is complex, for now just skip this case
+ return false;
+ }
+ merged_params[axis] = params;
+ }
+
+ // Build merged constant vectors
+ std::vector<int64_t> merged_axes;
+ std::vector<int64_t> merged_start;
+ std::vector<int64_t> merged_stop;
+ std::vector<int64_t> merged_step;
+
+ for (const auto& [axis, params] : merged_params) {
+ merged_axes.push_back(axis);
+ merged_start.push_back(std::get<0>(params));
+ merged_stop.push_back(std::get<1>(params));
+ merged_step.push_back(std::get<2>(params));
+ }
+
+ // Create merged slice
+ auto merged_slice = create_slice_with_params(parent_slice->input_value(0),
+ merged_axes,
+ merged_start,
+ merged_stop,
+ merged_step);
+ merged_slice->set_friendly_name(child_slice->get_friendly_name());
+
+ ov::replace_node(child_slice, merged_slice);
+ return true;
+ });
+ }
+};
+
+// Shared by R19/R20 below: given a node with multiple Slice consumers, factor out the axes that
+// all consumers slice identically into one common Slice on `parent_node`'s output, leaving each
+// original consumer with only its residual (non-common) axes. Returns false if the pattern
+// doesn't apply (e.g. non-Slice or non-reducing-Slice consumer, no common axes).
+static bool extract_common_slice_before_fanout(const std::shared_ptr<ov::Node>& parent_node) {
+ // A prior firing of this rule leaves the old per-consumer Slice nodes attached to
+ // parent_node's input edge (replace_node() only rewires their own consumers, not their own
+ // inputs); get_live_consumers() filters those stale edges out, or this rule would refire on
+ // them forever.
+ auto all_consumers = get_live_consumers(parent_node);
+ if (all_consumers.size() < 2) {
+ return false; // Need at least 2 live consumers
+ }
+
+ // Verify ALL consumers are reducing Slice nodes (multi-axis Slices supported)
+ std::vector<std::shared_ptr<ov::op::v8::Slice>> slice_consumers;
+ for (const auto& input : all_consumers) {
+ auto slice = std::dynamic_pointer_cast<ov::op::v8::Slice>(input.get_node()->shared_from_this());
+ if (!slice || !is_reducing_slice(slice)) {
+ return false; // Has non-Slice or non-reducing Slice consumer, skip optimization
+ }
+ slice_consumers.push_back(slice);
+ }
+
+ // Extract each consumer's own axis -> (start, stop, step) mapping
+ std::vector<std::map<int64_t, std::tuple<int64_t, int64_t, int64_t>>> slice_axis_params;
+ for (const auto& slice : slice_consumers) {
+ std::map<int64_t, std::tuple<int64_t, int64_t, int64_t>> axis_map;
+ if (!get_slice_all_axis_params(slice, axis_map)) {
+ return false;
+ }
+ slice_axis_params.push_back(axis_map);
+ }
+
+ // Find common axes: axes where ALL slices have IDENTICAL parameters
+ auto common_axes = find_common_slice_axes(slice_axis_params);
+ if (common_axes.empty()) {
+ return false;
+ }
+
+ // Create a common Slice right after parent_node (on its output). For Transpose specifically,
+ // no need to remap axes through the permutation here: PropagateSliceThroughTranspose already
+ // does that and will push this Slice upstream through Transpose on a later iteration.
+ std::shared_ptr<ov::Node> new_node = parent_node;
+ for (const auto& [axis, params] : common_axes) {
+ auto [start, stop, step] = params;
+ auto new_slice = create_slice_with_params(new_node, axis, start, stop, step);
+ new_slice->set_friendly_name(parent_node->get_friendly_name() + "_common_slice_ax" + std::to_string(axis));
+ new_node = new_slice;
+ }
+
+ // For each original Slice, create residual Slice (non-common axes only)
+ for (size_t idx = 0; idx < slice_consumers.size(); ++idx) {
+ const auto& original_slice = slice_consumers[idx];
+ const auto& orig_axes_params = slice_axis_params[idx];
+
+ std::vector<int64_t> residual_axes, residual_start, residual_stop, residual_step;
+ for (const auto& [axis, params] : orig_axes_params) {
+ if (common_axes.find(axis) == common_axes.end()) {
+ residual_axes.push_back(axis);
+ residual_start.push_back(std::get<0>(params));
+ residual_stop.push_back(std::get<1>(params));
+ residual_step.push_back(std::get<2>(params));
+ }
+ }
+
+ if (residual_axes.empty()) {
+ // No residual slice needed, connect directly to the common Slice
+ ov::replace_node(original_slice, new_node);
+ } else {
+ auto residual_slice =
+ create_slice_with_params(new_node, residual_axes, residual_start, residual_stop, residual_step);
+ residual_slice->set_friendly_name(original_slice->get_friendly_name());
+ ov::replace_node(original_slice, residual_slice);
+ }
+ }
+
+ return true;
+}
+
+// ---------------------------------------------------------------------------
+// R19/R20 – Extract common slice axes before a fanout point (Transpose or Multiply, for now)
+// when multiple Slices consume it.
+//
+// Pattern visualization (Transpose):
+// BEFORE:
+// Input[1,1024,2048]
+// |
+// Transpose(perm=[0,2,1]) // Swap axes 1 and 2
+// |
+// [1,2048,1024]
+// |
+// +--+--+
+// | |
+// Slice1 Slice2
+// (axis=1: 0:512) (axis=1: 0:1024)
+// | |
+// [1,512,1024] [1,1024,1024]
+//
+// Common axis: axis=1 sliced in both (to different ranges) -> common range 0:512
+//
+// AFTER:
+// Input[1,1024,2048]
+// |
+// Transpose(perm=[0,2,1])
+// |
+// [1,2048,1024]
+// |
+// Slice(axis=1: 0:512) // Extract common slice right after Transpose
+// |
+// [1,512,1024]
+// |
+// +--+--+
+// | |
+// Slice1' Slice2'
+// (no-op) (axis=1: 512:1024) - residual slice
+// | |
+// [1,512,1024] [1,1024,1024]
+//
+// Pattern visualization (Binary):
+// BEFORE:
+// Binary(A, B)[1,1024,8,512]
+// |
+// +--+--+
+// | | |
+// Slice1 Slice2 Slice3
+// axis=1: 0:1 axis=1: 0:1, axis=3: 0:256 axis=1: 0:1, axis=3: 256:512
+// | | |
+// [1,1,8,512] [1,1,8,256] [1,1,8,256]
+//
+// Common axis: axis=1 (all slices do 0:1)
+// Slice2 and Slice3 also slice on axis=3 (different ranges)
+//
+// AFTER:
+// Binary(A, B)[1,1024,8,512]
+// |
+// Slice(axis=1: 0:1) // Extract common slice axis
+// |
+// [1,1,8,512]
+// |
+// +--+--+
+// | | |
+// Direct Slice2' Slice3'
+// no-op axis=3: 0:256 axis=3: 256:512
+// | | |
+// [1,1,8,512] [1,1,8,256] [1,1,8,256]
+//
+// Pattern: <Transpose|Multiply> -> [Slice1, Slice2, ...] with some common slice axes
+// Result: <Transpose|Multiply> -> Slice(common axes) -> [new_Slice1, new_Slice2, ...] (residual axes)
+// ---------------------------------------------------------------------------
+class ExtractCommonSliceBeforeFanout : public ov::pass::MatcherPass {
+public:
+ OPENVINO_MATCHER_PASS_RTTI("ExtractCommonSliceBeforeFanout");
+
+ ExtractCommonSliceBeforeFanout() {
+ auto fanout = wrap_type<ov::op::v1::Transpose, ov::op::v1::Multiply>();
+
+ register_matcher(std::make_shared<Matcher>(fanout, "ExtractCommonSliceBeforeFanout"), [=](Matcher& m) {
+ return extract_common_slice_before_fanout(m.get_match_root());
+ });
+ }
+};
+
+} // anonymous namespace
+
+// ---------------------------------------------------------------------------
+// Pass entry point
+// ---------------------------------------------------------------------------
+namespace ov::npuw {
+
+bool PropagateSliceUp::run_on_model(const std::shared_ptr<ov::Model>& model) {
+ bool overall_changed = false;
+ bool iter_changed = true;
+ int iteration = 0;
+ const int max_iterations = 5000; // Safety limit to prevent infinite loops
+
+ // Iterative propagation until convergence (similar to SequenceIfReplacer)
+ // GraphRewrite.run_on_model() returns true when any matcher succeeds
+ while (iter_changed && iteration < max_iterations) {
+ LOG_DEBUG("PropagateSliceUp: iteration " << iteration);
+ iteration++;
+
+ ov::pass::GraphRewrite rewrite;
+ rewrite.add_matcher<RemoveNoOpSlice>(); // Simplify graph structure first
+ rewrite.add_matcher<PropagateSliceThroughUnary>();
+ rewrite.add_matcher<PropagateSliceThroughBinary>();
+ rewrite.add_matcher<PropagateSliceThroughReduce>();
+ rewrite.add_matcher<PropagateSliceThroughSDPA>();
+ rewrite.add_matcher<PropagateSliceThroughMatMul>();
+ rewrite.add_matcher<PropagateSliceThroughTileReshape>();
+ rewrite.add_matcher<PropagateSliceThroughUnsqueeze>();
+ rewrite.add_matcher<PropagateSliceThroughScatterElementsUpdate>();
+ rewrite.add_matcher<PropagateSliceThroughBroadcast>();
+ rewrite.add_matcher<PropagateSliceThroughTopK>();
+ rewrite.add_matcher<PropagateSliceThroughSoftmax>();
+ rewrite.add_matcher<PropagateSliceThroughConcat>();
+ rewrite.add_matcher<PropagateSliceThroughGather>();
+ rewrite.add_matcher<PropagateSliceThroughReshape>();
+ rewrite.add_matcher<ExtractCommonSliceBeforeFanout>();
+ rewrite.add_matcher<PropagateSliceThroughTranspose>();
+ rewrite.add_matcher<PropagateSliceThroughVariadicSplit>();
+ rewrite.add_matcher<MergeDuplicateSlices>();
+ rewrite.add_matcher<MergeConsecutiveSlices>();
+
+ iter_changed = rewrite.run_on_model(model);
+ overall_changed |= iter_changed;
+ }
+
+ if (iteration >= max_iterations) {
+ LOG_WARN("PropagateSliceUp: reached maximum iterations (" << max_iterations
+ << "), stopping to prevent infinite loop");
+ }
+
+ return overall_changed;
+}
+
+} // namespace ov::npuw
diff --git a/src/plugins/intel_npu/src/plugin/npuw/npuw_transformations/propagate_slice.hpp b/src/plugins/intel_npu/src/plugin/npuw/npuw_transformations/propagate_slice.hpp
new file mode 100644
index 00000000000..2933a617057
--- /dev/null
+++ b/src/plugins/intel_npu/src/plugin/npuw/npuw_transformations/propagate_slice.hpp
@@ -0,0 +1,117 @@
+// Copyright (C) 2018-2026 Intel Corporation
+// SPDX-License-Identifier: Apache-2.0
+//
+
+#pragma once
+
+#include <memory>
+#include <optional>
+
+#include "openvino/pass/pass.hpp"
+
+namespace ov::npuw {
+
+// rt_info key set by PropagateSliceThroughSDPA (rule R3) on the cloned SDPA node when it
+// slices Q's sequence axis: it records the query length *before* slicing, since K/V (and
+// thus context length) still reflect the original length. Its mere presence signals that
+// the slice propagation happened. Consumed by HFA and pyramid-attention extraction.
+inline constexpr const char* NPUW_ORIGINAL_QUERY_LENGTH_RT_KEY = "npuw_original_query_length";
+
+// Read the original (pre-slice) query length stashed by PropagateSliceThroughSDPA on
+// the SDPA's second MatMul node. Returns std::nullopt if the node is null, the rt_info
+// is absent, or it cannot be read as size_t.
+std::optional<std::size_t> find_propagated_original_query_length(const std::shared_ptr<ov::Node>& matmul2_node);
+
+// Resolve the original (pre-slice) query length for an SDPA subgraph, shared by both
+// HFA and pyramid-attention extraction. Prefers the value stashed by PropagateSliceUp on
+// `matmul2_node` (see find_propagated_original_query_length above); falls back to
+// `fallback_length` (typically derived from Q's or Softmax's static shape) when no such
+// rt_info is present, i.e. PropagateSliceUp never touched this SDPA.
+std::size_t resolve_original_query_length(std::size_t fallback_length, const std::shared_ptr<ov::Node>& matmul2_node);
+
+// Propagates an ov::op::v8::Slice upstream through elementwise ops and SDPA.
+// Each rule matches Slice(SomeOp(...)) and replaces it with SomeOp(Slice(...)).
+// GraphRewrite fires all rules to convergence so the Slice moves as far upstream
+// as possible in one pass invocation.
+//
+// Preconditions checked by every rule:
+// 1. The parent op has exactly one output consumer (the Slice).
+// 2. The Slice actually reduces the tensor (input_size > output_size on the sliced axis).
+//
+// Rules implemented:
+// R1. Slice(Eltwise1(X)) -> Eltwise1(Slice(X))
+// (single-input elementwise: Gelu, Relu, Sqrt, Tanh, Sigmoid, Erf, Convert, ...)
+// For Convert, the destination element type is explicitly preserved.
+// R2a. Slice(Eltwise2(A, B)) -> Eltwise2(Slice(A), Slice(B))
+// when A.shape == B.shape
+// R2b. Slice(Eltwise2(A, B)) -> Eltwise2(Slice(A), B) [or symmetric]
+// when one operand broadcasts on the sliced axis
+// R3. Slice(SDPA(Q,K,V,mask,...)) -> SDPA(Slice(Q),K,V,Slice(mask),...)
+// when the sliced axis is the Q sequence dimension
+// R4. Slice(Reduce*(X, axis)) -> Reduce*(Slice(X), axis)
+// when the sliced axis is different from the reduction axis
+// (supports ReduceMean, ReduceSum, ReduceMax, ReduceMin, ReduceProd, etc.)
+// R5. Slice(MatMul(X, W)) -> MatMul(Slice(X), W)
+// when the sliced axis is not the feature (last) dimension
+// R6. Slice(Reshape(X)) -> Reshape(Slice(X))
+// when the sliced axis structure is preserved by Reshape
+// R7. Slice(Transpose(X)) -> Transpose(Slice(X))
+// mapping slice axis through the permutation
+// R8. Slice(VariadicSplit(X)[i]) for all i -> VariadicSplit(Slice(X))
+// when all outputs have identical Slice consumers on the non-split axis
+// R9. Merge duplicate Slice nodes with identical inputs and parameters
+// R10. Slice(Reshape(Tile(X))) -> Reshape(Tile(Slice(X)))
+// when Tile expands a dimension that Reshape then splits, and Slice operates on the split dimension
+// (e.g., Tile([1024,2048],[128,1]) -> Reshape([131072,2048]) -> [128,1024,2048] -> Slice(axis=1))
+// R11. Slice(Unsqueeze(X)) -> Unsqueeze(Slice(X))
+// mapping slice axis accounting for inserted dimensions
+// (e.g., Unsqueeze([128,1024],axes=[2]) -> [128,1024,1] -> Slice(axis=1) -> [128,1,1])
+// R12. Slice(ScatterElementsUpdate(data, indices, updates)) ->
+// ScatterElementsUpdate(Slice(data), Slice(indices), Slice(updates))
+// when the sliced axis is not the scatter axis
+// (e.g., ScatterElementsUpdate([1024,8],[1024,8],[1024,1],axis=1) -> [1024,128] -> Slice(axis=0) -> [1,128])
+// R13. Slice(Broadcast(X)) -> Broadcast(X) with adjusted target shape
+// when input shape is compatible with slice output
+// (e.g., Broadcast([1],[1024,128]) -> [1024,128] -> Slice(axis=0) -> [1,128])
+// R14. Remove no-op Slice nodes where input_shape == output_shape
+// R15. Slice(TopK(X)[0]), Slice(TopK(X)[1]) -> TopK(Slice(X))
+// when both TopK outputs (values and indices) are consumed by semantically equivalent Slices
+// and the slice axis != TopK axis (otherwise would change TopK result)
+// (e.g., TopK([1024,128],axis=1,k=8) -> [1024,8] -> Slice(axis=0) -> [1,8])
+// R16. Slice(Softmax(X, axis=A), axis=B) -> Softmax(Slice(X, axis=B), axis=A)
+// when slice axis != Softmax axis (otherwise would change Softmax result)
+// (e.g., Softmax([1024,128],axis=1) -> [1024,128] -> Slice(axis=0) -> [1,128])
+// R17. Slice(Concat(X1,X2,...,axis=A), axis=B) -> Concat(Slice(X1,axis=B),Slice(X2,axis=B),...,axis=A)
+// when slice axis != Concat axis (otherwise would change Concat result)
+// (e.g., Concat([1,32,1024,64],[1,32,1024,64],axis=3) -> [1,32,1024,128] -> Slice(axis=2) -> [1,32,1,128])
+// R17a. Slice(Gather(X, indices, axis=A), axis=B) -> Gather(Slice(X, axis=B), indices, axis=A)
+// when slice axis != Gather axis (otherwise would affect the gathered dimension)
+// (e.g., Gather([1,1024,35,256],axis=2) -> [1,1024,256] -> Slice(axis=1) -> [1,1,256]
+// becomes Slice([1,1024,35,256],axis=1) -> [1,1,35,256] -> Gather(axis=2) -> [1,1,256])
+// R18. Slice(Slice(X)) -> Single Slice with merged parameters
+// when the two slices operate on different axes (same axis composition is complex, skipped for now)
+// (e.g., Slice([1,32,1024,128],axis=3) -> [1,32,1024,64] -> Slice(axis=2) -> [1,32,1,64]
+// becomes Slice([1,32,1024,128],axes=[2,3]) -> [1,32,1,64])
+// R19. Extract common slice axes before Transpose when multiple Slices consume it
+// Pattern: Transpose -> [Slice1, Slice2, ...] with common slice axes
+// Result: Slice(common axes) -> Transpose -> [residual_Slice1, residual_Slice2, ...]
+// (e.g., Transpose([1,1024,32,128]->[1,32,1024,128]) -> Slice1(axes=[2,3]), Slice2(axes=[2,3]),
+// Slice3(axes=[2,3])
+// where all have axis=2: 1024->1 (same), but axis=3 differs
+// becomes Slice(axis=1: 1024->1) -> Transpose([1,1,32,128]->[1,32,1,128]) -> residual slices on axis=3 only)
+// R20. Extract common slice axes before Binary op (Add/Multiply/etc.) when multiple Slices consume it
+// Pattern: Binary(A,B) -> [Slice1, Slice2, ...] with common slice axes
+// Result: Binary(Slice(A),Slice(B)) -> [residual_Slice1, residual_Slice2, ...]
+// (e.g., Multiply([1,1,1,512],[1,1024,8,512])->[1,1024,8,512] -> Slice1(axes=[1,3]), Slice2(axes=[1,3]),
+// Slice3(axes=[1])
+// where all have axis=1: 1024->1 (same), but axis=3 differs
+// becomes Multiply([1,1,1,512],Slice([1,1024,8,512]->[1,1,8,512]))->[1,1,8,512] -> residual slices on axis=3
+// only)
+
+class PropagateSliceUp : public ov::pass::ModelPass {
+public:
+ OPENVINO_MODEL_PASS_RTTI("ov::npuw::PropagateSliceUp");
+ bool run_on_model(const std::shared_ptr<ov::Model>& model) override;
+};
+
+} // namespace ov::npuw
diff --git a/src/plugins/intel_npu/src/plugin/npuw/pyramid_attention.cpp b/src/plugins/intel_npu/src/plugin/npuw/pyramid_attention.cpp
index c63174f293b..c0b047e2e14 100644
--- a/src/plugins/intel_npu/src/plugin/npuw/pyramid_attention.cpp
+++ b/src/plugins/intel_npu/src/plugin/npuw/pyramid_attention.cpp
@@ -7,6 +7,7 @@
#include <algorithm>
#include <utility>
+#include "npuw_transformations/propagate_slice.hpp"
#include "openvino/core/validation_util.hpp"
#include "openvino/op/broadcast.hpp"
#include "openvino/op/concat.hpp"
@@ -560,23 +561,28 @@ std::optional<PyramidValidationResult> validate_and_setup_pyramid_attention(cons
LOG_INFO("Found SDPA pattern: MatMul -> Add -> Softmax -> MatMul");
- // Extract query_length and full_context_length from Softmax output shape
+ // Extract query_length and full_context_length
+ // Strategy 1: Check if PropagateSliceUp has marked the SDPA (MatMul2) with original query_length
+ // Strategy 2: Fall back to Softmax output shape
auto softmax_output_shape = pattern_nodes.softmax_node->get_output_shape(0);
size_t query_length = 0;
size_t full_context_length = 0;
+ // First, get full_context_length and the default (fallback) query_length from Softmax output
if (softmax_output_shape.size() >= 2) {
- full_context_length = softmax_output_shape.back(); // Last dimension
+ full_context_length = softmax_output_shape.back(); // Last dimension (context length)
query_length = softmax_output_shape[softmax_output_shape.size() - 2]; // Second-to-last dimension
-
- LOG_DEBUG("Extracted from Softmax output shape:");
- LOG_DEBUG(" Query length: " << query_length);
- LOG_DEBUG(" Full context length: " << full_context_length);
} else {
LOG_WARN("Softmax output shape has insufficient dimensions: " << softmax_output_shape.size());
return std::nullopt;
}
+ // Try to get query_length from PropagateSliceUp rt_info (more reliable after slice propagation)
+ query_length = ov::npuw::resolve_original_query_length(query_length, pattern_nodes.matmul2_node);
+
+ LOG_DEBUG("Pyramid attention parameters: query_length=" << query_length
+ << ", full_context_length=" << full_context_length);
+
// Early return for invalid parameters
if (query_length == 0 || full_context_length == 0 || full_context_length < query_length) {
LOG_WARN("Invalid query_length (" << query_length << ") or full_context_length (" << full_context_length
diff --git a/src/plugins/intel_npu/src/plugin/sources.cmake b/src/plugins/intel_npu/src/plugin/sources.cmake
index d9f79bb3637..a03591fb98c 100644
--- a/src/plugins/intel_npu/src/plugin/sources.cmake
+++ b/src/plugins/intel_npu/src/plugin/sources.cmake
@@ -149,6 +149,8 @@ set(NPUW_SOURCES
${CMAKE_CURRENT_SOURCE_DIR}/npuw/npuw_transformations/reshape_sliced_head_to_static.hpp
${CMAKE_CURRENT_SOURCE_DIR}/npuw/npuw_transformations/reshape_to_static.cpp
${CMAKE_CURRENT_SOURCE_DIR}/npuw/npuw_transformations/reshape_to_static.hpp
+ ${CMAKE_CURRENT_SOURCE_DIR}/npuw/npuw_transformations/propagate_slice.cpp
+ ${CMAKE_CURRENT_SOURCE_DIR}/npuw/npuw_transformations/propagate_slice.hpp
${CMAKE_CURRENT_SOURCE_DIR}/npuw/npuw_transformations/slice_out_embeds.cpp
${CMAKE_CURRENT_SOURCE_DIR}/npuw/npuw_transformations/slice_out_embeds.hpp
${CMAKE_CURRENT_SOURCE_DIR}/npuw/npuw_transformations/sliding_window_mask.cpp
diff --git a/src/plugins/intel_npu/tests/unit/CMakeLists.txt b/src/plugins/intel_npu/tests/unit/CMakeLists.txt
index 344fa256975..9ec0a556096 100644
--- a/src/plugins/intel_npu/tests/unit/CMakeLists.txt
+++ b/src/plugins/intel_npu/tests/unit/CMakeLists.txt
@@ -123,6 +123,7 @@ ov_add_test_target(
${OpenVINO_SOURCE_DIR}/src/plugins/intel_npu/src/plugin/npuw/npuw_transformations/reshape_to_static.cpp
${OpenVINO_SOURCE_DIR}/src/plugins/intel_npu/src/plugin/npuw/npuw_transformations/replace_deepstack_scatter_with_add.cpp
${OpenVINO_SOURCE_DIR}/src/plugins/intel_npu/src/plugin/npuw/npuw_transformations/right_align_mask_slice_for_conv.cpp
+ ${OpenVINO_SOURCE_DIR}/src/plugins/intel_npu/src/plugin/npuw/npuw_transformations/propagate_slice.cpp
${OpenVINO_SOURCE_DIR}/src/plugins/intel_npu/src/plugin/npuw/npuw_transformations/slice_out_embeds.cpp
# kokoro pipeline
${OpenVINO_SOURCE_DIR}/src/plugins/intel_npu/src/plugin/npuw/pipelines/kokoro/kokoro_compiled_model.cpp
@@ -151,6 +152,13 @@ if(ENABLE_AVX2)
target_compile_definitions(${TARGET_NAME} PRIVATE HAVE_AVX2)
endif()
+# The unit test target compiles plugin source files directly without -fvisibility=hidden
+# (unlike the plugin itself). On GCC this causes -Wattributes for the visibility attribute
+# on static member functions in OpenVINO's rtti.hpp. Suppress the warning here.
+if(CMAKE_CXX_COMPILER_ID STREQUAL "GNU")
+ target_compile_options(${TARGET_NAME} PRIVATE -Wno-attributes)
+endif()
+
install(TARGETS ${TARGET_NAME}
RUNTIME DESTINATION tests
COMPONENT tests
diff --git a/src/plugins/intel_npu/tests/unit/npuw/pipeline_passes/propagate_slice_test.cpp b/src/plugins/intel_npu/tests/unit/npuw/pipeline_passes/propagate_slice_test.cpp
new file mode 100644
index 00000000000..5a498939551
--- /dev/null
+++ b/src/plugins/intel_npu/tests/unit/npuw/pipeline_passes/propagate_slice_test.cpp
@@ -0,0 +1,1187 @@
+// Copyright (C) 2018-2026 Intel Corporation
+// SPDX-License-Identifier: Apache-2.0
+//
+
+#include "npuw_transformations/propagate_slice.hpp"
+
+#include <gtest/gtest.h>
+
+#include "openvino/op/ops.hpp"
+
+using namespace ov;
+using namespace ov::op;
+
+// Helper to count Slice nodes
+static size_t count_slice_nodes(const std::shared_ptr<ov::Model>& model) {
+ size_t count = 0;
+ for (const auto& node : model->get_ops()) {
+ if (std::dynamic_pointer_cast<v8::Slice>(node)) {
+ count++;
+ }
+ }
+ return count;
+}
+
+// Helper to run PropagateSliceUp on a model
+static void apply_propagate_slice_up(const std::shared_ptr<ov::Model>& model) {
+ ov::npuw::PropagateSliceUp pass;
+ pass.run_on_model(model);
+}
+
+// Helper to build a single-axis Slice with explicit start/stop/step (default step=1) —
+// used by tests that slice an explicit sub-range along one axis.
+static std::shared_ptr<v8::Slice> make_slice(const Output<Node>& data,
+ int64_t axis,
+ int64_t start,
+ int64_t stop,
+ int64_t step = 1) {
+ auto start_c = v0::Constant::create(element::i64, Shape{1}, {start});
+ auto stop_c = v0::Constant::create(element::i64, Shape{1}, {stop});
+ auto step_c = v0::Constant::create(element::i64, Shape{1}, {step});
+ auto axes_c = v0::Constant::create(element::i64, Shape{1}, {axis});
+ return std::make_shared<v8::Slice>(data, start_c, stop_c, step_c, axes_c);
+}
+
+// Helper to build a single-axis Slice selecting the last index along `axis`
+// (start=-1, stop=INT64_MAX, step=1) — the common "reduce this axis to size 1"
+// pattern used across most propagation tests.
+static std::shared_ptr<v8::Slice> make_last_index_slice(const Output<Node>& data, int64_t axis) {
+ return make_slice(data, axis, -1, INT64_MAX, 1);
+}
+
+// Helper to build a multi-axis Slice with explicit per-axis start/stop (step defaults to 1 for all axes).
+static std::shared_ptr<v8::Slice> make_multi_axis_slice(const Output<Node>& data,
+ const std::vector<int64_t>& axes,
+ const std::vector<int64_t>& starts,
+ const std::vector<int64_t>& stops) {
+ std::vector<int64_t> steps(axes.size(), 1);
+ auto start_c = v0::Constant::create(element::i64, Shape{axes.size()}, starts);
+ auto stop_c = v0::Constant::create(element::i64, Shape{axes.size()}, stops);
+ auto step_c = v0::Constant::create(element::i64, Shape{axes.size()}, steps);
+ auto axes_c = v0::Constant::create(element::i64, Shape{axes.size()}, axes);
+ return std::make_shared<v8::Slice>(data, start_c, stop_c, step_c, axes_c);
+}
+
+// Test R1: Slice(Gelu(X)) -> Gelu(Slice(X))
+TEST(PropagateSliceTest, PropagateSliceThroughUnary_Gelu) {
+ // Build: Param[1,1024,3072] -> Gelu -> Slice(axis=1, 1024->1) -> Result[1,1,3072]
+ auto param = std::make_shared<v0::Parameter>(element::f32, Shape{1, 1024, 3072});
+ auto gelu = std::make_shared<v0::Gelu>(param);
+
+ auto slice = make_last_index_slice(gelu, 1);
+
+ auto result = std::make_shared<v0::Result>(slice);
+ auto model = std::make_shared<ov::Model>(ResultVector{result}, ParameterVector{param});
+
+ // Apply pass
+ apply_propagate_slice_up(model);
+
+ // Check: Slice should have moved before Gelu
+ // The result's input should be Gelu, and Gelu's input should be Slice
+ auto result_node = model->get_results()[0];
+ auto gelu_output = result_node->input_value(0);
+ ASSERT_TRUE(is_type<v0::Gelu>(gelu_output.get_node_shared_ptr()));
+
+ auto slice_output = gelu_output.get_node_shared_ptr()->input_value(0);
+ EXPECT_TRUE(is_type<v8::Slice>(slice_output.get_node_shared_ptr()));
+
+ // Check output shape
+ EXPECT_EQ(result_node->get_input_shape(0), (Shape{1, 1, 3072}));
+}
+
+// Test R2a: Slice(Add(A, B)) -> Add(Slice(A), Slice(B))
+TEST(PropagateSliceTest, PropagateSliceThroughBinary_Add_BothSliced) {
+ // Build: Add([1,1024,3072], [1,1024,3072]) -> Slice(axis=1) -> Result[1,1,3072]
+ auto param1 = std::make_shared<v0::Parameter>(element::f32, Shape{1, 1024, 3072});
+ auto param2 = std::make_shared<v0::Parameter>(element::f32, Shape{1, 1024, 3072});
+ auto add = std::make_shared<v1::Add>(param1, param2);
+
+ auto slice = make_last_index_slice(add, 1);
+
+ auto result = std::make_shared<v0::Result>(slice);
+ auto model = std::make_shared<ov::Model>(ResultVector{result}, ParameterVector{param1, param2});
+
+ // Apply pass
+ apply_propagate_slice_up(model);
+
+ // Check: Should have 2 Slice nodes (one on each input of Add)
+ EXPECT_EQ(count_slice_nodes(model), 2);
+
+ // Result's input should be Add
+ auto result_node = model->get_results()[0];
+ EXPECT_TRUE(is_type<v1::Add>(result_node->input_value(0).get_node_shared_ptr()));
+}
+
+// Test R2b: Slice(Add(A, broadcast_B)) -> Add(Slice(A), broadcast_B)
+TEST(PropagateSliceTest, PropagateSliceThroughBinary_Add_OneBroadcast) {
+ // Build: Add([1,1024,3072], [1,1,3072]) -> Slice(axis=1) -> Result[1,1,3072]
+ auto param1 = std::make_shared<v0::Parameter>(element::f32, Shape{1, 1024, 3072});
+ auto param2 = std::make_shared<v0::Parameter>(element::f32, Shape{1, 1, 3072});
+ auto add = std::make_shared<v1::Add>(param1, param2);
+
+ auto slice = make_last_index_slice(add, 1);
+
+ auto result = std::make_shared<v0::Result>(slice);
+ auto model = std::make_shared<ov::Model>(ResultVector{result}, ParameterVector{param1, param2});
+
+ // Apply pass
+ apply_propagate_slice_up(model);
+
+ // Check: Should have only 1 Slice node (on non-broadcast input)
+ EXPECT_EQ(count_slice_nodes(model), 1);
+}
+
+// Test R4: Slice(ReduceSum(X, axis=0)) with keep_dims=False
+TEST(PropagateSliceTest, PropagateSliceThroughReduce_ReduceSum) {
+ // Build: Param[8,1024,2048] -> ReduceSum(axis=0) -> [1024,2048] -> Slice(axis=0) -> [1,2048]
+ auto param = std::make_shared<v0::Parameter>(element::f32, Shape{8, 1024, 2048});
+ auto axes = v0::Constant::create(element::i64, Shape{1}, {0});
+ auto reduce = std::make_shared<v1::ReduceSum>(param, axes, false); // keep_dims=false
+
+ auto slice = make_last_index_slice(reduce, 0);
+
+ auto result = std::make_shared<v0::Result>(slice);
+ auto model = std::make_shared<ov::Model>(ResultVector{result}, ParameterVector{param});
+
+ // Apply pass
+ apply_propagate_slice_up(model);
+
+ // Check: Slice should have moved before ReduceSum on input axis=1
+ auto result_node = model->get_results()[0];
+ auto reduce_node = result_node->input_value(0).get_node_shared_ptr();
+ ASSERT_TRUE(is_type<v1::ReduceSum>(reduce_node));
+
+ auto slice_node = reduce_node->input_value(0).get_node_shared_ptr();
+ EXPECT_TRUE(is_type<v8::Slice>(slice_node));
+
+ // Check output shape: [8,1,2048] -> ReduceSum(axis=0) -> [1,2048]
+ EXPECT_EQ(result_node->get_input_shape(0), (Shape{1, 2048}));
+}
+
+// Test R5: Slice(MatMul(X, W))
+TEST(PropagateSliceTest, PropagateSliceThroughMatMul) {
+ // Build: Param[1,1024,3072] -> MatMul(W[3072,2048]) -> [1,1024,2048] -> Slice(axis=1) -> [1,1,2048]
+ auto param = std::make_shared<v0::Parameter>(element::f32, Shape{1, 1024, 3072});
+ auto weight = v0::Constant::create(element::f32, Shape{3072, 2048}, {0.1f});
+ auto matmul = std::make_shared<v0::MatMul>(param, weight);
+
+ auto slice = make_last_index_slice(matmul, 1);
+
+ auto result = std::make_shared<v0::Result>(slice);
+ auto model = std::make_shared<ov::Model>(ResultVector{result}, ParameterVector{param});
+
+ // Apply pass
+ apply_propagate_slice_up(model);
+
+ // Check: Slice should have moved before MatMul
+ auto result_node = model->get_results()[0];
+ auto matmul_node = result_node->input_value(0).get_node_shared_ptr();
+ ASSERT_TRUE(is_type<v0::MatMul>(matmul_node));
+
+ auto slice_node = matmul_node->input_value(0).get_node_shared_ptr();
+ EXPECT_TRUE(is_type<v8::Slice>(slice_node));
+}
+
+// Test R5: Slice(MatMul(X, W)) does not propagate onto the contracted (feature) axis
+TEST(PropagateSliceTest, PropagateSliceThroughMatMul_FeatureAxisBlocked) {
+ // Build: Param[1,1024,3072] -> MatMul(W[3072,2048]) -> [1,1024,2048] -> Slice(axis=2) -> [1,1024,1]
+ auto param = std::make_shared<v0::Parameter>(element::f32, Shape{1, 1024, 3072});
+ auto weight = v0::Constant::create(element::f32, Shape{3072, 2048}, {0.1f});
+ auto matmul = std::make_shared<v0::MatMul>(param, weight);
+
+ // Slicing axis=2 corresponds to the output's last (column) axis, which comes from the
+ // weight input and has no corresponding axis in the data input - must never propagate.
+ auto slice = make_last_index_slice(matmul, 2);
+
+ auto result = std::make_shared<v0::Result>(slice);
+ auto model = std::make_shared<ov::Model>(ResultVector{result}, ParameterVector{param});
+
+ apply_propagate_slice_up(model);
+
+ // Check: Slice should NOT have moved - Result's input is still the Slice, and the Slice's
+ // input is still the MatMul directly consuming the Parameter (unmodified).
+ auto result_node = model->get_results()[0];
+ auto slice_node = result_node->input_value(0).get_node_shared_ptr();
+ ASSERT_TRUE(is_type<v8::Slice>(slice_node));
+
+ auto matmul_node = slice_node->input_value(0).get_node_shared_ptr();
+ ASSERT_TRUE(is_type<v0::MatMul>(matmul_node));
+ EXPECT_TRUE(is_type<v0::Parameter>(matmul_node->input_value(0).get_node_shared_ptr()));
+}
+
+// Test R5: Slice(MatMul(X, W, transpose_a=true)) - with transpose_a, the data input's row
+// (free/non-contracted) dimension lives on its LAST raw axis rather than the second-to-last,
+// so the propagated Slice must be created on that remapped axis.
+TEST(PropagateSliceTest, PropagateSliceThroughMatMul_TransposeA) {
+ // Build: Param[1,3072,1024] (raw A: batch=1, K=3072, M=1024) -> MatMul(transpose_a=true, W[3072,2048])
+ // Effective A' = transpose(A) = [1,1024,3072] -> MatMul -> [1,1024,2048] -> Slice(axis=1) -> [1,1,2048]
+ auto param = std::make_shared<v0::Parameter>(element::f32, Shape{1, 3072, 1024});
+ auto weight = v0::Constant::create(element::f32, Shape{3072, 2048}, {0.1f});
+ auto matmul = std::make_shared<v0::MatMul>(param, weight, true, false);
+
+ auto slice = make_last_index_slice(matmul, 1);
+
+ auto result = std::make_shared<v0::Result>(slice);
+ auto model = std::make_shared<ov::Model>(ResultVector{result}, ParameterVector{param});
+
+ apply_propagate_slice_up(model);
+
+ // Check: Slice should have moved before MatMul, applied on the raw input's LAST axis (2),
+ // not on axis 1 (which would incorrectly slice the contracted K dimension).
+ auto result_node = model->get_results()[0];
+ auto matmul_node = result_node->input_value(0).get_node_shared_ptr();
+ ASSERT_TRUE(is_type<v0::MatMul>(matmul_node));
+
+ auto slice_node = std::dynamic_pointer_cast<v8::Slice>(matmul_node->input_value(0).get_node_shared_ptr());
+ ASSERT_TRUE(slice_node != nullptr);
+ EXPECT_TRUE(is_type<v0::Parameter>(slice_node->input_value(0).get_node_shared_ptr()));
+
+ auto axes_const = std::dynamic_pointer_cast<v0::Constant>(slice_node->input_value(4).get_node_shared_ptr());
+ ASSERT_TRUE(axes_const != nullptr);
+ EXPECT_EQ(axes_const->cast_vector<int64_t>(), (std::vector<int64_t>{2}));
+
+ // Final output shape must be unchanged: [1,1,2048]
+ EXPECT_EQ(result_node->get_input_shape(0), (Shape{1, 1, 2048}));
+}
+
+// Test R6: Slice(Reshape(X)) - squeeze-like with Unsqueeze
+TEST(PropagateSliceTest, PropagateSliceThroughReshape_SqueezeLike) {
+ // Build: Param[1024,2048] -> Reshape([1,1024,2048]) -> Slice(axis=1) -> [1,1,2048]
+ auto param = std::make_shared<v0::Parameter>(element::f32, Shape{1024, 2048});
+ auto pattern = v0::Constant::create(element::i64, Shape{3}, {1, 1024, 2048});
+ auto reshape = std::make_shared<v1::Reshape>(param, pattern, false);
+
+ auto slice = make_last_index_slice(reshape, 1);
+
+ auto result = std::make_shared<v0::Result>(slice);
+ auto model = std::make_shared<ov::Model>(ResultVector{result}, ParameterVector{param});
+
+ // Apply pass
+ apply_propagate_slice_up(model);
+
+ // Check: Should have Unsqueeze instead of Reshape
+ auto result_node = model->get_results()[0];
+ auto unsqueeze_node = result_node->input_value(0).get_node_shared_ptr();
+ EXPECT_TRUE(is_type<v0::Unsqueeze>(unsqueeze_node));
+
+ // Unsqueeze input should be Slice
+ auto slice_node = unsqueeze_node->input_value(0).get_node_shared_ptr();
+ EXPECT_TRUE(is_type<v8::Slice>(slice_node));
+}
+
+// Test R7: Slice(Transpose(X))
+TEST(PropagateSliceTest, PropagateSliceThroughTranspose) {
+ // Build: Param[1,32,1024,96] -> Transpose(0,2,1,3) -> [1,1024,32,96] -> Slice(axis=1) -> [1,1,32,96]
+ auto param = std::make_shared<v0::Parameter>(element::f32, Shape{1, 32, 1024, 96});
+ auto perm = v0::Constant::create(element::i64, Shape{4}, {0, 2, 1, 3});
+ auto transpose = std::make_shared<v1::Transpose>(param, perm);
+
+ auto slice = make_last_index_slice(transpose, 1);
+
+ auto result = std::make_shared<v0::Result>(slice);
+ auto model = std::make_shared<ov::Model>(ResultVector{result}, ParameterVector{param});
+
+ // Apply pass
+ apply_propagate_slice_up(model);
+
+ // Check: Slice should have moved before Transpose (on input axis=2)
+ auto result_node = model->get_results()[0];
+ auto transpose_node = result_node->input_value(0).get_node_shared_ptr();
+ ASSERT_TRUE(is_type<v1::Transpose>(transpose_node));
+
+ auto slice_node = transpose_node->input_value(0).get_node_shared_ptr();
+ EXPECT_TRUE(is_type<v8::Slice>(slice_node));
+}
+
+// Regression test: with a non-self-inverse permutation (unlike {0,2,1,3} used above, which
+// happens to be its own inverse), the propagated Slice must land on perm[output_slice_axis],
+// not on the index i where perm[i]==output_slice_axis (the inverse permutation).
+TEST(PropagateSliceTest, PropagateSliceThroughTranspose_NonSelfInversePermutation) {
+ // Build: Param[2,3,4] -> Transpose(order={1,2,0}) -> [3,4,2] -> Slice(axis=0: 3->1) -> [1,4,2]
+ // order={1,2,0} means output[0]=input[1], output[1]=input[2], output[2]=input[0].
+ // Slicing output axis=0 must propagate onto INPUT axis=1 (order[0]==1), not axis=2 (the index
+ // where order[i]==0).
+ auto param = std::make_shared<v0::Parameter>(element::f32, Shape{2, 3, 4});
+ auto order = v0::Constant::create(element::i64, Shape{3}, {1, 2, 0});
+ auto transpose = std::make_shared<v1::Transpose>(param, order);
+
+ auto slice = make_last_index_slice(transpose, 0);
+
+ auto result = std::make_shared<v0::Result>(slice);
+ auto model = std::make_shared<ov::Model>(ResultVector{result}, ParameterVector{param});
+
+ apply_propagate_slice_up(model);
+
+ auto result_node = model->get_results()[0];
+ auto transpose_node = result_node->input_value(0).get_node_shared_ptr();
+ ASSERT_TRUE(is_type<v1::Transpose>(transpose_node));
+
+ auto slice_node = std::dynamic_pointer_cast<v8::Slice>(transpose_node->input_value(0).get_node_shared_ptr());
+ ASSERT_TRUE(slice_node != nullptr);
+
+ // The propagated Slice must be on input axis=1 (order[0]==1), not axis=2.
+ auto axes_const = std::dynamic_pointer_cast<v0::Constant>(slice_node->input_value(4).get_node_shared_ptr());
+ ASSERT_TRUE(axes_const != nullptr);
+ EXPECT_EQ(axes_const->cast_vector<int64_t>(), (std::vector<int64_t>{1}));
+
+ // Final output shape must be unchanged: [1,4,2]
+ EXPECT_EQ(result_node->get_input_shape(0), (Shape{1, 4, 2}));
+}
+TEST(PropagateSliceTest, MergeDuplicateSlices) {
+ // Build: Param -> Gelu -> Split2 branches -> identical Slices on each branch
+ auto param = std::make_shared<v0::Parameter>(element::f32, Shape{1, 1024, 3072});
+ auto gelu = std::make_shared<v0::Gelu>(param);
+
+ // Create two identical slices
+ auto slice1 = make_last_index_slice(gelu, 1);
+ auto slice2 = make_last_index_slice(gelu, 1);
+
+ auto add = std::make_shared<v1::Add>(slice1, slice2);
+ auto result = std::make_shared<v0::Result>(add);
+ auto model = std::make_shared<ov::Model>(ResultVector{result}, ParameterVector{param});
+
+ // Before: 2 Slice nodes
+ ASSERT_EQ(count_slice_nodes(model), 2);
+
+ // Apply pass
+ apply_propagate_slice_up(model);
+
+ // After: Should merge to 1 Slice node
+ EXPECT_EQ(count_slice_nodes(model), 1);
+}
+
+// Test R9b: Do NOT merge slices from different output ports (e.g., TopK values vs indices)
+TEST(PropagateSliceTest, DoNotMergeSlicesFromDifferentOutputPorts) {
+ // Build: Param -> TopK(axis=1) -> [values(f32), indices(i64)] each with an identical Slice
+ // on axis=1 (the TopK axis itself). Slicing the TopK axis would change the semantics of TopK
+ // (it must see the full k-sized dimension), so PropagateSliceThroughTopK explicitly refuses
+ // to hoist this Slice above TopK -- unlike slicing any other axis, which IS a legal, intended
+ // optimization performed by that rule (and would legitimately collapse both Slices into a
+ // single one placed before TopK, which is not what this test is about).
+ // With propagation blocked, this test verifies the separate invariant that MergeDuplicateSlices
+ // never merges two Slices that consume different output ports of the same node, even when
+ // their slice parameters are identical.
+ auto param = std::make_shared<v0::Parameter>(element::f32, Shape{1024, 128});
+ auto k = v0::Constant::create(element::i64, Shape{}, {8});
+ auto topk = std::make_shared<v3::TopK>(param, k, 1, v3::TopK::Mode::MAX, v3::TopK::SortType::SORT_VALUES);
+
+ // Identical slice parameters on both outputs, slicing the TopK axis (axis=1): k=8 -> 4
+ auto slice_values = make_slice(topk->output(0), 1, 0, 4); // from values (f32)
+ auto slice_indices = make_slice(topk->output(1), 1, 0, 4); // from indices (i64)
+
+ auto result1 = std::make_shared<v0::Result>(slice_values);
+ auto result2 = std::make_shared<v0::Result>(slice_indices);
+ auto model = std::make_shared<ov::Model>(ResultVector{result1, result2}, ParameterVector{param});
+
+ // Before: 2 Slice nodes
+ ASSERT_EQ(count_slice_nodes(model), 2);
+
+ // Apply pass
+ apply_propagate_slice_up(model);
+
+ // After: Should still have 2 Slice nodes, each still consuming its own TopK output
+ // (no propagation above TopK since the sliced axis is the TopK axis itself,
+ // and no merge across the two different output ports)
+ EXPECT_EQ(count_slice_nodes(model), 2);
+
+ auto result1_input = model->get_results()[0]->input_value(0).get_node_shared_ptr();
+ EXPECT_TRUE(is_type<v8::Slice>(result1_input));
+ EXPECT_EQ(result1_input->input_value(0).get_index(), 0u);
+
+ auto result2_input = model->get_results()[1]->input_value(0).get_node_shared_ptr();
+ EXPECT_TRUE(is_type<v8::Slice>(result2_input));
+ EXPECT_EQ(result2_input->input_value(0).get_index(), 1u);
+}
+
+// Test R10: Slice(Reshape(Tile(X))) -> Reshape(Tile(Slice(X)))
+TEST(PropagateSliceTest, PropagateSliceThroughTileReshape) {
+ // Build: Param[1024,2048] -> Tile(repeats=[128,1]) -> [131072,2048]
+ // -> Reshape -> [128,1024,2048] -> Slice(axis=1,-1:) -> [128,1,2048]
+ auto param = std::make_shared<v0::Parameter>(element::f32, Shape{1024, 2048});
+
+ // Tile with repeats [128, 1]
+ auto repeats = v0::Constant::create(element::i64, Shape{2}, {128, 1});
+ auto tile = std::make_shared<v0::Tile>(param, repeats);
+
+ // Reshape [131072, 2048] -> [128, 1024, 2048]
+ auto pattern = v0::Constant::create(element::i64, Shape{3}, {128, 1024, 2048});
+ auto reshape = std::make_shared<v1::Reshape>(tile, pattern, false);
+
+ // Slice on axis=1: [128, 1024, 2048] -> [128, 1, 2048]
+ auto slice = make_last_index_slice(reshape, 1);
+
+ auto result = std::make_shared<v0::Result>(slice);
+ auto model = std::make_shared<ov::Model>(ResultVector{result}, ParameterVector{param});
+
+ // Verify initial shape
+ ASSERT_EQ(result->get_input_shape(0), (Shape{128, 1, 2048}));
+
+ // Apply pass
+ apply_propagate_slice_up(model);
+
+ // Check: Should have Reshape -> Tile -> Slice -> Param
+ auto result_node = model->get_results()[0];
+ auto reshape_node = result_node->input_value(0).get_node_shared_ptr();
+ ASSERT_TRUE(is_type<v1::Reshape>(reshape_node));
+
+ auto tile_node = reshape_node->input_value(0).get_node_shared_ptr();
+ EXPECT_TRUE(is_type<v0::Tile>(tile_node));
+
+ auto slice_node = tile_node->input_value(0).get_node_shared_ptr();
+ EXPECT_TRUE(is_type<v8::Slice>(slice_node));
+
+ // Verify final shape is still correct
+ EXPECT_EQ(result_node->get_input_shape(0), (Shape{128, 1, 2048}));
+
+ // Verify intermediate shapes
+ // Slice: [1024, 2048] -> [1, 2048]
+ EXPECT_EQ(slice_node->get_output_shape(0), (Shape{1, 2048}));
+ // Tile: [1, 2048] -> [128, 2048]
+ EXPECT_EQ(tile_node->get_output_shape(0), (Shape{128, 2048}));
+ // Reshape: [128, 2048] -> [128, 1, 2048]
+ EXPECT_EQ(reshape_node->get_output_shape(0), (Shape{128, 1, 2048}));
+}
+
+// Test R10: Slice(Reshape(Tile(X))) must NOT propagate when the Reshape splits dim0 into factors
+// that don't individually match [repeat_factor, original_dim] - even though their product matches.
+TEST(PropagateSliceTest, PropagateSliceThroughTileReshape_MismatchedSplitOrderBlocked) {
+ // Build: Param[4,10] -> Tile(repeats=[6,1]) -> [24,10]
+ // -> Reshape -> [3,8,10] (3*8=24, but NOT [repeat=6, original=4]) -> Slice(axis=1) -> [3,1,10]
+ auto param = std::make_shared<v0::Parameter>(element::f32, Shape{4, 10});
+
+ auto repeats = v0::Constant::create(element::i64, Shape{2}, {6, 1});
+ auto tile = std::make_shared<v0::Tile>(param, repeats);
+
+ // Reshape splits dim0 (24) into [3, 8] instead of the expected [6, 4]
+ auto pattern = v0::Constant::create(element::i64, Shape{3}, {3, 8, 10});
+ auto reshape = std::make_shared<v1::Reshape>(tile, pattern, false);
+
+ auto slice = make_last_index_slice(reshape, 1);
+
+ auto result = std::make_shared<v0::Result>(slice);
+ auto model = std::make_shared<ov::Model>(ResultVector{result}, ParameterVector{param});
+
+ apply_propagate_slice_up(model);
+
+ // Check: Slice must NOT have moved - Result's input is still Reshape -> Tile -> Param,
+ // with the Slice remaining right before the Result.
+ auto result_node = model->get_results()[0];
+ auto slice_node = result_node->input_value(0).get_node_shared_ptr();
+ ASSERT_TRUE(is_type<v8::Slice>(slice_node));
+
+ auto reshape_node = slice_node->input_value(0).get_node_shared_ptr();
+ ASSERT_TRUE(is_type<v1::Reshape>(reshape_node));
+
+ auto tile_node = reshape_node->input_value(0).get_node_shared_ptr();
+ ASSERT_TRUE(is_type<v0::Tile>(tile_node));
+ EXPECT_TRUE(is_type<v0::Parameter>(tile_node->input_value(0).get_node_shared_ptr()));
+}
+
+// Test R11: Slice(Unsqueeze(X)) -> Unsqueeze(Slice(X))
+TEST(PropagateSliceTest, PropagateSliceThroughUnsqueeze) {
+ // Build: Param[128,1024] -> Unsqueeze(axes=[2]) -> [128,1024,1] -> Slice(axis=1,-1:) -> [128,1,1]
+ auto param = std::make_shared<v0::Parameter>(element::f32, Shape{128, 1024});
+
+ // Unsqueeze on axis=2
+ auto axes = v0::Constant::create(element::i64, Shape{1}, {2});
+ auto unsqueeze = std::make_shared<v0::Unsqueeze>(param, axes);
+
+ // Slice on axis=1: [128, 1024, 1] -> [128, 1, 1]
+ auto slice = make_last_index_slice(unsqueeze, 1);
+
+ auto result = std::make_shared<v0::Result>(slice);
+ auto model = std::make_shared<ov::Model>(ResultVector{result}, ParameterVector{param});
+
+ // Verify initial shape
+ ASSERT_EQ(result->get_input_shape(0), (Shape{128, 1, 1}));
+
+ // Apply pass
+ apply_propagate_slice_up(model);
+
+ // Check: Should have Unsqueeze -> Slice -> Param
+ auto result_node = model->get_results()[0];
+ auto unsqueeze_node = result_node->input_value(0).get_node_shared_ptr();
+ ASSERT_TRUE(is_type<v0::Unsqueeze>(unsqueeze_node));
+
+ auto slice_node = unsqueeze_node->input_value(0).get_node_shared_ptr();
+ EXPECT_TRUE(is_type<v8::Slice>(slice_node));
+
+ // Verify final shape is still correct
+ EXPECT_EQ(result_node->get_input_shape(0), (Shape{128, 1, 1}));
+
+ // Verify intermediate shapes
+ // Slice: [128, 1024] -> [128, 1]
+ EXPECT_EQ(slice_node->get_output_shape(0), (Shape{128, 1}));
+ // Unsqueeze: [128, 1] -> [128, 1, 1]
+ EXPECT_EQ(unsqueeze_node->get_output_shape(0), (Shape{128, 1, 1}));
+}
+
+// Test R12: Slice(ScatterElementsUpdate(...)) -> ScatterElementsUpdate(Slice(...))
+TEST(PropagateSliceTest, PropagateSliceThroughScatterElementsUpdate) {
+ // Build: data[1024,8], indices[1024,8], updates[1024,8]
+ // -> ScatterElementsUpdate(axis=1) -> [1024,8] -> Slice(axis=0,-1:) -> [1,8]
+ auto data = std::make_shared<v0::Parameter>(element::f32, Shape{1024, 8});
+ auto indices = std::make_shared<v0::Parameter>(element::i32, Shape{1024, 8});
+ auto updates = std::make_shared<v0::Parameter>(element::f32, Shape{1024, 8});
+
+ // ScatterElementsUpdate with axis=1 (v12 version)
+ auto scatter_axis = v0::Constant::create(element::i64, Shape{}, {1});
+ auto scatter = std::make_shared<v12::ScatterElementsUpdate>(data, indices, updates, scatter_axis);
+
+ // Slice on axis=0: [1024, 8] -> [1, 8]
+ auto slice = make_last_index_slice(scatter, 0);
+
+ auto result = std::make_shared<v0::Result>(slice);
+ auto model = std::make_shared<ov::Model>(ResultVector{result}, ParameterVector{data, indices, updates});
+
+ // Apply pass
+ apply_propagate_slice_up(model);
+
+ // Check: Should have ScatterElementsUpdate with sliced inputs
+ auto result_node = model->get_results()[0];
+ auto scatter_node = result_node->input_value(0).get_node_shared_ptr();
+ ASSERT_TRUE(is_type<v12::ScatterElementsUpdate>(scatter_node));
+
+ // All three inputs should be Slice nodes
+ auto data_input = scatter_node->input_value(0).get_node_shared_ptr();
+ EXPECT_TRUE(is_type<v8::Slice>(data_input));
+
+ auto indices_input = scatter_node->input_value(1).get_node_shared_ptr();
+ EXPECT_TRUE(is_type<v8::Slice>(indices_input));
+
+ auto updates_input = scatter_node->input_value(2).get_node_shared_ptr();
+ EXPECT_TRUE(is_type<v8::Slice>(updates_input));
+
+ // Verify shapes: all sliced on axis=0, 1024 -> 1
+ EXPECT_EQ(data_input->get_output_shape(0), (Shape{1, 8}));
+ EXPECT_EQ(indices_input->get_output_shape(0), (Shape{1, 8}));
+ EXPECT_EQ(updates_input->get_output_shape(0), (Shape{1, 8}));
+}
+
+// Test: shared single_consumer() guard blocks propagation through a multi-consumer parent
+TEST(PropagateSliceTest, MultiConsumerBlocksPropagation) {
+ // Build: Param -> Gelu (2 consumers) -> Slice on one branch
+ auto param = std::make_shared<v0::Parameter>(element::f32, Shape{1, 1024, 3072});
+ auto gelu = std::make_shared<v0::Gelu>(param);
+
+ auto slice = make_last_index_slice(gelu, 1);
+
+ // Create second consumer
+ auto relu = std::make_shared<v0::Relu>(gelu);
+
+ auto result1 = std::make_shared<v0::Result>(slice);
+ auto result2 = std::make_shared<v0::Result>(relu);
+ auto model = std::make_shared<ov::Model>(ResultVector{result1, result2}, ParameterVector{param});
+
+ // Apply pass
+ apply_propagate_slice_up(model);
+
+ // Check: Slice should NOT have moved (Gelu has multiple consumers)
+ auto result_node = model->get_results()[0];
+ EXPECT_TRUE(is_type<v8::Slice>(result_node->input_value(0).get_node_shared_ptr()));
+}
+
+// Test R1 (Convert): Slice(Convert(X)) -> Convert(Slice(X))
+TEST(PropagateSliceTest, ConvertUnary) {
+ // Build: Param -> Convert -> Slice
+ auto param = std::make_shared<v0::Parameter>(element::f32, Shape{1, 1024, 3072});
+ auto convert = std::make_shared<v0::Convert>(param, element::f16);
+
+ auto slice = make_last_index_slice(convert, 1);
+
+ auto result = std::make_shared<v0::Result>(slice);
+ auto model = std::make_shared<ov::Model>(ResultVector{result}, ParameterVector{param});
+
+ // Apply pass
+ apply_propagate_slice_up(model);
+
+ // Expected: Param -> Slice -> Convert
+ auto result_node = model->get_results()[0];
+ auto out_convert = result_node->input_value(0).get_node_shared_ptr();
+ EXPECT_TRUE(is_type<v0::Convert>(out_convert));
+
+ auto convert_input = out_convert->input_value(0).get_node_shared_ptr();
+ EXPECT_TRUE(is_type<v8::Slice>(convert_input));
+
+ auto slice_input = convert_input->input_value(0).get_node_shared_ptr();
+ EXPECT_TRUE(is_type<v0::Parameter>(slice_input));
+}
+
+// Test R13: Slice(Broadcast(X)) -> Broadcast(X) with adjusted target_shape
+TEST(PropagateSliceTest, BroadcastSimplification) {
+ // Build: Param([1,128]) -> Broadcast([1024,128]) -> Slice(axis=0, -1:) -> [1,128]
+ auto param = std::make_shared<v0::Parameter>(element::f32, Shape{1, 128});
+ auto target_shape = v0::Constant::create(element::i64, Shape{2}, {1024, 128});
+ auto axes_mapping = v0::Constant::create(element::i64, Shape{2}, {0, 1});
+ auto broadcast = std::make_shared<v3::Broadcast>(param, target_shape, axes_mapping);
+
+ auto slice = make_last_index_slice(broadcast, 0);
+
+ auto result = std::make_shared<v0::Result>(slice);
+ auto model = std::make_shared<ov::Model>(ResultVector{result}, ParameterVector{param});
+
+ // Apply pass
+ apply_propagate_slice_up(model);
+
+ // Expected: Broadcast should be adjusted to output [1,128] directly
+ auto result_node = model->get_results()[0];
+ auto out_node = result_node->input_value(0).get_node_shared_ptr();
+
+ // Should be Broadcast directly, not Slice
+ EXPECT_TRUE(is_type<v3::Broadcast>(out_node));
+ EXPECT_EQ(out_node->get_output_shape(0), (Shape{1, 128}));
+}
+
+// Test R14: Remove no-op Slice nodes (input_shape == output_shape)
+TEST(PropagateSliceTest, RemoveNoOpSlice) {
+ // Build: Param([1024,128]) -> Slice(axis=0, 0:1024) [no-op] -> Gelu
+ auto param = std::make_shared<v0::Parameter>(element::f32, Shape{1024, 128});
+
+ // No-op slice: 0:1024 (same as input)
+ auto no_op_slice = make_slice(param, 0, 0, 1024);
+
+ auto gelu = std::make_shared<v0::Gelu>(no_op_slice);
+
+ auto result = std::make_shared<v0::Result>(gelu);
+ auto model = std::make_shared<ov::Model>(ResultVector{result}, ParameterVector{param});
+
+ // Apply pass
+ apply_propagate_slice_up(model);
+
+ // Expected: No-op slice should be removed, Gelu connected to param directly
+ auto result_node = model->get_results()[0];
+ auto out_gelu = result_node->input_value(0).get_node_shared_ptr();
+ EXPECT_TRUE(is_type<v0::Gelu>(out_gelu));
+
+ auto gelu_input = out_gelu->input_value(0).get_node_shared_ptr();
+ EXPECT_TRUE(is_type<v0::Parameter>(gelu_input));
+}
+
+// Regression test: a full-range Slice with a negative step reverses data while preserving
+// shape, so it must NOT be removed as a no-op even though input_shape == output_shape.
+TEST(PropagateSliceTest, RemoveNoOpSlice_ReversedStepNotRemoved) {
+ // Build: Param([1024,128]) -> Slice(axis=0, start=-1,stop=INT64_MIN,step=-1) [full reversal,
+ // same shape 1024] -> Gelu
+ auto param = std::make_shared<v0::Parameter>(element::f32, Shape{1024, 128});
+
+ auto reversed_slice = make_slice(param, 0, -1, INT64_MIN, -1);
+ ASSERT_EQ(reversed_slice->get_output_shape(0), (Shape{1024, 128}));
+
+ auto gelu = std::make_shared<v0::Gelu>(reversed_slice);
+
+ auto result = std::make_shared<v0::Result>(gelu);
+ auto model = std::make_shared<ov::Model>(ResultVector{result}, ParameterVector{param});
+
+ apply_propagate_slice_up(model);
+
+ // Expected: the reversing Slice must still be present between Param and Gelu.
+ auto result_node = model->get_results()[0];
+ auto out_gelu = result_node->input_value(0).get_node_shared_ptr();
+ ASSERT_TRUE(is_type<v0::Gelu>(out_gelu));
+
+ auto gelu_input = out_gelu->input_value(0).get_node_shared_ptr();
+ EXPECT_TRUE(is_type<v8::Slice>(gelu_input));
+}
+
+// Test R15: Slice(TopK(X)[values]), Slice(TopK(X)[indices]) -> TopK(Slice(X))
+TEST(PropagateSliceTest, PropagateSliceThroughTopK) {
+ // Build: Param[1024,128] -> TopK(axis=1, k=8) -> values[1024,8] -> Slice[1,8]
+ // -> indices[1024,8] -> Slice[1,8]
+ auto param = std::make_shared<v0::Parameter>(element::f32, Shape{1024, 128});
+ auto k = v0::Constant::create(element::i64, Shape{}, {8});
+ auto topk = std::make_shared<v3::TopK>(param, k, 1, v3::TopK::Mode::MAX, v3::TopK::SortType::SORT_VALUES);
+
+ // Slice on axis=0: [1024, 8] -> [1, 8]
+ auto values_slice = make_slice(topk->output(0), 0, 0, 1);
+ auto indices_slice = make_slice(topk->output(1), 0, 0, 1);
+
+ auto result1 = std::make_shared<v0::Result>(values_slice);
+ auto result2 = std::make_shared<v0::Result>(indices_slice);
+ auto model = std::make_shared<ov::Model>(ResultVector{result1, result2}, ParameterVector{param});
+
+ // Apply pass
+ apply_propagate_slice_up(model);
+
+ // Expected: TopK(Slice(param))
+ // Result 1 should be TopK output 0 (values)
+ auto result_node1 = model->get_results()[0];
+ auto topk_node1 = result_node1->input_value(0).get_node_shared_ptr();
+ EXPECT_TRUE(is_type<v3::TopK>(topk_node1));
+ EXPECT_EQ(topk_node1->get_output_shape(0), (Shape{1, 8}));
+
+ // Result 2 should be TopK output 1 (indices)
+ auto result_node2 = model->get_results()[1];
+ auto topk_node2 = result_node2->input_value(0).get_node_shared_ptr();
+ EXPECT_TRUE(is_type<v3::TopK>(topk_node2));
+ EXPECT_EQ(topk_node2->get_output_shape(1), (Shape{1, 8}));
+
+ // Both should point to the same TopK node
+ EXPECT_EQ(topk_node1.get(), topk_node2.get());
+
+ // TopK input should be Slice of param
+ auto slice_input = topk_node1->input_value(0).get_node_shared_ptr();
+ EXPECT_TRUE(is_type<v8::Slice>(slice_input));
+ EXPECT_EQ(slice_input->get_output_shape(0), (Shape{1, 128}));
+
+ auto param_input = slice_input->input_value(0).get_node_shared_ptr();
+ EXPECT_TRUE(is_type<v0::Parameter>(param_input));
+}
+
+// Test R16: Slice(Softmax(X, axis=A), axis=B) -> Softmax(Slice(X, axis=B), axis=A) where A != B
+TEST(PropagateSliceTest, PropagateSliceThroughSoftmax) {
+ // Build: Param[1024,128] -> Softmax(axis=1) -> [1024,128] -> Slice(axis=0) -> [1,128]
+ auto param = std::make_shared<v0::Parameter>(element::f32, Shape{1024, 128});
+ auto softmax = std::make_shared<v8::Softmax>(param, 1); // axis=1 (last dimension)
+
+ // Slice on axis=0: [1024,128] -> [1,128]
+ auto slice = make_slice(softmax, 0, 0, 1);
+
+ auto result = std::make_shared<v0::Result>(slice);
+ auto model = std::make_shared<ov::Model>(ResultVector{result}, ParameterVector{param});
+
+ // Apply pass
+ apply_propagate_slice_up(model);
+
+ // Expected: Softmax(Slice(param))
+ auto result_node = model->get_results()[0];
+ auto softmax_node = result_node->input_value(0).get_node_shared_ptr();
+ EXPECT_TRUE(is_type<v8::Softmax>(softmax_node));
+ EXPECT_EQ(softmax_node->get_output_shape(0), (Shape{1, 128}));
+
+ // Softmax input should be Slice of param
+ auto slice_input = softmax_node->input_value(0).get_node_shared_ptr();
+ EXPECT_TRUE(is_type<v8::Slice>(slice_input));
+ EXPECT_EQ(slice_input->get_output_shape(0), (Shape{1, 128}));
+
+ auto param_input = slice_input->input_value(0).get_node_shared_ptr();
+ EXPECT_TRUE(is_type<v0::Parameter>(param_input));
+}
+
+// Test R17: Slice(Concat(X1,X2,...,axis=A), axis=B) -> Concat(Slice(X1,axis=B),Slice(X2,axis=B),...,axis=A)
+TEST(PropagateSliceTest, PropagateSliceThroughConcat) {
+ // Build: Param1[1,32,1024,64] + Param2[1,32,1024,64] -> Concat(axis=3) -> [1,32,1024,128]
+ // -> Slice(axis=2) -> [1,32,1,128]
+ auto param1 = std::make_shared<v0::Parameter>(element::f32, Shape{1, 32, 1024, 64});
+ auto param2 = std::make_shared<v0::Parameter>(element::f32, Shape{1, 32, 1024, 64});
+ auto concat = std::make_shared<v0::Concat>(OutputVector{param1, param2}, 3); // axis=3
+
+ // Slice on axis=2: [1,32,1024,128] -> [1,32,1,128]
+ auto slice = make_slice(concat, 2, 0, 1);
+
+ auto result = std::make_shared<v0::Result>(slice);
+ auto model = std::make_shared<ov::Model>(ResultVector{result}, ParameterVector{param1, param2});
+
+ // Apply pass
+ apply_propagate_slice_up(model);
+
+ // Expected: Concat(Slice(param1), Slice(param2))
+ auto result_node = model->get_results()[0];
+ auto concat_node = result_node->input_value(0).get_node_shared_ptr();
+ EXPECT_TRUE(is_type<v0::Concat>(concat_node));
+ EXPECT_EQ(concat_node->get_output_shape(0), (Shape{1, 32, 1, 128}));
+
+ // Both Concat inputs should be Slices
+ auto input0 = concat_node->input_value(0).get_node_shared_ptr();
+ EXPECT_TRUE(is_type<v8::Slice>(input0));
+ EXPECT_EQ(input0->get_output_shape(0), (Shape{1, 32, 1, 64}));
+
+ auto input1 = concat_node->input_value(1).get_node_shared_ptr();
+ EXPECT_TRUE(is_type<v8::Slice>(input1));
+ EXPECT_EQ(input1->get_output_shape(0), (Shape{1, 32, 1, 64}));
+
+ // Slices should connect to params
+ EXPECT_TRUE(is_type<v0::Parameter>(input0->input_value(0).get_node_shared_ptr()));
+ EXPECT_TRUE(is_type<v0::Parameter>(input1->input_value(0).get_node_shared_ptr()));
+}
+
+// Test R18: Merge consecutive Slices on different axes
+TEST(PropagateSliceTest, MergeConsecutiveSlicesOnDifferentAxes) {
+ // Build: Param[1,32,1024,128] -> Slice(axis=3) -> [1,32,1024,64] -> Slice(axis=2) -> [1,32,1,64]
+ auto param = std::make_shared<v0::Parameter>(element::f32, Shape{1, 32, 1024, 128});
+
+ // First slice on axis=3: [1,32,1024,128] -> [1,32,1024,64]
+ auto slice1 = make_slice(param, 3, 0, 64);
+
+ // Second slice on axis=2: [1,32,1024,64] -> [1,32,1,64]
+ auto slice2 = make_slice(slice1, 2, 0, 1);
+
+ auto result = std::make_shared<v0::Result>(slice2);
+ auto model = std::make_shared<ov::Model>(ResultVector{result}, ParameterVector{param});
+
+ // Apply pass
+ apply_propagate_slice_up(model);
+
+ // Expected: Single merged Slice(param) with axes=[2,3]
+ auto result_node = model->get_results()[0];
+ auto merged_slice = result_node->input_value(0).get_node_shared_ptr();
+ EXPECT_TRUE(is_type<v8::Slice>(merged_slice));
+ EXPECT_EQ(merged_slice->get_output_shape(0), (Shape{1, 32, 1, 64}));
+
+ // Merged slice should directly connect to param
+ auto slice_input = merged_slice->input_value(0).get_node_shared_ptr();
+ EXPECT_TRUE(is_type<v0::Parameter>(slice_input));
+
+ // Verify that axes parameter contains both axes [2, 3]
+ auto axes_node = merged_slice->input_value(4).get_node_shared_ptr();
+ auto axes_const = std::dynamic_pointer_cast<v0::Constant>(axes_node);
+ ASSERT_TRUE(axes_const != nullptr);
+ auto axes_vec = axes_const->cast_vector<int64_t>();
+ EXPECT_EQ(axes_vec.size(), 2);
+ // Note: axes might be in sorted order
+ EXPECT_TRUE((axes_vec[0] == 2 && axes_vec[1] == 3) || (axes_vec[0] == 3 && axes_vec[1] == 2));
+}
+
+// Test R19: Extract common slice axes before Transpose
+TEST(PropagateSliceTest, ExtractCommonSliceBeforeTranspose) {
+ // Build: Transpose([1,1024,32,128] -> [1,32,1024,128])
+ // -> Slice1(axes=[2,3]): -> [1,32,1,64] (axis=2: 0:1, axis=3: 0:64)
+ // -> Slice2(axes=[2,3]): -> [1,32,1,64] (axis=2: 0:1, axis=3: 64:128)
+ // -> Slice3(axes=[2]): -> [1,32,1,128] (axis=2: 0:1 only)
+ // Common axis: 2 (all slices: 0:1:1)
+ // Expected: Slice(axis=1: 0:1:1) -> Transpose -> residual slices on axis=3
+
+ auto param = std::make_shared<v0::Parameter>(element::f32, Shape{1, 1024, 32, 128});
+ auto order = v0::Constant::create(element::i64, Shape{4}, {0, 2, 1, 3}); // [0,1,2,3] -> [0,2,1,3]
+ auto transpose = std::make_shared<v1::Transpose>(param, order);
+
+ // Slice1: axes=[2,3], start=[0,0], stop=[1,64]
+ auto slice1 = make_multi_axis_slice(transpose, {2, 3}, {0, 0}, {1, 64});
+
+ // Slice2: axes=[2,3], start=[0,64], stop=[1,128]
+ auto slice2 = make_multi_axis_slice(transpose, {2, 3}, {0, 64}, {1, 128});
+
+ // Slice3: axes=[2], start=[0], stop=[1]
+ auto slice3 = make_slice(transpose, 2, 0, 1);
+
+ auto result1 = std::make_shared<v0::Result>(slice1);
+ auto result2 = std::make_shared<v0::Result>(slice2);
+ auto result3 = std::make_shared<v0::Result>(slice3);
+ auto model = std::make_shared<ov::Model>(ResultVector{result1, result2, result3}, ParameterVector{param});
+
+ // Apply pass
+ apply_propagate_slice_up(model);
+
+ // Expected structure: Slice(axis=1) -> Transpose -> [residual_slice1, residual_slice2, result3]
+ // Find the Transpose in the graph
+ std::shared_ptr<v1::Transpose> new_transpose;
+ for (const auto& node : model->get_ops()) {
+ auto trans = std::dynamic_pointer_cast<v1::Transpose>(node);
+ if (trans) {
+ new_transpose = trans;
+ break;
+ }
+ }
+ ASSERT_TRUE(new_transpose != nullptr);
+
+ // Transpose input should be a Slice on param
+ auto transpose_input = new_transpose->input_value(0).get_node_shared_ptr();
+ EXPECT_TRUE(is_type<v8::Slice>(transpose_input));
+
+ // That slice should connect to param
+ auto slice_input = transpose_input->input_value(0).get_node_shared_ptr();
+ EXPECT_TRUE(is_type<v0::Parameter>(slice_input));
+
+ // Transpose output shape should be [1,32,1,128]
+ EXPECT_EQ(new_transpose->get_output_shape(0), (Shape{1, 32, 1, 128}));
+
+ // Result1 should have a residual slice (axis=3 only)
+ auto result1_input = model->get_results()[0]->input_value(0).get_node_shared_ptr();
+ EXPECT_TRUE(is_type<v8::Slice>(result1_input));
+ EXPECT_EQ(result1_input->get_output_shape(0), (Shape{1, 32, 1, 64}));
+
+ // Result2 should have a residual slice (axis=3 only)
+ auto result2_input = model->get_results()[1]->input_value(0).get_node_shared_ptr();
+ EXPECT_TRUE(is_type<v8::Slice>(result2_input));
+ EXPECT_EQ(result2_input->get_output_shape(0), (Shape{1, 32, 1, 64}));
+
+ // Result3 should connect directly to Transpose (no residual slice)
+ auto result3_input = model->get_results()[2]->input_value(0).get_node_shared_ptr();
+ EXPECT_TRUE(is_type<v1::Transpose>(result3_input));
+ EXPECT_EQ(result3_input->get_output_shape(0), (Shape{1, 32, 1, 128}));
+}
+
+// Test R20: Extract common slice axes before Binary op
+TEST(PropagateSliceTest, ExtractCommonSliceBeforeBinary) {
+ // Build: Multiply([1,1,1,512], [1,1024,8,512]) -> [1,1024,8,512]
+ // -> Slice1(axes=[1,3]): -> [1,1,8,512] (axis=1: 0:1, axis=3: 0:512)
+ // -> Slice2(axes=[1,3]): -> [1,1,8,256] (axis=1: 0:1, axis=3: 0:256)
+ // -> Slice3(axes=[1,3]): -> [1,1,8,256] (axis=1: 0:1, axis=3: 256:512)
+ // Common axis: 1 (all slices: 0:1:1)
+ // Expected: Multiply([1,1,1,512], Slice([1,1024,8,512]->[1,1,8,512])) -> [1,1,8,512]
+ // -> residual slices on axis=3
+
+ auto param1 = std::make_shared<v0::Parameter>(element::f32, Shape{1, 1, 1, 512});
+ auto param2 = std::make_shared<v0::Parameter>(element::f32, Shape{1, 1024, 8, 512});
+ auto multiply = std::make_shared<v1::Multiply>(param1, param2);
+
+ // Slice1/2/3 are constructed inline (not kept as named locals) so that once the pass
+ // rewires the Results away from them, the old Slice nodes are actually destroyed.
+ // Otherwise they'd keep dangling input edges into Multiply alive, making it look like
+ // it still has multiple consumers and blocking further propagation.
+ auto result1 = std::make_shared<v0::Result>(make_multi_axis_slice(multiply, {1, 3}, {0, 0}, {1, 512}));
+ auto result2 = std::make_shared<v0::Result>(make_multi_axis_slice(multiply, {1, 3}, {0, 0}, {1, 256}));
+ auto result3 = std::make_shared<v0::Result>(make_multi_axis_slice(multiply, {1, 3}, {0, 256}, {1, 512}));
+ auto model = std::make_shared<ov::Model>(ResultVector{result1, result2, result3}, ParameterVector{param1, param2});
+
+ // Apply pass
+ apply_propagate_slice_up(model);
+
+ // Expected structure: Multiply([1,1,1,512], Slice(param2)) -> residual slices
+ // Find the Multiply in the graph
+ std::shared_ptr<v1::Multiply> new_multiply;
+ for (const auto& node : model->get_ops()) {
+ auto mult = std::dynamic_pointer_cast<v1::Multiply>(node);
+ if (mult) {
+ new_multiply = mult;
+ break;
+ }
+ }
+ ASSERT_TRUE(new_multiply != nullptr);
+
+ // Multiply's second input should be a Slice on param2
+ auto multiply_input2 = new_multiply->input_value(1).get_node_shared_ptr();
+ EXPECT_TRUE(is_type<v8::Slice>(multiply_input2));
+
+ // That slice should connect to param2
+ auto slice_input = multiply_input2->input_value(0).get_node_shared_ptr();
+ EXPECT_TRUE(is_type<v0::Parameter>(slice_input));
+
+ // Multiply output shape should be [1,1,8,512]
+ EXPECT_EQ(new_multiply->get_output_shape(0), (Shape{1, 1, 8, 512}));
+
+ // Result1 should connect directly to Multiply (no residual slice, axis=3 is full range)
+ auto result1_input = model->get_results()[0]->input_value(0).get_node_shared_ptr();
+ EXPECT_TRUE(is_type<v1::Multiply>(result1_input));
+ EXPECT_EQ(result1_input->get_output_shape(0), (Shape{1, 1, 8, 512}));
+
+ // Result2 should have a residual slice (axis=3 only)
+ auto result2_input = model->get_results()[1]->input_value(0).get_node_shared_ptr();
+ EXPECT_TRUE(is_type<v8::Slice>(result2_input));
+ EXPECT_EQ(result2_input->get_output_shape(0), (Shape{1, 1, 8, 256}));
+
+ // Result3 should have a residual slice (axis=3 only)
+ auto result3_input = model->get_results()[2]->input_value(0).get_node_shared_ptr();
+ EXPECT_TRUE(is_type<v8::Slice>(result3_input));
+ EXPECT_EQ(result3_input->get_output_shape(0), (Shape{1, 1, 8, 256}));
+}
+
+// Test R17a: Slice(Gather(X, indices, axis=2), axis=1) -> Gather(Slice(X, axis=1), indices, axis=2)
+TEST(PropagateSliceTest, PropagateSliceThroughGather) {
+ // Build: Param[1,1024,35,256] -> Gather(axis=2, indices=constant) -> [1,1024,256]
+ // -> Slice(axis=1, 1024->1) -> [1,1,256]
+ auto param = std::make_shared<v0::Parameter>(element::f32, Shape{1, 1024, 35, 256});
+
+ // Gather on axis=2, select one element (index 0)
+ auto indices = v0::Constant::create(element::i64, Shape{}, {0});
+ auto gather_axis = v0::Constant::create(element::i64, Shape{}, {2});
+ auto gather = std::make_shared<v8::Gather>(param, indices, gather_axis);
+
+ // Slice on axis=1 (1024->1)
+ auto slice = make_slice(gather, 1, 0, 1);
+
+ auto result = std::make_shared<v0::Result>(slice);
+ auto model = std::make_shared<ov::Model>(ResultVector{result}, ParameterVector{param});
+
+ // Apply transformation
+ apply_propagate_slice_up(model);
+
+ // Expected: Parameter -> Slice(axis=1) -> Gather(axis=2) -> Result
+
+ // Find the Result's input
+ auto result_input = model->get_results()[0]->input_value(0).get_node_shared_ptr();
+
+ // Should be Gather
+ EXPECT_TRUE(is_type<v8::Gather>(result_input));
+ auto new_gather = std::dynamic_pointer_cast<v8::Gather>(result_input);
+ EXPECT_EQ(new_gather->get_output_shape(0), (Shape{1, 1, 256}));
+
+ // Gather's input should be Slice
+ auto gather_input = new_gather->input_value(0).get_node_shared_ptr();
+ EXPECT_TRUE(is_type<v8::Slice>(gather_input));
+ auto new_slice = std::dynamic_pointer_cast<v8::Slice>(gather_input);
+ EXPECT_EQ(new_slice->get_output_shape(0), (Shape{1, 1, 35, 256}));
+
+ // Slice's input should be Parameter
+ auto slice_input = new_slice->input_value(0).get_node_shared_ptr();
+ EXPECT_TRUE(is_type<v0::Parameter>(slice_input));
+}
+
+// Test R3: Slice(SDPA(Q,K,V), axis=seq) -> SDPA(Slice(Q,axis=seq), K, V)
+TEST(PropagateSliceTest, PropagateSliceThroughSDPA) {
+ // Build: Q,K,V[1,8,1024,64] -> SDPA(causal=false) -> [1,8,1024,64]
+ // -> Slice(axis=2, seq: 1024->1) -> [1,8,1,64]
+ auto q = std::make_shared<v0::Parameter>(element::f32, Shape{1, 8, 1024, 64});
+ auto k = std::make_shared<v0::Parameter>(element::f32, Shape{1, 8, 1024, 64});
+ auto v = std::make_shared<v0::Parameter>(element::f32, Shape{1, 8, 1024, 64});
+ auto sdpa = std::make_shared<v13::ScaledDotProductAttention>(q, k, v, false);
+
+ // Slice on axis=2 (query sequence axis): 1024 -> 1
+ auto slice = make_last_index_slice(sdpa, 2);
+
+ auto result = std::make_shared<v0::Result>(slice);
+ auto model = std::make_shared<ov::Model>(ResultVector{result}, ParameterVector{q, k, v});
+
+ // Apply pass
+ apply_propagate_slice_up(model);
+
+ // Expected: SDPA(Slice(Q), K, V) -- only Q is sliced, K/V are unaffected
+ auto result_node = model->get_results()[0];
+ auto sdpa_node = result_node->input_value(0).get_node_shared_ptr();
+ ASSERT_TRUE(is_type<v13::ScaledDotProductAttention>(sdpa_node));
+ EXPECT_EQ(sdpa_node->get_output_shape(0), (Shape{1, 8, 1, 64}));
+
+ auto q_input = sdpa_node->input_value(0).get_node_shared_ptr();
+ EXPECT_TRUE(is_type<v8::Slice>(q_input));
+ EXPECT_EQ(q_input->get_output_shape(0), (Shape{1, 8, 1, 64}));
+ EXPECT_TRUE(is_type<v0::Parameter>(q_input->input_value(0).get_node_shared_ptr()));
+
+ // K and V should remain the original (unsliced) Parameters
+ EXPECT_TRUE(is_type<v0::Parameter>(sdpa_node->input_value(1).get_node_shared_ptr()));
+ EXPECT_TRUE(is_type<v0::Parameter>(sdpa_node->input_value(2).get_node_shared_ptr()));
+}
+
+// Regression test: a mask with a DIFFERENT rank than the SDPA output (e.g. [B,Sq,Sk] vs a
+// 4-D [B,H,Sq,D] output) must block propagation entirely rather than mapping the sequence
+// axis onto the wrong mask dimension.
+TEST(PropagateSliceTest, PropagateSliceThroughSDPA_RankMismatchedMaskBlocksPropagation) {
+ // Build: Q,K,V[1,8,1024,64], mask[1,1024,1024] (3-D, one rank lower than the 4-D output)
+ // -> SDPA(causal=false) -> [1,8,1024,64] -> Slice(axis=2, seq: 1024->1) -> [1,8,1,64]
+ auto q = std::make_shared<v0::Parameter>(element::f32, Shape{1, 8, 1024, 64});
+ auto k = std::make_shared<v0::Parameter>(element::f32, Shape{1, 8, 1024, 64});
+ auto v = std::make_shared<v0::Parameter>(element::f32, Shape{1, 8, 1024, 64});
+ auto mask = std::make_shared<v0::Parameter>(element::f32, Shape{1, 1024, 1024});
+ auto sdpa = std::make_shared<v13::ScaledDotProductAttention>(q, k, v, mask, false);
+
+ auto slice = make_last_index_slice(sdpa, 2);
+
+ auto result = std::make_shared<v0::Result>(slice);
+ auto model = std::make_shared<ov::Model>(ResultVector{result}, ParameterVector{q, k, v, mask});
+
+ apply_propagate_slice_up(model);
+
+ // Check: Slice must NOT have moved - Result's input is still the Slice, directly on the
+ // original (unsliced) SDPA node.
+ auto result_node = model->get_results()[0];
+ auto slice_node = result_node->input_value(0).get_node_shared_ptr();
+ ASSERT_TRUE(is_type<v8::Slice>(slice_node));
+
+ auto sdpa_node = slice_node->input_value(0).get_node_shared_ptr();
+ ASSERT_TRUE(is_type<v13::ScaledDotProductAttention>(sdpa_node));
+ EXPECT_TRUE(is_type<v0::Parameter>(sdpa_node->input_value(0).get_node_shared_ptr()));
+}
+
+// Regression test: Add(split->output(0), split->output(1)) must NOT be treated as
+// "both inputs are the same node" - the two operands are different output ports of the
+// same VariadicSplit, so they must each get their own Slice (not a shared one).
+TEST(PropagateSliceTest, PropagateSliceThroughBinary_SameNodeDifferentPortsNotShared) {
+ // Build: Param[1,1024,2048] -> VariadicSplit(axis=2, [1024,1024]) -> out0[1,1024,1024], out1[1,1024,1024]
+ // -> Add(out0, out1) -> Slice(axis=1, 1024->1) -> [1,1,1024]
+ auto param = std::make_shared<v0::Parameter>(element::f32, Shape{1, 1024, 2048});
+ auto split_axis = v0::Constant::create(element::i64, Shape{}, {2});
+ auto split_lengths = v0::Constant::create(element::i64, Shape{2}, {1024, 1024});
+ auto vsplit = std::make_shared<v1::VariadicSplit>(param, split_axis, split_lengths);
+
+ auto add = std::make_shared<v1::Add>(vsplit->output(0), vsplit->output(1));
+ auto slice = make_last_index_slice(add, 1);
+
+ auto result = std::make_shared<v0::Result>(slice);
+ auto model = std::make_shared<ov::Model>(ResultVector{result}, ParameterVector{param});
+
+ apply_propagate_slice_up(model);
+
+ // Expected: Add(Slice(out0), Slice(out1)) - two DISTINCT Slice nodes, each consuming its
+ // own VariadicSplit output port (not a single Slice reused for both).
+ auto result_node = model->get_results()[0];
+ auto add_node = result_node->input_value(0).get_node_shared_ptr();
+ ASSERT_TRUE(is_type<v1::Add>(add_node));
+
+ auto add_input0 = add_node->input_value(0);
+ auto add_input1 = add_node->input_value(1);
+ ASSERT_TRUE(is_type<v8::Slice>(add_input0.get_node_shared_ptr()));
+ ASSERT_TRUE(is_type<v8::Slice>(add_input1.get_node_shared_ptr()));
+ EXPECT_NE(add_input0.get_node_shared_ptr(), add_input1.get_node_shared_ptr());
+
+ EXPECT_EQ(add_input0.get_node_shared_ptr()->input_value(0).get_index(), 0u);
+ EXPECT_EQ(add_input1.get_node_shared_ptr()->input_value(0).get_index(), 1u);
+}
+
+// Test R6 (non-squeeze-like): Slice(Reshape(X)) where Reshape genuinely splits a dimension
+// (not just inserts/removes size-1 dims), so the pass must update the Reshape's constant
+// pattern directly instead of inserting an Unsqueeze.
+TEST(PropagateSliceTest, PropagateSliceThroughReshape_UpdatePattern) {
+ // Build: Param[1024,6] -> Reshape([1024,2,3]) -> Slice(axis=0, 1024->1) -> [1,2,3]
+ auto param = std::make_shared<v0::Parameter>(element::f32, Shape{1024, 6});
+ auto pattern = v0::Constant::create(element::i64, Shape{3}, {1024, 2, 3});
+ auto reshape = std::make_shared<v1::Reshape>(param, pattern, false);
+
+ auto slice = make_last_index_slice(reshape, 0);
+
+ auto result = std::make_shared<v0::Result>(slice);
+ auto model = std::make_shared<ov::Model>(ResultVector{result}, ParameterVector{param});
+
+ // Verify initial shape
+ ASSERT_EQ(result->get_input_shape(0), (Shape{1, 2, 3}));
+
+ // Apply pass
+ apply_propagate_slice_up(model);
+
+ // Expected: Reshape(Slice(param)) with an updated constant pattern (still a Reshape, not Unsqueeze)
+ auto result_node = model->get_results()[0];
+ auto reshape_node = result_node->input_value(0).get_node_shared_ptr();
+ ASSERT_TRUE(is_type<v1::Reshape>(reshape_node));
+ EXPECT_EQ(reshape_node->get_output_shape(0), (Shape{1, 2, 3}));
+
+ auto slice_node = reshape_node->input_value(0).get_node_shared_ptr();
+ EXPECT_TRUE(is_type<v8::Slice>(slice_node));
+ EXPECT_EQ(slice_node->get_output_shape(0), (Shape{1, 6}));
+ EXPECT_TRUE(is_type<v0::Parameter>(slice_node->input_value(0).get_node_shared_ptr()));
+
+ // Reshape's pattern constant should reflect the sliced first dimension
+ auto pattern_node = std::dynamic_pointer_cast<v0::Constant>(reshape_node->input_value(1).get_node_shared_ptr());
+ ASSERT_TRUE(pattern_node != nullptr);
+ EXPECT_EQ(pattern_node->cast_vector<int64_t>(), (std::vector<int64_t>{1, 2, 3}));
+}
+
+// Test R8: Slice(VariadicSplit(X)[i]) for all i -> VariadicSplit(Slice(X))
+TEST(PropagateSliceTest, PropagateSliceThroughVariadicSplit) {
+ // Build: Param[1,1024,3072] -> VariadicSplit(axis=2, split_lengths=[1024,1024,1024])
+ // -> 3x [1,1024,1024], each followed by an identical Slice(axis=1, 0:1) -> [1,1,1024]
+ auto param = std::make_shared<v0::Parameter>(element::f32, Shape{1, 1024, 3072});
+ auto split_axis = v0::Constant::create(element::i64, Shape{}, {2});
+ auto split_lengths = v0::Constant::create(element::i64, Shape{3}, {1024, 1024, 1024});
+ auto vsplit = std::make_shared<v1::VariadicSplit>(param, split_axis, split_lengths);
+
+ auto slice0 = make_slice(vsplit->output(0), 1, 0, 1);
+ auto slice1 = make_slice(vsplit->output(1), 1, 0, 1);
+ auto slice2 = make_slice(vsplit->output(2), 1, 0, 1);
+
+ auto result0 = std::make_shared<v0::Result>(slice0);
+ auto result1 = std::make_shared<v0::Result>(slice1);
+ auto result2 = std::make_shared<v0::Result>(slice2);
+ auto model = std::make_shared<ov::Model>(ResultVector{result0, result1, result2}, ParameterVector{param});
+
+ // Before: 3 Slice nodes (one per VariadicSplit output)
+ ASSERT_EQ(count_slice_nodes(model), 3);
+
+ // Apply pass
+ apply_propagate_slice_up(model);
+
+ // After: a single common Slice moved before VariadicSplit; per-output Slices are gone
+ EXPECT_EQ(count_slice_nodes(model), 1);
+
+ // Each Result should now connect directly to a VariadicSplit output
+ std::shared_ptr<v1::VariadicSplit> new_vsplit;
+ for (size_t i = 0; i < 3; ++i) {
+ auto result_input = model->get_results()[i]->input_value(0).get_node_shared_ptr();
+ EXPECT_TRUE(is_type<v1::VariadicSplit>(result_input));
+ EXPECT_EQ(result_input->get_output_shape(i), (Shape{1, 1, 1024}));
+ new_vsplit = std::dynamic_pointer_cast<v1::VariadicSplit>(result_input);
+ }
+
+ // VariadicSplit's data input should be the propagated common Slice
+ ASSERT_TRUE(new_vsplit != nullptr);
+ auto vsplit_input = new_vsplit->input_value(0).get_node_shared_ptr();
+ EXPECT_TRUE(is_type<v8::Slice>(vsplit_input));
+ EXPECT_EQ(vsplit_input->get_output_shape(0), (Shape{1, 1, 3072}));
+ EXPECT_TRUE(is_type<v0::Parameter>(vsplit_input->input_value(0).get_node_shared_ptr()));
+}
diff --git a/src/plugins/intel_npu/tests/unit/npuw/pipeline_passes/slice_out_embeds_test.cpp b/src/plugins/intel_npu/tests/unit/npuw/pipeline_passes/slice_out_embeds_test.cpp
index 1341589c207..048c9a64da2 100644
--- a/src/plugins/intel_npu/tests/unit/npuw/pipeline_passes/slice_out_embeds_test.cpp
+++ b/src/plugins/intel_npu/tests/unit/npuw/pipeline_passes/slice_out_embeds_test.cpp
@@ -43,8 +43,10 @@ TEST_F(SliceOutEmbedsPassTest, SliceIsInsertedWhenGenerationTokenLenIsLessThanPr
std::unique_ptr<ov::npuw::LLMCompiledModel> compiled;
ASSERT_NO_THROW(compiled = create_compiled_model({{"NPUW_LLM_SHARED_HEAD", "YES"},
+ {"NPUW_LLM_PROPAGATE_SLICE_UP", "NO"},
{"NPUW_LLM_MAX_GENERATION_TOKEN_LEN", "8"}},
recorder));
+
ASSERT_NE(compiled, nullptr);
const auto& prefill = require_sub_model(recorder, "_prefill");
@@ -73,9 +75,9 @@ TEST_F(SliceOutEmbedsPassTest, SliceIsNotInsertedWhenGenerationTokenLenEqualsPro
std::unique_ptr<ov::npuw::LLMCompiledModel> compiled;
// MAX_GENERATION_TOKEN_LEN=128 equals MAX_PROMPT_LEN=128, so no slicing is needed.
- ASSERT_NO_THROW(compiled = create_compiled_model({{"NPUW_LLM_SHARED_HEAD", "YES"},
- {"NPUW_LLM_MAX_GENERATION_TOKEN_LEN", "128"}},
- recorder));
+ ASSERT_NO_THROW(compiled = create_compiled_model(
+ {{"NPUW_LLM_SHARED_HEAD", "YES"}, {"NPUW_LLM_MAX_GENERATION_TOKEN_LEN", "128"}},
+ recorder));
ASSERT_NE(compiled, nullptr);
const auto& prefill = require_sub_model(recorder, "_prefill");
@@ -101,9 +103,9 @@ TEST_F(SliceOutEmbedsPassTest, SliceNotAppliedWhenNoSharedHead) {
RecordingFactory recorder;
std::unique_ptr<ov::npuw::LLMCompiledModel> compiled;
- ASSERT_NO_THROW(compiled = create_compiled_model({{"NPUW_LLM_SHARED_HEAD", "NO"},
- {"NPUW_LLM_MAX_GENERATION_TOKEN_LEN", "8"}},
- recorder));
+ ASSERT_NO_THROW(
+ compiled = create_compiled_model({{"NPUW_LLM_SHARED_HEAD", "NO"}, {"NPUW_LLM_MAX_GENERATION_TOKEN_LEN", "8"}},
+ recorder));
ASSERT_NE(compiled, nullptr);
// lm_head sub-model must not exist when SHARED_HEAD=NO