简体   繁体   English

在 libtorch C++ 的 while 循环内创建和销毁张量

[英]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:我刚开始使用 libtorch,我在使用 while 循环和张量时遇到了一些问题:roll_eyes:所以,我的主要功能如下所示:

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 > 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;
randn_tensor_size--;
  }

  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 I can access it again in the whileloop.本质上,我想做的是在 while 循环中重新创建张量,并确保我可以在 while 循环中再次访问它。

Interestingly, it seems to have cerated the tensor of reduced size but the while loop does not seem to recognise this.有趣的是,它似乎已经证明了尺寸减小的张量,但 while 循环似乎没有认识到这一点。

Thank you!谢谢!

You have a shadowing issue here, try the loop that way:你在这里有一个阴影问题,尝试这样循环:

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

Maybe, the reset of the tensor isn't necessary further on, depends of the internals of this class.也许,张量的重置不再需要,取决于这个 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.不影响你的柜台。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM