lodet_basic.py 6.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192
  1. import numpy as np
  2. import torch
  3. import torch.nn as nn
  4. # ---------------------------- 2D CNN ----------------------------
  5. class SiLU(nn.Module):
  6. """export-friendly version of nn.SiLU()"""
  7. @staticmethod
  8. def forward(x):
  9. return x * torch.sigmoid(x)
  10. def get_conv2d(c1, c2, k, p, s, d, g, bias=False):
  11. conv = nn.Conv2d(c1, c2, k, stride=s, padding=p, dilation=d, groups=g, bias=bias)
  12. return conv
  13. def get_activation(act_type=None):
  14. if act_type == 'relu':
  15. return nn.ReLU(inplace=True)
  16. elif act_type == 'lrelu':
  17. return nn.LeakyReLU(0.1, inplace=True)
  18. elif act_type == 'mish':
  19. return nn.Mish(inplace=True)
  20. elif act_type == 'silu':
  21. return nn.SiLU(inplace=True)
  22. elif act_type is None:
  23. return nn.Identity()
  24. def get_norm(norm_type, dim):
  25. if norm_type == 'BN':
  26. return nn.BatchNorm2d(dim)
  27. elif norm_type == 'GN':
  28. return nn.GroupNorm(num_groups=32, num_channels=dim)
  29. # Basic conv layer
  30. class Conv(nn.Module):
  31. def __init__(self,
  32. c1, # in channels
  33. c2, # out channels
  34. k=1, # kernel size
  35. p=0, # padding
  36. s=1, # padding
  37. d=1, # dilation
  38. act_type='lrelu', # activation
  39. norm_type='BN', # normalization
  40. depthwise=False):
  41. super(Conv, self).__init__()
  42. convs = []
  43. add_bias = False if norm_type else True
  44. p = p if d == 1 else d
  45. if depthwise:
  46. convs.append(get_conv2d(c1, c1, k=k, p=p, s=s, d=d, g=c1, bias=add_bias))
  47. # depthwise conv
  48. if norm_type:
  49. convs.append(get_norm(norm_type, c1))
  50. if act_type:
  51. convs.append(get_activation(act_type))
  52. # pointwise conv
  53. convs.append(get_conv2d(c1, c2, k=1, p=0, s=1, d=d, g=1, bias=add_bias))
  54. if norm_type:
  55. convs.append(get_norm(norm_type, c2))
  56. if act_type:
  57. convs.append(get_activation(act_type))
  58. else:
  59. convs.append(get_conv2d(c1, c2, k=k, p=p, s=s, d=d, g=1, bias=add_bias))
  60. if norm_type:
  61. convs.append(get_norm(norm_type, c2))
  62. if act_type:
  63. convs.append(get_activation(act_type))
  64. self.convs = nn.Sequential(*convs)
  65. def forward(self, x):
  66. return self.convs(x)
  67. # ---------------------------- Core Modules ----------------------------
  68. ## Scale Modulation Block
  69. class SMBlock(nn.Module):
  70. def __init__(self, in_dim, out_dim, act_type='silu', norm_type='BN', depthwise=False):
  71. super(SMBlock, self).__init__()
  72. # -------------- Basic parameters --------------
  73. self.in_dim = in_dim
  74. self.out_dim = out_dim
  75. self.inter_dim = in_dim // 2
  76. # -------------- Network parameters --------------
  77. self.cv1 = Conv(self.inter_dim, self.inter_dim, k=1, act_type=act_type, norm_type=norm_type)
  78. self.cv2 = Conv(self.inter_dim, self.inter_dim, k=1, act_type=act_type, norm_type=norm_type)
  79. ## Scale Modulation
  80. self.sm1 = nn.Sequential(
  81. Conv(self.inter_dim, self.inter_dim, k=1, act_type=act_type, norm_type=norm_type),
  82. Conv(self.inter_dim, self.inter_dim, k=3, p=1, act_type=act_type, norm_type=norm_type, depthwise=depthwise)
  83. )
  84. self.sm2 = nn.Sequential(
  85. Conv(self.inter_dim, self.inter_dim, k=1, act_type=act_type, norm_type=norm_type),
  86. Conv(self.inter_dim, self.inter_dim, k=5, p=2, act_type=act_type, norm_type=norm_type, depthwise=depthwise)
  87. )
  88. self.sm3 = nn.Sequential(
  89. Conv(self.inter_dim, self.inter_dim, k=1, act_type=act_type, norm_type=norm_type),
  90. Conv(self.inter_dim, self.inter_dim, k=7, p=3, act_type=act_type, norm_type=norm_type, depthwise=depthwise)
  91. )
  92. ## Output proj
  93. self.out_proj = Conv(self.inter_dim*4, self.out_dim, k=1, act_type=act_type, norm_type=norm_type)
  94. def channel_shuffle(self, x, groups):
  95. # type: (torch.Tensor, int) -> torch.Tensor
  96. batchsize, num_channels, height, width = x.data.size()
  97. per_group_dim = num_channels // groups
  98. # reshape
  99. x = x.view(batchsize, groups, per_group_dim, height, width)
  100. x = torch.transpose(x, 1, 2).contiguous()
  101. # flatten
  102. x = x.view(batchsize, -1, height, width)
  103. return x
  104. def forward(self, x):
  105. x1, x2 = torch.chunk(x, 2, dim=1)
  106. x1 = self.cv1(x1)
  107. x2 = self.cv2(x2)
  108. x3 = self.sm1(x2)
  109. x4 = self.sm2(x3)
  110. x5 = self.sm3(x4)
  111. out = self.out_proj(torch.cat([x1, x3, x4, x5], dim=1))
  112. out = self.channel_shuffle(out, groups=4)
  113. return out
  114. ## DownSample Block
  115. class DSBlock(nn.Module):
  116. def __init__(self, in_dim, out_dim, act_type='silu', norm_type='BN', depthwise=False):
  117. super().__init__()
  118. self.maxpool = nn.MaxPool2d((2, 2), 2)
  119. self.conv = Conv(in_dim//2, in_dim//2, k=3, p=1, s=2, act_type=act_type, norm_type=norm_type, depthwise=depthwise)
  120. self.out_proj = Conv(in_dim, out_dim, k=1, act_type=act_type, norm_type=norm_type)
  121. def forward(self, x):
  122. x1, x2 = torch.chunk(x, 2, dim=1)
  123. x1 = self.maxpool(x1)
  124. x2 = self.conv(x2)
  125. out = torch.cat([x1, x2], dim=1)
  126. out = self.out_proj(out)
  127. return out
  128. # ---------------------------- FPN Modules ----------------------------
  129. ## build fpn's core block
  130. def build_fpn_block(cfg, in_dim, out_dim):
  131. if cfg['fpn_core_block'] == 'smblock':
  132. layer = SMBlock(in_dim=in_dim,
  133. out_dim=out_dim,
  134. act_type=cfg['fpn_act'],
  135. norm_type=cfg['fpn_norm'],
  136. depthwise=cfg['fpn_depthwise']
  137. )
  138. return layer
  139. ## build fpn's reduce layer
  140. def build_reduce_layer(cfg, in_dim, out_dim):
  141. if cfg['fpn_reduce_layer'] == 'conv':
  142. layer = Conv(in_dim, out_dim, k=1, act_type=cfg['fpn_act'], norm_type=cfg['fpn_norm'])
  143. return layer
  144. ## build fpn's downsample layer
  145. def build_downsample_layer(cfg, in_dim, out_dim):
  146. if cfg['fpn_downsample_layer'] == 'conv':
  147. layer = Conv(in_dim, out_dim, k=3, s=2, p=1, act_type=cfg['fpn_act'], norm_type=cfg['fpn_norm'])
  148. elif cfg['fpn_downsample_layer'] == 'maxpool':
  149. assert in_dim == out_dim
  150. layer = nn.MaxPool2d((2, 2), stride=2)
  151. elif cfg['fpn_downsample_layer'] == 'dsblock':
  152. layer = DSBlock(in_dim, out_dim, act_type=cfg['fpn_act'], norm_type=cfg['fpn_norm'], depthwise=cfg['fpn_depthwise'])
  153. return layer