Skip to content

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

[PT FE] Allow ModuleExtension to be conditionally applicable (#29244)

Maxim Vafine21980819bc6
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 a084c1d80da..faeb93dda5d 100644
--- a/src/bindings/python/src/openvino/frontend/pytorch/module_extension.py
+++ b/src/bindings/python/src/openvino/frontend/pytorch/module_extension.py
@@ -5,29 +5,32 @@
# mypy: ignore-errors
class ModuleExtension:
- def __init__(self, module, target_op, evaluate=None, convert=None):
+ def __init__(self, module, target_op, evaluate=None, convert=None, condition=None):
"""
- Creates an extension that replaces entire PyTorch module by a single operation.
+ Creates an extension that replaces the entire PyTorch module with a single operation.
This functionality works with PyTorch models only. A module can be identified by
- module type (e.g. torch.nn.Linear), module instance in the model or module name.
+ its type (e.g. torch.nn.Linear), module instance in the model, or module name.
Args:
- module (str, torch.nn.Module, type(torch.nn.Module)): PyTorch module to replace
+ module (str, torch.nn.Module, type(torch.nn.Module)): PyTorch module to replace.
- target_op (str): a target operation that will be used as a replacer for the module,
- could be a name of the extension operation or existing PyTorch operation
- (with prim:: or aten:: prefix following TorchScript syntax).
+ target_op (str): A target operation that will be used as a replacer for the module.
+ It could be the name of the extension operation or an existing PyTorch
+ operation (with prim:: or aten:: prefix following TorchScript syntax).
- evaluate (callable with args module, *args, **kwargs): a callable that will replace a target
- module in model execution it is responsible for producing valid output for
- the module to allow correct model tracing. By default it calls original module
- forward with the same arguments. The provided code will not be a part of the final
- traced model, it is used only to produce valid results in the tracing.
+ evaluate (callable with args module, *args, **kwargs): A callable that will replace a target
+ module in model execution it is responsible for producing valid output for
+ the module to allow correct model tracing. By default, it calls the original module
+ forward with the same arguments. The provided code will not be a part of the final
+ traced model; it is used only to produce valid results in the tracing.
- convert (callable with args target_op, *args, **kwargs): a callable that will be traced and become
- a part of the final model instead of the target module. It accepts target_op as
- the first parameter, target_op is callable that will appear as a single node in the
- graph, the type of the node is target_op provided as another argument above.
+ convert (callable with args target_op, *args, **kwargs): A callable that will be traced and become
+ a part of the final model instead of the target module. It accepts target_op as
+ the first parameter, target_op is callable that will appear as a single node in the
+ graph, and the type of the node is target_op provided as another argument above.
+
+ condition (callable with args module): A callable that returns whether the extension applies
+ to the given module.
"""
self.module = module
self.target_op = target_op
@@ -37,3 +40,6 @@ class ModuleExtension:
self.convert = convert
if self.convert is None:
self.convert = lambda module, target_op, *args, **kwargs: target_op(*args, **kwargs)
+ self.condition = condition
+ if self.condition is None:
+ self.condition = lambda module: True
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 81a427fc822..a4934b56d12 100644
--- a/src/bindings/python/src/openvino/frontend/pytorch/patch_model.py
+++ b/src/bindings/python/src/openvino/frontend/pytorch/patch_model.py
@@ -22,7 +22,7 @@ def patch_model(model, module_extensions, orig_forward_name):
elif name in module_extensions:
extension = module_extensions[name]
- if extension:
+ if extension and extension.condition(m):
log.debug("Patching module %s", m)
# The Trampoline class is instantiated for every module replacement, so we can use
# class members individually for each module.
@@ -82,6 +82,11 @@ def __make_16bit_traceable(model: torch.nn.Module):
- Replace known list of modules with ModuleExtension.
- Convert other modules with weights to FP32.
"""
+ def patch_condition(module):
+ supported = [torch.float32, torch.float16, torch.bfloat16]
+ return (hasattr(module, "weight")
+ and getattr(module.weight, "dtype", None) in supported)
+
extensions = {
torch.nn.Linear: ModuleExtension(
torch.nn.Linear, "ov_ext::linear",
@@ -89,7 +94,8 @@ def __make_16bit_traceable(model: torch.nn.Module):
module.weight,
module.bias),
evaluate=lambda module, *args, **kwargs: torch.full(
- list(args[0].shape[:-1]) + [module.out_features], 0.5, dtype=torch.float32)),
+ list(args[0].shape[:-1]) + [module.out_features], 0.5, dtype=torch.float32),
+ condition=patch_condition),
torch.nn.Embedding: ModuleExtension(
torch.nn.Embedding, "ov_ext::embedding",
convert=lambda module, target_op, *args, **kwargs: target_op(module.weight,
@@ -98,7 +104,8 @@ def __make_16bit_traceable(model: torch.nn.Module):
module.scale_grad_by_freq,
module.sparse),
evaluate=lambda module, *args, **kwargs: torch.full(
- list(args[1].shape) + [module.embedding_dim], 0.5, dtype=torch.float32)),
+ list(args[1].shape) + [module.embedding_dim], 0.5, dtype=torch.float32),
+ condition=patch_condition),
}
try:
from transformers.pytorch_utils import Conv1D
@@ -108,7 +115,8 @@ def __make_16bit_traceable(model: torch.nn.Module):
module.weight,
module.bias),
evaluate=lambda module, *args, **kwargs: torch.full(
- list(args[0].shape[:-1]) + [module.nf], 0.5, dtype=torch.float32))
+ list(args[0].shape[:-1]) + [module.nf], 0.5, dtype=torch.float32),
+ condition=patch_condition)
except ImportError:
pass
patch_model(model, extensions,
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 2d618ecb682..fa55fffa8f2 100644
--- a/tests/layer_tests/py_frontend_tests/test_torch_frontend.py
+++ b/tests/layer_tests/py_frontend_tests/test_torch_frontend.py
@@ -404,6 +404,26 @@ def test_module_extension():
assert [n.get_type_name() for n in converted_model.get_ordered_ops()] == [
"Parameter", "Sin", "Result"]
+ model = ModelWithModule()
+ model.cos_module.flag = False
+ me = ModuleExtension(CosModel,
+ "aten::sin",
+ condition=lambda m: getattr(m, "flag", False))
+ converted_model = convert_model(model, example_input=(torch.randn(100),),
+ extension=[me])
+ assert converted_model
+ assert [n.get_type_name() for n in converted_model.get_ordered_ops()] == [
+ "Parameter", "Cos", "Result"]
+
+ model = ModelWithModule()
+ model.cos_module.flag = True
+ converted_model = convert_model(model, example_input=(torch.randn(100),),
+ extension=[me])
+ assert converted_model
+ assert [n.get_type_name() for n in converted_model.get_ordered_ops()] == [
+ "Parameter", "Sin", "Result"]
+
+
def test_multiple_module_extension():
from openvino.frontend.pytorch.ts_decoder import TorchScriptPythonDecoder