torch.no_grad() 影响模型精度

Kha*_*lam 3 python model image-compression torch pytorch

我收到错误“CUDA 内存不足”,然后我将 torch.no_grad() 函数添加到我的代码中。这会影响我的准确性吗?

for iters in range(args.iterations):

with torch.no_grad():
    encoded, encoder_h_1, encoder_h_2, encoder_h_3 = encoder(
    res, encoder_h_1, encoder_h_2, encoder_h_3)

with torch.no_grad():
    code = binarizer(encoded)

with torch.no_grad():
    output, decoder_h_1, decoder_h_2, decoder_h_3, decoder_h_4 = decoder(
    code, decoder_h_1, decoder_h_2, decoder_h_3, decoder_h_4)

res = res - output.detach()
codes.append(code.data.cpu().numpy())
torch.cuda.empty_cache()
print('Iter: {:02d}; Loss: {:.06f}'.format(iters, res.data.abs().mean()))
Run Code Online (Sandbox Code Playgroud)

Nop*_*eos 5

torch.no_grad()只是禁用跟踪稍后计算梯度所需的任何计算。

它不会对纯推理模式的准确性产生任何影响,因为那里不需要梯度。当然,您不能在训练期间使用它,因为我们需要梯度来训练和优化。

一般来说,如果您进行推理,您总是希望将网络设置为评估模式并禁用梯度。这节省了运行时间和内存消耗,并且不会影响准确性。

回答类似的问题,解释eval()no_grad() https://discuss.pytorch.org/t/model-eval-vs-with-torch-no-grad/19615/2