regnet.py 55 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490
  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.in_chans = in_chans
  520. self.drop_rate = drop_rate
  521. assert output_stride in (8, 16, 32)
  522. cfg = replace(cfg, **kwargs) # update cfg with extra passed kwargs
  523. # Construct the stem
  524. stem_width = cfg.stem_width
  525. na_args = dict(act_layer=cfg.act_layer, norm_layer=cfg.norm_layer)
  526. if cfg.preact:
  527. self.stem = create_conv2d(in_chans, stem_width, 3, stride=2, **dd)
  528. else:
  529. self.stem = ConvNormAct(in_chans, stem_width, 3, stride=2, **na_args, **dd)
  530. self.feature_info = [dict(num_chs=stem_width, reduction=2, module='stem')]
  531. # Construct the stages
  532. prev_width = stem_width
  533. curr_stride = 2
  534. per_stage_args, common_args = self._get_stage_args(
  535. cfg,
  536. output_stride=output_stride,
  537. drop_path_rate=drop_path_rate,
  538. )
  539. assert len(per_stage_args) == 4
  540. block_fn = PreBottleneck if cfg.preact else Bottleneck
  541. for i, stage_args in enumerate(per_stage_args):
  542. stage_name = "s{}".format(i + 1)
  543. self.add_module(
  544. stage_name,
  545. RegStage(
  546. in_chs=prev_width,
  547. block_fn=block_fn,
  548. **stage_args,
  549. **common_args,
  550. **dd,
  551. )
  552. )
  553. prev_width = stage_args['out_chs']
  554. curr_stride *= stage_args['stride']
  555. self.feature_info += [dict(num_chs=prev_width, reduction=curr_stride, module=stage_name)]
  556. # Construct the head
  557. if cfg.num_features:
  558. self.final_conv = ConvNormAct(prev_width, cfg.num_features, kernel_size=1, **na_args, **dd)
  559. self.num_features = cfg.num_features
  560. else:
  561. final_act = cfg.linear_out or cfg.preact
  562. self.final_conv = get_act_layer(cfg.act_layer)() if final_act else nn.Identity()
  563. self.num_features = prev_width
  564. self.head_hidden_size = self.num_features
  565. self.head = ClassifierHead(
  566. in_features=self.num_features,
  567. num_classes=num_classes,
  568. pool_type=global_pool,
  569. drop_rate=drop_rate,
  570. **dd,
  571. )
  572. named_apply(partial(_init_weights, zero_init_last=zero_init_last), self)
  573. def _get_stage_args(
  574. self,
  575. cfg: RegNetCfg,
  576. default_stride: int = 2,
  577. output_stride: int = 32,
  578. drop_path_rate: float = 0.
  579. ) -> Tuple[List[Dict[str, Any]], Dict[str, Any]]:
  580. """Generate stage arguments from configuration.
  581. Args:`
  582. cfg: RegNet configuration.
  583. default_stride: Default stride for stages.
  584. output_stride: Target output stride.
  585. drop_path_rate: Stochastic depth rate.
  586. Returns:
  587. Tuple of (per_stage_args, common_args).
  588. """
  589. # Generate RegNet ws per block
  590. widths, num_stages, stage_gs = generate_regnet(cfg.wa, cfg.w0, cfg.wm, cfg.depth, cfg.group_size)
  591. # Convert to per stage format
  592. stage_widths, stage_depths = torch.unique(torch.tensor(widths), return_counts=True)
  593. stage_widths, stage_depths = stage_widths.tolist(), stage_depths.tolist()
  594. stage_br = [cfg.bottle_ratio for _ in range(num_stages)]
  595. stage_strides = []
  596. stage_dilations = []
  597. net_stride = 2
  598. dilation = 1
  599. for _ in range(num_stages):
  600. if net_stride >= output_stride:
  601. dilation *= default_stride
  602. stride = 1
  603. else:
  604. stride = default_stride
  605. net_stride *= stride
  606. stage_strides.append(stride)
  607. stage_dilations.append(dilation)
  608. stage_dpr = calculate_drop_path_rates(drop_path_rate, stage_depths, stagewise=True)
  609. # Adjust the compatibility of ws and gws
  610. stage_widths, stage_gs = adjust_widths_groups_comp(
  611. stage_widths, stage_br, stage_gs, min_ratio=cfg.group_min_ratio)
  612. arg_names = ['out_chs', 'stride', 'dilation', 'depth', 'bottle_ratio', 'group_size', 'drop_path_rates']
  613. per_stage_args = [
  614. dict(zip(arg_names, params)) for params in
  615. zip(stage_widths, stage_strides, stage_dilations, stage_depths, stage_br, stage_gs, stage_dpr)
  616. ]
  617. common_args = dict(
  618. downsample=cfg.downsample,
  619. se_ratio=cfg.se_ratio,
  620. linear_out=cfg.linear_out,
  621. act_layer=cfg.act_layer,
  622. norm_layer=cfg.norm_layer,
  623. )
  624. return per_stage_args, common_args
  625. @torch.jit.ignore
  626. def group_matcher(self, coarse: bool = False) -> Dict[str, Any]:
  627. """Group parameters for optimization."""
  628. return dict(
  629. stem=r'^stem',
  630. blocks=r'^s(\d+)' if coarse else r'^s(\d+)\.b(\d+)',
  631. )
  632. @torch.jit.ignore
  633. def set_grad_checkpointing(self, enable: bool = True) -> None:
  634. """Enable or disable gradient checkpointing."""
  635. for s in list(self.children())[1:-1]:
  636. s.grad_checkpointing = enable
  637. @torch.jit.ignore
  638. def get_classifier(self) -> nn.Module:
  639. """Get the classifier head."""
  640. return self.head.fc
  641. def reset_classifier(self, num_classes: int, global_pool: Optional[str] = None) -> None:
  642. """Reset the classifier head.
  643. Args:
  644. num_classes: Number of classes for new classifier.
  645. global_pool: Global pooling type.
  646. """
  647. self.num_classes = num_classes
  648. self.head.reset(num_classes, pool_type=global_pool)
  649. def forward_intermediates(
  650. self,
  651. x: torch.Tensor,
  652. indices: Optional[Union[int, List[int]]] = None,
  653. norm: bool = False,
  654. stop_early: bool = False,
  655. output_fmt: str = 'NCHW',
  656. intermediates_only: bool = False,
  657. ) -> Union[List[torch.Tensor], Tuple[torch.Tensor, List[torch.Tensor]]]:
  658. """ Forward features that returns intermediates.
  659. Args:
  660. x: Input image tensor
  661. indices: Take last n blocks if int, all if None, select matching indices if sequence
  662. norm: Apply norm layer to compatible intermediates
  663. stop_early: Stop iterating over blocks when last desired intermediate hit
  664. output_fmt: Shape of intermediate feature outputs
  665. intermediates_only: Only return intermediate features
  666. Returns:
  667. """
  668. assert output_fmt in ('NCHW',), 'Output shape must be NCHW.'
  669. intermediates = []
  670. take_indices, max_index = feature_take_indices(5, indices)
  671. # forward pass
  672. feat_idx = 0
  673. x = self.stem(x)
  674. if feat_idx in take_indices:
  675. intermediates.append(x)
  676. layer_names = ('s1', 's2', 's3', 's4')
  677. if stop_early:
  678. layer_names = layer_names[:max_index]
  679. for n in layer_names:
  680. feat_idx += 1
  681. x = getattr(self, n)(x) # won't work with torchscript, but keeps code reasonable, FML
  682. if feat_idx in take_indices:
  683. intermediates.append(x)
  684. if intermediates_only:
  685. return intermediates
  686. if feat_idx == 4:
  687. x = self.final_conv(x)
  688. return x, intermediates
  689. def prune_intermediate_layers(
  690. self,
  691. indices: Union[int, List[int]] = 1,
  692. prune_norm: bool = False,
  693. prune_head: bool = True,
  694. ) -> List[int]:
  695. """Prune layers not required for specified intermediates.
  696. Args:
  697. indices: Indices of intermediate layers to keep.
  698. prune_norm: Whether to prune normalization layer.
  699. prune_head: Whether to prune the classifier head.
  700. Returns:
  701. List of indices that were kept.
  702. """
  703. take_indices, max_index = feature_take_indices(5, indices)
  704. layer_names = ('s1', 's2', 's3', 's4')
  705. layer_names = layer_names[max_index:]
  706. for n in layer_names:
  707. setattr(self, n, nn.Identity())
  708. if max_index < 4:
  709. self.final_conv = nn.Identity()
  710. if prune_head:
  711. self.reset_classifier(0, '')
  712. return take_indices
  713. def forward_features(self, x: torch.Tensor) -> torch.Tensor:
  714. """Forward pass through feature extraction layers.
  715. Args:
  716. x: Input tensor.
  717. Returns:
  718. Feature tensor.
  719. """
  720. x = self.stem(x)
  721. x = self.s1(x)
  722. x = self.s2(x)
  723. x = self.s3(x)
  724. x = self.s4(x)
  725. x = self.final_conv(x)
  726. return x
  727. def forward_head(self, x: torch.Tensor, pre_logits: bool = False) -> torch.Tensor:
  728. """Forward pass through classifier head.
  729. Args:
  730. x: Input features.
  731. pre_logits: Return features before final linear layer.
  732. Returns:
  733. Classification logits or features.
  734. """
  735. return self.head(x, pre_logits=pre_logits) if pre_logits else self.head(x)
  736. def forward(self, x: torch.Tensor) -> torch.Tensor:
  737. """Forward pass.
  738. Args:
  739. x: Input tensor.
  740. Returns:
  741. Output logits.
  742. """
  743. x = self.forward_features(x)
  744. x = self.forward_head(x)
  745. return x
  746. def _init_weights(module: nn.Module, name: str = '', zero_init_last: bool = False) -> None:
  747. """Initialize module weights.
  748. Args:
  749. module: PyTorch module to initialize.
  750. name: Module name.
  751. zero_init_last: Zero-initialize last layer weights.
  752. """
  753. if isinstance(module, nn.Conv2d):
  754. fan_out = module.kernel_size[0] * module.kernel_size[1] * module.out_channels
  755. fan_out //= module.groups
  756. module.weight.data.normal_(0, math.sqrt(2.0 / fan_out))
  757. if module.bias is not None:
  758. module.bias.data.zero_()
  759. elif isinstance(module, nn.Linear):
  760. nn.init.normal_(module.weight, mean=0.0, std=0.01)
  761. if module.bias is not None:
  762. nn.init.zeros_(module.bias)
  763. elif zero_init_last and hasattr(module, 'zero_init_last'):
  764. module.zero_init_last()
  765. def _filter_fn(state_dict: Dict[str, Any]) -> Dict[str, Any]:
  766. """Filter and remap state dict keys for compatibility.
  767. Args:
  768. state_dict: Raw state dictionary.
  769. Returns:
  770. Filtered state dictionary.
  771. """
  772. state_dict = state_dict.get('model', state_dict)
  773. replaces = [
  774. ('f.a.0', 'conv1.conv'),
  775. ('f.a.1', 'conv1.bn'),
  776. ('f.b.0', 'conv2.conv'),
  777. ('f.b.1', 'conv2.bn'),
  778. ('f.final_bn', 'conv3.bn'),
  779. ('f.se.excitation.0', 'se.fc1'),
  780. ('f.se.excitation.2', 'se.fc2'),
  781. ('f.se', 'se'),
  782. ('f.c.0', 'conv3.conv'),
  783. ('f.c.1', 'conv3.bn'),
  784. ('f.c', 'conv3.conv'),
  785. ('proj.0', 'downsample.conv'),
  786. ('proj.1', 'downsample.bn'),
  787. ('proj', 'downsample.conv'),
  788. ]
  789. if 'classy_state_dict' in state_dict:
  790. # classy-vision & vissl (SEER) weights
  791. import re
  792. state_dict = state_dict['classy_state_dict']['base_model']['model']
  793. out = {}
  794. for k, v in state_dict['trunk'].items():
  795. k = k.replace('_feature_blocks.conv1.stem.0', 'stem.conv')
  796. k = k.replace('_feature_blocks.conv1.stem.1', 'stem.bn')
  797. k = re.sub(
  798. r'^_feature_blocks.res\d.block(\d)-(\d+)',
  799. lambda x: f's{int(x.group(1))}.b{int(x.group(2)) + 1}', k)
  800. k = re.sub(r's(\d)\.b(\d+)\.bn', r's\1.b\2.downsample.bn', k)
  801. for s, r in replaces:
  802. k = k.replace(s, r)
  803. out[k] = v
  804. for k, v in state_dict['heads'].items():
  805. if 'projection_head' in k or 'prototypes' in k:
  806. continue
  807. k = k.replace('0.clf.0', 'head.fc')
  808. out[k] = v
  809. return out
  810. if 'stem.0.weight' in state_dict:
  811. # torchvision weights
  812. import re
  813. out = {}
  814. for k, v in state_dict.items():
  815. k = k.replace('stem.0', 'stem.conv')
  816. k = k.replace('stem.1', 'stem.bn')
  817. k = re.sub(
  818. r'trunk_output.block(\d)\.block(\d+)\-(\d+)',
  819. lambda x: f's{int(x.group(1))}.b{int(x.group(3)) + 1}', k)
  820. for s, r in replaces:
  821. k = k.replace(s, r)
  822. k = k.replace('fc.', 'head.fc.')
  823. out[k] = v
  824. return out
  825. return state_dict
  826. # Model FLOPS = three trailing digits * 10^8
  827. model_cfgs = dict(
  828. # RegNet-X
  829. regnetx_002=RegNetCfg(w0=24, wa=36.44, wm=2.49, group_size=8, depth=13),
  830. regnetx_004=RegNetCfg(w0=24, wa=24.48, wm=2.54, group_size=16, depth=22),
  831. regnetx_004_tv=RegNetCfg(w0=24, wa=24.48, wm=2.54, group_size=16, depth=22, group_min_ratio=0.9),
  832. regnetx_006=RegNetCfg(w0=48, wa=36.97, wm=2.24, group_size=24, depth=16),
  833. regnetx_008=RegNetCfg(w0=56, wa=35.73, wm=2.28, group_size=16, depth=16),
  834. regnetx_016=RegNetCfg(w0=80, wa=34.01, wm=2.25, group_size=24, depth=18),
  835. regnetx_032=RegNetCfg(w0=88, wa=26.31, wm=2.25, group_size=48, depth=25),
  836. regnetx_040=RegNetCfg(w0=96, wa=38.65, wm=2.43, group_size=40, depth=23),
  837. regnetx_064=RegNetCfg(w0=184, wa=60.83, wm=2.07, group_size=56, depth=17),
  838. regnetx_080=RegNetCfg(w0=80, wa=49.56, wm=2.88, group_size=120, depth=23),
  839. regnetx_120=RegNetCfg(w0=168, wa=73.36, wm=2.37, group_size=112, depth=19),
  840. regnetx_160=RegNetCfg(w0=216, wa=55.59, wm=2.1, group_size=128, depth=22),
  841. regnetx_320=RegNetCfg(w0=320, wa=69.86, wm=2.0, group_size=168, depth=23),
  842. # RegNet-Y
  843. regnety_002=RegNetCfg(w0=24, wa=36.44, wm=2.49, group_size=8, depth=13, se_ratio=0.25),
  844. regnety_004=RegNetCfg(w0=48, wa=27.89, wm=2.09, group_size=8, depth=16, se_ratio=0.25),
  845. regnety_006=RegNetCfg(w0=48, wa=32.54, wm=2.32, group_size=16, depth=15, se_ratio=0.25),
  846. regnety_008=RegNetCfg(w0=56, wa=38.84, wm=2.4, group_size=16, depth=14, se_ratio=0.25),
  847. 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),
  848. regnety_016=RegNetCfg(w0=48, wa=20.71, wm=2.65, group_size=24, depth=27, se_ratio=0.25),
  849. regnety_032=RegNetCfg(w0=80, wa=42.63, wm=2.66, group_size=24, depth=21, se_ratio=0.25),
  850. regnety_040=RegNetCfg(w0=96, wa=31.41, wm=2.24, group_size=64, depth=22, se_ratio=0.25),
  851. regnety_064=RegNetCfg(w0=112, wa=33.22, wm=2.27, group_size=72, depth=25, se_ratio=0.25),
  852. regnety_080=RegNetCfg(w0=192, wa=76.82, wm=2.19, group_size=56, depth=17, se_ratio=0.25),
  853. 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),
  854. regnety_120=RegNetCfg(w0=168, wa=73.36, wm=2.37, group_size=112, depth=19, se_ratio=0.25),
  855. regnety_160=RegNetCfg(w0=200, wa=106.23, wm=2.48, group_size=112, depth=18, se_ratio=0.25),
  856. regnety_320=RegNetCfg(w0=232, wa=115.89, wm=2.53, group_size=232, depth=20, se_ratio=0.25),
  857. regnety_640=RegNetCfg(w0=352, wa=147.48, wm=2.4, group_size=328, depth=20, se_ratio=0.25),
  858. regnety_1280=RegNetCfg(w0=456, wa=160.83, wm=2.52, group_size=264, depth=27, se_ratio=0.25),
  859. regnety_2560=RegNetCfg(w0=640, wa=230.83, wm=2.53, group_size=373, depth=27, se_ratio=0.25),
  860. #regnety_2560=RegNetCfg(w0=640, wa=124.47, wm=2.04, group_size=848, depth=27, se_ratio=0.25),
  861. # Experimental
  862. regnety_040_sgn=RegNetCfg(
  863. w0=96, wa=31.41, wm=2.24, group_size=64, depth=22, se_ratio=0.25,
  864. act_layer='silu', norm_layer=partial(GroupNormAct, group_size=16)),
  865. # regnetv = 'preact regnet y'
  866. regnetv_040=RegNetCfg(
  867. depth=22, w0=96, wa=31.41, wm=2.24, group_size=64, se_ratio=0.25, preact=True, act_layer='silu'),
  868. regnetv_064=RegNetCfg(
  869. depth=25, w0=112, wa=33.22, wm=2.27, group_size=72, se_ratio=0.25, preact=True, act_layer='silu',
  870. downsample='avg'),
  871. # RegNet-Z (unverified)
  872. regnetz_005=RegNetCfg(
  873. depth=21, w0=16, wa=10.7, wm=2.51, group_size=4, bottle_ratio=4.0, se_ratio=0.25,
  874. downsample=None, linear_out=True, num_features=1024, act_layer='silu',
  875. ),
  876. regnetz_040=RegNetCfg(
  877. depth=28, w0=48, wa=14.5, wm=2.226, group_size=8, bottle_ratio=4.0, se_ratio=0.25,
  878. downsample=None, linear_out=True, num_features=0, act_layer='silu',
  879. ),
  880. regnetz_040_h=RegNetCfg(
  881. depth=28, w0=48, wa=14.5, wm=2.226, group_size=8, bottle_ratio=4.0, se_ratio=0.25,
  882. downsample=None, linear_out=True, num_features=1536, act_layer='silu',
  883. ),
  884. )
  885. def _create_regnet(variant: str, pretrained: bool, **kwargs) -> RegNet:
  886. """Create a RegNet model.
  887. Args:
  888. variant: Model variant name.
  889. pretrained: Load pretrained weights.
  890. **kwargs: Additional model arguments.
  891. Returns:
  892. RegNet model instance.
  893. """
  894. return build_model_with_cfg(
  895. RegNet, variant, pretrained,
  896. model_cfg=model_cfgs[variant],
  897. pretrained_filter_fn=_filter_fn,
  898. **kwargs)
  899. def _cfg(url: str = '', **kwargs) -> Dict[str, Any]:
  900. """Create default configuration dictionary.
  901. Args:
  902. url: Model weight URL.
  903. **kwargs: Additional configuration options.
  904. Returns:
  905. Configuration dictionary.
  906. """
  907. return {
  908. 'url': url, 'num_classes': 1000, 'input_size': (3, 224, 224), 'pool_size': (7, 7),
  909. 'test_input_size': (3, 288, 288), 'crop_pct': 0.95, 'test_crop_pct': 1.0,
  910. 'interpolation': 'bicubic', 'mean': IMAGENET_DEFAULT_MEAN, 'std': IMAGENET_DEFAULT_STD,
  911. 'first_conv': 'stem.conv', 'classifier': 'head.fc',
  912. 'license': 'apache-2.0', **kwargs
  913. }
  914. def _cfgpyc(url: str = '', **kwargs) -> Dict[str, Any]:
  915. """Create pycls configuration dictionary.
  916. Args:
  917. url: Model weight URL.
  918. **kwargs: Additional configuration options.
  919. Returns:
  920. Configuration dictionary.
  921. """
  922. return {
  923. 'url': url, 'num_classes': 1000, 'input_size': (3, 224, 224), 'pool_size': (7, 7),
  924. 'crop_pct': 0.875, 'interpolation': 'bicubic',
  925. 'mean': IMAGENET_DEFAULT_MEAN, 'std': IMAGENET_DEFAULT_STD,
  926. 'first_conv': 'stem.conv', 'classifier': 'head.fc',
  927. 'license': 'mit', 'origin_url': 'https://github.com/facebookresearch/pycls', **kwargs
  928. }
  929. def _cfgtv2(url: str = '', **kwargs) -> Dict[str, Any]:
  930. """Create torchvision v2 configuration dictionary.
  931. Args:
  932. url: Model weight URL.
  933. **kwargs: Additional configuration options.
  934. Returns:
  935. Configuration dictionary.
  936. """
  937. return {
  938. 'url': url, 'num_classes': 1000, 'input_size': (3, 224, 224), 'pool_size': (7, 7),
  939. 'crop_pct': 0.965, 'interpolation': 'bicubic',
  940. 'mean': IMAGENET_DEFAULT_MEAN, 'std': IMAGENET_DEFAULT_STD,
  941. 'first_conv': 'stem.conv', 'classifier': 'head.fc',
  942. 'license': 'bsd-3-clause', 'origin_url': 'https://github.com/pytorch/vision', **kwargs
  943. }
  944. default_cfgs = generate_default_cfgs({
  945. # timm trained models
  946. 'regnety_032.ra_in1k': _cfg(
  947. hf_hub_id='timm/',
  948. url='https://github.com/huggingface/pytorch-image-models/releases/download/v0.1-weights/regnety_032_ra-7f2439f9.pth'),
  949. 'regnety_040.ra3_in1k': _cfg(
  950. hf_hub_id='timm/',
  951. url='https://github.com/huggingface/pytorch-image-models/releases/download/v0.1-tpu-weights/regnety_040_ra3-670e1166.pth'),
  952. 'regnety_064.ra3_in1k': _cfg(
  953. hf_hub_id='timm/',
  954. url='https://github.com/huggingface/pytorch-image-models/releases/download/v0.1-tpu-weights/regnety_064_ra3-aa26dc7d.pth'),
  955. 'regnety_080.ra3_in1k': _cfg(
  956. hf_hub_id='timm/',
  957. url='https://github.com/huggingface/pytorch-image-models/releases/download/v0.1-tpu-weights/regnety_080_ra3-1fdc4344.pth'),
  958. 'regnety_120.sw_in12k_ft_in1k': _cfg(hf_hub_id='timm/'),
  959. 'regnety_160.sw_in12k_ft_in1k': _cfg(hf_hub_id='timm/'),
  960. 'regnety_160.lion_in12k_ft_in1k': _cfg(hf_hub_id='timm/'),
  961. # timm in12k pretrain
  962. 'regnety_120.sw_in12k': _cfg(
  963. hf_hub_id='timm/',
  964. num_classes=11821),
  965. 'regnety_160.sw_in12k': _cfg(
  966. hf_hub_id='timm/',
  967. num_classes=11821),
  968. # timm custom arch (v and z guess) + trained models
  969. 'regnety_040_sgn.untrained': _cfg(url=''),
  970. 'regnetv_040.ra3_in1k': _cfg(
  971. hf_hub_id='timm/',
  972. url='https://github.com/huggingface/pytorch-image-models/releases/download/v0.1-tpu-weights/regnetv_040_ra3-c248f51f.pth',
  973. first_conv='stem'),
  974. 'regnetv_064.ra3_in1k': _cfg(
  975. hf_hub_id='timm/',
  976. url='https://github.com/huggingface/pytorch-image-models/releases/download/v0.1-tpu-weights/regnetv_064_ra3-530616c2.pth',
  977. first_conv='stem'),
  978. 'regnetz_005.untrained': _cfg(url=''),
  979. 'regnetz_040.ra3_in1k': _cfg(
  980. hf_hub_id='timm/',
  981. url='https://github.com/huggingface/pytorch-image-models/releases/download/v0.1-tpu-weights/regnetz_040_ra3-9007edf5.pth',
  982. input_size=(3, 256, 256), pool_size=(8, 8), crop_pct=1.0, test_input_size=(3, 320, 320)),
  983. 'regnetz_040_h.ra3_in1k': _cfg(
  984. hf_hub_id='timm/',
  985. url='https://github.com/huggingface/pytorch-image-models/releases/download/v0.1-tpu-weights/regnetz_040h_ra3-f594343b.pth',
  986. input_size=(3, 256, 256), pool_size=(8, 8), crop_pct=1.0, test_input_size=(3, 320, 320)),
  987. # used in DeiT for distillation (from Facebook DeiT GitHub repository)
  988. 'regnety_160.deit_in1k': _cfg(
  989. hf_hub_id='timm/', url='https://dl.fbaipublicfiles.com/deit/regnety_160-a5fe301d.pth'),
  990. 'regnetx_004_tv.tv2_in1k': _cfgtv2(
  991. hf_hub_id='timm/',
  992. url='https://download.pytorch.org/models/regnet_x_400mf-62229a5f.pth'),
  993. 'regnetx_008.tv2_in1k': _cfgtv2(
  994. hf_hub_id='timm/',
  995. url='https://download.pytorch.org/models/regnet_x_800mf-94a99ebd.pth'),
  996. 'regnetx_016.tv2_in1k': _cfgtv2(
  997. hf_hub_id='timm/',
  998. url='https://download.pytorch.org/models/regnet_x_1_6gf-a12f2b72.pth'),
  999. 'regnetx_032.tv2_in1k': _cfgtv2(
  1000. hf_hub_id='timm/',
  1001. url='https://download.pytorch.org/models/regnet_x_3_2gf-7071aa85.pth'),
  1002. 'regnetx_080.tv2_in1k': _cfgtv2(
  1003. hf_hub_id='timm/',
  1004. url='https://download.pytorch.org/models/regnet_x_8gf-2b70d774.pth'),
  1005. 'regnetx_160.tv2_in1k': _cfgtv2(
  1006. hf_hub_id='timm/',
  1007. url='https://download.pytorch.org/models/regnet_x_16gf-ba3796d7.pth'),
  1008. 'regnetx_320.tv2_in1k': _cfgtv2(
  1009. hf_hub_id='timm/',
  1010. url='https://download.pytorch.org/models/regnet_x_32gf-6eb8fdc6.pth'),
  1011. 'regnety_004.tv2_in1k': _cfgtv2(
  1012. hf_hub_id='timm/',
  1013. url='https://download.pytorch.org/models/regnet_y_400mf-e6988f5f.pth'),
  1014. 'regnety_008_tv.tv2_in1k': _cfgtv2(
  1015. hf_hub_id='timm/',
  1016. url='https://download.pytorch.org/models/regnet_y_800mf-58fc7688.pth'),
  1017. 'regnety_016.tv2_in1k': _cfgtv2(
  1018. hf_hub_id='timm/',
  1019. url='https://download.pytorch.org/models/regnet_y_1_6gf-0d7bc02a.pth'),
  1020. 'regnety_032.tv2_in1k': _cfgtv2(
  1021. hf_hub_id='timm/',
  1022. url='https://download.pytorch.org/models/regnet_y_3_2gf-9180c971.pth'),
  1023. 'regnety_080_tv.tv2_in1k': _cfgtv2(
  1024. hf_hub_id='timm/',
  1025. url='https://download.pytorch.org/models/regnet_y_8gf-dc2b1b54.pth'),
  1026. 'regnety_160.tv2_in1k': _cfgtv2(
  1027. hf_hub_id='timm/',
  1028. url='https://download.pytorch.org/models/regnet_y_16gf-3e4a00f9.pth'),
  1029. 'regnety_320.tv2_in1k': _cfgtv2(
  1030. hf_hub_id='timm/',
  1031. url='https://download.pytorch.org/models/regnet_y_32gf-8db6d4b5.pth'),
  1032. 'regnety_160.swag_ft_in1k': _cfgtv2(
  1033. hf_hub_id='timm/',
  1034. url='https://download.pytorch.org/models/regnet_y_16gf_swag-43afe44d.pth', license='cc-by-nc-4.0',
  1035. input_size=(3, 384, 384), pool_size=(12, 12), crop_pct=1.0),
  1036. 'regnety_320.swag_ft_in1k': _cfgtv2(
  1037. hf_hub_id='timm/',
  1038. url='https://download.pytorch.org/models/regnet_y_32gf_swag-04fdfa75.pth', license='cc-by-nc-4.0',
  1039. input_size=(3, 384, 384), pool_size=(12, 12), crop_pct=1.0),
  1040. 'regnety_1280.swag_ft_in1k': _cfgtv2(
  1041. hf_hub_id='timm/',
  1042. url='https://download.pytorch.org/models/regnet_y_128gf_swag-c8ce3e52.pth', license='cc-by-nc-4.0',
  1043. input_size=(3, 384, 384), pool_size=(12, 12), crop_pct=1.0),
  1044. 'regnety_160.swag_lc_in1k': _cfgtv2(
  1045. hf_hub_id='timm/',
  1046. url='https://download.pytorch.org/models/regnet_y_16gf_lc_swag-f3ec0043.pth', license='cc-by-nc-4.0'),
  1047. 'regnety_320.swag_lc_in1k': _cfgtv2(
  1048. hf_hub_id='timm/',
  1049. url='https://download.pytorch.org/models/regnet_y_32gf_lc_swag-e1583746.pth', license='cc-by-nc-4.0'),
  1050. 'regnety_1280.swag_lc_in1k': _cfgtv2(
  1051. hf_hub_id='timm/',
  1052. url='https://download.pytorch.org/models/regnet_y_128gf_lc_swag-cbe8ce12.pth', license='cc-by-nc-4.0'),
  1053. 'regnety_320.seer_ft_in1k': _cfgtv2(
  1054. hf_hub_id='timm/',
  1055. license='seer-license', origin_url='https://github.com/facebookresearch/vissl',
  1056. url='https://dl.fbaipublicfiles.com/vissl/model_zoo/seer_finetuned/seer_regnet32_finetuned_in1k_model_final_checkpoint_phase78.torch',
  1057. input_size=(3, 384, 384), pool_size=(12, 12), crop_pct=1.0),
  1058. 'regnety_640.seer_ft_in1k': _cfgtv2(
  1059. hf_hub_id='timm/',
  1060. license='seer-license', origin_url='https://github.com/facebookresearch/vissl',
  1061. url='https://dl.fbaipublicfiles.com/vissl/model_zoo/seer_finetuned/seer_regnet64_finetuned_in1k_model_final_checkpoint_phase78.torch',
  1062. input_size=(3, 384, 384), pool_size=(12, 12), crop_pct=1.0),
  1063. 'regnety_1280.seer_ft_in1k': _cfgtv2(
  1064. hf_hub_id='timm/',
  1065. license='seer-license', origin_url='https://github.com/facebookresearch/vissl',
  1066. url='https://dl.fbaipublicfiles.com/vissl/model_zoo/seer_finetuned/seer_regnet128_finetuned_in1k_model_final_checkpoint_phase78.torch',
  1067. input_size=(3, 384, 384), pool_size=(12, 12), crop_pct=1.0),
  1068. 'regnety_2560.seer_ft_in1k': _cfgtv2(
  1069. hf_hub_id='timm/',
  1070. license='seer-license', origin_url='https://github.com/facebookresearch/vissl',
  1071. url='https://dl.fbaipublicfiles.com/vissl/model_zoo/seer_finetuned/seer_regnet256_finetuned_in1k_model_final_checkpoint_phase38.torch',
  1072. input_size=(3, 384, 384), pool_size=(12, 12), crop_pct=1.0),
  1073. 'regnety_320.seer': _cfgtv2(
  1074. hf_hub_id='timm/',
  1075. url='https://dl.fbaipublicfiles.com/vissl/model_zoo/seer_regnet32d/seer_regnet32gf_model_iteration244000.torch',
  1076. num_classes=0, license='seer-license', origin_url='https://github.com/facebookresearch/vissl'),
  1077. 'regnety_640.seer': _cfgtv2(
  1078. hf_hub_id='timm/',
  1079. url='https://dl.fbaipublicfiles.com/vissl/model_zoo/seer_regnet64/seer_regnet64gf_model_final_checkpoint_phase0.torch',
  1080. num_classes=0, license='seer-license', origin_url='https://github.com/facebookresearch/vissl'),
  1081. 'regnety_1280.seer': _cfgtv2(
  1082. hf_hub_id='timm/',
  1083. url='https://dl.fbaipublicfiles.com/vissl/model_zoo/swav_ig1b_regnet128Gf_cnstant_bs32_node16_sinkhorn10_proto16k_syncBN64_warmup8k/model_final_checkpoint_phase0.torch',
  1084. num_classes=0, license='seer-license', origin_url='https://github.com/facebookresearch/vissl'),
  1085. # FIXME invalid weight <-> model match, mistake on their end
  1086. #'regnety_2560.seer': _cfgtv2(
  1087. # 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',
  1088. # num_classes=0, license='other', origin_url='https://github.com/facebookresearch/vissl'),
  1089. 'regnetx_002.pycls_in1k': _cfgpyc(hf_hub_id='timm/'),
  1090. 'regnetx_004.pycls_in1k': _cfgpyc(hf_hub_id='timm/'),
  1091. 'regnetx_006.pycls_in1k': _cfgpyc(hf_hub_id='timm/'),
  1092. 'regnetx_008.pycls_in1k': _cfgpyc(hf_hub_id='timm/'),
  1093. 'regnetx_016.pycls_in1k': _cfgpyc(hf_hub_id='timm/'),
  1094. 'regnetx_032.pycls_in1k': _cfgpyc(hf_hub_id='timm/'),
  1095. 'regnetx_040.pycls_in1k': _cfgpyc(hf_hub_id='timm/'),
  1096. 'regnetx_064.pycls_in1k': _cfgpyc(hf_hub_id='timm/'),
  1097. 'regnetx_080.pycls_in1k': _cfgpyc(hf_hub_id='timm/'),
  1098. 'regnetx_120.pycls_in1k': _cfgpyc(hf_hub_id='timm/'),
  1099. 'regnetx_160.pycls_in1k': _cfgpyc(hf_hub_id='timm/'),
  1100. 'regnetx_320.pycls_in1k': _cfgpyc(hf_hub_id='timm/'),
  1101. 'regnety_002.pycls_in1k': _cfgpyc(hf_hub_id='timm/'),
  1102. 'regnety_004.pycls_in1k': _cfgpyc(hf_hub_id='timm/'),
  1103. 'regnety_006.pycls_in1k': _cfgpyc(hf_hub_id='timm/'),
  1104. 'regnety_008.pycls_in1k': _cfgpyc(hf_hub_id='timm/'),
  1105. 'regnety_016.pycls_in1k': _cfgpyc(hf_hub_id='timm/'),
  1106. 'regnety_032.pycls_in1k': _cfgpyc(hf_hub_id='timm/'),
  1107. 'regnety_040.pycls_in1k': _cfgpyc(hf_hub_id='timm/'),
  1108. 'regnety_064.pycls_in1k': _cfgpyc(hf_hub_id='timm/'),
  1109. 'regnety_080.pycls_in1k': _cfgpyc(hf_hub_id='timm/'),
  1110. 'regnety_120.pycls_in1k': _cfgpyc(hf_hub_id='timm/'),
  1111. 'regnety_160.pycls_in1k': _cfgpyc(hf_hub_id='timm/'),
  1112. 'regnety_320.pycls_in1k': _cfgpyc(hf_hub_id='timm/'),
  1113. })
  1114. @register_model
  1115. def regnetx_002(pretrained: bool = False, **kwargs) -> RegNet:
  1116. """RegNetX-200MF"""
  1117. return _create_regnet('regnetx_002', pretrained, **kwargs)
  1118. @register_model
  1119. def regnetx_004(pretrained: bool = False, **kwargs) -> RegNet:
  1120. """RegNetX-400MF"""
  1121. return _create_regnet('regnetx_004', pretrained, **kwargs)
  1122. @register_model
  1123. def regnetx_004_tv(pretrained: bool = False, **kwargs) -> RegNet:
  1124. """RegNetX-400MF w/ torchvision group rounding"""
  1125. return _create_regnet('regnetx_004_tv', pretrained, **kwargs)
  1126. @register_model
  1127. def regnetx_006(pretrained: bool = False, **kwargs) -> RegNet:
  1128. """RegNetX-600MF"""
  1129. return _create_regnet('regnetx_006', pretrained, **kwargs)
  1130. @register_model
  1131. def regnetx_008(pretrained: bool = False, **kwargs) -> RegNet:
  1132. """RegNetX-800MF"""
  1133. return _create_regnet('regnetx_008', pretrained, **kwargs)
  1134. @register_model
  1135. def regnetx_016(pretrained: bool = False, **kwargs) -> RegNet:
  1136. """RegNetX-1.6GF"""
  1137. return _create_regnet('regnetx_016', pretrained, **kwargs)
  1138. @register_model
  1139. def regnetx_032(pretrained: bool = False, **kwargs) -> RegNet:
  1140. """RegNetX-3.2GF"""
  1141. return _create_regnet('regnetx_032', pretrained, **kwargs)
  1142. @register_model
  1143. def regnetx_040(pretrained: bool = False, **kwargs) -> RegNet:
  1144. """RegNetX-4.0GF"""
  1145. return _create_regnet('regnetx_040', pretrained, **kwargs)
  1146. @register_model
  1147. def regnetx_064(pretrained: bool = False, **kwargs) -> RegNet:
  1148. """RegNetX-6.4GF"""
  1149. return _create_regnet('regnetx_064', pretrained, **kwargs)
  1150. @register_model
  1151. def regnetx_080(pretrained: bool = False, **kwargs) -> RegNet:
  1152. """RegNetX-8.0GF"""
  1153. return _create_regnet('regnetx_080', pretrained, **kwargs)
  1154. @register_model
  1155. def regnetx_120(pretrained: bool = False, **kwargs) -> RegNet:
  1156. """RegNetX-12GF"""
  1157. return _create_regnet('regnetx_120', pretrained, **kwargs)
  1158. @register_model
  1159. def regnetx_160(pretrained: bool = False, **kwargs) -> RegNet:
  1160. """RegNetX-16GF"""
  1161. return _create_regnet('regnetx_160', pretrained, **kwargs)
  1162. @register_model
  1163. def regnetx_320(pretrained: bool = False, **kwargs) -> RegNet:
  1164. """RegNetX-32GF"""
  1165. return _create_regnet('regnetx_320', pretrained, **kwargs)
  1166. @register_model
  1167. def regnety_002(pretrained: bool = False, **kwargs) -> RegNet:
  1168. """RegNetY-200MF"""
  1169. return _create_regnet('regnety_002', pretrained, **kwargs)
  1170. @register_model
  1171. def regnety_004(pretrained: bool = False, **kwargs) -> RegNet:
  1172. """RegNetY-400MF"""
  1173. return _create_regnet('regnety_004', pretrained, **kwargs)
  1174. @register_model
  1175. def regnety_006(pretrained: bool = False, **kwargs) -> RegNet:
  1176. """RegNetY-600MF"""
  1177. return _create_regnet('regnety_006', pretrained, **kwargs)
  1178. @register_model
  1179. def regnety_008(pretrained: bool = False, **kwargs) -> RegNet:
  1180. """RegNetY-800MF"""
  1181. return _create_regnet('regnety_008', pretrained, **kwargs)
  1182. @register_model
  1183. def regnety_008_tv(pretrained: bool = False, **kwargs) -> RegNet:
  1184. """RegNetY-800MF w/ torchvision group rounding"""
  1185. return _create_regnet('regnety_008_tv', pretrained, **kwargs)
  1186. @register_model
  1187. def regnety_016(pretrained: bool = False, **kwargs) -> RegNet:
  1188. """RegNetY-1.6GF"""
  1189. return _create_regnet('regnety_016', pretrained, **kwargs)
  1190. @register_model
  1191. def regnety_032(pretrained: bool = False, **kwargs) -> RegNet:
  1192. """RegNetY-3.2GF"""
  1193. return _create_regnet('regnety_032', pretrained, **kwargs)
  1194. @register_model
  1195. def regnety_040(pretrained: bool = False, **kwargs) -> RegNet:
  1196. """RegNetY-4.0GF"""
  1197. return _create_regnet('regnety_040', pretrained, **kwargs)
  1198. @register_model
  1199. def regnety_064(pretrained: bool = False, **kwargs) -> RegNet:
  1200. """RegNetY-6.4GF"""
  1201. return _create_regnet('regnety_064', pretrained, **kwargs)
  1202. @register_model
  1203. def regnety_080(pretrained: bool = False, **kwargs) -> RegNet:
  1204. """RegNetY-8.0GF"""
  1205. return _create_regnet('regnety_080', pretrained, **kwargs)
  1206. @register_model
  1207. def regnety_080_tv(pretrained: bool = False, **kwargs) -> RegNet:
  1208. """RegNetY-8.0GF w/ torchvision group rounding"""
  1209. return _create_regnet('regnety_080_tv', pretrained, **kwargs)
  1210. @register_model
  1211. def regnety_120(pretrained: bool = False, **kwargs) -> RegNet:
  1212. """RegNetY-12GF"""
  1213. return _create_regnet('regnety_120', pretrained, **kwargs)
  1214. @register_model
  1215. def regnety_160(pretrained: bool = False, **kwargs) -> RegNet:
  1216. """RegNetY-16GF"""
  1217. return _create_regnet('regnety_160', pretrained, **kwargs)
  1218. @register_model
  1219. def regnety_320(pretrained: bool = False, **kwargs) -> RegNet:
  1220. """RegNetY-32GF"""
  1221. return _create_regnet('regnety_320', pretrained, **kwargs)
  1222. @register_model
  1223. def regnety_640(pretrained: bool = False, **kwargs) -> RegNet:
  1224. """RegNetY-64GF"""
  1225. return _create_regnet('regnety_640', pretrained, **kwargs)
  1226. @register_model
  1227. def regnety_1280(pretrained: bool = False, **kwargs) -> RegNet:
  1228. """RegNetY-128GF"""
  1229. return _create_regnet('regnety_1280', pretrained, **kwargs)
  1230. @register_model
  1231. def regnety_2560(pretrained: bool = False, **kwargs) -> RegNet:
  1232. """RegNetY-256GF"""
  1233. return _create_regnet('regnety_2560', pretrained, **kwargs)
  1234. @register_model
  1235. def regnety_040_sgn(pretrained: bool = False, **kwargs) -> RegNet:
  1236. """RegNetY-4.0GF w/ GroupNorm """
  1237. return _create_regnet('regnety_040_sgn', pretrained, **kwargs)
  1238. @register_model
  1239. def regnetv_040(pretrained: bool = False, **kwargs) -> RegNet:
  1240. """RegNetV-4.0GF (pre-activation)"""
  1241. return _create_regnet('regnetv_040', pretrained, **kwargs)
  1242. @register_model
  1243. def regnetv_064(pretrained: bool = False, **kwargs) -> RegNet:
  1244. """RegNetV-6.4GF (pre-activation)"""
  1245. return _create_regnet('regnetv_064', pretrained, **kwargs)
  1246. @register_model
  1247. def regnetz_005(pretrained: bool = False, **kwargs) -> RegNet:
  1248. """RegNetZ-500MF
  1249. NOTE: config found in https://github.com/facebookresearch/ClassyVision/blob/main/classy_vision/models/regnet.py
  1250. but it's not clear it is equivalent to paper model as not detailed in the paper.
  1251. """
  1252. return _create_regnet('regnetz_005', pretrained, zero_init_last=False, **kwargs)
  1253. @register_model
  1254. def regnetz_040(pretrained: bool = False, **kwargs) -> RegNet:
  1255. """RegNetZ-4.0GF
  1256. NOTE: config found in https://github.com/facebookresearch/ClassyVision/blob/main/classy_vision/models/regnet.py
  1257. but it's not clear it is equivalent to paper model as not detailed in the paper.
  1258. """
  1259. return _create_regnet('regnetz_040', pretrained, zero_init_last=False, **kwargs)
  1260. @register_model
  1261. def regnetz_040_h(pretrained: bool = False, **kwargs) -> RegNet:
  1262. """RegNetZ-4.0GF
  1263. NOTE: config found in https://github.com/facebookresearch/ClassyVision/blob/main/classy_vision/models/regnet.py
  1264. but it's not clear it is equivalent to paper model as not detailed in the paper.
  1265. """
  1266. return _create_regnet('regnetz_040_h', pretrained, zero_init_last=False, **kwargs)
  1267. register_model_deprecations(__name__, {
  1268. 'regnetz_040h': 'regnetz_040_h',
  1269. })