Skip to content

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

[Transformations] Fixed PagedGatedDeltaNetFusion output shape (#38488)

Mikhail Ryzhovcafc381613c6
diff --git a/.github/workflows/job_pytorch_models_tests.yml b/.github/workflows/job_pytorch_models_tests.yml
index db922c074d2..d99afb5dcdd 100644
--- a/.github/workflows/job_pytorch_models_tests.yml
+++ b/.github/workflows/job_pytorch_models_tests.yml
@@ -226,6 +226,15 @@ jobs:
env:
TEST_DEVICE: CPU
+ - name: GatedDeltaNet Fusion Test
+ if: ${{ inputs.model_scope == 'precommit' }}
+ run: |
+ export PYTHONPATH=${MODEL_HUB_TESTS_INSTALL_DIR}:$PYTHONPATH
+ python3 -m pip install -r ${MODEL_HUB_TESTS_INSTALL_DIR}/pytorch/envs/gated_delta_net.txt
+ python3 -m pytest ${MODEL_HUB_TESTS_INSTALL_DIR}/transformation_tests/test_gated_delta_net_transformation.py -m precommit --html=${INSTALL_TEST_DIR}/TEST-torch_gated_delta_net_tests.html --self-contained-html -vvv -s --tb=short
+ env:
+ TEST_DEVICE: CPU
+
- name: RoPE Test
if: ${{ inputs.model_scope == 'precommit' }}
run: |
diff --git a/src/common/transformations/src/transformations/paged_attention/paged_gated_delta_net_fusion.cpp b/src/common/transformations/src/transformations/paged_attention/paged_gated_delta_net_fusion.cpp
index 00738a193b0..08dfd811f88 100644
--- a/src/common/transformations/src/transformations/paged_attention/paged_gated_delta_net_fusion.cpp
+++ b/src/common/transformations/src/transformations/paged_attention/paged_gated_delta_net_fusion.cpp
@@ -140,19 +140,14 @@ PagedGatedDeltaNetFusion::PagedGatedDeltaNetFusion(ov::pass::paged_attention::Pa
gdn_node->get_k_l2_norm_eps());
paged_gdn->set_friendly_name(gdn_node->get_friendly_name() + "/PagedGatedDeltaNet");
- const auto query_shape = std::make_shared<ov::op::v3::ShapeOf>(pm.at(query), ov::element::i64);
+
+ // PagedGatedDeltaNet output is [B*L, v_num_heads, value_head_dim]; restore the matched
+ // GatedDeltaNet output layout [B, L, v_num_heads, value_head_dim], which equals the value shape.
const auto value_shape = std::make_shared<ov::op::v3::ShapeOf>(pm.at(value), ov::element::i64);
- const auto axis_0 = v0::Constant::create(ov::element::i64, ov::Shape{}, {0});
- const auto idx_q = v0::Constant::create(ov::element::i64, ov::Shape{3}, {0, 1, 2});
- const auto idx_v = v0::Constant::create(ov::element::i64, ov::Shape{1}, {3});
- const auto q_dims = std::make_shared<ov::op::v8::Gather>(query_shape, idx_q, axis_0);
- const auto v_dim = std::make_shared<ov::op::v8::Gather>(value_shape, idx_v, axis_0);
- const auto out0_shape = std::make_shared<v0::Concat>(ov::OutputVector{q_dims, v_dim}, 0);
- const auto paged_gdn_out = std::make_shared<ov::op::v1::Reshape>(paged_gdn, out0_shape, false);
+ const auto paged_gdn_out = std::make_shared<ov::op::v1::Reshape>(paged_gdn, value_shape, false);
paged_gdn_out->set_friendly_name(gdn_node->get_friendly_name());
- ov::copy_runtime_info(gdn_node,
- {paged_gdn, query_shape, value_shape, q_dims, v_dim, out0_shape, paged_gdn_out});
+ ov::copy_runtime_info(gdn_node, {paged_gdn, value_shape, paged_gdn_out});
// Disconnect GDN state output consumers; cleanup is driven by ReadValue variable ids.
for (const auto& state_consumer : state_consumers) {
diff --git a/src/common/transformations/tests/common_optimizations/paged_gated_delta_net_fusion.cpp b/src/common/transformations/tests/common_optimizations/paged_gated_delta_net_fusion.cpp
index 55e576d9b70..38455a512f5 100644
--- a/src/common/transformations/tests/common_optimizations/paged_gated_delta_net_fusion.cpp
+++ b/src/common/transformations/tests/common_optimizations/paged_gated_delta_net_fusion.cpp
@@ -108,7 +108,7 @@ std::shared_ptr<ov::Model> build_fusable_model_with_gathered_state() {
return std::make_shared<ov::Model>(ResultVector{out, present_state}, params);
}
-// Mirrors flatten_blhd_to_thd from paged_gated_delta_net_fusion.cpp.
+// Mirrors flatten_batch_length(input, {2, 3}) from paged_gated_delta_net_fusion.cpp.
ov::Output<ov::Node> ref_flatten_blhd_to_thd(const ov::Output<ov::Node>& input) {
const auto shape_of = std::make_shared<v3::ShapeOf>(input, element::i64);
const auto idx_hd = v0::Constant::create(element::i64, Shape{2}, {2, 3});
@@ -119,7 +119,7 @@ ov::Output<ov::Node> ref_flatten_blhd_to_thd(const ov::Output<ov::Node>& input)
return std::make_shared<v1::Reshape>(input, flat_shape, false);
}
-// Mirrors flatten_blh_to_th from paged_gated_delta_net_fusion.cpp.
+// Mirrors flatten_batch_length(input, {2}) from paged_gated_delta_net_fusion.cpp.
ov::Output<ov::Node> ref_flatten_blh_to_th(const ov::Output<ov::Node>& input) {
const auto shape_of = std::make_shared<v3::ShapeOf>(input, element::i64);
const auto idx_h = v0::Constant::create(element::i64, Shape{1}, {2});
@@ -163,15 +163,8 @@ ov::Output<ov::Node> build_paged_gdn_block(const std::shared_ptr<v0::Parameter>&
cache_interval->output(0));
paged_gdn->set_friendly_name(gdn_friendly_name + "/PagedGatedDeltaNet");
- const auto q_shape = std::make_shared<v3::ShapeOf>(query, element::i64);
const auto v_shape = std::make_shared<v3::ShapeOf>(value, element::i64);
- const auto axis_0 = v0::Constant::create(element::i64, Shape{}, {0});
- const auto idx_q = v0::Constant::create(element::i64, Shape{3}, {0, 1, 2});
- const auto idx_v = v0::Constant::create(element::i64, Shape{1}, {3});
- const auto q_dims = std::make_shared<v8::Gather>(q_shape, idx_q, axis_0);
- const auto v_dim = std::make_shared<v8::Gather>(v_shape, idx_v, axis_0);
- const auto out_shape = std::make_shared<v0::Concat>(OutputVector{q_dims, v_dim}, 0);
- auto paged_gdn_out = std::make_shared<v1::Reshape>(paged_gdn, out_shape, false);
+ auto paged_gdn_out = std::make_shared<v1::Reshape>(paged_gdn, v_shape, false);
paged_gdn_out->set_friendly_name(gdn_friendly_name);
return paged_gdn_out->output(0);
}
@@ -351,10 +344,85 @@ std::shared_ptr<ov::Model> build_reference_fused_model_with_gathered_state() {
return std::make_shared<ov::Model>(ResultVector{out, present_state}, params);
}
+// Grouped-query variant: 2 query/key heads shared by 4 value heads.
+std::shared_ptr<ov::Model> build_fusable_gqa_model() {
+ auto query = ov::test::utils::make_param(element::f32, Shape{2, 3, 2, 8}, "query");
+ auto key = ov::test::utils::make_param(element::f32, Shape{2, 3, 2, 8}, "key");
+ auto value = ov::test::utils::make_param(element::f32, Shape{2, 3, 4, 6}, "value");
+
+ auto recurrent_state = ov::test::utils::make_param(element::f32, Shape{2, 4, 8, 6}, "past_recurrent_state");
+ recurrent_state->get_output_tensor(0).set_names({"cache_params.past.recurrent_state.0"});
+ auto read_value = std::make_shared<v3::ReadValue>(recurrent_state->output(0), "cache_param_0");
+
+ auto gate = ov::test::utils::make_param(element::f32, Shape{2, 3, 4}, "gate");
+ auto beta = ov::test::utils::make_param(element::f32, Shape{2, 3, 4}, "beta");
+
+ auto gdn = std::make_shared<internal::GatedDeltaNet>(query, key, value, read_value, gate, beta);
+
+ auto out = std::make_shared<v0::Result>(gdn->output(0));
+ auto present_state = std::make_shared<v0::Result>(gdn->output(1));
+ present_state->get_output_tensor(0).set_names({"cache_params.present.recurrent_state.0"});
+
+ ParameterVector params{query, key, value, recurrent_state, gate, beta};
+ return std::make_shared<ov::Model>(ResultVector{out, present_state}, params);
+}
+
+// Reference graph for build_fusable_gqa_model(): the restored output keeps the value head count.
+std::shared_ptr<ov::Model> build_reference_fused_gqa_model() {
+ auto query = ov::test::utils::make_param(element::f32, Shape{2, 3, 2, 8}, "query");
+ auto key = ov::test::utils::make_param(element::f32, Shape{2, 3, 2, 8}, "key");
+ auto value = ov::test::utils::make_param(element::f32, Shape{2, 3, 4, 6}, "value");
+ auto recurrent_state = ov::test::utils::make_param(element::f32, Shape{2, 4, 8, 6}, "past_recurrent_state");
+ recurrent_state->get_output_tensor(0).set_names({"cache_params.past.recurrent_state.0"});
+ auto gate = ov::test::utils::make_param(element::f32, Shape{2, 3, 4}, "gate");
+ auto beta = ov::test::utils::make_param(element::f32, Shape{2, 3, 4}, "beta");
+
+ const auto read_value = std::make_shared<v3::ReadValue>(recurrent_state->output(0), "cache_param_0");
+
+ auto subseq_begins = ov::test::utils::make_param(element::i32, PartialShape{-1}, "subsequence_begins");
+ auto block_indices = ov::test::utils::make_param(element::i32, PartialShape{-1}, "la.block_indices");
+ auto block_indices_begins = ov::test::utils::make_param(element::i32, PartialShape{-1}, "la.block_indices_begins");
+ auto past_lens = ov::test::utils::make_param(element::i32, PartialShape{-1}, "la.past_lens");
+ auto cache_interval = ov::test::utils::make_param(element::i32, PartialShape{-1}, "la.cache_interval");
+ auto state_table = ov::test::utils::make_param(element::dynamic,
+ PartialShape{Dimension::dynamic(), 4, 6, 8},
+ "gated_delta_state_table.0");
+
+ const auto paged_gdn_out = build_paged_gdn_block(query,
+ key,
+ value,
+ gate,
+ beta,
+ state_table,
+ subseq_begins,
+ block_indices,
+ block_indices_begins,
+ past_lens,
+ cache_interval,
+ "GatedDeltaNet");
+
+ auto out = std::make_shared<v0::Result>(paged_gdn_out);
+ auto present_state = std::make_shared<v0::Result>(read_value->output(0));
+ present_state->get_output_tensor(0).set_names({"cache_params.present.recurrent_state.0"});
+
+ ParameterVector params{query,
+ key,
+ value,
+ recurrent_state,
+ gate,
+ beta,
+ subseq_begins,
+ block_indices,
+ block_indices_begins,
+ past_lens,
+ cache_interval,
+ state_table};
+ return std::make_shared<ov::Model>(ResultVector{out, present_state}, params);
+}
+
} // namespace
class PagedGatedDeltaNetFusionTest : public ::TransformationTestsF {};
-
void run_paged_gated_delta_net_fusion(const std::shared_ptr<ov::Model>& model) {
ov::pass::paged_attention::PaParams pa_params{model->get_parameters()};
std::unordered_set<std::string> var_ids_to_remove;
@@ -389,3 +457,15 @@ TEST_F(PagedGatedDeltaNetFusionTest, FusesWhenStateInputIsGatherFromReadValue) {
model_ref = build_reference_fused_model_with_gathered_state();
run_paged_gated_delta_net_fusion(model);
}
+
+TEST_F(PagedGatedDeltaNetFusionTest, RestoredOutputKeepsValueHeadsForGroupedQueryAttention) {
+ model = build_fusable_gqa_model();
+ model_ref = build_reference_fused_gqa_model();
+ run_paged_gated_delta_net_fusion(model);
+
+ for (const auto& result : model->get_results()) {
+ if (result->get_output_tensor(0).get_names().count("cache_params.present.recurrent_state.0") == 0) {
+ EXPECT_EQ(result->get_input_partial_shape(0), (PartialShape{2, 3, 4, 6}));
+ }
+ }
+}
diff --git a/tests/model_hub_tests/pytorch/envs/gated_delta_net.txt b/tests/model_hub_tests/pytorch/envs/gated_delta_net.txt
new file mode 100644
index 00000000000..139dc3a50aa
--- /dev/null
+++ b/tests/model_hub_tests/pytorch/envs/gated_delta_net.txt
@@ -0,0 +1,5 @@
+# GatedDeltaNet -> PagedGatedDeltaNet fusion test environment overrides.
+# Qwen3-Next linear attention requires transformers>=4.57 and optimum-intel>=2.0.
+optimum-intel==2.2.0
+transformers==4.57.6
+huggingface-hub>=0.30.0,<1.0
diff --git a/tests/model_hub_tests/transformation_tests/models/hf-tiny-random-gdn-models-precommit b/tests/model_hub_tests/transformation_tests/models/hf-tiny-random-gdn-models-precommit
new file mode 100644
index 00000000000..f531c747be8
--- /dev/null
+++ b/tests/model_hub_tests/transformation_tests/models/hf-tiny-random-gdn-models-precommit
@@ -0,0 +1 @@
+optimum-intel-internal-testing/tiny-random-qwen3-next,https://huggingface.co/optimum-intel-internal-testing/tiny-random-qwen3-next
diff --git a/tests/model_hub_tests/transformation_tests/test_gated_delta_net_transformation.py b/tests/model_hub_tests/transformation_tests/test_gated_delta_net_transformation.py
new file mode 100644
index 00000000000..0b1664bfa1d
--- /dev/null
+++ b/tests/model_hub_tests/transformation_tests/test_gated_delta_net_transformation.py
@@ -0,0 +1,187 @@
+# Copyright (C) 2018-2026 Intel Corporation
+# SPDX-License-Identifier: Apache-2.0
+
+from huggingface_hub import snapshot_download
+from openvino._offline_transformations import paged_attention_transformation
+from openvino._pyopenvino import Type as OVType
+from optimum.intel import OVModelForCausalLM
+from transformers import AutoConfig, AutoModelForCausalLM
+import openvino as ov
+from models_hub_common.utils import retry
+import models_hub_common.utils as utils
+import pytest
+import os
+import platform
+
+# Number of linear-attention layers each model is expected to fuse into PagedGatedDeltaNet.
+ref_paged_gated_delta_net_count = {
+ "optimum-intel-internal-testing/tiny-random-qwen3-next": 3,
+}
+
+STATE_TABLE_PREFIX = "gated_delta_state_table."
+
+# Runtime inputs 6..10 of PagedGatedDeltaNet, in operation order.
+RUNTIME_INPUT_NAMES = (
+ "subsequence_begins",
+ "la.block_indices",
+ "la.block_indices_begins",
+ "la.past_lens",
+ "la.cache_interval",
+)
+
+
+def get_tensor_name(output: ov.Output) -> str:
+ names = list(output.get_names())
+ assert len(names) == 1, f"Expected a single tensor name, got {names}"
+ return names[0]
+
+
+def verify_paged_gated_delta_net(node, model_id: str):
+ """
+ Check a fused PagedGatedDeltaNet against the operation specification.
+
+ query/key are [batch_size_in_tokens, num_heads, key_head_dim], value is
+ [batch_size_in_tokens, v_num_heads, value_head_dim], the recurrent state table is
+ [num_blocks, v_num_heads, value_head_dim, key_head_dim] and the output repeats the
+ value shape. Grouped-query attention allows v_num_heads to be a multiple of num_heads,
+ so the value-derived dimensions must not be taken from query.
+ """
+ query_shape = node.get_input_partial_shape(0)
+ key_shape = node.get_input_partial_shape(1)
+ value_shape = node.get_input_partial_shape(2)
+ state_shape = node.get_input_partial_shape(3)
+
+ for port, shape in ((0, query_shape), (1, key_shape), (2, value_shape)):
+ assert shape.rank.get_length() == 3, \
+ f"{model_id}: input {port} of {node.get_friendly_name()} must be 3D, got {shape}"
+
+ num_heads = query_shape[1].get_length()
+ key_head_dim = key_shape[2].get_length()
+ v_num_heads = value_shape[1].get_length()
+ value_head_dim = value_shape[2].get_length()
+ assert v_num_heads % num_heads == 0, \
+ f"{model_id}: v_num_heads {v_num_heads} is not a multiple of num_heads {num_heads}"
+
+ state_table = node.input_value(3).get_node()
+ assert state_table.get_type_name() == "Parameter", \
+ f"{model_id}: recurrent_state_table must be a Parameter, got {state_table.get_type_name()}"
+ state_table_name = get_tensor_name(node.input_value(3))
+ assert state_table_name.startswith(STATE_TABLE_PREFIX), \
+ f"{model_id}: unexpected recurrent_state_table name '{state_table_name}'"
+ assert state_shape.rank.get_length() == 4 and state_shape[0].is_dynamic, state_shape
+ assert [state_shape[i].get_length() for i in (1, 2, 3)] == [v_num_heads, value_head_dim, key_head_dim], \
+ f"{model_id}: recurrent_state_table {state_shape} does not match " \
+ f"[num_blocks, {v_num_heads}, {value_head_dim}, {key_head_dim}]"
+
+ for port, name in enumerate(RUNTIME_INPUT_NAMES, start=6):
+ assert get_tensor_name(node.input_value(port)) == name, \
+ f"{model_id}: input {port} of {node.get_friendly_name()} is " \
+ f"'{get_tensor_name(node.input_value(port))}', expected '{name}'"
+ assert node.get_input_element_type(port) == OVType.i32, \
+ f"{model_id}: input {port} of {node.get_friendly_name()} must be i32"
+
+ assert node.get_output_partial_shape(0) == value_shape, \
+ f"{model_id}: output {node.get_output_partial_shape(0)} must repeat the value shape {value_shape}"
+
+ # The fusion restores the original GatedDeltaNet layout [batch, seq_len, v_num_heads, value_head_dim].
+ consumers = list(node.output(0).get_target_inputs())
+ assert len(consumers) == 1, f"{model_id}: expected a single consumer of {node.get_friendly_name()}"
+ restored = consumers[0].get_node()
+ assert restored.get_type_name() == "Reshape", \
+ f"{model_id}: expected the output to be reshaped back, got {restored.get_type_name()}"
+ restored_shape = restored.get_output_partial_shape(0)
+ assert restored_shape.rank.get_length() == 4, restored_shape
+ assert [restored_shape[2].get_length(), restored_shape[3].get_length()] == [v_num_heads, value_head_dim], \
+ f"{model_id}: restored output {restored_shape} must keep [{v_num_heads}, {value_head_dim}]"
+
+ return state_table_name
+
+
+def apply_transformation_and_verify(ov_model: ov.Model, model_id: str, ie_device: str, expected_count: int = None):
+ if expected_count is None:
+ expected_count = ref_paged_gated_delta_net_count[model_id]
+
+ # SDPAToPagedAttention first folds the exported linear-attention subgraphs into
+ # GatedDeltaNet, then PagedGatedDeltaNetFusion rewrites them for paged execution.
+ paged_attention_transformation(ov_model, False, False, False, False, False, False, False)
+
+ assert not any(op.get_type_name() == "GatedDeltaNet" for op in ov_model.get_ordered_ops()), \
+ f"{model_id}: GatedDeltaNet is left unfused"
+
+ state_table_names = [verify_paged_gated_delta_net(op, model_id)
+ for op in ov_model.get_ordered_ops() if op.get_type_name() == "PagedGatedDeltaNet"]
+ assert len(state_table_names) == expected_count, \
+ f"{model_id}: expected {expected_count} PagedGatedDeltaNet operations, got {len(state_table_names)}"
+ assert len(set(state_table_names)) == expected_count, \
+ f"{model_id}: recurrent state tables are shared between layers: {state_table_names}"
+
+ model_input_names = {name for model_input in ov_model.inputs for name in model_input.get_names()}
+ for name in (*RUNTIME_INPUT_NAMES, *state_table_names):
+ assert name in model_input_names, f"{model_id}: '{name}' is not exposed as a model input"
+
+ ov.Core().compile_model(ov_model, ie_device)
+
+
+@retry(3, exceptions=(OSError,), delay=1)
+def run_gated_delta_net_pa(model_id, ie_device):
+ model_cached = snapshot_download(model_id) # required to avoid HF rate limits
+ model = OVModelForCausalLM.from_pretrained(model_cached, export=True, trust_remote_code=True, compile=False)
+ apply_transformation_and_verify(model.model, model_id, ie_device)
+
+
+@retry(3, exceptions=(OSError,), delay=1)
+def run_gated_delta_net_pa_grouped_query(tmp_path, model_id, num_groups, ie_device):
+ """
+ Exercise grouped-query linear attention, where v_num_heads is a multiple of num_heads.
+
+ The tiny reference model uses one value head per key head, so the grouped case is only
+ reachable through a synthetic config with a single linear-attention layer.
+ """
+ config = AutoConfig.from_pretrained(snapshot_download(model_id))
+ config.linear_num_value_heads = config.linear_num_key_heads * num_groups
+ config.layer_types = ["linear_attention", "full_attention"]
+ config.num_hidden_layers = len(config.layer_types)
+
+ model_path = os.path.join(tmp_path, f"synthetic_gqa_{num_groups}")
+ AutoModelForCausalLM.from_config(config).save_pretrained(model_path)
+
+ model = OVModelForCausalLM.from_pretrained(model_path, export=True, trust_remote_code=True, compile=False)
+ apply_transformation_and_verify(model.model, model_id, ie_device, expected_count=1)
+
+
+GDN_PRECOMMIT_TEST_CASES = utils.get_models_list(
+ os.path.join(os.path.dirname(__file__), "models", "hf-tiny-random-gdn-models-precommit")
+)
+
+
[email protected]("model_info_tuple", GDN_PRECOMMIT_TEST_CASES, ids=lambda entry: entry[0])
+def test_gated_delta_net_pa_precommit(model_info_tuple, ie_device):
+ model_name, model_link, mark, reason = model_info_tuple
+ assert mark is None or mark == 'skip' or mark == 'xfail', \
+ "Incorrect test case: {}, {}".format(model_name, model_link)
+ if platform.machine() in ['arm', 'armv7l', 'aarch64', 'arm64', 'ARM64']:
+ pytest.skip("PagedAttention tests are not enabled on ARM")
+ if mark == 'skip':
+ pytest.skip(reason)
+ elif mark == 'xfail':
+ pytest.xfail(reason)
+
+ run_gated_delta_net_pa(model_name, ie_device)
+
+
[email protected]("model_info_tuple", GDN_PRECOMMIT_TEST_CASES, ids=lambda entry: entry[0])
[email protected]("num_groups", [2, 4])
+def test_gated_delta_net_pa_grouped_query_precommit(tmp_path, model_info_tuple, num_groups, ie_device):
+ model_name, model_link, mark, reason = model_info_tuple
+ assert mark is None or mark == 'skip' or mark == 'xfail', \
+ "Incorrect test case: {}, {}".format(model_name, model_link)
+ if platform.machine() in ['arm', 'armv7l', 'aarch64', 'arm64', 'ARM64']:
+ pytest.skip("PagedAttention tests are not enabled on ARM")
+ if mark == 'skip':
+ pytest.skip(reason)
+ elif mark == 'xfail':
+ pytest.xfail(reason)
+
+ run_gated_delta_net_pa_grouped_query(tmp_path, model_name, num_groups, ie_device)