system_allocator.cc 17.8 KB
Newer Older
1
/* Copyright (c) 2016 PaddlePaddle Authors. All Rights Reserved.
2 3 4 5 6 7 8 9 10 11 12 13

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. */
D
dzhwinter 已提交
14
#define GLOG_NO_ABBREVIATED_SEVERITIES
15

L
Leo Chen 已提交
16
#include "paddle/fluid/memory/allocation/system_allocator.h"
17

18 19
#include "paddle/fluid/memory/stats.h"

D
dzhwinter 已提交
20 21
#ifdef _WIN32
#include <malloc.h>
22 23 24
#ifndef NOMINMAX
#define NOMINMAX  // msvc max/min macro conflict with std::min/max
#endif
D
dzhwinter 已提交
25 26
#include <windows.h>  // VirtualLock/VirtualUnlock
#else
27
#include <sys/mman.h>  // for mlock and munlock
D
dzhwinter 已提交
28
#endif
29
#include "gflags/gflags.h"
30
#include "paddle/fluid/memory/allocation/allocator.h"
Y
Yi Wang 已提交
31
#include "paddle/fluid/platform/cpu_info.h"
32
#include "paddle/fluid/platform/device/gpu/gpu_info.h"
33
#include "paddle/fluid/platform/device/npu/npu_info.h"
Y
Yi Wang 已提交
34
#include "paddle/fluid/platform/enforce.h"
F
fwenguang 已提交
35 36 37
#ifdef PADDLE_WITH_MLU
#include "paddle/fluid/platform/device/mlu/mlu_info.h"
#endif
38

39
#if defined(PADDLE_WITH_CUDA) || defined(PADDLE_WITH_HIP)
40 41
#include "paddle/fluid/platform/cuda_device_guard.h"
#endif
42

43
#include "paddle/fluid/platform/device/device_wrapper.h"
44
#include "paddle/fluid/platform/profiler/mem_tracing.h"
45

S
sneaxiy 已提交
46
DECLARE_bool(use_pinned_memory);
47
DECLARE_double(fraction_of_gpu_memory_to_use);
48 49
DECLARE_uint64(initial_gpu_memory_in_mb);
DECLARE_uint64(reallocate_gpu_memory_in_mb);
Z
zhhsplendid 已提交
50

