Eext.meisanyou1add_passes
1e790026Add on Aug 21History
#include <cstring>
#include <iostream>
#include <set>
#include <arm_neon.h>
#include <half.hpp>

#include "all_ops.h"
#include "ge_ir_build.h"
#include "register/register_custom_pass.h"
#include "moe_pass.h"

using namespace ge;
using namespace moe_pass_constants;
using half_float::half;

std::ostream& operator<<(std::ostream& os, const std::vector<long int>& vec) {
    os << "[";
    for (size_t i = 0; i < vec.size(); ++i) {
        os << vec[i];
        if (i != vec.size() - 1) {
            os << ", ";
        }
    }
    os << "]";
    return os;
}

std::ostream& operator<<(std::ostream& os, const std::vector<int32_t>& vec) {
    os << "[";
    for (size_t i = 0; i < vec.size(); ++i) {
        os << vec[i];
        if (i != vec.size() - 1) {
            os << ", ";
        }
    }
    os << "]";
    return os;
}

bool CheckConstType(AscendString mm_node_type)
{
    return mm_node_type == kTypeConst || mm_node_type == kTypeConstant;
}

bool CheckReshapeType(GNodePtr node, AscendString node_type)
{
    if (node_type == kTypeReshape) {
        auto reshape_shape_node = node->GetInDataNodesAndPortIndexs(1).first;
        AscendString reshape_shape_dtype;
        reshape_shape_node->GetType(reshape_shape_dtype);
        if (!CheckConstType(reshape_shape_dtype)) {
            std::cout << "------------reshape shape node is not const" << std::endl;
            return false;
        }    
    }
    return node_type == kTypeReshape || node_type == kTypeSqueeze || node_type == kTypeUnsqueeze || node_type == kTypeUnsqueezeV3;
}

void FindNodesCanFusion(GraphPtr& graph, std::vector<FusionNode>& root_nodes)
{
    for (GNode& node : graph->GetAllNodes()) {
        AscendString node_type;
        node.GetType(node_type);
        if (CheckConstType(node_type)) {
            continue;
        }
        size_t output_size = node.GetOutputsSize();

        for (int32_t i = 0; i < output_size; i++) {
            auto output_nodes = node.GetOutDataNodesAndPortIndexs(i);
            if (output_nodes.size() <= 1) {
                continue;
            }
            root_nodes.emplace_back(node, i);
        }
    }
}

bool CheckActivationTypeAvailable(AscendString dtype) {
    return  dtype == "Relu";
}

void batch_convert_to_fp16(const float* input, half_float::half* output, size_t elem_num) {
    const size_t neon_batch = 8;
    size_t aligned_num = elem_num - (elem_num % neon_batch);

    for (size_t i = 0; i < aligned_num; i += neon_batch) {
        float32x4_t float_vec1 = vld1q_f32(input + i);
        float32x4_t float_vec2 = vld1q_f32(input + i + 4);
        
        float16x4_t fp16_vec1 = vcvt_f16_f32(float_vec1);
        float16x4_t fp16_vec2 = vcvt_f16_f32(float_vec2);
        
        float16x8_t fp16_vec = vcombine_f16(fp16_vec1, fp16_vec2);
        vst1q_f16(reinterpret_cast<float16_t*>(output + i), fp16_vec);
    }

    for (size_t i = aligned_num; i < elem_num; ++i) {
        output[i] = static_cast<half_float::half>(input[i]);
    }
}

template <typename T>
void batch_convert_to_fp16(const T* input, half* output, size_t elem_num) {
    for (size_t i = 0; i < elem_num; ++i) {
        output[i] = (half)input[i];
    }
}

void print_float_buffer(const uint8_t* data, size_t byte_size, bool is_fp32) {
    using half_float::half;
    
    const size_t elem_size = is_fp32 ? sizeof(float) : sizeof(half);
    size_t count = byte_size / elem_size;
    if (count > 16) {
        count = 16;
    }
 
    for (size_t i = 0; i < count; ++i) {
        if (is_fp32) {
            float val;
            std::memcpy(&val, data + i*sizeof(float), sizeof(float));
            std::cout << val << " ";
        } else {
            half val;
            std::memcpy(&val, data + i*sizeof(half), sizeof(half));
            std::cout << float(val) << " "; // 转换为float便于输出
        }
    }
    std::cout << std::endl;
}

template <typename T>
graphStatus concat_matrics_to16(const std::vector<uint8_t*>& input_tensors, size_t k_dim, size_t n_dim, size_t concat_dim, uint8_t*& output_matric)
{
    if (input_tensors.empty()) {
        throw std::invalid_argument("input_tensors is empty!");
        return GRAPH_FAILED;
    }
    if (concat_dim != 0 && concat_dim != 1) {
        throw std::invalid_argument("concat_dim must be 0 or 1!");
        return GRAPH_FAILED;
    }
    if (output_matric == nullptr) {
        throw std::invalid_argument("output_matric is nullptr!");
        return GRAPH_FAILED;
    }

    const size_t tensor_num = input_tensors.size();
    const size_t total_n = n_dim * tensor_num; 
    const size_t k = k_dim;
    const size_t single_tensor_elem = n_dim * k_dim;
    half_float::half* output_fp16 = reinterpret_cast<half_float::half*>(output_matric);
    size_t current_n_offset = 0;

    static thread_local std::vector<T> trans_buf;
    if (trans_buf.size() < n_dim) {
        trans_buf.resize(n_dim);
    }

    size_t offset_1 = 0;  
    size_t offset_0 = 0;  
    for (size_t tensor_idx = 0; tensor_idx < tensor_num; ++tensor_idx) {
        std::cout << "msy_debug------------------------------tensor_idx: " << tensor_idx << "; fp 32 tensor is: ";
        uint8_t* input_tensor = input_tensors[tensor_idx];
        print_float_buffer(input_tensor, k_dim * n_dim * 4, true);
        if (input_tensor == nullptr) {
            std::cerr << "input_tensors[" << tensor_idx << "] is nullptr!" << std::endl;
            return GRAPH_FAILED;
        }
        T* input_data = reinterpret_cast<T*>(input_tensor);

        if (concat_dim == 1) {
            for (size_t i = 0; i < k; ++i) {
                T* input_batch = input_data + i * n_dim;
                half_float::half* output_batch = output_fp16 + i * total_n + offset_1;
                batch_convert_to_fp16<T>(input_batch, output_batch, n_dim);
            }
            std::cout << "fp 16 tensor is:";
            uint8_t* cur_out_matric = output_matric +  tensor_idx * n_dim * k_dim * 2;
            print_float_buffer(cur_out_matric, k_dim * n_dim * 2, false);     
            offset_1 += n_dim;
        } else {
            half_float::half* output_batch = output_fp16 + offset_0;
            batch_convert_to_fp16<T>(input_data, output_batch, single_tensor_elem);
            std::cout << "fp 16 tensor is:";
            uint8_t* cur_out_matric = output_matric +  tensor_idx * n_dim * k_dim * 2;
            print_float_buffer(cur_out_matric, k_dim * n_dim * 2, false);
            offset_0 += single_tensor_elem;
        }
    }

    return GRAPH_SUCCESS;
}

