-
Notifications
You must be signed in to change notification settings - Fork 1
/
models.py
901 lines (781 loc) · 42.8 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
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Wed Feb 17 14:03:10 2021
@author: hossein
here we can find different types of models
that are define for person-attribute detection.
this is Hossein Bodaghies thesis
"""
import torch.nn as nn
import torch
from transformers import MBConvBlock, ScaledDotProductAttention
import copy
#%%
from torchreid.models.osnet import Conv1x1, OSBlock
device = torch.device('cuda' if torch.cuda.is_available() else 'cpu')
blocks = [OSBlock, OSBlock, OSBlock]
layers = [2, 2, 2]
channels = [16, 64, 96, 128] # channels are the only difference between os_net_x_1 and others
def _make_layer(
block,
layer,
in_channels,
out_channels,
reduce_spatial_size,
IN=False
):
layers = []
layers.append(block(in_channels, out_channels, IN=IN))
for i in range(1, layer):
layers.append(block(out_channels, out_channels, IN=IN))
if reduce_spatial_size:
layers.append(
nn.Sequential(
Conv1x1(out_channels, out_channels),
nn.AvgPool2d(2, stride=2)
)
)
return nn.Sequential(*layers)
#%%
class mb_transformer_build_model(nn.Module):
def __init__(self,
model,
device,
main_cov_size = 128,
attr_dim = 128,
dropout_p = 0.3):
super().__init__()
self.feature_dim = main_cov_size
self.dropout_p = dropout_p
self.model = model
self.attr_dim = attr_dim
self.global_avgpool = nn.AdaptiveAvgPool2d(1)
self.maxpool1d = nn.MaxPool1d(kernel_size=2, stride=2)
self.device = device
# convs + transforms:
# head
self.conv_head = nn.Sequential(MBConvBlock(ksize=3,input_filters=512, output_filters=128, image_size=(16,8)),
nn.Conv2d(128, 128, kernel_size=1),
nn.ReLU(),
nn.Conv2d(128, 128, kernel_size=1)
)
self.trans_head1 = ScaledDotProductAttention(128, 16, 16, 8)
self.trans_head2 = ScaledDotProductAttention(128, 16, 16, 8)
self.mlp_head1 = nn.Sequential(nn.Linear(128, 128), nn.ReLU(), nn.Linear(128, 128))
self.mlp_head2 = nn.Sequential(nn.Linear(128, 64), nn.ReLU(), nn.Linear(64, 32))
# head_color
self.conv_head_color = nn.Sequential(MBConvBlock(ksize=3,input_filters=512, output_filters=128, image_size=(16,8)),
nn.Conv2d(128, 128, kernel_size=1),
nn.ReLU(),
nn.Conv2d(128, 128, kernel_size=1)
)
self.trans_head_color1 = ScaledDotProductAttention(128, 16, 16, 8)
self.trans_head_color2 = ScaledDotProductAttention(128, 16, 16, 8)
self.mlp_head_color1 = nn.Sequential(nn.Linear(128, 128), nn.ReLU(), nn.Linear(128, 128))
self.mlp_head_color2 = nn.Sequential(nn.Linear(128, 64), nn.ReLU(), nn.Linear(64, 32))
# body
self.conv_body = nn.Sequential(MBConvBlock(ksize=3,input_filters=512, output_filters=128, image_size=(16,8)),
nn.Conv2d(128, 128, kernel_size=1),
nn.ReLU(),
nn.Conv2d(128, 128, kernel_size=1)
)
self.trans_body1 = ScaledDotProductAttention(128, 16, 16, 8)
self.trans_body2 = ScaledDotProductAttention(128, 16, 16, 8)
self.mlp_body1 = nn.Sequential(nn.Linear(128, 128), nn.ReLU(), nn.Linear(128, 128))
self.mlp_body2 = nn.Sequential(nn.Linear(128, 64), nn.ReLU(), nn.Linear(64, 32))
# body_color
self.conv_body_color = nn.Sequential(MBConvBlock(ksize=3,input_filters=512, output_filters=128, image_size=(16,8)),
nn.Conv2d(128, 128, kernel_size=1),
nn.ReLU(),
nn.Conv2d(128, 128, kernel_size=1)
)
self.trans_body_color1 = ScaledDotProductAttention(128, 16, 16, 8)
self.trans_body_color2 = ScaledDotProductAttention(128, 16, 16, 8)
self.mlp_body_color1 = nn.Sequential(nn.Linear(128, 128), nn.ReLU(), nn.Linear(128, 128))
self.mlp_body_color2 = nn.Sequential(nn.Linear(128, 64), nn.ReLU(), nn.Linear(64, 32))
# body_type
self.conv_body_type = nn.Sequential(MBConvBlock(ksize=3,input_filters=512, output_filters=128, image_size=(16,8)),
nn.Conv2d(128, 128, kernel_size=1),
nn.ReLU(),
nn.Conv2d(128, 128, kernel_size=1)
)
self.trans_body_type1 = ScaledDotProductAttention(128, 16, 16, 8)
self.trans_body_type2 = ScaledDotProductAttention(128, 16, 16, 8)
self.mlp_body_type1 = nn.Sequential(nn.Linear(128, 128), nn.ReLU(), nn.Linear(128, 128))
self.mlp_body_type2 = nn.Sequential(nn.Linear(128, 64), nn.ReLU(), nn.Linear(64, 32))
# leg
self.conv_leg = nn.Sequential(MBConvBlock(ksize=3,input_filters=512, output_filters=128, image_size=(16,8)),
nn.Conv2d(128, 128, kernel_size=1),
nn.ReLU(),
nn.Conv2d(128, 128, kernel_size=1)
)
self.trans_leg1 = ScaledDotProductAttention(128, 16, 16, 8)
self.trans_leg2 = ScaledDotProductAttention(128, 16, 16, 8)
self.mlp_leg1 = nn.Sequential(nn.Linear(128, 128), nn.ReLU(), nn.Linear(128, 128))
self.mlp_leg2 = nn.Sequential(nn.Linear(128, 64), nn.ReLU(), nn.Linear(64, 32))
# leg_color
self.conv_leg_color = nn.Sequential(MBConvBlock(ksize=3,input_filters=512, output_filters=128, image_size=(16,8)),
nn.Conv2d(128, 128, kernel_size=1),
nn.ReLU(),
nn.Conv2d(128, 128, kernel_size=1)
)
self.trans_leg_color1 = ScaledDotProductAttention(128, 16, 16, 8)
self.trans_leg_color2 = ScaledDotProductAttention(128, 16, 16, 8)
self.mlp_leg_color1 = nn.Sequential(nn.Linear(128, 128), nn.ReLU(), nn.Linear(128, 128))
self.mlp_leg_color2 = nn.Sequential(nn.Linear(128, 64), nn.ReLU(), nn.Linear(64, 32))
# foot
self.conv_foot = nn.Sequential(MBConvBlock(ksize=3,input_filters=512, output_filters=128, image_size=(16,8)),
nn.Conv2d(128, 128, kernel_size=1),
nn.ReLU(),
nn.Conv2d(128, 128, kernel_size=1)
)
self.trans_foot1 = ScaledDotProductAttention(128, 16, 16, 8)
self.trans_foot2 = ScaledDotProductAttention(128, 16, 16, 8)
self.mlp_foot1 = nn.Sequential(nn.Linear(128, 128), nn.ReLU(), nn.Linear(128, 128))
self.mlp_foot2 = nn.Sequential(nn.Linear(128, 64), nn.ReLU(), nn.Linear(64, 32))
# foot_color
self.conv_foot_color = nn.Sequential(MBConvBlock(ksize=3,input_filters=512, output_filters=128, image_size=(16,8)),
nn.Conv2d(128, 128, kernel_size=1),
nn.ReLU(),
nn.Conv2d(128, 128, kernel_size=1)
)
self.trans_foot_color1 = ScaledDotProductAttention(128, 16, 16, 8)
self.trans_foot_color2 = ScaledDotProductAttention(128, 16, 16, 8)
self.mlp_foot_color1 = nn.Sequential(nn.Linear(128, 128), nn.ReLU(), nn.Linear(128, 128))
self.mlp_foot_color2 = nn.Sequential(nn.Linear(128, 64), nn.ReLU(), nn.Linear(64, 32))
# gender
self.conv_gender = nn.Sequential(MBConvBlock(ksize=3,input_filters=512, output_filters=128, image_size=(16,8)),
nn.Conv2d(128, 128, kernel_size=1),
nn.ReLU(),
nn.Conv2d(128, 128, kernel_size=1)
)
self.trans_gender1 = ScaledDotProductAttention(128, 16, 16, 8)
self.trans_gender2 = ScaledDotProductAttention(128, 16, 16, 8)
self.mlp_gender1 = nn.Sequential(nn.Linear(128, 128), nn.ReLU(), nn.Linear(128, 128))
self.mlp_gender2 = nn.Sequential(nn.Linear(128, 64), nn.ReLU(), nn.Linear(64, 32))
# age
self.conv_age = nn.Sequential(MBConvBlock(ksize=3,input_filters=512, output_filters=128, image_size=(16,8)),
nn.Conv2d(128, 128, kernel_size=1),
nn.ReLU(),
nn.Conv2d(128, 128, kernel_size=1)
)
self.trans_age1 = ScaledDotProductAttention(128, 16, 16, 8)
self.trans_age2 = ScaledDotProductAttention(128, 16, 16, 8)
self.mlp_age1 = nn.Sequential(nn.Linear(128, 128), nn.ReLU(), nn.Linear(128, 128))
self.mlp_age2 = nn.Sequential(nn.Linear(128, 64), nn.ReLU(), nn.Linear(64, 32))
# bags
self.conv_bags = nn.Sequential(MBConvBlock(ksize=3,input_filters=512, output_filters=128, image_size=(16,8)),
nn.Conv2d(128, 128, kernel_size=1),
nn.ReLU(),
nn.Conv2d(128, 128, kernel_size=1)
)
self.trans_bags1 = ScaledDotProductAttention(128, 16, 16, 8)
self.trans_bags2 = ScaledDotProductAttention(128, 16, 16, 8)
self.mlp_bags1 = nn.Sequential(nn.Linear(128, 128), nn.ReLU(), nn.Linear(128, 128))
self.mlp_bags2 = nn.Sequential(nn.Linear(128, 64), nn.ReLU(), nn.Linear(64, 32))
# fully connecteds
# head
self.head_fc = [self._construct_fc_layer(self.attr_dim, 1024, dropout_p=dropout_p).to(self.device)]
self.head_color_fc = [self._construct_fc_layer(self.attr_dim, 1024, dropout_p=dropout_p).to(self.device)]
# upper body
self.body_fc = [self._construct_fc_layer(self.attr_dim, 1024, dropout_p=dropout_p).to(self.device)]
self.body_type_fc = [self._construct_fc_layer(self.attr_dim, 1024, dropout_p=dropout_p).to(self.device)]
self.body_color_fc = [self._construct_fc_layer(self.attr_dim, 1024, dropout_p=dropout_p).to(self.device)]
#lower body
self.leg_fc = [self._construct_fc_layer(self.attr_dim, 1024, dropout_p=dropout_p).to(self.device)]
self.leg_color_fc = [self._construct_fc_layer(self.attr_dim, 1024, dropout_p=dropout_p).to(self.device)]
#foot
self.foot_fc = [self._construct_fc_layer(self.attr_dim, 1024, dropout_p=dropout_p).to(self.device)]
self.foot_color_fc = [self._construct_fc_layer(self.attr_dim, 1024, dropout_p=dropout_p).to(self.device)]
#bags
self.bags_fc = [self._construct_fc_layer(self.attr_dim, 1024, dropout_p=dropout_p).to(self.device)]
# general
self.age_fc = [self._construct_fc_layer(self.attr_dim, 1024, dropout_p=dropout_p).to(self.device)]
self.gender_fc = [self._construct_fc_layer(self.attr_dim, 1024, dropout_p=dropout_p).to(self.device)]
# classifiers
# head
self.head_clf = [nn.Linear(self.attr_dim, 5).to(self.device)]
self.head_color_clf = [nn.Linear(self.attr_dim, 2).to(self.device)]
# body
self.body_clf = [nn.Linear(self.attr_dim, 4).to(self.device)]
self.body_type_clf = [nn.Linear(self.attr_dim, 1).to(self.device)]
self.body_color_clf = [nn.Linear(self.attr_dim, 8).to(self.device)]
# leg
self.leg_clf = [nn.Linear(self.attr_dim, 3).to(self.device)]
self.leg_color_clf = [nn.Linear(self.attr_dim, 9).to(self.device)]
# foot
self.foot_clf = [nn.Linear(self.attr_dim, 3).to(self.device)]
self.foot_color_clf = [nn.Linear(self.attr_dim, 4).to(self.device)]
# bag
self.bags_clf = [nn.Linear(self.attr_dim, 4).to(self.device)]
# gender
self.age_clf = [nn.Linear(self.attr_dim, 4).to(self.device)]
self.gender_clf = [nn.Linear(self.attr_dim, 1).to(self.device)]
def _construct_fc_layer(self, fc_dims, input_dim, dropout_p=None):
if fc_dims is None or fc_dims < 0:
self.feature_dim = input_dim
return None
if isinstance(fc_dims, int):
fc_dims = [fc_dims]
layers = []
for dim in fc_dims:
layers.append(nn.Linear(input_dim, dim))
layers.append(nn.BatchNorm1d(dim))
layers.append(nn.ReLU(inplace=True))
if dropout_p is not None:
layers.append(nn.Dropout(p=dropout_p))
input_dim = dim
self.feature_dim = fc_dims[-1]
return nn.Sequential(*layers)
def vector_features(self, x):
features = self.model(x)
out_attr = self.attr_lin(features)
out_features = torch.cat(features, out_attr, dim=1)
return out_features
def out_layers_extractor(self, x, layer):
out_os_layers = self.model.layer_extractor(x, layer)
return out_os_layers
def fc2clf(self, x, fc_layer, clf_layer, sep_clf=False, sep_fc=False, need_feature=False):
fc_out = []
clf_out = []
if sep_fc:
for i,fc in enumerate(fc_layer):
feature = fc_layer[i](x)
fc_out.append(feature)
clf_out.append(clf_layer[i](feature))
if need_feature:
return fc_out
else:
return clf_out
else:
fc_out.append(fc_layer[0](x))
if need_feature:
return fc_out
else:
if sep_clf:
for clf in clf_layer:
clf_out.append(clf(fc_out[0]))
return clf_out
else:
clf_out.append(clf_layer[0](fc_out[0]))
return clf_out
def attr_branch(self, x, fc_layer, clf_layer,
conv_layer, trans1, trans2, mlp1, mlp2, sep_fc=False,
sep_clf=False, need_feature=False):
''' fc_layer should be a list of fully connecteds
clf_layer hould be a list of classifiers
'''
# handling conv layer
if conv_layer:
x = conv_layer(x)
x = x.reshape(x.size(0), 128, -1).permute(0,2,1)
x = mlp1(trans1(x, x, x))
x = self.maxpool1d(x.permute(0,2,1)).permute(0,2,1)
x = mlp2(trans2(x, x, x))
x = self.maxpool1d(x.permute(0,2,1))
x = x.reshape(x.size(0), -1)
out = self.fc2clf(x=x, fc_layer=fc_layer,
clf_layer=clf_layer,
sep_clf=sep_clf, sep_fc=sep_fc,
need_feature=need_feature)
return out
def forward(self, x, need_feature=False):
out_conv4 = self.out_layers_extractor(x, 'out_conv4')
# head
out_head = self.attr_branch(out_conv4, fc_layer = self.head_fc,
clf_layer = self.head_clf,
conv_layer = self.conv_head,
trans1 = self.trans_head1,
trans2 = self.trans_head2,
mlp1 = self.mlp_head1, mlp2 = self.mlp_head2,
need_feature = need_feature)[0]
# head_colour
out_head_colour = self.attr_branch(out_conv4, fc_layer = self.head_color_fc,
clf_layer = self.head_color_clf,
conv_layer = self.conv_head_color,
trans1 = self.trans_head_color1,
trans2 = self.trans_head_color2,
mlp1 = self.mlp_head_color1, mlp2 = self.mlp_head_color2,
need_feature = need_feature)[0]
# body
out_body = self.attr_branch(out_conv4, fc_layer = self.body_fc,
clf_layer = self.body_clf,
conv_layer = self.conv_body,
trans1 = self.trans_body1,
trans2 = self.trans_body2,
mlp1 = self.mlp_body1, mlp2 = self.mlp_body2,
need_feature = need_feature)[0]
# out_body_colour
out_body_colour = self.attr_branch(out_conv4, fc_layer = self.body_color_fc,
clf_layer = self.body_color_clf,
conv_layer = self.conv_body_color,
trans1 = self.trans_body_color1,
trans2 = self.trans_body_color2,
mlp1 = self.mlp_body_color1, mlp2 = self.mlp_body_color2,
need_feature = need_feature)[0]
# body_type
out_body_type = self.attr_branch(out_conv4, fc_layer = self.body_type_fc,
clf_layer = self.body_type_clf,
conv_layer = self.conv_body_type,
trans1 = self.trans_body_type1,
trans2 = self.trans_body_type2,
mlp1 = self.mlp_body_type1, mlp2 = self.mlp_body_type2,
need_feature = need_feature)[0]
# leg
out_leg = self.attr_branch(out_conv4, fc_layer = self.leg_fc,
clf_layer = self.leg_clf,
conv_layer = self.conv_leg,
trans1 = self.trans_leg1,
trans2 = self.trans_leg2,
mlp1 = self.mlp_leg1, mlp2 = self.mlp_leg2,
need_feature = need_feature)[0]
# out_leg_colour
out_leg_colour = self.attr_branch(out_conv4, fc_layer = self.leg_color_fc,
clf_layer = self.leg_color_clf,
conv_layer = self.conv_leg_color,
trans1 = self.trans_leg_color1,
trans2 = self.trans_leg_color2,
mlp1 = self.mlp_leg_color1, mlp2 = self.mlp_leg_color2,
need_feature = need_feature)[0]
# foot
out_foot = self.attr_branch(out_conv4, fc_layer = self.foot_fc,
clf_layer = self.foot_clf,
conv_layer = self.conv_foot,
trans1 = self.trans_foot1,
trans2 = self.trans_foot2,
mlp1 = self.mlp_foot1, mlp2 = self.mlp_foot2,
need_feature = need_feature)[0]
# out_foot_colour
out_foot_colour = self.attr_branch(out_conv4, fc_layer = self.foot_color_fc,
clf_layer = self.foot_color_clf,
conv_layer = self.conv_foot_color,
trans1 = self.trans_foot_color1,
trans2 = self.trans_foot_color2,
mlp1 = self.mlp_foot_color1, mlp2 = self.mlp_foot_color2,
need_feature = need_feature)[0]
# bag
out_bags = self.attr_branch(out_conv4, fc_layer = self.bags_fc,
clf_layer = self.bags_clf,
conv_layer = self.conv_bags,
trans1 = self.trans_bags1,
trans2 = self.trans_bags2,
mlp1 = self.mlp_bags1, mlp2 = self.mlp_bags2,
need_feature = need_feature)[0]
# age
out_age = self.attr_branch(out_conv4, fc_layer = self.age_fc,
clf_layer = self.age_clf,
conv_layer = self.conv_age,
trans1 = self.trans_age1,
trans2 = self.trans_age2,
mlp1 = self.mlp_age1, mlp2 = self.mlp_age2,
need_feature = need_feature)[0]
# out_gender
out_gender = self.attr_branch(out_conv4, fc_layer = self.gender_fc,
clf_layer = self.gender_clf,
conv_layer = self.conv_gender,
trans1 = self.trans_gender1,
trans2 = self.trans_gender2,
mlp1 = self.mlp_gender1, mlp2 = self.mlp_gender2,
need_feature = need_feature)[0]
out_attributes = {'head':out_head,
'head_colour':out_head_colour,
'body':out_body,
'body_type':out_body_type,
'leg':out_leg,
'foot':out_foot,
'gender':out_gender,
'bags':out_bags,
'body_colour':out_body_colour,
'leg_colour':out_leg_colour,
'foot_colour':out_foot_colour,
'age':out_age}
return out_attributes
def save_baseline(self, saving_path):
torch.save(self.model.state_dict(), saving_path)
print('baseline model save to {}'.format(saving_path))
#%%
class CD_builder(nn.Module):
def __init__(self,
model,
num_id,
feature_dim = channels[3],
attr_feat_dim = channels[1],
attr_dim = 46,
dropout_p = 0.3):
super().__init__()
self.feature_dim = feature_dim
self.attr_feat_dim = attr_feat_dim
self.dropout_p = dropout_p
self.global_avgpool = nn.AdaptiveAvgPool2d(1)
self.softmax = nn.Softmax(dim=1)
self.sigmoid = nn.Sigmoid()
self.model = model
self.fc = self._construct_fc_layer(self.attr_feat_dim, channels[-1], dropout_p=dropout_p)
self.attr_clf = nn.Linear(self.attr_feat_dim, attr_dim)
def _construct_fc_layer(self, fc_dims, input_dim, dropout_p=None):
if fc_dims is None or fc_dims < 0:
self.feature_dim = input_dim
return None
if isinstance(fc_dims, int):
fc_dims = [fc_dims]
layers = []
for dim in fc_dims:
layers.append(nn.Linear(input_dim, dim))
layers.append(nn.BatchNorm1d(dim))
layers.append(nn.ReLU(inplace=True))
if dropout_p is not None:
layers.append(nn.Dropout(p=dropout_p))
input_dim = dim
self.feature_dim = fc_dims[-1]
return nn.Sequential(*layers)
def get_feature(self, x, get_attr=True, get_feature=True, get_collection=False):
out_conv4 = self.out_layers_extractor(x, 'out_conv4')
# The path for multi-branches for attributes
out_head = self.attr_branch(out_conv4, self.conv_head, self.head_fc, self.head_clf, need_feature=True)
out_body = self.attr_branch(out_conv4, self.conv_body, self.body_fc, self.body_clf, need_feature=True)
out_body_type = self.attr_branch(out_conv4, self.conv_body_type, self.body_type_fc, self.body_type_clf, need_feature=True)
out_leg = self.attr_branch(out_conv4, self.conv_leg ,self.leg_fc, self.leg_clf, need_feature=True)
out_foot = self.attr_branch(out_conv4, self.conv_foot, self.foot_fc, self.foot_clf, need_feature=True)
out_gender = self.attr_branch(out_conv4, self.conv_gender, self.gender_fc, self.gender_clf, need_feature=True)
out_bags = self.attr_branch(out_conv4, self.conv_bags, self.bags_fc, self.bags_clf, need_feature=True)
out_body_colour = self.attr_branch(out_conv4, self.conv_body_color, self.body_color_fc, self.body_color_clf, need_feature=True)
out_leg_colour = self.attr_branch(out_conv4, self.conv_leg_color, self.leg_color_fc, self.leg_color_clf, need_feature=True)
out_foot_colour = self.attr_branch(out_conv4, self.conv_foot_color, self.foot_color_fc, self.foot_color_clf, need_feature=True)
# The path for person re-id:
del out_conv4
x = self.out_layers_extractor(x, 'out_fc')
x = [out_head, out_body, out_body_type, out_leg,
out_foot, out_gender, out_bags, out_body_colour,
out_leg_colour, out_foot_colour, x]
outputs = torch.cat(x, dim=1)
return outputs
def vector_features(self, x):
features = self.model(x)
out_attr = self.attr_lin(features)
out_features = torch.cat(features, out_attr, dim=1)
return out_features
def out_layers_extractor(self, x, layer):
out_os_layers = self.model.layer_extractor(x, layer)
return out_os_layers
def attr_branch(self, x, conv_layer, fc_layer, clf_layer, need_feature=False):
x = conv_layer(x)
x = self.global_avgpool(x)
x = x.view(x.size(0), -1)
x = fc_layer(x)
if need_feature:
return x
else:
x = clf_layer(x)
return x
def forward(self, x):
features = self.out_layers_extractor(x, 'out_globalavg')
features = features.view(features.size(0), -1)
features = self.fc(features)
out_attr = self.attr_clf(features)
return {'attr':out_attr}
def save_baseline(self, saving_path):
torch.save(self.model.state_dict(), saving_path)
print('baseline model save to {}'.format(saving_path))
#%%
class attributes_model(nn.Module):
'''
a model for training whole attributes
'''
def __init__(self,
model,
feature_dim = 512,
attr_dim = 79,
branch_place = None):
super().__init__()
self.feature_dim = feature_dim
self.model = model
self.attr_lin = nn.Linear(in_features=feature_dim , out_features=attr_dim)
if branch_place:
self.branch_place = branch_place
self.layer_list = ['conv1', 'maxpool', 'conv2', 'conv3',
'conv4', 'conv5', 'global_avgpool', 'fc']
self.idx = self.layer_list.index(branch_place)
for i in range(self.idx+1, len(self.layer_list)):
setattr(self, self.layer_list[i], copy.deepcopy(getattr(model, self.layer_list[i])))
else: self.branch_place = 'fc'
def out_layers_extractor(self, x, layer):
out_os_layers = self.model.layer_extractor(x, layer)
return out_os_layers
def forward(self, x, get_features = False):
if get_features:
features = self.out_layers_extractor(x, 'fc')
return features
else:
x = self.out_layers_extractor(x, self.branch_place)
if self.branch_place != 'fc':
for i in range(self.idx+1, len(self.layer_list)):
if self.layer_list[i] != 'fc':
x = getattr(self, self.layer_list[i])(x)
else:
x = x.view(x.size(0), -1)
x = self.fc(x)
return {'attributes':self.attr_lin(x)}
def save_baseline(self, saving_path):
torch.save(self.model.state_dict(), saving_path)
print('baseline model save to {}'.format(saving_path))
#%%
from torchvision import transforms
class Loss_weighting(nn.Module):
'''
a model for training weights of loss functions
'''
def __init__(self, weights_dim=48):
super().__init__()
self.weights_dim = weights_dim
self.weights_lin1 = nn.Linear(in_features=weights_dim , out_features=weights_dim)
self.weights_lin2 = nn.Linear(in_features=weights_dim , out_features=weights_dim)
self.relu = nn.ReLU()
def forward(self, weights):
weights = self.weights_lin1(weights)
weights = self.relu(weights)
weights = self.weights_lin2(weights)
weights = torch.sigmoid(weights)
return weights
def save_baseline(self, saving_path):
torch.save(self.weights_lin.state_dict(), saving_path)
print('loss_weights saved to {}'.format(saving_path))
class mb_CA_auto_build_model(nn.Module):
def __init__(self,
model,
main_cov_size = 512,
attr_dim = 128,
dropout_p = 0.3,
sep_conv_size = 64,
branch_names = None,
feature_selection = None):
super().__init__()
self.feat_indices = feature_selection
self.feature_dim = main_cov_size
if self.feature_dim != 384 and self.feature_dim != 512:
raise Exception('main_cov_size should be 384 or 512')
self.dropout_p = dropout_p
self.global_avgpool = nn.AdaptiveAvgPool2d(1)
self.softmax = nn.Softmax(dim=1)
self.sigmoid = nn.Sigmoid()
self.model = model
self.sep_conv_size = sep_conv_size
self.attr_dim = attr_dim
self.branch_names = branch_names
if self.feat_indices is not None:
self.feature_dim = 25
self.attr_feat_dim = sep_conv_size
self.branches = {}
for k in self.branch_names.keys():
# convs
setattr(self, 'conv_'+k, _make_layer(blocks[2],
layers[2],
self.feature_dim,
self.sep_conv_size,
reduce_spatial_size=False
))
# fully connecteds
setattr(self, 'fc_'+k, self._construct_fc_layer(self.attr_dim, self.attr_feat_dim, dropout_p=dropout_p))
# classifiers
setattr(self, 'clf_'+k, nn.Linear(self.attr_dim, branch_names[k]))
def _construct_fc_layer(self, fc_dims, input_dim, dropout_p=None):
if isinstance(fc_dims, int):
fc_dims = [fc_dims]
layers = []
for dim in fc_dims:
layers.append(nn.Linear(input_dim, dim))
layers.append(nn.BatchNorm1d(dim))
layers.append(nn.ReLU(inplace=True))
if dropout_p is not None:
layers.append(nn.Dropout(p=dropout_p))
input_dim = dim
return nn.Sequential(*layers)
def get_feature(self, x, get_attr=True, get_feature=True, method='both', get_collection=False):
if self.feature_dim == 512:
out_conv4 = self.out_layers_extractor(x, 'out_conv4')
elif self.feature_dim == 384:
out_conv4 = self.out_layers_extractor(x, 'out_conv3')
else:
raise Exception('main_cov_size should be 384 or 512')
out_features = {}
for k in self.branch_names.keys():
out_features.setdefault(k, self.attr_branch(out_conv4 if self.feat_indices == None else torch.index_select(out_conv4, 1, self.feat_indices[0]),
fc_layer = getattr(self,'fc_'+k),
clf_layer = getattr(self,'clf_'+k),
conv_layer = getattr(self,'conv_'+k), need_feature = True)
)
del out_conv4
out_fc_branches = [item[0] for item in list(out_features.values())]
outputs_clfs = {}
for k, v in out_features.items():
outputs_clfs.update({k: v[1]})
x = self.out_layers_extractor(x, 'out_fc')
out_fc_branches = torch.cat(out_fc_branches, dim=1)
if method == 'both':
outputs_fcs = torch.cat((out_fc_branches,x), dim=1)
elif method == 'baseline':
outputs_fcs = x
elif method == 'branches':
outputs_fcs = out_fc_branches
return outputs_fcs, outputs_clfs
def vector_features(self, x):
features = self.model(x)
out_attr = self.attr_lin(features)
out_features = torch.cat(features, out_attr, dim=1)
return out_features
def out_layers_extractor(self, x, layer):
out_os_layers = self.model.layer_extractor(x, layer)
return out_os_layers
def attr_branch(self, x, fc_layer, clf_layer,
conv_layer=None, need_feature=False):
''' fc_layer should be a list of fully connecteds
clf_layer hould be a list of classifiers
'''
# handling conv layer
if conv_layer:
x = conv_layer(x)
x = self.global_avgpool(x)
x = x.view(x.size(0), -1)
x = fc_layer(x)
if need_feature:
out = clf_layer(x)
return x, out
out = clf_layer(x)
return out
def forward(self, x, need_feature=False):
if self.feature_dim == 512:
out_conv4 = self.out_layers_extractor(x, 'out_conv4')
elif self.feature_dim == 384:
out_conv4 = self.out_layers_extractor(x, 'out_conv3')
else:
raise Exception('main_cov_size should be 384 or 512')
out_attributes = {}
for k in self.branch_names.keys():
out_attributes.setdefault(k, self.attr_branch(out_conv4 if self.feat_indices == None else torch.index_select(out_conv4, 1, self.feat_indices[0]),
fc_layer = getattr(self,'fc_'+k),
clf_layer = getattr(self,'clf_'+k),
conv_layer = getattr(self,'conv_'+k), need_feature = need_feature)
)
return out_attributes
def save_baseline(self, saving_path):
torch.save(self.model.state_dict(), saving_path)
print('baseline model save to {}'.format(saving_path))
branch_channels = [16, 64, 96, 128]
base_channels = [64,64,256,384,512]
class mb_CA_auto_same_depth_build_model(nn.Module):
def __init__(self,
model,
branch_place,
dropout_p = 0.3,
branch_names = None,
feature_selection = None):
super().__init__()
self.branch_place = branch_place
self.feat_indices = feature_selection
self.dropout_p = dropout_p
self.global_avgpool = nn.AdaptiveAvgPool2d(1)
self.softmax = nn.Softmax(dim=1)
self.sigmoid = nn.Sigmoid()
self.model = model
self.branch_fcs = branch_names
self.layer_list = ['conv1', 'maxpool', 'conv2', 'conv3', 'conv4']
self.layer_init_dim = [64,64,256,384,512]
if self.feat_indices is not None:
self.feature_dim = 25
branches = {k:[] for k,v in self.branch_fcs.items()}
for k in self.branch_fcs.keys():
# convs
if branch_place not in ['conv5', 'conv4']:
idx = self.layer_list.index(branch_place)-1
for i, layer in enumerate(self.layer_list[self.layer_list.index(branch_place)+1:]):
branches[k].append(_make_layer(
blocks[idx],
layers[idx],
self.layer_init_dim[idx+1] if i==0 else branch_channels[idx],
branch_channels[idx+1],
reduce_spatial_size=False if layer=='conv4' else True
))
idx += 1
# classifiers
# if branch_place == 'conv4' or branch_place == 'conv5':
idx = self.layer_list.index('conv4')-1
if branch_place != 'conv5':
branches[k].append(Conv1x1(base_channels[idx+1] if branch_place=='conv4' else branch_channels[idx] ,
branch_channels[idx]))
branches[k].append(nn.AdaptiveAvgPool2d(1))
branches[k].append(self._construct_fc_layer(branch_channels[idx],
branch_channels[idx], dropout_p=None))
else:
branches[k].append(nn.AdaptiveAvgPool2d(1))
branches[k].append(self._construct_fc_layer(branch_channels[idx],
base_channels[idx+1], dropout_p=None))
branches[k].append(nn.Linear(branch_channels[idx], branch_names[k]))
setattr(self, 'branch_'+k, nn.Sequential(*branches[k]))
'''# convs
for layer in self.layer_list[self.layer_list.index(branch_place)+1:]:
branches[k].append(copy.deepcopy(getattr(model, layer)))
branches[k][-1].load_state_dict(getattr(model, layer).state_dict())
# classifiers
branches[k].append(nn.Linear(self.attr_dim, branch_names[k]))
setattr(self, 'branch_'+k, nn.Sequential(*branches[k]))
self.layer_list.append('clf')'''
def _construct_fc_layer(self, fc_dims, input_dim, dropout_p=None):
if isinstance(fc_dims, int):
fc_dims = [fc_dims]
layers = []
for dim in fc_dims:
layers.append(nn.Linear(input_dim, dim))
layers.append(nn.BatchNorm1d(dim))
layers.append(nn.ReLU(inplace=True))
if dropout_p is not None:
layers.append(nn.Dropout(p=dropout_p))
input_dim = dim
return nn.Sequential(*layers)
def get_feature(self, x, get_attr=True, get_feature=True, method='both', get_collection=False):
out_baseline = self.out_layers_extractor(x, self.branch_place)
out_attributes = {}
for k in self.branch_fcs.keys():
out_attributes.setdefault(k, self.attr_branch(out_baseline if self.feat_indices == None else torch.index_select(out_baseline, 1, self.feat_indices[0]),
getattr(self,'branch_'+k),
need_feature = False)
)
out_baseline = self.out_layers_extractor(x, 'fc')
return out_attributes, out_baseline
def vector_features(self, x):
features = self.model(x)
out_attr = self.attr_lin(features)
out_features = torch.cat(features, out_attr, dim=1)
return out_features
def out_layers_extractor(self, x, layer):
out_os_layers = self.model.layer_extractor(x, layer)
return out_os_layers
def attr_branch(self, x, branch_layers, need_feature=False):
''' fc_layer should be a list of fully connecteds
clf_layer hould be a list of classifiers
'''
# handling conv layer
if self.branch_place != 'conv5':
start_point = self.layer_list.index(self.branch_place)
else:
start_point = self.layer_list.index('conv4')
for idx, layer in enumerate(branch_layers):
if need_feature and self.layer_list[start_point+idx+1] == 'clf':
features = x
attr = layer(features)
return features, attr
if layer == branch_layers[-2]:
x = x.view(x.size(0), -1)
x = layer(x)
return x
def forward(self, x, need_feature=False):
out_baseline = self.out_layers_extractor(x, self.branch_place)
out_attributes = {}
for k in self.branch_fcs.keys():
out_attributes.setdefault(k, self.attr_branch(out_baseline if self.feat_indices == None else torch.index_select(out_baseline, 1, self.feat_indices[0]),
getattr(self,'branch_'+k),
need_feature = need_feature)
)
return out_attributes
def save_baseline(self, saving_path):
torch.save(self.model.state_dict(), saving_path)
print('baseline model save to {}'.format(saving_path))