-
Notifications
You must be signed in to change notification settings - Fork 1
/
utils.py
89 lines (77 loc) · 2.65 KB
/
utils.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
import os
import random
import numpy as np
import torch
import torch.nn as nn
import torch.nn.init as init
import math
def create_checkpoints_dir(dataset, num_blocks, hidden_size, code_length, estimator, hidden_channels, K):
"""
Create the dir of checkpoint.
for saving model or for loading model.
"""
dirName = f'checkpoints/{dataset}/'
if estimator in ['REALNVP']:
dirName = f'{dirName}b{num_blocks}h{hidden_size}c{code_length}/'
elif estimator == 'GLOW':
dirName = f'{dirName}K{K}L{num_blocks}h{hidden_channels}/'
else:
raise ValueError('Unknown flow model!')
if not os.path.exists(dirName):
os.makedirs(dirName)
print(f'Make Dir:{dirName}')
return dirName
def set_random_seed(seed):
"""
Sets random seeds.
:param seed: the seed to be set for all libraries.
"""
torch.backends.cudnn.benchmark = False
torch.backends.cudnn.deterministic = True
# torch.backends.cudnn.enabled = False
os.environ['PYTHONHASHSEED'] = str(seed)
random.seed(seed)
np.random.seed(seed)
# np.random.shuffle.seed(seed)
torch.manual_seed(seed)
torch.cuda.manual_seed(seed)
torch.cuda.manual_seed_all(seed)
def _init_fn(worker_id):
np.random.seed(int(seed))
def weights_init(m):
if isinstance(m, nn.Conv1d):
init.normal_(m.weight.data)
if m.bias is not None:
init.normal_(m.bias.data)
elif isinstance(m, nn.Conv2d):
init.xavier_normal_(m.weight.data)
if m.bias is not None:
init.normal_(m.bias.data)
elif isinstance(m, nn.Conv3d):
init.xavier_normal_(m.weight.data)
if m.bias is not None:
init.normal_(m.bias.data)
elif isinstance(m, nn.ConvTranspose1d):
init.normal_(m.weight.data)
if m.bias is not None:
init.normal_(m.bias.data)
elif isinstance(m, nn.ConvTranspose2d):
init.xavier_normal_(m.weight.data)
if m.bias is not None:
init.normal_(m.bias.data)
elif isinstance(m, nn.ConvTranspose3d):
init.xavier_normal_(m.weight.data)
if m.bias is not None:
init.normal_(m.bias.data)
elif isinstance(m, nn.BatchNorm1d):
init.normal_(m.weight.data, mean=1, std=0.02)
init.constant_(m.bias.data, 0)
elif isinstance(m, nn.BatchNorm2d):
init.normal_(m.weight.data, mean=1, std=0.02)
init.constant_(m.bias.data, 0)
elif isinstance(m, nn.BatchNorm3d):
init.normal_(m.weight.data, mean=1, std=0.02)
init.constant_(m.bias.data, 0)
elif isinstance(m, nn.Linear):
init.xavier_normal_(m.weight.data)
init.normal_(m.bias.data)