How to convert at::tensor to std::vector<float>


I was not able to convert at:tensor t to std::vector v. What I used:

std::vector<float> v(<float>(),<float>() + t.numel());

Is there any way to do that?



Make your tensor contiguous. Then try this:
std::vector v(t.data_ptr(), t.data_ptr() + t.numel());

Thanks for reply! I added

t = t.contiguous();

but still doesn’t work.

@jinchen62 Did you fill the float as the template type? like this?
std::vector v(t.data_ptr(), t.data_ptr() + t.numel())
Can you paste the error message here? I did not try on my computer, but this should work.

@glaringlee I think you need to add “\” before “<” to print the type. I ran

t = t.contiguous();
std::vector<float> v(t.data_ptr<float>(), t.data_ptr<float>() + t.numel());

Is it what you are saying?
Actually there is no error, it just get stuck at this point, even I’ve waited for a long time.

1 Like

@jinchen62 oh, crab…sry…I did not realize the type is not get printed out.

torch::Tensor ten = torch::rand({12, 12}, torch::TensorOptions(torch::kCPU).dtype(at::kFloat)); 
std::vector<float> v(ten.data_ptr<float>(), ten.data_ptr<float>() + ten.numel());
for (auto a : v) std::cout << a << std::endl;

This works for me. You have to ensure the tensor type and vector type are the same.


@glaringlee I’ve figured it out. The problem is my tensors are in cuda device, transfer to cpu fixs the problem.
Thanks a lot!

1 Like