hrnet.py 34 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019
  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. @torch.jit._overload_method # noqa: F811
  468. def forward(self, x):
  469. # type: (List[torch.Tensor]) -> (List[torch.Tensor])
  470. pass
  471. @torch.jit._overload_method # noqa: F811
  472. def forward(self, x):
  473. # type: (torch.Tensor) -> (List[torch.Tensor])
  474. pass
  475. def forward(self, x) -> List[torch.Tensor]:
  476. for module in self:
  477. x = module(x)
  478. return x
  479. @torch.jit.interface
  480. class ModuleInterface(torch.nn.Module):
  481. def forward(self, input: torch.Tensor) -> torch.Tensor: # `input` has a same name in Sequential forward
  482. pass
  483. block_types_dict = {
  484. 'BASIC': BasicBlock,
  485. 'BOTTLENECK': Bottleneck
  486. }
  487. class HighResolutionNet(nn.Module):
  488. def __init__(
  489. self,
  490. cfg: Dict,
  491. in_chans: int = 3,
  492. num_classes: int = 1000,
  493. output_stride: int = 32,
  494. global_pool: str = 'avg',
  495. drop_rate: float = 0.0,
  496. head: str = 'classification',
  497. device=None,
  498. dtype=None,
  499. **kwargs,
  500. ):
  501. dd = {'device': device, 'dtype': dtype}
  502. super().__init__()
  503. self.num_classes = num_classes
  504. assert output_stride == 32 # FIXME support dilation
  505. cfg.update(**kwargs)
  506. stem_width = cfg['stem_width']
  507. self.conv1 = nn.Conv2d(in_chans, stem_width, kernel_size=3, stride=2, padding=1, bias=False, **dd)
  508. self.bn1 = nn.BatchNorm2d(stem_width, momentum=_BN_MOMENTUM, **dd)
  509. self.act1 = nn.ReLU(inplace=True)
  510. self.conv2 = nn.Conv2d(stem_width, 64, kernel_size=3, stride=2, padding=1, bias=False, **dd)
  511. self.bn2 = nn.BatchNorm2d(64, momentum=_BN_MOMENTUM, **dd)
  512. self.act2 = nn.ReLU(inplace=True)
  513. self.stage1_cfg = cfg['stage1']
  514. num_channels = self.stage1_cfg['num_channels'][0]
  515. block_type = block_types_dict[self.stage1_cfg['block_type']]
  516. num_blocks = self.stage1_cfg['num_blocks'][0]
  517. self.layer1 = self._make_layer(block_type, 64, num_channels, num_blocks, **dd)
  518. stage1_out_channel = block_type.expansion * num_channels
  519. self.stage2_cfg = cfg['stage2']
  520. num_channels = self.stage2_cfg['num_channels']
  521. block_type = block_types_dict[self.stage2_cfg['block_type']]
  522. num_channels = [num_channels[i] * block_type.expansion for i in range(len(num_channels))]
  523. self.transition1 = self._make_transition_layer([stage1_out_channel], num_channels, **dd)
  524. self.stage2, pre_stage_channels = self._make_stage(self.stage2_cfg, num_channels, **dd)
  525. self.stage3_cfg = cfg['stage3']
  526. num_channels = self.stage3_cfg['num_channels']
  527. block_type = block_types_dict[self.stage3_cfg['block_type']]
  528. num_channels = [num_channels[i] * block_type.expansion for i in range(len(num_channels))]
  529. self.transition2 = self._make_transition_layer(pre_stage_channels, num_channels, **dd)
  530. self.stage3, pre_stage_channels = self._make_stage(self.stage3_cfg, num_channels, **dd)
  531. self.stage4_cfg = cfg['stage4']
  532. num_channels = self.stage4_cfg['num_channels']
  533. block_type = block_types_dict[self.stage4_cfg['block_type']]
  534. num_channels = [num_channels[i] * block_type.expansion for i in range(len(num_channels))]
  535. self.transition3 = self._make_transition_layer(pre_stage_channels, num_channels, **dd)
  536. self.stage4, pre_stage_channels = self._make_stage(self.stage4_cfg, num_channels, multi_scale_output=True, **dd)
  537. self.head = head
  538. self.head_channels = None # set if _make_head called
  539. head_conv_bias = cfg.pop('head_conv_bias', True)
  540. if head == 'classification':
  541. # Classification Head
  542. self.num_features = self.head_hidden_size = 2048
  543. self.incre_modules, self.downsamp_modules, self.final_layer = self._make_head(
  544. pre_stage_channels,
  545. conv_bias=head_conv_bias,
  546. **dd,
  547. )
  548. self.global_pool, self.head_drop, self.classifier = create_classifier(
  549. self.num_features,
  550. self.num_classes,
  551. pool_type=global_pool,
  552. drop_rate=drop_rate,
  553. **dd,
  554. )
  555. else:
  556. if head == 'incre':
  557. self.num_features = self.head_hidden_size = 2048
  558. self.incre_modules, _, _ = self._make_head(pre_stage_channels, incre_only=True, **dd)
  559. else:
  560. self.num_features = self.head_hidden_size = 256
  561. self.incre_modules = None
  562. self.global_pool = nn.Identity()
  563. self.head_drop = nn.Identity()
  564. self.classifier = nn.Identity()
  565. curr_stride = 2
  566. # module names aren't actually valid here, hook or FeatureNet based extraction would not work
  567. self.feature_info = [dict(num_chs=64, reduction=curr_stride, module='stem')]
  568. for i, c in enumerate(self.head_channels if self.head_channels else num_channels):
  569. curr_stride *= 2
  570. c = c * 4 if self.head_channels else c # head block_type expansion factor of 4
  571. self.feature_info += [dict(num_chs=c, reduction=curr_stride, module=f'stage{i + 1}')]
  572. self.init_weights()
  573. def _make_head(self, pre_stage_channels, incre_only=False, conv_bias=True, device=None, dtype=None):
  574. dd = {'device': device, 'dtype': dtype}
  575. head_block_type = Bottleneck
  576. self.head_channels = [32, 64, 128, 256]
  577. # Increasing the #channels on each resolution
  578. # from C, 2C, 4C, 8C to 128, 256, 512, 1024
  579. incre_modules = []
  580. for i, channels in enumerate(pre_stage_channels):
  581. incre_modules.append(self._make_layer(head_block_type, channels, self.head_channels[i], 1, stride=1, **dd))
  582. incre_modules = nn.ModuleList(incre_modules)
  583. if incre_only:
  584. return incre_modules, None, None
  585. # downsampling modules
  586. downsamp_modules = []
  587. for i in range(len(pre_stage_channels) - 1):
  588. in_channels = self.head_channels[i] * head_block_type.expansion
  589. out_channels = self.head_channels[i + 1] * head_block_type.expansion
  590. downsamp_module = nn.Sequential(
  591. nn.Conv2d(
  592. in_channels=in_channels,
  593. out_channels=out_channels,
  594. kernel_size=3,
  595. stride=2,
  596. padding=1,
  597. bias=conv_bias,
  598. **dd,
  599. ),
  600. nn.BatchNorm2d(out_channels, momentum=_BN_MOMENTUM, **dd),
  601. nn.ReLU(inplace=True)
  602. )
  603. downsamp_modules.append(downsamp_module)
  604. downsamp_modules = nn.ModuleList(downsamp_modules)
  605. final_layer = nn.Sequential(
  606. nn.Conv2d(
  607. in_channels=self.head_channels[3] * head_block_type.expansion,
  608. out_channels=self.num_features,
  609. kernel_size=1,
  610. stride=1,
  611. padding=0,
  612. bias=conv_bias,
  613. **dd,
  614. ),
  615. nn.BatchNorm2d(self.num_features, momentum=_BN_MOMENTUM, **dd),
  616. nn.ReLU(inplace=True)
  617. )
  618. return incre_modules, downsamp_modules, final_layer
  619. def _make_transition_layer(self, num_channels_pre_layer, num_channels_cur_layer, device=None, dtype=None):
  620. dd = {'device': device, 'dtype': dtype}
  621. num_branches_cur = len(num_channels_cur_layer)
  622. num_branches_pre = len(num_channels_pre_layer)
  623. transition_layers = []
  624. for i in range(num_branches_cur):
  625. if i < num_branches_pre:
  626. if num_channels_cur_layer[i] != num_channels_pre_layer[i]:
  627. transition_layers.append(nn.Sequential(
  628. nn.Conv2d(num_channels_pre_layer[i], num_channels_cur_layer[i], 3, 1, 1, bias=False, **dd),
  629. nn.BatchNorm2d(num_channels_cur_layer[i], momentum=_BN_MOMENTUM, **dd),
  630. nn.ReLU(inplace=True)))
  631. else:
  632. transition_layers.append(nn.Identity())
  633. else:
  634. conv3x3s = []
  635. for j in range(i + 1 - num_branches_pre):
  636. _in_chs = num_channels_pre_layer[-1]
  637. _out_chs = num_channels_cur_layer[i] if j == i - num_branches_pre else _in_chs
  638. conv3x3s.append(nn.Sequential(
  639. nn.Conv2d(_in_chs, _out_chs, 3, 2, 1, bias=False, **dd),
  640. nn.BatchNorm2d(_out_chs, momentum=_BN_MOMENTUM, **dd),
  641. nn.ReLU(inplace=True)))
  642. transition_layers.append(nn.Sequential(*conv3x3s))
  643. return nn.ModuleList(transition_layers)
  644. def _make_layer(self, block_type, inplanes, planes, block_types, stride=1, device=None, dtype=None):
  645. dd = {'device': device, 'dtype': dtype}
  646. downsample = None
  647. if stride != 1 or inplanes != planes * block_type.expansion:
  648. downsample = nn.Sequential(
  649. nn.Conv2d(inplanes, planes * block_type.expansion, kernel_size=1, stride=stride, bias=False, **dd),
  650. nn.BatchNorm2d(planes * block_type.expansion, momentum=_BN_MOMENTUM, **dd),
  651. )
  652. layers = [block_type(inplanes, planes, stride, downsample, **dd)]
  653. inplanes = planes * block_type.expansion
  654. for i in range(1, block_types):
  655. layers.append(block_type(inplanes, planes, **dd))
  656. return nn.Sequential(*layers)
  657. def _make_stage(self, layer_config, num_in_chs, multi_scale_output=True, device=None, dtype=None):
  658. num_modules = layer_config['num_modules']
  659. num_branches = layer_config['num_branches']
  660. num_blocks = layer_config['num_blocks']
  661. num_channels = layer_config['num_channels']
  662. block_type = block_types_dict[layer_config['block_type']]
  663. fuse_method = layer_config['fuse_method']
  664. modules = []
  665. for i in range(num_modules):
  666. # multi_scale_output is only used last module
  667. reset_multi_scale_output = multi_scale_output or i < num_modules - 1
  668. modules.append(HighResolutionModule(
  669. num_branches,
  670. block_type,
  671. num_blocks,
  672. num_in_chs,
  673. num_channels,
  674. fuse_method,
  675. reset_multi_scale_output,
  676. device=device,
  677. dtype=dtype,
  678. ))
  679. num_in_chs = modules[-1].get_num_in_chs()
  680. return SequentialList(*modules), num_in_chs
  681. @torch.jit.ignore
  682. def init_weights(self):
  683. for m in self.modules():
  684. if isinstance(m, nn.Conv2d):
  685. nn.init.kaiming_normal_(
  686. m.weight, mode='fan_out', nonlinearity='relu')
  687. elif isinstance(m, nn.BatchNorm2d):
  688. nn.init.constant_(m.weight, 1)
  689. nn.init.constant_(m.bias, 0)
  690. @torch.jit.ignore
  691. def group_matcher(self, coarse=False):
  692. matcher = dict(
  693. stem=r'^conv[12]|bn[12]',
  694. block_types=r'^(?:layer|stage|transition)(\d+)' if coarse else [
  695. (r'^layer(\d+)\.(\d+)', None),
  696. (r'^stage(\d+)\.(\d+)', None),
  697. (r'^transition(\d+)', (99999,)),
  698. ],
  699. )
  700. return matcher
  701. @torch.jit.ignore
  702. def set_grad_checkpointing(self, enable=True):
  703. assert not enable, "gradient checkpointing not supported"
  704. @torch.jit.ignore
  705. def get_classifier(self) -> nn.Module:
  706. return self.classifier
  707. def reset_classifier(self, num_classes: int, global_pool: str = 'avg'):
  708. self.num_classes = num_classes
  709. self.global_pool, self.classifier = create_classifier(
  710. self.num_features, self.num_classes, pool_type=global_pool)
  711. def stages(self, x) -> List[torch.Tensor]:
  712. x = self.layer1(x)
  713. xl = [t(x) for i, t in enumerate(self.transition1)]
  714. yl = self.stage2(xl)
  715. xl = [t(yl[-1]) if not isinstance(t, nn.Identity) else yl[i] for i, t in enumerate(self.transition2)]
  716. yl = self.stage3(xl)
  717. xl = [t(yl[-1]) if not isinstance(t, nn.Identity) else yl[i] for i, t in enumerate(self.transition3)]
  718. yl = self.stage4(xl)
  719. return yl
  720. def forward_features(self, x):
  721. # Stem
  722. x = self.conv1(x)
  723. x = self.bn1(x)
  724. x = self.act1(x)
  725. x = self.conv2(x)
  726. x = self.bn2(x)
  727. x = self.act2(x)
  728. # Stages
  729. yl = self.stages(x)
  730. if self.incre_modules is None or self.downsamp_modules is None:
  731. return yl
  732. y = None
  733. for i, incre in enumerate(self.incre_modules):
  734. if y is None:
  735. y = incre(yl[i])
  736. else:
  737. down: ModuleInterface = self.downsamp_modules[i - 1] # needed for torchscript module indexing
  738. y = incre(yl[i]) + down.forward(y)
  739. y = self.final_layer(y)
  740. return y
  741. def forward_head(self, x, pre_logits: bool = False):
  742. # Classification Head
  743. x = self.global_pool(x)
  744. x = self.head_drop(x)
  745. return x if pre_logits else self.classifier(x)
  746. def forward(self, x):
  747. y = self.forward_features(x)
  748. x = self.forward_head(y)
  749. return x
  750. class HighResolutionNetFeatures(HighResolutionNet):
  751. """HighResolutionNet feature extraction
  752. The design of HRNet makes it easy to grab feature maps, this class provides a simple wrapper to do so.
  753. It would be more complicated to use the FeatureNet helpers.
  754. The `feature_location=incre` allows grabbing increased channel count features using part of the
  755. classification head. If `feature_location=''` the default HRNet features are returned. First stem
  756. conv is used for stride 2 features.
  757. """
  758. def __init__(
  759. self,
  760. cfg,
  761. in_chans=3,
  762. num_classes=1000,
  763. output_stride=32,
  764. global_pool='avg',
  765. drop_rate=0.0,
  766. feature_location='incre',
  767. out_indices=(0, 1, 2, 3, 4),
  768. **kwargs,
  769. ):
  770. assert feature_location in ('incre', '')
  771. super().__init__(
  772. cfg,
  773. in_chans=in_chans,
  774. num_classes=num_classes,
  775. output_stride=output_stride,
  776. global_pool=global_pool,
  777. drop_rate=drop_rate,
  778. head=feature_location,
  779. **kwargs,
  780. )
  781. self.feature_info = FeatureInfo(self.feature_info, out_indices)
  782. self._out_idx = {f['index'] for f in self.feature_info.get_dicts()}
  783. def forward_features(self, x):
  784. assert False, 'Not supported'
  785. def forward(self, x) -> List[torch.Tensor]:
  786. out = []
  787. x = self.conv1(x)
  788. x = self.bn1(x)
  789. x = self.act1(x)
  790. if 0 in self._out_idx:
  791. out.append(x)
  792. x = self.conv2(x)
  793. x = self.bn2(x)
  794. x = self.act2(x)
  795. x = self.stages(x)
  796. if self.incre_modules is not None:
  797. x = [incre(f) for f, incre in zip(x, self.incre_modules)]
  798. for i, f in enumerate(x):
  799. if i + 1 in self._out_idx:
  800. out.append(f)
  801. return out
  802. def _create_hrnet(variant, pretrained=False, cfg_variant=None, **model_kwargs):
  803. model_cls = HighResolutionNet
  804. features_only = False
  805. kwargs_filter = None
  806. if model_kwargs.pop('features_only', False):
  807. model_cls = HighResolutionNetFeatures
  808. kwargs_filter = ('num_classes', 'global_pool')
  809. features_only = True
  810. cfg_variant = cfg_variant or variant
  811. pretrained_strict = model_kwargs.pop(
  812. 'pretrained_strict',
  813. not features_only and model_kwargs.get('head', 'classification') == 'classification'
  814. )
  815. model = build_model_with_cfg(
  816. model_cls,
  817. variant,
  818. pretrained,
  819. model_cfg=cfg_cls[cfg_variant],
  820. pretrained_strict=pretrained_strict,
  821. kwargs_filter=kwargs_filter,
  822. **model_kwargs,
  823. )
  824. if features_only:
  825. model.pretrained_cfg = pretrained_cfg_for_features(model.default_cfg)
  826. model.default_cfg = model.pretrained_cfg # backwards compat
  827. return model
  828. def _cfg(url='', **kwargs):
  829. return {
  830. 'url': url,
  831. 'num_classes': 1000, 'input_size': (3, 224, 224), 'pool_size': (7, 7),
  832. 'crop_pct': 0.875, 'interpolation': 'bilinear',
  833. 'mean': IMAGENET_DEFAULT_MEAN, 'std': IMAGENET_DEFAULT_STD,
  834. 'first_conv': 'conv1', 'classifier': 'classifier',
  835. 'license': 'mit',
  836. **kwargs
  837. }
  838. default_cfgs = generate_default_cfgs({
  839. 'hrnet_w18_small.gluon_in1k': _cfg(hf_hub_id='timm/', interpolation='bicubic', license='apache-2.0'),
  840. 'hrnet_w18_small.ms_in1k': _cfg(hf_hub_id='timm/'),
  841. 'hrnet_w18_small_v2.gluon_in1k': _cfg(hf_hub_id='timm/', interpolation='bicubic', license='apache-2.0'),
  842. 'hrnet_w18_small_v2.ms_in1k': _cfg(hf_hub_id='timm/'),
  843. 'hrnet_w18.ms_aug_in1k': _cfg(
  844. hf_hub_id='timm/',
  845. crop_pct=0.95,
  846. ),
  847. 'hrnet_w18.ms_in1k': _cfg(hf_hub_id='timm/'),
  848. 'hrnet_w30.ms_in1k': _cfg(hf_hub_id='timm/'),
  849. 'hrnet_w32.ms_in1k': _cfg(hf_hub_id='timm/'),
  850. 'hrnet_w40.ms_in1k': _cfg(hf_hub_id='timm/'),
  851. 'hrnet_w44.ms_in1k': _cfg(hf_hub_id='timm/'),
  852. 'hrnet_w48.ms_in1k': _cfg(hf_hub_id='timm/'),
  853. 'hrnet_w64.ms_in1k': _cfg(hf_hub_id='timm/'),
  854. 'hrnet_w18_ssld.paddle_in1k': _cfg(
  855. hf_hub_id='timm/',
  856. crop_pct=0.95, test_crop_pct=1.0, test_input_size=(3, 288, 288)
  857. ),
  858. 'hrnet_w48_ssld.paddle_in1k': _cfg(
  859. hf_hub_id='timm/',
  860. crop_pct=0.95, test_crop_pct=1.0, test_input_size=(3, 288, 288)
  861. ),
  862. })
  863. @register_model
  864. def hrnet_w18_small(pretrained=False, **kwargs) -> HighResolutionNet:
  865. return _create_hrnet('hrnet_w18_small', pretrained, **kwargs)
  866. @register_model
  867. def hrnet_w18_small_v2(pretrained=False, **kwargs) -> HighResolutionNet:
  868. return _create_hrnet('hrnet_w18_small_v2', pretrained, **kwargs)
  869. @register_model
  870. def hrnet_w18(pretrained=False, **kwargs) -> HighResolutionNet:
  871. return _create_hrnet('hrnet_w18', pretrained, **kwargs)
  872. @register_model
  873. def hrnet_w30(pretrained=False, **kwargs) -> HighResolutionNet:
  874. return _create_hrnet('hrnet_w30', pretrained, **kwargs)
  875. @register_model
  876. def hrnet_w32(pretrained=False, **kwargs) -> HighResolutionNet:
  877. return _create_hrnet('hrnet_w32', pretrained, **kwargs)
  878. @register_model
  879. def hrnet_w40(pretrained=False, **kwargs) -> HighResolutionNet:
  880. return _create_hrnet('hrnet_w40', pretrained, **kwargs)
  881. @register_model
  882. def hrnet_w44(pretrained=False, **kwargs) -> HighResolutionNet:
  883. return _create_hrnet('hrnet_w44', pretrained, **kwargs)
  884. @register_model
  885. def hrnet_w48(pretrained=False, **kwargs) -> HighResolutionNet:
  886. return _create_hrnet('hrnet_w48', pretrained, **kwargs)
  887. @register_model
  888. def hrnet_w64(pretrained=False, **kwargs) -> HighResolutionNet:
  889. return _create_hrnet('hrnet_w64', pretrained, **kwargs)
  890. @register_model
  891. def hrnet_w18_ssld(pretrained=False, **kwargs) -> HighResolutionNet:
  892. kwargs.setdefault('head_conv_bias', False)
  893. return _create_hrnet('hrnet_w18_ssld', cfg_variant='hrnet_w18', pretrained=pretrained, **kwargs)
  894. @register_model
  895. def hrnet_w48_ssld(pretrained=False, **kwargs) -> HighResolutionNet:
  896. kwargs.setdefault('head_conv_bias', False)
  897. return _create_hrnet('hrnet_w48_ssld', cfg_variant='hrnet_w48', pretrained=pretrained, **kwargs)