selecsls.py 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389
  1. """PyTorch SelecSLS Net example for ImageNet Classification
  2. License: CC BY 4.0 (https://creativecommons.org/licenses/by/4.0/legalcode)
  3. Author: Dushyant Mehta (@mehtadushy)
  4. SelecSLS (core) Network Architecture as proposed in "XNect: Real-time Multi-person 3D
  5. Human Pose Estimation with a Single RGB Camera, Mehta et al."
  6. https://arxiv.org/abs/1907.00837
  7. Based on ResNet implementation in https://github.com/rwightman/pytorch-image-models
  8. and SelecSLS Net implementation in https://github.com/mehtadushy/SelecSLS-Pytorch
  9. """
  10. from typing import List, Type
  11. import torch
  12. import torch.nn as nn
  13. from timm.data import IMAGENET_DEFAULT_MEAN, IMAGENET_DEFAULT_STD
  14. from timm.layers import create_classifier
  15. from ._builder import build_model_with_cfg
  16. from ._registry import register_model, generate_default_cfgs
  17. __all__ = ['SelecSls'] # model_registry will add each entrypoint fn to this
  18. class SequentialList(nn.Sequential):
  19. def __init__(self, *args):
  20. super().__init__(*args)
  21. def forward(self, x) -> List[torch.Tensor]:
  22. for module in self:
  23. x = module(x)
  24. return x
  25. class SelectSeq(nn.Module):
  26. def __init__(self, mode='index', index=0):
  27. super().__init__()
  28. self.mode = mode
  29. self.index = index
  30. def forward(self, x) -> torch.Tensor:
  31. if self.mode == 'index':
  32. return x[self.index]
  33. else:
  34. return torch.cat(x, dim=1)
  35. def conv_bn(in_chs, out_chs, k=3, stride=1, padding=None, dilation=1, device=None, dtype=None):
  36. dd = {'device': device, 'dtype': dtype}
  37. if padding is None:
  38. padding = ((stride - 1) + dilation * (k - 1)) // 2
  39. return nn.Sequential(
  40. nn.Conv2d(in_chs, out_chs, k, stride, padding=padding, dilation=dilation, bias=False, **dd),
  41. nn.BatchNorm2d(out_chs, **dd),
  42. nn.ReLU(inplace=True)
  43. )
  44. class SelecSlsBlock(nn.Module):
  45. def __init__(
  46. self,
  47. in_chs: int,
  48. skip_chs: int,
  49. mid_chs: int,
  50. out_chs: int,
  51. is_first: bool,
  52. stride: int,
  53. dilation: int = 1,
  54. device=None,
  55. dtype=None,
  56. ):
  57. dd = {'device': device, 'dtype': dtype}
  58. super().__init__()
  59. self.stride = stride
  60. self.is_first = is_first
  61. assert stride in [1, 2]
  62. # Process input with 4 conv blocks with the same number of input and output channels
  63. self.conv1 = conv_bn(in_chs, mid_chs, 3, stride, dilation=dilation, **dd)
  64. self.conv2 = conv_bn(mid_chs, mid_chs, 1, **dd)
  65. self.conv3 = conv_bn(mid_chs, mid_chs // 2, 3, **dd)
  66. self.conv4 = conv_bn(mid_chs // 2, mid_chs, 1, **dd)
  67. self.conv5 = conv_bn(mid_chs, mid_chs // 2, 3, **dd)
  68. self.conv6 = conv_bn(2 * mid_chs + (0 if is_first else skip_chs), out_chs, 1, **dd)
  69. def forward(self, x: List[torch.Tensor]) -> List[torch.Tensor]:
  70. if not isinstance(x, list):
  71. x = [x]
  72. assert len(x) in [1, 2]
  73. d1 = self.conv1(x[0])
  74. d2 = self.conv3(self.conv2(d1))
  75. d3 = self.conv5(self.conv4(d2))
  76. if self.is_first:
  77. out = self.conv6(torch.cat([d1, d2, d3], 1))
  78. return [out, out]
  79. else:
  80. return [self.conv6(torch.cat([d1, d2, d3, x[1]], 1)), x[1]]
  81. class SelecSls(nn.Module):
  82. """SelecSls42 / SelecSls60 / SelecSls84
  83. Parameters
  84. ----------
  85. cfg : network config dictionary specifying block type, feature, and head args
  86. num_classes : int, default 1000
  87. Number of classification classes.
  88. in_chans : int, default 3
  89. Number of input (color) channels.
  90. drop_rate : float, default 0.
  91. Dropout probability before classifier, for training
  92. global_pool : str, default 'avg'
  93. Global pooling type. One of 'avg', 'max', 'avgmax', 'catavgmax'
  94. """
  95. def __init__(
  96. self,
  97. cfg,
  98. num_classes: int = 1000,
  99. in_chans: int = 3,
  100. drop_rate: float = 0.0,
  101. global_pool: str = 'avg',
  102. device=None,
  103. dtype=None,
  104. ):
  105. self.num_classes = num_classes
  106. self.in_chans = in_chans
  107. super().__init__()
  108. dd = {'device': device, 'dtype': dtype}
  109. self.stem = conv_bn(in_chans, 32, stride=2, **dd)
  110. self.features = SequentialList(*[cfg['block'](*block_args, **dd) for block_args in cfg['features']])
  111. self.from_seq = SelectSeq() # from List[tensor] -> Tensor in module compatible way
  112. self.head = nn.Sequential(*[conv_bn(*conv_args, **dd) for conv_args in cfg['head']])
  113. self.num_features = self.head_hidden_size = cfg['num_features']
  114. self.feature_info = cfg['feature_info']
  115. self.global_pool, self.head_drop, self.fc = create_classifier(
  116. self.num_features,
  117. self.num_classes,
  118. pool_type=global_pool,
  119. drop_rate=drop_rate,
  120. **dd,
  121. )
  122. for n, m in self.named_modules():
  123. if isinstance(m, nn.Conv2d):
  124. nn.init.kaiming_normal_(m.weight, mode='fan_out', nonlinearity='relu')
  125. @torch.jit.ignore
  126. def group_matcher(self, coarse=False):
  127. return dict(
  128. stem=r'^stem',
  129. blocks=r'^features\.(\d+)',
  130. blocks_head=r'^head'
  131. )
  132. @torch.jit.ignore
  133. def set_grad_checkpointing(self, enable=True):
  134. assert not enable, 'gradient checkpointing not supported'
  135. @torch.jit.ignore
  136. def get_classifier(self) -> nn.Module:
  137. return self.fc
  138. def reset_classifier(self, num_classes: int, global_pool: str = 'avg'):
  139. self.num_classes = num_classes
  140. self.global_pool, self.fc = create_classifier(
  141. self.num_features,
  142. self.num_classes,
  143. pool_type=global_pool,
  144. device=self.fc.weight.device if hasattr(self.fc, 'weight') else None,
  145. dtype=self.fc.weight.dtype if hasattr(self.fc, 'weight') else None,
  146. )
  147. def forward_features(self, x):
  148. x = self.stem(x)
  149. x = self.features(x)
  150. x = self.head(self.from_seq(x))
  151. return x
  152. def forward_head(self, x, pre_logits: bool = False):
  153. x = self.global_pool(x)
  154. x = self.head_drop(x)
  155. return x if pre_logits else self.fc(x)
  156. def forward(self, x):
  157. x = self.forward_features(x)
  158. x = self.forward_head(x)
  159. return x
  160. def _create_selecsls(variant, pretrained, **kwargs):
  161. cfg = {}
  162. feature_info = [dict(num_chs=32, reduction=2, module='stem.2')]
  163. if variant.startswith('selecsls42'):
  164. cfg['block'] = SelecSlsBlock
  165. # Define configuration of the network after the initial neck
  166. cfg['features'] = [
  167. # in_chs, skip_chs, mid_chs, out_chs, is_first, stride
  168. (32, 0, 64, 64, True, 2),
  169. (64, 64, 64, 128, False, 1),
  170. (128, 0, 144, 144, True, 2),
  171. (144, 144, 144, 288, False, 1),
  172. (288, 0, 304, 304, True, 2),
  173. (304, 304, 304, 480, False, 1),
  174. ]
  175. feature_info.extend([
  176. dict(num_chs=128, reduction=4, module='features.1'),
  177. dict(num_chs=288, reduction=8, module='features.3'),
  178. dict(num_chs=480, reduction=16, module='features.5'),
  179. ])
  180. # Head can be replaced with alternative configurations depending on the problem
  181. feature_info.append(dict(num_chs=1024, reduction=32, module='head.1'))
  182. if variant == 'selecsls42b':
  183. cfg['head'] = [
  184. (480, 960, 3, 2),
  185. (960, 1024, 3, 1),
  186. (1024, 1280, 3, 2),
  187. (1280, 1024, 1, 1),
  188. ]
  189. feature_info.append(dict(num_chs=1024, reduction=64, module='head.3'))
  190. cfg['num_features'] = 1024
  191. else:
  192. cfg['head'] = [
  193. (480, 960, 3, 2),
  194. (960, 1024, 3, 1),
  195. (1024, 1024, 3, 2),
  196. (1024, 1280, 1, 1),
  197. ]
  198. feature_info.append(dict(num_chs=1280, reduction=64, module='head.3'))
  199. cfg['num_features'] = 1280
  200. elif variant.startswith('selecsls60'):
  201. cfg['block'] = SelecSlsBlock
  202. # Define configuration of the network after the initial neck
  203. cfg['features'] = [
  204. # in_chs, skip_chs, mid_chs, out_chs, is_first, stride
  205. (32, 0, 64, 64, True, 2),
  206. (64, 64, 64, 128, False, 1),
  207. (128, 0, 128, 128, True, 2),
  208. (128, 128, 128, 128, False, 1),
  209. (128, 128, 128, 288, False, 1),
  210. (288, 0, 288, 288, True, 2),
  211. (288, 288, 288, 288, False, 1),
  212. (288, 288, 288, 288, False, 1),
  213. (288, 288, 288, 416, False, 1),
  214. ]
  215. feature_info.extend([
  216. dict(num_chs=128, reduction=4, module='features.1'),
  217. dict(num_chs=288, reduction=8, module='features.4'),
  218. dict(num_chs=416, reduction=16, module='features.8'),
  219. ])
  220. # Head can be replaced with alternative configurations depending on the problem
  221. feature_info.append(dict(num_chs=1024, reduction=32, module='head.1'))
  222. if variant == 'selecsls60b':
  223. cfg['head'] = [
  224. (416, 756, 3, 2),
  225. (756, 1024, 3, 1),
  226. (1024, 1280, 3, 2),
  227. (1280, 1024, 1, 1),
  228. ]
  229. feature_info.append(dict(num_chs=1024, reduction=64, module='head.3'))
  230. cfg['num_features'] = 1024
  231. else:
  232. cfg['head'] = [
  233. (416, 756, 3, 2),
  234. (756, 1024, 3, 1),
  235. (1024, 1024, 3, 2),
  236. (1024, 1280, 1, 1),
  237. ]
  238. feature_info.append(dict(num_chs=1280, reduction=64, module='head.3'))
  239. cfg['num_features'] = 1280
  240. elif variant == 'selecsls84':
  241. cfg['block'] = SelecSlsBlock
  242. # Define configuration of the network after the initial neck
  243. cfg['features'] = [
  244. # in_chs, skip_chs, mid_chs, out_chs, is_first, stride
  245. (32, 0, 64, 64, True, 2),
  246. (64, 64, 64, 144, False, 1),
  247. (144, 0, 144, 144, True, 2),
  248. (144, 144, 144, 144, False, 1),
  249. (144, 144, 144, 144, False, 1),
  250. (144, 144, 144, 144, False, 1),
  251. (144, 144, 144, 304, False, 1),
  252. (304, 0, 304, 304, True, 2),
  253. (304, 304, 304, 304, False, 1),
  254. (304, 304, 304, 304, False, 1),
  255. (304, 304, 304, 304, False, 1),
  256. (304, 304, 304, 304, False, 1),
  257. (304, 304, 304, 512, False, 1),
  258. ]
  259. feature_info.extend([
  260. dict(num_chs=144, reduction=4, module='features.1'),
  261. dict(num_chs=304, reduction=8, module='features.6'),
  262. dict(num_chs=512, reduction=16, module='features.12'),
  263. ])
  264. # Head can be replaced with alternative configurations depending on the problem
  265. cfg['head'] = [
  266. (512, 960, 3, 2),
  267. (960, 1024, 3, 1),
  268. (1024, 1024, 3, 2),
  269. (1024, 1280, 3, 1),
  270. ]
  271. cfg['num_features'] = 1280
  272. feature_info.extend([
  273. dict(num_chs=1024, reduction=32, module='head.1'),
  274. dict(num_chs=1280, reduction=64, module='head.3')
  275. ])
  276. else:
  277. raise ValueError('Invalid net configuration ' + variant + ' !!!')
  278. cfg['feature_info'] = feature_info
  279. # this model can do 6 feature levels by default, unlike most others, leave as 0-4 to avoid surprises?
  280. return build_model_with_cfg(
  281. SelecSls,
  282. variant,
  283. pretrained,
  284. model_cfg=cfg,
  285. feature_cfg=dict(out_indices=(0, 1, 2, 3, 4), flatten_sequential=True),
  286. **kwargs,
  287. )
  288. def _cfg(url='', **kwargs):
  289. return {
  290. 'url': url,
  291. 'num_classes': 1000, 'input_size': (3, 224, 224), 'pool_size': (4, 4),
  292. 'crop_pct': 0.875, 'interpolation': 'bilinear',
  293. 'mean': IMAGENET_DEFAULT_MEAN, 'std': IMAGENET_DEFAULT_STD,
  294. 'first_conv': 'stem.0', 'classifier': 'fc',
  295. 'license': 'cc-by-4.0',
  296. **kwargs
  297. }
  298. default_cfgs = generate_default_cfgs({
  299. 'selecsls42.untrained': _cfg(
  300. interpolation='bicubic'),
  301. 'selecsls42b.in1k': _cfg(
  302. hf_hub_id='timm/',
  303. interpolation='bicubic'),
  304. 'selecsls60.in1k': _cfg(
  305. hf_hub_id='timm/',
  306. interpolation='bicubic'),
  307. 'selecsls60b.in1k': _cfg(
  308. hf_hub_id='timm/',
  309. interpolation='bicubic'),
  310. 'selecsls84.untrained': _cfg(
  311. interpolation='bicubic'),
  312. })
  313. @register_model
  314. def selecsls42(pretrained=False, **kwargs) -> SelecSls:
  315. """Constructs a SelecSls42 model.
  316. """
  317. return _create_selecsls('selecsls42', pretrained, **kwargs)
  318. @register_model
  319. def selecsls42b(pretrained=False, **kwargs) -> SelecSls:
  320. """Constructs a SelecSls42_B model.
  321. """
  322. return _create_selecsls('selecsls42b', pretrained, **kwargs)
  323. @register_model
  324. def selecsls60(pretrained=False, **kwargs) -> SelecSls:
  325. """Constructs a SelecSls60 model.
  326. """
  327. return _create_selecsls('selecsls60', pretrained, **kwargs)
  328. @register_model
  329. def selecsls60b(pretrained=False, **kwargs) -> SelecSls:
  330. """Constructs a SelecSls60_B model.
  331. """
  332. return _create_selecsls('selecsls60b', pretrained, **kwargs)
  333. @register_model
  334. def selecsls84(pretrained=False, **kwargs) -> SelecSls:
  335. """Constructs a SelecSls84 model.
  336. """
  337. return _create_selecsls('selecsls84', pretrained, **kwargs)