allocator_facade.cc 8.8 KB
Newer Older
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/memory/allocation/allocator.h"
S
sneaxiy 已提交
16
#include <gflags/gflags.h>
17
#include <map>
S
sneaxiy 已提交
18
#include <unordered_map>
19 20 21
#include <vector>
#include "paddle/fluid/memory/allocation/aligned_allocator.h"
#include "paddle/fluid/memory/allocation/allocator_facade.h"
Y
Yu Yang 已提交
22
#include "paddle/fluid/memory/allocation/auto_increment_allocator.h"
23
#include "paddle/fluid/memory/allocation/best_fit_allocator.h"
Y
Yu Yang 已提交
24
#include "paddle/fluid/memory/allocation/conditional_allocator.h"
25 26 27
#include "paddle/fluid/memory/allocation/cpu_allocator.h"
#include "paddle/fluid/memory/allocation/locked_allocator.h"
#include "paddle/fluid/memory/allocation/naive_managed_allocator.h"
S
sneaxiy 已提交
28
#include "paddle/fluid/memory/allocation/retry_allocator.h"
Y
Yu Yang 已提交
29
#include "paddle/fluid/memory/allocation/zero_size_allocator.h"
S
sneaxiy 已提交
30
#include "paddle/fluid/platform/cpu_info.h"
31 32 33
#include "paddle/fluid/platform/place.h"
#ifdef PADDLE_WITH_CUDA
#include "paddle/fluid/memory/allocation/cuda_allocator.h"
S
sneaxiy 已提交
34 35 36
#include "paddle/fluid/memory/allocation/pinned_allocator.h"
#include "paddle/fluid/platform/cuda_device_guard.h"
#include "paddle/fluid/platform/gpu_info.h"
37 38
#endif

S
sneaxiy 已提交
39
DEFINE_int64(
S
sneaxiy 已提交
40 41 42 43
    gpu_allocator_retry_time, 0,
    "The retry time (milliseconds) when allocator fails "
    "to allocate memory. No retry if this value is not greater than 0");

44 45 46 47
namespace paddle {
namespace memory {
namespace allocation {

Y
Yu Yang 已提交
48
// TODO(yy): Dirty code here. This class should be configurable in runtime.
Y
Yu Yang 已提交
49 50 51 52
class CPUManagedAllocator : public ManagedAllocator {
 public:
  CPUManagedAllocator()
      : normal_allocator_(NaiveManagedAllocator::Create(
S
sneaxiy 已提交
53
            std::unique_ptr<Allocator>(new CPUAllocator()))) {}
Y
Yu Yang 已提交
54 55

  std::unique_ptr<Allocation> Allocate(size_t size, Attr attr) override {
S
sneaxiy 已提交
56
    return normal_allocator_->Allocate(size, attr);
Y
Yu Yang 已提交
57 58 59
  }

  std::shared_ptr<Allocation> AllocateShared(size_t size, Attr attr) override {
S
sneaxiy 已提交
60
    return normal_allocator_->AllocateShared(size, attr);
Y
Yu Yang 已提交
61
  }
S
sneaxiy 已提交
62

Y
Yu Yang 已提交
63
  bool IsAllocThreadSafe() const override { return true; }
Y
Yu Yang 已提交
64 65 66 67 68

