Skip to content

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

[PT FE] Support ModuleExtension for torch.export path (dynamo=True) (#35463)

Maxim Vafinc619600845a5
diff --git a/src/bindings/python/src/openvino/frontend/pytorch/fx_decoder.py b/src/bindings/python/src/openvino/frontend/pytorch/fx_decoder.py
index aa3b974f49d..366e3b52f61 100644
--- a/src/bindings/python/src/openvino/frontend/pytorch/fx_decoder.py
+++ b/src/bindings/python/src/openvino/frontend/pytorch/fx_decoder.py
@@ -173,10 +173,12 @@ class TorchFXPythonDecoder (BaseFXDecoder):
def __init__(self, pt_module, fx_gm=None, nodes=None,
mark_node_callback=None, input_shapes=None,
- input_types=None, dynamic_shapes=False):
+ input_types=None, dynamic_shapes=False,
+ op_type_mapping=None):
super().__init__(mark_node_callback)
self.pt_module = pt_module
self.fx_gm = fx_gm if fx_gm is not None else pt_module
+ self._module_extension_target_ops = op_type_mapping or {}
self.input_types = input_types or []
self.input_types = [OVAny(pt_to_ov_type_map[str(t)])
for t in self.input_types]
@@ -264,14 +266,24 @@ class TorchFXPythonDecoder (BaseFXDecoder):
@classmethod
def from_exported_program(
- cls, exported_program: torch.export.ExportedProgram, dynamic_shapes=True
+ cls, exported_program: torch.export.ExportedProgram, dynamic_shapes=True,
+ op_type_mapping=None,
) -> "TorchFXPythonDecoder":
- """Create a TorchFXPythonDecoder instance from an exported PyTorch program."""
+ """Create a TorchFXPythonDecoder instance from an exported PyTorch program.
+
+ :param op_type_mapping: Optional mapping from registered
+ ``namespace::op_name`` strings (e.g. ``"ov_ext::MySinOp"``) to the
+ user-provided ``target_op`` labels from ``ModuleExtension``
+ (e.g. ``"MySinOp"``). Built by ``patch_model_for_export()`` and
+ used by ``get_op_type()`` to translate the FX graph node name back
+ to the ``target_op`` that the C++ frontend expects for
+ ``ConversionExtension`` lookup.
+ """
from packaging import version
if version.parse(torch.__version__) >= version.parse("2.6"):
if cls._decomp_table is None:
from torch.export.decomp_utils import CustomDecompTable
- from openvino.frontend.pytorch.torchdynamo.decompositions import ops_to_not_decompose
+ from openvino.frontend.pytorch.torchdynamo.export_decompositions import ops_to_not_decompose
cls._decomp_table = CustomDecompTable()
for op in ops_to_not_decompose():
try:
@@ -281,32 +293,57 @@ class TorchFXPythonDecoder (BaseFXDecoder):
exported_program = exported_program.run_decompositions(cls._decomp_table)
elif version.parse(torch.__version__) >= version.parse("2.2"):
from torch._decomp import get_decompositions
- from openvino.frontend.pytorch.torchdynamo.decompositions import get_export_decomposition_list
+ from openvino.frontend.pytorch.torchdynamo.export_decompositions import get_export_decomposition_list
decomp = get_decompositions(get_export_decomposition_list())
exported_program = exported_program.run_decompositions(decomp_table=decomp)
gm = exported_program.module()
logger.debug(gm.code)
- return cls(gm, dynamic_shapes=dynamic_shapes)
+ return cls(gm, dynamic_shapes=dynamic_shapes,
+ op_type_mapping=op_type_mapping)
@classmethod
def from_model(
cls, model: torch.nn.Module, example_inputs,
dynamic_shapes=None,
+ module_extensions=None,
) -> "TorchFXPythonDecoder":
- """Export a model and create a decoder, auto-patching quantized models.
+ """Export a model and create a decoder, applying module extensions and auto-patching.
This is the ``torch.export`` counterpart of TorchScriptPythonDecoder's
- auto-patching of quantized models. The method patches the model before
- ``torch.export.export`` so that custom ``ov_ext`` ops are captured in
- the FX graph, then unpatches afterwards.
+ module extension support. User-provided ``ModuleExtension`` objects and
+ automatic quantized-model patches are applied before
+ ``torch.export.export`` so that custom ops are captured in the FX graph,
+ then unpatched afterwards.
:param model: The ``torch.nn.Module`` to export and decode.
:param example_inputs: Example inputs for ``torch.export.export``.
:param dynamic_shapes: Dynamic shapes specification built by
``_build_dynamic_shapes`` for ``torch.export.export``, or ``None``
for a fully static graph.
+ :param module_extensions: A dict mapping module class/instance/name to
+ ``ModuleExtension`` objects, as returned by
+ ``extract_module_extensions``. ``None`` means no user extensions.
"""
from openvino.frontend.pytorch import quantized
+ from openvino.frontend.pytorch.patch_model import (
+ patch_model_for_export, unpatch_model, _clear_export_cache)
+
+ orig_forward_name = "_openvino_module_extension_patch_orig_forward"
+
+ op_type_mapping = {}
+ ext_patched = False
+ if module_extensions:
+ try:
+ op_type_mapping = patch_model_for_export(
+ model, module_extensions, orig_forward_name)
+ ext_patched = True
+ except Exception:
+ # Clean up any partial patches before re-raising.
+ try:
+ unpatch_model(model, orig_forward_name)
+ except Exception:
+ pass
+ raise
quant_patched = False
if quantized.detect_quantized_model(model) is not None:
@@ -329,9 +366,15 @@ class TorchFXPythonDecoder (BaseFXDecoder):
finally:
if quant_patched:
quantized.unpatch_quantized_for_export(model)
+ if ext_patched:
+ unpatch_model(model, orig_forward_name)
- return cls.from_exported_program(
- exported_program, dynamic_shapes=dynamic_shapes is not None)
+ try:
+ return cls.from_exported_program(
+ exported_program, dynamic_shapes=dynamic_shapes is not None,
+ op_type_mapping=op_type_mapping)
+ finally:
+ _clear_export_cache()
@staticmethod
def _export(model, inputs, dynamic_shapes=None):
@@ -516,7 +559,9 @@ class TorchFXPythonDecoder (BaseFXDecoder):
if is_subgraph:
continue
decoder = TorchFXPythonDecoder(
- node, self.fx_gm, self._nodes, mark_node_callback=self.mark_node_callback)
+ node, self.fx_gm, self._nodes,
+ mark_node_callback=self.mark_node_callback,
+ op_type_mapping=self._module_extension_target_ops)
self.m_decoders.append(decoder)
node_visitor(decoder)
@@ -541,7 +586,8 @@ class TorchFXPythonDecoder (BaseFXDecoder):
decoder = TorchFXPythonDecoder(
subgraph,
subgraph, # Use subgraph as fx_gm for proper constant resolution
- mark_node_callback=self.mark_node_callback
+ mark_node_callback=self.mark_node_callback,
+ op_type_mapping=self._module_extension_target_ops
)
self.m_decoders.append(decoder)
return decoder
@@ -549,8 +595,13 @@ class TorchFXPythonDecoder (BaseFXDecoder):
def get_op_type(self):
if self.pt_module.op == "call_function":
if type(self.pt_module.target).__name__ == "EdgeOpOverload":
- return self.pt_module.target.__name__
- return str(self.pt_module.target)
+ name = self.pt_module.target.__name__
+ else:
+ name = str(self.pt_module.target)
+ if self._module_extension_target_ops:
+ if name in self._module_extension_target_ops:
+ return self._module_extension_target_ops[name]
+ return name
elif self.pt_module.op == "get_attr":
return "get_attr" # FIXME should be aligned with get_attr from TS implementation
else:
diff --git a/src/bindings/python/src/openvino/frontend/pytorch/patch_model.py b/src/bindings/python/src/openvino/frontend/pytorch/patch_model.py
index 9dce2b01310..df4bc6eaca4 100644
--- a/src/bindings/python/src/openvino/frontend/pytorch/patch_model.py
+++ b/src/bindings/python/src/openvino/frontend/pytorch/patch_model.py
@@ -169,27 +169,264 @@ def _unpatch_torch_functions():
del _patched_torch_functions[key]
+# Single FRAGMENT library handle for auto-registered ModuleExtension ops.
+# Created lazily on first use; reused for all subsequent registrations to
+# avoid unbounded Library object accumulation in long-lived processes.
+_module_ext_lib = None
+_module_ext_registered_ops = {} # op_name → tuple(schema_args)
+_module_ext_lock = threading.Lock()
+
+# Thread-local context used by auto-registered Meta/CPU impls to call the
+# extension's ``evaluate`` callback with the original forward arguments.
+# ``new_forward`` pushes a callable onto the stack before calling
+# ``convert`` and pops it afterwards, so that the Meta dispatch inside
+# ``target_op(...)`` can obtain correct output shapes.
+_export_tracing_ctx = threading.local()
+
+# Cache of output (shape, dtype) keyed by (op_name, input_tensor_metadata).
+# Populated during dynamo tracing (phase 1 of torch.export) when the
+# evaluate stack is available. Consumed during aot_export metadata
+# collection (phase 2) when the stack is no longer on the call path.
+# Module-level (not thread-local) because phase 2 may run in a context
+# where thread-local attributes are reset. Cleared after each export
+# by ``_clear_export_cache()``.
+_meta_shape_cache = {}
+
+
+def _clear_export_cache():
+ """Clear per-export shape cache.
+
+ Called after ``torch.export`` completes to prevent stale shape
+ metadata from leaking across independent exports in long-lived
+ processes.
+ """
+ _meta_shape_cache.clear()
+
+
+def _auto_register_module_extension_op(namespace, op_name, schema_args):
+ """Auto-register a ``torch.library`` op for a ``ModuleExtension`` target.
+
+ ``schema_args`` is a list of schema-argument strings understood by
+ ``torch.library`` (e.g. ``["Tensor x0", "int x1", "Tensor? x2"]``).
+ The op returns a single ``Tensor``.
+
+ Uses a single shared ``FRAGMENT`` library handle for the ``ov_ext``
+ namespace to avoid creating a new ``Library`` object per op.
+
+ Thread-safe: guarded by ``_module_ext_lock``.
+ """
+ global _module_ext_lib
+ schema_key = tuple(schema_args)
+
+ with _module_ext_lock:
+ if _module_ext_lib is None:
+ # hasattr() is insufficient: torch.ops.__getattr__ raises
+ # RuntimeError (not AttributeError) for missing namespaces,
+ # so hasattr() may propagate the exception instead of
+ # returning False.
+ try:
+ getattr(torch.ops, namespace)
+ kind = "FRAGMENT"
+ except (AttributeError, RuntimeError):
+ kind = "DEF"
+ _module_ext_lib = torch.library.Library(namespace, kind)
+
+ if op_name in _module_ext_registered_ops:
+ existing = _module_ext_registered_ops[op_name]
+ if existing != schema_key:
+ raise RuntimeError(
+ f"ModuleExtension op '{namespace}::{op_name}' was already "
+ f"registered with schema ({', '.join(existing)}) but is now "
+ f"requested with ({', '.join(schema_key)}). Use distinct "
+ f"target_op names for extensions with different signatures.")
+ return getattr(getattr(torch.ops, namespace), op_name)
+
+ args = ", ".join(schema_args)
+ _module_ext_lib.define(f"{op_name}({args}) -> Tensor")
+
+ @torch.library.impl(_module_ext_lib, op_name, "Meta")
+ def _meta(*xs):
+ # Build a cache key from tensor shapes/dtypes for
+ # cross-phase lookup (phase 1 populates, phase 2 consumes).
+ cache_key = (op_name,) + tuple(
+ (tuple(a.shape), a.dtype) if isinstance(a, torch.Tensor)
+ else (type(a).__name__, a) for a in xs)
+
+ # Try evaluate callback (available during dynamo tracing).
+ stack = getattr(_export_tracing_ctx, "evaluate_stack", None)
+ if stack:
+ try:
+ result = stack[-1]()
+ if isinstance(result, torch.Tensor):
+ out_shape = tuple(result.shape)
+ out_dtype = result.dtype
+ _meta_shape_cache[cache_key] = (out_shape, out_dtype)
+ return torch.empty(out_shape, dtype=out_dtype, device="meta")
+ except Exception:
+ pass
+
+ # Fall back to cached shape from a previous evaluate call
+ # (needed during aot_export metadata collection).
+ if cache_key in _meta_shape_cache:
+ out_shape, out_dtype = _meta_shape_cache[cache_key]
+ return torch.empty(out_shape, dtype=out_dtype, device="meta")
+
+ for arg in xs:
+ if isinstance(arg, torch.Tensor):
+ return torch.empty_like(arg)
+ return torch.empty(1, device="meta")
+
+ @torch.library.impl(_module_ext_lib, op_name, "CPU")
+ def _cpu(*xs):
+ stack = getattr(_export_tracing_ctx, "evaluate_stack", None)
+ if stack:
+ try:
+ result = stack[-1]()
+ if isinstance(result, torch.Tensor):
+ return result
+ except Exception:
+ pass
+ for arg in xs:
+ if isinstance(arg, torch.Tensor):
+ return arg
+ return torch.empty(1)
+
+ _module_ext_registered_ops[op_name] = schema_key
+ return getattr(getattr(torch.ops, namespace), op_name)
+
+
+def _derive_schema_from_args(call_args, target_op_name):
+ """Derive ``torch.library`` schema-argument strings from actual call arguments.
+
+ Returns a list such as ``["Tensor x0", "int x1", "Tensor? x2"]``.
+ Raises ``RuntimeError`` for unsupported argument types.
+
+ ``None`` is not accepted because it is ambiguous (could be
+ ``Tensor?``, ``int?``, etc.) and the correct schema type cannot be
+ inferred. Use an explicit sentinel or avoid passing ``None`` from
+ ``convert()`` for auto-registered ops.
+ """
+ schema_parts = []
+ for i, arg in enumerate(call_args):
+ if isinstance(arg, torch.Tensor):
+ schema_parts.append(f"Tensor x{i}")
+ elif arg is None:
+ raise RuntimeError(
+ f"ModuleExtension '{target_op_name}': convert() passed "
+ f"None at position {i} to target_op. None is ambiguous "
+ f"for schema inference (Tensor?, int?, …). For ops with "
+ f"optional arguments, pre-register the op with an "
+ f"explicit schema in ov_custom_ops.py instead of relying "
+ f"on lazy auto-registration.")
+ elif isinstance(arg, bool):
+ # bool before int: bool is a subclass of int in Python.
+ schema_parts.append(f"bool x{i}")
+ elif isinstance(arg, int):
+ schema_parts.append(f"int x{i}")
+ elif isinstance(arg, float):
+ schema_parts.append(f"float x{i}")
+ elif isinstance(arg, str):
+ schema_parts.append(f"str x{i}")
+ else:
+ raise RuntimeError(
+ f"ModuleExtension '{target_op_name}': convert() passed "
+ f"unsupported argument type {type(arg).__name__} at position "
+ f"{i} to target_op. Supported types: Tensor, bool, "
+ f"int, float, str.")
+ return schema_parts
+
+
def patch_model_for_export(model, module_extensions, orig_forward_name):
- """Patch model modules for ``torch.export`` by replacing forwards with ``torch.ops.ov_ext.*`` calls.
+ """Patch model modules for ``torch.export`` by replacing forwards with ``torch.library`` op calls.
Unlike ``patch_model`` (which uses ``torch.autograd.Function`` / ``torch.jit.ignore``
for TorchScript tracing), this function creates forwards that call registered
``torch.library`` custom ops so that ``torch.export`` captures them as
``call_function`` nodes in the FX graph.
+
+ Returns:
+ dict: Mapping from the registered ``namespace::op_name`` to the
+ user-provided ``target_op`` string. The FX decoder uses this in
+ ``get_op_type()`` so that the C++ frontend sees the user's original
+ ``target_op`` name.
"""
import openvino.frontend.pytorch.ov_custom_ops # noqa: F401 – triggers registration
+ op_type_mapping = {} # registered_name → user target_op
+
def _resolve_target_op(extension):
- """Map an ``ov_ext::*`` target-op name to the corresponding ``torch.ops.ov_ext.*`` callable."""
- # extension.target_op is e.g. "ov_ext::linear"
- parts = extension.target_op.split("::")
- if len(parts) == 2 and parts[0] == "ov_ext":
- op_fn = getattr(torch.ops.ov_ext, parts[1], None)
- if op_fn is not None:
- return op_fn
- raise RuntimeError(
- f"Cannot resolve torch.library op for target_op='{extension.target_op}'. "
- "Make sure it is registered in openvino.frontend.pytorch.ov_custom_ops.")
+ """Resolve ``target_op`` to a ``torch.ops`` callable.
+
+ If the op is already registered (from ``ov_custom_ops.py`` or a
+ previous call), returns it directly. Otherwise returns a
+ lazy-registering wrapper that auto-registers the op on its first
+ call during ``torch.export`` tracing, deriving the schema from
+ the actual arguments that ``convert()`` passes.
+ """
+ target_op = extension.target_op
+ parts = target_op.split("::")
+ if len(parts) == 2:
+ namespace, op_name = parts
+ elif len(parts) == 1:
+ namespace, op_name = "ov_ext", parts[0]
+ else:
+ raise RuntimeError(
+ f"Invalid target_op format: '{target_op}'. "
+ "Expected 'op_name' or 'namespace::op_name'.")
+
+ # Warn if target_op collides with an existing PyTorch op.
+ # Note: torch.ops namespace __getattr__ raises RuntimeError (not
+ # AttributeError) for missing ops, so getattr(ns, name, default)
+ # does not work — explicit try/except is required.
+ if namespace != "ov_ext":
+ try:
+ getattr(getattr(torch.ops, namespace), op_name)
+ log.warning(
+ "ModuleExtension target_op '%s' matches an existing PyTorch "
+ "op. A passthrough op will be registered under the ov_ext "
+ "namespace instead (the original op will NOT be called, "
+ "consistent with TorchScript ModuleExtension behavior).",
+ target_op)
+ except (AttributeError, RuntimeError):
+ pass
+
+ # Always register under ov_ext — target_op is just a label.
+ # Sanitize dots in op_name (torch.library rejects them).
+ safe_op_name = op_name.replace(".", "_")
+ # Use the FX-style dotted name as the mapping key so that
+ # get_op_type() can do a direct dict lookup without parsing.
+ fx_name = f"ov_ext.{safe_op_name}.default"
+
+ # Detect mapping collisions: same fx_name but different target_op.
+ if (fx_name in op_type_mapping
+ and op_type_mapping[fx_name] != target_op):
+ raise RuntimeError(
+ f"ModuleExtension target_op collision: '{target_op}' and "
+ f"'{op_type_mapping[fx_name]}' both map to "
+ f"FX name '{fx_name}' (after dot "
+ "sanitization). Use distinct target_op names.")
+
+ # Reuse if already registered (pre-registered or previous extension).
+ try:
+ op_fn = getattr(torch.ops.ov_ext, safe_op_name)
+ op_type_mapping[fx_name] = target_op
+ return op_fn
+ except (AttributeError, RuntimeError):
+ pass
+
+ # Return a lazy wrapper: the op schema is derived from the actual
+ # arguments that convert() passes on the first call during tracing.
+ log.debug("Will lazily register torch.library op ov_ext::%s for "
+ "ModuleExtension (target_op='%s')", safe_op_name, target_op)
+
+ def _lazy_register_and_call(*call_args):
+ schema_args = _derive_schema_from_args(call_args, target_op)
+ op_fn = _auto_register_module_extension_op(
+ "ov_ext", safe_op_name, schema_args)
+ op_type_mapping[fx_name] = target_op
+ return op_fn(*call_args)
+
+ return _lazy_register_and_call
def module_patcher(module, name):
extension = None
@@ -203,12 +440,34 @@ def patch_model_for_export(model, module_extensions, orig_forward_name):
if extension and extension.condition(module):
log.debug("Patching module %s for torch.export", module)
target_op = _resolve_target_op(extension)
+ orig_fwd = module.forward # capture before overwrite
def new_forward(*args, **kwargs):
- return extension.convert(module, target_op, *args, **kwargs)
-
- new_forward = functools.wraps(module.forward)(new_forward)
- setattr(module, orig_forward_name, module.forward)
+ # Push an evaluate thunk so the auto-registered Meta/CPU
+ # impls can produce the correct output shape instead of
+ # blindly returning ``empty_like(first_tensor)``.
+ def _evaluate():
+ # Temporarily restore the original forward to avoid
+ # recursion (evaluate's default calls module()).
+ patched = module.forward
+ module.forward = orig_fwd
+ try:
+ return extension.evaluate(module, *args, **kwargs)
+ finally:
+ module.forward = patched
+
+ stack = getattr(_export_tracing_ctx, "evaluate_stack", None)
+ if stack is None:
+ stack = []
+ _export_tracing_ctx.evaluate_stack = stack
+ stack.append(_evaluate)
+ try:
+ return extension.convert(module, target_op, *args, **kwargs)
+ finally:
+ stack.pop()
+
+ new_forward = functools.wraps(orig_fwd)(new_forward)
+ setattr(module, orig_forward_name, orig_fwd)
module.forward = new_forward
for name, module in model.named_modules():
@@ -219,6 +478,8 @@ def patch_model_for_export(model, module_extensions, orig_forward_name):
continue
module_patcher(module, name)
+ return op_type_mapping
+
def _get_16bit_extensions(patch_condition=None):
"""Return a dict of ModuleExtension entries for known 16-bit module types."""
diff --git a/src/bindings/python/src/openvino/frontend/pytorch/torchdynamo/export_decompositions.py b/src/bindings/python/src/openvino/frontend/pytorch/torchdynamo/export_decompositions.py
new file mode 100644
index 00000000000..b0623edf88d
--- /dev/null
+++ b/src/bindings/python/src/openvino/frontend/pytorch/torchdynamo/export_decompositions.py
@@ -0,0 +1,271 @@
+# -*- coding: utf-8 -*-
+# Copyright (C) 2018-2026 Intel Corporation
+# SPDX-License-Identifier: Apache-2.0
+
+"""Decomposition lists for the ``torch.export`` path.
+
+Unlike ``decompositions.py``, this module does **not** register any global
+decompositions (via ``@register_decomposition``). It is safe to import from
+code paths that must not mutate PyTorch's global decomposition tables — in
+particular from ``TorchFXPythonDecoder.from_exported_program``, which may run
+before ``torch._inductor`` is imported.
+"""
+
+import torch
+
+
+def get_export_decomposition_list() -> list:
+ # list of decompositions from torch._decomp.core_aten_decompositions
+ # removed _backward ops and ops supported without decomposition
+ decomp = [
+ torch.ops.aten.addcdiv,
+ torch.ops.aten.addcdiv_,
+ torch.ops.aten.addcmul,
+ torch.ops.aten.addcmul_,
+ torch.ops.aten.addr,
+ torch.ops.aten.affine_grid_generator,
+ torch.ops.aten.all,
+ torch.ops.aten.aminmax,
+ torch.ops.aten.arange.default,
+ torch.ops.aten.arange.start,
+ torch.ops.aten.baddbmm,
+ torch.ops.aten.binary_cross_entropy,
+ torch.ops.aten.binary_cross_entropy_with_logits,
+ torch.ops.aten.block_diag,
+ torch.ops.aten.celu,
+ torch.ops.aten.celu_,
+ torch.ops.aten.clamp_max,
+ torch.ops.aten.clamp_min,
+ torch.ops.aten.count_nonzero,
+ torch.ops.aten.linalg_cross,
+ torch.ops.aten.cudnn_batch_norm,
+ torch.ops.aten.deg2rad,
+ torch.ops.aten.deg2rad_,
+ torch.ops.aten.detach,
+ torch.ops.aten.diag_embed,
+ torch.ops.aten.dot,
+ torch.ops.aten.vdot,
+ torch.ops.aten.elu,
+ torch.ops.aten.elu_,
+ torch.ops.aten._embedding_bag,
+ torch.ops.aten.empty_like,
+ torch.ops.aten._euclidean_dist.default,
+ torch.ops.aten.expand_as,
+ torch.ops.aten.eye,
+ torch.ops.aten.fill,
+ torch.ops.aten.fill_,
+ torch.ops.aten.floor_divide,
+ torch.ops.aten.frac,
+ torch.ops.aten.frac_,
+ torch.ops.aten._fused_moving_avg_obs_fq_helper,
+ torch.ops.aten.gelu_,
+ torch.ops.aten.glu,
+ torch.ops.aten.hardshrink,
+ torch.ops.aten.hardsigmoid,
+ torch.ops.aten.hardsigmoid_,
+ torch.ops.aten.hardswish,
+ torch.ops.aten.hardswish_,
+ torch.ops.aten.hardtanh_,
+ torch.ops.aten.heaviside,
+ torch.ops.aten.heaviside_,
+ torch.ops.aten.huber_loss,
+ torch.ops.aten.im2col,
+ torch.ops.aten.index_add,
+ torch.ops.aten.index_add_,
+ torch.ops.aten.index_copy,
+ torch.ops.aten.index_copy_,
+ torch.ops.aten.index_fill,
+ torch.ops.aten.index_fill_,
+ torch.ops.aten.isin,
+ torch.ops.aten.isneginf,
+ torch.ops.aten.isposinf,
+ torch.ops.aten.l1_loss,
+ torch.ops.aten.leaky_relu_,
+ torch.ops.aten.lerp,
+ torch.ops.aten.lerp_,
+ torch.ops.aten.linspace,
+ torch.ops.aten.logaddexp,
+ torch.ops.aten.logaddexp2,
+ torch.ops.aten.logit,
+ torch.ops.aten.logit_,
+ torch.ops.aten.log_sigmoid_forward,
+ torch.ops.aten.logspace,
+ torch.ops.aten.logsumexp.default,
+ torch.ops.aten.masked_fill,
+ torch.ops.aten.masked_fill_,
+ torch.ops.aten.mish,
+ torch.ops.aten.mish_,
+ torch.ops.aten.mse_loss,
+ torch.ops.aten.multi_margin_loss,
+ torch.ops.aten.multilabel_margin_loss_forward,
+ torch.ops.aten.mv,
+ torch.ops.aten.mvlgamma,
+ torch.ops.aten.mvlgamma_,
+ torch.ops.aten.nansum,
+ torch.ops.aten.nan_to_num,
+ torch.ops.aten.nan_to_num_,
+ torch.ops.aten.narrow,
+ torch.ops.aten.new_empty,
+ torch.ops.aten.new_full,
+ torch.ops.aten.new_ones,
+ torch.ops.aten.new_zeros,
+ torch.ops.aten.nll_loss_forward,
+ torch.ops.aten.norm,
+ torch.ops.aten.ones,
+ torch.ops.aten.ones_like,
+ torch.ops.aten._prelu_kernel,
+ torch.ops.aten._reshape_alias,
+ torch.ops.aten.rad2deg,
+ torch.ops.aten.rad2deg_,
+ torch.ops.aten.reflection_pad1d,
+ torch.ops.aten.reflection_pad2d,
+ torch.ops.aten.reflection_pad3d,
+ torch.ops.aten.replication_pad1d,
+ torch.ops.aten.replication_pad2d,
+ torch.ops.aten.replication_pad3d,
+ torch.ops.aten.renorm,
+ torch.ops.aten.renorm_,
+ torch.ops.aten.resize_as,
+ torch.ops.aten.roll,
+ torch.ops.aten.rot90,
+ torch.ops.aten.rrelu_with_noise,
+ torch.ops.aten.rrelu_with_noise_,
+ torch.ops.aten.rsub,
+ torch.ops.aten.select_scatter,
+ torch.ops.aten.sgn,
+ torch.ops.aten.sgn_,
+ torch.ops.aten.silu,
+ torch.ops.aten.silu_,
+ torch.ops.aten.sinc,
+ torch.ops.aten.sinc_,
+ torch.ops.aten.smooth_l1_loss,
+ torch.ops.aten.soft_margin_loss,
+ torch.ops.aten.softplus,
+ torch.ops.aten.softshrink,
+ torch.ops.aten.special_entr,
+ torch.ops.aten.special_log_ndtr,
+ torch.ops.aten.special_xlog1py,
+ torch.ops.aten.split.Tensor,
+ torch.ops.aten.split_with_sizes_copy,
+ torch.ops.aten.squeeze.default,
+ torch.ops.aten.squeeze.dim,
+ torch.ops.aten.std,
+ torch.ops.aten.std_mean,
+ torch.ops.aten.stack,
+ torch.ops.aten.sum.default,
+ torch.ops.aten.sum.out,
+ torch.ops.aten.t,
+ torch.ops.aten.take,
+ torch.ops.aten.threshold,
+ torch.ops.aten.threshold_,
+ torch.ops.aten.trace,
+ torch.ops.aten.transpose.int,
+ torch.ops.aten.tril,
+ torch.ops.aten.tril_,
+ torch.ops.aten.triu,
+ torch.ops.aten.triu_,
+ torch.ops.aten.unbind,
+ torch.ops.aten.unfold_copy,
+ torch.ops.aten._unsafe_index,
+ torch.ops.aten.unsafe_split.Tensor,
+ torch.ops.aten.unsafe_split_with_sizes,
+ torch.ops.aten._unsafe_view,
+ torch.ops.aten.view_as_complex,
+ torch.ops.aten.xlogy,
+ torch.ops.aten.xlogy_,
+ torch.ops.aten.zero,
+ torch.ops.aten.zero_,
+ torch.ops.aten.zeros,
+ torch.ops.aten.zeros_like,
+ torch.ops.aten._weight_norm_interface,
+ ]
+ try:
+ from packaging import version
+ if version.parse(torch.__version__) >= version.parse("2.3"):
+ decomp += [
+ torch.ops.aten._lazy_clone,
+ torch.ops.aten._test_parallel_materialize,
+ torch.ops.aten._chunk_cat,
+ ]
+ except ImportError:
+ pass
+ return decomp
+
+
+def ops_to_not_decompose() -> list:
+ # list of operations that shouldn't be decomposed because
+ # OpenVINO frontend handles them directly and more efficiently
+ return [
+ # Activation functions - each maps to a single dedicated OV op
+ torch.ops.aten.celu.default,
+ torch.ops.aten.elu_.default,
+ torch.ops.aten.glu.default,
+ torch.ops.aten.hardsigmoid.default,
+ torch.ops.aten.hardswish.default,
+ torch.ops.aten.hardswish_.default,
+ torch.ops.aten.hardtanh_.default,
+ torch.ops.aten.leaky_relu_.default,
+ torch.ops.aten.log_sigmoid_forward.default,
+ torch.ops.aten.mish.default,
+ torch.ops.aten.silu.default,
+ torch.ops.aten.silu_.default,
+ # Normalization
+ torch.ops.aten.linear.default,
+ torch.ops.aten.rms_norm.default,
+ # Math and reduction ops with dedicated translators
+ torch.ops.aten.all.default,
+ torch.ops.aten.argsort.default,
+ torch.ops.aten.argsort.stable,
+ torch.ops.aten.baddbmm.default,
+ torch.ops.aten.dot.default,
+ torch.ops.aten.logaddexp.default,
+ torch.ops.aten.logsumexp.default,
+ torch.ops.aten.outer.default,
+ torch.ops.aten.rad2deg.default,
+ torch.ops.aten.std.correction,
+ # Spatial and structural ops
+ torch.ops.aten.channel_shuffle.default,
+ torch.ops.aten.col2im.default,
+ torch.ops.aten.pixel_shuffle.default,
+ torch.ops.aten.pixel_unshuffle.default,
+ torch.ops.aten.reflection_pad1d.default,
+ torch.ops.aten.reflection_pad2d.default,
+ torch.ops.aten.reflection_pad3d.default,
+ torch.ops.aten.roll.default,
+ # Index and scatter ops
+ torch.ops.aten.index_add.default,
+ torch.ops.aten.index_add_.default,
+ torch.ops.aten.index_copy.default,
+ torch.ops.aten.index_fill.int_Scalar,
+ torch.ops.aten.index_fill_.int_Scalar,
+ torch.ops.aten.masked_fill.Scalar,
+ torch.ops.aten.masked_fill.Tensor,
+ torch.ops.aten.masked_fill_.Scalar,
+ torch.ops.aten.masked_fill_.Tensor,
+ torch.ops.aten.select_scatter.default,
+ # Tensor creation and manipulation
+ torch.ops.aten.hstack.default,
+ torch.ops.aten.linalg_cross.default,
+ torch.ops.aten.linspace.default,
+ torch.ops.aten.one_hot.default,
+ torch.ops.aten.repeat_interleave.self_int,
+ torch.ops.aten.repeat_interleave.self_Tensor,
+ # Note: aten.take_along_dim.default is not listed here because
+ # the translator doesn't handle the 2-input case (dim=None)
+ torch.ops.aten.tril.default,
+ torch.ops.aten.triu.default,
+ torch.ops.aten.vstack.default,
+ # Upsampling / interpolation
+ torch.ops.aten.upsample_nearest1d.default,
+ torch.ops.aten.upsample_nearest1d.vec,
+ torch.ops.aten.upsample_nearest2d.default,
+ torch.ops.aten.upsample_nearest2d.vec,
+ torch.ops.aten.upsample_nearest3d.default,
+ torch.ops.aten.upsample_nearest3d.vec,
+ torch.ops.aten.upsample_linear1d.vec,
+ torch.ops.aten.upsample_bilinear2d.vec,
+ torch.ops.aten.upsample_trilinear3d.vec,
+ torch.ops.aten.upsample_bicubic2d.vec,
+ # Attention
+ torch.ops.aten.scaled_dot_product_attention.default,
+ ]
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 035a71ca8f6..47c0296d09c 100644
--- a/tests/layer_tests/py_frontend_tests/test_torch_frontend.py
+++ b/tests/layer_tests/py_frontend_tests/test_torch_frontend.py
@@ -311,6 +311,15 @@ class CosModel(torch.nn.Module):
return torch.cos(x.to(torch.float32))
+class ModelWithCosModule(torch.nn.Module):
+ def __init__(self):
+ super().__init__()
+ self.cos_module = CosModel()
+
+ def forward(self, x):
+ return self.cos_module(x)
+
+
def test_op_extension():
from openvino.frontend.pytorch.ts_decoder import TorchScriptPythonDecoder
from openvino.frontend.pytorch import OpExtension
@@ -471,6 +480,365 @@ def test_multiple_module_extension():
"Parameter", "Sin", "Tan", "Add", "Result"]
[email protected]("match_key_fn", [
+ pytest.param(lambda m: type(m.cos_module), id="by_class"),
+ pytest.param(lambda m: m.cos_module, id="by_instance"),
+ pytest.param(lambda m: "cos_module", id="by_name"),
+])
+def test_module_extension_dynamo_match(match_key_fn):
+ """ModuleExtension matches by class, instance, or name with dynamo=True."""
+ from openvino.frontend.pytorch import ModuleExtension, ConversionExtension
+ from openvino import convert_model
+
+ def sin_op(context):
+ return ops.sin(context.get_input(0)).outputs()
+
+ model = ModelWithCosModule()
+ converted_model = convert_model(
+ model, example_input=[torch.randn(100)], dynamo=True,
+ extension=[
+ ModuleExtension(match_key_fn(model), "MySinOp"),
+ ConversionExtension("MySinOp", sin_op)])
+ assert converted_model
+ assert [n.get_type_name() for n in converted_model.get_ordered_ops()] == [
+ "Parameter", "Sin", "Result"]
+ assert converted_model.get_results()[0].get_output_partial_shape(0) == \
+ PartialShape([100])
+
+
+def test_module_extension_dynamo_condition():
+ """ModuleExtension condition callback controls whether extension is applied."""
+ from openvino.frontend.pytorch import ModuleExtension, ConversionExtension
+ from openvino import convert_model
+
+ def sin_op(context):
+ return ops.sin(context.get_input(0)).outputs()
+
+ me = ModuleExtension(CosModel, "MySinOp",
+ condition=lambda m: getattr(m, "flag", False))
+
+ # condition False → extension skipped, original Cos runs
+ model = ModelWithCosModule()
+ model.cos_module.flag = False
+ converted_model = convert_model(
+ model, example_input=[torch.randn(100)], dynamo=True,
+ extension=[me, ConversionExtension("MySinOp", sin_op)])
+ assert [n.get_type_name() for n in converted_model.get_ordered_ops()] == [
+ "Parameter", "Cos", "Result"]
+ assert converted_model.get_results()[0].get_output_partial_shape(0) == \
+ PartialShape([100])
+
+ # condition True → extension applies, Sin replaces Cos
+ model = ModelWithCosModule()
+ model.cos_module.flag = True
+ converted_model = convert_model(
+ model, example_input=[torch.randn(100)], dynamo=True,
+ extension=[me, ConversionExtension("MySinOp", sin_op)])
+ assert [n.get_type_name() for n in converted_model.get_ordered_ops()] == [
+ "Parameter", "Sin", "Result"]
+ assert converted_model.get_results()[0].get_output_partial_shape(0) == \
+ PartialShape([100])
+
+
+def test_module_extension_dynamo_unpatch():
+ """Model is unpatched after conversion (no leftover attributes)."""
+ from openvino.frontend.pytorch import ModuleExtension, ConversionExtension
+ from openvino import convert_model
+
+ def sin_op(context):
+ return ops.sin(context.get_input(0)).outputs()
+
+ model = ModelWithCosModule()
+ convert_model(
+ model, example_input=[torch.randn(100)], dynamo=True,
+ extension=[
+ ModuleExtension(CosModel, "MySinOp"),
+ ConversionExtension("MySinOp", sin_op)])
+
+ for _, m in model.named_modules():
+ assert not hasattr(m, "_openvino_module_extension_patch_orig_forward")
+
+ # Verify model still produces correct output after unpatching
+ x = torch.randn(100)
+ result = model(x)
+ expected = torch.cos(x.to(torch.float32))
+ assert torch.allclose(result, expected)
+
+
+def test_module_extension_dynamo_fx_op_reuse():
+ """FX-style op name as target_op reuses built-in FX translator."""
+ from openvino.frontend.pytorch import ModuleExtension
+ from openvino import convert_model
+
+ model = ModelWithCosModule()
+ converted_model = convert_model(
+ model, example_input=[torch.randn(100)], dynamo=True,
+ extension=[ModuleExtension(CosModel, "aten.sin.default")])
+ assert converted_model
+ assert [n.get_type_name() for n in converted_model.get_ordered_ops()] == [
+ "Parameter", "Sin", "Result"]
+ assert converted_model.get_results()[0].get_output_partial_shape(0) == \
+ PartialShape([100])
+
+
+def test_module_extension_dynamo_multi_input():
+ """Multi-input module: schema generated with correct arity."""
+ from openvino.frontend.pytorch import ModuleExtension, ConversionExtension
+ from openvino import convert_model
+
+ class AddModule(torch.nn.Module):
+ def forward(self, x, y):
+ return x + y
+
+ class ModelWithAdd(torch.nn.Module):
+ def __init__(self):
+ super().__init__()
+ self.add_mod = AddModule()
+
+ def forward(self, a, b):
+ return self.add_mod(a, b)
+
+ def mul_op(context):
+ return ops.multiply(context.get_input(0),
+ context.get_input(1)).outputs()
+
+ model = ModelWithAdd()
+ converted_model = convert_model(
+ model, example_input=[torch.randn(100), torch.randn(100)],
+ dynamo=True,
+ extension=[
+ ModuleExtension(AddModule, "MyMulOp"),
+ ConversionExtension("MyMulOp", mul_op)])
+ assert converted_model
+ assert [n.get_type_name() for n in converted_model.get_ordered_ops()] == [
+ "Parameter", "Parameter", "Multiply", "Result"]
+ assert converted_model.get_results()[0].get_output_partial_shape(0) == \
+ PartialShape([100])
+
+
+def test_module_extension_dynamo_weight_carrying():
+ """convert() passes extra module params (weight, bias) to target_op.
+
+ The auto-registered schema must match what convert() actually calls
+ (3 args: input, weight, bias), not the forward signature (1 arg: x).
+ """
+ from openvino.frontend.pytorch import ModuleExtension, ConversionExtension
+ from openvino import convert_model
+
+ class WeightedModule(torch.nn.Module):
+ def __init__(self, out_features):
+ super().__init__()
+ self.weight = torch.nn.Parameter(torch.randn(out_features, 10))
+ self.bias = torch.nn.Parameter(torch.randn(out_features))
+
+ def forward(self, x):
+ return x @ self.weight.t() + self.bias
+
+ class ModelWithWeighted(torch.nn.Module):
+ def __init__(self):
+ super().__init__()
+ self.linear = WeightedModule(5)
+
+ def forward(self, x):
+ return self.linear(x)
+
+ def custom_convert(module, target_op, *args, **kwargs):
+ return target_op(args[0], module.weight, module.bias)
+
+ def linear_op(context):
+ mm = ops.matmul(context.get_input(0),
+ context.get_input(1), False, True)
+ return ops.add(mm, context.get_input(2)).outputs()
+
+ model = ModelWithWeighted()
+ ref_weight = model.linear.weight.detach().numpy().copy()
+ ref_bias = model.linear.bias.detach().numpy().copy()
+
+ converted_model = convert_model(
+ model, example_input=[torch.randn(2, 10)], dynamo=True,
+ extension=[
+ ModuleExtension(WeightedModule, "WeightedLinear",
+ convert=custom_convert),
+ ConversionExtension("WeightedLinear", linear_op)])
+ assert converted_model
+ op_types = [n.get_type_name() for n in converted_model.get_ordered_ops()]
+ assert "MatMul" in op_types
+ assert "Add" in op_types
+ # Weight is [5, 10], input is [2, 10], MatMul(input, weight^T) → [2, 5]
+ assert converted_model.get_results()[0].get_output_partial_shape(0) == \
+ PartialShape([2, 5])
+
+ # Verify weight and bias constant values match the original parameters
+ found_weight = False
+ found_bias = False
+ for n in converted_model.get_ordered_ops():
+ if n.get_type_name() != "Constant":
+ continue
+ data = n.get_data()
+ if data.shape == ref_weight.shape and np.allclose(data, ref_weight):
+ found_weight = True
+ if data.size == ref_bias.size and np.allclose(data.flatten(), ref_bias.flatten()):
+ found_bias = True
+ assert found_weight, "Weight constant not found or values don't match"
+ assert found_bias, "Bias constant not found or values don't match"
+
+
+def test_module_extension_dynamo_scalar_args():
+ """convert() passes scalar args (int, bool) alongside tensors."""
+ from openvino.frontend.pytorch import ModuleExtension, ConversionExtension
+ from openvino import convert_model
+
+ class ScalarArgModule(torch.nn.Module):
+ def __init__(self):
+ super().__init__()
+ self.scale = 2
+ self.negate = True
+
+ def forward(self, x):
+ return x * self.scale * (-1 if self.negate else 1)
+
+ class ModelWithScalar(torch.nn.Module):
+ def __init__(self):
+ super().__init__()
+ self.mod = ScalarArgModule()
+
+ def forward(self, x):
+ return self.mod(x)
+
+ def scalar_convert(module, target_op, *args, **kwargs):
+ return target_op(args[0], module.scale, module.negate)
+
+ def scalar_op(context):
+ inp = context.get_input(0)
+ scale = context.get_values_from_const_input(1)
+ negate = context.get_values_from_const_input(2)
+ assert scale == 2, f"Expected scale=2, got {scale}"
+ assert negate == True, f"Expected negate=True, got {negate}"
+ # Apply: x * scale * (-1 if negate else 1)
+ scale_const = ops.constant(np.array([scale], dtype=np.float32))
+ result = ops.multiply(inp, scale_const)
+ if negate:
+ neg_one = ops.constant(np.array([-1], dtype=np.float32))
+ result = ops.multiply(result, neg_one)
+ return result.outputs()
+
+ model = ModelWithScalar()
+ converted_model = convert_model(
+ model, example_input=[torch.randn(100)], dynamo=True,
+ extension=[
+ ModuleExtension(ScalarArgModule, "ScalarOp",
+ convert=scalar_convert),
+ ConversionExtension("ScalarOp", scalar_op)])
+ assert converted_model
+ op_types = [n.get_type_name() for n in converted_model.get_ordered_ops()]
+ assert "Multiply" in op_types, f"Expected Multiply in ops, got {op_types}"
+ assert converted_model.get_results()[0].get_output_partial_shape(0) == \
+ PartialShape([100])
+
+
+def test_module_extension_dynamo_shape_changing():
+ """Shape-changing module: input [2,10] → output [2,5].
+
+ The Meta impl must use evaluate to infer correct output shape;
+ otherwise downstream ops see the wrong shape and export fails.
+ """
+ from openvino.frontend.pytorch import ModuleExtension, ConversionExtension
+ from openvino import convert_model
+
+ class ShapeChangingModule(torch.nn.Module):
+ def __init__(self, in_features, out_features):
+ super().__init__()
+ self.weight = torch.nn.Parameter(
+ torch.randn(out_features, in_features))
+ self.out_features = out_features
+
+ def forward(self, x):
+ return x @ self.weight.t()
+
+ class ModelWithShapeChange(torch.nn.Module):
+ def __init__(self):
+ super().__init__()
+ self.proj = ShapeChangingModule(10, 5)
+
+ def forward(self, x):
+ y = self.proj(x)
+ # Downstream op depends on correct output shape (2, 5).
+ return y + torch.ones(5)
+
+ def proj_convert(module, target_op, *args, **kwargs):
+ return target_op(args[0], module.weight)
+
+ def proj_op(context):
+ return ops.matmul(
+ context.get_input(0), context.get_input(1),
+ False, True).outputs()
+
+ model = ModelWithShapeChange()
+ converted_model = convert_model(
+ model, example_input=[torch.randn(2, 10)], dynamo=True,
+ extension=[
+ ModuleExtension(ShapeChangingModule, "ProjOp",
+ convert=proj_convert),
+ ConversionExtension("ProjOp", proj_op)])
+ assert converted_model
+ op_types = [n.get_type_name() for n in converted_model.get_ordered_ops()]
+ assert "MatMul" in op_types
+ assert "Add" in op_types
+ # Final output shape must be [2, 5] (proj [2,10]→[2,5], then + ones(5))
+ assert converted_model.get_results()[0].get_output_partial_shape(0) == \
+ PartialShape([2, 5])
+
+
+def test_module_extension_dynamo_custom_callbacks():
+ """Custom evaluate, convert, and condition callbacks."""
+ from openvino.frontend.pytorch import ModuleExtension, ConversionExtension
+ from openvino import convert_model
+
+ # Custom convert: negate input before calling target_op.
+ def custom_convert(module, target_op, *args, **kwargs):
+ return target_op(-args[0])
+
+ def custom_evaluate(module, *args, **kwargs):
+ return torch.zeros_like(args[0])
+
+ def custom_condition(module):
+ return getattr(module, "apply_ext", False)
+
+ def sin_op(context):
+ return ops.sin(context.get_input(0)).outputs()
+
+ me = ModuleExtension(CosModel, "CustomNegOp",
+ evaluate=custom_evaluate,
+ convert=custom_convert,
+ condition=custom_condition)
+ ce = ConversionExtension("CustomNegOp", sin_op)
+
+ # condition True → custom_convert negates input, then Sin
+ model = ModelWithCosModule()
+ model.cos_module.apply_ext = True
+ converted_model = convert_model(
+ model, example_input=[torch.randn(100)], dynamo=True,
+ extension=[me, ce])
+ assert converted_model
+ op_types = [n.get_type_name() for n in converted_model.get_ordered_ops()]
+ assert "Sin" in op_types
+ assert "Multiply" in op_types # negation: x * -1
+ assert "Cos" not in op_types
+ assert converted_model.get_results()[0].get_output_partial_shape(0) == \
+ PartialShape([100])
+
+ # condition False → extension skipped, original Cos runs
+ model = ModelWithCosModule()
+ model.cos_module.apply_ext = False
+ converted_model = convert_model(
+ model, example_input=[torch.randn(100)], dynamo=True,
+ extension=[me, ce])
+ assert [n.get_type_name() for n in converted_model.get_ordered_ops()] == [
+ "Parameter", "Cos", "Result"]
+ assert converted_model.get_results()[0].get_output_partial_shape(0) == \
+ PartialShape([100])
+
+
def verify_model(model, example_input, expected_ops):
import numpy as np
import openvino as ov
diff --git a/tools/ovc/openvino/tools/ovc/moc_frontend/pytorch_frontend_utils.py b/tools/ovc/openvino/tools/ovc/moc_frontend/pytorch_frontend_utils.py
index 1522f4284a1..2461650a2ac 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
@@ -156,7 +156,8 @@ def get_pytorch_decoder(model, example_inputs, args):
decoder = TorchFXPythonDecoder.from_model(
model,
example_inputs=inputs,
- dynamic_shapes=dynamic_shapes)
+ dynamic_shapes=dynamic_shapes,
+ module_extensions=extract_module_extensions(args))
else:
decoder = TorchScriptPythonDecoder(
model,