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
[PyTorch] Convert exported programs without run_decompositions (#38078)
Maxim Vafin8c8ab2687970
diff --git a/src/bindings/python/sources.cmake b/src/bindings/python/sources.cmakeindex 9f0f273fcb2..ac470fb6686 100644--- a/src/bindings/python/sources.cmake+++ b/src/bindings/python/sources.cmake@@ -21,6 +21,7 @@ set(OPENVINO_PYTHON_SOURCE_FILES${CMAKE_CURRENT_LIST_DIR}/src/openvino/frontend/paddle/__init__.py${CMAKE_CURRENT_LIST_DIR}/src/openvino/frontend/pytorch/__init__.py${CMAKE_CURRENT_LIST_DIR}/src/openvino/frontend/pytorch/compressed_tensors.py+ ${CMAKE_CURRENT_LIST_DIR}/src/openvino/frontend/pytorch/decoder_base.py${CMAKE_CURRENT_LIST_DIR}/src/openvino/frontend/pytorch/fx_decoder.py${CMAKE_CURRENT_LIST_DIR}/src/openvino/frontend/pytorch/gptq.py${CMAKE_CURRENT_LIST_DIR}/src/openvino/frontend/pytorch/inlined_extension.py@@ -34,7 +35,6 @@ set(OPENVINO_PYTHON_SOURCE_FILES${CMAKE_CURRENT_LIST_DIR}/src/openvino/frontend/pytorch/torchdynamo/compile.py${CMAKE_CURRENT_LIST_DIR}/src/openvino/frontend/pytorch/torchdynamo/decompositions.py${CMAKE_CURRENT_LIST_DIR}/src/openvino/frontend/pytorch/torchdynamo/execute.py- ${CMAKE_CURRENT_LIST_DIR}/src/openvino/frontend/pytorch/torchdynamo/export_decompositions.py${CMAKE_CURRENT_LIST_DIR}/src/openvino/frontend/pytorch/torchdynamo/op_support.py${CMAKE_CURRENT_LIST_DIR}/src/openvino/frontend/pytorch/torchdynamo/partition.py${CMAKE_CURRENT_LIST_DIR}/src/openvino/frontend/pytorch/ts_decoder.pydiff --git a/src/bindings/python/src/openvino/frontend/pytorch/decoder_base.py b/src/bindings/python/src/openvino/frontend/pytorch/decoder_base.pynew file mode 100644index 00000000000..3a2cebeb7d8--- /dev/null+++ b/src/bindings/python/src/openvino/frontend/pytorch/decoder_base.py@@ -0,0 +1,92 @@+# -*- coding: utf-8 -*-+# Copyright (C) 2018-2026 Intel Corporation+# SPDX-License-Identifier: Apache-2.0++# mypy: ignore-errors++from openvino import OVAny+from openvino.frontend.pytorch.py_pytorch_frontend import _FrontEndPytorchDecoder as Decoder+++class TorchDecoderBase(Decoder):+ """Logic shared by the TorchScript and FX decoders.++ Holds the parts of the decoder interface that do not depend on which PyTorch IR is+ being decoded: friendly-name construction, the input-signature fallback, and the+ defaults for capabilities that only one of the two IRs has. Everything that reads+ ``torch`` data structures belongs in the subclasses.+ """++ def __init__(self) -> None:+ super().__init__()+ # Every decoder produced by this decoder is kept here so that none of them is+ # destroyed while the first one is still alive.+ self.m_decoders = []+ self._input_signature = None++ # -- friendly names ----------------------------------------------------------------++ def _node_name_prefix(self):+ """Scope-like prefix for friendly names, or None when the node has no scope."""+ return None++ def mark_node(self, node):+ """Associate an OpenVINO node with the framework node being decoded.++ Subclasses may override this to attach framework data to ``node``; they should+ call ``super().mark_node(node)`` so that the friendly name is still applied.+ """+ name = self.get_op_type()+ if "FrameworkNode" not in node.get_type_name():+ name += "/" + node.get_type_name()+ prefix = self._node_name_prefix()+ node.set_friendly_name(f"{prefix}/{name}" if prefix else name)+ return node++ # -- inputs and outputs ------------------------------------------------------------++ def get_input_signature_name(self, index: int) -> str:+ signature = self._input_signature+ if signature is not None and index < len(signature):+ return signature[index]+ return self.get_input_debug_name(index)++ def output(self, index: int):+ return self.outputs()[index]++ def num_of_outputs(self):+ return len(self.outputs())++ def is_input_inlined(self, index):+ return False++ def get_inlined_input_decoder(self, index):+ return None++ # -- named inputs: FX kwargs only ---------------------------------------------------++ def get_attribute(self, name):+ return OVAny(None)++ def get_named_input(self, name):+ raise RuntimeError(f"{type(self).__name__} has no named inputs")++ # -- optional capabilities ----------------------------------------------------------++ def get_subgraphs(self) -> list:+ return []++ def get_subgraph_size(self) -> int:+ return len(self.get_subgraphs())++ def as_string(self):+ return None++ def may_produce_alias(self, in_index: int, out_index: int) -> bool:+ return False++ def get_rt_info(self):+ return {}++ def has_converter(self):+ return Falsediff --git a/src/bindings/python/src/openvino/frontend/pytorch/fx_decoder.py b/src/bindings/python/src/openvino/frontend/pytorch/fx_decoder.pyindex 9fd98f96774..2b224f7fe70 100644--- a/src/bindings/python/src/openvino/frontend/pytorch/fx_decoder.py+++ b/src/bindings/python/src/openvino/frontend/pytorch/fx_decoder.py@@ -6,6 +6,8 @@import loggingimport inspect+import operator+from functools import lru_cacheimport torch# Import HigherOrderOperator for detecting higher-order operations (while_loop, cond, etc.)@@ -17,29 +19,64 @@ except ImportError:_HAS_HIGHER_ORDER_OPERATOR = FalseHigherOrderOperator = None-from openvino.frontend.pytorch.py_pytorch_frontend import _FrontEndPytorchDecoder as Decoderfrom openvino.frontend.pytorch.py_pytorch_frontend import _Type as DecoderType+from openvino.frontend.pytorch.decoder_base import TorchDecoderBasefrom openvino import PartialShape, Type as OVType, OVAny, Shapefrom openvino.frontend.pytorch.utils import (- make_constant, fetch_attr, pt_to_ov_type_map, torch_tensor_to_ov_const)+ make_constant, fetch_attr, pt_to_ov_type_map, pt_to_scalar_type_map,+ torch_tensor_to_ov_const)logger = logging.getLogger(__name__)-class BaseFXDecoder(Decoder):+class IndexedNodes:+ """The nodes of an FX graph, with a constant-time reverse lookup.++ Decoders need both positional access (``nodes[i]``, to resolve an input id back to a+ node) and the reverse lookup (``index(node)``, to turn an argument into an input id).+ ``list.index`` makes the reverse lookup linear in the graph size, and it is performed+ once per node plus once per node-valued argument, so a plain list makes decoding the+ whole graph quadratic. ``torch.fx.Node`` hashes and compares by identity, so a dict+ keyed on the node gives the same answer as ``list.index``.+ """++ __slots__ = ("_nodes", "_positions")++ def __init__(self, nodes) -> None:+ self._nodes = list(nodes)+ self._positions = {}+ for position, node in enumerate(self._nodes):+ # Keep the first occurrence, matching list.index.+ self._positions.setdefault(node, position)++ def __len__(self):+ return len(self._nodes)++ def __iter__(self):+ return iter(self._nodes)++ def __getitem__(self, index):+ return self._nodes[index]++ def index(self, node):+ position = self._positions.get(node)+ if position is None:+ raise ValueError(f"{node} is not in the graph")+ return position+++class BaseFXDecoder(TorchDecoderBase):"""Extends Decoder to handle FX graph decoding in PyTorch.Provides a common interface for all FX decoders."""def __init__(self, mark_node_callback=None) -> None:- Decoder.__init__(self)+ super().__init__()self.mark_node_callback = mark_node_callback- # We store every decoder created by this decoder so that- # all them are not deleted until the first decoder is deleted- self.m_decoders = []self._inputs = []self._outputs = []+ self._output_ids = None@staticmethoddef unpack_containers(arg):@@ -61,7 +98,9 @@ class BaseFXDecoder(Decoder):@staticmethoddef arg_to_constant(arg):- if isinstance(arg, list):+ if isinstance(arg, torch.dtype):+ return make_constant(OVType.i64, Shape([]), [pt_to_scalar_type_map[arg]])+ elif isinstance(arg, list):if len(arg) > 0:return make_constant(pt_to_ov_type_map[type(arg[0]).__name__], Shape([len(arg)]), arg)@@ -74,6 +113,8 @@ class BaseFXDecoder(Decoder):return make_constant(OVType.i64, Shape([]), [arg])elif isinstance(arg, float):return make_constant(OVType.f32, Shape([]), [arg])+ elif isinstance(arg, complex):+ return make_constant(OVType.f32, Shape([2]), [arg.real, arg.imag])elif isinstance(arg, str):buf = bytearray(arg, "utf-8")u8_tensor = torch.frombuffer(buf, dtype=torch.uint8)@@ -83,6 +124,10 @@ class BaseFXDecoder(Decoder):@staticmethoddef get_type_for_value(value):if issubclass(type(value), torch.fx.Node):+ tensor = value.meta.get("val")+ if isinstance(tensor, torch.Tensor) and tensor.is_complex():+ # pt_to_ov_type_map already maps complex dtypes to DecoderType.Complex.+ return OVAny(pt_to_ov_type_map[str(tensor.dtype)])if ("tensor_meta" in value.meta.keys()):if value.meta["tensor_meta"] and isinstance(value.meta["tensor_meta"], torch.Tensor):pt_type = value.meta["tensor_meta"].dtype@@ -90,12 +135,16 @@ class BaseFXDecoder(Decoder):ov_type = pt_to_ov_type_map[str(pt_type)]return OVAny(ov_type)return OVAny(OVType.dynamic)+ elif isinstance(value, bool):+ return OVAny(DecoderType.PyScalar(OVAny(OVType.boolean)))elif isinstance(value, int):return OVAny(DecoderType.PyScalar(OVAny(OVType.i64)))elif isinstance(value, float):return OVAny(DecoderType.PyScalar(OVAny(OVType.f32)))- elif isinstance(value, bool):- return OVAny(DecoderType.PyScalar(OVAny(OVType.boolean)))+ elif isinstance(value, complex):+ return OVAny(DecoderType.Complex(OVAny(OVType.f32)))+ elif isinstance(value, str):+ return OVAny(DecoderType.Str())elif isinstance(value, list):if len(value) > 0:return OVAny(DecoderType.List(BaseFXDecoder.get_type_for_value(value[0])))@@ -107,9 +156,6 @@ class BaseFXDecoder(Decoder):# Consider 0 a special case which may mean the input is inlined, but not guaranteedreturn [x if not isinstance(x, InlinedInput) else 0 for x in self._inputs]- def output(self, index):- return self.outputs()[index]-def get_input_debug_name(self, index):return "input" + str(index)@@ -145,31 +191,32 @@ class BaseFXDecoder(Decoder):return "NONE"def mark_node(self, node):+ super().mark_node(node)+ # Hook for attaching framework data to the converted node.if self.mark_node_callback is not None:self.mark_node_callback(self, node)return node- def get_subgraphs(self):- return []-- def get_subgraph_size(self):- return len(self.get_subgraphs())-- def as_string(self):- return None-- def may_produce_alias(self, in_index: int, out_index: int) -> bool:- return False-- def get_rt_info(self):- rt_info = {}- return rt_info-class TorchFXPythonDecoder (BaseFXDecoder):"""Decoder for PyTorch FX GraphModule and Node objects to OpenVINO IR."""- _decomp_table = None+ @staticmethod+ @lru_cache(None)+ def _functional_out_target(target):+ schema = getattr(target, "_schema", None)+ if schema is None or len(schema.returns) != 1:+ return target+ out = next((arg for arg in schema.arguments if arg.name == "out"), None)+ if out is None or out.alias_info is None or not out.alias_info.is_write:+ return target+ args = [(arg.name, str(arg.type), arg.kwarg_only) for arg in schema.arguments if arg.name != "out"]+ for overload in target.overloadpacket.overloads():+ candidate = getattr(target.overloadpacket, overload)+ candidate_args = [(arg.name, str(arg.type), arg.kwarg_only) for arg in candidate._schema.arguments]+ if candidate_args == args and len(candidate._schema.returns) == 1:+ return candidate+ return targetdef __init__(self, pt_module, fx_gm=None, nodes=None,mark_node_callback=None, input_shapes=None,@@ -189,7 +236,7 @@ class TorchFXPythonDecoder (BaseFXDecoder):if isinstance(pt_module, torch.fx.graph_module.GraphModule):self._input_is_list = None- self._nodes = list(pt_module.graph.nodes)+ self._nodes = IndexedNodes(pt_module.graph.nodes)found_types = []found_shapes = []for i, value in enumerate(self._nodes):@@ -235,7 +282,17 @@ class TorchFXPythonDecoder (BaseFXDecoder):# Check if this is a higher-order operation that needs special tuple handlingis_higher_order_op = self._is_higher_order_op(pt_module)- for arg_idx, arg in enumerate(pt_module.args):+ args = list(pt_module.args)+ schema = getattr(pt_module.target, "_schema", None)+ if schema is not None:+ # Export omits arguments equal to their defaults. Present positional+ # defaults to the shared ATen converters just as TorchScript does.+ for argument in schema.arguments[len(args):]:+ if argument.kwarg_only:+ break+ args.append(pt_module.kwargs.get(argument.name, argument.default_value))++ for arg_idx, arg in enumerate(args):is_subgraph, graph_module = self._is_subgraph_arg(arg)if is_subgraph:@@ -279,23 +336,6 @@ class TorchFXPythonDecoder (BaseFXDecoder):to the ``target_op`` that the C++ frontend expects for``ConversionExtension`` lookup."""- from packaging import version- if version.parse(torch.__version__) >= version.parse("2.6"):- if cls._decomp_table is None:- from torch.export.decomp_utils import CustomDecompTable- from openvino.frontend.pytorch.torchdynamo.export_decompositions import ops_to_not_decompose- cls._decomp_table = CustomDecompTable()- for op in ops_to_not_decompose():- try:- cls._decomp_table.pop(op)- except KeyError as e:- logging.warning("Operation %s not found in decomp table", op, exc_info=e)- exported_program = exported_program.run_decompositions(cls._decomp_table)- elif version.parse(torch.__version__) >= version.parse("2.2"):- from torch._decomp import get_decompositions- from openvino.frontend.pytorch.torchdynamo.export_decompositions import get_export_decomposition_list- decomp = get_decompositions(get_export_decomposition_list())- exported_program = exported_program.run_decompositions(decomp_table=decomp)gm = exported_program.module()logger.debug(gm.code)return cls(gm, dynamic_shapes=dynamic_shapes,@@ -416,9 +456,12 @@ class TorchFXPythonDecoder (BaseFXDecoder):@staticmethoddef get_found_dtype(value) -> str:- # If input is a tensor, read the data type from meta data- if hasattr(value, "meta") and ("tensor_meta" in value.meta.keys()) and value.meta["tensor_meta"]:- return OVAny(pt_to_ov_type_map[str(value.meta["tensor_meta"].dtype)])+ # Deserialized exports retain FakeTensor values but may omit tensor_meta.+ if hasattr(value, "meta"):+ for key in ("tensor_meta", "val"):+ metadata = value.meta.get(key)+ if hasattr(metadata, "dtype"):+ return OVAny(pt_to_ov_type_map[str(metadata.dtype)])return Nonedef _is_higher_order_op(self, node):@@ -464,11 +507,6 @@ class TorchFXPythonDecoder (BaseFXDecoder):return True, subgraphreturn False, None- def get_input_signature_name(self, index: int) -> str:- if self._input_signature is not None and index < len(self._input_signature):- return self._input_signature[index]- return self.get_input_debug_name(index)-def get_input_shape(self, index):if index < len(self.input_shapes) and self.input_shapes[index] is not None:return PartialShape(self.input_shapes[index])@@ -594,11 +632,13 @@ class TorchFXPythonDecoder (BaseFXDecoder):return decoderdef get_op_type(self):+ if isinstance(self.pt_module, torch.fx.GraphModule):+ return "GraphModule"if self.pt_module.op == "call_function":if type(self.pt_module.target).__name__ == "EdgeOpOverload":name = self.pt_module.target.__name__else:- name = str(self.pt_module.target)+ name = str(self._functional_out_target(self.pt_module.target))if self._module_extension_target_ops:if name in self._module_extension_target_ops:return self._module_extension_target_ops[name]@@ -608,41 +648,68 @@ class TorchFXPythonDecoder (BaseFXDecoder):else:return "UNKNOWN_TYPE_" + str(self.pt_module.op)- def outputs(self):- return [o[1] for o in self._outputs]+ def get_schema(self):+ schema = getattr(getattr(self.pt_module, "target", None), "_schema", None)+ return str(schema) if schema is not None else "NONE"- def _raw_outputs(self):- return [self._nodes[x[1]] for x in self._outputs]+ def may_produce_alias(self, in_index: int, out_index: int) -> bool:+ if not isinstance(self.pt_module, torch.fx.Node):+ return False+ input_node = self._raw_input(in_index)+ input_value = input_node.meta.get("val") if isinstance(input_node, torch.fx.Node) else None+ output_value = self.pt_module.meta.get("val")+ if self.pt_module.target is operator.getitem:+ producer_schema = getattr(getattr(input_node, "target", None), "_schema", None)+ if producer_schema is None or not producer_schema.returns[0].alias_info:+ return False+ return isinstance(input_value, (tuple, list)) and isinstance(output_value, torch.Tensor) and any(+ isinstance(value, torch.Tensor) and torch._C._is_alias_of(value, output_value)+ for value in input_value)+ schema = getattr(self.pt_module.target, "_schema", None)+ if schema is None:+ return False+ # Each schema.arguments/returns access materializes a fresh list of Argument objects.+ arguments, returns = schema.arguments, schema.returns+ if in_index >= len(arguments) or out_index >= len(returns):+ return False+ input_alias = arguments[in_index].alias_info+ output_alias = returns[out_index].alias_info+ if input_alias is None or output_alias is None:+ return False+ # Reshape and contiguous may copy. FakeTensor metadata distinguishes the+ # actual storage relationship without running shape propagation again.+ if isinstance(input_value, torch.Tensor):+ values = output_value if isinstance(output_value, (list, tuple)) else [output_value]+ return any(isinstance(value, torch.Tensor) and torch._C._is_alias_of(input_value, value)+ for value in values)+ return bool(input_alias.after_set.intersection(output_alias.after_set))- def _raw_output(self, index):- return self._raw_outputs()[index]+ def outputs(self):+ if self._output_ids is None:+ self._output_ids = [o[1] for o in self._outputs]+ return self._output_ids- def _raw_inputs(self):- return [- self._nodes[x] if not isinstance(x, InlinedInput) and x < len(self._nodes) else x.data- for x in self._inputs- ]+ def _raw_output(self, index):+ return self._nodes[self._outputs[index][1]]def _raw_input(self, index):- return self._raw_inputs()[index]-- def num_of_outputs(self):- return len(self.outputs())+ item = self._inputs[index]+ if not isinstance(item, InlinedInput) and item < len(self._nodes):+ return self._nodes[item]+ return item.datadef output_list_size(self):+ value = self.pt_module.meta.get("val")+ if isinstance(value, (tuple, list)):+ return len(value)max_out_id = -1for user in self.pt_module.users:- if "<built-in function getitem>" == str(user.target) and max_out_id < user.args[1]:+ if user.target is operator.getitem and max_out_id < user.args[1]:max_out_id = user.args[1]return max_out_id + 1- def mark_node(self, node):- name = self.get_op_type()- if "FrameworkNode" not in node.get_type_name():- name += "/" + node.get_type_name()- node.set_friendly_name(self.pt_module.name + "/" + name)- super().mark_node(node)- return node+ def _node_name_prefix(self):+ return self.pt_module.namedef as_constant(self):assert self.pt_module.op == "get_attr", "Only get_attr is supported"@@ -709,9 +776,6 @@ class InlinedInputDecoder (BaseFXDecoder):def outputs(self):return [0]- def num_of_outputs(self):- return 1-def get_input_shape(self, index):return PartialShape.dynamic()@@ -719,7 +783,10 @@ class InlinedInputDecoder (BaseFXDecoder):return OVAny(OVType.dynamic)def get_output_type(self, index):- return OVAny(OVType.dynamic)+ return self.get_type_for_value(self.inlined_input.data)++ def as_string(self):+ return self.inlined_input.data if isinstance(self.inlined_input.data, str) else Nonedef input_is_none(self, index):if index < len(self._inputs) and isinstance(self._inputs[index], InlinedInput):@@ -732,11 +799,3 @@ class InlinedInputDecoder (BaseFXDecoder):if constant is not None:return constant.outputs()return []-- def mark_node(self, node):- name = self.get_op_type()- if "FrameworkNode" not in node.get_type_name():- name += "/" + node.get_type_name()- node.set_friendly_name(name)- super().mark_node(node)- return nodediff --git a/src/bindings/python/src/openvino/frontend/pytorch/torchdynamo/decompositions.py b/src/bindings/python/src/openvino/frontend/pytorch/torchdynamo/decompositions.pyindex 0eb8604302b..ee41c85da92 100644--- a/src/bindings/python/src/openvino/frontend/pytorch/torchdynamo/decompositions.py+++ b/src/bindings/python/src/openvino/frontend/pytorch/torchdynamo/decompositions.py@@ -130,260 +130,3 @@ def get_aot_decomposition_list():def get_inf_decomposition_list():return [torch.ops.aten.nll_loss_forward.default]---def get_export_decomposition_list():- # list of decompositions from torch._decomp.core_aten_decompositions- # removed _backward ops and ops supported without decomposition- decomp = [- torch.ops.aten.addcdiv,- torch.ops.aten.addcdiv_,- torch.ops.aten.addcmul,- torch.ops.aten.addcmul_,- torch.ops.aten.addr,- torch.ops.aten.affine_grid_generator,- torch.ops.aten.all,- torch.ops.aten.aminmax,- torch.ops.aten.arange.default,- torch.ops.aten.arange.start,- torch.ops.aten.baddbmm,- torch.ops.aten.binary_cross_entropy,- torch.ops.aten.binary_cross_entropy_with_logits,- torch.ops.aten.block_diag,- torch.ops.aten.celu,- torch.ops.aten.celu_,- torch.ops.aten.clamp_max,- torch.ops.aten.clamp_min,- torch.ops.aten.count_nonzero,- torch.ops.aten.linalg_cross,- torch.ops.aten.cudnn_batch_norm,- torch.ops.aten.deg2rad,- torch.ops.aten.deg2rad_,- torch.ops.aten.detach,- torch.ops.aten.diag_embed,- torch.ops.aten.dot,- torch.ops.aten.vdot,- torch.ops.aten.elu,- torch.ops.aten.elu_,- torch.ops.aten._embedding_bag,- torch.ops.aten.empty_like,- torch.ops.aten._euclidean_dist.default,- torch.ops.aten.expand_as,- torch.ops.aten.eye,- torch.ops.aten.fill,- torch.ops.aten.fill_,- torch.ops.aten.floor_divide,- torch.ops.aten.frac,- torch.ops.aten.frac_,- torch.ops.aten._fused_moving_avg_obs_fq_helper,- torch.ops.aten.gelu_,- torch.ops.aten.glu,- torch.ops.aten.hardshrink,- torch.ops.aten.hardsigmoid,- torch.ops.aten.hardsigmoid_,- torch.ops.aten.hardswish,- torch.ops.aten.hardswish_,- torch.ops.aten.hardtanh_,- torch.ops.aten.heaviside,- torch.ops.aten.heaviside_,- torch.ops.aten.huber_loss,- torch.ops.aten.im2col,- torch.ops.aten.index_add,- torch.ops.aten.index_add_,- torch.ops.aten.index_copy,- torch.ops.aten.index_copy_,- torch.ops.aten.index_fill,- torch.ops.aten.index_fill_,- torch.ops.aten.isin,- torch.ops.aten.isneginf,- torch.ops.aten.isposinf,- torch.ops.aten.l1_loss,- torch.ops.aten.leaky_relu_,- torch.ops.aten.lerp,- torch.ops.aten.lerp_,- torch.ops.aten.linspace,- torch.ops.aten.logaddexp,- torch.ops.aten.logaddexp2,- torch.ops.aten.logit,- torch.ops.aten.logit_,- torch.ops.aten.log_sigmoid_forward,- torch.ops.aten.logspace,- torch.ops.aten.logsumexp.default,- torch.ops.aten.masked_fill,- torch.ops.aten.masked_fill_,- torch.ops.aten.mish,- torch.ops.aten.mish_,- torch.ops.aten.mse_loss,- torch.ops.aten.multi_margin_loss,- torch.ops.aten.multilabel_margin_loss_forward,- torch.ops.aten.mv,- torch.ops.aten.mvlgamma,- torch.ops.aten.mvlgamma_,- torch.ops.aten.nansum,- torch.ops.aten.nan_to_num,- torch.ops.aten.nan_to_num_,- torch.ops.aten.narrow,- torch.ops.aten.new_empty,- torch.ops.aten.new_full,- torch.ops.aten.new_ones,- torch.ops.aten.new_zeros,- torch.ops.aten.nll_loss_forward,- torch.ops.aten.norm,- torch.ops.aten.ones,- torch.ops.aten.ones_like,- torch.ops.aten._prelu_kernel,- torch.ops.aten._reshape_alias,- torch.ops.aten.rad2deg,- torch.ops.aten.rad2deg_,- torch.ops.aten.reflection_pad1d,- torch.ops.aten.reflection_pad2d,- torch.ops.aten.reflection_pad3d,- torch.ops.aten.replication_pad1d,- torch.ops.aten.replication_pad2d,- torch.ops.aten.replication_pad3d,- torch.ops.aten.renorm,- torch.ops.aten.renorm_,- torch.ops.aten.resize_as,- torch.ops.aten.roll,- torch.ops.aten.rot90,- torch.ops.aten.rrelu_with_noise,- torch.ops.aten.rrelu_with_noise_,- torch.ops.aten.rsub,- torch.ops.aten.select_scatter,- torch.ops.aten.sgn,- torch.ops.aten.sgn_,- torch.ops.aten.silu,- torch.ops.aten.silu_,- torch.ops.aten.sinc,- torch.ops.aten.sinc_,- torch.ops.aten.smooth_l1_loss,- torch.ops.aten.soft_margin_loss,- torch.ops.aten.softplus,- torch.ops.aten.softshrink,- torch.ops.aten.special_entr,- torch.ops.aten.special_log_ndtr,- torch.ops.aten.special_xlog1py,- torch.ops.aten.split.Tensor,- torch.ops.aten.split_with_sizes_copy,- torch.ops.aten.squeeze.default,- torch.ops.aten.squeeze.dim,- torch.ops.aten.std,- torch.ops.aten.std_mean,- torch.ops.aten.stack,- torch.ops.aten.sum.default,- torch.ops.aten.sum.out,- torch.ops.aten.t,- torch.ops.aten.take,- torch.ops.aten.threshold,- torch.ops.aten.threshold_,- torch.ops.aten.trace,- torch.ops.aten.transpose.int,- torch.ops.aten.tril,- torch.ops.aten.tril_,- torch.ops.aten.triu,- torch.ops.aten.triu_,- torch.ops.aten.unbind,- torch.ops.aten.unfold_copy,- torch.ops.aten._unsafe_index,- torch.ops.aten.unsafe_split.Tensor,- torch.ops.aten.unsafe_split_with_sizes,- torch.ops.aten._unsafe_view,- torch.ops.aten.view_as_complex,- torch.ops.aten.xlogy,- torch.ops.aten.xlogy_,- torch.ops.aten.zero,- torch.ops.aten.zero_,- torch.ops.aten.zeros,- torch.ops.aten.zeros_like,- torch.ops.aten._weight_norm_interface,- ]- try:- from packaging import version- if version.parse(torch.__version__) >= version.parse("2.3"):- decomp += [- torch.ops.aten._lazy_clone,- torch.ops.aten._test_parallel_materialize,- torch.ops.aten._chunk_cat,- ]- except ImportError:- pass- return decomp---def ops_to_not_decompose():- # list of operations that shouldn't be decomposed because- # OpenVINO frontend handles them directly and more efficiently- return [- # Activation functions - each maps to a single dedicated OV op- torch.ops.aten.celu.default,- torch.ops.aten.elu_.default,- torch.ops.aten.glu.default,- torch.ops.aten.hardsigmoid.default,- torch.ops.aten.hardswish.default,- torch.ops.aten.hardswish_.default,- torch.ops.aten.hardtanh_.default,- torch.ops.aten.leaky_relu_.default,- torch.ops.aten.log_sigmoid_forward.default,- torch.ops.aten.mish.default,- torch.ops.aten.silu.default,- torch.ops.aten.silu_.default,- # Normalization- torch.ops.aten.linear.default,- torch.ops.aten.rms_norm.default,- # Math and reduction ops with dedicated translators- torch.ops.aten.all.default,- torch.ops.aten.argsort.default,- torch.ops.aten.argsort.stable,- torch.ops.aten.baddbmm.default,- torch.ops.aten.dot.default,- torch.ops.aten.logaddexp.default,- torch.ops.aten.logsumexp.default,- torch.ops.aten.outer.default,- torch.ops.aten.rad2deg.default,- torch.ops.aten.std.correction,- # Spatial and structural ops- torch.ops.aten.channel_shuffle.default,- torch.ops.aten.col2im.default,- torch.ops.aten.pixel_shuffle.default,- torch.ops.aten.pixel_unshuffle.default,- torch.ops.aten.reflection_pad1d.default,- torch.ops.aten.reflection_pad2d.default,- torch.ops.aten.reflection_pad3d.default,- torch.ops.aten.roll.default,- # Index and scatter ops- torch.ops.aten.index_add.default,- torch.ops.aten.index_add_.default,- torch.ops.aten.index_copy.default,- torch.ops.aten.index_fill.int_Scalar,- torch.ops.aten.index_fill_.int_Scalar,- torch.ops.aten.masked_fill.Scalar,- torch.ops.aten.masked_fill.Tensor,- torch.ops.aten.masked_fill_.Scalar,- torch.ops.aten.masked_fill_.Tensor,- torch.ops.aten.select_scatter.default,- # Tensor creation and manipulation- torch.ops.aten.hstack.default,- torch.ops.aten.linalg_cross.default,- torch.ops.aten.linspace.default,- torch.ops.aten.one_hot.default,- torch.ops.aten.repeat_interleave.self_int,- torch.ops.aten.repeat_interleave.self_Tensor,- # Note: aten.take_along_dim.default is not listed here because- # the translator doesn't handle the 2-input case (dim=None)- torch.ops.aten.tril.default,- torch.ops.aten.triu.default,- torch.ops.aten.vstack.default,- # Upsampling / interpolation- torch.ops.aten.upsample_nearest1d.default,- torch.ops.aten.upsample_nearest1d.vec,- torch.ops.aten.upsample_nearest2d.default,- torch.ops.aten.upsample_nearest2d.vec,- torch.ops.aten.upsample_nearest3d.default,- torch.ops.aten.upsample_nearest3d.vec,- torch.ops.aten.upsample_linear1d.vec,- torch.ops.aten.upsample_bilinear2d.vec,- torch.ops.aten.upsample_trilinear3d.vec,- torch.ops.aten.upsample_bicubic2d.vec,- # Attention- torch.ops.aten.scaled_dot_product_attention.default,- ]diff --git a/src/bindings/python/src/openvino/frontend/pytorch/torchdynamo/export_decompositions.py b/src/bindings/python/src/openvino/frontend/pytorch/torchdynamo/export_decompositions.pydeleted file mode 100644index a1a353342bb..00000000000--- a/src/bindings/python/src/openvino/frontend/pytorch/torchdynamo/export_decompositions.py+++ /dev/null@@ -1,272 +0,0 @@-# -*- coding: utf-8 -*--# Copyright (C) 2018-2026 Intel Corporation-# SPDX-License-Identifier: Apache-2.0--"""Decomposition lists for the ``torch.export`` path.--Unlike ``decompositions.py``, this module does **not** register any global-decompositions (via ``@register_decomposition``). It is safe to import from-code paths that must not mutate PyTorch's global decomposition tables — in-particular from ``TorchFXPythonDecoder.from_exported_program``, which may run-before ``torch._inductor`` is imported.-"""--import torch---def get_export_decomposition_list() -> list:- # list of decompositions from torch._decomp.core_aten_decompositions- # removed _backward ops and ops supported without decomposition- decomp = [- torch.ops.aten.addcdiv,- torch.ops.aten.addcdiv_,- torch.ops.aten.addcmul,- torch.ops.aten.addcmul_,- torch.ops.aten.addr,- torch.ops.aten.affine_grid_generator,- torch.ops.aten.all,- torch.ops.aten.aminmax,- torch.ops.aten.arange.default,- torch.ops.aten.arange.start,- torch.ops.aten.baddbmm,- torch.ops.aten.binary_cross_entropy,- torch.ops.aten.binary_cross_entropy_with_logits,- torch.ops.aten.block_diag,- torch.ops.aten.celu,- torch.ops.aten.celu_,- torch.ops.aten.clamp_max,- torch.ops.aten.clamp_min,- torch.ops.aten.count_nonzero,- torch.ops.aten.linalg_cross,- torch.ops.aten.cudnn_batch_norm,- torch.ops.aten.deg2rad,- torch.ops.aten.deg2rad_,- torch.ops.aten.detach,- torch.ops.aten.diag_embed,- torch.ops.aten.dot,- torch.ops.aten.vdot,- torch.ops.aten.elu,- torch.ops.aten.elu_,- torch.ops.aten._embedding_bag,- torch.ops.aten.empty_like,- torch.ops.aten._euclidean_dist.default,- torch.ops.aten.expand_as,- torch.ops.aten.eye,- torch.ops.aten.fill,- torch.ops.aten.fill_,- torch.ops.aten.floor_divide,- torch.ops.aten.frac,- torch.ops.aten.frac_,- torch.ops.aten._fused_moving_avg_obs_fq_helper,- torch.ops.aten.gelu_,- torch.ops.aten.glu,- torch.ops.aten.hardshrink,- torch.ops.aten.hardsigmoid,- torch.ops.aten.hardsigmoid_,- torch.ops.aten.hardswish,- torch.ops.aten.hardswish_,- torch.ops.aten.hardtanh_,- torch.ops.aten.heaviside,- torch.ops.aten.heaviside_,- torch.ops.aten.huber_loss,- torch.ops.aten.im2col,- torch.ops.aten.index_add,- torch.ops.aten.index_add_,- torch.ops.aten.index_copy,- torch.ops.aten.index_copy_,- torch.ops.aten.index_fill,- torch.ops.aten.index_fill_,- torch.ops.aten.isin,- torch.ops.aten.isneginf,- torch.ops.aten.isposinf,- torch.ops.aten.l1_loss,- torch.ops.aten.leaky_relu_,- torch.ops.aten.lerp,- torch.ops.aten.lerp_,- torch.ops.aten.linspace,- torch.ops.aten.logaddexp,- torch.ops.aten.logaddexp2,- torch.ops.aten.logit,- torch.ops.aten.logit_,- torch.ops.aten.log_sigmoid_forward,- torch.ops.aten.logspace,- torch.ops.aten.logsumexp.default,- torch.ops.aten.masked_fill,- torch.ops.aten.masked_fill_,- torch.ops.aten.mish,- torch.ops.aten.mish_,- torch.ops.aten.mse_loss,- torch.ops.aten.multi_margin_loss,- torch.ops.aten.multilabel_margin_loss_forward,- torch.ops.aten.mv,- torch.ops.aten.mvlgamma,- torch.ops.aten.mvlgamma_,- torch.ops.aten.nansum,- torch.ops.aten.nan_to_num,- torch.ops.aten.nan_to_num_,- torch.ops.aten.narrow,- torch.ops.aten.new_empty,- torch.ops.aten.new_full,- torch.ops.aten.new_ones,- torch.ops.aten.new_zeros,- torch.ops.aten.nll_loss_forward,- torch.ops.aten.norm,- torch.ops.aten.ones,- torch.ops.aten.ones_like,- torch.ops.aten._prelu_kernel,- torch.ops.aten._reshape_alias,- torch.ops.aten.rad2deg,- torch.ops.aten.rad2deg_,- torch.ops.aten.reflection_pad1d,- torch.ops.aten.reflection_pad2d,- torch.ops.aten.reflection_pad3d,- torch.ops.aten.replication_pad1d,- torch.ops.aten.replication_pad2d,- torch.ops.aten.replication_pad3d,- torch.ops.aten.renorm,- torch.ops.aten.renorm_,- torch.ops.aten.resize_as,- torch.ops.aten.roll,- torch.ops.aten.rot90,- torch.ops.aten.rrelu_with_noise,- torch.ops.aten.rrelu_with_noise_,- torch.ops.aten.rsub,- torch.ops.aten.select_scatter,- torch.ops.aten.sgn,- torch.ops.aten.sgn_,- torch.ops.aten.silu,- torch.ops.aten.silu_,- torch.ops.aten.sinc,- torch.ops.aten.sinc_,- torch.ops.aten.smooth_l1_loss,- torch.ops.aten.soft_margin_loss,- torch.ops.aten.softplus,- torch.ops.aten.softshrink,- torch.ops.aten.special_entr,- torch.ops.aten.special_log_ndtr,- torch.ops.aten.special_xlog1py,- torch.ops.aten.split.Tensor,- torch.ops.aten.split_with_sizes_copy,- torch.ops.aten.squeeze.default,- torch.ops.aten.squeeze.dim,- torch.ops.aten.std,- torch.ops.aten.std_mean,- torch.ops.aten.stack,- torch.ops.aten.sum.default,- torch.ops.aten.sum.out,- torch.ops.aten.t,- torch.ops.aten.take,- torch.ops.aten.threshold,- torch.ops.aten.threshold_,- torch.ops.aten.trace,- torch.ops.aten.transpose.int,- torch.ops.aten.tril,- torch.ops.aten.tril_,- torch.ops.aten.triu,- torch.ops.aten.triu_,- torch.ops.aten.unbind,- torch.ops.aten.unfold_copy,- torch.ops.aten._unsafe_index,- torch.ops.aten.unsafe_split.Tensor,- torch.ops.aten.unsafe_split_with_sizes,- torch.ops.aten._unsafe_view,- torch.ops.aten.view_as_complex,- torch.ops.aten.xlogy,- torch.ops.aten.xlogy_,- torch.ops.aten.zero,- torch.ops.aten.zero_,- torch.ops.aten.zeros,- torch.ops.aten.zeros_like,- torch.ops.aten._weight_norm_interface,- ]- try:- from packaging import version- if version.parse(torch.__version__) >= version.parse("2.3"):- decomp += [- torch.ops.aten._lazy_clone,- torch.ops.aten._test_parallel_materialize,- torch.ops.aten._chunk_cat,- ]- except ImportError:- pass- return decomp---def ops_to_not_decompose() -> list:- # list of operations that shouldn't be decomposed because- # OpenVINO frontend handles them directly and more efficiently- return [- # Activation functions - each maps to a single dedicated OV op- torch.ops.aten.celu.default,- torch.ops.aten.elu_.default,- torch.ops.aten.glu.default,- torch.ops.aten.hardsigmoid.default,- torch.ops.aten.hardswish.default,- torch.ops.aten.hardswish_.default,- torch.ops.aten.hardtanh_.default,- torch.ops.aten.leaky_relu_.default,- torch.ops.aten.log_sigmoid_forward.default,- torch.ops.aten.mish.default,- torch.ops.aten.rrelu.default,- torch.ops.aten.silu.default,- torch.ops.aten.silu_.default,- # Normalization- torch.ops.aten.linear.default,- torch.ops.aten.rms_norm.default,- # Math and reduction ops with dedicated translators- torch.ops.aten.all.default,- torch.ops.aten.argsort.default,- torch.ops.aten.argsort.stable,- torch.ops.aten.baddbmm.default,- torch.ops.aten.dot.default,- torch.ops.aten.logaddexp.default,- torch.ops.aten.logsumexp.default,- torch.ops.aten.outer.default,- torch.ops.aten.rad2deg.default,- torch.ops.aten.std.correction,- # Spatial and structural ops- torch.ops.aten.channel_shuffle.default,- torch.ops.aten.col2im.default,- torch.ops.aten.pixel_shuffle.default,- torch.ops.aten.pixel_unshuffle.default,- torch.ops.aten.reflection_pad1d.default,- torch.ops.aten.reflection_pad2d.default,- torch.ops.aten.reflection_pad3d.default,- torch.ops.aten.roll.default,- # Index and scatter ops- torch.ops.aten.index_add.default,- torch.ops.aten.index_add_.default,- torch.ops.aten.index_copy.default,- torch.ops.aten.index_fill.int_Scalar,- torch.ops.aten.index_fill_.int_Scalar,- torch.ops.aten.masked_fill.Scalar,- torch.ops.aten.masked_fill.Tensor,- torch.ops.aten.masked_fill_.Scalar,- torch.ops.aten.masked_fill_.Tensor,- torch.ops.aten.select_scatter.default,- # Tensor creation and manipulation- torch.ops.aten.hstack.default,- torch.ops.aten.linalg_cross.default,- torch.ops.aten.linspace.default,- torch.ops.aten.one_hot.default,- torch.ops.aten.repeat_interleave.self_int,- torch.ops.aten.repeat_interleave.self_Tensor,- # Note: aten.take_along_dim.default is not listed here because- # the translator doesn't handle the 2-input case (dim=None)- torch.ops.aten.tril.default,- torch.ops.aten.triu.default,- torch.ops.aten.vstack.default,- # Upsampling / interpolation- torch.ops.aten.upsample_nearest1d.default,- torch.ops.aten.upsample_nearest1d.vec,- torch.ops.aten.upsample_nearest2d.default,- torch.ops.aten.upsample_nearest2d.vec,- torch.ops.aten.upsample_nearest3d.default,- torch.ops.aten.upsample_nearest3d.vec,- torch.ops.aten.upsample_linear1d.vec,- torch.ops.aten.upsample_bilinear2d.vec,- torch.ops.aten.upsample_trilinear3d.vec,- torch.ops.aten.upsample_bicubic2d.vec,- # Attention- torch.ops.aten.scaled_dot_product_attention.default,- ]diff --git a/src/bindings/python/src/openvino/frontend/pytorch/ts_decoder.py b/src/bindings/python/src/openvino/frontend/pytorch/ts_decoder.pyindex f197ccc86e7..6ad4ff35879 100644--- a/src/bindings/python/src/openvino/frontend/pytorch/ts_decoder.py+++ b/src/bindings/python/src/openvino/frontend/pytorch/ts_decoder.py@@ -7,12 +7,11 @@import inspectimport loggingimport typing+from functools import lru_cacheimport torch-from openvino.frontend.pytorch.py_pytorch_frontend import (- _FrontEndPytorchDecoder as Decoder,- _Type as DecoderType-)+from openvino.frontend.pytorch.py_pytorch_frontend import _Type as DecoderType+from openvino.frontend.pytorch.decoder_base import TorchDecoderBasefrom openvino import op, PartialShape, Type as OVType, OVAnyfrom openvino.frontend.pytorch.utils import (ivalue_to_constant,@@ -32,12 +31,18 @@ from openvino.frontend.pytorch.patch_functions import FunctionsPatcherlog = logging.getLogger(__name__)+@lru_cache(maxsize=None)+def _parse_schema(schema_text: str):+ """Parse a TorchScript schema string. Nodes of the same operator share one schema text."""+ return torch._C.parse_schema(schema_text)++# A marker for a special type of conversion extension that is inlined in Trampoline classclass InlineConversionExtension:pass-class TorchScriptPythonDecoder(Decoder):+class TorchScriptPythonDecoder(TorchDecoderBase):def __init__(self,pt_module,@@ -49,15 +54,16 @@ class TorchScriptPythonDecoder(Decoder):constant_cache=None,module_extensions=None,trace_kwargs=None,+ getattr_cache=None,):super().__init__()- # We store every decoder created by this decoder so that all them are- # not deleted until the first decoder is deleted- self.m_decoders = []- self._input_signature = Noneself._shared_memory = shared_memoryself._input_is_list = Falseself.constant_cache = constant_cache if constant_cache is not None else dict() # noqa: C408+ # Resolving a prim::GetAttr chain walks the graph and the module tree. The same+ # node is resolved once per consumer, so results are shared by all decoders of+ # one module, like constant_cache.+ self.getattr_cache = getattr_cache if getattr_cache is not None else dict() # noqa: C408self.module_extensions = module_extensionsself.config = Noneself.out_debug_name_overwrites = {}@@ -95,6 +101,11 @@ class TorchScriptPythonDecoder(Decoder):self.pt_module = pt_moduleself.raw_inputs = list(self.graph_element.inputs())self.raw_outputs = list(self.graph_element.outputs())+ # A Value's unique id never changes, so derive the id lists once instead of+ # rebuilding them on every inputs()/outputs() call from the C++ side.+ self._input_ids = [x.unique() for x in self.raw_inputs]+ self._output_ids = [x.unique() for x in self.raw_outputs]+ self._subgraphs = Noneif self._input_signature is not None:if "self" in self.raw_inputs[0].debugName():self._input_signature.insert(0, "self")@@ -205,17 +216,20 @@ class TorchScriptPythonDecoder(Decoder):self._input_signature = input_signaturereturn f_model+ def _value_from_getattr(self, getattr_node):+ """Cached get_value_from_getattr for this decoder's module."""+ cached = self.getattr_cache.get(getattr_node)+ if cached is None:+ cached = get_value_from_getattr(getattr_node, self.pt_module)+ self.getattr_cache[getattr_node] = cached+ return cached+def inputs(self) -> list:- return [x.unique() for x in self.raw_inputs]+ return self._input_idsdef get_input_debug_name(self, index: int) -> str:return self._raw_input(index).debugName()- def get_input_signature_name(self, index: int) -> str:- if self._input_signature is not None and index < len(self._input_signature):- return self._input_signature[index]- return self.get_input_debug_name(index)-def get_input_shape(self, index: int):raw_input = self._raw_input(index)return self.get_shape_for_value(raw_input)@@ -312,6 +326,7 @@ class TorchScriptPythonDecoder(Decoder):shared_memory=self._shared_memory,constant_cache=self.constant_cache,module_extensions=self.module_extensions,+ getattr_cache=self.getattr_cache,)self.m_decoders.append(decoder)node_visitor(decoder)@@ -320,6 +335,12 @@ class TorchScriptPythonDecoder(Decoder):return "ts"def get_subgraphs(self) -> list:+ # Called once per node by get_subgraph_size, and inlining below is not free.+ if self._subgraphs is None:+ self._subgraphs = self._collect_subgraphs()+ return self._subgraphs++ def _collect_subgraphs(self) -> list:if self.graph_element.kind() in ["prim::PythonOp", "prim::fork"]:if "Subgraph" in self.graph_element.attributeNames():assert isinstance(@@ -339,7 +360,7 @@ class TorchScriptPythonDecoder(Decoder):if self.graph_element.kind() == "prim::fork":in0 = self.raw_inputs[0]if in0.node().kind() == "prim::GetAttr":- module, _ = get_value_from_getattr(in0.node(), self.pt_module)+ module, _ = self._value_from_getattr(in0.node())decoder = TorchScriptPythonDecoder(module,self.get_subgraphs()[index],alias_db=self.alias_db,@@ -358,6 +379,8 @@ class TorchScriptPythonDecoder(Decoder):return trampoline, getattr(trampoline, "target_extension", None)def get_op_type(self) -> str:+ if not isinstance(self.graph_element, torch.Node):+ return "prim::Graph"if op_extension := self.get_op_extension():trampoline, target_extension = op_extensionif isinstance(target_extension, ModuleExtension):@@ -382,7 +405,7 @@ class TorchScriptPythonDecoder(Decoder):return self.graph_element.schema()def outputs(self) -> list:- return [x.unique() for x in self.raw_outputs]+ return self._output_idsdef _raw_output(self, index: int):return self.raw_outputs[index]@@ -390,22 +413,9 @@ class TorchScriptPythonDecoder(Decoder):def _raw_input(self, index: int):return self.raw_inputs[index]- def num_of_outputs(self):- return len(self.raw_outputs)-- def output(self, index: int):- return self.outputs()[index]-- def mark_node(self, node):- name = self.get_op_type()- if "FrameworkNode" not in node.get_type_name():- name += "/" + node.get_type_name()- if self.graph_element.scopeName():- scope_name = self.graph_element.scopeName().split("/")[-1]- node.set_friendly_name(scope_name + "/" + name)- else:- node.set_friendly_name(name)- return node+ def _node_name_prefix(self):+ scope_name = self.graph_element.scopeName()+ return scope_name.split("/")[-1] if scope_name else Nonedef _add_name_to_const_and_cache(self, outputs, name, dtype=None):if len(outputs) == 1:@@ -415,8 +425,7 @@ class TorchScriptPythonDecoder(Decoder):self.constant_cache[name] = (outputs, dtype)def try_decode_get_attr(self):- pt_value, name = get_value_from_getattr(- self.graph_element, self.pt_module)+ pt_value, name = self._value_from_getattr(self.graph_element)assert pt_value is not None, "Couldn't retrieve value from prim::GetAttr"if isinstance(pt_value, torch.ScriptObject):# We assume this is __torch__.torch.classes.quantized.Conv2dPackedParamsBase@@ -545,24 +554,21 @@ class TorchScriptPythonDecoder(Decoder):else:in_node = r_input.node()if in_node.kind() == "prim::GetAttr":- pt_value, _ = get_value_from_getattr(- in_node, self.pt_module)+ pt_value, _ = self._value_from_getattr(in_node)return pt_value is Nonereturn Falsedef may_produce_alias(self, in_index: int, out_index: int) -> bool:- if self.get_op_type() in [- "aten::conv1d",- "aten::conv2d",- "aten::conv3d",- "aten::_convolution",- "aten::matmul",- "aten::clone",- ]:- # AliasDB::may_contain_alias sometimes return True for tensors produced- # by convolution or matmul, we have to workaround that- return Falsetry:+ schema_text = self.get_schema()+ if schema_text != "(no schema)":+ returns = _parse_schema(schema_text).returns+ if out_index < len(returns):+ result = returns[out_index]+ # Container use can put independent tensors in AliasDb's wildcard set.+ # A tensor return without a schema alias annotation has fresh storage.+ if isinstance(result.type, torch.TensorType) and result.alias_info is None:+ return Falsereturn self.alias_db.may_contain_alias(self._raw_input(in_index), self._raw_output(out_index))@@ -572,18 +578,6 @@ class TorchScriptPythonDecoder(Decoder):logging.debug("Failed to get alias information", exc_info=e)return False- def is_input_inlined(self, index):- return False-- def get_inlined_input_decoder(self, index):- return None-- def get_attribute(self, name):- return OVAny(None)-- def get_named_input(self, name):- raise RuntimeError("There is no named inputs in TS graph")-def get_rt_info(self):rt_info = {}if (diff --git a/src/bindings/python/src/openvino/frontend/pytorch/utils.py b/src/bindings/python/src/openvino/frontend/pytorch/utils.pyindex 7a0d141d45a..ced3e9e4474 100644--- a/src/bindings/python/src/openvino/frontend/pytorch/utils.py+++ b/src/bindings/python/src/openvino/frontend/pytorch/utils.py@@ -182,6 +182,29 @@ pt_to_ov_type_map = {"torch.qint32": OVType.i32,}+# torch.dtype to the ScalarType index which TorchScript's ATen schemas take as an integer+# input. This is the inverse of TORCH_TO_OV_TYPE in+# src/frontends/pytorch/src/utils.cpp, which decodes the index back to an OpenVINO type;+# keep the two in sync when PyTorch adds a dtype.+pt_to_scalar_type_map = {+ torch.uint8: 0,+ torch.int8: 1,+ torch.int16: 2,+ torch.int32: 3,+ torch.int64: 4,+ torch.float16: 5,+ torch.float32: 6,+ torch.float64: 7,+ torch.complex32: 8,+ torch.complex64: 9,+ torch.complex128: 10,+ torch.bool: 11,+ torch.qint8: 12,+ torch.quint8: 13,+ torch.qint32: 14,+ torch.bfloat16: 15,+}+wrapper_template = """import torchdiff --git a/src/frontends/pytorch/include/openvino/frontend/pytorch/node_context.hpp b/src/frontends/pytorch/include/openvino/frontend/pytorch/node_context.hppindex f8036127d4e..a7efed6bfa3 100644--- a/src/frontends/pytorch/include/openvino/frontend/pytorch/node_context.hpp+++ b/src/frontends/pytorch/include/openvino/frontend/pytorch/node_context.hpp@@ -53,6 +53,10 @@ public:// TODO: int due to base class uses it, but naturally it should be size_t for PTOutput<Node> get_input(int index) const override;+ Output<Node> resolve_tensor(size_t index) const;++ void mutate_input(const std::string& name, Output<Node> ov_output) const;+Output<Node> get_input(const std::string& name) const override;Any get_values_from_const_input(int index) const override;@@ -129,6 +133,8 @@ public:std::shared_ptr<ov::Model> convert_subgraph(size_t index) const;private:+ void mutate_tensor(size_t input_id, Output<Node> ov_output, const std::string& name) const;+ov::Any apply_additional_conversion_rules(const ov::Any& data, const std::type_info& type_info) const override;std::shared_ptr<TorchDecoder> m_decoder;diff --git a/src/frontends/pytorch/src/frontend.cpp b/src/frontends/pytorch/src/frontend.cppindex bd3c2a6a9aa..82f6522cdd2 100644--- a/src/frontends/pytorch/src/frontend.cpp+++ b/src/frontends/pytorch/src/frontend.cpp@@ -27,7 +27,6 @@#include "transforms/aten_index_put_replacer.hpp"#include "transforms/aten_index_replacer.hpp"#include "transforms/dict_resolver.hpp"-#include "transforms/einsum_list_construct.hpp"#include "transforms/index_loop_getitem_replacer.hpp"#include "transforms/listconstruct_replacer.hpp"#include "transforms/max_pool_dynamic_kernel_resolver.hpp"@@ -235,7 +234,6 @@ void FrontEnd::normalize(const std::shared_ptr<ov::Model>& model) const {manager.register_pass<ov::frontend::pytorch::pass::TupleUnpackInBodyReplacer>();manager.register_pass<ov::frontend::pass::SequenceConcatReplacer>();manager.register_pass<ov::frontend::pytorch::pass::AppendListUnpackReplacer>();- manager.register_pass<ov::frontend::pytorch::pass::AtenEinsumListConstructReplacer>();manager.register_pass<ov::frontend::pytorch::pass::MinMaxPrimListConstructReplacer>();manager.register_pass<ov::frontend::pytorch::pass::StringEqualityReplacer>();manager.register_pass<ov::frontend::pytorch::pass::PrimTupleUnpackReplacer>();@@ -370,10 +368,16 @@ ov::frontend::InputModel::Ptr FrontEnd::load_impl(const std::vector<ov::Any>& vastd::unordered_map<std::string, CreatorFunction> FrontEnd::get_supported_ops(const ov::frontend::InputModel::Ptr& model) const {std::unordered_map<std::string, CreatorFunction> supported_ops;- if (std::dynamic_pointer_cast<pytorch::InputModel>(model)->decoder_type_name() == "fx")+ if (std::dynamic_pointer_cast<pytorch::InputModel>(model)->decoder_type_name() == "fx") {supported_ops = get_supported_ops_fx();- else+ // FX and TorchScript names use disjoint separators (`aten.add.Tensor` vs `aten::add`), so both tables can be+ // merged. TranslateSession::convert_node resolves an FX name to its TorchScript entry when no FX-specific+ // translator is registered.+ const auto ts_ops = get_supported_ops_ts();+ supported_ops.insert(ts_ops.begin(), ts_ops.end());+ } else {supported_ops = get_supported_ops_ts();+ }for (const auto& ext : m_op_extension_translators) {supported_ops[ext.first] = ext.second;}diff --git a/src/frontends/pytorch/src/node_context.cpp b/src/frontends/pytorch/src/node_context.cppindex f1067b971fa..d366bbd54d6 100644--- a/src/frontends/pytorch/src/node_context.cpp+++ b/src/frontends/pytorch/src/node_context.cpp@@ -5,6 +5,7 @@#include "openvino/frontend/pytorch/node_context.hpp"#include "helper_ops/internal_op.hpp"+#include "openvino/core/rt_info.hpp"#include "openvino/core/validation_util.hpp"#include "openvino/frontend/complex_type_mark.hpp"#include "openvino/frontend/exception.hpp"@@ -22,6 +23,63 @@ namespace pytorch {using namespace ov::op;+namespace {+using ViewReplacements = std::map<Output<Node>, Output<Node>>;++// Maps a base value onto its replacement, including the parts of a structured base which views can be built from.+ViewReplacements view_replacements(const Output<Node>& old_base, const Output<Node>& new_base) {+ ViewReplacements replacements{{old_base, new_base}};+ if (ov::is_type<SequenceMark>(old_base.get_node_shared_ptr())) {+ const auto old_elements = old_base.get_node_shared_ptr()->input_values();+ const auto new_elements = new_base.get_node_shared_ptr()->input_values();+ FRONT_END_GENERAL_CHECK(old_elements.size() == new_elements.size(), "An aliased list cannot change length.");+ for (size_t i = 0; i < old_elements.size(); ++i) {+ replacements[old_elements[i]] = new_elements[i];+ }+ }+ if (const auto old_complex = ov::as_type_ptr<ComplexTypeMark>(old_base.get_node_shared_ptr())) {+ const auto new_complex = ov::as_type_ptr<ComplexTypeMark>(new_base.get_node_shared_ptr());+ FRONT_END_GENERAL_CHECK(new_complex, "An alias update must preserve complex element type.");+ replacements[old_complex->get_data()] = new_complex->get_data();+ replacements[old_complex->get_real()] = new_complex->get_real();+ replacements[old_complex->get_imag()] = new_complex->get_imag();+ }+ return replacements;+}++// Replays a view on top of a replaced base. `replacements` memoizes the walk, so passing the same map for every view+// of one base keeps the shared upstream chain cloned only once.+Output<Node> replay_view(const Output<Node>& view, ViewReplacements& replacements) {+ const auto found = replacements.find(view);+ if (found != replacements.end()) {+ return found->second;+ }+ const auto node = view.get_node_shared_ptr();+ const auto inputs = node->input_values();+ OutputVector new_inputs;+ new_inputs.reserve(inputs.size());+ for (const auto& input : inputs) {+ new_inputs.push_back(replay_view(input, replacements));+ }+ if (new_inputs == inputs) {+ replacements[view] = view;+ return view;+ }+ const auto updated = node->clone_with_new_inputs(new_inputs);+ updated->set_friendly_name(node->get_friendly_name());+ copy_runtime_info(node, updated);+ for (size_t i = 0; i < node->get_output_size(); ++i) {+ replacements[node->output(i)] = updated->output(i);+ }+ return updated->output(view.get_index());+}++Output<Node> rebase_view(const Output<Node>& view, const Output<Node>& old_base, const Output<Node>& new_base) {+ auto replacements = view_replacements(old_base, new_base);+ return replay_view(view, replacements);+}+} // namespace+OutputVector NodeContext::as_constant() const {auto dtype = m_decoder->get_output_type(0);if (dtype.is<type::Str>()) {@@ -61,13 +119,56 @@ std::shared_ptr<Node> NodeContext::mark_node(std::shared_ptr<Node> ov_node) consvoid NodeContext::mutate_input(size_t index, Output<Node> ov_output) const {FRONT_END_GENERAL_CHECK(!input_is_none(index), "Input is none with index: ", index);- auto input_id = m_decoder_inputs.at(index);+ mutate_tensor(m_decoder_inputs.at(index), ov_output, m_decoder->get_input_debug_name(index));+}++void NodeContext::mutate_input(const std::string& name, Output<Node> ov_output) const {+ mutate_tensor(m_decoder->get_named_input(name), ov_output, name);+}++void NodeContext::mutate_tensor(size_t input_id, Output<Node> ov_output, const std::string& name) const {auto tensor_it = m_tensor_map->find(input_id);FRONT_END_GENERAL_CHECK(tensor_it != m_tensor_map->end(), "No tensor corresponding input: ", input_id, " exist.");- m_translate_session->encode_tensor_name(ov_output, input_id, {m_decoder->get_input_debug_name(index)});+ const auto previous_value = tensor_it->second;+ m_translate_session->encode_tensor_name(ov_output, input_id, {name});tensor_it->second = ov_output;m_mutated_tensors->insert(input_id);+ if (ov::is_type<SequenceMark>(ov_output.get_node_shared_ptr())) {+ // Mutating a list changes its contents, not the storage of its member tensors.+ const auto alias = m_translate_session->m_may_be_alias.find(input_id);+ if (alias != m_translate_session->m_may_be_alias.end()) {+ alias->second.output = ov_output;+ if (!alias->second.element_ids.empty() && normalize_op_type(get_op_type()) == "aten::append") {+ alias->second.element_ids.push_back(m_decoder_inputs.at(1));+ }+ }+ return;+ }++ // In-place operations which only rewrite the base tensor's metadata, leaving its storage untouched.+ static const std::set<std::string> metadata_ops{"aten::unsqueeze_",+ "aten::squeeze_",+ "aten::transpose_",+ "aten::t_"};+ if (metadata_ops.count(normalize_op_type(get_op_type()))) {+ // Existing views retain their shape when the base tensor's metadata changes.+ const auto old_shape_view =+ m_translate_session->get_reverseprop_op(m_decoder, ov_output, ov_output, previous_value);+ for (auto& [alias_id, info] : m_translate_session->m_may_be_alias) {+ if (info.element_ids.empty() && info.base_id == input_id) {+ info.output = rebase_view(info.output, info.base_value, old_shape_view);+ info.base_value = ov_output;+ (*m_tensor_map)[alias_id] = info.output;+ }+ }+ const auto alias = m_translate_session->m_may_be_alias.find(input_id);+ if (alias != m_translate_session->m_may_be_alias.end()) {+ alias->second.output = ov_output;+ }+ return;+ }+// Resolve aliasesauto& back_input_id = input_id;auto& back_node_input = ov_output;@@ -75,10 +176,11 @@ void NodeContext::mutate_input(size_t index, Output<Node> ov_output) const {// Create node to aliased data. While loop is needed for the cases when alias to tensor point to another// alias to tensor. In that case we need to create a chain of reverseprop opsauto& alias_info = m_translate_session->m_may_be_alias.at(back_input_id);- size_t in_tensor = std::get<0>(alias_info);- auto& node = std::get<1>(alias_info);- auto& node_converted_output = std::get<2>(alias_info);- auto reverseprop_node = m_translate_session->get_reverseprop_op(node, node_converted_output, back_node_input);+ const auto in_tensor = alias_info.base_id;+ auto reverseprop_node = m_translate_session->get_reverseprop_op(alias_info.decoder,+ alias_info.output,+ back_node_input,+ alias_info.base_value);m_translate_session->encode_tensor_name(reverseprop_node, in_tensor);(*m_tensor_map)[in_tensor] = reverseprop_node;m_mutated_tensors->insert(in_tensor);@@ -89,11 +191,12 @@ void NodeContext::mutate_input(size_t index, Output<Node> ov_output) const {}void NodeContext::add_tensor_to_context(size_t index, const Output<Node>& ov_output) const {-#ifdef ENABLE_OPENVINO_DEBUGif (m_tensor_map->count(index)) {- OPENVINO_DEBUG("[ WARNING ] Current context has tensor ", index, ". Assuming mutated output.\n");+ // A subgraph returned a mutation of a captured tensor. Propagate it through+ // aliases in the parent graph using the parent's view and base values.+ mutate_tensor(index, ov_output, std::to_string(index));+ return;}-#endifm_translate_session->encode_tensor_name(ov_output, index);(*m_tensor_map)[index] = ov_output;}@@ -101,7 +204,7 @@ void NodeContext::add_tensor_to_context(size_t index, const Output<Node>& ov_outOutput<Node> NodeContext::get_tensor_from_model_or_create_input(size_t index) const {auto tensor_it = m_tensor_map->find(index);if (tensor_it != m_tensor_map->end()) {- return tensor_it->second;+ return resolve_tensor(index);} else {// nested subgraphs caseauto parameter = std::make_shared<v0::Parameter>(element::dynamic, PartialShape::dynamic());@@ -186,9 +289,47 @@ Output<Node> NodeContext::get_input(int index) const {}}}- auto tensor_it = m_tensor_map->find(input);- FRONT_END_GENERAL_CHECK(tensor_it != m_tensor_map->end(), "No tensor corresponding input: ", input, " exist.");- return tensor_it->second;+ return resolve_tensor(input);+}++Output<Node> NodeContext::resolve_tensor(size_t index) const {+ const auto tensor_it = m_tensor_map->find(index);+ FRONT_END_GENERAL_CHECK(tensor_it != m_tensor_map->end(), "No tensor corresponding input: ", index, " exist.");+ const auto alias = m_translate_session->m_may_be_alias.find(index);+ if (alias == m_translate_session->m_may_be_alias.end() || !alias->second.base_value.get_node()) {+ return tensor_it->second;+ }+ // Recursive resolution may insert into the tensor map, so `tensor_it` must not be reused below.+ auto& info = alias->second;+ if (!info.element_ids.empty()) {+ OutputVector elements;+ elements.reserve(info.element_ids.size());+ for (const auto element_id : info.element_ids) {+ elements.push_back(resolve_tensor(element_id));+ }+ const auto list = info.output.get_node();+ bool changed = elements.size() != list->get_input_size();+ for (size_t i = 0; !changed && i < elements.size(); ++i) {+ changed = elements[i] != list->input_value(i);+ }+ if (changed) {+ info.output = make_list_construct(elements);+ (*m_tensor_map)[index] = info.output;+ m_translate_session->encode_tensor_name(info.output, index);+ }+ return m_tensor_map->at(index);+ }+ const auto base = resolve_tensor(info.base_id);+ if (base != info.base_value) {+ // Replaying a view against the current base updates sibling views and+ // views created before an in-place write. Previously consumed values+ // remain connected to their original OpenVINO nodes.+ info.output = rebase_view(info.output, info.base_value, base);+ info.base_value = base;+ (*m_tensor_map)[index] = info.output;+ m_translate_session->encode_tensor_name(info.output, index);+ }+ return m_tensor_map->at(index);}Output<Node> NodeContext::get_input(const std::string& name) const {@@ -201,7 +342,7 @@ Output<Node> NodeContext::get_input(const std::string& name) const {// None means input is unknown type, most likely a Nodeauto input = m_decoder->get_named_input(name);FRONT_END_GENERAL_CHECK(m_tensor_map->count(input), "No tensor corresponding input: ", input, " exist.");- return m_tensor_map->at(input);+ return resolve_tensor(input);}FRONT_END_GENERAL_CHECK(false, "Input has type which can't be converted to ov::Node.");}diff --git a/src/frontends/pytorch/src/op/adaptive_poolnd.cpp b/src/frontends/pytorch/src/op/adaptive_poolnd.cppindex 6077032a3be..002aaad0127 100644--- a/src/frontends/pytorch/src/op/adaptive_poolnd.cpp+++ b/src/frontends/pytorch/src/op/adaptive_poolnd.cpp@@ -142,21 +142,6 @@ OutputVector translate_adaptive_max_pool1d(const NodeContext& context) {return translate_adaptive_max_pool_base(context, const_tile_params, const_neg_1);};-OutputVector translate_adaptive_max_pool3d_fx(const NodeContext& context) {- auto outs = translate_adaptive_max_pool3d(context);- return {context.mark_node(make_list_construct(outs))};-};--OutputVector translate_adaptive_max_pool2d_fx(const NodeContext& context) {- auto outs = translate_adaptive_max_pool2d(context);- return {context.mark_node(make_list_construct(outs))};-};--OutputVector translate_adaptive_max_pool1d_fx(const NodeContext& context) {- auto outs = translate_adaptive_max_pool1d(context);- return {context.mark_node(make_list_construct(outs))};-};-} // namespace op} // namespace pytorch} // namespace frontenddiff --git a/src/frontends/pytorch/src/op/copy.cpp b/src/frontends/pytorch/src/op/copy.cppindex d3972572fb9..024b86c1390 100644--- a/src/frontends/pytorch/src/op/copy.cpp+++ b/src/frontends/pytorch/src/op/copy.cpp@@ -30,9 +30,10 @@ OutputVector translate_copy_(const NodeContext& context) {};OutputVector translate_copy_fx(const NodeContext& context) {+ // aten::copy(Tensor self, Tensor src, bool non_blocking=False) -> Tensor// copy = torch.ops.aten.copy.default(slice_4);// copy = torch.ops.aten.copy.default(slice_4, clone);- num_inputs_check(context, 1, 2);+ num_inputs_check(context, 1, 3);auto self = context.get_input(0);if (context.input_is_none(1)) {return {self};@@ -59,4 +60,4 @@ OutputVector translate_alias_copy(const NodeContext& context) {} // namespace op} // namespace pytorch} // namespace frontend-} // namespace ov\ No newline at end of file+} // namespace ovdiff --git a/src/frontends/pytorch/src/op/cross.cpp b/src/frontends/pytorch/src/op/cross.cppindex 58d934a9dfb..917e58429ec 100644--- a/src/frontends/pytorch/src/op/cross.cpp+++ b/src/frontends/pytorch/src/op/cross.cpp@@ -34,13 +34,16 @@ Output<Node> translate_cross_base(const NodeContext& context, Output<Node> self,OutputVector translate_linalg_cross(const NodeContext& context) {// aten::linalg_cross(Tensor self, Tensor other, int? dim=-1) -> Tensor// aten::linalg_cross.out(Tensor self, Tensor other, int? dim=-1, *, Tensor(a!) out) -> Tensor(a!)- num_inputs_check(context, 3, 4);+ num_inputs_check(context, 2, 4);Output<Node> self;Output<Node> other;std::tie(self, other) = get_inputs_with_promoted_types(context, 0, 1);auto const_minus_1 = context.mark_node(v0::Constant::create(element::i32, Shape{1}, {-1}));Output<Node> dim;- if (context.input_is_none(2)) {+ if (context.has_attribute("dim")) {+ const auto axis = context.get_attribute<int64_t>("dim");+ dim = context.mark_node(v0::Constant::create(element::i32, Shape{1}, {axis}));+ } else if (context.input_is_none(2)) {dim = const_minus_1;} else {dim = context.get_input(2);diff --git a/src/frontends/pytorch/src/op/einsum.cpp b/src/frontends/pytorch/src/op/einsum.cppnew file mode 100644index 00000000000..ecd157f49bb--- /dev/null+++ b/src/frontends/pytorch/src/op/einsum.cpp@@ -0,0 +1,26 @@+// Copyright (C) 2018-2026 Intel Corporation+// SPDX-License-Identifier: Apache-2.0+//++#include "openvino/op/einsum.hpp"++#include "openvino/frontend/pytorch/node_context.hpp"+#include "utils.hpp"++namespace ov {+namespace frontend {+namespace pytorch {+namespace op {++OutputVector translate_einsum(const NodeContext& context) {+ num_inputs_check(context, 2, 3);+ const auto equation = context.const_input<std::string>(0);+ const auto tensors = get_list_as_outputs(context.get_input(1));+ const OutputVector inputs(tensors.begin(), tensors.end());+ return {context.mark_node(std::make_shared<ov::op::v7::Einsum>(inputs, equation))};+}++} // namespace op+} // namespace pytorch+} // namespace frontend+} // namespace ovdiff --git a/src/frontends/pytorch/src/op/embedding_bag.cpp b/src/frontends/pytorch/src/op/embedding_bag.cppindex adbfd780ee2..95a6462e2b3 100644--- a/src/frontends/pytorch/src/op/embedding_bag.cpp+++ b/src/frontends/pytorch/src/op/embedding_bag.cpp@@ -15,7 +15,8 @@ namespace frontend {namespace pytorch {namespace op {-OutputVector translate_embedding_bag_common(const NodeContext& context) {+OutputVector translate_embedding_bag(const NodeContext& context) {+ num_inputs_check(context, 3, 9);// aten::embedding_bag(weight, input, offsets=None, scale_grad_by_freq=False, mode_enum=1, sparse=False,// per_sample_weights=None, include_last_offset=False, padding_idx=None)// we have only EmbeddingBag case support, check it before translation@@ -75,17 +76,6 @@ OutputVector translate_embedding_bag_common(const NodeContext& context) {return {result, zero, zero, zero};};-OutputVector translate_embedding_bag(const NodeContext& context) {- num_inputs_check(context, 9, 9);- return translate_embedding_bag_common(context);-}--OutputVector translate_embedding_bag_fx(const NodeContext& context) {- num_inputs_check(context, 3, 9);- ov::OutputVector output = translate_embedding_bag_common(context);- return {context.mark_node(make_list_construct(output))};-}-} // namespace op} // namespace pytorch} // namespace frontenddiff --git a/src/frontends/pytorch/src/op/eye.cpp b/src/frontends/pytorch/src/op/eye.cppindex 39e493b6d5e..a82f3475c13 100644--- a/src/frontends/pytorch/src/op/eye.cpp+++ b/src/frontends/pytorch/src/op/eye.cpp@@ -46,12 +46,12 @@ OutputVector translate_eye(const NodeContext& context) {};OutputVector translate_eye_fx(const NodeContext& context) {- num_inputs_check(context, 2, 2);+ num_inputs_check(context, 1, 2);auto x = get_input_as_i32(context, 0);- auto y = get_input_as_i32(context, 1);+ auto y = context.input_is_none(1) ? x : get_input_as_i32(context, 1);// aten::eye support only main diagonalauto diagonal = context.mark_node(v0::Constant::create(element::i32, Shape{}, {0}));- auto dtype = element::i32;+ auto dtype = element::f32;if (context.has_attribute("dtype")) {dtype = context.get_attribute<element::Type>("dtype");}@@ -62,4 +62,4 @@ OutputVector translate_eye_fx(const NodeContext& context) {} // namespace op} // namespace pytorch} // namespace frontend-} // namespace ov\ No newline at end of file+} // namespace ovdiff --git a/src/frontends/pytorch/src/op/index_add.cpp b/src/frontends/pytorch/src/op/index_add.cppindex 4cd5d96f8fe..4036f0ad8fc 100644--- a/src/frontends/pytorch/src/op/index_add.cpp+++ b/src/frontends/pytorch/src/op/index_add.cpp@@ -27,12 +27,14 @@ OutputVector translate_index_add(const NodeContext& context) {// aten::index_add(Tensor self, int dim, Tensor index, Tensor source, *, Scalar alpha=1) -> Tensor// aten::index_add.out(Tensor self, int dim, Tensor index, Tensor source, *, Scalar alpha=1, Tensor(a!) out) ->// Tensor(a!)- num_inputs_check(context, 5, 6);+ num_inputs_check(context, 4, 6);auto input = context.get_input(0);auto dim = context.get_input(1);auto index = context.mark_node(std::make_shared<v0::Convert>(context.get_input(2), element::i32));auto src = context.get_input(3);- auto alpha = context.get_input(4);+ auto alpha = !context.input_is_none(4) ? context.get_input(4)+ : context.has_attribute("alpha") ? context.get_input("alpha")+ : v0::Constant::create(element::i32, Shape{}, {1});auto converted_alpha = context.mark_node(std::make_shared<v1::ConvertLike>(alpha, src));auto alpha_src = context.mark_node(std::make_shared<v1::Multiply>(converted_alpha, src));auto input_shape_rank = get_shape_rank(context, input);diff --git a/src/frontends/pytorch/src/op/lstm.cpp b/src/frontends/pytorch/src/op/lstm.cppindex d7b3521c4e2..6c4933b360a 100644--- a/src/frontends/pytorch/src/op/lstm.cpp+++ b/src/frontends/pytorch/src/op/lstm.cpp@@ -383,7 +383,7 @@ OutputVector translate_rnn(const NodeContext& context) {const auto batch_first = context.const_input<bool>(8);const auto weight = get_list_as_outputs(weight_v);- const auto variant_it = RNN_VARIANT_MAP.find(context.get_op_type());+ const auto variant_it = RNN_VARIANT_MAP.find(normalize_op_type(context.get_op_type()));PYTORCH_OP_CONVERSION_CHECK(variant_it != RNN_VARIANT_MAP.end(), "Unsupported RNN variant.");const auto res = generic_rnn(rg,variant_it->second,diff --git a/src/frontends/pytorch/src/op/max_poolnd.cpp b/src/frontends/pytorch/src/op/max_poolnd.cppindex 0ed7f4a3228..d6873637fe8 100644--- a/src/frontends/pytorch/src/op/max_poolnd.cpp+++ b/src/frontends/pytorch/src/op/max_poolnd.cpp@@ -14,7 +14,7 @@ namespace op {using namespace ov::op;-OutputVector translate_max_pool_base(const NodeContext& context, int dims, bool return_indices) {+OutputVector translate_max_pool_base(const NodeContext& context, int dims) {num_inputs_check(context, 2, 6);auto input = context.get_input(0);@@ -56,6 +56,7 @@ OutputVector translate_max_pool_base(const NodeContext& context, int dims, boolrounding_type = context.const_input<bool>(5) ? RoundingType::CEIL_TORCH : RoundingType::FLOOR;}+ const bool return_indices = context.get_op_type().find("_with_indices") != std::string::npos;ov::pass::NodeRegistry rg;auto res = build_static_max_pool(rg, input, dims, return_indices, kernel, strides, pads, dilations, rounding_type);context.mark_nodes(rg.get());@@ -63,25 +64,15 @@ OutputVector translate_max_pool_base(const NodeContext& context, int dims, bool};OutputVector translate_max_pool1d(const NodeContext& context) {- return translate_max_pool_base(context, 1, context.get_output_size() == 2);+ return translate_max_pool_base(context, 1);};OutputVector translate_max_pool2d(const NodeContext& context) {- return translate_max_pool_base(context, 2, context.get_output_size() == 2);+ return translate_max_pool_base(context, 2);};OutputVector translate_max_pool3d(const NodeContext& context) {- return translate_max_pool_base(context, 3, context.get_output_size() == 2);-};--OutputVector translate_max_pool2d_fx(const NodeContext& context) {- auto output = translate_max_pool_base(context, 2, true);- return {context.mark_node(make_list_construct(output))};-};--OutputVector translate_max_pool3d_fx(const NodeContext& context) {- auto output = translate_max_pool_base(context, 3, true);- return {context.mark_node(make_list_construct(output))};+ return translate_max_pool_base(context, 3);};} // namespace opdiff --git a/src/frontends/pytorch/src/op/mean.cpp b/src/frontends/pytorch/src/op/mean.cppindex 51669489310..529ebe3550e 100644--- a/src/frontends/pytorch/src/op/mean.cpp+++ b/src/frontends/pytorch/src/op/mean.cpp@@ -61,7 +61,9 @@ OutputVector translate_mean_fx(const NodeContext& context) {axes = get_input_concat_if_list(context, 1);}if (num_inputs > 2) {- axes = get_input_concat_if_list(context, 1);+ if (!context.input_is_none(1)) {+ axes = get_input_concat_if_list(context, 1);+ }if (!context.input_is_none(2)) {keep_dims = context.const_input<bool>(2);}diff --git a/src/frontends/pytorch/src/op/min_max.cpp b/src/frontends/pytorch/src/op/min_max.cppindex 6ff474bc64d..386e599d969 100644--- a/src/frontends/pytorch/src/op/min_max.cpp+++ b/src/frontends/pytorch/src/op/min_max.cpp@@ -64,34 +64,6 @@ OutputVector translate_max(const NodeContext& context) {return {values, indices};};-OutputVector translate_max_dim(const NodeContext& context) {- // torch.max.dim(x, dim, keepdim)- num_inputs_check(context, 2, 3);- auto x = context.get_input(0);- auto axes_node = context.get_input(1);- auto axis_const = context.const_input<int64_t>(1);-- bool keepdims = false;- if (!context.input_is_none(2)) {- keepdims = context.const_input<bool>(2);- }-- auto values = context.mark_node(std::make_shared<v1::ReduceMax>(x, axes_node, keepdims));- auto k = context.mark_node(std::make_shared<v0::Constant>(element::i32, Shape{}, 1));- auto topk = context.mark_node(- std::make_shared<v11::TopK>(x, k, axis_const, TopKMode::MAX, TopKSortType::NONE, element::i64));- auto indices = topk->output(1);- if (!keepdims) {- indices = context.mark_node(std::make_shared<v0::Squeeze>(indices, axes_node));- }- return {values, indices};-};--OutputVector translate_max_dim_fx(const NodeContext& context) {- ov::OutputVector out_vec = translate_max_dim(context);- return {context.mark_node(make_list_construct(out_vec))};-};-OutputVector translate_min(const NodeContext& context) {// torch.min (same for torch.max) actually has two interfaces smashed together:// torch.min(x, dim, keepdim) and torch.min(x, y)@@ -123,34 +95,6 @@ OutputVector translate_min(const NodeContext& context) {return {values, indices};};-OutputVector translate_min_dim(const NodeContext& context) {- // torch.min.dim(x, dim, keepdim)- num_inputs_check(context, 2, 3);- auto x = context.get_input(0);- auto axes_node = context.get_input(1);- auto axis_const = context.const_input<int64_t>(1);-- bool keepdims = false;- if (!context.input_is_none(2)) {- keepdims = context.const_input<bool>(2);- }-- auto values = context.mark_node(std::make_shared<v1::ReduceMin>(x, axes_node, keepdims));- auto k = context.mark_node(std::make_shared<v0::Constant>(element::i32, Shape{}, 1));- auto topk = context.mark_node(- std::make_shared<v11::TopK>(x, k, axis_const, TopKMode::MIN, TopKSortType::NONE, element::i64));- auto indices = topk->output(1);- if (!keepdims) {- indices = context.mark_node(std::make_shared<v0::Squeeze>(indices, axes_node));- }- return {values, indices};-};--OutputVector translate_min_dim_fx(const NodeContext& context) {- ov::OutputVector out_vec = translate_min_dim(context);- return {context.mark_node(make_list_construct(out_vec))};-};-OutputVector translate_maximum(const NodeContext& context) {// aten::maximum(Tensor self, Tensor other) -> Tensor@@ -230,11 +174,12 @@ OutputVector translate_aminmax(const NodeContext& context) {auto input = context.get_input(0);// From torch 2.8, amax dim input is optional; an empty list also means reduce all dims- auto dim_input = !context.input_is_none(1) ? context.get_input(1) : Output<Node>{};+ auto dim_input = context.has_attribute("dim") ? context.get_input("dim")+ : (!context.input_is_none(1) ? context.get_input(1) : Output<Node>{});auto dim = (dim_input.get_node() == nullptr || is_empty_axes(dim_input)) ? get_axes_range(context, 0) : dim_input;// check if keepdim is provided, if not, set it to false like PyTorch- bool keep_dims = !context.input_is_none(2) ? context.const_input<bool>(2) : false;+ bool keep_dims = get_const_input_or_attribute(context, 2, "keepdim", false);auto amin = context.mark_node(std::make_shared<v1::ReduceMin>(input, dim, keep_dims));auto amax = context.mark_node(std::make_shared<v1::ReduceMax>(input, dim, keep_dims));diff --git a/src/frontends/pytorch/src/op/norm.cpp b/src/frontends/pytorch/src/op/norm.cppindex 9880ba91791..735e0768b60 100644--- a/src/frontends/pytorch/src/op/norm.cpp+++ b/src/frontends/pytorch/src/op/norm.cpp@@ -54,9 +54,6 @@ Output<Node> norm_vector(const NodeContext& context,auto abs = context.mark_node(std::make_shared<v0::Abs>(input_tensor));res = context.mark_node(std::make_shared<v1::ReduceMin>(abs, dim, keep_dim));} else if (p == 0) {- auto input_rank = input_tensor.get_partial_shape().rank();- PYTORCH_OP_CONVERSION_CHECK(input_rank.is_dynamic() || input_rank.get_length() == 1,- "ord=0 supported only for vector norm");auto zero = context.mark_node(v0::Constant::create(element::f32, Shape{}, {0}));zero = context.mark_node(std::make_shared<v1::ConvertLike>(zero, input_tensor));auto cond = context.mark_node(std::make_shared<v1::NotEqual>(input_tensor, zero));@@ -201,9 +198,7 @@ OutputVector translate_linalg_vector_norm(const NodeContext& context) {}// dtype may be used to perform the computation in a more precise dtype. It is semantically equivalent to calling// linalg.vector_norm(x.to(dtype))- if (!context.input_is_none(4)) {- x = apply_dtype(context, 4, x);- }+ x = apply_optional_dtype(context, 4, x);result = norm_vector(context, x, dim, ord, keep_dim);// output tensorif (!context.input_is_none(5)) {@@ -217,7 +212,7 @@ OutputVector translate_linalg_matrix_norm(const NodeContext& context) {// dtype=None, Tensor(a!) out) -> Tensor(a!) aten::linalg_matrix_norm(Tensor self, Scalar ord, int[] dim=[-2, -1],// bool keepdim=False, *, ScalarType? dtype=None) aten::linalg_matrix_norm.str_ord(Tensor self, str ord="fro", int[]// dim=[-2, -1], bool keepdim=False, *, ScalarType? dtype=None)- num_inputs_check(context, 5, 6);+ num_inputs_check(context, 4, 6);auto x = context.get_input(0);// ord defines the vector norm that is computed can be string or numberauto ord_type = context.get_input_type(1);@@ -227,9 +222,7 @@ OutputVector translate_linalg_matrix_norm(const NodeContext& context) {// dtype may be used to perform the computation in a more precise dtype. It is semantically equivalent to calling// linalg.matrix_norm(x.to(dtype))- if (!context.input_is_none(4)) {- x = apply_dtype(context, 4, x);- }+ x = apply_optional_dtype(context, 4, x);if (ord_type.is<type::Str>()) {auto p_str = context.const_input<std::string>(1);if (p_str == "fro") {@@ -253,16 +246,14 @@ OutputVector translate_linalg_norm(const NodeContext& context) {// aten::linalg_norm.ord_str(Tensor self, str ord, int[1]? dim=None, bool keepdim=False, *, ScalarType? dtype=None)// aten::linalg_norm.ord_str_out(Tensor self, str ord, int[1]? dim=None, bool keepdim=False, *, ScalarType?// dtype=None, Tensor(a!) out) -> Tensor(a!)- num_inputs_check(context, 5, 6);+ num_inputs_check(context, 4, 6);auto x = context.get_input(0);bool keep_dim = context.const_input<bool>(3);Output<Node> result;Output<Node> dim;// dtype may be used to perform the computation in a more precise dtype. It is semantically equivalent to calling// linalg.norm(x.to(dtype))- if (!context.input_is_none(4)) {- x = apply_dtype(context, 4, x);- }+ x = apply_optional_dtype(context, 4, x);// If dim=None apply for all dimensionsif (context.input_is_none(2)) {dim = get_node_axes_range(context, x);diff --git a/src/frontends/pytorch/src/op/pow.cpp b/src/frontends/pytorch/src/op/pow.cppindex ff3d0a43b31..72d01351f62 100644--- a/src/frontends/pytorch/src/op/pow.cpp+++ b/src/frontends/pytorch/src/op/pow.cpp@@ -15,7 +15,7 @@ OutputVector translate_pow(const NodeContext& context) {num_inputs_check(context, 2, 2);auto lhs = context.get_input(0);auto rhs = context.get_input(1);- auto inplace = context.get_op_type() == "aten::pow_";+ auto inplace = normalize_op_type(context.get_op_type()) == "aten::pow_";if (inplace) {rhs = std::make_shared<ov::op::v1::ConvertLike>(rhs, lhs);} else {diff --git a/src/frontends/pytorch/src/op/rand.cpp b/src/frontends/pytorch/src/op/rand.cppindex b5570b994c2..b08d8b12f22 100644--- a/src/frontends/pytorch/src/op/rand.cpp+++ b/src/frontends/pytorch/src/op/rand.cpp@@ -285,16 +285,24 @@ OutputVector translate_normal(const NodeContext& context) {auto mean = context.get_input(0);auto std = context.get_input(1);auto dtype = element::f32;- if (context.get_input_size() == 3 || context.get_input_size() == 4) {+ if (context.get_op_type().find("aten.normal.float_float") == 0) {+ if (context.has_attribute("dtype")) {+ dtype = context.get_attribute<element::Type>("dtype");+ }+ return make_random_normal(context, context.get_input(2), dtype, std, mean);+ }+ if (context.get_input_size() >= 2 && context.get_input_size() <= 4) {// aten::normal.Tensor_float(Tensor mean, float std=1., *, Generator? generator=None) -> Tensor// aten::normal.Tensor_Tensor(Tensor mean, Tensor std, *, Generator? generator=None) -> Tensor+ // aten::normal.float_Tensor(float mean, Tensor std, *, Generator? generator=None) -> Tensor// aten::normal.Tensor_float_out(Tensor mean, float std=1., *, Generator? generator=None, Tensor(a!) out) ->// Tensor(a!)- // aten::normal.Tensor_float_out(Tensor mean, float std=1., *, Generator? generator=None, Tensor(a!)+ // aten::normal.float_Tensor_out(float mean, Tensor std, *, Generator? generator=None, Tensor(a!)// out) -> Tensor(a!)// aten::normal.Tensor_Tensor_out(Tensor mean, Tensor std, *, Generator? generator=None,// Tensor(a!) out) -> Tensor(a!)- auto sizes = context.mark_node(std::make_shared<v3::ShapeOf>(mean, element::i32));+ const auto tensor = is_python_scalar_input(context, 0) ? std : mean;+ auto sizes = context.mark_node(std::make_shared<v3::ShapeOf>(tensor, element::i32));auto res = make_random_normal(context, sizes, dtype, std, mean);if (!context.input_is_none(3)) {// outdiff --git a/src/frontends/pytorch/src/op/scaled_dot_product_attention.cpp b/src/frontends/pytorch/src/op/scaled_dot_product_attention.cppindex 2a09c1c2ead..30aa0a0b625 100644--- a/src/frontends/pytorch/src/op/scaled_dot_product_attention.cpp+++ b/src/frontends/pytorch/src/op/scaled_dot_product_attention.cpp@@ -178,7 +178,7 @@ std::shared_ptr<ov::Node> translate_scaled_dot_product_attention_common(const Noscale = context.get_input("scale");scale = context.mark_node(std::make_shared<v1::ConvertLike>(scale, query));}- if (!context.input_is_none(7) && context.const_input<bool>(7)) {+ if (get_const_input_or_attribute(context, 7, "enable_gqa", false)) {return decompose_gqa(context, query, key, value, scale, attn_mask, is_causal);}diff --git a/src/frontends/pytorch/src/op/scatter.cpp b/src/frontends/pytorch/src/op/scatter.cppindex 6e75ba12342..5071e83518e 100644--- a/src/frontends/pytorch/src/op/scatter.cpp+++ b/src/frontends/pytorch/src/op/scatter.cpp@@ -94,6 +94,8 @@ OutputVector translate_scatter(const NodeContext& context) {if (input_num > 4 && !context.input_is_none(4) && context.get_input_type(4).is<type::Str>()) {auto reduce_mode = context.const_input<std::string>(4);reduction = get_reduction_mode(reduce_mode);+ } else if (context.has_attribute("reduce")) {+ reduction = get_reduction_mode(context.get_attribute<std::string>("reduce"));}auto src_input_dtype = prepare_source(context, src, index, input);@@ -114,14 +116,14 @@ OutputVector translate_scatter_reduce(const NodeContext& context) {// Inplace schema// aten::scatter_reduce_.two(Tensor(a!) self, int dim, Tensor index, Tensor src, str reduce, *, bool// include_self=True) -> Tensor(a!)- num_inputs_check(context, 6, 7);+ num_inputs_check(context, 5, 7);auto input = context.get_input(0);auto dim = context.get_input(1);auto index = context.mark_node(std::make_shared<v0::Convert>(context.get_input(2), element::i32));auto src = context.get_input(3);auto reduce_mode = context.const_input<std::string>(4);auto reduction = get_reduction_mode(reduce_mode);- auto include_self = context.const_input<bool>(5);+ auto include_self = get_const_input_or_attribute(context, 5, "include_self", true);auto src_input_dtype = prepare_source(context, src, index, input);auto scatter_result = context.mark_node(std::make_shared<v12::ScatterElementsUpdate>(input, index, src_input_dtype, dim, reduction, include_self));diff --git a/src/frontends/pytorch/src/op/search_sorted.cpp b/src/frontends/pytorch/src/op/search_sorted.cppindex b6634de6288..20fda7dec0d 100644--- a/src/frontends/pytorch/src/op/search_sorted.cpp+++ b/src/frontends/pytorch/src/op/search_sorted.cpp@@ -19,12 +19,14 @@ OutputVector translate_search_sorted(const NodeContext& context) {Output<Node> sorted;Output<Node> values;std::tie(sorted, values) = get_inputs_with_promoted_types(context, 0, 1);- const bool out_int32 = context.const_input<bool>(2);+ const bool out_int32 = get_const_input_or_attribute(context, 2, "out_int32", false);PYTORCH_OP_CONVERSION_CHECK(out_int32 == false, "aten::searchsorted(out_int32=true) unsupported");- const bool right_mode = context.const_input<bool>(3);- PYTORCH_OP_CONVERSION_CHECK(context.input_is_none(4), "aten::searchsorted(side) unsupported");+ const bool right_mode = get_const_input_or_attribute(context, 3, "right", false);+ PYTORCH_OP_CONVERSION_CHECK(context.input_is_none(4) && !context.has_attribute("side"),+ "aten::searchsorted(side) unsupported");PYTORCH_OP_CONVERSION_CHECK(context.input_is_none(5), "aten::searchsorted(out) unsupported");- PYTORCH_OP_CONVERSION_CHECK(context.input_is_none(6), "aten::searchsorted(sorter) unsupported");+ PYTORCH_OP_CONVERSION_CHECK(context.input_is_none(6) && !context.has_attribute("sorter"),+ "aten::searchsorted(sorter) unsupported");auto op = context.mark_node(std::make_shared<ov::op::v15::SearchSorted>(sorted, values, right_mode));return {op};};diff --git a/src/frontends/pytorch/src/op/sort.cpp b/src/frontends/pytorch/src/op/sort.cppindex 3fd4483a585..d54b0d99435 100644--- a/src/frontends/pytorch/src/op/sort.cpp+++ b/src/frontends/pytorch/src/op/sort.cpp@@ -28,11 +28,15 @@ OutputVector translate_sort_common(const NodeContext& context, bool stable, int6}OutputVector translate_sort(const NodeContext& context) {- num_inputs_check(context, 3, 4);+ num_inputs_check(context, 1, 4);bool stable, descending;int64_t dim;- if (context.get_input_size() == 4) {+ if (context.has_attribute("stable")) {+ stable = context.get_attribute<bool>("stable");+ dim = context.get_attribute<int64_t>("dim", -1);+ descending = context.get_attribute<bool>("descending", false);+ } else if (context.get_input_size() == 4) {stable = context.const_input<bool>(1);dim = context.const_input<int64_t>(2);descending = context.const_input<bool>(3);@@ -45,72 +49,11 @@ OutputVector translate_sort(const NodeContext& context) {return translate_sort_common(context, stable, dim, descending);};-OutputVector translate_sort_fx(const NodeContext& context) {- // aten.sort.default(Tensor self, int dim=-1, bool descending=False) -> (Tensor values, Tensor indices)- // aten.sort.stable(Tensor self, *, bool? stable=None, int dim=-1, bool descending=False) -> (Tensor values, Tensor- // indices)- num_inputs_check(context, 1, 4);- bool descending = false;- bool stable = false;- int64_t dim = -1;-- if (context.has_attribute("stable")) {- // aten.sort.stable: keyword args (stable, dim, descending)- stable = context.get_attribute<bool>("stable");- if (context.has_attribute("dim")) {- dim = context.get_attribute<int64_t>("dim");- }- if (context.has_attribute("descending")) {- descending = context.get_attribute<bool>("descending");- }- } else {- // aten.sort.default: positional args (self, dim, descending)- if (!context.input_is_none(1)) {- dim = context.const_input<int64_t>(1);- }- if (!context.input_is_none(2)) {- descending = context.const_input<bool>(2);- }- }-- auto topk_outputs = translate_sort_common(context, stable, dim, descending);- return {context.mark_node(make_list_construct(OutputVector({topk_outputs[0], topk_outputs[1]})))};-};-OutputVector translate_argsort(const NodeContext& context) {auto sort = translate_sort(context);return {sort[1]};};-OutputVector translate_argsort_fx(const NodeContext& context) {- // aten.argsort.default(Tensor self, int dim=-1, bool descending=False) -> Tensor- // aten.argsort.stable(Tensor self, *, bool? stable=None, int dim=-1, bool descending=False) -> Tensor- num_inputs_check(context, 1, 3);- bool descending = false;- bool stable = false;- int64_t dim = -1;-- if (context.has_attribute("stable")) {- stable = context.get_attribute<bool>("stable");- if (context.has_attribute("dim")) {- dim = context.get_attribute<int64_t>("dim");- }- if (context.has_attribute("descending")) {- descending = context.get_attribute<bool>("descending");- }- } else {- if (!context.input_is_none(1)) {- dim = context.const_input<int64_t>(1);- }- if (!context.input_is_none(2)) {- descending = context.const_input<bool>(2);- }- }-- auto topk_outputs = translate_sort_common(context, stable, dim, descending);- return {topk_outputs[1]};-};-} // namespace op} // namespace pytorch} // namespace frontenddiff --git a/src/frontends/pytorch/src/op/split.cpp b/src/frontends/pytorch/src/op/split.cppindex 0bab8adb7af..e0ea5efa335 100644--- a/src/frontends/pytorch/src/op/split.cpp+++ b/src/frontends/pytorch/src/op/split.cpp@@ -4,8 +4,17 @@#include "openvino/op/split.hpp"+#include "helper_ops/internal_op.hpp"#include "openvino/frontend/complex_type_mark.hpp"#include "openvino/frontend/pytorch/node_context.hpp"+#include "openvino/op/add.hpp"+#include "openvino/op/divide.hpp"+#include "openvino/op/gather.hpp"+#include "openvino/op/minimum.hpp"+#include "openvino/op/mod.hpp"+#include "openvino/op/multiply.hpp"+#include "openvino/op/shape_of.hpp"+#include "openvino/op/slice.hpp"#include "openvino/op/squeeze.hpp"#include "openvino/op/util/framework_node.hpp"#include "openvino/op/variadic_split.hpp"@@ -18,60 +27,75 @@ namespace op {using namespace ov::op;-OutputVector translate_chunk_fx(const NodeContext& context) {- num_inputs_check(context, 3, 3);- auto num_chunks = context.const_input<int>(1);- auto dim = context.get_input(2);- std::shared_ptr<ov::Node> chunk;-- auto shape = context.get_input(0).get_partial_shape();- if (shape.rank().is_dynamic()) {- size_t num_splits = context.get_decoder()->output_list_size();- std::vector<int32_t> split_lengths_vec;- for (size_t i = 0; i < num_splits - 1; i++) {- split_lengths_vec.push_back(num_chunks);+OutputVector translate_list_view_fx(const NodeContext& context) {+ const auto& name = context.get_op_type();+ const auto count = context.get_decoder()->output_list_size();+ const auto data = context.get_input(0);+ const auto zero = v0::Constant::create(element::i64, Shape{1}, {0});+ const auto one = v0::Constant::create(element::i64, Shape{1}, {1});+ const auto dim_index = name == "aten.unbind.int" ? 1 : 2;+ const auto axis = context.const_input<int64_t>(dim_index);+ const auto dim = v0::Constant::create(element::i64, Shape{1}, {axis});+ const auto shape = context.mark_node(std::make_shared<v3::ShapeOf>(data));+ const auto size = context.mark_node(std::make_shared<v8::Gather>(shape, dim, zero));+ Output<Node> step;+ Output<Node> remainder;+ std::vector<int64_t> indices;+ const bool sections = name == "aten.tensor_split.sections";+ if (name == "aten.tensor_split.indices") {+ indices = context.const_input<std::vector<int64_t>>(1);+ } else if (name != "aten.unbind.int") {+ const auto amount = context.const_input<int64_t>(1);+ const auto divisor = v0::Constant::create(element::i64, Shape{1}, {amount});+ if (sections) {+ step = context.mark_node(std::make_shared<v1::Divide>(size, divisor, true));+ remainder = context.mark_node(std::make_shared<v1::Mod>(size, divisor));+ } else if (name == "aten.split.Tensor") {+ step = divisor;+ } else {+ const auto offset = v0::Constant::create(element::i64, Shape{1}, {amount - 1});+ const auto rounded = context.mark_node(std::make_shared<v1::Add>(size, offset));+ step = context.mark_node(std::make_shared<v1::Divide>(rounded, divisor, true));}- split_lengths_vec.push_back(-1);- auto split_lengths =- context.mark_node(v0::Constant::create(element::i32, Shape{num_splits}, split_lengths_vec));- auto split = context.mark_node(std::make_shared<v1::VariadicSplit>(context.get_input(0), dim, split_lengths));- return {context.mark_node(make_list_construct(split->outputs()))};}- auto dim_val = context.const_input<int>(2);- if (dim_val < 0) {- dim_val = static_cast<int>(shape.rank().get_length()) + dim_val;+ OutputVector outputs;+ Output<Node> start = zero;+ for (size_t i = 0; i < count; ++i) {+ if (name == "aten.unbind.int") {+ const auto index = v0::Constant::create(element::i64, Shape{}, {i});+ outputs.push_back(context.mark_node(std::make_shared<v8::Gather>(data, index, dim)));+ continue;+ }+ Output<Node> end;+ if (i + 1 == count) {+ end = size;+ } else if (!indices.empty()) {+ end = v0::Constant::create(element::i64, Shape{1}, {indices[i]});+ } else {+ const auto index = v0::Constant::create(element::i64, Shape{1}, {i + 1});+ end = context.mark_node(std::make_shared<v1::Multiply>(step, index));+ if (sections) {+ const auto extra = context.mark_node(std::make_shared<v1::Minimum>(index, remainder));+ end = context.mark_node(std::make_shared<v1::Add>(end, extra));+ }+ }+ outputs.push_back(context.mark_node(std::make_shared<v8::Slice>(data, start, end, one, dim)));+ start = end;}- int num_splits = static_cast<int>(shape[dim_val].get_length()) / num_chunks;-- chunk = context.mark_node(std::make_shared<v1::Split>(context.get_input(0), dim, num_splits));-- return {context.mark_node(make_list_construct(chunk->outputs()))};+ return {context.mark_node(make_list_construct(outputs))};}-OutputVector translate_unbind_int_fx(const NodeContext& context) {- num_inputs_check(context, 1, 3);- auto input = context.get_input(0);- Output<Node> dim;- int64_t dim_val = 0;- if (context.input_is_none(1)) {- dim = context.mark_node(v0::Constant::create(element::i32, Shape{}, {0}));- } else {- dim = context.get_input(1);- dim_val = context.const_input<int>(1);- }- auto shape = input.get_shape();- if (dim_val < 0) {- dim_val = static_cast<int>(shape.size()) + dim_val;- }-- auto num_splits = static_cast<int>(shape[dim_val]);- auto chunk = context.mark_node(std::make_shared<v1::Split>(input, dim, num_splits));-- ov::OutputVector out_vec;- for (auto& out : chunk->outputs())- out_vec.push_back(std::make_shared<v0::Squeeze>(out, dim));-- return {context.mark_node(make_list_construct(out_vec))};+OutputVector translate_list_unpack_fx(const NodeContext& context) {+ // Reuse TorchScript's list-unpack normalization for ATen list operations.+ // Export fixes the list length, even when the tensor dimensions are dynamic.+ const auto ts_name = normalize_op_type(context.get_op_type());+ const auto count = context.get_decoder()->output_list_size();+ auto operation = context.mark_node(+ std::make_shared<PtFrameworkNode>(std::make_shared<InternalOpDecoder>(ts_name, 1), context.inputs()));+ auto unpack = context.mark_node(+ std::make_shared<PtFrameworkNode>(std::make_shared<InternalOpDecoder>("prim::ListUnpack", count),+ OutputVector{operation}));+ return {context.mark_node(make_list_construct(unpack->outputs()))};}OutputVector translate_split_with_sizes(const NodeContext& context) {diff --git a/src/frontends/pytorch/src/op/sub.cpp b/src/frontends/pytorch/src/op/sub.cppindex 531d641eb11..d0ca4a10ec2 100644--- a/src/frontends/pytorch/src/op/sub.cpp+++ b/src/frontends/pytorch/src/op/sub.cpp@@ -34,8 +34,8 @@ OutputVector translate_sub_common(const NodeContext& context, bool inplace) {}// default alpha is 1 so no need to multiply if alpha is not provided- if (!context.input_is_none(2)) {- auto alpha = context.get_input(2);+ if (!context.input_is_none(2) || context.has_attribute("alpha")) {+ auto alpha = context.input_is_none(2) ? context.get_input("alpha") : context.get_input(2);auto casted_alpha = ComplexTypeMark::convert_like(context, alpha, y);y = ComplexTypeMark::mul(context, casted_alpha, y);@@ -56,20 +56,6 @@ OutputVector translate_sub_(const NodeContext& context) {return translate_sub_common(context, true);};-OutputVector translate_sub_fx(const NodeContext& context) {- num_inputs_check(context, 2, 2);- Output<Node> x;- Output<Node> y;- std::tie(x, y) = get_inputs_with_promoted_types(context, 0, 1);- // default alpha is 1 so no need to multiply if alpha is not provided- if (context.has_attribute("alpha")) {- auto alpha = context.get_attribute<Output<Node>>("alpha");- auto casted_alpha = context.mark_node(std::make_shared<v1::ConvertLike>(alpha, y));- y = context.mark_node(std::make_shared<v1::Multiply>(casted_alpha, y));- }- return {context.mark_node(std::make_shared<v1::Subtract>(x, y))};-};-} // namespace op} // namespace pytorch} // namespace frontenddiff --git a/src/frontends/pytorch/src/op/topk.cpp b/src/frontends/pytorch/src/op/topk.cppindex ddd4faccf9e..ad83406e1a3 100644--- a/src/frontends/pytorch/src/op/topk.cpp+++ b/src/frontends/pytorch/src/op/topk.cpp@@ -5,7 +5,6 @@#include "openvino/op/topk.hpp"#include "openvino/frontend/pytorch/node_context.hpp"-#include "openvino/op/convert.hpp"#include "utils.hpp"namespace ov {@@ -40,39 +39,6 @@ OutputVector translate_topk(const NodeContext& context) {return topk->outputs();};-OutputVector translate_topk_fx(const NodeContext& context) {- // aten.topk.default(Tensor self, int k, int dim=-1, bool largest=True, bool sorted=True) -> Tuple[Tensor, Tensor]- num_inputs_check(context, 2, 5);- const auto input_tensor = context.get_input(0);- auto k = context.get_input(1);- int64_t axis{-1};- bool largest = true;- bool sorted = true;- auto mode = TopKMode::MIN;- auto sort = TopKSortType::NONE;-- if (!context.input_is_none(2)) {- axis = context.const_input<int64_t>(2);- }- if (!context.input_is_none(3)) {- largest = context.const_input<bool>(3);- }- if (!context.input_is_none(4)) {- sorted = context.const_input<bool>(4);- }- if (largest) {- mode = TopKMode::MAX;- }- if (sorted) {- sort = TopKSortType::SORT_VALUES;- }-- auto topk = context.mark_node(std::make_shared<v3::TopK>(input_tensor, k, axis, mode, sort));- auto indices = context.mark_node(std::make_shared<v0::Convert>(topk->output(1), element::i64));-- return {context.mark_node(make_list_construct(OutputVector({topk->output(0), indices})))};-};-} // namespace op} // namespace pytorch} // namespace frontenddiff --git a/src/frontends/pytorch/src/op/var_mean.cpp b/src/frontends/pytorch/src/op/var_mean.cppindex 7d7cd196101..bdd38386c60 100644--- a/src/frontends/pytorch/src/op/var_mean.cpp+++ b/src/frontends/pytorch/src/op/var_mean.cpp@@ -104,8 +104,7 @@ OutputVector translate_var_mean_fx(const NodeContext& context) {if (context.has_attribute("keepdim")) {keepdim = context.get_attribute<bool>("keepdim");}- auto res = translate_var_mean_common(context, data, axes, correction, keepdim);- return {context.mark_node(make_list_construct(res))};+ return translate_var_mean_common(context, data, axes, correction, keepdim);};OutputVector translate_var_fx(const NodeContext& context) {diff --git a/src/frontends/pytorch/src/op_table.cpp b/src/frontends/pytorch/src/op_table.cppindex 998e4f5fcee..b7125eeeb56 100644--- a/src/frontends/pytorch/src/op_table.cpp+++ b/src/frontends/pytorch/src/op_table.cpp@@ -43,7 +43,6 @@ OP_CONVERTER(translate_and);OP_CONVERTER(translate_arange);OP_CONVERTER(translate_append);OP_CONVERTER(translate_argsort);-OP_CONVERTER(translate_argsort_fx);OP_CONVERTER(translate_argmax);OP_CONVERTER(translate_argmin);OP_CONVERTER(translate_as_strided);@@ -84,6 +83,7 @@ OP_CONVERTER(translate_dim);OP_CONVERTER(translate_div);OP_CONVERTER(translate_div_);OP_CONVERTER(translate_dot);+OP_CONVERTER(translate_einsum);OP_CONVERTER(translate_elu);OP_CONVERTER(translate_embedding);OP_CONVERTER(translate_embedding_bag);@@ -306,9 +306,6 @@ OP_CONVERTER(translate_quantized_convnd_relu);OP_CONVERTER(translate_quantized_linear);OP_CONVERTER(translate_xor);// Torch FX Translations-OP_CONVERTER(translate_adaptive_max_pool1d_fx);-OP_CONVERTER(translate_adaptive_max_pool2d_fx);-OP_CONVERTER(translate_adaptive_max_pool3d_fx);OP_CONVERTER(translate_addcmul_fx);OP_CONVERTER(translate_addmm_fx);OP_CONVERTER(translate_any_fx);@@ -319,10 +316,10 @@ OP_CONVERTER(translate_batch_norm_legit_no_stats_fx);OP_CONVERTER(translate_cat_fx);OP_CONVERTER(translate_copy_fx);OP_CONVERTER(translate_cumsum_fx);-OP_CONVERTER(translate_chunk_fx);+OP_CONVERTER(translate_list_unpack_fx);+OP_CONVERTER(translate_list_view_fx);OP_CONVERTER(translate_div_fx);OP_CONVERTER(translate_div_fx_);-OP_CONVERTER(translate_embedding_bag_fx);OP_CONVERTER(translate_eye_fx);OP_CONVERTER(translate_fake_quantize_per_channel_affine_fx);OP_CONVERTER(translate_fake_quantize_per_tensor_affine_fx);@@ -335,11 +332,7 @@ OP_CONVERTER(translate_layer_norm_fx);OP_CONVERTER(translate_leaky_relu_fx);OP_CONVERTER(translate_log_sigmoid_fx);OP_CONVERTER(translate_log_softmax_fx);-OP_CONVERTER(translate_max_dim_fx);-OP_CONVERTER(translate_max_pool2d_fx);-OP_CONVERTER(translate_max_pool3d_fx);OP_CONVERTER(translate_mean_fx);-OP_CONVERTER(translate_min_dim_fx);OP_CONVERTER(translate_new_full_fx);OP_CONVERTER(translate_new_ones_fx);OP_CONVERTER(translate_new_zeros_fx);@@ -355,19 +348,15 @@ OP_CONVERTER(translate_select_scatter_fx);OP_CONVERTER(translate_slice_fx);OP_CONVERTER(translate_slice_scatter_fx);OP_CONVERTER(translate_softmax_fx);-OP_CONVERTER(translate_sort_fx);OP_CONVERTER(translate_stack_fx);-OP_CONVERTER(translate_sub_fx);OP_CONVERTER(translate_sum_fx);OP_CONVERTER(translate_std_fx);-OP_CONVERTER(translate_topk_fx);OP_CONVERTER(translate_to_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_vstack);-OP_CONVERTER(translate_unbind_int_fx);OP_CONVERTER(translate_zeros_fx);OP_CONVERTER(translate_zeros_like_fx);// Extensions@@ -516,7 +505,7 @@ const std::unordered_map<std::string, CreatorFunction> get_supported_ops_ts() {{"aten::dot", op::translate_dot},{"aten::dropout", op::skip_node},{"aten::dropout_", op::skip_node},- // aten::einsum - Supported in limited set of patterns+ {"aten::einsum", op::translate_einsum},{"aten::elu", op::translate_elu},{"aten::embedding", op::translate_embedding},{"aten::embedding_bag", op::translate_embedding_bag},@@ -861,6 +850,7 @@ const std::unordered_map<std::string, CreatorFunction> get_supported_ops_ts() {};const std::unordered_map<std::string, CreatorFunction> get_supported_ops_fx() {+ // ATen operations reuse the TorchScript table by name. Keep only FX-specific names and schemas here.return {{"<built-in function add>", op::translate_add},{"<built-in function floordiv>", op::translate_floor_divide},@@ -872,16 +862,12 @@ const std::unordered_map<std::string, CreatorFunction> get_supported_ops_fx() {{"aten._adaptive_avg_pool2d.default", op::translate_adaptive_avg_pool2d},{"aten._adaptive_avg_pool3d.default", op::translate_adaptive_avg_pool3d},{"aten._cdist_forward.default", op::translate_cdist},- {"aten._convolution.default", op::translate_convolution},- {"aten._embedding_bag.default", op::translate_embedding_bag_fx},- {"aten._embedding_bag_forward_only.default", op::translate_embedding_bag_fx},+ {"aten._embedding_bag.default", op::translate_embedding_bag},+ {"aten._embedding_bag_forward_only.default", op::translate_embedding_bag},{"aten._fake_quantize_per_tensor_affine_cachemask_tensor_qparams.default",op::translate_fake_quantize_per_tensor_affine_fx},- {"aten._grouped_mm.default", op::translate_grouped_mm},{"aten._local_scalar_dense.default", op::skip_node},{"aten._log_softmax.default", op::translate_log_softmax_fx},- {"aten.__lshift__.Tensor", op::translate_bitwise_left_shift},- {"aten.__rshift__.Tensor", op::translate_bitwise_right_shift},{"aten._native_batch_norm_legit.default", op::translate_batch_norm_legit_fx},{"aten._native_batch_norm_legit.no_stats", op::translate_batch_norm_legit_no_stats_fx},{"aten._native_batch_norm_legit_functional.default", op::translate_batch_norm_legit_fx},@@ -892,306 +878,93 @@ const std::unordered_map<std::string, CreatorFunction> get_supported_ops_fx() {{"aten._scaled_dot_product_flash_attention_for_cpu.default", op::translate_scaled_dot_product_attention_fx},{"aten._softmax.default", op::translate_softmax_fx},{"aten._to_copy.default", op::translate_to_fx},- {"aten._transformer_encoder_layer_fwd.default", op::translate_transformer_encoder_layer_fwd},{"aten._unsafe_view.default", op::translate_reshape},- {"aten.abs.default", op::translate_1to1_match_1_inputs<opset10::Abs>},- {"aten.absolute.default", op::translate_1to1_match_1_inputs<opset10::Abs>},- {"aten.acos.default", op::translate_1to1_match_1_inputs_with_fp32_type_alignment<opset10::Acos>},- {"aten.acosh.default", op::translate_1to1_match_1_inputs_with_fp32_type_alignment<opset10::Acosh>},- {"aten.adaptive_max_pool1d.default", op::translate_adaptive_max_pool1d_fx},- {"aten.adaptive_max_pool2d.default", op::translate_adaptive_max_pool2d_fx},- {"aten.adaptive_max_pool3d.default", op::translate_adaptive_max_pool3d_fx},- {"aten.add.Scalar", op::translate_add},- {"aten.add.Tensor", op::translate_add},- {"aten.add_.Tensor", op::translate_add},{"aten.addcmul.default", op::translate_addcmul_fx},{"aten.addmm.default", op::translate_addmm_fx},- {"aten.alias.default", op::skip_node},- {"aten.alias_copy.default", op::translate_alias_copy},- {"aten.all.default", op::translate_all},- {"aten.amax.default", op::translate_amax},- {"aten.amin.default", op::translate_amin},- {"aten.angle.default", common_translators::translate_angle},{"aten.any.default", op::translate_any_fx},{"aten.any.dim", op::translate_any_fx},{"aten.any.dims", op::translate_any_fx},{"aten.arange.default", op::translate_arange_fx},{"aten.arange.start", op::translate_arange_fx},{"aten.arange.start_step", op::translate_arange_fx},- {"aten.argmax.default", op::translate_argmax},- {"aten.argmin.default", op::translate_argmin},- {"aten.as_strided.default", op::translate_as_strided},{"aten.as_strided_.default", op::translate_as_strided},- {"aten.as_strided_copy.default", op::translate_as_strided},- {"aten.asin.default", op::translate_1to1_match_1_inputs_with_fp32_type_alignment<opset10::Asin>},- {"aten.asinh.default", op::translate_1to1_match_1_inputs_with_fp32_type_alignment<opset10::Asinh>},- {"aten.atan.default", op::translate_1to1_match_1_inputs_with_fp32_type_alignment<opset10::Atan>},- {"aten.atanh.default", op::translate_1to1_match_1_inputs_with_fp32_type_alignment<opset10::Atanh>},- {"aten.atan2.default", op::translate_atan2},- {"aten.avg_pool2d.default", op::translate_avg_pool2d},- {"aten.avg_pool3d.default", op::translate_avg_pool3d},+ {"aten.arctan2.default", op::translate_atan2},{"aten.baddbmm.default", op::translate_addmm_fx},- {"aten.bitwise_and.Scalar", op::translate_bitwise_and},- {"aten.bitwise_and.Tensor", op::translate_bitwise_and},- {"aten.bitwise_left_shift.Tensor", op::translate_bitwise_left_shift},- {"aten.bitwise_not.default", op::translate_bitwise_not},- {"aten.bitwise_or.Tensor", op::translate_bitwise_or},// {"aten.bitwise_right_shift.Tensor", op::translate_bitwise_right_shift}, - temporarily disable- {"aten.bitwise_xor.Tensor", op::translate_bitwise_xor},{"aten.bmm.default", op::translate_1to1_match_2_inputs_align_types<opset10::MatMul>},- {"aten.bucketize.Tensor", op::translate_bucketize},+ {"aten.broadcast_tensors.default", op::translate_list_unpack_fx},{"aten.cat.default", op::translate_cat_fx},- {"aten.ceil.default", op::translate_1to1_match_1_inputs<opset10::Ceiling>},- {"aten.celu.default", op::translate_celu},- {"aten.clamp.default", op::translate_clamp},- {"aten.clamp.Tensor", op::translate_clamp},- {"aten.clamp_max.default", op::translate_1to1_match_2_inputs_align_types<opset10::Minimum>},- {"aten.clamp_max.Tensor", op::translate_1to1_match_2_inputs_align_types<opset10::Minimum>},- {"aten.clamp_min.default", op::translate_1to1_match_2_inputs_align_types<opset10::Maximum>},- {"aten.clamp_min.Tensor", op::translate_1to1_match_2_inputs_align_types<opset10::Maximum>},- {"aten.clone.default", op::skip_node}, // ignore clone operators that are inserted by PyTorch autograd- {"aten.col2im.default", op::translate_col2im},- {"aten.constant_pad_nd.default", op::translate_constant_pad_nd},- {"aten.convolution.default", op::translate_convolution},+ {"aten.chunk.default", op::translate_list_view_fx},{"aten.copy.default", op::translate_copy_fx},- {"aten.copy_.default", op::translate_copy_},- {"aten.cos.default", op::translate_1to1_match_1_inputs_with_fp32_type_alignment<opset10::Cos>},- {"aten.cosh.default", op::translate_1to1_match_1_inputs_with_fp32_type_alignment<opset10::Cosh>},{"aten.cumsum.default", op::translate_cumsum_fx},- {"aten.channel_shuffle.default", op::translate_channel_shuffle},- {"aten.detach.default", op::skip_node},{"aten.detach_.default", op::skip_node},{"aten.div.Scalar", op::translate_div_fx},{"aten.div.Tensor", op::translate_div_fx},{"aten.div.Tensor_mode", op::translate_div_fx},{"aten.div_.Tensor", op::translate_div_fx_},- {"aten.elu.default", op::translate_elu},- {"aten.elu_.default", op::inplace_op<op::translate_elu>},- {"aten.embedding.default", op::translate_embedding},+ {"aten.empty_like.default", op::translate_zeros_like_fx},{"aten.empty.memory_format", op::translate_empty_fx},- {"aten.eq.Scalar", op::translate_1to1_match_2_inputs_align_types<opset10::Equal>},- {"aten.eq.Tensor", op::translate_1to1_match_2_inputs_align_types<opset10::Equal>},- {"aten.erf.default", op::translate_erf},- {"aten.erfc.default", op::translate_erfc},- {"aten.erfinv.default", op::translate_1to1_match_1_inputs_with_fp32_type_alignment<ov::op::v17::ErfInv>},- {"aten.exp.default", op::translate_1to1_match_1_inputs_with_fp32_type_alignment<opset10::Exp>},- {"aten.expm1.default", op::translate_expm1},- {"aten.expand.default", op::translate_expand},- {"aten.expand_copy.default", op::translate_expand},+ {"aten.eye.default", op::translate_eye_fx},{"aten.eye.m", op::translate_eye_fx},{"aten.fake_quantize_per_channel_affine_cachemask.default", op::translate_fake_quantize_per_channel_affine_fx},{"aten.fake_quantize_per_tensor_affine_cachemask.default", op::translate_fake_quantize_per_tensor_affine_fx},- {"aten.fill.Scalar", op::translate_fill},- {"aten.fill_.Scalar", op::inplace_op<op::translate_fill>},- {"aten.fill.Tensor", op::translate_fill},- {"aten.fill_.Tensor", op::inplace_op<op::translate_fill>},- {"aten.flip.default", op::translate_flip},- {"aten.floor.default", op::translate_1to1_match_1_inputs<opset10::Floor>},- {"aten.floor_divide.default", op::translate_floor_divide},- {"aten.fmod.Scalar", op::translate_fmod},- {"aten.fmod.Tensor", op::translate_fmod},{"aten.full.default", op::translate_full_fx},{"aten.full.names", op::translate_full_fx},{"aten.full_like.default", op::translate_full_like_fx},- {"aten.gather.default", op::translate_gather},- {"aten.ge.Scalar", op::translate_1to1_match_2_inputs_align_types<opset10::GreaterEqual>},- {"aten.ge.Tensor", op::translate_1to1_match_2_inputs_align_types<opset10::GreaterEqual>},{"aten.gelu.default", op::translate_gelu_fx},- {"aten.glu.default", op::translate_glu},{"aten.grid_sampler_2d.default", op::translate_grid_sampler},- {"aten.gt.Scalar", op::translate_1to1_match_2_inputs_align_types<opset10::Greater>},- {"aten.gt.Tensor", op::translate_1to1_match_2_inputs_align_types<opset10::Greater>},- {"aten.hardsigmoid.default", op::translate_1to1_match_1_inputs<opset10::HSigmoid>},- {"aten.hardswish.default", op::translate_1to1_match_1_inputs<opset10::HSwish>},- {"aten.hardswish_.default", op::inplace_op<op::translate_1to1_match_1_inputs<opset10::HSwish>>},- {"aten.hardtanh.default", op::translate_hardtanh},- {"aten.hardtanh_.default", op::inplace_op<op::translate_hardtanh>},{"aten.index.Tensor", op::translate_index_fx},{"aten._unsafe_index.Tensor", op::translate_index_fx},- {"aten.index_select.default", op::translate_index_select},- {"aten.index_add.default", op::translate_index_add},- {"aten.index_add_.default", op::inplace_op<op::translate_index_add>},{"aten.index_fill.int_Scalar", op::translate_index_fill_},- {"aten.index_fill_.int_Scalar", op::inplace_op<op::translate_index_fill_>},- {"aten.index_copy.default", op::translate_index_copy_},- {"aten.index_put.default", op::translate_index_put},- {"aten.instance_norm.default", op::translate_instance_norm},- {"aten.isfinite.default", op::translate_1to1_match_1_inputs<opset10::IsFinite>},- {"aten.isinf.default", op::translate_1to1_match_1_inputs<opset10::IsInf>},- {"aten.isnan.default", op::translate_1to1_match_1_inputs<opset10::IsNaN>},- {"aten.le.Scalar", op::translate_1to1_match_2_inputs_align_types<opset10::LessEqual>},- {"aten.le.Tensor", op::translate_1to1_match_2_inputs_align_types<opset10::LessEqual>},{"aten.leaky_relu.default", op::translate_leaky_relu_fx},{"aten.leaky_relu_.default", op::inplace_op<op::translate_leaky_relu_fx>},- {"aten.lift_fresh_copy.default", op::skip_node},- {"aten.linalg_vector_norm.default", op::translate_linalg_vector_norm},- {"aten.linear.default", op::translate_linear},- {"aten.linalg_cross.default", op::translate_linalg_cross},- {"aten.linspace.default", op::translate_linspace},- {"aten.log.default", op::translate_1to1_match_1_inputs_with_fp32_type_alignment<opset10::Log>},- {"aten.logaddexp.default", op::translate_logaddexp},{"aten.log_sigmoid_forward.default", op::translate_log_sigmoid_fx},- {"aten.log10.default", op::translate_log10},- {"aten.log1p.default", op::translate_log1p},- {"aten.log2.default", op::translate_log2},- {"aten.logical_and.default", op::translate_and},- {"aten.logical_not.default", op::translate_not},- {"aten.logical_or.default", op::translate_or},- {"aten.logical_xor.default", op::translate_xor},- {"aten.logsumexp.default", op::translate_logsumexp},- {"aten.dot.default", op::translate_dot},- {"aten.gcd.default", op::translate_gcd},- {"aten.hstack.default", op::translate_hstack},- {"aten.kthvalue.default", op::translate_kthvalue},- {"aten.lt.Scalar", op::translate_1to1_match_2_inputs_align_types<opset10::Less>},- {"aten.lt.Tensor", op::translate_1to1_match_2_inputs_align_types<opset10::Less>},- {"aten.masked_fill.Scalar", op::translate_masked_fill},- {"aten.masked_fill.Tensor", op::translate_masked_fill},- {"aten.masked_fill_.Scalar", op::inplace_op<op::translate_masked_fill>},- {"aten.masked_fill_.Tensor", op::inplace_op<op::translate_masked_fill>},- {"aten.masked_scatter.default", op::translate_masked_scatter},- {"aten.max.default", op::translate_max},- {"aten.max.dim", op::translate_max_dim_fx},- {"aten.max_pool2d_with_indices.default", op::translate_max_pool2d_fx},- {"aten.max_pool3d_with_indices.default", op::translate_max_pool3d_fx},- {"aten.maximum.default", op::translate_maximum},{"aten.mean.default", op::translate_mean_fx},{"aten.mean.dim", op::translate_mean_fx},- {"aten.min.default", op::translate_min},- {"aten.min.dim", op::translate_min_dim_fx},- {"aten.minimum.default", op::translate_minimum},- {"aten.mish.default", op::translate_1to1_match_1_inputs_with_fp32_type_alignment<opset10::Mish>},- {"aten.mm.default", op::translate_1to1_match_2_inputs<opset10::MatMul>},- {"aten.mul.Scalar", op::translate_mul},- {"aten.mul.Tensor", op::translate_mul},- {"aten.mul_.Tensor", op::translate_mul},{"aten.native_batch_norm.default", op::translate_batch_norm_legit_fx},{"aten.native_dropout.default", op::skip_node},{"aten.native_group_norm.default", op::translate_group_norm_fx},{"aten.native_layer_norm.default", op::translate_layer_norm_fx},- {"aten.ne.Scalar", op::translate_1to1_match_2_inputs_align_types<opset10::NotEqual>},- {"aten.ne.Tensor", op::translate_1to1_match_2_inputs_align_types<opset10::NotEqual>},- {"aten.neg.default", op::translate_neg},+ {"aten.new_empty.default", op::translate_new_zeros_fx},{"aten.new_full.default", op::translate_new_full_fx},{"aten.new_ones.default", op::translate_new_ones_fx},{"aten.new_zeros.default", op::translate_new_zeros_fx},- {"aten.nonzero.default", op::translate_nonzero},+ {"aten.nonzero_numpy.default", op::translate_list_unpack_fx},{"aten.ones.default", op::translate_ones_fx},{"aten.ones.names", op::translate_ones_fx},{"aten.ones_like.default", op::translate_ones_like_fx},- {"aten.one_hot.default", op::translate_one_hot},- {"aten.outer.default", op::translate_outer},- {"aten.permute.default", op::translate_permute},- {"aten.permute_copy.default", op::translate_permute},- {"aten.pow.Scalar", op::translate_pow},- {"aten.pow.Tensor_Scalar", op::translate_pow},- {"aten.pow.Tensor_Tensor", op::translate_pow},- {"aten.pixel_shuffle.default", op::translate_pixel_shuffle},- {"aten.pixel_unshuffle.default", op::translate_pixel_unshuffle},{"aten.prod.default", op::translate_prod_fx},{"aten.prod.dim_int", op::translate_prod_fx},- {"aten.rand.default", op::translate_rand},- {"aten.reciprocal.default", op::translate_reciprocal},- {"aten.reflection_pad1d.default", op::translate_reflection_pad_nd},- {"aten.reflection_pad2d.default", op::translate_reflection_pad_nd},- {"aten.reflection_pad3d.default", op::translate_reflection_pad_nd},- {"aten.relu.default", op::translate_1to1_match_1_inputs<opset10::Relu>},- {"aten.relu_.default", op::inplace_op<op::translate_1to1_match_1_inputs<opset10::Relu>>},- {"aten.rrelu.default", op::translate_rrelu},- {"aten.rrelu_.default", op::inplace_op<op::translate_rrelu>},- {"aten.remainder.default", op::translate_remainder},- {"aten.remainder.Scalar", op::translate_remainder},- {"aten.remainder.Tensor", op::translate_remainder},{"aten.repeat.default", op::translate_repeat_fx},- {"aten.repeat_interleave.self_int", op::translate_repeat_interleave},- {"aten.repeat_interleave.self_Tensor", op::translate_repeat_interleave},- {"aten.rms_norm.default", op::translate_rms_norm},- {"aten.roll.default", op::translate_roll},- {"aten.rad2deg.default", op::translate_rad2deg},- {"aten.rot90.default", op::translate_rot90},- {"aten.round.default", op::translate_round},- {"aten.round.out", op::translate_round},- {"aten.rsqrt.default", op::translate_rsqrt},{"aten.rsub.Scalar", op::translate_rsub_fx},{"aten.rsub.Tensor", op::translate_rsub_fx},- {"aten.scalar_tensor.default", op::translate_scalar_tensor_fx},- {"aten.scaled_dot_product_attention.default", op::translate_scaled_dot_product_attention},- {"aten.scatter.src", op::translate_scatter},- {"aten.scatter.value", op::translate_scatter},- {"aten.scatter_add.default", op::translate_scatter_add},- {"aten.searchsorted.Tensor", op::translate_search_sorted},- {"aten.select.int", op::translate_select},- {"aten.select_copy.int", op::translate_select},{"aten.select_scatter.default", op::translate_select_scatter_fx},- {"aten.sigmoid.default", op::translate_1to1_match_1_inputs_with_fp32_type_alignment<opset10::Sigmoid>},- {"aten.sigmoid_.default", op::translate_1to1_match_1_inputs_with_fp32_type_alignment<opset10::Sigmoid>},- {"aten.sign.default", op::translate_sign},- {"aten.silu.default", op::translate_1to1_match_1_inputs<opset10::Swish>},- {"aten.silu_.default", op::inplace_op<op::translate_1to1_match_1_inputs<opset10::Swish>>},- {"aten.sin.default", op::translate_1to1_match_1_inputs_with_fp32_type_alignment<opset10::Sin>},- {"aten.sinh.default", op::translate_1to1_match_1_inputs_with_fp32_type_alignment<opset10::Sinh>},{"aten.slice.Tensor", op::translate_slice_fx},{"aten.slice_copy.Tensor", op::translate_slice_fx},{"aten.slice_scatter.default", op::translate_slice_scatter_fx},- {"aten.argsort.default", op::translate_argsort_fx},- {"aten.argsort.stable", op::translate_argsort_fx},- {"aten.sort.default", op::translate_sort_fx},- {"aten.sort.stable", op::translate_sort_fx},- {"aten.split.Tensor", op::translate_chunk_fx},- {"aten.split_with_sizes.default", op::translate_split_with_sizes},- {"aten.split_with_sizes_copy.default", op::translate_split_with_sizes},- {"aten.sqrt.default", op::translate_1to1_match_1_inputs_with_fp32_type_alignment<opset10::Sqrt>},- {"aten.squeeze.dim", op::translate_squeeze},- {"aten.squeeze.dims", op::translate_squeeze},- {"aten.squeeze_copy.dims", op::translate_squeeze},+ {"aten.split.Tensor", op::translate_list_view_fx},{"aten.stack.default", op::translate_stack_fx},{"aten.std.correction", op::translate_std_fx},- {"aten.sub.default", op::translate_sub_fx},- {"aten.sub.Tensor", op::translate_sub_fx},{"aten.sum.default", op::translate_sum_fx},{"aten.sum.dim_IntList", op::translate_sum_fx},{"aten.sym_size.int", op::translate_size},- {"aten.t.default", op::translate_t},- {"aten.take_along_dim.default", op::translate_take_along_dim},- {"aten.tan.default", op::translate_1to1_match_1_inputs_with_fp32_type_alignment<opset10::Tan>},- {"aten.tanh.default", op::translate_1to1_match_1_inputs_with_fp32_type_alignment<opset10::Tanh>},- {"aten.topk.default", op::translate_topk_fx},- {"aten.transpose.int", op::translate_transpose},- {"aten.tril.default", op::translate_tril},- {"aten.triu.default", op::translate_triu},- {"aten.unbind.int", op::translate_unbind_int_fx},- {"aten.unfold.default", op::translate_unfold},- {"aten.unsqueeze.default", common_translators::translate_unsqueeze},+ {"aten.tensor_split.indices", op::translate_list_view_fx},+ {"aten.tensor_split.sections", op::translate_list_view_fx},+ {"aten.to.dtype_layout", op::translate_to_fx},+ {"aten.unbind.int", op::translate_list_view_fx},+ {"aten.unsafe_chunk.default", op::translate_list_view_fx},{"aten.unsqueeze_copy.default", op::translate_1to1_match_2_inputs<opset10::Unsqueeze>},- {"aten.upsample_bicubic2d.default", op::translate_upsample_bicubic2d},- {"aten.upsample_bicubic2d.vec", op::translate_upsample_bicubic2d},- {"aten.upsample_bilinear2d", op::translate_upsample_bilinear2d},- {"aten.upsample_bilinear2d.vec", op::translate_upsample_bilinear2d},- {"aten.upsample_bilinear2d.default", op::translate_upsample_bilinear2d},- {"aten.upsample_linear1d.vec", op::translate_upsample_linear1d},- {"aten.upsample_nearest1d.default", op::translate_upsample_nearest1d},- {"aten.upsample_nearest1d.vec", op::translate_upsample_nearest1d},- {"aten.upsample_nearest2d.default", op::translate_upsample_nearest2d},- {"aten.upsample_nearest2d.vec", op::translate_upsample_nearest2d},- {"aten.upsample_nearest3d.default", op::translate_upsample_nearest3d},- {"aten.upsample_nearest3d.vec", op::translate_upsample_nearest3d},- {"aten.upsample_trilinear3d.vec", op::translate_upsample_trilinear3d},{"aten.var.correction", op::translate_var_fx},{"aten.var_mean.correction", op::translate_var_mean_fx},- {"aten.vstack.default", op::translate_vstack},- {"aten.view.default", op::translate_reshape},- {"aten.view_copy.default", op::translate_reshape},- {"aten.view_as_complex.default", op::translate_view_as_complex},- {"aten.view_as_real.default", op::translate_view_as_real},- {"aten.where.default", op::translate_where},- {"aten.where.self", op::translate_where},{"aten.zero.default", op::translate_zeros_like_fx},{"aten.zeros.default", op::translate_zeros_fx},+ {"aten.zeros.out", op::translate_zeros_fx},{"aten.zeros.names", op::translate_zeros_fx},{"aten.zeros_like.default", op::translate_zeros_like_fx},{"get_attr", op::translate_constant},{"scalar_tensor.default", op::translate_scalar_tensor_fx},{"torchvision.deform_conv2d.default", op::translate_deform_conv},+ {"torchvision.nms.default", op::translate_nms},{"torchvision.roi_align.default", op::translate_roi_align},{"quantized_decomposed.quantize_per_tensor.default", op::translate_quantize_per_tensor_fx},{"quantized_decomposed.quantize_per_channel.default", op::translate_quantize_per_channel_fx},diff --git a/src/frontends/pytorch/src/transforms/aten_index_put_replacer.cpp b/src/frontends/pytorch/src/transforms/aten_index_put_replacer.cppindex be2b5ee286b..f09e02432ed 100644--- a/src/frontends/pytorch/src/transforms/aten_index_put_replacer.cpp+++ b/src/frontends/pytorch/src/transforms/aten_index_put_replacer.cpp@@ -38,7 +38,7 @@ using namespace ov::op;AtenIndexPutReplacer::AtenIndexPutReplacer() {auto index_op = ov::pass::pattern::wrap_type<ov::op::util::FrameworkNode>(- fw_node_predicate({"aten::index_put_", "aten.index_put.default"}));+ fw_node_predicate({"aten::index_put_", "aten.index_put.default", "aten.index_put_.default"}));ov::matcher_pass_callback callback = [](ov::pass::pattern::Matcher& m) {auto index_op = m.get_match_root();diff --git a/src/frontends/pytorch/src/transforms/einsum_list_construct.cpp b/src/frontends/pytorch/src/transforms/einsum_list_construct.cppdeleted file mode 100644index 3fc7bfec7c5..00000000000--- a/src/frontends/pytorch/src/transforms/einsum_list_construct.cpp+++ /dev/null@@ -1,63 +0,0 @@-// Copyright (C) 2018-2026 Intel Corporation-// SPDX-License-Identifier: Apache-2.0-//--#include "einsum_list_construct.hpp"--#include "openvino/core/graph_util.hpp"-#include "openvino/core/rt_info.hpp"-#include "openvino/frontend/sequence_mark.hpp"-#include "openvino/op/einsum.hpp"-#include "openvino/op/util/framework_node.hpp"-#include "openvino/pass/pattern/matcher.hpp"-#include "openvino/pass/pattern/op/wrap_type.hpp"-#include "utils.hpp"--using namespace ov::pass::pattern;--namespace ov {-namespace frontend {-namespace pytorch {-namespace pass {--using namespace ov::pass;-using namespace ov::op;--AtenEinsumListConstructReplacer::AtenEinsumListConstructReplacer() {- auto einsum_op = pattern::wrap_type<ov::op::util::FrameworkNode>(fw_node_predicate({"aten::einsum"}));- ov::matcher_pass_callback callback = [](pattern::Matcher& m) {- auto einsum_op = m.get_match_root();- const auto& equation_input = einsum_op->input_value(0).get_node_shared_ptr();- const auto& tensor_list = einsum_op->input_value(1).get_node_shared_ptr();- std::string equation;- if (const auto& fw_node_mode = cast_fw_node(equation_input, "prim::Constant")) {- const auto& attrs = fw_node_mode->get_attrs();- if (attrs.find("string_value") != attrs.end()) {- equation = attrs.at("string_value");- }- } else {- add_exception_to_fw_node(einsum_op, "aten::einsum: equation should be string constant.");- return false;- }- // Check if SequenceMark is an input- if (auto seq_mark = ov::as_type_ptr<SequenceMark>(tensor_list)) {- const auto& list_inputs = seq_mark->input_values();- OutputVector node_vector(list_inputs.begin(), list_inputs.end());- auto einsum = std::make_shared<v7::Einsum>(node_vector, equation);- copy_runtime_info_and_name(einsum_op, {einsum}, {equation_input, tensor_list});- replace_node(einsum_op, einsum);- return true;- }- add_exception_to_fw_node(einsum_op, "aten::einsum: unsupported case.");- return false;- };-- auto m =- std::make_shared<pattern::Matcher>(einsum_op, "ov::frontend::pytorch::pass::AtenEinsumListConstructReplacer");- this->register_matcher(m, callback);-};--} // namespace pass-} // namespace pytorch-} // namespace frontend-} // namespace ov\ No newline at end of filediff --git a/src/frontends/pytorch/src/transforms/einsum_list_construct.hpp b/src/frontends/pytorch/src/transforms/einsum_list_construct.hppdeleted file mode 100644index dda625c63cf..00000000000--- a/src/frontends/pytorch/src/transforms/einsum_list_construct.hpp+++ /dev/null@@ -1,24 +0,0 @@-// Copyright (C) 2018-2026 Intel Corporation-// SPDX-License-Identifier: Apache-2.0-//--#pragma once--#include "openvino/pass/graph_rewrite.hpp"-#include "openvino/pass/pass.hpp"--namespace ov {-namespace frontend {-namespace pytorch {-namespace pass {--class AtenEinsumListConstructReplacer : public ov::pass::MatcherPass {-public:- OPENVINO_MATCHER_PASS_RTTI("ov::frontend::pytorch::pass::AtenEinsumListConstructReplacer");- AtenEinsumListConstructReplacer();-};--} // namespace pass-} // namespace pytorch-} // namespace frontend-} // namespace ovdiff --git a/src/frontends/pytorch/src/translate_session.cpp b/src/frontends/pytorch/src/translate_session.cppindex 7628fe6e0d6..096448ac037 100644--- a/src/frontends/pytorch/src/translate_session.cpp+++ b/src/frontends/pytorch/src/translate_session.cpp@@ -7,8 +7,19 @@#include "helper_ops/gather_assign.hpp"#include "helper_ops/slice_assign.hpp"#include "input_model.hpp"+#include "openvino/core/validation_util.hpp"+#include "openvino/op/concat.hpp"#include "openvino/op/gather.hpp"+#include "openvino/op/range.hpp"+#include "openvino/op/reshape.hpp"+#include "openvino/op/scatter_elements_update.hpp"+#include "openvino/op/shape_of.hpp"#include "openvino/op/slice.hpp"+#include "openvino/op/split.hpp"+#include "openvino/op/squeeze.hpp"+#include "openvino/op/transpose.hpp"+#include "openvino/op/unsqueeze.hpp"+#include "openvino/op/variadic_split.hpp"#include "openvino/util/log.hpp"#include "place.hpp"#include "pt_framework_node.hpp"@@ -21,6 +32,22 @@ namespace pytorch {using namespace ov::op;namespace {+// Alias views and their base values belong to the graph where they were converted.+class AliasScope {+public:+ explicit AliasScope(TranslateSession& session) : m_session(session) {+ m_aliases.swap(m_session.m_may_be_alias);+ }++ ~AliasScope() {+ m_aliases.swap(m_session.m_may_be_alias);+ }++private:+ TranslateSession& m_session;+ decltype(TranslateSession::m_may_be_alias) m_aliases;+};+// Helper to extract complex part element type from raw typeelement::Type get_complex_part_type(const Any& raw_type) {element::Type complex_part_type = element::dynamic;@@ -87,8 +114,12 @@ std::shared_ptr<ov::Model> TranslateSession::translate_graph(const ov::frontend:FRONT_END_GENERAL_CHECK(pytorch_model != nullptr, "Invalid input model");auto model = convert_pytorch_model(pytorch_model->m_model_decoder, {}, pytorch_model);// First delete tensor indexes from outputs then resolve input names, otherwise Parameter->Result will fail+ std::set<Output<Node>> named_outputs;for (auto& result : model->get_results()) {auto tensor_desc = result->input_value(0);+ if (!named_outputs.insert(tensor_desc).second) {+ continue;+ }auto names = tensor_desc.get_names();if (!names.empty()) {auto tensor_idx = decode_tensor_name(tensor_desc);@@ -119,6 +150,10 @@ std::shared_ptr<Model> TranslateSession::convert_pytorch_model(std::shared_ptr<TorchDecoder> pytorch_model,const TensorMap& external_tensor_map,const std::shared_ptr<pytorch::InputModel>& input_model) {+ AliasScope alias_scope(*this);+ // The decoder type is a property of the decoder class, so read it once per graph rather+ // than per node; every access crosses into Python.+ m_is_fx = pytorch_model->decoder_type_name() == "fx";std::shared_ptr<Model> resulting_model; // define here to make a conversion in a nested scope{auto parameters = std::make_shared<ParameterVector>();@@ -206,8 +241,15 @@ std::shared_ptr<Model> TranslateSession::convert_pytorch_model(// Add op type in the statisticsm_op_statistics[context.get_op_type()]++;auto converted_outputs = convert_node(context);+ const bool has_out = m_is_fx && context.has_attribute("out");+ if (has_out) {+ FRONT_END_OP_CONVERSION_CHECK(converted_outputs.size() == 1, "Expected a single out tensor.");+ const auto out = context.get_input("out");+ converted_outputs[0] = ComplexTypeMark::convert_like(context, converted_outputs[0], out);+ context.mutate_input("out", converted_outputs[0]);+ }- const auto& fw_outputs = node->outputs();+ const auto fw_outputs = context.outputs();// Ops with subgraphs or with mutated inputs may have more outputs after conversion compared to pytorch onesFRONT_END_OP_CONVERSION_CHECK(fw_outputs.size() <= converted_outputs.size(),"Number of ",@@ -218,28 +260,51 @@ std::shared_ptr<Model> TranslateSession::convert_pytorch_model(converted_outputs.size()," respectively.");- const bool has_inputs = !node->inputs().empty();- const size_t in_tensor_id = has_inputs ? node->inputs().at(0) : 0;+ const bool has_inputs = !raw_inputs.empty();+ const size_t first_input_id = has_out ? node->get_named_input("out") : (has_inputs ? raw_inputs.at(0) : 0);+ const auto& op_type = context.get_op_type();+ const bool constructs_sequence = op_type == "prim::TupleConstruct" || op_type == "prim::ListConstruct";+ std::vector<size_t> unpacked_ids;+ const auto sequence = m_may_be_alias.find(first_input_id);+ if (sequence != m_may_be_alias.end() && !sequence->second.element_ids.empty()) {+ const auto& elements = sequence->second.element_ids;+ if (op_type == "prim::TupleUnpack" || op_type == "prim::ListUnpack") {+ unpacked_ids = elements;+ } else if (op_type == "aten::__getitem__") {+ if (const auto index_node = ov::util::get_constant_from_source(context.get_input(1))) {+ auto index = index_node->cast_vector<int64_t>().at(0);+ if (index < 0) {+ index += static_cast<int64_t>(elements.size());+ }+ if (index >= 0 && static_cast<size_t>(index) < elements.size()) {+ unpacked_ids = {elements[index]};+ }+ }+ }+ }for (size_t i = 0; i < fw_outputs.size(); ++i) {- size_t fw_tensor_id = node->output(i);- if (has_inputs && node->may_produce_alias(0, i)) {+ size_t fw_tensor_id = fw_outputs.at(i);+ const auto in_tensor_id = unpacked_ids.empty() ? first_input_id : unpacked_ids.at(i);+ if (has_out || (has_inputs && (constructs_sequence || node->may_produce_alias(0, i)))) {auto alias_iter = m_may_be_alias.find(fw_tensor_id);// TODO: do we need to check other inputs, not only 0?if (alias_iter != m_may_be_alias.end()) {- size_t recorded_in_tensor_id;- std::shared_ptr<TorchDecoder> recorded_node;- std::tie(recorded_in_tensor_id, recorded_node, std::ignore) = alias_iter->second;- FRONT_END_GENERAL_CHECK(recorded_in_tensor_id == in_tensor_id,+ const auto& recorded = alias_iter->second;+ FRONT_END_GENERAL_CHECK(recorded.base_id == in_tensor_id,"Operation ",context.get_op_type()," creates alias to tensor which was already created before by ",- recorded_node->get_op_type(),+ recorded.decoder->get_op_type(),", but from different tensor: ",in_tensor_id," vs ",- recorded_in_tensor_id);+ recorded.base_id);}- m_may_be_alias[fw_tensor_id] = {node->inputs().at(0), node, converted_outputs[i]};+ m_may_be_alias[fw_tensor_id] = {in_tensor_id,+ node,+ converted_outputs[i],+ tensor_map->at(in_tensor_id),+ constructs_sequence ? raw_inputs : std::vector<size_t>{}};OPENVINO_DEBUG("Registered alias: ",fw_tensor_id," of tensor: ",@@ -275,6 +340,7 @@ std::shared_ptr<Model> TranslateSession::convert_pytorch_model("Model should have exactly 1 subgraph for TorchScript.");pytorch_model->visit_subgraph(node_visitor);+ NodeContext output_context(pytorch_model, external_tensor_map, tensor_map, parameters, mutated_tensors, this);ResultVector results;if (input_model) {// For the case when we have InputModel we need to have same order as its outputs@@ -282,7 +348,7 @@ std::shared_ptr<Model> TranslateSession::convert_pytorch_model(auto pytorch_place = std::dynamic_pointer_cast<pytorch::Place>(output_p);FRONT_END_GENERAL_CHECK(pytorch_place, "Only place produced by PyTorch Frontend is supported.");auto tensor_id = pytorch_place->get_tensor_index();- auto ov_output = tensor_map->at(tensor_id);+ auto ov_output = output_context.resolve_tensor(tensor_id);FRONT_END_GENERAL_CHECK(!ov_output.get_names().empty(),"Tensor doesn't have name, while it should have name: ",tensor_id);@@ -303,7 +369,7 @@ std::shared_ptr<Model> TranslateSession::convert_pytorch_model(FRONT_END_GENERAL_CHECK(!it->second.get_names().empty(),"Tensor doesn't have name, while it should have name: ",id);- auto result = std::make_shared<v0::Result>(it->second);+ auto result = std::make_shared<v0::Result>(output_context.resolve_tensor(id));results.push_back(result);}}@@ -354,10 +420,23 @@ std::shared_ptr<Model> TranslateSession::convert_pytorch_model(OutputVector TranslateSession::convert_node(const NodeContext& context) {std::string exception;try {- const auto& op_type = context.get_op_type();- auto it = m_translator_map.find(op_type);+ const auto& raw_op_type = context.get_op_type();+ auto it = m_translator_map.find(raw_op_type);+ // FX names carry an overload suffix; fall back to the shared TorchScript translator for the same operator.+ // Stays empty unless that fallback is needed, so the common path does not copy the name.+ std::string canonical_op_type;+ if (it == m_translator_map.end()) {+ canonical_op_type = normalize_op_type(raw_op_type);+ it = m_translator_map.find(canonical_op_type);+ }+ const std::string& op_type = canonical_op_type.empty() ? raw_op_type : canonical_op_type;if (it != m_translator_map.end()) {- return it->second(context);+ auto outputs = it->second(context);+ // FX represents multiple operator results as a single tuple value.+ if (outputs.size() > 1 && m_is_fx) {+ return {context.mark_node(make_list_construct(outputs))};+ }+ return outputs;} else if (op_type.back() == '_') {// inplace op casestd::string op_type_cut = op_type.substr(0, op_type.size() - 1);@@ -476,21 +555,95 @@ Output<Node> select_reverseprop(const Output<Node>& select_output, const Output<}} // namespace-using ReversepropCreatorFunction = std::function<ov::Output<ov::Node>(const Output<Node>&, const Output<Node>&)>;-Output<Node> TranslateSession::get_reverseprop_op(const std::shared_ptr<TorchDecoder>& node,const Output<Node>& direct_op_output,- const Output<Node>& value) {- static const std::map<std::string, ReversepropCreatorFunction> backprop_map = {- {"aten::slice", slice_reverseprop},- {"aten::select", select_reverseprop},- };-- Output<Node> backprop_node;+ const Output<Node>& value,+ const Output<Node>& base) {try {- auto it = backprop_map.find(node->get_op_type());- if (it != backprop_map.end()) {- return it->second(direct_op_output, value);+ const auto direct_node = direct_op_output.get_node_shared_ptr();+ if (base.get_node()) {+ if (direct_op_output == base) {+ return value;+ }+ if (const auto sequence = ov::as_type_ptr<SequenceMark>(base.get_node_shared_ptr())) {+ auto elements = sequence->get_sequence();+ for (auto& element : elements) {+ if (direct_op_output == element) {+ element = value;+ return make_list_construct(elements);+ }+ }+ }+ if (const auto sequence = ov::as_type_ptr<SequenceMark>(direct_node)) {+ const auto updated_sequence = ov::as_type_ptr<SequenceMark>(value.get_node_shared_ptr());+ FRONT_END_OP_CONVERSION_CHECK(updated_sequence, "Expected an aliased list update.");+ const auto elements = sequence->get_sequence();+ const auto updates = updated_sequence->get_sequence();+ FRONT_END_OP_CONVERSION_CHECK(elements.size() == updates.size(),+ "An aliased list cannot change length.");+ Output<Node> updated_base;+ for (size_t i = 0; i < elements.size(); ++i) {+ if (elements[i] != updates[i]) {+ FRONT_END_OP_CONVERSION_CHECK(!updated_base.get_node(), "Expected one updated list element.");+ updated_base = get_reverseprop_op(node, elements[i], updates[i], base);+ }+ }+ return updated_base.get_node() ? updated_base : base;+ }+ if (const auto complex_base = ov::as_type_ptr<ComplexTypeMark>(base.get_node_shared_ptr())) {+ if (direct_op_output == complex_base->get_data()) {+ return std::make_shared<ComplexTypeMark>(value, value.get_element_type());+ }+ if (direct_op_output == complex_base->get_real()) {+ return std::make_shared<ComplexTypeMark>(value, complex_base->get_imag());+ }+ if (direct_op_output == complex_base->get_imag()) {+ return std::make_shared<ComplexTypeMark>(complex_base->get_real(), value);+ }+ }+ if (const auto complex_view = ov::as_type_ptr<ComplexTypeMark>(direct_node)) {+ const auto complex_value = ov::as_type_ptr<ComplexTypeMark>(value.get_node_shared_ptr());+ FRONT_END_OP_CONVERSION_CHECK(complex_value, "Expected a complex alias update.");+ return get_reverseprop_op(node, complex_view->get_data(), complex_value->get_data(), base);+ }+ const auto updated = get_reverseprop_op(node, direct_op_output, value);+ if (ov::as_type_ptr<PtFrameworkNode>(updated.get_node_shared_ptr())) {+ return updated;+ }+ return get_reverseprop_op(node, direct_node->input_value(0), updated, base);+ }+ if (ov::is_type<v0::Convert>(direct_node) || ov::is_type<v1::ConvertLike>(direct_node)) {+ return value;+ }+ if (ov::is_type<v8::Slice>(direct_node)) {+ return slice_reverseprop(direct_op_output, value);+ }+ if (ov::is_type<v8::Gather>(direct_node)) {+ return select_reverseprop(direct_op_output, value);+ }+ if (ov::is_type<v1::Split>(direct_node) || ov::is_type<v1::VariadicSplit>(direct_node)) {+ const auto axis = ov::util::get_constant_from_source(direct_node->input_value(1));+ FRONT_END_OP_CONVERSION_CHECK(axis, "Cannot reverse a split with a dynamic axis.");+ auto outputs = direct_node->outputs();+ outputs[direct_op_output.get_index()] = value;+ return std::make_shared<v0::Concat>(outputs, axis->cast_vector<int64_t>().at(0));+ }+ if (ov::is_type<v1::Reshape>(direct_node) || ov::is_type<v0::Squeeze>(direct_node) ||+ ov::is_type<v0::Unsqueeze>(direct_node)) {+ return std::make_shared<v1::Reshape>(value,+ std::make_shared<v3::ShapeOf>(direct_node->input_value(0)),+ false);+ }+ if (ov::is_type<v1::Transpose>(direct_node)) {+ const auto order = direct_node->input_value(1);+ const auto zero = v0::Constant::create(element::i32, Shape{}, {0});+ const auto one = v0::Constant::create(element::i32, Shape{}, {1});+ const auto shape = std::make_shared<v3::ShapeOf>(order, element::i32);+ const auto rank = std::make_shared<v8::Gather>(shape, zero, zero);+ const auto axes = std::make_shared<v4::Range>(zero, rank, one, order.get_element_type());+ // inverse[order[i]] = i, including permutations built from a dynamic rank.+ const auto inverse = std::make_shared<v3::ScatterElementsUpdate>(axes, order, axes, zero);+ return std::make_shared<v1::Transpose>(value, inverse);}}diff --git a/src/frontends/pytorch/src/translate_session.hpp b/src/frontends/pytorch/src/translate_session.hppindex 1dc18d97e2b..ff66665947a 100644--- a/src/frontends/pytorch/src/translate_session.hpp+++ b/src/frontends/pytorch/src/translate_session.hpp@@ -37,7 +37,8 @@ public:/// \brief Returns reverseprop operations for direct operationOutput<Node> get_reverseprop_op(const std::shared_ptr<TorchDecoder>& node,const Output<Node>& direct_op_output,- const Output<Node>& value);+ const Output<Node>& value,+ const Output<Node>& base = {});/// \brief Writes pytorch tensor index into openvino tensorvoid encode_tensor_name(Output<Node> tensor_desc,@@ -47,9 +48,16 @@ public:/// \brief Gets pytorch tensor index from openvino tensorsize_t decode_tensor_name(const Output<Node>& tensor_desc);- // Maps tensor index to initial tensor index which it is alias to, and to decoder of the node produced this alias- // and to the output produced during conversion of this node- std::map<size_t, std::tuple<size_t, std::shared_ptr<TorchDecoder>, Output<Node>>> m_may_be_alias;+ struct AliasInfo {+ size_t base_id;+ std::shared_ptr<TorchDecoder> decoder;+ Output<Node> output;+ // Base value used to convert and replay a view.+ Output<Node> base_value;+ // Constructed containers hold references to distinct tensors, not views of input 0.+ std::vector<size_t> element_ids;+ };+ std::map<size_t, AliasInfo> m_may_be_alias;OutputVector convert_node(const NodeContext& context);@@ -61,6 +69,8 @@ private:std::map<size_t, std::pair<size_t, Output<Node>>> m_counter_map;std::map<std::string, uint64_t> m_op_statistics;+ // Set per converted graph in convert_pytorch_model; the decoder type never varies within one.+ bool m_is_fx = false;};} // namespace pytorchdiff --git a/src/frontends/pytorch/src/utils.cpp b/src/frontends/pytorch/src/utils.cppindex 1ba74a1550d..c45e7dd4afa 100644--- a/src/frontends/pytorch/src/utils.cpp+++ b/src/frontends/pytorch/src/utils.cpp@@ -330,6 +330,18 @@ Output<Node> apply_dtype(const NodeContext& context, size_t dtype_port, const Oureturn input_tensor;};+Output<Node> apply_optional_dtype(const NodeContext& context, size_t dtype_port, const Output<Node>& input_tensor) {+ if (!context.input_is_none(dtype_port)) {+ return apply_dtype(context, dtype_port, input_tensor);+ }+ if (context.has_attribute("dtype")) {+ // Export passes the keyword-only dtype as an attribute already resolved to an OpenVINO type.+ return context.mark_node(+ std::make_shared<v0::Convert>(input_tensor, context.get_attribute<element::Type>("dtype")));+ }+ return input_tensor;+};+PadType convert_pad(const std::string& pt_pad) {FRONT_END_OP_CONVERSION_CHECK(TORCH_AUTO_PAD_TO_OV.count(pt_pad), "Unknown pad: ", pt_pad);return TORCH_AUTO_PAD_TO_OV.at(pt_pad);@@ -572,6 +584,18 @@ bool is_python_scalar_input(const NodeContext& context, size_t index) {return context.get_input_type(index).is<type::PyScalar>();}+std::string normalize_op_type(const std::string& op_type) {+ constexpr std::string_view fx_prefix = "aten.";+ if (op_type.compare(0, fx_prefix.size(), fx_prefix) != 0) {+ return op_type;+ }+ const auto overload = op_type.find('.', fx_prefix.size());+ if (overload == std::string::npos) {+ return op_type;+ }+ return "aten::" + op_type.substr(fx_prefix.size(), overload - fx_prefix.size());+}+void align_eltwise_input_types(const NodeContext& context,Output<Node>& lhs,Output<Node>& rhs,diff --git a/src/frontends/pytorch/src/utils.hpp b/src/frontends/pytorch/src/utils.hppindex a9253583069..635c5e8687d 100644--- a/src/frontends/pytorch/src/utils.hpp+++ b/src/frontends/pytorch/src/utils.hpp@@ -86,6 +86,10 @@ bool is_complex_dtype(int64_t pt_type);Output<Node> apply_dtype(const NodeContext& context, size_t dtype_port, const Output<Node>& input_tensor);+/// \brief Applies an optional `dtype` argument, which export may pass positionally or as an attribute.+/// \return The converted tensor, or \p input_tensor unchanged when no dtype was given.+Output<Node> apply_optional_dtype(const NodeContext& context, size_t dtype_port, const Output<Node>& input_tensor);+op::PadType convert_pad(const std::string& pt_pad);Output<Node> concat_list_construct(const Output<Node>& input);@@ -117,6 +121,25 @@ void add_exception_to_fw_node(std::shared_ptr<Node> node, const std::string& msgbool is_python_scalar_input(const NodeContext& context, size_t index);+/// \brief Converts an operation name to its canonical TorchScript spelling.+///+/// FX names carry an overload suffix, e.g. `aten.add.Tensor`, while TorchScript uses `aten::add`. Translators and+/// transformations match the TorchScript spelling, so both decoders are normalized to it. Names which are not in the+/// `aten.name.overload` form are returned unchanged.+std::string normalize_op_type(const std::string& op_type);++/// \brief Reads an optional operator argument which export may pass either positionally or by keyword.+///+/// Export omits arguments equal to their default and passes keyword-only arguments as attributes, so an optional+/// argument may arrive as input \p index, as attribute \p name, or not at all.+template <typename T>+T get_const_input_or_attribute(const NodeContext& context, size_t index, const std::string& name, T default_value) {+ if (!context.input_is_none(index)) {+ return context.const_input<T>(index);+ }+ return context.get_attribute<T>(name, default_value);+}+void align_eltwise_input_types(const NodeContext& context,Output<Node>& lhs,Output<Node>& rhs,diff --git a/tests/constraints.txt b/tests/constraints.txtindex ca67b801d36..f0899b33b26 100644--- a/tests/constraints.txt+++ b/tests/constraints.txt@@ -25,5 +25,5 @@ pytest-timeout==2.4.0kornia==0.8.3--extra-index-url https://download.pytorch.org/whl/cpu-torch~=2.12.0-torchvision~=0.27.0+torch~=2.13.0+torchvision~=0.28.0diff --git a/tests/layer_tests/py_frontend_tests/test_torch_decoder.py b/tests/layer_tests/py_frontend_tests/test_torch_decoder.pyindex e5214b35ad2..3045f6811e6 100644--- a/tests/layer_tests/py_frontend_tests/test_torch_decoder.py+++ b/tests/layer_tests/py_frontend_tests/test_torch_decoder.py@@ -780,6 +780,33 @@ def test_pytorch_fx_decoder_extracts_signature():assert nc_decoder._input_signature == ["a", "b"][email protected]("return_indices", [False, True])+def test_pytorch_fx_pool_without_output_metadata(return_indices):+ import numpy as np+ from torch.fx.experimental.proxy_tensor import make_fx+ from openvino import Core, convert_model+ from openvino.frontend.pytorch.fx_decoder import TorchFXPythonDecoder++ def model(data):+ return torch.nn.functional.max_pool2d(data, 2, return_indices=return_indices)++ data = torch.arange(16, dtype=torch.float32).reshape(1, 1, 4, 4)+ graph = make_fx(model)(data)+ for node in graph.graph.nodes:+ if node.target == torch.ops.aten.max_pool2d_with_indices.default:+ node.meta.clear()+ converted = convert_model(TorchFXPythonDecoder(graph))+ compiled = Core().compile_model(converted, "CPU")+ actual = compiled([data.numpy()])+ expected = model(data)+ if not return_indices:+ expected = (expected,)+ assert len(actual) == len(expected)+ for index, value in enumerate(expected):+ np.testing.assert_array_equal(actual[index], value.numpy())++@pytest.mark.parametrize(("testing_value", "expected"),[@@ -794,4 +821,3 @@ def test_pytorch_fx_decoder_extracts_signature():def test_is_testing_flag(testing_value, expected):"""Test that the _is_testing flag evaluates correctly."""assert _is_testing({"testing": testing_value}) == expected-\ No newline at end of filediff --git a/tests/layer_tests/pytorch_tests/conftest.py b/tests/layer_tests/pytorch_tests/conftest.pyindex 20271c22e05..f293fffdaee 100644--- a/tests/layer_tests/pytorch_tests/conftest.py+++ b/tests/layer_tests/pytorch_tests/conftest.py@@ -2,41 +2,10 @@# SPDX-License-Identifier: Apache-2.0import inspect-import osfrom pytorch_layer_test_class import get_params-def _patch_cia_ops_cache():- """Cache _collect_all_valid_cia_ops to speed up run_decompositions.-- PyTorch's run_decompositions() calls _collect_all_valid_cia_ops() on every- invocation, scanning 12K+ registered ops across 46 namespaces. The result- is constant within a process, so caching it saves ~18ms per model conversion.- """- try:- import torch._export.utils as _export_utils- _orig_collect = _export_utils._collect_all_valid_cia_ops- _cached_result = None-- def _cached_collect_all_valid_cia_ops():- nonlocal _cached_result- if _cached_result is None:- _cached_result = _orig_collect()- return _cached_result-- _export_utils._collect_all_valid_cia_ops = _cached_collect_all_valid_cia_ops- import torch.export.exported_program as _ep_module- if hasattr(_ep_module, '_collect_all_valid_cia_ops'):- _ep_module._collect_all_valid_cia_ops = _cached_collect_all_valid_cia_ops- except (ImportError, AttributeError):- pass---if os.environ.get("PYTORCH_TRACING_MODE", "").upper() == "EXPORT":- _patch_cia_ops_cache()--def pytest_generate_tests(metafunc):test_gen_attrs_names = list(inspect.signature(get_params).parameters)params = get_params()diff --git a/tests/layer_tests/pytorch_tests/pytorch_layer_test_class.py b/tests/layer_tests/pytorch_tests/pytorch_layer_test_class.pyindex 3bc8d5712db..cbb7da04e2e 100644--- a/tests/layer_tests/pytorch_tests/pytorch_layer_test_class.py+++ b/tests/layer_tests/pytorch_tests/pytorch_layer_test_class.py@@ -265,6 +265,15 @@ class PytorchLayerTest:return torch_compile_env == "EXPORT"return False+ @staticmethod+ def out_variant(eager_op, aten_out_op):+ """Picks the callable that keeps an ``out=`` argument in the traced graph.++ torch.export traces the Python ``out=`` API into its functional form, so the ATen+ ``.out`` overload has to be called directly to exercise the out-variant conversion.+ """+ return aten_out_op if PytorchLayerTest.use_torch_export() else eager_op+def _test(self, model, kind, ie_device, precision, ir_version, infer_timeout=60, dynamic_shapes=True,**kwargs):@@ -337,7 +346,7 @@ class PytorchLayerTest:dynamic_shapes = kwargs.get('dynamic_shapes_for_export', {})- em = export(model, tuple(torch_inputs), dynamic_shapes=dynamic_shapes)+ em = export(deepcopy(model), tuple(deepcopy(torch_inputs)), dynamic_shapes=dynamic_shapes)# Verify FX graph operations exist# Use explicit fx_kind if provided, otherwise auto-derive from TorchScript kinddiff --git a/tests/layer_tests/pytorch_tests/test_add.py b/tests/layer_tests/pytorch_tests/test_add.pyindex 9b1112348ce..337a90e09a5 100644--- a/tests/layer_tests/pytorch_tests/test_add.py+++ b/tests/layer_tests/pytorch_tests/test_add.py@@ -4,7 +4,7 @@import pytestimport torch-from pytorch_layer_test_class import PytorchLayerTest, skip_check+from pytorch_layer_test_class import PytorchLayerTest, skip_if_fx@pytest.mark.parametrize('alpha', (-0.5, 0, 0.5, 1, 2))@@ -39,11 +39,11 @@ class TestAdd(PytorchLayerTest):@pytest.mark.precommit@pytest.mark.precommit_torch_export@pytest.mark.precommit_fx_backend- @pytest.mark.parametrize("op_type", ["add", skip_check("add_")])+ @pytest.mark.parametrize("op_type", ["add", skip_if_fx("add_")])def test_add(self, ie_device, precision, ir_version, alpha, input_shape_rhs, op_type):self.input_rhs = self.random.randn(*input_shape_rhs)self._test(*self.create_model(alpha, op_type), ie_device, precision, ir_version, use_convert_model=True,- fx_kind="aten.add")+ fx_kind=f"aten.{op_type}")class TestAddTypes(PytorchLayerTest):diff --git a/tests/layer_tests/pytorch_tests/test_aliases.py b/tests/layer_tests/pytorch_tests/test_aliases.pyindex dc71eb33c77..8817ca8a632 100644--- a/tests/layer_tests/pytorch_tests/test_aliases.py+++ b/tests/layer_tests/pytorch_tests/test_aliases.py@@ -64,3 +64,251 @@ class TestAliases(PytorchLayerTest):"prim::Loop"],ie_device, precision, ir_version, freeze_model=False,fx_kind=["aten.clone.default", "aten.select.int", "aten.fill_.Tensor"])+++class TestAliasSchema(PytorchLayerTest):+ def _prepare_input(self):+ return (self.random.randn(1, 2, 3, 4).astype("float32"),)++ @pytest.mark.nightly+ @pytest.mark.precommit+ @pytest.mark.precommit_torch_export+ @pytest.mark.parametrize("operation", ["clone", "matmul", "conv2d", "relu", "sigmoid", "slice"])+ def test_tensor_in_list(self, operation, ie_device, precision, ir_version):+ class Model(torch.nn.Module):+ __constants__ = ["operation"]++ def __init__(self, operation):+ super().__init__()+ self.operation = operation++ def forward(self, tensor):+ if self.operation == "clone":+ result = tensor.clone()+ elif self.operation == "matmul":+ result = torch.matmul(tensor, tensor.transpose(-1, -2))+ elif self.operation == "conv2d":+ result = torch.conv2d(tensor, torch.ones(2, 2, 1, 1))+ elif self.operation == "relu":+ result = tensor.relu()+ elif self.operation == "sigmoid":+ result = tensor.sigmoid()+ else:+ result = tensor[:, :, :, :2]+ result.add_(1)+ # Container use puts even independent tensors in AliasDb's wildcard set.+ values = [tensor, result]+ return values[0], values[1]++ self._test(Model(operation), [f"aten::{operation}", "aten::add_", "prim::ListConstruct"],+ ie_device, precision, ir_version, freeze_model=False,+ fx_kind=[f"aten.{operation}", "aten.add_"])++[email protected]_torch_export+class TestViewMutations(PytorchLayerTest):+ def _prepare_input(self):+ return (self.random.randn(3, 4, 5).astype("float32"),)++ @pytest.mark.parametrize("view", ["view", "transpose", "permute", "unsqueeze", "squeeze", "detach", "nested"])+ @pytest.mark.parametrize("mutate_base", [False, True])+ def test_view_mutation(self, view, mutate_base, ie_device, precision, ir_version):+ class Model(torch.nn.Module):+ __constants__ = ["view", "mutate_base"]++ def __init__(self):+ super().__init__()+ self.view = view+ self.mutate_base = mutate_base++ def forward(self, data):+ base = data.clone()+ if self.view == "view":+ alias = base.view(3, 20)+ elif self.view == "transpose":+ alias = base.transpose(0, 2)+ elif self.view == "permute":+ alias = base.permute(2, 0, 1)+ elif self.view == "unsqueeze":+ alias = base.unsqueeze(0)+ elif self.view == "squeeze":+ alias = base.unsqueeze(0).squeeze(0)+ elif self.view == "detach":+ alias = base.detach()+ else:+ alias = base.transpose(0, 2)[1:4, :, 1:].unsqueeze(0)+ before = alias + 1+ if self.mutate_base:+ base.add_(2)+ else:+ alias.add_(2)+ return base, alias, before, alias * 3++ self._test(Model(), "aten::add_", ie_device, precision, ir_version, freeze_model=False)++ def test_sibling_views(self, ie_device, precision, ir_version):+ class Model(torch.nn.Module):+ def forward(self, data):+ base = data.clone()+ left = base[:, :3]+ right = base[:, 1:]+ before = right + 1+ left.add_(2)+ right.mul_(3)+ left[:, 1].fill_(7)+ return base, left, right, before, right + 1++ self._test(Model(), ["aten::add_", "aten::mul_", "aten::fill_"],+ ie_device, precision, ir_version, freeze_model=False)++ @pytest.mark.parametrize("same_values", [False, True])+ def test_tuple_member_mutation(self, same_values, ie_device, precision, ir_version):+ class Pair(torch.nn.Module):+ def forward(self, data):+ right = data.clone() if same_values else data + 1+ return data.clone(), right++ class Model(torch.nn.Module):+ def __init__(self):+ super().__init__()+ self.pair = Pair()++ def forward(self, data):+ left, right = self.pair(data)+ before = right + 1+ right.add_(2)+ left.mul_(3)+ return data, left, right, before++ self._test(Model(), ["prim::TupleConstruct", "aten::add_", "aten::mul_"],+ ie_device, precision, ir_version, trace_model=True, freeze_model=False,+ fx_kind=["aten.add_", "aten.mul_"])++ @pytest.mark.parametrize("unpack", [False, True])+ @pytest.mark.parametrize("mutate_base", [False, True])+ def test_split_view_mutation(self, unpack, mutate_base, ie_device, precision, ir_version):+ class Model(torch.nn.Module):+ __constants__ = ["unpack", "mutate_base"]++ def __init__(self):+ super().__init__()+ self.unpack = unpack+ self.mutate_base = mutate_base++ def forward(self, data):+ base = data.clone()+ parts = torch.split_with_sizes(base, [1, 3], dim=1)+ if self.unpack:+ left, right = parts+ else:+ left, right = parts[0], parts[1]+ before = right + 1+ if self.mutate_base:+ base.add_(2)+ else:+ right.add_(2)+ left.mul_(3)+ return base, left, right, before++ self._test(Model(), ["aten::split_with_sizes", "aten::mul_"],+ ie_device, precision, ir_version, freeze_model=False)++ def test_list_append_then_base_mutation(self, ie_device, precision, ir_version):+ class Model(torch.nn.Module):+ def forward(self, data):+ base = data.clone()+ parts = [base, base[:, :2]]+ parts.append(base[:, 2:])+ before = parts[2] + 1+ base.add_(2)+ return parts[0], parts[1], parts[2], before++ self._test(Model(), ["aten::append", "aten::add_"],+ ie_device, precision, ir_version, freeze_model=False, fx_kind="aten.add_")++ @pytest.mark.parametrize("mutate_base", [False, True])+ def test_loop_view_mutation(self, mutate_base, ie_device, precision, ir_version):+ class Model(torch.nn.Module):+ __constants__ = ["mutate_base"]++ def __init__(self):+ super().__init__()+ self.mutate_base = mutate_base++ def forward(self, data):+ base = data.clone()+ view = base.transpose(0, 2)+ before = view + 1+ for _ in range(2):+ if self.mutate_base:+ base.add_(2)+ else:+ view.add_(2)+ return base, view, before++ self._test(Model(), ["prim::Loop", "aten::add_"],+ ie_device, precision, ir_version, freeze_model=False, fx_kind="aten.add_")++ @pytest.mark.parametrize("change_base", [False, True])+ @pytest.mark.parametrize("metadata_op", ["unsqueeze", "squeeze", "transpose"])+ def test_metadata_mutation(self, change_base, metadata_op, ie_device, precision, ir_version):+ class Model(torch.nn.Module):+ __constants__ = ["change_base", "metadata_op"]++ def __init__(self):+ super().__init__()+ self.change_base = change_base+ self.metadata_op = metadata_op++ def forward(self, data):+ base = data.clone().unsqueeze(0)+ view = base[:, :, 1:]+ before = view + 1+ target = base if self.change_base else view+ if self.metadata_op == "unsqueeze":+ target.unsqueeze_(0)+ elif self.metadata_op == "squeeze":+ target.squeeze_(0)+ else:+ target.transpose_(1, 3)+ target.add_(2)+ return base, view, before++ self._test(Model(), [f"aten::{metadata_op}_", "aten::add_"],+ ie_device, precision, ir_version, freeze_model=False)++ @pytest.mark.parametrize("view", ["real", "imag", "view_as_real", "view_as_complex"])+ @pytest.mark.parametrize("mutate_base", [False, True])+ def test_complex_view_mutation(self, view, mutate_base, ie_device, precision, ir_version):+ class Model(torch.nn.Module):+ __constants__ = ["view", "mutate_base"]++ def __init__(self):+ super().__init__()+ self.view = view+ self.mutate_base = mutate_base++ def forward(self, data):+ if self.view == "view_as_complex":+ base = torch.stack((data, data * 2), dim=-1)+ alias = torch.view_as_complex(base)+ else:+ base = torch.complex(data, data * 2)+ if self.view == "real":+ alias = base.real+ elif self.view == "imag":+ alias = base.imag+ else:+ alias = torch.view_as_real(base)+ before = alias + 1+ if self.mutate_base:+ base.add_(2)+ else:+ alias.add_(2)+ if self.view == "view_as_complex":+ return base, torch.view_as_real(alias), torch.view_as_real(before)+ return torch.view_as_real(base), alias, before++ self._test(Model(), "aten::add_", ie_device, precision, ir_version, freeze_model=False)diff --git a/tests/layer_tests/pytorch_tests/test_all.py b/tests/layer_tests/pytorch_tests/test_all.pyindex 2878690e7e7..3f753e8a607 100644--- a/tests/layer_tests/pytorch_tests/test_all.py+++ b/tests/layer_tests/pytorch_tests/test_all.py@@ -7,7 +7,7 @@ import numpy as npimport pytestimport torch-from pytorch_layer_test_class import PytorchLayerTest, skip_if_export+from pytorch_layer_test_class import PytorchLayerTestclass aten_all_noparam(torch.nn.Module):def __init__(self) -> None:@@ -79,7 +79,7 @@ class TestAll(PytorchLayerTest):([7, 7], np.uint8),([4, 4], bool)])- @pytest.mark.parametrize("out", [skip_if_export(True), False])+ @pytest.mark.parametrize("out", [True, False])@pytest.mark.nightly@pytest.mark.precommit@pytest.mark.precommit_torch_export@@ -108,7 +108,7 @@ class TestAll(PytorchLayerTest):False,None])- @pytest.mark.parametrize("out", [skip_if_export(True), False])+ @pytest.mark.parametrize("out", [True, False])@pytest.mark.nightly@pytest.mark.precommit@pytest.mark.precommit_torch_exportdiff --git a/tests/layer_tests/pytorch_tests/test_aminmax.py b/tests/layer_tests/pytorch_tests/test_aminmax.pyindex 48723b94ae1..128d2c2a190 100644--- a/tests/layer_tests/pytorch_tests/test_aminmax.py+++ b/tests/layer_tests/pytorch_tests/test_aminmax.py@@ -46,6 +46,7 @@ class TestAminMax(PytorchLayerTest):(0, False), # Test with dim provided and keepdim=False(0, True), # Test with dim provided and keepdim=True(None, True)]) # Test with keepdim=True and dim not provided+ @pytest.mark.precommit_torch_exportdef test_aminmax(self, dtype, inputs, ie_device,precision, ir_version, dim, keepdim):self._test(diff --git a/tests/layer_tests/pytorch_tests/test_any.py b/tests/layer_tests/pytorch_tests/test_any.pyindex 0d3f3e3f934..cb95c8948d6 100644--- a/tests/layer_tests/pytorch_tests/test_any.py+++ b/tests/layer_tests/pytorch_tests/test_any.py@@ -7,7 +7,7 @@ import numpy as npimport pytestimport torch-from pytorch_layer_test_class import PytorchLayerTest, skip_if_export+from pytorch_layer_test_class import PytorchLayerTestclass aten_any_noparam(torch.nn.Module):def __init__(self) -> None:@@ -79,7 +79,7 @@ class TestAny(PytorchLayerTest):([7, 7], np.uint8),([4, 4], bool)])- @pytest.mark.parametrize("out", [skip_if_export(True), False])+ @pytest.mark.parametrize("out", [True, False])@pytest.mark.nightly@pytest.mark.precommit@pytest.mark.precommit_torch_export@@ -108,7 +108,7 @@ class TestAny(PytorchLayerTest):False,None])- @pytest.mark.parametrize("out", [skip_if_export(True), False])+ @pytest.mark.parametrize("out", [True, False])@pytest.mark.nightly@pytest.mark.precommit@pytest.mark.precommit_torch_exportdiff --git a/tests/layer_tests/pytorch_tests/test_bitwise_ops.py b/tests/layer_tests/pytorch_tests/test_bitwise_ops.pyindex f0773a7f36e..f9ea314b745 100644--- a/tests/layer_tests/pytorch_tests/test_bitwise_ops.py+++ b/tests/layer_tests/pytorch_tests/test_bitwise_ops.py@@ -6,7 +6,7 @@ import pytestimport torchfrom packaging.version import parse as parse_version-from pytorch_layer_test_class import PytorchLayerTest, skip_if_export+from pytorch_layer_test_class import PytorchLayerTestclass TestBitwiseOp(PytorchLayerTest):@@ -68,7 +68,7 @@ class TestBitwiseOp(PytorchLayerTest):([], [2, 3]),],)- @pytest.mark.parametrize("out", [False, skip_if_export(True)])+ @pytest.mark.parametrize("out", [False, True])def test_bitwise_mixed_dtypes(self, op_type, out, lhs_dtype, rhs_dtype, lhs_shape, rhs_shape, ie_device, precision, ir_version):diff --git a/tests/layer_tests/pytorch_tests/test_celu.py b/tests/layer_tests/pytorch_tests/test_celu.pyindex c98d6c5b83b..60ef68745c4 100644--- a/tests/layer_tests/pytorch_tests/test_celu.py+++ b/tests/layer_tests/pytorch_tests/test_celu.py@@ -5,7 +5,7 @@ import pytestimport torchimport torch.nn.functional as F-from pytorch_layer_test_class import PytorchLayerTest, skip_if_export+from pytorch_layer_test_class import PytorchLayerTestclass aten_celu(torch.nn.Module):@@ -35,7 +35,7 @@ class TestCelu(PytorchLayerTest):@pytest.mark.precommit_torch_export@pytest.mark.parametrize("alpha", [None, 0.5, 2.])@pytest.mark.parametrize("dtype", [torch.float16, torch.float32, torch.float64])- @pytest.mark.parametrize("inplace", [skip_if_export(True), False])+ @pytest.mark.parametrize("inplace", [True, False])def test_celu(self, alpha, dtype, inplace, ie_device, precision, ir_version):kwargs = {}if dtype == torch.float16:diff --git a/tests/layer_tests/pytorch_tests/test_clamp.py b/tests/layer_tests/pytorch_tests/test_clamp.pyindex fea492d038a..48c5dfd1317 100644--- a/tests/layer_tests/pytorch_tests/test_clamp.py+++ b/tests/layer_tests/pytorch_tests/test_clamp.py@@ -42,14 +42,14 @@ class TestClamp(PytorchLayerTest):@pytest.mark.parametrize("minimum,maximum",[(0., 1.), (-0.5, 1.5), (None, 10.), (None, -10.), (10., None), (-10., None), (100, 200), (1.0, 0.0)])@pytest.mark.parametrize("as_tensors", [skip_if_export(True), False])- @pytest.mark.parametrize("op_type", ["clamp", skip_if_export("clamp_")])+ @pytest.mark.parametrize("op_type", ["clamp", "clamp_"])@pytest.mark.nightly@pytest.mark.precommit@pytest.mark.precommit_torch_export@pytest.mark.precommit_fx_backenddef test_clamp(self, minimum, maximum, as_tensors, op_type, ie_device, precision, ir_version):self._test(*self.create_model(minimum, maximum, as_tensors,- op_type), ie_device, precision, ir_version, fx_kind="aten.clamp")+ op_type), ie_device, precision, ir_version, fx_kind=f"aten.{op_type}")class TestClampMin(PytorchLayerTest):@@ -113,11 +113,11 @@ class TestClampMax(PytorchLayerTest):@pytest.mark.parametrize("maximum", [0., 1., -1., 0.5, 2])@pytest.mark.parametrize("as_tensor", [True, False])- @pytest.mark.parametrize("inplace", [skip_if_export(True), False])+ @pytest.mark.parametrize("inplace", [True, False])@pytest.mark.nightly@pytest.mark.precommit@pytest.mark.precommit_torch_export@pytest.mark.precommit_fx_backenddef test_clamp_max(self, maximum, as_tensor, inplace, ie_device, precision, ir_version):self._test(*self.create_model(maximum, as_tensor, inplace), ie_device,- precision, ir_version, use_convert_model=True, trace_model=True, fx_kind="aten.clamp_max")+ precision, ir_version, use_convert_model=True, trace_model=True, fx_kind="aten.clamp_max_" if inplace else "aten.clamp_max")diff --git a/tests/layer_tests/pytorch_tests/test_copy.py b/tests/layer_tests/pytorch_tests/test_copy.pyindex 1d666ac5c91..9b2c4d30503 100644--- a/tests/layer_tests/pytorch_tests/test_copy.py+++ b/tests/layer_tests/pytorch_tests/test_copy.py@@ -3,7 +3,7 @@import pytest-from pytorch_layer_test_class import PytorchLayerTest, skip_if_export+from pytorch_layer_test_class import PytorchLayerTestclass TestCopy(PytorchLayerTest):@@ -34,6 +34,35 @@ class TestCopy(PytorchLayerTest):self._test(*self.create_model(value), ie_device, precision, ir_version)+ not (PytorchLayerTest.use_torch_export() or PytorchLayerTest.use_torch_compile_backend()),+ reason="Tests the functional ATen copy used by FX graphs",+)+class TestFunctionalCopy(PytorchLayerTest):+ def _prepare_input(self, source_shape):+ return (self.random.randn(2, 3).astype("float32"),+ self.random.randint(-10, 10, size=source_shape).astype("int32"))++ @pytest.mark.precommit_torch_export+ @pytest.mark.precommit_fx_backend+ @pytest.mark.nightly+ @pytest.mark.parametrize("non_blocking", [None, False, True])+ @pytest.mark.parametrize("source_shape", [(2, 3), (3,)])+ def test_copy(self, non_blocking, source_shape, ie_device, precision, ir_version):+ import torch++ class Model(torch.nn.Module):+ def forward(self, destination, source):+ if non_blocking is None:+ copied = torch.ops.aten.copy.default(destination, source)+ else:+ copied = torch.ops.aten.copy.default(destination, source, non_blocking)+ return copied, destination, source++ self._test(Model(), "aten::copy", ie_device, precision, ir_version,+ kwargs_to_prepare_input={"source_shape": source_shape})++class TestAliasCopy(PytorchLayerTest):def _prepare_input(self, out):import numpy as np@@ -63,6 +92,6 @@ class TestAliasCopy(PytorchLayerTest):@pytest.mark.precommit@pytest.mark.precommit_fx_backend@pytest.mark.precommit_torch_export- @pytest.mark.parametrize("out", [skip_if_export(True), False])+ @pytest.mark.parametrize("out", [True, False])def test_copy_(self, out, ie_device, precision, ir_version):self._test(*self.create_model(out), ie_device, precision, ir_version, kwargs_to_prepare_input={"out": out})diff --git a/tests/layer_tests/pytorch_tests/test_cross.py b/tests/layer_tests/pytorch_tests/test_cross.pyindex 9b82a806561..c963b63543d 100644--- a/tests/layer_tests/pytorch_tests/test_cross.py+++ b/tests/layer_tests/pytorch_tests/test_cross.py@@ -53,6 +53,7 @@ class TestLinalgCross(PytorchLayerTest):@pytest.mark.nightly@pytest.mark.precommit+ @pytest.mark.precommit_torch_export@pytest.mark.parametrize("x_shape,y_shape,dim", [((4, 3), (4, 3), None),((1, 3), (4, 3), -1),@@ -113,6 +114,7 @@ class TestCross(PytorchLayerTest):@pytest.mark.nightly@pytest.mark.precommit+ @pytest.mark.precommit_torch_export@pytest.mark.parametrize("x_shape,y_shape,dim", [((1, 3), (4, 3), -1),((4, 3), (1, 3), 1),diff --git a/tests/layer_tests/pytorch_tests/test_dot.py b/tests/layer_tests/pytorch_tests/test_dot.pyindex f9317403675..ad8a62f373d 100644--- a/tests/layer_tests/pytorch_tests/test_dot.py+++ b/tests/layer_tests/pytorch_tests/test_dot.py@@ -3,7 +3,7 @@import pytest-from pytorch_layer_test_class import PytorchLayerTest, skip_if_export+from pytorch_layer_test_class import PytorchLayerTestclass TestDot(PytorchLayerTest):def _prepare_input(self, inputs, dtype, out=False):@@ -51,8 +51,8 @@ class TestDot(PytorchLayerTest):@pytest.mark.precommit_torch_export@pytest.mark.parametrize("mode, dtype", [("", "float32"), ("", "float64"), ("", "int32"), ("", "int64"), ("", "int8"),- skip_if_export("out", "float32"), skip_if_export("out", "float64"),- skip_if_export("out", "int32"), skip_if_export("out", "int64"), skip_if_export("out", "int8")])+ ("out", "float32"), ("out", "float64"),+ ("out", "int32"), ("out", "int64"), ("out", "int8")])@pytest.mark.parametrize("inputs", [([0, 1, 2, 3, 4], [5, 6, 7, 8, 9]), ([1, 2, 3], [4, 5, 6]), ([1, 1, 1], [1, 1, 1])])diff --git a/tests/layer_tests/pytorch_tests/test_einsum.py b/tests/layer_tests/pytorch_tests/test_einsum.pyindex 19f623dc4de..1e4f2649b27 100644--- a/tests/layer_tests/pytorch_tests/test_einsum.py+++ b/tests/layer_tests/pytorch_tests/test_einsum.py@@ -23,6 +23,7 @@ class TestEinsumBatchMatMul(PytorchLayerTest):@pytest.mark.nightly@pytest.mark.precommit+ @pytest.mark.precommit_torch_exportdef test_einsum_batch_matmul(self, ie_device, precision, ir_version):self._test(*self.create_model(), ie_device, precision, ir_version)@@ -44,6 +45,7 @@ class TestEinsumBatchDiagonal(PytorchLayerTest):@pytest.mark.nightly@pytest.mark.precommit+ @pytest.mark.precommit_torch_export@pytest.mark.xfail(reason='OpenVINO CPU plugin does not support einsum diagonal')def test_einsum_batch_diagonal(self, ie_device, precision, ir_version):self._test(*self.create_model(), ie_device, precision, ir_version, dynamic_shapes=False)@@ -66,6 +68,7 @@ class TestEinsumInnerProd(PytorchLayerTest):@pytest.mark.nightly@pytest.mark.precommit+ @pytest.mark.precommit_torch_exportdef test_einsum_inner_prod(self, ie_device, precision, ir_version):self._test(*self.create_model(), ie_device, precision, ir_version)@@ -87,5 +90,6 @@ class TestEinsumTranspose(PytorchLayerTest):@pytest.mark.nightly@pytest.mark.precommit+ @pytest.mark.precommit_torch_exportdef test_einsum_transpose(self, ie_device, precision, ir_version):self._test(*self.create_model(), ie_device, precision, ir_version)diff --git a/tests/layer_tests/pytorch_tests/test_elu.py b/tests/layer_tests/pytorch_tests/test_elu.pyindex 9429c93f202..f8d9e52bf39 100644--- a/tests/layer_tests/pytorch_tests/test_elu.py+++ b/tests/layer_tests/pytorch_tests/test_elu.py@@ -5,7 +5,7 @@ import pytestimport torchimport torch.nn.functional as F-from pytorch_layer_test_class import PytorchLayerTest, skip_if_export+from pytorch_layer_test_class import PytorchLayerTestclass aten_elu(torch.nn.Module):@@ -35,7 +35,7 @@ class TestElu(PytorchLayerTest):@pytest.mark.precommit_torch_export@pytest.mark.parametrize("alpha", [None, 0.5, 2.])@pytest.mark.parametrize("dtype", [torch.float16, torch.float32, torch.float64])- @pytest.mark.parametrize("inplace", [skip_if_export(True), False])+ @pytest.mark.parametrize("inplace", [True, False])def test_elu(self, alpha, dtype, inplace, ie_device, precision, ir_version):kwargs = {}if dtype == torch.float16:diff --git a/tests/layer_tests/pytorch_tests/test_empty.py b/tests/layer_tests/pytorch_tests/test_empty.pyindex a2ed4730dbe..74a8ba6aa96 100644--- a/tests/layer_tests/pytorch_tests/test_empty.py+++ b/tests/layer_tests/pytorch_tests/test_empty.py@@ -172,7 +172,7 @@ class TestNewEmpty(PytorchLayerTest):# We don't want to compare values, just shape and type,# so we call zeros_like on data. Multiplying by zero would# produce sporadic errors if nan would be in empty.- return torch.zeros_like(empty)+ return torch.zeros_like(empty), input_tensorclass aten_empty_with_dtype(torch.nn.Module):def __init__(self, shape, dtype):@@ -186,7 +186,7 @@ class TestNewEmpty(PytorchLayerTest):# We don't want to compare values, just shape and type,# so we call zeros_like on data. Multiplying by zero would# produce sporadic errors if nan would be in empty.- return torch.zeros_like(empty)+ return torch.zeros_like(empty), input_tensormodel = aten_empty(shape)@@ -200,6 +200,7 @@ class TestNewEmpty(PytorchLayerTest):@pytest.mark.parametrize("input_dtype", [np.uint8, np.int8, np.int32, np.int64, np.float32, np.float64])@pytest.mark.nightly@pytest.mark.precommit+ @pytest.mark.precommit_torch_exportdef test_new_empty(self, shape, input_dtype, ie_device, precision, ir_version):self._test(*self.create_model(shape), ie_device, precision, ir_version,kwargs_to_prepare_input={'input_dtype': input_dtype}, use_convert_model=True)@@ -208,6 +209,7 @@ class TestNewEmpty(PytorchLayerTest):@pytest.mark.parametrize("input_dtype", [bool, np.uint8, np.int8, np.int32, np.int64, np.float32, np.float64])@pytest.mark.parametrize("dtype", ["bool", "uint8", "int8", "int32", "int64", "float32", "float64"])@pytest.mark.nightly+ @pytest.mark.precommit_torch_exportdef test_new_empty_with_dtype(self, shape, dtype, input_dtype, ie_device, precision, ir_version):self._test(*self.create_model(shape, dtype=dtype, used_dtype=True), ie_device, precision, ir_version,kwargs_to_prepare_input={'input_dtype': input_dtype}, use_convert_model=True)diff --git a/tests/layer_tests/pytorch_tests/test_export_mutations.py b/tests/layer_tests/pytorch_tests/test_export_mutations.pynew file mode 100644index 00000000000..06dc23f9791--- /dev/null+++ b/tests/layer_tests/pytorch_tests/test_export_mutations.py@@ -0,0 +1,106 @@+# Copyright (C) 2018-2026 Intel Corporation+# SPDX-License-Identifier: Apache-2.0++from unittest.mock import patch++import pytest+import torch++from pytorch_layer_test_class import PytorchLayerTest++[email protected](not PytorchLayerTest.use_torch_export(), reason="Tests the exported ATen graph")[email protected]_torch_export+class TestExportMutations(PytorchLayerTest):+ """Mutation cases which only exist in the exported ATen graph.++ View mutations shared with TorchScript are covered by test_aliases.py::TestViewMutations,+ which the harness also runs in export mode.+ """++ @pytest.fixture(autouse=True)+ def forbid_decompositions(self):+ # Conversion must handle the exported ATen ops directly.+ with patch.object(torch.export.ExportedProgram, "run_decompositions",+ side_effect=AssertionError("Conversion must not run decompositions")):+ yield++ def _prepare_input(self):+ return (self.random.randn(3, 4, 5).astype("float32"),)++ @pytest.mark.parametrize("view", ["slice", "select", "copy"])+ @pytest.mark.parametrize("mutate_base", [False, True])+ def test_view_mutation(self, view, mutate_base, ie_device, precision, ir_version):+ class Model(torch.nn.Module):+ def forward(self, x):+ base = x.clone()+ if view == "slice":+ alias = base[:, 1:3, ::2]+ elif view == "select":+ alias = base[1]+ else:+ # A non-contiguous reshape allocates new storage.+ alias = base.transpose(0, 2).reshape(-1)+ before = alias + 1+ if mutate_base:+ base.add_(2)+ else:+ alias.add_(2)+ return base, alias, before, alias * 3++ self._test(Model(), "aten::add_", ie_device, precision, ir_version)++ def test_inplace_result_alias(self, ie_device, precision, ir_version):+ class Model(torch.nn.Module):+ def forward(self, x):+ result = x.add_(2)+ before = result * 2+ x.mul_(3)+ result.sub_(1)+ return x, result, before++ self._test(Model(), ["aten::add_", "aten::mul_", "aten::sub_"], ie_device, precision, ir_version)++ @pytest.mark.parametrize("view", ["split", "chunk", "unbind", "indices", "sections", "sizes"])+ @pytest.mark.parametrize("mutate_base", [False, True])+ def test_list_view_mutation(self, view, mutate_base, ie_device, precision, ir_version):+ class Model(torch.nn.Module):+ def forward(self, x):+ base = x.clone()+ if view == "split":+ parts = base.split(1, dim=1)+ elif view == "chunk":+ parts = base.chunk(2, dim=1)+ elif view == "unbind":+ parts = base.unbind(dim=1)+ elif view == "indices":+ parts = base.tensor_split([1, 3], dim=1)+ elif view == "sections":+ parts = base.tensor_split(3, dim=1)+ else:+ parts = base.split([1, 3], dim=1)+ before = parts[1] + 1+ if mutate_base:+ base.add_(2)+ else:+ parts[1].add_(2)+ parts[0].mul_(3)+ return base, parts, before++ self._test(Model(), ["aten::add_", "aten::mul_"], ie_device, precision, ir_version,+ dynamic_shapes_for_export={"x": {0: torch.export.Dim("batch", min=2)}})++ def test_out_view_mutation(self, ie_device, precision, ir_version):+ class Model(torch.nn.Module):+ def forward(self, x):+ base = torch.zeros_like(x)+ view = base[:, 1:3]+ before = base + 3+ result = torch.add(x[:, 1:3], 1, out=view)+ base.add_(2)+ result.mul_(2)+ return base, view, result, before++ self._test(Model(), ["aten::add", "aten::add_", "aten::mul_"], ie_device, precision, ir_version,+ fx_kind=["aten.add.out", "aten.add_.Tensor", "aten.mul_.Tensor"])diff --git a/tests/layer_tests/pytorch_tests/test_flip.py b/tests/layer_tests/pytorch_tests/test_flip.pyindex 74359e0728a..c2c951f9967 100644--- a/tests/layer_tests/pytorch_tests/test_flip.py+++ b/tests/layer_tests/pytorch_tests/test_flip.py@@ -3,7 +3,7 @@import pytest-from pytorch_layer_test_class import PytorchLayerTest, skip_if_export+from pytorch_layer_test_class import PytorchLayerTestclass TestFlip(PytorchLayerTest):@@ -23,12 +23,13 @@ class TestFlip(PytorchLayerTest):self.dim = dimif out:self.forward = self.forward_out+ self.out_op = PytorchLayerTest.out_variant(torch.flip, torch.ops.aten.flip.out)def forward(self, x):return torch.flip(x, self.dim)def forward_out(self, x, y):- return torch.flip(x, self.dim, out=y), y+ return self.out_op(x, self.dim, out=y), yreturn aten_flip(axis, out), "aten::flip"@@ -37,7 +38,7 @@ class TestFlip(PytorchLayerTest):@pytest.mark.precommit@pytest.mark.precommit_torch_export@pytest.mark.parametrize("axis", [[0], [1], [-1], [1, 2], [2, 3], [1, 2, 3]])- @pytest.mark.parametrize("out", [skip_if_export(True), False])+ @pytest.mark.parametrize("out", [True, False])@pytest.mark.parametrize("dtype", ["float32", "float64", "int32", "int64", "uint8"])def test_flip(self, axis, out, dtype, ie_device, precision, ir_version):self._test(*self.create_model(axis, out), ie_device, precision, ir_version, kwargs_to_prepare_input={"out": out, "dtype": dtype})diff --git a/tests/layer_tests/pytorch_tests/test_full.py b/tests/layer_tests/pytorch_tests/test_full.pyindex 04dc5d1198e..dcc61974c10 100644--- a/tests/layer_tests/pytorch_tests/test_full.py+++ b/tests/layer_tests/pytorch_tests/test_full.py@@ -6,14 +6,14 @@ import platformimport numpy as npimport pytest-from pytorch_layer_test_class import PytorchLayerTest, skip_if_export+from pytorch_layer_test_class import PytorchLayerTestclass TestFull(PytorchLayerTest):def _prepare_input(self, value):return (np.array(value, dtype=np.float32),)- def create_model(self, shape, dtype=None, use_dtype=False, use_out=False, with_names=False):+ def create_model(self, shape, dtype=None, use_dtype=False, use_out=False):import torchdtype_map = {"float32": torch.float32,@@ -42,15 +42,6 @@ class TestFull(PytorchLayerTest):def forward(self, x: float):return torch.full(self.shape, x, dtype=self.dtype)- class aten_full_dtype_with_names(torch.nn.Module):- def __init__(self, shape, dtype):- super().__init__()- self.shape = shape- self.dtype = dtype-- def forward(self, x: float):- return torch.full(self.shape, x, dtype=self.dtype, names=None)-class aten_full_out(torch.nn.Module):def __init__(self, shape, dtype):super().__init__()@@ -60,22 +51,13 @@ class TestFull(PytorchLayerTest):def forward(self, x: float):return torch.full(self.shape, x, out=torch.zeros(self.shape, dtype=self.dtype))- class aten_full_out_with_names(torch.nn.Module):- def __init__(self, shape, dtype):- super().__init__()- self.shape = shape- self.dtype = dtype-- def forward(self, x: float):- return torch.full(self.shape, x, out=torch.zeros(self.shape, dtype=self.dtype), names=None)-model = aten_full(shape)if use_dtype or use_out:dtype = dtype_map.get(dtype, dtype)if not use_out:- model = aten_full_dtype(shape, dtype) if not with_names else aten_full_dtype_with_names(shape, dtype)+ model = aten_full_dtype(shape, dtype)else:- model = aten_full_out(shape, dtype) if not with_names else aten_full_out_with_names(shape, dtype)+ model = aten_full_out(shape, dtype)return model, "aten::full"@@ -91,20 +73,18 @@ class TestFull(PytorchLayerTest):@pytest.mark.parametrize("shape", [[1], [1, 2], [1, 2, 3], [1, 2, 3, 4], [2, 3, 4, 5, 6]])@pytest.mark.parametrize("value", [0, 1, -1, 0.5])@pytest.mark.parametrize("dtype", ["int8", "int32", "int64", "float32", "float64"])- @pytest.mark.parametrize("with_names", [skip_if_export(True), False])@pytest.mark.nightly@pytest.mark.precommit_fx_backend- def test_full_dtype(self, shape, value, dtype, with_names, ie_device, precision, ir_version):- self._test(*self.create_model(shape, dtype=dtype, use_dtype=True, with_names=with_names), ie_device, precision,+ def test_full_dtype(self, shape, value, dtype, ie_device, precision, ir_version):+ self._test(*self.create_model(shape, dtype=dtype, use_dtype=True), ie_device, precision,ir_version, kwargs_to_prepare_input={'value': value})@pytest.mark.parametrize("shape", [[1], [1, 2], [1, 2, 3], [1, 2, 3, 4], [2, 3, 4, 5, 6]])@pytest.mark.parametrize("value", [0, 1, -1, 0.5])@pytest.mark.parametrize("dtype", ["int8", "int32", "int64", "float32", "float64"])- @pytest.mark.parametrize("with_names", [skip_if_export(True), False])@pytest.mark.nightly- def test_full_out(self, shape, value, dtype, with_names, ie_device, precision, ir_version):- self._test(*self.create_model(shape, dtype=dtype, use_out=True, with_names=with_names), ie_device, precision,+ def test_full_out(self, shape, value, dtype, ie_device, precision, ir_version):+ self._test(*self.create_model(shape, dtype=dtype, use_out=True), ie_device, precision,ir_version, kwargs_to_prepare_input={'value': value})class TestFill(PytorchLayerTest):@@ -137,6 +117,16 @@ class TestFill(PytorchLayerTest):model = aten_fill(mode)+ if self.use_torch_export():+ # Tensor.fill is only exposed through the ATen API in eager PyTorch.+ class ExportFill(torch.nn.Module):+ def forward(self, input_t, x, out=None):+ if mode == "inplace":+ return input_t.fill_(x)+ if mode == "out":+ return torch.ops.aten.fill.Tensor_out(input_t, x, out=out), out+ return torch.ops.aten.fill.Tensor(input_t, x)+ model = ExportFill()return model, "aten::fill_" if mode == "inplace" else "aten::fill"@@ -149,6 +139,7 @@ class TestFill(PytorchLayerTest):@pytest.mark.precommit@pytest.mark.xfail(condition=platform.system() == 'Darwin' and platform.machine() == 'arm64',reason='Ticket - 122715')+ @pytest.mark.precommit_torch_exportdef test_fill(self, shape, value, input_dtype, value_dtype, mode, ie_device, precision, ir_version):self._test(*self.create_model(mode), ie_device, precision, ir_version,kwargs_to_prepare_input={@@ -189,6 +180,7 @@ class TestFillDiagonal(PytorchLayerTest):@pytest.mark.precommit@pytest.mark.xfail(condition=platform.system() == 'Darwin' and platform.machine() == 'arm64',reason='Ticket - 122715')+ @pytest.mark.precommit_torch_exportdef test_fill_diagonal(self, shape, value, input_dtype, value_dtype, wrap, ie_device, precision, ir_version):if ie_device == "GPU":pytest.xfail(reason="fill_diagonal is not supported on GPU")@@ -364,7 +356,7 @@ class TestZerosAndOnes(PytorchLayerTest):def _prepare_input(self, shape):return (self.random.randn(*shape),)- def create_model(self, op_type, dtype=None, with_dtype=False, with_out=False, with_names=False):+ def create_model(self, op_type, dtype=None, with_dtype=False, with_out=False):import torchops = {"aten::zeros": torch.zeros,@@ -409,11 +401,6 @@ class TestZerosAndOnes(PytorchLayerTest):shape = x.shapereturn self.op(shape, dtype=self.dtype), x- class aten_op_dtype_with_names(aten_op_dtype):- def forward(self, x):- shape = x.shape- return self.op(shape, dtype=self.dtype, names=None), x-class aten_op_like_dtype(torch.nn.Module):def __init__(self, op, dtype):super().__init__()@@ -431,17 +418,7 @@ class TestZerosAndOnes(PytorchLayerTest):def forward(self, x):shape = x.shape- return self.op(shape, out=torch.zeros_like(x, dtype=self.dtype))-- class aten_op_out_with_names(torch.nn.Module):- def __init__(self, op, dtype):- super().__init__()- self.op = op- self.dtype = dtype-- def forward(self, x):- shape = x.shape- return self.op(shape, out=torch.zeros_like(x, dtype=self.dtype), names=None)+ return self.op(shape, out=torch.zeros_like(x, dtype=self.dtype)), xclass aten_op_like_out(torch.nn.Module):def __init__(self, op, dtype):@@ -459,9 +436,9 @@ class TestZerosAndOnes(PytorchLayerTest):if with_dtype or with_out:dtype = dtype_map[dtype]if with_dtype:- model_cls = aten_op_dtype(op, dtype) if not with_names else aten_op_dtype_with_names(op, dtype)+ model_cls = aten_op_dtype(op, dtype)if with_out:- model_cls = aten_op_out(op, dtype) if not with_names else aten_op_out_with_names(op, dtype)+ model_cls = aten_op_out(op, dtype)else:model_cls = aten_op_like(op)if with_dtype or with_out:@@ -485,22 +462,21 @@ class TestZerosAndOnes(PytorchLayerTest):@pytest.mark.parametrize("shape", [(1, 1), (1, 2), (1, 2, 3), (1, 2, 3, 4), (2, 3, 4, 5, 6)])@pytest.mark.parametrize("op_type", ["aten::zeros", "aten::ones"])@pytest.mark.parametrize("dtype", ["int8", "int32", "int64", "float32", "float64"])- @pytest.mark.parametrize("with_names", [skip_if_export(True), False])@pytest.mark.nightly@pytest.mark.precommit_fx_backend@pytest.mark.precommit_torch_export- def test_zeros_ones_with_dtype(self, op_type, shape, dtype, with_names, ie_device, precision, ir_version):- self._test(*self.create_model(op_type, dtype=dtype, with_dtype=True, with_names=with_names), ie_device,+ def test_zeros_ones_with_dtype(self, op_type, shape, dtype, ie_device, precision, ir_version):+ self._test(*self.create_model(op_type, dtype=dtype, with_dtype=True), ie_device,precision,ir_version, kwargs_to_prepare_input={'shape': shape})@pytest.mark.parametrize("shape", [(1, 1), (1, 2), (1, 2, 3), (1, 2, 3, 4), (2, 3, 4, 5, 6)])@pytest.mark.parametrize("op_type", ["aten::zeros", "aten::ones"])@pytest.mark.parametrize("dtype", ["int8", "int32", "int64", "float32", "float64"])- @pytest.mark.parametrize("with_names", [skip_if_export(True), False])@pytest.mark.nightly- def test_zeros_ones_with_out(self, op_type, shape, dtype, with_names, ie_device, precision, ir_version):- self._test(*self.create_model(op_type, dtype=dtype, with_out=True, with_names=with_names), ie_device, precision,+ @pytest.mark.precommit_torch_export+ def test_zeros_ones_with_out(self, op_type, shape, dtype, ie_device, precision, ir_version):+ self._test(*self.create_model(op_type, dtype=dtype, with_out=True), ie_device, precision,ir_version, kwargs_to_prepare_input={'shape': shape})@pytest.mark.parametrize("shape", [(1, 1), (1, 2), (1, 2, 3), (1, 2, 3, 4), (2, 3, 4, 5, 6)])diff --git a/tests/layer_tests/pytorch_tests/test_gather.py b/tests/layer_tests/pytorch_tests/test_gather.pyindex 8057236466b..c253398e5b8 100644--- a/tests/layer_tests/pytorch_tests/test_gather.py+++ b/tests/layer_tests/pytorch_tests/test_gather.py@@ -3,7 +3,7 @@import pytest-from pytorch_layer_test_class import PytorchLayerTest, skip_if_export+from pytorch_layer_test_class import PytorchLayerTestclass TestGather(PytorchLayerTest):@@ -42,7 +42,7 @@ class TestGather(PytorchLayerTest):@pytest.mark.parametrize("m", [2, 10, 100])@pytest.mark.parametrize("n", [2, 10, 100])@pytest.mark.parametrize("axis", [0, 1])- @pytest.mark.parametrize("out", [skip_if_export(True), False])+ @pytest.mark.parametrize("out", [True, False])def test_gather(self, m, n, axis, out, ie_device, precision, ir_version):self._test(*self.create_model(axis, out), ie_device, precision, ir_version, kwargs_to_prepare_input={"m": m, "n": n, "max_val": m if axis == 0 else n, "out": outdiff --git a/tests/layer_tests/pytorch_tests/test_grouped_mm.py b/tests/layer_tests/pytorch_tests/test_grouped_mm.pyindex d9974da045d..8367bf50426 100644--- a/tests/layer_tests/pytorch_tests/test_grouped_mm.py+++ b/tests/layer_tests/pytorch_tests/test_grouped_mm.py@@ -55,7 +55,7 @@ class TestGroupedMMConstWeights(PytorchLayerTest):pytest.skip("GPU gather_matmul kernel does not support FP32")self._test(*self.create_model(b_shape=b_shape, bf16=self.use_torch_export()), ie_device, precision, ir_version,kwargs_to_prepare_input={"a_shape": a_shape},- trace_model=True)+ trace_model=True, custom_eps=2e-2 if self.use_torch_export() else 1e-4)class TestGroupedMMOffsetsConstWeights(PytorchLayerTest):@@ -103,7 +103,7 @@ class TestGroupedMMOffsetsConstWeights(PytorchLayerTest):self._test(*self.create_model(k=k, n=n, num_groups=len(offsets), bf16=self.use_torch_export()),ie_device, precision, ir_version,kwargs_to_prepare_input={"total_tokens": total_tokens, "offsets": offsets, "k": k},- trace_model=True)+ trace_model=True, custom_eps=2e-2 if self.use_torch_export() else 1e-4)# ---------------------------------------------------------------------------@@ -153,7 +153,7 @@ class TestFunctionalGroupedMMConstWeights(PytorchLayerTest):pytest.skip("GPU gather_matmul kernel does not support FP32")self._test(*self.create_model(b_shape=b_shape, bf16=self.use_torch_export()), ie_device, precision, ir_version,kwargs_to_prepare_input={"a_shape": a_shape},- trace_model=True)+ trace_model=True, custom_eps=2e-2 if self.use_torch_export() else 1e-4)class TestFunctionalGroupedMMOffsetsConstWeights(PytorchLayerTest):@@ -201,4 +201,4 @@ class TestFunctionalGroupedMMOffsetsConstWeights(PytorchLayerTest):self._test(*self.create_model(k=k, n=n, num_groups=len(offsets), bf16=self.use_torch_export()),ie_device, precision, ir_version,kwargs_to_prepare_input={"total_tokens": total_tokens, "offsets": offsets, "k": k},- trace_model=True)+ trace_model=True, custom_eps=2e-2 if self.use_torch_export() else 1e-4)diff --git a/tests/layer_tests/pytorch_tests/test_hadsigmoid.py b/tests/layer_tests/pytorch_tests/test_hadsigmoid.pyindex 53317e8e409..b2011938773 100644--- a/tests/layer_tests/pytorch_tests/test_hadsigmoid.py+++ b/tests/layer_tests/pytorch_tests/test_hadsigmoid.py@@ -3,7 +3,7 @@import pytest-from pytorch_layer_test_class import PytorchLayerTest, skip_if_export+from pytorch_layer_test_class import PytorchLayerTestclass TestHardSigmoid(PytorchLayerTest):@@ -30,6 +30,6 @@ class TestHardSigmoid(PytorchLayerTest):@pytest.mark.precommit_torch_export@pytest.mark.parametrize("shape", [[1, 10], [1, 2, 3], [1, 2, 3, 4], [1, 2, 3, 4, 5]])@pytest.mark.parametrize("dtype", ["float32", "float64"])- @pytest.mark.parametrize("inplace", [skip_if_export(True), False])+ @pytest.mark.parametrize("inplace", [True, False])def test_hardsigmoid(self, shape, dtype, inplace, ie_device, precision, ir_version):self._test(*self.create_model(inplace), ie_device, precision, ir_version, kwargs_to_prepare_input={"shape": shape, "dtype": dtype})diff --git a/tests/layer_tests/pytorch_tests/test_hstack.py b/tests/layer_tests/pytorch_tests/test_hstack.pyindex 9a55a2f5cde..fb4a9b94f2e 100644--- a/tests/layer_tests/pytorch_tests/test_hstack.py+++ b/tests/layer_tests/pytorch_tests/test_hstack.py@@ -6,7 +6,7 @@ import torchimport numpy as npimport numpy as np-from pytorch_layer_test_class import PytorchLayerTest, skip_if_export+from pytorch_layer_test_class import PytorchLayerTestclass aten_hstack(torch.nn.Module):def forward(self, x):@@ -31,7 +31,7 @@ class TestHstack(PytorchLayerTest):@pytest.mark.nightly@pytest.mark.precommit@pytest.mark.precommit_torch_export- @pytest.mark.parametrize("out", [False, skip_if_export(True)])+ @pytest.mark.parametrize("out", [False, True])def test_hstack(self, out, ie_device, precision, ir_version):model = aten_hstack() if not out else aten_hstack_out()self._test(model, "aten::hstack", ie_device,diff --git a/tests/layer_tests/pytorch_tests/test_index_add.py b/tests/layer_tests/pytorch_tests/test_index_add.pyindex 7def7a0f3fa..c7458051bcf 100644--- a/tests/layer_tests/pytorch_tests/test_index_add.py+++ b/tests/layer_tests/pytorch_tests/test_index_add.py@@ -51,9 +51,14 @@ class TestIndexAdd(PytorchLayerTest):],)@pytest.mark.parametrize("src", [torch.tensor([[1, 2, 3], [4, 5, 6], [7, 8, 9]])])- @pytest.mark.parametrize("dtype", ["int32", "int64", "float32", "float64"])+ @pytest.mark.precommit_torch_export+ @pytest.mark.parametrize("dtype,alpha", [+ (dtype, alpha)+ for dtype in ["int32", "int64", "float32", "float64"]+ for alpha in [1, -1, 0.5, 0.25]+ if dtype.startswith("float") or isinstance(alpha, int)+ ])@pytest.mark.parametrize("mode", ["inplace", "out", "default"])- @pytest.mark.parametrize("alpha", [1, -1, 0.5, 0.25])def test_scatter_reduce(self, dim, index, src, dtype, mode, alpha, ie_device, precision, ir_version):if isinstance(src, torch.Tensor):src = src.to(getattr(torch, dtype))diff --git a/tests/layer_tests/pytorch_tests/test_index_copy_.py b/tests/layer_tests/pytorch_tests/test_index_copy_.pyindex dcd7fb9482d..082b664cdca 100644--- a/tests/layer_tests/pytorch_tests/test_index_copy_.py+++ b/tests/layer_tests/pytorch_tests/test_index_copy_.py@@ -5,7 +5,7 @@import pytestimport torch-from pytorch_layer_test_class import PytorchLayerTest, skip_if_export+from pytorch_layer_test_class import PytorchLayerTestclass TestIndexCopy(PytorchLayerTest):@@ -80,7 +80,7 @@ class TestIndexCopy(PytorchLayerTest):@pytest.mark.precommit@pytest.mark.precommit_torch_export@pytest.mark.precommit_fx_backend- @pytest.mark.parametrize('inplace', [skip_if_export(True), False])+ @pytest.mark.parametrize('inplace', [True, False])def test_index_copy_single_index(self, inplace, ie_device, precision, ir_version, input_data):self.input_tensor = self.random.randn(*input_data["input_shape"])self.values = self.random.randn(*input_data["values_shape"])diff --git a/tests/layer_tests/pytorch_tests/test_index_select.py b/tests/layer_tests/pytorch_tests/test_index_select.pyindex 3d99b6784f3..7fac16f2405 100644--- a/tests/layer_tests/pytorch_tests/test_index_select.py+++ b/tests/layer_tests/pytorch_tests/test_index_select.py@@ -3,7 +3,7 @@import pytest-from pytorch_layer_test_class import PytorchLayerTest, skip_if_export+from pytorch_layer_test_class import PytorchLayerTestclass TestIndexSelect(PytorchLayerTest):@@ -37,7 +37,7 @@ class TestIndexSelect(PytorchLayerTest):@pytest.mark.parametrize("dim", [0, 1, 2, 3, -1, -2, -3])@pytest.mark.parametrize("indices", [[0, 1], [0], [1, 0]])- @pytest.mark.parametrize("out", [False, skip_if_export(True)])+ @pytest.mark.parametrize("out", [False, True])@pytest.mark.nightly@pytest.mark.precommit@pytest.mark.precommit_fx_backenddiff --git a/tests/layer_tests/pytorch_tests/test_leaky_relu.py b/tests/layer_tests/pytorch_tests/test_leaky_relu.pyindex d508a6e9ba3..462168aba62 100644--- a/tests/layer_tests/pytorch_tests/test_leaky_relu.py+++ b/tests/layer_tests/pytorch_tests/test_leaky_relu.py@@ -3,7 +3,7 @@import pytest-from pytorch_layer_test_class import PytorchLayerTest, skip_check+from pytorch_layer_test_class import PytorchLayerTest, skip_if_fxclass TestLeakyRelu(PytorchLayerTest):@@ -27,7 +27,7 @@ class TestLeakyRelu(PytorchLayerTest):return aten_leaky_relu(alpha, inplace), "aten::leaky_relu" if not inplace else "aten::leaky_relu_"@pytest.mark.parametrize("alpha", [0.01, 1.01, -0.01])- @pytest.mark.parametrize("inplace", [skip_check(True), False])+ @pytest.mark.parametrize("inplace", [skip_if_fx(True), False])@pytest.mark.nightly@pytest.mark.precommit@pytest.mark.precommit_torch_exportdiff --git a/tests/layer_tests/pytorch_tests/test_logaddexp.py b/tests/layer_tests/pytorch_tests/test_logaddexp.pyindex 3a7e3c843d5..2c005ae6bfe 100644--- a/tests/layer_tests/pytorch_tests/test_logaddexp.py+++ b/tests/layer_tests/pytorch_tests/test_logaddexp.py@@ -3,7 +3,7 @@import pytestimport numpy as np-from pytorch_layer_test_class import PytorchLayerTest, skip_if_export+from pytorch_layer_test_class import PytorchLayerTestclass TestLogAddExp(PytorchLayerTest):@@ -116,7 +116,7 @@ class TestLogAddExp(PytorchLayerTest):],)@pytest.mark.parametrize(- "out", (False, skip_if_export(True))+ "out", (False, True))def test_logaddexp_shapes(self, dtype1, dtype2, shape, out, ie_device, precision, ir_version):# Generate random inputs within a reasonable rangediff --git a/tests/layer_tests/pytorch_tests/test_logical_ops.py b/tests/layer_tests/pytorch_tests/test_logical_ops.pyindex 66e6d5bbcd7..8b6bada78a6 100644--- a/tests/layer_tests/pytorch_tests/test_logical_ops.py+++ b/tests/layer_tests/pytorch_tests/test_logical_ops.py@@ -3,7 +3,7 @@import numpy as npimport pytest-from pytorch_layer_test_class import PytorchLayerTest, skip_if_export+from pytorch_layer_test_class import PytorchLayerTestclass TestLogicalOp(PytorchLayerTest):@@ -60,7 +60,7 @@ class TestLogicalOp(PytorchLayerTest):@pytest.mark.parametrize("op_type", ["and", "or", "not", "xor"])@pytest.mark.parametrize("first_dtype", ["bool", "int32", 'int8', 'float32'])@pytest.mark.parametrize("second_dtype", ["bool", "int32", 'int8', 'float32'])- @pytest.mark.parametrize("out", [skip_if_export(True), False])+ @pytest.mark.parametrize("out", [True, False])def test_logical(self, op_type, out, first_dtype, second_dtype, ie_device, precision, ir_version):self._test(*self.create_model(op_type, out),ie_device, precision, ir_version,diff --git a/tests/layer_tests/pytorch_tests/test_lstm.py b/tests/layer_tests/pytorch_tests/test_lstm.pyindex 28a43d696b4..21d0b52d50a 100644--- a/tests/layer_tests/pytorch_tests/test_lstm.py+++ b/tests/layer_tests/pytorch_tests/test_lstm.py@@ -101,13 +101,14 @@ class TestLSTM(PytorchLayerTest):@pytest.mark.parametrize("batch_first", [True, False])@pytest.mark.nightly@pytest.mark.precommit+ @pytest.mark.precommit_torch_exportdef test_lstm(self, input_size, hidden_size, num_layers, has_bias, bidirectional, batch_first, ie_device, precision, ir_version):self.input_size = input_sizeself.hidden_size = hidden_sizeself.num_layers = num_layersself.bidirectional = bidirectionalself.batch_first = batch_first- self._test(aten_lstm(input_size, hidden_size, num_layers, has_bias, bidirectional, batch_first), "aten::lstm",+ self._test(aten_lstm(input_size, hidden_size, num_layers, has_bias, bidirectional, batch_first).eval(), "aten::lstm",ie_device, precision, ir_version, trace_model=True)@@ -166,13 +167,14 @@ class TestGRU(PytorchLayerTest):@pytest.mark.parametrize("batch_first", [True, False])@pytest.mark.nightly@pytest.mark.precommit+ @pytest.mark.precommit_torch_exportdef test_gru(self, input_size, hidden_size, num_layers, has_bias, bidirectional, batch_first, ie_device, precision, ir_version):self.input_size = input_sizeself.hidden_size = hidden_sizeself.num_layers = num_layersself.bidirectional = bidirectionalself.batch_first = batch_first- self._test(aten_gru(input_size, hidden_size, num_layers, has_bias, bidirectional, batch_first), "aten::gru",+ self._test(aten_gru(input_size, hidden_size, num_layers, has_bias, bidirectional, batch_first).eval(), "aten::gru",ie_device, precision, ir_version, trace_model=True)@@ -196,11 +198,12 @@ class TestRNN(PytorchLayerTest):@pytest.mark.parametrize("nonlinearity", ["tanh", "relu"])@pytest.mark.nightly@pytest.mark.precommit+ @pytest.mark.precommit_torch_exportdef test_rnn(self, input_size, hidden_size, num_layers, has_bias, bidirectional, batch_first, nonlinearity, ie_device, precision, ir_version):self.input_size = input_sizeself.hidden_size = hidden_sizeself.num_layers = num_layersself.bidirectional = bidirectionalself.batch_first = batch_first- self._test(aten_rnn(input_size, hidden_size, num_layers, has_bias, bidirectional, batch_first, nonlinearity), f"aten::rnn_{nonlinearity}",+ self._test(aten_rnn(input_size, hidden_size, num_layers, has_bias, bidirectional, batch_first, nonlinearity).eval(), f"aten::rnn_{nonlinearity}",ie_device, precision, ir_version, trace_model=True)diff --git a/tests/layer_tests/pytorch_tests/test_masked_fill.py b/tests/layer_tests/pytorch_tests/test_masked_fill.pyindex cc6091280c8..dae4734cd0d 100644--- a/tests/layer_tests/pytorch_tests/test_masked_fill.py+++ b/tests/layer_tests/pytorch_tests/test_masked_fill.py@@ -6,7 +6,7 @@ import torchfrom packaging.version import parse as parse_versionimport pytest-from pytorch_layer_test_class import PytorchLayerTest, skip_if_export+from pytorch_layer_test_class import PytorchLayerTestclass TestMaskedFill(PytorchLayerTest):@@ -50,7 +50,7 @@ class TestMaskedFill(PytorchLayerTest):"mask_fill", ['zeros', 'ones', 'random'])@pytest.mark.parametrize("input_dtype", [np.float32, np.float64, int, np.int32])@pytest.mark.parametrize("mask_dtype", [bool]) # np.float32 incorrectly casted to bool- @pytest.mark.parametrize("inplace", [skip_if_export(True), False])+ @pytest.mark.parametrize("inplace", [True, False])@pytest.mark.nightly@pytest.mark.precommit@pytest.mark.precommit_torch_export@@ -66,7 +66,7 @@ class TestMaskedFill(PytorchLayerTest):"mask_fill", ['zeros', 'ones', 'random'])@pytest.mark.parametrize("input_dtype", [np.float32, np.float64, int, np.int32])@pytest.mark.parametrize("mask_dtype", [np.uint8, np.int32]) # np.float32 incorrectly casted to bool- @pytest.mark.parametrize("inplace", [skip_if_export(True), False])+ @pytest.mark.parametrize("inplace", [True, False])@pytest.mark.nightly@pytest.mark.precommit@pytest.mark.precommit_torch_exportdiff --git a/tests/layer_tests/pytorch_tests/test_masked_scatter.py b/tests/layer_tests/pytorch_tests/test_masked_scatter.pyindex 6017f62e4dd..c10dc53cd71 100644--- a/tests/layer_tests/pytorch_tests/test_masked_scatter.py+++ b/tests/layer_tests/pytorch_tests/test_masked_scatter.py@@ -5,7 +5,7 @@ import pytestimport torchfrom packaging.version import parse as parse_version-from pytorch_layer_test_class import PytorchLayerTest, skip_if_export+from pytorch_layer_test_class import PytorchLayerTestclass TestMaskedScatter(PytorchLayerTest):@@ -29,12 +29,13 @@ class TestMaskedScatter(PytorchLayerTest):self.forward = self.forward_inplaceif out:self.forward = self.forward_out+ self.out_op = PytorchLayerTest.out_variant(torch.masked_scatter, torch.ops.aten.masked_scatter.out)def forward(self, x, mask, source):return torch.masked_scatter(x, mask, source)def forward_out(self, x, mask, source, out):- return torch.masked_scatter(x, mask, source, out=out), out+ return self.out_op(x, mask, source, out=out), outdef forward_inplace(self, x, mask, source):return x.masked_scatter_(mask, source), x@@ -48,7 +49,7 @@ class TestMaskedScatter(PytorchLayerTest):@pytest.mark.parametrize("shape", [[2, 5], [10, 10], [2, 3, 4], [10, 5, 10, 3], [2, 6, 4, 1]])@pytest.mark.parametrize("input_dtype", ["float32", "int32", "float", "int", "uint8"])@pytest.mark.parametrize("mask_dtype", ["bool"])- @pytest.mark.parametrize("out", [skip_if_export(True), False])+ @pytest.mark.parametrize("out", [True, False])def test_masked_scatter(self, shape, input_dtype, mask_dtype, out, ie_device, precision, ir_version):self._test(*self.create_model(out), ie_device, precision, ir_version,kwargs_to_prepare_input={"shape": shape, "x_dtype": input_dtype, "mask_dtype": mask_dtype, "out": out})@@ -58,6 +59,7 @@ class TestMaskedScatter(PytorchLayerTest):@pytest.mark.parametrize("shape", [[2, 5], [10, 10], [2, 3, 4], [10, 5, 10, 3], [2, 6, 4, 1]])@pytest.mark.parametrize("input_dtype", ["float32", "int32", "float", "int", "uint8"])@pytest.mark.parametrize("mask_dtype", ["bool"])+ @pytest.mark.precommit_torch_exportdef test_masked_scatter_inplace(self, shape, input_dtype, mask_dtype, ie_device, precision, ir_version):self._test(*self.create_model(inplace=True), ie_device, precision, ir_version,kwargs_to_prepare_input={"shape": shape, "x_dtype": input_dtype, "mask_dtype": mask_dtype})diff --git a/tests/layer_tests/pytorch_tests/test_min_max.py b/tests/layer_tests/pytorch_tests/test_min_max.pyindex a6a475efe68..a3b5865d1fa 100644--- a/tests/layer_tests/pytorch_tests/test_min_max.py+++ b/tests/layer_tests/pytorch_tests/test_min_max.py@@ -3,7 +3,7 @@import pytest-from pytorch_layer_test_class import PytorchLayerTest, skip_if_export+from pytorch_layer_test_class import PytorchLayerTestclass TestMinMax(PytorchLayerTest):@@ -339,7 +339,7 @@ class TestAminAmax(PytorchLayerTest):@pytest.mark.parametrize("op_type", ["amin", "amax"])@pytest.mark.parametrize("axis", [None, 0, -1, 1, [1, 2], [-1, -2], [2, 0, -1], [0, 1, 2, 3]])@pytest.mark.parametrize("keep_dims", [True, False])- @pytest.mark.parametrize("out", [skip_if_export(True), False])+ @pytest.mark.parametrize("out", [True, False])@pytest.mark.parametrize("input_dtype", ['float32', 'int32', 'int64', 'float64'])@pytest.mark.precommit@pytest.mark.precommit_torch_exportdiff --git a/tests/layer_tests/pytorch_tests/test_nms.py b/tests/layer_tests/pytorch_tests/test_nms.pyindex ed1b6b33b54..6d8b8bdc78b 100644--- a/tests/layer_tests/pytorch_tests/test_nms.py+++ b/tests/layer_tests/pytorch_tests/test_nms.py@@ -36,6 +36,7 @@ class TestNms(PytorchLayerTest):@pytest.mark.nightly@pytest.mark.precommit+ @pytest.mark.precommit_torch_export@pytest.mark.xfail(condition=platform.system() == 'Darwin' and platform.machine() == 'arm64',reason='Ticket - 122715')def test_nms(self, ie_device, precision, ir_version, boxes_num):diff --git a/tests/layer_tests/pytorch_tests/test_norm.py b/tests/layer_tests/pytorch_tests/test_norm.pyindex 6993109155e..d8869da1648 100644--- a/tests/layer_tests/pytorch_tests/test_norm.py+++ b/tests/layer_tests/pytorch_tests/test_norm.py@@ -215,6 +215,7 @@ class TestLinalgVectorNorm(PytorchLayerTest):@pytest.mark.parametrize("dtype", ["float32", None])@pytest.mark.parametrize("out", [True, False])@pytest.mark.parametrize("prim_dtype", [True, False])+ @pytest.mark.precommit_torch_exportdef test_linalg_vector_norm(self, p, dim, keepdim, dtype, out, prim_dtype, ie_device, precision, ir_version):self._test(*self.create_model(p, dim, keepdim, dtype, out, prim_dtype),ie_device, precision, ir_version,@@ -222,6 +223,43 @@ class TestLinalgVectorNorm(PytorchLayerTest):"dim": dim, "keepdim": keepdim})+class TestLinalgVectorNormZeroOrder(PytorchLayerTest):+ def _prepare_input(self, input_shape):+ # Include zeros and both signs, with different nonzero counts per slice.+ data = np.array([0, -2, 0, 3, 4, 0, 0, 0, 0, -1, 2, 3], dtype=np.float32)+ return (data.reshape(input_shape),)++ @pytest.mark.nightly+ @pytest.mark.precommit+ @pytest.mark.precommit_torch_export+ @pytest.mark.parametrize("input_shape,dim", [+ ((3, 4), 1),+ ((3, 4), -1),+ ((2, 2, 3), 1),+ ((2, 2, 3), (0, 2)),+ ((2, 2, 3), None),+ ])+ @pytest.mark.parametrize("keepdim", [False, True])+ @pytest.mark.parametrize("dynamic_shapes", [False, True])+ def test_zero_order(self, input_shape, dim, keepdim, dynamic_shapes,+ ie_device, precision, ir_version):+ """ord=0 counts nonzeros along the reduction axes for inputs of any rank."""+ class ZeroOrderNorm(torch.nn.Module):+ def __init__(self):+ super().__init__()+ self.dim = dim+ self.keepdim = keepdim++ def forward(self, x):+ return torch.linalg.vector_norm(x, ord=0, dim=self.dim, keepdim=self.keepdim)++ self._test(ZeroOrderNorm(), "aten::linalg_vector_norm", ie_device, precision, ir_version,+ dynamic_shapes=dynamic_shapes,+ dynamic_shapes_for_export={"x": tuple(torch.export.Dim.DYNAMIC for _ in input_shape)}+ if dynamic_shapes else {},+ kwargs_to_prepare_input={"input_shape": input_shape})++class TestLinalgMatrixNorm(PytorchLayerTest):def _prepare_input(self, out=False, out_dtype=None, dim=None, keepdim=False):@@ -290,6 +328,7 @@ class TestLinalgMatrixNorm(PytorchLayerTest):'aarch64','arm64', 'ARM64'),reason='Ticket - 122715')+ @pytest.mark.precommit_torch_exportdef test_linalg_matrix_norm(self, p, dim, keepdim, dtype, out, prim_dtype, ie_device, precision, ir_version):self._test(*self.create_model(p, dim, keepdim, dtype, out, prim_dtype),ie_device, precision, ir_version,@@ -385,6 +424,7 @@ class TestLinalgNorm(PytorchLayerTest):@pytest.mark.parametrize("dtype", ["float32", None])@pytest.mark.parametrize("out", [True, False])@pytest.mark.parametrize("prim_dtype", [True, False])+ @pytest.mark.precommit_torch_exportdef test_linalg_norm(self, p, dim, keepdim, dtype, out, prim_dtype, input_shape, ie_device, precision, ir_version):self._test(*self.create_model(p, dim, keepdim, dtype, out, prim_dtype),ie_device, precision, ir_version,diff --git a/tests/layer_tests/pytorch_tests/test_outer.py b/tests/layer_tests/pytorch_tests/test_outer.pyindex 6c95692990c..189516d8726 100644--- a/tests/layer_tests/pytorch_tests/test_outer.py+++ b/tests/layer_tests/pytorch_tests/test_outer.py@@ -3,7 +3,7 @@import pytest-from pytorch_layer_test_class import PytorchLayerTest, skip_if_export+from pytorch_layer_test_class import PytorchLayerTestclass TestOuter(PytorchLayerTest):@@ -47,7 +47,7 @@ class TestOuter(PytorchLayerTest):@pytest.mark.parametrize("y_shape", ([1], [7], [5]))@pytest.mark.parametrize("x_dtype", ("float32", "float64", "int32"))@pytest.mark.parametrize("y_dtype", ("float32", "float64", "int32"))- @pytest.mark.parametrize("out", [skip_if_export(True), False])+ @pytest.mark.parametrize("out", [True, False])@pytest.mark.nightly@pytest.mark.precommit@pytest.mark.precommit_torch_exportdiff --git a/tests/layer_tests/pytorch_tests/test_pow.py b/tests/layer_tests/pytorch_tests/test_pow.pyindex 06414c95499..ea4d667c81f 100644--- a/tests/layer_tests/pytorch_tests/test_pow.py+++ b/tests/layer_tests/pytorch_tests/test_pow.py@@ -49,8 +49,6 @@ class TestPow(PytorchLayerTest):@pytest.mark.precommit_torch_export@pytest.mark.precommit_fx_backenddef test_pow(self, inplace, ie_device, precision, ir_version, test_input):- if inplace and PytorchLayerTest.use_torch_export():- pytest.skip(reason="export fails for inplace")self.test_input = test_inputself._test(*self.create_model(inplace), ie_device, precision,ir_version, use_convert_model=True)diff --git a/tests/layer_tests/pytorch_tests/test_quantize.py b/tests/layer_tests/pytorch_tests/test_quantize.pyindex 1d74c4ffeeb..9163bd294ba 100644--- a/tests/layer_tests/pytorch_tests/test_quantize.py+++ b/tests/layer_tests/pytorch_tests/test_quantize.py@@ -93,6 +93,7 @@ class TestQuantizePerTensorDequantize(PytorchLayerTest):@pytest.mark.precommit@pytest.mark.xfail(condition=platform.system() == 'Darwin' and platform.machine() == 'arm64',reason='Ticket - 122715')+ @pytest.mark.precommit_torch_exportdef test_quantize_per_tensor_dequantize(self, scale, zero_point, dtype, ie_device, precision, ir_version):if dtype == torch.quint8: zero_point = abs(zero_point)self._test(aten_quantize_per_tensor_aten_dequantize(scale, zero_point, dtype), ["aten::quantize_per_tensor", "aten::dequantize"],diff --git a/tests/layer_tests/pytorch_tests/test_rand.py b/tests/layer_tests/pytorch_tests/test_rand.pyindex e9825597fa3..cc2f10fe03c 100644--- a/tests/layer_tests/pytorch_tests/test_rand.py+++ b/tests/layer_tests/pytorch_tests/test_rand.py@@ -71,12 +71,13 @@ class TestNormal(PytorchLayerTest):class aten_normal6(torch.nn.Module):def forward(self, x):x = x.to(torch.float32)- return torch.normal(0., 1., x.shape)+ return torch.normal(0., 1., x.shape), xclass aten_normal7(torch.nn.Module):def forward(self, x):x = x.to(torch.float32)- return torch.normal(0., 1., x.shape, out=x), x+ before = x.clone()+ return torch.normal(0., 1., x.shape, out=x), x, before@pytest.mark.nightly@pytest.mark.precommit@@ -89,6 +90,7 @@ class TestNormal(PytorchLayerTest):(aten_normal6(), [1, 3, 224, 224]),(aten_normal7(), [1, 3, 224, 224]),])+ @pytest.mark.precommit_torch_exportdef test_inplace_normal(self, model, inputs, ie_device, precision, ir_version):self.inputs = inputsself._test(model, "aten::normal",@@ -96,6 +98,43 @@ class TestNormal(PytorchLayerTest):class TestStatistics():+ @pytest.mark.nightly+ @pytest.mark.precommit+ @pytest.mark.precommit_torch_export+ @pytest.mark.parametrize("shape", [(257,), (16, 32)])+ @pytest.mark.parametrize("use_out", [False, True])+ def test_normal_scalar_mean(self, shape, use_out, ie_device, precision):+ import numpy as np+ import openvino as ov++ class Model(torch.nn.Module):+ def __init__(self):+ super().__init__()+ self.use_out = use_out++ def forward(self, std):+ if self.use_out:+ out = torch.empty_like(std)+ return torch.normal(2.5, std, out=out)+ return torch.normal(2.5, std)++ std = torch.full(shape, 3.0)+ model = Model()+ if PytorchLayerTest.use_torch_export():+ input_model = torch.export.export(model, (std,))+ else:+ input_model = torch.jit.trace(model, (std,), check_trace=False)+ ov_model = ov.convert_model(input_model)+ config = {"INFERENCE_PRECISION_HINT": "f32"} if precision == "FP32" else {}+ compiled_model = ov.Core().compile_model(ov_model, ie_device, config)+ result = compiled_model([std.numpy()])[0]++ assert result.shape == shape+ assert np.isfinite(result).all()+ # A scalar random sample broadcast over std has the right shape but no+ # variation between elements. This must generate a sample per element.+ assert np.ptp(result) > 0+class aten_normal(torch.nn.Module):def forward(self, mean, std):return torch.normal(mean, std)diff --git a/tests/layer_tests/pytorch_tests/test_rope_pattern.py b/tests/layer_tests/pytorch_tests/test_rope_pattern.pyindex 95b33960a40..38f4b4e225d 100644--- a/tests/layer_tests/pytorch_tests/test_rope_pattern.py+++ b/tests/layer_tests/pytorch_tests/test_rope_pattern.py@@ -42,6 +42,7 @@ class TestRoPEPattern(PytorchLayerTest):@pytest.mark.parametrize("dim", [32, 64, 128])@pytest.mark.nightly@pytest.mark.precommit+ @pytest.mark.precommit_torch_exportdef 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},@@ -79,6 +80,7 @@ class TestComplexBufferUnsqueeze(PytorchLayerTest):@pytest.mark.nightly@pytest.mark.precommit+ @pytest.mark.precommit_torch_exportdef test_complex_buffer_unsqueeze(self, ie_device, precision, ir_version):self._test(*self.create_model(), ie_device, precision, ir_version,trace_model=True)@@ -114,6 +116,7 @@ class TestComplexBufferMultipleOps(PytorchLayerTest):@pytest.mark.nightly@pytest.mark.precommit+ @pytest.mark.precommit_torch_exportdef 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_round.py b/tests/layer_tests/pytorch_tests/test_round.pyindex 27fef455775..02b95d6dd56 100644--- a/tests/layer_tests/pytorch_tests/test_round.py+++ b/tests/layer_tests/pytorch_tests/test_round.py@@ -3,7 +3,7 @@import pytest-from pytorch_layer_test_class import PytorchLayerTest, skip_if_export+from pytorch_layer_test_class import PytorchLayerTestclass TestRound(PytorchLayerTest):@@ -41,7 +41,7 @@ class TestRound(PytorchLayerTest):@pytest.mark.precommit@pytest.mark.precommit_torch_export@pytest.mark.precommit_fx_backend- @pytest.mark.parametrize("out", [skip_if_export(True), False])+ @pytest.mark.parametrize("out", [True, False])@pytest.mark.parametrize("dtype", ["float32", "float64", "int32", "int64"])def test_round(self, out, dtype, ie_device, precision, ir_version):if ie_device == "GPU" and dtype not in ["float32", "float64"]:diff --git a/tests/layer_tests/pytorch_tests/test_rrelu.py b/tests/layer_tests/pytorch_tests/test_rrelu.pyindex d52c1d52fca..51b7f655fc6 100644--- a/tests/layer_tests/pytorch_tests/test_rrelu.py+++ b/tests/layer_tests/pytorch_tests/test_rrelu.py@@ -5,7 +5,7 @@ import pytestimport torchimport torch.nn.functional as F-from pytorch_layer_test_class import PytorchLayerTest, skip_if_export+from pytorch_layer_test_class import PytorchLayerTestclass aten_rrelu(torch.nn.Module):@@ -34,7 +34,7 @@ class TestRRelu(PytorchLayerTest):(0.0, 1.0),])@pytest.mark.parametrize("dtype", [torch.float16, torch.float32, torch.float64])- @pytest.mark.parametrize("inplace", [skip_if_export(True), False])+ @pytest.mark.parametrize("inplace", [True, False])def test_rrelu(self, lower, upper, dtype, inplace, ie_device, precision, ir_version):kwargs = {}if dtype == torch.float16:diff --git a/tests/layer_tests/pytorch_tests/test_scaled_dot_product_attention.py b/tests/layer_tests/pytorch_tests/test_scaled_dot_product_attention.pyindex 9d48f83d916..aec9e2f2223 100644--- a/tests/layer_tests/pytorch_tests/test_scaled_dot_product_attention.py+++ b/tests/layer_tests/pytorch_tests/test_scaled_dot_product_attention.py@@ -133,6 +133,7 @@ class TestScaledDotProductAttentionWithGroupQuery(PytorchLayerTest):(1, 1, 8, 1),(1, 1, 8, 16)])@pytest.mark.parametrize('dyn_shapes', (True, False))+ @pytest.mark.precommit_torch_exportdef test_scaled_dot_product_atten_with_gqa(self, ie_device, precision, ir_version,mask, is_causal, mask_shape, dyn_shapes):dtype = np.float32diff --git a/tests/layer_tests/pytorch_tests/test_scatter.py b/tests/layer_tests/pytorch_tests/test_scatter.pyindex e9a7c7d9a8a..c5e0e239ca1 100644--- a/tests/layer_tests/pytorch_tests/test_scatter.py+++ b/tests/layer_tests/pytorch_tests/test_scatter.py@@ -4,7 +4,7 @@import numpy as npimport pytestimport torch-from pytorch_layer_test_class import PytorchLayerTest, skip_if_export+from pytorch_layer_test_class import PytorchLayerTestclass TestScatter(PytorchLayerTest):@@ -111,6 +111,7 @@ class TestScatter(PytorchLayerTest):])@pytest.mark.parametrize("dtype", ["int32", "float32"])@pytest.mark.parametrize(["inplace", "has_out"], [(True, False), (False, True), (False, False)])+ @pytest.mark.precommit_torch_exportdef test_scatter(self, src, reduce, index, dim, dtype, inplace, has_out, ie_device, precision, ir_version):if isinstance(src, torch.Tensor):src = src.to(getattr(torch, dtype))@@ -198,6 +199,7 @@ class TestScatterReduce(PytorchLayerTest):@pytest.mark.parametrize(["inplace", "has_out"], [(True, False), (False, True), (False, False)])@pytest.mark.parametrize("reduce", ["sum", "prod", "mean", "amax", "amin"])@pytest.mark.parametrize("include_self", [True, False])+ @pytest.mark.precommit_torch_exportdef test_scatter_reduce(self, dim, index, src, dtype, inplace, has_out, reduce, include_self, ie_device, precision, ir_version):if isinstance(src, torch.Tensor):src = src.to(getattr(torch, dtype))@@ -260,7 +262,7 @@ class TestScatterAdd(PytorchLayerTest):)@pytest.mark.parametrize("src", [torch.arange(1, 26).reshape(5, 5)])@pytest.mark.parametrize("dtype", ["int32", "float32"])- @pytest.mark.parametrize("inplace", [skip_if_export(True), False])+ @pytest.mark.parametrize("inplace", [True, False])def test_scatter_add(self, dim, index, src, dtype, inplace, ie_device, precision, ir_version):if isinstance(src, torch.Tensor):src = src.to(getattr(torch, dtype))@@ -270,5 +272,5 @@ class TestScatterAdd(PytorchLayerTest):precision,ir_version,kwargs_to_prepare_input={"dtype": dtype},- fx_kind="aten.scatter_add",+ fx_kind="aten.scatter_add_" if inplace else "aten.scatter_add",)diff --git a/tests/layer_tests/pytorch_tests/test_search_sorted.py b/tests/layer_tests/pytorch_tests/test_search_sorted.pyindex dea2c248264..a478750562c 100644--- a/tests/layer_tests/pytorch_tests/test_search_sorted.py+++ b/tests/layer_tests/pytorch_tests/test_search_sorted.py@@ -36,6 +36,7 @@ class TestSearchSorted(PytorchLayerTest):@pytest.mark.parametrize("right_mode", [False, True])@pytest.mark.parametrize("sorted_type", [np.float32, np.float16, np.int8])@pytest.mark.parametrize("values_type", [np.float16, np.int32, np.int64])+ @pytest.mark.precommit_torch_exportdef test_searchsorted(self, sorted, values, right_mode, sorted_type, values_type, ie_device, precision, ir_version):self.sorted = sortedself.values = valuesdiff --git a/tests/layer_tests/pytorch_tests/test_sort.py b/tests/layer_tests/pytorch_tests/test_sort.pyindex bb3177d61b3..6c97b1562df 100644--- a/tests/layer_tests/pytorch_tests/test_sort.py+++ b/tests/layer_tests/pytorch_tests/test_sort.py@@ -8,6 +8,34 @@ import pytestfrom pytorch_layer_test_class import PytorchLayerTest+class TestSortOutputs(PytorchLayerTest):+ def _prepare_input(self):+ data = [[3, 1, 4, 2], [7, 5, 8, 6]]+ if self.stable:+ data = [[3, 1, 3, 1], [2, 2, 1, 1]]+ return (np.array(data, dtype=np.float32),)++ @pytest.mark.parametrize("stable", [None, False, True])+ @pytest.mark.parametrize("descending", [False, True])+ @pytest.mark.precommit+ @pytest.mark.precommit_torch_export+ @pytest.mark.precommit_fx_backend+ def test_sort_outputs(self, stable, descending, ie_device, precision, ir_version):+ class SortOutputs(torch.nn.Module):+ def __init__(self):+ super().__init__()+ self.stable = stable+ self.descending = descending++ def forward(self, data):+ if self.stable is None:+ return torch.sort(data, descending=self.descending)+ return torch.sort(data, stable=self.stable, descending=self.descending)++ self.stable = stable+ self._test(SortOutputs(), "aten::sort", ie_device, precision, ir_version)++class TestSortConstants(PytorchLayerTest):def _prepare_input(self):return (self.input_tensor,)diff --git a/tests/layer_tests/pytorch_tests/test_sum.py b/tests/layer_tests/pytorch_tests/test_sum.pyindex 6c95b907c0d..1aa33d08df5 100644--- a/tests/layer_tests/pytorch_tests/test_sum.py+++ b/tests/layer_tests/pytorch_tests/test_sum.py@@ -3,7 +3,7 @@import pytest-from pytorch_layer_test_class import PytorchLayerTest, skip_if_export+from pytorch_layer_test_class import PytorchLayerTestclass TestSum(PytorchLayerTest):@@ -76,15 +76,7 @@ class TestSum(PytorchLayerTest):def forward_out(self, x, out):x = x.to(self.input_dtype)if self.axes is None and self.keep_dims is None:- if self.dtype is None:- return torch.sum(x, out=out), out- else:- return torch.sum(x, out=out, dtype=self.dtype), out- if self.axes is None and self.keep_dims is None:- if self.dtype is not None:- return torch.sum(x, dtype=self.dtype, out=out), out- else:- return torch.sum(x, out=out), out+ return torch.sum(x, dim=None, dtype=self.dtype, out=out), outif self.axes is not None and self.keep_dims is None:if self.dtype is not None:return torch.sum(x, self.axes, dtype=self.dtype, out=out), out@@ -102,7 +94,7 @@ class TestSum(PytorchLayerTest):@pytest.mark.parametrize("axes,keep_dims",[(None, None), (None, False), (-1, None), (1, None), ((2, 3), False), ((3, 2), True)])@pytest.mark.parametrize("dtype", [None, "float32", "int64"])- @pytest.mark.parametrize("out", [skip_if_export(True), False])+ @pytest.mark.parametrize("out", [True, False])@pytest.mark.parametrize("input_dtype", ["float32", "uint8", "bool", "int64"])@pytest.mark.nightly@pytest.mark.precommitdiff --git a/tests/layer_tests/pytorch_tests/test_take_along_dim.py b/tests/layer_tests/pytorch_tests/test_take_along_dim.pyindex c21b728fdf8..687409e0f8f 100644--- a/tests/layer_tests/pytorch_tests/test_take_along_dim.py+++ b/tests/layer_tests/pytorch_tests/test_take_along_dim.py@@ -3,7 +3,7 @@import pytest-from pytorch_layer_test_class import PytorchLayerTest, skip_if_export+from pytorch_layer_test_class import PytorchLayerTestclass TestTakeAlongDim(PytorchLayerTest):def _prepare_input(self, m, n, max_val, out=False, flattenize=False):@@ -49,7 +49,7 @@ class TestTakeAlongDim(PytorchLayerTest):@pytest.mark.parametrize("m", [2, 10, 100])@pytest.mark.parametrize("n", [2, 10, 100])@pytest.mark.parametrize("axis", [0, 1, None])- @pytest.mark.parametrize("out", [skip_if_export(True), False])+ @pytest.mark.parametrize("out", [True, False])def test_gather(self, m, n, axis, out, ie_device, precision, ir_version):self._test(*self.create_model(axis, out), ie_device, precision, ir_version, kwargs_to_prepare_input={"m": m, "n": n, "max_val": m if axis == 0 else n, "out": out, "flattenize": axis is Nonediff --git a/tests/layer_tests/pytorch_tests/test_to.py b/tests/layer_tests/pytorch_tests/test_to.pyindex 0375611afa6..a4a1f5e7c21 100644--- a/tests/layer_tests/pytorch_tests/test_to.py+++ b/tests/layer_tests/pytorch_tests/test_to.py@@ -99,6 +99,7 @@ class TestAtenTo(PytorchLayerTest):precision, ir_version, kwargs_to_prepare_input={"input_shape": input_shape})[email protected]_torch_exportclass TestAtenToDevice(PytorchLayerTest):def _prepare_input(self):return (self.random.uniform(low=0.0, high=50.0, size=(3,)), self.random.uniform(low=0.0, high=50.0, size=(3,)))@@ -122,6 +123,7 @@ class TestAtenToDevice(PytorchLayerTest):ir_version, trace_model=use_trace)[email protected]_torch_exportclass TestAtenToDeviceConst(PytorchLayerTest):def _prepare_input(self):return (self.random.uniform(low=0.0, high=50.0, size=(3,)),)diff --git a/tests/layer_tests/pytorch_tests/test_unary_ops.py b/tests/layer_tests/pytorch_tests/test_unary_ops.pyindex 3dd509608a8..53796a6f6d2 100644--- a/tests/layer_tests/pytorch_tests/test_unary_ops.py+++ b/tests/layer_tests/pytorch_tests/test_unary_ops.py@@ -5,7 +5,7 @@ import pytestimport torchimport torch.nn.functional as F-from pytorch_layer_test_class import PytorchLayerTest, skip_if_export+from pytorch_layer_test_class import PytorchLayerTestOPS = {"aten::abs": torch.abs,@@ -91,12 +91,13 @@ class unary_op_out_net(torch.nn.Module):super().__init__()self.dtype = dtypeself.op = op+ self.out_op = PytorchLayerTest.out_variant(op, torch.ops.aten.relu.out) if op == torch.relu else opdef forward(self, x):x1 = x.to(self.dtype)y = self.op(x1)z = torch.empty_like(y)- y1 = self.op(x1, out=z)+ y1 = self.out_op(x1, out=z)return y1, z@@ -163,11 +164,11 @@ class TestUnaryOp(PytorchLayerTest):"aten::exp","aten::expm1","aten::relu",- skip_if_export("aten::relu_"),+ "aten::relu_","aten::ceil",- skip_if_export("aten::ceil_"),+ "aten::ceil_","aten::floor",- skip_if_export("aten::floor_"),+ "aten::floor_","aten::sigmoid","aten::reciprocal","aten::log",@@ -281,6 +282,7 @@ class TestUnaryOp(PytorchLayerTest):"aten::asinh","aten::atanh"])+ @pytest.mark.precommit_torch_exportdef test_unary_op_out(self, op_type, dtype, ie_device, precision, ir_version):self.dtype = dtypeself._test(unary_op_out_net(OPS[op_type], dtype), op_type,@@ -298,6 +300,7 @@ class TestUnaryOp(PytorchLayerTest):"aten::hardswish","aten::mish",])+ @pytest.mark.precommit_torch_exportdef test_unary_func_op_inplace(self, op_type, dtype, ie_device, precision, ir_version):self.dtype = dtypeself._test(unary_func_op_inplace_net(OPS[op_type], dtype), op_type + "_",@@ -321,6 +324,7 @@ class TestUnaryOp(PytorchLayerTest):"aten::abs","aten::exp",])+ @pytest.mark.precommit_torch_exportdef test_complex_unary_op(self, op_type, dtype, ie_device, precision, ir_version):self.dtype = dtypeself._test(unary_op_complex_net(OPS[op_type], dtype), op_type,diff --git a/tests/layer_tests/pytorch_tests/test_unsqueeze.py b/tests/layer_tests/pytorch_tests/test_unsqueeze.pyindex 7322a5ed93e..f07a325c93b 100644--- a/tests/layer_tests/pytorch_tests/test_unsqueeze.py+++ b/tests/layer_tests/pytorch_tests/test_unsqueeze.py@@ -3,7 +3,7 @@import pytest-from pytorch_layer_test_class import PytorchLayerTest, skip_if_export+from pytorch_layer_test_class import PytorchLayerTestclass TestUnsqueeze(PytorchLayerTest):@@ -28,13 +28,14 @@ class TestUnsqueeze(PytorchLayerTest):self.dim = dimdef forward(self, x):+ x = x.clone()return x, x.unsqueeze_(self.dim)model_class, op = (aten_unsqueeze, "aten::unsqueeze") if not inplace else (aten_unsqueeze_, "aten::unsqueeze_")return model_class(dim), op- @pytest.mark.parametrize("inplace", [False, skip_if_export(True)])+ @pytest.mark.parametrize("inplace", [False, True])@pytest.mark.parametrize("dim", [0, 1, -1])@pytest.mark.nightly@pytest.mark.precommit@@ -100,7 +101,7 @@ class TestUnsqueezeWithComplex(PytorchLayerTest):return model_class(dim), op- @pytest.mark.parametrize("inplace", [False, skip_if_export(True)])+ @pytest.mark.parametrize("inplace", [False, True])@pytest.mark.parametrize("dim", [0, 1, -1, -2])@pytest.mark.nightly@pytest.mark.precommitdiff --git a/tests/layer_tests/pytorch_tests/test_vstack.py b/tests/layer_tests/pytorch_tests/test_vstack.pyindex f8346a0577a..fb13d1d1a54 100644--- a/tests/layer_tests/pytorch_tests/test_vstack.py+++ b/tests/layer_tests/pytorch_tests/test_vstack.py@@ -4,7 +4,7 @@import pytestimport torchimport numpy as np-from pytorch_layer_test_class import PytorchLayerTest, skip_if_export+from pytorch_layer_test_class import PytorchLayerTestclass aten_vstack(torch.nn.Module):def forward(self, x):@@ -29,7 +29,7 @@ class TestVstack(PytorchLayerTest):@pytest.mark.nightly@pytest.mark.precommit@pytest.mark.precommit_torch_export- @pytest.mark.parametrize("out", [False, skip_if_export(True)])+ @pytest.mark.parametrize("out", [False, True])def test_vstack(self, out, ie_device, precision, ir_version):model = aten_vstack() if not out else aten_vstack_out()self._test(model, "aten::vstack", ie_device,diff --git a/tests/model_hub_tests/pytorch/test_llm.py b/tests/model_hub_tests/pytorch/test_llm.pyindex 29ef648032d..be9d8be2a87 100644--- a/tests/model_hub_tests/pytorch/test_llm.py+++ b/tests/model_hub_tests/pytorch/test_llm.py@@ -551,6 +551,14 @@ class TestLLMModel(TestTorchConvertModel):return self._infer_ov_model_export(ov_model, ie_device)return super().infer_ov_model(ov_model, inputs, ie_device)+ def get_compile_config(self, ie_device):+ config = super().get_compile_config(ie_device)+ if ie_device == "CPU" and platform.machine() in ["aarch64", "arm64", "ARM64"]:+ # ARM CPU defaults to FP16, whose accumulated rounding error in the KV cache+ # can exceed this conversion test's tolerance against the FP32 reference.+ config["INFERENCE_PRECISION_HINT"] = "f32"+ return config+def compare_results(self, fw_outputs, ov_outputs):if self.export_mode and isinstance(fw_outputs, (list, tuple)):# In export mode, only compare the first output (logits).diff --git a/tests/requirements_pytorch b/tests/requirements_pytorchindex ac1b2bbe324..806b651d865 100644--- a/tests/requirements_pytorch+++ b/tests/requirements_pytorch@@ -8,8 +8,8 @@ numpy==1.26.4; python_version < "3.12"numpy==2.1.1; python_version >= "3.12"--extra-index-url https://download.pytorch.org/whl/cpu-torch==2.12.0-torchvision==0.27.0+torch==2.14.0+torchvision==0.29.0pytest==7.0.1; python_version < '3.10'pytest==7.2.0; python_version >= '3.10'