detector.py 93 KB

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