convnext.py 6.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168
  1. # The implementation is borrowed and partly modified from ConvNext,
  2. # made publicly available under the MIT License at https://github.com/facebookresearch/ConvNeXt.
  3. import os
  4. import torch
  5. import torch.nn as nn
  6. import torch.nn.functional as F
  7. from timm.models.layers import DropPath, trunc_normal_
  8. from timm.models.registry import register_model
  9. class Block(nn.Module):
  10. r""" ConvNeXt Block. There are two equivalent implementations:
  11. (1) DwConv -> LayerNorm (channels_first) -> 1x1 Conv -> GELU -> 1x1 Conv; all in (N, C, H, W)
  12. (2) DwConv -> Permute to (N, H, W, C); LayerNorm (channels_last) -> Linear -> GELU -> Linear; Permute back
  13. We use (2) as we find it slightly faster in PyTorch
  14. Args:
  15. dim (int): Number of input channels.
  16. drop_path (float): Stochastic depth rate. Default: 0.0
  17. layer_scale_init_value (float): Init value for Layer Scale. Default: 1e-6.
  18. """
  19. def __init__(self, dim, drop_path=0., layer_scale_init_value=1e-6):
  20. super().__init__()
  21. self.dwconv = nn.Conv2d(
  22. dim, dim, kernel_size=7, padding=3, groups=dim) # depthwise conv
  23. self.norm = LayerNorm(dim, eps=1e-6)
  24. self.pwconv1 = nn.Linear(
  25. dim,
  26. 4 * dim) # pointwise/1x1 convs, implemented with linear layers
  27. self.act = nn.GELU()
  28. self.pwconv2 = nn.Linear(4 * dim, dim)
  29. self.gamma = nn.Parameter(
  30. layer_scale_init_value * torch.ones((dim)),
  31. requires_grad=True) if layer_scale_init_value > 0 else None
  32. self.drop_path = DropPath(
  33. drop_path) if drop_path > 0. else nn.Identity()
  34. def forward(self, x):
  35. input = x
  36. x = self.dwconv(x)
  37. x = x.permute(0, 2, 3, 1) # (N, C, H, W) -> (N, H, W, C)
  38. x = self.norm(x)
  39. x = self.pwconv1(x)
  40. x = self.act(x)
  41. x = self.pwconv2(x)
  42. if self.gamma is not None:
  43. x = self.gamma * x
  44. x = x.permute(0, 3, 1, 2) # (N, H, W, C) -> (N, C, H, W)
  45. x = input + self.drop_path(x)
  46. return x
  47. class ConvNeXt(nn.Module):
  48. r""" ConvNeXt
  49. A PyTorch impl of : `A ConvNet for the 2020s` -
  50. https://arxiv.org/pdf/2201.03545.pdf
  51. Args:
  52. in_chans (int): Number of input image channels. Default: 3
  53. num_classes (int): Number of classes for classification head. Default: 1000
  54. depths (tuple(int)): Number of blocks at each stage. Default: [3, 3, 9, 3]
  55. dims (int): Feature dimension at each stage. Default: [96, 192, 384, 768]
  56. drop_path_rate (float): Stochastic depth rate. Default: 0.
  57. layer_scale_init_value (float): Init value for Layer Scale. Default: 1e-6.
  58. head_init_scale (float): Init scaling value for classifier weights and biases. Default: 1.
  59. """
  60. def __init__(
  61. self,
  62. in_chans=3,
  63. depths=[3, 3, 9, 3],
  64. dims=[96, 192, 384, 768],
  65. drop_path_rate=0.,
  66. layer_scale_init_value=1e-6,
  67. ):
  68. super().__init__()
  69. self.downsample_layers = nn.ModuleList(
  70. ) # stem and 3 intermediate downsampling conv layers
  71. stem = nn.Sequential(
  72. nn.Conv2d(in_chans, dims[0], kernel_size=4, stride=4),
  73. LayerNorm(dims[0], eps=1e-6, data_format='channels_first'))
  74. self.downsample_layers.append(stem)
  75. for i in range(3):
  76. downsample_layer = nn.Sequential(
  77. LayerNorm(dims[i], eps=1e-6, data_format='channels_first'),
  78. nn.Conv2d(dims[i], dims[i + 1], kernel_size=2, stride=2),
  79. )
  80. self.downsample_layers.append(downsample_layer)
  81. self.stages = nn.ModuleList(
  82. ) # 4 feature resolution stages, each consisting of multiple residual blocks
  83. dp_rates = [
  84. x.item() for x in torch.linspace(0, drop_path_rate, sum(depths))
  85. ]
  86. cur = 0
  87. for i in range(4):
  88. stage = nn.Sequential(*[
  89. Block(
  90. dim=dims[i],
  91. drop_path=dp_rates[cur + j],
  92. layer_scale_init_value=layer_scale_init_value)
  93. for j in range(depths[i])
  94. ])
  95. self.stages.append(stage)
  96. cur += depths[i]
  97. # self.norm = nn.LayerNorm(dims[-1], eps=1e-6) # final norm layer
  98. self.dims = dims
  99. self.apply(self._init_weights)
  100. def _init_weights(self, m):
  101. if isinstance(m, (nn.Conv2d, nn.Linear)):
  102. trunc_normal_(m.weight, std=.02)
  103. nn.init.constant_(m.bias, 0)
  104. def forward(self, x):
  105. xs = []
  106. for i in range(4):
  107. x = self.downsample_layers[i](x)
  108. x = self.stages[i](x)
  109. xs.append(x)
  110. # x = x.permute(0, 2, 3, 1) # [N, H, W, C]
  111. # x = self.norm(x)
  112. # x = x.permute(0, 3, 1, 2) # [N, C, H, W]
  113. return tuple(xs)
  114. class LayerNorm(nn.Module):
  115. r""" LayerNorm that supports two data formats: channels_last (default) or channels_first.
  116. The ordering of the dimensions in the inputs. channels_last corresponds to inputs with
  117. shape (batch_size, height, width, channels) while channels_first corresponds to inputs
  118. with shape (batch_size, channels, height, width).
  119. """
  120. def __init__(self,
  121. normalized_shape,
  122. eps=1e-6,
  123. data_format='channels_last'):
  124. super().__init__()
  125. self.weight = nn.Parameter(torch.ones(normalized_shape))
  126. self.bias = nn.Parameter(torch.zeros(normalized_shape))
  127. self.eps = eps
  128. self.data_format = data_format
  129. if self.data_format not in ['channels_last', 'channels_first']:
  130. raise NotImplementedError
  131. self.normalized_shape = (normalized_shape, )
  132. def forward(self, x):
  133. if self.data_format == 'channels_last':
  134. return F.layer_norm(x, self.normalized_shape, self.weight,
  135. self.bias, self.eps)
  136. elif self.data_format == 'channels_first':
  137. u = x.mean(1, keepdim=True)
  138. s = (x - u).pow(2).mean(1, keepdim=True)
  139. x = (x - u) / torch.sqrt(s + self.eps)
  140. x = self.weight[:, None, None] * x + self.bias[:, None, None]
  141. return x
  142. @register_model
  143. def convnext_tiny(pretrained=False, in_22k=False, **kwargs):
  144. model = ConvNeXt(depths=[3, 3, 9, 3], dims=[96, 192, 384, 768], **kwargs)
  145. return model