allocator_facade.cc 8.2 KB
Newer Older
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/memory/allocation/allocator_facade.h"

S
sneaxiy 已提交
17
#include <gflags/gflags.h>
18

19
#include <map>
Y
Yu Yang 已提交
20
#include <string>
S
sneaxiy 已提交
21
#include <unordered_map>
S
sneaxiy 已提交
22
#include <utility>
23
#include <vector>
24 25

#include "paddle/fluid/memory/allocation/allocator.h"
Y
Yu Yang 已提交
26
#include "paddle/fluid/memory/allocation/allocator_strategy.h"
27
#include "paddle/fluid/memory/allocation/auto_growth_best_fit_allocator.h"
28 29
#include "paddle/fluid/memory/allocation/cpu_allocator.h"
#include "paddle/fluid/memory/allocation/locked_allocator.h"
30
#include "paddle/fluid/memory/allocation/naive_best_fit_allocator.h"
S
sneaxiy 已提交
31
#include "paddle/fluid/memory/allocation/retry_allocator.h"
S
sneaxiy 已提交
32
#include "paddle/fluid/platform/cpu_info.h"
S
sneaxiy 已提交
33
#include "paddle/fluid/platform/enforce.h"
34 35 36
#include "paddle/fluid/platform/place.h"
#ifdef PADDLE_WITH_CUDA
#include "paddle/fluid/memory/allocation/cuda_allocator.h"
S
sneaxiy 已提交
37
#include "paddle/fluid/memory/allocation/pinned_allocator.h"
38
#include "paddle/fluid/memory/allocation/thread_local_allocator.h"
S
sneaxiy 已提交
39 40
#include "paddle/fluid/platform/cuda_device_guard.h"
#include "paddle/fluid/platform/gpu_info.h"
41 42
#endif

S
sneaxiy 已提交
43
DEFINE_int64(
44
    gpu_allocator_retry_time, 10000,
S
sneaxiy 已提交
45 46 47
    "The retry time (milliseconds) when allocator fails "
    "to allocate memory. No retry if this value is not greater than 0");

48 49 50 51
DEFINE_bool(use_system_allocator, false,
            "Whether to use system allocator to allocate CPU and GPU memory. "
            "Only used for unittests.");

52 53 54 55
namespace paddle {
namespace memory {
namespace allocation {

Y
Yu Yang 已提交
56 57
class AllocatorFacadePrivate {
 public:
58 59
  using AllocatorMap = std::map<platform::Place, std::shared_ptr<Allocator>>;

60
  AllocatorFacadePrivate() {
Z
Zeng Jinle 已提交
61 62
    auto strategy = GetAllocatorStrategy();
    switch (strategy) {
63 64 65 66 67 68 69 70 71
      case AllocatorStrategy::kNaiveBestFit: {
        InitNaiveBestFitCPUAllocator();
#ifdef PADDLE_WITH_CUDA
        for (int dev_id = 0; dev_id < platform::GetCUDADeviceCount();
             ++dev_id) {
          InitNaiveBestFitCUDAAllocator(platform::CUDAPlace(dev_id));
        }
        InitNaiveBestFitCUDAPinnedAllocator();
#endif
Z
Zeng Jinle 已提交
72 73
        break;
      }
74 75 76 77 78 79 80 81 82 83

      case AllocatorStrategy::kAutoGrowth: {
        InitNaiveBestFitCPUAllocator();
#ifdef PADDLE_WITH_CUDA
        for (int dev_id = 0; dev_id < platform::GetCUDADeviceCount();
             ++dev_id) {
          InitAutoGrowthCUDAAllocator(platform::CUDAPlace(dev_id));
        }
        InitNaiveBestFitCUDAPinnedAllocator();
#endif
Z
Zeng Jinle 已提交
84 85
        break;
      }
86

87 88 89 90 91 92 93 94 95 96 97 98
      case AllocatorStrategy::kThreadLocal: {
        InitNaiveBestFitCPUAllocator();
#ifdef PADDLE_WITH_CUDA
        for (int dev_id = 0; dev_id < platform::GetCUDADeviceCount();
             ++dev_id) {
          InitThreadLocalCUDAAllocator(platform::CUDAPlace(dev_id));
        }
        InitNaiveBestFitCUDAPinnedAllocator();
#endif
        break;
      }

Z
Zeng Jinle 已提交
99
      default: {
100 101
        PADDLE_THROW(platform::errors::InvalidArgument(
            "Unsupported allocator strategy: %d", static_cast<int>(strategy)));
Z
Zeng Jinle 已提交
102
      }
Y
Yu Yang 已提交
103
    }
Z
Zeng Jinle 已提交
104
    InitZeroSizeAllocators();
105
    InitSystemAllocators();
106 107 108 109 110 111

    if (FLAGS_gpu_allocator_retry_time > 0) {
      WrapCUDARetryAllocator(FLAGS_gpu_allocator_retry_time);
    }

    CheckAllocThreadSafe();
Z
Zeng Jinle 已提交
112 113 114 115
  }

  inline const std::shared_ptr<Allocator>& GetAllocator(
      const platform::Place& place, size_t size) {
116 117 118 119
    const auto& allocators =
        (size > 0 ? (UNLIKELY(FLAGS_use_system_allocator) ? system_allocators_
                                                          : allocators_)
                  : zero_size_allocators_);
Z
Zeng Jinle 已提交
120
    auto iter = allocators.find(place);
121 122 123
    PADDLE_ENFORCE_NE(iter, allocators.end(),
                      platform::errors::NotFound(
                          "No allocator found for the place, %s", place));
Z
Zeng Jinle 已提交
124
    return iter->second;
125 126 127
  }

