regnet.py 55 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489
  1. """RegNet X, Y, Z, and more
  2. Paper: `Designing Network Design Spaces` - https://arxiv.org/abs/2003.13678
  3. Original Impl: https://github.com/facebookresearch/pycls/blob/master/pycls/models/regnet.py
  4. Paper: `Fast and Accurate Model Scaling` - https://arxiv.org/abs/2103.06877
  5. Original Impl: None
  6. Based on original PyTorch impl linked above, but re-wrote to use my own blocks (adapted from ResNet here)
  7. and cleaned up with more descriptive variable names.
  8. Weights from original pycls impl have been modified:
  9. * first layer from BGR -> RGB as most PyTorch models are
  10. * removed training specific dict entries from checkpoints and keep model state_dict only
  11. * remap names to match the ones here
  12. Supports weight loading from torchvision and classy-vision (incl VISSL SEER)
  13. A number of custom timm model definitions additions including:
  14. * stochastic depth, gradient checkpointing, layer-decay, configurable dilation
  15. * a pre-activation 'V' variant
  16. * only known RegNet-Z model definitions with pretrained weights
  17. Hacked together by / Copyright 2020 Ross Wightman
  18. """
  19. import math
  20. from dataclasses import dataclass, replace
  21. from functools import partial
  22. from typing import Any, Callable, Dict, List, Optional, Union, Tuple, Type
  23. import torch
  24. import torch.nn as nn
  25. from timm.data import IMAGENET_DEFAULT_MEAN, IMAGENET_DEFAULT_STD
  26. from timm.layers import ClassifierHead, AvgPool2dSame, ConvNormAct, SEModule, DropPath, GroupNormAct, calculate_drop_path_rates
  27. from timm.layers import get_act_layer, get_norm_act_layer, create_conv2d, make_divisible
  28. from ._builder import build_model_with_cfg
  29. from ._features import feature_take_indices
  30. from ._manipulate import checkpoint_seq, named_apply
  31. from ._registry import generate_default_cfgs, register_model, register_model_deprecations
  32. __all__ = ['RegNet', 'RegNetCfg'] # model_registry will add each entrypoint fn to this
  33. @dataclass
  34. class RegNetCfg:
  35. """RegNet architecture configuration."""
  36. depth: int = 21
  37. w0: int = 80
  38. wa: float = 42.63
  39. wm: float = 2.66
  40. group_size: int = 24
  41. bottle_ratio: float = 1.
  42. se_ratio: float = 0.
  43. group_min_ratio: float = 0.
  44. stem_width: int = 32
  45. downsample: Optional[str] = 'conv1x1'
  46. linear_out: bool = False
  47. preact: bool = False
  48. num_features: int = 0
  49. act_layer: Union[str, Callable] = 'relu'
  50. norm_layer: Union[str, Callable] = 'batchnorm'
  51. def quantize_float(f: float, q: int) -> int:
  52. """Converts a float to the closest non-zero int divisible by q.
  53. Args:
  54. f: Input float value.
  55. q: Quantization divisor.
  56. Returns:
  57. Quantized integer value.
  58. """
  59. return int(round(f / q) * q)
  60. def adjust_widths_groups_comp(
  61. widths: List[int],
  62. bottle_ratios: List[float],
  63. groups: List[int],
  64. min_ratio: float = 0.
  65. ) -> Tuple[List[int], List[int]]:
  66. """Adjusts the compatibility of widths and groups.
  67. Args:
  68. widths: List of channel widths.
  69. bottle_ratios: List of bottleneck ratios.
  70. groups: List of group sizes.
  71. min_ratio: Minimum ratio for divisibility.
  72. Returns:
  73. Tuple of adjusted widths and groups.
  74. """
  75. bottleneck_widths = [int(w * b) for w, b in zip(widths, bottle_ratios)]
  76. groups = [min(g, w_bot) for g, w_bot in zip(groups, bottleneck_widths)]
  77. if min_ratio:
  78. # torchvision uses a different rounding scheme for ensuring bottleneck widths divisible by group widths
  79. bottleneck_widths = [make_divisible(w_bot, g, min_ratio) for w_bot, g in zip(bottleneck_widths, groups)]
  80. else:
  81. bottleneck_widths = [quantize_float(w_bot, g) for w_bot, g in zip(bottleneck_widths, groups)]
  82. widths = [int(w_bot / b) for w_bot, b in zip(bottleneck_widths, bottle_ratios)]
  83. return widths, groups
  84. def generate_regnet(
  85. width_slope: float,
  86. width_initial: int,
  87. width_mult: float,
  88. depth: int,
  89. group_size: int,
  90. quant: int = 8
  91. ) -> Tuple[List[int], int, List[int]]:
  92. """Generates per block widths from RegNet parameters.
  93. Args:
  94. width_slope: Slope parameter for width progression.
  95. width_initial: Initial width.
  96. width_mult: Width multiplier.
  97. depth: Network depth.
  98. group_size: Group convolution size.
  99. quant: Quantization factor.
  100. Returns:
  101. Tuple of (widths, num_stages, groups).
  102. """
  103. assert width_slope >= 0 and width_initial > 0 and width_mult > 1 and width_initial % quant == 0
  104. # TODO dWr scaling?
  105. # depth = int(depth * (scale ** 0.1))
  106. # width_scale = scale ** 0.4 # dWr scale, exp 0.8 / 2, applied to both group and layer widths
  107. widths_cont = torch.arange(depth, dtype=torch.float32) * width_slope + width_initial
  108. width_exps = torch.round(torch.log(widths_cont / width_initial) / math.log(width_mult))
  109. widths = torch.round((width_initial * torch.pow(width_mult, width_exps)) / quant) * quant
  110. num_stages, max_stage = len(torch.unique(widths)), int(width_exps.max().item()) + 1
  111. groups = torch.tensor([group_size for _ in range(num_stages)], dtype=torch.int32)
  112. return widths.int().tolist(), num_stages, groups.tolist()
  113. def downsample_conv(
  114. in_chs: int,
  115. out_chs: int,
  116. kernel_size: int = 1,
  117. stride: int = 1,
  118. dilation: int = 1,
  119. norm_layer: Optional[Type[nn.Module]] = None,
  120. preact: bool = False,
  121. device=None,
  122. dtype=None,
  123. ) -> nn.Module:
  124. """Create convolutional downsampling module.
  125. Args:
  126. in_chs: Input channels.
  127. out_chs: Output channels.
  128. kernel_size: Convolution kernel size.
  129. stride: Convolution stride.
  130. dilation: Convolution dilation.
  131. norm_layer: Normalization layer.
  132. preact: Use pre-activation.
  133. Returns:
  134. Downsampling module.
  135. """
  136. dd = {'device': device, 'dtype': dtype}
  137. norm_layer = norm_layer or nn.BatchNorm2d
  138. kernel_size = 1 if stride == 1 and dilation == 1 else kernel_size
  139. dilation = dilation if kernel_size > 1 else 1
  140. if preact:
  141. return create_conv2d(
  142. in_chs,
  143. out_chs,
  144. kernel_size,
  145. stride=stride,
  146. dilation=dilation,
  147. **dd,
  148. )
  149. else:
  150. return ConvNormAct(
  151. in_chs,
  152. out_chs,
  153. kernel_size,
  154. stride=stride,
  155. dilation=dilation,
  156. norm_layer=norm_layer,
  157. apply_act=False,
  158. **dd,
  159. )
  160. def downsample_avg(
  161. in_chs: int,
  162. out_chs: int,
  163. kernel_size: int = 1,
  164. stride: int = 1,
  165. dilation: int = 1,
  166. norm_layer: Optional[Type[nn.Module]] = None,
  167. preact: bool = False,
  168. device=None,
  169. dtype=None,
  170. ) -> nn.Sequential:
  171. """Create average pool downsampling module.
  172. AvgPool Downsampling as in 'D' ResNet variants. This is not in RegNet space but I might experiment.
  173. Args:
  174. in_chs: Input channels.
  175. out_chs: Output channels.
  176. kernel_size: Convolution kernel size.
  177. stride: Convolution stride.
  178. dilation: Convolution dilation.
  179. norm_layer: Normalization layer.
  180. preact: Use pre-activation.
  181. Returns:
  182. Sequential downsampling module.
  183. """
  184. dd = {'device': device, 'dtype': dtype}
  185. norm_layer = norm_layer or nn.BatchNorm2d
  186. avg_stride = stride if dilation == 1 else 1
  187. pool = nn.Identity()
  188. if stride > 1 or dilation > 1:
  189. avg_pool_fn = AvgPool2dSame if avg_stride == 1 and dilation > 1 else nn.AvgPool2d
  190. pool = avg_pool_fn(2, avg_stride, ceil_mode=True, count_include_pad=False)
  191. if preact:
  192. conv = create_conv2d(in_chs, out_chs, 1, stride=1, **dd)
  193. else:
  194. conv = ConvNormAct(in_chs, out_chs, 1, stride=1, norm_layer=norm_layer, apply_act=False, **dd)
  195. return nn.Sequential(*[pool, conv])
  196. def create_shortcut(
  197. downsample_type: Optional[str],
  198. in_chs: int,
  199. out_chs: int,
  200. kernel_size: int,
  201. stride: int,
  202. dilation: Tuple[int, int] = (1, 1),
  203. norm_layer: Optional[Type[nn.Module]] = None,
  204. preact: bool = False,
  205. device=None,
  206. dtype=None,
  207. ) -> Optional[nn.Module]:
  208. """Create shortcut connection for residual blocks.
  209. Args:
  210. downsample_type: Type of downsampling ('avg', 'conv1x1', or None).
  211. in_chs: Input channels.
  212. out_chs: Output channels.
  213. kernel_size: Kernel size for conv downsampling.
  214. stride: Stride for downsampling.
  215. dilation: Dilation rates.
  216. norm_layer: Normalization layer.
  217. preact: Use pre-activation.
  218. Returns:
  219. Shortcut module or None.
  220. """
  221. dd = {'device': device, 'dtype': dtype}
  222. assert downsample_type in ('avg', 'conv1x1', '', None)
  223. if in_chs != out_chs or stride != 1 or dilation[0] != dilation[1]:
  224. dargs = dict(stride=stride, dilation=dilation[0], norm_layer=norm_layer, preact=preact, **dd)
  225. if not downsample_type:
  226. return None # no shortcut, no downsample
  227. elif downsample_type == 'avg':
  228. return downsample_avg(in_chs, out_chs, **dargs)
  229. else:
  230. return downsample_conv(in_chs, out_chs, kernel_size=kernel_size, **dargs)
  231. else:
  232. return nn.Identity() # identity shortcut (no downsample)
  233. class Bottleneck(nn.Module):
  234. """RegNet Bottleneck block.
  235. This is almost exactly the same as a ResNet Bottleneck. The main difference is the SE block is moved from
  236. after conv3 to after conv2. Otherwise, it's just redefining the arguments for groups/bottleneck channels.
  237. """
  238. def __init__(
  239. self,
  240. in_chs: int,
  241. out_chs: int,
  242. stride: int = 1,
  243. dilation: Tuple[int, int] = (1, 1),
  244. bottle_ratio: float = 1,
  245. group_size: int = 1,
  246. se_ratio: float = 0.25,
  247. downsample: str = 'conv1x1',
  248. linear_out: bool = False,
  249. act_layer: Type[nn.Module] = nn.ReLU,
  250. norm_layer: Type[nn.Module] = nn.BatchNorm2d,
  251. drop_block: Optional[Type[nn.Module]] = None,
  252. drop_path_rate: float = 0.,
  253. device=None,
  254. dtype=None,
  255. ):
  256. """Initialize RegNet Bottleneck block.
  257. Args:
  258. in_chs: Input channels.
  259. out_chs: Output channels.
  260. stride: Convolution stride.
  261. dilation: Dilation rates for conv2 and shortcut.
  262. bottle_ratio: Bottleneck ratio (reduction factor).
  263. group_size: Group convolution size.
  264. se_ratio: Squeeze-and-excitation ratio.
  265. downsample: Shortcut downsampling type.
  266. linear_out: Use linear activation for output.
  267. act_layer: Activation layer.
  268. norm_layer: Normalization layer.
  269. drop_block: Drop block layer.
  270. drop_path_rate: Stochastic depth drop rate.
  271. """
  272. dd = {'device': device, 'dtype': dtype}
  273. super().__init__()
  274. act_layer = get_act_layer(act_layer)
  275. bottleneck_chs = int(round(out_chs * bottle_ratio))
  276. groups = bottleneck_chs // group_size
  277. cargs = dict(act_layer=act_layer, norm_layer=norm_layer)
  278. self.conv1 = ConvNormAct(in_chs, bottleneck_chs, kernel_size=1, **cargs, **dd)
  279. self.conv2 = ConvNormAct(
  280. bottleneck_chs,
  281. bottleneck_chs,
  282. kernel_size=3,
  283. stride=stride,
  284. dilation=dilation[0],
  285. groups=groups,
  286. drop_layer=drop_block,
  287. **cargs,
  288. **dd,
  289. )
  290. if se_ratio:
  291. se_channels = int(round(in_chs * se_ratio))
  292. self.se = SEModule(bottleneck_chs, rd_channels=se_channels, act_layer=act_layer, **dd)
  293. else:
  294. self.se = nn.Identity()
  295. self.conv3 = ConvNormAct(bottleneck_chs, out_chs, kernel_size=1, apply_act=False, **cargs, **dd)
  296. self.act3 = nn.Identity() if linear_out else act_layer()
  297. self.downsample = create_shortcut(
  298. downsample,
  299. in_chs,
  300. out_chs,
  301. kernel_size=1,
  302. stride=stride,
  303. dilation=dilation,
  304. norm_layer=norm_layer,
  305. **dd,
  306. )
  307. self.drop_path = DropPath(drop_path_rate) if drop_path_rate > 0 else nn.Identity()
  308. def zero_init_last(self) -> None:
  309. """Zero-initialize the last batch norm in the block."""
  310. nn.init.zeros_(self.conv3.bn.weight)
  311. def forward(self, x: torch.Tensor) -> torch.Tensor:
  312. """Forward pass.
  313. Args:
  314. x: Input tensor.
  315. Returns:
  316. Output tensor.
  317. """
  318. shortcut = x
  319. x = self.conv1(x)
  320. x = self.conv2(x)
  321. x = self.se(x)
  322. x = self.conv3(x)
  323. if self.downsample is not None:
  324. # NOTE stuck with downsample as the attr name due to weight compatibility
  325. # now represents the shortcut, no shortcut if None, and non-downsample shortcut == nn.Identity()
  326. x = self.drop_path(x) + self.downsample(shortcut)
  327. x = self.act3(x)
  328. return x
  329. class PreBottleneck(nn.Module):
  330. """Pre-activation RegNet Bottleneck block.
  331. Similar to Bottleneck but with pre-activation normalization.
  332. """
  333. def __init__(
  334. self,
  335. in_chs: int,
  336. out_chs: int,
  337. stride: int = 1,
  338. dilation: Tuple[int, int] = (1, 1),
  339. bottle_ratio: float = 1,
  340. group_size: int = 1,
  341. se_ratio: float = 0.25,
  342. downsample: str = 'conv1x1',
  343. linear_out: bool = False,
  344. act_layer: Type[nn.Module] = nn.ReLU,
  345. norm_layer: Type[nn.Module] = nn.BatchNorm2d,
  346. drop_block: Optional[Type[nn.Module]] = None,
  347. drop_path_rate: float = 0.,
  348. device=None,
  349. dtype=None,
  350. ):
  351. """Initialize pre-activation RegNet Bottleneck block.
  352. Args:
  353. in_chs: Input channels.
  354. out_chs: Output channels.
  355. stride: Convolution stride.
  356. dilation: Dilation rates for conv2 and shortcut.
  357. bottle_ratio: Bottleneck ratio (reduction factor).
  358. group_size: Group convolution size.
  359. se_ratio: Squeeze-and-excitation ratio.
  360. downsample: Shortcut downsampling type.
  361. linear_out: Use linear activation for output.
  362. act_layer: Activation layer.
  363. norm_layer: Normalization layer.
  364. drop_block: Drop block layer.
  365. drop_path_rate: Stochastic depth drop rate.
  366. """
  367. dd = {'device': device, 'dtype': dtype}
  368. super().__init__()
  369. norm_act_layer = get_norm_act_layer(norm_layer, act_layer)
  370. bottleneck_chs = int(round(out_chs * bottle_ratio))
  371. groups = bottleneck_chs // group_size
  372. self.norm1 = norm_act_layer(in_chs, **dd)
  373. self.conv1 = create_conv2d(in_chs, bottleneck_chs, kernel_size=1, **dd)
  374. self.norm2 = norm_act_layer(bottleneck_chs, **dd)
  375. self.conv2 = create_conv2d(
  376. bottleneck_chs,
  377. bottleneck_chs,
  378. kernel_size=3,
  379. stride=stride,
  380. dilation=dilation[0],
  381. groups=groups,
  382. **dd,
  383. )
  384. if se_ratio:
  385. se_channels = int(round(in_chs * se_ratio))
  386. self.se = SEModule(bottleneck_chs, rd_channels=se_channels, act_layer=act_layer, **dd)
  387. else:
  388. self.se = nn.Identity()
  389. self.norm3 = norm_act_layer(bottleneck_chs, **dd)
  390. self.conv3 = create_conv2d(bottleneck_chs, out_chs, kernel_size=1, **dd)
  391. self.downsample = create_shortcut(
  392. downsample,
  393. in_chs,
  394. out_chs,
  395. kernel_size=1,
  396. stride=stride,
  397. dilation=dilation,
  398. preact=True,
  399. **dd,
  400. )
  401. self.drop_path = DropPath(drop_path_rate) if drop_path_rate > 0 else nn.Identity()
  402. def zero_init_last(self) -> None:
  403. """Zero-initialize the last batch norm (no-op for pre-activation)."""
  404. pass
  405. def forward(self, x: torch.Tensor) -> torch.Tensor:
  406. """Forward pass.
  407. Args:
  408. x: Input tensor.
  409. Returns:
  410. Output tensor.
  411. """
  412. x = self.norm1(x)
  413. shortcut = x
  414. x = self.conv1(x)
  415. x = self.norm2(x)
  416. x = self.conv2(x)
  417. x = self.se(x)
  418. x = self.norm3(x)
  419. x = self.conv3(x)
  420. if self.downsample is not None:
  421. # NOTE stuck with downsample as the attr name due to weight compatibility
  422. # now represents the shortcut, no shortcut if None, and non-downsample shortcut == nn.Identity()
  423. x = self.drop_path(x) + self.downsample(shortcut)
  424. return x
  425. class RegStage(nn.Module):
  426. """RegNet stage (sequence of blocks with the same output shape).
  427. A stage consists of multiple bottleneck blocks with the same output dimensions.
  428. """
  429. def __init__(
  430. self,
  431. depth: int,
  432. in_chs: int,
  433. out_chs: int,
  434. stride: int,
  435. dilation: int,
  436. drop_path_rates: Optional[List[float]] = None,
  437. block_fn: Type[nn.Module] = Bottleneck,
  438. **block_kwargs,
  439. ):
  440. """Initialize RegNet stage.
  441. Args:
  442. depth: Number of blocks in stage.
  443. in_chs: Input channels.
  444. out_chs: Output channels.
  445. stride: Stride for first block.
  446. dilation: Dilation rate.
  447. drop_path_rates: Drop path rates for each block.
  448. block_fn: Block class to use.
  449. **block_kwargs: Additional block arguments.
  450. """
  451. super().__init__()
  452. self.grad_checkpointing = False
  453. first_dilation = 1 if dilation in (1, 2) else 2
  454. for i in range(depth):
  455. block_stride = stride if i == 0 else 1
  456. block_in_chs = in_chs if i == 0 else out_chs
  457. block_dilation = (first_dilation, dilation)
  458. dpr = drop_path_rates[i] if drop_path_rates is not None else 0.
  459. name = "b{}".format(i + 1)
  460. self.add_module(
  461. name,
  462. block_fn(
  463. block_in_chs,
  464. out_chs,
  465. stride=block_stride,
  466. dilation=block_dilation,
  467. drop_path_rate=dpr,
  468. **block_kwargs,
  469. )
  470. )
  471. first_dilation = dilation
  472. def forward(self, x: torch.Tensor) -> torch.Tensor:
  473. """Forward pass through all blocks in the stage.
  474. Args:
  475. x: Input tensor.
  476. Returns:
  477. Output tensor.
  478. """
  479. if self.grad_checkpointing and not torch.jit.is_scripting():
  480. x = checkpoint_seq(self.children(), x)
  481. else:
  482. for block in self.children():
  483. x = block(x)
  484. return x
  485. class RegNet(nn.Module):
  486. """RegNet-X, Y, and Z Models.
  487. Paper: https://arxiv.org/abs/2003.13678
  488. Original Impl: https://github.com/facebookresearch/pycls/blob/master/pycls/models/regnet.py
  489. """
  490. def __init__(
  491. self,
  492. cfg: RegNetCfg,
  493. in_chans: int = 3,
  494. num_classes: int = 1000,
  495. output_stride: int = 32,
  496. global_pool: str = 'avg',
  497. drop_rate: float = 0.,
  498. drop_path_rate: float = 0.,
  499. zero_init_last: bool = True,
  500. device=None,
  501. dtype=None,
  502. **kwargs,
  503. ):
  504. """Initialize RegNet model.
  505. Args:
  506. cfg: Model architecture configuration.
  507. in_chans: Number of input channels.
  508. num_classes: Number of classifier classes.
  509. output_stride: Output stride of network, one of (8, 16, 32).
  510. global_pool: Global pooling type.
  511. drop_rate: Dropout rate.
  512. drop_path_rate: Stochastic depth drop-path rate.
  513. zero_init_last: Zero-init last weight of residual path.
  514. kwargs: Extra kwargs overlayed onto cfg.
  515. """
  516. super().__init__()
  517. dd = {'device': device, 'dtype': dtype}
  518. self.num_classes = num_classes
  519. self.drop_rate = drop_rate
  520. assert output_stride in (8, 16, 32)
  521. cfg = replace(cfg, **kwargs) # update cfg with extra passed kwargs
  522. # Construct the stem
  523. stem_width = cfg.stem_width
  524. na_args = dict(act_layer=cfg.act_layer, norm_layer=cfg.norm_layer)
  525. if cfg.preact:
  526. self.stem = create_conv2d(in_chans, stem_width, 3, stride=2, **dd)
  527. else:
  528. self.stem = ConvNormAct(in_chans, stem_width, 3, stride=2, **na_args, **dd)
  529. self.feature_info = [dict(num_chs=stem_width, reduction=2, module='stem')]
  530. # Construct the stages
  531. prev_width = stem_width
  532. curr_stride = 2
  533. per_stage_args, common_args = self._get_stage_args(
  534. cfg,
  535. output_stride=output_stride,
  536. drop_path_rate=drop_path_rate,
  537. )
  538. assert len(per_stage_args) == 4
  539. block_fn = PreBottleneck if cfg.preact else Bottleneck
  540. for i, stage_args in enumerate(per_stage_args):
  541. stage_name = "s{}".format(i + 1)
  542. self.add_module(
  543. stage_name,
  544. RegStage(
  545. in_chs=prev_width,
  546. block_fn=block_fn,
  547. **stage_args,
  548. **common_args,
  549. **dd,
  550. )
  551. )
  552. prev_width = stage_args['out_chs']
  553. curr_stride *= stage_args['stride']
  554. self.feature_info += [dict(num_chs=prev_width, reduction=curr_stride, module=stage_name)]
  555. # Construct the head
  556. if cfg.num_features:
  557. self.final_conv = ConvNormAct(prev_width, cfg.num_features, kernel_size=1, **na_args, **dd)
  558. self.num_features = cfg.num_features
  559. else:
  560. final_act = cfg.linear_out or cfg.preact
  561. self.final_conv = get_act_layer(cfg.act_layer)() if final_act else nn.Identity()
  562. self.num_features = prev_width
  563. self.head_hidden_size = self.num_features
  564. self.head = ClassifierHead(
  565. in_features=self.num_features,
  566. num_classes=num_classes,
  567. pool_type=global_pool,
  568. drop_rate=drop_rate,
  569. **dd,
  570. )
  571. named_apply(partial(_init_weights, zero_init_last=zero_init_last), self)
  572. def _get_stage_args(
  573. self,
  574. cfg: RegNetCfg,
  575. default_stride: int = 2,
  576. output_stride: int = 32,
  577. drop_path_rate: float = 0.
  578. ) -> Tuple[List[Dict[str, Any]], Dict[str, Any]]:
  579. """Generate stage arguments from configuration.
  580. Args:`
  581. cfg: RegNet configuration.
  582. default_stride: Default stride for stages.
  583. output_stride: Target output stride.
  584. drop_path_rate: Stochastic depth rate.
  585. Returns:
  586. Tuple of (per_stage_args, common_args).
  587. """
  588. # Generate RegNet ws per block
  589. widths, num_stages, stage_gs = generate_regnet(cfg.wa, cfg.w0, cfg.wm, cfg.depth, cfg.group_size)
  590. # Convert to per stage format
  591. stage_widths, stage_depths = torch.unique(torch.tensor(widths), return_counts=True)
  592. stage_widths, stage_depths = stage_widths.tolist(), stage_depths.tolist()
  593. stage_br = [cfg.bottle_ratio for _ in range(num_stages)]
  594. stage_strides = []
  595. stage_dilations = []
  596. net_stride = 2
  597. dilation = 1
  598. for _ in range(num_stages):
  599. if net_stride >= output_stride:
  600. dilation *= default_stride
  601. stride = 1
  602. else:
  603. stride = default_stride
  604. net_stride *= stride
  605. stage_strides.append(stride)
  606. stage_dilations.append(dilation)
  607. stage_dpr = calculate_drop_path_rates(drop_path_rate, stage_depths, stagewise=True)
  608. # Adjust the compatibility of ws and gws
  609. stage_widths, stage_gs = adjust_widths_groups_comp(
  610. stage_widths, stage_br, stage_gs, min_ratio=cfg.group_min_ratio)
  611. arg_names = ['out_chs', 'stride', 'dilation', 'depth', 'bottle_ratio', 'group_size', 'drop_path_rates']
  612. per_stage_args = [
  613. dict(zip(arg_names, params)) for params in
  614. zip(stage_widths, stage_strides, stage_dilations, stage_depths, stage_br, stage_gs, stage_dpr)
  615. ]
  616. common_args = dict(
  617. downsample=cfg.downsample,
  618. se_ratio=cfg.se_ratio,
  619. linear_out=cfg.linear_out,
  620. act_layer=cfg.act_layer,
  621. norm_layer=cfg.norm_layer,
  622. )
  623. return per_stage_args, common_args
  624. @torch.jit.ignore
  625. def group_matcher(self, coarse: bool = False) -> Dict[str, Any]:
  626. """Group parameters for optimization."""
  627. return dict(
  628. stem=r'^stem',
  629. blocks=r'^s(\d+)' if coarse else r'^s(\d+)\.b(\d+)',
  630. )
  631. @torch.jit.ignore
  632. def set_grad_checkpointing(self, enable: bool = True) -> None:
  633. """Enable or disable gradient checkpointing."""
  634. for s in list(self.children())[1:-1]:
  635. s.grad_checkpointing = enable
  636. @torch.jit.ignore
  637. def get_classifier(self) -> nn.Module:
  638. """Get the classifier head."""
  639. return self.head.fc
  640. def reset_classifier(self, num_classes: int, global_pool: Optional[str] = None) -> None:
  641. """Reset the classifier head.
  642. Args:
  643. num_classes: Number of classes for new classifier.
  644. global_pool: Global pooling type.
  645. """
  646. self.num_classes = num_classes
  647. self.head.reset(num_classes, pool_type=global_pool)
  648. def forward_intermediates(
  649. self,
  650. x: torch.Tensor,
  651. indices: Optional[Union[int, List[int]]] = None,
  652. norm: bool = False,
  653. stop_early: bool = False,
  654. output_fmt: str = 'NCHW',
  655. intermediates_only: bool = False,
  656. ) -> Union[List[torch.Tensor], Tuple[torch.Tensor, List[torch.Tensor]]]:
  657. """ Forward features that returns intermediates.
  658. Args:
  659. x: Input image tensor
  660. indices: Take last n blocks if int, all if None, select matching indices if sequence
  661. norm: Apply norm layer to compatible intermediates
  662. stop_early: Stop iterating over blocks when last desired intermediate hit
  663. output_fmt: Shape of intermediate feature outputs
  664. intermediates_only: Only return intermediate features
  665. Returns:
  666. """
  667. assert output_fmt in ('NCHW',), 'Output shape must be NCHW.'
  668. intermediates = []
  669. take_indices, max_index = feature_take_indices(5, indices)
  670. # forward pass
  671. feat_idx = 0
  672. x = self.stem(x)
  673. if feat_idx in take_indices:
  674. intermediates.append(x)
  675. layer_names = ('s1', 's2', 's3', 's4')
  676. if stop_early:
  677. layer_names = layer_names[:max_index]
  678. for n in layer_names:
  679. feat_idx += 1
  680. x = getattr(self, n)(x) # won't work with torchscript, but keeps code reasonable, FML
  681. if feat_idx in take_indices:
  682. intermediates.append(x)
  683. if intermediates_only:
  684. return intermediates
  685. if feat_idx == 4:
  686. x = self.final_conv(x)
  687. return x, intermediates
  688. def prune_intermediate_layers(
  689. self,
  690. indices: Union[int, List[int]] = 1,
  691. prune_norm: bool = False,
  692. prune_head: bool = True,
  693. ) -> List[int]:
  694. """Prune layers not required for specified intermediates.
  695. Args:
  696. indices: Indices of intermediate layers to keep.
  697. prune_norm: Whether to prune normalization layer.
  698. prune_head: Whether to prune the classifier head.
  699. Returns:
  700. List of indices that were kept.
  701. """
  702. take_indices, max_index = feature_take_indices(5, indices)
  703. layer_names = ('s1', 's2', 's3', 's4')
  704. layer_names = layer_names[max_index:]
  705. for n in layer_names:
  706. setattr(self, n, nn.Identity())
  707. if max_index < 4:
  708. self.final_conv = nn.Identity()
  709. if prune_head:
  710. self.reset_classifier(0, '')
  711. return take_indices
  712. def forward_features(self, x: torch.Tensor) -> torch.Tensor:
  713. """Forward pass through feature extraction layers.
  714. Args:
  715. x: Input tensor.
  716. Returns:
  717. Feature tensor.
  718. """
  719. x = self.stem(x)
  720. x = self.s1(x)
  721. x = self.s2(x)
  722. x = self.s3(x)
  723. x = self.s4(x)
  724. x = self.final_conv(x)
  725. return x
  726. def forward_head(self, x: torch.Tensor, pre_logits: bool = False) -> torch.Tensor:
  727. """Forward pass through classifier head.
  728. Args:
  729. x: Input features.
  730. pre_logits: Return features before final linear layer.
  731. Returns:
  732. Classification logits or features.
  733. """
  734. return self.head(x, pre_logits=pre_logits) if pre_logits else self.head(x)
  735. def forward(self, x: torch.Tensor) -> torch.Tensor:
  736. """Forward pass.
  737. Args:
  738. x: Input tensor.
  739. Returns:
  740. Output logits.
  741. """
  742. x = self.forward_features(x)
  743. x = self.forward_head(x)
  744. return x
  745. def _init_weights(module: nn.Module, name: str = '', zero_init_last: bool = False) -> None:
  746. """Initialize module weights.
  747. Args:
  748. module: PyTorch module to initialize.
  749. name: Module name.
  750. zero_init_last: Zero-initialize last layer weights.
  751. """
  752. if isinstance(module, nn.Conv2d):
  753. fan_out = module.kernel_size[0] * module.kernel_size[1] * module.out_channels
  754. fan_out //= module.groups
  755. module.weight.data.normal_(0, math.sqrt(2.0 / fan_out))
  756. if module.bias is not None:
  757. module.bias.data.zero_()
  758. elif isinstance(module, nn.Linear):
  759. nn.init.normal_(module.weight, mean=0.0, std=0.01)
  760. if module.bias is not None:
  761. nn.init.zeros_(module.bias)
  762. elif zero_init_last and hasattr(module, 'zero_init_last'):
  763. module.zero_init_last()
  764. def _filter_fn(state_dict: Dict[str, Any]) -> Dict[str, Any]:
  765. """Filter and remap state dict keys for compatibility.
  766. Args:
  767. state_dict: Raw state dictionary.
  768. Returns:
  769. Filtered state dictionary.
  770. """
  771. state_dict = state_dict.get('model', state_dict)
  772. replaces = [
  773. ('f.a.0', 'conv1.conv'),
  774. ('f.a.1', 'conv1.bn'),
  775. ('f.b.0', 'conv2.conv'),
  776. ('f.b.1', 'conv2.bn'),
  777. ('f.final_bn', 'conv3.bn'),
  778. ('f.se.excitation.0', 'se.fc1'),
  779. ('f.se.excitation.2', 'se.fc2'),
  780. ('f.se', 'se'),
  781. ('f.c.0', 'conv3.conv'),
  782. ('f.c.1', 'conv3.bn'),
  783. ('f.c', 'conv3.conv'),
  784. ('proj.0', 'downsample.conv'),
  785. ('proj.1', 'downsample.bn'),
  786. ('proj', 'downsample.conv'),
  787. ]
  788. if 'classy_state_dict' in state_dict:
  789. # classy-vision & vissl (SEER) weights
  790. import re
  791. state_dict = state_dict['classy_state_dict']['base_model']['model']
  792. out = {}
  793. for k, v in state_dict['trunk'].items():
  794. k = k.replace('_feature_blocks.conv1.stem.0', 'stem.conv')
  795. k = k.replace('_feature_blocks.conv1.stem.1', 'stem.bn')
  796. k = re.sub(
  797. r'^_feature_blocks.res\d.block(\d)-(\d+)',
  798. lambda x: f's{int(x.group(1))}.b{int(x.group(2)) + 1}', k)
  799. k = re.sub(r's(\d)\.b(\d+)\.bn', r's\1.b\2.downsample.bn', k)
  800. for s, r in replaces:
  801. k = k.replace(s, r)
  802. out[k] = v
  803. for k, v in state_dict['heads'].items():
  804. if 'projection_head' in k or 'prototypes' in k:
  805. continue
  806. k = k.replace('0.clf.0', 'head.fc')
  807. out[k] = v
  808. return out
  809. if 'stem.0.weight' in state_dict:
  810. # torchvision weights
  811. import re
  812. out = {}
  813. for k, v in state_dict.items():
  814. k = k.replace('stem.0', 'stem.conv')
  815. k = k.replace('stem.1', 'stem.bn')
  816. k = re.sub(
  817. r'trunk_output.block(\d)\.block(\d+)\-(\d+)',
  818. lambda x: f's{int(x.group(1))}.b{int(x.group(3)) + 1}', k)
  819. for s, r in replaces:
  820. k = k.replace(s, r)
  821. k = k.replace('fc.', 'head.fc.')
  822. out[k] = v
  823. return out
  824. return state_dict
  825. # Model FLOPS = three trailing digits * 10^8
  826. model_cfgs = dict(
  827. # RegNet-X
  828. regnetx_002=RegNetCfg(w0=24, wa=36.44, wm=2.49, group_size=8, depth=13),
  829. regnetx_004=RegNetCfg(w0=24, wa=24.48, wm=2.54, group_size=16, depth=22),
  830. regnetx_004_tv=RegNetCfg(w0=24, wa=24.48, wm=2.54, group_size=16, depth=22, group_min_ratio=0.9),
  831. regnetx_006=RegNetCfg(w0=48, wa=36.97, wm=2.24, group_size=24, depth=16),
  832. regnetx_008=RegNetCfg(w0=56, wa=35.73, wm=2.28, group_size=16, depth=16),
  833. regnetx_016=RegNetCfg(w0=80, wa=34.01, wm=2.25, group_size=24, depth=18),
  834. regnetx_032=RegNetCfg(w0=88, wa=26.31, wm=2.25, group_size=48, depth=25),
  835. regnetx_040=RegNetCfg(w0=96, wa=38.65, wm=2.43, group_size=40, depth=23),
  836. regnetx_064=RegNetCfg(w0=184, wa=60.83, wm=2.07, group_size=56, depth=17),
  837. regnetx_080=RegNetCfg(w0=80, wa=49.56, wm=2.88, group_size=120, depth=23),
  838. regnetx_120=RegNetCfg(w0=168, wa=73.36, wm=2.37, group_size=112, depth=19),
  839. regnetx_160=RegNetCfg(w0=216, wa=55.59, wm=2.1, group_size=128, depth=22),
  840. regnetx_320=RegNetCfg(w0=320, wa=69.86, wm=2.0, group_size=168, depth=23),
  841. # RegNet-Y
  842. regnety_002=RegNetCfg(w0=24, wa=36.44, wm=2.49, group_size=8, depth=13, se_ratio=0.25),
  843. regnety_004=RegNetCfg(w0=48, wa=27.89, wm=2.09, group_size=8, depth=16, se_ratio=0.25),
  844. regnety_006=RegNetCfg(w0=48, wa=32.54, wm=2.32, group_size=16, depth=15, se_ratio=0.25),
  845. regnety_008=RegNetCfg(w0=56, wa=38.84, wm=2.4, group_size=16, depth=14, se_ratio=0.25),
  846. regnety_008_tv=RegNetCfg(w0=56, wa=38.84, wm=2.4, group_size=16, depth=14, se_ratio=0.25, group_min_ratio=0.9),
  847. regnety_016=RegNetCfg(w0=48, wa=20.71, wm=2.65, group_size=24, depth=27, se_ratio=0.25),
  848. regnety_032=RegNetCfg(w0=80, wa=42.63, wm=2.66, group_size=24, depth=21, se_ratio=0.25),
  849. regnety_040=RegNetCfg(w0=96, wa=31.41, wm=2.24, group_size=64, depth=22, se_ratio=0.25),
  850. regnety_064=RegNetCfg(w0=112, wa=33.22, wm=2.27, group_size=72, depth=25, se_ratio=0.25),
  851. regnety_080=RegNetCfg(w0=192, wa=76.82, wm=2.19, group_size=56, depth=17, se_ratio=0.25),
  852. regnety_080_tv=RegNetCfg(w0=192, wa=76.82, wm=2.19, group_size=56, depth=17, se_ratio=0.25, group_min_ratio=0.9),
  853. regnety_120=RegNetCfg(w0=168, wa=73.36, wm=2.37, group_size=112, depth=19, se_ratio=0.25),
  854. regnety_160=RegNetCfg(w0=200, wa=106.23, wm=2.48, group_size=112, depth=18, se_ratio=0.25),
  855. regnety_320=RegNetCfg(w0=232, wa=115.89, wm=2.53, group_size=232, depth=20, se_ratio=0.25),
  856. regnety_640=RegNetCfg(w0=352, wa=147.48, wm=2.4, group_size=328, depth=20, se_ratio=0.25),
  857. regnety_1280=RegNetCfg(w0=456, wa=160.83, wm=2.52, group_size=264, depth=27, se_ratio=0.25),
  858. regnety_2560=RegNetCfg(w0=640, wa=230.83, wm=2.53, group_size=373, depth=27, se_ratio=0.25),
  859. #regnety_2560=RegNetCfg(w0=640, wa=124.47, wm=2.04, group_size=848, depth=27, se_ratio=0.25),
  860. # Experimental
  861. regnety_040_sgn=RegNetCfg(
  862. w0=96, wa=31.41, wm=2.24, group_size=64, depth=22, se_ratio=0.25,
  863. act_layer='silu', norm_layer=partial(GroupNormAct, group_size=16)),
  864. # regnetv = 'preact regnet y'
  865. regnetv_040=RegNetCfg(
  866. depth=22, w0=96, wa=31.41, wm=2.24, group_size=64, se_ratio=0.25, preact=True, act_layer='silu'),
  867. regnetv_064=RegNetCfg(
  868. depth=25, w0=112, wa=33.22, wm=2.27, group_size=72, se_ratio=0.25, preact=True, act_layer='silu',
  869. downsample='avg'),
  870. # RegNet-Z (unverified)
  871. regnetz_005=RegNetCfg(
  872. depth=21, w0=16, wa=10.7, wm=2.51, group_size=4, bottle_ratio=4.0, se_ratio=0.25,
  873. downsample=None, linear_out=True, num_features=1024, act_layer='silu',
  874. ),
  875. regnetz_040=RegNetCfg(
  876. depth=28, w0=48, wa=14.5, wm=2.226, group_size=8, bottle_ratio=4.0, se_ratio=0.25,
  877. downsample=None, linear_out=True, num_features=0, act_layer='silu',
  878. ),
  879. regnetz_040_h=RegNetCfg(
  880. depth=28, w0=48, wa=14.5, wm=2.226, group_size=8, bottle_ratio=4.0, se_ratio=0.25,
  881. downsample=None, linear_out=True, num_features=1536, act_layer='silu',
  882. ),
  883. )
  884. def _create_regnet(variant: str, pretrained: bool, **kwargs) -> RegNet:
  885. """Create a RegNet model.
  886. Args:
  887. variant: Model variant name.
  888. pretrained: Load pretrained weights.
  889. **kwargs: Additional model arguments.
  890. Returns:
  891. RegNet model instance.
  892. """
  893. return build_model_with_cfg(
  894. RegNet, variant, pretrained,
  895. model_cfg=model_cfgs[variant],
  896. pretrained_filter_fn=_filter_fn,
  897. **kwargs)
  898. def _cfg(url: str = '', **kwargs) -> Dict[str, Any]:
  899. """Create default configuration dictionary.
  900. Args:
  901. url: Model weight URL.
  902. **kwargs: Additional configuration options.
  903. Returns:
  904. Configuration dictionary.
  905. """
  906. return {
  907. 'url': url, 'num_classes': 1000, 'input_size': (3, 224, 224), 'pool_size': (7, 7),
  908. 'test_input_size': (3, 288, 288), 'crop_pct': 0.95, 'test_crop_pct': 1.0,
  909. 'interpolation': 'bicubic', 'mean': IMAGENET_DEFAULT_MEAN, 'std': IMAGENET_DEFAULT_STD,
  910. 'first_conv': 'stem.conv', 'classifier': 'head.fc',
  911. 'license': 'apache-2.0', **kwargs
  912. }
  913. def _cfgpyc(url: str = '', **kwargs) -> Dict[str, Any]:
  914. """Create pycls configuration dictionary.
  915. Args:
  916. url: Model weight URL.
  917. **kwargs: Additional configuration options.
  918. Returns:
  919. Configuration dictionary.
  920. """
  921. return {
  922. 'url': url, 'num_classes': 1000, 'input_size': (3, 224, 224), 'pool_size': (7, 7),
  923. 'crop_pct': 0.875, 'interpolation': 'bicubic',
  924. 'mean': IMAGENET_DEFAULT_MEAN, 'std': IMAGENET_DEFAULT_STD,
  925. 'first_conv': 'stem.conv', 'classifier': 'head.fc',
  926. 'license': 'mit', 'origin_url': 'https://github.com/facebookresearch/pycls', **kwargs
  927. }
  928. def _cfgtv2(url: str = '', **kwargs) -> Dict[str, Any]:
  929. """Create torchvision v2 configuration dictionary.
  930. Args:
  931. url: Model weight URL.
  932. **kwargs: Additional configuration options.
  933. Returns:
  934. Configuration dictionary.
  935. """
  936. return {
  937. 'url': url, 'num_classes': 1000, 'input_size': (3, 224, 224), 'pool_size': (7, 7),
  938. 'crop_pct': 0.965, 'interpolation': 'bicubic',
  939. 'mean': IMAGENET_DEFAULT_MEAN, 'std': IMAGENET_DEFAULT_STD,
  940. 'first_conv': 'stem.conv', 'classifier': 'head.fc',
  941. 'license': 'bsd-3-clause', 'origin_url': 'https://github.com/pytorch/vision', **kwargs
  942. }
  943. default_cfgs = generate_default_cfgs({
  944. # timm trained models
  945. 'regnety_032.ra_in1k': _cfg(
  946. hf_hub_id='timm/',
  947. url='https://github.com/huggingface/pytorch-image-models/releases/download/v0.1-weights/regnety_032_ra-7f2439f9.pth'),
  948. 'regnety_040.ra3_in1k': _cfg(
  949. hf_hub_id='timm/',
  950. url='https://github.com/huggingface/pytorch-image-models/releases/download/v0.1-tpu-weights/regnety_040_ra3-670e1166.pth'),
  951. 'regnety_064.ra3_in1k': _cfg(
  952. hf_hub_id='timm/',
  953. url='https://github.com/huggingface/pytorch-image-models/releases/download/v0.1-tpu-weights/regnety_064_ra3-aa26dc7d.pth'),
  954. 'regnety_080.ra3_in1k': _cfg(
  955. hf_hub_id='timm/',
  956. url='https://github.com/huggingface/pytorch-image-models/releases/download/v0.1-tpu-weights/regnety_080_ra3-1fdc4344.pth'),
  957. 'regnety_120.sw_in12k_ft_in1k': _cfg(hf_hub_id='timm/'),
  958. 'regnety_160.sw_in12k_ft_in1k': _cfg(hf_hub_id='timm/'),
  959. 'regnety_160.lion_in12k_ft_in1k': _cfg(hf_hub_id='timm/'),
  960. # timm in12k pretrain
  961. 'regnety_120.sw_in12k': _cfg(
  962. hf_hub_id='timm/',
  963. num_classes=11821),
  964. 'regnety_160.sw_in12k': _cfg(
  965. hf_hub_id='timm/',
  966. num_classes=11821),
  967. # timm custom arch (v and z guess) + trained models
  968. 'regnety_040_sgn.untrained': _cfg(url=''),
  969. 'regnetv_040.ra3_in1k': _cfg(
  970. hf_hub_id='timm/',
  971. url='https://github.com/huggingface/pytorch-image-models/releases/download/v0.1-tpu-weights/regnetv_040_ra3-c248f51f.pth',
  972. first_conv='stem'),
  973. 'regnetv_064.ra3_in1k': _cfg(
  974. hf_hub_id='timm/',
  975. url='https://github.com/huggingface/pytorch-image-models/releases/download/v0.1-tpu-weights/regnetv_064_ra3-530616c2.pth',
  976. first_conv='stem'),
  977. 'regnetz_005.untrained': _cfg(url=''),
  978. 'regnetz_040.ra3_in1k': _cfg(
  979. hf_hub_id='timm/',
  980. url='https://github.com/huggingface/pytorch-image-models/releases/download/v0.1-tpu-weights/regnetz_040_ra3-9007edf5.pth',
  981. input_size=(3, 256, 256), pool_size=(8, 8), crop_pct=1.0, test_input_size=(3, 320, 320)),
  982. 'regnetz_040_h.ra3_in1k': _cfg(
  983. hf_hub_id='timm/',
  984. url='https://github.com/huggingface/pytorch-image-models/releases/download/v0.1-tpu-weights/regnetz_040h_ra3-f594343b.pth',
  985. input_size=(3, 256, 256), pool_size=(8, 8), crop_pct=1.0, test_input_size=(3, 320, 320)),
  986. # used in DeiT for distillation (from Facebook DeiT GitHub repository)
  987. 'regnety_160.deit_in1k': _cfg(
  988. hf_hub_id='timm/', url='https://dl.fbaipublicfiles.com/deit/regnety_160-a5fe301d.pth'),
  989. 'regnetx_004_tv.tv2_in1k': _cfgtv2(
  990. hf_hub_id='timm/',
  991. url='https://download.pytorch.org/models/regnet_x_400mf-62229a5f.pth'),
  992. 'regnetx_008.tv2_in1k': _cfgtv2(
  993. hf_hub_id='timm/',
  994. url='https://download.pytorch.org/models/regnet_x_800mf-94a99ebd.pth'),
  995. 'regnetx_016.tv2_in1k': _cfgtv2(
  996. hf_hub_id='timm/',
  997. url='https://download.pytorch.org/models/regnet_x_1_6gf-a12f2b72.pth'),
  998. 'regnetx_032.tv2_in1k': _cfgtv2(
  999. hf_hub_id='timm/',
  1000. url='https://download.pytorch.org/models/regnet_x_3_2gf-7071aa85.pth'),
  1001. 'regnetx_080.tv2_in1k': _cfgtv2(
  1002. hf_hub_id='timm/',
  1003. url='https://download.pytorch.org/models/regnet_x_8gf-2b70d774.pth'),
  1004. 'regnetx_160.tv2_in1k': _cfgtv2(
  1005. hf_hub_id='timm/',
  1006. url='https://download.pytorch.org/models/regnet_x_16gf-ba3796d7.pth'),
  1007. 'regnetx_320.tv2_in1k': _cfgtv2(
  1008. hf_hub_id='timm/',
  1009. url='https://download.pytorch.org/models/regnet_x_32gf-6eb8fdc6.pth'),
  1010. 'regnety_004.tv2_in1k': _cfgtv2(
  1011. hf_hub_id='timm/',
  1012. url='https://download.pytorch.org/models/regnet_y_400mf-e6988f5f.pth'),
  1013. 'regnety_008_tv.tv2_in1k': _cfgtv2(
  1014. hf_hub_id='timm/',
  1015. url='https://download.pytorch.org/models/regnet_y_800mf-58fc7688.pth'),
  1016. 'regnety_016.tv2_in1k': _cfgtv2(
  1017. hf_hub_id='timm/',
  1018. url='https://download.pytorch.org/models/regnet_y_1_6gf-0d7bc02a.pth'),
  1019. 'regnety_032.tv2_in1k': _cfgtv2(
  1020. hf_hub_id='timm/',
  1021. url='https://download.pytorch.org/models/regnet_y_3_2gf-9180c971.pth'),
  1022. 'regnety_080_tv.tv2_in1k': _cfgtv2(
  1023. hf_hub_id='timm/',
  1024. url='https://download.pytorch.org/models/regnet_y_8gf-dc2b1b54.pth'),
  1025. 'regnety_160.tv2_in1k': _cfgtv2(
  1026. hf_hub_id='timm/',
  1027. url='https://download.pytorch.org/models/regnet_y_16gf-3e4a00f9.pth'),
  1028. 'regnety_320.tv2_in1k': _cfgtv2(
  1029. hf_hub_id='timm/',
  1030. url='https://download.pytorch.org/models/regnet_y_32gf-8db6d4b5.pth'),
  1031. 'regnety_160.swag_ft_in1k': _cfgtv2(
  1032. hf_hub_id='timm/',
  1033. url='https://download.pytorch.org/models/regnet_y_16gf_swag-43afe44d.pth', license='cc-by-nc-4.0',
  1034. input_size=(3, 384, 384), pool_size=(12, 12), crop_pct=1.0),
  1035. 'regnety_320.swag_ft_in1k': _cfgtv2(
  1036. hf_hub_id='timm/',
  1037. url='https://download.pytorch.org/models/regnet_y_32gf_swag-04fdfa75.pth', license='cc-by-nc-4.0',
  1038. input_size=(3, 384, 384), pool_size=(12, 12), crop_pct=1.0),
  1039. 'regnety_1280.swag_ft_in1k': _cfgtv2(
  1040. hf_hub_id='timm/',
  1041. url='https://download.pytorch.org/models/regnet_y_128gf_swag-c8ce3e52.pth', license='cc-by-nc-4.0',
  1042. input_size=(3, 384, 384), pool_size=(12, 12), crop_pct=1.0),
  1043. 'regnety_160.swag_lc_in1k': _cfgtv2(
  1044. hf_hub_id='timm/',
  1045. url='https://download.pytorch.org/models/regnet_y_16gf_lc_swag-f3ec0043.pth', license='cc-by-nc-4.0'),
  1046. 'regnety_320.swag_lc_in1k': _cfgtv2(
  1047. hf_hub_id='timm/',
  1048. url='https://download.pytorch.org/models/regnet_y_32gf_lc_swag-e1583746.pth', license='cc-by-nc-4.0'),
  1049. 'regnety_1280.swag_lc_in1k': _cfgtv2(
  1050. hf_hub_id='timm/',
  1051. url='https://download.pytorch.org/models/regnet_y_128gf_lc_swag-cbe8ce12.pth', license='cc-by-nc-4.0'),
  1052. 'regnety_320.seer_ft_in1k': _cfgtv2(
  1053. hf_hub_id='timm/',
  1054. license='seer-license', origin_url='https://github.com/facebookresearch/vissl',
  1055. url='https://dl.fbaipublicfiles.com/vissl/model_zoo/seer_finetuned/seer_regnet32_finetuned_in1k_model_final_checkpoint_phase78.torch',
  1056. input_size=(3, 384, 384), pool_size=(12, 12), crop_pct=1.0),
  1057. 'regnety_640.seer_ft_in1k': _cfgtv2(
  1058. hf_hub_id='timm/',
  1059. license='seer-license', origin_url='https://github.com/facebookresearch/vissl',
  1060. url='https://dl.fbaipublicfiles.com/vissl/model_zoo/seer_finetuned/seer_regnet64_finetuned_in1k_model_final_checkpoint_phase78.torch',
  1061. input_size=(3, 384, 384), pool_size=(12, 12), crop_pct=1.0),
  1062. 'regnety_1280.seer_ft_in1k': _cfgtv2(
  1063. hf_hub_id='timm/',
  1064. license='seer-license', origin_url='https://github.com/facebookresearch/vissl',
  1065. url='https://dl.fbaipublicfiles.com/vissl/model_zoo/seer_finetuned/seer_regnet128_finetuned_in1k_model_final_checkpoint_phase78.torch',
  1066. input_size=(3, 384, 384), pool_size=(12, 12), crop_pct=1.0),
  1067. 'regnety_2560.seer_ft_in1k': _cfgtv2(
  1068. hf_hub_id='timm/',
  1069. license='seer-license', origin_url='https://github.com/facebookresearch/vissl',
  1070. url='https://dl.fbaipublicfiles.com/vissl/model_zoo/seer_finetuned/seer_regnet256_finetuned_in1k_model_final_checkpoint_phase38.torch',
  1071. input_size=(3, 384, 384), pool_size=(12, 12), crop_pct=1.0),
  1072. 'regnety_320.seer': _cfgtv2(
  1073. hf_hub_id='timm/',
  1074. url='https://dl.fbaipublicfiles.com/vissl/model_zoo/seer_regnet32d/seer_regnet32gf_model_iteration244000.torch',
  1075. num_classes=0, license='seer-license', origin_url='https://github.com/facebookresearch/vissl'),
  1076. 'regnety_640.seer': _cfgtv2(
  1077. hf_hub_id='timm/',
  1078. url='https://dl.fbaipublicfiles.com/vissl/model_zoo/seer_regnet64/seer_regnet64gf_model_final_checkpoint_phase0.torch',
  1079. num_classes=0, license='seer-license', origin_url='https://github.com/facebookresearch/vissl'),
  1080. 'regnety_1280.seer': _cfgtv2(
  1081. hf_hub_id='timm/',
  1082. url='https://dl.fbaipublicfiles.com/vissl/model_zoo/swav_ig1b_regnet128Gf_cnstant_bs32_node16_sinkhorn10_proto16k_syncBN64_warmup8k/model_final_checkpoint_phase0.torch',
  1083. num_classes=0, license='seer-license', origin_url='https://github.com/facebookresearch/vissl'),
  1084. # FIXME invalid weight <-> model match, mistake on their end
  1085. #'regnety_2560.seer': _cfgtv2(
  1086. # url='https://dl.fbaipublicfiles.com/vissl/model_zoo/swav_ig1b_cosine_rg256gf_noBNhead_wd1e5_fairstore_bs16_node64_sinkhorn10_proto16k_apex_syncBN64_warmup8k/model_final_checkpoint_phase0.torch',
  1087. # num_classes=0, license='other', origin_url='https://github.com/facebookresearch/vissl'),
  1088. 'regnetx_002.pycls_in1k': _cfgpyc(hf_hub_id='timm/'),
  1089. 'regnetx_004.pycls_in1k': _cfgpyc(hf_hub_id='timm/'),
  1090. 'regnetx_006.pycls_in1k': _cfgpyc(hf_hub_id='timm/'),
  1091. 'regnetx_008.pycls_in1k': _cfgpyc(hf_hub_id='timm/'),
  1092. 'regnetx_016.pycls_in1k': _cfgpyc(hf_hub_id='timm/'),
  1093. 'regnetx_032.pycls_in1k': _cfgpyc(hf_hub_id='timm/'),
  1094. 'regnetx_040.pycls_in1k': _cfgpyc(hf_hub_id='timm/'),
  1095. 'regnetx_064.pycls_in1k': _cfgpyc(hf_hub_id='timm/'),
  1096. 'regnetx_080.pycls_in1k': _cfgpyc(hf_hub_id='timm/'),
  1097. 'regnetx_120.pycls_in1k': _cfgpyc(hf_hub_id='timm/'),
  1098. 'regnetx_160.pycls_in1k': _cfgpyc(hf_hub_id='timm/'),
  1099. 'regnetx_320.pycls_in1k': _cfgpyc(hf_hub_id='timm/'),
  1100. 'regnety_002.pycls_in1k': _cfgpyc(hf_hub_id='timm/'),
  1101. 'regnety_004.pycls_in1k': _cfgpyc(hf_hub_id='timm/'),
  1102. 'regnety_006.pycls_in1k': _cfgpyc(hf_hub_id='timm/'),
  1103. 'regnety_008.pycls_in1k': _cfgpyc(hf_hub_id='timm/'),
  1104. 'regnety_016.pycls_in1k': _cfgpyc(hf_hub_id='timm/'),
  1105. 'regnety_032.pycls_in1k': _cfgpyc(hf_hub_id='timm/'),
  1106. 'regnety_040.pycls_in1k': _cfgpyc(hf_hub_id='timm/'),
  1107. 'regnety_064.pycls_in1k': _cfgpyc(hf_hub_id='timm/'),
  1108. 'regnety_080.pycls_in1k': _cfgpyc(hf_hub_id='timm/'),
  1109. 'regnety_120.pycls_in1k': _cfgpyc(hf_hub_id='timm/'),
  1110. 'regnety_160.pycls_in1k': _cfgpyc(hf_hub_id='timm/'),
  1111. 'regnety_320.pycls_in1k': _cfgpyc(hf_hub_id='timm/'),
  1112. })
  1113. @register_model
  1114. def regnetx_002(pretrained: bool = False, **kwargs) -> RegNet:
  1115. """RegNetX-200MF"""
  1116. return _create_regnet('regnetx_002', pretrained, **kwargs)
  1117. @register_model
  1118. def regnetx_004(pretrained: bool = False, **kwargs) -> RegNet:
  1119. """RegNetX-400MF"""
  1120. return _create_regnet('regnetx_004', pretrained, **kwargs)
  1121. @register_model
  1122. def regnetx_004_tv(pretrained: bool = False, **kwargs) -> RegNet:
  1123. """RegNetX-400MF w/ torchvision group rounding"""
  1124. return _create_regnet('regnetx_004_tv', pretrained, **kwargs)
  1125. @register_model
  1126. def regnetx_006(pretrained: bool = False, **kwargs) -> RegNet:
  1127. """RegNetX-600MF"""
  1128. return _create_regnet('regnetx_006', pretrained, **kwargs)
  1129. @register_model
  1130. def regnetx_008(pretrained: bool = False, **kwargs) -> RegNet:
  1131. """RegNetX-800MF"""
  1132. return _create_regnet('regnetx_008', pretrained, **kwargs)
  1133. @register_model
  1134. def regnetx_016(pretrained: bool = False, **kwargs) -> RegNet:
  1135. """RegNetX-1.6GF"""
  1136. return _create_regnet('regnetx_016', pretrained, **kwargs)
  1137. @register_model
  1138. def regnetx_032(pretrained: bool = False, **kwargs) -> RegNet:
  1139. """RegNetX-3.2GF"""
  1140. return _create_regnet('regnetx_032', pretrained, **kwargs)
  1141. @register_model
  1142. def regnetx_040(pretrained: bool = False, **kwargs) -> RegNet:
  1143. """RegNetX-4.0GF"""
  1144. return _create_regnet('regnetx_040', pretrained, **kwargs)
  1145. @register_model
  1146. def regnetx_064(pretrained: bool = False, **kwargs) -> RegNet:
  1147. """RegNetX-6.4GF"""
  1148. return _create_regnet('regnetx_064', pretrained, **kwargs)
  1149. @register_model
  1150. def regnetx_080(pretrained: bool = False, **kwargs) -> RegNet:
  1151. """RegNetX-8.0GF"""
  1152. return _create_regnet('regnetx_080', pretrained, **kwargs)
  1153. @register_model
  1154. def regnetx_120(pretrained: bool = False, **kwargs) -> RegNet:
  1155. """RegNetX-12GF"""
  1156. return _create_regnet('regnetx_120', pretrained, **kwargs)
  1157. @register_model
  1158. def regnetx_160(pretrained: bool = False, **kwargs) -> RegNet:
  1159. """RegNetX-16GF"""
  1160. return _create_regnet('regnetx_160', pretrained, **kwargs)
  1161. @register_model
  1162. def regnetx_320(pretrained: bool = False, **kwargs) -> RegNet:
  1163. """RegNetX-32GF"""
  1164. return _create_regnet('regnetx_320', pretrained, **kwargs)
  1165. @register_model
  1166. def regnety_002(pretrained: bool = False, **kwargs) -> RegNet:
  1167. """RegNetY-200MF"""
  1168. return _create_regnet('regnety_002', pretrained, **kwargs)
  1169. @register_model
  1170. def regnety_004(pretrained: bool = False, **kwargs) -> RegNet:
  1171. """RegNetY-400MF"""
  1172. return _create_regnet('regnety_004', pretrained, **kwargs)
  1173. @register_model
  1174. def regnety_006(pretrained: bool = False, **kwargs) -> RegNet:
  1175. """RegNetY-600MF"""
  1176. return _create_regnet('regnety_006', pretrained, **kwargs)
  1177. @register_model
  1178. def regnety_008(pretrained: bool = False, **kwargs) -> RegNet:
  1179. """RegNetY-800MF"""
  1180. return _create_regnet('regnety_008', pretrained, **kwargs)
  1181. @register_model
  1182. def regnety_008_tv(pretrained: bool = False, **kwargs) -> RegNet:
  1183. """RegNetY-800MF w/ torchvision group rounding"""
  1184. return _create_regnet('regnety_008_tv', pretrained, **kwargs)
  1185. @register_model
  1186. def regnety_016(pretrained: bool = False, **kwargs) -> RegNet:
  1187. """RegNetY-1.6GF"""
  1188. return _create_regnet('regnety_016', pretrained, **kwargs)
  1189. @register_model
  1190. def regnety_032(pretrained: bool = False, **kwargs) -> RegNet:
  1191. """RegNetY-3.2GF"""
  1192. return _create_regnet('regnety_032', pretrained, **kwargs)
  1193. @register_model
  1194. def regnety_040(pretrained: bool = False, **kwargs) -> RegNet:
  1195. """RegNetY-4.0GF"""
  1196. return _create_regnet('regnety_040', pretrained, **kwargs)
  1197. @register_model
  1198. def regnety_064(pretrained: bool = False, **kwargs) -> RegNet:
  1199. """RegNetY-6.4GF"""
  1200. return _create_regnet('regnety_064', pretrained, **kwargs)
  1201. @register_model
  1202. def regnety_080(pretrained: bool = False, **kwargs) -> RegNet:
  1203. """RegNetY-8.0GF"""
  1204. return _create_regnet('regnety_080', pretrained, **kwargs)
  1205. @register_model
  1206. def regnety_080_tv(pretrained: bool = False, **kwargs) -> RegNet:
  1207. """RegNetY-8.0GF w/ torchvision group rounding"""
  1208. return _create_regnet('regnety_080_tv', pretrained, **kwargs)
  1209. @register_model
  1210. def regnety_120(pretrained: bool = False, **kwargs) -> RegNet:
  1211. """RegNetY-12GF"""
  1212. return _create_regnet('regnety_120', pretrained, **kwargs)
  1213. @register_model
  1214. def regnety_160(pretrained: bool = False, **kwargs) -> RegNet:
  1215. """RegNetY-16GF"""
  1216. return _create_regnet('regnety_160', pretrained, **kwargs)
  1217. @register_model
  1218. def regnety_320(pretrained: bool = False, **kwargs) -> RegNet:
  1219. """RegNetY-32GF"""
  1220. return _create_regnet('regnety_320', pretrained, **kwargs)
  1221. @register_model
  1222. def regnety_640(pretrained: bool = False, **kwargs) -> RegNet:
  1223. """RegNetY-64GF"""
  1224. return _create_regnet('regnety_640', pretrained, **kwargs)
  1225. @register_model
  1226. def regnety_1280(pretrained: bool = False, **kwargs) -> RegNet:
  1227. """RegNetY-128GF"""
  1228. return _create_regnet('regnety_1280', pretrained, **kwargs)
  1229. @register_model
  1230. def regnety_2560(pretrained: bool = False, **kwargs) -> RegNet:
  1231. """RegNetY-256GF"""
  1232. return _create_regnet('regnety_2560', pretrained, **kwargs)
  1233. @register_model
  1234. def regnety_040_sgn(pretrained: bool = False, **kwargs) -> RegNet:
  1235. """RegNetY-4.0GF w/ GroupNorm """
  1236. return _create_regnet('regnety_040_sgn', pretrained, **kwargs)
  1237. @register_model
  1238. def regnetv_040(pretrained: bool = False, **kwargs) -> RegNet:
  1239. """RegNetV-4.0GF (pre-activation)"""
  1240. return _create_regnet('regnetv_040', pretrained, **kwargs)
  1241. @register_model
  1242. def regnetv_064(pretrained: bool = False, **kwargs) -> RegNet:
  1243. """RegNetV-6.4GF (pre-activation)"""
  1244. return _create_regnet('regnetv_064', pretrained, **kwargs)
  1245. @register_model
  1246. def regnetz_005(pretrained: bool = False, **kwargs) -> RegNet:
  1247. """RegNetZ-500MF
  1248. NOTE: config found in https://github.com/facebookresearch/ClassyVision/blob/main/classy_vision/models/regnet.py
  1249. but it's not clear it is equivalent to paper model as not detailed in the paper.
  1250. """
  1251. return _create_regnet('regnetz_005', pretrained, zero_init_last=False, **kwargs)
  1252. @register_model
  1253. def regnetz_040(pretrained: bool = False, **kwargs) -> RegNet:
  1254. """RegNetZ-4.0GF
  1255. NOTE: config found in https://github.com/facebookresearch/ClassyVision/blob/main/classy_vision/models/regnet.py
  1256. but it's not clear it is equivalent to paper model as not detailed in the paper.
  1257. """
  1258. return _create_regnet('regnetz_040', pretrained, zero_init_last=False, **kwargs)
  1259. @register_model
  1260. def regnetz_040_h(pretrained: bool = False, **kwargs) -> RegNet:
  1261. """RegNetZ-4.0GF
  1262. NOTE: config found in https://github.com/facebookresearch/ClassyVision/blob/main/classy_vision/models/regnet.py
  1263. but it's not clear it is equivalent to paper model as not detailed in the paper.
  1264. """
  1265. return _create_regnet('regnetz_040_h', pretrained, zero_init_last=False, **kwargs)
  1266. register_model_deprecations(__name__, {
  1267. 'regnetz_040h': 'regnetz_040_h',
  1268. })