graphStatus CombinedConstTensor(const SingleLayerContext& ctx, bool to16, bool is_first_layer, Tensor& new_wieght_tensor) {
    size_t n_dim;
    size_t k_dim;
    size_t concat_dim;

    if (ctx.transpose_b) {
        n_dim = ctx.mm_const_shape.GetDim(0);
        k_dim = ctx.mm_const_shape.GetDim(1);
        concat_dim = 0;
    } else {
        n_dim = ctx.mm_const_shape.GetDim(1);
        k_dim = ctx.mm_const_shape.GetDim(0);
        concat_dim = 1;
    }

    if (!is_first_layer) {
        concat_dim = 0;
    }

    DataType dtype;
    std::vector<Tensor> tensor_storage;
    std::vector<uint8_t*> datas;
    for (auto mm_node: ctx.matmul_nodes) {
        Tensor const_tensor;
        if (mm_node -> GetInputConstData(1, const_tensor) != GRAPH_SUCCESS) {
            std::cout << "get input const data failed" << std::endl;
            return GRAPH_FAILED;
        }
        std::cout << "---------------------------in mm node tensor combine, tensor addr is: " << static_cast<void*>(const_tensor.GetData()) << "; value is:";
        print_float_buffer(const_tensor.GetData(), const_tensor.GetSize(), true);
        datas.push_back(const_tensor.GetData());
        tensor_storage.emplace_back(const_tensor);
        dtype = const_tensor.GetDataType();
    }

    if (!to16) {
        std::cout << "unsupport to 16 data" << std::endl;
        return GRAPH_FAILED;
    }

    if (dtype != DT_FLOAT) {
        std::cout << "unsupported input data type" << std::endl;
        return GRAPH_FAILED;
    }
    int32_t total_size = n_dim * k_dim * ctx.matmul_nodes.size() * sizeof(half);
    uint8_t* combined_data = new uint8_t[total_size];
    if (concat_matrics_to16<float>(datas, k_dim, n_dim, concat_dim, combined_data) != GRAPH_SUCCESS) {
        std::cout << "concat matrics to 16 failed" << std::endl;
        return GRAPH_FAILED;
    }

    AscendString ori_name;
    ctx.matmul_nodes[0] -> GetName(ori_name);
    std::string new_weight_name = std::string(ori_name.GetString()) + "/new_weight";
    op::Const new_weight(new_weight_name.c_str());

    Shape new_weight_shape;
    if (is_first_layer) {
        if (concat_dim  == 1) {
            new_weight_shape = Shape({k_dim, n_dim * ctx.matmul_nodes.size()});
        } else {
            new_weight_shape = Shape({n_dim * ctx.matmul_nodes.size(), k_dim});
        }
    } else {
        if (ctx.transpose_b) {
            new_weight_shape = Shape({ctx.matmul_nodes.size(), n_dim, k_dim});
        } else {
            new_weight_shape = Shape({ctx.matmul_nodes.size(), k_dim, n_dim});
        }
    }

    TensorDesc new_weight_desc(new_weight_shape, FORMAT_ND, DT_FLOAT16);
    new_weight_desc.SetOriginShape(new_weight_shape);
    new_wieght_tensor = Tensor(new_weight_desc, combined_data, total_size);
    delete[] combined_data;

    return GRAPH_SUCCESS;
}

graphStatus CombinedBiasTensor(const SingleLayerContext& ctx, bool to16, bool is_first_layer, Tensor& new_wieght_tensor) {
    int32_t n_dim = ctx.bias_const_shape.GetDim(0);
    int32_t k_dim = 1;
    int32_t concat_dim = 0;

    DataType dtype;
    std::vector<Tensor> tensor_storage;
    std::vector<uint8_t*> datas;
    for (auto bias_node: ctx.bias_nodes) {
        Tensor const_tensor;
        if (bias_node -> GetInputConstData(1, const_tensor) != GRAPH_SUCCESS) {
            if (bias_node -> GetInputConstData(0, const_tensor) != GRAPH_SUCCESS) {
                std::cout << "get input const data failed" << std::endl;
                return GRAPH_FAILED;
            }
        }
        datas.emplace_back(const_tensor.GetData());
        tensor_storage.emplace_back(const_tensor);
        dtype = const_tensor.GetDataType();
    }

    if (!to16) {
        std::cout << "unsupport to 16 data" << std::endl;
        return GRAPH_FAILED;
    }

    if (dtype != DT_FLOAT) {
        std::cout << "unsupported input data type" << std::endl;
        return GRAPH_FAILED;
    }
    int32_t total_size = n_dim * k_dim * ctx.bias_nodes.size() * sizeof(half);
    uint8_t* combined_data = new uint8_t[total_size];
    if (concat_matrics_to16<float>(datas, k_dim, n_dim, concat_dim, combined_data) != GRAPH_SUCCESS) {
        std::cout << "concat matrics to 16 failed" << std::endl;
        return GRAPH_FAILED;
    }

    Shape new_weight_shape;
    if (is_first_layer) {
        new_weight_shape = Shape({n_dim * ctx.matmul_nodes.size()});
    } else {
        new_weight_shape = Shape({ctx.matmul_nodes.size(), 1, n_dim});
    }

    AscendString ori_name;
    ctx.bias_nodes[0] -> GetName(ori_name);
    std::string new_weight_name = std::string(ori_name.GetString()) + "/new_weight";
    op::Const new_weight(new_weight_name.c_str());
    TensorDesc new_weight_desc(new_weight_shape, FORMAT_ND, DT_FLOAT16);
    new_weight_desc.SetOriginShape(new_weight_shape);
    new_wieght_tensor = Tensor(new_weight_desc, combined_data, total_size);
    delete[] combined_data;

    return GRAPH_SUCCESS;
}

bool MoePattern::FindNextCalcNode(GNodePtr src_node, GNodePtr& ret_node) 
{
    if (src_node == nullptr) {
        std::cout << "------------src node is null ptr" << std::endl;
        return false;
    }

    size_t output_size = src_node->GetOutputsSize();
    if (output_size != 1) {
        return false;
    }

    auto output_nodes = src_node->GetOutDataNodesAndPortIndexs(0);
    if (output_nodes.size() != 1) {
        return false;
    }

    auto output_node = output_nodes[0].first;
    AscendString output_dtype;
    output_node->GetType(output_dtype);

    if (output_dtype != kTypeReshape && output_dtype != kTypeSqueeze && output_dtype != kTypeUnsqueeze && output_dtype != kTypeUnsqueezeV3) {
        ret_node = output_node;
        return true;
    }

    if (output_dtype == kTypeReshape) {
        auto reshape_shape_node = output_node->GetInDataNodesAndPortIndexs(1).first;
        AscendString reshape_shape_dtype;
        reshape_shape_node->GetType(reshape_shape_dtype);
        if (!CheckConstType(reshape_shape_dtype)) {
            std::cout << "------------reshape shape node is not const" << std::endl;
            return false;
        }
    }

    return FindNextCalcNode(output_node, ret_node);
}  

bool MoePattern::FindNextCalcNodeWithPeerIndex(GNodePtr src_node, GNodePtr& ret_node, int32_t& peer_idx) 
{
    if (src_node == nullptr) {
        std::cout << "------------src node is null ptr" << std::endl;
        return false;
    }    

    size_t output_size = src_node->GetOutputsSize();
    if (output_size != 1) { 
        return false;
    }    

    auto output_nodes = src_node->GetOutDataNodesAndPortIndexs(0);
    if (output_nodes.size() != 1) { 
        return false;
    }    

    auto output_node = output_nodes[0].first;
    peer_idx = output_nodes[0].second;
    AscendString output_dtype;
    output_node->GetType(output_dtype);

    if (output_dtype != kTypeReshape && output_dtype != kTypeSqueeze && output_dtype != kTypeUnsqueeze && output_dtype != kTypeUnsqueezeV3) {
        ret_node = output_node;
        return true;
    }    

    if (output_dtype == kTypeReshape) {
        auto reshape_shape_node = output_node->GetInDataNodesAndPortIndexs(1).first;
        AscendString reshape_shape_dtype;
        reshape_shape_node->GetType(reshape_shape_dtype);
        if (!CheckConstType(reshape_shape_dtype)) {
            std::cout << "------------reshape shape node is not const" << std::endl;
            return false;
        }
    }    

    return FindNextCalcNodeWithPeerIndex(output_node, ret_node, peer_idx);
}

