fc_fuse_pass.cc 6.1 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
// Copyright (c) 2018 PaddlePaddle Authors. 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 "paddle/fluid/framework/ir/fc_fuse_pass.h"
16
#include <memory>
17
#include <string>
18
#include <unordered_set>
19
#include <vector>
Y
Yan Chunwei 已提交
20
#include "paddle/fluid/framework/ir/graph_helper.h"
21 22 23 24 25 26
#include "paddle/fluid/platform/enforce.h"

namespace paddle {
namespace framework {
namespace ir {

27
void FCFusePass::ApplyImpl(ir::Graph* graph) const {
28
  PADDLE_ENFORCE_NOT_NULL(graph);
29
  FusePassBase::Init("fc_fuse", graph);
30

31 32 33 34
  int found_fc_count = 0;
  for (bool with_relu : {true, false}) {
    found_fc_count += ApplyFCPattern(graph, with_relu);
  }
35

36 37 38 39
  AddStatis(found_fc_count);
}

int FCFusePass::ApplyFCPattern(Graph* graph, bool with_relu) const {
40
  GraphPatternDetector gpd;
41 42 43 44
  auto* x = gpd.mutable_pattern()
                ->NewNode("fc_fuse/x")
                ->AsInput()
                ->assert_is_op_input("mul", "X");
Y
Yan Chunwei 已提交
45
  patterns::FC fc_pattern(gpd.mutable_pattern(), "fc_fuse");
46
  fc_pattern(x, true /*with bias*/, with_relu);
47

Y
Yan Chunwei 已提交
48
  int found_fc_count = 0;
49
  auto handler = [&](const GraphPatternDetector::subgraph_t& subgraph,
50
                     Graph* g) {
51 52 53 54 55
    if (subgraph.count(x) <= 0) {
      LOG(WARNING) << "The subgraph is empty.";
      return;
    }

M
minqiyang 已提交
56
    VLOG(4) << "handle FC fuse";
Y
Yan Chunwei 已提交
57
    GET_IR_NODE_FROM_SUBGRAPH(w, w, fc_pattern);
58 59 60
    GET_IR_NODE_FROM_SUBGRAPH(bias, bias, fc_pattern);
    GET_IR_NODE_FROM_SUBGRAPH(elementwise_add_out, elementwise_add_out,
                              fc_pattern);
Y
Yan Chunwei 已提交
61 62 63
    GET_IR_NODE_FROM_SUBGRAPH(mul, mul, fc_pattern);
    GET_IR_NODE_FROM_SUBGRAPH(elementwise_add, elementwise_add, fc_pattern);
    GET_IR_NODE_FROM_SUBGRAPH(mul_out, mul_out, fc_pattern);
64 65 66 67 68 69 70 71
    Node* relu = nullptr;
    Node* relu_out = nullptr;
    if (with_relu) {
      GET_IR_NODE_FROM_SUBGRAPH(tmp_relu, relu, fc_pattern);
      GET_IR_NODE_FROM_SUBGRAPH(tmp_relu_out, relu_out, fc_pattern);
      relu = tmp_relu;
      relu_out = tmp_relu_out;
    }
72 73 74

    // Create an FC Node.
    OpDesc desc;
75 76 77 78 79 80 81 82 83 84 85 86 87
    desc.SetType("fc");

    // Set inputs of fc
    desc.SetInput("Input", {subgraph.at(x)->Name()});
    desc.SetInput("W", {w->Name()});
    desc.SetInput("Bias", {bias->Name()});

    // Set output of fc
    std::string fc_out_name =
        with_relu ? relu_out->Name() : elementwise_add_out->Name();
    desc.SetOutput("Out", std::vector<std::string>({fc_out_name}));

    // Set attrs of fc
T
Tao Luo 已提交
88
    desc.SetAttr("in_num_col_dims", mul->Op()->GetAttr("x_num_col_dims"));
89 90
    std::string activation_type = with_relu ? "relu" : "";
    desc.SetAttr("activation_type", activation_type);
91

92 93 94
    // This is to add padding for dimension 128 on concern of MKL performance
    auto* scope = param_scope();
    auto* weight = scope->FindVar(w->Name())->GetMutable<LoDTensor>();
95
    auto* weight_data = weight->data<float>();
96 97 98 99
    auto weight_dims = weight->dims();
    int weight_num = product(weight_dims);
    int w_h = weight_dims[0];
    int w_w = weight_dims[1];
100 101 102 103
    bool use_gpu = Has("use_gpu") ? Get<bool>("use_gpu") : false;
    bool use_fc_padding =
        Has("use_fc_padding") ? Get<bool>("use_fc_padding") : true;
    if (!use_gpu && use_fc_padding) {
104
      if (w_h % 128 == 0 && w_w % 128 == 0) {
105
        auto* weight_data_tmp = new float[weight_num];
106 107 108 109 110
        for (int i = 0; i < w_h; i++) {
          memcpy(weight_data_tmp + i * w_w, weight_data + i * w_w,
                 w_w * sizeof(float));
        }
        weight->Resize(DDim{weight_dims[0] + 4, weight_dims[1] + 4});
111
        auto* weight_data_new =
112 113 114 115 116 117 118 119 120 121
            weight->mutable_data<float>(platform::CPUPlace());
        for (int i = 0; i < w_h; i++) {
          memcpy(weight_data_new + i * (w_w + 4), weight_data_tmp + i * w_w,
                 w_w * sizeof(float));
        }
        delete[] weight_data_tmp;
        desc.SetAttr("padding_weights", true);
      }
    }

122 123
    // For anakin subgraph int8
    // When in anakin subgraph int8 mode, the pattern like "fake_quant + mul +
124 125 126 127 128 129 130 131
    // fake_dequant" can be detected by the quant_dequant_fuse_pass. This pass
    // will add "input_scale", "weight_scale" which are extracted from
    // fake_quant op and fake_dequant op to mul op, and then delete the
    // fake_quant op and fake_dequant op in the graph. If the mul op has the
    // scale info, we should add those to the fused fc.
    auto* mul_op_desc = mul->Op();
    if (mul_op_desc->HasAttr("enable_int8")) {
      desc.SetAttr("enable_int8", mul_op_desc->GetAttr("enable_int8"));
132
      desc.SetAttr("Input_scale", mul_op_desc->GetAttr("X_scale"));
133 134 135
      desc.SetAttr("weight_scale", mul_op_desc->GetAttr("weight_scale"));
      if (mul_op_desc->HasAttr("out_scale"))
        desc.SetAttr("out_scale", mul_op_desc->GetAttr("out_scale"));
136 137 138
      auto elementwise_desc = elementwise_add->Op();
      if (elementwise_desc->HasAttr("out_scale"))
        desc.SetAttr("out_scale", elementwise_desc->GetAttr("out_scale"));
139 140
    }

141
    auto fc_node = g->CreateOpNode(&desc);  // OpDesc will be copied.
142 143 144 145 146 147
    if (with_relu) {
      GraphSafeRemoveNodes(
          graph, {mul, elementwise_add, mul_out, elementwise_add_out, relu});
    } else {
      GraphSafeRemoveNodes(graph, {mul, elementwise_add, mul_out});
    }
148

Y
Yan Chunwei 已提交
149
    IR_NODE_LINK_TO(subgraph.at(x), fc_node);
150
    IR_NODE_LINK_TO(w, fc_node);
151 152 153 154 155 156
    IR_NODE_LINK_TO(bias, fc_node);
    if (with_relu) {
      IR_NODE_LINK_TO(fc_node, relu_out);
    } else {
      IR_NODE_LINK_TO(fc_node, elementwise_add_out);
    }
Y
Yan Chunwei 已提交
157 158

    found_fc_count++;
159
  };
160
  gpd(graph, handler);
161
  return found_fc_count;
162 163 164 165 166 167
}

}  // namespace ir
}  // namespace framework
}  // namespace paddle

168 169
REGISTER_PASS(fc_fuse_pass, paddle::framework::ir::FCFusePass)
    .RequirePassAttr("use_gpu");