【Pytorch】中不可复现的问题
最近遇到一个非常棘手的BUG,即使设定好了随机种子,但CNN模型,即包含Conv2d/Conv1d操作的模型仍不可复现。
查阅资料,问题出在这,如果:
cudnn.benchmark = True # if benchmark=True, deterministic will be False
cudnn.deterministic = False
- cudnn.benchmark = True,该值默认为True,为True,cuDNN就会使用非确定性算法就会自动寻找最适合当前配置的高效算法,来达到优化运行效率的问题。
- cudnn.deterministic = False ,若benchmark=True,那么deterministic=False,因此默认为False,这意味着卷积算法是可变的,每次运行CNN模型都会有不同的卷积算法,得到的结果自然就不同了。
因此为了保证每次结果都能复现,我们可以设置随机种子函数:
def set_seed(seed):
random.seed(seed) #random函数的随机种子
np.random.seed(seed) #np.random函数的随机种子
torch.manual_seed(seed) #pytorch的随机种子
cudnn.benchmark = False # if benchmark=True, deterministic will be False
cudnn.deterministic = True # 固定卷积算法
if torch.cuda.is_available() > 0:
torch.cuda.manual_seed_all(seed)#pytorch.cuda的随机种子