graphStatus MoePattern::ParseSingleLayer(GNodePtr src_node, bool is_first_node, GNodePtr& ret_node, SingleLayerContext& ctx, bool& success)
{
    AscendString src_name;
    src_node->GetName(src_name);
    std::cout << "--------start to parse single layer on node: " << src_name.GetString() << std::endl;
    success = false;
    GNodePtr mm_node;
    AscendString src_type;
    src_node -> GetType(src_type);
    if (src_type == kTypeMatmulV2 || src_type == kTypeBatchMatmulV2) {
        mm_node = src_node;
    } else if (is_first_node && !CheckReshapeType(src_node, src_type)) {
        std::cout << "--------src node is not matmul nor reshape" << std::endl;
        return GRAPH_SUCCESS;
    } else {
        if (!FindNextCalcNode(src_node, mm_node)) {
            std::cout << "--------not find next node" << std::endl;
            return GRAPH_SUCCESS;
        } 
    } 

    AscendString next_name;
    mm_node->GetName(next_name);
    std::cout << "--------next node name is: " << next_name.GetString() << std::endl;
    AscendString mm_node_type;
    mm_node -> GetType(mm_node_type);
    if (mm_node_type != kTypeMatmulV2 && mm_node_type != kTypeBatchMatmulV2) {
        std::cout << "--------next calc node is not Matmul" << std::endl;
        return GRAPH_SUCCESS;
    }

    auto mm_const_node = mm_node -> GetInDataNodesAndPortIndexs(1).first;
    AscendString const_mm_node_type;
    mm_const_node -> GetType(const_mm_node_type);

    if (!CheckConstType(const_mm_node_type)) {
        std::cout << "---------matmul right node is not const" << std::endl;
        return GRAPH_SUCCESS;
    }

    TensorDesc const_input_desc;
    if (mm_node -> GetInputDesc(1, const_input_desc)) {
        std::cout << "--------get const input desc failed" << std::endl;
        return GRAPH_FAILED;
    }

    ctx.mm_const_shape = const_input_desc.GetShape();
    if (ctx.mm_const_shape.GetDimNum() != 2) {
        std::cout << "--------const dims does not align" << std::endl;
        return GRAPH_SUCCESS;
    }

    TensorDesc mm_data_input_desc;
    if (mm_node -> GetInputDesc(0, mm_data_input_desc)) {
        std::cout << "--------get mm data input desc failed" << std::endl;
        return GRAPH_FAILED;
    }

    ctx.mm_shape = mm_data_input_desc.GetShape();

    if (mm_node_type == kTypeMatmulV2) {
        if (mm_node -> GetAttr(AscendString("transpose_x1"), ctx.transpose_a) != GRAPH_SUCCESS) {
            std::cout << "--------get transpose_x1 attr failed" << std::endl;
            return GRAPH_FAILED;
        }

        if (mm_node -> GetAttr(AscendString("transpose_x2"), ctx.transpose_b) != GRAPH_SUCCESS) {
            std::cout << "--------get transpose_x2 attr failed" << std::endl;
            return GRAPH_FAILED;
        }
        ctx.is_matmul = true;
    } else {
        if (mm_node -> GetAttr(AscendString("adj_x1"), ctx.transpose_a) != GRAPH_SUCCESS) {
            std::cout << "--------get adj_x1 attr failed" << std::endl;
            return GRAPH_FAILED;
        }

        if (mm_node -> GetAttr(AscendString("adj_x2"), ctx.transpose_b) != GRAPH_SUCCESS) {
            std::cout << "--------get adj_x2 attr failed" << std::endl;
            return GRAPH_FAILED;
        }        
        ctx.is_matmul = false;
    }

    int64_t n_dim;
    if (!ctx.transpose_b) {
        n_dim = ctx.mm_const_shape.GetDim(1);
    } else {
        n_dim = ctx.mm_const_shape.GetDim(0);
    }

    ctx.matmul_nodes.emplace_back(mm_node);
    ctx.matmul_const_nodes.emplace_back(mm_const_node);
    GNodePtr next_node;
    int32_t mm_peer_idx;
    if (!FindNextCalcNodeWithPeerIndex(mm_node, next_node, mm_peer_idx)) {
        std::cout << "--------not find next node" << std::endl;
        return GRAPH_SUCCESS;
    }    

    GNodePtr end_node = next_node;
    AscendString bias_node_name;
    next_node->GetName(bias_node_name);
    std::cout << "--------bias node name is: " << bias_node_name.GetString() << std::endl;
    AscendString next_node_type;
    next_node -> GetType(next_node_type);
    if (next_node_type == kTypeBiasAdd || next_node_type == kTypeAdd) {
        GNodePtr bias_node = next_node;
        int32_t const_idx = 1 - mm_peer_idx;
        auto bias_const_node = bias_node -> GetInDataNodesAndPortIndexs(const_idx).first;
        AscendString bias_const_type;
        bias_const_node -> GetType(bias_const_type);
        
        if (!CheckConstType(bias_const_type)) {
            std::cout << "---------bias is not from const" << std::endl;
            return GRAPH_SUCCESS;
        }

        TensorDesc bias_const_desc;
        if (bias_const_node -> GetOutputDesc(0, bias_const_desc) != GRAPH_SUCCESS) {
            std::cout << "get bias const desc failed" << std::endl;
            return GRAPH_FAILED;
        }

        Shape bias_const_shape = bias_const_desc.GetShape();
        if (bias_const_shape.GetDimNum() != 1) {
            std::cout << "bias dims is not 1" << std::endl;
            return GRAPH_SUCCESS;
        }

        int64_t bias_dim = bias_const_shape.GetDim(0);
        if (bias_dim != n_dim) {
            std::cout << "bias dims does not equal the n dim" << std::endl;
            return GRAPH_SUCCESS;
        }

        ctx.bias_nodes.emplace_back(bias_node);
        ctx.has_bias = true;
        ctx.bias_const_shape = bias_const_shape;
        ctx.bias_const_nodes.emplace_back(bias_const_node);
        if (!FindNextCalcNode(bias_node, next_node)) {
            std::cout << "--------not find bias add next node" << std::endl;
            return GRAPH_SUCCESS;
        }         
    }

    AscendString act_node_name;
    next_node->GetName(act_node_name);
    std::cout << "--------act node name is: " << act_node_name.GetString() << std::endl;
    ret_node = end_node;
    if (next_node->GetInputsSize() != 1) {
        std::cout << "--------no activation node" << std::endl;
        ctx.has_activation = false;
        success = true;
        return GRAPH_SUCCESS;
    }
    next_node -> GetType(next_node_type);
    if (!CheckActivationTypeAvailable(next_node_type)) {
        std::cout << "--------not available node" << std::endl;
        return GRAPH_SUCCESS;
    }
    ret_node = next_node;
    std::cout << "--------add node success" << std::endl;
    success = true;
    ctx.has_activation = true;
    ctx.activation_type = next_node_type;
    ctx.activation_nodes.emplace_back(next_node);
    return GRAPH_SUCCESS;
}

graphStatus MoePattern::ParseExpert(GraphPtr& graph, FusionNode& fusion_node, std::vector<MoeContext>& contexts, GNodePtr src_node)
{
    int32_t layers_count = 0;
    GNodePtr cur_node = src_node;
    GNodePtr next_node;
    MoeContext moe_ctx(graph, fusion_node);
    std::vector<SingleLayerContext> layer_ctxs;
    bool is_first_node = true;
    while (true) {
        bool success = false;
        SingleLayerContext layer_ctx;
        if (ParseSingleLayer(cur_node, is_first_node, next_node, layer_ctx, success) != GRAPH_SUCCESS) {
            std::cout << "----parse single layer failed" << std::endl;
            return GRAPH_FAILED;
        }   
        is_first_node = false;

        if (!success) {
            break;
        }

        layer_ctxs.emplace_back(layer_ctx);
        cur_node = next_node;
        layers_count++;
    }

    std::cout << "--------------------" << std::endl;
    if (layers_count < 2) {
        return GRAPH_SUCCESS;
    }

    int32_t peer_idx;
    if (!FindNextCalcNodeWithPeerIndex(cur_node, next_node, peer_idx)) {
        std::cout << "--------not find next node" << std::endl;
        return GRAPH_SUCCESS;
    }

    AscendString end_node_name;
    next_node->GetName(end_node_name);
    std::cout << "----end node name is:" << end_node_name.GetString() << "---------peer idx is: " << peer_idx << std::endl;
    AscendString end_node_type;
    next_node->GetType(end_node_type);   
    if (end_node_type != kTypeConcat && end_node_type != kTypeConcatD && end_node_type != kTypeConcatV2 && end_node_type != kTypePack) {
        std::cout << "----invalid end type" << std::endl;
        return GRAPH_SUCCESS;
    } 

    for (auto& ctx: layer_ctxs) {
        ctx.order.emplace_back(peer_idx);
    }
    if (contexts.size() == 0) {
        moe_ctx.SetLayers(layers_count);
        if (end_node_type == kTypeConcat || end_node_type == kTypeConcatD || end_node_type == kTypeConcatV2) {
            std::cout << "----first node type is const" << std::endl;
            moe_ctx.SetEndAsPack(false);
            moe_ctx.SetEndNode(next_node);
            std::cout << "*******************layer_ctxs's size is: " << layer_ctxs.size() << "; size in moe_ctx is: " << moe_ctx.GetLayerCtxs().size() << std::endl;
            moe_ctx.SetLayerCtxs(std::move(layer_ctxs));
            std::cout << "*******************layer_ctxs's size is: " << layer_ctxs.size() << "; size in moe_ctx is: " << moe_ctx.GetLayerCtxs().size() << std::endl;
            contexts.emplace_back(moe_ctx);
            return GRAPH_SUCCESS;
        } else if (end_node_type == kTypePack) {
            std::cout << "----first node type is pack" << std::endl;
            moe_ctx.SetEndAsPack(true);
            moe_ctx.SetEndNode(next_node);
            moe_ctx.SetLayerCtxs(std::move(layer_ctxs));
            contexts.emplace_back(moe_ctx);
            return GRAPH_SUCCESS;        
        }
        std::cout << "----end_node_type is not concat nor pack, is: " << end_node_type.GetString() << std::endl;
    } else {
        std::cout << "----start to compair end node" << std::endl;
        for (auto& ctx: contexts) {
            if (!ctx.CompareEndNode(next_node)) {
                std::cout << "end_node is not the same" << std::endl;
                continue;
            }
            std::cout << "----end to compair end node" << std::endl;

            if (ctx.GetLayerCtxs().size() != layer_ctxs.size()) { 
                std::cout << "layer size is not the same, ori size is: " << ctx.GetLayerCtxs().size() << "; current size is: " << layer_ctxs.size() << std::endl;
                continue; 
            }

            bool matches = true;
            for (int32_t i = 0; i < layers_count; i++) {
                SingleLayerContext& base_ctx = ctx.GetLayerCtxs()[i];
                SingleLayerContext& new_ctx = layer_ctxs[i];
                if (!base_ctx.CompapreAttrs(new_ctx)) {
                    std::cout << "single layer ctx is not the same" << std::endl;
                    matches = false;
                    break;
                }
            }
            if (!matches) {continue;}
            std::cout << "----end to compare attr" << std::endl;

            for (int32_t i = 0; i < layers_count; i++) {
                SingleLayerContext& base_ctx = ctx.GetLayerCtxs()[i];
                SingleLayerContext& new_ctx = layer_ctxs[i];            
                base_ctx.CombineExpert(new_ctx);
            }
            std::cout << "----combined single layer" << std::endl;
            return GRAPH_SUCCESS;
        }
        if (end_node_type == kTypeConcat || end_node_type == kTypeConcatD || end_node_type == kTypeConcatV2) {
            std::cout << "----first node type is const" << std::endl;
            moe_ctx.SetEndAsPack(false);
            moe_ctx.SetEndNode(next_node);
            std::cout << "*******************layer_ctxs's size is: " << layer_ctxs.size() << "; size in moe_ctx is: " << moe_ctx.GetLayerCtxs().size() << std::endl;
            moe_ctx.SetLayerCtxs(std::move(layer_ctxs));
            std::cout << "*******************layer_ctxs's size is: " << layer_ctxs.size() << "; size in moe_ctx is: " << moe_ctx.GetLayerCtxs().size() << std::endl;
            contexts.emplace_back(moe_ctx);
            return GRAPH_SUCCESS;
        } else if (end_node_type == kTypePack) {
            std::cout << "----first node type is pack" << std::endl;
            moe_ctx.SetEndAsPack(true);
            moe_ctx.SetEndNode(next_node);
            moe_ctx.SetLayerCtxs(std::move(layer_ctxs));
            contexts.emplace_back(moe_ctx);
            return GRAPH_SUCCESS;
        }
    }

    return GRAPH_SUCCESS;
}

