fc_lstm_fuse_pass.cc 7.1 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12 13
// 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.
T
tensor-tang 已提交
14

15
#include "paddle/fluid/framework/ir/fc_lstm_fuse_pass.h"
T
tensor-tang 已提交
16
#include <string>
17
#include <unordered_set>
T
tensor-tang 已提交
18
#include "paddle/fluid/framework/lod_tensor.h"
19 20 21 22 23

namespace paddle {
namespace framework {
namespace ir {

Y
Yan Chunwei 已提交
24 25 26 27
int BuildFusion(Graph* graph, const std::string& name_scope, Scope* scope,
                bool with_fc_bias) {
  GraphPatternDetector gpd;
  auto* pattern = gpd.mutable_pattern();
28

Y
Yan Chunwei 已提交
29 30
  // Build pattern
  PDNode* x = pattern->NewNode(patterns::PDNodeName(name_scope, "x"))
31 32
                  ->assert_is_op_input("mul")
                  ->assert_var_not_persistable();
Y
Yan Chunwei 已提交
33
  patterns::FC fc_pattern(pattern, name_scope);
34

Y
Yan Chunwei 已提交
35
  // fc_out is a tmp var, will be removed after fuse, so marked as intermediate.
36 37
  auto* fc_out =
      fc_pattern(x, with_fc_bias, /* with_relu */ false)->AsIntermediate();
Y
Yan Chunwei 已提交
38 39
  patterns::LSTM lstm_pattern(pattern, name_scope);
  lstm_pattern(fc_out);
40 41

  // Create New OpDesc
Y
Yan Chunwei 已提交
42 43 44
  auto lstm_creator = [&](Node* lstm, Node* input, Node* weight_x,
                          Node* weight_h, Node* bias, Node* hidden, Node* cell,
                          Node* xx, Node* fc_bias) {
45 46
    OpDesc op_desc;
    op_desc.SetType("fusion_lstm");
Y
Yan Chunwei 已提交
47
#define SET_IN(Key, node__) op_desc.SetInput(#Key, {node__->Name()});
48 49 50 51 52
    SET_IN(X, input);
    SET_IN(WeightX, weight_x);
    SET_IN(WeightH, weight_h);
    SET_IN(Bias, bias);
#undef SET_IN
53 54
    if (with_fc_bias) {
      // Add FC-bias with LSTM-bias and create a new weight
55 56
      PADDLE_ENFORCE_NOT_NULL(
          scope, platform::errors::InvalidArgument("Scope cannot be nullptr."));
L
luotao1 已提交
57
      const std::string& new_bias_var = patterns::UniqueKey("NewBias");
58
      auto* bias_var = scope->Var(new_bias_var);
59 60
      PADDLE_ENFORCE_NOT_NULL(bias_var, platform::errors::InvalidArgument(
                                            "Bias var ptr cannot be nullptr."));
61
      auto* bias_tensor = bias_var->GetMutable<framework::LoDTensor>();
Y
Yan Chunwei 已提交
62
      auto* lstm_bias_var = scope->FindVar(bias->Name());
63 64 65
      PADDLE_ENFORCE_NOT_NULL(lstm_bias_var,
                              platform::errors::InvalidArgument(
                                  "Lstm bias var ptr cannot be nullptr."));
66 67 68
      const auto& lstm_bias_tensor = lstm_bias_var->Get<framework::LoDTensor>();
      bias_tensor->Resize(lstm_bias_tensor.dims());

Y
Yan Chunwei 已提交
69
      auto* fc_bias_var = scope->FindVar(fc_bias->Name());
70 71 72 73 74 75 76 77 78 79
      const auto& fc_bias_tensor = fc_bias_var->Get<framework::LoDTensor>();

      auto* data = bias_tensor->mutable_data<float>(platform::CPUPlace());

      for (int i = 0; i < bias_tensor->numel(); i++) {
        data[i] =
            fc_bias_tensor.data<float>()[i] + lstm_bias_tensor.data<float>()[i];
      }
      op_desc.SetInput("Bias", {new_bias_var});
    }
80 81 82

    op_desc.SetInput("H0", {});
    op_desc.SetInput("C0", {});
Y
Yan Chunwei 已提交
83 84 85 86 87
    op_desc.SetOutput("Hidden", {hidden->Name()});
    op_desc.SetOutput("Cell", {cell->Name()});
    op_desc.SetOutput("XX", {xx->Name()});
    op_desc.SetAttr("is_reverse", lstm->Op()->GetAttr("is_reverse"));
    op_desc.SetAttr("use_peepholes", lstm->Op()->GetAttr("use_peepholes"));
T
tensor-tang 已提交
88 89
    // TODO(TJ): get from attr
    op_desc.SetAttr("use_seq", true);
T
tensor-tang 已提交
90

91
// Create temp variables.
Y
Yan Chunwei 已提交
92 93
#define OP_SET_OUT(x)                            \
  const std::string x = patterns::UniqueKey(#x); \
94 95 96 97 98 99
  op_desc.SetOutput(#x, {x});

    OP_SET_OUT(BatchedGate);
    OP_SET_OUT(BatchedCellPreAct);
    OP_SET_OUT(BatchedInput);
    OP_SET_OUT(CheckedCell);
T
tensor-tang 已提交
100 101 102 103 104
    OP_SET_OUT(BatchedCell);
    OP_SET_OUT(BatchedHidden);
    OP_SET_OUT(ReorderedH0);
    OP_SET_OUT(ReorderedC0);
#undef OP_SET_OUT
105 106

    auto* op = graph->CreateOpNode(&op_desc);
107

Y
Yan Chunwei 已提交
108 109 110 111 112
    IR_NODE_LINK_TO(input, op);
    IR_NODE_LINK_TO(weight_x, op);
    IR_NODE_LINK_TO(weight_h, op);
    IR_NODE_LINK_TO(bias, op);
    IR_NODE_LINK_TO(op, hidden);
113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129

#define IR_NODE(x)                                 \
  VarDesc key_##x(x);                              \
  key_##x.SetPersistable(false);                   \
  auto* node_##x = graph->CreateVarNode(&key_##x); \
  IR_NODE_LINK_TO(op, node_##x);

    IR_NODE(BatchedGate);
    IR_NODE(BatchedCellPreAct);
    IR_NODE(BatchedInput);
    IR_NODE(CheckedCell);
    IR_NODE(BatchedCell);
    IR_NODE(BatchedHidden);
    IR_NODE(ReorderedH0);
    IR_NODE(ReorderedC0);
#undef IR_NODE

130 131 132
    return op;
  };

133
  int fusion_count{0};
134

135 136
  auto handler = [&](const GraphPatternDetector::subgraph_t& subgraph,
                     Graph* g) {
Y
Yan Chunwei 已提交
137 138 139 140
    GET_IR_NODE_FROM_SUBGRAPH(lstm, lstm, lstm_pattern);
    GET_IR_NODE_FROM_SUBGRAPH(Weight, Weight, lstm_pattern);
    GET_IR_NODE_FROM_SUBGRAPH(Bias, Bias, lstm_pattern);
    GET_IR_NODE_FROM_SUBGRAPH(Hidden, Hidden, lstm_pattern);
141 142 143
    GET_IR_NODE_FROM_SUBGRAPH(BatchCellPreAct, BatchCellPreAct, lstm_pattern);
    GET_IR_NODE_FROM_SUBGRAPH(BatchGate, BatchGate, lstm_pattern);
    GET_IR_NODE_FROM_SUBGRAPH(Cell, Cell, lstm_pattern);
Y
Yan Chunwei 已提交
144 145
    GET_IR_NODE_FROM_SUBGRAPH(w, w, fc_pattern);
    GET_IR_NODE_FROM_SUBGRAPH(mul, mul, fc_pattern);
146
    if (with_fc_bias) {
147
      GET_IR_NODE_FROM_SUBGRAPH(fc_out, elementwise_add_out, fc_pattern);
Y
Yan Chunwei 已提交
148
      GET_IR_NODE_FROM_SUBGRAPH(fc_bias, bias, fc_pattern);
149
      GET_IR_NODE_FROM_SUBGRAPH(mul_out, mul_out, fc_pattern);
Y
Yan Chunwei 已提交
150 151 152
      GET_IR_NODE_FROM_SUBGRAPH(elementwise_add, elementwise_add, fc_pattern);
      lstm_creator(lstm, subgraph.at(x), w, Weight, Bias, Hidden, Cell, fc_out,
                   fc_bias);
153 154
      // Remove unneeded nodes.
      std::unordered_set<const Node*> marked_nodes(
155
          {mul, lstm, elementwise_add, mul_out, BatchGate, BatchCellPreAct});
156
      GraphSafeRemoveNodes(graph, marked_nodes);
157
    } else {
Y
Yan Chunwei 已提交
158 159 160
      GET_IR_NODE_FROM_SUBGRAPH(fc_out, mul_out, fc_pattern);
      lstm_creator(lstm, subgraph.at(x), w, Weight, Bias, Hidden, Cell, fc_out,
                   nullptr);
161
      // Remove unneeded nodes.
162 163
      std::unordered_set<const Node*> marked_nodes(
          {mul, lstm, BatchGate, BatchCellPreAct});
164
      GraphSafeRemoveNodes(graph, marked_nodes);
165
    }
166 167 168 169

    ++fusion_count;
  };

170
  gpd(graph, handler);
171 172 173 174

  return fusion_count;
}

175 176
void MulLstmFusePass::ApplyImpl(ir::Graph* graph) const {
  FusePassBase::Init(name_scope_, graph);
177

178 179
  int fusion_count =
      BuildFusion(graph, name_scope_, param_scope(), false /*with_fc_bias*/);
180 181 182 183

  AddStatis(fusion_count);
}

184 185
void FCLstmFusePass::ApplyImpl(ir::Graph* graph) const {
  FusePassBase::Init(name_scope_, graph);
186

187 188
  int fusion_count =
      BuildFusion(graph, name_scope_, param_scope(), true /*with_fc_bias*/);
189

190
  AddStatis(fusion_count);
191 192 193 194 195 196
}

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

197
REGISTER_PASS(mul_lstm_fuse_pass, paddle::framework::ir::MulLstmFusePass);
198
REGISTER_PASS(fc_lstm_fuse_pass, paddle::framework::ir::FCLstmFusePass);