OpenVINO™ is an open source toolkit for optimizing and deploying AI inference
C++ aicomputer-visiondeep-learningdeploy-aidiffusion-modelsgenerative-aigood-first-issueinferencellm-inferencenatural-language-processingnlpopenvinooptimize-aiperformance-boostrecommendation-systemspeech-recognitionstable-diffusiontransformersyolo
[PT FE] Code cleanup and coverity fixes (#25888)
Maxim Vafin595ce79dab15
diff --git a/src/bindings/python/src/openvino/frontend/pytorch/ts_decoder.py b/src/bindings/python/src/openvino/frontend/pytorch/ts_decoder.pyindex 1853842a8ee..8e840d111a3 100644--- a/src/bindings/python/src/openvino/frontend/pytorch/ts_decoder.py+++ b/src/bindings/python/src/openvino/frontend/pytorch/ts_decoder.py@@ -7,7 +7,14 @@from openvino.frontend.pytorch.py_pytorch_frontend import _FrontEndPytorchDecoder as Decoderfrom openvino.frontend.pytorch.py_pytorch_frontend import _Type as DecoderTypefrom openvino.runtime import op, PartialShape, Type as OVType, OVAny-from openvino.frontend.pytorch.utils import ivalue_to_constant, get_value_from_getattr, pt_to_ov_type_map, prepare_example_inputs_and_model, convert_quantized_tensor, graph_has_ops+from openvino.frontend.pytorch.utils import (+ ivalue_to_constant,+ get_value_from_getattr,+ pt_to_ov_type_map,+ prepare_example_inputs_and_model,+ convert_quantized_tensor,+ graph_has_ops,+)from openvino.runtime import opset11 as opsfrom openvino.frontend.pytorch import gptqfrom openvino.frontend.pytorch import patch_model@@ -15,20 +22,22 @@ from openvino.frontend.pytorch.module_extension import ModuleExtensionimport typingimport torch+import inspect-class TorchScriptPythonDecoder (Decoder):+class TorchScriptPythonDecoder(Decoder):def __init__(- self,- pt_module,- graph_element=None,- example_input=None,- alias_db=None,- shared_memory=True,- skip_freeze=False,- constant_cache=None,- module_extensions=None):- Decoder.__init__(self)+ self,+ pt_module,+ graph_element=None,+ example_input=None,+ alias_db=None,+ shared_memory=True,+ skip_freeze=False,+ constant_cache=None,+ module_extensions=None,+ ):+ super().__init__()# We store every decoder created by this decoder so that all them are not deleted until the first decoder is deletedself.m_decoders = []self._input_signature = None@@ -37,9 +46,11 @@ class TorchScriptPythonDecoder (Decoder):self.constant_cache = constant_cache if constant_cache is not None else dict()self.module_extensions = module_extensionsself.config = None- if hasattr(pt_module, "config"):- self.config = pt_module.config.to_dict() if not isinstance(pt_module.config, dict) else pt_module.config+ self.out_debug_name_overwrites = {}if graph_element is None:+ if hasattr(pt_module, "config"):+ self.config = pt_module.config.to_dict() if not isinstance(+ pt_module.config, dict) else pt_module.configtry:pt_module = self._get_scripted_model(pt_module, example_input, skip_freeze)@@ -56,7 +67,8 @@ class TorchScriptPythonDecoder (Decoder):f"Couldn't get TorchScript module by {msg}. With exception:\n{e}\n{help_msg} ""You can also provide TorchScript module that you obtained"" yourself, please refer to PyTorch documentation: "- "https://pytorch.org/tutorials/beginner/Intro_to_TorchScript_tutorial.html.")+ "https://pytorch.org/tutorials/beginner/Intro_to_TorchScript_tutorial.html."+ )self.graph_element = pt_module.inlined_graphself.alias_db = self.graph_element.alias_db()else:@@ -80,27 +92,27 @@ class TorchScriptPythonDecoder (Decoder):self._transform_tensor_list_constants_to_listconstruct(self.graph_element)self._transform_optional_constants(self.graph_element)- self.out_debug_name_overwrites = {}@staticmethoddef _get_preserved_attributes(model) -> list:preserved_attributes = []for name, module in model.named_modules():- if hasattr(module, "weight"):- if module.weight is not None and getattr(module.weight, "dtype", None) in [torch.int8, torch.uint8, torch.float16, torch.bfloat16]:- preserved_attributes.append(name)+ compressed_types = [torch.int8, torch.uint8,+ torch.float16, torch.bfloat16]+ if hasattr(module, "weight") and getattr(module.weight, "dtype", None) in compressed_types:+ preserved_attributes.append(name)return preserved_attributesdef _get_scripted_model(self, pt_module, example_inputs=None, skip_freeze=False):- import torch- import inspect-freeze_by_default = Falseif isinstance(pt_module, torch.nn.Module):pt_module.eval()input_signature = Noneinput_parameters = None- if isinstance(pt_module, torch.nn.Module) and not isinstance(pt_module, (torch.jit._trace.TopLevelTracedModule, torch.jit._script.RecursiveScriptModule)):+ if isinstance(pt_module, torch.nn.Module) and not isinstance(+ pt_module, (torch.jit._trace.TopLevelTracedModule,+ torch.jit._script.RecursiveScriptModule)+ ):# input params is dictionary contains input names and their signature values (type hints and default values if any)input_params = inspect.signature(pt_module.forward if hasattr(pt_module, "forward") else pt_module.__call__).parameters@@ -108,7 +120,8 @@ class TorchScriptPythonDecoder (Decoder):if example_inputs is None:if self.module_extensions:- raise RuntimeError("ModuleExtension is not supported for scripting. Please provide valid example_input argument to run tracing.")+ raise RuntimeError(+ "ModuleExtension is not supported for scripting. Please provide valid example_input argument to run tracing.")scripted = torch.jit.script(pt_module)freeze_by_default = Trueelse:@@ -116,9 +129,10 @@ class TorchScriptPythonDecoder (Decoder):example_inputs, input_params, pt_module)# name of attribute in a patched module where the original forward method is kept- orig_forward_name = '_openvino_module_extension_patch_orig_forward'+ orig_forward_name = "_openvino_module_extension_patch_orig_forward"if self.module_extensions:- patch_model.patch_model(pt_module, self.module_extensions, orig_forward_name)+ patch_model.patch_model(+ pt_module, self.module_extensions, orig_forward_name)gptq_patched = Falseif gptq.detect_gptq_model(pt_module):@@ -127,9 +141,9 @@ class TorchScriptPythonDecoder (Decoder):gptq_patched = Trueexcept Exception as error:print(- '[ WARNING ] Failed patching of AutoGPTQ model. Error message:\n', error)+ "[ WARNING ] Failed patching of AutoGPTQ model. Error message:\n", error)print(- '[ WARNING ] Tracing of the model will likely be unsuccessful or incorrect')+ "[ WARNING ] Tracing of the model will likely be unsuccessful or incorrect")gptq.unpatch_model(pt_module)gptq_patched = False@@ -142,10 +156,13 @@ class TorchScriptPythonDecoder (Decoder):if self.module_extensions:patch_model.unpatch_model(pt_module, orig_forward_name)- if not freeze_by_default and graph_has_ops(scripted.inlined_graph, ["prim::Uninitialized", "prim::unchecked_cast", "aten::append"]):+ have_to_freeze_ops = ["prim::Uninitialized",+ "prim::unchecked_cast", "aten::append"]+ if not freeze_by_default and graph_has_ops(scripted.inlined_graph, have_to_freeze_ops):# freeze models with unsupported opsfreeze_by_default = True- if freeze_by_default and graph_has_ops(scripted.inlined_graph, ["quantized", "aten::as_strided"]):+ quantized_hint_ops = ["quantized", "aten::as_strided"]+ if freeze_by_default and graph_has_ops(scripted.inlined_graph, quantized_hint_ops):# do not freeze quantized models and can't freeze for aten::as_strided it will result in incorrect inferencefreeze_by_default = Falseif freeze_by_default and not skip_freeze:@@ -256,12 +273,14 @@ class TorchScriptPythonDecoder (Decoder):def visit_subgraph(self, node_visitor) -> None:# make sure topological order is satisfiedfor node in self.graph_element.nodes():- decoder = TorchScriptPythonDecoder(self.pt_module,- node,- alias_db=self.alias_db,- shared_memory=self._shared_memory,- constant_cache=self.constant_cache,- module_extensions=self.module_extensions)+ decoder = TorchScriptPythonDecoder(+ self.pt_module,+ node,+ alias_db=self.alias_db,+ shared_memory=self._shared_memory,+ constant_cache=self.constant_cache,+ module_extensions=self.module_extensions,+ )self.m_decoders.append(decoder)node_visitor(decoder)@@ -281,31 +300,32 @@ class TorchScriptPythonDecoder (Decoder):return list(self.graph_element.blocks())def get_subgraph_decoder(self, index: int):- decoder = TorchScriptPythonDecoder(self.pt_module,- self.get_subgraphs()[index],- alias_db=self.alias_db,- shared_memory=self._shared_memory,- module_extensions=self.module_extensions)+ decoder = TorchScriptPythonDecoder(+ self.pt_module, self.get_subgraphs(+ )[index], alias_db=self.alias_db, shared_memory=self._shared_memory, module_extensions=self.module_extensions+ )self.m_decoders.append(decoder)return decoderdef get_op_type(self) -> str:assert isinstance(self.graph_element, torch.Node), "Function can be called only when self.graph_element is of type torch.Node"- if self.graph_element.kind() == "prim::PythonOp":- if hasattr(self.graph_element, 'pyobj') and callable(self.graph_element.pyobj) and hasattr(self.graph_element.pyobj(), '__self__'):- trampoline = self.graph_element.pyobj().__self__- if hasattr(trampoline, 'target_extension') and isinstance(trampoline.target_extension, ModuleExtension):- target_op = trampoline.target_extension.target_op- if callable(target_op):- target = target_op(trampoline.original_module)- elif isinstance(target_op, str):- target = target_op- # TODO: Support target as a callable that will play a role of ConversionExtension for an entire module instead of a single op.- # Without supporting target as a callable here, ConversionExtension functionality is still possible to implement- # by combining two extensions: ModuleExtension that use temporary name as a target op and another extension of type ConversionExtension- # that translates that particular temporary name to custom graph. But providing conversion code as a callable `target` is more convenient.- return target+ if self.graph_element.kind() == "prim::PythonOp" and callable(getattr(self.graph_element, "pyobj", None)):+ pyobj = self.graph_element.pyobj()+ trampoline = getattr(pyobj, "__self__", None)+ target_extension = getattr(trampoline, "target_extension", None)++ if isinstance(target_extension, ModuleExtension):+ target_op = target_extension.target_op+ if callable(target_op):+ target = target_op(trampoline.original_module)+ elif isinstance(target_op, str):+ target = target_op+ # TODO: Support target as a callable that will play a role of ConversionExtension for an entire module instead of a single op.+ # Without supporting target as a callable here, ConversionExtension functionality is still possible to implement+ # by combining two extensions: ModuleExtension that use temporary name as a target op and another extension of type ConversionExtension+ # that translates that particular temporary name to custom graph. But providing conversion code as a callable `target` is more convenient.+ return targetreturn self.graph_element.kind()def get_schema(self) -> str:@@ -345,8 +365,8 @@ class TorchScriptPythonDecoder (Decoder):self.constant_cache[name] = outputsdef try_decode_get_attr(self):- pt_value, name = get_value_from_getattr(self.graph_element,- self.pt_module)+ pt_value, name = get_value_from_getattr(+ self.graph_element, self.pt_module)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 or __torch__.torch.classes.quantized.LinearPackedParamsBase@@ -392,8 +412,8 @@ class TorchScriptPythonDecoder (Decoder):if name in self.constant_cache:const = self.constant_cache[name]else:- const = ivalue_to_constant(pt_value,- shared_memory=self._shared_memory)+ const = ivalue_to_constant(+ pt_value, shared_memory=self._shared_memory)self._add_name_to_const_and_cache(const, name)return constelse:@@ -407,12 +427,11 @@ class TorchScriptPythonDecoder (Decoder):pt_value = self._raw_output(0)pt_type = pt_value.type()if isinstance(pt_type, torch.TensorType):- return ivalue_to_constant(pt_value.toIValue(),- shared_memory=self._shared_memory)+ return ivalue_to_constant(pt_value.toIValue(), shared_memory=self._shared_memory)if isinstance(pt_type, torch.ListType):return self._as_constant_list(pt_value)- const = ivalue_to_constant(pt_value.toIValue(),- shared_memory=self._shared_memory)+ const = ivalue_to_constant(+ pt_value.toIValue(), shared_memory=self._shared_memory)if len(const) > 0:# set name corresponding to state_dict nameconst[0].get_node().set_friendly_name(@@ -466,8 +485,8 @@ 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, _ = get_value_from_getattr(+ in_node, self.pt_module)return pt_value is Nonereturn False@@ -496,7 +515,8 @@ class TorchScriptPythonDecoder (Decoder):def get_rt_info(self):rt_info = {}if self.config is not None and "quantization_config" in self.config and "sym" in self.config["quantization_config"]:- rt_info["symmetric_quantization"] = OVAny(self.config["quantization_config"]["sym"])+ rt_info["symmetric_quantization"] = OVAny(+ self.config["quantization_config"]["sym"])return rt_info@staticmethoddiff --git a/src/bindings/python/src/openvino/frontend/pytorch/utils.py b/src/bindings/python/src/openvino/frontend/pytorch/utils.pyindex 4b94503adb5..06a58eb80ff 100644--- a/src/bindings/python/src/openvino/frontend/pytorch/utils.py+++ b/src/bindings/python/src/openvino/frontend/pytorch/utils.py@@ -25,7 +25,7 @@ def fetch_attr(self_module, target: str):Return:Any: The value of the attribute."""- target_atoms = target.split('.')+ target_atoms = target.split(".")attr_itr = self_modulefor i, atom in enumerate(target_atoms):if not hasattr(attr_itr, atom):@@ -91,12 +91,13 @@ def get_value_from_getattr(getattr_node, self_module):node = stack.pop()attr_name = node.s("name")assert hasattr(- module, attr_name), f"No attribute with name \"{attr_name}\" found in module."+ module, attr_name), f'No attribute with name "{attr_name}" found in module.'path_name = ".".join([path_name, attr_name])module = getattr(module, attr_name)return module, path_name-def graph_has_ops(graph, op_types:list) -> bool:++def graph_has_ops(graph, op_types: list) -> bool:res = Falsefor n in graph.nodes():if any(kind in n.kind() for kind in op_types):@@ -106,7 +107,7 @@ def graph_has_ops(graph, op_types:list) -> bool:if res:return resreturn res-+pt_to_ov_type_map = {"float": OVType.f32,@@ -134,7 +135,7 @@ pt_to_ov_type_map = {"torch.BoolTensor": OVType.boolean,"torch.quint8": OVType.u8,"torch.qint8": OVType.i8,- "torch.qint32": OVType.i32+ "torch.qint32": OVType.i32,}@@ -159,7 +160,7 @@ def process_dict_inputs(inputs, input_params, model):ordered_inputs.append(input_name)input_signature = list(input_params)- if ordered_inputs == input_signature[:len(ordered_inputs)]:+ 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]):return {"example_inputs": [inputs[name] for name in ordered_inputs]}, ordered_inputs, model@@ -191,8 +192,8 @@ def process_dict_inputs(inputs, input_params, model):str(input_params[input_name]).replace("NoneType", "None"))input_params_str.append(f"{input_name}={input_name}")- wrapper_class = wrapper_template.format(input_sign=', '.join(- input_sign_str), example_input=', '.join(input_params_str))+ wrapper_class = wrapper_template.format(input_sign=", ".join(+ input_sign_str), example_input=", ".join(input_params_str))result = {}try:exec(wrapper_class, result)@@ -210,7 +211,8 @@ def prepare_example_inputs_and_model(inputs, input_params, model):input_is_list = Falseinput_signature = list(input_params)if isinstance(inputs, dict):- examples, ordered, wrapped = process_dict_inputs(inputs, input_params, model)+ examples, ordered, wrapped = process_dict_inputs(+ inputs, input_params, model)return examples, ordered, wrapped, input_is_listif isinstance(inputs, list) and len(inputs) == 1 and isinstance(inputs[0], torch.Tensor):if "typing.List" in str(input_params[input_signature[0]].annotation):@@ -219,7 +221,7 @@ def prepare_example_inputs_and_model(inputs, input_params, model):if isinstance(inputs, torch.Tensor):inputs = [inputs]- input_signature = input_signature[:len(inputs)]+ input_signature = input_signature[: len(inputs)]return {"example_inputs": inputs}, input_signature, model, input_is_listdiff --git a/src/common/transformations/src/transformations/fp16_compression/mark_decompression_convert_constant_folding.cpp b/src/common/transformations/src/transformations/fp16_compression/mark_decompression_convert_constant_folding.cppindex 136ee34877c..7724692be61 100644--- a/src/common/transformations/src/transformations/fp16_compression/mark_decompression_convert_constant_folding.cpp+++ b/src/common/transformations/src/transformations/fp16_compression/mark_decompression_convert_constant_folding.cpp@@ -141,7 +141,7 @@ pass::MarkCompressedFloatConstants::MarkCompressedFloatConstants() {mark_as_decompression(convert_node);disable_constant_folding(const_node);disable_constant_folding(convert_node);- return true;+ return false;};auto m = std::make_shared<pass::pattern::Matcher>(convert, matcher_name);diff --git a/src/frontends/pytorch/include/openvino/frontend/pytorch/frontend.hpp b/src/frontends/pytorch/include/openvino/frontend/pytorch/frontend.hppindex 2f9ac5432ff..3b0da6f0a18 100644--- a/src/frontends/pytorch/include/openvino/frontend/pytorch/frontend.hpp+++ b/src/frontends/pytorch/include/openvino/frontend/pytorch/frontend.hpp@@ -61,7 +61,8 @@ public:protected:bool supported_impl(const std::vector<ov::Any>& variants) const override;ov::frontend::InputModel::Ptr load_impl(const std::vector<ov::Any>& variants) const override;- std::map<std::string, CreatorFunction> get_supported_ops(const ov::frontend::InputModel::Ptr& model) const;+ std::unordered_map<std::string, CreatorFunction> get_supported_ops(+ const ov::frontend::InputModel::Ptr& model) const;std::map<std::string, CreatorFunction> m_op_extension_translators;std::vector<ConversionExtensionBase::Ptr> m_conversion_extensions;diff --git a/src/frontends/pytorch/include/openvino/frontend/pytorch/node_context.hpp b/src/frontends/pytorch/include/openvino/frontend/pytorch/node_context.hppindex b1f9153835e..110beedb8b2 100644--- a/src/frontends/pytorch/include/openvino/frontend/pytorch/node_context.hpp+++ b/src/frontends/pytorch/include/openvino/frontend/pytorch/node_context.hpp@@ -18,11 +18,11 @@ typedef std::unordered_map<size_t, Output<Node>> TensorMap;class NodeContext : public frontend::NodeContext {public:- NodeContext(std::shared_ptr<TorchDecoder> decoder,+ NodeContext(const std::shared_ptr<TorchDecoder>& decoder,const TensorMap& ext_tensor_map,- std::shared_ptr<TensorMap> tensor_map,- std::shared_ptr<ParameterVector> external_parameters,- std::shared_ptr<std::set<size_t>> mutated_tensors,+ const std::shared_ptr<TensorMap>& tensor_map,+ const std::shared_ptr<ParameterVector>& external_parameters,+ const std::shared_ptr<std::set<size_t>>& mutated_tensors,TranslateSession* translate_session): frontend::NodeContext(decoder->get_op_type()),m_decoder(decoder),@@ -32,11 +32,12 @@ public:m_mutated_tensors(mutated_tensors),m_translate_session(translate_session),m_decoder_inputs(decoder->inputs()),- m_decoder_outputs(decoder->outputs()) {+ m_decoder_outputs(decoder->outputs()),+ m_inputs_is_none(m_decoder_inputs.size(), false) {FRONT_END_GENERAL_CHECK(m_tensor_map != nullptr && m_external_parameters != nullptr &&m_mutated_tensors != nullptr && m_translate_session != nullptr);for (size_t i = 0; i < m_decoder_inputs.size(); i++) {- m_inputs_is_none.push_back(decoder->input_is_none(i));+ m_inputs_is_none[i] = decoder->input_is_none(i);}}@@ -140,7 +141,7 @@ public:return m_translate_session;}- void add_tensor_to_context(size_t index, Output<Node> ov_output) const;+ void add_tensor_to_context(size_t index, const Output<Node>& ov_output) const;Output<Node> get_tensor_from_model(size_t index) const {if (m_tensor_map->find(index) != m_tensor_map->end()) {diff --git a/src/frontends/pytorch/src/frontend.cpp b/src/frontends/pytorch/src/frontend.cppindex 2940e385cd4..e0b068c4329 100644--- a/src/frontends/pytorch/src/frontend.cpp+++ b/src/frontends/pytorch/src/frontend.cpp@@ -57,26 +57,28 @@ namespace pytorch {namespace {std::map<std::string, std::string> get_unconverted_types_from_model(const std::shared_ptr<Model>& model) {std::map<std::string, std::string> unconverted_ops_types;- for (const auto& node : model->get_ordered_ops()) {+ ov::traverse_nodes(model, [&](const std::shared_ptr<Node>& node) {if (const auto& fw_node = ov::as_type_ptr<PtFrameworkNode>(node)) {const auto& attrs = fw_node->get_attrs();- FRONT_END_GENERAL_CHECK(attrs.find(PtFrameworkNode::op_type_key) != attrs.end(),+ auto op_type_it = attrs.find(PtFrameworkNode::op_type_key);+ FRONT_END_GENERAL_CHECK(op_type_it != attrs.end(),"FrameworkNode attributes do not contain operation type.");std::string exception_msg;- if (attrs.find(PtFrameworkNode::failed_conversion_key) != attrs.end()) {- exception_msg = attrs.at(PtFrameworkNode::failed_conversion_key);+ auto exception_it = attrs.find(PtFrameworkNode::failed_conversion_key);+ if (exception_it != attrs.end()) {+ exception_msg = exception_it->second;}- if (!unconverted_ops_types.count(attrs.at(PtFrameworkNode::op_type_key))) {- unconverted_ops_types[attrs.at(PtFrameworkNode::op_type_key)] = exception_msg;+ if (!unconverted_ops_types.count(op_type_it->second)) {+ unconverted_ops_types.emplace(op_type_it->second, std::move(exception_msg));}}if (const auto& fw_node = ov::as_type_ptr<ov::op::util::MultiSubGraphOp>(node)) {- for (size_t i = 0; i < fw_node->get_internal_subgraphs_size(); i++) {+ for (size_t i = 0; i < fw_node->get_internal_subgraphs_size(); ++i) {const auto& internal_types = get_unconverted_types_from_model(fw_node->get_function(i));unconverted_ops_types.insert(internal_types.begin(), internal_types.end());}}- }+ });return unconverted_ops_types;}@@ -142,7 +144,7 @@ FrontEnd::FrontEnd() {}std::shared_ptr<Model> FrontEnd::convert(const ov::frontend::InputModel::Ptr& model) const {auto pt_model = std::dynamic_pointer_cast<pytorch::InputModel>(model);FRONT_END_GENERAL_CHECK(pt_model, "Invalid input model");- std::map<std::string, CreatorFunction> supported_ops = get_supported_ops(model);+ const auto& supported_ops = get_supported_ops(model);std::shared_ptr<Model> converted_model;{pt_model->flush_places();@@ -223,7 +225,7 @@ void FrontEnd::convert(const std::shared_ptr<Model>& partiallyConverted) const {std::shared_ptr<Model> FrontEnd::convert_partially(const ov::frontend::InputModel::Ptr& model) const {auto pt_model = std::dynamic_pointer_cast<pytorch::InputModel>(model);FRONT_END_GENERAL_CHECK(pt_model, "Invalid input model");- std::map<std::string, CreatorFunction> supported_ops = get_supported_ops(model);+ const auto& supported_ops = get_supported_ops(model);std::shared_ptr<Model> partial_model;{pt_model->flush_places();@@ -247,11 +249,18 @@ std::shared_ptr<Model> FrontEnd::decode(const InputModel::Ptr& model) const {void FrontEnd::normalize(const std::shared_ptr<ov::Model>& model) const {ov::pass::Manager manager("Frontend:Pytorch:normalize");- // GPTQ transformations need to be executed before other passes- // Once the GPTQ patterns are modified by other transformations,- // they cannot be captured anymore- manager.register_pass<ov::frontend::pytorch::pass::GPTQDecompressionReplacer>();- manager.register_pass<ov::frontend::pytorch::pass::GPTQMultPatternReplacer>();+ bool is_fx = false;+ if (model->has_rt_info("decoder_type_name")) {+ is_fx = model->get_rt_info()["decoder_type_name"].as<std::string>() == "fx";+ }+ // These transformations are only applicable to fx+ if (is_fx) {+ // GPTQ transformations need to be executed before other passes+ // Once the GPTQ patterns are modified by other transformations,+ // they cannot be captured anymore+ manager.register_pass<ov::frontend::pytorch::pass::GPTQDecompressionReplacer>();+ manager.register_pass<ov::frontend::pytorch::pass::GPTQMultPatternReplacer>();+ }// the following 2 transformations are needed for keypoint detectron2 models to work.// AtenIndexToSelect will be called twice@@ -374,14 +383,16 @@ ov::frontend::InputModel::Ptr FrontEnd::load_impl(const std::vector<ov::Any>& vareturn std::make_shared<pytorch::InputModel>(tdecoder);}-std::map<std::string, CreatorFunction> FrontEnd::get_supported_ops(const ov::frontend::InputModel::Ptr& model) const {- std::map<std::string, CreatorFunction> supported_ops;+std::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")supported_ops = get_supported_ops_fx();elsesupported_ops = get_supported_ops_ts();- for (auto i = m_op_extension_translators.begin(); i != m_op_extension_translators.end(); i++)- supported_ops[i->first] = i->second;+ for (const auto& ext : m_op_extension_translators) {+ supported_ops[ext.first] = ext.second;+ }return supported_ops;}diff --git a/src/frontends/pytorch/src/input_model.cpp b/src/frontends/pytorch/src/input_model.cppindex 72140881c89..52a90d6d1cc 100644--- a/src/frontends/pytorch/src/input_model.cpp+++ b/src/frontends/pytorch/src/input_model.cpp@@ -11,7 +11,9 @@ namespace ov {namespace frontend {namespace pytorch {-InputModel::InputModel(const std::shared_ptr<TorchDecoder>& model_decoder) : m_model_decoder(model_decoder) {+InputModel::InputModel(const std::shared_ptr<TorchDecoder>& model_decoder)+ : m_model_decoder(model_decoder),+ m_decoder_type_name(model_decoder->decoder_type_name()) {const auto& inputs = m_model_decoder->inputs();for (size_t i = 0; i < inputs.size(); ++i) {auto in_place = std::make_shared<pytorch::Place>(*this, inputs[i]);@@ -166,7 +168,7 @@ void InputModel::override_all_inputs(const std::vector<Place::Ptr>& inputs) {});FRONT_END_GENERAL_CHECK(all_inputs, "Only initial inputs are supported by override_all_inputs.");// We need to add back "self" input if it was in initial inputs- if (m_inputs.size() > 0 && m_inputs[0]) {+ if (!m_inputs.empty() && m_inputs[0]) {// We need to remove "self" input to not confuse external usersconst auto& names = m_inputs[0]->get_names();if (std::any_of(names.cbegin(), names.cend(), [](const std::string& n) {@@ -180,12 +182,14 @@ void InputModel::override_all_inputs(const std::vector<Place::Ptr>& inputs) {inputs.size());auto self_place = m_inputs[0];// Verify that no same place already in vector- auto no_self = std::all_of(inputs.cbegin(), inputs.cend(), [&](const Place::Ptr& p) {- return !p->is_equal(self_place);+ auto no_self = std::none_of(inputs.cbegin(), inputs.cend(), [&](const Place::Ptr& p) {+ return p->is_equal(self_place);});FRONT_END_GENERAL_CHECK(no_self, "Unexpected input of 'self' was provided to override_all_inputs.");- m_inputs = std::vector<ov::frontend::Place::Ptr>{self_place};- m_inputs.insert(m_inputs.cend(), inputs.cbegin(), inputs.cend());+ m_inputs.clear();+ m_inputs.reserve(inputs.size() + 1);+ m_inputs.push_back(std::move(self_place));+ m_inputs.insert(m_inputs.end(), inputs.cbegin(), inputs.cend());return;}}@@ -199,7 +203,7 @@ void InputModel::override_all_inputs(const std::vector<Place::Ptr>& inputs) {}const std::string& InputModel::decoder_type_name() const {- return m_model_decoder->decoder_type_name();+ return m_decoder_type_name;}std::shared_ptr<TorchDecoder> InputModel::get_decoder() const {diff --git a/src/frontends/pytorch/src/input_model.hpp b/src/frontends/pytorch/src/input_model.hppindex b647da29465..bfadc970e6a 100644--- a/src/frontends/pytorch/src/input_model.hpp+++ b/src/frontends/pytorch/src/input_model.hpp@@ -52,6 +52,7 @@ private:std::vector<std::shared_ptr<frontend::Place>> m_outputs;std::vector<std::shared_ptr<frontend::Place>> m_requested_places;std::unordered_map<size_t, PlaceDesc> m_descriptors;+ const std::string m_decoder_type_name;};} // namespace pytorchdiff --git a/src/frontends/pytorch/src/node_context.cpp b/src/frontends/pytorch/src/node_context.cppindex 5684212f109..efc3bb107eb 100644--- a/src/frontends/pytorch/src/node_context.cpp+++ b/src/frontends/pytorch/src/node_context.cpp@@ -55,31 +55,23 @@ 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);- FRONT_END_GENERAL_CHECK(m_tensor_map->count(input_id), "No tensor corresponding input: ", input_id, " exist.");+ 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)});- (*m_tensor_map)[input_id] = ov_output;+ tensor_it->second = ov_output;m_mutated_tensors->insert(input_id);// Resolve aliases- auto back_input_id = input_id;- auto back_node_input = ov_output;+ auto& back_input_id = input_id;+ auto& back_node_input = ov_output;while (m_translate_session->m_may_be_alias.count(back_input_id)) {- // Create node to reverseprop data. While loop is needed for the cases when alias to tensor point to another+ // 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 ops- size_t in_tensor;- std::shared_ptr<TorchDecoder> node;- Output<Node> node_converted_output;- std::tie(in_tensor, node, node_converted_output) = m_translate_session->m_may_be_alias.at(back_input_id);+ auto& 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);- if (m_tensor_map->count(in_tensor)) {- // Tensor is not found in the scope of this body, need to get it from internal context and mark mutated- OPENVINO_DEBUG("Couldn't find in the current body the initial aliased tensor: ",- in_tensor,- " for operation: ",- node->get_op_type(),- " creating new body input.");- get_tensor_from_model_or_create_input(in_tensor);- }m_translate_session->encode_tensor_name(reverseprop_node, in_tensor);(*m_tensor_map)[in_tensor] = reverseprop_node;m_mutated_tensors->insert(in_tensor);@@ -89,17 +81,20 @@ void NodeContext::mutate_input(size_t index, Output<Node> ov_output) const {}}-void NodeContext::add_tensor_to_context(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");}+#endifm_translate_session->encode_tensor_name(ov_output, index);(*m_tensor_map)[index] = ov_output;}Output<Node> NodeContext::get_tensor_from_model_or_create_input(size_t index) const {- if (m_tensor_map->find(index) != m_tensor_map->end()) {- return m_tensor_map->at(index);+ auto tensor_it = m_tensor_map->find(index);+ if (tensor_it != m_tensor_map->end()) {+ return tensor_it->second;} else {// nested subgraphs caseauto parameter = std::make_shared<v0::Parameter>(element::dynamic, PartialShape::dynamic());@@ -131,7 +126,7 @@ std::shared_ptr<ov::Model> NodeContext::convert_subgraph(size_t index) const {// Extend external context with internal tensors except Parameter nodes, because internal Parameters are created to// link internal context with externalTensorMap ext_map(m_ext_tensor_map);- // map::insert does not update elements if their key is already in map; so if we have real tensors in outter scope+ // map::insert does not update elements if their key is already in map; so if we have real tensors in outer scope// we will not add Parameters we created in inner scope.ext_map.insert(m_tensor_map->begin(), m_tensor_map->end());@@ -159,10 +154,12 @@ OutputVector NodeContext::inputs() const {auto inlined_input = m_decoder->inlined_input(i);FRONT_END_GENERAL_CHECK(inlined_input.size() == 1, "Incorrect inlined input with index:", i);res.push_back(inlined_input[0]);+ continue;}}- FRONT_END_GENERAL_CHECK(m_tensor_map->count(input), "No tensor corresponding input: ", input, " exist.");- res.push_back(m_tensor_map->at(input));+ auto tensor_it = m_tensor_map->find(input);+ FRONT_END_GENERAL_CHECK(tensor_it != m_tensor_map->end(), "No tensor corresponding input: ", input, " exist.");+ res.push_back(tensor_it->second);}return res;}diff --git a/src/frontends/pytorch/src/op/adaptive_poolnd.cpp b/src/frontends/pytorch/src/op/adaptive_poolnd.cppindex 1288f1402e7..7d52386d0ed 100644--- a/src/frontends/pytorch/src/op/adaptive_poolnd.cpp+++ b/src/frontends/pytorch/src/op/adaptive_poolnd.cpp@@ -102,7 +102,7 @@ OutputVector translate_adaptive_max_pool_base(const NodeContext& context,pooled_indices = context.mark_node(std::make_shared<v1::Reshape>(pooled_indices, output_shape, false));// aten::adaptive_max_pool{n}d always returns tuple with 2 tensors: pooled tensor and indicies// output selecting only first or preserve both made outside of operation by return_indices flag- return {pooled_tensor, pooled_indices};+ return {std::move(pooled_tensor), std::move(pooled_indices)};};} // namespacediff --git a/src/frontends/pytorch/src/op/add.cpp b/src/frontends/pytorch/src/op/add.cppindex eada7871b87..dd72222a9ec 100644--- a/src/frontends/pytorch/src/op/add.cpp+++ b/src/frontends/pytorch/src/op/add.cpp@@ -18,6 +18,7 @@ namespace op {using namespace ov::op;+namespace {OutputVector translate_add_common(const NodeContext& context, bool inplace) {num_inputs_check(context, 2, 3);Output<Node> lhs;@@ -67,6 +68,7 @@ OutputVector translate_add_common(const NodeContext& context, bool inplace) {context.mutate_input(0, add);return {add};};+} // namespaceOutputVector translate_add(const NodeContext& context) {return translate_add_common(context, false);diff --git a/src/frontends/pytorch/src/op/addmm.cpp b/src/frontends/pytorch/src/op/addmm.cppindex 522c5237ecd..4ecfd403afc 100644--- a/src/frontends/pytorch/src/op/addmm.cpp+++ b/src/frontends/pytorch/src/op/addmm.cpp@@ -46,7 +46,7 @@ OutputVector translate_addmm(const NodeContext& context) {if (!context.input_is_none(4)) {alpha = context.get_input(4);}- return {translate_addmm_common(context, beta, alpha)};+ return {translate_addmm_common(context, std::move(beta), std::move(alpha))};};OutputVector translate_addmm_fx(const NodeContext& context) {@@ -60,7 +60,7 @@ OutputVector translate_addmm_fx(const NodeContext& context) {if (context.has_attribute("alpha")) {alpha = context.get_input("alpha");}- return {translate_addmm_common(context, beta, alpha)};+ return {translate_addmm_common(context, std::move(beta), std::move(alpha))};};OutputVector translate_conv1d_ext(const NodeContext& context) {diff --git a/src/frontends/pytorch/src/op/any.cpp b/src/frontends/pytorch/src/op/any.cppindex fb36c4268cf..a17b8777e5f 100644--- a/src/frontends/pytorch/src/op/any.cpp+++ b/src/frontends/pytorch/src/op/any.cpp@@ -55,7 +55,7 @@ OutputVector translate_any(const NodeContext& context) {out_id = 3;}- auto result = translate_any_common(context, input_tensor, axes, keep_dims);+ const auto& result = translate_any_common(context, input_tensor, axes, keep_dims);if (!context.input_is_none(out_id)) {context.mutate_input(out_id, result);}@@ -75,7 +75,7 @@ OutputVector translate_any_fx(const NodeContext& context) {bool keep_dims = false;if (!context.input_is_none(2))keep_dims = context.const_input<bool>(2);- auto any = translate_any_common(context, x, dims, keep_dims);+ const auto& any = translate_any_common(context, x, dims, keep_dims);return {any};};diff --git a/src/frontends/pytorch/src/op/argmax_argmin.cpp b/src/frontends/pytorch/src/op/argmax_argmin.cppindex e3b0b9d2068..9d6360609f0 100644--- a/src/frontends/pytorch/src/op/argmax_argmin.cpp+++ b/src/frontends/pytorch/src/op/argmax_argmin.cpp@@ -46,8 +46,7 @@ OutputVector create_argmax_argmin_op(const NodeContext& context, TopKMode mode)std::make_shared<v11::TopK>(flatten_input, k, axis, mode, TopKSortType::SORT_VALUES, element::i64, true));indices = topk->output(1);if (keep_dims) {- auto input_shape = context.mark_node(std::make_shared<v3::ShapeOf>(input, element::i32));- auto input_rank = context.mark_node(std::make_shared<v3::ShapeOf>(input_shape, element::i32));+ auto input_rank = std::get<1>(get_shape_rank(context, input));auto new_shape = context.mark_node(std::make_shared<v3::Broadcast>(k, input_rank));indices =context.mark_node(std::make_shared<v3::Broadcast>(indices, new_shape, BroadcastType::BIDIRECTIONAL));@@ -56,7 +55,7 @@ OutputVector create_argmax_argmin_op(const NodeContext& context, TopKMode mode)indices = context.mark_node(std::make_shared<v0::Squeeze>(indices, zero));}}- return {indices};+ return {std::move(indices)};}}; // namespacediff --git a/src/frontends/pytorch/src/op/as_strided.cpp b/src/frontends/pytorch/src/op/as_strided.cppindex 01bad08af60..20efb3ba5cb 100644--- a/src/frontends/pytorch/src/op/as_strided.cpp+++ b/src/frontends/pytorch/src/op/as_strided.cpp@@ -33,7 +33,7 @@ OutputVector translate_as_strided(const NodeContext& context) {auto const_neg_1 = context.mark_node(v0::Constant::create(element::i32, Shape{1}, {-1}));auto input_strides = decoder->get_input_strides(0);PYTORCH_OP_CONVERSION_CHECK(input_strides.size() != 0,- "aten::as_strided: Couldn't retrive input stride information from torchscript.");+ "aten::as_strided: Couldn't retrieve input stride information from torchscript.");std::vector<size_t> idxs(input_strides.size());iota(idxs.begin(), idxs.end(), 0);diff --git a/src/frontends/pytorch/src/op/batch_norm.cpp b/src/frontends/pytorch/src/op/batch_norm.cppindex 7f31d0894e4..03c6f8a75d2 100644--- a/src/frontends/pytorch/src/op/batch_norm.cpp+++ b/src/frontends/pytorch/src/op/batch_norm.cpp@@ -63,7 +63,6 @@ OutputVector make_batch_norm(const NodeContext& context,} else {b = context.mark_node(std::make_shared<v1::ConvertLike>(b, input));}- auto zero = context.mark_node(v0::Constant::create(element::i32, Shape{}, {0}));auto zero_1d = context.mark_node(v0::Constant::create(element::i32, Shape{1}, {0}));auto one = context.mark_node(v0::Constant::create(element::i32, Shape{}, {1}));auto two = context.mark_node(v0::Constant::create(element::i32, Shape{}, {2}));diff --git a/src/frontends/pytorch/src/op/clamp.cpp b/src/frontends/pytorch/src/op/clamp.cppindex 67002dd6104..691a2d95008 100644--- a/src/frontends/pytorch/src/op/clamp.cpp+++ b/src/frontends/pytorch/src/op/clamp.cpp@@ -28,7 +28,7 @@ OutputVector translate_clamp(const NodeContext& context) {max_clip = context.mark_node(std::make_shared<v1::ConvertLike>(max_clip, x));x = context.mark_node(std::make_shared<v1::Minimum>(x, max_clip));}- return {x};+ return {std::move(x)};};} // namespace opdiff --git a/src/frontends/pytorch/src/op/dim.cpp b/src/frontends/pytorch/src/op/dim.cppindex 443a171733e..1d15e0b9e4d 100644--- a/src/frontends/pytorch/src/op/dim.cpp+++ b/src/frontends/pytorch/src/op/dim.cpp@@ -14,8 +14,7 @@ using namespace ov::op;OutputVector translate_dim(const NodeContext& context) {num_inputs_check(context, 1, 1);- Output<Node> rank;- std::tie(std::ignore, rank) = get_shape_rank(context, context.get_input(0), true);+ Output<Node> rank = std::get<1>(get_shape_rank(context, context.get_input(0), true));return {rank};};diff --git a/src/frontends/pytorch/src/op/div.cpp b/src/frontends/pytorch/src/op/div.cppindex 7c091f2c2cb..55ef9508dec 100644--- a/src/frontends/pytorch/src/op/div.cpp+++ b/src/frontends/pytorch/src/op/div.cpp@@ -17,6 +17,7 @@ namespace frontend {namespace pytorch {namespace op {+namespace {OutputVector translate_div_common(const NodeContext& context,const Output<Node>& lhs,const Output<Node>& rhs,@@ -56,6 +57,7 @@ OutputVector translate_div_common(const NodeContext& context,context.mutate_input(0, res);return {res};};+} // namespaceOutputVector translate_div(const NodeContext& context) {num_inputs_check(context, 2, 3);diff --git a/src/frontends/pytorch/src/op/pad.cpp b/src/frontends/pytorch/src/op/pad.cppindex 2a8365de8a6..c8f35a0afab 100644--- a/src/frontends/pytorch/src/op/pad.cpp+++ b/src/frontends/pytorch/src/op/pad.cpp@@ -85,7 +85,7 @@ OutputVector translate_pad_common(const NodeContext& context,return {cur};}auto pad_value_ = context.mark_node(std::make_shared<v1::ConvertLike>(pad_value, data));- const std::map<std::string, PadMode> pt_to_ov_pad{+ static const std::map<std::string, PadMode> pt_to_ov_pad{{"constant", PadMode::CONSTANT},{"reflect", PadMode::REFLECT},{"replicate", PadMode::EDGE},diff --git a/src/frontends/pytorch/src/op_table.cpp b/src/frontends/pytorch/src/op_table.cppindex 83ff923efcd..b3c606f3f05 100644--- a/src/frontends/pytorch/src/op_table.cpp+++ b/src/frontends/pytorch/src/op_table.cpp@@ -318,7 +318,7 @@ OP_CONVERTER(translate_zeros_like_fx);} // namespace op// Supported ops for TorchScript-const std::map<std::string, CreatorFunction> get_supported_ops_ts() {+const std::unordered_map<std::string, CreatorFunction> get_supported_ops_ts() {return {{"aten::__and__", op::translate_bitwise_and},{"aten::__derive_index", op::translate_derive_index},@@ -398,17 +398,12 @@ const std::map<std::string, CreatorFunction> get_supported_ops_ts() {{"aten::ceil", op::optional_out<op::translate_1to1_match_1_inputs<opset10::Ceiling>, 1>},{"aten::ceil_", op::inplace_op<op::translate_1to1_match_1_inputs<opset10::Ceiling>>},{"aten::celu", op::translate_celu},- {"aten::celu_", op::inplace_op<op::translate_celu>},{"aten::channel_shuffle", op::translate_channel_shuffle},// aten::chunk - Supported in limited set of patterns{"aten::clamp", op::translate_clamp},- {"aten::clamp_", op::inplace_op<op::translate_clamp>},{"aten::clamp_max", op::translate_1to1_match_2_inputs_align_types<opset10::Minimum>},- {"aten::clamp_max_", op::inplace_op<op::translate_1to1_match_2_inputs_align_types<opset10::Minimum>>},{"aten::clamp_min", op::translate_1to1_match_2_inputs_align_types<opset10::Maximum>},- {"aten::clamp_min_", op::inplace_op<op::translate_1to1_match_2_inputs_align_types<opset10::Maximum>>},{"aten::clip", op::translate_clamp},- {"aten::clip_", op::inplace_op<op::translate_clamp>},{"aten::clone", op::skip_node}, // ignore clone operators that are inserted by PyTorch autograd{"aten::col2im", op::translate_col2im},// aten::complex - Supported in limited set of patterns@@ -440,22 +435,18 @@ const std::map<std::string, CreatorFunction> get_supported_ops_ts() {{"aten::dropout_", op::skip_node},// aten::einsum - Supported in limited set of patterns{"aten::elu", op::translate_elu},- {"aten::elu_", op::inplace_op<op::translate_elu>},{"aten::embedding", op::translate_embedding},{"aten::embedding_bag", op::translate_embedding_bag},{"aten::empty", op::translate_empty},{"aten::empty_like", op::translate_empty_like},{"aten::eq", op::translate_1to1_match_2_inputs_align_types<opset10::Equal>},{"aten::erf", op::translate_erf},- {"aten::erf_", op::inplace_op<op::translate_erf>},{"aten::erfc", op::translate_erfc},- {"aten::erfc_", op::inplace_op<op::translate_erfc>},{"aten::exp", op::optional_out<op::translate_1to1_match_1_inputs_with_fp32_type_alignment<opset10::Exp>, 1>},{"aten::exp_", op::inplace_op<op::translate_1to1_match_1_inputs_with_fp32_type_alignment<opset10::Exp>>},{"aten::expand", op::translate_expand},{"aten::expand_as", op::translate_expand_as},{"aten::expm1", op::translate_expm1},- {"aten::expm1_", op::inplace_op<op::translate_expm1>},{"aten::eye", op::translate_eye},{"aten::fake_quantize_per_channel_affine", op::translate_fake_quantize_per_channel_affine},{"aten::fake_quantize_per_tensor_affine", op::translate_fake_quantize_per_tensor_affine},@@ -463,14 +454,12 @@ const std::map<std::string, CreatorFunction> get_supported_ops_ts() {// aten::fft_irfftn - Supported in limited set of patterns// aten::fft_rfftn - Supported in limited set of patterns{"aten::fill", op::translate_fill},- {"aten::fill_", op::inplace_op<op::translate_fill>},- {"aten::fill_diagonal_", op::inplace_op<op::translate_fill_diagonal>},+ {"aten::fill_diagonal", op::translate_fill_diagonal},{"aten::flatten", op::quantizable_op<op::translate_flatten>},{"aten::flip", op::translate_flip},{"aten::floor", op::optional_out<op::translate_1to1_match_1_inputs<opset10::Floor>, 1>},{"aten::floor_", op::inplace_op<op::translate_1to1_match_1_inputs<opset10::Floor>>},{"aten::floor_divide", op::translate_floor_divide},- {"aten::floor_divide_", op::inplace_op<op::translate_floor_divide>},{"aten::floordiv", op::translate_floor_divide},{"aten::fmod", op::translate_fmod},{"aten::frobenius_norm", op::translate_frobenius_norm},@@ -487,19 +476,14 @@ const std::map<std::string, CreatorFunction> get_supported_ops_ts() {{"aten::gt", op::translate_1to1_match_2_inputs_align_types<opset10::Greater>},{"aten::hann_window", op::translate_hann_window},{"aten::hardsigmoid", op::quantizable_op<op::translate_1to1_match_1_inputs<opset10::HSigmoid>>},- {"aten::hardsigmoid_",- op::quantizable_op<op::inplace_op<op::translate_1to1_match_1_inputs<opset10::HSigmoid>>>},{"aten::hardswish", op::quantizable_op<op::translate_1to1_match_1_inputs<opset10::HSwish>>},- {"aten::hardswish_", op::quantizable_op<op::inplace_op<op::translate_1to1_match_1_inputs<opset10::HSwish>>>},{"aten::hardtanh", op::quantizable_op<op::translate_hardtanh>},- {"aten::hardtanh_", op::inplace_op<op::quantizable_op<op::translate_hardtanh>>},{"aten::im2col", op::translate_im2col},// aten::imag - Supported in limited set of patterns// aten::index - Supported in limited set of patterns{"aten::index_copy_", op::inplace_op<op::translate_index_copy_>},{"aten::index_put_", op::inplace_op<op::translate_index_put_>},{"aten::index_add", op::translate_index_add},- {"aten::index_add_", op::inplace_op<op::translate_index_add>},{"aten::index_select", op::translate_index_select},{"aten::instance_norm", op::translate_instance_norm},{"aten::inverse", op::translate_inverse},@@ -514,7 +498,6 @@ const std::map<std::string, CreatorFunction> get_supported_ops_ts() {{"aten::layer_norm", op::translate_layer_norm},{"aten::le", op::translate_1to1_match_2_inputs_align_types<opset10::LessEqual>},{"aten::leaky_relu", op::translate_1to1_match_2_inputs<opset10::PRelu>},- {"aten::leaky_relu_", op::inplace_op<op::translate_1to1_match_2_inputs<opset10::PRelu>>},{"aten::len", op::translate_len},// lift op is torchscript specific op responsible for tensors coping with guarantee of new memory allocation{"aten::lift", op::skip_node},@@ -544,9 +527,7 @@ const std::map<std::string, CreatorFunction> get_supported_ops_ts() {{"aten::lstm", op::translate_lstm},{"aten::lt", op::translate_1to1_match_2_inputs_align_types<opset10::Less>},{"aten::masked_fill", op::translate_masked_fill},- {"aten::masked_fill_", op::inplace_op<op::translate_masked_fill>},{"aten::masked_scatter", op::translate_masked_scatter},- {"aten::masked_scatter_", op::inplace_op<op::translate_masked_scatter>},{"aten::matmul", op::translate_1to1_match_2_inputs<opset10::MatMul>},{"aten::max", op::translate_max},{"aten::mv", op::translate_1to1_match_2_inputs<opset10::MatMul>},@@ -562,7 +543,6 @@ const std::map<std::string, CreatorFunction> get_supported_ops_ts() {{"aten::min", op::translate_min},{"aten::minimum", op::translate_minimum},{"aten::mish", op::translate_1to1_match_1_inputs_with_fp32_type_alignment<opset10::Mish>},- {"aten::mish_", op::inplace_op<op::translate_1to1_match_1_inputs_with_fp32_type_alignment<opset10::Mish>>},{"aten::mm", op::translate_1to1_match_2_inputs<opset10::MatMul>},{"aten::movedim", op::translate_movedim},{"aten::mul", op::translate_mul},@@ -611,7 +591,6 @@ const std::map<std::string, CreatorFunction> get_supported_ops_ts() {{"aten::relu", op::optional_out<op::translate_1to1_match_1_inputs<opset10::Relu>, 1>},{"aten::relu_", op::inplace_op<op::translate_1to1_match_1_inputs<opset10::Relu>>},{"aten::relu6", op::translate_relu6},- {"aten::relu6_", op::inplace_op<op::translate_relu6>},{"aten::remainder", op::translate_remainder},{"aten::repeat", op::translate_1to1_match_2_inputs<opset10::Tile>},{"aten::repeat_interleave", op::translate_repeat_interleave},@@ -632,20 +611,15 @@ const std::map<std::string, CreatorFunction> get_supported_ops_ts() {{"aten::ScalarImplicit", op::skip_node},{"aten::scaled_dot_product_attention", op::translate_scaled_dot_product_attention},{"aten::scatter", op::translate_scatter},- {"aten::scatter_", op::inplace_op<op::translate_scatter>},{"aten::scatter_add", op::translate_scatter_add},- {"aten::scatter_add_", op::inplace_op<op::translate_scatter_add>},{"aten::scatter_reduce", op::translate_scatter_reduce},- {"aten::scatter_reduce_", op::inplace_op<op::translate_scatter_reduce>},{"aten::select", op::quantizable_op<op::translate_select>},{"aten::selu", op::translate_selu},- {"aten::selu_", op::inplace_op<op::translate_selu>},{"aten::sigmoid",op::optional_out<op::translate_1to1_match_1_inputs_with_fp32_type_alignment<opset10::Sigmoid>, 1>},{"aten::sigmoid_", op::inplace_op<op::translate_1to1_match_1_inputs<opset10::Sigmoid>>},{"aten::sign", op::translate_sign},{"aten::silu", op::translate_1to1_match_1_inputs<opset10::Swish>},- {"aten::silu_", op::inplace_op<op::translate_1to1_match_1_inputs<opset10::Swish>>},{"aten::sin", op::optional_out<op::translate_1to1_match_1_inputs_with_fp32_type_alignment<opset10::Sin>, 1>},{"aten::sin_", op::inplace_op<op::translate_1to1_match_1_inputs<opset10::Sin>>},{"aten::sinh", op::optional_out<op::translate_1to1_match_1_inputs_with_fp32_type_alignment<opset10::Sinh>, 1>},@@ -669,7 +643,6 @@ const std::map<std::string, CreatorFunction> get_supported_ops_ts() {{"aten::sum", op::translate_sum},{"aten::swapaxes", op::quantizable_op<op::translate_transpose>},{"aten::t", op::translate_t},- {"aten::t_", op::inplace_op<op::translate_t>},{"aten::take_along_dim", op::translate_take_along_dim},{"aten::tan", op::optional_out<op::translate_1to1_match_1_inputs_with_fp32_type_alignment<opset10::Tan>, 1>},{"aten::tan_", op::inplace_op<op::translate_1to1_match_1_inputs<opset10::Tan>>},@@ -682,16 +655,13 @@ const std::map<std::string, CreatorFunction> get_supported_ops_ts() {{"aten::topk", op::translate_topk},{"aten::transpose", op::quantizable_op<op::translate_transpose>},{"aten::tril", op::translate_tril},- {"aten::tril_", op::inplace_op<op::translate_tril>},{"aten::triu", op::translate_triu},- {"aten::triu_", op::inplace_op<op::translate_triu>},{"aten::type_as",op::translate_1to1_match_2_inputs<opset10::ConvertLike>}, // TODO: overflow semantics is different// aten::unbind - Supported in limited set of patterns{"aten::unflatten", op::translate_unflatten},{"aten::unfold", op::translate_unfold},{"aten::unsqueeze", op::quantizable_op<op::translate_1to1_match_2_inputs<opset10::Unsqueeze>>},- {"aten::unsqueeze_", op::quantizable_op<op::inplace_op<op::translate_1to1_match_2_inputs<opset10::Unsqueeze>>>},{"aten::upsample_bicubic2d", op::translate_upsample_bicubic2d},{"aten::upsample_bilinear2d", op::translate_upsample_bilinear2d},{"aten::upsample_linear1d", op::translate_upsample_linear1d},@@ -704,7 +674,7 @@ const std::map<std::string, CreatorFunction> get_supported_ops_ts() {{"aten::view", op::quantizable_op<op::translate_reshape>},{"aten::view_as", op::translate_reshape_as},{"aten::where", op::translate_where},- {"aten::zero_", op::inplace_op<op::translate_zeros_like>},+ {"aten::zero", op::translate_zeros_like},{"aten::zeros", op::translate_zeros},{"aten::zeros_like", op::translate_zeros_like},{"ov_ext::embedding", op::translate_embedding_ext},@@ -742,7 +712,7 @@ const std::map<std::string, CreatorFunction> get_supported_ops_ts() {};};-const std::map<std::string, CreatorFunction> get_supported_ops_fx() {+const std::unordered_map<std::string, CreatorFunction> get_supported_ops_fx() {return {{"<built-in function add>", op::translate_add},{"<built-in function floordiv>", op::translate_floor_divide},diff --git a/src/frontends/pytorch/src/op_table.hpp b/src/frontends/pytorch/src/op_table.hppindex f7f1a51b571..721146a426a 100644--- a/src/frontends/pytorch/src/op_table.hpp+++ b/src/frontends/pytorch/src/op_table.hpp@@ -10,8 +10,8 @@ namespace ov {namespace frontend {namespace pytorch {-const std::map<std::string, CreatorFunction> get_supported_ops_ts();-const std::map<std::string, CreatorFunction> get_supported_ops_fx();+const std::unordered_map<std::string, CreatorFunction> get_supported_ops_ts();+const std::unordered_map<std::string, CreatorFunction> get_supported_ops_fx();} // namespace pytorch} // namespace frontenddiff --git a/src/frontends/pytorch/src/transforms/append_list_unpack_replacer.cpp b/src/frontends/pytorch/src/transforms/append_list_unpack_replacer.cppindex fc5689639ec..6263e769639 100644--- a/src/frontends/pytorch/src/transforms/append_list_unpack_replacer.cpp+++ b/src/frontends/pytorch/src/transforms/append_list_unpack_replacer.cpp@@ -44,20 +44,23 @@ AppendListUnpackReplacer::AppendListUnpackReplacer() {while (auto append_node = cast_fw_node(input_node, "aten::append")) {rt_copy_from.push_back(append_node);- tmp_inputs.push_back(append_node->input(1).get_source_output());+ tmp_inputs.emplace_back(append_node->input(1).get_source_output());input_node = append_node->input(0).get_source_output().get_node_shared_ptr();}OutputVector inputs;- auto list_construct_node = cast_fw_node(input_node, "prim::ListConstruct");+ auto list_construct_node = cast_fw_node(std::move(input_node), "prim::ListConstruct");if (!list_construct_node) {return false;}+ inputs.reserve(list_construct_node->inputs().size() + tmp_inputs.size());rt_copy_from.push_back(list_construct_node);for (auto& input : list_construct_node->inputs()) {inputs.push_back(input.get_source_output());}- inputs.insert(inputs.end(), tmp_inputs.rbegin(), tmp_inputs.rend());+ inputs.insert(inputs.end(),+ std::make_move_iterator(tmp_inputs.rbegin()),+ std::make_move_iterator(tmp_inputs.rend()));if (getitem_node) {// If aten::__getitem__, expect inputs to be equivalent of pytorch Tensor[][].// Tensor selected by aten::__getitem__ index needs to be splitted in axis 0.@@ -81,7 +84,7 @@ AppendListUnpackReplacer::AppendListUnpackReplacer() {to_copy_rt.push_back(squeeze);res.push_back(squeeze);}- copy_runtime_info_and_name(list_unpack, to_copy_rt, rt_copy_from);+ copy_runtime_info_and_name(list_unpack, std::move(to_copy_rt), rt_copy_from);replace_node(list_unpack, res);return true;} else {diff --git a/src/frontends/pytorch/src/transforms/aten_getitem_replacer.cpp b/src/frontends/pytorch/src/transforms/aten_getitem_replacer.cppindex 4249363a8ef..5d371e0d65f 100644--- a/src/frontends/pytorch/src/transforms/aten_getitem_replacer.cpp+++ b/src/frontends/pytorch/src/transforms/aten_getitem_replacer.cpp@@ -47,7 +47,7 @@ AtenGetItemReplacer::AtenGetItemReplacer() {return false;ov::pass::NodeRegistry rg;- auto input_node = getitem->input_value(0).get_node_shared_ptr();+ const auto& input_node = getitem->input_value(0).get_node_shared_ptr();if (auto torch_split = cast_fw_node(input_node, "aten::split")) {auto rank = torch_split->input(1).get_partial_shape().rank();if (rank.is_dynamic()) {diff --git a/src/frontends/pytorch/src/transforms/aten_stack_list_construct_replacer.cpp b/src/frontends/pytorch/src/transforms/aten_stack_list_construct_replacer.cppindex b58c42b1791..aad973c3769 100644--- a/src/frontends/pytorch/src/transforms/aten_stack_list_construct_replacer.cpp+++ b/src/frontends/pytorch/src/transforms/aten_stack_list_construct_replacer.cpp@@ -23,19 +23,19 @@ using namespace ov::op;using namespace ov::pass::pattern;AtenStackListConstructReplacer::AtenStackListConstructReplacer() {- auto list_construct = wrap_type<ov::op::util::FrameworkNode>();- auto axis = wrap_type<v0::Constant>();+ const auto& list_construct = wrap_type<ov::op::util::FrameworkNode>();+ const auto& axis = wrap_type<v0::Constant>();// We search for a pattern: ListConstruct -> aten::stack <- Constant- auto stack = wrap_type<ov::op::util::FrameworkNode>({list_construct, axis});+ const auto& stack = wrap_type<ov::op::util::FrameworkNode>({list_construct, axis});- ov::matcher_pass_callback callback = [=](Matcher& m) {+ ov::matcher_pass_callback callback = [list_construct, axis](Matcher& m) {auto stack = cast_fw_node(m.get_match_root(), "aten::stack");if (!stack) {return false;}const auto& pattern_map = m.get_pattern_value_map();- auto input_node = pattern_map.at(list_construct).get_node_shared_ptr();+ const auto& input_node = pattern_map.at(list_construct).get_node_shared_ptr();auto axis_node = pattern_map.at(axis).get_node_shared_ptr();auto axis_const = std::dynamic_pointer_cast<v0::Constant>(axis_node);auto axis = axis_const->cast_vector<int64_t>();@@ -47,7 +47,7 @@ AtenStackListConstructReplacer::AtenStackListConstructReplacer() {if (auto list_construct_node = cast_fw_node(input_node, "prim::ListConstruct")) {const auto& list_inputs = list_construct_node->input_values();std::shared_ptr<Node> node;- if (auto compression = u4_compression_stack(list_inputs, axis[0])) {+ if (const auto& compression = u4_compression_stack(list_inputs, axis[0])) {node = compression;} else {OutputVector node_vector;diff --git a/src/frontends/pytorch/src/transforms/einsum_list_construct.cpp b/src/frontends/pytorch/src/transforms/einsum_list_construct.cppindex d0873e8479e..a8f43d8f52c 100644--- a/src/frontends/pytorch/src/transforms/einsum_list_construct.cpp+++ b/src/frontends/pytorch/src/transforms/einsum_list_construct.cpp@@ -28,8 +28,8 @@ AtenEinsumListConstructReplacer::AtenEinsumListConstructReplacer() {if (!einsum_op) {return false;}- auto equation_input = einsum_op->input_value(0).get_node_shared_ptr();- auto tensor_list = einsum_op->input_value(1).get_node_shared_ptr();+ 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();diff --git a/src/frontends/pytorch/src/transforms/listconstruct_replacer.cpp b/src/frontends/pytorch/src/transforms/listconstruct_replacer.cppindex c7db874634b..caa8d3cc18a 100644--- a/src/frontends/pytorch/src/transforms/listconstruct_replacer.cpp+++ b/src/frontends/pytorch/src/transforms/listconstruct_replacer.cpp@@ -38,48 +38,48 @@ using namespace ov::op;ListConstructReplacer::ListConstructReplacer() {// Transformation for torch operators for cases where prim::ListConstruct can be replaced with Concat.- auto list = pattern::wrap_type<ov::op::util::FrameworkNode>();+ const auto& list = pattern::wrap_type<ov::op::util::FrameworkNode>();// Both aten::view and aten::reshape are using same translation returning Reshape operator.- auto reshape_op = pattern::wrap_type<v1::Reshape>({pattern::any_input(), list});- auto roll_op = pattern::wrap_type<v7::Roll>({pattern::any_input(), list, pattern::any_input()});- auto broadcast_op = pattern::wrap_type<v3::Broadcast>({pattern::any_input(), list});- auto adapool_op = pattern::wrap_type<v8::AdaptiveAvgPool>({pattern::any_input(), list});+ const auto& reshape_op = pattern::wrap_type<v1::Reshape>({pattern::any_input(), list});+ const auto& roll_op = pattern::wrap_type<v7::Roll>({pattern::any_input(), list, pattern::any_input()});+ const auto& broadcast_op = pattern::wrap_type<v3::Broadcast>({pattern::any_input(), list});+ const auto& adapool_op = pattern::wrap_type<v8::AdaptiveAvgPool>({pattern::any_input(), list});// replace list construct for aten::expand(tensor, prim::ListConstruct(shapes)) old decomposition- // shape_of + broadcast + equal + select- auto shape_of_op = pattern::wrap_type<v3::ShapeOf>({list});- auto equal_op = pattern::wrap_type<v1::Equal>({list, pattern::any_input()});- auto select_op = pattern::wrap_type<v1::Select>({pattern::any_input(), pattern::any_input(), list});+ // shape_of + broadcast + equal + select+ const auto& shape_of_op = pattern::wrap_type<v3::ShapeOf>({list});+ const auto& equal_op = pattern::wrap_type<v1::Equal>({list, pattern::any_input()});+ const auto& select_op = pattern::wrap_type<v1::Select>({pattern::any_input(), pattern::any_input(), list});// replace list construct for aten::expand(tensor, prim::ListConstruct(shapes)) new decomposition- auto abs_op = pattern::wrap_type<v0::Abs>({list});- auto expand_op = pattern::wrap_type<v3::Broadcast>({pattern::any_input(), abs_op});+ const auto& abs_op = pattern::wrap_type<v0::Abs>({list});+ const auto& expand_op = pattern::wrap_type<v3::Broadcast>({pattern::any_input(), abs_op});// replace list construct for aten::repeat(tensor, prim::ListConstruct(shapes)))// shape_of + broadcast + tile- auto tile_op = pattern::wrap_type<v0::Tile>({pattern::any_input(), list});+ const auto& tile_op = pattern::wrap_type<v0::Tile>({pattern::any_input(), list});// replace aten::permute(tensor, prim::ListConstruct)- auto transpose_op = pattern::wrap_type<v1::Transpose>({pattern::any_input(), list});+ const auto& transpose_op = pattern::wrap_type<v1::Transpose>({pattern::any_input(), list});// aten::split_with_sizes case- auto vsplit_op = pattern::wrap_type<v1::VariadicSplit>({pattern::any_input(), pattern::any_input(), list});+ const auto& vsplit_op = pattern::wrap_type<v1::VariadicSplit>({pattern::any_input(), pattern::any_input(), list});// aten::upsample... case inside the body when body was removed- auto interpolate_convert_op = pattern::wrap_type<v0::Convert>({list});- auto interpolate_mul_op = pattern::wrap_type<v1::Multiply>({interpolate_convert_op, pattern::any_input()});- auto interpolate_op =+ const auto& interpolate_convert_op = pattern::wrap_type<v0::Convert>({list});+ const auto& interpolate_mul_op = pattern::wrap_type<v1::Multiply>({interpolate_convert_op, pattern::any_input()});+ const auto& interpolate_op =pattern::wrap_type<v11::Interpolate>({pattern::any_input(), interpolate_mul_op, pattern::any_input()});// aten::randint case- auto rand_op = pattern::wrap_type<v8::RandomUniform>({list, pattern::any_input(), pattern::any_input()});- auto lc_pattern = std::make_shared<pattern::op::Or>(OutputVector{reshape_op,- roll_op,- broadcast_op,- adapool_op,- shape_of_op,- equal_op,- select_op,- expand_op,- tile_op,- transpose_op,- vsplit_op,- interpolate_op,- rand_op});+ const auto& rand_op = pattern::wrap_type<v8::RandomUniform>({list, pattern::any_input(), pattern::any_input()});+ const auto& lc_pattern = std::make_shared<pattern::op::Or>(OutputVector{reshape_op,+ roll_op,+ broadcast_op,+ adapool_op,+ shape_of_op,+ equal_op,+ select_op,+ expand_op,+ tile_op,+ transpose_op,+ vsplit_op,+ interpolate_op,+ rand_op});ov::matcher_pass_callback callback = [=](pattern::Matcher& m) {auto& pattern_map = m.get_pattern_value_map();diff --git a/src/frontends/pytorch/src/transforms/min_max_prim_list_construct_replacer.cpp b/src/frontends/pytorch/src/transforms/min_max_prim_list_construct_replacer.cppindex f2e092d316c..8c056067b6b 100644--- a/src/frontends/pytorch/src/transforms/min_max_prim_list_construct_replacer.cpp+++ b/src/frontends/pytorch/src/transforms/min_max_prim_list_construct_replacer.cpp@@ -26,12 +26,12 @@ namespace pass {using namespace ov::op;MinMaxPrimListConstructReplacer::MinMaxPrimListConstructReplacer() {- auto op = ov::pass::pattern::wrap_type<ov::op::util::FrameworkNode>();+ const auto& op = ov::pass::pattern::wrap_type<ov::op::util::FrameworkNode>();ov::matcher_pass_callback callback = [](ov::pass::pattern::Matcher& m) {bool is_min = false;- auto max_op = cast_fw_node(m.get_match_root(), "prim::max");- auto min_op = cast_fw_node(m.get_match_root(), "prim::min");+ const auto& max_op = cast_fw_node(m.get_match_root(), "prim::max");+ const auto& min_op = cast_fw_node(m.get_match_root(), "prim::min");std::shared_ptr<ov::op::util::FrameworkNode> op;if (!max_op && !min_op) {return false;diff --git a/src/frontends/pytorch/src/transforms/prim_list_construct_pad.cpp b/src/frontends/pytorch/src/transforms/prim_list_construct_pad.cppindex a8483cd8829..480d37d0168 100644--- a/src/frontends/pytorch/src/transforms/prim_list_construct_pad.cpp+++ b/src/frontends/pytorch/src/transforms/prim_list_construct_pad.cpp@@ -59,7 +59,7 @@ const std::unordered_map<std::string, PadMode> PAD_MODES = {{"constant", PadModePrimListConstructPadReplacer::PrimListConstructPadReplacer() {// transformation for case aten::pad + prim::ListConstruct as paddings- auto pad_op = ov::pass::pattern::wrap_type<ov::op::util::FrameworkNode>();+ const auto& pad_op = ov::pass::pattern::wrap_type<ov::op::util::FrameworkNode>();ov::matcher_pass_callback callback = [](ov::pass::pattern::Matcher& m) {Output<Node> input_node;Output<Node> padding;@@ -70,7 +70,7 @@ PrimListConstructPadReplacer::PrimListConstructPadReplacer() {mode = "constant";input_node = pad_op->input_value(0);padding = pad_op->input_value(1);- auto mode_node = pad_op->input_value(2).get_node_shared_ptr();+ const auto& mode_node = pad_op->input_value(2).get_node_shared_ptr();if (const auto& fw_node_mode = cast_fw_node(mode_node, "prim::Constant")) {const auto& attrs = fw_node_mode->get_attrs();if (attrs.find("string_value") != attrs.end()) {diff --git a/src/frontends/pytorch/src/transforms/prim_list_tuple_construct_replacer.cpp b/src/frontends/pytorch/src/transforms/prim_list_tuple_construct_replacer.cppindex 44f77188728..0c3f75360cb 100644--- a/src/frontends/pytorch/src/transforms/prim_list_tuple_construct_replacer.cpp+++ b/src/frontends/pytorch/src/transforms/prim_list_tuple_construct_replacer.cpp@@ -52,7 +52,7 @@ bool DecomposeListTupleResults::run_on_model(const std::shared_ptr<Model>& model}auto names = out.get_names();out.set_names({});- for (auto name : names) {+ for (auto& name : names) {if (!is_index(name)) {// Set first found non-index name as output name. If such name exist it will be debug nameout.set_names({name});diff --git a/src/frontends/pytorch/src/transforms/prim_list_unpack_replacer.cpp b/src/frontends/pytorch/src/transforms/prim_list_unpack_replacer.cppindex cec60b6a1a2..27d1245d475 100644--- a/src/frontends/pytorch/src/transforms/prim_list_unpack_replacer.cpp+++ b/src/frontends/pytorch/src/transforms/prim_list_unpack_replacer.cpp@@ -156,7 +156,8 @@ PrimListUnpackReplacer::PrimListUnpackReplacer() {auto range =rg.make<opset10::Range>(const_0_scalar, list_num_outs_scalar, const_1_scalar, element::i32);auto range_plus_1 = rg.make<opset10::Add>(range, const_1);- auto sections = rg.make<opset10::Concat>(OutputVector{const_0, indices_or_sections, const_max}, 0);+ auto sections =+ rg.make<opset10::Concat>(OutputVector{const_0, std::move(indices_or_sections), const_max}, 0);auto starts_tensor = rg.make<opset10::Slice>(sections, const_0, const_neg_1, const_1, const_0);auto starts =diff --git a/src/frontends/pytorch/src/transforms/string_equality_replacer.cpp b/src/frontends/pytorch/src/transforms/string_equality_replacer.cppindex 028de354665..60a12b802f2 100644--- a/src/frontends/pytorch/src/transforms/string_equality_replacer.cpp+++ b/src/frontends/pytorch/src/transforms/string_equality_replacer.cpp@@ -24,12 +24,12 @@ using namespace ov::pass;using namespace ov::op;StringEqualityReplacer::StringEqualityReplacer() {- auto framework_node_lhs = pattern::wrap_type<PtFrameworkNode>();- auto framework_node_rhs = pattern::wrap_type<PtFrameworkNode>();- auto equal_op = pattern::wrap_type<v1::Equal>({framework_node_lhs, framework_node_rhs});- auto not_equal_op = pattern::wrap_type<v1::NotEqual>({framework_node_lhs, framework_node_rhs});+ const auto& framework_node_lhs = pattern::wrap_type<PtFrameworkNode>();+ const auto& framework_node_rhs = pattern::wrap_type<PtFrameworkNode>();+ const auto& equal_op = pattern::wrap_type<v1::Equal>({framework_node_lhs, framework_node_rhs});+ const auto& not_equal_op = pattern::wrap_type<v1::NotEqual>({framework_node_lhs, framework_node_rhs});- auto string_equality_pattern = std::make_shared<pattern::op::Or>(OutputVector{equal_op, not_equal_op});+ const auto& string_equality_pattern = std::make_shared<pattern::op::Or>(OutputVector{equal_op, not_equal_op});ov::matcher_pass_callback callback = [=](pattern::Matcher& m) {auto& pattern_map = m.get_pattern_value_map();diff --git a/src/frontends/pytorch/src/transforms/torchfx_gptq_pattern_replacer.cpp b/src/frontends/pytorch/src/transforms/torchfx_gptq_pattern_replacer.cppindex 95682cd784f..3108765b21e 100644--- a/src/frontends/pytorch/src/transforms/torchfx_gptq_pattern_replacer.cpp+++ b/src/frontends/pytorch/src/transforms/torchfx_gptq_pattern_replacer.cpp@@ -52,28 +52,28 @@ void write_u4_data(void* array, size_t index, uint32_t data) {};GPTQDecompressionReplacer::GPTQDecompressionReplacer() {- auto const_1 = wrap_type<v0::Constant>();- auto const_2 = wrap_type<v0::Constant>();- auto unsqueeze_1 = wrap_type<v0::Unsqueeze>({const_1, const_2});- auto const_abs = wrap_type<v0::Constant>();- auto abs = wrap_type<v0::Abs>({const_abs});- auto broadcast_3 = wrap_type<ov::op::v3::Broadcast>({unsqueeze_1, abs});- auto const_6 = wrap_type<v0::Constant>();- auto const_7 = wrap_type<v0::Constant>();- auto unsqueeze_2 = wrap_type<v0::Unsqueeze>({const_6, const_7});- auto bitwise_right_shift = wrap_type<ov::op::util::FrameworkNode>({broadcast_3, unsqueeze_2});- auto convert_1 = wrap_type<v0::Convert>({bitwise_right_shift});- auto const_8 = wrap_type<v0::Constant>();- auto convert_2 = wrap_type<v0::Convert>({const_8});- auto bitwise_and = wrap_type<ov::op::v13::BitwiseAnd>({convert_1, convert_2});-- ov::matcher_pass_callback callback = [=](Matcher& m) {+ const auto& const_1 = wrap_type<v0::Constant>();+ const auto& const_2 = wrap_type<v0::Constant>();+ const auto& unsqueeze_1 = wrap_type<v0::Unsqueeze>({const_1, const_2});+ const auto& const_abs = wrap_type<v0::Constant>();+ const auto& abs = wrap_type<v0::Abs>({const_abs});+ const auto& broadcast_3 = wrap_type<ov::op::v3::Broadcast>({unsqueeze_1, abs});+ const auto& const_6 = wrap_type<v0::Constant>();+ const auto& const_7 = wrap_type<v0::Constant>();+ const auto& unsqueeze_2 = wrap_type<v0::Unsqueeze>({const_6, const_7});+ const auto& bitwise_right_shift = wrap_type<ov::op::util::FrameworkNode>({broadcast_3, unsqueeze_2});+ const auto& convert_1 = wrap_type<v0::Convert>({bitwise_right_shift});+ const auto& const_8 = wrap_type<v0::Constant>();+ const auto& convert_2 = wrap_type<v0::Convert>({const_8});+ const auto& bitwise_and = wrap_type<ov::op::v13::BitwiseAnd>({convert_1, convert_2});++ ov::matcher_pass_callback callback = [unsqueeze_1](Matcher& m) {auto bitwise_and = m.get_match_root();if (!bitwise_and) {return false;}const auto& pattern_map = m.get_pattern_value_map();- auto input_node = pattern_map.at(unsqueeze_1).get_node_shared_ptr();+ const auto& input_node = pattern_map.at(unsqueeze_1).get_node_shared_ptr();auto weights_u32 = std::dynamic_pointer_cast<v0::Constant>(input_node->get_input_node_shared_ptr(0));auto axis = std::dynamic_pointer_cast<v0::Constant>(input_node->get_input_node_shared_ptr(1));auto axis_data = axis->get_data_ptr<uint32_t>();@@ -118,7 +118,7 @@ GPTQDecompressionReplacer::GPTQDecompressionReplacer() {}}- copy_runtime_info_and_name(weights_u32, {new_const}, {weights_u32, bitwise_and, bitwise_right_shift});+ copy_runtime_info_and_name(weights_u32, {new_const}, {weights_u32, bitwise_and});auto new_convert = std::make_shared<v0::Convert>(new_const, bitwise_and->get_output_element_type(0));copy_runtime_info_and_name(bitwise_and, {new_convert}, {input_node});@@ -131,22 +131,22 @@ GPTQDecompressionReplacer::GPTQDecompressionReplacer() {};GPTQMultPatternReplacer::GPTQMultPatternReplacer() {- auto const_1_1 = wrap_type<v0::Constant>();- auto convert_1 = wrap_type<v0::Convert>({const_1_1});- auto const_1_2 = wrap_type<v0::Constant>();- auto convert_2 = wrap_type<v0::Convert>({const_1_2});- auto add = wrap_type<v1::Add>({convert_1, convert_2});- auto const_2 = wrap_type<v0::Constant>();- auto reshape_1 = wrap_type<v1::Reshape>({add, const_2});- auto const_3_1 = wrap_type<v0::Constant>();- auto convert_4 = wrap_type<v0::Convert>({const_3_1});- auto const_3_2 = wrap_type<v0::Constant>();- auto reshape_2 = wrap_type<v1::Reshape>({convert_4, const_3_2});- auto subtract = wrap_type<v1::Subtract>({reshape_2, reshape_1});- auto convert_3 = wrap_type<v0::Convert>({subtract});- auto const_4_1 = wrap_type<v0::Constant>();- auto const_4_2 = wrap_type<v0::Constant>();- auto reshape_3 = wrap_type<v1::Reshape>({const_4_1, const_4_2});+ const auto& const_1_1 = wrap_type<v0::Constant>();+ const auto& convert_1 = wrap_type<v0::Convert>({const_1_1});+ const auto& const_1_2 = wrap_type<v0::Constant>();+ const auto& convert_2 = wrap_type<v0::Convert>({const_1_2});+ const auto& add = wrap_type<v1::Add>({convert_1, convert_2});+ const auto& const_2 = wrap_type<v0::Constant>();+ const auto& reshape_1 = wrap_type<v1::Reshape>({add, const_2});+ const auto& const_3_1 = wrap_type<v0::Constant>();+ const auto& convert_4 = wrap_type<v0::Convert>({const_3_1});+ const auto& const_3_2 = wrap_type<v0::Constant>();+ const auto& reshape_2 = wrap_type<v1::Reshape>({convert_4, const_3_2});+ const auto& subtract = wrap_type<v1::Subtract>({reshape_2, reshape_1});+ const auto& convert_3 = wrap_type<v0::Convert>({subtract});+ const auto& const_4_1 = wrap_type<v0::Constant>();+ const auto& const_4_2 = wrap_type<v0::Constant>();+ const auto& reshape_3 = wrap_type<v1::Reshape>({const_4_1, const_4_2});auto mult = wrap_type<v1::Multiply>({reshape_3, convert_3});@@ -174,8 +174,8 @@ GPTQMultPatternReplacer::GPTQMultPatternReplacer() {auto add_in1_ptr = convert_2_input_const->get_data_ptr<uint8_t>();if (!add_in1_ptr)return false;- auto add_in0_shape = add_input0_const->get_shape();- auto static_shape_1 = reshape_node->get_shape();+ const auto& add_in0_shape = add_input0_const->get_shape();+ const auto& static_shape_1 = reshape_node->get_shape();size_t add_in0_size = shape_size(add_in0_shape);auto add_replace_const = std::make_shared<v0::Constant>(element::f32, static_shape_1);auto add_replace_ptr = const_cast<float*>(reinterpret_cast<const float*>(add_replace_const->get_data_ptr()));@@ -191,7 +191,7 @@ GPTQMultPatternReplacer::GPTQMultPatternReplacer() {add_replace_ptr[i] = (float)val;}- auto static_shape_2 = reshape2_node->get_shape();+ const auto& static_shape_2 = reshape2_node->get_shape();auto reshape2_in0_const = std::dynamic_pointer_cast<v0::Constant>(convert_4_node->get_input_node_shared_ptr(0));auto sub_replace_const = std::make_shared<v0::Constant>(reshape2_in0_const->get_element_type(),static_shape_2,@@ -199,7 +199,7 @@ GPTQMultPatternReplacer::GPTQMultPatternReplacer() {auto new_convert_node = std::make_shared<v0::Convert>(sub_replace_const, element::f32);auto new_sub_node = std::make_shared<v1::Subtract>(new_convert_node, add_replace_const);- auto static_shape_3 = reshape3_node->get_shape();+ const auto& static_shape_3 = reshape3_node->get_shape();auto reshape3_in0_const = std::dynamic_pointer_cast<v0::Constant>(reshape3_node->get_input_node_shared_ptr(0));auto mult_scale_const = std::make_shared<v0::Constant>(reshape3_in0_const->get_element_type(),static_shape_3,diff --git a/src/frontends/pytorch/src/transforms/tuple_unpack_replacer.cpp b/src/frontends/pytorch/src/transforms/tuple_unpack_replacer.cppindex a9690c8a37c..7ea557fa816 100644--- a/src/frontends/pytorch/src/transforms/tuple_unpack_replacer.cpp+++ b/src/frontends/pytorch/src/transforms/tuple_unpack_replacer.cpp@@ -145,8 +145,8 @@ bool TupleUnpackInBodyReplacer::run_on_model(const std::shared_ptr<Model>& modelint else_p_idx = inputs_mapping[j].second;if (else_p_idx > else_body_idx && else_body_idx != -1)else_p_idx--;- auto then_p = then_p_idx == -1 ? nullptr : then_body->get_parameters()[then_p_idx];- auto else_p = else_p_idx == -1 ? nullptr : else_body->get_parameters()[else_p_idx];+ const auto& then_p = then_p_idx == -1 ? nullptr : then_body->get_parameters()[then_p_idx];+ const auto& else_p = else_p_idx == -1 ? nullptr : else_body->get_parameters()[else_p_idx];if (then_p || else_p)new_if->set_invariant_inputs(if_op->input_value(j), {then_p, else_p});}diff --git a/src/frontends/pytorch/src/transforms/u4_block_repack.cpp b/src/frontends/pytorch/src/transforms/u4_block_repack.cppindex 8d268d111d3..9fc4d2c8b10 100644--- a/src/frontends/pytorch/src/transforms/u4_block_repack.cpp+++ b/src/frontends/pytorch/src/transforms/u4_block_repack.cpp@@ -22,22 +22,22 @@ using namespace ov::op;using namespace ov::pass::pattern;U4BlockRepack::U4BlockRepack(bool is_symmetrical) {- const auto m_constant = ov::pass::pattern::wrap_type<ov::op::v0::Constant>();- const auto m_reshape1 = ov::pass::pattern::wrap_type<ov::op::v1::Reshape>({m_constant, any_input()});- const auto m_transpose = ov::pass::pattern::wrap_type<ov::op::v1::Transpose>({m_reshape1, any_input()});- const auto m_reshape2 = ov::pass::pattern::wrap_type<ov::op::v1::Reshape>({m_transpose, any_input()});+ const auto& m_constant = ov::pass::pattern::wrap_type<ov::op::v0::Constant>();+ const auto& m_reshape1 = ov::pass::pattern::wrap_type<ov::op::v1::Reshape>({m_constant, any_input()});+ const auto& m_transpose = ov::pass::pattern::wrap_type<ov::op::v1::Transpose>({m_reshape1, any_input()});+ const auto& m_reshape2 = ov::pass::pattern::wrap_type<ov::op::v1::Reshape>({m_transpose, any_input()});auto pack_byte = [](uint8_t lo, uint8_t hi) -> uint8_t {return (hi << 4) | (lo & 0x0F);}; // swap halfs because Convert op assumes this layout- std::function<uint8_t(const uint8_t*, size_t)> get_u4 = [](const uint8_t* src, size_t idx) {+ const std::function<uint8_t(const uint8_t*, size_t)>& get_u4 = [](const uint8_t* src, size_t idx) {const size_t byte_idx = idx / 2;const uint8_t bit_shift = 4 * (idx % 2);return (src[byte_idx] >> bit_shift) & 0xF;};- std::function<uint8_t(const uint8_t*, size_t)> get_i4 = [get_u4](const uint8_t* src, size_t idx) {+ const std::function<uint8_t(const uint8_t*, size_t)>& get_i4 = [get_u4](const uint8_t* src, size_t idx) {// by flipping first bit we get same effect as subtracting 8return get_u4(src, idx) ^ 0b1000;};diff --git a/src/frontends/pytorch/src/translate_session.cpp b/src/frontends/pytorch/src/translate_session.cppindex eb7c6c08137..a17e1b7d03b 100644--- a/src/frontends/pytorch/src/translate_session.cpp+++ b/src/frontends/pytorch/src/translate_session.cpp@@ -21,7 +21,7 @@ namespace pytorch {using namespace ov::op;TranslateSession::TranslateSession(const ov::frontend::InputModel::Ptr& input_model,- const std::map<std::string, CreatorFunction>& translator_map,+ const std::unordered_map<std::string, CreatorFunction>& translator_map,const std::shared_ptr<TelemetryExtension>& telemetry): m_input_model(input_model),m_translator_map(translator_map),@@ -70,9 +70,10 @@ std::shared_ptr<ov::Model> TranslateSession::translate_graph(const ov::frontend:// process model rt_infoauto rt_info = pytorch_model->get_decoder()->get_rt_info();- for (auto item : rt_info) {+ for (const auto& item : rt_info) {model->set_rt_info(item.second, item.first);}+ model->set_rt_info("decoder_type_name", pytorch_model->decoder_type_name());return model;}@@ -99,10 +100,10 @@ std::shared_ptr<Model> TranslateSession::convert_pytorch_model(element::Type type = pytorch_place->get_element_type();PartialShape pshape = pytorch_place->get_partial_shape();auto parameter = std::make_shared<v0::Parameter>(type, pshape);- if (pytorch_place->get_names().size() > 0)- parameter->set_friendly_name(pytorch_place->get_names().at(0));+ if (!pytorch_place->get_names().empty())+ parameter->set_friendly_name(pytorch_place->get_names().front());encode_tensor_name(parameter->output(0), tensor_id);- parameters->push_back(parameter);+ parameters->emplace_back(parameter);(*tensor_map)[tensor_id] = parameter;}} else {@@ -119,7 +120,7 @@ std::shared_ptr<Model> TranslateSession::convert_pytorch_model(auto parameter = std::make_shared<v0::Parameter>(type, pshape);parameter->set_friendly_name(pytorch_model->get_input_signature_name(i));encode_tensor_name(parameter->output(0), inputs.at(i), {pytorch_model->get_input_debug_name(i)});- parameters->push_back(parameter);+ parameters->emplace_back(parameter);(*tensor_map)[inputs.at(i)] = parameter;}}@@ -176,15 +177,17 @@ 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;for (size_t i = 0; i < fw_outputs.size(); ++i) {size_t fw_tensor_id = node->output(i);- if (node->inputs().size() > 0 && node->may_produce_alias(0, i)) {+ if (has_inputs && 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?- auto in_tensor_id = node->inputs().at(0);- if (m_may_be_alias.count(fw_tensor_id)) {+ 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) = m_may_be_alias.at(fw_tensor_id);+ std::tie(recorded_in_tensor_id, recorded_node, std::ignore) = alias_iter->second;FRONT_END_GENERAL_CHECK(recorded_in_tensor_id == in_tensor_id,"Operation ",context.get_op_type(),@@ -199,14 +202,16 @@ std::shared_ptr<Model> TranslateSession::convert_pytorch_model(OPENVINO_DEBUG("Registered alias: ",fw_tensor_id," of tensor: ",- node->inputs().at(0),+ in_tensor_id," of operation: ",context.get_op_type());}FRONT_END_GENERAL_CHECK(tensor_map->find(fw_tensor_id) == tensor_map->end(),"Duplicated producer for PT value with unique ID: ",fw_tensor_id);- auto out_type = context.get_output_type(i);++#ifdef ENABLE_OPENVINO_DEBUG+ const auto out_type = context.get_output_type(i);if (out_type.is<element::Type>()) {if (!converted_outputs[i].get_element_type().compatible(out_type.as<element::Type>())) {OPENVINO_DEBUG("[WARNING] Produced output type for operation ",@@ -219,6 +224,7 @@ std::shared_ptr<Model> TranslateSession::convert_pytorch_model(out_type.as<element::Type>());}}+#endif(*tensor_map)[fw_tensor_id] = converted_outputs[i];encode_tensor_name(converted_outputs[i], fw_tensor_id, {node->get_output_debug_name(i)});}@@ -236,7 +242,7 @@ std::shared_ptr<Model> TranslateSession::convert_pytorch_model(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);- FRONT_END_GENERAL_CHECK(ov_output.get_names().size() > 0,+ FRONT_END_GENERAL_CHECK(!ov_output.get_names().empty(),"Tensor doesn't have name, while it should have name: ",tensor_id);auto result = std::make_shared<v0::Result>(ov_output);@@ -245,18 +251,18 @@ std::shared_ptr<Model> TranslateSession::convert_pytorch_model(} else {for (size_t i = 0; i < pytorch_model->num_of_outputs(); ++i) {size_t id = pytorch_model->output(i);- if (tensor_map->find(id) == tensor_map->end()) {+ auto it = tensor_map->find(id);+ if (it == tensor_map->end()) {// Not found in this scope, adding Parameter to connect to external scopeauto parameter = std::make_shared<v0::Parameter>(element::dynamic, PartialShape::dynamic());encode_tensor_name(parameter->output(0), id);parameters->push_back(parameter);- (*tensor_map)[id] = parameter;+ it = tensor_map->emplace(id, parameter).first;}- auto ov_output = tensor_map->at(id);- FRONT_END_GENERAL_CHECK(ov_output.get_names().size() > 0,+ 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>(ov_output);+ auto result = std::make_shared<v0::Result>(it->second);results.push_back(result);}}@@ -307,11 +313,22 @@ std::shared_ptr<Model> TranslateSession::convert_pytorch_model(OutputVector TranslateSession::convert_node(const NodeContext& context) {std::string exception;try {- auto it = m_translator_map.find(context.get_op_type());+ const auto& op_type = context.get_op_type();+ auto it = m_translator_map.find(op_type);if (it != m_translator_map.end()) {return it->second(context);+ } else if (op_type.back() == '_') {+ // inplace op case+ std::string op_type_cut = op_type.substr(0, op_type.size() - 1);+ auto it = m_translator_map.find(op_type_cut);+ if (it != m_translator_map.end()) {+ const auto& res = it->second(context);+ FRONT_END_OP_CONVERSION_CHECK(res.size() == 1, "inplace op must have single output.");+ context.mutate_input(0, res[0]);+ return res;+ }}- OPENVINO_DEBUG("No translator found for: ", context.get_op_type(), "\n");+ OPENVINO_DEBUG("No translator found for: ", op_type, "\n");} catch (std::exception& e) {exception = e.what();} catch (...) {@@ -332,7 +349,7 @@ OutputVector TranslateSession::convert_node(const NodeContext& context) {void TranslateSession::encode_tensor_name(Output<Node> output,size_t tensor_idx,- std::vector<std::string> additional_names) {+ const std::vector<std::string>& additional_names) {if (!output.get_names().empty()) {OPENVINO_DEBUG("Tensor names already exist: ",output.get_any_name(),@@ -342,22 +359,21 @@ void TranslateSession::encode_tensor_name(Output<Node> output,return;}auto name = std::to_string(tensor_idx);- std::unordered_set<std::string> names;- names.insert(name);- if (additional_names.size() > 0) {+ std::unordered_set<std::string> names = {name};+ if (!additional_names.empty()) {names.insert(additional_names.begin(), additional_names.end());}- if (m_counter_map.count(tensor_idx)) {- auto&& pair = m_counter_map[tensor_idx];+ auto it = m_counter_map.find(tensor_idx);+ if (it != m_counter_map.end()) {+ auto& pair = it->second;auto new_name = name + '_' + std::to_string(++pair.first);- pair.second.set_names({new_name});+ pair.second.set_names({std::move(new_name)});pair.second = output;- output.set_names(names);} else {- m_counter_map[tensor_idx] = {0, output};- output.set_names(names);+ m_counter_map.emplace(tensor_idx, std::make_pair(0, output));}+ output.set_names(std::move(names));}namespace {@@ -424,7 +440,7 @@ using ReversepropCreatorFunction = std::function<ov::Output<ov::Node>(const OutpOutput<Node> TranslateSession::get_reverseprop_op(const std::shared_ptr<TorchDecoder>& node,const Output<Node>& direct_op_output,const Output<Node>& value) {- std::map<std::string, ReversepropCreatorFunction> backprop_map = {+ static const std::map<std::string, ReversepropCreatorFunction> backprop_map = {{"aten::slice", slice_reverseprop},{"aten::select", select_reverseprop},};diff --git a/src/frontends/pytorch/src/translate_session.hpp b/src/frontends/pytorch/src/translate_session.hppindex 723e94e2511..df669dbabe1 100644--- a/src/frontends/pytorch/src/translate_session.hpp+++ b/src/frontends/pytorch/src/translate_session.hpp@@ -18,7 +18,7 @@ namespace pytorch {class TranslateSession {public:TranslateSession(const frontend::InputModel::Ptr& input_model,- const std::map<std::string, CreatorFunction>& translator_map,+ const std::unordered_map<std::string, CreatorFunction>& translator_map,const std::shared_ptr<TelemetryExtension>& telemetry);~TranslateSession();std::shared_ptr<Model> get_converted_model();@@ -42,7 +42,7 @@ public:/// \brief Writes pytorch tensor index into openvino tensorvoid encode_tensor_name(Output<Node> tensor_desc,size_t tensor_idx,- std::vector<std::string> additional_names = {});+ const std::vector<std::string>& additional_names = {});/// \brief Gets pytorch tensor index from openvino tensorsize_t decode_tensor_name(const Output<Node>& tensor_desc);@@ -55,7 +55,7 @@ private:OutputVector convert_node(const NodeContext& context);const frontend::InputModel::Ptr m_input_model;- const std::map<std::string, CreatorFunction>& m_translator_map;+ const std::unordered_map<std::string, CreatorFunction>& m_translator_map;std::shared_ptr<TelemetryExtension> m_telemetry;std::shared_ptr<Model> m_ov_model;diff --git a/src/frontends/pytorch/src/utils.cpp b/src/frontends/pytorch/src/utils.cppindex a2c4b35529d..b096da45f25 100644--- a/src/frontends/pytorch/src/utils.cpp+++ b/src/frontends/pytorch/src/utils.cpp@@ -130,9 +130,7 @@ std::shared_ptr<Node> get_node_axes_range(const NodeContext& context, const OutpOutput<Node> normalize_axis(const NodeContext& context, const Output<Node>& axis, const Output<Node>& rank) {auto axis_rank = context.mark_node(std::make_shared<opset10::Add>(axis, rank));- auto is_less = context.mark_node(std::make_shared<opset10::Less>(axis_rank, rank));- auto new_axis = context.mark_node(std::make_shared<opset10::Select>(is_less, axis_rank, axis));- return new_axis;+ return context.mark_node(std::make_shared<opset10::Mod>(axis_rank, rank));}std::shared_ptr<Node> numel(const NodeContext& context, const Output<Node>& x, element::Type output_type) {@@ -217,14 +215,13 @@ std::shared_ptr<PtFrameworkNode> create_fw_node_with_exception(const NodeContextbool skip_subgraphs = false) {auto fw_node = std::make_shared<PtFrameworkNode>(context.get_decoder(), inputs, num_outputs, false, skip_subgraphs);context.mark_node(fw_node);- auto attrs = fw_node->get_attrs();- std::string message(exception_message);- if (!message.empty()) {- message = "Exception happened during conversion of operation " + fw_node->get_friendly_name() +- " with schema " + context.get_schema() + '\n' + message;+ if (!exception_message.empty()) {+ auto attrs = fw_node->get_attrs();+ std::string message = "Exception happened during conversion of operation " + fw_node->get_friendly_name() ++ " with schema " + context.get_schema() + '\n' + exception_message;+ attrs[PtFrameworkNode::failed_conversion_key] = std::move(message);+ fw_node->set_attrs(attrs);}- attrs[PtFrameworkNode::failed_conversion_key] = message;- fw_node->set_attrs(attrs);return fw_node;}} // namespace@@ -537,7 +534,7 @@ void copy_runtime_info_and_name(const std::shared_ptr<Node>& from,} else {unique_names.insert(new_name);}- op->set_friendly_name(new_name);+ op->set_friendly_name(std::move(new_name));}}copy_runtime_info(from, to);diff --git a/src/frontends/pytorch/src/utils_quantize.cpp b/src/frontends/pytorch/src/utils_quantize.cppindex ad61dc38a95..ccf7f20785b 100644--- a/src/frontends/pytorch/src/utils_quantize.cpp+++ b/src/frontends/pytorch/src/utils_quantize.cpp@@ -256,9 +256,9 @@ std::shared_ptr<Node> u4_compression_stack(const OutputVector& list_elems, int64// Pattern detected, weights_u8 is target u8 packed constant with weights// Part 2: Form u4 constant by repacking of the original weights_u8- // Repacking transformes half of lanes to interleaved representation.+ // Repacking transforms half of lanes to interleaved representation.- auto u8_shape = weights_u8->get_shape();+ const auto& u8_shape = weights_u8->get_shape();size_t full_size = shape_size(u8_shape);auto src = weights_u8->get_data_ptr<uint8_t>();@@ -268,7 +268,7 @@ std::shared_ptr<Node> u4_compression_stack(const OutputVector& list_elems, int64auto dst = const_cast<uint8_t*>(reinterpret_cast<const uint8_t*>(new_const->get_data_ptr()));std::copy(src, src + full_size, dst); // TODO: Avoid copying, reuse the same constant- copy_runtime_info_and_name(weights_u8, {new_const}, {weights_u8, bitwise_and, bitwise_shift});+ copy_runtime_info_and_name(weights_u8, {new_const}, {weights_u8, std::move(bitwise_and), bitwise_shift});return new_const;}