-
Notifications
You must be signed in to change notification settings - Fork 9
/
model_full.py
1734 lines (1405 loc) · 92.4 KB
/
model_full.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 torch
import torch.nn as nn
import torch.nn.functional as F
import numpy as np
import time
from tqdm import tqdm
import os
from PIL import Image
from collections import OrderedDict
from vgg_utils.VGG16 import VGG_Slim
from dataset_utils.common import generate_colors2
from hparam import HParams
from rnn2 import HyperLSTMCell
from utils import correspondence_clinging, get_correspondence_window_size, spatial_transform_reverse_point, \
image_cropping_stn, normalize_image_m1to1, draw_dot, seq_params_to_list
import pydiffvg
pydiffvg.set_use_gpu(torch.cuda.is_available())
print('Setting pydiffvg.set_use_gpu:', torch.cuda.is_available())
def get_default_hparams():
"""Return default HParams for sketch-rnn."""
hparams = HParams(
add_coordconv=True,
use_atrous_conv=False,
first_kernel_size=3, # 7 or 3
z_size=256, # Size of latent vector z.
# parameters for two transformation modules
use_square_window=False,
init_window_size_corres_trans=0.6,
transform_with_rotation=True,
transform_use_global_info=True,
enc_model_transform='combined', # ['combined', 'separated']
dec_model_transform='mlp', # ['rnn', 'mlp']
transform_module_zero_init='last', # ['none', 'last', 'all']
frozen_transform_module=True,
# parameters for correspondence module
enc_model_correspondence='separated', # ['combined', 'separated']
raster_size_corres=256, # cropping size for starting point correspondence module
use_clinging=True,
clinging_binary_threshold=128.0,
use_segment_img=True,
use_reference_canvas=False,
use_target_canvas=True,
use_attn_corres=True,
attn_type_corres='SA',
sa_block_pos_corres=3, # [1, 2, 3, 4]
use_dropout=False,
dropout_rate=0.3, # probability of an element to be zeroed
# parameters for tracing module
raster_size=192,
window_size_scaling_ref=1.5, # [1.25, 1.5, 2.0]
window_size_scaling_init_tar=1.5, # [1.25, 1.5, 2.0]
window_size_scaling_times_tar=(0.2, 2.0),
window_size_min=48, # [1.25, 1.5, 2.0]
hidden_states_zero=True, # whether setting input hidden states to zero for starting of each stroke
enc_model_tracing='separated', # ['combined', 'separated']
dec_model_tracing='rnn', # ['rnn', 'mlp']
dec_rnn_size=256, # Size of decoder.
rnn_model='hyper', # Decoder: lstm, layer_norm or hyper.
stroke_thickness=1.2, # 2.0 for toy; 1.2 for TUB
raster_loss_base_type='perceptual', # [l1, mse, perceptual]
perc_loss_layers=['ReLU1_2', 'ReLU2_2', 'ReLU3_3', 'ReLU4_3', 'ReLU5_1'],
perc_loss_fuse_type='add', # ['max', 'add', 'raw_add', 'weighted_sum']
perceptual_model_path='models/quickdraw-perceptual.pth',
trained_models_dir='models',
inference_root='outputs/inference'
)
return hparams
def general_conv2d(in_dim, output_dim, kernel_size, stride, do_norm=True, norm_type='instance_norm', padding=1,
atrous=False, atrous_rate=1):
if atrous:
conv = nn.Conv2d(in_dim, output_dim, kernel_size=kernel_size, stride=stride, padding=atrous_rate, dilation=atrous_rate)
else:
conv = nn.Conv2d(in_dim, output_dim, kernel_size=kernel_size, stride=stride, padding=padding)
if do_norm:
if norm_type == 'instance_norm':
norm = nn.InstanceNorm2d(output_dim, affine=True)
elif norm_type == 'batch_norm':
norm = nn.BatchNorm2d(output_dim)
elif norm_type == 'layer_norm':
norm = nn.LayerNorm(output_dim)
else:
raise Exception('Unknown norm_type:', norm_type)
return nn.Sequential(
OrderedDict([
('conv', conv),
(norm_type, norm)
]))
else:
return conv
class SelfAttention(nn.Module):
def __init__(self, in_dim):
super(SelfAttention, self).__init__()
self.query_conv = nn.Conv2d(in_channels=in_dim, out_channels=in_dim // 8, kernel_size=1)
self.key_conv = nn.Conv2d(in_channels=in_dim, out_channels=in_dim // 8, kernel_size=1)
self.value_conv = nn.Conv2d(in_channels=in_dim, out_channels=in_dim, kernel_size=1)
self.output_conv = nn.Conv2d(in_channels=in_dim, out_channels=in_dim, kernel_size=1)
self.gamma = nn.Parameter(torch.zeros(1))
self.softmax = nn.Softmax(dim=-1)
def forward(self, x):
"""
inputs :
x : input feature maps (N, C, h, w)
returns :
out : self attention value + input feature
attention: N X hw X hw
"""
m_batchsize, C, height, width = x.size()
proj_query = self.query_conv(x).view(m_batchsize, -1, height * width).permute(0, 2, 1) # (N, hw, c)
proj_key = self.key_conv(x).view(m_batchsize, -1, height * width) # (N, c, hw)
energy = torch.bmm(proj_query, proj_key) # (N, hw, hw)
attn_map = self.softmax(energy) # (N, hw, hw)
proj_value = self.value_conv(x).view(m_batchsize, -1, height * width) # (N, C, hw)
x_attn = torch.bmm(proj_value, attn_map.permute(0, 2, 1)) # (N, C, hw)
x_attn = x_attn.view(m_batchsize, C, height, width) # (N, C, h, w)
x_attn = self.output_conv(x_attn) # (N, C, h, w)
out = self.gamma * x_attn + x
return out, attn_map
class CNN_SepEncoder_correspondence(nn.Module):
def __init__(self, input_dim_ref, input_dim_tar, output_dim, input_size, use_atrous,
use_attn, attn_type=None, sa_block_pos=None, use_dropout=False, dropout_rate=0.0):
super(CNN_SepEncoder_correspondence, self).__init__()
if use_atrous:
atrou_rates = [1, 1, 2, 4, 4]
else:
atrou_rates = [1, 1, 1, 1, 1]
# reference
self.cnn_enc_11_ref = general_conv2d(input_dim_ref, 16, kernel_size=3, stride=1, atrous=use_atrous, atrous_rate=atrou_rates[0])
self.cnn_enc_12_ref = general_conv2d(16, 32, kernel_size=3, stride=2, atrous=use_atrous, atrous_rate=atrou_rates[0])
self.cnn_enc_21_ref = general_conv2d(32, 32, kernel_size=3, stride=1, atrous=use_atrous, atrous_rate=atrou_rates[1])
self.cnn_enc_22_ref = general_conv2d(32, 64, kernel_size=3, stride=2, atrous=use_atrous, atrous_rate=atrou_rates[1])
self.cnn_enc_31_ref = general_conv2d(64, 64, kernel_size=3, stride=1, atrous=use_atrous, atrous_rate=atrou_rates[2])
self.cnn_enc_32_ref = general_conv2d(64, 64, kernel_size=3, stride=1, atrous=use_atrous, atrous_rate=atrou_rates[2])
self.cnn_enc_33_ref = general_conv2d(64, 128, kernel_size=3, stride=2, atrous=use_atrous, atrous_rate=atrou_rates[2])
self.cnn_enc_41_ref = general_conv2d(128, 128, kernel_size=3, stride=1, atrous=use_atrous, atrous_rate=atrou_rates[3])
self.cnn_enc_42_ref = general_conv2d(128, 128, kernel_size=3, stride=1, atrous=use_atrous, atrous_rate=atrou_rates[3])
self.cnn_enc_43_ref = general_conv2d(128, 256, kernel_size=3, stride=2, atrous=use_atrous, atrous_rate=atrou_rates[3])
# target
self.cnn_enc_11_tar = general_conv2d(input_dim_tar, 16, kernel_size=3, stride=1, atrous=use_atrous, atrous_rate=atrou_rates[0])
self.cnn_enc_12_tar = general_conv2d(16, 32, kernel_size=3, stride=2, atrous=use_atrous, atrous_rate=atrou_rates[0])
self.cnn_enc_21_tar = general_conv2d(64, 32, kernel_size=3, stride=1, atrous=use_atrous, atrous_rate=atrou_rates[1])
self.cnn_enc_22_tar = general_conv2d(32, 64, kernel_size=3, stride=2, atrous=use_atrous, atrous_rate=atrou_rates[1])
self.cnn_enc_31_tar = general_conv2d(128, 64, kernel_size=3, stride=1, atrous=use_atrous, atrous_rate=atrou_rates[2])
self.cnn_enc_32_tar = general_conv2d(64, 64, kernel_size=3, stride=1, atrous=use_atrous, atrous_rate=atrou_rates[2])
self.cnn_enc_33_tar = general_conv2d(64, 128, kernel_size=3, stride=2, atrous=use_atrous, atrous_rate=atrou_rates[2])
self.cnn_enc_41_tar = general_conv2d(256, 128, kernel_size=3, stride=1, atrous=use_atrous, atrous_rate=atrou_rates[3])
self.cnn_enc_42_tar = general_conv2d(128, 128, kernel_size=3, stride=1, atrous=use_atrous, atrous_rate=atrou_rates[3])
self.cnn_enc_43_tar = general_conv2d(128, 256, kernel_size=3, stride=2, atrous=use_atrous, atrous_rate=atrou_rates[3])
self.cnn_enc_51_tar = general_conv2d(512, 256, kernel_size=3, stride=1, atrous=use_atrous, atrous_rate=atrou_rates[4])
self.cnn_enc_52_tar = general_conv2d(256, 256, kernel_size=3, stride=1, atrous=use_atrous, atrous_rate=atrou_rates[4])
self.cnn_enc_53_tar = general_conv2d(256, 512, kernel_size=3, stride=2, atrous=use_atrous, atrous_rate=atrou_rates[4])
self.use_attn = [False for _ in range(4)]
if use_attn:
if attn_type == 'SA':
assert sa_block_pos in [1, 2, 3, 4]
self.attn_1 = SelfAttention(in_dim=64) if sa_block_pos == 1 else None
self.attn_2 = SelfAttention(in_dim=128) if sa_block_pos == 2 else None
self.attn_3 = SelfAttention(in_dim=256) if sa_block_pos == 3 else None
self.attn_4 = SelfAttention(in_dim=512) if sa_block_pos == 4 else None
self.use_attn[int(sa_block_pos - 1)] = True
else:
raise Exception('Unknown attn_type:', attn_type)
assert input_size % 32 == 0
self.feature_size = input_size // 32
self.gap = nn.AvgPool2d(self.feature_size)
self.use_dropout = use_dropout
if self.use_dropout:
self.dropout = nn.Dropout(dropout_rate)
self.fc = nn.Linear(512, output_dim)
def forward(self, inputs_ref, inputs_tar):
x_r = inputs_ref
x_r11 = F.relu(self.cnn_enc_11_ref(x_r))
x_r12 = F.relu(self.cnn_enc_12_ref(x_r11))
x_r21 = F.relu(self.cnn_enc_21_ref(x_r12))
x_r22 = F.relu(self.cnn_enc_22_ref(x_r21))
x_r31 = F.relu(self.cnn_enc_31_ref(x_r22))
x_r32 = F.relu(self.cnn_enc_32_ref(x_r31))
x_r33 = F.relu(self.cnn_enc_33_ref(x_r32))
x_r41 = F.relu(self.cnn_enc_41_ref(x_r33))
x_r42 = F.relu(self.cnn_enc_42_ref(x_r41))
x_r43 = F.relu(self.cnn_enc_43_ref(x_r42))
x = inputs_tar
x = F.relu(self.cnn_enc_11_tar(x))
x = F.relu(self.cnn_enc_12_tar(x))
x = torch.cat([x, x_r12], dim=1)
if self.use_attn[0]:
x = F.relu(self.attn_1(x)[0])
x = F.relu(self.cnn_enc_21_tar(x))
x = F.relu(self.cnn_enc_22_tar(x))
x = torch.cat([x, x_r22], dim=1)
if self.use_attn[1]:
x = F.relu(self.attn_2(x)[0])
x = F.relu(self.cnn_enc_31_tar(x))
x = F.relu(self.cnn_enc_32_tar(x))
x = F.relu(self.cnn_enc_33_tar(x))
x = torch.cat([x, x_r33], dim=1)
if self.use_attn[2]:
x = F.relu(self.attn_3(x)[0])
x = F.relu(self.cnn_enc_41_tar(x))
x = F.relu(self.cnn_enc_42_tar(x))
x = F.relu(self.cnn_enc_43_tar(x))
x = torch.cat([x, x_r43], dim=1)
if self.use_attn[3]:
x = F.relu(self.attn_4(x)[0])
x = F.relu(self.cnn_enc_51_tar(x))
x = F.relu(self.cnn_enc_52_tar(x))
x = F.relu(self.cnn_enc_53_tar(x)) # (N, C, H/32, W/32)
x = self.gap(x) # (N, C, 1, 1)
x = torch.reshape(x, (x.size(0), -1)) # (N, C)
if self.use_dropout:
x = self.dropout(x)
x = self.fc(x) # (N, 2)
x = torch.tanh(x) # (N, 2), [-1.0, 1.0]
return x
class CNN_SepEncoder(nn.Module):
def __init__(self, input_dim_ref, input_dim_tar, output_dim, input_size, first_kernel_size, first_padding, use_atrous):
super(CNN_SepEncoder, self).__init__()
if use_atrous:
atrou_rates = [1, 1, 2, 4, 4]
else:
atrou_rates = [1, 1, 1, 1, 1]
# reference
self.cnn_enc_11_ref = general_conv2d(input_dim_ref, 32, kernel_size=first_kernel_size, stride=2, padding=first_padding, atrous=use_atrous, atrous_rate=atrou_rates[0])
self.cnn_enc_12_ref = general_conv2d(32, 32, kernel_size=3, stride=1, atrous=use_atrous, atrous_rate=atrou_rates[0])
self.cnn_enc_21_ref = general_conv2d(32, 64, kernel_size=3, stride=2, atrous=use_atrous, atrous_rate=atrou_rates[1])
self.cnn_enc_22_ref = general_conv2d(64, 64, kernel_size=3, stride=1, atrous=use_atrous, atrous_rate=atrou_rates[1])
self.cnn_enc_31_ref = general_conv2d(64, 128, kernel_size=3, stride=2, atrous=use_atrous, atrous_rate=atrou_rates[2])
self.cnn_enc_32_ref = general_conv2d(128, 128, kernel_size=3, stride=1, atrous=use_atrous, atrous_rate=atrou_rates[2])
self.cnn_enc_33_ref = general_conv2d(128, 128, kernel_size=3, stride=1, atrous=use_atrous, atrous_rate=atrou_rates[2])
self.cnn_enc_41_ref = general_conv2d(128, 256, kernel_size=3, stride=2, atrous=use_atrous, atrous_rate=atrou_rates[3])
self.cnn_enc_42_ref = general_conv2d(256, 256, kernel_size=3, stride=1, atrous=use_atrous, atrous_rate=atrou_rates[3])
self.cnn_enc_43_ref = general_conv2d(256, 256, kernel_size=3, stride=1, atrous=use_atrous, atrous_rate=atrou_rates[3])
# target
self.cnn_enc_11_tar = general_conv2d(input_dim_tar, 32, kernel_size=first_kernel_size, stride=2, padding=first_padding, atrous=use_atrous, atrous_rate=atrou_rates[0])
self.cnn_enc_12_tar = general_conv2d(32, 32, kernel_size=3, stride=1, atrous=use_atrous, atrous_rate=atrou_rates[0])
self.cnn_enc_21_tar = general_conv2d(64, 64, kernel_size=3, stride=2, atrous=use_atrous, atrous_rate=atrou_rates[1])
self.cnn_enc_22_tar = general_conv2d(64, 64, kernel_size=3, stride=1, atrous=use_atrous, atrous_rate=atrou_rates[1])
self.cnn_enc_31_tar = general_conv2d(128, 128, kernel_size=3, stride=2, atrous=use_atrous, atrous_rate=atrou_rates[2])
self.cnn_enc_32_tar = general_conv2d(128, 128, kernel_size=3, stride=1, atrous=use_atrous, atrous_rate=atrou_rates[2])
self.cnn_enc_33_tar = general_conv2d(128, 128, kernel_size=3, stride=1, atrous=use_atrous, atrous_rate=atrou_rates[2])
self.cnn_enc_41_tar = general_conv2d(256, 256, kernel_size=3, stride=2, atrous=use_atrous, atrous_rate=atrou_rates[3])
self.cnn_enc_42_tar = general_conv2d(256, 256, kernel_size=3, stride=1, atrous=use_atrous, atrous_rate=atrou_rates[3])
self.cnn_enc_43_tar = general_conv2d(256, 256, kernel_size=3, stride=1, atrous=use_atrous, atrous_rate=atrou_rates[3])
self.cnn_enc_51_tar = general_conv2d(512, 512, kernel_size=3, stride=2, atrous=use_atrous, atrous_rate=atrou_rates[4])
self.cnn_enc_52_tar = general_conv2d(512, 512, kernel_size=3, stride=1, atrous=use_atrous, atrous_rate=atrou_rates[4])
self.cnn_enc_53_tar = general_conv2d(512, 512, kernel_size=3, stride=1, atrous=use_atrous, atrous_rate=atrou_rates[4])
assert input_size % 32 == 0
self.feature_size = input_size // 32
self.fc = nn.Linear(512 * self.feature_size * self.feature_size, output_dim)
self.use_attn = [False for _ in range(4)]
def forward(self, inputs_ref, inputs_tar):
x_r = inputs_ref
x_r11 = F.relu(self.cnn_enc_11_ref(x_r))
x_r12 = F.relu(self.cnn_enc_12_ref(x_r11))
x_r21 = F.relu(self.cnn_enc_21_ref(x_r12))
x_r22 = F.relu(self.cnn_enc_22_ref(x_r21))
x_r31 = F.relu(self.cnn_enc_31_ref(x_r22))
x_r32 = F.relu(self.cnn_enc_32_ref(x_r31))
x_r33 = F.relu(self.cnn_enc_33_ref(x_r32))
x_r41 = F.relu(self.cnn_enc_41_ref(x_r33))
x_r42 = F.relu(self.cnn_enc_42_ref(x_r41))
x_r43 = F.relu(self.cnn_enc_43_ref(x_r42))
x = inputs_tar
x = F.relu(self.cnn_enc_11_tar(x))
x = F.relu(self.cnn_enc_12_tar(x))
x = torch.cat([x, x_r12], dim=1)
if self.use_attn[0]:
x = F.relu(self.attn_1(x)[0])
x = F.relu(self.cnn_enc_21_tar(x))
x = F.relu(self.cnn_enc_22_tar(x))
x = torch.cat([x, x_r22], dim=1)
if self.use_attn[1]:
x = F.relu(self.attn_2(x)[0])
x = F.relu(self.cnn_enc_31_tar(x))
x = F.relu(self.cnn_enc_32_tar(x))
x = F.relu(self.cnn_enc_33_tar(x))
x = torch.cat([x, x_r33], dim=1)
if self.use_attn[2]:
x = F.relu(self.attn_3(x)[0])
x = F.relu(self.cnn_enc_41_tar(x))
x = F.relu(self.cnn_enc_42_tar(x))
x = F.relu(self.cnn_enc_43_tar(x))
x = torch.cat([x, x_r43], dim=1)
if self.use_attn[3]:
x = F.relu(self.attn_4(x)[0])
x = F.relu(self.cnn_enc_51_tar(x))
x = F.relu(self.cnn_enc_52_tar(x))
x = F.relu(self.cnn_enc_53_tar(x))
# x = x.view(-1, 512 * 4 * 4)
x = torch.reshape(x, (-1, 512 * self.feature_size * self.feature_size))
x = self.fc(x)
return x
class CNN_Encoder(nn.Module):
def __init__(self, input_dim, output_dim, input_size, first_kernel_size, first_padding, use_atrous):
super(CNN_Encoder, self).__init__()
if use_atrous:
atrou_rates = [1, 1, 2, 4, 4]
else:
atrou_rates = [1, 1, 1, 1, 1]
self.cnn_enc_11 = general_conv2d(input_dim, 32, kernel_size=first_kernel_size, stride=2, padding=first_padding, atrous=use_atrous, atrous_rate=atrou_rates[0])
self.cnn_enc_12 = general_conv2d(32, 32, kernel_size=3, stride=1, atrous=use_atrous, atrous_rate=atrou_rates[0])
self.cnn_enc_21 = general_conv2d(32, 64, kernel_size=3, stride=2, atrous=use_atrous, atrous_rate=atrou_rates[1])
self.cnn_enc_22 = general_conv2d(64, 64, kernel_size=3, stride=1, atrous=use_atrous, atrous_rate=atrou_rates[1])
self.cnn_enc_31 = general_conv2d(64, 128, kernel_size=3, stride=2, atrous=use_atrous, atrous_rate=atrou_rates[2])
self.cnn_enc_32 = general_conv2d(128, 128, kernel_size=3, stride=1, atrous=use_atrous, atrous_rate=atrou_rates[2])
self.cnn_enc_33 = general_conv2d(128, 128, kernel_size=3, stride=1, atrous=use_atrous, atrous_rate=atrou_rates[2])
self.cnn_enc_41 = general_conv2d(128, 256, kernel_size=3, stride=2, atrous=use_atrous, atrous_rate=atrou_rates[3])
self.cnn_enc_42 = general_conv2d(256, 256, kernel_size=3, stride=1, atrous=use_atrous, atrous_rate=atrou_rates[3])
self.cnn_enc_43 = general_conv2d(256, 256, kernel_size=3, stride=1, atrous=use_atrous, atrous_rate=atrou_rates[3])
self.cnn_enc_51 = general_conv2d(256, 512, kernel_size=3, stride=2, atrous=use_atrous, atrous_rate=atrou_rates[4])
self.cnn_enc_52 = general_conv2d(512, 512, kernel_size=3, stride=1, atrous=use_atrous, atrous_rate=atrou_rates[4])
self.cnn_enc_53 = general_conv2d(512, 512, kernel_size=3, stride=1, atrous=use_atrous, atrous_rate=atrou_rates[4])
assert input_size % 32 == 0
self.feature_size = input_size // 32
self.fc = nn.Linear(512 * self.feature_size * self.feature_size, output_dim)
self.use_attn = [False for _ in range(4)]
def forward(self, inputs):
x = inputs
x = F.relu(self.cnn_enc_11(x))
# print('cnn_enc_11', x.size())
x = F.relu(self.cnn_enc_12(x))
# print('cnn_enc_12', x.size())
if self.use_attn[0]:
x = F.relu(self.attn_1(x)[0])
x = F.relu(self.cnn_enc_21(x))
# print('cnn_enc_21', x.size())
x = F.relu(self.cnn_enc_22(x))
# print('cnn_enc_22', x.size())
if self.use_attn[1]:
x = F.relu(self.attn_2(x)[0])
x = F.relu(self.cnn_enc_31(x))
# print('cnn_enc_31', x.size())
x = F.relu(self.cnn_enc_32(x))
# print('cnn_enc_32', x.size())
x = F.relu(self.cnn_enc_33(x))
# print('cnn_enc_33', x.size())
if self.use_attn[2]:
x = F.relu(self.attn_3(x)[0])
x = F.relu(self.cnn_enc_41(x))
# print('cnn_enc_41', x.size())
x = F.relu(self.cnn_enc_42(x))
# print('cnn_enc_42', x.size())
x = F.relu(self.cnn_enc_43(x))
# print('cnn_enc_43', x.size())
if self.use_attn[3]:
x = F.relu(self.attn_4(x)[0])
x = F.relu(self.cnn_enc_51(x))
# print('cnn_enc_51', x.size())
x = F.relu(self.cnn_enc_52(x))
# print('cnn_enc_52', x.size())
x = F.relu(self.cnn_enc_53(x))
# print('cnn_enc_53', x.size())
# x = x.view(-1, 512 * 4 * 4)
x = torch.reshape(x, (-1, 512 * self.feature_size * self.feature_size))
# print('x', x.size())
x = self.fc(x)
# print('fc', x.size())
return x
class RNN_Decoder(nn.Module):
def __init__(self, input_size, dec_rnn_size, output_size, is_hyper=False, zero_init='none'):
super(RNN_Decoder, self).__init__()
self.input_size = input_size
self.dec_rnn_size = dec_rnn_size
self.is_hyper = is_hyper
if not is_hyper:
self.lstm = nn.LSTMCell(input_size, dec_rnn_size)
else:
self.lstm = HyperLSTMCell(input_size, dec_rnn_size)
self.dec_fc_params = nn.Linear(dec_rnn_size, output_size)
if zero_init == 'final':
for (m_name, m) in self.named_modules():
if isinstance(m, nn.Linear) and m_name == 'dec_fc_params':
nn.init.constant_(m.weight, 0)
nn.init.constant_(m.bias, 0)
elif zero_init == 'all':
for (m_name, m) in self.named_modules():
if isinstance(m, nn.Linear):
nn.init.constant_(m.weight, 0)
if m.bias is not None:
nn.init.constant_(m.bias, 0)
elif isinstance(m, nn.LayerNorm):
nn.init.constant_(m.weight, 1)
nn.init.constant_(m.bias, 0)
else:
assert zero_init == 'none'
# print('RNN_Decoder zero init:', zero_init)
def forward(self, input_x, in_state=None):
"""
:param input_x: (batch_size, input_size)
:param in_state: (h0, c0) / (h0, c0, h0_hat, c0_hat)
:return:
"""
input_state = in_state
if not self.is_hyper:
rnn_hidden, cell_state = self.lstm(input_x, input_state) # (N, dec_rnn_size)
output_state = (rnn_hidden, cell_state)
else:
input_state_h, input_state_h_hat, input_state_c, input_state_c_hat = input_state
rnn_hidden, cell_state, rnn_hidden_hat, cell_state_hat = self.lstm(
input_x, input_state_h, input_state_c, input_state_h_hat, input_state_c_hat) # each with (N, dec_rnn_size)
output_state = (rnn_hidden, rnn_hidden_hat, cell_state, cell_state_hat)
output = self.dec_fc_params(rnn_hidden) # (N, n_out)
return output, output_state
class MLP_Decoder(nn.Module):
def __init__(self, input_size, output_size, zero_init='none'):
super(MLP_Decoder, self).__init__()
self.input_size = input_size
hidden_size = 128
self.dec_fc_1 = nn.Linear(input_size, hidden_size)
# self.dec_fc_2 = nn.Linear(hidden_size, hidden_size)
self.dec_fc_params = nn.Linear(hidden_size, output_size)
if zero_init == 'last':
for (m_name, m) in self.named_modules():
if isinstance(m, nn.Linear) and m_name == 'dec_fc_params':
nn.init.constant_(m.weight, 0)
nn.init.constant_(m.bias, 0)
elif zero_init == 'all':
for (m_name, m) in self.named_modules():
if isinstance(m, nn.Linear):
nn.init.constant_(m.weight, 0)
nn.init.constant_(m.bias, 0)
else:
assert zero_init == 'none'
# print('MLP_Decoder zero init:', zero_init)
def forward(self, input_x):
"""
:param input_x: (batch_size, input_size)
:return:
"""
features_1 = self.dec_fc_1(input_x)
# features_2 = self.dec_fc_2(features_1)
output = self.dec_fc_params(features_1) # (N, n_out)
return output
class Correspondence_Model(nn.Module):
def __init__(self, hps):
super(Correspondence_Model, self).__init__()
self.hps = hps
transform_out_size = 1 if self.hps.use_square_window else 2 # scaling
transform_out_size += 2 # translation
if self.hps.transform_with_rotation:
transform_out_size += 1
first_kernel_size = self.hps.first_kernel_size
first_padding = (first_kernel_size - 1) // 2
# transform encoder
if self.hps.enc_model_transform == 'combined':
cnn_in_size = 2
if self.hps.add_coordconv:
cnn_in_size += 2
cnn_out_size = self.hps.z_size
self.encoder_transform = CNN_Encoder(cnn_in_size, cnn_out_size, input_size=self.hps.raster_size_corres,
first_kernel_size=first_kernel_size, first_padding=first_padding,
use_atrous=self.hps.use_atrous_conv)
else:
raise Exception('Unknown enc_model_transform:', self.hps.enc_model_transform)
dec_in_size = self.hps.z_size
if self.hps.dec_model_transform == 'mlp':
self.decoder_transform = MLP_Decoder(dec_in_size, transform_out_size,
zero_init=self.hps.transform_module_zero_init)
else:
raise Exception('Unknown dec_model_transform:', self.hps.dec_model_transform)
if self.hps.enc_model_correspondence == 'separated':
cnn_in_size_ref = 2
cnn_in_size_tar = 1
if self.hps.use_segment_img:
cnn_in_size_ref += 1
if self.hps.use_reference_canvas:
cnn_in_size_ref += 1
if self.hps.use_target_canvas:
cnn_in_size_tar += 1
if self.hps.add_coordconv:
cnn_in_size_ref += 2
cnn_in_size_tar += 2
cnn_out_size = 2
self.encoder = CNN_SepEncoder_correspondence(cnn_in_size_ref, cnn_in_size_tar, cnn_out_size, input_size=self.hps.raster_size_corres,
use_atrous=self.hps.use_atrous_conv,
use_attn=self.hps.use_attn_corres, attn_type=self.hps.attn_type_corres,
sa_block_pos=self.hps.sa_block_pos_corres,
use_dropout=self.hps.use_dropout, dropout_rate=self.hps.dropout_rate)
else:
raise Exception('Unknown enc_model_correspondence:', self.hps.enc_model_correspondence)
if self.hps.add_coordconv:
self.coordconv_input = self.get_coordconv() # (2, image_size, image_size)
def forward(self, reference_images, reference_dot_images, reference_segment_images, reference_canvas_images,
target_images, target_canvas_images,
cursor_position_ref, image_size, init_trans_window_sizes):
"""
:param reference_images: (N, H, W, 1), float32, [0.0-stroke, 1.0-BG]
:param reference_dot_images: (N, H_c, W_c, 1), float32, [0.0-stroke, 1.0-BG]
:param reference_segment_images: (N, H, W, 1), float32, [0.0-stroke, 1.0-BG]
:param reference_canvas_images: (N, H, W, 1), float32, [0.0-stroke, 1.0-BG]
:param target_images: (N, H, W, 1), float32, [0.0-stroke, 1.0-BG]
:param target_canvas_images: (N, H, W, 1), [0.0-stroke, 1.0-BG]
:param cursor_position_ref: (N, 1, 2), in size [0.0, 1.0]
:param init_trans_window_sizes: (1, 1, 2)
"""
# ================== Stage-1: Transformation ================== #
# reference_images, target_images: (N, H, W, 1), [0.0-stroke, 1.0-BG]
crop_inputs_trans = torch.cat([reference_images, target_images], dim=-1) # (N, H, W, *)
cropped_outputs_trans = image_cropping_stn(cursor_position_ref, crop_inputs_trans, image_size,
init_trans_window_sizes, raster_size=self.hps.raster_size_corres)
curr_patch_input_ref_trans = cropped_outputs_trans[:, :, :, 0:1] # (N, raster_size, raster_size, 1), [0.0-stroke, 1.0-BG]
curr_patch_input_tar_trans = cropped_outputs_trans[:, :, :, 1:2] # (N, raster_size, raster_size, 1), [0.0-stroke, 1.0-BG]
curr_patch_input_ref_trans_in = normalize_image_m1to1(curr_patch_input_ref_trans)
curr_patch_input_tar_trans_in = normalize_image_m1to1(curr_patch_input_tar_trans)
# (N, raster_size, raster_size, 1), [-1.0-stroke, 1.0-BG]
## generate the transformation of target window size
transform_z = self.build_encoder_transform(curr_patch_input_ref_trans_in, curr_patch_input_tar_trans_in)
transform_output, _ = self.build_decoder_transform(transform_z, None)
# transform_output: (N, 5)
transform_output_translation = transform_output[:, 0:2] # (N, 2)
transform_output_scaling = transform_output[:, 2:4] # (N, 2)
if self.hps.transform_with_rotation:
transform_output_rotate_angle = transform_output[:, 4:5] # (N, 1)
## Then, use a small window to crop patches for the correspondence
corres_window_sizes_ref = torch.tensor([self.hps.raster_size_corres, self.hps.raster_size_corres]).float()
corres_window_sizes_ref = corres_window_sizes_ref.unsqueeze(dim=0).unsqueeze(dim=0).cuda() # (1, 1, 2)
## Reference
crop_inputs_corres_ref = torch.cat([reference_images, reference_segment_images, reference_canvas_images], dim=-1) # (N, H, W, *)
crop_outputs_corres_ref = image_cropping_stn(cursor_position_ref, crop_inputs_corres_ref, image_size,
corres_window_sizes_ref, raster_size=self.hps.raster_size_corres)
reference_images_patch_corres = crop_outputs_corres_ref[:, :, :, 0:1]
reference_segment_images_patch_corres = crop_outputs_corres_ref[:, :, :, 1:2]
reference_canvas_images_patch_corres = crop_outputs_corres_ref[:, :, :, 2:3]
# reference_images_patch_corres: (N, H_c, W_c, 1), [0-stroke, 1-BG]
# reference_segment_images_patch_corres: (N, H_c, W_c, 1), [0-stroke, 1-BG]
# reference_canvas_images_patch_corres: (N, H_c, W_c, 1), [0-stroke, 1-BG]
## Target
# Translation
pred_window_translate = torch.tanh(transform_output_translation) # (N, 2), [-1.0, 1.0]
pred_window_translate = pred_window_translate.unsqueeze(dim=1) * (init_trans_window_sizes / 2.0) # (N, 1, 2), in full size
pred_cursor_position_tar = cursor_position_ref * image_size + pred_window_translate # (N, 1, 2), in full size
# print(' >> Correspondence | pred_cursor_position_tar', pred_cursor_position_tar)
pred_cursor_position_tar = pred_cursor_position_tar / float(image_size) # (N, 1, 2), [0.0, 1.0]
# Scaling
pred_window_scaling_times_tar = torch.tanh(transform_output_scaling) # (N, 2), [-1.0, 1.0]
pred_window_scaling_times_tar = (pred_window_scaling_times_tar + 1.0) / 2.0 * self.hps.window_size_scaling_times_tar[1] # (N, 2), [0.0, 2.0]
pred_window_scaling_times_tar = torch.clamp(pred_window_scaling_times_tar, self.hps.window_size_scaling_times_tar[0], self.hps.window_size_scaling_times_tar[1]) # (N, 2), [0.2, 2.0]
# print(' >> Correspondence | pred_window_scaling_times_tar', pred_window_scaling_times_tar)
curr_window_size_tar_pred = pred_window_scaling_times_tar.unsqueeze(dim=1) * corres_window_sizes_ref # (N, 1, 2), in full size
curr_window_size_tar_pred = torch.max(curr_window_size_tar_pred, torch.tensor(self.hps.window_size_min).float().cuda())
curr_window_size_tar_pred = torch.min(curr_window_size_tar_pred, torch.tensor(image_size * 2.0).float().cuda())
# Rotation
if self.hps.transform_with_rotation:
pred_window_rotate_angle_tar = torch.tanh(transform_output_rotate_angle) # (N, 1), [-1.0, 1.0]
pred_window_rotate_angle_tar = torch.mul(pred_window_rotate_angle_tar, 180.0) # (N, 1), [-180.0, 180.0]
# print(' >> Correspondence | pred_window_rotate_angle_tar', pred_window_rotate_angle_tar)
else:
pred_window_rotate_angle_tar = None
## crop the target again
crop_inputs_corres_tar = torch.cat([target_images, target_canvas_images], dim=-1) # (N, H, W, *)
cropped_outputs_corres_tar = image_cropping_stn(pred_cursor_position_tar, crop_inputs_corres_tar, image_size,
curr_window_size_tar_pred, raster_size=self.hps.raster_size_corres,
rotation_angle=pred_window_rotate_angle_tar)
target_images_patch_corres = cropped_outputs_corres_tar[:, :, :, 0:1]
target_canvas_images_patch_corres = cropped_outputs_corres_tar[:, :, :, 1:2]
# target_images_patch_corres: (N, H_c, W_c, 1), [0-stroke, 1-BG]
# target_canvas_images_patch_corres: (N, H_c, W_c, 1), [0-stroke, 1-BG]
# ================== Stage-2: Correspondence ================== #
reference_images_patch_corres_in = normalize_image_m1to1(reference_images_patch_corres)
reference_dot_img_patch_corres_in = normalize_image_m1to1(reference_dot_images)
reference_segment_images_patch_corres_in = normalize_image_m1to1(reference_segment_images_patch_corres)
reference_canvas_images_patch_corres_in = normalize_image_m1to1(reference_canvas_images_patch_corres)
target_images_patch_corres_in = normalize_image_m1to1(target_images_patch_corres)
target_canvas_images_patch_corres_in = normalize_image_m1to1(target_canvas_images_patch_corres)
# (N, H, W, 1), [-1.0-stroke, 1.0-BG]
if self.hps.enc_model_correspondence == 'separated':
batch_input_ref_list = [reference_images_patch_corres_in]
if self.hps.use_reference_canvas:
batch_input_ref_list.append(reference_canvas_images_patch_corres_in)
if self.hps.use_segment_img:
batch_input_ref_list.append(reference_segment_images_patch_corres_in)
batch_input_ref_list.append(reference_dot_img_patch_corres_in)
batch_input_ref = torch.cat(batch_input_ref_list, dim=-1) # (N, H, W, *), [-1.0-stroke, 1.0-BG]
if self.hps.use_target_canvas:
batch_input_tar = torch.cat([target_images_patch_corres_in, target_canvas_images_patch_corres_in], dim=-1) # (N, H, W, 2), [-1.0-stroke, 1.0-BG]
else:
batch_input_tar = target_images_patch_corres_in # (N, H, W, 1), [-1.0-stroke, 1.0-BG]
# transform to nchw
batch_input_ref = batch_input_ref.permute(0, 3, 1, 2) # (N, *, H, W), [-1.0-stroke, 1.0-BG]
batch_input_tar = batch_input_tar.permute(0, 3, 1, 2) # (N, *, H, W), [-1.0-stroke, 1.0-BG]
if self.hps.add_coordconv:
batch_input_ref = self.add_coords(batch_input_ref) # (N, in_dim + 2, in_H, in_W)
batch_input_tar = self.add_coords(batch_input_tar) # (N, in_dim + 2, in_H, in_W)
pred_params_trans = self.encoder(batch_input_ref, batch_input_tar) # (N, 2), [-1.0, 1.0]
else:
raise Exception('Unknown enc_model_correspondence:', self.hps.enc_model_correspondence)
if self.hps.use_clinging:
pred_params_trans_np = pred_params_trans.cpu().data.numpy()
target_images_patch_corres_np = target_images_patch_corres.cpu().data.numpy()
pred_params_trans_np = correspondence_clinging(target_images_patch_corres_np, pred_params_trans_np,
self.hps.raster_size_corres,
binary_threshold=self.hps.clinging_binary_threshold)
pred_params_trans = torch.tensor(pred_params_trans_np).float().cuda() # (N, 2), [-1.0, 1.0]
## Reversed Transformation
if self.hps.transform_with_rotation:
pred_params_rel = spatial_transform_reverse_point(pred_params_trans, pred_window_rotate_angle_tar) # (N, 2), [-1.0+, 1.0+]
else:
pred_params_rel = pred_params_trans
pred_params_offset_global = pred_params_rel * (curr_window_size_tar_pred.squeeze(dim=1) / 2.0) # (N, 2)
pred_params_global = pred_cursor_position_tar.squeeze(dim=1) * float(image_size) + pred_params_offset_global # (N, 2), in full size
pred_params_global = pred_params_global / float(image_size) # (N, 2), in [0.0, 1.0]
return pred_params_global
def get_coordconv(self):
xx_ones = torch.ones(self.hps.raster_size_corres, dtype=torch.int32) # e.g. (image_size)
xx_ones = xx_ones.unsqueeze(dim=-1) # e.g. (image_size, 1)
xx_range = torch.arange(self.hps.raster_size_corres, dtype=torch.int32) # e.g. (image_size)
xx_range = xx_range.unsqueeze(0) # e.g. (1, image_size)
xx_channel = torch.matmul(xx_ones, xx_range) # e.g. (image_size, image_size)
xx_channel = xx_channel.unsqueeze(0) # e.g. (1, image_size, image_size)
yy_ones = torch.ones(self.hps.raster_size_corres, dtype=torch.int32) # e.g. (image_size)
yy_ones = yy_ones.unsqueeze(0) # e.g. (1, image_size)
yy_range = torch.arange(self.hps.raster_size_corres, dtype=torch.int32) # (image_size)
yy_range = yy_range.unsqueeze(-1) # e.g. (image_size, 1)
yy_channel = torch.matmul(yy_range, yy_ones) # e.g. (image_size, image_size)
yy_channel = yy_channel.unsqueeze(0) # e.g. (1, image_size, image_size)
xx_channel = xx_channel.float() / (self.hps.raster_size_corres - 1)
yy_channel = yy_channel.float() / (self.hps.raster_size_corres - 1)
xx_channel = xx_channel * 2 - 1 # [-1, 1]
yy_channel = yy_channel * 2 - 1
# xx_channel = xx_channel.cuda()
# yy_channel = yy_channel.cuda()
ret = torch.cat([
xx_channel,
yy_channel,
], dim=0) # (2, image_size, image_size)
ret = ret.detach()
return ret
def add_coords(self, input_tensor):
batch_size = input_tensor.size()[0] # get N size
coords = torch.unsqueeze(self.coordconv_input, dim=0).repeat(batch_size, 1, 1, 1) # (N, 2, image_size, image_size)
coords = coords.to(input_tensor.device)
result = torch.cat([input_tensor, coords], dim=1) # (N, C+2, image_size, image_size)
return result
def build_encoder_transform(self, patch_input_ref, patch_input_tar):
"""
:param patch_input_ref & patch_input_tar: (N, raster_size, raster_size, 1), [-1.0-stroke, 1.0-BG]
:return:
"""
# transform to nchw
patch_inputs_ref = patch_input_ref # (N, raster_size, raster_size, 1), [-1.0-stroke, 1.0-BG]
patch_inputs_ref = patch_inputs_ref.permute(0, 3, 1, 2) # (N, 1, raster_size, raster_size), [-1.0-stroke, 1.0-BG]
patch_inputs_tar = patch_input_tar # (N, raster_size, raster_size, 1), [-1.0-stroke, 1.0-BG]
patch_inputs_tar = patch_inputs_tar.permute(0, 3, 1, 2) # (N, 1, raster_size, raster_size), [-1.0-stroke, 1.0-BG]
if self.hps.enc_model_transform == 'combined':
batch_input = torch.cat([patch_inputs_ref, patch_inputs_tar], dim=1) # (N, 4, raster_size, raster_size), [-1.0-stroke, 1.0-BG]
if self.hps.add_coordconv:
batch_input = self.add_coords(batch_input) # (N, in_dim + 2, in_H, in_W)
output = self.encoder_transform(batch_input) # (N, z_size)
else:
raise Exception('Unknown enc_model_transform:', self.hps.enc_model_transform)
return output
def build_decoder_transform(self, dec_input, prev_state):
"""
:param dec_input: (N, in_dim)
:return:
"""
h_output = self.decoder_transform(dec_input)
next_state = None
return h_output, next_state
class Generative_Model(nn.Module):
def __init__(self, hps, corres_module):
super(Generative_Model, self).__init__()
self.hps = hps
self.stroke_thickness = hps.stroke_thickness
self.correspondence_module = corres_module
if self.hps.data_type in ['TU-Derlin', 'TU-Refined']:
self.color_rgb_set = generate_colors2(40)
transform_out_size = 1 if self.hps.use_square_window else 2
if self.hps.transform_with_rotation:
transform_out_size += 1
first_kernel_size = self.hps.first_kernel_size
first_padding = (first_kernel_size - 1) // 2
# transform encoder
if self.hps.enc_model_transform == 'combined':
cnn_in_size = 2
if self.hps.transform_use_global_info:
cnn_in_size += 1
if self.hps.add_coordconv:
cnn_in_size += 2
cnn_out_size = self.hps.z_size
self.encoder_transform = CNN_Encoder(cnn_in_size, cnn_out_size, input_size=self.hps.raster_size,
first_kernel_size=first_kernel_size, first_padding=first_padding,
use_atrous=self.hps.use_atrous_conv)
else:
raise Exception('Unknown enc_model_transform:', self.hps.enc_model_transform)
# tracing encoder
if self.hps.enc_model_tracing == 'separated':
cnn_in_size_ref = 3
cnn_in_size_tar_end = 2
cnn_in_size_tar_ctrl = 3
if self.hps.add_coordconv:
cnn_in_size_ref += 2
cnn_in_size_tar_end += 2
cnn_in_size_tar_ctrl += 2
cnn_out_size = self.hps.z_size
self.encoder_end = CNN_SepEncoder(cnn_in_size_ref, cnn_in_size_tar_end, cnn_out_size, input_size=self.hps.raster_size,
first_kernel_size=first_kernel_size, first_padding=first_padding,
use_atrous=self.hps.use_atrous_conv)
self.encoder_ctrl = CNN_SepEncoder(cnn_in_size_ref, cnn_in_size_tar_ctrl, cnn_out_size, input_size=self.hps.raster_size,
first_kernel_size=first_kernel_size, first_padding=first_padding,
use_atrous=self.hps.use_atrous_conv)
else:
raise Exception('Unknown enc_model_tracing:', self.hps.enc_model_tracing)
if self.hps.add_coordconv:
self.coordconv_input = self.get_coordconv() # (2, raster_size, raster_size)
dec_in_size = self.hps.z_size
dec_out_size_end = 2
dec_out_size_ctrl = 4
is_hyper = True if self.hps.rnn_model == 'hyper' else False
if self.hps.dec_model_transform == 'mlp':
self.decoder_transform = MLP_Decoder(dec_in_size, transform_out_size, zero_init=self.hps.transform_module_zero_init)
else:
raise Exception('Unknown dec_model_transform:', self.hps.dec_model_transform)
if self.hps.dec_model_tracing == 'rnn':
self.decoder_end = RNN_Decoder(dec_in_size, self.hps.dec_rnn_size, dec_out_size_end, is_hyper=is_hyper)
self.decoder_ctrl = RNN_Decoder(dec_in_size, self.hps.dec_rnn_size, dec_out_size_ctrl, is_hyper=is_hyper)
else:
raise Exception('Unknown dec_model_tracing:', self.hps.dec_model_tracing)
def forward(self, seq_num, reference_images, target_images,
reference_dot_images_patch, reference_segment_images,
endpoints_pos_ref, starting_states, base_window_size, model_mode, image_size):
"""
:param reference_images: (N, H, W, 1), float32, [0.0-stroke, 1.0-BG]
:param target_images: (N, H, W, 1), float32, [0.0-stroke, 1.0-BG]
:param reference_segment_images: (N, seq_num, H, W), [0.0-stroke, 1.0-BG]
:param reference_dot_images_patch: (N, H_c, W_c), [0.0-stroke, 1.0-BG]
:param endpoints_pos_ref: (N, seq_num, 2), float32, in [0.0, 1.0]
:param starting_states: (N, seq_num), {1.0, 0.0}
:param base_window_size: (N, seq_num), float32, in [0.0, 1.0]
:return:
"""
self.model_mode = model_mode
assert model_mode in ['eval', 'inference']
if self.hps.data_type not in ['TU-Derlin', 'TU-Refined']:
self.color_rgb_set = generate_colors2(seq_num) # (seq_num, 3), in [0., 1.]
pred_params, pred_raster_images, pred_raster_images_rgb = \
self.get_points_and_raster_image(seq_num, reference_images, target_images, reference_segment_images,
reference_dot_images_patch, endpoints_pos_ref,
starting_states, base_window_size, image_size)
# pred_params: (N, seq_num, 4, 2), in full size
# pred_raster_images: (N, H, W), [0.0-BG, 1.0-stroke]
# pred_raster_images_rgb: (N, H, W, 3), [0.0-BG, 1.0-stroke]
pred_raster_images = 1.0 - pred_raster_images # (N, H, W), [0.0-stroke, 1.0-BG]
pred_raster_images_rgb = 1.0 - pred_raster_images_rgb # (N, H, W, 3), [0.0-stroke, 1.0-BG]
return pred_raster_images, pred_raster_images_rgb, pred_params
def get_points_and_raster_image(self, seq_num,
reference_images, target_images, reference_segment_images,
reference_dot_images_patch, endpoints_pos_ref,
starting_states, base_window_size, image_size):
"""
:param reference_images: (N, H, W, 1), float32, [0.0-stroke, 1.0-BG]
:param target_images: (N, H, W, 1), float32, [0.0-stroke, 1.0-BG]
:param reference_segment_images: (N, seq_num, H, W), [0.0-stroke, 1.0-BG]
:param reference_dot_images_patch: (N, H_c, W_c), [0.0-stroke, 1.0-BG]
:param endpoints_pos_ref: (N, seq_num, 2), float32, in [0.0, 1.0]
:param starting_states: (N, seq_num), {1.0, 0.0}
:param base_window_size: (N, seq_num), float32, in [0.0, 1.0]
:return:
"""
zero_state = torch.zeros(reference_images.size(0), self.hps.dec_rnn_size).cuda()
if not self.hps.rnn_model == 'hyper':
next_state_end = (zero_state, zero_state)
next_state_ctrl = (zero_state, zero_state)
transform_next_state = (zero_state, zero_state)
else:
next_state_end = (zero_state, zero_state, zero_state, zero_state)
next_state_ctrl = (zero_state, zero_state, zero_state, zero_state)
transform_next_state = (zero_state, zero_state, zero_state, zero_state)
corres_window_size = get_correspondence_window_size(image_size, self.hps.init_window_size_corres_trans)
corres_window_sizes = torch.tensor([corres_window_size, corres_window_size]).float()
corres_window_sizes = corres_window_sizes.unsqueeze(dim=0).unsqueeze(dim=0).cuda() # (1, 1, 2)
segment_params_list = []
curr_canvas_ref = torch.squeeze(torch.zeros_like(reference_images), dim=-1) # (N, H, W), [0.0-BG, 1.0-stroke]
curr_canvas_tar_black = torch.squeeze(torch.zeros_like(target_images), dim=-1) # (N, H, W), [0.0-BG, 1.0-stroke]
curr_canvas_tar_rgb = torch.zeros_like(target_images)
curr_canvas_tar_rgb = curr_canvas_tar_rgb.repeat(1, 1, 1, 3) # (N, H, W, 3), [0.0-BG, 1.0-stroke]
cursor_position_loop_tar_inference = None
for seq_i in tqdm(range(seq_num)):
# reference cursor position
cursor_position_loop_ref = endpoints_pos_ref[:, seq_i:seq_i + 1, :] # (N, 1, 2), in size [0.0, 1.0]
# reference segment image
curr_segment_image_ref = reference_segment_images[:, seq_i, :, :] # (N, H, W), [0.0-stroke, 1.0-BG]
curr_segment_image_ref = curr_segment_image_ref.unsqueeze(dim=-1) # (N, H, W, 1), [0.0-stroke, 1.0-BG]
# canvas images
curr_canvas_ref_for_crop = 1.0 - curr_canvas_ref.unsqueeze(dim=-1) # (N, H, W, 1), [0.0-stroke, 1.0-BG]
curr_canvas_tar_for_crop = 1.0 - curr_canvas_tar_black.unsqueeze(dim=-1) # (N, H, W, 1), [0.0-stroke, 1.0-BG]
# ================== Stage-1: Starting point correspondence ================== #
if starting_states[0, seq_i] == 1:
# print('Starting point correspondence:', seq_i)
reference_dot_images_patch_corres = torch.unsqueeze(reference_dot_images_patch, dim=-1) # (N, H_c, W_c, 1), [0-stroke, 1-BG]
pred_params_corres = self.correspondence_module(reference_images=reference_images,
reference_dot_images=reference_dot_images_patch_corres,
reference_segment_images=curr_segment_image_ref,
reference_canvas_images=curr_canvas_ref_for_crop,
target_images=target_images,
target_canvas_images=curr_canvas_tar_for_crop,
cursor_position_ref=cursor_position_loop_ref,
image_size=image_size,
init_trans_window_sizes=corres_window_sizes)
# pred_params_corres: (N, 2), in [0.0, 1.0]
cursor_position_loop_tar_inference = pred_params_corres.unsqueeze(dim=1) # (N, 1, 2), in [0.0, 1.0]
# =================== Stage-2: Transformation and Tracing =================== #
## Reference processing