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
[ONNX FE] Enable conversion of ONNX Attention 24 operation (#36689)
Andrii Staikov8f80f6f6f8c6
diff --git a/src/frontends/onnx/docs/supported_ops.md b/src/frontends/onnx/docs/supported_ops.mdindex 4c5234ce63b..7521da35d54 100644--- a/src/frontends/onnx/docs/supported_ops.md+++ b/src/frontends/onnx/docs/supported_ops.md@@ -20,7 +20,7 @@ OpenVINO provides support for operations of Default Opset (empty in table below)| |Asinh |9 |22, 9 | || |Atan |7 |22, 7 | || |Atanh |9 |22, 9 | |-| |Attention |23 |23 | |+| |Attention |24, 23 |24, 23 | || |AveragePool |1 |22, 19, 11, 10, 7, 1 | || |BatchNormalization |14, 7, 1 |15, 14, 9, 7, 6, 1 | || |Bernoulli | |22, 15 | |diff --git a/src/frontends/onnx/frontend/CMakeLists.txt b/src/frontends/onnx/frontend/CMakeLists.txtindex 0757af6e455..40b8a21a5a6 100644--- a/src/frontends/onnx/frontend/CMakeLists.txt+++ b/src/frontends/onnx/frontend/CMakeLists.txt@@ -77,7 +77,7 @@ ov_add_frontend(NAME onnxFILEDESCRIPTION "FrontEnd to load and convert ONNX file format"LINK_LIBRARIES openvino_onnx_common openvino::core::dev)-set(ONNX_OPSET_VERSION 23 CACHE INTERNAL "Supported version of ONNX operator set")+set(ONNX_OPSET_VERSION 24 CACHE INTERNAL "Supported version of ONNX operator set")target_compile_definitions(${TARGET_NAME} PRIVATE ONNX_OPSET_VERSION=${ONNX_OPSET_VERSION})if(BUILD_SHARED_LIBS)diff --git a/src/frontends/onnx/frontend/src/op/attention.cpp b/src/frontends/onnx/frontend/src/op/attention.cppindex 28b858766af..721f2522b6c 100644--- a/src/frontends/onnx/frontend/src/op/attention.cpp+++ b/src/frontends/onnx/frontend/src/op/attention.cpp@@ -4,17 +4,31 @@#include "utils/attention.hpp"+#include <limits>+#include "core/null_node.hpp"#include "core/operator_set.hpp"#include "exceptions.hpp"#include "openvino/op/add.hpp"#include "openvino/op/concat.hpp"#include "openvino/op/constant.hpp"+#include "openvino/op/convert.hpp"+#include "openvino/op/convert_like.hpp"#include "openvino/op/divide.hpp"+#include "openvino/op/is_nan.hpp"+#include "openvino/op/less.hpp"+#include "openvino/op/multiply.hpp"+#include "openvino/op/pad.hpp"+#include "openvino/op/range.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/squeeze.hpp"+#include "openvino/op/subtract.hpp"#include "openvino/op/tile.hpp"#include "openvino/op/transpose.hpp"+#include "openvino/op/unsqueeze.hpp"#include "utils/common.hpp"using namespace ov::op;@@ -27,95 +41,113 @@ namespace ai_onnx {namespace detail {namespace {-// Reshape 3D input (batch, seq, num_heads * head_size) to 4D (batch, num_heads, seq, head_size)-// Uses direct reshape matching the ONNX Attention spec (no transpose):-// the hidden dimension is split as [num_heads, seq, head_size] in row-major order.-ov::Output<ov::Node> reshape_3d_to_4d(const ov::Output<ov::Node>& input, int64_t num_heads) {- auto input_shape = std::make_shared<v3::ShapeOf>(input);- auto batch = get_dimensions(input_shape, {0});- auto seq = get_dimensions(input_shape, {1});- auto num_heads_node = v0::Constant::create(ov::element::i64, ov::Shape{1}, {num_heads});- auto hidden = get_dimensions(input_shape, {2});- auto head_size = std::make_shared<v1::Divide>(hidden, num_heads_node);- // Direct reshape to (batch, num_heads, seq, head_size)- auto new_shape = std::make_shared<v0::Concat>(ov::NodeVector{batch, num_heads_node, seq, head_size}, 0);- return std::make_shared<v1::Reshape>(input, new_shape, false);-}--// Reshape 4D output (batch, num_heads, seq, head_size) back to 3D (batch, seq, num_heads * head_size)-ov::Output<ov::Node> reshape_4d_to_3d(const ov::Output<ov::Node>& output) {- // Transpose from (batch, num_heads, seq, head_size) to (batch, seq, num_heads, head_size)- auto perm = v0::Constant::create(ov::element::i64, ov::Shape{4}, {0, 2, 1, 3});- auto transposed = std::make_shared<v1::Transpose>(output, perm);- // Reshape to (batch, seq, num_heads * head_size)- auto reshape_pattern = v0::Constant::create(ov::element::i32, ov::Shape{3}, {0, 0, -1});- return std::make_shared<v1::Reshape>(transposed, reshape_pattern, true);-}--// Repeat K/V heads for GQA: (B, kv_h, seq, h) -> (B, kv_h * n_rep, seq, h)-// Uses Tile to match ONNX spec's np.tile(K, [1, n_rep, 1, 1]) behavior.+// Repeat K/V heads for GQA: (B, kv_h, seq, h) -> (B, kv_h * n_rep, seq, h).+// Interleave-repeats each KV head n_rep times ([h0]*n_rep, [h1]*n_rep, ...) to match the ONNX+// reference's np.repeat(K, n_rep, axis=1): contiguous query-head groups share one KV head.// n_rep = q_num_heads / kv_num_headsov::Output<ov::Node> repeat_kv(const ov::Output<ov::Node>& input, int64_t n_rep) {if (n_rep == 1) {return input;}- auto repeats = v0::Constant::create(ov::element::i64, ov::Shape{4}, std::vector<int64_t>{1, n_rep, 1, 1});- return std::make_shared<v0::Tile>(input, repeats);+ auto shape = std::make_shared<v3::ShapeOf>(input);+ auto batch = get_dimensions(shape, {0});+ auto kv_h = get_dimensions(shape, {1});+ auto seq = get_dimensions(shape, {2});+ auto head = get_dimensions(shape, {3});+ auto n_rep_node = v0::Constant::create(ov::element::i64, ov::Shape{1}, {n_rep});+ auto new_heads = std::make_shared<v1::Multiply>(kv_h, n_rep_node); // kv_h * n_rep++ // (B, kv_h, seq, h) -> (B, kv_h, 1, seq, h) -> (B, kv_h, n_rep, seq, h)+ auto axis2 = v0::Constant::create(ov::element::i64, ov::Shape{1}, {2});+ auto unsq = std::make_shared<v0::Unsqueeze>(input, axis2);+ auto tile_repeats = v0::Constant::create(ov::element::i64, ov::Shape{5}, std::vector<int64_t>{1, 1, n_rep, 1, 1});+ auto tiled = std::make_shared<v0::Tile>(unsq, tile_repeats);++ // merge (kv_h, n_rep) -> kv_h*n_rep : (B, kv_h*n_rep, seq, h)+ auto new_shape = std::make_shared<v0::Concat>(ov::OutputVector{batch, new_heads, seq, head}, 0);+ return std::make_shared<v1::Reshape>(tiled, new_shape, false);}-} // namespace-} // namespace detail+const float NEG_INF = -std::numeric_limits<float>::infinity();-namespace opset_23 {-ov::OutputVector attention(const ov::frontend::onnx::Node& node) {- auto inputs = node.get_ov_inputs();- const auto num_inputs = inputs.size();- CHECK_VALID_NODE(node, num_inputs >= 3, "Attention expects at least 3 inputs, got: ", num_inputs);+// Build an additive padding mask (-inf for disallowed) from nonpad_kv_seqlen.+// Key position j is valid for batch b iff j < nonpad[b]. Result shape: (B, 1, 1, seq_kv).+ov::Output<ov::Node> build_padding_mask(const ov::Output<ov::Node>& K, const ov::Output<ov::Node>& nonpad) {+ auto k_shape = std::make_shared<v3::ShapeOf>(K);+ auto seq_kv = get_dimensions(k_shape, {2}); // (1,)+ auto zero = v0::Constant::create(ov::element::i64, ov::Shape{}, {0});+ auto one = v0::Constant::create(ov::element::i64, ov::Shape{}, {1});+ auto seq_kv_s = std::make_shared<v0::Squeeze>(seq_kv, zero);+ auto col = std::make_shared<v4::Range>(zero, seq_kv_s, one, ov::element::i64); // (seq_kv,)- // Required inputs- auto Q = inputs[0];- auto K = inputs[1];- auto V = inputs[2];+ auto col_shape = v0::Constant::create(ov::element::i64, ov::Shape{4}, {1, 1, 1, -1});+ auto col_4d = std::make_shared<v1::Reshape>(col, col_shape, false); // (1, 1, 1, seq_kv)+ auto nonpad_shape = v0::Constant::create(ov::element::i64, ov::Shape{4}, {-1, 1, 1, 1});+ auto nonpad_4d = std::make_shared<v1::Reshape>(nonpad, nonpad_shape, false); // (B, 1, 1, 1)- // Optional inputs- bool has_attn_mask = common::is_input_valid(node, 3);- bool has_past_key = common::is_input_valid(node, 4);- bool has_past_value = common::is_input_valid(node, 5);+ auto allowed = std::make_shared<v1::Less>(col_4d, nonpad_4d); // (B, 1, 1, seq_kv)+ return convert_boolean_mask(allowed, K.get_element_type());+}- CHECK_VALID_NODE(node,- has_past_key == has_past_value,- "past_key and past_value must be both present or both absent");+// Pad the last dimension of an additive float mask up to total_kv with -inf (opset-24 allows the+// attention mask's last dimension to be shorter than the total sequence length). Requires a static+// mask rank; returns the mask unchanged when the rank is dynamic.+ov::Output<ov::Node> pad_attn_mask_last_dim(const ov::Output<ov::Node>& mask, const ov::Output<ov::Node>& K) {+ const auto rank = mask.get_partial_shape().rank();+ if (rank.is_dynamic()) {+ return mask;+ }+ const auto r = static_cast<size_t>(rank.get_length());- // Attributes- bool is_causal = static_cast<bool>(node.get_attribute_value<int64_t>("is_causal", 0));- float scale_attr = node.get_attribute_value<float>("scale", 0.0f);- float softcap = node.get_attribute_value<float>("softcap", 0.0f);- int64_t qk_matmul_output_mode = node.get_attribute_value<int64_t>("qk_matmul_output_mode", 0);- int64_t q_num_heads = node.get_attribute_value<int64_t>("q_num_heads", 0);- int64_t kv_num_heads = node.get_attribute_value<int64_t>("kv_num_heads", 0);+ auto mask_shape = std::make_shared<v3::ShapeOf>(mask);+ auto k_shape = std::make_shared<v3::ShapeOf>(K);+ auto cur_last = get_dimensions(mask_shape, {static_cast<int>(r) - 1}); // (1,)+ auto total_kv = get_dimensions(k_shape, {2}); // (1,)- CHECK_VALID_NODE(node, softcap >= 0.0f, "softcap must be non-negative, got: ", softcap);- CHECK_VALID_NODE(node,- qk_matmul_output_mode >= 0 && qk_matmul_output_mode <= 3,- "qk_matmul_output_mode must be 0, 1, 2, or 3, got: ",- qk_matmul_output_mode);+ auto pad_amount = std::make_shared<v1::Subtract>(total_kv, cur_last); // (1,)- // Determine number of requested outputs- size_t num_outputs = node.get_outputs_size();- const auto& output_names = node.get_output_names();- bool needs_qk_output = output_names.size() > 3 && !output_names[3].get().empty();+ auto pads_begin = v0::Constant::create(ov::element::i64, ov::Shape{r}, std::vector<int64_t>(r, 0));+ auto zeros_head = v0::Constant::create(ov::element::i64, ov::Shape{r - 1}, std::vector<int64_t>(r - 1, 0));+ auto pads_end = std::make_shared<v0::Concat>(ov::OutputVector{zeros_head, pad_amount}, 0); // (r,)- // Determine if inputs are 3D and need reshaping- auto q_rank = Q.get_partial_shape().rank();- auto k_rank = K.get_partial_shape().rank();- auto v_rank = V.get_partial_shape().rank();+ auto pad_value_f32 = v0::Constant::create(ov::element::f32, ov::Shape{}, {NEG_INF});+ auto pad_value = std::make_shared<v1::ConvertLike>(pad_value_f32, mask);+ return std::make_shared<v12::Pad>(mask, pads_begin, pads_end, pad_value, ov::op::PadMode::CONSTANT);+}++// Result of the shared Attention prologue.+struct PreparedQKV {+ ov::Output<ov::Node> Q;+ ov::Output<ov::Node> K;+ ov::Output<ov::Node> V;+ ov::Output<ov::Node> present_key;+ ov::Output<ov::Node> present_value;bool q_is_3d = false;+};++// Shared prologue for ONNX Attention opset-23/-24: validates input ranks, reshapes 3D inputs to 4D,+// concatenates the KV cache along the sequence axis, captures present_key/present_value (before head+// expansion) and expands K/V heads for grouped-query attention. This logic is identical across the+// two opset versions; only the mask construction and attention core differ.+PreparedQKV prepare_qkv(const ov::frontend::onnx::Node& node,+ const ov::OutputVector& inputs,+ bool has_past_key,+ int64_t q_num_heads,+ int64_t kv_num_heads) {+ PreparedQKV out;+ out.Q = inputs[0];+ out.K = inputs[1];+ out.V = inputs[2];++ auto q_rank = out.Q.get_partial_shape().rank();+ auto k_rank = out.K.get_partial_shape().rank();+ auto v_rank = out.V.get_partial_shape().rank();bool kv_is_3d = false;if (q_rank.is_static()) {- q_is_3d = (q_rank.get_length() == 3);+ out.q_is_3d = (q_rank.get_length() == 3);CHECK_VALID_NODE(node,- q_is_3d || q_rank.get_length() == 4,+ out.q_is_3d || q_rank.get_length() == 4,"Q input rank must be 3 or 4, got: ",q_rank.get_length());}@@ -133,29 +165,27 @@ ov::OutputVector attention(const ov::frontend::onnx::Node& node) {v_rank.get_length());}- // Reshape 3D inputs to 4D- if (q_is_3d) {+ if (out.q_is_3d) {CHECK_VALID_NODE(node, q_num_heads > 0, "q_num_heads attribute is required for 3D Q input");- Q = detail::reshape_3d_to_4d(Q, q_num_heads);+ out.Q = reshape_3d_to_4d(out.Q, q_num_heads);}if (kv_is_3d) {CHECK_VALID_NODE(node, kv_num_heads > 0, "kv_num_heads attribute is required for 3D K/V inputs");- K = detail::reshape_3d_to_4d(K, kv_num_heads);- V = detail::reshape_3d_to_4d(V, kv_num_heads);+ out.K = reshape_3d_to_4d(out.K, kv_num_heads);+ out.V = reshape_3d_to_4d(out.V, kv_num_heads);}- // Handle KV cache: concatenate past K/V with current K/V along sequence dim (axis=2)+ // KV cache: concatenate past K/V with current K/V along the sequence dim (axis=2).if (has_past_key) {- K = std::make_shared<v0::Concat>(ov::OutputVector{inputs[4], K}, 2);- V = std::make_shared<v0::Concat>(ov::OutputVector{inputs[5], V}, 2);+ out.K = std::make_shared<v0::Concat>(ov::OutputVector{inputs[4], out.K}, 2);+ out.V = std::make_shared<v0::Concat>(ov::OutputVector{inputs[5], out.V}, 2);}- // present_key and present_value are the K and V after concatenation (before head expansion)- auto present_key = K;- auto present_value = V;+ // present_key/present_value are K/V after concatenation, before head expansion.+ out.present_key = out.K;+ out.present_value = out.V;- // Handle GQA: expand K/V heads to match Q heads- // Case 1: head counts from explicit attributes (3D inputs)+ // GQA head expansion.if (q_num_heads > 0 && kv_num_heads > 0 && q_num_heads != kv_num_heads) {CHECK_VALID_NODE(node,q_num_heads % kv_num_heads == 0,@@ -164,13 +194,11 @@ ov::OutputVector attention(const ov::frontend::onnx::Node& node) {", kv_num_heads=",kv_num_heads);int64_t n_rep = q_num_heads / kv_num_heads;- K = detail::repeat_kv(K, n_rep);- V = detail::repeat_kv(V, n_rep);- }- // Case 2: head counts from shapes (4D inputs without attributes)- else {- auto q_pshape = Q.get_partial_shape();- auto k_pshape = K.get_partial_shape();+ out.K = repeat_kv(out.K, n_rep);+ out.V = repeat_kv(out.V, n_rep);+ } else {+ auto q_pshape = out.Q.get_partial_shape();+ auto k_pshape = out.K.get_partial_shape();if (q_pshape.rank().is_static() && q_pshape.rank().get_length() == 4 && k_pshape.rank().is_static() &&k_pshape.rank().get_length() == 4 && q_pshape[1].is_static() && k_pshape[1].is_static()) {auto q_heads = q_pshape[1].get_length();@@ -183,30 +211,117 @@ ov::OutputVector attention(const ov::frontend::onnx::Node& node) {", kv_heads=",kv_heads);int64_t n_rep = static_cast<int64_t>(q_heads / kv_heads);- K = detail::repeat_kv(K, n_rep);- V = detail::repeat_kv(V, n_rep);+ out.K = repeat_kv(out.K, n_rep);+ out.V = repeat_kv(out.V, n_rep);}}}- // Prepare attention mask+ return out;+}++} // namespace+} // namespace detail++namespace detail {++static ov::OutputVector attention_common(const ov::frontend::onnx::Node& node, bool is_opset24) {+ auto inputs = node.get_ov_inputs();+ const auto num_inputs = inputs.size();+ CHECK_VALID_NODE(node, num_inputs >= 3, "Attention expects at least 3 inputs, got: ", num_inputs);++ auto Q = inputs[0];+ auto K = inputs[1];+ auto V = inputs[2];++ bool has_attn_mask = common::is_input_valid(node, 3);+ bool has_past_key = common::is_input_valid(node, 4);+ bool has_past_value = common::is_input_valid(node, 5);+ bool has_nonpad = is_opset24 && common::is_input_valid(node, 6);++ CHECK_VALID_NODE(node,+ has_past_key == has_past_value,+ "past_key and past_value must be both present or both absent");+ if (is_opset24)+ CHECK_VALID_NODE(node,+ !(has_nonpad && (has_past_key || has_past_value)),+ "nonpad_kv_seqlen is mutually exclusive with past_key/past_value");++ bool is_causal = static_cast<bool>(node.get_attribute_value<int64_t>("is_causal", 0));+ float scale_attr = node.get_attribute_value<float>("scale", 0.0f);+ float softcap = node.get_attribute_value<float>("softcap", 0.0f);+ int64_t qk_matmul_output_mode = node.get_attribute_value<int64_t>("qk_matmul_output_mode", 0);+ int64_t q_num_heads = node.get_attribute_value<int64_t>("q_num_heads", 0);+ int64_t kv_num_heads = node.get_attribute_value<int64_t>("kv_num_heads", 0);++ CHECK_VALID_NODE(node, softcap >= 0.0f, "softcap must be non-negative, got: ", softcap);+ CHECK_VALID_NODE(node,+ qk_matmul_output_mode >= 0 && qk_matmul_output_mode <= 3,+ "qk_matmul_output_mode must be 0, 1, 2, or 3, got: ",+ qk_matmul_output_mode);++ size_t num_outputs = node.get_outputs_size();+ const auto& output_names = node.get_output_names();+ if (num_outputs > 1) {+ bool has_present_key = !output_names[1].get().empty();+ bool has_present_value = num_outputs > 2 && !output_names[2].get().empty();+ CHECK_VALID_NODE(node,+ has_present_key == has_present_value,+ "present_key and present_value must be both present or both absent");+ }+ bool needs_qk_output = output_names.size() > 3 && !output_names[3].get().empty();+ if (!needs_qk_output)+ qk_matmul_output_mode = -1;++ auto prepared = detail::prepare_qkv(node, inputs, has_past_key, q_num_heads, kv_num_heads);+ Q = prepared.Q;+ K = prepared.K;+ V = prepared.V;+ auto present_key = prepared.present_key;+ auto present_value = prepared.present_value;+ bool q_is_3d = prepared.q_is_3d;++ const auto& compute_type = Q.get_element_type();+ CHECK_VALID_NODE(node, compute_type != ov::element::dynamic, "Q input type must be static, got: ", compute_type);++ // Build the additive attention mask (-inf for disallowed positions).ov::Output<ov::Node> attn_mask;if (has_attn_mask) {attn_mask = inputs[3];+ CHECK_VALID_NODE(+ node,+ attn_mask.get_element_type() == ov::element::boolean || attn_mask.get_element_type() == compute_type,+ "Attention mask must be boolean or match Q/K/V type (",+ compute_type,+ "), got: ",+ attn_mask.get_element_type());if (attn_mask.get_element_type() == ov::element::boolean) {- // For manual path, convert boolean to float; for SDPA path, SDPA handles boolean natively- if (softcap > 0.0f || needs_qk_output) {- attn_mask = convert_boolean_mask(attn_mask, Q.get_element_type());- }+ // opset-24 always converts; opset-23 only when the manual path will be taken.+ bool must_convert = is_opset24 || softcap > 0.0f || qk_matmul_output_mode >= 0 || is_causal;+ if (must_convert)+ attn_mask = convert_boolean_mask(attn_mask, compute_type);}+ if (is_opset24) // opset-24 pads mask last dim to total seq_kv length+ attn_mask = pad_attn_mask_last_dim(attn_mask, K);+ } else {+ auto zero_f32 = v0::Constant::create(ov::element::f32, ov::Shape{}, {0.0f});+ attn_mask = std::make_shared<v1::ConvertLike>(zero_f32, Q);}- // Build an explicit causal mask instead of relying on SDPA's internal is_causal flag.- // SDPA's internal mask uses offset-based semantics (ncausal = kv_len - q_len + m + 1)- // which doesn't match the ONNX spec's np.tril(k=0) for non-square attention matrices- // (seq_q != seq_kv). For KV cache scenarios, use offset to account for past sequence.+ ov::Output<ov::Node> nonpad;+ if (has_nonpad)+ nonpad = inputs[6];++ // Build an explicit causal mask rather than relying on the SDPA op's is_causal flag, because+ // the flag is implemented inconsistently across backends (CPU: bottom-right offset, GPU: top-left offset).+ // An explicit additive mask gives identical results on every backend. offset = past_sequence_length when a KV cache+ // is present (bottom-right alignment per the ONNX Attention spec, confirmed by onnx/onnx#8068).if (is_causal) {- auto causal_mask = build_causal_mask(Q, K, has_past_key);+ // opset-24 supports NONPAD causal alignment.+ CausalKind kind = has_past_key ? CausalKind::PAST+ : (is_opset24 && has_nonpad) ? CausalKind::NONPAD+ : CausalKind::NONE;+ auto causal_mask = build_causal_mask(Q, K, kind, NEG_INF, nonpad);if (has_attn_mask) {attn_mask = std::make_shared<v1::Add>(attn_mask, causal_mask);} else {@@ -216,70 +331,72 @@ ov::OutputVector attention(const ov::frontend::onnx::Node& node) {is_causal = false;}- // Choose execution path+ if (has_nonpad) {+ auto padding_mask = build_padding_mask(K, nonpad);+ if (has_attn_mask) {+ attn_mask = std::make_shared<v1::Add>(attn_mask, padding_mask);+ } else {+ attn_mask = padding_mask;+ }+ has_attn_mask = true;+ }+ov::Output<ov::Node> Y;ov::Output<ov::Node> qk_debug_output;- if (softcap > 0.0f || needs_qk_output) {- // Manual decomposition path (softcap or debug output)- auto results = build_manual_attention(Q,- K,- V,- has_attn_mask,- attn_mask,- scale_attr,- softcap,- is_causal,- qk_matmul_output_mode,- needs_qk_output);+ // opset-24 forces the manual path when nonpad_kv_seqlen is present.+ if (softcap > 0.0f || qk_matmul_output_mode >= 0 || has_nonpad) {+ auto results = build_manual_attention(Q, K, V, attn_mask, scale_attr, softcap, qk_matmul_output_mode);Y = results[0];- if (needs_qk_output && results.size() > 1 && results[1].get_node()) {+ if (results[1].get_node())qk_debug_output = results[1];- }} else {- // SDPA path (primary fast path)- Y = build_sdpa(Q, K, V, has_attn_mask, attn_mask, scale_attr, is_causal);- }-- // Reshape output back to 3D if Q was 3D- if (q_is_3d) {- Y = detail::reshape_4d_to_3d(Y);- }-- // Build output vector.- // Output names from the ONNX graph determine which outputs are actually requested.- // Empty names indicate unused optional outputs — push NullNode for those to avoid- // creating shared input/output parameters that confuse port resolution.- ov::OutputVector results;- results.push_back(Y);-- if (num_outputs > 1) {- if (!output_names[1].get().empty()) {- results.push_back(present_key);- } else {- results.push_back(std::make_shared<NullNode>()->output(0));+ ov::OutputVector inputs{Q, K, V, attn_mask};+ if (scale_attr != 0.0f) {+ auto scale_f32 = v0::Constant::create(ov::element::f32, ov::Shape{}, {scale_attr});+ inputs.push_back(std::make_shared<v1::ConvertLike>(scale_f32, Q));}- }- if (num_outputs > 2) {- if (!output_names[2].get().empty()) {- results.push_back(present_value);- } else {- results.push_back(std::make_shared<NullNode>()->output(0));- }- }- if (num_outputs > 3) {- if (qk_debug_output.get_node() && !output_names[3].get().empty()) {- results.push_back(qk_debug_output);- } else {- results.push_back(std::make_shared<NullNode>()->output(0));+ Y = std::make_shared<v13::ScaledDotProductAttention>(inputs, is_causal)->output(0);+ if (has_attn_mask) {+ // Fully-masked rows yield NaN after softmax inside SDPA; replace with zeros.+ auto zero_f32 = v0::Constant::create(ov::element::f32, ov::Shape{}, {0.0f});+ auto zero = std::make_shared<v1::ConvertLike>(zero_f32, Y);+ auto is_nan = std::make_shared<v10::IsNaN>(Y);+ Y = std::make_shared<v1::Select>(is_nan, zero, Y);}}+ if (q_is_3d)+ Y = reshape_4d_to_3d(Y);++ ov::OutputVector results{Y};+ if (num_outputs > 1)+ results.push_back(!output_names[1].get().empty() ? present_key : std::make_shared<NullNode>()->output(0));+ if (num_outputs > 2)+ results.push_back(!output_names[2].get().empty() ? present_value : std::make_shared<NullNode>()->output(0));+ if (num_outputs > 3)+ results.push_back((qk_debug_output.get_node() && !output_names[3].get().empty())+ ? qk_debug_output+ : std::make_shared<NullNode>()->output(0));return results;}-ONNX_OP("Attention", OPSET_SINCE(1), ai_onnx::opset_23::attention);++} // namespace detail++namespace opset_23 {+ov::OutputVector attention(const ov::frontend::onnx::Node& node) {+ return detail::attention_common(node, /*is_opset24=*/false);+}+ONNX_OP("Attention", OPSET_RANGE(1, 23), ai_onnx::opset_23::attention);} // namespace opset_23+namespace opset_24 {+ov::OutputVector attention(const ov::frontend::onnx::Node& node) {+ return detail::attention_common(node, /*is_opset24=*/true);+}+ONNX_OP("Attention", OPSET_SINCE(24), ai_onnx::opset_24::attention);+} // namespace opset_24+} // namespace ai_onnx} // namespace onnx} // namespace frontenddiff --git a/src/frontends/onnx/frontend/src/op/com.microsoft/multi_head_attention.cpp b/src/frontends/onnx/frontend/src/op/com.microsoft/multi_head_attention.cppindex ee4dcf9c24e..f2c94e65fb8 100644--- a/src/frontends/onnx/frontend/src/op/com.microsoft/multi_head_attention.cpp+++ b/src/frontends/onnx/frontend/src/op/com.microsoft/multi_head_attention.cpp@@ -13,11 +13,13 @@#include "openvino/op/concat.hpp"#include "openvino/op/constant.hpp"#include "openvino/op/convert.hpp"+#include "openvino/op/convert_like.hpp"#include "openvino/op/gather_elements.hpp"#include "openvino/op/greater.hpp"#include "openvino/op/multiply.hpp"#include "openvino/op/range.hpp"#include "openvino/op/reshape.hpp"+#include "openvino/op/scaled_dot_product_attention.hpp"#include "openvino/op/scatter_update.hpp"#include "openvino/op/shape_of.hpp"#include "openvino/op/slice.hpp"@@ -39,26 +41,6 @@ namespace com_microsoft {namespace detail {namespace {-// Reshape 3D input (batch, seq, num_heads * head_size) to 4D (batch, num_heads, seq, head_size)-ov::Output<ov::Node> reshape_3d_to_4d(const ov::Output<ov::Node>& input, int64_t num_heads) {- // Reshape to (batch, seq, num_heads, head_size)- auto reshape_pattern = v0::Constant::create<int64_t>(ov::element::i64, ov::Shape{4}, {0, 0, num_heads, -1});- auto reshaped = std::make_shared<v1::Reshape>(input, reshape_pattern, true);- // Transpose to (batch, num_heads, seq, head_size)- auto perm = v0::Constant::create(ov::element::i64, ov::Shape{4}, {0, 2, 1, 3});- return std::make_shared<v1::Transpose>(reshaped, perm);-}--// Reshape 4D output (batch, num_heads, seq, head_size) back to 3D (batch, seq, num_heads * head_size)-ov::Output<ov::Node> reshape_4d_to_3d(const ov::Output<ov::Node>& output) {- // Transpose from (batch, num_heads, seq, head_size) to (batch, seq, num_heads, head_size)- auto perm = v0::Constant::create(ov::element::i64, ov::Shape{4}, {0, 2, 1, 3});- auto transposed = std::make_shared<v1::Transpose>(output, perm);- // Reshape to (batch, seq, num_heads * head_size)- auto reshape_pattern = v0::Constant::create(ov::element::i64, ov::Shape{3}, {0, 0, -1});- return std::make_shared<v1::Reshape>(transposed, reshape_pattern, true);-}-// Split bias into Q, K, V parts and reshape each to (1, num_heads, 1, head_size) for broadcasting.OutputVector split_bias(const Output<ov::Node>& bias,const Output<ov::Node>& Q,@@ -300,7 +282,6 @@ ov::OutputVector multi_head_attention(const ov::frontend::onnx::Node& node) {const auto num_inputs = inputs.size();CHECK_VALID_NODE(node, num_inputs >= 1, "MultiHeadAttention expects at least 1 input, got: ", num_inputs);- // Attributesint64_t num_heads = node.get_attribute_value<int64_t>("num_heads");float mask_filter_value = node.get_attribute_value<float>("mask_filter_value", -10000.0f);bool unidirectional = static_cast<bool>(node.get_attribute_value<int64_t>("unidirectional", 0));@@ -342,7 +323,6 @@ ov::OutputVector multi_head_attention(const ov::frontend::onnx::Node& node) {V = std::make_shared<v1::Add>(V, bias_splits[2]);}- // Handle KV cacheov::Output<ov::Node> present_key = K;ov::Output<ov::Node> present_value = V;if (has_past_key) {@@ -353,7 +333,6 @@ ov::OutputVector multi_head_attention(const ov::frontend::onnx::Node& node) {present_value = kv_cache_result[3];}- // Prepare attention maskov::Output<ov::Node> attn_mask;if (has_key_padding_mask) {attn_mask = inputs[4];@@ -361,14 +340,19 @@ ov::OutputVector multi_head_attention(const ov::frontend::onnx::Node& node) {CHECK_VALID_NODE(node, attn_rank.is_static(), "Attention rank must be static, got rank: ", attn_rank);attn_mask = detail::build_mask(attn_mask, Q, K, mask_filter_value);+ } else {+ auto zero_f32 = v0::Constant::create(ov::element::f32, ov::Shape{}, {0.0f});+ attn_mask = std::make_shared<v1::ConvertLike>(zero_f32, Q);}- // Build an explicit unidirectional mask instead of relying on SDPA's internal is_causal flag.- // SDPA's internal mask uses offset-based semantics (ncausal = kv_len - q_len + m + 1)- // which doesn't match the ONNX spec's np.tril(k=0) for non-square attention matrices- // (seq_q != seq_kv). For KV cache scenarios, use offset to account for past sequence.+ // Build an explicit unidirectional mask rather than using the SDPA op's is_causal flag, because the flag+ // is implemented inconsistently across backends (CPU: bottom-right offset, GPU: top-left).+ // An explicit additive mask gives identical results on every backend. The mask uses+ // offset = past_sequence_length when a KV cache is present and 0 otherwise — the bottom-right+ // alignment according to the ONNX Attention spec (confirmed by onnx/onnx#8068).if (unidirectional) {- auto unidirectional_mask = build_causal_mask(Q, K, has_past_key);+ auto kind = has_past_key ? CausalKind::PAST : CausalKind::NONE;+ auto unidirectional_mask = build_causal_mask(Q, K, kind, mask_filter_value);if (has_key_padding_mask) {attn_mask = std::make_shared<v1::Add>(attn_mask, unidirectional_mask);} else {@@ -392,42 +376,42 @@ ov::OutputVector multi_head_attention(const ov::frontend::onnx::Node& node) {has_key_padding_mask = true;}- // Choose execution pathov::Output<ov::Node> Y;ov::Output<ov::Node> qk_debug_output;- // Determine number of requested outputssize_t num_outputs = node.get_outputs_size();const auto& output_names = node.get_output_names();bool needs_qk_output = output_names.size() > 3 && !output_names[3].get().empty();if (needs_qk_output) {- // Manual decomposition path (softcap or debug output)+ // Manual decomposition path. Use ONNX Runtime MHA semantics: no fully-masked-row guard+ // (masked positions carry a finite mask_filter_value, so softmax stays finite).auto results = build_manual_attention(Q,K,V,- has_key_padding_mask,attn_mask,scale_attr,0.0f /*softcap*/,- false,- 0,- true);+ 0 /*qk_matmul_output_mode*/,+ false /*include_safe_softmax*/);Y = results[0];qk_debug_output = results[1];} else {- // SDPA path (primary fast path)- Y = build_sdpa(Q, K, V, has_key_padding_mask, attn_mask, scale_attr, false);+ ov::OutputVector inputs{Q, K, V, attn_mask};+ if (scale_attr != 0.0f) {+ auto scale_f32 = v0::Constant::create(ov::element::f32, ov::Shape{}, {scale_attr});+ inputs.push_back(std::make_shared<v1::ConvertLike>(scale_f32, Q));+ }++ Y = std::make_shared<v13::ScaledDotProductAttention>(inputs, false)->output(0);}- Y = detail::reshape_4d_to_3d(Y);+ Y = reshape_4d_to_3d(Y);- // Build output vector.// Output names from the ONNX graph determine which outputs are actually requested.// Empty names indicate unused optional outputs — push NullNode for those to avoid// creating shared input/output parameters that confuse port resolution.- ov::OutputVector results;- results.push_back(Y);+ ov::OutputVector results{Y};if (num_outputs > 1) {if (!output_names[1].get().empty()) {diff --git a/src/frontends/onnx/frontend/src/utils/attention.cpp b/src/frontends/onnx/frontend/src/utils/attention.cppindex 419d964d58b..3f2f1d84292 100644--- a/src/frontends/onnx/frontend/src/utils/attention.cpp+++ b/src/frontends/onnx/frontend/src/utils/attention.cpp@@ -4,15 +4,22 @@#include "utils/attention.hpp"+#include <limits>+#include "openvino/op/add.hpp"+#include "openvino/op/concat.hpp"#include "openvino/op/constant.hpp"#include "openvino/op/convert.hpp"+#include "openvino/op/convert_like.hpp"#include "openvino/op/divide.hpp"#include "openvino/op/gather.hpp"#include "openvino/op/greater_eq.hpp"+#include "openvino/op/is_nan.hpp"+#include "openvino/op/less_eq.hpp"#include "openvino/op/matmul.hpp"#include "openvino/op/multiply.hpp"#include "openvino/op/range.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"@@ -21,6 +28,7 @@#include "openvino/op/squeeze.hpp"#include "openvino/op/subtract.hpp"#include "openvino/op/tanh.hpp"+#include "openvino/op/transpose.hpp"#include "openvino/op/unsqueeze.hpp"using namespace ov::op;@@ -40,26 +48,45 @@ std::shared_ptr<ov::Node> get_dimensions(const std::shared_ptr<ov::Node>& node,return get_dimensions(std::make_shared<v3::ShapeOf>(node), dims);}-// Convert boolean mask to float additive mask: true -> 0.0, false -> -10000.0+// Reshape 3D input (batch, seq, num_heads * head_size) to 4D (batch, num_heads, seq, head_size).+ov::Output<ov::Node> reshape_3d_to_4d(const ov::Output<ov::Node>& input, int64_t num_heads) {+ auto reshape_pattern =+ v0::Constant::create(ov::element::i64, ov::Shape{4}, std::vector<int64_t>{0, 0, num_heads, -1});+ auto reshaped = std::make_shared<v1::Reshape>(input, reshape_pattern, true);+ auto perm = v0::Constant::create(ov::element::i64, ov::Shape{4}, {0, 2, 1, 3});+ return std::make_shared<v1::Transpose>(reshaped, perm);+}++// Reshape 4D output (batch, num_heads, seq, head_size) back to 3D (batch, seq, num_heads * head_size).+ov::Output<ov::Node> reshape_4d_to_3d(const ov::Output<ov::Node>& output) {+ auto perm = v0::Constant::create(ov::element::i64, ov::Shape{4}, {0, 2, 1, 3});+ auto transposed = std::make_shared<v1::Transpose>(output, perm);+ auto reshape_pattern = v0::Constant::create(ov::element::i64, ov::Shape{3}, {0, 0, -1});+ return std::make_shared<v1::Reshape>(transposed, reshape_pattern, true);+}++// Convert boolean mask to float additive mask: true -> 0.0, false -> mask_filter_value (default -inf).ov::Output<ov::Node> convert_boolean_mask(const ov::Output<ov::Node>& mask,const ov::element::Type& type,float mask_filter_value) {auto zero = v0::Constant::create(type, ov::Shape{}, {0.0f});- auto neg_large = v0::Constant::create(type, ov::Shape{}, {mask_filter_value});- return std::make_shared<v1::Select>(mask, zero, neg_large);+ auto neg_large = v0::Constant::create(ov::element::f32, ov::Shape{}, {mask_filter_value});+ auto conv_neg_large = std::make_shared<v1::ConvertLike>(neg_large, zero);+ return std::make_shared<v1::Select>(mask, zero, conv_neg_large);}-// Build additive causal mask of shape (seq_q, seq_kv): 0 for allowed, -10000 for masked.-// When use_offset=true, accounts for KV cache offset so that query position i attends to-// key positions j where j <= i + (seq_kv - seq_q). Use this for KV cache scenarios.-// When use_offset=false, builds a simple lower-triangular mask matching np.tril(k=0),-// where query position i attends to key positions j where j <= i.-ov::Output<ov::Node> build_causal_mask(const ov::Output<ov::Node>& Q, const ov::Output<ov::Node>& K, bool use_offset) {+// Build an additive causal mask with opset-24 bottom-right alignment. For CausalKind::NONPAD the offset+// varies per batch and the result has shape (B, 1, seq_q, seq_kv); otherwise the result is (seq_q, seq_kv)+// and broadcasts over batch and heads.+ov::Output<ov::Node> build_causal_mask(const ov::Output<ov::Node>& Q,+ const ov::Output<ov::Node>& K,+ CausalKind kind,+ float mask_filter_value,+ const ov::Output<ov::Node>& nonpad) {auto q_shape = std::make_shared<v3::ShapeOf>(Q);auto k_shape = std::make_shared<v3::ShapeOf>(K);- // Q is 4D: (B, heads, seq_q, head_size), K is 4D: (B, heads, seq_kv, head_size)- auto seq_q = get_dimensions(q_shape, {2});- auto seq_kv = get_dimensions(k_shape, {2});+ auto seq_q = get_dimensions(q_shape, {2}); // (1,)+ auto seq_kv = get_dimensions(k_shape, {2}); // (1,)auto zero = v0::Constant::create(ov::element::i64, ov::Shape{}, {0});auto one = v0::Constant::create(ov::element::i64, ov::Shape{}, {1});@@ -67,134 +94,117 @@ ov::Output<ov::Node> build_causal_mask(const ov::Output<ov::Node>& Q, const ov::auto seq_q_scalar = std::make_shared<v0::Squeeze>(seq_q, zero);auto seq_kv_scalar = std::make_shared<v0::Squeeze>(seq_kv, zero);- // Column indices: [0, 1, ..., seq_kv-1]- auto col_indices = std::make_shared<v4::Range>(zero, seq_kv_scalar, one, ov::element::i64);-- std::shared_ptr<ov::Node> row_indices;- if (use_offset) {- // Row indices adjusted for KV cache offset: [offset, offset+1, ..., offset+seq_q-1]- auto offset = std::make_shared<v1::Subtract>(seq_kv_scalar, seq_q_scalar);- auto end = std::make_shared<v1::Add>(offset, seq_q_scalar);- row_indices = std::make_shared<v4::Range>(offset, end, one, ov::element::i64);+ auto col = std::make_shared<v4::Range>(zero, seq_kv_scalar, one, ov::element::i64); // (seq_kv,)+ auto row = std::make_shared<v4::Range>(zero, seq_q_scalar, one, ov::element::i64); // (seq_q,)++ // diff[i, j] = col[j] - row[i] -> (seq_q, seq_kv)+ auto axis1 = v0::Constant::create(ov::element::i64, ov::Shape{1}, {1});+ auto row_2d = std::make_shared<v0::Unsqueeze>(row, axis1); // (seq_q, 1)+ auto diff = std::make_shared<v1::Subtract>(col, row_2d); // (seq_q, seq_kv)++ std::shared_ptr<ov::Node> allowed;+ if (kind == CausalKind::NONPAD) {+ // offset_b = nonpad[b] - seq_q ; allowed[b, i, j] = diff[i, j] <= offset_b+ auto offset = std::make_shared<v1::Subtract>(nonpad, seq_q); // (B,)+ auto offset_shape = v0::Constant::create(ov::element::i64, ov::Shape{3}, {-1, 1, 1});+ auto offset_3d = std::make_shared<v1::Reshape>(offset, offset_shape, false); // (B, 1, 1)+ auto axis0 = v0::Constant::create(ov::element::i64, ov::Shape{1}, {0});+ auto diff_3d = std::make_shared<v0::Unsqueeze>(diff, axis0); // (1, seq_q, seq_kv)+ auto allowed_3d = std::make_shared<v1::LessEqual>(diff_3d, offset_3d); // (B, seq_q, seq_kv)+ allowed = std::make_shared<v0::Unsqueeze>(allowed_3d, axis1); // (B, 1, seq_q, seq_kv)+ } else if (kind == CausalKind::PAST) {+ auto offset = std::make_shared<v1::Subtract>(seq_kv_scalar, seq_q_scalar); // scalar+ allowed = std::make_shared<v1::LessEqual>(diff, offset);} else {- // Row indices without offset: [0, 1, ..., seq_q-1] (matches np.tril(k=0))- row_indices = std::make_shared<v4::Range>(zero, seq_q_scalar, one, ov::element::i64);+ allowed = std::make_shared<v1::LessEqual>(diff, zero);}- // Unsqueeze rows to (seq_q, 1) for broadcasting with (seq_kv,)- auto axis = v0::Constant::create(ov::element::i64, ov::Shape{1}, {1});- auto rows_2d = std::make_shared<v0::Unsqueeze>(row_indices, axis);-- // Lower-triangular: position (i, j) allowed when adjusted_row[i] >= col[j]- auto is_allowed = std::make_shared<v1::GreaterEqual>(rows_2d, col_indices);-- // Convert boolean to additive float mask: true -> 0.0, false -> -10000.0- return convert_boolean_mask(is_allowed, Q.get_element_type());-}--// Build SDPA-based attention (primary fast path)-ov::Output<ov::Node> build_sdpa(const ov::Output<ov::Node>& Q,- const ov::Output<ov::Node>& K,- const ov::Output<ov::Node>& V,- bool has_mask,- const ov::Output<ov::Node>& attn_mask,- float scale_attr,- bool is_causal) {- ov::OutputVector inputs{Q, K, V};- if (has_mask) {- inputs.push_back(attn_mask);- }- if (scale_attr != 0.0f) {- if (!has_mask) {- // SDPA interprets inputs positionally (index 3 = mask, index 4 = scale),- // so a zero mask placeholder is needed when only scale is provided- inputs.push_back(v0::Constant::create(Q.get_element_type(), ov::Shape{}, {0.0f}));- }- inputs.push_back(v0::Constant::create(Q.get_element_type(), ov::Shape{}, {scale_attr}));- }- return std::make_shared<v13::ScaledDotProductAttention>(inputs, is_causal)->output(0);+ return convert_boolean_mask(allowed, Q.get_element_type(), mask_filter_value);}-// Build manual attention decomposition (for softcap or qk_matmul_output)-// Returns {Y, qk_matmul_output_or_null}+// Build manual attention decomposition following ONNX opset-24 semantics.+// The mask passed in is already merged (attention + causal + padding) using -inf for disallowed+// positions. Order of operations: scale -> softcap -> mask -> softmax. When include_safe_softmax is+// true the fully-masked-row guard is applied (opset-23/-24); MultiHeadAttention passes false.ov::OutputVector build_manual_attention(const ov::Output<ov::Node>& Q,const ov::Output<ov::Node>& K,const ov::Output<ov::Node>& V,- bool has_mask,const ov::Output<ov::Node>& attn_mask,float scale_attr,float softcap,- bool is_causal,int64_t qk_matmul_output_mode,- bool needs_qk_output) {+ bool include_safe_softmax) {// 1. Q @ K^Tauto qk = std::make_shared<v0::MatMul>(Q, K, false, true);// 2. Apply scalestd::shared_ptr<ov::Node> scaled_qk;if (scale_attr != 0.0f) {- auto scale_node = v0::Constant::create(Q.get_element_type(), ov::Shape{}, {scale_attr});+ auto scale_f32 = v0::Constant::create(ov::element::f32, ov::Shape{}, {scale_attr});+ auto scale_node = std::make_shared<v1::ConvertLike>(scale_f32, qk);scaled_qk = std::make_shared<v1::Multiply>(qk, scale_node);} else {- // Default scale: 1/sqrt(head_size). Q is always 4D here: (B, heads, seq, head_size)auto q_shape = std::make_shared<v3::ShapeOf>(Q);auto head_size = get_dimensions(q_shape, {3});- auto head_size_f = std::make_shared<v0::Convert>(head_size, Q.get_element_type());+ auto head_size_f = std::make_shared<v1::ConvertLike>(head_size, Q);auto sqrt_head = std::make_shared<v0::Sqrt>(head_size_f);scaled_qk = std::make_shared<v1::Divide>(qk, sqrt_head);}- // 3. Apply attention mask and causal mask- std::shared_ptr<ov::Node> masked = scaled_qk;- if (has_mask) {- masked = std::make_shared<v1::Add>(scaled_qk, attn_mask);- }- if (is_causal) {- auto causal_mask = build_causal_mask(Q, K, false);- masked = std::make_shared<v1::Add>(masked, causal_mask);- }-- // Capture qk_matmul_output at mode 0 (raw QK) or mode 1 (after mask)- ov::Output<ov::Node> qk_debug_output;- if (needs_qk_output && qk_matmul_output_mode == 0) {- qk_debug_output = scaled_qk->output(0);- } else if (needs_qk_output && qk_matmul_output_mode == 1) {- qk_debug_output = masked->output(0);- }-- // 4. Apply softcap: softcap * tanh(scores / softcap)- std::shared_ptr<ov::Node> capped = masked;+ // 3. Apply softcap: softcap * tanh(scores / softcap)+ std::shared_ptr<ov::Node> capped = scaled_qk;if (softcap > 0.0f) {- auto cap = v0::Constant::create(Q.get_element_type(), ov::Shape{}, {softcap});- auto divided = std::make_shared<v1::Divide>(masked, cap);+ auto cap_f32 = v0::Constant::create(ov::element::f32, ov::Shape{}, {softcap});+ auto cap = std::make_shared<v1::ConvertLike>(cap_f32, scaled_qk);+ auto divided = std::make_shared<v1::Divide>(scaled_qk, cap);auto tanh_out = std::make_shared<v0::Tanh>(divided);capped = std::make_shared<v1::Multiply>(tanh_out, cap);}- // Capture at mode 2 (after softcap)- if (needs_qk_output && qk_matmul_output_mode == 2) {- qk_debug_output = capped->output(0);- }+ // 4. Apply the (already merged) additive attention mask+ std::shared_ptr<ov::Node> masked = std::make_shared<v1::Add>(capped, attn_mask);++ // 5. Softmax with an optional fully-masked-row guard: rows whose keys are all masked out (additive+ // mask of -inf) would yield NaN after softmax; opset-24 requires a zero output row instead.+ std::shared_ptr<ov::Node> softmax_out = std::make_shared<v8::Softmax>(masked, -1);- // 5. Softmax- auto softmax_out = std::make_shared<v8::Softmax>(capped, -1);+ if (include_safe_softmax) {+ bool non_empty_attn_mask = true;+ if (auto mask_const = ov::as_type_ptr<v0::Constant>(attn_mask.get_node_shared_ptr())) {+ if (ov::shape_size(mask_const->get_shape()) == 1 && mask_const->cast_vector<float>()[0] == 0.0f)+ non_empty_attn_mask = false;+ }- // Capture at mode 3 (after softmax)- if (needs_qk_output && qk_matmul_output_mode == 3) {+ if (non_empty_attn_mask) {+ auto zero_f32 = v0::Constant::create(ov::element::f32, ov::Shape{}, {0.0f});+ auto zero = std::make_shared<v1::ConvertLike>(zero_f32, softmax_out);+ auto is_nan = std::make_shared<v10::IsNaN>(softmax_out);+ softmax_out = std::make_shared<v1::Select>(is_nan, zero, softmax_out);+ }+ }++ ov::Output<ov::Node> qk_debug_output;+ switch (qk_matmul_output_mode) {+ case 0:+ qk_debug_output = scaled_qk->output(0);+ break;+ case 1:+ qk_debug_output = capped->output(0);+ break;+ case 2:+ qk_debug_output = masked->output(0);+ break;+ case 3:qk_debug_output = softmax_out->output(0);+ break;+ default:+ break;}// 6. softmax @ Vauto output = std::make_shared<v0::MatMul>(softmax_out, V);- ov::OutputVector results;- results.push_back(output->output(0));- if (needs_qk_output && qk_debug_output.get_node()) {- results.push_back(qk_debug_output);- } else {- results.push_back(ov::Output<ov::Node>{});- }- return results;+ return {output, qk_debug_output};}} // namespace attentiondiff --git a/src/frontends/onnx/frontend/src/utils/attention.hpp b/src/frontends/onnx/frontend/src/utils/attention.hppindex 42cec237130..f3bc3a4a0f0 100644--- a/src/frontends/onnx/frontend/src/utils/attention.hpp+++ b/src/frontends/onnx/frontend/src/utils/attention.hpp@@ -3,6 +3,7 @@//#pragma once+#include <limits>#include <memory>#include <vector>@@ -25,68 +26,81 @@ std::shared_ptr<ov::Node> get_dimensions(const std::shared_ptr<ov::op::v3::Shape/// \brief Convenience overload: computes ShapeOf for the given node, then extracts dimensions.std::shared_ptr<ov::Node> get_dimensions(const std::shared_ptr<ov::Node>& node, const std::vector<int>& dims);+/// \brief Reshape a 3D tensor (batch, seq, num_heads * head_size) to 4D (batch, num_heads, seq, head_size).+///+/// \param input 3D tensor of shape (batch, seq, num_heads * head_size).+/// \param num_heads Number of attention heads.+/// \return A 4D tensor of shape (batch, num_heads, seq, head_size).+ov::Output<ov::Node> reshape_3d_to_4d(const ov::Output<ov::Node>& input, int64_t num_heads);++/// \brief Reshape a 4D tensor (batch, num_heads, seq, head_size) back to 3D (batch, seq, num_heads * head_size).+///+/// \param output 4D tensor of shape (batch, num_heads, seq, head_size).+/// \return A 3D tensor of shape (batch, seq, num_heads * head_size).+ov::Output<ov::Node> reshape_4d_to_3d(const ov::Output<ov::Node>& output);+/// \brief Convert boolean mask to float additive mask: true -> 0.0, false -> mask_filter_value.////// \param mask Boolean tensor where true means "attend" and false means "mask out"./// \param type Target floating-point element type for the output mask.-/// \param mask_filter_value Value assigned to masked (false) positions (default: -10000.0).+/// \param mask_filter_value Value assigned to masked (false) positions (default: -inf, required for+/// the fully-masked-row guard in build_manual_attention; pass a finite value+/// such as ORT's -10000 only where that guard must stay inert)./// \return A Select node producing an additive float mask of the same shape as the input.ov::Output<ov::Node> convert_boolean_mask(const ov::Output<ov::Node>& mask,const ov::element::Type& type,- float mask_filter_value = -10000.0f);+ float mask_filter_value = -std::numeric_limits<float>::infinity());-/// \brief Build additive causal mask of shape (seq_q, seq_kv): 0 for allowed, -10000 for masked.+/// \brief Alignment mode for the causal mask offset.+enum class CausalKind {+ NONE, // offset 0: query i attends key j iff j <= i+ PAST, // offset = seq_kv - seq_q (internal KV cache, bottom-right alignment)+ NONPAD, // per-batch offset = nonpad[b] - seq_q (external KV cache)+};++/// \brief Build an additive causal mask with opset-24 bottom-right alignment.+///+/// For CausalKind::NONPAD the offset varies per batch and the result has shape (B, 1, seq_q, seq_kv);+/// otherwise the result is (seq_q, seq_kv) and broadcasts over batch and heads.///-/// \param Q Query tensor of shape (B, heads, seq_q, head_size).-/// \param K Key tensor of shape (B, heads, seq_kv, head_size).-/// \param use_offset When true, adjusts row indices for KV cache offset so that query position i-/// attends to key positions j where j <= i + (seq_kv - seq_q). When false, builds-/// a simple lower-triangular mask (np.tril with k=0).+/// \param Q Query tensor of shape (B, heads, seq_q, head_size).+/// \param K Key tensor of shape (B, heads, seq_kv, head_size).+/// \param kind Offset alignment mode (NONE / PAST / NONPAD).+/// \param mask_filter_value Value assigned to masked positions (default: -inf).+/// \param nonpad Per-batch non-pad KV length (only used for CausalKind::NONPAD)./// \return A float additive mask broadcastable over the attention scores.-ov::Output<ov::Node> build_causal_mask(const ov::Output<ov::Node>& Q, const ov::Output<ov::Node>& K, bool use_offset);+ov::Output<ov::Node> build_causal_mask(const ov::Output<ov::Node>& Q,+ const ov::Output<ov::Node>& K,+ CausalKind kind = CausalKind::NONE,+ float mask_filter_value = -std::numeric_limits<float>::infinity(),+ const ov::Output<ov::Node>& nonpad = {});-/// \brief Build SDPA-based attention (primary fast path).+/// \brief Build manual attention decomposition following ONNX opset-24 semantics.///-/// \param Q Query tensor of shape (B, heads, seq_q, head_size).-/// \param K Key tensor of shape (B, heads, seq_kv, head_size).-/// \param V Value tensor of shape (B, heads, seq_kv, head_size).-/// \param has_mask Whether an attention mask is provided.-/// \param attn_mask Additive attention mask (used only when has_mask is true).-/// \param scale_attr Explicit scale factor; when 0.0 the SDPA op uses the default 1/sqrt(head_size).-/// \param is_causal When true, the SDPA op applies internal causal masking.-/// \return The output of ScaledDotProductAttention.-ov::Output<ov::Node> build_sdpa(const ov::Output<ov::Node>& Q,- const ov::Output<ov::Node>& K,- const ov::Output<ov::Node>& V,- bool has_mask,- const ov::Output<ov::Node>& attn_mask,- float scale_attr,- bool is_causal);--/// \brief Build manual attention decomposition (for softcap or qk_matmul_output).+/// The mask passed in is already merged (attention + causal + padding) using -inf for disallowed+/// positions. Order of operations: scale -> softcap -> mask -> softmax.////// \param Q Query tensor of shape (B, heads, seq_q, head_size)./// \param K Key tensor of shape (B, heads, seq_kv, head_size)./// \param V Value tensor of shape (B, heads, seq_kv, head_size).-/// \param has_mask Whether an attention mask is provided./// \param attn_mask Additive attention mask (used only when has_mask is true)./// \param scale_attr Explicit scale factor; when 0.0, uses default 1/sqrt(head_size)./// \param softcap Soft-capping value; when > 0, applies softcap * tanh(scores / softcap).-/// \param is_causal When true, adds an additive causal mask to attention scores./// \param qk_matmul_output_mode Selects at which stage the intermediate QK tensor is captured:-/// 0 = after scale, 1 = after mask, 2 = after softcap, 3 = after softmax.-/// \param needs_qk_output When true, the intermediate QK tensor is returned as the second output.+/// 0 = after scale, 1 = after softcap, 2 = after mask, 3 = after softmax.+/// \param include_safe_softmax When true (ONNX Attention opset-23/-24), applies the fully-masked-row+/// guard so a row whose keys are all masked (-inf) yields a zero output row+/// instead of NaN. Set to false for ONNX Runtime MultiHeadAttention+/// semantics (finite mask_filter_value, no zero-row guard)./// \return A two-element OutputVector: {attention_output, qk_intermediate_or_empty}.ov::OutputVector build_manual_attention(const ov::Output<ov::Node>& Q,const ov::Output<ov::Node>& K,const ov::Output<ov::Node>& V,- bool has_mask,const ov::Output<ov::Node>& attn_mask,float scale_attr,float softcap,- bool is_causal,int64_t qk_matmul_output_mode,- bool needs_qk_output);+ bool include_safe_softmax = true);} // namespace attention} // namespace onnxdiff --git a/src/frontends/onnx/tests/__init__.py b/src/frontends/onnx/tests/__init__.pyindex 052be60f804..028aa8eee09 100644--- a/src/frontends/onnx/tests/__init__.py+++ b/src/frontends/onnx/tests/__init__.py@@ -178,3 +178,10 @@ skip_issue_119896 = pytest.mark.skip(reason="Unsupported element type: FLOAT8")xfail_issue_171767 = pytest.mark.skip(reason="Unsupported element type: FLOAT4E2M1")xfail_issue_171771 = pytest.mark.skip(reason="Mismatches in tests: Top K values")xfail_issue_171772 = pytest.mark.skip(reason="Mismatches in tests: AveragePool")++# Attention op (ONNX opset 23/24) -- requires ONNX >= 1.23; CI uses ONNX 1.18.+# Tests pass locally when ONNX >= 1.23 is installed.+xfail_attention_onnx_version = pytest.mark.skip(reason="Attention op tests require ONNX >= 1.23; CI uses ONNX 1.18")++# Attention op fully-masked-row / NaN-robustness tests that do not yet pass:+xfail_attention_nan_robustness = pytest.mark.skip(reason="Attention fully-masked-row NaN robustness not yet handled in expanded/SDPA paths")diff --git a/src/frontends/onnx/tests/onnx_import.in.cpp b/src/frontends/onnx/tests/onnx_import.in.cppindex 005458aeb37..fc32cb171a7 100644--- a/src/frontends/onnx/tests/onnx_import.in.cpp+++ b/src/frontends/onnx/tests/onnx_import.in.cpp@@ -7882,9 +7882,9 @@ OPENVINO_TEST(${BACKEND_NAME}, onnx_model_attention_mha_4d) {-0.072010f, 1.003533f, 0.361636f, -0.645120f, 0.361396f, 1.538037f});test_case.add_expected_output<float>(Shape{1, 2, 4, 3},- {0.143204f, -0.312989f, 0.232224f, -0.004593f, -0.555314f, 0.383667f, 0.235821f, -0.206320f,- 0.154587f, 0.028000f, -0.570602f, 0.413158f, -0.428041f, 0.006260f, -0.832314f, -0.546679f,- 0.298202f, 0.292189f, -0.625760f, 0.324462f, 0.962753f, -0.387417f, 0.509615f, 0.017205f});+ {0.143205f, -0.312989f, 0.232224f, -0.004592f, -0.555314f, 0.383666f, 0.235821f, -0.206320f,+ 0.154587f, 0.028000f, -0.570603f, 0.413158f, -0.428041f, 0.006261f, -0.832314f, -0.546679f,+ 0.298202f, 0.292189f, -0.625760f, 0.324463f, 0.962753f, -0.387417f, 0.509615f, 0.017205f});test_case.run_with_tolerance_as_fp(1e-4f);}@@ -7908,9 +7908,9 @@ OPENVINO_TEST(${BACKEND_NAME}, onnx_model_attention_mha_3d) {0.813517f, -1.230864f, 0.227460f, 1.307143f, -1.607483f, 0.184634f});test_case.add_expected_output<float>(Shape{1, 4, 6},- {-0.376205f, -1.164383f, 0.494832f, 1.251880f, -1.010314f, -0.134396f, -0.433258f, -0.718601f,- 0.898995f, 0.979683f, -0.832299f, -0.209895f, -1.080272f, 0.093997f, 1.487117f, 0.203439f,- -0.572602f, -0.311992f, -0.340959f, -1.273095f, 0.406927f, -0.541346f, 0.026989f, -0.646756f});+ {-0.816504f, 0.238808f, -0.665579f, -0.060809f, -0.843913f, 0.576091f, -0.524377f, -0.428967f,+ 0.031840f, -0.012819f, -1.422445f, 0.157862f, -0.073136f, -0.735764f, 0.342599f, 0.410357f,+ -0.630925f, 0.507768f, -0.197636f, -0.370013f, 0.007059f, -0.711657f, -0.161920f, 1.430161f});test_case.run_with_tolerance_as_fp(1e-4f);}@@ -7938,10 +7938,10 @@ OPENVINO_TEST(${BACKEND_NAME}, onnx_model_attention_gqa_4d) {test_case.add_expected_output<float>(Shape{1, 4, 4, 3},{0.357977f, 0.265504f, -1.042098f, 0.420300f, 0.040855f, -0.967495f, 0.294989f, 0.216078f,- -1.011940f, 0.274893f, 0.215012f, -1.007991f, 1.105739f, 0.072415f, -0.710253f, 0.288786f,- 0.032542f, -0.470010f, 0.351593f, 0.006968f, -0.509201f, 0.309487f, 0.065849f, -0.691483f,- 0.049388f, 0.099175f, -0.919799f, 0.268812f, 0.031392f, -0.937286f, 0.548290f, 0.176453f,- -1.039254f, 0.600669f, 0.085532f, -1.012268f, 0.247689f, 0.055143f, -0.270079f, 0.423475f,+ -1.011940f, 0.274893f, 0.215012f, -1.007991f, 0.324332f, 0.377184f, -1.079051f, 0.140310f,+ 0.069755f, -0.926549f, 0.196098f, 0.122324f, -0.957042f, 0.791963f, 0.093056f, -1.045666f,+ -0.043123f, 0.276709f, -0.463525f, 0.146081f, 0.278636f, -0.665001f, 0.872397f, 0.204653f,+ -0.902212f, 0.233920f, 0.045356f, -0.650669f, 0.247689f, 0.055143f, -0.270079f, 0.423475f,0.074996f, -0.605837f, 0.572569f, 0.121736f, -0.539797f, -0.127635f, 0.346899f, -0.659494f});test_case.run_with_tolerance_as_fp(1e-4f);}@@ -7985,12 +7985,12 @@ OPENVINO_TEST(${BACKEND_NAME}, onnx_model_attention_mqa_4d) {1.098777f});test_case.add_expected_output<float>(Shape{1, 4, 4, 3},- {0.337986f, -0.303017f, 0.547312f, 0.205010f, -0.423954f, 0.599464f, 0.558864f, -0.305937f,- 0.481555f, 0.487686f, -0.377153f, 0.524956f, -0.169225f, -0.387052f, 0.832382f, 0.005277f,- -0.308193f, 0.762964f, -0.027680f, -0.357686f, 0.754208f, 0.108195f, -0.432638f, 0.547678f,+ {0.337986f, -0.303017f, 0.547312f, 0.205010f, -0.423954f, 0.599463f, 0.558864f, -0.305937f,+ 0.481555f, 0.487686f, -0.377153f, 0.524956f, -0.169226f, -0.387052f, 0.832382f, 0.005277f,+ -0.308193f, 0.762964f, -0.027681f, -0.357686f, 0.754208f, 0.108196f, -0.432638f, 0.547678f,0.597206f, -0.330012f, 0.463645f, 0.332367f, -0.286605f, 0.489778f, 0.550417f, -0.424551f,0.558099f, 0.385289f, -0.361417f, 0.535184f, 0.273678f, -0.371122f, 0.586114f, 0.322549f,- -0.312850f, 0.592683f, 0.691556f, -0.417891f, 0.548147f, 0.397891f, -0.242785f, 0.454272f});+ -0.312850f, 0.592683f, 0.691556f, -0.417890f, 0.548147f, 0.397891f, -0.242785f, 0.454272f});test_case.run_with_tolerance_as_fp(1e-4f);}@@ -8028,17 +8028,17 @@ OPENVINO_TEST(${BACKEND_NAME}, onnx_model_attention_gqa_3d) {0.473238f, -0.072829f, -0.846794f, -1.514847f, -0.446515f, 0.856399f});test_case.add_expected_output<float>(Shape{1, 3, 32},- {-0.704795f, 0.707981f, 0.593540f, -0.898167f, 1.008786f, 0.399956f, 0.432802f, 1.435332f, -0.019993f,- 1.311787f, -0.201133f, 2.317111f, 0.445180f, -0.896102f, -0.965436f, 0.532888f, -0.251821f, 0.630770f,- -0.325360f, -1.050858f, 0.983863f, 0.369530f, -0.032157f, 0.748155f, -0.048911f, 1.124254f, -0.210208f,- 1.941960f, 0.327995f, -0.843507f, -0.842911f, 0.574183f, -0.474955f, 0.530429f, 0.053854f, -0.919247f,- 1.248044f, 0.406687f, -0.272292f, 0.869132f, -0.184070f, 0.404185f, -0.092606f, 0.242662f, -0.321041f,- -0.812016f, -0.344628f, 0.774335f, -0.372639f, 0.473363f, -0.174731f, -0.937587f, 1.314551f, 0.406163f,- -0.511668f, 0.651625f, -0.183792f, 0.282770f, -0.218555f, 0.203643f, -0.240109f, -0.643703f, -0.287215f,- 0.768312f, -0.479064f, 0.635002f, 0.117315f, -0.960196f, 1.059176f, 0.390321f, 0.084115f, 1.038653f,- -0.054916f, 1.087806f, -0.209541f, 1.864920f, 0.302044f, -0.836003f, -0.818654f, 0.582872f, -0.866851f,- 0.733830f, 0.921344f, -0.842817f, 1.020930f, 0.411125f, 0.593132f, 1.678388f, -0.154474f, 0.530392f,- -0.150549f, 0.603883f, -0.158533f, -0.775794f, -0.438776f, 0.729069f});+ {-0.578544f, 0.906466f, 0.478973f, -0.269664f, 0.824521f, 0.163096f, 0.379487f, 1.367918f, -0.228119f,+ 0.938606f, -0.176255f, -0.213897f, 0.699997f, 0.071186f, 0.145251f, 0.919134f, -0.311386f, 0.091799f,+ -0.057718f, -0.457374f, -0.090073f, -0.486672f, -0.311790f, 0.810723f, -0.398406f, 0.348400f, 0.234535f,+ -0.407879f, 0.272713f, -0.532246f, -0.636800f, 0.777365f, -0.031783f, 0.998567f, -0.512509f, 0.063863f,+ 0.631195f, -0.053956f, -0.075798f, 0.656805f, -0.155417f, 1.099274f, -0.198931f, 0.702556f, 0.677710f,+ -0.218220f, -0.233016f, 0.786070f, -0.288275f, -0.219073f, -0.362853f, -0.590179f, -0.078985f, -0.178768f,+ -0.097950f, 0.816286f, -0.472167f, 0.188257f, 0.128272f, -0.552101f, 0.747385f, -0.110647f, -0.713881f,+ 0.743961f, -0.766305f, 0.875843f, 0.820194f, -0.378289f, 0.890933f, 0.235868f, 0.533681f, 1.611858f,+ -0.461761f, 0.887748f, 0.238967f, -0.423998f, 0.782344f, 0.184127f, 0.364423f, 1.225991f, -0.431317f,+ 0.092407f, 0.014144f, -0.563205f, 0.566190f, -0.119241f, -0.574239f, 0.759954f, -0.489198f, 0.175638f,+ 0.126567f, -0.573394f, 0.846203f, -0.042984f, -0.744475f, 0.736579f});test_case.run_with_tolerance_as_fp(1e-4f);}@@ -8062,9 +8062,9 @@ OPENVINO_TEST(${BACKEND_NAME}, onnx_model_attention_causal) {1.644968f, -0.249036f, 0.576557f, 0.311250f, 3.078881f, 1.119575f});test_case.add_expected_output<float>(Shape{1, 2, 4, 3},- {-0.107030f, -1.035242f, -0.553649f, -0.151585f, -0.912711f, -0.529596f, -0.308122f, -0.584946f,- -0.412347f, -0.755049f, 0.745656f, -0.131881f, -0.530501f, -0.575818f, -0.275052f, -0.891396f,- -0.767198f, 0.059461f, -0.424143f, -0.658454f, 0.108633f, -1.459665f, -0.765383f, 1.122714f});+ {-0.107030f, -1.035242f, -0.553649f, -0.151585f, -0.912711f, -0.529595f, -0.308122f, -0.584946f,+ -0.412347f, -0.755049f, 0.745657f, -0.131881f, -0.530501f, -0.575818f, -0.275052f, -0.891395f,+ -0.767198f, 0.059460f, -0.424142f, -0.658454f, 0.108633f, -1.459665f, -0.765382f, 1.122714f});test_case.run_with_tolerance_as_fp(1e-4f);}@@ -8105,9 +8105,9 @@ OPENVINO_TEST(${BACKEND_NAME}, onnx_model_attention_mask_float) {0.0f});test_case.add_expected_output<float>(Shape{1, 2, 4, 3},- {0.259723f, -0.904317f, 0.638592f, -0.670611f, -0.498413f, -0.257053f, -0.529244f, -0.382512f,+ {0.259723f, -0.904317f, 0.638592f, -0.670610f, -0.498413f, -0.257053f, -0.529244f, -0.382512f,-0.320152f, -0.514261f, 0.291701f, -0.555729f, 0.835692f, -1.129707f, 0.529804f, 1.204720f,- -1.947056f, -0.278264f, 1.169140f, -1.832562f, -0.273470f, 1.201381f, -2.001133f, -0.412585f});+ -1.947056f, -0.278264f, 1.169140f, -1.832562f, -0.273470f, 1.201382f, -2.001132f, -0.412585f});test_case.run_with_tolerance_as_fp(1e-4f);}@@ -8134,9 +8134,9 @@ OPENVINO_TEST(${BACKEND_NAME}, onnx_model_attention_mask_bool) {{true, false, false, false, true, true, false, false, true, true, true, false, true, true, true, true});test_case.add_expected_output<float>(Shape{1, 2, 4, 3},- {0.756989f, -0.922165f, 0.869606f, 1.003041f, -0.373216f, 1.283574f, 0.603106f, -0.411673f,+ {0.756989f, -0.922165f, 0.869606f, 1.003042f, -0.373216f, 1.283574f, 0.603106f, -0.411673f,0.590585f, 0.369631f, -0.489830f, 0.009988f, 0.279969f, -1.125489f, 2.445752f, 0.231076f,- -0.724973f, 1.887900f, 0.229914f, -0.068798f, 0.681135f, 0.338080f, 0.258214f, 0.664186f});+ -0.724973f, 1.887901f, 0.229914f, -0.068798f, 0.681136f, 0.338080f, 0.258214f, 0.664186f});test_case.run_with_tolerance_as_fp(1e-4f);}@@ -8160,8 +8160,8 @@ OPENVINO_TEST(${BACKEND_NAME}, onnx_model_attention_custom_scale) {-0.360966f, 1.159330f, -1.081063f, 0.615936f, 0.593101f, -0.309546f});test_case.add_expected_output<float>(Shape{1, 2, 4, 3},- {0.175016f, 0.297030f, 1.008947f, -0.314262f, -0.197272f, -0.397901f, -0.615684f, -0.441686f,- -0.360722f, -0.612660f, -0.599629f, 1.158077f, 0.054589f, 0.835598f, -0.574787f, -0.731885f,+ {0.175016f, 0.297030f, 1.008946f, -0.314263f, -0.197272f, -0.397902f, -0.615685f, -0.441686f,+ -0.360722f, -0.612660f, -0.599629f, 1.158077f, 0.054589f, 0.835598f, -0.574786f, -0.731885f,0.722422f, 0.079574f, -0.591538f, 0.747547f, -0.051516f, -0.699099f, 0.720287f, 0.091489f});test_case.run_with_tolerance_as_fp(1e-4f);}@@ -8251,9 +8251,9 @@ OPENVINO_TEST(${BACKEND_NAME}, onnx_model_attention_softcap) {0.267050f, 0.889631f, 0.082284f, 1.065480f, -0.517288f, 1.409347f});test_case.add_expected_output<float>(Shape{1, 2, 4, 3},- {-0.217309f, -0.010507f, 0.432435f, -0.418403f, 0.393266f, -0.258099f, -0.274749f, 0.222249f,- 0.149638f, -0.297697f, 0.183658f, 0.133947f, 0.548682f, -0.324988f, 1.232658f, 0.393897f,- 0.368712f, -0.122598f, 0.260566f, 0.421482f, -0.243643f, 0.329124f, 0.370001f, -0.109046f});+ {-0.217310f, -0.010507f, 0.432435f, -0.418403f, 0.393266f, -0.258099f, -0.274749f, 0.222249f,+ 0.149638f, -0.297697f, 0.183658f, 0.133948f, 0.548682f, -0.324987f, 1.232658f, 0.393897f,+ 0.368712f, -0.122598f, 0.260566f, 0.421482f, -0.243643f, 0.329123f, 0.370001f, -0.109046f});test_case.run_with_tolerance_as_fp(1e-4f);}@@ -8277,9 +8277,9 @@ OPENVINO_TEST(${BACKEND_NAME}, onnx_model_attention_causal_softcap) {1.644968f, -0.249036f, 0.576557f, 0.311250f, 3.078881f, 1.119575f});test_case.add_expected_output<float>(Shape{1, 2, 4, 3},- {-0.201853f, -0.724072f, -0.430133f, -0.234045f, -0.630293f, -0.405222f, -0.332883f, -0.469627f,- -0.355742f, -0.732414f, 0.696189f, -0.129281f, -0.326636f, -0.078002f, 0.361213f, -0.583892f,- -0.368495f, 0.273408f, -0.393912f, -0.557303f, 0.172777f, -0.918016f, -0.294001f, 0.962115f});+ {-0.107030f, -1.035242f, -0.553649f, -0.204205f, -0.767998f, -0.501187f, -0.336917f, -0.508691f,+ -0.395867f, -0.732414f, 0.696189f, -0.129281f, -0.530501f, -0.575818f, -0.275052f, -0.969258f,+ -0.808488f, 0.131632f, -0.415063f, -0.666371f, 0.144377f, -0.918016f, -0.294001f, 0.962115f});test_case.run_with_tolerance_as_fp(1e-4f);}@@ -8311,17 +8311,17 @@ OPENVINO_TEST(${BACKEND_NAME}, onnx_model_attention_mqa_3d) {-0.012247f, -0.897254f, 0.075805f, -0.677162f, 0.975120f, -0.147057f});test_case.add_expected_output<float>(Shape{1, 3, 32},- {0.584764f, 0.724167f, 0.503125f, 0.499875f, 0.105035f, -0.625041f, 0.657639f, 0.136957f, 0.561326f,- 0.682043f, 0.229291f, 0.147373f, 0.011446f, -0.687052f, 0.802709f, 0.090234f, 0.468962f, 0.677608f,- 0.096148f, 0.687705f, -0.176568f, -0.779856f, 0.830123f, 0.257721f, 0.620987f, 0.722240f, 0.533878f,- 0.244191f, 0.174668f, -0.592084f, 0.659237f, 0.063294f, 0.270539f, 0.623238f, -0.452431f, 1.312983f,- -0.630656f, -1.021292f, 1.040076f, 0.519944f, 0.573690f, 0.686437f, 0.269369f, 0.120435f, 0.040868f,- -0.671063f, 0.786234f, 0.076085f, 0.596900f, 0.703859f, 0.398307f, 0.179405f, 0.106362f, -0.632444f,- 0.724410f, 0.069487f, 0.463907f, 0.680591f, 0.107749f, 0.755809f, -0.183249f, -0.781909f, 0.820756f,- 0.273910f, 0.387734f, 0.625262f, -0.304596f, 0.584345f, -0.396129f, -0.906919f, 1.017432f, 0.299585f,- 0.380968f, 0.640075f, -0.225713f, 0.804712f, -0.392961f, -0.899516f, 0.968444f, 0.344800f, 0.544325f,- 0.695915f, 0.290788f, 0.422251f, -0.006723f, -0.690354f, 0.758272f, 0.153030f, 0.550951f, 0.630505f,- -0.084503f, -0.401461f, -0.066788f, -0.745357f, 0.977725f, -0.002030f});+ {0.584764f, 0.724167f, 0.503125f, 0.499875f, 0.105036f, -0.625041f, 0.657639f, 0.136957f, 0.270539f,+ 0.623238f, -0.452432f, 1.312982f, -0.630656f, -1.021292f, 1.040076f, 0.519945f, 0.387734f, 0.625261f,+ -0.304596f, 0.584346f, -0.396129f, -0.906920f, 1.017433f, 0.299586f, 0.561326f, 0.682043f, 0.229291f,+ 0.147373f, 0.011446f, -0.687052f, 0.802709f, 0.090234f, 0.573690f, 0.686437f, 0.269369f, 0.120435f,+ 0.040868f, -0.671063f, 0.786234f, 0.076085f, 0.380968f, 0.640075f, -0.225713f, 0.804712f, -0.392960f,+ -0.899516f, 0.968444f, 0.344800f, 0.468962f, 0.677608f, 0.096148f, 0.687704f, -0.176567f, -0.779856f,+ 0.830123f, 0.257721f, 0.596900f, 0.703859f, 0.398307f, 0.179405f, 0.106362f, -0.632445f, 0.724410f,+ 0.069488f, 0.544325f, 0.695915f, 0.290789f, 0.422250f, -0.006723f, -0.690354f, 0.758271f, 0.153030f,+ 0.620987f, 0.722240f, 0.533878f, 0.244191f, 0.174668f, -0.592084f, 0.659237f, 0.063294f, 0.463907f,+ 0.680591f, 0.107749f, 0.755809f, -0.183249f, -0.781910f, 0.820756f, 0.273910f, 0.550951f, 0.630505f,+ -0.084503f, -0.401460f, -0.066788f, -0.745357f, 0.977726f, -0.002029f});test_case.run_with_tolerance_as_fp(1e-4f);}@@ -8453,12 +8453,12 @@ OPENVINO_TEST(${BACKEND_NAME}, onnx_model_attention_kv_cache_gqa) {{0.076141f,-0.128282f,-0.279242f,- -0.229337f,- -0.029947f,- 0.363563f,- 0.338080f,- 0.709321f,- -0.281886f,+ 0.467538f,+ -0.493630f,+ -0.304832f,+ -0.333913f,+ 0.380137f,+ 0.196774f,-0.308233f,0.372735f,0.221593f});@@ -8509,12 +8509,12 @@ OPENVINO_TEST(${BACKEND_NAME}, onnx_model_attention_diff_seq_len) {test_case.add_expected_output<float>(Shape{1, 2, 2, 3},{0.087744f,0.192022f,- -1.163300f,+ -1.163301f,-0.317679f,- 0.342993f,+ 0.342994f,-1.627566f,0.149217f,- 0.118020f,+ 0.118019f,-0.205577f,0.717496f,0.189523f,@@ -8560,9 +8560,9 @@ OPENVINO_TEST(${BACKEND_NAME}, onnx_model_attention_softcap_mask_float) {// Y: (1, 2, 4, 3)test_case.add_expected_output<float>(Shape{1, 2, 4, 3},- {-0.337778f, 1.083041f, -0.154105f, -0.339207f, 0.462505f, -0.138030f, -0.370519f, 0.002809f,- 0.361551f, -0.745861f, -0.868438f, -1.783549f, 0.011989f, -1.158582f, 0.926068f, 0.141611f,- -1.070733f, 1.395292f, 0.616303f, -0.716178f, -0.001065f, 0.855951f, -0.863237f, 0.067472f});+ {-0.297563f, 1.375707f, -0.150056f, -0.170432f, 0.910380f, -0.100291f, -0.363657f, 0.017126f,+ 0.397768f, -0.745860f, -0.868437f, -1.783548f, -0.638962f, -1.323090f, 1.642015f, -0.057527f,+ -1.099181f, 1.857277f, 0.568421f, -0.696923f, 0.045950f, 0.855951f, -0.863237f, 0.067472f});test_case.run_with_tolerance_as_fp(1e-4f);}@@ -8590,9 +8590,9 @@ OPENVINO_TEST(${BACKEND_NAME}, onnx_model_attention_softcap_mask_bool) {// Y: (1, 2, 4, 3)test_case.add_expected_output<float>(Shape{1, 2, 4, 3},- {-0.241921f, 0.798990f, -0.230361f, 0.031411f, 0.426047f, -0.109958f, -0.235019f, 0.815910f,- -0.332928f, 0.011776f, 0.637913f, -0.187854f, 0.077533f, -0.218485f, 0.436238f, -0.007613f,- 0.145932f, 0.949036f, -0.284543f, -0.485247f, 0.518275f, 1.190462f, -0.484776f, 1.201895f});+ {-0.718407f, 0.894924f, -0.294950f, 0.083588f, 0.255165f, -0.060837f, -0.269058f, 0.827289f,+ -0.379579f, 0.011777f, 0.637912f, -0.187854f, -0.185288f, -0.129821f, 0.043811f, -0.168807f,+ 0.340980f, 0.976508f, -0.357822f, -0.477100f, 0.489599f, 1.190461f, -0.484776f, 1.201895f});test_case.run_with_tolerance_as_fp(1e-4f);}@@ -8626,12 +8626,12 @@ OPENVINO_TEST(${BACKEND_NAME}, onnx_model_attention_batch2) {// Y: (2, 2, 4, 3)test_case.add_expected_output<float>(Shape{2, 2, 4, 3},- {-0.166310f, 0.212826f, 0.543234f, -0.213388f, 0.101926f, 0.318213f, -0.244788f, 0.644003f,- 0.065711f, -0.246961f, 0.717591f, 0.121477f, 0.259517f, -1.429630f, -0.810381f, 0.316639f,- -1.466488f, -0.807307f, 0.461846f, -1.459568f, -0.789374f, 0.353310f, -1.386105f, -1.080682f,- -0.116249f, -0.031849f, -0.247218f, -0.044228f, -0.413143f, 0.152197f, -0.035514f, -0.486822f,- 0.250045f, -0.074804f, 0.083506f, -0.153397f, 0.785283f, -0.624480f, 0.412796f, 0.880455f,- -0.668594f, 1.260619f, 0.931097f, -0.776981f, -0.151116f, 0.801838f, -0.673882f, 0.952639f});+ {-0.166310f, 0.212826f, 0.543234f, -0.213388f, 0.101926f, 0.318213f, -0.244788f, 0.644002f,+ 0.065710f, -0.246961f, 0.717590f, 0.121477f, 0.259517f, -1.429630f, -0.810381f, 0.316639f,+ -1.466488f, -0.807307f, 0.461846f, -1.459568f, -0.789375f, 0.353310f, -1.386105f, -1.080682f,+ -0.116249f, -0.031850f, -0.247219f, -0.044228f, -0.413144f, 0.152197f, -0.035515f, -0.486823f,+ 0.250045f, -0.074804f, 0.083506f, -0.153397f, 0.785283f, -0.624481f, 0.412797f, 0.880455f,+ -0.668594f, 1.260620f, 0.931096f, -0.776981f, -0.151115f, 0.801838f, -0.673882f, 0.952639f});test_case.run_with_tolerance_as_fp(1e-4f);}@@ -8657,8 +8657,8 @@ OPENVINO_TEST(${BACKEND_NAME}, onnx_model_attention_present_no_past) {test_case.add_expected_output<float>(Shape{1, 2, 4, 3},{1.135819f, 0.473164f, 0.391118f, 0.387219f, 0.351068f, -0.033320f, 0.515863f, 0.408149f,- -0.001368f, 0.225511f, 0.208291f, 0.004389f, -0.568707f, 0.630642f, 0.114516f, -0.462505f,- 0.597372f, 1.021277f, -0.496153f, 0.599542f, 0.792319f, -0.305059f, 0.656953f, 0.223635f});+ -0.001367f, 0.225511f, 0.208291f, 0.004389f, -0.568708f, 0.630642f, 0.114516f, -0.462505f,+ 0.597372f, 1.021277f, -0.496154f, 0.599542f, 0.792318f, -0.305059f, 0.656953f, 0.223635f});// present_key: (1, 2, 4, 3) — same as K (no past to concatenate)test_case.add_expected_output<float>(Shape{1, 2, 4, 3},@@ -8699,10 +8699,10 @@ OPENVINO_TEST(${BACKEND_NAME}, onnx_model_attention_gqa_causal) {test_case.add_expected_output<float>(Shape{1, 4, 4, 3},{-0.372207f, 1.088749f, 1.884586f, 1.043291f, -0.077079f, -0.335489f, 0.256285f, -0.624200f,- 0.527349f, 0.517354f, -0.237278f, -0.074090f, 0.513600f, -0.532701f, -1.169917f, 0.115278f,- -0.473270f, -0.823793f, -0.248875f, -0.389089f, -0.318127f, 0.186889f, -0.530199f, -0.385138f,- -0.372207f, 1.088749f, 1.884586f, 0.717689f, 0.191092f, 0.175188f, 0.189007f, -0.193952f,- 0.749369f, -0.011048f, 0.054519f, -0.166278f, 0.513600f, -0.532701f, -1.169917f, -1.055831f,+ 0.527349f, 0.517354f, -0.237278f, -0.074090f, -0.372207f, 1.088749f, 1.884586f, 0.420766f,+ 0.435643f, 0.640882f, 0.231063f, -0.034779f, 0.743644f, 0.222117f, -0.325168f, -0.371449f,+ 0.513600f, -0.532701f, -1.169917f, -2.030353f, -0.153132f, 1.040669f, -0.652405f, -0.318728f,+ 0.096893f, 0.433480f, -0.778922f, -0.306615f, 0.513600f, -0.532701f, -1.169917f, -1.055831f,-0.298535f, 0.193851f, -0.273476f, -0.274162f, 0.408617f, -0.612912f, -0.347982f, 0.594694f});test_case.run_with_tolerance_as_fp(1e-4f);}diff --git a/src/frontends/onnx/tests/tests_python/test_backend.py b/src/frontends/onnx/tests/tests_python/test_backend.pyindex 30a9fc5c449..f12da65ce16 100644--- a/src/frontends/onnx/tests/tests_python/test_backend.py+++ b/src/frontends/onnx/tests/tests_python/test_backend.py@@ -70,6 +70,8 @@ from tests import (xfail_issue_171767,xfail_issue_171771,xfail_issue_171772,+ xfail_attention_onnx_version,+ xfail_attention_nan_robustness,)from tests.tests_python.utils.onnx_backend import OpenVinoTestBackend@@ -584,6 +586,58 @@ tests_expected_to_fail = ["OnnxBackendNodeModelTest.test_averagepool_2d_ceil_last_window_starts_on_pad_cpu","OnnxBackendNodeModelTest.test_averagepool_3d_dilations_large_count_include_pad_is_1_ceil_mode_is_True_cpu",),+ (+ xfail_attention_onnx_version,+ # Pass locally with ONNX >= 1.23+ "OnnxBackendNodeModelTest.test_attention_3d_attn_mask_cpu",+ "OnnxBackendNodeModelTest.test_attention_3d_causal_cpu",+ "OnnxBackendNodeModelTest.test_attention_3d_cpu",+ "OnnxBackendNodeModelTest.test_attention_3d_diff_heads_sizes_attn_mask_cpu",+ "OnnxBackendNodeModelTest.test_attention_3d_diff_heads_sizes_causal_cpu",+ "OnnxBackendNodeModelTest.test_attention_3d_diff_heads_sizes_cpu",+ "OnnxBackendNodeModelTest.test_attention_3d_diff_heads_sizes_scaled_cpu",+ "OnnxBackendNodeModelTest.test_attention_3d_diff_heads_sizes_softcap_cpu",+ "OnnxBackendNodeModelTest.test_attention_3d_diff_heads_with_past_and_present_cpu",+ "OnnxBackendNodeModelTest.test_attention_3d_gqa_attn_mask_cpu",+ "OnnxBackendNodeModelTest.test_attention_3d_gqa_causal_cpu",+ "OnnxBackendNodeModelTest.test_attention_3d_gqa_cpu",+ "OnnxBackendNodeModelTest.test_attention_3d_gqa_scaled_cpu",+ "OnnxBackendNodeModelTest.test_attention_3d_gqa_softcap_cpu",+ "OnnxBackendNodeModelTest.test_attention_3d_gqa_with_past_and_present_cpu",+ "OnnxBackendNodeModelTest.test_attention_3d_scaled_cpu",+ "OnnxBackendNodeModelTest.test_attention_3d_softcap_cpu",+ "OnnxBackendNodeModelTest.test_attention_3d_with_past_and_present_cpu",+ "OnnxBackendNodeModelTest.test_attention_3d_with_past_and_present_qk_matmul_bias_cpu",+ "OnnxBackendNodeModelTest.test_attention_3d_with_past_and_present_qk_matmul_cpu",+ "OnnxBackendNodeModelTest.test_attention_3d_with_past_and_present_qk_matmul_softcap_cpu",+ "OnnxBackendNodeModelTest.test_attention_3d_with_past_and_present_qk_matmul_softmax_cpu",+ "OnnxBackendNodeModelTest.test_attention_4d_gqa_attn_mask_cpu",+ "OnnxBackendNodeModelTest.test_attention_4d_gqa_causal_cpu",+ "OnnxBackendNodeModelTest.test_attention_4d_gqa_cpu",+ "OnnxBackendNodeModelTest.test_attention_4d_gqa_scaled_cpu",+ "OnnxBackendNodeModelTest.test_attention_4d_gqa_softcap_cpu",+ "OnnxBackendNodeModelTest.test_attention_4d_gqa_with_past_and_present_cpu",+ "OnnxBackendNodeModelTest.test_attention_4d_with_past_and_present_qk_matmul_bias_cpu",+ "OnnxBackendNodeModelTest.test_attention_4d_with_qk_matmul_bias_cpu",+ "OnnxBackendNodeModelTest.test_attention_4d_with_qk_matmul_softcap_cpu",+ ),+ (+ xfail_attention_onnx_version,+ # These 4 tests pass locally with ONNX >= 1.23+ # They are skipped in CI because ONNX 1.18 does not provide correct reference values for opset-23/24 tests.+ "OnnxBackendNodeModelTest.test_attention_23_fullymasked_qk_matmul_output_mode3_zero_cpu",+ "OnnxBackendNodeModelTest.test_attention_24_fullymasked_qk_matmul_output_mode3_zero_cpu",+ "OnnxBackendNodeModelTest.test_attention_24_qk_matmul_output_mode3_softmax_precision_cpu",+ "OnnxBackendNodeModelTest.test_attention_23_boolmask_fullymasked_row_nan_robustness_cpu",+ ),+ (+ xfail_attention_nan_robustness,+ # expanded variants use the ONNX reference decomposition (not our translator) and do not yet pass.+ "OnnxBackendNodeModelTest.test_attention_23_boolmask_fullymasked_row_nan_robustness_expanded_cpu",+ "OnnxBackendNodeModelTest.test_attention_23_fullymasked_qk_matmul_output_mode3_zero_expanded_cpu",+ "OnnxBackendNodeModelTest.test_attention_24_fullymasked_qk_matmul_output_mode3_zero_expanded_cpu",+ "OnnxBackendNodeModelTest.test_attention_24_qk_matmul_output_mode3_softmax_precision_expanded_cpu",+ ),]if platform.system() == 'Darwin':