文|Seraph
01 | 知识点
- torcht.is_tensor(a) 判断是否为张量
- Pytorch GPU环境是否正常测试代码:
import torch
flag = torch.cuda.is_available()
print(flag)
ngpu= 1
# Decide which device we want to run on
device = torch.device("cuda:0" if (torch.cuda.is_available() and ngpu > 0) else "cpu")
print(device)
print(torch.cuda.get_device_name(0))
print(torch.rand(3,3).cuda())
- cuDNN使用非确定算法设置
torch.backends.cudnn.enabled = False
可以关闭。
当设置
torch.backends.cudnn.enabled = true
torch.backends.cudnn.benchmark = true
cuDNN使用的非确定性算法就会自动寻找最适合当前配置的高效算法,来达到优化运行效率的问题。
适用场景是网络结构固定、输入形状不变的情况。如卷积层的设置一直变化,会导致程序不断再优化,从而耗费更多的时间。
- torch.manual_seed(args.seed) #为CPU设置种子用于生成随机数
torch.cuda.manual_seed(args.seed)#为当前GPU设置随机种子;如果使用多个GPU,应该使用torch.cuda.manual_seed_all()为所有的GPU设置种子。
之所以设置种子,是因为可以复现结果。
99 | 问题解决
- 执行
loss.data[0]
报错:IndexError: invalid index of a 0-dim tensor. Use tensor.item() to convert a 0-dim tensor to a Python number
。
解决:将loss.data[0]
换成loss.item()
。 - 使用
DistributedSampler()
后再Dataloader()
参数中加入了shuffle=True
报错:Dataloader BUG ValueError: sampler option is mutually exclusive with shuffle
。
解决:去掉该参数。因为torch.utils.data.distributed.DistributedSampler
是默认使用shuffle=True
的,所以不能多次使用。 - Expected object of scalar type Float but got scalar type Long for argument #2 ‘target’
解决:将target类型转换为float:
target = target.float()