-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathutils.py
112 lines (82 loc) · 2.99 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
"""
Utilities
"""
import os
import logging
import shutil
import numpy as np
import torch
import torch.nn as nn
def encrypt_with_iso(g, ratio, th=5.0, device='cpu'):
g = g.cpu()
g_original_shape = g.shape
g = g.view(g_original_shape[0], -1)
g_norm = torch.norm(g, dim=1, keepdim=False)
g_norm = g_norm.view(-1, 1)
max_norm = torch.max(g_norm)
gaussian_noise = torch.normal(size=g.shape, mean=0.0,
std=1e-6+ratio * max_norm / torch.sqrt(torch.tensor(g.shape[1], dtype=torch.float32)))
res = g + gaussian_noise
res = res.view(g_original_shape).to(device)
return res
def get_logger(file_path):
""" Make python logger """
# [!] Since tensorboardX use default logger (e.g. logging.info()), we should use custom logger
logger = logging.getLogger('darts')
log_format = '%(asctime)s | %(message)s'
formatter = logging.Formatter(log_format, datefmt='%m/%d %I:%M:%S %p')
file_handler = logging.FileHandler(file_path, mode='w')
file_handler.setFormatter(formatter)
stream_handler = logging.StreamHandler()
stream_handler.setFormatter(formatter)
logger.addHandler(file_handler)
logger.addHandler(stream_handler)
logger.setLevel(logging.INFO)
return logger
def param_size(model):
""" Compute parameter size in MB """
n_params = sum(
np.prod(v.size()) for k, v in model.named_parameters() if not k.startswith('aux_head'))
return n_params / 1024. / 1024.
class AverageMeter():
""" Computes and stores the average and current value """
def __init__(self):
self.reset()
def reset(self):
""" Reset all statistics """
self.val = 0
self.avg = 0
self.sum = 0
self.count = 0
def update(self, val, n=1):
""" Update statistics """
self.val = val
self.sum += val * n
self.count += n
self.avg = self.sum / self.count
def accuracy(output, target, topk=(1,)):
maxk = max(topk)
batch_size = target.size(0)
_, pred = output.topk(maxk, 1, True, True)
pred = pred.t()
correct = pred.eq(target.view(1, -1).expand_as(pred))
res = []
for k in topk:
correct_k = correct[:k].reshape(-1).float().sum(0)
res.append(correct_k.mul_(100.0 / batch_size))
return res
def create_exp_dir(path, scripts_to_save=None):
os.makedirs(path, exist_ok=True)
print('Experiment dir : {}'.format(path))
if scripts_to_save is not None:
os.makedirs(os.path.join(path, 'scripts'), exist_ok=True)
for script in scripts_to_save:
dst_file = os.path.join(path, 'scripts', os.path.basename(script))
shutil.copyfile(script, dst_file)
def save_checkpoint(state, ckpt_dir, is_best=False):
os.makedirs(ckpt_dir, exist_ok=True)
filename = os.path.join(ckpt_dir, 'checkpoint.pth.tar')
torch.save(state, filename)
if is_best:
best_filename = os.path.join(ckpt_dir, 'best.pth.tar')
shutil.copyfile(filename, best_filename)