graphStatus MoePattern::PatternMatch(GraphPtr& graph, FusionNode& fusion_node, std::vector<MoeContext>& ctx) {
    std::cout << "start to pattern match" << std::endl;
    GNode& src_node = fusion_node.node;
    int32_t output_idx = fusion_node.output_idx;

    AscendString src_name;
    src_node.GetName(src_name);
    std::cout << "----src node is:" << src_name.GetString() << "; output_idx is:" << output_idx << std::endl;
    auto output_pairs = src_node.GetOutDataNodesAndPortIndexs(output_idx);
    for (auto pair: output_pairs) {
        if (ParseExpert(graph, fusion_node, ctx, pair.first) != GRAPH_SUCCESS) {
            return GRAPH_FAILED;
        }
    }

    ctx.erase(
        std::remove_if(ctx.begin(), ctx.end(),
            [](const MoeContext& ctx) {
                return !ctx.CheckValidation();
            }
        ),
        ctx.end()
    );

    for (auto& single_ctx: ctx) {
        single_ctx.Reorder();
    }
    return GRAPH_SUCCESS;
}

graphStatus MoeContext::UpdateReshape(const SingleLayerContext& ctx, GNode& src_node, GNode& first_layer_end_node, GNode& end_node)
{
    GraphPtr graph = GetGraph();
    TensorDesc src_output_desc;
    if (src_node.GetOutputDesc(0, src_output_desc) != GRAPH_SUCCESS) {
        std::cout << "get src node output desc failed" << std::endl;
        return GRAPH_FAILED;
    }

    AscendString src_name;
    src_node.GetName(src_name);
    std::string shape_name = std::string(src_name.GetString()) + "/Shape";
    op::Shape shape_op(shape_name.c_str());
    GNode shape_gnode = graph -> AddNodeByOp(shape_op);

    TensorDesc shape_input_desc(src_output_desc);
    if (shape_gnode.UpdateInputDesc(0, shape_input_desc) != GRAPH_SUCCESS) {
        std::cout << "update shape input desc 0 failed" << std::endl;
        return GRAPH_FAILED;
    }

    if (shape_op.InferShapeAndType() != GRAPH_SUCCESS) {
        std::cout << "infershape to shape of shape op failed" << std::endl;
        return GRAPH_FAILED;
    }

    if (graph -> AddDataEdge(src_node, 0, shape_gnode, 0) != GRAPH_SUCCESS) {
        std::cout << "add data edge src node to shape node failed" << std::endl;
        return GRAPH_FAILED;
    }

    TensorDesc shape_output_desc;
    if (shape_gnode.GetOutputDesc(0, shape_output_desc) != GRAPH_SUCCESS) {
        std::cout << "get shape node output desc failed" << std::endl;
        return GRAPH_FAILED;
    }

    std::string slice_name = std::string(src_name.GetString()) + "/Slice";
    std::string slice_offsets_name = std::string(src_name.GetString()) + "/Slice_offsets";
    std::string slice_size_name = std::string(src_name.GetString()) + "/Slice_size";
    op::Slice slice_op(slice_name.c_str());
    op::Const slice_offsets_op(slice_offsets_name.c_str());
    op::Const slice_size_op(slice_size_name.c_str());
    slice_op.SetInput("offsets", slice_offsets_op);
    slice_op.SetInput("size", slice_size_op);

    TensorDesc slice_offsets_desc(ge::Shape({1}), FORMAT_ND, DT_INT32);
    int32_t slice_offsets_val = 0;
    Tensor slice_offsets_tensor(slice_offsets_desc, reinterpret_cast<const uint8_t*>(&slice_offsets_val), sizeof(int32_t));
    slice_offsets_op.set_attr_value(slice_offsets_tensor);
    GNode slice_offsets_gnode = graph->AddNodeByOp(slice_offsets_op);

    if (slice_offsets_op.UpdateOutputDesc(static_cast<uint32_t>(0), slice_offsets_desc) != GRAPH_SUCCESS) {
        std::cout << "update slice offsets op desc failed" << std::endl;
        return GRAPH_FAILED;
    }

    if (slice_offsets_op.InferShapeAndType() != GRAPH_SUCCESS) {
        std::cout << "infershape to slice offsets failed" << std::endl;
        return GRAPH_FAILED;
    }

    TensorDesc slice_size_desc(ge::Shape({1}), FORMAT_ND, DT_INT32);
    int32_t slice_size_val = ctx.mm_shape.GetDimNum() - 1;
    Tensor slice_size_tensor(slice_size_desc, reinterpret_cast<const uint8_t*>(&slice_size_val), sizeof(int32_t));
    slice_size_op.set_attr_value(slice_size_tensor);
    GNode slice_size_gnode = graph->AddNodeByOp(slice_size_op); 
    if (slice_size_op.UpdateOutputDesc(static_cast<uint32_t>(0), slice_size_desc) != GRAPH_SUCCESS) {
        std::cout << "update slice offsets op desc failed" << std::endl;
        return GRAPH_FAILED;
    }

    if (slice_size_op.InferShapeAndType() != GRAPH_SUCCESS) {
        std::cout << "infershape to slice offsets failed" << std::endl;
        return GRAPH_FAILED;
    }

    GNode slice_gnode = graph->AddNodeByOp(slice_op);
    if (graph->AddDataEdge(shape_gnode, 0, slice_gnode, 0) != GRAPH_SUCCESS) {
        std::cout << "add edge shape node to slice node failed" << std::endl;
        return GRAPH_FAILED;
    }
    if (graph->AddDataEdge(slice_offsets_gnode, 0, slice_gnode, 1) != GRAPH_SUCCESS) {
        std::cout << "add edge slice offsets to slice node failed" << std::endl;
        return GRAPH_FAILED;
    }
    if (graph->AddDataEdge(slice_size_gnode, 0, slice_gnode, 2) != GRAPH_SUCCESS) {
        std::cout << "add edge slice size to slice node failed" << std::endl;
        return GRAPH_FAILED;
    }

    TensorDesc slice_input_desc0(shape_output_desc);
    TensorDesc slice_input_desc1(slice_offsets_desc);
    TensorDesc slice_input_desc2(slice_size_desc);
    slice_input_desc1.SetOriginShape(ge::Shape({1}));
    slice_input_desc2.SetOriginShape(ge::Shape({1}));
    if (slice_op.UpdateInputDesc(static_cast<uint32_t>(0), slice_input_desc0) != GRAPH_SUCCESS) {
        std::cout << "update slice input desc 0 failed" << std::endl;
        return GRAPH_FAILED;
    }
    if (slice_op.UpdateInputDesc(static_cast<uint32_t>(1), slice_input_desc1) != GRAPH_SUCCESS) {
        std::cout << "update slice input desc 1 failed" << std::endl;
        return GRAPH_FAILED;
    }
    if (slice_op.UpdateInputDesc(static_cast<uint32_t>(2), slice_input_desc2) != GRAPH_SUCCESS) {
        std::cout << "update slice input desc 2 failed" << std::endl;
        return GRAPH_FAILED;
    }
    if (slice_op.InferShapeAndType() != GRAPH_SUCCESS) {
        std::cout << "infershape to slice op failed" << std::endl;
        return GRAPH_FAILED;
    }
    slice_op.BreakConnect();

    TensorDesc slice_output_desc;
    if (slice_gnode.GetOutputDesc(0, slice_output_desc) != GRAPH_SUCCESS) {
        std::cout << "get slice node output desc failed" << std::endl;
        return GRAPH_FAILED;
    }

    std::string concat_name = std::string(src_name.GetString()) + "/Concat";
    std::string concat_const_name = std::string(src_name.GetString()) + "/Concat_const";
    op::ConcatD concat_op;
    concat_op = op::ConcatD(concat_name).create_dynamic_input_x(2);
    op::Const concat_const_op(concat_const_name);
    concat_op.SetInput("x", 1, concat_const_op);
    concat_op.set_attr_concat_dim(0);
    concat_op.set_attr_N(2);
    GNode concat_gnode = graph->AddNodeByOp(concat_op);
    AscendString concat_gnode_name;
    concat_gnode.GetName(concat_gnode_name);
    std::cout << "111concat gnode_name is: " <<concat_gnode_name.GetString() << std::endl;
    
    int32_t n_dim;
    if (ctx.transpose_b) {
        n_dim = ctx.mm_const_shape.GetDim(0);
    } else {
        n_dim = ctx.mm_const_shape.GetDim(1);
    }
    ge::Shape concat_const_shape = ge::Shape({2});
    TensorDesc concat_const_desc(concat_const_shape, FORMAT_ND, DT_INT32);
    concat_const_desc.SetOriginFormat(FORMAT_ND);
    concat_const_desc.SetOriginShape(concat_const_shape);
    std::cout << "msy_concat_dim_debug---------------------------------" << ctx.matmul_nodes.size() << "  " << n_dim << "  " << concat_const_shape.GetShapeSize() << " " << concat_const_desc.GetSize() << std::endl;
    std::vector<int32_t> concat_const_val{ctx.matmul_nodes.size(), n_dim};
    Tensor concat_const_tensor(concat_const_desc, reinterpret_cast<const uint8_t*>(concat_const_val.data()), concat_const_val.size() * sizeof(int32_t));
    concat_const_op.set_attr_value(concat_const_tensor);
    GNode concat_const_gnode = graph->AddNodeByOp(concat_const_op);

    if (concat_const_op.UpdateOutputDesc(static_cast<uint32_t>(0), concat_const_desc) != GRAPH_SUCCESS) {
        std::cout << "update concat const op desc failed" << std::endl;
        return GRAPH_FAILED;
    }

    if (concat_const_op.InferShapeAndType() != GRAPH_SUCCESS) {
        std::cout << "infershape to concat const op failed" << std::endl;
        return GRAPH_FAILED;
    }

    TensorDesc concat_input_desc0(slice_output_desc);
    TensorDesc concat_input_desc1(concat_const_desc);
    concat_input_desc1.SetOriginFormat(FORMAT_ND);
    concat_input_desc1.SetOriginShape(concat_const_shape);
    if (concat_op.UpdateDynamicInputDesc("x", 0, concat_input_desc0) != GRAPH_SUCCESS) {
        std::cout << "update concat input desc 0 failed" << std::endl;
        return GRAPH_FAILED;
    }
    if (concat_op.UpdateDynamicInputDesc("x", 1, concat_input_desc1) != GRAPH_SUCCESS) {
        std::cout << "update concat input desc 1 failed" << std::endl;
        return GRAPH_FAILED;
    }

    if (concat_op.InferShapeAndType() != GRAPH_SUCCESS) {
        std::cout << "infershape to concat op failed" << std::endl;
        return GRAPH_FAILED;
    }

    if (graph->AddDataEdge(slice_gnode, 0, concat_gnode, 0) != GRAPH_SUCCESS) {
        std::cout << "add edge slice node to concat gnode failed" << std::endl;
        return GRAPH_FAILED;
    }
    concat_gnode.GetName(concat_gnode_name);
    std::cout << "222concat gnode_name is: " <<concat_gnode_name.GetString() << std::endl;
    if (graph->AddDataEdge(concat_const_gnode, 0, concat_gnode, 1) != GRAPH_SUCCESS) {
        std::cout << "add edge concat const to concat node failed" << std::endl;
        return GRAPH_FAILED;
    }
    concat_op.BreakConnect();
 
    TensorDesc first_layer_output_desc;
    if (first_layer_end_node.GetOutputDesc(0, first_layer_output_desc) != GRAPH_SUCCESS) {
        std::cout << "get first layer end node output desc failed" << std::endl;
        return GRAPH_FAILED;
    }
    TensorDesc reshape_data_input_desc(first_layer_output_desc);

    TensorDesc concat_output_desc;
    if (concat_gnode.GetOutputDesc(0, concat_output_desc) != GRAPH_SUCCESS) {
        std::cout << "get concat node output desc failed" << std::endl;
        return GRAPH_FAILED;
    }
    TensorDesc reshape_shape_input_desc(concat_output_desc);

    std::string reshape_name = std::string(src_name.GetString()) + "/ReshapeNode";
    op::Reshape reshape_op(reshape_name.c_str());
    GNode reshape_gnode = graph->AddNodeByOp(reshape_op);

    if (graph->AddDataEdge(first_layer_end_node, 0, reshape_gnode, 0) != GRAPH_SUCCESS) {
        std::cout << "add edge end node to reshape failed" << std::endl;
        return GRAPH_FAILED;
    }
    if (graph->AddDataEdge(concat_gnode, 0, reshape_gnode, 1) != GRAPH_SUCCESS) {
        std::cout << "add edge reshape shape to reshape failed" << std::endl;
        return GRAPH_FAILED;
    }

    if (reshape_op.UpdateInputDesc(static_cast<uint32_t>(0), reshape_data_input_desc) != GRAPH_SUCCESS) {
        std::cout << "update reshape x op desc failed" << std::endl;
        return GRAPH_FAILED;
    }

    if (reshape_op.UpdateInputDesc(static_cast<uint32_t>(1), reshape_shape_input_desc) != GRAPH_SUCCESS) {
        std::cout << "update reshape shape op desc failed" << std::endl;
        return GRAPH_FAILED;
    }

    if (reshape_op.InferShapeAndType() != GRAPH_SUCCESS) {
        std::cout << "infershape to reshape failed" << std::endl;
        return GRAPH_FAILED;
    }
    reshape_op.BreakConnect();

    std::string transpose_name = std::string(src_name.GetString()) + "/Transpose";
    std::string transpose_perm_name = std::string(src_name.GetString()) + "/Transpose_perm";        
    op::Transpose transpose_op(transpose_name);
    op::Const transpose_perm_op(transpose_perm_name);

    size_t transpose_perm_size = ctx.mm_shape.GetDimNum() + 1;
    std::vector<int32_t> transpose_perm_val(transpose_perm_size);
    for (int32_t i = 0; i < transpose_perm_size; ++i) {
        transpose_perm_val[i] = i;
    }
    std::swap(transpose_perm_val[transpose_perm_size - 3], transpose_perm_val[transpose_perm_size - 2]);

    ge::Shape transpose_perm_shape = ge::Shape({transpose_perm_size});
    TensorDesc transpose_perm_desc(transpose_perm_shape, FORMAT_ND, DT_INT32);
    Tensor transpose_perm_tensor(transpose_perm_desc, reinterpret_cast<const uint8_t*>(transpose_perm_val.data()), transpose_perm_val.size() * sizeof(int32_t));
    transpose_perm_op.set_attr_value(transpose_perm_tensor);
    transpose_op.SetInput("perm", transpose_perm_op);

    if (transpose_perm_op.UpdateOutputDesc(static_cast<uint32_t>(0), transpose_perm_desc) != GRAPH_SUCCESS) {
        std::cout << "update transpose perm op desc failed" << std::endl;
        return GRAPH_FAILED;
    }

    if (transpose_perm_op.InferShapeAndType() != GRAPH_SUCCESS) {
        std::cout << "infershape to transpose perm op failed" << std::endl;
        return GRAPH_FAILED;
    }

    end_node = graph->AddNodeByOp(transpose_op);
    GNode transpose_perm_gnode = graph->AddNodeByOp(transpose_perm_op);

    TensorDesc reshape_output_desc;
    if (reshape_gnode.GetOutputDesc(0, reshape_output_desc) != GRAPH_SUCCESS) {
        std::cout << "get reshape node output desc failed" << std::endl;
        return GRAPH_FAILED;
    }

    TensorDesc transpose_input_desc0(reshape_output_desc);
    TensorDesc transpose_input_desc1(transpose_perm_desc);
    transpose_input_desc1.SetOriginShape(transpose_perm_shape);

    if (transpose_op.UpdateInputDesc(static_cast<uint32_t>(0), transpose_input_desc0) != GRAPH_SUCCESS) {
        std::cout << "update transpose input desc 0 failed" << std::endl;
        return GRAPH_FAILED;
    }
    if (transpose_op.UpdateInputDesc(static_cast<uint32_t>(1), transpose_input_desc1) != GRAPH_SUCCESS) {
        std::cout << "update transpose input desc 1 failed" << std::endl;
        return GRAPH_FAILED;
    }

    if (transpose_op.InferShapeAndType() != GRAPH_SUCCESS) {
        std::cout << "infershape to transpose op failed" << std::endl;
        return GRAPH_FAILED;
    }

    if (graph->AddDataEdge(reshape_gnode, 0, end_node, 0) != GRAPH_SUCCESS) {
        std::cout << "add edge reshape node to transpose gnode failed" << std::endl;
        return GRAPH_FAILED;
    }
    if (graph->AddDataEdge(transpose_perm_gnode, 0, end_node, 1) != GRAPH_SUCCESS) {
        std::cout << "add edge concat const to transpose node failed" << std::endl;
        return GRAPH_FAILED;
    }
    transpose_op.BreakConnect();
    
    return GRAPH_SUCCESS;
}

