artdet_head.py 6.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173
  1. import torch
  2. import torch.nn as nn
  3. import torch.nn.functional as F
  4. try:
  5. from .artdet_basic import Conv
  6. except:
  7. from artdet_basic import Conv
  8. class DecoupledHead(nn.Module):
  9. def __init__(self, cfg, in_dim, out_dim, num_classes=80):
  10. super().__init__()
  11. print('==============================')
  12. print('Head: Decoupled Head')
  13. # --------- Basic Parameters ----------
  14. self.in_dim = in_dim
  15. self.num_classes = num_classes
  16. self.reg_max = cfg['reg_max']
  17. self.num_cls_head=cfg['num_cls_head']
  18. self.num_reg_head=cfg['num_reg_head']
  19. # --------- Network Parameters ----------
  20. ## cls head
  21. cls_feats = []
  22. self.cls_out_dim = out_dim
  23. for i in range(cfg['num_cls_head']):
  24. if i == 0:
  25. cls_feats.append(
  26. Conv(in_dim, self.cls_out_dim, k=3, p=1, s=1,
  27. act_type=cfg['head_act'],
  28. norm_type=cfg['head_norm'],
  29. depthwise=cfg['head_depthwise'])
  30. )
  31. else:
  32. cls_feats.append(
  33. Conv(self.cls_out_dim, self.cls_out_dim, k=3, p=1, s=1,
  34. act_type=cfg['head_act'],
  35. norm_type=cfg['head_norm'],
  36. depthwise=cfg['head_depthwise'])
  37. )
  38. ## reg head
  39. reg_feats = []
  40. self.reg_out_dim = out_dim
  41. for i in range(cfg['num_reg_head']):
  42. if i == 0:
  43. reg_feats.append(
  44. Conv(in_dim, self.reg_out_dim, k=3, p=1, s=1,
  45. act_type=cfg['head_act'],
  46. norm_type=cfg['head_norm'],
  47. depthwise=cfg['head_depthwise'])
  48. )
  49. else:
  50. reg_feats.append(
  51. Conv(self.reg_out_dim, self.reg_out_dim, k=3, p=1, s=1,
  52. act_type=cfg['head_act'],
  53. norm_type=cfg['head_norm'],
  54. depthwise=cfg['head_depthwise'])
  55. )
  56. self.cls_feats = nn.Sequential(*cls_feats)
  57. self.reg_feats = nn.Sequential(*reg_feats)
  58. ## Pred
  59. self.cls_pred = nn.Conv2d(self.cls_out_dim, num_classes, kernel_size=1)
  60. self.reg_pred = nn.Conv2d(self.reg_out_dim, 4*cfg['reg_max'], kernel_size=1)
  61. ## ----------- proj_conv ------------
  62. self.proj = nn.Parameter(torch.linspace(0, cfg['reg_max'], cfg['reg_max']), requires_grad=False)
  63. self.proj_conv = nn.Conv2d(self.reg_max, 1, kernel_size=1, bias=False)
  64. self.proj_conv.weight = nn.Parameter(self.proj.view([1, cfg['reg_max'], 1, 1]).clone().detach(), requires_grad=False)
  65. def forward(self, x, anchors, stride):
  66. """
  67. in_feats: (Tensor) [B, C, H, W]
  68. """
  69. cls_feats = self.cls_feats(x)
  70. reg_feats = self.reg_feats(x)
  71. cls_pred = self.cls_pred(cls_feats)
  72. reg_pred = self.reg_pred(reg_feats)
  73. # process preds
  74. B = x.shape[0]
  75. cls_pred = cls_pred.permute(0, 2, 3, 1).contiguous().view(B, -1, self.num_classes)
  76. reg_pred = reg_pred.permute(0, 2, 3, 1).contiguous().view(B, -1, 4*self.reg_max)
  77. # ----------------------- Decode bbox -----------------------
  78. M = reg_pred.shape[1]
  79. # [B, M, 4*(reg_max)] -> [B, M, 4, reg_max] -> [B, 4, M, reg_max]
  80. reg_pred_ = reg_pred.reshape([B, M, 4, self.reg_max])
  81. # [B, M, 4, reg_max] -> [B, reg_max, 4, M]
  82. reg_pred_ = reg_pred_.permute(0, 3, 2, 1).contiguous()
  83. # [B, reg_max, 4, M] -> [B, 1, 4, M]
  84. reg_pred_ = self.proj_conv(F.softmax(reg_pred_, dim=1))
  85. # [B, 1, 4, M] -> [B, 4, M] -> [B, M, 4]
  86. reg_pred_ = reg_pred_.view(B, 4, M).permute(0, 2, 1).contiguous()
  87. ## tlbr -> xyxy
  88. x1y1_pred = anchors[None] - reg_pred_[..., :2] * stride
  89. x2y2_pred = anchors[None] + reg_pred_[..., 2:] * stride
  90. box_pred = torch.cat([x1y1_pred, x2y2_pred], dim=-1)
  91. return cls_pred, reg_pred, box_pred
  92. # build detection head
  93. def build_head(cfg, in_dim, out_dim, num_classes=80):
  94. if cfg['head'] == 'decoupled_head':
  95. head = DecoupledHead(cfg, in_dim, out_dim, num_classes)
  96. return head
  97. if __name__ == '__main__':
  98. import time
  99. from thop import profile
  100. cfg = {
  101. 'head': 'decoupled_head',
  102. 'num_cls_head': 2,
  103. 'num_reg_head': 2,
  104. 'head_act': 'silu',
  105. 'head_norm': 'BN',
  106. 'head_depthwise': False,
  107. 'reg_max': 16,
  108. }
  109. fpn_dims = [256, 512, 512]
  110. # Head-1
  111. model = build_head(cfg, 256, fpn_dims, num_classes=80)
  112. x = torch.randn(1, 256, 80, 80)
  113. t0 = time.time()
  114. outputs = model(x)
  115. t1 = time.time()
  116. print('Time: ', t1 - t0)
  117. # for out in outputs:
  118. # print(out.shape)
  119. print('==============================')
  120. flops, params = profile(model, inputs=(x, ), verbose=False)
  121. print('==============================')
  122. print('Head-1: GFLOPs : {:.2f}'.format(flops / 1e9 * 2))
  123. print('Head-1: Params : {:.2f} M'.format(params / 1e6))
  124. # Head-2
  125. model = build_head(cfg, 512, fpn_dims, num_classes=80)
  126. x = torch.randn(1, 512, 40, 40)
  127. t0 = time.time()
  128. outputs = model(x)
  129. t1 = time.time()
  130. print('Time: ', t1 - t0)
  131. # for out in outputs:
  132. # print(out.shape)
  133. print('==============================')
  134. flops, params = profile(model, inputs=(x, ), verbose=False)
  135. print('==============================')
  136. print('Head-2: GFLOPs : {:.2f}'.format(flops / 1e9 * 2))
  137. print('Head-2: Params : {:.2f} M'.format(params / 1e6))
  138. # Head-3
  139. model = build_head(cfg, 512, fpn_dims, num_classes=80)
  140. x = torch.randn(1, 512, 20, 20)
  141. t0 = time.time()
  142. outputs = model(x)
  143. t1 = time.time()
  144. print('Time: ', t1 - t0)
  145. # for out in outputs:
  146. # print(out.shape)
  147. print('==============================')
  148. flops, params = profile(model, inputs=(x, ), verbose=False)
  149. print('==============================')
  150. print('Head-3: GFLOPs : {:.2f}'.format(flops / 1e9 * 2))
  151. print('Head-3: Params : {:.2f} M'.format(params / 1e6))