ttfnet.py 4.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132
  1. # Copyright (c) 2020 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. from __future__ import absolute_import
  15. from __future__ import division
  16. from __future__ import print_function
  17. from collections import OrderedDict
  18. from paddle import fluid
  19. from ppdet.experimental import mixed_precision_global_state
  20. from ppdet.core.workspace import register
  21. __all__ = ['TTFNet']
  22. @register
  23. class TTFNet(object):
  24. """
  25. TTFNet network, see https://arxiv.org/abs/1909.00700
  26. Args:
  27. backbone (object): backbone instance
  28. ttf_head (object): `TTFHead` instance
  29. num_classes (int): the number of classes, 80 by default.
  30. """
  31. __category__ = 'architecture'
  32. __inject__ = ['backbone', 'ttf_head']
  33. __shared__ = ['num_classes']
  34. def __init__(self, backbone, ttf_head='TTFHead', num_classes=80):
  35. super(TTFNet, self).__init__()
  36. self.backbone = backbone
  37. self.ttf_head = ttf_head
  38. self.num_classes = num_classes
  39. def build(self, feed_vars, mode='train', exclude_nms=False):
  40. im = feed_vars['image']
  41. mixed_precision_enabled = mixed_precision_global_state() is not None
  42. # cast inputs to FP16
  43. if mixed_precision_enabled:
  44. im = fluid.layers.cast(im, 'float16')
  45. body_feats = self.backbone(im)
  46. if isinstance(body_feats, OrderedDict):
  47. body_feat_names = list(body_feats.keys())
  48. body_feats = [body_feats[name] for name in body_feat_names]
  49. # cast features back to FP32
  50. if mixed_precision_enabled:
  51. body_feats = [fluid.layers.cast(v, 'float32') for v in body_feats]
  52. predict_hm, predict_wh = self.ttf_head.get_output(
  53. body_feats, 'ttf_head', is_test=mode == 'test')
  54. if mode == 'train':
  55. heatmap = feed_vars['ttf_heatmap']
  56. box_target = feed_vars['ttf_box_target']
  57. reg_weight = feed_vars['ttf_reg_weight']
  58. loss = self.ttf_head.get_loss(predict_hm, predict_wh, heatmap,
  59. box_target, reg_weight)
  60. total_loss = fluid.layers.sum(list(loss.values()))
  61. loss.update({'loss': total_loss})
  62. return loss
  63. else:
  64. results = self.ttf_head.get_bboxes(predict_hm, predict_wh,
  65. feed_vars['scale_factor'])
  66. return results
  67. def _inputs_def(self, image_shape, downsample):
  68. im_shape = [None] + image_shape
  69. H, W = im_shape[2:]
  70. target_h = None if H is None else H // downsample
  71. target_w = None if W is None else W // downsample
  72. # yapf: disable
  73. inputs_def = {
  74. 'image': {'shape': im_shape, 'dtype': 'float32', 'lod_level': 0},
  75. 'scale_factor': {'shape': [None, 4], 'dtype': 'float32', 'lod_level': 0},
  76. 'im_id': {'shape': [None, 1], 'dtype': 'int64', 'lod_level': 0},
  77. 'ttf_heatmap': {'shape': [None, self.num_classes, target_h, target_w], 'dtype': 'float32', 'lod_level': 0},
  78. 'ttf_box_target': {'shape': [None, 4, target_h, target_w], 'dtype': 'float32', 'lod_level': 0},
  79. 'ttf_reg_weight': {'shape': [None, 1, target_h, target_w], 'dtype': 'float32', 'lod_level': 0},
  80. }
  81. # yapf: enable
  82. return inputs_def
  83. def build_inputs(
  84. self,
  85. image_shape=[3, None, None],
  86. fields=[
  87. 'image', 'ttf_heatmap', 'ttf_box_target', 'ttf_reg_weight'
  88. ], # for train
  89. use_dataloader=True,
  90. iterable=False,
  91. downsample=4):
  92. inputs_def = self._inputs_def(image_shape, downsample)
  93. feed_vars = OrderedDict([(key, fluid.data(
  94. name=key,
  95. shape=inputs_def[key]['shape'],
  96. dtype=inputs_def[key]['dtype'],
  97. lod_level=inputs_def[key]['lod_level'])) for key in fields])
  98. loader = fluid.io.DataLoader.from_generator(
  99. feed_list=list(feed_vars.values()),
  100. capacity=16,
  101. use_double_buffer=True,
  102. iterable=iterable) if use_dataloader else None
  103. return feed_vars, loader
  104. def train(self, feed_vars):
  105. return self.build(feed_vars, mode='train')
  106. def eval(self, feed_vars):
  107. return self.build(feed_vars, mode='test')
  108. def test(self, feed_vars, exclude_nms=False):
  109. return self.build(feed_vars, mode='test', exclude_nms=exclude_nms)