fairmot_embedding_head.py 4.3 KB

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