-
Notifications
You must be signed in to change notification settings - Fork 26
/
utils.py
237 lines (213 loc) · 9.06 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
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
import math
import random
import numpy as np
import torch
import torch.distributed as dist
import torch.nn as nn
import torch.nn.functional as F
from pytorch_msssim import ms_ssim, ssim
def quantize_per_tensor(t, bit=8, axis=-1):
if axis == -1:
t_valid = t!=0
t_min, t_max = t[t_valid].min(), t[t_valid].max()
scale = (t_max - t_min) / 2**bit
elif axis == 0:
min_max_list = []
for i in range(t.size(0)):
t_valid = t[i]!=0
if t_valid.sum():
min_max_list.append([t[i][t_valid].min(), t[i][t_valid].max()])
else:
min_max_list.append([0, 0])
min_max_tf = torch.tensor(min_max_list).to(t.device)
scale = (min_max_tf[:,1] - min_max_tf[:,0]) / 2**bit
if t.dim() == 4:
scale = scale[:,None,None,None]
t_min = min_max_tf[:,0,None,None,None]
elif t.dim() == 2:
scale = scale[:,None]
t_min = min_max_tf[:,0,None]
elif axis == 1:
min_max_list = []
for i in range(t.size(1)):
t_valid = t[:,i]!=0
if t_valid.sum():
min_max_list.append([t[:,i][t_valid].min(), t[:,i][t_valid].max()])
else:
min_max_list.append([0, 0])
min_max_tf = torch.tensor(min_max_list).to(t.device)
scale = (min_max_tf[:,1] - min_max_tf[:,0]) / 2**bit
if t.dim() == 4:
scale = scale[None,:,None,None]
t_min = min_max_tf[None,:,0,None,None]
elif t.dim() == 2:
scale = scale[None,:]
t_min = min_max_tf[None,:,0]
# import pdb; pdb.set_trace; from IPython import embed; embed()
quant_t = ((t - t_min) / (scale + 1e-19)).round()
new_t = t_min + scale * quant_t
return quant_t, new_t
def all_gather(tensors):
"""
All gathers the provided tensors from all processes across machines.
Args:
tensors (list): tensors to perform all gather across all processes in
all machines.
"""
gather_list = []
output_tensor = []
world_size = dist.get_world_size()
for tensor in tensors:
tensor_placeholder = [
torch.ones_like(tensor) for _ in range(world_size)
]
dist.all_gather(tensor_placeholder, tensor, async_op=False)
gather_list.append(tensor_placeholder)
for gathered_tensor in gather_list:
output_tensor.append(torch.cat(gathered_tensor, dim=0))
return output_tensor
def all_reduce(tensors, average=True):
"""
All reduce the provided tensors from all processes across machines.
Args:
tensors (list): tensors to perform all reduce across all processes in
all machines.
average (bool): scales the reduced tensor by the number of overall
processes across all machines.
"""
for tensor in tensors:
dist.all_reduce(tensor, async_op=False)
if average:
world_size = dist.get_world_size()
for tensor in tensors:
tensor.mul_(1.0 / world_size)
return tensors
class PositionalEncoding(nn.Module):
def __init__(self, pe_embed):
super(PositionalEncoding, self).__init__()
self.pe_embed = pe_embed.lower()
if self.pe_embed == 'none':
self.embed_length = 1
else:
self.lbase, self.levels = [float(x) for x in pe_embed.split('_')]
self.levels = int(self.levels)
self.embed_length = 2 * self.levels
def forward(self, pos):
if self.pe_embed == 'none':
return pos[:,None]
else:
pe_list = []
for i in range(self.levels):
temp_value = pos * self.lbase **(i) * math.pi
pe_list += [torch.sin(temp_value), torch.cos(temp_value)]
return torch.stack(pe_list, 1)
def psnr2(img1, img2):
mse = (img1 - img2) ** 2
PIXEL_MAX = 1
psnr = -10 * torch.log10(mse)
psnr = torch.clamp(psnr, min=0, max=50)
return psnr
def loss_fn(pred, target, args):
target = target.detach()
if args.loss_type == 'L2':
loss = F.mse_loss(pred, target, reduction='none')
loss = loss.mean()
elif args.loss_type == 'L1':
loss = torch.mean(torch.abs(pred - target))
elif args.loss_type == 'SSIM':
loss = 1 - ssim(pred, target, data_range=1, size_average=True)
elif args.loss_type == 'Fusion1':
loss = 0.3 * F.mse_loss(pred, target) + 0.7 * (1 - ssim(pred, target, data_range=1, size_average=True))
elif args.loss_type == 'Fusion2':
loss = 0.3 * torch.mean(torch.abs(pred - target)) + 0.7 * (1 - ssim(pred, target, data_range=1, size_average=True))
elif args.loss_type == 'Fusion3':
loss = 0.5 * F.mse_loss(pred, target) + 0.5 * (1 - ssim(pred, target, data_range=1, size_average=True))
elif args.loss_type == 'Fusion4':
loss = 0.5 * torch.mean(torch.abs(pred - target)) + 0.5 * (1 - ssim(pred, target, data_range=1, size_average=True))
elif args.loss_type == 'Fusion5':
loss = 0.7 * F.mse_loss(pred, target) + 0.3 * (1 - ssim(pred, target, data_range=1, size_average=True))
elif args.loss_type == 'Fusion6':
loss = 0.7 * torch.mean(torch.abs(pred - target)) + 0.3 * (1 - ssim(pred, target, data_range=1, size_average=True))
elif args.loss_type == 'Fusion7':
loss = 0.7 * F.mse_loss(pred, target) + 0.3 * torch.mean(torch.abs(pred - target))
elif args.loss_type == 'Fusion8':
loss = 0.5 * F.mse_loss(pred, target) + 0.5 * torch.mean(torch.abs(pred - target))
elif args.loss_type == 'Fusion9':
loss = 0.9 * torch.mean(torch.abs(pred - target)) + 0.1 * (1 - ssim(pred, target, data_range=1, size_average=True))
elif args.loss_type == 'Fusion10':
loss = 0.7 * torch.mean(torch.abs(pred - target)) + 0.3 * (1 - ms_ssim(pred, target, data_range=1, size_average=True))
elif args.loss_type == 'Fusion11':
loss = 0.9 * torch.mean(torch.abs(pred - target)) + 0.1 * (1 - ms_ssim(pred, target, data_range=1, size_average=True))
elif args.loss_type == 'Fusion12':
loss = 0.8 * torch.mean(torch.abs(pred - target)) + 0.2 * (1 - ms_ssim(pred, target, data_range=1, size_average=True))
return loss
def psnr_fn(output_list, target_list):
psnr_list = []
for output, target in zip(output_list, target_list):
l2_loss = F.mse_loss(output.detach(), target.detach(), reduction='mean')
psnr = -10 * torch.log10(l2_loss)
psnr = psnr.view(1, 1).expand(output.size(0), -1)
psnr_list.append(psnr)
psnr = torch.cat(psnr_list, dim=1) #(batchsize, num_stage)
return psnr
def msssim_fn(output_list, target_list):
msssim_list = []
for output, target in zip(output_list, target_list):
if output.size(-2) >= 160:
msssim = ms_ssim(output.float().detach(), target.detach(), data_range=1, size_average=True)
else:
msssim = torch.tensor(0).to(output.device)
msssim_list.append(msssim.view(1))
msssim = torch.cat(msssim_list, dim=0) #(num_stage)
msssim = msssim.view(1, -1).expand(output_list[-1].size(0), -1) #(batchsize, num_stage)
return msssim
def RoundTensor(x, num=2, group_str=False):
if group_str:
str_list = []
for i in range(x.size(0)):
x_row = [str(round(ele, num)) for ele in x[i].tolist()]
str_list.append(','.join(x_row))
out_str = '/'.join(str_list)
else:
str_list = [str(round(ele, num)) for ele in x.flatten().tolist()]
out_str = ','.join(str_list)
return out_str
def adjust_lr(optimizer, cur_epoch, cur_iter, data_size, args):
cur_epoch = cur_epoch + (float(cur_iter) / data_size)
if args.lr_type == 'cosine':
lr_mult = 0.5 * (math.cos(math.pi * (cur_epoch - args.warmup)/ (args.epochs - args.warmup)) + 1.0)
elif args.lr_type == 'step':
lr_mult = 0.1 ** (sum(cur_epoch >= np.array(args.lr_steps)))
elif args.lr_type == 'const':
lr_mult = 1
elif args.lr_type == 'plateau':
lr_mult = 1
else:
raise NotImplementedError
if cur_epoch < args.warmup:
lr_mult = 0.1 + 0.9 * cur_epoch / args.warmup
for i, param_group in enumerate(optimizer.param_groups):
param_group['lr'] = args.lr * lr_mult
return args.lr * lr_mult
def worker_init_fn(worker_id):
"""
Re-seed each worker process to preserve reproducibility
"""
worker_seed = torch.initial_seed() % 2**32
np.random.seed(worker_seed)
random.seed(worker_seed)
return
class PositionalEncodingTrans(nn.Module):
def __init__(self, d_model, max_len):
super().__init__()
self.max_len = max_len
pe = torch.zeros(max_len, d_model)
position = torch.arange(0, max_len, dtype=torch.float).unsqueeze(1)
div_term = torch.exp(torch.arange(0, d_model, 2).float() * (-math.log(10000.0) / d_model))
pe[:, 0::2] = torch.sin(position * div_term)
pe[:, 1::2] = torch.cos(position * div_term)
self.register_buffer('pe', pe)
def forward(self, pos):
index = torch.round(pos * self.max_len).long()
p = self.pe[index]
return p