allocator_facade.cc 9.6 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"

17
#include "gflags/gflags.h"
18
#include "paddle/fluid/memory/allocation/allocator.h"
Y
Yu Yang 已提交
19
#include "paddle/fluid/memory/allocation/allocator_strategy.h"
20
#include "paddle/fluid/memory/allocation/auto_growth_best_fit_allocator.h"
21
#include "paddle/fluid/memory/allocation/cpu_allocator.h"
22
#include "paddle/fluid/memory/allocation/naive_best_fit_allocator.h"
S
sneaxiy 已提交
23
#include "paddle/fluid/memory/allocation/retry_allocator.h"
S
sneaxiy 已提交
24
#include "paddle/fluid/platform/enforce.h"
25
#include "paddle/fluid/platform/place.h"
26
#if defined(PADDLE_WITH_CUDA) || defined(PADDLE_WITH_HIP)
27
#include "paddle/fluid/memory/allocation/cuda_allocator.h"
S
sneaxiy 已提交
28
#include "paddle/fluid/memory/allocation/pinned_allocator.h"
29
#include "paddle/fluid/memory/allocation/thread_local_allocator.h"
S
sneaxiy 已提交
30
#include "paddle/fluid/platform/gpu_info.h"
31
#endif
32 33 34
#ifdef PADDLE_WITH_XPU
#include "paddle/fluid/platform/xpu_info.h"
#endif
35

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

41 42 43 44
DEFINE_bool(use_system_allocator, false,
            "Whether to use system allocator to allocate CPU and GPU memory. "
            "Only used for unittests.");

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

Y
Yu Yang 已提交
49 50
class AllocatorFacadePrivate {
 public:
51 52
  using AllocatorMap = std::map<platform::Place, std::shared_ptr<Allocator>>;

53
  AllocatorFacadePrivate() {
Z
Zeng Jinle 已提交
54 55
    auto strategy = GetAllocatorStrategy();
    switch (strategy) {
56 57
      case AllocatorStrategy::kNaiveBestFit: {
        InitNaiveBestFitCPUAllocator();
58 59 60 61 62
#ifdef PADDLE_WITH_XPU
        for (int dev_id = 0; dev_id < platform::GetXPUDeviceCount(); ++dev_id) {
          InitNaiveBestFitXPUAllocator(platform::XPUPlace(dev_id));
        }
#endif
63
#if defined(PADDLE_WITH_CUDA) || defined(PADDLE_WITH_HIP)
64 65 66 67 68 69
        for (int dev_id = 0; dev_id < platform::GetCUDADeviceCount();
             ++dev_id) {
          InitNaiveBestFitCUDAAllocator(platform::CUDAPlace(dev_id));
        }
        InitNaiveBestFitCUDAPinnedAllocator();
#endif
Z
Zeng Jinle 已提交
70 71
        break;
      }
72 73 74

      case AllocatorStrategy::kAutoGrowth: {
        InitNaiveBestFitCPUAllocator();
75 76 77 78 79
#ifdef PADDLE_WITH_XPU
        for (int dev_id = 0; dev_id < platform::GetXPUDeviceCount(); ++dev_id) {
          InitNaiveBestFitXPUAllocator(platform::XPUPlace(dev_id));
        }
#endif
80
#if defined(PADDLE_WITH_CUDA) || defined(PADDLE_WITH_HIP)
81 82 83 84 85 86
        for (int dev_id = 0; dev_id < platform::GetCUDADeviceCount();
             ++dev_id) {
          InitAutoGrowthCUDAAllocator(platform::CUDAPlace(dev_id));
        }
        InitNaiveBestFitCUDAPinnedAllocator();
#endif
Z
Zeng Jinle 已提交
87 88
        break;
      }
89

90 91
      case AllocatorStrategy::kThreadLocal: {
        InitNaiveBestFitCPUAllocator();
92 93 94 95 96
#ifdef PADDLE_WITH_XPU
        for (int dev_id = 0; dev_id < platform::GetXPUDeviceCount(); ++dev_id) {
          InitNaiveBestFitXPUAllocator(platform::XPUPlace(dev_id));
        }
#endif
97
#if defined(PADDLE_WITH_CUDA) || defined(PADDLE_WITH_HIP)
98 99 100 101 102 103 104 105 106
        for (int dev_id = 0; dev_id < platform::GetCUDADeviceCount();
             ++dev_id) {
          InitThreadLocalCUDAAllocator(platform::CUDAPlace(dev_id));
        }
        InitNaiveBestFitCUDAPinnedAllocator();
#endif
        break;
      }

Z
Zeng Jinle 已提交
107
      default: {
108 109
        PADDLE_THROW(platform::errors::InvalidArgument(
            "Unsupported allocator strategy: %d", static_cast<int>(strategy)));
Z
Zeng Jinle 已提交
110
      }
Y
Yu Yang 已提交
111
    }
Z
Zeng Jinle 已提交
112
    InitZeroSizeAllocators();
113
    InitSystemAllocators();
114 115 116 117 118 119

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

    CheckAllocThreadSafe();
Z
Zeng Jinle 已提交
120 121 122 123
  }

  inline const std::shared_ptr<Allocator>& GetAllocator(
      const platform::Place& place, size_t size) {
124 125 126 127
    const auto& allocators =
        (size > 0 ? (UNLIKELY(FLAGS_use_system_allocator) ? system_allocators_
                                                          : allocators_)
                  : zero_size_allocators_);
Z
Zeng Jinle 已提交
128
    auto iter = allocators.find(place);
129 130 131
    PADDLE_ENFORCE_NE(iter, allocators.end(),
                      platform::errors::NotFound(
                          "No allocator found for the place, %s", place));
Z
Zeng Jinle 已提交
132
    return iter->second;
133 134 135
  }

