Using the C++ libtorch frontend for Pytorch
I want to create a torch::Tensor
from a C++ double[]
array. Comming from a legacy C/C++ API.
I could not find a simple documentation about the subject not in docs nor in the forums.
Something like:
double array[5] = {1, 2, 3, 4, 5}; // or double *array;
auto tharray = torch::Tensor(array, 5, torch::Device(torch::kCUDA));
The only thing I found is to use torch::from_blob
but then I would have to clone()
and use to(device)
if I wanted to use it with CUDA.
double array[] = { 1, 2, 3, 4, 5};. // or double *array;
auto options = torch::TensorOptions().dtype(torch::kFloat64);
torch::Tensor tharray = torch::from_blob(array, {5}, options);
Is there any cleaner way of doing so?
You can read more about tensor creation here: https://pytorch.org/cppdocs/notes/tensor_creation.html
I don't know of any way to create a tensor from an array without using from_blob
but you can use TensorOptions
to control various things about the tensor including its device.
Based on your example you could create your tensor on the GPU as follows:
double array[] = { 1, 2, 3, 4, 5};
auto options = torch::TensorOptions().dtype(torch::kFloat64).device(torch::kCUDA, 1);
torch::Tensor tharray = torch::from_blob(array, {5}, options);
I usually use:
torch::Tensor tharray = torch::tensor({1, 2, 3, 4, 5}, {torch::kFloat64});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With