fc_gru_fuse_pass.cc 11.4 KB
Newer Older
T
tensor-tang 已提交
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_gru_fuse_pass.h"
16

T
tensor-tang 已提交
17
#include <string>
W
wanghuancoder 已提交
18

19
#include "paddle/fluid/framework/op_version_registry.h"
L
lidanqing 已提交
20
#include "paddle/fluid/string/pretty_log.h"
21 22 23 24 25 26
namespace paddle {
namespace framework {
class Scope;
}  // namespace framework
}  // namespace paddle

T
tensor-tang 已提交
27 28 29 30
namespace paddle {
namespace framework {
namespace ir {

W
wanghuancoder 已提交
31 32
class Node;

33
MulGRUFusePass::MulGRUFusePass() {
B
baoachun 已提交
34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49
  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();
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
  AddOpCompat(OpCompat("gru"))
      .AddInput("Input")
      .IsTensor()
      .End()
      .AddInput("H0")
      .IsTensor()
      .IsOptional()
      .End()
      .AddInput("Weight")
      .IsTensor()
      .End()
      .AddInput("Bias")
      .IsTensor()
      .End()
      .AddOutput("BatchGate")
      .IsTensor()
      .End()
      .AddOutput("BatchResetHiddenPrev")
      .IsTensor()
      .End()
      .AddOutput("BatchHidden")
      .IsTensor()
      .End()
      .AddOutput("Hidden")
      .IsTensor()
      .End()
      .AddAttr("activation")
B
baoachun 已提交
77
      .IsStringIn({"sigmoid", "tanh"})
78 79
      .End()
      .AddAttr("gate_activation")
B
baoachun 已提交
80
      .IsStringIn({"sigmoid", "tanh"})
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
      .End()
      .AddAttr("is_reverse")
      .IsType<bool>()
      .End()
      .AddAttr("origin_mode")
      .IsType<bool>()
      .IsOptional()
      .End();
}

FCGRUFusePass::FCGRUFusePass() {
  AddOpCompat(OpCompat("gru"))
      .AddInput("Input")
      .IsTensor()
      .End()
      .AddInput("H0")
      .IsTensor()
      .IsOptional()
      .End()
      .AddInput("Weight")
      .IsTensor()
      .End()
      .AddInput("Bias")
      .IsTensor()
      .End()
      .AddOutput("BatchGate")
      .IsTensor()
      .End()
      .AddOutput("BatchResetHiddenPrev")
      .IsTensor()
      .End()
      .AddOutput("BatchHidden")
      .IsTensor()
      .End()
      .AddOutput("Hidden")
      .IsTensor()
      .End()
      .AddAttr("activation")
      .IsStringIn({"sigmoid", "tanh", "relu", "identity"})
      .End()
      .AddAttr("gate_activation")
      .IsStringIn({"sigmoid", "tanh", "relu", "identity"})
      .End()
      .AddAttr("is_reverse")
      .IsType<bool>()
      .End()
      .AddAttr("origin_mode")
      .IsType<bool>()
      .IsOptional()
      .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();
}

162 163 164 165
int FCGRUFusePass::BuildFusion(Graph* graph,
                               const std::string& name_scope,
                               Scope* scope,
                               bool with_fc_bias) const {
T
tensor-tang 已提交
166 167 168
  GraphPatternDetector gpd;
  auto* pattern = gpd.mutable_pattern();

Y
Yan Chunwei 已提交
169 170 171
  PDNode* x =
      pattern->NewNode(patterns::UniqueKey("x"))->assert_var_not_persistable();

A
Adam 已提交
172 173
  // Create pattern.
  patterns::FC fc_pattern(pattern, name_scope);
174
  auto* fc_out = fc_pattern(x, with_fc_bias, /* with_relu */ false);
Y
Yan Chunwei 已提交
175
  fc_out->AsIntermediate();  // fc_out is a tmp var, will be removed after fuse.
A
Adam 已提交
176 177

  patterns::GRU gru_pattern(pattern, name_scope);
Y
Yan Chunwei 已提交
178
  gru_pattern(fc_out);
T
tensor-tang 已提交
179 180

  // Create New OpDesc
181 182 183 184 185 186 187
  auto gru_creator = [&](Node* gru,
                         Node* x,
                         Node* weight_x,
                         Node* weight_h,
                         Node* bias,
                         Node* hidden,
                         Node* fc_bias,
188
                         const bool use_mkldnn) {
T
tensor-tang 已提交
189 190
    OpDesc op_desc;
    op_desc.SetType("fusion_gru");
T
tensor-tang 已提交
191 192

#define NEW_NAME(x) name_scope + "/at." #x ".new"
Y
Yan Chunwei 已提交
193
#define SET_IN(Key, node__) op_desc.SetInput(#Key, {node__->Name()});
T
tensor-tang 已提交
194 195 196
    SET_IN(X, x);
    SET_IN(WeightX, weight_x);
    SET_IN(WeightH, weight_h);
A
Adam 已提交
197
    SET_IN(Bias, bias);
T
tensor-tang 已提交
198
#undef SET_IN
A
Adam 已提交
199
    // TODO(grygielski): Add H0 to the pass
T
tensor-tang 已提交
200
    op_desc.SetInput("H0", {});
Y
Yan Chunwei 已提交
201 202
    op_desc.SetOutput("Hidden", {hidden->Name()});
    op_desc.SetAttr("is_reverse", gru->Op()->GetAttr("is_reverse"));
A
Adam 已提交
203 204
    op_desc.SetAttr("origin_mode",
                    gru->Op()->GetAttrIfExists<bool>("origin_mode"));
T
tensor-tang 已提交
205 206
    // TODO(TJ): This should be a option for infer
    op_desc.SetAttr("use_seq", true);
207
    op_desc.SetAttr("use_mkldnn", use_mkldnn);
A
Adam 已提交
208 209
    op_desc.SetAttr("activation", gru->Op()->GetAttr("activation"));
    op_desc.SetAttr("gate_activation", gru->Op()->GetAttr("gate_activation"));
T
tensor-tang 已提交
210 211 212 213 214 215 216 217 218

#define SET_IMTERMEDIATE_OUT(key) op_desc.SetOutput(#key, {NEW_NAME(key)})
    SET_IMTERMEDIATE_OUT(ReorderedH0);
    SET_IMTERMEDIATE_OUT(XX);
    SET_IMTERMEDIATE_OUT(BatchedInput);
    SET_IMTERMEDIATE_OUT(BatchedOut);
#undef SET_IMTERMEDIATE_OUT

    auto* op = graph->CreateOpNode(&op_desc);
T
tensor-tang 已提交
219
    if (with_fc_bias) {
A
Adam 已提交
220 221 222
      auto* gru_bias_var = scope->FindVar(bias->Name());
      auto* fc_bias_var = scope->FindVar(fc_bias->Name());
      PADDLE_ENFORCE_NE(
223 224
          gru_bias_var,
          nullptr,
A
Adam 已提交
225 226
          platform::errors::NotFound("GRU bias var has not been found."));
      PADDLE_ENFORCE_NE(
227 228
          fc_bias_var,
          nullptr,
A
Adam 已提交
229 230 231 232 233
          platform::errors::NotFound("FC bias var has not been found."));

      auto* gru_bias_tensor = gru_bias_var->GetMutable<LoDTensor>();
      auto* fc_bias_tensor = fc_bias_var->GetMutable<LoDTensor>();
      PADDLE_ENFORCE_EQ(
234 235
          gru_bias_tensor->numel(),
          fc_bias_tensor->numel(),
A
Adam 已提交
236 237 238 239 240 241 242 243 244 245
          platform::errors::PreconditionNotMet(
              "GRU and FC biases have to have equal number of elements."));

      auto gru_bias_data =
          gru_bias_tensor->mutable_data<float>(platform::CPUPlace());
      auto* fc_bias_data = fc_bias_tensor->data<float>();

      // Recompute GRU bias
      for (int i = 0; i < gru_bias_tensor->numel(); ++i) {
        gru_bias_data[i] += fc_bias_data[i];
T
tensor-tang 已提交
246 247 248 249
      }
    }
#undef GET_NODE

250 251 252 253 254 255
#define NEW_IMTERMEDIATE_OUT(key)                \
  VarDesc key(NEW_NAME(key));                    \
  key.SetPersistable(false);                     \
  auto* key##_node = graph->CreateVarNode(&key); \
  IR_NODE_LINK_TO(op, key##_node);

T
tensor-tang 已提交
256 257 258 259 260 261
    NEW_IMTERMEDIATE_OUT(ReorderedH0);
    NEW_IMTERMEDIATE_OUT(XX);
    NEW_IMTERMEDIATE_OUT(BatchedInput);
    NEW_IMTERMEDIATE_OUT(BatchedOut);
#undef NEW_NAME
#undef NEW_IMTERMEDIATE_OUT
T
tensor-tang 已提交
262

Y
Yan Chunwei 已提交
263 264 265
    IR_NODE_LINK_TO(x, op);
    IR_NODE_LINK_TO(weight_x, op);
    IR_NODE_LINK_TO(weight_h, op);
A
Adam 已提交
266
    IR_NODE_LINK_TO(bias, op);
Y
Yan Chunwei 已提交
267
    IR_NODE_LINK_TO(op, hidden);
T
tensor-tang 已提交
268 269 270 271 272 273 274
    // h0?
    return op;
  };

  int fusion_count{0};
  auto handler = [&](const GraphPatternDetector::subgraph_t& subgraph,
                     Graph* g) {
275 276 277 278
    if (!IsCompat(subgraph, g)) {
      LOG(WARNING) << "Pass in op compat failed.";
      return;
    }
Y
Yan Chunwei 已提交
279 280 281 282 283 284 285
    auto* x_n = subgraph.at(x);
    GET_IR_NODE_FROM_SUBGRAPH(w, w, fc_pattern);
    GET_IR_NODE_FROM_SUBGRAPH(mul, mul, fc_pattern);
    GET_IR_NODE_FROM_SUBGRAPH(Weight, Weight, gru_pattern);
    GET_IR_NODE_FROM_SUBGRAPH(gru, gru, gru_pattern);
    GET_IR_NODE_FROM_SUBGRAPH(Bias, Bias, gru_pattern);
    GET_IR_NODE_FROM_SUBGRAPH(Hidden, Hidden, gru_pattern);
T
tensor-tang 已提交
286
    // nodes need be removed
Y
Yan Chunwei 已提交
287
    GET_IR_NODE_FROM_SUBGRAPH(BatchGate, BatchGate, gru_pattern);
288 289
    GET_IR_NODE_FROM_SUBGRAPH(
        BatchResetHiddenPrev, BatchResetHiddenPrev, gru_pattern);
290
    GET_IR_NODE_FROM_SUBGRAPH(BatchHidden, BatchHidden, gru_pattern);
T
tensor-tang 已提交
291

292 293 294 295 296
    // TODO(wilber): Support origin_mode=True.
    if (gru->Op()->GetAttrIfExists<bool>("origin_mode") == true) {
      LOG(INFO) << "fc_gru_fuse_pass not supported when origin_mode=True.";
      return;
    }
297 298 299 300 301
    const bool use_mkldnn =
        (mul->Op()->GetAttrIfExists<bool>("use_mkldnn") &&
         gru->Op()->GetAttrIfExists<std::string>("activation") == "tanh" &&
         gru->Op()->GetAttrIfExists<std::string>("gate_activation") ==
             "sigmoid");
302

T
tensor-tang 已提交
303
    if (with_fc_bias) {
Y
Yan Chunwei 已提交
304 305 306
      GET_IR_NODE_FROM_SUBGRAPH(mul_out, mul_out, fc_pattern);
      GET_IR_NODE_FROM_SUBGRAPH(fc_bias, bias, fc_pattern);
      GET_IR_NODE_FROM_SUBGRAPH(elementwise_add, elementwise_add, fc_pattern);
307
      GET_IR_NODE_FROM_SUBGRAPH(fc_out, elementwise_add_out, fc_pattern);
Y
Yan Chunwei 已提交
308

309
      gru_creator(gru, x_n, w, Weight, Bias, Hidden, fc_bias, use_mkldnn);
T
tensor-tang 已提交
310
      // Remove unneeded nodes.
311 312 313 314 315 316 317 318
      std::unordered_set<const Node*> marked_nodes({mul,
                                                    gru,
                                                    elementwise_add,
                                                    fc_out,
                                                    mul_out,
                                                    BatchGate,
                                                    BatchResetHiddenPrev,
                                                    BatchHidden});
T
tensor-tang 已提交
319 320
      GraphSafeRemoveNodes(graph, marked_nodes);
    } else {
321
      gru_creator(gru, x_n, w, Weight, Bias, Hidden, nullptr, use_mkldnn);
T
tensor-tang 已提交
322
      // Remove unneeded nodes.
T
tensor-tang 已提交
323
      std::unordered_set<const Node*> marked_nodes(
Y
Yan Chunwei 已提交
324
          {mul, gru, BatchGate, BatchResetHiddenPrev, BatchHidden});
T
tensor-tang 已提交
325 326 327 328 329 330 331 332 333 334 335 336
      GraphSafeRemoveNodes(graph, marked_nodes);
    }
#undef GET_NODE

    ++fusion_count;
  };

  gpd(graph, handler);

  return fusion_count;
}

337 338
void MulGRUFusePass::ApplyImpl(ir::Graph* graph) const {
  FusePassBase::Init(name_scope_, graph);
T
tensor-tang 已提交
339

340 341
  int fusion_count = MulGRUFusePass::BuildFusion(
      graph, name_scope_, param_scope(), false /*with_fc_bias*/);
T
tensor-tang 已提交
342 343 344 345

  AddStatis(fusion_count);
}

346 347
void FCGRUFusePass::ApplyImpl(ir::Graph* graph) const {
  FusePassBase::Init(name_scope_, graph);
T
tensor-tang 已提交
348

349 350
  int fusion_count = FCGRUFusePass::BuildFusion(
      graph, name_scope_, param_scope(), true /*with_fc_bias*/);
T
tensor-tang 已提交
351 352

  AddStatis(fusion_count);
353 354
  if ((!Has("disable_logs") || !Get<bool>("disable_logs")) &&
      (fusion_count > 0))
355 356
    string::PrettyLogDetail("---    fused %d pairs of fc gru patterns",
                            fusion_count);
T
tensor-tang 已提交
357 358 359 360 361 362
}

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

T
tensor-tang 已提交
363 364
REGISTER_PASS(mul_gru_fuse_pass, paddle::framework::ir::MulGRUFusePass);
REGISTER_PASS(fc_gru_fuse_pass, paddle::framework::ir::FCGRUFusePass);
365 366 367 368 369
REGISTER_PASS_CAPABILITY(mul_gru_fuse_pass)
    .AddCombination(
        paddle::framework::compatible::OpVersionComparatorCombination()
            .EQ("mul", 0)
            .EQ("gru", 0)
370
            .LE("fusion_gru", 1));
371 372 373 374
REGISTER_PASS_CAPABILITY(fc_gru_fuse_pass)
    .AddCombination(
        paddle::framework::compatible::OpVersionComparatorCombination()
            .EQ("mul", 0)
375
            .LE("elementwise_add", 1)
376
            .EQ("gru", 0)
377
            .LE("fusion_gru", 1));