Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Create a torch::Tensor from C/C++ array without using "from_blob(...)..."

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?

like image 600
iambr Avatar asked Dec 01 '22 09:12

iambr


2 Answers

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);
like image 169
JoshVarty Avatar answered Mar 08 '23 23:03

JoshVarty


I usually use:

torch::Tensor tharray = torch::tensor({1, 2, 3, 4, 5}, {torch::kFloat64});
like image 26
Sholto Armstrong Avatar answered Mar 09 '23 00:03

Sholto Armstrong