yolox.py 4.7 KB

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