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
Fix flake8 style in pytorch python bindings (#29140)
Maxim Vafin8b41805ee75c
diff --git a/src/bindings/python/src/openvino/frontend/pytorch/__init__.py b/src/bindings/python/src/openvino/frontend/pytorch/__init__.pyindex 0ec7bdc9bbb..3504c495344 100644--- a/src/bindings/python/src/openvino/frontend/pytorch/__init__.py+++ b/src/bindings/python/src/openvino/frontend/pytorch/__init__.py@@ -1,13 +1,12 @@+# -*- coding: utf-8 -*-# Copyright (C) 2018-2025 Intel Corporation# SPDX-License-Identifier: Apache-2.0-"""-Package: openvino+"""Package: openvino.+Low level wrappers for the FrontEnd C++ API."""-# flake8: noqa-try:from openvino.frontend.pytorch.py_pytorch_frontend import _FrontEndPytorchDecoder as Decoderfrom openvino.frontend.pytorch.py_pytorch_frontend import _Type as DecoderType@@ -15,5 +14,4 @@ try:from openvino.frontend.pytorch.py_pytorch_frontend import OpExtensionPytorch as OpExtensionfrom openvino.frontend.pytorch.module_extension import ModuleExtensionexcept ImportError as err:- raise ImportError("OpenVINO PyTorch frontend is not available, please make sure the frontend is built."- "{}".format(err))+ raise ImportError(f"OpenVINO PyTorch frontend is not available, please make sure the frontend is built. {err}")diff --git a/src/bindings/python/src/openvino/frontend/pytorch/fx_decoder.py b/src/bindings/python/src/openvino/frontend/pytorch/fx_decoder.pyindex b1ebd9076e1..417bac5db83 100644--- a/src/bindings/python/src/openvino/frontend/pytorch/fx_decoder.py+++ b/src/bindings/python/src/openvino/frontend/pytorch/fx_decoder.py@@ -1,12 +1,11 @@+# -*- coding: utf-8 -*-# Copyright (C) 2018-2025 Intel Corporation# SPDX-License-Identifier: Apache-2.0-# flake8: noqa# mypy: ignore-errorsimport loggingimport inspect-from typing import Any, Optionalimport torchfrom openvino.frontend.pytorch.py_pytorch_frontend import _FrontEndPytorchDecoder as Decoder@@ -18,11 +17,10 @@ from openvino.frontend.pytorch.utils import (logger = logging.getLogger(__name__)-class BaseFXDecoder (Decoder):- """- BaseFXDecoder is a class that extends the Decoder class to handle decoding- operations for FX graphs in PyTorch. It provides a common interface for all- FX decoders.+class BaseFXDecoder(Decoder):+ """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:@@ -38,15 +36,15 @@ class BaseFXDecoder (Decoder):def unpack_containers(arg):if isinstance(arg, (tuple, list)):res = []- for e in arg:- res.extend(BaseFXDecoder.unpack_containers(e))+ for element in arg:+ res.extend(BaseFXDecoder.unpack_containers(element))return reselif isinstance(arg, dict):res = []- for k, e in arg.items():- unpacked = BaseFXDecoder.unpack_containers(e)+ for key, element in arg.items():+ unpacked = BaseFXDecoder.unpack_containers(element)if len(unpacked) == 1:- unpacked[0] = (k, unpacked[0][1])+ unpacked[0] = (key, unpacked[0][1])res.extend(unpacked)return reselse:@@ -75,9 +73,9 @@ class BaseFXDecoder (Decoder):@staticmethoddef get_type_for_value(value):if issubclass(type(value), torch.fx.Node):- 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+ 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"].dtypeif str(pt_type) in pt_to_ov_type_map:ov_type = pt_to_ov_type_map[str(pt_type)]return OVAny(ov_type)@@ -99,9 +97,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 input(self, index):- return self.inputs()[index]-def output(self, index):return self.outputs()[index]@@ -137,7 +132,7 @@ class BaseFXDecoder (Decoder):return "fx"def get_schema(self):- return 'NONE'+ return "NONE"def mark_node(self, node):if self.mark_node_callback is not None:@@ -162,20 +157,20 @@ class BaseFXDecoder (Decoder):class TorchFXPythonDecoder (BaseFXDecoder):- """- Decoder for PyTorch FX GraphModule and Node objects to OpenVINO IR.- """+ """Decoder for PyTorch FX GraphModule and Node objects to OpenVINO IR."""_decomp_table = Nonedef __init__(self, pt_module, fx_gm=None, nodes=None,- mark_node_callback=None, input_shapes=[], input_types=[], dynamic_shapes=False):+ mark_node_callback=None, input_shapes=None,+ input_types=None, dynamic_shapes=False):super().__init__(mark_node_callback)self.pt_module = pt_moduleself.fx_gm = fx_gm if fx_gm is not None else pt_module+ self.input_types = input_types or []self.input_types = [OVAny(pt_to_ov_type_map[str(t)])- for t in input_types]- self.input_shapes = input_shapes+ for t in self.input_types]+ self.input_shapes = input_shapes or []self._input_signature = []self._example_input = None@@ -186,7 +181,7 @@ class TorchFXPythonDecoder (BaseFXDecoder):found_types = []found_shapes = []for i, value in enumerate(self._nodes):- if value.op == 'placeholder':+ if value.op == "placeholder":self._inputs.append(i)self._input_signature.append(value.name)@@ -201,7 +196,7 @@ class TorchFXPythonDecoder (BaseFXDecoder):new_shape.append(dim)found_shapes[-1] = torch.Size(new_shape)- elif value.op == 'output':+ elif value.op == "output":# Instead of putting output index, refer to its targetuargs = self.unpack_containers(value.args)self._outputs = [(arg[0], self._nodes.index(arg[1]))@@ -233,10 +228,8 @@ class TorchFXPythonDecoder (BaseFXDecoder):BaseFXDecoder.get_type_for_value(arg))@classmethod- def from_exported_program(cls, exported_program: torch.export.ExportedProgram) -> 'TorchFXPythonDecoder':- """- Create a TorchFXPythonDecoder instance from an exported PyTorch program.- """+ def from_exported_program(cls, exported_program: torch.export.ExportedProgram) -> "TorchFXPythonDecoder":+ """Create a TorchFXPythonDecoder instance from an exported PyTorch program."""from packaging import versionif version.parse(torch.__version__) >= version.parse("2.6"):if cls._decomp_table is None:@@ -262,17 +255,17 @@ class TorchFXPythonDecoder (BaseFXDecoder):def get_found_shape(value) -> str:# If input is a tensor, read the shape from meta dataif hasattr(value, "meta"):- if ('tensor_meta' in value.meta.keys()) and value.meta['tensor_meta']:- return value.meta['tensor_meta'].shape- if ('val' in value.meta.keys()) and isinstance(value.meta["val"], torch.Tensor):- return value.meta['val'].shape+ if ("tensor_meta" in value.meta.keys()) and value.meta["tensor_meta"]:+ return value.meta["tensor_meta"].shape+ if ("val" in value.meta.keys()) and isinstance(value.meta["val"], torch.Tensor):+ return value.meta["val"].shapereturn None@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)])+ 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)])return Nonedef get_input_signature_name(self, index: int) -> str:@@ -283,8 +276,8 @@ class TorchFXPythonDecoder (BaseFXDecoder):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])- input = self._raw_input(index)- return self.get_shape_for_value(input)+ _input = self._raw_input(index)+ return self.get_shape_for_value(_input)def get_input_strides(self, index: int) -> list:raw_input = self._raw_input(index)@@ -299,8 +292,8 @@ class TorchFXPythonDecoder (BaseFXDecoder):def get_input_type(self, index):if index < len(self.input_types) and self.input_types[index] is not None:return self.input_types[index]- input = self._raw_input(index)- return self.get_type_for_value(input)+ _input = self._raw_input(index)+ return self.get_type_for_value(_input)def get_output_debug_name(self, index):if self._outputs is not None and index < len(self._outputs) and self._outputs[index][0]:@@ -317,9 +310,9 @@ class TorchFXPythonDecoder (BaseFXDecoder):return self.get_type_for_value(output)def get_shape_for_value(self, value):- if value and hasattr(value, "meta") and ('tensor_meta' in value.meta.keys()):- if value.meta['tensor_meta']:- return PartialShape(len(value.meta['tensor_meta'].shape) * [-1])+ if value and hasattr(value, "meta") and ("tensor_meta" in value.meta.keys()):+ if value.meta["tensor_meta"]:+ return PartialShape(len(value.meta["tensor_meta"].shape) * [-1])return PartialShape.dynamic()def get_attribute(self, name):@@ -340,8 +333,9 @@ class TorchFXPythonDecoder (BaseFXDecoder):return OVAny(None)def get_named_input(self, name):- """- Returns id of kwargs input. Such input can be Node or a constant value,+ """Returns id of kwargs input.++ Such input can be Node or a constant value,this function is only used for to return node index. If the input isconstant, get_attribute should be used."""@@ -354,9 +348,9 @@ class TorchFXPythonDecoder (BaseFXDecoder):def visit_subgraph(self, node_visitor):# make sure topological order is satisfiedfor node in self._nodes:- if node.op == 'placeholder' or node.op == 'output':+ if node.op in {"placeholder", "output"}:continue # skipping non-operational nodes- if node.op == 'call_function' and str(node.target) in ["aten._assert_async.msg"]:+ if node.op == "call_function" and str(node.target) in ["aten._assert_async.msg"]:continuedecoder = TorchFXPythonDecoder(node, self.fx_gm, self._nodes, mark_node_callback=self.mark_node_callback)@@ -371,14 +365,14 @@ class TorchFXPythonDecoder (BaseFXDecoder):return decoderdef get_op_type(self):- if self.pt_module.op == 'call_function':+ if self.pt_module.op == "call_function":if type(self.pt_module.target).__name__ == "EdgeOpOverload":return self.pt_module.target.__name__return str(self.pt_module.target)- elif self.pt_module.op == 'get_attr':- return 'get_attr' # FIXME should be aligned with get_attr from TS implementation+ elif self.pt_module.op == "get_attr":+ return "get_attr" # FIXME should be aligned with get_attr from TS implementationelse:- return 'UNKNOWN_TYPE_' + str(self.pt_module.op)+ return "UNKNOWN_TYPE_" + str(self.pt_module.op)def outputs(self):return [o[1] for o in self._outputs]@@ -414,7 +408,7 @@ class TorchFXPythonDecoder (BaseFXDecoder):return nodedef as_constant(self):- assert self.pt_module.op == 'get_attr', "Only get_attr is supported"+ assert self.pt_module.op == "get_attr", "Only get_attr is supported"# Extract Constant from FX module fieldret = fetch_attr(self.fx_gm, self.pt_module.target)ov_const = torch_tensor_to_ov_const(ret, shared_memory=True)@@ -425,16 +419,16 @@ class TorchFXPythonDecoder (BaseFXDecoder):return Trueelse:r_input = self._raw_input(index)- return str(type(r_input)) in ['torch.NoneType', 'NoneType']+ return str(type(r_input)) in ["torch.NoneType", "NoneType"]def debug(self):self.pt_module.print()class InlinedInput:- """- Represents an inlined input. This is a special case- where the input is not a node, but a constant value.+ """Represents an inlined input.++ This is a special case where the input is not a node, but a constant value."""def __init__(self, data) -> None:@@ -442,9 +436,7 @@ class InlinedInput:class InlinedInputDecoder (BaseFXDecoder):- """- Decoder for inlined inputs in PyTorch FX graphs.- """+ """Decoder for inlined inputs in PyTorch FX graphs."""def __init__(self, inlined_input: InlinedInput, nodes=None, mark_node_callback=None) -> None:super().__init__(mark_node_callback)diff --git a/src/bindings/python/src/openvino/frontend/pytorch/gptq.py b/src/bindings/python/src/openvino/frontend/pytorch/gptq.pyindex 73795a421af..86d3f78f88c 100644--- a/src/bindings/python/src/openvino/frontend/pytorch/gptq.py+++ b/src/bindings/python/src/openvino/frontend/pytorch/gptq.py@@ -1,7 +1,7 @@+# -*- coding: utf-8 -*-# Copyright (C) 2018-2025 Intel Corporation# SPDX-License-Identifier: Apache-2.0-# flake8: noqa# mypy: ignore-errorsfrom functools import partial@@ -12,7 +12,8 @@ log = logging.getLogger(__name__)# Wraps a single tensor to a module to prevent it from jit.freezing-# It depends on a tensor dtype whether it will be preserved from freezing. Refer to the decoder code to learn which types will be preserved.+# It depends on a tensor dtype whether it will be preserved from freezing.+# Refer to the decoder code to learn which types will be preserved.class KeepWeight(torch.nn.Module):def __init__(self, weight):@@ -30,13 +31,13 @@ def decompression_pattern(weights):def patched_forward(self, *args, **kwargs):- if hasattr(self, '_hf_hook'):+ if hasattr(self, "_hf_hook"):args, kwargs = self._hf_hook.pre_forward(self, *args, **kwargs)- x = args[0]- dtype = x.dtype- outshape = x.shape[:-1] + (self.width,)- x = x.contiguous().view(-1, x.shape[-1])+ arg = args[0]+ dtype = arg.dtype+ outshape = arg.shape[:-1] + (self.width,)+ arg = arg.contiguous().view(-1, arg.shape[-1])groups = self.qzeros.shape[0]height = self.qweight.shape[0]@@ -50,25 +51,25 @@ def patched_forward(self, *args, **kwargs):unpacked_weights = (unpacked_weights.to(dtype) - unpacked_zp) * self.scalesunpacked_weights = unpacked_weights.view(-1, self.width)- out = x @ unpacked_weights+ out = arg @ unpacked_weightsout = out.view(outshape)if self.bias is not None:out.add_(self.bias)- if hasattr(self, '_hf_hook'):+ if hasattr(self, "_hf_hook"):out = self._hf_hook.post_forward(self, out)return outdef patched_forward_sym(self, *args, **kwargs):- if hasattr(self, '_hf_hook'):+ if hasattr(self, "_hf_hook"):args, kwargs = self._hf_hook.pre_forward(self, *args, **kwargs)- x = args[0]- dtype = x.dtype- outshape = x.shape[:-1] + (self.width,)- x = x.contiguous().view(-1, x.shape[-1])+ arg = args[0]+ dtype = arg.dtype+ outshape = arg.shape[:-1] + (self.width,)+ arg = arg.contiguous().view(-1, arg.shape[-1])height = self.qweight.shape[0]unpacked_weights = decompression_pattern(@@ -81,19 +82,19 @@ def patched_forward_sym(self, *args, **kwargs):unpacked_weights = unpacked_weights.to(dtype) * self.scalesunpacked_weights = unpacked_weights.view(-1, self.width)- out = x @ unpacked_weights+ out = arg @ unpacked_weightsout = out.view(outshape)if self.bias is not None:out.add_(self.bias)- if hasattr(self, '_hf_hook'):+ if hasattr(self, "_hf_hook"):out = self._hf_hook.post_forward(self, out)return out-# All the following AutoGPTQ's quant types are supposed to have the same weights packing schema-supported_quant_types = ['triton', 'exllama', 'exllamav2', 'cuda-old']+# All the following AutoGPTQ"s quant types are supposed to have the same weights packing schema+supported_quant_types = ["triton", "exllama", "exllamav2", "cuda-old"]def patch_model(model):@@ -104,75 +105,75 @@ def patch_model(model):elif hasattr(model, "model") and hasattr(model.model, "config"):# original model was wrappedconfig = model.model.config- if config is not None and hasattr(config, 'quantization_config') and hasattr(config.quantization_config, 'sym'):+ if config is not None and hasattr(config, "quantization_config") and hasattr(config.quantization_config, "sym"):is_symmetrical = config.quantization_config.sym- for name, m in model.named_modules():- if hasattr(m, '_openvino_patch_orig_forward'):+ for name, module in model.named_modules():+ if hasattr(module, "_openvino_patch_orig_forward"):# already patched, skippingcontinue# TODO: Check module type- is_quantized = getattr(m, 'is_quantized', None)+ is_quantized = getattr(module, "is_quantized", None)if is_quantized is not None:- m.is_quantized = False- m.float() # enables tracing on CPU, applied for all modules- if hasattr(m, 'QUANT_TYPE'):- if m.QUANT_TYPE not in supported_quant_types:- raise ValueError(f'Unsupported QUANT_TYPE == {m.QUANT_TYPE} is discovered for '- 'AutoGPTQ model, only the following types are supported: '- f'{supported_quant_types}')- if m.bits != 4:- raise ValueError(f'Unsupported bits == {m.bits} is discovered in module {name} '- 'in AutoGPTQ model, only bits == 4 is supported.')+ module.is_quantized = False+ module.float() # enables tracing on CPU, applied for all modules+ if hasattr(module, "QUANT_TYPE"):+ if module.QUANT_TYPE not in supported_quant_types:+ raise ValueError(f"Unsupported QUANT_TYPE == {module.QUANT_TYPE} is discovered for "+ "AutoGPTQ model, only the following types are supported: "+ f"{supported_quant_types}")+ if module.bits != 4:+ raise ValueError(f"Unsupported bits == {module.bits} is discovered in module {name} "+ "in AutoGPTQ model, only bits == 4 is supported.")int4_in_int32 = 8- groups = m.qzeros.shape[0]- m.width = m.qweight.shape[1]- assert m.group_size == m.qweight.shape[0] * int4_in_int32 // groups+ groups = module.qzeros.shape[0]+ module.width = module.qweight.shape[1]+ assert module.group_size == module.qweight.shape[0] * int4_in_int32 // groups- m._openvino_patch_orig_forward = m.forward+ module._openvino_patch_orig_forward = module.forwardif is_symmetrical:- m.forward = partial(patched_forward_sym, m)+ module.forward = partial(patched_forward_sym, module)else:- m.forward = partial(patched_forward, m)+ module.forward = partial(patched_forward, module)# Keep original field properties to be used when model is returned back to its original state- m._openvino_patch_orig_qweights_type = m.qweight.dtype- m._openvino_patch_orig_qzeros_type = m.qzeros.dtype- m._openvino_patch_orig_scale_shape = m.scales.shape+ module._openvino_patch_orig_qweights_type = module.qweight.dtype+ module._openvino_patch_orig_qzeros_type = module.qzeros.dtype+ module._openvino_patch_orig_scale_shape = module.scales.shape- m.qweight = m.qweight.view(dtype=torch.uint8)- m.qzeros = m.qzeros.view(dtype=torch.uint8)+ module.qweight = module.qweight.view(dtype=torch.uint8)+ module.qzeros = module.qzeros.view(dtype=torch.uint8)- # TODO: Redundant tensor copy? Try to remove m.qweight and m.qzeros after keeping modified values as submodules- m.add_module(- '_openvino_u4_compression_submodule_qweights', KeepWeight(m.qweight))+ # TODO: Redundant tensor copy? Try to remove module.qweight and module.qzeros after keeping modified values as submodules+ module.add_module(+ "_openvino_u4_compression_submodule_qweights", KeepWeight(module.qweight))# Adding 17 to move zp+1 step from after unpacking to before to have correct decompression pattern. Can it overflow?- m.add_module('_openvino_u4_compression_submodule_qzeros',- KeepWeight(m.qzeros + torch.tensor(17, dtype=torch.uint8)))+ module.add_module("_openvino_u4_compression_submodule_qzeros",+ KeepWeight(module.qzeros + torch.tensor(17, dtype=torch.uint8)))- m.scales = m.scales.view(-1, 1, m.width)+ module.scales = module.scales.view(-1, 1, module.width)def unpatch_model(model):- for _, m in model.named_modules():- if hasattr(m, '_openvino_patch_orig_forward'):+ for _, module in model.named_modules():+ if hasattr(module, "_openvino_patch_orig_forward"):try:- m.forward = m._openvino_patch_orig_forward- del m._openvino_patch_orig_forward+ module.forward = module._openvino_patch_orig_forward+ del module._openvino_patch_orig_forward- m.qweight = m.qweight.view(- dtype=m._openvino_patch_orig_qweights_type)- del m._openvino_patch_orig_qweights_type+ module.qweight = module.qweight.view(+ dtype=module._openvino_patch_orig_qweights_type)+ del module._openvino_patch_orig_qweights_type- m.qzeros = m.qzeros.view(- dtype=m._openvino_patch_orig_qzeros_type)- del m._openvino_patch_orig_qzeros_type+ module.qzeros = module.qzeros.view(+ dtype=module._openvino_patch_orig_qzeros_type)+ del module._openvino_patch_orig_qzeros_type- m.scales = m.scales.view(m._openvino_patch_orig_scale_shape)- del m._openvino_patch_orig_scale_shape+ module.scales = module.scales.view(module._openvino_patch_orig_scale_shape)+ del module._openvino_patch_orig_scale_shape- del m._openvino_u4_compression_submodule_qweights- del m._openvino_u4_compression_submodule_qzeros+ del module._openvino_u4_compression_submodule_qweights+ del module._openvino_u4_compression_submodule_qzerosexcept Exception as error:log.warning("Exception raised during GPTQ model unpatching. ""Depending on the exact issue it may lead to broken "diff --git a/src/bindings/python/src/openvino/frontend/pytorch/module_extension.py b/src/bindings/python/src/openvino/frontend/pytorch/module_extension.pyindex faeb93dda5d..a698d0bdd5a 100644--- a/src/bindings/python/src/openvino/frontend/pytorch/module_extension.py+++ b/src/bindings/python/src/openvino/frontend/pytorch/module_extension.py@@ -1,36 +1,58 @@+# -*- coding: utf-8 -*-# Copyright (C) 2018-2025 Intel Corporation# SPDX-License-Identifier: Apache-2.0-# flake8: noqa-# mypy: ignore-errors+from typing import Callable, Optional, Type, Union+import torch+class ModuleExtension:- def __init__(self, module, target_op, evaluate=None, convert=None, condition=None):- """- Creates an extension that replaces the entire PyTorch module with a single operation.- This functionality works with PyTorch models only. A module can be identified by- its type (e.g. torch.nn.Linear), module instance in the model, or module name.+ """An extension that replaces a PyTorch module with a single operation.++ A module can be identified by its type (e.g., `torch.nn.Linear`), module+ instance in the model, or module name.+ """++ def __init__(self,+ module: Union[str, torch.nn.Module, Type[torch.nn.Module]],+ target_op: str,+ evaluate: Optional[Callable] = None,+ convert: Optional[Callable] = None,+ condition: Optional[Callable] = None):+ """Create an extension that replaces a PyTorch module with a single op.++ This functionality works with PyTorch models only. A module can be+ identified by its type (e.g., `torch.nn.Linear`), module instance in+ the model, or module name.Args:- module (str, torch.nn.Module, type(torch.nn.Module)): PyTorch module to replace.+ module (str, torch.nn.Module, type(torch.nn.Module)): PyTorch+ module to replace.- target_op (str): A target operation that will be used as a replacer for the module.- It could be the name of the extension operation or an existing PyTorch- operation (with prim:: or aten:: prefix following TorchScript syntax).+ target_op (str): A target operation that will be used as a replacer+ for the module. It could be the name of the extension operation+ or an existing PyTorch operation (with `prim::` or `aten::`+ prefix following TorchScript syntax).- evaluate (callable with args module, *args, **kwargs): A callable that will replace a target- module in model execution it is responsible for producing valid output for- the module to allow correct model tracing. By default, it calls the original module- forward with the same arguments. The provided code will not be a part of the final- traced model; it is used only to produce valid results in the tracing.+ evaluate (callable): A function with the signature+ `evaluate(module, *args, **kwargs)`. It replaces the target+ module in model execution and is responsible for producing+ valid output for the module to allow correct model tracing. By+ default, it calls the original module's forward method with+ the same arguments. The provided code will not be part of the+ final traced model; it is used only to produce valid results+ during tracing.- convert (callable with args target_op, *args, **kwargs): A callable that will be traced and become- a part of the final model instead of the target module. It accepts target_op as- the first parameter, target_op is callable that will appear as a single node in the- graph, and the type of the node is target_op provided as another argument above.+ convert (callable): A function with the signature+ `convert(target_op, *args, **kwargs)`. It is traced and becomes+ part of the final model instead of the target module. It+ accepts `target_op` as the first parameter, which appears as a+ single node in the graph, with the type of the node being the+ `target_op` provided as another argument above.- condition (callable with args module): A callable that returns whether the extension applies- to the given module.+ condition (callable): A function with the signature+ `condition(module)`. It returns a boolean indicating whether+ the extension applies to the given module."""self.module = moduleself.target_op = target_opdiff --git a/src/bindings/python/src/openvino/frontend/pytorch/patch_model.py b/src/bindings/python/src/openvino/frontend/pytorch/patch_model.pyindex dda830599cd..6d8346e4f5c 100644--- a/src/bindings/python/src/openvino/frontend/pytorch/patch_model.py+++ b/src/bindings/python/src/openvino/frontend/pytorch/patch_model.py@@ -1,7 +1,7 @@+# -*- coding: utf-8 -*-# Copyright (C) 2018-2025 Intel Corporation# SPDX-License-Identifier: Apache-2.0-# flake8: noqa# mypy: ignore-errorsimport functools@@ -13,17 +13,17 @@ log = logging.getLogger(__name__)def patch_model(model, module_extensions, orig_forward_name):- def module_patcher(m, name):+ def module_patcher(module, name):extension = None- if m in module_extensions:- extension = module_extensions[m]- elif m.__class__ in module_extensions:- extension = module_extensions[m.__class__]+ if module in module_extensions:+ extension = module_extensions[module]+ elif module.__class__ in module_extensions:+ extension = module_extensions[module.__class__]elif name in module_extensions:extension = module_extensions[name]- if extension and extension.condition(m):- log.debug("Patching module %s", m)+ if extension and extension.condition(module):+ log.debug("Patching module %s", module)# The Trampoline class is instantiated for every module replacement, so we can use# class members individually for each module.@@ -36,24 +36,24 @@ def patch_model(model, module_extensions, orig_forward_name):def forward(ctx, *args, **kwargs):# Temporarily restore the original forward function of `module` to avoid# recursion issues in `evaluate`, then revert it back.- patched_forward = m.forward+ patched_forward = module.forward# set original forward for the module- m.forward = getattr(m, orig_forward_name)+ module.forward = getattr(module, orig_forward_name)# call user code- results = extension.evaluate(m, *args, **kwargs)- m.forward = patched_forward # return patched forward back+ results = extension.evaluate(module, *args, **kwargs)+ module.forward = patched_forward # return patched forward backreturn resultsdef new_forward(*args, **kwargs):- return extension.convert(m, Trampoline.apply, *args, **kwargs)+ return extension.convert(module, Trampoline.apply, *args, **kwargs)# make signature of new_forward same as of forward- new_forward = functools.wraps(m.forward)(new_forward)- setattr(m, orig_forward_name, m.forward)- m.forward = new_forward+ new_forward = functools.wraps(module.forward)(new_forward)+ setattr(module, orig_forward_name, module.forward)+ module.forward = new_forward- for name, m in model.named_modules():- if hasattr(m, orig_forward_name):+ for name, module in model.named_modules():+ if hasattr(module, orig_forward_name):# already patched, skipping. It may happen when patching applied for same module twicelog.debug("Unexpectedly found already patched module %s while applying ""ModuleExtension during PyTorch model conversion. "@@ -61,15 +61,15 @@ def patch_model(model, module_extensions, orig_forward_name):"it may lead to broken original model.", name)continue- module_patcher(m, name)+ module_patcher(module, name)def unpatch_model(model, orig_forward_name):- for _, m in model.named_modules():- if hasattr(m, orig_forward_name):+ for _, module in model.named_modules():+ if hasattr(module, orig_forward_name):try:- m.forward = getattr(m, orig_forward_name)- delattr(m, orig_forward_name)+ module.forward = getattr(module, orig_forward_name)+ delattr(module, orig_forward_name)except Exception as error:log.warning("Exception raised during model unpatching. ""Depending on the exact issue it may lead to broken original model.\n"@@ -79,10 +79,10 @@ def unpatch_model(model, orig_forward_name):def __make_16bit_traceable(model: torch.nn.Module,orig_forward_name: str = "_openvino_module_extension_patch_orig_forward",patch_condition=None):- """- Prepare a 16-bit PyTorch model for tracing with OpenVINO.- - Replace known list of modules with ModuleExtension.- - Convert other modules with weights to FP32.+ """Prepare a 16-bit PyTorch model for tracing with OpenVINO.++ - Replace known list of modules with ModuleExtension.+ - Convert other modules with weights to FP32."""supported = {torch.float16, torch.bfloat16, torch.float8_e4m3fn, torch.float8_e5m2}if patch_condition is None:@@ -93,7 +93,7 @@ def __make_16bit_traceable(model: torch.nn.Module,def fp32_tensor(*shape):return torch.full(shape, 0.5, dtype=torch.float32)-+extensions = {torch.nn.Linear: ModuleExtension(torch.nn.Linear, "ov_ext::linear",@@ -125,8 +125,8 @@ def __make_16bit_traceable(model: torch.nn.Module,passpatch_model(model, extensions, orig_forward_name)for _, module in model.named_modules():- if (module.__class__ not in extensions and- (any(p.dtype in supported for p in module.parameters(False))- or any(b.dtype in supported for b in module.buffers(False)))):+ if (module.__class__ not in extensions+ and (any(p.dtype in supported for p in module.parameters(False))+ or any(b.dtype in supported for b in module.buffers(False)))):log.debug("Casting module %s to float32", module)module.float()diff --git a/src/bindings/python/src/openvino/frontend/pytorch/torchdynamo/backend_utils.py b/src/bindings/python/src/openvino/frontend/pytorch/torchdynamo/backend_utils.pyindex 089c71a4eb5..115e2b9a6a9 100644--- a/src/bindings/python/src/openvino/frontend/pytorch/torchdynamo/backend_utils.py+++ b/src/bindings/python/src/openvino/frontend/pytorch/torchdynamo/backend_utils.py@@ -1,7 +1,7 @@+# -*- coding: utf-8 -*-# Copyright (C) 2018-2025 Intel Corporation# SPDX-License-Identifier: Apache-2.0-# flake8: noqa# mypy: ignore-errorsfrom typing import Optional, Any@@ -25,6 +25,7 @@ def _get_device(options) -> Optional[Any]:device = "CPU"return device+def _is_cache_dir_in_config(options) -> Optional[Any]:if options is not None and "config" in options:cfg = options["config"]@@ -64,22 +65,24 @@ def _get_config(options) -> Optional[Any]:return options["config"]return {}+def _get_decompositions(options) -> Optional[Any]:decompositions = []if options is not None and "decompositions" in options:decompositions = options["decompositions"]return decompositions+def _get_disabled_ops(options) -> Optional[Any]:disabled_ops = []if options is not None and "disabled_ops" in options:disabled_ops = options["disabled_ops"]return disabled_ops+def _is_testing(options) -> Optional[Any]:if options is not None and "testing" in options:is_testing = options["testing"]if bool(is_testing) and str(is_testing).lower not in ["false", "0"]:return Truereturn False-diff --git a/src/bindings/python/src/openvino/frontend/pytorch/torchdynamo/compile.py b/src/bindings/python/src/openvino/frontend/pytorch/torchdynamo/compile.pyindex 71d96da38f0..72446ff6685 100644--- a/src/bindings/python/src/openvino/frontend/pytorch/torchdynamo/compile.py+++ b/src/bindings/python/src/openvino/frontend/pytorch/torchdynamo/compile.py@@ -2,14 +2,14 @@# Copyright (C) 2018-2025 Intel Corporation# SPDX-License-Identifier: Apache-2.0-# flake8: noqa# mypy: ignore-errorsimport os+import logging+from hashlib import sha256+import torchimport torch.overrides--from hashlib import sha256from torch.fx import GraphModulefrom openvino.frontend import FrontEndManager@@ -17,13 +17,11 @@ from openvino.frontend.pytorch.fx_decoder import TorchFXPythonDecoderfrom openvino import Core, Type, PartialShape, serializefrom openvino.frontend.pytorch.torchdynamo.backend_utils import _get_cache_dir, _get_device, _get_config, _is_cache_dir_in_config-from typing import Callable, Optional--import logginglogger = logging.getLogger(__name__)logger.setLevel(logging.WARNING)-def cached_model_name(model_hash_str, device, args, cache_root, reversed = False):++def cached_model_name(model_hash_str, device, args, cache_root, reversed=False): # noqa: VNE003if model_hash_str is None:return None@@ -33,20 +31,22 @@ def cached_model_name(model_hash_str, device, args, cache_root, reversed = Falseos.makedirs(model_cache_dir, exist_ok=True)file_name = model_cache_dir + model_hash_str + "_" + deviceexcept OSError as error:- logger.warning(f"Cache directory {cache_root} cannot be created. Model caching is disabled. Error: {error }")+ logger.warning("Cache directory %s cannot be created. Model caching is disabled. Error: %s", cache_root, error)return Noneinputs_str = ""- for idx, input_data in enumerate(args):+ for input_data in args:+ arg_str = str(input_data.type()) + str(input_data.size())[11:-1].replace(" ", "")if reversed:- inputs_str = "_" + str(input_data.type()) + str(input_data.size())[11:-1].replace(" ", "") + inputs_str+ inputs_str = "_" + arg_str + inputs_strelse:- inputs_str += "_" + str(input_data.type()) + str(input_data.size())[11:-1].replace(" ", "")- inputs_str = sha256(inputs_str.encode('utf-8')).hexdigest()+ inputs_str += "_" + arg_str+ inputs_str = sha256(inputs_str.encode("utf-8")).hexdigest()file_name += inputs_strreturn file_name+def openvino_compile_cached_model(cached_model_path, options, *example_inputs):core = Core()om = core.read_model(cached_model_path + ".xml")@@ -78,6 +78,7 @@ def openvino_compile_cached_model(cached_model_path, options, *example_inputs):return compiled_model+def openvino_compile(gm: GraphModule, *args, model_hash_str: str = None, options=None):core = Core()@@ -93,7 +94,7 @@ def openvino_compile(gm: GraphModule, *args, model_hash_str: str = None, optionsinput_shapes = []input_types = []- for idx, input_data in enumerate(args):+ for input_data in args:if isinstance(input_data, int):input_types.append(torch.int64)input_shapes.append(torch.Size([1]))diff --git a/src/bindings/python/src/openvino/frontend/pytorch/torchdynamo/decompositions.py b/src/bindings/python/src/openvino/frontend/pytorch/torchdynamo/decompositions.pyindex 3fae1d72f6b..8117960252f 100644--- a/src/bindings/python/src/openvino/frontend/pytorch/torchdynamo/decompositions.py+++ b/src/bindings/python/src/openvino/frontend/pytorch/torchdynamo/decompositions.py@@ -2,7 +2,6 @@# Copyright (C) 2018-2025 Intel Corporation# SPDX-License-Identifier: Apache-2.0-# flake8: noqa# mypy: ignore-errorsimport torchdiff --git a/src/bindings/python/src/openvino/frontend/pytorch/torchdynamo/op_support.py b/src/bindings/python/src/openvino/frontend/pytorch/torchdynamo/op_support.pyindex da36e091ee2..10801cbe9c8 100644--- a/src/bindings/python/src/openvino/frontend/pytorch/torchdynamo/op_support.py+++ b/src/bindings/python/src/openvino/frontend/pytorch/torchdynamo/op_support.py@@ -1,30 +1,26 @@+# -*- coding: utf-8 -*-# Copyright (C) 2018-2025 Intel Corporation# SPDX-License-Identifier: Apache-2.0-# flake8: noqa# mypy: ignore-errors-from typing import Dict+import typing as t+import logging-import torchfrom torch.nn import Modulefrom torch._ops import OpOverloadfrom torch.fx.node import Node, _get_qualified_name-from torch.fx.passes.operator_support import OperatorSupport+from torch.fx.passes.operator_support import OperatorSupport as OpSupportfrom torch.fx.passes.tools_common import CALLABLE_NODE_OPSfrom openvino.frontend.pytorch.torchdynamo.backend_utils import _get_disabled_ops-import typing as t-import logging-logger = logging.getLogger(__name__)logger.setLevel(logging.WARNING)-class OperatorSupport(OperatorSupport):- """- Operator support for OpenVINO backend.- """++class OperatorSupport(OpSupport):+ """Operator support for OpenVINO backend."""def __init__(self, options):support_dict = {@@ -78,7 +74,6 @@ class OperatorSupport(OperatorSupport):"torch.ops.aten.as_strided_copy.default": None,"torch.ops.aten.asin.default": None,"torch.ops.aten.asinh.default": None,- "torch.ops.aten.asinh.default": None,"torch.ops.aten.atanh.default": None,"torch.ops.aten.avg_pool2d.default": None,"torch.ops.aten.avg_pool3d.default": None,@@ -127,7 +122,6 @@ class OperatorSupport(OperatorSupport):"torch.ops.aten.fill_.Tensor": None,"torch.ops.aten.flip.default": None,"torch.ops.aten.floor.default": None,- "torch.ops.aten.floor.default": None,"torch.ops.aten.fmod.Scalar": None,"torch.ops.aten.fmod.Tensor": None,"torch.ops.aten.full.default": None,@@ -268,9 +262,8 @@ class OperatorSupport(OperatorSupport):"torch.ops.quantized_decomposed.quantize_per_channel.default": None,"torch.ops.quantized_decomposed.dequantize_per_tensor.default": None,"torch.ops.quantized_decomposed.dequantize_per_channel.default": None-}-+self.enabled_op_names = []for op in _get_disabled_ops(options):diff --git a/src/bindings/python/src/openvino/frontend/pytorch/torchdynamo/partition.py b/src/bindings/python/src/openvino/frontend/pytorch/torchdynamo/partition.pyindex 052eb37e231..9c18a017227 100644--- a/src/bindings/python/src/openvino/frontend/pytorch/torchdynamo/partition.py+++ b/src/bindings/python/src/openvino/frontend/pytorch/torchdynamo/partition.py@@ -89,22 +89,22 @@ class Partitioner:const_0_node = PatternNodeconst_0_node.op_types["get_attr"] = Noneunsqueeze_0_node = PatternNode- unsqueeze_0_node.op_types["call_function:aten.unsqueeze.default"] = [const_0_node,]+ unsqueeze_0_node.op_types["call_function:aten.unsqueeze.default"] = [const_0_node]expand_node = PatternNode- expand_node.op_types["call_function:aten.expand.default"] = [unsqueeze_0_node,]+ expand_node.op_types["call_function:aten.expand.default"] = [unsqueeze_0_node]const_1_node = PatternNodeconst_1_node.op_types["get_attr"] = Noneunsqueeze_1_node = PatternNode- unsqueeze_1_node.op_types["call_function:aten.unsqueeze.default"] = [const_1_node,]+ unsqueeze_1_node.op_types["call_function:aten.unsqueeze.default"] = [const_1_node]bitwise_right_shift_node = PatternNodebitwise_right_shift_node.op_types["call_function:aten.bitwise_right_shift.Tensor"] = [expand_node, unsqueeze_1_node]to_copy_node = PatternNode- to_copy_node.op_types["call_function:aten._to_copy.default"] = [bitwise_right_shift_node,]+ to_copy_node.op_types["call_function:aten._to_copy.default"] = [bitwise_right_shift_node]add_or_to_copy_node = PatternNode- add_or_to_copy_node.op_types["call_function:aten._to_copy.default"] = [bitwise_right_shift_node,]- add_or_to_copy_node.op_types["call_function:aten.add.Tensor"] = [to_copy_node,]+ add_or_to_copy_node.op_types["call_function:aten._to_copy.default"] = [bitwise_right_shift_node]+ add_or_to_copy_node.op_types["call_function:aten.add.Tensor"] = [to_copy_node]bitwise_and_node = PatternNode- bitwise_and_node.op_types["call_function:aten.bitwise_and.Scalar"] = [add_or_to_copy_node,]+ bitwise_and_node.op_types["call_function:aten.bitwise_and.Scalar"] = [add_or_to_copy_node]for node in graph_module.graph.nodes:if str(node.op) == "call_function" and str(node.target) == "aten.bitwise_and.Scalar":@@ -120,7 +120,7 @@ class Partitioner:bitwise_right_shift_node = PatternNodebitwise_right_shift_node.op_types["call_function:aten.bitwise_right_shift.Tensor_Scalar"] = [const_node]bitwise_and_node = PatternNode- bitwise_and_node.op_types["call_function:aten.bitwise_and.Scalar"] = [const_node,]+ bitwise_and_node.op_types["call_function:aten.bitwise_and.Scalar"] = [const_node]stack_node = PatternNodestack_node.op_types["call_function:aten.stack.default"] = [bitwise_and_node, bitwise_right_shift_node]diff --git a/src/bindings/python/src/openvino/frontend/pytorch/ts_decoder.py b/src/bindings/python/src/openvino/frontend/pytorch/ts_decoder.pyindex 066dc7c50dc..e1b8ee9f29f 100644--- a/src/bindings/python/src/openvino/frontend/pytorch/ts_decoder.py+++ b/src/bindings/python/src/openvino/frontend/pytorch/ts_decoder.py@@ -200,9 +200,6 @@ class TorchScriptPythonDecoder(Decoder):def inputs(self) -> list:return [x.unique() for x in self.raw_inputs]- def get_input(self, index: int):- return self.inputs()[index]-def get_input_debug_name(self, index: int) -> str:return self._raw_input(index).debugName()diff --git a/src/bindings/python/src/openvino/frontend/pytorch/utils.py b/src/bindings/python/src/openvino/frontend/pytorch/utils.pyindex 2cc5cdc16c1..4390c600e19 100644--- a/src/bindings/python/src/openvino/frontend/pytorch/utils.py+++ b/src/bindings/python/src/openvino/frontend/pytorch/utils.py@@ -1,7 +1,7 @@+# -*- coding: utf-8 -*-# Copyright (C) 2018-2025 Intel Corporation# SPDX-License-Identifier: Apache-2.0-# flake8: noqa# mypy: ignore-errorsimport inspect@@ -21,13 +21,13 @@ def make_constant(*args, **kwargs):def fetch_attr(self_module, target: str):- """- Fetch an attribute from the ``Module`` hierarchy of ``self.module``.+ """Fetch an attribute from the `Module` hierarchy of `self.module`.Args:+ self_module (torch.nn.Module): The module to fetch the attribute fromtarget (str): The fully-qualified name of the attribute to fetch- Return:+ Returns:Any: The value of the attribute."""target_atoms = target.split(".")@@ -65,7 +65,7 @@ def torch_tensor_to_ov_const(torch_t: torch.Tensor, shared_memory=True):raise AssertionError("`FakeTensor` detected. Infer the ""model before exporting to avoid this.")except ImportError:- pass+ log.debug("Failed to import FakeTensor")dtype = torch_t.dtypetorch_t = torch_t.contiguous()@@ -134,11 +134,11 @@ def get_value_from_getattr(getattr_node, self_module):def graph_has_ops(graph, op_types: list) -> bool:res = False- for n in graph.nodes():- if any(kind in n.kind() for kind in op_types):+ for node in graph.nodes():+ if any(kind in node.kind() for kind in op_types):return True- for b in n.blocks():- res = graph_has_ops(b, op_types)+ for block in node.blocks():+ res = graph_has_ops(block, op_types)if res:return resreturn res@@ -197,9 +197,7 @@ class ModelWrapper(torch.nn.Module):def build_wrapper(template, model):- """- Builds a wrapper around the given model using the provided template.- """+ """Builds a wrapper around the given model using the provided template."""result = {}try:exec(template, result)@@ -222,7 +220,7 @@ def process_dict_inputs(inputs, input_params, model):input_signature = list(input_params)if ordered_inputs == input_signature[: len(ordered_inputs)]:example_inputs = [inputs[input_name] for input_name in ordered_inputs]- if all([isinstance(inp, torch.Tensor) for inp in example_inputs]):+ if all(isinstance(inp, torch.Tensor) for inp in example_inputs):return {"example_inputs": [inputs[name] for name in ordered_inputs]}, ordered_inputs, modelreturn {"example_inputs": example_inputs}, ordered_inputs, model@@ -308,48 +306,51 @@ def convert_quantized_tensor(qtensor: torch.Tensor, shared_memory: bool):convert = ops.convert(int8_const, np.float32)sub = ops.subtract(convert, zero_point)return ops.multiply(sub, scale).outputs()- assert False, "Unsupported qscheme"+ raise AssertionError(f"Unsupported qscheme: {qscheme}")-def process_individual_input(x, x_name):- """- Processes an individual input and generates a signature,- parameter string, example entry, and a wrap flag.+def process_individual_input(arg, arg_name):+ """Generate signature, param string, example, and wrap flag from input.++ Args:+ arg: The input value to process.+ arg_name: The name of the input.++ Returns:+ Tuple: (signature, param string, example entry, wrap flag)."""sign = Noneparam = Noneexample_entry = Noneto_wrap = False- if isinstance(x, tuple):+ if isinstance(arg, tuple):internal_input = []new_tuple = []index = 0- for v in x:- if v is None:+ for value in arg:+ if value is None:to_wrap = Trueinternal_input.append("None")else:- internal_input.append(f"{x_name}[{index}]")- new_tuple.append(v)+ internal_input.append(f"{arg_name}[{index}]")+ new_tuple.append(value)index += 1param = f"({', '.join(internal_input)},)"if len(new_tuple) > 0:example_entry = tuple(new_tuple)- sign = x_name- elif x is None:+ sign = arg_name+ elif arg is None:to_wrap = Trueparam = "None"else:- sign = x_name- param = x_name- example_entry = x+ sign = arg_name+ param = arg_name+ example_entry = argreturn sign, param, example_entry, to_wrapdef patch_none_example(model: torch.nn.Module, example):- """- Patches a PyTorch model to handle None values in the input example.- """+ """Patch a PyTorch model to handle None values in the input example."""callable_func = getattr(model, "forward", model.__call__)input_params = inspect.signature(callable_func).parametersinput_signature = list(input_params)@@ -358,9 +359,9 @@ def patch_none_example(model: torch.nn.Module, example):to_wrap = Falseif isinstance(example, tuple) and len(input_signature) >= len(example):new_example = []- for i, x in enumerate(example):- x_name = input_signature[i]- sign, param, example_entry, _to_wrap = process_individual_input(x, x_name)+ for i, arg in enumerate(example):+ arg_name = input_signature[i]+ sign, param, example_entry, _to_wrap = process_individual_input(arg, arg_name)to_wrap = to_wrap or _to_wrapif sign is not None:input_sign_str.append(str(input_params[sign]))@@ -377,15 +378,15 @@ def patch_none_example(model: torch.nn.Module, example):elif isinstance(example, dict) and len(input_signature) >= len(example):new_example = {}input_signature = [s for s in input_signature if s in example]- for x_name in input_signature:- x = example[x_name]- sign, param, example_entry, _to_wrap = process_individual_input(x, x_name)+ for arg_name in input_signature:+ arg = example[arg_name]+ sign, param, example_entry, _to_wrap = process_individual_input(arg, arg_name)to_wrap = to_wrap or _to_wrapif sign is not None:input_sign_str.append(str(input_params[sign]))- input_params_str.append(f"{x_name}={param}")+ input_params_str.append(f"{arg_name}={param}")if example_entry is not None:- new_example[x_name] = example_entry+ new_example[arg_name] = example_entryif to_wrap:wrapper_class = wrapper_template.format(input_sign=", ".join(input_sign_str),example_input=", ".join(input_params_str))