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] Make patched matmuls fp32 (#29299)
Maxim Vafine6ade0a0590a
diff --git a/src/frontends/pytorch/src/op/linear.cpp b/src/frontends/pytorch/src/op/linear.cppindex c6e345f70a9..e757bcf210b 100644--- a/src/frontends/pytorch/src/op/linear.cpp+++ b/src/frontends/pytorch/src/op/linear.cpp@@ -23,10 +23,30 @@ OutputVector translate_linear(const NodeContext& context) {num_inputs_check(context, 2, 3);auto x = context.get_input(0);auto weight = context.get_input(1);- if (weight.get_element_type() == element::f16 || weight.get_element_type() == element::bf16) {+ auto matmul = context.mark_node(std::make_shared<v0::MatMul>(x, weight, false, true));+ if (!context.input_is_none(2)) {+ auto bias = context.get_input(2);+ matmul = context.mark_node(std::make_shared<v1::Add>(matmul, bias));+ }+ return {matmul};+};++OutputVector translate_linear_ext(const NodeContext& context) {+ num_inputs_check(context, 2, 3);+ auto x = context.get_input(0);+ auto initial_x = x;+ auto weight = context.get_input(1);+ bool is_compressed = weight.get_element_type() == element::f16 || weight.get_element_type() == element::bf16;+ bool convert_back = false;+ if (is_compressed) {// In case of patched linear it can have mixed fp16/bf16 and fp32 input type.// In other cases these conversion is not required.- weight = context.mark_node(std::make_shared<v1::ConvertLike>(weight, x));+ weight = context.mark_node(std::make_shared<v0::Convert>(weight, element::f32));+ if (x.get_element_type() != element::f32) {+ // Convert to f32+ x = context.mark_node(std::make_shared<v0::Convert>(x, element::f32));+ convert_back = true;+ }}auto matmul = context.mark_node(std::make_shared<v0::MatMul>(x, weight, false, true));if (!context.input_is_none(2)) {@@ -34,10 +54,13 @@ OutputVector translate_linear(const NodeContext& context) {if (bias.get_element_type() == element::f16 || bias.get_element_type() == element::bf16) {// Same reason as for weight.- bias = context.mark_node(std::make_shared<v1::ConvertLike>(bias, x));+ bias = context.mark_node(std::make_shared<v0::Convert>(bias, element::f32));}matmul = context.mark_node(std::make_shared<v1::Add>(matmul, bias));}+ if (convert_back) {+ matmul = context.mark_node(std::make_shared<v1::ConvertLike>(matmul, initial_x));+ }return {matmul};};diff --git a/src/frontends/pytorch/src/op_table.cpp b/src/frontends/pytorch/src/op_table.cppindex 556ef9cf142..0101429ba7b 100644--- a/src/frontends/pytorch/src/op_table.cpp+++ b/src/frontends/pytorch/src/op_table.cpp@@ -340,6 +340,7 @@ OP_CONVERTER(translate_zeros_like_fx);OP_CONVERTER(translate_conv1d_ext);OP_CONVERTER(translate_embedding_ext);OP_CONVERTER(translate_linear_awq);+OP_CONVERTER(translate_linear_ext);} // namespace op@@ -726,7 +727,7 @@ const std::unordered_map<std::string, CreatorFunction> get_supported_ops_ts() {{"ov_ext::awq_gemm", op::translate_linear_awq},{"ov_ext::embedding", op::translate_embedding_ext},{"ov_ext::conv1d", op::translate_conv1d_ext},- {"ov_ext::linear", op::translate_linear},+ {"ov_ext::linear", op::translate_linear_ext},{"prim::abs", op::translate_1to1_match_1_inputs<opset10::Abs>},{"prim::Constant", op::translate_constant},{"prim::device", op::translate_constant},diff --git a/tests/layer_tests/py_frontend_tests/test_torch_frontend.py b/tests/layer_tests/py_frontend_tests/test_torch_frontend.pyindex fa55fffa8f2..14529a35b3e 100644--- a/tests/layer_tests/py_frontend_tests/test_torch_frontend.py+++ b/tests/layer_tests/py_frontend_tests/test_torch_frontend.py@@ -760,6 +760,39 @@ def test_patched_16bit_model_converts():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)+def test_patched_16bit_model_with_convert():+ from openvino.frontend.pytorch import patch_model+ from openvino import convert_model, Type++ class ModelWithLinear(torch.nn.Module):+ def __init__(self):+ super().__init__()+ self.l1 = torch.nn.Linear(32, 64, dtype=torch.float16)+ self.l2 = torch.nn.Linear(64, 32, dtype=torch.float16)++ def forward(self, x):+ x = self.l1(x)+ x = x.to(self.l1.weight.dtype)+ x = self.l2(x)+ return x++ 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++class InlinedInputsModel(torch.nn.Module):def __init__(self):