 private:
136 137
  void InitSystemAllocators() {
    system_allocators_[platform::CPUPlace()] = std::make_shared<CPUAllocator>();
138 139 140 141 142 143 144
#ifdef PADDLE_WITH_XPU
    int device_count = platform::GetXPUDeviceCount();
    for (int i = 0; i < device_count; ++i) {
      platform::XPUPlace p(i);
      system_allocators_[p] = std::make_shared<NaiveBestFitAllocator>(p);
    }
#endif
145
#if defined(PADDLE_WITH_CUDA) || defined(PADDLE_WITH_HIP)
146 147 148 149 150 151 152 153 154 155
    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
  }

156 157 158
  void InitNaiveBestFitCPUAllocator() {
    allocators_[platform::CPUPlace()] =
        std::make_shared<NaiveBestFitAllocator>(platform::CPUPlace());
Y
Yu Yang 已提交
159 160
  }

161
#if defined(PADDLE_WITH_CUDA) || defined(PADDLE_WITH_HIP)
162 163 164
  void InitNaiveBestFitCUDAPinnedAllocator() {
    allocators_[platform::CUDAPinnedPlace()] =
        std::make_shared<NaiveBestFitAllocator>(platform::CUDAPinnedPlace());
165 166
  }

167 168
  void InitNaiveBestFitCUDAAllocator(platform::CUDAPlace p) {
    allocators_[p] = std::make_shared<NaiveBestFitAllocator>(p);
169
  }
Y
Yu Yang 已提交
170

171 172 173 174
  void InitThreadLocalCUDAAllocator(platform::CUDAPlace p) {
    allocators_[p] = std::make_shared<ThreadLocalCUDAAllocator>(p);
  }

175 176 177 178
  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 已提交
179
  }
180
#endif
S
sneaxiy 已提交
181

182 183 184 185 186 187
#ifdef PADDLE_WITH_XPU
  void InitNaiveBestFitXPUAllocator(platform::XPUPlace p) {
    allocators_[p] = std::make_shared<NaiveBestFitAllocator>(p);
  }
#endif

Z
Zeng Jinle 已提交
188 189 190 191
  class ZeroSizeAllocator : public Allocator {
   public:
    explicit ZeroSizeAllocator(platform::Place place) : place_(place) {}

192 193
    bool IsAllocThreadSafe() const override { return true; }

Z
Zeng Jinle 已提交
194
   protected:
195
    Allocation* AllocateImpl(size_t size) override {
Z
Zeng Jinle 已提交
196 197 198 199 200 201 202 203 204 205 206 207
      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());
208
#if defined(PADDLE_WITH_CUDA) || defined(PADDLE_WITH_HIP)
Z
Zeng Jinle 已提交
209 210 211 212 213 214
    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
215 216 217 218 219 220
#ifdef PADDLE_WITH_XPU
    int device_count = platform::GetXPUDeviceCount();
    for (int dev_id = 0; dev_id < device_count; ++dev_id) {
      places.emplace_back(platform::XPUPlace(dev_id));
    }
#endif
Z
Zeng Jinle 已提交
221 222 223

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

227 228 229 230 231
  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"));
232
    }
233
  }
234

235 236 237 238
  void CheckAllocThreadSafe() const {
    CheckAllocThreadSafe(allocators_);
    CheckAllocThreadSafe(zero_size_allocators_);
    CheckAllocThreadSafe(system_allocators_);
239 240 241
  }

  void WrapCUDARetryAllocator(size_t retry_time) {
242 243 244 245
    PADDLE_ENFORCE_GT(
        retry_time, 0,
        platform::errors::InvalidArgument(
            "Retry time should be larger than 0, but got %d", retry_time));
246 247 248 249 250 251 252
    for (auto& pair : allocators_) {
      if (platform::is_gpu_place(pair.first)) {
        pair.second = std::make_shared<RetryAllocator>(pair.second, retry_time);
      }
    }
  }

Z
Zeng Jinle 已提交
253
 private:
254 255 256
  AllocatorMap allocators_;
  AllocatorMap zero_size_allocators_;
  AllocatorMap system_allocators_;
257 258
};

Y
Refine  
Yu Yang 已提交
259
// Pimpl. Make interface clean.
260
AllocatorFacade::AllocatorFacade() : m_(new AllocatorFacadePrivate()) {}
261 262 263
// delete m_ may cause core dump when the destructor of python in conflict with
// cpp.
AllocatorFacade::~AllocatorFacade() {}
264 265 266 267 268 269 270

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

std::shared_ptr<Allocation> AllocatorFacade::AllocShared(
271 272
    const platform::Place& place, size_t size) {
  return std::shared_ptr<Allocation>(Alloc(place, size));
273 274
}

275 276 277
AllocationPtr AllocatorFacade::Alloc(const platform::Place& place,
                                     size_t size) {
  return m_->GetAllocator(place, size)->Allocate(size);
278 279
}

W
Wilber 已提交
280 281
uint64_t AllocatorFacade::Release(const platform::Place& place) {
  return m_->GetAllocator(place, /* A non-zero num to choose allocator_ */ 1)
282 283 284
      ->Release(place);
}

285 286 287
}  // namespace allocation
}  // namespace memory
}  // namespace paddle