yolov8_neck.py 2.5 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970
  1. import torch
  2. import torch.nn as nn
  3. from .yolov8_basic import Conv
  4. # Spatial Pyramid Pooling - Fast (SPPF) layer for YOLOv5 by Glenn Jocher
  5. class SPPF(nn.Module):
  6. """
  7. This code referenced to https://github.com/ultralytics/yolov5
  8. """
  9. def __init__(self, cfg, in_dim, out_dim, expand_ratio=0.5):
  10. super().__init__()
  11. inter_dim = int(in_dim * expand_ratio)
  12. self.out_dim = out_dim
  13. self.cv1 = Conv(in_dim, inter_dim, k=1, act_type=cfg['neck_act'], norm_type=cfg['neck_norm'])
  14. self.cv2 = Conv(inter_dim * 4, out_dim, k=1, act_type=cfg['neck_act'], norm_type=cfg['neck_norm'])
  15. self.m = nn.MaxPool2d(kernel_size=cfg['pooling_size'], stride=1, padding=cfg['pooling_size'] // 2)
  16. def forward(self, x):
  17. x = self.cv1(x)
  18. y1 = self.m(x)
  19. y2 = self.m(y1)
  20. return self.cv2(torch.cat((x, y1, y2, self.m(y2)), 1))
  21. # SPPF block with CSP module
  22. class SPPFBlockCSP(nn.Module):
  23. """
  24. CSP Spatial Pyramid Pooling Block
  25. """
  26. def __init__(self, cfg, in_dim, out_dim, expand_ratio):
  27. super(SPPFBlockCSP, self).__init__()
  28. inter_dim = int(in_dim * expand_ratio)
  29. self.out_dim = out_dim
  30. self.cv1 = Conv(in_dim, inter_dim, k=1, act_type=cfg['neck_act'], norm_type=cfg['neck_norm'])
  31. self.cv2 = Conv(in_dim, inter_dim, k=1, act_type=cfg['neck_act'], norm_type=cfg['neck_norm'])
  32. self.m = nn.Sequential(
  33. Conv(inter_dim, inter_dim, k=3, p=1,
  34. act_type=cfg['neck_act'], norm_type=cfg['neck_norm'],
  35. depthwise=cfg['neck_depthwise']),
  36. SPPF(cfg, inter_dim, inter_dim, expand_ratio=1.0),
  37. Conv(inter_dim, inter_dim, k=3, p=1,
  38. act_type=cfg['neck_act'], norm_type=cfg['neck_norm'],
  39. depthwise=cfg['neck_depthwise'])
  40. )
  41. self.cv3 = Conv(inter_dim * 2, self.out_dim, k=1, act_type=cfg['neck_act'], norm_type=cfg['neck_norm'])
  42. def forward(self, x):
  43. x1 = self.cv1(x)
  44. x2 = self.cv2(x)
  45. x3 = self.m(x2)
  46. y = self.cv3(torch.cat([x1, x3], dim=1))
  47. return y
  48. def build_neck(cfg, in_dim, out_dim):
  49. model = cfg['neck']
  50. print('==============================')
  51. print('Neck: {}'.format(model))
  52. # build neck
  53. if model == 'sppf':
  54. neck = SPPF(cfg, in_dim, out_dim, cfg['neck_expand_ratio'])
  55. elif model == 'csp_sppf':
  56. neck = SPPFBlockCSP(cfg, in_dim, out_dim, cfg['neck_expand_ratio'])
  57. return neck