rtcdet_v2_neck.py 2.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263
  1. import torch
  2. import torch.nn as nn
  3. from .rtcdet_v2_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.spp = SPPF(cfg, inter_dim, inter_dim, expand_ratio=1.0)
  33. self.cv3 = Conv(inter_dim * 2, self.out_dim, k=1, act_type=cfg['neck_act'], norm_type=cfg['neck_norm'])
  34. def forward(self, x):
  35. x1 = self.cv1(x)
  36. x2 = self.cv2(x)
  37. x3 = self.spp(x2)
  38. y = self.cv3(torch.cat([x1, x3], dim=1))
  39. return y
  40. # build neck
  41. def build_neck(cfg, in_dim, out_dim):
  42. model = cfg['neck']
  43. print('==============================')
  44. print('Neck: {}'.format(model))
  45. # build neck
  46. if model == 'sppf':
  47. neck = SPPF(cfg, in_dim, out_dim, cfg['neck_expand_ratio'])
  48. elif model == 'csp_sppf':
  49. neck = SPPFBlockCSP(cfg, in_dim, out_dim, cfg['neck_expand_ratio'])
  50. return neck