 private:
  std::shared_ptr<ManagedAllocator> normal_allocator_;
};

Y
Yu Yang 已提交
69
// TODO(yy): Dirty code here. This class should be configurable in runtime.
S
sneaxiy 已提交
70
class ChunkedManagedAllocator : public ManagedAllocator {
71
 public:
S
sneaxiy 已提交
72 73 74 75 76
  explicit ChunkedManagedAllocator(std::unique_ptr<Allocator> system_allocator,
                                   size_t max_chunk_size, size_t capacity = 1,
                                   int64_t retry_time = -1)
      : max_chunk_size_(max_chunk_size), retry_time_(retry_time) {
    raw_allocator_ = NaiveManagedAllocator::Create(std::move(system_allocator));
S
sneaxiy 已提交
77 78 79 80 81

    if (max_chunk_size_ == 0) {
      default_allocator_ = raw_allocator_;
    } else {
      if (capacity == 1) {
S
sneaxiy 已提交
82 83
        VLOG(10) << "Create BestFitAllocator with chunk_size "
                 << max_chunk_size_;
S
sneaxiy 已提交
84 85
        default_allocator_ = BestFitAllocatorCreator();
      } else {
S
sneaxiy 已提交
86 87
        VLOG(10) << "Create AutoIncrementAllocator with chunk_size "
                 << max_chunk_size_ << " and capacity " << capacity;
S
sneaxiy 已提交
88 89 90 91
        default_allocator_ = std::make_shared<AutoIncrementAllocator>(
            [this] { return std::move(BestFitAllocatorCreator()); }, capacity);
      }
    }
Y
Yu Yang 已提交
92 93 94 95 96 97 98 99 100 101 102 103

    auto* cond_allocator = new ConditionalAllocator();
    cond_allocator
        ->AddAllocator(
            [this](size_t size, Attr attr) { return size < max_chunk_size_; },
            default_allocator_)
        .AddAllocator(
            [](size_t size, Attr attr) {
              return true;  // default case
            },
            raw_allocator_);
    default_allocator_.reset(cond_allocator);
Y
Yu Yang 已提交
104
  }
105

S
sneaxiy 已提交
106
  ~ChunkedManagedAllocator() {
107
    // Specify destruct order.
Y
Yu Yang 已提交
108 109 110 111 112 113 114 115
    default_allocator_.reset();
    chunks_.clear();
    raw_allocator_.reset();
  }

  std::unique_ptr<Allocation> Allocate(size_t size, Attr attr) override {
    return default_allocator_->Allocate(size, attr);
  }
S
sneaxiy 已提交
116

Y
Yu Yang 已提交
117 118 119 120 121 122 123
  std::shared_ptr<Allocation> AllocateShared(size_t size, Attr attr) override {
    return default_allocator_->AllocateShared(size, attr);
  }

  std::shared_ptr<ManagedAllocator> BestFitAllocatorCreator() {
    chunks_.emplace_back(raw_allocator_->Allocate(max_chunk_size_));
    auto* allocation = chunks_.back().get();
S
sneaxiy 已提交
124 125 126
    std::unique_ptr<Allocator> unmanaged_allocator(new LockedAllocator(
        std::unique_ptr<Allocator>(new BestFitAllocator(allocation))));

S
sneaxiy 已提交
127
    if (retry_time_ <= 0) {
S
sneaxiy 已提交
128 129 130 131
      VLOG(10) << "Create NaiveManagedAllocator without retry";
      return std::make_shared<AlignedAllocator<64u>>(
          NaiveManagedAllocator::Create(std::move(unmanaged_allocator)));
    } else {
S
sneaxiy 已提交
132 133
      VLOG(10) << "Create RetryAllocator with retry_time " << retry_time_
               << "ms";
S
sneaxiy 已提交
134
      return std::make_shared<AlignedAllocator<64u>>(RetryAllocator::Create(
S
sneaxiy 已提交
135
          std::move(unmanaged_allocator), static_cast<size_t>(retry_time_)));
S
sneaxiy 已提交
136
    }
137
  }
S
sneaxiy 已提交
138

Y
Yu Yang 已提交
139 140
  bool IsAllocThreadSafe() const override { return true; }

S
sneaxiy 已提交
141
 protected:
Y
Yu Yang 已提交
142
  size_t max_chunk_size_;
S
sneaxiy 已提交
143
  int64_t retry_time_;
Y
Yu Yang 已提交
144 145 146 147
  std::vector<std::unique_ptr<Allocation>> chunks_;
  std::shared_ptr<ManagedAllocator> raw_allocator_;
  std::shared_ptr<ManagedAllocator> default_allocator_;
};
S
sneaxiy 已提交
148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191

#ifdef PADDLE_WITH_CUDA

class CUDAManagedAllocator : public ChunkedManagedAllocator {
 public:
  explicit CUDAManagedAllocator(int dev_id)
      : ChunkedManagedAllocator(
            std::unique_ptr<Allocator>(
                new CUDAAllocator(platform::CUDAPlace(dev_id))),
            GetMaxChunkSize(dev_id), GetCapcity(dev_id), GetRetryTime()) {}

 private:
  static size_t GetMaxChunkSize(int dev_id) {
    platform::CUDADeviceGuard guard(dev_id);
    return platform::GpuMaxChunkSize();
  }

