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);

  int randn_tensor_size = randn_tensor.sizes()[0];

  while (randn_tensor_size &gt; 5)
  {
    std::cout &lt;&lt; &quot;==&gt; randn_tensor shape: &quot; &lt;&lt; randn_tensor.sizes() &lt;&lt; std::endl;
    randn_tensor.reset(); //reset();
    torch::Tensor randn_tensor = torch::randn({3}, tensor_create_options);
    std::cout &lt;&lt; &quot;==&gt; randn_tensor shape 3: &quot; &lt;&lt; randn_tensor.sizes() &lt;&lt; std::endl;
randn_tensor_size--;
  }

  return 0;
}

and I get thrown this:
==&gt; randn_tensor shape: [10]
==&gt; 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 I can access it again in the whileloop.
Interestingly, it seems to have cerated the tensor of reduced size but the while loop does not seem to recognise this.
Thank you!

You have a shadowing issue here, try the loop that way:
while (randn_tensor_size &gt; 5)
{
    std::cout &lt;&lt; &quot;==&gt; randn_tensor shape: &quot; &lt;&lt; randn_tensor.sizes() &lt;&lt; std::endl;
    randn_tensor.reset(); //reset();
    randn_tensor = torch::randn({3}, tensor_create_options);
    std::cout &lt;&lt; &quot;==&gt; randn_tensor shape 3: &quot; &lt;&lt; randn_tensor.sizes() &lt;&lt; std::endl;
    randn_tensor_size--;
}

Maybe, the reset of the tensor isn't necessary further on, depends of the internals of this class. If that's not the actual intention of your code and you want only the original tensor to be deleted, then simply reset that one right before the loop. Indepently of this, try to make the code clearer in terms of intention emphasis! I do not really understand what you want to achieve exactly. Your loop counter is misued at all since you mix size and counting semantics, depending on the initial size only. Within the loop, you simply recreate the tensor on the stack again and again, not affecting your counter.
