#include "../node_context.h"
#include "../op_table.h"
#include "../utils.h"
#include "ggml-openvino/ggml-openvino-extra.h"
#include <cstddef>
#include <cstdint>
#include <memory>
#include <openvino/op/add.hpp>
#include <openvino/op/broadcast.hpp>
#include <openvino/op/concat.hpp>
#include <openvino/op/constant.hpp>
#include <openvino/op/convert.hpp>
#include <openvino/op/matmul.hpp>
#include <openvino/op/maximum.hpp>
#include <openvino/op/multiply.hpp>
#include <openvino/op/reshape.hpp>
#include <openvino/op/scaled_dot_product_attention.hpp>
#include <openvino/op/scatter_update.hpp>
#include <openvino/op/slice.hpp>
#include <openvino/op/softmax.hpp>
#include <openvino/op/tanh.hpp>
#include <openvino/op/tile.hpp>
#include <openvino/op/transpose.hpp>
#include <openvino/op/unsqueeze.hpp>
#include <optional>
#include <string>
#include <unordered_set>
namespace ov {
namespace frontend {
namespace ggml {
namespace op {
static std::optional<ov::Output<ov::Node>> find_scatter_updates(const ov::Output<ov::Node> & root) {
std::vector<ov::Output<ov::Node>> pending{root};
std::unordered_set<const ov::Node *> visited;
std::optional<ov::Output<ov::Node>> updates;
while (!pending.empty()) {
auto output = pending.back();
pending.pop_back();
auto node = output.get_node_shared_ptr();
if (!node || !visited.insert(node.get()).second) {
continue;
}
if (auto scatter = ov::as_type_ptr<ov::op::v3::ScatterUpdate>(node)) {
OPENVINO_ASSERT(!updates.has_value(), "HFA KV input contains multiple ScatterUpdate ancestors");
updates = scatter->input_value(2);
continue;
}
for (const auto & input : node->inputs()) {
pending.push_back(input.get_source_output());
}
}
return updates;
}
static ov::Output<ov::Node> reshape_present_kv(const ov::Output<ov::Node> & updates,
int64_t n_heads_kv,
int64_t head_size) {
auto shape = updates.get_partial_shape();
OPENVINO_ASSERT(shape.rank().is_static() && shape.rank().get_length() == 4,
"HFA present KV updates must be rank 4");
auto reshaped = std::make_shared<ov::op::v1::Reshape>(
updates,
ov::op::v0::Constant::create(
ov::element::i64, {4}, std::vector<int64_t>{1, -1, n_heads_kv, head_size}),
false);
return std::make_shared<ov::op::v1::Transpose>(
reshaped, ov::op::v0::Constant::create(ov::element::i64, {4}, {0, 2, 1, 3}));
}
static int extract_layer(const std::string & name) {
const auto begin = name.find("_l");
OPENVINO_ASSERT(begin != std::string::npos, "HFA KV input has no layer suffix: ", name);
return std::stoi(name.substr(begin + 2));
}
static ov::Output<ov::Node> reshape_flat_kv(const ov::Output<ov::Node> & kv_flat,
size_t view_offset_bytes,
size_t nb1_bytes,
int64_t n_head,
int64_t head_size,
const ov::Output<ov::Node> & attention_size) {
int64_t n_state = n_head * head_size;
int64_t layer_start_elem = (int64_t) (view_offset_bytes / (nb1_bytes / n_state));
auto start_c = ov::op::v0::Constant::create(ov::element::i64, {1}, {layer_start_elem});
auto n_state_c = ov::op::v0::Constant::create(ov::element::i64, {1}, {n_state});
auto kv_len_elems = std::make_shared<ov::op::v1::Multiply>(attention_size, n_state_c);
auto end_c = std::make_shared<ov::op::v1::Add>(start_c, kv_len_elems);
auto step_c = ov::op::v0::Constant::create(ov::element::i64, {1}, {1});
auto axis_c = ov::op::v0::Constant::create(ov::element::i64, {1}, {3});
auto sliced = std::make_shared<ov::op::v8::Slice>(kv_flat, start_c, end_c, step_c, axis_c);
auto one_c = ov::op::v0::Constant::create(ov::element::i64, {1}, {1});
auto n_head_c = ov::op::v0::Constant::create(ov::element::i64, {1}, {n_head});
auto head_size_c = ov::op::v0::Constant::create(ov::element::i64, {1}, {head_size});
auto new_shape =
std::make_shared<ov::op::v0::Concat>(ov::OutputVector{one_c, attention_size, n_head_c, head_size_c}, 0);
auto reshaped = std::make_shared<ov::op::v1::Reshape>(sliced, new_shape, false);
auto perm = ov::op::v0::Constant::create(ov::element::i64, {4}, {0, 2, 1, 3});
auto ret = std::make_shared<ov::op::v1::Transpose>(reshaped, perm);
return ret;
}
OutputVector translate_flash_attn_ext(const NodeContext & context) {
num_inputs_check(context, 3, 5);
const bool has_mask = context.get_input_size() >= 4;
const bool has_sink = context.get_input_size() == 5;
auto q_f32 = context.get_input(0);
auto k = context.get_input(1);
auto v = context.get_input(2);
const auto k_cache = k;
const auto v_cache = v;
const int op_case = context.get_op_case();
if (op_case == 1 || op_case == 2) {
int64_t n_state_head = (int64_t) context.get_view_input_ggml_shape(1, 0)[3];
int64_t n_head = (int64_t) context.get_view_input_ggml_shape(1, 0)[1];
size_t nb1 = context.get_view_input_stride(1, 0)[2];
size_t offset = context.get_view_input_offset(1, 0);
ov::Output<ov::Node> attention_size;
if (op_case == 1) {
attention_size = context.get_input("attention_size");
} else {
attention_size = context.get_input("attention_size_static");
}
k = reshape_flat_kv(k, offset, nb1, n_head, n_state_head, attention_size);
v = reshape_flat_kv(v, offset, nb1, n_head, n_state_head, attention_size);
}
float * params = reinterpret_cast<float *>(context.get_output_op_params());
float scale = params[0];
const float logit_softcap = params[2];
auto q = std::make_shared<ov::op::v0::Convert>(q_f32, ov::element::f16);
auto scale_node = std::make_shared<ov::op::v0::Constant>(ov::element::f16, ov::Shape{}, std::vector<float>{scale});
ov::Output<ov::Node> res;
ov::Output<ov::Node> mask;
if (has_mask) {
mask = get_kq_mask_input(context, 3);
if (mask.get_element_type() != ov::element::f16) {
mask = std::make_shared<ov::op::v0::Convert>(mask, ov::element::f16);
}
}
ov::Output<ov::Node> sink;
if (has_sink) {
sink = context.get_input(4);
if (sink.get_element_type() != q->get_element_type()) {
sink = std::make_shared<ov::op::v0::Convert>(sink, q->get_element_type());
}
sink = std::make_shared<ov::op::v1::Reshape>(
sink,
ov::op::v0::Constant::create(ov::element::i64, {4},
std::vector<int64_t>{1, context.get_input_shape(0)[1].get_length(), 1, 1}),
false);
}
auto q_shape = context.get_input_shape(0).to_shape();
auto k_shape = context.get_input_shape(1).to_shape();
auto v_shape = context.get_input_shape(2).to_shape();
const int64_t num_heads = q_shape[1];
const int64_t num_heads_kv = k_shape[1];
const int64_t head_size = q_shape[3];
const int64_t factor = num_heads / num_heads_kv;
static const bool manual_gqa_enabled = ggml_openvino_manual_gqa_enabled();
const bool same_head_size = k_shape[3] == q_shape[3] && v_shape[3] == q_shape[3];
const bool use_manual_gqa_attention =
!has_sink &&
(logit_softcap != 0.0f || (manual_gqa_enabled && factor > 1 && num_heads_kv > 1 && !context.is_stateful())) &&
same_head_size;
FRONT_END_OP_CONVERSION_CHECK(logit_softcap == 0.0f || use_manual_gqa_attention,
"FLASH_ATTN_EXT with logit soft-capping is not supported with different K/V head "
"sizes");
if (use_manual_gqa_attention) {
auto q_r = std::make_shared<ov::op::v1::Reshape>(
q,
ov::op::v0::Constant::create(ov::element::i64, {4}, std::vector<int64_t>{0, num_heads_kv, -1, head_size}),
true);
auto qk = std::make_shared<ov::op::v0::MatMul>(q_r, k, false, true);
ov::Output<ov::Node> probs;
if (logit_softcap != 0.0f) {
probs = std::make_shared<ov::op::v1::Multiply>(
qk,
ov::op::v0::Constant::create(ov::element::f16, ov::Shape{}, std::vector<float>{scale / logit_softcap}));
probs = std::make_shared<ov::op::v1::Multiply>(
std::make_shared<ov::op::v0::Tanh>(probs),
ov::op::v0::Constant::create(ov::element::f16, ov::Shape{}, std::vector<float>{logit_softcap}));
} else {
probs = std::make_shared<ov::op::v1::Multiply>(qk, scale_node);
}
if (has_mask) {
auto mask_finite = std::make_shared<ov::op::v1::Maximum>(
mask, ov::op::v0::Constant::create(ov::element::f16, ov::Shape{}, std::vector<float>{-30000.0f}));
auto mask_tiled = std::make_shared<ov::op::v0::Tile>(
mask_finite,
ov::op::v0::Constant::create(ov::element::i64, {4}, std::vector<int64_t>{1, 1, factor, 1}));
probs = std::make_shared<ov::op::v1::Add>(probs, mask_tiled);
}
probs = std::make_shared<ov::op::v8::Softmax>(probs, -1);
auto attn = std::make_shared<ov::op::v0::MatMul>(probs, v);
auto out_4d_shape =
ov::op::v0::Constant::create(ov::element::i64, {4}, std::vector<int64_t>{0, num_heads, -1, head_size});
auto out_4d = std::make_shared<ov::op::v1::Reshape>(attn, out_4d_shape, true);
res = std::make_shared<ov::op::v1::Transpose>(
out_4d, ov::op::v0::Constant::create(ov::element::i64, {4}, {0, 2, 1, 3}));
res = std::make_shared<ov::op::v0::Convert>(res, ov::element::f32);
return rename_outputs_with_suffix({res}, context.get_name());
}
auto tile_kv = [&](int64_t n_heads, int64_t n_heads_kv, int64_t hs, ov::Output<Node> kv, bool transposed = false) {
int64_t f = n_heads / n_heads_kv;
if (f > 1 && n_heads_kv > 1) {
ov::Output<ov::Node> kv_broadcast_shape;
ov::Output<ov::Node> kv_unsqueezed;
ov::Output<ov::Node> new_kv_shape;
auto unsqueeze_axes = ov::op::v0::Constant::create(ov::element::i64, Shape{}, {2});
kv_unsqueezed = std::make_shared<ov::op::v0::Unsqueeze>(kv, unsqueeze_axes);
kv_broadcast_shape = ov::op::v0::Constant::create(ov::element::i64, {5},
{(int64_t) 1, (int64_t) 1, f, (int64_t) 1, (int64_t) 1});
new_kv_shape = ov::op::v0::Constant::create(
ov::element::i64, {4},
transposed ? std::vector<int64_t>{0, n_heads, hs, -1} : std::vector<int64_t>{0, n_heads, -1, hs});
kv = std::make_shared<ov::op::v3::Broadcast>(kv_unsqueezed, kv_broadcast_shape,
ov::op::BroadcastType::BIDIRECTIONAL);
kv = std::make_shared<ov::op::v1::Reshape>(kv, new_kv_shape, true);
}
return kv;
};
const bool v_transposed = ggml_openvino_npu_kv_head_major_enabled() && context.is_static() &&
context.get_input_names()[2].find("cache_v_l") != std::string::npos;
const bool use_hfa_gate =
ggml_openvino_npu_hfa_prefill_enabled() && context.is_static() && context.is_prefill() && has_mask && !has_sink;
if (use_hfa_gate) {
const int layer = extract_layer(context.get_input_names()[1]);
auto past_k = context.get_input("ggml_hfa_past_cache_k_l" + std::to_string(layer));
auto past_v = context.get_input("ggml_hfa_past_cache_v_l" + std::to_string(layer));
auto hfa_mask = context.get_input("ggml_hfa_mask");
auto present_k_updates = find_scatter_updates(k_cache);
auto present_v_updates = find_scatter_updates(v_cache);
if (!present_v_updates && v_transposed) {
ov::Output<ov::Node> rows = v_cache;
while (auto slice = ov::as_type_ptr<ov::op::v8::Slice>(rows.get_node_shared_ptr())) {
rows = slice->input_value(0);
}
present_v_updates = rows;
}
OPENVINO_ASSERT(present_k_updates.has_value() && present_v_updates.has_value(),
"HFA prefill requires ScatterUpdate-backed K/V cache inputs");
if (ggml_openvino_npu_kv_head_major_enabled()) {
k = std::make_shared<ov::op::v0::Concat>(ov::OutputVector{past_k, *present_k_updates}, 2);
v = std::make_shared<ov::op::v0::Concat>(ov::OutputVector{past_v, *present_v_updates},
v_transposed ? 3 : 2);
} else {
auto present_k = reshape_present_kv(*present_k_updates, num_heads_kv, head_size);
auto present_v = reshape_present_kv(*present_v_updates, num_heads_kv, head_size);
auto to_bhsd = ov::op::v0::Constant::create(ov::element::i64, {4}, {0, 2, 1, 3});
k = std::make_shared<ov::op::v0::Concat>(
ov::OutputVector{std::make_shared<ov::op::v1::Transpose>(past_k, to_bhsd), present_k}, 2);
v = std::make_shared<ov::op::v0::Concat>(
ov::OutputVector{std::make_shared<ov::op::v1::Transpose>(past_v, to_bhsd), present_v}, 2);
}
k = tile_kv(num_heads, num_heads_kv, head_size, k);
v = tile_kv(num_heads, num_heads_kv, head_size, v, v_transposed);
auto q_scaled = std::make_shared<ov::op::v1::Multiply>(q, scale_node);
auto scores = std::make_shared<ov::op::v0::MatMul>(q_scaled, k, false, true);
auto masked_scores = std::make_shared<ov::op::v1::Add>(scores, hfa_mask);
auto probs = std::make_shared<ov::op::v8::Softmax>(masked_scores, -1);
auto attended = std::make_shared<ov::op::v0::MatMul>(probs, v, false, v_transposed);
auto transposed = std::make_shared<ov::op::v1::Transpose>(
attended, ov::op::v0::Constant::create(ov::element::i64, {4}, {0, 2, 1, 3}));
auto output_shape = ov::op::v0::Constant::create(
ov::element::i64, {3}, std::vector<int64_t>{0, -1, num_heads * head_size});
res = std::make_shared<ov::op::v1::Reshape>(transposed, output_shape, true);
auto restored_shape = ov::op::v0::Constant::create(
ov::element::i64, {4}, std::vector<int64_t>{0, -1, num_heads, head_size});
res = std::make_shared<ov::op::v1::Reshape>(res, restored_shape, true);
res = std::make_shared<ov::op::v0::Convert>(res, ov::element::f32);
return rename_outputs_with_suffix({res}, context.get_name());
}
k = tile_kv(num_heads, num_heads_kv, head_size, k);
v = tile_kv(num_heads, num_heads_kv, head_size, v, v_transposed);
const auto k_dims = k.get_partial_shape();
const bool npu_square_k = ggml_openvino_npu_is_4000() && !has_sink && num_heads_kv == 1 &&
k_dims.rank().is_static() && k_dims.size() == 4 && k_dims[2].is_static() &&
k_dims[3].is_static() && k_dims[2].get_length() == k_dims[3].get_length();
if (v_transposed || npu_square_k) {
auto q_scaled = std::make_shared<ov::op::v1::Multiply>(q, scale_node);
ov::Output<ov::Node> scores = std::make_shared<ov::op::v0::MatMul>(q_scaled, k, false, true);
if (has_mask) {
scores = std::make_shared<ov::op::v1::Add>(scores, mask);
}
auto probs = std::make_shared<ov::op::v8::Softmax>(scores, -1);
auto attended = std::make_shared<ov::op::v0::MatMul>(probs, v, false, v_transposed);
res = std::make_shared<ov::op::v1::Transpose>(
attended, ov::op::v0::Constant::create(ov::element::i64, {4}, {0, 2, 1, 3}));
res = std::make_shared<ov::op::v0::Convert>(res, ov::element::f32);
return rename_outputs_with_suffix({res}, context.get_name());
}
if (has_mask && ggml_openvino_is_gpu() && !context.is_stateful() && ggml_openvino_shape_from_mask_enabled()) {
mask = std::make_shared<ov::op::v1::Maximum>(
mask, ov::op::v0::Constant::create(ov::element::f16, ov::Shape{}, std::vector<float>{-30000.0f}));
}
constexpr auto causal = false;
if (has_mask && has_sink) {
auto sdpa = std::make_shared<ov::op::v13::ScaledDotProductAttention>(q, k, v, mask, scale_node, sink, causal);
res = std::make_shared<ov::op::v1::Transpose>(
sdpa, ov::op::v0::Constant::create(ov::element::i64, {4}, {0, 2, 1, 3}));
} else if (has_mask) {
auto sdpa = std::make_shared<ov::op::v13::ScaledDotProductAttention>(q, k, v, mask, scale_node, causal);
res = std::make_shared<ov::op::v1::Transpose>(
sdpa, ov::op::v0::Constant::create(ov::element::i64, {4}, {0, 2, 1, 3}));
} else {
auto sdpa = std::make_shared<ov::op::v13::ScaledDotProductAttention>(q, k, v, scale_node, causal);
res = std::make_shared<ov::op::v1::Transpose>(
sdpa, ov::op::v0::Constant::create(ov::element::i64, {4}, {0, 2, 1, 3}));
}
res = std::make_shared<ov::op::v0::Convert>(res, ov::element::f32);
return rename_outputs_with_suffix({res}, context.get_name());
}
} } } }