yolox.py 4.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138
  1. # Copyright (c) 2022 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 ppdet.core.workspace import register, create
  18. from .meta_arch import BaseArch
  19. import random
  20. import paddle
  21. import paddle.nn.functional as F
  22. import paddle.distributed as dist
  23. __all__ = ['YOLOX']
  24. @register
  25. class YOLOX(BaseArch):
  26. """
  27. YOLOX network, see https://arxiv.org/abs/2107.08430
  28. Args:
  29. backbone (nn.Layer): backbone instance
  30. neck (nn.Layer): neck instance
  31. head (nn.Layer): head instance
  32. for_mot (bool): whether used for MOT or not
  33. input_size (list[int]): initial scale, will be reset by self._preprocess()
  34. size_stride (int): stride of the size range
  35. size_range (list[int]): multi-scale range for training
  36. random_interval (int): interval of iter to change self._input_size
  37. """
  38. __category__ = 'architecture'
  39. def __init__(self,
  40. backbone='CSPDarkNet',
  41. neck='YOLOCSPPAN',
  42. head='YOLOXHead',
  43. for_mot=False,
  44. input_size=[640, 640],
  45. size_stride=32,
  46. size_range=[15, 25],
  47. random_interval=10):
  48. super(YOLOX, self).__init__()
  49. self.backbone = backbone
  50. self.neck = neck
  51. self.head = head
  52. self.for_mot = for_mot
  53. self.input_size = input_size
  54. self._input_size = paddle.to_tensor(input_size)
  55. self.size_stride = size_stride
  56. self.size_range = size_range
  57. self.random_interval = random_interval
  58. self._step = 0
  59. @classmethod
  60. def from_config(cls, cfg, *args, **kwargs):
  61. # backbone
  62. backbone = create(cfg['backbone'])
  63. # fpn
  64. kwargs = {'input_shape': backbone.out_shape}
  65. neck = create(cfg['neck'], **kwargs)
  66. # head
  67. kwargs = {'input_shape': neck.out_shape}
  68. head = create(cfg['head'], **kwargs)
  69. return {
  70. 'backbone': backbone,
  71. 'neck': neck,
  72. "head": head,
  73. }
  74. def _forward(self):
  75. if self.training:
  76. self._preprocess()
  77. body_feats = self.backbone(self.inputs)
  78. neck_feats = self.neck(body_feats, self.for_mot)
  79. if self.training:
  80. yolox_losses = self.head(neck_feats, self.inputs)
  81. yolox_losses.update({'size': self._input_size[0]})
  82. return yolox_losses
  83. else:
  84. head_outs = self.head(neck_feats)
  85. bbox, bbox_num = self.head.post_process(
  86. head_outs, self.inputs['im_shape'], self.inputs['scale_factor'])
  87. return {'bbox': bbox, 'bbox_num': bbox_num}
  88. def get_loss(self):
  89. return self._forward()
  90. def get_pred(self):
  91. return self._forward()
  92. def _preprocess(self):
  93. # YOLOX multi-scale training, interpolate resize before inputs of the network.
  94. self._get_size()
  95. scale_y = self._input_size[0] / self.input_size[0]
  96. scale_x = self._input_size[1] / self.input_size[1]
  97. if scale_x != 1 or scale_y != 1:
  98. self.inputs['image'] = F.interpolate(
  99. self.inputs['image'],
  100. size=self._input_size,
  101. mode='bilinear',
  102. align_corners=False)
  103. gt_bboxes = self.inputs['gt_bbox']
  104. for i in range(len(gt_bboxes)):
  105. if len(gt_bboxes[i]) > 0:
  106. gt_bboxes[i][:, 0::2] = gt_bboxes[i][:, 0::2] * scale_x
  107. gt_bboxes[i][:, 1::2] = gt_bboxes[i][:, 1::2] * scale_y
  108. self.inputs['gt_bbox'] = gt_bboxes
  109. def _get_size(self):
  110. # random_interval = 10 as default, every 10 iters to change self._input_size
  111. image_ratio = self.input_size[1] * 1.0 / self.input_size[0]
  112. if self._step % self.random_interval == 0:
  113. size_factor = random.randint(*self.size_range)
  114. size = [
  115. self.size_stride * size_factor,
  116. self.size_stride * int(size_factor * image_ratio)
  117. ]
  118. self._input_size = paddle.to_tensor(size)
  119. self._step += 1