-
Notifications
You must be signed in to change notification settings - Fork 0
/
manager.py
2696 lines (2269 loc) · 120 KB
/
manager.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
# PNN Library: Neural network manager
# Imports
import os
import gc
import re
import io
import csv
# noinspection PyCompatibility
import pwd
import sys
import math
import json
import yaml
import stat
import pickle
import base64
import hashlib
import os.path
import inspect
import argparse
import datetime
import platform
import itertools
import contextlib
import statistics
import subprocess
import collections
import dataclasses
from enum import Enum, auto
from typing import Any, Union, Tuple, Iterable, Callable, Dict
import portalocker
import torch
import torch.backends.cudnn
import ppyutil.git
import ppyutil.nvsmi
import ppyutil.objmanip
import ppyutil.interpreter
import ppyutil.contextman
import ppyutil.execlock
import ppyutil.filter
import ppyutil.pickle
import ppyutil.print
import ppyutil.string
import ppyutil.stdtee
from ppyutil.classes import EnumLU
from ppyutil.string import strtobool
from ppyutil.print import print_warn
from ppyutil.argparse import AppendData, IntRange
from pnnlib import config, yaml_spec, netmodel, dataset, training, GPUHardwareError
from pnnlib.training import loss_fmt, rloss_fmt
from pnnlib.util import system_info, device_util, tensor_util, model_util, misc_util
from pnnlib.util.device_util import GPULevel
# Conditionally import tensorwatch
try:
import tensorwatch
except ImportError:
tensorwatch = None
####################
### Enumerations ###
####################
# Context enumeration
class Context(Enum):
Process = auto()
Action = auto()
# Actions enumeration
class Action(Enum):
DebugArgs = auto()
LoadModel = auto()
KeepModel = auto()
ResetModel = auto()
ShowConfigs = auto()
ShowCSVFmts = auto()
GitSnapshot = auto()
ModelInfo = auto()
DrawModel = auto()
DatasetInfo = auto()
DatasetStats = auto()
Train = auto()
TrainAll = auto()
PerfModel = auto()
PerfModelOptim = auto()
# Configuration enumeration
class Configuration(Enum):
Default = auto()
NonDefault = auto()
All = auto()
# Learning rate scheduler arguments enumeration
class LRSchedulerArgs(Enum):
NoArgs = auto()
ValidLoss = auto()
MinRefValidLoss = auto()
# Dataset statistics basis
class DatasetStatsBasis(EnumLU):
Element = auto()
Sample = auto()
Batch = auto()
Default = Sample
#################
### Constants ###
#################
# Config parameter specifications
pnn_config_spec = {
'CudnnBenchmarkMode': bool, # Whether to use cuDNN benchmark mode (https://discuss.pytorch.org/t/what-does-torch-backends-cudnn-benchmark-do/5936, ignored and always false if deterministic)
'Deterministic': bool, # Whether all random number generation should be performed deterministically
'DeterministicSeed': int, # Seed to use for deterministic random number generation
'GPUTempLowPassTs': float, # Settling time to use for GPU temperature low pass filtering in units of epochs
'GPUTempSafetyMargin': float, # Safety margin for GPU overheating detection (if low-pass GPU temp exceeds this many degrees below hardware slowdown temperature then trigger overheating detection)
'RunLockEnterDelay': float, # Time interval to wait right after acquiring the lowest real run level lock or going solo
'RunLockMaxCountsCPU': tuple, # Maximum counts to use for device run level locking if the device is of type CPU
'RunLockMaxCountsGPU': tuple, # Maximum counts to use for device run level locking if the device is of type GPU
'TrainEpochs': int, # Number of epochs to train
'TrainPerf': bool, # Whether to evaluate the performance of model(s) resulting from training
'TrainPerfAllSaved': bool, # Whether to evaluate the performance of all (still existing) saved models or just the last one
'TrainPerfOptimise': bool, # Whether to optimise threshold hyperparameters in order to find the best possible model performance
'TrainLockFirstEpochs': int, # Number of first epochs to apply a high memory high execution solo lock to (-1 => Solo lock all epochs, 0 => Disable solo locking, 1 => Solo lock up to end of first epoch, ...)
'TrainLogCSV': bool, # Whether to log training results per epoch in CSV format
'TrainResultsJSON': bool, # Whether to save training results in JSON format
'TrainResultsPickle': bool, # Whether to save training results in pickle format
'TrainResultsYAML': bool, # Whether to save training results in YAML format
'TrainRefLosses': bool, # Whether to calculate reference losses in order to give model losses a sense of scale
'TrainSaveNumLatest': int, # Maximum number of model saves to keep in the models save directory (always keeping the latest, 0 = Keep all)
'TrainSaveOnlyIfBeatsRef': bool, # Only save new best models during training if they are better than all the reference losses
}
# Config parameter check specifications
# noinspection PyTypeChecker
pnn_config_check = {
'GPUTempLowPassTs': 0,
'GPUTempSafetyMargin': 0,
'RunLockEnterDelay': 0,
'RunLockMaxCountsCPU': [(len(device_util.GPULevel) - 2,) * 2, 1],
'RunLockMaxCountsGPU': [(len(device_util.GPULevel) - 2,) * 2, 1],
'TrainEpochs': 1,
'TrainLockFirstEpochs': -1,
'TrainSaveNumLatest': 0,
}
# File extensions
SAVED_MODEL_EXT = '.model'
SAVED_MODEL_META_EXT = '.yaml'
SAVED_MODEL_META_SUFFIX = '_meta'
SAVED_MODEL_META_SUFFIX_EXT = SAVED_MODEL_META_SUFFIX + SAVED_MODEL_META_EXT
# Print formats
perf_fmt = lambda value: 'd' if isinstance(value, int) else '#.4g' # noqa
###############
### Classes ###
###############
# PNN manager class
class PNNManager:
#
# Construction
#
def __init__(self, name, version, script_path, config_spec, config_check, default_config_file=None, default_csvfmt_file=None, config_converters=None, config_kwargs=None):
# name = Name of neural network, e.g. 'MyNet'
# version = Version of neural network, e.g. '0.1'
# script_path = Path of main script file, e.g. __file__ ('/path/to/my_net.py', relative or absolute)
# config_spec = See config.ConfigManager class
# config_check = See config.ConfigManager class
# default_config_file = Default configuration file path, e.g. 'my_net.cfg' (default: script_path with extension changed to *.cfg)
# default_csvfmt_file = Default CSV format file path, e.g. 'my_net_csvfmt.yaml' (default: script_path with extension changed to *_csvfmt.yaml)
# config_converters = See config.ConfigManager class (converters argument of __init__)
# config_kwargs = See config.ConfigManager class (kwargs of __init__)
self.default_group = 'Default'
self.default_models_name = 'models'
self.models_subdir_meta = '.models_dir'
self.timestamp_format = '%Y%m%d_%H%M%S'
self.timestamp_frac_format = '.%f'
self.git_force_valid_patch = False
self.git_snapshot_tracked_binary = True
self.git_snapshot_untracked_binary = False
self.source_snapshot_builtins = False
self.source_snapshot_in_prefix = False
change_constants_fn = getattr(self, 'change_constants', None)
if callable(change_constants_fn):
change_constants_fn()
self.name = name
self.version = str(version)
self.script_path = os.path.abspath(script_path)
self.script_file = os.path.basename(self.script_path)
self.script_dir_path = os.path.dirname(self.script_path)
self.script_dir_name = os.path.basename(self.script_dir_path)
gpu_index = -1
match = re.search(r'GPU([0-9]+)$', self.script_dir_name)
if match:
try:
gpu_index = int(match.group(1))
except ValueError:
raise ValueError(f"Found GPU specification in directory name '{self.script_dir_name}', but failed to extract desired default GPU index")
self.default_cuda_device = f'cuda:{gpu_index}' if gpu_index >= 0 else 'auto'
if gpu_index >= 0 or re.search(r'GPU[A-Z]$', self.script_dir_name):
self.default_models_dir = os.path.abspath(os.path.join(self.script_dir_path, '..', self.default_models_name))
else:
self.default_models_dir = os.path.join(self.script_dir_path, self.default_models_name)
self.default_config_file = default_config_file if default_config_file else os.path.splitext(self.script_path)[0] + '.cfg'
self.default_csvfmt_file = default_csvfmt_file if default_csvfmt_file else os.path.splitext(self.script_path)[0] + '_csvfmt.yaml'
self.config_spec = config_spec
self.config_check = config_check
self.config_converters = config_converters
self.config_kwargs = {} if config_kwargs is None else config_kwargs
self.device = None
self.run_lock = None
self.models_dir = None
self.config_file = None
self.config_manager = None
self.csvfmt_file = None
self.csvfmt_manager = None
self.input_saved_model = None
self.input_saved_model_list = [None]
self.output_saved_model = None
self.output_saved_model_list = [None]
self.cm = {context: None for context in Context}
def initialise(self, config_file=None, csvfmt_file=None, models_dir=None, device=None):
# config_file = Configuration file path to use (None for default)
# csvfmt_file = CSV format file path to use (None for default)
# models_dir = Directory to load/save models from/to (None for default)
# device = Torch device to use (see device_util.resolve_device() function, or 'auto')
misc_util.print_header(self.__class__.__name__)
if device is None:
device = self.default_cuda_device
if device == 'auto':
self.device = torch.device(type='cuda', index=0) if torch.cuda.device_count() <= 1 else None
else:
self.device = device_util.resolve_device(device)
print(f"Device: {'Will auto-select' if self.device is None else repr(self.device)}")
self.run_lock = device_util.GPULevelLockV(self.device, (1, 1, 1, 1), lock_delay=1, autoselect_cb=self.device_autoselect_cb, verbose=True, newline=True)
self.models_dir = os.path.abspath(models_dir if models_dir is not None else self.default_models_dir)
models_dir_note = ''
try:
statinfo = os.stat(self.models_dir)
if not stat.S_ISDIR(statinfo.st_mode):
raise NotADirectoryError(f"Specified models directory exists but is not a directory: {self.models_dir}")
except FileNotFoundError:
models_dir_parent = os.path.dirname(self.models_dir)
if not os.path.isdir(models_dir_parent):
raise NotADirectoryError(f"Specified models directory does not exist and neither does its parent directory => Not allowing directory creation on demand for safety reasons: {self.models_dir}")
models_dir_note = ' (WILL BE CREATED ON DEMAND)'
print(f"Models directory{models_dir_note}: {self.models_dir}")
print()
self.config_file = os.path.abspath(config_file if config_file is not None else self.default_config_file)
print(f"Config file: {self.config_file}")
self.config_manager = config.ConfigManager(self.config_file, self.config_spec, config_check=self.config_check, converters=self.config_converters, **self.config_kwargs)
print("Loaded configurations:")
ppyutil.print.print_as_columns(self.config_manager.config_names(), line_prefix=' ')
print()
self.csvfmt_file = os.path.abspath(csvfmt_file if csvfmt_file is not None else self.default_csvfmt_file)
print(f"CSV format file: {self.csvfmt_file}")
self.csvfmt_manager = yaml_spec.YAMLSpecManager(self.csvfmt_file, join_lists=yaml_spec.JoinLists.Append)
print("Loaded CSV formats:")
ppyutil.print.print_as_columns(self.csvfmt_manager.spec_names(), line_prefix=' ')
print()
return self
def device_autoselect_cb(self, selected_device):
self.device = selected_device
def ensure_models_dir_exists(self):
try:
os.mkdir(self.models_dir)
print(f"Created models directory: {self.models_dir}")
except OSError:
# Cannot rely on checking for EEXIST, since the operating system could give priority to other errors like EACCES or EROFS
if not os.path.isdir(self.models_dir):
raise Exception(f"Failed to create required models directory (does the parent directory exist?): {self.models_dir}")
print(f"Using models directory: {self.models_dir}")
def create_cmdline_argparser(self):
parser = argparse.ArgumentParser(
prog=f"{self.name}",
add_help=False,
usage=f"{self.script_file} [OPTIONS] [ACTIONS]",
description=f"Command line tool for training, running and testing the {self.name} network."
)
opt_general = parser.add_argument_group('General options')
opt_general.add_argument('-h', '--help', action='help', help='Show this help message and exit')
opt_general.add_argument('-v', '--version', action='version', version=f'{self.version}', help='Show version number (%(version)s) and exit')
opt_general.add_argument('--group', dest='group', action='store', default=self.default_group, metavar='GROUP', help='Group to assign the current run to (default: %(default)s)')
opt_general.add_argument('-c', '--config', dest='config', action='store', default=Configuration.Default, metavar='CONFIG', help='Configuration to use by default for completing actions with no explicit configuration specified')
opt_general.add_argument('-f', '--csvfmt', dest='csvfmt', action='store', default=None, metavar='FORMAT', help='CSV format to use for outputting results data (default: use default CSV format)')
opt_general.add_argument('-e', '--epochs', dest='epochs', action='store', type=IntRange(1), default=0, metavar='NUM', help='Number of epochs to train (default: use value from active configuration)')
opt_initialise = parser.add_argument_group('Initialisation options')
opt_initialise.add_argument('--config_file', dest='config_file', action='store', default=self.default_config_file, metavar='FILE', help='Config file to use (default: %(default)s)')
opt_initialise.add_argument('--csvfmt_file', dest='csvfmt_file', action='store', default=self.default_csvfmt_file, metavar='FILE', help='CSV format file to use (default: %(default)s)')
opt_initialise.add_argument('--models_dir', dest='models_dir', action='store', default=self.default_models_dir, metavar='DIR', help='Directory to load/save models from/to (default: %(default)s)')
opt_initialise.add_argument('-d', '--device', '-g', dest='device', action='store', default=self.default_cuda_device, metavar='DEVICE', help='Device on which to run the network, e.g. auto, cpu, cuda, cuda:1, 2, 01:00.0, 0:A0 (default: %(default)s)')
opt_initialise.add_argument('--cpu', dest='device', action='store_const', const='cpu', help='Shortcut for \'--device %(const)s\'')
opt_initialise.add_argument('--cuda', dest='device', action='store_const', const=self.default_cuda_device, help='Shortcut for \'--device %(const)s\'')
opt_action = parser.add_argument_group('Actions')
opt_action.add_argument('--repeat', dest='repeat', action='store', type=IntRange(1), default=1, metavar='NUM', help='Repeat the entire action agenda a given number of times (default: %(default)d)')
opt_action.add_argument('--debug_args', dest='agenda', key=Action.DebugArgs, action=AppendData, help='Debug the parsing of the command line arguments')
opt_action.add_argument('--load_model', dest='agenda', key=Action.LoadModel, action=AppendData, nargs=1, metavar='MODEL', help='Load a model as the starting point for the next action (File => Find model file in models directory, Path => Explicit path to model file)')
opt_action.add_argument('--keep_model', dest='agenda', key=Action.KeepModel, action=AppendData, help='Keep the model resulting from the last generative action as the starting point for the next action')
opt_action.add_argument('--reset_model', dest='agenda', key=Action.ResetModel, action=AppendData, help='Clear any stored starting point model')
opt_action.add_argument('--show_configs', dest='agenda', key=Action.ShowConfigs, action=AppendData, help='Show all available configurations and respective config parameters')
opt_action.add_argument('--show_csvfmts', dest='agenda', key=Action.ShowCSVFmts, action=AppendData, help='Show details of all available CSV formats')
opt_action.add_argument('--git_snapshot', dest='agenda', key=Action.GitSnapshot, action=AppendData, nargs='?', metavar='PATCH', help='Provide help in temporarily resetting the code to a particular git snapshot, e.g. so that a saved model can be loaded correctly')
opt_action.add_argument('--model_info', dest='agenda', key=Action.ModelInfo, action=AppendData, nargs='?', metavar='CONFIG', help='Show information about the neural network model')
opt_action.add_argument('--draw_model', dest='agenda', key=Action.DrawModel, action=AppendData, nargs=1, metavar='PDFPATH', help='Draw the neural network model to a pdf')
opt_action.add_argument('--dataset_info', dest='agenda', key=Action.DatasetInfo, action=AppendData, help='Load a dataset and show how many samples there are')
opt_action.add_argument('--dataset_stats', dest='agenda', key=Action.DatasetStats, action=AppendData, nargs='?', metavar='BASIS', help='Calculate statistics of the dataset (basis can be element, sample (default) or batch)')
opt_action.add_argument('--train', dest='agenda', key=Action.Train, action=AppendData, nargs='*', metavar='CONFIG', help='Train the network in the given configurations (special values: nondefault, all)')
opt_action.add_argument('--train_all', dest='agenda', key=Action.TrainAll, action=AppendData, nargs='?', metavar='STR', help='Train the network in all configurations starting with the specified string (special values: nondefault, all)')
opt_action.add_argument('--perf_model', dest='agenda', key=Action.PerfModel, action=AppendData, nargs='*', metavar='MODEL', help='Evaluate the performance of the specified models (specified by file name or path)')
opt_action.add_argument('--perf_model_optim', dest='agenda', key=Action.PerfModelOptim, action=AppendData, nargs='*', metavar='MODEL', help='Same as --perf_model but force parameter optimisation')
return parser, opt_general, opt_initialise, opt_action
def parse_arguments(self, argv):
parser = self.create_cmdline_argparser()[0]
args = parser.parse_args(argv)
if not args.agenda:
args.agenda = []
with contextlib.suppress(ValueError):
args.device = int(args.device)
return args
#
# Run command line
#
def run_cmdline(self, argv):
# argv = List of arguments to parse, e.g. sys.argv[1:]
args = self.parse_arguments(argv)
ppyutil.print.printc(f"{self.name} {self.version}", misc_util.header_color)
print()
self.initialise(config_file=args.config_file, csvfmt_file=args.csvfmt_file, models_dir=args.models_dir, device=args.device)
with self.enter_cm(Context.Process):
for repetition in range(args.repeat):
for item in args.agenda:
with self.enter_cm(Context.Action):
if isinstance(item, str):
key = item
arg = None
else:
key = item[0]
arg = item[1]
if not self.handle_action(key, arg, args):
misc_util.print_header("Unknown agenda key")
print_warn(f"Unknown agenda key '{key}'")
print()
misc_util.print_header("All actions completed")
return self
def handle_action(self, key, arg, args):
# key = Action key (see 'key=' in create_cmdline_argparser)
# arg = Arguments passed to key on the command line
# args = All parsed command line arguments
if key == Action.DebugArgs:
misc_util.print_header("Debug command line arguments")
print('Parsed arguments:')
ppyutil.print.pprint_to_width(vars(args))
print()
elif key == Action.LoadModel:
self.load_saved_model(saved_model=arg[0])
elif key == Action.KeepModel:
self.keep_saved_model()
elif key == Action.ResetModel:
self.reset_saved_model()
elif key == Action.ShowConfigs:
self.show_configs()
elif key == Action.ShowCSVFmts:
self.show_csvfmts()
elif key == Action.GitSnapshot:
self.git_snapshot(patch_path=arg)
elif key == Action.ModelInfo:
self.model_info(configuration=args.config if arg is None else arg)
elif key == Action.DrawModel:
self.draw_model(configuration=args.config, pdfpath=arg[0])
elif key == Action.DatasetInfo:
self.dataset_stats(configuration=args.config, stats_basis=arg, quick=True)
elif key == Action.DatasetStats:
self.dataset_stats(configuration=args.config, stats_basis=arg, quick=False)
elif key == Action.Train:
train_kwargs = {'csvfmt': args.csvfmt, 'group': args.group, 'epochs': args.epochs}
if not arg:
self.train_network(configuration=args.config, **train_kwargs)
elif len(arg) == 1:
configuration = arg[0]
if configuration == 'nondefault':
self.train_networks(configurations=Configuration.NonDefault, **train_kwargs)
elif configuration == 'all':
self.train_networks(configurations=Configuration.All, **train_kwargs)
else:
self.train_network(configuration=configuration, **train_kwargs)
else:
self.train_networks(configurations=arg, **train_kwargs)
elif key == Action.TrainAll:
train_kwargs = {'csvfmt': args.csvfmt, 'group': args.group, 'epochs': args.epochs}
if not arg or arg == 'all':
self.train_networks(configurations=Configuration.All, **train_kwargs)
elif arg == 'nondefault':
self.train_networks(configurations=Configuration.NonDefault, **train_kwargs)
else:
self.train_networks(configurations=lambda cname: cname.startswith(arg), **train_kwargs)
elif key == Action.PerfModel:
self.eval_model_perfs(configuration=args.config, saved_models=arg, force_optim=False)
elif key == Action.PerfModelOptim:
self.eval_model_perfs(configuration=args.config, saved_models=arg, force_optim=True)
else:
return False
return True
#
# Context management
#
@contextlib.contextmanager
def enter_cm(self, context): # Note: Process context is REQUIRED, must envelop ALL action contexts, and the process MUST exit/quit right after leaving the process context manager (otherwise it could illegally continue to take up CUDA memory for example)
# context = Context to enter (Context enum)
# Return the dynamic context instance used to enter the required context
if context not in self.cm:
raise ValueError(f"Unknown context: {context}")
if self.cm[context]: # We implement 'reentrance' by simply doing nothing if we detect we are already inside a 'context' context
yield self.cm[context]
return
def clear_context_callback():
self.cm[context] = None
newline_config = self.run_lock.config(newline=False, block_newline=True, restore_to_init=True, sticky=True)
with contextlib.ExitStack() as stack:
with ppyutil.contextman.DynamicContext() as cm:
cm.register_callback(clear_context_callback)
self.cm[context] = cm
if context == Context.Process:
cm.enter_context(self.run_lock, key="run_lock")
try:
yield cm
finally:
stack.enter_context(newline_config)
if context == Context.Process:
self.process_cleanup()
elif context == Context.Action:
self.action_cleanup()
def process_cleanup(self):
# Clean up whatever should always be cleaned right before the Process context exits (before anything is popped from the associated exit stack), no matter what happened inside the Process context
self.action_cleanup() # In case no Action context was entered during the Process context, we treat the entire Process context as a single Action and clean up after that Action now. If Action contexts WERE entered, this justs redundantly cleans up again after the last action, which is okay too.
# noinspection PyUnresolvedReferences
def action_cleanup(self):
# Clean up whatever should always be cleaned right before the Action context exits (before anything is popped from the associated exit stack), no matter what happened inside the Action context
if torch.cuda.is_initialized():
if self.device is None:
print_warn("CUDA runtime is in the initialised state even though no device has been selected => This should not happen...")
print()
elif self.device.type == 'cuda':
torch.cuda.synchronize(self.device)
else:
print_warn(f"CUDA runtime is in the initialised state even though the current device is not a CUDA device ({self.device.type}) => This should not happen...")
print()
gc.collect()
if torch.cuda.is_initialized():
torch.cuda.ipc_collect()
torch.cuda.empty_cache()
self.verify_lowmem()
def ensure_entered(self, context):
# context = Context to ensure has been entered (Context enum)
# Return the associated dynamic context instance
if context not in self.cm:
raise ValueError(f"Unknown context: {context}")
context_cm = self.cm[context]
if not context_cm:
raise ValueError(f"Specified context has not been entered yet: {context}")
return context_cm
def ensure_lowmem(self):
process_cm = self.ensure_entered(Context.Process)
if "run_lock_lowmem" not in process_cm:
process_cm.enter_context(self.run_lock.level(GPULevel.LowMemNoExec), key="run_lock_lowmem", parent="run_lock")
def clear_lowmem(self):
process_cm = self.ensure_entered(Context.Process)
if "run_lock_lowmem" in process_cm:
process_cm.leave_context("run_lock_lowmem")
# noinspection PyUnresolvedReferences
def verify_lowmem(self):
if ppyutil.execlock.process_exiting():
return
if torch.cuda.is_initialized():
if sys.exc_info()[0] is None:
self.ensure_lowmem() # Fail-safe against bad code that doesn't call ensure_lowmem() before executing tasks that can initialise the CUDA runtime and allocate CUDA memory
else:
self.clear_lowmem() # Although ensure_lowmem() was called, the CUDA runtime was not subsequently initialised, so no CUDA memory has been allocated yet
#
# Configurations
#
def resolve_configuration_list(self, configurations: Union[Configuration, Callable[[str], bool], Iterable[Union[Configuration, str, config.Config]]]):
# configurations = Configuration enum, callable (str -> bool), or iterable of configuration specifications accepted by resolve_configuration()
# Return list of configurations of type config.Config
if configurations == Configuration.Default:
configurations = [self.config_manager.default_name()]
elif configurations == Configuration.NonDefault:
default_cname = self.config_manager.default_name()
configurations = [C for cname, C in self.config_manager.config_dict().items() if cname != default_cname]
elif configurations == Configuration.All:
configurations = list(self.config_manager.config_dict().values())
elif callable(configurations):
configurations = [C for cname, C in self.config_manager.config_dict().items() if configurations(cname)]
return [self.resolve_configuration(configuration) for configuration in configurations]
def resolve_configuration(self, configuration: Union[Configuration, str, config.Config]) -> Any:
# configuration = Configuration.Default, str or config.Config
# Return configuration of type config.Config
if configuration == Configuration.Default:
C = self.config_manager.default_config()
elif isinstance(configuration, str):
C = self.config_manager.get_config(configuration)
else:
C = configuration
if not isinstance(C, config.Config):
raise TypeError(f"Invalid single configuration (should be of type config.Config): {C}")
return C
def resolve_csvfmt(self, csvfmt):
# csvfmt = None (Default format), str or yaml_spec.YAMLSpec
# Return CSV format of type yaml_spec.YAMLSpec
if csvfmt is None:
CSVF = self.csvfmt_manager.default_spec()
elif isinstance(csvfmt, str):
CSVF = self.csvfmt_manager.get_spec(csvfmt)
else:
CSVF = csvfmt
if not isinstance(CSVF, yaml_spec.YAMLSpec):
raise TypeError(f"Invalid CSV format object (should be of type yaml_spec.YAMLSpec): {CSVF}")
return CSVF
def resolve_saved_model(self, saved_model):
# saved_model = Saved model specification to resolve (None => Use raw model, File => Find model file in models directory, Path => Explicit path to model file)
# Return absolute saved model path or None or raise an error if not found
if saved_model is None:
return None
saved_model_path = os.path.abspath(saved_model)
if not os.path.isfile(saved_model_path) and os.path.basename(saved_model) == saved_model:
saved_model_path = None
alternative_paths = set()
for dirpath, dirnames, filenames in os.walk(self.models_dir, topdown=False, followlinks=False):
if saved_model in filenames:
new_saved_model_path = os.path.join(dirpath, saved_model)
if saved_model_path is None or saved_model_path < new_saved_model_path:
if saved_model_path is not None:
alternative_paths.add(saved_model_path)
saved_model_path = new_saved_model_path
else:
alternative_paths.add(new_saved_model_path)
for model_path in sorted(alternative_paths):
print_warn(f"Ambiguous alternative saved model: {model_path}")
if saved_model_path is None:
raise FileNotFoundError(f"Failed to find saved model: {saved_model}")
return saved_model_path
@staticmethod
def resolve_stats_basis(stats_basis):
# stats_basis = None (Default basis) or str
# Return a valid DatasetStatsBasis
if stats_basis is None:
return DatasetStatsBasis.Default
elif isinstance(stats_basis, str):
return DatasetStatsBasis.from_str(stats_basis)
else:
raise TypeError(f"Invalid dataset statistics basis specification (should be None or str): {stats_basis}")
#
# Actions
#
def load_saved_model(self, saved_model):
misc_util.print_header("Load saved model")
print(f"Saved model to load: {saved_model}")
saved_model = self.resolve_saved_model(saved_model)
print(f"Resolved saved model: {saved_model}")
self.input_saved_model = saved_model
self.input_saved_model_list = [saved_model]
print()
self.show_input_saved_models()
def keep_saved_model(self):
misc_util.print_header("Keep saved model")
print("Keeping current saved model(s) as the starting point for the next action...")
self.input_saved_model = self.output_saved_model
self.input_saved_model_list = self.output_saved_model_list
print()
self.show_input_saved_models()
def reset_saved_model(self):
misc_util.print_header("Reset saved model")
print("Resetting current saved model(s) for the next action...")
self.input_saved_model = None
self.input_saved_model_list = [None]
print()
self.show_input_saved_models()
def show_input_saved_models(self):
print("Main saved model:")
print(f" {self.input_saved_model}")
print()
print("Saved model list:")
for saved_model in self.input_saved_model_list:
print(f" {saved_model}")
print()
def show_configs(self):
misc_util.print_header("Show available configurations")
print(f"Config file: {self.config_file}")
print("Loaded configurations:")
ppyutil.print.print_as_columns(self.config_manager.config_names(), line_prefix=' ')
print()
self.config_manager.pprint()
def show_csvfmts(self):
misc_util.print_header("Show available CSV formats")
print(f"CSV format file: {self.csvfmt_file}")
print("Loaded CSV formats:")
ppyutil.print.print_as_columns(self.csvfmt_manager.spec_names(), line_prefix=' ')
print()
self.csvfmt_manager.pprint(header='CSV format')
def git_snapshot(self, patch_path=None):
# patch_path = A specific git snapshot patch file to adjust the provided helpful commands to
misc_util.print_header("Git snapshot help")
use_patch = False
empty_patch = True
patch_path_abs = None
repo_path = None
commit_hash = None
tracked_binary = None
untracked_binary = None
if patch_path is None:
print("Providing general help, as no specific patch file was passed as an argument...")
print()
else:
patch_path_abs = os.path.abspath(patch_path)
print(f"Providing help for: {patch_path_abs}")
try:
with open(patch_path_abs, 'r') as file:
for line in file:
if line.startswith('diff') or (line.startswith('@@') and line.rstrip() != '@@ -1,1 +1,1 @@ empty_diff'):
empty_patch = False
break
elif line.startswith('Git repo:'):
words = line.split()
if len(words) >= 3:
repo_path = words[2]
elif line.startswith('Latest commit:'):
words = line.split()
if len(words) >= 3:
commit_hash = words[2]
elif line.startswith('Includes tracked binary files:'):
with contextlib.suppress(ValueError, IndexError):
tracked_binary = strtobool(line.split()[4])
elif line.startswith('Includes untracked binary files:'):
with contextlib.suppress(ValueError, IndexError):
untracked_binary = strtobool(line.split()[4])
if repo_path:
print(f"Repo path: {repo_path}")
else:
print_warn("Failed to parse git repository path from patch file")
if commit_hash:
print(f"Commit hash: {commit_hash}")
else:
print_warn("Failed to parse required commit hash from patch file")
use_patch = bool(repo_path and commit_hash)
if tracked_binary is None:
print_warn("Failed to parse whether tracked binary files are included in the patch file")
if untracked_binary is None:
print_warn("Failed to parse whether untracked binary files are included in the patch file")
except OSError:
print_warn("Failed to open/read specified patch file => Ignoring patch file and providing only general help instead...")
print()
have_notes = False
repo_dirty = True
orig_head = None
if use_patch:
repo = ppyutil.git.get_git_repo(path=repo_path)
if repo is None:
print_warn(f"Failed to open git repository => Skipping checks that require repository access...")
have_notes = True
else:
repo_dirty = repo.is_dirty(index=True, working_tree=True, untracked_files=True)
orig_head = ppyutil.git.head_symbolic_ref(repo)
if not repo_dirty:
print("Note: Git repository is currently clean (no working changes/untracked files) => Skipping git stash/pop in the instructions below...")
have_notes = True
if use_patch and empty_patch:
print("Note: Patch file contains no actual working changes => Skipping git apply in the instructions below...")
have_notes = True
if not tracked_binary or not untracked_binary:
if tracked_binary is None:
print(f"Note: Tracked binary files may or may not have been included in the patch file (probably {'yes' if self.git_snapshot_tracked_binary else 'no'}) => Take care!")
elif not tracked_binary:
print(f"Note: Patch file does not include tracked binary files => Take care!")
if untracked_binary is None:
print(f"Note: Untracked binary files may or may not have been included in the patch file (probably {'yes' if self.git_snapshot_untracked_binary else 'no'}) => Take care!")
elif not untracked_binary:
print(f"Note: Patch file does not include untracked binary files => Take care!")
have_notes = True
if have_notes:
print()
ind = ' '
step = 0
if not use_patch or repo_dirty:
step += 1
print(f"{step}) Get the git repo into a clean state (no working changes/untracked files):")
print(f" {ind}cd \"{repo_path if use_patch else 'REPO_PATH'}\"")
print(f" {ind}git stash -u")
print(" If there were no local changes to save, no stash is created and you shouldn't attempt to pop the stash again at the end.")
print()
step += 1
if orig_head:
print(f"{step}) Check out the required snapshot commit:")
else:
print(f"{step}) Save the current git HEAD and proceed to check out the required snapshot commit:")
print(f" {ind}ORIGHEAD=\"$(git symbolic-ref -q --short HEAD || git rev-parse HEAD)\" && echo \"$ORIGHEAD\"")
print(f" {ind}git checkout {commit_hash if use_patch else 'COMMIT_HASH'}")
print()
if not use_patch or not empty_patch:
step += 1
print(f"{step}) Apply the snapshot patch:")
print(f" {ind}git apply \"{patch_path_abs if use_patch else 'PATCH_PATH'}\"")
print()
step += 1
print(f"{step}) Do whatever you want to do at this snapshot, e.g. test a model that was saved at this snapshot.")
print(" Just note that if you add/change any git-ignored files, then these changes will remain when returning to the original HEAD state.")
print(" Staged, unstaged and untracked files are not a problem however, and are managed/restored correctly.")
print()
step += 1
print(f"{step}) Once done, if you made any non-git-ignored changes then you need to deal with them.")
print(" If you have any changes that you want to keep for accessing again some other time:")
print(f" {ind}git checkout -b NEW_BRANCH")
print(f" {ind}git gui")
print(f" {ind}# <-- Commit the changes you want to keep")
print(" Push the new branch to the remote if desired (sets up branch tracking):")
print(f" {ind}git push -u origin NEW_BRANCH")
print(" Discard any remaining working directory changes:")
print(f" {ind}git reset --hard HEAD")
print(f" {ind}git clean -df")
print()
step += 1
print(f"{step}) Return the git repo to the original HEAD state:")
if orig_head:
print(f" {ind}git checkout {orig_head}")
else:
print(f" {ind}git checkout \"$ORIGHEAD\"")
print()
if not use_patch or repo_dirty:
step += 1
print(f"{step}) Restore the original working changes and untracked files (ONLY if a stash was actually created at the beginning):")
print(f" {ind}git stash pop")
print()
print("Note that if you train and save a model while at the git snapshot, the saved model file(s) will still be available when returning to the original git HEAD as they are git-ignored. This works the same for all other git-ignored files as well.")
print()
def model_info(self, configuration=Configuration.Default):
# configuration = Configuration (see resolve_configuration() function)
misc_util.print_header("Model info")
C = self.resolve_configuration(configuration)
self.model_info_impl(C)
def draw_model(self, configuration=Configuration.Default, pdfpath=None):
# configuration = Configuration (see resolve_configuration() function)
# pdfpath = String path of the required output pdf file (None => Just return the generated graph)
misc_util.print_header("Draw model")
C = self.resolve_configuration(configuration)
return self.draw_model_impl(C, pdfpath=pdfpath)
def dataset_stats(self, configuration=Configuration.Default, stats_basis=None, quick=False):
# configuration = Configuration (see resolve_configuration() function)
# stats_basis = Dataset statistics basis (see resolve_stats_basis() function)
# quick = Whether to avoid long running operations
misc_util.print_header("Dataset statistics")
C = self.resolve_configuration(configuration)
basis = self.resolve_stats_basis(stats_basis)
return self.dataset_stats_impl(C, basis=basis, quick=quick)
def train_networks(self, configurations: Any = Configuration.All, csvfmt=None, group=None, epochs=None):
# configurations = Configuration list (see resolve_configuration_list() function)
# csvfmt = CSV format to use (see resolve_csvfmt() function)
# group = Group to assign this training run to
# epochs = Maximum number of epochs to train (overrides configurations if >= 1)
# Return list of individual train_network() return values
misc_util.print_header("Train network in multiple configurations")
configurations = self.resolve_configuration_list(configurations)
CSVF = self.resolve_csvfmt(csvfmt)
print("Configurations to train:")
for configuration in configurations:
print(f" {configuration.name()}")
if not configurations:
print_warn(f"Empty configuration list => Nothing to do")
print()
print("Additional options:")
print(f" CSV format: {CSVF.name}")
if group is not None:
print(f" Group: {group}")
if epochs is not None and epochs >= 1:
print(f" Epoch limit: {epochs}")
print()
ret = []
for configuration in configurations:
ret.append(self.train_network(configuration=configuration, csvfmt=CSVF, group=group, epochs=epochs))
return ret
def train_network(self, configuration: Union[Configuration, str, config.Config] = Configuration.Default, csvfmt=None, group=None, epochs=None):
# configuration = Configuration (see resolve_configuration() function)
# csvfmt = CSV format to use (see resolve_csvfmt() function)
# group = Group to assign this training run to
# epochs = Maximum number of epochs to train (overrides configuration if >= 1)
# Return train_network_impl() return value
misc_util.print_header("Train network")
C = self.resolve_configuration(configuration)
CSVF = self.resolve_csvfmt(csvfmt)
return self.train_network_impl(C, CSVF=CSVF, group=group, epochs=epochs)
def eval_model_perfs(self, configuration=Configuration.Default, saved_models=None, force_optim=False):
# configuration = Configuration (see resolve_configuration() function)
# saved_models = Sequence of saved models (see resolve_saved_model() function)
# force_optim = Whether to force optimisation of performance parameters even if already optimised ones are already available
# Return eval_model_perfs_impl() return value
misc_util.print_header("Evaluate model performances")
C = self.resolve_configuration(configuration)
if saved_models:
saved_model_paths = [self.resolve_saved_model(saved_model) for saved_model in saved_models]
else:
saved_model_paths = list(saved_model_path for saved_model_path in self.input_saved_model_list if saved_model_path is not None)[::-1]
return self.eval_model_perfs_impl(C, saved_model_paths, force_optim=force_optim)
#
# Load network
#
# Note: MUST be called at the very beginning of every action (important amongst other things for determinism and run level locking)
def apply_global_config(self, C: Any, showC=True, force_cpu=False, allow_cudnn_bench=True):
# C = Configuration of type config.Config
# showC = Whether to pretty print the value of C
# force_cpu = Whether to force use only of the CPU (avoid CUDA)
# allow_cudnn_bench = Whether to allow enabling of cuDNN benchmark mode
# Return the system information gathered using system_info.print_system_info_summary()
print(f"Running python script path: {self.script_path}")
print()
device_is_cpu = (self.device and self.device.type == 'cpu')
max_counts_tuple = C.RunLockMaxCountsCPU if device_is_cpu else C.RunLockMaxCountsGPU
self.run_lock.update_max_counts(dict(zip(self.run_lock.run_levels(), max_counts_tuple)))
self.run_lock.lock_delay = C.RunLockEnterDelay
if not force_cpu:
self.ensure_lowmem()
cpu_only = force_cpu or device_is_cpu
if not cpu_only and self.device.index is not None:
torch.cuda.set_device(self.device)
print("Applying global configurations:")
print(f" Making calculations {'deterministic' if C.Deterministic else 'indeterministic'}")
misc_util.update_determinism(C.Deterministic, C.DeterministicSeed, allow_cudnn_bench and not force_cpu and C.CudnnBenchmarkMode)
# noinspection PyUnresolvedReferences
print(f" Cudnn benchmark mode: {torch.backends.cudnn.benchmark}")
print()
sysinfo = system_info.print_system_info_summary(cpu_only=cpu_only)
if showC:
C.pprint()
return sysinfo
def load_network(self, C, load_model_opts=None, load_dataset_opts=None, force_cpu=False):
# C = Configuration of type config.Config
# load_model_opts = Custom options for loading the model (e.g. for optional initialisation of model from state-dict object, or for multi-stage training where the model can change between stages in a way not implementable by simple changes to C)
# load_dataset_opts = Custom options for loading the dataset (e.g. for multi-stage training where the dataset format can change between stages in a way not implementable by simple changes to C)
# force_cpu = Whether to force the model to run on the CPU
# Return model (netmodel.NetModel), data_loaders (dataset.DatasetTuple of torch.utils.data.DataLoader), datasets (dataset.DatasetTuple of dataset.StagedDataset), info dict about the loaded model, info dict about the loaded dataset, model run level lock or None, model C, model metadata dict
model, model_info, model_lock, modelC, model_meta = self.load_network_model(C, load_model_opts, force_cpu=force_cpu)
data_loaders, datasets, dataset_info = self.load_network_dataset(C, model.reqd_inputs, model.reqd_targets, model.device, load_dataset_opts)
return model, data_loaders, datasets, model_info, dataset_info, model_lock, modelC, model_meta
def load_network_model(self, C, load_model_opts, force_cpu=False):
# C = Configuration of type config.Config
# load_model_opts = Custom options for loading the model
# force_cpu = Whether to force the model to run on the CPU
# Return model (netmodel.NetModel), info dict about the loaded model, optional model run level lock, model C, model metadata dict (non-trivial if loaded from saved model)
model_info: Dict[str, Any] = {}
if force_cpu:
model_lock = None
else: