selecsls.py 14 KB

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