Skip to content

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

[PyTorch] Avoid false ModuleExtension output aliases (#39963)

Maxim Vafine8d09770824e
diff --git a/src/bindings/python/src/openvino/frontend/pytorch/module_extension.py b/src/bindings/python/src/openvino/frontend/pytorch/module_extension.py
index 3a33f9acf89..da8a520a80d 100644
--- a/src/bindings/python/src/openvino/frontend/pytorch/module_extension.py
+++ b/src/bindings/python/src/openvino/frontend/pytorch/module_extension.py
@@ -12,6 +12,11 @@ class ModuleExtension:
A module can be identified by its type (e.g., `torch.nn.Linear`), module
instance in the model, or module name.
+
+ In TorchScript conversion, the replacement operation's outputs are assumed
+ not to alias its inputs. Returning an input or a view of one is unsupported:
+ aliasing is not preserved, and in-place mutations involving aliased outputs
+ may silently produce incorrect results.
"""
def __init__(self,
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 db5b2559af0..fa80dc2bd2d 100644
--- a/src/bindings/python/src/openvino/frontend/pytorch/ts_decoder.py
+++ b/src/bindings/python/src/openvino/frontend/pytorch/ts_decoder.py
@@ -580,6 +580,9 @@ class TorchScriptPythonDecoder(TorchDecoderBase):
def may_produce_alias(self, in_index: int, out_index: int) -> bool:
try:
+ extension = self.get_op_extension()
+ if extension and isinstance(extension[1], ModuleExtension):
+ return False
schema_text = self.get_schema()
if schema_text != "(no schema)":
returns = _parse_schema(schema_text).returns
diff --git a/src/frontends/pytorch/README.md b/src/frontends/pytorch/README.md
index 325bbca5311..b4eddd3c63d 100644
--- a/src/frontends/pytorch/README.md
+++ b/src/frontends/pytorch/README.md
@@ -58,6 +58,13 @@ The following extension types are supported:
* `ov::BaseOpExtension` - enable support for a custom operation.
* `ov::detail::SOExtension` - allow support for `ov::BaseOpExtension` extensions loaded from an external library.
+### Python module extensions
+
+For TorchScript conversion, `ModuleExtension` replacement operations are assumed
+to return tensors that do not alias their inputs. Returning an input or a view
+of one is unsupported: aliasing is not preserved, and in-place mutations
+involving aliased outputs may silently produce incorrect results.
+
### Context-manager scopes in exported models
OpenVINO performs inference only. `torch.export` represents `torch.no_grad()`,
diff --git a/tests/layer_tests/py_frontend_tests/test_torch_frontend.py b/tests/layer_tests/py_frontend_tests/test_torch_frontend.py
index acb0ffaf860..c6fa0a059c1 100644
--- a/tests/layer_tests/py_frontend_tests/test_torch_frontend.py
+++ b/tests/layer_tests/py_frontend_tests/test_torch_frontend.py
@@ -839,6 +839,172 @@ def test_module_extension_dynamo_custom_callbacks():
PartialShape([100])
[email protected]("dtype", [torch.float32, torch.float16])
[email protected]("kind", ["linear", "conv1d"])
+def test_patched_projection_output_view_mutation(dtype, kind):
+ from openvino import convert_model, compile_model
+ from openvino.frontend.pytorch import patch_model
+
+ class Model(torch.nn.Module):
+ def __init__(self):
+ super().__init__()
+ if kind == "linear":
+ self.proj = torch.nn.Linear(8, 8, dtype=dtype)
+ else:
+ conv1d = pytest.importorskip("transformers.pytorch_utils").Conv1D
+ self.proj = conv1d(8, 8).to(dtype=dtype)
+
+ def forward(self, x):
+ query = self.proj(x)
+ sibling = self.proj(x)
+ query = query.view(1, 4, 2, 4).transpose(1, 2)
+ query[:, :1] = -query[:, :1]
+ return query, sibling, x
+
+ torch.manual_seed(0)
+ model = Model().eval()
+ example = torch.randn(1, 4, 8, dtype=dtype)
+ with torch.no_grad():
+ expected = tuple(value.numpy() for value in model(example))
+ try:
+ patch_model.__make_16bit_traceable(model)
+ converted = convert_model(model, example_input=example)
+ actual = compile_model(converted, "CPU", default_cfg)(example.numpy())
+ for index, value in enumerate(expected):
+ np.testing.assert_allclose(actual[index], value, atol=2e-3, rtol=2e-3)
+ finally:
+ patch_model.unpatch_model(model, "_openvino_module_extension_patch_orig_forward")
+
+
+def test_patched_bmm_output_view_mutation():
+ from openvino import convert_model, compile_model
+ from openvino.frontend.pytorch import patch_model
+
+ class Model(torch.nn.Module):
+ def forward(self, x, y):
+ query = torch.bmm(x, y)
+ sibling = torch.bmm(x, y)
+ query[:, :1] = -query[:, :1]
+ return query, sibling, x, y
+
+ model = Model().eval()
+ generator = torch.Generator().manual_seed(0)
+ example = (torch.randn(1, 4, 8, generator=generator), torch.randn(1, 8, 8, generator=generator))
+ with torch.no_grad():
+ expected = tuple(value.numpy().copy() for value in model(*example))
+ try:
+ patch_model.__make_16bit_traceable(model)
+ converted = convert_model(model, example_input=example)
+ actual = compile_model(converted, "CPU", default_cfg)([value.numpy() for value in example])
+ for index, value in enumerate(expected):
+ np.testing.assert_allclose(actual[index], value, atol=1e-5, rtol=1e-5)
+ finally:
+ patch_model.unpatch_model(model, "_openvino_module_extension_patch_orig_forward")
+
+
[email protected]("target_op", ["aten::sin", "CustomSin"])
[email protected]("mutation", ["view", "direct"])
+def test_custom_module_extension_output_mutation(target_op, mutation):
+ from openvino import convert_model, compile_model
+ from openvino.frontend.pytorch import ModuleExtension, ConversionExtension
+
+ class Projection(torch.nn.Module):
+ def forward(self, x):
+ return torch.sin(x)
+
+ class Model(torch.nn.Module):
+ def __init__(self):
+ super().__init__()
+ self.proj = Projection()
+
+ def forward(self, x):
+ query = self.proj(x)
+ sibling = self.proj(x)
+ if mutation == "view":
+ query = query.view(1, 4, 2, 4).transpose(1, 2)
+ query[:, :1] = -query[:, :1]
+ else:
+ query.add_(1)
+ return query, sibling, x
+
+ model = Model().eval()
+ example = torch.linspace(-1, 1, 32).reshape(1, 4, 8)
+ extensions = [ModuleExtension(Projection, target_op)]
+ if target_op == "CustomSin":
+ extensions.append(ConversionExtension(target_op, lambda context: ops.sin(context.get_input(0)).outputs()))
+
+ with torch.no_grad():
+ expected = tuple(value.numpy().copy() for value in model(example))
+ converted = convert_model(model, example_input=example, extension=extensions)
+ actual = compile_model(converted, "CPU", default_cfg)(example.numpy())
+ for index, value in enumerate(expected):
+ np.testing.assert_allclose(actual[index], value, atol=1e-5, rtol=1e-5)
+
+
+def test_non_module_extension_pythonop_uses_alias_db():
+ from unittest.mock import Mock
+ from openvino.frontend.pytorch.ts_decoder import TorchScriptPythonDecoder
+
+ class SinFunction(torch.autograd.Function):
+ @staticmethod
+ def forward(ctx, x):
+ return torch.sin(x)
+
+ class Model(torch.nn.Module):
+ def forward(self, x):
+ return SinFunction.apply(x)
+
+ model = Model().eval()
+ example = torch.arange(24, dtype=torch.float32).reshape(1, 3, 8)
+ decoder = TorchScriptPythonDecoder(model, example_input=example)
+ nodes = []
+ decoder.visit_subgraph(nodes.append)
+ node = next(node for node in nodes if node.get_op_type() == "prim::PythonOp")
+ node.alias_db = Mock()
+ node.alias_db.may_contain_alias.return_value = True
+ assert node.may_produce_alias(0, 0)
+ node.alias_db.may_contain_alias.assert_called_once()
+
+
+def test_module_extension_pythonop_skips_alias_db():
+ from unittest.mock import Mock
+ from openvino.frontend.pytorch import ModuleExtension, patch_model
+ from openvino.frontend.pytorch.ts_decoder import TorchScriptPythonDecoder
+
+ class Projection(torch.nn.Module):
+ def forward(self, x):
+ return torch.sin(x)
+
+ class Model(torch.nn.Module):
+ def __init__(self):
+ super().__init__()
+ self.proj = Projection()
+
+ def forward(self, x):
+ return self.proj(x)
+
+ model = Model().eval()
+ example = torch.arange(24, dtype=torch.float32).reshape(1, 3, 8)
+ extensions = {Projection: ModuleExtension(Projection, "aten::sin")}
+ try:
+ decoder = TorchScriptPythonDecoder(
+ model, example_input=(example,), module_extensions=extensions)
+ nodes = []
+ decoder.visit_subgraph(nodes.append)
+ node = next(node for node in nodes if node.get_op_extension())
+ assert isinstance(node.get_op_extension()[1], ModuleExtension)
+ node.alias_db = Mock()
+ assert not node.may_produce_alias(0, 0)
+ node.alias_db.may_contain_alias.assert_not_called()
+ finally:
+ patch_model.unpatch_model(model, "_openvino_module_extension_patch_orig_forward")
+
+
@pytest.mark.parametrize("dtype", [torch.float16, torch.bfloat16])
def test_make_16bit_traceable_preserves_extension_dtypes(dtype):
"""__make_16bit_traceable exposes FP32 placeholders for ModuleExtension