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
[OVC] Preserve example metadata for TorchScript input aliases (#39103)
Maxim Vafin02cf6eefff28
diff --git a/tests/layer_tests/py_frontend_tests/test_torch_input_metadata.py b/tests/layer_tests/py_frontend_tests/test_torch_input_metadata.pynew file mode 100644index 00000000000..4065f1e9be5--- /dev/null+++ b/tests/layer_tests/py_frontend_tests/test_torch_input_metadata.py@@ -0,0 +1,116 @@+# Copyright (C) 2018-2026 Intel Corporation+# SPDX-License-Identifier: Apache-2.0++from argparse import Namespace++import numpy as np+import openvino as ov+import pytest+import torch++from openvino.frontend.pytorch.ts_decoder import TorchScriptPythonDecoder+from openvino.tools.ovc.cli_parser import _InputCutInfo+from openvino.tools.ovc.moc_frontend.pytorch_frontend_utils import extract_input_info_from_example+++class TimestepModel(torch.nn.Module):+ def forward(self, sample: torch.Tensor, timestep: torch.Tensor):+ return sample + timestep.unsqueeze(0).to(torch.int32)++[email protected]('dtype', [torch.float16, torch.float32])[email protected]('saved', [False, True])[email protected]('reverse_inputs', [False, True])[email protected]('explicit_shape', [False, True])+def test_torchscript_dict_example_matches_graph_inputs(dtype, saved, reverse_inputs, explicit_shape, tmp_path):+ model = torch.jit.script(TimestepModel().eval())+ if saved:+ path = tmp_path / 'model.pt'+ model.save(str(path))+ model = torch.jit.load(str(path))+ sample = torch.ones(2, dtype=torch.float32)+ timestep = torch.tensor(7.0, dtype=dtype)+ examples = {'timestep': timestep, 'sample': sample}+ names = [value.debugName() for value in list(model.inlined_graph.inputs())[1:]]+ shapes = [[2], []]+ inputs = list(zip(names, shapes)) if explicit_shape else names+ tensors = [sample.numpy(), timestep.numpy()]+ if reverse_inputs:+ inputs = inputs[::-1]+ tensors = tensors[::-1]++ converted = ov.convert_model(model, example_input=examples, input=inputs)++ expected_types = [ov.Type.f32, ov.Type.f16 if dtype == torch.float16 else ov.Type.f32]+ if reverse_inputs:+ expected_types = expected_types[::-1]+ assert [port.get_element_type() for port in converted.inputs] == expected_types+ assert examples['timestep'] is timestep+ assert examples['sample'] is sample+ compiled = ov.Core().compile_model(converted, 'CPU', {'INFERENCE_PRECISION_HINT': 'f32'})+ actual = next(iter(compiled(tensors).values()))+ np.testing.assert_array_equal(actual, model(sample, timestep).numpy())++[email protected]('case', ['explicit_metadata', 'exact_priority', 'unrelated_name'])+def test_torchscript_example_metadata_precedence(case):+ model = torch.jit.script(TimestepModel().eval())+ sample = torch.ones(2, dtype=torch.float32)+ timestep = torch.tensor(7.0, dtype=torch.float16)+ examples = {'timestep': timestep, 'sample': sample}+ names = [value.debugName() for value in list(model.inlined_graph.inputs())[1:]]+ descs = [_InputCutInfo(name, None, None, None) for name in names]+ if case == 'explicit_metadata':+ descs[0] = _InputCutInfo(names[0], ov.PartialShape([8]), ov.Type.f64, 5)+ elif case == 'exact_priority':+ examples[names[0]] = examples.pop('sample').to(torch.int64)+ else:+ descs[0] = _InputCutInfo('unrelated.1', None, None, None)+ decoder = TorchScriptPythonDecoder(model, example_input=examples)+ args = Namespace(input_model=decoder, example_input=examples, input=descs)++ extract_input_info_from_example(args, args.input)++ assert decoder._example_input is examples+ assert args.input[1].type == ov.Type.f16+ assert args.input[1].shape.rank.get_length() == 0+ if case == 'explicit_metadata':+ assert args.input[0] == descs[0]+ elif case == 'exact_priority':+ assert args.input[0].type == ov.Type.i64+ assert args.input[0].shape.rank.get_length() == 1+ else:+ assert args.input[0].type is None+ assert args.input[0].shape is None+++def timestep_function(timestep: torch.Tensor):+ return timestep.unsqueeze(0).to(torch.int32)++[email protected]('dtype', [torch.float16, torch.float32])+def test_torchscript_function_example_matches_graph_input(dtype):+ model = torch.jit.script(timestep_function)+ timestep = torch.tensor(7.0, dtype=dtype)+ name = next(model.inlined_graph.inputs()).debugName()++ converted = ov.convert_model(model, example_input={'timestep': timestep}, input=[(name, [])])++ assert converted.input().get_element_type() == (ov.Type.f16 if dtype == torch.float16 else ov.Type.f32)+ compiled = ov.Core().compile_model(converted, 'CPU')+ np.testing.assert_array_equal(next(iter(compiled([timestep.numpy()]).values())), np.array([7], dtype=np.int32))+++def test_torchscript_alias_does_not_reuse_exact_match():+ model = torch.jit.script(TimestepModel().eval())+ examples = {'sample': torch.ones(2), 'timestep': torch.tensor(7.0)}+ decoder = TorchScriptPythonDecoder(model, example_input=examples)+ debug_name = list(model.inlined_graph.inputs())[1].debugName()+ descs = [_InputCutInfo(name, None, None, None) for name in ['sample', debug_name]]+ args = Namespace(input_model=decoder, example_input=examples, input=descs)++ extract_input_info_from_example(args, args.input)++ assert args.input[0].type == ov.Type.f32+ assert args.input[1].type is None+ assert args.input[1].shape is Nonediff --git a/tools/ovc/openvino/tools/ovc/moc_frontend/pytorch_frontend_utils.py b/tools/ovc/openvino/tools/ovc/moc_frontend/pytorch_frontend_utils.pyindex 7159a3e47c2..fcefef42b3a 100644--- a/tools/ovc/openvino/tools/ovc/moc_frontend/pytorch_frontend_utils.py+++ b/tools/ovc/openvino/tools/ovc/moc_frontend/pytorch_frontend_utils.py@@ -343,6 +343,17 @@ def flatten_inputs(inputs, names=None):return flattened+def _torchscript_input_aliases(model):+ from openvino.frontend.pytorch.ts_decoder import TorchScriptPythonDecoder+ if not isinstance(model, TorchScriptPythonDecoder):+ return {}+ schema = getattr(getattr(model.pt_module, "forward", model.pt_module), "schema", None)+ if schema is None or len(schema.arguments) != len(model.raw_inputs):+ return {}+ # TorchScript schema names and graph debug names identify the same inputs.+ return {model.get_input_debug_name(i): argument.name for i, argument in enumerate(schema.arguments)}++def extract_input_info_from_example(args, inputs):try:from openvino.frontend.pytorch.utils import pt_to_ov_type_map # pylint: disable=no-name-in-module,import-error@@ -381,11 +392,18 @@ def extract_input_info_from_example(args, inputs):input_arg.append(single_input_to_input_cut_info((shape, dtype)))if inputs is not None and len(inputs) != 0:if len(inputs) == len(input_arg):- # Pass 1: exact name matches. Pass 2: unmatched descriptors take leftover- # examples in order; a named descriptor may only take an unnamed example.+ # Pass 1: exact name matches, then TorchScript alias matches for examples+ # not taken yet. Pass 2: unmatched descriptors take leftover examples in+ # order; a named descriptor may only take an unnamed example.by_name = {ex.name: ex for ex in input_arg if ex.name is not None}matched = [by_name.get(desc.name) for desc in args.input]used = {id(ex) for ex in matched if ex is not None}+ aliases = _torchscript_input_aliases(args.input_model)+ for i, desc in enumerate(args.input):+ ex = by_name.get(aliases.get(desc.name))+ if matched[i] is None and ex is not None and id(ex) not in used:+ matched[i] = ex+ used.add(id(ex))leftover = [ex for ex in input_arg if id(ex) not in used]new_input = []for desc, ex in zip(args.input, matched):