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


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);

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



Thank you Tomas!

I’ll try that.

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


Could you please point me to the documentation for the torch::tensor API? Thank you.

What do you want to achieve?

If you need examples on how to create tensor, here,there are examples in the tests:

C++ doc is here:

Thank you @glaringlee. I want to create a torch::Tensor on device from (preferably const) std::vector.
I got around by calling torch::from_blob and .clone(). Not sure if there is any more convenient way to do so.

The link you provided to GitHub is expired.
The C++ doc describes the usage of torch::Tensor class instead of the torch::tensor function.

That link works, the quote symbol is problematic, I fixed it.
But if you want to use from_blob, that’s not in tensor examples.
See this ‘
You can take a look how we use it.

A short example is like this:
Tensor out = torch::from_blob(vec.data_ptr(), {sizes},torch::Device(torch::kCUDA, 0).dtype(torch::kFloat32));

1 Like

Thank you @glaringlee.
BTW, I think you mean This returns a const pointer and is not compatible with the from_blob inputs.

Yes, data(), that’s sudo code, sry.
Did you check the example I send you?
You can cast the data() ptr to the type you need.

Thank you, @glaringlee . I see. You are essentially doing a C++ const_cast equivalent here.