Skip to content

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

[PT FE] Introduce inlined_extension (#30355)

Maxim Vafinb85c5f2b1148
diff --git a/src/bindings/python/src/openvino/frontend/pytorch/__init__.py b/src/bindings/python/src/openvino/frontend/pytorch/__init__.py
index 3504c495344..2c843bc9958 100644
--- a/src/bindings/python/src/openvino/frontend/pytorch/__init__.py
+++ b/src/bindings/python/src/openvino/frontend/pytorch/__init__.py
@@ -13,5 +13,6 @@ try:
from openvino.frontend.pytorch.py_pytorch_frontend import ConversionExtensionPytorch as ConversionExtension
from openvino.frontend.pytorch.py_pytorch_frontend import OpExtensionPytorch as OpExtension
from openvino.frontend.pytorch.module_extension import ModuleExtension
+ from openvino.frontend.pytorch.inlined_extension import inlined_extension
except ImportError as err:
raise ImportError(f"OpenVINO PyTorch frontend is not available, please make sure the frontend is built. {err}")
diff --git a/src/bindings/python/src/openvino/frontend/pytorch/inlined_extension.py b/src/bindings/python/src/openvino/frontend/pytorch/inlined_extension.py
new file mode 100644
index 00000000000..0df31ac2629
--- /dev/null
+++ b/src/bindings/python/src/openvino/frontend/pytorch/inlined_extension.py
@@ -0,0 +1,260 @@
+# -*- coding: utf-8 -*-
+# Copyright (C) 2018-2025 Intel Corporation
+# SPDX-License-Identifier: Apache-2.0
+
+from typing import Any, Callable, Union, Optional
+import torch
+import numpy as np
+import openvino as ov
+from openvino.frontend.pytorch.ts_decoder import InlineConversionExtension
+from openvino.frontend.pytorch.utils import pt_to_ov_type_map, no_jit_trace
+
+
+class ConstWrap:
+ """Wraps a constant value for comparison and representation."""
+
+ def __init__(self, value: Any) -> None:
+ self.value = value
+
+ def __eq__(self, other: Any) -> bool:
+ return self.value == other
+
+ def __repr__(self) -> str:
+ return f"ConstWrap({str(self.value)})"
+
+
+def unpack(
+ packed: Any,
+ types: Union[type, tuple[type, ...]],
+ index: int = 0
+) -> tuple[tuple, Any, int]:
+ """Unpacks nested structures into a flat tuple."""
+ unpacked_result: tuple = ()
+ packer_result: Any = None
+ if isinstance(packed, tuple):
+ packer_result = ()
+ for el in packed:
+ unpacked, packer, index = unpack(el, types, index)
+ unpacked_result += unpacked
+ packer_result += (packer,)
+ elif isinstance(packed, list):
+ packer_result = []
+ for el in packed:
+ unpacked, packer, index = unpack(el, types, index)
+ unpacked_result += unpacked
+ packer_result.append(packer)
+ elif isinstance(packed, dict):
+ packer_result = {}
+ for key, el in packed.items():
+ unpacked, packer, index = unpack(el, types, index)
+ unpacked_result += unpacked
+ packer_result[key] = packer
+ elif isinstance(packed, types):
+ unpacked_result = (packed,)
+ packer_result = index
+ index += 1
+ else:
+ packer_result = ConstWrap(packed)
+ return unpacked_result, packer_result, index
+
+
+def pack(unpacked: tuple, packer: Any) -> Any:
+ """Packs unpacked elements back into their original structure."""
+ if isinstance(packer, (tuple, list)):
+ return type(packer)(pack(unpacked, el) for el in packer)
+ if isinstance(packer, dict):
+ return {k: pack(unpacked, v) for k, v in packer.items()}
+ if isinstance(packer, ConstWrap):
+ return packer.value
+ return unpacked[packer]
+
+
+global_counter_id = 0
+
+
+def make_custom_op_class(func: Callable,
+ input_signature: tuple[tuple[Any, Any], ...],
+ output_signature: tuple[tuple[Any, Any], ...],
+ input_packer: Any,
+ output_packer: Any) -> type:
+ """Creates a custom operation class from a function and signatures."""
+ global global_counter_id
+
+ class InlinedCustomOp(ov.Op): # type: ignore
+ class_type_info = ov.runtime.DiscreteTypeInfo(
+ "InlinedCustomOp", "extension")
+
+ def __init__(self, *args: Any) -> None:
+ # TODO: What about attributes?
+ super().__init__(self, args)
+ # `id` attribute distinguishes different instances of the same
+ # class, we need it because different instances may have different
+ # behavior
+ self.attrs = {"id": global_counter_id}
+ self.constructor_validate_and_infer_types()
+
+ def evaluate(self, outputs: Any, inputs: Any) -> bool:
+ # TODO: Check memory sharing
+ inputs_torch = tuple(torch.from_numpy(input.data)
+ for input in inputs)
+ args, kwargs = pack(inputs_torch, input_packer)
+ result = func(*args, **kwargs)
+ result, result_packer, _ = unpack(result, torch.Tensor)
+ assert result_packer == output_packer
+ for i, tensor in enumerate(result):
+ if isinstance(tensor, torch.Tensor):
+ ov_t = ov.Tensor(tensor.numpy(
+ force=True), shared_memory=True)
+ else:
+ ov_t = ov.Tensor(np.array(tensor), shared_memory=True)
+ # TODO: set the output tensor directly without copying
+ ov_t.copy_to(outputs[i])
+ return True
+
+ def has_evaluate(self, *args: Any) -> bool:
+ return True
+
+ def visit_attributes(self, visitor: Any) -> bool:
+ visitor.on_attributes(self.attrs)
+ return True
+
+ def validate_and_infer_types(self) -> None:
+ # TODO: Validate input signature
+ assert output_signature != (), (
+ "Operation does not produce any output. "
+ "It will be removed from the graph."
+ )
+ for i, output in enumerate(output_signature):
+ self.set_output_type(i, output[0], output[1])
+
+ global_counter_id += 1
+ return InlinedCustomOp
+
+
+def make_signature(args: Any) -> tuple[tuple[Any, Any], ...]:
+ """Generate a signature tuple for PyTorch tensors.
+
+ Maps PyTorch tensor types to OpenVINO types and partial shapes, setting
+ all dimensions dynamic preserving rank. Currently assumes that all input
+ arguments are torch.Tensor.
+ """
+ # TODO: Extend beyond just tensors
+ return tuple(
+ (pt_to_ov_type_map.get(str(arg.dtype)), ov.PartialShape.dynamic(arg.ndim))
+ for arg in args
+ )
+
+
+def make_input_signature(args: Any) -> tuple[tuple[Any, Any], ...]:
+ """Generates an input signature for the provided arguments."""
+ return make_signature(args)
+
+
+def make_output_signature(args: Any) -> tuple[tuple[Any, Any], ...]:
+ """Generates an output signature for the provided arguments."""
+ if args is None:
+ args = ()
+ if not isinstance(args, tuple):
+ args = (args,)
+ return make_signature(args)
+
+
+def make_trampoline_class(func: Callable,
+ op: Optional[type],
+ op_attrs: Any) -> type[torch.autograd.Function]:
+ """Creates a trampoline class for a function."""
+
+ class Trampoline(torch.autograd.Function):
+ # this is a marker for this type of extension
+ target_extension = InlineConversionExtension()
+
+ # This function defines how the operation behaves when called as a
+ # part of PyTorch model code in eager execution or while jit.trace
+ @staticmethod
+ def forward(ctx: Any, *call_args: Any) -> Any:
+ cls = ctx._forward_cls
+ if not op:
+ input_signature = make_input_signature(call_args)
+ # TODO: Try to trace `func` with the hope to obtain traceable
+ # shapes to build more precise `validate_and_infer_types`
+ # automatically (unlikely possible)
+ packed_args, packed_kwargs = pack(
+ call_args, cls.input_packer)
+ with no_jit_trace():
+ result = func(*packed_args, **packed_kwargs)
+ result, cls.output_packer, _ = unpack(result, torch.Tensor)
+ if not op:
+ output_signature = make_output_signature(result)
+ cls.op = make_custom_op_class(func, input_signature,
+ output_signature,
+ cls.input_packer,
+ cls.output_packer)
+ else:
+ cls.op = op
+ return result
+
+ @classmethod
+ def unpack_inputs(cls, args: Any, kwargs: Any) -> tuple:
+ """Unpacks inputs for the operation.
+
+ Unpack each element that is a tuple, a list, or a dict to a
+ tuple of their values and concatenate together. Build `packer`
+ function to pack the result back to the original nested data
+ types, save this `packer` to class member to use it later in
+ `forward`.
+ """
+ unpacked, cls.input_packer, _ = unpack(
+ (args, kwargs), torch.Tensor)
+ return unpacked
+
+ @classmethod
+ def pack_outputs(cls, result: Any) -> Any:
+ """Packs outputs for the operation."""
+ return pack(result, cls.output_packer)
+
+ @classmethod
+ def convert(cls, node_context: Any) -> tuple:
+ """Defines how the operation is represented in graph."""
+ num_inps = node_context.get_input_size()
+ inputs = [node_context.get_input(i) for i in range(num_inps)]
+ node = cls.op(*inputs, **op_attrs)
+ # to trigger prim::TupleUnpack bypass in FrontEnd transformation
+ node.get_rt_info()["__torch_tuple_unpackable__"] = True
+ return node.outputs()
+
+ return Trampoline
+
+
+def inlined_extension(*args: Any, **op_attrs: Any) -> Callable:
+ """Creates an inlined extension for a function."""
+
+ def make_trampoline(func: Callable,
+ op: Optional[type] = None) -> Callable:
+ def trampoline(*args: Any, **kwargs: Any) -> Any:
+ # Keep trampoline class creation at the point when the function is
+ # called to make each time a new trampoline. It is required
+ # because `func` is fused inside Trampoline class and can have
+ # different behavior from call to call in PyTorch world even if
+ # the same op is specified to wrap multiple different functions.
+ # It happens due to capturing a global context and values kept in
+ # non-traceable part of inputs.
+ trampoline = make_trampoline_class(func, op, op_attrs)
+ # flattening inputs and unflattening outputs should be visible for
+ # PyTorch jit tracer, so it should be called outside of
+ # `trampoline.apply` to have clean Tensor-only signature for the
+ # custom op. Non-traceable part of inputs (and outputs) is captured
+ # as `trampoline` class fields.
+ args = trampoline.unpack_inputs(args, kwargs)
+ result = trampoline.apply(*args) # type: ignore
+ # pack to the expected nested data types here
+ return trampoline.pack_outputs(result)
+ return trampoline
+
+ if (len(args) == 1 and callable(args[0])
+ and not (isinstance(args[0], type)
+ and issubclass(args[0], ov.Op))):
+ func = args[0]
+ return make_trampoline(func)
+
+ op = args[0]
+ return lambda func: make_trampoline(func, op)
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 82649ca28b4..8a0c0bfb79c 100644
--- a/src/bindings/python/src/openvino/frontend/pytorch/ts_decoder.py
+++ b/src/bindings/python/src/openvino/frontend/pytorch/ts_decoder.py
@@ -32,6 +32,11 @@ from openvino.frontend.pytorch.patch_functions import FunctionsPatcher
log = logging.getLogger(__name__)
+# A marker for a special type of conversion extension that is inlined in Trampoline class
+class InlineConversionExtension:
+ pass
+
+
class TorchScriptPythonDecoder(Decoder):
def __init__(
self,
@@ -344,14 +349,17 @@ class TorchScriptPythonDecoder(Decoder):
self.m_decoders.append(decoder)
return decoder
- def get_op_type(self) -> str:
+ def get_op_extension(self):
assert isinstance(
self.graph_element, torch.Node), "Function can be called only when self.graph_element is of type torch.Node"
if self.graph_element.kind() == "prim::PythonOp" and callable(getattr(self.graph_element, "pyobj", None)):
pyobj = self.graph_element.pyobj()
trampoline = getattr(pyobj, "__self__", None)
- target_extension = getattr(trampoline, "target_extension", None)
+ return trampoline, getattr(trampoline, "target_extension", None)
+ def get_op_type(self) -> str:
+ if op_extension := self.get_op_extension():
+ trampoline, target_extension = op_extension
if isinstance(target_extension, ModuleExtension):
target_op = target_extension.target_op
if callable(target_op):
@@ -618,3 +626,24 @@ class TorchScriptPythonDecoder(Decoder):
const_input.node().moveBefore(node)
const_input.node().copyMetadata(node)
node.output().replaceAllUsesWith(const_input)
+
+ def has_converter(self):
+ if op_extension := self.get_op_extension():
+ _, target_extension = op_extension
+ return isinstance(target_extension, InlineConversionExtension)
+ return False
+
+ def convert(self, node_context):
+ if op_extension := self.get_op_extension():
+ trampoline, target_extension = op_extension
+ assert isinstance(target_extension, InlineConversionExtension)
+ try:
+ return trampoline.convert(node_context)
+ except Exception as e:
+ log.error("Exception happened during calling of custom "
+ "converter for PyTorch operation. PyTorch Script "
+ "code: %s", self.graph_element, exc_info=e)
+ raise
+ raise AssertionError("PyTorch FrontEnd Internal Error: `converter` "
+ "method of TorchScriptPythonDecoder is called "
+ "for node that has no custom converter")
diff --git a/src/bindings/python/src/openvino/frontend/pytorch/utils.py b/src/bindings/python/src/openvino/frontend/pytorch/utils.py
index 4390c600e19..f6d9566c49f 100644
--- a/src/bindings/python/src/openvino/frontend/pytorch/utils.py
+++ b/src/bindings/python/src/openvino/frontend/pytorch/utils.py
@@ -8,6 +8,7 @@ import inspect
import logging
import torch
import numpy as np
+from contextlib import contextmanager
from openvino import op, Type as OVType, Shape, Tensor, OVAny
from openvino import opset11 as ops
@@ -395,3 +396,17 @@ def patch_none_example(model: torch.nn.Module, example):
"with None will be removed from the resulting model.")
return wrapped_model, new_example
return model, example
+
+
+@contextmanager
+def no_jit_trace():
+ """Context manager to disable JIT tracing.
+
+ Note: using this function on large models consume a lot of memory.
+ """
+ state = torch._C._get_tracing_state()
+ torch._C._set_tracing_state(None)
+ try:
+ yield
+ finally:
+ torch._C._set_tracing_state(state)
diff --git a/src/bindings/python/src/pyopenvino/frontend/pytorch/decoder.hpp b/src/bindings/python/src/pyopenvino/frontend/pytorch/decoder.hpp
index bc67d3a1706..632d648e0dc 100644
--- a/src/bindings/python/src/pyopenvino/frontend/pytorch/decoder.hpp
+++ b/src/bindings/python/src/pyopenvino/frontend/pytorch/decoder.hpp
@@ -7,6 +7,7 @@
#include <pybind11/pybind11.h>
#include "openvino/frontend/pytorch/decoder.hpp"
+#include "openvino/frontend/node_context.hpp"
namespace py = pybind11;
@@ -137,6 +138,14 @@ class PyDecoder : public ov::frontend::pytorch::TorchDecoder {
ov::frontend::pytorch::DecoderRTInfo get_rt_info() const override {
PYBIND11_OVERRIDE_PURE(ov::frontend::pytorch::DecoderRTInfo, TorchDecoder, get_rt_info);
}
+
+ bool has_converter() const override {
+ PYBIND11_OVERRIDE_PURE(bool, TorchDecoder, has_converter);
+ }
+
+ ov::OutputVector convert(const ov::frontend::NodeContext* context) const override {
+ PYBIND11_OVERRIDE_PURE(ov::OutputVector, TorchDecoder, convert, context);
+ }
};
void regclass_frontend_pytorch_decoder(py::module m);
diff --git a/src/common/transformations/src/transformations/convert_precision.cpp b/src/common/transformations/src/transformations/convert_precision.cpp
index 76cd43b7f22..4535ac0f5e8 100644
--- a/src/common/transformations/src/transformations/convert_precision.cpp
+++ b/src/common/transformations/src/transformations/convert_precision.cpp
@@ -481,7 +481,10 @@ bool ov::pass::ConvertPrecision::run_on_model(const std::shared_ptr<ov::Model>&
{ov::op::v8::PriorBox::get_type_info_static(), fuse_type_to_prior_box<ov::op::v8::PriorBox>},
{ov::op::v0::PriorBoxClustered::get_type_info_static(), fuse_type_to_prior_box<ov::op::v0::PriorBoxClustered>},
{ov::op::v15::SearchSorted::get_type_info_static(), fuse_type_to_search_sorted_v15},
- {ov::op::internal::RMS::get_type_info_static(), fuse_type_to_rms}};
+ {ov::op::internal::RMS::get_type_info_static(), fuse_type_to_rms},
+ // This is operation representing inline_extension from
+ // src/bindings/python/src/openvino/frontend/pytorch/inlined_extension.py
+ {ov::DiscreteTypeInfo("InlinedCustomOp", "extension"), wrap_into_original_type}};
for (const auto& it : m_additional_type_to_fuse_map) {
type_to_fuse[it.first] = it.second;
diff --git a/src/frontends/pytorch/include/openvino/frontend/pytorch/decoder.hpp b/src/frontends/pytorch/include/openvino/frontend/pytorch/decoder.hpp
index 97546c03534..8564feeeef7 100644
--- a/src/frontends/pytorch/include/openvino/frontend/pytorch/decoder.hpp
+++ b/src/frontends/pytorch/include/openvino/frontend/pytorch/decoder.hpp
@@ -6,6 +6,7 @@
#include "openvino/core/node.hpp"
#include "openvino/frontend/decoder.hpp"
+#include "openvino/frontend/node_context.hpp"
#include "openvino/frontend/pytorch/visibility.hpp"
namespace ov {
@@ -134,6 +135,15 @@ public:
/// \brief Returns the rt_info for the element
virtual DecoderRTInfo get_rt_info() const = 0;
+
+ /// \brief Returns if node has a custom converter that should be used instead (if any) of the default converter
+ /// registered in front-end If this method returns true, `convert` method should be used as a conversion extension
+ /// for this node instead of (any) default converter Such node may not have implemented other methods, like
+ /// `get_op_type` that usually are implemented for "normal" nodes.
+ virtual bool has_converter() const = 0;
+
+ /// \brief Converts the node if `has_converter` returns true
+ virtual OutputVector convert(const ov::frontend::NodeContext* context) const = 0;
};
} // namespace pytorch
diff --git a/src/frontends/pytorch/src/op/pythonop.cpp b/src/frontends/pytorch/src/op/pythonop.cpp
index 6cd1465414a..37495f331e1 100644
--- a/src/frontends/pytorch/src/op/pythonop.cpp
+++ b/src/frontends/pytorch/src/op/pythonop.cpp
@@ -13,6 +13,11 @@ namespace op {
OutputVector translate_pythonop(const NodeContext& context) {
auto decoder = context.get_decoder();
+ if (decoder->has_converter()) {
+ // If the node has a custom converter, use it
+ // A custom converter is defined for in-model definition of a custom operation.
+ return decoder->convert(&context);
+ }
PYTORCH_OP_CONVERSION_CHECK(decoder->get_subgraph_size() == 1,
"PythonOp must have 1 subgraph to be able to translate it to OV.");
auto body = context.convert_subgraph(0);
diff --git a/src/frontends/pytorch/src/transforms/tuple_unpack_replacer.cpp b/src/frontends/pytorch/src/transforms/tuple_unpack_replacer.cpp
index 256e29072db..d4595d8fe5c 100644
--- a/src/frontends/pytorch/src/transforms/tuple_unpack_replacer.cpp
+++ b/src/frontends/pytorch/src/transforms/tuple_unpack_replacer.cpp
@@ -47,6 +47,12 @@ PrimTupleUnpackReplacer::PrimTupleUnpackReplacer() {
replace_output_update_name(tuple_unpack->output(i), squeeze);
}
return true;
+ } else if (input_node->get_rt_info().count("__torch_tuple_unpackable__")) {
+ // This case is produced by inlined_extension
+ input_node->get_rt_info().erase("__torch_tuple_unpackable__");
+ // remove TupleUnpack just bypassing it with all outputs from a custom operation which returns tuple
+ replace_node(tuple_unpack, input_node->outputs());
+ return true;
}
return false;
};
diff --git a/src/frontends/pytorch/src/utils.hpp b/src/frontends/pytorch/src/utils.hpp
index 76a97cdbcc3..8f766f8f10b 100644
--- a/src/frontends/pytorch/src/utils.hpp
+++ b/src/frontends/pytorch/src/utils.hpp
@@ -326,6 +326,12 @@ public:
virtual std::unordered_map<std::string, ov::Any> get_rt_info() const override {
FRONT_END_NOT_IMPLEMENTED(get_rt_info);
}
+ virtual bool has_converter() const override {
+ FRONT_END_NOT_IMPLEMENTED(has_converter);
+ }
+ virtual OutputVector convert(const ov::frontend::NodeContext* context) const override {
+ FRONT_END_NOT_IMPLEMENTED(convert);
+ }
private:
const std::string m_schema = "NONE";
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 37bb789e765..2c194ccf62b 100644
--- a/tests/layer_tests/py_frontend_tests/test_torch_frontend.py
+++ b/tests/layer_tests/py_frontend_tests/test_torch_frontend.py
@@ -8,6 +8,7 @@ import math
import os
import re
import logging
+import platform
from pathlib import Path
import torch
@@ -256,7 +257,7 @@ def test_so_extension():
converted_model = fe.convert(input_model)
assert converted_model
assert [n.get_type_name() for n in converted_model.get_ordered_ops()] == [
- 'Parameter', 'Elu', 'Constant', 'ConvertLike', 'Multiply', 'Result']
+ "Parameter", "Elu", "Constant", "ConvertLike", "Multiply", "Result"]
fe.add_extension(get_builtin_extensions_path())
converted_model = fe.convert(input_model)
@@ -464,6 +465,148 @@ def test_multiple_module_extension():
"Parameter", "Sin", "Tan", "Add", "Result"]
+def verify_model(model, example_input, expected_ops):
+ import numpy as np
+ import openvino as ov
+ # Convert and compile the model
+ converted_model = ov.convert_model(model, example_input=(example_input,))
+ assert converted_model, "Model conversion failed."
+ compiled_model = ov.compile_model(converted_model, "CPU")
+ assert compiled_model, "Model compilation failed."
+
+ # Verify model operations
+ actual_ops = [n.get_type_name() for n in converted_model.get_ordered_ops()]
+ assert actual_ops == expected_ops, f"Expected {expected_ops}, but got {actual_ops}."
+
+ # Test model execution
+ test_input = example_input.numpy(force=True)
+ res = compiled_model((test_input,))
+ ref = model(torch.from_numpy(test_input))
+ rtol, atol = 1e-7, 0
+ if platform.machine() in ('arm', 'armv7l', 'aarch64', 'arm64', 'ARM64'):
+ rtol, atol = 0.1, 0.001
+ if isinstance(ref, tuple):
+ for i, ref_part in enumerate(ref):
+ np.testing.assert_allclose(res[i], ref_part.numpy(), rtol, atol)
+ else:
+ np.testing.assert_allclose(res[0], ref.numpy(), rtol, atol)
+
+
+def test_inlined_extension():
+ from openvino.frontend.pytorch import inlined_extension
+ rng = np.random.default_rng(42)
+
+ @inlined_extension
+ def numpy_cos(x):
+ return torch.from_numpy(np.cos(x.numpy(force=True)))
+
+ class ModelWithModule(torch.nn.Module):
+ def __init__(self):
+ super().__init__()
+ self.relu_module = torch.nn.ReLU()
+
+ def forward(self, x):
+ x = x.to(torch.float32)
+ return numpy_cos(x) + self.relu_module(x)
+
+ model = ModelWithModule()
+ example = torch.from_numpy(rng.random([100], dtype=np.float32))
+ expected_ops = ["Parameter", "InlinedCustomOp", "Relu", "Add", "Result"]
+ verify_model(model, example, expected_ops)
+
+
+def test_multiple_inlined_extension():
+ from openvino.frontend.pytorch import inlined_extension
+ rng = np.random.default_rng(42)
+
+ @inlined_extension
+ def numpy_roll(x):
+ return torch.from_numpy(np.roll(x.numpy(force=True), 10, 0))
+
+ @inlined_extension
+ def numpy_cos(x):
+ return torch.from_numpy(np.cos(x.numpy(force=True)))
+
+ class ModelWithModule(torch.nn.Module):
+ def __init__(self):
+ super().__init__()
+ self.relu_module = torch.nn.ReLU()
+
+ def forward(self, x):
+ x = x.to(torch.float32)
+ x = numpy_roll(x) + self.relu_module(x)
+ x = numpy_cos(x) + self.relu_module(x)
+ return numpy_roll(x) + self.relu_module(x)
+
+ model = ModelWithModule()
+ example = torch.from_numpy(rng.random([100], dtype=np.float32))
+ expected_ops = ["Parameter", "InlinedCustomOp", "Relu", "Add", "InlinedCustomOp", "Relu", "Add", "InlinedCustomOp", "Relu", "Add", "Result"]
+ verify_model(model, example, expected_ops)
+
+
+def test_inlined_extension_multiple_outputs():
+ from openvino.frontend.pytorch import inlined_extension
+ rng = np.random.default_rng(42)
+
+ @inlined_extension
+ def numpy_split(x):
+ np_array = x.numpy(force=True)
+ midpoint = np_array.shape[0] // 2
+ part1 = np_array[:midpoint]
+ part2 = np_array[midpoint:]
+ return torch.from_numpy(part1), torch.from_numpy(part2)
+
+ class ModelWithMultipleOutputs(torch.nn.Module):
+ def __init__(self):
+ super().__init__()
+ self.relu_module = torch.nn.ReLU()
+
+ def forward(self, x):
+ x = x.to(torch.float32)
+ part1, part2 = numpy_split(x)
+ return self.relu_module(part1), self.relu_module(part2)
+
+ model = ModelWithMultipleOutputs()
+ example = torch.from_numpy(rng.random([100], dtype=np.float32))
+ expected_ops = ["Parameter", "InlinedCustomOp", "Relu", "Result", "Relu", "Result"]
+ verify_model(model, example, expected_ops)
+
+
+def test_inlined_extension_with_torch_model():
+ from openvino.frontend.pytorch import inlined_extension
+ rng = np.random.default_rng(42)
+
+ # Define a simple PyTorch model
+ class SimpleTorchModel(torch.nn.Module):
+ def __init__(self):
+ super().__init__()
+ self.linear = torch.nn.Linear(100, 100)
+
+ def forward(self, x):
+ return self.linear(x)
+
+ # Instantiate the model
+ simple_model = SimpleTorchModel()
+
+ @inlined_extension
+ def model_based_extension(x):
+ return simple_model(x)
+
+ class ModelWithInlinedTorchModel(torch.nn.Module):
+ def __init__(self):
+ super().__init__()
+ self.relu_module = torch.nn.ReLU()
+
+ def forward(self, x):
+ x = x.to(torch.float32)
+ return model_based_extension(x) + self.relu_module(x)
+
+ model = ModelWithInlinedTorchModel()
+ example = torch.from_numpy(rng.random([100], dtype=np.float32))
+ expected_ops = ["Parameter", "InlinedCustomOp", "Relu", "Add", "Result"]
+ verify_model(model, example, expected_ops)
+
+
def test_pytorch_telemetry():
from openvino.frontend import TelemetryExtension
from openvino.frontend.pytorch.ts_decoder import TorchScriptPythonDecoder