system_allocator.cc 12.2 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

Y
Yi Wang 已提交
16
#include "paddle/fluid/memory/detail/system_allocator.h"
17

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

34
#if defined(PADDLE_WITH_CUDA) || defined(PADDLE_WITH_HIP)
35 36
#include "paddle/fluid/platform/cuda_device_guard.h"
#endif
37

S
sneaxiy 已提交
38
DECLARE_bool(use_pinned_memory);
39
DECLARE_double(fraction_of_gpu_memory_to_use);
40 41
DECLARE_uint64(initial_gpu_memory_in_mb);
DECLARE_uint64(reallocate_gpu_memory_in_mb);
Z
zhhsplendid 已提交
42

43 44 45 46
namespace paddle {
namespace memory {
namespace detail {

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

  if (p != nullptr) {
    if (FLAGS_use_pinned_memory) {
Y
Yi Wang 已提交
81
      *index = 1;
D
dzhwinter 已提交
82 83 84
#ifdef _WIN32
      VirtualLock(p, size);
#else
85
      mlock(p, size);  // lock memory
D
dzhwinter 已提交
86
#endif
87
    }
88
  }
89

90 91 92
  return p;
}

L
liaogang 已提交
93
void CPUAllocator::Free(void* p, size_t size, size_t index) {
94
  if (p != nullptr && index == 1) {
D
dzhwinter 已提交
95 96 97
#ifdef _WIN32
    VirtualUnlock(p, size);
#else
98
    munlock(p, size);
D
dzhwinter 已提交
99
#endif
100
  }
P
peizhilin 已提交
101 102 103
#ifdef _WIN32
  _aligned_free(p);
#else
104
  free(p);
P
peizhilin 已提交
105
#endif
106 107
}

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

110
#if defined(PADDLE_WITH_CUDA) || defined(PADDLE_WITH_HIP)
111

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

117
  void* p;
118
  auto result = platform::RecordedGpuMalloc(&p, size, gpu_id_);
Y
Yu Yang 已提交
119

120
  if (result == gpuSuccess) {
Y
Yi Wang 已提交
121
    *index = 0;
122
    gpu_alloc_size_ += size;
L
liaogang 已提交
123
    return p;
124
  } else {
125
    size_t avail, total, actual_avail, actual_total;
126
    bool is_limited = platform::RecordedGpuMemGetInfo(
127
        &avail, &total, &actual_avail, &actual_total, gpu_id_);
128
    size_t allocated = total - avail;
129 130 131 132 133 134 135 136 137 138 139

    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`.",
          limit_size, limit_size);
    }
140

141
    PADDLE_THROW_BAD_ALLOC(platform::errors::ResourceExhausted(
142
        "\n\nOut of memory error on GPU %d. "
143
        "Cannot allocate %s memory on GPU %d, %s memory has been allocated and "
144 145 146 147 148 149 150 151
        "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 "
152
        "`export FLAGS_fraction_of_gpu_memory_to_use=xxx`.%s\n\n",
153
        gpu_id_, string::HumanReadableSize(size), gpu_id_,
154 155
        string::HumanReadableSize(allocated), string::HumanReadableSize(avail),
        gpu_id_, FLAGS_fraction_of_gpu_memory_to_use, err_msg));
L
liaogang 已提交
156
  }
157 158
}

L
liaogang 已提交
159
void GPUAllocator::Free(void* p, size_t size, size_t index) {
160 161 162 163 164 165 166
  PADDLE_ENFORCE_EQ(index, 0, platform::errors::InvalidArgument(
                                  "The index should be 0, index is %d", index));
  PADDLE_ENFORCE_GE(gpu_alloc_size_, size,
                    platform::errors::InvalidArgument(
                        "The size of memory (%d) to free exceeds the size of "
                        "allocated gpu memory (%d)",
                        size, gpu_alloc_size_));
167
  gpu_alloc_size_ -= size;
168

169
  platform::RecordedGpuFree(p, size, gpu_id_);
170 171
}

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

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

179
  // NOTE: here, we use CUDAPinnedMaxAllocSize as the maximum memory size
C
chengduoZH 已提交
180
  // of host pinned allocation. Allocates too much would reduce
C
chengduoZH 已提交
181
  // the amount of memory available to the underlying system for paging.
C
chengduoZH 已提交
182
  size_t usable =
183
      paddle::platform::CUDAPinnedMaxAllocSize() - cuda_pinnd_alloc_size_;
C
chengduoZH 已提交
184

C
chengduoZH 已提交
185 186 187 188 189 190
  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 已提交
191

C
chengduoZH 已提交
192
  void* p;
193 194
// PINNED memory is visible to all CUDA contexts.
#ifdef PADDLE_WITH_HIP
195
  hipError_t result = hipHostMalloc(&p, size, hipHostMallocPortable);
196
#else
D
Dun Liang 已提交
197
  cudaError_t result = cudaHostAlloc(&p, size, cudaHostAllocPortable);
198
#endif
C
chengduoZH 已提交
199

200
  if (result == gpuSuccess) {
Y
Yi Wang 已提交
201
    *index = 1;  // PINNED memory
C
chengduoZH 已提交
202
    cuda_pinnd_alloc_size_ += size;
C
chengduoZH 已提交
203
    return p;
C
chengduoZH 已提交
204
  } else {
D
Dun Liang 已提交
205
    LOG(WARNING) << "cudaHostAlloc failed.";
C
chengduoZH 已提交
206
    return nullptr;
C
chengduoZH 已提交
207 208 209 210 211 212
  }

  return nullptr;
}

void CUDAPinnedAllocator::Free(void* p, size_t size, size_t index) {
213
  gpuError_t err;
214 215 216 217 218 219 220 221
  PADDLE_ENFORCE_EQ(index, 1, platform::errors::InvalidArgument(
                                  "The index should be 1, but got %d", index));

  PADDLE_ENFORCE_GE(cuda_pinnd_alloc_size_, size,
                    platform::errors::InvalidArgument(
                        "The size of memory (%d) to free exceeds the size of "
                        "allocated cuda pinned memory (%d)",
                        size, cuda_pinnd_alloc_size_));
C
chengduoZH 已提交
222
  cuda_pinnd_alloc_size_ -= size;
223 224 225 226 227 228 229 230 231
#ifdef PADDLE_WITH_HIP
  err = hipHostFree(p);
  if (err != hipErrorDeinitialized) {
    PADDLE_ENFORCE_EQ(
        err, hipSuccess,
        platform::errors::Fatal(
            "hipFreeHost failed in GPUPinnedAllocator, error code is %d", err));
  }
#else
C
chengduoZH 已提交
232 233 234
  err = cudaFreeHost(p);

  // Purposefully allow cudaErrorCudartUnloading, because
C
chengduoZH 已提交
235
  // that is returned if you ever call cudaFreeHost after the
C
chengduoZH 已提交
236 237
  // driver has already shutdown. This happens only if the
  // process is terminating, in which case we don't care if
C
chengduoZH 已提交
238
  // cudaFreeHost succeeds.
C
chengduoZH 已提交
239
  if (err != cudaErrorCudartUnloading) {
240 241 242 243 244
    PADDLE_ENFORCE_EQ(
        err, 0,
        platform::errors::Fatal(
            "cudaFreeHost failed in GPUPinnedAllocator, error code is %d",
            err));
C
chengduoZH 已提交
245
  }
246
#endif
C
chengduoZH 已提交
247 248
}

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

L
Luo Tao 已提交
251
#endif
252

253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312
#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`.",
          limit_size, limit_size);
    }

    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",
        npu_id_, string::HumanReadableSize(size), npu_id_,
        string::HumanReadableSize(avail), npu_id_,
        FLAGS_fraction_of_gpu_memory_to_use, err_msg));
  }
}

