-
Notifications
You must be signed in to change notification settings - Fork 7
/
train_video.py
234 lines (172 loc) · 7.92 KB
/
train_video.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
import time
import warnings
import torch
import torch.nn.parallel
import torch.backends.cudnn as cudnn
import torch.optim
import torch.utils.data
from config.config_reader import parse_args, create_parser
from dataloader.load_dataloader import load_dataloader
from model.unsupervised_model import Model
from loss.compute_loss import *
from utils import Logger, mkdir_p, save_images
from utils.model_utils import *
best_loss = 10000
def main():
args = parse_args(create_parser())
if args.gpu is not None:
warnings.warn('You have chosen a specific GPU. This will completely '
'disable data parallelism.')
ngpus_per_node = torch.cuda.device_count()
main_worker(args.gpu, ngpus_per_node, args)
def main_worker(gpu, ngpus_per_node, args):
global best_loss
args.gpu = gpu
if args.gpu is not None:
print("Use GPU: {} for training".format(args.gpu))
# create model
output_shape = (int(args.image_size/4), int(args.image_size/4))
model = Model(args.nkpts, output_shape=output_shape)
if args.gpu is not None:
torch.cuda.set_device(args.gpu)
model = model.cuda(args.gpu)
else:
model = torch.nn.DataParallel(model).cuda()
loss_module = computeLoss(args)
optimizer = torch.optim.SGD(model.parameters(), args.lr,
momentum=args.momentum,
weight_decay=args.weight_decay)
# optionally resume from a checkpoint
if not os.path.isdir(args.checkpoint):
mkdir_p(args.checkpoint)
title = 'Landmark-discovery'
if args.resume:
if os.path.isfile(args.resume):
print("=> loading checkpoint '{}'".format(args.resume))
if args.gpu is None:
checkpoint = torch.load(args.resume)
else:
# Map model to be loaded to specified single gpu.
loc = 'cuda:{}'.format(args.gpu)
checkpoint = torch.load(args.resume, map_location=loc)
args.start_epoch = checkpoint['epoch']
best_loss = checkpoint['best_loss']
model.load_state_dict(checkpoint['state_dict'])
optimizer.load_state_dict(checkpoint['optimizer'])
print("=> loaded checkpoint '{}' (epoch {})"
.format(args.resume, checkpoint['epoch']))
logger = Logger(os.path.join(args.checkpoint, 'log.txt'), title=title, resume=True)
else:
print("=> no checkpoint found at '{}'".format(args.resume))
else:
logger = Logger(os.path.join(args.checkpoint, 'log.txt'), title=title)
logger.set_names(['Learning Rate', 'Train Loss', 'Valid Loss',])
cudnn.benchmark = True
# Data loading code
traindir = os.path.join(args.data)
valdir = os.path.join(args.data)
train_dataset, val_dataset = load_dataloader(args)
train_sampler = None
train_loader = torch.utils.data.DataLoader(
train_dataset, batch_size=args.batch_size, shuffle=(train_sampler is None),
num_workers=args.workers, pin_memory=True, sampler=train_sampler)
val_loader = torch.utils.data.DataLoader(
val_dataset, batch_size=args.batch_size, shuffle=False,
num_workers=args.workers, pin_memory=True)
if args.evaluate:
validate(val_loader, model, loss_module, 0, args)
return
is_best = True
for epoch in range(args.start_epoch, args.epochs):
adjust_learning_rate(optimizer, epoch, args)
# train for one epoch
train_loss = train(train_loader, model, loss_module, optimizer, epoch, args)
# evaluate on validation set every val_schedule epochs
if epoch > 0 and epoch%args.val_schedule == 0:
test_loss = validate(val_loader, model, loss_module, epoch, args)
else:
test_loss = 10000 # set test_loss = 100000 when not using validate
logger.append([args.lr * (0.1 ** (epoch // args.schedule)), train_loss, test_loss])
# remember best acc@1 and save checkpoint
is_best = test_loss < best_loss
best_loss = min(test_loss, best_loss)
save_checkpoint({
'epoch': epoch + 1,
'state_dict': model.state_dict(),
'best_loss': best_loss,
'optimizer' : optimizer.state_dict(),
}, is_best, checkpoint=args.checkpoint)
def train(train_loader, model, loss_module, optimizer, epoch, args):
batch_time = AverageMeter('Time', ':6.3f')
data_time = AverageMeter('Data', ':6.3f')
losses = AverageMeter('Loss', ':.4e')
progress = ProgressMeter(
len(train_loader),
[batch_time, data_time, 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.gpu is not None:
inputs, tr_inputs, loss_mask, in_mask = images[0].cuda(args.gpu, non_blocking=True), \
images[1].cuda(args.gpu, non_blocking=True), \
images[2].cuda(args.gpu, non_blocking=True), \
images[3].cuda(args.gpu, non_blocking=True)
rot_im1, rot_im2,rot_im3 = images[4].cuda(args.gpu, non_blocking=True), \
images[5].cuda(args.gpu, non_blocking=True), \
images[6].cuda(args.gpu, non_blocking=True)
if epoch < args.curriculum:
output = model(inputs, tr_inputs)
else:
output = model(inputs, tr_inputs, gmtr_x1 = rot_im1, gmtr_x2 = rot_im2, gmtr_x3 = rot_im3)
loss = loss_module.update_loss(inputs, tr_inputs, loss_mask, output, epoch)
# measure accuracy and record loss
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)
if args.visualize:
save_images(tr_inputs, output, epoch, args, epoch)
return losses.avg
def validate(val_loader, model, loss_module, epoch, args):
batch_time = AverageMeter('Time', ':6.3f')
losses = AverageMeter('Loss', ':.4e')
progress = ProgressMeter(
len(val_loader),
[batch_time, losses],
prefix='Test: ')
# switch to evaluate mode
model.eval()
with torch.no_grad():
end = time.time()
for i, images in enumerate(val_loader):
if args.gpu is not None:
inputs, tr_inputs, loss_mask, in_mask = images[0].cuda(args.gpu, non_blocking=True), \
images[1].cuda(args.gpu, non_blocking=True), \
images[2].cuda(args.gpu, non_blocking=True), \
images[3].cuda(args.gpu, non_blocking=True)
rot_im1, rot_im2,rot_im3 = images[4].cuda(args.gpu, non_blocking=True), \
images[5].cuda(args.gpu, non_blocking=True), \
images[6].cuda(args.gpu, non_blocking=True)
# compute output
output = model(inputs, tr_inputs, gmtr_x1 = rot_im1, gmtr_x2 = rot_im2, gmtr_x3 = rot_im3)
# Note that validate function only computes MSE loss
loss = loss_module.criterion[1](output[0] * loss_mask, tr_inputs * loss_mask)
losses.update(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)
return losses.avg
if __name__ == '__main__':
main()