-
Notifications
You must be signed in to change notification settings - Fork 6
/
run_training.py
1010 lines (901 loc) · 29.1 KB
/
run_training.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
import warnings
import os
import torch
from torch import multiprocessing as mp
import stylegan2
from stylegan2 import utils
from stylegan2.external_models import inception, lpips
from stylegan2.metrics import fid, ppl
#----------------------------------------------------------------------------
def get_arg_parser():
parser = utils.ConfigArgumentParser()
parser.add_argument(
'--output',
help='Output directory for model weights.',
type=str,
default=None,
metavar='DIR'
)
#----------------------------------------------------------------------------
# Model options
parser.add_argument(
'--channels',
help='Specify the channels for each layer (can be overriden for individual ' + \
'networks with "--g_channels" and "--d_channels". ' + \
'Default: %(default)s',
nargs='*',
type=int,
default=[32, 32, 64, 128, 256, 512, 512, 512, 512],
metavar='CHANNELS'
)
parser.add_argument(
'--latent',
help='Size of the prior (noise vector). Default: %(default)s',
type=int,
default=512,
metavar='VALUE'
)
parser.add_argument(
'--label',
help='Number of unique labels. Unused if not specified.',
type=int,
default=0,
metavar='VALUE'
)
parser.add_argument(
'--base_shape',
help='Data shape of first layer in generator or ' + \
'last layer in discriminator. Default: %(default)s',
nargs=2,
type=int,
default=(4, 4),
metavar='SIZE'
)
parser.add_argument(
'--kernel_size',
help='Size of conv kernel. Default: %(default)s',
type=int,
default=3,
metavar='SIZE'
)
parser.add_argument(
'--pad_once',
help='Pad filtered convs only once before filter instead ' + \
'of twice. Default: %(default)s',
type=utils.bool_type,
const=True,
nargs='?',
default=True,
metavar='BOOL'
)
parser.add_argument(
'--pad_mode',
help='Padding mode for conv layers. Default: %(default)s',
type=str,
default='constant',
metavar='MODE'
)
parser.add_argument(
'--pad_constant',
help='Padding constant for conv layers when `pad_mode` is ' + \
'\'constant\'. Default: %(default)s',
type=float,
default=0,
metavar='VALUE'
)
parser.add_argument(
'--filter_pad_mode',
help='Padding mode for filter layers. Default: %(default)s',
type=str,
default='constant',
metavar='MODE'
)
parser.add_argument(
'--filter_pad_constant',
help='Padding constant for filter layers when `filter_pad_mode` ' + \
'is \'constant\'. Default: %(default)s',
type=float,
default=0,
metavar='VALUE'
)
parser.add_argument(
'--filter',
help='Filter to use whenever FIR is applied. Default: %(default)s',
nargs='*',
type=float,
default=[1, 3, 3, 1],
metavar='VALUE'
)
parser.add_argument(
'--weight_scale',
help='Use weight scaling for equalized learning rate. Default: %(default)s',
type=utils.bool_type,
const=True,
nargs='?',
default=True,
metavar='BOOL'
)
#----------------------------------------------------------------------------
# Generator options
parser.add_argument(
'--g_file',
help='Load a generator model from a file instead of constructing a new one. Disabled unless a file is specified.',
type=str,
default=None,
metavar='FILE'
)
parser.add_argument(
'--g_channels',
help='Instead of the values of "--channels", ' + \
'use these for the generator instead.',
nargs='*',
type=int,
default=[],
metavar='CHANNELS'
)
parser.add_argument(
'--g_skip',
help='Use skip connections for the generator. Default: %(default)s',
type=utils.bool_type,
const=True,
nargs='?',
default=True,
metavar='BOOL'
)
parser.add_argument(
'--g_resnet',
help='Use resnet connections for the generator. Default: %(default)s',
type=utils.bool_type,
const=True,
nargs='?',
default=False,
metavar='BOOL'
)
parser.add_argument(
'--g_conv_block_size',
help='Number of layers in a conv block in the generator. Default: %(default)s',
type=int,
default=2,
metavar='VALUE'
)
parser.add_argument(
'--g_normalize',
help='Normalize conv features for generator. Default: %(default)s',
type=utils.bool_type,
const=True,
nargs='?',
default=True,
metavar='BOOL'
)
parser.add_argument(
'--g_fused_conv',
help='Fuse conv & upsample into a transposed ' + \
'conv for the generator. Default: %(default)s',
type=utils.bool_type,
const=True,
nargs='?',
default=True,
metavar='BOOL'
)
parser.add_argument(
'--g_activation',
help='The non-linear activaiton function for ' + \
'the generator. Default: %(default)s',
default='leaky:0.2',
type=str,
metavar='ACTIVATION'
)
parser.add_argument(
'--g_conv_resample_mode',
help='Resample mode for upsampling conv ' + \
'layers for generator. Default: %(default)s',
type=str,
default='FIR',
metavar='MODE'
)
parser.add_argument(
'--g_skip_resample_mode',
help='Resample mode for skip connection ' + \
'upsamples for the generator. Default: %(default)s',
type=str,
default='FIR',
metavar='MODE'
)
parser.add_argument(
'--g_lr',
help='The learning rate for the generator. Default: %(default)s',
default=2e-3,
type=float,
metavar='VALUE'
)
parser.add_argument(
'--g_betas',
help='Beta values for the generator Adam optimizer. Default: %(default)s',
type=float,
nargs=2,
default=(0, 0.99),
metavar='VALUE'
)
parser.add_argument(
'--g_loss',
help='Loss function for the generator. Default: %(default)s',
default='logistic_ns',
type=str,
metavar='LOSS'
)
parser.add_argument(
'--g_reg',
help='Regularization function for the generator with an optional weight (:?). Default: %(default)s',
default='pathreg:2',
type=str,
metavar='REG'
)
parser.add_argument(
'--g_reg_interval',
help='Interval at which to regularize the generator. Default: %(default)s',
default=4,
type=int,
metavar='INTERVAL'
)
parser.add_argument(
'--g_iter',
help='Number of generator iterations per training iteration. Default: %(default)s',
default=1,
type=int,
metavar='ITER'
)
parser.add_argument(
'--style_mix',
help='The probability of passing more than one ' + \
'latent to the generator. Default: %(default)s',
type=float,
default=0.9,
metavar='PROBABILITY'
)
parser.add_argument(
'--latent_mapping_layers',
help='The number of layers of the latent mapping network. Default: %(default)s',
type=int,
default=8,
metavar='LAYERS'
)
parser.add_argument(
'--latent_mapping_lr_mul',
help='The learning rate multiplier for the latent ' + \
'mapping network. Default: %(default)s',
type=float,
default=0.01,
metavar='LR_MUL'
)
parser.add_argument(
'--normalize_latent',
help='Normalize latent inputs. Default: %(default)s',
type=utils.bool_type,
const=True,
nargs='?',
default=True,
metavar='BOOL'
)
parser.add_argument(
'--modulate_rgb',
help='Modulate RGB layers (use style for output ' + \
'layers of generator). Default: %(default)s',
type=utils.bool_type,
const=True,
nargs='?',
default=True,
metavar='BOOL'
)
#----------------------------------------------------------------------------
# Discriminator options
parser.add_argument(
'--d_file',
help='Load a discriminator model from a file instead of constructing a new one. Disabled unless a file is specified.',
type=str,
default=None,
metavar='FILE'
)
parser.add_argument(
'--d_channels',
help='Instead of the values of "--channels", ' + \
'use these for the discriminator instead.',
nargs='*',
type=int,
default=[],
metavar='CHANNELS'
)
parser.add_argument(
'--d_skip',
help='Use skip connections for the discriminator. Default: %(default)s',
type=utils.bool_type,
const=True,
nargs='?',
default=False,
metavar='BOOL'
)
parser.add_argument(
'--d_resnet',
help='Use resnet connections for the discriminator. Default: %(default)s',
type=utils.bool_type,
const=True,
nargs='?',
default=True,
metavar='BOOL'
)
parser.add_argument(
'--d_conv_block_size',
help='Number of layers in a conv block in the discriminator. Default: %(default)s',
type=int,
default=2,
metavar='VALUE'
)
parser.add_argument(
'--d_fused_conv',
help='Fuse conv & downsample into a strided ' + \
'conv for the discriminator. Default: %(default)s',
type=utils.bool_type,
const=True,
nargs='?',
default=True,
metavar='BOOL'
)
parser.add_argument(
'--group_size',
help='Size of the groups in batch std layer. Default: %(default)s',
type=int,
default=4,
metavar='VALUE'
)
parser.add_argument(
'--d_activation',
help='The non-linear activaiton function for the discriminator. Default: %(default)s',
default='leaky:0.2',
type=str,
metavar='ACTIVATION'
)
parser.add_argument(
'--d_conv_resample_mode',
help='Resample mode for downsampling conv ' + \
'layers for discriminator. Default: %(default)s',
type=str,
default='FIR',
metavar='MODE'
)
parser.add_argument(
'--d_skip_resample_mode',
help='Resample mode for skip connection ' + \
'downsamples for the discriminator. Default: %(default)s',
type=str,
default='FIR',
metavar='MODE'
)
parser.add_argument(
'--d_loss',
help='Loss function for the disriminator. Default: %(default)s',
default='logistic',
type=str,
metavar='LOSS'
)
parser.add_argument(
'--d_reg',
help='Regularization function for the discriminator ' + \
'with an optional weight (:?). Default: %(default)s',
default='r1:10',
type=str,
metavar='REG'
)
parser.add_argument(
'--d_reg_interval',
help='Interval at which to regularize the discriminator. Default: %(default)s',
default=16,
type=int,
metavar='INTERVAL'
)
parser.add_argument(
'--d_iter',
help='Number of discriminator iterations per training iteration. Default: %(default)s',
default=1,
type=int,
metavar='ITER'
)
parser.add_argument(
'--d_lr',
help='The learning rate for the discriminator. Default: %(default)s',
default=2e-3,
type=float,
metavar='VALUE'
)
parser.add_argument(
'--d_betas',
help='Beta values for the discriminator Adam optimizer. Default: %(default)s',
type=float,
nargs=2,
default=(0, 0.99),
metavar='VALUE'
)
#----------------------------------------------------------------------------
# Training options
parser.add_argument(
'--iterations',
help='Number of iterations to train for. Default: %(default)s',
type=int,
default=10000,
metavar='ITERATIONS'
)
parser.add_argument(
'--gpu',
help='The cuda device(s) to use. Example: ""--gpu 0 1" will train ' + \
'on GPU 0 and GPU 1. Default: Only use CPU',
type=int,
default=[],
nargs='*',
metavar='DEVICE_ID'
)
parser.add_argument(
'--distributed',
help='When more than one gpu device is passed, automatically ' + \
'start one process for each device and give it the correct ' + \
'distributed args (rank, world_size etc). Disable this if ' + \
'you want training to be performed with only one process ' + \
'using the DataParallel module. Default: %(default)s',
type=utils.bool_type,
const=True,
nargs='?',
default=True,
metavar='BOOL'
)
parser.add_argument(
'--rank',
help='Rank for distributed training.',
type=int,
default=None,
)
parser.add_argument(
'--world_size',
help='World size for distributed training.',
type=int,
default=None,
)
parser.add_argument(
'--master_addr',
help='Address for distributed training.',
type=str,
default=None,
)
parser.add_argument(
'--master_port',
help='Port for distributed training.',
type=str,
default=None,
)
parser.add_argument(
'--batch_size',
help='Size of each batch. Default: %(default)s',
default=32,
type=int,
metavar='VALUE'
)
parser.add_argument(
'--device_batch_size',
help='Maximum number of items to fit on single device at a time. Default: %(default)s',
default=4,
type=int,
metavar='VALUE'
)
parser.add_argument(
'--g_reg_batch_size',
help='Size of each batch used to regularize the generator. Default: %(default)s',
default=16,
type=int,
metavar='VALUE'
)
parser.add_argument(
'--g_reg_device_batch_size',
help='Maximum number of items to fit on single device when ' + \
'regularizing the generator. Default: %(default)s',
default=2,
type=int,
metavar='VALUE'
)
parser.add_argument(
'--half',
help='Use mixed precision training. Default: %(default)s',
type=utils.bool_type,
const=True,
nargs='?',
default=False,
metavar='BOOL'
)
parser.add_argument(
'--resume',
help='Resume from the latest saved checkpoint in the checkpoint_dir. ' + \
'This loads all previous training settings except for the dataset options, ' + \
'device args (--gpu ...) and distributed training args (--rank, --world_size e.t.c) ' + \
'as well as metrics and logging.',
type=utils.bool_type,
const=True,
nargs='?',
default=False,
metavar='BOOL'
)
#----------------------------------------------------------------------------
# Extra metric options
parser.add_argument(
'--fid_interval',
help='If specified, evaluate the FID metric with this interval.',
default=None,
type=int,
metavar='INTERVAL'
)
parser.add_argument(
'--ppl_interval',
help='If specified, evaluate the PPL metric with this interval.',
default=None,
type=int,
metavar='INTERVAL'
)
parser.add_argument(
'--ppl_ffhq_crop',
help='Crop images evaluated for PPL with crop values for FFHQ. Default: %(default)s',
type=utils.bool_type,
const=True,
nargs='?',
default=False,
metavar='BOOL'
)
#----------------------------------------------------------------------------
# Data options
parser.add_argument(
'--pixel_min',
help='Minimum of the value range of pixels in generated images. Default: %(default)s',
default=-1,
type=float,
metavar='VALUE'
)
parser.add_argument(
'--pixel_max',
help='Maximum of the value range of pixels in generated images. Default: %(default)s',
default=1,
type=float,
metavar='VALUE'
)
parser.add_argument(
'--data_channels',
help='Number of channels in the data. Default: 3 (RGB)',
default=3,
type=int,
choices=[1, 3],
metavar='CHANNELS'
)
parser.add_argument(
'--data_dir',
help='The root directory of the dataset. This argument is required!',
type=str,
default=None
)
parser.add_argument(
'--data_resize',
help='Resize data to fit input size of discriminator. Default: %(default)s',
type=utils.bool_type,
const=True,
nargs='?',
default=False,
metavar='BOOL'
)
parser.add_argument(
'--mirror_augment',
help='Use random horizontal flipping for data images. Default: %(default)s',
type=utils.bool_type,
const=True,
nargs='?',
default=False,
metavar='BOOL'
)
parser.add_argument(
'--data_workers',
help='Number of worker processes that handles dataloading. Default: %(default)s',
default=4,
type=int,
metavar='WORKERS'
)
#----------------------------------------------------------------------------
# Logging options
parser.add_argument(
'--checkpoint_dir',
help='If specified, save checkpoints to this directory.',
default=None,
type=str,
metavar='DIR'
)
parser.add_argument(
'--checkpoint_interval',
help='Save checkpoints with this interval. Default: %(default)s',
default=10000,
type=int,
metavar='INTERVAL'
)
parser.add_argument(
'--tensorboard_log_dir',
help='Log to this tensorboard directory if specified.',
default=None,
type=str,
metavar='DIR'
)
parser.add_argument(
'--tensorboard_image_interval',
help='Log images to tensorboard with this interval if specified.',
default=None,
type=int,
metavar='INTERVAL'
)
parser.add_argument(
'--tensorboard_image_size',
help='Size of images logged to tensorboard. Default: %(default)s',
default=256,
type=int,
metavar='VALUE'
)
return parser
#----------------------------------------------------------------------------
def get_dataset(args):
assert args.data_dir, '--data_dir has to be specified.'
height, width = [
shape * 2 ** (len(args.d_channels or args.channels) - 1)
for shape in args.base_shape
]
dataset = utils.ImageFolder(
args.data_dir,
mirror=args.mirror_augment,
pixel_min=args.pixel_min,
pixel_max=args.pixel_max,
height=height,
width=width,
resize=args.data_resize,
grayscale=args.data_channels == 1
)
assert len(dataset), 'No images found at {}'.format(args.data_dir)
return dataset
#----------------------------------------------------------------------------
def get_models(args):
common_kwargs = dict(
data_channels=args.data_channels,
base_shape=args.base_shape,
conv_filter=args.filter,
skip_filter=args.filter,
kernel_size=args.kernel_size,
conv_pad_mode=args.pad_mode,
conv_pad_constant=args.pad_constant,
filter_pad_mode=args.filter_pad_mode,
filter_pad_constant=args.filter_pad_constant,
pad_once=args.pad_once,
weight_scale=args.weight_scale
)
if args.g_file:
# be sure the G_mapping is from FFHQ dataset pretrain and freeze it.
# if not, run
# G1 = stylegan2.models.load('G_pretrain.pth')
# G2 = stylegan2.models.load(args.g_file)
# G = stylegan2.models.Generator(G_mapping=G1.G_mapping, G_synthesis=G2.G_synthesis)
G = stylegan2.models.load(args.g_file)
for param in G.G_mapping.parameters():
param.requires_grad = False
assert isinstance(G, stylegan2.models.Generator), \
'`--g_file` should specify a generator model, found {}'.format(type(G))
else:
G_M = stylegan2.models.GeneratorMapping(
latent_size=args.latent,
label_size=args.label,
num_layers=args.latent_mapping_layers,
hidden=args.latent,
activation=args.g_activation,
normalize_input=args.normalize_latent,
lr_mul=args.latent_mapping_lr_mul,
weight_scale=args.weight_scale
)
G_S = stylegan2.models.GeneratorSynthesis(
channels=args.g_channels or args.channels,
latent_size=args.latent,
demodulate=args.g_normalize,
modulate_data_out=args.modulate_rgb,
conv_block_size=args.g_conv_block_size,
activation=args.g_activation,
conv_resample_mode=args.g_conv_resample_mode,
skip_resample_mode=args.g_skip_resample_mode,
resnet=args.g_resnet,
skip=args.g_skip,
fused_resample=args.g_fused_conv,
**common_kwargs
)
G = stylegan2.models.Generator(G_mapping=G_M, G_synthesis=G_S)
if args.d_file:
D = stylegan2.models.load(args.d_file)
assert isinstance(D, stylegan2.models.Discriminator), \
'`--d_file` should specify a discriminator model, found {}'.format(type(D))
else:
D = stylegan2.models.Discriminator(
channels=args.d_channels or args.channels,
label_size=args.label,
conv_block_size=args.d_conv_block_size,
activation=args.d_activation,
conv_resample_mode=args.d_conv_resample_mode,
skip_resample_mode=args.d_skip_resample_mode,
mbstd_group_size=args.group_size,
resnet=args.d_resnet,
skip=args.d_skip,
fused_resample=args.d_fused_conv,
**common_kwargs
)
assert len(G.G_synthesis.channels) == len(D.channels), \
'While the number of channels for each layer can ' + \
'differ between generator and discriminator, the ' + \
'number of layers have to be the same. Received ' + \
'{} generator layers and {} discriminator layers.'.format(
len(G.G_synthesis.channels), len(D.channels))
return G, D
#----------------------------------------------------------------------------
def get_trainer(args):
dataset = get_dataset(args)
if args.resume and stylegan2.train._find_checkpoint(args.checkpoint_dir):
trainer = stylegan2.train.Trainer.load_checkpoint(
args.checkpoint_dir,
dataset,
device=args.gpu,
rank=args.rank,
world_size=args.world_size,
master_addr=args.master_addr,
master_port=args.master_port,
tensorboard_log_dir=args.tensorboard_log_dir
)
else:
G, D = get_models(args)
trainer = stylegan2.train.Trainer(
G=G,
D=D,
latent_size=args.latent,
dataset=dataset,
device=args.gpu,
batch_size=args.batch_size,
device_batch_size=args.device_batch_size,
label_size=args.label,
data_workers=args.data_workers,
G_loss=args.g_loss,
D_loss=args.d_loss,
G_reg=args.g_reg,
G_reg_interval=args.g_reg_interval,
G_opt_kwargs={'lr': args.g_lr, 'betas': args.g_betas},
G_reg_batch_size=args.g_reg_batch_size,
G_reg_device_batch_size=args.g_reg_device_batch_size,
D_reg=args.d_reg,
D_reg_interval=args.d_reg_interval,
D_opt_kwargs={'lr': args.d_lr, 'betas': args.d_betas},
style_mix_prob=args.style_mix,
G_iter=args.g_iter,
D_iter=args.d_iter,
tensorboard_log_dir=args.tensorboard_log_dir,
checkpoint_dir=args.checkpoint_dir,
checkpoint_interval=args.checkpoint_interval,
half=args.half,
rank=args.rank,
world_size=args.world_size,
master_addr=args.master_addr,
master_port=args.master_port
)
if args.fid_interval and not args.rank:
fid_model = inception.InceptionV3FeatureExtractor(
pixel_min=args.pixel_min, pixel_max=args.pixel_max)
trainer.register_metric(
name='FID (299x299)',
eval_fn=fid.FID(
trainer.Gs,
trainer.prior_generator,
dataset=dataset,
fid_model=fid_model,
fid_size=299,
reals_batch_size=64
),
interval=args.fid_interval
)
trainer.register_metric(
name='FID',
eval_fn=fid.FID(
trainer.Gs,
trainer.prior_generator,
dataset=dataset,
fid_model=fid_model,
fid_size=None
),
interval=args.fid_interval
)
if args.ppl_interval and not args.rank:
lpips_model = lpips.LPIPS_VGG16(
pixel_min=args.pixel_min, pixel_max=args.pixel_max)
crop = None
if args.ppl_ffhq_crop:
crop = ppl.PPL.FFHQ_CROP
trainer.register_metric(
name='PPL_end',
eval_fn=ppl.PPL(
trainer.Gs,
trainer.prior_generator,
full_sampling=False,
crop=crop,
lpips_model=lpips_model,
lpips_size=256
),
interval=args.ppl_interval
)
trainer.register_metric(
name='PPL_full',
eval_fn=ppl.PPL(
trainer.Gs,
trainer.prior_generator,
full_sampling=True,
crop=crop,
lpips_model=lpips_model,
lpips_size=256
),
interval=args.ppl_interval
)
if args.tensorboard_image_interval:
for static in [True, False]:
for trunc in [0.5, 0.7, 1.0]:
if static:
name = 'static'
else:
name = 'random'
name += '/trunc_{:.1f}'.format(trunc)
trainer.add_tensorboard_image_logging(
name=name,
num_images=4,
interval=args.tensorboard_image_interval,
resize=args.tensorboard_image_size,
seed=1234567890 if static else None,
truncation_psi=trunc,
pixel_min=args.pixel_min,
pixel_max=args.pixel_max
)
return trainer
#----------------------------------------------------------------------------
def run(args):
if not args.rank:
if not (args.checkpoint_dir or args.output):
warnings.warn(
'Neither an output path or checkpoint dir has been ' + \
'given. Weights from this training run will never ' + \
'be saved.'
)
if args.output:
assert os.path.isdir(args.output) or not os.path.splitext(args.output)[-1], \
'--output argument should specify a directory, not a file.'
trainer = get_trainer(args)
trainer.train(iterations=args.iterations)
if not args.rank and args.output:
print('Saving models to {}'.format(args.output))
if not os.path.exists(args.output):
os.makedirs(args.output)
for model_name in ['G', 'D', 'Gs']:
getattr(trainer, model_name).save(
os.path.join(args.output_dir, model_name + '.pth'))
#----------------------------------------------------------------------------
def run_distributed(rank, args):
args.rank = rank
args.world_size = len(args.gpu)
args.gpu = args.gpu[rank]
args.master_addr = args.master_addr or '127.0.0.1'
args.master_port = args.master_port or '23456'
run(args)
#----------------------------------------------------------------------------
def main():
parser = get_arg_parser()
args = parser.parse_args()
if len(args.gpu) > 1 and args.distributed:
assert args.rank is None and args.world_size is None, \
'When --distributed is enabled (default) the rank and ' + \