detector.py 74 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782
  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. from __future__ import absolute_import
  15. import collections
  16. import copy
  17. import os
  18. import os.path as osp
  19. import six
  20. import numpy as np
  21. import paddle
  22. from paddle.static import InputSpec
  23. import paddlex.ppdet as ppdet
  24. from paddlex.ppdet.modeling.proposal_generator.target_layer import BBoxAssigner, MaskAssigner
  25. import paddlex
  26. import paddlex.utils.logging as logging
  27. from paddlex.cv.transforms.operators import _NormalizeBox, _PadBox, _BboxXYXY2XYWH, Resize, Padding
  28. from paddlex.cv.transforms.batch_operators import BatchCompose, BatchRandomResize, BatchRandomResizeByShort, _BatchPadding, _Gt2YoloTarget
  29. from paddlex.cv.transforms import arrange_transforms
  30. from .base import BaseModel
  31. from .utils.det_metrics import VOCMetric, COCOMetric
  32. from .utils.ema import ExponentialMovingAverage
  33. from paddlex.utils.checkpoint import det_pretrain_weights_dict
  34. __all__ = [
  35. "YOLOv3", "FasterRCNN", "PPYOLO", "PPYOLOTiny", "PPYOLOv2", "MaskRCNN"
  36. ]
  37. class BaseDetector(BaseModel):
  38. def __init__(self, model_name, num_classes=80, **params):
  39. self.init_params.update(locals())
  40. if 'with_net' in self.init_params:
  41. del self.init_params['with_net']
  42. super(BaseDetector, self).__init__('detector')
  43. if not hasattr(ppdet.modeling, model_name):
  44. raise Exception("ERROR: There's no model named {}.".format(
  45. model_name))
  46. self.model_name = model_name
  47. self.num_classes = num_classes
  48. self.labels = None
  49. if params.get('with_net', True):
  50. params.pop('with_net', None)
  51. self.net = self.build_net(**params)
  52. def build_net(self, **params):
  53. with paddle.utils.unique_name.guard():
  54. net = ppdet.modeling.__dict__[self.model_name](**params)
  55. return net
  56. def _fix_transforms_shape(self, image_shape):
  57. raise NotImplementedError("_fix_transforms_shape: not implemented!")
  58. def _define_input_spec(self, image_shape):
  59. input_spec = [{
  60. "image": InputSpec(
  61. shape=image_shape, name='image', dtype='float32'),
  62. "im_shape": InputSpec(
  63. shape=[image_shape[0], 2], name='im_shape', dtype='float32'),
  64. "scale_factor": InputSpec(
  65. shape=[image_shape[0], 2],
  66. name='scale_factor',
  67. dtype='float32')
  68. }]
  69. return input_spec
  70. def _check_image_shape(self, image_shape):
  71. if len(image_shape) == 2:
  72. image_shape = [1, 3] + image_shape
  73. if image_shape[-2] % 32 > 0 or image_shape[-1] % 32 > 0:
  74. raise Exception(
  75. "Height and width in fixed_input_shape must be a multiple of 32, but received {}.".
  76. format(image_shape[-2:]))
  77. return image_shape
  78. def _get_test_inputs(self, image_shape):
  79. if image_shape is not None:
  80. image_shape = self._check_image_shape(image_shape)
  81. self._fix_transforms_shape(image_shape[-2:])
  82. else:
  83. image_shape = [None, 3, -1, -1]
  84. self.fixed_input_shape = image_shape
  85. return self._define_input_spec(image_shape)
  86. def _get_backbone(self, backbone_name, **params):
  87. backbone = getattr(ppdet.modeling, backbone_name)(**params)
  88. return backbone
  89. def run(self, net, inputs, mode):
  90. net_out = net(inputs)
  91. if mode in ['train', 'eval']:
  92. outputs = net_out
  93. else:
  94. for key in ['im_shape', 'scale_factor']:
  95. net_out[key] = inputs[key]
  96. outputs = dict()
  97. for key in net_out:
  98. outputs[key] = net_out[key].numpy()
  99. return outputs
  100. def default_optimizer(self, parameters, learning_rate, warmup_steps,
  101. warmup_start_lr, lr_decay_epochs, lr_decay_gamma,
  102. num_steps_each_epoch):
  103. boundaries = [b * num_steps_each_epoch for b in lr_decay_epochs]
  104. values = [(lr_decay_gamma**i) * learning_rate
  105. for i in range(len(lr_decay_epochs) + 1)]
  106. scheduler = paddle.optimizer.lr.PiecewiseDecay(
  107. boundaries=boundaries, values=values)
  108. if warmup_steps > 0:
  109. if warmup_steps > lr_decay_epochs[0] * num_steps_each_epoch:
  110. logging.error(
  111. "In function train(), parameters should satisfy: "
  112. "warmup_steps <= lr_decay_epochs[0]*num_samples_in_train_dataset",
  113. exit=False)
  114. logging.error(
  115. "See this doc for more information: "
  116. "https://github.com/PaddlePaddle/PaddleX/blob/develop/docs/appendix/parameters.md#notice",
  117. exit=False)
  118. scheduler = paddle.optimizer.lr.LinearWarmup(
  119. learning_rate=scheduler,
  120. warmup_steps=warmup_steps,
  121. start_lr=warmup_start_lr,
  122. end_lr=learning_rate)
  123. optimizer = paddle.optimizer.Momentum(
  124. scheduler,
  125. momentum=.9,
  126. weight_decay=paddle.regularizer.L2Decay(coeff=1e-04),
  127. parameters=parameters)
  128. return optimizer
  129. def train(self,
  130. num_epochs,
  131. train_dataset,
  132. train_batch_size=64,
  133. eval_dataset=None,
  134. optimizer=None,
  135. save_interval_epochs=1,
  136. log_interval_steps=10,
  137. save_dir='output',
  138. pretrain_weights='IMAGENET',
  139. learning_rate=.001,
  140. warmup_steps=0,
  141. warmup_start_lr=0.0,
  142. lr_decay_epochs=(216, 243),
  143. lr_decay_gamma=0.1,
  144. metric=None,
  145. use_ema=False,
  146. early_stop=False,
  147. early_stop_patience=5,
  148. use_vdl=True,
  149. resume_checkpoint=None):
  150. """
  151. Train the model.
  152. Args:
  153. num_epochs(int): The number of epochs.
  154. train_dataset(paddlex.dataset): Training dataset.
  155. train_batch_size(int, optional): Total batch size among all cards used in training. Defaults to 64.
  156. eval_dataset(paddlex.dataset, optional):
  157. Evaluation dataset. If None, the model will not be evaluated during training process. Defaults to None.
  158. optimizer(paddle.optimizer.Optimizer or None, optional):
  159. Optimizer used for training. If None, a default optimizer is used. Defaults to None.
  160. save_interval_epochs(int, optional): Epoch interval for saving the model. Defaults to 1.
  161. log_interval_steps(int, optional): Step interval for printing training information. Defaults to 10.
  162. save_dir(str, optional): Directory to save the model. Defaults to 'output'.
  163. pretrain_weights(str or None, optional):
  164. None or name/path of pretrained weights. If None, no pretrained weights will be loaded. Defaults to 'IMAGENET'.
  165. learning_rate(float, optional): Learning rate for training. Defaults to .001.
  166. warmup_steps(int, optional): The number of steps of warm-up training. Defaults to 0.
  167. warmup_start_lr(float, optional): Start learning rate of warm-up training. Defaults to 0..
  168. lr_decay_epochs(list or tuple, optional): Epoch milestones for learning rate decay. Defaults to (216, 243).
  169. lr_decay_gamma(float, optional): Gamma coefficient of learning rate decay. Defaults to .1.
  170. metric({'VOC', 'COCO', None}, optional):
  171. Evaluation metric. If None, determine the metric according to the dataset format. Defaults to None.
  172. use_ema(bool, optional): Whether to use exponential moving average strategy. Defaults to False.
  173. early_stop(bool, optional): Whether to adopt early stop strategy. Defaults to False.
  174. early_stop_patience(int, optional): Early stop patience. Defaults to 5.
  175. use_vdl(bool, optional): Whether to use VisualDL to monitor the training process. Defaults to True.
  176. resume_checkpoint(str or None, optional): The path of the checkpoint to resume training from.
  177. If None, no training checkpoint will be resumed. At most one of `resume_checkpoint` and
  178. `pretrain_weights` can be set simultaneously. Defaults to None.
  179. """
  180. if pretrain_weights is not None and resume_checkpoint is not None:
  181. logging.error(
  182. "pretrain_weights and resume_checkpoint cannot be set simultaneously.",
  183. exit=True)
  184. if train_dataset.__class__.__name__ == 'VOCDetection':
  185. train_dataset.data_fields = {
  186. 'im_id', 'image_shape', 'image', 'gt_bbox', 'gt_class',
  187. 'difficult'
  188. }
  189. elif train_dataset.__class__.__name__ == 'CocoDetection':
  190. if self.__class__.__name__ == 'MaskRCNN':
  191. train_dataset.data_fields = {
  192. 'im_id', 'image_shape', 'image', 'gt_bbox', 'gt_class',
  193. 'gt_poly', 'is_crowd'
  194. }
  195. else:
  196. train_dataset.data_fields = {
  197. 'im_id', 'image_shape', 'image', 'gt_bbox', 'gt_class',
  198. 'is_crowd'
  199. }
  200. if metric is None:
  201. if eval_dataset.__class__.__name__ == 'VOCDetection':
  202. self.metric = 'voc'
  203. elif eval_dataset.__class__.__name__ == 'CocoDetection':
  204. self.metric = 'coco'
  205. else:
  206. assert metric.lower() in ['coco', 'voc'], \
  207. "Evaluation metric {} is not supported, please choose form 'COCO' and 'VOC'"
  208. self.metric = metric.lower()
  209. self.labels = train_dataset.labels
  210. self.num_max_boxes = train_dataset.num_max_boxes
  211. train_dataset.batch_transforms = self._compose_batch_transform(
  212. train_dataset.transforms, mode='train')
  213. # build optimizer if not defined
  214. if optimizer is None:
  215. num_steps_each_epoch = len(train_dataset) // train_batch_size
  216. self.optimizer = self.default_optimizer(
  217. parameters=self.net.parameters(),
  218. learning_rate=learning_rate,
  219. warmup_steps=warmup_steps,
  220. warmup_start_lr=warmup_start_lr,
  221. lr_decay_epochs=lr_decay_epochs,
  222. lr_decay_gamma=lr_decay_gamma,
  223. num_steps_each_epoch=num_steps_each_epoch)
  224. else:
  225. self.optimizer = optimizer
  226. # initiate weights
  227. if pretrain_weights is not None and not osp.exists(pretrain_weights):
  228. if pretrain_weights not in det_pretrain_weights_dict['_'.join(
  229. [self.model_name, self.backbone_name])]:
  230. logging.warning(
  231. "Path of pretrain_weights('{}') does not exist!".format(
  232. pretrain_weights))
  233. pretrain_weights = det_pretrain_weights_dict['_'.join(
  234. [self.model_name, self.backbone_name])][0]
  235. logging.warning("Pretrain_weights is forcibly set to '{}'. "
  236. "If you don't want to use pretrain weights, "
  237. "set pretrain_weights to be None.".format(
  238. pretrain_weights))
  239. elif pretrain_weights is not None and osp.exists(pretrain_weights):
  240. if osp.splitext(pretrain_weights)[-1] != '.pdparams':
  241. logging.error(
  242. "Invalid pretrain weights. Please specify a '.pdparams' file.",
  243. exit=True)
  244. pretrained_dir = osp.join(save_dir, 'pretrain')
  245. self.net_initialize(
  246. pretrain_weights=pretrain_weights,
  247. save_dir=pretrained_dir,
  248. resume_checkpoint=resume_checkpoint)
  249. if use_ema:
  250. ema = ExponentialMovingAverage(
  251. decay=.9998, model=self.net, use_thres_step=True)
  252. else:
  253. ema = None
  254. # start train loop
  255. self.train_loop(
  256. num_epochs=num_epochs,
  257. train_dataset=train_dataset,
  258. train_batch_size=train_batch_size,
  259. eval_dataset=eval_dataset,
  260. save_interval_epochs=save_interval_epochs,
  261. log_interval_steps=log_interval_steps,
  262. save_dir=save_dir,
  263. ema=ema,
  264. early_stop=early_stop,
  265. early_stop_patience=early_stop_patience,
  266. use_vdl=use_vdl)
  267. def quant_aware_train(self,
  268. num_epochs,
  269. train_dataset,
  270. train_batch_size=64,
  271. eval_dataset=None,
  272. optimizer=None,
  273. save_interval_epochs=1,
  274. log_interval_steps=10,
  275. save_dir='output',
  276. learning_rate=.00001,
  277. warmup_steps=0,
  278. warmup_start_lr=0.0,
  279. lr_decay_epochs=(216, 243),
  280. lr_decay_gamma=0.1,
  281. metric=None,
  282. use_ema=False,
  283. early_stop=False,
  284. early_stop_patience=5,
  285. use_vdl=True,
  286. resume_checkpoint=None,
  287. quant_config=None):
  288. """
  289. Quantization-aware training.
  290. Args:
  291. num_epochs(int): The number of epochs.
  292. train_dataset(paddlex.dataset): Training dataset.
  293. train_batch_size(int, optional): Total batch size among all cards used in training. Defaults to 64.
  294. eval_dataset(paddlex.dataset, optional):
  295. Evaluation dataset. If None, the model will not be evaluated during training process. Defaults to None.
  296. optimizer(paddle.optimizer.Optimizer or None, optional):
  297. Optimizer used for training. If None, a default optimizer is used. Defaults to None.
  298. save_interval_epochs(int, optional): Epoch interval for saving the model. Defaults to 1.
  299. log_interval_steps(int, optional): Step interval for printing training information. Defaults to 10.
  300. save_dir(str, optional): Directory to save the model. Defaults to 'output'.
  301. learning_rate(float, optional): Learning rate for training. Defaults to .001.
  302. warmup_steps(int, optional): The number of steps of warm-up training. Defaults to 0.
  303. warmup_start_lr(float, optional): Start learning rate of warm-up training. Defaults to 0..
  304. lr_decay_epochs(list or tuple, optional): Epoch milestones for learning rate decay. Defaults to (216, 243).
  305. lr_decay_gamma(float, optional): Gamma coefficient of learning rate decay. Defaults to .1.
  306. metric({'VOC', 'COCO', None}, optional):
  307. Evaluation metric. If None, determine the metric according to the dataset format. Defaults to None.
  308. use_ema(bool, optional): Whether to use exponential moving average strategy. Defaults to False.
  309. early_stop(bool, optional): Whether to adopt early stop strategy. Defaults to False.
  310. early_stop_patience(int, optional): Early stop patience. Defaults to 5.
  311. use_vdl(bool, optional): Whether to use VisualDL to monitor the training process. Defaults to True.
  312. quant_config(dict or None, optional): Quantization configuration. If None, a default rule of thumb
  313. configuration will be used. Defaults to None.
  314. resume_checkpoint(str or None, optional): The path of the checkpoint to resume quantization-aware training
  315. from. If None, no training checkpoint will be resumed. Defaults to None.
  316. """
  317. self._prepare_qat(quant_config)
  318. self.train(
  319. num_epochs=num_epochs,
  320. train_dataset=train_dataset,
  321. train_batch_size=train_batch_size,
  322. eval_dataset=eval_dataset,
  323. optimizer=optimizer,
  324. save_interval_epochs=save_interval_epochs,
  325. log_interval_steps=log_interval_steps,
  326. save_dir=save_dir,
  327. pretrain_weights=None,
  328. learning_rate=learning_rate,
  329. warmup_steps=warmup_steps,
  330. warmup_start_lr=warmup_start_lr,
  331. lr_decay_epochs=lr_decay_epochs,
  332. lr_decay_gamma=lr_decay_gamma,
  333. metric=metric,
  334. use_ema=use_ema,
  335. early_stop=early_stop,
  336. early_stop_patience=early_stop_patience,
  337. use_vdl=use_vdl,
  338. resume_checkpoint=resume_checkpoint)
  339. def evaluate(self,
  340. eval_dataset,
  341. batch_size=1,
  342. metric=None,
  343. return_details=False):
  344. """
  345. Evaluate the model.
  346. Args:
  347. eval_dataset(paddlex.dataset): Evaluation dataset.
  348. batch_size(int, optional): Total batch size among all cards used for evaluation. Defaults to 1.
  349. metric({'VOC', 'COCO', None}, optional):
  350. Evaluation metric. If None, determine the metric according to the dataset format. Defaults to None.
  351. return_details(bool, optional): Whether to return evaluation details. Defaults to False.
  352. Returns:
  353. collections.OrderedDict with key-value pairs: {"mAP(0.50, 11point)":`mean average precision`}.
  354. """
  355. if metric is None:
  356. if not hasattr(self, 'metric'):
  357. if eval_dataset.__class__.__name__ == 'VOCDetection':
  358. self.metric = 'voc'
  359. elif eval_dataset.__class__.__name__ == 'CocoDetection':
  360. self.metric = 'coco'
  361. else:
  362. assert metric.lower() in ['coco', 'voc'], \
  363. "Evaluation metric {} is not supported, please choose form 'COCO' and 'VOC'"
  364. self.metric = metric.lower()
  365. if self.metric == 'voc':
  366. eval_dataset.data_fields = {
  367. 'im_id', 'image_shape', 'image', 'gt_bbox', 'gt_class',
  368. 'difficult'
  369. }
  370. elif self.metric == 'coco':
  371. if self.__class__.__name__ == 'MaskRCNN':
  372. eval_dataset.data_fields = {
  373. 'im_id', 'image_shape', 'image', 'gt_bbox', 'gt_class',
  374. 'gt_poly', 'is_crowd'
  375. }
  376. else:
  377. eval_dataset.data_fields = {
  378. 'im_id', 'image_shape', 'image', 'gt_bbox', 'gt_class',
  379. 'is_crowd'
  380. }
  381. eval_dataset.batch_transforms = self._compose_batch_transform(
  382. eval_dataset.transforms, mode='eval')
  383. arrange_transforms(
  384. model_type=self.model_type,
  385. transforms=eval_dataset.transforms,
  386. mode='eval')
  387. self.net.eval()
  388. nranks = paddle.distributed.get_world_size()
  389. local_rank = paddle.distributed.get_rank()
  390. if nranks > 1:
  391. # Initialize parallel environment if not done.
  392. if not paddle.distributed.parallel.parallel_helper._is_parallel_ctx_initialized(
  393. ):
  394. paddle.distributed.init_parallel_env()
  395. if batch_size > 1:
  396. logging.warning(
  397. "Detector only supports single card evaluation with batch_size=1 "
  398. "during evaluation, so batch_size is forcibly set to 1.")
  399. batch_size = 1
  400. if nranks < 2 or local_rank == 0:
  401. self.eval_data_loader = self.build_data_loader(
  402. eval_dataset, batch_size=batch_size, mode='eval')
  403. is_bbox_normalized = False
  404. if eval_dataset.batch_transforms is not None:
  405. is_bbox_normalized = any(
  406. isinstance(t, _NormalizeBox)
  407. for t in eval_dataset.batch_transforms.batch_transforms)
  408. if self.metric == 'voc':
  409. eval_metric = VOCMetric(
  410. labels=eval_dataset.labels,
  411. coco_gt=copy.deepcopy(eval_dataset.coco_gt),
  412. is_bbox_normalized=is_bbox_normalized,
  413. classwise=False)
  414. else:
  415. eval_metric = COCOMetric(
  416. coco_gt=copy.deepcopy(eval_dataset.coco_gt),
  417. classwise=False)
  418. scores = collections.OrderedDict()
  419. logging.info(
  420. "Start to evaluate(total_samples={}, total_steps={})...".
  421. format(eval_dataset.num_samples, eval_dataset.num_samples))
  422. with paddle.no_grad():
  423. for step, data in enumerate(self.eval_data_loader):
  424. outputs = self.run(self.net, data, 'eval')
  425. eval_metric.update(data, outputs)
  426. eval_metric.accumulate()
  427. self.eval_details = eval_metric.details
  428. scores.update(eval_metric.get())
  429. eval_metric.reset()
  430. if return_details:
  431. return scores, self.eval_details
  432. return scores
  433. def predict(self, img_file, transforms=None):
  434. """
  435. Do inference.
  436. Args:
  437. img_file(List[np.ndarray or str], str or np.ndarray): img_file(list or str or np.array):
  438. Image path or decoded image data in a BGR format, which also could constitute a list,
  439. meaning all images to be predicted as a mini-batch.
  440. transforms(paddlex.transforms.Compose or None, optional):
  441. Transforms for inputs. If None, the transforms for evaluation process will be used. Defaults to None.
  442. Returns:
  443. If img_file is a string or np.array, the result is a list of dict with key-value pairs:
  444. {"category_id": `category_id`, "category": `category`, "bbox": `[x, y, w, h]`, "score": `score`}.
  445. If img_file is a list, the result is a list composed of dicts with the corresponding fields:
  446. category_id(int): the predicted category ID. 0 represents the first category in the dataset, and so on.
  447. category(str): category name
  448. bbox(list): bounding box in [x, y, w, h] format
  449. score(str): confidence
  450. mask(dict): Only for instance segmentation task. Mask of the object in RLE format
  451. """
  452. if transforms is None and not hasattr(self, 'test_transforms'):
  453. raise Exception("transforms need to be defined, now is None.")
  454. if transforms is None:
  455. transforms = self.test_transforms
  456. if isinstance(img_file, (str, np.ndarray)):
  457. images = [img_file]
  458. else:
  459. images = img_file
  460. batch_samples = self._preprocess(images, transforms)
  461. self.net.eval()
  462. outputs = self.run(self.net, batch_samples, 'test')
  463. prediction = self._postprocess(outputs)
  464. if isinstance(img_file, (str, np.ndarray)):
  465. prediction = prediction[0]
  466. return prediction
  467. def _preprocess(self, images, transforms):
  468. arrange_transforms(
  469. model_type=self.model_type, transforms=transforms, mode='test')
  470. batch_samples = list()
  471. for im in images:
  472. sample = {'image': im}
  473. batch_samples.append(transforms(sample))
  474. batch_transforms = self._compose_batch_transform(transforms, 'test')
  475. batch_samples = batch_transforms(batch_samples)
  476. for k, v in batch_samples.items():
  477. batch_samples[k] = paddle.to_tensor(v)
  478. return batch_samples
  479. def _postprocess(self, batch_pred):
  480. infer_result = {}
  481. if 'bbox' in batch_pred:
  482. bboxes = batch_pred['bbox']
  483. bbox_nums = batch_pred['bbox_num']
  484. det_res = []
  485. k = 0
  486. for i in range(len(bbox_nums)):
  487. det_nums = bbox_nums[i]
  488. for j in range(det_nums):
  489. dt = bboxes[k]
  490. k = k + 1
  491. num_id, score, xmin, ymin, xmax, ymax = dt.tolist()
  492. if int(num_id) < 0:
  493. continue
  494. category = self.labels[int(num_id)]
  495. w = xmax - xmin
  496. h = ymax - ymin
  497. bbox = [xmin, ymin, w, h]
  498. dt_res = {
  499. 'category_id': int(num_id),
  500. 'category': category,
  501. 'bbox': bbox,
  502. 'score': score
  503. }
  504. det_res.append(dt_res)
  505. infer_result['bbox'] = det_res
  506. if 'mask' in batch_pred:
  507. masks = batch_pred['mask']
  508. bboxes = batch_pred['bbox']
  509. mask_nums = batch_pred['bbox_num']
  510. seg_res = []
  511. k = 0
  512. for i in range(len(mask_nums)):
  513. det_nums = mask_nums[i]
  514. for j in range(det_nums):
  515. mask = masks[k].astype(np.uint8)
  516. score = float(bboxes[k][1])
  517. label = int(bboxes[k][0])
  518. k = k + 1
  519. if label == -1:
  520. continue
  521. category = self.labels[int(label)]
  522. import pycocotools.mask as mask_util
  523. rle = mask_util.encode(
  524. np.array(
  525. mask[:, :, None], order="F", dtype="uint8"))[0]
  526. if six.PY3:
  527. if 'counts' in rle:
  528. rle['counts'] = rle['counts'].decode("utf8")
  529. sg_res = {
  530. 'category_id': int(label),
  531. 'category': category,
  532. 'mask': rle,
  533. 'score': score
  534. }
  535. seg_res.append(sg_res)
  536. infer_result['mask'] = seg_res
  537. bbox_num = batch_pred['bbox_num']
  538. results = []
  539. start = 0
  540. for num in bbox_num:
  541. end = start + num
  542. curr_res = infer_result['bbox'][start:end]
  543. if 'mask' in infer_result:
  544. mask_res = infer_result['mask'][start:end]
  545. for box, mask in zip(curr_res, mask_res):
  546. box.update(mask)
  547. results.append(curr_res)
  548. start = end
  549. return results
  550. class YOLOv3(BaseDetector):
  551. def __init__(self,
  552. num_classes=80,
  553. backbone='MobileNetV1',
  554. anchors=[[10, 13], [16, 30], [33, 23], [30, 61], [62, 45],
  555. [59, 119], [116, 90], [156, 198], [373, 326]],
  556. anchor_masks=[[6, 7, 8], [3, 4, 5], [0, 1, 2]],
  557. ignore_threshold=0.7,
  558. nms_score_threshold=0.01,
  559. nms_topk=1000,
  560. nms_keep_topk=100,
  561. nms_iou_threshold=0.45,
  562. label_smooth=False,
  563. **params):
  564. self.init_params = locals()
  565. if backbone not in [
  566. 'MobileNetV1', 'MobileNetV1_ssld', 'MobileNetV3',
  567. 'MobileNetV3_ssld', 'DarkNet53', 'ResNet50_vd_dcn', 'ResNet34'
  568. ]:
  569. raise ValueError(
  570. "backbone: {} is not supported. Please choose one of "
  571. "('MobileNetV1', 'MobileNetV1_ssld', 'MobileNetV3', 'MobileNetV3_ssld', 'DarkNet53', 'ResNet50_vd_dcn', 'ResNet34')".
  572. format(backbone))
  573. self.backbone_name = backbone
  574. if params.get('with_net', True):
  575. if paddlex.env_info['place'] == 'gpu' and paddlex.env_info[
  576. 'num'] > 1 and not os.environ.get('PADDLEX_EXPORT_STAGE'):
  577. norm_type = 'sync_bn'
  578. else:
  579. norm_type = 'bn'
  580. if 'MobileNetV1' in backbone:
  581. norm_type = 'bn'
  582. backbone = self._get_backbone('MobileNet', norm_type=norm_type)
  583. elif 'MobileNetV3' in backbone:
  584. backbone = self._get_backbone(
  585. 'MobileNetV3',
  586. norm_type=norm_type,
  587. feature_maps=[7, 13, 16])
  588. elif backbone == 'ResNet50_vd_dcn':
  589. backbone = self._get_backbone(
  590. 'ResNet',
  591. norm_type=norm_type,
  592. variant='d',
  593. return_idx=[1, 2, 3],
  594. dcn_v2_stages=[3],
  595. freeze_at=-1,
  596. freeze_norm=False)
  597. elif backbone == 'ResNet34':
  598. backbone = self._get_backbone(
  599. 'ResNet',
  600. depth=34,
  601. norm_type=norm_type,
  602. return_idx=[1, 2, 3],
  603. freeze_at=-1,
  604. freeze_norm=False,
  605. norm_decay=0.)
  606. else:
  607. backbone = self._get_backbone('DarkNet', norm_type=norm_type)
  608. neck = ppdet.modeling.YOLOv3FPN(
  609. norm_type=norm_type,
  610. in_channels=[i.channels for i in backbone.out_shape])
  611. loss = ppdet.modeling.YOLOv3Loss(
  612. num_classes=num_classes,
  613. ignore_thresh=ignore_threshold,
  614. label_smooth=label_smooth)
  615. yolo_head = ppdet.modeling.YOLOv3Head(
  616. in_channels=[i.channels for i in neck.out_shape],
  617. anchors=anchors,
  618. anchor_masks=anchor_masks,
  619. num_classes=num_classes,
  620. loss=loss)
  621. post_process = ppdet.modeling.BBoxPostProcess(
  622. decode=ppdet.modeling.YOLOBox(num_classes=num_classes),
  623. nms=ppdet.modeling.MultiClassNMS(
  624. score_threshold=nms_score_threshold,
  625. nms_top_k=nms_topk,
  626. keep_top_k=nms_keep_topk,
  627. nms_threshold=nms_iou_threshold))
  628. params.update({
  629. 'backbone': backbone,
  630. 'neck': neck,
  631. 'yolo_head': yolo_head,
  632. 'post_process': post_process
  633. })
  634. super(YOLOv3, self).__init__(
  635. model_name='YOLOv3', num_classes=num_classes, **params)
  636. self.anchors = anchors
  637. self.anchor_masks = anchor_masks
  638. def _compose_batch_transform(self, transforms, mode='train'):
  639. if mode == 'train':
  640. default_batch_transforms = [
  641. _BatchPadding(pad_to_stride=-1), _NormalizeBox(),
  642. _PadBox(getattr(self, 'num_max_boxes', 50)), _BboxXYXY2XYWH(),
  643. _Gt2YoloTarget(
  644. anchor_masks=self.anchor_masks,
  645. anchors=self.anchors,
  646. downsample_ratios=getattr(self, 'downsample_ratios',
  647. [32, 16, 8]),
  648. num_classes=self.num_classes)
  649. ]
  650. else:
  651. default_batch_transforms = [_BatchPadding(pad_to_stride=-1)]
  652. if mode == 'eval' and self.metric == 'voc':
  653. collate_batch = False
  654. else:
  655. collate_batch = True
  656. custom_batch_transforms = []
  657. for i, op in enumerate(transforms.transforms):
  658. if isinstance(op, (BatchRandomResize, BatchRandomResizeByShort)):
  659. if mode != 'train':
  660. raise Exception(
  661. "{} cannot be present in the {} transforms. ".format(
  662. op.__class__.__name__, mode) +
  663. "Please check the {} transforms.".format(mode))
  664. custom_batch_transforms.insert(0, copy.deepcopy(op))
  665. batch_transforms = BatchCompose(
  666. custom_batch_transforms + default_batch_transforms,
  667. collate_batch=collate_batch)
  668. return batch_transforms
  669. def _fix_transforms_shape(self, image_shape):
  670. if hasattr(self, 'test_transforms'):
  671. if self.test_transforms is not None:
  672. has_resize_op = False
  673. resize_op_idx = -1
  674. normalize_op_idx = len(self.test_transforms.transforms)
  675. for idx, op in enumerate(self.test_transforms.transforms):
  676. name = op.__class__.__name__
  677. if name == 'Resize':
  678. has_resize_op = True
  679. resize_op_idx = idx
  680. if name == 'Normalize':
  681. normalize_op_idx = idx
  682. if not has_resize_op:
  683. self.test_transforms.transforms.insert(
  684. normalize_op_idx,
  685. Resize(
  686. target_size=image_shape, interp='CUBIC'))
  687. else:
  688. self.test_transforms.transforms[
  689. resize_op_idx].target_size = image_shape
  690. class FasterRCNN(BaseDetector):
  691. def __init__(self,
  692. num_classes=80,
  693. backbone='ResNet50',
  694. with_fpn=True,
  695. with_dcn=False,
  696. aspect_ratios=[0.5, 1.0, 2.0],
  697. anchor_sizes=[[32], [64], [128], [256], [512]],
  698. keep_top_k=100,
  699. nms_threshold=0.5,
  700. score_threshold=0.05,
  701. fpn_num_channels=256,
  702. rpn_batch_size_per_im=256,
  703. rpn_fg_fraction=0.5,
  704. test_pre_nms_top_n=None,
  705. test_post_nms_top_n=1000,
  706. **params):
  707. self.init_params = locals()
  708. if backbone not in [
  709. 'ResNet50', 'ResNet50_vd', 'ResNet50_vd_ssld', 'ResNet34',
  710. 'ResNet34_vd', 'ResNet101', 'ResNet101_vd', 'HRNet_W18'
  711. ]:
  712. raise ValueError(
  713. "backbone: {} is not supported. Please choose one of "
  714. "('ResNet50', 'ResNet50_vd', 'ResNet50_vd_ssld', 'ResNet34', 'ResNet34_vd', "
  715. "'ResNet101', 'ResNet101_vd', 'HRNet_W18')".format(backbone))
  716. self.backbone_name = backbone
  717. if params.get('with_net', True):
  718. dcn_v2_stages = [1, 2, 3] if with_dcn else [-1]
  719. if backbone == 'HRNet_W18':
  720. if not with_fpn:
  721. logging.warning(
  722. "Backbone {} should be used along with fpn enabled, 'with_fpn' is forcibly set to True".
  723. format(backbone))
  724. with_fpn = True
  725. if with_dcn:
  726. logging.warning(
  727. "Backbone {} should be used along with dcn disabled, 'with_dcn' is forcibly set to False".
  728. format(backbone))
  729. backbone = self._get_backbone(
  730. 'HRNet', width=18, freeze_at=0, return_idx=[0, 1, 2, 3])
  731. elif backbone == 'ResNet50_vd_ssld':
  732. if not with_fpn:
  733. logging.warning(
  734. "Backbone {} should be used along with fpn enabled, 'with_fpn' is forcibly set to True".
  735. format(backbone))
  736. with_fpn = True
  737. backbone = self._get_backbone(
  738. 'ResNet',
  739. variant='d',
  740. norm_type='bn',
  741. freeze_at=0,
  742. return_idx=[0, 1, 2, 3],
  743. num_stages=4,
  744. lr_mult_list=[0.05, 0.05, 0.1, 0.15],
  745. dcn_v2_stages=dcn_v2_stages)
  746. elif 'ResNet50' in backbone:
  747. if with_fpn:
  748. backbone = self._get_backbone(
  749. 'ResNet',
  750. variant='d' if '_vd' in backbone else 'b',
  751. norm_type='bn',
  752. freeze_at=0,
  753. return_idx=[0, 1, 2, 3],
  754. num_stages=4,
  755. dcn_v2_stages=dcn_v2_stages)
  756. else:
  757. if with_dcn:
  758. logging.warning(
  759. "Backbone {} without fpn should be used along with dcn disabled, 'with_dcn' is forcibly set to False".
  760. format(backbone))
  761. backbone = self._get_backbone(
  762. 'ResNet',
  763. variant='d' if '_vd' in backbone else 'b',
  764. norm_type='bn',
  765. freeze_at=0,
  766. return_idx=[2],
  767. num_stages=3)
  768. elif 'ResNet34' in backbone:
  769. if not with_fpn:
  770. logging.warning(
  771. "Backbone {} should be used along with fpn enabled, 'with_fpn' is forcibly set to True".
  772. format(backbone))
  773. with_fpn = True
  774. backbone = self._get_backbone(
  775. 'ResNet',
  776. depth=34,
  777. variant='d' if 'vd' in backbone else 'b',
  778. norm_type='bn',
  779. freeze_at=0,
  780. return_idx=[0, 1, 2, 3],
  781. num_stages=4,
  782. dcn_v2_stages=dcn_v2_stages)
  783. else:
  784. if not with_fpn:
  785. logging.warning(
  786. "Backbone {} should be used along with fpn enabled, 'with_fpn' is forcibly set to True".
  787. format(backbone))
  788. with_fpn = True
  789. backbone = self._get_backbone(
  790. 'ResNet',
  791. depth=101,
  792. variant='d' if 'vd' in backbone else 'b',
  793. norm_type='bn',
  794. freeze_at=0,
  795. return_idx=[0, 1, 2, 3],
  796. num_stages=4,
  797. dcn_v2_stages=dcn_v2_stages)
  798. rpn_in_channel = backbone.out_shape[0].channels
  799. if with_fpn:
  800. self.backbone_name = self.backbone_name + '_fpn'
  801. if 'HRNet' in self.backbone_name:
  802. neck = ppdet.modeling.HRFPN(
  803. in_channels=[i.channels for i in backbone.out_shape],
  804. out_channel=fpn_num_channels,
  805. spatial_scales=[
  806. 1.0 / i.stride for i in backbone.out_shape
  807. ],
  808. share_conv=False)
  809. else:
  810. neck = ppdet.modeling.FPN(
  811. in_channels=[i.channels for i in backbone.out_shape],
  812. out_channel=fpn_num_channels,
  813. spatial_scales=[
  814. 1.0 / i.stride for i in backbone.out_shape
  815. ])
  816. rpn_in_channel = neck.out_shape[0].channels
  817. anchor_generator_cfg = {
  818. 'aspect_ratios': aspect_ratios,
  819. 'anchor_sizes': anchor_sizes,
  820. 'strides': [4, 8, 16, 32, 64]
  821. }
  822. train_proposal_cfg = {
  823. 'min_size': 0.0,
  824. 'nms_thresh': .7,
  825. 'pre_nms_top_n': 2000,
  826. 'post_nms_top_n': 1000,
  827. 'topk_after_collect': True
  828. }
  829. test_proposal_cfg = {
  830. 'min_size': 0.0,
  831. 'nms_thresh': .7,
  832. 'pre_nms_top_n': 1000
  833. if test_pre_nms_top_n is None else test_pre_nms_top_n,
  834. 'post_nms_top_n': test_post_nms_top_n
  835. }
  836. head = ppdet.modeling.TwoFCHead(
  837. in_channel=neck.out_shape[0].channels, out_channel=1024)
  838. roi_extractor_cfg = {
  839. 'resolution': 7,
  840. 'spatial_scale': [1. / i.stride for i in neck.out_shape],
  841. 'sampling_ratio': 0,
  842. 'aligned': True
  843. }
  844. with_pool = False
  845. else:
  846. neck = None
  847. anchor_generator_cfg = {
  848. 'aspect_ratios': aspect_ratios,
  849. 'anchor_sizes': anchor_sizes,
  850. 'strides': [16]
  851. }
  852. train_proposal_cfg = {
  853. 'min_size': 0.0,
  854. 'nms_thresh': .7,
  855. 'pre_nms_top_n': 12000,
  856. 'post_nms_top_n': 2000,
  857. 'topk_after_collect': False
  858. }
  859. test_proposal_cfg = {
  860. 'min_size': 0.0,
  861. 'nms_thresh': .7,
  862. 'pre_nms_top_n': 6000
  863. if test_pre_nms_top_n is None else test_pre_nms_top_n,
  864. 'post_nms_top_n': test_post_nms_top_n
  865. }
  866. head = ppdet.modeling.Res5Head()
  867. roi_extractor_cfg = {
  868. 'resolution': 14,
  869. 'spatial_scale':
  870. [1. / i.stride for i in backbone.out_shape],
  871. 'sampling_ratio': 0,
  872. 'aligned': True
  873. }
  874. with_pool = True
  875. rpn_target_assign_cfg = {
  876. 'batch_size_per_im': rpn_batch_size_per_im,
  877. 'fg_fraction': rpn_fg_fraction,
  878. 'negative_overlap': .3,
  879. 'positive_overlap': .7,
  880. 'use_random': True
  881. }
  882. rpn_head = ppdet.modeling.RPNHead(
  883. anchor_generator=anchor_generator_cfg,
  884. rpn_target_assign=rpn_target_assign_cfg,
  885. train_proposal=train_proposal_cfg,
  886. test_proposal=test_proposal_cfg,
  887. in_channel=rpn_in_channel)
  888. bbox_assigner = BBoxAssigner(num_classes=num_classes)
  889. bbox_head = ppdet.modeling.BBoxHead(
  890. head=head,
  891. in_channel=head.out_shape[0].channels,
  892. roi_extractor=roi_extractor_cfg,
  893. with_pool=with_pool,
  894. bbox_assigner=bbox_assigner,
  895. num_classes=num_classes)
  896. bbox_post_process = ppdet.modeling.BBoxPostProcess(
  897. num_classes=num_classes,
  898. decode=ppdet.modeling.RCNNBox(num_classes=num_classes),
  899. nms=ppdet.modeling.MultiClassNMS(
  900. score_threshold=score_threshold,
  901. keep_top_k=keep_top_k,
  902. nms_threshold=nms_threshold))
  903. params.update({
  904. 'backbone': backbone,
  905. 'neck': neck,
  906. 'rpn_head': rpn_head,
  907. 'bbox_head': bbox_head,
  908. 'bbox_post_process': bbox_post_process
  909. })
  910. else:
  911. if backbone not in ['ResNet50', 'ResNet50_vd']:
  912. with_fpn = True
  913. self.with_fpn = with_fpn
  914. super(FasterRCNN, self).__init__(
  915. model_name='FasterRCNN', num_classes=num_classes, **params)
  916. def _compose_batch_transform(self, transforms, mode='train'):
  917. if mode == 'train':
  918. default_batch_transforms = [
  919. _BatchPadding(pad_to_stride=32 if self.with_fpn else -1)
  920. ]
  921. collate_batch = False
  922. else:
  923. default_batch_transforms = [
  924. _BatchPadding(pad_to_stride=32 if self.with_fpn else -1)
  925. ]
  926. collate_batch = True
  927. custom_batch_transforms = []
  928. for i, op in enumerate(transforms.transforms):
  929. if isinstance(op, (BatchRandomResize, BatchRandomResizeByShort)):
  930. if mode != 'train':
  931. raise Exception(
  932. "{} cannot be present in the {} transforms. ".format(
  933. op.__class__.__name__, mode) +
  934. "Please check the {} transforms.".format(mode))
  935. custom_batch_transforms.insert(0, copy.deepcopy(op))
  936. batch_transforms = BatchCompose(
  937. custom_batch_transforms + default_batch_transforms,
  938. collate_batch=collate_batch)
  939. return batch_transforms
  940. def _fix_transforms_shape(self, image_shape):
  941. if hasattr(self, 'test_transforms'):
  942. if self.test_transforms is not None:
  943. has_resize_op = False
  944. resize_op_idx = -1
  945. normalize_op_idx = len(self.test_transforms.transforms)
  946. for idx, op in enumerate(self.test_transforms.transforms):
  947. name = op.__class__.__name__
  948. if name == 'ResizeByShort':
  949. has_resize_op = True
  950. resize_op_idx = idx
  951. if name == 'Normalize':
  952. normalize_op_idx = idx
  953. if not has_resize_op:
  954. self.test_transforms.transforms.insert(
  955. normalize_op_idx,
  956. Resize(
  957. target_size=image_shape,
  958. keep_ratio=True,
  959. interp='CUBIC'))
  960. else:
  961. self.test_transforms.transforms[resize_op_idx] = Resize(
  962. target_size=image_shape,
  963. keep_ratio=True,
  964. interp='CUBIC')
  965. self.test_transforms.transforms.append(
  966. Padding(im_padding_value=[0., 0., 0.]))
  967. def _get_test_inputs(self, image_shape):
  968. if image_shape is not None:
  969. image_shape = self._check_image_shape(image_shape)
  970. self._fix_transforms_shape(image_shape[-2:])
  971. else:
  972. image_shape = [None, 3, -1, -1]
  973. if self.with_fpn:
  974. self.test_transforms.transforms.append(
  975. Padding(im_padding_value=[0., 0., 0.]))
  976. self.fixed_input_shape = image_shape
  977. return self._define_input_spec(image_shape)
  978. class PPYOLO(YOLOv3):
  979. def __init__(self,
  980. num_classes=80,
  981. backbone='ResNet50_vd_dcn',
  982. anchors=None,
  983. anchor_masks=None,
  984. use_coord_conv=True,
  985. use_iou_aware=True,
  986. use_spp=True,
  987. use_drop_block=True,
  988. scale_x_y=1.05,
  989. ignore_threshold=0.7,
  990. label_smooth=False,
  991. use_iou_loss=True,
  992. use_matrix_nms=True,
  993. nms_score_threshold=0.01,
  994. nms_topk=-1,
  995. nms_keep_topk=100,
  996. nms_iou_threshold=0.45,
  997. **params):
  998. self.init_params = locals()
  999. if backbone not in [
  1000. 'ResNet50_vd_dcn', 'ResNet18_vd', 'MobileNetV3_large',
  1001. 'MobileNetV3_small'
  1002. ]:
  1003. raise ValueError(
  1004. "backbone: {} is not supported. Please choose one of "
  1005. "('ResNet50_vd_dcn', 'ResNet18_vd', 'MobileNetV3_large', 'MobileNetV3_small')".
  1006. format(backbone))
  1007. self.backbone_name = backbone
  1008. if params.get('with_net', True):
  1009. if paddlex.env_info['place'] == 'gpu' and paddlex.env_info[
  1010. 'num'] > 1 and not os.environ.get('PADDLEX_EXPORT_STAGE'):
  1011. norm_type = 'sync_bn'
  1012. else:
  1013. norm_type = 'bn'
  1014. if anchors is None and anchor_masks is None:
  1015. if 'MobileNetV3' in backbone:
  1016. anchors = [[11, 18], [34, 47], [51, 126], [115, 71],
  1017. [120, 195], [254, 235]]
  1018. anchor_masks = [[3, 4, 5], [0, 1, 2]]
  1019. elif backbone == 'ResNet50_vd_dcn':
  1020. anchors = [[10, 13], [16, 30], [33, 23], [30, 61],
  1021. [62, 45], [59, 119], [116, 90], [156, 198],
  1022. [373, 326]]
  1023. anchor_masks = [[6, 7, 8], [3, 4, 5], [0, 1, 2]]
  1024. else:
  1025. anchors = [[10, 14], [23, 27], [37, 58], [81, 82],
  1026. [135, 169], [344, 319]]
  1027. anchor_masks = [[3, 4, 5], [0, 1, 2]]
  1028. elif anchors is None or anchor_masks is None:
  1029. raise ValueError(
  1030. "Please define both anchors and anchor_masks.")
  1031. if backbone == 'ResNet50_vd_dcn':
  1032. backbone = self._get_backbone(
  1033. 'ResNet',
  1034. variant='d',
  1035. norm_type=norm_type,
  1036. return_idx=[1, 2, 3],
  1037. dcn_v2_stages=[3],
  1038. freeze_at=-1,
  1039. freeze_norm=False,
  1040. norm_decay=0.)
  1041. downsample_ratios = [32, 16, 8]
  1042. elif backbone == 'ResNet18_vd':
  1043. backbone = self._get_backbone(
  1044. 'ResNet',
  1045. depth=18,
  1046. variant='d',
  1047. norm_type=norm_type,
  1048. return_idx=[2, 3],
  1049. freeze_at=-1,
  1050. freeze_norm=False,
  1051. norm_decay=0.)
  1052. downsample_ratios = [32, 16]
  1053. elif backbone == 'MobileNetV3_large':
  1054. backbone = self._get_backbone(
  1055. 'MobileNetV3',
  1056. model_name='large',
  1057. norm_type=norm_type,
  1058. scale=1,
  1059. with_extra_blocks=False,
  1060. extra_block_filters=[],
  1061. feature_maps=[13, 16])
  1062. downsample_ratios = [32, 16]
  1063. elif backbone == 'MobileNetV3_small':
  1064. backbone = self._get_backbone(
  1065. 'MobileNetV3',
  1066. model_name='small',
  1067. norm_type=norm_type,
  1068. scale=1,
  1069. with_extra_blocks=False,
  1070. extra_block_filters=[],
  1071. feature_maps=[9, 12])
  1072. downsample_ratios = [32, 16]
  1073. neck = ppdet.modeling.PPYOLOFPN(
  1074. norm_type=norm_type,
  1075. in_channels=[i.channels for i in backbone.out_shape],
  1076. coord_conv=use_coord_conv,
  1077. drop_block=use_drop_block,
  1078. spp=use_spp,
  1079. conv_block_num=0
  1080. if ('MobileNetV3' in self.backbone_name or
  1081. self.backbone_name == 'ResNet18_vd') else 2)
  1082. loss = ppdet.modeling.YOLOv3Loss(
  1083. num_classes=num_classes,
  1084. ignore_thresh=ignore_threshold,
  1085. downsample=downsample_ratios,
  1086. label_smooth=label_smooth,
  1087. scale_x_y=scale_x_y,
  1088. iou_loss=ppdet.modeling.IouLoss(
  1089. loss_weight=2.5, loss_square=True)
  1090. if use_iou_loss else None,
  1091. iou_aware_loss=ppdet.modeling.IouAwareLoss(loss_weight=1.0)
  1092. if use_iou_aware else None)
  1093. yolo_head = ppdet.modeling.YOLOv3Head(
  1094. in_channels=[i.channels for i in neck.out_shape],
  1095. anchors=anchors,
  1096. anchor_masks=anchor_masks,
  1097. num_classes=num_classes,
  1098. loss=loss,
  1099. iou_aware=use_iou_aware)
  1100. if use_matrix_nms:
  1101. nms = ppdet.modeling.MatrixNMS(
  1102. keep_top_k=nms_keep_topk,
  1103. score_threshold=nms_score_threshold,
  1104. post_threshold=.05
  1105. if 'MobileNetV3' in self.backbone_name else .01,
  1106. nms_top_k=nms_topk,
  1107. background_label=-1)
  1108. else:
  1109. nms = ppdet.modeling.MultiClassNMS(
  1110. score_threshold=nms_score_threshold,
  1111. nms_top_k=nms_topk,
  1112. keep_top_k=nms_keep_topk,
  1113. nms_threshold=nms_iou_threshold)
  1114. post_process = ppdet.modeling.BBoxPostProcess(
  1115. decode=ppdet.modeling.YOLOBox(
  1116. num_classes=num_classes,
  1117. conf_thresh=.005
  1118. if 'MobileNetV3' in self.backbone_name else .01,
  1119. scale_x_y=scale_x_y),
  1120. nms=nms)
  1121. params.update({
  1122. 'backbone': backbone,
  1123. 'neck': neck,
  1124. 'yolo_head': yolo_head,
  1125. 'post_process': post_process
  1126. })
  1127. super(YOLOv3, self).__init__(
  1128. model_name='YOLOv3', num_classes=num_classes, **params)
  1129. self.anchors = anchors
  1130. self.anchor_masks = anchor_masks
  1131. self.downsample_ratios = downsample_ratios
  1132. self.model_name = 'PPYOLO'
  1133. class PPYOLOTiny(YOLOv3):
  1134. def __init__(self,
  1135. num_classes=80,
  1136. backbone='MobileNetV3',
  1137. anchors=[[10, 15], [24, 36], [72, 42], [35, 87], [102, 96],
  1138. [60, 170], [220, 125], [128, 222], [264, 266]],
  1139. anchor_masks=[[6, 7, 8], [3, 4, 5], [0, 1, 2]],
  1140. use_iou_aware=False,
  1141. use_spp=True,
  1142. use_drop_block=True,
  1143. scale_x_y=1.05,
  1144. ignore_threshold=0.5,
  1145. label_smooth=False,
  1146. use_iou_loss=True,
  1147. use_matrix_nms=False,
  1148. nms_score_threshold=0.005,
  1149. nms_topk=1000,
  1150. nms_keep_topk=100,
  1151. nms_iou_threshold=0.45,
  1152. **params):
  1153. self.init_params = locals()
  1154. if backbone != 'MobileNetV3':
  1155. logging.warning(
  1156. "PPYOLOTiny only supports MobileNetV3 as backbone. "
  1157. "Backbone is forcibly set to MobileNetV3.")
  1158. self.backbone_name = 'MobileNetV3'
  1159. if params.get('with_net', True):
  1160. if paddlex.env_info['place'] == 'gpu' and paddlex.env_info[
  1161. 'num'] > 1 and not os.environ.get('PADDLEX_EXPORT_STAGE'):
  1162. norm_type = 'sync_bn'
  1163. else:
  1164. norm_type = 'bn'
  1165. backbone = self._get_backbone(
  1166. 'MobileNetV3',
  1167. model_name='large',
  1168. norm_type=norm_type,
  1169. scale=.5,
  1170. with_extra_blocks=False,
  1171. extra_block_filters=[],
  1172. feature_maps=[7, 13, 16])
  1173. downsample_ratios = [32, 16, 8]
  1174. neck = ppdet.modeling.PPYOLOTinyFPN(
  1175. detection_block_channels=[160, 128, 96],
  1176. in_channels=[i.channels for i in backbone.out_shape],
  1177. spp=use_spp,
  1178. drop_block=use_drop_block)
  1179. loss = ppdet.modeling.YOLOv3Loss(
  1180. num_classes=num_classes,
  1181. ignore_thresh=ignore_threshold,
  1182. downsample=downsample_ratios,
  1183. label_smooth=label_smooth,
  1184. scale_x_y=scale_x_y,
  1185. iou_loss=ppdet.modeling.IouLoss(
  1186. loss_weight=2.5, loss_square=True)
  1187. if use_iou_loss else None,
  1188. iou_aware_loss=ppdet.modeling.IouAwareLoss(loss_weight=1.0)
  1189. if use_iou_aware else None)
  1190. yolo_head = ppdet.modeling.YOLOv3Head(
  1191. in_channels=[i.channels for i in neck.out_shape],
  1192. anchors=anchors,
  1193. anchor_masks=anchor_masks,
  1194. num_classes=num_classes,
  1195. loss=loss,
  1196. iou_aware=use_iou_aware)
  1197. if use_matrix_nms:
  1198. nms = ppdet.modeling.MatrixNMS(
  1199. keep_top_k=nms_keep_topk,
  1200. score_threshold=nms_score_threshold,
  1201. post_threshold=.05,
  1202. nms_top_k=nms_topk,
  1203. background_label=-1)
  1204. else:
  1205. nms = ppdet.modeling.MultiClassNMS(
  1206. score_threshold=nms_score_threshold,
  1207. nms_top_k=nms_topk,
  1208. keep_top_k=nms_keep_topk,
  1209. nms_threshold=nms_iou_threshold)
  1210. post_process = ppdet.modeling.BBoxPostProcess(
  1211. decode=ppdet.modeling.YOLOBox(
  1212. num_classes=num_classes,
  1213. conf_thresh=.005,
  1214. downsample_ratio=32,
  1215. clip_bbox=True,
  1216. scale_x_y=scale_x_y),
  1217. nms=nms)
  1218. params.update({
  1219. 'backbone': backbone,
  1220. 'neck': neck,
  1221. 'yolo_head': yolo_head,
  1222. 'post_process': post_process
  1223. })
  1224. super(YOLOv3, self).__init__(
  1225. model_name='YOLOv3', num_classes=num_classes, **params)
  1226. self.anchors = anchors
  1227. self.anchor_masks = anchor_masks
  1228. self.downsample_ratios = downsample_ratios
  1229. self.model_name = 'PPYOLOTiny'
  1230. class PPYOLOv2(YOLOv3):
  1231. def __init__(self,
  1232. num_classes=80,
  1233. backbone='ResNet50_vd_dcn',
  1234. anchors=[[10, 13], [16, 30], [33, 23], [30, 61], [62, 45],
  1235. [59, 119], [116, 90], [156, 198], [373, 326]],
  1236. anchor_masks=[[6, 7, 8], [3, 4, 5], [0, 1, 2]],
  1237. use_iou_aware=True,
  1238. use_spp=True,
  1239. use_drop_block=True,
  1240. scale_x_y=1.05,
  1241. ignore_threshold=0.7,
  1242. label_smooth=False,
  1243. use_iou_loss=True,
  1244. use_matrix_nms=True,
  1245. nms_score_threshold=0.01,
  1246. nms_topk=-1,
  1247. nms_keep_topk=100,
  1248. nms_iou_threshold=0.45,
  1249. **params):
  1250. self.init_params = locals()
  1251. if backbone not in ['ResNet50_vd_dcn', 'ResNet101_vd_dcn']:
  1252. raise ValueError(
  1253. "backbone: {} is not supported. Please choose one of "
  1254. "('ResNet50_vd_dcn', 'ResNet101_vd_dcn')".format(backbone))
  1255. self.backbone_name = backbone
  1256. if params.get('with_net', True):
  1257. if paddlex.env_info['place'] == 'gpu' and paddlex.env_info[
  1258. 'num'] > 1 and not os.environ.get('PADDLEX_EXPORT_STAGE'):
  1259. norm_type = 'sync_bn'
  1260. else:
  1261. norm_type = 'bn'
  1262. if backbone == 'ResNet50_vd_dcn':
  1263. backbone = self._get_backbone(
  1264. 'ResNet',
  1265. variant='d',
  1266. norm_type=norm_type,
  1267. return_idx=[1, 2, 3],
  1268. dcn_v2_stages=[3],
  1269. freeze_at=-1,
  1270. freeze_norm=False,
  1271. norm_decay=0.)
  1272. downsample_ratios = [32, 16, 8]
  1273. elif backbone == 'ResNet101_vd_dcn':
  1274. backbone = self._get_backbone(
  1275. 'ResNet',
  1276. depth=101,
  1277. variant='d',
  1278. norm_type=norm_type,
  1279. return_idx=[1, 2, 3],
  1280. dcn_v2_stages=[3],
  1281. freeze_at=-1,
  1282. freeze_norm=False,
  1283. norm_decay=0.)
  1284. downsample_ratios = [32, 16, 8]
  1285. neck = ppdet.modeling.PPYOLOPAN(
  1286. norm_type=norm_type,
  1287. in_channels=[i.channels for i in backbone.out_shape],
  1288. drop_block=use_drop_block,
  1289. block_size=3,
  1290. keep_prob=.9,
  1291. spp=use_spp)
  1292. loss = ppdet.modeling.YOLOv3Loss(
  1293. num_classes=num_classes,
  1294. ignore_thresh=ignore_threshold,
  1295. downsample=downsample_ratios,
  1296. label_smooth=label_smooth,
  1297. scale_x_y=scale_x_y,
  1298. iou_loss=ppdet.modeling.IouLoss(
  1299. loss_weight=2.5, loss_square=True)
  1300. if use_iou_loss else None,
  1301. iou_aware_loss=ppdet.modeling.IouAwareLoss(loss_weight=1.0)
  1302. if use_iou_aware else None)
  1303. yolo_head = ppdet.modeling.YOLOv3Head(
  1304. in_channels=[i.channels for i in neck.out_shape],
  1305. anchors=anchors,
  1306. anchor_masks=anchor_masks,
  1307. num_classes=num_classes,
  1308. loss=loss,
  1309. iou_aware=use_iou_aware,
  1310. iou_aware_factor=.5)
  1311. if use_matrix_nms:
  1312. nms = ppdet.modeling.MatrixNMS(
  1313. keep_top_k=nms_keep_topk,
  1314. score_threshold=nms_score_threshold,
  1315. post_threshold=.01,
  1316. nms_top_k=nms_topk,
  1317. background_label=-1)
  1318. else:
  1319. nms = ppdet.modeling.MultiClassNMS(
  1320. score_threshold=nms_score_threshold,
  1321. nms_top_k=nms_topk,
  1322. keep_top_k=nms_keep_topk,
  1323. nms_threshold=nms_iou_threshold)
  1324. post_process = ppdet.modeling.BBoxPostProcess(
  1325. decode=ppdet.modeling.YOLOBox(
  1326. num_classes=num_classes,
  1327. conf_thresh=.01,
  1328. downsample_ratio=32,
  1329. clip_bbox=True,
  1330. scale_x_y=scale_x_y),
  1331. nms=nms)
  1332. params.update({
  1333. 'backbone': backbone,
  1334. 'neck': neck,
  1335. 'yolo_head': yolo_head,
  1336. 'post_process': post_process
  1337. })
  1338. super(YOLOv3, self).__init__(
  1339. model_name='YOLOv3', num_classes=num_classes, **params)
  1340. self.anchors = anchors
  1341. self.anchor_masks = anchor_masks
  1342. self.downsample_ratios = downsample_ratios
  1343. self.model_name = 'PPYOLOv2'
  1344. def _get_test_inputs(self, image_shape):
  1345. if image_shape is not None:
  1346. image_shape = self._check_image_shape(image_shape)
  1347. self._fix_transforms_shape(image_shape[-2:])
  1348. else:
  1349. image_shape = [None, 3, 608, 608]
  1350. logging.warning(
  1351. '[Important!!!] When exporting inference model for {},'.format(
  1352. self.__class__.__name__) +
  1353. ' if fixed_input_shape is not set, it will be forcibly set to [None, 3, 608, 608]. '
  1354. +
  1355. 'Please check image shape after transforms is [3, 608, 608], if not, fixed_input_shape '
  1356. + 'should be specified manually.')
  1357. self.fixed_input_shape = image_shape
  1358. return self._define_input_spec(image_shape)
  1359. class MaskRCNN(BaseDetector):
  1360. def __init__(self,
  1361. num_classes=80,
  1362. backbone='ResNet50_vd',
  1363. with_fpn=True,
  1364. with_dcn=False,
  1365. aspect_ratios=[0.5, 1.0, 2.0],
  1366. anchor_sizes=[[32], [64], [128], [256], [512]],
  1367. keep_top_k=100,
  1368. nms_threshold=0.5,
  1369. score_threshold=0.05,
  1370. fpn_num_channels=256,
  1371. rpn_batch_size_per_im=256,
  1372. rpn_fg_fraction=0.5,
  1373. test_pre_nms_top_n=None,
  1374. test_post_nms_top_n=1000,
  1375. **params):
  1376. self.init_params = locals()
  1377. if backbone not in [
  1378. 'ResNet50', 'ResNet50_vd', 'ResNet50_vd_ssld', 'ResNet101',
  1379. 'ResNet101_vd'
  1380. ]:
  1381. raise ValueError(
  1382. "backbone: {} is not supported. Please choose one of "
  1383. "('ResNet50', 'ResNet50_vd', 'ResNet50_vd_ssld', 'ResNet101', 'ResNet101_vd')".
  1384. format(backbone))
  1385. self.backbone_name = backbone + '_fpn' if with_fpn else backbone
  1386. dcn_v2_stages = [1, 2, 3] if with_dcn else [-1]
  1387. if params.get('with_net', True):
  1388. if backbone == 'ResNet50':
  1389. if with_fpn:
  1390. backbone = self._get_backbone(
  1391. 'ResNet',
  1392. norm_type='bn',
  1393. freeze_at=0,
  1394. return_idx=[0, 1, 2, 3],
  1395. num_stages=4,
  1396. dcn_v2_stages=dcn_v2_stages)
  1397. else:
  1398. if with_dcn:
  1399. logging.warning(
  1400. "Backbone {} should be used along with dcn disabled, 'with_dcn' is forcibly set to False".
  1401. format(backbone))
  1402. backbone = self._get_backbone(
  1403. 'ResNet',
  1404. norm_type='bn',
  1405. freeze_at=0,
  1406. return_idx=[2],
  1407. num_stages=3)
  1408. elif 'ResNet50_vd' in backbone:
  1409. if not with_fpn:
  1410. logging.warning(
  1411. "Backbone {} should be used along with fpn enabled, 'with_fpn' is forcibly set to True".
  1412. format(backbone))
  1413. with_fpn = True
  1414. backbone = self._get_backbone(
  1415. 'ResNet',
  1416. variant='d',
  1417. norm_type='bn',
  1418. freeze_at=0,
  1419. return_idx=[0, 1, 2, 3],
  1420. num_stages=4,
  1421. lr_mult_list=[0.05, 0.05, 0.1, 0.15]
  1422. if '_ssld' in backbone else [1.0, 1.0, 1.0, 1.0],
  1423. dcn_v2_stages=dcn_v2_stages)
  1424. else:
  1425. if not with_fpn:
  1426. logging.warning(
  1427. "Backbone {} should be used along with fpn enabled, 'with_fpn' is forcibly set to True".
  1428. format(backbone))
  1429. with_fpn = True
  1430. backbone = self._get_backbone(
  1431. 'ResNet',
  1432. variant='d' if '_vd' in backbone else 'b',
  1433. depth=101,
  1434. norm_type='bn',
  1435. freeze_at=0,
  1436. return_idx=[0, 1, 2, 3],
  1437. num_stages=4,
  1438. dcn_v2_stages=dcn_v2_stages)
  1439. rpn_in_channel = backbone.out_shape[0].channels
  1440. if with_fpn:
  1441. neck = ppdet.modeling.FPN(
  1442. in_channels=[i.channels for i in backbone.out_shape],
  1443. out_channel=fpn_num_channels,
  1444. spatial_scales=[
  1445. 1.0 / i.stride for i in backbone.out_shape
  1446. ])
  1447. rpn_in_channel = neck.out_shape[0].channels
  1448. anchor_generator_cfg = {
  1449. 'aspect_ratios': aspect_ratios,
  1450. 'anchor_sizes': anchor_sizes,
  1451. 'strides': [4, 8, 16, 32, 64]
  1452. }
  1453. train_proposal_cfg = {
  1454. 'min_size': 0.0,
  1455. 'nms_thresh': .7,
  1456. 'pre_nms_top_n': 2000,
  1457. 'post_nms_top_n': 1000,
  1458. 'topk_after_collect': True
  1459. }
  1460. test_proposal_cfg = {
  1461. 'min_size': 0.0,
  1462. 'nms_thresh': .7,
  1463. 'pre_nms_top_n': 1000
  1464. if test_pre_nms_top_n is None else test_pre_nms_top_n,
  1465. 'post_nms_top_n': test_post_nms_top_n
  1466. }
  1467. bb_head = ppdet.modeling.TwoFCHead(
  1468. in_channel=neck.out_shape[0].channels, out_channel=1024)
  1469. bb_roi_extractor_cfg = {
  1470. 'resolution': 7,
  1471. 'spatial_scale': [1. / i.stride for i in neck.out_shape],
  1472. 'sampling_ratio': 0,
  1473. 'aligned': True
  1474. }
  1475. with_pool = False
  1476. m_head = ppdet.modeling.MaskFeat(
  1477. in_channel=neck.out_shape[0].channels,
  1478. out_channel=256,
  1479. num_convs=4)
  1480. m_roi_extractor_cfg = {
  1481. 'resolution': 14,
  1482. 'spatial_scale': [1. / i.stride for i in neck.out_shape],
  1483. 'sampling_ratio': 0,
  1484. 'aligned': True
  1485. }
  1486. mask_assigner = MaskAssigner(
  1487. num_classes=num_classes, mask_resolution=28)
  1488. share_bbox_feat = False
  1489. else:
  1490. neck = None
  1491. anchor_generator_cfg = {
  1492. 'aspect_ratios': aspect_ratios,
  1493. 'anchor_sizes': anchor_sizes,
  1494. 'strides': [16]
  1495. }
  1496. train_proposal_cfg = {
  1497. 'min_size': 0.0,
  1498. 'nms_thresh': .7,
  1499. 'pre_nms_top_n': 12000,
  1500. 'post_nms_top_n': 2000,
  1501. 'topk_after_collect': False
  1502. }
  1503. test_proposal_cfg = {
  1504. 'min_size': 0.0,
  1505. 'nms_thresh': .7,
  1506. 'pre_nms_top_n': 6000
  1507. if test_pre_nms_top_n is None else test_pre_nms_top_n,
  1508. 'post_nms_top_n': test_post_nms_top_n
  1509. }
  1510. bb_head = ppdet.modeling.Res5Head()
  1511. bb_roi_extractor_cfg = {
  1512. 'resolution': 14,
  1513. 'spatial_scale':
  1514. [1. / i.stride for i in backbone.out_shape],
  1515. 'sampling_ratio': 0,
  1516. 'aligned': True
  1517. }
  1518. with_pool = True
  1519. m_head = ppdet.modeling.MaskFeat(
  1520. in_channel=bb_head.out_shape[0].channels,
  1521. out_channel=256,
  1522. num_convs=0)
  1523. m_roi_extractor_cfg = {
  1524. 'resolution': 14,
  1525. 'spatial_scale':
  1526. [1. / i.stride for i in backbone.out_shape],
  1527. 'sampling_ratio': 0,
  1528. 'aligned': True
  1529. }
  1530. mask_assigner = MaskAssigner(
  1531. num_classes=num_classes, mask_resolution=14)
  1532. share_bbox_feat = True
  1533. rpn_target_assign_cfg = {
  1534. 'batch_size_per_im': rpn_batch_size_per_im,
  1535. 'fg_fraction': rpn_fg_fraction,
  1536. 'negative_overlap': .3,
  1537. 'positive_overlap': .7,
  1538. 'use_random': True
  1539. }
  1540. rpn_head = ppdet.modeling.RPNHead(
  1541. anchor_generator=anchor_generator_cfg,
  1542. rpn_target_assign=rpn_target_assign_cfg,
  1543. train_proposal=train_proposal_cfg,
  1544. test_proposal=test_proposal_cfg,
  1545. in_channel=rpn_in_channel)
  1546. bbox_assigner = BBoxAssigner(num_classes=num_classes)
  1547. bbox_head = ppdet.modeling.BBoxHead(
  1548. head=bb_head,
  1549. in_channel=bb_head.out_shape[0].channels,
  1550. roi_extractor=bb_roi_extractor_cfg,
  1551. with_pool=with_pool,
  1552. bbox_assigner=bbox_assigner,
  1553. num_classes=num_classes)
  1554. mask_head = ppdet.modeling.MaskHead(
  1555. head=m_head,
  1556. roi_extractor=m_roi_extractor_cfg,
  1557. mask_assigner=mask_assigner,
  1558. share_bbox_feat=share_bbox_feat,
  1559. num_classes=num_classes)
  1560. bbox_post_process = ppdet.modeling.BBoxPostProcess(
  1561. num_classes=num_classes,
  1562. decode=ppdet.modeling.RCNNBox(num_classes=num_classes),
  1563. nms=ppdet.modeling.MultiClassNMS(
  1564. score_threshold=score_threshold,
  1565. keep_top_k=keep_top_k,
  1566. nms_threshold=nms_threshold))
  1567. mask_post_process = ppdet.modeling.MaskPostProcess(
  1568. binary_thresh=.5)
  1569. params.update({
  1570. 'backbone': backbone,
  1571. 'neck': neck,
  1572. 'rpn_head': rpn_head,
  1573. 'bbox_head': bbox_head,
  1574. 'mask_head': mask_head,
  1575. 'bbox_post_process': bbox_post_process,
  1576. 'mask_post_process': mask_post_process
  1577. })
  1578. self.with_fpn = with_fpn
  1579. super(MaskRCNN, self).__init__(
  1580. model_name='MaskRCNN', num_classes=num_classes, **params)
  1581. def _compose_batch_transform(self, transforms, mode='train'):
  1582. if mode == 'train':
  1583. default_batch_transforms = [
  1584. _BatchPadding(pad_to_stride=32 if self.with_fpn else -1)
  1585. ]
  1586. collate_batch = False
  1587. else:
  1588. default_batch_transforms = [
  1589. _BatchPadding(pad_to_stride=32 if self.with_fpn else -1)
  1590. ]
  1591. collate_batch = True
  1592. custom_batch_transforms = []
  1593. for i, op in enumerate(transforms.transforms):
  1594. if isinstance(op, (BatchRandomResize, BatchRandomResizeByShort)):
  1595. if mode != 'train':
  1596. raise Exception(
  1597. "{} cannot be present in the {} transforms. ".format(
  1598. op.__class__.__name__, mode) +
  1599. "Please check the {} transforms.".format(mode))
  1600. custom_batch_transforms.insert(0, copy.deepcopy(op))
  1601. batch_transforms = BatchCompose(
  1602. custom_batch_transforms + default_batch_transforms,
  1603. collate_batch=collate_batch)
  1604. return batch_transforms
  1605. def _fix_transforms_shape(self, image_shape):
  1606. if hasattr(self, 'test_transforms'):
  1607. if self.test_transforms is not None:
  1608. has_resize_op = False
  1609. resize_op_idx = -1
  1610. normalize_op_idx = len(self.test_transforms.transforms)
  1611. for idx, op in enumerate(self.test_transforms.transforms):
  1612. name = op.__class__.__name__
  1613. if name == 'ResizeByShort':
  1614. has_resize_op = True
  1615. resize_op_idx = idx
  1616. if name == 'Normalize':
  1617. normalize_op_idx = idx
  1618. if not has_resize_op:
  1619. self.test_transforms.transforms.insert(
  1620. normalize_op_idx,
  1621. Resize(
  1622. target_size=image_shape,
  1623. keep_ratio=True,
  1624. interp='CUBIC'))
  1625. else:
  1626. self.test_transforms.transforms[resize_op_idx] = Resize(
  1627. target_size=image_shape,
  1628. keep_ratio=True,
  1629. interp='CUBIC')
  1630. self.test_transforms.transforms.append(
  1631. Padding(im_padding_value=[0., 0., 0.]))
  1632. def _get_test_inputs(self, image_shape):
  1633. if image_shape is not None:
  1634. image_shape = self._check_image_shape(image_shape)
  1635. self._fix_transforms_shape(image_shape[-2:])
  1636. else:
  1637. image_shape = [None, 3, -1, -1]
  1638. if self.with_fpn:
  1639. self.test_transforms.transforms.append(
  1640. Padding(im_padding_value=[0., 0., 0.]))
  1641. self.fixed_input_shape = image_shape
  1642. return self._define_input_spec(image_shape)