Dorian
Dorian

Reputation: 1488

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

Upvotes: 4

Views: 4889

Answers (1)

trialNerror
trialNerror

Reputation: 3553

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

Upvotes: 6

Related Questions