Caffe2 - C++ API
A deep learning, cross platform ML framework
allocator.h
1 #ifndef CAFFE2_CORE_ALLOCATOR_H_
2 #define CAFFE2_CORE_ALLOCATOR_H_
3 
4 #include <unordered_map>
5 
6 #include "caffe2/core/logging.h"
7 #include "caffe2/core/numa.h"
8 
9 CAFFE2_DECLARE_bool(caffe2_report_cpu_memory_usage);
10 CAFFE2_DECLARE_bool(caffe2_cpu_allocator_do_zero_fill);
11 
12 namespace caffe2 {
13 
14 // Use 32-byte alignment should be enough for computation up to AVX512.
15 constexpr size_t gCaffe2Alignment = 32;
16 
17 using MemoryDeleter = void (*)(void*);
18 
19 // A helper function that is basically doing nothing.
20 void NoDelete(void*);
21 
22 // A virtual allocator class to do memory allocation and deallocation.
23 struct CPUAllocator {
24  CPUAllocator() {}
25  virtual ~CPUAllocator() noexcept {}
26  virtual std::pair<void*, MemoryDeleter> New(size_t nbytes) = 0;
27  virtual MemoryDeleter GetDeleter() = 0;
28 };
29 
30 // A virtual struct that is used to report Caffe2's memory allocation and
31 // deallocation status
33  public:
34  MemoryAllocationReporter() : allocated_(0) {}
35  void New(void* ptr, size_t nbytes);
36  void Delete(void* ptr);
37 
38  private:
39  std::mutex mutex_;
40  std::unordered_map<void*, size_t> size_table_;
41  size_t allocated_;
42 };
43 
46  ~DefaultCPUAllocator() override {}
47  std::pair<void*, MemoryDeleter> New(size_t nbytes) override {
48  void* data = nullptr;
49 #ifdef __ANDROID__
50  data = memalign(gCaffe2Alignment, nbytes);
51 #elif defined(_MSC_VER)
52  data = _aligned_malloc(nbytes, gCaffe2Alignment);
53 #else
54  CAFFE_ENFORCE_EQ(posix_memalign(&data, gCaffe2Alignment, nbytes), 0);
55 #endif
56  CAFFE_ENFORCE(data);
57  // move data to a thread's NUMA node
58  NUMAMove(data, nbytes, GetCurrentNUMANode());
59  if (FLAGS_caffe2_cpu_allocator_do_zero_fill) {
60  memset(data, 0, nbytes);
61  }
62  return {data, Delete};
63  }
64 
65 #ifdef _MSC_VER
66  static void Delete(void* data) {
67  _aligned_free(data);
68  }
69 #else
70  static void Delete(void* data) {
71  free(data);
72  }
73 #endif
74 
75  MemoryDeleter GetDeleter() override {
76  return Delete;
77  }
78 };
79 
80 // Get the CPU Alloctor.
81 CPUAllocator* GetCPUAllocator();
82 // Sets the CPU allocator to the given allocator: the caller gives away the
83 // ownership of the pointer.
84 void SetCPUAllocator(CPUAllocator* alloc);
85 
86 } // namespace caffe2
87 
88 #endif // CAFFE2_CORE_ALLOCATOR_H_
A global dictionary that holds information about what Caffe2 modules have been loaded in the current ...