system_allocator.h 2.1 KB
Newer Older
1
/* Copyright (c) 2016 PaddlePaddle Authors. All Rights Reserved.
L
liaogang 已提交
2 3 4 5 6 7 8 9 10 11 12 13 14 15 16

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

#pragma once

17
#include <stddef.h>  // for size_t
W
Wei Liu 已提交
18
#include <unordered_map>
Y
Yi Wang 已提交
19

L
liaogang 已提交
20 21 22 23
namespace paddle {
namespace memory {
namespace detail {

L
liaogang 已提交
24
/**
C
chengduoZH 已提交
25 26 27
 * \brief SystemAllocator is the parent class of CPUAllocator,
 *        CUDAPinnedAllocator and GPUAllocator. A BuddyAllocator
 *        object uses a SystemAllocator* pointing to the
L
liaogang 已提交
28 29
 *        underlying system allocator.
 */
30
class SystemAllocator {
31
 public:
32
  virtual ~SystemAllocator() {}
Y
Yi Wang 已提交
33
  virtual void* Alloc(size_t* index, size_t size) = 0;
L
liaogang 已提交
34
  virtual void Free(void* p, size_t size, size_t index) = 0;
L
liaogang 已提交
35
  virtual bool UseGpu() const = 0;
Y
Yi Wang 已提交
36 37
};

38
class CPUAllocator : public SystemAllocator {
39
 public:
Y
Yi Wang 已提交
40
  virtual void* Alloc(size_t* index, size_t size);
L
liaogang 已提交
41
  virtual void Free(void* p, size_t size, size_t index);
L
liaogang 已提交
42
  virtual bool UseGpu() const;
L
liaogang 已提交
43 44
};

45
#ifdef PADDLE_WITH_CUDA
46 47
class GPUAllocator : public SystemAllocator {
 public:
W
Wei Liu 已提交
48 49
  std::unordered_map<int, uint64_t> s_memoryMap;

C
chengduoZH 已提交
50 51
  explicit GPUAllocator(int gpu_id) : gpu_id_(gpu_id) {}

Y
Yi Wang 已提交
52
  virtual void* Alloc(size_t* index, size_t size);
L
liaogang 已提交
53
  virtual void Free(void* p, size_t size, size_t index);
L
liaogang 已提交
54
  virtual bool UseGpu() const;
L
liaogang 已提交
55

L
liaogang 已提交
56
 private:
57 58
  size_t gpu_alloc_size_ = 0;
  size_t fallback_alloc_size_ = 0;
C
chengduoZH 已提交
59
  int gpu_id_;
60
};
C
chengduoZH 已提交
61 62 63

class CUDAPinnedAllocator : public SystemAllocator {
 public:
Y
Yi Wang 已提交
64
  virtual void* Alloc(size_t* index, size_t size);
C
chengduoZH 已提交
65 66 67 68
  virtual void Free(void* p, size_t size, size_t index);
  virtual bool UseGpu() const;

 private:
C
chengduoZH 已提交
69
  size_t cuda_pinnd_alloc_size_ = 0;
C
chengduoZH 已提交
70
};
L
Luo Tao 已提交
71
#endif
L
liaogang 已提交
72 73 74 75

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