pytorch/caffe2/core/event_gpu_test.cc
Jerry Zhang 9f4bcdf075 caffe2::DeviceType -> at::DeviceType (#11254)
Summary:
Pull Request resolved: https://github.com/pytorch/pytorch/pull/11254
Previously we use DeviceType in caffe2.proto directly, but it's an `enum` and have implicit conversion to int, which does not have type safety, e.g. we have to explicitly check for a device type is valid in event.h:
```
template <int d>
struct EventCreateFunctionRegisterer {
  explicit EventCreateFunctionRegisterer(EventCreateFunction f) {
    static_assert(d < MaxDeviceTypes, "");
    Event::event_creator_[d] = f;
  }
};
```
at::DeviceType is an `enum class`, and it does not have implicit conversion to int, and provides better type safety guarantees. In this diff we have done the following refactor(taking CPU as an example):

    1. caffe2::DeviceType → caffe2::DeviceTypeProto
    2. caffe2::CPU → caffe2::PROTO_CPU
    3. caffe2::DeviceType = at::DeviceType
    4. caffe2::CPU = at::DeviceType::CPU

codemod -d caffe2/caffe2 --extensions h,cc,cpp 'device_type\(\), ' 'device_type(), PROTO_'
+ some manual changes

In short, after this diff, in c++, caffe2::CPU refers to the at::DeviceType::CPU and the old proto caffe2::CPU will be caffe2::PROTO_CPU.
In python side, we have a temporary workaround that alias `caffe2_pb2.CPU = caffe2_pb2.PROOT_CPU` to make the change easier to review and this will be removed later.

Reviewed By: ezyang

Differential Revision: D9545704

fbshipit-source-id: 461a28a4ca74e616d3ee183a607078a717fd38a7
2018-09-05 16:28:09 -07:00

50 lines
1.2 KiB
C++

#include <gtest/gtest.h>
#include "caffe2/core/context.h"
#include "caffe2/core/context_gpu.h"
#include "caffe2/core/event.h"
namespace caffe2 {
TEST(EventCUDATest, EventBasics) {
if (!HasCudaGPU())
return;
DeviceOption device_cpu;
device_cpu.set_device_type(PROTO_CPU);
DeviceOption device_cuda;
device_cuda.set_device_type(PROTO_CUDA);
CPUContext context_cpu(device_cpu);
CUDAContext context_cuda(device_cuda);
Event event_cpu(device_cpu);
Event event_cuda(device_cuda);
// CPU context and event interactions
context_cpu.Record(&event_cpu);
event_cpu.SetFinished();
event_cpu.Finish();
context_cpu.WaitEvent(event_cpu);
event_cpu.Reset();
event_cpu.Record(CPU, &context_cpu);
event_cpu.SetFinished();
event_cpu.Wait(CPU, &context_cpu);
// CUDA context and event interactions
context_cuda.SwitchToDevice();
context_cuda.Record(&event_cuda);
context_cuda.WaitEvent(event_cuda);
event_cuda.Finish();
event_cuda.Reset();
event_cuda.Record(CUDA, &context_cuda);
event_cuda.Wait(CUDA, &context_cuda);
// CPU context waiting for CUDA event
context_cpu.WaitEvent(event_cuda);
// CUDA context waiting for CPU event
context_cuda.WaitEvent(event_cpu);
}
} // namespace caffe2