Skip to content

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

[NPUW] Re-lay out linear-attention conv state as channels-innermost (#38723)

Pengqiang Lib5890b7e922d
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 dd6c797212b..484f71d69b9 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
@@ -63,6 +63,7 @@ INTEL_NPU_NPUW_SIMPLE_OPT(NPUW_LLM_MAX_PROMPT_LEN, uint32_t, 1024, ov::intel_npu
INTEL_NPU_NPUW_SIMPLE_OPT(NPUW_LLM_MAX_GENERATION_TOKEN_LEN, uint32_t, 1, ov::intel_npu::npuw::llm, max_generation_token_len, "NPUW_LLM_MAX_GENERATION_TOKEN_LEN", LLM, EXPOSED, CACHED, ALL)
INTEL_NPU_NPUW_SIMPLE_OPT(NPUW_LLM_MIN_RESPONSE_LEN, uint32_t, 128, ov::intel_npu::npuw::llm, min_response_len, "NPUW_LLM_MIN_RESPONSE_LEN", LLM, EXPOSED, CACHED, ALL)
INTEL_NPU_NPUW_SIMPLE_OPT(NPUW_LLM_OPTIMIZE_V_TENSORS, bool, true, ov::intel_npu::npuw::llm, optimize_v_tensors, "NPUW_LLM_OPTIMIZE_V_TENSORS", LLM, EXPOSED, CACHED, ALL)
+INTEL_NPU_NPUW_SIMPLE_OPT(NPUW_LLM_OPTIMIZE_LINCACHE_LAYOUT, bool, true, ov::intel_npu::npuw::llm, optimize_lincache_layout, "NPUW_LLM_OPTIMIZE_LINCACHE_LAYOUT", LLM, EXPOSED, CACHED, ALL)
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)
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 b3634c3867d..1d3f9b6571c 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
@@ -23,6 +23,7 @@
#include "npuw_transformations/duplicate_shared_kv_concat.hpp"
#include "npuw_transformations/insert_vocab_sub128.hpp"
#include "npuw_transformations/lora_stateful_to_stateless.hpp"
+#include "npuw_transformations/optimize_lincache_layout.hpp"
#include "npuw_transformations/optimize_value_tensors.hpp"
#include "npuw_transformations/patch_sliding_window_mask.hpp"
#include "npuw_transformations/propagate_slice.hpp"
@@ -1001,6 +1002,14 @@ ov::npuw::LLMCompiledModel::LLMCompiledModel(const std::shared_ptr<ov::Model>& m
ov::npuw::PatchSlidingWindowMask().run_on_model(kvcache_model);
}
+ if (m_cfg.get<::intel_npu::NPUW_LLM_OPTIMIZE_LINCACHE_LAYOUT>()) {
+ // Applied once before the prefill model and the generate variants are cloned, so all of
+ // them share the conv state layout that the byte-wise present -> past copy relies on.
+ if (ov::npuw::util::OptimizeLinCacheLayout().run_on_model(kvcache_model)) {
+ LOG_DEBUG("Conv state tensors re-laid out as [batch, kernel, channels]");
+ }
+ }
+
LOG_DEBUG("Creating prefill model as clone of transformed kvcache one.");
auto prefill_model = kvcache_model->clone();
prefill_model->set_friendly_name(kvcache_model->get_friendly_name() + "_prefill");
@@ -2084,6 +2093,7 @@ void ov::npuw::LLMCompiledModel::implement_properties() {
BIND(npuw::llm::max_prompt_len, NPUW_LLM_MAX_PROMPT_LEN, get),
BIND(npuw::llm::min_response_len, NPUW_LLM_MIN_RESPONSE_LEN, get),
BIND(npuw::llm::optimize_v_tensors, NPUW_LLM_OPTIMIZE_V_TENSORS, get),
+ BIND(npuw::llm::optimize_lincache_layout, NPUW_LLM_OPTIMIZE_LINCACHE_LAYOUT, get),
BIND(npuw::llm::optimize_fp8, NPUW_LLM_OPTIMIZE_FP8, get),
BIND(npuw::llm::cache_rope, NPUW_LLM_CACHE_ROPE, get),
BIND(npuw::llm::enable_block_based_kv_cache, NPUW_LLM_ENABLE_BLOCK_BASED_KV_CACHE, get),
diff --git a/src/plugins/intel_npu/src/plugin/npuw/npuw_transformations/optimize_lincache_layout.cpp b/src/plugins/intel_npu/src/plugin/npuw/npuw_transformations/optimize_lincache_layout.cpp
new file mode 100644
index 00000000000..3e41801a4da
--- /dev/null
+++ b/src/plugins/intel_npu/src/plugin/npuw/npuw_transformations/optimize_lincache_layout.cpp
@@ -0,0 +1,146 @@
+// Copyright (C) 2018-2026 Intel Corporation
+// SPDX-License-Identifier: Apache-2.0
+//
+
+#include "optimize_lincache_layout.hpp"
+
+#include <map>
+#include <optional>
+#include <string>
+#include <unordered_set>
+#include <utility>
+#include <vector>
+
+#include "../logging.hpp"
+#include "../util.hpp"
+#include "openvino/core/validation_util.hpp"
+#include "openvino/op/concat.hpp"
+#include "openvino/op/constant.hpp"
+#include "openvino/op/parameter.hpp"
+#include "openvino/op/result.hpp"
+#include "openvino/op/transpose.hpp"
+
+namespace {
+
+// Returns the cache_params.{past|present}.conv.N name carried by the tensor, if any.
+std::optional<std::string> conv_cache_name(const ov::descriptor::Tensor& tensor, const std::string& past_or_present) {
+ for (const auto& name : tensor.get_names()) {
+ if (name.find(".conv.") != std::string::npos && ov::npuw::util::matchLinCacheString(name, past_or_present)) {
+ return name;
+ }
+ }
+ return std::nullopt;
+}
+
+// cache_params.past.conv.12 -> "12"
+std::string layer_index(const std::string& name) {
+ return name.substr(name.rfind('.') + 1);
+}
+
+bool is_rank3(const ov::PartialShape& shape) {
+ return shape.rank().is_static() && shape.rank().get_length() == 3;
+}
+
+// Matches the conv state consumer of the supported hybrid models (Qwen3.5, MiniCPM-V-4.7, LFM2).
+// StatefulToStateless replaces the beam-search Gather on the state with the Parameter, so the pass sees
+// Parameter -> Concat(last axis)
+// New tokens are appended along the last axis, so the kernel axis is innermost. Any other graph
+// shape is not recognized and the state is left alone.
+bool is_kernel_innermost(const ov::Output<ov::Node>& state) {
+ for (const auto& input : state.get_target_inputs()) {
+ if (const auto concat = ov::as_type<ov::op::v0::Concat>(input.get_node())) {
+ const auto rank = concat->get_output_partial_shape(0).rank();
+ return rank.is_static() && ov::util::normalize_axis(concat->get_axis(), rank.get_length()) == 2;
+ }
+ }
+ return false;
+}
+
+std::shared_ptr<ov::op::v0::Constant> swap_last_two_axes() {
+ return ov::op::v0::Constant::create(ov::element::i32, ov::Shape{3}, {0, 2, 1});
+}
+
+} // namespace
+
+bool ov::npuw::util::OptimizeLinCacheLayout::run_on_model(const std::shared_ptr<ov::Model>& model) {
+ std::map<std::string, std::shared_ptr<ov::op::v0::Parameter>> past;
+ std::map<std::string, std::shared_ptr<ov::op::v0::Result>> present;
+
+ for (const auto& param : model->get_parameters()) {
+ if (const auto name = conv_cache_name(param->get_output_tensor(0), "past")) {
+ past.emplace(layer_index(*name), param);
+ }
+ }
+ for (const auto& result : model->get_results()) {
+ if (const auto name = conv_cache_name(result->get_input_tensor(0), "present")) {
+ present.emplace(layer_index(*name), result);
+ }
+ }
+ if (past.empty()) {
+ return false;
+ }
+
+ // The pipeline copies present -> past byte-wise, so every past state needs a present
+ // counterpart and both must be the expected [batch, channels, kernel] rank-3 tensors,
+ // with the kernel axis innermost as observed from how the state is consumed.
+ // Apply the transform to all pairs or to none to keep the copy consistent.
+ for (const auto& [idx, param] : past) {
+ const auto it = present.find(idx);
+ if (it == present.end()) {
+ LOG_DEBUG("Conv state " << idx << " has no present counterpart, lincache layout left unchanged");
+ return false;
+ }
+ if (!is_rank3(param->get_partial_shape()) || !is_rank3(it->second->get_input_partial_shape(0))) {
+ LOG_DEBUG("Conv state " << idx << " is not rank-3, lincache layout left unchanged");
+ return false;
+ }
+ if (!is_kernel_innermost(param->output(0))) {
+ LOG_DEBUG("Conv state " << idx << " is not stored kernel-innermost, lincache layout left unchanged");
+ return false;
+ }
+ }
+
+ // A pass-through Result can share its tensor names with a Parameter. Snapshot all
+ // I/O names before reconnecting any consumers, and restore them after validation.
+ std::vector<std::pair<ov::Output<ov::Node>, std::unordered_set<std::string>>> io_names;
+ for (const auto& input : model->inputs()) {
+ io_names.emplace_back(input, input.get_names());
+ }
+ for (const auto& output : model->outputs()) {
+ io_names.emplace_back(output, output.get_names());
+ }
+
+ for (auto& [idx, param] : past) {
+ // Parameter: [batch, channels, kernel] -> [batch, kernel, channels], then restore the
+ // original layout for the consumers with a Transpose.
+ auto shape = param->get_partial_shape();
+ std::swap(shape[1], shape[2]);
+ const auto consumers = param->output(0).get_target_inputs();
+ param->set_partial_shape(shape);
+ param->validate_and_infer_types();
+
+ auto to_kernel_innermost = std::make_shared<ov::op::v1::Transpose>(param, swap_last_two_axes());
+ to_kernel_innermost->set_friendly_name(param->get_friendly_name() + "/lincache_layout");
+ for (auto consumer : consumers) {
+ consumer.replace_source_output(to_kernel_innermost);
+ }
+
+ // Result: transpose the produced state into the new layout.
+ auto result = present.at(idx);
+ auto source = result->input_value(0);
+
+ auto to_channels_innermost = std::make_shared<ov::op::v1::Transpose>(source, swap_last_two_axes());
+ to_channels_innermost->set_friendly_name(result->get_friendly_name() + "/lincache_layout");
+ source.set_names({});
+ result->input(0).replace_source_output(to_channels_innermost);
+ result->validate_and_infer_types();
+
+ LOG_DEBUG("Conv state " << idx << " re-laid out to " << shape);
+ }
+
+ model->validate_nodes_and_infer_types();
+ for (auto& [port, names] : io_names) {
+ port.set_names(names);
+ }
+ return true;
+}
diff --git a/src/plugins/intel_npu/src/plugin/npuw/npuw_transformations/optimize_lincache_layout.hpp b/src/plugins/intel_npu/src/plugin/npuw/npuw_transformations/optimize_lincache_layout.hpp
new file mode 100644
index 00000000000..768b7794676
--- /dev/null
+++ b/src/plugins/intel_npu/src/plugin/npuw/npuw_transformations/optimize_lincache_layout.hpp
@@ -0,0 +1,39 @@
+// Copyright (C) 2018-2026 Intel Corporation
+// SPDX-License-Identifier: Apache-2.0
+//
+
+#pragma once
+
+#include "openvino/pass/pass.hpp"
+
+namespace ov {
+namespace npuw {
+namespace util {
+
+// Re-lays out the depthwise-conv state of linear-attention layers (GatedDeltaNet,
+// Mamba-style and LFM2 short-conv mixers) from [batch, channels, kernel] to
+// [batch, kernel, channels].
+//
+// The state is only ever produced and consumed by the LLM pipeline itself
+// (present -> past copy), so its physical layout is free to choose. With the
+// channels innermost the NPU compiler can feed the Concat -> GroupConvolution
+// chain in NHWC directly and the per-token transpose of the state (a slow
+// element-wise permute DMA) plus its inverse on the output disappear.
+//
+// Graph semantics are preserved: a Transpose is inserted right after each
+// cache_params.past.conv.N Parameter and right before each
+// cache_params.present.conv.N Result. Tensor names stay on the model I/O.
+// Only the conv state consumer of the supported hybrid models is recognized,
+// Parameter -> Concat(last axis); otherwise no state is changed.
+// The pass is not idempotent: run it once, before the prefill and generate models are cloned.
+class OptimizeLinCacheLayout : public ov::pass::ModelPass {
+public:
+ OPENVINO_MODEL_PASS_RTTI("ov::npuw::OptimizeLinCacheLayout");
+
+ // Returns true when the conv state pairs have been re-laid out.
+ bool run_on_model(const std::shared_ptr<ov::Model>& model) override;
+};
+
+} // namespace util
+} // namespace npuw
+} // namespace ov
diff --git a/src/plugins/intel_npu/src/plugin/sources.cmake b/src/plugins/intel_npu/src/plugin/sources.cmake
index 2c8717059e7..57bbbca515b 100644
--- a/src/plugins/intel_npu/src/plugin/sources.cmake
+++ b/src/plugins/intel_npu/src/plugin/sources.cmake
@@ -141,6 +141,8 @@ set(NPUW_SOURCES
${CMAKE_CURRENT_SOURCE_DIR}/npuw/npuw_transformations/kv_cache_compressed.hpp
${CMAKE_CURRENT_SOURCE_DIR}/npuw/npuw_transformations/lora_stateful_to_stateless.cpp
${CMAKE_CURRENT_SOURCE_DIR}/npuw/npuw_transformations/lora_stateful_to_stateless.hpp
+ ${CMAKE_CURRENT_SOURCE_DIR}/npuw/npuw_transformations/optimize_lincache_layout.cpp
+ ${CMAKE_CURRENT_SOURCE_DIR}/npuw/npuw_transformations/optimize_lincache_layout.hpp
${CMAKE_CURRENT_SOURCE_DIR}/npuw/npuw_transformations/optimize_value_tensors.cpp
${CMAKE_CURRENT_SOURCE_DIR}/npuw/npuw_transformations/optimize_value_tensors.hpp
${CMAKE_CURRENT_SOURCE_DIR}/npuw/npuw_transformations/shrink_sliding_window_kv_cache.cpp
diff --git a/src/plugins/intel_npu/tests/unit/CMakeLists.txt b/src/plugins/intel_npu/tests/unit/CMakeLists.txt
index f616a0402a4..f9ca9a76d4f 100644
--- a/src/plugins/intel_npu/tests/unit/CMakeLists.txt
+++ b/src/plugins/intel_npu/tests/unit/CMakeLists.txt
@@ -119,6 +119,7 @@ ov_add_test_target(
${OpenVINO_SOURCE_DIR}/src/plugins/intel_npu/src/plugin/npuw/npuw_transformations/drop_zp_subtract.cpp
${OpenVINO_SOURCE_DIR}/src/plugins/intel_npu/src/plugin/npuw/npuw_transformations/untangle_dq_scale.cpp
${OpenVINO_SOURCE_DIR}/src/plugins/intel_npu/src/plugin/npuw/npuw_transformations/lora_stateful_to_stateless.cpp
+ ${OpenVINO_SOURCE_DIR}/src/plugins/intel_npu/src/plugin/npuw/npuw_transformations/optimize_lincache_layout.cpp
${OpenVINO_SOURCE_DIR}/src/plugins/intel_npu/src/plugin/npuw/npuw_transformations/optimize_value_tensors.cpp
${OpenVINO_SOURCE_DIR}/src/plugins/intel_npu/src/plugin/npuw/npuw_transformations/shrink_sliding_window_kv_cache.cpp
${OpenVINO_SOURCE_DIR}/src/plugins/intel_npu/src/plugin/npuw/npuw_transformations/patch_sliding_window_mask.cpp
@@ -219,6 +220,7 @@ target_sources(${TARGET_NAME} PRIVATE
${CMAKE_CURRENT_SOURCE_DIR}/npuw/pipeline_passes/remove_empty_kv_inputs_test.cpp
${CMAKE_CURRENT_SOURCE_DIR}/npuw/pipeline_passes/remove_token_type_ids_test.cpp
${CMAKE_CURRENT_SOURCE_DIR}/npuw/pipeline_passes/stateful_to_stateless_test.cpp
+ ${CMAKE_CURRENT_SOURCE_DIR}/npuw/pipeline_passes/optimize_lincache_layout_test.cpp
${CMAKE_CURRENT_SOURCE_DIR}/npuw/pyramid_attention_test.cpp
${CMAKE_CURRENT_SOURCE_DIR}/npuw/sdpa_pattern_matcher_test.cpp
${CMAKE_CURRENT_SOURCE_DIR}/npuw/host_flash_attention_test.cpp
diff --git a/src/plugins/intel_npu/tests/unit/npuw/npuw_options_smoke_test.cpp b/src/plugins/intel_npu/tests/unit/npuw/npuw_options_smoke_test.cpp
index e6a276ed8ce..7210e99d926 100644
--- a/src/plugins/intel_npu/tests/unit/npuw/npuw_options_smoke_test.cpp
+++ b/src/plugins/intel_npu/tests/unit/npuw/npuw_options_smoke_test.cpp
@@ -142,6 +142,7 @@ std::vector<Case> make_cases() {
numeric_case<::intel_npu::NPUW_LLM_MIN_RESPONSE_LEN>("NPUW_LLM_MIN_RESPONSE_LEN", "192", uint32_t{192}),
numeric_case<::intel_npu::NPUW_LLM_MAX_LORA_RANK>("NPUW_LLM_MAX_LORA_RANK", "64", uint32_t{64}),
bool_case<::intel_npu::NPUW_LLM_OPTIMIZE_V_TENSORS>("NPUW_LLM_OPTIMIZE_V_TENSORS", "NO", false),
+ bool_case<::intel_npu::NPUW_LLM_OPTIMIZE_LINCACHE_LAYOUT>("NPUW_LLM_OPTIMIZE_LINCACHE_LAYOUT", "NO", false),
bool_case<::intel_npu::NPUW_LLM_OPTIMIZE_FP8>("NPUW_LLM_OPTIMIZE_FP8", "YES", true),
bool_case<::intel_npu::NPUW_LLM_CACHE_ROPE>("NPUW_LLM_CACHE_ROPE", "NO", false),
enum_case<::intel_npu::NPUW_LLM_PREFILL_MOE_HINT>("NPUW_LLM_PREFILL_MOE_HINT", "HOST_ROUTED", "HOST_ROUTED"),
diff --git a/src/plugins/intel_npu/tests/unit/npuw/pipeline_passes/optimize_lincache_layout_test.cpp b/src/plugins/intel_npu/tests/unit/npuw/pipeline_passes/optimize_lincache_layout_test.cpp
new file mode 100644
index 00000000000..eb62594b80c
--- /dev/null
+++ b/src/plugins/intel_npu/tests/unit/npuw/pipeline_passes/optimize_lincache_layout_test.cpp
@@ -0,0 +1,332 @@
+// Copyright (C) 2018-2026 Intel Corporation
+// SPDX-License-Identifier: Apache-2.0
+//
+
+#include "npuw_transformations/optimize_lincache_layout.hpp"
+
+#include <gtest/gtest.h>
+
+#include <cstdint>
+#include <map>
+#include <numeric>
+#include <regex>
+#include <string>
+#include <string_view>
+#include <vector>
+
+#include "llm_pass_test_fixture.hpp"
+#include "openvino/op/concat.hpp"
+#include "openvino/op/constant.hpp"
+#include "openvino/op/gather.hpp"
+#include "openvino/op/parameter.hpp"
+#include "openvino/op/reduce_sum.hpp"
+#include "openvino/op/result.hpp"
+#include "openvino/op/slice.hpp"
+#include "openvino/op/transpose.hpp"
+#include "openvino/pass/stateful_to_stateless.hpp"
+#include "openvino/runtime/tensor.hpp"
+
+namespace {
+
+using ov::test::npuw::RecordingFactory;
+
+ov::PartialShape swap_last_two(const ov::PartialShape& shape) {
+ ov::PartialShape swapped = shape;
+ std::swap(swapped[1], swapped[2]);
+ return swapped;
+}
+
+// Collects the shapes of all inputs (outputs) whose names contain `needle`, keyed by name.
+template <class Ports>
+std::map<std::string, ov::PartialShape> shapes_by_name(const Ports& ports, std::string_view needle) {
+ std::map<std::string, ov::PartialShape> result;
+ for (const auto& port : ports) {
+ for (const auto& name : port.get_names()) {
+ if (name.find(needle) != std::string::npos) {
+ result[name] = port.get_partial_shape();
+ }
+ }
+ }
+ return result;
+}
+
+class OptimizeLinCacheLayoutPassTest : public ov::test::npuw::LLMPassTestFixture {
+protected:
+ // Stateless models for direct pass testing: conv states become cache_params.{past,present}.conv.N
+ static std::shared_ptr<ov::Model> make_stateless(std::shared_ptr<ov::Model> model) {
+ ov::pass::StatefulToStateless().run_on_model(model);
+ return model;
+ }
+
+ // The pass must swap the last two dims of every conv state pair and leave every other I/O alone.
+ static void expect_conv_states_relaid_out(const std::shared_ptr<ov::Model>& reference,
+ const std::shared_ptr<ov::Model>& optimized) {
+ const auto ref_past = shapes_by_name(reference->inputs(), "cache_params.past.conv");
+ const auto opt_past = shapes_by_name(optimized->inputs(), "cache_params.past.conv");
+ ASSERT_FALSE(ref_past.empty());
+ ASSERT_EQ(ref_past.size(), opt_past.size());
+ for (const auto& [name, shape] : ref_past) {
+ ASSERT_TRUE(opt_past.count(name)) << name;
+ EXPECT_EQ(opt_past.at(name), swap_last_two(shape)) << name;
+ }
+
+ const auto ref_present = shapes_by_name(reference->outputs(), "cache_params.present.conv");
+ const auto opt_present = shapes_by_name(optimized->outputs(), "cache_params.present.conv");
+ ASSERT_EQ(ref_present.size(), ref_past.size());
+ ASSERT_EQ(ref_present.size(), opt_present.size());
+ for (const auto& [name, shape] : ref_present) {
+ ASSERT_TRUE(opt_present.count(name)) << name;
+ EXPECT_EQ(opt_present.at(name), swap_last_two(shape)) << name;
+ // present and past of the same layer must stay byte-copy compatible
+ const auto past_name = std::regex_replace(name, std::regex("present"), "past");
+ EXPECT_EQ(opt_present.at(name), opt_past.at(past_name)) << name;
+ }
+
+ // Everything that is not a conv state keeps its shape (SSM states, KV cache, activations).
+ auto non_conv = [](const auto& ports) {
+ std::map<std::string, ov::PartialShape> result;
+ for (const auto& port : ports) {
+ const auto name = port.get_any_name();
+ if (name.find(".conv.") == std::string::npos) {
+ result[name] = port.get_partial_shape();
+ }
+ }
+ return result;
+ };
+ EXPECT_EQ(non_conv(reference->inputs()), non_conv(optimized->inputs()));
+ EXPECT_EQ(non_conv(reference->outputs()), non_conv(optimized->outputs()));
+ }
+};
+
+// Direct pass test on the GatedDeltaNet hybrid model (conv + SSM states).
+TEST_F(OptimizeLinCacheLayoutPassTest, TransposesConvStatesOnly) {
+ auto reference = make_stateless(ov::test::npuw::build_hybrid_llm_test_model());
+ auto optimized = reference->clone();
+
+ EXPECT_TRUE(ov::npuw::util::OptimizeLinCacheLayout().run_on_model(optimized));
+ ASSERT_NO_THROW(optimized->validate_nodes_and_infer_types());
+
+ expect_conv_states_relaid_out(reference, optimized);
+
+ // One Transpose per Parameter plus one per Result.
+ const auto n_states = shapes_by_name(reference->inputs(), "cache_params.past.conv").size();
+ EXPECT_EQ(count_ops<ov::op::v1::Transpose>(optimized) - count_ops<ov::op::v1::Transpose>(reference), 2u * n_states);
+}
+
+// LFM2-style short-conv states have a different kernel size but the same [batch, channels, kernel] layout.
+TEST_F(OptimizeLinCacheLayoutPassTest, TransposesShortConvStates) {
+ auto reference = make_stateless(ov::test::npuw::build_lfm2_llm_test_model());
+ auto optimized = reference->clone();
+
+ EXPECT_TRUE(ov::npuw::util::OptimizeLinCacheLayout().run_on_model(optimized));
+ expect_conv_states_relaid_out(reference, optimized);
+}
+
+// Models without linear-attention states are left untouched.
+TEST_F(OptimizeLinCacheLayoutPassTest, NoConvStatesIsNoOp) {
+ auto model = make_stateless(ov::test::npuw::build_llm_test_model());
+ const auto n_ops = model->get_ops().size();
+
+ EXPECT_FALSE(ov::npuw::util::OptimizeLinCacheLayout().run_on_model(model));
+ EXPECT_EQ(model->get_ops().size(), n_ops);
+}
+
+// A Result fed straight from a state Parameter shares that Parameter's tensor, so its present name lives
+// on the same tensor as the past name (possibly of another layer). Rewiring must keep every I/O name.
+TEST_F(OptimizeLinCacheLayoutPassTest, PreservesPassThroughStateNames) {
+ for (const bool cross_layer : {false, true}) {
+ SCOPED_TRACE(cross_layer);
+ ov::ParameterVector params;
+ ov::ResultVector results;
+ for (size_t i = 0; i < 2; ++i) {
+ auto param = std::make_shared<ov::op::v0::Parameter>(ov::element::f32, ov::Shape{1, 2, 3});
+ param->output(0).set_names({"cache_params.past.conv." + std::to_string(i),
+ "cache_params.present.conv." + std::to_string(cross_layer ? 1 - i : i)});
+ params.push_back(param);
+ results.push_back(std::make_shared<ov::op::v0::Result>(param));
+ }
+ // The states are also appended to along the kernel axis, as the conv mixers do.
+ for (const auto& param : params) {
+ auto concat = std::make_shared<ov::op::v0::Concat>(ov::OutputVector{param, param}, 2);
+ auto axis = ov::op::v0::Constant::create(ov::element::i64, ov::Shape{1}, {2});
+ results.push_back(
+ std::make_shared<ov::op::v0::Result>(std::make_shared<ov::op::v1::ReduceSum>(concat, axis, false)));
+ }
+ auto reference = std::make_shared<ov::Model>(results, params);
+ auto optimized = reference->clone();
+ ASSERT_TRUE(ov::npuw::util::OptimizeLinCacheLayout().run_on_model(optimized));
+ for (size_t i = 0; i < 2; ++i) {
+ EXPECT_EQ(optimized->input(i).get_names(), reference->input(i).get_names());
+ EXPECT_EQ(optimized->output(i).get_names(), reference->output(i).get_names());
+ EXPECT_EQ(optimized->output(i).get_shape(), (ov::Shape{1, 3, 2}));
+ }
+ }
+}
+
+TEST_F(OptimizeLinCacheLayoutPassTest, UnsupportedPairLeavesAllStatesUnchanged) {
+ for (const bool missing_present : {false, true}) {
+ SCOPED_TRACE(missing_present);
+ auto model = make_stateless(ov::test::npuw::build_lfm2_llm_test_model());
+ const auto port = find_output(model, "cache_params.present.conv.1");
+ ASSERT_TRUE(port.has_value());
+ auto result = model->get_results().at(model->get_result_index(*port));
+ if (missing_present) {
+ model->remove_result(result);
+ } else {
+ const auto names = result->input_value(0).get_names();
+ result->input(0).replace_source_output(
+ ov::op::v0::Constant::create(ov::element::f32, ov::Shape{2, 3}, {0}));
+ result->input_value(0).set_names(names);
+ model->validate_nodes_and_infer_types();
+ }
+ const auto past = shapes_by_name(model->inputs(), "cache_params.past.conv");
+ const auto present = shapes_by_name(model->outputs(), "cache_params.present.conv");
+ const auto n_ops = model->get_ops().size();
+ EXPECT_FALSE(ov::npuw::util::OptimizeLinCacheLayout().run_on_model(model));
+ EXPECT_EQ(model->get_ops().size(), n_ops);
+ EXPECT_EQ(shapes_by_name(model->inputs(), "cache_params.past.conv"), past);
+ EXPECT_EQ(shapes_by_name(model->outputs(), "cache_params.present.conv"), present);
+ }
+}
+
+// Evaluable single-state model mirroring the conv state consumer seen by the pass after
+// StatefulToStateless: state -> Concat -> Slice.
+// The state is [1, 2 channels, 3 kernel]; with `channels_last` it is stored as [1, 3, 2] and tokens are
+// appended along axis 1 instead. `negative_axis` spells the concatenation axis as -1, and `gather_between`
+// inserts a Gather between the state and the Concat.
+std::shared_ptr<ov::Model> make_cache_step_model(int64_t token_count,
+ bool channels_last = false,
+ bool negative_axis = false,
+ bool gather_between = false) {
+ const int64_t time_axis = channels_last ? 1 : 2;
+ auto past = std::make_shared<ov::op::v0::Parameter>(ov::element::f32,
+ channels_last ? ov::Shape{1, 3, 2} : ov::Shape{1, 2, 3});
+ past->output(0).set_names({"cache_params.past.conv.0"});
+ auto tokens = std::make_shared<ov::op::v0::Parameter>(
+ ov::element::f32,
+ channels_last ? ov::PartialShape{1, token_count, 2} : ov::PartialShape{1, 2, token_count});
+ tokens->output(0).set_names({"tokens"});
+ ov::Output<ov::Node> state = past;
+ if (gather_between) {
+ state = std::make_shared<ov::op::v8::Gather>(past,
+ ov::op::v0::Constant::create(ov::element::i32, ov::Shape{1}, {0}),
+ ov::op::v0::Constant::create(ov::element::i64, ov::Shape{}, {0}));
+ }
+ auto concat = std::make_shared<ov::op::v0::Concat>(ov::OutputVector{state, tokens}, negative_axis ? -1 : time_axis);
+ auto axis = ov::op::v0::Constant::create(ov::element::i64, ov::Shape{1}, {time_axis});
+ auto present = std::make_shared<ov::op::v8::Slice>(
+ concat,
+ ov::op::v0::Constant::create(ov::element::i64, ov::Shape{1}, {token_count}),
+ ov::op::v0::Constant::create(ov::element::i64, ov::Shape{1}, {token_count + 3}),
+ ov::op::v0::Constant::create(ov::element::i64, ov::Shape{1}, {1}),
+ axis);
+ present->output(0).set_names({"cache_params.present.conv.0"});
+ auto activation = std::make_shared<ov::op::v1::ReduceSum>(concat, axis, false);
+ activation->output(0).set_names({"activation"});
+ return std::make_shared<ov::Model>(ov::OutputVector{activation, present}, ov::ParameterVector{past, tokens});
+}
+
+// A state that is already stored channels-innermost must not be transposed back to the slow layout.
+TEST_F(OptimizeLinCacheLayoutPassTest, LeavesChannelsLastStateUnchanged) {
+ auto model = make_cache_step_model(1, /*channels_last=*/true);
+ const auto n_ops = model->get_ops().size();
+ EXPECT_FALSE(ov::npuw::util::OptimizeLinCacheLayout().run_on_model(model));
+ EXPECT_EQ(model->get_ops().size(), n_ops);
+ EXPECT_EQ(model->input(0).get_partial_shape(), (ov::PartialShape{1, 3, 2}));
+ EXPECT_EQ(model->output(1).get_partial_shape(), (ov::PartialShape{1, 3, 2}));
+}
+
+// Exported models spell the concatenation axis as -1.
+TEST_F(OptimizeLinCacheLayoutPassTest, AcceptsNegativeConcatAxis) {
+ auto model = make_cache_step_model(1, /*channels_last=*/false, /*negative_axis=*/true);
+ EXPECT_TRUE(ov::npuw::util::OptimizeLinCacheLayout().run_on_model(model));
+ EXPECT_EQ(model->input(0).get_partial_shape(), (ov::PartialShape{1, 3, 2}));
+ EXPECT_EQ(model->output(1).get_partial_shape(), (ov::PartialShape{1, 3, 2}));
+}
+
+// Only the direct Parameter -> Concat consumer is recognized; a state behind any other op is left alone.
+TEST_F(OptimizeLinCacheLayoutPassTest, SkipsStateBehindOtherOp) {
+ auto model = make_cache_step_model(1, /*channels_last=*/false, /*negative_axis=*/false, /*gather_between=*/true);
+ const auto n_ops = model->get_ops().size();
+ EXPECT_FALSE(ov::npuw::util::OptimizeLinCacheLayout().run_on_model(model));
+ EXPECT_EQ(model->get_ops().size(), n_ops);
+ EXPECT_EQ(model->input(0).get_partial_shape(), (ov::PartialShape{1, 2, 3}));
+}
+
+TEST_F(OptimizeLinCacheLayoutPassTest, PreservesNonzeroStateAcrossPrefillAndDecode) {
+ std::vector<std::shared_ptr<ov::Model>> references{make_cache_step_model(2),
+ make_cache_step_model(1),
+ make_cache_step_model(1)};
+ std::vector<std::shared_ptr<ov::Model>> optimized;
+ for (const auto& reference : references) {
+ optimized.push_back(reference->clone());
+ ASSERT_TRUE(ov::npuw::util::OptimizeLinCacheLayout().run_on_model(optimized.back()));
+ }
+ ov::Tensor ref_state(ov::element::f32, {1, 2, 3});
+ ov::Tensor opt_state(ov::element::f32, {1, 3, 2});
+ std::iota(ref_state.data<float>(), ref_state.data<float>() + ref_state.get_size(), 1.0f);
+ for (size_t c = 0; c < 2; ++c) {
+ for (size_t k = 0; k < 3; ++k) {
+ opt_state.data<float>()[k * 2 + c] = ref_state.data<float>()[c * 3 + k];
+ }
+ }
+ // Two prefill chunks, then decode with a switch to a separate generate model.
+ size_t step = 0;
+ for (const size_t variant : {0, 0, 1, 1, 2, 2}) {
+ SCOPED_TRACE(step);
+ const auto& reference = references.at(variant);
+ const auto& transformed = optimized.at(variant);
+ ov::Tensor tokens(ov::element::f32, reference->input(1).get_shape());
+ std::iota(tokens.data<float>(), tokens.data<float>() + tokens.get_size(), 10.0f * (++step));
+ ov::TensorVector ref_outputs, opt_outputs;
+ for (size_t i = 0; i < reference->outputs().size(); ++i) {
+ ref_outputs.emplace_back(ov::element::f32, reference->output(i).get_shape());
+ opt_outputs.emplace_back(ov::element::f32, transformed->output(i).get_shape());
+ }
+ ASSERT_TRUE(reference->evaluate(ref_outputs, ov::TensorVector{ref_state, tokens}));
+ ASSERT_TRUE(transformed->evaluate(opt_outputs, ov::TensorVector{opt_state, tokens}));
+ for (size_t i = 0; i < ref_outputs[0].get_size(); ++i) {
+ EXPECT_FLOAT_EQ(ref_outputs[0].data<float>()[i], opt_outputs[0].data<float>()[i]);
+ }
+ for (size_t c = 0; c < 2; ++c) {
+ for (size_t k = 0; k < 3; ++k) {
+ EXPECT_FLOAT_EQ(ref_outputs[1].data<float>()[c * 3 + k], opt_outputs[1].data<float>()[k * 2 + c]);
+ }
+ }
+ ref_outputs[1].copy_to(ref_state);
+ opt_outputs[1].copy_to(opt_state);
+ }
+}
+
+// Pipeline-level: with the option on, the pass runs once on the shared model before prefill and
+// generate are cloned from it, so both sub-models get the new layout and the byte-wise present -> past
+// copy between them sees identical conv state shapes. With the option off nothing changes.
+TEST_F(OptimizeLinCacheLayoutPassTest, PrefillAndGenerateShareNewConvStateLayout) {
+ RecordingFactory recorder_off;
+ RecordingFactory recorder_on;
+ std::unique_ptr<ov::npuw::LLMCompiledModel> compiled_off;
+ std::unique_ptr<ov::npuw::LLMCompiledModel> compiled_on;
+ ASSERT_NO_THROW(compiled_off = create_compiled_model(ov::test::npuw::build_lfm2_llm_test_model(),
+ {{"NPUW_LLM_OPTIMIZE_LINCACHE_LAYOUT", "NO"}},
+ recorder_off));
+ ASSERT_NO_THROW(compiled_on = create_compiled_model(ov::test::npuw::build_lfm2_llm_test_model(),
+ {{"NPUW_LLM_OPTIMIZE_LINCACHE_LAYOUT", "YES"}},
+ recorder_on));
+ ASSERT_NE(compiled_off, nullptr);
+ ASSERT_NE(compiled_on, nullptr);
+
+ for (const std::string fragment : {"_prefill", "_kv"}) {
+ SCOPED_TRACE(fragment);
+ expect_conv_states_relaid_out(require_sub_model_containing(recorder_off, fragment).model,
+ require_sub_model_containing(recorder_on, fragment).model);
+ }
+
+ const auto& prefill = require_sub_model_containing(recorder_on, "_prefill").model;
+ const auto& generate = require_sub_model_containing(recorder_on, "_kv").model;
+ EXPECT_EQ(shapes_by_name(prefill->inputs(), "cache_params.past.conv"),
+ shapes_by_name(generate->inputs(), "cache_params.past.conv"));
+ EXPECT_EQ(shapes_by_name(prefill->outputs(), "cache_params.present.conv"),
+ shapes_by_name(generate->outputs(), "cache_params.present.conv"));
+}
+
+} // namespace