OpenVINO™ is an open source toolkit for optimizing and deploying AI inference
C++ aicomputer-visiondeep-learningdeploy-aidiffusion-modelsgenerative-aigood-first-issueinferencellm-inferencenatural-language-processingnlpopenvinooptimize-aiperformance-boostrecommendation-systemspeech-recognitionstable-diffusiontransformersyolo
[PyTorch] Preserve module paths in FX operation names (#40069)
Maxim Vafinf538c16a249b
diff --git a/src/bindings/python/src/openvino/frontend/pytorch/fx_decoder.py b/src/bindings/python/src/openvino/frontend/pytorch/fx_decoder.pyindex 08c633b5034..80dde866c64 100644--- a/src/bindings/python/src/openvino/frontend/pytorch/fx_decoder.py+++ b/src/bindings/python/src/openvino/frontend/pytorch/fx_decoder.py@@ -803,6 +803,9 @@ class TorchFXPythonDecoder (BaseFXDecoder):return max_out_id + 1def _node_name_prefix(self):+ for module_path, _ in reversed(self.pt_module.meta.get("nn_module_stack", {}).values()):+ if module_path:+ return f"{module_path}/{self.pt_module.name}"return self.pt_module.namedef as_constant(self):diff --git a/src/frontends/pytorch/README.md b/src/frontends/pytorch/README.mdindex b4eddd3c63d..6da5b2a812b 100644--- a/src/frontends/pytorch/README.md+++ b/src/frontends/pytorch/README.md@@ -87,6 +87,21 @@ This region trace runs after export for both models and supplied exported graphsThe original graph stays unchanged, no OpenVINO loops are introduced, and thetrace must not introduce new shape guards.+### Operation names in exported models++When converting with `openvino.convert_model(..., dynamo=True)` or converting a+`torch.export.ExportedProgram`, operation friendly names include the original+module path when it is available in the FX node's `nn_module_stack` metadata:+`<module path>/<FX node name>/<PyTorch operation>/<OpenVINO operation>`.+For example, `encoder.0.activation/relu/aten.relu.default/Relu` identifies a ReLU+inside `encoder.0.activation`. Functional operations use their containing+module's path, and the FX node name distinguishes repeated operations.++Nodes without a non-empty module path retain names without that prefix.+This does not change input/output tensor names or TorchScript conversion names.+Subsequent graph optimizations may fuse or replace operations, so names do not+guarantee a one-to-one mapping to the original graph.+## How to Implement Support for a New PyTorch OperationPyTorch conversion into the OpenVINO opset operations consists of two stages:diff --git a/tests/layer_tests/py_frontend_tests/test_torch_decoder.py b/tests/layer_tests/py_frontend_tests/test_torch_decoder.pyindex 1c337905685..914e86b0aaa 100644--- a/tests/layer_tests/py_frontend_tests/test_torch_decoder.py+++ b/tests/layer_tests/py_frontend_tests/test_torch_decoder.py@@ -951,6 +951,45 @@ def test_pytorch_fx_frontend_keeps_first_input_named_self(model, example, names)np.testing.assert_allclose(result, (flat[0] * 2 + flat[1] * 3).numpy())[email protected]("module_stack,expected_prefix", [+ (None, "relu"),+ ({}, "relu"),+ ({"root": ("", "Model")}, "relu"),+ ({+ "root": ("", "Model"),+ "exporter_generated_key": ("encoder", "Block"),+ "another_generated_key": ("encoder.activation", "ReLU"),+ }, "encoder.activation/relu"),+])+def test_pytorch_fx_decoder_friendly_name(module_stack, expected_prefix):+ import openvino.opset13 as ops+ from openvino import Type+ from openvino.frontend.pytorch.fx_decoder import IndexedNodes, TorchFXPythonDecoder++ graph = torch.fx.Graph()+ data = graph.placeholder("data")+ relu = graph.call_function(torch.ops.aten.relu.default, (data,), name="relu")+ graph.output(relu)+ if module_stack is not None:+ relu.meta["nn_module_stack"] = module_stack+ graph_module = torch.fx.GraphModule(torch.nn.Module(), graph)+ names_seen = []++ def mark_node_callback(decoder, node):+ names_seen.append(node.get_friendly_name())+ node.set_friendly_name("callback/" + node.get_friendly_name())++ decoder = TorchFXPythonDecoder(+ relu, graph_module, IndexedNodes(graph.nodes), mark_node_callback=mark_node_callback)+ node = ops.relu(ops.parameter([2, 4], Type.f32))++ assert decoder.mark_node(node) is node+ expected_name = expected_prefix + "/aten.relu.default/Relu"+ assert names_seen == [expected_name]+ assert node.get_friendly_name() == "callback/" + expected_name++@pytest.mark.precommit@pytest.mark.parametrize("return_indices", [False, True])def test_pytorch_fx_pool_without_output_metadata(return_indices):diff --git a/tests/layer_tests/py_frontend_tests/test_torch_frontend.py b/tests/layer_tests/py_frontend_tests/test_torch_frontend.pyindex c6fa0a059c1..9cd739377e6 100644--- a/tests/layer_tests/py_frontend_tests/test_torch_frontend.py+++ b/tests/layer_tests/py_frontend_tests/test_torch_frontend.py@@ -2685,6 +2685,82 @@ class TestBuildDynamicShapes:class TestConvertModelDynamo:"""Tests for convert_model with dynamo=True (torch.export path)."""+ @pytest.mark.precommit+ @pytest.mark.parametrize("model_format", ["dynamo", "exported_program", "decomposed"])+ def test_module_friendly_names(self, model_format, tmp_path):+ from openvino import Core, convert_model, serialize+ from openvino.frontend.pytorch.fx_decoder import TorchFXPythonDecoder++ class Block(torch.nn.Module):+ def __init__(self):+ super().__init__()+ self.activation = torch.nn.ReLU()++ def forward(self, x):+ x = self.activation(x)+ return torch.sigmoid(x) + torch.sigmoid(x + 0.5)++ class Model(torch.nn.Module):+ def __init__(self):+ super().__init__()+ self.encoder = torch.nn.Sequential(Block(), Block())++ def forward(self, x):+ return {"prediction": self.encoder(x)}++ model = Model().eval()+ example = (torch.linspace(-2, 2, 8).reshape(2, 4),)+ exported = torch.export.export(model, example)+ if model_format == "decomposed":+ exported = exported.run_decompositions()+ if model_format == "dynamo":+ converted = convert_model(model, example_input=example, dynamo=True)+ else:+ converted = convert_model(exported)++ expected_names = {+ "encoder.0.activation/relu/aten.relu.default/Relu",+ "encoder.1.activation/relu_1/aten.relu.default/Relu",+ "encoder.0/sigmoid/aten.sigmoid.default/Sigmoid",+ "encoder.0/sigmoid_1/aten.sigmoid.default/Sigmoid",+ "encoder.1/sigmoid_2/aten.sigmoid.default/Sigmoid",+ "encoder.1/sigmoid_3/aten.sigmoid.default/Sigmoid",+ }+ names = [node.get_friendly_name() for node in converted.get_ordered_ops()+ if node.get_type_name() in ("Relu", "Sigmoid")]+ assert set(names) == expected_names+ assert len(names) == len(expected_names)++ graph_module = exported.module()+ for node in graph_module.graph.nodes:+ node.meta.pop("nn_module_stack", None)+ unscoped = convert_model(TorchFXPythonDecoder(+ graph_module, output_names=["prediction"]))+ assert [port.get_names() for port in converted.inputs] == [+ port.get_names() for port in unscoped.inputs]+ assert [port.get_names() for port in converted.outputs] == [+ port.get_names() for port in unscoped.outputs]++ core = Core()+ compiled = core.compile_model(converted, "CPU", default_cfg)+ np.testing.assert_allclose(+ compiled([example[0].numpy()])[0],+ model(*example)["prediction"].numpy(), atol=1e-6, rtol=1e-6)++ path = tmp_path / "scoped.xml"+ serialize(converted, path)+ reloaded = core.read_model(path)+ assert [node.get_friendly_name() for node in reloaded.get_ordered_ops()+ if node.get_type_name() in ("Relu", "Sigmoid")] == names++ if model_format == "dynamo":+ traced = convert_model(model, example_input=example)+ assert {node.get_friendly_name() for node in traced.get_ordered_ops()+ if node.get_type_name() == "Relu"} == {+ "__module.encoder.0.activation/aten::relu/Relu",+ "__module.encoder.1.activation/aten::relu/Relu",+ }+def test_basic(self):from openvino import convert_model, compile_model