void NPUAllocator::Free(void* p, size_t size, size_t index) {
  VLOG(4) << "Free " << p << " size " << size;
  PADDLE_ENFORCE_EQ(index, 0, platform::errors::InvalidArgument(
                                  "The index should be 0, index is %d", index));
  PADDLE_ENFORCE_GE(npu_alloc_size_, size,
                    platform::errors::InvalidArgument(
                        "The size of memory (%d) to free exceeds the size of "
                        "allocated gpu memory (%d)",
                        size, npu_alloc_size_));
  npu_alloc_size_ -= size;

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

bool NPUAllocator::UseGpu() const { return true; }
313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328

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.
329
  auto result = platform::NPUHostMalloc(&p, size);
330 331 332 333 334 335

  if (result == ACL_ERROR_NONE) {
    *index = 1;  // PINNED memory
    npu_pinnd_alloc_size_ += size;
    return p;
  } else {
336
    LOG(WARNING) << "NPUHostMalloc failed.";
337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353
    return nullptr;
  }

  return nullptr;
}

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

  PADDLE_ENFORCE_GE(npu_pinnd_alloc_size_, size,
                    platform::errors::InvalidArgument(
                        "The size of memory (%d) to free exceeds the size of "
                        "allocated npu pinned memory (%d)",
                        size, npu_pinnd_alloc_size_));
  npu_pinnd_alloc_size_ -= size;
354
  err = platform::NPUHostFree(p);
355 356 357 358 359

  if (err != ACL_ERROR_NONE) {
    PADDLE_ENFORCE_EQ(
        err, 0,
        platform::errors::Fatal(
360
            "NPUHostFree failed in NPUPinnedAllocator, error code is %d", err));
361 362 363 364 365
  }
}

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

366 367
#endif

368 369 370
}  // namespace detail
}  // namespace memory
}  // namespace paddle