buddy_allocator.cc 10.9 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"
Z
zhhsplendid 已提交
16

17 18
#include <algorithm>
#include <utility>
Z
zhhsplendid 已提交
19

L
liaogang 已提交
20
#include "glog/logging.h"
21

22 23 24 25
DEFINE_bool(free_idle_memory, false,
            "If it is true, Paddle will try to free idle memory trunks during "
            "running time.");

26 27 28 29
#ifdef PADDLE_WITH_CUDA
DECLARE_uint64(reallocate_gpu_memory_in_mb);
#endif

30 31 32 33
namespace paddle {
namespace memory {
namespace detail {

G
gongweibao 已提交
34 35 36
BuddyAllocator::BuddyAllocator(
    std::unique_ptr<SystemAllocator> system_allocator, size_t min_chunk_size,
    size_t max_chunk_size)
37 38 39
    : min_chunk_size_(min_chunk_size),
      max_chunk_size_(max_chunk_size),
      cache_(system_allocator->UseGpu()),
L
liaogang 已提交
40 41 42
      system_allocator_(std::move(system_allocator)) {}

BuddyAllocator::~BuddyAllocator() {
M
minqiyang 已提交
43 44
  VLOG(10) << "BuddyAllocator Disconstructor makes sure that all of these "
              "have actually been freed";
L
liaogang 已提交
45 46
  while (!pool_.empty()) {
    auto block = static_cast<MemoryBlock*>(std::get<2>(*pool_.begin()));
47 48
    VLOG(10) << "Free from block (" << block << ", " << block->size(cache_)
             << ")";
L
liaogang 已提交
49

50
    system_allocator_->Free(block, block->size(cache_), block->index(cache_));
L
liaogang 已提交
51 52 53
    cache_.invalidate(block);
    pool_.erase(pool_.begin());
  }
L
liaogang 已提交
54 55 56 57 58 59 60 61 62
}

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 已提交
63 64
  size_t size =
      align(unaligned_size + sizeof(MemoryBlock::Desc), min_chunk_size_);
L
liaogang 已提交
65 66 67 68

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

M
minqiyang 已提交
69 70
  VLOG(10) << "Allocate " << unaligned_size << " bytes from chunk size "
           << size;
L
liaogang 已提交
71 72 73

  // if the allocation is huge, send directly to the system allocator
  if (size > max_chunk_size_) {
M
minqiyang 已提交
74
    VLOG(10) << "Allocate from system allocator.";
L
liaogang 已提交
75 76 77 78 79 80 81 82
    return SystemAlloc(size);
  }

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

  // refill the pool if failure
  if (it == pool_.end()) {
83
    it = RefillPool(size);
L
liaogang 已提交
84 85 86 87
    // if still failure, fail fatally
    if (it == pool_.end()) {
      return nullptr;
    }
L
liaogang 已提交
88
  } else {
M
minqiyang 已提交
89 90 91
    VLOG(10) << "Allocation from existing memory block " << std::get<2>(*it)
             << " at address "
             << reinterpret_cast<MemoryBlock*>(std::get<2>(*it))->data();
L
liaogang 已提交
92 93 94 95 96 97 98 99 100
  }

  total_used_ += size;
  total_free_ -= size;

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

L
liaogang 已提交
101
void BuddyAllocator::Free(void* p) {
L
liaogang 已提交
102
  // Point back to metadata
L
liaogang 已提交
103 104
  auto block = static_cast<MemoryBlock*>(p)->metadata();

L
liaogang 已提交
105
  // Acquire the allocator lock
L
liaogang 已提交
106
  std::lock_guard<std::mutex> lock(mutex_);
L
liaogang 已提交
107

M
minqiyang 已提交
108
  VLOG(10) << "Free from address " << block;
L
liaogang 已提交
109 110

  if (block->type(cache_) == MemoryBlock::HUGE_CHUNK) {
M
minqiyang 已提交
111
    VLOG(10) << "Free directly from system allocator";
L
liaogang 已提交
112 113 114 115
    system_allocator_->Free(block, block->total_size(cache_),
                            block->index(cache_));

    // Invalidate GPU allocation from cache
116 117
    cache_.invalidate(block);

L
liaogang 已提交
118 119 120
    return;
  }

Y
Update  
Yi Wang 已提交
121
  block->mark_as_free(&cache_);
L
liaogang 已提交
122 123 124 125 126 127

  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 已提交
128 129
    VLOG(10) << "Merging this block " << block << " with its right buddy "
             << block->right_buddy(cache_);
130 131 132 133 134

    auto right_buddy = block->right_buddy(cache_);

    if (right_buddy->type(cache_) == MemoryBlock::FREE_CHUNK) {
      // Take away right buddy from pool
L
liaogang 已提交
135 136 137
      pool_.erase(IndexSizeAddress(right_buddy->index(cache_),
                                   right_buddy->total_size(cache_),
                                   right_buddy));
138 139

      // merge its right buddy to the block
Y
Update  
Yi Wang 已提交
140
      block->merge(&cache_, right_buddy);
141
    }
L
liaogang 已提交
142 143 144 145
  }

