-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmain.py
539 lines (503 loc) · 20.2 KB
/
main.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
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
#!/usr/bin/env python3
import argparse
import logging
import sys
from pathlib import Path
from typing import Any, Dict
import torch
import tensorly as tl
import data
import wandb
import compress
import os
import torchshow as ts
import pandas as pd
from model_loader import load_checkpoint, make_model
from data import PreprocessedEPICDataset, PostprocessedEPICDataset
from torch.utils.data import DataLoader
from torch import nn, optim
from torch.optim.optimizer import Optimizer
from torchvision import transforms
from ops.utils import compute_accuracy
tl.set_backend('pytorch')
torch.backends.cudnn.benchmark = True
torch.autograd.set_detect_anomaly(True)
if torch.cuda.is_available():
DEVICE = torch.device('cuda')
else:
DEVICE = torch.device('cpu')
parser = argparse.ArgumentParser(
description="Hub for everything necessary to train the neural network",
formatter_class=argparse.ArgumentDefaultsHelpFormatter,
)
parser.add_argument(
"model_type",
nargs="?",
choices=["tsn", "tsm", "tsm-nl", "trn", "mtrn"],
default=None,
)
parser.add_argument(
"--checkpoint",
type=Path,
help="Path to checkpointed model. Should be a dictionary containing the keys:"
" 'model_type', 'segment_count', 'modality', 'state_dict', and 'arch'.",
)
parser.add_argument(
"--arch",
default="resnet50",
choices=["BNInception", "resnet50"],
help="Backbone architecture",
)
parser.add_argument(
"--modality", default="RGB", choices=["RGB", "Flow"], help="Input modality"
)
parser.add_argument(
"--flow-length", default=5, type=int, help="Number of (u, v) pairs in flow stack"
)
parser.add_argument(
"--dropout",
default=0.7,
type=float,
help="Dropout probability. The dropout layer replaces the "
"backbone's classification layer.",
)
parser.add_argument(
"--trn-img-feature-dim",
default=256,
type=int,
help="Number of dimensions for the output of backbone network. "
"This is effectively the image feature dimensionality.",
)
parser.add_argument(
"--segment-count",
default=8,
type=int,
help="Number of segments. For RGB this corresponds to number of "
"frames, whereas for Flow, it is the number of points from "
"which a stack of (u, v) frames are sampled.",
)
parser.add_argument(
"--tsn-consensus-type",
choices=["avg", "max"],
default="avg",
help="Consensus function for TSN used to fuse class scores from "
"each segment's predictoin.",
)
parser.add_argument(
"--tsm-shift-div",
default=8,
type=int,
help="Reciprocal proportion of features temporally-shifted.",
)
parser.add_argument(
"--tsm-shift-place",
default="blockres",
choices=["block", "blockres"],
help="Location for the temporal shift to take place. Either 'block' for the shift "
"to happen in the non-residual part of a block, or 'blockres' if the shift happens "
"in the residual path.",
)
parser.add_argument(
"--tsm-temporal-pool",
action="store_true",
help="Gradually temporally pool throughout the network",
)
parser.add_argument(
"--load",
default="preprocessed",
choices=["preprocessed", "postprocessed"],
help="Use 'preprocessed' or 'postprocessed' dataset",
)
parser.add_argument(
"--dataset-path",
default="",
type=str,
help="Path to the EPIC-KITCHENS folder on the device"
)
parser.add_argument(
"--label",
default="EPIC",
type=str,
help="Label prepended to preprocessed dataset files"
)
parser.add_argument(
"--matrix-type",
default=None,
choices=[None, "bernoulli", "gaussian"],
help="'bernoulli' or 'gaussian' matrices",
)
parser.add_argument(
"--measurements",
nargs='*',
default=None,
type=int,
help="Heights of measurement matrices"
)
parser.add_argument(
"--modes",
nargs='*',
default=None,
type=int,
help="Modes corresponding to measurement matrices"
)
parser.add_argument(
"--learn-phi",
default=False,
action="store_true",
help="Adds the measurement matrices as a learnable parameter"
)
parser.add_argument(
"--learn-theta",
default=False,
action="store_true",
help="Adds the inference matrices as a learnable parameter"
)
parser.add_argument(
"--num-annotations",
default=1000,
type=int,
help="Number of annotations to postprocess from EPIC-KITCHENS"
)
parser.add_argument(
"--chunks",
default=1,
type=int,
help="Number of evenly sized chunks in preprocessed dataset"
)
parser.add_argument(
"--ratio",
nargs=3,
default=[80, 10, 10],
type=int,
help="Ratio of train/val/test splits respectively in postprocessed dataset"
)
parser.add_argument(
"--seed",
default=0,
type=int,
help="Random seed used to generate train/val/test splits"
)
parser.add_argument(
"--epochs",
default=10,
type=int,
help="Number of epochs to train"
)
parser.add_argument(
"--batch-size",
default=10,
type=int,
help="Number of clips per batch"
)
parser.add_argument(
"--lr",
default=1e-3,
type=float,
help="Learning rate of the network"
)
parser.add_argument(
"--val-frequency",
default=1,
type=int,
help="Epochs until validation set is tested"
)
parser.add_argument(
"--log-frequency",
default=0,
type=int,
help="Steps until logs are saved with `wandb`"
)
parser.add_argument(
"--print-frequency",
default=10,
type=int,
help="Steps until training batch results are printed"
)
parser.add_argument(
"--print-model",
action="store_true",
help="Print model definition"
)
parser.add_argument(
"--model-label",
default=None,
type=str,
help="Label of given checkpoint"
)
parser.add_argument(
"--save-model",
default=False,
action="store_true",
help="Saves model for inference"
)
parser.add_argument(
"--load-model",
default=None,
choices=[None, "clip", "dataset", "filters"],
help="Loads model for inference"
)
parser.add_argument(
"--index",
default=0,
type=int,
help="Clip to do model inference with"
)
parser.add_argument(
"--matrix-label",
default=None,
type=str,
help="Label of matrix checkpoint to use for inference"
)
def extract_settings_from_args(args: argparse.Namespace) -> Dict[str, Any]:
settings = vars(args)
for variant in ["trn", "tsm", "tsn"]:
variant_key_prefix = f"{variant}_"
variant_keys = {
key for key in settings.keys() if key.startswith(variant_key_prefix)
}
for key in variant_keys:
stripped_key = key[len(variant_key_prefix) :]
settings[stripped_key] = settings[key]
del settings[key]
return settings
def get_dataloaders(dataprocessor, args):
if args.load == 'preprocessed':
train_dataset = PreprocessedEPICDataset(dataprocessor, args.label, args.chunks, 'train')
val_dataset = PreprocessedEPICDataset(dataprocessor, args.label, args.chunks, 'val')
test_dataset = PreprocessedEPICDataset(dataprocessor, args.label, args.chunks, 'test')
elif args.load == 'postprocessed':
train, val, test = dataprocessor.split_annotations(args.num_annotations, tuple(args.ratio), args.seed)
train_dataset = PostprocessedEPICDataset(args.dataset_path, train.reset_index(),
transforms.Compose([transforms.PILToTensor(), transforms.Resize((224, 224))]),
args.segment_count)
val_dataset = PostprocessedEPICDataset(args.dataset_path, val.reset_index(),
transforms.Compose([transforms.PILToTensor(), transforms.Resize((224, 224))]),
args.segment_count)
test_dataset = PostprocessedEPICDataset(args.dataset_path, test.reset_index(),
transforms.Compose([transforms.PILToTensor(), transforms.Resize((224, 224))]),
args.segment_count)
train_dataloader = DataLoader(dataset=train_dataset, batch_size=args.batch_size, shuffle=True)
val_dataloader = DataLoader(dataset=val_dataset, batch_size=args.batch_size, shuffle=False)
test_dataloader = DataLoader(dataset=test_dataset, batch_size=args.batch_size, shuffle=False)
return train_dataloader, val_dataloader, test_dataloader
def get_matrices(clip_dims, args):
if args.matrix_type == 'bernoulli':
matrix_gen = compress.random_bernoulli_matrix
elif args.matrix_type == 'gaussian':
matrix_gen = compress.random_gaussian_matrix
phi_matrices = None if args.matrix_type == None else list(map(lambda x, y:
matrix_gen((x, clip_dims[y])).to(DEVICE), args.measurements, args.modes))
return phi_matrices
def get_model(args, phi_matrices):
if args.checkpoint is None:
if args.model_type is None:
print("If not providing a checkpoint, you must specify model_type")
sys.exit(1)
settings = extract_settings_from_args(args)
if args.learn_phi and args.learn_theta:
settings.update({'phi_matrices': phi_matrices})
settings.update({'theta_matrices': list(map(lambda x: x.clone(), phi_matrices))})
elif args.learn_phi and not args.learn_theta:
settings.update({'phi_matrices': phi_matrices})
settings.update({'theta_matrices': None})
elif not args.learn_phi and args.learn_theta:
settings.update({'phi_matrices': None})
settings.update({'theta_matrices': list(map(lambda x: x.clone(), phi_matrices))})
else:
settings.update({'phi_matrices': None})
settings.update({'theta_matrices': None})
model = make_model(settings)
elif args.checkpoint is not None and args.checkpoint.exists():
model = load_checkpoint(args.checkpoint)
else:
print(f"{args.checkpoint} doesn't exist")
sys.exit(1)
return settings, model
def save_model(trainer, args, phi_matrices, theta_matrices):
if not os.path.exists(f'checkpoints/{args.model_label}'):
os.makedirs(f'checkpoints/{args.model_label}')
torch.save(trainer.model.state_dict(), f'checkpoints/{args.model_label}/{args.model_label}.pt')
if phi_matrices != None:
torch.save(phi_matrices, f'checkpoints/{args.model_label}/phi_{args.model_label}.pt')
if theta_matrices != None:
torch.save(theta_matrices, f'checkpoints/{args.model_label}/theta_{args.model_label}.pt')
def clip_inference(model, args, test_dataloader, phi_matrices, theta_matrices):
model.load_state_dict(torch.load(f'checkpoints/{args.model_label}/{args.model_label}.pt'))
model.to(DEVICE)
model.eval()
if args.matrix_type != None:
phi_matrices = list(torch.load(f'checkpoints/{args.model_label}/phi_{args.model_label}.pt', map_location=DEVICE))
theta_matrices = list(torch.load(f'checkpoints/{args.model_label}/theta_{args.model_label}.pt', map_location=DEVICE))
with torch.no_grad():
x, y = test_dataloader.dataset.__getitem__(args.index)
ts.show(x)
x = x.float().to(DEVICE)
if phi_matrices != None:
compressed = tl.tenalg.multi_mode_dot(x, phi_matrices, args.modes)
x = tl.tenalg.multi_mode_dot(compressed, theta_matrices, args.modes, transpose=True)
ts.show(x)
verb_output, noun_output = model(x)
probabilities = nn.functional.softmax(verb_output, dim=-1), nn.functional.softmax(noun_output, dim=-1)
print(f'true label {y}, predicted labels {torch.topk(probabilities[0], 3).indices},{torch.topk(probabilities[1], 3).indices}, probabilities {torch.topk(probabilities[0], 3).values},{torch.topk(probabilities[1], 3).values}')
def dataset_inference(model, args, test_dataloader, phi_matrices, theta_matrices):
model.load_state_dict(torch.load(f'checkpoints/{args.model_label}/{args.model_label}.pt'))
model.to(DEVICE)
model.eval()
if args.matrix_type != None:
phi_matrices = list(torch.load(f'checkpoints/{args.matrix_label}/phi_{args.matrix_label}.pt', map_location=DEVICE))
theta_matrices = list(torch.load(f'checkpoints/{args.matrix_label}/theta_{args.matrix_label}.pt', map_location=DEVICE))
ys = []
y_hats = []
with torch.no_grad():
for x, y in test_dataloader:
x = x.float().to(DEVICE)
y = y.to(DEVICE)
if phi_matrices != None: compress.process_batch(x, phi_matrices, theta_matrices, args.modes)
verb_output, noun_output = model(x)
y_hat_verb = torch.argmax(verb_output, dim=-1)
y_hat_noun = torch.argmax(noun_output, dim=-1)
ys.append(y)
y_hats.append(torch.stack((y_hat_verb, y_hat_noun), 1))
ys = torch.cat(ys)
y_hats = torch.cat(y_hats)
predictions_df = pd.DataFrame(y_hats.to('cpu')).rename(columns={0: 'verb_class', 1: 'noun_class'})
print(predictions_df.astype('object').describe())
verb_accuracy = compute_accuracy(ys[:, 0], y_hats[:, 0])
noun_accuracy = compute_accuracy(ys[:, 1], y_hats[:, 1])
print(f'verb accuracy {verb_accuracy * 100:.2f}, noun accuracy {noun_accuracy * 100:.2f}')
def visualise_filters(model, args):
model.load_state_dict(torch.load(f'checkpoints/{args.model_label}/{args.model_label}.pt'))
model.to(DEVICE)
model.eval()
print(list(model.state_dict()))
ts.show(model.state_dict()['base_model.conv1.weight'])
ts.show(torch.sum(model.state_dict()['base_model.layer1.0.conv2.weight'], dim=1, keepdim=True))
ts.show(torch.sum(model.state_dict()['base_model.layer2.0.conv2.weight'], dim=1, keepdim=True))
ts.show(torch.sum(model.state_dict()['base_model.layer3.0.conv2.weight'], dim=1, keepdim=True))
ts.show(torch.sum(model.state_dict()['base_model.layer4.0.conv2.weight'], dim=1, keepdim=True))
class Trainer:
def __init__(self,
model: nn.Module,
train_dataloader: DataLoader,
val_dataloader: DataLoader,
test_dataloader: DataLoader,
criterion: nn.Module,
optimizer: Optimizer,
phi_matrices: list,
theta_matrices: list,
modes: list):
self.model = model.to(DEVICE)
self.train_dataloader = train_dataloader
self.val_dataloader = val_dataloader
self.test_dataloader = test_dataloader
self.criterion = criterion
self.optimizer = optimizer
self.phi_matrices = phi_matrices
self.theta_matrices = theta_matrices
self.modes = modes
def train(self, epochs, val_frequency, log_frequency, print_frequency):
self.model.train()
for epoch in range(1, epochs + 1):
self.step = 1
self.model.train()
for x, y in self.train_dataloader:
x = x.float().to(DEVICE)
y = y.to(DEVICE)
if self.phi_matrices != None: compress.process_batch(x, self.phi_matrices, self.theta_matrices, self.modes)
verb_output, noun_output = self.model(x)
verb_loss = self.criterion(verb_output, y[:, 0])
noun_loss = self.criterion(noun_output, y[:, 1])
loss = verb_loss + noun_loss
loss.backward()
self.optimizer.step()
self.optimizer.zero_grad()
with torch.no_grad():
y_hat_verb = torch.argmax(verb_output, dim=-1)
y_hat_noun = torch.argmax(noun_output, dim=-1)
verb_accuracy = compute_accuracy(y[:, 0], y_hat_verb)
noun_accuracy = compute_accuracy(y[:, 1], y_hat_noun)
if log_frequency != 0 and (self.step % log_frequency) == 0:
wandb.log({'train/verb-loss': verb_loss,
'train/noun-loss': noun_loss,
'train/verb-accuracy': verb_accuracy,
'train/noun-accuracy': noun_accuracy})
if (self.step % print_frequency) == 0:
self.print_metrics(epoch, verb_loss, noun_loss, verb_accuracy, noun_accuracy)
self.step += 1
if (epoch % val_frequency) == 0:
self.validate('val', log_frequency)
self.validate('test', log_frequency)
self.model.train()
def validate(self, split, log_frequency):
if split == 'val': split_dataloader = self.val_dataloader
elif split == 'test': split_dataloader = self.test_dataloader
self.model.eval()
total_verb_loss = 0
total_noun_loss = 0
ys = []
y_hats = []
with torch.no_grad():
for x, y in split_dataloader:
x = x.float().to(DEVICE)
y = y.to(DEVICE)
if self.phi_matrices != None: compress.process_batch(x, self.phi_matrices, self.theta_matrices, self.modes)
verb_output, noun_output = self.model(x)
verb_loss = self.criterion(verb_output, y[:, 0])
noun_loss = self.criterion(noun_output, y[:, 1])
total_verb_loss += verb_loss.item()
total_noun_loss += noun_loss.item()
y_hat_verb = torch.argmax(verb_output, dim=-1)
y_hat_noun = torch.argmax(noun_output, dim=-1)
ys.append(y)
y_hats.append(torch.stack((y_hat_verb, y_hat_noun), 1))
ys = torch.cat(ys)
y_hats = torch.cat(y_hats)
verb_accuracy = compute_accuracy(ys[:, 0], y_hats[:, 0])
noun_accuracy = compute_accuracy(ys[:, 1], y_hats[:, 1])
average_verb_loss = total_verb_loss / len(split_dataloader)
average_noun_loss = total_noun_loss / len(split_dataloader)
if (log_frequency != 0):
wandb.log({f'{split}/avg-verb-loss': average_verb_loss,
f'{split}/avg-noun-loss': average_noun_loss,
f'{split}/verb-accuracy': verb_accuracy,
f'{split}/noun-accuracy': noun_accuracy})
print(f"{split}: avg verb loss: {average_verb_loss:.5f} avg noun loss: {average_noun_loss:.5f}, verb accuracy: {verb_accuracy * 100:2.2f} noun accuracy: {noun_accuracy * 100:2.2f}")
def print_metrics(self, epoch, verb_loss, noun_loss, verb_accuracy, noun_accuracy):
epoch_step = self.step % len(self.train_dataloader)
if epoch_step == 0: epoch_step = len(self.train_dataloader)
print(
f"epoch: [{epoch}], "
f"step: [{epoch_step}/{len(self.train_dataloader)}], "
f"batch verb loss: {verb_loss:.5f}",
f"batch noun loss: {noun_loss:.5f}, "
f"batch verb accuracy: {verb_accuracy * 100:2.2f}",
f"batch noun accuracy: {noun_accuracy * 100:2.2f} "
)
def main(args):
dataprocessor = data.DataProcessor(args.dataset_path, 'annotations', 'data')
train_dataloader, val_dataloader, test_dataloader = get_dataloaders(dataprocessor, args)
phi_matrices = get_matrices(train_dataloader.dataset.__getitem__(0)[0].size(), args)
logging.basicConfig(level=logging.INFO)
settings, model = get_model(args, phi_matrices)
if args.learn_phi: phi_matrices = model.phi_matrices
if args.learn_theta: theta_matrices = model.theta_matrices
if not args.learn_theta: theta_matrices = phi_matrices
if args.load_model == None:
if args.print_model:
print(model)
if args.log_frequency != 0:
wandb.init(project="egocentric-compressed-learning-results", config=settings)
criterion = nn.CrossEntropyLoss()
optimizer = optim.SGD(model.parameters(), lr=args.lr)
trainer = Trainer(model, train_dataloader, val_dataloader, test_dataloader, criterion, optimizer, phi_matrices, theta_matrices, args.modes)
trainer.train(args.epochs, args.val_frequency, args.log_frequency, args.print_frequency)
if args.save_model:
save_model(trainer, args, phi_matrices, theta_matrices)
elif args.load_model == 'clip':
clip_inference(model, args, test_dataloader, phi_matrices, theta_matrices)
elif args.load_model == 'dataset':
dataset_inference(model, args, test_dataloader, phi_matrices, theta_matrices)
elif args.load_model == 'filters':
visualise_filters(model, args)
if __name__ == "__main__":
main(parser.parse_args())