  static size_t GetCapcity(int dev_id) {
    platform::CUDADeviceGuard guard(dev_id);
    size_t available, total;
    platform::GpuMemoryUsage(&available, &total);
    size_t max_chunk_size = platform::GpuMaxChunkSize();
    return max_chunk_size == 0 ? 0 : available / max_chunk_size;
  }

  static int64_t GetRetryTime() { return FLAGS_gpu_allocator_retry_time; }
};

class CUDAPinnedManagedAllocator : public ChunkedManagedAllocator {
 public:
  CUDAPinnedManagedAllocator()
      : ChunkedManagedAllocator(
            std::unique_ptr<Allocator>(new CPUPinnedAllocator()),
            platform::CUDAPinnedMaxChunkSize(), GetCapacity(), -1) {
  }  // never retry

 private:
  static size_t GetCapacity() {
    size_t total = platform::CpuTotalPhysicalMemory();
    size_t max_chunk_size = platform::CUDAPinnedMaxChunkSize();
    return max_chunk_size == 0 ? 0 : total / max_chunk_size;
  }
};

Y
Refine  
Yu Yang 已提交
192
#endif
Y
Yu Yang 已提交
193 194 195

class AllocatorFacadePrivate {
 public:
Y
Yu Yang 已提交
196
  std::map<platform::Place, std::shared_ptr<ManagedAllocator>> allocators_;
Y
Yu Yang 已提交
197

Y
Refine  
Yu Yang 已提交
198
  ~AllocatorFacadePrivate() = default;
199 200 201 202

  AllocatorFacadePrivate() {
    InitCPUAllocator();
    InitCUDAAllocator();
S
sneaxiy 已提交
203
    InitCUDAPinnedAllocator();
Y
Yu Yang 已提交
204
    WrapZeroSizeAllocator();
205 206 207 208
  }

 private:
  void InitCPUAllocator() {
Y
Yu Yang 已提交
209
    allocators_[platform::CPUPlace()] = std::make_shared<CPUManagedAllocator>();
210 211 212 213
  }

  void InitCUDAAllocator() {
#ifdef PADDLE_WITH_CUDA
S
sneaxiy 已提交
214 215
    int device_count = platform::GetCUDADeviceCount();
    for (int dev_id = 0; dev_id < device_count; ++dev_id) {
216
      allocators_[platform::CUDAPlace(dev_id)] =
Y
Yu Yang 已提交
217
          std::make_shared<CUDAManagedAllocator>(dev_id);
218 219 220
    }
#endif
  }
Y
Yu Yang 已提交
221

S
sneaxiy 已提交
222 223 224 225 226 227 228
  void InitCUDAPinnedAllocator() {
#ifdef PADDLE_WITH_CUDA
    allocators_[platform::CUDAPinnedPlace()] =
        std::make_shared<CUDAPinnedManagedAllocator>();
#endif
  }

Y
Yu Yang 已提交
229 230 231 232 233 234
  void WrapZeroSizeAllocator() {
    for (auto& pair : allocators_) {
      pair.second =
          std::make_shared<ZeroSizeAllocator>(pair.second, pair.first);
    }
  }
235 236
};

Y
Refine  
Yu Yang 已提交
237
// Pimpl. Make interface clean.
238 239 240 241 242 243 244 245 246 247
AllocatorFacade::AllocatorFacade() : m_(new AllocatorFacadePrivate()) {}
AllocatorFacade::~AllocatorFacade() { delete m_; }

AllocatorFacade& AllocatorFacade::Instance() {
  static AllocatorFacade instance;
  return instance;
}

std::shared_ptr<Allocation> AllocatorFacade::AllocShared(
    const platform::Place& place, size_t size, Allocator::Attr attr) {
S
sneaxiy 已提交
248
  return m_->allocators_.at(place)->AllocateShared(size, attr);
249 250 251 252 253
}

std::unique_ptr<Allocation> AllocatorFacade::Alloc(const platform::Place& place,
                                                   size_t size,
                                                   Allocator::Attr attr) {
S
sneaxiy 已提交
254
  return m_->allocators_.at(place)->Allocate(size, attr);
255 256 257 258 259
}

}  // namespace allocation
}  // namespace memory
}  // namespace paddle