nfnet.py 45 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189
  1. """ Normalization Free Nets. NFNet, NF-RegNet, NF-ResNet (pre-activation) Models
  2. Paper: `Characterizing signal propagation to close the performance gap in unnormalized ResNets`
  3. - https://arxiv.org/abs/2101.08692
  4. Paper: `High-Performance Large-Scale Image Recognition Without Normalization`
  5. - https://arxiv.org/abs/2102.06171
  6. Official Deepmind JAX code: https://github.com/deepmind/deepmind-research/tree/master/nfnets
  7. Status:
  8. * These models are a work in progress, experiments ongoing.
  9. * Pretrained weights for two models so far, more to come.
  10. * Model details updated to closer match official JAX code now that it's released
  11. * NF-ResNet, NF-RegNet-B, and NFNet-F models supported
  12. Hacked together by / copyright Ross Wightman, 2021.
  13. """
  14. from collections import OrderedDict
  15. from dataclasses import dataclass, replace
  16. from functools import partial
  17. from typing import Any, Callable, Dict, Optional, Tuple
  18. import torch
  19. import torch.nn as nn
  20. from timm.data import IMAGENET_DEFAULT_MEAN, IMAGENET_DEFAULT_STD
  21. from timm.layers import ClassifierHead, DropPath, calculate_drop_path_rates, AvgPool2dSame, ScaledStdConv2d, ScaledStdConv2dSame, \
  22. get_act_layer, get_act_fn, get_attn, make_divisible
  23. from ._builder import build_model_with_cfg
  24. from ._features_fx import register_notrace_module
  25. from ._manipulate import checkpoint_seq
  26. from ._registry import generate_default_cfgs, register_model
  27. __all__ = ['NormFreeNet', 'NfCfg'] # model_registry will add each entrypoint fn to this
  28. @dataclass
  29. class NfCfg:
  30. """Configuration for Normalization-Free Networks."""
  31. depths: Tuple[int, int, int, int]
  32. channels: Tuple[int, int, int, int]
  33. alpha: float = 0.2
  34. stem_type: str = '3x3'
  35. stem_chs: Optional[int] = None
  36. group_size: Optional[int] = None
  37. attn_layer: Optional[str] = None
  38. attn_kwargs: Optional[Dict[str, Any]] = None
  39. attn_gain: float = 2.0 # NF correction gain to apply if attn layer is used
  40. width_factor: float = 1.0
  41. bottle_ratio: float = 0.5
  42. num_features: int = 0 # num out_channels for final conv, no final_conv if 0
  43. ch_div: int = 8 # round channels % 8 == 0 to keep tensor-core use optimal
  44. reg: bool = False # enables EfficientNet-like options used in RegNet variants, expand from in_chs, se in middle
  45. extra_conv: bool = False # extra 3x3 bottleneck convolution for NFNet models
  46. gamma_in_act: bool = False
  47. same_padding: bool = False
  48. std_conv_eps: float = 1e-5
  49. skipinit: bool = False # disabled by default, non-trivial performance impact
  50. zero_init_fc: bool = False
  51. act_layer: str = 'silu'
  52. class GammaAct(nn.Module):
  53. """Activation function with gamma scaling factor."""
  54. def __init__(self, act_type: str = 'relu', gamma: float = 1.0, inplace: bool = False):
  55. """Initialize GammaAct.
  56. Args:
  57. act_type: Type of activation function.
  58. gamma: Scaling factor for activation output.
  59. inplace: Whether to perform activation in-place.
  60. """
  61. super().__init__()
  62. self.act_fn = get_act_fn(act_type)
  63. self.gamma = gamma
  64. self.inplace = inplace
  65. def forward(self, x: torch.Tensor) -> torch.Tensor:
  66. """Forward pass.
  67. Args:
  68. x: Input tensor.
  69. Returns:
  70. Scaled activation output.
  71. """
  72. return self.act_fn(x, inplace=self.inplace).mul_(self.gamma)
  73. def act_with_gamma(act_type: str, gamma: float = 1.) -> Callable:
  74. """Create activation function factory with gamma scaling.
  75. Args:
  76. act_type: Type of activation function.
  77. gamma: Scaling factor for activation output.
  78. Returns:
  79. Activation function factory.
  80. """
  81. def _create(inplace: bool = False) -> GammaAct:
  82. return GammaAct(act_type, gamma=gamma, inplace=inplace)
  83. return _create
  84. class DownsampleAvg(nn.Module):
  85. """AvgPool downsampling as in 'D' ResNet variants with dilation support."""
  86. def __init__(
  87. self,
  88. in_chs: int,
  89. out_chs: int,
  90. stride: int = 1,
  91. dilation: int = 1,
  92. first_dilation: Optional[int] = None,
  93. conv_layer: Callable = ScaledStdConv2d,
  94. device=None,
  95. dtype=None,
  96. ):
  97. """Initialize DownsampleAvg.
  98. Args:
  99. in_chs: Input channels.
  100. out_chs: Output channels.
  101. stride: Stride for downsampling.
  102. dilation: Dilation rate.
  103. first_dilation: First dilation rate (unused).
  104. conv_layer: Convolution layer type.
  105. """
  106. super().__init__()
  107. avg_stride = stride if dilation == 1 else 1
  108. if stride > 1 or dilation > 1:
  109. avg_pool_fn = AvgPool2dSame if avg_stride == 1 and dilation > 1 else nn.AvgPool2d
  110. self.pool = avg_pool_fn(2, avg_stride, ceil_mode=True, count_include_pad=False)
  111. else:
  112. self.pool = nn.Identity()
  113. self.conv = conv_layer(in_chs, out_chs, 1, stride=1, device=device, dtype=dtype)
  114. def forward(self, x: torch.Tensor) -> torch.Tensor:
  115. """Forward pass.
  116. Args:
  117. x: Input tensor.
  118. Returns:
  119. Downsampled tensor.
  120. """
  121. return self.conv(self.pool(x))
  122. @register_notrace_module # reason: mul_ causes FX to drop a relevant node. https://github.com/pytorch/pytorch/issues/68301
  123. class NormFreeBlock(nn.Module):
  124. """Normalization-Free pre-activation block.
  125. """
  126. def __init__(
  127. self,
  128. in_chs: int,
  129. out_chs: Optional[int] = None,
  130. stride: int = 1,
  131. dilation: int = 1,
  132. first_dilation: Optional[int] = None,
  133. alpha: float = 1.0,
  134. beta: float = 1.0,
  135. bottle_ratio: float = 0.25,
  136. group_size: Optional[int] = None,
  137. ch_div: int = 1,
  138. reg: bool = True,
  139. extra_conv: bool = False,
  140. skipinit: bool = False,
  141. attn_layer: Optional[Callable] = None,
  142. attn_gain: float = 2.0,
  143. act_layer: Optional[Callable] = None,
  144. conv_layer: Callable = ScaledStdConv2d,
  145. drop_path_rate: float = 0.,
  146. device=None,
  147. dtype=None,
  148. ):
  149. """Initialize NormFreeBlock.
  150. Args:
  151. in_chs: Input channels.
  152. out_chs: Output channels.
  153. stride: Stride for convolution.
  154. dilation: Dilation rate.
  155. first_dilation: First dilation rate.
  156. alpha: Alpha scaling factor for residual.
  157. beta: Beta scaling factor for pre-activation.
  158. bottle_ratio: Bottleneck ratio.
  159. group_size: Group convolution size.
  160. ch_div: Channel divisor for rounding.
  161. reg: Use RegNet-style configuration.
  162. extra_conv: Add extra 3x3 convolution.
  163. skipinit: Use skipinit initialization.
  164. attn_layer: Attention layer type.
  165. attn_gain: Attention gain factor.
  166. act_layer: Activation layer type.
  167. conv_layer: Convolution layer type.
  168. drop_path_rate: Stochastic depth drop rate.
  169. """
  170. dd = {'device': device, 'dtype': dtype}
  171. super().__init__()
  172. first_dilation = first_dilation or dilation
  173. out_chs = out_chs or in_chs
  174. # RegNet variants scale bottleneck from in_chs, otherwise scale from out_chs like ResNet
  175. mid_chs = make_divisible(in_chs * bottle_ratio if reg else out_chs * bottle_ratio, ch_div)
  176. groups = 1 if not group_size else mid_chs // group_size
  177. if group_size and group_size % ch_div == 0:
  178. mid_chs = group_size * groups # correct mid_chs if group_size divisible by ch_div, otherwise error
  179. self.alpha = alpha
  180. self.beta = beta
  181. self.attn_gain = attn_gain
  182. if in_chs != out_chs or stride != 1 or dilation != first_dilation:
  183. self.downsample = DownsampleAvg(
  184. in_chs,
  185. out_chs,
  186. stride=stride,
  187. dilation=dilation,
  188. first_dilation=first_dilation,
  189. conv_layer=conv_layer,
  190. **dd,
  191. )
  192. else:
  193. self.downsample = None
  194. self.act1 = act_layer()
  195. self.conv1 = conv_layer(in_chs, mid_chs, 1, **dd)
  196. self.act2 = act_layer(inplace=True)
  197. self.conv2 = conv_layer(mid_chs, mid_chs, 3, stride=stride, dilation=first_dilation, groups=groups, **dd)
  198. if extra_conv:
  199. self.act2b = act_layer(inplace=True)
  200. self.conv2b = conv_layer(mid_chs, mid_chs, 3, stride=1, dilation=dilation, groups=groups, **dd)
  201. else:
  202. self.act2b = None
  203. self.conv2b = None
  204. if reg and attn_layer is not None:
  205. self.attn = attn_layer(mid_chs, **dd) # RegNet blocks apply attn btw conv2 & 3
  206. else:
  207. self.attn = None
  208. self.act3 = act_layer()
  209. self.conv3 = conv_layer(mid_chs, out_chs, 1, gain_init=1. if skipinit else 0., **dd)
  210. if not reg and attn_layer is not None:
  211. self.attn_last = attn_layer(out_chs, **dd) # ResNet blocks apply attn after conv3
  212. else:
  213. self.attn_last = None
  214. self.drop_path = DropPath(drop_path_rate) if drop_path_rate > 0 else nn.Identity()
  215. self.skipinit_gain = nn.Parameter(torch.tensor(0., **dd)) if skipinit else None
  216. def forward(self, x: torch.Tensor) -> torch.Tensor:
  217. """Forward pass.
  218. Args:
  219. x: Input tensor.
  220. Returns:
  221. Output tensor.
  222. """
  223. out = self.act1(x) * self.beta
  224. # shortcut branch
  225. shortcut = x
  226. if self.downsample is not None:
  227. shortcut = self.downsample(out)
  228. # residual branch
  229. out = self.conv1(out)
  230. out = self.conv2(self.act2(out))
  231. if self.conv2b is not None:
  232. out = self.conv2b(self.act2b(out))
  233. if self.attn is not None:
  234. out = self.attn_gain * self.attn(out)
  235. out = self.conv3(self.act3(out))
  236. if self.attn_last is not None:
  237. out = self.attn_gain * self.attn_last(out)
  238. out = self.drop_path(out)
  239. if self.skipinit_gain is not None:
  240. out.mul_(self.skipinit_gain)
  241. out = out * self.alpha + shortcut
  242. return out
  243. def create_stem(
  244. in_chs: int,
  245. out_chs: int,
  246. stem_type: str = '',
  247. conv_layer: Optional[Callable] = None,
  248. act_layer: Optional[Callable] = None,
  249. preact_feature: bool = True,
  250. device=None,
  251. dtype=None,
  252. ) -> Tuple[nn.Sequential, int, Dict[str, Any]]:
  253. """Create stem module for NFNet models.
  254. Args:
  255. in_chs: Input channels.
  256. out_chs: Output channels.
  257. stem_type: Type of stem ('', 'deep', 'deep_tiered', 'deep_quad', '3x3', '7x7', etc.).
  258. conv_layer: Convolution layer type.
  259. act_layer: Activation layer type.
  260. preact_feature: Use pre-activation feature.
  261. Returns:
  262. Tuple of (stem_module, stem_stride, stem_feature_info).
  263. """
  264. dd = {'device': device, 'dtype': dtype}
  265. stem_stride = 2
  266. stem_feature = dict(num_chs=out_chs, reduction=2, module='stem.conv')
  267. stem = OrderedDict()
  268. assert stem_type in ('', 'deep', 'deep_tiered', 'deep_quad', '3x3', '7x7', 'deep_pool', '3x3_pool', '7x7_pool')
  269. if 'deep' in stem_type:
  270. if 'quad' in stem_type:
  271. # 4 deep conv stack as in NFNet-F models
  272. assert 'pool' not in stem_type
  273. stem_chs = (out_chs // 8, out_chs // 4, out_chs // 2, out_chs)
  274. strides = (2, 1, 1, 2)
  275. stem_stride = 4
  276. stem_feature = dict(num_chs=out_chs // 2, reduction=2, module='stem.conv3')
  277. else:
  278. if 'tiered' in stem_type:
  279. stem_chs = (3 * out_chs // 8, out_chs // 2, out_chs) # 'T' resnets in resnet.py
  280. else:
  281. stem_chs = (out_chs // 2, out_chs // 2, out_chs) # 'D' ResNets
  282. strides = (2, 1, 1)
  283. stem_feature = dict(num_chs=out_chs // 2, reduction=2, module='stem.conv2')
  284. last_idx = len(stem_chs) - 1
  285. for i, (c, s) in enumerate(zip(stem_chs, strides)):
  286. stem[f'conv{i + 1}'] = conv_layer(in_chs, c, kernel_size=3, stride=s, **dd)
  287. if i != last_idx:
  288. stem[f'act{i + 2}'] = act_layer(inplace=True)
  289. in_chs = c
  290. elif '3x3' in stem_type:
  291. # 3x3 stem conv as in RegNet
  292. stem['conv'] = conv_layer(in_chs, out_chs, kernel_size=3, stride=2, **dd)
  293. else:
  294. # 7x7 stem conv as in ResNet
  295. stem['conv'] = conv_layer(in_chs, out_chs, kernel_size=7, stride=2, **dd)
  296. if 'pool' in stem_type:
  297. stem['pool'] = nn.MaxPool2d(3, stride=2, padding=1)
  298. stem_stride = 4
  299. return nn.Sequential(stem), stem_stride, stem_feature
  300. # from https://github.com/deepmind/deepmind-research/tree/master/nfnets
  301. _nonlin_gamma = dict(
  302. identity=1.0,
  303. celu=1.270926833152771,
  304. elu=1.2716004848480225,
  305. gelu=1.7015043497085571,
  306. leaky_relu=1.70590341091156,
  307. log_sigmoid=1.9193484783172607,
  308. log_softmax=1.0002083778381348,
  309. relu=1.7139588594436646,
  310. relu6=1.7131484746932983,
  311. selu=1.0008515119552612,
  312. sigmoid=4.803835391998291,
  313. silu=1.7881293296813965,
  314. softsign=2.338853120803833,
  315. softplus=1.9203323125839233,
  316. tanh=1.5939117670059204,
  317. )
  318. class NormFreeNet(nn.Module):
  319. """ Normalization-Free Network
  320. As described in :
  321. `Characterizing signal propagation to close the performance gap in unnormalized ResNets`
  322. - https://arxiv.org/abs/2101.08692
  323. and
  324. `High-Performance Large-Scale Image Recognition Without Normalization` - https://arxiv.org/abs/2102.06171
  325. This model aims to cover both the NFRegNet-Bx models as detailed in the paper's code snippets and
  326. the (preact) ResNet models described earlier in the paper.
  327. There are a few differences:
  328. * channels are rounded to be divisible by 8 by default (keep tensor core kernels happy),
  329. this changes channel dim and param counts slightly from the paper models
  330. * activation correcting gamma constants are moved into the ScaledStdConv as it has less performance
  331. impact in PyTorch when done with the weight scaling there. This likely wasn't a concern in the JAX impl.
  332. * a config option `gamma_in_act` can be enabled to not apply gamma in StdConv as described above, but
  333. apply it in each activation. This is slightly slower, numerically different, but matches official impl.
  334. * skipinit is disabled by default, it seems to have a rather drastic impact on GPU memory use and throughput
  335. for what it is/does. Approx 8-10% throughput loss.
  336. """
  337. def __init__(
  338. self,
  339. cfg: NfCfg,
  340. num_classes: int = 1000,
  341. in_chans: int = 3,
  342. global_pool: str = 'avg',
  343. output_stride: int = 32,
  344. drop_rate: float = 0.,
  345. drop_path_rate: float = 0.,
  346. device=None,
  347. dtype=None,
  348. **kwargs: Any,
  349. ):
  350. """
  351. Args:
  352. cfg: Model architecture configuration.
  353. num_classes: Number of classifier classes.
  354. in_chans: Number of input channels.
  355. global_pool: Global pooling type.
  356. output_stride: Output stride of network, one of (8, 16, 32).
  357. drop_rate: Dropout rate.
  358. drop_path_rate: Stochastic depth drop-path rate.
  359. **kwargs: Extra kwargs overlayed onto cfg.
  360. """
  361. super().__init__()
  362. dd = {'device': device, 'dtype': dtype}
  363. self.num_classes = num_classes
  364. self.in_chans = in_chans
  365. self.drop_rate = drop_rate
  366. self.grad_checkpointing = False
  367. cfg = replace(cfg, **kwargs)
  368. assert cfg.act_layer in _nonlin_gamma, f"Please add non-linearity constants for activation ({cfg.act_layer})."
  369. conv_layer = ScaledStdConv2dSame if cfg.same_padding else ScaledStdConv2d
  370. if cfg.gamma_in_act:
  371. act_layer = act_with_gamma(cfg.act_layer, gamma=_nonlin_gamma[cfg.act_layer])
  372. conv_layer = partial(conv_layer, eps=cfg.std_conv_eps)
  373. else:
  374. act_layer = get_act_layer(cfg.act_layer)
  375. conv_layer = partial(conv_layer, gamma=_nonlin_gamma[cfg.act_layer], eps=cfg.std_conv_eps)
  376. attn_layer = partial(get_attn(cfg.attn_layer), **cfg.attn_kwargs) if cfg.attn_layer else None
  377. stem_chs = make_divisible((cfg.stem_chs or cfg.channels[0]) * cfg.width_factor, cfg.ch_div)
  378. self.stem, stem_stride, stem_feat = create_stem(
  379. in_chans,
  380. stem_chs,
  381. cfg.stem_type,
  382. conv_layer=conv_layer,
  383. act_layer=act_layer,
  384. **dd,
  385. )
  386. self.feature_info = [stem_feat]
  387. drop_path_rates = calculate_drop_path_rates(drop_path_rate, cfg.depths, stagewise=True)
  388. prev_chs = stem_chs
  389. net_stride = stem_stride
  390. dilation = 1
  391. expected_var = 1.0
  392. stages = []
  393. for stage_idx, stage_depth in enumerate(cfg.depths):
  394. stride = 1 if stage_idx == 0 and stem_stride > 2 else 2
  395. if net_stride >= output_stride and stride > 1:
  396. dilation *= stride
  397. stride = 1
  398. net_stride *= stride
  399. first_dilation = 1 if dilation in (1, 2) else 2
  400. blocks = []
  401. for block_idx in range(cfg.depths[stage_idx]):
  402. first_block = block_idx == 0 and stage_idx == 0
  403. out_chs = make_divisible(cfg.channels[stage_idx] * cfg.width_factor, cfg.ch_div)
  404. blocks += [NormFreeBlock(
  405. in_chs=prev_chs, out_chs=out_chs,
  406. alpha=cfg.alpha,
  407. beta=1. / expected_var ** 0.5,
  408. stride=stride if block_idx == 0 else 1,
  409. dilation=dilation,
  410. first_dilation=first_dilation,
  411. group_size=cfg.group_size,
  412. bottle_ratio=1. if cfg.reg and first_block else cfg.bottle_ratio,
  413. ch_div=cfg.ch_div,
  414. reg=cfg.reg,
  415. extra_conv=cfg.extra_conv,
  416. skipinit=cfg.skipinit,
  417. attn_layer=attn_layer,
  418. attn_gain=cfg.attn_gain,
  419. act_layer=act_layer,
  420. conv_layer=conv_layer,
  421. drop_path_rate=drop_path_rates[stage_idx][block_idx],
  422. **dd,
  423. )]
  424. if block_idx == 0:
  425. expected_var = 1. # expected var is reset after first block of each stage
  426. expected_var += cfg.alpha ** 2 # Even if reset occurs, increment expected variance
  427. first_dilation = dilation
  428. prev_chs = out_chs
  429. self.feature_info += [dict(num_chs=prev_chs, reduction=net_stride, module=f'stages.{stage_idx}')]
  430. stages += [nn.Sequential(*blocks)]
  431. self.stages = nn.Sequential(*stages)
  432. if cfg.num_features:
  433. # The paper NFRegNet models have an EfficientNet-like final head convolution.
  434. self.num_features = make_divisible(cfg.width_factor * cfg.num_features, cfg.ch_div)
  435. self.final_conv = conv_layer(prev_chs, self.num_features, 1, **dd)
  436. self.feature_info[-1] = dict(num_chs=self.num_features, reduction=net_stride, module=f'final_conv')
  437. else:
  438. self.num_features = prev_chs
  439. self.final_conv = nn.Identity()
  440. self.final_act = act_layer(inplace=cfg.num_features > 0)
  441. self.head_hidden_size = self.num_features
  442. self.head = ClassifierHead(
  443. self.num_features,
  444. num_classes,
  445. pool_type=global_pool,
  446. drop_rate=self.drop_rate,
  447. **dd,
  448. )
  449. for n, m in self.named_modules():
  450. if 'fc' in n and isinstance(m, nn.Linear):
  451. if cfg.zero_init_fc:
  452. nn.init.zeros_(m.weight)
  453. else:
  454. nn.init.normal_(m.weight, 0., .01)
  455. if m.bias is not None:
  456. nn.init.zeros_(m.bias)
  457. elif isinstance(m, nn.Conv2d):
  458. nn.init.kaiming_normal_(m.weight, mode='fan_in', nonlinearity='linear')
  459. if m.bias is not None:
  460. nn.init.zeros_(m.bias)
  461. @torch.jit.ignore
  462. def group_matcher(self, coarse: bool = False) -> Dict[str, Any]:
  463. """Group parameters for optimization."""
  464. matcher = dict(
  465. stem=r'^stem',
  466. blocks=[
  467. (r'^stages\.(\d+)' if coarse else r'^stages\.(\d+)\.(\d+)', None),
  468. (r'^final_conv', (99999,))
  469. ]
  470. )
  471. return matcher
  472. @torch.jit.ignore
  473. def set_grad_checkpointing(self, enable: bool = True) -> None:
  474. """Enable or disable gradient checkpointing."""
  475. self.grad_checkpointing = enable
  476. @torch.jit.ignore
  477. def get_classifier(self) -> nn.Module:
  478. """Get the classifier head."""
  479. return self.head.fc
  480. def reset_classifier(self, num_classes: int, global_pool: Optional[str] = None) -> None:
  481. """Reset the classifier head.
  482. Args:
  483. num_classes: Number of classes for new classifier.
  484. global_pool: Global pooling type.
  485. """
  486. self.num_classes = num_classes
  487. self.head.reset(num_classes, global_pool)
  488. def forward_features(self, x: torch.Tensor) -> torch.Tensor:
  489. """Forward pass through feature extraction layers.
  490. Args:
  491. x: Input tensor.
  492. Returns:
  493. Feature tensor.
  494. """
  495. x = self.stem(x)
  496. if self.grad_checkpointing and not torch.jit.is_scripting():
  497. x = checkpoint_seq(self.stages, x)
  498. else:
  499. x = self.stages(x)
  500. x = self.final_conv(x)
  501. x = self.final_act(x)
  502. return x
  503. def forward_head(self, x: torch.Tensor, pre_logits: bool = False) -> torch.Tensor:
  504. """Forward pass through classifier head.
  505. Args:
  506. x: Input features.
  507. pre_logits: Return features before final linear layer.
  508. Returns:
  509. Classification logits or features.
  510. """
  511. return self.head(x, pre_logits=pre_logits) if pre_logits else self.head(x)
  512. def forward(self, x: torch.Tensor) -> torch.Tensor:
  513. """Forward pass.
  514. Args:
  515. x: Input tensor.
  516. Returns:
  517. Output logits.
  518. """
  519. x = self.forward_features(x)
  520. x = self.forward_head(x)
  521. return x
  522. def _nfres_cfg(
  523. depths: Tuple[int, ...],
  524. channels: Tuple[int, ...] = (256, 512, 1024, 2048),
  525. group_size: Optional[int] = None,
  526. act_layer: str = 'relu',
  527. attn_layer: Optional[str] = None,
  528. attn_kwargs: Optional[Dict[str, Any]] = None,
  529. ) -> NfCfg:
  530. """Create NFNet ResNet configuration.
  531. Args:
  532. depths: Number of blocks in each stage.
  533. channels: Channel dimensions for each stage.
  534. group_size: Group convolution size.
  535. act_layer: Activation layer type.
  536. attn_layer: Attention layer type.
  537. attn_kwargs: Attention layer arguments.
  538. Returns:
  539. NFNet configuration.
  540. """
  541. attn_kwargs = attn_kwargs or {}
  542. cfg = NfCfg(
  543. depths=depths,
  544. channels=channels,
  545. stem_type='7x7_pool',
  546. stem_chs=64,
  547. bottle_ratio=0.25,
  548. group_size=group_size,
  549. act_layer=act_layer,
  550. attn_layer=attn_layer,
  551. attn_kwargs=attn_kwargs,
  552. )
  553. return cfg
  554. def _nfreg_cfg(depths: Tuple[int, ...], channels: Tuple[int, ...] = (48, 104, 208, 440)) -> NfCfg:
  555. """Create NFNet RegNet configuration.
  556. Args:
  557. depths: Number of blocks in each stage.
  558. channels: Channel dimensions for each stage.
  559. Returns:
  560. NFNet configuration.
  561. """
  562. num_features = 1280 * channels[-1] // 440
  563. attn_kwargs = dict(rd_ratio=0.5)
  564. cfg = NfCfg(
  565. depths=depths,
  566. channels=channels,
  567. stem_type='3x3',
  568. group_size=8,
  569. width_factor=0.75,
  570. bottle_ratio=2.25,
  571. num_features=num_features,
  572. reg=True,
  573. attn_layer='se',
  574. attn_kwargs=attn_kwargs,
  575. )
  576. return cfg
  577. def _nfnet_cfg(
  578. depths: Tuple[int, ...],
  579. channels: Tuple[int, ...] = (256, 512, 1536, 1536),
  580. group_size: int = 128,
  581. bottle_ratio: float = 0.5,
  582. feat_mult: float = 2.,
  583. act_layer: str = 'gelu',
  584. attn_layer: str = 'se',
  585. attn_kwargs: Optional[Dict[str, Any]] = None,
  586. ) -> NfCfg:
  587. """Create NFNet configuration.
  588. Args:
  589. depths: Number of blocks in each stage.
  590. channels: Channel dimensions for each stage.
  591. group_size: Group convolution size.
  592. bottle_ratio: Bottleneck ratio.
  593. feat_mult: Feature multiplier for final layer.
  594. act_layer: Activation layer type.
  595. attn_layer: Attention layer type.
  596. attn_kwargs: Attention layer arguments.
  597. Returns:
  598. NFNet configuration.
  599. """
  600. num_features = int(channels[-1] * feat_mult)
  601. attn_kwargs = attn_kwargs if attn_kwargs is not None else dict(rd_ratio=0.5)
  602. cfg = NfCfg(
  603. depths=depths,
  604. channels=channels,
  605. stem_type='deep_quad',
  606. stem_chs=128,
  607. group_size=group_size,
  608. bottle_ratio=bottle_ratio,
  609. extra_conv=True,
  610. num_features=num_features,
  611. act_layer=act_layer,
  612. attn_layer=attn_layer,
  613. attn_kwargs=attn_kwargs,
  614. )
  615. return cfg
  616. def _dm_nfnet_cfg(
  617. depths: Tuple[int, ...],
  618. channels: Tuple[int, ...] = (256, 512, 1536, 1536),
  619. act_layer: str = 'gelu',
  620. skipinit: bool = True,
  621. ) -> NfCfg:
  622. """Create DeepMind NFNet configuration.
  623. Args:
  624. depths: Number of blocks in each stage.
  625. channels: Channel dimensions for each stage.
  626. act_layer: Activation layer type.
  627. skipinit: Use skipinit initialization.
  628. Returns:
  629. NFNet configuration.
  630. """
  631. cfg = NfCfg(
  632. depths=depths,
  633. channels=channels,
  634. stem_type='deep_quad',
  635. stem_chs=128,
  636. group_size=128,
  637. bottle_ratio=0.5,
  638. extra_conv=True,
  639. gamma_in_act=True,
  640. same_padding=True,
  641. skipinit=skipinit,
  642. num_features=int(channels[-1] * 2.0),
  643. act_layer=act_layer,
  644. attn_layer='se',
  645. attn_kwargs=dict(rd_ratio=0.5),
  646. )
  647. return cfg
  648. model_cfgs = dict(
  649. # NFNet-F models w/ GELU compatible with DeepMind weights
  650. dm_nfnet_f0=_dm_nfnet_cfg(depths=(1, 2, 6, 3)),
  651. dm_nfnet_f1=_dm_nfnet_cfg(depths=(2, 4, 12, 6)),
  652. dm_nfnet_f2=_dm_nfnet_cfg(depths=(3, 6, 18, 9)),
  653. dm_nfnet_f3=_dm_nfnet_cfg(depths=(4, 8, 24, 12)),
  654. dm_nfnet_f4=_dm_nfnet_cfg(depths=(5, 10, 30, 15)),
  655. dm_nfnet_f5=_dm_nfnet_cfg(depths=(6, 12, 36, 18)),
  656. dm_nfnet_f6=_dm_nfnet_cfg(depths=(7, 14, 42, 21)),
  657. # NFNet-F models w/ GELU
  658. nfnet_f0=_nfnet_cfg(depths=(1, 2, 6, 3)),
  659. nfnet_f1=_nfnet_cfg(depths=(2, 4, 12, 6)),
  660. nfnet_f2=_nfnet_cfg(depths=(3, 6, 18, 9)),
  661. nfnet_f3=_nfnet_cfg(depths=(4, 8, 24, 12)),
  662. nfnet_f4=_nfnet_cfg(depths=(5, 10, 30, 15)),
  663. nfnet_f5=_nfnet_cfg(depths=(6, 12, 36, 18)),
  664. nfnet_f6=_nfnet_cfg(depths=(7, 14, 42, 21)),
  665. nfnet_f7=_nfnet_cfg(depths=(8, 16, 48, 24)),
  666. # Experimental 'light' versions of NFNet-F that are little leaner, w/ SiLU act
  667. nfnet_l0=_nfnet_cfg(
  668. depths=(1, 2, 6, 3), feat_mult=1.5, group_size=64, bottle_ratio=0.25,
  669. attn_kwargs=dict(rd_ratio=0.25, rd_divisor=8), act_layer='silu'),
  670. eca_nfnet_l0=_nfnet_cfg(
  671. depths=(1, 2, 6, 3), feat_mult=1.5, group_size=64, bottle_ratio=0.25,
  672. attn_layer='eca', attn_kwargs=dict(), act_layer='silu'),
  673. eca_nfnet_l1=_nfnet_cfg(
  674. depths=(2, 4, 12, 6), feat_mult=2, group_size=64, bottle_ratio=0.25,
  675. attn_layer='eca', attn_kwargs=dict(), act_layer='silu'),
  676. eca_nfnet_l2=_nfnet_cfg(
  677. depths=(3, 6, 18, 9), feat_mult=2, group_size=64, bottle_ratio=0.25,
  678. attn_layer='eca', attn_kwargs=dict(), act_layer='silu'),
  679. eca_nfnet_l3=_nfnet_cfg(
  680. depths=(4, 8, 24, 12), feat_mult=2, group_size=64, bottle_ratio=0.25,
  681. attn_layer='eca', attn_kwargs=dict(), act_layer='silu'),
  682. # EffNet influenced RegNet defs.
  683. # NOTE: These aren't quite the official ver, ch_div=1 must be set for exact ch counts. I round to ch_div=8.
  684. nf_regnet_b0=_nfreg_cfg(depths=(1, 3, 6, 6)),
  685. nf_regnet_b1=_nfreg_cfg(depths=(2, 4, 7, 7)),
  686. nf_regnet_b2=_nfreg_cfg(depths=(2, 4, 8, 8), channels=(56, 112, 232, 488)),
  687. nf_regnet_b3=_nfreg_cfg(depths=(2, 5, 9, 9), channels=(56, 128, 248, 528)),
  688. nf_regnet_b4=_nfreg_cfg(depths=(2, 6, 11, 11), channels=(64, 144, 288, 616)),
  689. nf_regnet_b5=_nfreg_cfg(depths=(3, 7, 14, 14), channels=(80, 168, 336, 704)),
  690. # ResNet (preact, D style deep stem/avg down) defs
  691. nf_resnet26=_nfres_cfg(depths=(2, 2, 2, 2)),
  692. nf_resnet50=_nfres_cfg(depths=(3, 4, 6, 3)),
  693. nf_resnet101=_nfres_cfg(depths=(3, 4, 23, 3)),
  694. nf_seresnet26=_nfres_cfg(depths=(2, 2, 2, 2), attn_layer='se', attn_kwargs=dict(rd_ratio=1/16)),
  695. nf_seresnet50=_nfres_cfg(depths=(3, 4, 6, 3), attn_layer='se', attn_kwargs=dict(rd_ratio=1/16)),
  696. nf_seresnet101=_nfres_cfg(depths=(3, 4, 23, 3), attn_layer='se', attn_kwargs=dict(rd_ratio=1/16)),
  697. nf_ecaresnet26=_nfres_cfg(depths=(2, 2, 2, 2), attn_layer='eca', attn_kwargs=dict()),
  698. nf_ecaresnet50=_nfres_cfg(depths=(3, 4, 6, 3), attn_layer='eca', attn_kwargs=dict()),
  699. nf_ecaresnet101=_nfres_cfg(depths=(3, 4, 23, 3), attn_layer='eca', attn_kwargs=dict()),
  700. test_nfnet=_nfnet_cfg(
  701. depths=(1, 1, 1, 1), channels=(32, 64, 96, 128), feat_mult=1.5, group_size=8, bottle_ratio=0.25,
  702. attn_kwargs=dict(rd_ratio=0.25, rd_divisor=8), act_layer='silu'),
  703. )
  704. def _create_normfreenet(variant: str, pretrained: bool = False, **kwargs: Any) -> NormFreeNet:
  705. """Create a NormFreeNet model.
  706. Args:
  707. variant: Model variant name.
  708. pretrained: Load pretrained weights.
  709. **kwargs: Additional model arguments.
  710. Returns:
  711. NormFreeNet model instance.
  712. """
  713. model_cfg = model_cfgs[variant]
  714. feature_cfg = dict(flatten_sequential=True)
  715. return build_model_with_cfg(
  716. NormFreeNet,
  717. variant,
  718. pretrained,
  719. model_cfg=model_cfg,
  720. feature_cfg=feature_cfg,
  721. **kwargs,
  722. )
  723. def _dcfg(url: str = '', **kwargs: Any) -> Dict[str, Any]:
  724. """Create default configuration dictionary.
  725. Args:
  726. url: Model weight URL.
  727. **kwargs: Additional configuration options.
  728. Returns:
  729. Configuration dictionary.
  730. """
  731. return {
  732. 'url': url,
  733. 'num_classes': 1000, 'input_size': (3, 224, 224), 'pool_size': (7, 7),
  734. 'crop_pct': 0.9, 'interpolation': 'bicubic',
  735. 'mean': IMAGENET_DEFAULT_MEAN, 'std': IMAGENET_DEFAULT_STD,
  736. 'first_conv': 'stem.conv1', 'classifier': 'head.fc', 'license': 'apache-2.0',
  737. **kwargs
  738. }
  739. default_cfgs = generate_default_cfgs({
  740. 'dm_nfnet_f0.dm_in1k': _dcfg(
  741. hf_hub_id='timm/',
  742. url='https://github.com/rwightman/pytorch-image-models/releases/download/v0.1-dnf-weights/dm_nfnet_f0-604f9c3a.pth',
  743. pool_size=(6, 6), input_size=(3, 192, 192), test_input_size=(3, 256, 256), crop_pct=.9, crop_mode='squash'),
  744. 'dm_nfnet_f1.dm_in1k': _dcfg(
  745. hf_hub_id='timm/',
  746. url='https://github.com/rwightman/pytorch-image-models/releases/download/v0.1-dnf-weights/dm_nfnet_f1-fc540f82.pth',
  747. pool_size=(7, 7), input_size=(3, 224, 224), test_input_size=(3, 320, 320), crop_pct=0.91, crop_mode='squash'),
  748. 'dm_nfnet_f2.dm_in1k': _dcfg(
  749. hf_hub_id='timm/',
  750. url='https://github.com/rwightman/pytorch-image-models/releases/download/v0.1-dnf-weights/dm_nfnet_f2-89875923.pth',
  751. pool_size=(8, 8), input_size=(3, 256, 256), test_input_size=(3, 352, 352), crop_pct=0.92, crop_mode='squash'),
  752. 'dm_nfnet_f3.dm_in1k': _dcfg(
  753. hf_hub_id='timm/',
  754. url='https://github.com/rwightman/pytorch-image-models/releases/download/v0.1-dnf-weights/dm_nfnet_f3-d74ab3aa.pth',
  755. pool_size=(10, 10), input_size=(3, 320, 320), test_input_size=(3, 416, 416), crop_pct=0.94, crop_mode='squash'),
  756. 'dm_nfnet_f4.dm_in1k': _dcfg(
  757. hf_hub_id='timm/',
  758. url='https://github.com/rwightman/pytorch-image-models/releases/download/v0.1-dnf-weights/dm_nfnet_f4-0ac5b10b.pth',
  759. pool_size=(12, 12), input_size=(3, 384, 384), test_input_size=(3, 512, 512), crop_pct=0.951, crop_mode='squash'),
  760. 'dm_nfnet_f5.dm_in1k': _dcfg(
  761. hf_hub_id='timm/',
  762. url='https://github.com/rwightman/pytorch-image-models/releases/download/v0.1-dnf-weights/dm_nfnet_f5-ecb20ab1.pth',
  763. pool_size=(13, 13), input_size=(3, 416, 416), test_input_size=(3, 544, 544), crop_pct=0.954, crop_mode='squash'),
  764. 'dm_nfnet_f6.dm_in1k': _dcfg(
  765. hf_hub_id='timm/',
  766. url='https://github.com/rwightman/pytorch-image-models/releases/download/v0.1-dnf-weights/dm_nfnet_f6-e0f12116.pth',
  767. pool_size=(14, 14), input_size=(3, 448, 448), test_input_size=(3, 576, 576), crop_pct=0.956, crop_mode='squash'),
  768. 'nfnet_f0': _dcfg(
  769. url='', pool_size=(6, 6), input_size=(3, 192, 192), test_input_size=(3, 256, 256)),
  770. 'nfnet_f1': _dcfg(
  771. url='', pool_size=(7, 7), input_size=(3, 224, 224), test_input_size=(3, 320, 320)),
  772. 'nfnet_f2': _dcfg(
  773. url='', pool_size=(8, 8), input_size=(3, 256, 256), test_input_size=(3, 352, 352)),
  774. 'nfnet_f3': _dcfg(
  775. url='', pool_size=(10, 10), input_size=(3, 320, 320), test_input_size=(3, 416, 416)),
  776. 'nfnet_f4': _dcfg(
  777. url='', pool_size=(12, 12), input_size=(3, 384, 384), test_input_size=(3, 512, 512)),
  778. 'nfnet_f5': _dcfg(
  779. url='', pool_size=(13, 13), input_size=(3, 416, 416), test_input_size=(3, 544, 544)),
  780. 'nfnet_f6': _dcfg(
  781. url='', pool_size=(14, 14), input_size=(3, 448, 448), test_input_size=(3, 576, 576)),
  782. 'nfnet_f7': _dcfg(
  783. url='', pool_size=(15, 15), input_size=(3, 480, 480), test_input_size=(3, 608, 608)),
  784. 'nfnet_l0.ra2_in1k': _dcfg(
  785. hf_hub_id='timm/',
  786. url='https://github.com/rwightman/pytorch-image-models/releases/download/v0.1-weights/nfnet_l0_ra2-45c6688d.pth',
  787. pool_size=(7, 7), input_size=(3, 224, 224), test_input_size=(3, 288, 288), test_crop_pct=1.0),
  788. 'eca_nfnet_l0.ra2_in1k': _dcfg(
  789. hf_hub_id='timm/',
  790. url='https://github.com/rwightman/pytorch-image-models/releases/download/v0.1-weights/ecanfnet_l0_ra2-e3e9ac50.pth',
  791. pool_size=(7, 7), input_size=(3, 224, 224), test_input_size=(3, 288, 288), test_crop_pct=1.0),
  792. 'eca_nfnet_l1.ra2_in1k': _dcfg(
  793. hf_hub_id='timm/',
  794. url='https://github.com/rwightman/pytorch-image-models/releases/download/v0.1-weights/ecanfnet_l1_ra2-7dce93cd.pth',
  795. pool_size=(8, 8), input_size=(3, 256, 256), test_input_size=(3, 320, 320), test_crop_pct=1.0),
  796. 'eca_nfnet_l2.ra3_in1k': _dcfg(
  797. hf_hub_id='timm/',
  798. url='https://github.com/rwightman/pytorch-image-models/releases/download/v0.1-weights/ecanfnet_l2_ra3-da781a61.pth',
  799. pool_size=(10, 10), input_size=(3, 320, 320), test_input_size=(3, 384, 384), test_crop_pct=1.0),
  800. 'eca_nfnet_l3': _dcfg(
  801. url='',
  802. pool_size=(11, 11), input_size=(3, 352, 352), test_input_size=(3, 448, 448), test_crop_pct=1.0),
  803. 'nf_regnet_b0': _dcfg(
  804. url='', pool_size=(6, 6), input_size=(3, 192, 192), test_input_size=(3, 256, 256), first_conv='stem.conv'),
  805. 'nf_regnet_b1.ra2_in1k': _dcfg(
  806. hf_hub_id='timm/',
  807. url='https://github.com/rwightman/pytorch-image-models/releases/download/v0.1-weights/nf_regnet_b1_256_ra2-ad85cfef.pth',
  808. pool_size=(8, 8), input_size=(3, 256, 256), test_input_size=(3, 288, 288), first_conv='stem.conv'), # NOT to paper spec
  809. 'nf_regnet_b2': _dcfg(
  810. url='', pool_size=(8, 8), input_size=(3, 240, 240), test_input_size=(3, 272, 272), first_conv='stem.conv'),
  811. 'nf_regnet_b3': _dcfg(
  812. url='', pool_size=(9, 9), input_size=(3, 288, 288), test_input_size=(3, 320, 320), first_conv='stem.conv'),
  813. 'nf_regnet_b4': _dcfg(
  814. url='', pool_size=(10, 10), input_size=(3, 320, 320), test_input_size=(3, 384, 384), first_conv='stem.conv'),
  815. 'nf_regnet_b5': _dcfg(
  816. url='', pool_size=(12, 12), input_size=(3, 384, 384), test_input_size=(3, 456, 456), first_conv='stem.conv'),
  817. 'nf_resnet26': _dcfg(url='', first_conv='stem.conv'),
  818. 'nf_resnet50.ra2_in1k': _dcfg(
  819. hf_hub_id='timm/',
  820. url='https://github.com/rwightman/pytorch-image-models/releases/download/v0.1-weights/nf_resnet50_ra2-9f236009.pth',
  821. pool_size=(8, 8), input_size=(3, 256, 256), test_input_size=(3, 288, 288), crop_pct=0.94, first_conv='stem.conv'),
  822. 'nf_resnet101': _dcfg(url='', first_conv='stem.conv'),
  823. 'nf_seresnet26': _dcfg(url='', first_conv='stem.conv'),
  824. 'nf_seresnet50': _dcfg(url='', first_conv='stem.conv'),
  825. 'nf_seresnet101': _dcfg(url='', first_conv='stem.conv'),
  826. 'nf_ecaresnet26': _dcfg(url='', first_conv='stem.conv'),
  827. 'nf_ecaresnet50': _dcfg(url='', first_conv='stem.conv'),
  828. 'nf_ecaresnet101': _dcfg(url='', first_conv='stem.conv'),
  829. 'test_nfnet.r160_in1k': _dcfg(
  830. hf_hub_id='timm/',
  831. mean=(0.5, 0.5, 0.5), std=(0.5, 0.5, 0.5),
  832. crop_pct=0.95, input_size=(3, 160, 160), pool_size=(5, 5)),
  833. })
  834. @register_model
  835. def dm_nfnet_f0(pretrained: bool = False, **kwargs: Any) -> NormFreeNet:
  836. """NFNet-F0 (DeepMind weight compatible)."""
  837. return _create_normfreenet('dm_nfnet_f0', pretrained=pretrained, **kwargs)
  838. @register_model
  839. def dm_nfnet_f1(pretrained: bool = False, **kwargs: Any) -> NormFreeNet:
  840. """NFNet-F1 (DeepMind weight compatible)."""
  841. return _create_normfreenet('dm_nfnet_f1', pretrained=pretrained, **kwargs)
  842. @register_model
  843. def dm_nfnet_f2(pretrained: bool = False, **kwargs: Any) -> NormFreeNet:
  844. """NFNet-F2 (DeepMind weight compatible)."""
  845. return _create_normfreenet('dm_nfnet_f2', pretrained=pretrained, **kwargs)
  846. @register_model
  847. def dm_nfnet_f3(pretrained: bool = False, **kwargs: Any) -> NormFreeNet:
  848. """NFNet-F3 (DeepMind weight compatible)."""
  849. return _create_normfreenet('dm_nfnet_f3', pretrained=pretrained, **kwargs)
  850. @register_model
  851. def dm_nfnet_f4(pretrained: bool = False, **kwargs: Any) -> NormFreeNet:
  852. """NFNet-F4 (DeepMind weight compatible)."""
  853. return _create_normfreenet('dm_nfnet_f4', pretrained=pretrained, **kwargs)
  854. @register_model
  855. def dm_nfnet_f5(pretrained: bool = False, **kwargs: Any) -> NormFreeNet:
  856. """NFNet-F5 (DeepMind weight compatible)."""
  857. return _create_normfreenet('dm_nfnet_f5', pretrained=pretrained, **kwargs)
  858. @register_model
  859. def dm_nfnet_f6(pretrained: bool = False, **kwargs: Any) -> NormFreeNet:
  860. """NFNet-F6 (DeepMind weight compatible)."""
  861. return _create_normfreenet('dm_nfnet_f6', pretrained=pretrained, **kwargs)
  862. @register_model
  863. def nfnet_f0(pretrained: bool = False, **kwargs: Any) -> NormFreeNet:
  864. """NFNet-F0."""
  865. return _create_normfreenet('nfnet_f0', pretrained=pretrained, **kwargs)
  866. @register_model
  867. def nfnet_f1(pretrained: bool = False, **kwargs: Any) -> NormFreeNet:
  868. """NFNet-F1."""
  869. return _create_normfreenet('nfnet_f1', pretrained=pretrained, **kwargs)
  870. @register_model
  871. def nfnet_f2(pretrained: bool = False, **kwargs: Any) -> NormFreeNet:
  872. """NFNet-F2."""
  873. return _create_normfreenet('nfnet_f2', pretrained=pretrained, **kwargs)
  874. @register_model
  875. def nfnet_f3(pretrained: bool = False, **kwargs: Any) -> NormFreeNet:
  876. """NFNet-F3."""
  877. return _create_normfreenet('nfnet_f3', pretrained=pretrained, **kwargs)
  878. @register_model
  879. def nfnet_f4(pretrained: bool = False, **kwargs: Any) -> NormFreeNet:
  880. """NFNet-F4."""
  881. return _create_normfreenet('nfnet_f4', pretrained=pretrained, **kwargs)
  882. @register_model
  883. def nfnet_f5(pretrained: bool = False, **kwargs: Any) -> NormFreeNet:
  884. """NFNet-F5."""
  885. return _create_normfreenet('nfnet_f5', pretrained=pretrained, **kwargs)
  886. @register_model
  887. def nfnet_f6(pretrained: bool = False, **kwargs: Any) -> NormFreeNet:
  888. """NFNet-F6."""
  889. return _create_normfreenet('nfnet_f6', pretrained=pretrained, **kwargs)
  890. @register_model
  891. def nfnet_f7(pretrained: bool = False, **kwargs: Any) -> NormFreeNet:
  892. """NFNet-F7."""
  893. return _create_normfreenet('nfnet_f7', pretrained=pretrained, **kwargs)
  894. @register_model
  895. def nfnet_l0(pretrained: bool = False, **kwargs: Any) -> NormFreeNet:
  896. """NFNet-L0b w/ SiLU.
  897. My experimental 'light' model w/ F0 repeats, 1.5x final_conv mult, 64 group_size, .25 bottleneck & SE ratio
  898. """
  899. return _create_normfreenet('nfnet_l0', pretrained=pretrained, **kwargs)
  900. @register_model
  901. def eca_nfnet_l0(pretrained: bool = False, **kwargs: Any) -> NormFreeNet:
  902. """ECA-NFNet-L0 w/ SiLU.
  903. My experimental 'light' model w/ F0 repeats, 1.5x final_conv mult, 64 group_size, .25 bottleneck & ECA attn
  904. """
  905. return _create_normfreenet('eca_nfnet_l0', pretrained=pretrained, **kwargs)
  906. @register_model
  907. def eca_nfnet_l1(pretrained: bool = False, **kwargs: Any) -> NormFreeNet:
  908. """ECA-NFNet-L1 w/ SiLU.
  909. My experimental 'light' model w/ F1 repeats, 2.0x final_conv mult, 64 group_size, .25 bottleneck & ECA attn
  910. """
  911. return _create_normfreenet('eca_nfnet_l1', pretrained=pretrained, **kwargs)
  912. @register_model
  913. def eca_nfnet_l2(pretrained: bool = False, **kwargs: Any) -> NormFreeNet:
  914. """ECA-NFNet-L2 w/ SiLU.
  915. My experimental 'light' model w/ F2 repeats, 2.0x final_conv mult, 64 group_size, .25 bottleneck & ECA attn
  916. """
  917. return _create_normfreenet('eca_nfnet_l2', pretrained=pretrained, **kwargs)
  918. @register_model
  919. def eca_nfnet_l3(pretrained: bool = False, **kwargs: Any) -> NormFreeNet:
  920. """ECA-NFNet-L3 w/ SiLU.
  921. My experimental 'light' model w/ F3 repeats, 2.0x final_conv mult, 64 group_size, .25 bottleneck & ECA attn
  922. """
  923. return _create_normfreenet('eca_nfnet_l3', pretrained=pretrained, **kwargs)
  924. @register_model
  925. def nf_regnet_b0(pretrained: bool = False, **kwargs: Any) -> NormFreeNet:
  926. """Normalization-Free RegNet-B0.
  927. """
  928. return _create_normfreenet('nf_regnet_b0', pretrained=pretrained, **kwargs)
  929. @register_model
  930. def nf_regnet_b1(pretrained: bool = False, **kwargs: Any) -> NormFreeNet:
  931. """Normalization-Free RegNet-B1.
  932. """
  933. return _create_normfreenet('nf_regnet_b1', pretrained=pretrained, **kwargs)
  934. @register_model
  935. def nf_regnet_b2(pretrained: bool = False, **kwargs: Any) -> NormFreeNet:
  936. """Normalization-Free RegNet-B2.
  937. """
  938. return _create_normfreenet('nf_regnet_b2', pretrained=pretrained, **kwargs)
  939. @register_model
  940. def nf_regnet_b3(pretrained: bool = False, **kwargs: Any) -> NormFreeNet:
  941. """Normalization-Free RegNet-B3.
  942. """
  943. return _create_normfreenet('nf_regnet_b3', pretrained=pretrained, **kwargs)
  944. @register_model
  945. def nf_regnet_b4(pretrained: bool = False, **kwargs: Any) -> NormFreeNet:
  946. """Normalization-Free RegNet-B4.
  947. """
  948. return _create_normfreenet('nf_regnet_b4', pretrained=pretrained, **kwargs)
  949. @register_model
  950. def nf_regnet_b5(pretrained: bool = False, **kwargs: Any) -> NormFreeNet:
  951. """Normalization-Free RegNet-B5.
  952. """
  953. return _create_normfreenet('nf_regnet_b5', pretrained=pretrained, **kwargs)
  954. @register_model
  955. def nf_resnet26(pretrained: bool = False, **kwargs: Any) -> NormFreeNet:
  956. """Normalization-Free ResNet-26.
  957. """
  958. return _create_normfreenet('nf_resnet26', pretrained=pretrained, **kwargs)
  959. @register_model
  960. def nf_resnet50(pretrained: bool = False, **kwargs: Any) -> NormFreeNet:
  961. """Normalization-Free ResNet-50.
  962. """
  963. return _create_normfreenet('nf_resnet50', pretrained=pretrained, **kwargs)
  964. @register_model
  965. def nf_resnet101(pretrained: bool = False, **kwargs: Any) -> NormFreeNet:
  966. """Normalization-Free ResNet-101.
  967. """
  968. return _create_normfreenet('nf_resnet101', pretrained=pretrained, **kwargs)
  969. @register_model
  970. def nf_seresnet26(pretrained: bool = False, **kwargs: Any) -> NormFreeNet:
  971. """Normalization-Free SE-ResNet26."""
  972. return _create_normfreenet('nf_seresnet26', pretrained=pretrained, **kwargs)
  973. @register_model
  974. def nf_seresnet50(pretrained: bool = False, **kwargs: Any) -> NormFreeNet:
  975. """Normalization-Free SE-ResNet50."""
  976. return _create_normfreenet('nf_seresnet50', pretrained=pretrained, **kwargs)
  977. @register_model
  978. def nf_seresnet101(pretrained: bool = False, **kwargs: Any) -> NormFreeNet:
  979. """Normalization-Free SE-ResNet101."""
  980. return _create_normfreenet('nf_seresnet101', pretrained=pretrained, **kwargs)
  981. @register_model
  982. def nf_ecaresnet26(pretrained: bool = False, **kwargs: Any) -> NormFreeNet:
  983. """Normalization-Free ECA-ResNet26."""
  984. return _create_normfreenet('nf_ecaresnet26', pretrained=pretrained, **kwargs)
  985. @register_model
  986. def nf_ecaresnet50(pretrained: bool = False, **kwargs: Any) -> NormFreeNet:
  987. """Normalization-Free ECA-ResNet50."""
  988. return _create_normfreenet('nf_ecaresnet50', pretrained=pretrained, **kwargs)
  989. @register_model
  990. def nf_ecaresnet101(pretrained: bool = False, **kwargs: Any) -> NormFreeNet:
  991. """Normalization-Free ECA-ResNet101."""
  992. return _create_normfreenet('nf_ecaresnet101', pretrained=pretrained, **kwargs)
  993. @register_model
  994. def test_nfnet(pretrained: bool = False, **kwargs: Any) -> NormFreeNet:
  995. """Test NFNet model for experimentation."""
  996. return _create_normfreenet('test_nfnet', pretrained=pretrained, **kwargs)