1 #ifndef CAFFE2_CORE_CONTEXT_H_ 2 #define CAFFE2_CORE_CONTEXT_H_ 7 #include <unordered_map> 9 #include "caffe2/core/allocator.h" 10 #include "caffe2/core/event.h" 11 #include "caffe2/core/logging.h" 12 #include "caffe2/core/typeid.h" 13 #include "caffe2/proto/caffe2.pb.h" 15 CAFFE2_DECLARE_bool(caffe2_report_cpu_memory_usage);
68 typedef std::mt19937 rand_gen_type;
70 explicit CPUContext(
const DeviceOption& option)
72 option.has_random_seed() ? option.random_seed()
74 CAFFE_ENFORCE_EQ(option.device_type(), CPU);
79 inline void SwitchToDevice(
int ) {}
80 inline void SwitchToDevice() {
84 inline void WaitEvent(
const Event& ev) {
88 inline void Record(
Event* ev,
const char* err_msg =
nullptr)
const {
89 CAFFE_ENFORCE(ev,
"Event must not be null.");
90 ev->Record(CPU,
this, err_msg);
93 inline void FinishDeviceComputation() {}
95 inline rand_gen_type& RandGenerator() {
96 if (!random_generator_.get()) {
97 random_generator_.reset(
new rand_gen_type(random_seed_));
99 return *random_generator_.get();
102 static std::pair<void*, MemoryDeleter> New(
size_t nbytes) {
103 auto data_and_deleter = GetCPUAllocator()->New(nbytes);
104 if (FLAGS_caffe2_report_cpu_memory_usage) {
105 reporter_.New(data_and_deleter.first, nbytes);
106 data_and_deleter.second = ReportAndDelete;
108 return data_and_deleter;
112 template <
class SrcContext,
class DstContext>
113 inline void CopyBytes(
size_t nbytes,
const void* src,
void* dst);
115 template <
typename T,
class SrcContext,
class DstContext>
116 inline void Copy(
size_t n,
const T* src, T* dst) {
117 if (std::is_fundamental<T>::value) {
118 CopyBytes<SrcContext, DstContext>(
120 static_cast<const void*>(src),
121 static_cast<void*
>(dst));
123 for (
int i = 0; i < n; ++i) {
129 template <
class SrcContext,
class DstContext>
131 CopyItems(
const TypeMeta& meta,
size_t n,
const void* src,
void* dst) {
133 meta.
copy()(src, dst, n);
135 CopyBytes<SrcContext, DstContext>(n * meta.
itemsize(), src, dst);
140 static bool HasAsyncPartDefault() {
144 static bool SupportsAsyncScheduling() {
150 static bool IsStreamFree(
const DeviceOption& ,
int ) {
156 int random_seed_{1701};
157 std::unique_ptr<rand_gen_type> random_generator_;
161 static void ReportAndDelete(
void* ptr) {
162 reporter_.Delete(ptr);
163 GetCPUAllocator()->GetDeleter()(ptr);
168 inline void CPUContext::CopyBytes<CPUContext, CPUContext>(
169 size_t nbytes,
const void* src,
void* dst) {
175 memcpy(dst, src, nbytes);
180 #endif // CAFFE2_CORE_CONTEXT_H_ The CPU Context, representing the bare minimum of what a Context class in Caffe2 should implement...
A global dictionary that holds information about what Caffe2 modules have been loaded in the current ...
uint32_t RandomNumberSeed()
A function to generate a random number seed that is unique in a best-effort basis, using an ever-incrementing seed and the current time.