rtcdet_v2.py 5.9 KB

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