rtpdetr_decoder.py 15 KB

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