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

问题描述

我刚刚开始使用 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;
}

然后我被抛出这个:

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

本质上,我想做的是在 while 循环中重新创建张量,并确保我可以在 while 循环中再次访问它。

有趣的是,它似乎已将尺寸减小的张量放大,但 while 循环似乎没有识别出这一点。

谢谢!

解决方法

您在这里遇到了阴影问题,请以这种方式尝试循环:

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

也许,不需要进一步重置张量,这取决于此类的内部结构。如果这不是您的代码的实际意图,并且您只想删除原始张量,那么只需在循环之前重置那个张量。独立于这一点,尝试在意图强调方面使代码更清晰!我真的不明白你到底想达到什么目的。您的循环计数器完全被误用了,因为您混合了大小和计数语义,仅取决于初始大小。在循环中,您只需一次又一次地在堆栈上重新创建张量,而不会影响您的计数器。