在使用pytorch时,并不是所有的操作都需要进行计算图的生成(计算过程的构建,以便梯度反向传播等操作)。而对于tensor的计算操作,默认是要进行计算图的构建的,在这种情况下,可以使用 with torch.no_grad():,强制之后的内容不进行计算图构建。
下面针对是否使用torch.no_grad()做个实验。
1. 不使用torch.no_grad()
import torchx = torch.arange(4.0)
x.requires_grad_(True)
# 默认是要进行计算图的构建的
y = 2 * torch.dot(x, x)
y.backward()
x.grad
# 输出 tensor([ 0., 4., 8., 12.])
2. 使用torch.no_grad()
import torchx = torch.arange(4.0)
x.requires_grad_(True)
# 强制之后的内容不进行计算图构建
with torch.no_grad
y = 2 * torch.dot(x, x)y.backward()
# 报错 RuntimeError: element 0 of tensors does not require grad and does not have a grad_fn
参考资料
- https://blog.csdn.net/weixin_44134757/article/details/105775027;
- https://zh-v2.d2l.ai/chapter_preliminaries/autograd.html;