Pytorch中的随机种子分为CPU种子和GPU种子,分别使用
torch.manual_seed(seed)
torch.cuda.manual_seed(seed)
来设置。但是即使seed一样,两者的结果却完全不同。
例如,定义一个GPU上的张量x = torch.zeros((3, 4), device=torch.device("cuda"))
,那么相同的随机种子情况下,下面两个的输出是完全不一样的。
torch.randn(x.shape).to(x.device)
torch.randn_like(x)
因为前一句是在CPU使用随机数,再传到GPU上,而后者直接使用GPU随机数。两者虽然意思一样,但是结果完全不同。以后要注意。