motr_det.py 32 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677
  1. # ------------------------------------------------------------------------
  2. # Copyright (c) 2021 megvii-model. All Rights Reserved.
  3. # ------------------------------------------------------------------------
  4. # Modified from Deformable DETR (https://github.com/fundamentalvision/Deformable-DETR)
  5. # Copyright (c) 2020 SenseTime. All Rights Reserved.
  6. # ------------------------------------------------------------------------
  7. # Modified from DETR (https://github.com/facebookresearch/detr)
  8. # Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved
  9. # ------------------------------------------------------------------------
  10. """
  11. DETR model and criterion classes.
  12. """
  13. import copy
  14. import math
  15. import numpy as np
  16. import torch
  17. import torch.nn.functional as F
  18. from torch import nn, Tensor
  19. from typing import List
  20. from util import box_ops
  21. from util.misc import (NestedTensor, nested_tensor_from_tensor_list,
  22. accuracy, get_world_size, interpolate, get_rank,
  23. is_dist_avail_and_initialized, inverse_sigmoid)
  24. from models.structures import Instances, Boxes, pairwise_iou, matched_boxlist_iou
  25. from .backbone import build_backbone
  26. from .matcher import build_matcher
  27. from .deformable_transformer_plus import build_deforamble_transformer
  28. from .qim import build as build_query_interaction_layer
  29. from .memory_bank import build_memory_bank
  30. from .deformable_detr import SetCriterion, MLP
  31. from .segmentation import sigmoid_focal_loss
  32. class ClipMatcher(SetCriterion):
  33. def __init__(self, num_classes,
  34. matcher,
  35. weight_dict,
  36. losses):
  37. """ Create the criterion.
  38. Parameters:
  39. num_classes: number of object categories, omitting the special no-object category
  40. matcher: module able to compute a matching between targets and proposals
  41. weight_dict: dict containing as key the names of the losses and as values their relative weight.
  42. eos_coef: relative classification weight applied to the no-object category
  43. losses: list of all the losses to be applied. See get_loss for list of available losses.
  44. """
  45. super().__init__(num_classes, matcher, weight_dict, losses)
  46. self.num_classes = num_classes
  47. self.matcher = matcher
  48. self.weight_dict = weight_dict
  49. self.losses = losses
  50. self.focal_loss = True
  51. self.losses_dict = {}
  52. self._current_frame_idx = 0
  53. def initialize_for_single_clip(self, gt_instances: List[Instances]):
  54. self.gt_instances = gt_instances
  55. self.num_samples = 0
  56. self.sample_device = None
  57. self._current_frame_idx = 0
  58. self.losses_dict = {}
  59. def _step(self):
  60. self._current_frame_idx += 1
  61. def calc_loss_for_track_scores(self, track_instances: Instances):
  62. frame_id = self._current_frame_idx - 1
  63. gt_instances = self.gt_instances[frame_id]
  64. outputs = {
  65. 'pred_logits': track_instances.track_scores[None],
  66. }
  67. device = track_instances.track_scores.device
  68. num_tracks = len(track_instances)
  69. src_idx = torch.arange(num_tracks, dtype=torch.long, device=device)
  70. tgt_idx = track_instances.matched_gt_idxes # -1 for FP tracks and disappeared tracks
  71. track_losses = self.get_loss('labels',
  72. outputs=outputs,
  73. gt_instances=[gt_instances],
  74. indices=[(src_idx, tgt_idx)],
  75. num_boxes=1)
  76. self.losses_dict.update(
  77. {'frame_{}_track_{}'.format(frame_id, key): value for key, value in
  78. track_losses.items()})
  79. def get_num_boxes(self, num_samples):
  80. num_boxes = torch.as_tensor(num_samples, dtype=torch.float, device=self.sample_device)
  81. if is_dist_avail_and_initialized():
  82. torch.distributed.all_reduce(num_boxes)
  83. num_boxes = torch.clamp(num_boxes / get_world_size(), min=1).item()
  84. return num_boxes
  85. def get_loss(self, loss, outputs, gt_instances, indices, num_boxes, **kwargs):
  86. loss_map = {
  87. 'labels': self.loss_labels,
  88. 'cardinality': self.loss_cardinality,
  89. 'boxes': self.loss_boxes,
  90. }
  91. assert loss in loss_map, f'do you really want to compute {loss} loss?'
  92. return loss_map[loss](outputs, gt_instances, indices, num_boxes, **kwargs)
  93. def loss_boxes(self, outputs, gt_instances: List[Instances], indices: List[tuple], num_boxes):
  94. """Compute the losses related to the bounding boxes, the L1 regression loss and the GIoU loss
  95. targets dicts must contain the key "boxes" containing a tensor of dim [nb_target_boxes, 4]
  96. The target boxes are expected in format (center_x, center_y, h, w), normalized by the image size.
  97. """
  98. # We ignore the regression loss of the track-disappear slots.
  99. #TODO: Make this filter process more elegant.
  100. filtered_idx = []
  101. for src_per_img, tgt_per_img in indices:
  102. keep = tgt_per_img != -1
  103. filtered_idx.append((src_per_img[keep], tgt_per_img[keep]))
  104. indices = filtered_idx
  105. idx = self._get_src_permutation_idx(indices)
  106. src_boxes = outputs['pred_boxes'][idx]
  107. target_boxes = torch.cat([gt_per_img.boxes[i] for gt_per_img, (_, i) in zip(gt_instances, indices)], dim=0)
  108. # for pad target, don't calculate regression loss, judged by whether obj_id=-1
  109. target_obj_ids = torch.cat([gt_per_img.obj_ids[i] for gt_per_img, (_, i) in zip(gt_instances, indices)], dim=0) # size(16)
  110. mask = (target_obj_ids != -1)
  111. loss_bbox = F.l1_loss(src_boxes[mask], target_boxes[mask], reduction='none')
  112. loss_giou = 1 - torch.diag(box_ops.generalized_box_iou(
  113. box_ops.box_cxcywh_to_xyxy(src_boxes[mask]),
  114. box_ops.box_cxcywh_to_xyxy(target_boxes[mask])))
  115. losses = {}
  116. losses['loss_bbox'] = loss_bbox.sum() / num_boxes
  117. losses['loss_giou'] = loss_giou.sum() / num_boxes
  118. return losses
  119. def loss_labels(self, outputs, gt_instances: List[Instances], indices, num_boxes, log=False):
  120. """Classification loss (NLL)
  121. targets dicts must contain the key "labels" containing a tensor of dim [nb_target_boxes]
  122. """
  123. src_logits = outputs['pred_logits']
  124. idx = self._get_src_permutation_idx(indices)
  125. target_classes = torch.full(src_logits.shape[:2], self.num_classes,
  126. dtype=torch.int64, device=src_logits.device)
  127. # The matched gt for disappear track query is set -1.
  128. labels = []
  129. for gt_per_img, (_, J) in zip(gt_instances, indices):
  130. labels_per_img = torch.ones_like(J)
  131. # set labels of track-appear slots to 0.
  132. if len(gt_per_img) > 0:
  133. labels_per_img[J != -1] = gt_per_img.labels[J[J != -1]]
  134. labels.append(labels_per_img)
  135. target_classes_o = torch.cat(labels)
  136. target_classes[idx] = target_classes_o
  137. if self.focal_loss:
  138. gt_labels_target = F.one_hot(target_classes, num_classes=self.num_classes + 1)[:, :, :-1] # no loss for the last (background) class
  139. gt_labels_target = gt_labels_target.to(src_logits)
  140. loss_ce = sigmoid_focal_loss(src_logits.flatten(1),
  141. gt_labels_target.flatten(1),
  142. alpha=0.25,
  143. gamma=2,
  144. num_boxes=num_boxes, mean_in_dim1=False)
  145. loss_ce = loss_ce.sum()
  146. else:
  147. loss_ce = F.cross_entropy(src_logits.transpose(1, 2), target_classes, self.empty_weight)
  148. losses = {'loss_ce': loss_ce}
  149. if log:
  150. # TODO this should probably be a separate loss, not hacked in this one here
  151. losses['class_error'] = 100 - accuracy(src_logits[idx], target_classes_o)[0]
  152. return losses
  153. def match_for_single_frame(self, outputs: dict):
  154. outputs_without_aux = {k: v for k, v in outputs.items() if k != 'aux_outputs'}
  155. gt_instances_i = self.gt_instances[self._current_frame_idx] # gt instances of i-th image.
  156. track_instances: Instances = outputs_without_aux['track_instances']
  157. pred_logits_i = track_instances.pred_logits # predicted logits of i-th image.
  158. pred_boxes_i = track_instances.pred_boxes # predicted boxes of i-th image.
  159. obj_idxes = gt_instances_i.obj_ids
  160. obj_idxes_list = obj_idxes.detach().cpu().numpy().tolist()
  161. obj_idx_to_gt_idx = {obj_idx: gt_idx for gt_idx, obj_idx in enumerate(obj_idxes_list)}
  162. outputs_i = {
  163. 'pred_logits': pred_logits_i.unsqueeze(0),
  164. 'pred_boxes': pred_boxes_i.unsqueeze(0),
  165. }
  166. # step1. inherit and update the previous tracks.
  167. num_disappear_track = 0
  168. for j in range(len(track_instances)):
  169. obj_id = track_instances.obj_idxes[j].item()
  170. # set new target idx.
  171. if obj_id >= 0:
  172. if obj_id in obj_idx_to_gt_idx:
  173. track_instances.matched_gt_idxes[j] = obj_idx_to_gt_idx[obj_id]
  174. else:
  175. num_disappear_track += 1
  176. track_instances.matched_gt_idxes[j] = -1 # track-disappear case.
  177. else:
  178. track_instances.matched_gt_idxes[j] = -1
  179. full_track_idxes = torch.arange(len(track_instances), dtype=torch.long).to(pred_logits_i.device)
  180. matched_track_idxes = (track_instances.obj_idxes >= 0) # occu
  181. prev_matched_indices = torch.stack(
  182. [full_track_idxes[matched_track_idxes], track_instances.matched_gt_idxes[matched_track_idxes]], dim=1).to(
  183. pred_logits_i.device)
  184. # step2. select the unmatched slots.
  185. # note that the FP tracks whose obj_idxes are -2 will not be selected here.
  186. unmatched_track_idxes = full_track_idxes[track_instances.obj_idxes == -1]
  187. # step3. select the untracked gt instances (new tracks).
  188. tgt_indexes = track_instances.matched_gt_idxes
  189. tgt_indexes = tgt_indexes[tgt_indexes != -1]
  190. tgt_state = torch.zeros(len(gt_instances_i)).to(pred_logits_i.device)
  191. tgt_state[tgt_indexes] = 1
  192. untracked_tgt_indexes = torch.arange(len(gt_instances_i)).to(pred_logits_i.device)[tgt_state == 0]
  193. # untracked_tgt_indexes = select_unmatched_indexes(tgt_indexes, len(gt_instances_i))
  194. untracked_gt_instances = gt_instances_i[untracked_tgt_indexes]
  195. def match_for_single_decoder_layer(unmatched_outputs, matcher):
  196. new_track_indices = matcher(unmatched_outputs,
  197. [untracked_gt_instances]) # list[tuple(src_idx, tgt_idx)]
  198. src_idx = new_track_indices[0][0]
  199. tgt_idx = new_track_indices[0][1]
  200. # concat src and tgt.
  201. new_matched_indices = torch.stack([unmatched_track_idxes[src_idx], untracked_tgt_indexes[tgt_idx]],
  202. dim=1).to(pred_logits_i.device)
  203. return new_matched_indices
  204. # step4. do matching between the unmatched slots and GTs.
  205. unmatched_outputs = {
  206. 'pred_logits': track_instances.pred_logits[unmatched_track_idxes].unsqueeze(0),
  207. 'pred_boxes': track_instances.pred_boxes[unmatched_track_idxes].unsqueeze(0),
  208. }
  209. new_matched_indices = match_for_single_decoder_layer(unmatched_outputs, self.matcher)
  210. # step5. update obj_idxes according to the new matching result.
  211. track_instances.obj_idxes[new_matched_indices[:, 0]] = gt_instances_i.obj_ids[new_matched_indices[:, 1]].long()
  212. track_instances.matched_gt_idxes[new_matched_indices[:, 0]] = new_matched_indices[:, 1]
  213. # step6. calculate iou.
  214. active_idxes = (track_instances.obj_idxes >= 0) & (track_instances.matched_gt_idxes >= 0)
  215. active_track_boxes = track_instances.pred_boxes[active_idxes]
  216. if len(active_track_boxes) > 0:
  217. gt_boxes = gt_instances_i.boxes[track_instances.matched_gt_idxes[active_idxes]]
  218. active_track_boxes = box_ops.box_cxcywh_to_xyxy(active_track_boxes)
  219. gt_boxes = box_ops.box_cxcywh_to_xyxy(gt_boxes)
  220. track_instances.iou[active_idxes] = matched_boxlist_iou(Boxes(active_track_boxes), Boxes(gt_boxes))
  221. # step7. merge the unmatched pairs and the matched pairs.
  222. matched_indices = torch.cat([new_matched_indices, prev_matched_indices], dim=0)
  223. # step8. calculate losses.
  224. self.num_samples += len(gt_instances_i) + num_disappear_track
  225. self.sample_device = pred_logits_i.device
  226. for loss in self.losses:
  227. new_track_loss = self.get_loss(loss,
  228. outputs=outputs_i,
  229. gt_instances=[gt_instances_i],
  230. indices=[(matched_indices[:, 0], matched_indices[:, 1])],
  231. num_boxes=1)
  232. self.losses_dict.update(
  233. {'frame_{}_{}'.format(self._current_frame_idx, key): value for key, value in new_track_loss.items()})
  234. if 'aux_outputs' in outputs:
  235. for i, aux_outputs in enumerate(outputs['aux_outputs']):
  236. unmatched_outputs_layer = {
  237. 'pred_logits': aux_outputs['pred_logits'][0, unmatched_track_idxes].unsqueeze(0),
  238. 'pred_boxes': aux_outputs['pred_boxes'][0, unmatched_track_idxes].unsqueeze(0),
  239. }
  240. new_matched_indices_layer = match_for_single_decoder_layer(unmatched_outputs_layer, self.matcher)
  241. matched_indices_layer = torch.cat([new_matched_indices_layer, prev_matched_indices], dim=0)
  242. for loss in self.losses:
  243. if loss == 'masks':
  244. # Intermediate masks losses are too costly to compute, we ignore them.
  245. continue
  246. l_dict = self.get_loss(loss,
  247. aux_outputs,
  248. gt_instances=[gt_instances_i],
  249. indices=[(matched_indices_layer[:, 0], matched_indices_layer[:, 1])],
  250. num_boxes=1, )
  251. self.losses_dict.update(
  252. {'frame_{}_aux{}_{}'.format(self._current_frame_idx, i, key): value for key, value in
  253. l_dict.items()})
  254. self._step()
  255. return track_instances
  256. def forward(self, outputs, input_data: dict):
  257. # losses of each frame are calculated during the model's forwarding and are outputted by the model as outputs['losses_dict].
  258. losses = outputs.pop("losses_dict")
  259. num_samples = self.get_num_boxes(self.num_samples)
  260. for loss_name, loss in losses.items():
  261. losses[loss_name] /= num_samples
  262. return losses
  263. class RuntimeTrackerBase(object):
  264. def __init__(self, score_thresh=0.8, filter_score_thresh=0.6, miss_tolerance=5):
  265. self.score_thresh = score_thresh
  266. self.filter_score_thresh = filter_score_thresh
  267. self.miss_tolerance = miss_tolerance
  268. self.max_obj_id = 0
  269. def clear(self):
  270. self.max_obj_id = 0
  271. def update(self, track_instances: Instances):
  272. track_instances.disappear_time[track_instances.scores >= self.score_thresh] = 0
  273. for i in range(len(track_instances)):
  274. if track_instances.obj_idxes[i] == -1 and track_instances.scores[i] >= self.score_thresh:
  275. # print("track {} has score {}, assign obj_id {}".format(i, track_instances.scores[i], self.max_obj_id))
  276. track_instances.obj_idxes[i] = self.max_obj_id
  277. self.max_obj_id += 1
  278. elif track_instances.obj_idxes[i] >= 0 and track_instances.scores[i] < self.filter_score_thresh:
  279. track_instances.disappear_time[i] += 1
  280. if track_instances.disappear_time[i] >= self.miss_tolerance:
  281. # Set the obj_id to -1.
  282. # Then this track will be removed by TrackEmbeddingLayer.
  283. track_instances.obj_idxes[i] = -1
  284. class TrackerPostProcess(nn.Module):
  285. """ This module converts the model's output into the format expected by the coco api"""
  286. def __init__(self):
  287. super().__init__()
  288. @torch.no_grad()
  289. def forward(self, track_instances: Instances, target_size) -> Instances:
  290. """ Perform the computation
  291. Parameters:
  292. outputs: raw outputs of the model
  293. target_sizes: tensor of dimension [batch_size x 2] containing the size of each images of the batch
  294. For evaluation, this must be the original image size (before any data augmentation)
  295. For visualization, this should be the image size after data augment, but before padding
  296. """
  297. out_logits = track_instances.pred_logits
  298. out_bbox = track_instances.pred_boxes
  299. prob = out_logits.sigmoid()
  300. # prob = out_logits[...,:1].sigmoid()
  301. scores, labels = prob.max(-1)
  302. # convert to [x0, y0, x1, y1] format
  303. boxes = box_ops.box_cxcywh_to_xyxy(out_bbox)
  304. # and from relative [0, 1] to absolute [0, height] coordinates
  305. img_h, img_w = target_size
  306. scale_fct = torch.Tensor([img_w, img_h, img_w, img_h]).to(boxes)
  307. boxes = boxes * scale_fct[None, :]
  308. track_instances.boxes = boxes
  309. track_instances.scores = scores
  310. track_instances.labels = labels
  311. # track_instances.remove('pred_logits')
  312. # track_instances.remove('pred_boxes')
  313. return track_instances
  314. def _get_clones(module, N):
  315. return nn.ModuleList([copy.deepcopy(module) for i in range(N)])
  316. class MOTR(nn.Module):
  317. def __init__(self, backbone, transformer, num_classes, num_queries, num_feature_levels, criterion, track_embed,
  318. aux_loss=True, with_box_refine=False, two_stage=False, memory_bank=None):
  319. """ Initializes the model.
  320. Parameters:
  321. backbone: torch module of the backbone to be used. See backbone.py
  322. transformer: torch module of the transformer architecture. See transformer.py
  323. num_classes: number of object classes
  324. num_queries: number of object queries, ie detection slot. This is the maximal number of objects
  325. DETR can detect in a single image. For COCO, we recommend 100 queries.
  326. aux_loss: True if auxiliary decoding losses (loss at each decoder layer) are to be used.
  327. with_box_refine: iterative bounding box refinement
  328. two_stage: two-stage Deformable DETR
  329. """
  330. super().__init__()
  331. self.num_queries = num_queries
  332. self.track_embed = track_embed
  333. self.transformer = transformer
  334. hidden_dim = transformer.d_model
  335. self.num_classes = num_classes
  336. self.class_embed = nn.Linear(hidden_dim, num_classes)
  337. self.bbox_embed = MLP(hidden_dim, hidden_dim, 4, 3)
  338. self.num_feature_levels = num_feature_levels
  339. if not two_stage:
  340. self.query_embed = nn.Embedding(num_queries, hidden_dim * 2)
  341. if num_feature_levels > 1:
  342. num_backbone_outs = len(backbone.strides)
  343. input_proj_list = []
  344. for _ in range(num_backbone_outs):
  345. in_channels = backbone.num_channels[_]
  346. input_proj_list.append(nn.Sequential(
  347. nn.Conv2d(in_channels, hidden_dim, kernel_size=1),
  348. nn.GroupNorm(32, hidden_dim),
  349. ))
  350. for _ in range(num_feature_levels - num_backbone_outs):
  351. input_proj_list.append(nn.Sequential(
  352. nn.Conv2d(in_channels, hidden_dim, kernel_size=3, stride=2, padding=1),
  353. nn.GroupNorm(32, hidden_dim),
  354. ))
  355. in_channels = hidden_dim
  356. self.input_proj = nn.ModuleList(input_proj_list)
  357. else:
  358. self.input_proj = nn.ModuleList([
  359. nn.Sequential(
  360. nn.Conv2d(backbone.num_channels[0], hidden_dim, kernel_size=1),
  361. nn.GroupNorm(32, hidden_dim),
  362. )])
  363. self.backbone = backbone
  364. self.aux_loss = aux_loss
  365. self.with_box_refine = with_box_refine
  366. self.two_stage = two_stage
  367. prior_prob = 0.01
  368. bias_value = -math.log((1 - prior_prob) / prior_prob)
  369. self.class_embed.bias.data = torch.ones(num_classes) * bias_value
  370. nn.init.constant_(self.bbox_embed.layers[-1].weight.data, 0)
  371. nn.init.constant_(self.bbox_embed.layers[-1].bias.data, 0)
  372. for proj in self.input_proj:
  373. nn.init.xavier_uniform_(proj[0].weight, gain=1)
  374. nn.init.constant_(proj[0].bias, 0)
  375. # if two-stage, the last class_embed and bbox_embed is for region proposal generation
  376. num_pred = (transformer.decoder.num_layers + 1) if two_stage else transformer.decoder.num_layers
  377. if with_box_refine:
  378. self.class_embed = _get_clones(self.class_embed, num_pred)
  379. self.bbox_embed = _get_clones(self.bbox_embed, num_pred)
  380. nn.init.constant_(self.bbox_embed[0].layers[-1].bias.data[2:], -2.0)
  381. # hack implementation for iterative bounding box refinement
  382. self.transformer.decoder.bbox_embed = self.bbox_embed
  383. else:
  384. nn.init.constant_(self.bbox_embed.layers[-1].bias.data[2:], -2.0)
  385. self.class_embed = nn.ModuleList([self.class_embed for _ in range(num_pred)])
  386. self.bbox_embed = nn.ModuleList([self.bbox_embed for _ in range(num_pred)])
  387. self.transformer.decoder.bbox_embed = None
  388. if two_stage:
  389. # hack implementation for two-stage
  390. self.transformer.decoder.class_embed = self.class_embed
  391. for box_embed in self.bbox_embed:
  392. nn.init.constant_(box_embed.layers[-1].bias.data[2:], 0.0)
  393. self.post_process = TrackerPostProcess()
  394. self.track_base = RuntimeTrackerBase()
  395. self.criterion = criterion
  396. self.memory_bank = memory_bank
  397. self.mem_bank_len = 0 if memory_bank is None else memory_bank.max_his_length
  398. def _generate_empty_tracks(self):
  399. track_instances = Instances((1, 1))
  400. num_queries, dim = self.query_embed.weight.shape # (300, 512)
  401. device = self.query_embed.weight.device
  402. track_instances.ref_pts = self.transformer.reference_points(self.query_embed.weight[:, :dim // 2])
  403. track_instances.query_pos = self.query_embed.weight
  404. track_instances.output_embedding = torch.zeros((num_queries, dim >> 1), device=device)
  405. track_instances.obj_idxes = torch.full((len(track_instances),), -1, dtype=torch.long, device=device)
  406. track_instances.matched_gt_idxes = torch.full((len(track_instances),), -1, dtype=torch.long, device=device)
  407. track_instances.disappear_time = torch.zeros((len(track_instances), ), dtype=torch.long, device=device)
  408. track_instances.iou = torch.zeros((len(track_instances),), dtype=torch.float, device=device)
  409. track_instances.scores = torch.zeros((len(track_instances),), dtype=torch.float, device=device)
  410. track_instances.track_scores = torch.zeros((len(track_instances),), dtype=torch.float, device=device)
  411. track_instances.pred_boxes = torch.zeros((len(track_instances), 4), dtype=torch.float, device=device)
  412. track_instances.pred_logits = torch.zeros((len(track_instances), self.num_classes), dtype=torch.float, device=device)
  413. mem_bank_len = self.mem_bank_len
  414. track_instances.mem_bank = torch.zeros((len(track_instances), mem_bank_len, dim // 2), dtype=torch.float32, device=device)
  415. track_instances.mem_padding_mask = torch.ones((len(track_instances), mem_bank_len), dtype=torch.bool, device=device)
  416. track_instances.save_period = torch.zeros((len(track_instances), ), dtype=torch.float32, device=device)
  417. return track_instances.to(self.query_embed.weight.device)
  418. def clear(self):
  419. self.track_base.clear()
  420. @torch.jit.unused
  421. def _set_aux_loss(self, outputs_class, outputs_coord):
  422. # this is a workaround to make torchscript happy, as torchscript
  423. # doesn't support dictionary with non-homogeneous values, such
  424. # as a dict having both a Tensor and a list.
  425. return [{'pred_logits': a, 'pred_boxes': b, }
  426. for a, b in zip(outputs_class[:-1], outputs_coord[:-1])]
  427. def _forward_single_image(self, samples, track_instances: Instances):
  428. features, pos = self.backbone(samples)
  429. src, mask = features[-1].decompose()
  430. assert mask is not None
  431. srcs = []
  432. masks = []
  433. for l, feat in enumerate(features):
  434. src, mask = feat.decompose()
  435. srcs.append(self.input_proj[l](src))
  436. masks.append(mask)
  437. assert mask is not None
  438. if self.num_feature_levels > len(srcs):
  439. _len_srcs = len(srcs)
  440. for l in range(_len_srcs, self.num_feature_levels):
  441. if l == _len_srcs:
  442. src = self.input_proj[l](features[-1].tensors)
  443. else:
  444. src = self.input_proj[l](srcs[-1])
  445. m = samples.mask
  446. mask = F.interpolate(m[None].float(), size=src.shape[-2:]).to(torch.bool)[0]
  447. pos_l = self.backbone[1](NestedTensor(src, mask)).to(src.dtype)
  448. srcs.append(src)
  449. masks.append(mask)
  450. pos.append(pos_l)
  451. hs, init_reference, inter_references, enc_outputs_class, enc_outputs_coord_unact = self.transformer(srcs, masks, pos, track_instances.query_pos, ref_pts=track_instances.ref_pts)
  452. outputs_classes = []
  453. outputs_coords = []
  454. for lvl in range(hs.shape[0]):
  455. if lvl == 0:
  456. reference = init_reference
  457. else:
  458. reference = inter_references[lvl - 1]
  459. reference = inverse_sigmoid(reference)
  460. outputs_class = self.class_embed[lvl](hs[lvl])
  461. tmp = self.bbox_embed[lvl](hs[lvl])
  462. if reference.shape[-1] == 4:
  463. tmp += reference
  464. else:
  465. assert reference.shape[-1] == 2
  466. tmp[..., :2] += reference
  467. outputs_coord = tmp.sigmoid()
  468. outputs_classes.append(outputs_class)
  469. outputs_coords.append(outputs_coord)
  470. outputs_class = torch.stack(outputs_classes)
  471. outputs_coord = torch.stack(outputs_coords)
  472. ref_pts_all = torch.cat([init_reference[None], inter_references[:, :, :, :2]], dim=0)
  473. out = {'pred_logits': outputs_class[-1], 'pred_boxes': outputs_coord[-1], 'ref_pts': ref_pts_all[5]}
  474. if self.aux_loss:
  475. out['aux_outputs'] = self._set_aux_loss(outputs_class, outputs_coord)
  476. with torch.no_grad():
  477. if self.training:
  478. track_scores = outputs_class[-1, 0, :].sigmoid().max(dim=-1).values
  479. else:
  480. track_scores = outputs_class[-1, 0, :, 0].sigmoid()
  481. track_instances.scores = track_scores
  482. track_instances.pred_logits = outputs_class[-1, 0]
  483. track_instances.pred_boxes = outputs_coord[-1, 0]
  484. track_instances.output_embedding = hs[-1, 0]
  485. if self.training:
  486. # the track id will be assigned by the mather.
  487. out['track_instances'] = track_instances
  488. track_instances = self.criterion.match_for_single_frame(out)
  489. else:
  490. # each track will be assigned an unique global id by the track base.
  491. self.track_base.update(track_instances)
  492. if self.memory_bank is not None:
  493. track_instances = self.memory_bank(track_instances)
  494. # track_instances.track_scores = track_instances.track_scores[..., 0]
  495. # track_instances.scores = track_instances.track_scores.sigmoid()
  496. if self.training:
  497. self.criterion.calc_loss_for_track_scores(track_instances)
  498. tmp = {}
  499. tmp['init_track_instances'] = self._generate_empty_tracks()
  500. tmp['track_instances'] = track_instances
  501. out_track_instances = self.track_embed(tmp)
  502. out['track_instances'] = out_track_instances
  503. return out
  504. @torch.no_grad()
  505. def inference_single_image(self, img, ori_img_size, track_instances=None):
  506. if not isinstance(img, NestedTensor):
  507. img = nested_tensor_from_tensor_list(img)
  508. # if track_instances is None:
  509. # track_instances = self._generate_empty_tracks()
  510. track_instances = self._generate_empty_tracks()
  511. res = self._forward_single_image(img, track_instances=track_instances)
  512. track_instances = res['track_instances']
  513. track_instances = self.post_process(track_instances, ori_img_size)
  514. ret = {'track_instances': track_instances}
  515. if 'ref_pts' in res:
  516. ref_pts = res['ref_pts']
  517. img_h, img_w = ori_img_size
  518. scale_fct = torch.Tensor([img_w, img_h]).to(ref_pts)
  519. ref_pts = ref_pts * scale_fct[None]
  520. ret['ref_pts'] = ref_pts
  521. return ret
  522. def forward(self, data: dict):
  523. if self.training:
  524. self.criterion.initialize_for_single_clip(data['gt_instances'])
  525. frames = data['imgs'] # list of Tensor.
  526. outputs = {
  527. 'pred_logits': [],
  528. 'pred_boxes': [],
  529. }
  530. track_instances = self._generate_empty_tracks()
  531. for frame in frames:
  532. if not isinstance(frame, NestedTensor):
  533. frame = nested_tensor_from_tensor_list([frame])
  534. frame_res = self._forward_single_image(frame, track_instances)
  535. track_instances = frame_res['track_instances']
  536. outputs['pred_logits'].append(frame_res['pred_logits'])
  537. outputs['pred_boxes'].append(frame_res['pred_boxes'])
  538. if not self.training:
  539. outputs['track_instances'] = track_instances
  540. else:
  541. outputs['losses_dict'] = self.criterion.losses_dict
  542. return outputs
  543. def build(args):
  544. dataset_to_num_classes = {
  545. 'coco': 91,
  546. 'coco_panoptic': 250,
  547. 'e2e_mot': 1,
  548. 'e2e_joint': 1,
  549. 'e2e_static_mot': 1
  550. }
  551. assert args.dataset_file in dataset_to_num_classes
  552. num_classes = dataset_to_num_classes[args.dataset_file]
  553. device = torch.device(args.device)
  554. backbone = build_backbone(args)
  555. transformer = build_deforamble_transformer(args)
  556. d_model = transformer.d_model
  557. hidden_dim = args.dim_feedforward
  558. query_interaction_layer = build_query_interaction_layer(args, args.query_interaction_layer, d_model, hidden_dim, d_model*2)
  559. img_matcher = build_matcher(args)
  560. num_frames_per_batch = max(args.sampler_lengths)
  561. weight_dict = {}
  562. for i in range(num_frames_per_batch):
  563. weight_dict.update({"frame_{}_loss_ce".format(i): args.cls_loss_coef,
  564. 'frame_{}_loss_bbox'.format(i): args.bbox_loss_coef,
  565. 'frame_{}_loss_giou'.format(i): args.giou_loss_coef,
  566. })
  567. # TODO this is a hack
  568. if args.aux_loss:
  569. for i in range(num_frames_per_batch):
  570. for j in range(args.dec_layers - 1):
  571. weight_dict.update({"frame_{}_aux{}_loss_ce".format(i, j): args.cls_loss_coef,
  572. 'frame_{}_aux{}_loss_bbox'.format(i, j): args.bbox_loss_coef,
  573. 'frame_{}_aux{}_loss_giou'.format(i, j): args.giou_loss_coef,
  574. })
  575. if args.memory_bank_type is not None and len(args.memory_bank_type) > 0:
  576. memory_bank = build_memory_bank(args, d_model, hidden_dim, d_model * 2)
  577. for i in range(num_frames_per_batch):
  578. weight_dict.update({"frame_{}_track_loss_ce".format(i): args.cls_loss_coef})
  579. else:
  580. memory_bank = None
  581. losses = ['labels', 'boxes']
  582. criterion = ClipMatcher(num_classes, matcher=img_matcher, weight_dict=weight_dict, losses=losses)
  583. criterion.to(device)
  584. postprocessors = {}
  585. model = MOTR(
  586. backbone,
  587. transformer,
  588. track_embed=query_interaction_layer,
  589. num_feature_levels=args.num_feature_levels,
  590. num_classes=num_classes,
  591. num_queries=args.num_queries,
  592. aux_loss=args.aux_loss,
  593. criterion=criterion,
  594. with_box_refine=args.with_box_refine,
  595. two_stage=args.two_stage,
  596. memory_bank=memory_bank,
  597. )
  598. return model, criterion, postprocessors