Luk*_*ron 2 machine-learning pytorch autograd
with torch.no_grad():
input = Variable(input).cuda()
target = Variable(target).cuda(non_blocking=True)
y=model(input)
# many things here
Run Code Online (Sandbox Code Playgroud)
no_grad 是否继续在“with”范围之外生效?
在no_grad有外“同向”的范围没有任何影响。
根据这一答案从上pytorch博客版主:
with torch.no_grad():
# No gradients in this block
x = self.cnn(x)
# Gradients as usual outside of it
x = self.lstm(x)
Run Code Online (Sandbox Code Playgroud)
这是withpython中语句的目的。with(here torch.no_grad())使用的变量仅在with上下文中有效,而在之后无效。有关完整的详细信息,请参阅python 文档。