pass.cc 8.8 KB
Newer Older
X
Xin Pan 已提交
1
/* Copyright (c) 2018 PaddlePaddle Authors. All Rights Reserved.
X
start  
Xin Pan 已提交
2 3 4 5 6 7 8 9 10 11 12 13 14 15

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/pass.h"
Q
Qiao Longfei 已提交
16

17
#include <algorithm>
18

X
Xin Pan 已提交
19
#include "paddle/fluid/framework/ir/graph_helper.h"
20
#include "paddle/fluid/framework/op_proto_maker.h"
W
wanghuancoder 已提交
21 22 23 24 25 26 27 28

namespace paddle {
namespace framework {
namespace ir {
class Graph;
}  // namespace ir
}  // namespace framework
}  // namespace paddle
29 30 31
#ifdef PADDLE_WITH_MKLDNN
#include "paddle/fluid/platform/mkldnn_helper.h"
#endif
X
start  
Xin Pan 已提交
32 33

namespace paddle {
X
Xin Pan 已提交
34 35
namespace framework {
namespace ir {
36

37 38
Graph *Pass::Apply(Graph *graph) const {
  VLOG(10) << "start to apply pass " << Type() << " to graph";
C
chengduo 已提交
39
  CheckPrevPass();
40 41
  PADDLE_ENFORCE_NOT_NULL(
      graph, platform::errors::InvalidArgument("Graph cannot be nullptr."));
42
  for (const std::string &attr : required_pass_attrs_) {
43
    PADDLE_ENFORCE_NE(
44 45
        attrs_.find(attr),
        attrs_.end(),
46 47
        platform::errors::InvalidArgument(
            "Required atrribute %s for pass < %s > is not set.", attr, Type()));
X
Xin Pan 已提交
48
  }
49
  for (const std::string &attr : required_graph_attrs_) {
50 51
    PADDLE_ENFORCE_EQ(graph->Has(attr),
                      true,
52 53
                      platform::errors::InvalidArgument(
                          "Required atrribute %s for graph is not set.", attr));
X
Xin Pan 已提交
54
  }
55
  ApplyImpl(graph);
X
Xin Pan 已提交
56
  // TODO(panyx0718): Add more verifications.
57
  PADDLE_ENFORCE_EQ(
58 59
      HasCircle(*graph),
      false,
60 61 62
      platform::errors::InvalidArgument(
          "Illegal pass %s. Generated graph shouldn't contain cycle.", Type()));
  PADDLE_ENFORCE_EQ(
63 64
      VarDescIsConsistency(*graph),
      true,
65 66
      platform::errors::InvalidArgument(
          "The VarDescs of persistable variable are not consistency."));
X
Xin Pan 已提交
67
  applied_ = true;
C
chengduo 已提交
68 69 70 71
  if (!graph->Has(kPassRecorder)) {
    graph->Set<PassRecorder>(kPassRecorder, new PassRecorder);
  }
  graph->Get<PassRecorder>(kPassRecorder).insert(Type());
72 73 74
#ifdef PADDLE_WITH_MKLDNN
  // Clear mkl-dnn cache,
  // Passes can change params, tensors, so caching need to be discarded
75
  platform::ClearMKLDNNCache(paddle::platform::CPUPlace());
76
#endif
77
  VLOG(10) << "finish to apply pass " << Type() << " to graph";
78
  return graph;
X
Xin Pan 已提交
79 80
}

81
template <typename Container, typename Visitor>
82 83
static void VisitAllElements(Container &&container,
                             Visitor &&visitor,
84 85 86 87 88 89 90 91
                             bool reverse) {
  if (reverse) {
    std::for_each(container.rbegin(), container.rend(), visitor);
  } else {
    std::for_each(container.begin(), container.end(), visitor);
  }
}

92 93
static void MergePrograms(ProgramDesc *dst,
                          const details::ProgramDescs &srcs,
94
                          bool append) {
95 96 97 98 99
  PADDLE_ENFORCE_NOT_NULL(
      dst, platform::errors::InvalidArgument("Dst program must be provided."));
  bool reverse = !append;

  auto create_var_visitor = [dst](const ProgramDesc &src) {
100
    PADDLE_ENFORCE_EQ(
101 102
        src.Size(),
        1,
103 104
        platform::errors::Unimplemented("MergePrograms can only support to "
                                        "merge program with only one block."));
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
    const auto &src_block = src.Block(0);
    auto *dst_block = dst->MutableBlock(0);
    for (const auto *src_new_var : src_block.AllVars()) {
      if (dst_block->FindVar(src_new_var->Name())) continue;
      auto *dst_new_var = dst_block->Var(src_new_var->Name());
      *dst_new_var = *src_new_var;
      VLOG(10) << "Create new variable " << dst_new_var->Name();
    }
  };
  VisitAllElements(srcs, create_var_visitor, reverse);

  auto create_op_visitor = [dst, reverse](const ProgramDesc &src) {
    auto ops = src.Block(0).AllOps();
    auto copy_op_visitor = [dst, reverse](const OpDesc *src_op) {
      auto *dst_block = dst->MutableBlock(0);
      auto *op = reverse ? dst_block->PrependOp() : dst_block->AppendOp();
      op->CopyFrom(*src_op);
      VLOG(10) << (reverse ? "Prepend" : "Append") << " op " << op->Type();
      // FIXME(zjl): some passes does not add VarDesc to program,
      // we should fix this bug later...
      for (const auto &in_var_name : op->InputArgumentNames()) {
        dst_block->Var(in_var_name);
      }
      for (const auto &out_var_name : op->OutputArgumentNames()) {
        dst_block->Var(out_var_name);
      }
    };
    VisitAllElements(ops, copy_op_visitor, reverse);
  };
  VisitAllElements(srcs, create_op_visitor, reverse);
}

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 176 177 178 179 180 181 182
static void FillNotSpecifiedOpRole(const ProgramDesc &main_program) {
  for (size_t block_idx = 0; block_idx < main_program.Size(); ++block_idx) {
    auto ops = main_program.Block(block_idx).AllOps();
    size_t n = ops.size();
    std::vector<OpRole> roles;
    roles.reserve(n);
    auto op_role_attr = OpProtoAndCheckerMaker::OpRoleAttrName();
    for (auto *op : ops) {
      OpRole role;
      if (op->HasAttr(op_role_attr)) {
        role = static_cast<OpRole>(op->GetAttrIfExists<int>(op_role_attr));
      } else {
        role = OpRole::kNotSpecified;
      }
      roles.emplace_back(role);
    }

    // NOTE: The following codes may be wrong in some cases.
    // But how can we get the right OpRole? The right way
    // is that all passes should deal with unspecified OpRole.
    auto prev_role = OpRole::kForward;
    for (size_t i = 0; i < n; ++i) {
      if (roles[i] == OpRole::kNotSpecified) {
        VLOG(10) << "Fill op role of " << ops[i]->Type() << " as "
                 << static_cast<int>(prev_role);
        ops[i]->SetAttr(op_role_attr, static_cast<int>(prev_role));
      } else {
        prev_role = roles[i];
      }
    }
  }
}

void Pass::ApplyPassesToProgram(const std::vector<const Pass *> &passes,
                                ProgramDesc *main_program,
                                ProgramDesc *startup_program) {
  VLOG(10) << "ApplyPassesToProgram is called";
  PADDLE_ENFORCE_NOT_NULL(
      main_program,
      platform::errors::InvalidArgument("The main program must be provided."));

  PADDLE_ENFORCE_NOT_NULL(startup_program,
                          platform::errors::InvalidArgument(
                              "The startup program must be provided."));

  for (auto *p : passes) {
183 184 185
    PADDLE_ENFORCE_NOT_NULL(p,
                            platform::errors::InvalidArgument(
                                "The provided pass cannot be nullptr."));
186 187
    VLOG(10) << "Pass " << p->Type();
    if (passes.size() > 1) {
188 189
      PADDLE_ENFORCE_EQ(p->SupportApplyProgramViaGraph(),
                        true,
190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211
                        platform::errors::PermissionDenied(
                            "Each pass must support to be applied via Graph if "
                            "multi-passes are applied."));
    }
  }

  if (passes.size() == 1 && !passes[0]->SupportApplyProgramViaGraph()) {
    VLOG(10) << "apply pass " << passes[0]->Type() << " to program";
    passes[0]->ApplyImpl(main_program, startup_program);
    FillNotSpecifiedOpRole(*main_program);
    VLOG(10) << "finish to apply pass " << passes[0]->Type() << " to program";
    return;
  }

  Graph graph(*main_program);
  for (auto *p : passes) {
    p->Apply(&graph);
  }
  ConvertToPrograms(&graph, main_program, startup_program);
  FillNotSpecifiedOpRole(*main_program);
}

212 213
void Pass::ApplyImpl(ProgramDesc *main_program,
                     ProgramDesc *startup_program) const {
214 215 216
  PADDLE_THROW(platform::errors::Unimplemented(
      "The pass %s does not support to apply ProgramDesc directly", Type()));
}
217

218 219
void Pass::ConvertToPrograms(Graph *graph,
                             ProgramDesc *main_program,
220
                             ProgramDesc *startup_program) {
221
  ProgramDesc new_main_program;
222
  GraphToProgram(*graph, &new_main_program);
223 224
  main_program->CopyFrom(*new_main_program.Proto());

225
  if (graph->Has(details::kStartupProgramDescs)) {
226
    const auto &startups =
227
        graph->Get<details::ProgramDescs>(details::kStartupProgramDescs);
228 229
    VLOG(10) << "Merge startup programs";
    MergePrograms(startup_program, startups, /*append=*/true);
230
    graph->Erase(details::kStartupProgramDescs);
231 232
  }

233
  if (graph->Has(details::kProgramDescs)) {
234
    const auto &mains =
235
        graph->Get<details::ProgramDescs>(details::kProgramDescs);
236 237
    VLOG(10) << "Merge main programs";
    MergePrograms(main_program, mains, /*append=*/false);
238
    graph->Erase(details::kProgramDescs);
239 240
  }

241 242 243 244
  startup_program->Flush();
  main_program->Flush();
}

245
PassRegistry &PassRegistry::Instance() {
X
Xin Pan 已提交
246 247 248 249 250
  static PassRegistry g_pass_info_map;
  return g_pass_info_map;
}
}  // namespace ir
}  // namespace framework
X
start  
Xin Pan 已提交
251
}  // namespace paddle