OpenVINO™ is an open source toolkit for optimizing and deploying AI inference
C++ aicomputer-visiondeep-learningdeploy-aidiffusion-modelsgenerative-aigood-first-issueinferencellm-inferencenatural-language-processingnlpopenvinooptimize-aiperformance-boostrecommendation-systemspeech-recognitionstable-diffusiontransformersyolo
[PT FE] Support complex constants (#29138)
Maxim Vafin220487a273bf
diff --git a/src/bindings/python/src/openvino/frontend/pytorch/ts_decoder.py b/src/bindings/python/src/openvino/frontend/pytorch/ts_decoder.pyindex a9aec8f8aa9..6538a418462 100644--- a/src/bindings/python/src/openvino/frontend/pytorch/ts_decoder.py+++ b/src/bindings/python/src/openvino/frontend/pytorch/ts_decoder.py@@ -1,7 +1,7 @@+# -*- coding: utf-8 -*-# Copyright (C) 2018-2025 Intel Corporation# SPDX-License-Identifier: Apache-2.0-# flake8: noqa# mypy: ignore-errorsimport inspect@@ -9,8 +9,10 @@ import loggingimport typingimport torch-from openvino.frontend.pytorch.py_pytorch_frontend import _FrontEndPytorchDecoder as Decoder-from openvino.frontend.pytorch.py_pytorch_frontend import _Type as DecoderType+from openvino.frontend.pytorch.py_pytorch_frontend import (+ _FrontEndPytorchDecoder as Decoder,+ _Type as DecoderType+)from openvino import op, PartialShape, Type as OVType, OVAnyfrom openvino.frontend.pytorch.utils import (ivalue_to_constant,@@ -42,15 +44,17 @@ class TorchScriptPythonDecoder(Decoder):trace_kwargs=None,):super().__init__()- # We store every decoder created by this decoder so that all them are not deleted until the first decoder is deleted+ # We store every decoder created by this decoder so that all them are+ # not deleted until the first decoder is deletedself.m_decoders = []self._input_signature = Noneself._shared_memory = shared_memoryself._input_is_list = False- self.constant_cache = constant_cache if constant_cache is not None else dict()+ self.constant_cache = constant_cache if constant_cache is not None else dict() # noqa: C408self.module_extensions = module_extensionsself.config = Noneself.out_debug_name_overwrites = {}+ self.cached_out_types = []if graph_element is None:if hasattr(pt_module, "config"):if isinstance(pt_module.config, dict):@@ -63,13 +67,13 @@ class TorchScriptPythonDecoder(Decoder):except Exception as e:if example_input is not None:msg = "tracing"- help_msg = "Please check correctness of provided 'example_input'. " \- "Sometimes models can be converted in scripted mode, please try running " \- "conversion without 'example_input'.\n"+ help_msg = ("Please check correctness of provided 'example_input'. "+ "Sometimes models can be converted in scripted mode, please try running "+ "conversion without 'example_input'.\n")else:msg = "scripting"- help_msg = "Tracing sometimes provide better results, " \- "please provide valid 'example_input' argument.\n"+ help_msg = ("Tracing sometimes provide better results, "+ "please provide valid 'example_input' argument.\n")raise RuntimeError(f"Couldn't get TorchScript module by {msg}.\n{help_msg} ""You can also provide TorchScript module that you obtained"@@ -88,12 +92,13 @@ class TorchScriptPythonDecoder(Decoder):if "self" in self.raw_inputs[0].debugName():self._input_signature.insert(0, "self")if 0 < len(self._input_signature) < len(self.raw_inputs):- # last input is args input, we need to multiply that name by number of extra inputs+ # last input is args input, we need to multiply that name by+ # number of extra inputsself._input_signature = self._input_signature[:-1]- n = len(self._input_signature)- for i in range(len(self.raw_inputs) - n):+ s_len = len(self._input_signature)+ for i in range(len(self.raw_inputs) - s_len):self._input_signature.append(- self.raw_inputs[i + n].debugName())+ self.raw_inputs[i + s_len].debugName())if isinstance(self.graph_element, torch.Graph):self._transform_tensor_list_constants_to_listconstruct(@@ -121,7 +126,8 @@ class TorchScriptPythonDecoder(Decoder):pt_module, (torch.jit._trace.TopLevelTracedModule,torch.jit._script.RecursiveScriptModule)):- # input params is dictionary contains input names and their signature values (type hints and default values if any)+ # input params is dictionary contains input names and their+ # signature values (type hints and default values if any)input_params = inspect.signature(pt_module.forward if hasattr(pt_module, "forward") else pt_module.__call__).parametersinput_signature = list(input_params)@@ -138,7 +144,8 @@ class TorchScriptPythonDecoder(Decoder):input_parameters, input_signature, pt_module, self._input_is_list = prepare_example_inputs_and_model(example_inputs, input_params, pt_module)- # name of attribute in a patched module where the original forward method is kept+ # name of attribute in a patched module where the+ # original forward method is keptorig_forward_name = "_openvino_module_extension_patch_orig_forward"if self.module_extensions:patch_model.patch_model(@@ -173,7 +180,8 @@ class TorchScriptPythonDecoder(Decoder):freeze_by_default = Truequantized_hint_ops = ["quantized", "aten::as_strided"]if freeze_by_default and graph_has_ops(scripted.inlined_graph, quantized_hint_ops):- # do not freeze quantized models and can't freeze for aten::as_strided it will result in incorrect inference+ # do not freeze quantized models and can't freeze for+ # aten::as_strided it will result in incorrect inferencefreeze_by_default = Falseif freeze_by_default and not skip_freeze:preserved_attrs = self._get_preserved_attributes(scripted)@@ -231,6 +239,8 @@ class TorchScriptPythonDecoder(Decoder):return self.get_shape_for_value(output)def get_output_type(self, index: int):+ if index < len(self.cached_out_types):+ return self.cached_out_types[index]output = self._raw_output(index)return self.get_type_for_value(output)@@ -242,8 +252,13 @@ class TorchScriptPythonDecoder(Decoder):# TODO: Don't use str, use native typesif str(pt_type) in ["int", "float", "bool"]:return OVAny(DecoderType.PyScalar(OVAny(pt_to_ov_type_map[str(pt_type)])))+ elif isinstance(pt_type, torch.dtype) and pt_type.is_complex:+ return OVAny(DecoderType.Complex(self._get_known_type_for_value(pt_type.to_real())))elif str(pt_type) in pt_to_ov_type_map:return OVAny(pt_to_ov_type_map[str(pt_type)])+ elif isinstance(pt_type, torch.ComplexType):+ # Tensor type, parse element type+ return OVAny(DecoderType.Tensor(OVAny(DecoderType.Complex(OVAny(OVType.dynamic)))))elif isinstance(pt_type, torch.TensorType):# Tensor type, parse element typereturn OVAny(DecoderType.Tensor(self._get_known_type_for_value(pt_type.dtype())))@@ -264,14 +279,16 @@ class TorchScriptPythonDecoder(Decoder):ps = PartialShape([-1] * len(value.type().sizes()))return pselse:- # TODO: Recognize types that we can represent as a nested constructs with objects from DecoderType- # If recognized, return scalar instead of dynamic. Scalar means a single value of that custom type.- # See get_type_for_value for reference+ # TODO: Recognize types that we can represent as a nested+ # constructs with objects from DecoderType If recognized,+ # return scalar instead of dynamic. Scalar means a single+ # value of that custom type. See get_type_for_value for referencepassreturn PartialShape.dynamic()def get_type_for_value(self, value: torch.Value):- full_type = self._get_known_type_for_value(value.type())+ _type = value.type() if hasattr(value, "type") else type(value).__name__+ full_type = self._get_known_type_for_value(_type)return full_typedef get_subgraph_size(self) -> int:@@ -306,7 +323,8 @@ class TorchScriptPythonDecoder(Decoder):torch._C._jit_pass_inline(subgraph)return [subgraph]else:- # Attribute "Subgraph" is only available if Graph was created using tracing.+ # Attribute "Subgraph" is only available if Graph was+ # created using tracing.# TODO Find way to extract subgraph for scripted Graph.return []return list(self.graph_element.blocks())@@ -340,10 +358,15 @@ class TorchScriptPythonDecoder(Decoder):target = target_op(trampoline.original_module)elif isinstance(target_op, str):target = target_op- # TODO: Support target as a callable that will play a role of ConversionExtension for an entire module instead of a single op.- # Without supporting target as a callable here, ConversionExtension functionality is still possible to implement- # by combining two extensions: ModuleExtension that use temporary name as a target op and another extension of type ConversionExtension- # that translates that particular temporary name to custom graph. But providing conversion code as a callable `target` is more convenient.+ # TODO: Support target as a callable that will play a role of+ # ConversionExtension for an entire module instead of a single+ # op. Without supporting target as a callable here,+ # ConversionExtension functionality is still possible to+ # implement by combining two extensions: ModuleExtension that+ # use temporary name as a target op and another extension of+ # type ConversionExtension that translates that particular+ # temporary name to custom graph. But providing conversion code+ # as a callable `target` is more convenient.return targetreturn self.graph_element.kind()@@ -370,18 +393,18 @@ class TorchScriptPythonDecoder(Decoder):if "FrameworkNode" not in node.get_type_name():name += "/" + node.get_type_name()if self.graph_element.scopeName():- node.set_friendly_name(- self.graph_element.scopeName().split("/")[-1] + "/" + name)+ scope_name = self.graph_element.scopeName().split("/")[-1]+ node.set_friendly_name(scope_name + "/" + name)else:node.set_friendly_name(name)return node- def _add_name_to_const_and_cache(self, outputs, name):+ def _add_name_to_const_and_cache(self, outputs, name, dtype=None):if len(outputs) == 1:# set name corresponding to state_dict nameoutputs[0].get_node().set_friendly_name(name)self.out_debug_name_overwrites[0] = name- self.constant_cache[name] = outputs+ self.constant_cache[name] = (outputs, dtype)def try_decode_get_attr(self):pt_value, name = get_value_from_getattr(@@ -393,7 +416,7 @@ class TorchScriptPythonDecoder(Decoder):weight, bias = pt_value.unpack()w_name = name + ".weight"if w_name in self.constant_cache:- res = self.constant_cache[w_name]+ res = self.constant_cache[w_name][0]else:res = convert_quantized_tensor(weight, self._shared_memory)self._add_name_to_const_and_cache(res, w_name)@@ -401,7 +424,7 @@ class TorchScriptPythonDecoder(Decoder):if isinstance(bias, torch.Tensor):b_name = name + ".bias"if b_name in self.constant_cache:- res += self.constant_cache[b_name]+ res += self.constant_cache[b_name][0]else:b_res = ivalue_to_constant(bias)self._add_name_to_const_and_cache(b_res, b_name)@@ -423,17 +446,22 @@ class TorchScriptPythonDecoder(Decoder):shared_memory=self._shared_memory)res += ivalue_to_constant(groups,shared_memory=self._shared_memory)- except:- pass+ except Exception as e:+ logging.debug("Failed to get conv params", exc_info=e)return reselif not isinstance(pt_value, (torch.jit.ScriptModule, torch.jit.TracedModule)):# this tensor can be used multiple times in the model, so we have to reuse constantsif name in self.constant_cache:- const = self.constant_cache[name]+ const, dtype = self.constant_cache[name]else:+ dtype = self.get_type_for_value(pt_value)+ if hasattr(pt_value, "dtype") and pt_value.dtype.is_complex:+ pt_value = torch.view_as_real(pt_value)const = ivalue_to_constant(pt_value, shared_memory=self._shared_memory)- self._add_name_to_const_and_cache(const, name)+ self._add_name_to_const_and_cache(const, name, dtype)+ if dtype is not None:+ self.cached_out_types = [dtype]return constelse:return []@@ -519,8 +547,9 @@ class TorchScriptPythonDecoder(Decoder):return Falsetry:return self.alias_db.may_contain_alias(self._raw_input(in_index), self._raw_output(out_index))- except:+ except Exception as e:# Sometimes pytorch fails to get result with IndexError exception while these indexes exist in node+ logging.debug("Failed to get alias information", exc_info=e)return Falsedef is_input_inlined(self, index):@@ -560,8 +589,8 @@ class TorchScriptPythonDecoder(Decoder):if not any(allowed_types):continueconst_inputs = []- for val in node.output().toIValue():- const_input = graph.insertConstant(val)+ for value in node.output().toIValue():+ const_input = graph.insertConstant(value)const_input.node().moveBefore(node)const_input.node().copyMetadata(node)const_inputs.append(const_input)diff --git a/src/bindings/python/src/openvino/frontend/pytorch/utils.py b/src/bindings/python/src/openvino/frontend/pytorch/utils.pyindex fa6a680976d..6c1ffa90137 100644--- a/src/bindings/python/src/openvino/frontend/pytorch/utils.py+++ b/src/bindings/python/src/openvino/frontend/pytorch/utils.py@@ -9,8 +9,9 @@ import loggingimport torchimport numpy as np-from openvino import op, Type as OVType, Shape, Tensor+from openvino import op, Type as OVType, Shape, Tensor, OVAnyfrom openvino import opset11 as ops+from openvino.frontend.pytorch.py_pytorch_frontend import _Type as DecoderTypelog = logging.getLogger(__name__)@@ -78,6 +79,10 @@ def torch_tensor_to_ov_const(torch_t: torch.Tensor, shared_memory=True):narr = torch_t.numpy(force=True)tensor = Tensor(narr, torch_t.shape, F8_DTYPE_MAP[dtype])ov_const = op.Constant(tensor, shared_memory=shared_memory)+ elif torch_t.is_complex():+ narr = torch.view_as_real(torch_t).numpy(force=True)+ # we rely on frontend to mark the constant as complex internally+ ov_const = op.Constant(narr, shared_memory=shared_memory)else:narr = torch_t.numpy(force=True)ov_const = op.Constant(narr, shared_memory=shared_memory)@@ -144,6 +149,9 @@ pt_to_ov_type_map = {"torch.float16": OVType.f16,"torch.float32": OVType.f32,"torch.float64": OVType.f64,+ "torch.complex32": DecoderType.Complex(OVAny(OVType.f16)),+ "torch.complex64": DecoderType.Complex(OVAny(OVType.f32)),+ "torch.complex128": DecoderType.Complex(OVAny(OVType.f64)),"torch.uint8": OVType.u8,"torch.int8": OVType.i8,"torch.int16": OVType.i16,@@ -160,6 +168,9 @@ pt_to_ov_type_map = {"torch.CharTensor": OVType.i8,"torch.ByteTensor": OVType.u8,"torch.BoolTensor": OVType.boolean,+ "torch.ComplexHalfTensor": DecoderType.Complex(OVAny(OVType.f16)),+ "torch.ComplexFloatTensor": DecoderType.Complex(OVAny(OVType.f32)),+ "torch.ComplexDoubleTensor": DecoderType.Complex(OVAny(OVType.f64)),"torch.quint8": OVType.u8,"torch.qint8": OVType.i8,"torch.qint32": OVType.i32,diff --git a/src/bindings/python/src/pyopenvino/core/common.cpp b/src/bindings/python/src/pyopenvino/core/common.cppindex e08dfdc8c39..1c3594151dd 100644--- a/src/bindings/python/src/pyopenvino/core/common.cpp+++ b/src/bindings/python/src/pyopenvino/core/common.cpp@@ -74,13 +74,8 @@ const std::map<int, ov::element::Type>& dtype_num_to_ov_type() {}ov::element::Type get_ov_type(const py::array& array) {- // More about character codes:- // https://numpy.org/doc/stable/reference/arrays.scalars.html- char ctype = array.dtype().kind();- if (ctype == 'U' || ctype == 'S') {- return ov::element::string;- }- return dtype_num_to_ov_type().at(array.dtype().num());+ auto dtype = array.dtype();+ return get_ov_type(dtype);}ov::element::Type get_ov_type(py::dtype& dtype) {@@ -90,7 +85,10 @@ ov::element::Type get_ov_type(py::dtype& dtype) {if (ctype == 'U' || ctype == 'S') {return ov::element::string;}- return dtype_num_to_ov_type().at(dtype.num());+ const auto dtype_map = dtype_num_to_ov_type();+ auto ov_type_it = dtype_map.find(dtype.num());+ OPENVINO_ASSERT(ov_type_it != dtype_map.end(), "Unsupported data type: ", dtype);+ return ov_type_it->second;}}; // namespace type_helpersdiff --git a/src/bindings/python/src/pyopenvino/frontend/pytorch/decoder.cpp b/src/bindings/python/src/pyopenvino/frontend/pytorch/decoder.cppindex 45f91ebbbca..ede8f5927ee 100644--- a/src/bindings/python/src/pyopenvino/frontend/pytorch/decoder.cpp+++ b/src/bindings/python/src/pyopenvino/frontend/pytorch/decoder.cpp@@ -26,6 +26,8 @@ void regclass_frontend_pytorch_decoder(py::module m) {// Register classes for TorchScript type systempy::class_<type::Tensor>(type_module, "Tensor").def(py::init<Any>());+ py::class_<type::Complex>(type_module, "Complex").+ def(py::init<Any>());py::class_<type::List>(type_module, "List").def(py::init<Any>());py::class_<type::Str>(type_module, "Str").diff --git a/src/bindings/python/src/pyopenvino/utils/utils.cpp b/src/bindings/python/src/pyopenvino/utils/utils.cppindex 199e7f0320a..ce2f80eea83 100644--- a/src/bindings/python/src/pyopenvino/utils/utils.cpp+++ b/src/bindings/python/src/pyopenvino/utils/utils.cpp@@ -261,6 +261,8 @@ py::object from_ov_any(const ov::Any& any) {return py::cast(any.as<ov::frontend::type::List>());} else if (any.is<ov::frontend::type::Tensor>()) {return py::cast(any.as<ov::frontend::type::Tensor>());+ } else if (any.is<ov::frontend::type::Complex>()) {+ return py::cast(any.as<ov::frontend::type::Complex>());} else if (any.is<ov::frontend::type::Str>()) {return py::cast(any.as<ov::frontend::type::Str>());} else if (any.is<ov::frontend::type::PyNone>()) {@@ -485,6 +487,8 @@ ov::Any py_object_to_any(const py::object& py_obj) {// Custom FrontEnd Types} else if (py::isinstance<ov::frontend::type::Tensor>(py_obj)) {return py::cast<ov::frontend::type::Tensor>(py_obj);+ } else if (py::isinstance<ov::frontend::type::Complex>(py_obj)) {+ return py::cast<ov::frontend::type::Complex>(py_obj);} else if (py::isinstance<ov::frontend::type::List>(py_obj)) {return py::cast<ov::frontend::type::List>(py_obj);} else if (py::isinstance<ov::frontend::type::Str>(py_obj)) {diff --git a/src/frontends/common/include/openvino/frontend/decoder.hpp b/src/frontends/common/include/openvino/frontend/decoder.hppindex 7794cc23b94..6a181693dbd 100644--- a/src/frontends/common/include/openvino/frontend/decoder.hpp+++ b/src/frontends/common/include/openvino/frontend/decoder.hpp@@ -21,6 +21,12 @@ struct Tensor {Any element_type;};+struct Complex {+ Complex() = default;+ explicit Complex(const Any& _element_type) : element_type(_element_type) {}+ Any element_type;+};+struct Tuple;struct List {diff --git a/src/frontends/common_translators/src/op/complex.cpp b/src/frontends/common_translators/src/op/complex.cppindex e6d0afb3626..73bc8d8267f 100644--- a/src/frontends/common_translators/src/op/complex.cpp+++ b/src/frontends/common_translators/src/op/complex.cpp@@ -37,9 +37,9 @@ OutputVector translate_real(const NodeContext& context) {auto complex = context.get_input(0);auto complex_type_mark = as_type_ptr<ComplexTypeMark>(complex.get_node_shared_ptr());- auto op_type = context.get_op_type();- FRONT_END_OP_CONVERSION_CHECK(complex_type_mark, op_type + " operation expects complex type tensor on input.");-+ if (!complex_type_mark)+ // if input is not a complex number, just return it as is. This is allowed in torch.+ return {complex};return {complex_type_mark->get_real()};};diff --git a/src/frontends/pytorch/src/node_context.cpp b/src/frontends/pytorch/src/node_context.cppindex f0d771ef7d3..f2364c9f5fb 100644--- a/src/frontends/pytorch/src/node_context.cpp+++ b/src/frontends/pytorch/src/node_context.cpp@@ -6,6 +6,7 @@#include "helper_ops/internal_op.hpp"#include "openvino/core/validation_util.hpp"+#include "openvino/frontend/complex_type_mark.hpp"#include "openvino/frontend/exception.hpp"#include "openvino/frontend/pytorch/decoder.hpp"#include "openvino/op/constant.hpp"@@ -44,6 +45,10 @@ 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>()) {+ // Add complex mark to complex constant+ c_outs = {mark_node(std::make_shared<ComplexTypeMark>(c_outs[0], c_outs[0].get_element_type()))};+ }return c_outs;}}diff --git a/src/frontends/pytorch/src/op/complex.cpp b/src/frontends/pytorch/src/op/complex.cppindex 83f8a0fe3c4..6d91baf8a88 100644--- a/src/frontends/pytorch/src/op/complex.cpp+++ b/src/frontends/pytorch/src/op/complex.cpp@@ -22,7 +22,7 @@ OutputVector translate_view_as_real(const NodeContext& context) {auto complex = context.get_input(0);auto complex_type_mark = as_type_ptr<ComplexTypeMark>(complex.get_node_shared_ptr());- PYTORCH_OP_CONVERSION_CHECK(complex_type_mark, "aten::real operation expects complex type tensor on input.");+ PYTORCH_OP_CONVERSION_CHECK(complex_type_mark, "aten::view_as_real is only supported for complex tensors");return {complex_type_mark->get_data()};};diff --git a/src/frontends/pytorch/src/op/get_attr.cpp b/src/frontends/pytorch/src/op/get_attr.cppindex b6871ed8180..365247154ab 100644--- a/src/frontends/pytorch/src/op/get_attr.cpp+++ b/src/frontends/pytorch/src/op/get_attr.cpp@@ -2,6 +2,7 @@// 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"@@ -12,15 +13,21 @@ namespace pytorch {namespace op {OutputVector translate_get_attr(const NodeContext& context) {- auto res = context.get_decoder()->try_decode_get_attr();+ auto decoder = context.get_decoder();+ auto res = decoder->try_decode_get_attr();PYTORCH_OP_CONVERSION_CHECK(res.size() > 0,"Failed to obtain data from GetAttr with output tensor name: ",- context.get_decoder()->get_output_debug_name(0));+ decoder->get_output_debug_name(0));if (res.size() == 1) {auto node = res[0].get_node();- if (node->get_friendly_name() != node->get_name()) {+ if (node && node->get_friendly_name() != node->get_name()) {res[0].add_names({node->get_friendly_name()});}+ auto dtype = decoder->get_output_type(0);+ if (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()))};+ }return res;} else {// Packed params case@@ -31,7 +38,7 @@ OutputVector translate_get_attr(const NodeContext& context) {"node.");return {context.mark_node(fw_node)};}-};+}} // namespace op} // namespace pytorchdiff --git a/src/frontends/pytorch/src/op/to.cpp b/src/frontends/pytorch/src/op/to.cppindex 9d6525253d8..6e7be29caa1 100644--- a/src/frontends/pytorch/src/op/to.cpp+++ b/src/frontends/pytorch/src/op/to.cpp@@ -2,6 +2,7 @@// SPDX-License-Identifier: Apache-2.0//+#include "openvino/frontend/complex_type_mark.hpp"#include "openvino/frontend/pytorch/node_context.hpp"#include "openvino/op/constant.hpp"#include "openvino/op/convert.hpp"@@ -67,16 +68,52 @@ OutputVector translate_to(const NodeContext& context) {// memory format is ignored since it changes strides of a tensor. In openvino tensors are always contigiousauto dtype_ext_node = context.get_input_from_visible_context(dtype_idx).get_node_shared_ptr();auto dtype_fw_node = ov::as_type_ptr<PtFrameworkNode>(dtype_ext_node);+ auto data = context.get_input(0);++ auto complex_mark = as_type_ptr<ComplexTypeMark>(data.get_node_shared_ptr());Output<Node> cast;if (dtype_fw_node && dtype_fw_node->get_op_type() == "prim::dtype") {auto type_input = dtype_fw_node->input_value(0);- cast = context.mark_node(std::make_shared<v1::ConvertLike>(context.get_input(0), type_input));+ auto type_complex_mark = as_type_ptr<ComplexTypeMark>(type_input.get_node_shared_ptr());+ bool to_complex = type_complex_mark != nullptr;+ bool is_complex = complex_mark != nullptr;+ if (to_complex) {+ type_input = type_complex_mark->get_data();+ }+ if (is_complex && !to_complex) {+ data = complex_mark->get_real();+ } else if (is_complex) {+ data = complex_mark->get_data();+ }+ cast = context.mark_node(std::make_shared<v1::ConvertLike>(data, type_input));+ if (to_complex && !is_complex) {+ auto imag = context.mark_node(v0::Constant::create(element::f32, Shape{}, {0}));+ imag = context.mark_node(std::make_shared<v1::ConvertLike>(imag, type_input));+ cast = context.mark_node(std::make_shared<ComplexTypeMark>(cast, imag, cast.get_element_type()));+ } else if (to_complex) {+ cast = context.mark_node(std::make_shared<ComplexTypeMark>(cast, cast.get_element_type()));+ }} else if (const auto dtype_const = ov::as_type_ptr<v0::Constant>(dtype_ext_node)) {auto pt_type = dtype_const->cast_vector<int64_t>()[0];+ bool to_complex = is_complex_dtype(pt_type);auto dtype = convert_dtype(pt_type);- cast = context.mark_node(std::make_shared<v0::Convert>(context.get_input(0), dtype));++ bool is_complex = complex_mark != nullptr;+ if (is_complex && !to_complex) {+ data = complex_mark->get_real();+ } else if (is_complex) {+ data = complex_mark->get_data();+ }++ cast = context.mark_node(std::make_shared<v0::Convert>(data, dtype));+ if (to_complex && !is_complex) {+ auto imag = context.mark_node(v0::Constant::create(dtype, Shape{}, {0}));+ cast = context.mark_node(std::make_shared<ComplexTypeMark>(cast, imag, dtype));+ } else if (to_complex) {+ cast = context.mark_node(std::make_shared<ComplexTypeMark>(cast, cast.get_element_type()));+ }} else {- cast = context.mark_node(std::make_shared<v1::ConvertLike>(context.get_input(0), context.get_input(1)));+ cast = context.mark_node(std::make_shared<v1::ConvertLike>(data, context.get_input(1)));}return {cast};}diff --git a/src/frontends/pytorch/src/op_table.cpp b/src/frontends/pytorch/src/op_table.cppindex 0101429ba7b..15f2b8bd47d 100644--- a/src/frontends/pytorch/src/op_table.cpp+++ b/src/frontends/pytorch/src/op_table.cpp@@ -63,7 +63,6 @@ OP_CONVERTER(translate_celu);OP_CONVERTER(translate_channel_shuffle);OP_CONVERTER(translate_clamp);OP_CONVERTER(translate_col2im);-OP_CONVERTER(translate_complex);OP_CONVERTER(translate_constant);OP_CONVERTER(translate_conv_transposend);OP_CONVERTER(translate_convnd);@@ -115,7 +114,6 @@ OP_CONVERTER(translate_hann_window);OP_CONVERTER(translate_hardtanh);OP_CONVERTER(translate_if);OP_CONVERTER(translate_im2col);-OP_CONVERTER(translate_imag);OP_CONVERTER(translate_index);OP_CONVERTER(translate_index_add);OP_CONVERTER(translate_index_copy_);@@ -201,7 +199,6 @@ OP_CONVERTER(translate_randn);OP_CONVERTER(translate_randint);OP_CONVERTER(translate_rand_like);OP_CONVERTER(translate_randn_like);-OP_CONVERTER(translate_real);OP_CONVERTER(translate_reciprocal);OP_CONVERTER(translate_relu6);OP_CONVERTER(translate_remainder);@@ -246,6 +243,7 @@ OP_CONVERTER(translate_triu);OP_CONVERTER(translate_tuple_index);OP_CONVERTER(translate_unflatten);OP_CONVERTER(translate_unfold);+OP_CONVERTER(translate_unique2);OP_CONVERTER(translate_upsample_bicubic2d);OP_CONVERTER(translate_upsample_bilinear2d);OP_CONVERTER(translate_upsample_bicubic2d_aa);@@ -327,13 +325,11 @@ OP_CONVERTER(translate_sum_fx);OP_CONVERTER(translate_std_fx);OP_CONVERTER(translate_topk_fx);OP_CONVERTER(translate_to_fx);-OP_CONVERTER(translate_transpose_fx);OP_CONVERTER(translate_quantize_per_channel_fx);OP_CONVERTER(translate_quantize_per_tensor_fx);OP_CONVERTER(translate_var_fx);OP_CONVERTER(translate_var_mean_fx);OP_CONVERTER(translate_unbind_int_fx);-OP_CONVERTER(translate_unique2);OP_CONVERTER(translate_zeros_fx);OP_CONVERTER(translate_zeros_like_fx);// Extensionsdiff --git a/src/frontends/pytorch/src/utils.cpp b/src/frontends/pytorch/src/utils.cppindex 69753fbc358..3789577a07f 100644--- a/src/frontends/pytorch/src/utils.cpp+++ b/src/frontends/pytorch/src/utils.cpp@@ -209,6 +209,9 @@ const std::unordered_map<int64_t, element::Type> TORCH_TO_OV_TYPE{{5, element::f16},{6, element::f32},{7, element::f64},+ {8, element::f16}, // complex32+ {9, element::f32}, // complex64+ {10, element::f64}, // complex128{11, element::boolean},{12, element::i8}, // quantized i8{13, element::u8}, // quantized u8@@ -216,6 +219,8 @@ const std::unordered_map<int64_t, element::Type> TORCH_TO_OV_TYPE{{15, element::bf16},};+const std::vector<int64_t> COMPLEX_TYPE = {8, 9, 10};+const std::unordered_map<std::string, PadType> TORCH_AUTO_PAD_TO_OV{{"valid", PadType::VALID},{"same", PadType::SAME_UPPER}};} // namespace@@ -225,6 +230,10 @@ element::Type convert_dtype(int64_t pt_type) {return TORCH_TO_OV_TYPE.at(pt_type);};+bool is_complex_dtype(int64_t pt_type) {+ return std::find(COMPLEX_TYPE.begin(), COMPLEX_TYPE.end(), pt_type) != COMPLEX_TYPE.end();+};+Output<Node> apply_dtype(const NodeContext& context, size_t dtype_port, const Output<Node>& input_tensor) {if (ov::as_type_ptr<v0::Constant>(context.get_input_from_visible_context(dtype_port).get_node_shared_ptr())) {auto dtype = convert_dtype(context.const_input<int64_t>(dtype_port));diff --git a/src/frontends/pytorch/src/utils.hpp b/src/frontends/pytorch/src/utils.hppindex ece73b3ea86..165b4203306 100644--- a/src/frontends/pytorch/src/utils.hpp+++ b/src/frontends/pytorch/src/utils.hpp@@ -64,6 +64,7 @@ std::shared_ptr<Node> numel(const NodeContext& context,element::Type output_type = element::i32);element::Type convert_dtype(int64_t dtype_value);+bool is_complex_dtype(int64_t pt_type);Output<Node> apply_dtype(const NodeContext& context, size_t dtype_port, const Output<Node>& input_tensor);diff --git a/tests/layer_tests/py_frontend_tests/test_torch_decoder.py b/tests/layer_tests/py_frontend_tests/test_torch_decoder.pyindex d8c55d70605..d072b5d9f6f 100644--- a/tests/layer_tests/py_frontend_tests/test_torch_decoder.py+++ b/tests/layer_tests/py_frontend_tests/test_torch_decoder.py@@ -228,6 +228,54 @@ def test_pytorch_decoder_can_convert_fp64_tensor():assert ov_const[0].get_partial_shape() == PartialShape([2])+def test_pytorch_decoder_can_convert_complex64_tensor():+ from openvino.frontend.pytorch.ts_decoder import TorchScriptPythonDecoder+ from openvino import PartialShape, Type++ class SomeTensor(torch.nn.Module):+ def forward(self):+ r = torch.tensor([1, 2], dtype=torch.float32)+ i = torch.tensor([3, 4], dtype=torch.float32)+ return torch.complex(r, i)++ model = get_scripted_model(SomeTensor())+ consts = [n for n in model.inlined_graph.nodes() if n.kind() ==+ "prim::Constant"]+ assert len(consts) > 0+ some_const = consts[0]+ nc_decoder = TorchScriptPythonDecoder(model, some_const)+ ov_const = nc_decoder.as_constant()+ assert ov_const is not None+ assert len(ov_const) == 1+ assert ov_const[0].get_element_type() == Type.f32+ assert ov_const[0].get_partial_shape() == PartialShape([2, 2])+++def test_pytorch_decoder_can_convert_complex128_tensor():+ from openvino.frontend.pytorch.ts_decoder import TorchScriptPythonDecoder+ from openvino import PartialShape, Type++ class SomeTensor(torch.nn.Module):+ def forward(self):+ r = torch.tensor([1, 2], dtype=torch.float64)+ i = torch.tensor([3, 4], dtype=torch.float64)+ return torch.complex(r, i)++ model = get_scripted_model(SomeTensor())+ consts = [n for n in model.inlined_graph.nodes() if n.kind() ==+ "prim::Constant"]+ assert len(consts) > 0+ some_const = consts[0]+ nc_decoder = TorchScriptPythonDecoder(model, some_const)+ ov_const = nc_decoder.as_constant()+ assert ov_const is not None+ assert len(ov_const) == 1+ assert ov_const[0].get_element_type() == Type.f64+ assert ov_const[0].get_partial_shape() == PartialShape([2, 2])++@pytest.mark.precommitdef test_pytorch_decoder_can_convert_bool_tensor():from openvino.frontend.pytorch.ts_decoder import TorchScriptPythonDecoderdiff --git a/tests/layer_tests/py_frontend_tests/test_torch_frontend.py b/tests/layer_tests/py_frontend_tests/test_torch_frontend.pyindex 14529a35b3e..6dcb512bbb6 100644--- a/tests/layer_tests/py_frontend_tests/test_torch_frontend.py+++ b/tests/layer_tests/py_frontend_tests/test_torch_frontend.py@@ -2,20 +2,24 @@# Copyright (C) 2018-2025 Intel Corporation# SPDX-License-Identifier: Apache-2.0-import torch-import numpy as np-from openvino.frontend import FrontEndManager, ConversionExtension, NodeContext-from openvino.runtime import PartialShape, Type-import openvino.runtime.opset10 as ops-import pytest-import globimport itertoolsimport mathimport osimport re+import loggingfrom pathlib import Path+import torch+import numpy as np+import pytest++from openvino.frontend import FrontEndManager, ConversionExtension, NodeContext+from openvino import PartialShape, Type+import openvino.opset10 as ops++logging.basicConfig(level=logging.DEBUG)+class aten_relu(torch.nn.Module):def forward(self, x):diff --git a/tests/layer_tests/pytorch_tests/test_complex.py b/tests/layer_tests/pytorch_tests/test_complex.pynew file mode 100644index 00000000000..885db986cb5--- /dev/null+++ b/tests/layer_tests/pytorch_tests/test_complex.py@@ -0,0 +1,77 @@+# Copyright (C) 2018-2025 Intel Corporation+# SPDX-License-Identifier: Apache-2.0++import pytest+import torch++from pytorch_layer_test_class import PytorchLayerTest+++class TestComplex(PytorchLayerTest):+ def _prepare_input(self):+ import numpy as np+ return (np.random.randn(2).astype(np.float32),)++ def create_model(self, dtype):+ class complex_model(torch.nn.Module):+ def __init__(self, dtype):+ super().__init__()+ self.dtype = dtype+ x = torch.tensor([1.0 + 2.0j, 3.0 + 4.0j], dtype=dtype)+ self.complex_attr = torch.nn.Parameter(x)++ def forward(self, x):+ complex_const = torch.tensor(+ [5.0 + 6.0j, 7.0 + 8.0j], dtype=self.dtype)++ real_attr = self.complex_attr.real+ imag_attr = self.complex_attr.imag++ real_const = complex_const.real+ imag_const = complex_const.imag++ real_result = x + real_attr + real_const+ imag_result = imag_attr + imag_const++ result = real_result + imag_result+ return result++ return complex_model(dtype), None, ["prim::GetAttr", "prim::Constant"]++ @pytest.mark.nightly+ @pytest.mark.precommit+ @pytest.mark.parametrize("dtype", [+ torch.complex32,+ torch.complex64,+ torch.complex128])+ def test_complex(self, dtype, ie_device, precision, ir_version):+ self._test(*self.create_model(dtype), ie_device,+ precision, ir_version, trace_model=True)+++class TestReal(PytorchLayerTest):+ def _prepare_input(self, y):+ import numpy as np+ if y:+ return (np.random.randn(2, 3).astype(np.float32),+ np.random.randn(2, 3).astype(np.float32))+ return (np.random.randn(2, 3).astype(np.float32),)++ def create_model(self):+ class aten_real(torch.nn.Module):+ def forward(self, x, y=None):+ if y is not None:+ c = torch.complex(x, y)+ else:+ c = x+ return torch.real(c)++ return aten_real(), None, "aten::real"++ @pytest.mark.nightly+ @pytest.mark.precommit+ @pytest.mark.parametrize("second_input", [True, False])+ def test_complex(self, second_input, ie_device, precision, ir_version):+ self._test(*self.create_model(), ie_device,+ precision, ir_version, trace_model=True,+ kwargs_to_prepare_input={"y": second_input})diff --git a/tests/layer_tests/pytorch_tests/test_to.py b/tests/layer_tests/pytorch_tests/test_to.pyindex ddfd092321d..856ab64414d 100644--- a/tests/layer_tests/pytorch_tests/test_to.py+++ b/tests/layer_tests/pytorch_tests/test_to.py@@ -147,3 +147,88 @@ class TestAtenToDeviceConst(PytorchLayerTest):def test_aten_to_device_const(self, use_trace, ie_device, precision, ir_version):self._test(*self.create_model(), ie_device, precision,ir_version, trace_model=use_trace)+++class TestAtenToComplex(PytorchLayerTest):+ def _prepare_input(self):+ return (np.random.randn(2, 3),)++ def create_model(self, dtype):+ import torch++ class aten_to_complex(torch.nn.Module):+ def __init__(self, dtype):+ super().__init__()+ self.dtype = dtype++ def forward(self, x):+ return torch.view_as_real(x.to(self.dtype))++ return aten_to_complex(dtype), None, "aten::to"++ @pytest.mark.parametrize("dtype", [torch.complex32,+ torch.complex64,+ torch.complex128])+ @pytest.mark.nightly+ @pytest.mark.precommit+ def test_aten_to_complex(self, dtype, ie_device, precision, ir_version):+ self._test(*self.create_model(dtype), ie_device, precision,+ ir_version, trace_model=True)+++class TestAtenToFromComplex(PytorchLayerTest):+ def _prepare_input(self):+ # double conversion to avoid accuracy issues due to different precision+ return (np.random.randn(2, 3, 2).astype(np.float16).astype(np.float32),)++ def create_model(self, dtype):+ import torch++ class aten_to_from_complex(torch.nn.Module):+ def __init__(self, dtype):+ super().__init__()+ self.dtype = dtype++ def forward(self, x):+ c = torch.view_as_complex(x.to(self.dtype))+ return c.to(torch.float32)++ return aten_to_from_complex(dtype), None, "aten::to"++ @pytest.mark.parametrize("dtype", [torch.float16,+ torch.float32,+ torch.float64])+ @pytest.mark.nightly+ @pytest.mark.precommit+ def test_aten_to_from_complex(self, dtype, ie_device, precision, ir_version):+ self._test(*self.create_model(dtype), ie_device, precision,+ ir_version)+++class TestAtenToFromComplexTensor(PytorchLayerTest):+ def _prepare_input(self):+ # double conversion to avoid accuracy issues due to different precision+ return (np.random.randn(2, 3, 2).astype(np.float16).astype(np.float32),)++ def create_model(self, dtype):+ import torch++ class aten_to_from_complex(torch.nn.Module):+ def __init__(self, dtype):+ super().__init__()+ self.dtype = dtype++ def forward(self, x):+ c = torch.view_as_complex(x.to(self.dtype))+ return c.to(x.dtype)++ return aten_to_from_complex(dtype), None, "aten::to"++ @pytest.mark.parametrize("dtype", [torch.float16,+ torch.float32,+ torch.float64])+ @pytest.mark.nightly+ @pytest.mark.precommit+ def test_aten_to_from_complex(self, dtype, ie_device, precision, ir_version):+ self._test(*self.create_model(dtype), ie_device, precision,+ ir_version)