fairmot_embedding_head.py 4.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117
  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 import ParamAttr
  20. from paddle.nn.initializer import KaimingUniform, Uniform
  21. from paddlex.ppdet.core.workspace import register
  22. from paddlex.ppdet.modeling.heads.centernet_head import ConvLayer
  23. __all__ = ['FairMOTEmbeddingHead']
  24. @register
  25. class FairMOTEmbeddingHead(nn.Layer):
  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_identifiers (int): the number of identifiers, 14455 by default.
  32. """
  33. def __init__(self,
  34. in_channels,
  35. ch_head=256,
  36. ch_emb=128,
  37. num_identifiers=14455):
  38. super(FairMOTEmbeddingHead, self).__init__()
  39. self.reid = nn.Sequential(
  40. ConvLayer(
  41. in_channels, ch_head, kernel_size=3, padding=1, bias=True),
  42. nn.ReLU(),
  43. ConvLayer(
  44. ch_head, ch_emb, kernel_size=1, stride=1, padding=0,
  45. bias=True))
  46. param_attr = paddle.ParamAttr(initializer=KaimingUniform())
  47. bound = 1 / math.sqrt(ch_emb)
  48. bias_attr = paddle.ParamAttr(initializer=Uniform(-bound, bound))
  49. self.classifier = nn.Linear(
  50. ch_emb,
  51. num_identifiers,
  52. weight_attr=param_attr,
  53. bias_attr=bias_attr)
  54. self.reid_loss = nn.CrossEntropyLoss(ignore_index=-1, reduction='sum')
  55. # When num_identifiers is 1, emb_scale is set as 1
  56. self.emb_scale = math.sqrt(2) * math.log(
  57. num_identifiers - 1) if num_identifiers > 1 else 1
  58. @classmethod
  59. def from_config(cls, cfg, input_shape):
  60. if isinstance(input_shape, (list, tuple)):
  61. input_shape = input_shape[0]
  62. return {'in_channels': input_shape.channels}
  63. def forward(self, feat, inputs):
  64. reid_feat = self.reid(feat)
  65. if self.training:
  66. loss = self.get_loss(reid_feat, inputs)
  67. return loss
  68. else:
  69. reid_feat = F.normalize(reid_feat)
  70. return reid_feat
  71. def get_loss(self, feat, inputs):
  72. index = inputs['index']
  73. mask = inputs['index_mask']
  74. target = inputs['reid']
  75. target = paddle.masked_select(target, mask > 0)
  76. target = paddle.unsqueeze(target, 1)
  77. feat = paddle.transpose(feat, perm=[0, 2, 3, 1])
  78. feat_n, feat_h, feat_w, feat_c = feat.shape
  79. feat = paddle.reshape(feat, shape=[feat_n, -1, feat_c])
  80. index = paddle.unsqueeze(index, 2)
  81. batch_inds = list()
  82. for i in range(feat_n):
  83. batch_ind = paddle.full(
  84. shape=[1, index.shape[1], 1], fill_value=i, dtype='int64')
  85. batch_inds.append(batch_ind)
  86. batch_inds = paddle.concat(batch_inds, axis=0)
  87. index = paddle.concat(x=[batch_inds, index], axis=2)
  88. feat = paddle.gather_nd(feat, index=index)
  89. mask = paddle.unsqueeze(mask, axis=2)
  90. mask = paddle.expand_as(mask, feat)
  91. mask.stop_gradient = True
  92. feat = paddle.masked_select(feat, mask > 0)
  93. feat = paddle.reshape(feat, shape=[-1, feat_c])
  94. feat = F.normalize(feat)
  95. feat = self.emb_scale * feat
  96. logit = self.classifier(feat)
  97. target.stop_gradient = True
  98. loss = self.reid_loss(logit, target)
  99. valid = (target != self.reid_loss.ignore_index)
  100. valid.stop_gradient = True
  101. count = paddle.sum((paddle.cast(valid, dtype=np.int32)))
  102. count.stop_gradient = True
  103. if count > 0:
  104. loss = loss / count
  105. return loss