convnext.py 8.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245
  1. # Copyright (c) 2022 PaddlePaddle Authors. All Rights Reserved.
  2. #
  3. # Licensed under the Apache License, Version 2.0 (the "License");
  4. # you may not use this file except in compliance with the License.
  5. # You may obtain a copy of the License at
  6. #
  7. # http://www.apache.org/licenses/LICENSE-2.0
  8. #
  9. # Unless required by applicable law or agreed to in writing, software
  10. # distributed under the License is distributed on an "AS IS" BASIS,
  11. # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  12. # See the License for the specific language governing permissions and
  13. # limitations under the License.
  14. '''
  15. Modified from https://github.com/facebookresearch/ConvNeXt
  16. Copyright (c) Meta Platforms, Inc. and affiliates.
  17. All rights reserved.
  18. This source code is licensed under the license found in the
  19. LICENSE file in the root directory of this source tree.
  20. '''
  21. import paddle
  22. import paddle.nn as nn
  23. import paddle.nn.functional as F
  24. from paddle import ParamAttr
  25. from paddle.nn.initializer import Constant
  26. import numpy as np
  27. from ppdet.core.workspace import register, serializable
  28. from ..shape_spec import ShapeSpec
  29. from .transformer_utils import DropPath, trunc_normal_, zeros_
  30. __all__ = ['ConvNeXt']
  31. class Block(nn.Layer):
  32. r""" ConvNeXt Block. There are two equivalent implementations:
  33. (1) DwConv -> LayerNorm (channels_first) -> 1x1 Conv -> GELU -> 1x1 Conv; all in (N, C, H, W)
  34. (2) DwConv -> Permute to (N, H, W, C); LayerNorm (channels_last) -> Linear -> GELU -> Linear; Permute back
  35. We use (2) as we find it slightly faster in Pypaddle
  36. Args:
  37. dim (int): Number of input channels.
  38. drop_path (float): Stochastic depth rate. Default: 0.0
  39. layer_scale_init_value (float): Init value for Layer Scale. Default: 1e-6.
  40. """
  41. def __init__(self, dim, drop_path=0., layer_scale_init_value=1e-6):
  42. super().__init__()
  43. self.dwconv = nn.Conv2D(
  44. dim, dim, kernel_size=7, padding=3, groups=dim) # depthwise conv
  45. self.norm = LayerNorm(dim, eps=1e-6)
  46. self.pwconv1 = nn.Linear(
  47. dim, 4 * dim) # pointwise/1x1 convs, implemented with linear layers
  48. self.act = nn.GELU()
  49. self.pwconv2 = nn.Linear(4 * dim, dim)
  50. if layer_scale_init_value > 0:
  51. self.gamma = self.create_parameter(
  52. shape=(dim, ),
  53. attr=ParamAttr(initializer=Constant(layer_scale_init_value)))
  54. else:
  55. self.gamma = None
  56. self.drop_path = DropPath(drop_path) if drop_path > 0. else nn.Identity(
  57. )
  58. def forward(self, x):
  59. input = x
  60. x = self.dwconv(x)
  61. x = x.transpose([0, 2, 3, 1])
  62. x = self.norm(x)
  63. x = self.pwconv1(x)
  64. x = self.act(x)
  65. x = self.pwconv2(x)
  66. if self.gamma is not None:
  67. x = self.gamma * x
  68. x = x.transpose([0, 3, 1, 2])
  69. x = input + self.drop_path(x)
  70. return x
  71. class LayerNorm(nn.Layer):
  72. r""" LayerNorm that supports two data formats: channels_last (default) or channels_first.
  73. The ordering of the dimensions in the inputs. channels_last corresponds to inputs with
  74. shape (batch_size, height, width, channels) while channels_first corresponds to inputs
  75. with shape (batch_size, channels, height, width).
  76. """
  77. def __init__(self, normalized_shape, eps=1e-6, data_format="channels_last"):
  78. super().__init__()
  79. self.weight = self.create_parameter(
  80. shape=(normalized_shape, ),
  81. attr=ParamAttr(initializer=Constant(1.)))
  82. self.bias = self.create_parameter(
  83. shape=(normalized_shape, ),
  84. attr=ParamAttr(initializer=Constant(0.)))
  85. self.eps = eps
  86. self.data_format = data_format
  87. if self.data_format not in ["channels_last", "channels_first"]:
  88. raise NotImplementedError
  89. self.normalized_shape = (normalized_shape, )
  90. def forward(self, x):
  91. if self.data_format == "channels_last":
  92. return F.layer_norm(x, self.normalized_shape, self.weight,
  93. self.bias, self.eps)
  94. elif self.data_format == "channels_first":
  95. u = x.mean(1, keepdim=True)
  96. s = (x - u).pow(2).mean(1, keepdim=True)
  97. x = (x - u) / paddle.sqrt(s + self.eps)
  98. x = self.weight[:, None, None] * x + self.bias[:, None, None]
  99. return x
  100. @register
  101. @serializable
  102. class ConvNeXt(nn.Layer):
  103. r""" ConvNeXt
  104. A Pypaddle impl of : `A ConvNet for the 2020s` -
  105. https://arxiv.org/pdf/2201.03545.pdf
  106. Args:
  107. in_chans (int): Number of input image channels. Default: 3
  108. depths (tuple(int)): Number of blocks at each stage. Default: [3, 3, 9, 3]
  109. dims (int): Feature dimension at each stage. Default: [96, 192, 384, 768]
  110. drop_path_rate (float): Stochastic depth rate. Default: 0.
  111. layer_scale_init_value (float): Init value for Layer Scale. Default: 1e-6.
  112. """
  113. arch_settings = {
  114. 'tiny': {
  115. 'depths': [3, 3, 9, 3],
  116. 'dims': [96, 192, 384, 768]
  117. },
  118. 'small': {
  119. 'depths': [3, 3, 27, 3],
  120. 'dims': [96, 192, 384, 768]
  121. },
  122. 'base': {
  123. 'depths': [3, 3, 27, 3],
  124. 'dims': [128, 256, 512, 1024]
  125. },
  126. 'large': {
  127. 'depths': [3, 3, 27, 3],
  128. 'dims': [192, 384, 768, 1536]
  129. },
  130. 'xlarge': {
  131. 'depths': [3, 3, 27, 3],
  132. 'dims': [256, 512, 1024, 2048]
  133. },
  134. }
  135. def __init__(
  136. self,
  137. arch='tiny',
  138. in_chans=3,
  139. drop_path_rate=0.,
  140. layer_scale_init_value=1e-6,
  141. return_idx=[1, 2, 3],
  142. norm_output=True,
  143. pretrained=None, ):
  144. super().__init__()
  145. depths = self.arch_settings[arch]['depths']
  146. dims = self.arch_settings[arch]['dims']
  147. self.downsample_layers = nn.LayerList(
  148. ) # stem and 3 intermediate downsampling conv layers
  149. stem = nn.Sequential(
  150. nn.Conv2D(
  151. in_chans, dims[0], kernel_size=4, stride=4),
  152. LayerNorm(
  153. dims[0], eps=1e-6, data_format="channels_first"))
  154. self.downsample_layers.append(stem)
  155. for i in range(3):
  156. downsample_layer = nn.Sequential(
  157. LayerNorm(
  158. dims[i], eps=1e-6, data_format="channels_first"),
  159. nn.Conv2D(
  160. dims[i], dims[i + 1], kernel_size=2, stride=2), )
  161. self.downsample_layers.append(downsample_layer)
  162. self.stages = nn.LayerList(
  163. ) # 4 feature resolution stages, each consisting of multiple residual blocks
  164. dp_rates = [x for x in np.linspace(0, drop_path_rate, sum(depths))]
  165. cur = 0
  166. for i in range(4):
  167. stage = nn.Sequential(* [
  168. Block(
  169. dim=dims[i],
  170. drop_path=dp_rates[cur + j],
  171. layer_scale_init_value=layer_scale_init_value)
  172. for j in range(depths[i])
  173. ])
  174. self.stages.append(stage)
  175. cur += depths[i]
  176. self.return_idx = return_idx
  177. self.dims = [dims[i] for i in return_idx] # [::-1]
  178. self.norm_output = norm_output
  179. if norm_output:
  180. self.norms = nn.LayerList([
  181. LayerNorm(
  182. c, eps=1e-6, data_format="channels_first")
  183. for c in self.dims
  184. ])
  185. self.apply(self._init_weights)
  186. if pretrained is not None:
  187. if 'http' in pretrained: #URL
  188. path = paddle.utils.download.get_weights_path_from_url(
  189. pretrained)
  190. else: #model in local path
  191. path = pretrained
  192. self.set_state_dict(paddle.load(path))
  193. def _init_weights(self, m):
  194. if isinstance(m, (nn.Conv2D, nn.Linear)):
  195. trunc_normal_(m.weight)
  196. zeros_(m.bias)
  197. def forward_features(self, x):
  198. output = []
  199. for i in range(4):
  200. x = self.downsample_layers[i](x)
  201. x = self.stages[i](x)
  202. output.append(x)
  203. outputs = [output[i] for i in self.return_idx]
  204. if self.norm_output:
  205. outputs = [self.norms[i](out) for i, out in enumerate(outputs)]
  206. return outputs
  207. def forward(self, x):
  208. x = self.forward_features(x['image'])
  209. return x
  210. @property
  211. def out_shape(self):
  212. return [ShapeSpec(channels=c) for c in self.dims]