Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to populate torch::tensor with c++ array?

This is very basic: I am normally using Eigen3 for my math operations, but need to use libtorch for a network forward pass. Now I want to populate the torch::tensor with the data from my Eigen3 (or pure C++ array), but without a for loop. How can I do this?

Here is the solution with a loop:

Eigen::Matrix<double, N, 1> inputEigen;  // previously initialized

torch::Tensor inputTorch = torch::ones({1, N});  // my torch tensor for the forward pass
for (int i = 0; i < N; i++) {
  inputTorch[0][i] = inputEigen[i];  // batch size == 1
}

std::vector<torch::jit::IValue> inputs;
inputs.push_back(inputTorch);
at::Tensor output = net.forward(inputs).toTensor();

This works fine for now, but N might become really large and I'm just looking for a way to directly set the underlying data of my torch::tensor with a previously used C++ array

like image 222
Dorian Avatar asked Oct 27 '25 02:10

Dorian


1 Answers

Libtorch provides the torch::from_blob function (see this thread), which asks for a void* pointer to some data and an IntArrayRef to know the dimensions of the interpreted data. So that would give something like:

Eigen::Matrix<double, N, 1> inputEigen; // previously initialized;
torch::Tensor inputElement = torch::from_blob(inputEigen.data(), {1,N}).clone();             // dims

Please note the call to clone which you may or may not need depending or your use case : basically from_blob does not take ownership of the underlying data, so without the clone it will remain shared with (and possibly destroyed by) your Eigen matrix

like image 144
trialNerror Avatar answered Oct 29 '25 17:10

trialNerror



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!