torch.backends.cudnn.deterministic 使用cuda保证每次结果一样
為什么使用相同的網(wǎng)絡(luò)結(jié)構(gòu),跑出來的效果完全不同,用的學(xué)習(xí)率,迭代次數(shù),batch size 都是一樣?固定隨機(jī)數(shù)種子是非常重要的。但是如果你使用的是PyTorch等框架,還要看一下框架的種子是否固定了。還有,如果你用了cuda,別忘了cuda的隨機(jī)數(shù)種子。這里還需要用到torch.backends.cudnn.deterministic.
torch.backends.cudnn.deterministic是啥?顧名思義,將這個(gè) flag 置為True的話,每次返回的卷積算法將是確定的,即默認(rèn)算法。如果配合上設(shè)置 Torch 的隨機(jī)種子為固定值的話,應(yīng)該可以保證每次運(yùn)行網(wǎng)絡(luò)的時(shí)候相同輸入的輸出是固定的,代碼大致這樣
def init_seeds(seed=0):
torch.manual_seed(seed) # sets the seed for generating random numbers.
torch.cuda.manual_seed(seed) # Sets the seed for generating random numbers for the current GPU. It’s safe to call this function if CUDA is not available; in that case, it is silently ignored.
torch.cuda.manual_seed_all(seed) # Sets the seed for generating random numbers on all GPUs. It’s safe to call this function if CUDA is not available; in that case, it is silently ignored.
if seed == 0:torch.backends.cudnn.deterministic = Truetorch.backends.cudnn.benchmark = False
總結(jié)
以上是生活随笔為你收集整理的torch.backends.cudnn.deterministic 使用cuda保证每次结果一样的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 对列表去重并保持原来的顺序
- 下一篇: torch.nn.functional.