detector.py 66 KB

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