yolox2.py 6.2 KB

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