forked from analogdevicesinc/ai8x-training
-
Notifications
You must be signed in to change notification settings - Fork 0
/
train.py
executable file
·1619 lines (1397 loc) · 73.3 KB
/
train.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
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#!/usr/bin/env python3
###################################################################################################
#
# Copyright (C) 2019-2021 Maxim Integrated Products, Inc. All Rights Reserved.
#
# Maxim Integrated Products, Inc. Default Copyright Notice:
# https://www.maximintegrated.com/en/aboutus/legal/copyrights.html
#
###################################################################################################
#
# Portions Copyright (c) 2018 Intel Corporation
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
"""This is an example application for compressing image classification models.
The application borrows its main flow code from torchvision's ImageNet classification
training sample application (https://github.com/pytorch/examples/tree/master/imagenet).
We tried to keep it similar, in order to make it familiar and easy to understand.
Integrating compression is very simple: simply add invocations of the appropriate
compression_scheduler callbacks, for each stage in the training. The training skeleton
looks like the pseudo code below. The boiler-plate Pytorch classification training
is speckled with invocations of CompressionScheduler.
For each epoch:
compression_scheduler.on_epoch_begin(epoch)
train()
validate()
save_checkpoint()
compression_scheduler.on_epoch_end(epoch)
train():
For each training step:
compression_scheduler.on_minibatch_begin(epoch)
output = model(input)
loss = criterion(output, target)
compression_scheduler.before_backward_pass(epoch)
loss.backward()
compression_scheduler.before_parameter_optimization(epoch)
optimizer.step()
compression_scheduler.on_minibatch_end(epoch)
This example application can be used with torchvision's ImageNet image classification
models, or with the provided sample models:
- ResNet for CIFAR: https://github.com/junyuseu/pytorch-cifar-models
- MobileNet for ImageNet: https://github.com/marvis/pytorch-mobilenet
"""
import copy
import fnmatch
import logging
import operator
import os
import sys
import time
import traceback
from collections import OrderedDict
from functools import partial
from pydoc import locate
import numpy as np
import matplotlib
from pkg_resources import parse_version
# TensorFlow 2.x compatibility
try:
import tensorboard # pylint: disable=import-error
import tensorflow # pylint: disable=import-error
tensorflow.io.gfile = tensorboard.compat.tensorflow_stub.io.gfile
except (ModuleNotFoundError, AttributeError):
pass
import torch
import torch.nn.parallel
import torch.optim
import torch.utils.data
from torch import nn
from torch.backends import cudnn
# pylint: disable=wrong-import-order
import distiller
import examples.auto_compression.amc as adc
import shap
import torchnet.meter as tnt
from distiller import apputils, model_summaries
from distiller.data_loggers import PythonLogger, TensorBoardLogger
# pylint: disable=no-name-in-module
from distiller.data_loggers.collector import (QuantCalibrationStatsCollector,
RecordsActivationStatsCollector,
SummaryActivationStatsCollector, collectors_context)
from distiller.quantization.range_linear import PostTrainLinearQuantizer
# pylint: enable=no-name-in-module
import ai8x
import ai8x_nas
import datasets
import nnplot
import parse_qat_yaml
import parsecmd
import sample
from nas import parse_nas_yaml
# from range_linear_ai84 import PostTrainLinearQuantizerAI84
matplotlib.use("pgf")
# Logger handle
msglogger = None
# Globals
weight_min = None
weight_max = None
weight_count = None
weight_sum = None
weight_stddev = None
weight_mean = None
def main():
"""main"""
script_dir = os.path.dirname(__file__)
global msglogger # pylint: disable=global-statement
supported_models = []
supported_sources = []
model_names = []
dataset_names = []
# Dynamically load models
for _, _, files in sorted(os.walk('models')):
for name in sorted(files):
if fnmatch.fnmatch(name, '*.py'):
fn = 'models.' + name[:-3]
m = locate(fn)
try:
for i in m.models:
i['module'] = fn
supported_models += m.models
model_names += [item['name'] for item in m.models]
except AttributeError:
# Skip files that don't have 'models' or 'models.name'
pass
# Dynamically load datasets
for _, _, files in sorted(os.walk('datasets')):
for name in sorted(files):
if fnmatch.fnmatch(name, '*.py'):
ds = locate('datasets.' + name[:-3])
try:
supported_sources += ds.datasets
dataset_names += [item['name'] for item in ds.datasets]
except AttributeError:
# Skip files that don't have 'datasets' or 'datasets.name'
pass
# Parse arguments
args = parsecmd.get_parser(model_names, dataset_names).parse_args()
# Set hardware device
ai8x.set_device(args.device, args.act_mode_8bit, args.avg_pool_rounding)
if args.epochs is None:
args.epochs = 90
if not os.path.exists(args.output_dir):
os.makedirs(args.output_dir)
if args.shap > 0:
args.batch_size = 100 + args.shap
if args.optimizer is None:
if not args.evaluate:
print('WARNING: --optimizer not set, selecting SGD.')
args.optimizer = 'SGD'
if args.lr is None:
if not args.evaluate:
print('WARNING: Initial learning rate (--lr) not set, selecting 0.1.')
args.lr = 0.1
msglogger = apputils.config_pylogger(os.path.join(script_dir, 'logging.conf'), args.name,
args.output_dir)
# Log various details about the execution environment. It is sometimes useful
# to refer to past experiment executions and this information may be useful.
apputils.log_execution_env_state(args.compress, msglogger.logdir)
msglogger.debug("Distiller: %s", distiller.__version__)
start_epoch = 0
ending_epoch = args.epochs
perf_scores_history = []
if args.evaluate and args.shap == 0:
args.deterministic = True
if args.deterministic:
# torch.set_deterministic(True)
distiller.set_deterministic(args.seed) # For experiment reproducability
if args.seed is not None:
distiller.set_seed(args.seed)
else:
# Turn on CUDNN benchmark mode for best performance. This is usually "safe" for image
# classification models, as the input sizes don't change during the run
# See here:
# https://discuss.pytorch.org/t/what-does-torch-backends-cudnn-benchmark-do/5936/3
cudnn.benchmark = True
if args.cpu or not torch.cuda.is_available():
if not args.cpu:
# Print warning if no hardware acceleration
print("WARNING: CUDA hardware acceleration is not available, training will be slow")
# Set GPU index to -1 if using CPU
args.device = 'cpu'
args.gpus = -1
else:
args.device = 'cuda'
if args.gpus is not None:
try:
args.gpus = [int(s) for s in args.gpus.split(',')]
except ValueError as exc:
raise ValueError('ERROR: Argument --gpus must be a comma-separated '
'list of integers only') from exc
available_gpus = torch.cuda.device_count()
for dev_id in args.gpus:
if dev_id >= available_gpus:
raise ValueError(f'ERROR: GPU device ID {dev_id} requested, but only '
f'{available_gpus} devices available')
# Set default device in case the first one on the list != 0
torch.cuda.set_device(args.gpus[0])
if args.earlyexit_thresholds:
args.num_exits = len(args.earlyexit_thresholds) + 1
args.loss_exits = [0] * args.num_exits
args.losses_exits = []
args.exiterrors = []
selected_source = next((item for item in supported_sources if item['name'] == args.dataset))
args.labels = selected_source['output']
args.num_classes = len(args.labels)
if args.num_classes == 1 \
or ('regression' in selected_source and selected_source['regression']):
args.regression = True
dimensions = selected_source['input']
if len(dimensions) == 2:
dimensions += (1, )
args.dimensions = dimensions
args.datasets_fn = selected_source['loader']
args.visualize_fn = selected_source['visualize'] \
if 'visualize' in selected_source else datasets.visualize_data
if args.regression and args.display_confusion:
raise ValueError('ERROR: Argument --confusion cannot be used with regression')
if args.regression and args.display_prcurves:
raise ValueError('ERROR: Argument --pr-curves cannot be used with regression')
if args.regression and args.display_embedding:
raise ValueError('ERROR: Argument --embedding cannot be used with regression')
model = create_model(supported_models, dimensions, args)
# if args.add_logsoftmax:
# model = nn.Sequential(model, nn.LogSoftmax(dim=1))
# if args.add_softmax:
# model = nn.Sequential(model, nn.Softmax(dim=1))
compression_scheduler = None
# Create a couple of logging backends. TensorBoardLogger writes log files in a format
# that can be read by Google's Tensor Board. PythonLogger writes to the Python logger.
pylogger = PythonLogger(msglogger, log_1d=True)
all_loggers = [pylogger]
if args.tblog:
tflogger = TensorBoardLogger(msglogger.logdir, log_1d=True, comment='_'+args.dataset)
tflogger.tblogger.writer.add_text('Command line', str(args))
if dimensions[2] > 1:
dummy_input = torch.randn((1, ) + dimensions)
else: # 1D input
dummy_input = torch.randn((1, ) + dimensions[:-1])
tflogger.tblogger.writer.add_graph(model.to('cpu'), (dummy_input, ), False)
all_loggers.append(tflogger)
all_tbloggers = [tflogger]
else:
tflogger = None
all_tbloggers = []
# Capture thresholds for early-exit training
if args.earlyexit_thresholds:
msglogger.info('=> using early-exit threshold values of %s', args.earlyexit_thresholds)
# Get policy for quantization aware training
qat_policy = parse_qat_yaml.parse(args.qat_policy) \
if args.qat_policy.lower() != "none" else None
# Get policy for once for all training policy
nas_policy = parse_nas_yaml.parse(args.nas_policy) \
if args.nas and args.nas_policy.lower() != '' else None
# We can optionally resume from a checkpoint
optimizer = None
if args.resumed_checkpoint_path:
update_old_model_params(args.resumed_checkpoint_path, model)
if qat_policy is not None:
checkpoint = torch.load(args.resumed_checkpoint_path,
map_location=lambda storage, loc: storage)
# pylint: disable=unsubscriptable-object
if checkpoint.get('epoch', None) >= qat_policy['start_epoch']:
ai8x.fuse_bn_layers(model)
# pylint: enable=unsubscriptable-object
model, compression_scheduler, optimizer, start_epoch = apputils.load_checkpoint(
model, args.resumed_checkpoint_path, model_device=args.device)
ai8x.update_model(model)
elif args.load_model_path:
update_old_model_params(args.load_model_path, model)
if qat_policy is not None:
checkpoint = torch.load(args.load_model_path,
map_location=lambda storage, loc: storage)
# pylint: disable=unsubscriptable-object
if checkpoint.get('epoch', None) >= qat_policy['start_epoch']:
ai8x.fuse_bn_layers(model)
# pylint: enable=unsubscriptable-object
model = apputils.load_lean_checkpoint(model, args.load_model_path,
model_device=args.device)
ai8x.update_model(model)
if not args.load_serialized and args.gpus != -1 and torch.cuda.device_count() > 1:
model = torch.nn.DataParallel(model, device_ids=args.gpus).to(args.device)
if args.reset_optimizer:
start_epoch = 0
if optimizer is not None:
optimizer = None
msglogger.info('\nreset_optimizer flag set: Overriding resumed optimizer and '
'resetting epoch count to 0')
# Define loss function (criterion)
if not args.regression:
if 'weight' in selected_source:
criterion = nn.CrossEntropyLoss(
torch.Tensor(selected_source['weight'])
).to(args.device)
else:
criterion = nn.CrossEntropyLoss().to(args.device)
else:
criterion = nn.MSELoss().to(args.device)
if optimizer is None:
optimizer = create_optimizer(model, args)
msglogger.info('Optimizer Type: %s', type(optimizer))
msglogger.info('Optimizer Args: %s', optimizer.defaults)
if args.amc_cfg_file:
return automated_deep_compression(model, criterion, optimizer, pylogger, args)
if args.greedy:
return greedy(model, criterion, optimizer, pylogger, args)
# This sample application can be invoked to produce various summary reports.
if args.summary:
return summarize_model(model, args.dataset, which_summary=args.summary,
filename=args.summary_filename)
activations_collectors = create_activation_stats_collectors(model, *args.activation_stats)
if args.qe_calibration:
msglogger.info('Quantization calibration stats collection enabled:')
msglogger.info('\tStats will be collected for %.1f%% of test dataset', args.qe_calibration)
msglogger.info('\tSetting constant seeds and converting model to serialized execution')
distiller.set_deterministic()
model = distiller.make_non_parallel_copy(model)
activations_collectors.update(create_quantization_stats_collector(model))
args.evaluate = True
args.effective_test_size = args.qe_calibration
# Load the datasets
train_loader, val_loader, test_loader, _ = apputils.get_data_loaders(
args.datasets_fn, (os.path.expanduser(args.data), args), args.batch_size,
args.workers, args.validation_split, args.deterministic,
args.effective_train_size, args.effective_valid_size, args.effective_test_size)
msglogger.info('Dataset sizes:\n\ttraining=%d\n\tvalidation=%d\n\ttest=%d',
len(train_loader.sampler), len(val_loader.sampler), len(test_loader.sampler))
if args.sensitivity is not None:
sensitivities = np.arange(args.sensitivity_range[0], args.sensitivity_range[1],
args.sensitivity_range[2])
return sensitivity_analysis(model, criterion, test_loader, pylogger, args, sensitivities)
if args.evaluate:
return evaluate_model(model, criterion, test_loader, pylogger, activations_collectors,
args, compression_scheduler)
if args.compress:
# The main use-case for this sample application is CNN compression. Compression
# requires a compression schedule configuration file in YAML.
compression_scheduler = distiller.file_config(model, optimizer, args.compress,
compression_scheduler,
(start_epoch-1)
if args.resumed_checkpoint_path else None)
elif compression_scheduler is None:
compression_scheduler = distiller.CompressionScheduler(model)
# Model is re-transferred to GPU in case parameters were added (e.g. PACTQuantizer)
model.to(args.device)
if args.thinnify:
# zeros_mask_dict = distiller.create_model_masks_dict(model)
assert args.resumed_checkpoint_path is not None, \
"You must use --resume-from to provide a checkpoint file to thinnify"
distiller.remove_filters(model, compression_scheduler.zeros_mask_dict, args.cnn,
args.dataset, optimizer=None)
apputils.save_checkpoint(0, args.cnn, model, optimizer=None,
scheduler=compression_scheduler,
name=f'{args.resumed_checkpoint_path.replace(".pth.tar", "")}'
'_thinned',
dir=msglogger.logdir)
print("Note: your model may have collapsed to random inference, "
"so you may want to fine-tune")
return None
args.kd_policy = None
if args.kd_teacher:
teacher = create_model(supported_models, dimensions, args)
if args.kd_resume:
teacher = apputils.load_lean_checkpoint(teacher, args.kd_resume)
dlw = distiller.DistillationLossWeights(args.kd_distill_wt, args.kd_student_wt,
args.kd_teacher_wt)
args.kd_policy = distiller.KnowledgeDistillationPolicy(model, teacher, args.kd_temp, dlw)
compression_scheduler.add_policy(args.kd_policy, starting_epoch=args.kd_start_epoch,
ending_epoch=args.epochs, frequency=1)
msglogger.info('\nStudent-Teacher knowledge distillation enabled:')
msglogger.info('\tTeacher Model: %s', args.kd_teacher)
msglogger.info('\tTemperature: %s', args.kd_temp)
msglogger.info('\tLoss Weights (distillation | student | teacher): %s',
' | '.join([f'{val:.2f}' for val in dlw]))
msglogger.info('\tStarting from Epoch: %d', args.kd_start_epoch)
if start_epoch >= ending_epoch:
msglogger.error('epoch count is too low, starting epoch is %d but total epochs set '
'to %d', start_epoch, ending_epoch)
raise ValueError('Epochs parameter is too low. Nothing to do.')
if args.nas:
assert isinstance(model, ai8x_nas.OnceForAllModel), 'Model should implement ' \
'OnceForAllModel interface for NAS training!'
if nas_policy:
args.nas_stage_transition_list = create_nas_training_stage_list(model, nas_policy)
# pylint: disable=unsubscriptable-object
args.nas_kd_params = nas_policy['kd_params'] \
if nas_policy and 'kd_params' in nas_policy else None
# pylint: enable=unsubscriptable-object
if args.nas_kd_resume_from == '':
args.nas_kd_policy = None
else:
if args.nas_kd_params['teacher_model'] == 'full_model':
kd_end_epoch = args.epochs
else:
kd_end_epoch = get_next_stage_start_epoch(start_epoch,
args.nas_stage_transition_list,
args.epochs)
create_nas_kd_policy(model, compression_scheduler, start_epoch, kd_end_epoch, args)
vloss = 10**6
for epoch in range(start_epoch, ending_epoch):
# pylint: disable=unsubscriptable-object
if qat_policy is not None and epoch > 0 and epoch == qat_policy['start_epoch']:
# Fuse the BN parameters into conv layers before Quantization Aware Training (QAT)
ai8x.fuse_bn_layers(model)
# Switch model from unquantized to quantized for QAT
ai8x.initiate_qat(model, qat_policy)
# Model is re-transferred to GPU in case parameters were added
model.to(args.device)
# Empty the performance scores list for QAT operation
perf_scores_history = []
if args.name:
args.name = f'{args.name}_qat'
else:
args.name = 'qat'
# pylint: enable=unsubscriptable-object
# This is the main training loop.
msglogger.info('\n')
if compression_scheduler:
compression_scheduler.on_epoch_begin(epoch, metrics=vloss)
# Train for one epoch
with collectors_context(activations_collectors["train"]) as collectors:
train(train_loader, model, criterion, optimizer, epoch, compression_scheduler,
loggers=all_loggers, args=args)
# distiller.log_weights_sparsity(model, epoch, loggers=all_loggers)
distiller.log_activation_statistics(epoch, "train", loggers=all_tbloggers,
collector=collectors["sparsity"])
if args.masks_sparsity:
msglogger.info(distiller.masks_sparsity_tbl_summary(model, compression_scheduler))
# evaluate on validation set
# pylint: disable=unsubscriptable-object
run_validation = not args.nas or (args.nas and (epoch < nas_policy['start_epoch']))
run_nas_validation = args.nas and (epoch >= nas_policy['start_epoch']) and \
((epoch+1) % nas_policy['validation_freq'] == 0)
# pylint: enable=unsubscriptable-object
if run_validation or run_nas_validation:
checkpoint_name = args.name
# run pre validation steps if NAS is running
if run_nas_validation:
update_bn_stats(train_loader, model, args)
stage, level = get_nas_training_stage(epoch, args.nas_stage_transition_list)
if args.name:
checkpoint_name = f'{args.name}_nas_stg{stage}_lev{level}'
else:
checkpoint_name = f'nas_stg{stage}_lev{level}'
with collectors_context(activations_collectors["valid"]) as collectors:
top1, top5, vloss = validate(val_loader, model, criterion, [pylogger], args, epoch,
tflogger)
distiller.log_activation_statistics(epoch, "valid", loggers=all_tbloggers,
collector=collectors["sparsity"])
save_collectors_data(collectors, msglogger.logdir)
if not args.regression:
stats = ('Performance/Validation/', OrderedDict([('Loss', vloss), ('Top1', top1)]))
if args.num_classes > 5:
stats[1]['Top5'] = top5
else:
stats = ('Performance/Validation/', OrderedDict([('Loss', vloss), ('MSE', top1)]))
distiller.log_training_progress(stats, None, epoch, steps_completed=0, total_steps=1,
log_freq=1, loggers=all_tbloggers)
# Update the list of top scores achieved so far
update_training_scores_history(perf_scores_history, model, top1, top5, epoch, args)
# Save the checkpoint
if run_validation:
is_best = epoch == perf_scores_history[0].epoch
checkpoint_extras = {'current_top1': top1,
'best_top1': perf_scores_history[0].top1,
'best_epoch': perf_scores_history[0].epoch}
else:
is_best = False
checkpoint_extras = {'current_top1': top1}
apputils.save_checkpoint(epoch, args.cnn, model, optimizer=optimizer,
scheduler=compression_scheduler, extras=checkpoint_extras,
is_best=is_best, name=checkpoint_name,
dir=msglogger.logdir)
if compression_scheduler:
compression_scheduler.on_epoch_end(epoch, optimizer)
# Finally run results on the test set
test(test_loader, model, criterion, [pylogger], activations_collectors, args=args)
return None
OVERALL_LOSS_KEY = 'Overall Loss'
OBJECTIVE_LOSS_KEY = 'Objective Loss'
def create_model(supported_models, dimensions, args):
"""Create the model"""
module = next(item for item in supported_models if item['name'] == args.cnn)
# Override distiller's input shape detection. This is not a very clean way to do it since
# we're replacing a protected member.
distiller.utils._validate_input_shape = ( # pylint: disable=protected-access
lambda _a, _b: (1, ) + dimensions[:module['dim'] + 1]
)
Model = locate(module['module'] + '.' + args.cnn)
if not Model:
raise RuntimeError("Model " + args.cnn + " not found\n")
# Set model paramaters
if args.act_mode_8bit:
weight_bits = 8
bias_bits = 8
quantize_activation = True
else:
weight_bits = None
bias_bits = None
quantize_activation = False
if module['dim'] > 1 and module['min_input'] > dimensions[2]:
model = Model(pretrained=False, num_classes=args.num_classes,
num_channels=dimensions[0],
dimensions=(dimensions[1], dimensions[2]),
padding=(module['min_input'] - dimensions[2] + 1) // 2,
bias=args.use_bias,
weight_bits=weight_bits,
bias_bits=bias_bits,
quantize_activation=quantize_activation).to(args.device)
else:
model = Model(pretrained=False, num_classes=args.num_classes,
num_channels=dimensions[0],
dimensions=(dimensions[1], dimensions[2]),
bias=args.use_bias,
weight_bits=weight_bits,
bias_bits=bias_bits,
quantize_activation=quantize_activation).to(args.device)
return model
def create_optimizer(model, args):
"""Create the optimizer"""
if args.optimizer.lower() == 'sgd':
optimizer = torch.optim.SGD(model.parameters(), lr=args.lr, momentum=args.momentum,
weight_decay=args.weight_decay)
elif args.optimizer.lower() == 'adam':
optimizer = torch.optim.Adam(model.parameters(), lr=args.lr)
else:
msglogger.info('Unknown optimizer type: %s. SGD is set as optimizer!!!', args.optimizer)
optimizer = torch.optim.SGD(model.parameters(), lr=args.lr, momentum=args.momentum,
weight_decay=args.weight_decay)
return optimizer
def create_nas_kd_policy(model, compression_scheduler, epoch, next_state_start_epoch, args):
"""Create knowledge distillation policy for nas"""
teacher = copy.deepcopy(model)
dlw = distiller.DistillationLossWeights(args.nas_kd_params['distill_loss'],
args.nas_kd_params['student_loss'], 0)
args.nas_kd_policy = distiller.KnowledgeDistillationPolicy(model, teacher,
args.nas_kd_params['temperature'],
dlw)
compression_scheduler.add_policy(args.nas_kd_policy, starting_epoch=epoch,
ending_epoch=next_state_start_epoch, frequency=1)
msglogger.info('\nStudent-Teacher knowledge distillation enabled for NAS:')
msglogger.info('\tStart Epoch: %d, End Epoch: %d', epoch, next_state_start_epoch)
msglogger.info('\tTemperature: %s', args.nas_kd_params['temperature'])
msglogger.info("\tLoss Weights (distillation | student | teacher): %s",
' | '.join([f'{val:.2f}' for val in dlw]))
def train(train_loader, model, criterion, optimizer, epoch,
compression_scheduler, loggers, args):
"""Training loop for one epoch."""
losses = OrderedDict([(OVERALL_LOSS_KEY, tnt.AverageValueMeter()),
(OBJECTIVE_LOSS_KEY, tnt.AverageValueMeter())])
if not args.regression:
classerr = tnt.ClassErrorMeter(accuracy=True, topk=(1, min(args.num_classes, 5)))
else:
classerr = tnt.MSEMeter()
batch_time = tnt.AverageValueMeter()
data_time = tnt.AverageValueMeter()
# For Early Exit, we define statistics for each exit
# So exiterrors is analogous to classerr for the non-Early Exit case
if args.earlyexit_lossweights:
args.exiterrors = []
for exitnum in range(args.num_exits):
if not args.regression:
args.exiterrors.append(tnt.ClassErrorMeter(accuracy=True, topk=(1, 5)))
else:
args.exiterrors.append(tnt.MSEMeter())
total_samples = len(train_loader.sampler)
batch_size = train_loader.batch_size
steps_per_epoch = (total_samples + batch_size - 1) // batch_size
msglogger.info('Training epoch: %d samples (%d per mini-batch)', total_samples, batch_size)
if args.nas:
if args.nas_stage_transition_list is not None:
stage, level = get_nas_training_stage(epoch, args.nas_stage_transition_list)
prev_stage, _ = get_nas_training_stage(epoch-1, args.nas_stage_transition_list)
else:
stage = prev_stage = 0
level = 0
if prev_stage != stage:
if args.nas_kd_params:
if ('teacher_model' not in args.nas_kd_params) or \
('teacher_model' in args.nas_kd_params and
args.nas_kd_params['teacher_model'] == 'full_model' and prev_stage == 0):
create_nas_kd_policy(model, compression_scheduler, epoch, args.epochs, args)
elif 'teacher_model' in args.nas_kd_params and \
args.nas_kd_params['teacher_model'] == 'prev_stage_model':
next_stage_start_epoch = get_next_stage_start_epoch(
epoch, args.nas_stage_transition_list, args.epochs)
create_nas_kd_policy(model, compression_scheduler, epoch,
next_stage_start_epoch, args)
# Switch to train mode
model.train()
acc_stats = []
end = time.time()
for train_step, (inputs, target) in enumerate(train_loader):
# Measure data loading time
data_time.add(time.time() - end)
inputs, target = inputs.to(args.device), target.to(args.device)
# Set nas parameters if necessary
if args.nas:
if stage == 1:
ai8x_nas.sample_subnet_kernel(model, level)
elif stage == 2:
ai8x_nas.sample_subnet_depth(model, level)
elif stage == 3:
ai8x_nas.sample_subnet_width(model, level)
# Execute the forward phase, compute the output and measure loss
if compression_scheduler:
compression_scheduler.on_minibatch_begin(epoch, train_step, steps_per_epoch, optimizer)
if not hasattr(args, 'kd_policy') or args.kd_policy is None:
if not hasattr(args, 'nas_kd_policy') or args.nas_kd_policy is None:
output = model(inputs)
else:
output = args.nas_kd_policy.forward(inputs)
else:
output = args.kd_policy.forward(inputs)
if not args.earlyexit_lossweights:
loss = criterion(output, target)
# Measure accuracy if the conditions are set. For `Last Batch` only accuracy
# calculateion last two batches are used as the last batch might include just a few
# samples.
if args.show_train_accuracy == 'full' or \
(args.show_train_accuracy == 'last_batch' and train_step >= len(train_loader)-2):
if len(output.data.shape) <= 2:
classerr.add(output.data, target)
else:
classerr.add(output.data.permute(0, 2, 3, 1).flatten(start_dim=0, end_dim=2),
target.flatten())
if not args.regression:
acc_stats.append([classerr.value(1), classerr.value(min(args.num_classes, 5))])
else:
acc_stats.append([classerr.value()])
else:
# Measure accuracy and record loss
loss = earlyexit_loss(output, target, criterion, args)
# Record loss
losses[OBJECTIVE_LOSS_KEY].add(loss.item())
if compression_scheduler:
# Before running the backward phase, we allow the scheduler to modify the loss
# (e.g. add regularization loss)
agg_loss = compression_scheduler.before_backward_pass(epoch, train_step,
steps_per_epoch, loss,
optimizer=optimizer,
return_loss_components=True)
loss = agg_loss.overall_loss
losses[OVERALL_LOSS_KEY].add(loss.item())
for lc in agg_loss.loss_components:
if lc.name not in losses:
losses[lc.name] = tnt.AverageValueMeter()
losses[lc.name].add(lc.value.item())
else:
losses[OVERALL_LOSS_KEY].add(loss.item())
# Compute the gradient and do SGD step
optimizer.zero_grad()
loss.backward()
if compression_scheduler:
compression_scheduler.before_parameter_optimization(epoch, train_step,
steps_per_epoch, optimizer)
optimizer.step()
if compression_scheduler:
compression_scheduler.on_minibatch_end(epoch, train_step, steps_per_epoch, optimizer)
# Reset elastic sampling wrt NAS stage if necessary
if args.nas:
if stage == 1:
ai8x_nas.reset_kernel_sampling(model)
elif stage == 2:
ai8x_nas.reset_depth_sampling(model)
elif stage == 3:
ai8x_nas.reset_width_sampling(model)
# measure elapsed time
batch_time.add(time.time() - end)
steps_completed = (train_step+1)
if steps_completed % args.print_freq == 0 or steps_completed == steps_per_epoch:
# Log some statistics
errs = OrderedDict()
if not args.earlyexit_lossweights:
if not args.regression:
if classerr.n != 0:
errs['Top1'] = classerr.value(1)
if args.num_classes > 5:
errs['Top5'] = classerr.value(5)
else:
errs['Top1'] = None
errs['Top5'] = None
else:
if classerr.n != 0:
errs['MSE'] = classerr.value()
else:
errs['MSE'] = None
else:
# for Early Exit case, the Top1 and Top5 stats are computed for each exit.
for exitnum in range(args.num_exits):
if not args.regression:
errs['Top1_exit' + str(exitnum)] = args.exiterrors[exitnum].value(1)
if args.num_classes > 5:
errs['Top5_exit' + str(exitnum)] = args.exiterrors[exitnum].value(5)
else:
errs['MSE_exit' + str(exitnum)] = args.exiterrors[exitnum].value()
stats_dict = OrderedDict()
for loss_name, meter in losses.items():
stats_dict[loss_name] = meter.mean
stats_dict.update(errs)
if args.nas:
stats_dict['NAS-Stage'] = stage
if stage != 0:
stats_dict['NAS-Level'] = level
stats_dict['LR'] = optimizer.param_groups[0]['lr']
stats_dict['Time'] = batch_time.mean
stats = ('Performance/Training/', stats_dict)
params = model.named_parameters() if args.log_params_histograms else None
distiller.log_training_progress(stats,
params,
epoch, steps_completed,
steps_per_epoch, args.print_freq,
loggers)
end = time.time()
return acc_stats
def update_bn_stats(train_loader, model, args):
"""Routine to update BatchNorm statistics"""
model.train()
for (inputs, target) in train_loader:
inputs, target = inputs.to(args.device), target.to(args.device)
_ = model(inputs)
def validate(val_loader, model, criterion, loggers, args, epoch=-1, tflogger=None):
"""Model validation"""
if epoch > -1:
msglogger.info('--- validate (epoch=%d)-----------', epoch)
else:
msglogger.info('--- validate ---------------------')
return _validate(val_loader, model, criterion, loggers, args, epoch, tflogger)
def test(test_loader, model, criterion, loggers, activations_collectors, args):
"""Model Test"""
msglogger.info('--- test ---------------------')
if activations_collectors is None:
activations_collectors = create_activation_stats_collectors(model, None)
with collectors_context(activations_collectors["test"]) as collectors:
top1, top5, losses = _validate(test_loader, model, criterion, loggers, args)
distiller.log_activation_statistics(-1, "test", loggers, collector=collectors['sparsity'])
if args.kernel_stats:
print("==> Kernel Stats")
with torch.no_grad():
global weight_min, weight_max, weight_count # pylint: disable=global-statement
global weight_sum, weight_stddev, weight_mean # pylint: disable=global-statement
weight_min = torch.Tensor(float('inf'))
weight_max = torch.Tensor(float('-inf'))
weight_count = torch.Tensor(0, dtype=torch.int)
weight_sum = torch.Tensor(0.0)
weight_stddev = torch.Tensor(0.0)
def traverse_pass1(m):
"""
Traverse model to build weight stats
"""
global weight_min, weight_max # pylint: disable=global-statement
global weight_count, weight_sum # pylint: disable=global-statement
if isinstance(m, nn.Conv2d):
weight_min = torch.min(torch.min(m.weight), weight_min)
weight_max = torch.max(torch.max(m.weight), weight_max)
weight_count += len(m.weight.flatten())
weight_sum += m.weight.flatten().sum()
if hasattr(m, 'bias') and m.bias is not None:
weight_min = torch.min(torch.min(m.bias), weight_min)
weight_max = torch.max(torch.max(m.bias), weight_max)
weight_count += len(m.bias.flatten())
weight_sum += m.bias.flatten().sum()
def traverse_pass2(m):
"""
Traverse model to build weight stats
"""
global weight_stddev # pylint: disable=global-statement
if isinstance(m, nn.Conv2d):
weight_stddev += ((m.weight.flatten() - weight_mean) ** 2).sum()
if hasattr(m, 'bias') and m.bias is not None:
weight_stddev += ((m.bias.flatten() - weight_mean) ** 2).sum()
model.apply(traverse_pass1)
weight_mean = weight_sum / weight_count
model.apply(traverse_pass2)
weight_stddev = torch.sqrt(weight_stddev / weight_count)
print(f"Total 2D kernel weights: {weight_count} --> min: {weight_min}, "
f"max: {weight_max}, stddev: {weight_stddev}")
save_collectors_data(collectors, msglogger.logdir)
return top1, top5, losses
def _validate(data_loader, model, criterion, loggers, args, epoch=-1, tflogger=None):
"""Execute the validation/test loop."""
losses = {'objective_loss': tnt.AverageValueMeter()}
if not args.regression:
classerr = tnt.ClassErrorMeter(accuracy=True, topk=(1, min(args.num_classes, 5)))
else:
classerr = tnt.MSEMeter()
def save_tensor(t, f, regression=True):
""" Save tensor `t` to file handle `f` in CSV format """
if t.dim() > 1:
if not regression:
t = torch.nn.functional.softmax(t, dim=1)
np.savetxt(f, t.reshape(t.shape[0], t.shape[1], -1).cpu().numpy().mean(axis=2),
delimiter=",")
else:
if regression:
np.savetxt(f, t.cpu().numpy(), delimiter=",")
else:
for _, i in enumerate(t):
f.write(f'{args.labels[i.int()]}\n')
if args.csv_prefix is not None:
with open(f'{args.csv_prefix}_ytrue.csv', mode='w', encoding='utf-8') as f_ytrue:
f_ytrue.write('truth\n')
with open(f'{args.csv_prefix}_ypred.csv', mode='w', encoding='utf-8') as f_ypred:
f_ypred.write(','.join(args.labels) + '\n')
with open(f'{args.csv_prefix}_x.csv', mode='w', encoding='utf-8') as f_x:
for i in range(args.dimensions[0]-1):
f_x.write(f'x_{i}_mean,')
f_x.write(f'x_{args.dimensions[0]-1}_mean\n')
if args.earlyexit_thresholds:
# for Early Exit, we have a list of errors and losses for each of the exits.
args.exiterrors = []
args.losses_exits = []
for exitnum in range(args.num_exits):
if not args.regression:
args.exiterrors.append(tnt.ClassErrorMeter(accuracy=True,
topk=(1, min(args.num_classes, 5))))
else:
args.exiterrors.append(tnt.MSEMeter())
args.losses_exits.append(tnt.AverageValueMeter())
args.exit_taken = [0] * args.num_exits
batch_time = tnt.AverageValueMeter()
total_samples = len(data_loader.sampler)
batch_size = data_loader.batch_size
if args.display_confusion:
confusion = tnt.ConfusionMeter(args.num_classes)
total_steps = (total_samples + batch_size - 1) // batch_size
msglogger.info('%d samples (%d per mini-batch)', total_samples, batch_size)
# Switch to evaluation mode
model.eval()
end = time.time()
class_probs = []
class_preds = []
for validation_step, (inputs, target) in enumerate(data_loader):
with torch.no_grad():
inputs, target = inputs.to(args.device), target.to(args.device)
# compute output from model
output = model(inputs)
# correct output for accurate loss calculation
if args.act_mode_8bit:
output /= 128.
for key in model.__dict__['_modules'].keys():
if (hasattr(model.__dict__['_modules'][key], 'wide')
and model.__dict__['_modules'][key].wide):
output /= 256.
if args.generate_sample is not None:
sample.generate(args.generate_sample, inputs, target, output, args.dataset, False)
return .0, .0, .0