yolov3_neck.py 1.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051
  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. inter_dim = in_dim // 2
  15. self.out_dim = out_dim
  16. self.cv1 = ConvModule(in_dim, inter_dim, kernel_size=1)
  17. self.cv2 = ConvModule(inter_dim * 4, out_dim, kernel_size=1)
  18. self.m = nn.MaxPool2d(kernel_size=5, stride=1, padding=5 // 2)
  19. def forward(self, x):
  20. x = self.cv1(x)
  21. y1 = self.m(x)
  22. y2 = self.m(y1)
  23. return self.cv2(torch.cat((x, y1, y2, self.m(y2)), 1))
  24. if __name__=='__main__':
  25. from thop import profile
  26. # Build a neck
  27. in_dim = 512
  28. out_dim = 512
  29. model = SPPF(512, 512)
  30. # Randomly generate a input data
  31. x = torch.randn(2, in_dim, 20, 20)
  32. # Inference
  33. output = model(x)
  34. print(' - the shape of input : ', x.shape)
  35. print(' - the shape of output : ', output.shape)
  36. x = torch.randn(1, in_dim, 20, 20)
  37. flops, params = profile(model, inputs=(x, ), verbose=False)
  38. print('============== FLOPs & Params ================')
  39. print(' - FLOPs : {:.2f} G'.format(flops / 1e9 * 2))
  40. print(' - Params : {:.2f} M'.format(params / 1e6))