ValueError: Cannot assign non-leaf Tensor to parameter ‘weight‘

问题:

在运行YOLOV7 时,出现下面错误:在解决过程中找了很多资料,但是都没有确切的答案~~~~行吧,自己解决**

  File "/usr/local/anaconda3/envs/coat/lib/python3.8/site-packages/torch/nn/modules/module.py", line 727, in _call_impl
    result = self.forward(*input, **kwargs)
  File "/usr/local/anaconda3/envs/coat/lib/python3.8/site-packages/torch/nn/parallel/data_parallel.py", line 160, in forward
    replicas = self.replicate(self.module, self.device_ids[:len(inputs)])
  File "/usr/local/anaconda3/envs/coat/lib/python3.8/site-packages/torch/nn/parallel/data_parallel.py", line 165, in replicate
    return replicate(module, device_ids, not torch.is_grad_enabled())
  File "/usr/local/anaconda3/envs/coat/lib/python3.8/site-packages/torch/nn/parallel/replicate.py", line 146, in replicate
    setattr(replica, key, param)
  File "/usr/local/anaconda3/envs/coat/lib/python3.8/site-packages/torch/nn/modules/module.py", line 796, in __setattr__
    self.register_parameter(name, value)
  File "/usr/local/anaconda3/envs/coat/lib/python3.8/site-packages/torch/nn/modules/module.py", line 325, in register_parameter
    raise ValueError(
ValueError: Cannot assign non-leaf Tensor to parameter 'weight'. Model parameters must be created explicitly. To express 'weight' as a function of another Tensor, compute the value in the forward() method.

分析原因

根据报错代码段发现报错的地方是在nn.Module中,找到

 **def register_parameter(self, name: str, param: Optional[Parameter]) -> None:**
函数中的报错代码:
        elif param.grad_fn:
            raise ValueError(
                "Cannot assign non-leaf Tensor to parameter '{0}'. Model "
                "parameters must be created explicitly. To express '{0}' "
                "as a function of another Tensor, compute the value in "
                "the forward() method.".format(name))

通过分析,笔者分析是在模型计算图片的时候进行了反向传播,很明显这是不对的,推理阶段是不会进行反向传播的,所以笔者分析:是不是因为用的服务器,有两张显卡,但是一张图片的计算是在一张显卡上计算的,导致另外一张显卡空闲,进行了反向传播?这个原因只是猜测,毕竟博主能力有限。

                                                   ****(希望佬们能够给些建议)****

解决方法

既然笔者觉得不能用显卡计算,那就直接把cuda关掉,用CPU进行推理!

Input image filename:/home/zkd/yolov7-pytorch/img/street.jpg
b'bicycle 0.82' 708 779 1026 1259
b'car 0.74' 595 649 767 968
b'person 0.76' 550 74 927 223
b'person 0.71' 504 891 961 1159
b'person 0.70' 521 471 861 638
<PIL.JpegImagePlugin.JpegImageFile image mode=RGB size=1330x1330 at 0x7F368899F6D0>

成功输出!!

你可能感兴趣的:(python,深度学习,机器学习)