torch.backends.cudnn.deterministic 使用cuda保证每次结果一样
為什么使用相同的網絡結構,跑出來的效果完全不同,用的學習率,迭代次數,batch size 都是一樣?固定隨機數種子是非常重要的。但是如果你使用的是PyTorch等框架,還要看一下框架的種子是否固定了。還有,如果你用了cuda,別忘了cuda的隨機數種子。這里還需要用到torch.backends.cudnn.deterministic.
torch.backends.cudnn.deterministic是啥?顧名思義,將這個 flag 置為True的話,每次返回的卷積算法將是確定的,即默認算法。如果配合上設置 Torch 的隨機種子為固定值的話,應該可以保證每次運行網絡的時候相同輸入的輸出是固定的,代碼大致這樣
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
總結
以上是生活随笔為你收集整理的torch.backends.cudnn.deterministic 使用cuda保证每次结果一样的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 对列表去重并保持原来的顺序
- 下一篇: torch.nn.functional.