-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.py
312 lines (245 loc) · 10 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
import torch
from processor import Processor, setup, cleanup
from models import MODELS
from utils import LOSS, SEGMENT_GENERATOR, STATISTICS
from utils import Parser
from utils.metrics import F1Score, EditScore, ConfusionMatrix
import os
import random
def pick_model(args):
"""Returns a constructor for the selected model variant.
Args:
args : ``dict``
Parsed CLI arguments.
Returns:
PyTorch Model corresponding to the user-defined CLI parameters.
"""
return \
MODELS[args.processor['model']], \
LOSS[args.processor['model']], \
SEGMENT_GENERATOR[args.processor['model']], \
STATISTICS[args.processor['model']]
def assert_parameters(args):
"""Performs model and job configuration parameter checks."""
# do some desired parameter checking
if (False):
raise ValueError(
'GCN parameter list sizes do not match the number of stages. '
'Check your config file.')
return None
def train(rank, world_size, args):
"""Entry point for training a single selected model.
Args:
rank :
Local GPU index.
world_size :
Number of used GPUs.
args : ``dict``
Parsed CLI arguments.
"""
# return reference to the user selected model constructor
Model, Loss, SegmentGenerator, Statistics = pick_model(args)
# perform common setup around the model's black box
model, loss, segment_generator, statistics, train_dataloader, val_dataloader, args = setup(Model, Loss, SegmentGenerator, Statistics, rank, world_size, args)
# list metrics that Processor should record
metrics = [
F1Score(rank, args.arch['num_classes'], args.processor['iou_threshold']),
EditScore(rank, args.arch['num_classes']),
ConfusionMatrix(rank, args.arch['num_classes'])]
# construct a processing wrapper
processor = Processor(rank, world_size, model, loss, statistics, segment_generator, metrics)
# perform the training
# (the model is trained on all skeletons in the scene, simultaneously)
processor.train(
train_dataloader=train_dataloader,
val_dataloader=val_dataloader,
proc_conf=args.processor,
optim_conf=args.optimizer,
job_conf=args.job)
# copy over resulting files of interest into the $VSC_DATA persistent storage
if args.processor.get('backup'):
for f in [
'accuracy-curve.csv',
'train-validation-curve.csv',
'final.pt',
'accuracy.csv',
'edit.csv',
'confusion-matrix.csv',
*['segmentation-{0}.csv'.format(i) for i in args.processor['demo']]]:
os.system('cp {0}/{1} {2}'.format(args.processor['save_dir'], f, args.processor['backup_dir']))
os.system(
'mail -s "[{0}]: COMPLETED" {1} <<< ""'
.format(
args.job['jobname'],
args.job['email']))
# perform common cleanup
cleanup(args)
return None
def test(rank, world_size, args):
"""Entry point for testing performance of a single pretrained model.
Args:
rank :
Local GPU index.
world_size :
Number of used GPUs.
args : ``dict``
Parsed CLI arguments.
"""
# return reference to the user selected model constructor
Model, Loss, SegmentGenerator, Statistics = pick_model(args)
# perform common setup around the model's black box
model, loss, segment_generator, statistics, train_dataloader, val_dataloader, args = setup(Model, Loss, SegmentGenerator, Statistics, rank, world_size, args)
# list metrics that Processor should record
metrics = [
F1Score(rank, args.arch['num_classes'], args.processor['iou_threshold']),
EditScore(rank, args.arch['num_classes']),
ConfusionMatrix(rank, args.arch['num_classes'])]
# construct a processing wrapper
processor = Processor(rank, world_size, model, loss, statistics, segment_generator, metrics)
# perform the testing
processor.test(
dataloader=val_dataloader,
proc_conf=args.processor,
job_conf=args.job)
# copy over resulting files of interest into the $VSC_DATA persistent storage
if args.processor.get('backup'):
for f in [
'accuracy.csv',
'edit.csv',
'confusion-matrix.csv',
*['segmentation-{0}.csv'.format(i) for i in args.processor['demo']]]:
os.system('cp {0}/{1} {2}'.format(args.processor['save_dir'], f, args.processor['backup_dir']))
os.system(
'mail -s "[{0}]: COMPLETED" {1} <<< ""'
.format(
args.job['jobname'],
args.job['email']))
# perform common cleanup
cleanup(args)
return None
def benchmark(rank, world_size, args):
"""Entry point for benchmarking inference of a model, including quantization.
TODO: add custom quantization conversion modules for other models
Args:
rank :
Local GPU index.
world_size :
Number of used GPUs.
args : ``dict``
Parsed CLI arguments.
"""
# return reference to the user selected model constructor
Model, Loss, SegmentGenerator, Statistics = pick_model(args)
# perform common setup around the model's black box
model, loss, segment_generator, statistics, train_dataloader, val_dataloader, args = setup(Model, Loss, SegmentGenerator, Statistics, rank, world_size, args)
# list metrics that Processor should record
metrics = [
F1Score(rank, args.arch['num_classes'], args.processor['iou_threshold']),
EditScore(rank, args.arch['num_classes']),
ConfusionMatrix(rank, args.arch['num_classes'])]
# construct a processing wrapper
processor = Processor(rank, world_size, model, loss, statistics, segment_generator, metrics)
# perform the testing
processor.benchmark(
dataloader=val_dataloader,
proc_conf=args.processor,
arch_conf=args.arch,
job_conf=args.job)
if args.processor.get('backup'):
for f in [
'accuracy.csv',
'loss.csv',
'edit.csv',
'latency.csv',
'model-size.csv',
'confusion-matrix_fp32.csv',
'confusion-matrix_int8.csv',
*['segmentation-{0}_fp32.csv'.format(i) for i in args.processor['demo']],
*['segmentation-{0}_int8.csv'.format(i) for i in args.processor['demo']]]:
os.system('cp {0}/{1} {2}'.format(args.processor['save_dir'], f, args.processor['backup_dir']))
os.system(
'mail -s "[{0}]: COMPLETED" {1} <<< ""'
.format(
args.job['jobname'],
args.job['email']))
# perform common cleanup
cleanup(args)
return None
def main(args):
"""Entrypoint into the script that routes to the correct function."""
# check user inputs using user logic
assert_parameters(args)
# setting up random number generator for deterministic and meaningful benchmarking
device = torch.device("cuda:0" if torch.cuda.is_available() else "cpu")
world_size = torch.cuda.device_count()
random.seed(args.optimizer['seed'])
torch.manual_seed(args.optimizer['seed'])
torch.cuda.manual_seed_all(args.optimizer['seed'])
torch.backends.cudnn.deterministic = True
# enter the appropriate command
args.func(device, (1 if world_size in [None, 0] else world_size), args)
return None
if __name__ == '__main__':
# top-level custom CLI parser ->
parser = Parser(
prog='main',
description="""Script for continual human action recognition model processing.
\nSupports: {{{0}}}""".format('|'.join(MODELS.keys())),
epilog='Maxim Yudayev ([email protected])')
subparsers= parser.add_subparsers(
title='commands',
dest='command',
required=True)
# train command parser
parser_train = subparsers.add_parser(
'train',
usage="""%(prog)s [-h]
\r\t[--config FILE]""",
help='train target continual HAR network',
epilog='Maxim Yudayev ([email protected])')
parser_train.add_argument(
'--config',
type=str,
default='config/pku-mmd/stgcn_local.json',
metavar='',
help='path to the NN config file. Must be the last argument if combined '
'with other CLI arguments. Provides default values for all arguments, except --log '
'(default: config/pku-mmd/stgcn_local.json)')
# test command parser
parser_test = subparsers.add_parser(
'test',
usage="""%(prog)s\n\t[-h]
\r\t[--config FILE]""",
help='test target continual HAR network',
epilog='Maxim Yudayev ([email protected])')
parser_test.add_argument(
'--config',
type=str,
default='config/pku-mmd/stgcn_local.json',
metavar='',
help='path to the NN config file. Must be the last argument if combined '
'with other CLI arguments. Provides default values for all arguments, except --log '
'(default: config/pku-mmd/stgcn_local.json)')
# benchmark command parser
parser_benchmark = subparsers.add_parser(
'benchmark',
usage="""%(prog)s\n\t[-h]
\r\t[--config FILE]""",
help='benchmark target ST-GCN network (accuracy, scores, latency).',
epilog='Maxim Yudayev ([email protected])')
parser_benchmark.add_argument(
'--config',
type=str,
default='config/pku-mmd/stgcn_local.json',
metavar='',
help='path to the NN config file. Must be the last argument if combined '
'with other CLI arguments. Provides default values for all arguments, except --log '
'(default: config/pku-mmd/stgcn_local.json)')
parser_train.set_defaults(func=train)
parser_test.set_defaults(func=test)
parser_benchmark.set_defaults(func=benchmark)
# parse the arguments
main(parser.parse_args())