convnextv2.py 7.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213
  1. # Copyright (c) Meta Platforms, Inc. and affiliates.
  2. # All rights reserved.
  3. # This source code is licensed under the license found in the
  4. # LICENSE file in the root directory of this source tree.
  5. import torch
  6. import torch.nn as nn
  7. import torch.nn.functional as F
  8. from torch.nn.init import trunc_normal_
  9. from openrec.modeling.common import DropPath
  10. class LayerNorm(nn.Module):
  11. """ LayerNorm that supports two data formats: channels_last (default) or channels_first.
  12. The ordering of the dimensions in the inputs. channels_last corresponds to inputs with
  13. shape (batch_size, height, width, channels) while channels_first corresponds to inputs
  14. with shape (batch_size, channels, height, width).
  15. """
  16. def __init__(self,
  17. normalized_shape,
  18. eps=1e-6,
  19. data_format='channels_last'):
  20. super().__init__()
  21. self.weight = nn.Parameter(torch.ones(normalized_shape))
  22. self.bias = nn.Parameter(torch.zeros(normalized_shape))
  23. self.eps = eps
  24. self.data_format = data_format
  25. if self.data_format not in ['channels_last', 'channels_first']:
  26. raise NotImplementedError
  27. self.normalized_shape = (normalized_shape, )
  28. def forward(self, x):
  29. if self.data_format == 'channels_last':
  30. return F.layer_norm(x, self.normalized_shape, self.weight,
  31. self.bias, self.eps)
  32. elif self.data_format == 'channels_first':
  33. u = x.mean(1, keepdim=True)
  34. s = (x - u).pow(2).mean(1, keepdim=True)
  35. x = (x - u) / torch.sqrt(s + self.eps)
  36. x = self.weight[:, None, None] * x + self.bias[:, None, None]
  37. return x
  38. class GRN(nn.Module):
  39. """ GRN (Global Response Normalization) layer
  40. """
  41. def __init__(self, dim):
  42. super().__init__()
  43. self.gamma = nn.Parameter(torch.zeros(1, 1, 1, dim))
  44. self.beta = nn.Parameter(torch.zeros(1, 1, 1, dim))
  45. def forward(self, inputs, mask=None):
  46. x = inputs
  47. if mask is not None:
  48. x = x * (1. - mask)
  49. Gx = torch.norm(x, p=2, dim=(1, 2), keepdim=True)
  50. Nx = Gx / (Gx.mean(dim=-1, keepdim=True) + 1e-6)
  51. return self.gamma * (inputs * Nx) + self.beta + inputs
  52. class Block(nn.Module):
  53. """ ConvNeXtV2 Block.
  54. Args:
  55. dim (int): Number of input channels.
  56. drop_path (float): Stochastic depth rate. Default: 0.0
  57. """
  58. def __init__(self, dim, drop_path=0.):
  59. super().__init__()
  60. self.dwconv = nn.Conv2d(dim, dim, kernel_size=7, padding=3,
  61. groups=dim) # depthwise conv
  62. self.norm = LayerNorm(dim, eps=1e-6)
  63. self.pwconv1 = nn.Linear(
  64. dim,
  65. 4 * dim) # pointwise/1x1 convs, implemented with linear layers
  66. self.act = nn.GELU()
  67. self.grn = GRN(4 * dim)
  68. self.pwconv2 = nn.Linear(4 * dim, dim)
  69. self.drop_path = DropPath(
  70. drop_path) if drop_path > 0. else nn.Identity()
  71. def forward(self, x):
  72. input = x
  73. x = self.dwconv(x.contiguous())
  74. x = x.permute(0, 2, 3, 1) # (N, C, H, W) -> (N, H, W, C)
  75. x = self.norm(x)
  76. x = self.pwconv1(x)
  77. x = self.act(x)
  78. x = self.grn(x)
  79. x = self.pwconv2(x)
  80. x = x.permute(0, 3, 1, 2) # (N, H, W, C) -> (N, C, H, W)
  81. x = input + self.drop_path(x)
  82. return x
  83. class ConvNeXtV2(nn.Module):
  84. """ ConvNeXt V2
  85. Args:
  86. in_chans (int): Number of input image channels. Default: 3
  87. num_classes (int): Number of classes for classification head. Default: 1000
  88. depths (tuple(int)): Number of blocks at each stage. Default: [3, 3, 9, 3]
  89. dims (int): Feature dimension at each stage. Default: [96, 192, 384, 768]
  90. drop_path_rate (float): Stochastic depth rate. Default: 0.
  91. head_init_scale (float): Init scaling value for classifier weights and biases. Default: 1.
  92. """
  93. def __init__(
  94. self,
  95. in_channels=3,
  96. depths=[3, 3, 9, 3],
  97. dims=[96, 192, 384, 768],
  98. drop_path_rate=0.,
  99. strides=[(4, 4), (2, 2), (2, 2), (2, 2)],
  100. out_channels=256,
  101. last_stage=False,
  102. feat2d=False,
  103. **kwargs,
  104. ):
  105. super().__init__()
  106. self.strides = strides
  107. self.depths = depths
  108. self.downsample_layers = nn.ModuleList(
  109. ) # stem and 3 intermediate downsampling conv layers
  110. stem = nn.Sequential(
  111. nn.Conv2d(in_channels,
  112. dims[0],
  113. kernel_size=strides[0],
  114. stride=strides[0]),
  115. LayerNorm(dims[0], eps=1e-6, data_format='channels_first'))
  116. self.downsample_layers.append(stem)
  117. for i in range(3):
  118. downsample_layer = nn.Sequential(
  119. LayerNorm(dims[i], eps=1e-6, data_format='channels_first'),
  120. nn.Conv2d(dims[i],
  121. dims[i + 1],
  122. kernel_size=strides[i + 1],
  123. stride=strides[i + 1]),
  124. )
  125. self.downsample_layers.append(downsample_layer)
  126. self.stages = nn.ModuleList(
  127. ) # 4 feature resolution stages, each consisting of multiple residual blocks
  128. dp_rates = [
  129. x.item() for x in torch.linspace(0, drop_path_rate, sum(depths))
  130. ]
  131. cur = 0
  132. for i in range(4):
  133. stage = nn.Sequential(*[
  134. Block(dim=dims[i], drop_path=dp_rates[cur + j])
  135. for j in range(depths[i])
  136. ])
  137. self.stages.append(stage)
  138. cur += depths[i]
  139. self.out_channels = dims[-1]
  140. self.last_stage = last_stage
  141. self.feat2d = feat2d
  142. if last_stage:
  143. self.out_channels = out_channels
  144. self.last_conv = nn.Linear(dims[-1], self.out_channels, bias=False)
  145. self.hardswish = nn.Hardswish()
  146. self.dropout = nn.Dropout(p=0.1)
  147. self.apply(self._init_weights)
  148. def _init_weights(self, m):
  149. if isinstance(m, (nn.Conv2d, nn.Linear)):
  150. trunc_normal_(m.weight, std=.02)
  151. if isinstance(m, (nn.Conv2d, nn.Linear)) and m.bias is not None:
  152. nn.init.constant_(m.bias, 0)
  153. elif isinstance(m, nn.LayerNorm):
  154. if m.bias is not None:
  155. nn.init.constant_(m.bias, 0)
  156. if m.weight is not None:
  157. nn.init.constant_(m.weight, 1.0)
  158. elif isinstance(m, nn.SyncBatchNorm):
  159. if m.bias is not None:
  160. nn.init.constant_(m.bias, 0)
  161. if m.weight is not None:
  162. nn.init.constant_(m.weight, 1.0)
  163. elif isinstance(m, nn.BatchNorm2d):
  164. if m.bias is not None:
  165. nn.init.constant_(m.bias, 0)
  166. if m.weight is not None:
  167. nn.init.constant_(m.weight, 1.0)
  168. def no_weight_decay(self):
  169. return {}
  170. def forward(self, x):
  171. feats = []
  172. for i in range(4):
  173. x = self.downsample_layers[i](x)
  174. x = self.stages[i](x)
  175. feats.append(x)
  176. if self.last_stage:
  177. x = x.mean(2).transpose(1, 2)
  178. x = self.last_conv(x)
  179. x = self.hardswish(x)
  180. x = self.dropout(x)
  181. return x
  182. if self.feat2d:
  183. return x
  184. return feats