eager_deletion_op_handle.cc 6.9 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.

15 16
#include "paddle/fluid/framework/details/eager_deletion_op_handle.h"

17
#include "paddle/fluid/framework/ir/memory_optimize_pass/memory_optimization_var_info.h"
18
#include "paddle/fluid/platform/profiler/event_tracing.h"
19
#if defined(PADDLE_WITH_CUDA) || defined(PADDLE_WITH_HIP)
S
fix bug  
sneaxiy 已提交
20
#include "paddle/fluid/platform/cuda_device_guard.h"
S
sneaxiy 已提交
21
#endif
Z
Zeng Jinle 已提交
22
#include <algorithm>
S
sneaxiy 已提交
23

24 25 26 27 28 29
namespace paddle {
namespace framework {
class Variable;
}  // namespace framework
}  // namespace paddle

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

EagerDeletionOpHandle::EagerDeletionOpHandle(
35 36
    ir::Node *node, Scope *scope, size_t scope_idx,
    const platform::Place &place,
37
    const std::unordered_set<ir::MemOptVarInfo *> &vars, GarbageCollector *gc)
S
fix bug  
sneaxiy 已提交
38 39
    : OpHandleBase(node),
      scope_(scope),
40
      scope_idx_(scope_idx),
41 42 43
      place_(place),
      var_infos_(vars.begin(), vars.end()),
      gc_(gc) {
44
#if defined(PADDLE_WITH_CUDA) || defined(PADDLE_WITH_HIP)
S
sneaxiy 已提交
45
  if (platform::is_gpu_place(place)) {
S
sneaxiy 已提交
46
    dev_ctx_ = reinterpret_cast<platform::CUDADeviceContext *>(
S
sneaxiy 已提交
47
        platform::DeviceContextPool::Instance().Get(place));
S
sneaxiy 已提交
48
    if (dynamic_cast<StreamGarbageCollector *>(gc_)) {
49
      platform::CUDADeviceGuard guard(place.device);
50
#ifdef PADDLE_WITH_HIP
51
      PADDLE_ENFORCE_GPU_SUCCESS(
52 53
          hipEventCreateWithFlags(&event_, hipEventDisableTiming));
#else
54
      PADDLE_ENFORCE_GPU_SUCCESS(
55
          cudaEventCreateWithFlags(&event_, cudaEventDisableTiming));
56
#endif
57 58
      PADDLE_ENFORCE_NOT_NULL(event_, platform::errors::InvalidArgument(
                                          "The cuda envet created is NULL."));
S
sneaxiy 已提交
59 60 61
    }
  }
#endif
62 63 64
  PADDLE_ENFORCE_NE(vars.empty(), true,
                    platform::errors::InvalidArgument(
                        "The variables to be deleted are empty."));
65
  for (auto *var : var_infos_) {
66 67
    PADDLE_ENFORCE_NOT_NULL(var, platform::errors::InvalidArgument(
                                     "The memory optimization info is NULL."));
68
  }
S
sneaxiy 已提交
69 70 71
}

EagerDeletionOpHandle::~EagerDeletionOpHandle() {
72
#if defined(PADDLE_WITH_CUDA) || defined(PADDLE_WITH_HIP)
S
sneaxiy 已提交
73
  if (event_) {
74
    auto gpu_place = dev_ctx_->GetPlace();
S
fix bug  
sneaxiy 已提交
75
    platform::CUDADeviceGuard guard(gpu_place.device);
76
#ifdef PADDLE_WITH_HIP
77
    PADDLE_ENFORCE_GPU_SUCCESS(hipEventDestroy(event_));
78
#else
79
    PADDLE_ENFORCE_GPU_SUCCESS(cudaEventDestroy(event_));
80
#endif
S
sneaxiy 已提交
81 82 83 84
  }
#endif
}

85
void EagerDeletionOpHandle::InitCUDA() {
86
#if defined(PADDLE_WITH_CUDA) || defined(PADDLE_WITH_HIP)
87
  int dev_id = dev_ctxes_.begin()->first.device;
88 89 90 91 92
  events_[dev_id] = nullptr;
#endif
}

void EagerDeletionOpHandle::CallOnce() {
93 94 95 96
  PADDLE_ENFORCE_EQ(
      vars_.empty(), true,
      platform::errors::InvalidArgument(
          "The variables to be deleted should be initialized here."));
97 98 99
  Scope *exec_scope = local_exec_scopes_[0];
  for (auto *var_info : var_infos_) {
    auto *var = exec_scope->FindVar(var_info->Name());
100 101 102 103
    PADDLE_ENFORCE_NOT_NULL(
        var, platform::errors::NotFound(
                 "The variable(%s) to be inplaced is not found in scope.",
                 var_info->Name()));
104 105 106 107
    vars_.emplace_back(var);
  }
}

S
sneaxiy 已提交
108
std::string EagerDeletionOpHandle::Name() const { return "eager_deletion"; }
S
sneaxiy 已提交
109

