program_optimize.cpp 11.1 KB
Newer Older
L
liuruilong 已提交
1 2 3 4 5 6 7 8 9 10 11 12 13 14
/* 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. */

L
liuruilong 已提交
15
#include "framework/program/program-optimize/program_optimize.h"
D
dolphin8 已提交
16
#include <algorithm>
D
dolphin8 已提交
17
#include "framework/program/program-optimize/fusion_op_register.h"
L
liuruilong 已提交
18 19 20 21 22

namespace paddle_mobile {

namespace framework {

L
liuruilong 已提交
23
std::shared_ptr<ProgramDesc> ProgramOptimize::FusionOptimize(
L
liuruilong 已提交
24
    std::shared_ptr<ProgramDesc> ori_des, bool add_split) {
L
liuruilong 已提交
25 26 27
  //  ProgramDesc *optimize_program = new ProgramDesc(*ori_des);
  std::shared_ptr<ProgramDesc> optimize_program =
      std::make_shared<ProgramDesc>(*ori_des);
L
liuruilong 已提交
28
  current_block_ = optimize_program->Blocks().size();
L
liuruilong 已提交
29 30 31

  for (int i = 0; i < optimize_program->Blocks().size(); ++i) {
    std::unordered_map<std::string, std::shared_ptr<Node>> output_nodes;
32 33 34 35 36
    std::unordered_map<
        std::string,
        std::vector<
            std::pair<std::shared_ptr<Node>,
                      std::unordered_map<std::string, std::shared_ptr<Node>>>>>
L
liuruilong 已提交
37 38
        type_map;

39 40
    std::unordered_map<std::string, bool> output_has;

L
liuruilong 已提交
41 42
    std::vector<std::shared_ptr<Node>> nodes;

L
liuruilong 已提交
43 44 45 46 47 48 49
    std::shared_ptr<Node> begin_node;
    auto block = optimize_program->Block(i);
    //        DLOG << " ops size: " << block->Ops().size();
    for (int j = 0; j < block->Ops().size(); ++j) {
      auto op = block->Ops()[j];
      auto op_type = op->Type();
      if (op_input_output_key.find(op->Type()) == op_input_output_key.end()) {
L
liuruilong 已提交
50 51
        LOG(kLOG_ERROR) << "has not support op return null "
                        << " op type: " << op->Type();
L
liuruilong 已提交
52 53 54 55
        return nullptr;
      }

      std::shared_ptr<Node> node = std::make_shared<Node>(op);
L
liuruilong 已提交
56
      nodes.push_back(node);
L
liuruilong 已提交
57 58

      //
59
      type_map[op->Type()].push_back({node, output_nodes});
L
liuruilong 已提交
60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77

      if (j == 0) {
        begin_node = node;
      }

      auto input_keys = op_input_output_key.at(op->Type()).first;
      for (auto input_key : input_keys) {
        auto op_inputs = op->Input(input_key);
        for (int l = 0; l < op_inputs.size(); ++l) {
          std::string input_key = op_inputs[l];
          if (output_nodes.find(input_key) != output_nodes.end()) {
            auto input_node = output_nodes[input_key];
            *input_node > node;
          }
        }
      }

      auto output_keys = op_input_output_key.at(op_type).second;
78

L
liuruilong 已提交
79 80 81 82 83 84 85 86 87
      for (auto output_key : output_keys) {
        auto op_outputs = op->Output(output_key);
        for (int k = 0; k < op_outputs.size(); ++k) {
          output_nodes[op_outputs[k]] = node;
        }
      }
    }

    for (auto &registed : FusionOpRegister::Instance()->Matchers()) {
L
liuruilong 已提交
88 89
      std::string fusion_type = registed->Type();
      std::shared_ptr<FusionOpMatcher> matcher = registed;
L
liuruilong 已提交
90 91 92

      auto match_vector = type_map[matcher->BeginType()];

93 94 95 96 97
      for (auto &match_node_pair : match_vector) {
        auto match_node = match_node_pair.first;

        auto node_has = match_node_pair.second;

L
liuruilong 已提交
98 99 100 101
        auto depth = matcher->BeginNode().Depth();
        auto sub_node = match_node->To(depth);
        //        DLOG << " sub node: " << *sub_node;
        if (*sub_node == matcher->BeginNode()) {
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
          bool can_folder = true;

          auto relationship_map = sub_node->Relationship();

          for (auto to_check : matcher->NeedCheck()) {
            //            if (node_has)
            auto nodes = (*sub_node)[to_check.first];
            for (auto node : nodes) {
              auto inputs_to_check =
                  node->OpDescOfNode()->Input(to_check.second);

              for (auto input_to_check : inputs_to_check) {
                if (node_has.find(input_to_check) == node_has.end()) {
                  if (relationship_map.find(input_to_check) ==
                      relationship_map.end()) {
                    can_folder = false;
                  } else {
                  }
                }
              }
            }
          }

          if (!can_folder) {
            continue;
          }

L
liuruilong 已提交
129 130 131 132
          //          DLOG << " match success " << " fusion node: \n" <<
          //          matcher->BeginNode() << "\nsub node: \n" << *sub_node;
          //          DLOG << "match node\n"<< *match_node;

L
liuruilong 已提交
133 134 135
          std::vector<std::shared_ptr<Node>> removed_nodes;
          matcher->FolderNodes(match_node.get(), &removed_nodes);

136 137
          for (int k = removed_nodes.size() - 1; k >= 0; --k) {
            auto removed_node = removed_nodes[k];
L
liuruilong 已提交
138 139
            auto removed_ite =
                std::find(nodes.begin(), nodes.end(), removed_node);
140 141 142
            if (removed_ite != nodes.end()) {
              nodes.erase(removed_ite);
            }
L
liuruilong 已提交
143
          }
L
liuruilong 已提交
144 145 146 147
        }
      }
    }

L
liuruilong 已提交
148
    std::vector<std::shared_ptr<framework::OpDesc>> op_descs;
L
liuruilong 已提交
149 150 151 152 153 154 155
    if (add_split) {
      GenerateOps(&op_descs, begin_node.get(), add_split);
    } else {
      for (int m = 0; m < nodes.size(); ++m) {
        auto &node = nodes[m];
        op_descs.push_back(node->op_desc_);
      }
L
liuruilong 已提交
156
    }
L
liuruilong 已提交
157 158 159 160 161 162 163
    block->ops_ = op_descs;
  }

  for (int m = 0; m < new_blocks_.size(); ++m) {
    std::shared_ptr<BlockDesc> new_block = new_blocks_[m];
    new_block->index_ = m + ori_des->blocks_.size();
    optimize_program->blocks_.push_back(new_block);
L
liuruilong 已提交
164
  }
L
liuruilong 已提交
165
  return optimize_program;
L
liuruilong 已提交
166
}
L
liuruilong 已提交
167

L
liuruilong 已提交
168
void ProgramOptimize::GenerateOps(
L
liuruilong 已提交
169 170
    std::vector<std::shared_ptr<framework::OpDesc>> *op_desc, Node *input_node,
    Node *current_node) {
L
liuruilong 已提交
171 172
  if (current_node->inputs_.size() > 1 &&
      input_node != current_node->inputs_.back()) {
L
liuruilong 已提交
173 174 175 176 177 178 179 180
    DLOG << " current type " << current_node->type_;

    DLOG << " inputs size of current node > 0 ";

    for (int i = 0; i < current_node->inputs_.size(); ++i) {
      DLOG << " input i: " << current_node->inputs_[i]->type_;
    }

L
liuruilong 已提交
181 182 183 184 185 186 187 188 189 190 191 192 193 194
    return;
  } else if (current_node->inputs_.size() > 1 &&
             input_node == current_node->inputs_.back()) {
    op_desc->push_back(current_node->op_desc_);
  } else {
    op_desc->push_back(current_node->op_desc_);
  }

  for (int i = 0; i < current_node->outputs_.size(); ++i) {
    auto &output = current_node->outputs_[i];
    GenerateOps(op_desc, current_node, output.get());
  }
}

L
liuruilong 已提交
195 196 197 198
void ProgramOptimize::GenerateOps(
    std::vector<std::shared_ptr<framework::OpDesc>> *op_desc, Node *input_node,
    Node *current_node, bool adding_thread, int thread_num,
    std::shared_ptr<BlockDesc> new_block) {
L
liuruilong 已提交
199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226
  if (current_node->outputs_.size() > 1) {
    adding_thread = false;
  }

  bool can_add_split = false;
  // 如果当前节点有多个输出 并且 只有当前节点对应的 op_desc_ 输出数为 1 时支持
  if (current_node->outputs_.size() > 1 &&
      op_input_output_key[current_node->op_desc_->type_].second.size() == 1) {
    can_add_split = true;

    // 遍历当前节点的 output 节点
    for (const auto &output : current_node->outputs_) {
      // 不支持 output 有多个 output 的情况
      if (output->outputs_.size() > 1) {
        DLOG << "don't support multi output of output";
        can_add_split = false;
        break;
      }

      //与节点关联的 OpDesc
      std::shared_ptr<framework::OpDesc> &op_desc = output->op_desc_;

      //获取这个 op 的 inputs key 和 outputs key
      auto inputs_and_outputs = op_input_output_key[op_desc->type_];

      //判断现在 是否存在这个 op
      //判断这个 output 和 input key 的 size 等于 1
      if (op_input_output_key.find(op_desc->type_) !=
L
liuruilong 已提交
227
              op_input_output_key.end() &&
L
liuruilong 已提交
228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251
          inputs_and_outputs.first.size() == 1 &&
          inputs_and_outputs.second.size() == 1) {
        auto inputs_of_output = op_desc->Input(inputs_and_outputs.first[0]);
        auto outputs_of_output = op_desc->Output(inputs_and_outputs.second[0]);

        // 判断一下, 如果输入和输出没有同名, 是支持的
        for (int i = 0; i < inputs_of_output.size(); ++i) {
          std::string input_of_output = inputs_of_output[i];
          for (int j = 0; j < outputs_of_output.size(); ++j) {
            std::string output_of_output = outputs_of_output[j];
            if (input_of_output == output_of_output) {
              DLOG << "output的 output 包含 input" << input_of_output;
              can_add_split = false;
              break;
            }
          }
        }
      } else {  // 如果模型中包含没有的 op, 则不支持添加 split
        DLOG << "找不到 这个 op 类型: " << output->op_desc_->type_;
        can_add_split = false;
      }
    }
  }

L
liuruilong 已提交
252 253
  if (current_node->inputs_.size() > 1 &&
      input_node != current_node->inputs_.back()) {
L
liuruilong 已提交
254
    return;
L
liuruilong 已提交
255 256
  } else if (current_node->inputs_.size() > 1 &&
             input_node == current_node->inputs_.back()) {
L
liuruilong 已提交
257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279
    new_block.reset();
    adding_thread = false;
    op_desc->push_back(current_node->op_desc_);
  } else {
    if (new_block.get() && adding_thread) {
      new_block->ops_.push_back(current_node->op_desc_);
    } else {
      op_desc->push_back(current_node->op_desc_);
    }
  }
  if (adding_thread) {
    Attribute attr;
    attr.Set<int>(thread_num);
    current_node->op_desc_->attrs_["thread"] = attr;
  }

  if (can_add_split) {
    new_block = std::make_shared<BlockDesc>();
    new_block->multi_thread_ = true;
    new_block->index_ = current_block_;
    new_blocks_.push_back(new_block);

    adding_thread = true;
L
liuruilong 已提交
280
    std::shared_ptr<OpDesc> split_op_desc = std::make_shared<OpDesc>();
L
liuruilong 已提交
281 282
    split_op_desc->type_ = G_OP_TYPE_SPLIT;
    auto outputs = current_node->op_desc_->Output(
L
liuruilong 已提交
283
        op_input_output_key[current_node->op_desc_->Type()].second[0]);
L
liuruilong 已提交
284
    split_op_desc->inputs_ = {
L
liuruilong 已提交
285
        {op_input_output_key[G_OP_TYPE_SPLIT].first[0], outputs}};
L
liuruilong 已提交
286
    auto &split_outputs =
L
liuruilong 已提交
287
        split_op_desc->outputs_[op_input_output_key[G_OP_TYPE_SPLIT].second[0]];
L
liuruilong 已提交
288 289 290 291 292 293 294 295 296 297 298 299 300 301 302
    for (const auto &output : current_node->outputs_) {
      split_outputs.push_back(outputs[0]);
    }

    Attribute attr;
    attr.Set<int>(current_block_);
    split_op_desc->attrs_["block_id"] = attr;

    op_desc->push_back(split_op_desc);
    current_block_++;
  }

  for (int i = 0; i < current_node->outputs_.size(); ++i) {
    auto &output = current_node->outputs_[i];
    if (can_add_split) {
L
liuruilong 已提交
303 304
      GenerateOps(op_desc, current_node, output.get(), adding_thread, i,
                  new_block);
L
liuruilong 已提交
305
    } else {
L
liuruilong 已提交
306 307
      GenerateOps(op_desc, current_node, output.get(), adding_thread,
                  thread_num, new_block);
L
liuruilong 已提交
308 309 310 311
    }
  }
}

L
liuruilong 已提交
312
void ProgramOptimize::GenerateOps(
L
liuruilong 已提交
313 314
    std::vector<std::shared_ptr<framework::OpDesc>> *op_descs, Node *begin_node,
    bool can_add_split) {
L
liuruilong 已提交
315 316 317
  // std::vector<std::shared_ptr<framework::OpDesc>> *op_desc,
  //             Node *input_node, Node *current_node, bool adding_thread, int
  //             thread_num
L
liuruilong 已提交
318
  if (can_add_split) {
L
liuruilong 已提交
319 320 321 322
    this->GenerateOps(op_descs, begin_node, begin_node, false, -1, nullptr);
  } else {
    this->GenerateOps(op_descs, begin_node, begin_node);
  }
L
liuruilong 已提交
323 324
}

L
liuruilong 已提交
325 326
}  // namespace framework
}  // namespace paddle_mobile