detector.py 62 KB

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