110 111 112 113 114 115 116 117 118 119 120 121 122 123 124
static bool CanBeErased(ir::MemOptVarInfo *var_info) {
  if (var_info->IsSkippedAllMemoryOptimization() ||
      !var_info->DecreaseRefCnt()) {
    return false;
  }
#ifdef PADDLE_WITH_CINN
  // if parent_holder exists, it should meet deletion condition too.
  std::shared_ptr<ir::MemOptVarInfo> parent_holder = var_info->ParentHolder();
  if (parent_holder && !CanBeErased(parent_holder.get())) {
    return false;
  }
#endif
  return true;
}

S
sneaxiy 已提交
125
void EagerDeletionOpHandle::RunImpl() {
126 127
  if (vars_.size() != var_infos_.size() || is_variant_scope_) {
    vars_.clear();
128 129 130
    CallOnce();
  }

131 132
  platform::RecordEvent record_event(Name(),
                                     platform::TracerEventType::UserDefined, 2);
S
sneaxiy 已提交
133
  std::deque<std::shared_ptr<memory::Allocation>> garbages;
134 135
  for (size_t i = 0; i < var_infos_.size(); ++i) {
    auto *var_info = var_infos_[i];
136
    if (!CanBeErased(var_info)) {
137
      VLOG(4) << "skip memory optimization with var: " << var_info->Name();
S
sneaxiy 已提交
138 139 140
      continue;
    }

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

143
    Variable *var = vars_[i];
S
sneaxiy 已提交
144

S
sneaxiy 已提交
145
    if (var->IsType<LoDTensor>()) {
S
sneaxiy 已提交
146
      garbages.emplace_back(var->GetMutable<LoDTensor>()->MoveMemoryHolder());
147 148 149 150
    } else if (var->IsType<pten::SelectedRows>()) {
      garbages.emplace_back(var->GetMutable<pten::SelectedRows>()
                                ->mutable_value()
                                ->MoveMemoryHolder());
S
sneaxiy 已提交
151
    } else if (var->IsType<LoDTensorArray>()) {
S
sneaxiy 已提交
152 153
      auto *tensor_arr = var->GetMutable<LoDTensorArray>();
      for (auto &t : *tensor_arr) {
S
sneaxiy 已提交
154
        garbages.emplace_back(t.MoveMemoryHolder());
S
sneaxiy 已提交
155
      }
S
sneaxiy 已提交
156
    } else {
157 158 159
      PADDLE_THROW(platform::errors::Unimplemented(
          "The variable(%s) of type %s is not supported in eager deletion.",
          framework::ToTypeName(var->Type()), var_info->Name()));
S
sneaxiy 已提交
160 161 162
    }
  }

S
sneaxiy 已提交
163 164
  if (!garbages.empty()) {
    ClearGarbages(&garbages);
S
sneaxiy 已提交
165 166 167
  }
}

S
sneaxiy 已提交
168 169
void EagerDeletionOpHandle::ClearGarbages(
    std::deque<std::shared_ptr<memory::Allocation>> *garbages) {
170
#if defined(PADDLE_WITH_CUDA) || defined(PADDLE_WITH_HIP)
S
sneaxiy 已提交
171 172 173
  if (event_) {
    auto compute_stream = dev_ctx_->stream();
    auto callback_stream =
S
sneaxiy 已提交
174
        reinterpret_cast<StreamGarbageCollector *>(gc_)->stream();
S
sneaxiy 已提交
175
    auto callback_func = [=]() {
176
#ifdef PADDLE_WITH_HIP
177 178
      PADDLE_ENFORCE_GPU_SUCCESS(hipEventRecord(event_, compute_stream));
      PADDLE_ENFORCE_GPU_SUCCESS(
179 180
          hipStreamWaitEvent(callback_stream, event_, 0));
#else
181 182
      PADDLE_ENFORCE_GPU_SUCCESS(cudaEventRecord(event_, compute_stream));
      PADDLE_ENFORCE_GPU_SUCCESS(
183
          cudaStreamWaitEvent(callback_stream, event_, 0));
184
#endif
S
sneaxiy 已提交
185
    };
S
sneaxiy 已提交
186
    gc_->Add(std::move(*garbages), callback_func);
S
sneaxiy 已提交
187 188
  } else {
#endif
S
sneaxiy 已提交
189
    gc_->Add(std::move(*garbages));
190
#if defined(PADDLE_WITH_CUDA) || defined(PADDLE_WITH_HIP)
S
sneaxiy 已提交
191 192 193 194
  }
#endif
}

Z
Zeng Jinle 已提交
195 196 197 198 199 200 201 202 203 204
std::vector<std::string> EagerDeletionOpHandle::VarsToDelete() const {
  std::vector<std::string> var_names;
  var_names.reserve(var_infos_.size());
  for (auto &info : var_infos_) {
    var_names.emplace_back(info->Name());
  }
  std::sort(var_names.begin(), var_names.end());
  return var_names;
}

S
sneaxiy 已提交
205 206 207
}  // namespace details
}  // namespace framework
}  // namespace paddle