OpenVINO™ is an open source toolkit for optimizing and deploying AI inference
C++ aicomputer-visiondeep-learningdeploy-aidiffusion-modelsgenerative-aigood-first-issueinferencellm-inferencenatural-language-processingnlpopenvinooptimize-aiperformance-boostrecommendation-systemspeech-recognitionstable-diffusiontransformersyolo
[PyTorch FE] Do not apply FP32 conversion recursively during tracing when patching ops (#36360)
Andrii Staikov49247df7e27e
diff --git a/src/bindings/python/src/openvino/frontend/pytorch/patch_model.py b/src/bindings/python/src/openvino/frontend/pytorch/patch_model.pyindex df4bc6eaca4..138c2d132ac 100644--- a/src/bindings/python/src/openvino/frontend/pytorch/patch_model.py+++ b/src/bindings/python/src/openvino/frontend/pytorch/patch_model.py@@ -13,56 +13,63 @@ from openvino.frontend.pytorch import ModuleExtensionlog = logging.getLogger(__name__)-def patch_model(model, module_extensions, orig_forward_name):- def module_patcher(module, name):- extension = None- if module in module_extensions:- extension = module_extensions[module]- elif module.__class__ in module_extensions:- extension = module_extensions[module.__class__]- elif name in module_extensions:- extension = module_extensions[name]+def has_been_patched(module, name, orig_forward_name):+ """Return True if `module` was already patched, logging a warning if so."""+ if hasattr(module, orig_forward_name):+ # already patched, skipping. It may happen when patching applied for same module twice+ log.debug("Unexpectedly found already patched module %s while applying "+ "ModuleExtension during PyTorch model conversion. "+ "Result of the conversion maybe broken. Depending on the exact issue "+ "it may lead to broken original model.", name)+ return True+ return False+++def module_patcher(module, name, orig_forward_name, module_extensions):+ extension = None+ if module in module_extensions:+ extension = module_extensions[module]+ elif module.__class__ in module_extensions:+ extension = module_extensions[module.__class__]+ elif name in module_extensions:+ extension = module_extensions[name]++ if extension and extension.condition(module):+ log.debug("Patching module %s", module)+ # The Trampoline class is instantiated for every module replacement, so we can use+ # class members individually for each module.++ class Trampoline(torch.autograd.Function):+ # required to be saved in class+ target_extension = extension++ @staticmethod+ @torch.jit.ignore+ def forward(ctx, *args, **kwargs):+ # Temporarily restore the original forward function of `module` to avoid+ # recursion issues in `evaluate`, then revert it back.+ patched_forward = module.forward+ # set original forward for the module+ module.forward = getattr(module, orig_forward_name)+ # call user code+ results = extension.evaluate(module, *args, **kwargs)+ module.forward = patched_forward # return patched forward back+ return results- if extension and extension.condition(module):- log.debug("Patching module %s", module)- # The Trampoline class is instantiated for every module replacement, so we can use- # class members individually for each module.-- class Trampoline(torch.autograd.Function):- # required to be saved in class- target_extension = extension-- @staticmethod- @torch.jit.ignore- def forward(ctx, *args, **kwargs):- # Temporarily restore the original forward function of `module` to avoid- # recursion issues in `evaluate`, then revert it back.- patched_forward = module.forward- # set original forward for the module- module.forward = getattr(module, orig_forward_name)- # call user code- results = extension.evaluate(module, *args, **kwargs)- module.forward = patched_forward # return patched forward back- return results+ def new_forward(*args, **kwargs):+ return extension.convert(module, Trampoline.apply, *args, **kwargs)- def new_forward(*args, **kwargs):- return extension.convert(module, Trampoline.apply, *args, **kwargs)+ # make signature of new_forward same as of forward+ new_forward = functools.wraps(module.forward)(new_forward)+ setattr(module, orig_forward_name, module.forward)+ module.forward = new_forward- # make signature of new_forward same as of forward- new_forward = functools.wraps(module.forward)(new_forward)- setattr(module, orig_forward_name, module.forward)- module.forward = new_forward+def patch_model(model, module_extensions, orig_forward_name):for name, module in model.named_modules():- if hasattr(module, orig_forward_name):- # already patched, skipping. It may happen when patching applied for same module twice- log.debug("Unexpectedly found already patched module %s while applying "- "ModuleExtension during PyTorch model conversion. "- "Result of the conversion maybe broken. Depending on the exact issue "- "it may lead to broken original model.", name)+ if has_been_patched(module, name, orig_forward_name):continue-- module_patcher(module, name)+ module_patcher(module, name, orig_forward_name, module_extensions)def unpatch_model(model, orig_forward_name):@@ -471,10 +478,7 @@ def patch_model_for_export(model, module_extensions, orig_forward_name):module.forward = new_forwardfor name, module in model.named_modules():- if hasattr(module, orig_forward_name):- log.debug("Unexpectedly found already patched module %s while applying "- "ModuleExtension for torch.export during PyTorch model conversion. "- "Result of the conversion maybe broken.", name)+ if has_been_patched(module, name, orig_forward_name):continuemodule_patcher(module, name)@@ -539,10 +543,17 @@ def __make_16bit_traceable(model: torch.nn.Module,_patch_torch_functions()extensions, supported = _get_16bit_extensions(patch_condition)- patch_model(model, extensions, orig_forward_name)- for _, module in model.named_modules():- if (module.__class__ not in extensions- and (any(p.dtype in supported for p in module.parameters(False))- or any(b.dtype in supported for b in module.buffers(False)))):- log.debug("Casting module %s to float32", module)- module.float()+ for name, module in model.named_modules():+ if has_been_patched(module, name, orig_forward_name):+ continue+ if module.__class__ in extensions:+ module_patcher(module, name, orig_forward_name, extensions)+ else:+ for param in module.parameters(recurse=False):+ if param.dtype in supported:+ log.debug("Casting parameter of module %s to float32", name)+ param.data = param.data.float()+ for buf in module.buffers(recurse=False):+ if buf.dtype in supported:+ log.debug("Casting buffer of module %s to float32", name)+ buf.data = buf.data.float()diff --git a/tests/layer_tests/py_frontend_tests/test_torch_frontend.py b/tests/layer_tests/py_frontend_tests/test_torch_frontend.pyindex cda59c2a7bd..4fa01b85ac1 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,41 @@ def test_module_extension_dynamo_custom_callbacks():PartialShape([100])[email protected]("dtype", [torch.float16, torch.bfloat16])+def test_make_16bit_traceable_preserves_extension_dtypes(dtype):+ """__make_16bit_traceable keeps ModuleExtension (Linear/Embedding) weights+ in 16-bit while up-casting params/buffers of non-extension modules to fp32.+ """+ from openvino.frontend.pytorch import patch_model++ class Block(torch.nn.Module):+ def __init__(self):+ super().__init__()+ self.scale_shift_table = torch.nn.Parameter(torch.randn(2, 4))+ self.linear = torch.nn.Linear(4, 4)+ self.embedding = torch.nn.Embedding(8, 4)+ self.norm = torch.nn.LayerNorm(4)++ model = Block().to(dtype)++ assert all(p.dtype == dtype for p in model.parameters())++ orig_forward_name = "_openvino_module_extension_patch_orig_forward"+ try:+ patch_model.__make_16bit_traceable(model)++ # Linear/Embedding weights are consumed by ModuleExtension and must+ # stay in 16-bit+ assert model.linear.weight.dtype == dtype+ assert model.embedding.weight.dtype == dtype++ # Param and non-extension module weights are up-cast to fp32.+ assert model.scale_shift_table.dtype == torch.float32+ assert model.norm.weight.dtype == torch.float32+ finally:+ patch_model.unpatch_model(model, orig_forward_name)++def verify_model(model, example_input, expected_ops):import numpy as npimport openvino as ov