fc_lstm_fuse_pass.cc 6.8 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>
T
tensor-tang 已提交
17
#include "paddle/fluid/framework/lod_tensor.h"
18 19 20 21 22

namespace paddle {
namespace framework {
namespace ir {

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

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

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

  // Create New OpDesc
Y
Yan Chunwei 已提交
40 41 42
  auto lstm_creator = [&](Node* lstm, Node* input, Node* weight_x,
                          Node* weight_h, Node* bias, Node* hidden, Node* cell,
                          Node* xx, Node* fc_bias) {
43 44
    OpDesc op_desc;
    op_desc.SetType("fusion_lstm");
Y
Yan Chunwei 已提交
45
#define SET_IN(Key, node__) op_desc.SetInput(#Key, {node__->Name()});
46 47 48 49 50
    SET_IN(X, input);
    SET_IN(WeightX, weight_x);
    SET_IN(WeightH, weight_h);
    SET_IN(Bias, bias);
#undef SET_IN
51 52 53 54 55 56 57
    if (with_fc_bias) {
      // Add FC-bias with LSTM-bias and create a new weight
      PADDLE_ENFORCE(scope);
      const std::string& new_bias_var = name_scope + "_bias.new";
      auto* bias_var = scope->Var(new_bias_var);
      PADDLE_ENFORCE(bias_var);
      auto* bias_tensor = bias_var->GetMutable<framework::LoDTensor>();
Y
Yan Chunwei 已提交
58
      auto* lstm_bias_var = scope->FindVar(bias->Name());
59 60 61 62
      PADDLE_ENFORCE(lstm_bias_var);
      const auto& lstm_bias_tensor = lstm_bias_var->Get<framework::LoDTensor>();
      bias_tensor->Resize(lstm_bias_tensor.dims());

Y
Yan Chunwei 已提交
63
      auto* fc_bias_var = scope->FindVar(fc_bias->Name());
64 65 66 67 68 69 70 71 72 73
      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});
    }
74

75
    // Create temp variables.
Y
Yan Chunwei 已提交
76 77 78 79 80 81 82 83
    const std::string BatchedInput = patterns::UniqueKey("BatchedInput");
    const std::string BatchedCellPreAct =
        patterns::UniqueKey("BatchedCellPreAct");
    const std::string BatchedGate = patterns::UniqueKey("BatchedGate");

    scope->Var(BatchedInput)->GetMutable<framework::LoDTensor>();
    scope->Var(BatchedCellPreAct)->GetMutable<framework::LoDTensor>();
    scope->Var(BatchedGate)->GetMutable<framework::LoDTensor>();
84

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

Y
Yan Chunwei 已提交
98 99 100 101 102 103
    PADDLE_ENFORCE(graph->Has(kParamScopeAttr));
    auto* scope = graph->Get<Scope*>(kParamScopeAttr);
#define OP_SET_OUT(x)                            \
  const std::string x = patterns::UniqueKey(#x); \
  op_desc.SetOutput(#x, {x});                    \
  scope->Var(x)->GetMutable<LoDTensor>()
T
tensor-tang 已提交
104 105 106 107 108
    OP_SET_OUT(BatchedCell);
    OP_SET_OUT(BatchedHidden);
    OP_SET_OUT(ReorderedH0);
    OP_SET_OUT(ReorderedC0);
#undef OP_SET_OUT
109 110

    auto* op = graph->CreateOpNode(&op_desc);
Y
Yan Chunwei 已提交
111 112 113 114 115
    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);
116 117 118
    return op;
  };

119
  int fusion_count{0};
120

121 122
  auto handler = [&](const GraphPatternDetector::subgraph_t& subgraph,
                     Graph* g) {
123

Y
Yan Chunwei 已提交
124 125 126 127 128 129 130
    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(Cell, Cell, lstm_pattern);
    GET_IR_NODE_FROM_SUBGRAPH(Hidden, Hidden, lstm_pattern);
    GET_IR_NODE_FROM_SUBGRAPH(w, w, fc_pattern);
    GET_IR_NODE_FROM_SUBGRAPH(mul, mul, fc_pattern);
131
    if (with_fc_bias) {
Y
Yan Chunwei 已提交
132 133 134 135 136
      GET_IR_NODE_FROM_SUBGRAPH(fc_out, Out, fc_pattern);
      GET_IR_NODE_FROM_SUBGRAPH(fc_bias, bias, fc_pattern);
      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);
137 138
      // Remove unneeded nodes.
      std::unordered_set<const Node*> marked_nodes(
Y
Yan Chunwei 已提交
139
          {mul, lstm, elementwise_add});
140
      GraphSafeRemoveNodes(graph, marked_nodes);
141
    } else {
Y
Yan Chunwei 已提交
142 143 144
      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);
145
      // Remove unneeded nodes.
Y
Yan Chunwei 已提交
146
      std::unordered_set<const Node*> marked_nodes({mul, lstm});
147
      GraphSafeRemoveNodes(graph, marked_nodes);
148
    }
149 150 151 152

    ++fusion_count;
  };

153
  gpd(graph, handler);
154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174

  return fusion_count;
}

std::unique_ptr<ir::Graph> MulLstmFusePass::ApplyImpl(
    std::unique_ptr<ir::Graph> graph) const {
  FusePassBase::Init(name_scope_, graph.get());

  int fusion_count = BuildFusion(graph.get(), name_scope_, param_scope(),
                                 false /*with_fc_bias*/);

  AddStatis(fusion_count);
  return graph;
}

std::unique_ptr<ir::Graph> FCLstmFusePass::ApplyImpl(
    std::unique_ptr<ir::Graph> graph) const {
  FusePassBase::Init(name_scope_, graph.get());

  int fusion_count = BuildFusion(graph.get(), name_scope_, param_scope(),
                                 true /*with_fc_bias*/);
175

176
  AddStatis(fusion_count);
177 178 179 180 181 182 183
  return graph;
}

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

184
REGISTER_PASS(mul_lstm_fuse_pass, paddle::framework::ir::MulLstmFusePass);
185
REGISTER_PASS(fc_lstm_fuse_pass, paddle::framework::ir::FCLstmFusePass);