eager_deletion_op_handle.cc 5.0 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 17 18
#include <memory>
#include <unordered_set>
#include <utility>

S
sneaxiy 已提交
19
#include "paddle/fluid/framework/details/eager_deletion_op_handle.h"
20
#include "paddle/fluid/framework/ir/memory_optimize_pass/memory_optimization_var_info.h"
S
sneaxiy 已提交
21 22 23
#include "paddle/fluid/framework/lod_tensor_array.h"
#include "paddle/fluid/framework/scope.h"
#include "paddle/fluid/framework/selected_rows.h"
24
#include "paddle/fluid/platform/profiler.h"
S
sneaxiy 已提交
25
#ifdef PADDLE_WITH_CUDA
S
fix bug  
sneaxiy 已提交
26
#include "paddle/fluid/platform/cuda_device_guard.h"
S
sneaxiy 已提交
27
#endif
S
sneaxiy 已提交
28 29 30 31 32 33

namespace paddle {
namespace framework {
namespace details {

EagerDeletionOpHandle::EagerDeletionOpHandle(
34 35
    ir::Node *node, Scope *scope, size_t scope_idx,
    const platform::Place &place,
36
    const std::unordered_set<ir::MemOptVarInfo *> &vars, GarbageCollector *gc)
S
fix bug  
sneaxiy 已提交
37 38
    : OpHandleBase(node),
      scope_(scope),
39
      scope_idx_(scope_idx),
40 41 42
      place_(place),
      var_infos_(vars.begin(), vars.end()),
      gc_(gc) {
S
sneaxiy 已提交
43 44
#ifdef PADDLE_WITH_CUDA
  if (platform::is_gpu_place(place)) {
S
sneaxiy 已提交
45
    dev_ctx_ = reinterpret_cast<platform::CUDADeviceContext *>(
S
sneaxiy 已提交
46
        platform::DeviceContextPool::Instance().Get(place));
S
sneaxiy 已提交
47
    if (dynamic_cast<StreamGarbageCollector *>(gc_)) {
S
fix bug  
sneaxiy 已提交
48 49
      platform::CUDADeviceGuard guard(
          boost::get<platform::CUDAPlace>(place).device);
S
sneaxiy 已提交
50
      PADDLE_ENFORCE(cudaEventCreateWithFlags(&event_, cudaEventDisableTiming));
S
fix bug  
sneaxiy 已提交
51
      PADDLE_ENFORCE_NOT_NULL(event_);
S
sneaxiy 已提交
52 53 54
    }
  }
#endif
55 56
  PADDLE_ENFORCE_NE(vars.empty(), true, platform::errors::InvalidArgument(
                                            "Variable names are empty."));
57 58 59
  for (auto *var : var_infos_) {
    PADDLE_ENFORCE_NOT_NULL(var);
  }
S
sneaxiy 已提交
60 61 62 63 64 65
}

EagerDeletionOpHandle::~EagerDeletionOpHandle() {
#ifdef PADDLE_WITH_CUDA
  if (event_) {
    auto gpu_place = boost::get<platform::CUDAPlace>(dev_ctx_->GetPlace());
S
fix bug  
sneaxiy 已提交
66
    platform::CUDADeviceGuard guard(gpu_place.device);
S
sneaxiy 已提交
67 68 69 70 71
    PADDLE_ENFORCE(cudaEventDestroy(event_));
  }
#endif
}

72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90
void EagerDeletionOpHandle::InitCUDA() {
#ifdef PADDLE_WITH_CUDA
  int dev_id =
      boost::get<platform::CUDAPlace>(dev_ctxes_.begin()->first).device;
  events_[dev_id] = nullptr;
#endif
}

void EagerDeletionOpHandle::CallOnce() {
  PADDLE_ENFORCE(vars_.empty(), "vars_ must be initialized here");
  Scope *exec_scope = local_exec_scopes_[0];
  for (auto *var_info : var_infos_) {
    auto *var = exec_scope->FindVar(var_info->Name());
    PADDLE_ENFORCE_NOT_NULL(var, "Variable %s should not be nullptr",
                            var_info->Name());
    vars_.emplace_back(var);
  }
}

S
sneaxiy 已提交
91
std::string EagerDeletionOpHandle::Name() const { return "eager_deletion"; }
S
sneaxiy 已提交
92 93

void EagerDeletionOpHandle::RunImpl() {
94 95 96 97
  if (vars_.size() != var_infos_.size()) {
    CallOnce();
  }

98
  platform::RecordEvent record_event(Name());
S
sneaxiy 已提交
99
  std::deque<std::shared_ptr<memory::Allocation>> garbages;
100 101
  for (size_t i = 0; i < var_infos_.size(); ++i) {
    auto *var_info = var_infos_[i];
102 103
    if (var_info->IsSkippedAllMemoryOptimization() ||
        !var_info->DecreaseRefCnt()) {
S
sneaxiy 已提交
104 105 106
      continue;
    }

107
    VLOG(2) << "Erase variable " << var_info->Name() << " on " << place_;
S
sneaxiy 已提交
108

109
    Variable *var = vars_[i];
S
sneaxiy 已提交
110

S
sneaxiy 已提交
111
    if (var->IsType<LoDTensor>()) {
S
sneaxiy 已提交
112
      garbages.emplace_back(var->GetMutable<LoDTensor>()->MoveMemoryHolder());
S
sneaxiy 已提交
113
    } else if (var->IsType<SelectedRows>()) {
S
sneaxiy 已提交
114
      garbages.emplace_back(
S
sneaxiy 已提交
115
          var->GetMutable<SelectedRows>()->mutable_value()->MoveMemoryHolder());
S
sneaxiy 已提交
116
    } else if (var->IsType<LoDTensorArray>()) {
S
sneaxiy 已提交
117 118
      auto *tensor_arr = var->GetMutable<LoDTensorArray>();
      for (auto &t : *tensor_arr) {
S
sneaxiy 已提交
119
        garbages.emplace_back(t.MoveMemoryHolder());
S
sneaxiy 已提交
120
      }
S
sneaxiy 已提交
121 122
    } else {
      PADDLE_THROW("Type %s of %s is not supported eager deletion",
123
                   framework::ToTypeName(var->Type()), var_info->Name());
S
sneaxiy 已提交
124 125 126
    }
  }

S
sneaxiy 已提交
127 128
  if (!garbages.empty()) {
    ClearGarbages(&garbages);
S
sneaxiy 已提交
129 130 131
  }
}

S
sneaxiy 已提交
132 133
void EagerDeletionOpHandle::ClearGarbages(
    std::deque<std::shared_ptr<memory::Allocation>> *garbages) {
S
sneaxiy 已提交
134 135 136 137
#ifdef PADDLE_WITH_CUDA
  if (event_) {
    auto compute_stream = dev_ctx_->stream();
    auto callback_stream =
S
sneaxiy 已提交
138
        reinterpret_cast<StreamGarbageCollector *>(gc_)->stream();
S
sneaxiy 已提交
139 140 141 142
    auto callback_func = [=]() {
      PADDLE_ENFORCE(cudaEventRecord(event_, compute_stream));
      PADDLE_ENFORCE(cudaStreamWaitEvent(callback_stream, event_, 0));
    };
S
sneaxiy 已提交
143
    gc_->Add(std::move(*garbages), callback_func);
S
sneaxiy 已提交
144 145
  } else {
#endif
S
sneaxiy 已提交
146
    gc_->Add(std::move(*garbages));
S
sneaxiy 已提交
147 148 149 150 151 152 153 154
#ifdef PADDLE_WITH_CUDA
  }
#endif
}

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