  // Trying to merge the left buddy
  if (block->has_left_buddy(cache_)) {
M
minqiyang 已提交
146 147
    VLOG(10) << "Merging this block " << block << " with its left buddy "
             << block->left_buddy(cache_);
148 149 150 151 152

    auto left_buddy = block->left_buddy(cache_);

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

      // merge the block to its left buddy
Y
Update  
Yi Wang 已提交
157
      left_buddy->merge(&cache_, block);
158 159
      block = left_buddy;
    }
L
liaogang 已提交
160 161 162
  }

  // Dumping this block into pool
M
minqiyang 已提交
163 164
  VLOG(10) << "Inserting free block (" << block << ", "
           << block->total_size(cache_) << ")";
L
liaogang 已提交
165 166
  pool_.insert(
      IndexSizeAddress(block->index(cache_), block->total_size(cache_), block));
L
liaogang 已提交
167

168 169 170 171
  if (FLAGS_free_idle_memory) {
    // Clean up if existing too much free memory
    // Prefer freeing fallback allocation first
    CleanIdleFallBackAlloc();
L
liaogang 已提交
172

173 174 175
    // Free normal allocation
    CleanIdleNormalAlloc();
  }
L
liaogang 已提交
176 177
}

L
liaogang 已提交
178
size_t BuddyAllocator::Used() { return total_used_; }
D
Dun Liang 已提交
179 180
size_t BuddyAllocator::GetMinChunkSize() { return min_chunk_size_; }
size_t BuddyAllocator::GetMaxChunkSize() { return max_chunk_size_; }
L
liaogang 已提交
181

L
liaogang 已提交
182 183
void* BuddyAllocator::SystemAlloc(size_t size) {
  size_t index = 0;
Y
Update  
Yi Wang 已提交
184
  void* p = system_allocator_->Alloc(&index, size);
L
liaogang 已提交
185

M
minqiyang 已提交
186
  VLOG(10) << "Allocated " << p << " from system allocator.";
L
liaogang 已提交
187 188 189

  if (p == nullptr) return nullptr;

Y
Update  
Yi Wang 已提交
190
  static_cast<MemoryBlock*>(p)->init(&cache_, MemoryBlock::HUGE_CHUNK, index,
L
liaogang 已提交
191 192 193 194 195
                                     size, nullptr, nullptr);

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

196 197
BuddyAllocator::PoolSet::iterator BuddyAllocator::RefillPool(
    size_t request_bytes) {
Z
zhhsplendid 已提交
198 199 200
  size_t allocate_bytes = max_chunk_size_;
  size_t index = 0;

201
#ifdef PADDLE_WITH_CUDA
L
liaogang 已提交
202 203
  if (system_allocator_->UseGpu()) {
    if ((total_used_ + total_free_) == 0) {
Z
zhhsplendid 已提交
204
      // Compute the allocation size for gpu for the first allocation.
205
      allocate_bytes = std::max(platform::GpuInitAllocSize(), request_bytes);
Z
zhhsplendid 已提交
206
    } else {
207 208 209
      // Compute the re-allocation size, we store the re-allocation size when
      // user set FLAGS_reallocate_gpu_memory_in_mb to fix value.
      if (realloc_size_ == 0 || FLAGS_reallocate_gpu_memory_in_mb == 0ul) {
Z
zhhsplendid 已提交
210 211
        realloc_size_ = platform::GpuReallocSize();
      }
212
      allocate_bytes = std::max(realloc_size_, request_bytes);
L
liaogang 已提交
213 214
    }
  }
L
Luo Tao 已提交
215
#endif
L
liaogang 已提交
216

Z
zhhsplendid 已提交
217 218
  // Allocate a new block
  void* p = system_allocator_->Alloc(&index, allocate_bytes);
L
liaogang 已提交
219 220 221

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

M
minqiyang 已提交
222 223
  VLOG(10) << "Creating and inserting new block " << p
           << " from system allocator";
L
liaogang 已提交
224

Y
Yi Wang 已提交
225
  static_cast<MemoryBlock*>(p)->init(&cache_, MemoryBlock::FREE_CHUNK, index,
Z
zhhsplendid 已提交
226
                                     allocate_bytes, nullptr, nullptr);
L
liaogang 已提交
227

228 229 230 231 232 233
  // gpu fallback allocation
  if (system_allocator_->UseGpu() &&
      static_cast<MemoryBlock*>(p)->index(cache_) == 1) {
    fallback_alloc_count_++;
  }

Z
zhhsplendid 已提交
234
  total_free_ += allocate_bytes;
L
liaogang 已提交
235 236

  // dump the block into pool
Z
zhhsplendid 已提交
237
  return pool_.insert(IndexSizeAddress(index, allocate_bytes, p)).first;
L
liaogang 已提交
238 239 240 241 242 243
}

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

  while (1) {
L
liaogang 已提交
244
    auto it = pool_.lower_bound(IndexSizeAddress(index, size, nullptr));
245 246

    // no match chunk memory
L
liaogang 已提交
247 248 249
    if (it == pool_.end()) return it;

    if (std::get<0>(*it) > index) {
250
      // find suitable one
L
liaogang 已提交
251 252 253
      if (std::get<1>(*it) >= size) {
        return it;
      }
254
      // update and continue
L
liaogang 已提交
255 256 257 258 259 260 261 262 263 264 265 266
      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 已提交
267 268
  VLOG(10) << "Split block (" << block << ", " << block->total_size(cache_)
           << ") into";
Y
Update  
Yi Wang 已提交
269
  block->split(&cache_, size);
L
liaogang 已提交
270

M
minqiyang 已提交
271 272
  VLOG(10) << "Left block (" << block << ", " << block->total_size(cache_)
           << ")";
Y
Update  
Yi Wang 已提交
273
  block->set_type(&cache_, MemoryBlock::ARENA_CHUNK);
L
liaogang 已提交
274 275 276 277

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

L
liaogang 已提交
281 282 283 284
      pool_.insert(
          IndexSizeAddress(block->right_buddy(cache_)->index(cache_),
                           block->right_buddy(cache_)->total_size(cache_),
                           block->right_buddy(cache_)));
L
liaogang 已提交
285 286 287 288
    }
  }

  return block;
289 290
}

L
liaogang 已提交
291
void BuddyAllocator::CleanIdleFallBackAlloc() {
292 293 294 295 296 297 298 299 300 301 302 303 304 305
  // If fallback allocation does not exist, return directly
  if (!fallback_alloc_count_) return;

  for (auto pool = pool_.rbegin(); pool != pool_.rend();) {
    // If free memory block less than max_chunk_size_, return directly
    if (std::get<1>(*pool) < max_chunk_size_) return;

    MemoryBlock* block = static_cast<MemoryBlock*>(std::get<2>(*pool));

    // If no GPU fallback allocator, return
    if (!system_allocator_->UseGpu() || block->index(cache_) == 0) {
      return;
    }

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

308
    system_allocator_->Free(block, block->size(cache_), block->index(cache_));
309 310 311 312
    cache_.invalidate(block);

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

313
    total_free_ -= block->size(cache_);
314 315 316 317 318
    fallback_alloc_count_--;

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

321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341
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();) {
    // If free memory block less than max_chunk_size_, return directly
    if (std::get<1>(*pool) < max_chunk_size_) return;

    MemoryBlock* block = static_cast<MemoryBlock*>(std::get<2>(*pool));

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

344
    system_allocator_->Free(block, block->size(cache_), block->index(cache_));
345 346 347 348
    cache_.invalidate(block);

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

349
    total_free_ -= block->size(cache_);
350 351 352 353

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

355 356 357
}  // namespace detail
}  // namespace memory
}  // namespace paddle