detector.py 74 KB

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