What I want is an elegant way of getting data from a 1D tensor to a C++ std::vector or array (don’t worry about gradient or anything, at that point it already doesn’t matter). I am considering creating a tensor using from_blob with a vector with size initialized (which makes the vector share memory with the tensor), then use in place operations (e.g. add_out) to compute the tensor. In this way, at the end the vector will be modified along with the tensor, which effectively pass the computation result out.
The problem is, now I don’t actually want to modify the implementation of how the result is computed, because it is used in different occasions, many of which does not need to have the result being converted to C++ data types, and the computation is complicated. So my idea is to just use a step that copies the data from my original computation to the tensor I created using from_blob with the vector, and in an in-place fashion.
It should be approximately like the following except this I tested wouldn’t work, because regular assignment is not in-place, i.e. it’ll change the memory location of the underlying data storage thus not actually assigning it to the vector
torch::Tensor result = foo(); // a complicated computation function, parameters omitted
std::vector<double> v(100);
torch::Tensor result_copy = from_blob(v.data(), {100}, torch::kDouble);
result_copy = result; // does not work as it is not in-place
so what I really want is something that achieve the semantics of assigning or copying the values in a tensor to another tensor but without changing the memory location of the data for the destination tensor
torch::Tensor result = foo(); // a complicated computation function, parameters omitted
std::vector<double> v(100);
torch::Tensor result_copy = from_blob(v.data(), {100}, torch::kDouble);
copy_out(result_copy, result); // this function doesn't actually exist, or it is called a different name I don't know
So I want to ask does such “copy_out” function exist, or I have to do some other things like use add_out to add to a zero tensor, or take_out to take values according to indices to get around (sounds not elegant)? Or maybe there are other better solutions to transfer data from a tensor to std::vector?
Thanks,