detector.py 61 KB

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