detector.py 62 KB

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