yolov8.py 6.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180
  1. # --------------- Torch components ---------------
  2. import torch
  3. import torch.nn as nn
  4. # --------------- Model components ---------------
  5. from .yolov8_backbone import build_backbone
  6. from .yolov8_neck import build_neck
  7. from .yolov8_pafpn import build_fpn
  8. from .yolov8_head import build_det_head
  9. from .yolov8_pred import build_pred_layer
  10. # --------------- External components ---------------
  11. from utils.misc import multiclass_nms
  12. # YOLOv8
  13. class YOLOv8(nn.Module):
  14. def __init__(self,
  15. cfg,
  16. device,
  17. num_classes = 20,
  18. conf_thresh = 0.01,
  19. nms_thresh = 0.5,
  20. topk = 1000,
  21. max_dets = 300,
  22. trainable = False,
  23. deploy = False,
  24. nms_class_agnostic = False):
  25. super(YOLOv8, self).__init__()
  26. # ---------------------- Basic Parameters ----------------------
  27. self.cfg = cfg
  28. self.device = device
  29. self.strides = cfg['stride']
  30. self.reg_max = cfg['reg_max']
  31. self.num_classes = num_classes
  32. self.trainable = trainable
  33. self.conf_thresh = conf_thresh
  34. self.nms_thresh = nms_thresh
  35. self.num_levels = len(self.strides)
  36. self.num_classes = num_classes
  37. self.topk = topk
  38. self.max_dets = max_dets
  39. self.deploy = deploy
  40. self.nms_class_agnostic = nms_class_agnostic
  41. # ---------------------- Network Parameters ----------------------
  42. ## ----------- Backbone -----------
  43. self.backbone, feat_dims = build_backbone(cfg)
  44. ## ----------- Neck: SPP -----------
  45. self.neck = build_neck(cfg, feat_dims[-1], feat_dims[-1])
  46. feat_dims[-1] = self.neck.out_dim
  47. ## ----------- Neck: FPN -----------
  48. self.fpn = build_fpn(cfg, feat_dims)
  49. self.fpn_dims = self.fpn.out_dim
  50. ## ----------- Heads -----------
  51. self.det_heads = build_det_head(cfg, self.fpn_dims, self.num_levels, num_classes, self.reg_max)
  52. ## ----------- Preds -----------
  53. self.pred_layers = build_pred_layer(cls_dim = self.det_heads.cls_head_dim,
  54. reg_dim = self.det_heads.reg_head_dim,
  55. strides = self.strides,
  56. num_classes = num_classes,
  57. num_coords = 4,
  58. num_levels = self.num_levels,
  59. reg_max = self.reg_max)
  60. ## post-process
  61. def post_process(self, cls_preds, box_preds):
  62. """
  63. Input:
  64. cls_preds: List(Tensor) [[H x W, C], ...]
  65. box_preds: List(Tensor) [[H x W, 4], ...]
  66. """
  67. all_scores = []
  68. all_labels = []
  69. all_bboxes = []
  70. for cls_pred_i, box_pred_i in zip(cls_preds, box_preds):
  71. cls_pred_i = cls_pred_i[0]
  72. box_pred_i = box_pred_i[0]
  73. # (H x W x C,)
  74. scores_i = cls_pred_i.sigmoid().flatten()
  75. # Keep top k top scoring indices only.
  76. num_topk = min(self.topk, box_pred_i.size(0))
  77. # torch.sort is actually faster than .topk (at least on GPUs)
  78. predicted_prob, topk_idxs = scores_i.sort(descending=True)
  79. topk_scores = predicted_prob[:num_topk]
  80. topk_idxs = topk_idxs[:num_topk]
  81. # filter out the proposals with low confidence score
  82. keep_idxs = topk_scores > self.conf_thresh
  83. scores = topk_scores[keep_idxs]
  84. topk_idxs = topk_idxs[keep_idxs]
  85. anchor_idxs = torch.div(topk_idxs, self.num_classes, rounding_mode='floor')
  86. labels = topk_idxs % self.num_classes
  87. bboxes = box_pred_i[anchor_idxs]
  88. all_scores.append(scores)
  89. all_labels.append(labels)
  90. all_bboxes.append(bboxes)
  91. scores = torch.cat(all_scores)
  92. labels = torch.cat(all_labels)
  93. bboxes = torch.cat(all_bboxes)
  94. # to cpu & numpy
  95. scores = scores.cpu().numpy()
  96. labels = labels.cpu().numpy()
  97. bboxes = bboxes.cpu().numpy()
  98. # nms
  99. scores, labels, bboxes = multiclass_nms(
  100. scores, labels, bboxes, self.nms_thresh, self.num_classes, self.nms_class_agnostic, self.max_dets)
  101. return bboxes, scores, labels
  102. # ---------------------- Main Process for Inference ----------------------
  103. @torch.no_grad()
  104. def inference_single_image(self, x):
  105. # ---------------- Backbone ----------------
  106. pyramid_feats = self.backbone(x)
  107. # ---------------- Neck: SPP ----------------
  108. pyramid_feats[-1] = self.neck(pyramid_feats[-1])
  109. # ---------------- Neck: PaFPN ----------------
  110. pyramid_feats = self.fpn(pyramid_feats)
  111. # ---------------- Heads ----------------
  112. cls_feats, reg_feats = self.det_heads(pyramid_feats)
  113. # ---------------- Preds ----------------
  114. outputs = self.pred_layers(cls_feats, reg_feats)
  115. all_cls_preds = outputs['pred_cls']
  116. all_box_preds = outputs['pred_box']
  117. if self.deploy:
  118. cls_preds = torch.cat(all_cls_preds, dim=1)[0]
  119. box_preds = torch.cat(all_box_preds, dim=1)[0]
  120. scores = cls_preds.sigmoid()
  121. bboxes = box_preds
  122. # [n_anchors_all, 4 + C]
  123. outputs = torch.cat([bboxes, scores], dim=-1)
  124. return outputs
  125. else:
  126. # post process
  127. bboxes, scores, labels = self.post_process(all_cls_preds, all_box_preds)
  128. return bboxes, scores, labels
  129. def forward(self, x):
  130. if not self.trainable:
  131. return self.inference_single_image(x)
  132. else:
  133. # ---------------- Backbone ----------------
  134. pyramid_feats = self.backbone(x)
  135. # ---------------- Neck: SPP ----------------
  136. pyramid_feats[-1] = self.neck(pyramid_feats[-1])
  137. # ---------------- Neck: PaFPN ----------------
  138. pyramid_feats = self.fpn(pyramid_feats)
  139. # ---------------- Heads ----------------
  140. cls_feats, reg_feats = self.det_heads(pyramid_feats)
  141. # ---------------- Preds ----------------
  142. outputs = self.pred_layers(cls_feats, reg_feats)
  143. return outputs