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] Patch torch functions (torch.bmm) (#34046)
Maxim Vafinb7f9dbfa7944
diff --git a/src/bindings/python/src/openvino/frontend/pytorch/patch_model.py b/src/bindings/python/src/openvino/frontend/pytorch/patch_model.pyindex 0f39b790289..e9f26dcd646 100644--- a/src/bindings/python/src/openvino/frontend/pytorch/patch_model.py+++ b/src/bindings/python/src/openvino/frontend/pytorch/patch_model.py@@ -6,6 +6,7 @@import functoolsimport logging+import threadingimport torchfrom openvino.frontend.pytorch import ModuleExtension@@ -65,6 +66,9 @@ def patch_model(model, module_extensions, orig_forward_name):def unpatch_model(model, orig_forward_name):+ # Restore patched torch functions (bmm, baddbmm, etc.)+ _unpatch_torch_functions()+for _, module in model.named_modules():if hasattr(module, orig_forward_name):try:@@ -76,31 +80,123 @@ def unpatch_model(model, orig_forward_name):"Original exception details:\n%s", error)+def _create_function_wrapper(extension):+ """Create a wrapper for a torch function using the same Trampoline pattern as modules."""++ class Trampoline(torch.autograd.Function):+ target_extension = extension++ @staticmethod+ @torch.jit.ignore+ def forward(ctx, *args, **kwargs):+ return extension.evaluate(None, *args, **kwargs)++ def wrapper(*args, **kwargs):+ return extension.convert(None, Trampoline.apply, *args, **kwargs)++ return wrapper+++def _fp32_tensor(*shape, device=None):+ """Create a placeholder FP32 tensor with the given shape and device."""+ return torch.full(shape, 0.5, dtype=torch.float32, device=device)+++# Extension for torch.bmm: (b, n, m) @ (b, m, p) -> (b, n, p)+_bmm_extension = ModuleExtension(+ None, "ov_ext::bmm",+ convert=lambda module, target_op, *args, **kwargs: target_op(*args),+ evaluate=lambda module, *args, **kwargs: _fp32_tensor(+ args[0].shape[0], args[0].shape[1], args[1].shape[2], device=args[0].device)+)+++# Thread-safe, reference-counted storage for patched torch functions.+# Each entry: key -> (orig_fn, ref_count)+_patched_torch_functions = {}+_patch_lock = threading.Lock()+++def _patch_torch_functions():+ """Patch torch functions that don't work well with 16-bit types (e.g., bmm for MoE models).++ These patches skip actual computation and create custom ops in the TorchScript graph,+ similar to how ModuleExtension works for modules. This speeds up tracing and avoids+ loading weights from mmap.++ Thread-safe and ref-counted: the wrapper is installed only on the first call and+ restored only when every matching _unpatch_torch_functions() call has been made,+ so concurrent or nested patching is safe.+ """+ functions_to_patch = [+ (torch, "bmm", _bmm_extension),+ ]++ with _patch_lock:+ for module, fn_name, extension in functions_to_patch:+ key = (module, fn_name)+ if key in _patched_torch_functions:+ orig_fn, ref_count = _patched_torch_functions[key]+ _patched_torch_functions[key] = (orig_fn, ref_count + 1)+ log.debug("Already patched torch function: %s.%s (ref_count=%d)",+ module.__name__, fn_name, ref_count + 1)+ else:+ orig_fn = getattr(module, fn_name)+ _patched_torch_functions[key] = (orig_fn, 1)+ setattr(module, fn_name, _create_function_wrapper(extension))+ log.debug("Patched torch function: %s.%s", module.__name__, fn_name)+++def _unpatch_torch_functions():+ """Restore original torch functions.++ Decrements the ref count; the original function is restored only when the+ count reaches zero, so nested/concurrent patch pairs work correctly.+ """+ with _patch_lock:+ to_remove = []+ for (module, fn_name), (orig_fn, ref_count) in _patched_torch_functions.items():+ new_count = ref_count - 1+ if new_count <= 0:+ setattr(module, fn_name, orig_fn)+ to_remove.append((module, fn_name))+ log.debug("Restored torch function: %s.%s", module.__name__, fn_name)+ else:+ _patched_torch_functions[(module, fn_name)] = (orig_fn, new_count)+ log.debug("Decremented ref count for torch function: %s.%s (ref_count=%d)",+ module.__name__, fn_name, new_count)+ for key in to_remove:+ del _patched_torch_functions[key]++def __make_16bit_traceable(model: torch.nn.Module,orig_forward_name: str = "_openvino_module_extension_patch_orig_forward",patch_condition=None):"""Prepare a 16-bit PyTorch model for tracing with OpenVINO.- 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."""supported = {torch.float16, torch.bfloat16, torch.float8_e4m3fn, torch.float8_e5m2}++ # Patch torch functions for operations like bmm used in MoE models+ _patch_torch_functions()+if patch_condition is None:def patch_condition(module):dtype_to_patch = {torch.float32, *supported}weight = getattr(module, "weight", None)return weight is not None and weight.dtype in dtype_to_patch- def fp32_tensor(*shape):- return torch.full(shape, 0.5, dtype=torch.float32)-extensions = {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),- evaluate=lambda module, *args, **kwargs: fp32_tensor(*args[0].shape[:-1], module.out_features),+ 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",@@ -109,7 +205,8 @@ def __make_16bit_traceable(model: torch.nn.Module,module.padding_idx,module.scale_grad_by_freq,module.sparse),- evaluate=lambda module, *args, **kwargs: fp32_tensor(*args[1].shape, module.embedding_dim),+ evaluate=lambda module, *args, **kwargs: _fp32_tensor(+ *args[1].shape, module.embedding_dim, device=args[1].device),condition=patch_condition),}try:@@ -119,7 +216,8 @@ def __make_16bit_traceable(model: torch.nn.Module,convert=lambda module, target_op, *args, **kwargs: target_op(args[0],module.weight,module.bias),- evaluate=lambda module, *args, **kwargs: fp32_tensor(*args[0].shape[:-1], module.nf),+ evaluate=lambda module, *args, **kwargs: _fp32_tensor(+ *args[0].shape[:-1], module.nf, device=args[0].device),condition=patch_condition)except ImportError:passdiff --git a/src/bindings/python/src/pyopenvino/CMakeLists.txt b/src/bindings/python/src/pyopenvino/CMakeLists.txtindex 3aadbe94add..1f8f6276359 100644--- a/src/bindings/python/src/pyopenvino/CMakeLists.txt+++ b/src/bindings/python/src/pyopenvino/CMakeLists.txt@@ -90,12 +90,27 @@ if(OV_GENERATOR_MULTI_CONFIG)COMMAND_EXPAND_LISTS)endif()-# perform copy-add_custom_command(TARGET ${PROJECT_NAME}- POST_BUILD- COMMAND ${CMAKE_COMMAND} -E copy_directory ${OpenVINOPython_SOURCE_DIR}/src/openvino ${CMAKE_LIBRARY_OUTPUT_DIRECTORY}- COMMAND ${CMAKE_COMMAND} -E copy ${OpenVINOPython_SOURCE_DIR}/requirements.txt ${CMAKE_LIBRARY_OUTPUT_DIRECTORY}/../requirements.txt- )+# Collect all Python source files for dependency tracking+file(GLOB_RECURSE OPENVINO_PYTHON_SOURCE_FILES CONFIGURE_DEPENDS ${OpenVINOPython_SOURCE_DIR}/src/openvino/*.py)++# Create a stamp file to track when copy was last performed+set(PYTHON_COPY_STAMP_FILE ${CMAKE_CURRENT_BINARY_DIR}/python_copy.stamp)++# Use add_custom_command with OUTPUT to properly track dependencies+add_custom_command(+ OUTPUT ${PYTHON_COPY_STAMP_FILE}+ COMMAND ${CMAKE_COMMAND} -E copy_directory ${OpenVINOPython_SOURCE_DIR}/src/openvino ${CMAKE_LIBRARY_OUTPUT_DIRECTORY}+ COMMAND ${CMAKE_COMMAND} -E copy ${OpenVINOPython_SOURCE_DIR}/requirements.txt ${CMAKE_LIBRARY_OUTPUT_DIRECTORY}/../requirements.txt+ COMMAND ${CMAKE_COMMAND} -E touch ${PYTHON_COPY_STAMP_FILE}+ DEPENDS ${OPENVINO_PYTHON_SOURCE_FILES} ${OpenVINOPython_SOURCE_DIR}/requirements.txt+ COMMENT "Copying Python source files to build directory"+)++# Create a target that depends on the stamp file+add_custom_target(copy_python_files ALL DEPENDS ${PYTHON_COPY_STAMP_FILE})++# Ensure pyopenvino depends on copy_python_files so the files are copied when building pyopenvino+add_dependencies(${PROJECT_NAME} copy_python_files)ov_python_minimal_api(${PROJECT_NAME})ov_add_clang_format_target(${PROJECT_NAME}_clang FOR_TARGETS ${PROJECT_NAME})diff --git a/src/frontends/pytorch/src/op/linear.cpp b/src/frontends/pytorch/src/op/linear.cppindex 6c621f2b1ff..dc112d628e3 100644--- a/src/frontends/pytorch/src/op/linear.cpp+++ b/src/frontends/pytorch/src/op/linear.cpp@@ -220,6 +220,32 @@ OutputVector translate_linear_bitnet(const NodeContext& context) {return {matmul};};+OutputVector translate_bmm_ext(const NodeContext& context) {+ // ov_ext::bmm - batch matrix multiplication for 16-bit models+ // schema: ov_ext::bmm(Tensor batch1, Tensor batch2) -> Tensor+ num_inputs_check(context, 2, 2);+ auto batch1 = context.get_input(0);+ auto batch2 = context.get_input(1);+ const auto initial_batch1 = batch1;++ // Handle mixed precision - convert to f32 if inputs are fp16/bf16+ const bool convert_back = batch1.get_element_type() != element::f32;+ if (batch2.get_element_type() != element::f32) {+ batch2 = context.mark_node(std::make_shared<v0::Convert>(batch2, element::f32));+ }+ if (convert_back) {+ batch1 = context.mark_node(std::make_shared<v0::Convert>(batch1, element::f32));+ }++ // bmm: (b, n, m) @ (b, m, p) -> (b, n, p)+ auto matmul = context.mark_node(std::make_shared<v0::MatMul>(std::move(batch1), std::move(batch2), false, false));++ if (convert_back) {+ matmul = context.mark_node(std::make_shared<v1::ConvertLike>(std::move(matmul), initial_batch1));+ }+ return {matmul};+}+} // namespace op} // namespace pytorch} // namespace frontenddiff --git a/src/frontends/pytorch/src/op_table.cpp b/src/frontends/pytorch/src/op_table.cppindex 421cc603b6a..c502eac6042 100644--- a/src/frontends/pytorch/src/op_table.cpp+++ b/src/frontends/pytorch/src/op_table.cpp@@ -361,6 +361,7 @@ OP_CONVERTER(translate_unbind_int_fx);OP_CONVERTER(translate_zeros_fx);OP_CONVERTER(translate_zeros_like_fx);// Extensions+OP_CONVERTER(translate_bmm_ext);OP_CONVERTER(translate_conv1d_ext);OP_CONVERTER(translate_embedding_ext);OP_CONVERTER(translate_linear_awq);@@ -784,6 +785,7 @@ const std::unordered_map<std::string, CreatorFunction> get_supported_ops_ts() {{"aten::zeros_like", op::translate_zeros_like},{"ov_ext::awq_gemm", op::translate_linear_awq},{"ov_ext::bit_linear", op::translate_linear_bitnet},+ {"ov_ext::bmm", op::translate_bmm_ext},{"ov_ext::embedding", op::translate_embedding_ext},{"ov_ext::conv1d", op::translate_conv1d_ext},{"ov_ext::linear", op::translate_linear_ext},diff --git a/tests/layer_tests/py_frontend_tests/test_torch_frontend.py b/tests/layer_tests/py_frontend_tests/test_torch_frontend.pyindex 144311977f2..08a7d90a7d6 100644--- a/tests/layer_tests/py_frontend_tests/test_torch_frontend.py+++ b/tests/layer_tests/py_frontend_tests/test_torch_frontend.py@@ -889,28 +889,34 @@ def test_patched_16bit_model_converts():model_fp16 = copy.deepcopy(model_ref).half()patch_model.__make_16bit_traceable(model_fp16)- # verify torch.nn.Linear signature after patching- signature = inspect.signature(model_ref.branch1[0].forward).parameters- assert ["input"] == list(signature)- # the approach with patching only works for node with no grad- with torch.no_grad():- converted_model = convert_model(model_fp16, example_input=example)- assert converted_model- cm_fp16 = compile_model(converted_model, "CPU", default_cfg)- res_fp16 = cm_fp16([x.numpy() for x in example])- np.testing.assert_allclose(res_fp16[0], res_ref[0].numpy(), atol=1e-2)- np.testing.assert_allclose(res_fp16[1], res_ref[1].numpy(), atol=1e-2)+ try:+ # verify torch.nn.Linear signature after patching+ signature = inspect.signature(model_ref.branch1[0].forward).parameters+ assert ["input"] == list(signature)+ # the approach with patching only works for node with no grad+ with torch.no_grad():+ converted_model = convert_model(model_fp16, example_input=example)+ assert converted_model+ cm_fp16 = compile_model(converted_model, "CPU", default_cfg)+ res_fp16 = cm_fp16([x.numpy() for x in example])+ np.testing.assert_allclose(res_fp16[0], res_ref[0].numpy(), atol=1e-2)+ np.testing.assert_allclose(res_fp16[1], res_ref[1].numpy(), atol=1e-2)+ finally:+ patch_model._unpatch_torch_functions()model_bf16 = copy.deepcopy(model_ref).bfloat16()patch_model.__make_16bit_traceable(model_bf16)- # the approach with patching only works for node with no grad- with torch.no_grad():- converted_model = convert_model(model_bf16, example_input=example)- assert converted_model- cm_bf16 = compile_model(converted_model, "CPU", default_cfg)- res_bf16 = cm_bf16([x.numpy() for x in example])- np.testing.assert_allclose(res_bf16[0], res_ref[0].numpy(), atol=1e-2)- np.testing.assert_allclose(res_bf16[1], res_ref[1].numpy(), atol=1e-2)+ try:+ # the approach with patching only works for node with no grad+ with torch.no_grad():+ converted_model = convert_model(model_bf16, example_input=example)+ assert converted_model+ cm_bf16 = compile_model(converted_model, "CPU", default_cfg)+ res_bf16 = cm_bf16([x.numpy() for x in example])+ np.testing.assert_allclose(res_bf16[0], res_ref[0].numpy(), atol=1e-2)+ np.testing.assert_allclose(res_bf16[1], res_ref[1].numpy(), atol=1e-2)+ finally:+ patch_model._unpatch_torch_functions()def test_patched_16bit_model_with_convert():@@ -932,18 +938,21 @@ def test_patched_16bit_model_with_convert():example = (torch.randint(0, 10, [16, 32]),)model = ModelWithLinear()patch_model.__make_16bit_traceable(model)- with torch.no_grad():- converted_model = convert_model(model, example_input=example)- assert converted_model- mm_num = 0- for node in converted_model.get_ordered_ops():- if node.get_type_name() == "MatMul":- mm_num += 1- # verify all matmuls are executed in fp32- assert node.get_input_element_type(0) == Type.f32- assert node.get_input_element_type(1) == Type.f32- assert node.get_output_element_type(0) == Type.f32- assert mm_num == 2+ try:+ with torch.no_grad():+ converted_model = convert_model(model, example_input=example)+ assert converted_model+ mm_num = 0+ for node in converted_model.get_ordered_ops():+ if node.get_type_name() == "MatMul":+ mm_num += 1+ # verify all matmuls are executed in fp32+ assert node.get_input_element_type(0) == Type.f32+ assert node.get_input_element_type(1) == Type.f32+ assert node.get_output_element_type(0) == Type.f32+ assert mm_num == 2+ finally:+ patch_model._unpatch_torch_functions()def test_patched_8bit_model_converts_e4m3fn():@@ -978,14 +987,17 @@ def test_patched_8bit_model_converts_e4m3fn():res_ref = model_ref(*example)model_f8_e4m3 = model_ref.to(torch.float8_e4m3fn)patch_model.__make_16bit_traceable(model_f8_e4m3)- # the approach with patching only works for node with no grad- with torch.no_grad():- converted_model = convert_model(model_f8_e4m3, example_input=example)- assert converted_model- cm_f8_e4m3 = compile_model(converted_model, "CPU", default_cfg)- res_f8_e4m3 = cm_f8_e4m3([x.numpy() for x in example])- np.testing.assert_allclose(res_f8_e4m3[0], res_ref[0].numpy(), atol=1e-2)- np.testing.assert_allclose(res_f8_e4m3[1], res_ref[1].numpy(), atol=1e-2)+ try:+ # the approach with patching only works for node with no grad+ with torch.no_grad():+ converted_model = convert_model(model_f8_e4m3, example_input=example)+ assert converted_model+ cm_f8_e4m3 = compile_model(converted_model, "CPU", default_cfg)+ res_f8_e4m3 = cm_f8_e4m3([x.numpy() for x in example])+ np.testing.assert_allclose(res_f8_e4m3[0], res_ref[0].numpy(), atol=1e-2)+ np.testing.assert_allclose(res_f8_e4m3[1], res_ref[1].numpy(), atol=1e-2)+ finally:+ patch_model._unpatch_torch_functions()@pytest.mark.skipif(@@ -1024,14 +1036,66 @@ def test_patched_8bit_model_converts_e5m2():res_ref = model_ref(*example)model_f8_e5m2 = model_ref.to(torch.float8_e5m2)patch_model.__make_16bit_traceable(model_f8_e5m2)- # the approach with patching only works for node with no grad+ try:+ # the approach with patching only works for node with no grad+ with torch.no_grad():+ converted_model = convert_model(model_f8_e5m2, example_input=example)+ assert converted_model+ cm_f8_e5m2 = compile_model(converted_model, "CPU", default_cfg)+ res_f8_e5m2 = cm_f8_e5m2([x.numpy() for x in example])+ np.testing.assert_allclose(res_f8_e5m2[0], res_ref[0].numpy(), atol=1e-2)+ np.testing.assert_allclose(res_f8_e5m2[1], res_ref[1].numpy(), atol=1e-2)+ finally:+ patch_model._unpatch_torch_functions()+++def test_patched_16bit_model_with_bmm():+ from openvino.frontend.pytorch import patch_model+ from openvino import convert_model, compile_model+ import copy++ rng = torch.Generator().manual_seed(42)++ class MoEStyleModel(torch.nn.Module):+ def __init__(self):+ super().__init__()+ self.expert_weights = torch.nn.Parameter(+ torch.randint(-4, 5, (4, 32, 64), generator=rng).float() * 0.25)+ self.linear = torch.nn.Linear(64, 32, bias=False)+ self.linear.weight.data = torch.randint(-4, 5, (32, 64), generator=rng).float() * 0.25++ def forward(self, x):+ batch, seq, _ = x.shape+ x_expanded = x.reshape(1, batch * seq, -1).expand(4, -1, -1)+ expert_out = torch.bmm(x_expanded, self.expert_weights)+ out = expert_out.mean(dim=0).reshape(batch, seq, -1)+ return self.linear(out)++ example = (torch.randint(-4, 5, (2, 8, 32), generator=rng).float() * 0.25,)+ model_ref = MoEStyleModel()with torch.no_grad():- converted_model = convert_model(model_f8_e5m2, example_input=example)- assert converted_model- cm_f8_e5m2 = compile_model(converted_model, "CPU", default_cfg)- res_f8_e5m2 = cm_f8_e5m2([x.numpy() for x in example])- np.testing.assert_allclose(res_f8_e5m2[0], res_ref[0].numpy(), atol=1e-2)- np.testing.assert_allclose(res_f8_e5m2[1], res_ref[1].numpy(), atol=1e-2)+ res_ref = model_ref(*example)++ try:+ model_bf16 = copy.deepcopy(model_ref).bfloat16()+ patch_model.__make_16bit_traceable(model_bf16)+ with torch.no_grad():+ converted_model = convert_model(model_bf16, example_input=example)+ assert converted_model+ cm_bf16 = compile_model(converted_model, "CPU")+ res_bf16 = cm_bf16([x.numpy() for x in example])+ np.testing.assert_allclose(res_bf16[0], res_ref.numpy(), atol=1e-2)++ model_fp16 = copy.deepcopy(model_ref).half()+ patch_model.__make_16bit_traceable(model_fp16)+ with torch.no_grad():+ converted_model = convert_model(model_fp16, example_input=example)+ assert converted_model+ cm_fp16 = compile_model(converted_model, "CPU")+ res_fp16 = cm_fp16([x.numpy() for x in example])+ np.testing.assert_allclose(res_fp16[0], res_ref.numpy(), atol=1e-2)+ finally:+ patch_model._unpatch_torch_functions()@pytest.mark.skipif(sys.platform.lower().startswith("win"), reason="CVS-174725")