graphStatus MoeContext::UpdateOneLayer(const SingleLayerContext& ctx, bool to16, bool is_first_layer, GNode& src_node, GNode& end_node)
{
    GraphPtr graph = GetGraph();
    Tensor new_mm_const_tensor;
    if (CombinedConstTensor(ctx, to16, is_first_layer, new_mm_const_tensor) != GRAPH_SUCCESS) {
       std::cout << "combined const tensor failed" << std::endl;
       return GRAPH_FAILED;
    }    
    AscendString src_name;
    src_node.GetName(src_name);
    std::cout <<  "--------src name is: " << src_name.GetString() << std::endl;

    AscendString mm_const_name;
    ctx.matmul_const_nodes[0] -> GetName(mm_const_name);
    
    std::string new_mm_const_name = std::string(mm_const_name.GetString()) + "/combined";
    op::Const new_mm_const_op(new_mm_const_name);
    new_mm_const_op.set_attr_value(new_mm_const_tensor);

    GNode new_mm_const_gnode = graph -> AddNodeByOp(new_mm_const_op);
    TensorDesc new_mm_const_desc = new_mm_const_tensor.GetTensorDesc();
    if (new_mm_const_gnode.UpdateOutputDesc(0, new_mm_const_desc) != GRAPH_SUCCESS) {
        std::cout << "update new_mm_const_gnode output desc failed" << std::endl;
        return GRAPH_FAILED;
    }    
    
    AscendString mm_name;
    ctx.matmul_nodes[0] -> GetName(mm_name);
    std::string new_mm_name = std::string(mm_name.GetString()) + "/combined";

    ge::Operator new_matmul_op;     
    bool use_matmul = ctx.is_matmul && is_first_layer;
    if (use_matmul) {
        new_matmul_op = op::MatMulV2(new_mm_name.c_str());
    } else {
        new_matmul_op = op::BatchMatMulV2(new_mm_name.c_str());
    }    

    GNode new_matmul_gnode = graph->AddNodeByOp(new_matmul_op);
    if (graph->AddDataEdge(new_mm_const_gnode, 0, new_matmul_gnode, 1) != GRAPH_SUCCESS) {
        std::cout << "add edge new const to new matmul failed" << std::endl;
        return GRAPH_FAILED;
    }    

    TensorDesc mm_input_desc;
    if (is_first_layer) {
        if (ctx.matmul_nodes[0] -> GetInputDesc(0, mm_input_desc) != GRAPH_SUCCESS) {
            std::cout << "get mm input desc failed" << std::endl;
            return GRAPH_FAILED;
        }
        if (to16) {
            mm_input_desc.SetDataType(DT_FLOAT16);
        }
    }  else {
        if (src_node.GetInputDesc(0, mm_input_desc) != GRAPH_SUCCESS) {
            std::cout << "get mm input desc failed" << std::endl;
            return GRAPH_FAILED;
        }
    }   
    TensorDesc new_matmul_data_desc(mm_input_desc);
    TensorDesc new_matmul_const_desc(new_mm_const_desc);
    if (new_matmul_gnode.UpdateInputDesc(0, new_matmul_data_desc) != GRAPH_SUCCESS) {
        std::cout << "update new matmul data input desc failed" << std::endl;
        return GRAPH_FAILED;
    }    
    if (new_matmul_gnode.UpdateInputDesc(1, new_matmul_const_desc) != GRAPH_SUCCESS) {
        std::cout << "update new matmul const desc failed" << std::endl;
        return GRAPH_FAILED;
    }   
    Shape test_input_desc0 = new_matmul_data_desc.GetShape();
    Shape test_input_desc1 = new_matmul_const_desc.GetShape();
    std::cout << "------------mm new input desc0 shape is: " << test_input_desc0.GetDims() << "; input desc1 shape is:" << test_input_desc1.GetDims() << std::endl;
    bool transpose_a = ctx.transpose_a;
    bool transpose_b = ctx.transpose_b; 
    if (use_matmul) {
        if (new_matmul_gnode.SetAttr(AscendString("transpose_x1"), transpose_a) != GRAPH_SUCCESS) {
            std::cout << "mm node set adj_x1 attr failed" << std::endl;
            return GRAPH_FAILED;
        }
        if (new_matmul_gnode.SetAttr(AscendString("transpose_x2"), transpose_b) != GRAPH_SUCCESS) {
            std::cout << "mm node set adj_x2 attr failed" << std::endl;
            return GRAPH_FAILED;
        }
    } else {
        if (new_matmul_gnode.SetAttr(AscendString("adj_x1"), transpose_a) != GRAPH_SUCCESS) {
            std::cout << "mm node set adj_x1 attr failed" << std::endl;
            return GRAPH_FAILED;
        }
        if (new_matmul_gnode.SetAttr(AscendString("adj_x2"), transpose_b) != GRAPH_SUCCESS) {
            std::cout << "mm node set adj_x2 attr failed" << std::endl;
        }
    }
    if (new_matmul_op.InferShapeAndType() != GRAPH_SUCCESS) {
        std::cout << "infer new matmul op shape and type failed" << std::endl;
        return GRAPH_FAILED;
    }

    if (graph -> AddDataEdge(src_node, 0, new_matmul_gnode, 0) != GRAPH_SUCCESS) {
        std::cout << "add data edge src node to new mm failed" << std::endl;
        return GRAPH_FAILED;
    }

    end_node = new_matmul_gnode;
    if (ctx.has_bias) {
        Tensor new_bias_const_tensor;
        if (CombinedBiasTensor(ctx, to16, is_first_layer, new_bias_const_tensor) != GRAPH_SUCCESS) {
            std::cout << "combind bias tensor failed" << std::endl;
            return GRAPH_FAILED;
        }

        AscendString bias_const_name;
        ctx.bias_const_nodes[0] -> GetName(bias_const_name);

        std::string new_bias_const_name = std::string(bias_const_name.GetString()) + "/combined";
        op::Const new_bias_const_op(new_bias_const_name);
        new_bias_const_op.set_attr_value(new_bias_const_tensor);

        GNode new_bias_const_gnode = graph -> AddNodeByOp(new_bias_const_op);
        TensorDesc new_bias_const_desc = new_bias_const_tensor.GetTensorDesc();
        if (new_bias_const_gnode.UpdateOutputDesc(0, new_bias_const_desc) != GRAPH_SUCCESS) {
            std::cout << "update new_mm_const_gnode output desc failed" << std::endl;
            return GRAPH_FAILED;
        }

        AscendString bias_name;
        ctx.bias_nodes[0] -> GetName(bias_name);
        std::string new_bias_name = std::string(bias_name.GetString()) + "/combined";

        op::BiasAdd new_bias_op(new_bias_name.c_str());
        GNode new_bias_gnode = graph->AddNodeByOp(new_bias_op);
        if (graph->AddDataEdge(new_bias_const_gnode, 0, new_bias_gnode, 1) != GRAPH_SUCCESS) {
            std::cout << "add edge new const to new matmul failed" << std::endl;
            return GRAPH_FAILED;
        }

        TensorDesc end_output_desc;
        if (end_node.GetOutputDesc(0, end_output_desc) != GRAPH_SUCCESS) {
            std::cout << "get src output desc failed" << std::endl;
            return GRAPH_FAILED;
        }
        TensorDesc bias_data_input_desc(end_output_desc);
        TensorDesc bias_const_input_desc(new_bias_const_desc);

        if (new_bias_gnode.UpdateInputDesc(0, bias_data_input_desc) != GRAPH_SUCCESS) {
            std::cout << "update bias input desc 0 failed" << std::endl;
            return GRAPH_FAILED;
        }

        if (new_bias_gnode.UpdateInputDesc(1, bias_const_input_desc) != GRAPH_SUCCESS) {
            std::cout << "update bias input desc 1 failed" << std::endl;
            return GRAPH_FAILED;
        }

        if (new_bias_op.InferShapeAndType() != GRAPH_SUCCESS) {
            std::cout << "infer shape on new_bias op failed" << std::endl;
            return GRAPH_FAILED;
        }
 
        if (graph->AddDataEdge(end_node, 0, new_bias_gnode, 0) != GRAPH_SUCCESS) {
            std::cout << "add edge src_node to new biasadd failed" << std::endl;
            return GRAPH_FAILED;
        }

        end_node = new_bias_gnode;
    }

    if (ctx.has_activation) {
        AscendString act_name;
        ctx.activation_nodes[0] -> GetName(act_name);

        std::string new_act_name = std::string(act_name.GetString()) + "/new";
        ge::Operator new_act_op;
        if (ctx.activation_type == "Relu") {
            new_act_op = op::Relu(new_act_name);
        } else {
            std::cout << "unsupport activation node" << std::endl;
            return GRAPH_FAILED;
        }

        GNode new_act_gnode = graph->AddNodeByOp(new_act_op);
        TensorDesc end_output_desc;
        if (end_node.GetOutputDesc(0, end_output_desc) != GRAPH_SUCCESS) {
            std::cout << "get src output desc failed" << std::endl;
            return GRAPH_FAILED;
        }
        TensorDesc act_input_desc(end_output_desc);

        if (new_act_gnode.UpdateInputDesc(0, act_input_desc) != GRAPH_SUCCESS) {
            std::cout << "update act input desc 0 failed" << std::endl;
            return GRAPH_FAILED;
        }

        if (new_act_op.InferShapeAndType() != GRAPH_SUCCESS) {
            std::cout << "infer shape on new act op failed" << std::endl;
            return GRAPH_FAILED;
        }

        if (graph->AddDataEdge(end_node, 0, new_act_gnode, 0) != GRAPH_SUCCESS) {
            std::cout << "add edge src_node to new act failed" << std::endl;
            return GRAPH_FAILED;
        }
        end_node = new_act_gnode;
    }

    if (is_first_layer) {
        GNode first_layer_end_node = end_node;
        if (UpdateReshape(ctx, first_layer_end_node, first_layer_end_node, end_node) != GRAPH_SUCCESS) {
            std::cout << "update reshape after first layer failed" << std::endl;
            return GRAPH_FAILED;
        }
        std::cout << "--------msy_debug update first layer success" << std::endl;
    }

    return GRAPH_SUCCESS;
}

