buddy_allocator.cc 10.3 KB
Newer Older
1
/* Copyright (c) 2016 PaddlePaddle Authors. All Rights Reserved.
2

L
Luo Tao 已提交
3 4 5
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
6

L
Luo Tao 已提交
7
    http://www.apache.org/licenses/LICENSE-2.0
8

L
Luo Tao 已提交
9 10 11 12 13
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. */
14

Y
Yi Wang 已提交
15
#include "paddle/fluid/memory/detail/buddy_allocator.h"
L
liaogang 已提交
16
#include "glog/logging.h"
17

18 19 20 21
DEFINE_bool(free_idle_memory, false,
            "If it is true, Paddle will try to free idle memory trunks during "
            "running time.");

22 23 24 25
namespace paddle {
namespace memory {
namespace detail {

G
gongweibao 已提交
26 27
BuddyAllocator::BuddyAllocator(
    std::unique_ptr<SystemAllocator> system_allocator, size_t min_chunk_size,
S
sneaxiy 已提交
28
    size_t first_allocate_chunk_size, size_t reallocate_chunk_size)
29
    : min_chunk_size_(min_chunk_size),
S
sneaxiy 已提交
30 31 32
      first_allocate_chunk_size_(first_allocate_chunk_size),
      reallocate_chunk_size_(reallocate_chunk_size),
      max_chunk_size_(first_allocate_chunk_size),
33
      cache_(system_allocator->UseGpu()),
L
liaogang 已提交
34 35 36
      system_allocator_(std::move(system_allocator)) {}

BuddyAllocator::~BuddyAllocator() {
M
minqiyang 已提交
37 38
  VLOG(10) << "BuddyAllocator Disconstructor makes sure that all of these "
              "have actually been freed";
L
liaogang 已提交
39 40
  while (!pool_.empty()) {
    auto block = static_cast<MemoryBlock*>(std::get<2>(*pool_.begin()));
S
sneaxiy 已提交
41 42
    auto desc = cache_.load(block);
    VLOG(10) << "Free from block (" << block << ", " << desc.size << ")";
L
liaogang 已提交
43

S
sneaxiy 已提交
44
    system_allocator_->Free(block, desc.size, desc.index);
L
liaogang 已提交
45 46 47
    cache_.invalidate(block);
    pool_.erase(pool_.begin());
  }
L
liaogang 已提交
48 49 50 51 52 53 54 55 56
}

inline size_t align(size_t size, size_t alignment) {
  size_t remaining = size % alignment;
  return remaining == 0 ? size : size + (alignment - remaining);
}

void* BuddyAllocator::Alloc(size_t unaligned_size) {
  // adjust allocation alignment
Y
Update  
Yi Wang 已提交
57 58
  size_t size =
      align(unaligned_size + sizeof(MemoryBlock::Desc), min_chunk_size_);
L
liaogang 已提交
59 60 61 62

  // acquire the allocator lock
  std::lock_guard<std::mutex> lock(mutex_);

M
minqiyang 已提交
63 64
  VLOG(10) << "Allocate " << unaligned_size << " bytes from chunk size "
           << size;
L
liaogang 已提交
65 66 67

  // if the allocation is huge, send directly to the system allocator
  if (size > max_chunk_size_) {
M
minqiyang 已提交
68
    VLOG(10) << "Allocate from system allocator.";
S
sneaxiy 已提交
69
    return SystemAlloc(size, false);
L
liaogang 已提交
70 71 72 73 74 75 76 77
  }

  // query and allocate from the existing chunk
  auto it = FindExistChunk(size);

  // refill the pool if failure
  if (it == pool_.end()) {
    it = RefillPool();
S
sneaxiy 已提交
78
    // if still failure, try to allocate from SystemAllocator
L
liaogang 已提交
79
    if (it == pool_.end()) {
S
sneaxiy 已提交
80
      return SystemAlloc(size, false);
L
liaogang 已提交
81
    }
L
liaogang 已提交
82
  } else {
M
minqiyang 已提交
83 84 85
    VLOG(10) << "Allocation from existing memory block " << std::get<2>(*it)
             << " at address "
             << reinterpret_cast<MemoryBlock*>(std::get<2>(*it))->data();
L
liaogang 已提交
86 87 88 89 90 91 92 93 94
  }

  total_used_ += size;
  total_free_ -= size;

  // split the allocation and return data for use
  return reinterpret_cast<MemoryBlock*>(SplitToAlloc(it, size))->data();
}

L
liaogang 已提交
95
void BuddyAllocator::Free(void* p) {
L
liaogang 已提交
96
  // Point back to metadata
L
liaogang 已提交
97 98
  auto block = static_cast<MemoryBlock*>(p)->metadata();

L
liaogang 已提交
99
  // Acquire the allocator lock
L
liaogang 已提交
100
  std::lock_guard<std::mutex> lock(mutex_);
L
liaogang 已提交
101

M
minqiyang 已提交
102
  VLOG(10) << "Free from address " << block;
L
liaogang 已提交
103

S
sneaxiy 已提交
104
  if (block->type(cache_) == MemoryBlock::UNMANAGED_HUGE_CHUNK) {
M
minqiyang 已提交
105
    VLOG(10) << "Free directly from system allocator";
L
liaogang 已提交
106 107 108 109
    system_allocator_->Free(block, block->total_size(cache_),
                            block->index(cache_));

    // Invalidate GPU allocation from cache
110 111
    cache_.invalidate(block);

L
liaogang 已提交
112 113 114
    return;
  }

Y
Update  
Yi Wang 已提交
115
  block->mark_as_free(&cache_);
L
liaogang 已提交
116 117 118 119 120 121

  total_used_ -= block->total_size(cache_);
  total_free_ += block->total_size(cache_);

  // Trying to merge the right buddy
  if (block->has_right_buddy(cache_)) {
M
minqiyang 已提交
122 123
    VLOG(10) << "Merging this block " << block << " with its right buddy "
             << block->right_buddy(cache_);
124 125 126 127 128

    auto right_buddy = block->right_buddy(cache_);

    if (right_buddy->type(cache_) == MemoryBlock::FREE_CHUNK) {
      // Take away right buddy from pool
L
liaogang 已提交
129 130 131
      pool_.erase(IndexSizeAddress(right_buddy->index(cache_),
                                   right_buddy->total_size(cache_),
                                   right_buddy));
132 133

      // merge its right buddy to the block
Y
Update  
Yi Wang 已提交
134
      block->merge(&cache_, right_buddy);
135
    }
L
liaogang 已提交
136 137 138 139
  }

  // Trying to merge the left buddy
  if (block->has_left_buddy(cache_)) {
M
minqiyang 已提交
140 141
    VLOG(10) << "Merging this block " << block << " with its left buddy "
             << block->left_buddy(cache_);
142 143 144 145 146

    auto left_buddy = block->left_buddy(cache_);

    if (left_buddy->type(cache_) == MemoryBlock::FREE_CHUNK) {
      // Take away right buddy from pool
L
liaogang 已提交
147 148
      pool_.erase(IndexSizeAddress(left_buddy->index(cache_),
                                   left_buddy->total_size(cache_), left_buddy));
149 150

      // merge the block to its left buddy
Y
Update  
Yi Wang 已提交
151
      left_buddy->merge(&cache_, block);
152 153
      block = left_buddy;
    }
L
liaogang 已提交
154 155 156
  }

  // Dumping this block into pool
M
minqiyang 已提交
157 158
  VLOG(10) << "Inserting free block (" << block << ", "
           << block->total_size(cache_) << ")";
L
liaogang 已提交
159 160
  pool_.insert(
      IndexSizeAddress(block->index(cache_), block->total_size(cache_), block));
L
liaogang 已提交
161

162 163 164 165
  if (FLAGS_free_idle_memory) {
    // Clean up if existing too much free memory
    // Prefer freeing fallback allocation first
    CleanIdleFallBackAlloc();
L
liaogang 已提交
166

167 168 169
    // Free normal allocation
    CleanIdleNormalAlloc();
  }
L
liaogang 已提交
170 171
}

L
liaogang 已提交
172
size_t BuddyAllocator::Used() { return total_used_; }
D
Dun Liang 已提交
173
size_t BuddyAllocator::GetMinChunkSize() { return min_chunk_size_; }
S
sneaxiy 已提交
174 175 176 177
size_t BuddyAllocator::GetMaxChunkSize() {
  std::lock_guard<std::mutex> lock(mutex_);
  return max_chunk_size_;
}
L
liaogang 已提交
178

S
sneaxiy 已提交
179
void* BuddyAllocator::SystemAlloc(size_t size, bool is_managed) {
L
liaogang 已提交
180
  size_t index = 0;
Y
Update  
Yi Wang 已提交
181
  void* p = system_allocator_->Alloc(&index, size);
L
liaogang 已提交
182

M
minqiyang 已提交
183
  VLOG(10) << "Allocated " << p << " from system allocator.";
L
liaogang 已提交
184 185 186

  if (p == nullptr) return nullptr;

S
sneaxiy 已提交
187 188 189 190
  static_cast<MemoryBlock*>(p)->init(
      &cache_, is_managed ? MemoryBlock::MANAGED_HUGE_CHUNK
                          : MemoryBlock::UNMANAGED_HUGE_CHUNK,
      index, size, nullptr, nullptr);
L
liaogang 已提交
191 192 193 194 195

  return static_cast<MemoryBlock*>(p)->data();
}

BuddyAllocator::PoolSet::iterator BuddyAllocator::RefillPool() {
S
sneaxiy 已提交
196 197
  if (total_used_ + total_free_ > 0) {
    max_chunk_size_ = reallocate_chunk_size_;
L
liaogang 已提交
198 199 200 201
  }

  // Allocate a new maximum sized block
  size_t index = 0;
S
sneaxiy 已提交
202 203
  size_t chunk_size = max_chunk_size_;
  void* p = system_allocator_->Alloc(&index, chunk_size);
L
liaogang 已提交
204 205 206

  if (p == nullptr) return pool_.end();

M
minqiyang 已提交
207 208
  VLOG(10) << "Creating and inserting new block " << p
           << " from system allocator";
L
liaogang 已提交
209

Y
Yi Wang 已提交
210
  static_cast<MemoryBlock*>(p)->init(&cache_, MemoryBlock::FREE_CHUNK, index,
S
sneaxiy 已提交
211
                                     chunk_size, nullptr, nullptr);
L
liaogang 已提交
212

213 214 215 216 217 218
  // gpu fallback allocation
  if (system_allocator_->UseGpu() &&
      static_cast<MemoryBlock*>(p)->index(cache_) == 1) {
    fallback_alloc_count_++;
  }

S
sneaxiy 已提交
219
  total_free_ += chunk_size;
L
liaogang 已提交
220 221

  // dump the block into pool
S
sneaxiy 已提交
222
  return pool_.insert(IndexSizeAddress(index, chunk_size, p)).first;
L
liaogang 已提交
223 224 225 226 227 228
}

BuddyAllocator::PoolSet::iterator BuddyAllocator::FindExistChunk(size_t size) {
  size_t index = 0;

  while (1) {
L
liaogang 已提交
229
    auto it = pool_.lower_bound(IndexSizeAddress(index, size, nullptr));
230 231

    // no match chunk memory
L
liaogang 已提交
232 233 234
    if (it == pool_.end()) return it;

    if (std::get<0>(*it) > index) {
235
      // find suitable one
L
liaogang 已提交
236 237 238
      if (std::get<1>(*it) >= size) {
        return it;
      }
239
      // update and continue
L
liaogang 已提交
240 241 242 243 244 245 246 247 248 249 250 251
      index = std::get<0>(*it);
      continue;
    }
    return it;
  }
}

void* BuddyAllocator::SplitToAlloc(BuddyAllocator::PoolSet::iterator it,
                                   size_t size) {
  auto block = static_cast<MemoryBlock*>(std::get<2>(*it));
  pool_.erase(it);

M
minqiyang 已提交
252 253
  VLOG(10) << "Split block (" << block << ", " << block->total_size(cache_)
           << ") into";
Y
Update  
Yi Wang 已提交
254
  block->split(&cache_, size);
L
liaogang 已提交
255

M
minqiyang 已提交
256 257
  VLOG(10) << "Left block (" << block << ", " << block->total_size(cache_)
           << ")";
Y
Update  
Yi Wang 已提交
258
  block->set_type(&cache_, MemoryBlock::ARENA_CHUNK);
L
liaogang 已提交
259 260 261 262

  // the rest of memory if exist
  if (block->has_right_buddy(cache_)) {
    if (block->right_buddy(cache_)->type(cache_) == MemoryBlock::FREE_CHUNK) {
M
minqiyang 已提交
263 264
      VLOG(10) << "Insert right block (" << block->right_buddy(cache_) << ", "
               << block->right_buddy(cache_)->total_size(cache_) << ")";
L
liaogang 已提交
265

L
liaogang 已提交
266 267 268 269
      pool_.insert(
          IndexSizeAddress(block->right_buddy(cache_)->index(cache_),
                           block->right_buddy(cache_)->total_size(cache_),
                           block->right_buddy(cache_)));
L
liaogang 已提交
270 271 272 273
    }
  }

  return block;
274 275
}

L
liaogang 已提交
276
void BuddyAllocator::CleanIdleFallBackAlloc() {
277
  // If fallback allocation does not exist, return directly
S
sneaxiy 已提交
278
  if (!fallback_alloc_count_ || !system_allocator_->UseGpu()) return;
279 280 281 282

  for (auto pool = pool_.rbegin(); pool != pool_.rend();) {
    MemoryBlock* block = static_cast<MemoryBlock*>(std::get<2>(*pool));

S
sneaxiy 已提交
283 284
    auto desc = cache_.load(block);
    if (desc.index == 0) {
285 286 287
      return;
    }

M
minqiyang 已提交
288
    VLOG(10) << "Return block " << block << " to fallback allocator.";
289

S
sneaxiy 已提交
290
    system_allocator_->Free(block, desc.size, block->index(cache_));
291 292 293 294
    cache_.invalidate(block);

    pool = PoolSet::reverse_iterator(pool_.erase(std::next(pool).base()));

S
sneaxiy 已提交
295
    total_free_ -= desc.size;
296 297 298 299 300
    fallback_alloc_count_--;

    // If no fall allocation exists, return directly
    if (!fallback_alloc_count_) return;
  }
301 302
}

303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319
void BuddyAllocator::CleanIdleNormalAlloc() {
  auto shall_free_alloc = [&]() -> bool {
    // free all fallback allocations
    if (fallback_alloc_count_ > 0) {
      return true;
    }
    // keep 2x overhead if we haven't fallen back
    if ((total_used_ + max_chunk_size_) * 2 < total_free_) {
      return true;
    }
    return false;
  };

  if (!shall_free_alloc()) return;

  for (auto pool = pool_.rbegin(); pool != pool_.rend();) {
    MemoryBlock* block = static_cast<MemoryBlock*>(std::get<2>(*pool));
S
sneaxiy 已提交
320 321 322 323 324
    auto desc = cache_.load(block);

    if (desc.type != MemoryBlock::MANAGED_HUGE_CHUNK) {
      return;
    }
325

M
minqiyang 已提交
326
    VLOG(10) << "Return block " << block << " to base allocator.";
327

S
sneaxiy 已提交
328
    system_allocator_->Free(block, desc.size, desc.index);
329 330 331 332
    cache_.invalidate(block);

    pool = PoolSet::reverse_iterator(pool_.erase(std::next(pool).base()));

S
sneaxiy 已提交
333
    total_free_ -= desc.size;
334 335 336 337

    if (!shall_free_alloc()) return;
  }
}
L
liaogang 已提交
338

339 340 341
}  // namespace detail
}  // namespace memory
}  // namespace paddle