allocator.h 6.3 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17
// 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.

#pragma once
#include <memory>
#include <string>
Z
Zeng Jinle 已提交
18
#include <type_traits>
S
sneaxiy 已提交
19
#include <utility>
S
sneaxiy 已提交
20
#include <vector>
W
wanghuancoder 已提交
21

Z
Zeng Jinle 已提交
22
#include "paddle/fluid/framework/inlined_vector.h"
23
#include "paddle/fluid/platform/enforce.h"
24
#include "paddle/fluid/platform/place.h"
25
#include "paddle/phi/core/allocator.h"
26

F
From00 已提交
27 28
DECLARE_string(allocator_strategy);

29 30 31 32
namespace paddle {
namespace memory {
namespace allocation {

Y
Yu Yang 已提交
33
// Exception when `Alloc`/`AllocShared` failed
34 35 36 37
struct BadAlloc : public std::exception {
  inline explicit BadAlloc(std::string err_msg, const char* file, int line)
      : err_str_(platform::GetTraceBackString(std::move(err_msg), file, line)) {
  }
Z
Zeng Jinle 已提交
38

39
  const char* what() const noexcept override { return err_str_.c_str(); }
40

41
  std::string err_str_;
42 43
};

Y
Yu Yang 已提交
44
class Allocator;
Z
Zeng Jinle 已提交
45

Y
Yu Yang 已提交
46 47 48 49 50 51
// Allocation is the object holding the actually pointer. Use
// `Allocation::ptr()` will returns the pointer that allocated.
//
// NOTE: this is the base class of Allocation. Each allocator can use its own
//       allocation object.
// NOTE: the `Allocation::ptr()` could be nullptr, if the allocation size is 0
Z
Zeng Jinle 已提交
52 53 54 55 56 57 58 59

/**
 * Allocation is returned by Allocator::Allocate() method.
 *
 * An allocator may be decorated by another allocator. For example, we can
 * decorate a RetryAllocator to any allocator to perform allocation retry when
 * first allocation request fails.
 *
Z
Zeng Jinle 已提交
60
 * Explanations of Allocator design are as follows:
Z
Zeng Jinle 已提交
61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83
 *
 * Suppose we have an allocator which is decorated by several allocators:
 *
 *   A(1) <- A(2) <- A(3) <- ... <- A(n)
 *
 * , and the public allocator is A(1).
 *
 * The allocation process would be:
 *
 *   A(n).Allocate() -> ... -> A(2).Allocate() -> A(1).Allocate()
 *
 * , and the free process would be:
 *
 *   A(1).Free() -> A(2).Free() -> ... -> A(n).Free()
 *
 * Therefore, we should record the allocator chain when allocating, so
 * that we can free the allocation in the reverse order of allocator chain.
 * The field `decorated_allocators_` is used to record this chain.
 *
 * Another example is that we want to add additional fields in Allocation,
 * e.g., something what is done in AlignedAllocator, etc.
 * In this case, we should declare a derived class of Allocation, which
 * contains an underlying Allocation allocated by the underlying allocator.
84 85
 * Therefore, `decorated_allocators_` of the new Allocation object
 * would
Z
Zeng Jinle 已提交
86 87
 * be a new chain, differing from the underlying Allocation object.
 */
88
class Allocation : public phi::Allocation {
89
 public:
90
  Allocation(void* ptr, size_t size, platform::Place place)
91
      : phi::Allocation(ptr, size, place), base_ptr_(ptr) {}
92 93
  Allocation(void* ptr, void* base_ptr, size_t size,
             const platform::Place& place)
94
      : phi::Allocation(ptr, size, place), base_ptr_(base_ptr) {}
95

96
  void* base_ptr() const { return base_ptr_; }
F
From00 已提交
97

Z
Zeng Jinle 已提交
98 99 100 101
 private:
  inline void RegisterDecoratedAllocator(Allocator* allocator) {
    decorated_allocators_.emplace_back(allocator);
  }
S
sneaxiy 已提交
102

Z
Zeng Jinle 已提交
103
  inline void PopDecoratedAllocator() { decorated_allocators_.pop_back(); }
S
sneaxiy 已提交
104

Z
Zeng Jinle 已提交
105 106 107
  inline Allocator* TopDecoratedAllocator() {
    return decorated_allocators_.back();
  }
Y
Yu Yang 已提交
108

109
 private:
F
From00 已提交
110
  void* base_ptr_;  // the point that directly requested from system
111

Z
Zeng Jinle 已提交
112 113 114 115 116 117 118 119 120
  /**
   * NOTE(zjl): Since decorated_allocators_ is usually a small vector.
   * We reserve a small buffer to it to prevent frequent heap allocation
   *
   * Instead, we can use a std::vector<Allocator *> here, and reserve
   * kReserveAllocatorNum in constructor of Allocation.
   * But using std::vector<Allocator *> would make ocr recognition model
   * fail in CE. The train duration is 8% slower than KPI.
   */
Z
Zeng Jinle 已提交
121 122 123 124 125 126 127 128
  static constexpr size_t kReserveAllocatorNum = 8;
  using DecoratedAllocatorStack =
      framework::InlinedVector<Allocator*, kReserveAllocatorNum>;

