Skip to content

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

Fix ComplexTypeMark handling for pattern from QwenImage (#33599)

Evgeny Kotovd01919d27f22
diff --git a/src/frontends/pytorch/src/frontend.cpp b/src/frontends/pytorch/src/frontend.cpp
index b750c83602e..a2dd3ef79ba 100644
--- a/src/frontends/pytorch/src/frontend.cpp
+++ b/src/frontends/pytorch/src/frontend.cpp
@@ -301,6 +301,9 @@ void FrontEnd::normalize(const std::shared_ptr<ov::Model>& model) const {
manager.register_pass<ov::frontend::pytorch::pass::ReversepropResolver>();
manager.register_pass<ov::frontend::pytorch::pass::MovePackThroughLstm>();
manager.register_pass<ov::frontend::pytorch::pass::RemovePackingOps>();
+ // PrimListUnpackReplacer must run before validation to handle chunk+ListUnpack patterns
+ // that may exist alongside operations with shape inference issues
+ manager.register_pass<ov::frontend::pytorch::pass::PrimListUnpackReplacer>();
bool is_changed = manager.run_passes(model);
// make validation after previously non-validated passes
@@ -310,7 +313,6 @@ void FrontEnd::normalize(const std::shared_ptr<ov::Model>& model) const {
ov::pass::Manager manager("Frontend:Pytorch:normalize");
manager.register_pass<ov::pass::UnrollIf>();
- manager.register_pass<ov::frontend::pytorch::pass::PrimListUnpackReplacer>();
manager.register_pass<ov::frontend::pytorch::pass::AtenGetItemReplacer>();
manager.register_pass<ov::frontend::pytorch::pass::ListConstructReplacer>();
// TODO: remove AtenIndexToSelect when problem with dynamic input rank is gone.
diff --git a/src/frontends/pytorch/src/node_context.cpp b/src/frontends/pytorch/src/node_context.cpp
index b9ad278acbc..284efea0785 100644
--- a/src/frontends/pytorch/src/node_context.cpp
+++ b/src/frontends/pytorch/src/node_context.cpp
@@ -14,6 +14,7 @@
#include "openvino/util/log.hpp"
#include "pt_framework_node.hpp"
#include "translate_session.hpp"
+#include "utils.hpp"
namespace ov {
namespace frontend {
@@ -45,7 +46,7 @@ OutputVector NodeContext::as_constant() const {
} else {
auto c_outs = m_decoder->as_constant();
FRONT_END_OP_CONVERSION_CHECK(c_outs.size() == 1, "Constant must have exactly one output.");
- if (dtype.is<type::Tensor>() && dtype.as<type::Tensor>().element_type.is<type::Complex>()) {
+ if (simplified_type_interpret(dtype).is<type::Complex>()) {
// Add complex mark to complex constant
c_outs = {mark_node(std::make_shared<ComplexTypeMark>(c_outs[0], c_outs[0].get_element_type()))};
}
diff --git a/src/frontends/pytorch/src/op/get_attr.cpp b/src/frontends/pytorch/src/op/get_attr.cpp
index e505d2ffb41..dd719f640c6 100644
--- a/src/frontends/pytorch/src/op/get_attr.cpp
+++ b/src/frontends/pytorch/src/op/get_attr.cpp
@@ -24,7 +24,7 @@ OutputVector translate_get_attr(const NodeContext& context) {
res[0].add_names({node->get_friendly_name()});
}
auto dtype = decoder->get_output_type(0);
- if (dtype.is<type::Complex>()) {
+ if (simplified_type_interpret(dtype).is<type::Complex>()) {
// Add complex mark to complex constant
res = {context.mark_node(std::make_shared<ComplexTypeMark>(res[0], res[0].get_element_type()))};
}
diff --git a/src/frontends/pytorch/src/op/list_unpack.cpp b/src/frontends/pytorch/src/op/list_unpack.cpp
index 436bcc960db..876d67b1516 100644
--- a/src/frontends/pytorch/src/op/list_unpack.cpp
+++ b/src/frontends/pytorch/src/op/list_unpack.cpp
@@ -4,6 +4,7 @@
#include "openvino/frontend/complex_type_mark.hpp"
#include "openvino/frontend/pytorch/node_context.hpp"
+#include "pt_framework_node.hpp"
#include "utils.hpp"
#include "utils_quantize.hpp"
@@ -15,46 +16,49 @@ namespace op {
using namespace ov::op;
OutputVector translate_list_unpack(const NodeContext& context) {
- auto input = context.get_input(0);
-
- auto complex = as_type_ptr<ComplexTypeMark>(input.get_node_shared_ptr());
- bool is_complex = complex != nullptr;
- if (is_complex) {
- input = complex->get_input_source_output(0);
- }
+ // ComplexTypeMark handling: unwrap input, create FrameworkNode with unwrapped data,
+ // wrap outputs. This ensures transformations see clean graph without ComplexTypeMark.
+ auto [input, complex] = unwrap_complex(context.get_input(0));
if (const auto& list = cast_fw_node(input.get_node_shared_ptr(), "prim::ListConstruct")) {
// ListConstruct -> ListUnpack can be annihilated
auto res = list->input_values();
- if (is_complex) {
- for (auto& output : res) {
- output = context.mark_node(std::make_shared<ComplexTypeMark>(output));
- }
- }
- return res;
+ return wrap_complex(context, res, complex);
} else {
- const auto& outputs =
- make_framework_node(context, "Lists are not supported yet and can be resolved only in specific cases.");
- OutputVector res;
+ // Create FrameworkNode with UNWRAPPED input (transformations will see clean graph)
+ auto list_unpack_fw = std::make_shared<PtFrameworkNode>(context.get_decoder(),
+ OutputVector{input}, // unwrapped!
+ context.get_output_size());
+ context.mark_node(list_unpack_fw);
+ add_exception_to_fw_node(list_unpack_fw,
+ "Lists are not supported yet and can be resolved only in specific cases.");
+
+ auto outputs = list_unpack_fw->outputs();
+
+ // Handle quantized nodes
const auto& input_node = input.get_node_shared_ptr();
- const auto& quantized_node = input_node->input_value(0);
- if (const auto& quantized_pt_node = cast_quantized_fw_node(quantized_node.get_node_shared_ptr())) {
- if (const auto& chunk_node = cast_fw_node(input_node, "aten::chunk")) {
- for (const auto& output : outputs) {
- res.push_back(
- context.mark_node(std::make_shared<QuantizedPtNode>(quantized_pt_node->get_type(),
- output,
- quantized_pt_node->get_scale(),
- quantized_pt_node->get_zero_point(),
- quantized_pt_node->get_dtype())));
+ if (input_node->get_input_size() > 0) {
+ const auto& quantized_node = input_node->input_value(0);
+ if (const auto& quantized_pt_node = cast_quantized_fw_node(quantized_node.get_node_shared_ptr())) {
+ if (const auto& chunk_node = cast_fw_node(input_node, "aten::chunk")) {
+ OutputVector res;
+ for (const auto& output : outputs) {
+ res.push_back(
+ context.mark_node(std::make_shared<QuantizedPtNode>(quantized_pt_node->get_type(),
+ output,
+ quantized_pt_node->get_scale(),
+ quantized_pt_node->get_zero_point(),
+ quantized_pt_node->get_dtype())));
+ }
+ return res;
+ } else {
+ PYTORCH_OP_CONVERSION_CHECK(false, "Unsupported operation type.");
}
- return res;
- } else {
- PYTORCH_OP_CONVERSION_CHECK(false, "Unsupported operation type.");
}
- } else {
- return outputs;
}
+
+ // Wrap outputs in ComplexTypeMark if input was complex
+ return wrap_complex(context, outputs, complex);
}
};
diff --git a/src/frontends/pytorch/src/op/tuple_unpack.cpp b/src/frontends/pytorch/src/op/tuple_unpack.cpp
new file mode 100644
index 00000000000..7d06cf2481c
--- /dev/null
+++ b/src/frontends/pytorch/src/op/tuple_unpack.cpp
@@ -0,0 +1,43 @@
+// Copyright (C) 2018-2026 Intel Corporation
+// SPDX-License-Identifier: Apache-2.0
+//
+
+#include "openvino/frontend/complex_type_mark.hpp"
+#include "openvino/frontend/pytorch/node_context.hpp"
+#include "pt_framework_node.hpp"
+#include "utils.hpp"
+
+namespace ov {
+namespace frontend {
+namespace pytorch {
+namespace op {
+
+using namespace ov::op;
+
+OutputVector translate_tuple_unpack(const NodeContext& context) {
+ // ComplexTypeMark handling: unwrap input, create FrameworkNode with unwrapped data,
+ // wrap outputs. This ensures transformations see clean graph without ComplexTypeMark.
+ auto [input, complex] = unwrap_complex(context.get_input(0));
+
+ if (const auto& tuple = cast_fw_node(input.get_node_shared_ptr(), "prim::TupleConstruct")) {
+ // TupleConstruct -> TupleUnpack can be annihilated
+ auto res = tuple->input_values();
+ return wrap_complex(context, res, complex);
+ } else {
+ // Create FrameworkNode with UNWRAPPED input (transformations will see clean graph)
+ auto tuple_unpack_fw = std::make_shared<PtFrameworkNode>(context.get_decoder(),
+ OutputVector{input}, // unwrapped!
+ context.get_output_size());
+ context.mark_node(tuple_unpack_fw);
+ add_exception_to_fw_node(tuple_unpack_fw,
+ "Tuples are not supported yet and can be resolved only in specific cases.");
+
+ // Wrap outputs in ComplexTypeMark if input was complex
+ return wrap_complex(context, tuple_unpack_fw->outputs(), complex);
+ }
+};
+
+} // namespace op
+} // namespace pytorch
+} // namespace frontend
+} // namespace ov
diff --git a/src/frontends/pytorch/src/op/type_as.cpp b/src/frontends/pytorch/src/op/type_as.cpp
new file mode 100644
index 00000000000..4dccb36a666
--- /dev/null
+++ b/src/frontends/pytorch/src/op/type_as.cpp
@@ -0,0 +1,33 @@
+// Copyright (C) 2018-2026 Intel Corporation
+// SPDX-License-Identifier: Apache-2.0
+//
+
+#include "openvino/frontend/complex_type_mark.hpp"
+#include "openvino/frontend/pytorch/node_context.hpp"
+#include "openvino/op/convert_like.hpp"
+#include "utils.hpp"
+
+namespace ov {
+namespace frontend {
+namespace pytorch {
+namespace op {
+
+using namespace ov::op;
+
+OutputVector translate_type_as(const NodeContext& context) {
+ // aten::type_as(Tensor self, Tensor other) -> Tensor
+ // Converts self to the dtype of other
+ num_inputs_check(context, 2, 2, true); // allow_complex = true
+ FRONT_END_OP_CONVERSION_CHECK(!context.input_is_none(0) && !context.input_is_none(1), "Inputs should not be None.");
+
+ auto input = context.get_input(0);
+ auto like = context.get_input(1);
+
+ // Use ComplexTypeMark::convert_like for proper handling of complex types
+ return {ComplexTypeMark::convert_like(context, input, like)};
+}
+
+} // namespace op
+} // namespace pytorch
+} // namespace frontend
+} // namespace ov
diff --git a/src/frontends/pytorch/src/op_table.cpp b/src/frontends/pytorch/src/op_table.cpp
index f5d173221cf..89bb929581a 100644
--- a/src/frontends/pytorch/src/op_table.cpp
+++ b/src/frontends/pytorch/src/op_table.cpp
@@ -266,7 +266,9 @@ OP_CONVERTER(translate_topk);
OP_CONVERTER(translate_transpose);
OP_CONVERTER(translate_tril);
OP_CONVERTER(translate_triu);
+OP_CONVERTER(translate_type_as);
OP_CONVERTER(translate_tuple_index);
+OP_CONVERTER(translate_tuple_unpack);
OP_CONVERTER(translate_unflatten);
OP_CONVERTER(translate_unfold);
OP_CONVERTER(translate_unique2);
@@ -754,8 +756,7 @@ const std::unordered_map<std::string, CreatorFunction> get_supported_ops_ts() {
{"aten::transpose", op::quantizable_op<op::translate_transpose>},
{"aten::tril", op::translate_tril},
{"aten::triu", op::translate_triu},
- {"aten::type_as",
- op::translate_1to1_match_2_inputs<opset10::ConvertLike>}, // TODO: overflow semantics is different
+ {"aten::type_as", op::translate_type_as},
// aten::unbind - Supported in limited set of patterns
{"aten::unflatten", op::translate_unflatten},
{"aten::unfold", op::translate_unfold},
@@ -803,7 +804,7 @@ const std::unordered_map<std::string, CreatorFunction> get_supported_ops_ts() {
{"prim::requires_grad", op::return_false_scalar},
// prim::TupleConstruct - Supported in limited set of patterns
{"prim::TupleIndex", op::translate_tuple_index},
- // prim::TupleUnpack - Supported in limited set of patterns
+ {"prim::TupleUnpack", op::translate_tuple_unpack},
{"prim::type", op::skip_node}, // Used with prim::device, pass PtFrameworkNode.
{"prim::data", op::skip_node},
{"quantized::add", op::translate_quantized_add},
diff --git a/src/frontends/pytorch/src/translate_session.cpp b/src/frontends/pytorch/src/translate_session.cpp
index bbde398aa9b..7628fe6e0d6 100644
--- a/src/frontends/pytorch/src/translate_session.cpp
+++ b/src/frontends/pytorch/src/translate_session.cpp
@@ -20,6 +20,43 @@ namespace pytorch {
using namespace ov::op;
+namespace {
+// Helper to extract complex part element type from raw type
+element::Type get_complex_part_type(const Any& raw_type) {
+ element::Type complex_part_type = element::dynamic;
+ if (raw_type.is<type::Complex>()) {
+ const auto& complex_type = raw_type.as<type::Complex>();
+ if (complex_type.element_type.is<element::Type>()) {
+ complex_part_type = complex_type.element_type.as<element::Type>();
+ }
+ } else if (raw_type.is<type::Tensor>()) {
+ const auto& tensor_type = raw_type.as<type::Tensor>();
+ if (tensor_type.element_type.is<type::Complex>()) {
+ const auto& complex_type = tensor_type.element_type.as<type::Complex>();
+ if (complex_type.element_type.is<element::Type>()) {
+ complex_part_type = complex_type.element_type.as<element::Type>();
+ }
+ }
+ }
+ return complex_part_type;
+}
+
+// Helper to create parameter and register it in tensor_map, wrapping in ComplexTypeMark if needed
+void register_parameter_in_tensor_map(const std::shared_ptr<v0::Parameter>& parameter,
+ size_t input_id,
+ const Any& type_any,
+ const Any& raw_type,
+ const std::shared_ptr<std::unordered_map<size_t, Output<Node>>>& tensor_map) {
+ if (type_any.is<type::Complex>()) {
+ auto complex_part_type = get_complex_part_type(raw_type);
+ auto complex_mark = std::make_shared<ComplexTypeMark>(parameter->output(0), complex_part_type);
+ (*tensor_map)[input_id] = complex_mark;
+ } else {
+ (*tensor_map)[input_id] = parameter;
+ }
+}
+} // namespace
+
TranslateSession::TranslateSession(const ov::frontend::InputModel::Ptr& input_model,
const std::unordered_map<std::string, CreatorFunction>& translator_map,
const std::shared_ptr<TelemetryExtension>& telemetry)
@@ -112,7 +149,8 @@ std::shared_ptr<Model> TranslateSession::convert_pytorch_model(
for (size_t i = 0; i < inputs.size(); ++i) {
element::Type type = element::dynamic;
PartialShape pshape = pytorch_model->get_input_shape(i);
- auto type_any = simplified_type_interpret(pytorch_model->get_input_type(i));
+ auto raw_type = pytorch_model->get_input_type(i);
+ auto type_any = simplified_type_interpret(raw_type);
// TODO: Use special API to set custom type specification
if (type_any.is<element::Type>()) {
type = type_any.as<element::Type>();
@@ -121,7 +159,8 @@ std::shared_ptr<Model> TranslateSession::convert_pytorch_model(
parameter->set_friendly_name(pytorch_model->get_input_signature_name(i));
encode_tensor_name(parameter->output(0), inputs.at(i), {pytorch_model->get_input_debug_name(i)});
parameters->emplace_back(parameter);
- (*tensor_map)[inputs.at(i)] = parameter;
+
+ register_parameter_in_tensor_map(parameter, inputs.at(i), type_any, raw_type, tensor_map);
}
}
if (input_model) {
@@ -148,17 +187,19 @@ std::shared_ptr<Model> TranslateSession::convert_pytorch_model(
// Linkage to external scope will be performed on the level of the parent operation (if or loop)
// TODO: Eliminate duplication with the main code for Parameters creation
PartialShape ps = node->get_input_shape(i);
- auto type = simplified_type_interpret(node->get_input_type(i));
+ auto raw_type = node->get_input_type(i);
+ auto type = simplified_type_interpret(raw_type);
auto dtype = element::dynamic;
if (type.is<element::Type>()) {
dtype = type.as<element::Type>();
}
auto parameter = std::make_shared<v0::Parameter>(dtype, ps);
- (*tensor_map)[input] = parameter;
// set name of parameter to the index of node in the model
encode_tensor_name(parameter->output(0), input);
parameters->push_back(parameter);
inserted_params.push_back(input);
+
+ register_parameter_in_tensor_map(parameter, input, type, raw_type, tensor_map);
}
}
auto context = NodeContext(node, external_tensor_map, tensor_map, parameters, mutated_tensors, this);
diff --git a/src/frontends/pytorch/src/utils.cpp b/src/frontends/pytorch/src/utils.cpp
index a98049be0c9..aa4b1bc3a2a 100644
--- a/src/frontends/pytorch/src/utils.cpp
+++ b/src/frontends/pytorch/src/utils.cpp
@@ -485,6 +485,10 @@ Any simplified_type_interpret(Any type) {
if (tensor.element_type.is<element::Type>()) {
return tensor.element_type;
}
+ // If tensor element type is Complex, return Complex
+ if (tensor.element_type.is<type::Complex>()) {
+ return tensor.element_type;
+ }
} else if (type.is<type::PyScalar>()) {
const auto& scalar = type.as<type::PyScalar>();
if (scalar.element_type.is<element::Type>()) {
@@ -930,6 +934,38 @@ Output<Node> get_complex_shape(const NodeContext& context, const Output<Node>& c
return context.mark_node(std::make_shared<v8::Slice>(input_shape, zero, stop, step, zero));
}
+std::pair<Output<Node>, std::shared_ptr<ComplexTypeMark>> unwrap_complex(const Output<Node>& input) {
+ auto complex = as_type_ptr<ComplexTypeMark>(input.get_node_shared_ptr());
+ if (complex) {
+ return {complex->get_input_source_output(0), complex};
+ }
+ return {input, nullptr};
+}
+
+Output<Node> wrap_complex(const NodeContext& context,
+ const Output<Node>& result,
+ const std::shared_ptr<ComplexTypeMark>& complex) {
+ if (complex) {
+ return context.mark_node(std::make_shared<ComplexTypeMark>(result, complex->get_complex_part_type()));
+ }
+ return result;
+}
+
+OutputVector wrap_complex(const NodeContext& context,
+ const OutputVector& results,
+ const std::shared_ptr<ComplexTypeMark>& complex) {
+ if (complex) {
+ OutputVector wrapped;
+ wrapped.reserve(results.size());
+ for (const auto& r : results) {
+ wrapped.push_back(
+ context.mark_node(std::make_shared<ComplexTypeMark>(r, complex->get_complex_part_type())));
+ }
+ return wrapped;
+ }
+ return results;
+}
+
} // namespace pytorch
} // namespace frontend
} // namespace ov
diff --git a/src/frontends/pytorch/src/utils.hpp b/src/frontends/pytorch/src/utils.hpp
index 9aa2dd92cd8..244adb221ca 100644
--- a/src/frontends/pytorch/src/utils.hpp
+++ b/src/frontends/pytorch/src/utils.hpp
@@ -4,6 +4,7 @@
#pragma once
+#include "openvino/frontend/complex_type_mark.hpp"
#include "openvino/frontend/pytorch/node_context.hpp"
#include "openvino/op/constant.hpp"
#include "openvino/op/convert.hpp"
@@ -140,6 +141,31 @@ bool index_tensor_on_list(ov::pass::NodeRegistry& rg,
Output<Node> get_complex_shape(const NodeContext& context, const Output<Node>& complex_input);
+/// \brief Unwraps ComplexTypeMark node if present.
+/// \param input Input node to check.
+/// \return Pair of {underlying_data, complex_node_or_nullptr}.
+/// If input is ComplexTypeMark, returns its underlying data and the ComplexTypeMark node.
+/// Otherwise returns input as-is and nullptr.
+std::pair<Output<Node>, std::shared_ptr<ComplexTypeMark>> unwrap_complex(const Output<Node>& input);
+
+/// \brief Wraps result in ComplexTypeMark if complex is not nullptr.
+/// \param context Node context for marking nodes.
+/// \param result Result to wrap.
+/// \param complex ComplexTypeMark node to get type from, or nullptr to skip wrapping.
+/// \return Wrapped result if complex is not nullptr, otherwise result as-is.
+Output<Node> wrap_complex(const NodeContext& context,
+ const Output<Node>& result,
+ const std::shared_ptr<ComplexTypeMark>& complex);
+
+/// \brief Wraps multiple results in ComplexTypeMark if complex is not nullptr.
+/// \param context Node context for marking nodes.
+/// \param results Results to wrap.
+/// \param complex ComplexTypeMark node to get type from, or nullptr to skip wrapping.
+/// \return Wrapped results if complex is not nullptr, otherwise results as-is.
+OutputVector wrap_complex(const NodeContext& context,
+ const OutputVector& results,
+ const std::shared_ptr<ComplexTypeMark>& complex);
+
namespace op {
template <OutputVector (*T)(const NodeContext&), size_t idx = 0>
OutputVector inplace_op(const NodeContext& context) {
diff --git a/tests/layer_tests/pytorch_tests/test_listunpack.py b/tests/layer_tests/pytorch_tests/test_listunpack.py
index 02222edb6ff..7649cd9c5d8 100644
--- a/tests/layer_tests/pytorch_tests/test_listunpack.py
+++ b/tests/layer_tests/pytorch_tests/test_listunpack.py
@@ -322,3 +322,38 @@ class TestListUnpackParameterMultiple(PytorchLayerTest):
@pytest.mark.nightly
def test(self, ie_device, precision, ir_version):
self._test(*self.create_model(), ie_device, precision, ir_version)
+
+
+class TestComplexListUnpack(PytorchLayerTest):
+ """Test prim::ListUnpack with complex tensors (ComplexTypeMark propagation).
+
+ This tests the changes in list_unpack.cpp that handle ComplexTypeMark
+ propagation through ListUnpack operations.
+ """
+
+ def _prepare_input(self):
+ rng = np.random.default_rng(43)
+ return (rng.standard_normal((2, 4, 2)).astype(np.float32),)
+
+ def create_model(self):
+ class ComplexListUnpack(torch.nn.Module):
+ def __init__(self):
+ super().__init__()
+ g = torch.Generator().manual_seed(42)
+ freqs = torch.randn(4, 2, generator=g)
+ complex_freqs = torch.view_as_complex(freqs)
+ self.register_buffer('freqs', torch.view_as_real(complex_freqs))
+
+ def forward(self, x):
+ cx = torch.view_as_complex(x)
+ cf = torch.view_as_complex(self.freqs)
+ result = cx * cf
+ return torch.view_as_real(result)
+
+ return ComplexListUnpack(), None, "aten::mul"
+
+ @pytest.mark.nightly
+ @pytest.mark.precommit
+ def test_complex_list_unpack(self, ie_device, precision, ir_version):
+ self._test(*self.create_model(), ie_device, precision, ir_version,
+ trace_model=True)
diff --git a/tests/layer_tests/pytorch_tests/test_rope_pattern.py b/tests/layer_tests/pytorch_tests/test_rope_pattern.py
new file mode 100644
index 00000000000..1725b0e68ea
--- /dev/null
+++ b/tests/layer_tests/pytorch_tests/test_rope_pattern.py
@@ -0,0 +1,126 @@
+# Copyright (C) 2018-2026 Intel Corporation
+# SPDX-License-Identifier: Apache-2.0
+
+"""Test Rotary Position Embedding (RoPE) pattern with complex tensors.
+"""
+
+import numpy as np
+import pytest
+import torch
+
+from pytorch_layer_test_class import PytorchLayerTest
+
+
+class TestRoPEPattern(PytorchLayerTest):
+ """Test RoPE pattern: complex buffer -> unsqueeze -> view_as_real.
+
+ This is the main pattern that caused issues in Qwen-Image model.
+ """
+
+ def _prepare_input(self, seq_len=8, dim=64):
+ rng = np.random.default_rng(43)
+ return (rng.standard_normal((1, seq_len, dim)).astype(np.float32),)
+
+ def create_model(self, dim=64):
+ class RoPEModule(torch.nn.Module):
+ def __init__(self, dim):
+ super().__init__()
+ # Create freqs_cis as complex buffer (like in Qwen-Image)
+ g = torch.Generator().manual_seed(42)
+ freqs = torch.randn(8, dim // 2, generator=g)
+ self.register_buffer("freqs_cis",
+ torch.polar(torch.ones_like(freqs), freqs))
+
+ def forward(self, x):
+ batch, seq_len, dim = x.shape
+ freqs = self.freqs_cis[:seq_len]
+ freqs = freqs.unsqueeze(0) # This was causing the bug
+ freqs_real = torch.view_as_real(freqs)
+ x_reshaped = x.view(batch, seq_len, dim // 2, 2)
+ result = x_reshaped * freqs_real
+ return result.view(batch, seq_len, dim)
+
+ return RoPEModule(dim), None, ["aten::unsqueeze", "aten::view_as_real"]
+
+ @pytest.mark.parametrize("dim", [32, 64, 128])
+ @pytest.mark.nightly
+ @pytest.mark.precommit
+ def test_rope_pattern(self, dim, ie_device, precision, ir_version):
+ self._test(*self.create_model(dim), ie_device, precision, ir_version,
+ kwargs_to_prepare_input={"dim": dim},
+ trace_model=True)
+
+
+class TestComplexBufferUnsqueeze(PytorchLayerTest):
+ """Test complex buffer + unsqueeze
+
+ This is the minimal test case that reproduces the original bug:
+ - Complex buffer (pos_embed) registered in module
+ - Slicing the buffer
+ - Unsqueeze operation
+ - view_as_real to get output
+ """
+
+ def _prepare_input(self):
+ rng = np.random.default_rng(43)
+ return (rng.standard_normal((1, 4, 8)).astype(np.float32),)
+
+ def create_model(self):
+ class ComplexBufferUnsqueeze(torch.nn.Module):
+ def __init__(self):
+ super().__init__()
+ g = torch.Generator().manual_seed(42)
+ real = torch.randn(4, 8, generator=g)
+ imag = torch.randn(4, 8, generator=g)
+ self.register_buffer("pos_embed", torch.complex(real, imag))
+
+ def forward(self, x):
+ pos = self.pos_embed[:x.shape[1]]
+ pos = pos.unsqueeze(0) # Bug trigger
+ pos_real = torch.view_as_real(pos)
+ return x.unsqueeze(-1) + pos_real
+
+ return ComplexBufferUnsqueeze(), None, "aten::unsqueeze"
+
+ @pytest.mark.nightly
+ @pytest.mark.precommit
+ def test_complex_buffer_unsqueeze(self, ie_device, precision, ir_version):
+ self._test(*self.create_model(), ie_device, precision, ir_version,
+ trace_model=True)
+
+
+class TestComplexBufferMultipleOps(PytorchLayerTest):
+ """Test complex buffer with multiple operations.
+
+ Tests complex buffer going through multiple operations before view_as_real.
+ """
+
+ def _prepare_input(self):
+ rng = np.random.default_rng(43)
+ return (rng.standard_normal((1, 4, 2)).astype(np.float32),)
+
+ def create_model(self):
+ class ComplexBufferMultipleOps(torch.nn.Module):
+ def __init__(self):
+ super().__init__()
+ g = torch.Generator().manual_seed(42)
+ freqs = torch.randn(4, 2, generator=g)
+ complex_freqs = torch.view_as_complex(freqs)
+ self.register_buffer("freqs_a", complex_freqs)
+ self.register_buffer("freqs_b", complex_freqs * 2)
+
+ def forward(self, x):
+ cx = torch.view_as_complex(x)
+ # Multiple operations with complex buffers
+ a = self.freqs_a.unsqueeze(0)
+ b = self.freqs_b.unsqueeze(0)
+ result = cx * a + cx * b
+ return torch.view_as_real(result)
+
+ return ComplexBufferMultipleOps(), None, ["aten::unsqueeze", "aten::mul"]
+
+ @pytest.mark.nightly
+ @pytest.mark.precommit
+ def test_complex_buffer_multiple_ops(self, ie_device, precision, ir_version):
+ self._test(*self.create_model(), ie_device, precision, ir_version,
+ trace_model=True)
diff --git a/tests/layer_tests/pytorch_tests/test_tuple_unpack.py b/tests/layer_tests/pytorch_tests/test_tuple_unpack.py
index 1591714d3ed..a56a44ac3cd 100644
--- a/tests/layer_tests/pytorch_tests/test_tuple_unpack.py
+++ b/tests/layer_tests/pytorch_tests/test_tuple_unpack.py
@@ -1,7 +1,9 @@
# Copyright (C) 2018-2026 Intel Corporation
# SPDX-License-Identifier: Apache-2.0
+import numpy as np
import pytest
+import torch
from pytorch_layer_test_class import PytorchLayerTest
@@ -32,3 +34,82 @@ class TestTupleUnpack(PytorchLayerTest):
def test_touple_unpack(self, ie_device, precision, ir_version):
self._test(*self.create_model(), ie_device, precision, ir_version,
trace_model=False, freeze_model=False)
+
+
+class TestComplexTupleUnpack(PytorchLayerTest):
+ """Test TupleUnpack with complex tensors (ComplexTypeMark preservation).
+
+ This tests the changes in:
+ - src/frontends/pytorch/src/op/tuple_unpack.cpp
+ - src/frontends/pytorch/src/transforms/tuple_unpack_replacer.cpp
+
+ The test verifies that complex tensor operations work correctly when
+ tensors are used in tuple-like patterns. We use trace_model=True to
+ get proper TorchScript representation.
+ """
+
+ def _prepare_input(self):
+ rng = np.random.default_rng(43)
+ return (rng.standard_normal((2, 4, 2)).astype(np.float32),)
+
+ def create_model(self):
+ class ComplexTupleUnpack(torch.nn.Module):
+ def __init__(self):
+ super().__init__()
+ # Use separate buffers instead of tuple
+ g = torch.Generator().manual_seed(42)
+ freqs = torch.randn(4, 2, generator=g)
+ complex_freqs = torch.view_as_complex(freqs)
+ self.register_buffer('freqs_a', torch.view_as_real(complex_freqs))
+ self.register_buffer('freqs_b', torch.view_as_real(complex_freqs * 2))
+
+ def forward(self, x):
+ complex_x = torch.view_as_complex(x)
+ # Use view_as_complex on buffers
+ a = torch.view_as_complex(self.freqs_a)
+ b = torch.view_as_complex(self.freqs_b)
+ result = complex_x * a + complex_x * b
+ return torch.view_as_real(result)
+
+ return ComplexTupleUnpack(), None, "aten::mul"
+
+ @pytest.mark.nightly
+ @pytest.mark.precommit
+ def test_complex_tuple_unpack(self, ie_device, precision, ir_version):
+ self._test(*self.create_model(), ie_device, precision, ir_version,
+ trace_model=True)
+
+
+class TestComplexTupleUnpackMultiple(PytorchLayerTest):
+ """Test TupleUnpack with multiple complex tensor outputs."""
+
+ def _prepare_input(self):
+ rng = np.random.default_rng(43)
+ return (rng.standard_normal((2, 4, 2)).astype(np.float32),)
+
+ def create_model(self):
+ class ComplexTupleUnpackMultiple(torch.nn.Module):
+ def __init__(self):
+ super().__init__()
+ g = torch.Generator().manual_seed(42)
+ freqs = torch.randn(4, 2, generator=g)
+ complex_freqs = torch.view_as_complex(freqs)
+ self.register_buffer('freqs_a', torch.view_as_real(complex_freqs))
+ self.register_buffer('freqs_b', torch.view_as_real(complex_freqs * 2))
+ self.register_buffer('freqs_c', torch.view_as_real(complex_freqs * 3))
+
+ def forward(self, x):
+ complex_x = torch.view_as_complex(x)
+ a = torch.view_as_complex(self.freqs_a)
+ b = torch.view_as_complex(self.freqs_b)
+ c = torch.view_as_complex(self.freqs_c)
+ result = complex_x * a + complex_x * b + complex_x * c
+ return torch.view_as_real(result)
+
+ return ComplexTupleUnpackMultiple(), None, "aten::mul"
+
+ @pytest.mark.nightly
+ @pytest.mark.precommit
+ def test_complex_tuple_unpack_multiple(self, ie_device, precision, ir_version):
+ self._test(*self.create_model(), ie_device, precision, ir_version,
+ trace_model=True)
diff --git a/tests/layer_tests/pytorch_tests/test_type_as.py b/tests/layer_tests/pytorch_tests/test_type_as.py
index 0525d29ee67..c2dda54308a 100644
--- a/tests/layer_tests/pytorch_tests/test_type_as.py
+++ b/tests/layer_tests/pytorch_tests/test_type_as.py
@@ -32,3 +32,35 @@ class TestTypeAs(PytorchLayerTest):
def test_type_as(self, input_dtype, cast_dtype, ie_device, precision, ir_version):
self._test(*self.create_model(), ie_device, precision, ir_version,
kwargs_to_prepare_input={"input_dtype": input_dtype, "cast_dtype": cast_dtype})
+
+
+class TestComplexTypeAs(PytorchLayerTest):
+ """Test aten::type_as with complex tensors."""
+
+ def _prepare_input(self, input_dtype=np.float32, cast_dtype=np.float64):
+ # Complex tensor represented as real with shape [..., 2]
+ rng = np.random.default_rng(43)
+ return (rng.standard_normal((2, 4, 2)).astype(input_dtype),
+ rng.standard_normal((2, 4, 2)).astype(cast_dtype))
+
+ def create_model(self):
+ import torch
+
+ class ComplexTypeAs(torch.nn.Module):
+ def forward(self, x, y):
+ # Convert to complex, use type_as, convert back
+ cx = torch.view_as_complex(x)
+ cy = torch.view_as_complex(y)
+ result = cx.type_as(cy)
+ return torch.view_as_real(result)
+
+ return ComplexTypeAs(), None, "aten::type_as"
+
+ @pytest.mark.parametrize("input_dtype", [np.float32, np.float64])
+ @pytest.mark.parametrize("cast_dtype", [np.float32, np.float64])
+ @pytest.mark.nightly
+ @pytest.mark.precommit
+ def test_complex_type_as(self, input_dtype, cast_dtype, ie_device, precision, ir_version):
+ self._test(*self.create_model(), ie_device, precision, ir_version,
+ kwargs_to_prepare_input={"input_dtype": input_dtype, "cast_dtype": cast_dtype},
+ trace_model=True)