1 #ifndef CAFFE2_OPERATORS_PREFETCH_OP_H_ 2 #define CAFFE2_OPERATORS_PREFETCH_OP_H_ 4 #include <condition_variable> 8 #include "caffe2/core/context.h" 9 #include "caffe2/core/operator.h" 25 template <
class Context>
30 context_(operator_def.device_option()),
32 prefetch_success_(
true),
34 no_prefetch_(GetSingleArgument<bool>(
"no_prefetch",
false)) {
35 context_.SwitchToDevice();
39 CHECK(finalize_ || !prefetch_thread_.get()) <<
40 "YOU MADE A PROGRAMING ERROR: derived class of PrefetchOperator " 41 "should call Finalize() in its destructor so the prefetching " 46 if (prefetch_thread_.get()) {
48 std::unique_lock<std::mutex> lock(prefetch_access_mutex_);
54 producer_.notify_one();
55 prefetch_thread_->join();
56 prefetch_thread_.reset();
64 bool Run(
int )
override {
66 context_.SwitchToDevice();
67 bool result = Prefetch() && CopyPrefetched();
68 context_.FinishDeviceComputation();
74 if (!prefetch_thread_) {
75 prefetch_thread_.reset(
76 new std::thread([
this] { this->PrefetchWorker(); }));
78 context_.SwitchToDevice();
79 std::unique_lock<std::mutex> lock(prefetch_access_mutex_);
82 if (!prefetch_success_) {
83 LOG(ERROR) <<
"Prefetching failed.";
86 if (!CopyPrefetched()) {
87 LOG(ERROR) <<
"Error when copying prefetched data.";
91 context_.FinishDeviceComputation();
92 producer_.notify_one();
96 void PrefetchWorker() {
97 context_.SwitchToDevice();
98 std::unique_lock<std::mutex> lock(prefetch_access_mutex_);
100 producer_.wait(lock);
106 prefetch_success_ = Prefetch();
107 context_.FinishDeviceComputation();
108 }
catch (
const std::exception& e) {
110 LOG(ERROR) <<
"Prefetching error " << e.what();
111 prefetch_success_ =
false;
114 consumer_.notify_one();
116 producer_.wait(lock);
121 virtual bool Prefetch() = 0;
122 virtual bool CopyPrefetched() = 0;
126 std::mutex prefetch_access_mutex_;
127 std::condition_variable producer_, consumer_;
129 std::atomic<bool> prefetched_;
131 std::atomic<bool> prefetch_success_;
133 std::atomic<bool> finalize_;
134 unique_ptr<std::thread> prefetch_thread_;
137 const bool no_prefetch_;
142 #endif // CAFFE2_OPERATORS_PREFETCH_OP_H_ Workspace is a class that holds all the related objects created during runtime: (1) all blobs...
A global dictionary that holds information about what Caffe2 modules have been loaded in the current ...