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

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. */

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

#include <stdlib.h>    // for malloc and free
#include <sys/mman.h>  // for mlock and munlock
19
#include <algorithm>   // for std::max
20 21

#include "gflags/gflags.h"
Y
Yi Wang 已提交
22 23 24 25
#include "paddle/fluid/platform/assert.h"
#include "paddle/fluid/platform/cpu_info.h"
#include "paddle/fluid/platform/enforce.h"
#include "paddle/fluid/platform/gpu_info.h"
26 27 28 29 30 31

// If use_pinned_memory is true, CPUAllocator calls mlock, which
// returns pinned and locked memory as staging areas for data exchange
// between host and device.  Allocates too much would reduce the amount
// of memory available to the system for paging.  So, by default, we
// should set false to use_pinned_memory.
32
DEFINE_bool(use_pinned_memory, true, "If set, allocate cpu pinned memory.");
33
DECLARE_double(fraction_of_gpu_memory_to_use);
34 35 36 37
namespace paddle {
namespace memory {
namespace detail {

Y
Yi Wang 已提交
38
void* CPUAllocator::Alloc(size_t* index, size_t size) {
39 40 41 42 43
  // 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;

Y
Yi Wang 已提交
44
  *index = 0;  // unlock memory
L
liaogang 已提交
45

G
gongweibao 已提交
46
  void* p = nullptr;
47

T
tensor-tang 已提交
48
#ifdef PADDLE_WITH_MKLDNN
49 50
  // refer to https://github.com/01org/mkl-dnn/blob/master/include/mkldnn.hpp
  // memory alignment
G
gongweibao 已提交
51 52
  PADDLE_ENFORCE_EQ(posix_memalign(&p, 4096ul, size), 0, "Alloc %ld error!",
                    size);
53
#else
G
gongweibao 已提交
54 55
  PADDLE_ENFORCE_EQ(posix_memalign(&p, 32ul, size), 0, "Alloc %ld error!",
                    size);
56 57
#endif
  PADDLE_ENFORCE(p, "Fail to allocate CPU memory: size = %d .", size);
58 59 60

  if (p != nullptr) {
    if (FLAGS_use_pinned_memory) {
Y
Yi Wang 已提交
61
      *index = 1;
62 63
      mlock(p, size);  // lock memory
    }
64
  }
65

66 67 68
  return p;
}

L
liaogang 已提交
69
void CPUAllocator::Free(void* p, size_t size, size_t index) {
70
  if (p != nullptr && index == 1) {
71 72 73 74 75
    munlock(p, size);
  }
  free(p);
}

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

78
#ifdef PADDLE_WITH_CUDA
79

Y
Yi Wang 已提交
80
void* GPUAllocator::Alloc(size_t* index, size_t size) {
81 82
  // CUDA documentation doesn't explain if cudaMalloc returns nullptr
  // if size is 0.  We just make sure it does.
L
liaogang 已提交
83
  if (size <= 0) return nullptr;
84
  void* p;
Y
Yu Yang 已提交
85 86 87 88 89 90
  int prev_id;
  cudaGetDevice(&prev_id);
  if (prev_id != gpu_id_) {
    cudaSetDevice(gpu_id_);
  }

91
  cudaError_t result = cudaMalloc(&p, size);
Y
Yu Yang 已提交
92 93 94 95 96

  if (prev_id != gpu_id_) {
    cudaSetDevice(prev_id);
  }

L
liaogang 已提交
97
  if (result == cudaSuccess) {
Y
Yi Wang 已提交
98
    *index = 0;
99
    gpu_alloc_size_ += size;
L
liaogang 已提交
100
    return p;
101 102 103 104 105 106 107
  } else {
    LOG(WARNING)
        << "Cannot malloc " << size / 1024.0 / 1024.0
        << " MB GPU memory. Please shrink FLAGS_fraction_of_gpu_memory_to_use "
           "environment variable to a lower value. Current value is "
        << FLAGS_fraction_of_gpu_memory_to_use;
    return nullptr;
L
liaogang 已提交
108
  }
109 110
}

L
liaogang 已提交
111
void GPUAllocator::Free(void* p, size_t size, size_t index) {
112 113 114 115 116 117 118 119 120 121 122 123
  cudaError_t err;

  if (index == 0) {
    PADDLE_ASSERT(gpu_alloc_size_ >= size);
    gpu_alloc_size_ -= size;
    err = cudaFree(p);
  } else {
    PADDLE_ASSERT(fallback_alloc_size_ >= size);
    fallback_alloc_size_ -= size;
    err = cudaFreeHost(p);
  }

124 125 126 127 128 129
  // Purposefully allow cudaErrorCudartUnloading, because
  // that is returned if you ever call cudaFree after the
  // driver has already shutdown. This happens only if the
  // process is terminating, in which case we don't care if
  // cudaFree succeeds.
  if (err != cudaErrorCudartUnloading) {
L
liaogang 已提交
130
    PADDLE_ENFORCE(err, "cudaFree{Host} failed in GPUAllocator::Free.");
131 132 133
  }
}

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

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

141
  // NOTE: here, we use CUDAPinnedMaxAllocSize as the maximum memory size
C
chengduoZH 已提交
142
  // of host pinned allocation. Allocates too much would reduce
C
chengduoZH 已提交
143
  // the amount of memory available to the underlying system for paging.
C
chengduoZH 已提交
144
  size_t usable =
145
      paddle::platform::CUDAPinnedMaxAllocSize() - cuda_pinnd_alloc_size_;
C
chengduoZH 已提交
146

C
chengduoZH 已提交
147 148 149 150 151 152
  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 已提交
153

C
chengduoZH 已提交
154
  void* p;
C
chengduoZH 已提交
155
  // PINNED memory is visible to all CUDA contexts.
C
chengduoZH 已提交
156
  cudaError_t result = cudaMallocHost(&p, size);
C
chengduoZH 已提交
157

C
chengduoZH 已提交
158
  if (result == cudaSuccess) {
Y
Yi Wang 已提交
159
    *index = 1;  // PINNED memory
C
chengduoZH 已提交
160
    cuda_pinnd_alloc_size_ += size;
C
chengduoZH 已提交
161
    return p;
C
chengduoZH 已提交
162 163 164
  } else {
    LOG(WARNING) << "cudaMallocHost failed.";
    return nullptr;
C
chengduoZH 已提交
165 166 167 168 169 170 171 172 173
  }

  return nullptr;
}

void CUDAPinnedAllocator::Free(void* p, size_t size, size_t index) {
  cudaError_t err;
  PADDLE_ASSERT(index == 1);

C
chengduoZH 已提交
174 175
  PADDLE_ASSERT(cuda_pinnd_alloc_size_ >= size);
  cuda_pinnd_alloc_size_ -= size;
C
chengduoZH 已提交
176 177 178
  err = cudaFreeHost(p);

  // Purposefully allow cudaErrorCudartUnloading, because
C
chengduoZH 已提交
179
  // that is returned if you ever call cudaFreeHost after the
C
chengduoZH 已提交
180 181
  // driver has already shutdown. This happens only if the
  // process is terminating, in which case we don't care if
C
chengduoZH 已提交
182
  // cudaFreeHost succeeds.
C
chengduoZH 已提交
183 184 185 186 187
  if (err != cudaErrorCudartUnloading) {
    PADDLE_ENFORCE(err, "cudaFreeHost failed in GPUPinnedAllocator::Free.");
  }
}

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

L
Luo Tao 已提交
190
#endif
191 192 193 194

}  // namespace detail
}  // namespace memory
}  // namespace paddle