Skip to content

OpenVINO™ is an open source toolkit for optimizing and deploying AI inference

[PT FE] Name flattened container inputs correctly in the FX decoder (#39387)

Somay kousis31c323a0e374
diff --git a/src/bindings/python/src/openvino/frontend/pytorch/fx_decoder.py b/src/bindings/python/src/openvino/frontend/pytorch/fx_decoder.py
index 9470aad6b57..08c633b5034 100644
--- a/src/bindings/python/src/openvino/frontend/pytorch/fx_decoder.py
+++ b/src/bindings/python/src/openvino/frontend/pytorch/fx_decoder.py
@@ -237,6 +237,7 @@ class TorchFXPythonDecoder (BaseFXDecoder):
self.input_shapes = input_shapes or []
self._input_signature = []
+ self._input_names = None
self._example_input = None
if isinstance(pt_module, torch.fx.graph_module.GraphModule):
@@ -273,9 +274,11 @@ class TorchFXPythonDecoder (BaseFXDecoder):
if not input_types or len(input_types) == 0:
self.input_types = found_types
+ placeholder_names = list(self._input_signature)
if hasattr(self.pt_module, "forward"):
input_params = inspect.signature(self.pt_module.forward).parameters
self._input_signature = list(input_params)
+ self._input_names = self._get_input_names_from_spec(placeholder_names)
elif isinstance(pt_module, torch.fx.Node):
self._nodes = nodes # passed from outer context
@@ -481,6 +484,51 @@ class TorchFXPythonDecoder (BaseFXDecoder):
return torch.export.export(model, **export_args_dict)
+ def _get_input_names_from_spec(self, placeholder_names: list) -> "list | None":
+ """Name each flattened input after its forward parameter, or after its placeholder inside a container.
+
+ Container arguments (list, tuple, dict) are flattened into several inputs, so the forward parameter names
+ do not line up with the input indices. Returns None if the input spec of the module is not available.
+ """
+ def children(spec):
+ # children() replaces the deprecated children_specs in newer torch versions
+ return list(spec.children()) if hasattr(spec, "children") else list(spec.children_specs)
+
+ in_spec = getattr(self.pt_module, "_in_spec", None)
+ if in_spec is None or in_spec.num_leaves != len(placeholder_names) or len(children(in_spec)) != 2:
+ return None
+ args_spec, kwargs_spec = children(in_spec)
+ argument_specs = list(zip(self._input_signature, children(args_spec)))
+ if kwargs_spec.num_leaves:
+ argument_specs += list(zip(kwargs_spec.context, children(kwargs_spec)))
+ names = []
+ is_container_leaf = []
+ for name, spec in argument_specs:
+ start = len(names)
+ leaves = [name] if spec.is_leaf() else placeholder_names[start:start + spec.num_leaves]
+ names += leaves
+ is_container_leaf += [not spec.is_leaf()] * len(leaves)
+ if len(names) != len(placeholder_names):
+ return None
+ # A plain argument keeps its own name. A container leaf whose placeholder name is already taken,
+ # e.g. pair[0] -> "pair_0" next to an argument called "pair_0", gets a suffix instead.
+ taken = {name for name, leaf in zip(names, is_container_leaf) if not leaf}
+ reserved = taken | {name for name, leaf in zip(names, is_container_leaf) if leaf}
+ for i, name in enumerate(names):
+ if is_container_leaf[i] and name in taken:
+ suffix = 1
+ while f"{name}_{suffix}" in reserved:
+ suffix += 1
+ name = names[i] = f"{name}_{suffix}"
+ reserved.add(name)
+ taken.add(name)
+ return names
+
+ def get_input_signature_name(self, index: int) -> str:
+ if self._input_names is not None and index < len(self._input_names):
+ return self._input_names[index]
+ return super().get_input_signature_name(index)
+
@staticmethod
def get_found_shape(value) -> str:
# If input is a tensor, read the shape from meta data
diff --git a/src/frontends/pytorch/src/input_model.cpp b/src/frontends/pytorch/src/input_model.cpp
index 87e552c00f1..f9588f9ef20 100644
--- a/src/frontends/pytorch/src/input_model.cpp
+++ b/src/frontends/pytorch/src/input_model.cpp
@@ -33,7 +33,8 @@ InputModel::InputModel(const std::shared_ptr<TorchDecoder>& model_decoder)
}
std::vector<ov::frontend::Place::Ptr> InputModel::get_inputs() const {
- if (m_inputs.size() > 0 && m_inputs[0]) {
+ // FX graphs have no receiver input, so the "self" check applies only to TorchScript
+ if (m_decoder_type_name != "fx" && m_inputs.size() > 0 && m_inputs[0]) {
// We need to remove "self" input to not confuse external users
const auto& names = m_inputs[0]->get_names();
if (std::any_of(names.cbegin(), names.cend(), [](const std::string& n) {
@@ -166,7 +167,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.empty() && m_inputs[0]) {
+ if (m_decoder_type_name != "fx" && !m_inputs.empty() && m_inputs[0]) {
// We need to remove "self" input to not confuse external users
const auto& names = m_inputs[0]->get_names();
if (std::any_of(names.cbegin(), names.cend(), [](const std::string& n) {
diff --git a/tests/layer_tests/py_frontend_tests/test_torch_decoder.py b/tests/layer_tests/py_frontend_tests/test_torch_decoder.py
index baa3298dac4..1c337905685 100644
--- a/tests/layer_tests/py_frontend_tests/test_torch_decoder.py
+++ b/tests/layer_tests/py_frontend_tests/test_torch_decoder.py
@@ -775,11 +775,182 @@ def test_pytorch_fx_decoder_extracts_signature():
example = ({"x": torch.tensor(1), "y": torch.tensor(2)}, torch.tensor(3))
em = torch.export.export(TestModel(), example)
nc_decoder = TorchFXPythonDecoder(em.module())
- assert nc_decoder.get_input_signature_name(0) == "a"
- assert nc_decoder.get_input_signature_name(1) == "b"
+ # The dict is flattened into two inputs, so each input is named after its own placeholder
+ assert [nc_decoder.get_input_signature_name(i) for i in range(3)] == ["a_x", "a_y", "b"]
assert nc_decoder._input_signature == ["a", "b"]
+def test_pytorch_fx_decoder_names_flattened_list_inputs():
+ from openvino.frontend.pytorch.fx_decoder import TorchFXPythonDecoder
+
+ class TestModel(torch.nn.Module):
+ def forward(self, pair, scale):
+ return (pair[0] + pair[1]).sum() * scale
+
+ example = ([torch.ones(2, 4), torch.ones(2, 4)], torch.tensor([10.0]))
+ em = torch.export.export(TestModel(), example)
+ decoder = TorchFXPythonDecoder(em.module())
+ assert [decoder.get_input_signature_name(i) for i in range(3)] == ["pair_0", "pair_1", "scale"]
+ assert decoder._input_signature == ["pair", "scale"]
+
+
+def test_pytorch_fx_decoder_names_mixed_and_empty_container_inputs():
+ from openvino.frontend.pytorch.fx_decoder import TorchFXPythonDecoder
+
+ class TestModel(torch.nn.Module):
+ # "input" is renamed to "input_1" by torch.export, but the input keeps the parameter name
+ def forward(self, input, empty, pair, scale):
+ return (input + pair[0] + pair[1]) * scale
+
+ example = (torch.ones(2), (), [torch.ones(2), torch.ones(2)], torch.ones(2))
+ em = torch.export.export(TestModel(), example)
+ decoder = TorchFXPythonDecoder(em.module())
+ assert [decoder.get_input_signature_name(i) for i in range(4)] == ["input", "pair_0", "pair_1", "scale"]
+
+
+def test_pytorch_dynamo_convert_builtin_named_input_with_list_input():
+ import numpy as np
+ from openvino import Core, convert_model
+
+ class TestModel(torch.nn.Module):
+ def forward(self, input, pair):
+ return (input + pair[0] + pair[1] * 2) * 3
+
+ example = (torch.ones(2, 4), [torch.ones(2, 4) * 2, torch.ones(2, 4) * 3])
+ model = TestModel()
+ expected = model(*example).numpy()
+
+ ov_model = convert_model(model, example_input=example, dynamo=True)
+
+ assert [sorted(port.get_names()) for port in ov_model.inputs] == [["input"], ["pair_0"], ["pair_1"]]
+ compiled = Core().compile_model(ov_model, "CPU")
+ result = compiled([example[0].numpy(), example[1][0].numpy(), example[1][1].numpy()])[0]
+ np.testing.assert_allclose(result, expected)
+
+
+def test_pytorch_fx_decoder_flat_input_names_unchanged():
+ from openvino.frontend.pytorch.fx_decoder import TorchFXPythonDecoder
+
+ class TestModel(torch.nn.Module):
+ def forward(self, x, y):
+ return x + y
+
+ em = torch.export.export(TestModel(), (torch.ones(2), torch.ones(2)))
+ decoder = TorchFXPythonDecoder(em.module())
+ assert [decoder.get_input_signature_name(i) for i in range(2)] == ["x", "y"]
+
+
+def test_pytorch_dynamo_convert_with_list_input_keeps_input_names():
+ import numpy as np
+ from openvino import Core, convert_model
+
+ class TestModel(torch.nn.Module):
+ def forward(self, pair, scale):
+ return (pair[0] + pair[1] * 2).sum() * scale
+
+ pair = [torch.ones(2, 4), torch.ones(2, 4) * 2]
+ scale = torch.tensor([10.0])
+ model = TestModel()
+ expected = model(pair, scale).numpy()
+
+ ov_model = convert_model(model, example_input=(pair, scale), dynamo=True)
+
+ assert [sorted(port.get_names()) for port in ov_model.inputs] == [["pair_0"], ["pair_1"], ["scale"]]
+ assert list(ov_model.input("scale").get_partial_shape()) == [1]
+ compiled = Core().compile_model(ov_model, "CPU")
+ result = compiled({"pair_0": pair[0].numpy(), "pair_1": pair[1].numpy(), "scale": scale.numpy()})[0]
+ np.testing.assert_allclose(result, expected)
+
+
+def test_pytorch_fx_decoder_container_name_does_not_take_argument_name():
+ from openvino.frontend.pytorch.fx_decoder import TorchFXPythonDecoder
+
+ class TestModel(torch.nn.Module):
+ def forward(self, pair, pair_0):
+ return pair[0] * 2 + pair_0 * 3
+
+ em = torch.export.export(TestModel(), ([torch.ones(2, 4)], torch.ones(2, 4)))
+ decoder = TorchFXPythonDecoder(em.module())
+ # The plain argument keeps its own name, so the list element has to give way
+ assert [decoder.get_input_signature_name(i) for i in range(2)] == ["pair_0_1", "pair_0"]
+
+ class ChainModel(torch.nn.Module):
+ def forward(self, pair, pair_0, pair_0_1):
+ return pair[0] + pair_0 + pair_0_1
+
+ em = torch.export.export(ChainModel(), ([torch.ones(2)], torch.ones(2), torch.ones(2)))
+ decoder = TorchFXPythonDecoder(em.module())
+ # The suffix skips names that other arguments already use
+ assert [decoder.get_input_signature_name(i) for i in range(3)] == ["pair_0_2", "pair_0", "pair_0_1"]
+
+
+def test_pytorch_dynamo_convert_named_input_reaches_argument_not_container():
+ import numpy as np
+ from openvino import Core, PartialShape, convert_model
+
+ class TestModel(torch.nn.Module):
+ def forward(self, pair, pair_0):
+ return pair[0] * 2 + pair_0 * 3
+
+ pair = [torch.ones(2, 4) * 5]
+ pair_0 = torch.ones(2, 4) * 7
+ model = TestModel()
+ expected = model(pair, pair_0).numpy()
+
+ ov_model = convert_model(
+ model, example_input=(pair, pair_0), dynamo=True, input={"pair_0": PartialShape([2, 4])}
+ )
+
+ assert [sorted(port.get_names()) for port in ov_model.inputs] == [["pair_0_1"], ["pair_0"]]
+ assert list(ov_model.input("pair_0").get_partial_shape()) == [2, 4]
+ assert ov_model.input("pair_0_1").get_partial_shape().is_dynamic
+ compiled = Core().compile_model(ov_model, "CPU")
+ result = compiled({"pair_0_1": pair[0].numpy(), "pair_0": pair_0.numpy()})[0]
+ np.testing.assert_allclose(result, expected)
+
+
+class _SelfKeyDictModel(torch.nn.Module):
+ def forward(self, a):
+ return a["self"] * 2 + a["x"] * 3
+
+
+class _SelfAttnMaskModel(torch.nn.Module):
+ def forward(self, self_attn_mask, x):
+ return self_attn_mask * 2 + x * 3
+
+
+ "model, example, names",
+ [
+ (_SelfKeyDictModel(), ({"self": torch.ones(2) * 5, "x": torch.ones(2) * 7},), ["a_self", "a_x"]),
+ (_SelfAttnMaskModel(), (torch.ones(2) * 5, torch.ones(2) * 7), ["self_attn_mask", "x"]),
+ ],
+)
+def test_pytorch_fx_frontend_keeps_first_input_named_self(model, example, names):
+ # Only a TorchScript graph has a "self" receiver input, so no FX input may be hidden for its name
+ import numpy as np
+ import openvino as ov
+ from openvino.frontend.pytorch.fx_decoder import TorchFXPythonDecoder
+
+ decoder = TorchFXPythonDecoder(torch.export.export(model, example).module())
+ frontend = ov.frontend.FrontEndManager().load_by_framework("pytorch")
+ input_model = frontend.load(decoder)
+ inputs = input_model.get_inputs()
+ assert [sorted(place.get_names())[0] for place in inputs] == names
+
+ input_model.override_all_inputs(inputs[::-1])
+ ov_model = frontend.convert(input_model)
+ assert [sorted(port.get_names())[0] for port in ov_model.inputs] == names[::-1]
+ flat = [example[0]["self"], example[0]["x"]] if isinstance(example[0], dict) else list(example)
+ compiled = ov.Core().compile_model(ov_model, "CPU")
+ result = compiled({names[0]: flat[0].numpy(), names[1]: flat[1].numpy()})[0]
+ np.testing.assert_allclose(result, (flat[0] * 2 + flat[1] * 3).numpy())
+
+
@pytest.mark.precommit
@pytest.mark.parametrize("return_indices", [False, True])
def test_pytorch_fx_pool_without_output_metadata(return_indices):