graphStatus MoeContext::UpdateEndTranspose(GNode& src_node, GNode& end_node) {
    GraphPtr graph = GetGraph();
    AscendString src_name;
    src_node.GetName(src_name);
    TensorDesc src_output_desc;
    if (src_node.GetOutputDesc(0, src_output_desc) != GRAPH_SUCCESS) {
        std::cout << "get src node ouptut desc node failed" << std::endl;
        return GRAPH_FAILED;
    }

    Shape src_output_shape = src_output_desc.GetShape();
    std::vector<int64_t> src_output_dims = src_output_shape.GetDims();
    int64_t target_n_dim;
    int64_t ori_concat_dim = src_output_dims.size() - 3;
    if (end_as_pack_) {
        if (end_node_ -> GetAttr("axis", target_n_dim) != GRAPH_SUCCESS) {
            std::cout << "get pack axis attr failed" << std::endl;
            return GRAPH_FAILED;
        }
        if (target_n_dim < 0) {
            TensorDesc pack_input_desc;
            if (end_node_ -> GetInputDesc(0, pack_input_desc) != GRAPH_SUCCESS) {
                std::cout << "get pack input desc failed" << std::endl;
                return GRAPH_FAILED;
            }
            Shape pack_input_shape = pack_input_desc.GetShape();
            target_n_dim = pack_input_shape.GetDimNum() + target_n_dim + 1;  
        }
    } else {
        if (end_node_ -> GetAttr("concat_dim", target_n_dim) != GRAPH_SUCCESS) {
            std::cout << "get pack axis attr failed" << std::endl;
            return GRAPH_FAILED;
        }
        if (target_n_dim < 0) {
            TensorDesc pack_input_desc;
            if (end_node_ -> GetInputDesc(0, pack_input_desc) != GRAPH_SUCCESS) {
                std::cout << "get pack input desc failed" << std::endl;
                return GRAPH_FAILED;
            }
            Shape pack_input_shape = pack_input_desc.GetShape();
            target_n_dim = pack_input_shape.GetDimNum() + target_n_dim;
        }
    }

    if (target_n_dim != ori_concat_dim) {
        std::string transpose_name = std::string(src_name.GetString()) + "/Transpose";
        std::string transpose_perm_name = std::string(src_name.GetString()) + "/Transpose_perm";
        op::Transpose transpose_op(transpose_name);
        op::Const transpose_perm_op(transpose_perm_name);

        size_t transpose_perm_size = src_output_dims.size();
        std::vector<int32_t> transpose_perm_val(transpose_perm_size);
        for (int32_t i = 0; i < transpose_perm_size; ++i) {
            if (ori_concat_dim < target_n_dim) {
                if (i < ori_concat_dim || i > target_n_dim) {
                    transpose_perm_val[i] = i;
                } else if (i >= ori_concat_dim && i < target_n_dim) {
                    transpose_perm_val[i] = i + 1;
                } else {
                    transpose_perm_val[i] = ori_concat_dim;
                }
            } else {
                if (i < target_n_dim || i > ori_concat_dim) {
                    transpose_perm_val[i] = i;
                } else if (i == target_n_dim) {
                    transpose_perm_val[i] = ori_concat_dim;
                } else {
                    transpose_perm_val[i] = i - 1;
                }
            }
        }
        std::cout << "msy_perm is: " << transpose_perm_val << std::endl;

        ge::Shape transpose_perm_shape = ge::Shape({transpose_perm_size});
        TensorDesc transpose_perm_desc(transpose_perm_shape, FORMAT_ND, DT_INT32);
        Tensor transpose_perm_tensor(transpose_perm_desc, reinterpret_cast<const uint8_t*>(transpose_perm_val.data()), transpose_perm_val.size() * sizeof(int32_t));
        transpose_perm_op.set_attr_value(transpose_perm_tensor);
        transpose_op.SetInput("perm", transpose_perm_op);

        if (transpose_perm_op.UpdateOutputDesc(static_cast<uint32_t>(0), transpose_perm_desc) != GRAPH_SUCCESS) {
            std::cout << "update transpose perm op desc failed" << std::endl;
            return GRAPH_FAILED;
        }

        if (transpose_perm_op.InferShapeAndType() != GRAPH_SUCCESS) {
            std::cout << "infershape to transpose perm op failed" << std::endl;
            return GRAPH_FAILED;
        }

        end_node = graph->AddNodeByOp(transpose_op);
        GNode transpose_perm_gnode = graph->AddNodeByOp(transpose_perm_op);

        TensorDesc reshape_output_desc;
        if (src_node.GetOutputDesc(0, reshape_output_desc) != GRAPH_SUCCESS) {
            std::cout << "get reshape node output desc failed" << std::endl;
            return GRAPH_FAILED;
        }

        TensorDesc transpose_input_desc0(reshape_output_desc);
        TensorDesc transpose_input_desc1(transpose_perm_desc);
        transpose_input_desc1.SetOriginShape(transpose_perm_shape);

        if (transpose_op.UpdateInputDesc(static_cast<uint32_t>(0), transpose_input_desc0) != GRAPH_SUCCESS) {
            std::cout << "update transpose input desc 0 failed" << std::endl;
            return GRAPH_FAILED;
        }
        if (transpose_op.UpdateInputDesc(static_cast<uint32_t>(1), transpose_input_desc1) != GRAPH_SUCCESS) {
            std::cout << "update transpose input desc 1 failed" << std::endl;
            return GRAPH_FAILED;
        }

        if (transpose_op.InferShapeAndType() != GRAPH_SUCCESS) {
            std::cout << "infershape to transpose op failed" << std::endl;
            return GRAPH_FAILED;
        }

        if (graph->AddDataEdge(src_node, 0, end_node, 0) != GRAPH_SUCCESS) {
            std::cout << "add edge reshape node to transpose gnode failed" << std::endl;
            return GRAPH_FAILED;
        }
        if (graph->AddDataEdge(transpose_perm_gnode, 0, end_node, 1) != GRAPH_SUCCESS) {
            std::cout << "add edge concat const to transpose node failed" << std::endl;
            return GRAPH_FAILED;
        }
        transpose_op.BreakConnect();       
    }

    return GRAPH_SUCCESS; 
}