  DecoratedAllocatorStack decorated_allocators_;

  friend class Allocator;
};
Y
Yu Yang 已提交
129

130
using AllocationPtr = phi::Allocator::AllocationPtr;
131
using DecoratedAllocationPtr =
132
    std::unique_ptr<Allocation, phi::Allocator::DeleterType>;
133

Y
Yu Yang 已提交
134
// Base interface class of memory Allocator.
135
class Allocator : public phi::Allocator {
136
 public:
137
  static void AllocationDeleter(phi::Allocation* allocation) {
138 139 140 141
    Allocator* allocator =
        static_cast<Allocation*>(allocation)->TopDecoratedAllocator();
    allocator->Free(allocation);
  }
Y
Yu Yang 已提交
142

Y
Yu Yang 已提交
143
  // Allocate an allocation.
144 145 146
  // size may be 0, but it would be too complex if we handle size == 0
  // in each Allocator. So we handle size == 0 inside AllocatorFacade
  // in our design.
147
  AllocationPtr Allocate(size_t size) override {
148
    auto ptr = AllocateImpl(size);
149 150
    static_cast<Allocation*>(ptr)->RegisterDecoratedAllocator(this);
    return AllocationPtr(ptr, AllocationDeleter);
Z
Zeng Jinle 已提交
151 152
  }

153
  void Free(phi::Allocation* allocation) {
154
    static_cast<Allocation*>(allocation)->PopDecoratedAllocator();
Z
Zeng Jinle 已提交
155 156
    FreeImpl(allocation);
  }
157

158
  uint64_t Release(const platform::Place& place) { return ReleaseImpl(place); }
Y
Yu Yang 已提交
159 160

 protected:
161 162
  virtual phi::Allocation* AllocateImpl(size_t size) = 0;
  virtual void FreeImpl(phi::Allocation* allocation);
W
Wilber 已提交
163
  virtual uint64_t ReleaseImpl(const platform::Place& place) { return 0; }
164 165
};

166 167 168 169 170 171 172 173 174 175 176
inline size_t AlignedSize(size_t size, size_t alignment) {
  auto remaining = size % alignment;
  return remaining == 0 ? size : size + alignment - remaining;
}

inline size_t AlignedPtrOffset(const void* ptr, size_t alignment) {
  auto ptr_addr = reinterpret_cast<uintptr_t>(ptr);
  auto diff = ptr_addr % alignment;
  return diff == 0 ? 0 : alignment - diff;
}

177 178 179 180 181 182 183 184
template <typename Derived, typename Base, typename BaseDel>
decltype(auto) static_unique_ptr_cast(std::unique_ptr<Base, BaseDel>&& p) {
  static_assert(std::is_base_of<Base, Derived>::value,
                "Derived type must derive from Base.");
  auto d = static_cast<Derived*>(p.release());
  return std::unique_ptr<Derived, BaseDel>(d, p.get_deleter());
}

185 186 187
}  // namespace allocation
}  // namespace memory
}  // namespace paddle