fairmot_embedding_head.py 8.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224
  1. # Copyright (c) 2021 PaddlePaddle Authors. All Rights Reserved.
  2. #
  3. # Licensed under the Apache License, Version 2.0 (the "License");
  4. # you may not use this file except in compliance with the License.
  5. # You may obtain a copy of the License at
  6. #
  7. # http://www.apache.org/licenses/LICENSE-2.0
  8. #
  9. # Unless required by applicable law or agreed to in writing, software
  10. # distributed under the License is distributed on an "AS IS" BASIS,
  11. # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  12. # See the License for the specific language governing permissions and
  13. # limitations under the License.
  14. import numpy as np
  15. import math
  16. import paddle
  17. import paddle.nn as nn
  18. import paddle.nn.functional as F
  19. from paddle.nn.initializer import KaimingUniform, Uniform
  20. from ppdet.core.workspace import register
  21. from ppdet.modeling.heads.centernet_head import ConvLayer
  22. __all__ = ['FairMOTEmbeddingHead']
  23. @register
  24. class FairMOTEmbeddingHead(nn.Layer):
  25. __shared__ = ['num_classes']
  26. """
  27. Args:
  28. in_channels (int): the channel number of input to FairMOTEmbeddingHead.
  29. ch_head (int): the channel of features before fed into embedding, 256 by default.
  30. ch_emb (int): the channel of the embedding feature, 128 by default.
  31. num_identities_dict (dict): the number of identities of each category,
  32. support single class and multi-calss, {0: 14455} as default.
  33. """
  34. def __init__(self,
  35. in_channels,
  36. ch_head=256,
  37. ch_emb=128,
  38. num_classes=1,
  39. num_identities_dict={0: 14455}):
  40. super(FairMOTEmbeddingHead, self).__init__()
  41. assert num_classes >= 1
  42. self.num_classes = num_classes
  43. self.ch_emb = ch_emb
  44. self.num_identities_dict = num_identities_dict
  45. self.reid = nn.Sequential(
  46. ConvLayer(
  47. in_channels, ch_head, kernel_size=3, padding=1, bias=True),
  48. nn.ReLU(),
  49. ConvLayer(
  50. ch_head, ch_emb, kernel_size=1, stride=1, padding=0, bias=True))
  51. param_attr = paddle.ParamAttr(initializer=KaimingUniform())
  52. bound = 1 / math.sqrt(ch_emb)
  53. bias_attr = paddle.ParamAttr(initializer=Uniform(-bound, bound))
  54. self.reid_loss = nn.CrossEntropyLoss(ignore_index=-1, reduction='sum')
  55. if num_classes == 1:
  56. nID = self.num_identities_dict[0] # single class
  57. self.classifier = nn.Linear(
  58. ch_emb, nID, weight_attr=param_attr, bias_attr=bias_attr)
  59. # When num_identities(nID) is 1, emb_scale is set as 1
  60. self.emb_scale = math.sqrt(2) * math.log(nID - 1) if nID > 1 else 1
  61. else:
  62. self.classifiers = dict()
  63. self.emb_scale_dict = dict()
  64. for cls_id, nID in self.num_identities_dict.items():
  65. self.classifiers[str(cls_id)] = nn.Linear(
  66. ch_emb, nID, weight_attr=param_attr, bias_attr=bias_attr)
  67. # When num_identities(nID) is 1, emb_scale is set as 1
  68. self.emb_scale_dict[str(cls_id)] = math.sqrt(2) * math.log(
  69. nID - 1) if nID > 1 else 1
  70. @classmethod
  71. def from_config(cls, cfg, input_shape):
  72. if isinstance(input_shape, (list, tuple)):
  73. input_shape = input_shape[0]
  74. return {'in_channels': input_shape.channels}
  75. def process_by_class(self, bboxes, embedding, bbox_inds, topk_clses):
  76. pred_dets, pred_embs = [], []
  77. for cls_id in range(self.num_classes):
  78. inds_masks = topk_clses == cls_id
  79. inds_masks = paddle.cast(inds_masks, 'float32')
  80. pos_num = inds_masks.sum().numpy()
  81. if pos_num == 0:
  82. continue
  83. cls_inds_mask = inds_masks > 0
  84. bbox_mask = paddle.nonzero(cls_inds_mask)
  85. cls_bboxes = paddle.gather_nd(bboxes, bbox_mask)
  86. pred_dets.append(cls_bboxes)
  87. cls_inds = paddle.masked_select(bbox_inds, cls_inds_mask)
  88. cls_inds = cls_inds.unsqueeze(-1)
  89. cls_embedding = paddle.gather_nd(embedding, cls_inds)
  90. pred_embs.append(cls_embedding)
  91. return paddle.concat(pred_dets), paddle.concat(pred_embs)
  92. def forward(self,
  93. neck_feat,
  94. inputs,
  95. bboxes=None,
  96. bbox_inds=None,
  97. topk_clses=None):
  98. reid_feat = self.reid(neck_feat)
  99. if self.training:
  100. if self.num_classes == 1:
  101. loss = self.get_loss(reid_feat, inputs)
  102. else:
  103. loss = self.get_mc_loss(reid_feat, inputs)
  104. return loss
  105. else:
  106. assert bboxes is not None and bbox_inds is not None
  107. reid_feat = F.normalize(reid_feat)
  108. embedding = paddle.transpose(reid_feat, [0, 2, 3, 1])
  109. embedding = paddle.reshape(embedding, [-1, self.ch_emb])
  110. # embedding shape: [bs * h * w, ch_emb]
  111. if self.num_classes == 1:
  112. pred_dets = bboxes
  113. pred_embs = paddle.gather(embedding, bbox_inds)
  114. else:
  115. pred_dets, pred_embs = self.process_by_class(
  116. bboxes, embedding, bbox_inds, topk_clses)
  117. return pred_dets, pred_embs
  118. def get_loss(self, feat, inputs):
  119. index = inputs['index']
  120. mask = inputs['index_mask']
  121. target = inputs['reid']
  122. target = paddle.masked_select(target, mask > 0)
  123. target = paddle.unsqueeze(target, 1)
  124. feat = paddle.transpose(feat, perm=[0, 2, 3, 1])
  125. feat_n, feat_h, feat_w, feat_c = feat.shape
  126. feat = paddle.reshape(feat, shape=[feat_n, -1, feat_c])
  127. index = paddle.unsqueeze(index, 2)
  128. batch_inds = list()
  129. for i in range(feat_n):
  130. batch_ind = paddle.full(
  131. shape=[1, index.shape[1], 1], fill_value=i, dtype='int64')
  132. batch_inds.append(batch_ind)
  133. batch_inds = paddle.concat(batch_inds, axis=0)
  134. index = paddle.concat(x=[batch_inds, index], axis=2)
  135. feat = paddle.gather_nd(feat, index=index)
  136. mask = paddle.unsqueeze(mask, axis=2)
  137. mask = paddle.expand_as(mask, feat)
  138. mask.stop_gradient = True
  139. feat = paddle.masked_select(feat, mask > 0)
  140. feat = paddle.reshape(feat, shape=[-1, feat_c])
  141. feat = F.normalize(feat)
  142. feat = self.emb_scale * feat
  143. logit = self.classifier(feat)
  144. target.stop_gradient = True
  145. loss = self.reid_loss(logit, target)
  146. valid = (target != self.reid_loss.ignore_index)
  147. valid.stop_gradient = True
  148. count = paddle.sum((paddle.cast(valid, dtype=np.int32)))
  149. count.stop_gradient = True
  150. if count > 0:
  151. loss = loss / count
  152. return loss
  153. def get_mc_loss(self, feat, inputs):
  154. # feat.shape = [bs, ch_emb, h, w]
  155. assert 'cls_id_map' in inputs and 'cls_tr_ids' in inputs
  156. index = inputs['index']
  157. mask = inputs['index_mask']
  158. cls_id_map = inputs['cls_id_map'] # [bs, h, w]
  159. cls_tr_ids = inputs['cls_tr_ids'] # [bs, num_classes, h, w]
  160. feat = paddle.transpose(feat, perm=[0, 2, 3, 1])
  161. feat_n, feat_h, feat_w, feat_c = feat.shape
  162. feat = paddle.reshape(feat, shape=[feat_n, -1, feat_c])
  163. index = paddle.unsqueeze(index, 2)
  164. batch_inds = list()
  165. for i in range(feat_n):
  166. batch_ind = paddle.full(
  167. shape=[1, index.shape[1], 1], fill_value=i, dtype='int64')
  168. batch_inds.append(batch_ind)
  169. batch_inds = paddle.concat(batch_inds, axis=0)
  170. index = paddle.concat(x=[batch_inds, index], axis=2)
  171. feat = paddle.gather_nd(feat, index=index)
  172. mask = paddle.unsqueeze(mask, axis=2)
  173. mask = paddle.expand_as(mask, feat)
  174. mask.stop_gradient = True
  175. feat = paddle.masked_select(feat, mask > 0)
  176. feat = paddle.reshape(feat, shape=[-1, feat_c])
  177. reid_losses = 0
  178. for cls_id, id_num in self.num_identities_dict.items():
  179. # target
  180. cur_cls_tr_ids = paddle.reshape(
  181. cls_tr_ids[:, cls_id, :, :], shape=[feat_n, -1]) # [bs, h*w]
  182. cls_id_target = paddle.gather_nd(cur_cls_tr_ids, index=index)
  183. mask = inputs['index_mask']
  184. cls_id_target = paddle.masked_select(cls_id_target, mask > 0)
  185. cls_id_target.stop_gradient = True
  186. # feat
  187. cls_id_feat = self.emb_scale_dict[str(cls_id)] * F.normalize(feat)
  188. cls_id_pred = self.classifiers[str(cls_id)](cls_id_feat)
  189. loss = self.reid_loss(cls_id_pred, cls_id_target)
  190. valid = (cls_id_target != self.reid_loss.ignore_index)
  191. valid.stop_gradient = True
  192. count = paddle.sum((paddle.cast(valid, dtype=np.int32)))
  193. count.stop_gradient = True
  194. if count > 0:
  195. loss = loss / count
  196. reid_losses += loss
  197. return reid_losses