graphStatus MoeContext::UpdateMoe() 
{
    std::cout << "start to update moe" << std::endl;
    bool to16;
    char* value = getenv("MOE_TO_FP16");
    GraphPtr graph = GetGraph();
    std::string moe_to_fp16 = (value != nullptr) ? value: "False";
    if (moe_to_fp16 == "True") {
        to16 = true;
    } else if (moe_to_fp16 == "False") {
        to16 = false;
    } else {
        std::cout << "unsupported moe to fp16 env" << std::endl;
        return GRAPH_FAILED;
    }

    if (!to16) {
        std::cout << "unsupported to16 val" << std::endl;
        return GRAPH_SUCCESS;
    }

    GNode& src_node = GetSrcNode();
    AscendString src_name;
    src_node.GetName(src_name);

    AscendString end_name;
    GetEndNode() -> GetName(end_name);

    std::string top_cast_name = std::string(src_name.GetString()) + "/Cast_to_" + std::string(end_name.GetString());
    op::Cast top_cast_op(top_cast_name);
    top_cast_op.set_attr_dst_type(1); // to float16

    GNode top_cast_node = graph->AddNodeByOp(top_cast_op);
    TensorDesc src_output_desc;
    if (src_node.GetOutputDesc(GetOutputIdx(), src_output_desc) != GRAPH_SUCCESS) {
        std::cout << "get src node output desc failed" << std::endl;
        return GRAPH_FAILED;
    }
    TensorDesc top_cast_input_desc(src_output_desc);
    if (top_cast_node.UpdateInputDesc(0, top_cast_input_desc) != GRAPH_SUCCESS) {
        std::cout << "update top cast input desc failed" << std::endl;
        return GRAPH_FAILED;
    }
    if (top_cast_op.InferShapeAndType() != GRAPH_SUCCESS) {
        std::cout << "infer top cast shape and type failed" << std::endl;
        return GRAPH_FAILED;
    }

    if (graph -> AddDataEdge(src_node, GetOutputIdx(), top_cast_node, 0) != GRAPH_SUCCESS) {
        std::cout << "add data edge src node to top cast node failed" << std::endl;
        return GRAPH_FAILED;
    }  
    
    auto layer_ctxs = GetLayerCtxs();
    if (layer_ctxs.size() < 2) {
        std::cout << "unsupport layer_ctxs' size" << std::endl;
        return GRAPH_FAILED;
    }
       
    GNode first_layer_end_node; 
    auto first_layer = layer_ctxs[0];
    if (UpdateOneLayer(first_layer, to16, true, top_cast_node, first_layer_end_node) != GRAPH_SUCCESS) {
        std::cout << "update first layer failed" << std::endl;
        return GRAPH_FAILED;
    }
 
    GNode start_node = first_layer_end_node;
    GNode end_node;
    for (int32_t i = 1; i < layer_ctxs.size(); i++) {
        if (UpdateOneLayer(layer_ctxs[i], to16, false, start_node, end_node) != GRAPH_SUCCESS) {
            std::cout << "update layer " << i << " failed" << std::endl;
            return GRAPH_FAILED;
        }
        start_node = end_node;
    }

    if (UpdateEndTranspose(start_node, end_node) != GRAPH_SUCCESS) {
        std::cout << "update end transpose failed" << std::endl;
        return GRAPH_FAILED;
    }

    TensorDesc ori_output_desc;
    if (fusion_node_.node.GetOutputDesc(fusion_node_.output_idx, ori_output_desc) != GRAPH_SUCCESS) {
        std::cout << "get ori node dtype failed" << std::endl;
        return GRAPH_FAILED;
    }
    DataType ori_data_type = ori_output_desc.GetDataType();

    std::string end_cast_name = std::string(end_name.GetString()) + "/Cast";
    op::Cast end_cast_op(end_cast_name);
    end_cast_op.set_attr_dst_type(ori_data_type);

    GNode end_cast_node = graph->AddNodeByOp(end_cast_op);
    TensorDesc end_output_desc;
    if (end_node.GetOutputDesc(GetOutputIdx(), end_output_desc) != GRAPH_SUCCESS) {
        std::cout << "get end node output desc failed" << std::endl;
        return GRAPH_FAILED;
    }
    TensorDesc end_cast_input_desc(end_output_desc);
    if (end_cast_node.UpdateInputDesc(0, end_cast_input_desc) != GRAPH_SUCCESS) {
        std::cout << "update end cast input desc failed" << std::endl;
        return GRAPH_FAILED;
    }
    if (end_cast_op.InferShapeAndType() != GRAPH_SUCCESS) {
        std::cout << "infer end cast shape and type failed" << std::endl;
        return GRAPH_FAILED;
    }

    if (graph -> AddDataEdge(end_node, 0, end_cast_node, 0) != GRAPH_SUCCESS) {
        std::cout << "add data edge end node to end cast node failed" << std::endl;
        return GRAPH_FAILED;
    }
 
    auto outputs = end_node_->GetOutDataNodesAndPortIndexs(0);
    for (auto& pair: outputs) {
        if (graph -> RemoveEdge(*end_node_, 0, *pair.first, pair.second) != GRAPH_SUCCESS) {
            std::cout << "remove end node edge failed" << std::endl;
            return GRAPH_FAILED;
        }
        if (graph -> AddDataEdge(end_cast_node, 0, *pair.first, pair.second) != GRAPH_SUCCESS) {
            std::cout << "add end node edge failed" << std::endl;
            return GRAPH_FAILED;
        }
    }

    // to update
    for (auto& ctx: layer_ctxs) {
	for (auto& node: ctx.matmul_nodes) {
            if (graph -> RemoveNode(*node) != GRAPH_SUCCESS) {
                std::cout << "remove matmul node failed" << std::endl;
                return GRAPH_FAILED;
            }
        } 
    }

    return GRAPH_SUCCESS;
}

