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] Reduce memory consumption for MoE model conversion (#38917)
Maxim Vafina5d3d87c6c5f
diff --git a/src/bindings/python/src/openvino/frontend/pytorch/patch_model.py b/src/bindings/python/src/openvino/frontend/pytorch/patch_model.pyindex efe4a32fe5f..9be3bd51fef 100644--- a/src/bindings/python/src/openvino/frontend/pytorch/patch_model.py+++ b/src/bindings/python/src/openvino/frontend/pytorch/patch_model.py@@ -153,12 +153,29 @@ def _stash_weights_as_fp32_placeholders(module, supported, weight_attrs=("weightsetattr(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))+ placeholder = torch.nn.Parameter(placeholder, requires_grad=False)+ # Constant creation emits the original tensor for tracing placeholders (see torch_tensor_to_ov_const).+ placeholder._openvino_orig_tensor = param+ setattr(module, attr, placeholder)+++# Packed expert weights of Transformers MoE modules, e.g. (num_experts, hidden, 2 * intermediate).+_PACKED_EXPERT_WEIGHT_NAMES = ("gate_up_proj", "up_proj", "down_proj")+++def _packed_expert_weight_names(module, supported):+ """Return names of packed 16-bit expert weights, which are too large to copy to FP32."""+ if isinstance(module, torch.jit.ScriptModule):+ return () # parameters cannot be added to a scripted module+ num_experts = getattr(module, "num_experts", None)+ return tuple(name for name, param in module.named_parameters(recurse=False)+ if name in _PACKED_EXPERT_WEIGHT_NAMES and param.dtype in supported+ and param.ndim == 3 and param.shape[0] == num_experts)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__)+ stash_names = [n for n in list(module._parameters.keys()) + list(module.__dict__)if n.startswith(_ORIG_WEIGHT_ATTR_PREFIX)]for stash_name in stash_names:attr = stash_name[len(_ORIG_WEIGHT_ATTR_PREFIX):]@@ -648,8 +665,10 @@ def __make_16bit_traceable(model: torch.nn.Module,_stash_weights_as_fp32_placeholders(module, supported)module_patcher(module, name, orig_forward_name, extensions)else:- for param in module.parameters(recurse=False):- if param.dtype in supported:+ # Memory-free placeholders for packed experts; they are only consumed by the patched torch.bmm.+ _stash_weights_as_fp32_placeholders(module, supported, _packed_expert_weight_names(module, supported))+ for attr, param in module._parameters.items():+ if param is not None and param.dtype in supported and not attr.startswith(_ORIG_WEIGHT_ATTR_PREFIX):log.debug("Casting parameter of module %s to float32", name)param.data = param.data.float()for buf in module.buffers(recurse=False):diff --git a/src/bindings/python/src/openvino/frontend/pytorch/ts_decoder.py b/src/bindings/python/src/openvino/frontend/pytorch/ts_decoder.pyindex 2ea9025c4a4..db5b2559af0 100644--- a/src/bindings/python/src/openvino/frontend/pytorch/ts_decoder.py+++ b/src/bindings/python/src/openvino/frontend/pytorch/ts_decoder.py@@ -132,6 +132,12 @@ class TorchScriptPythonDecoder(TorchDecoderBase):torch.float16, torch.bfloat16]if hasattr(module, "weight") and getattr(module.weight, "dtype", None) in compressed_types:preserved_attributes.append(name)+ for attr in module._parameters.keys():+ if attr.startswith(patch_model._ORIG_WEIGHT_ATTR_PREFIX):+ # Freezing would fold the zero placeholder into a constant and drop the original weight.+ prefix = name + "." if name else ""+ preserved_attributes.extend([prefix + attr[len(patch_model._ORIG_WEIGHT_ATTR_PREFIX):],+ prefix + attr])return preserved_attributesdef _get_scripted_model(self, pt_module, example_inputs=None, skip_freeze=False, trace_kwargs=None):diff --git a/src/bindings/python/src/openvino/frontend/pytorch/utils.py b/src/bindings/python/src/openvino/frontend/pytorch/utils.pyindex ced3e9e4474..0103e2fcc33 100644--- a/src/bindings/python/src/openvino/frontend/pytorch/utils.py+++ b/src/bindings/python/src/openvino/frontend/pytorch/utils.py@@ -60,6 +60,10 @@ F8_DTYPE_MAP = {def torch_tensor_to_ov_const(torch_t: torch.Tensor, shared_memory=True):+ # Memory-free tracing placeholder: emit the original tensor and convert it to FP32 in the graph.+ original = getattr(torch_t, "_openvino_orig_tensor", None)+ if original is not None:+ return ops.convert(torch_tensor_to_ov_const(original, shared_memory=shared_memory), OVType.f32)try:from torch._prims import FakeTensorif isinstance(torch_t, FakeTensor):diff --git a/tests/layer_tests/py_frontend_tests/test_torch_frontend.py b/tests/layer_tests/py_frontend_tests/test_torch_frontend.pyindex a5c691f2a1b..1c465d754a3 100644--- a/tests/layer_tests/py_frontend_tests/test_torch_frontend.py+++ b/tests/layer_tests/py_frontend_tests/test_torch_frontend.py@@ -889,6 +889,178 @@ def test_make_16bit_traceable_preserves_extension_dtypes(dtype):assert not hasattr(model.embedding, "_openvino_orig_weight")+class _PackedExperts(torch.nn.Module):+ """Dense batched-MoE experts: packed weights are only transposed, sized and passed to torch.bmm."""++ def __init__(self, num_experts=4, hidden=8, intermediate=6):+ super().__init__()+ self.num_experts = num_experts+ self.gate_up_proj = torch.nn.Parameter(torch.empty(num_experts, 2 * intermediate, hidden))+ self.down_proj = torch.nn.Parameter(torch.empty(num_experts, hidden, intermediate))+ self.register_buffer("offset", torch.empty(hidden), persistent=False)++ def forward(self, x):+ x = x.repeat(self.gate_up_proj.size(0), 1).view(self.num_experts, -1, x.shape[-1])+ gate, up = torch.bmm(x, self.gate_up_proj.transpose(1, 2)).chunk(2, dim=-1)+ return torch.bmm(torch.nn.functional.silu(gate) * up, self.down_proj.transpose(1, 2)).sum(0) + self.offset+++def _packed_experts(dtype, tmp_path=None):+ model = _PackedExperts()+ with torch.no_grad():+ model.gate_up_proj.copy_(torch.linspace(-0.5, 0.5, model.gate_up_proj.numel()).reshape(model.gate_up_proj.shape))+ model.down_proj.copy_(torch.linspace(-0.5, 0.5, model.down_proj.numel()).reshape(model.down_proj.shape))+ model.gate_up_proj.data = model.gate_up_proj.data.to(dtype)+ model.down_proj.data = model.down_proj.data.to(dtype)+ model.offset = torch.arange(8).to(dtype)+ return model.eval().requires_grad_(False)+++def _packed_experts_reference(model, example):+ reference = _PackedExperts()+ reference.gate_up_proj.data = model.gate_up_proj.data.float()+ reference.down_proj.data = model.down_proj.data.float()+ reference.offset = model.offset.float()+ return reference(example).detach()++[email protected]("dtype", [torch.float16, torch.bfloat16, torch.float8_e4m3fn, torch.float8_e5m2])+def test_make_16bit_traceable_packed_experts_share_storage(tmp_path, dtype):+ from openvino import convert_model, compile_model+ from openvino.frontend.pytorch import patch_model++ torch.save({name: value.detach() for name, value in _packed_experts(dtype).state_dict().items()},+ tmp_path / "weights.pt")+ with torch.device("meta"):+ model = _PackedExperts()+ model.load_state_dict(torch.load(tmp_path / "weights.pt", mmap=True, weights_only=True), assign=True, strict=False)+ model.offset = torch.arange(8).to(dtype)+ model.eval().requires_grad_(False)+ originals = {"gate_up_proj": model.gate_up_proj, "down_proj": model.down_proj}+ example = torch.linspace(-0.5, 0.5, 16).reshape(2, 8)+ expected = _packed_experts_reference(model, example)++ try:+ patch_model.__make_16bit_traceable(model)+ for name, original in originals.items():+ placeholder = getattr(model, name)+ assert placeholder.dtype == torch.float32+ assert placeholder.untyped_storage().nbytes() <= 4+ assert placeholder._openvino_orig_tensor is original+ assert model.offset.dtype == torch.float32+ with torch.no_grad():+ converted = convert_model(model, example_input=(example,))+ for name, original in originals.items():+ constant = next(op for op in converted.get_ops() if op.get_type_name() == "Constant"+ and list(op.get_shape()) == list(original.shape))+ assert constant.get_byte_size() == original.numel() * original.element_size()+ assert constant.get_data().__array_interface__["data"][0] == original.data_ptr()+ result = compile_model(converted, "CPU", default_cfg)(example.numpy())[0]+ np.testing.assert_allclose(result, expected.numpy(), atol=1e-5, rtol=1e-5)+ finally:+ patch_model.unpatch_model(model, "_openvino_module_extension_patch_orig_forward")+ for name, original in originals.items():+ assert getattr(model, name) is original+ assert not hasattr(model, "_openvino_orig_" + name)+ assert "offset" in model._buffers and "offset" not in model.state_dict()++[email protected]("dtype", [torch.float16, torch.bfloat16])+def test_make_16bit_traceable_packed_experts_freeze(dtype):+ from openvino import convert_model, compile_model+ from openvino.frontend.pytorch import patch_model+ from openvino.frontend.pytorch.ts_decoder import TorchScriptPythonDecoder++ class Loop(torch.nn.Module):+ def __init__(self):+ super().__init__()+ self.flag = True++ def forward(self, value):+ for _ in range(2):+ if self.flag:+ return value * 1.0+ return value + 1++ class Model(torch.nn.Module):+ def __init__(self):+ super().__init__()+ self.experts = _packed_experts(dtype)+ self.loop = torch.jit.script(Loop())++ def forward(self, value):+ return self.experts(self.loop(value))++ model = Model().eval()+ original = model.experts.gate_up_proj+ example = torch.linspace(-0.5, 0.5, 16).reshape(2, 8)+ expected = _packed_experts_reference(model.experts, example)+ try:+ patch_model.__make_16bit_traceable(model)+ traced = torch.jit.trace(model, example)+ assert "prim::Uninitialized" in str(traced.inlined_graph)+ decoder = TorchScriptPythonDecoder(model, example_input=(example,))+ converted = convert_model(decoder)+ result = compile_model(converted, "CPU", default_cfg)(example.numpy())[0]+ np.testing.assert_allclose(result, expected.numpy(), atol=1e-2, rtol=1e-2)+ assert model.experts.gate_up_proj.untyped_storage().nbytes() <= 4+ finally:+ patch_model.unpatch_model(model, "_openvino_module_extension_patch_orig_forward")+ assert model.experts.gate_up_proj is original++[email protected]("dtype", [torch.float16, torch.bfloat16])+def test_make_16bit_traceable_scripted_experts_fall_back_to_fp32(dtype):+ from openvino.frontend.pytorch import patch_model++ class Experts(torch.nn.Module):+ def __init__(self):+ super().__init__()+ self.num_experts = 4+ self.gate_up_proj = torch.nn.Parameter(torch.ones(4, 4, 2, dtype=dtype), requires_grad=False)++ def forward(self, value):+ return value + self.gate_up_proj.sum()++ model = torch.nn.Sequential(torch.jit.script(Experts().eval()))+ try:+ patch_model.__make_16bit_traceable(model)+ parameter = model[0].gate_up_proj+ assert parameter.dtype == torch.float32+ assert parameter.untyped_storage().nbytes() == parameter.numel() * 4+ finally:+ patch_model.unpatch_model(model, "_openvino_module_extension_patch_orig_forward")++[email protected]("dtype", [torch.float16, torch.bfloat16])+def test_make_16bit_traceable_casts_other_raw_weights(dtype):+ """Only packed expert weights get placeholders; other raw parameters are cast to FP32."""+ from openvino.frontend.pytorch import patch_model++ class Model(torch.nn.Module):+ def __init__(self):+ super().__init__()+ self.num_experts = 4+ self.gate_up_proj = torch.nn.Parameter(torch.ones(4, 4, dtype=dtype), requires_grad=False) # 2D+ self.other_proj = torch.nn.Parameter(torch.ones(4, 2, 2, dtype=dtype), requires_grad=False) # not packed+ self.down_proj = torch.nn.Parameter(torch.ones(3, 2, 2, dtype=dtype), requires_grad=False) # wrong experts++ model = Model()+ try:+ patch_model.__make_16bit_traceable(model)+ for name in ["gate_up_proj", "other_proj", "down_proj"]:+ parameter = getattr(model, name)+ assert parameter.dtype == torch.float32+ assert parameter.untyped_storage().nbytes() == parameter.numel() * 4+ assert not hasattr(model, "_openvino_orig_" + name)+ finally:+ patch_model.unpatch_model(model, "_openvino_module_extension_patch_orig_forward")++@pytest.mark.parametrize("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