detector.py 66 KB

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