Torch常用库和相关问题解决

Out Of Memory

  1. 调整BatchSize为$2^n$,一般为4
  2. 清除无用缓存
import torch, gc

gc.collect()
torch.cuda.empty_cache()
  1. test和eval阶段加入with torch.no_grad()
  2. 使用别人代码时如果有kwargs = {'num_workers': 6, 'pin_memory': True} if torch.cuda.is_available() else {}就去掉,这里pin_memory可以提高速度但是占用更多内存
  3. 环境变量加入export PYTORCH_CUDA_ALLOC_CONF=max_split_size_mb:32

Torch和其它数据类型的转换

torch.from_numpy

torch.item()将数字Tensor转化成Python变量类型

参考

https://blog.csdn.net/m0_50502579/article/details/126059178