-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathmodels.py
3084 lines (2876 loc) · 167 KB
/
models.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
"""
Main DLP and DDLP models.
"""
# imports
import numpy as np
# torch
import torch
import torch.nn.functional as F
import torch.nn as nn
# modules
from modules.modules import KeyPointCNNOriginal, VariationalKeyPointPatchEncoder, CNNDecoder, \
ObjectDecoderCNN, FCToCNN
from modules.modules import ParticleAttributeEncoder, ParticleFeaturesEncoder, ParticleFilterMixer
from modules.dynamics_modules import DynamicsDLP
# util functions
from utils.util_func import reparameterize, create_masks_fast, spatial_transform, calc_model_size
from utils.loss_functions import ChamferLossKL, calc_kl, calc_reconstruction_loss, VGGDistance, calc_kl_beta_dist
class FgDLP(nn.Module):
def __init__(self, cdim=3, enc_channels=(16, 16, 32), prior_channels=(16, 16, 32), image_size=64, n_kp=1,
pad_mode='replicate', sigma=1.0, dropout=0.0,
patch_size=16, n_kp_enc=20, n_kp_prior=20, learned_feature_dim=16,
kp_range=(-1, 1), kp_activation="tanh", anchor_s=0.25,
use_resblock=False, use_correlation_heatmaps=True, enable_enc_attn=False,
filtering_heuristic='variance'):
super(FgDLP, self).__init__()
"""
DLP Foreground Module -- extract objects from an image
cdim: channels of the input image (3...)
enc_channels: channels for the posterior CNN (takes in the whole image)
prior_channels: channels for prior CNN (takes in patches)
n_kp: number of kp to extract from each (!) patch
n_kp_prior: number of kp to filter from the set of prior kp (of size n_kp x num_patches)
n_kp_enc: number of posterior kp to be learned (this is the actual number of kp that will be learnt)
pad_mode: padding for the CNNs, 'zeros' or 'replicate' (default)
sigma: the prior std of the KP
dropout: dropout for the CNNs. We don't use it though...
patch_size: patch size for the prior KP proposals network (not to be confused with the glimpse size)
kp_range: the range of keypoints, can be [-1, 1] (default) or [0,1]
learned_feature_dim: the latent visual features dimensions extracted from glimpses.
kp_activation: the type of activation to apply on the keypoints: "tanh" for kp_range [-1, 1], "sigmoid" for [0, 1]
anchor_s: defines the glimpse size as a ratio of image_size (e.g., 0.25 for image_size=128 -> glimpse_size=32)
use_correlation_heatmaps: use correlation heatmaps as input to model particle properties (e.g., xy offset)
enable_enc_attn: enable attention between patches features in the particle encoder
filtering heuristic: filtering heuristic to filter prior keypoints,['distance', 'variance', 'random', 'none']
"""
self.image_size = image_size
self.sigma = sigma
self.dropout = dropout
self.kp_range = kp_range
self.num_patches = int((image_size // patch_size) ** 2)
self.n_kp = n_kp
self.n_kp_total = self.n_kp * self.num_patches
self.n_kp_prior = min(self.n_kp_total, n_kp_prior)
self.n_kp_enc = n_kp_enc
self.kp_activation = kp_activation
self.patch_size = patch_size
self.anchor_patch_s = patch_size / image_size
self.features_dim = int(image_size // (2 ** (len(enc_channels) - 1)))
self.learned_feature_dim = learned_feature_dim
assert learned_feature_dim > 0, "learned_feature_dim must be greater than 0"
self.anchor_s = anchor_s
self.obj_patch_size = np.round(anchor_s * (image_size - 1)).astype(int)
self.exclusive_patches = False
self.cdim = cdim
self.use_resblock = use_resblock
self.use_correlation_heatmaps = use_correlation_heatmaps
self.enable_enc_attn = enable_enc_attn
assert filtering_heuristic in ['distance', 'variance',
'random', 'none'], f'unknown filtering heuristic: {filtering_heuristic}'
self.filtering_heuristic = filtering_heuristic
# prior
self.prior = VariationalKeyPointPatchEncoder(cdim=cdim, channels=prior_channels, image_size=image_size,
n_kp=n_kp, kp_range=self.kp_range,
patch_size=patch_size,
pad_mode=pad_mode, sigma=sigma, dropout=dropout,
learnable_logvar=False, learned_feature_dim=0,
use_resblock=self.use_resblock)
# posterior encoder
if self.filtering_heuristic == 'none':
# no filtering at all - we need a module that maps n_kp_prior -> n_kp_enc
self.particle_mixer = ParticleFilterMixer(anchor_size=anchor_s, image_size=image_size,
margin=0, ch=cdim, n_kp_prior=self.n_kp_total,
n_kp_enc=self.n_kp_enc,
cnn_channels=prior_channels)
else:
self.particle_mixer = nn.Identity()
# attribute encoder - anchor (z_a), offset (z_o), scale (z_s), transparency (z_t) and depth (z_d)
self.particle_attribute_enc = ParticleAttributeEncoder(anchor_size=anchor_s, image_size=image_size,
margin=0, ch=cdim,
kp_activation=kp_activation,
use_resblock=self.use_resblock,
max_offset=1.0, cnn_channels=prior_channels,
use_correlation_heatmaps=use_correlation_heatmaps,
enable_attn=self.enable_enc_attn, attn_dropout=0.0)
# appearance encoder - visual features encoder (z_f)
self.particle_features_enc = ParticleFeaturesEncoder(anchor_s, learned_feature_dim,
image_size,
cnn_channels=prior_channels,
margin=0, enable_attn=self.enable_enc_attn,
attn_dropout=0.0)
# object decoder
self.object_dec = ObjectDecoderCNN(patch_size=(self.obj_patch_size, self.obj_patch_size), num_chans=4,
bottleneck_size=learned_feature_dim, use_resblock=self.use_resblock)
self.init_weights()
def get_parameters(self, prior=True, encoder=True, decoder=True):
parameters = []
if prior:
parameters.extend(list(self.prior.parameters()))
if encoder:
parameters.extend(list(self.particle_mixer.parameters()))
parameters.extend(list(self.particle_attribute_enc.parameters()))
# parameters.extend(list(self.particle_attribute_enc_dyn.parameters()))
parameters.extend(list(self.particle_features_enc.parameters()))
if decoder:
parameters.extend(list(self.object_dec.parameters()))
return parameters
def set_require_grad(self, prior_value=True, enc_value=True, dec_value=True):
# prior
for param in self.prior.parameters():
param.requires_grad = prior_value
# encoder
for param in self.particle_mixer.parameters():
param.requires_grad = enc_value
for param in self.particle_attribute_enc.parameters():
param.requires_grad = enc_value
# for param in self.particle_attribute_enc_dyn.parameters():
# param.requires_grad = enc_value
for param in self.particle_features_enc.parameters():
param.requires_grad = enc_value
# decoder
for param in self.object_dec.parameters():
param.requires_grad = dec_value
def init_weights(self):
for m in self.modules():
if isinstance(m, nn.Conv2d):
nn.init.normal_(m.weight, 0, 0.01)
if m.bias is not None:
nn.init.constant_(m.bias, 0)
elif isinstance(m, (nn.BatchNorm2d, nn.GroupNorm)):
nn.init.constant_(m.weight, 1)
nn.init.constant_(m.bias, 0)
elif isinstance(m, nn.Linear):
# use pytorch's default
pass
def encode_all(self, x, deterministic=False, noisy=False, warmup=False, kp_init=None, cropped_objects_prev=None,
scale_prev=None, refinement_iter=False, with_offset=True):
"""
2-stage encoding:
0. if kp_init is None: create evenly spaced anchors. kp_init is z_base.
1. attributes encoding: obj_on (z_t), depth (z_d), offset (z_o) and scale (z_s) encoding:
produces [obj_on_a, obj_on_b] / [mu, logvar].
2. features (z_f) encoding: [mu, logvar]
"""
# kp_init: [batch_size, n_kp, 2] in [-1, 1]
batch_size, ch, h, w = x.shape
# 0. create or filter anchors
if kp_init is None:
# randomly sample n_kp_enc kp
mu = torch.rand(batch_size, self.n_kp_enc, 2, device=x.device) * 2 - 1 # in [-1, 1]
elif kp_init.shape[1] > self.n_kp_enc:
mu = kp_init[:, :self.n_kp_enc]
else:
mu = kp_init
logvar = torch.zeros_like(mu)
z_base = mu + 0.0 * logvar # deterministic value for chamfer-kl
kp_heatmap = None # backward compatibility, this is not used
# 1. posterior offsets and scale, it is okay of scale_prev is None
scale_in = None if (noisy or warmup) else scale_prev
cropped_objects_prev = None if (noisy or warmup) else cropped_objects_prev
particle_stats_dict = self.particle_attribute_enc(x, z_base.detach(),
previous_objects=cropped_objects_prev,
z_scale=scale_in)
# first iteration encodes the refined anchor (z_a), then a second one to lock on target better (z_o)
if refinement_iter:
mu_offset = particle_stats_dict['mu']
mu = z_base + mu_offset
z_base = mu + 0.0 * logvar
if scale_prev is None:
scale_prev = None if (noisy or warmup) else particle_stats_dict['mu_scale'].detach()
cropped_objects_prev = None if (noisy or warmup) else cropped_objects_prev
particle_stats_dict = self.particle_attribute_enc(x, z_base.detach(),
previous_objects=cropped_objects_prev,
z_scale=scale_prev)
if with_offset:
mu_offset = particle_stats_dict['mu']
logvar_offset = particle_stats_dict['logvar']
else:
mu_offset = torch.zeros_like(particle_stats_dict['mu'])
logvar_offset = torch.zeros_like(particle_stats_dict['logvar'])
mu_scale = particle_stats_dict['mu_scale']
logvar_scale = particle_stats_dict['logvar_scale']
lobj_on_a = particle_stats_dict['lobj_on_a']
lobj_on_b = particle_stats_dict['lobj_on_b']
mu_depth = particle_stats_dict['mu_depth']
logvar_depth = particle_stats_dict['logvar_depth']
# final position
mu_tot = z_base + mu_offset
logvar_tot = logvar_offset
obj_on_a = lobj_on_a.exp().clamp_min(1e-5)
obj_on_b = lobj_on_b.exp().clamp_min(1e-5)
# if torch.isnan(obj_on_a).any():
# print(f'obj_on_a has nan')
# # torch.nan_to_num_(obj_on_a, nan=0.01)
# if torch.isnan(obj_on_b).any():
# print(f'obj_on_b has nan')
# raise SystemError('NaNs detected')
# # torch.nan_to_num_(obj_on_b, nan=0.01)
# try:
# obj_on_beta_dist = torch.distributions.Beta(obj_on_a, obj_on_b)
# except ValueError:
# print(f'obj_on_a: {obj_on_a}')
# print(f'obj_on_b: {obj_on_b}')
# raise SystemError
obj_on_beta_dist = torch.distributions.Beta(obj_on_a, obj_on_b)
# reparameterize
if deterministic:
z = mu_tot
z_offset = mu_offset
z_scale = mu_scale
z_depth = mu_depth
z_obj_on = obj_on_beta_dist.mean
else:
z = reparameterize(mu_tot, logvar_tot) if with_offset else mu_tot
z_offset = reparameterize(mu_offset, logvar_offset) # not used
z_scale = reparameterize(mu_scale, logvar_scale)
z_depth = reparameterize(mu_depth, logvar_depth)
z_obj_on = obj_on_beta_dist.rsample()
# during warm-up and noisy stages we use small values around the patch size for the scale
if z_scale is not None and noisy:
anchor_size = self.anchor_s
z_scale = 0.0 * z_scale + (np.log(anchor_size / (1 - anchor_size + 1e-5)) + 0.1 * torch.randn_like(z_scale))
# to avoid null cases where obj_on -> 0, we noise its values during the noisy stage
# z_obj_on = z_obj_on if not noisy else (0.0 * z_obj_on + 1.0)
if warmup:
z_base = z_base.detach()
z = z.detach()
z_scale = z_scale.detach()
# 2. posterior attributes: obj_on, depth and visual features
obj_enc_out = self.particle_features_enc(x, z, z_scale=z_scale.detach())
mu_features = obj_enc_out['mu_features']
logvar_features = obj_enc_out['logvar_features']
cropped_objects = obj_enc_out['cropped_objects']
# reparameterize
if deterministic:
z_features = mu_features
else:
z_features = reparameterize(mu_features, logvar_features)
encode_dict = {'mu': mu, 'logvar': logvar, 'z_base': z_base, 'z': z, 'kp_heatmap': kp_heatmap,
'mu_features': mu_features, 'logvar_features': logvar_features, 'z_features': z_features,
'obj_on_a': obj_on_a, 'obj_on_b': obj_on_b, 'obj_on': z_obj_on,
'mu_depth': mu_depth, 'logvar_depth': logvar_depth, 'z_depth': z_depth,
'cropped_objects': cropped_objects,
'mu_scale': mu_scale, 'logvar_scale': logvar_scale, 'z_scale': z_scale,
'mu_offset': mu_offset, 'logvar_offset': logvar_offset, 'z_offset': z_offset}
return encode_dict
def encode_prior(self, x, x_prior=None, filtering_heuristic='variance', k=None):
# encodes prior keypoints by patchifying the image and applying spatial-softmax
if k is None:
k = self.n_kp_prior
if x_prior is None:
x_prior = x
kp_p, var_kp_p = self.prior(x_prior, global_kp=True)
kp_p = kp_p.view(x_prior.shape[0], -1, 2) # [batch_size, n_kp_total, 2]
var_kp_p = var_kp_p.view(x_prior.shape[0], kp_p.shape[1], -1) # [batch_size, n_kp_total, 3]
if filtering_heuristic == 'distance':
# filter proposals by distance to the patches' center
dist_from_center = self.prior.get_distance_from_patch_centers(kp_p, global_kp=True)
_, indices = torch.topk(dist_from_center, k=k, dim=-1, largest=True)
batch_indices = torch.arange(kp_p.shape[0]).view(-1, 1).to(kp_p.device)
kp_p = kp_p[batch_indices, indices]
elif filtering_heuristic == 'variance':
total_var = var_kp_p.sum(-1)
_, indices = torch.topk(total_var, k=k, dim=-1, largest=False)
batch_indices = torch.arange(kp_p.shape[0]).view(-1, 1).to(kp_p.device)
kp_p = kp_p[batch_indices, indices]
elif filtering_heuristic == 'none':
return kp_p
else:
# alternatively, just sample random kp
kp_p = kp_p[:, torch.randperm(kp_p.shape[1])[:k]]
return kp_p
def translate_patches(self, kp_batch, patches_batch, scale=None, translation=None, scale_normalized=False):
"""
translate patches to be centered around given keypoints
kp_batch: [bs, n_kp, 2] in [-1, 1]
patches: [bs, n_kp, ch_patches, patch_size, patch_size]
scale: None or [bs, n_kp, 2] or [bs, n_kp, 1]
translation: None or [bs, n_kp, 2] or [bs, n_kp, 1] (delta from kp)
scale_normalized: False if scale is not in [0, 1]
:return: translated_padded_patches [bs, n_kp, ch, img_size, img_size]
"""
batch_size, n_kp, ch_patch, patch_size, _ = patches_batch.shape
img_size = self.image_size
if scale is None:
z_scale = (patch_size / img_size) * torch.ones_like(kp_batch)
else:
# normalize to [0, 1]
if scale_normalized:
z_scale = scale
else:
z_scale = torch.sigmoid(scale) # -> [0, 1]
z_pos = kp_batch.reshape(-1, kp_batch.shape[-1]) # [bs * n_kp, 2]
z_scale = z_scale.view(-1, z_scale.shape[-1]) # [bs * n_kp, 2]
patches_batch = patches_batch.reshape(-1, *patches_batch.shape[2:])
out_dims = (batch_size * n_kp, ch_patch, img_size, img_size)
trans_patches_batch = spatial_transform(patches_batch, z_pos, z_scale, out_dims, inverse=True)
trans_padded_patches_batch = trans_patches_batch.view(batch_size, n_kp, *trans_patches_batch.shape[1:])
# [bs, n_kp, ch, img_size, img_size]
return trans_padded_patches_batch
def get_objects_alpha_rgb(self, z_kp, z_features, z_scale=None, translation=None, noisy=False):
# decode the latent particles into RGBA glimpses and place them on the canvas
dec_objects = self.object_dec(z_features) # [bs * n_kp, 4, patch_size, patch_size]
dec_objects = dec_objects.view(-1, self.n_kp_enc,
*dec_objects.shape[1:]) # [bs, n_kp, 4, patch_size, patch_size]
# translate patches - place the decoded glimpses on the canvas
dec_objects_trans = self.translate_patches(z_kp, dec_objects, z_scale, translation)
dec_objects_trans = dec_objects_trans.clamp(0, 1) # STN can change values to be < 0
# dec_objects_trans: [bs, n_kp, 3, im_size, im_size]
# multiply by alpha channel
a_obj, rgb_obj = torch.split(dec_objects_trans, [1, 3], dim=2)
if noisy:
a_obj = a_obj + 0.1 * torch.randn_like(a_obj)
a_obj = a_obj.clamp(0, 1)
return dec_objects, a_obj, rgb_obj
def get_objects_alpha_rgb_with_depth(self, a_obj, rgb_obj, obj_on, z_depth, eps=1e-5):
# stitching the glimpses by factoring the alpha maps and the particle's inferred depth
# obj_on: [bs, n_kp, 1]
# z_depth: [bs, n_kp, 1]
# turn off inactive particles
a_obj = obj_on[:, :, None, None, None] * a_obj # [bs, n_kp, 1, im_size, im_size]
rgba_obj = a_obj * rgb_obj
# importance map
importance_map = a_obj * torch.sigmoid(-z_depth[:, :, :, None, None])
# normalize
importance_map = importance_map / (torch.sum(importance_map, dim=1, keepdim=True) + eps)
# this imitates softmax to move objects on the depth axis
dec_objects_trans = (rgba_obj * importance_map).sum(dim=1)
alpha_mask = 1.0 - (importance_map * a_obj).sum(dim=1)
a_obj = importance_map * a_obj
return a_obj, alpha_mask, dec_objects_trans
def decode_objects(self, z_kp, z_features, obj_on, z_scale=None, translation=None, noisy=False, z_depth=None):
# stitching the decoded latent particles -> RGB, factoring the alpha maps and depths
dec_objects, a_obj, rgb_obj = self.get_objects_alpha_rgb(z_kp, z_features, z_scale=z_scale,
translation=translation, noisy=noisy)
alpha_masks, bg_mask, dec_objects_trans = self.get_objects_alpha_rgb_with_depth(a_obj, rgb_obj, obj_on=obj_on,
z_depth=z_depth)
return dec_objects, dec_objects_trans, alpha_masks, bg_mask
def decode_all(self, z, z_features, obj_on, z_depth=None, noisy=False, z_scale=None):
# a wrapper function to decode latent particles into and RGB image (no bg)
object_dec_out = self.decode_objects(z, z_features, obj_on, noisy=noisy, z_depth=z_depth, z_scale=z_scale)
dec_objects, dec_objects_trans, alpha_masks, bg_mask = object_dec_out
decoder_out = {'dec_objects': dec_objects, 'dec_objects_trans': dec_objects_trans,
'bg_mask': bg_mask, 'alpha_masks': alpha_masks}
return decoder_out
def forward(self, x, deterministic=False, x_prior=None, warmup=False, noisy=False,
cropped_objects_prev=None, mu_scale_prev=None, train_prior=True, refinement_iter=False):
# refinement_iter: do another encoding step to get a better lock on the object's position (z_a + z_o)
# first, extract prior KP proposals
# prior proposals
kp_p = self.encode_prior(x, x_prior=x_prior, filtering_heuristic=self.filtering_heuristic)
kp_init = kp_p if train_prior else (0.0 * kp_p + kp_p.detach()) # 0.0 * kp_p is because of distributed training
if self.filtering_heuristic == 'none':
# n_kp_prior -> n_kp_enc
kp_init = self.particle_mixer(x, kp_init)
encoder_out = self.encode_all(x, deterministic=deterministic, noisy=noisy, warmup=warmup, kp_init=kp_init,
cropped_objects_prev=cropped_objects_prev, scale_prev=mu_scale_prev,
refinement_iter=refinement_iter)
# detach for the kl-divergence
kp_p = kp_p.detach()
mu = encoder_out['mu']
logvar = encoder_out['logvar']
z_base = encoder_out['z_base']
z = encoder_out['z']
mu_offset = encoder_out['mu_offset']
logvar_offset = encoder_out['logvar_offset']
z_offset = encoder_out['z_offset']
kp_heatmap = encoder_out['kp_heatmap']
mu_features = encoder_out['mu_features']
logvar_features = encoder_out['logvar_features']
z_features = encoder_out['z_features']
obj_on = encoder_out['obj_on']
obj_on_a = encoder_out['obj_on_a']
obj_on_b = encoder_out['obj_on_b']
mu_depth = encoder_out['mu_depth']
logvar_depth = encoder_out['logvar_depth']
z_depth = encoder_out['z_depth']
cropped_objects = encoder_out['cropped_objects']
mu_scale = encoder_out['mu_scale']
logvar_scale = encoder_out['logvar_scale']
z_scale = encoder_out['z_scale']
obj_on_sample = obj_on
decoder_out = self.decode_all(z, z_features, obj_on_sample, z_depth, noisy=noisy, z_scale=z_scale)
dec_objects = decoder_out['dec_objects']
dec_objects_trans = decoder_out['dec_objects_trans']
bg_mask = decoder_out['bg_mask']
alpha_masks = decoder_out['alpha_masks']
output_dict = {}
output_dict['kp_p'] = kp_p
output_dict['mu'] = mu
output_dict['logvar'] = logvar
output_dict['z_base'] = z_base
output_dict['z'] = z
output_dict['mu_offset'] = mu_offset
output_dict['logvar_offset'] = logvar_offset
output_dict['mu_features'] = mu_features
output_dict['logvar_features'] = logvar_features
output_dict['z_features'] = z_features
output_dict['bg_mask'] = bg_mask
output_dict['cropped_objects_original'] = cropped_objects
output_dict['obj_on_a'] = obj_on_a
output_dict['obj_on_b'] = obj_on_b
output_dict['obj_on'] = obj_on
output_dict['dec_objects_original'] = dec_objects
output_dict['dec_objects'] = dec_objects_trans
output_dict['mu_depth'] = mu_depth
output_dict['logvar_depth'] = logvar_depth
output_dict['z_depth'] = z_depth
output_dict['mu_scale'] = mu_scale
output_dict['logvar_scale'] = logvar_scale
output_dict['z_scale'] = z_scale
output_dict['alpha_masks'] = alpha_masks
return output_dict
# class FgDDLP(nn.Module):
# def __init__(self, cdim=3, enc_channels=(16, 16, 32), prior_channels=(16, 16, 32), image_size=64, n_kp=1,
# pad_mode='replicate', sigma=1.0, dropout=0.0,
# patch_size=16, n_kp_enc=20, n_kp_prior=20, learned_feature_dim=16,
# kp_range=(-1, 1), kp_activation="tanh", anchor_s=0.25,
# use_resblock=False, use_correlation_heatmaps=True, enable_enc_attn=False):
# super(FgDDLP, self).__init__()
# """
# DDLP Foreground Module
# Difference from DLP: separate encoders for static and dynamic statistics (e.g. mu/logvar)
# cdim: channels of the input image (3...)
# enc_channels: channels for the posterior CNN (takes in the whole image)
# prior_channels: channels for prior CNN (takes in patches)
# n_kp: number of kp to extract from each (!) patch
# n_kp_prior: number of kp to filter from the set of prior kp (of size n_kp x num_patches)
# n_kp_enc: number of posterior kp to be learned (this is the actual number of kp that will be learnt)
# pad_mode: padding for the CNNs, 'zeros' or 'replicate' (default)
# sigma: the prior std of the KP
# dropout: dropout for the CNNs. We don't use it though...
# patch_size: patch size for the prior KP proposals network (not to be confused with the glimpse size)
# kp_range: the range of keypoints, can be [-1, 1] (default) or [0,1]
# learned_feature_dim: the latent visual features dimensions extracted from glimpses.
# kp_activation: the type of activation to apply on the keypoints: "tanh" for kp_range [-1, 1], "sigmoid" for [0, 1]
# anchor_s: defines the glimpse size as a ratio of image_size (e.g., 0.25 for image_size=128 -> glimpse_size=32)
# use_correlation_heatmaps: use correlation heatmaps as input to model particle properties (e.g., xy offset)
# enable_enc_attn: enable attention between patches features in the particle encoder
# """
# self.image_size = image_size
# self.sigma = sigma
# self.dropout = dropout
# self.kp_range = kp_range
# self.num_patches = int((image_size // patch_size) ** 2)
# self.n_kp = n_kp
# self.n_kp_total = self.n_kp * self.num_patches
# self.n_kp_prior = min(self.n_kp_total, n_kp_prior)
# self.n_kp_enc = n_kp_enc
# self.kp_activation = kp_activation
# self.patch_size = patch_size
# self.anchor_patch_s = patch_size / image_size
# self.features_dim = int(image_size // (2 ** (len(enc_channels) - 1)))
# self.learned_feature_dim = learned_feature_dim
# assert learned_feature_dim > 0, "learned_feature_dim must be greater than 0"
# self.anchor_s = anchor_s
# self.obj_patch_size = np.round(anchor_s * (image_size - 1)).astype(int)
# self.exclusive_patches = False
# self.cdim = cdim
# self.use_resblock = use_resblock
# self.use_correlation_heatmaps = use_correlation_heatmaps
# self.enable_enc_attn = enable_enc_attn
#
# # prior
# self.prior = VariationalKeyPointPatchEncoder(cdim=cdim, channels=prior_channels, image_size=image_size,
# n_kp=n_kp, kp_range=self.kp_range,
# patch_size=patch_size,
# pad_mode=pad_mode, sigma=sigma, dropout=dropout,
# learnable_logvar=False, learned_feature_dim=0,
# use_resblock=self.use_resblock)
#
# # posterior encoder
# self.particle_attribute_enc = ParticleAttributeEncoder(anchor_size=anchor_s, image_size=image_size,
# margin=0, ch=cdim,
# kp_activation=kp_activation,
# use_resblock=self.use_resblock,
# max_offset=1.0, cnn_channels=prior_channels,
# use_correlation_heatmaps=use_correlation_heatmaps,
# enable_attn=self.enable_enc_attn, attn_dropout=0.0)
# self.particle_attribute_enc_dyn = ParticleAttributeEncoder(anchor_size=anchor_s, image_size=image_size,
# margin=0, ch=cdim,
# kp_activation=kp_activation,
# use_resblock=self.use_resblock,
# max_offset=1.0, cnn_channels=prior_channels,
# use_correlation_heatmaps=use_correlation_heatmaps,
# enable_attn=self.enable_enc_attn, attn_dropout=0.0)
# self.particle_features_enc = ParticleFeaturesEncoder(anchor_s, learned_feature_dim,
# image_size,
# cnn_channels=prior_channels,
# margin=0, enable_attn=self.enable_enc_attn,
# attn_dropout=0.0)
# self.particle_features_enc_dyn = ParticleFeaturesEncoder(anchor_s, learned_feature_dim,
# image_size,
# cnn_channels=prior_channels,
# margin=0, enable_attn=self.enable_enc_attn,
# attn_dropout=0.0)
#
# # object decoder
# self.object_dec = ObjectDecoderCNN(patch_size=(self.obj_patch_size, self.obj_patch_size), num_chans=4,
# bottleneck_size=learned_feature_dim, use_resblock=self.use_resblock)
# self.init_weights()
#
# def get_parameters(self, prior=True, encoder=True, decoder=True):
# parameters = []
# if prior:
# parameters.extend(list(self.prior.parameters()))
# if encoder:
# parameters.extend(list(self.particle_attribute_enc.parameters()))
# parameters.extend(list(self.particle_features_enc.parameters()))
# parameters.extend(list(self.particle_attribute_enc_dyn.parameters()))
# parameters.extend(list(self.particle_features_enc_dyn.parameters()))
# if decoder:
# parameters.extend(list(self.object_dec.parameters()))
# return parameters
#
# def set_require_grad(self, prior_value=True, enc_value=True, dec_value=True):
# # prior
# for param in self.prior.parameters():
# param.requires_grad = prior_value
# # encoder
# for param in self.particle_attribute_enc.parameters():
# param.requires_grad = enc_value
# for param in self.particle_attribute_enc_dyn.parameters():
# param.requires_grad = enc_value
# for param in self.particle_features_enc.parameters():
# param.requires_grad = enc_value
# for param in self.particle_features_enc_dyn.parameters():
# param.requires_grad = enc_value
# # decoder
# for param in self.object_dec.parameters():
# param.requires_grad = dec_value
#
# def init_weights(self):
# for m in self.modules():
# if isinstance(m, nn.Conv2d):
# nn.init.normal_(m.weight, 0, 0.01)
# if m.bias is not None:
# nn.init.constant_(m.bias, 0)
# elif isinstance(m, (nn.BatchNorm2d, nn.GroupNorm)):
# nn.init.constant_(m.weight, 1)
# nn.init.constant_(m.bias, 0)
# elif isinstance(m, nn.Linear):
# # use pytorch's default
# pass
#
# def encode_all(self, x, deterministic=False, noisy=False, warmup=False, kp_init=None, cropped_objects_prev=None,
# scale_prev=None, refinement_iter=False, use_static_encoders=True):
# """
# 2-stage encoding:
# 0. if kp_init is None: create evenly spaced anchors. kp_init is z_base.
# 1. offset and scale encoding: produces offset and scale [mu, logvar].
# 2. attributes encoding: obj_on, depth and features [obj_on_a, obj_on_b] / [mu, logvar]
# """
# # kp_init: [batch_size, n_kp, 2] in [-1, 1]
# batch_size, ch, h, w = x.shape
# # 0. create or filter anchors
# if kp_init is None:
# # randomly sample n_kp_enc kp
# mu = torch.rand(batch_size, self.n_kp_enc, 2, device=x.device) * 2 - 1 # in [-1, 1]
# elif kp_init.shape[1] > self.n_kp_enc:
# mu = kp_init[:, :self.n_kp_enc]
# else:
# mu = kp_init
# logvar = torch.zeros_like(mu)
# z_base = mu + 0.0 * logvar # deterministic value for chamfer-kl
# kp_heatmap = None # backward compatibility, this is not used
#
# attribute_enc = self.particle_attribute_enc if use_static_encoders else self.particle_attribute_enc_dyn
# features_enc = self.particle_features_enc if use_static_encoders else self.particle_features_enc_dyn
# # 1. posterior offsets and scale, it is okay of scale_prev is None
# particle_stats_dict = attribute_enc(x, z_base.detach(), previous_objects=cropped_objects_prev,
# z_scale=scale_prev)
# # "second chance" to lock on target better
# if refinement_iter:
# mu_offset = particle_stats_dict['mu']
# mu = z_base + mu_offset # TODO: mu_offset.detach()?
# z_base = mu + 0.0 * logvar
# if scale_prev is None:
# scale_prev = particle_stats_dict['mu_scale']
# particle_stats_dict = attribute_enc(x, z_base.detach(),
# previous_objects=cropped_objects_prev,
# z_scale=scale_prev.detach())
# mu_offset = particle_stats_dict['mu']
# logvar_offset = particle_stats_dict['logvar']
# mu_scale = particle_stats_dict['mu_scale']
# logvar_scale = particle_stats_dict['logvar_scale']
#
# lobj_on_a = particle_stats_dict['lobj_on_a']
# lobj_on_b = particle_stats_dict['lobj_on_b']
# mu_depth = particle_stats_dict['mu_depth']
# logvar_depth = particle_stats_dict['logvar_depth']
# # final position
# mu_tot = z_base + mu_offset
# logvar_tot = logvar_offset
#
# obj_on_a = lobj_on_a.exp().clamp_min(1e-5)
# obj_on_b = lobj_on_b.exp().clamp_min(1e-5)
# if torch.isnan(obj_on_a).any():
# print(f'obj_on_a has nan')
# torch.nan_to_num_(obj_on_a, nan=0.01)
# if torch.isnan(obj_on_b).any():
# print(f'obj_on_b has nan')
# torch.nan_to_num_(obj_on_b, nan=0.01)
# obj_on_beta_dist = torch.distributions.Beta(obj_on_a, obj_on_b)
#
# # reparameterize
# if deterministic:
# z = mu_tot
# z_offset = mu_offset
# z_scale = mu_scale
# z_depth = mu_depth
# z_obj_on = obj_on_beta_dist.mean
# else:
# z = reparameterize(mu_tot, logvar_tot)
# z_offset = reparameterize(mu_offset, logvar_offset) # not used
# z_scale = reparameterize(mu_scale, logvar_scale)
# z_depth = reparameterize(mu_depth, logvar_depth)
# z_obj_on = obj_on_beta_dist.rsample()
#
# # during warm-up and noisy stages we use small values around the patch size for the scale
# if z_scale is not None and noisy:
# anchor_size = self.anchor_s
# z_scale = 0.0 * z_scale + (np.log(anchor_size / (1 - anchor_size + 1e-5)) + 0.3 * torch.randn_like(z_scale))
# # to avoid null cases where obj_on -> 0, we noise its values during the noisy stage
# # z_obj_on = z_obj_on if not noisy else (z_obj_on + self.sigma * torch.randn_like(z_obj_on)).clamp(0, 1)
#
# if warmup:
# z_base = z_base.detach()
# z = z.detach()
# z_scale = z_scale.detach()
#
# # 2. posterior attributes: obj_on, depth and visual features
# obj_enc_out = features_enc(x, z, z_scale=z_scale.detach())
#
# mu_features = obj_enc_out['mu_features']
# logvar_features = obj_enc_out['logvar_features']
# cropped_objects = obj_enc_out['cropped_objects']
#
# # reparameterize
# if deterministic:
# z_features = mu_features
# else:
# z_features = reparameterize(mu_features, logvar_features)
#
# encode_dict = {'mu': mu, 'logvar': logvar, 'z_base': z_base, 'z': z, 'kp_heatmap': kp_heatmap,
# 'mu_features': mu_features, 'logvar_features': logvar_features, 'z_features': z_features,
# 'obj_on_a': obj_on_a, 'obj_on_b': obj_on_b, 'obj_on': z_obj_on,
# 'mu_depth': mu_depth, 'logvar_depth': logvar_depth, 'z_depth': z_depth,
# 'cropped_objects': cropped_objects,
# 'mu_scale': mu_scale, 'logvar_scale': logvar_scale, 'z_scale': z_scale,
# 'mu_offset': mu_offset, 'logvar_offset': logvar_offset, 'z_offset': z_offset}
# return encode_dict
#
# def encode_prior(self, x, x_prior=None, filtering_heuristic='variance', k=None):
# if k is None:
# k = self.n_kp_prior
# if x_prior is None:
# x_prior = x
# kp_p, var_kp_p = self.prior(x_prior, global_kp=True)
# kp_p = kp_p.view(x_prior.shape[0], -1, 2) # [batch_size, n_kp_total, 2]
# var_kp_p = var_kp_p.view(x_prior.shape[0], kp_p.shape[1], -1) # [batch_size, n_kp_total, 3]
# if filtering_heuristic == 'distance':
# # filter proposals by distance to the patches' center
# dist_from_center = self.prior.get_distance_from_patch_centers(kp_p, global_kp=True)
# _, indices = torch.topk(dist_from_center, k=k, dim=-1, largest=True)
# batch_indices = torch.arange(kp_p.shape[0]).view(-1, 1).to(kp_p.device)
# kp_p = kp_p[batch_indices, indices]
# elif filtering_heuristic == 'variance':
# total_var = var_kp_p.sum(-1)
# _, indices = torch.topk(total_var, k=k, dim=-1, largest=False)
# batch_indices = torch.arange(kp_p.shape[0]).view(-1, 1).to(kp_p.device)
# kp_p = kp_p[batch_indices, indices]
# else:
# # alternatively, just sample random kp
# kp_p = kp_p[:, torch.randperm(kp_p.shape[1])[:k]]
# return kp_p
#
# def translate_patches(self, kp_batch, patches_batch, scale=None, translation=None, scale_normalized=False):
# """
# translate patches to be centered around given keypoints
# kp_batch: [bs, n_kp, 2] in [-1, 1]
# patches: [bs, n_kp, ch_patches, patch_size, patch_size]
# scale: None or [bs, n_kp, 2] or [bs, n_kp, 1]
# translation: None or [bs, n_kp, 2] or [bs, n_kp, 1] (delta from kp)
# scale_normalized: False if scale is not in [0, 1]
# :return: translated_padded_pathces [bs, n_kp, ch, img_size, img_size]
# """
# batch_size, n_kp, ch_patch, patch_size, _ = patches_batch.shape
# img_size = self.image_size
# if scale is None:
# z_scale = (patch_size / img_size) * torch.ones_like(kp_batch)
# else:
# # normalize to [0, 1]
# if scale_normalized:
# z_scale = scale
# else:
# z_scale = torch.sigmoid(scale) # -> [0, 1]
# z_pos = kp_batch.reshape(-1, kp_batch.shape[-1]) # [bs * n_kp, 2]
# z_scale = z_scale.view(-1, z_scale.shape[-1]) # [bs * n_kp, 2]
# patches_batch = patches_batch.reshape(-1, *patches_batch.shape[2:])
# out_dims = (batch_size * n_kp, ch_patch, img_size, img_size)
# trans_patches_batch = spatial_transform(patches_batch, z_pos, z_scale, out_dims, inverse=True)
# trans_padded_patches_batch = trans_patches_batch.view(batch_size, n_kp, *trans_patches_batch.shape[1:])
# # [bs, n_kp, ch, img_size, img_size]
# return trans_padded_patches_batch
#
# def get_objects_alpha_rgb(self, z_kp, z_features, z_scale=None, translation=None, noisy=False):
# dec_objects = self.object_dec(z_features) # [bs * n_kp, 4, patch_size, patch_size]
# dec_objects = dec_objects.view(-1, self.n_kp_enc,
# *dec_objects.shape[1:]) # [bs, n_kp, 4, patch_size, patch_size]
# # translate patches
# dec_objects_trans = self.translate_patches(z_kp, dec_objects, z_scale, translation)
# dec_objects_trans = dec_objects_trans.clamp(0, 1) # STN can change values to be < 0
# # dec_objects_trans: [bs, n_kp, 3, im_size, im_size]
# # multiply by alpha channel
# a_obj, rgb_obj = torch.split(dec_objects_trans, [1, 3], dim=2)
#
# if noisy:
# a_obj = a_obj + 0.1 * torch.randn_like(a_obj)
# a_obj = a_obj.clamp(0, 1)
# return dec_objects, a_obj, rgb_obj
#
# def get_objects_alpha_rgb_with_depth(self, a_obj, rgb_obj, obj_on, z_depth, eps=1e-5):
# # obj_on: [bs, n_kp, 1]
# # z_depth: [bs, n_kp, 1]
# # turn off inactive particles
# a_obj = obj_on[:, :, None, None, None] * a_obj # [bs, n_kp, 1, im_size, im_size]
# rgba_obj = a_obj * rgb_obj
# # importance map
# importance_map = a_obj * torch.sigmoid(-z_depth[:, :, :, None, None])
# # normalize
# importance_map = importance_map / (torch.sum(importance_map, dim=1, keepdim=True) + eps)
# # this imitates softmax
# dec_objects_trans = (rgba_obj * importance_map).sum(dim=1)
# alpha_mask = 1.0 - (importance_map * a_obj).sum(dim=1)
# a_obj = importance_map * a_obj
# return a_obj, alpha_mask, dec_objects_trans
#
# def decode_objects(self, z_kp, z_features, obj_on, z_scale=None, translation=None, noisy=False, z_depth=None):
# dec_objects, a_obj, rgb_obj = self.get_objects_alpha_rgb(z_kp, z_features, z_scale=z_scale,
# translation=translation, noisy=noisy)
# alpha_masks, bg_mask, dec_objects_trans = self.get_objects_alpha_rgb_with_depth(a_obj, rgb_obj, obj_on=obj_on,
# z_depth=z_depth)
# return dec_objects, dec_objects_trans, alpha_masks, bg_mask
#
# def decode_all(self, z, z_features, obj_on, z_depth=None, noisy=False, z_scale=None):
# object_dec_out = self.decode_objects(z, z_features, obj_on, noisy=noisy, z_depth=z_depth, z_scale=z_scale)
# dec_objects, dec_objects_trans, alpha_masks, bg_mask = object_dec_out
#
# decoder_out = {'dec_objects': dec_objects, 'dec_objects_trans': dec_objects_trans,
# 'bg_mask': bg_mask, 'alpha_masks': alpha_masks}
#
# return decoder_out
#
# def forward(self, x, deterministic=False, x_prior=None, warmup=False, noisy=False,
# cropped_objects_prev=None, mu_scale_prev=None, train_prior=True, refinement_iter=False,
# use_static_encoders=True):
# # refinement_iter: do another encoding step to get a better lock on the object's position
# # first, extract prior KP proposals
# # prior proposals
# kp_p = self.encode_prior(x, x_prior=x_prior, filtering_heuristic='variance')
# kp_init = kp_p if train_prior else kp_p.detach()
# encoder_out = self.encode_all(x, deterministic=deterministic, noisy=noisy, warmup=warmup, kp_init=kp_init,
# cropped_objects_prev=cropped_objects_prev, scale_prev=mu_scale_prev,
# refinement_iter=refinement_iter, use_static_encoders=use_static_encoders)
# # detach for the kl-divergence
# kp_p = kp_p.detach()
# mu = encoder_out['mu']
# logvar = encoder_out['logvar']
# z_base = encoder_out['z_base']
# z = encoder_out['z']
# mu_offset = encoder_out['mu_offset']
# logvar_offset = encoder_out['logvar_offset']
# z_offset = encoder_out['z_offset']
# kp_heatmap = encoder_out['kp_heatmap']
# mu_features = encoder_out['mu_features']
# logvar_features = encoder_out['logvar_features']
# z_features = encoder_out['z_features']
# obj_on = encoder_out['obj_on']
# obj_on_a = encoder_out['obj_on_a']
# obj_on_b = encoder_out['obj_on_b']
# mu_depth = encoder_out['mu_depth']
# logvar_depth = encoder_out['logvar_depth']
# z_depth = encoder_out['z_depth']
# cropped_objects = encoder_out['cropped_objects']
# mu_scale = encoder_out['mu_scale']
# logvar_scale = encoder_out['logvar_scale']
# z_scale = encoder_out['z_scale']
#
# obj_on_sample = obj_on
#
# decoder_out = self.decode_all(z, z_features, obj_on_sample, z_depth, noisy=noisy, z_scale=z_scale)
# dec_objects = decoder_out['dec_objects']
# dec_objects_trans = decoder_out['dec_objects_trans']
# bg_mask = decoder_out['bg_mask']
# alpha_masks = decoder_out['alpha_masks']
#
# output_dict = {}
# output_dict['kp_p'] = kp_p
# output_dict['mu'] = mu
# output_dict['logvar'] = logvar
# output_dict['z_base'] = z_base
# output_dict['z'] = z
# output_dict['mu_offset'] = mu_offset
# output_dict['logvar_offset'] = logvar_offset
# output_dict['mu_features'] = mu_features
# output_dict['logvar_features'] = logvar_features
# output_dict['z_features'] = z_features
# output_dict['bg_mask'] = bg_mask
# output_dict['cropped_objects_original'] = cropped_objects
# output_dict['obj_on_a'] = obj_on_a
# output_dict['obj_on_b'] = obj_on_b
# output_dict['obj_on'] = obj_on
# output_dict['dec_objects_original'] = dec_objects
# output_dict['dec_objects'] = dec_objects_trans
# output_dict['mu_depth'] = mu_depth
# output_dict['logvar_depth'] = logvar_depth
# output_dict['z_depth'] = z_depth
# output_dict['mu_scale'] = mu_scale
# output_dict['logvar_scale'] = logvar_scale
# output_dict['z_scale'] = z_scale
# output_dict['alpha_masks'] = alpha_masks
#
# return output_dict
class BgDLP(nn.Module):
def __init__(self, cdim=3, enc_channels=(16, 16, 32), image_size=64, pad_mode='replicate', dropout=0.0,
learned_feature_dim=16, n_kp_enc=10, use_resblock=False):
super(BgDLP, self).__init__()
"""
DLP Background Module -- encode a latent for the (masked) background, z_bg
Basically, just a convolutional-based encoder used in standard VAEs
cdim: channels of the input image (3...)
enc_channels: channels for the posterior CNN (takes in the whole image)
pad_mode: padding for the CNNs, 'zeros' or 'replicate' (default)
learned_feature_dim: the latent visual features dimensions extracted from glimpses.
"""
self.image_size = image_size
self.dropout = dropout
self.features_dim = int(image_size // (2 ** (len(enc_channels) - 1)))
self.learned_feature_dim = learned_feature_dim
assert learned_feature_dim > 0, "learned_feature_dim must be greater than 0"
self.cdim = cdim
self.n_kp_enc = 32
self.use_resblock = use_resblock
# encoder
self.bg_cnn_enc = KeyPointCNNOriginal(cdim=cdim, channels=enc_channels, image_size=image_size,
n_kp=self.n_kp_enc,
pad_mode=pad_mode, use_resblock=self.use_resblock)
bg_enc_output_dim = self.learned_feature_dim * 2 # [mu_features, sigma_features]
self.bg_enc = nn.Sequential(nn.Linear(self.n_kp_enc * self.features_dim ** 2, 256),
nn.ReLU(True),
nn.Linear(256, 256),
nn.ReLU(True),
nn.Linear(256, bg_enc_output_dim))
# decoder
decoder_n_kp = self.n_kp_enc
self.latent_to_feat_map = FCToCNN(target_hw=self.features_dim, n_ch=decoder_n_kp,
features_dim=self.learned_feature_dim, pad_mode=pad_mode,
use_resblock=self.use_resblock)
self.dec = CNNDecoder(cdim=cdim, channels=enc_channels, image_size=image_size, in_ch=decoder_n_kp,
pad_mode=pad_mode, use_resblock=self.use_resblock)
self.init_weights()
def get_parameters(self, prior=True, encoder=True, decoder=True):
parameters = []
if encoder:
parameters.extend(list(self.bg_cnn_enc.parameters()))
parameters.extend(list(self.bg_enc.parameters()))
if decoder:
parameters.extend(list(self.dec.parameters()))
parameters.extend(list(self.latent_to_feat_map.parameters()))
return parameters
def set_require_grad(self, prior_value=True, enc_value=True, dec_value=True):
for param in self.bg_cnn_enc.parameters():
param.requires_grad = enc_value
for param in self.bg_enc.parameters():
param.requires_grad = enc_value
for param in self.dec.parameters():
param.requires_grad = dec_value
for param in self.latent_to_feat_map.parameters():
param.requires_grad = dec_value
def init_weights(self):
for m in self.modules():
if isinstance(m, nn.Conv2d):
nn.init.normal_(m.weight, 0, 0.01)
if m.bias is not None:
nn.init.constant_(m.bias, 0)
elif isinstance(m, (nn.BatchNorm2d, nn.GroupNorm)):
nn.init.constant_(m.weight, 1)
nn.init.constant_(m.bias, 0)
elif isinstance(m, nn.Linear):
# use pytorch's default
pass
def encode_bg_features(self, x, masks=None):
# x: [bs, ch, image_size, image_size]
# masks: [bs, 1, image_size, image_size]
batch_size, _, features_dim, _ = x.shape
# bg features
if masks is not None:
x_in = x * masks
else:
x_in = x
_, cnn_features = self.bg_cnn_enc(x_in)
cnn_features = cnn_features.view(batch_size, -1) # flatten
bg_enc_out = self.bg_enc(cnn_features) # [bs,, 2 * learned_features_dim]
mu_bg, logvar_bg = bg_enc_out.chunk(2, dim=-1)
return mu_bg, logvar_bg
def encode_all(self, x, masks=None, deterministic=False):
# encode background
mu_bg, logvar_bg = self.encode_bg_features(x, masks)
if deterministic:
z_bg = mu_bg
else:
z_bg = reparameterize(mu_bg, logvar_bg)
z_kp = torch.zeros(mu_bg.shape[0], 1, 2, device=x.device, dtype=torch.float)
encode_dict = {'mu_bg': mu_bg, 'logvar_bg': logvar_bg, 'z_bg': z_bg, 'z_kp': z_kp}
return encode_dict
def decode_all(self, z_features):
feature_maps = self.latent_to_feat_map(z_features)
bg_rec = self.dec(feature_maps)
return bg_rec
def forward(self, x, masks=None, deterministic=False):
encoder_out = self.encode_all(x, masks, deterministic)
mu_bg = encoder_out['mu_bg']
logvar_bg = encoder_out['logvar_bg']
z_bg = encoder_out['z_bg']
z_kp = encoder_out['z_kp']
bg_rec = self.decode_all(z_bg)
output_dict = {'mu_bg': mu_bg, 'logvar_bg': logvar_bg, 'z_bg': z_bg, 'z_kp': z_kp, 'bg_rec': bg_rec}
return output_dict
# single-image deep latent particles
class ObjectDLP(nn.Module):
def __init__(self, cdim=3, enc_channels=(16, 16, 32), prior_channels=(16, 16, 32), image_size=64, n_kp=1,
pad_mode='replicate', sigma=1.0, dropout=0.0,
patch_size=16, n_kp_enc=20, n_kp_prior=20, learned_feature_dim=16,
bg_learned_feature_dim=None,
kp_range=(-1, 1), kp_activation="tanh", anchor_s=0.25, use_tracking=False,
use_resblock=False, scale_std=0.3, offset_std=0.2, obj_on_alpha=0.1, obj_on_beta=0.1,
use_correlation_heatmaps=False, enable_enc_attn=False, filtering_heuristic='variance'):
super(ObjectDLP, self).__init__()
"""
cdim: channels of the input image (3...)
enc_channels: channels for the posterior CNN (takes in the whole image)