hrnet.py 34 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004
  1. """ HRNet
  2. Copied from https://github.com/HRNet/HRNet-Image-Classification
  3. Original header:
  4. Copyright (c) Microsoft
  5. Licensed under the MIT License.
  6. Written by Bin Xiao (Bin.Xiao@microsoft.com)
  7. Modified by Ke Sun (sunk@mail.ustc.edu.cn)
  8. """
  9. import logging
  10. from typing import Dict, List, Type, Optional, Tuple
  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, pretrained_cfg_for_features
  16. from ._features import FeatureInfo
  17. from ._registry import register_model, generate_default_cfgs
  18. from .resnet import BasicBlock, Bottleneck # leveraging ResNet block_types w/ additional features like SE
  19. __all__ = ['HighResolutionNet', 'HighResolutionNetFeatures'] # model_registry will add each entrypoint fn to this
  20. _BN_MOMENTUM = 0.1
  21. _logger = logging.getLogger(__name__)
  22. cfg_cls = dict(
  23. hrnet_w18_small=dict(
  24. stem_width=64,
  25. stage1=dict(
  26. num_modules=1,
  27. num_branches=1,
  28. block_type='BOTTLENECK',
  29. num_blocks=(1,),
  30. num_channels=(32,),
  31. fuse_method='SUM',
  32. ),
  33. stage2=dict(
  34. num_modules=1,
  35. num_branches=2,
  36. block_type='BASIC',
  37. num_blocks=(2, 2),
  38. num_channels=(16, 32),
  39. fuse_method='SUM'
  40. ),
  41. stage3=dict(
  42. num_modules=1,
  43. num_branches=3,
  44. block_type='BASIC',
  45. num_blocks=(2, 2, 2),
  46. num_channels=(16, 32, 64),
  47. fuse_method='SUM'
  48. ),
  49. stage4=dict(
  50. num_modules=1,
  51. num_branches=4,
  52. block_type='BASIC',
  53. num_blocks=(2, 2, 2, 2),
  54. num_channels=(16, 32, 64, 128),
  55. fuse_method='SUM',
  56. ),
  57. ),
  58. hrnet_w18_small_v2=dict(
  59. stem_width=64,
  60. stage1=dict(
  61. num_modules=1,
  62. num_branches=1,
  63. block_type='BOTTLENECK',
  64. num_blocks=(2,),
  65. num_channels=(64,),
  66. fuse_method='SUM',
  67. ),
  68. stage2=dict(
  69. num_modules=1,
  70. num_branches=2,
  71. block_type='BASIC',
  72. num_blocks=(2, 2),
  73. num_channels=(18, 36),
  74. fuse_method='SUM'
  75. ),
  76. stage3=dict(
  77. num_modules=3,
  78. num_branches=3,
  79. block_type='BASIC',
  80. num_blocks=(2, 2, 2),
  81. num_channels=(18, 36, 72),
  82. fuse_method='SUM'
  83. ),
  84. stage4=dict(
  85. num_modules=2,
  86. num_branches=4,
  87. block_type='BASIC',
  88. num_blocks=(2, 2, 2, 2),
  89. num_channels=(18, 36, 72, 144),
  90. fuse_method='SUM',
  91. ),
  92. ),
  93. hrnet_w18=dict(
  94. stem_width=64,
  95. stage1=dict(
  96. num_modules=1,
  97. num_branches=1,
  98. block_type='BOTTLENECK',
  99. num_blocks=(4,),
  100. num_channels=(64,),
  101. fuse_method='SUM',
  102. ),
  103. stage2=dict(
  104. num_modules=1,
  105. num_branches=2,
  106. block_type='BASIC',
  107. num_blocks=(4, 4),
  108. num_channels=(18, 36),
  109. fuse_method='SUM'
  110. ),
  111. stage3=dict(
  112. num_modules=4,
  113. num_branches=3,
  114. block_type='BASIC',
  115. num_blocks=(4, 4, 4),
  116. num_channels=(18, 36, 72),
  117. fuse_method='SUM'
  118. ),
  119. stage4=dict(
  120. num_modules=3,
  121. num_branches=4,
  122. block_type='BASIC',
  123. num_blocks=(4, 4, 4, 4),
  124. num_channels=(18, 36, 72, 144),
  125. fuse_method='SUM',
  126. ),
  127. ),
  128. hrnet_w30=dict(
  129. stem_width=64,
  130. stage1=dict(
  131. num_modules=1,
  132. num_branches=1,
  133. block_type='BOTTLENECK',
  134. num_blocks=(4,),
  135. num_channels=(64,),
  136. fuse_method='SUM',
  137. ),
  138. stage2=dict(
  139. num_modules=1,
  140. num_branches=2,
  141. block_type='BASIC',
  142. num_blocks=(4, 4),
  143. num_channels=(30, 60),
  144. fuse_method='SUM'
  145. ),
  146. stage3=dict(
  147. num_modules=4,
  148. num_branches=3,
  149. block_type='BASIC',
  150. num_blocks=(4, 4, 4),
  151. num_channels=(30, 60, 120),
  152. fuse_method='SUM'
  153. ),
  154. stage4=dict(
  155. num_modules=3,
  156. num_branches=4,
  157. block_type='BASIC',
  158. num_blocks=(4, 4, 4, 4),
  159. num_channels=(30, 60, 120, 240),
  160. fuse_method='SUM',
  161. ),
  162. ),
  163. hrnet_w32=dict(
  164. stem_width=64,
  165. stage1=dict(
  166. num_modules=1,
  167. num_branches=1,
  168. block_type='BOTTLENECK',
  169. num_blocks=(4,),
  170. num_channels=(64,),
  171. fuse_method='SUM',
  172. ),
  173. stage2=dict(
  174. num_modules=1,
  175. num_branches=2,
  176. block_type='BASIC',
  177. num_blocks=(4, 4),
  178. num_channels=(32, 64),
  179. fuse_method='SUM'
  180. ),
  181. stage3=dict(
  182. num_modules=4,
  183. num_branches=3,
  184. block_type='BASIC',
  185. num_blocks=(4, 4, 4),
  186. num_channels=(32, 64, 128),
  187. fuse_method='SUM'
  188. ),
  189. stage4=dict(
  190. num_modules=3,
  191. num_branches=4,
  192. block_type='BASIC',
  193. num_blocks=(4, 4, 4, 4),
  194. num_channels=(32, 64, 128, 256),
  195. fuse_method='SUM',
  196. ),
  197. ),
  198. hrnet_w40=dict(
  199. stem_width=64,
  200. stage1=dict(
  201. num_modules=1,
  202. num_branches=1,
  203. block_type='BOTTLENECK',
  204. num_blocks=(4,),
  205. num_channels=(64,),
  206. fuse_method='SUM',
  207. ),
  208. stage2=dict(
  209. num_modules=1,
  210. num_branches=2,
  211. block_type='BASIC',
  212. num_blocks=(4, 4),
  213. num_channels=(40, 80),
  214. fuse_method='SUM'
  215. ),
  216. stage3=dict(
  217. num_modules=4,
  218. num_branches=3,
  219. block_type='BASIC',
  220. num_blocks=(4, 4, 4),
  221. num_channels=(40, 80, 160),
  222. fuse_method='SUM'
  223. ),
  224. stage4=dict(
  225. num_modules=3,
  226. num_branches=4,
  227. block_type='BASIC',
  228. num_blocks=(4, 4, 4, 4),
  229. num_channels=(40, 80, 160, 320),
  230. fuse_method='SUM',
  231. ),
  232. ),
  233. hrnet_w44=dict(
  234. stem_width=64,
  235. stage1=dict(
  236. num_modules=1,
  237. num_branches=1,
  238. block_type='BOTTLENECK',
  239. num_blocks=(4,),
  240. num_channels=(64,),
  241. fuse_method='SUM',
  242. ),
  243. stage2=dict(
  244. num_modules=1,
  245. num_branches=2,
  246. block_type='BASIC',
  247. num_blocks=(4, 4),
  248. num_channels=(44, 88),
  249. fuse_method='SUM'
  250. ),
  251. stage3=dict(
  252. num_modules=4,
  253. num_branches=3,
  254. block_type='BASIC',
  255. num_blocks=(4, 4, 4),
  256. num_channels=(44, 88, 176),
  257. fuse_method='SUM'
  258. ),
  259. stage4=dict(
  260. num_modules=3,
  261. num_branches=4,
  262. block_type='BASIC',
  263. num_blocks=(4, 4, 4, 4),
  264. num_channels=(44, 88, 176, 352),
  265. fuse_method='SUM',
  266. ),
  267. ),
  268. hrnet_w48=dict(
  269. stem_width=64,
  270. stage1=dict(
  271. num_modules=1,
  272. num_branches=1,
  273. block_type='BOTTLENECK',
  274. num_blocks=(4,),
  275. num_channels=(64,),
  276. fuse_method='SUM',
  277. ),
  278. stage2=dict(
  279. num_modules=1,
  280. num_branches=2,
  281. block_type='BASIC',
  282. num_blocks=(4, 4),
  283. num_channels=(48, 96),
  284. fuse_method='SUM'
  285. ),
  286. stage3=dict(
  287. num_modules=4,
  288. num_branches=3,
  289. block_type='BASIC',
  290. num_blocks=(4, 4, 4),
  291. num_channels=(48, 96, 192),
  292. fuse_method='SUM'
  293. ),
  294. stage4=dict(
  295. num_modules=3,
  296. num_branches=4,
  297. block_type='BASIC',
  298. num_blocks=(4, 4, 4, 4),
  299. num_channels=(48, 96, 192, 384),
  300. fuse_method='SUM',
  301. ),
  302. ),
  303. hrnet_w64=dict(
  304. stem_width=64,
  305. stage1=dict(
  306. num_modules=1,
  307. num_branches=1,
  308. block_type='BOTTLENECK',
  309. num_blocks=(4,),
  310. num_channels=(64,),
  311. fuse_method='SUM',
  312. ),
  313. stage2=dict(
  314. num_modules=1,
  315. num_branches=2,
  316. block_type='BASIC',
  317. num_blocks=(4, 4),
  318. num_channels=(64, 128),
  319. fuse_method='SUM'
  320. ),
  321. stage3=dict(
  322. num_modules=4,
  323. num_branches=3,
  324. block_type='BASIC',
  325. num_blocks=(4, 4, 4),
  326. num_channels=(64, 128, 256),
  327. fuse_method='SUM'
  328. ),
  329. stage4=dict(
  330. num_modules=3,
  331. num_branches=4,
  332. block_type='BASIC',
  333. num_blocks=(4, 4, 4, 4),
  334. num_channels=(64, 128, 256, 512),
  335. fuse_method='SUM',
  336. ),
  337. )
  338. )
  339. class HighResolutionModule(nn.Module):
  340. def __init__(
  341. self,
  342. num_branches: int,
  343. block_types: Type[nn.Module],
  344. num_blocks: Tuple[int, ...],
  345. num_in_chs: List[int],
  346. num_channels: Tuple[int, ...],
  347. fuse_method: str,
  348. multi_scale_output: bool = True,
  349. device=None,
  350. dtype=None,
  351. ):
  352. dd = {'device': device, 'dtype': dtype}
  353. super().__init__()
  354. self._check_branches(
  355. num_branches,
  356. block_types,
  357. num_blocks,
  358. num_in_chs,
  359. num_channels,
  360. )
  361. self.num_in_chs = num_in_chs
  362. self.fuse_method = fuse_method
  363. self.num_branches = num_branches
  364. self.multi_scale_output = multi_scale_output
  365. self.branches = self._make_branches(
  366. num_branches,
  367. block_types,
  368. num_blocks,
  369. num_channels,
  370. **dd,
  371. )
  372. self.fuse_layers = self._make_fuse_layers(**dd)
  373. self.fuse_act = nn.ReLU(False)
  374. def _check_branches(self, num_branches, block_types, num_blocks, num_in_chs, num_channels):
  375. error_msg = ''
  376. if num_branches != len(num_blocks):
  377. error_msg = 'num_branches({}) <> num_blocks({})'.format(num_branches, len(num_blocks))
  378. elif num_branches != len(num_channels):
  379. error_msg = 'num_branches({}) <> num_channels({})'.format(num_branches, len(num_channels))
  380. elif num_branches != len(num_in_chs):
  381. error_msg = 'num_branches({}) <> num_in_chs({})'.format(num_branches, len(num_in_chs))
  382. if error_msg:
  383. _logger.error(error_msg)
  384. raise ValueError(error_msg)
  385. def _make_one_branch(self, branch_index, block_type, num_blocks, num_channels, stride=1, device=None, dtype=None):
  386. dd = {'device': device, 'dtype': dtype}
  387. downsample = None
  388. if stride != 1 or self.num_in_chs[branch_index] != num_channels[branch_index] * block_type.expansion:
  389. downsample = nn.Sequential(
  390. nn.Conv2d(
  391. self.num_in_chs[branch_index],
  392. num_channels[branch_index] * block_type.expansion,
  393. kernel_size=1,
  394. stride=stride,
  395. bias=False,
  396. **dd,
  397. ),
  398. nn.BatchNorm2d(num_channels[branch_index] * block_type.expansion, momentum=_BN_MOMENTUM, **dd),
  399. )
  400. layers = [block_type(self.num_in_chs[branch_index], num_channels[branch_index], stride, downsample, **dd)]
  401. self.num_in_chs[branch_index] = num_channels[branch_index] * block_type.expansion
  402. for i in range(1, num_blocks[branch_index]):
  403. layers.append(block_type(self.num_in_chs[branch_index], num_channels[branch_index], **dd))
  404. return nn.Sequential(*layers)
  405. def _make_branches(self, num_branches, block_type, num_blocks, num_channels, device=None, dtype=None):
  406. dd = {'device': device, 'dtype': dtype}
  407. branches = []
  408. for i in range(num_branches):
  409. branches.append(self._make_one_branch(i, block_type, num_blocks, num_channels, **dd))
  410. return nn.ModuleList(branches)
  411. def _make_fuse_layers(self, device=None, dtype=None):
  412. dd = {'device': device, 'dtype': dtype}
  413. if self.num_branches == 1:
  414. return nn.Identity()
  415. num_branches = self.num_branches
  416. num_in_chs = self.num_in_chs
  417. fuse_layers = []
  418. for i in range(num_branches if self.multi_scale_output else 1):
  419. fuse_layer = []
  420. for j in range(num_branches):
  421. if j > i:
  422. fuse_layer.append(nn.Sequential(
  423. nn.Conv2d(num_in_chs[j], num_in_chs[i], 1, 1, 0, bias=False, **dd),
  424. nn.BatchNorm2d(num_in_chs[i], momentum=_BN_MOMENTUM, **dd),
  425. nn.Upsample(scale_factor=2 ** (j - i), mode='nearest')))
  426. elif j == i:
  427. fuse_layer.append(nn.Identity())
  428. else:
  429. conv3x3s = []
  430. for k in range(i - j):
  431. if k == i - j - 1:
  432. num_out_chs_conv3x3 = num_in_chs[i]
  433. conv3x3s.append(nn.Sequential(
  434. nn.Conv2d(num_in_chs[j], num_out_chs_conv3x3, 3, 2, 1, bias=False, **dd),
  435. nn.BatchNorm2d(num_out_chs_conv3x3, momentum=_BN_MOMENTUM, **dd)
  436. ))
  437. else:
  438. num_out_chs_conv3x3 = num_in_chs[j]
  439. conv3x3s.append(nn.Sequential(
  440. nn.Conv2d(num_in_chs[j], num_out_chs_conv3x3, 3, 2, 1, bias=False, **dd),
  441. nn.BatchNorm2d(num_out_chs_conv3x3, momentum=_BN_MOMENTUM, **dd),
  442. nn.ReLU(False)
  443. ))
  444. fuse_layer.append(nn.Sequential(*conv3x3s))
  445. fuse_layers.append(nn.ModuleList(fuse_layer))
  446. return nn.ModuleList(fuse_layers)
  447. def get_num_in_chs(self):
  448. return self.num_in_chs
  449. def forward(self, x: List[torch.Tensor]) -> List[torch.Tensor]:
  450. if self.num_branches == 1:
  451. return [self.branches[0](x[0])]
  452. for i, branch in enumerate(self.branches):
  453. x[i] = branch(x[i])
  454. x_fuse = []
  455. for i, fuse_outer in enumerate(self.fuse_layers):
  456. y = None
  457. for j, f in enumerate(fuse_outer):
  458. if y is None:
  459. y = f(x[j])
  460. else:
  461. y = y + f(x[j])
  462. x_fuse.append(self.fuse_act(y))
  463. return x_fuse
  464. class SequentialList(nn.Sequential):
  465. def __init__(self, *args):
  466. super().__init__(*args)
  467. def forward(self, x) -> List[torch.Tensor]:
  468. for module in self:
  469. x = module(x)
  470. return x
  471. block_types_dict = {
  472. 'BASIC': BasicBlock,
  473. 'BOTTLENECK': Bottleneck
  474. }
  475. class HighResolutionNet(nn.Module):
  476. def __init__(
  477. self,
  478. cfg: Dict,
  479. in_chans: int = 3,
  480. num_classes: int = 1000,
  481. output_stride: int = 32,
  482. global_pool: str = 'avg',
  483. drop_rate: float = 0.0,
  484. head: str = 'classification',
  485. device=None,
  486. dtype=None,
  487. **kwargs,
  488. ):
  489. dd = {'device': device, 'dtype': dtype}
  490. super().__init__()
  491. self.num_classes = num_classes
  492. self.in_chans = in_chans
  493. assert output_stride == 32 # FIXME support dilation
  494. cfg.update(**kwargs)
  495. stem_width = cfg['stem_width']
  496. self.conv1 = nn.Conv2d(in_chans, stem_width, kernel_size=3, stride=2, padding=1, bias=False, **dd)
  497. self.bn1 = nn.BatchNorm2d(stem_width, momentum=_BN_MOMENTUM, **dd)
  498. self.act1 = nn.ReLU(inplace=True)
  499. self.conv2 = nn.Conv2d(stem_width, 64, kernel_size=3, stride=2, padding=1, bias=False, **dd)
  500. self.bn2 = nn.BatchNorm2d(64, momentum=_BN_MOMENTUM, **dd)
  501. self.act2 = nn.ReLU(inplace=True)
  502. self.stage1_cfg = cfg['stage1']
  503. num_channels = self.stage1_cfg['num_channels'][0]
  504. block_type = block_types_dict[self.stage1_cfg['block_type']]
  505. num_blocks = self.stage1_cfg['num_blocks'][0]
  506. self.layer1 = self._make_layer(block_type, 64, num_channels, num_blocks, **dd)
  507. stage1_out_channel = block_type.expansion * num_channels
  508. self.stage2_cfg = cfg['stage2']
  509. num_channels = self.stage2_cfg['num_channels']
  510. block_type = block_types_dict[self.stage2_cfg['block_type']]
  511. num_channels = [num_channels[i] * block_type.expansion for i in range(len(num_channels))]
  512. self.transition1 = self._make_transition_layer([stage1_out_channel], num_channels, **dd)
  513. self.stage2, pre_stage_channels = self._make_stage(self.stage2_cfg, num_channels, **dd)
  514. self.stage3_cfg = cfg['stage3']
  515. num_channels = self.stage3_cfg['num_channels']
  516. block_type = block_types_dict[self.stage3_cfg['block_type']]
  517. num_channels = [num_channels[i] * block_type.expansion for i in range(len(num_channels))]
  518. self.transition2 = self._make_transition_layer(pre_stage_channels, num_channels, **dd)
  519. self.stage3, pre_stage_channels = self._make_stage(self.stage3_cfg, num_channels, **dd)
  520. self.stage4_cfg = cfg['stage4']
  521. num_channels = self.stage4_cfg['num_channels']
  522. block_type = block_types_dict[self.stage4_cfg['block_type']]
  523. num_channels = [num_channels[i] * block_type.expansion for i in range(len(num_channels))]
  524. self.transition3 = self._make_transition_layer(pre_stage_channels, num_channels, **dd)
  525. self.stage4, pre_stage_channels = self._make_stage(self.stage4_cfg, num_channels, multi_scale_output=True, **dd)
  526. self.head = head
  527. self.head_channels = None # set if _make_head called
  528. head_conv_bias = cfg.pop('head_conv_bias', True)
  529. if head == 'classification':
  530. # Classification Head
  531. self.num_features = self.head_hidden_size = 2048
  532. self.incre_modules, self.downsamp_modules, self.final_layer = self._make_head(
  533. pre_stage_channels,
  534. conv_bias=head_conv_bias,
  535. **dd,
  536. )
  537. self.global_pool, self.head_drop, self.classifier = create_classifier(
  538. self.num_features,
  539. self.num_classes,
  540. pool_type=global_pool,
  541. drop_rate=drop_rate,
  542. **dd,
  543. )
  544. else:
  545. if head == 'incre':
  546. self.num_features = self.head_hidden_size = 2048
  547. self.incre_modules, _, _ = self._make_head(pre_stage_channels, incre_only=True, **dd)
  548. else:
  549. self.num_features = self.head_hidden_size = 256
  550. self.incre_modules = None
  551. self.global_pool = nn.Identity()
  552. self.head_drop = nn.Identity()
  553. self.classifier = nn.Identity()
  554. curr_stride = 2
  555. # module names aren't actually valid here, hook or FeatureNet based extraction would not work
  556. self.feature_info = [dict(num_chs=64, reduction=curr_stride, module='stem')]
  557. for i, c in enumerate(self.head_channels if self.head_channels else num_channels):
  558. curr_stride *= 2
  559. c = c * 4 if self.head_channels else c # head block_type expansion factor of 4
  560. self.feature_info += [dict(num_chs=c, reduction=curr_stride, module=f'stage{i + 1}')]
  561. self.init_weights()
  562. def _make_head(self, pre_stage_channels, incre_only=False, conv_bias=True, device=None, dtype=None):
  563. dd = {'device': device, 'dtype': dtype}
  564. head_block_type = Bottleneck
  565. self.head_channels = [32, 64, 128, 256]
  566. # Increasing the #channels on each resolution
  567. # from C, 2C, 4C, 8C to 128, 256, 512, 1024
  568. incre_modules = []
  569. for i, channels in enumerate(pre_stage_channels):
  570. incre_modules.append(self._make_layer(head_block_type, channels, self.head_channels[i], 1, stride=1, **dd))
  571. incre_modules = nn.ModuleList(incre_modules)
  572. if incre_only:
  573. return incre_modules, None, None
  574. # downsampling modules
  575. downsamp_modules = []
  576. for i in range(len(pre_stage_channels) - 1):
  577. in_channels = self.head_channels[i] * head_block_type.expansion
  578. out_channels = self.head_channels[i + 1] * head_block_type.expansion
  579. downsamp_module = nn.Sequential(
  580. nn.Conv2d(
  581. in_channels=in_channels,
  582. out_channels=out_channels,
  583. kernel_size=3,
  584. stride=2,
  585. padding=1,
  586. bias=conv_bias,
  587. **dd,
  588. ),
  589. nn.BatchNorm2d(out_channels, momentum=_BN_MOMENTUM, **dd),
  590. nn.ReLU(inplace=True)
  591. )
  592. downsamp_modules.append(downsamp_module)
  593. downsamp_modules = nn.ModuleList(downsamp_modules)
  594. final_layer = nn.Sequential(
  595. nn.Conv2d(
  596. in_channels=self.head_channels[3] * head_block_type.expansion,
  597. out_channels=self.num_features,
  598. kernel_size=1,
  599. stride=1,
  600. padding=0,
  601. bias=conv_bias,
  602. **dd,
  603. ),
  604. nn.BatchNorm2d(self.num_features, momentum=_BN_MOMENTUM, **dd),
  605. nn.ReLU(inplace=True)
  606. )
  607. return incre_modules, downsamp_modules, final_layer
  608. def _make_transition_layer(self, num_channels_pre_layer, num_channels_cur_layer, device=None, dtype=None):
  609. dd = {'device': device, 'dtype': dtype}
  610. num_branches_cur = len(num_channels_cur_layer)
  611. num_branches_pre = len(num_channels_pre_layer)
  612. transition_layers = []
  613. for i in range(num_branches_cur):
  614. if i < num_branches_pre:
  615. if num_channels_cur_layer[i] != num_channels_pre_layer[i]:
  616. transition_layers.append(nn.Sequential(
  617. nn.Conv2d(num_channels_pre_layer[i], num_channels_cur_layer[i], 3, 1, 1, bias=False, **dd),
  618. nn.BatchNorm2d(num_channels_cur_layer[i], momentum=_BN_MOMENTUM, **dd),
  619. nn.ReLU(inplace=True)))
  620. else:
  621. transition_layers.append(nn.Identity())
  622. else:
  623. conv3x3s = []
  624. for j in range(i + 1 - num_branches_pre):
  625. _in_chs = num_channels_pre_layer[-1]
  626. _out_chs = num_channels_cur_layer[i] if j == i - num_branches_pre else _in_chs
  627. conv3x3s.append(nn.Sequential(
  628. nn.Conv2d(_in_chs, _out_chs, 3, 2, 1, bias=False, **dd),
  629. nn.BatchNorm2d(_out_chs, momentum=_BN_MOMENTUM, **dd),
  630. nn.ReLU(inplace=True)))
  631. transition_layers.append(nn.Sequential(*conv3x3s))
  632. return nn.ModuleList(transition_layers)
  633. def _make_layer(self, block_type, inplanes, planes, block_types, stride=1, device=None, dtype=None):
  634. dd = {'device': device, 'dtype': dtype}
  635. downsample = None
  636. if stride != 1 or inplanes != planes * block_type.expansion:
  637. downsample = nn.Sequential(
  638. nn.Conv2d(inplanes, planes * block_type.expansion, kernel_size=1, stride=stride, bias=False, **dd),
  639. nn.BatchNorm2d(planes * block_type.expansion, momentum=_BN_MOMENTUM, **dd),
  640. )
  641. layers = [block_type(inplanes, planes, stride, downsample, **dd)]
  642. inplanes = planes * block_type.expansion
  643. for i in range(1, block_types):
  644. layers.append(block_type(inplanes, planes, **dd))
  645. return nn.Sequential(*layers)
  646. def _make_stage(self, layer_config, num_in_chs, multi_scale_output=True, device=None, dtype=None):
  647. num_modules = layer_config['num_modules']
  648. num_branches = layer_config['num_branches']
  649. num_blocks = layer_config['num_blocks']
  650. num_channels = layer_config['num_channels']
  651. block_type = block_types_dict[layer_config['block_type']]
  652. fuse_method = layer_config['fuse_method']
  653. modules = []
  654. for i in range(num_modules):
  655. # multi_scale_output is only used last module
  656. reset_multi_scale_output = multi_scale_output or i < num_modules - 1
  657. modules.append(HighResolutionModule(
  658. num_branches,
  659. block_type,
  660. num_blocks,
  661. num_in_chs,
  662. num_channels,
  663. fuse_method,
  664. reset_multi_scale_output,
  665. device=device,
  666. dtype=dtype,
  667. ))
  668. num_in_chs = modules[-1].get_num_in_chs()
  669. return SequentialList(*modules), num_in_chs
  670. @torch.jit.ignore
  671. def init_weights(self):
  672. for m in self.modules():
  673. if isinstance(m, nn.Conv2d):
  674. nn.init.kaiming_normal_(
  675. m.weight, mode='fan_out', nonlinearity='relu')
  676. elif isinstance(m, nn.BatchNorm2d):
  677. nn.init.constant_(m.weight, 1)
  678. nn.init.constant_(m.bias, 0)
  679. @torch.jit.ignore
  680. def group_matcher(self, coarse=False):
  681. matcher = dict(
  682. stem=r'^conv[12]|bn[12]',
  683. block_types=r'^(?:layer|stage|transition)(\d+)' if coarse else [
  684. (r'^layer(\d+)\.(\d+)', None),
  685. (r'^stage(\d+)\.(\d+)', None),
  686. (r'^transition(\d+)', (99999,)),
  687. ],
  688. )
  689. return matcher
  690. @torch.jit.ignore
  691. def set_grad_checkpointing(self, enable=True):
  692. assert not enable, "gradient checkpointing not supported"
  693. @torch.jit.ignore
  694. def get_classifier(self) -> nn.Module:
  695. return self.classifier
  696. def reset_classifier(self, num_classes: int, global_pool: str = 'avg'):
  697. self.num_classes = num_classes
  698. self.global_pool, self.classifier = create_classifier(
  699. self.num_features, self.num_classes, pool_type=global_pool)
  700. def stages(self, x) -> List[torch.Tensor]:
  701. x = self.layer1(x)
  702. xl = [t(x) for i, t in enumerate(self.transition1)]
  703. yl = self.stage2(xl)
  704. xl = [t(yl[-1]) if not isinstance(t, nn.Identity) else yl[i] for i, t in enumerate(self.transition2)]
  705. yl = self.stage3(xl)
  706. xl = [t(yl[-1]) if not isinstance(t, nn.Identity) else yl[i] for i, t in enumerate(self.transition3)]
  707. yl = self.stage4(xl)
  708. return yl
  709. def forward_features(self, x):
  710. # Stem
  711. x = self.conv1(x)
  712. x = self.bn1(x)
  713. x = self.act1(x)
  714. x = self.conv2(x)
  715. x = self.bn2(x)
  716. x = self.act2(x)
  717. # Stages
  718. yl = self.stages(x)
  719. if self.incre_modules is None or self.downsamp_modules is None:
  720. return yl
  721. y = None
  722. for i, incre in enumerate(self.incre_modules):
  723. if y is None:
  724. y = incre(yl[i])
  725. else:
  726. down = self.downsamp_modules[i - 1]
  727. y = incre(yl[i]) + down.forward(y)
  728. y = self.final_layer(y)
  729. return y
  730. def forward_head(self, x, pre_logits: bool = False):
  731. # Classification Head
  732. x = self.global_pool(x)
  733. x = self.head_drop(x)
  734. return x if pre_logits else self.classifier(x)
  735. def forward(self, x):
  736. y = self.forward_features(x)
  737. x = self.forward_head(y)
  738. return x
  739. class HighResolutionNetFeatures(HighResolutionNet):
  740. """HighResolutionNet feature extraction
  741. The design of HRNet makes it easy to grab feature maps, this class provides a simple wrapper to do so.
  742. It would be more complicated to use the FeatureNet helpers.
  743. The `feature_location=incre` allows grabbing increased channel count features using part of the
  744. classification head. If `feature_location=''` the default HRNet features are returned. First stem
  745. conv is used for stride 2 features.
  746. """
  747. def __init__(
  748. self,
  749. cfg,
  750. in_chans=3,
  751. num_classes=1000,
  752. output_stride=32,
  753. global_pool='avg',
  754. drop_rate=0.0,
  755. feature_location='incre',
  756. out_indices=(0, 1, 2, 3, 4),
  757. **kwargs,
  758. ):
  759. assert feature_location in ('incre', '')
  760. super().__init__(
  761. cfg,
  762. in_chans=in_chans,
  763. num_classes=num_classes,
  764. output_stride=output_stride,
  765. global_pool=global_pool,
  766. drop_rate=drop_rate,
  767. head=feature_location,
  768. **kwargs,
  769. )
  770. self.feature_info = FeatureInfo(self.feature_info, out_indices)
  771. self._out_idx = {f['index'] for f in self.feature_info.get_dicts()}
  772. def forward_features(self, x):
  773. assert False, 'Not supported'
  774. def forward(self, x) -> List[torch.Tensor]:
  775. out = []
  776. x = self.conv1(x)
  777. x = self.bn1(x)
  778. x = self.act1(x)
  779. if 0 in self._out_idx:
  780. out.append(x)
  781. x = self.conv2(x)
  782. x = self.bn2(x)
  783. x = self.act2(x)
  784. x = self.stages(x)
  785. if self.incre_modules is not None:
  786. x = [incre(f) for f, incre in zip(x, self.incre_modules)]
  787. for i, f in enumerate(x):
  788. if i + 1 in self._out_idx:
  789. out.append(f)
  790. return out
  791. def _create_hrnet(variant, pretrained=False, cfg_variant=None, **model_kwargs):
  792. model_cls = HighResolutionNet
  793. features_only = False
  794. kwargs_filter = None
  795. if model_kwargs.pop('features_only', False):
  796. model_cls = HighResolutionNetFeatures
  797. kwargs_filter = ('num_classes', 'global_pool')
  798. features_only = True
  799. cfg_variant = cfg_variant or variant
  800. pretrained_strict = model_kwargs.pop(
  801. 'pretrained_strict',
  802. not features_only and model_kwargs.get('head', 'classification') == 'classification'
  803. )
  804. model = build_model_with_cfg(
  805. model_cls,
  806. variant,
  807. pretrained,
  808. model_cfg=cfg_cls[cfg_variant],
  809. pretrained_strict=pretrained_strict,
  810. kwargs_filter=kwargs_filter,
  811. **model_kwargs,
  812. )
  813. if features_only:
  814. model.pretrained_cfg = pretrained_cfg_for_features(model.default_cfg)
  815. model.default_cfg = model.pretrained_cfg # backwards compat
  816. return model
  817. def _cfg(url='', **kwargs):
  818. return {
  819. 'url': url,
  820. 'num_classes': 1000, 'input_size': (3, 224, 224), 'pool_size': (7, 7),
  821. 'crop_pct': 0.875, 'interpolation': 'bilinear',
  822. 'mean': IMAGENET_DEFAULT_MEAN, 'std': IMAGENET_DEFAULT_STD,
  823. 'first_conv': 'conv1', 'classifier': 'classifier',
  824. 'license': 'mit',
  825. **kwargs
  826. }
  827. default_cfgs = generate_default_cfgs({
  828. 'hrnet_w18_small.gluon_in1k': _cfg(hf_hub_id='timm/', interpolation='bicubic', license='apache-2.0'),
  829. 'hrnet_w18_small.ms_in1k': _cfg(hf_hub_id='timm/'),
  830. 'hrnet_w18_small_v2.gluon_in1k': _cfg(hf_hub_id='timm/', interpolation='bicubic', license='apache-2.0'),
  831. 'hrnet_w18_small_v2.ms_in1k': _cfg(hf_hub_id='timm/'),
  832. 'hrnet_w18.ms_aug_in1k': _cfg(
  833. hf_hub_id='timm/',
  834. crop_pct=0.95,
  835. ),
  836. 'hrnet_w18.ms_in1k': _cfg(hf_hub_id='timm/'),
  837. 'hrnet_w30.ms_in1k': _cfg(hf_hub_id='timm/'),
  838. 'hrnet_w32.ms_in1k': _cfg(hf_hub_id='timm/'),
  839. 'hrnet_w40.ms_in1k': _cfg(hf_hub_id='timm/'),
  840. 'hrnet_w44.ms_in1k': _cfg(hf_hub_id='timm/'),
  841. 'hrnet_w48.ms_in1k': _cfg(hf_hub_id='timm/'),
  842. 'hrnet_w64.ms_in1k': _cfg(hf_hub_id='timm/'),
  843. 'hrnet_w18_ssld.paddle_in1k': _cfg(
  844. hf_hub_id='timm/',
  845. crop_pct=0.95, test_crop_pct=1.0, test_input_size=(3, 288, 288)
  846. ),
  847. 'hrnet_w48_ssld.paddle_in1k': _cfg(
  848. hf_hub_id='timm/',
  849. crop_pct=0.95, test_crop_pct=1.0, test_input_size=(3, 288, 288)
  850. ),
  851. })
  852. @register_model
  853. def hrnet_w18_small(pretrained=False, **kwargs) -> HighResolutionNet:
  854. return _create_hrnet('hrnet_w18_small', pretrained, **kwargs)
  855. @register_model
  856. def hrnet_w18_small_v2(pretrained=False, **kwargs) -> HighResolutionNet:
  857. return _create_hrnet('hrnet_w18_small_v2', pretrained, **kwargs)
  858. @register_model
  859. def hrnet_w18(pretrained=False, **kwargs) -> HighResolutionNet:
  860. return _create_hrnet('hrnet_w18', pretrained, **kwargs)
  861. @register_model
  862. def hrnet_w30(pretrained=False, **kwargs) -> HighResolutionNet:
  863. return _create_hrnet('hrnet_w30', pretrained, **kwargs)
  864. @register_model
  865. def hrnet_w32(pretrained=False, **kwargs) -> HighResolutionNet:
  866. return _create_hrnet('hrnet_w32', pretrained, **kwargs)
  867. @register_model
  868. def hrnet_w40(pretrained=False, **kwargs) -> HighResolutionNet:
  869. return _create_hrnet('hrnet_w40', pretrained, **kwargs)
  870. @register_model
  871. def hrnet_w44(pretrained=False, **kwargs) -> HighResolutionNet:
  872. return _create_hrnet('hrnet_w44', pretrained, **kwargs)
  873. @register_model
  874. def hrnet_w48(pretrained=False, **kwargs) -> HighResolutionNet:
  875. return _create_hrnet('hrnet_w48', pretrained, **kwargs)
  876. @register_model
  877. def hrnet_w64(pretrained=False, **kwargs) -> HighResolutionNet:
  878. return _create_hrnet('hrnet_w64', pretrained, **kwargs)
  879. @register_model
  880. def hrnet_w18_ssld(pretrained=False, **kwargs) -> HighResolutionNet:
  881. kwargs.setdefault('head_conv_bias', False)
  882. return _create_hrnet('hrnet_w18_ssld', cfg_variant='hrnet_w18', pretrained=pretrained, **kwargs)
  883. @register_model
  884. def hrnet_w48_ssld(pretrained=False, **kwargs) -> HighResolutionNet:
  885. kwargs.setdefault('head_conv_bias', False)
  886. return _create_hrnet('hrnet_w48_ssld', cfg_variant='hrnet_w48', pretrained=pretrained, **kwargs)