fc_lstm_fuse_pass.cc 11.2 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>
W
wanghuancoder 已提交
17

18
#include "paddle/fluid/framework/op_version_registry.h"
L
lidanqing 已提交
19
#include "paddle/fluid/string/pretty_log.h"
20

21 22 23 24 25 26
namespace paddle {
namespace framework {
class Scope;
}  // namespace framework
}  // namespace paddle

27 28 29 30
namespace paddle {
namespace framework {
namespace ir {

W
wanghuancoder 已提交
31 32
class Node;

33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175
MulLstmFusePass::MulLstmFusePass() {
  AddOpCompat(OpCompat("lstm"))
      .AddInput("Input")
      .IsTensor()
      .End()
      .AddInput("H0")
      .IsTensor()
      .IsOptional()
      .End()
      .AddInput("C0")
      .IsTensor()
      .IsOptional()
      .End()
      .AddInput("Weight")
      .IsTensor()
      .End()
      .AddInput("Bias")
      .IsTensor()
      .End()
      .AddOutput("Hidden")
      .IsTensor()
      .End()
      .AddOutput("Cell")
      .IsTensor()
      .End()
      .AddOutput("BatchGate")
      .IsTensor()
      .End()
      .AddOutput("BatchCellPreAct")
      .IsTensor()
      .End()
      .AddAttr("use_peepholes")
      .IsType<bool>()
      .End()
      .AddAttr("is_reverse")
      .IsType<bool>()
      .End()
      .AddAttr("gate_activation")
      .IsStringIn({"sigmoid", "tanh", "relu", "identity"})
      .End()
      .AddAttr("cell_activation")
      .IsStringIn({"sigmoid", "tanh", "relu", "identity"})
      .End()
      .AddAttr("candidate_activation")
      .IsStringIn({"sigmoid", "tanh", "relu", "identity"})
      .End();
  AddOpCompat(OpCompat("mul"))
      .AddInput("X")
      .IsTensor()
      .End()
      .AddInput("Y")
      .IsTensor()
      .End()
      .AddOutput("Out")
      .IsTensor()
      .End()
      .AddAttr("x_num_col_dims")
      .IsNumEQ(1)
      .End()
      .AddAttr("y_num_col_dims")
      .IsNumEQ(1)
      .End();
}

FCLstmFusePass::FCLstmFusePass() {
  AddOpCompat(OpCompat("lstm"))
      .AddInput("Input")
      .IsTensor()
      .End()
      .AddInput("H0")
      .IsTensor()
      .IsOptional()
      .End()
      .AddInput("C0")
      .IsTensor()
      .IsOptional()
      .End()
      .AddInput("Weight")
      .IsTensor()
      .End()
      .AddInput("Bias")
      .IsTensor()
      .End()
      .AddOutput("Hidden")
      .IsTensor()
      .End()
      .AddOutput("Cell")
      .IsTensor()
      .End()
      .AddOutput("BatchGate")
      .IsTensor()
      .End()
      .AddOutput("BatchCellPreAct")
      .IsTensor()
      .End()
      .AddAttr("use_peepholes")
      .IsType<bool>()
      .End()
      .AddAttr("is_reverse")
      .IsType<bool>()
      .End()
      .AddAttr("gate_activation")
      .IsStringIn({"sigmoid", "tanh", "relu", "identity"})
      .End()
      .AddAttr("cell_activation")
      .IsStringIn({"sigmoid", "tanh", "relu", "identity"})
      .End()
      .AddAttr("candidate_activation")
      .IsStringIn({"sigmoid", "tanh", "relu", "identity"})
      .End();
  AddOpCompat(OpCompat("mul"))
      .AddInput("X")
      .IsTensor()
      .End()
      .AddInput("Y")
      .IsTensor()
      .End()
      .AddOutput("Out")
      .IsTensor()
      .End()
      .AddAttr("x_num_col_dims")
      .IsNumEQ(1)
      .End()
      .AddAttr("y_num_col_dims")
      .IsNumEQ(1)
      .End();
  AddOpCompat(OpCompat("elementwise_add"))
      .AddInput("X")
      .IsTensor()
      .End()
      .AddInput("Y")
      .IsTensor()
      .End()
      .AddOutput("Out")
      .IsTensor()
      .End()
      .AddAttr("axis")
      .IsNumGE(-1)
      .End();
}

int FCLstmFusePass::BuildFusion(Graph* graph, const std::string& name_scope,
                                Scope* scope, bool with_fc_bias) const {
Y
Yan Chunwei 已提交
176 177
  GraphPatternDetector gpd;
  auto* pattern = gpd.mutable_pattern();
178

Y
Yan Chunwei 已提交
179 180
  // Build pattern
  PDNode* x = pattern->NewNode(patterns::PDNodeName(name_scope, "x"))
181 182
                  ->assert_is_op_input("mul")
                  ->assert_var_not_persistable();
Y
Yan Chunwei 已提交
183
  patterns::FC fc_pattern(pattern, name_scope);
184

185
  auto* fc_out = fc_pattern(x, with_fc_bias, /* with_relu */ false);
Y
Yan Chunwei 已提交
186 187
  patterns::LSTM lstm_pattern(pattern, name_scope);
  lstm_pattern(fc_out);
188 189

  // Create New OpDesc
Y
Yan Chunwei 已提交
190 191
  auto lstm_creator = [&](Node* lstm, Node* input, Node* weight_x,
                          Node* weight_h, Node* bias, Node* hidden, Node* cell,
192
                          Node* xx, Node* fc_bias, const bool use_mkldnn) {
193 194
    OpDesc op_desc;
    op_desc.SetType("fusion_lstm");
Y
Yan Chunwei 已提交
195
#define SET_IN(Key, node__) op_desc.SetInput(#Key, {node__->Name()});
196 197 198 199 200
    SET_IN(X, input);
    SET_IN(WeightX, weight_x);
    SET_IN(WeightH, weight_h);
    SET_IN(Bias, bias);
#undef SET_IN
201 202
    if (with_fc_bias) {
      // Add FC-bias with LSTM-bias and create a new weight
203 204
      PADDLE_ENFORCE_NOT_NULL(
          scope, platform::errors::InvalidArgument("Scope cannot be nullptr."));
Y
Yan Chunwei 已提交
205
      auto* lstm_bias_var = scope->FindVar(bias->Name());
206
      auto* fc_bias_var = scope->FindVar(fc_bias->Name());
207 208 209
      PADDLE_ENFORCE_NOT_NULL(lstm_bias_var,
                              platform::errors::InvalidArgument(
                                  "Lstm bias var ptr cannot be nullptr."));
210 211 212 213 214
      PADDLE_ENFORCE_NOT_NULL(fc_bias_var,
                              platform::errors::InvalidArgument(
                                  "FC bias var ptr cannot be nullptr."));
      auto* lstm_bias_tensor =
          lstm_bias_var->GetMutable<framework::LoDTensor>();
215 216
      const auto& fc_bias_tensor = fc_bias_var->Get<framework::LoDTensor>();

217 218 219
      auto lstm_bias_data =
          lstm_bias_tensor->mutable_data<float>(platform::CPUPlace());
      auto* fc_bias_data = fc_bias_tensor.data<float>();
220

221 222
      for (int i = 0; i < lstm_bias_tensor->numel(); i++) {
        lstm_bias_data[i] += fc_bias_data[i];
223 224
      }
    }
225 226 227

    op_desc.SetInput("H0", {});
    op_desc.SetInput("C0", {});
Y
Yan Chunwei 已提交
228 229 230 231 232
    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"));
233
    op_desc.SetAttr("use_mkldnn", use_mkldnn);
T
tensor-tang 已提交
234 235
    // TODO(TJ): get from attr
    op_desc.SetAttr("use_seq", true);
T
tensor-tang 已提交
236

237
// Create temp variables.
Y
Yan Chunwei 已提交
238 239
#define OP_SET_OUT(x)                            \
  const std::string x = patterns::UniqueKey(#x); \
240 241 242 243 244 245
  op_desc.SetOutput(#x, {x});

    OP_SET_OUT(BatchedGate);
    OP_SET_OUT(BatchedCellPreAct);
    OP_SET_OUT(BatchedInput);
    OP_SET_OUT(CheckedCell);
T
tensor-tang 已提交
246 247 248 249 250
    OP_SET_OUT(BatchedCell);
    OP_SET_OUT(BatchedHidden);
    OP_SET_OUT(ReorderedH0);
    OP_SET_OUT(ReorderedC0);
#undef OP_SET_OUT
251 252

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

Y
Yan Chunwei 已提交
254 255 256 257 258
    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);
259 260
    IR_NODE_LINK_TO(op, cell);
    IR_NODE_LINK_TO(op, xx);
261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277

#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

278 279 280
    return op;
  };

281
  int fusion_count{0};
282

283 284
  auto handler = [&](const GraphPatternDetector::subgraph_t& subgraph,
                     Graph* g) {
285 286 287 288
    if (!IsCompat(subgraph, g)) {
      LOG(WARNING) << "Pass in op compat failed.";
      return;
    }
Y
Yan Chunwei 已提交
289 290 291 292
    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);
293 294 295
    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 已提交
296 297
    GET_IR_NODE_FROM_SUBGRAPH(w, w, fc_pattern);
    GET_IR_NODE_FROM_SUBGRAPH(mul, mul, fc_pattern);
298 299 300 301 302 303 304 305 306
    const bool use_mkldnn =
        (mul->Op()->GetAttrIfExists<bool>("use_mkldnn") &&
         lstm->Op()->GetAttrIfExists<std::string>("gate_activation") ==
             "sigmoid" &&
         lstm->Op()->GetAttrIfExists<std::string>("cell_activation") ==
             "tanh" &&
         lstm->Op()->GetAttrIfExists<std::string>("candidate_activation") ==
             "tanh");

307
    if (with_fc_bias) {
308
      GET_IR_NODE_FROM_SUBGRAPH(fc_out, elementwise_add_out, fc_pattern);
Y
Yan Chunwei 已提交
309
      GET_IR_NODE_FROM_SUBGRAPH(fc_bias, bias, fc_pattern);
310
      GET_IR_NODE_FROM_SUBGRAPH(mul_out, mul_out, fc_pattern);
Y
Yan Chunwei 已提交
311 312
      GET_IR_NODE_FROM_SUBGRAPH(elementwise_add, elementwise_add, fc_pattern);
      lstm_creator(lstm, subgraph.at(x), w, Weight, Bias, Hidden, Cell, fc_out,
313
                   fc_bias, use_mkldnn);
314 315
      // Remove unneeded nodes.
      std::unordered_set<const Node*> marked_nodes(
316
          {mul, lstm, elementwise_add, mul_out, BatchGate, BatchCellPreAct});
317
      GraphSafeRemoveNodes(graph, marked_nodes);
318
    } else {
Y
Yan Chunwei 已提交
319 320
      GET_IR_NODE_FROM_SUBGRAPH(fc_out, mul_out, fc_pattern);
      lstm_creator(lstm, subgraph.at(x), w, Weight, Bias, Hidden, Cell, fc_out,
321
                   nullptr, use_mkldnn);
322
      // Remove unneeded nodes.
323 324
      std::unordered_set<const Node*> marked_nodes(
          {mul, lstm, BatchGate, BatchCellPreAct});
325
      GraphSafeRemoveNodes(graph, marked_nodes);
326
    }
327 328 329 330

    ++fusion_count;
  };

331
  gpd(graph, handler);
332 333 334 335

  return fusion_count;
}

336 337
void MulLstmFusePass::ApplyImpl(ir::Graph* graph) const {
  FusePassBase::Init(name_scope_, graph);
338

339 340
  int fusion_count =
      BuildFusion(graph, name_scope_, param_scope(), false /*with_fc_bias*/);
341 342 343 344

  AddStatis(fusion_count);
}

345 346
void FCLstmFusePass::ApplyImpl(ir::Graph* graph) const {
  FusePassBase::Init(name_scope_, graph);
347

348 349
  int fusion_count =
      BuildFusion(graph, name_scope_, param_scope(), true /*with_fc_bias*/);
350

351
  AddStatis(fusion_count);
352 353 354
  if (!Has("disable_logs") || !Get<bool>("disable_logs"))
    string::PrettyLogDetail("---    fused %d pairs of fc lstm patterns",
                            fusion_count);
355 356 357 358 359 360
}

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

361
REGISTER_PASS(mul_lstm_fuse_pass, paddle::framework::ir::MulLstmFusePass);
362
REGISTER_PASS(fc_lstm_fuse_pass, paddle::framework::ir::FCLstmFusePass);
363 364 365 366 367

REGISTER_PASS_CAPABILITY(fc_lstm_fuse_pass)
    .AddCombination(
        paddle::framework::compatible::OpVersionComparatorCombination()
            .EQ("mul", 0)
368
            .LE("elementwise_add", 1)
369 370 371 372 373 374 375 376
            .EQ("lstm", 0)
            .EQ("fusion_lstm", 0));
REGISTER_PASS_CAPABILITY(mul_lstm_fuse_pass)
    .AddCombination(
        paddle::framework::compatible::OpVersionComparatorCombination()
            .EQ("mul", 0)
            .EQ("lstm", 0)
            .EQ("fusion_lstm", 0));