forked from michiyasunaga/dragon
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathutils.py
159 lines (108 loc) · 3.7 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
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
import argparse
import io
import json
import os
import pickle
import time
import types
import torch
def bool_flag(v):
if v.lower() in ('yes', 'true', 't', 'y', '1'):
return True
elif v.lower() in ('no', 'false', 'f', 'n', '0'):
return False
else:
raise argparse.ArgumentTypeError('Boolean value expected.')
def bool_str_flag(v):
if v.lower() in ('yes', 'true', 't', 'y', '1'):
return True
elif v.lower() in ('no', 'false', 'f', 'n', '0'):
return False
else:
return v
def int_flag(v):
return int(float(v))
def check_path(path):
d = os.path.dirname(path)
if not os.path.exists(d):
os.makedirs(d)
def check_file(file):
return os.path.isfile(file)
def export_config(config, path):
param_dict = vars(config)
check_path(path)
with open(path, 'w') as fout:
json.dump(param_dict, fout, indent=4)
def import_config(imported_args, existing_args):
existing_param_dict = vars(existing_args)
existing_param_dict.update(vars(imported_args))
config = types.SimpleNamespace(**existing_param_dict)
return config
def freeze_net(module):
for p in module.parameters():
p.requires_grad = False
def unfreeze_net(module):
for p in module.parameters():
p.requires_grad = True
def test_data_loader_ms_per_batch(data_loader, max_steps=10000):
start = time.time()
n_batch = sum(1 for batch, _ in zip(data_loader, range(max_steps)))
return (time.time() - start) * 1000 / n_batch
def print_cuda_info():
print('torch version:', torch.__version__)
print('torch cuda version:', torch.version.cuda)
print('cuda is available:', torch.cuda.is_available())
print('cuda device count:', torch.cuda.device_count())
print("cudnn version:", torch.backends.cudnn.version())
def move_tensor(t, device):
if type(t) == torch.Tensor:
return t.to(device)
elif type(t) == list:
return [move_tensor(x, device) for x in t]
else:
return t
def freeze_params(params):
for p in params:
p.requires_grad = False
def unfreeze_params(params):
for p in params:
p.requires_grad = True
def save_pickle(data, data_path):
check_path(data_path)
with open(data_path, "wb") as f:
pickle.dump(data, f, protocol=4)
def load_pickle(file_path):
with open(file_path, "rb") as f:
return pickle.load(f)
def save_json(data, file_path):
check_path(file_path)
with open(file_path, "w") as f:
json.dump(data, f, default=set_default)
def save_json_pretty(data, file_path):
"""save formatted json, use this one for some json config files"""
check_path(file_path)
with open(file_path, "w") as f:
f.write(json.dumps(data, indent=4, sort_keys=True, default=set_default))
def load_json(file_path):
with open(file_path, "r") as f:
return json.load(f)
def set_default(obj):
if isinstance(obj, set):
return list(obj)
raise TypeError
def append_filename(filename, appendix):
name, ext = os.path.splitext(filename)
return "{name}_{uid}{ext}".format(name=name, uid=appendix, ext=ext)
class CPU_Unpickler(pickle.Unpickler):
def find_class(self, module, name):
if module == 'torch.storage' and name == '_load_from_bytes':
return lambda b: torch.load(io.BytesIO(b), map_location='cpu')
else:
return super().find_class(module, name)
def map_wrapper(*args, **kwargs):
return map(*args)
def sort_dict(d):
return {k: v for k, v in sorted(d.items(), key=lambda item: item[1], reverse=True)}
def sort_and_normalize_dict(d):
s = sum(d.values())
return {k: v / s for k, v in sorted(d.items(), key=lambda item: item[1], reverse=True)}