inceptionresnetv2.py 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358
  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': 'http://data.lip6.fr/cadene/pretrainedmodels/inceptionresnetv2-520b38e4.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,
  13. kernel_size=kernel_size, stride=stride,
  14. padding=padding, bias=False) # verify bias false
  15. self.bn = nn.BatchNorm2d(out_planes,
  16. eps=0.001, # value found in tensorflow
  17. momentum=0.1, # default pytorch value
  18. affine=True)
  19. self.relu = nn.ReLU(inplace=False)
  20. def forward(self, x):
  21. x = self.conv(x)
  22. x = self.bn(x)
  23. x = self.relu(x)
  24. return x
  25. class Mixed_5b(nn.Module):
  26. def __init__(self):
  27. super(Mixed_5b, self).__init__()
  28. self.branch0 = BasicConv2d(192, 96, kernel_size=1, stride=1)
  29. self.branch1 = nn.Sequential(
  30. BasicConv2d(192, 48, kernel_size=1, stride=1),
  31. BasicConv2d(48, 64, kernel_size=5, stride=1, padding=2)
  32. )
  33. self.branch2 = nn.Sequential(
  34. BasicConv2d(192, 64, kernel_size=1, stride=1),
  35. BasicConv2d(64, 96, kernel_size=3, stride=1, padding=1),
  36. BasicConv2d(96, 96, kernel_size=3, stride=1, padding=1)
  37. )
  38. self.branch3 = nn.Sequential(
  39. nn.AvgPool2d(3, stride=1, padding=1, count_include_pad=False),
  40. BasicConv2d(192, 64, kernel_size=1, stride=1)
  41. )
  42. def forward(self, x):
  43. x0 = self.branch0(x)
  44. x1 = self.branch1(x)
  45. x2 = self.branch2(x)
  46. x3 = self.branch3(x)
  47. out = torch.cat((x0, x1, x2, x3), 1)
  48. return out
  49. class Block35(nn.Module):
  50. def __init__(self, scale=1.0):
  51. super(Block35, self).__init__()
  52. self.scale = scale
  53. self.branch0 = BasicConv2d(320, 32, kernel_size=1, stride=1)
  54. self.branch1 = nn.Sequential(
  55. BasicConv2d(320, 32, kernel_size=1, stride=1),
  56. BasicConv2d(32, 32, kernel_size=3, stride=1, padding=1)
  57. )
  58. self.branch2 = nn.Sequential(
  59. BasicConv2d(320, 32, kernel_size=1, stride=1),
  60. BasicConv2d(32, 48, kernel_size=3, stride=1, padding=1),
  61. BasicConv2d(48, 64, kernel_size=3, stride=1, padding=1)
  62. )
  63. self.conv2d = nn.Conv2d(128, 320, kernel_size=1, stride=1)
  64. self.relu = nn.ReLU(inplace=False)
  65. def forward(self, x):
  66. x0 = self.branch0(x)
  67. x1 = self.branch1(x)
  68. x2 = self.branch2(x)
  69. out = torch.cat((x0, x1, x2), 1)
  70. out = self.conv2d(out)
  71. out = out * self.scale + x
  72. out = self.relu(out)
  73. return out
  74. class Mixed_6a(nn.Module):
  75. def __init__(self):
  76. super(Mixed_6a, self).__init__()
  77. self.branch0 = BasicConv2d(320, 384, kernel_size=3, stride=2)
  78. self.branch1 = nn.Sequential(
  79. BasicConv2d(320, 256, kernel_size=1, stride=1),
  80. BasicConv2d(256, 256, kernel_size=3, stride=1, padding=1),
  81. BasicConv2d(256, 384, kernel_size=3, stride=2)
  82. )
  83. self.branch2 = nn.MaxPool2d(3, stride=2)
  84. def forward(self, x):
  85. x0 = self.branch0(x)
  86. x1 = self.branch1(x)
  87. x2 = self.branch2(x)
  88. out = torch.cat((x0, x1, x2), 1)
  89. return out
  90. class Block17(nn.Module):
  91. def __init__(self, scale=1.0):
  92. super(Block17, self).__init__()
  93. self.scale = scale
  94. self.branch0 = BasicConv2d(1088, 192, kernel_size=1, stride=1)
  95. self.branch1 = nn.Sequential(
  96. BasicConv2d(1088, 128, kernel_size=1, stride=1),
  97. BasicConv2d(128, 160, kernel_size=(1,7), stride=1, padding=(0,3)),
  98. BasicConv2d(160, 192, kernel_size=(7,1), stride=1, padding=(3,0))
  99. )
  100. self.conv2d = nn.Conv2d(384, 1088, kernel_size=1, stride=1)
  101. self.relu = nn.ReLU(inplace=False)
  102. def forward(self, x):
  103. x0 = self.branch0(x)
  104. x1 = self.branch1(x)
  105. out = torch.cat((x0, x1), 1)
  106. out = self.conv2d(out)
  107. out = out * self.scale + x
  108. out = self.relu(out)
  109. return out
  110. class Mixed_7a(nn.Module):
  111. def __init__(self):
  112. super(Mixed_7a, self).__init__()
  113. self.branch0 = nn.Sequential(
  114. BasicConv2d(1088, 256, kernel_size=1, stride=1),
  115. BasicConv2d(256, 384, kernel_size=3, stride=2)
  116. )
  117. self.branch1 = nn.Sequential(
  118. BasicConv2d(1088, 256, kernel_size=1, stride=1),
  119. BasicConv2d(256, 288, kernel_size=3, stride=2)
  120. )
  121. self.branch2 = nn.Sequential(
  122. BasicConv2d(1088, 256, kernel_size=1, stride=1),
  123. BasicConv2d(256, 288, kernel_size=3, stride=1, padding=1),
  124. BasicConv2d(288, 320, kernel_size=3, stride=2)
  125. )
  126. self.branch3 = nn.MaxPool2d(3, stride=2)
  127. def forward(self, x):
  128. x0 = self.branch0(x)
  129. x1 = self.branch1(x)
  130. x2 = self.branch2(x)
  131. x3 = self.branch3(x)
  132. out = torch.cat((x0, x1, x2, x3), 1)
  133. return out
  134. class Block8(nn.Module):
  135. def __init__(self, scale=1.0, noReLU=False):
  136. super(Block8, self).__init__()
  137. self.scale = scale
  138. self.noReLU = noReLU
  139. self.branch0 = BasicConv2d(2080, 192, kernel_size=1, stride=1)
  140. self.branch1 = nn.Sequential(
  141. BasicConv2d(2080, 192, kernel_size=1, stride=1),
  142. BasicConv2d(192, 224, kernel_size=(1,3), stride=1, padding=(0,1)),
  143. BasicConv2d(224, 256, kernel_size=(3,1), stride=1, padding=(1,0))
  144. )
  145. self.conv2d = nn.Conv2d(448, 2080, kernel_size=1, stride=1)
  146. if not self.noReLU:
  147. self.relu = nn.ReLU(inplace=False)
  148. def forward(self, x):
  149. x0 = self.branch0(x)
  150. x1 = self.branch1(x)
  151. out = torch.cat((x0, x1), 1)
  152. out = self.conv2d(out)
  153. out = out * self.scale + x
  154. if not self.noReLU:
  155. out = self.relu(out)
  156. return out
  157. class InceptionResnetV2(nn.Module):
  158. def __init__(self, num_classes=1001):
  159. super(InceptionResnetV2, self).__init__()
  160. # Special attributs
  161. self.input_space = None
  162. self.input_size = (299, 299, 3)
  163. self.mean = None
  164. self.std = None
  165. # Modules
  166. self.conv2d_1a = BasicConv2d(3, 32, kernel_size=3, stride=2)
  167. self.conv2d_2a = BasicConv2d(32, 32, kernel_size=3, stride=1)
  168. self.conv2d_2b = BasicConv2d(32, 64, kernel_size=3, stride=1, padding=1)
  169. self.maxpool_3a = nn.MaxPool2d(3, stride=2)
  170. self.conv2d_3b = BasicConv2d(64, 80, kernel_size=1, stride=1)
  171. self.conv2d_4a = BasicConv2d(80, 192, kernel_size=3, stride=1)
  172. self.maxpool_5a = nn.MaxPool2d(3, stride=2)
  173. self.mixed_5b = Mixed_5b()
  174. self.repeat = nn.Sequential(
  175. Block35(scale=0.17),
  176. Block35(scale=0.17),
  177. Block35(scale=0.17),
  178. Block35(scale=0.17),
  179. Block35(scale=0.17),
  180. Block35(scale=0.17),
  181. Block35(scale=0.17),
  182. Block35(scale=0.17),
  183. Block35(scale=0.17),
  184. Block35(scale=0.17)
  185. )
  186. self.mixed_6a = Mixed_6a()
  187. self.repeat_1 = nn.Sequential(
  188. Block17(scale=0.10),
  189. Block17(scale=0.10),
  190. Block17(scale=0.10),
  191. Block17(scale=0.10),
  192. Block17(scale=0.10),
  193. Block17(scale=0.10),
  194. Block17(scale=0.10),
  195. Block17(scale=0.10),
  196. Block17(scale=0.10),
  197. Block17(scale=0.10),
  198. Block17(scale=0.10),
  199. Block17(scale=0.10),
  200. Block17(scale=0.10),
  201. Block17(scale=0.10),
  202. Block17(scale=0.10),
  203. Block17(scale=0.10),
  204. Block17(scale=0.10),
  205. Block17(scale=0.10),
  206. Block17(scale=0.10),
  207. Block17(scale=0.10)
  208. )
  209. self.mixed_7a = Mixed_7a()
  210. self.repeat_2 = nn.Sequential(
  211. Block8(scale=0.20),
  212. Block8(scale=0.20),
  213. Block8(scale=0.20),
  214. Block8(scale=0.20),
  215. Block8(scale=0.20),
  216. Block8(scale=0.20),
  217. Block8(scale=0.20),
  218. Block8(scale=0.20),
  219. Block8(scale=0.20)
  220. )
  221. self.block8 = Block8(noReLU=True)
  222. self.conv2d_7b = BasicConv2d(2080, 1536, kernel_size=1, stride=1)
  223. self.avgpool_1a = nn.AvgPool2d(8, count_include_pad=False)
  224. self.last_linear = nn.Linear(1536, num_classes)
  225. def features(self, input):
  226. x = self.conv2d_1a(input)
  227. x = self.conv2d_2a(x)
  228. x = self.conv2d_2b(x)
  229. x = self.maxpool_3a(x)
  230. x = self.conv2d_3b(x)
  231. x = self.conv2d_4a(x)
  232. x = self.maxpool_5a(x)
  233. x = self.mixed_5b(x)
  234. x = self.repeat(x)
  235. x = self.mixed_6a(x)
  236. x = self.repeat_1(x)
  237. x = self.mixed_7a(x)
  238. x = self.repeat_2(x)
  239. x = self.block8(x)
  240. x = self.conv2d_7b(x)
  241. return x
  242. def logits(self, features):
  243. x = self.avgpool_1a(features)
  244. x = x.view(x.size(0), -1)
  245. x = self.last_linear(x)
  246. return x
  247. def forward(self, input):
  248. x = self.features(input)
  249. x = self.logits(x)
  250. return x
  251. def inceptionresnetv2(num_classes=1000, pretrained='imagenet'):
  252. r"""InceptionResNetV2 model architecture from the
  253. `"InceptionV4, Inception-ResNet..." <https://arxiv.org/abs/1602.07261>`_ paper.
  254. """
  255. if pretrained:
  256. settings = pretrained_settings['inceptionresnetv2'][pretrained]
  257. assert num_classes == settings['num_classes'], \
  258. "num_classes should be {}, but is {}".format(settings['num_classes'], num_classes)
  259. # both 'imagenet'&'imagenet+background' are loaded from same parameters
  260. model = InceptionResNetV2(num_classes=1001)
  261. model.load_state_dict(model_zoo.load_url(settings['url']))
  262. if pretrained == 'imagenet':
  263. new_last_linear = nn.Linear(1536, 1000)
  264. new_last_linear.weight.data = model.last_linear.weight.data[1:]
  265. new_last_linear.bias.data = model.last_linear.bias.data[1:]
  266. model.last_linear = new_last_linear
  267. model.input_space = settings['input_space']
  268. model.input_size = settings['input_size']
  269. model.input_range = settings['input_range']
  270. model.mean = settings['mean']
  271. model.std = settings['std']
  272. else:
  273. model = InceptionResNetV2(num_classes=num_classes)
  274. return model
  275. '''
  276. TEST
  277. Run this code with:
  278. ```
  279. cd $HOME/pretrained-models.pytorch
  280. python -m pretrainedmodels.inceptionresnetv2
  281. ```
  282. '''
  283. if __name__ == '__main__':
  284. assert inceptionresnetv2(num_classes=10, pretrained=None)
  285. print('success')
  286. assert inceptionresnetv2(num_classes=1000, pretrained='imagenet')
  287. print('success')
  288. assert inceptionresnetv2(num_classes=1001, pretrained='imagenet+background')
  289. print('success')
  290. # fail
  291. assert inceptionresnetv2(num_classes=1001, pretrained='imagenet')