Skip to content

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

[PyTorch FE] Fix captured constants in TorchScript subgraphs (#39105)

Maxim Vafina9051440f690
diff --git a/src/frontends/pytorch/include/openvino/frontend/pytorch/node_context.hpp b/src/frontends/pytorch/include/openvino/frontend/pytorch/node_context.hpp
index 7a7e0eac076..9d4b50feac3 100644
--- a/src/frontends/pytorch/include/openvino/frontend/pytorch/node_context.hpp
+++ b/src/frontends/pytorch/include/openvino/frontend/pytorch/node_context.hpp
@@ -128,6 +128,8 @@ public:
Output<Node> get_tensor_from_model_or_create_input(size_t index) const;
Output<Node> get_input_from_visible_context(size_t index) const;
+
+ Output<Node> get_input_from_visible_context(size_t index, bool resolve_sequence_constants) const;
std::shared_ptr<ov::Model> convert_subgraph(size_t index) const;
private:
diff --git a/src/frontends/pytorch/src/node_context.cpp b/src/frontends/pytorch/src/node_context.cpp
index d2c836bf764..315cd39cc3f 100644
--- a/src/frontends/pytorch/src/node_context.cpp
+++ b/src/frontends/pytorch/src/node_context.cpp
@@ -260,6 +260,10 @@ Output<Node> NodeContext::get_tensor_from_model_or_create_input(size_t index) co
}
Output<Node> NodeContext::get_input_from_visible_context(size_t index) const {
+ return get_input_from_visible_context(index, false);
+}
+
+Output<Node> NodeContext::get_input_from_visible_context(size_t index, bool resolve_sequence_constants) const {
FRONT_END_GENERAL_CHECK(index < get_input_size(), "Index ", index, " is lower than number of inputs.");
auto input_tensor = get_input(static_cast<int>(index));
auto input_node = input_tensor.get_node_shared_ptr();
@@ -270,6 +274,27 @@ Output<Node> NodeContext::get_input_from_visible_context(size_t index) const {
input_tensor = m_ext_tensor_map.at(tensor_idx);
}
}
+ if (resolve_sequence_constants) {
+ std::function<Output<Node>(const Output<Node>&)> resolve_constants =
+ [&](const Output<Node>& value) -> Output<Node> {
+ if (ov::is_type<v0::Parameter>(value.get_node())) {
+ const auto tensor_id = m_translate_session->decode_tensor_name(value);
+ const auto external = m_ext_tensor_map.find(tensor_id);
+ if (external != m_ext_tensor_map.end()) {
+ return external->second;
+ }
+ }
+ if (const auto sequence = ov::as_type_ptr<SequenceMark>(value.get_node_shared_ptr())) {
+ OutputVector elements;
+ for (const auto& element : sequence->input_values()) {
+ elements.push_back(resolve_constants(element));
+ }
+ return make_list_construct(elements);
+ }
+ return value;
+ };
+ input_tensor = resolve_constants(input_tensor);
+ }
return input_tensor;
}
@@ -279,9 +304,13 @@ 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 external
TensorMap 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 outer scope
- // we will not add Parameters we created in inner scope.
- ext_map.insert(m_tensor_map->begin(), m_tensor_map->end());
+ for (const auto& [tensor_id, value] : *m_tensor_map) {
+ if (!ov::is_type<v0::Parameter>(value.get_node())) {
+ ext_map[tensor_id] = value;
+ } else {
+ ext_map.emplace(tensor_id, value);
+ }
+ }
auto model = m_translate_session->convert_pytorch_model(subgraph_decoder, ext_map);
// Remove unused parameters, they could be created as inputs to the parts of graph that weren't
@@ -411,7 +440,7 @@ bool NodeContext::input_is_none(size_t index) const {
namespace {
std::shared_ptr<v0::Constant> get_constant_at_input(const NodeContext& ctx, size_t index, bool allow_empty = true) {
FRONT_END_GENERAL_CHECK(!ctx.input_is_none(index), "Input with index: ", index, " is none.");
- auto input_val = ctx.get_input_from_visible_context(index);
+ auto input_val = ctx.get_input_from_visible_context(index, true);
if (ctx.get_input_type(index).is<type::List>()) {
if (allow_empty && is_empty_list(input_val))
return {};
diff --git a/tests/layer_tests/py_frontend_tests/test_torch_subgraph_constants.py b/tests/layer_tests/py_frontend_tests/test_torch_subgraph_constants.py
new file mode 100644
index 00000000000..942388a1589
--- /dev/null
+++ b/tests/layer_tests/py_frontend_tests/test_torch_subgraph_constants.py
@@ -0,0 +1,204 @@
+# Copyright (C) 2018-2026 Intel Corporation
+# SPDX-License-Identifier: Apache-2.0
+
+from copy import deepcopy
+
+import numpy as np
+import openvino as ov
+import pytest
+import torch
+from openvino.frontend.pytorch.ts_decoder import TorchScriptPythonDecoder
+
+
[email protected]("dimension", [1, 2, 3])
[email protected]("groups", [1, 2])
[email protected]("scope", ["branch", "nested", "loop"])
+def test_torchscript_subgraph_convolution_constants(dimension, groups, scope):
+ class Decoder(torch.nn.Module):
+ __constants__ = ["scope"]
+
+ def __init__(self):
+ super().__init__()
+ conv = getattr(torch.nn, f"Conv{dimension}d")
+ self.conv = conv(4, 4, 2, stride=2, padding=1, dilation=2, groups=groups)
+ self.context_size = 2
+ self.scope = scope
+ self.repeat = 2
+
+ def forward(self, x: torch.Tensor):
+ if self.context_size > 1:
+ if self.scope == "loop":
+ for _ in range(self.repeat):
+ x = self.conv(x)
+ else:
+ x = self.conv(x)
+ return x
+
+ class Wrapper(torch.nn.Module):
+ def __init__(self, decoder):
+ super().__init__()
+ self.decoder = decoder
+ self.enabled = True
+
+ def forward(self, x: torch.Tensor):
+ if self.enabled:
+ return self.decoder(x)
+ return x
+
+ torch.manual_seed(0)
+ model = Wrapper(Decoder())
+ if scope == "nested":
+ model = Wrapper(model)
+ model.eval()
+ source = torch.jit.script(model)
+ inputs = torch.randn((1, 4) + (6,) * dimension)
+ converted = ov.convert_model(source, example_input=inputs)
+ compiled = ov.Core().compile_model(converted, "CPU", {"INFERENCE_PRECISION_HINT": "f32"})
+ actual = compiled(inputs.numpy())[0]
+ expected = source(inputs).detach().numpy()
+ np.testing.assert_allclose(actual, expected, rtol=1e-5, atol=1e-6)
+
+
[email protected]("scope", ["branch", "nested", "loop"])
+def test_torchscript_subgraph_computed_convolution_constants(scope):
+ class Model(torch.nn.Module):
+ __constants__ = ["scope"]
+
+ def __init__(self):
+ super().__init__()
+ self.weight = torch.nn.Parameter(torch.randn(4, 4, 3, 3))
+ self.kernel_size = 3
+ self.enabled = True
+ self.inner_enabled = True
+ self.repeat = 2
+ self.scope = scope
+
+ def convolve(self, x: torch.Tensor, stride: int, padding: int):
+ return torch.nn.functional.conv2d(x, self.weight, stride=[stride, stride], padding=[padding, padding])
+
+ def forward(self, x: torch.Tensor):
+ stride = self.kernel_size - 1
+ padding = self.kernel_size // 2
+ if self.enabled:
+ if self.scope == "loop":
+ for _ in range(self.repeat):
+ x = self.convolve(x, stride, padding)
+ elif self.scope == "nested":
+ if self.inner_enabled:
+ x = self.convolve(x, stride, padding)
+ else:
+ x = self.convolve(x, stride, padding)
+ return x
+
+ torch.manual_seed(0)
+ source = torch.jit.script(Model().eval())
+ inputs = torch.randn(1, 4, 9, 9)
+ converted = ov.convert_model(source, example_input=inputs)
+ compiled = ov.Core().compile_model(converted, "CPU", {"INFERENCE_PRECISION_HINT": "f32"})
+ actual = compiled(inputs.numpy())[0]
+ expected = source(inputs).detach().numpy()
+ np.testing.assert_allclose(actual, expected, rtol=1e-5, atol=1e-6)
+
+
[email protected]("outer,inner", [(False, False), (False, True), (True, False), (True, True)])
+def test_torchscript_nested_constant_mutation_before_append(outer, inner):
+ class Model(torch.nn.Module):
+ def forward(self, x: torch.Tensor, weight: torch.Tensor, outer: torch.Tensor, inner: torch.Tensor):
+ if bool(outer):
+ weight.add_(3)
+ if bool(inner):
+ values = [x]
+ values.append(weight)
+ return torch.cat(values)
+ return weight
+ return x
+
+ inputs = (torch.tensor([10., 20.]), torch.tensor([1., 2.]), torch.tensor(outer), torch.tensor(inner))
+ source = torch.jit.script(Model().eval())
+ expected = source(*deepcopy(inputs)).numpy()
+ frontend = ov.frontend.FrontEndManager().load_by_framework("pytorch")
+ decoder = TorchScriptPythonDecoder(source)
+ input_model = frontend.load(decoder)
+ places = input_model.get_inputs()
+ for place, value in zip(places, inputs):
+ input_model.set_partial_shape(place, ov.PartialShape(value.shape))
+ input_model.set_element_type(place, ov.Type.boolean if value.dtype == torch.bool else ov.Type.f32)
+ input_model.set_tensor_value(places[1], inputs[1].numpy())
+ converted = frontend.convert(input_model)
+ compiled = ov.Core().compile_model(converted, "CPU", {"INFERENCE_PRECISION_HINT": "f32"})
+ actual = compiled([value.numpy() for value in (inputs[0], inputs[2], inputs[3])])[0]
+ np.testing.assert_array_equal(actual, expected)
+
+
[email protected]("container", ["list", "tuple"])
[email protected]("positive", [False, True])
+def test_torchscript_nested_runtime_sequence_values(container, positive):
+ class ListModel(torch.nn.Module):
+ def forward(self, x: torch.Tensor):
+ values = [x, x + 1]
+ if x.sum() > 0:
+ x.add_(2)
+ else:
+ x.sub_(2)
+ return values[0] + values[1]
+
+ class TupleModel(torch.nn.Module):
+ def forward(self, x: torch.Tensor):
+ values = (x, x + 1)
+ if x.sum() > 0:
+ x.add_(2)
+ else:
+ x.sub_(2)
+ return values[0] + values[1]
+
+ source = torch.jit.script((ListModel() if container == "list" else TupleModel()).eval())
+ inputs = torch.full((2, 3), 1.0 if positive else -1.0)
+ expected = source(inputs.clone()).numpy()
+ converted = ov.convert_model(source, example_input=inputs.clone())
+ compiled = ov.Core().compile_model(converted, "CPU", {"INFERENCE_PRECISION_HINT": "f32"})
+ actual = compiled(inputs.numpy())[0]
+ np.testing.assert_array_equal(actual, expected)
+
+
[email protected]("iterations", [1, 2, 3])
+def test_torchscript_loop_carried_constant_sequence(iterations):
+ class Model(torch.nn.Module):
+ __constants__ = ["iterations"]
+
+ def __init__(self):
+ super().__init__()
+ self.iterations = iterations
+
+ def forward(self, x: torch.Tensor, weight: torch.Tensor):
+ out = x.clone()
+ for _ in range(self.iterations):
+ values = [weight]
+ out = out + torch.cat(values)
+ weight.add_(3)
+ return out
+
+ inputs = (torch.tensor([10., 20.]), torch.tensor([1., 2.]))
+ source = torch.jit.script(Model().eval())
+ expected = source(*deepcopy(inputs)).numpy()
+ frontend = ov.frontend.FrontEndManager().load_by_framework("pytorch")
+ decoder = TorchScriptPythonDecoder(source)
+ input_model = frontend.load(decoder)
+ places = input_model.get_inputs()
+ for place, value in zip(places, inputs):
+ input_model.set_partial_shape(place, ov.PartialShape(value.shape))
+ input_model.set_element_type(place, ov.Type.f32)
+ input_model.set_tensor_value(places[1], inputs[1].numpy())
+ converted = frontend.convert(input_model)
+ compiled = ov.Core().compile_model(converted, "CPU", {"INFERENCE_PRECISION_HINT": "f32"})
+ actual = compiled(inputs[0].numpy())[0]
+ np.testing.assert_array_equal(actual, expected)