def set_seed(seed = 42):
np.random.seed(seed)
random.seed(seed)
torch.manual_seed(seed)
torch.cuda.manual_seed(seed)
torch.backends.cudnn.deterministic = True
torch.backends.cudnn.benchmark = False
os.environ['PYTHONHASHSEED'] = str(seed)
random.random()
np.random
과 관련된 함수들에 대해서 고정해준다.
>>> import random
>>> random.seed(100)
>>> random.random()
0.1456692551041303
>>> random.random()
0.45492700451402135
>>> random.seed(50)
>>> random.random()
0.4975365687586023
>>> random.random()
0.2661737230725406
>>> random.seed(100)
>>> random.random()
0.1456692551041303
>>> random.random()
0.45492700451402135
기본적인 torch.rand()
torch.randint()
와 같은 함수들에 대해서 seed 적용을 하는 것.
torch.cuda.manual_seed(seed)
현재 GPU를 통해 만들어내는 결과들에 randomness 를 통제하는 것.
cuda 사용하지 않으면 자연스럽게 넘어간다.
manual_seed_all()
로 바꾸어서 사용해야한다.CuDNN 은 딥러닝 프레임워크에서 사용되는 것들에 대해서 Randomness 조절을 하기 위함.
deterministic 과 cudnn.benchmark 로 인하여 로 두어서 모델의 결과는 고정될 수 있지만, 속도면에서는 하락하게 된다고 함.
torch.backends.cudnn.deterministic = True
torch.backends.cudnn.benchmark = False
Seed는 Mersenne Twister 라는 알고리즘에서의 인자값에 해당한다.
Mersenne Twister 에 대해서 자세히 이해할 필요까지는 없을 것 같아서 간단하게 넘겼음.
대략적인 내용은, Seed 를 받으면 이를 변형하고 그 값을 출력하는 것인데. 처음 받은 값으로 변형을 진행하기 때문에, Seed 받는 것에 따라서 결과가 달라지는 것이다.
https://wikidocs.net/15652
https://pytorch.org/docs/stable/index.html