yolov5_basic.py 5.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165
  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. if depthwise:
  45. convs.append(get_conv2d(c1, c1, k=k, p=p, s=s, d=d, g=c1, bias=add_bias))
  46. # depthwise conv
  47. if norm_type:
  48. convs.append(get_norm(norm_type, c1))
  49. if act_type:
  50. convs.append(get_activation(act_type))
  51. # pointwise conv
  52. convs.append(get_conv2d(c1, c2, k=1, p=0, s=1, d=d, g=1, bias=add_bias))
  53. if norm_type:
  54. convs.append(get_norm(norm_type, c2))
  55. if act_type:
  56. convs.append(get_activation(act_type))
  57. else:
  58. convs.append(get_conv2d(c1, c2, k=k, p=p, s=s, d=d, g=1, bias=add_bias))
  59. if norm_type:
  60. convs.append(get_norm(norm_type, c2))
  61. if act_type:
  62. convs.append(get_activation(act_type))
  63. self.convs = nn.Sequential(*convs)
  64. def forward(self, x):
  65. return self.convs(x)
  66. # ---------------------------- YOLOv5 Modules ----------------------------
  67. ## BottleNeck
  68. class Bottleneck(nn.Module):
  69. def __init__(self,
  70. in_dim,
  71. out_dim,
  72. expand_ratio=0.5,
  73. shortcut=False,
  74. depthwise=False,
  75. act_type='silu',
  76. norm_type='BN'):
  77. super(Bottleneck, self).__init__()
  78. inter_dim = int(out_dim * expand_ratio) # hidden channels
  79. self.cv1 = Conv(in_dim, inter_dim, k=1, norm_type=norm_type, act_type=act_type)
  80. self.cv2 = Conv(inter_dim, out_dim, k=3, p=1, norm_type=norm_type, act_type=act_type, depthwise=depthwise)
  81. self.shortcut = shortcut and in_dim == out_dim
  82. def forward(self, x):
  83. h = self.cv2(self.cv1(x))
  84. return x + h if self.shortcut else h
  85. ## CSP-stage block
  86. class CSPBlock(nn.Module):
  87. def __init__(self,
  88. in_dim,
  89. out_dim,
  90. expand_ratio=0.5,
  91. nblocks=1,
  92. shortcut=False,
  93. depthwise=False,
  94. act_type='silu',
  95. norm_type='BN'):
  96. super(CSPBlock, self).__init__()
  97. inter_dim = int(out_dim * expand_ratio)
  98. self.cv1 = Conv(in_dim, inter_dim, k=1, norm_type=norm_type, act_type=act_type)
  99. self.cv2 = Conv(in_dim, inter_dim, k=1, norm_type=norm_type, act_type=act_type)
  100. self.cv3 = Conv(2 * inter_dim, out_dim, k=1, norm_type=norm_type, act_type=act_type)
  101. self.m = nn.Sequential(*[
  102. Bottleneck(inter_dim, inter_dim, expand_ratio=1.0, shortcut=shortcut,
  103. norm_type=norm_type, act_type=act_type, depthwise=depthwise)
  104. for _ in range(nblocks)
  105. ])
  106. def forward(self, x):
  107. x1 = self.cv1(x)
  108. x2 = self.cv2(x)
  109. x3 = self.m(x1)
  110. out = self.cv3(torch.cat([x3, x2], dim=1))
  111. return out
  112. # ---------------------------- FPN Modules ----------------------------
  113. ## build fpn's core block
  114. def build_fpn_block(cfg, in_dim, out_dim):
  115. if cfg['fpn_core_block'] == 'CSPBlock':
  116. layer = CSPBlock(in_dim=in_dim,
  117. out_dim=out_dim,
  118. expand_ratio=0.5,
  119. nblocks = round(3*cfg['depth']),
  120. shortcut = False,
  121. act_type=cfg['fpn_act'],
  122. norm_type=cfg['fpn_norm'],
  123. depthwise=cfg['fpn_depthwise']
  124. )
  125. return layer
  126. ## build fpn's reduce layer
  127. def build_reduce_layer(cfg, in_dim, out_dim):
  128. if cfg['fpn_reduce_layer'] == 'Conv':
  129. layer = Conv(in_dim, out_dim, k=1, act_type=cfg['fpn_act'], norm_type=cfg['fpn_norm'])
  130. return layer
  131. ## build fpn's downsample layer
  132. def build_downsample_layer(cfg, in_dim, out_dim):
  133. if cfg['fpn_downsample_layer'] == 'Conv':
  134. layer = Conv(in_dim, out_dim, k=3, s=2, p=1, act_type=cfg['fpn_act'], norm_type=cfg['fpn_norm'])
  135. return layer