yolovx.py 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277
  1. # --------------- Torch components ---------------
  2. import torch
  3. import torch.nn as nn
  4. import torch.nn.functional as F
  5. # --------------- Model components ---------------
  6. from .yolovx_backbone import build_backbone
  7. from .yolovx_neck import build_neck
  8. from .yolovx_pafpn import build_fpn
  9. from .yolovx_head import build_head
  10. # --------------- External components ---------------
  11. from utils.misc import multiclass_nms
  12. # YOLOvx
  13. class YOLOvx(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(YOLOvx, 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. ## ----------- proj_conv ------------
  38. self.proj = nn.Parameter(torch.linspace(0, cfg['reg_max'], cfg['reg_max']), requires_grad=False)
  39. self.proj_conv = nn.Conv2d(self.reg_max, 1, kernel_size=1, bias=False)
  40. self.proj_conv.weight = nn.Parameter(self.proj.view([1, cfg['reg_max'], 1, 1]).clone().detach(), requires_grad=False)
  41. ## ----------- Backbone -----------
  42. self.backbone, feats_dim = build_backbone(cfg, trainable&cfg['pretrained'])
  43. ## ----------- Neck: SPP -----------
  44. self.neck = build_neck(cfg=cfg, in_dim=feats_dim[-1], out_dim=feats_dim[-1])
  45. feats_dim[-1] = self.neck.out_dim
  46. ## ----------- Neck: FPN -----------
  47. self.fpn = build_fpn(cfg=cfg, in_dims=feats_dim, out_dim=round(256*cfg['width']))
  48. self.fpn_dims = self.fpn.out_dim
  49. ## ----------- Heads -----------
  50. self.heads = build_head(cfg, self.fpn_dims, self.head_dim, num_classes)
  51. ## ----------- Preds -----------
  52. self.cls_preds = nn.ModuleList(
  53. [nn.Conv2d(self.head_dim, num_classes, kernel_size=1)
  54. for _ in range(len(self.stride))
  55. ])
  56. self.reg_preds = nn.ModuleList(
  57. [nn.Conv2d(self.head_dim, 4*cfg['reg_max'], kernel_size=1)
  58. for _ in range(len(self.stride))
  59. ])
  60. # ---------------------- Basic Functions ----------------------
  61. ## generate anchor points
  62. def generate_anchors(self, level, fmp_size):
  63. """
  64. fmp_size: (List) [H, W]
  65. """
  66. # generate grid cells
  67. fmp_h, fmp_w = fmp_size
  68. anchor_y, anchor_x = torch.meshgrid([torch.arange(fmp_h), torch.arange(fmp_w)])
  69. # [H, W, 2] -> [HW, 2]
  70. anchor_xy = torch.stack([anchor_x, anchor_y], dim=-1).float().view(-1, 2)
  71. anchor_xy += 0.5 # add center offset
  72. anchor_xy *= self.stride[level]
  73. anchors = anchor_xy.to(self.device)
  74. return anchors
  75. ## post-process
  76. def post_process(self, cls_preds, box_preds):
  77. """
  78. Input:
  79. cls_preds: List(Tensor) [[H x W, C], ...]
  80. box_preds: List(Tensor) [[H x W, 4], ...]
  81. """
  82. all_scores = []
  83. all_labels = []
  84. all_bboxes = []
  85. for cls_pred_i, box_pred_i in zip(cls_preds, box_preds):
  86. # (H x W x C,)
  87. scores_i = cls_pred_i.sigmoid().flatten()
  88. # Keep top k top scoring indices only.
  89. num_topk = min(self.topk, box_pred_i.size(0))
  90. # torch.sort is actually faster than .topk (at least on GPUs)
  91. predicted_prob, topk_idxs = scores_i.sort(descending=True)
  92. topk_scores = predicted_prob[:num_topk]
  93. topk_idxs = topk_idxs[:num_topk]
  94. # filter out the proposals with low confidence score
  95. keep_idxs = topk_scores > self.conf_thresh
  96. scores = topk_scores[keep_idxs]
  97. topk_idxs = topk_idxs[keep_idxs]
  98. anchor_idxs = torch.div(topk_idxs, self.num_classes, rounding_mode='floor')
  99. labels = topk_idxs % self.num_classes
  100. bboxes = box_pred_i[anchor_idxs]
  101. all_scores.append(scores)
  102. all_labels.append(labels)
  103. all_bboxes.append(bboxes)
  104. scores = torch.cat(all_scores)
  105. labels = torch.cat(all_labels)
  106. bboxes = torch.cat(all_bboxes)
  107. # to cpu & numpy
  108. scores = scores.cpu().numpy()
  109. labels = labels.cpu().numpy()
  110. bboxes = bboxes.cpu().numpy()
  111. # nms
  112. scores, labels, bboxes = multiclass_nms(
  113. scores, labels, bboxes, self.nms_thresh, self.num_classes, False)
  114. return bboxes, scores, labels
  115. # ---------------------- Main Process for Inference ----------------------
  116. @torch.no_grad()
  117. def inference_single_image(self, x):
  118. # ---------------- Backbone ----------------
  119. pyramid_feats = self.backbone(x)
  120. # ---------------- Neck: SPP ----------------
  121. pyramid_feats[-1] = self.neck(pyramid_feats[-1])
  122. # ---------------- Neck: PaFPN ----------------
  123. pyramid_feats = self.fpn(pyramid_feats)
  124. # ---------------- Heads ----------------
  125. cls_feats, reg_feats = self.heads(pyramid_feats)
  126. # ---------------- Preds ----------------
  127. all_cls_preds = []
  128. all_box_preds = []
  129. for level, (cls_feat, reg_feat) in enumerate(zip(cls_feats, reg_feats)):
  130. # prediction
  131. cls_pred = self.cls_preds[level](cls_feat)
  132. reg_pred = self.reg_preds[level](reg_feat)
  133. # anchors: [M, 2]
  134. B, _, H, W = cls_feat.size()
  135. anchors = self.generate_anchors(level, [H, W])
  136. # process preds
  137. cls_pred = cls_pred.permute(0, 2, 3, 1).contiguous().view(B, -1, self.num_classes)
  138. reg_pred = reg_pred.permute(0, 2, 3, 1).contiguous().view(B, -1, 4*self.reg_max)
  139. # ----------------------- Decode bbox -----------------------
  140. B, M = reg_pred.shape[:2]
  141. # [B, M, 4*(reg_max)] -> [B, M, 4, reg_max] -> [B, 4, M, reg_max]
  142. reg_pred = reg_pred.reshape([B, M, 4, self.reg_max])
  143. # [B, M, 4, reg_max] -> [B, reg_max, 4, M]
  144. reg_pred = reg_pred.permute(0, 3, 2, 1).contiguous()
  145. # [B, reg_max, 4, M] -> [B, 1, 4, M]
  146. reg_pred = self.proj_conv(F.softmax(reg_pred, dim=1))
  147. # [B, 1, 4, M] -> [B, 4, M] -> [B, M, 4]
  148. reg_pred = reg_pred.view(B, 4, M).permute(0, 2, 1).contiguous()
  149. ## tlbr -> xyxy
  150. x1y1_pred = anchors[None] - reg_pred[..., :2] * self.stride[level]
  151. x2y2_pred = anchors[None] + reg_pred[..., 2:] * self.stride[level]
  152. box_pred = torch.cat([x1y1_pred, x2y2_pred], dim=-1)
  153. # collect preds
  154. all_cls_preds.append(cls_pred[0])
  155. all_box_preds.append(box_pred[0])
  156. if self.deploy:
  157. # no post process
  158. cls_preds = torch.cat(all_cls_preds, dim=0)
  159. box_pred = torch.cat(all_box_preds, dim=0)
  160. # [n_anchors_all, 4 + C]
  161. outputs = torch.cat([box_pred, cls_preds.sigmoid()], dim=-1)
  162. return outputs
  163. else:
  164. # post process
  165. bboxes, scores, labels = self.post_process(all_cls_preds, all_box_preds)
  166. return bboxes, scores, labels
  167. # ---------------------- Main Process for Training ----------------------
  168. def forward(self, x):
  169. if not self.trainable:
  170. return self.inference_single_image(x)
  171. else:
  172. # ---------------- Backbone ----------------
  173. pyramid_feats = self.backbone(x)
  174. # ---------------- Neck: SPP ----------------
  175. pyramid_feats[-1] = self.neck(pyramid_feats[-1])
  176. # ---------------- Neck: PaFPN ----------------
  177. pyramid_feats = self.fpn(pyramid_feats)
  178. # ---------------- Heads ----------------
  179. cls_feats, reg_feats = self.heads(pyramid_feats)
  180. # ---------------- Preds ----------------
  181. all_anchors = []
  182. all_strides = []
  183. all_cls_preds = []
  184. all_reg_preds = []
  185. all_box_preds = []
  186. for level, (cls_feat, reg_feat) in enumerate(zip(cls_feats, reg_feats)):
  187. # prediction
  188. cls_pred = self.cls_preds[level](cls_feat)
  189. reg_pred = self.reg_preds[level](reg_feat)
  190. B, _, H, W = cls_pred.size()
  191. # generate anchor boxes: [M, 4]
  192. anchors = self.generate_anchors(level, [H, W])
  193. # stride tensor: [M, 1]
  194. stride_tensor = torch.ones_like(anchors[..., :1]) * self.stride[level]
  195. # process preds
  196. cls_pred = cls_pred.permute(0, 2, 3, 1).contiguous().view(B, -1, self.num_classes)
  197. reg_pred = reg_pred.permute(0, 2, 3, 1).contiguous().view(B, -1, 4*self.reg_max)
  198. # ----------------------- Decode bbox -----------------------
  199. B, M = reg_pred.shape[:2]
  200. # [B, M, 4*(reg_max)] -> [B, M, 4, reg_max] -> [B, 4, M, reg_max]
  201. reg_pred_ = reg_pred.reshape([B, M, 4, self.reg_max])
  202. # [B, M, 4, reg_max] -> [B, reg_max, 4, M]
  203. reg_pred_ = reg_pred_.permute(0, 3, 2, 1).contiguous()
  204. # [B, reg_max, 4, M] -> [B, 1, 4, M]
  205. reg_pred_ = self.proj_conv(F.softmax(reg_pred_, dim=1))
  206. # [B, 1, 4, M] -> [B, 4, M] -> [B, M, 4]
  207. reg_pred_ = reg_pred_.view(B, 4, M).permute(0, 2, 1).contiguous()
  208. ## tlbr -> xyxy
  209. x1y1_pred = anchors[None] - reg_pred_[..., :2] * self.stride[level]
  210. x2y2_pred = anchors[None] + reg_pred_[..., 2:] * self.stride[level]
  211. box_pred = torch.cat([x1y1_pred, x2y2_pred], dim=-1)
  212. # collect preds
  213. all_cls_preds.append(cls_pred)
  214. all_reg_preds.append(reg_pred)
  215. all_box_preds.append(box_pred)
  216. all_anchors.append(anchors)
  217. all_strides.append(stride_tensor)
  218. # output dict
  219. outputs = {"pred_cls": all_cls_preds, # List(Tensor) [B, M, C]
  220. "pred_reg": all_reg_preds, # List(Tensor) [B, M, 4*(reg_max)]
  221. "pred_box": all_box_preds, # List(Tensor) [B, M, 4]
  222. "anchors": all_anchors, # List(Tensor) [M, 2]
  223. "strides": self.stride, # List(Int) = [8, 16, 32]
  224. "stride_tensor": all_strides # List(Tensor) [M, 1]
  225. }
  226. return outputs