Skip to content

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

[PyTorch] Resolve mutations through unpacked container aliases (#38852)

Maxim Vafind9f39e43bdf0
diff --git a/src/bindings/python/src/openvino/frontend/pytorch/decoder_base.py b/src/bindings/python/src/openvino/frontend/pytorch/decoder_base.py
index 3a2cebeb7d8..9ccf4dac68a 100644
--- a/src/bindings/python/src/openvino/frontend/pytorch/decoder_base.py
+++ b/src/bindings/python/src/openvino/frontend/pytorch/decoder_base.py
@@ -85,6 +85,9 @@ class TorchDecoderBase(Decoder):
def may_produce_alias(self, in_index: int, out_index: int) -> bool:
return False
+ def get_input_sequences(self) -> dict:
+ return {}
+
def get_rt_info(self):
return {}
diff --git a/src/bindings/python/src/openvino/frontend/pytorch/ts_decoder.py b/src/bindings/python/src/openvino/frontend/pytorch/ts_decoder.py
index f03547cc920..2ea9025c4a4 100644
--- a/src/bindings/python/src/openvino/frontend/pytorch/ts_decoder.py
+++ b/src/bindings/python/src/openvino/frontend/pytorch/ts_decoder.py
@@ -566,6 +566,12 @@ class TorchScriptPythonDecoder(TorchDecoderBase):
return pt_value is None
return False
+ def get_input_sequences(self) -> dict:
+ if (isinstance(self.graph_element, torch.Node)
+ and self.graph_element.kind() in ("prim::ListUnpack", "prim::TupleUnpack")):
+ return {0: list(range(len(self.raw_outputs)))}
+ return {}
+
def may_produce_alias(self, in_index: int, out_index: int) -> bool:
try:
schema_text = self.get_schema()
diff --git a/src/bindings/python/src/pyopenvino/frontend/pytorch/decoder.hpp b/src/bindings/python/src/pyopenvino/frontend/pytorch/decoder.hpp
index 585247c9201..1e823ba1d56 100644
--- a/src/bindings/python/src/pyopenvino/frontend/pytorch/decoder.hpp
+++ b/src/bindings/python/src/pyopenvino/frontend/pytorch/decoder.hpp
@@ -5,6 +5,7 @@
#pragma once
#include <pybind11/pybind11.h>
+#include <pybind11/stl.h>
#include "openvino/frontend/pytorch/decoder.hpp"
#include "openvino/frontend/node_context.hpp"
@@ -146,6 +147,9 @@ class PyDecoder : public ov::frontend::pytorch::TorchDecoder {
ov::OutputVector convert(const ov::frontend::NodeContext* context) const override {
PYBIND11_OVERRIDE_PURE(ov::OutputVector, TorchDecoder, convert, context);
}
+ InputSequences get_input_sequences() const override {
+ PYBIND11_OVERRIDE(InputSequences, TorchDecoder, get_input_sequences);
+ }
};
void regclass_frontend_pytorch_decoder(py::module m);
diff --git a/src/frontends/pytorch/include/openvino/frontend/pytorch/decoder.hpp b/src/frontends/pytorch/include/openvino/frontend/pytorch/decoder.hpp
index dce3cfa42c5..fe694d3f01e 100644
--- a/src/frontends/pytorch/include/openvino/frontend/pytorch/decoder.hpp
+++ b/src/frontends/pytorch/include/openvino/frontend/pytorch/decoder.hpp
@@ -4,6 +4,8 @@
#pragma once
+#include <map>
+
#include "openvino/core/node.hpp"
#include "openvino/frontend/decoder.hpp"
#include "openvino/frontend/node_context.hpp"
@@ -142,6 +144,13 @@ public:
/// \brief Converts the node if `has_converter` returns true
virtual OutputVector convert(const ov::frontend::NodeContext* context) const = 0;
+
+ using InputSequences = std::map<size_t, std::vector<size_t>>;
+
+ // Sequence input indices mapped to their ordered element output indices; empty when unknown.
+ virtual InputSequences get_input_sequences() const {
+ return {};
+ }
};
} // namespace ov::frontend::pytorch
diff --git a/src/frontends/pytorch/src/node_context.cpp b/src/frontends/pytorch/src/node_context.cpp
index 681397998c9..d2c836bf764 100644
--- a/src/frontends/pytorch/src/node_context.cpp
+++ b/src/frontends/pytorch/src/node_context.cpp
@@ -127,9 +127,30 @@ void NodeContext::mutate_input(const std::string& name, Output<Node> ov_output)
void NodeContext::mutate_tensor(size_t input_id, Output<Node> ov_output, const std::string& name) const {
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.");
- const auto previous_value = tensor_it->second;
+ static const std::set<std::string> metadata_ops{"aten::unsqueeze_",
+ "aten::squeeze_",
+ "aten::transpose_",
+ "aten::t_"};
+ const bool metadata_only = metadata_ops.count(normalize_op_type(get_op_type()));
+ const auto previous_value = metadata_only ? resolve_tensor(input_id) : tensor_it->second;
+ if (metadata_only) {
+ std::set<size_t> related_ids{input_id};
+ for (auto alias = m_translate_session->m_may_be_alias.find(input_id);
+ alias != m_translate_session->m_may_be_alias.end();
+ alias = m_translate_session->m_may_be_alias.find(alias->second.base_id)) {
+ if (!related_ids.insert(alias->second.base_id).second) {
+ break;
+ }
+ }
+ for (const auto& [alias_id, info] : m_translate_session->m_may_be_alias) {
+ if (related_ids.count(alias_id) || related_ids.count(info.base_id)) {
+ resolve_tensor(alias_id);
+ related_ids.insert(alias_id);
+ }
+ }
+ }
m_translate_session->encode_tensor_name(ov_output, input_id, {name});
- tensor_it->second = ov_output;
+ (*m_tensor_map)[input_id] = ov_output;
m_mutated_tensors->insert(input_id);
if (ov::is_type<SequenceMark>(ov_output.get_node_shared_ptr())) {
@@ -144,27 +165,41 @@ void NodeContext::mutate_tensor(size_t input_id, Output<Node> ov_output, const s
return;
}
- // In-place operations which only rewrite the base tensor's metadata, leaving its storage untouched.
- static const std::set<std::string> metadata_ops{"aten::unsqueeze_",
- "aten::squeeze_",
- "aten::transpose_",
- "aten::t_"};
- if (metadata_ops.count(normalize_op_type(get_op_type()))) {
- // Existing views retain their shape when the base tensor's metadata changes.
+ if (metadata_only) {
const auto old_shape_view =
m_translate_session->get_reverseprop_op(m_decoder, ov_output, ov_output, previous_value);
+ std::set<size_t> same_tensor_ids{input_id};
+ std::vector<size_t> pending{input_id};
+ while (!pending.empty()) {
+ const auto current_id = pending.back();
+ pending.pop_back();
+ const auto current = m_translate_session->m_may_be_alias.find(current_id);
+ for (const auto& [alias_id, info] : m_translate_session->m_may_be_alias) {
+ if ((alias_id == current_id || info.base_id == current_id) &&
+ (info.same_tensor ||
+ (info.output == info.base_value && info.decoder->get_schema().find('!') != std::string::npos))) {
+ const auto related = alias_id == current_id ? info.base_id : alias_id;
+ if (same_tensor_ids.insert(related).second) {
+ pending.push_back(related);
+ }
+ }
+ if (current != m_translate_session->m_may_be_alias.end() &&
+ ov::is_type<SequenceMark>(info.base_value.get_node()) && info.base_id == current->second.base_id &&
+ info.output == current->second.output && same_tensor_ids.insert(alias_id).second) {
+ pending.push_back(alias_id);
+ }
+ }
+ }
for (auto& [alias_id, info] : m_translate_session->m_may_be_alias) {
- if (info.element_ids.empty() && info.base_id == input_id) {
+ if (!same_tensor_ids.count(alias_id) && info.element_ids.empty() && same_tensor_ids.count(info.base_id)) {
info.output = rebase_view(info.output, info.base_value, old_shape_view);
info.base_value = ov_output;
(*m_tensor_map)[alias_id] = info.output;
}
}
- const auto alias = m_translate_session->m_may_be_alias.find(input_id);
- if (alias != m_translate_session->m_may_be_alias.end()) {
- alias->second.output = ov_output;
+ for (const auto tensor_id : same_tensor_ids) {
+ (*m_tensor_map)[tensor_id] = ov_output;
}
- return;
}
// Resolve aliases
@@ -175,10 +210,20 @@ void NodeContext::mutate_tensor(size_t input_id, Output<Node> ov_output, const s
// alias to tensor. In that case we need to create a chain of reverseprop ops
auto& alias_info = m_translate_session->m_may_be_alias.at(back_input_id);
const auto in_tensor = alias_info.base_id;
+ if (metadata_only && !alias_info.same_tensor && !ov::is_type<SequenceMark>(alias_info.base_value.get_node()) &&
+ (alias_info.output != alias_info.base_value ||
+ alias_info.decoder->get_schema().find('!') == std::string::npos)) {
+ alias_info.output = back_node_input;
+ break;
+ }
auto reverseprop_node = m_translate_session->get_reverseprop_op(alias_info.decoder,
alias_info.output,
back_node_input,
alias_info.base_value);
+ if (metadata_only) {
+ alias_info.output = back_node_input;
+ alias_info.base_value = reverseprop_node;
+ }
m_translate_session->encode_tensor_name(reverseprop_node, in_tensor);
(*m_tensor_map)[in_tensor] = reverseprop_node;
m_mutated_tensors->insert(in_tensor);
diff --git a/src/frontends/pytorch/src/op/list_unpack.cpp b/src/frontends/pytorch/src/op/list_unpack.cpp
index afaf6d7b70e..661a8c50950 100644
--- a/src/frontends/pytorch/src/op/list_unpack.cpp
+++ b/src/frontends/pytorch/src/op/list_unpack.cpp
@@ -6,6 +6,7 @@
#include "openvino/frontend/pytorch/node_context.hpp"
#include "openvino/frontend/sequence_mark.hpp"
#include "pt_framework_node.hpp"
+#include "transforms/prim_list_unpack_replacer.hpp"
#include "utils.hpp"
#include "utils_quantize.hpp"
@@ -55,6 +56,11 @@ OutputVector translate_list_unpack(const NodeContext& context) {
}
}
+ const auto sequence = make_list_construct(outputs);
+ if (pass::PrimListUnpackReplacer().apply(list_unpack_fw)) {
+ return wrap_complex(context, sequence->get_sequence(), complex);
+ }
+
// Wrap outputs in ComplexTypeMark if input was complex
return wrap_complex(context, outputs, complex);
}
diff --git a/src/frontends/pytorch/src/transforms/reverseprop_resolver.cpp b/src/frontends/pytorch/src/transforms/reverseprop_resolver.cpp
index cbd1a07036f..d6f891bd282 100644
--- a/src/frontends/pytorch/src/transforms/reverseprop_resolver.cpp
+++ b/src/frontends/pytorch/src/transforms/reverseprop_resolver.cpp
@@ -4,9 +4,6 @@
#include "reverseprop_resolver.hpp"
-#include <memory>
-#include <utility>
-
#include "helper_ops/gather_assign.hpp"
#include "helper_ops/internal_op.hpp"
#include "helper_ops/slice_assign.hpp"
@@ -30,6 +27,8 @@ using namespace ov::pass;
using namespace ov::op;
ReversepropResolver::ReversepropResolver() {
+ // GraphRewrite refreshes shapes before later mutations use them.
+ m_enable_shape_inference = true;
auto reverse_op = pattern::wrap_type<InternalReverseOperation>();
ov::matcher_pass_callback callback = [](pattern::Matcher& m) {
@@ -107,7 +106,7 @@ ReversepropResolver::ReversepropResolver() {
auto m =
std::make_shared<ov::pass::pattern::Matcher>(reverse_op, "ov::frontend::pytorch::pass::ReversepropResolver");
- this->register_matcher(m, callback);
+ add_matcher(std::make_shared<ov::pass::MatcherPass>(m, callback));
};
} // namespace ov::frontend::pytorch::pass
diff --git a/src/frontends/pytorch/src/transforms/reverseprop_resolver.hpp b/src/frontends/pytorch/src/transforms/reverseprop_resolver.hpp
index 0e9bc9dc5c7..e4782d74d81 100644
--- a/src/frontends/pytorch/src/transforms/reverseprop_resolver.hpp
+++ b/src/frontends/pytorch/src/transforms/reverseprop_resolver.hpp
@@ -11,9 +11,9 @@ namespace ov::frontend::pytorch::pass {
/**
* Replace sequence of reverseprop operations with ScatterNdUpdate.
*/
-class ReversepropResolver : public ov::pass::MatcherPass {
+class ReversepropResolver : public ov::pass::GraphRewrite {
public:
- OPENVINO_MATCHER_PASS_RTTI("ov::frontend::pytorch::pass::ReversepropResolver");
+ OPENVINO_GRAPH_REWRITE_RTTI("ov::frontend::pytorch::pass::ReversepropResolver");
ReversepropResolver();
};
diff --git a/src/frontends/pytorch/src/translate_session.cpp b/src/frontends/pytorch/src/translate_session.cpp
index 5b47ef06f70..6e69c0b7392 100644
--- a/src/frontends/pytorch/src/translate_session.cpp
+++ b/src/frontends/pytorch/src/translate_session.cpp
@@ -262,14 +262,74 @@ std::shared_ptr<Model> TranslateSession::convert_pytorch_model(
converted_outputs.size(),
" respectively.");
+ const auto get_sequence_elements = [&](size_t id) {
+ std::set<size_t> visited;
+ for (auto alias = m_may_be_alias.find(id);
+ alias != m_may_be_alias.end() && visited.insert(alias->first).second;
+ alias = m_may_be_alias.find(alias->second.base_id)) {
+ const auto& info = alias->second;
+ if (!info.element_ids.empty()) {
+ return info.element_ids;
+ }
+ if (!info.same_tensor &&
+ (info.output != info.base_value || info.decoder->get_schema().find('!') == std::string::npos)) {
+ break;
+ }
+ }
+ return std::vector<size_t>{};
+ };
+ std::map<size_t, size_t> sequence_aliases;
+ const auto input_sequences =
+ raw_inputs.empty() ? TorchDecoder::InputSequences{} : node->get_input_sequences();
+ for (const auto& sequence_input : input_sequences) {
+ const auto i = sequence_input.first;
+ const auto& elements = sequence_input.second;
+ FRONT_END_OP_CONVERSION_CHECK(i < raw_inputs.size(), "Sequence input index is out of range.");
+ if (elements.empty()) {
+ continue;
+ }
+ const auto alias = m_may_be_alias.find(raw_inputs[i]);
+ const auto element_ids = get_sequence_elements(raw_inputs[i]);
+ FRONT_END_OP_CONVERSION_CHECK(element_ids.empty() || element_ids.size() == elements.size(),
+ "Sequence extraction must preserve the number of elements.");
+ OutputVector values;
+ for (size_t j = 0; j < elements.size(); ++j) {
+ const auto output_index = elements[j];
+ FRONT_END_OP_CONVERSION_CHECK(output_index < fw_outputs.size(),
+ "Sequence element output index is out of range.");
+ const auto base_id = element_ids.empty() ? raw_inputs[i] : element_ids[j];
+ FRONT_END_OP_CONVERSION_CHECK(sequence_aliases.emplace(output_index, base_id).second,
+ "A sequence extraction output must identify exactly one element.");
+ values.push_back(converted_outputs.at(output_index));
+ }
+ if (!ov::is_type<SequenceMark>(tensor_map->at(raw_inputs[i]).get_node_shared_ptr())) {
+ const auto sequence = make_list_construct(values);
+ encode_tensor_name(sequence, raw_inputs[i]);
+ (*tensor_map)[raw_inputs[i]] = sequence;
+ for (auto current = alias; current != m_may_be_alias.end();
+ current = m_may_be_alias.find(current->second.base_id)) {
+ auto& info = current->second;
+ if (ov::is_type<SequenceMark>(info.base_value.get_node())) {
+ break;
+ }
+ const bool same_value = info.output == info.base_value;
+ info.output = sequence;
+ if (!same_value) {
+ break;
+ }
+ info.base_value = sequence;
+ (*tensor_map)[info.base_id] = sequence;
+ }
+ }
+ }
+
const bool has_inputs = !raw_inputs.empty();
const size_t first_input_id = has_out ? node->get_named_input("out") : (has_inputs ? raw_inputs.at(0) : 0);
const auto& op_type = context.get_op_type();
const bool constructs_sequence = op_type == "prim::TupleConstruct" || op_type == "prim::ListConstruct";
std::vector<size_t> unpacked_ids;
- const auto sequence = m_may_be_alias.find(first_input_id);
- if (sequence != m_may_be_alias.end() && !sequence->second.element_ids.empty()) {
- const auto& elements = sequence->second.element_ids;
+ const auto elements = get_sequence_elements(first_input_id);
+ if (!elements.empty()) {
if (op_type == "prim::TupleUnpack" || op_type == "prim::ListUnpack") {
unpacked_ids = elements;
} else if (op_type == "aten::__getitem__") {
@@ -286,8 +346,12 @@ std::shared_ptr<Model> TranslateSession::convert_pytorch_model(
}
for (size_t i = 0; i < fw_outputs.size(); ++i) {
size_t fw_tensor_id = fw_outputs.at(i);
- const auto in_tensor_id = unpacked_ids.empty() ? first_input_id : unpacked_ids.at(i);
- if (has_out || (has_inputs && (constructs_sequence || node->may_produce_alias(0, i)))) {
+ const auto extracted = sequence_aliases.find(i);
+ const bool sequence_element = extracted != sequence_aliases.end();
+ const auto in_tensor_id =
+ sequence_element ? extracted->second : (unpacked_ids.empty() ? first_input_id : unpacked_ids.at(i));
+ if (has_out || sequence_element ||
+ (has_inputs && (constructs_sequence || 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?
if (alias_iter != m_may_be_alias.end()) {
@@ -302,11 +366,14 @@ std::shared_ptr<Model> TranslateSession::convert_pytorch_model(
" vs ",
recorded.base_id);
}
- m_may_be_alias[fw_tensor_id] = {in_tensor_id,
- node,
- converted_outputs[i],
- tensor_map->at(in_tensor_id),
- constructs_sequence ? raw_inputs : std::vector<size_t>{}};
+ m_may_be_alias[fw_tensor_id] = {
+ in_tensor_id,
+ node,
+ converted_outputs[i],
+ tensor_map->at(in_tensor_id),
+ constructs_sequence ? raw_inputs : std::vector<size_t>{},
+ !unpacked_ids.empty() ||
+ (sequence_element && !ov::is_type<SequenceMark>(tensor_map->at(in_tensor_id).get_node()))};
OPENVINO_DEBUG("Registered alias: ",
fw_tensor_id,
" of tensor: ",
diff --git a/src/frontends/pytorch/src/translate_session.hpp b/src/frontends/pytorch/src/translate_session.hpp
index 2564f7bcf75..48c86dc2da5 100644
--- a/src/frontends/pytorch/src/translate_session.hpp
+++ b/src/frontends/pytorch/src/translate_session.hpp
@@ -54,6 +54,7 @@ public:
Output<Node> base_value;
// Constructed containers hold references to distinct tensors, not views of input 0.
std::vector<size_t> element_ids;
+ bool same_tensor = false;
};
std::map<size_t, AliasInfo> m_may_be_alias;
// Aliases of tuple elements returned by inlined subgraphs, keyed by tuple tensor id and element index and
diff --git a/tests/layer_tests/py_frontend_tests/test_torch_container_aliases.py b/tests/layer_tests/py_frontend_tests/test_torch_container_aliases.py
new file mode 100644
index 00000000000..d97cbd233c9
--- /dev/null
+++ b/tests/layer_tests/py_frontend_tests/test_torch_container_aliases.py
@@ -0,0 +1,428 @@
+# Copyright (C) 2018-2026 Intel Corporation
+# SPDX-License-Identifier: Apache-2.0
+
+from copy import deepcopy
+from typing import List, Tuple
+
+import numpy as np
+import openvino as ov
+import pytest
+import torch
+
+
+class ContainerMetadataMutation(torch.nn.Module):
+ __constants__ = ["mutation", "right", "update_other"]
+
+ def __init__(self, mutation, right, update_other):
+ super().__init__()
+ self.mutation = mutation
+ self.right = right
+ self.update_other = update_other
+
+ def forward(self, cache: Tuple[torch.Tensor, torch.Tensor]):
+ return self.mutate(cache)
+
+ def mutate(self, cache: Tuple[torch.Tensor, torch.Tensor]):
+ left, right = cache
+ member = right if self.right else left
+ other = left if self.right else right
+ view = member[:, :2]
+ if self.update_other:
+ other.add_(1)
+ if self.mutation == "chain":
+ member.transpose_(0, 1).unsqueeze_(0)
+ elif self.mutation == "transpose":
+ member.transpose_(0, 1)
+ elif self.mutation == "unsqueeze":
+ member.unsqueeze_(0)
+ else:
+ member.squeeze_(0)
+ if self.update_other:
+ other.unsqueeze_(-1)
+ member.add_(2)
+ return cache, view
+
+
+class NestedContainerMetadataMutation(ContainerMetadataMutation):
+ def forward(self, cache: Tuple[Tuple[torch.Tensor, torch.Tensor]]):
+ inner, = cache
+ _, view = self.mutate(inner)
+ return cache, view
+
+
+class ListMetadataMutation(torch.nn.Module):
+ __constants__ = ["operation"]
+
+ def __init__(self, operation):
+ super().__init__()
+ self.operation = operation
+
+ def forward(self, cache: List[torch.Tensor]):
+ left, right = cache
+ view = left[:, :2]
+ if self.operation == "storage":
+ cache[0].add_(1)
+ cache[0].transpose_(0, 1)
+ if self.operation == "metadata":
+ cache[0].unsqueeze_(0)
+ return cache, left, view
+
+
+def test_torch_metadata_mutation_after_unrelated_append():
+ class Model(torch.nn.Module):
+ def forward(self, cache: List[torch.Tensor], extra: torch.Tensor, target: torch.Tensor):
+ left, right = cache
+ before = left + right
+ cache.append(extra)
+ target.unsqueeze_(0)
+ return before, torch.cat(cache), target
+
+ model = torch.jit.script(Model())
+ inputs = ([torch.ones(2, 3), torch.full((2, 3), 2.0)], torch.full((2, 3), 3.0), torch.arange(6.0).reshape(2, 3))
+ converted = ov.convert_model(model, example_input=deepcopy(inputs))
+ compiled = ov.Core().compile_model(converted, "CPU", {"INFERENCE_PRECISION_HINT": "f32"})
+ results = list(compiled([value.numpy() for value in (*inputs[0], *inputs[1:])]).values())
+ assert len(results) == 3
+ for actual, reference in zip(results, model(*deepcopy(inputs))):
+ np.testing.assert_array_equal(actual, reference.numpy())
+
+
[email protected]("mutate_clone", [False, True])
[email protected]("operation", ["clone", "detach"])
+def test_torch_tensor_metadata_identity(mutate_clone, operation):
+ class Model(torch.nn.Module):
+ __constants__ = ["mutate_clone", "operation"]
+
+ def __init__(self):
+ super().__init__()
+ self.mutate_clone = mutate_clone
+ self.operation = operation
+
+ def forward(self, source):
+ clone = source.clone() if self.operation == "clone" else source.detach()
+ target = clone if self.mutate_clone else source
+ target.unsqueeze_(0)
+ return source, clone
+
+ model = torch.jit.script(Model())
+ source = torch.arange(6, dtype=torch.float32).reshape(2, 3)
+ converted = ov.convert_model(model, example_input=source)
+ compiled = ov.Core().compile_model(converted, "CPU", {"INFERENCE_PRECISION_HINT": "f32"})
+ results = list(compiled([source.numpy()]).values())
+ expected = model(source.clone())
+ assert len(results) == 2
+ for actual, reference in zip(results, expected):
+ np.testing.assert_array_equal(actual, reference.numpy())
+
+
[email protected]("operation", ["transpose", "storage", "metadata"])
+def test_torch_list_member_metadata_preserves_views(operation):
+ inputs = [torch.arange(6, dtype=torch.float32).reshape(2, 3), torch.ones(2, 3)]
+ model = torch.jit.script(ListMetadataMutation(operation))
+ converted = ov.convert_model(model, example_input=(deepcopy(inputs),))
+ compiled = ov.Core().compile_model(converted, "CPU", {"INFERENCE_PRECISION_HINT": "f32"})
+ cache, left, view = model(deepcopy(inputs))
+ results = list(compiled([x.numpy() for x in inputs]).values())
+ assert len(results) == 4
+ for expected, actual in zip((*cache, left, view), results):
+ np.testing.assert_array_equal(actual, expected.numpy())
+
+
+def test_torch_wrapped_chunk_base_mutation():
+ from openvino.frontend.pytorch.ts_decoder import TorchScriptPythonDecoder
+
+ graph = torch._C.parse_ir("""graph(%base : Tensor):
+ %two : int = prim::Constant[value=2]()
+ %zero : int = prim::Constant[value=0]()
+ %one : int = prim::Constant[value=1]()
+ %parts : Tensor[] = aten::chunk(%base, %two, %zero)
+ %wrapped : (Tensor[]) = prim::TupleConstruct(%parts)
+ %alias : Tensor[] = prim::TupleUnpack(%wrapped)
+ %a : Tensor, %b : Tensor = prim::ListUnpack(%alias)
+ %updated : Tensor = aten::add_(%base, %one, %one)
+ return (%a, %b)
+ """)
+ frontend = ov.frontend.FrontEndManager().load_by_framework("pytorch")
+ decoder = TorchScriptPythonDecoder(None, graph, alias_db=graph.alias_db())
+ input_model = frontend.load(decoder)
+ input_model.set_element_type(input_model.get_inputs()[0], ov.Type.f32)
+ input_model.set_partial_shape(input_model.get_inputs()[0], ov.PartialShape([4, 3]))
+ converted = frontend.convert(input_model)
+ compiled = ov.Core().compile_model(converted, "CPU", {"INFERENCE_PRECISION_HINT": "f32"})
+ source = np.arange(12, dtype=np.float32).reshape(4, 3)
+ results = list(compiled([source]).values())
+ assert len(results) == 2
+ for actual, expected in zip(results, np.split(source + 1, 2)):
+ np.testing.assert_array_equal(actual, expected)
+
+
[email protected]("mutation,right,update_other,nested", [
+ ("transpose", False, False, False),
+ ("unsqueeze", False, False, False),
+ ("squeeze", True, False, True),
+ ("chain", True, False, False),
+ ("chain", False, True, True),
+ ("transpose", True, True, False),
+])
+def test_torch_container_metadata_mutation(mutation, right, update_other, nested):
+ generator = torch.Generator().manual_seed(42)
+ rows = 1 if mutation == "squeeze" else 2
+ inputs = tuple(torch.randn(rows, 3, generator=generator) for _ in range(2))
+ inputs = (inputs,) if nested else inputs
+ module = NestedContainerMetadataMutation if nested else ContainerMetadataMutation
+ model = torch.jit.script(module(mutation, right, update_other))
+ converted = ov.convert_model(model, example_input=(deepcopy(inputs),))
+ compiled = ov.Core().compile_model(converted, "CPU", {"INFERENCE_PRECISION_HINT": "f32"})
+ for columns in (3, 5):
+ inputs = tuple(torch.randn(rows, columns, generator=generator) for _ in range(2))
+ cache, view = model(deepcopy((inputs,) if nested else inputs))
+ cache = cache[0] if nested else cache
+ actual = list(compiled([member.numpy() for member in inputs]).values())
+ assert len(actual) == 3
+ for reference, result in zip((*cache, view), actual):
+ np.testing.assert_array_equal(result, reference.numpy())
+
+
+class ContainerMutation(torch.nn.Module):
+ def __init__(self, nested, mutation):
+ super().__init__()
+ self.nested = nested
+ self.mutation = mutation
+
+ def forward(self, source, cache):
+ left, right = cache[0] if self.nested else cache
+ before = left + right
+ left_view = left[:, :, :2]
+ right_view = right[:, :, :2]
+ if self.mutation == "view":
+ left_view.copy_(source[:, :, :2])
+ elif self.mutation == "right":
+ right.copy_(source)
+ else:
+ left.copy_(source)
+ if self.mutation == "repeated":
+ left.add_(2)
+ elif self.mutation == "siblings":
+ right.copy_(source + 5)
+ values = cache[0] if self.nested else cache
+ return before, left, right, left_view, right_view, values[0], values[1]
+
+
[email protected]("container,nested,mutation", [
+ (list, False, "copy"), (tuple, False, "right"),
+ (list, False, "view"), (tuple, True, "view"),
+ (tuple, True, "repeated"), (list, True, "siblings"),
+])
+def test_torch_container_input_mutation(container, nested, mutation):
+ generator = torch.Generator().manual_seed(42)
+
+ def make_inputs(batch):
+ source = torch.randn(batch, 4, 3, generator=generator)
+ elements = container(torch.randn(batch, 4, 3, generator=generator) for _ in range(2))
+ cache = container([elements]) if nested else elements
+ return source, cache
+
+ inputs = make_inputs(1)
+ model = torch.jit.trace(ContainerMutation(nested, mutation), deepcopy(inputs),
+ strict=False, check_trace=False)
+ converted = ov.convert_model(model, example_input=deepcopy(inputs))
+ assert len(converted.inputs) == 3
+ compiled = ov.Core().compile_model(converted, "CPU", {"INFERENCE_PRECISION_HINT": "f32"})
+ for batch in (1, 2):
+ source, cache = make_inputs(batch)
+ expected = model(*deepcopy((source, cache)))
+ elements = cache[0] if nested else cache
+ actual = list(compiled([source.numpy()] + [element.numpy() for element in elements]).values())
+ assert len(actual) == len(expected)
+ for reference, result in zip(expected, actual):
+ np.testing.assert_allclose(result, reference.numpy(), rtol=1e-5, atol=1e-6)
+
+
+class ChunkCacheMutation(torch.nn.Module):
+ def forward(self, source, cache):
+ b, c, x = source.chunk(3, dim=1)
+ cache[0].copy_(b * x)
+ return c * cache[0], cache
+
+
+class SequenceViewMutation(torch.nn.Module):
+ def __init__(self, operation):
+ super().__init__()
+ self.operation = operation
+
+ def forward(self, source, data):
+ base = data.clone()
+ if self.operation == "split":
+ parts = torch.split_with_sizes(base, [2, 2], dim=1)
+ else:
+ parts = torch.unbind(base.reshape(base.shape[0], 2, 2, 3), dim=1)
+ before = parts[0] + parts[1]
+ parts[0].copy_(source)
+ parts[1].add_(2)
+ return base, before, parts[0], parts[1]
+
+
+class SequenceBaseMutation(torch.nn.Module):
+ def __init__(self, operation):
+ super().__init__()
+ self.operation = operation
+
+ def forward(self, data):
+ base = data.clone()
+ if self.operation == "chunk":
+ left, right = base.chunk(2, dim=1)
+ else:
+ left, right = base.split([2, 2], dim=1)
+ before = left + right
+ base.add_(1)
+ after = left + right
+ right.add_(2)
+ return base, before, after, left, right
+
+
[email protected]("operation", ["chunk", "split"])
+def test_torch_sequence_base_mutation(operation):
+ generator = torch.Generator().manual_seed(42)
+ data = torch.randn(2, 4, 3, generator=generator)
+ model = torch.jit.trace(SequenceBaseMutation(operation), data)
+ converted = ov.convert_model(model, example_input=data)
+ converted.reshape({converted.input(0): ov.PartialShape([-1, 4, 3])})
+ compiled = ov.Core().compile_model(converted, "CPU", {"INFERENCE_PRECISION_HINT": "f32"})
+ for batch in (1, 2):
+ data = torch.randn(batch, 4, 3, generator=generator)
+ expected = model(data)
+ actual = list(compiled([data.numpy()]).values())
+ assert len(actual) == len(expected)
+ for reference, result in zip(expected, actual):
+ np.testing.assert_allclose(result, reference.numpy(), rtol=1e-5, atol=1e-6)
+
+
[email protected]("operation,capture", [("split", "torchscript"), ("unbind", "export")])
+def test_torch_sequence_view_mutation(operation, capture):
+ generator = torch.Generator().manual_seed(42)
+ inputs = (torch.randn(2, 2, 3, generator=generator), torch.randn(2, 4, 3, generator=generator))
+ model = SequenceViewMutation(operation)
+ if capture == "torchscript":
+ model = torch.jit.trace(model, deepcopy(inputs))
+ converted = ov.convert_model(model, example_input=deepcopy(inputs))
+ else:
+ batch = torch.export.Dim("batch", min=1)
+ exported = torch.export.export(model, deepcopy(inputs), dynamic_shapes=({0: batch}, {0: batch}))
+ converted = ov.convert_model(exported)
+ compiled = ov.Core().compile_model(converted, "CPU", {"INFERENCE_PRECISION_HINT": "f32"})
+ for batch in (1, 2):
+ inputs = (torch.randn(batch, 2, 3, generator=generator), torch.randn(batch, 4, 3, generator=generator))
+ expected = model(*deepcopy(inputs))
+ actual = list(compiled([element.numpy() for element in inputs]).values())
+ assert len(actual) == len(expected)
+ for reference, result in zip(expected, actual):
+ np.testing.assert_allclose(result, reference.numpy(), rtol=1e-5, atol=1e-6)
+
+
+def test_torch_chunk_cache_mutation():
+ generator = torch.Generator().manual_seed(42)
+ source = torch.randn(1, 12, 3, generator=generator)
+ cache = [torch.randn(1, 4, 3, generator=generator) for _ in range(2)]
+ inputs = source, cache
+ model = torch.jit.trace(ChunkCacheMutation(), deepcopy(inputs), strict=False, check_trace=False)
+ converted = ov.convert_model(model, example_input=deepcopy(inputs))
+ compiled = ov.Core().compile_model(converted, "CPU", {"INFERENCE_PRECISION_HINT": "f32"})
+ for batch in (1, 2):
+ source = torch.randn(batch, 12, 3, generator=generator)
+ cache = [torch.randn(batch, 4, 3, generator=generator) for _ in range(2)]
+ output, updated_cache = model(*deepcopy((source, cache)))
+ expected = [output] + updated_cache
+ actual = list(compiled([source.numpy()] + [element.numpy() for element in cache]).values())
+ assert len(actual) == len(expected)
+ for reference, result in zip(expected, actual):
+ np.testing.assert_allclose(result, reference.numpy(), rtol=1e-5, atol=1e-6)
+
+
[email protected]("sequence_input,mapping,error,metadata", [
+ (0, [1, 0], None, False), (1, [1, 0], None, False), (1, [1, 0], None, True),
+ (0, [0], "preserve the number of elements", False),
+ (0, [0, 1, 0], "preserve the number of elements", False),
+ (0, [0, 0], "exactly one element", False), (0, [0, 2], "out of range", False),
+])
+def test_torch_decoder_sequence_output_order(sequence_input, mapping, error, metadata):
+ from openvino.frontend.pytorch.ts_decoder import TorchScriptPythonDecoder
+
+ ir = """graph(%left : Tensor, %right : Tensor, %source : Tensor):
+ %pair : (Tensor, Tensor) = prim::TupleConstruct(%left, %right)
+ %first : Tensor, %second : Tensor = prim::TupleUnpack(%pair)
+ %blocking : bool = prim::Constant[value=0]()
+ %updated : Tensor = aten::copy_(%first, %source, %blocking)
+ return (%left, %right, %second)
+ """
+ if metadata:
+ ir = ir.replace("%blocking : bool", "%blocking : int").replace(
+ "aten::copy_(%first, %source, %blocking)", "aten::unsqueeze_(%first, %blocking)")
+ graph = torch._C.parse_ir(ir)
+
+ class ReversedSequenceDecoder(TorchScriptPythonDecoder):
+ def __init__(self, *args, **kwargs):
+ super().__init__(*args, **kwargs)
+ self.sequence_queries = 0
+ if self.get_op_type() == "custom::reversed_sequence" and sequence_input == 1:
+ self.raw_inputs.insert(0, list(graph.inputs())[0])
+ self._input_ids.insert(0, self.raw_inputs[0].unique())
+
+ def get_op_type(self):
+ if isinstance(self.graph_element, torch.Node) and self.graph_element.kind() == "prim::TupleUnpack":
+ return "custom::reversed_sequence"
+ return super().get_op_type()
+
+ def get_input_sequences(self):
+ self.sequence_queries += 1
+ return {sequence_input: mapping} if self.get_op_type() == "custom::reversed_sequence" else {}
+
+ def visit_subgraph(self, visitor):
+ for node in self.graph_element.nodes():
+ decoder = ReversedSequenceDecoder(None, node, alias_db=self.alias_db)
+ self.m_decoders.append(decoder)
+ visitor(decoder)
+
+ decoder = ReversedSequenceDecoder(None, graph, alias_db=graph.alias_db())
+ frontend = ov.frontend.FrontEndManager().load_by_framework("pytorch")
+ frontend.add_extension(ov.frontend.ConversionExtension(
+ "custom::reversed_sequence",
+ lambda context: list(reversed(context.get_input(sequence_input).get_node().input_values()))))
+ input_model = frontend.load(decoder)
+ for place in input_model.get_inputs():
+ input_model.set_element_type(place, ov.Type.f32)
+ if error:
+ with pytest.raises(RuntimeError, match=error):
+ frontend.convert(input_model)
+ return
+ converted = frontend.convert(input_model)
+ assert all(child.sequence_queries == bool(child.inputs()) for child in decoder.m_decoders)
+ converted.reshape({port: ov.PartialShape([-1, 4, 3]) for port in converted.inputs})
+ compiled = ov.Core().compile_model(converted, "CPU", {"INFERENCE_PRECISION_HINT": "f32"})
+ generator = np.random.default_rng(42)
+ for batch in (1, 2):
+ left, right, source = [generator.standard_normal((batch, 4, 3)).astype(np.float32) for _ in range(3)]
+ actual = list(compiled([left, right, source]).values())
+ assert len(actual) == 3
+ expected = (left, right[None], left) if metadata else (left, source, left)
+ for result, expected in zip(actual, expected):
+ np.testing.assert_allclose(result, expected)
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 3045f6811e6..baa3298dac4 100644
--- a/tests/layer_tests/py_frontend_tests/test_torch_decoder.py
+++ b/tests/layer_tests/py_frontend_tests/test_torch_decoder.py
@@ -821,3 +821,82 @@ def test_pytorch_fx_pool_without_output_metadata(return_indices):
def test_is_testing_flag(testing_value, expected):
"""Test that the _is_testing flag evaluates correctly."""
assert _is_testing({"testing": testing_value}) == expected
+
+
[email protected]("ir,expected", [
+ ("graph(%values : Tensor[]):\n %a : Tensor, %b : Tensor = prim::ListUnpack(%values)\n return (%a, %b)\n", [0, 1]),
+ ("graph(%values : (Tensor, Tensor)):\n %a : Tensor, %b : Tensor = prim::TupleUnpack(%values)\n return (%a, %b)\n", [0, 1]),
+ ("graph(%value : Tensor):\n %a : Tensor = aten::alias(%value)\n return (%a)\n", []),
+])
+def test_pytorch_decoder_input_sequence(ir, expected):
+ from openvino.frontend.pytorch.ts_decoder import TorchScriptPythonDecoder
+
+ graph = torch._C.parse_ir(ir)
+ node = list(graph.nodes())[-1]
+ decoder = TorchScriptPythonDecoder(None, node, alias_db=graph.alias_db())
+ assert decoder.get_input_sequences() == ({0: expected} if expected else {})
+
+
[email protected]("metadata", [False, True])
[email protected]("wrapped,legacy", [(False, True), (True, False), (True, True)])
+def test_pytorch_decoder_conversion_without_sequence_override(metadata, wrapped, legacy):
+ import numpy as np
+ import openvino as ov
+ from openvino.frontend.pytorch.ts_decoder import TorchScriptPythonDecoder
+ from openvino.frontend.pytorch.py_pytorch_frontend import _FrontEndPytorchDecoder
+
+ class LegacyDecoder(_FrontEndPytorchDecoder):
+ def __init__(self, wrapped):
+ super().__init__()
+ self.wrapped = wrapped
+ self.children = []
+
+ def __getattr__(self, name):
+ if name == "get_input_sequences":
+ raise AttributeError(name)
+ return getattr(self.wrapped, name)
+
+ def visit_subgraph(self, visitor):
+ def wrap_child(child):
+ decoder = LegacyDecoder(child)
+ self.children.append(decoder)
+ visitor(decoder)
+ self.wrapped.visit_subgraph(wrap_child)
+
+ ir = """graph(%left : Tensor, %right : Tensor):
+ %pair : (Tensor, Tensor) = prim::TupleConstruct(%left, %right)
+ %first : Tensor, %second : Tensor = prim::TupleUnpack(%pair)
+ %one : int = prim::Constant[value=1]()
+ %updated : Tensor = aten::add_(%second, %one, %one)
+ return (%left, %right, %first, %second)
+ """
+ if metadata:
+ ir = ir.replace("aten::add_(%second, %one, %one)", "aten::unsqueeze_(%second, %one)")
+ if wrapped:
+ ir = ir.replace("%first : Tensor, %second : Tensor = prim::TupleUnpack(%pair)", """
+ %wrapped : ((Tensor, Tensor)) = prim::TupleConstruct(%pair)
+ %alias : (Tensor, Tensor) = prim::TupleUnpack(%wrapped)
+ %first : Tensor, %second : Tensor = prim::TupleUnpack(%alias)""").replace(
+ "return (%left, %right, %first, %second)",
+ "return (%left, %right, %first, %second, %pair, %alias)")
+ graph = torch._C.parse_ir(ir)
+ decoder = TorchScriptPythonDecoder(None, graph, alias_db=graph.alias_db())
+ if legacy:
+ decoder = LegacyDecoder(decoder)
+ frontend = ov.frontend.FrontEndManager().load_by_framework("pytorch")
+ input_model = frontend.load(decoder)
+ for place in input_model.get_inputs():
+ input_model.set_element_type(place, ov.Type.f32)
+ input_model.set_partial_shape(place, ov.PartialShape([2, 3]))
+ converted = frontend.convert(input_model)
+ compiled = ov.Core().compile_model(converted, "CPU")
+ data = torch.arange(6, dtype=torch.float32).reshape(2, 3).numpy()
+ right = data + 10
+ actual = list(compiled([data, right]).values())
+ updated = right[:, None, :] if metadata else right + 1
+ expected = (data, updated, data, updated) + ((data, updated, data, updated) if wrapped else ())
+ assert len(actual) == len(expected)
+ for result, expected in zip(actual, expected):
+ np.testing.assert_array_equal(result, expected)
diff --git a/tests/layer_tests/py_frontend_tests/test_torch_mutation_normalization.py b/tests/layer_tests/py_frontend_tests/test_torch_mutation_normalization.py
new file mode 100644
index 00000000000..fcc56db822d
--- /dev/null
+++ b/tests/layer_tests/py_frontend_tests/test_torch_mutation_normalization.py
@@ -0,0 +1,35 @@
+# Copyright (C) 2018-2026 Intel Corporation
+# SPDX-License-Identifier: Apache-2.0
+
+import numpy as np
+import openvino as ov
+import pytest
+import torch
+
+
+class FrameSliceMutation(torch.nn.Module):
+ def forward(self, source):
+ frames = torch.zeros_like(source)
+ for index in range(source.shape[1]):
+ frames[:, index] = source[:, index]
+ selected = frames[0, source[0, :, 0] > 0]
+ output = torch.zeros_like(source)
+ output[0, :selected.size(0), :] = selected
+ return output
+
+
[email protected]("trace", [False, True])
+def test_slice_mutation_uses_updated_shapes_after_loop(trace):
+ generator = torch.Generator().manual_seed(42)
+ example = torch.randn(2, 5, 4, generator=generator)
+ module = FrameSliceMutation()
+ model = torch.jit.trace(torch.jit.script(module), example) if trace else torch.jit.script(module)
+ converted = ov.convert_model(model, example_input=(example,))
+ compiled = ov.Core().compile_model(converted, "CPU", {"INFERENCE_PRECISION_HINT": "f32"})
+ for batch, length in ((2, 5), (1, 7), (3, 4)):
+ source = torch.randn(batch, length, 4, generator=generator)
+ expected = model(source).numpy()
+ actual = next(iter(compiled([source.numpy()]).values()))
+ np.testing.assert_array_equal(actual, expected)