memory_optimize_pass.cc 13.3 KB
Newer Older
Y
Yan Chunwei 已提交
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/inference/analysis/passes/memory_optimize_pass.h"
W
wanghuancoder 已提交
16

Y
Yan Chunwei 已提交
17
#include <string>
18
#include <unordered_set>
Y
Yan Chunwei 已提交
19
#include <utility>
20
#include <vector>
W
wanghuancoder 已提交
21

22
#include "glog/logging.h"
Y
Yan Chunwei 已提交
23
#include "paddle/fluid/framework/ir/graph_helper.h"
24
#include "paddle/fluid/inference/analysis/pass_result_info.h"
25
#include "paddle/fluid/platform/enforce.h"
W
wanghuancoder 已提交
26 27 28 29 30 31 32 33 34

namespace paddle {
namespace framework {
namespace ir {
class Graph;
class Node;
}  // namespace ir
}  // namespace framework
}  // namespace paddle
Y
Yan Chunwei 已提交
35 36 37 38 39 40 41 42 43 44

namespace paddle {
namespace inference {
namespace analysis {

using framework::ir::Graph;
using framework::ir::Node;
using framework::ir::TopologyVarientSort;
using space_table_t = MemoryOptimizePass::space_table_t;

45 46 47 48 49 50 51 52
typedef struct {
  std::string name;
  size_t size;
  int cluster;
  std::pair<int, int> lifetime;
  std::unordered_set<std::string> adj;
} MemNode;

Y
Yan Chunwei 已提交
53 54 55 56 57
// Collect the lifecycles of the tensors.
// Traverse the graph in topological order.
// The traversal order also affect the lifecycles, so different sort_kind is
// used.
void MemoryOptimizePass::CollectLifeCycle(
58 59
    Graph* graph,
    std::unordered_map<std::string, lifecycle_t>* lifecycles,
Y
Yan Chunwei 已提交
60
    int sort_kind) const {
61
  int max_lifecycle = 0;
Y
Yan Chunwei 已提交
62
  for (auto* op_node : framework::ir::TopologyVarientSort(
63
           *graph, static_cast<framework::ir::SortKind>(sort_kind))) {
Y
Yan Chunwei 已提交
64 65 66 67
    if (!op_node->IsOp()) continue;
    auto reads = op_node->inputs;
    auto writes = op_node->outputs;

68 69
    std::vector<Node*>
    requires(reads.begin(), reads.end());
Y
Yan Chunwei 已提交
70 71 72 73 74 75 76 77 78 79 80 81
    requires.insert(requires.end(), writes.begin(), writes.end());

    // Disable reuse of feed variables.
    if (op_node->Name() == "feed") {
      for (auto* node : op_node->outputs) {
        auto var = node->Name();
        lifecycles->emplace(var,
                            std::make_pair(0, std::numeric_limits<int>::max()));
      }
    } else {
      // Normal operators.
      for (const Node* node : requires) {
82
        if (!node->Var()) continue;
Y
Yan Chunwei 已提交
83 84 85
        if (node->Var()->Persistable()) continue;
        std::string var = node->Name();
        if (!lifecycles->count(var)) {
86
          (*lifecycles)[var] = std::make_pair(max_lifecycle, max_lifecycle);
Y
Yan Chunwei 已提交
87 88
        } else {
          (*lifecycles)[var].second =
89
              std::max(max_lifecycle, lifecycles->at(var).second);  // max()
Y
Yan Chunwei 已提交
90 91 92 93
        }
      }
    }

94
    ++max_lifecycle;
Y
Yan Chunwei 已提交
95 96 97
  }
}

98
void MemoryOptimizePass::CollectVarMemorySize(
99
    Graph* graph, space_table_t* space_table) const {
100
  const int fake_batch_size = 1;
101

102
  auto valid_var = [&](framework::ir::Node* node) -> bool {
103
    // lod operator reuse may cause unknown errors.
104 105
    std::set<std::string> invalid_op = {"while",
                                        "conditional_block",
106
                                        "tensorrt_engine",
107 108 109 110
                                        "conditional_block_infer",
                                        "merge_lod_tensor_infer",
                                        "merge_lod_tensor",
                                        "equal",
111
                                        "sequence_pool",
112
                                        "recurrent",
113
                                        "lod_reset",
114 115
                                        "fetch",
                                        "share_data"};
116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133
    for (auto* tmp : node->inputs) {
      CHECK(tmp->IsOp());
      std::string op_type = tmp->Op()->Type();
      if (std::find(invalid_op.begin(), invalid_op.end(), op_type) !=
          invalid_op.end()) {
        return false;
      }
    }
    for (auto* tmp : node->outputs) {
      CHECK(tmp->IsOp());
      std::string op_type = tmp->Op()->Type();
      if (std::find(invalid_op.begin(), invalid_op.end(), op_type) !=
          invalid_op.end()) {
        return false;
      }
    }
    return true;
  };
W
wenbin 已提交
134 135 136 137 138

  // MemoryOptimizePass surppose input model is directed acyclic graph
  // although it's not always the case. so black list is the best compromise
  // between performance and underlying principle.
  std::unordered_set<std::string> black_list;
139
  for (auto* node : graph->Nodes()) {
140
    if (node->IsVar() && node->Var() &&
W
wenbin 已提交
141 142 143 144 145 146 147 148
        node->Var()->GetType() ==
            framework::proto::VarType::Type::VarType_Type_LOD_TENSOR) {
      if (!valid_var(node)) {
        black_list.emplace(node->Var()->Name());
      }
    }
  }

149
  // Collect tensors from graph.
150
  for (auto* node : graph->Nodes()) {
151
    if (node->IsVar() && node->Var() &&
152
        node->Var()->GetType() ==
153
            framework::proto::VarType::Type::VarType_Type_LOD_TENSOR &&
W
wenbin 已提交
154
        !black_list.count(node->Var()->Name())) {
155 156 157 158 159 160 161
      // Parameters will not be reused.
      if (node->Var()->Persistable()) continue;
      auto shape = node->Var()->GetShape();
      for (auto& v : shape) {
        if (v < 0) v = fake_batch_size;
      }

162 163
      int size = std::accumulate(
          shape.begin(), shape.end(), 1, std::multiplies<int>());
164
      (*space_table)[node->Var()->Name()] =
165
          size * paddle::framework::SizeOfType(node->Var()->GetDataType());
166 167 168 169 170 171 172 173 174 175 176
    }
  }
}

void MakeSimpleReusePlan(
    const std::unordered_map<std::string, std::pair<int, int>>& lifecycles,
    const std::unordered_map<std::string, size_t>& space_table,
    std::unordered_map<std::string, std::string>* node2cluster,
    std::unordered_map<std::string, int>* cluster_size) {
  std::vector<MemNode> mem_nodes;
  for (auto& data : lifecycles) {
177
    if (!space_table.count(data.first)) continue;
178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 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
    MemNode temp_node;
    temp_node.name = data.first;
    temp_node.size = space_table.at(data.first);
    temp_node.cluster = -1;
    temp_node.lifetime = data.second;
    mem_nodes.push_back(temp_node);
  }
  auto overlap = [](std::pair<int, int> a, std::pair<int, int> b) -> bool {
    return b.second >= a.first && a.second >= b.first;
  };
  // If the lifetime of two nodes is overwritten, we set them as adjacent nodes.
  for (size_t i = 0; i < mem_nodes.size(); i++) {
    for (size_t j = i + 1; j < mem_nodes.size(); j++) {
      if (overlap(mem_nodes[i].lifetime, mem_nodes[j].lifetime)) {
        mem_nodes[i].adj.insert(mem_nodes[j].name);
        mem_nodes[j].adj.insert(mem_nodes[i].name);
      }
    }
  }

  // Sort the nodes according to the node memory size.
  auto sort_func = [](MemNode a, MemNode b) { return a.size > b.size; };
  std::sort(mem_nodes.begin(), mem_nodes.end(), sort_func);

  // Generating Memory Reuse Strategy Based on Greedy Way
  for (size_t i = 0; i < mem_nodes.size(); i++) {
    if (mem_nodes[i].cluster >= 0) continue;
    int cluster_index = cluster_size->size();
    mem_nodes[i].cluster = cluster_index;
    (*cluster_size)[mem_nodes[i].name] = mem_nodes[i].size;
    (*node2cluster)[mem_nodes[i].name] = mem_nodes[i].name;
    std::unordered_set<std::string> cluster_adj = mem_nodes[i].adj;
    for (size_t j = i + 1; j < mem_nodes.size(); j++) {
      if (mem_nodes[j].cluster < 0 &&
          (cluster_adj.find(mem_nodes[j].name) == cluster_adj.end())) {
        (*node2cluster)[mem_nodes[j].name] = mem_nodes[i].name;
        mem_nodes[j].cluster = cluster_index;
        for (auto& n : mem_nodes[j].adj) {
          cluster_adj.insert(n);
        }
      }
    }
  }
  for (auto& cluster : *cluster_size) {
    LOG(INFO) << "Cluster name : " << cluster.first
              << "  size: " << cluster.second;
  }
}

227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271
// Remove the inplace operation from the plan because it does not support memory
// reuse
void DelInplaceOpFromPlan(
    Graph* graph,
    std::unordered_map<std::string, std::string>* node2cluster,
    int sort_kind) {
  auto topo_nodes = TopologyVarientSort(
      *graph, static_cast<framework::ir::SortKind>(sort_kind));
  for (auto* op_node : topo_nodes) {
    if (!op_node->IsOp()) continue;
    auto input_tensors = op_node->inputs;
    auto output_tensors = op_node->outputs;

    std::unordered_set<std::string> in_names;
    for (const Node* node : input_tensors) {
      if (!node->Var()) continue;
      if (node->Var()->Persistable()) continue;
      std::string var = node->Name();
      in_names.insert(var);
    }

    for (const Node* node : output_tensors) {
      if (!node->Var()) continue;
      if (node->Var()->Persistable()) continue;
      std::string var = node->Name();
      if (in_names.find(var) != in_names.end()) {
        // delete key
        if (node2cluster->count(var)) {
          node2cluster->erase(var);
        }
        // delete value
        std::string tmp_name = "";
        for (auto it = node2cluster->begin(); it != node2cluster->end(); ++it) {
          if (it->second == var) {
            if (tmp_name == "") {
              tmp_name = it->first;
            }
            it->second = tmp_name;
          }
        }
      }
    }
  }
}

Y
Yan Chunwei 已提交
272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294
// NOTE The optimized opdesc doesn't match ir::Graph.
void UpdateOpDescsByReuse(
    Graph* graph,
    const std::unordered_map<std::string, std::string>& reuse_table,
    int sort_kind) {
  // TODO(Superjomn) change here to be compatible with the runtime order.
  for (auto* node : TopologyVarientSort(
           *graph, static_cast<framework::ir::SortKind>(sort_kind))) {
    if (node->IsOp()) {
      // Replace the original inputs/outputs with the reused tensors.
      std::unordered_map<std::string, std::vector<std::string>> in_args,
          out_args;
      for (auto argument : node->Op()->Inputs()) {
        for (const auto& x : argument.second) {
          auto name = x;
          if (reuse_table.count(x) && reuse_table.at(x) != x) {
            name = reuse_table.at(x);
          }
          in_args[argument.first].push_back(name);
          VLOG(4) << node->Name() << " input " << x << " -> " << name;
        }
      }

295 296
      // modify the graph
      for (auto input_node : node->inputs) {
297 298
        PADDLE_ENFORCE_EQ(input_node->IsVar(),
                          true,
299 300
                          platform::errors::PreconditionNotMet(
                              "The input node should be a variable."));
301 302 303 304 305 306 307 308
        std::string input_node_name = input_node->Name();
        if (reuse_table.count(input_node_name) &&
            reuse_table.at(input_node_name) != input_node_name) {
          auto name = reuse_table.at(input_node_name);
          input_node->RenameVar(name);
        }
      }

Y
Yan Chunwei 已提交
309 310 311 312 313 314 315 316 317 318 319
      for (auto argument : node->Op()->Outputs()) {
        for (const auto& x : argument.second) {
          auto name = x;
          if (reuse_table.count(x) && reuse_table.at(x) != x) {
            name = reuse_table.at(x);
          }
          out_args[argument.first].push_back(name);
          VLOG(4) << node->Name() << " output " << x << " -> " << name;
        }
      }

320 321
      // modify the graph
      for (auto out_node : node->outputs) {
322 323
        PADDLE_ENFORCE_EQ(out_node->IsVar(),
                          true,
324 325
                          platform::errors::PreconditionNotMet(
                              "The output node should be a variable."));
326 327 328 329 330 331 332 333
        std::string out_node_name = out_node->Name();
        if (reuse_table.count(out_node_name) &&
            reuse_table.at(out_node_name) != out_node_name) {
          auto name = reuse_table.at(out_node_name);
          out_node->RenameVar(name);
        }
      }

Y
Yan Chunwei 已提交
334 335 336 337 338 339 340 341 342 343 344 345
      // Update arguments.
      for (auto& arg : in_args) {
        node->Op()->SetInput(arg.first, arg.second);
      }
      for (auto& arg : out_args) {
        node->Op()->SetOutput(arg.first, arg.second);
      }
      node->Op()->Flush();
    }
  }
}

346
std::string MemoryOptimizePass::repr() const { return "memory_optimize_pass"; }
Y
Yan Chunwei 已提交
347 348

void MemoryOptimizePass::RunImpl(Argument* argument) {
349 350 351 352 353 354 355 356 357 358 359
  // Memory optimization.
  // We will perform the following operation:
  // 1. Collect all var's lifetime.
  // 2. Make reuse plan: the vars can be reused if there is no overlap(on
  // lifetime) between
  // them.
  // The final plan is a mapping table in which the key represents the original
  // name of var and the value in the table represents the current name of var.
  // 3. Perform reuse plan: Replace all var's name in the model according to the
  // mapping table.
  if (!argument->enable_memory_optim()) return;
360
  // Because of pass is a singleton, graph can not be member
361
  // variables,otherwise, errors will be caused under multithreading
362 363
  // conditions.
  auto graph = argument->main_graph_ptr();
Y
Yan Chunwei 已提交
364

365 366
  int sort_kind = 0;
  std::unordered_map<std::string, lifecycle_t> lifecycles;
Y
Yan Chunwei 已提交
367
  space_table_t space_table;
368 369 370
  std::unordered_map<std::string, std::string> node2cluster;
  std::unordered_map<std::string, int> cluster_size;

371 372
  CollectLifeCycle(graph, &lifecycles, sort_kind);
  CollectVarMemorySize(graph, &space_table);
373
  MakeSimpleReusePlan(lifecycles, space_table, &node2cluster, &cluster_size);
374
  DelInplaceOpFromPlan(graph, &node2cluster, sort_kind);
375 376 377 378 379

  auto* pass_res_info = PassResultInfoForRuntime::Instance();
  pass_res_info->Set(
      argument->root_predictor_id(), "memory_optimize_pass", node2cluster);

380
  return;
Y
Yan Chunwei 已提交
381 382 383 384 385
}

}  // namespace analysis
}  // namespace inference
}  // namespace paddle