yolov1_neck.py 2.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384
  1. import torch
  2. import torch.nn as nn
  3. try:
  4. from .yolov1_basic import BasicConv
  5. except:
  6. from yolov1_basic import BasicConv
  7. # Spatial Pyramid Pooling - Fast (SPPF) layer for YOLOv5 by Glenn Jocher
  8. class SPPF(nn.Module):
  9. """
  10. This code referenced to https://github.com/ultralytics/yolov5
  11. """
  12. def __init__(self, cfg, in_dim, out_dim):
  13. super().__init__()
  14. ## ----------- Basic Parameters -----------
  15. inter_dim = round(in_dim * cfg.neck_expand_ratio)
  16. self.out_dim = out_dim
  17. ## ----------- Network Parameters -----------
  18. self.cv1 = BasicConv(in_dim, inter_dim,
  19. kernel_size=1, padding=0, stride=1,
  20. act_type=cfg.neck_act, norm_type=cfg.neck_norm)
  21. self.cv2 = BasicConv(inter_dim * 4, out_dim,
  22. kernel_size=1, padding=0, stride=1,
  23. act_type=cfg.neck_act, norm_type=cfg.neck_norm)
  24. self.m = nn.MaxPool2d(kernel_size=cfg.spp_pooling_size,
  25. stride=1,
  26. padding=cfg.spp_pooling_size // 2)
  27. # Initialize all layers
  28. self.init_weights()
  29. def init_weights(self):
  30. """Initialize the parameters."""
  31. for m in self.modules():
  32. if isinstance(m, torch.nn.Conv2d):
  33. # In order to be consistent with the source code,
  34. # reset the Conv2d initialization parameters
  35. m.reset_parameters()
  36. def forward(self, x):
  37. x = self.cv1(x)
  38. y1 = self.m(x)
  39. y2 = self.m(y1)
  40. return self.cv2(torch.cat((x, y1, y2, self.m(y2)), 1))
  41. if __name__=='__main__':
  42. from thop import profile
  43. # YOLOv1 configuration
  44. class Yolov1BaseConfig(object):
  45. def __init__(self) -> None:
  46. # ---------------- Model config ----------------
  47. self.out_stride = 32
  48. self.max_stride = 32
  49. ## Neck
  50. self.neck_act = 'lrelu'
  51. self.neck_norm = 'BN'
  52. self.neck_depthwise = False
  53. self.neck_expand_ratio = 0.5
  54. self.spp_pooling_size = 5
  55. cfg = Yolov1BaseConfig()
  56. # Build a neck
  57. in_dim = 512
  58. out_dim = 512
  59. model = SPPF(cfg, 512, 512)
  60. # Randomly generate a input data
  61. x = torch.randn(2, in_dim, 20, 20)
  62. # Inference
  63. output = model(x)
  64. print(' - the shape of input : ', x.shape)
  65. print(' - the shape of output : ', output.shape)
  66. x = torch.randn(1, in_dim, 20, 20)
  67. flops, params = profile(model, inputs=(x, ), verbose=False)
  68. print('============== FLOPs & Params ================')
  69. print(' - FLOPs : {:.2f} G'.format(flops / 1e9 * 2))
  70. print(' - Params : {:.2f} M'.format(params / 1e6))