51 52 53 54
namespace paddle {
namespace memory {
namespace detail {

D
dzhwinter 已提交
55
void* AlignedMalloc(size_t size) {
G
gongweibao 已提交
56
  void* p = nullptr;
D
dzhwinter 已提交
57
  size_t alignment = 32ul;
T
tensor-tang 已提交
58
#ifdef PADDLE_WITH_MKLDNN
59
  // refer to https://github.com/01org/mkl-dnn/blob/master/include/dnnl.hpp
60
  // memory alignment
D
dzhwinter 已提交
61 62 63 64
  alignment = 4096ul;
#endif
#ifdef _WIN32
  p = _aligned_malloc(size, alignment);
65
#else
66 67
  int error = posix_memalign(&p, alignment, size);
  PADDLE_ENFORCE_EQ(
68 69
      error,
      0,
70 71
      platform::errors::ResourceExhausted(
          "Fail to alloc memory of %ld size, error code is %d.", size, error));
72
#endif
73 74 75
  PADDLE_ENFORCE_NOT_NULL(p,
                          platform::errors::ResourceExhausted(
                              "Fail to alloc memory of %ld size.", size));
D
dzhwinter 已提交
76 77 78 79 80 81 82 83 84 85 86 87
  return p;
}

void* CPUAllocator::Alloc(size_t* index, size_t size) {
  // According to http://www.cplusplus.com/reference/cstdlib/malloc/,
  // malloc might not return nullptr if size is zero, but the returned
  // pointer shall not be dereferenced -- so we make it nullptr.
  if (size <= 0) return nullptr;

  *index = 0;  // unlock memory

  void* p = AlignedMalloc(size);
88 89 90

  if (p != nullptr) {
    if (FLAGS_use_pinned_memory) {
Y
Yi Wang 已提交
91
      *index = 1;
D
dzhwinter 已提交
92 93 94
#ifdef _WIN32
      VirtualLock(p, size);
#else
95
      mlock(p, size);  // lock memory
D
dzhwinter 已提交
96
#endif
97
    }
98
  }
99

100
  HOST_MEMORY_STAT_UPDATE(Reserved, 0, size);
101 102
  platform::RecordMemEvent(
      p, CPUPlace(), size, platform::TracerMemEventType::ReservedAllocate);
103 104 105
  return p;
}

L
liaogang 已提交
106
void CPUAllocator::Free(void* p, size_t size, size_t index) {
107
  if (p != nullptr && index == 1) {
D
dzhwinter 已提交
108 109 110
#ifdef _WIN32
    VirtualUnlock(p, size);
#else
111
    munlock(p, size);
D
dzhwinter 已提交
112
#endif
113
  }
C
chenjian 已提交
114 115 116
  HOST_MEMORY_STAT_UPDATE(Reserved, 0, -size);
  platform::RecordMemEvent(
      p, CPUPlace(), size, platform::TracerMemEventType::ReservedFree);
P
peizhilin 已提交
117 118 119
#ifdef _WIN32
  _aligned_free(p);
#else
120
  free(p);
P
peizhilin 已提交
121
#endif
122 123
}

L
liaogang 已提交
124
bool CPUAllocator::UseGpu() const { return false; }
L
liaogang 已提交
125

126
#if defined(PADDLE_WITH_CUDA) || defined(PADDLE_WITH_HIP)
127

Y
Yi Wang 已提交
128
void* GPUAllocator::Alloc(size_t* index, size_t size) {
129 130
  // CUDA documentation doesn't explain if cudaMalloc returns nullptr
  // if size is 0.  We just make sure it does.
L
liaogang 已提交
131
  if (size <= 0) return nullptr;
Y
Yu Yang 已提交
132

133
  void* p;
134
  auto result = platform::RecordedGpuMalloc(&p, size, gpu_id_);
Y
Yu Yang 已提交
135

136
  if (result == gpuSuccess) {
Y
Yi Wang 已提交
137
    *index = 0;
138
    gpu_alloc_size_ += size;
L
liaogang 已提交
139
    return p;
140
  } else {
141
    size_t avail, total, actual_avail, actual_total;
142
    bool is_limited = platform::RecordedGpuMemGetInfo(
143
        &avail, &total, &actual_avail, &actual_total, gpu_id_);
144
    size_t allocated = total - avail;
145 146 147 148 149 150 151 152 153

    std::string err_msg;
    if (is_limited) {
      auto limit_size = (total >> 20);
      err_msg = string::Sprintf(
          "\n   3) Set environment variable `FLAGS_gpu_memory_limit_mb` to a "
          "larger value. Currently `FLAGS_gpu_memory_limit_mb` is %d, so the "
          "maximum GPU memory usage is limited to %d MB.\n"
          "      The command is `export FLAGS_gpu_memory_limit_mb=xxx`.",
154 155
          limit_size,
          limit_size);
156
    }
157

158
    PADDLE_THROW_BAD_ALLOC(platform::errors::ResourceExhausted(
159
        "\n\nOut of memory error on GPU %d. "
160
        "Cannot allocate %s memory on GPU %d, %s memory has been allocated and "
161 162 163 164 165 166 167 168
        "available memory is only %s.\n\n"
        "Please check whether there is any other process using GPU %d.\n"
        "1. If yes, please stop them, or start PaddlePaddle on another GPU.\n"
        "2. If no, please try one of the following suggestions:\n"
        "   1) Decrease the batch size of your model.\n"
        "   2) FLAGS_fraction_of_gpu_memory_to_use is %.2lf now, "
        "please set it to a higher value but less than 1.0.\n"
        "      The command is "
169
        "`export FLAGS_fraction_of_gpu_memory_to_use=xxx`.%s\n\n",
170 171 172 173 174 175 176 177
        gpu_id_,
        string::HumanReadableSize(size),
        gpu_id_,
        string::HumanReadableSize(allocated),
        string::HumanReadableSize(avail),
        gpu_id_,
        FLAGS_fraction_of_gpu_memory_to_use,
        err_msg));
L
liaogang 已提交
178
  }
179 180
}

L
liaogang 已提交
181
void GPUAllocator::Free(void* p, size_t size, size_t index) {
182 183
  PADDLE_ENFORCE_EQ(index,
                    0,
184 185
                    platform::errors::InvalidArgument(
                        "The index should be 0, index is %d", index));
186 187
  PADDLE_ENFORCE_GE(gpu_alloc_size_,
                    size,
188 189 190
                    platform::errors::InvalidArgument(
                        "The size of memory (%d) to free exceeds the size of "
                        "allocated gpu memory (%d)",
191 192
                        size,
                        gpu_alloc_size_));
193
  gpu_alloc_size_ -= size;
194

195
  platform::RecordedGpuFree(p, size, gpu_id_);
196 197
}

L
liaogang 已提交
198
bool GPUAllocator::UseGpu() const { return true; }
L
liaogang 已提交
199

C
chengduoZH 已提交
200 201
// PINNED memory allows direct DMA transfers by the GPU to and from system
// memory. It’s locked to a physical address.
Y
Yi Wang 已提交
202
void* CUDAPinnedAllocator::Alloc(size_t* index, size_t size) {
C
chengduoZH 已提交
203
  if (size <= 0) return nullptr;
C
chengduoZH 已提交
204

205
  // NOTE: here, we use CUDAPinnedMaxAllocSize as the maximum memory size
C
chengduoZH 已提交
206
  // of host pinned allocation. Allocates too much would reduce
C
chengduoZH 已提交
207
  // the amount of memory available to the underlying system for paging.
C
chengduoZH 已提交
208
  size_t usable =
209
      paddle::platform::CUDAPinnedMaxAllocSize() - cuda_pinnd_alloc_size_;
C
chengduoZH 已提交
210

C
chengduoZH 已提交
211 212 213 214 215 216
  if (size > usable) {
    LOG(WARNING) << "Cannot malloc " << size / 1024.0 / 1024.0
                 << " MB pinned memory."
                 << ", available " << usable / 1024.0 / 1024.0 << " MB";
    return nullptr;
  }
C
chengduoZH 已提交
217

C
chengduoZH 已提交
218
  void* p;
219 220
// PINNED memory is visible to all CUDA contexts.
#ifdef PADDLE_WITH_HIP
221
  hipError_t result = hipHostMalloc(&p, size, hipHostMallocPortable);
222
#else
D
Dun Liang 已提交
223
  cudaError_t result = cudaHostAlloc(&p, size, cudaHostAllocPortable);
224
#endif
C
chengduoZH 已提交
225

226
  if (result == gpuSuccess) {
Y
Yi Wang 已提交
227
    *index = 1;  // PINNED memory
C
chengduoZH 已提交
228
    cuda_pinnd_alloc_size_ += size;
229
    HOST_MEMORY_STAT_UPDATE(Reserved, 0, size);
230 231
    platform::RecordMemEvent(
        p, CPUPlace(), size, platform::TracerMemEventType::ReservedAllocate);
C
chengduoZH 已提交
232
    return p;
C
chengduoZH 已提交
233
  } else {
D
Dun Liang 已提交
234
    LOG(WARNING) << "cudaHostAlloc failed.";
C
chengduoZH 已提交
235
    return nullptr;
C
chengduoZH 已提交
236 237 238 239 240 241
  }

  return nullptr;
}

void CUDAPinnedAllocator::Free(void* p, size_t size, size_t index) {
242
  gpuError_t err;
243 244
  PADDLE_ENFORCE_EQ(index,
                    1,
245 246
                    platform::errors::InvalidArgument(
                        "The index should be 1, but got %d", index));
247

248 249
  PADDLE_ENFORCE_GE(cuda_pinnd_alloc_size_,
                    size,
250 251 252
                    platform::errors::InvalidArgument(
                        "The size of memory (%d) to free exceeds the size of "
                        "allocated cuda pinned memory (%d)",
253 254
                        size,
                        cuda_pinnd_alloc_size_));
C
chengduoZH 已提交
255
  cuda_pinnd_alloc_size_ -= size;
256 257 258 259
#ifdef PADDLE_WITH_HIP
  err = hipHostFree(p);
  if (err != hipErrorDeinitialized) {
    PADDLE_ENFORCE_EQ(
260 261
        err,
        hipSuccess,
262 263 264 265
        platform::errors::Fatal(
            "hipFreeHost failed in GPUPinnedAllocator, error code is %d", err));
  }
#else
C
chengduoZH 已提交
266 267 268
  err = cudaFreeHost(p);

  // Purposefully allow cudaErrorCudartUnloading, because
C
chengduoZH 已提交
269
  // that is returned if you ever call cudaFreeHost after the
C
chengduoZH 已提交
270 271
  // driver has already shutdown. This happens only if the
  // process is terminating, in which case we don't care if
C
chengduoZH 已提交
272
  // cudaFreeHost succeeds.
C
chengduoZH 已提交
273
  if (err != cudaErrorCudartUnloading) {
274
    PADDLE_ENFORCE_EQ(
275 276
        err,
        0,
277 278 279
        platform::errors::Fatal(
            "cudaFreeHost failed in GPUPinnedAllocator, error code is %d",
            err));
C
chengduoZH 已提交
280
  }
281
#endif
282
  HOST_MEMORY_STAT_UPDATE(Reserved, 0, -size);
283 284
  platform::RecordMemEvent(
      p, CPUPlace(), size, platform::TracerMemEventType::ReservedFree);
C
chengduoZH 已提交
285 286
}

C
chengduoZH 已提交
287
bool CUDAPinnedAllocator::UseGpu() const { return false; }
C
chengduoZH 已提交
288

L
Luo Tao 已提交
289
#endif
290

291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314
#ifdef PADDLE_WITH_ASCEND_CL
void* NPUAllocator::Alloc(size_t* index, size_t size) {
  if (size <= 0) return nullptr;

  void* p;
  auto result = platform::RecordedNPUMalloc(&p, size, npu_id_);

  if (result == ACL_ERROR_NONE) {
    *index = 0;
    npu_alloc_size_ += size;
    return p;
  } else {
    size_t avail, total, actual_avail, actual_total;
    bool is_limited = platform::RecordedNPUMemGetInfo(
        &avail, &total, &actual_avail, &actual_total, npu_id_);

    std::string err_msg;
    if (is_limited) {
      auto limit_size = (total >> 20);
      err_msg = string::Sprintf(
          "\n   3) Set environment variable `FLAGS_gpu_memory_limit_mb` to a "
          "larger value. Currently `FLAGS_gpu_memory_limit_mb` is %d, so the "
          "maximum GPU memory usage is limited to %d MB.\n"
          "      The command is `export FLAGS_gpu_memory_limit_mb=xxx`.",
315 316
          limit_size,
          limit_size);
317 318 319 320 321 322 323 324 325 326 327 328 329 330
    }

    PADDLE_THROW_BAD_ALLOC(platform::errors::ResourceExhausted(
        "\n\nOut of memory error on NPU %d. "
        "Cannot allocate %s memory on NPU %d, "
        "available memory is only %s.\n\n"
        "Please check whether there is any other process using NPU %d.\n"
        "1. If yes, please stop them, or start PaddlePaddle on another NPU.\n"
        "2. If no, please try one of the following suggestions:\n"
        "   1) Decrease the batch size of your model.\n"
        "   2) FLAGS_fraction_of_gpu_memory_to_use is %.2lf now, "
        "please set it to a higher value but less than 1.0.\n"
        "      The command is "
        "`export FLAGS_fraction_of_gpu_memory_to_use=xxx`.%s\n\n",
331 332 333 334 335 336 337
        npu_id_,
        string::HumanReadableSize(size),
        npu_id_,
        string::HumanReadableSize(avail),
        npu_id_,
        FLAGS_fraction_of_gpu_memory_to_use,
        err_msg));
338 339 340 341 342
  }
}

void NPUAllocator::Free(void* p, size_t size, size_t index) {
  VLOG(4) << "Free " << p << " size " << size;
343 344
  PADDLE_ENFORCE_EQ(index,
                    0,
345 346
                    platform::errors::InvalidArgument(
                        "The index should be 0, index is %d", index));
347 348
  PADDLE_ENFORCE_GE(npu_alloc_size_,
                    size,
349 350 351
                    platform::errors::InvalidArgument(
                        "The size of memory (%d) to free exceeds the size of "
                        "allocated gpu memory (%d)",
352 353
                        size,
                        npu_alloc_size_));
354 355 356 357 358 359
  npu_alloc_size_ -= size;

  platform::RecordedNPUFree(p, size, npu_id_);
}

bool NPUAllocator::UseGpu() const { return true; }
360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375

void* NPUPinnedAllocator::Alloc(size_t* index, size_t size) {
  if (size <= 0) return nullptr;

  size_t usable =
      paddle::platform::NPUPinnedMaxAllocSize() - npu_pinnd_alloc_size_;

  if (size > usable) {
    LOG(WARNING) << "Cannot malloc " << size / 1024.0 / 1024.0
                 << " MB pinned memory."
                 << ", available " << usable / 1024.0 / 1024.0 << " MB";
    return nullptr;
  }

  void* p;
  // PINNED memory is visible to all NPU contexts.
376
  auto result = platform::NPUHostMalloc(&p, size);
377 378 379 380 381 382

  if (result == ACL_ERROR_NONE) {
    *index = 1;  // PINNED memory
    npu_pinnd_alloc_size_ += size;
    return p;
  } else {
383
    LOG(WARNING) << "NPUHostMalloc failed.";
384 385 386 387 388 389 390 391
    return nullptr;
  }

  return nullptr;
}

void NPUPinnedAllocator::Free(void* p, size_t size, size_t index) {
  aclError err;
392 393
  PADDLE_ENFORCE_EQ(index,
                    1,
394 395
                    platform::errors::InvalidArgument(
                        "The index should be 1, but got %d", index));
396

397 398
  PADDLE_ENFORCE_GE(npu_pinnd_alloc_size_,
                    size,
399 400 401
                    platform::errors::InvalidArgument(
                        "The size of memory (%d) to free exceeds the size of "
                        "allocated npu pinned memory (%d)",
402 403
                        size,
                        npu_pinnd_alloc_size_));
404
  npu_pinnd_alloc_size_ -= size;
405
  err = platform::NPUHostFree(p);
406 407 408

  if (err != ACL_ERROR_NONE) {
    PADDLE_ENFORCE_EQ(
409 410
        err,
        0,
411
        platform::errors::Fatal(
412
            "NPUHostFree failed in NPUPinnedAllocator, error code is %d", err));
413 414 415 416 417
  }
}

bool NPUPinnedAllocator::UseGpu() const { return false; }

418 419
#endif

F
fwenguang 已提交
420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444
#ifdef PADDLE_WITH_MLU
void* MLUAllocator::Alloc(size_t* index, size_t size) {
  if (size <= 0) return nullptr;

  void* p;
  auto result = platform::RecordedMLUMalloc(&p, size, mlu_id_);

  if (result == cnrtSuccess) {
    *index = 0;
    mlu_alloc_size_ += size;
    return p;
  } else {
    size_t avail, total, actual_avail, actual_total;
    bool is_limited = platform::RecordedMLUMemGetInfo(
        &avail, &total, &actual_avail, &actual_total, mlu_id_);
    size_t allocated = total - avail;

    std::string err_msg;
    if (is_limited) {
      auto limit_size = (total >> 20);
      err_msg = string::Sprintf(
          "\n   3) Set environment variable `FLAGS_gpu_memory_limit_mb` to a "
          "larger value. Currently `FLAGS_gpu_memory_limit_mb` is %d, so the "
          "maximum MLU memory usage is limited to %d MB.\n"
          "      The command is `export FLAGS_gpu_memory_limit_mb=xxx`.",
445 446
          limit_size,
          limit_size);
F
fwenguang 已提交
447 448 449 450 451 452 453 454 455 456 457 458 459 460
    }

    PADDLE_THROW_BAD_ALLOC(platform::errors::ResourceExhausted(
        "\n\nOut of memory error on MLU %d. "
        "Cannot allocate %s memory on MLU %d, %s memory has been allocated and "
        "available memory is only %s.\n\n"
        "Please check whether there is any other process using MLU %d.\n"
        "1. If yes, please stop them, or start PaddlePaddle on another MLU.\n"
        "2. If no, please try one of the following suggestions:\n"
        "   1) Decrease the batch size of your model.\n"
        "   2) FLAGS_fraction_of_gpu_memory_to_use is %.2lf now, "
        "please set it to a higher value but less than 1.0.\n"
        "      The command is "
        "`export FLAGS_fraction_of_gpu_memory_to_use=xxx`.%s\n\n",
461 462 463 464 465 466 467 468
        mlu_id_,
        string::HumanReadableSize(size),
        mlu_id_,
        string::HumanReadableSize(allocated),
        string::HumanReadableSize(avail),
        mlu_id_,
        FLAGS_fraction_of_gpu_memory_to_use,
        err_msg));
F
fwenguang 已提交
469 470 471 472
  }
}

void MLUAllocator::Free(void* p, size_t size, size_t index) {
473 474
  PADDLE_ENFORCE_EQ(index,
                    0,
475 476
                    platform::errors::InvalidArgument(
                        "The index should be 0, index is %d", index));
477 478
  PADDLE_ENFORCE_GE(mlu_alloc_size_,
                    size,
F
fwenguang 已提交
479 480 481
                    platform::errors::InvalidArgument(
                        "The size of memory (%d) to free exceeds the size of "
                        "allocated gpu memory (%d)",
482 483
                        size,
                        mlu_alloc_size_));
F
fwenguang 已提交
484 485 486 487 488 489 490 491
  mlu_alloc_size_ -= size;

  platform::RecordedMLUFree(p, size, mlu_id_);
}

bool MLUAllocator::UseGpu() const { return true; }
#endif

492 493 494 495 496 497
#ifdef PADDLE_WITH_CUSTOM_DEVICE
void* CustomAllocator::Alloc(size_t* index, size_t size) {
  if (size <= 0) return nullptr;

  void* p;
  auto place = platform::CustomPlace(dev_type_, dev_id_);
498
  auto device = phi::DeviceManager::GetDeviceWithPlace(place);
499 500 501 502 503 504 505 506
  p = device->MemoryAllocate(size);
  if (LIKELY(p)) {
    VLOG(4) << "CustomAllocator::Alloc " << p << " size " << size;
    *index = 0;
    plug_alloc_size += size;
  } else {
    size_t avail, total;

507
    phi::DeviceManager::MemoryStats(place, &total, &avail);
508 509 510 511
    PADDLE_THROW_BAD_ALLOC(platform::errors::ResourceExhausted(
        "\n\nOut of memory error on %s %d. "
        "total memory is %s, used memory is %s, "
        "available memory is only %s.\n\n",
512 513 514
        dev_type_,
        dev_id_,
        string::HumanReadableSize(total),
515 516 517 518 519 520 521 522
        string::HumanReadableSize(total - avail),
        string::HumanReadableSize(avail)));
  }
  return p;
}

void CustomAllocator::Free(void* p, size_t size, size_t index) {
  VLOG(4) << "CustomAllocator::Free " << p << " size " << size;
523 524
  PADDLE_ENFORCE_EQ(index,
                    0,
525 526
                    platform::errors::InvalidArgument(
                        "The index should be 0, index is %d", index));
527 528
  PADDLE_ENFORCE_GE(plug_alloc_size,
                    size,
529 530 531
                    platform::errors::InvalidArgument(
                        "The size of memory (%d) to free exceeds the size of "
                        "allocated gpu memory (%d)",
532 533
                        size,
                        plug_alloc_size));
534 535
  plug_alloc_size -= size;
  auto place = platform::CustomPlace(dev_type_, dev_id_);
536
  auto device = phi::DeviceManager::GetDeviceWithPlace(place);
537 538 539 540 541 542
  device->MemoryDeallocate(p, size);
}

bool CustomAllocator::UseGpu() const { return true; }
#endif

543 544 545
}  // namespace detail
}  // namespace memory
}  // namespace paddle