cnn_basic.py 6.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174
  1. import torch
  2. import torch.nn as nn
  3. # ------------------------------- Basic Modules -------------------------------
  4. class SiLU(nn.Module):
  5. """export-friendly version of nn.SiLU()"""
  6. @staticmethod
  7. def forward(x):
  8. return x * torch.sigmoid(x)
  9. def get_conv2d(c1, c2, k, p, s, d, g, bias=False):
  10. conv = nn.Conv2d(c1, c2, k, stride=s, padding=p, dilation=d, groups=g, bias=bias)
  11. return conv
  12. def get_activation(act_type=None):
  13. if act_type == 'relu':
  14. return nn.ReLU(inplace=True)
  15. elif act_type == 'gelu':
  16. return nn.GELU()
  17. elif act_type == 'lrelu':
  18. return nn.LeakyReLU(0.1, inplace=True)
  19. elif act_type == 'mish':
  20. return nn.Mish(inplace=True)
  21. elif act_type == 'silu':
  22. return nn.SiLU(inplace=True)
  23. def get_norm(norm_type, dim):
  24. if norm_type == 'BN':
  25. return nn.BatchNorm2d(dim)
  26. elif norm_type == 'GN':
  27. return nn.GroupNorm(num_groups=32, num_channels=dim)
  28. elif norm_type == 'LN':
  29. return nn.LayerNorm(dim)
  30. # ------------------------------- Conv -------------------------------
  31. class Conv(nn.Module):
  32. def __init__(self,
  33. c1, # in channels
  34. c2, # out channels
  35. k=1, # kernel size
  36. p=0, # padding
  37. s=1, # padding
  38. d=1, # dilation
  39. act_type='relu', # activation
  40. norm_type='BN', # normalization
  41. depthwise=False):
  42. super(Conv, self).__init__()
  43. convs = []
  44. add_bias = False if norm_type else True
  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. # ---------------------------- Modified YOLOv7's Modules ----------------------------
  68. ## ELANBlock
  69. class ELANBlock(nn.Module):
  70. def __init__(self, in_dim, out_dim, expand_ratio=0.5, depth=1.0, act_type='silu', norm_type='BN', depthwise=False):
  71. super(ELANBlock, self).__init__()
  72. if isinstance(expand_ratio, float):
  73. inter_dim = int(in_dim * expand_ratio)
  74. inter_dim2 = inter_dim
  75. elif isinstance(expand_ratio, list):
  76. assert len(expand_ratio) == 2
  77. e1, e2 = expand_ratio
  78. inter_dim = int(in_dim * e1)
  79. inter_dim2 = int(inter_dim * e2)
  80. # branch-1
  81. self.cv1 = Conv(in_dim, inter_dim, k=1, act_type=act_type, norm_type=norm_type)
  82. # branch-2
  83. self.cv2 = Conv(in_dim, inter_dim, k=1, act_type=act_type, norm_type=norm_type)
  84. # branch-3
  85. for idx in range(round(3*depth)):
  86. if idx == 0:
  87. cv3 = [Conv(inter_dim, inter_dim2, k=3, p=1, act_type=act_type, norm_type=norm_type, depthwise=depthwise)]
  88. else:
  89. cv3.append(Conv(inter_dim2, inter_dim2, k=3, p=1, act_type=act_type, norm_type=norm_type, depthwise=depthwise))
  90. self.cv3 = nn.Sequential(*cv3)
  91. # branch-4
  92. self.cv4 = nn.Sequential(*[
  93. Conv(inter_dim2, inter_dim2, k=3, p=1, act_type=act_type, norm_type=norm_type, depthwise=depthwise)
  94. for _ in range(round(3*depth))
  95. ])
  96. # output
  97. self.out = Conv(inter_dim*2 + inter_dim2*2, out_dim, k=1, act_type=act_type, norm_type=norm_type)
  98. def forward(self, x):
  99. x1 = self.cv1(x)
  100. x2 = self.cv2(x)
  101. x3 = self.cv3(x2)
  102. x4 = self.cv4(x3)
  103. out = self.out(torch.cat([x1, x2, x3, x4], dim=1))
  104. return out
  105. ## DownSample
  106. class DownSample(nn.Module):
  107. def __init__(self, in_dim, out_dim, act_type='silu', norm_type='BN', depthwise=False):
  108. super().__init__()
  109. inter_dim = out_dim // 2
  110. self.mp = nn.MaxPool2d((2, 2), 2)
  111. self.cv1 = Conv(in_dim, inter_dim, k=1, act_type=act_type, norm_type=norm_type)
  112. self.cv2 = nn.Sequential(
  113. Conv(in_dim, inter_dim, k=1, act_type=act_type, norm_type=norm_type),
  114. Conv(inter_dim, inter_dim, k=3, p=1, s=2, act_type=act_type, norm_type=norm_type, depthwise=depthwise)
  115. )
  116. def forward(self, x):
  117. x1 = self.cv1(self.mp(x))
  118. x2 = self.cv2(x)
  119. out = torch.cat([x1, x2], dim=1)
  120. return out
  121. ## build core block for CSFM
  122. def build_fpn_block(cfg, in_dim, out_dim):
  123. if cfg['fpn_core_block'] == 'elanblock':
  124. layer = ELANBlock(in_dim=in_dim,
  125. out_dim=out_dim,
  126. expand_ratio=[0.5, 0.5],
  127. depth=cfg['depth'],
  128. act_type=cfg['fpn_act'],
  129. norm_type=cfg['fpn_norm'],
  130. depthwise=cfg['fpn_depthwise']
  131. )
  132. return layer
  133. ## build reduce layer for CSFM
  134. def build_reduce_layer(cfg, in_dim, out_dim):
  135. layer = Conv(in_dim, out_dim, k=1,
  136. act_type=cfg['fpn_act'], norm_type=cfg['fpn_norm'])
  137. return layer
  138. ## build downsample layer for CSFM
  139. def build_downsample_layer(cfg, in_dim, out_dim):
  140. if cfg['fpn_downsample_layer'] == 'conv':
  141. layer = Conv(in_dim, out_dim, k=3, s=2, p=1,
  142. act_type=cfg['fpn_act'], norm_type=cfg['fpn_norm'])
  143. return layer