Register
Login
Resources
Docs Blog Datasets Glossary Case Studies Tutorials & Webinars
Product
Data Engine LLMs Platform Enterprise
Pricing Explore
Connect to our Discord channel

model.py 8.4 KB

You have to be logged in to leave a comment. Sign In
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
  1. import torch
  2. from torch import nn
  3. from torch.nn import init
  4. import torch.nn.functional as F
  5. import math
  6. from torch.autograd import Variable
  7. import numpy as np
  8. from resnet import resnet50
  9. from vgg import vgg16
  10. config_vgg = {'convert': [[128,256,512,512,512],[64,128,256,512,512]], 'merge1': [[128, 256, 128, 3,1], [256, 512, 256, 3, 1], [512, 0, 512, 5, 2], [512, 0, 512, 5, 2],[512, 0, 512, 7, 3]], 'merge2': [[128], [256, 512, 512, 512]]} # no convert layer, no conv6
  11. config_resnet = {'convert': [[64,256,512,1024,2048],[128,256,512,512,512]], 'deep_pool': [[512, 512, 256, 256, 128], [512, 256, 256, 128, 128], [False, True, True, True, False], [True, True, True, True, False]], 'score': 256, 'edgeinfo':[[16, 16, 16, 16], 128, [16,8,4,2]],'edgeinfoc':[64,128], 'block': [[512, [16]], [256, [16]], [256, [16]], [128, [16]]], 'fuse': [[16, 16, 16, 16], True], 'fuse_ratio': [[16,1], [8,1], [4,1], [2,1]], 'merge1': [[128, 256, 128, 3,1], [256, 512, 256, 3, 1], [512, 0, 512, 5, 2], [512, 0, 512, 5, 2],[512, 0, 512, 7, 3]], 'merge2': [[128], [256, 512, 512, 512]]}
  12. class ConvertLayer(nn.Module):
  13. def __init__(self, list_k):
  14. super(ConvertLayer, self).__init__()
  15. up0, up1, up2 = [], [], []
  16. for i in range(len(list_k[0])):
  17. up0.append(nn.Sequential(nn.Conv2d(list_k[0][i], list_k[1][i], 1, 1, bias=False), nn.ReLU(inplace=True)))
  18. self.convert0 = nn.ModuleList(up0)
  19. def forward(self, list_x):
  20. resl = []
  21. for i in range(len(list_x)):
  22. resl.append(self.convert0[i](list_x[i]))
  23. return resl
  24. class MergeLayer1(nn.Module): # list_k: [[64, 512, 64], [128, 512, 128], [256, 0, 256] ... ]
  25. def __init__(self, list_k):
  26. super(MergeLayer1, self).__init__()
  27. self.list_k = list_k
  28. trans, up, score = [], [], []
  29. for ik in list_k:
  30. if ik[1] > 0:
  31. trans.append(nn.Sequential(nn.Conv2d(ik[1], ik[0], 1, 1, bias=False), nn.ReLU(inplace=True)))
  32. up.append(nn.Sequential(nn.Conv2d(ik[0], ik[2], ik[3], 1, ik[4]), nn.ReLU(inplace=True), nn.Conv2d(ik[2], ik[2], ik[3], 1, ik[4]), nn.ReLU(inplace=True), nn.Conv2d(ik[2], ik[2], ik[3], 1, ik[4]), nn.ReLU(inplace=True)))
  33. score.append(nn.Conv2d(ik[2], 1, 3, 1, 1))
  34. trans.append(nn.Sequential(nn.Conv2d(512, 128, 1, 1, bias=False), nn.ReLU(inplace=True)))
  35. self.trans, self.up, self.score = nn.ModuleList(trans), nn.ModuleList(up), nn.ModuleList(score)
  36. self.relu =nn.ReLU()
  37. def forward(self, list_x, x_size):
  38. up_edge, up_sal, edge_feature, sal_feature = [], [], [], []
  39. num_f = len(list_x)
  40. tmp = self.up[num_f - 1](list_x[num_f-1])
  41. sal_feature.append(tmp)
  42. U_tmp = tmp
  43. up_sal.append(F.interpolate(self.score[num_f - 1](tmp), x_size, mode='bilinear', align_corners=True))
  44. for j in range(2, num_f ):
  45. i = num_f - j
  46. if list_x[i].size()[1] < U_tmp.size()[1]:
  47. U_tmp = list_x[i] + F.interpolate((self.trans[i](U_tmp)), list_x[i].size()[2:], mode='bilinear', align_corners=True)
  48. else:
  49. U_tmp = list_x[i] + F.interpolate((U_tmp), list_x[i].size()[2:], mode='bilinear', align_corners=True)
  50. tmp = self.up[i](U_tmp)
  51. U_tmp = tmp
  52. sal_feature.append(tmp)
  53. up_sal.append(F.interpolate(self.score[i](tmp), x_size, mode='bilinear', align_corners=True))
  54. U_tmp = list_x[0] + F.interpolate((self.trans[-1](sal_feature[0])), list_x[0].size()[2:], mode='bilinear', align_corners=True)
  55. tmp = self.up[0](U_tmp)
  56. edge_feature.append(tmp)
  57. up_edge.append(F.interpolate(self.score[0](tmp), x_size, mode='bilinear', align_corners=True))
  58. return up_edge, edge_feature, up_sal, sal_feature
  59. class MergeLayer2(nn.Module):
  60. def __init__(self, list_k):
  61. super(MergeLayer2, self).__init__()
  62. self.list_k = list_k
  63. trans, up, score = [], [], []
  64. for i in list_k[0]:
  65. tmp = []
  66. tmp_up = []
  67. tmp_score = []
  68. feature_k = [[3,1],[5,2], [5,2], [7,3]]
  69. for idx, j in enumerate(list_k[1]):
  70. tmp.append(nn.Sequential(nn.Conv2d(j, i, 1, 1, bias=False), nn.ReLU(inplace=True)))
  71. tmp_up.append(nn.Sequential(nn.Conv2d(i , i, feature_k[idx][0], 1, feature_k[idx][1]), nn.ReLU(inplace=True), nn.Conv2d(i, i, feature_k[idx][0],1 , feature_k[idx][1]), nn.ReLU(inplace=True), nn.Conv2d(i, i, feature_k[idx][0], 1, feature_k[idx][1]), nn.ReLU(inplace=True)))
  72. tmp_score.append(nn.Conv2d(i, 1, 3, 1, 1))
  73. trans.append(nn.ModuleList(tmp))
  74. up.append(nn.ModuleList(tmp_up))
  75. score.append(nn.ModuleList(tmp_score))
  76. self.trans, self.up, self.score = nn.ModuleList(trans), nn.ModuleList(up), nn.ModuleList(score)
  77. self.final_score = nn.Sequential(nn.Conv2d(list_k[0][0], list_k[0][0], 5, 1, 2), nn.ReLU(inplace=True), nn.Conv2d(list_k[0][0], 1, 3, 1, 1))
  78. self.relu =nn.ReLU()
  79. def forward(self, list_x, list_y, x_size):
  80. up_score, tmp_feature = [], []
  81. list_y = list_y[::-1]
  82. for i, i_x in enumerate(list_x):
  83. for j, j_x in enumerate(list_y):
  84. tmp = F.interpolate(self.trans[i][j](j_x), i_x.size()[2:], mode='bilinear', align_corners=True) + i_x
  85. tmp_f = self.up[i][j](tmp)
  86. up_score.append(F.interpolate(self.score[i][j](tmp_f), x_size, mode='bilinear', align_corners=True))
  87. tmp_feature.append(tmp_f)
  88. tmp_fea = tmp_feature[0]
  89. for i_fea in range(len(tmp_feature) - 1):
  90. tmp_fea = self.relu(torch.add(tmp_fea, F.interpolate((tmp_feature[i_fea+1]), tmp_feature[0].size()[2:], mode='bilinear', align_corners=True)))
  91. up_score.append(F.interpolate(self.final_score(tmp_fea), x_size, mode='bilinear', align_corners=True))
  92. return up_score
  93. # extra part
  94. def extra_layer(base_model_cfg, vgg):
  95. if base_model_cfg == 'vgg':
  96. config = config_vgg
  97. elif base_model_cfg == 'resnet':
  98. config = config_resnet
  99. merge1_layers = MergeLayer1(config['merge1'])
  100. merge2_layers = MergeLayer2(config['merge2'])
  101. return vgg, merge1_layers, merge2_layers
  102. # TUN network
  103. class TUN_bone(nn.Module):
  104. def __init__(self, base_model_cfg, base, merge1_layers, merge2_layers):
  105. super(TUN_bone, self).__init__()
  106. self.base_model_cfg = base_model_cfg
  107. if self.base_model_cfg == 'vgg':
  108. self.base = base
  109. # self.base_ex = nn.ModuleList(base_ex)
  110. self.merge1 = merge1_layers
  111. self.merge2 = merge2_layers
  112. elif self.base_model_cfg == 'resnet':
  113. self.convert = ConvertLayer(config_resnet['convert'])
  114. self.base = base
  115. self.merge1 = merge1_layers
  116. self.merge2 = merge2_layers
  117. def forward(self, x):
  118. x_size = x.size()[2:]
  119. conv2merge = self.base(x)
  120. if self.base_model_cfg == 'resnet':
  121. conv2merge = self.convert(conv2merge)
  122. up_edge, edge_feature, up_sal, sal_feature = self.merge1(conv2merge, x_size)
  123. up_sal_final = self.merge2(edge_feature, sal_feature, x_size)
  124. return up_edge, up_sal, up_sal_final
  125. # build the whole network
  126. def build_model(base_model_cfg='vgg'):
  127. if base_model_cfg == 'vgg':
  128. return TUN_bone(base_model_cfg, *extra_layer(base_model_cfg, vgg16()))
  129. elif base_model_cfg == 'resnet':
  130. return TUN_bone(base_model_cfg, *extra_layer(base_model_cfg, resnet50()))
  131. # weight init
  132. def xavier(param):
  133. # init.xavier_uniform(param)
  134. init.xavier_uniform_(param)
  135. def weights_init(m):
  136. if isinstance(m, nn.Conv2d):
  137. # xavier(m.weight.data)
  138. m.weight.data.normal_(0, 0.01)
  139. if m.bias is not None:
  140. m.bias.data.zero_()
  141. if __name__ == '__main__':
  142. from torch.autograd import Variable
  143. net = TUN(*extra_layer(vgg(base['tun'], 3), vgg(base['tun_ex'], 512), config['merge_block'], config['fuse'])).cuda()
  144. img = Variable(torch.randn((1, 3, 256, 256))).cuda()
  145. out = net(img, mode = 2)
  146. print(len(out))
  147. print(len(out[0]))
  148. print(out[0].shape)
  149. print(len(out[1]))
  150. # print(net)
  151. input('Press Any to Continue...')
Tip!

Press p or to see the previous file or, n or to see the next file

Comments

Loading...