repo
stringlengths
2
99
file
stringlengths
13
225
code
stringlengths
0
18.3M
file_length
int64
0
18.3M
avg_line_length
float64
0
1.36M
max_line_length
int64
0
4.26M
extension_type
stringclasses
1 value
PseCo
PseCo-master/thirdparty/mmdetection/tools/dataset_converters/cityscapes.py
# Copyright (c) OpenMMLab. All rights reserved. import argparse import glob import os.path as osp import cityscapesscripts.helpers.labels as CSLabels import mmcv import numpy as np import pycocotools.mask as maskUtils def collect_files(img_dir, gt_dir): suffix = 'leftImg8bit.png' files = [] for img_file in glob.glob(osp.join(img_dir, '**/*.png')): assert img_file.endswith(suffix), img_file inst_file = gt_dir + img_file[ len(img_dir):-len(suffix)] + 'gtFine_instanceIds.png' # Note that labelIds are not converted to trainId for seg map segm_file = gt_dir + img_file[ len(img_dir):-len(suffix)] + 'gtFine_labelIds.png' files.append((img_file, inst_file, segm_file)) assert len(files), f'No images found in {img_dir}' print(f'Loaded {len(files)} images from {img_dir}') return files def collect_annotations(files, nproc=1): print('Loading annotation images') if nproc > 1: images = mmcv.track_parallel_progress( load_img_info, files, nproc=nproc) else: images = mmcv.track_progress(load_img_info, files) return images def load_img_info(files): img_file, inst_file, segm_file = files inst_img = mmcv.imread(inst_file, 'unchanged') # ids < 24 are stuff labels (filtering them first is about 5% faster) unique_inst_ids = np.unique(inst_img[inst_img >= 24]) anno_info = [] for inst_id in unique_inst_ids: # For non-crowd annotations, inst_id // 1000 is the label_id # Crowd annotations have <1000 instance ids label_id = inst_id // 1000 if inst_id >= 1000 else inst_id label = CSLabels.id2label[label_id] if not label.hasInstances or label.ignoreInEval: continue category_id = label.id iscrowd = int(inst_id < 1000) mask = np.asarray(inst_img == inst_id, dtype=np.uint8, order='F') mask_rle = maskUtils.encode(mask[:, :, None])[0] area = maskUtils.area(mask_rle) # convert to COCO style XYWH format bbox = maskUtils.toBbox(mask_rle) # for json encoding mask_rle['counts'] = mask_rle['counts'].decode() anno = dict( iscrowd=iscrowd, category_id=category_id, bbox=bbox.tolist(), area=area.tolist(), segmentation=mask_rle) anno_info.append(anno) video_name = osp.basename(osp.dirname(img_file)) img_info = dict( # remove img_prefix for filename file_name=osp.join(video_name, osp.basename(img_file)), height=inst_img.shape[0], width=inst_img.shape[1], anno_info=anno_info, segm_file=osp.join(video_name, osp.basename(segm_file))) return img_info def cvt_annotations(image_infos, out_json_name): out_json = dict() img_id = 0 ann_id = 0 out_json['images'] = [] out_json['categories'] = [] out_json['annotations'] = [] for image_info in image_infos: image_info['id'] = img_id anno_infos = image_info.pop('anno_info') out_json['images'].append(image_info) for anno_info in anno_infos: anno_info['image_id'] = img_id anno_info['id'] = ann_id out_json['annotations'].append(anno_info) ann_id += 1 img_id += 1 for label in CSLabels.labels: if label.hasInstances and not label.ignoreInEval: cat = dict(id=label.id, name=label.name) out_json['categories'].append(cat) if len(out_json['annotations']) == 0: out_json.pop('annotations') mmcv.dump(out_json, out_json_name) return out_json def parse_args(): parser = argparse.ArgumentParser( description='Convert Cityscapes annotations to COCO format') parser.add_argument('cityscapes_path', help='cityscapes data path') parser.add_argument('--img-dir', default='leftImg8bit', type=str) parser.add_argument('--gt-dir', default='gtFine', type=str) parser.add_argument('-o', '--out-dir', help='output path') parser.add_argument( '--nproc', default=1, type=int, help='number of process') args = parser.parse_args() return args def main(): args = parse_args() cityscapes_path = args.cityscapes_path out_dir = args.out_dir if args.out_dir else cityscapes_path mmcv.mkdir_or_exist(out_dir) img_dir = osp.join(cityscapes_path, args.img_dir) gt_dir = osp.join(cityscapes_path, args.gt_dir) set_name = dict( train='instancesonly_filtered_gtFine_train.json', val='instancesonly_filtered_gtFine_val.json', test='instancesonly_filtered_gtFine_test.json') for split, json_name in set_name.items(): print(f'Converting {split} into {json_name}') with mmcv.Timer( print_tmpl='It took {}s to convert Cityscapes annotation'): files = collect_files( osp.join(img_dir, split), osp.join(gt_dir, split)) image_infos = collect_annotations(files, nproc=args.nproc) cvt_annotations(image_infos, osp.join(out_dir, json_name)) if __name__ == '__main__': main()
5,172
32.810458
75
py
PseCo
PseCo-master/thirdparty/mmdetection/tools/dataset_converters/pascal_voc.py
# Copyright (c) OpenMMLab. All rights reserved. import argparse import os.path as osp import xml.etree.ElementTree as ET import mmcv import numpy as np from mmdet.core import voc_classes label_ids = {name: i for i, name in enumerate(voc_classes())} def parse_xml(args): xml_path, img_path = args tree = ET.parse(xml_path) root = tree.getroot() size = root.find('size') w = int(size.find('width').text) h = int(size.find('height').text) bboxes = [] labels = [] bboxes_ignore = [] labels_ignore = [] for obj in root.findall('object'): name = obj.find('name').text label = label_ids[name] difficult = int(obj.find('difficult').text) bnd_box = obj.find('bndbox') bbox = [ int(bnd_box.find('xmin').text), int(bnd_box.find('ymin').text), int(bnd_box.find('xmax').text), int(bnd_box.find('ymax').text) ] if difficult: bboxes_ignore.append(bbox) labels_ignore.append(label) else: bboxes.append(bbox) labels.append(label) if not bboxes: bboxes = np.zeros((0, 4)) labels = np.zeros((0, )) else: bboxes = np.array(bboxes, ndmin=2) - 1 labels = np.array(labels) if not bboxes_ignore: bboxes_ignore = np.zeros((0, 4)) labels_ignore = np.zeros((0, )) else: bboxes_ignore = np.array(bboxes_ignore, ndmin=2) - 1 labels_ignore = np.array(labels_ignore) annotation = { 'filename': img_path, 'width': w, 'height': h, 'ann': { 'bboxes': bboxes.astype(np.float32), 'labels': labels.astype(np.int64), 'bboxes_ignore': bboxes_ignore.astype(np.float32), 'labels_ignore': labels_ignore.astype(np.int64) } } return annotation def cvt_annotations(devkit_path, years, split, out_file): if not isinstance(years, list): years = [years] annotations = [] for year in years: filelist = osp.join(devkit_path, f'VOC{year}/ImageSets/Main/{split}.txt') if not osp.isfile(filelist): print(f'filelist does not exist: {filelist}, ' f'skip voc{year} {split}') return img_names = mmcv.list_from_file(filelist) xml_paths = [ osp.join(devkit_path, f'VOC{year}/Annotations/{img_name}.xml') for img_name in img_names ] img_paths = [ f'VOC{year}/JPEGImages/{img_name}.jpg' for img_name in img_names ] part_annotations = mmcv.track_progress(parse_xml, list(zip(xml_paths, img_paths))) annotations.extend(part_annotations) if out_file.endswith('json'): annotations = cvt_to_coco_json(annotations) mmcv.dump(annotations, out_file) return annotations def cvt_to_coco_json(annotations): image_id = 0 annotation_id = 0 coco = dict() coco['images'] = [] coco['type'] = 'instance' coco['categories'] = [] coco['annotations'] = [] image_set = set() def addAnnItem(annotation_id, image_id, category_id, bbox, difficult_flag): annotation_item = dict() annotation_item['segmentation'] = [] seg = [] # bbox[] is x1,y1,x2,y2 # left_top seg.append(int(bbox[0])) seg.append(int(bbox[1])) # left_bottom seg.append(int(bbox[0])) seg.append(int(bbox[3])) # right_bottom seg.append(int(bbox[2])) seg.append(int(bbox[3])) # right_top seg.append(int(bbox[2])) seg.append(int(bbox[1])) annotation_item['segmentation'].append(seg) xywh = np.array( [bbox[0], bbox[1], bbox[2] - bbox[0], bbox[3] - bbox[1]]) annotation_item['area'] = int(xywh[2] * xywh[3]) if difficult_flag == 1: annotation_item['ignore'] = 0 annotation_item['iscrowd'] = 1 else: annotation_item['ignore'] = 0 annotation_item['iscrowd'] = 0 annotation_item['image_id'] = int(image_id) annotation_item['bbox'] = xywh.astype(int).tolist() annotation_item['category_id'] = int(category_id) annotation_item['id'] = int(annotation_id) coco['annotations'].append(annotation_item) return annotation_id + 1 for category_id, name in enumerate(voc_classes()): category_item = dict() category_item['supercategory'] = str('none') category_item['id'] = int(category_id) category_item['name'] = str(name) coco['categories'].append(category_item) for ann_dict in annotations: file_name = ann_dict['filename'] ann = ann_dict['ann'] assert file_name not in image_set image_item = dict() image_item['id'] = int(image_id) image_item['file_name'] = str(file_name) image_item['height'] = int(ann_dict['height']) image_item['width'] = int(ann_dict['width']) coco['images'].append(image_item) image_set.add(file_name) bboxes = ann['bboxes'][:, :4] labels = ann['labels'] for bbox_id in range(len(bboxes)): bbox = bboxes[bbox_id] label = labels[bbox_id] annotation_id = addAnnItem( annotation_id, image_id, label, bbox, difficult_flag=0) bboxes_ignore = ann['bboxes_ignore'][:, :4] labels_ignore = ann['labels_ignore'] for bbox_id in range(len(bboxes_ignore)): bbox = bboxes_ignore[bbox_id] label = labels_ignore[bbox_id] annotation_id = addAnnItem( annotation_id, image_id, label, bbox, difficult_flag=1) image_id += 1 return coco def parse_args(): parser = argparse.ArgumentParser( description='Convert PASCAL VOC annotations to mmdetection format') parser.add_argument('devkit_path', help='pascal voc devkit path') parser.add_argument('-o', '--out-dir', help='output path') parser.add_argument( '--out-format', default='pkl', choices=('pkl', 'coco'), help='output format, "coco" indicates coco annotation format') args = parser.parse_args() return args def main(): args = parse_args() devkit_path = args.devkit_path out_dir = args.out_dir if args.out_dir else devkit_path mmcv.mkdir_or_exist(out_dir) years = [] if osp.isdir(osp.join(devkit_path, 'VOC2007')): years.append('2007') if osp.isdir(osp.join(devkit_path, 'VOC2012')): years.append('2012') if '2007' in years and '2012' in years: years.append(['2007', '2012']) if not years: raise IOError(f'The devkit path {devkit_path} contains neither ' '"VOC2007" nor "VOC2012" subfolder') out_fmt = f'.{args.out_format}' if args.out_format == 'coco': out_fmt = '.json' for year in years: if year == '2007': prefix = 'voc07' elif year == '2012': prefix = 'voc12' elif year == ['2007', '2012']: prefix = 'voc0712' for split in ['train', 'val', 'trainval']: dataset_name = prefix + '_' + split print(f'processing {dataset_name} ...') cvt_annotations(devkit_path, year, split, osp.join(out_dir, dataset_name + out_fmt)) if not isinstance(year, list): dataset_name = prefix + '_test' print(f'processing {dataset_name} ...') cvt_annotations(devkit_path, year, 'test', osp.join(out_dir, dataset_name + out_fmt)) print('Done!') if __name__ == '__main__': main()
7,841
31.94958
79
py
PseCo
PseCo-master/thirdparty/mmdetection/tools/analysis_tools/analyze_results.py
# Copyright (c) OpenMMLab. All rights reserved. import argparse import os.path as osp import mmcv import numpy as np from mmcv import Config, DictAction from mmdet.core.evaluation import eval_map from mmdet.core.visualization import imshow_gt_det_bboxes from mmdet.datasets import build_dataset, get_loading_pipeline def bbox_map_eval(det_result, annotation): """Evaluate mAP of single image det result. Args: det_result (list[list]): [[cls1_det, cls2_det, ...], ...]. The outer list indicates images, and the inner list indicates per-class detected bboxes. annotation (dict): Ground truth annotations where keys of annotations are: - bboxes: numpy array of shape (n, 4) - labels: numpy array of shape (n, ) - bboxes_ignore (optional): numpy array of shape (k, 4) - labels_ignore (optional): numpy array of shape (k, ) Returns: float: mAP """ # use only bbox det result if isinstance(det_result, tuple): bbox_det_result = [det_result[0]] else: bbox_det_result = [det_result] # mAP iou_thrs = np.linspace( .5, 0.95, int(np.round((0.95 - .5) / .05)) + 1, endpoint=True) mean_aps = [] for thr in iou_thrs: mean_ap, _ = eval_map( bbox_det_result, [annotation], iou_thr=thr, logger='silent') mean_aps.append(mean_ap) return sum(mean_aps) / len(mean_aps) class ResultVisualizer: """Display and save evaluation results. Args: show (bool): Whether to show the image. Default: True wait_time (float): Value of waitKey param. Default: 0. score_thr (float): Minimum score of bboxes to be shown. Default: 0 """ def __init__(self, show=False, wait_time=0, score_thr=0): self.show = show self.wait_time = wait_time self.score_thr = score_thr def _save_image_gts_results(self, dataset, results, mAPs, out_dir=None): mmcv.mkdir_or_exist(out_dir) for mAP_info in mAPs: index, mAP = mAP_info data_info = dataset.prepare_train_img(index) # calc save file path filename = data_info['filename'] if data_info['img_prefix'] is not None: filename = osp.join(data_info['img_prefix'], filename) else: filename = data_info['filename'] fname, name = osp.splitext(osp.basename(filename)) save_filename = fname + '_' + str(round(mAP, 3)) + name out_file = osp.join(out_dir, save_filename) imshow_gt_det_bboxes( data_info['img'], data_info, results[index], dataset.CLASSES, show=self.show, score_thr=self.score_thr, wait_time=self.wait_time, out_file=out_file) def evaluate_and_show(self, dataset, results, topk=20, show_dir='work_dir', eval_fn=None): """Evaluate and show results. Args: dataset (Dataset): A PyTorch dataset. results (list): Det results from test results pkl file topk (int): Number of the highest topk and lowest topk after evaluation index sorting. Default: 20 show_dir (str, optional): The filename to write the image. Default: 'work_dir' eval_fn (callable, optional): Eval function, Default: None """ assert topk > 0 if (topk * 2) > len(dataset): topk = len(dataset) // 2 if eval_fn is None: eval_fn = bbox_map_eval else: assert callable(eval_fn) prog_bar = mmcv.ProgressBar(len(results)) _mAPs = {} for i, (result, ) in enumerate(zip(results)): # self.dataset[i] should not call directly # because there is a risk of mismatch data_info = dataset.prepare_train_img(i) mAP = eval_fn(result, data_info['ann_info']) _mAPs[i] = mAP prog_bar.update() # descending select topk image _mAPs = list(sorted(_mAPs.items(), key=lambda kv: kv[1])) good_mAPs = _mAPs[-topk:] bad_mAPs = _mAPs[:topk] good_dir = osp.abspath(osp.join(show_dir, 'good')) bad_dir = osp.abspath(osp.join(show_dir, 'bad')) self._save_image_gts_results(dataset, results, good_mAPs, good_dir) self._save_image_gts_results(dataset, results, bad_mAPs, bad_dir) def parse_args(): parser = argparse.ArgumentParser( description='MMDet eval image prediction result for each') parser.add_argument('config', help='test config file path') parser.add_argument( 'prediction_path', help='prediction path where test pkl result') parser.add_argument( 'show_dir', help='directory where painted images will be saved') parser.add_argument('--show', action='store_true', help='show results') parser.add_argument( '--wait-time', type=float, default=0, help='the interval of show (s), 0 is block') parser.add_argument( '--topk', default=20, type=int, help='saved Number of the highest topk ' 'and lowest topk after index sorting') parser.add_argument( '--show-score-thr', type=float, default=0, help='score threshold (default: 0.)') parser.add_argument( '--cfg-options', nargs='+', action=DictAction, help='override some settings in the used config, the key-value pair ' 'in xxx=yyy format will be merged into config file. If the value to ' 'be overwritten is a list, it should be like key="[a,b]" or key=a,b ' 'It also allows nested list/tuple values, e.g. key="[(a,b),(c,d)]" ' 'Note that the quotation marks are necessary and that no white space ' 'is allowed.') args = parser.parse_args() return args def main(): args = parse_args() mmcv.check_file_exist(args.prediction_path) cfg = Config.fromfile(args.config) if args.cfg_options is not None: cfg.merge_from_dict(args.cfg_options) cfg.data.test.test_mode = True # import modules from string list. if cfg.get('custom_imports', None): from mmcv.utils import import_modules_from_strings import_modules_from_strings(**cfg['custom_imports']) cfg.data.test.pop('samples_per_gpu', 0) cfg.data.test.pipeline = get_loading_pipeline(cfg.data.train.pipeline) dataset = build_dataset(cfg.data.test) outputs = mmcv.load(args.prediction_path) result_visualizer = ResultVisualizer(args.show, args.wait_time, args.show_score_thr) result_visualizer.evaluate_and_show( dataset, outputs, topk=args.topk, show_dir=args.show_dir) if __name__ == '__main__': main()
7,096
33.789216
78
py
PseCo
PseCo-master/thirdparty/mmdetection/tools/analysis_tools/eval_metric.py
# Copyright (c) OpenMMLab. All rights reserved. import argparse import mmcv from mmcv import Config, DictAction from mmdet.datasets import build_dataset def parse_args(): parser = argparse.ArgumentParser(description='Evaluate metric of the ' 'results saved in pkl format') parser.add_argument('config', help='Config of the model') parser.add_argument('pkl_results', help='Results in pickle format') parser.add_argument( '--format-only', action='store_true', help='Format the output results without perform evaluation. It is' 'useful when you want to format the result to a specific format and ' 'submit it to the test server') parser.add_argument( '--eval', type=str, nargs='+', help='Evaluation metrics, which depends on the dataset, e.g., "bbox",' ' "segm", "proposal" for COCO, and "mAP", "recall" for PASCAL VOC') parser.add_argument( '--cfg-options', nargs='+', action=DictAction, help='override some settings in the used config, the key-value pair ' 'in xxx=yyy format will be merged into config file. If the value to ' 'be overwritten is a list, it should be like key="[a,b]" or key=a,b ' 'It also allows nested list/tuple values, e.g. key="[(a,b),(c,d)]" ' 'Note that the quotation marks are necessary and that no white space ' 'is allowed.') parser.add_argument( '--eval-options', nargs='+', action=DictAction, help='custom options for evaluation, the key-value pair in xxx=yyy ' 'format will be kwargs for dataset.evaluate() function') args = parser.parse_args() return args def main(): args = parse_args() cfg = Config.fromfile(args.config) assert args.eval or args.format_only, ( 'Please specify at least one operation (eval/format the results) with ' 'the argument "--eval", "--format-only"') if args.eval and args.format_only: raise ValueError('--eval and --format_only cannot be both specified') if args.cfg_options is not None: cfg.merge_from_dict(args.cfg_options) # import modules from string list. if cfg.get('custom_imports', None): from mmcv.utils import import_modules_from_strings import_modules_from_strings(**cfg['custom_imports']) cfg.data.test.test_mode = True dataset = build_dataset(cfg.data.test) outputs = mmcv.load(args.pkl_results) kwargs = {} if args.eval_options is None else args.eval_options if args.format_only: dataset.format_results(outputs, **kwargs) if args.eval: eval_kwargs = cfg.get('evaluation', {}).copy() # hard-code way to remove EvalHook args for key in [ 'interval', 'tmpdir', 'start', 'gpu_collect', 'save_best', 'rule' ]: eval_kwargs.pop(key, None) eval_kwargs.update(dict(metric=args.eval, **kwargs)) print(dataset.evaluate(outputs, **eval_kwargs)) if __name__ == '__main__': main()
3,118
35.694118
79
py
PseCo
PseCo-master/thirdparty/mmdetection/tools/analysis_tools/benchmark.py
# Copyright (c) OpenMMLab. All rights reserved. import argparse import os import time import torch from mmcv import Config, DictAction from mmcv.cnn import fuse_conv_bn from mmcv.parallel import MMDistributedDataParallel from mmcv.runner import init_dist, load_checkpoint, wrap_fp16_model from mmdet.datasets import (build_dataloader, build_dataset, replace_ImageToTensor) from mmdet.models import build_detector def parse_args(): parser = argparse.ArgumentParser(description='MMDet benchmark a model') parser.add_argument('config', help='test config file path') parser.add_argument('checkpoint', help='checkpoint file') parser.add_argument( '--max-iter', type=int, default=2000, help='num of max iter') parser.add_argument( '--log-interval', type=int, default=50, help='interval of logging') parser.add_argument( '--fuse-conv-bn', action='store_true', help='Whether to fuse conv and bn, this will slightly increase' 'the inference speed') parser.add_argument( '--cfg-options', nargs='+', action=DictAction, help='override some settings in the used config, the key-value pair ' 'in xxx=yyy format will be merged into config file. If the value to ' 'be overwritten is a list, it should be like key="[a,b]" or key=a,b ' 'It also allows nested list/tuple values, e.g. key="[(a,b),(c,d)]" ' 'Note that the quotation marks are necessary and that no white space ' 'is allowed.') parser.add_argument( '--launcher', choices=['none', 'pytorch', 'slurm', 'mpi'], default='none', help='job launcher') parser.add_argument('--local_rank', type=int, default=0) args = parser.parse_args() if 'LOCAL_RANK' not in os.environ: os.environ['LOCAL_RANK'] = str(args.local_rank) return args def measure_inferense_speed(cfg, checkpoint, max_iter, log_interval, is_fuse_conv_bn): # set cudnn_benchmark if cfg.get('cudnn_benchmark', False): torch.backends.cudnn.benchmark = True cfg.model.pretrained = None cfg.data.test.test_mode = True # build the dataloader samples_per_gpu = cfg.data.test.pop('samples_per_gpu', 1) if samples_per_gpu > 1: # Replace 'ImageToTensor' to 'DefaultFormatBundle' cfg.data.test.pipeline = replace_ImageToTensor(cfg.data.test.pipeline) dataset = build_dataset(cfg.data.test) data_loader = build_dataloader( dataset, samples_per_gpu=1, workers_per_gpu=cfg.data.workers_per_gpu, dist=True, shuffle=False) # build the model and load checkpoint cfg.model.train_cfg = None model = build_detector(cfg.model, test_cfg=cfg.get('test_cfg')) fp16_cfg = cfg.get('fp16', None) if fp16_cfg is not None: wrap_fp16_model(model) load_checkpoint(model, checkpoint, map_location='cpu') if is_fuse_conv_bn: model = fuse_conv_bn(model) model = MMDistributedDataParallel( model.cuda(), device_ids=[torch.cuda.current_device()], broadcast_buffers=False) model.eval() # the first several iterations may be very slow so skip them num_warmup = 5 pure_inf_time = 0 fps = 0 # benchmark with 2000 image and take the average for i, data in enumerate(data_loader): torch.cuda.synchronize() start_time = time.perf_counter() with torch.no_grad(): model(return_loss=False, rescale=True, **data) torch.cuda.synchronize() elapsed = time.perf_counter() - start_time if i >= num_warmup: pure_inf_time += elapsed if (i + 1) % log_interval == 0: fps = (i + 1 - num_warmup) / pure_inf_time print( f'Done image [{i + 1:<3}/ {max_iter}], ' f'fps: {fps:.1f} img / s, ' f'times per image: {1000 / fps:.1f} ms / img', flush=True) if (i + 1) == max_iter: fps = (i + 1 - num_warmup) / pure_inf_time print( f'Overall fps: {fps:.1f} img / s, ' f'times per image: {1000 / fps:.1f} ms / img', flush=True) break return fps def main(): args = parse_args() cfg = Config.fromfile(args.config) if args.cfg_options is not None: cfg.merge_from_dict(args.cfg_options) if args.launcher == 'none': raise NotImplementedError('Only supports distributed mode') else: init_dist(args.launcher, **cfg.dist_params) measure_inferense_speed(cfg, args.checkpoint, args.max_iter, args.log_interval, args.fuse_conv_bn) if __name__ == '__main__': main()
4,843
32.638889
78
py
PseCo
PseCo-master/thirdparty/mmdetection/tools/analysis_tools/optimize_anchors.py
# Copyright (c) OpenMMLab. All rights reserved. """Optimize anchor settings on a specific dataset. This script provides two method to optimize YOLO anchors including k-means anchor cluster and differential evolution. You can use ``--algorithm k-means`` and ``--algorithm differential_evolution`` to switch two method. Example: Use k-means anchor cluster:: python tools/analysis_tools/optimize_anchors.py ${CONFIG} \ --algorithm k-means --input-shape ${INPUT_SHAPE [WIDTH HEIGHT]} \ --output-dir ${OUTPUT_DIR} Use differential evolution to optimize anchors:: python tools/analysis_tools/optimize_anchors.py ${CONFIG} \ --algorithm differential_evolution \ --input-shape ${INPUT_SHAPE [WIDTH HEIGHT]} \ --output-dir ${OUTPUT_DIR} """ import argparse import os.path as osp import mmcv import numpy as np import torch from mmcv import Config from scipy.optimize import differential_evolution from mmdet.core import bbox_cxcywh_to_xyxy, bbox_overlaps, bbox_xyxy_to_cxcywh from mmdet.datasets import build_dataset from mmdet.utils import get_root_logger def parse_args(): parser = argparse.ArgumentParser(description='Optimize anchor parameters.') parser.add_argument('config', help='Train config file path.') parser.add_argument( '--device', default='cuda:0', help='Device used for calculating.') parser.add_argument( '--input-shape', type=int, nargs='+', default=[608, 608], help='input image size') parser.add_argument( '--algorithm', default='differential_evolution', help='Algorithm used for anchor optimizing.' 'Support k-means and differential_evolution for YOLO.') parser.add_argument( '--iters', default=1000, type=int, help='Maximum iterations for optimizer.') parser.add_argument( '--output-dir', default=None, type=str, help='Path to save anchor optimize result.') args = parser.parse_args() return args class BaseAnchorOptimizer: """Base class for anchor optimizer. Args: dataset (obj:`Dataset`): Dataset object. input_shape (list[int]): Input image shape of the model. Format in [width, height]. logger (obj:`logging.Logger`): The logger for logging. device (str, optional): Device used for calculating. Default: 'cuda:0' out_dir (str, optional): Path to save anchor optimize result. Default: None """ def __init__(self, dataset, input_shape, logger, device='cuda:0', out_dir=None): self.dataset = dataset self.input_shape = input_shape self.logger = logger self.device = device self.out_dir = out_dir bbox_whs, img_shapes = self.get_whs_and_shapes() ratios = img_shapes.max(1, keepdims=True) / np.array([input_shape]) # resize to input shape self.bbox_whs = bbox_whs / ratios def get_whs_and_shapes(self): """Get widths and heights of bboxes and shapes of images. Returns: tuple[np.ndarray]: Array of bbox shapes and array of image shapes with shape (num_bboxes, 2) in [width, height] format. """ self.logger.info('Collecting bboxes from annotation...') bbox_whs = [] img_shapes = [] prog_bar = mmcv.ProgressBar(len(self.dataset)) for idx in range(len(self.dataset)): ann = self.dataset.get_ann_info(idx) data_info = self.dataset.data_infos[idx] img_shape = np.array([data_info['width'], data_info['height']]) gt_bboxes = ann['bboxes'] for bbox in gt_bboxes: wh = bbox[2:4] - bbox[0:2] img_shapes.append(img_shape) bbox_whs.append(wh) prog_bar.update() print('\n') bbox_whs = np.array(bbox_whs) img_shapes = np.array(img_shapes) self.logger.info(f'Collected {bbox_whs.shape[0]} bboxes.') return bbox_whs, img_shapes def get_zero_center_bbox_tensor(self): """Get a tensor of bboxes centered at (0, 0). Returns: Tensor: Tensor of bboxes with shape (num_bboxes, 4) in [xmin, ymin, xmax, ymax] format. """ whs = torch.from_numpy(self.bbox_whs).to( self.device, dtype=torch.float32) bboxes = bbox_cxcywh_to_xyxy( torch.cat([torch.zeros_like(whs), whs], dim=1)) return bboxes def optimize(self): raise NotImplementedError def save_result(self, anchors, path=None): anchor_results = [] for w, h in anchors: anchor_results.append([round(w), round(h)]) self.logger.info(f'Anchor optimize result:{anchor_results}') if path: json_path = osp.join(path, 'anchor_optimize_result.json') mmcv.dump(anchor_results, json_path) self.logger.info(f'Result saved in {json_path}') class YOLOKMeansAnchorOptimizer(BaseAnchorOptimizer): r"""YOLO anchor optimizer using k-means. Code refer to `AlexeyAB/darknet. <https://github.com/AlexeyAB/darknet/blob/master/src/detector.c>`_. Args: num_anchors (int) : Number of anchors. iters (int): Maximum iterations for k-means. """ def __init__(self, num_anchors, iters, **kwargs): super(YOLOKMeansAnchorOptimizer, self).__init__(**kwargs) self.num_anchors = num_anchors self.iters = iters def optimize(self): anchors = self.kmeans_anchors() self.save_result(anchors, self.out_dir) def kmeans_anchors(self): self.logger.info( f'Start cluster {self.num_anchors} YOLO anchors with K-means...') bboxes = self.get_zero_center_bbox_tensor() cluster_center_idx = torch.randint( 0, bboxes.shape[0], (self.num_anchors, )).to(self.device) assignments = torch.zeros((bboxes.shape[0], )).to(self.device) cluster_centers = bboxes[cluster_center_idx] if self.num_anchors == 1: cluster_centers = self.kmeans_maximization(bboxes, assignments, cluster_centers) anchors = bbox_xyxy_to_cxcywh(cluster_centers)[:, 2:].cpu().numpy() anchors = sorted(anchors, key=lambda x: x[0] * x[1]) return anchors prog_bar = mmcv.ProgressBar(self.iters) for i in range(self.iters): converged, assignments = self.kmeans_expectation( bboxes, assignments, cluster_centers) if converged: self.logger.info(f'K-means process has converged at iter {i}.') break cluster_centers = self.kmeans_maximization(bboxes, assignments, cluster_centers) prog_bar.update() print('\n') avg_iou = bbox_overlaps(bboxes, cluster_centers).max(1)[0].mean().item() anchors = bbox_xyxy_to_cxcywh(cluster_centers)[:, 2:].cpu().numpy() anchors = sorted(anchors, key=lambda x: x[0] * x[1]) self.logger.info(f'Anchor cluster finish. Average IOU: {avg_iou}') return anchors def kmeans_maximization(self, bboxes, assignments, centers): """Maximization part of EM algorithm(Expectation-Maximization)""" new_centers = torch.zeros_like(centers) for i in range(centers.shape[0]): mask = (assignments == i) if mask.sum(): new_centers[i, :] = bboxes[mask].mean(0) return new_centers def kmeans_expectation(self, bboxes, assignments, centers): """Expectation part of EM algorithm(Expectation-Maximization)""" ious = bbox_overlaps(bboxes, centers) closest = ious.argmax(1) converged = (closest == assignments).all() return converged, closest class YOLODEAnchorOptimizer(BaseAnchorOptimizer): """YOLO anchor optimizer using differential evolution algorithm. Args: num_anchors (int) : Number of anchors. iters (int): Maximum iterations for k-means. strategy (str): The differential evolution strategy to use. Should be one of: - 'best1bin' - 'best1exp' - 'rand1exp' - 'randtobest1exp' - 'currenttobest1exp' - 'best2exp' - 'rand2exp' - 'randtobest1bin' - 'currenttobest1bin' - 'best2bin' - 'rand2bin' - 'rand1bin' Default: 'best1bin'. population_size (int): Total population size of evolution algorithm. Default: 15. convergence_thr (float): Tolerance for convergence, the optimizing stops when ``np.std(pop) <= abs(convergence_thr) + convergence_thr * np.abs(np.mean(population_energies))``, respectively. Default: 0.0001. mutation (tuple[float]): Range of dithering randomly changes the mutation constant. Default: (0.5, 1). recombination (float): Recombination constant of crossover probability. Default: 0.7. """ def __init__(self, num_anchors, iters, strategy='best1bin', population_size=15, convergence_thr=0.0001, mutation=(0.5, 1), recombination=0.7, **kwargs): super(YOLODEAnchorOptimizer, self).__init__(**kwargs) self.num_anchors = num_anchors self.iters = iters self.strategy = strategy self.population_size = population_size self.convergence_thr = convergence_thr self.mutation = mutation self.recombination = recombination def optimize(self): anchors = self.differential_evolution() self.save_result(anchors, self.out_dir) def differential_evolution(self): bboxes = self.get_zero_center_bbox_tensor() bounds = [] for i in range(self.num_anchors): bounds.extend([(0, self.input_shape[0]), (0, self.input_shape[1])]) result = differential_evolution( func=self.avg_iou_cost, bounds=bounds, args=(bboxes, ), strategy=self.strategy, maxiter=self.iters, popsize=self.population_size, tol=self.convergence_thr, mutation=self.mutation, recombination=self.recombination, updating='immediate', disp=True) self.logger.info( f'Anchor evolution finish. Average IOU: {1 - result.fun}') anchors = [(w, h) for w, h in zip(result.x[::2], result.x[1::2])] anchors = sorted(anchors, key=lambda x: x[0] * x[1]) return anchors @staticmethod def avg_iou_cost(anchor_params, bboxes): assert len(anchor_params) % 2 == 0 anchor_whs = torch.tensor( [[w, h] for w, h in zip(anchor_params[::2], anchor_params[1::2])]).to( bboxes.device, dtype=bboxes.dtype) anchor_boxes = bbox_cxcywh_to_xyxy( torch.cat([torch.zeros_like(anchor_whs), anchor_whs], dim=1)) ious = bbox_overlaps(bboxes, anchor_boxes) max_ious, _ = ious.max(1) cost = 1 - max_ious.mean().item() return cost def main(): logger = get_root_logger() args = parse_args() cfg = args.config cfg = Config.fromfile(cfg) input_shape = args.input_shape assert len(input_shape) == 2 anchor_type = cfg.model.bbox_head.anchor_generator.type assert anchor_type == 'YOLOAnchorGenerator', \ f'Only support optimize YOLOAnchor, but get {anchor_type}.' base_sizes = cfg.model.bbox_head.anchor_generator.base_sizes num_anchors = sum([len(sizes) for sizes in base_sizes]) train_data_cfg = cfg.data.train while 'dataset' in train_data_cfg: train_data_cfg = train_data_cfg['dataset'] dataset = build_dataset(train_data_cfg) if args.algorithm == 'k-means': optimizer = YOLOKMeansAnchorOptimizer( dataset=dataset, input_shape=input_shape, device=args.device, num_anchors=num_anchors, iters=args.iters, logger=logger, out_dir=args.output_dir) elif args.algorithm == 'differential_evolution': optimizer = YOLODEAnchorOptimizer( dataset=dataset, input_shape=input_shape, device=args.device, num_anchors=num_anchors, iters=args.iters, logger=logger, out_dir=args.output_dir) else: raise NotImplementedError( f'Only support k-means and differential_evolution, ' f'but get {args.algorithm}') optimizer.optimize() if __name__ == '__main__': main()
13,161
34.477089
79
py
PseCo
PseCo-master/thirdparty/mmdetection/tools/analysis_tools/get_flops.py
# Copyright (c) OpenMMLab. All rights reserved. import argparse import numpy as np import torch from mmcv import Config, DictAction from mmdet.models import build_detector try: from mmcv.cnn import get_model_complexity_info except ImportError: raise ImportError('Please upgrade mmcv to >0.6.2') def parse_args(): parser = argparse.ArgumentParser(description='Train a detector') parser.add_argument('config', help='train config file path') parser.add_argument( '--shape', type=int, nargs='+', default=[1280, 800], help='input image size') parser.add_argument( '--cfg-options', nargs='+', action=DictAction, help='override some settings in the used config, the key-value pair ' 'in xxx=yyy format will be merged into config file. If the value to ' 'be overwritten is a list, it should be like key="[a,b]" or key=a,b ' 'It also allows nested list/tuple values, e.g. key="[(a,b),(c,d)]" ' 'Note that the quotation marks are necessary and that no white space ' 'is allowed.') parser.add_argument( '--size-divisor', type=int, default=32, help='Pad the input image, the minimum size that is divisible ' 'by size_divisor, -1 means do not pad the image.') args = parser.parse_args() return args def main(): args = parse_args() if len(args.shape) == 1: h = w = args.shape[0] elif len(args.shape) == 2: h, w = args.shape else: raise ValueError('invalid input shape') orig_shape = (3, h, w) divisor = args.size_divisor if divisor > 0: h = int(np.ceil(h / divisor)) * divisor w = int(np.ceil(w / divisor)) * divisor input_shape = (3, h, w) cfg = Config.fromfile(args.config) if args.cfg_options is not None: cfg.merge_from_dict(args.cfg_options) # import modules from string list. if cfg.get('custom_imports', None): from mmcv.utils import import_modules_from_strings import_modules_from_strings(**cfg['custom_imports']) model = build_detector( cfg.model, train_cfg=cfg.get('train_cfg'), test_cfg=cfg.get('test_cfg')) if torch.cuda.is_available(): model.cuda() model.eval() if hasattr(model, 'forward_dummy'): model.forward = model.forward_dummy else: raise NotImplementedError( 'FLOPs counter is currently not currently supported with {}'. format(model.__class__.__name__)) flops, params = get_model_complexity_info(model, input_shape) split_line = '=' * 30 if divisor > 0 and \ input_shape != orig_shape: print(f'{split_line}\nUse size divisor set input shape ' f'from {orig_shape} to {input_shape}\n') print(f'{split_line}\nInput shape: {input_shape}\n' f'Flops: {flops}\nParams: {params}\n{split_line}') print('!!!Please be cautious if you use the results in papers. ' 'You may need to check if all ops are supported and verify that the ' 'flops computation is correct.') if __name__ == '__main__': main()
3,194
30.323529
79
py
PseCo
PseCo-master/thirdparty/mmdetection/tools/analysis_tools/analyze_logs.py
# Copyright (c) OpenMMLab. All rights reserved. import argparse import json from collections import defaultdict import matplotlib.pyplot as plt import numpy as np import seaborn as sns def cal_train_time(log_dicts, args): for i, log_dict in enumerate(log_dicts): print(f'{"-" * 5}Analyze train time of {args.json_logs[i]}{"-" * 5}') all_times = [] for epoch in log_dict.keys(): if args.include_outliers: all_times.append(log_dict[epoch]['time']) else: all_times.append(log_dict[epoch]['time'][1:]) all_times = np.array(all_times) epoch_ave_time = all_times.mean(-1) slowest_epoch = epoch_ave_time.argmax() fastest_epoch = epoch_ave_time.argmin() std_over_epoch = epoch_ave_time.std() print(f'slowest epoch {slowest_epoch + 1}, ' f'average time is {epoch_ave_time[slowest_epoch]:.4f}') print(f'fastest epoch {fastest_epoch + 1}, ' f'average time is {epoch_ave_time[fastest_epoch]:.4f}') print(f'time std over epochs is {std_over_epoch:.4f}') print(f'average iter time: {np.mean(all_times):.4f} s/iter') print() def plot_curve(log_dicts, args): if args.backend is not None: plt.switch_backend(args.backend) sns.set_style(args.style) # if legend is None, use {filename}_{key} as legend legend = args.legend if legend is None: legend = [] for json_log in args.json_logs: for metric in args.keys: legend.append(f'{json_log}_{metric}') assert len(legend) == (len(args.json_logs) * len(args.keys)) metrics = args.keys num_metrics = len(metrics) for i, log_dict in enumerate(log_dicts): epochs = list(log_dict.keys()) for j, metric in enumerate(metrics): print(f'plot curve of {args.json_logs[i]}, metric is {metric}') if metric not in log_dict[epochs[0]]: raise KeyError( f'{args.json_logs[i]} does not contain metric {metric}') if 'mAP' in metric: xs = np.arange(1, max(epochs) + 1) ys = [] for epoch in epochs: ys += log_dict[epoch][metric] ax = plt.gca() ax.set_xticks(xs) plt.xlabel('epoch') plt.plot(xs, ys, label=legend[i * num_metrics + j], marker='o') else: xs = [] ys = [] num_iters_per_epoch = log_dict[epochs[0]]['iter'][-2] for epoch in epochs: iters = log_dict[epoch]['iter'] if log_dict[epoch]['mode'][-1] == 'val': iters = iters[:-1] xs.append( np.array(iters) + (epoch - 1) * num_iters_per_epoch) ys.append(np.array(log_dict[epoch][metric][:len(iters)])) xs = np.concatenate(xs) ys = np.concatenate(ys) plt.xlabel('iter') plt.plot( xs, ys, label=legend[i * num_metrics + j], linewidth=0.5) plt.legend() if args.title is not None: plt.title(args.title) if args.out is None: plt.show() else: print(f'save curve to: {args.out}') plt.savefig(args.out) plt.cla() def add_plot_parser(subparsers): parser_plt = subparsers.add_parser( 'plot_curve', help='parser for plotting curves') parser_plt.add_argument( 'json_logs', type=str, nargs='+', help='path of train log in json format') parser_plt.add_argument( '--keys', type=str, nargs='+', default=['bbox_mAP'], help='the metric that you want to plot') parser_plt.add_argument('--title', type=str, help='title of figure') parser_plt.add_argument( '--legend', type=str, nargs='+', default=None, help='legend of each plot') parser_plt.add_argument( '--backend', type=str, default=None, help='backend of plt') parser_plt.add_argument( '--style', type=str, default='dark', help='style of plt') parser_plt.add_argument('--out', type=str, default=None) def add_time_parser(subparsers): parser_time = subparsers.add_parser( 'cal_train_time', help='parser for computing the average time per training iteration') parser_time.add_argument( 'json_logs', type=str, nargs='+', help='path of train log in json format') parser_time.add_argument( '--include-outliers', action='store_true', help='include the first value of every epoch when computing ' 'the average time') def parse_args(): parser = argparse.ArgumentParser(description='Analyze Json Log') # currently only support plot curve and calculate average train time subparsers = parser.add_subparsers(dest='task', help='task parser') add_plot_parser(subparsers) add_time_parser(subparsers) args = parser.parse_args() return args def load_json_logs(json_logs): # load and convert json_logs to log_dict, key is epoch, value is a sub dict # keys of sub dict is different metrics, e.g. memory, bbox_mAP # value of sub dict is a list of corresponding values of all iterations log_dicts = [dict() for _ in json_logs] for json_log, log_dict in zip(json_logs, log_dicts): with open(json_log, 'r') as log_file: for line in log_file: log = json.loads(line.strip()) # skip lines without `epoch` field if 'epoch' not in log: continue epoch = log.pop('epoch') if epoch not in log_dict: log_dict[epoch] = defaultdict(list) for k, v in log.items(): log_dict[epoch][k].append(v) return log_dicts def main(): args = parse_args() json_logs = args.json_logs for json_log in json_logs: assert json_log.endswith('.json') log_dicts = load_json_logs(json_logs) eval(args.task)(log_dicts, args) if __name__ == '__main__': main()
6,300
33.812155
79
py
PseCo
PseCo-master/thirdparty/mmdetection/tools/analysis_tools/test_robustness.py
# Copyright (c) OpenMMLab. All rights reserved. import argparse import copy import os import os.path as osp import mmcv import torch from mmcv import DictAction from mmcv.parallel import MMDataParallel, MMDistributedDataParallel from mmcv.runner import (get_dist_info, init_dist, load_checkpoint, wrap_fp16_model) from pycocotools.coco import COCO from pycocotools.cocoeval import COCOeval from tools.analysis_tools.robustness_eval import get_results from mmdet import datasets from mmdet.apis import multi_gpu_test, set_random_seed, single_gpu_test from mmdet.core import eval_map from mmdet.datasets import build_dataloader, build_dataset from mmdet.models import build_detector def coco_eval_with_return(result_files, result_types, coco, max_dets=(100, 300, 1000)): for res_type in result_types: assert res_type in ['proposal', 'bbox', 'segm', 'keypoints'] if mmcv.is_str(coco): coco = COCO(coco) assert isinstance(coco, COCO) eval_results = {} for res_type in result_types: result_file = result_files[res_type] assert result_file.endswith('.json') coco_dets = coco.loadRes(result_file) img_ids = coco.getImgIds() iou_type = 'bbox' if res_type == 'proposal' else res_type cocoEval = COCOeval(coco, coco_dets, iou_type) cocoEval.params.imgIds = img_ids if res_type == 'proposal': cocoEval.params.useCats = 0 cocoEval.params.maxDets = list(max_dets) cocoEval.evaluate() cocoEval.accumulate() cocoEval.summarize() if res_type == 'segm' or res_type == 'bbox': metric_names = [ 'AP', 'AP50', 'AP75', 'APs', 'APm', 'APl', 'AR1', 'AR10', 'AR100', 'ARs', 'ARm', 'ARl' ] eval_results[res_type] = { metric_names[i]: cocoEval.stats[i] for i in range(len(metric_names)) } else: eval_results[res_type] = cocoEval.stats return eval_results def voc_eval_with_return(result_file, dataset, iou_thr=0.5, logger='print', only_ap=True): det_results = mmcv.load(result_file) annotations = [dataset.get_ann_info(i) for i in range(len(dataset))] if hasattr(dataset, 'year') and dataset.year == 2007: dataset_name = 'voc07' else: dataset_name = dataset.CLASSES mean_ap, eval_results = eval_map( det_results, annotations, scale_ranges=None, iou_thr=iou_thr, dataset=dataset_name, logger=logger) if only_ap: eval_results = [{ 'ap': eval_results[i]['ap'] } for i in range(len(eval_results))] return mean_ap, eval_results def parse_args(): parser = argparse.ArgumentParser(description='MMDet test detector') parser.add_argument('config', help='test config file path') parser.add_argument('checkpoint', help='checkpoint file') parser.add_argument('--out', help='output result file') parser.add_argument( '--corruptions', type=str, nargs='+', default='benchmark', choices=[ 'all', 'benchmark', 'noise', 'blur', 'weather', 'digital', 'holdout', 'None', 'gaussian_noise', 'shot_noise', 'impulse_noise', 'defocus_blur', 'glass_blur', 'motion_blur', 'zoom_blur', 'snow', 'frost', 'fog', 'brightness', 'contrast', 'elastic_transform', 'pixelate', 'jpeg_compression', 'speckle_noise', 'gaussian_blur', 'spatter', 'saturate' ], help='corruptions') parser.add_argument( '--severities', type=int, nargs='+', default=[0, 1, 2, 3, 4, 5], help='corruption severity levels') parser.add_argument( '--eval', type=str, nargs='+', choices=['proposal', 'proposal_fast', 'bbox', 'segm', 'keypoints'], help='eval types') parser.add_argument( '--iou-thr', type=float, default=0.5, help='IoU threshold for pascal voc evaluation') parser.add_argument( '--summaries', type=bool, default=False, help='Print summaries for every corruption and severity') parser.add_argument( '--workers', type=int, default=32, help='workers per gpu') parser.add_argument('--show', action='store_true', help='show results') parser.add_argument( '--show-dir', help='directory where painted images will be saved') parser.add_argument( '--show-score-thr', type=float, default=0.3, help='score threshold (default: 0.3)') parser.add_argument('--tmpdir', help='tmp dir for writing some results') parser.add_argument('--seed', type=int, default=None, help='random seed') parser.add_argument( '--launcher', choices=['none', 'pytorch', 'slurm', 'mpi'], default='none', help='job launcher') parser.add_argument('--local_rank', type=int, default=0) parser.add_argument( '--final-prints', type=str, nargs='+', choices=['P', 'mPC', 'rPC'], default='mPC', help='corruption benchmark metric to print at the end') parser.add_argument( '--final-prints-aggregate', type=str, choices=['all', 'benchmark'], default='benchmark', help='aggregate all results or only those for benchmark corruptions') parser.add_argument( '--cfg-options', nargs='+', action=DictAction, help='override some settings in the used config, the key-value pair ' 'in xxx=yyy format will be merged into config file. If the value to ' 'be overwritten is a list, it should be like key="[a,b]" or key=a,b ' 'It also allows nested list/tuple values, e.g. key="[(a,b),(c,d)]" ' 'Note that the quotation marks are necessary and that no white space ' 'is allowed.') args = parser.parse_args() if 'LOCAL_RANK' not in os.environ: os.environ['LOCAL_RANK'] = str(args.local_rank) return args def main(): args = parse_args() assert args.out or args.show or args.show_dir, \ ('Please specify at least one operation (save or show the results) ' 'with the argument "--out", "--show" or "show-dir"') if args.out is not None and not args.out.endswith(('.pkl', '.pickle')): raise ValueError('The output file must be a pkl file.') cfg = mmcv.Config.fromfile(args.config) if args.cfg_options is not None: cfg.merge_from_dict(args.cfg_options) # import modules from string list. if cfg.get('custom_imports', None): from mmcv.utils import import_modules_from_strings import_modules_from_strings(**cfg['custom_imports']) # set cudnn_benchmark if cfg.get('cudnn_benchmark', False): torch.backends.cudnn.benchmark = True cfg.model.pretrained = None cfg.data.test.test_mode = True if args.workers == 0: args.workers = cfg.data.workers_per_gpu # init distributed env first, since logger depends on the dist info. if args.launcher == 'none': distributed = False else: distributed = True init_dist(args.launcher, **cfg.dist_params) # set random seeds if args.seed is not None: set_random_seed(args.seed) if 'all' in args.corruptions: corruptions = [ 'gaussian_noise', 'shot_noise', 'impulse_noise', 'defocus_blur', 'glass_blur', 'motion_blur', 'zoom_blur', 'snow', 'frost', 'fog', 'brightness', 'contrast', 'elastic_transform', 'pixelate', 'jpeg_compression', 'speckle_noise', 'gaussian_blur', 'spatter', 'saturate' ] elif 'benchmark' in args.corruptions: corruptions = [ 'gaussian_noise', 'shot_noise', 'impulse_noise', 'defocus_blur', 'glass_blur', 'motion_blur', 'zoom_blur', 'snow', 'frost', 'fog', 'brightness', 'contrast', 'elastic_transform', 'pixelate', 'jpeg_compression' ] elif 'noise' in args.corruptions: corruptions = ['gaussian_noise', 'shot_noise', 'impulse_noise'] elif 'blur' in args.corruptions: corruptions = [ 'defocus_blur', 'glass_blur', 'motion_blur', 'zoom_blur' ] elif 'weather' in args.corruptions: corruptions = ['snow', 'frost', 'fog', 'brightness'] elif 'digital' in args.corruptions: corruptions = [ 'contrast', 'elastic_transform', 'pixelate', 'jpeg_compression' ] elif 'holdout' in args.corruptions: corruptions = ['speckle_noise', 'gaussian_blur', 'spatter', 'saturate'] elif 'None' in args.corruptions: corruptions = ['None'] args.severities = [0] else: corruptions = args.corruptions rank, _ = get_dist_info() aggregated_results = {} for corr_i, corruption in enumerate(corruptions): aggregated_results[corruption] = {} for sev_i, corruption_severity in enumerate(args.severities): # evaluate severity 0 (= no corruption) only once if corr_i > 0 and corruption_severity == 0: aggregated_results[corruption][0] = \ aggregated_results[corruptions[0]][0] continue test_data_cfg = copy.deepcopy(cfg.data.test) # assign corruption and severity if corruption_severity > 0: corruption_trans = dict( type='Corrupt', corruption=corruption, severity=corruption_severity) # TODO: hard coded "1", we assume that the first step is # loading images, which needs to be fixed in the future test_data_cfg['pipeline'].insert(1, corruption_trans) # print info print(f'\nTesting {corruption} at severity {corruption_severity}') # build the dataloader # TODO: support multiple images per gpu # (only minor changes are needed) dataset = build_dataset(test_data_cfg) data_loader = build_dataloader( dataset, samples_per_gpu=1, workers_per_gpu=args.workers, dist=distributed, shuffle=False) # build the model and load checkpoint cfg.model.train_cfg = None model = build_detector(cfg.model, test_cfg=cfg.get('test_cfg')) fp16_cfg = cfg.get('fp16', None) if fp16_cfg is not None: wrap_fp16_model(model) checkpoint = load_checkpoint( model, args.checkpoint, map_location='cpu') # old versions did not save class info in checkpoints, # this walkaround is for backward compatibility if 'CLASSES' in checkpoint.get('meta', {}): model.CLASSES = checkpoint['meta']['CLASSES'] else: model.CLASSES = dataset.CLASSES if not distributed: model = MMDataParallel(model, device_ids=[0]) show_dir = args.show_dir if show_dir is not None: show_dir = osp.join(show_dir, corruption) show_dir = osp.join(show_dir, str(corruption_severity)) if not osp.exists(show_dir): osp.makedirs(show_dir) outputs = single_gpu_test(model, data_loader, args.show, show_dir, args.show_score_thr) else: model = MMDistributedDataParallel( model.cuda(), device_ids=[torch.cuda.current_device()], broadcast_buffers=False) outputs = multi_gpu_test(model, data_loader, args.tmpdir) if args.out and rank == 0: eval_results_filename = ( osp.splitext(args.out)[0] + '_results' + osp.splitext(args.out)[1]) mmcv.dump(outputs, args.out) eval_types = args.eval if cfg.dataset_type == 'VOCDataset': if eval_types: for eval_type in eval_types: if eval_type == 'bbox': test_dataset = mmcv.runner.obj_from_dict( cfg.data.test, datasets) logger = 'print' if args.summaries else None mean_ap, eval_results = \ voc_eval_with_return( args.out, test_dataset, args.iou_thr, logger) aggregated_results[corruption][ corruption_severity] = eval_results else: print('\nOnly "bbox" evaluation \ is supported for pascal voc') else: if eval_types: print(f'Starting evaluate {" and ".join(eval_types)}') if eval_types == ['proposal_fast']: result_file = args.out else: if not isinstance(outputs[0], dict): result_files = dataset.results2json( outputs, args.out) else: for name in outputs[0]: print(f'\nEvaluating {name}') outputs_ = [out[name] for out in outputs] result_file = args.out + f'.{name}' result_files = dataset.results2json( outputs_, result_file) eval_results = coco_eval_with_return( result_files, eval_types, dataset.coco) aggregated_results[corruption][ corruption_severity] = eval_results else: print('\nNo task was selected for evaluation;' '\nUse --eval to select a task') # save results after each evaluation mmcv.dump(aggregated_results, eval_results_filename) if rank == 0: # print final results print('\nAggregated results:') prints = args.final_prints aggregate = args.final_prints_aggregate if cfg.dataset_type == 'VOCDataset': get_results( eval_results_filename, dataset='voc', prints=prints, aggregate=aggregate) else: get_results( eval_results_filename, dataset='coco', prints=prints, aggregate=aggregate) if __name__ == '__main__': main()
15,421
38.341837
79
py
PseCo
PseCo-master/thirdparty/mmdetection/tools/analysis_tools/coco_error_analysis.py
# Copyright (c) OpenMMLab. All rights reserved. import copy import os from argparse import ArgumentParser from multiprocessing import Pool import matplotlib.pyplot as plt import numpy as np from pycocotools.coco import COCO from pycocotools.cocoeval import COCOeval def makeplot(rs, ps, outDir, class_name, iou_type): cs = np.vstack([ np.ones((2, 3)), np.array([0.31, 0.51, 0.74]), np.array([0.75, 0.31, 0.30]), np.array([0.36, 0.90, 0.38]), np.array([0.50, 0.39, 0.64]), np.array([1, 0.6, 0]), ]) areaNames = ['allarea', 'small', 'medium', 'large'] types = ['C75', 'C50', 'Loc', 'Sim', 'Oth', 'BG', 'FN'] for i in range(len(areaNames)): area_ps = ps[..., i, 0] figure_title = iou_type + '-' + class_name + '-' + areaNames[i] aps = [ps_.mean() for ps_ in area_ps] ps_curve = [ ps_.mean(axis=1) if ps_.ndim > 1 else ps_ for ps_ in area_ps ] ps_curve.insert(0, np.zeros(ps_curve[0].shape)) fig = plt.figure() ax = plt.subplot(111) for k in range(len(types)): ax.plot(rs, ps_curve[k + 1], color=[0, 0, 0], linewidth=0.5) ax.fill_between( rs, ps_curve[k], ps_curve[k + 1], color=cs[k], label=str(f'[{aps[k]:.3f}]' + types[k]), ) plt.xlabel('recall') plt.ylabel('precision') plt.xlim(0, 1.0) plt.ylim(0, 1.0) plt.title(figure_title) plt.legend() # plt.show() fig.savefig(outDir + f'/{figure_title}.png') plt.close(fig) def autolabel(ax, rects): """Attach a text label above each bar in *rects*, displaying its height.""" for rect in rects: height = rect.get_height() if height > 0 and height <= 1: # for percent values text_label = '{:2.0f}'.format(height * 100) else: text_label = '{:2.0f}'.format(height) ax.annotate( text_label, xy=(rect.get_x() + rect.get_width() / 2, height), xytext=(0, 3), # 3 points vertical offset textcoords='offset points', ha='center', va='bottom', fontsize='x-small', ) def makebarplot(rs, ps, outDir, class_name, iou_type): areaNames = ['allarea', 'small', 'medium', 'large'] types = ['C75', 'C50', 'Loc', 'Sim', 'Oth', 'BG', 'FN'] fig, ax = plt.subplots() x = np.arange(len(areaNames)) # the areaNames locations width = 0.60 # the width of the bars rects_list = [] figure_title = iou_type + '-' + class_name + '-' + 'ap bar plot' for i in range(len(types) - 1): type_ps = ps[i, ..., 0] aps = [ps_.mean() for ps_ in type_ps.T] rects_list.append( ax.bar( x - width / 2 + (i + 1) * width / len(types), aps, width / len(types), label=types[i], )) # Add some text for labels, title and custom x-axis tick labels, etc. ax.set_ylabel('Mean Average Precision (mAP)') ax.set_title(figure_title) ax.set_xticks(x) ax.set_xticklabels(areaNames) ax.legend() # Add score texts over bars for rects in rects_list: autolabel(ax, rects) # Save plot fig.savefig(outDir + f'/{figure_title}.png') plt.close(fig) def get_gt_area_group_numbers(cocoEval): areaRng = cocoEval.params.areaRng areaRngStr = [str(aRng) for aRng in areaRng] areaRngLbl = cocoEval.params.areaRngLbl areaRngStr2areaRngLbl = dict(zip(areaRngStr, areaRngLbl)) areaRngLbl2Number = dict.fromkeys(areaRngLbl, 0) for evalImg in cocoEval.evalImgs: if evalImg: for gtIgnore in evalImg['gtIgnore']: if not gtIgnore: aRngLbl = areaRngStr2areaRngLbl[str(evalImg['aRng'])] areaRngLbl2Number[aRngLbl] += 1 return areaRngLbl2Number def make_gt_area_group_numbers_plot(cocoEval, outDir, verbose=True): areaRngLbl2Number = get_gt_area_group_numbers(cocoEval) areaRngLbl = areaRngLbl2Number.keys() if verbose: print('number of annotations per area group:', areaRngLbl2Number) # Init figure fig, ax = plt.subplots() x = np.arange(len(areaRngLbl)) # the areaNames locations width = 0.60 # the width of the bars figure_title = 'number of annotations per area group' rects = ax.bar(x, areaRngLbl2Number.values(), width) # Add some text for labels, title and custom x-axis tick labels, etc. ax.set_ylabel('Number of annotations') ax.set_title(figure_title) ax.set_xticks(x) ax.set_xticklabels(areaRngLbl) # Add score texts over bars autolabel(ax, rects) # Save plot fig.tight_layout() fig.savefig(outDir + f'/{figure_title}.png') plt.close(fig) def make_gt_area_histogram_plot(cocoEval, outDir): n_bins = 100 areas = [ann['area'] for ann in cocoEval.cocoGt.anns.values()] # init figure figure_title = 'gt annotation areas histogram plot' fig, ax = plt.subplots() # Set the number of bins ax.hist(np.sqrt(areas), bins=n_bins) # Add some text for labels, title and custom x-axis tick labels, etc. ax.set_xlabel('Squareroot Area') ax.set_ylabel('Number of annotations') ax.set_title(figure_title) # Save plot fig.tight_layout() fig.savefig(outDir + f'/{figure_title}.png') plt.close(fig) def analyze_individual_category(k, cocoDt, cocoGt, catId, iou_type, areas=None): nm = cocoGt.loadCats(catId)[0] print(f'--------------analyzing {k + 1}-{nm["name"]}---------------') ps_ = {} dt = copy.deepcopy(cocoDt) nm = cocoGt.loadCats(catId)[0] imgIds = cocoGt.getImgIds() dt_anns = dt.dataset['annotations'] select_dt_anns = [] for ann in dt_anns: if ann['category_id'] == catId: select_dt_anns.append(ann) dt.dataset['annotations'] = select_dt_anns dt.createIndex() # compute precision but ignore superclass confusion gt = copy.deepcopy(cocoGt) child_catIds = gt.getCatIds(supNms=[nm['supercategory']]) for idx, ann in enumerate(gt.dataset['annotations']): if ann['category_id'] in child_catIds and ann['category_id'] != catId: gt.dataset['annotations'][idx]['ignore'] = 1 gt.dataset['annotations'][idx]['iscrowd'] = 1 gt.dataset['annotations'][idx]['category_id'] = catId cocoEval = COCOeval(gt, copy.deepcopy(dt), iou_type) cocoEval.params.imgIds = imgIds cocoEval.params.maxDets = [100] cocoEval.params.iouThrs = [0.1] cocoEval.params.useCats = 1 if areas: cocoEval.params.areaRng = [[0**2, areas[2]], [0**2, areas[0]], [areas[0], areas[1]], [areas[1], areas[2]]] cocoEval.evaluate() cocoEval.accumulate() ps_supercategory = cocoEval.eval['precision'][0, :, k, :, :] ps_['ps_supercategory'] = ps_supercategory # compute precision but ignore any class confusion gt = copy.deepcopy(cocoGt) for idx, ann in enumerate(gt.dataset['annotations']): if ann['category_id'] != catId: gt.dataset['annotations'][idx]['ignore'] = 1 gt.dataset['annotations'][idx]['iscrowd'] = 1 gt.dataset['annotations'][idx]['category_id'] = catId cocoEval = COCOeval(gt, copy.deepcopy(dt), iou_type) cocoEval.params.imgIds = imgIds cocoEval.params.maxDets = [100] cocoEval.params.iouThrs = [0.1] cocoEval.params.useCats = 1 if areas: cocoEval.params.areaRng = [[0**2, areas[2]], [0**2, areas[0]], [areas[0], areas[1]], [areas[1], areas[2]]] cocoEval.evaluate() cocoEval.accumulate() ps_allcategory = cocoEval.eval['precision'][0, :, k, :, :] ps_['ps_allcategory'] = ps_allcategory return k, ps_ def analyze_results(res_file, ann_file, res_types, out_dir, extraplots=None, areas=None): for res_type in res_types: assert res_type in ['bbox', 'segm'] if areas: assert len(areas) == 3, '3 integers should be specified as areas, \ representing 3 area regions' directory = os.path.dirname(out_dir + '/') if not os.path.exists(directory): print(f'-------------create {out_dir}-----------------') os.makedirs(directory) cocoGt = COCO(ann_file) cocoDt = cocoGt.loadRes(res_file) imgIds = cocoGt.getImgIds() for res_type in res_types: res_out_dir = out_dir + '/' + res_type + '/' res_directory = os.path.dirname(res_out_dir) if not os.path.exists(res_directory): print(f'-------------create {res_out_dir}-----------------') os.makedirs(res_directory) iou_type = res_type cocoEval = COCOeval( copy.deepcopy(cocoGt), copy.deepcopy(cocoDt), iou_type) cocoEval.params.imgIds = imgIds cocoEval.params.iouThrs = [0.75, 0.5, 0.1] cocoEval.params.maxDets = [100] if areas: cocoEval.params.areaRng = [[0**2, areas[2]], [0**2, areas[0]], [areas[0], areas[1]], [areas[1], areas[2]]] cocoEval.evaluate() cocoEval.accumulate() ps = cocoEval.eval['precision'] ps = np.vstack([ps, np.zeros((4, *ps.shape[1:]))]) catIds = cocoGt.getCatIds() recThrs = cocoEval.params.recThrs with Pool(processes=48) as pool: args = [(k, cocoDt, cocoGt, catId, iou_type, areas) for k, catId in enumerate(catIds)] analyze_results = pool.starmap(analyze_individual_category, args) for k, catId in enumerate(catIds): nm = cocoGt.loadCats(catId)[0] print(f'--------------saving {k + 1}-{nm["name"]}---------------') analyze_result = analyze_results[k] assert k == analyze_result[0] ps_supercategory = analyze_result[1]['ps_supercategory'] ps_allcategory = analyze_result[1]['ps_allcategory'] # compute precision but ignore superclass confusion ps[3, :, k, :, :] = ps_supercategory # compute precision but ignore any class confusion ps[4, :, k, :, :] = ps_allcategory # fill in background and false negative errors and plot ps[ps == -1] = 0 ps[5, :, k, :, :] = ps[4, :, k, :, :] > 0 ps[6, :, k, :, :] = 1.0 makeplot(recThrs, ps[:, :, k], res_out_dir, nm['name'], iou_type) if extraplots: makebarplot(recThrs, ps[:, :, k], res_out_dir, nm['name'], iou_type) makeplot(recThrs, ps, res_out_dir, 'allclass', iou_type) if extraplots: makebarplot(recThrs, ps, res_out_dir, 'allclass', iou_type) make_gt_area_group_numbers_plot( cocoEval=cocoEval, outDir=res_out_dir, verbose=True) make_gt_area_histogram_plot(cocoEval=cocoEval, outDir=res_out_dir) def main(): parser = ArgumentParser(description='COCO Error Analysis Tool') parser.add_argument('result', help='result file (json format) path') parser.add_argument('out_dir', help='dir to save analyze result images') parser.add_argument( '--ann', default='data/coco/annotations/instances_val2017.json', help='annotation file path') parser.add_argument( '--types', type=str, nargs='+', default=['bbox'], help='result types') parser.add_argument( '--extraplots', action='store_true', help='export extra bar/stat plots') parser.add_argument( '--areas', type=int, nargs='+', default=[1024, 9216, 10000000000], help='area regions') args = parser.parse_args() analyze_results( args.result, args.ann, args.types, out_dir=args.out_dir, extraplots=args.extraplots, areas=args.areas) if __name__ == '__main__': main()
12,389
35.441176
79
py
PseCo
PseCo-master/thirdparty/mmdetection/tools/analysis_tools/robustness_eval.py
# Copyright (c) OpenMMLab. All rights reserved. import os.path as osp from argparse import ArgumentParser import mmcv import numpy as np def print_coco_results(results): def _print(result, ap=1, iouThr=None, areaRng='all', maxDets=100): titleStr = 'Average Precision' if ap == 1 else 'Average Recall' typeStr = '(AP)' if ap == 1 else '(AR)' iouStr = '0.50:0.95' \ if iouThr is None else f'{iouThr:0.2f}' iStr = f' {titleStr:<18} {typeStr} @[ IoU={iouStr:<9} | ' iStr += f'area={areaRng:>6s} | maxDets={maxDets:>3d} ] = {result:0.3f}' print(iStr) stats = np.zeros((12, )) stats[0] = _print(results[0], 1) stats[1] = _print(results[1], 1, iouThr=.5) stats[2] = _print(results[2], 1, iouThr=.75) stats[3] = _print(results[3], 1, areaRng='small') stats[4] = _print(results[4], 1, areaRng='medium') stats[5] = _print(results[5], 1, areaRng='large') stats[6] = _print(results[6], 0, maxDets=1) stats[7] = _print(results[7], 0, maxDets=10) stats[8] = _print(results[8], 0) stats[9] = _print(results[9], 0, areaRng='small') stats[10] = _print(results[10], 0, areaRng='medium') stats[11] = _print(results[11], 0, areaRng='large') def get_coco_style_results(filename, task='bbox', metric=None, prints='mPC', aggregate='benchmark'): assert aggregate in ['benchmark', 'all'] if prints == 'all': prints = ['P', 'mPC', 'rPC'] elif isinstance(prints, str): prints = [prints] for p in prints: assert p in ['P', 'mPC', 'rPC'] if metric is None: metrics = [ 'AP', 'AP50', 'AP75', 'APs', 'APm', 'APl', 'AR1', 'AR10', 'AR100', 'ARs', 'ARm', 'ARl' ] elif isinstance(metric, list): metrics = metric else: metrics = [metric] for metric_name in metrics: assert metric_name in [ 'AP', 'AP50', 'AP75', 'APs', 'APm', 'APl', 'AR1', 'AR10', 'AR100', 'ARs', 'ARm', 'ARl' ] eval_output = mmcv.load(filename) num_distortions = len(list(eval_output.keys())) results = np.zeros((num_distortions, 6, len(metrics)), dtype='float32') for corr_i, distortion in enumerate(eval_output): for severity in eval_output[distortion]: for metric_j, metric_name in enumerate(metrics): mAP = eval_output[distortion][severity][task][metric_name] results[corr_i, severity, metric_j] = mAP P = results[0, 0, :] if aggregate == 'benchmark': mPC = np.mean(results[:15, 1:, :], axis=(0, 1)) else: mPC = np.mean(results[:, 1:, :], axis=(0, 1)) rPC = mPC / P print(f'\nmodel: {osp.basename(filename)}') if metric is None: if 'P' in prints: print(f'Performance on Clean Data [P] ({task})') print_coco_results(P) if 'mPC' in prints: print(f'Mean Performance under Corruption [mPC] ({task})') print_coco_results(mPC) if 'rPC' in prints: print(f'Relative Performance under Corruption [rPC] ({task})') print_coco_results(rPC) else: if 'P' in prints: print(f'Performance on Clean Data [P] ({task})') for metric_i, metric_name in enumerate(metrics): print(f'{metric_name:5} = {P[metric_i]:0.3f}') if 'mPC' in prints: print(f'Mean Performance under Corruption [mPC] ({task})') for metric_i, metric_name in enumerate(metrics): print(f'{metric_name:5} = {mPC[metric_i]:0.3f}') if 'rPC' in prints: print(f'Relative Performance under Corruption [rPC] ({task})') for metric_i, metric_name in enumerate(metrics): print(f'{metric_name:5} => {rPC[metric_i] * 100:0.1f} %') return results def get_voc_style_results(filename, prints='mPC', aggregate='benchmark'): assert aggregate in ['benchmark', 'all'] if prints == 'all': prints = ['P', 'mPC', 'rPC'] elif isinstance(prints, str): prints = [prints] for p in prints: assert p in ['P', 'mPC', 'rPC'] eval_output = mmcv.load(filename) num_distortions = len(list(eval_output.keys())) results = np.zeros((num_distortions, 6, 20), dtype='float32') for i, distortion in enumerate(eval_output): for severity in eval_output[distortion]: mAP = [ eval_output[distortion][severity][j]['ap'] for j in range(len(eval_output[distortion][severity])) ] results[i, severity, :] = mAP P = results[0, 0, :] if aggregate == 'benchmark': mPC = np.mean(results[:15, 1:, :], axis=(0, 1)) else: mPC = np.mean(results[:, 1:, :], axis=(0, 1)) rPC = mPC / P print(f'\nmodel: {osp.basename(filename)}') if 'P' in prints: print(f'Performance on Clean Data [P] in AP50 = {np.mean(P):0.3f}') if 'mPC' in prints: print('Mean Performance under Corruption [mPC] in AP50 = ' f'{np.mean(mPC):0.3f}') if 'rPC' in prints: print('Relative Performance under Corruption [rPC] in % = ' f'{np.mean(rPC) * 100:0.1f}') return np.mean(results, axis=2, keepdims=True) def get_results(filename, dataset='coco', task='bbox', metric=None, prints='mPC', aggregate='benchmark'): assert dataset in ['coco', 'voc', 'cityscapes'] if dataset in ['coco', 'cityscapes']: results = get_coco_style_results( filename, task=task, metric=metric, prints=prints, aggregate=aggregate) elif dataset == 'voc': if task != 'bbox': print('Only bbox analysis is supported for Pascal VOC') print('Will report bbox results\n') if metric not in [None, ['AP'], ['AP50']]: print('Only the AP50 metric is supported for Pascal VOC') print('Will report AP50 metric\n') results = get_voc_style_results( filename, prints=prints, aggregate=aggregate) return results def get_distortions_from_file(filename): eval_output = mmcv.load(filename) return get_distortions_from_results(eval_output) def get_distortions_from_results(eval_output): distortions = [] for i, distortion in enumerate(eval_output): distortions.append(distortion.replace('_', ' ')) return distortions def main(): parser = ArgumentParser(description='Corruption Result Analysis') parser.add_argument('filename', help='result file path') parser.add_argument( '--dataset', type=str, choices=['coco', 'voc', 'cityscapes'], default='coco', help='dataset type') parser.add_argument( '--task', type=str, nargs='+', choices=['bbox', 'segm'], default=['bbox'], help='task to report') parser.add_argument( '--metric', nargs='+', choices=[ None, 'AP', 'AP50', 'AP75', 'APs', 'APm', 'APl', 'AR1', 'AR10', 'AR100', 'ARs', 'ARm', 'ARl' ], default=None, help='metric to report') parser.add_argument( '--prints', type=str, nargs='+', choices=['P', 'mPC', 'rPC'], default='mPC', help='corruption benchmark metric to print') parser.add_argument( '--aggregate', type=str, choices=['all', 'benchmark'], default='benchmark', help='aggregate all results or only those \ for benchmark corruptions') args = parser.parse_args() for task in args.task: get_results( args.filename, dataset=args.dataset, task=task, metric=args.metric, prints=args.prints, aggregate=args.aggregate) if __name__ == '__main__': main()
8,112
31.194444
79
py
PseCo
PseCo-master/thirdparty/mmdetection/docs_zh-CN/stat.py
#!/usr/bin/env python import functools as func import glob import os.path as osp import re import numpy as np url_prefix = 'https://github.com/open-mmlab/mmdetection/blob/master/' files = sorted(glob.glob('../configs/*/README.md')) stats = [] titles = [] num_ckpts = 0 for f in files: url = osp.dirname(f.replace('../', url_prefix)) with open(f, 'r') as content_file: content = content_file.read() title = content.split('\n')[0].replace('# ', '').strip() ckpts = set(x.lower().strip() for x in re.findall(r'\[model\]\((https?.*)\)', content)) if len(ckpts) == 0: continue _papertype = [x for x in re.findall(r'\[([A-Z]+)\]', content)] assert len(_papertype) > 0 papertype = _papertype[0] paper = set([(papertype, title)]) titles.append(title) num_ckpts += len(ckpts) statsmsg = f""" \t* [{papertype}] [{title}]({url}) ({len(ckpts)} ckpts) """ stats.append((paper, ckpts, statsmsg)) allpapers = func.reduce(lambda a, b: a.union(b), [p for p, _, _ in stats]) msglist = '\n'.join(x for _, _, x in stats) papertypes, papercounts = np.unique([t for t, _ in allpapers], return_counts=True) countstr = '\n'.join( [f' - {t}: {c}' for t, c in zip(papertypes, papercounts)]) modelzoo = f""" # Model Zoo Statistics * Number of papers: {len(set(titles))} {countstr} * Number of checkpoints: {num_ckpts} {msglist} """ with open('modelzoo_statistics.md', 'w') as f: f.write(modelzoo)
1,519
22.384615
74
py
PseCo
PseCo-master/thirdparty/mmdetection/docs_zh-CN/conf.py
# Configuration file for the Sphinx documentation builder. # # This file only contains a selection of the most common options. For a full # list see the documentation: # https://www.sphinx-doc.org/en/master/usage/configuration.html # -- Path setup -------------------------------------------------------------- # If extensions (or modules to document with autodoc) are in another directory, # add these directories to sys.path here. If the directory is relative to the # documentation root, use os.path.abspath to make it absolute, like shown here. # import os import subprocess import sys sys.path.insert(0, os.path.abspath('..')) # -- Project information ----------------------------------------------------- project = 'MMDetection' copyright = '2018-2021, OpenMMLab' author = 'MMDetection Authors' version_file = '../mmdet/version.py' def get_version(): with open(version_file, 'r') as f: exec(compile(f.read(), version_file, 'exec')) return locals()['__version__'] # The full version, including alpha/beta/rc tags release = get_version() # -- General configuration --------------------------------------------------- # Add any Sphinx extension module names here, as strings. They can be # extensions coming with Sphinx (named 'sphinx.ext.*') or your custom # ones. extensions = [ 'sphinx.ext.autodoc', 'sphinx.ext.napoleon', 'sphinx.ext.viewcode', 'recommonmark', 'sphinx_markdown_tables', ] autodoc_mock_imports = [ 'matplotlib', 'pycocotools', 'terminaltables', 'mmdet.version', 'mmcv.ops' ] # Add any paths that contain templates here, relative to this directory. templates_path = ['_templates'] # The suffix(es) of source filenames. # You can specify multiple suffix as a list of string: # source_suffix = { '.rst': 'restructuredtext', '.md': 'markdown', } # The master toctree document. master_doc = 'index' # List of patterns, relative to source directory, that match files and # directories to ignore when looking for source files. # This pattern also affects html_static_path and html_extra_path. exclude_patterns = ['_build', 'Thumbs.db', '.DS_Store'] # -- Options for HTML output ------------------------------------------------- # The theme to use for HTML and HTML Help pages. See the documentation for # a list of builtin themes. # html_theme = 'sphinx_rtd_theme' # Add any paths that contain custom static files (such as style sheets) here, # relative to this directory. They are copied after the builtin static files, # so a file named "default.css" will overwrite the builtin "default.css". html_static_path = ['_static'] language = 'zh_CN' def builder_inited_handler(app): subprocess.run(['./stat.py']) def setup(app): app.connect('builder-inited', builder_inited_handler)
2,775
28.849462
79
py
PseCo
PseCo-master/thirdparty/mmdetection/.dev_scripts/convert_train_benchmark_script.py
# Copyright (c) OpenMMLab. All rights reserved. import argparse import os import os.path as osp def parse_args(): parser = argparse.ArgumentParser( description='Convert benchmark model json to script') parser.add_argument( 'txt_path', type=str, help='txt path output by benchmark_filter') parser.add_argument( '--partition', type=str, default='openmmlab', help='slurm partition name') parser.add_argument( '--max-keep-ckpts', type=int, default=1, help='The maximum checkpoints to keep') parser.add_argument( '--run', action='store_true', help='run script directly') parser.add_argument( '--out', type=str, help='path to save model benchmark script') args = parser.parse_args() return args def main(): args = parse_args() if args.out: out_suffix = args.out.split('.')[-1] assert args.out.endswith('.sh'), \ f'Expected out file path suffix is .sh, but get .{out_suffix}' assert args.out or args.run, \ ('Please specify at least one operation (save/run/ the ' 'script) with the argument "--out" or "--run"') partition = args.partition # cluster name root_name = './tools' train_script_name = osp.join(root_name, 'slurm_train.sh') # stdout is no output stdout_cfg = '>/dev/null' max_keep_ckpts = args.max_keep_ckpts commands = [] with open(args.txt_path, 'r') as f: model_cfgs = f.readlines() for i, cfg in enumerate(model_cfgs): cfg = cfg.strip() if len(cfg) == 0: continue # print cfg name echo_info = f'echo \'{cfg}\' &' commands.append(echo_info) commands.append('\n') fname, _ = osp.splitext(osp.basename(cfg)) out_fname = osp.join(root_name, 'work_dir', fname) # default setting if cfg.find('16x') >= 0: command_info = f'GPUS=16 GPUS_PER_NODE=8 ' \ f'CPUS_PER_TASK=2 {train_script_name} ' elif cfg.find('gn-head_4x4_1x_coco.py') >= 0 or \ cfg.find('gn-head_4x4_2x_coco.py') >= 0: command_info = f'GPUS=4 GPUS_PER_NODE=4 ' \ f'CPUS_PER_TASK=2 {train_script_name} ' else: command_info = f'GPUS=8 GPUS_PER_NODE=8 ' \ f'CPUS_PER_TASK=2 {train_script_name} ' command_info += f'{partition} ' command_info += f'{fname} ' command_info += f'{cfg} ' command_info += f'{out_fname} ' if max_keep_ckpts: command_info += f'--cfg-options ' \ f'checkpoint_config.max_keep_ckpts=' \ f'{max_keep_ckpts}' + ' ' command_info += f'{stdout_cfg} &' commands.append(command_info) if i < len(model_cfgs): commands.append('\n') command_str = ''.join(commands) if args.out: with open(args.out, 'w') as f: f.write(command_str) if args.run: os.system(command_str) if __name__ == '__main__': main()
3,307
32.08
74
py
PseCo
PseCo-master/thirdparty/mmdetection/.dev_scripts/gather_test_benchmark_metric.py
# Copyright (c) OpenMMLab. All rights reserved. import argparse import glob import os.path as osp import mmcv from mmcv import Config def parse_args(): parser = argparse.ArgumentParser( description='Gather benchmarked models metric') parser.add_argument('config', help='test config file path') parser.add_argument( 'root', type=str, help='root path of benchmarked models to be gathered') parser.add_argument( '--out', type=str, help='output path of gathered metrics to be stored') parser.add_argument( '--not-show', action='store_true', help='not show metrics') parser.add_argument( '--show-all', action='store_true', help='show all model metrics') args = parser.parse_args() return args if __name__ == '__main__': args = parse_args() root_path = args.root metrics_out = args.out result_dict = {} cfg = Config.fromfile(args.config) for model_key in cfg: model_infos = cfg[model_key] if not isinstance(model_infos, list): model_infos = [model_infos] for model_info in model_infos: record_metrics = model_info['metric'] config = model_info['config'].strip() fname, _ = osp.splitext(osp.basename(config)) metric_json_dir = osp.join(root_path, fname) if osp.exists(metric_json_dir): json_list = glob.glob(osp.join(metric_json_dir, '*.json')) if len(json_list) > 0: log_json_path = list(sorted(json_list))[-1] metric = mmcv.load(log_json_path) if config in metric.get('config', {}): new_metrics = dict() for record_metric_key in record_metrics: record_metric_key_bk = record_metric_key old_metric = record_metrics[record_metric_key] if record_metric_key == 'AR_1000': record_metric_key = 'AR@1000' if record_metric_key not in metric['metric']: raise KeyError( 'record_metric_key not exist, please ' 'check your config') new_metric = round( metric['metric'][record_metric_key] * 100, 1) new_metrics[record_metric_key_bk] = new_metric if args.show_all: result_dict[config] = dict( before=record_metrics, after=new_metrics) else: for record_metric_key in record_metrics: old_metric = record_metrics[record_metric_key] new_metric = new_metrics[record_metric_key] if old_metric != new_metric: result_dict[config] = dict( before=record_metrics, after=new_metrics) break else: print(f'{config} not included in: {log_json_path}') else: print(f'{config} not exist file: {metric_json_dir}') else: print(f'{config} not exist dir: {metric_json_dir}') if metrics_out: mmcv.mkdir_or_exist(metrics_out) mmcv.dump(result_dict, osp.join(metrics_out, 'batch_test_metric_info.json')) if not args.not_show: print('===================================') for config_name, metrics in result_dict.items(): print(config_name, metrics) print('===================================')
3,916
39.381443
79
py
PseCo
PseCo-master/thirdparty/mmdetection/.dev_scripts/benchmark_filter.py
# Copyright (c) OpenMMLab. All rights reserved. import argparse import os import os.path as osp def parse_args(): parser = argparse.ArgumentParser(description='Filter configs to train') parser.add_argument( '--basic-arch', action='store_true', help='to train models in basic arch') parser.add_argument( '--datasets', action='store_true', help='to train models in dataset') parser.add_argument( '--data-pipeline', action='store_true', help='to train models related to data pipeline, e.g. augmentations') parser.add_argument( '--nn-module', action='store_true', help='to train models related to neural network modules') parser.add_argument( '--model-options', nargs='+', help='custom options to special model benchmark') parser.add_argument( '--out', type=str, default='batch_train_list.txt', help='output path of gathered metrics to be stored') args = parser.parse_args() return args basic_arch_root = [ 'atss', 'autoassign', 'cascade_rcnn', 'cascade_rpn', 'centripetalnet', 'cornernet', 'detectors', 'deformable_detr', 'detr', 'double_heads', 'dynamic_rcnn', 'faster_rcnn', 'fcos', 'foveabox', 'fp16', 'free_anchor', 'fsaf', 'gfl', 'ghm', 'grid_rcnn', 'guided_anchoring', 'htc', 'ld', 'libra_rcnn', 'mask_rcnn', 'ms_rcnn', 'nas_fcos', 'paa', 'pisa', 'point_rend', 'reppoints', 'retinanet', 'rpn', 'sabl', 'ssd', 'tridentnet', 'vfnet', 'yolact', 'yolo', 'sparse_rcnn', 'scnet', 'yolof', 'centernet' ] datasets_root = [ 'wider_face', 'pascal_voc', 'cityscapes', 'lvis', 'deepfashion' ] data_pipeline_root = ['albu_example', 'instaboost'] nn_module_root = [ 'carafe', 'dcn', 'empirical_attention', 'gcnet', 'gn', 'gn+ws', 'hrnet', 'pafpn', 'nas_fpn', 'regnet', 'resnest', 'res2net', 'groie' ] benchmark_pool = [ 'configs/albu_example/mask_rcnn_r50_fpn_albu_1x_coco.py', 'configs/atss/atss_r50_fpn_1x_coco.py', 'configs/autoassign/autoassign_r50_fpn_8x2_1x_coco.py', 'configs/carafe/mask_rcnn_r50_fpn_carafe_1x_coco.py', 'configs/cascade_rcnn/cascade_mask_rcnn_r50_fpn_1x_coco.py', 'configs/cascade_rpn/crpn_faster_rcnn_r50_caffe_fpn_1x_coco.py', 'configs/centernet/centernet_resnet18_dcnv2_140e_coco.py', 'configs/centripetalnet/' 'centripetalnet_hourglass104_mstest_16x6_210e_coco.py', 'configs/cityscapes/mask_rcnn_r50_fpn_1x_cityscapes.py', 'configs/cornernet/' 'cornernet_hourglass104_mstest_8x6_210e_coco.py', 'configs/dcn/mask_rcnn_r50_fpn_mdconv_c3-c5_1x_coco.py', 'configs/dcn/faster_rcnn_r50_fpn_dpool_1x_coco.py', 'configs/dcn/faster_rcnn_r50_fpn_mdpool_1x_coco.py', 'configs/dcn/mask_rcnn_r50_fpn_dconv_c3-c5_1x_coco.py', 'configs/deformable_detr/deformable_detr_r50_16x2_50e_coco.py', 'configs/detectors/detectors_htc_r50_1x_coco.py', 'configs/detr/detr_r50_8x2_150e_coco.py', 'configs/double_heads/dh_faster_rcnn_r50_fpn_1x_coco.py', 'configs/dynamic_rcnn/dynamic_rcnn_r50_fpn_1x_coco.py', 'configs/empirical_attention/faster_rcnn_r50_fpn_attention_1111_dcn_1x_coco.py', # noqa 'configs/faster_rcnn/faster_rcnn_r50_fpn_1x_coco.py', 'configs/faster_rcnn/faster_rcnn_r50_fpn_ohem_1x_coco.py', 'configs/faster_rcnn/faster_rcnn_r50_caffe_fpn_1x_coco.py', 'configs/faster_rcnn/faster_rcnn_r50_caffe_fpn_mstrain_1x_coco.py', 'configs/faster_rcnn/faster_rcnn_r50_caffe_dc5_mstrain_1x_coco.py', 'configs/fcos/fcos_center_r50_caffe_fpn_gn-head_4x4_1x_coco.py', 'configs/foveabox/fovea_align_r50_fpn_gn-head_4x4_2x_coco.py', 'configs/fp16/retinanet_r50_fpn_fp16_1x_coco.py', 'configs/fp16/mask_rcnn_r50_fpn_fp16_1x_coco.py', 'configs/free_anchor/retinanet_free_anchor_r50_fpn_1x_coco.py', 'configs/fsaf/fsaf_r50_fpn_1x_coco.py', 'configs/gcnet/mask_rcnn_r50_fpn_r4_gcb_c3-c5_1x_coco.py', 'configs/gfl/gfl_r50_fpn_1x_coco.py', 'configs/ghm/retinanet_ghm_r50_fpn_1x_coco.py', 'configs/gn/mask_rcnn_r50_fpn_gn-all_2x_coco.py', 'configs/gn+ws/mask_rcnn_r50_fpn_gn_ws-all_2x_coco.py', 'configs/grid_rcnn/grid_rcnn_r50_fpn_gn-head_2x_coco.py', 'configs/groie/faster_rcnn_r50_fpn_groie_1x_coco.py', 'configs/guided_anchoring/ga_faster_r50_caffe_fpn_1x_coco.py', 'configs/hrnet/mask_rcnn_hrnetv2p_w18_1x_coco.py', 'configs/htc/htc_r50_fpn_1x_coco.py', 'configs/instaboost/mask_rcnn_r50_fpn_instaboost_4x_coco.py', 'configs/ld/ld_r18_gflv1_r101_fpn_coco_1x.py', 'configs/libra_rcnn/libra_faster_rcnn_r50_fpn_1x_coco.py', 'configs/lvis/mask_rcnn_r50_fpn_sample1e-3_mstrain_1x_lvis_v1.py', 'configs/mask_rcnn/mask_rcnn_r50_caffe_fpn_mstrain-poly_1x_coco.py', 'configs/ms_rcnn/ms_rcnn_r50_caffe_fpn_1x_coco.py', 'configs/nas_fcos/nas_fcos_nashead_r50_caffe_fpn_gn-head_4x4_1x_coco.py', 'configs/nas_fpn/retinanet_r50_nasfpn_crop640_50e_coco.py', 'configs/paa/paa_r50_fpn_1x_coco.py', 'configs/pafpn/faster_rcnn_r50_pafpn_1x_coco.py', 'configs/pisa/pisa_mask_rcnn_r50_fpn_1x_coco.py', 'configs/point_rend/point_rend_r50_caffe_fpn_mstrain_1x_coco.py', 'configs/regnet/mask_rcnn_regnetx-3.2GF_fpn_1x_coco.py', 'configs/reppoints/reppoints_moment_r50_fpn_gn-neck+head_1x_coco.py', 'configs/res2net/faster_rcnn_r2_101_fpn_2x_coco.py', 'configs/resnest/' 'mask_rcnn_s50_fpn_syncbn-backbone+head_mstrain_1x_coco.py', 'configs/retinanet/retinanet_r50_caffe_fpn_1x_coco.py', 'configs/rpn/rpn_r50_fpn_1x_coco.py', 'configs/sabl/sabl_retinanet_r50_fpn_1x_coco.py', 'configs/ssd/ssd300_coco.py', 'configs/tridentnet/tridentnet_r50_caffe_1x_coco.py', 'configs/vfnet/vfnet_r50_fpn_1x_coco.py', 'configs/yolact/yolact_r50_1x8_coco.py', 'configs/yolo/yolov3_d53_320_273e_coco.py', 'configs/sparse_rcnn/sparse_rcnn_r50_fpn_1x_coco.py', 'configs/scnet/scnet_r50_fpn_1x_coco.py', 'configs/yolof/yolof_r50_c5_8x8_1x_coco.py', ] def main(): args = parse_args() benchmark_type = [] if args.basic_arch: benchmark_type += basic_arch_root if args.datasets: benchmark_type += datasets_root if args.data_pipeline: benchmark_type += data_pipeline_root if args.nn_module: benchmark_type += nn_module_root special_model = args.model_options if special_model is not None: benchmark_type += special_model config_dpath = 'configs/' benchmark_configs = [] for cfg_root in benchmark_type: cfg_dir = osp.join(config_dpath, cfg_root) configs = os.scandir(cfg_dir) for cfg in configs: config_path = osp.join(cfg_dir, cfg.name) if (config_path in benchmark_pool and config_path not in benchmark_configs): benchmark_configs.append(config_path) print(f'Totally found {len(benchmark_configs)} configs to benchmark') with open(args.out, 'w') as f: for config in benchmark_configs: f.write(config + '\n') if __name__ == '__main__': main()
7,096
41.244048
92
py
PseCo
PseCo-master/thirdparty/mmdetection/.dev_scripts/gather_models.py
# Copyright (c) OpenMMLab. All rights reserved. import argparse import glob import json import os.path as osp import shutil import subprocess from collections import OrderedDict import mmcv import torch import yaml def ordered_yaml_dump(data, stream=None, Dumper=yaml.SafeDumper, **kwds): class OrderedDumper(Dumper): pass def _dict_representer(dumper, data): return dumper.represent_mapping( yaml.resolver.BaseResolver.DEFAULT_MAPPING_TAG, data.items()) OrderedDumper.add_representer(OrderedDict, _dict_representer) return yaml.dump(data, stream, OrderedDumper, **kwds) def process_checkpoint(in_file, out_file): checkpoint = torch.load(in_file, map_location='cpu') # remove optimizer for smaller file size if 'optimizer' in checkpoint: del checkpoint['optimizer'] # remove ema state_dict for key in list(checkpoint['state_dict']): if key.startswith('ema_'): checkpoint['state_dict'].pop(key) # if it is necessary to remove some sensitive data in checkpoint['meta'], # add the code here. if torch.__version__ >= '1.6': torch.save(checkpoint, out_file, _use_new_zipfile_serialization=False) else: torch.save(checkpoint, out_file) sha = subprocess.check_output(['sha256sum', out_file]).decode() final_file = out_file.rstrip('.pth') + '-{}.pth'.format(sha[:8]) subprocess.Popen(['mv', out_file, final_file]) return final_file def get_final_epoch(config): cfg = mmcv.Config.fromfile('./configs/' + config) return cfg.runner.max_epochs def get_real_epoch(config): cfg = mmcv.Config.fromfile('./configs/' + config) epoch = cfg.runner.max_epochs if cfg.data.train.type == 'RepeatDataset': epoch *= cfg.data.train.times return epoch def get_final_results(log_json_path, epoch, results_lut): result_dict = dict() with open(log_json_path, 'r') as f: for line in f.readlines(): log_line = json.loads(line) if 'mode' not in log_line.keys(): continue if log_line['mode'] == 'train' and log_line['epoch'] == epoch: result_dict['memory'] = log_line['memory'] if log_line['mode'] == 'val' and log_line['epoch'] == epoch: result_dict.update({ key: log_line[key] for key in results_lut if key in log_line }) return result_dict def get_dataset_name(config): # If there are more dataset, add here. name_map = dict( CityscapesDataset='Cityscapes', CocoDataset='COCO', CocoPanopticDataset='COCO', DeepFashionDataset='Deep Fashion', LVISV05Dataset='LVIS v0.5', LVISV1Dataset='LVIS v1', VOCDataset='Pascal VOC', WIDERFaceDataset='WIDER Face') cfg = mmcv.Config.fromfile('./configs/' + config) return name_map[cfg.dataset_type] def convert_model_info_to_pwc(model_infos): pwc_files = {} for model in model_infos: cfg_folder_name = osp.split(model['config'])[-2] pwc_model_info = OrderedDict() pwc_model_info['Name'] = osp.split(model['config'])[-1].split('.')[0] pwc_model_info['In Collection'] = 'Please fill in Collection name' pwc_model_info['Config'] = osp.join('configs', model['config']) # get metadata memory = round(model['results']['memory'] / 1024, 1) epochs = get_real_epoch(model['config']) meta_data = OrderedDict() meta_data['Training Memory (GB)'] = memory meta_data['Epochs'] = epochs pwc_model_info['Metadata'] = meta_data # get dataset name dataset_name = get_dataset_name(model['config']) # get results results = [] # if there are more metrics, add here. if 'bbox_mAP' in model['results']: metric = round(model['results']['bbox_mAP'] * 100, 1) results.append( OrderedDict( Task='Object Detection', Dataset=dataset_name, Metrics={'box AP': metric})) if 'segm_mAP' in model['results']: metric = round(model['results']['segm_mAP'] * 100, 1) results.append( OrderedDict( Task='Instance Segmentation', Dataset=dataset_name, Metrics={'mask AP': metric})) if 'PQ' in model['results']: metric = round(model['results']['PQ'], 1) results.append( OrderedDict( Task='Panoptic Segmentation', Dataset=dataset_name, Metrics={'PQ': metric})) pwc_model_info['Results'] = results link_string = 'https://download.openmmlab.com/mmdetection/v2.0/' link_string += '{}/{}'.format(model['config'].rstrip('.py'), osp.split(model['model_path'])[-1]) pwc_model_info['Weights'] = link_string if cfg_folder_name in pwc_files: pwc_files[cfg_folder_name].append(pwc_model_info) else: pwc_files[cfg_folder_name] = [pwc_model_info] return pwc_files def parse_args(): parser = argparse.ArgumentParser(description='Gather benchmarked models') parser.add_argument( 'root', type=str, help='root path of benchmarked models to be gathered') parser.add_argument( 'out', type=str, help='output path of gathered models to be stored') args = parser.parse_args() return args def main(): args = parse_args() models_root = args.root models_out = args.out mmcv.mkdir_or_exist(models_out) # find all models in the root directory to be gathered raw_configs = list(mmcv.scandir('./configs', '.py', recursive=True)) # filter configs that is not trained in the experiments dir used_configs = [] for raw_config in raw_configs: if osp.exists(osp.join(models_root, raw_config)): used_configs.append(raw_config) print(f'Find {len(used_configs)} models to be gathered') # find final_ckpt and log file for trained each config # and parse the best performance model_infos = [] for used_config in used_configs: exp_dir = osp.join(models_root, used_config) # check whether the exps is finished final_epoch = get_final_epoch(used_config) final_model = 'epoch_{}.pth'.format(final_epoch) model_path = osp.join(exp_dir, final_model) # skip if the model is still training if not osp.exists(model_path): continue # get the latest logs log_json_path = list( sorted(glob.glob(osp.join(exp_dir, '*.log.json'))))[-1] log_txt_path = list(sorted(glob.glob(osp.join(exp_dir, '*.log'))))[-1] cfg = mmcv.Config.fromfile('./configs/' + used_config) results_lut = cfg.evaluation.metric if not isinstance(results_lut, list): results_lut = [results_lut] # case when using VOC, the evaluation key is only 'mAP' # when using Panoptic Dataset, the evaluation key is 'PQ'. for i, key in enumerate(results_lut): if 'mAP' not in key and 'PQ' not in key: results_lut[i] = key + 'm_AP' model_performance = get_final_results(log_json_path, final_epoch, results_lut) if model_performance is None: continue model_time = osp.split(log_txt_path)[-1].split('.')[0] model_infos.append( dict( config=used_config, results=model_performance, epochs=final_epoch, model_time=model_time, log_json_path=osp.split(log_json_path)[-1])) # publish model for each checkpoint publish_model_infos = [] for model in model_infos: model_publish_dir = osp.join(models_out, model['config'].rstrip('.py')) mmcv.mkdir_or_exist(model_publish_dir) model_name = osp.split(model['config'])[-1].split('.')[0] model_name += '_' + model['model_time'] publish_model_path = osp.join(model_publish_dir, model_name) trained_model_path = osp.join(models_root, model['config'], 'epoch_{}.pth'.format(model['epochs'])) # convert model final_model_path = process_checkpoint(trained_model_path, publish_model_path) # copy log shutil.copy( osp.join(models_root, model['config'], model['log_json_path']), osp.join(model_publish_dir, f'{model_name}.log.json')) shutil.copy( osp.join(models_root, model['config'], model['log_json_path'].rstrip('.json')), osp.join(model_publish_dir, f'{model_name}.log')) # copy config to guarantee reproducibility config_path = model['config'] config_path = osp.join( 'configs', config_path) if 'configs' not in config_path else config_path target_cconfig_path = osp.split(config_path)[-1] shutil.copy(config_path, osp.join(model_publish_dir, target_cconfig_path)) model['model_path'] = final_model_path publish_model_infos.append(model) models = dict(models=publish_model_infos) print(f'Totally gathered {len(publish_model_infos)} models') mmcv.dump(models, osp.join(models_out, 'model_info.json')) pwc_files = convert_model_info_to_pwc(publish_model_infos) for name in pwc_files: with open(osp.join(models_out, name + '_metafile.yml'), 'w') as f: ordered_yaml_dump(pwc_files[name], f, encoding='utf-8') if __name__ == '__main__': main()
9,899
34.869565
79
py
PseCo
PseCo-master/thirdparty/mmdetection/.dev_scripts/test_init_backbone.py
# Copyright (c) OpenMMLab. All rights reserved. """Check out backbone whether successfully load pretrained checkpoint.""" import copy import os from os.path import dirname, exists, join import pytest from mmcv import Config, ProgressBar from mmcv.runner import _load_checkpoint from mmdet.models import build_detector def _get_config_directory(): """Find the predefined detector config directory.""" try: # Assume we are running in the source mmdetection repo repo_dpath = dirname(dirname(__file__)) except NameError: # For IPython development when this __file__ is not defined import mmdet repo_dpath = dirname(dirname(mmdet.__file__)) config_dpath = join(repo_dpath, 'configs') if not exists(config_dpath): raise Exception('Cannot find config path') return config_dpath def _get_config_module(fname): """Load a configuration as a python module.""" from mmcv import Config config_dpath = _get_config_directory() config_fpath = join(config_dpath, fname) config_mod = Config.fromfile(config_fpath) return config_mod def _get_detector_cfg(fname): """Grab configs necessary to create a detector. These are deep copied to allow for safe modification of parameters without influencing other tests. """ config = _get_config_module(fname) model = copy.deepcopy(config.model) return model def _traversed_config_file(): """We traversed all potential config files under the `config` file. If you need to print details or debug code, you can use this function. If the `backbone.init_cfg` is None (do not use `Pretrained` init way), you need add the folder name in `ignores_folder` (if the config files in this folder all set backbone.init_cfg is None) or add config name in `ignores_file` (if the config file set backbone.init_cfg is None) """ config_path = _get_config_directory() check_cfg_names = [] # `base`, `legacy_1.x` and `common` ignored by default. ignores_folder = ['_base_', 'legacy_1.x', 'common'] # 'ld' need load teacher model, if want to check 'ld', # please check teacher_config path first. ignores_folder += ['ld'] # `selfsup_pretrain` need convert model, if want to check this model, # need to convert the model first. ignores_folder += ['selfsup_pretrain'] # the `init_cfg` in 'centripetalnet', 'cornernet', 'cityscapes', # 'scratch' is None. # the `init_cfg` in ssdlite(`ssdlite_mobilenetv2_scratch_600e_coco.py`) # is None # Please confirm `bockbone.init_cfg` is None first. ignores_folder += ['centripetalnet', 'cornernet', 'cityscapes', 'scratch'] ignores_file = ['ssdlite_mobilenetv2_scratch_600e_coco.py'] for config_file_name in os.listdir(config_path): if config_file_name not in ignores_folder: config_file = join(config_path, config_file_name) if os.path.isdir(config_file): for config_sub_file in os.listdir(config_file): if config_sub_file.endswith('py') and \ config_sub_file not in ignores_file: name = join(config_file, config_sub_file) check_cfg_names.append(name) return check_cfg_names def _check_backbone(config, print_cfg=True): """Check out backbone whether successfully load pretrained model, by using `backbone.init_cfg`. First, using `mmcv._load_checkpoint` to load the checkpoint without loading models. Then, using `build_detector` to build models, and using `model.init_weights()` to initialize the parameters. Finally, assert weights and bias of each layer loaded from pretrained checkpoint are equal to the weights and bias of original checkpoint. For the convenience of comparison, we sum up weights and bias of each loaded layer separately. Args: config (str): Config file path. print_cfg (bool): Whether print logger and return the result. Returns: results (str or None): If backbone successfully load pretrained checkpoint, return None; else, return config file path. """ if print_cfg: print('-' * 15 + 'loading ', config) cfg = Config.fromfile(config) init_cfg = None try: init_cfg = cfg.model.backbone.init_cfg init_flag = True except AttributeError: init_flag = False if init_cfg is None or init_cfg.get('type') != 'Pretrained': init_flag = False if init_flag: checkpoint = _load_checkpoint(init_cfg.checkpoint) if 'state_dict' in checkpoint: state_dict = checkpoint['state_dict'] else: state_dict = checkpoint model = build_detector( cfg.model, train_cfg=cfg.get('train_cfg'), test_cfg=cfg.get('test_cfg')) model.init_weights() checkpoint_layers = state_dict.keys() for name, value in model.backbone.state_dict().items(): if name in checkpoint_layers: assert value.equal(state_dict[name]) if print_cfg: print('-' * 10 + 'Successfully load checkpoint' + '-' * 10 + '\n', ) return None else: if print_cfg: print(config + '\n' + '-' * 10 + 'config file do not have init_cfg' + '-' * 10 + '\n') return config @pytest.mark.parametrize('config', _traversed_config_file()) def test_load_pretrained(config): """Check out backbone whether successfully load pretrained model by using `backbone.init_cfg`. Details please refer to `_check_backbone` """ _check_backbone(config, print_cfg=False) def _test_load_pretrained(): """We traversed all potential config files under the `config` file. If you need to print details or debug code, you can use this function. Returns: check_cfg_names (list[str]): Config files that backbone initialized from pretrained checkpoint might be problematic. Need to recheck the config file. The output including the config files that the backbone.init_cfg is None """ check_cfg_names = _traversed_config_file() need_check_cfg = [] prog_bar = ProgressBar(len(check_cfg_names)) for config in check_cfg_names: init_cfg_name = _check_backbone(config) if init_cfg_name is not None: need_check_cfg.append(init_cfg_name) prog_bar.update() print('These config files need to be checked again') print(need_check_cfg)
6,625
35.406593
78
py
PseCo
PseCo-master/thirdparty/mmdetection/.dev_scripts/benchmark_inference_fps.py
# Copyright (c) OpenMMLab. All rights reserved. import argparse import os import os.path as osp import mmcv from mmcv import Config, DictAction from mmcv.runner import init_dist from tools.analysis_tools.benchmark import measure_inferense_speed def parse_args(): parser = argparse.ArgumentParser( description='MMDet benchmark a model of FPS') parser.add_argument('config', help='test config file path') parser.add_argument('checkpoint_root', help='Checkpoint file root path') parser.add_argument( '--round-num', type=int, default=1, help='round a number to a given precision in decimal digits') parser.add_argument( '--out', type=str, help='output path of gathered fps to be stored') parser.add_argument( '--max-iter', type=int, default=400, help='num of max iter') parser.add_argument( '--log-interval', type=int, default=40, help='interval of logging') parser.add_argument( '--fuse-conv-bn', action='store_true', help='Whether to fuse conv and bn, this will slightly increase' 'the inference speed') parser.add_argument( '--cfg-options', nargs='+', action=DictAction, help='override some settings in the used config, the key-value pair ' 'in xxx=yyy format will be merged into config file. If the value to ' 'be overwritten is a list, it should be like key="[a,b]" or key=a,b ' 'It also allows nested list/tuple values, e.g. key="[(a,b),(c,d)]" ' 'Note that the quotation marks are necessary and that no white space ' 'is allowed.') parser.add_argument( '--launcher', choices=['none', 'pytorch', 'slurm', 'mpi'], default='none', help='job launcher') parser.add_argument('--local_rank', type=int, default=0) args = parser.parse_args() if 'LOCAL_RANK' not in os.environ: os.environ['LOCAL_RANK'] = str(args.local_rank) return args if __name__ == '__main__': args = parse_args() assert args.round_num >= 0 config = Config.fromfile(args.config) if args.launcher == 'none': raise NotImplementedError('Only supports distributed mode') else: init_dist(args.launcher) result_dict = {} for model_key in config: model_infos = config[model_key] if not isinstance(model_infos, list): model_infos = [model_infos] for model_info in model_infos: record_metrics = model_info['metric'] cfg_path = model_info['config'].strip() cfg = Config.fromfile(cfg_path) checkpoint = osp.join(args.checkpoint_root, model_info['checkpoint'].strip()) try: fps = measure_inferense_speed(cfg, checkpoint, args.max_iter, args.log_interval, args.fuse_conv_bn) print( f'{cfg_path} fps : {fps:.{args.round_num}f} img / s, ' f'times per image: {1000/fps:.{args.round_num}f} ms / img', flush=True) result_dict[cfg_path] = dict( fps=round(fps, args.round_num), ms_times_pre_image=round(1000 / fps, args.round_num)) except Exception as e: print(f'{config} error: {repr(e)}') result_dict[cfg_path] = 0 if args.out: mmcv.mkdir_or_exist(args.out) mmcv.dump(result_dict, osp.join(args.out, 'batch_inference_fps.json'))
3,626
37.178947
79
py
PseCo
PseCo-master/thirdparty/mmdetection/.dev_scripts/gather_train_benchmark_metric.py
# Copyright (c) OpenMMLab. All rights reserved. import argparse import glob import os.path as osp import mmcv from gather_models import get_final_results try: import xlrd except ImportError: xlrd = None try: import xlutils from xlutils.copy import copy except ImportError: xlutils = None def parse_args(): parser = argparse.ArgumentParser( description='Gather benchmarked models metric') parser.add_argument( 'root', type=str, help='root path of benchmarked models to be gathered') parser.add_argument( 'txt_path', type=str, help='txt path output by benchmark_filter') parser.add_argument( '--out', type=str, help='output path of gathered metrics to be stored') parser.add_argument( '--not-show', action='store_true', help='not show metrics') parser.add_argument( '--excel', type=str, help='input path of excel to be recorded') parser.add_argument( '--ncol', type=int, help='Number of column to be modified or appended') args = parser.parse_args() return args if __name__ == '__main__': args = parse_args() if args.excel: assert args.ncol, 'Please specify "--excel" and "--ncol" ' \ 'at the same time' if xlrd is None: raise RuntimeError( 'xlrd is not installed,' 'Please use “pip install xlrd==1.2.0” to install') if xlutils is None: raise RuntimeError( 'xlutils is not installed,' 'Please use “pip install xlutils==2.0.0” to install') readbook = xlrd.open_workbook(args.excel) sheet = readbook.sheet_by_name('Sheet1') sheet_info = {} total_nrows = sheet.nrows for i in range(3, sheet.nrows): sheet_info[sheet.row_values(i)[0]] = i xlrw = copy(readbook) table = xlrw.get_sheet(0) root_path = args.root metrics_out = args.out result_dict = {} with open(args.txt_path, 'r') as f: model_cfgs = f.readlines() for i, config in enumerate(model_cfgs): config = config.strip() if len(config) == 0: continue config_name = osp.split(config)[-1] config_name = osp.splitext(config_name)[0] result_path = osp.join(root_path, config_name) if osp.exists(result_path): # 1 read config cfg = mmcv.Config.fromfile(config) total_epochs = cfg.runner.max_epochs final_results = cfg.evaluation.metric if not isinstance(final_results, list): final_results = [final_results] final_results_out = [] for key in final_results: if 'proposal_fast' in key: final_results_out.append('AR@1000') # RPN elif 'mAP' not in key: final_results_out.append(key + '_mAP') # 2 determine whether total_epochs ckpt exists ckpt_path = f'epoch_{total_epochs}.pth' if osp.exists(osp.join(result_path, ckpt_path)): log_json_path = list( sorted(glob.glob(osp.join(result_path, '*.log.json'))))[-1] # 3 read metric model_performance = get_final_results( log_json_path, total_epochs, final_results_out) if model_performance is None: print(f'log file error: {log_json_path}') continue for performance in model_performance: if performance in ['AR@1000', 'bbox_mAP', 'segm_mAP']: metric = round( model_performance[performance] * 100, 1) model_performance[performance] = metric result_dict[config] = model_performance # update and append excel content if args.excel: if 'AR@1000' in model_performance: metrics = f'{model_performance["AR@1000"]}' \ f'(AR@1000)' elif 'segm_mAP' in model_performance: metrics = f'{model_performance["bbox_mAP"]}/' \ f'{model_performance["segm_mAP"]}' else: metrics = f'{model_performance["bbox_mAP"]}' row_num = sheet_info.get(config, None) if row_num: table.write(row_num, args.ncol, metrics) else: table.write(total_nrows, 0, config) table.write(total_nrows, args.ncol, metrics) total_nrows += 1 else: print(f'{config} not exist: {ckpt_path}') else: print(f'not exist: {config}') # 4 save or print results if metrics_out: mmcv.mkdir_or_exist(metrics_out) mmcv.dump(result_dict, osp.join(metrics_out, 'model_metric_info.json')) if not args.not_show: print('===================================') for config_name, metrics in result_dict.items(): print(config_name, metrics) print('===================================') if args.excel: filename, sufflx = osp.splitext(args.excel) xlrw.save(f'{filename}_o{sufflx}') print(f'>>> Output {filename}_o{sufflx}')
5,843
37.701987
79
py
PseCo
PseCo-master/thirdparty/mmdetection/.dev_scripts/batch_test_list.py
# Copyright (c) OpenMMLab. All rights reserved. # yapf: disable atss = dict( config='configs/atss/atss_r50_fpn_1x_coco.py', checkpoint='atss_r50_fpn_1x_coco_20200209-985f7bd0.pth', eval='bbox', metric=dict(bbox_mAP=39.4), ) autoassign = dict( config='configs/autoassign/autoassign_r50_fpn_8x2_1x_coco.py', checkpoint='auto_assign_r50_fpn_1x_coco_20210413_115540-5e17991f.pth', eval='bbox', metric=dict(bbox_mAP=40.4), ) carafe = dict( config='configs/carafe/faster_rcnn_r50_fpn_carafe_1x_coco.py', checkpoint='faster_rcnn_r50_fpn_carafe_1x_coco_bbox_mAP-0.386_20200504_175733-385a75b7.pth', # noqa eval='bbox', metric=dict(bbox_mAP=38.6), ) cascade_rcnn = [ dict( config='configs/cascade_rcnn/cascade_rcnn_r50_fpn_1x_coco.py', checkpoint='cascade_rcnn_r50_fpn_1x_coco_20200316-3dc56deb.pth', eval='bbox', metric=dict(bbox_mAP=40.3), ), dict( config='configs/cascade_rcnn/cascade_mask_rcnn_r50_fpn_1x_coco.py', checkpoint='cascade_mask_rcnn_r50_fpn_1x_coco_20200203-9d4dcb24.pth', eval=['bbox', 'segm'], metric=dict(bbox_mAP=41.2, segm_mAP=35.9), ), ] cascade_rpn = dict( config='configs/cascade_rpn/crpn_faster_rcnn_r50_caffe_fpn_1x_coco.py', checkpoint='crpn_faster_rcnn_r50_caffe_fpn_1x_coco-c8283cca.pth', eval='bbox', metric=dict(bbox_mAP=40.4), ) centripetalnet = dict( config='configs/centripetalnet/centripetalnet_hourglass104_mstest_16x6_210e_coco.py', # noqa checkpoint='centripetalnet_hourglass104_mstest_16x6_210e_coco_20200915_204804-3ccc61e5.pth', # noqa eval='bbox', metric=dict(bbox_mAP=44.7), ) cornernet = dict( config='configs/cornernet/cornernet_hourglass104_mstest_8x6_210e_coco.py', checkpoint='cornernet_hourglass104_mstest_8x6_210e_coco_20200825_150618-79b44c30.pth', # noqa eval='bbox', metric=dict(bbox_mAP=41.2), ) dcn = dict( config='configs/dcn/faster_rcnn_r50_fpn_dconv_c3-c5_1x_coco.py', checkpoint='faster_rcnn_r50_fpn_dconv_c3-c5_1x_coco_20200130-d68aed1e.pth', eval='bbox', metric=dict(bbox_mAP=41.3), ) deformable_detr = dict( config='configs/deformable_detr/deformable_detr_r50_16x2_50e_coco.py', checkpoint='deformable_detr_r50_16x2_50e_coco_20210419_220030-a12b9512.pth', # noqa eval='bbox', metric=dict(bbox_mAP=44.5), ) detectors = dict( config='configs/detectors/detectors_htc_r50_1x_coco.py', checkpoint='detectors_htc_r50_1x_coco-329b1453.pth', eval=['bbox', 'segm'], metric=dict(bbox_mAP=49.1, segm_mAP=42.6), ) detr = dict( config='configs/detr/detr_r50_8x2_150e_coco.py', checkpoint='detr_r50_8x2_150e_coco_20201130_194835-2c4b8974.pth', eval='bbox', metric=dict(bbox_mAP=40.1), ) double_heads = dict( config='configs/double_heads/dh_faster_rcnn_r50_fpn_1x_coco.py', checkpoint='dh_faster_rcnn_r50_fpn_1x_coco_20200130-586b67df.pth', eval='bbox', metric=dict(bbox_mAP=40.0), ) dynamic_rcnn = dict( config='configs/dynamic_rcnn/dynamic_rcnn_r50_fpn_1x_coco.py', checkpoint='dynamic_rcnn_r50_fpn_1x-62a3f276.pth', eval='bbox', metric=dict(bbox_mAP=38.9), ) empirical_attention = dict( config='configs/empirical_attention/faster_rcnn_r50_fpn_attention_1111_1x_coco.py', # noqa checkpoint='faster_rcnn_r50_fpn_attention_1111_1x_coco_20200130-403cccba.pth', # noqa eval='bbox', metric=dict(bbox_mAP=40.0), ) faster_rcnn = dict( config='configs/faster_rcnn/faster_rcnn_r50_fpn_1x_coco.py', checkpoint='faster_rcnn_r50_fpn_1x_coco_20200130-047c8118.pth', eval='bbox', metric=dict(bbox_mAP=37.4), ) fcos = dict( config='configs/fcos/fcos_center-normbbox-centeronreg-giou_r50_caffe_fpn_gn-head_1x_coco.py', # noqa checkpoint='fcos_center-normbbox-centeronreg-giou_r50_caffe_fpn_gn-head_1x_coco-0a0d75a8.pth', # noqa eval='bbox', metric=dict(bbox_mAP=38.7), ) foveabox = dict( config='configs/foveabox/fovea_align_r50_fpn_gn-head_4x4_2x_coco.py', checkpoint='fovea_align_r50_fpn_gn-head_4x4_2x_coco_20200203-8987880d.pth', eval='bbox', metric=dict(bbox_mAP=37.9), ) free_anchor = dict( config='configs/free_anchor/retinanet_free_anchor_r50_fpn_1x_coco.py', checkpoint='retinanet_free_anchor_r50_fpn_1x_coco_20200130-0f67375f.pth', eval='bbox', metric=dict(bbox_mAP=38.7), ) fsaf = dict( config='configs/fsaf/fsaf_r50_fpn_1x_coco.py', checkpoint='fsaf_r50_fpn_1x_coco-94ccc51f.pth', eval='bbox', metric=dict(bbox_mAP=37.4), ) gcnet = dict( config='configs/gcnet/mask_rcnn_r50_fpn_syncbn-backbone_r16_gcb_c3-c5_1x_coco.py', # noqa checkpoint='mask_rcnn_r50_fpn_syncbn-backbone_r16_gcb_c3-c5_1x_coco_20200202-587b99aa.pth', # noqa eval=['bbox', 'segm'], metric=dict(bbox_mAP=40.4, segm_mAP=36.2), ) gfl = dict( config='configs/gfl/gfl_r50_fpn_1x_coco.py', checkpoint='gfl_r50_fpn_1x_coco_20200629_121244-25944287.pth', eval='bbox', metric=dict(bbox_mAP=40.2), ) gn = dict( config='configs/gn/mask_rcnn_r50_fpn_gn-all_2x_coco.py', checkpoint='mask_rcnn_r50_fpn_gn-all_2x_coco_20200206-8eee02a6.pth', eval=['bbox', 'segm'], metric=dict(bbox_mAP=40.1, segm_mAP=36.4), ) gn_ws = dict( config='configs/gn+ws/faster_rcnn_r50_fpn_gn_ws-all_1x_coco.py', checkpoint='faster_rcnn_r50_fpn_gn_ws-all_1x_coco_20200130-613d9fe2.pth', eval='bbox', metric=dict(bbox_mAP=39.7), ) grid_rcnn = dict( config='configs/grid_rcnn/grid_rcnn_r50_fpn_gn-head_2x_coco.py', checkpoint='grid_rcnn_r50_fpn_gn-head_2x_coco_20200130-6cca8223.pth', eval='bbox', metric=dict(bbox_mAP=40.4), ) groie = dict( config='configs/groie/faster_rcnn_r50_fpn_groie_1x_coco.py', checkpoint='faster_rcnn_r50_fpn_groie_1x_coco_20200604_211715-66ee9516.pth', # noqa eval='bbox', metric=dict(bbox_mAP=38.3), ) guided_anchoring = [ dict( config='configs/guided_anchoring/ga_retinanet_r50_caffe_fpn_1x_coco.py', # noqa checkpoint='ga_retinanet_r50_caffe_fpn_1x_coco_20201020-39581c6f.pth', eval='bbox', metric=dict(bbox_mAP=36.9), ), dict( config='configs/guided_anchoring/ga_faster_r50_caffe_fpn_1x_coco.py', checkpoint='ga_faster_r50_caffe_fpn_1x_coco_20200702_000718-a11ccfe6.pth', # noqa eval='bbox', metric=dict(bbox_mAP=39.6), ), ] hrnet = dict( config='configs/hrnet/faster_rcnn_hrnetv2p_w18_1x_coco.py', checkpoint='faster_rcnn_hrnetv2p_w18_1x_coco_20200130-56651a6d.pth', eval='bbox', metric=dict(bbox_mAP=36.9), ) htc = dict( config='configs/htc/htc_r50_fpn_1x_coco.py', checkpoint='htc_r50_fpn_1x_coco_20200317-7332cf16.pth', eval=['bbox', 'segm'], metric=dict(bbox_mAP=42.3, segm_mAP=37.4), ) libra_rcnn = dict( config='configs/libra_rcnn/libra_faster_rcnn_r50_fpn_1x_coco.py', checkpoint='libra_faster_rcnn_r50_fpn_1x_coco_20200130-3afee3a9.pth', eval='bbox', metric=dict(bbox_mAP=38.3), ) mask_rcnn = dict( config='configs/mask_rcnn/mask_rcnn_r50_fpn_1x_coco.py', checkpoint='mask_rcnn_r50_fpn_1x_coco_20200205-d4b0c5d6.pth', eval=['bbox', 'segm'], metric=dict(bbox_mAP=38.2, segm_mAP=34.7), ) ms_rcnn = dict( config='configs/ms_rcnn/ms_rcnn_r50_caffe_fpn_1x_coco.py', checkpoint='ms_rcnn_r50_caffe_fpn_1x_coco_20200702_180848-61c9355e.pth', eval=['bbox', 'segm'], metric=dict(bbox_mAP=38.2, segm_mAP=36.0), ) nas_fcos = dict( config='configs/nas_fcos/nas_fcos_nashead_r50_caffe_fpn_gn-head_4x4_1x_coco.py', # noqa checkpoint='nas_fcos_nashead_r50_caffe_fpn_gn-head_4x4_1x_coco_20200520-1bdba3ce.pth', # noqa eval='bbox', metric=dict(bbox_mAP=39.4), ) nas_fpn = dict( config='configs/nas_fpn/retinanet_r50_nasfpn_crop640_50e_coco.py', checkpoint='retinanet_r50_nasfpn_crop640_50e_coco-0ad1f644.pth', eval='bbox', metric=dict(bbox_mAP=40.5), ) paa = dict( config='configs/paa/paa_r50_fpn_1x_coco.py', checkpoint='paa_r50_fpn_1x_coco_20200821-936edec3.pth', eval='bbox', metric=dict(bbox_mAP=40.4), ) pafpn = dict( config='configs/pafpn/faster_rcnn_r50_pafpn_1x_coco.py', checkpoint='faster_rcnn_r50_pafpn_1x_coco_bbox_mAP-0.375_20200503_105836-b7b4b9bd.pth', # noqa eval='bbox', metric=dict(bbox_mAP=37.5), ) pisa = dict( config='configs/pisa/pisa_faster_rcnn_r50_fpn_1x_coco.py', checkpoint='pisa_faster_rcnn_r50_fpn_1x_coco-dea93523.pth', eval='bbox', metric=dict(bbox_mAP=38.4), ) point_rend = dict( config='configs/point_rend/point_rend_r50_caffe_fpn_mstrain_1x_coco.py', checkpoint='point_rend_r50_caffe_fpn_mstrain_1x_coco-1bcb5fb4.pth', eval=['bbox', 'segm'], metric=dict(bbox_mAP=38.4, segm_mAP=36.3), ) regnet = dict( config='configs/regnet/mask_rcnn_regnetx-3.2GF_fpn_1x_coco.py', checkpoint='mask_rcnn_regnetx-3.2GF_fpn_1x_coco_20200520_163141-2a9d1814.pth', # noqa eval=['bbox', 'segm'], metric=dict(bbox_mAP=40.4, segm_mAP=36.7), ) reppoints = dict( config='configs/reppoints/reppoints_moment_r50_fpn_1x_coco.py', checkpoint='reppoints_moment_r50_fpn_1x_coco_20200330-b73db8d1.pth', eval='bbox', metric=dict(bbox_mAP=37.0), ) res2net = dict( config='configs/res2net/faster_rcnn_r2_101_fpn_2x_coco.py', checkpoint='faster_rcnn_r2_101_fpn_2x_coco-175f1da6.pth', eval='bbox', metric=dict(bbox_mAP=43.0), ) resnest = dict( config='configs/resnest/faster_rcnn_s50_fpn_syncbn-backbone+head_mstrain-range_1x_coco.py', # noqa checkpoint='faster_rcnn_s50_fpn_syncbn-backbone+head_mstrain-range_1x_coco_20200926_125502-20289c16.pth', # noqa eval='bbox', metric=dict(bbox_mAP=42.0), ) retinanet = dict( config='configs/retinanet/retinanet_r50_fpn_1x_coco.py', checkpoint='retinanet_r50_fpn_1x_coco_20200130-c2398f9e.pth', eval='bbox', metric=dict(bbox_mAP=36.5), ) rpn = dict( config='configs/rpn/rpn_r50_fpn_1x_coco.py', checkpoint='rpn_r50_fpn_1x_coco_20200218-5525fa2e.pth', eval='proposal_fast', metric=dict(AR_1000=58.2), ) sabl = [ dict( config='configs/sabl/sabl_retinanet_r50_fpn_1x_coco.py', checkpoint='sabl_retinanet_r50_fpn_1x_coco-6c54fd4f.pth', eval='bbox', metric=dict(bbox_mAP=37.7), ), dict( config='configs/sabl/sabl_faster_rcnn_r50_fpn_1x_coco.py', checkpoint='sabl_faster_rcnn_r50_fpn_1x_coco-e867595b.pth', eval='bbox', metric=dict(bbox_mAP=39.9), ), ] scnet = dict( config='configs/scnet/scnet_r50_fpn_1x_coco.py', checkpoint='scnet_r50_fpn_1x_coco-c3f09857.pth', eval='bbox', metric=dict(bbox_mAP=43.5), ) sparse_rcnn = dict( config='configs/sparse_rcnn/sparse_rcnn_r50_fpn_1x_coco.py', checkpoint='sparse_rcnn_r50_fpn_1x_coco_20201222_214453-dc79b137.pth', eval='bbox', metric=dict(bbox_mAP=37.9), ) ssd = [ dict( config='configs/ssd/ssd300_coco.py', checkpoint='ssd300_coco_20210803_015428-d231a06e.pth', eval='bbox', metric=dict(bbox_mAP=25.5), ), dict( config='configs/ssd/ssdlite_mobilenetv2_scratch_600e_coco.py', checkpoint='ssdlite_mobilenetv2_scratch_600e_coco_20210629_110627-974d9307.pth',# noqa eval='bbox', metric=dict(bbox_mAP=21.3), ), ] tridentnet = dict( config='configs/tridentnet/tridentnet_r50_caffe_1x_coco.py', checkpoint='tridentnet_r50_caffe_1x_coco_20201230_141838-2ec0b530.pth', eval='bbox', metric=dict(bbox_mAP=37.6), ) vfnet = dict( config='configs/vfnet/vfnet_r50_fpn_1x_coco.py', checkpoint='vfnet_r50_fpn_1x_coco_20201027-38db6f58.pth', eval='bbox', metric=dict(bbox_mAP=41.6), ) yolact = dict( config='configs/yolact/yolact_r50_1x8_coco.py', checkpoint='yolact_r50_1x8_coco_20200908-f38d58df.pth', eval=['bbox', 'segm'], metric=dict(bbox_mAP=31.2, segm_mAP=29.0), ) yolo = dict( config='configs/yolo/yolov3_d53_320_273e_coco.py', checkpoint='yolov3_d53_320_273e_coco-421362b6.pth', eval='bbox', metric=dict(bbox_mAP=27.9), ) yolof = dict( config='configs/yolof/yolof_r50_c5_8x8_1x_coco.py', checkpoint='yolof_r50_c5_8x8_1x_coco_20210425_024427-8e864411.pth', eval='bbox', metric=dict(bbox_mAP=37.5), ) centernet = dict( config='configs/centernet/centernet_resnet18_dcnv2_140e_coco.py', checkpoint='centernet_resnet18_dcnv2_140e_coco_20210702_155131-c8cd631f.pth', # noqa eval='bbox', metric=dict(bbox_mAP=29.5), ) yolox = dict( config='configs/yolox/yolox_tiny_8x8_300e_coco.py', checkpoint='yolox_tiny_8x8_300e_coco_20210806_234250-4ff3b67e.pth', # noqa eval='bbox', metric=dict(bbox_mAP=31.5), ) # yapf: enable
12,707
34.3
117
py
PseCo
PseCo-master/thirdparty/mmdetection/.dev_scripts/benchmark_test_image.py
# Copyright (c) OpenMMLab. All rights reserved. import logging import os.path as osp from argparse import ArgumentParser from mmcv import Config from mmdet.apis import inference_detector, init_detector, show_result_pyplot from mmdet.utils import get_root_logger def parse_args(): parser = ArgumentParser() parser.add_argument('config', help='test config file path') parser.add_argument('checkpoint_root', help='Checkpoint file root path') parser.add_argument('--img', default='demo/demo.jpg', help='Image file') parser.add_argument('--aug', action='store_true', help='aug test') parser.add_argument('--model-name', help='model name to inference') parser.add_argument('--show', action='store_true', help='show results') parser.add_argument( '--wait-time', type=float, default=1, help='the interval of show (s), 0 is block') parser.add_argument( '--device', default='cuda:0', help='Device used for inference') parser.add_argument( '--score-thr', type=float, default=0.3, help='bbox score threshold') args = parser.parse_args() return args def inference_model(config_name, checkpoint, args, logger=None): cfg = Config.fromfile(config_name) if args.aug: if 'flip' in cfg.data.test.pipeline[1]: cfg.data.test.pipeline[1].flip = True else: if logger is not None: logger.error(f'{config_name}: unable to start aug test') else: print(f'{config_name}: unable to start aug test', flush=True) model = init_detector(cfg, checkpoint, device=args.device) # test a single image result = inference_detector(model, args.img) # show the results if args.show: show_result_pyplot( model, args.img, result, score_thr=args.score_thr, wait_time=args.wait_time) return result # Sample test whether the inference code is correct def main(args): config = Config.fromfile(args.config) # test single model if args.model_name: if args.model_name in config: model_infos = config[args.model_name] if not isinstance(model_infos, list): model_infos = [model_infos] model_info = model_infos[0] config_name = model_info['config'].strip() print(f'processing: {config_name}', flush=True) checkpoint = osp.join(args.checkpoint_root, model_info['checkpoint'].strip()) # build the model from a config file and a checkpoint file inference_model(config_name, checkpoint, args) return else: raise RuntimeError('model name input error.') # test all model logger = get_root_logger( log_file='benchmark_test_image.log', log_level=logging.ERROR) for model_key in config: model_infos = config[model_key] if not isinstance(model_infos, list): model_infos = [model_infos] for model_info in model_infos: print('processing: ', model_info['config'], flush=True) config_name = model_info['config'].strip() checkpoint = osp.join(args.checkpoint_root, model_info['checkpoint'].strip()) try: # build the model from a config file and a checkpoint file inference_model(config_name, checkpoint, args, logger) except Exception as e: logger.error(f'{config_name} " : {repr(e)}') if __name__ == '__main__': args = parse_args() main(args)
3,674
34.679612
77
py
PseCo
PseCo-master/thirdparty/mmdetection/.dev_scripts/convert_test_benchmark_script.py
# Copyright (c) OpenMMLab. All rights reserved. import argparse import os import os.path as osp from mmcv import Config def parse_args(): parser = argparse.ArgumentParser( description='Convert benchmark model list to script') parser.add_argument('config', help='test config file path') parser.add_argument('--port', type=int, default=29666, help='dist port') parser.add_argument( '--work-dir', default='tools/batch_test', help='the dir to save metric') parser.add_argument( '--run', action='store_true', help='run script directly') parser.add_argument( '--out', type=str, help='path to save model benchmark script') args = parser.parse_args() return args def process_model_info(model_info, work_dir): config = model_info['config'].strip() fname, _ = osp.splitext(osp.basename(config)) job_name = fname work_dir = osp.join(work_dir, fname) checkpoint = model_info['checkpoint'].strip() if not isinstance(model_info['eval'], list): evals = [model_info['eval']] else: evals = model_info['eval'] eval = ' '.join(evals) return dict( config=config, job_name=job_name, work_dir=work_dir, checkpoint=checkpoint, eval=eval) def create_test_bash_info(commands, model_test_dict, port, script_name, partition): config = model_test_dict['config'] job_name = model_test_dict['job_name'] checkpoint = model_test_dict['checkpoint'] work_dir = model_test_dict['work_dir'] eval = model_test_dict['eval'] echo_info = f' \necho \'{config}\' &' commands.append(echo_info) commands.append('\n') command_info = f'GPUS=8 GPUS_PER_NODE=8 ' \ f'CPUS_PER_TASK=2 {script_name} ' command_info += f'{partition} ' command_info += f'{job_name} ' command_info += f'{config} ' command_info += f'$CHECKPOINT_DIR/{checkpoint} ' command_info += f'--work-dir {work_dir} ' command_info += f'--eval {eval} ' command_info += f'--cfg-option dist_params.port={port} ' command_info += ' &' commands.append(command_info) def main(): args = parse_args() if args.out: out_suffix = args.out.split('.')[-1] assert args.out.endswith('.sh'), \ f'Expected out file path suffix is .sh, but get .{out_suffix}' assert args.out or args.run, \ ('Please specify at least one operation (save/run/ the ' 'script) with the argument "--out" or "--run"') commands = [] partition_name = 'PARTITION=$1 ' commands.append(partition_name) commands.append('\n') checkpoint_root = 'CHECKPOINT_DIR=$2 ' commands.append(checkpoint_root) commands.append('\n') script_name = osp.join('tools', 'slurm_test.sh') port = args.port work_dir = args.work_dir cfg = Config.fromfile(args.config) for model_key in cfg: model_infos = cfg[model_key] if not isinstance(model_infos, list): model_infos = [model_infos] for model_info in model_infos: print('processing: ', model_info['config']) model_test_dict = process_model_info(model_info, work_dir) create_test_bash_info(commands, model_test_dict, port, script_name, '$PARTITION') port += 1 command_str = ''.join(commands) if args.out: with open(args.out, 'w') as f: f.write(command_str) if args.run: os.system(command_str) if __name__ == '__main__': main()
3,604
29.041667
79
py
PseCo
PseCo-master/thirdparty/mmdetection/demo/video_demo.py
# Copyright (c) OpenMMLab. All rights reserved. import argparse import cv2 import mmcv from mmdet.apis import inference_detector, init_detector def parse_args(): parser = argparse.ArgumentParser(description='MMDetection video demo') parser.add_argument('video', help='Video file') parser.add_argument('config', help='Config file') parser.add_argument('checkpoint', help='Checkpoint file') parser.add_argument( '--device', default='cuda:0', help='Device used for inference') parser.add_argument( '--score-thr', type=float, default=0.3, help='Bbox score threshold') parser.add_argument('--out', type=str, help='Output video file') parser.add_argument('--show', action='store_true', help='Show video') parser.add_argument( '--wait-time', type=float, default=1, help='The interval of show (s), 0 is block') args = parser.parse_args() return args def main(): args = parse_args() assert args.out or args.show, \ ('Please specify at least one operation (save/show the ' 'video) with the argument "--out" or "--show"') model = init_detector(args.config, args.checkpoint, device=args.device) video_reader = mmcv.VideoReader(args.video) video_writer = None if args.out: fourcc = cv2.VideoWriter_fourcc(*'mp4v') video_writer = cv2.VideoWriter( args.out, fourcc, video_reader.fps, (video_reader.width, video_reader.height)) for frame in mmcv.track_iter_progress(video_reader): result = inference_detector(model, frame) frame = model.show_result(frame, result, score_thr=args.score_thr) if args.show: cv2.namedWindow('video', 0) mmcv.imshow(frame, 'video', args.wait_time) if args.out: video_writer.write(frame) if video_writer: video_writer.release() cv2.destroyAllWindows() if __name__ == '__main__': main()
1,974
30.854839
76
py
PseCo
PseCo-master/thirdparty/mmdetection/demo/create_result_gif.py
# Copyright (c) OpenMMLab. All rights reserved. import argparse import os import os.path as osp import matplotlib.patches as mpatches import matplotlib.pyplot as plt import mmcv import numpy as np try: import imageio except ImportError: imageio = None def parse_args(): parser = argparse.ArgumentParser(description='Create GIF for demo') parser.add_argument( 'image_dir', help='directory where result ' 'images save path generated by ‘analyze_results.py’') parser.add_argument( '--out', type=str, default='result.gif', help='gif path where will be saved') args = parser.parse_args() return args def _generate_batch_data(sampler, batch_size): batch = [] for idx in sampler: batch.append(idx) if len(batch) == batch_size: yield batch batch = [] if len(batch) > 0: yield batch def create_gif(frames, gif_name, duration=2): """Create gif through imageio. Args: frames (list[ndarray]): Image frames gif_name (str): Saved gif name duration (int): Display interval (s), Default: 2 """ if imageio is None: raise RuntimeError('imageio is not installed,' 'Please use “pip install imageio” to install') imageio.mimsave(gif_name, frames, 'GIF', duration=duration) def create_frame_by_matplotlib(image_dir, nrows=1, fig_size=(300, 300), font_size=15): """Create gif frame image through matplotlib. Args: image_dir (str): Root directory of result images nrows (int): Number of rows displayed, Default: 1 fig_size (tuple): Figure size of the pyplot figure. Default: (300, 300) font_size (int): Font size of texts. Default: 15 Returns: list[ndarray]: image frames """ result_dir_names = os.listdir(image_dir) assert len(result_dir_names) == 2 # Longer length has higher priority result_dir_names.reverse() images_list = [] for dir_names in result_dir_names: images_list.append(mmcv.scandir(osp.join(image_dir, dir_names))) frames = [] for paths in _generate_batch_data(zip(*images_list), nrows): fig, axes = plt.subplots(nrows=nrows, ncols=2) fig.suptitle('Good/bad case selected according ' 'to the COCO mAP of the single image') det_patch = mpatches.Patch(color='salmon', label='prediction') gt_patch = mpatches.Patch(color='royalblue', label='ground truth') # bbox_to_anchor may need to be finetuned plt.legend( handles=[det_patch, gt_patch], bbox_to_anchor=(1, -0.18), loc='lower right', borderaxespad=0.) if nrows == 1: axes = [axes] dpi = fig.get_dpi() # set fig size and margin fig.set_size_inches( (fig_size[0] * 2 + fig_size[0] // 20) / dpi, (fig_size[1] * nrows + fig_size[1] // 3) / dpi, ) fig.tight_layout() # set subplot margin plt.subplots_adjust( hspace=.05, wspace=0.05, left=0.02, right=0.98, bottom=0.02, top=0.98) for i, (path_tuple, ax_tuple) in enumerate(zip(paths, axes)): image_path_left = osp.join( osp.join(image_dir, result_dir_names[0], path_tuple[0])) image_path_right = osp.join( osp.join(image_dir, result_dir_names[1], path_tuple[1])) image_left = mmcv.imread(image_path_left) image_left = mmcv.rgb2bgr(image_left) image_right = mmcv.imread(image_path_right) image_right = mmcv.rgb2bgr(image_right) if i == 0: ax_tuple[0].set_title( result_dir_names[0], fontdict={'size': font_size}) ax_tuple[1].set_title( result_dir_names[1], fontdict={'size': font_size}) ax_tuple[0].imshow( image_left, extent=(0, *fig_size, 0), interpolation='bilinear') ax_tuple[0].axis('off') ax_tuple[1].imshow( image_right, extent=(0, *fig_size, 0), interpolation='bilinear') ax_tuple[1].axis('off') canvas = fig.canvas s, (width, height) = canvas.print_to_buffer() buffer = np.frombuffer(s, dtype='uint8') img_rgba = buffer.reshape(height, width, 4) rgb, alpha = np.split(img_rgba, [3], axis=2) img = rgb.astype('uint8') frames.append(img) return frames def main(): args = parse_args() frames = create_frame_by_matplotlib(args.image_dir) create_gif(frames, args.out) if __name__ == '__main__': main()
4,930
29.067073
79
py
PseCo
PseCo-master/thirdparty/mmdetection/demo/webcam_demo.py
# Copyright (c) OpenMMLab. All rights reserved. import argparse import cv2 import torch from mmdet.apis import inference_detector, init_detector def parse_args(): parser = argparse.ArgumentParser(description='MMDetection webcam demo') parser.add_argument('config', help='test config file path') parser.add_argument('checkpoint', help='checkpoint file') parser.add_argument( '--device', type=str, default='cuda:0', help='CPU/CUDA device option') parser.add_argument( '--camera-id', type=int, default=0, help='camera device id') parser.add_argument( '--score-thr', type=float, default=0.5, help='bbox score threshold') args = parser.parse_args() return args def main(): args = parse_args() device = torch.device(args.device) model = init_detector(args.config, args.checkpoint, device=device) camera = cv2.VideoCapture(args.camera_id) print('Press "Esc", "q" or "Q" to exit.') while True: ret_val, img = camera.read() result = inference_detector(model, img) ch = cv2.waitKey(1) if ch == 27 or ch == ord('q') or ch == ord('Q'): break model.show_result( img, result, score_thr=args.score_thr, wait_time=1, show=True) if __name__ == '__main__': main()
1,308
26.270833
78
py
PseCo
PseCo-master/thirdparty/mmdetection/demo/image_demo.py
# Copyright (c) OpenMMLab. All rights reserved. import asyncio from argparse import ArgumentParser from mmdet.apis import (async_inference_detector, inference_detector, init_detector, show_result_pyplot) def parse_args(): parser = ArgumentParser() parser.add_argument('img', help='Image file') parser.add_argument('config', help='Config file') parser.add_argument('checkpoint', help='Checkpoint file') parser.add_argument( '--device', default='cuda:0', help='Device used for inference') parser.add_argument( '--score-thr', type=float, default=0.3, help='bbox score threshold') parser.add_argument( '--async-test', action='store_true', help='whether to set async options for async inference.') args = parser.parse_args() return args def main(args): # build the model from a config file and a checkpoint file model = init_detector(args.config, args.checkpoint, device=args.device) # test a single image result = inference_detector(model, args.img) # show the results show_result_pyplot(model, args.img, result, score_thr=args.score_thr) async def async_main(args): # build the model from a config file and a checkpoint file model = init_detector(args.config, args.checkpoint, device=args.device) # test a single image tasks = asyncio.create_task(async_inference_detector(model, args.img)) result = await asyncio.gather(tasks) # show the results show_result_pyplot(model, args.img, result[0], score_thr=args.score_thr) if __name__ == '__main__': args = parse_args() if args.async_test: asyncio.run(async_main(args)) else: main(args)
1,719
32.72549
76
py
PseCo
PseCo-master/thirdparty/mmdetection/configs/ghm/retinanet_ghm_x101_32x4d_fpn_1x_coco.py
_base_ = './retinanet_ghm_r50_fpn_1x_coco.py' model = dict( backbone=dict( type='ResNeXt', depth=101, groups=32, base_width=4, num_stages=4, out_indices=(0, 1, 2, 3), frozen_stages=1, norm_cfg=dict(type='BN', requires_grad=True), style='pytorch', init_cfg=dict( type='Pretrained', checkpoint='open-mmlab://resnext101_32x4d')))
423
27.266667
76
py
PseCo
PseCo-master/thirdparty/mmdetection/configs/ghm/retinanet_ghm_r101_fpn_1x_coco.py
_base_ = './retinanet_ghm_r50_fpn_1x_coco.py' model = dict( backbone=dict( depth=101, init_cfg=dict(type='Pretrained', checkpoint='torchvision://resnet101')))
201
27.857143
61
py
PseCo
PseCo-master/thirdparty/mmdetection/configs/ghm/retinanet_ghm_r50_fpn_1x_coco.py
_base_ = '../retinanet/retinanet_r50_fpn_1x_coco.py' model = dict( bbox_head=dict( loss_cls=dict( _delete_=True, type='GHMC', bins=30, momentum=0.75, use_sigmoid=True, loss_weight=1.0), loss_bbox=dict( _delete_=True, type='GHMR', mu=0.02, bins=10, momentum=0.7, loss_weight=10.0))) optimizer_config = dict( _delete_=True, grad_clip=dict(max_norm=35, norm_type=2))
532
25.65
60
py
PseCo
PseCo-master/thirdparty/mmdetection/configs/ghm/retinanet_ghm_x101_64x4d_fpn_1x_coco.py
_base_ = './retinanet_ghm_r50_fpn_1x_coco.py' model = dict( backbone=dict( type='ResNeXt', depth=101, groups=64, base_width=4, num_stages=4, out_indices=(0, 1, 2, 3), frozen_stages=1, norm_cfg=dict(type='BN', requires_grad=True), style='pytorch', init_cfg=dict( type='Pretrained', checkpoint='open-mmlab://resnext101_64x4d')))
423
27.266667
76
py
PseCo
PseCo-master/thirdparty/mmdetection/configs/dcn/cascade_rcnn_r50_fpn_dconv_c3-c5_1x_coco.py
_base_ = '../cascade_rcnn/cascade_rcnn_r50_fpn_1x_coco.py' model = dict( backbone=dict( dcn=dict(type='DCN', deform_groups=1, fallback_on_stride=False), stage_with_dcn=(False, True, True, True)))
216
35.166667
72
py
PseCo
PseCo-master/thirdparty/mmdetection/configs/dcn/mask_rcnn_r50_fpn_mdconv_c3-c5_1x_coco.py
_base_ = '../mask_rcnn/mask_rcnn_r50_fpn_1x_coco.py' model = dict( backbone=dict( dcn=dict(type='DCNv2', deform_groups=1, fallback_on_stride=False), stage_with_dcn=(False, True, True, True)))
212
34.5
74
py
PseCo
PseCo-master/thirdparty/mmdetection/configs/dcn/cascade_rcnn_r101_fpn_dconv_c3-c5_1x_coco.py
_base_ = '../cascade_rcnn/cascade_rcnn_r101_fpn_1x_coco.py' model = dict( backbone=dict( dcn=dict(type='DCN', deform_groups=1, fallback_on_stride=False), stage_with_dcn=(False, True, True, True)))
217
35.333333
72
py
PseCo
PseCo-master/thirdparty/mmdetection/configs/dcn/faster_rcnn_r50_fpn_mdconv_c3-c5_1x_coco.py
_base_ = '../faster_rcnn/faster_rcnn_r50_fpn_1x_coco.py' model = dict( backbone=dict( dcn=dict(type='DCNv2', deform_groups=1, fallback_on_stride=False), stage_with_dcn=(False, True, True, True)))
216
35.166667
74
py
PseCo
PseCo-master/thirdparty/mmdetection/configs/dcn/faster_rcnn_r50_fpn_dpool_1x_coco.py
_base_ = '../faster_rcnn/faster_rcnn_r50_fpn_1x_coco.py' model = dict( roi_head=dict( bbox_roi_extractor=dict( type='SingleRoIExtractor', roi_layer=dict( _delete_=True, type='DeformRoIPoolPack', output_size=7, output_channels=256), out_channels=256, featmap_strides=[4, 8, 16, 32])))
408
30.461538
56
py
PseCo
PseCo-master/thirdparty/mmdetection/configs/dcn/mask_rcnn_r50_fpn_dconv_c3-c5_1x_coco.py
_base_ = '../mask_rcnn/mask_rcnn_r50_fpn_1x_coco.py' model = dict( backbone=dict( dcn=dict(type='DCN', deform_groups=1, fallback_on_stride=False), stage_with_dcn=(False, True, True, True)))
210
34.166667
72
py
PseCo
PseCo-master/thirdparty/mmdetection/configs/dcn/cascade_mask_rcnn_x101_32x4d_fpn_dconv_c3-c5_1x_coco.py
_base_ = '../cascade_rcnn/cascade_mask_rcnn_x101_32x4d_fpn_1x_coco.py' model = dict( backbone=dict( dcn=dict(type='DCN', deform_groups=1, fallback_on_stride=False), stage_with_dcn=(False, True, True, True)))
228
37.166667
72
py
PseCo
PseCo-master/thirdparty/mmdetection/configs/dcn/faster_rcnn_x101_32x4d_fpn_dconv_c3-c5_1x_coco.py
_base_ = '../faster_rcnn/faster_rcnn_r50_fpn_1x_coco.py' model = dict( backbone=dict( type='ResNeXt', depth=101, groups=32, base_width=4, num_stages=4, out_indices=(0, 1, 2, 3), frozen_stages=1, norm_cfg=dict(type='BN', requires_grad=True), style='pytorch', dcn=dict(type='DCN', deform_groups=1, fallback_on_stride=False), stage_with_dcn=(False, True, True, True), init_cfg=dict( type='Pretrained', checkpoint='open-mmlab://resnext101_32x4d')))
557
31.823529
76
py
PseCo
PseCo-master/thirdparty/mmdetection/configs/dcn/cascade_mask_rcnn_r50_fpn_dconv_c3-c5_1x_coco.py
_base_ = '../cascade_rcnn/cascade_mask_rcnn_r50_fpn_1x_coco.py' model = dict( backbone=dict( dcn=dict(type='DCN', deform_groups=1, fallback_on_stride=False), stage_with_dcn=(False, True, True, True)))
221
36
72
py
PseCo
PseCo-master/thirdparty/mmdetection/configs/dcn/cascade_mask_rcnn_r101_fpn_dconv_c3-c5_1x_coco.py
_base_ = '../cascade_rcnn/cascade_mask_rcnn_r101_fpn_1x_coco.py' model = dict( backbone=dict( dcn=dict(type='DCN', deform_groups=1, fallback_on_stride=False), stage_with_dcn=(False, True, True, True)))
222
36.166667
72
py
PseCo
PseCo-master/thirdparty/mmdetection/configs/dcn/faster_rcnn_r50_fpn_dconv_c3-c5_1x_coco.py
_base_ = '../faster_rcnn/faster_rcnn_r50_fpn_1x_coco.py' model = dict( backbone=dict( dcn=dict(type='DCN', deform_groups=1, fallback_on_stride=False), stage_with_dcn=(False, True, True, True)))
214
34.833333
72
py
PseCo
PseCo-master/thirdparty/mmdetection/configs/dcn/faster_rcnn_r50_fpn_mdconv_c3-c5_group4_1x_coco.py
_base_ = '../faster_rcnn/faster_rcnn_r50_fpn_1x_coco.py' model = dict( backbone=dict( dcn=dict(type='DCNv2', deform_groups=4, fallback_on_stride=False), stage_with_dcn=(False, True, True, True)))
216
35.166667
74
py
PseCo
PseCo-master/thirdparty/mmdetection/configs/dcn/faster_rcnn_r101_fpn_dconv_c3-c5_1x_coco.py
_base_ = '../faster_rcnn/faster_rcnn_r101_fpn_1x_coco.py' model = dict( backbone=dict( dcn=dict(type='DCN', deform_groups=1, fallback_on_stride=False), stage_with_dcn=(False, True, True, True)))
215
35
72
py
PseCo
PseCo-master/thirdparty/mmdetection/configs/dcn/mask_rcnn_r101_fpn_dconv_c3-c5_1x_coco.py
_base_ = '../mask_rcnn/mask_rcnn_r101_fpn_1x_coco.py' model = dict( backbone=dict( dcn=dict(type='DCN', deform_groups=1, fallback_on_stride=False), stage_with_dcn=(False, True, True, True)))
211
34.333333
72
py
PseCo
PseCo-master/thirdparty/mmdetection/configs/dcn/faster_rcnn_r50_fpn_mdpool_1x_coco.py
_base_ = '../faster_rcnn/faster_rcnn_r50_fpn_1x_coco.py' model = dict( roi_head=dict( bbox_roi_extractor=dict( type='SingleRoIExtractor', roi_layer=dict( _delete_=True, type='ModulatedDeformRoIPoolPack', output_size=7, output_channels=256), out_channels=256, featmap_strides=[4, 8, 16, 32])))
417
31.153846
56
py
PseCo
PseCo-master/thirdparty/mmdetection/configs/htc/htc_x101_64x4d_fpn_16x1_20e_coco.py
_base_ = './htc_r50_fpn_1x_coco.py' model = dict( backbone=dict( type='ResNeXt', depth=101, groups=64, base_width=4, num_stages=4, out_indices=(0, 1, 2, 3), frozen_stages=1, norm_cfg=dict(type='BN', requires_grad=True), norm_eval=True, style='pytorch', init_cfg=dict( type='Pretrained', checkpoint='open-mmlab://resnext101_64x4d'))) data = dict(samples_per_gpu=1, workers_per_gpu=1) # learning policy lr_config = dict(step=[16, 19]) runner = dict(type='EpochBasedRunner', max_epochs=20)
591
28.6
76
py
PseCo
PseCo-master/thirdparty/mmdetection/configs/htc/htc_r50_fpn_20e_coco.py
_base_ = './htc_r50_fpn_1x_coco.py' # learning policy lr_config = dict(step=[16, 19]) runner = dict(type='EpochBasedRunner', max_epochs=20)
140
27.2
53
py
PseCo
PseCo-master/thirdparty/mmdetection/configs/htc/htc_without_semantic_r50_fpn_1x_coco.py
_base_ = [ '../_base_/datasets/coco_instance.py', '../_base_/schedules/schedule_1x.py', '../_base_/default_runtime.py' ] # model settings model = dict( type='HybridTaskCascade', backbone=dict( type='ResNet', depth=50, num_stages=4, out_indices=(0, 1, 2, 3), frozen_stages=1, norm_cfg=dict(type='BN', requires_grad=True), norm_eval=True, style='pytorch', init_cfg=dict(type='Pretrained', checkpoint='torchvision://resnet50')), neck=dict( type='FPN', in_channels=[256, 512, 1024, 2048], out_channels=256, num_outs=5), rpn_head=dict( type='RPNHead', in_channels=256, feat_channels=256, anchor_generator=dict( type='AnchorGenerator', scales=[8], ratios=[0.5, 1.0, 2.0], strides=[4, 8, 16, 32, 64]), bbox_coder=dict( type='DeltaXYWHBBoxCoder', target_means=[.0, .0, .0, .0], target_stds=[1.0, 1.0, 1.0, 1.0]), loss_cls=dict( type='CrossEntropyLoss', use_sigmoid=True, loss_weight=1.0), loss_bbox=dict(type='SmoothL1Loss', beta=1.0 / 9.0, loss_weight=1.0)), roi_head=dict( type='HybridTaskCascadeRoIHead', interleaved=True, mask_info_flow=True, num_stages=3, stage_loss_weights=[1, 0.5, 0.25], bbox_roi_extractor=dict( type='SingleRoIExtractor', roi_layer=dict(type='RoIAlign', output_size=7, sampling_ratio=0), out_channels=256, featmap_strides=[4, 8, 16, 32]), bbox_head=[ dict( type='Shared2FCBBoxHead', in_channels=256, fc_out_channels=1024, roi_feat_size=7, num_classes=80, bbox_coder=dict( type='DeltaXYWHBBoxCoder', target_means=[0., 0., 0., 0.], target_stds=[0.1, 0.1, 0.2, 0.2]), reg_class_agnostic=True, loss_cls=dict( type='CrossEntropyLoss', use_sigmoid=False, loss_weight=1.0), loss_bbox=dict(type='SmoothL1Loss', beta=1.0, loss_weight=1.0)), dict( type='Shared2FCBBoxHead', in_channels=256, fc_out_channels=1024, roi_feat_size=7, num_classes=80, bbox_coder=dict( type='DeltaXYWHBBoxCoder', target_means=[0., 0., 0., 0.], target_stds=[0.05, 0.05, 0.1, 0.1]), reg_class_agnostic=True, loss_cls=dict( type='CrossEntropyLoss', use_sigmoid=False, loss_weight=1.0), loss_bbox=dict(type='SmoothL1Loss', beta=1.0, loss_weight=1.0)), dict( type='Shared2FCBBoxHead', in_channels=256, fc_out_channels=1024, roi_feat_size=7, num_classes=80, bbox_coder=dict( type='DeltaXYWHBBoxCoder', target_means=[0., 0., 0., 0.], target_stds=[0.033, 0.033, 0.067, 0.067]), reg_class_agnostic=True, loss_cls=dict( type='CrossEntropyLoss', use_sigmoid=False, loss_weight=1.0), loss_bbox=dict(type='SmoothL1Loss', beta=1.0, loss_weight=1.0)) ], mask_roi_extractor=dict( type='SingleRoIExtractor', roi_layer=dict(type='RoIAlign', output_size=14, sampling_ratio=0), out_channels=256, featmap_strides=[4, 8, 16, 32]), mask_head=[ dict( type='HTCMaskHead', with_conv_res=False, num_convs=4, in_channels=256, conv_out_channels=256, num_classes=80, loss_mask=dict( type='CrossEntropyLoss', use_mask=True, loss_weight=1.0)), dict( type='HTCMaskHead', num_convs=4, in_channels=256, conv_out_channels=256, num_classes=80, loss_mask=dict( type='CrossEntropyLoss', use_mask=True, loss_weight=1.0)), dict( type='HTCMaskHead', num_convs=4, in_channels=256, conv_out_channels=256, num_classes=80, loss_mask=dict( type='CrossEntropyLoss', use_mask=True, loss_weight=1.0)) ]), # model training and testing settings train_cfg=dict( rpn=dict( assigner=dict( type='MaxIoUAssigner', pos_iou_thr=0.7, neg_iou_thr=0.3, min_pos_iou=0.3, ignore_iof_thr=-1), sampler=dict( type='RandomSampler', num=256, pos_fraction=0.5, neg_pos_ub=-1, add_gt_as_proposals=False), allowed_border=0, pos_weight=-1, debug=False), rpn_proposal=dict( nms_pre=2000, max_per_img=2000, nms=dict(type='nms', iou_threshold=0.7), min_bbox_size=0), rcnn=[ dict( assigner=dict( type='MaxIoUAssigner', pos_iou_thr=0.5, neg_iou_thr=0.5, min_pos_iou=0.5, ignore_iof_thr=-1), sampler=dict( type='RandomSampler', num=512, pos_fraction=0.25, neg_pos_ub=-1, add_gt_as_proposals=True), mask_size=28, pos_weight=-1, debug=False), dict( assigner=dict( type='MaxIoUAssigner', pos_iou_thr=0.6, neg_iou_thr=0.6, min_pos_iou=0.6, ignore_iof_thr=-1), sampler=dict( type='RandomSampler', num=512, pos_fraction=0.25, neg_pos_ub=-1, add_gt_as_proposals=True), mask_size=28, pos_weight=-1, debug=False), dict( assigner=dict( type='MaxIoUAssigner', pos_iou_thr=0.7, neg_iou_thr=0.7, min_pos_iou=0.7, ignore_iof_thr=-1), sampler=dict( type='RandomSampler', num=512, pos_fraction=0.25, neg_pos_ub=-1, add_gt_as_proposals=True), mask_size=28, pos_weight=-1, debug=False) ]), test_cfg=dict( rpn=dict( nms_pre=1000, max_per_img=1000, nms=dict(type='nms', iou_threshold=0.7), min_bbox_size=0), rcnn=dict( score_thr=0.001, nms=dict(type='nms', iou_threshold=0.5), max_per_img=100, mask_thr_binary=0.5))) img_norm_cfg = dict( mean=[123.675, 116.28, 103.53], std=[58.395, 57.12, 57.375], to_rgb=True) test_pipeline = [ dict(type='LoadImageFromFile'), dict( type='MultiScaleFlipAug', img_scale=(1333, 800), flip=False, transforms=[ dict(type='Resize', keep_ratio=True), dict(type='RandomFlip', flip_ratio=0.5), dict(type='Normalize', **img_norm_cfg), dict(type='Pad', size_divisor=32), dict(type='ImageToTensor', keys=['img']), dict(type='Collect', keys=['img']), ]) ] data = dict( val=dict(pipeline=test_pipeline), test=dict(pipeline=test_pipeline))
8,333
34.164557
79
py
PseCo
PseCo-master/thirdparty/mmdetection/configs/htc/htc_x101_32x4d_fpn_16x1_20e_coco.py
_base_ = './htc_r50_fpn_1x_coco.py' model = dict( backbone=dict( type='ResNeXt', depth=101, groups=32, base_width=4, num_stages=4, out_indices=(0, 1, 2, 3), frozen_stages=1, norm_cfg=dict(type='BN', requires_grad=True), norm_eval=True, style='pytorch', init_cfg=dict( type='Pretrained', checkpoint='open-mmlab://resnext101_32x4d'))) data = dict(samples_per_gpu=1, workers_per_gpu=1) # learning policy lr_config = dict(step=[16, 19]) runner = dict(type='EpochBasedRunner', max_epochs=20)
591
28.6
76
py
PseCo
PseCo-master/thirdparty/mmdetection/configs/htc/htc_x101_64x4d_fpn_dconv_c3-c5_mstrain_400_1400_16x1_20e_coco.py
_base_ = './htc_r50_fpn_1x_coco.py' model = dict( backbone=dict( type='ResNeXt', depth=101, groups=64, base_width=4, num_stages=4, out_indices=(0, 1, 2, 3), frozen_stages=1, norm_cfg=dict(type='BN', requires_grad=True), norm_eval=True, style='pytorch', dcn=dict(type='DCN', deform_groups=1, fallback_on_stride=False), stage_with_dcn=(False, True, True, True), init_cfg=dict( type='Pretrained', checkpoint='open-mmlab://resnext101_64x4d'))) # dataset settings img_norm_cfg = dict( mean=[123.675, 116.28, 103.53], std=[58.395, 57.12, 57.375], to_rgb=True) train_pipeline = [ dict(type='LoadImageFromFile'), dict( type='LoadAnnotations', with_bbox=True, with_mask=True, with_seg=True), dict( type='Resize', img_scale=[(1600, 400), (1600, 1400)], multiscale_mode='range', keep_ratio=True), dict(type='RandomFlip', flip_ratio=0.5), dict(type='Normalize', **img_norm_cfg), dict(type='Pad', size_divisor=32), dict(type='SegRescale', scale_factor=1 / 8), dict(type='DefaultFormatBundle'), dict( type='Collect', keys=['img', 'gt_bboxes', 'gt_labels', 'gt_masks', 'gt_semantic_seg']), ] data = dict( samples_per_gpu=1, workers_per_gpu=1, train=dict(pipeline=train_pipeline)) # learning policy lr_config = dict(step=[16, 19]) runner = dict(type='EpochBasedRunner', max_epochs=20)
1,489
32.863636
79
py
PseCo
PseCo-master/thirdparty/mmdetection/configs/htc/htc_r50_fpn_1x_coco.py
_base_ = './htc_without_semantic_r50_fpn_1x_coco.py' model = dict( roi_head=dict( semantic_roi_extractor=dict( type='SingleRoIExtractor', roi_layer=dict(type='RoIAlign', output_size=14, sampling_ratio=0), out_channels=256, featmap_strides=[8]), semantic_head=dict( type='FusedSemanticHead', num_ins=5, fusion_level=1, num_convs=4, in_channels=256, conv_out_channels=256, num_classes=183, loss_seg=dict( type='CrossEntropyLoss', ignore_index=255, loss_weight=0.2)))) data_root = 'data/coco/' img_norm_cfg = dict( mean=[123.675, 116.28, 103.53], std=[58.395, 57.12, 57.375], to_rgb=True) train_pipeline = [ dict(type='LoadImageFromFile'), dict( type='LoadAnnotations', with_bbox=True, with_mask=True, with_seg=True), dict(type='Resize', img_scale=(1333, 800), keep_ratio=True), dict(type='RandomFlip', flip_ratio=0.5), dict(type='Normalize', **img_norm_cfg), dict(type='Pad', size_divisor=32), dict(type='SegRescale', scale_factor=1 / 8), dict(type='DefaultFormatBundle'), dict( type='Collect', keys=['img', 'gt_bboxes', 'gt_labels', 'gt_masks', 'gt_semantic_seg']), ] test_pipeline = [ dict(type='LoadImageFromFile'), dict( type='MultiScaleFlipAug', img_scale=(1333, 800), flip=False, transforms=[ dict(type='Resize', keep_ratio=True), dict(type='RandomFlip', flip_ratio=0.5), dict(type='Normalize', **img_norm_cfg), dict(type='Pad', size_divisor=32), dict(type='ImageToTensor', keys=['img']), dict(type='Collect', keys=['img']), ]) ] data = dict( train=dict( seg_prefix=data_root + 'stuffthingmaps/train2017/', pipeline=train_pipeline), val=dict(pipeline=test_pipeline), test=dict(pipeline=test_pipeline))
1,998
34.070175
79
py
PseCo
PseCo-master/thirdparty/mmdetection/configs/htc/htc_r101_fpn_20e_coco.py
_base_ = './htc_r50_fpn_1x_coco.py' model = dict( backbone=dict( depth=101, init_cfg=dict(type='Pretrained', checkpoint='torchvision://resnet101'))) # learning policy lr_config = dict(step=[16, 19]) runner = dict(type='EpochBasedRunner', max_epochs=20)
295
28.6
61
py
PseCo
PseCo-master/thirdparty/mmdetection/configs/reppoints/reppoints_moment_r101_fpn_dconv_c3-c5_gn-neck+head_2x_coco.py
_base_ = './reppoints_moment_r50_fpn_gn-neck+head_2x_coco.py' model = dict( backbone=dict( depth=101, dcn=dict(type='DCN', deform_groups=1, fallback_on_stride=False), stage_with_dcn=(False, True, True, True), init_cfg=dict(type='Pretrained', checkpoint='torchvision://resnet101')))
340
36.888889
72
py
PseCo
PseCo-master/thirdparty/mmdetection/configs/reppoints/reppoints_moment_r101_fpn_gn-neck+head_2x_coco.py
_base_ = './reppoints_moment_r50_fpn_gn-neck+head_2x_coco.py' model = dict( backbone=dict( depth=101, init_cfg=dict(type='Pretrained', checkpoint='torchvision://resnet101')))
217
30.142857
61
py
PseCo
PseCo-master/thirdparty/mmdetection/configs/reppoints/reppoints_moment_r50_fpn_1x_coco.py
_base_ = [ '../_base_/datasets/coco_detection.py', '../_base_/schedules/schedule_1x.py', '../_base_/default_runtime.py' ] model = dict( type='RepPointsDetector', backbone=dict( type='ResNet', depth=50, num_stages=4, out_indices=(0, 1, 2, 3), frozen_stages=1, norm_cfg=dict(type='BN', requires_grad=True), norm_eval=True, style='pytorch', init_cfg=dict(type='Pretrained', checkpoint='torchvision://resnet50')), neck=dict( type='FPN', in_channels=[256, 512, 1024, 2048], out_channels=256, start_level=1, add_extra_convs='on_input', num_outs=5), bbox_head=dict( type='RepPointsHead', num_classes=80, in_channels=256, feat_channels=256, point_feat_channels=256, stacked_convs=3, num_points=9, gradient_mul=0.1, point_strides=[8, 16, 32, 64, 128], point_base_scale=4, loss_cls=dict( type='FocalLoss', use_sigmoid=True, gamma=2.0, alpha=0.25, loss_weight=1.0), loss_bbox_init=dict(type='SmoothL1Loss', beta=0.11, loss_weight=0.5), loss_bbox_refine=dict(type='SmoothL1Loss', beta=0.11, loss_weight=1.0), transform_method='moment'), # training and testing settings train_cfg=dict( init=dict( assigner=dict(type='PointAssigner', scale=4, pos_num=1), allowed_border=-1, pos_weight=-1, debug=False), refine=dict( assigner=dict( type='MaxIoUAssigner', pos_iou_thr=0.5, neg_iou_thr=0.4, min_pos_iou=0, ignore_iof_thr=-1), allowed_border=-1, pos_weight=-1, debug=False)), test_cfg=dict( nms_pre=1000, min_bbox_size=0, score_thr=0.05, nms=dict(type='nms', iou_threshold=0.5), max_per_img=100)) optimizer = dict(lr=0.01)
2,065
29.382353
79
py
PseCo
PseCo-master/thirdparty/mmdetection/configs/reppoints/reppoints_partial_minmax_r50_fpn_gn-neck+head_1x_coco.py
_base_ = './reppoints_moment_r50_fpn_gn-neck+head_1x_coco.py' model = dict(bbox_head=dict(transform_method='partial_minmax'))
126
41.333333
63
py
PseCo
PseCo-master/thirdparty/mmdetection/configs/reppoints/reppoints_moment_r50_fpn_gn-neck+head_1x_coco.py
_base_ = './reppoints_moment_r50_fpn_1x_coco.py' norm_cfg = dict(type='GN', num_groups=32, requires_grad=True) model = dict(neck=dict(norm_cfg=norm_cfg), bbox_head=dict(norm_cfg=norm_cfg)) optimizer = dict(lr=0.01)
215
42.2
77
py
PseCo
PseCo-master/thirdparty/mmdetection/configs/reppoints/bbox_r50_grid_fpn_gn-neck+head_1x_coco.py
_base_ = './reppoints_moment_r50_fpn_gn-neck+head_1x_coco.py' model = dict( bbox_head=dict(transform_method='minmax', use_grid_points=True), # training and testing settings train_cfg=dict( init=dict( assigner=dict( _delete_=True, type='MaxIoUAssigner', pos_iou_thr=0.5, neg_iou_thr=0.4, min_pos_iou=0, ignore_iof_thr=-1))))
452
31.357143
68
py
PseCo
PseCo-master/thirdparty/mmdetection/configs/reppoints/reppoints_moment_r50_fpn_gn-neck+head_2x_coco.py
_base_ = './reppoints_moment_r50_fpn_gn-neck+head_1x_coco.py' lr_config = dict(step=[16, 22]) runner = dict(type='EpochBasedRunner', max_epochs=24)
148
36.25
61
py
PseCo
PseCo-master/thirdparty/mmdetection/configs/reppoints/bbox_r50_grid_center_fpn_gn-neck+head_1x_coco.py
_base_ = './reppoints_moment_r50_fpn_gn-neck+head_1x_coco.py' model = dict(bbox_head=dict(transform_method='minmax', use_grid_points=True))
140
46
77
py
PseCo
PseCo-master/thirdparty/mmdetection/configs/reppoints/reppoints_moment_x101_fpn_dconv_c3-c5_gn-neck+head_2x_coco.py
_base_ = './reppoints_moment_r50_fpn_gn-neck+head_2x_coco.py' model = dict( backbone=dict( type='ResNeXt', depth=101, groups=32, base_width=4, num_stages=4, out_indices=(0, 1, 2, 3), frozen_stages=1, norm_cfg=dict(type='BN', requires_grad=True), style='pytorch', dcn=dict(type='DCN', deform_groups=1, fallback_on_stride=False), stage_with_dcn=(False, True, True, True), init_cfg=dict( type='Pretrained', checkpoint='open-mmlab://resnext101_32x4d')))
562
32.117647
76
py
PseCo
PseCo-master/thirdparty/mmdetection/configs/reppoints/reppoints_minmax_r50_fpn_gn-neck+head_1x_coco.py
_base_ = './reppoints_moment_r50_fpn_gn-neck+head_1x_coco.py' model = dict(bbox_head=dict(transform_method='minmax'))
118
38.666667
61
py
PseCo
PseCo-master/thirdparty/mmdetection/configs/gfl/gfl_x101_32x4d_fpn_dconv_c4-c5_mstrain_2x_coco.py
_base_ = './gfl_r50_fpn_mstrain_2x_coco.py' model = dict( type='GFL', backbone=dict( type='ResNeXt', depth=101, groups=32, base_width=4, num_stages=4, out_indices=(0, 1, 2, 3), frozen_stages=1, norm_cfg=dict(type='BN', requires_grad=True), dcn=dict(type='DCN', deform_groups=1, fallback_on_stride=False), stage_with_dcn=(False, False, True, True), norm_eval=True, style='pytorch', init_cfg=dict( type='Pretrained', checkpoint='open-mmlab://resnext101_32x4d')))
585
29.842105
76
py
PseCo
PseCo-master/thirdparty/mmdetection/configs/gfl/gfl_r50_fpn_mstrain_2x_coco.py
_base_ = './gfl_r50_fpn_1x_coco.py' # learning policy lr_config = dict(step=[16, 22]) runner = dict(type='EpochBasedRunner', max_epochs=24) # multi-scale training img_norm_cfg = dict( mean=[123.675, 116.28, 103.53], std=[58.395, 57.12, 57.375], to_rgb=True) train_pipeline = [ dict(type='LoadImageFromFile'), dict(type='LoadAnnotations', with_bbox=True), dict( type='Resize', img_scale=[(1333, 480), (1333, 800)], multiscale_mode='range', keep_ratio=True), dict(type='RandomFlip', flip_ratio=0.5), dict(type='Normalize', **img_norm_cfg), dict(type='Pad', size_divisor=32), dict(type='DefaultFormatBundle'), dict(type='Collect', keys=['img', 'gt_bboxes', 'gt_labels']), ] data = dict(train=dict(pipeline=train_pipeline))
788
33.304348
77
py
PseCo
PseCo-master/thirdparty/mmdetection/configs/gfl/gfl_x101_32x4d_fpn_mstrain_2x_coco.py
_base_ = './gfl_r50_fpn_mstrain_2x_coco.py' model = dict( type='GFL', backbone=dict( type='ResNeXt', depth=101, groups=32, base_width=4, num_stages=4, out_indices=(0, 1, 2, 3), frozen_stages=1, norm_cfg=dict(type='BN', requires_grad=True), norm_eval=True, style='pytorch', init_cfg=dict( type='Pretrained', checkpoint='open-mmlab://resnext101_32x4d')))
461
26.176471
76
py
PseCo
PseCo-master/thirdparty/mmdetection/configs/gfl/gfl_r101_fpn_mstrain_2x_coco.py
_base_ = './gfl_r50_fpn_mstrain_2x_coco.py' model = dict( backbone=dict( type='ResNet', depth=101, num_stages=4, out_indices=(0, 1, 2, 3), frozen_stages=1, norm_cfg=dict(type='BN', requires_grad=True), norm_eval=True, style='pytorch', init_cfg=dict(type='Pretrained', checkpoint='torchvision://resnet101')))
406
28.071429
61
py
PseCo
PseCo-master/thirdparty/mmdetection/configs/gfl/gfl_r50_fpn_1x_coco.py
_base_ = [ '../_base_/datasets/coco_detection.py', '../_base_/schedules/schedule_1x.py', '../_base_/default_runtime.py' ] model = dict( type='GFL', backbone=dict( type='ResNet', depth=50, num_stages=4, out_indices=(0, 1, 2, 3), frozen_stages=1, norm_cfg=dict(type='BN', requires_grad=True), norm_eval=True, style='pytorch', init_cfg=dict(type='Pretrained', checkpoint='torchvision://resnet50')), neck=dict( type='FPN', in_channels=[256, 512, 1024, 2048], out_channels=256, start_level=1, add_extra_convs='on_output', num_outs=5), bbox_head=dict( type='GFLHead', num_classes=80, in_channels=256, stacked_convs=4, feat_channels=256, anchor_generator=dict( type='AnchorGenerator', ratios=[1.0], octave_base_scale=8, scales_per_octave=1, strides=[8, 16, 32, 64, 128]), loss_cls=dict( type='QualityFocalLoss', use_sigmoid=True, beta=2.0, loss_weight=1.0), loss_dfl=dict(type='DistributionFocalLoss', loss_weight=0.25), reg_max=16, loss_bbox=dict(type='GIoULoss', loss_weight=2.0)), # training and testing settings train_cfg=dict( assigner=dict(type='ATSSAssigner', topk=9), allowed_border=-1, pos_weight=-1, debug=False), test_cfg=dict( nms_pre=1000, min_bbox_size=0, score_thr=0.05, nms=dict(type='nms', iou_threshold=0.6), max_per_img=100)) # optimizer optimizer = dict(type='SGD', lr=0.01, momentum=0.9, weight_decay=0.0001)
1,739
29
79
py
PseCo
PseCo-master/thirdparty/mmdetection/configs/gfl/gfl_r101_fpn_dconv_c3-c5_mstrain_2x_coco.py
_base_ = './gfl_r50_fpn_mstrain_2x_coco.py' model = dict( backbone=dict( type='ResNet', depth=101, num_stages=4, out_indices=(0, 1, 2, 3), frozen_stages=1, norm_cfg=dict(type='BN', requires_grad=True), dcn=dict(type='DCN', deform_groups=1, fallback_on_stride=False), stage_with_dcn=(False, True, True, True), norm_eval=True, style='pytorch', init_cfg=dict(type='Pretrained', checkpoint='torchvision://resnet101')))
529
32.125
72
py
PseCo
PseCo-master/thirdparty/mmdetection/configs/tridentnet/tridentnet_r50_caffe_mstrain_1x_coco.py
_base_ = 'tridentnet_r50_caffe_1x_coco.py' # use caffe img_norm img_norm_cfg = dict( mean=[103.530, 116.280, 123.675], std=[1.0, 1.0, 1.0], to_rgb=False) train_pipeline = [ dict(type='LoadImageFromFile'), dict(type='LoadAnnotations', with_bbox=True), dict( type='Resize', img_scale=[(1333, 640), (1333, 672), (1333, 704), (1333, 736), (1333, 768), (1333, 800)], multiscale_mode='value', keep_ratio=True), dict(type='RandomFlip', flip_ratio=0.5), dict(type='Normalize', **img_norm_cfg), dict(type='Pad', size_divisor=32), dict(type='DefaultFormatBundle'), dict(type='Collect', keys=['img', 'gt_bboxes', 'gt_labels']) ] data = dict(train=dict(pipeline=train_pipeline))
756
31.913043
72
py
PseCo
PseCo-master/thirdparty/mmdetection/configs/tridentnet/tridentnet_r50_caffe_mstrain_3x_coco.py
_base_ = 'tridentnet_r50_caffe_mstrain_1x_coco.py' lr_config = dict(step=[28, 34]) runner = dict(type='EpochBasedRunner', max_epochs=36)
138
26.8
53
py
PseCo
PseCo-master/thirdparty/mmdetection/configs/tridentnet/tridentnet_r50_caffe_1x_coco.py
_base_ = [ '../_base_/models/faster_rcnn_r50_caffe_c4.py', '../_base_/datasets/coco_detection.py', '../_base_/schedules/schedule_1x.py', '../_base_/default_runtime.py' ] model = dict( type='TridentFasterRCNN', backbone=dict( type='TridentResNet', trident_dilations=(1, 2, 3), num_branch=3, test_branch_idx=1, init_cfg=dict( type='Pretrained', checkpoint='open-mmlab://detectron2/resnet50_caffe')), roi_head=dict(type='TridentRoIHead', num_branch=3, test_branch_idx=1), train_cfg=dict( rpn_proposal=dict(max_per_img=500), rcnn=dict( sampler=dict(num=128, pos_fraction=0.5, add_gt_as_proposals=False)))) # use caffe img_norm img_norm_cfg = dict( mean=[103.530, 116.280, 123.675], std=[1.0, 1.0, 1.0], to_rgb=False) train_pipeline = [ dict(type='LoadImageFromFile'), dict(type='LoadAnnotations', with_bbox=True), dict(type='Resize', img_scale=(1333, 800), keep_ratio=True), dict(type='RandomFlip', flip_ratio=0.5), dict(type='Normalize', **img_norm_cfg), dict(type='Pad', size_divisor=32), dict(type='DefaultFormatBundle'), dict(type='Collect', keys=['img', 'gt_bboxes', 'gt_labels']) ] test_pipeline = [ dict(type='LoadImageFromFile'), dict( type='MultiScaleFlipAug', img_scale=(1333, 800), flip=False, transforms=[ dict(type='Resize', keep_ratio=True), dict(type='RandomFlip'), dict(type='Normalize', **img_norm_cfg), dict(type='Pad', size_divisor=32), dict(type='ImageToTensor', keys=['img']), dict(type='Collect', keys=['img']) ]) ] data = dict( train=dict(pipeline=train_pipeline), val=dict(pipeline=test_pipeline), test=dict(pipeline=test_pipeline))
1,868
32.375
74
py
PseCo
PseCo-master/thirdparty/mmdetection/configs/ssd/ssd512_coco.py
_base_ = 'ssd300_coco.py' input_size = 512 model = dict( neck=dict( out_channels=(512, 1024, 512, 256, 256, 256, 256), level_strides=(2, 2, 2, 2, 1), level_paddings=(1, 1, 1, 1, 1), last_kernel_size=4), bbox_head=dict( in_channels=(512, 1024, 512, 256, 256, 256, 256), anchor_generator=dict( type='SSDAnchorGenerator', scale_major=False, input_size=input_size, basesize_ratio_range=(0.1, 0.9), strides=[8, 16, 32, 64, 128, 256, 512], ratios=[[2], [2, 3], [2, 3], [2, 3], [2, 3], [2], [2]]))) # dataset settings dataset_type = 'CocoDataset' data_root = 'data/coco/' img_norm_cfg = dict(mean=[123.675, 116.28, 103.53], std=[1, 1, 1], to_rgb=True) train_pipeline = [ dict(type='LoadImageFromFile', to_float32=True), dict(type='LoadAnnotations', with_bbox=True), dict( type='PhotoMetricDistortion', brightness_delta=32, contrast_range=(0.5, 1.5), saturation_range=(0.5, 1.5), hue_delta=18), dict( type='Expand', mean=img_norm_cfg['mean'], to_rgb=img_norm_cfg['to_rgb'], ratio_range=(1, 4)), dict( type='MinIoURandomCrop', min_ious=(0.1, 0.3, 0.5, 0.7, 0.9), min_crop_size=0.3), dict(type='Resize', img_scale=(512, 512), keep_ratio=False), dict(type='Normalize', **img_norm_cfg), dict(type='RandomFlip', flip_ratio=0.5), dict(type='DefaultFormatBundle'), dict(type='Collect', keys=['img', 'gt_bboxes', 'gt_labels']), ] test_pipeline = [ dict(type='LoadImageFromFile'), dict( type='MultiScaleFlipAug', img_scale=(512, 512), flip=False, transforms=[ dict(type='Resize', keep_ratio=False), dict(type='Normalize', **img_norm_cfg), dict(type='ImageToTensor', keys=['img']), dict(type='Collect', keys=['img']), ]) ] data = dict( samples_per_gpu=8, workers_per_gpu=3, train=dict( _delete_=True, type='RepeatDataset', times=5, dataset=dict( type=dataset_type, ann_file=data_root + 'annotations/instances_train2017.json', img_prefix=data_root + 'train2017/', pipeline=train_pipeline)), val=dict(pipeline=test_pipeline), test=dict(pipeline=test_pipeline)) # optimizer optimizer = dict(type='SGD', lr=2e-3, momentum=0.9, weight_decay=5e-4) optimizer_config = dict(_delete_=True) custom_hooks = [ dict(type='NumClassCheckHook'), dict(type='CheckInvalidLossHook', interval=50, priority='VERY_LOW') ]
2,650
32.1375
79
py
PseCo
PseCo-master/thirdparty/mmdetection/configs/ssd/ssd300_coco.py
_base_ = [ '../_base_/models/ssd300.py', '../_base_/datasets/coco_detection.py', '../_base_/schedules/schedule_2x.py', '../_base_/default_runtime.py' ] # dataset settings dataset_type = 'CocoDataset' data_root = 'data/coco/' img_norm_cfg = dict(mean=[123.675, 116.28, 103.53], std=[1, 1, 1], to_rgb=True) train_pipeline = [ dict(type='LoadImageFromFile', to_float32=True), dict(type='LoadAnnotations', with_bbox=True), dict( type='PhotoMetricDistortion', brightness_delta=32, contrast_range=(0.5, 1.5), saturation_range=(0.5, 1.5), hue_delta=18), dict( type='Expand', mean=img_norm_cfg['mean'], to_rgb=img_norm_cfg['to_rgb'], ratio_range=(1, 4)), dict( type='MinIoURandomCrop', min_ious=(0.1, 0.3, 0.5, 0.7, 0.9), min_crop_size=0.3), dict(type='Resize', img_scale=(300, 300), keep_ratio=False), dict(type='Normalize', **img_norm_cfg), dict(type='RandomFlip', flip_ratio=0.5), dict(type='DefaultFormatBundle'), dict(type='Collect', keys=['img', 'gt_bboxes', 'gt_labels']), ] test_pipeline = [ dict(type='LoadImageFromFile'), dict( type='MultiScaleFlipAug', img_scale=(300, 300), flip=False, transforms=[ dict(type='Resize', keep_ratio=False), dict(type='Normalize', **img_norm_cfg), dict(type='ImageToTensor', keys=['img']), dict(type='Collect', keys=['img']), ]) ] data = dict( samples_per_gpu=8, workers_per_gpu=3, train=dict( _delete_=True, type='RepeatDataset', times=5, dataset=dict( type=dataset_type, ann_file=data_root + 'annotations/instances_train2017.json', img_prefix=data_root + 'train2017/', pipeline=train_pipeline)), val=dict(pipeline=test_pipeline), test=dict(pipeline=test_pipeline)) # optimizer optimizer = dict(type='SGD', lr=2e-3, momentum=0.9, weight_decay=5e-4) optimizer_config = dict(_delete_=True) custom_hooks = [ dict(type='NumClassCheckHook'), dict(type='CheckInvalidLossHook', interval=50, priority='VERY_LOW') ]
2,190
31.701493
79
py
PseCo
PseCo-master/thirdparty/mmdetection/configs/ssd/ssdlite_mobilenetv2_scratch_600e_coco.py
_base_ = [ '../_base_/datasets/coco_detection.py', '../_base_/default_runtime.py' ] model = dict( type='SingleStageDetector', backbone=dict( type='MobileNetV2', out_indices=(4, 7), norm_cfg=dict(type='BN', eps=0.001, momentum=0.03), init_cfg=dict(type='TruncNormal', layer='Conv2d', std=0.03)), neck=dict( type='SSDNeck', in_channels=(96, 1280), out_channels=(96, 1280, 512, 256, 256, 128), level_strides=(2, 2, 2, 2), level_paddings=(1, 1, 1, 1), l2_norm_scale=None, use_depthwise=True, norm_cfg=dict(type='BN', eps=0.001, momentum=0.03), act_cfg=dict(type='ReLU6'), init_cfg=dict(type='TruncNormal', layer='Conv2d', std=0.03)), bbox_head=dict( type='SSDHead', in_channels=(96, 1280, 512, 256, 256, 128), num_classes=80, use_depthwise=True, norm_cfg=dict(type='BN', eps=0.001, momentum=0.03), act_cfg=dict(type='ReLU6'), init_cfg=dict(type='Normal', layer='Conv2d', std=0.001), # set anchor size manually instead of using the predefined # SSD300 setting. anchor_generator=dict( type='SSDAnchorGenerator', scale_major=False, strides=[16, 32, 64, 107, 160, 320], ratios=[[2, 3], [2, 3], [2, 3], [2, 3], [2, 3], [2, 3]], min_sizes=[48, 100, 150, 202, 253, 304], max_sizes=[100, 150, 202, 253, 304, 320]), bbox_coder=dict( type='DeltaXYWHBBoxCoder', target_means=[.0, .0, .0, .0], target_stds=[0.1, 0.1, 0.2, 0.2])), # model training and testing settings train_cfg=dict( assigner=dict( type='MaxIoUAssigner', pos_iou_thr=0.5, neg_iou_thr=0.5, min_pos_iou=0., ignore_iof_thr=-1, gt_max_assign_all=False), smoothl1_beta=1., allowed_border=-1, pos_weight=-1, neg_pos_ratio=3, debug=False), test_cfg=dict( nms_pre=1000, nms=dict(type='nms', iou_threshold=0.45), min_bbox_size=0, score_thr=0.02, max_per_img=200)) cudnn_benchmark = True # dataset settings dataset_type = 'CocoDataset' data_root = 'data/coco/' img_norm_cfg = dict( mean=[123.675, 116.28, 103.53], std=[58.395, 57.12, 57.375], to_rgb=True) train_pipeline = [ dict(type='LoadImageFromFile', to_float32=True), dict(type='LoadAnnotations', with_bbox=True), dict( type='PhotoMetricDistortion', brightness_delta=32, contrast_range=(0.5, 1.5), saturation_range=(0.5, 1.5), hue_delta=18), dict( type='Expand', mean=img_norm_cfg['mean'], to_rgb=img_norm_cfg['to_rgb'], ratio_range=(1, 4)), dict( type='MinIoURandomCrop', min_ious=(0.1, 0.3, 0.5, 0.7, 0.9), min_crop_size=0.3), dict(type='Resize', img_scale=(320, 320), keep_ratio=False), dict(type='Normalize', **img_norm_cfg), dict(type='RandomFlip', flip_ratio=0.5), dict(type='Pad', size_divisor=320), dict(type='DefaultFormatBundle'), dict(type='Collect', keys=['img', 'gt_bboxes', 'gt_labels']), ] test_pipeline = [ dict(type='LoadImageFromFile'), dict( type='MultiScaleFlipAug', img_scale=(320, 320), flip=False, transforms=[ dict(type='Resize', keep_ratio=False), dict(type='Normalize', **img_norm_cfg), dict(type='Pad', size_divisor=320), dict(type='ImageToTensor', keys=['img']), dict(type='Collect', keys=['img']), ]) ] data = dict( samples_per_gpu=24, workers_per_gpu=4, train=dict( _delete_=True, type='RepeatDataset', # use RepeatDataset to speed up training times=5, dataset=dict( type=dataset_type, ann_file=data_root + 'annotations/instances_train2017.json', img_prefix=data_root + 'train2017/', pipeline=train_pipeline)), val=dict(pipeline=test_pipeline), test=dict(pipeline=test_pipeline)) # optimizer optimizer = dict(type='SGD', lr=0.015, momentum=0.9, weight_decay=4.0e-5) optimizer_config = dict(grad_clip=None) # learning policy lr_config = dict( policy='CosineAnnealing', warmup='linear', warmup_iters=500, warmup_ratio=0.001, min_lr=0) runner = dict(type='EpochBasedRunner', max_epochs=120) # Avoid evaluation and saving weights too frequently evaluation = dict(interval=5, metric='bbox') checkpoint_config = dict(interval=5) custom_hooks = [ dict(type='NumClassCheckHook'), dict(type='CheckInvalidLossHook', interval=50, priority='VERY_LOW') ]
4,756
31.582192
77
py
PseCo
PseCo-master/thirdparty/mmdetection/configs/nas_fpn/retinanet_r50_fpn_crop640_50e_coco.py
_base_ = [ '../_base_/models/retinanet_r50_fpn.py', '../_base_/datasets/coco_detection.py', '../_base_/default_runtime.py' ] cudnn_benchmark = True norm_cfg = dict(type='BN', requires_grad=True) model = dict( backbone=dict( type='ResNet', depth=50, num_stages=4, out_indices=(0, 1, 2, 3), frozen_stages=1, norm_cfg=norm_cfg, norm_eval=False, style='pytorch', init_cfg=dict(type='Pretrained', checkpoint='torchvision://resnet50')), neck=dict( relu_before_extra_convs=True, no_norm_on_lateral=True, norm_cfg=norm_cfg), bbox_head=dict(type='RetinaSepBNHead', num_ins=5, norm_cfg=norm_cfg), # training and testing settings train_cfg=dict(assigner=dict(neg_iou_thr=0.5))) # dataset settings img_norm_cfg = dict( mean=[123.675, 116.28, 103.53], std=[58.395, 57.12, 57.375], to_rgb=True) train_pipeline = [ dict(type='LoadImageFromFile'), dict(type='LoadAnnotations', with_bbox=True), dict( type='Resize', img_scale=(640, 640), ratio_range=(0.8, 1.2), keep_ratio=True), dict(type='RandomCrop', crop_size=(640, 640)), dict(type='RandomFlip', flip_ratio=0.5), dict(type='Normalize', **img_norm_cfg), dict(type='Pad', size=(640, 640)), dict(type='DefaultFormatBundle'), dict(type='Collect', keys=['img', 'gt_bboxes', 'gt_labels']), ] test_pipeline = [ dict(type='LoadImageFromFile'), dict( type='MultiScaleFlipAug', img_scale=(640, 640), flip=False, transforms=[ dict(type='Resize', keep_ratio=True), dict(type='RandomFlip'), dict(type='Normalize', **img_norm_cfg), dict(type='Pad', size_divisor=64), dict(type='ImageToTensor', keys=['img']), dict(type='Collect', keys=['img']), ]) ] data = dict( samples_per_gpu=8, workers_per_gpu=4, train=dict(pipeline=train_pipeline), val=dict(pipeline=test_pipeline), test=dict(pipeline=test_pipeline)) # optimizer optimizer = dict( type='SGD', lr=0.08, momentum=0.9, weight_decay=0.0001, paramwise_cfg=dict(norm_decay_mult=0, bypass_duplicate=True)) optimizer_config = dict(grad_clip=None) # learning policy lr_config = dict( policy='step', warmup='linear', warmup_iters=1000, warmup_ratio=0.1, step=[30, 40]) # runtime settings runner = dict(type='EpochBasedRunner', max_epochs=50)
2,488
29.728395
79
py
PseCo
PseCo-master/thirdparty/mmdetection/configs/nas_fpn/retinanet_r50_nasfpn_crop640_50e_coco.py
_base_ = [ '../_base_/models/retinanet_r50_fpn.py', '../_base_/datasets/coco_detection.py', '../_base_/default_runtime.py' ] cudnn_benchmark = True # model settings norm_cfg = dict(type='BN', requires_grad=True) model = dict( type='RetinaNet', backbone=dict( type='ResNet', depth=50, num_stages=4, out_indices=(0, 1, 2, 3), frozen_stages=1, norm_cfg=norm_cfg, norm_eval=False, style='pytorch', init_cfg=dict(type='Pretrained', checkpoint='torchvision://resnet50')), neck=dict(type='NASFPN', stack_times=7, norm_cfg=norm_cfg), bbox_head=dict(type='RetinaSepBNHead', num_ins=5, norm_cfg=norm_cfg), # training and testing settings train_cfg=dict(assigner=dict(neg_iou_thr=0.5))) # dataset settings img_norm_cfg = dict( mean=[123.675, 116.28, 103.53], std=[58.395, 57.12, 57.375], to_rgb=True) train_pipeline = [ dict(type='LoadImageFromFile'), dict(type='LoadAnnotations', with_bbox=True), dict( type='Resize', img_scale=(640, 640), ratio_range=(0.8, 1.2), keep_ratio=True), dict(type='RandomCrop', crop_size=(640, 640)), dict(type='RandomFlip', flip_ratio=0.5), dict(type='Normalize', **img_norm_cfg), dict(type='Pad', size=(640, 640)), dict(type='DefaultFormatBundle'), dict(type='Collect', keys=['img', 'gt_bboxes', 'gt_labels']), ] test_pipeline = [ dict(type='LoadImageFromFile'), dict( type='MultiScaleFlipAug', img_scale=(640, 640), flip=False, transforms=[ dict(type='Resize', keep_ratio=True), dict(type='RandomFlip'), dict(type='Normalize', **img_norm_cfg), dict(type='Pad', size_divisor=128), dict(type='ImageToTensor', keys=['img']), dict(type='Collect', keys=['img']), ]) ] data = dict( samples_per_gpu=8, workers_per_gpu=4, train=dict(pipeline=train_pipeline), val=dict(pipeline=test_pipeline), test=dict(pipeline=test_pipeline)) # optimizer optimizer = dict( type='SGD', lr=0.08, momentum=0.9, weight_decay=0.0001, paramwise_cfg=dict(norm_decay_mult=0, bypass_duplicate=True)) optimizer_config = dict(grad_clip=None) # learning policy lr_config = dict( policy='step', warmup='linear', warmup_iters=1000, warmup_ratio=0.1, step=[30, 40]) # runtime settings runner = dict(type='EpochBasedRunner', max_epochs=50)
2,478
29.9875
79
py
PseCo
PseCo-master/thirdparty/mmdetection/configs/paa/paa_r50_fpn_1x_coco.py
_base_ = [ '../_base_/datasets/coco_detection.py', '../_base_/schedules/schedule_1x.py', '../_base_/default_runtime.py' ] model = dict( type='PAA', backbone=dict( type='ResNet', depth=50, num_stages=4, out_indices=(0, 1, 2, 3), frozen_stages=1, norm_cfg=dict(type='BN', requires_grad=True), norm_eval=True, style='pytorch', init_cfg=dict(type='Pretrained', checkpoint='torchvision://resnet50')), neck=dict( type='FPN', in_channels=[256, 512, 1024, 2048], out_channels=256, start_level=1, add_extra_convs='on_output', num_outs=5), bbox_head=dict( type='PAAHead', reg_decoded_bbox=True, score_voting=True, topk=9, num_classes=80, in_channels=256, stacked_convs=4, feat_channels=256, anchor_generator=dict( type='AnchorGenerator', ratios=[1.0], octave_base_scale=8, scales_per_octave=1, strides=[8, 16, 32, 64, 128]), bbox_coder=dict( type='DeltaXYWHBBoxCoder', target_means=[.0, .0, .0, .0], target_stds=[0.1, 0.1, 0.2, 0.2]), loss_cls=dict( type='FocalLoss', use_sigmoid=True, gamma=2.0, alpha=0.25, loss_weight=1.0), loss_bbox=dict(type='GIoULoss', loss_weight=1.3), loss_centerness=dict( type='CrossEntropyLoss', use_sigmoid=True, loss_weight=0.5)), # training and testing settings train_cfg=dict( assigner=dict( type='MaxIoUAssigner', pos_iou_thr=0.1, neg_iou_thr=0.1, min_pos_iou=0, ignore_iof_thr=-1), allowed_border=-1, pos_weight=-1, debug=False), test_cfg=dict( nms_pre=1000, min_bbox_size=0, score_thr=0.05, nms=dict(type='nms', iou_threshold=0.6), max_per_img=100)) # optimizer optimizer = dict(type='SGD', lr=0.01, momentum=0.9, weight_decay=0.0001)
2,120
28.873239
79
py
PseCo
PseCo-master/thirdparty/mmdetection/configs/paa/paa_r101_fpn_mstrain_3x_coco.py
_base_ = './paa_r50_fpn_mstrain_3x_coco.py' model = dict( backbone=dict( depth=101, init_cfg=dict(type='Pretrained', checkpoint='torchvision://resnet101')))
199
27.571429
61
py
PseCo
PseCo-master/thirdparty/mmdetection/configs/paa/paa_r50_fpn_2x_coco.py
_base_ = './paa_r50_fpn_1x_coco.py' lr_config = dict(step=[16, 22]) runner = dict(type='EpochBasedRunner', max_epochs=24)
122
29.75
53
py
PseCo
PseCo-master/thirdparty/mmdetection/configs/paa/paa_r101_fpn_1x_coco.py
_base_ = './paa_r50_fpn_1x_coco.py' model = dict( backbone=dict( depth=101, init_cfg=dict(type='Pretrained', checkpoint='torchvision://resnet101')))
191
26.428571
61
py
PseCo
PseCo-master/thirdparty/mmdetection/configs/paa/paa_r50_fpn_1.5x_coco.py
_base_ = './paa_r50_fpn_1x_coco.py' lr_config = dict(step=[12, 16]) runner = dict(type='EpochBasedRunner', max_epochs=18)
122
29.75
53
py
PseCo
PseCo-master/thirdparty/mmdetection/configs/paa/paa_r50_fpn_mstrain_3x_coco.py
_base_ = './paa_r50_fpn_1x_coco.py' img_norm_cfg = dict( mean=[123.675, 116.28, 103.53], std=[58.395, 57.12, 57.375], to_rgb=True) train_pipeline = [ dict(type='LoadImageFromFile'), dict(type='LoadAnnotations', with_bbox=True), dict( type='Resize', img_scale=[(1333, 640), (1333, 800)], multiscale_mode='range', keep_ratio=True), dict(type='RandomFlip', flip_ratio=0.5), dict(type='Normalize', **img_norm_cfg), dict(type='Pad', size_divisor=32), dict(type='DefaultFormatBundle'), dict(type='Collect', keys=['img', 'gt_bboxes', 'gt_labels']), ] data = dict(train=dict(pipeline=train_pipeline)) lr_config = dict(step=[28, 34]) runner = dict(type='EpochBasedRunner', max_epochs=36)
747
34.619048
77
py
PseCo
PseCo-master/thirdparty/mmdetection/configs/paa/paa_r101_fpn_2x_coco.py
_base_ = './paa_r101_fpn_1x_coco.py' lr_config = dict(step=[16, 22]) runner = dict(type='EpochBasedRunner', max_epochs=24)
123
30
53
py
PseCo
PseCo-master/thirdparty/mmdetection/configs/yolact/yolact_r50_1x8_coco.py
_base_ = '../_base_/default_runtime.py' # model settings img_size = 550 model = dict( type='YOLACT', backbone=dict( type='ResNet', depth=50, num_stages=4, out_indices=(0, 1, 2, 3), frozen_stages=-1, # do not freeze stem norm_cfg=dict(type='BN', requires_grad=True), norm_eval=False, # update the statistics of bn zero_init_residual=False, style='pytorch', init_cfg=dict(type='Pretrained', checkpoint='torchvision://resnet50')), neck=dict( type='FPN', in_channels=[256, 512, 1024, 2048], out_channels=256, start_level=1, add_extra_convs='on_input', num_outs=5, upsample_cfg=dict(mode='bilinear')), bbox_head=dict( type='YOLACTHead', num_classes=80, in_channels=256, feat_channels=256, anchor_generator=dict( type='AnchorGenerator', octave_base_scale=3, scales_per_octave=1, base_sizes=[8, 16, 32, 64, 128], ratios=[0.5, 1.0, 2.0], strides=[550.0 / x for x in [69, 35, 18, 9, 5]], centers=[(550 * 0.5 / x, 550 * 0.5 / x) for x in [69, 35, 18, 9, 5]]), bbox_coder=dict( type='DeltaXYWHBBoxCoder', target_means=[.0, .0, .0, .0], target_stds=[0.1, 0.1, 0.2, 0.2]), loss_cls=dict( type='CrossEntropyLoss', use_sigmoid=False, reduction='none', loss_weight=1.0), loss_bbox=dict(type='SmoothL1Loss', beta=1.0, loss_weight=1.5), num_head_convs=1, num_protos=32, use_ohem=True), mask_head=dict( type='YOLACTProtonet', in_channels=256, num_protos=32, num_classes=80, max_masks_to_train=100, loss_mask_weight=6.125), segm_head=dict( type='YOLACTSegmHead', num_classes=80, in_channels=256, loss_segm=dict( type='CrossEntropyLoss', use_sigmoid=True, loss_weight=1.0)), # training and testing settings train_cfg=dict( assigner=dict( type='MaxIoUAssigner', pos_iou_thr=0.5, neg_iou_thr=0.4, min_pos_iou=0., ignore_iof_thr=-1, gt_max_assign_all=False), # smoothl1_beta=1., allowed_border=-1, pos_weight=-1, neg_pos_ratio=3, debug=False), test_cfg=dict( nms_pre=1000, min_bbox_size=0, score_thr=0.05, iou_thr=0.5, top_k=200, max_per_img=100)) # dataset settings dataset_type = 'CocoDataset' data_root = 'data/coco/' img_norm_cfg = dict( mean=[123.68, 116.78, 103.94], std=[58.40, 57.12, 57.38], to_rgb=True) train_pipeline = [ dict(type='LoadImageFromFile', to_float32=True), dict(type='LoadAnnotations', with_bbox=True, with_mask=True), dict(type='FilterAnnotations', min_gt_bbox_wh=(4.0, 4.0)), dict( type='PhotoMetricDistortion', brightness_delta=32, contrast_range=(0.5, 1.5), saturation_range=(0.5, 1.5), hue_delta=18), dict( type='Expand', mean=img_norm_cfg['mean'], to_rgb=img_norm_cfg['to_rgb'], ratio_range=(1, 4)), dict( type='MinIoURandomCrop', min_ious=(0.1, 0.3, 0.5, 0.7, 0.9), min_crop_size=0.3), dict(type='Resize', img_scale=(img_size, img_size), keep_ratio=False), dict(type='Normalize', **img_norm_cfg), dict(type='RandomFlip', flip_ratio=0.5), dict(type='DefaultFormatBundle'), dict(type='Collect', keys=['img', 'gt_bboxes', 'gt_labels', 'gt_masks']), ] test_pipeline = [ dict(type='LoadImageFromFile'), dict( type='MultiScaleFlipAug', img_scale=(img_size, img_size), flip=False, transforms=[ dict(type='Resize', keep_ratio=False), dict(type='Normalize', **img_norm_cfg), dict(type='ImageToTensor', keys=['img']), dict(type='Collect', keys=['img']), ]) ] data = dict( samples_per_gpu=8, workers_per_gpu=4, train=dict( type=dataset_type, ann_file=data_root + 'annotations/instances_train2017.json', img_prefix=data_root + 'train2017/', pipeline=train_pipeline), val=dict( type=dataset_type, ann_file=data_root + 'annotations/instances_val2017.json', img_prefix=data_root + 'val2017/', pipeline=test_pipeline), test=dict( type=dataset_type, ann_file=data_root + 'annotations/instances_val2017.json', img_prefix=data_root + 'val2017/', pipeline=test_pipeline)) # optimizer optimizer = dict(type='SGD', lr=1e-3, momentum=0.9, weight_decay=5e-4) optimizer_config = dict() # learning policy lr_config = dict( policy='step', warmup='linear', warmup_iters=500, warmup_ratio=0.1, step=[20, 42, 49, 52]) runner = dict(type='EpochBasedRunner', max_epochs=55) cudnn_benchmark = True evaluation = dict(metric=['bbox', 'segm'])
5,103
30.701863
79
py
PseCo
PseCo-master/thirdparty/mmdetection/configs/yolact/yolact_r101_1x8_coco.py
_base_ = './yolact_r50_1x8_coco.py' model = dict( backbone=dict( depth=101, init_cfg=dict(type='Pretrained', checkpoint='torchvision://resnet101')))
192
23.125
61
py
PseCo
PseCo-master/thirdparty/mmdetection/configs/yolact/yolact_r50_8x8_coco.py
_base_ = 'yolact_r50_1x8_coco.py' optimizer = dict(type='SGD', lr=8e-3, momentum=0.9, weight_decay=5e-4) optimizer_config = dict(grad_clip=dict(max_norm=35, norm_type=2)) # learning policy lr_config = dict( policy='step', warmup='linear', warmup_iters=1000, warmup_ratio=0.1, step=[20, 42, 49, 52])
320
25.75
70
py
PseCo
PseCo-master/thirdparty/mmdetection/configs/cornernet/cornernet_hourglass104_mstest_8x6_210e_coco.py
_base_ = [ '../_base_/default_runtime.py', '../_base_/datasets/coco_detection.py' ] # model settings model = dict( type='CornerNet', backbone=dict( type='HourglassNet', downsample_times=5, num_stacks=2, stage_channels=[256, 256, 384, 384, 384, 512], stage_blocks=[2, 2, 2, 2, 2, 4], norm_cfg=dict(type='BN', requires_grad=True)), neck=None, bbox_head=dict( type='CornerHead', num_classes=80, in_channels=256, num_feat_levels=2, corner_emb_channels=1, loss_heatmap=dict( type='GaussianFocalLoss', alpha=2.0, gamma=4.0, loss_weight=1), loss_embedding=dict( type='AssociativeEmbeddingLoss', pull_weight=0.10, push_weight=0.10), loss_offset=dict(type='SmoothL1Loss', beta=1.0, loss_weight=1)), # training and testing settings train_cfg=None, test_cfg=dict( corner_topk=100, local_maximum_kernel=3, distance_threshold=0.5, score_thr=0.05, max_per_img=100, nms=dict(type='soft_nms', iou_threshold=0.5, method='gaussian'))) # data settings img_norm_cfg = dict( mean=[123.675, 116.28, 103.53], std=[58.395, 57.12, 57.375], to_rgb=True) train_pipeline = [ dict(type='LoadImageFromFile', to_float32=True), dict(type='LoadAnnotations', with_bbox=True), dict( type='PhotoMetricDistortion', brightness_delta=32, contrast_range=(0.5, 1.5), saturation_range=(0.5, 1.5), hue_delta=18), dict( type='RandomCenterCropPad', crop_size=(511, 511), ratios=(0.6, 0.7, 0.8, 0.9, 1.0, 1.1, 1.2, 1.3), test_mode=False, test_pad_mode=None, **img_norm_cfg), dict(type='Resize', img_scale=(511, 511), keep_ratio=False), dict(type='RandomFlip', flip_ratio=0.5), dict(type='Normalize', **img_norm_cfg), dict(type='DefaultFormatBundle'), dict(type='Collect', keys=['img', 'gt_bboxes', 'gt_labels']), ] test_pipeline = [ dict(type='LoadImageFromFile', to_float32=True), dict( type='MultiScaleFlipAug', scale_factor=1.0, flip=True, transforms=[ dict(type='Resize'), dict( type='RandomCenterCropPad', crop_size=None, ratios=None, border=None, test_mode=True, test_pad_mode=['logical_or', 127], **img_norm_cfg), dict(type='RandomFlip'), dict(type='Normalize', **img_norm_cfg), dict(type='ImageToTensor', keys=['img']), dict( type='Collect', keys=['img'], meta_keys=('filename', 'ori_shape', 'img_shape', 'pad_shape', 'scale_factor', 'flip', 'img_norm_cfg', 'border')), ]) ] data = dict( samples_per_gpu=6, workers_per_gpu=3, train=dict(pipeline=train_pipeline), val=dict(pipeline=test_pipeline), test=dict(pipeline=test_pipeline)) # optimizer optimizer = dict(type='Adam', lr=0.0005) optimizer_config = dict(grad_clip=dict(max_norm=35, norm_type=2)) # learning policy lr_config = dict( policy='step', warmup='linear', warmup_iters=500, warmup_ratio=1.0 / 3, step=[180]) runner = dict(type='EpochBasedRunner', max_epochs=210)
3,404
31.122642
78
py
PseCo
PseCo-master/thirdparty/mmdetection/configs/cornernet/cornernet_hourglass104_mstest_10x5_210e_coco.py
_base_ = [ '../_base_/default_runtime.py', '../_base_/datasets/coco_detection.py' ] # model settings model = dict( type='CornerNet', backbone=dict( type='HourglassNet', downsample_times=5, num_stacks=2, stage_channels=[256, 256, 384, 384, 384, 512], stage_blocks=[2, 2, 2, 2, 2, 4], norm_cfg=dict(type='BN', requires_grad=True)), neck=None, bbox_head=dict( type='CornerHead', num_classes=80, in_channels=256, num_feat_levels=2, corner_emb_channels=1, loss_heatmap=dict( type='GaussianFocalLoss', alpha=2.0, gamma=4.0, loss_weight=1), loss_embedding=dict( type='AssociativeEmbeddingLoss', pull_weight=0.10, push_weight=0.10), loss_offset=dict(type='SmoothL1Loss', beta=1.0, loss_weight=1)), # training and testing settings train_cfg=None, test_cfg=dict( corner_topk=100, local_maximum_kernel=3, distance_threshold=0.5, score_thr=0.05, max_per_img=100, nms=dict(type='soft_nms', iou_threshold=0.5, method='gaussian'))) # data settings img_norm_cfg = dict( mean=[123.675, 116.28, 103.53], std=[58.395, 57.12, 57.375], to_rgb=True) train_pipeline = [ dict(type='LoadImageFromFile', to_float32=True), dict(type='LoadAnnotations', with_bbox=True), dict( type='PhotoMetricDistortion', brightness_delta=32, contrast_range=(0.5, 1.5), saturation_range=(0.5, 1.5), hue_delta=18), dict( type='RandomCenterCropPad', crop_size=(511, 511), ratios=(0.6, 0.7, 0.8, 0.9, 1.0, 1.1, 1.2, 1.3), test_mode=False, test_pad_mode=None, **img_norm_cfg), dict(type='Resize', img_scale=(511, 511), keep_ratio=False), dict(type='RandomFlip', flip_ratio=0.5), dict(type='Normalize', **img_norm_cfg), dict(type='DefaultFormatBundle'), dict(type='Collect', keys=['img', 'gt_bboxes', 'gt_labels']), ] test_pipeline = [ dict(type='LoadImageFromFile', to_float32=True), dict( type='MultiScaleFlipAug', scale_factor=1.0, flip=True, transforms=[ dict(type='Resize'), dict( type='RandomCenterCropPad', crop_size=None, ratios=None, border=None, test_mode=True, test_pad_mode=['logical_or', 127], **img_norm_cfg), dict(type='RandomFlip'), dict(type='Normalize', **img_norm_cfg), dict(type='ImageToTensor', keys=['img']), dict( type='Collect', keys=['img'], meta_keys=('filename', 'ori_shape', 'img_shape', 'pad_shape', 'scale_factor', 'flip', 'img_norm_cfg', 'border')), ]) ] data = dict( samples_per_gpu=5, workers_per_gpu=3, train=dict(pipeline=train_pipeline), val=dict(pipeline=test_pipeline), test=dict(pipeline=test_pipeline)) # optimizer optimizer = dict(type='Adam', lr=0.0005) optimizer_config = dict(grad_clip=dict(max_norm=35, norm_type=2)) # learning policy lr_config = dict( policy='step', warmup='linear', warmup_iters=500, warmup_ratio=1.0 / 3, step=[180]) runner = dict(type='EpochBasedRunner', max_epochs=210)
3,404
31.122642
78
py
PseCo
PseCo-master/thirdparty/mmdetection/configs/cornernet/cornernet_hourglass104_mstest_32x3_210e_coco.py
_base_ = [ '../_base_/default_runtime.py', '../_base_/datasets/coco_detection.py' ] # model settings model = dict( type='CornerNet', backbone=dict( type='HourglassNet', downsample_times=5, num_stacks=2, stage_channels=[256, 256, 384, 384, 384, 512], stage_blocks=[2, 2, 2, 2, 2, 4], norm_cfg=dict(type='BN', requires_grad=True)), neck=None, bbox_head=dict( type='CornerHead', num_classes=80, in_channels=256, num_feat_levels=2, corner_emb_channels=1, loss_heatmap=dict( type='GaussianFocalLoss', alpha=2.0, gamma=4.0, loss_weight=1), loss_embedding=dict( type='AssociativeEmbeddingLoss', pull_weight=0.10, push_weight=0.10), loss_offset=dict(type='SmoothL1Loss', beta=1.0, loss_weight=1)), # training and testing settings train_cfg=None, test_cfg=dict( corner_topk=100, local_maximum_kernel=3, distance_threshold=0.5, score_thr=0.05, max_per_img=100, nms=dict(type='soft_nms', iou_threshold=0.5, method='gaussian'))) # data settings img_norm_cfg = dict( mean=[123.675, 116.28, 103.53], std=[58.395, 57.12, 57.375], to_rgb=True) train_pipeline = [ dict(type='LoadImageFromFile', to_float32=True), dict(type='LoadAnnotations', with_bbox=True), dict( type='PhotoMetricDistortion', brightness_delta=32, contrast_range=(0.5, 1.5), saturation_range=(0.5, 1.5), hue_delta=18), dict( type='RandomCenterCropPad', crop_size=(511, 511), ratios=(0.6, 0.7, 0.8, 0.9, 1.0, 1.1, 1.2, 1.3), test_mode=False, test_pad_mode=None, **img_norm_cfg), dict(type='Resize', img_scale=(511, 511), keep_ratio=False), dict(type='RandomFlip', flip_ratio=0.5), dict(type='Normalize', **img_norm_cfg), dict(type='DefaultFormatBundle'), dict(type='Collect', keys=['img', 'gt_bboxes', 'gt_labels']), ] test_pipeline = [ dict(type='LoadImageFromFile', to_float32=True), dict( type='MultiScaleFlipAug', scale_factor=1.0, flip=True, transforms=[ dict(type='Resize'), dict( type='RandomCenterCropPad', crop_size=None, ratios=None, border=None, test_mode=True, test_pad_mode=['logical_or', 127], **img_norm_cfg), dict(type='RandomFlip'), dict(type='Normalize', **img_norm_cfg), dict(type='ImageToTensor', keys=['img']), dict( type='Collect', keys=['img'], meta_keys=('filename', 'ori_shape', 'img_shape', 'pad_shape', 'scale_factor', 'flip', 'img_norm_cfg', 'border')), ]) ] data = dict( samples_per_gpu=3, workers_per_gpu=3, train=dict(pipeline=train_pipeline), val=dict(pipeline=test_pipeline), test=dict(pipeline=test_pipeline)) # optimizer optimizer = dict(type='Adam', lr=0.0005) optimizer_config = dict(grad_clip=dict(max_norm=35, norm_type=2)) # learning policy lr_config = dict( policy='step', warmup='linear', warmup_iters=500, warmup_ratio=1.0 / 3, step=[180]) runner = dict(type='EpochBasedRunner', max_epochs=210)
3,404
31.122642
78
py
PseCo
PseCo-master/thirdparty/mmdetection/configs/fp16/mask_rcnn_r50_fpn_fp16_mdconv_c3-c5_1x_coco.py
_base_ = '../mask_rcnn/mask_rcnn_r50_fpn_1x_coco.py' model = dict( backbone=dict( dcn=dict(type='DCNv2', deform_groups=1, fallback_on_stride=False), stage_with_dcn=(False, True, True, True))) fp16 = dict(loss_scale=512.)
242
29.375
74
py
PseCo
PseCo-master/thirdparty/mmdetection/configs/fp16/mask_rcnn_r50_fpn_fp16_dconv_c3-c5_1x_coco.py
_base_ = '../mask_rcnn/mask_rcnn_r50_fpn_1x_coco.py' model = dict( backbone=dict( dcn=dict(type='DCN', deform_groups=1, fallback_on_stride=False), stage_with_dcn=(False, True, True, True))) fp16 = dict(loss_scale=512.)
240
29.125
72
py
PseCo
PseCo-master/thirdparty/mmdetection/configs/fp16/mask_rcnn_r50_fpn_fp16_1x_coco.py
_base_ = '../mask_rcnn/mask_rcnn_r50_fpn_1x_coco.py' # fp16 settings fp16 = dict(loss_scale=512.)
98
23.75
52
py
PseCo
PseCo-master/thirdparty/mmdetection/configs/fp16/faster_rcnn_r50_fpn_fp16_1x_coco.py
_base_ = '../faster_rcnn/faster_rcnn_r50_fpn_1x_coco.py' # fp16 settings fp16 = dict(loss_scale=512.)
102
24.75
56
py
PseCo
PseCo-master/thirdparty/mmdetection/configs/fp16/retinanet_r50_fpn_fp16_1x_coco.py
_base_ = '../retinanet/retinanet_r50_fpn_1x_coco.py' # fp16 settings fp16 = dict(loss_scale=512.)
98
23.75
52
py
PseCo
PseCo-master/thirdparty/mmdetection/configs/point_rend/point_rend_r50_caffe_fpn_mstrain_1x_coco.py
_base_ = '../mask_rcnn/mask_rcnn_r50_caffe_fpn_mstrain_1x_coco.py' # model settings model = dict( type='PointRend', roi_head=dict( type='PointRendRoIHead', mask_roi_extractor=dict( type='GenericRoIExtractor', aggregation='concat', roi_layer=dict( _delete_=True, type='SimpleRoIAlign', output_size=14), out_channels=256, featmap_strides=[4]), mask_head=dict( _delete_=True, type='CoarseMaskHead', num_fcs=2, in_channels=256, conv_out_channels=256, fc_out_channels=1024, num_classes=80, loss_mask=dict( type='CrossEntropyLoss', use_mask=True, loss_weight=1.0)), point_head=dict( type='MaskPointHead', num_fcs=3, in_channels=256, fc_channels=256, num_classes=80, coarse_pred_each_layer=True, loss_point=dict( type='CrossEntropyLoss', use_mask=True, loss_weight=1.0))), # model training and testing settings train_cfg=dict( rcnn=dict( mask_size=7, num_points=14 * 14, oversample_ratio=3, importance_sample_ratio=0.75)), test_cfg=dict( rcnn=dict( subdivision_steps=5, subdivision_num_points=28 * 28, scale_factor=2)))
1,453
31.311111
75
py
PseCo
PseCo-master/thirdparty/mmdetection/configs/point_rend/point_rend_r50_caffe_fpn_mstrain_3x_coco.py
_base_ = './point_rend_r50_caffe_fpn_mstrain_1x_coco.py' # learning policy lr_config = dict(step=[28, 34]) runner = dict(type='EpochBasedRunner', max_epochs=36)
161
31.4
56
py
PseCo
PseCo-master/thirdparty/mmdetection/configs/detectors/detectors_htc_r101_20e_coco.py
_base_ = '../htc/htc_r101_fpn_20e_coco.py' model = dict( backbone=dict( type='DetectoRS_ResNet', conv_cfg=dict(type='ConvAWS'), sac=dict(type='SAC', use_deform=True), stage_with_sac=(False, True, True, True), output_img=True), neck=dict( type='RFP', rfp_steps=2, aspp_out_channels=64, aspp_dilations=(1, 3, 6, 1), rfp_backbone=dict( rfp_inplanes=256, type='DetectoRS_ResNet', depth=101, num_stages=4, out_indices=(0, 1, 2, 3), frozen_stages=1, norm_cfg=dict(type='BN', requires_grad=True), norm_eval=True, conv_cfg=dict(type='ConvAWS'), sac=dict(type='SAC', use_deform=True), stage_with_sac=(False, True, True, True), pretrained='torchvision://resnet101', style='pytorch')))
920
30.758621
57
py
PseCo
PseCo-master/thirdparty/mmdetection/configs/detectors/detectors_cascade_rcnn_r50_1x_coco.py
_base_ = [ '../_base_/models/cascade_rcnn_r50_fpn.py', '../_base_/datasets/coco_detection.py', '../_base_/schedules/schedule_1x.py', '../_base_/default_runtime.py' ] model = dict( backbone=dict( type='DetectoRS_ResNet', conv_cfg=dict(type='ConvAWS'), sac=dict(type='SAC', use_deform=True), stage_with_sac=(False, True, True, True), output_img=True), neck=dict( type='RFP', rfp_steps=2, aspp_out_channels=64, aspp_dilations=(1, 3, 6, 1), rfp_backbone=dict( rfp_inplanes=256, type='DetectoRS_ResNet', depth=50, num_stages=4, out_indices=(0, 1, 2, 3), frozen_stages=1, norm_cfg=dict(type='BN', requires_grad=True), norm_eval=True, conv_cfg=dict(type='ConvAWS'), sac=dict(type='SAC', use_deform=True), stage_with_sac=(False, True, True, True), pretrained='torchvision://resnet50', style='pytorch')))
1,053
30.939394
72
py
PseCo
PseCo-master/thirdparty/mmdetection/configs/detectors/cascade_rcnn_r50_sac_1x_coco.py
_base_ = [ '../_base_/models/cascade_rcnn_r50_fpn.py', '../_base_/datasets/coco_detection.py', '../_base_/schedules/schedule_1x.py', '../_base_/default_runtime.py' ] model = dict( backbone=dict( type='DetectoRS_ResNet', conv_cfg=dict(type='ConvAWS'), sac=dict(type='SAC', use_deform=True), stage_with_sac=(False, True, True, True)))
382
28.461538
72
py