vendredi 26 février 2021

Tensor creation and destruction within a while loop in libtorch C++

I have just started with libtorch and I am having some trouble with while loops and tensors :roll_eyes: So, my main func looks like so:

int main()
{

  auto tensor_create_options = torch::TensorOptions().dtype(torch::kFloat32).device(torch::kCPU).requires_grad(false);
  torch::Tensor randn_tensor = torch::randn({10}, tensor_create_options);

  while (randn_tensor.sizes()[0] > 5)
  {
    std::cout << "==> randn_tensor shape: " << randn_tensor.sizes() << std::endl;
    randn_tensor.reset(); //reset();
    torch::Tensor randn_tensor = torch::randn({3}, tensor_create_options);
    std::cout << "==> randn_tensor shape 3: " << randn_tensor.sizes() << std::endl;

  }

  return 0;
}

and I get thrown this:

==> randn_tensor shape: [10]
==> randn_tensor shape 3: [3]
terminate called after throwing an instance of 'c10::Error'
  what():  sizes() called on undefined Tensor

Essentially, what I want to do is recreate the tensor within the while loop and ensure that the sizes of this newly created tensor is reflected in the while(recreated_tensor_size SOME_CONDITION){}

Interestingly, it seems to have cerated the tensor of reduced size but the while loop does not seem to recognise this.

Thank you!

Aucun commentaire:

Enregistrer un commentaire