Pytorch转ONNX报错-Cannot insert a Tensor that requires grad as a constant
pytorch模型转换onnx的时候,遇到了下面的报错信息:
1 | RuntimeError: Cannot insert a Tensor that requires grad as a constant. Consider making it a parameter or input, or detaching the gradient |
翻译过来就是不能将一个需要梯度的tensor转换为constant。
定位到报错的层,是一个Conv2D,看起来是它对应的weight设置了requires_grad为True。本以为直接修改requires_grad = False 就可以了,但比较诡异的是,实际试下来并不行。
具体来说,尝试了下面的方案,都不work:
- 给forward 函数增加torch.inference_mode() 装饰符
- 在报错的层前面加torch.no_grad() context
- 给输入增加.detach() 函数,去掉梯度
- 给层对应的weight设置requires_grad 为False
最后还是在网上发现了解决方案,尝试之后是work的。具体来说,就是将对应模型的所有层的参数都设置为requires_grad = False
:
1 | for param in model.parameters(): |
大功告成。