detector.py 74 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783
  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):
  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, to_tensor=True):
  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. if to_tensor:
  477. for k, v in batch_samples.items():
  478. batch_samples[k] = paddle.to_tensor(v)
  479. return batch_samples
  480. def _postprocess(self, batch_pred):
  481. infer_result = {}
  482. if 'bbox' in batch_pred:
  483. bboxes = batch_pred['bbox']
  484. bbox_nums = batch_pred['bbox_num']
  485. det_res = []
  486. k = 0
  487. for i in range(len(bbox_nums)):
  488. det_nums = bbox_nums[i]
  489. for j in range(det_nums):
  490. dt = bboxes[k]
  491. k = k + 1
  492. num_id, score, xmin, ymin, xmax, ymax = dt.tolist()
  493. if int(num_id) < 0:
  494. continue
  495. category = self.labels[int(num_id)]
  496. w = xmax - xmin
  497. h = ymax - ymin
  498. bbox = [xmin, ymin, w, h]
  499. dt_res = {
  500. 'category_id': int(num_id),
  501. 'category': category,
  502. 'bbox': bbox,
  503. 'score': score
  504. }
  505. det_res.append(dt_res)
  506. infer_result['bbox'] = det_res
  507. if 'mask' in batch_pred:
  508. masks = batch_pred['mask']
  509. bboxes = batch_pred['bbox']
  510. mask_nums = batch_pred['bbox_num']
  511. seg_res = []
  512. k = 0
  513. for i in range(len(mask_nums)):
  514. det_nums = mask_nums[i]
  515. for j in range(det_nums):
  516. mask = masks[k].astype(np.uint8)
  517. score = float(bboxes[k][1])
  518. label = int(bboxes[k][0])
  519. k = k + 1
  520. if label == -1:
  521. continue
  522. category = self.labels[int(label)]
  523. import pycocotools.mask as mask_util
  524. rle = mask_util.encode(
  525. np.array(
  526. mask[:, :, None], order="F", dtype="uint8"))[0]
  527. if six.PY3:
  528. if 'counts' in rle:
  529. rle['counts'] = rle['counts'].decode("utf8")
  530. sg_res = {
  531. 'category_id': int(label),
  532. 'category': category,
  533. 'mask': rle,
  534. 'score': score
  535. }
  536. seg_res.append(sg_res)
  537. infer_result['mask'] = seg_res
  538. bbox_num = batch_pred['bbox_num']
  539. results = []
  540. start = 0
  541. for num in bbox_num:
  542. end = start + num
  543. curr_res = infer_result['bbox'][start:end]
  544. if 'mask' in infer_result:
  545. mask_res = infer_result['mask'][start:end]
  546. for box, mask in zip(curr_res, mask_res):
  547. box.update(mask)
  548. results.append(curr_res)
  549. start = end
  550. return results
  551. class YOLOv3(BaseDetector):
  552. def __init__(self,
  553. num_classes=80,
  554. backbone='MobileNetV1',
  555. anchors=[[10, 13], [16, 30], [33, 23], [30, 61], [62, 45],
  556. [59, 119], [116, 90], [156, 198], [373, 326]],
  557. anchor_masks=[[6, 7, 8], [3, 4, 5], [0, 1, 2]],
  558. ignore_threshold=0.7,
  559. nms_score_threshold=0.01,
  560. nms_topk=1000,
  561. nms_keep_topk=100,
  562. nms_iou_threshold=0.45,
  563. label_smooth=False,
  564. **params):
  565. self.init_params = locals()
  566. if backbone not in [
  567. 'MobileNetV1', 'MobileNetV1_ssld', 'MobileNetV3',
  568. 'MobileNetV3_ssld', 'DarkNet53', 'ResNet50_vd_dcn', 'ResNet34'
  569. ]:
  570. raise ValueError(
  571. "backbone: {} is not supported. Please choose one of "
  572. "('MobileNetV1', 'MobileNetV1_ssld', 'MobileNetV3', 'MobileNetV3_ssld', 'DarkNet53', 'ResNet50_vd_dcn', 'ResNet34')".
  573. format(backbone))
  574. self.backbone_name = backbone
  575. if params.get('with_net', True):
  576. if paddlex.env_info['place'] == 'gpu' and paddlex.env_info[
  577. 'num'] > 1 and not os.environ.get('PADDLEX_EXPORT_STAGE'):
  578. norm_type = 'sync_bn'
  579. else:
  580. norm_type = 'bn'
  581. if 'MobileNetV1' in backbone:
  582. norm_type = 'bn'
  583. backbone = self._get_backbone('MobileNet', norm_type=norm_type)
  584. elif 'MobileNetV3' in backbone:
  585. backbone = self._get_backbone(
  586. 'MobileNetV3',
  587. norm_type=norm_type,
  588. feature_maps=[7, 13, 16])
  589. elif backbone == 'ResNet50_vd_dcn':
  590. backbone = self._get_backbone(
  591. 'ResNet',
  592. norm_type=norm_type,
  593. variant='d',
  594. return_idx=[1, 2, 3],
  595. dcn_v2_stages=[3],
  596. freeze_at=-1,
  597. freeze_norm=False)
  598. elif backbone == 'ResNet34':
  599. backbone = self._get_backbone(
  600. 'ResNet',
  601. depth=34,
  602. norm_type=norm_type,
  603. return_idx=[1, 2, 3],
  604. freeze_at=-1,
  605. freeze_norm=False,
  606. norm_decay=0.)
  607. else:
  608. backbone = self._get_backbone('DarkNet', norm_type=norm_type)
  609. neck = ppdet.modeling.YOLOv3FPN(
  610. norm_type=norm_type,
  611. in_channels=[i.channels for i in backbone.out_shape])
  612. loss = ppdet.modeling.YOLOv3Loss(
  613. num_classes=num_classes,
  614. ignore_thresh=ignore_threshold,
  615. label_smooth=label_smooth)
  616. yolo_head = ppdet.modeling.YOLOv3Head(
  617. in_channels=[i.channels for i in neck.out_shape],
  618. anchors=anchors,
  619. anchor_masks=anchor_masks,
  620. num_classes=num_classes,
  621. loss=loss)
  622. post_process = ppdet.modeling.BBoxPostProcess(
  623. decode=ppdet.modeling.YOLOBox(num_classes=num_classes),
  624. nms=ppdet.modeling.MultiClassNMS(
  625. score_threshold=nms_score_threshold,
  626. nms_top_k=nms_topk,
  627. keep_top_k=nms_keep_topk,
  628. nms_threshold=nms_iou_threshold))
  629. params.update({
  630. 'backbone': backbone,
  631. 'neck': neck,
  632. 'yolo_head': yolo_head,
  633. 'post_process': post_process
  634. })
  635. super(YOLOv3, self).__init__(
  636. model_name='YOLOv3', num_classes=num_classes, **params)
  637. self.anchors = anchors
  638. self.anchor_masks = anchor_masks
  639. def _compose_batch_transform(self, transforms, mode='train'):
  640. if mode == 'train':
  641. default_batch_transforms = [
  642. _BatchPadding(pad_to_stride=-1), _NormalizeBox(),
  643. _PadBox(getattr(self, 'num_max_boxes', 50)), _BboxXYXY2XYWH(),
  644. _Gt2YoloTarget(
  645. anchor_masks=self.anchor_masks,
  646. anchors=self.anchors,
  647. downsample_ratios=getattr(self, 'downsample_ratios',
  648. [32, 16, 8]),
  649. num_classes=self.num_classes)
  650. ]
  651. else:
  652. default_batch_transforms = [_BatchPadding(pad_to_stride=-1)]
  653. if mode == 'eval' and self.metric == 'voc':
  654. collate_batch = False
  655. else:
  656. collate_batch = True
  657. custom_batch_transforms = []
  658. for i, op in enumerate(transforms.transforms):
  659. if isinstance(op, (BatchRandomResize, BatchRandomResizeByShort)):
  660. if mode != 'train':
  661. raise Exception(
  662. "{} cannot be present in the {} transforms. ".format(
  663. op.__class__.__name__, mode) +
  664. "Please check the {} transforms.".format(mode))
  665. custom_batch_transforms.insert(0, copy.deepcopy(op))
  666. batch_transforms = BatchCompose(
  667. custom_batch_transforms + default_batch_transforms,
  668. collate_batch=collate_batch)
  669. return batch_transforms
  670. def _fix_transforms_shape(self, image_shape):
  671. if hasattr(self, 'test_transforms'):
  672. if self.test_transforms is not None:
  673. has_resize_op = False
  674. resize_op_idx = -1
  675. normalize_op_idx = len(self.test_transforms.transforms)
  676. for idx, op in enumerate(self.test_transforms.transforms):
  677. name = op.__class__.__name__
  678. if name == 'Resize':
  679. has_resize_op = True
  680. resize_op_idx = idx
  681. if name == 'Normalize':
  682. normalize_op_idx = idx
  683. if not has_resize_op:
  684. self.test_transforms.transforms.insert(
  685. normalize_op_idx,
  686. Resize(
  687. target_size=image_shape, interp='CUBIC'))
  688. else:
  689. self.test_transforms.transforms[
  690. resize_op_idx].target_size = image_shape
  691. class FasterRCNN(BaseDetector):
  692. def __init__(self,
  693. num_classes=80,
  694. backbone='ResNet50',
  695. with_fpn=True,
  696. with_dcn=False,
  697. aspect_ratios=[0.5, 1.0, 2.0],
  698. anchor_sizes=[[32], [64], [128], [256], [512]],
  699. keep_top_k=100,
  700. nms_threshold=0.5,
  701. score_threshold=0.05,
  702. fpn_num_channels=256,
  703. rpn_batch_size_per_im=256,
  704. rpn_fg_fraction=0.5,
  705. test_pre_nms_top_n=None,
  706. test_post_nms_top_n=1000,
  707. **params):
  708. self.init_params = locals()
  709. if backbone not in [
  710. 'ResNet50', 'ResNet50_vd', 'ResNet50_vd_ssld', 'ResNet34',
  711. 'ResNet34_vd', 'ResNet101', 'ResNet101_vd', 'HRNet_W18'
  712. ]:
  713. raise ValueError(
  714. "backbone: {} is not supported. Please choose one of "
  715. "('ResNet50', 'ResNet50_vd', 'ResNet50_vd_ssld', 'ResNet34', 'ResNet34_vd', "
  716. "'ResNet101', 'ResNet101_vd', 'HRNet_W18')".format(backbone))
  717. self.backbone_name = backbone
  718. if params.get('with_net', True):
  719. dcn_v2_stages = [1, 2, 3] if with_dcn else [-1]
  720. if backbone == 'HRNet_W18':
  721. if not with_fpn:
  722. logging.warning(
  723. "Backbone {} should be used along with fpn enabled, 'with_fpn' is forcibly set to True".
  724. format(backbone))
  725. with_fpn = True
  726. if with_dcn:
  727. logging.warning(
  728. "Backbone {} should be used along with dcn disabled, 'with_dcn' is forcibly set to False".
  729. format(backbone))
  730. backbone = self._get_backbone(
  731. 'HRNet', width=18, freeze_at=0, return_idx=[0, 1, 2, 3])
  732. elif backbone == 'ResNet50_vd_ssld':
  733. if not with_fpn:
  734. logging.warning(
  735. "Backbone {} should be used along with fpn enabled, 'with_fpn' is forcibly set to True".
  736. format(backbone))
  737. with_fpn = True
  738. backbone = self._get_backbone(
  739. 'ResNet',
  740. variant='d',
  741. norm_type='bn',
  742. freeze_at=0,
  743. return_idx=[0, 1, 2, 3],
  744. num_stages=4,
  745. lr_mult_list=[0.05, 0.05, 0.1, 0.15],
  746. dcn_v2_stages=dcn_v2_stages)
  747. elif 'ResNet50' in backbone:
  748. if with_fpn:
  749. backbone = self._get_backbone(
  750. 'ResNet',
  751. variant='d' if '_vd' in backbone else 'b',
  752. norm_type='bn',
  753. freeze_at=0,
  754. return_idx=[0, 1, 2, 3],
  755. num_stages=4,
  756. dcn_v2_stages=dcn_v2_stages)
  757. else:
  758. if with_dcn:
  759. logging.warning(
  760. "Backbone {} without fpn should be used along with dcn disabled, 'with_dcn' is forcibly set to False".
  761. format(backbone))
  762. backbone = self._get_backbone(
  763. 'ResNet',
  764. variant='d' if '_vd' in backbone else 'b',
  765. norm_type='bn',
  766. freeze_at=0,
  767. return_idx=[2],
  768. num_stages=3)
  769. elif 'ResNet34' in backbone:
  770. if not with_fpn:
  771. logging.warning(
  772. "Backbone {} should be used along with fpn enabled, 'with_fpn' is forcibly set to True".
  773. format(backbone))
  774. with_fpn = True
  775. backbone = self._get_backbone(
  776. 'ResNet',
  777. depth=34,
  778. variant='d' if 'vd' in backbone else 'b',
  779. norm_type='bn',
  780. freeze_at=0,
  781. return_idx=[0, 1, 2, 3],
  782. num_stages=4,
  783. dcn_v2_stages=dcn_v2_stages)
  784. else:
  785. if not with_fpn:
  786. logging.warning(
  787. "Backbone {} should be used along with fpn enabled, 'with_fpn' is forcibly set to True".
  788. format(backbone))
  789. with_fpn = True
  790. backbone = self._get_backbone(
  791. 'ResNet',
  792. depth=101,
  793. variant='d' if 'vd' in backbone else 'b',
  794. norm_type='bn',
  795. freeze_at=0,
  796. return_idx=[0, 1, 2, 3],
  797. num_stages=4,
  798. dcn_v2_stages=dcn_v2_stages)
  799. rpn_in_channel = backbone.out_shape[0].channels
  800. if with_fpn:
  801. self.backbone_name = self.backbone_name + '_fpn'
  802. if 'HRNet' in self.backbone_name:
  803. neck = ppdet.modeling.HRFPN(
  804. in_channels=[i.channels for i in backbone.out_shape],
  805. out_channel=fpn_num_channels,
  806. spatial_scales=[
  807. 1.0 / i.stride for i in backbone.out_shape
  808. ],
  809. share_conv=False)
  810. else:
  811. neck = ppdet.modeling.FPN(
  812. in_channels=[i.channels for i in backbone.out_shape],
  813. out_channel=fpn_num_channels,
  814. spatial_scales=[
  815. 1.0 / i.stride for i in backbone.out_shape
  816. ])
  817. rpn_in_channel = neck.out_shape[0].channels
  818. anchor_generator_cfg = {
  819. 'aspect_ratios': aspect_ratios,
  820. 'anchor_sizes': anchor_sizes,
  821. 'strides': [4, 8, 16, 32, 64]
  822. }
  823. train_proposal_cfg = {
  824. 'min_size': 0.0,
  825. 'nms_thresh': .7,
  826. 'pre_nms_top_n': 2000,
  827. 'post_nms_top_n': 1000,
  828. 'topk_after_collect': True
  829. }
  830. test_proposal_cfg = {
  831. 'min_size': 0.0,
  832. 'nms_thresh': .7,
  833. 'pre_nms_top_n': 1000
  834. if test_pre_nms_top_n is None else test_pre_nms_top_n,
  835. 'post_nms_top_n': test_post_nms_top_n
  836. }
  837. head = ppdet.modeling.TwoFCHead(
  838. in_channel=neck.out_shape[0].channels, out_channel=1024)
  839. roi_extractor_cfg = {
  840. 'resolution': 7,
  841. 'spatial_scale': [1. / i.stride for i in neck.out_shape],
  842. 'sampling_ratio': 0,
  843. 'aligned': True
  844. }
  845. with_pool = False
  846. else:
  847. neck = None
  848. anchor_generator_cfg = {
  849. 'aspect_ratios': aspect_ratios,
  850. 'anchor_sizes': anchor_sizes,
  851. 'strides': [16]
  852. }
  853. train_proposal_cfg = {
  854. 'min_size': 0.0,
  855. 'nms_thresh': .7,
  856. 'pre_nms_top_n': 12000,
  857. 'post_nms_top_n': 2000,
  858. 'topk_after_collect': False
  859. }
  860. test_proposal_cfg = {
  861. 'min_size': 0.0,
  862. 'nms_thresh': .7,
  863. 'pre_nms_top_n': 6000
  864. if test_pre_nms_top_n is None else test_pre_nms_top_n,
  865. 'post_nms_top_n': test_post_nms_top_n
  866. }
  867. head = ppdet.modeling.Res5Head()
  868. roi_extractor_cfg = {
  869. 'resolution': 14,
  870. 'spatial_scale':
  871. [1. / i.stride for i in backbone.out_shape],
  872. 'sampling_ratio': 0,
  873. 'aligned': True
  874. }
  875. with_pool = True
  876. rpn_target_assign_cfg = {
  877. 'batch_size_per_im': rpn_batch_size_per_im,
  878. 'fg_fraction': rpn_fg_fraction,
  879. 'negative_overlap': .3,
  880. 'positive_overlap': .7,
  881. 'use_random': True
  882. }
  883. rpn_head = ppdet.modeling.RPNHead(
  884. anchor_generator=anchor_generator_cfg,
  885. rpn_target_assign=rpn_target_assign_cfg,
  886. train_proposal=train_proposal_cfg,
  887. test_proposal=test_proposal_cfg,
  888. in_channel=rpn_in_channel)
  889. bbox_assigner = BBoxAssigner(num_classes=num_classes)
  890. bbox_head = ppdet.modeling.BBoxHead(
  891. head=head,
  892. in_channel=head.out_shape[0].channels,
  893. roi_extractor=roi_extractor_cfg,
  894. with_pool=with_pool,
  895. bbox_assigner=bbox_assigner,
  896. num_classes=num_classes)
  897. bbox_post_process = ppdet.modeling.BBoxPostProcess(
  898. num_classes=num_classes,
  899. decode=ppdet.modeling.RCNNBox(num_classes=num_classes),
  900. nms=ppdet.modeling.MultiClassNMS(
  901. score_threshold=score_threshold,
  902. keep_top_k=keep_top_k,
  903. nms_threshold=nms_threshold))
  904. params.update({
  905. 'backbone': backbone,
  906. 'neck': neck,
  907. 'rpn_head': rpn_head,
  908. 'bbox_head': bbox_head,
  909. 'bbox_post_process': bbox_post_process
  910. })
  911. else:
  912. if backbone not in ['ResNet50', 'ResNet50_vd']:
  913. with_fpn = True
  914. self.with_fpn = with_fpn
  915. super(FasterRCNN, self).__init__(
  916. model_name='FasterRCNN', num_classes=num_classes, **params)
  917. def _compose_batch_transform(self, transforms, mode='train'):
  918. if mode == 'train':
  919. default_batch_transforms = [
  920. _BatchPadding(pad_to_stride=32 if self.with_fpn else -1)
  921. ]
  922. collate_batch = False
  923. else:
  924. default_batch_transforms = [
  925. _BatchPadding(pad_to_stride=32 if self.with_fpn else -1)
  926. ]
  927. collate_batch = True
  928. custom_batch_transforms = []
  929. for i, op in enumerate(transforms.transforms):
  930. if isinstance(op, (BatchRandomResize, BatchRandomResizeByShort)):
  931. if mode != 'train':
  932. raise Exception(
  933. "{} cannot be present in the {} transforms. ".format(
  934. op.__class__.__name__, mode) +
  935. "Please check the {} transforms.".format(mode))
  936. custom_batch_transforms.insert(0, copy.deepcopy(op))
  937. batch_transforms = BatchCompose(
  938. custom_batch_transforms + default_batch_transforms,
  939. collate_batch=collate_batch)
  940. return batch_transforms
  941. def _fix_transforms_shape(self, image_shape):
  942. if hasattr(self, 'test_transforms'):
  943. if self.test_transforms is not None:
  944. has_resize_op = False
  945. resize_op_idx = -1
  946. normalize_op_idx = len(self.test_transforms.transforms)
  947. for idx, op in enumerate(self.test_transforms.transforms):
  948. name = op.__class__.__name__
  949. if name == 'ResizeByShort':
  950. has_resize_op = True
  951. resize_op_idx = idx
  952. if name == 'Normalize':
  953. normalize_op_idx = idx
  954. if not has_resize_op:
  955. self.test_transforms.transforms.insert(
  956. normalize_op_idx,
  957. Resize(
  958. target_size=image_shape,
  959. keep_ratio=True,
  960. interp='CUBIC'))
  961. else:
  962. self.test_transforms.transforms[resize_op_idx] = Resize(
  963. target_size=image_shape,
  964. keep_ratio=True,
  965. interp='CUBIC')
  966. self.test_transforms.transforms.append(
  967. Padding(im_padding_value=[0., 0., 0.]))
  968. def _get_test_inputs(self, image_shape):
  969. if image_shape is not None:
  970. image_shape = self._check_image_shape(image_shape)
  971. self._fix_transforms_shape(image_shape[-2:])
  972. else:
  973. image_shape = [None, 3, -1, -1]
  974. if self.with_fpn:
  975. self.test_transforms.transforms.append(
  976. Padding(im_padding_value=[0., 0., 0.]))
  977. self.fixed_input_shape = image_shape
  978. return self._define_input_spec(image_shape)
  979. class PPYOLO(YOLOv3):
  980. def __init__(self,
  981. num_classes=80,
  982. backbone='ResNet50_vd_dcn',
  983. anchors=None,
  984. anchor_masks=None,
  985. use_coord_conv=True,
  986. use_iou_aware=True,
  987. use_spp=True,
  988. use_drop_block=True,
  989. scale_x_y=1.05,
  990. ignore_threshold=0.7,
  991. label_smooth=False,
  992. use_iou_loss=True,
  993. use_matrix_nms=True,
  994. nms_score_threshold=0.01,
  995. nms_topk=-1,
  996. nms_keep_topk=100,
  997. nms_iou_threshold=0.45,
  998. **params):
  999. self.init_params = locals()
  1000. if backbone not in [
  1001. 'ResNet50_vd_dcn', 'ResNet18_vd', 'MobileNetV3_large',
  1002. 'MobileNetV3_small'
  1003. ]:
  1004. raise ValueError(
  1005. "backbone: {} is not supported. Please choose one of "
  1006. "('ResNet50_vd_dcn', 'ResNet18_vd', 'MobileNetV3_large', 'MobileNetV3_small')".
  1007. format(backbone))
  1008. self.backbone_name = backbone
  1009. if params.get('with_net', True):
  1010. if paddlex.env_info['place'] == 'gpu' and paddlex.env_info[
  1011. 'num'] > 1 and not os.environ.get('PADDLEX_EXPORT_STAGE'):
  1012. norm_type = 'sync_bn'
  1013. else:
  1014. norm_type = 'bn'
  1015. if anchors is None and anchor_masks is None:
  1016. if 'MobileNetV3' in backbone:
  1017. anchors = [[11, 18], [34, 47], [51, 126], [115, 71],
  1018. [120, 195], [254, 235]]
  1019. anchor_masks = [[3, 4, 5], [0, 1, 2]]
  1020. elif backbone == 'ResNet50_vd_dcn':
  1021. anchors = [[10, 13], [16, 30], [33, 23], [30, 61],
  1022. [62, 45], [59, 119], [116, 90], [156, 198],
  1023. [373, 326]]
  1024. anchor_masks = [[6, 7, 8], [3, 4, 5], [0, 1, 2]]
  1025. else:
  1026. anchors = [[10, 14], [23, 27], [37, 58], [81, 82],
  1027. [135, 169], [344, 319]]
  1028. anchor_masks = [[3, 4, 5], [0, 1, 2]]
  1029. elif anchors is None or anchor_masks is None:
  1030. raise ValueError(
  1031. "Please define both anchors and anchor_masks.")
  1032. if backbone == 'ResNet50_vd_dcn':
  1033. backbone = self._get_backbone(
  1034. 'ResNet',
  1035. variant='d',
  1036. norm_type=norm_type,
  1037. return_idx=[1, 2, 3],
  1038. dcn_v2_stages=[3],
  1039. freeze_at=-1,
  1040. freeze_norm=False,
  1041. norm_decay=0.)
  1042. downsample_ratios = [32, 16, 8]
  1043. elif backbone == 'ResNet18_vd':
  1044. backbone = self._get_backbone(
  1045. 'ResNet',
  1046. depth=18,
  1047. variant='d',
  1048. norm_type=norm_type,
  1049. return_idx=[2, 3],
  1050. freeze_at=-1,
  1051. freeze_norm=False,
  1052. norm_decay=0.)
  1053. downsample_ratios = [32, 16]
  1054. elif backbone == 'MobileNetV3_large':
  1055. backbone = self._get_backbone(
  1056. 'MobileNetV3',
  1057. model_name='large',
  1058. norm_type=norm_type,
  1059. scale=1,
  1060. with_extra_blocks=False,
  1061. extra_block_filters=[],
  1062. feature_maps=[13, 16])
  1063. downsample_ratios = [32, 16]
  1064. elif backbone == 'MobileNetV3_small':
  1065. backbone = self._get_backbone(
  1066. 'MobileNetV3',
  1067. model_name='small',
  1068. norm_type=norm_type,
  1069. scale=1,
  1070. with_extra_blocks=False,
  1071. extra_block_filters=[],
  1072. feature_maps=[9, 12])
  1073. downsample_ratios = [32, 16]
  1074. neck = ppdet.modeling.PPYOLOFPN(
  1075. norm_type=norm_type,
  1076. in_channels=[i.channels for i in backbone.out_shape],
  1077. coord_conv=use_coord_conv,
  1078. drop_block=use_drop_block,
  1079. spp=use_spp,
  1080. conv_block_num=0
  1081. if ('MobileNetV3' in self.backbone_name or
  1082. self.backbone_name == 'ResNet18_vd') else 2)
  1083. loss = ppdet.modeling.YOLOv3Loss(
  1084. num_classes=num_classes,
  1085. ignore_thresh=ignore_threshold,
  1086. downsample=downsample_ratios,
  1087. label_smooth=label_smooth,
  1088. scale_x_y=scale_x_y,
  1089. iou_loss=ppdet.modeling.IouLoss(
  1090. loss_weight=2.5, loss_square=True)
  1091. if use_iou_loss else None,
  1092. iou_aware_loss=ppdet.modeling.IouAwareLoss(loss_weight=1.0)
  1093. if use_iou_aware else None)
  1094. yolo_head = ppdet.modeling.YOLOv3Head(
  1095. in_channels=[i.channels for i in neck.out_shape],
  1096. anchors=anchors,
  1097. anchor_masks=anchor_masks,
  1098. num_classes=num_classes,
  1099. loss=loss,
  1100. iou_aware=use_iou_aware)
  1101. if use_matrix_nms:
  1102. nms = ppdet.modeling.MatrixNMS(
  1103. keep_top_k=nms_keep_topk,
  1104. score_threshold=nms_score_threshold,
  1105. post_threshold=.05
  1106. if 'MobileNetV3' in self.backbone_name else .01,
  1107. nms_top_k=nms_topk,
  1108. background_label=-1)
  1109. else:
  1110. nms = ppdet.modeling.MultiClassNMS(
  1111. score_threshold=nms_score_threshold,
  1112. nms_top_k=nms_topk,
  1113. keep_top_k=nms_keep_topk,
  1114. nms_threshold=nms_iou_threshold)
  1115. post_process = ppdet.modeling.BBoxPostProcess(
  1116. decode=ppdet.modeling.YOLOBox(
  1117. num_classes=num_classes,
  1118. conf_thresh=.005
  1119. if 'MobileNetV3' in self.backbone_name else .01,
  1120. scale_x_y=scale_x_y),
  1121. nms=nms)
  1122. params.update({
  1123. 'backbone': backbone,
  1124. 'neck': neck,
  1125. 'yolo_head': yolo_head,
  1126. 'post_process': post_process
  1127. })
  1128. super(YOLOv3, self).__init__(
  1129. model_name='YOLOv3', num_classes=num_classes, **params)
  1130. self.anchors = anchors
  1131. self.anchor_masks = anchor_masks
  1132. self.downsample_ratios = downsample_ratios
  1133. self.model_name = 'PPYOLO'
  1134. class PPYOLOTiny(YOLOv3):
  1135. def __init__(self,
  1136. num_classes=80,
  1137. backbone='MobileNetV3',
  1138. anchors=[[10, 15], [24, 36], [72, 42], [35, 87], [102, 96],
  1139. [60, 170], [220, 125], [128, 222], [264, 266]],
  1140. anchor_masks=[[6, 7, 8], [3, 4, 5], [0, 1, 2]],
  1141. use_iou_aware=False,
  1142. use_spp=True,
  1143. use_drop_block=True,
  1144. scale_x_y=1.05,
  1145. ignore_threshold=0.5,
  1146. label_smooth=False,
  1147. use_iou_loss=True,
  1148. use_matrix_nms=False,
  1149. nms_score_threshold=0.005,
  1150. nms_topk=1000,
  1151. nms_keep_topk=100,
  1152. nms_iou_threshold=0.45,
  1153. **params):
  1154. self.init_params = locals()
  1155. if backbone != 'MobileNetV3':
  1156. logging.warning(
  1157. "PPYOLOTiny only supports MobileNetV3 as backbone. "
  1158. "Backbone is forcibly set to MobileNetV3.")
  1159. self.backbone_name = 'MobileNetV3'
  1160. if params.get('with_net', True):
  1161. if paddlex.env_info['place'] == 'gpu' and paddlex.env_info[
  1162. 'num'] > 1 and not os.environ.get('PADDLEX_EXPORT_STAGE'):
  1163. norm_type = 'sync_bn'
  1164. else:
  1165. norm_type = 'bn'
  1166. backbone = self._get_backbone(
  1167. 'MobileNetV3',
  1168. model_name='large',
  1169. norm_type=norm_type,
  1170. scale=.5,
  1171. with_extra_blocks=False,
  1172. extra_block_filters=[],
  1173. feature_maps=[7, 13, 16])
  1174. downsample_ratios = [32, 16, 8]
  1175. neck = ppdet.modeling.PPYOLOTinyFPN(
  1176. detection_block_channels=[160, 128, 96],
  1177. in_channels=[i.channels for i in backbone.out_shape],
  1178. spp=use_spp,
  1179. drop_block=use_drop_block)
  1180. loss = ppdet.modeling.YOLOv3Loss(
  1181. num_classes=num_classes,
  1182. ignore_thresh=ignore_threshold,
  1183. downsample=downsample_ratios,
  1184. label_smooth=label_smooth,
  1185. scale_x_y=scale_x_y,
  1186. iou_loss=ppdet.modeling.IouLoss(
  1187. loss_weight=2.5, loss_square=True)
  1188. if use_iou_loss else None,
  1189. iou_aware_loss=ppdet.modeling.IouAwareLoss(loss_weight=1.0)
  1190. if use_iou_aware else None)
  1191. yolo_head = ppdet.modeling.YOLOv3Head(
  1192. in_channels=[i.channels for i in neck.out_shape],
  1193. anchors=anchors,
  1194. anchor_masks=anchor_masks,
  1195. num_classes=num_classes,
  1196. loss=loss,
  1197. iou_aware=use_iou_aware)
  1198. if use_matrix_nms:
  1199. nms = ppdet.modeling.MatrixNMS(
  1200. keep_top_k=nms_keep_topk,
  1201. score_threshold=nms_score_threshold,
  1202. post_threshold=.05,
  1203. nms_top_k=nms_topk,
  1204. background_label=-1)
  1205. else:
  1206. nms = ppdet.modeling.MultiClassNMS(
  1207. score_threshold=nms_score_threshold,
  1208. nms_top_k=nms_topk,
  1209. keep_top_k=nms_keep_topk,
  1210. nms_threshold=nms_iou_threshold)
  1211. post_process = ppdet.modeling.BBoxPostProcess(
  1212. decode=ppdet.modeling.YOLOBox(
  1213. num_classes=num_classes,
  1214. conf_thresh=.005,
  1215. downsample_ratio=32,
  1216. clip_bbox=True,
  1217. scale_x_y=scale_x_y),
  1218. nms=nms)
  1219. params.update({
  1220. 'backbone': backbone,
  1221. 'neck': neck,
  1222. 'yolo_head': yolo_head,
  1223. 'post_process': post_process
  1224. })
  1225. super(YOLOv3, self).__init__(
  1226. model_name='YOLOv3', num_classes=num_classes, **params)
  1227. self.anchors = anchors
  1228. self.anchor_masks = anchor_masks
  1229. self.downsample_ratios = downsample_ratios
  1230. self.model_name = 'PPYOLOTiny'
  1231. class PPYOLOv2(YOLOv3):
  1232. def __init__(self,
  1233. num_classes=80,
  1234. backbone='ResNet50_vd_dcn',
  1235. anchors=[[10, 13], [16, 30], [33, 23], [30, 61], [62, 45],
  1236. [59, 119], [116, 90], [156, 198], [373, 326]],
  1237. anchor_masks=[[6, 7, 8], [3, 4, 5], [0, 1, 2]],
  1238. use_iou_aware=True,
  1239. use_spp=True,
  1240. use_drop_block=True,
  1241. scale_x_y=1.05,
  1242. ignore_threshold=0.7,
  1243. label_smooth=False,
  1244. use_iou_loss=True,
  1245. use_matrix_nms=True,
  1246. nms_score_threshold=0.01,
  1247. nms_topk=-1,
  1248. nms_keep_topk=100,
  1249. nms_iou_threshold=0.45,
  1250. **params):
  1251. self.init_params = locals()
  1252. if backbone not in ['ResNet50_vd_dcn', 'ResNet101_vd_dcn']:
  1253. raise ValueError(
  1254. "backbone: {} is not supported. Please choose one of "
  1255. "('ResNet50_vd_dcn', 'ResNet101_vd_dcn')".format(backbone))
  1256. self.backbone_name = backbone
  1257. if params.get('with_net', True):
  1258. if paddlex.env_info['place'] == 'gpu' and paddlex.env_info[
  1259. 'num'] > 1 and not os.environ.get('PADDLEX_EXPORT_STAGE'):
  1260. norm_type = 'sync_bn'
  1261. else:
  1262. norm_type = 'bn'
  1263. if backbone == 'ResNet50_vd_dcn':
  1264. backbone = self._get_backbone(
  1265. 'ResNet',
  1266. variant='d',
  1267. norm_type=norm_type,
  1268. return_idx=[1, 2, 3],
  1269. dcn_v2_stages=[3],
  1270. freeze_at=-1,
  1271. freeze_norm=False,
  1272. norm_decay=0.)
  1273. downsample_ratios = [32, 16, 8]
  1274. elif backbone == 'ResNet101_vd_dcn':
  1275. backbone = self._get_backbone(
  1276. 'ResNet',
  1277. depth=101,
  1278. variant='d',
  1279. norm_type=norm_type,
  1280. return_idx=[1, 2, 3],
  1281. dcn_v2_stages=[3],
  1282. freeze_at=-1,
  1283. freeze_norm=False,
  1284. norm_decay=0.)
  1285. downsample_ratios = [32, 16, 8]
  1286. neck = ppdet.modeling.PPYOLOPAN(
  1287. norm_type=norm_type,
  1288. in_channels=[i.channels for i in backbone.out_shape],
  1289. drop_block=use_drop_block,
  1290. block_size=3,
  1291. keep_prob=.9,
  1292. spp=use_spp)
  1293. loss = ppdet.modeling.YOLOv3Loss(
  1294. num_classes=num_classes,
  1295. ignore_thresh=ignore_threshold,
  1296. downsample=downsample_ratios,
  1297. label_smooth=label_smooth,
  1298. scale_x_y=scale_x_y,
  1299. iou_loss=ppdet.modeling.IouLoss(
  1300. loss_weight=2.5, loss_square=True)
  1301. if use_iou_loss else None,
  1302. iou_aware_loss=ppdet.modeling.IouAwareLoss(loss_weight=1.0)
  1303. if use_iou_aware else None)
  1304. yolo_head = ppdet.modeling.YOLOv3Head(
  1305. in_channels=[i.channels for i in neck.out_shape],
  1306. anchors=anchors,
  1307. anchor_masks=anchor_masks,
  1308. num_classes=num_classes,
  1309. loss=loss,
  1310. iou_aware=use_iou_aware,
  1311. iou_aware_factor=.5)
  1312. if use_matrix_nms:
  1313. nms = ppdet.modeling.MatrixNMS(
  1314. keep_top_k=nms_keep_topk,
  1315. score_threshold=nms_score_threshold,
  1316. post_threshold=.01,
  1317. nms_top_k=nms_topk,
  1318. background_label=-1)
  1319. else:
  1320. nms = ppdet.modeling.MultiClassNMS(
  1321. score_threshold=nms_score_threshold,
  1322. nms_top_k=nms_topk,
  1323. keep_top_k=nms_keep_topk,
  1324. nms_threshold=nms_iou_threshold)
  1325. post_process = ppdet.modeling.BBoxPostProcess(
  1326. decode=ppdet.modeling.YOLOBox(
  1327. num_classes=num_classes,
  1328. conf_thresh=.01,
  1329. downsample_ratio=32,
  1330. clip_bbox=True,
  1331. scale_x_y=scale_x_y),
  1332. nms=nms)
  1333. params.update({
  1334. 'backbone': backbone,
  1335. 'neck': neck,
  1336. 'yolo_head': yolo_head,
  1337. 'post_process': post_process
  1338. })
  1339. super(YOLOv3, self).__init__(
  1340. model_name='YOLOv3', num_classes=num_classes, **params)
  1341. self.anchors = anchors
  1342. self.anchor_masks = anchor_masks
  1343. self.downsample_ratios = downsample_ratios
  1344. self.model_name = 'PPYOLOv2'
  1345. def _get_test_inputs(self, image_shape):
  1346. if image_shape is not None:
  1347. image_shape = self._check_image_shape(image_shape)
  1348. self._fix_transforms_shape(image_shape[-2:])
  1349. else:
  1350. image_shape = [None, 3, 608, 608]
  1351. logging.warning(
  1352. '[Important!!!] When exporting inference model for {},'.format(
  1353. self.__class__.__name__) +
  1354. ' if fixed_input_shape is not set, it will be forcibly set to [None, 3, 608, 608]. '
  1355. +
  1356. 'Please check image shape after transforms is [3, 608, 608], if not, fixed_input_shape '
  1357. + 'should be specified manually.')
  1358. self.fixed_input_shape = image_shape
  1359. return self._define_input_spec(image_shape)
  1360. class MaskRCNN(BaseDetector):
  1361. def __init__(self,
  1362. num_classes=80,
  1363. backbone='ResNet50_vd',
  1364. with_fpn=True,
  1365. with_dcn=False,
  1366. aspect_ratios=[0.5, 1.0, 2.0],
  1367. anchor_sizes=[[32], [64], [128], [256], [512]],
  1368. keep_top_k=100,
  1369. nms_threshold=0.5,
  1370. score_threshold=0.05,
  1371. fpn_num_channels=256,
  1372. rpn_batch_size_per_im=256,
  1373. rpn_fg_fraction=0.5,
  1374. test_pre_nms_top_n=None,
  1375. test_post_nms_top_n=1000,
  1376. **params):
  1377. self.init_params = locals()
  1378. if backbone not in [
  1379. 'ResNet50', 'ResNet50_vd', 'ResNet50_vd_ssld', 'ResNet101',
  1380. 'ResNet101_vd'
  1381. ]:
  1382. raise ValueError(
  1383. "backbone: {} is not supported. Please choose one of "
  1384. "('ResNet50', 'ResNet50_vd', 'ResNet50_vd_ssld', 'ResNet101', 'ResNet101_vd')".
  1385. format(backbone))
  1386. self.backbone_name = backbone + '_fpn' if with_fpn else backbone
  1387. dcn_v2_stages = [1, 2, 3] if with_dcn else [-1]
  1388. if params.get('with_net', True):
  1389. if backbone == 'ResNet50':
  1390. if with_fpn:
  1391. backbone = self._get_backbone(
  1392. 'ResNet',
  1393. norm_type='bn',
  1394. freeze_at=0,
  1395. return_idx=[0, 1, 2, 3],
  1396. num_stages=4,
  1397. dcn_v2_stages=dcn_v2_stages)
  1398. else:
  1399. if with_dcn:
  1400. logging.warning(
  1401. "Backbone {} should be used along with dcn disabled, 'with_dcn' is forcibly set to False".
  1402. format(backbone))
  1403. backbone = self._get_backbone(
  1404. 'ResNet',
  1405. norm_type='bn',
  1406. freeze_at=0,
  1407. return_idx=[2],
  1408. num_stages=3)
  1409. elif 'ResNet50_vd' in backbone:
  1410. if not with_fpn:
  1411. logging.warning(
  1412. "Backbone {} should be used along with fpn enabled, 'with_fpn' is forcibly set to True".
  1413. format(backbone))
  1414. with_fpn = True
  1415. backbone = self._get_backbone(
  1416. 'ResNet',
  1417. variant='d',
  1418. norm_type='bn',
  1419. freeze_at=0,
  1420. return_idx=[0, 1, 2, 3],
  1421. num_stages=4,
  1422. lr_mult_list=[0.05, 0.05, 0.1, 0.15]
  1423. if '_ssld' in backbone else [1.0, 1.0, 1.0, 1.0],
  1424. dcn_v2_stages=dcn_v2_stages)
  1425. else:
  1426. if not with_fpn:
  1427. logging.warning(
  1428. "Backbone {} should be used along with fpn enabled, 'with_fpn' is forcibly set to True".
  1429. format(backbone))
  1430. with_fpn = True
  1431. backbone = self._get_backbone(
  1432. 'ResNet',
  1433. variant='d' if '_vd' in backbone else 'b',
  1434. depth=101,
  1435. norm_type='bn',
  1436. freeze_at=0,
  1437. return_idx=[0, 1, 2, 3],
  1438. num_stages=4,
  1439. dcn_v2_stages=dcn_v2_stages)
  1440. rpn_in_channel = backbone.out_shape[0].channels
  1441. if with_fpn:
  1442. neck = ppdet.modeling.FPN(
  1443. in_channels=[i.channels for i in backbone.out_shape],
  1444. out_channel=fpn_num_channels,
  1445. spatial_scales=[
  1446. 1.0 / i.stride for i in backbone.out_shape
  1447. ])
  1448. rpn_in_channel = neck.out_shape[0].channels
  1449. anchor_generator_cfg = {
  1450. 'aspect_ratios': aspect_ratios,
  1451. 'anchor_sizes': anchor_sizes,
  1452. 'strides': [4, 8, 16, 32, 64]
  1453. }
  1454. train_proposal_cfg = {
  1455. 'min_size': 0.0,
  1456. 'nms_thresh': .7,
  1457. 'pre_nms_top_n': 2000,
  1458. 'post_nms_top_n': 1000,
  1459. 'topk_after_collect': True
  1460. }
  1461. test_proposal_cfg = {
  1462. 'min_size': 0.0,
  1463. 'nms_thresh': .7,
  1464. 'pre_nms_top_n': 1000
  1465. if test_pre_nms_top_n is None else test_pre_nms_top_n,
  1466. 'post_nms_top_n': test_post_nms_top_n
  1467. }
  1468. bb_head = ppdet.modeling.TwoFCHead(
  1469. in_channel=neck.out_shape[0].channels, out_channel=1024)
  1470. bb_roi_extractor_cfg = {
  1471. 'resolution': 7,
  1472. 'spatial_scale': [1. / i.stride for i in neck.out_shape],
  1473. 'sampling_ratio': 0,
  1474. 'aligned': True
  1475. }
  1476. with_pool = False
  1477. m_head = ppdet.modeling.MaskFeat(
  1478. in_channel=neck.out_shape[0].channels,
  1479. out_channel=256,
  1480. num_convs=4)
  1481. m_roi_extractor_cfg = {
  1482. 'resolution': 14,
  1483. 'spatial_scale': [1. / i.stride for i in neck.out_shape],
  1484. 'sampling_ratio': 0,
  1485. 'aligned': True
  1486. }
  1487. mask_assigner = MaskAssigner(
  1488. num_classes=num_classes, mask_resolution=28)
  1489. share_bbox_feat = False
  1490. else:
  1491. neck = None
  1492. anchor_generator_cfg = {
  1493. 'aspect_ratios': aspect_ratios,
  1494. 'anchor_sizes': anchor_sizes,
  1495. 'strides': [16]
  1496. }
  1497. train_proposal_cfg = {
  1498. 'min_size': 0.0,
  1499. 'nms_thresh': .7,
  1500. 'pre_nms_top_n': 12000,
  1501. 'post_nms_top_n': 2000,
  1502. 'topk_after_collect': False
  1503. }
  1504. test_proposal_cfg = {
  1505. 'min_size': 0.0,
  1506. 'nms_thresh': .7,
  1507. 'pre_nms_top_n': 6000
  1508. if test_pre_nms_top_n is None else test_pre_nms_top_n,
  1509. 'post_nms_top_n': test_post_nms_top_n
  1510. }
  1511. bb_head = ppdet.modeling.Res5Head()
  1512. bb_roi_extractor_cfg = {
  1513. 'resolution': 14,
  1514. 'spatial_scale':
  1515. [1. / i.stride for i in backbone.out_shape],
  1516. 'sampling_ratio': 0,
  1517. 'aligned': True
  1518. }
  1519. with_pool = True
  1520. m_head = ppdet.modeling.MaskFeat(
  1521. in_channel=bb_head.out_shape[0].channels,
  1522. out_channel=256,
  1523. num_convs=0)
  1524. m_roi_extractor_cfg = {
  1525. 'resolution': 14,
  1526. 'spatial_scale':
  1527. [1. / i.stride for i in backbone.out_shape],
  1528. 'sampling_ratio': 0,
  1529. 'aligned': True
  1530. }
  1531. mask_assigner = MaskAssigner(
  1532. num_classes=num_classes, mask_resolution=14)
  1533. share_bbox_feat = True
  1534. rpn_target_assign_cfg = {
  1535. 'batch_size_per_im': rpn_batch_size_per_im,
  1536. 'fg_fraction': rpn_fg_fraction,
  1537. 'negative_overlap': .3,
  1538. 'positive_overlap': .7,
  1539. 'use_random': True
  1540. }
  1541. rpn_head = ppdet.modeling.RPNHead(
  1542. anchor_generator=anchor_generator_cfg,
  1543. rpn_target_assign=rpn_target_assign_cfg,
  1544. train_proposal=train_proposal_cfg,
  1545. test_proposal=test_proposal_cfg,
  1546. in_channel=rpn_in_channel)
  1547. bbox_assigner = BBoxAssigner(num_classes=num_classes)
  1548. bbox_head = ppdet.modeling.BBoxHead(
  1549. head=bb_head,
  1550. in_channel=bb_head.out_shape[0].channels,
  1551. roi_extractor=bb_roi_extractor_cfg,
  1552. with_pool=with_pool,
  1553. bbox_assigner=bbox_assigner,
  1554. num_classes=num_classes)
  1555. mask_head = ppdet.modeling.MaskHead(
  1556. head=m_head,
  1557. roi_extractor=m_roi_extractor_cfg,
  1558. mask_assigner=mask_assigner,
  1559. share_bbox_feat=share_bbox_feat,
  1560. num_classes=num_classes)
  1561. bbox_post_process = ppdet.modeling.BBoxPostProcess(
  1562. num_classes=num_classes,
  1563. decode=ppdet.modeling.RCNNBox(num_classes=num_classes),
  1564. nms=ppdet.modeling.MultiClassNMS(
  1565. score_threshold=score_threshold,
  1566. keep_top_k=keep_top_k,
  1567. nms_threshold=nms_threshold))
  1568. mask_post_process = ppdet.modeling.MaskPostProcess(
  1569. binary_thresh=.5)
  1570. params.update({
  1571. 'backbone': backbone,
  1572. 'neck': neck,
  1573. 'rpn_head': rpn_head,
  1574. 'bbox_head': bbox_head,
  1575. 'mask_head': mask_head,
  1576. 'bbox_post_process': bbox_post_process,
  1577. 'mask_post_process': mask_post_process
  1578. })
  1579. self.with_fpn = with_fpn
  1580. super(MaskRCNN, self).__init__(
  1581. model_name='MaskRCNN', num_classes=num_classes, **params)
  1582. def _compose_batch_transform(self, transforms, mode='train'):
  1583. if mode == 'train':
  1584. default_batch_transforms = [
  1585. _BatchPadding(pad_to_stride=32 if self.with_fpn else -1)
  1586. ]
  1587. collate_batch = False
  1588. else:
  1589. default_batch_transforms = [
  1590. _BatchPadding(pad_to_stride=32 if self.with_fpn else -1)
  1591. ]
  1592. collate_batch = True
  1593. custom_batch_transforms = []
  1594. for i, op in enumerate(transforms.transforms):
  1595. if isinstance(op, (BatchRandomResize, BatchRandomResizeByShort)):
  1596. if mode != 'train':
  1597. raise Exception(
  1598. "{} cannot be present in the {} transforms. ".format(
  1599. op.__class__.__name__, mode) +
  1600. "Please check the {} transforms.".format(mode))
  1601. custom_batch_transforms.insert(0, copy.deepcopy(op))
  1602. batch_transforms = BatchCompose(
  1603. custom_batch_transforms + default_batch_transforms,
  1604. collate_batch=collate_batch)
  1605. return batch_transforms
  1606. def _fix_transforms_shape(self, image_shape):
  1607. if hasattr(self, 'test_transforms'):
  1608. if self.test_transforms is not None:
  1609. has_resize_op = False
  1610. resize_op_idx = -1
  1611. normalize_op_idx = len(self.test_transforms.transforms)
  1612. for idx, op in enumerate(self.test_transforms.transforms):
  1613. name = op.__class__.__name__
  1614. if name == 'ResizeByShort':
  1615. has_resize_op = True
  1616. resize_op_idx = idx
  1617. if name == 'Normalize':
  1618. normalize_op_idx = idx
  1619. if not has_resize_op:
  1620. self.test_transforms.transforms.insert(
  1621. normalize_op_idx,
  1622. Resize(
  1623. target_size=image_shape,
  1624. keep_ratio=True,
  1625. interp='CUBIC'))
  1626. else:
  1627. self.test_transforms.transforms[resize_op_idx] = Resize(
  1628. target_size=image_shape,
  1629. keep_ratio=True,
  1630. interp='CUBIC')
  1631. self.test_transforms.transforms.append(
  1632. Padding(im_padding_value=[0., 0., 0.]))
  1633. def _get_test_inputs(self, image_shape):
  1634. if image_shape is not None:
  1635. image_shape = self._check_image_shape(image_shape)
  1636. self._fix_transforms_shape(image_shape[-2:])
  1637. else:
  1638. image_shape = [None, 3, -1, -1]
  1639. if self.with_fpn:
  1640. self.test_transforms.transforms.append(
  1641. Padding(im_padding_value=[0., 0., 0.]))
  1642. self.fixed_input_shape = image_shape
  1643. return self._define_input_spec(image_shape)