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] Support aten::_transformer_encoder_layer_fwd (#37168)
Maxim Vafin015f0a90894e
diff --git a/docs/sphinx_setup/_static/conformance_files/pytorch_ops.csv b/docs/sphinx_setup/_static/conformance_files/pytorch_ops.csvindex 93910ec63cf..001f7fbbf2e 100644--- a/docs/sphinx_setup/_static/conformance_files/pytorch_ops.csv+++ b/docs/sphinx_setup/_static/conformance_files/pytorch_ops.csv@@ -13,6 +13,7 @@ aten::_pack_padded_sequence,aten::_pad_packed_sequence,aten::_set_item,aten::_shape_as_tensor,+aten::_transformer_encoder_layer_fwd,aten::_unique2,aten::_upsample_bicubic2d_aa,aten::_upsample_bilinear2d_aa,diff --git a/src/frontends/pytorch/src/op/native_multi_head_attention.cpp b/src/frontends/pytorch/src/op/native_multi_head_attention.cppindex 217271c1fdf..15fc4cc3649 100644--- a/src/frontends/pytorch/src/op/native_multi_head_attention.cpp+++ b/src/frontends/pytorch/src/op/native_multi_head_attention.cpp@@ -3,23 +3,6 @@//#include "openvino/frontend/pytorch/node_context.hpp"-#include "openvino/op/add.hpp"-#include "openvino/op/broadcast.hpp"-#include "openvino/op/concat.hpp"-#include "openvino/op/divide.hpp"-#include "openvino/op/gather.hpp"-#include "openvino/op/logical_not.hpp"-#include "openvino/op/matmul.hpp"-#include "openvino/op/multiply.hpp"-#include "openvino/op/reduce_sum.hpp"-#include "openvino/op/reshape.hpp"-#include "openvino/op/select.hpp"-#include "openvino/op/shape_of.hpp"-#include "openvino/op/slice.hpp"-#include "openvino/op/softmax.hpp"-#include "openvino/op/sqrt.hpp"-#include "openvino/op/transpose.hpp"-#include "openvino/op/unsqueeze.hpp"#include "pt_framework_node.hpp"#include "utils.hpp"@@ -28,8 +11,6 @@ namespace frontend {namespace pytorch {namespace op {-using namespace ov::op;-OutputVector translate_native_multi_head_attention(const NodeContext& context) {/*aten::_native_multi_head_attention(@@ -49,155 +30,40 @@ OutputVector translate_native_multi_head_attention(const NodeContext& context) {)*/num_inputs_check(context, 13, 13);- const auto query = context.get_input(0);- const auto key = context.get_input(1);- const auto value = context.get_input(2);- const auto embed_dim = context.get_input(3);- const auto num_head = context.get_input(4);- const auto qkv_weight = context.get_input(5);- const auto qkv_bias = context.get_input(6);- const auto proj_weight = context.get_input(7);- const auto proj_bias = context.get_input(8);const auto need_weights = context.const_input<bool>(10);const auto average_weights = context.const_input<bool>(11);- const auto minus_inf =- context.mark_node(v0::Constant::create(element::f32, Shape{}, {-std::numeric_limits<float>::infinity()}));- const auto embed_dim_i64 = context.mark_node(std::make_shared<v0::Convert>(embed_dim, element::i64));- const auto num_head_i64 = context.mark_node(std::make_shared<v0::Convert>(num_head, element::i64));-- const auto neg_one_1d = context.mark_node(v0::Constant::create(element::i64, Shape{1}, {-1}));- const auto zero_1d = context.mark_node(v0::Constant::create(element::i64, Shape{1}, {0}));- const auto one_1d = context.mark_node(v0::Constant::create(element::i64, Shape{1}, {1}));- const auto two_1d = context.mark_node(v0::Constant::create(element::i64, Shape{1}, {2}));- const auto three_1d = context.mark_node(v0::Constant::create(element::i64, Shape{1}, {3}));- const auto heads_1d = context.mark_node(std::make_shared<v0::Unsqueeze>(num_head_i64, zero_1d));-- const auto ev_1_slice_1d = context.mark_node(std::make_shared<v1::Multiply>(one_1d, embed_dim_i64));- const auto ev_2_slice_1d = context.mark_node(std::make_shared<v1::Multiply>(two_1d, embed_dim_i64));- const auto ev_3_slice_1d = context.mark_node(std::make_shared<v1::Multiply>(three_1d, embed_dim_i64));-- const auto qkv_shape = context.mark_node(std::make_shared<v3::ShapeOf>(query));- const auto batch_size = context.mark_node(std::make_shared<v8::Gather>(qkv_shape, zero_1d, zero_1d));- const auto seq_size = context.mark_node(std::make_shared<v8::Gather>(qkv_shape, one_1d, zero_1d));- const auto embed_div_heads = context.mark_node(std::make_shared<v1::Divide>(embed_dim_i64, heads_1d, true));-- const auto query_proj_weight =- context.mark_node(std::make_shared<v8::Slice>(qkv_weight, zero_1d, ev_1_slice_1d, one_1d, zero_1d));- const auto key_proj_weight =- context.mark_node(std::make_shared<v8::Slice>(qkv_weight, ev_1_slice_1d, ev_2_slice_1d, one_1d, zero_1d));- const auto value_proj_weight =- context.mark_node(std::make_shared<v8::Slice>(qkv_weight, ev_2_slice_1d, ev_3_slice_1d, one_1d, zero_1d));- const auto query_proj_bias =- context.mark_node(std::make_shared<v8::Slice>(qkv_bias, zero_1d, ev_1_slice_1d, one_1d, zero_1d));- const auto key_proj_bias =- context.mark_node(std::make_shared<v8::Slice>(qkv_bias, ev_1_slice_1d, ev_2_slice_1d, one_1d, zero_1d));- const auto value_proj_bias =- context.mark_node(std::make_shared<v8::Slice>(qkv_bias, ev_2_slice_1d, ev_3_slice_1d, one_1d, zero_1d));-- const auto query_weighted = context.mark_node(std::make_shared<v0::MatMul>(query, query_proj_weight, false, true));- const auto key_weighted = context.mark_node(std::make_shared<v0::MatMul>(key, key_proj_weight, false, true));- const auto value_weighted = context.mark_node(std::make_shared<v0::MatMul>(value, value_proj_weight, false, true));-- const auto query_biased = context.mark_node(std::make_shared<v1::Add>(query_weighted, query_proj_bias));- const auto key_biased = context.mark_node(std::make_shared<v1::Add>(key_weighted, key_proj_bias));- const auto value_biased = context.mark_node(std::make_shared<v1::Add>(value_weighted, value_proj_bias));-- const auto qkv_reshape_dims =- context.mark_node(std::make_shared<v0::Concat>(OutputVector{batch_size, seq_size, heads_1d, neg_one_1d}, 0));- const auto qv_transpose_dims = context.mark_node(v0::Constant::create(element::i64, Shape{4}, {0, 2, 1, 3}));- const auto k_transpose_dims = context.mark_node(v0::Constant::create(element::i64, Shape{4}, {0, 2, 3, 1}));-- const auto query_reshaped = context.mark_node(std::make_shared<v1::Reshape>(query_biased, qkv_reshape_dims, false));- const auto key_reshaped = context.mark_node(std::make_shared<v1::Reshape>(key_biased, qkv_reshape_dims, false));- const auto value_reshaped = context.mark_node(std::make_shared<v1::Reshape>(value_biased, qkv_reshape_dims, false));-- const auto query_transposed = context.mark_node(std::make_shared<v1::Transpose>(query_reshaped, qv_transpose_dims));- const auto key_transposed = context.mark_node(std::make_shared<v1::Transpose>(key_reshaped, k_transpose_dims));- const auto value_transposed = context.mark_node(std::make_shared<v1::Transpose>(value_reshaped, qv_transpose_dims));-- const auto scale_one = context.mark_node(std::make_shared<v1::ConvertLike>(one_1d, query_transposed));- const auto scale_dim = context.mark_node(std::make_shared<v1::ConvertLike>(embed_div_heads, query_transposed));- const auto scale_dim_sqrt = context.mark_node(std::make_shared<v0::Sqrt>(scale_dim));- const auto scale = context.mark_node(std::make_shared<v1::Divide>(scale_one, scale_dim_sqrt));-- const auto query_key_transpose_dot_product =- context.mark_node(std::make_shared<v0::MatMul>(query_transposed, key_transposed));-- auto scaled_dot_product = context.mark_node(std::make_shared<v1::Multiply>(query_key_transpose_dot_product, scale));-- // Mask handling+ Output<Node> mask;+ int64_t mask_type = 0;if (!context.input_is_none(9) && !context.input_is_none(12)) {- auto atten_mask = context.get_input(9);- // Only allow boolean masks - PyTorch automatically converts- // non-boolean to boolean masks- if (atten_mask.get_element_type() == element::boolean) {- const auto minus_inf_conv =- context.mark_node(std::make_shared<v1::ConvertLike>(minus_inf, scaled_dot_product));- const auto mask_inverse = context.mark_node(std::make_shared<v1::LogicalNot>(atten_mask));- atten_mask = context.mark_node(std::make_shared<v1::ConvertLike>(atten_mask, scaled_dot_product));- atten_mask = context.mark_node(std::make_shared<v1::Select>(mask_inverse, atten_mask, minus_inf_conv));- } else {- // Once int/float mask type is supported in PyTorch,- // remove this assert to allow for such masks in OV- PYTORCH_OP_CONVERSION_CHECK(1, "Non-boolean masks are not supported.");- atten_mask = context.mark_node(std::make_shared<v1::ConvertLike>(atten_mask, scaled_dot_product));- }-- // If mask type is 1 (only key-padding) then mask's shape is (N, S).- // It must be reshaped to (N, 1, 1, S) to properly broadcast it proper dims in the next step- if (context.const_input<int64_t>(12) == 1) {- const auto target_mask_reshape =- context.mark_node(std::make_shared<v0::Concat>(OutputVector{batch_size, one_1d, one_1d, seq_size}, 0));- atten_mask = context.mark_node(std::make_shared<v1::Reshape>(atten_mask, target_mask_reshape, false));- }-- // All mask types should be broadcast to this shape,- // Except for type 2 which already has this shape- if (context.const_input<int64_t>(12) != 2) {- const auto target_mask_shape = context.mark_node(- std::make_shared<v0::Concat>(OutputVector{batch_size, heads_1d, seq_size, seq_size}, 0));- atten_mask = context.mark_node(std::make_shared<v3::Broadcast>(atten_mask, target_mask_shape));- }- scaled_dot_product = context.mark_node(std::make_shared<v1::Add>(scaled_dot_product, atten_mask));+ mask = context.get_input(9);+ mask_type = context.const_input<int64_t>(12);}- const auto scaled_dot_product_softmax = context.mark_node(std::make_shared<v8::Softmax>(scaled_dot_product, -1));- const auto scaled_dot_product_attention =- context.mark_node(std::make_shared<v0::MatMul>(scaled_dot_product_softmax, value_transposed));-- const auto sdp_reshape_dims =- context.mark_node(std::make_shared<v0::Concat>(OutputVector{batch_size, seq_size, neg_one_1d}, 0));- // Undo transpose (transpose back to original qv shape)- const auto scaled_dot_product_attention_transposed =- context.mark_node(std::make_shared<v1::Transpose>(scaled_dot_product_attention, qv_transpose_dims));- const auto scaled_dot_product_attention_reshaped = context.mark_node(- std::make_shared<v1::Reshape>(scaled_dot_product_attention_transposed, sdp_reshape_dims, false));-- const auto scaled_dot_product_attention_weighted = context.mark_node(- std::make_shared<v0::MatMul>(scaled_dot_product_attention_reshaped, proj_weight, false, true));- const auto scaled_dot_product_attention_biased =- context.mark_node(std::make_shared<v1::Add>(scaled_dot_product_attention_weighted, proj_bias));-- if (average_weights) {- const auto target_div_shape = context.mark_node(std::make_shared<v3::ShapeOf>(scaled_dot_product));- const auto heads_div = context.mark_node(std::make_shared<v3::Broadcast>(heads_1d, target_div_shape));- const auto heads_div_conv = context.mark_node(std::make_shared<v1::ConvertLike>(heads_div, scaled_dot_product));- scaled_dot_product = context.mark_node(std::make_shared<v1::Divide>(scaled_dot_product, heads_div_conv, false));- scaled_dot_product = context.mark_node(std::make_shared<v1::ReduceSum>(scaled_dot_product, one_1d));- }+ const auto mha = build_multi_head_attention(context,+ context.get_input(0),+ context.get_input(1),+ context.get_input(2),+ context.get_input(3),+ context.get_input(4),+ context.get_input(5),+ context.get_input(6),+ context.get_input(7),+ context.get_input(8),+ mask,+ mask_type,+ need_weights,+ average_weights);if (need_weights) {- return {scaled_dot_product_attention_biased, scaled_dot_product};- } else {- // When need_weights == false, returns None as a second output- const auto none = std::make_shared<PtFrameworkNode>(context.get_decoder(), context.inputs());- auto attrs = none->get_attrs();- attrs["none_value"] = "";- none->set_attrs(attrs);- const auto none_marked = context.mark_node(none);- return {scaled_dot_product_attention_biased, none_marked};+ return {mha.first, mha.second};}+ // When need_weights == false, returns None as a second output+ const auto none = std::make_shared<PtFrameworkNode>(context.get_decoder(), context.inputs());+ auto attrs = none->get_attrs();+ attrs["none_value"] = "";+ none->set_attrs(attrs);+ return {mha.first, context.mark_node(none)};};} // namespace opdiff --git a/src/frontends/pytorch/src/op/transformer_encoder_layer.cpp b/src/frontends/pytorch/src/op/transformer_encoder_layer.cppnew file mode 100644index 00000000000..b6be9842379--- /dev/null+++ b/src/frontends/pytorch/src/op/transformer_encoder_layer.cpp@@ -0,0 +1,149 @@+// Copyright (C) 2018-2026 Intel Corporation+// SPDX-License-Identifier: Apache-2.0+//++#include "openvino/frontend/pytorch/node_context.hpp"+#include "openvino/op/add.hpp"+#include "openvino/op/constant.hpp"+#include "openvino/op/convert_like.hpp"+#include "openvino/op/gelu.hpp"+#include "openvino/op/matmul.hpp"+#include "openvino/op/multiply.hpp"+#include "openvino/op/mvn.hpp"+#include "openvino/op/relu.hpp"+#include "utils.hpp"++namespace ov {+namespace frontend {+namespace pytorch {+namespace op {++using namespace ov::op;++namespace {+Output<Node> layer_norm(const NodeContext& context,+ const Output<Node>& input,+ const Output<Node>& weight,+ const Output<Node>& bias,+ float eps) {+ // The input is always normalized over the last dimension, which is embed_dim.+ const auto axes = context.mark_node(v0::Constant::create(element::i32, Shape{1}, {-1}));+ Output<Node> res = context.mark_node(std::make_shared<v6::MVN>(input, axes, true, eps, MVNEpsMode::INSIDE_SQRT));+ const auto weight_conv = context.mark_node(std::make_shared<v1::ConvertLike>(weight, res));+ res = context.mark_node(std::make_shared<v1::Multiply>(res, weight_conv));+ const auto bias_conv = context.mark_node(std::make_shared<v1::ConvertLike>(bias, res));+ return context.mark_node(std::make_shared<v1::Add>(res, bias_conv));+}++Output<Node> linear(const NodeContext& context,+ const Output<Node>& input,+ const Output<Node>& weight,+ const Output<Node>& bias) {+ const auto matmul = context.mark_node(std::make_shared<v0::MatMul>(input, weight, false, true));+ return context.mark_node(std::make_shared<v1::Add>(matmul, bias));+}+} // namespace++OutputVector translate_transformer_encoder_layer_fwd(const NodeContext& context) {+ /*+ aten::_transformer_encoder_layer_fwd(+ Tensor src,+ int embed_dim,+ int num_heads,+ Tensor qkv_weight,+ Tensor qkv_bias,+ Tensor proj_weight,+ Tensor proj_bias,+ bool use_gelu,+ bool norm_first,+ float eps,+ Tensor norm_weight_1,+ Tensor norm_bias_1,+ Tensor norm_weight_2,+ Tensor norm_bias_2,+ Tensor ffn_weight_1,+ Tensor ffn_bias_1,+ Tensor ffn_weight_2,+ Tensor ffn_bias_2,+ Optional[Tensor] mask = None,+ Optional[int64] mask_type = None+ )+ */+ // The mask and the mask type are missing in the graphs produced by torch.export.+ num_inputs_check(context, 18, 20);+ const auto src = context.get_input(0);+ const auto embed_dim = context.get_input(1);+ const auto num_heads = context.get_input(2);+ const auto qkv_weight = context.get_input(3);+ const auto qkv_bias = context.get_input(4);+ const auto proj_weight = context.get_input(5);+ const auto proj_bias = context.get_input(6);+ const auto use_gelu = context.const_input<bool>(7);+ const auto norm_first = context.const_input<bool>(8);+ const auto eps = context.const_input<float>(9);+ const auto norm_weight_1 = context.get_input(10);+ const auto norm_bias_1 = context.get_input(11);+ const auto norm_weight_2 = context.get_input(12);+ const auto norm_bias_2 = context.get_input(13);+ const auto ffn_weight_1 = context.get_input(14);+ const auto ffn_bias_1 = context.get_input(15);+ const auto ffn_weight_2 = context.get_input(16);+ const auto ffn_bias_2 = context.get_input(17);++ Output<Node> mask;+ // Mask type 0 is a source mask of shape [sequence, sequence], which is broadcastable to the+ // attention weights, so it is a safe default when the type is not provided.+ int64_t mask_type = 0;+ if (context.get_input_size() > 18 && !context.input_is_none(18)) {+ mask = context.get_input(18);+ if (context.get_input_size() > 19 && !context.input_is_none(19)) {+ mask_type = context.const_input<int64_t>(19);+ }+ }++ Output<Node> x = src;+ if (norm_first) {+ x = layer_norm(context, x, norm_weight_1, norm_bias_1, eps);+ }+ x = build_multi_head_attention(context,+ x,+ x,+ x,+ embed_dim,+ num_heads,+ qkv_weight,+ qkv_bias,+ proj_weight,+ proj_bias,+ mask,+ mask_type,+ /* need_weights */ false,+ /* average_weights */ false)+ .first;+ x = context.mark_node(std::make_shared<v1::Add>(x, src));+ if (!norm_first) {+ x = layer_norm(context, x, norm_weight_1, norm_bias_1, eps);+ }++ const auto pre_ffn_res = x;+ if (norm_first) {+ x = layer_norm(context, x, norm_weight_2, norm_bias_2, eps);+ }+ x = linear(context, x, ffn_weight_1, ffn_bias_1);+ if (use_gelu) {+ x = context.mark_node(std::make_shared<v7::Gelu>(x, GeluApproximationMode::ERF));+ } else {+ x = context.mark_node(std::make_shared<v0::Relu>(x));+ }+ x = linear(context, x, ffn_weight_2, ffn_bias_2);+ x = context.mark_node(std::make_shared<v1::Add>(x, pre_ffn_res));+ if (!norm_first) {+ x = layer_norm(context, x, norm_weight_2, norm_bias_2, eps);+ }+ return {x};+};++} // namespace op+} // namespace pytorch+} // namespace frontend+} // namespace ovdiff --git a/src/frontends/pytorch/src/op_table.cpp b/src/frontends/pytorch/src/op_table.cppindex 038eb783ba3..998e4f5fcee 100644--- a/src/frontends/pytorch/src/op_table.cpp+++ b/src/frontends/pytorch/src/op_table.cpp@@ -273,6 +273,7 @@ OP_CONVERTER(translate_t);OP_CONVERTER(translate_take_along_dim);OP_CONVERTER(translate_to);OP_CONVERTER(translate_topk);+OP_CONVERTER(translate_transformer_encoder_layer_fwd);OP_CONVERTER(translate_transpose);OP_CONVERTER(translate_tril);OP_CONVERTER(translate_triu);@@ -403,6 +404,7 @@ const std::unordered_map<std::string, CreatorFunction> get_supported_ops_ts() {{"aten::_pad_packed_sequence", op::translate_pad_packed_sequence},{"aten::_set_item", op::translate_set_item},{"aten::_shape_as_tensor", op::translate_shape_as_tensor},+ {"aten::_transformer_encoder_layer_fwd", op::translate_transformer_encoder_layer_fwd},{"aten::_unique2", op::translate_unique2},{"aten::_upsample_bicubic2d_aa", op::translate_upsample_bicubic2d_aa},{"aten::_upsample_bilinear2d_aa", op::translate_upsample_bilinear2d_aa},@@ -890,6 +892,7 @@ const std::unordered_map<std::string, CreatorFunction> get_supported_ops_fx() {{"aten._scaled_dot_product_flash_attention_for_cpu.default", op::translate_scaled_dot_product_attention_fx},{"aten._softmax.default", op::translate_softmax_fx},{"aten._to_copy.default", op::translate_to_fx},+ {"aten._transformer_encoder_layer_fwd.default", op::translate_transformer_encoder_layer_fwd},{"aten._unsafe_view.default", op::translate_reshape},{"aten.abs.default", op::translate_1to1_match_1_inputs<opset10::Abs>},{"aten.absolute.default", op::translate_1to1_match_1_inputs<opset10::Abs>},diff --git a/src/frontends/pytorch/src/utils.cpp b/src/frontends/pytorch/src/utils.cppindex 99bf5a92f05..1ba74a1550d 100644--- a/src/frontends/pytorch/src/utils.cpp+++ b/src/frontends/pytorch/src/utils.cpp@@ -18,18 +18,24 @@#include "openvino/op/divide.hpp"#include "openvino/op/gather.hpp"#include "openvino/op/gather_nd.hpp"+#include "openvino/op/logical_not.hpp"#include "openvino/op/loop.hpp"+#include "openvino/op/matmul.hpp"#include "openvino/op/max_pool.hpp"#include "openvino/op/mod.hpp"#include "openvino/op/multiply.hpp"#include "openvino/op/non_zero.hpp"#include "openvino/op/range.hpp"+#include "openvino/op/reduce_mean.hpp"#include "openvino/op/reduce_prod.hpp"#include "openvino/op/reshape.hpp"+#include "openvino/op/scaled_dot_product_attention.hpp"#include "openvino/op/select.hpp"#include "openvino/op/shape_of.hpp"#include "openvino/op/slice.hpp"+#include "openvino/op/softmax.hpp"#include "openvino/op/split.hpp"+#include "openvino/op/sqrt.hpp"#include "openvino/op/squeeze.hpp"#include "openvino/op/subtract.hpp"#include "openvino/op/transpose.hpp"@@ -821,6 +827,113 @@ Output<Node> masked_select(const NodeContext& context, const Output<Node>& data,return context.mark_node(std::make_shared<v8::GatherND>(data, masked_id));}+std::pair<Output<Node>, Output<Node>> build_multi_head_attention(const NodeContext& context,+ const Output<Node>& query,+ const Output<Node>& key,+ const Output<Node>& value,+ const Output<Node>& embed_dim,+ const Output<Node>& num_heads,+ const Output<Node>& qkv_weight,+ const Output<Node>& qkv_bias,+ const Output<Node>& proj_weight,+ const Output<Node>& proj_bias,+ const Output<Node>& attn_mask,+ int64_t mask_type,+ bool need_weights,+ bool average_weights) {+ const auto neg_one_1d = context.mark_node(v0::Constant::create(element::i64, Shape{1}, {-1}));+ const auto zero_1d = context.mark_node(v0::Constant::create(element::i64, Shape{1}, {0}));+ const auto one_1d = context.mark_node(v0::Constant::create(element::i64, Shape{1}, {1}));+ const auto two_1d = context.mark_node(v0::Constant::create(element::i64, Shape{1}, {2}));+ const auto three_1d = context.mark_node(v0::Constant::create(element::i64, Shape{1}, {3}));++ const auto embed_dim_i64 = context.mark_node(std::make_shared<v0::Convert>(embed_dim, element::i64));+ const auto num_heads_i64 = context.mark_node(std::make_shared<v0::Convert>(num_heads, element::i64));+ const auto embed_dim_1d = context.mark_node(std::make_shared<v0::Unsqueeze>(embed_dim_i64, zero_1d));+ const auto heads_1d = context.mark_node(std::make_shared<v0::Unsqueeze>(num_heads_i64, zero_1d));+ const auto embed_dim_2x = context.mark_node(std::make_shared<v1::Multiply>(embed_dim_1d, two_1d));+ const auto embed_dim_3x = context.mark_node(std::make_shared<v1::Multiply>(embed_dim_1d, three_1d));++ // Zeros keep the batch and the sequence dimensions of the input, so no ShapeOf is needed.+ const auto to_heads_shape =+ context.mark_node(std::make_shared<v0::Concat>(OutputVector{zero_1d, zero_1d, heads_1d, neg_one_1d}, 0));+ const auto from_heads_shape =+ context.mark_node(std::make_shared<v0::Constant>(element::i64, Shape{3}, std::vector<int64_t>{0, 0, -1}));+ const auto heads_perm =+ context.mark_node(std::make_shared<v0::Constant>(element::i64, Shape{4}, std::vector<int64_t>{0, 2, 1, 3}));++ // Slices the packed projection, applies it and splits the result into heads:+ // [batch, sequence, embed_dim] -> [batch, heads, sequence, embed_dim / heads]+ const auto project = [&](const Output<Node>& x, const Output<Node>& begin, const Output<Node>& end) {+ const auto weight = context.mark_node(std::make_shared<v8::Slice>(qkv_weight, begin, end, one_1d, zero_1d));+ const auto bias = context.mark_node(std::make_shared<v8::Slice>(qkv_bias, begin, end, one_1d, zero_1d));+ Output<Node> res = context.mark_node(std::make_shared<v0::MatMul>(x, weight, false, true));+ res = context.mark_node(std::make_shared<v1::Add>(res, bias));+ res = context.mark_node(std::make_shared<v1::Reshape>(res, to_heads_shape, true));+ return context.mark_node(std::make_shared<v1::Transpose>(res, heads_perm));+ };++ const auto q = project(query, zero_1d, embed_dim_1d);+ const auto k = project(key, embed_dim_1d, embed_dim_2x);+ const auto v = project(value, embed_dim_2x, embed_dim_3x);++ Output<Node> mask = attn_mask;+ if (mask.get_node_shared_ptr() && mask_type == 1) {+ // Key padding mask of shape [batch, sequence] has to be made broadcastable to the attention+ // weights shape [batch, heads, sequence, sequence].+ const auto axes = context.mark_node(v0::Constant::create(element::i64, Shape{2}, {1, 2}));+ mask = context.mark_node(std::make_shared<v0::Unsqueeze>(mask, axes));+ }+ const bool mask_is_boolean = mask.get_node_shared_ptr() && mask.get_element_type() == element::boolean;+ if (mask.get_node_shared_ptr() && !mask_is_boolean) {+ // Any non-boolean mask is additive and has to share the element type with the attention weights.+ mask = context.mark_node(std::make_shared<v1::ConvertLike>(mask, q));+ }++ Output<Node> attention;+ Output<Node> weights;+ if (need_weights) {+ // ScaledDotProductAttention does not expose the attention weights, so it is decomposed here.+ const auto head_dim = context.mark_node(std::make_shared<v1::Divide>(embed_dim_i64, num_heads_i64, true));+ const auto scale_one = context.mark_node(std::make_shared<v1::ConvertLike>(one_1d, q));+ const auto scale_dim = context.mark_node(std::make_shared<v1::ConvertLike>(head_dim, q));+ const auto scale_dim_sqrt = context.mark_node(std::make_shared<v0::Sqrt>(scale_dim));+ const auto scale = context.mark_node(std::make_shared<v1::Divide>(scale_one, scale_dim_sqrt));++ const auto qk = context.mark_node(std::make_shared<v0::MatMul>(q, k, false, true));+ weights = context.mark_node(std::make_shared<v1::Multiply>(qk, scale));+ if (mask_is_boolean) {+ const auto minus_inf = context.mark_node(+ v0::Constant::create(element::f32, Shape{}, {-std::numeric_limits<float>::infinity()}));+ const auto minus_inf_conv = context.mark_node(std::make_shared<v1::ConvertLike>(minus_inf, weights));+ weights = context.mark_node(std::make_shared<v1::Select>(mask, minus_inf_conv, weights));+ } else if (mask.get_node_shared_ptr()) {+ weights = context.mark_node(std::make_shared<v1::Add>(weights, mask));+ }+ weights = context.mark_node(std::make_shared<v8::Softmax>(weights, -1));+ attention = context.mark_node(std::make_shared<v0::MatMul>(weights, v));+ if (average_weights) {+ weights = context.mark_node(std::make_shared<v1::ReduceMean>(weights, one_1d, false));+ }+ } else {+ OutputVector sdpa_inputs{q, k, v};+ if (mask.get_node_shared_ptr()) {+ // A boolean mask marks the positions to exclude in PyTorch and the positions to keep in+ // ScaledDotProductAttention.+ sdpa_inputs.push_back(mask_is_boolean ? context.mark_node(std::make_shared<v1::LogicalNot>(mask)) : mask);+ }+ // The default ScaledDotProductAttention scale is 1 / sqrt(embed_dim / heads), same as PyTorch uses.+ attention = context.mark_node(std::make_shared<v13::ScaledDotProductAttention>(sdpa_inputs, false));+ }++ // [batch, heads, sequence, embed_dim / heads] -> [batch, sequence, embed_dim]+ Output<Node> res = context.mark_node(std::make_shared<v1::Transpose>(attention, heads_perm));+ res = context.mark_node(std::make_shared<v1::Reshape>(res, from_heads_shape, true));+ res = context.mark_node(std::make_shared<v0::MatMul>(res, proj_weight, false, true));+ res = context.mark_node(std::make_shared<v1::Add>(res, proj_bias));+ return {res, weights};+}+OutputVector build_static_max_pool(ov::pass::NodeRegistry& rg,Output<Node> input,int dims,diff --git a/src/frontends/pytorch/src/utils.hpp b/src/frontends/pytorch/src/utils.hppindex b305871a07a..a9253583069 100644--- a/src/frontends/pytorch/src/utils.hpp+++ b/src/frontends/pytorch/src/utils.hpp@@ -164,6 +164,46 @@ OutputVector build_static_max_pool(ov::pass::NodeRegistry& rg,Output<Node> masked_select(const NodeContext& context, const Output<Node>& data, const Output<Node>& mask);+/// \brief Builds a multi-head attention subgraph with packed query/key/value projection weights.+///+/// Shared by `aten::_native_multi_head_attention` and `aten::_transformer_encoder_layer_fwd`.+/// When the attention weights are not requested, the attention itself is expressed with a single+/// `v13::ScaledDotProductAttention`, otherwise it is decomposed so that the weights can be returned.+///+/// \param context Node context used to mark the created nodes.+/// \param query Query tensor of shape [batch, sequence, embed_dim].+/// \param key Key tensor of shape [batch, sequence, embed_dim].+/// \param value Value tensor of shape [batch, sequence, embed_dim].+/// \param embed_dim Scalar embedding dimension.+/// \param num_heads Scalar number of attention heads.+/// \param qkv_weight Packed query/key/value projection weight of shape [3 * embed_dim, embed_dim].+/// \param qkv_bias Packed query/key/value projection bias of shape [3 * embed_dim].+/// \param proj_weight Output projection weight.+/// \param proj_bias Output projection bias.+/// \param attn_mask Optional attention mask. A boolean mask excludes the positions marked with+/// `true`, any other mask is additive. Pass an empty output to skip masking.+/// \param mask_type PyTorch mask type: 0 - source mask of shape [sequence, sequence], 1 - key+/// padding mask of shape [batch, sequence], 2 - mask already broadcast to the attention+/// weights shape. Ignored when `attn_mask` is empty.+/// \param need_weights When true, the attention weights are computed and returned as the second+/// element of the result, otherwise the second element is empty.+/// \param average_weights When true, the returned attention weights are averaged over the heads.+/// \return Pair of the attention output and the attention weights.+std::pair<Output<Node>, Output<Node>> build_multi_head_attention(const NodeContext& context,+ const Output<Node>& query,+ const Output<Node>& key,+ const Output<Node>& value,+ const Output<Node>& embed_dim,+ const Output<Node>& num_heads,+ const Output<Node>& qkv_weight,+ const Output<Node>& qkv_bias,+ const Output<Node>& proj_weight,+ const Output<Node>& proj_bias,+ const Output<Node>& attn_mask,+ int64_t mask_type,+ bool need_weights,+ bool average_weights);+Output<Node> flatten(ov::pass::NodeRegistry& rg, const Output<Node>& value, size_t axis);bool index_tensor_on_list(ov::pass::NodeRegistry& rg,diff --git a/tests/layer_tests/pytorch_tests/test_native_multi_head_attention.py b/tests/layer_tests/pytorch_tests/test_native_multi_head_attention.pyindex e7f1363a3e3..84a1911ddfc 100644--- a/tests/layer_tests/pytorch_tests/test_native_multi_head_attention.py+++ b/tests/layer_tests/pytorch_tests/test_native_multi_head_attention.py@@ -16,7 +16,7 @@ BATCH_SIZE = 1NO_MASK, ATTN_MASK, KEY_PAD_MASK, MERGED_MASK = -1, 0, 1, 2class aten_native_multi_head_attention(torch.nn.Module):- def __init__(self, mask, need_weights, average_attn_weights, mask_data=None) -> None:+ def __init__(self, mask, need_weights, average_attn_weights, mask_data=None, mask_dtype="bool") -> None:super().__init__()self.qkv = torch.nn.Linear(EMBED_DIM, 3 * EMBED_DIM, dtype = torch.float32)self.qkv.requires_grad_(False)@@ -28,17 +28,21 @@ class aten_native_multi_head_attention(torch.nn.Module):self.need_weights = need_weightsself.average_attn_weights = average_attn_weights- # Currently only int masks are working correctly, they are converted to bool.- # Float masks raise a warning in PyTorch and are (incorrectly) converted to bool,- # which later returns NaNs as MHA's output+ def make_mask(data):+ bool_mask = torch.from_numpy(data.astype("bool"))+ if mask_dtype == "float":+ # A non-boolean mask is additive: masked positions carry -inf, unmasked ones 0.+ return torch.zeros(bool_mask.shape, dtype=torch.float32).masked_fill(bool_mask, float("-inf"))+ return bool_mask+if mask == ATTN_MASK:- self.mask = torch.from_numpy(mask_data.astype("bool")) if mask_data is not None else None+ self.mask = make_mask(mask_data) if mask_data is not None else Noneself.mask_type = ATTN_MASKelif mask == KEY_PAD_MASK:- self.mask = torch.from_numpy(mask_data.astype("bool")) if mask_data is not None else None+ self.mask = make_mask(mask_data) if mask_data is not None else Noneself.mask_type = KEY_PAD_MASKelif mask == MERGED_MASK:- self.mask = torch.from_numpy(mask_data.astype("bool")) if mask_data is not None else None+ self.mask = make_mask(mask_data) if mask_data is not None else Noneself.mask_type = MERGED_MASKelse:self.mask = None@@ -55,6 +59,23 @@ class aten_native_multi_head_attention(torch.nn.Module):mask_type = self.mask_type)[0]++class aten_native_multi_head_attention_with_weights(aten_native_multi_head_attention):+ """Like aten_native_multi_head_attention, but also returns the attention weights output.+ Only meant to be used with need_weights=True, where the second output is a Tensor (not None),+ so the traced/scripted graph has a single, well defined output type."""++ def forward(self, query, key, value):+ return torch.ops.aten._native_multi_head_attention(+ query, key, value,+ embed_dim=self.embed_dim, num_head=self.num_heads,+ qkv_weight=self.qkv.weight, qkv_bias=self.qkv.bias,+ proj_weight=self.proj.weight, proj_bias=self.proj.bias,+ mask = self.mask, need_weights=self.need_weights,+ average_attn_weights = self.average_attn_weights,+ mask_type = self.mask_type+ )+class TestNativeMultiHeadAttention(PytorchLayerTest):def _prepare_input(self):# NativeMHA is self-attention@@ -90,3 +111,37 @@ class TestNativeMultiHeadAttention(PytorchLayerTest):def test_native_multi_head_attention(self, ie_device, precision, ir_version, mask, need_weights, average_attn_weights):mask_data = self._get_mask_data(mask)self._test(aten_native_multi_head_attention(mask, need_weights, average_attn_weights, mask_data), "aten::_native_multi_head_attention", ie_device, precision, ir_version)++ @pytest.mark.nightly+ @pytest.mark.precommit+ @pytest.mark.parametrize(+ "mask",+ [NO_MASK, ATTN_MASK, KEY_PAD_MASK, MERGED_MASK]+ )+ @pytest.mark.parametrize("average_attn_weights", [False, True])+ @pytest.mark.parametrize("mask_dtype", ["bool", "float"])+ @pytest.mark.xfail(condition=platform.system() in ('Darwin', 'Linux') and platform.machine() in ('arm', 'armv7l',+ 'aarch64',+ 'arm64', 'ARM64'),+ reason='Ticket - 122715')+ def test_native_multi_head_attention_weights(self, ie_device, precision, ir_version, mask, average_attn_weights,+ mask_dtype):+ # The attention weights (second output) are only produced/checked here, both averaged and+ # non-averaged. This also covers non-boolean (additive) masks: aten::_native_multi_head_attention+ # accepts them the same way as aten::_transformer_encoder_layer_fwd does.+ if ie_device == "CPU" and mask == KEY_PAD_MASK and mask_dtype == "float":+ # A key-padding mask, once unsqueezed to [batch, 1, 1, seq], is additive and has exactly+ # `seq` elements, i.e. the same size as the last dimension of the preceding QK^T MatMul.+ # The CPU plugin's post-ops fusion (DnnlPostOpsComposer::appendBinary) misidentifies this+ # Add as a fusable per-output-channel bias and fails with+ # "Check 'data.size() == OC' failed ... data size: 6 OC: 0" at graph compilation time,+ # because MatMul (unlike Convolution/FullyConnected) has no well-defined output-channel+ # axis for this fusion. This is a CPU plugin defect, not a PyTorch FE conversion issue -+ # the produced graph is mathematically correct and matches PyTorch's output.+ pytest.xfail("CPU plugin fails to compile Add(MatMul_output, mask) when the additive mask "+ "has as many elements as the MatMul's last dimension "+ "(dnnl_postops_composer.cpp:483, 'data.size() == OC' assertion)")+ mask_data = self._get_mask_data(mask)+ self._test(aten_native_multi_head_attention_with_weights(mask, True, average_attn_weights, mask_data,+ mask_dtype=mask_dtype),+ "aten::_native_multi_head_attention", ie_device, precision, ir_version)diff --git a/tests/layer_tests/pytorch_tests/test_transformer_encoder_layer.py b/tests/layer_tests/pytorch_tests/test_transformer_encoder_layer.pynew file mode 100644index 00000000000..4819710307f--- /dev/null+++ b/tests/layer_tests/pytorch_tests/test_transformer_encoder_layer.py@@ -0,0 +1,129 @@+# Copyright (C) 2018-2026 Intel Corporation+# SPDX-License-Identifier: Apache-2.0++import pytest+import torch++from pytorch_layer_test_class import PytorchLayerTest++EMBED_DIM = 8+NUM_HEADS = 4+FFN_DIM = 16+SEQ_LENGTH = 6+BATCH_SIZE = 2++NO_MASK, ATTN_MASK, KEY_PAD_MASK, MERGED_MASK = -1, 0, 1, 2+++def make_encoder_layer(norm_first, activation):+ layer = torch.nn.TransformerEncoderLayer(d_model=EMBED_DIM,+ nhead=NUM_HEADS,+ dim_feedforward=FFN_DIM,+ dropout=0.0,+ activation=activation,+ norm_first=norm_first,+ batch_first=True,+ dtype=torch.float32)+ layer.eval()+ layer.requires_grad_(False)+ return layer+++class aten_transformer_encoder_layer_fwd(torch.nn.Module):+ """Calls the fast-path operation directly, so that it is present both in+ TorchScript and in the graph produced by torch.export."""++ def __init__(self, norm_first, use_gelu, mask_type, mask_data=None) -> None:+ super().__init__()+ self.layer = make_encoder_layer(norm_first, "gelu" if use_gelu else "relu")+ self.use_gelu = use_gelu+ self.norm_first = norm_first+ self.mask_type = mask_type if mask_type != NO_MASK else None+ # PyTorch canonicalizes boolean masks into additive float masks before+ # calling the fast path operation.+ self.mask = None+ if mask_data is not None:+ self.mask = torch.zeros(mask_data.shape, dtype=torch.float32).masked_fill(+ torch.from_numpy(mask_data.astype("bool")), float("-inf"))++ def forward(self, src):+ layer = self.layer+ return torch.ops.aten._transformer_encoder_layer_fwd(+ src, EMBED_DIM, NUM_HEADS,+ layer.self_attn.in_proj_weight, layer.self_attn.in_proj_bias,+ layer.self_attn.out_proj.weight, layer.self_attn.out_proj.bias,+ self.use_gelu, self.norm_first, layer.norm1.eps,+ layer.norm1.weight, layer.norm1.bias,+ layer.norm2.weight, layer.norm2.bias,+ layer.linear1.weight, layer.linear1.bias,+ layer.linear2.weight, layer.linear2.bias,+ self.mask, self.mask_type)+++class aten_transformer_encoder_layer_module(torch.nn.Module):+ """Uses the public module, which dispatches to the fast path when traced."""++ def __init__(self, norm_first, activation, mask_type=NO_MASK, mask_data=None) -> None:+ super().__init__()+ self.layer = make_encoder_layer(norm_first, activation)+ self.mask_type = mask_type+ self.mask = torch.from_numpy(mask_data.astype("bool")) if mask_data is not None else None++ def forward(self, src):+ if self.mask_type == KEY_PAD_MASK:+ return self.layer(src, src_key_padding_mask=self.mask)+ if self.mask_type == ATTN_MASK:+ return self.layer(src, src_mask=self.mask)+ return self.layer(src)+++class TestTransformerEncoderLayerFwd(PytorchLayerTest):+ def _prepare_input(self):+ return (self.random.randn(BATCH_SIZE, SEQ_LENGTH, EMBED_DIM).astype("float32"),)++ def _get_mask_data(self, mask_type):+ if mask_type == ATTN_MASK:+ # Keep at least one unmasked position per row to avoid NaNs in softmax+ mask = self.random.randint(0, 2, (SEQ_LENGTH, SEQ_LENGTH))+ mask[:, 0] = 0+ return mask+ if mask_type == KEY_PAD_MASK:+ # Keep at least one unmasked position per row to avoid NaNs in softmax+ mask = self.random.randint(0, 2, (BATCH_SIZE, SEQ_LENGTH))+ mask[:, 0] = 0+ return mask+ if mask_type == MERGED_MASK:+ mask = self.random.randint(0, 2, (BATCH_SIZE, NUM_HEADS, SEQ_LENGTH, SEQ_LENGTH))+ mask[:, :, :, 0] = 0+ return mask+ return None++ @pytest.mark.nightly+ @pytest.mark.precommit+ @pytest.mark.parametrize("norm_first", [False, True])+ @pytest.mark.parametrize("use_gelu", [False, True])+ @pytest.mark.parametrize("mask_type", [NO_MASK, ATTN_MASK, KEY_PAD_MASK, MERGED_MASK])+ def test_transformer_encoder_layer_fwd(self, norm_first, use_gelu, mask_type,+ ie_device, precision, ir_version):+ mask_data = self._get_mask_data(mask_type)+ self._test(aten_transformer_encoder_layer_fwd(norm_first, use_gelu, mask_type, mask_data),+ "aten::_transformer_encoder_layer_fwd", ie_device, precision, ir_version,+ trace_model=True, custom_eps=1e-4)++ @pytest.mark.nightly+ @pytest.mark.precommit+ # norm_first=True disables PyTorch's fused fast path (why_not_sparsity_fast_path =+ # "norm_first was True"), so the traced graph decomposes into elementary ops and+ # aten::_transformer_encoder_layer_fwd is never emitted. That case is already covered+ # by test_transformer_encoder_layer_fwd, which calls the fast-path op directly.+ @pytest.mark.parametrize("norm_first", [False])+ @pytest.mark.parametrize("activation", ["relu", "gelu"])+ @pytest.mark.skipif(PytorchLayerTest.use_torch_export(),+ reason="TransformerEncoderLayer fast path is not used by torch.export")+ @pytest.mark.parametrize("mask_type", [NO_MASK, ATTN_MASK, KEY_PAD_MASK])+ def test_transformer_encoder_layer_module(self, norm_first, activation, mask_type,+ ie_device, precision, ir_version):+ mask_data = self._get_mask_data(mask_type)+ self._test(aten_transformer_encoder_layer_module(norm_first, activation, mask_type, mask_data),+ "aten::_transformer_encoder_layer_fwd", ie_device, precision, ir_version,+ trace_model=True, custom_eps=1e-4)