eager_deletion_pass.cc 7.7 KB
Newer Older
S
sneaxiy 已提交
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.

S
sneaxiy 已提交
15 16
#include <algorithm>
#include <functional>
S
sneaxiy 已提交
17 18
#include <queue>
#include <string>
S
sneaxiy 已提交
19
#include <tuple>
S
sneaxiy 已提交
20 21 22 23 24 25 26 27
#include <vector>

#include "paddle/fluid/framework/details/computation_op_handle.h"
#include "paddle/fluid/framework/details/eager_deletion_op_handle.h"
#include "paddle/fluid/framework/details/eager_deletion_pass.h"
#include "paddle/fluid/framework/details/multi_devices_helper.h"
#include "paddle/fluid/framework/ir/graph_helper.h"

S
sneaxiy 已提交
28 29 30
DEFINE_double(fraction_of_eager_deletion, 1.0, "Fraction of eager deletion");
DEFINE_bool(eager_delete_tensor_only, false, "");

S
sneaxiy 已提交
31 32 33 34
namespace paddle {
namespace framework {
namespace details {

S
sneaxiy 已提交
35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 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 77 78 79 80 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
namespace {  // NOLINT
using OpToVarNameSetMap =
    std::unordered_map<ComputationOpHandle *, std::unordered_set<std::string>>;
}  // NOLINT

static bool IsLoDTensor(VarDesc *var) {
  return var->Proto()->type().type() == proto::VarType::LOD_TENSOR;
}

static int64_t GetNumel(const GraphVars &vars, const std::string &var_name,
                        size_t scope_idx) {
  auto *var_desc = TryGetLatestVarDesc(vars[scope_idx].at(var_name));
  PADDLE_ENFORCE(IsLoDTensor(var_desc));
  auto dims = var_desc->GetShape();
  return std::accumulate(dims.begin(), dims.end(), static_cast<int64_t>(1),
                         std::multiplies<int64_t>());
}

static void SplitIntoLoDTensorAndNonLoDTensorVars(
    const OpToVarNameSetMap &m, const GraphVars &vars,
    OpToVarNameSetMap *lod_tensors, OpToVarNameSetMap *other_vars) {
  lod_tensors->clear();
  other_vars->clear();

  for (auto &op_vars_pair : m) {
    for (auto &var_name : op_vars_pair.second) {
      auto *var_desc = TryGetLatestVarDesc(
          vars[op_vars_pair.first->GetScopeIdx()].at(var_name));
      if (IsLoDTensor(var_desc)) {
        (*lod_tensors)[op_vars_pair.first].insert(var_name);
      } else {
        (*other_vars)[op_vars_pair.first].insert(var_name);
      }
    }
  }
}

static OpToVarNameSetMap ShrinkGCVars(const OpToVarNameSetMap &m,
                                      const GraphVars &vars,
                                      double fraction_of_memory_size,
                                      bool delete_lod_tensor_only = false) {
  // Do not perform gc
  if (fraction_of_memory_size <= 0.0) return {};

  // Perform complete gc
  if (fraction_of_memory_size >= 1.0) {
    if (delete_lod_tensor_only) {
      OpToVarNameSetMap lod_tensors, other_vars;
      SplitIntoLoDTensorAndNonLoDTensorVars(m, vars, &lod_tensors, &other_vars);
      return lod_tensors;
    } else {
      return m;
    }
  }

  // Perform partial gc
  OpToVarNameSetMap lod_tensors, other_vars;
  SplitIntoLoDTensorAndNonLoDTensorVars(m, vars, &lod_tensors, &other_vars);

  using TupleType = std::tuple<std::string, ComputationOpHandle *, int64_t>;

  std::unordered_map<size_t, std::vector<TupleType>> place_to_vars;
  std::unordered_map<size_t, int64_t> total_memory_size;
  for (auto &op_vars_pair : lod_tensors) {
    auto scope_idx = op_vars_pair.first->GetScopeIdx();
    int64_t size = 0;
    for (auto &var_name : op_vars_pair.second) {
      auto var_size = GetNumel(vars, var_name, scope_idx);
      size += std::abs(var_size);
      place_to_vars[scope_idx].emplace_back(var_name, op_vars_pair.first,
                                            var_size);
    }
    total_memory_size.emplace(scope_idx, size);
  }

  for (auto &pair : place_to_vars) {
    std::sort(pair.second.begin(), pair.second.end(),
              [](const TupleType &t1, const TupleType &t2) {
                return std::abs(std::get<2>(t1)) > std::abs(std::get<2>(t2));
              });
  }

  OpToVarNameSetMap ret;
  for (auto &pair : place_to_vars) {
    auto desired_delete_size = static_cast<int64_t>(
        fraction_of_memory_size * total_memory_size.at(pair.first));
    int64_t cur_size = 0;
    for (size_t i = 0; i < pair.second.size() && cur_size < desired_delete_size;
         ++i) {
      auto &var_name = std::get<0>(pair.second[i]);
      auto *op = std::get<1>(pair.second[i]);
      cur_size += std::get<2>(pair.second[i]);
      ret[op].insert(var_name);
    }
  }

  if (!delete_lod_tensor_only) {
    for (auto &op_vars_pair : other_vars) {
      for (auto &var_name : op_vars_pair.second) {
        ret[op_vars_pair.first].insert(var_name);
      }
    }
  }

  return ret;
}

S
sneaxiy 已提交
142 143 144
std::unique_ptr<ir::Graph> EagerDeletionPass::ApplyImpl(
    std::unique_ptr<ir::Graph> graph) const {
  auto &ref_cnts =
S
sneaxiy 已提交
145
      Get<std::vector<AtomicReferenceCountMap>>(kRuntimeReferenceCount);
S
sneaxiy 已提交
146 147 148 149 150 151
  PADDLE_ENFORCE(ref_cnts.empty(),
                 "kRuntimeReferenceCount should be initialized here!");

  const auto &vars = graph->Get<GraphVars>(kGraphVars);
  ref_cnts.resize(vars.size());

S
fix bug  
sneaxiy 已提交
152 153
  const auto &last_live_ops =
      Get<std::vector<LastLiveOpsOfVars>>(kLastLiveOpsOfVars);
S
sneaxiy 已提交
154
  const auto &gcs = Get<GarbageCollectorMap>(kGarbageCollector);
S
sneaxiy 已提交
155
  const auto &places = Get<std::vector<platform::Place>>(kAllPlaces);
S
sneaxiy 已提交
156

S
sneaxiy 已提交
157 158
  // a reverse map of last_live_ops
  //   i.e., last op --> variable names which can be deleted.
S
sneaxiy 已提交
159
  OpToVarNameSetMap op_vars_map;
S
sneaxiy 已提交
160 161 162
  for (auto &var_ops_map : last_live_ops) {
    for (auto &var_ops_pair : var_ops_map) {
      const std::string &var_name = var_ops_pair.first;
S
fix bug  
sneaxiy 已提交
163 164
      for (auto *op : var_ops_pair.second) {
        op_vars_map[op].insert(var_name);
S
sneaxiy 已提交
165 166 167
      }
    }
  }
S
fix bug  
sneaxiy 已提交
168

S
sneaxiy 已提交
169 170 171 172
  op_vars_map =
      ShrinkGCVars(op_vars_map, vars, FLAGS_fraction_of_eager_deletion,
                   FLAGS_eager_delete_tensor_only);

S
fix bug  
sneaxiy 已提交
173 174 175 176 177 178 179
  for (auto &pair : op_vars_map) {
    auto *op = pair.first;
    auto &var_names = pair.second;

    auto *eager_deletion_node =
        graph->CreateEmptyNode("eager_deletion", ir::Node::Type::kOperation);
    auto *eager_deletion_op = new EagerDeletionOpHandle(
S
sneaxiy 已提交
180 181
        eager_deletion_node, op->GetScope(), op->GetPlace(), var_names,
        gcs.at(places[op->GetScopeIdx()]).get(),
S
fix bug  
sneaxiy 已提交
182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202
        &(ref_cnts[op->GetScopeIdx()]));

    auto it = std::find_if(
        op->Outputs().begin(), op->Outputs().end(), [](VarHandleBase *var) {
          return dynamic_cast<DummyVarHandle *>(var) != nullptr;
        });

    if (it != op->Outputs().end()) {
      eager_deletion_op->AddInput(*it);
    } else {
      auto *dep_var = new DummyVarHandle(graph->CreateControlDepVar());
      graph->Get<GraphDepVars>(kGraphDepVars).emplace(dep_var);
      op->AddOutput(dep_var);
      eager_deletion_op->AddInput(dep_var);
    }

    auto *dummy_leaf = new DummyVarHandle(graph->CreateControlDepVar());
    graph->Get<GraphDepVars>(kGraphDepVars).emplace(dummy_leaf);
    eager_deletion_op->AddOutput(dummy_leaf);
  }

S
sneaxiy 已提交
203 204 205 206
  VLOG(10) << "FLAGS_fraction_of_eager_deletion = "
           << FLAGS_fraction_of_eager_deletion;
  VLOG(10) << "FLAGS_eager_delete_tensor_only = "
           << FLAGS_eager_delete_tensor_only;
S
fix bug  
sneaxiy 已提交
207
  VLOG(10) << "Create " << op_vars_map.size() << " EagerDeletionOpHandle(s)";
S
sneaxiy 已提交
208 209 210 211 212 213 214 215 216
  return graph;
}

}  // namespace details
}  // namespace framework
}  // namespace paddle

REGISTER_PASS(eager_deletion_pass,
              paddle::framework::details::EagerDeletionPass)
S
sneaxiy 已提交
217
    .RequirePassAttr(paddle::framework::details::kRuntimeReferenceCount)
S
sneaxiy 已提交
218
    .RequirePassAttr(paddle::framework::details::kLastLiveOpsOfVars)
S
sneaxiy 已提交
219
    .RequirePassAttr(paddle::framework::details::kAllPlaces)
S
sneaxiy 已提交
220
    .RequirePassAttr(paddle::framework::details::kGarbageCollector);