convnext.py 8.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249
  1. from functools import partial
  2. from typing import Optional
  3. import torch
  4. import torch.nn.functional as F
  5. from torch import nn
  6. def drop_path(
  7. x, drop_prob: float = 0.0, training: bool = False, scale_by_keep: bool = True
  8. ):
  9. """Drop paths (Stochastic Depth) per sample (when applied in main path of residual blocks).
  10. This is the same as the DropConnect impl I created for EfficientNet, etc networks, however,
  11. the original name is misleading as 'Drop Connect' is a different form of dropout in a separate paper...
  12. See discussion: https://github.com/tensorflow/tpu/issues/494#issuecomment-532968956 ... I've opted for
  13. changing the layer and argument names to 'drop path' rather than mix DropConnect as a layer name and use
  14. 'survival rate' as the argument.
  15. """ # noqa: E501
  16. if drop_prob == 0.0 or not training:
  17. return x
  18. keep_prob = 1 - drop_prob
  19. shape = (x.shape[0],) + (1,) * (
  20. x.ndim - 1
  21. ) # work with diff dim tensors, not just 2D ConvNets
  22. random_tensor = x.new_empty(shape).bernoulli_(keep_prob)
  23. if keep_prob > 0.0 and scale_by_keep:
  24. random_tensor.div_(keep_prob)
  25. return x * random_tensor
  26. class DropPath(nn.Module):
  27. """Drop paths (Stochastic Depth) per sample (when applied in main path of residual blocks).""" # noqa: E501
  28. def __init__(self, drop_prob: float = 0.0, scale_by_keep: bool = True):
  29. super(DropPath, self).__init__()
  30. self.drop_prob = drop_prob
  31. self.scale_by_keep = scale_by_keep
  32. def forward(self, x):
  33. return drop_path(x, self.drop_prob, self.training, self.scale_by_keep)
  34. def extra_repr(self):
  35. return f"drop_prob={round(self.drop_prob,3):0.3f}"
  36. class LayerNorm(nn.Module):
  37. r"""LayerNorm that supports two data formats: channels_last (default) or channels_first.
  38. The ordering of the dimensions in the inputs. channels_last corresponds to inputs with
  39. shape (batch_size, height, width, channels) while channels_first corresponds to inputs
  40. with shape (batch_size, channels, height, width).
  41. """ # noqa: E501
  42. def __init__(self, normalized_shape, eps=1e-6, data_format="channels_last"):
  43. super().__init__()
  44. self.weight = nn.Parameter(torch.ones(normalized_shape))
  45. self.bias = nn.Parameter(torch.zeros(normalized_shape))
  46. self.eps = eps
  47. self.data_format = data_format
  48. if self.data_format not in ["channels_last", "channels_first"]:
  49. raise NotImplementedError
  50. self.normalized_shape = (normalized_shape,)
  51. def forward(self, x):
  52. if self.data_format == "channels_last":
  53. return F.layer_norm(
  54. x, self.normalized_shape, self.weight, self.bias, self.eps
  55. )
  56. elif self.data_format == "channels_first":
  57. u = x.mean(1, keepdim=True)
  58. s = (x - u).pow(2).mean(1, keepdim=True)
  59. x = (x - u) / torch.sqrt(s + self.eps)
  60. x = self.weight[:, None] * x + self.bias[:, None]
  61. return x
  62. class ConvNeXtBlock(nn.Module):
  63. r"""ConvNeXt Block. There are two equivalent implementations:
  64. (1) DwConv -> LayerNorm (channels_first) -> 1x1 Conv -> GELU -> 1x1 Conv; all in (N, C, H, W)
  65. (2) DwConv -> Permute to (N, H, W, C); LayerNorm (channels_last) -> Linear -> GELU -> Linear; Permute back
  66. We use (2) as we find it slightly faster in PyTorch
  67. Args:
  68. dim (int): Number of input channels.
  69. drop_path (float): Stochastic depth rate. Default: 0.0
  70. layer_scale_init_value (float): Init value for Layer Scale. Default: 1e-6.
  71. mlp_ratio (float): Ratio of mlp hidden dim to embedding dim. Default: 4.0.
  72. kernel_size (int): Kernel size for depthwise conv. Default: 7.
  73. dilation (int): Dilation for depthwise conv. Default: 1.
  74. """ # noqa: E501
  75. def __init__(
  76. self,
  77. dim: int,
  78. drop_path: float = 0.0,
  79. layer_scale_init_value: float = 1e-6,
  80. mlp_ratio: float = 4.0,
  81. kernel_size: int = 7,
  82. dilation: int = 1,
  83. ):
  84. super().__init__()
  85. self.dwconv = nn.Conv1d(
  86. dim,
  87. dim,
  88. kernel_size=kernel_size,
  89. padding=int(dilation * (kernel_size - 1) / 2),
  90. groups=dim,
  91. ) # depthwise conv
  92. self.norm = LayerNorm(dim, eps=1e-6)
  93. self.pwconv1 = nn.Linear(
  94. dim, int(mlp_ratio * dim)
  95. ) # pointwise/1x1 convs, implemented with linear layers
  96. self.act = nn.GELU()
  97. self.pwconv2 = nn.Linear(int(mlp_ratio * dim), dim)
  98. self.gamma = (
  99. nn.Parameter(layer_scale_init_value * torch.ones((dim)), requires_grad=True)
  100. if layer_scale_init_value > 0
  101. else None
  102. )
  103. self.drop_path = DropPath(drop_path) if drop_path > 0.0 else nn.Identity()
  104. def forward(self, x, apply_residual: bool = True):
  105. input = x
  106. x = self.dwconv(x)
  107. x = x.permute(0, 2, 1) # (N, C, L) -> (N, L, C)
  108. x = self.norm(x)
  109. x = self.pwconv1(x)
  110. x = self.act(x)
  111. x = self.pwconv2(x)
  112. if self.gamma is not None:
  113. x = self.gamma * x
  114. x = x.permute(0, 2, 1) # (N, L, C) -> (N, C, L)
  115. x = self.drop_path(x)
  116. if apply_residual:
  117. x = input + x
  118. return x
  119. class ParallelConvNeXtBlock(nn.Module):
  120. def __init__(self, kernel_sizes: list[int], *args, **kwargs):
  121. super().__init__()
  122. self.blocks = nn.ModuleList(
  123. [
  124. ConvNeXtBlock(kernel_size=kernel_size, *args, **kwargs)
  125. for kernel_size in kernel_sizes
  126. ]
  127. )
  128. def forward(self, x: torch.Tensor) -> torch.Tensor:
  129. return torch.stack(
  130. [block(x, apply_residual=False) for block in self.blocks] + [x],
  131. dim=1,
  132. ).sum(dim=1)
  133. class ConvNeXtEncoder(nn.Module):
  134. def __init__(
  135. self,
  136. input_channels: int = 3,
  137. output_channels: Optional[int] = None,
  138. depths: list[int] = [3, 3, 9, 3],
  139. dims: list[int] = [96, 192, 384, 768],
  140. drop_path_rate: float = 0.0,
  141. layer_scale_init_value: float = 1e-6,
  142. kernel_sizes: tuple[int] = (7,),
  143. ):
  144. super().__init__()
  145. assert len(depths) == len(dims)
  146. self.channel_layers = nn.ModuleList()
  147. stem = nn.Sequential(
  148. nn.Conv1d(
  149. input_channels,
  150. dims[0],
  151. kernel_size=7,
  152. padding=3,
  153. padding_mode="zeros",
  154. ),
  155. LayerNorm(dims[0], eps=1e-6, data_format="channels_first"),
  156. )
  157. self.channel_layers.append(stem)
  158. for i in range(len(depths) - 1):
  159. mid_layer = nn.Sequential(
  160. LayerNorm(dims[i], eps=1e-6, data_format="channels_first"),
  161. nn.Conv1d(dims[i], dims[i + 1], kernel_size=1),
  162. )
  163. self.channel_layers.append(mid_layer)
  164. block_fn = (
  165. partial(ConvNeXtBlock, kernel_size=kernel_sizes[0])
  166. if len(kernel_sizes) == 1
  167. else partial(ParallelConvNeXtBlock, kernel_sizes=kernel_sizes)
  168. )
  169. self.stages = nn.ModuleList()
  170. drop_path_rates = [
  171. x.item() for x in torch.linspace(0, drop_path_rate, sum(depths))
  172. ]
  173. cur = 0
  174. for i in range(len(depths)):
  175. stage = nn.Sequential(
  176. *[
  177. block_fn(
  178. dim=dims[i],
  179. drop_path=drop_path_rates[cur + j],
  180. layer_scale_init_value=layer_scale_init_value,
  181. )
  182. for j in range(depths[i])
  183. ]
  184. )
  185. self.stages.append(stage)
  186. cur += depths[i]
  187. self.norm = LayerNorm(dims[-1], eps=1e-6, data_format="channels_first")
  188. if output_channels is not None:
  189. self.output_projection = nn.Conv1d(dims[-1], output_channels, kernel_size=1)
  190. self.apply(self._init_weights)
  191. def _init_weights(self, m):
  192. if isinstance(m, (nn.Conv1d, nn.Linear)):
  193. nn.init.trunc_normal_(m.weight, std=0.02)
  194. nn.init.constant_(m.bias, 0)
  195. def forward(
  196. self,
  197. x: torch.Tensor,
  198. ) -> torch.Tensor:
  199. for channel_layer, stage in zip(self.channel_layers, self.stages):
  200. x = channel_layer(x)
  201. x = stage(x)
  202. x = self.norm(x)
  203. if hasattr(self, "output_projection"):
  204. x = self.output_projection(x)
  205. return x