yolov1_neck.py 2.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172
  1. import torch
  2. import torch.nn as nn
  3. try:
  4. from .modules import ConvModule
  5. except:
  6. from modules import ConvModule
  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, in_dim, out_dim):
  13. super().__init__()
  14. ## ----------- Basic Parameters -----------
  15. inter_dim = in_dim // 2
  16. self.out_dim = out_dim
  17. ## ----------- Network Parameters -----------
  18. self.cv1 = ConvModule(in_dim, inter_dim, kernel_size=1, padding=0, stride=1)
  19. self.cv2 = ConvModule(inter_dim * 4, out_dim, kernel_size=1, padding=0, stride=1)
  20. self.m = nn.MaxPool2d(kernel_size=5, stride=1, padding=2)
  21. # Initialize all layers
  22. self.init_weights()
  23. def init_weights(self):
  24. for m in self.modules():
  25. if isinstance(m, torch.nn.Conv2d):
  26. m.reset_parameters()
  27. def forward(self, x):
  28. x = self.cv1(x)
  29. y1 = self.m(x)
  30. y2 = self.m(y1)
  31. return self.cv2(torch.cat((x, y1, y2, self.m(y2)), 1))
  32. if __name__=='__main__':
  33. from thop import profile
  34. # YOLOv1 configuration
  35. class Yolov1BaseConfig(object):
  36. def __init__(self) -> None:
  37. # ---------------- Model config ----------------
  38. self.out_stride = 32
  39. self.max_stride = 32
  40. ## Neck
  41. self.neck_expand_ratio = 0.5
  42. self.spp_pooling_size = 5
  43. cfg = Yolov1BaseConfig()
  44. # Build a neck
  45. in_dim = 512
  46. out_dim = 512
  47. model = SPPF(cfg, 512, 512)
  48. # Randomly generate a input data
  49. x = torch.randn(2, in_dim, 20, 20)
  50. # Inference
  51. output = model(x)
  52. print(' - the shape of input : ', x.shape)
  53. print(' - the shape of output : ', output.shape)
  54. x = torch.randn(1, in_dim, 20, 20)
  55. flops, params = profile(model, inputs=(x, ), verbose=False)
  56. print('============== FLOPs & Params ================')
  57. print(' - FLOPs : {:.2f} G'.format(flops / 1e9 * 2))
  58. print(' - Params : {:.2f} M'.format(params / 1e6))