detector.py 66 KB

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