system_allocator.h 2.0 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
Y
Yi Wang 已提交
18

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

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

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

44
#ifdef PADDLE_WITH_CUDA
45 46
class GPUAllocator : public SystemAllocator {
 public:
C
chengduoZH 已提交
47 48
  explicit GPUAllocator(int gpu_id) : gpu_id_(gpu_id) {}

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

L
liaogang 已提交
53
 private:
54 55
  size_t gpu_alloc_size_ = 0;
  size_t fallback_alloc_size_ = 0;
C
chengduoZH 已提交
56
  int gpu_id_;
57
};
C
chengduoZH 已提交
58 59 60

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

 private:
C
chengduoZH 已提交
66
  size_t cuda_pinnd_alloc_size_ = 0;
C
chengduoZH 已提交
67
};
L
Luo Tao 已提交
68
#endif
L
liaogang 已提交
69 70 71 72

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