Save LibTorch tensor to flattened 1D C array

I want to save a 3D LibTorch complex-tensor (kComplexDouble) to a 1D C complex-array (``std::complex) in a C++ program.

The 3D tensor is shape (N_rs, N_thetas, N_phis).

The 1D C array has length N_rs * N_thetas * N_phis and is declared as: std::complex<double> * Psi_spec = new std::complex<double> [N_rs * N_thetas * N_phis];

The 3D tensor is Psi_spec_Tor. The 1D C array is Psi_spec.

At the moment, I am doing:

Psi_spec_Tor = Psi_spec_Tor.view( Psi_spec_Tor.sizes()[0] * Psi_spec_Tor.sizes()[1] * Psi_spec_Tor.sizes()[2] );
Psi_spec_Tor = Psi_spec_Tor.contiguous();
Psi_spec_Tor = Psi_spec_Tor.cpu();
std::memcpy( Psi_spec, Psi_spec_Tor.data_ptr(), sizeof(std::complex<double>) * Psi_spec_Tor.numel() );

Then I index Psi_spec as if it was a 3D tensor, using idx = i * (N_thetas * N_phis) + j * N_phis + k, where the usual 3D tensor would be indexed [i][j][k].

Is the above correct?

Or shall I do the .contiguous before the .view?

Thank you!

It looks like you are just flattening the tensor without changing the order of the data (e.g., by reordering the axes)?

In this case the .contiguous() call would be unnecessary, and you can verify this by checking Psi_spec_Tor.is_contiguous() before the call.

If the .contiguous() call is verified to be unnecessary, then the view is also unnecessary, as data lives in memory in this flattened order already.

1 Like