pytorch的顯示記憶體機制torch.cuda.empty_cache()

  • 2020 年 2 月 14 日
  • 筆記

Pytorch 訓練時有時候會因為載入的東西過多而爆顯示記憶體,有些時候這種情況還可以使用cuda的清理技術進行修整,當然如果模型實在太大,那也沒辦法。使用torch.cuda.empty_cache()刪除一些不需要的變數程式碼示例如下:

try:    output = model(input)    except RuntimeError as exception:    if "out of memory" in str(exception):    print("WARNING: out of memory")    if hasattr(torch.cuda, 'empty_cache'):    torch.cuda.empty_cache()    else:    raise exception

測試的時候爆顯示記憶體有可能是忘記設置no_grad, 示例程式碼如下:

with torch.no_grad():    for ii,(inputs,filelist) in tqdm(enumerate(test_loader), desc='predict'):    if opt.use_gpu:    inputs = inputs.cuda()    if len(inputs.shape) < 4:    inputs = inputs.unsqueeze(1)      else:    if len(inputs.shape) < 4:    inputs = torch.transpose(inputs, 1, 2)