我连续两次在相同的输入上调用相同的模型,但没有得到相同的结果,这个模型有 nn.GRU 层,所以我怀疑它有一些内部状态应该是在第二次运行之前发布?
如何重置 RNN 隐藏状态以使其与模型最初加载时相同?
更新:
一些背景:
我正在尝试从这里运行模型:
https://github.com/erogol/WaveRNN/blob/master/models/wavernn.py#L93
我正在调用生成
:
https://github.com/erogol/WaveRNN/blob/master/models/wavernn.py#L148
这里实际上有一些使用 pytorch 中的随机生成器的代码:
https://github.com/erogol/WaveRNN/blob/master/models/wavernn.py#L200
https://github.com/erogol/WaveRNN/blob/master/utils/distribution.py#L110
https://github.com/erogol/WaveRNN/blob/master/utils/distribution.py#L129
我已经放置(我正在 CPU 上运行代码):
torch.manual_seed(0)
torch.cuda.manual_seed_all(0)
torch.backends.cudnn.deterministic = True
torch.backends.cudnn.benchmark = False
np.random.seed(0)
在
https://github.com/erogol/WaveRNN/blob/master/utils/distribution.py
在所有导入之后。
我检查了运行之间的 GRU 权重,它们是相同的:
https://github.com/erogol/WaveRNN/blob/master/models/wavernn.py#L153
此外,我还检查了运行之间的 logits
和 sample
,并且 logits
相同,但 sample
不同,所以@Andrew Naguib关于随机种子的说法似乎是正确的,但我不确定修复随机种子的代码应该放在哪里?
https://github.com/erogol/WaveRNN/blob/master/models/wavernn.py#L200
更新2:
我已将种子 init 放入 generate
中,现在结果是一致的:
https://github.com/erogol/WaveRNN/blob/master/models/wavernn.py#L148
最佳答案
我相信这可能与Random Seeding高度相关。为了确保可重复的结果( as stated by them ),您必须像这样播种 torch
:
import torch
torch.manual_seed(0)
还有 CuDNN
模块。
torch.backends.cudnn.deterministic = True
torch.backends.cudnn.benchmark = False
如果您使用numpy
,您也可以这样做:
import numpy as np
np.random.seed(0)
但是,他们警告您:
Deterministic mode can have a performance impact, depending on your model.
我经常使用的一个建议脚本,它可以很好地重现结果:
# imports
import numpy as np
import random
import torch
# ...
""" Set Random Seed """
if args.random_seed is not None:
"""Following seeding lines of code are to ensure reproducible results
Seeding the two pseudorandom number generators involved in PyTorch"""
random.seed(args.random_seed)
np.random.seed(args.random_seed)
torch.manual_seed(args.random_seed)
# https://pytorch.org/docs/master/notes/randomness.html#cudnn
if not args.cpu_only:
torch.cuda.manual_seed(args.random_seed)
cudnn.deterministic = True
cudnn.benchmark = False
关于pytorch - 如何在多次运行中重现 RNN 结果?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56190274/