Can I initialize tensor from std::vector in libtorch?

Hi,

I wonder if I can initialize torch::Tensor from std::vector like this

#include <torch/torch.h>
#include <vector>

int main()
{
  std::vector<T> initializer;
  ...
  torch::Tensor tensor = torch::from_blob(initializer);
}
2 Likes

I used torch::tensor(ArrayRef<float>) successfully.
I’m not 100% certain whether that copies already. You might have to take care of ownership or clone the output while the array ref is still alive, I think you have to do that when you use form_blob, too.

Best regards

Thomas

2 Likes

Thank you Tomas!

I’ll try that.

torch::tensor makes a copy, from_blob does not (but torch::from_blob(vector).clone() does)

5 Likes