detector.py 57 KB

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