rexnet.py 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604
  1. """ ReXNet
  2. A PyTorch impl of `ReXNet: Diminishing Representational Bottleneck on Convolutional Neural Network` -
  3. https://arxiv.org/abs/2007.00992
  4. Adapted from original impl at https://github.com/clovaai/rexnet
  5. Copyright (c) 2020-present NAVER Corp. MIT license
  6. Changes for timm, feature extraction, and rounded channel variant hacked together by Ross Wightman
  7. Copyright 2020 Ross Wightman
  8. """
  9. from functools import partial
  10. from math import ceil
  11. from typing import Any, Dict, List, Optional, Tuple, Type, Union
  12. import torch
  13. import torch.nn as nn
  14. from timm.data import IMAGENET_DEFAULT_MEAN, IMAGENET_DEFAULT_STD
  15. from timm.layers import ClassifierHead, create_act_layer, ConvNormAct, DropPath, make_divisible, SEModule
  16. from ._builder import build_model_with_cfg
  17. from ._efficientnet_builder import efficientnet_init_weights
  18. from ._features import feature_take_indices
  19. from ._manipulate import checkpoint, checkpoint_seq
  20. from ._registry import generate_default_cfgs, register_model
  21. __all__ = ['RexNet'] # model_registry will add each entrypoint fn to this
  22. SEWithNorm = partial(SEModule, norm_layer=nn.BatchNorm2d)
  23. class LinearBottleneck(nn.Module):
  24. """Linear bottleneck block for ReXNet.
  25. A mobile inverted residual bottleneck block as used in MobileNetV2 and subsequent models.
  26. """
  27. def __init__(
  28. self,
  29. in_chs: int,
  30. out_chs: int,
  31. stride: int,
  32. dilation: Tuple[int, int] = (1, 1),
  33. exp_ratio: float = 1.0,
  34. se_ratio: float = 0.,
  35. ch_div: int = 1,
  36. act_layer: str = 'swish',
  37. dw_act_layer: str = 'relu6',
  38. drop_path: Optional[nn.Module] = None,
  39. device=None,
  40. dtype=None,
  41. ):
  42. """Initialize LinearBottleneck.
  43. Args:
  44. in_chs: Number of input channels.
  45. out_chs: Number of output channels.
  46. stride: Stride for depthwise conv.
  47. dilation: Dilation rates.
  48. exp_ratio: Expansion ratio.
  49. se_ratio: Squeeze-excitation ratio.
  50. ch_div: Channel divisor.
  51. act_layer: Activation layer for expansion.
  52. dw_act_layer: Activation layer for depthwise.
  53. drop_path: Drop path module.
  54. """
  55. dd = {'device': device, 'dtype': dtype}
  56. super().__init__()
  57. self.use_shortcut = stride == 1 and dilation[0] == dilation[1] and in_chs <= out_chs
  58. self.in_channels = in_chs
  59. self.out_channels = out_chs
  60. if exp_ratio != 1.:
  61. dw_chs = make_divisible(round(in_chs * exp_ratio), divisor=ch_div)
  62. self.conv_exp = ConvNormAct(in_chs, dw_chs, act_layer=act_layer, **dd)
  63. else:
  64. dw_chs = in_chs
  65. self.conv_exp = None
  66. self.conv_dw = ConvNormAct(
  67. dw_chs,
  68. dw_chs,
  69. kernel_size=3,
  70. stride=stride,
  71. dilation=dilation[0],
  72. groups=dw_chs,
  73. apply_act=False,
  74. **dd,
  75. )
  76. if se_ratio > 0:
  77. self.se = SEWithNorm(dw_chs, rd_channels=make_divisible(int(dw_chs * se_ratio), ch_div), **dd)
  78. else:
  79. self.se = None
  80. self.act_dw = create_act_layer(dw_act_layer)
  81. self.conv_pwl = ConvNormAct(dw_chs, out_chs, 1, apply_act=False, **dd)
  82. self.drop_path = drop_path
  83. def feat_channels(self, exp: bool = False) -> int:
  84. """Get feature channel count.
  85. Args:
  86. exp: Return expanded channels if True.
  87. Returns:
  88. Number of feature channels.
  89. """
  90. return self.conv_dw.out_channels if exp else self.out_channels
  91. def forward(self, x: torch.Tensor) -> torch.Tensor:
  92. """Forward pass.
  93. Args:
  94. x: Input tensor.
  95. Returns:
  96. Output tensor.
  97. """
  98. shortcut = x
  99. if self.conv_exp is not None:
  100. x = self.conv_exp(x)
  101. x = self.conv_dw(x)
  102. if self.se is not None:
  103. x = self.se(x)
  104. x = self.act_dw(x)
  105. x = self.conv_pwl(x)
  106. if self.use_shortcut:
  107. if self.drop_path is not None:
  108. x = self.drop_path(x)
  109. x = torch.cat([x[:, 0:self.in_channels] + shortcut, x[:, self.in_channels:]], dim=1)
  110. return x
  111. def _block_cfg(
  112. width_mult: float = 1.0,
  113. depth_mult: float = 1.0,
  114. initial_chs: int = 16,
  115. final_chs: int = 180,
  116. se_ratio: float = 0.,
  117. ch_div: int = 1,
  118. ) -> List[Tuple[int, float, int, float]]:
  119. """Generate ReXNet block configuration.
  120. Args:
  121. width_mult: Width multiplier.
  122. depth_mult: Depth multiplier.
  123. initial_chs: Initial channel count.
  124. final_chs: Final channel count.
  125. se_ratio: Squeeze-excitation ratio.
  126. ch_div: Channel divisor.
  127. Returns:
  128. List of tuples (out_channels, exp_ratio, stride, se_ratio).
  129. """
  130. layers = [1, 2, 2, 3, 3, 5]
  131. strides = [1, 2, 2, 2, 1, 2]
  132. layers = [ceil(element * depth_mult) for element in layers]
  133. strides = sum([[element] + [1] * (layers[idx] - 1) for idx, element in enumerate(strides)], [])
  134. exp_ratios = [1] * layers[0] + [6] * sum(layers[1:])
  135. depth = sum(layers[:]) * 3
  136. base_chs = initial_chs / width_mult if width_mult < 1.0 else initial_chs
  137. # The following channel configuration is a simple instance to make each layer become an expand layer.
  138. out_chs_list = []
  139. for i in range(depth // 3):
  140. out_chs_list.append(make_divisible(round(base_chs * width_mult), divisor=ch_div))
  141. base_chs += final_chs / (depth // 3 * 1.0)
  142. se_ratios = [0.] * (layers[0] + layers[1]) + [se_ratio] * sum(layers[2:])
  143. return list(zip(out_chs_list, exp_ratios, strides, se_ratios))
  144. def _build_blocks(
  145. block_cfg: List[Tuple[int, float, int, float]],
  146. prev_chs: int,
  147. width_mult: float,
  148. ch_div: int = 1,
  149. output_stride: int = 32,
  150. act_layer: str = 'swish',
  151. dw_act_layer: str = 'relu6',
  152. drop_path_rate: float = 0.,
  153. device=None,
  154. dtype=None,
  155. ) -> Tuple[List[nn.Module], List[Dict[str, Any]]]:
  156. """Build ReXNet blocks from configuration.
  157. Args:
  158. block_cfg: Block configuration list.
  159. prev_chs: Previous channel count.
  160. width_mult: Width multiplier.
  161. ch_div: Channel divisor.
  162. output_stride: Target output stride.
  163. act_layer: Activation layer name.
  164. dw_act_layer: Depthwise activation layer name.
  165. drop_path_rate: Drop path rate.
  166. Returns:
  167. Tuple of (features list, feature_info list).
  168. """
  169. dd = {'device': device, 'dtype': dtype}
  170. feat_chs = [prev_chs]
  171. feature_info = []
  172. curr_stride = 2
  173. dilation = 1
  174. features = []
  175. num_blocks = len(block_cfg)
  176. for block_idx, (chs, exp_ratio, stride, se_ratio) in enumerate(block_cfg):
  177. next_dilation = dilation
  178. if stride > 1:
  179. fname = 'stem' if block_idx == 0 else f'features.{block_idx - 1}'
  180. feature_info += [dict(num_chs=feat_chs[-1], reduction=curr_stride, module=fname)]
  181. if curr_stride >= output_stride:
  182. next_dilation = dilation * stride
  183. stride = 1
  184. block_dpr = drop_path_rate * block_idx / (num_blocks - 1) # stochastic depth linear decay rule
  185. drop_path = DropPath(block_dpr) if block_dpr > 0. else None
  186. features.append(LinearBottleneck(
  187. in_chs=prev_chs,
  188. out_chs=chs,
  189. exp_ratio=exp_ratio,
  190. stride=stride,
  191. dilation=(dilation, next_dilation),
  192. se_ratio=se_ratio,
  193. ch_div=ch_div,
  194. act_layer=act_layer,
  195. dw_act_layer=dw_act_layer,
  196. drop_path=drop_path,
  197. **dd,
  198. ))
  199. curr_stride *= stride
  200. dilation = next_dilation
  201. prev_chs = chs
  202. feat_chs += [features[-1].feat_channels()]
  203. pen_chs = make_divisible(1280 * width_mult, divisor=ch_div)
  204. feature_info += [dict(num_chs=feat_chs[-1], reduction=curr_stride, module=f'features.{len(features) - 1}')]
  205. features.append(ConvNormAct(prev_chs, pen_chs, act_layer=act_layer, **dd))
  206. return features, feature_info
  207. class RexNet(nn.Module):
  208. """ReXNet model architecture.
  209. Based on `ReXNet: Diminishing Representational Bottleneck on Convolutional Neural Network`
  210. - https://arxiv.org/abs/2007.00992
  211. """
  212. def __init__(
  213. self,
  214. in_chans: int = 3,
  215. num_classes: int = 1000,
  216. global_pool: str = 'avg',
  217. output_stride: int = 32,
  218. initial_chs: int = 16,
  219. final_chs: int = 180,
  220. width_mult: float = 1.0,
  221. depth_mult: float = 1.0,
  222. se_ratio: float = 1/12.,
  223. ch_div: int = 1,
  224. act_layer: str = 'swish',
  225. dw_act_layer: str = 'relu6',
  226. drop_rate: float = 0.2,
  227. drop_path_rate: float = 0.,
  228. device=None,
  229. dtype=None,
  230. ):
  231. """Initialize ReXNet.
  232. Args:
  233. in_chans: Number of input channels.
  234. num_classes: Number of classes for classification.
  235. global_pool: Global pooling type.
  236. output_stride: Output stride.
  237. initial_chs: Initial channel count.
  238. final_chs: Final channel count.
  239. width_mult: Width multiplier.
  240. depth_mult: Depth multiplier.
  241. se_ratio: Squeeze-excitation ratio.
  242. ch_div: Channel divisor.
  243. act_layer: Activation layer name.
  244. dw_act_layer: Depthwise activation layer name.
  245. drop_rate: Dropout rate.
  246. drop_path_rate: Drop path rate.
  247. """
  248. super().__init__()
  249. dd = {'device': device, 'dtype': dtype}
  250. self.num_classes = num_classes
  251. self.in_chans = in_chans
  252. self.drop_rate = drop_rate
  253. self.grad_checkpointing = False
  254. assert output_stride in (32, 16, 8)
  255. stem_base_chs = 32 / width_mult if width_mult < 1.0 else 32
  256. stem_chs = make_divisible(round(stem_base_chs * width_mult), divisor=ch_div)
  257. self.stem = ConvNormAct(in_chans, stem_chs, 3, stride=2, act_layer=act_layer, **dd)
  258. block_cfg = _block_cfg(width_mult, depth_mult, initial_chs, final_chs, se_ratio, ch_div)
  259. features, self.feature_info = _build_blocks(
  260. block_cfg,
  261. stem_chs,
  262. width_mult,
  263. ch_div,
  264. output_stride,
  265. act_layer,
  266. dw_act_layer,
  267. drop_path_rate,
  268. **dd,
  269. )
  270. self.num_features = self.head_hidden_size = features[-1].out_channels
  271. self.features = nn.Sequential(*features)
  272. self.head = ClassifierHead(self.num_features, num_classes, global_pool, drop_rate, **dd)
  273. efficientnet_init_weights(self)
  274. @torch.jit.ignore
  275. def group_matcher(self, coarse: bool = False) -> Dict[str, Any]:
  276. """Group matcher for parameter groups.
  277. Args:
  278. coarse: Whether to use coarse grouping.
  279. Returns:
  280. Dictionary of grouped parameters.
  281. """
  282. matcher = dict(
  283. stem=r'^stem',
  284. blocks=r'^features\.(\d+)',
  285. )
  286. return matcher
  287. @torch.jit.ignore
  288. def set_grad_checkpointing(self, enable: bool = True) -> None:
  289. """Enable or disable gradient checkpointing.
  290. Args:
  291. enable: Whether to enable gradient checkpointing.
  292. """
  293. self.grad_checkpointing = enable
  294. @torch.jit.ignore
  295. def get_classifier(self) -> nn.Module:
  296. """Get the classifier module.
  297. Returns:
  298. Classifier module.
  299. """
  300. return self.head.fc
  301. def reset_classifier(self, num_classes: int, global_pool: Optional[str] = None, device=None, dtype=None) -> None:
  302. """Reset the classifier.
  303. Args:
  304. num_classes: Number of classes for new classifier.
  305. global_pool: Global pooling type.
  306. """
  307. self.num_classes = num_classes
  308. if device is not None or dtype is not None:
  309. dd = {'device': device, 'dtype': dtype}
  310. pool_type = global_pool if global_pool is not None else self.head.global_pool.pool_type
  311. self.head = ClassifierHead(self.num_features, num_classes, pool_type, self.drop_rate, **dd)
  312. else:
  313. self.head.reset(num_classes, global_pool)
  314. def forward_intermediates(
  315. self,
  316. x: torch.Tensor,
  317. indices: Optional[Union[int, List[int]]] = None,
  318. norm: bool = False,
  319. stop_early: bool = False,
  320. output_fmt: str = 'NCHW',
  321. intermediates_only: bool = False,
  322. ) -> Union[List[torch.Tensor], Tuple[torch.Tensor, List[torch.Tensor]]]:
  323. """ Forward features that returns intermediates.
  324. Args:
  325. x: Input image tensor
  326. indices: Take last n blocks if int, all if None, select matching indices if sequence
  327. norm: Apply norm layer to compatible intermediates
  328. stop_early: Stop iterating over blocks when last desired intermediate hit
  329. output_fmt: Shape of intermediate feature outputs
  330. intermediates_only: Only return intermediate features
  331. Returns:
  332. """
  333. assert output_fmt in ('NCHW',), 'Output shape must be NCHW.'
  334. intermediates = []
  335. stage_ends = [int(info['module'].split('.')[-1]) for info in self.feature_info]
  336. take_indices, max_index = feature_take_indices(len(stage_ends), indices)
  337. take_indices = [stage_ends[i] for i in take_indices]
  338. max_index = stage_ends[max_index]
  339. # forward pass
  340. x = self.stem(x)
  341. if torch.jit.is_scripting() or not stop_early: # can't slice blocks in torchscript
  342. stages = self.features
  343. else:
  344. stages = self.features[:max_index + 1]
  345. for feat_idx, stage in enumerate(stages):
  346. if self.grad_checkpointing and not torch.jit.is_scripting():
  347. x = checkpoint(stage, x)
  348. else:
  349. x = stage(x)
  350. if feat_idx in take_indices:
  351. intermediates.append(x)
  352. if intermediates_only:
  353. return intermediates
  354. return x, intermediates
  355. def prune_intermediate_layers(
  356. self,
  357. indices: Union[int, List[int]] = 1,
  358. prune_norm: bool = False,
  359. prune_head: bool = True,
  360. ) -> List[int]:
  361. """Prune layers not required for specified intermediates.
  362. Args:
  363. indices: Indices of intermediate layers to keep.
  364. prune_norm: Whether to prune normalization layer.
  365. prune_head: Whether to prune the classifier head.
  366. Returns:
  367. List of indices that were kept.
  368. """
  369. stage_ends = [int(info['module'].split('.')[-1]) for info in self.feature_info]
  370. take_indices, max_index = feature_take_indices(len(stage_ends), indices)
  371. max_index = stage_ends[max_index]
  372. self.features = self.features[:max_index + 1] # truncate blocks w/ stem as idx 0
  373. if prune_head:
  374. self.reset_classifier(0, '')
  375. return take_indices
  376. def forward_features(self, x: torch.Tensor) -> torch.Tensor:
  377. """Forward pass through feature extraction layers.
  378. Args:
  379. x: Input tensor.
  380. Returns:
  381. Feature tensor.
  382. """
  383. x = self.stem(x)
  384. if self.grad_checkpointing and not torch.jit.is_scripting():
  385. x = checkpoint_seq(self.features, x)
  386. else:
  387. x = self.features(x)
  388. return x
  389. def forward_head(self, x: torch.Tensor, pre_logits: bool = False) -> torch.Tensor:
  390. """Forward pass through head.
  391. Args:
  392. x: Input features.
  393. pre_logits: Return features before final linear layer.
  394. Returns:
  395. Classification logits or features.
  396. """
  397. return self.head(x, pre_logits=pre_logits) if pre_logits else self.head(x)
  398. def forward(self, x: torch.Tensor) -> torch.Tensor:
  399. """Forward pass.
  400. Args:
  401. x: Input tensor.
  402. Returns:
  403. Output logits.
  404. """
  405. x = self.forward_features(x)
  406. x = self.forward_head(x)
  407. return x
  408. def _create_rexnet(variant: str, pretrained: bool, **kwargs) -> RexNet:
  409. """Create a ReXNet model.
  410. Args:
  411. variant: Model variant name.
  412. pretrained: Load pretrained weights.
  413. **kwargs: Additional model arguments.
  414. Returns:
  415. ReXNet model instance.
  416. """
  417. feature_cfg = dict(flatten_sequential=True)
  418. return build_model_with_cfg(
  419. RexNet,
  420. variant,
  421. pretrained,
  422. feature_cfg=feature_cfg,
  423. **kwargs,
  424. )
  425. def _cfg(url: str = '', **kwargs) -> Dict[str, Any]:
  426. """Create default configuration dictionary.
  427. Args:
  428. url: Model weight URL.
  429. **kwargs: Additional configuration options.
  430. Returns:
  431. Configuration dictionary.
  432. """
  433. return {
  434. 'url': url, 'num_classes': 1000, 'input_size': (3, 224, 224), 'pool_size': (7, 7),
  435. 'crop_pct': 0.875, 'interpolation': 'bicubic',
  436. 'mean': IMAGENET_DEFAULT_MEAN, 'std': IMAGENET_DEFAULT_STD,
  437. 'first_conv': 'stem.conv', 'classifier': 'head.fc',
  438. 'license': 'mit', **kwargs
  439. }
  440. default_cfgs = generate_default_cfgs({
  441. 'rexnet_100.nav_in1k': _cfg(hf_hub_id='timm/'),
  442. 'rexnet_130.nav_in1k': _cfg(hf_hub_id='timm/'),
  443. 'rexnet_150.nav_in1k': _cfg(hf_hub_id='timm/'),
  444. 'rexnet_200.nav_in1k': _cfg(hf_hub_id='timm/'),
  445. 'rexnet_300.nav_in1k': _cfg(hf_hub_id='timm/'),
  446. 'rexnetr_100.untrained': _cfg(),
  447. 'rexnetr_130.untrained': _cfg(),
  448. 'rexnetr_150.untrained': _cfg(),
  449. 'rexnetr_200.sw_in12k_ft_in1k': _cfg(
  450. hf_hub_id='timm/',
  451. crop_pct=0.95, test_crop_pct=1.0, test_input_size=(3, 288, 288), license='apache-2.0'),
  452. 'rexnetr_300.sw_in12k_ft_in1k': _cfg(
  453. hf_hub_id='timm/',
  454. crop_pct=0.95, test_crop_pct=1.0, test_input_size=(3, 288, 288), license='apache-2.0'),
  455. 'rexnetr_200.sw_in12k': _cfg(
  456. hf_hub_id='timm/',
  457. num_classes=11821,
  458. crop_pct=0.95, test_crop_pct=1.0, test_input_size=(3, 288, 288), license='apache-2.0'),
  459. 'rexnetr_300.sw_in12k': _cfg(
  460. hf_hub_id='timm/',
  461. num_classes=11821,
  462. crop_pct=0.95, test_crop_pct=1.0, test_input_size=(3, 288, 288), license='apache-2.0'),
  463. })
  464. @register_model
  465. def rexnet_100(pretrained: bool = False, **kwargs) -> RexNet:
  466. """ReXNet V1 1.0x"""
  467. return _create_rexnet('rexnet_100', pretrained, **kwargs)
  468. @register_model
  469. def rexnet_130(pretrained: bool = False, **kwargs) -> RexNet:
  470. """ReXNet V1 1.3x"""
  471. return _create_rexnet('rexnet_130', pretrained, width_mult=1.3, **kwargs)
  472. @register_model
  473. def rexnet_150(pretrained: bool = False, **kwargs) -> RexNet:
  474. """ReXNet V1 1.5x"""
  475. return _create_rexnet('rexnet_150', pretrained, width_mult=1.5, **kwargs)
  476. @register_model
  477. def rexnet_200(pretrained: bool = False, **kwargs) -> RexNet:
  478. """ReXNet V1 2.0x"""
  479. return _create_rexnet('rexnet_200', pretrained, width_mult=2.0, **kwargs)
  480. @register_model
  481. def rexnet_300(pretrained: bool = False, **kwargs) -> RexNet:
  482. """ReXNet V1 3.0x"""
  483. return _create_rexnet('rexnet_300', pretrained, width_mult=3.0, **kwargs)
  484. @register_model
  485. def rexnetr_100(pretrained: bool = False, **kwargs) -> RexNet:
  486. """ReXNet V1 1.0x w/ rounded (mod 8) channels"""
  487. return _create_rexnet('rexnetr_100', pretrained, ch_div=8, **kwargs)
  488. @register_model
  489. def rexnetr_130(pretrained: bool = False, **kwargs) -> RexNet:
  490. """ReXNet V1 1.3x w/ rounded (mod 8) channels"""
  491. return _create_rexnet('rexnetr_130', pretrained, width_mult=1.3, ch_div=8, **kwargs)
  492. @register_model
  493. def rexnetr_150(pretrained: bool = False, **kwargs) -> RexNet:
  494. """ReXNet V1 1.5x w/ rounded (mod 8) channels"""
  495. return _create_rexnet('rexnetr_150', pretrained, width_mult=1.5, ch_div=8, **kwargs)
  496. @register_model
  497. def rexnetr_200(pretrained: bool = False, **kwargs) -> RexNet:
  498. """ReXNet V1 2.0x w/ rounded (mod 8) channels"""
  499. return _create_rexnet('rexnetr_200', pretrained, width_mult=2.0, ch_div=8, **kwargs)
  500. @register_model
  501. def rexnetr_300(pretrained: bool = False, **kwargs) -> RexNet:
  502. """ReXNet V1 3.0x w/ rounded (mod 16) channels"""
  503. return _create_rexnet('rexnetr_300', pretrained, width_mult=3.0, ch_div=16, **kwargs)