rtdetr_decoder.py 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375
  1. import math
  2. import torch
  3. import torch.nn as nn
  4. import torch.nn.functional as F
  5. from torch.nn.init import constant_, xavier_uniform_, uniform_, normal_
  6. from typing import List
  7. try:
  8. from .basic_modules.basic import BasicConv, MLP
  9. from .basic_modules.transformer import DeformableTransformerDecoder
  10. from .basic_modules.dn_compoments import get_contrastive_denoising_training_group
  11. except:
  12. from basic_modules.basic import BasicConv, MLP
  13. from basic_modules.transformer import DeformableTransformerDecoder
  14. from basic_modules.dn_compoments import get_contrastive_denoising_training_group
  15. def build_transformer(cfg, in_dims, num_classes, return_intermediate=False):
  16. if cfg['transformer'] == 'rtdetr_transformer':
  17. return RTDETRTransformer(in_dims = in_dims,
  18. hidden_dim = cfg['hidden_dim'],
  19. strides = cfg['out_stride'],
  20. num_classes = num_classes,
  21. num_queries = cfg['num_queries'],
  22. pos_embed_type = 'sine',
  23. num_heads = cfg['de_num_heads'],
  24. num_layers = cfg['de_num_layers'],
  25. num_levels = len(cfg['out_stride']),
  26. num_points = cfg['de_num_points'],
  27. ffn_dim = cfg['de_ffn_dim'],
  28. dropout = cfg['de_dropout'],
  29. act_type = cfg['de_act'],
  30. return_intermediate = return_intermediate,
  31. num_denoising = cfg['dn_num_denoising'],
  32. label_noise_ratio = cfg['dn_label_noise_ratio'],
  33. box_noise_scale = cfg['dn_box_noise_scale'],
  34. learnt_init_query = cfg['learnt_init_query'],
  35. )
  36. # ----------------- Dencoder for Detection task -----------------
  37. ## RTDETR's Transformer for Detection task
  38. class RTDETRTransformer(nn.Module):
  39. def __init__(self,
  40. # basic parameters
  41. in_dims :List = [256, 512, 1024],
  42. hidden_dim :int = 256,
  43. strides :List = [8, 16, 32],
  44. num_classes :int = 80,
  45. num_queries :int = 300,
  46. pos_embed_type :str = 'sine',
  47. # transformer parameters
  48. num_heads :int = 8,
  49. num_layers :int = 1,
  50. num_levels :int = 3,
  51. num_points :int = 4,
  52. ffn_dim :int = 1024,
  53. dropout :float = 0.1,
  54. act_type :str = "relu",
  55. return_intermediate :bool = False,
  56. # Denoising parameters
  57. num_denoising :int = 100,
  58. label_noise_ratio :float = 0.5,
  59. box_noise_scale :float = 1.0,
  60. learnt_init_query :bool = False,
  61. aux_loss :bool = True
  62. ):
  63. super().__init__()
  64. # --------------- Basic setting ---------------
  65. ## Basic parameters
  66. self.in_dims = in_dims
  67. self.strides = strides
  68. self.num_queries = num_queries
  69. self.pos_embed_type = pos_embed_type
  70. self.num_classes = num_classes
  71. self.eps = 1e-2
  72. self.aux_loss = aux_loss
  73. ## Transformer parameters
  74. self.num_heads = num_heads
  75. self.num_layers = num_layers
  76. self.num_levels = num_levels
  77. self.num_points = num_points
  78. self.ffn_dim = ffn_dim
  79. self.dropout = dropout
  80. self.act_type = act_type
  81. self.return_intermediate = return_intermediate
  82. ## Denoising parameters
  83. self.num_denoising = num_denoising
  84. self.label_noise_ratio = label_noise_ratio
  85. self.box_noise_scale = box_noise_scale
  86. self.learnt_init_query = learnt_init_query
  87. # --------------- Network setting ---------------
  88. ## Input proj layers
  89. self.input_proj_layers = nn.ModuleList(
  90. BasicConv(in_dims[i], hidden_dim, kernel_size=1, act_type=None, norm_type="BN")
  91. for i in range(num_levels)
  92. )
  93. ## Deformable transformer decoder
  94. self.decoder = DeformableTransformerDecoder(
  95. d_model = hidden_dim,
  96. num_heads = num_heads,
  97. num_layers = num_layers,
  98. num_levels = num_levels,
  99. num_points = num_points,
  100. ffn_dim = ffn_dim,
  101. dropout = dropout,
  102. act_type = act_type,
  103. return_intermediate = return_intermediate
  104. )
  105. ## Detection head for Encoder
  106. self.enc_output = nn.Sequential(
  107. nn.Linear(hidden_dim, hidden_dim),
  108. nn.LayerNorm(hidden_dim)
  109. )
  110. self.enc_class_head = nn.Linear(hidden_dim, num_classes)
  111. self.enc_bbox_head = MLP(hidden_dim, hidden_dim, 4, num_layers=3)
  112. ## Detection head for Decoder
  113. self.dec_class_head = nn.ModuleList([
  114. nn.Linear(hidden_dim, num_classes)
  115. for _ in range(num_layers)
  116. ])
  117. self.dec_bbox_head = nn.ModuleList([
  118. MLP(hidden_dim, hidden_dim, 4, num_layers=3)
  119. for _ in range(num_layers)
  120. ])
  121. ## Object query
  122. if learnt_init_query:
  123. self.tgt_embed = nn.Embedding(num_queries, hidden_dim)
  124. self.query_pos_head = MLP(4, 2 * hidden_dim, hidden_dim, num_layers=2)
  125. ## Denoising part
  126. if num_denoising > 0:
  127. self.denoising_class_embed = nn.Embedding(num_classes+1, hidden_dim, padding_idx=num_classes)
  128. self._reset_parameters()
  129. def _reset_parameters(self):
  130. # class and bbox head init
  131. prior_prob = 0.01
  132. cls_bias_init = float(-math.log((1 - prior_prob) / prior_prob))
  133. nn.init.constant_(self.enc_class_head.bias, cls_bias_init)
  134. nn.init.constant_(self.enc_bbox_head.layers[-1].weight, 0.)
  135. nn.init.constant_(self.enc_bbox_head.layers[-1].bias, 0.)
  136. for cls_, reg_ in zip(self.dec_class_head, self.dec_bbox_head):
  137. nn.init.constant_(cls_.bias, cls_bias_init)
  138. nn.init.constant_(reg_.layers[-1].weight, 0.)
  139. nn.init.constant_(reg_.layers[-1].bias, 0.)
  140. nn.init.xavier_uniform_(self.enc_output[0].weight)
  141. if self.learnt_init_query:
  142. nn.init.xavier_uniform_(self.tgt_embed.weight)
  143. nn.init.xavier_uniform_(self.query_pos_head.layers[0].weight)
  144. nn.init.xavier_uniform_(self.query_pos_head.layers[1].weight)
  145. @torch.jit.unused
  146. def _set_aux_loss(self, outputs_class, outputs_coord):
  147. # this is a workaround to make torchscript happy, as torchscript
  148. # doesn't support dictionary with non-homogeneous values, such
  149. # as a dict having both a Tensor and a list.
  150. return [{'pred_logits': a, 'pred_boxes': b}
  151. for a, b in zip(outputs_class, outputs_coord)]
  152. def generate_anchors(self, spatial_shapes, grid_size=0.05):
  153. anchors = []
  154. for lvl, (h, w) in enumerate(spatial_shapes):
  155. grid_y, grid_x = torch.meshgrid(torch.arange(h), torch.arange(w))
  156. # [H, W, 2]
  157. grid_xy = torch.stack([grid_x, grid_y], dim=-1).float()
  158. valid_WH = torch.as_tensor([w, h]).float()
  159. grid_xy = (grid_xy.unsqueeze(0) + 0.5) / valid_WH
  160. wh = torch.ones_like(grid_xy) * grid_size * (2.0**lvl)
  161. # [H, W, 4] -> [1, N, 4], N=HxW
  162. anchors.append(torch.cat([grid_xy, wh], dim=-1).reshape(-1, h * w, 4))
  163. # List[L, 1, N_i, 4] -> [1, N, 4], N=N_0 + N_1 + N_2 + ...
  164. anchors = torch.cat(anchors, dim=1)
  165. valid_mask = ((anchors > self.eps) * (anchors < 1 - self.eps)).all(-1, keepdim=True)
  166. anchors = torch.log(anchors / (1 - anchors))
  167. # Equal to operation: anchors = torch.masked_fill(anchors, ~valid_mask, torch.as_tensor(float("inf")))
  168. anchors = torch.where(valid_mask, anchors, torch.inf)
  169. return anchors, valid_mask
  170. def get_encoder_input(self, feats):
  171. # get projection features
  172. proj_feats = [self.input_proj_layers[i](feat) for i, feat in enumerate(feats)]
  173. # get encoder inputs
  174. feat_flatten = []
  175. spatial_shapes = []
  176. level_start_index = [0, ]
  177. for i, feat in enumerate(proj_feats):
  178. _, _, h, w = feat.shape
  179. spatial_shapes.append([h, w])
  180. # [l], start index of each level
  181. level_start_index.append(h * w + level_start_index[-1])
  182. # [B, C, H, W] -> [B, N, C], N=HxW
  183. feat_flatten.append(feat.flatten(2).permute(0, 2, 1).contiguous())
  184. # [B, N, C], N = N_0 + N_1 + ...
  185. feat_flatten = torch.cat(feat_flatten, dim=1)
  186. level_start_index.pop()
  187. return (feat_flatten, spatial_shapes, level_start_index)
  188. def get_decoder_input(self,
  189. memory,
  190. spatial_shapes,
  191. denoising_class=None,
  192. denoising_bbox_unact=None):
  193. bs, _, _ = memory.shape
  194. # Prepare input for decoder
  195. anchors, valid_mask = self.generate_anchors(spatial_shapes)
  196. anchors = anchors.to(memory.device)
  197. valid_mask = valid_mask.to(memory.device)
  198. # Process encoder's output
  199. memory = torch.where(valid_mask, memory, torch.as_tensor(0., device=memory.device))
  200. output_memory = self.enc_output(memory)
  201. # Head for encoder's output : [bs, num_quries, c]
  202. enc_outputs_class = self.enc_class_head(output_memory)
  203. enc_outputs_coord_unact = self.enc_bbox_head(output_memory) + anchors
  204. # Topk proposals from encoder's output
  205. topk = self.num_queries
  206. topk_ind = torch.topk(enc_outputs_class.max(-1)[0], topk, dim=1)[1] # [bs, num_queries]
  207. enc_topk_logits = torch.gather(
  208. enc_outputs_class, 1, topk_ind.unsqueeze(-1).repeat(1, 1, self.num_classes)) # [bs, num_queries, nc]
  209. reference_points_unact = torch.gather(
  210. enc_outputs_coord_unact, 1, topk_ind.unsqueeze(-1).repeat(1, 1, 4)) # [bs, num_queries, 4]
  211. enc_topk_bboxes = F.sigmoid(reference_points_unact)
  212. if denoising_bbox_unact is not None:
  213. reference_points_unact = torch.cat(
  214. [denoising_bbox_unact, reference_points_unact], dim=1)
  215. # Extract region features
  216. if self.learnt_init_query:
  217. # [num_queries, c] -> [b, num_queries, c]
  218. target = self.tgt_embed.weight.unsqueeze(0).repeat(bs, 1, 1)
  219. else:
  220. # [num_queries, c] -> [b, num_queries, c]
  221. target = torch.gather(output_memory, 1, topk_ind.unsqueeze(-1).repeat(1, 1, output_memory.shape[-1]))
  222. target = target.detach()
  223. if denoising_class is not None:
  224. target = torch.cat([denoising_class, target], dim=1)
  225. return target, reference_points_unact.detach(), enc_topk_bboxes, enc_topk_logits
  226. def forward(self, feats, targets=None):
  227. # input projection and embedding
  228. memory, spatial_shapes, _ = self.get_encoder_input(feats)
  229. # prepare denoising training
  230. if self.training and self.num_denoising > 0:
  231. denoising_class, denoising_bbox_unact, attn_mask, dn_meta = \
  232. get_contrastive_denoising_training_group(targets, \
  233. self.num_classes,
  234. self.num_queries,
  235. self.denoising_class_embed,
  236. num_denoising=self.num_denoising,
  237. label_noise_ratio=self.label_noise_ratio,
  238. box_noise_scale=self.box_noise_scale, )
  239. else:
  240. denoising_class, denoising_bbox_unact, attn_mask, dn_meta = None, None, None, None
  241. target, init_ref_points_unact, enc_topk_bboxes, enc_topk_logits = \
  242. self.get_decoder_input(
  243. memory, spatial_shapes, denoising_class, denoising_bbox_unact)
  244. # decoder
  245. out_bboxes, out_logits = self.decoder(target,
  246. init_ref_points_unact,
  247. memory,
  248. spatial_shapes,
  249. self.dec_bbox_head,
  250. self.dec_class_head,
  251. self.query_pos_head,
  252. attn_mask)
  253. if self.training and dn_meta is not None:
  254. dn_out_bboxes, out_bboxes = torch.split(out_bboxes, dn_meta['dn_num_split'], dim=2)
  255. dn_out_logits, out_logits = torch.split(out_logits, dn_meta['dn_num_split'], dim=2)
  256. out = {'pred_logits': out_logits[-1], 'pred_boxes': out_bboxes[-1]}
  257. if self.training and self.aux_loss:
  258. out['aux_outputs'] = self._set_aux_loss(out_logits[:-1], out_bboxes[:-1])
  259. out['aux_outputs'].extend(self._set_aux_loss([enc_topk_logits], [enc_topk_bboxes]))
  260. if self.training and dn_meta is not None:
  261. out['dn_aux_outputs'] = self._set_aux_loss(dn_out_logits, dn_out_bboxes)
  262. out['dn_meta'] = dn_meta
  263. return out
  264. # ----------------- Dencoder for Segmentation task -----------------
  265. ## RTDETR's Transformer for Segmentation task
  266. class SegTransformerDecoder(nn.Module):
  267. def __init__(self, ):
  268. super().__init__()
  269. # TODO: design seg-decoder
  270. def forward(self, x):
  271. return
  272. # ----------------- Dencoder for Pose estimation task -----------------
  273. ## RTDETR's Transformer for Pose estimation task
  274. class PosTransformerDecoder(nn.Module):
  275. def __init__(self, ):
  276. super().__init__()
  277. # TODO: design seg-decoder
  278. def forward(self, x):
  279. return
  280. if __name__ == '__main__':
  281. import time
  282. from thop import profile
  283. cfg = {
  284. 'out_stride': [8, 16, 32],
  285. # Transformer Decoder
  286. 'transformer': 'rtdetr_transformer',
  287. 'hidden_dim': 256,
  288. 'de_num_heads': 8,
  289. 'de_num_layers': 6,
  290. 'de_ffn_dim': 1024,
  291. 'de_dropout': 0.1,
  292. 'de_act': 'gelu',
  293. 'de_num_points': 4,
  294. 'num_queries': 300,
  295. 'learnt_init_query': False,
  296. 'pe_temperature': 10000.,
  297. 'dn_num_denoising': 100,
  298. 'dn_label_noise_ratio': 0.5,
  299. 'dn_box_noise_scale': 1,
  300. }
  301. bs = 1
  302. hidden_dim = cfg['hidden_dim']
  303. in_dims = [hidden_dim] * 3
  304. targets = [{
  305. 'labels': torch.tensor([2, 4, 5, 8]).long(),
  306. 'boxes': torch.tensor([[0, 0, 10, 10], [12, 23, 56, 70], [0, 10, 20, 30], [50, 60, 55, 150]]).float()
  307. }] * bs
  308. pyramid_feats = [torch.randn(bs, hidden_dim, 80, 80),
  309. torch.randn(bs, hidden_dim, 40, 40),
  310. torch.randn(bs, hidden_dim, 20, 20)]
  311. model = build_transformer(cfg, in_dims, 80, True)
  312. model.train()
  313. t0 = time.time()
  314. outputs = model(pyramid_feats, targets)
  315. t1 = time.time()
  316. print('Time: ', t1 - t0)
  317. print(outputs["pred_logits"].shape)
  318. print(outputs["pred_boxes"].shape)
  319. print('==============================')
  320. model.eval()
  321. flops, params = profile(model, inputs=(pyramid_feats, ), verbose=False)
  322. print('==============================')
  323. print('GFLOPs : {:.2f}'.format(flops / 1e9 * 2))
  324. print('Params : {:.2f} M'.format(params / 1e6))