peterkros commited on
Commit
1d6f4fc
·
verified ·
1 Parent(s): 72e4293

Create wrapper.py

Browse files
Files changed (1) hide show
  1. src/models/backbones/wrapper.py +82 -0
src/models/backbones/wrapper.py ADDED
@@ -0,0 +1,82 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os
2
+ from functools import reduce
3
+
4
+ import torch
5
+ import torch.nn as nn
6
+
7
+ from .mobilenetv2 import MobileNetV2
8
+
9
+
10
+ class BaseBackbone(nn.Module):
11
+ """ Superclass of Replaceable Backbone Model for Semantic Estimation
12
+ """
13
+
14
+ def __init__(self, in_channels):
15
+ super(BaseBackbone, self).__init__()
16
+ self.in_channels = in_channels
17
+
18
+ self.model = None
19
+ self.enc_channels = []
20
+
21
+ def forward(self, x):
22
+ raise NotImplementedError
23
+
24
+ def load_pretrained_ckpt(self):
25
+ raise NotImplementedError
26
+
27
+
28
+ class MobileNetV2Backbone(BaseBackbone):
29
+ """ MobileNetV2 Backbone
30
+ """
31
+
32
+ def __init__(self, in_channels):
33
+ super(MobileNetV2Backbone, self).__init__(in_channels)
34
+
35
+ self.model = MobileNetV2(self.in_channels, alpha=1.0, expansion=6, num_classes=None)
36
+ self.enc_channels = [16, 24, 32, 96, 1280]
37
+
38
+ def forward(self, x):
39
+ # x = reduce(lambda x, n: self.model.features[n](x), list(range(0, 2)), x)
40
+ x = self.model.features[0](x)
41
+ x = self.model.features[1](x)
42
+ enc2x = x
43
+
44
+ # x = reduce(lambda x, n: self.model.features[n](x), list(range(2, 4)), x)
45
+ x = self.model.features[2](x)
46
+ x = self.model.features[3](x)
47
+ enc4x = x
48
+
49
+ # x = reduce(lambda x, n: self.model.features[n](x), list(range(4, 7)), x)
50
+ x = self.model.features[4](x)
51
+ x = self.model.features[5](x)
52
+ x = self.model.features[6](x)
53
+ enc8x = x
54
+
55
+ # x = reduce(lambda x, n: self.model.features[n](x), list(range(7, 14)), x)
56
+ x = self.model.features[7](x)
57
+ x = self.model.features[8](x)
58
+ x = self.model.features[9](x)
59
+ x = self.model.features[10](x)
60
+ x = self.model.features[11](x)
61
+ x = self.model.features[12](x)
62
+ x = self.model.features[13](x)
63
+ enc16x = x
64
+
65
+ # x = reduce(lambda x, n: self.model.features[n](x), list(range(14, 19)), x)
66
+ x = self.model.features[14](x)
67
+ x = self.model.features[15](x)
68
+ x = self.model.features[16](x)
69
+ x = self.model.features[17](x)
70
+ x = self.model.features[18](x)
71
+ enc32x = x
72
+ return [enc2x, enc4x, enc8x, enc16x, enc32x]
73
+
74
+ def load_pretrained_ckpt(self):
75
+ # the pre-trained model is provided by https://github.com/thuyngch/Human-Segmentation-PyTorch
76
+ ckpt_path = './pretrained/mobilenetv2_human_seg.ckpt'
77
+ if not os.path.exists(ckpt_path):
78
+ print('cannot find the pretrained mobilenetv2 backbone')
79
+ exit()
80
+
81
+ ckpt = torch.load(ckpt_path)
82
+ self.model.load_state_dict(ckpt)