conv.py 5.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144
  1. import torch
  2. import torch.nn as nn
  3. # ----------------- Basic CNN Ops -----------------
  4. def get_conv2d(c1, c2, k, p, s, g, bias=False):
  5. conv = nn.Conv2d(c1, c2, k, stride=s, padding=p, groups=g, bias=bias)
  6. return conv
  7. def get_activation(act_type=None):
  8. if act_type == 'relu':
  9. return nn.ReLU(inplace=True)
  10. elif act_type == 'lrelu':
  11. return nn.LeakyReLU(0.1, inplace=True)
  12. elif act_type == 'mish':
  13. return nn.Mish(inplace=True)
  14. elif act_type == 'silu':
  15. return nn.SiLU(inplace=True)
  16. elif act_type == 'gelu':
  17. return nn.GELU()
  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. # ----------------- CNN Modules -----------------
  47. class BasicConv(nn.Module):
  48. def __init__(self,
  49. in_dim, # in channels
  50. out_dim, # out channels
  51. kernel_size=1, # kernel size
  52. padding=0, # padding
  53. stride=1, # padding
  54. act_type :str = 'lrelu', # activation
  55. norm_type :str = 'BN', # normalization
  56. depthwise :bool = False
  57. ):
  58. super(BasicConv, self).__init__()
  59. add_bias = False if norm_type else True
  60. self.depthwise = depthwise
  61. if not depthwise:
  62. self.conv = get_conv2d(in_dim, out_dim, k=kernel_size, p=padding, s=stride, g=1, bias=add_bias)
  63. self.norm = get_norm(norm_type, out_dim)
  64. else:
  65. self.conv1 = get_conv2d(in_dim, in_dim, k=kernel_size, p=padding, s=stride, g=1, bias=add_bias)
  66. self.norm1 = get_norm(norm_type, in_dim)
  67. self.conv2 = get_conv2d(in_dim, out_dim, k=kernel_size, p=padding, s=stride, g=1, bias=add_bias)
  68. self.norm2 = get_norm(norm_type, out_dim)
  69. self.act = get_activation(act_type)
  70. def forward(self, x):
  71. if not self.depthwise:
  72. return self.act(self.norm(self.conv(x)))
  73. else:
  74. # Depthwise conv
  75. x = self.norm1(self.conv1(x))
  76. # Pointwise conv
  77. x = self.act(self.norm2(self.conv2(x)))
  78. return x
  79. class Bottleneck(nn.Module):
  80. def __init__(self,
  81. in_dim,
  82. out_dim,
  83. expand_ratio = 0.5,
  84. kernel_sizes = [3, 3],
  85. shortcut = True,
  86. act_type = 'silu',
  87. norm_type = 'BN',
  88. depthwise = False,):
  89. super(Bottleneck, self).__init__()
  90. inter_dim = int(out_dim * expand_ratio)
  91. paddings = [k // 2 for k in kernel_sizes]
  92. self.cv1 = BasicConv(in_dim, inter_dim,
  93. kernel_size=kernel_sizes[0], padding=paddings[0],
  94. act_type=act_type, norm_type=norm_type, depthwise=depthwise)
  95. self.cv2 = BasicConv(inter_dim, out_dim,
  96. kernel_size=kernel_sizes[1], padding=paddings[1],
  97. act_type=act_type, norm_type=norm_type, depthwise=depthwise)
  98. self.shortcut = shortcut and in_dim == out_dim
  99. def forward(self, x):
  100. h = self.cv2(self.cv1(x))
  101. return x + h if self.shortcut else h
  102. class ELANLayer(nn.Module):
  103. def __init__(self,
  104. in_dim :int,
  105. out_dim :int,
  106. num_blocks :int = 1,
  107. expand_ratio :float = 0.5,
  108. shortcut :bool = False,
  109. act_type :str = 'silu',
  110. norm_type :str = 'BN',
  111. depthwise :bool = False,):
  112. super(ELANLayer, self).__init__()
  113. self.inter_dim = round(out_dim * expand_ratio)
  114. self.conv1 = BasicConv(in_dim, self.inter_dim, kernel_size=1, act_type=act_type, norm_type=norm_type)
  115. self.conv2 = BasicConv(in_dim, self.inter_dim, kernel_size=1, act_type=act_type, norm_type=norm_type)
  116. self.cmodules = nn.ModuleList([Bottleneck(self.inter_dim, self.inter_dim,
  117. 1.0, [3, 3], shortcut,
  118. act_type, norm_type, depthwise)
  119. for _ in range(num_blocks)])
  120. self.conv3 = BasicConv(self.inter_dim * (2 + num_blocks), out_dim, kernel_size=1, act_type=act_type, norm_type=norm_type)
  121. def forward(self, x):
  122. x1, x2 = self.conv1(x), self.conv2(x)
  123. out = [x1, x2]
  124. for m in self.cmodules:
  125. x2 = m(x2)
  126. out.append(x2)
  127. return self.conv3(torch.cat(out, dim=1))