-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathmain.py
1542 lines (1241 loc) · 58.7 KB
/
main.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
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
# -*- coding: utf-8 -*-
"""
Created on Thu Nov 12 11:56:37 2020
@author: student
"""
###############################################################################
"""
MODULES
"""
import tensorflow as tf
#from tensorflow.keras.utils import plot_model
import numpy as np
#from scipy.stats import median_absolute_deviation
import time
import os
import sys
sys.path.append('.')
sys.path.append('<<<FOB DIR GOES HERE>>>')
from base_functions import (make_dataset,
up,
down,
generator_loss,
encoder_loss,
critic_loss,
RandomWeightedAverage,
instance_noise_alpha,
instance_noise_B_Bdomain,
instance_noise_B_Rdomain,
instance_noise_R_Bdomain,
instance_noise_R_Rdomain,
reparameterize)
from models import (make_generator_model,
make_encoder_model,
make_critic_model)
###############################################################################
"""
PARAMETERS
"""
# Build a simplified version of the models (fewer depth blocks) to debug code?
TESTING = True
# Are you using a deterministic encoder?
# If you are using a variational encoder, this is False.
DETERMINISTIC = True
# How many BATCHES without improvement in critic validation loss to consecutively train C per update of G/E?
if TESTING:
critic_patience = 2
else:
critic_patience = 5
# Number of validation batches to evaluate whether or not a critic has converged per model update.
if TESTING:
num_val_batches = 1
else:
num_val_batches = 5
# How many EPOCHS without improvement in ANY of generator, encoder, and critic validation losses to continue train the models?
# Note that this should not start incrementing til instance noise is done annealing, as some loss functions do not apply in that regime and return absurdly low values.
if TESTING:
training_patience = 4
else:
training_patience = 20
# What is the critic input?
# 'B': C is a function of B only, C(B).
# 'R': C is a function of R only, C(R).
# 'AB': C is a function of B, conditioned on A, C(A,B).
critic_input = 'R'
# Need to label output files correctly.
critic_input_label = f'CriticInput{critic_input}'
# Are you using an explicit consistency loss?
CONSISTENT = True
# Need to label output files correctly.
if CONSISTENT:
consistency_label = 'consistent'
else:
consistency_label = 'NOTconsistent'
# What dimension of latent space?
z_dim = 100
# Save the models and losses every <this many> epochs. If it is <= 0, do not save.
if TESTING:
SAVE_INTERVAL = 0
else:
SAVE_INTERVAL = 1
# Where are the tfrecords files stored?
# This is also where the demonstration data is stored.
tfrecords_filepath = '/home/student/Work/Keras/GAN/mySRGAN/new_implementation/multiGPU_datasetAPI/custom_train_loop_function_method/DATA_FOR_AAAI/code/'
# What are the shapes of the input/output images?
x_shape = (14, 14, 1)
# If you are loading pretrained files, where are they located?
# If not, these should be None
pretrained_G_filepath = None
pretrained_E_filepath = None
pretrained_C_filepath = None
# Are you restoring from a previous checkpoint (e.g., if you are continuing training after running out of wall time)?
# If not, this should be None. Otherwise, it should be '.../ckpt-#', where # is the desired checkpoint to be restored.
ckpt_path = None
# How many epochs to train?
# This is a maximum value, and if the patience condition is met early, training will stip before reaching this.
# begin_epoch can be set to maintain consistency in file naming if training had to be restarted for whatever reason.
begin_epoch = 0
if TESTING:
begin_epoch = 0
fin_epoch = 2
else:
fin_epoch = 10000
# What is the cutoff epoch for fading out instance noise? alpha will anneal from 0 to 1 over this many epochs.
if TESTING:
noisy_epochs = 1
else:
noisy_epochs = 99
# Number of training data per model update.
# Should be a divisor of 60,000 (the total number of training examples in fashion-MNIST).
batch_size = 200
# Are you doing layer normalization or not?
LAYER_NORM = True
###############################################################################
"""
LAMBDAS
"""
"""
Weights to multiply each loss term by when calculating the total loss.
###############################################################################
###############################################################################
###############################################################################
G LOSSES
if not CONSISTENT:
[total,
||R_cyc - R||_1,
-(1*C(R_gen)) (cLR),
-(1*C(R_cyc)) (cAE)]
else:
[total,
||R_cyc - R||_1,
-(1*C(R_gen)) (cLR),
-(1*C(R_cyc)) (cAE),
||down(R_gen)||_2 (cLR),
||down(R_cyc)||_2 (cAE)]
###############################################################################
E LOSSES
if DETERMINISTIC:
[total,
||z - z_cyc||_1,
KL[z_cyc, N(0,1)] (cLR), <- EVALUATED OVER ENTIRE BATCH
KL[z_enc, N(0,1)] (cAE)] <- EVALUATED OVER ENTIRE BATCH
else:
[total,
||z - mu||_1,
KL[N(mu_cyc,var), N(0,1)],
KL[N(mu_enc,var), N(0,1)]]
###############################################################################
C LOSSES
[total,
-(1*C(R)),
-(-1*C(R_gen))/2 (cLR),
-(-1*C(R_cyc))/2 (cAE),
GP (cLR),
GP (cAE)]
"""
# Multiply the gradient penalty by this number (to increase it to the point that it can compete with Wasserstein loss). The original paper used 10. This value is used for the GP loss when updating C.
LAMBDA_GP = 10
# How much weight to accord the critic verdict (cLR and cAE paths) when updating G?
LAMBDA_CRITIC_cLR = 1
LAMBDA_CRITIC_cAE = 1
# In C? This value is used for the GP loss when updating C.
LAMBDA_CRITIC_C = 1
# How much weight to accord the batch-wise KL divergence (deterministic) or point-cloud-based KL divergence (variational) when updating E?
LAMBDA_KL_cLR = 1
LAMBDA_KL_cAE = 1
# How much weight to accord the downsampling consistency term when updating G?
LAMBDA_CONSISTENCY_cLR = 0.1
LAMBDA_CONSISTENCY_cAE = 0.1
# How much weight to accord the reconstruction terms in G and E, respectively??
LAMBDA_R_RECONSTRUCTION = 1
LAMBDA_Z_RECONSTRUCTION = 10
# The loss weight lists are then:
G_loss_weights = [LAMBDA_R_RECONSTRUCTION,
LAMBDA_CRITIC_cLR,
LAMBDA_CRITIC_cAE,
LAMBDA_CONSISTENCY_cLR,
LAMBDA_CONSISTENCY_cAE]
E_loss_weights = [LAMBDA_Z_RECONSTRUCTION,
LAMBDA_KL_cLR,
LAMBDA_KL_cAE]
C_loss_weights = [LAMBDA_CRITIC_C,
LAMBDA_GP]
###############################################################################
"""
LOAD & PRE-PROCESS THE DATASET
"""
x_train = tfrecords_filepath + 'xy_train_fMNIST.tfrecords'
x_val = tfrecords_filepath + 'xy_val_fMNIST.tfrecords'
# how many train/val examples?
num_train_examples = 60_000
num_val_examples = 10_000
x_train = make_dataset(x_train,
z_dim,
batch_size,
shuffle_buffer_size=num_train_examples)
x_val = make_dataset(x_val,
z_dim,
batch_size,
shuffle_buffer_size=num_val_examples)
if TESTING:
x_train = x_train.take(3)
x_val = x_val.take(2)
"""
MAKE THE DEMO DATASET
"""
x_demo = tfrecords_filepath + 'x_demo.npy'
z_demo = tfrecords_filepath + 'z_demo.npy'
x_demo = np.load(x_demo)
z_demo = np.load(z_demo)
# z_demo has shape (4,1000,1) and needs to be converted to (4,z_dim,1)
z_demo = z_demo[:,
0:z_dim,
:]
# downsample x once to get ground truth, and a second time to get conditioner.
x_demo_down1 = down(x_demo)
x_demo_down2 = down(x_demo_down1)
demo_dataset = None
# Iterate over the 10 classes
for i in range(10):
# Iterate over the 4 z vectors
for j in range(4):
xyz_demo_0 = z_demo[j:j+1]
xyz_demo_0 = tf.data.Dataset.from_tensor_slices(xyz_demo_0)
xyz_demo_1 = up(x_demo_down2[i:i+1]).numpy()
xyz_demo_1 = tf.data.Dataset.from_tensor_slices(xyz_demo_1)
xyz_demo_2 = x_demo_down1[i:i+1]
xyz_demo_2 = tf.data.Dataset.from_tensor_slices(xyz_demo_2)
xyz_demo = tf.data.Dataset.zip((xyz_demo_0,
xyz_demo_1,
xyz_demo_2))
if not demo_dataset:
demo_dataset = xyz_demo
else:
demo_dataset = demo_dataset.concatenate(xyz_demo)
demo_dataset = demo_dataset.batch(4)
"""
MAKE THE MODELS
"""
generator = make_generator_model(z_dim,
x_shape,
LAYER_NORM,
TESTING,
pretrained_G_filepath)
encoder = make_encoder_model(z_dim,
x_shape,
DETERMINISTIC,
LAYER_NORM,
TESTING,
pretrained_E_filepath)
critic = make_critic_model(x_shape,
critic_input,
LAYER_NORM,
TESTING,
pretrained_C_filepath)
# Define the optimizers
generator_optimizer = tf.keras.optimizers.Adam()
encoder_optimizer = tf.keras.optimizers.Adam()
critic_optimizer = tf.keras.optimizers.Adam()
"""
SET CHECKPOINTS
"""
# Save checkpoints
checkpoint_dir = f'./{critic_input_label}_{consistency_label}_training_checkpoints'
checkpoint_prefix = os.path.join(checkpoint_dir, "ckpt")
checkpoint = tf.train.Checkpoint(
generator_optimizer=generator_optimizer,
encoder_optimizer=encoder_optimizer,
critic_optimizer=critic_optimizer,
generator=generator,
encoder=encoder,
critic=critic)
if ckpt_path:
status = checkpoint.restore(ckpt_path)
print(f'CHECKPOINT RESTORED from path {ckpt_path}')
print('')
"""
DEFINE TRAINING STEPS
"""
@tf.function
def generator_train_step(x,
critic_input,
DETERMINISTIC,
CONSISTENT,
alpha):
"""
Args:
x: tuple (z, A, B)
critic_input: One of 'AB', 'B', or 'R'. The input(s) to the critic.
DETERMINISTIC: Boolean. Whether or not E is deterministic, outputting a z vector, or variational, outputting a tuple (mu, logvar).
CONSISTENT: Boolean. Whether or not to include self-consistency terms in the generator loss function.
alpha: (1-alpha) is the fraction of instance noise.
Returns:
G_loss: The outputs of generator_loss(...) for the generator.
Updates the generator's weights.
"""
(z, up_B2, B1) = x
with tf.GradientTape() as gen_tape:
# The generated residual.
R1_gen = generator([z,
up_B2])
# Add instance noise to the fake image.
if critic_input == 'R':
R1_gen = instance_noise_R_Rdomain(R1_gen,
alpha)
else:
R1_gen = instance_noise_R_Bdomain(R1_gen,
up_B2,
alpha)
# The full B-domain generated image is then:
B1_gen = R1_gen + up_B2
# Add instance noise to the real image.
if critic_input == 'R':
B1 = instance_noise_B_Rdomain(B1,
up_B2,
alpha)
else:
B1 = instance_noise_B_Bdomain(B1,
alpha)
# The ground truth residual.
R1_real = B1 - up_B2
# The encoded ground truth residual.
if DETERMINISTIC:
z_enc = encoder([R1_real,
up_B2])
else:
z_enc = reparameterize(encoder([R1_real,
up_B2]))
# The cycled ground truth residual.
R1_cyc = generator([z_enc,
up_B2])
# Add instance noise to the cycled residual. Noise does enter into this twice, since both B1 and now R1_cyc are noise-ified...but this will improve as the noise is phased out.
if critic_input == 'R':
R1_cyc = instance_noise_R_Rdomain(R1_cyc,
alpha)
else:
R1_cyc = instance_noise_R_Bdomain(R1_cyc,
up_B2,
alpha)
# The full B-domain cycled image is then:
B1_cyc = R1_cyc + up_B2
# The critic verdict on the generated residual and
# the critic verdict on the cycled residual.
if critic_input == 'B':
verdict_R1_gen = critic(B1_gen)
verdict_R1_cyc = critic(B1_cyc)
elif critic_input == 'R':
verdict_R1_gen = critic(R1_gen)
verdict_R1_cyc = critic(R1_cyc)
elif critic_input == 'AB':
verdict_R1_gen = critic([B1_gen,
up_B2])
verdict_R1_cyc = critic([B1_cyc,
up_B2])
# Get the loss for generator.
G_loss = generator_loss(R1_real,
R1_gen,
R1_cyc,
verdict_R1_gen,
verdict_R1_cyc,
CONSISTENT,
G_loss_weights)
# Get the total loss.
total_G_loss = G_loss[0]
# Now, calculate the gradients for generator.
G_gradients = gen_tape.gradient(total_G_loss,
generator.trainable_variables)
# Apply the gradients to generator.
generator_optimizer.apply_gradients(zip(G_gradients,
generator.trainable_variables))
return G_loss
@tf.function
def encoder_train_step(x,
critic_input,
DETERMINISTIC,
alpha):
"""
Args:
x: tuple (z, A, B)
NOTE: z, A, and B are all BATCHES of size batch_size. They are NOT individual examples. For example, z has TensorShape([200, 100]) for batch_size=200 and z_dim=100.
critic_input: One of 'AB', 'B', or 'R'. The input(s) to the critic.
DETERMINISTIC: Boolean. Whether or not E is deterministic, outputting a z vector, or variational, outputting a tuple (mu, logvar).
alpha: (1-alpha) is the fraction of instance noise.
Returns:
E_loss: The outputs of encoder_loss(...) for the encoder.
Updates the encoder's weights.
"""
(z, up_B2, B1) = x
with tf.GradientTape() as enc_tape:
# The generated residual.
R1_gen = generator([z,
up_B2])
# Add instance noise to the fake image.
if critic_input == 'R':
R1_gen = instance_noise_R_Rdomain(R1_gen,
alpha)
else:
R1_gen = instance_noise_R_Bdomain(R1_gen,
up_B2,
alpha)
# The cycled z vector.
if DETERMINISTIC:
z_cyc = encoder([R1_gen,
up_B2])
else:
z_cyc = encoder([R1_gen,
up_B2])[0]
# Add instance noise to the real image.
if critic_input == 'R':
B1 = instance_noise_B_Rdomain(B1,
up_B2,
alpha)
else:
B1 = instance_noise_B_Bdomain(B1,
alpha)
# The ground truth residual.
R1_real = B1 - up_B2
# The encoded ground truth residual.
if DETERMINISTIC:
z_enc = encoder([R1_real,
up_B2])
else:
z_enc = reparameterize(encoder([R1_real,
up_B2]))
# Get the loss for encoder.
E_loss = encoder_loss(z,
z_cyc,
z_enc,
E_loss_weights)
# Get the total loss.
total_E_loss = E_loss[0]
# Now, calculate the gradients for encoder.
E_gradients = enc_tape.gradient(total_E_loss,
encoder.trainable_variables)
# Apply the gradients to encoder.
encoder_optimizer.apply_gradients(zip(E_gradients,
encoder.trainable_variables))
return E_loss
@tf.function
def critic_train_step(x,
critic_input,
DETERMINISTIC,
alpha):
"""
Args:
x: tuple (z, up(B2), B1)
critic_input: One of 'AB', 'B', or 'R'. The input(s) to the critic.
DETERMINISTIC: Boolean. Whether or not E is deterministic, outputting a z vector, or variational, outputting a tuple (mu, logvar).
alpha: (1-alpha) is the fraction of instance noise.
Returns:
C_loss: The outputs of critic_loss(...) for the critic.
Updates the critic's weights.
"""
(z, up_B2, B1) = x
with tf.GradientTape() as crit_tape:
# The generated residual.
R1_gen = generator([z,
up_B2])
# Add instance noise to the fake image.
if critic_input == 'R':
R1_gen = instance_noise_R_Rdomain(R1_gen,
alpha)
else:
R1_gen = instance_noise_R_Bdomain(R1_gen,
up_B2,
alpha)
# The full B-domain generated image is then:
B1_gen = R1_gen + up_B2
# Add instance noise to the real image.
if critic_input == 'R':
B1 = instance_noise_B_Rdomain(B1,
up_B2,
alpha)
else:
B1 = instance_noise_B_Bdomain(B1,
alpha)
# The ground truth residual.
R1_real = B1 - up_B2
# The encoded ground truth residual.
if DETERMINISTIC:
z_enc = encoder([R1_real,
up_B2])
else:
z_enc = reparameterize(encoder([R1_real,
up_B2]))
# The cycled ground truth residual.
R1_cyc = generator([z_enc,
up_B2])
# Add instance noise to the cycled residual. Noise does enter into this twice, since both B1 and now R1_cyc are noise-ified...but this will improve as the noise is phased out.
if critic_input == 'R':
R1_cyc = instance_noise_R_Rdomain(R1_cyc,
alpha)
else:
R1_cyc = instance_noise_R_Bdomain(R1_cyc,
up_B2,
alpha)
# The full B-domain cycled image is then:
B1_cyc = R1_cyc + up_B2
# Randomly weighted averages for the Wasserstein GP loss term.
random_average_gen = RandomWeightedAverage(tf.identity(R1_real),
tf.identity(R1_gen))
random_average_cyc = RandomWeightedAverage(tf.identity(R1_real),
tf.identity(R1_cyc))
# Need these in the B domain, depending on the critic input.
if critic_input=='B' \
or critic_input=='AB':
random_B1_gen = random_average_gen + up_B2
random_B1_cyc = random_average_cyc + up_B2
# The critic verdict on the ground truth residual,
# the critic verdict on the generated residual,
# the critic verdict on the cycled residual,
# the critic verdict on the random average of real and gen, and
# the critic verdict on the random average of real and cyc.
if critic_input == 'B':
verdict_R1_real = critic(B1)
verdict_R1_gen = critic(B1_gen)
verdict_R1_cyc = critic(B1_cyc)
verdict_avg_gen = critic(random_B1_gen)
verdict_avg_cyc = critic(random_B1_cyc)
elif critic_input == 'R':
verdict_R1_real = critic(R1_real)
verdict_R1_gen = critic(R1_gen)
verdict_R1_cyc = critic(R1_cyc)
verdict_avg_gen = critic(random_average_gen)
verdict_avg_cyc = critic(random_average_cyc)
elif critic_input == 'AB':
verdict_R1_real = critic([B1,
up_B2])
verdict_R1_gen = critic([B1_gen,
up_B2])
verdict_R1_cyc = critic([B1_cyc,
up_B2])
verdict_avg_gen = critic([random_B1_gen,
up_B2])
verdict_avg_cyc = critic([random_B1_cyc,
up_B2])
# Get the loss for critic_2.
C_loss = critic_loss(verdict_R1_real,
verdict_R1_gen,
verdict_R1_cyc,
random_average_gen,
verdict_avg_gen,
random_average_cyc,
verdict_avg_cyc,
C_loss_weights)
total_C_loss = C_loss[0]
# Now, calculate the gradients for critic.
C_gradients = crit_tape.gradient(total_C_loss,
critic.trainable_variables)
# Apply the gradients to critic.
critic_optimizer.apply_gradients(zip(C_gradients,
critic.trainable_variables))
return C_loss
"""
DEFINE EVALUATORS
"""
@tf.function
def generator_eval(x,
critic_input,
DETERMINISTIC,
CONSISTENT,
alpha):
"""
Args:
x: tuple (z, A, B)
critic_input: One of 'AB', 'B', or 'R'. The input(s) to the critic.
DETERMINISTIC: Boolean. Whether or not E is deterministic, outputting a z vector, or variational, outputting a tuple (mu, logvar).
CONSISTENT: Boolean. Whether or not to include self-consistency terms in the generator loss function.
alpha: (1-alpha) is the fraction of instance noise.
Returns:
G_loss: The outputs of generator_loss(...) for the generator.
"""
(z, up_B2, B1) = x
# The generated residual.
R1_gen = generator([z,
up_B2])
# Add instance noise to the fake image.
if critic_input == 'R':
R1_gen = instance_noise_R_Rdomain(R1_gen,
alpha)
else:
R1_gen = instance_noise_R_Bdomain(R1_gen,
up_B2,
alpha)
# The full B-domain generated image is then:
B1_gen = R1_gen + up_B2
# Add instance noise to the real image.
if critic_input == 'R':
B1 = instance_noise_B_Rdomain(B1,
up_B2,
alpha)
else:
B1 = instance_noise_B_Bdomain(B1,
alpha)
# The ground truth residual.
R1_real = B1 - up_B2
# The encoded ground truth residual.
if DETERMINISTIC:
z_enc = encoder([R1_real,
up_B2])
else:
z_enc = reparameterize(encoder([R1_real,
up_B2]))
# The cycled ground truth residual.
R1_cyc = generator([z_enc,
up_B2])
# Add instance noise to the cycled residual. Noise does enter into this twice, since both B1 and now R1_cyc are noise-ified...but this will improve as the noise is phased out.
if critic_input == 'R':
R1_cyc = instance_noise_R_Rdomain(R1_cyc,
alpha)
else:
R1_cyc = instance_noise_R_Bdomain(R1_cyc,
up_B2,
alpha)
# The full B-domain cycled image is then:
B1_cyc = R1_cyc + up_B2
# The critic verdict on the generated residual and
# the critic verdict on the cycled residual.
if critic_input == 'B':
verdict_R1_gen = critic(B1_gen)
verdict_R1_cyc = critic(B1_cyc)
elif critic_input == 'R':
verdict_R1_gen = critic(R1_gen)
verdict_R1_cyc = critic(R1_cyc)
elif critic_input == 'AB':
verdict_R1_gen = critic([B1_gen,
up_B2])
verdict_R1_cyc = critic([B1_cyc,
up_B2])
# Get the loss for generator.
G_loss = generator_loss(R1_real,
R1_gen,
R1_cyc,
verdict_R1_gen,
verdict_R1_cyc,
CONSISTENT,
G_loss_weights)
return G_loss
@tf.function
def encoder_eval(x,
critic_input,
DETERMINISTIC,
alpha):
"""
Args:
x: tuple (z, A, B)
NOTE: z, A, and B are all BATCHES of size batch_size. They are NOT individual examples. For example, z has TensorShape([200, 100]) for batch_size=200 and z_dim=100.
critic_input: One of 'AB', 'B', or 'R'. The input(s) to the critic.
DETERMINISTIC: Boolean. Whether or not E is deterministic, outputting a z vector, or variational, outputting a tuple (mu, logvar).
alpha: (1-alpha) is the fraction of instance noise.
Returns:
E_loss: The outputs of encoder_loss(...) for the encoder.
"""
(z, up_B2, B1) = x
# The generated residual.
R1_gen = generator([z,
up_B2])
# Add instance noise to the fake image.
if critic_input == 'R':
R1_gen = instance_noise_R_Rdomain(R1_gen,
alpha)
else:
R1_gen = instance_noise_R_Bdomain(R1_gen,
up_B2,
alpha)
# The cycled z vector.
if DETERMINISTIC:
z_cyc = encoder([R1_gen,
up_B2])
else:
z_cyc = encoder([R1_gen,
up_B2])[0]
# Add instance noise to the real image.
if critic_input == 'R':
B1 = instance_noise_B_Rdomain(B1,
up_B2,
alpha)
else:
B1 = instance_noise_B_Bdomain(B1,
alpha)
# The ground truth residual.
R1_real = B1 - up_B2
# The encoded ground truth residual.
if DETERMINISTIC:
z_enc = encoder([R1_real,
up_B2])
else:
z_enc = reparameterize(encoder([R1_real,
up_B2]))
# Get the loss for encoder.
E_loss = encoder_loss(z,
z_cyc,
z_enc,
E_loss_weights)
return E_loss
@tf.function
def critic_eval(x,
critic_input,
DETERMINISTIC,
alpha):
"""
Args:
x: tuple (z, up(B2), B1)
critic_input: One of 'AB', 'B', or 'R'. The input(s) to the critic.
DETERMINISTIC: Boolean. Whether or not E is deterministic, outputting a z vector, or variational, outputting a tuple (mu, logvar).
alpha: (1-alpha) is the fraction of instance noise.
Returns:
C_loss: The outputs of critic_loss(...) for the critic.
"""
(z, up_B2, B1) = x
# The generated residual.
R1_gen = generator([z,
up_B2])
# Add instance noise to the fake image.
if critic_input == 'R':
R1_gen = instance_noise_R_Rdomain(R1_gen,
alpha)
else:
R1_gen = instance_noise_R_Bdomain(R1_gen,
up_B2,
alpha)
# The full B-domain generated image is then:
B1_gen = R1_gen + up_B2
# Add instance noise to the real image.
if critic_input == 'R':
B1 = instance_noise_B_Rdomain(B1,
up_B2,
alpha)
else:
B1 = instance_noise_B_Bdomain(B1,
alpha)
# The ground truth residual.
R1_real = B1 - up_B2
# The encoded ground truth residual.
if DETERMINISTIC:
z_enc = encoder([R1_real,
up_B2])
else:
z_enc = reparameterize(encoder([R1_real,
up_B2]))
# The cycled ground truth residual.
R1_cyc = generator([z_enc,
up_B2])
# Add instance noise to the cycled residual. Noise does enter into this twice, since both B1 and now R1_cyc are noise-ified...but this will improve as the noise is phased out.
if critic_input == 'R':
R1_cyc = instance_noise_R_Rdomain(R1_cyc,
alpha)
else:
R1_cyc = instance_noise_R_Bdomain(R1_cyc,
up_B2,
alpha)
# The full B-domain cycled image is then:
B1_cyc = R1_cyc + up_B2
# Randomly weighted averages for the Wasserstein GP loss term.
random_average_gen = RandomWeightedAverage(tf.identity(R1_real),
tf.identity(R1_gen))
random_average_cyc = RandomWeightedAverage(tf.identity(R1_real),
tf.identity(R1_cyc))
# Need these in the B domain, depending on the critic input.
if critic_input=='B' \
or critic_input=='AB':
random_B1_gen = random_average_gen + up_B2
random_B1_cyc = random_average_cyc + up_B2
# The critic verdict on the ground truth residual,
# the critic verdict on the generated residual,
# the critic verdict on the cycled residual,
# the critic verdict on the random average of real and gen, and
# the critic verdict on the random average of real and cyc.
if critic_input == 'B':
verdict_R1_real = critic(B1)
verdict_R1_gen = critic(B1_gen)
verdict_R1_cyc = critic(B1_cyc)
verdict_avg_gen = critic(random_B1_gen)
verdict_avg_cyc = critic(random_B1_cyc)
elif critic_input == 'R':
verdict_R1_real = critic(R1_real)
verdict_R1_gen = critic(R1_gen)
verdict_R1_cyc = critic(R1_cyc)
verdict_avg_gen = critic(random_average_gen)
verdict_avg_cyc = critic(random_average_cyc)
elif critic_input == 'AB':
verdict_R1_real = critic([B1,
up_B2])
verdict_R1_gen = critic([B1_gen,
up_B2])
verdict_R1_cyc = critic([B1_cyc,
up_B2])
verdict_avg_gen = critic([random_B1_gen,
up_B2])
verdict_avg_cyc = critic([random_B1_cyc,
up_B2])
# Get the loss for critic_2.
C_loss = critic_loss(verdict_R1_real,
verdict_R1_gen,
verdict_R1_cyc,
random_average_gen,
verdict_avg_gen,
random_average_cyc,
verdict_avg_cyc,
C_loss_weights)
return C_loss
"""
FUNCTION FOR SAVING IMAGES DURING TRAINING
"""
def generate_and_save_images(epoch,
critic_input,
alpha,
DETERMINISTIC):
"""
Args:
epoch: The epoch.