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
[PT FE] Expose FP32 weight placeholders during 16-bit tracing (#36807)
Maxim Vafin108f0d320c38
diff --git a/src/bindings/python/src/openvino/frontend/pytorch/patch_model.py b/src/bindings/python/src/openvino/frontend/pytorch/patch_model.pyindex 138c2d132ac..451a8a31c6d 100644--- a/src/bindings/python/src/openvino/frontend/pytorch/patch_model.py+++ b/src/bindings/python/src/openvino/frontend/pytorch/patch_model.py@@ -77,6 +77,8 @@ def unpatch_model(model, orig_forward_name):_unpatch_torch_functions()for _, module in model.named_modules():+ # Re-attach real 16-bit weights that were swapped for FP32 placeholders.+ _restore_stashed_weights(module)if hasattr(module, orig_forward_name):try:module.forward = getattr(module, orig_forward_name)@@ -109,6 +111,59 @@ def _fp32_tensor(*shape, device=None):return torch.full(shape, 0.5, dtype=torch.float32, device=device)+# Prefix for attributes where the real (16-bit) weight tensors of a patched+# module are stashed while ``module.weight``/``module.bias`` expose FP32+# placeholders. See ``_stash_weights_as_fp32_placeholders``.+_ORIG_WEIGHT_ATTR_PREFIX = "_openvino_orig_"+++def _orig_weight(module, attr):+ """Return the stashed real weight tensor for ``attr`` if present.++ Falls back to the live ``module.<attr>`` so extensions still work for+ modules that were patched without stashing (e.g. FP32 weights).+ """+ return getattr(module, _ORIG_WEIGHT_ATTR_PREFIX + attr, getattr(module, attr, None))+++def _stash_weights_as_fp32_placeholders(module, supported, weight_attrs=("weight", "bias")):+ """Replace a module's 16-bit weight tensors with FP32 placeholders.++ The real 16-bit tensors are stashed under ``_openvino_orig_<attr>`` so the+ extension ``convert`` callback can still emit them as the graph constant+ (via ``_orig_weight``), while model code that reads ``module.weight.dtype``+ (or ``.device``) during tracing sees a plain FP32 tensor. This prevents the+ tracer from baking a 16-bit ``aten::to`` cast into the graph.++ The placeholder shares a single-element storage (a broadcasted zero) so it+ costs virtually no memory even for large weights, and it keeps the original+ device so that ``x.to(module.weight.device)`` traces correctly.+ """+ for attr in weight_attrs:+ param = getattr(module, attr, None)+ if not isinstance(param, torch.Tensor) or param.dtype not in supported:+ continue+ stash_name = _ORIG_WEIGHT_ATTR_PREFIX + attr+ if hasattr(module, stash_name):+ continue # already stashed+ # Keep the real 16-bit tensor reachable for `convert` (registered so+ # tracing can resolve the prim::GetAttr for it).+ setattr(module, stash_name, param)+ placeholder = torch.zeros((), dtype=torch.float32,+ device=param.device).expand(param.shape)+ setattr(module, attr, torch.nn.Parameter(placeholder, requires_grad=False))+++def _restore_stashed_weights(module):+ """Undo ``_stash_weights_as_fp32_placeholders`` for a single module."""+ stash_names = [n for n in list(module._parameters) + list(module.__dict__)+ if n.startswith(_ORIG_WEIGHT_ATTR_PREFIX)]+ for stash_name in stash_names:+ attr = stash_name[len(_ORIG_WEIGHT_ATTR_PREFIX):]+ setattr(module, attr, getattr(module, stash_name))+ delattr(module, stash_name)++# Extension for torch.bmm: (b, n, m) @ (b, m, p) -> (b, n, p)_bmm_extension = ModuleExtension(None, "ov_ext::bmm",@@ -499,14 +554,14 @@ def _get_16bit_extensions(patch_condition=None):torch.nn.Linear: ModuleExtension(torch.nn.Linear, "ov_ext::linear",convert=lambda module, target_op, *args, **kwargs: target_op(args[0],- module.weight,- module.bias),+ _orig_weight(module, "weight"),+ _orig_weight(module, "bias")),evaluate=lambda module, *args, **kwargs: _fp32_tensor(*args[0].shape[:-1], module.out_features, device=args[0].device),condition=patch_condition),torch.nn.Embedding: ModuleExtension(torch.nn.Embedding, "ov_ext::embedding",- convert=lambda module, target_op, *args, **kwargs: target_op(module.weight,+ convert=lambda module, target_op, *args, **kwargs: target_op(_orig_weight(module, "weight"),args[0],module.padding_idx,module.scale_grad_by_freq,@@ -520,8 +575,8 @@ def _get_16bit_extensions(patch_condition=None):extensions[Conv1D] = ModuleExtension(Conv1D, "ov_ext::conv1d",convert=lambda module, target_op, *args, **kwargs: target_op(args[0],- module.weight,- module.bias),+ _orig_weight(module, "weight"),+ _orig_weight(module, "bias")),evaluate=lambda module, *args, **kwargs: _fp32_tensor(*args[0].shape[:-1], module.nf, device=args[0].device),condition=patch_condition)@@ -538,6 +593,15 @@ def __make_16bit_traceable(model: torch.nn.Module,- Replace known list of modules with ModuleExtension.- Patch torch functions (bmm, baddbmm, etc.) for MoE and similar models.- Convert other modules with weights to FP32.++ For extension-backed modules (Linear/Embedding/Conv1D) the real 16-bit+ weight is stashed aside and ``module.weight``/``module.bias`` are replaced+ with FP32 placeholders. The extension ``convert`` callbacks still emit the+ stashed 16-bit tensor as the graph constant, but any model code that+ inspects ``module.weight.dtype`` (or ``.device``) during tracing now sees+ FP32 instead of the 16-bit type. Without this, such introspection bakes a+ 16-bit ``aten::to`` cast into the traced graph and the model runs in 16-bit+ at inference even though the intent was FP32 activations."""# Patch torch functions for operations like bmm used in MoE models_patch_torch_functions()@@ -547,6 +611,10 @@ def __make_16bit_traceable(model: torch.nn.Module,if has_been_patched(module, name, orig_forward_name):continueif module.__class__ in extensions:+ # Expose FP32 placeholders as .weight/.bias so dtype/device+ # introspection during tracing sees FP32; the real 16-bit tensor+ # is stashed and re-attached by the extension's convert callback.+ _stash_weights_as_fp32_placeholders(module, supported)module_patcher(module, name, orig_forward_name, extensions)else:for param in module.parameters(recurse=False):diff --git a/tests/layer_tests/py_frontend_tests/test_torch_frontend.py b/tests/layer_tests/py_frontend_tests/test_torch_frontend.pyindex c8d04e2f39d..8a26cc49591 100644--- a/tests/layer_tests/py_frontend_tests/test_torch_frontend.py+++ b/tests/layer_tests/py_frontend_tests/test_torch_frontend.py@@ -841,8 +841,9 @@ def test_module_extension_dynamo_custom_callbacks():@pytest.mark.parametrize("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.+ """__make_16bit_traceable exposes FP32 placeholders for ModuleExtension+ (Linear/Embedding) weights while keeping the real 16-bit tensor stashed,+ and up-casts params/buffers of non-extension modules to fp32."""from openvino.frontend.pytorch import patch_model@@ -862,10 +863,17 @@ def test_make_16bit_traceable_preserves_extension_dtypes(dtype):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+ # Linear/Embedding weights are consumed by ModuleExtension. Their+ # public .weight is replaced with an FP32 placeholder so that model+ # code reading weight.dtype during tracing sees FP32, while the real+ # 16-bit tensor is stashed for the convert callback to emit as the+ # graph constant. The placeholder must not allocate a full-size buffer.+ assert model.linear.weight.dtype == torch.float32+ assert model.embedding.weight.dtype == torch.float32+ assert model.linear.weight.shape == (4, 4)+ assert model.linear.weight.untyped_storage().nbytes() <= 4+ assert model.linear._openvino_orig_weight.dtype == dtype+ assert model.embedding._openvino_orig_weight.dtype == dtype# Param and non-extension module weights are up-cast to fp32.assert model.scale_shift_table.dtype == torch.float32@@ -873,6 +881,72 @@ def test_make_16bit_traceable_preserves_extension_dtypes(dtype):finally:patch_model.unpatch_model(model, orig_forward_name)+ # After unpatching, the real 16-bit weights are restored and the stash+ # attributes are removed, so the original model is usable again.+ assert model.linear.weight.dtype == dtype+ assert model.embedding.weight.dtype == dtype+ assert not hasattr(model.linear, "_openvino_orig_weight")+ assert not hasattr(model.embedding, "_openvino_orig_weight")++[email protected]("dtype", [torch.float16, torch.bfloat16])+def test_make_16bit_traceable_no_16bit_activation_cast(dtype):+ """A submodule that casts activations to its Linear weight's dtype must not+ bake a 16-bit ``aten::to`` into the traced graph after __make_16bit_traceable.++ Before the FP32-placeholder fix, tracing read the 16-bit ``weight.dtype``+ and produced a Convert to fp16/bf16, forcing 16-bit activations at+ inference. With the fix, ``weight.dtype`` is FP32 during tracing, so no+ 16-bit Convert appears and the weight constant keeps its 16-bit precision.+ """+ from openvino.frontend.pytorch import patch_model+ from openvino.frontend.pytorch.ts_decoder import TorchScriptPythonDecoder+ from openvino import convert_model, Type++ class DtypeSniffer(torch.nn.Module):+ def __init__(self, lin):+ super().__init__()+ self.lin = lin++ def forward(self, x):+ # Common pattern (e.g. RMSNorm): cast activation to weight dtype.+ x = x.to(self.lin.weight.dtype)+ return self.lin(x)++ class Model(torch.nn.Module):+ def __init__(self):+ super().__init__()+ self.lin = torch.nn.Linear(4, 3, bias=True)+ self.sniff = DtypeSniffer(self.lin)++ def forward(self, x):+ return self.sniff(x)++ model = Model().to(dtype).eval()+ example = torch.randn(2, 4, dtype=torch.float32)++ ov_dtype = Type.f16 if dtype == torch.float16 else Type.bf16+ patch_model.__make_16bit_traceable(model)+ try:+ with torch.no_grad():+ decoder = TorchScriptPythonDecoder(+ model, example_input=(example,),+ module_extensions=patch_model._get_16bit_extensions()[0])+ converted_model = convert_model(decoder, example_input=(example,))+ finally:+ patch_model._unpatch_torch_functions()++ convert_dtypes = [op.get_element_type() for op in converted_model.get_ordered_ops()+ if op.get_type_name() == "Convert"]+ # No activation should be downcast to the 16-bit type.+ assert ov_dtype not in convert_dtypes, \+ f"Unexpected Convert to {ov_dtype}: {convert_dtypes}"+ # The weight constant must still be stored in the original 16-bit precision.+ const_dtypes = [op.get_element_type() for op in converted_model.get_ordered_ops()+ if op.get_type_name() == "Constant"]+ assert ov_dtype in const_dtypes, \+ f"Expected a {ov_dtype} weight constant, got {const_dtypes}"+def verify_model(model, example_input, expected_ops):import numpy as np