basic.py 6.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195
  1. import torch
  2. import torch.nn as nn
  3. from torch import Tensor
  4. from typing import List, Optional, Callable
  5. # ----------------- CNN modules -----------------
  6. def get_conv2d(c1, c2, k, p, s, d, g, bias=False):
  7. conv = nn.Conv2d(c1, c2, k, stride=s, padding=p, dilation=d, groups=g, bias=bias)
  8. return conv
  9. def get_activation(act_type=None):
  10. if act_type == 'relu':
  11. return nn.ReLU(inplace=True)
  12. elif act_type == 'lrelu':
  13. return nn.LeakyReLU(0.1, inplace=True)
  14. elif act_type == 'mish':
  15. return nn.Mish(inplace=True)
  16. elif act_type == 'silu':
  17. return nn.SiLU(inplace=True)
  18. elif act_type is None:
  19. return nn.Identity()
  20. else:
  21. raise NotImplementedError
  22. def get_norm(norm_type, dim):
  23. if norm_type == 'BN':
  24. return nn.BatchNorm2d(dim)
  25. elif norm_type == 'GN':
  26. return nn.GroupNorm(num_groups=32, num_channels=dim)
  27. elif norm_type is None:
  28. return nn.Identity()
  29. else:
  30. raise NotImplementedError
  31. def conv3x3(in_planes: int, out_planes: int, stride: int = 1, groups: int = 1, dilation: int = 1) -> nn.Conv2d:
  32. """3x3 convolution with padding"""
  33. return nn.Conv2d(
  34. in_planes,
  35. out_planes,
  36. kernel_size=3,
  37. stride=stride,
  38. padding=dilation,
  39. groups=groups,
  40. bias=False,
  41. dilation=dilation,
  42. )
  43. def conv1x1(in_planes: int, out_planes: int, stride: int = 1) -> nn.Conv2d:
  44. """1x1 convolution"""
  45. return nn.Conv2d(in_planes, out_planes, kernel_size=1, stride=stride, bias=False)
  46. class Conv(nn.Module):
  47. def __init__(self,
  48. c1, # in channels
  49. c2, # out channels
  50. k=1, # kernel size
  51. p=0, # padding
  52. s=1, # padding
  53. d=1, # dilation
  54. act_type :str = 'lrelu', # activation
  55. norm_type :str ='BN', # normalization
  56. depthwise :bool =False):
  57. super(Conv, self).__init__()
  58. convs = []
  59. add_bias = False if norm_type else True
  60. if depthwise:
  61. convs.append(get_conv2d(c1, c1, k=k, p=p, s=s, d=d, g=c1, bias=add_bias))
  62. # depthwise conv
  63. if norm_type:
  64. convs.append(get_norm(norm_type, c1))
  65. if act_type:
  66. convs.append(get_activation(act_type))
  67. # pointwise conv
  68. convs.append(get_conv2d(c1, c2, k=1, p=0, s=1, d=d, g=1, bias=add_bias))
  69. if norm_type:
  70. convs.append(get_norm(norm_type, c2))
  71. if act_type:
  72. convs.append(get_activation(act_type))
  73. else:
  74. convs.append(get_conv2d(c1, c2, k=k, p=p, s=s, d=d, g=1, bias=add_bias))
  75. if norm_type:
  76. convs.append(get_norm(norm_type, c2))
  77. if act_type:
  78. convs.append(get_activation(act_type))
  79. self.convs = nn.Sequential(*convs)
  80. def forward(self, x):
  81. return self.convs(x)
  82. class BasicBlock(nn.Module):
  83. expansion: int = 1
  84. def __init__(
  85. self,
  86. inplanes: int,
  87. planes: int,
  88. stride: int = 1,
  89. downsample: Optional[nn.Module] = None,
  90. groups: int = 1,
  91. base_width: int = 64,
  92. dilation: int = 1,
  93. norm_layer: Optional[Callable[..., nn.Module]] = None,
  94. ) -> None:
  95. super().__init__()
  96. if norm_layer is None:
  97. norm_layer = nn.BatchNorm2d
  98. if groups != 1 or base_width != 64:
  99. raise ValueError("BasicBlock only supports groups=1 and base_width=64")
  100. if dilation > 1:
  101. raise NotImplementedError("Dilation > 1 not supported in BasicBlock")
  102. # Both self.conv1 and self.downsample layers downsample the input when stride != 1
  103. self.conv1 = conv3x3(inplanes, planes, stride)
  104. self.bn1 = norm_layer(planes)
  105. self.relu = nn.ReLU(inplace=True)
  106. self.conv2 = conv3x3(planes, planes)
  107. self.bn2 = norm_layer(planes)
  108. self.downsample = downsample
  109. self.stride = stride
  110. def forward(self, x: Tensor) -> Tensor:
  111. identity = x
  112. out = self.conv1(x)
  113. out = self.bn1(out)
  114. out = self.relu(out)
  115. out = self.conv2(out)
  116. out = self.bn2(out)
  117. if self.downsample is not None:
  118. identity = self.downsample(x)
  119. out += identity
  120. out = self.relu(out)
  121. return out
  122. class Bottleneck(nn.Module):
  123. expansion: int = 4
  124. def __init__(
  125. self,
  126. inplanes: int,
  127. planes: int,
  128. stride: int = 1,
  129. downsample: Optional[nn.Module] = None,
  130. groups: int = 1,
  131. base_width: int = 64,
  132. dilation: int = 1,
  133. norm_layer: Optional[Callable[..., nn.Module]] = None,
  134. ) -> None:
  135. super().__init__()
  136. if norm_layer is None:
  137. norm_layer = nn.BatchNorm2d
  138. width = int(planes * (base_width / 64.0)) * groups
  139. # Both self.conv2 and self.downsample layers downsample the input when stride != 1
  140. self.conv1 = conv1x1(inplanes, width)
  141. self.bn1 = norm_layer(width)
  142. self.conv2 = conv3x3(width, width, stride, groups, dilation)
  143. self.bn2 = norm_layer(width)
  144. self.conv3 = conv1x1(width, planes * self.expansion)
  145. self.bn3 = norm_layer(planes * self.expansion)
  146. self.relu = nn.ReLU(inplace=True)
  147. self.downsample = downsample
  148. self.stride = stride
  149. def forward(self, x: Tensor) -> Tensor:
  150. identity = x
  151. out = self.conv1(x)
  152. out = self.bn1(out)
  153. out = self.relu(out)
  154. out = self.conv2(out)
  155. out = self.bn2(out)
  156. out = self.relu(out)
  157. out = self.conv3(out)
  158. out = self.bn3(out)
  159. if self.downsample is not None:
  160. identity = self.downsample(x)
  161. out += identity
  162. out = self.relu(out)
  163. return out
  164. # ----------------- Transformer modules -----------------