TensorOptions
See https://github.com/pytorch/pytorch/blob/master/c10/core/TensorOptions.h
Constructors (not recommended)
./code/tensor-options/main.cc (Not recommended constructors)
 1void TestConstructor() {
 2  // not recommended
 3  torch::TensorOptions opt1(torch::kCPU);
 4  torch::TensorOptions opt2(torch::Device(torch::kCPU));
 5  torch::TensorOptions opt3(torch::Device({torch::kCUDA, 1}));
 6  torch::TensorOptions opt4("cpu");
 7  // torch::TensorOptions opt5("CPU") // error;
 8  torch::TensorOptions opt6("cuda:1");
 9  // torch::TensorOptions opt7("CUDA:1"); // error
10
11  // not recommended, from a scalar type (implicit)
12  torch::TensorOptions opt8(torch::kInt32);
13}
Constructors (Recommended)
./code/tensor-options/main.cc (Recommended constructors)
 1void TestConstructor2() {
 2  // recommended
 3  torch::TensorOptions opt1 = torch::dtype(torch::kFloat);
 4  torch::TensorOptions opt2 = torch::dtype(caffe2::TypeMeta::Make<float>());
 5  torch::TensorOptions opt3 = torch::device(torch::kCPU);
 6  torch::TensorOptions opt4 = torch::device({torch::kCUDA, 1});
 7  // Note: torch::device() returns a TensorOptions
 8  // while torch::Device() is the constructor of a class
 9
10  torch::TensorOptions opt5 = torch::requires_grad(true);
11  std::cout << opt5 << "\n";
12  // TensorOptions(dtype=float (default), device=cpu (default), layout=Strided
13  // (default), requires_grad=true, pinned_memory=false (default),
14  // memory_format=(nullopt))
15
16  torch::TensorOptions opt6 = torch::dtype<float>();
17  std::cout << torch::toString(opt6) << "\n";
18  // TensorOptions(dtype=float, device=cpu (default), layout=Strided (default),
19  // requires_grad=false (default), pinned_memory=false (default),
20  // memory_format=(nullopt))
21
22  std::cout << "default:" << torch::TensorOptions() << "\n";
23  // default:TensorOptions(dtype=float (default), device=cpu (default),
24  // layout=Strided (default), requires_grad=false (default),
25  // pinned_memory=false (default), memory_format=(nullopt))
26}
Methods
./code/tensor-options/main.cc (Methods)
 1void TestMethods() {
 2  torch::TensorOptions opts = torch::dtype<float>();
 3  TORCH_CHECK(opts.device() == torch::Device(torch::kCPU));
 4  // It has not device_type()!
 5  TORCH_CHECK(opts.device() == torch::kCPU);
 6  TORCH_CHECK(opts.device().type() == torch::kCPU);
 7  TORCH_CHECK(opts.requires_grad() == false);
 8
 9  torch::TensorOptions opts2 =
10      opts.device("cuda:2").dtype(torch::kInt).requires_grad(false);
11
12  TORCH_CHECK(opts2.dtype() == caffe2::TypeMeta::Make<int32_t>());
13  TORCH_CHECK(opts2.dtype() == torch::kInt32);
14  TORCH_CHECK(opts2.requires_grad() == false);
15}