-
Notifications
You must be signed in to change notification settings - Fork 9
/
trainer.py
241 lines (195 loc) · 9.47 KB
/
trainer.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
238
239
240
241
from utils import AverageMeter,ProgressMeter
import torch
import time
from torch.autograd import Variable
def train_dir(train_loader, model, nce_criterion, mse_criterion, optimizer, epoch, args):
batch_time = AverageMeter('Time', ':6.3f')
data_time = AverageMeter('Data', ':6.3f')
nce_losses = AverageMeter('NCE Loss', ':.4e')
mse_losses = AverageMeter('MSE Loss', ':.4e')
losses = AverageMeter('Loss', ':.4e')
progress = ProgressMeter(
len(train_loader),
[batch_time, data_time, nce_losses,mse_losses,losses],
prefix="Epoch: [{}]".format(epoch))
# switch to train mode
model.train()
end = time.time()
for i, (images) in enumerate(train_loader):
# measure data loading time
data_time.update(time.time() - end)
if args.mode.lower() == "di":
if args.gpu is not None:
images[0] = images[0].cuda(args.gpu, non_blocking=True)
images[1] = images[1].cuda(args.gpu, non_blocking=True)
output, target = model(im_q=images[0], im_k=images[1])
loss = nce_criterion(output, target)
nce_losses.update(loss.item(), images[0].size(0))
losses.update(loss.item(), images[0].size(0))
else:
if args.gpu is not None:
images[0] = images[0].cuda(args.gpu, non_blocking=True)
images[1] = images[1].cuda(args.gpu, non_blocking=True)
images[2] = images[2].cuda(args.gpu, non_blocking=True)
output, target, rec_output = model(im_q=images[0], im_k=images[1])
nce_loss = nce_criterion(output, target)
mse_loss = mse_criterion(rec_output, images[2])
loss = args.contrastive_weight * nce_loss + args.mse_weight * mse_loss
nce_losses.update(nce_loss.item(), images[0].size(0))
mse_losses.update(mse_loss.item(), images[0].size(0))
losses.update(loss.item(), images[0].size(0))
# compute gradient and do SGD step
optimizer.zero_grad()
loss.backward()
optimizer.step()
# measure elapsed time
batch_time.update(time.time() - end)
end = time.time()
if i % args.print_freq == 0:
progress.display(i)
def validate_dir(val_loader, model, nce_criterion, mse_criterion, epoch, args):
batch_time = AverageMeter('Time', ':6.3f')
data_time = AverageMeter('Data', ':6.3f')
nce_losses = AverageMeter('NCE Loss', ':.4e')
mse_losses = AverageMeter('MSE Loss', ':.4e')
losses = AverageMeter('Loss', ':.4e')
progress = ProgressMeter(
len(val_loader),
[batch_time, data_time, nce_losses,mse_losses,losses],
prefix="Validation: ")
model.eval()
counter = torch.zeros((2,), device=torch.device(f'cuda:{args.rank}'))
end = time.time()
for i, (images) in enumerate(val_loader):
with torch.no_grad():
# measure data loading time
data_time.update(time.time() - end)
if args.mode.lower() == "di":
if args.gpu is not None:
images[0] = images[0].cuda(args.gpu, non_blocking=True)
images[1] = images[1].cuda(args.gpu, non_blocking=True)
output, target = model(im_q=images[0], im_k=images[1])
loss = nce_criterion(output, target)
nce_losses.update(loss.item(), images[0].size(0))
losses.update(loss.item(), images[0].size(0))
else:
if args.gpu is not None:
images[0] = images[0].cuda(args.gpu, non_blocking=True)
images[1] = images[1].cuda(args.gpu, non_blocking=True)
images[2] = images[2].cuda(args.gpu, non_blocking=True)
output, target, rec_output = model(im_q=images[0], im_k=images[1])
nce_loss = nce_criterion(output, target)
mse_loss = mse_criterion(rec_output, images[2])
loss = args.contrastive_weight * nce_loss + args.mse_weight * mse_loss
nce_losses.update(nce_loss.item(), images[0].size(0))
mse_losses.update(mse_loss.item(), images[0].size(0))
losses.update(loss.item(), images[0].size(0))
counter[0] += loss.item()
counter[1] += 1
# measure elapsed time
batch_time.update(time.time() - end)
end = time.time()
if i % args.print_freq == 0:
progress.display(i)
return counter
def train_dira(train_loader, generator, nce_criterion, mse_criterion, adversarial_criterion, optimizer_G, epoch, args, discriminator,optimizer_D,D_output_shape):
batch_time = AverageMeter('Time', ':6.3f')
data_time = AverageMeter('Data', ':6.3f')
nce_losses = AverageMeter('NCE Loss', ':.4e')
mse_losses = AverageMeter('MSE Loss', ':.4e')
g_losses = AverageMeter('Adversarial G Loss', ':.4e')
d_losses = AverageMeter('Discriminator Loss', ':.4e')
losses = AverageMeter('Generator Loss', ':.4e')
progress = ProgressMeter(
len(train_loader),
[batch_time, data_time, nce_losses,mse_losses,g_losses,d_losses,losses],
prefix="Epoch: [{}]".format(epoch))
# switch to train mode
generator.train()
end = time.time()
Tensor = torch.cuda.FloatTensor
for i, (images) in enumerate(train_loader):
# measure data loading time
data_time.update(time.time() - end)
valid = Variable(Tensor(images[0].shape[0], *D_output_shape).fill_(1.0), requires_grad=False)
fake = Variable(Tensor(images[0].shape[0], *D_output_shape).fill_(0.0), requires_grad=False)
if args.gpu is not None:
images[0] = images[0].cuda(args.gpu, non_blocking=True)
images[1] = images[1].cuda(args.gpu, non_blocking=True)
images[2] = images[2].cuda(args.gpu, non_blocking=True)
# -----------------
# Train Generator
# -----------------
# compute output
output, target, rec_output = generator(im_q=images[0], im_k=images[1])
nce_loss = nce_criterion(output, target)
mse_loss = mse_criterion(rec_output, images[2])
g_adv = adversarial_criterion(discriminator(rec_output), valid)
g_loss = args.contrastive_weight * nce_loss + args.mse_weight * mse_loss + args.adv_weight * g_adv
nce_losses.update(nce_loss.item(), images[0].size(0))
mse_losses.update(mse_loss.item(), images[0].size(0))
g_losses.update(g_adv.item(), images[0].size(0))
losses.update(g_loss.item(), images[0].size(0))
# compute gradient and do SGD step
optimizer_G.zero_grad()
g_loss.backward()
optimizer_G.step()
# ---------------------
# Train Discriminator
# ---------------------
optimizer_D.zero_grad()
# Measure discriminator's ability to classify real from generated samples
real_loss = adversarial_criterion(discriminator(images[2]), valid)
fake_loss = adversarial_criterion(discriminator(rec_output.detach()), fake)
d_loss = 0.5 * (real_loss + fake_loss)
d_loss.backward()
optimizer_D.step()
d_losses.update(d_loss.item(), images[0].size(0))
# measure elapsed time
batch_time.update(time.time() - end)
end = time.time()
if i % args.print_freq == 0:
progress.display(i)
def validate_dira(val_loader, model, nce_criterion, mse_criterion,adversarial_criterion, epoch, args,discriminator,D_output_shape):
batch_time = AverageMeter('Time', ':6.3f')
data_time = AverageMeter('Data', ':6.3f')
nce_losses = AverageMeter('NCE Loss', ':.4e')
mse_losses = AverageMeter('MSE Loss', ':.4e')
g_losses = AverageMeter('Adversarial G Loss', ':.4e')
losses = AverageMeter('Generator Loss', ':.4e')
progress = ProgressMeter(
len(val_loader),
[batch_time, data_time, nce_losses,mse_losses,losses],
prefix="Validation: ")
# switch to train mode
model.eval()
counter = torch.zeros((2,), device=torch.device(f'cuda:{args.rank}'))
end = time.time()
Tensor = torch.cuda.FloatTensor
for i, (images) in enumerate(val_loader):
with torch.no_grad():
# measure data loading time
data_time.update(time.time() - end)
valid = Variable(Tensor(images[0].shape[0], *D_output_shape).fill_(1.0), requires_grad=False)
if args.gpu is not None:
images[0] = images[0].cuda(args.gpu, non_blocking=True)
images[1] = images[1].cuda(args.gpu, non_blocking=True)
images[2] = images[2].cuda(args.gpu, non_blocking=True)
# compute output
output, target, rec_output = model(im_q=images[0], im_k=images[1])
nce_loss = nce_criterion(output, target)
mse_loss = mse_criterion(rec_output, images[2])
g_adv = adversarial_criterion(discriminator(rec_output), valid)
loss = args.contrastive_weight * nce_loss + args.mse_weight * mse_loss + args.adv_weight * g_adv
nce_losses.update(nce_loss.item(), images[0].size(0))
mse_losses.update(mse_loss.item(), images[0].size(0))
g_losses.update(g_adv.item(), images[0].size(0))
losses.update(loss.item(), images[0].size(0))
counter[0] += loss.item()
counter[1] += 1
# measure elapsed time
batch_time.update(time.time() - end)
end = time.time()
if i % args.print_freq == 0:
progress.display(i)
return counter