 private:
128 129 130 131 132 133 134 135 136 137 138 139 140
  void InitSystemAllocators() {
    system_allocators_[platform::CPUPlace()] = std::make_shared<CPUAllocator>();
#ifdef PADDLE_WITH_CUDA
    system_allocators_[platform::CUDAPinnedPlace()] =
        std::make_shared<CPUPinnedAllocator>();
    int device_count = platform::GetCUDADeviceCount();
    for (int i = 0; i < device_count; ++i) {
      platform::CUDAPlace p(i);
      system_allocators_[p] = std::make_shared<CUDAAllocator>(p);
    }
#endif
  }

141 142 143
  void InitNaiveBestFitCPUAllocator() {
    allocators_[platform::CPUPlace()] =
        std::make_shared<NaiveBestFitAllocator>(platform::CPUPlace());
Y
Yu Yang 已提交
144 145
  }

146 147 148 149
#ifdef PADDLE_WITH_CUDA
  void InitNaiveBestFitCUDAPinnedAllocator() {
    allocators_[platform::CUDAPinnedPlace()] =
        std::make_shared<NaiveBestFitAllocator>(platform::CUDAPinnedPlace());
150 151
  }

152 153
  void InitNaiveBestFitCUDAAllocator(platform::CUDAPlace p) {
    allocators_[p] = std::make_shared<NaiveBestFitAllocator>(p);
154
  }
Y
Yu Yang 已提交
155

156 157 158 159
  void InitThreadLocalCUDAAllocator(platform::CUDAPlace p) {
    allocators_[p] = std::make_shared<ThreadLocalCUDAAllocator>(p);
  }

160 161 162 163
  void InitAutoGrowthCUDAAllocator(platform::CUDAPlace p) {
    auto cuda_allocator = std::make_shared<CUDAAllocator>(p);
    allocators_[p] = std::make_shared<AutoGrowthBestFitAllocator>(
        cuda_allocator, platform::GpuMinChunkSize());
S
sneaxiy 已提交
164
  }
165
#endif
S
sneaxiy 已提交
166

Z
Zeng Jinle 已提交
167 168 169 170
  class ZeroSizeAllocator : public Allocator {
   public:
    explicit ZeroSizeAllocator(platform::Place place) : place_(place) {}

171 172
    bool IsAllocThreadSafe() const override { return true; }

Z
Zeng Jinle 已提交
173
   protected:
174
    Allocation* AllocateImpl(size_t size) override {
Z
Zeng Jinle 已提交
175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196
      return new Allocation(nullptr, 0, place_);
    }

    void FreeImpl(Allocation* allocation) override { delete allocation; }

   private:
    platform::Place place_;
  };

  void InitZeroSizeAllocators() {
    std::vector<platform::Place> places;
    places.emplace_back(platform::CPUPlace());
#ifdef PADDLE_WITH_CUDA
    int device_count = platform::GetCUDADeviceCount();
    for (int dev_id = 0; dev_id < device_count; ++dev_id) {
      places.emplace_back(platform::CUDAPlace(dev_id));
    }
    places.emplace_back(platform::CUDAPinnedPlace());
#endif

    for (auto& p : places) {
      zero_size_allocators_[p] = std::make_shared<ZeroSizeAllocator>(p);
Y
Yu Yang 已提交
197 198
    }
  }
Z
Zeng Jinle 已提交
199

200 201 202 203 204
  static void CheckAllocThreadSafe(const AllocatorMap& allocators) {
    for (auto& pair : allocators) {
      PADDLE_ENFORCE_EQ(pair.second->IsAllocThreadSafe(), true,
                        platform::errors::InvalidArgument(
                            "Public allocators must be thread safe"));
205
    }
206
  }
207

208 209 210 211
  void CheckAllocThreadSafe() const {
    CheckAllocThreadSafe(allocators_);
    CheckAllocThreadSafe(zero_size_allocators_);
    CheckAllocThreadSafe(system_allocators_);
212 213 214
  }

  void WrapCUDARetryAllocator(size_t retry_time) {
215 216 217 218
    PADDLE_ENFORCE_GT(
        retry_time, 0,
        platform::errors::InvalidArgument(
            "Retry time should be larger than 0, but got %d", retry_time));
219 220 221 222 223 224 225
    for (auto& pair : allocators_) {
      if (platform::is_gpu_place(pair.first)) {
        pair.second = std::make_shared<RetryAllocator>(pair.second, retry_time);
      }
    }
  }

Z
Zeng Jinle 已提交
226
 private:
227 228 229
  AllocatorMap allocators_;
  AllocatorMap zero_size_allocators_;
  AllocatorMap system_allocators_;
230 231
};

Y
Refine  
Yu Yang 已提交
232
// Pimpl. Make interface clean.
233
AllocatorFacade::AllocatorFacade() : m_(new AllocatorFacadePrivate()) {}
234 235 236
// delete m_ may cause core dump when the destructor of python in conflict with
// cpp.
AllocatorFacade::~AllocatorFacade() {}
237 238 239 240 241 242 243

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

std::shared_ptr<Allocation> AllocatorFacade::AllocShared(
244 245
    const platform::Place& place, size_t size) {
  return std::shared_ptr<Allocation>(Alloc(place, size));
246 247
}

248 249 250
AllocationPtr AllocatorFacade::Alloc(const platform::Place& place,
                                     size_t size) {
  return m_->GetAllocator(place, size)->Allocate(size);
251 252 253 254 255
}

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