inceptionv4.py 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442
  1. import torch
  2. import torch.nn as nn
  3. import torch.utils.model_zoo as model_zoo
  4. import os
  5. import sys
  6. model_urls = {
  7. 'imagenet': 'https://s3.amazonaws.com/pytorch/models/inceptionv4-58153ba9.pth'
  8. }
  9. class BasicConv2d(nn.Module):
  10. def __init__(self, in_planes, out_planes, kernel_size, stride, padding=0):
  11. super(BasicConv2d, self).__init__()
  12. self.conv = nn.Conv2d(in_planes, out_planes, kernel_size=kernel_size, stride=stride, padding=padding, bias=False) # verify bias false
  13. self.bn = nn.BatchNorm2d(out_planes)
  14. self.relu = nn.ReLU(inplace=True)
  15. def forward(self, x):
  16. x = self.conv(x)
  17. x = self.bn(x)
  18. x = self.relu(x)
  19. return x
  20. class Mixed_3a(nn.Module):
  21. def __init__(self):
  22. super(Mixed_3a, self).__init__()
  23. self.maxpool = nn.MaxPool2d(3, stride=2)
  24. self.conv = BasicConv2d(64, 96, kernel_size=3, stride=2)
  25. def forward(self, x):
  26. x0 = self.maxpool(x)
  27. x1 = self.conv(x)
  28. out = torch.cat((x0, x1), 1)
  29. return out
  30. class Mixed_4a(nn.Module):
  31. def __init__(self):
  32. super(Mixed_4a, self).__init__()
  33. self.block0 = nn.Sequential(
  34. BasicConv2d(160, 64, kernel_size=1, stride=1),
  35. BasicConv2d(64, 96, kernel_size=3, stride=1)
  36. )
  37. self.block1 = nn.Sequential(
  38. BasicConv2d(160, 64, kernel_size=1, stride=1),
  39. BasicConv2d(64, 64, kernel_size=(1,7), stride=1, padding=(0,3)),
  40. BasicConv2d(64, 64, kernel_size=(7,1), stride=1, padding=(3,0)),
  41. BasicConv2d(64, 96, kernel_size=(3,3), stride=1)
  42. )
  43. def forward(self, x):
  44. x0 = self.block0(x)
  45. x1 = self.block1(x)
  46. out = torch.cat((x0, x1), 1)
  47. return out
  48. class Mixed_5a(nn.Module):
  49. def __init__(self):
  50. super(Mixed_5a, self).__init__()
  51. self.conv = BasicConv2d(192, 192, kernel_size=3, stride=2)
  52. self.maxpool = nn.MaxPool2d(3, stride=2)
  53. def forward(self, x):
  54. x0 = self.conv(x)
  55. x1 = self.maxpool(x)
  56. out = torch.cat((x0, x1), 1)
  57. return out
  58. class Inception_A(nn.Module):
  59. def __init__(self):
  60. super(Inception_A, self).__init__()
  61. self.block0 = BasicConv2d(384, 96, kernel_size=1, stride=1)
  62. self.block1 = nn.Sequential(
  63. BasicConv2d(384, 64, kernel_size=1, stride=1),
  64. BasicConv2d(64, 96, kernel_size=3, stride=1, padding=1)
  65. )
  66. self.block2 = nn.Sequential(
  67. BasicConv2d(384, 64, kernel_size=1, stride=1),
  68. BasicConv2d(64, 96, kernel_size=3, stride=1, padding=1),
  69. BasicConv2d(96, 96, kernel_size=3, stride=1, padding=1)
  70. )
  71. self.block3 = nn.Sequential(
  72. nn.AvgPool2d(3, stride=1, padding=1, count_include_pad=False),
  73. BasicConv2d(384, 96, kernel_size=1, stride=1)
  74. )
  75. def forward(self, x):
  76. x0 = self.block0(x)
  77. x1 = self.block1(x)
  78. x2 = self.block2(x)
  79. x3 = self.block3(x)
  80. out = torch.cat((x0, x1, x2, x3), 1)
  81. return out
  82. class Reduction_A(nn.Module):
  83. def __init__(self):
  84. super(Reduction_A, self).__init__()
  85. self.block0 = BasicConv2d(384, 384, kernel_size=3, stride=2)
  86. self.block1 = nn.Sequential(
  87. BasicConv2d(384, 192, kernel_size=1, stride=1),
  88. BasicConv2d(192, 224, kernel_size=3, stride=1, padding=1),
  89. BasicConv2d(224, 256, kernel_size=3, stride=2)
  90. )
  91. self.block2 = nn.MaxPool2d(3, stride=2)
  92. def forward(self, x):
  93. x0 = self.block0(x)
  94. x1 = self.block1(x)
  95. x2 = self.block2(x)
  96. out = torch.cat((x0, x1, x2), 1)
  97. return out
  98. class Inception_B(nn.Module):
  99. def __init__(self):
  100. super(Inception_B, self).__init__()
  101. self.block0 = BasicConv2d(1024, 384, kernel_size=1, stride=1)
  102. self.block1 = nn.Sequential(
  103. BasicConv2d(1024, 192, kernel_size=1, stride=1),
  104. BasicConv2d(192, 224, kernel_size=(1,7), stride=1, padding=(0,3)),
  105. BasicConv2d(224, 256, kernel_size=(7,1), stride=1, padding=(3,0))
  106. )
  107. self.block2 = nn.Sequential(
  108. BasicConv2d(1024, 192, kernel_size=1, stride=1),
  109. BasicConv2d(192, 192, kernel_size=(7,1), stride=1, padding=(3,0)),
  110. BasicConv2d(192, 224, kernel_size=(1,7), stride=1, padding=(0,3)),
  111. BasicConv2d(224, 224, kernel_size=(7,1), stride=1, padding=(3,0)),
  112. BasicConv2d(224, 256, kernel_size=(1,7), stride=1, padding=(0,3))
  113. )
  114. self.block3 = nn.Sequential(
  115. nn.AvgPool2d(3, stride=1, padding=1, count_include_pad=False),
  116. BasicConv2d(1024, 128, kernel_size=1, stride=1)
  117. )
  118. def forward(self, x):
  119. x0 = self.block0(x)
  120. x1 = self.block1(x)
  121. x2 = self.block2(x)
  122. x3 = self.block3(x)
  123. out = torch.cat((x0, x1, x2, x3), 1)
  124. return out
  125. class Reduction_B(nn.Module):
  126. def __init__(self):
  127. super(Reduction_B, self).__init__()
  128. self.block0 = nn.Sequential(
  129. BasicConv2d(1024, 192, kernel_size=1, stride=1),
  130. BasicConv2d(192, 192, kernel_size=3, stride=2)
  131. )
  132. self.block1 = nn.Sequential(
  133. BasicConv2d(1024, 256, kernel_size=1, stride=1),
  134. BasicConv2d(256, 256, kernel_size=(1,7), stride=1, padding=(0,3)),
  135. BasicConv2d(256, 320, kernel_size=(7,1), stride=1, padding=(3,0)),
  136. BasicConv2d(320, 320, kernel_size=3, stride=2)
  137. )
  138. self.block2 = nn.MaxPool2d(3, stride=2)
  139. def forward(self, x):
  140. x0 = self.block0(x)
  141. x1 = self.block1(x)
  142. x2 = self.block2(x)
  143. out = torch.cat((x0, x1, x2), 1)
  144. return out
  145. class Inception_C(nn.Module):
  146. def __init__(self):
  147. super(Inception_C, self).__init__()
  148. self.block0 = BasicConv2d(1536, 256, kernel_size=1, stride=1)
  149. self.block1_0 = BasicConv2d(1536, 384, kernel_size=1, stride=1)
  150. self.block1_1a = BasicConv2d(384, 256, kernel_size=(1,3), stride=1, padding=(0,1))
  151. self.block1_1b = BasicConv2d(384, 256, kernel_size=(3,1), stride=1, padding=(1,0))
  152. self.block2_0 = BasicConv2d(1536, 384, kernel_size=1, stride=1)
  153. self.block2_1 = BasicConv2d(384, 448, kernel_size=(3,1), stride=1, padding=(1,0))
  154. self.block2_2 = BasicConv2d(448, 512, kernel_size=(1,3), stride=1, padding=(0,1))
  155. self.block2_3a = BasicConv2d(512, 256, kernel_size=(1,3), stride=1, padding=(0,1))
  156. self.block2_3b = BasicConv2d(512, 256, kernel_size=(3,1), stride=1, padding=(1,0))
  157. self.block3 = nn.Sequential(
  158. nn.AvgPool2d(3, stride=1, padding=1, count_include_pad=False),
  159. BasicConv2d(1536, 256, kernel_size=1, stride=1)
  160. )
  161. def forward(self, x):
  162. x0 = self.block0(x)
  163. x1_0 = self.block1_0(x)
  164. x1_1a = self.block1_1a(x1_0)
  165. x1_1b = self.block1_1b(x1_0)
  166. x1 = torch.cat((x1_1a, x1_1b), 1)
  167. x2_0 = self.block2_0(x)
  168. x2_1 = self.block2_1(x2_0)
  169. x2_2 = self.block2_2(x2_1)
  170. x2_3a = self.block2_3a(x2_2)
  171. x2_3b = self.block2_3b(x2_2)
  172. x2 = torch.cat((x2_3a, x2_3b), 1)
  173. x3 = self.block3(x)
  174. out = torch.cat((x0, x1, x2, x3), 1)
  175. return out
  176. class InceptionV4(nn.Module):
  177. def __init__(self, num_classes=1001):
  178. super(InceptionV4, self).__init__()
  179. self.features = nn.Sequential(
  180. BasicConv2d(3, 32, kernel_size=3, stride=2),
  181. BasicConv2d(32, 32, kernel_size=3, stride=1),
  182. BasicConv2d(32, 64, kernel_size=3, stride=1, padding=1),
  183. Mixed_3a(),
  184. Mixed_4a(),
  185. Mixed_5a(),
  186. Inception_A(),
  187. Inception_A(),
  188. Inception_A(),
  189. Inception_A(),
  190. Reduction_A(), # Mixed_6a
  191. Inception_B(),
  192. Inception_B(),
  193. Inception_B(),
  194. Inception_B(),
  195. Inception_B(),
  196. Inception_B(),
  197. Inception_B(),
  198. Reduction_B(), # Mixed_7a
  199. Inception_C(),
  200. Inception_C(),
  201. Inception_C(),
  202. nn.AdaptiveAvgPool2d((1,1))
  203. )
  204. self.classif = nn.Linear(1536, num_classes)
  205. def forward(self, x):
  206. x = self.features(x)
  207. x = x.view(x.size(0), -1)
  208. x = self.classif(x)
  209. return x
  210. def inceptionv4(pretrained=True):
  211. r"""InceptionV4 model architecture from the
  212. `"Inception-v4, Inception-ResNet..." <https://arxiv.org/abs/1602.07261>`_ paper.
  213. Args:
  214. pretrained (bool): If True, returns a model pre-trained on ImageNet
  215. """
  216. model = InceptionV4()
  217. if pretrained:
  218. model.load_state_dict(model_zoo.load_url(model_urls['imagenet']))
  219. return model
  220. ######################################################################
  221. ## Load parameters from HDF5 to Dict
  222. ######################################################################
  223. def load_conv2d(state_dict, name_pth, name_tf):
  224. h5f = h5py.File('dump/InceptionV4/'+name_tf+'.h5', 'r')
  225. state_dict[name_pth+'.conv.weight'] = torch.from_numpy(h5f['weights'][()]).permute(3, 2, 0, 1)
  226. out_planes = state_dict[name_pth+'.conv.weight'].size(0)
  227. state_dict[name_pth+'.bn.weight'] = torch.ones(out_planes)
  228. state_dict[name_pth+'.bn.bias'] = torch.from_numpy(h5f['beta'][()])
  229. state_dict[name_pth+'.bn.running_mean'] = torch.from_numpy(h5f['mean'][()])
  230. state_dict[name_pth+'.bn.running_var'] = torch.from_numpy(h5f['var'][()])
  231. h5f.close()
  232. def load_linear(state_dict, name_pth, name_tf):
  233. h5f = h5py.File('dump/InceptionV4/'+name_tf+'.h5', 'r')
  234. state_dict[name_pth+'.weight'] = torch.from_numpy(h5f['weights'][()]).t()
  235. state_dict[name_pth+'.bias'] = torch.from_numpy(h5f['biases'][()])
  236. h5f.close()
  237. def load_mixed_4a_7a(state_dict, name_pth, name_tf):
  238. load_conv2d(state_dict, name_pth+'.branch0.0', name_tf+'/Branch_0/Conv2d_0a_1x1')
  239. load_conv2d(state_dict, name_pth+'.branch0.1', name_tf+'/Branch_0/Conv2d_1a_3x3')
  240. load_conv2d(state_dict, name_pth+'.branch1.0', name_tf+'/Branch_1/Conv2d_0a_1x1')
  241. load_conv2d(state_dict, name_pth+'.branch1.1', name_tf+'/Branch_1/Conv2d_0b_1x7')
  242. load_conv2d(state_dict, name_pth+'.branch1.2', name_tf+'/Branch_1/Conv2d_0c_7x1')
  243. load_conv2d(state_dict, name_pth+'.branch1.3', name_tf+'/Branch_1/Conv2d_1a_3x3')
  244. def load_mixed_5(state_dict, name_pth, name_tf):
  245. load_conv2d(state_dict, name_pth+'.branch0', name_tf+'/Branch_0/Conv2d_0a_1x1')
  246. load_conv2d(state_dict, name_pth+'.branch1.0', name_tf+'/Branch_1/Conv2d_0a_1x1')
  247. load_conv2d(state_dict, name_pth+'.branch1.1', name_tf+'/Branch_1/Conv2d_0b_3x3')
  248. load_conv2d(state_dict, name_pth+'.branch2.0', name_tf+'/Branch_2/Conv2d_0a_1x1')
  249. load_conv2d(state_dict, name_pth+'.branch2.1', name_tf+'/Branch_2/Conv2d_0b_3x3')
  250. load_conv2d(state_dict, name_pth+'.branch2.2', name_tf+'/Branch_2/Conv2d_0c_3x3')
  251. load_conv2d(state_dict, name_pth+'.branch3.1', name_tf+'/Branch_3/Conv2d_0b_1x1')
  252. def load_mixed_6(state_dict, name_pth, name_tf):
  253. load_conv2d(state_dict, name_pth+'.branch0', name_tf+'/Branch_0/Conv2d_0a_1x1')
  254. load_conv2d(state_dict, name_pth+'.branch1.0', name_tf+'/Branch_1/Conv2d_0a_1x1')
  255. load_conv2d(state_dict, name_pth+'.branch1.1', name_tf+'/Branch_1/Conv2d_0b_1x7')
  256. load_conv2d(state_dict, name_pth+'.branch1.2', name_tf+'/Branch_1/Conv2d_0c_7x1')
  257. load_conv2d(state_dict, name_pth+'.branch2.0', name_tf+'/Branch_2/Conv2d_0a_1x1')
  258. load_conv2d(state_dict, name_pth+'.branch2.1', name_tf+'/Branch_2/Conv2d_0b_7x1')
  259. load_conv2d(state_dict, name_pth+'.branch2.2', name_tf+'/Branch_2/Conv2d_0c_1x7')
  260. load_conv2d(state_dict, name_pth+'.branch2.3', name_tf+'/Branch_2/Conv2d_0d_7x1')
  261. load_conv2d(state_dict, name_pth+'.branch2.4', name_tf+'/Branch_2/Conv2d_0e_1x7')
  262. load_conv2d(state_dict, name_pth+'.branch3.1', name_tf+'/Branch_3/Conv2d_0b_1x1')
  263. def load_mixed_7(state_dict, name_pth, name_tf):
  264. load_conv2d(state_dict, name_pth+'.branch0', name_tf+'/Branch_0/Conv2d_0a_1x1')
  265. load_conv2d(state_dict, name_pth+'.branch1_0', name_tf+'/Branch_1/Conv2d_0a_1x1')
  266. load_conv2d(state_dict, name_pth+'.branch1_1a', name_tf+'/Branch_1/Conv2d_0b_1x3')
  267. load_conv2d(state_dict, name_pth+'.branch1_1b', name_tf+'/Branch_1/Conv2d_0c_3x1')
  268. load_conv2d(state_dict, name_pth+'.branch2_0', name_tf+'/Branch_2/Conv2d_0a_1x1')
  269. load_conv2d(state_dict, name_pth+'.branch2_1', name_tf+'/Branch_2/Conv2d_0b_3x1')
  270. load_conv2d(state_dict, name_pth+'.branch2_2', name_tf+'/Branch_2/Conv2d_0c_1x3')
  271. load_conv2d(state_dict, name_pth+'.branch2_3a', name_tf+'/Branch_2/Conv2d_0d_1x3')
  272. load_conv2d(state_dict, name_pth+'.branch2_3b', name_tf+'/Branch_2/Conv2d_0e_3x1')
  273. load_conv2d(state_dict, name_pth+'.branch3.1', name_tf+'/Branch_3/Conv2d_0b_1x1')
  274. def load():
  275. state_dict={}
  276. load_conv2d(state_dict, name_pth='features.0', name_tf='Conv2d_1a_3x3')
  277. load_conv2d(state_dict, name_pth='features.1', name_tf='Conv2d_2a_3x3')
  278. load_conv2d(state_dict, name_pth='features.2', name_tf='Conv2d_2b_3x3')
  279. load_conv2d(state_dict, name_pth='features.3.conv', name_tf='Mixed_3a/Branch_1/Conv2d_0a_3x3')
  280. load_mixed_4a_7a(state_dict, name_pth='features.4', name_tf='Mixed_4a')
  281. load_conv2d(state_dict, name_pth='features.5.conv', name_tf='Mixed_5a/Branch_0/Conv2d_1a_3x3')
  282. load_mixed_5(state_dict, name_pth='features.6', name_tf='Mixed_5b')
  283. load_mixed_5(state_dict, name_pth='features.7', name_tf='Mixed_5c')
  284. load_mixed_5(state_dict, name_pth='features.8', name_tf='Mixed_5d')
  285. load_mixed_5(state_dict, name_pth='features.9', name_tf='Mixed_5e')
  286. load_conv2d(state_dict, name_pth='features.10.branch0', name_tf='Mixed_6a/Branch_0/Conv2d_1a_3x3')
  287. load_conv2d(state_dict, name_pth='features.10.branch1.0', name_tf='Mixed_6a/Branch_1/Conv2d_0a_1x1')
  288. load_conv2d(state_dict, name_pth='features.10.branch1.1', name_tf='Mixed_6a/Branch_1/Conv2d_0b_3x3')
  289. load_conv2d(state_dict, name_pth='features.10.branch1.2', name_tf='Mixed_6a/Branch_1/Conv2d_1a_3x3')
  290. load_mixed_6(state_dict, name_pth='features.11', name_tf='Mixed_6b')
  291. load_mixed_6(state_dict, name_pth='features.12', name_tf='Mixed_6c')
  292. load_mixed_6(state_dict, name_pth='features.13', name_tf='Mixed_6d')
  293. load_mixed_6(state_dict, name_pth='features.14', name_tf='Mixed_6e')
  294. load_mixed_6(state_dict, name_pth='features.15', name_tf='Mixed_6f')
  295. load_mixed_6(state_dict, name_pth='features.16', name_tf='Mixed_6g')
  296. load_mixed_6(state_dict, name_pth='features.17', name_tf='Mixed_6h')
  297. load_mixed_4a_7a(state_dict, name_pth='features.18', name_tf='Mixed_7a')
  298. load_mixed_7(state_dict, name_pth='features.19', name_tf='Mixed_7b')
  299. load_mixed_7(state_dict, name_pth='features.20', name_tf='Mixed_7c')
  300. load_mixed_7(state_dict, name_pth='features.21', name_tf='Mixed_7d')
  301. load_linear(state_dict, name_pth='classif', name_tf='Logits')
  302. return state_dict
  303. ######################################################################
  304. ## Test
  305. ######################################################################
  306. def test(model):
  307. model.eval()
  308. from scipy import misc
  309. img = misc.imread('lena_299.png')
  310. inputs = torch.zeros(1,299,299,3)
  311. inputs[0] = torch.from_numpy(img)
  312. inputs.transpose_(1,3)
  313. inputs.transpose_(2,3)
  314. # 1, 3, 299, 299
  315. outputs = model.forward(torch.autograd.Variable(inputs))
  316. h5f = h5py.File('dump/InceptionV4/Logits.h5', 'r')
  317. outputs_tf = torch.from_numpy(h5f['out'][()])
  318. h5f.close()
  319. outputs = torch.nn.functional.softmax(outputs)
  320. print(torch.dist(outputs.data, outputs_tf))
  321. return outputs
  322. def test_conv2d(module, name):
  323. #global output_tf
  324. h5f = h5py.File('dump/InceptionV4/'+name+'.h5', 'r')
  325. output_tf = torch.from_numpy(h5f['relu_out'][()])
  326. output_tf.transpose_(1,3)
  327. output_tf.transpose_(2,3)
  328. h5f.close()
  329. def test_dist(self, input, output):
  330. print(name, torch.dist(output.data, output_tf))
  331. module.register_forward_hook(test_dist)
  332. def test_mixed_4a_7a(module, name):
  333. test_conv2d(module.branch0[0], name+'/Branch_0/Conv2d_0a_1x1')
  334. test_conv2d(module.branch0[1], name+'/Branch_0/Conv2d_1a_3x3')
  335. test_conv2d(module.branch1[0], name+'/Branch_1/Conv2d_0a_1x1')
  336. test_conv2d(module.branch1[1], name+'/Branch_1/Conv2d_0b_1x7')
  337. test_conv2d(module.branch1[2], name+'/Branch_1/Conv2d_0c_7x1')
  338. test_conv2d(module.branch1[3], name+'/Branch_1/Conv2d_1a_3x3')
  339. ######################################################################
  340. ## Main
  341. ######################################################################
  342. if __name__ == "__main__":
  343. import h5py
  344. model = InceptionV4()
  345. state_dict = load()
  346. model.load_state_dict(state_dict)
  347. # test_conv2d(model.features[0], 'Conv2d_1a_3x3')
  348. # test_conv2d(model.features[1], 'Conv2d_2a_3x3')
  349. # test_conv2d(model.features[2], 'Conv2d_2b_3x3')
  350. # test_conv2d(model.features[3].conv, 'Mixed_3a/Branch_1/Conv2d_0a_3x3')
  351. # test_mixed_4a_7a(model.features[4], 'Mixed_4a')
  352. os.system('mkdir -p save')
  353. torch.save(model, 'save/inceptionv4.pth')
  354. torch.save(state_dict, 'save/inceptionv4_state.pth')
  355. outputs = test(model)