resnetv2.py 45 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191
  1. """Pre-Activation ResNet v2 with GroupNorm and Weight Standardization.
  2. A PyTorch implementation of ResNetV2 adapted from the Google Big-Transfer (BiT) source code
  3. at https://github.com/google-research/big_transfer to match timm interfaces. The BiT weights have
  4. been included here as pretrained models from their original .NPZ checkpoints.
  5. Additionally, supports non pre-activation bottleneck for use as a backbone for Vision Transformers (ViT) and
  6. extra padding support to allow porting of official Hybrid ResNet pretrained weights from
  7. https://github.com/google-research/vision_transformer
  8. Thanks to the Google team for the above two repositories and associated papers:
  9. * Big Transfer (BiT): General Visual Representation Learning - https://arxiv.org/abs/1912.11370
  10. * An Image is Worth 16x16 Words: Transformers for Image Recognition at Scale - https://arxiv.org/abs/2010.11929
  11. * Knowledge distillation: A good teacher is patient and consistent - https://arxiv.org/abs/2106.05237
  12. Original copyright of Google code below, modifications by Ross Wightman, Copyright 2020.
  13. """
  14. # Copyright 2020 Google LLC
  15. #
  16. # Licensed under the Apache License, Version 2.0 (the "License");
  17. # you may not use this file except in compliance with the License.
  18. # You may obtain a copy of the License at
  19. #
  20. # http://www.apache.org/licenses/LICENSE-2.0
  21. #
  22. # Unless required by applicable law or agreed to in writing, software
  23. # distributed under the License is distributed on an "AS IS" BASIS,
  24. # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  25. # See the License for the specific language governing permissions and
  26. # limitations under the License.
  27. from collections import OrderedDict # pylint: disable=g-importing-member
  28. from functools import partial
  29. from typing import Any, Callable, Dict, List, Optional, Tuple, Union
  30. import torch
  31. import torch.nn as nn
  32. from timm.data import IMAGENET_INCEPTION_MEAN, IMAGENET_INCEPTION_STD
  33. from timm.layers import GroupNormAct, BatchNormAct2d, EvoNorm2dS0, FilterResponseNormTlu2d, ClassifierHead, \
  34. DropPath, calculate_drop_path_rates, AvgPool2dSame, create_pool2d, StdConv2d, create_conv2d, get_act_layer, get_norm_act_layer, make_divisible
  35. from ._builder import build_model_with_cfg
  36. from ._features import feature_take_indices
  37. from ._manipulate import checkpoint_seq, named_apply, adapt_input_conv
  38. from ._registry import generate_default_cfgs, register_model, register_model_deprecations
  39. __all__ = ['ResNetV2'] # model_registry will add each entrypoint fn to this
  40. class PreActBasic(nn.Module):
  41. """Pre-activation basic block (not in typical 'v2' implementations)."""
  42. def __init__(
  43. self,
  44. in_chs: int,
  45. out_chs: Optional[int] = None,
  46. bottle_ratio: float = 1.0,
  47. stride: int = 1,
  48. dilation: int = 1,
  49. first_dilation: Optional[int] = None,
  50. groups: int = 1,
  51. act_layer: Optional[Callable] = None,
  52. conv_layer: Optional[Callable] = None,
  53. norm_layer: Optional[Callable] = None,
  54. proj_layer: Optional[Callable] = None,
  55. drop_path_rate: float = 0.,
  56. device=None,
  57. dtype=None,
  58. ):
  59. """Initialize PreActBasic block.
  60. Args:
  61. in_chs: Input channels.
  62. out_chs: Output channels.
  63. bottle_ratio: Bottleneck ratio (not used in basic block).
  64. stride: Stride for convolution.
  65. dilation: Dilation rate.
  66. first_dilation: First dilation rate.
  67. groups: Group convolution size.
  68. act_layer: Activation layer type.
  69. conv_layer: Convolution layer type.
  70. norm_layer: Normalization layer type.
  71. proj_layer: Projection/downsampling layer type.
  72. drop_path_rate: Stochastic depth drop rate.
  73. """
  74. dd = {'device': device, 'dtype': dtype}
  75. super().__init__()
  76. first_dilation = first_dilation or dilation
  77. conv_layer = conv_layer or StdConv2d
  78. norm_layer = norm_layer or partial(GroupNormAct, num_groups=32)
  79. out_chs = out_chs or in_chs
  80. mid_chs = make_divisible(out_chs * bottle_ratio)
  81. if proj_layer is not None and (stride != 1 or first_dilation != dilation or in_chs != out_chs):
  82. self.downsample = proj_layer(
  83. in_chs,
  84. out_chs,
  85. stride=stride,
  86. dilation=dilation,
  87. first_dilation=first_dilation,
  88. preact=True,
  89. conv_layer=conv_layer,
  90. norm_layer=norm_layer,
  91. **dd,
  92. )
  93. else:
  94. self.downsample = None
  95. self.norm1 = norm_layer(in_chs, **dd)
  96. self.conv1 = conv_layer(in_chs, mid_chs, 3, stride=stride, dilation=first_dilation, groups=groups, **dd)
  97. self.norm2 = norm_layer(mid_chs, **dd)
  98. self.conv2 = conv_layer(mid_chs, out_chs, 3, dilation=dilation, groups=groups, **dd)
  99. self.drop_path = DropPath(drop_path_rate) if drop_path_rate > 0 else nn.Identity()
  100. def zero_init_last(self) -> None:
  101. """Zero-initialize the last convolution weight (not applicable to basic block)."""
  102. nn.init.zeros_(self.conv2.weight)
  103. def forward(self, x: torch.Tensor) -> torch.Tensor:
  104. """Forward pass.
  105. Args:
  106. x: Input tensor.
  107. Returns:
  108. Output tensor.
  109. """
  110. x_preact = self.norm1(x)
  111. # shortcut branch
  112. shortcut = x
  113. if self.downsample is not None:
  114. shortcut = self.downsample(x_preact)
  115. # residual branch
  116. x = self.conv1(x_preact)
  117. x = self.conv2(self.norm2(x))
  118. x = self.drop_path(x)
  119. return x + shortcut
  120. class PreActBottleneck(nn.Module):
  121. """Pre-activation (v2) bottleneck block.
  122. Follows the implementation of "Identity Mappings in Deep Residual Networks":
  123. https://github.com/KaimingHe/resnet-1k-layers/blob/master/resnet-pre-act.lua
  124. Except it puts the stride on 3x3 conv when available.
  125. """
  126. def __init__(
  127. self,
  128. in_chs: int,
  129. out_chs: Optional[int] = None,
  130. bottle_ratio: float = 0.25,
  131. stride: int = 1,
  132. dilation: int = 1,
  133. first_dilation: Optional[int] = None,
  134. groups: int = 1,
  135. act_layer: Optional[Callable] = None,
  136. conv_layer: Optional[Callable] = None,
  137. norm_layer: Optional[Callable] = None,
  138. proj_layer: Optional[Callable] = None,
  139. drop_path_rate: float = 0.,
  140. device=None,
  141. dtype=None,
  142. ):
  143. """Initialize PreActBottleneck block.
  144. Args:
  145. in_chs: Input channels.
  146. out_chs: Output channels.
  147. bottle_ratio: Bottleneck ratio.
  148. stride: Stride for convolution.
  149. dilation: Dilation rate.
  150. first_dilation: First dilation rate.
  151. groups: Group convolution size.
  152. act_layer: Activation layer type.
  153. conv_layer: Convolution layer type.
  154. norm_layer: Normalization layer type.
  155. proj_layer: Projection/downsampling layer type.
  156. drop_path_rate: Stochastic depth drop rate.
  157. """
  158. dd = {'device': device, 'dtype': dtype}
  159. super().__init__()
  160. first_dilation = first_dilation or dilation
  161. conv_layer = conv_layer or StdConv2d
  162. norm_layer = norm_layer or partial(GroupNormAct, num_groups=32)
  163. out_chs = out_chs or in_chs
  164. mid_chs = make_divisible(out_chs * bottle_ratio)
  165. if proj_layer is not None:
  166. self.downsample = proj_layer(
  167. in_chs,
  168. out_chs,
  169. stride=stride,
  170. dilation=dilation,
  171. first_dilation=first_dilation,
  172. preact=True,
  173. conv_layer=conv_layer,
  174. norm_layer=norm_layer,
  175. **dd,
  176. )
  177. else:
  178. self.downsample = None
  179. self.norm1 = norm_layer(in_chs, **dd)
  180. self.conv1 = conv_layer(in_chs, mid_chs, 1, **dd)
  181. self.norm2 = norm_layer(mid_chs, **dd)
  182. self.conv2 = conv_layer(mid_chs, mid_chs, 3, stride=stride, dilation=first_dilation, groups=groups, **dd)
  183. self.norm3 = norm_layer(mid_chs, **dd)
  184. self.conv3 = conv_layer(mid_chs, out_chs, 1, **dd)
  185. self.drop_path = DropPath(drop_path_rate) if drop_path_rate > 0 else nn.Identity()
  186. def zero_init_last(self) -> None:
  187. """Zero-initialize the last convolution weight."""
  188. nn.init.zeros_(self.conv3.weight)
  189. def forward(self, x: torch.Tensor) -> torch.Tensor:
  190. """Forward pass.
  191. Args:
  192. x: Input tensor.
  193. Returns:
  194. Output tensor.
  195. """
  196. x_preact = self.norm1(x)
  197. # shortcut branch
  198. shortcut = x
  199. if self.downsample is not None:
  200. shortcut = self.downsample(x_preact)
  201. # residual branch
  202. x = self.conv1(x_preact)
  203. x = self.conv2(self.norm2(x))
  204. x = self.conv3(self.norm3(x))
  205. x = self.drop_path(x)
  206. return x + shortcut
  207. class Bottleneck(nn.Module):
  208. """Non Pre-activation bottleneck block, equiv to V1.5/V1b Bottleneck. Used for ViT.
  209. """
  210. def __init__(
  211. self,
  212. in_chs: int,
  213. out_chs: Optional[int] = None,
  214. bottle_ratio: float = 0.25,
  215. stride: int = 1,
  216. dilation: int = 1,
  217. first_dilation: Optional[int] = None,
  218. groups: int = 1,
  219. act_layer: Optional[Callable] = None,
  220. conv_layer: Optional[Callable] = None,
  221. norm_layer: Optional[Callable] = None,
  222. proj_layer: Optional[Callable] = None,
  223. drop_path_rate: float = 0.,
  224. device=None,
  225. dtype=None,
  226. ):
  227. dd = {'device': device, 'dtype': dtype}
  228. super().__init__()
  229. first_dilation = first_dilation or dilation
  230. act_layer = act_layer or nn.ReLU
  231. conv_layer = conv_layer or StdConv2d
  232. norm_layer = norm_layer or partial(GroupNormAct, num_groups=32)
  233. out_chs = out_chs or in_chs
  234. mid_chs = make_divisible(out_chs * bottle_ratio)
  235. if proj_layer is not None:
  236. self.downsample = proj_layer(
  237. in_chs,
  238. out_chs,
  239. stride=stride,
  240. dilation=dilation,
  241. preact=False,
  242. conv_layer=conv_layer,
  243. norm_layer=norm_layer,
  244. **dd,
  245. )
  246. else:
  247. self.downsample = None
  248. self.conv1 = conv_layer(in_chs, mid_chs, 1, **dd)
  249. self.norm1 = norm_layer(mid_chs, **dd)
  250. self.conv2 = conv_layer(mid_chs, mid_chs, 3, stride=stride, dilation=first_dilation, groups=groups, **dd)
  251. self.norm2 = norm_layer(mid_chs, **dd)
  252. self.conv3 = conv_layer(mid_chs, out_chs, 1, **dd)
  253. self.norm3 = norm_layer(out_chs, apply_act=False, **dd)
  254. self.drop_path = DropPath(drop_path_rate) if drop_path_rate > 0 else nn.Identity()
  255. self.act3 = act_layer(inplace=True)
  256. def zero_init_last(self) -> None:
  257. """Zero-initialize the last batch norm weight."""
  258. if getattr(self.norm3, 'weight', None) is not None:
  259. nn.init.zeros_(self.norm3.weight)
  260. def forward(self, x: torch.Tensor) -> torch.Tensor:
  261. """Forward pass.
  262. Args:
  263. x: Input tensor.
  264. Returns:
  265. Output tensor.
  266. """
  267. # shortcut branch
  268. shortcut = x
  269. if self.downsample is not None:
  270. shortcut = self.downsample(x)
  271. # residual
  272. x = self.conv1(x)
  273. x = self.norm1(x)
  274. x = self.conv2(x)
  275. x = self.norm2(x)
  276. x = self.conv3(x)
  277. x = self.norm3(x)
  278. x = self.drop_path(x)
  279. x = self.act3(x + shortcut)
  280. return x
  281. class DownsampleConv(nn.Module):
  282. """1x1 convolution downsampling module."""
  283. def __init__(
  284. self,
  285. in_chs: int,
  286. out_chs: int,
  287. stride: int = 1,
  288. dilation: int = 1,
  289. first_dilation: Optional[int] = None,
  290. preact: bool = True,
  291. conv_layer: Optional[Callable] = None,
  292. norm_layer: Optional[Callable] = None,
  293. device=None,
  294. dtype=None,
  295. ):
  296. dd = {'device': device, 'dtype': dtype}
  297. super().__init__()
  298. self.conv = conv_layer(in_chs, out_chs, 1, stride=stride, **dd)
  299. self.norm = nn.Identity() if preact else norm_layer(out_chs, apply_act=False, **dd)
  300. def forward(self, x: torch.Tensor) -> torch.Tensor:
  301. """Forward pass.
  302. Args:
  303. x: Input tensor.
  304. Returns:
  305. Downsampled tensor.
  306. """
  307. return self.norm(self.conv(x))
  308. class DownsampleAvg(nn.Module):
  309. """AvgPool downsampling as in 'D' ResNet variants."""
  310. def __init__(
  311. self,
  312. in_chs: int,
  313. out_chs: int,
  314. stride: int = 1,
  315. dilation: int = 1,
  316. first_dilation: Optional[int] = None,
  317. preact: bool = True,
  318. conv_layer: Optional[Callable] = None,
  319. norm_layer: Optional[Callable] = None,
  320. device=None,
  321. dtype=None,
  322. ):
  323. dd = {'device': device, 'dtype': dtype}
  324. super().__init__()
  325. avg_stride = stride if dilation == 1 else 1
  326. if stride > 1 or dilation > 1:
  327. avg_pool_fn = AvgPool2dSame if avg_stride == 1 and dilation > 1 else nn.AvgPool2d
  328. self.pool = avg_pool_fn(2, avg_stride, ceil_mode=True, count_include_pad=False)
  329. else:
  330. self.pool = nn.Identity()
  331. self.conv = conv_layer(in_chs, out_chs, 1, stride=1, **dd)
  332. self.norm = nn.Identity() if preact else norm_layer(out_chs, apply_act=False, **dd)
  333. def forward(self, x: torch.Tensor) -> torch.Tensor:
  334. """Forward pass.
  335. Args:
  336. x: Input tensor.
  337. Returns:
  338. Downsampled tensor.
  339. """
  340. return self.norm(self.conv(self.pool(x)))
  341. class ResNetStage(nn.Module):
  342. """ResNet Stage."""
  343. def __init__(
  344. self,
  345. in_chs: int,
  346. out_chs: int,
  347. stride: int,
  348. dilation: int,
  349. depth: int,
  350. bottle_ratio: float = 0.25,
  351. groups: int = 1,
  352. avg_down: bool = False,
  353. block_dpr: Optional[List[float]] = None,
  354. block_fn: Callable = PreActBottleneck,
  355. act_layer: Optional[Callable] = None,
  356. conv_layer: Optional[Callable] = None,
  357. norm_layer: Optional[Callable] = None,
  358. **block_kwargs: Any,
  359. ):
  360. super().__init__()
  361. self.grad_checkpointing = False
  362. first_dilation = 1 if dilation in (1, 2) else 2
  363. layer_kwargs = dict(act_layer=act_layer, conv_layer=conv_layer, norm_layer=norm_layer)
  364. proj_layer = DownsampleAvg if avg_down else DownsampleConv
  365. prev_chs = in_chs
  366. self.blocks = nn.Sequential()
  367. for block_idx in range(depth):
  368. drop_path_rate = block_dpr[block_idx] if block_dpr else 0.
  369. stride = stride if block_idx == 0 else 1
  370. self.blocks.add_module(str(block_idx), block_fn(
  371. prev_chs,
  372. out_chs,
  373. stride=stride,
  374. dilation=dilation,
  375. bottle_ratio=bottle_ratio,
  376. groups=groups,
  377. first_dilation=first_dilation,
  378. proj_layer=proj_layer,
  379. drop_path_rate=drop_path_rate,
  380. **layer_kwargs,
  381. **block_kwargs,
  382. ))
  383. prev_chs = out_chs
  384. first_dilation = dilation
  385. proj_layer = None
  386. def forward(self, x: torch.Tensor) -> torch.Tensor:
  387. """Forward pass through all blocks in the stage.
  388. Args:
  389. x: Input tensor.
  390. Returns:
  391. Output tensor.
  392. """
  393. if self.grad_checkpointing and not torch.jit.is_scripting():
  394. x = checkpoint_seq(self.blocks, x)
  395. else:
  396. x = self.blocks(x)
  397. return x
  398. def is_stem_deep(stem_type: str) -> bool:
  399. """Check if stem type is deep (has multiple convolutions).
  400. Args:
  401. stem_type: Type of stem to check.
  402. Returns:
  403. True if stem is deep, False otherwise.
  404. """
  405. return any([s in stem_type for s in ('deep', 'tiered')])
  406. def create_resnetv2_stem(
  407. in_chs: int,
  408. out_chs: int = 64,
  409. stem_type: str = '',
  410. preact: bool = True,
  411. conv_layer: Callable = StdConv2d,
  412. norm_layer: Callable = partial(GroupNormAct, num_groups=32),
  413. device=None,
  414. dtype=None,
  415. ) -> nn.Sequential:
  416. dd = {'device': device, 'dtype': dtype}
  417. stem = OrderedDict()
  418. assert stem_type in ('', 'fixed', 'same', 'deep', 'deep_fixed', 'deep_same', 'tiered')
  419. # NOTE conv padding mode can be changed by overriding the conv_layer def
  420. if is_stem_deep(stem_type):
  421. # A 3 deep 3x3 conv stack as in ResNet V1D models
  422. if 'tiered' in stem_type:
  423. stem_chs = (3 * out_chs // 8, out_chs // 2) # 'T' resnets in resnet.py
  424. else:
  425. stem_chs = (out_chs // 2, out_chs // 2) # 'D' ResNets
  426. stem['conv1'] = conv_layer(in_chs, stem_chs[0], kernel_size=3, stride=2, **dd)
  427. stem['norm1'] = norm_layer(stem_chs[0], **dd)
  428. stem['conv2'] = conv_layer(stem_chs[0], stem_chs[1], kernel_size=3, stride=1, **dd)
  429. stem['norm2'] = norm_layer(stem_chs[1], **dd)
  430. stem['conv3'] = conv_layer(stem_chs[1], out_chs, kernel_size=3, stride=1, **dd)
  431. if not preact:
  432. stem['norm3'] = norm_layer(out_chs, **dd)
  433. else:
  434. # The usual 7x7 stem conv
  435. stem['conv'] = conv_layer(in_chs, out_chs, kernel_size=7, stride=2, **dd)
  436. if not preact:
  437. stem['norm'] = norm_layer(out_chs, **dd)
  438. if 'fixed' in stem_type:
  439. # 'fixed' SAME padding approximation that is used in BiT models
  440. stem['pad'] = nn.ConstantPad2d(1, 0.)
  441. stem['pool'] = nn.MaxPool2d(kernel_size=3, stride=2, padding=0)
  442. elif 'same' in stem_type:
  443. # full, input size based 'SAME' padding, used in ViT Hybrid model
  444. stem['pool'] = create_pool2d('max', kernel_size=3, stride=2, padding='same')
  445. else:
  446. # the usual PyTorch symmetric padding
  447. stem['pool'] = nn.MaxPool2d(kernel_size=3, stride=2, padding=1)
  448. return nn.Sequential(stem)
  449. class ResNetV2(nn.Module):
  450. """Implementation of Pre-activation (v2) ResNet mode.
  451. """
  452. def __init__(
  453. self,
  454. layers: List[int],
  455. channels: Tuple[int, ...] = (256, 512, 1024, 2048),
  456. num_classes: int = 1000,
  457. in_chans: int = 3,
  458. global_pool: str = 'avg',
  459. output_stride: int = 32,
  460. width_factor: int = 1,
  461. stem_chs: int = 64,
  462. stem_type: str = '',
  463. avg_down: bool = False,
  464. preact: bool = True,
  465. basic: bool = False,
  466. bottle_ratio: float = 0.25,
  467. act_layer: Callable = nn.ReLU,
  468. norm_layer: Callable = partial(GroupNormAct, num_groups=32),
  469. conv_layer: Callable = StdConv2d,
  470. drop_rate: float = 0.,
  471. drop_path_rate: float = 0.,
  472. zero_init_last: bool = False,
  473. device=None,
  474. dtype=None,
  475. ):
  476. """
  477. Args:
  478. layers (List[int]) : number of layers in each block
  479. channels (List[int]) : number of channels in each block:
  480. num_classes (int): number of classification classes (default 1000)
  481. in_chans (int): number of input (color) channels. (default 3)
  482. global_pool (str): Global pooling type. One of 'avg', 'max', 'avgmax', 'catavgmax' (default 'avg')
  483. output_stride (int): output stride of the network, 32, 16, or 8. (default 32)
  484. width_factor (int): channel (width) multiplication factor
  485. stem_chs (int): stem width (default: 64)
  486. stem_type (str): stem type (default: '' == 7x7)
  487. avg_down (bool): average pooling in residual downsampling (default: False)
  488. preact (bool): pre-activation (default: True)
  489. act_layer (Union[str, nn.Module]): activation layer
  490. norm_layer (Union[str, nn.Module]): normalization layer
  491. conv_layer (nn.Module): convolution module
  492. drop_rate: classifier dropout rate (default: 0.)
  493. drop_path_rate: stochastic depth rate (default: 0.)
  494. zero_init_last: zero-init last weight in residual path (default: False)
  495. """
  496. super().__init__()
  497. dd = {'device': device, 'dtype': dtype}
  498. self.num_classes = num_classes
  499. self.drop_rate = drop_rate
  500. wf = width_factor
  501. norm_layer = get_norm_act_layer(norm_layer, act_layer=act_layer)
  502. act_layer = get_act_layer(act_layer)
  503. self.feature_info = []
  504. stem_chs = make_divisible(stem_chs * wf)
  505. self.stem = create_resnetv2_stem(
  506. in_chans,
  507. stem_chs,
  508. stem_type,
  509. preact,
  510. conv_layer=conv_layer,
  511. norm_layer=norm_layer,
  512. **dd,
  513. )
  514. stem_feat = ('stem.conv3' if is_stem_deep(stem_type) else 'stem.conv') if preact else 'stem.norm'
  515. self.feature_info.append(dict(num_chs=stem_chs, reduction=2, module=stem_feat))
  516. prev_chs = stem_chs
  517. curr_stride = 4
  518. dilation = 1
  519. block_dprs = calculate_drop_path_rates(drop_path_rate, layers, stagewise=True)
  520. if preact:
  521. block_fn = PreActBasic if basic else PreActBottleneck
  522. else:
  523. assert not basic
  524. block_fn = Bottleneck
  525. self.stages = nn.Sequential()
  526. for stage_idx, (d, c, bdpr) in enumerate(zip(layers, channels, block_dprs)):
  527. out_chs = make_divisible(c * wf)
  528. stride = 1 if stage_idx == 0 else 2
  529. if curr_stride >= output_stride:
  530. dilation *= stride
  531. stride = 1
  532. stage = ResNetStage(
  533. prev_chs,
  534. out_chs,
  535. stride=stride,
  536. dilation=dilation,
  537. depth=d,
  538. bottle_ratio=bottle_ratio,
  539. avg_down=avg_down,
  540. act_layer=act_layer,
  541. conv_layer=conv_layer,
  542. norm_layer=norm_layer,
  543. block_dpr=bdpr,
  544. block_fn=block_fn,
  545. **dd,
  546. )
  547. prev_chs = out_chs
  548. curr_stride *= stride
  549. self.feature_info += [dict(num_chs=prev_chs, reduction=curr_stride, module=f'stages.{stage_idx}')]
  550. self.stages.add_module(str(stage_idx), stage)
  551. self.num_features = self.head_hidden_size = prev_chs
  552. self.norm = norm_layer(self.num_features, **dd) if preact else nn.Identity()
  553. self.head = ClassifierHead(
  554. self.num_features,
  555. num_classes,
  556. pool_type=global_pool,
  557. drop_rate=self.drop_rate,
  558. use_conv=True,
  559. **dd,
  560. )
  561. self.init_weights(zero_init_last=zero_init_last)
  562. @torch.jit.ignore
  563. def init_weights(self, zero_init_last: bool = True) -> None:
  564. """Initialize model weights."""
  565. named_apply(partial(_init_weights, zero_init_last=zero_init_last), self)
  566. @torch.jit.ignore()
  567. def load_pretrained(self, checkpoint_path: str, prefix: str = 'resnet/') -> None:
  568. """Load pretrained weights."""
  569. _load_weights(self, checkpoint_path, prefix)
  570. @torch.jit.ignore
  571. def group_matcher(self, coarse: bool = False) -> Dict[str, Any]:
  572. """Group parameters for optimization."""
  573. matcher = dict(
  574. stem=r'^stem',
  575. blocks=r'^stages\.(\d+)' if coarse else [
  576. (r'^stages\.(\d+)\.blocks\.(\d+)', None),
  577. (r'^norm', (99999,))
  578. ]
  579. )
  580. return matcher
  581. @torch.jit.ignore
  582. def set_grad_checkpointing(self, enable: bool = True) -> None:
  583. """Enable or disable gradient checkpointing."""
  584. for s in self.stages:
  585. s.grad_checkpointing = enable
  586. @torch.jit.ignore
  587. def get_classifier(self) -> nn.Module:
  588. """Get the classifier head."""
  589. return self.head.fc
  590. def reset_classifier(self, num_classes: int, global_pool: Optional[str] = None) -> None:
  591. """Reset the classifier head.
  592. Args:
  593. num_classes: Number of classes for new classifier.
  594. global_pool: Global pooling type.
  595. """
  596. self.num_classes = num_classes
  597. self.head.reset(num_classes, global_pool)
  598. def forward_intermediates(
  599. self,
  600. x: torch.Tensor,
  601. indices: Optional[Union[int, List[int]]] = None,
  602. norm: bool = False,
  603. stop_early: bool = False,
  604. output_fmt: str = 'NCHW',
  605. intermediates_only: bool = False,
  606. ) -> Union[List[torch.Tensor], Tuple[torch.Tensor, List[torch.Tensor]]]:
  607. """ Forward features that returns intermediates.
  608. Args:
  609. x: Input image tensor
  610. indices: Take last n blocks if int, all if None, select matching indices if sequence
  611. norm: Apply norm layer to compatible intermediates
  612. stop_early: Stop iterating over blocks when last desired intermediate hit
  613. output_fmt: Shape of intermediate feature outputs
  614. intermediates_only: Only return intermediate features
  615. Returns:
  616. """
  617. assert output_fmt in ('NCHW',), 'Output shape must be NCHW.'
  618. intermediates = []
  619. take_indices, max_index = feature_take_indices(5, indices)
  620. # forward pass
  621. feat_idx = 0
  622. H, W = x.shape[-2:]
  623. for stem in self.stem:
  624. x = stem(x)
  625. if x.shape[-2:] == (H //2, W //2):
  626. x_down = x
  627. if feat_idx in take_indices:
  628. intermediates.append(x_down)
  629. last_idx = len(self.stages)
  630. if torch.jit.is_scripting() or not stop_early: # can't slice blocks in torchscript
  631. stages = self.stages
  632. else:
  633. stages = self.stages[:max_index]
  634. for feat_idx, stage in enumerate(stages, start=1):
  635. x = stage(x)
  636. if feat_idx in take_indices:
  637. if feat_idx == last_idx:
  638. x_inter = self.norm(x) if norm else x
  639. intermediates.append(x_inter)
  640. else:
  641. intermediates.append(x)
  642. if intermediates_only:
  643. return intermediates
  644. if feat_idx == last_idx:
  645. x = self.norm(x)
  646. return x, intermediates
  647. def prune_intermediate_layers(
  648. self,
  649. indices: Union[int, List[int]] = 1,
  650. prune_norm: bool = False,
  651. prune_head: bool = True,
  652. ):
  653. """ Prune layers not required for specified intermediates.
  654. """
  655. take_indices, max_index = feature_take_indices(5, indices)
  656. self.stages = self.stages[:max_index] # truncate blocks w/ stem as idx 0
  657. if prune_norm:
  658. self.norm = nn.Identity()
  659. if prune_head:
  660. self.reset_classifier(0, '')
  661. return take_indices
  662. def forward_features(self, x: torch.Tensor) -> torch.Tensor:
  663. """Forward pass through feature extraction layers.
  664. Args:
  665. x: Input tensor.
  666. Returns:
  667. Feature tensor.
  668. """
  669. x = self.stem(x)
  670. x = self.stages(x)
  671. x = self.norm(x)
  672. return x
  673. def forward_head(self, x: torch.Tensor, pre_logits: bool = False) -> torch.Tensor:
  674. """Forward pass through classifier head.
  675. Args:
  676. x: Input features.
  677. pre_logits: Return features before final linear layer.
  678. Returns:
  679. Classification logits or features.
  680. """
  681. return self.head(x, pre_logits=pre_logits) if pre_logits else self.head(x)
  682. def forward(self, x: torch.Tensor) -> torch.Tensor:
  683. """Forward pass.
  684. Args:
  685. x: Input tensor.
  686. Returns:
  687. Output logits.
  688. """
  689. x = self.forward_features(x)
  690. x = self.forward_head(x)
  691. return x
  692. def _init_weights(module: nn.Module, name: str = '', zero_init_last: bool = True) -> None:
  693. """Initialize module weights.
  694. Args:
  695. module: PyTorch module to initialize.
  696. name: Module name.
  697. zero_init_last: Zero-initialize last layer weights.
  698. """
  699. if isinstance(module, nn.Linear) or ('head.fc' in name and isinstance(module, nn.Conv2d)):
  700. nn.init.normal_(module.weight, mean=0.0, std=0.01)
  701. nn.init.zeros_(module.bias)
  702. elif isinstance(module, nn.Conv2d):
  703. nn.init.kaiming_normal_(module.weight, mode='fan_out', nonlinearity='relu')
  704. if module.bias is not None:
  705. nn.init.zeros_(module.bias)
  706. elif isinstance(module, (nn.BatchNorm2d, nn.LayerNorm, nn.GroupNorm)):
  707. nn.init.ones_(module.weight)
  708. nn.init.zeros_(module.bias)
  709. elif zero_init_last and hasattr(module, 'zero_init_last'):
  710. module.zero_init_last()
  711. @torch.no_grad()
  712. def _load_weights(model: nn.Module, checkpoint_path: str, prefix: str = 'resnet/'):
  713. import numpy as np
  714. def t2p(conv_weights):
  715. """Possibly convert HWIO to OIHW."""
  716. if conv_weights.ndim == 4:
  717. conv_weights = conv_weights.transpose([3, 2, 0, 1])
  718. return torch.from_numpy(conv_weights)
  719. weights = np.load(checkpoint_path)
  720. stem_conv_w = adapt_input_conv(
  721. model.stem.conv.weight.shape[1], t2p(weights[f'{prefix}root_block/standardized_conv2d/kernel']))
  722. model.stem.conv.weight.copy_(stem_conv_w)
  723. model.norm.weight.copy_(t2p(weights[f'{prefix}group_norm/gamma']))
  724. model.norm.bias.copy_(t2p(weights[f'{prefix}group_norm/beta']))
  725. if isinstance(getattr(model.head, 'fc', None), nn.Conv2d) and \
  726. model.head.fc.weight.shape[0] == weights[f'{prefix}head/conv2d/kernel'].shape[-1]:
  727. model.head.fc.weight.copy_(t2p(weights[f'{prefix}head/conv2d/kernel']))
  728. model.head.fc.bias.copy_(t2p(weights[f'{prefix}head/conv2d/bias']))
  729. for i, (sname, stage) in enumerate(model.stages.named_children()):
  730. for j, (bname, block) in enumerate(stage.blocks.named_children()):
  731. cname = 'standardized_conv2d'
  732. block_prefix = f'{prefix}block{i + 1}/unit{j + 1:02d}/'
  733. block.conv1.weight.copy_(t2p(weights[f'{block_prefix}a/{cname}/kernel']))
  734. block.conv2.weight.copy_(t2p(weights[f'{block_prefix}b/{cname}/kernel']))
  735. block.conv3.weight.copy_(t2p(weights[f'{block_prefix}c/{cname}/kernel']))
  736. block.norm1.weight.copy_(t2p(weights[f'{block_prefix}a/group_norm/gamma']))
  737. block.norm2.weight.copy_(t2p(weights[f'{block_prefix}b/group_norm/gamma']))
  738. block.norm3.weight.copy_(t2p(weights[f'{block_prefix}c/group_norm/gamma']))
  739. block.norm1.bias.copy_(t2p(weights[f'{block_prefix}a/group_norm/beta']))
  740. block.norm2.bias.copy_(t2p(weights[f'{block_prefix}b/group_norm/beta']))
  741. block.norm3.bias.copy_(t2p(weights[f'{block_prefix}c/group_norm/beta']))
  742. if block.downsample is not None:
  743. w = weights[f'{block_prefix}a/proj/{cname}/kernel']
  744. block.downsample.conv.weight.copy_(t2p(w))
  745. def _create_resnetv2(variant: str, pretrained: bool = False, **kwargs: Any) -> ResNetV2:
  746. """Create a ResNetV2 model.
  747. Args:
  748. variant: Model variant name.
  749. pretrained: Load pretrained weights.
  750. **kwargs: Additional model arguments.
  751. Returns:
  752. ResNetV2 model instance.
  753. """
  754. feature_cfg = dict(flatten_sequential=True)
  755. return build_model_with_cfg(
  756. ResNetV2, variant, pretrained,
  757. feature_cfg=feature_cfg,
  758. **kwargs,
  759. )
  760. def _create_resnetv2_bit(variant: str, pretrained: bool = False, **kwargs: Any) -> ResNetV2:
  761. """Create a ResNetV2 model with BiT weights.
  762. Args:
  763. variant: Model variant name.
  764. pretrained: Load pretrained weights.
  765. **kwargs: Additional model arguments.
  766. Returns:
  767. ResNetV2 model instance.
  768. """
  769. return _create_resnetv2(
  770. variant,
  771. pretrained=pretrained,
  772. stem_type='fixed',
  773. conv_layer=partial(StdConv2d, eps=1e-8),
  774. **kwargs,
  775. )
  776. def _cfg(url: str = '', **kwargs: Any) -> Dict[str, Any]:
  777. return {
  778. 'url': url,
  779. 'num_classes': 1000, 'input_size': (3, 224, 224), 'pool_size': (7, 7),
  780. 'crop_pct': 0.875, 'interpolation': 'bilinear',
  781. 'mean': IMAGENET_INCEPTION_MEAN, 'std': IMAGENET_INCEPTION_STD,
  782. 'first_conv': 'stem.conv', 'classifier': 'head.fc',
  783. 'license': 'apache-2.0',
  784. **kwargs
  785. }
  786. default_cfgs = generate_default_cfgs({
  787. # Paper: Knowledge distillation: A good teacher is patient and consistent - https://arxiv.org/abs/2106.05237
  788. 'resnetv2_50x1_bit.goog_distilled_in1k': _cfg(
  789. hf_hub_id='timm/',
  790. interpolation='bicubic', custom_load=True),
  791. 'resnetv2_152x2_bit.goog_teacher_in21k_ft_in1k': _cfg(
  792. hf_hub_id='timm/',
  793. interpolation='bicubic', custom_load=True),
  794. 'resnetv2_152x2_bit.goog_teacher_in21k_ft_in1k_384': _cfg(
  795. hf_hub_id='timm/',
  796. input_size=(3, 384, 384), pool_size=(12, 12), crop_pct=1.0, interpolation='bicubic', custom_load=True),
  797. # pretrained on imagenet21k, finetuned on imagenet1k
  798. 'resnetv2_50x1_bit.goog_in21k_ft_in1k': _cfg(
  799. hf_hub_id='timm/',
  800. input_size=(3, 448, 448), pool_size=(14, 14), crop_pct=1.0, custom_load=True),
  801. 'resnetv2_50x3_bit.goog_in21k_ft_in1k': _cfg(
  802. hf_hub_id='timm/',
  803. input_size=(3, 448, 448), pool_size=(14, 14), crop_pct=1.0, custom_load=True),
  804. 'resnetv2_101x1_bit.goog_in21k_ft_in1k': _cfg(
  805. hf_hub_id='timm/',
  806. input_size=(3, 448, 448), pool_size=(14, 14), crop_pct=1.0, custom_load=True),
  807. 'resnetv2_101x3_bit.goog_in21k_ft_in1k': _cfg(
  808. hf_hub_id='timm/',
  809. input_size=(3, 448, 448), pool_size=(14, 14), crop_pct=1.0, custom_load=True),
  810. 'resnetv2_152x2_bit.goog_in21k_ft_in1k': _cfg(
  811. hf_hub_id='timm/',
  812. input_size=(3, 448, 448), pool_size=(14, 14), crop_pct=1.0, custom_load=True),
  813. 'resnetv2_152x4_bit.goog_in21k_ft_in1k': _cfg(
  814. hf_hub_id='timm/',
  815. input_size=(3, 480, 480), pool_size=(15, 15), crop_pct=1.0, custom_load=True), # only one at 480x480?
  816. # trained on imagenet-21k
  817. 'resnetv2_50x1_bit.goog_in21k': _cfg(
  818. hf_hub_id='timm/',
  819. num_classes=21843, custom_load=True),
  820. 'resnetv2_50x3_bit.goog_in21k': _cfg(
  821. hf_hub_id='timm/',
  822. num_classes=21843, custom_load=True),
  823. 'resnetv2_101x1_bit.goog_in21k': _cfg(
  824. hf_hub_id='timm/',
  825. num_classes=21843, custom_load=True),
  826. 'resnetv2_101x3_bit.goog_in21k': _cfg(
  827. hf_hub_id='timm/',
  828. num_classes=21843, custom_load=True),
  829. 'resnetv2_152x2_bit.goog_in21k': _cfg(
  830. hf_hub_id='timm/',
  831. num_classes=21843, custom_load=True),
  832. 'resnetv2_152x4_bit.goog_in21k': _cfg(
  833. hf_hub_id='timm/',
  834. num_classes=21843, custom_load=True),
  835. 'resnetv2_18.ra4_e3600_r224_in1k': _cfg(
  836. hf_hub_id='timm/',
  837. interpolation='bicubic', crop_pct=0.9, test_input_size=(3, 288, 288), test_crop_pct=1.0),
  838. 'resnetv2_18d.ra4_e3600_r224_in1k': _cfg(
  839. hf_hub_id='timm/',
  840. interpolation='bicubic', crop_pct=0.9, test_input_size=(3, 288, 288), test_crop_pct=1.0,
  841. first_conv='stem.conv1'),
  842. 'resnetv2_34.ra4_e3600_r224_in1k': _cfg(
  843. hf_hub_id='timm/',
  844. interpolation='bicubic', crop_pct=0.9, test_input_size=(3, 288, 288), test_crop_pct=1.0),
  845. 'resnetv2_34d.ra4_e3600_r224_in1k': _cfg(
  846. hf_hub_id='timm/',
  847. interpolation='bicubic', crop_pct=0.9, test_input_size=(3, 288, 288), test_crop_pct=1.0,
  848. first_conv='stem.conv1'),
  849. 'resnetv2_34d.ra4_e3600_r384_in1k': _cfg(
  850. hf_hub_id='timm/',
  851. crop_pct=1.0, input_size=(3, 384, 384), pool_size=(12, 12), test_input_size=(3, 448, 448),
  852. interpolation='bicubic', first_conv='stem.conv1'),
  853. 'resnetv2_50.a1h_in1k': _cfg(
  854. hf_hub_id='timm/',
  855. interpolation='bicubic', crop_pct=0.95, test_input_size=(3, 288, 288), test_crop_pct=1.0),
  856. 'resnetv2_50d.untrained': _cfg(
  857. interpolation='bicubic', first_conv='stem.conv1'),
  858. 'resnetv2_50t.untrained': _cfg(
  859. interpolation='bicubic', first_conv='stem.conv1'),
  860. 'resnetv2_101.a1h_in1k': _cfg(
  861. hf_hub_id='timm/',
  862. interpolation='bicubic', crop_pct=0.95, test_input_size=(3, 288, 288), test_crop_pct=1.0),
  863. 'resnetv2_101d.untrained': _cfg(
  864. interpolation='bicubic', first_conv='stem.conv1'),
  865. 'resnetv2_152.untrained': _cfg(
  866. interpolation='bicubic'),
  867. 'resnetv2_152d.untrained': _cfg(
  868. interpolation='bicubic', first_conv='stem.conv1'),
  869. 'resnetv2_50d_gn.ah_in1k': _cfg(
  870. hf_hub_id='timm/',
  871. interpolation='bicubic', first_conv='stem.conv1',
  872. crop_pct=0.95, test_input_size=(3, 288, 288), test_crop_pct=1.0),
  873. 'resnetv2_50d_evos.ah_in1k': _cfg(
  874. hf_hub_id='timm/',
  875. interpolation='bicubic', first_conv='stem.conv1',
  876. crop_pct=0.95, test_input_size=(3, 288, 288), test_crop_pct=1.0),
  877. 'resnetv2_50d_frn.untrained': _cfg(
  878. interpolation='bicubic', first_conv='stem.conv1'),
  879. })
  880. @register_model
  881. def resnetv2_50x1_bit(pretrained: bool = False, **kwargs: Any) -> ResNetV2:
  882. """ResNetV2-50x1-BiT model."""
  883. return _create_resnetv2_bit(
  884. 'resnetv2_50x1_bit', pretrained=pretrained, layers=[3, 4, 6, 3], width_factor=1, **kwargs)
  885. @register_model
  886. def resnetv2_50x3_bit(pretrained: bool = False, **kwargs: Any) -> ResNetV2:
  887. """ResNetV2-50x3-BiT model."""
  888. return _create_resnetv2_bit(
  889. 'resnetv2_50x3_bit', pretrained=pretrained, layers=[3, 4, 6, 3], width_factor=3, **kwargs)
  890. @register_model
  891. def resnetv2_101x1_bit(pretrained: bool = False, **kwargs: Any) -> ResNetV2:
  892. """ResNetV2-101x1-BiT model."""
  893. return _create_resnetv2_bit(
  894. 'resnetv2_101x1_bit', pretrained=pretrained, layers=[3, 4, 23, 3], width_factor=1, **kwargs)
  895. @register_model
  896. def resnetv2_101x3_bit(pretrained: bool = False, **kwargs: Any) -> ResNetV2:
  897. """ResNetV2-101x3-BiT model."""
  898. return _create_resnetv2_bit(
  899. 'resnetv2_101x3_bit', pretrained=pretrained, layers=[3, 4, 23, 3], width_factor=3, **kwargs)
  900. @register_model
  901. def resnetv2_152x2_bit(pretrained: bool = False, **kwargs: Any) -> ResNetV2:
  902. """ResNetV2-152x2-BiT model."""
  903. return _create_resnetv2_bit(
  904. 'resnetv2_152x2_bit', pretrained=pretrained, layers=[3, 8, 36, 3], width_factor=2, **kwargs)
  905. @register_model
  906. def resnetv2_152x4_bit(pretrained: bool = False, **kwargs: Any) -> ResNetV2:
  907. """ResNetV2-152x4-BiT model."""
  908. return _create_resnetv2_bit(
  909. 'resnetv2_152x4_bit', pretrained=pretrained, layers=[3, 8, 36, 3], width_factor=4, **kwargs)
  910. @register_model
  911. def resnetv2_18(pretrained: bool = False, **kwargs: Any) -> ResNetV2:
  912. """ResNetV2-18 model."""
  913. model_args = dict(
  914. layers=[2, 2, 2, 2], channels=(64, 128, 256, 512), basic=True, bottle_ratio=1.0,
  915. conv_layer=create_conv2d, norm_layer=BatchNormAct2d
  916. )
  917. return _create_resnetv2('resnetv2_18', pretrained=pretrained, **dict(model_args, **kwargs))
  918. @register_model
  919. def resnetv2_18d(pretrained: bool = False, **kwargs: Any) -> ResNetV2:
  920. """ResNetV2-18d model (deep stem variant)."""
  921. model_args = dict(
  922. layers=[2, 2, 2, 2], channels=(64, 128, 256, 512), basic=True, bottle_ratio=1.0,
  923. conv_layer=create_conv2d, norm_layer=BatchNormAct2d, stem_type='deep', avg_down=True
  924. )
  925. return _create_resnetv2('resnetv2_18d', pretrained=pretrained, **dict(model_args, **kwargs))
  926. @register_model
  927. def resnetv2_34(pretrained: bool = False, **kwargs: Any) -> ResNetV2:
  928. """ResNetV2-34 model."""
  929. model_args = dict(
  930. layers=(3, 4, 6, 3), channels=(64, 128, 256, 512), basic=True, bottle_ratio=1.0,
  931. conv_layer=create_conv2d, norm_layer=BatchNormAct2d
  932. )
  933. return _create_resnetv2('resnetv2_34', pretrained=pretrained, **dict(model_args, **kwargs))
  934. @register_model
  935. def resnetv2_34d(pretrained: bool = False, **kwargs: Any) -> ResNetV2:
  936. """ResNetV2-34d model (deep stem variant)."""
  937. model_args = dict(
  938. layers=(3, 4, 6, 3), channels=(64, 128, 256, 512), basic=True, bottle_ratio=1.0,
  939. conv_layer=create_conv2d, norm_layer=BatchNormAct2d, stem_type='deep', avg_down=True
  940. )
  941. return _create_resnetv2('resnetv2_34d', pretrained=pretrained, **dict(model_args, **kwargs))
  942. @register_model
  943. def resnetv2_50(pretrained: bool = False, **kwargs: Any) -> ResNetV2:
  944. """ResNetV2-50 model."""
  945. model_args = dict(layers=[3, 4, 6, 3], conv_layer=create_conv2d, norm_layer=BatchNormAct2d)
  946. return _create_resnetv2('resnetv2_50', pretrained=pretrained, **dict(model_args, **kwargs))
  947. @register_model
  948. def resnetv2_50d(pretrained: bool = False, **kwargs: Any) -> ResNetV2:
  949. """ResNetV2-50d model (deep stem variant)."""
  950. model_args = dict(
  951. layers=[3, 4, 6, 3], conv_layer=create_conv2d, norm_layer=BatchNormAct2d,
  952. stem_type='deep', avg_down=True)
  953. return _create_resnetv2('resnetv2_50d', pretrained=pretrained, **dict(model_args, **kwargs))
  954. @register_model
  955. def resnetv2_50t(pretrained: bool = False, **kwargs: Any) -> ResNetV2:
  956. """ResNetV2-50t model (tiered stem variant)."""
  957. model_args = dict(
  958. layers=[3, 4, 6, 3], conv_layer=create_conv2d, norm_layer=BatchNormAct2d,
  959. stem_type='tiered', avg_down=True)
  960. return _create_resnetv2('resnetv2_50t', pretrained=pretrained, **dict(model_args, **kwargs))
  961. @register_model
  962. def resnetv2_101(pretrained: bool = False, **kwargs: Any) -> ResNetV2:
  963. """ResNetV2-101 model."""
  964. model_args = dict(layers=[3, 4, 23, 3], conv_layer=create_conv2d, norm_layer=BatchNormAct2d)
  965. return _create_resnetv2('resnetv2_101', pretrained=pretrained, **dict(model_args, **kwargs))
  966. @register_model
  967. def resnetv2_101d(pretrained: bool = False, **kwargs: Any) -> ResNetV2:
  968. """ResNetV2-101d model (deep stem variant)."""
  969. model_args = dict(
  970. layers=[3, 4, 23, 3], conv_layer=create_conv2d, norm_layer=BatchNormAct2d,
  971. stem_type='deep', avg_down=True)
  972. return _create_resnetv2('resnetv2_101d', pretrained=pretrained, **dict(model_args, **kwargs))
  973. @register_model
  974. def resnetv2_152(pretrained: bool = False, **kwargs: Any) -> ResNetV2:
  975. """ResNetV2-152 model."""
  976. model_args = dict(layers=[3, 8, 36, 3], conv_layer=create_conv2d, norm_layer=BatchNormAct2d)
  977. return _create_resnetv2('resnetv2_152', pretrained=pretrained, **dict(model_args, **kwargs))
  978. @register_model
  979. def resnetv2_152d(pretrained: bool = False, **kwargs: Any) -> ResNetV2:
  980. """ResNetV2-152d model (deep stem variant)."""
  981. model_args = dict(
  982. layers=[3, 8, 36, 3], conv_layer=create_conv2d, norm_layer=BatchNormAct2d,
  983. stem_type='deep', avg_down=True)
  984. return _create_resnetv2('resnetv2_152d', pretrained=pretrained, **dict(model_args, **kwargs))
  985. # Experimental configs (may change / be removed)
  986. @register_model
  987. def resnetv2_50d_gn(pretrained: bool = False, **kwargs: Any) -> ResNetV2:
  988. """ResNetV2-50d model with Group Normalization."""
  989. model_args = dict(
  990. layers=[3, 4, 6, 3], conv_layer=create_conv2d, norm_layer=GroupNormAct,
  991. stem_type='deep', avg_down=True)
  992. return _create_resnetv2('resnetv2_50d_gn', pretrained=pretrained, **dict(model_args, **kwargs))
  993. @register_model
  994. def resnetv2_50d_evos(pretrained: bool = False, **kwargs: Any) -> ResNetV2:
  995. """ResNetV2-50d model with EvoNorm."""
  996. model_args = dict(
  997. layers=[3, 4, 6, 3], conv_layer=create_conv2d, norm_layer=EvoNorm2dS0,
  998. stem_type='deep', avg_down=True)
  999. return _create_resnetv2('resnetv2_50d_evos', pretrained=pretrained, **dict(model_args, **kwargs))
  1000. @register_model
  1001. def resnetv2_50d_frn(pretrained: bool = False, **kwargs: Any) -> ResNetV2:
  1002. """ResNetV2-50d model with Filter Response Normalization."""
  1003. model_args = dict(
  1004. layers=[3, 4, 6, 3], conv_layer=create_conv2d, norm_layer=FilterResponseNormTlu2d,
  1005. stem_type='deep', avg_down=True)
  1006. return _create_resnetv2('resnetv2_50d_frn', pretrained=pretrained, **dict(model_args, **kwargs))
  1007. register_model_deprecations(__name__, {
  1008. 'resnetv2_50x1_bitm': 'resnetv2_50x1_bit.goog_in21k_ft_in1k',
  1009. 'resnetv2_50x3_bitm': 'resnetv2_50x3_bit.goog_in21k_ft_in1k',
  1010. 'resnetv2_101x1_bitm': 'resnetv2_101x1_bit.goog_in21k_ft_in1k',
  1011. 'resnetv2_101x3_bitm': 'resnetv2_101x3_bit.goog_in21k_ft_in1k',
  1012. 'resnetv2_152x2_bitm': 'resnetv2_152x2_bit.goog_in21k_ft_in1k',
  1013. 'resnetv2_152x4_bitm': 'resnetv2_152x4_bit.goog_in21k_ft_in1k',
  1014. 'resnetv2_50x1_bitm_in21k': 'resnetv2_50x1_bit.goog_in21k',
  1015. 'resnetv2_50x3_bitm_in21k': 'resnetv2_50x3_bit.goog_in21k',
  1016. 'resnetv2_101x1_bitm_in21k': 'resnetv2_101x1_bit.goog_in21k',
  1017. 'resnetv2_101x3_bitm_in21k': 'resnetv2_101x3_bit.goog_in21k',
  1018. 'resnetv2_152x2_bitm_in21k': 'resnetv2_152x2_bit.goog_in21k',
  1019. 'resnetv2_152x4_bitm_in21k': 'resnetv2_152x4_bit.goog_in21k',
  1020. 'resnetv2_50x1_bit_distilled': 'resnetv2_50x1_bit.goog_distilled_in1k',
  1021. 'resnetv2_152x2_bit_teacher': 'resnetv2_152x2_bit.goog_teacher_in21k_ft_in1k',
  1022. 'resnetv2_152x2_bit_teacher_384': 'resnetv2_152x2_bit.goog_teacher_in21k_ft_in1k_384',
  1023. })