detector.py 91 KB

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