yolov1_neck.py 2.8 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586
  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. import time
  43. from thop import profile
  44. # Model config
  45. # YOLOv1 configuration
  46. class Yolov1BaseConfig(object):
  47. def __init__(self) -> None:
  48. # ---------------- Model config ----------------
  49. self.out_stride = 32
  50. self.max_stride = 32
  51. ## Neck
  52. self.neck_act = 'lrelu'
  53. self.neck_norm = 'BN'
  54. self.neck_depthwise = False
  55. self.neck_expand_ratio = 0.5
  56. self.spp_pooling_size = 5
  57. cfg = Yolov1BaseConfig()
  58. # Build a neck
  59. in_dim = 512
  60. out_dim = 512
  61. model = SPPF(cfg, 512, 512)
  62. # Randomly generate a input data
  63. x = torch.randn(2, in_dim, 20, 20)
  64. # Inference
  65. output = model(x)
  66. print(' - the shape of input : ', x.shape)
  67. print(' - the shape of output : ', output.shape)
  68. x = torch.randn(1, in_dim, 20, 20)
  69. flops, params = profile(model, inputs=(x, ), verbose=False)
  70. print('============== FLOPs & Params ================')
  71. print(' - FLOPs : {:.2f} G'.format(flops / 1e9 * 2))
  72. print(' - Params : {:.2f} M'.format(params / 1e6))