I want to get raw data of tensor and return an array, currently I’m doing like this:
...
torch::Tensor flatten_tensor = input.to(torch::kCPU).flatten();
tensorSizes = output.sizes();
*arrayProto.mutable_float_val() = {flatten_tensor.data_ptr<float>, flatten_tensor.data_ptr<float> + tensor_size};
...
torch::Tensor output = torch::empty(torch::IntArrayRef(tensorSizes), tensorOptions);
memcpy(output.data_ptr<float>(), arrayProto.float_val().data(), tensor_size*sizeof(float));
...
I’m not sure:
- Whether the tensor input.to(torch::kCPU) is contiguous in memory? (input may in cuda memory or cpu memory)
- If it’s contiguous, will the flatten_tensor return the right values of the tensor?
- Can I get the right value (same as input) in output? Is there any risk in my code ?
I tried some simple models and tensors by this and it works. But I’m worrying it’s not 100% work in any scenario.
Thank you very much!