graphStatus ReplaceMoe(GraphPtr& graph, FusionNode& fusion_node, CustomPassContext& context, int64_t& replaced_count, std::map<AscendString, int64_t> deleted_nodes)
{
    std::vector<MoeContext> ctxs;
    MoePattern pattern;
    if (pattern.PatternMatch(graph, fusion_node, ctxs) != GRAPH_SUCCESS) {
        std::cout << "----pattern match failed" << std::endl;
        return GRAPH_FAILED;
    }
    for (auto& ctx: ctxs) {
        //ctx.PrintDebug();
        if (ctx.UpdateMoe() != GRAPH_SUCCESS) {
            std::cout << "----update mode struct failed" << std::endl;
            return GRAPH_FAILED;
        }
        replaced_count++;
    }
    return GRAPH_SUCCESS;
}

graphStatus MoePass(GraphPtr& graph, CustomPassContext& context)
{
    std::cout << "----------MoePass new begin----------" << std::endl;
    std::vector<FusionNode> root_nodes;
    std::map<AscendString, int64_t> deleted_nodes;
    FindNodesCanFusion(graph, root_nodes);

    if (root_nodes.empty()) {
        std::cout << "Not found nodes has multiple output reference" << std::endl;
        return GRAPH_SUCCESS;
    }

    int64_t replaced_count = 0;
    std::cout << "----------------------------------root nodes size is:" << root_nodes.size() << std::endl;

    for (auto& fusion_node : root_nodes) {
        if (ReplaceMoe(graph, fusion_node, context, replaced_count, deleted_nodes) != GRAPH_SUCCESS) {
            std::cout << "replace moe failed" << std::endl;
            return GRAPH_FAILED;
        }
    }
    //char* file_name = "msy_debug_graph";
    //aclgrphDumpGraph(*graph, file_name, strlen(file_name));
    std::cout << "MoePass end, affect count: " << replaced_count << std::endl;
    return GRAPH_SUCCESS;
}

REGISTER_CUSTOM_PASS("MoePass").CustomPassFn(MoePass).Stage(CustomPassStage::kAfterInferShape);