Copyright (c) Huawei Technologies Co., Ltd. 2026. All rights reserved.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
==============================================================================*/
#include <iostream>
#include <set>
#include <cmath>
#include <cstring>
#include "register/register_custom_pass.h"
#include "all_ops.h"
using namespace ge;
enum LogLevel {
LOG_INFO,
LOG_WARN,
LOG_ERROR
};
static std::string GetFileName(const char* path)
{
std::string s(path);
size_t pos = s.find_last_of("/\\");
if (pos == std::string::npos)
{
return s;
}
return s.substr(pos + 1);
}
inline std::ostream& LogStream(LogLevel level, const char* file, int line)
{
switch (level)
{
case LOG_INFO:
std::cout << "[INFO] ";
break;
case LOG_WARN:
std::cout << "[WARN] ";
break;
case LOG_ERROR:
std::cout << "[ERROR] ";
break;
default:
std::cout << "[UNKNOWN] ";
break;
}
std::cout << "[File:" << GetFileName(file) << ":" << line << "]: ";
return std::cout;
}
#define LOG(level) LogStream(level, __FILE__, __LINE__)
namespace {
constexpr const char* const kTypeReduceSumD = "ReduceSumD";
constexpr const char* const kTypeCast = "Cast";
constexpr const char* const kTypeReduceSum = "ReduceSum";
constexpr const char* const kTypeConst = "Const";
constexpr const char* const kTypeConstant = "Constant";
constexpr const char* const kTypeSqrt = "Sqrt";
constexpr const char* const kTypeReduceMean = "ReduceMean";
constexpr const char* const kTypeAdd = "Add";
constexpr const char* const kTypeDiv = "RealDiv";
constexpr const char* const kTypeMul = "Mul";
constexpr const char* const kTypePow = "Pow";
constexpr const char* const kTypeTranspose = "Transpose";
constexpr const char* const kTypeBatchMatMul = "BatchMatMulV2";
constexpr const char* const kTypeSelectV2 = "SelectV2";
constexpr const char* const kTypeEqual = "Equal";
constexpr const char* const kTypeSoftmax = "SoftmaxV2";
constexpr const char* const kTypeRmsNorm = "RmsNorm";
constexpr const char* const kTypeReshape = "Reshape";
}
void FindNodesCanFusion(GraphPtr& graph, std::vector<GNode>& nodes_can_fusion)
{
for (const GNode& node : graph->GetAllNodes()) {
AscendString type;
node.GetType(type);
if (type == kTypeTranspose) {
nodes_can_fusion.emplace_back(node);
}
}
}
bool CheckOutputNum(GNodePtr node, size_t output_num = 1) {
if (node == nullptr) {
return false;
}
auto output_list = node->GetOutDataNodesAndPortIndexs(0);
auto ret = output_list.size() == output_num;
if (!ret) {
AscendString node_name;
node -> GetName(node_name);
LOG(LOG_ERROR) << "node: " << node_name.GetString() << " expects " << output_num << " outputs, but actuall has " << output_list.size() << " outputs" << std::endl;
}
return ret;
}
struct FaContext {
GNodePtr end_transpose_node;
GNodePtr end_transpose_perm_node;
GNodePtr att_out_bmm_node;
GNodePtr v_transpose_node;
GNodePtr v_transpose_perm_node;
GNodePtr end_select_node;
GNodePtr end_select_false_const_node;
GNodePtr redundant_cast0_node;
GNodePtr redundant_cast1_node;
GNodePtr softmax_node;
GNodePtr mask_equal_node;
GNodePtr mask_equal_const_node;
GNodePtr mask_cast_node;
GNodePtr top_select_node;
GNodePtr top_select_false_const_node;
GNodePtr qk_scale_mul_node;
GNodePtr qk_scale_mul_const_node;
GNodePtr attn_score_node;
GNodePtr q_transpose_node;
GNodePtr q_transpose_perm_node;
GNodePtr k_transpose_node;
GNodePtr k_transpose_perm_node;
float scale;
int32_t head_num;
bool is_match = false;
};
graphStatus ReplaceOp(GraphPtr& graph, const FaContext& ctx)
{
LOG(LOG_INFO) << "start to reaplace op" << std::endl;
AscendString att_node_name;
auto ret = ctx.attn_score_node -> GetName(att_node_name);
if (ret != GRAPH_SUCCESS) {
LOG(LOG_ERROR) << "get fa name failed" << std::endl;
return GRAPH_FAILED;
}
AscendString mask_node_name;
ret = ctx.mask_cast_node -> GetName(mask_node_name);
if (ret != GRAPH_SUCCESS) {
LOG(LOG_ERROR) << "get fa mask name failed" << std::endl;
return GRAPH_FAILED;
}
std::string fa_mask_equal_name = std::string(mask_node_name.GetString()) + "/Equal";
op::Equal equal_op(fa_mask_equal_name);
GNode equal_gnode = graph->AddNodeByOp(equal_op);
std::string fa_mask_equal_const_name = std::string(mask_node_name.GetString()) + "/Equal_Const";
op::Const equal_const_op(fa_mask_equal_const_name);
TensorDesc equal_const_desc(ge::Shape({1}), FORMAT_ND, DT_INT32);
int32_t equal_const_val = 0;
Tensor equal_const_tensor(equal_const_desc, reinterpret_cast<const uint8_t*>(&equal_const_val), sizeof(int32_t));
equal_const_op.set_attr_value(equal_const_tensor);
if (equal_const_op.UpdateOutputDesc(static_cast<uint32_t>(0), equal_const_desc) != GRAPH_SUCCESS) {
LOG(LOG_ERROR) << "update equal const op desc failed" << std::endl;
return GRAPH_FAILED;
}
if (equal_const_op.InferShapeAndType() != GRAPH_SUCCESS) {
LOG(LOG_ERROR) << "infershape to equal const op failed" << std::endl;
return GRAPH_FAILED;
}
GNode equal_const_gnode = graph->AddNodeByOp(equal_const_op);
auto cast_input_node_pair = ctx.mask_cast_node -> GetInDataNodesAndPortIndexs(0);
TensorDesc ori_cast_input_output_desc;
if (cast_input_node_pair.first -> GetInputDesc(0, ori_cast_input_output_desc) != GRAPH_SUCCESS) {
LOG(LOG_ERROR) << "get ori cast input output desc failed" << std::endl;
return GRAPH_FAILED;
}
TensorDesc equal_input0_desc(ori_cast_input_output_desc);
TensorDesc equal_input1_desc(equal_const_desc);
if (equal_gnode.UpdateInputDesc(0, equal_input0_desc) != GRAPH_SUCCESS) {
LOG(LOG_ERROR) << "update equal input0 desc failed" << std::endl;
return GRAPH_FAILED;
}
if (equal_gnode.UpdateInputDesc(1, equal_input1_desc) != GRAPH_SUCCESS) {
LOG(LOG_ERROR) << "update equal input1 desc failed" << std::endl;
return GRAPH_FAILED;
}
if (equal_op.InferShapeAndType() != GRAPH_SUCCESS) {
LOG(LOG_ERROR) << "infer mask cast shape and type failed" << std::endl;
return GRAPH_FAILED;
}
if (graph -> AddDataEdge(*cast_input_node_pair.first, cast_input_node_pair.second, equal_gnode, 0) != GRAPH_SUCCESS) {
LOG(LOG_ERROR) << "add data edge to mask equal node failed" << std::endl;
return GRAPH_FAILED;
}
if (graph -> AddDataEdge(equal_const_gnode, 0, equal_gnode, 1) != GRAPH_SUCCESS) {
LOG(LOG_ERROR) << "add edge equal const node to mask equal node failed" << std::endl;
return GRAPH_FAILED;
}
std::string fa_name = std::string(att_node_name.GetString()) + "/FlashAttention";
op::FlashAttentionScore fa_op(fa_name);
fa_op.set_attr_scale_value(ctx.scale);
fa_op.set_attr_head_num(ctx.head_num);
fa_op.set_attr_input_layout("BSND");
GNode fa_gnode = graph->AddNodeByOp(fa_op);
auto q_input_node_pair = ctx.q_transpose_node -> GetInDataNodesAndPortIndexs(0);
auto k_input_node_pair = ctx.k_transpose_node -> GetInDataNodesAndPortIndexs(0);
auto v_input_node_pair = ctx.v_transpose_node -> GetInDataNodesAndPortIndexs(0);
TensorDesc q_input_desc, k_input_desc, v_input_desc, mask_input_desc;
if (q_input_node_pair.first -> GetInputDesc(0, q_input_desc) != GRAPH_SUCCESS) {
LOG(LOG_ERROR) << "get q input desc failed" << std::endl;
return GRAPH_FAILED;
}
if (k_input_node_pair.first -> GetInputDesc(0, k_input_desc) != GRAPH_SUCCESS) {
LOG(LOG_ERROR) << "get k input desc failed" << std::endl;
return GRAPH_FAILED;
}
if (v_input_node_pair.first -> GetInputDesc(0, v_input_desc) != GRAPH_SUCCESS) {
LOG(LOG_ERROR) << "get v input desc failed" << std::endl;
return GRAPH_FAILED;
}
if (equal_gnode.GetOutputDesc(0, mask_input_desc) != GRAPH_SUCCESS) {
LOG(LOG_ERROR) << "get mask input desc failed" << std::endl;
return GRAPH_FAILED;
}
TensorDesc fa_q_input_desc(q_input_desc);
TensorDesc fa_k_input_desc(k_input_desc);
TensorDesc fa_v_input_desc(v_input_desc);
TensorDesc fa_mask_input_desc(mask_input_desc);
if (fa_gnode.UpdateInputDesc(0, fa_q_input_desc) != GRAPH_SUCCESS) {
LOG(LOG_ERROR) << "update fa q input desc failed" << std::endl;
return GRAPH_FAILED;
}
if (fa_gnode.UpdateInputDesc(1, fa_k_input_desc) != GRAPH_SUCCESS) {
LOG(LOG_ERROR) << "update fa k input desc failed" << std::endl;
return GRAPH_FAILED;
}
if (fa_gnode.UpdateInputDesc(2, fa_v_input_desc) != GRAPH_SUCCESS) {
LOG(LOG_ERROR) << "update fa v input desc failed" << std::endl;
return GRAPH_FAILED;
}
if (fa_gnode.UpdateInputDesc(6, mask_input_desc) != GRAPH_SUCCESS) {
LOG(LOG_ERROR) << "update fa mask input desc failed" << std::endl;
return GRAPH_FAILED;
}
fa_op.SetInput("atten_mask", equal_op);
if (fa_op.InferShapeAndType() != GRAPH_SUCCESS) {
LOG(LOG_ERROR) << "infer fa shape and type failed" << std::endl;
return GRAPH_FAILED;
}
fa_op.BreakConnect();
if (graph -> AddDataEdge(*q_input_node_pair.first, q_input_node_pair.second, fa_gnode, 0) != GRAPH_SUCCESS) {
LOG(LOG_ERROR) << "add data edge q to fa node failed" << std::endl;
return GRAPH_FAILED;
}
if (graph -> AddDataEdge(*k_input_node_pair.first, k_input_node_pair.second, fa_gnode, 1) != GRAPH_SUCCESS) {
LOG(LOG_ERROR) << "add data edge k to fa node failed" << std::endl;
return GRAPH_FAILED;
}
if (graph -> AddDataEdge(*v_input_node_pair.first, v_input_node_pair.second, fa_gnode, 2) != GRAPH_SUCCESS) {
LOG(LOG_ERROR) << "add data edge v to fa node failed" << std::endl;
return GRAPH_FAILED;
}
if (graph -> AddDataEdge(equal_gnode, 0, fa_gnode, 6) != GRAPH_SUCCESS) {
LOG(LOG_ERROR) << "add data edge mask to fa node failed" << std::endl;
return GRAPH_FAILED;
}
auto outputs = ctx.end_transpose_node->GetOutDataNodesAndPortIndexs(0);
for (auto out_node : outputs) {
if (graph->RemoveEdge(*ctx.end_transpose_node, 0, *out_node.first, out_node.second) != GRAPH_SUCCESS) {
LOG(LOG_ERROR) << "remove end transpose output edge failed" << std::endl;
return GRAPH_FAILED;
}
if (graph->AddDataEdge(fa_gnode, 3, *out_node.first, out_node.second) != GRAPH_SUCCESS) {
LOG(LOG_ERROR) << "add edge fa to output failed" << std::endl;
return GRAPH_FAILED;
}
}
if (graph->RemoveNode(*ctx.end_transpose_node) != GRAPH_SUCCESS) {
LOG(LOG_ERROR) << "remove end transpose node failed" << std::endl;
return GRAPH_FAILED;
}
if (CheckOutputNum(ctx.end_transpose_perm_node, 0)) {
if (graph->RemoveNode(*ctx.end_transpose_perm_node) != GRAPH_SUCCESS) {
LOG(LOG_ERROR) << "remove end transpose perm node failed" << std::endl;
return GRAPH_FAILED;
}
}
if (graph->RemoveNode(*ctx.att_out_bmm_node) != GRAPH_SUCCESS) {
LOG(LOG_ERROR) << "remove att out bmm node failed" << std::endl;
return GRAPH_FAILED;
}
if (graph->RemoveNode(*ctx.v_transpose_node) != GRAPH_SUCCESS) {
LOG(LOG_ERROR) << "remove v transpose node failed" << std::endl;
return GRAPH_FAILED;
}
if (CheckOutputNum(ctx.v_transpose_perm_node, 0)) {
if (graph->RemoveNode(*ctx.v_transpose_perm_node) != GRAPH_SUCCESS) {
LOG(LOG_ERROR) << "remove v transpose perm node failed" << std::endl;
return GRAPH_FAILED;
}
}
if (graph->RemoveNode(*ctx.end_select_node) != GRAPH_SUCCESS) {
LOG(LOG_ERROR) << "remove end select node failed" << std::endl;
return GRAPH_FAILED;
}
if (CheckOutputNum(ctx.end_select_false_const_node, 0)) {
if (graph->RemoveNode(*ctx.end_select_false_const_node) != GRAPH_SUCCESS) {
LOG(LOG_ERROR) << "remove end select false const node failed" << std::endl;
return GRAPH_FAILED;
}
}
if (graph->RemoveNode(*ctx.redundant_cast0_node) != GRAPH_SUCCESS) {
LOG(LOG_ERROR) << "remove redundant cast 0 node failed" << std::endl;
return GRAPH_FAILED;
}
if (graph->RemoveNode(*ctx.redundant_cast1_node) != GRAPH_SUCCESS) {
LOG(LOG_ERROR) << "remove redundant cast 1 node failed" << std::endl;
return GRAPH_FAILED;
}
if (graph->RemoveNode(*ctx.softmax_node) != GRAPH_SUCCESS) {
LOG(LOG_ERROR) << "remove softmax node failed" << std::endl;
return GRAPH_FAILED;
}
if (graph->RemoveNode(*ctx.mask_equal_node) != GRAPH_SUCCESS) {
LOG(LOG_ERROR) << "remove mask equal node failed" << std::endl;
return GRAPH_FAILED;
}
if (CheckOutputNum(ctx.mask_equal_const_node, 0)) {
if (graph->RemoveNode(*ctx.mask_equal_const_node) != GRAPH_SUCCESS) {
LOG(LOG_ERROR) << "remove mask equal const node failed" << std::endl;
return GRAPH_FAILED;
}
}
if (graph->RemoveNode(*ctx.mask_cast_node) != GRAPH_SUCCESS) {
LOG(LOG_ERROR) << "remove mask cast node failed" << std::endl;
return GRAPH_FAILED;
}
if (graph->RemoveNode(*ctx.top_select_node) != GRAPH_SUCCESS) {
LOG(LOG_ERROR) << "remove top select node failed" << std::endl;
return GRAPH_FAILED;
}
if (CheckOutputNum(ctx.top_select_false_const_node, 0)) {
if (graph->RemoveNode(*ctx.top_select_false_const_node) != GRAPH_SUCCESS) {
LOG(LOG_ERROR) << "remove top select false const node failed" << std::endl;
return GRAPH_FAILED;
}
}
if (graph->RemoveNode(*ctx.qk_scale_mul_node) != GRAPH_SUCCESS) {
LOG(LOG_ERROR) << "remove qk scale mul node failed" << std::endl;
return GRAPH_FAILED;
}
if (CheckOutputNum(ctx.qk_scale_mul_const_node, 0)) {
if (graph->RemoveNode(*ctx.qk_scale_mul_const_node) != GRAPH_SUCCESS) {
LOG(LOG_ERROR) << "remove qk scale mul const node failed" << std::endl;
return GRAPH_FAILED;
}
}
if (graph->RemoveNode(*ctx.attn_score_node) != GRAPH_SUCCESS) {
LOG(LOG_ERROR) << "remove attn score node failed" << std::endl;
return GRAPH_FAILED;
}
if (graph->RemoveNode(*ctx.q_transpose_node) != GRAPH_SUCCESS) {
LOG(LOG_ERROR) << "remove q transpose node failed" << std::endl;
return GRAPH_FAILED;
}
if (CheckOutputNum(ctx.q_transpose_perm_node, 0)) {
if (graph->RemoveNode(*ctx.q_transpose_perm_node) != GRAPH_SUCCESS) {
LOG(LOG_ERROR) << "remove q transpose perm node failed" << std::endl;
return GRAPH_FAILED;
}
}
if (graph->RemoveNode(*ctx.k_transpose_node) != GRAPH_SUCCESS) {
LOG(LOG_ERROR) << "remove k transpose node failed" << std::endl;
return GRAPH_FAILED;
}
if (CheckOutputNum(ctx.k_transpose_perm_node, 0)) {
if (graph->RemoveNode(*ctx.k_transpose_perm_node) != GRAPH_SUCCESS) {
LOG(LOG_ERROR) << "remove k transpose perm node failed" << std::endl;
return GRAPH_FAILED;
}
}
return GRAPH_SUCCESS;
}
bool CheckConstNode(GNodePtr node) {
AscendString node_type;
node -> GetType(node_type);
return node_type == kTypeConst || node_type == kTypeConstant;
}
bool CheckNodeType(GNodePtr node, const char* type) {
AscendString node_type;
node -> GetType(node_type);
auto ret = node_type == type;
if (!ret) {
LOG(LOG_ERROR) << "node type is not: " << type << ", is: " << node_type.GetString() << std::endl;
}
return ret;
}
bool CheckTransposePerm(GNode& node, const std::vector<int32_t>& target_perm = {0, 2, 1, 3})
{
Tensor transpose_perm_tensor;
auto ret = node.GetInputConstData(1, transpose_perm_tensor);
if (ret != GRAPH_SUCCESS)
{
LOG(LOG_ERROR) << "get input const data failed" << std::endl;
return false;
}
if (transpose_perm_tensor.GetDataType() != DT_INT32)
{
LOG(LOG_ERROR) << "dtype is not int32, is: " << transpose_perm_tensor.GetDataType() << std::endl;
return false;
}
size_t size = transpose_perm_tensor.GetSize();
if (size != target_perm.size() * sizeof(int32_t))
{
LOG(LOG_ERROR) << "perm size is not: " << target_perm.size() * sizeof(int32_t) << ", is: " << size << std::endl;
return false;
}
int32_t* data = reinterpret_cast<int32_t*>(transpose_perm_tensor.GetData());
for (size_t i = 0; i < size / sizeof(int32_t); i++)
{
if (data[i] != target_perm[i])
{
LOG(LOG_ERROR) << "perm is not the same, perm[" << i << "] is:" << data[i] << std::endl;
return false;
}
}
return true;
}
graphStatus MatchFaPattern(GraphPtr& graph, FaContext& ctx) {
auto att_out_bmm_node = ctx.end_transpose_node -> GetInDataNodesAndPortIndexs(0).first;
if (!CheckNodeType(att_out_bmm_node, kTypeBatchMatMul)) {
LOG(LOG_ERROR) << "check att out bmm node op type failed" << std::endl;
return GRAPH_SUCCESS;
}
if (!CheckOutputNum(att_out_bmm_node)) {
LOG(LOG_ERROR) << "check att out bmm node output num failed" << std::endl;
return GRAPH_SUCCESS;
}
ctx.att_out_bmm_node = att_out_bmm_node;
auto v_transpose_node = att_out_bmm_node -> GetInDataNodesAndPortIndexs(1).first;
if (!CheckNodeType(v_transpose_node, kTypeTranspose)) {
LOG(LOG_ERROR) << "check v transpose node op type failed" << std::endl;
return GRAPH_SUCCESS;
}
if (!CheckOutputNum(att_out_bmm_node)) {
LOG(LOG_ERROR) << "check v transpose node output num failed" << std::endl;
return GRAPH_SUCCESS;
}
ctx.v_transpose_node = v_transpose_node;
auto v_transpose_perm_node = v_transpose_node -> GetInDataNodesAndPortIndexs(1).first;
if (!CheckConstNode(v_transpose_perm_node)) {
LOG(LOG_ERROR) << "check v transpose perm node op type failed" << std::endl;
return GRAPH_SUCCESS;
}
if (!CheckTransposePerm(*v_transpose_node)) {
LOG(LOG_ERROR) << "check v transpose perm failed" << std::endl;
return GRAPH_SUCCESS;
}
ctx.v_transpose_perm_node = v_transpose_perm_node;
auto end_select_node = att_out_bmm_node -> GetInDataNodesAndPortIndexs(0).first;
if (!CheckNodeType(end_select_node, kTypeSelectV2)) {
LOG(LOG_ERROR) << "check end select node type failed" << std::endl;
return GRAPH_SUCCESS;
}
if (!CheckOutputNum(end_select_node)) {
LOG(LOG_ERROR) << "check end select output num failed" << std::endl;
return GRAPH_SUCCESS;
}
ctx.end_select_node = end_select_node;
auto end_select_false_const_node = end_select_node -> GetInDataNodesAndPortIndexs(2).first;
if (!CheckConstNode(end_select_false_const_node)) {
LOG(LOG_ERROR) << "check end slect false const node op type failed" << std::endl;
return GRAPH_SUCCESS;
}
Tensor end_select_false_const_tensor;
auto ret = end_select_node->GetInputConstData(2, end_select_false_const_tensor);
if (ret != GRAPH_SUCCESS) {
LOG(LOG_ERROR) << "get end select input const tensor failed" << std::endl;
return GRAPH_SUCCESS;
}
if (end_select_false_const_tensor.GetDataType() != DT_BF16) {
if (end_select_false_const_tensor.GetDataType() != DT_FLOAT) {
LOG(LOG_ERROR) << "end select input const tensor dtype is not float or bf16" << std::endl;
return GRAPH_SUCCESS;
}
size_t size = end_select_false_const_tensor.GetSize();
if (size != sizeof(float)) {
LOG(LOG_ERROR) << "end select input const tensor's size is not 4" << std::endl;
return GRAPH_SUCCESS;
}
float* data_end_false = reinterpret_cast<float*>(end_select_false_const_tensor.GetData());
if (std::fabs(*data_end_false - 0.0f) > 1e-6f) {
std::cout << "end select input const is not 0" << std::endl;
return GRAPH_SUCCESS;
}
}
ctx.end_select_false_const_node = end_select_false_const_node;
auto mask_equal_node = end_select_node -> GetInDataNodesAndPortIndexs(0).first;
if (!CheckNodeType(mask_equal_node, kTypeEqual)) {
LOG(LOG_ERROR) << "check mask equal node type failed" << std::endl;
return GRAPH_SUCCESS;
}
if (!CheckOutputNum(mask_equal_node, 2)) {
LOG(LOG_ERROR) << "check mask equal output num failed" << std::endl;
return GRAPH_SUCCESS;
}
ctx.mask_equal_node = mask_equal_node;
auto mask_equal_const_node = mask_equal_node -> GetInDataNodesAndPortIndexs(1).first;
if (!CheckConstNode(mask_equal_const_node)) {
LOG(LOG_ERROR) << "check mask equal const node op type failed" << std::endl;
return GRAPH_SUCCESS;
}
Tensor mask_equal_const_tensor;
ret = mask_equal_node->GetInputConstData(1, mask_equal_const_tensor);
if (ret != GRAPH_SUCCESS) {
LOG(LOG_ERROR) << "get mask equal const tensor failed" << std::endl;
return GRAPH_FAILED;
}
if (mask_equal_const_tensor.GetDataType() != DT_INT64) {
LOG(LOG_ERROR) << "mask equal const tensor dtype is not int64" << std::endl;
return GRAPH_SUCCESS;
}
auto size = mask_equal_const_tensor.GetSize();
if (size != sizeof(int64_t)) {
LOG(LOG_ERROR) << "mask equal const tensor's size is not 8" << std::endl;
return GRAPH_SUCCESS;
}
ctx.mask_equal_const_node = mask_equal_const_node;
int64_t* data_mask_equal = reinterpret_cast<int64_t*>(mask_equal_const_tensor.GetData());
if (*data_mask_equal != 1) {
LOG(LOG_ERROR) << "mask equal const is not 1" << std::endl;
return GRAPH_SUCCESS;
}
auto mask_cast_node = mask_equal_node -> GetInDataNodesAndPortIndexs(0).first;
if (!CheckNodeType(mask_cast_node, kTypeCast)) {
LOG(LOG_ERROR) << "check mask cast type failed" << std::endl;
return GRAPH_SUCCESS;
}
if (!CheckOutputNum(mask_cast_node)) {
LOG(LOG_ERROR) << "check mask cast output num failed" << std::endl;
return GRAPH_SUCCESS;
}
TensorDesc mask_equal_cast_input_desc;
if (mask_cast_node -> GetInputDesc(0, mask_equal_cast_input_desc) != GRAPH_SUCCESS) {
LOG(LOG_ERROR) << "get mask equal cast input desc failed" << std::endl;
return GRAPH_FAILED;
}
if (mask_equal_cast_input_desc.GetDataType() != DT_INT32) {
LOG(LOG_ERROR) << "mask equal cast input dtype is not int32" << std::endl;
return GRAPH_SUCCESS;
}
ctx.mask_cast_node = mask_cast_node;
bool from_bf16 = false;
auto redundant_cast0_node = end_select_node -> GetInDataNodesAndPortIndexs(1).first;
if (!CheckNodeType(redundant_cast0_node, kTypeCast)) {
LOG(LOG_ERROR) << "check redundant cast0 type failed" << std::endl;
return GRAPH_SUCCESS;
}
if (!CheckOutputNum(redundant_cast0_node)) {
LOG(LOG_ERROR) << "check redundant cast0 output num failed" << std::endl;
return GRAPH_SUCCESS;
}
TensorDesc redundant_cast0_input_desc, redundant_cast0_output_desc;
if (redundant_cast0_node -> GetInputDesc(0, redundant_cast0_input_desc) != GRAPH_SUCCESS) {
LOG(LOG_ERROR) << "get redundant cast0 input desc failed" << std::endl;
return GRAPH_FAILED;
}
if (redundant_cast0_input_desc.GetDataType() != DT_FLOAT) {
LOG(LOG_ERROR) << "redundant cast0 input dtype is not float" << std::endl;
return GRAPH_SUCCESS;
}
if (redundant_cast0_node -> GetOutputDesc(0, redundant_cast0_output_desc) != GRAPH_SUCCESS) {
LOG(LOG_ERROR) << "get redundant cast0 output desc failed" << std::endl;
return GRAPH_FAILED;
}
if (redundant_cast0_output_desc.GetDataType() != DT_FLOAT && redundant_cast0_output_desc.GetDataType() != DT_BF16) {
LOG(LOG_ERROR) << "redundant cast0 output dtype is not float nor bfloat16" << std::endl;
return GRAPH_SUCCESS;
}
if (redundant_cast0_output_desc.GetDataType() == DT_BF16) {
from_bf16=true;
}
ctx.redundant_cast0_node = redundant_cast0_node;
auto redundant_cast1_node = redundant_cast0_node -> GetInDataNodesAndPortIndexs(0).first;
if (!CheckNodeType(redundant_cast1_node, kTypeCast)) {
LOG(LOG_ERROR) << "check redundant cast1 type failed" << std::endl;
return GRAPH_SUCCESS;
}
if (!CheckOutputNum(redundant_cast1_node)) {
LOG(LOG_ERROR) << "check redundant cast1 output num failed" << std::endl;
return GRAPH_SUCCESS;
}
TensorDesc redundant_cast1_input_desc, redundant_cast1_output_desc;
if (redundant_cast1_node -> GetInputDesc(0, redundant_cast1_input_desc) != GRAPH_SUCCESS) {
LOG(LOG_ERROR) << "get redundant cast1 input desc failed" << std::endl;
return GRAPH_FAILED;
}
if (from_bf16) {
if (redundant_cast1_input_desc.GetDataType() != DT_BF16) {
LOG(LOG_ERROR) << "redundant cast1 input dtype is not bf16" << std::endl;
return GRAPH_SUCCESS;
}
} else {
if (redundant_cast1_input_desc.GetDataType() != DT_FLOAT) {
LOG(LOG_ERROR) << "redundant cast1 input dtype is not float" << std::endl;
return GRAPH_SUCCESS;
}
}
if (redundant_cast1_node -> GetOutputDesc(0, redundant_cast1_output_desc) != GRAPH_SUCCESS) {
LOG(LOG_ERROR) << "get redundant cast1 output desc failed" << std::endl;
return GRAPH_FAILED;
}
if (redundant_cast1_output_desc.GetDataType() != DT_FLOAT) {
LOG(LOG_ERROR) << "redundant cast1 cast output dtype is not float" << std::endl;
return GRAPH_SUCCESS;
}
ctx.redundant_cast1_node = redundant_cast1_node;
auto softmax_node = redundant_cast1_node -> GetInDataNodesAndPortIndexs(0).first;
if (!CheckNodeType(softmax_node, kTypeSoftmax)) {
LOG(LOG_ERROR) << "check softmax type failed" << std::endl;
return GRAPH_SUCCESS;
}
if (!CheckOutputNum(softmax_node)) {
LOG(LOG_ERROR) << "check softmax node output num failed" << std::endl;
return GRAPH_SUCCESS;
}
ctx.softmax_node = softmax_node;
auto top_select_node = softmax_node -> GetInDataNodesAndPortIndexs(0).first;
if (!CheckNodeType(top_select_node, kTypeSelectV2)) {
LOG(LOG_ERROR) << "check top select type failed--" << std::endl;
return GRAPH_SUCCESS;
}
if (!CheckOutputNum(top_select_node)) {
LOG(LOG_ERROR) << "check top select node output num failed" << std::endl;
return GRAPH_SUCCESS;
}
ctx.top_select_node = top_select_node;
auto top_select_false_const_node = top_select_node -> GetInDataNodesAndPortIndexs(2).first;
if (!CheckConstNode(top_select_false_const_node)) {
LOG(LOG_ERROR) << "check top select false const node op type failed" << std::endl;
return GRAPH_SUCCESS;
}
Tensor top_select_false_const_tensor;
ret = top_select_node->GetInputConstData(2, top_select_false_const_tensor);
if (ret != GRAPH_SUCCESS) {
LOG(LOG_ERROR) << "get top select input const tensor failed" << std::endl;
return GRAPH_SUCCESS;
}
if (top_select_false_const_tensor.GetDataType() != DT_BF16) {
if (top_select_false_const_tensor.GetDataType() != DT_FLOAT) {
LOG(LOG_ERROR) << "top select input const tensor dtype is not float nor bf16" << std::endl;
return GRAPH_SUCCESS;
}
size = top_select_false_const_tensor.GetSize();
if (size != sizeof(float)) {
LOG(LOG_ERROR) << "top select input const tensor's size is not 4" << std::endl;
return GRAPH_SUCCESS;
}
float* data_top_false = reinterpret_cast<float*>(top_select_false_const_tensor.GetData());
if (!std::isinf(*data_top_false) || !std::signbit(*data_top_false)) {
LOG(LOG_ERROR) << "top select input const is not -inf" << std::endl;
return GRAPH_SUCCESS;
}
}
ctx.top_select_false_const_node = top_select_false_const_node;
auto mask_equal_node_from_top = top_select_node -> GetInDataNodesAndPortIndexs(0).first;
AscendString mask_equal_node_name0;
AscendString mask_equal_node_name1;
mask_equal_node_from_top -> GetName(mask_equal_node_name0);
ctx.mask_equal_node -> GetName(mask_equal_node_name1);
if (strcmp(mask_equal_node_name0.GetString(), mask_equal_node_name1.GetString())) {
LOG(LOG_ERROR) << "mask cast is not the same, cast 0 is: " << mask_equal_node_name0.GetString() << ", cast 1 is: " << mask_equal_node_name1.GetString() << std::endl;
return GRAPH_SUCCESS;
}
auto qk_scale_mul_node = top_select_node -> GetInDataNodesAndPortIndexs(1).first;
if (!CheckNodeType(qk_scale_mul_node, kTypeMul)) {
LOG(LOG_ERROR) << "check qk scale mul type failed" << std::endl;
return GRAPH_SUCCESS;
}
if (!CheckOutputNum(qk_scale_mul_node)) {
LOG(LOG_ERROR) << "check qk scale mul node output num failed" << std::endl;
return GRAPH_SUCCESS;
}
ctx.qk_scale_mul_node = qk_scale_mul_node;
auto qk_scale_mul_const_node = qk_scale_mul_node -> GetInDataNodesAndPortIndexs(1).first;
if (!CheckConstNode(qk_scale_mul_const_node)) {
LOG(LOG_ERROR) << "check qk scale mul const node op type failed" << std::endl;
return GRAPH_SUCCESS;
}
ctx.qk_scale_mul_const_node = qk_scale_mul_const_node;
auto attn_score_node = qk_scale_mul_node -> GetInDataNodesAndPortIndexs(0).first;
if (!CheckNodeType(attn_score_node, kTypeBatchMatMul)) {
LOG(LOG_ERROR) << "check attn score type failed" << std::endl;
return GRAPH_SUCCESS;
}
if (!CheckOutputNum(attn_score_node)) {
LOG(LOG_ERROR) << "check attn score node output num failed" << std::endl;
return GRAPH_SUCCESS;
}
TensorDesc attn_score_input0_desc;
if (attn_score_node -> GetInputDesc(0, attn_score_input0_desc) != GRAPH_SUCCESS) {
LOG(LOG_ERROR) << "get attn score input0 input desc failed" << std::endl;
return GRAPH_FAILED;
}
Shape attn_score_input0_shape = attn_score_input0_desc.GetShape();
int64_t dim_d = attn_score_input0_shape.GetDim(3);
if (dim_d <= 0) {
LOG(LOG_ERROR) << "dim_d not large than 0" << std::endl;
return GRAPH_SUCCESS;
}
Tensor qk_mul_const_tensor;
ret = qk_scale_mul_node->GetInputConstData(1, qk_mul_const_tensor);
if (ret != GRAPH_SUCCESS) {
LOG(LOG_ERROR) << "get qk mul const tensor failed" << std::endl;
return GRAPH_SUCCESS;
}
float dim_float = static_cast<float>(dim_d);
float expect_scale = 1.0f / std::sqrt(dim_float);
if (qk_mul_const_tensor.GetDataType() != DT_BF16) {
if (qk_mul_const_tensor.GetDataType() != DT_FLOAT) {
LOG(LOG_ERROR) << "qk mul const tensor dtype is not float nor bf16" << std::endl;
return GRAPH_SUCCESS;
}
size = qk_mul_const_tensor.GetSize();
if (size != sizeof(float)) {
LOG(LOG_ERROR) << "qk mul const tensor's size is not 4" << std::endl;
return GRAPH_SUCCESS;
}
float* data_qk = reinterpret_cast<float*>(qk_mul_const_tensor.GetData());
float const_val = *data_qk;
if (std::isnan(const_val)) {
LOG(LOG_ERROR) << "qk scale mul const is NaN" << std::endl;
return GRAPH_SUCCESS;
}
if (std::isinf(const_val)) {
if (std::signbit(const_val)) {
LOG(LOG_ERROR) << "qk scale mul const is -inf" << std::endl;
} else {
LOG(LOG_ERROR) << "qk scale mul const is +inf" << std::endl;
}
return GRAPH_SUCCESS;
}
const float eps = 1e-6f;
if (std::fabs(const_val - expect_scale) > eps) {
LOG(LOG_ERROR) << "qk scale mul const mismatch, expect 1/sqrt(" << dim_d
<< ") = " << expect_scale << ", actual = " << const_val << std::endl;
return GRAPH_SUCCESS;
}
}
ctx.attn_score_node = attn_score_node;
ctx.scale = expect_scale;
auto q_transpose_node = attn_score_node -> GetInDataNodesAndPortIndexs(0).first;
if (!CheckNodeType(q_transpose_node, kTypeTranspose)) {
LOG(LOG_ERROR) << "check q transpose type failed" << std::endl;
return GRAPH_SUCCESS;
}
if (!CheckOutputNum(q_transpose_node)) {
LOG(LOG_ERROR) << "check q transpose node output num failed" << std::endl;
return GRAPH_SUCCESS;
}
ctx.q_transpose_node = q_transpose_node;
auto k_transpose_node = attn_score_node -> GetInDataNodesAndPortIndexs(1).first;
if (!CheckNodeType(k_transpose_node, kTypeTranspose)) {
LOG(LOG_ERROR) << "check k transpose type failed" << std::endl;
return GRAPH_SUCCESS;
}
if (!CheckOutputNum(k_transpose_node)) {
LOG(LOG_ERROR) << "check k transpose node output num failed" << std::endl;
return GRAPH_SUCCESS;
}
ctx.k_transpose_node = k_transpose_node;
auto q_transpose_perm_node = q_transpose_node -> GetInDataNodesAndPortIndexs(1).first;
if (!CheckConstNode(q_transpose_perm_node)) {
LOG(LOG_ERROR) << "check q transpose perm node op type failed" << std::endl;
return GRAPH_SUCCESS;
}
if (!CheckTransposePerm(*q_transpose_node)) {
LOG(LOG_ERROR) << "check q transpose perm failed" << std::endl;
return GRAPH_SUCCESS;
}
ctx.q_transpose_perm_node = q_transpose_perm_node;
auto k_transpose_perm_node = k_transpose_node -> GetInDataNodesAndPortIndexs(1).first;
if (!CheckConstNode(k_transpose_perm_node)) {
LOG(LOG_ERROR) << "check k transpose perm node op type failed" << std::endl;
return GRAPH_SUCCESS;
}
if (!CheckTransposePerm(*k_transpose_node, {0, 2, 3, 1})) {
LOG(LOG_ERROR) << "check k transpose perm failed" << std::endl;
return GRAPH_SUCCESS;
}
ctx.k_transpose_perm_node = k_transpose_perm_node;
auto q_rms_node = q_transpose_node -> GetInDataNodesAndPortIndexs(0).first;
if (!CheckNodeType(q_rms_node, kTypeRmsNorm)) {
LOG(LOG_ERROR) << "check q rms norm op type failed" << std::endl;
return GRAPH_SUCCESS;
}
auto q_reshape_node = q_rms_node -> GetInDataNodesAndPortIndexs(0).first;
if (!CheckNodeType(q_reshape_node, kTypeReshape)) {
LOG(LOG_ERROR) << "check q reshape op type failed" << std::endl;
return GRAPH_SUCCESS;
}
auto q_bmm_node = q_reshape_node -> GetInDataNodesAndPortIndexs(0).first;
if (!CheckNodeType(q_bmm_node, kTypeBatchMatMul)) {
LOG(LOG_ERROR) << "check q batch matmul op type failed" << std::endl;
return GRAPH_SUCCESS;
}
TensorDesc bmm_output_desc;
if (q_bmm_node -> GetOutputDesc(0, bmm_output_desc) != GRAPH_SUCCESS) {
LOG(LOG_ERROR) << "get bmm output failed" << std::endl;
return GRAPH_FAILED;
}
Shape bmm_output_shape = bmm_output_desc.GetShape();
int64_t dim_nd = bmm_output_shape.GetDim(2);
if (dim_nd <= 0) {
LOG(LOG_ERROR) << "dim nd not large than 0" << std::endl;
return GRAPH_SUCCESS;
}
if (dim_nd % dim_d != 0) {
LOG(LOG_ERROR) << "dim_nd % dim_d != 0" << std::endl;
return GRAPH_SUCCESS;
}
ctx.head_num = static_cast<int32_t>(dim_nd / dim_d);
ctx.is_match = true;
return GRAPH_SUCCESS;
}
graphStatus ReplaceOpWithFusionOp(GraphPtr& graph, GNode& node, CustomPassContext& context, int64_t& replaced_count)
{
AscendString node_name;
auto ret = node.GetName(node_name);
if (ret != GRAPH_SUCCESS) {
std::cout << "get node name failed" << std::endl;
return GRAPH_FAILED;
}
LOG(LOG_INFO) << "start deal with node: " << node_name.GetString() << std::endl;
auto transpose_perm_node = node.GetInDataNodesAndPortIndexs(1).first;
if (!CheckConstNode(transpose_perm_node)) {
LOG(LOG_ERROR) << "end transpose perm is not const" << std::endl;
return GRAPH_FAILED;
}
if (!CheckTransposePerm(node)) {
LOG(LOG_ERROR) << "check transpose perm failed" << std::endl;
return GRAPH_FAILED;
}
FaContext ctx;
ctx.end_transpose_node = std::shared_ptr<GNode>(&node, [](GNode*){});
ctx.end_transpose_perm_node = transpose_perm_node;
ret = MatchFaPattern(graph, ctx);
if (ret != GRAPH_SUCCESS) {
LOG(LOG_ERROR) << "match fa pattern failed" << std::endl;
return GRAPH_FAILED;
}
if (!ctx.is_match) {
return GRAPH_SUCCESS;
}
if (ReplaceOp(graph, ctx) != GRAPH_SUCCESS) {
LOG(LOG_ERROR) << "replace fa node failed" << std::endl;
return GRAPH_FAILED;
}
replaced_count += 1;
return GRAPH_SUCCESS;
}
graphStatus FaPass(GraphPtr& graph, CustomPassContext& context)
{
std::cout << "----------Fa Pass begin----------" << std::endl;
std::vector<GNode> node_list;
FindNodesCanFusion(graph, node_list);
if (node_list.empty()) {
std::cout << "Not found transpose node for Fa Pass" << std::endl;
return GRAPH_SUCCESS;
}
int64_t replaced_count = 0;
for (GNode& node : node_list) {
if (ReplaceOpWithFusionOp(graph, node, context, replaced_count) != GRAPH_SUCCESS) {
std::cout << "replace fusion op failed" << std::endl;
}
}
std::cout << "Fa Pass end, affect count: " << replaced_count << std::endl;
return GRAPH_SUCCESS;
}
REGISTER_CUSTOM_PASS("FaPass").CustomPassFn(FaPass).Stage(CustomPassStage::kAfterInferShape);