完整报错信息如下
RuntimeError: set_sizes_and_strides is not allowed on a Tensor created from .data or .detach().
If your intent is to change the metadata of a Tensor (such as sizes / strides / storage / storage_offset)
without autograd tracking the change, remove the .data / .detach() call and wrap the change in a `with torch.no_grad():` block.
For example, change:
x.data.set_(y)
to:
with torch.no_grad():
x.set_(y)
报错的大意是用了一些操作后不能用.detach()或者.data,我的模型是生成对抗网络,在主函数中,报错部分对应的主要代码是
pre = model_g(img_tensor)
dis = model_d(pre.detach())
loss_d2_d = nn.BCELoss()(dis, torch.ones_like(dis))
我的生成器用到了.permute()和F.interpolate(),所以报错,神奇的是,我把F.interpolate()的参数scale_factor从8改为2后就没报错了,后面就没管,但改了网络后又报错,经过尝试,发现nn.Upsample()和nn.ConvTranspose2d()也会引起同样的报错,大概是这些操作的中间过程修改了size吧?具体的我也不懂。
后来发现解决这个问题其实很简单,两种方法都可以解决:
- 加个.clone()
修改后代码为
pre = model_g(img_tensor)
dis = model_d(pre.detach().clone())
loss_d2_d = nn.BCELoss()(dis, torch.ones_like(dis))
就不报错了!
- 加个.contiguous()
另外,我发现其实不用这个方法,其实最根本的是在生成器forward()函数中,permute和reshape操作后应该加个.contiguous(),即我的模型中那句代码由
x = x.permute(0, 2, 1).reshape((n, c*4, h//4, h//4))
改为:
x = x.permute(0, 2, 1).reshape((n, c*4, h//4, h//4)).contiguous()
然后不用.clone()了,正常地用pre.detach()就行了。
就也不报错了!
虽然问题解决了,不过报错的具体原因我也不是特别清楚,有人对这处错误有比较清楚的认识的话麻烦告诉我一下吧,感谢!(●’◡’●)