├── README.md ├── image_classification ├── datasets.py ├── engine.py ├── main.py ├── models │ ├── convnext.py │ ├── fcaformer.py │ └── swin_transformer.py ├── optim_factory.py ├── scripts │ ├── fca_l1.sh │ ├── fca_l2.sh │ ├── fca_l3.sh │ └── fca_l4.sh └── utils.py ├── object_detection ├── configs │ ├── _base_ │ │ ├── datasets │ │ │ └── coco_instance.py │ │ ├── default_runtime.py │ │ ├── models │ │ │ ├── cascade_mask_rcnn_convnext_fpn.py │ │ │ ├── cascade_mask_rcnn_fcaformer_fpn.py │ │ │ ├── cascade_mask_rcnn_swin_fpn.py │ │ │ ├── mask_rcnn_convnext_fpn.py │ │ │ ├── mask_rcnn_fcaformer_fpn.py │ │ │ └── mask_rcnn_swin_fpn.py │ │ └── schedules │ │ │ ├── schedule_1x.py │ │ │ ├── schedule_20e.py │ │ │ └── schedule_2x.py │ └── fcaformer │ │ ├── cascade_mask_rcnn_fcaformer_l2_set1_480-800_adamw_3x_coco_in1k.py │ │ └── mask_rcnn_fcaformer_l2_set1_480-800_adamw_3x_coco_in1k.py ├── mmcv_custom │ ├── __init__.py │ ├── checkpoint.py │ ├── customized_text.py │ ├── layer_decay_optimizer_constructor.py │ └── runner │ │ ├── __init__.py │ │ ├── checkpoint.py │ │ └── epoch_based_runner.py ├── mmdet │ ├── __init__.py │ ├── apis │ │ ├── __init__.py │ │ ├── inference.py │ │ ├── test.py │ │ └── train.py │ ├── core │ │ ├── __init__.py │ │ ├── anchor │ │ │ ├── __init__.py │ │ │ ├── anchor_generator.py │ │ │ ├── builder.py │ │ │ ├── point_generator.py │ │ │ └── utils.py │ │ ├── bbox │ │ │ ├── __init__.py │ │ │ ├── assigners │ │ │ │ ├── __init__.py │ │ │ │ ├── approx_max_iou_assigner.py │ │ │ │ ├── assign_result.py │ │ │ │ ├── atss_assigner.py │ │ │ │ ├── base_assigner.py │ │ │ │ ├── center_region_assigner.py │ │ │ │ ├── grid_assigner.py │ │ │ │ ├── hungarian_assigner.py │ │ │ │ ├── max_iou_assigner.py │ │ │ │ ├── point_assigner.py │ │ │ │ └── region_assigner.py │ │ │ ├── builder.py │ │ │ ├── coder │ │ │ │ ├── __init__.py │ │ │ │ ├── base_bbox_coder.py │ │ │ │ ├── bucketing_bbox_coder.py │ │ │ │ ├── delta_xywh_bbox_coder.py │ │ │ │ ├── legacy_delta_xywh_bbox_coder.py │ │ │ │ ├── pseudo_bbox_coder.py │ │ │ │ ├── tblr_bbox_coder.py │ │ │ │ └── yolo_bbox_coder.py │ │ │ ├── demodata.py │ │ │ ├── iou_calculators │ │ │ │ ├── __init__.py │ │ │ │ ├── builder.py │ │ │ │ └── iou2d_calculator.py │ │ │ ├── match_costs │ │ │ │ ├── __init__.py │ │ │ │ ├── builder.py │ │ │ │ └── match_cost.py │ │ │ ├── samplers │ │ │ │ ├── __init__.py │ │ │ │ ├── base_sampler.py │ │ │ │ ├── combined_sampler.py │ │ │ │ ├── instance_balanced_pos_sampler.py │ │ │ │ ├── iou_balanced_neg_sampler.py │ │ │ │ ├── ohem_sampler.py │ │ │ │ ├── pseudo_sampler.py │ │ │ │ ├── random_sampler.py │ │ │ │ ├── sampling_result.py │ │ │ │ └── score_hlr_sampler.py │ │ │ └── transforms.py │ │ ├── evaluation │ │ │ ├── __init__.py │ │ │ ├── bbox_overlaps.py │ │ │ ├── class_names.py │ │ │ ├── eval_hooks.py │ │ │ ├── mean_ap.py │ │ │ └── recall.py │ │ ├── export │ │ │ ├── __init__.py │ │ │ └── pytorch2onnx.py │ │ ├── mask │ │ │ ├── __init__.py │ │ │ ├── mask_target.py │ │ │ ├── structures.py │ │ │ └── utils.py │ │ ├── post_processing │ │ │ ├── __init__.py │ │ │ ├── bbox_nms.py │ │ │ └── merge_augs.py │ │ ├── utils │ │ │ ├── __init__.py │ │ │ ├── dist_utils.py │ │ │ └── misc.py │ │ └── visualization │ │ │ ├── __init__.py │ │ │ └── image.py │ ├── datasets │ │ ├── __init__.py │ │ ├── builder.py │ │ ├── cityscapes.py │ │ ├── coco.py │ │ ├── custom.py │ │ ├── dataset_wrappers.py │ │ ├── deepfashion.py │ │ ├── lvis.py │ │ ├── pipelines │ │ │ ├── __init__.py │ │ │ ├── auto_augment.py │ │ │ ├── compose.py │ │ │ ├── formating.py │ │ │ ├── instaboost.py │ │ │ ├── loading.py │ │ │ ├── test_time_aug.py │ │ │ └── transforms.py │ │ ├── samplers │ │ │ ├── __init__.py │ │ │ ├── distributed_sampler.py │ │ │ └── group_sampler.py │ │ ├── utils.py │ │ ├── voc.py │ │ ├── wider_face.py │ │ └── xml_style.py │ ├── models │ │ ├── __init__.py │ │ ├── backbones │ │ │ ├── __init__.py │ │ │ ├── convnext.py │ │ │ ├── fcaformer.py │ │ │ ├── resnet.py │ │ │ └── swin_transformer.py │ │ ├── builder.py │ │ ├── dense_heads │ │ │ ├── __init__.py │ │ │ ├── anchor_free_head.py │ │ │ ├── anchor_head.py │ │ │ ├── atss_head.py │ │ │ ├── base_dense_head.py │ │ │ ├── cascade_rpn_head.py │ │ │ ├── centripetal_head.py │ │ │ ├── corner_head.py │ │ │ ├── dense_test_mixins.py │ │ │ ├── embedding_rpn_head.py │ │ │ ├── fcos_head.py │ │ │ ├── fovea_head.py │ │ │ ├── free_anchor_retina_head.py │ │ │ ├── fsaf_head.py │ │ │ ├── ga_retina_head.py │ │ │ ├── ga_rpn_head.py │ │ │ ├── gfl_head.py │ │ │ ├── guided_anchor_head.py │ │ │ ├── ld_head.py │ │ │ ├── nasfcos_head.py │ │ │ ├── paa_head.py │ │ │ ├── pisa_retinanet_head.py │ │ │ ├── pisa_ssd_head.py │ │ │ ├── reppoints_head.py │ │ │ ├── retina_head.py │ │ │ ├── retina_sepbn_head.py │ │ │ ├── rpn_head.py │ │ │ ├── rpn_test_mixin.py │ │ │ ├── sabl_retina_head.py │ │ │ ├── ssd_head.py │ │ │ ├── transformer_head.py │ │ │ ├── vfnet_head.py │ │ │ ├── yolact_head.py │ │ │ └── yolo_head.py │ │ ├── detectors │ │ │ ├── __init__.py │ │ │ ├── atss.py │ │ │ ├── base.py │ │ │ ├── cascade_rcnn.py │ │ │ ├── cornernet.py │ │ │ ├── detr.py │ │ │ ├── fast_rcnn.py │ │ │ ├── faster_rcnn.py │ │ │ ├── fcos.py │ │ │ ├── fovea.py │ │ │ ├── fsaf.py │ │ │ ├── gfl.py │ │ │ ├── grid_rcnn.py │ │ │ ├── htc.py │ │ │ ├── kd_one_stage.py │ │ │ ├── mask_rcnn.py │ │ │ ├── mask_scoring_rcnn.py │ │ │ ├── nasfcos.py │ │ │ ├── paa.py │ │ │ ├── point_rend.py │ │ │ ├── reppoints_detector.py │ │ │ ├── retinanet.py │ │ │ ├── rpn.py │ │ │ ├── scnet.py │ │ │ ├── single_stage.py │ │ │ ├── sparse_rcnn.py │ │ │ ├── trident_faster_rcnn.py │ │ │ ├── two_stage.py │ │ │ ├── vfnet.py │ │ │ ├── yolact.py │ │ │ └── yolo.py │ │ ├── losses │ │ │ ├── __init__.py │ │ │ ├── accuracy.py │ │ │ ├── ae_loss.py │ │ │ ├── balanced_l1_loss.py │ │ │ ├── cross_entropy_loss.py │ │ │ ├── focal_loss.py │ │ │ ├── gaussian_focal_loss.py │ │ │ ├── gfocal_loss.py │ │ │ ├── ghm_loss.py │ │ │ ├── iou_loss.py │ │ │ ├── kd_loss.py │ │ │ ├── mse_loss.py │ │ │ ├── pisa_loss.py │ │ │ ├── smooth_l1_loss.py │ │ │ ├── utils.py │ │ │ └── varifocal_loss.py │ │ ├── necks │ │ │ ├── __init__.py │ │ │ ├── bfp.py │ │ │ ├── channel_mapper.py │ │ │ ├── fpg.py │ │ │ ├── fpn.py │ │ │ ├── fpn_carafe.py │ │ │ ├── hrfpn.py │ │ │ ├── nas_fpn.py │ │ │ ├── nasfcos_fpn.py │ │ │ ├── pafpn.py │ │ │ ├── rfp.py │ │ │ └── yolo_neck.py │ │ ├── roi_heads │ │ │ ├── __init__.py │ │ │ ├── base_roi_head.py │ │ │ ├── bbox_heads │ │ │ │ ├── __init__.py │ │ │ │ ├── bbox_head.py │ │ │ │ ├── convfc_bbox_head.py │ │ │ │ ├── dii_head.py │ │ │ │ ├── double_bbox_head.py │ │ │ │ ├── sabl_head.py │ │ │ │ └── scnet_bbox_head.py │ │ │ ├── cascade_roi_head.py │ │ │ ├── double_roi_head.py │ │ │ ├── dynamic_roi_head.py │ │ │ ├── grid_roi_head.py │ │ │ ├── htc_roi_head.py │ │ │ ├── mask_heads │ │ │ │ ├── __init__.py │ │ │ │ ├── coarse_mask_head.py │ │ │ │ ├── fcn_mask_head.py │ │ │ │ ├── feature_relay_head.py │ │ │ │ ├── fused_semantic_head.py │ │ │ │ ├── global_context_head.py │ │ │ │ ├── grid_head.py │ │ │ │ ├── htc_mask_head.py │ │ │ │ ├── mask_point_head.py │ │ │ │ ├── maskiou_head.py │ │ │ │ ├── scnet_mask_head.py │ │ │ │ └── scnet_semantic_head.py │ │ │ ├── mask_scoring_roi_head.py │ │ │ ├── pisa_roi_head.py │ │ │ ├── point_rend_roi_head.py │ │ │ ├── roi_extractors │ │ │ │ ├── __init__.py │ │ │ │ ├── base_roi_extractor.py │ │ │ │ ├── generic_roi_extractor.py │ │ │ │ └── single_level_roi_extractor.py │ │ │ ├── scnet_roi_head.py │ │ │ ├── shared_heads │ │ │ │ ├── __init__.py │ │ │ │ └── res_layer.py │ │ │ ├── sparse_roi_head.py │ │ │ ├── standard_roi_head.py │ │ │ ├── test_mixins.py │ │ │ └── trident_roi_head.py │ │ └── utils │ │ │ ├── __init__.py │ │ │ ├── builder.py │ │ │ ├── gaussian_target.py │ │ │ ├── positional_encoding.py │ │ │ ├── res_layer.py │ │ │ └── transformer.py │ ├── utils │ │ ├── __init__.py │ │ ├── collect_env.py │ │ ├── contextmanagers.py │ │ ├── logger.py │ │ ├── optimizer.py │ │ ├── profiling.py │ │ ├── util_mixins.py │ │ └── util_random.py │ └── version.py ├── scripts_det │ └── fcaformer └── tools │ ├── dist_test.sh │ ├── dist_train.sh │ ├── get_flops.py │ ├── slurm_test.sh │ ├── slurm_train.sh │ ├── test.py │ └── train.py └── semantic-segmentation ├── backbone ├── __init__.py ├── beit.py ├── convnext.py ├── fcaformer.py └── model_test.py ├── configs ├── _base_ │ ├── datasets │ │ ├── ade20k.py │ │ ├── ade20k_640x640.py │ │ └── ade20k_local.py │ ├── default_runtime.py │ ├── models │ │ └── upernet_convnext.py │ └── schedules │ │ ├── schedule_160k.py │ │ └── schedule_320k.py └── fcaformer │ └── upernet_fcaformer_l2_160k_ade20k_ms.py ├── mmcv_custom ├── __init__.py ├── apex_runner │ ├── __init__.py │ ├── apex_iter_based_runner.py │ ├── checkpoint.py │ └── optimizer.py ├── checkpoint.py ├── customized_text.py ├── layer_decay_optimizer_constructor.py ├── resize_transform.py └── train_api.py ├── scripts_seg └── fcaformer └── tools ├── dist_test.sh ├── dist_train.sh ├── get_flops.py ├── test.py └── train.py /image_classification/datasets.py: -------------------------------------------------------------------------------- 1 | # Copyright (c) Meta Platforms, Inc. and affiliates. 2 | 3 | # All rights reserved. 4 | 5 | # This source code is licensed under the license found in the 6 | # LICENSE file in the root directory of this source tree. 7 | 8 | 9 | import os 10 | from torchvision import datasets, transforms 11 | 12 | from timm.data.constants import \ 13 | IMAGENET_DEFAULT_MEAN, IMAGENET_DEFAULT_STD, IMAGENET_INCEPTION_MEAN, IMAGENET_INCEPTION_STD 14 | from timm.data import create_transform 15 | 16 | def build_dataset(is_train, args): 17 | transform = build_transform(is_train, args) 18 | 19 | print("Transform = ") 20 | if isinstance(transform, tuple): 21 | for trans in transform: 22 | print(" - - - - - - - - - - ") 23 | for t in trans.transforms: 24 | print(t) 25 | else: 26 | for t in transform.transforms: 27 | print(t) 28 | print("---------------------------") 29 | 30 | if args.data_set == 'CIFAR': 31 | dataset = datasets.CIFAR100(args.data_path, train=is_train, transform=transform, download=True) 32 | nb_classes = 100 33 | elif args.data_set == 'IMNET': 34 | print("reading from datapath", args.data_path) 35 | root = os.path.join(args.data_path, 'train' if is_train else 'val') 36 | dataset = datasets.ImageFolder(root, transform=transform) 37 | nb_classes = 1000 38 | elif args.data_set == "image_folder": 39 | root = args.data_path if is_train else args.eval_data_path 40 | dataset = datasets.ImageFolder(root, transform=transform) 41 | nb_classes = args.nb_classes 42 | assert len(dataset.class_to_idx) == nb_classes 43 | else: 44 | raise NotImplementedError() 45 | print("Number of the class = %d" % nb_classes) 46 | 47 | return dataset, nb_classes 48 | 49 | 50 | def build_transform(is_train, args): 51 | resize_im = args.input_size > 32 52 | imagenet_default_mean_and_std = args.imagenet_default_mean_and_std 53 | mean = IMAGENET_INCEPTION_MEAN if not imagenet_default_mean_and_std else IMAGENET_DEFAULT_MEAN 54 | std = IMAGENET_INCEPTION_STD if not imagenet_default_mean_and_std else IMAGENET_DEFAULT_STD 55 | 56 | if is_train: 57 | # this should always dispatch to transforms_imagenet_train 58 | transform = create_transform( 59 | input_size=args.input_size, 60 | is_training=True, 61 | color_jitter=args.color_jitter, 62 | auto_augment=args.aa, 63 | interpolation=args.train_interpolation, 64 | re_prob=args.reprob, 65 | re_mode=args.remode, 66 | re_count=args.recount, 67 | mean=mean, 68 | std=std, 69 | ) 70 | if not resize_im: 71 | transform.transforms[0] = transforms.RandomCrop( 72 | args.input_size, padding=4) 73 | return transform 74 | 75 | t = [] 76 | if resize_im: 77 | # warping (no cropping) when evaluated at 384 or larger 78 | if args.input_size >= 384: 79 | t.append( 80 | transforms.Resize((args.input_size, args.input_size), 81 | interpolation=transforms.InterpolationMode.BICUBIC), 82 | ) 83 | print(f"Warping {args.input_size} size input images...") 84 | else: 85 | if args.crop_pct is None: 86 | args.crop_pct = 224 / 256 87 | size = int(args.input_size / args.crop_pct) 88 | t.append( 89 | # to maintain same ratio w.r.t. 224 images 90 | transforms.Resize(size, interpolation=transforms.InterpolationMode.BICUBIC), 91 | ) 92 | t.append(transforms.CenterCrop(args.input_size)) 93 | 94 | t.append(transforms.ToTensor()) 95 | t.append(transforms.Normalize(mean, std)) 96 | return transforms.Compose(t) 97 | -------------------------------------------------------------------------------- /image_classification/scripts/fca_l1.sh: -------------------------------------------------------------------------------- 1 | python -m torch.distributed.launch --nproc_per_node=8 ../main.py --model fcaformer_l1 --drop_path 0.0 --batch_size 128 --lr 2e-3 --update_freq 1 --model_ema true --model_ema_eval true --data_path /home/disk/data/imagenet1k --output_dir /home/disk/result/fcaformer/imgnet1k_cls/fcaformer_l1 -------------------------------------------------------------------------------- /image_classification/scripts/fca_l2.sh: -------------------------------------------------------------------------------- 1 | python -m torch.distributed.launch --nproc_per_node=8 ../main.py --model fcaformer_l2 --drop_path 0.1 --batch_size 128 --lr 2e-3 --update_freq 1 --model_ema true --model_ema_eval true --data_path /home/disk/data/imagenet1k --output_dir /home/disk/result/fcaformer/imgnet1k_cls/fcaformer_l2 -------------------------------------------------------------------------------- /image_classification/scripts/fca_l3.sh: -------------------------------------------------------------------------------- 1 | python -m torch.distributed.launch --nproc_per_node=8 ../main.py --model fcaformer_l3 --drop_path 0.2 --batch_size 128 --lr 2e-3 --update_freq 1 --model_ema true --model_ema_eval true --data_path /home/disk/data/imagenet1k --output_dir /home/disk/result/fcaformer/imagenet1k_cls/fcaformer_l3 2 | -------------------------------------------------------------------------------- /image_classification/scripts/fca_l4.sh: -------------------------------------------------------------------------------- 1 | python -m torch.distributed.launch --nproc_per_node=8 ../main.py --model fcaformer_l4 --drop_path 0.4 --batch_size 128 --lr 2e-3 --update_freq 1 --model_ema true --model_ema_eval true --data_path /home/disk/data/imagenet1k --output_dir /home/disk/result/fcaformer/imgnet1k_cls/fcaformer_l4 -------------------------------------------------------------------------------- /object_detection/configs/_base_/datasets/coco_instance.py: -------------------------------------------------------------------------------- 1 | dataset_type = 'CocoDataset' 2 | data_root = 'data/coco/' 3 | img_norm_cfg = dict( 4 | mean=[123.675, 116.28, 103.53], std=[58.395, 57.12, 57.375], to_rgb=True) 5 | train_pipeline = [ 6 | dict(type='LoadImageFromFile'), 7 | dict(type='LoadAnnotations', with_bbox=True, with_mask=True), 8 | dict(type='Resize', img_scale=(1333, 800), keep_ratio=True), 9 | dict(type='RandomFlip', flip_ratio=0.5), 10 | dict(type='Normalize', **img_norm_cfg), 11 | dict(type='Pad', size_divisor=32), 12 | dict(type='DefaultFormatBundle'), 13 | dict(type='Collect', keys=['img', 'gt_bboxes', 'gt_labels', 'gt_masks']), 14 | ] 15 | test_pipeline = [ 16 | dict(type='LoadImageFromFile'), 17 | dict( 18 | type='MultiScaleFlipAug', 19 | img_scale=(1333, 800), 20 | flip=False, 21 | transforms=[ 22 | dict(type='Resize', keep_ratio=True), 23 | dict(type='RandomFlip'), 24 | dict(type='Normalize', **img_norm_cfg), 25 | dict(type='Pad', size_divisor=32), 26 | dict(type='ImageToTensor', keys=['img']), 27 | dict(type='Collect', keys=['img']), 28 | ]) 29 | ] 30 | data = dict( 31 | samples_per_gpu=2, 32 | workers_per_gpu=2, 33 | train=dict( 34 | type=dataset_type, 35 | ann_file=data_root + 'annotations/instances_train2017.json', 36 | img_prefix=data_root + 'train2017/', 37 | pipeline=train_pipeline), 38 | val=dict( 39 | type=dataset_type, 40 | ann_file=data_root + 'annotations/instances_val2017.json', 41 | img_prefix=data_root + 'val2017/', 42 | pipeline=test_pipeline), 43 | test=dict( 44 | type=dataset_type, 45 | ann_file=data_root + 'annotations/instances_val2017.json', 46 | img_prefix=data_root + 'val2017/', 47 | pipeline=test_pipeline)) 48 | evaluation = dict(metric=['bbox', 'segm']) 49 | -------------------------------------------------------------------------------- /object_detection/configs/_base_/default_runtime.py: -------------------------------------------------------------------------------- 1 | checkpoint_config = dict(interval=1) 2 | # yapf:disable 3 | log_config = dict( 4 | interval=50, 5 | hooks=[ 6 | dict(type='CustomizedTextLoggerHook'), 7 | # dict(type='TensorboardLoggerHook') 8 | ]) 9 | # yapf:enable 10 | custom_hooks = [dict(type='NumClassCheckHook')] 11 | 12 | dist_params = dict(backend='nccl') 13 | log_level = 'INFO' 14 | load_from = None 15 | resume_from = None 16 | workflow = [('train', 1)] 17 | -------------------------------------------------------------------------------- /object_detection/configs/_base_/schedules/schedule_1x.py: -------------------------------------------------------------------------------- 1 | # optimizer 2 | optimizer = dict(type='SGD', lr=0.02, momentum=0.9, weight_decay=0.0001) 3 | optimizer_config = dict(grad_clip=None) 4 | # learning policy 5 | lr_config = dict( 6 | policy='step', 7 | warmup='linear', 8 | warmup_iters=500, 9 | warmup_ratio=0.001, 10 | step=[8, 11]) 11 | runner = dict(type='EpochBasedRunner', max_epochs=12) 12 | -------------------------------------------------------------------------------- /object_detection/configs/_base_/schedules/schedule_20e.py: -------------------------------------------------------------------------------- 1 | # optimizer 2 | optimizer = dict(type='SGD', lr=0.02, momentum=0.9, weight_decay=0.0001) 3 | optimizer_config = dict(grad_clip=None) 4 | # learning policy 5 | lr_config = dict( 6 | policy='step', 7 | warmup='linear', 8 | warmup_iters=500, 9 | warmup_ratio=0.001, 10 | step=[16, 19]) 11 | runner = dict(type='EpochBasedRunner', max_epochs=20) 12 | -------------------------------------------------------------------------------- /object_detection/configs/_base_/schedules/schedule_2x.py: -------------------------------------------------------------------------------- 1 | # optimizer 2 | optimizer = dict(type='SGD', lr=0.02, momentum=0.9, weight_decay=0.0001) 3 | optimizer_config = dict(grad_clip=None) 4 | # learning policy 5 | lr_config = dict( 6 | policy='step', 7 | warmup='linear', 8 | warmup_iters=500, 9 | warmup_ratio=0.001, 10 | step=[16, 22]) 11 | runner = dict(type='EpochBasedRunner', max_epochs=24) 12 | -------------------------------------------------------------------------------- /object_detection/configs/fcaformer/mask_rcnn_fcaformer_l2_set1_480-800_adamw_3x_coco_in1k.py: -------------------------------------------------------------------------------- 1 | _base_ = [ 2 | '../_base_/models/mask_rcnn_fcaformer_fpn.py', 3 | '../_base_/datasets/coco_instance.py', 4 | '../_base_/schedules/schedule_1x.py', '../_base_/default_runtime.py' 5 | ] 6 | 7 | model = dict( 8 | backbone=dict( 9 | in_chans=3, 10 | dims=[96, 192, 320, 480], 11 | depths=[2, 2, 7, 2], 12 | drop_path_rate=0.2, 13 | layer_scale_init_value=1.0, 14 | out_indices=[0, 1, 2, 3], 15 | ), 16 | neck=dict(in_channels=[96, 192, 384, 768])) 17 | 18 | img_norm_cfg = dict( 19 | mean=[123.675, 116.28, 103.53], std=[58.395, 57.12, 57.375], to_rgb=True) 20 | 21 | # augmentation strategy originates from DETR / Sparse RCNN 22 | train_pipeline = [ 23 | dict(type='LoadImageFromFile'), 24 | dict(type='LoadAnnotations', with_bbox=True, with_mask=True), 25 | dict(type='RandomFlip', flip_ratio=0.5), 26 | dict(type='AutoAugment', 27 | policies=[ 28 | [ 29 | dict(type='Resize', 30 | img_scale=[(480, 1333), (512, 1333), (544, 1333), (576, 1333), 31 | (608, 1333), (640, 1333), (672, 1333), (704, 1333), 32 | (736, 1333), (768, 1333), (800, 1333)], 33 | multiscale_mode='value', 34 | keep_ratio=True) 35 | ], 36 | [ 37 | dict(type='Resize', 38 | img_scale=[(400, 1333), (500, 1333), (600, 1333)], 39 | multiscale_mode='value', 40 | keep_ratio=True), 41 | dict(type='RandomCrop', 42 | crop_type='absolute_range', 43 | crop_size=(384, 600), 44 | allow_negative_crop=True), 45 | dict(type='Resize', 46 | img_scale=[(480, 1333), (512, 1333), (544, 1333), 47 | (576, 1333), (608, 1333), (640, 1333), 48 | (672, 1333), (704, 1333), (736, 1333), 49 | (768, 1333), (800, 1333)], 50 | multiscale_mode='value', 51 | override=True, 52 | keep_ratio=True) 53 | ] 54 | ]), 55 | dict(type='Normalize', **img_norm_cfg), 56 | dict(type='Pad', size_divisor=32), 57 | dict(type='DefaultFormatBundle'), 58 | dict(type='Collect', keys=['img', 'gt_bboxes', 'gt_labels', 'gt_masks']), 59 | ] 60 | data = dict(train=dict(pipeline=train_pipeline)) 61 | 62 | optimizer = dict(constructor='LearningRateDecayOptimizerConstructor', _delete_=True, type='AdamW', 63 | lr=0.0001, betas=(0.9, 0.999), weight_decay=0.05, 64 | paramwise_cfg={'decay_rate': 0.95, 65 | 'decay_type': 'layer_wise_cab', 66 | 'num_layers': 6}) 67 | 68 | lr_config = dict(step=[27, 33]) 69 | runner = dict(type='EpochBasedRunnerAmp', max_epochs=36) 70 | 71 | # do not use mmdet version fp16 72 | fp16 = None 73 | optimizer_config = dict( 74 | type="DistOptimizerHook", 75 | update_interval=1, 76 | grad_clip=None, 77 | coalesce=True, 78 | bucket_size_mb=-1, 79 | use_fp16=True, 80 | ) 81 | -------------------------------------------------------------------------------- /object_detection/mmcv_custom/__init__.py: -------------------------------------------------------------------------------- 1 | # Copyright (c) Meta Platforms, Inc. and affiliates. 2 | 3 | # All rights reserved. 4 | 5 | # This source code is licensed under the license found in the 6 | # LICENSE file in the root directory of this source tree. 7 | 8 | 9 | # -*- coding: utf-8 -*- 10 | 11 | from .checkpoint import load_checkpoint 12 | from .layer_decay_optimizer_constructor import LearningRateDecayOptimizerConstructor 13 | from .customized_text import CustomizedTextLoggerHook 14 | 15 | __all__ = ['load_checkpoint', 'LearningRateDecayOptimizerConstructor', 'CustomizedTextLoggerHook'] 16 | -------------------------------------------------------------------------------- /object_detection/mmcv_custom/runner/__init__.py: -------------------------------------------------------------------------------- 1 | # Copyright (c) Open-MMLab. All rights reserved. 2 | from .checkpoint import save_checkpoint 3 | from .epoch_based_runner import EpochBasedRunnerAmp 4 | 5 | 6 | __all__ = [ 7 | 'EpochBasedRunnerAmp', 'save_checkpoint' 8 | ] 9 | -------------------------------------------------------------------------------- /object_detection/mmcv_custom/runner/checkpoint.py: -------------------------------------------------------------------------------- 1 | # Copyright (c) Open-MMLab. All rights reserved. 2 | import os.path as osp 3 | import time 4 | from tempfile import TemporaryDirectory 5 | 6 | import torch 7 | from torch.optim import Optimizer 8 | 9 | import mmcv 10 | from mmcv.parallel import is_module_wrapper 11 | from mmcv.runner.checkpoint import weights_to_cpu, get_state_dict 12 | 13 | try: 14 | import apex 15 | except: 16 | print('apex is not installed') 17 | 18 | 19 | def save_checkpoint(model, filename, optimizer=None, meta=None): 20 | """Save checkpoint to file. 21 | 22 | The checkpoint will have 4 fields: ``meta``, ``state_dict`` and 23 | ``optimizer``, ``amp``. By default ``meta`` will contain version 24 | and time info. 25 | 26 | Args: 27 | model (Module): Module whose params are to be saved. 28 | filename (str): Checkpoint filename. 29 | optimizer (:obj:`Optimizer`, optional): Optimizer to be saved. 30 | meta (dict, optional): Metadata to be saved in checkpoint. 31 | """ 32 | if meta is None: 33 | meta = {} 34 | elif not isinstance(meta, dict): 35 | raise TypeError(f'meta must be a dict or None, but got {type(meta)}') 36 | meta.update(mmcv_version=mmcv.__version__, time=time.asctime()) 37 | 38 | if is_module_wrapper(model): 39 | model = model.module 40 | 41 | if hasattr(model, 'CLASSES') and model.CLASSES is not None: 42 | # save class name to the meta 43 | meta.update(CLASSES=model.CLASSES) 44 | 45 | checkpoint = { 46 | 'meta': meta, 47 | 'state_dict': weights_to_cpu(get_state_dict(model)) 48 | } 49 | # save optimizer state dict in the checkpoint 50 | if isinstance(optimizer, Optimizer): 51 | checkpoint['optimizer'] = optimizer.state_dict() 52 | elif isinstance(optimizer, dict): 53 | checkpoint['optimizer'] = {} 54 | for name, optim in optimizer.items(): 55 | checkpoint['optimizer'][name] = optim.state_dict() 56 | 57 | # save amp state dict in the checkpoint 58 | # checkpoint['amp'] = apex.amp.state_dict() 59 | 60 | if filename.startswith('pavi://'): 61 | try: 62 | from pavi import modelcloud 63 | from pavi.exception import NodeNotFoundError 64 | except ImportError: 65 | raise ImportError( 66 | 'Please install pavi to load checkpoint from modelcloud.') 67 | model_path = filename[7:] 68 | root = modelcloud.Folder() 69 | model_dir, model_name = osp.split(model_path) 70 | try: 71 | model = modelcloud.get(model_dir) 72 | except NodeNotFoundError: 73 | model = root.create_training_model(model_dir) 74 | with TemporaryDirectory() as tmp_dir: 75 | checkpoint_file = osp.join(tmp_dir, model_name) 76 | with open(checkpoint_file, 'wb') as f: 77 | torch.save(checkpoint, f) 78 | f.flush() 79 | model.create_file(checkpoint_file, name=model_name) 80 | else: 81 | mmcv.mkdir_or_exist(osp.dirname(filename)) 82 | # immediately flush buffer 83 | with open(filename, 'wb') as f: 84 | torch.save(checkpoint, f) 85 | f.flush() 86 | -------------------------------------------------------------------------------- /object_detection/mmdet/__init__.py: -------------------------------------------------------------------------------- 1 | import mmcv 2 | 3 | from .version import __version__, short_version 4 | 5 | 6 | def digit_version(version_str): 7 | digit_version = [] 8 | for x in version_str.split('.'): 9 | if x.isdigit(): 10 | digit_version.append(int(x)) 11 | elif x.find('rc') != -1: 12 | patch_version = x.split('rc') 13 | digit_version.append(int(patch_version[0]) - 1) 14 | digit_version.append(int(patch_version[1])) 15 | return digit_version 16 | 17 | 18 | mmcv_minimum_version = '1.2.4' 19 | mmcv_maximum_version = '1.4.0' 20 | mmcv_version = digit_version(mmcv.__version__) 21 | 22 | 23 | assert (mmcv_version >= digit_version(mmcv_minimum_version) 24 | and mmcv_version <= digit_version(mmcv_maximum_version)), \ 25 | f'MMCV=={mmcv.__version__} is used but incompatible. ' \ 26 | f'Please install mmcv>={mmcv_minimum_version}, <={mmcv_maximum_version}.' 27 | 28 | __all__ = ['__version__', 'short_version'] 29 | -------------------------------------------------------------------------------- /object_detection/mmdet/apis/__init__.py: -------------------------------------------------------------------------------- 1 | from .inference import (async_inference_detector, inference_detector, 2 | init_detector, show_result_pyplot) 3 | from .test import multi_gpu_test, single_gpu_test 4 | from .train import get_root_logger, set_random_seed, train_detector 5 | 6 | __all__ = [ 7 | 'get_root_logger', 'set_random_seed', 'train_detector', 'init_detector', 8 | 'async_inference_detector', 'inference_detector', 'show_result_pyplot', 9 | 'multi_gpu_test', 'single_gpu_test' 10 | ] 11 | -------------------------------------------------------------------------------- /object_detection/mmdet/core/__init__.py: -------------------------------------------------------------------------------- 1 | from .anchor import * # noqa: F401, F403 2 | from .bbox import * # noqa: F401, F403 3 | from .evaluation import * # noqa: F401, F403 4 | from .export import * # noqa: F401, F403 5 | from .mask import * # noqa: F401, F403 6 | from .post_processing import * # noqa: F401, F403 7 | from .utils import * # noqa: F401, F403 8 | -------------------------------------------------------------------------------- /object_detection/mmdet/core/anchor/__init__.py: -------------------------------------------------------------------------------- 1 | from .anchor_generator import (AnchorGenerator, LegacyAnchorGenerator, 2 | YOLOAnchorGenerator) 3 | from .builder import ANCHOR_GENERATORS, build_anchor_generator 4 | from .point_generator import PointGenerator 5 | from .utils import anchor_inside_flags, calc_region, images_to_levels 6 | 7 | __all__ = [ 8 | 'AnchorGenerator', 'LegacyAnchorGenerator', 'anchor_inside_flags', 9 | 'PointGenerator', 'images_to_levels', 'calc_region', 10 | 'build_anchor_generator', 'ANCHOR_GENERATORS', 'YOLOAnchorGenerator' 11 | ] 12 | -------------------------------------------------------------------------------- /object_detection/mmdet/core/anchor/builder.py: -------------------------------------------------------------------------------- 1 | from mmcv.utils import Registry, build_from_cfg 2 | 3 | ANCHOR_GENERATORS = Registry('Anchor generator') 4 | 5 | 6 | def build_anchor_generator(cfg, default_args=None): 7 | return build_from_cfg(cfg, ANCHOR_GENERATORS, default_args) 8 | -------------------------------------------------------------------------------- /object_detection/mmdet/core/anchor/point_generator.py: -------------------------------------------------------------------------------- 1 | import torch 2 | 3 | from .builder import ANCHOR_GENERATORS 4 | 5 | 6 | @ANCHOR_GENERATORS.register_module() 7 | class PointGenerator(object): 8 | 9 | def _meshgrid(self, x, y, row_major=True): 10 | xx = x.repeat(len(y)) 11 | yy = y.view(-1, 1).repeat(1, len(x)).view(-1) 12 | if row_major: 13 | return xx, yy 14 | else: 15 | return yy, xx 16 | 17 | def grid_points(self, featmap_size, stride=16, device='cuda'): 18 | feat_h, feat_w = featmap_size 19 | shift_x = torch.arange(0., feat_w, device=device) * stride 20 | shift_y = torch.arange(0., feat_h, device=device) * stride 21 | shift_xx, shift_yy = self._meshgrid(shift_x, shift_y) 22 | stride = shift_x.new_full((shift_xx.shape[0], ), stride) 23 | shifts = torch.stack([shift_xx, shift_yy, stride], dim=-1) 24 | all_points = shifts.to(device) 25 | return all_points 26 | 27 | def valid_flags(self, featmap_size, valid_size, device='cuda'): 28 | feat_h, feat_w = featmap_size 29 | valid_h, valid_w = valid_size 30 | assert valid_h <= feat_h and valid_w <= feat_w 31 | valid_x = torch.zeros(feat_w, dtype=torch.bool, device=device) 32 | valid_y = torch.zeros(feat_h, dtype=torch.bool, device=device) 33 | valid_x[:valid_w] = 1 34 | valid_y[:valid_h] = 1 35 | valid_xx, valid_yy = self._meshgrid(valid_x, valid_y) 36 | valid = valid_xx & valid_yy 37 | return valid 38 | -------------------------------------------------------------------------------- /object_detection/mmdet/core/anchor/utils.py: -------------------------------------------------------------------------------- 1 | import torch 2 | 3 | 4 | def images_to_levels(target, num_levels): 5 | """Convert targets by image to targets by feature level. 6 | 7 | [target_img0, target_img1] -> [target_level0, target_level1, ...] 8 | """ 9 | target = torch.stack(target, 0) 10 | level_targets = [] 11 | start = 0 12 | for n in num_levels: 13 | end = start + n 14 | # level_targets.append(target[:, start:end].squeeze(0)) 15 | level_targets.append(target[:, start:end]) 16 | start = end 17 | return level_targets 18 | 19 | 20 | def anchor_inside_flags(flat_anchors, 21 | valid_flags, 22 | img_shape, 23 | allowed_border=0): 24 | """Check whether the anchors are inside the border. 25 | 26 | Args: 27 | flat_anchors (torch.Tensor): Flatten anchors, shape (n, 4). 28 | valid_flags (torch.Tensor): An existing valid flags of anchors. 29 | img_shape (tuple(int)): Shape of current image. 30 | allowed_border (int, optional): The border to allow the valid anchor. 31 | Defaults to 0. 32 | 33 | Returns: 34 | torch.Tensor: Flags indicating whether the anchors are inside a \ 35 | valid range. 36 | """ 37 | img_h, img_w = img_shape[:2] 38 | if allowed_border >= 0: 39 | inside_flags = valid_flags & \ 40 | (flat_anchors[:, 0] >= -allowed_border) & \ 41 | (flat_anchors[:, 1] >= -allowed_border) & \ 42 | (flat_anchors[:, 2] < img_w + allowed_border) & \ 43 | (flat_anchors[:, 3] < img_h + allowed_border) 44 | else: 45 | inside_flags = valid_flags 46 | return inside_flags 47 | 48 | 49 | def calc_region(bbox, ratio, featmap_size=None): 50 | """Calculate a proportional bbox region. 51 | 52 | The bbox center are fixed and the new h' and w' is h * ratio and w * ratio. 53 | 54 | Args: 55 | bbox (Tensor): Bboxes to calculate regions, shape (n, 4). 56 | ratio (float): Ratio of the output region. 57 | featmap_size (tuple): Feature map size used for clipping the boundary. 58 | 59 | Returns: 60 | tuple: x1, y1, x2, y2 61 | """ 62 | x1 = torch.round((1 - ratio) * bbox[0] + ratio * bbox[2]).long() 63 | y1 = torch.round((1 - ratio) * bbox[1] + ratio * bbox[3]).long() 64 | x2 = torch.round(ratio * bbox[0] + (1 - ratio) * bbox[2]).long() 65 | y2 = torch.round(ratio * bbox[1] + (1 - ratio) * bbox[3]).long() 66 | if featmap_size is not None: 67 | x1 = x1.clamp(min=0, max=featmap_size[1]) 68 | y1 = y1.clamp(min=0, max=featmap_size[0]) 69 | x2 = x2.clamp(min=0, max=featmap_size[1]) 70 | y2 = y2.clamp(min=0, max=featmap_size[0]) 71 | return (x1, y1, x2, y2) 72 | -------------------------------------------------------------------------------- /object_detection/mmdet/core/bbox/__init__.py: -------------------------------------------------------------------------------- 1 | from .assigners import (AssignResult, BaseAssigner, CenterRegionAssigner, 2 | MaxIoUAssigner, RegionAssigner) 3 | from .builder import build_assigner, build_bbox_coder, build_sampler 4 | from .coder import (BaseBBoxCoder, DeltaXYWHBBoxCoder, PseudoBBoxCoder, 5 | TBLRBBoxCoder) 6 | from .iou_calculators import BboxOverlaps2D, bbox_overlaps 7 | from .samplers import (BaseSampler, CombinedSampler, 8 | InstanceBalancedPosSampler, IoUBalancedNegSampler, 9 | OHEMSampler, PseudoSampler, RandomSampler, 10 | SamplingResult, ScoreHLRSampler) 11 | from .transforms import (bbox2distance, bbox2result, bbox2roi, 12 | bbox_cxcywh_to_xyxy, bbox_flip, bbox_mapping, 13 | bbox_mapping_back, bbox_rescale, bbox_xyxy_to_cxcywh, 14 | distance2bbox, roi2bbox) 15 | 16 | __all__ = [ 17 | 'bbox_overlaps', 'BboxOverlaps2D', 'BaseAssigner', 'MaxIoUAssigner', 18 | 'AssignResult', 'BaseSampler', 'PseudoSampler', 'RandomSampler', 19 | 'InstanceBalancedPosSampler', 'IoUBalancedNegSampler', 'CombinedSampler', 20 | 'OHEMSampler', 'SamplingResult', 'ScoreHLRSampler', 'build_assigner', 21 | 'build_sampler', 'bbox_flip', 'bbox_mapping', 'bbox_mapping_back', 22 | 'bbox2roi', 'roi2bbox', 'bbox2result', 'distance2bbox', 'bbox2distance', 23 | 'build_bbox_coder', 'BaseBBoxCoder', 'PseudoBBoxCoder', 24 | 'DeltaXYWHBBoxCoder', 'TBLRBBoxCoder', 'CenterRegionAssigner', 25 | 'bbox_rescale', 'bbox_cxcywh_to_xyxy', 'bbox_xyxy_to_cxcywh', 26 | 'RegionAssigner' 27 | ] 28 | -------------------------------------------------------------------------------- /object_detection/mmdet/core/bbox/assigners/__init__.py: -------------------------------------------------------------------------------- 1 | from .approx_max_iou_assigner import ApproxMaxIoUAssigner 2 | from .assign_result import AssignResult 3 | from .atss_assigner import ATSSAssigner 4 | from .base_assigner import BaseAssigner 5 | from .center_region_assigner import CenterRegionAssigner 6 | from .grid_assigner import GridAssigner 7 | from .hungarian_assigner import HungarianAssigner 8 | from .max_iou_assigner import MaxIoUAssigner 9 | from .point_assigner import PointAssigner 10 | from .region_assigner import RegionAssigner 11 | 12 | __all__ = [ 13 | 'BaseAssigner', 'MaxIoUAssigner', 'ApproxMaxIoUAssigner', 'AssignResult', 14 | 'PointAssigner', 'ATSSAssigner', 'CenterRegionAssigner', 'GridAssigner', 15 | 'HungarianAssigner', 'RegionAssigner' 16 | ] 17 | -------------------------------------------------------------------------------- /object_detection/mmdet/core/bbox/assigners/base_assigner.py: -------------------------------------------------------------------------------- 1 | from abc import ABCMeta, abstractmethod 2 | 3 | 4 | class BaseAssigner(metaclass=ABCMeta): 5 | """Base assigner that assigns boxes to ground truth boxes.""" 6 | 7 | @abstractmethod 8 | def assign(self, bboxes, gt_bboxes, gt_bboxes_ignore=None, gt_labels=None): 9 | """Assign boxes to either a ground truth boxes or a negative boxes.""" 10 | -------------------------------------------------------------------------------- /object_detection/mmdet/core/bbox/builder.py: -------------------------------------------------------------------------------- 1 | from mmcv.utils import Registry, build_from_cfg 2 | 3 | BBOX_ASSIGNERS = Registry('bbox_assigner') 4 | BBOX_SAMPLERS = Registry('bbox_sampler') 5 | BBOX_CODERS = Registry('bbox_coder') 6 | 7 | 8 | def build_assigner(cfg, **default_args): 9 | """Builder of box assigner.""" 10 | return build_from_cfg(cfg, BBOX_ASSIGNERS, default_args) 11 | 12 | 13 | def build_sampler(cfg, **default_args): 14 | """Builder of box sampler.""" 15 | return build_from_cfg(cfg, BBOX_SAMPLERS, default_args) 16 | 17 | 18 | def build_bbox_coder(cfg, **default_args): 19 | """Builder of box coder.""" 20 | return build_from_cfg(cfg, BBOX_CODERS, default_args) 21 | -------------------------------------------------------------------------------- /object_detection/mmdet/core/bbox/coder/__init__.py: -------------------------------------------------------------------------------- 1 | from .base_bbox_coder import BaseBBoxCoder 2 | from .bucketing_bbox_coder import BucketingBBoxCoder 3 | from .delta_xywh_bbox_coder import DeltaXYWHBBoxCoder 4 | from .legacy_delta_xywh_bbox_coder import LegacyDeltaXYWHBBoxCoder 5 | from .pseudo_bbox_coder import PseudoBBoxCoder 6 | from .tblr_bbox_coder import TBLRBBoxCoder 7 | from .yolo_bbox_coder import YOLOBBoxCoder 8 | 9 | __all__ = [ 10 | 'BaseBBoxCoder', 'PseudoBBoxCoder', 'DeltaXYWHBBoxCoder', 11 | 'LegacyDeltaXYWHBBoxCoder', 'TBLRBBoxCoder', 'YOLOBBoxCoder', 12 | 'BucketingBBoxCoder' 13 | ] 14 | -------------------------------------------------------------------------------- /object_detection/mmdet/core/bbox/coder/base_bbox_coder.py: -------------------------------------------------------------------------------- 1 | from abc import ABCMeta, abstractmethod 2 | 3 | 4 | class BaseBBoxCoder(metaclass=ABCMeta): 5 | """Base bounding box coder.""" 6 | 7 | def __init__(self, **kwargs): 8 | pass 9 | 10 | @abstractmethod 11 | def encode(self, bboxes, gt_bboxes): 12 | """Encode deltas between bboxes and ground truth boxes.""" 13 | 14 | @abstractmethod 15 | def decode(self, bboxes, bboxes_pred): 16 | """Decode the predicted bboxes according to prediction and base 17 | boxes.""" 18 | -------------------------------------------------------------------------------- /object_detection/mmdet/core/bbox/coder/pseudo_bbox_coder.py: -------------------------------------------------------------------------------- 1 | from ..builder import BBOX_CODERS 2 | from .base_bbox_coder import BaseBBoxCoder 3 | 4 | 5 | @BBOX_CODERS.register_module() 6 | class PseudoBBoxCoder(BaseBBoxCoder): 7 | """Pseudo bounding box coder.""" 8 | 9 | def __init__(self, **kwargs): 10 | super(BaseBBoxCoder, self).__init__(**kwargs) 11 | 12 | def encode(self, bboxes, gt_bboxes): 13 | """torch.Tensor: return the given ``bboxes``""" 14 | return gt_bboxes 15 | 16 | def decode(self, bboxes, pred_bboxes): 17 | """torch.Tensor: return the given ``pred_bboxes``""" 18 | return pred_bboxes 19 | -------------------------------------------------------------------------------- /object_detection/mmdet/core/bbox/coder/yolo_bbox_coder.py: -------------------------------------------------------------------------------- 1 | import mmcv 2 | import torch 3 | 4 | from ..builder import BBOX_CODERS 5 | from .base_bbox_coder import BaseBBoxCoder 6 | 7 | 8 | @BBOX_CODERS.register_module() 9 | class YOLOBBoxCoder(BaseBBoxCoder): 10 | """YOLO BBox coder. 11 | 12 | Following `YOLO `_, this coder divide 13 | image into grids, and encode bbox (x1, y1, x2, y2) into (cx, cy, dw, dh). 14 | cx, cy in [0., 1.], denotes relative center position w.r.t the center of 15 | bboxes. dw, dh are the same as :obj:`DeltaXYWHBBoxCoder`. 16 | 17 | Args: 18 | eps (float): Min value of cx, cy when encoding. 19 | """ 20 | 21 | def __init__(self, eps=1e-6): 22 | super(BaseBBoxCoder, self).__init__() 23 | self.eps = eps 24 | 25 | @mmcv.jit(coderize=True) 26 | def encode(self, bboxes, gt_bboxes, stride): 27 | """Get box regression transformation deltas that can be used to 28 | transform the ``bboxes`` into the ``gt_bboxes``. 29 | 30 | Args: 31 | bboxes (torch.Tensor): Source boxes, e.g., anchors. 32 | gt_bboxes (torch.Tensor): Target of the transformation, e.g., 33 | ground-truth boxes. 34 | stride (torch.Tensor | int): Stride of bboxes. 35 | 36 | Returns: 37 | torch.Tensor: Box transformation deltas 38 | """ 39 | 40 | assert bboxes.size(0) == gt_bboxes.size(0) 41 | assert bboxes.size(-1) == gt_bboxes.size(-1) == 4 42 | x_center_gt = (gt_bboxes[..., 0] + gt_bboxes[..., 2]) * 0.5 43 | y_center_gt = (gt_bboxes[..., 1] + gt_bboxes[..., 3]) * 0.5 44 | w_gt = gt_bboxes[..., 2] - gt_bboxes[..., 0] 45 | h_gt = gt_bboxes[..., 3] - gt_bboxes[..., 1] 46 | x_center = (bboxes[..., 0] + bboxes[..., 2]) * 0.5 47 | y_center = (bboxes[..., 1] + bboxes[..., 3]) * 0.5 48 | w = bboxes[..., 2] - bboxes[..., 0] 49 | h = bboxes[..., 3] - bboxes[..., 1] 50 | w_target = torch.log((w_gt / w).clamp(min=self.eps)) 51 | h_target = torch.log((h_gt / h).clamp(min=self.eps)) 52 | x_center_target = ((x_center_gt - x_center) / stride + 0.5).clamp( 53 | self.eps, 1 - self.eps) 54 | y_center_target = ((y_center_gt - y_center) / stride + 0.5).clamp( 55 | self.eps, 1 - self.eps) 56 | encoded_bboxes = torch.stack( 57 | [x_center_target, y_center_target, w_target, h_target], dim=-1) 58 | return encoded_bboxes 59 | 60 | @mmcv.jit(coderize=True) 61 | def decode(self, bboxes, pred_bboxes, stride): 62 | """Apply transformation `pred_bboxes` to `boxes`. 63 | 64 | Args: 65 | boxes (torch.Tensor): Basic boxes, e.g. anchors. 66 | pred_bboxes (torch.Tensor): Encoded boxes with shape 67 | stride (torch.Tensor | int): Strides of bboxes. 68 | 69 | Returns: 70 | torch.Tensor: Decoded boxes. 71 | """ 72 | assert pred_bboxes.size(0) == bboxes.size(0) 73 | assert pred_bboxes.size(-1) == bboxes.size(-1) == 4 74 | x_center = (bboxes[..., 0] + bboxes[..., 2]) * 0.5 75 | y_center = (bboxes[..., 1] + bboxes[..., 3]) * 0.5 76 | w = bboxes[..., 2] - bboxes[..., 0] 77 | h = bboxes[..., 3] - bboxes[..., 1] 78 | # Get outputs x, y 79 | x_center_pred = (pred_bboxes[..., 0] - 0.5) * stride + x_center 80 | y_center_pred = (pred_bboxes[..., 1] - 0.5) * stride + y_center 81 | w_pred = torch.exp(pred_bboxes[..., 2]) * w 82 | h_pred = torch.exp(pred_bboxes[..., 3]) * h 83 | 84 | decoded_bboxes = torch.stack( 85 | (x_center_pred - w_pred / 2, y_center_pred - h_pred / 2, 86 | x_center_pred + w_pred / 2, y_center_pred + h_pred / 2), 87 | dim=-1) 88 | 89 | return decoded_bboxes 90 | -------------------------------------------------------------------------------- /object_detection/mmdet/core/bbox/demodata.py: -------------------------------------------------------------------------------- 1 | import numpy as np 2 | import torch 3 | 4 | from mmdet.utils.util_random import ensure_rng 5 | 6 | 7 | def random_boxes(num=1, scale=1, rng=None): 8 | """Simple version of ``kwimage.Boxes.random`` 9 | 10 | Returns: 11 | Tensor: shape (n, 4) in x1, y1, x2, y2 format. 12 | 13 | References: 14 | https://gitlab.kitware.com/computer-vision/kwimage/blob/master/kwimage/structs/boxes.py#L1390 15 | 16 | Example: 17 | >>> num = 3 18 | >>> scale = 512 19 | >>> rng = 0 20 | >>> boxes = random_boxes(num, scale, rng) 21 | >>> print(boxes) 22 | tensor([[280.9925, 278.9802, 308.6148, 366.1769], 23 | [216.9113, 330.6978, 224.0446, 456.5878], 24 | [405.3632, 196.3221, 493.3953, 270.7942]]) 25 | """ 26 | rng = ensure_rng(rng) 27 | 28 | tlbr = rng.rand(num, 4).astype(np.float32) 29 | 30 | tl_x = np.minimum(tlbr[:, 0], tlbr[:, 2]) 31 | tl_y = np.minimum(tlbr[:, 1], tlbr[:, 3]) 32 | br_x = np.maximum(tlbr[:, 0], tlbr[:, 2]) 33 | br_y = np.maximum(tlbr[:, 1], tlbr[:, 3]) 34 | 35 | tlbr[:, 0] = tl_x * scale 36 | tlbr[:, 1] = tl_y * scale 37 | tlbr[:, 2] = br_x * scale 38 | tlbr[:, 3] = br_y * scale 39 | 40 | boxes = torch.from_numpy(tlbr) 41 | return boxes 42 | -------------------------------------------------------------------------------- /object_detection/mmdet/core/bbox/iou_calculators/__init__.py: -------------------------------------------------------------------------------- 1 | from .builder import build_iou_calculator 2 | from .iou2d_calculator import BboxOverlaps2D, bbox_overlaps 3 | 4 | __all__ = ['build_iou_calculator', 'BboxOverlaps2D', 'bbox_overlaps'] 5 | -------------------------------------------------------------------------------- /object_detection/mmdet/core/bbox/iou_calculators/builder.py: -------------------------------------------------------------------------------- 1 | from mmcv.utils import Registry, build_from_cfg 2 | 3 | IOU_CALCULATORS = Registry('IoU calculator') 4 | 5 | 6 | def build_iou_calculator(cfg, default_args=None): 7 | """Builder of IoU calculator.""" 8 | return build_from_cfg(cfg, IOU_CALCULATORS, default_args) 9 | -------------------------------------------------------------------------------- /object_detection/mmdet/core/bbox/match_costs/__init__.py: -------------------------------------------------------------------------------- 1 | from .builder import build_match_cost 2 | from .match_cost import BBoxL1Cost, ClassificationCost, FocalLossCost, IoUCost 3 | 4 | __all__ = [ 5 | 'build_match_cost', 'ClassificationCost', 'BBoxL1Cost', 'IoUCost', 6 | 'FocalLossCost' 7 | ] 8 | -------------------------------------------------------------------------------- /object_detection/mmdet/core/bbox/match_costs/builder.py: -------------------------------------------------------------------------------- 1 | from mmcv.utils import Registry, build_from_cfg 2 | 3 | MATCH_COST = Registry('Match Cost') 4 | 5 | 6 | def build_match_cost(cfg, default_args=None): 7 | """Builder of IoU calculator.""" 8 | return build_from_cfg(cfg, MATCH_COST, default_args) 9 | -------------------------------------------------------------------------------- /object_detection/mmdet/core/bbox/samplers/__init__.py: -------------------------------------------------------------------------------- 1 | from .base_sampler import BaseSampler 2 | from .combined_sampler import CombinedSampler 3 | from .instance_balanced_pos_sampler import InstanceBalancedPosSampler 4 | from .iou_balanced_neg_sampler import IoUBalancedNegSampler 5 | from .ohem_sampler import OHEMSampler 6 | from .pseudo_sampler import PseudoSampler 7 | from .random_sampler import RandomSampler 8 | from .sampling_result import SamplingResult 9 | from .score_hlr_sampler import ScoreHLRSampler 10 | 11 | __all__ = [ 12 | 'BaseSampler', 'PseudoSampler', 'RandomSampler', 13 | 'InstanceBalancedPosSampler', 'IoUBalancedNegSampler', 'CombinedSampler', 14 | 'OHEMSampler', 'SamplingResult', 'ScoreHLRSampler' 15 | ] 16 | -------------------------------------------------------------------------------- /object_detection/mmdet/core/bbox/samplers/combined_sampler.py: -------------------------------------------------------------------------------- 1 | from ..builder import BBOX_SAMPLERS, build_sampler 2 | from .base_sampler import BaseSampler 3 | 4 | 5 | @BBOX_SAMPLERS.register_module() 6 | class CombinedSampler(BaseSampler): 7 | """A sampler that combines positive sampler and negative sampler.""" 8 | 9 | def __init__(self, pos_sampler, neg_sampler, **kwargs): 10 | super(CombinedSampler, self).__init__(**kwargs) 11 | self.pos_sampler = build_sampler(pos_sampler, **kwargs) 12 | self.neg_sampler = build_sampler(neg_sampler, **kwargs) 13 | 14 | def _sample_pos(self, **kwargs): 15 | """Sample positive samples.""" 16 | raise NotImplementedError 17 | 18 | def _sample_neg(self, **kwargs): 19 | """Sample negative samples.""" 20 | raise NotImplementedError 21 | -------------------------------------------------------------------------------- /object_detection/mmdet/core/bbox/samplers/instance_balanced_pos_sampler.py: -------------------------------------------------------------------------------- 1 | import numpy as np 2 | import torch 3 | 4 | from ..builder import BBOX_SAMPLERS 5 | from .random_sampler import RandomSampler 6 | 7 | 8 | @BBOX_SAMPLERS.register_module() 9 | class InstanceBalancedPosSampler(RandomSampler): 10 | """Instance balanced sampler that samples equal number of positive samples 11 | for each instance.""" 12 | 13 | def _sample_pos(self, assign_result, num_expected, **kwargs): 14 | """Sample positive boxes. 15 | 16 | Args: 17 | assign_result (:obj:`AssignResult`): The assigned results of boxes. 18 | num_expected (int): The number of expected positive samples 19 | 20 | Returns: 21 | Tensor or ndarray: sampled indices. 22 | """ 23 | pos_inds = torch.nonzero(assign_result.gt_inds > 0, as_tuple=False) 24 | if pos_inds.numel() != 0: 25 | pos_inds = pos_inds.squeeze(1) 26 | if pos_inds.numel() <= num_expected: 27 | return pos_inds 28 | else: 29 | unique_gt_inds = assign_result.gt_inds[pos_inds].unique() 30 | num_gts = len(unique_gt_inds) 31 | num_per_gt = int(round(num_expected / float(num_gts)) + 1) 32 | sampled_inds = [] 33 | for i in unique_gt_inds: 34 | inds = torch.nonzero( 35 | assign_result.gt_inds == i.item(), as_tuple=False) 36 | if inds.numel() != 0: 37 | inds = inds.squeeze(1) 38 | else: 39 | continue 40 | if len(inds) > num_per_gt: 41 | inds = self.random_choice(inds, num_per_gt) 42 | sampled_inds.append(inds) 43 | sampled_inds = torch.cat(sampled_inds) 44 | if len(sampled_inds) < num_expected: 45 | num_extra = num_expected - len(sampled_inds) 46 | extra_inds = np.array( 47 | list(set(pos_inds.cpu()) - set(sampled_inds.cpu()))) 48 | if len(extra_inds) > num_extra: 49 | extra_inds = self.random_choice(extra_inds, num_extra) 50 | extra_inds = torch.from_numpy(extra_inds).to( 51 | assign_result.gt_inds.device).long() 52 | sampled_inds = torch.cat([sampled_inds, extra_inds]) 53 | elif len(sampled_inds) > num_expected: 54 | sampled_inds = self.random_choice(sampled_inds, num_expected) 55 | return sampled_inds 56 | -------------------------------------------------------------------------------- /object_detection/mmdet/core/bbox/samplers/pseudo_sampler.py: -------------------------------------------------------------------------------- 1 | import torch 2 | 3 | from ..builder import BBOX_SAMPLERS 4 | from .base_sampler import BaseSampler 5 | from .sampling_result import SamplingResult 6 | 7 | 8 | @BBOX_SAMPLERS.register_module() 9 | class PseudoSampler(BaseSampler): 10 | """A pseudo sampler that does not do sampling actually.""" 11 | 12 | def __init__(self, **kwargs): 13 | pass 14 | 15 | def _sample_pos(self, **kwargs): 16 | """Sample positive samples.""" 17 | raise NotImplementedError 18 | 19 | def _sample_neg(self, **kwargs): 20 | """Sample negative samples.""" 21 | raise NotImplementedError 22 | 23 | def sample(self, assign_result, bboxes, gt_bboxes, **kwargs): 24 | """Directly returns the positive and negative indices of samples. 25 | 26 | Args: 27 | assign_result (:obj:`AssignResult`): Assigned results 28 | bboxes (torch.Tensor): Bounding boxes 29 | gt_bboxes (torch.Tensor): Ground truth boxes 30 | 31 | Returns: 32 | :obj:`SamplingResult`: sampler results 33 | """ 34 | pos_inds = torch.nonzero( 35 | assign_result.gt_inds > 0, as_tuple=False).squeeze(-1).unique() 36 | neg_inds = torch.nonzero( 37 | assign_result.gt_inds == 0, as_tuple=False).squeeze(-1).unique() 38 | gt_flags = bboxes.new_zeros(bboxes.shape[0], dtype=torch.uint8) 39 | sampling_result = SamplingResult(pos_inds, neg_inds, bboxes, gt_bboxes, 40 | assign_result, gt_flags) 41 | return sampling_result 42 | -------------------------------------------------------------------------------- /object_detection/mmdet/core/bbox/samplers/random_sampler.py: -------------------------------------------------------------------------------- 1 | import torch 2 | 3 | from ..builder import BBOX_SAMPLERS 4 | from .base_sampler import BaseSampler 5 | 6 | 7 | @BBOX_SAMPLERS.register_module() 8 | class RandomSampler(BaseSampler): 9 | """Random sampler. 10 | 11 | Args: 12 | num (int): Number of samples 13 | pos_fraction (float): Fraction of positive samples 14 | neg_pos_up (int, optional): Upper bound number of negative and 15 | positive samples. Defaults to -1. 16 | add_gt_as_proposals (bool, optional): Whether to add ground truth 17 | boxes as proposals. Defaults to True. 18 | """ 19 | 20 | def __init__(self, 21 | num, 22 | pos_fraction, 23 | neg_pos_ub=-1, 24 | add_gt_as_proposals=True, 25 | **kwargs): 26 | from mmdet.core.bbox import demodata 27 | super(RandomSampler, self).__init__(num, pos_fraction, neg_pos_ub, 28 | add_gt_as_proposals) 29 | self.rng = demodata.ensure_rng(kwargs.get('rng', None)) 30 | 31 | def random_choice(self, gallery, num): 32 | """Random select some elements from the gallery. 33 | 34 | If `gallery` is a Tensor, the returned indices will be a Tensor; 35 | If `gallery` is a ndarray or list, the returned indices will be a 36 | ndarray. 37 | 38 | Args: 39 | gallery (Tensor | ndarray | list): indices pool. 40 | num (int): expected sample num. 41 | 42 | Returns: 43 | Tensor or ndarray: sampled indices. 44 | """ 45 | assert len(gallery) >= num 46 | 47 | is_tensor = isinstance(gallery, torch.Tensor) 48 | if not is_tensor: 49 | if torch.cuda.is_available(): 50 | device = torch.cuda.current_device() 51 | else: 52 | device = 'cpu' 53 | gallery = torch.tensor(gallery, dtype=torch.long, device=device) 54 | perm = torch.randperm(gallery.numel(), device=gallery.device)[:num] 55 | rand_inds = gallery[perm] 56 | if not is_tensor: 57 | rand_inds = rand_inds.cpu().numpy() 58 | return rand_inds 59 | 60 | def _sample_pos(self, assign_result, num_expected, **kwargs): 61 | """Randomly sample some positive samples.""" 62 | pos_inds = torch.nonzero(assign_result.gt_inds > 0, as_tuple=False) 63 | if pos_inds.numel() != 0: 64 | pos_inds = pos_inds.squeeze(1) 65 | if pos_inds.numel() <= num_expected: 66 | return pos_inds 67 | else: 68 | return self.random_choice(pos_inds, num_expected) 69 | 70 | def _sample_neg(self, assign_result, num_expected, **kwargs): 71 | """Randomly sample some negative samples.""" 72 | neg_inds = torch.nonzero(assign_result.gt_inds == 0, as_tuple=False) 73 | if neg_inds.numel() != 0: 74 | neg_inds = neg_inds.squeeze(1) 75 | if len(neg_inds) <= num_expected: 76 | return neg_inds 77 | else: 78 | return self.random_choice(neg_inds, num_expected) 79 | -------------------------------------------------------------------------------- /object_detection/mmdet/core/evaluation/__init__.py: -------------------------------------------------------------------------------- 1 | from .class_names import (cityscapes_classes, coco_classes, dataset_aliases, 2 | get_classes, imagenet_det_classes, 3 | imagenet_vid_classes, voc_classes) 4 | from .eval_hooks import DistEvalHook, EvalHook 5 | from .mean_ap import average_precision, eval_map, print_map_summary 6 | from .recall import (eval_recalls, plot_iou_recall, plot_num_recall, 7 | print_recall_summary) 8 | 9 | __all__ = [ 10 | 'voc_classes', 'imagenet_det_classes', 'imagenet_vid_classes', 11 | 'coco_classes', 'cityscapes_classes', 'dataset_aliases', 'get_classes', 12 | 'DistEvalHook', 'EvalHook', 'average_precision', 'eval_map', 13 | 'print_map_summary', 'eval_recalls', 'print_recall_summary', 14 | 'plot_num_recall', 'plot_iou_recall' 15 | ] 16 | -------------------------------------------------------------------------------- /object_detection/mmdet/core/evaluation/bbox_overlaps.py: -------------------------------------------------------------------------------- 1 | import numpy as np 2 | 3 | 4 | def bbox_overlaps(bboxes1, bboxes2, mode='iou', eps=1e-6): 5 | """Calculate the ious between each bbox of bboxes1 and bboxes2. 6 | 7 | Args: 8 | bboxes1(ndarray): shape (n, 4) 9 | bboxes2(ndarray): shape (k, 4) 10 | mode(str): iou (intersection over union) or iof (intersection 11 | over foreground) 12 | 13 | Returns: 14 | ious(ndarray): shape (n, k) 15 | """ 16 | 17 | assert mode in ['iou', 'iof'] 18 | 19 | bboxes1 = bboxes1.astype(np.float32) 20 | bboxes2 = bboxes2.astype(np.float32) 21 | rows = bboxes1.shape[0] 22 | cols = bboxes2.shape[0] 23 | ious = np.zeros((rows, cols), dtype=np.float32) 24 | if rows * cols == 0: 25 | return ious 26 | exchange = False 27 | if bboxes1.shape[0] > bboxes2.shape[0]: 28 | bboxes1, bboxes2 = bboxes2, bboxes1 29 | ious = np.zeros((cols, rows), dtype=np.float32) 30 | exchange = True 31 | area1 = (bboxes1[:, 2] - bboxes1[:, 0]) * (bboxes1[:, 3] - bboxes1[:, 1]) 32 | area2 = (bboxes2[:, 2] - bboxes2[:, 0]) * (bboxes2[:, 3] - bboxes2[:, 1]) 33 | for i in range(bboxes1.shape[0]): 34 | x_start = np.maximum(bboxes1[i, 0], bboxes2[:, 0]) 35 | y_start = np.maximum(bboxes1[i, 1], bboxes2[:, 1]) 36 | x_end = np.minimum(bboxes1[i, 2], bboxes2[:, 2]) 37 | y_end = np.minimum(bboxes1[i, 3], bboxes2[:, 3]) 38 | overlap = np.maximum(x_end - x_start, 0) * np.maximum( 39 | y_end - y_start, 0) 40 | if mode == 'iou': 41 | union = area1[i] + area2 - overlap 42 | else: 43 | union = area1[i] if not exchange else area2 44 | union = np.maximum(union, eps) 45 | ious[i, :] = overlap / union 46 | if exchange: 47 | ious = ious.T 48 | return ious 49 | -------------------------------------------------------------------------------- /object_detection/mmdet/core/export/__init__.py: -------------------------------------------------------------------------------- 1 | from .pytorch2onnx import (build_model_from_cfg, 2 | generate_inputs_and_wrap_model, 3 | preprocess_example_input) 4 | 5 | __all__ = [ 6 | 'build_model_from_cfg', 'generate_inputs_and_wrap_model', 7 | 'preprocess_example_input' 8 | ] 9 | -------------------------------------------------------------------------------- /object_detection/mmdet/core/mask/__init__.py: -------------------------------------------------------------------------------- 1 | from .mask_target import mask_target 2 | from .structures import BaseInstanceMasks, BitmapMasks, PolygonMasks 3 | from .utils import encode_mask_results, split_combined_polys 4 | 5 | __all__ = [ 6 | 'split_combined_polys', 'mask_target', 'BaseInstanceMasks', 'BitmapMasks', 7 | 'PolygonMasks', 'encode_mask_results' 8 | ] 9 | -------------------------------------------------------------------------------- /object_detection/mmdet/core/mask/utils.py: -------------------------------------------------------------------------------- 1 | import mmcv 2 | import numpy as np 3 | import pycocotools.mask as mask_util 4 | 5 | 6 | def split_combined_polys(polys, poly_lens, polys_per_mask): 7 | """Split the combined 1-D polys into masks. 8 | 9 | A mask is represented as a list of polys, and a poly is represented as 10 | a 1-D array. In dataset, all masks are concatenated into a single 1-D 11 | tensor. Here we need to split the tensor into original representations. 12 | 13 | Args: 14 | polys (list): a list (length = image num) of 1-D tensors 15 | poly_lens (list): a list (length = image num) of poly length 16 | polys_per_mask (list): a list (length = image num) of poly number 17 | of each mask 18 | 19 | Returns: 20 | list: a list (length = image num) of list (length = mask num) of \ 21 | list (length = poly num) of numpy array. 22 | """ 23 | mask_polys_list = [] 24 | for img_id in range(len(polys)): 25 | polys_single = polys[img_id] 26 | polys_lens_single = poly_lens[img_id].tolist() 27 | polys_per_mask_single = polys_per_mask[img_id].tolist() 28 | 29 | split_polys = mmcv.slice_list(polys_single, polys_lens_single) 30 | mask_polys = mmcv.slice_list(split_polys, polys_per_mask_single) 31 | mask_polys_list.append(mask_polys) 32 | return mask_polys_list 33 | 34 | 35 | # TODO: move this function to more proper place 36 | def encode_mask_results(mask_results): 37 | """Encode bitmap mask to RLE code. 38 | 39 | Args: 40 | mask_results (list | tuple[list]): bitmap mask results. 41 | In mask scoring rcnn, mask_results is a tuple of (segm_results, 42 | segm_cls_score). 43 | 44 | Returns: 45 | list | tuple: RLE encoded mask. 46 | """ 47 | if isinstance(mask_results, tuple): # mask scoring 48 | cls_segms, cls_mask_scores = mask_results 49 | else: 50 | cls_segms = mask_results 51 | num_classes = len(cls_segms) 52 | encoded_mask_results = [[] for _ in range(num_classes)] 53 | for i in range(len(cls_segms)): 54 | for cls_segm in cls_segms[i]: 55 | encoded_mask_results[i].append( 56 | mask_util.encode( 57 | np.array( 58 | cls_segm[:, :, np.newaxis], order='F', 59 | dtype='uint8'))[0]) # encoded with RLE 60 | if isinstance(mask_results, tuple): 61 | return encoded_mask_results, cls_mask_scores 62 | else: 63 | return encoded_mask_results 64 | -------------------------------------------------------------------------------- /object_detection/mmdet/core/post_processing/__init__.py: -------------------------------------------------------------------------------- 1 | from .bbox_nms import fast_nms, multiclass_nms 2 | from .merge_augs import (merge_aug_bboxes, merge_aug_masks, 3 | merge_aug_proposals, merge_aug_scores) 4 | 5 | __all__ = [ 6 | 'multiclass_nms', 'merge_aug_proposals', 'merge_aug_bboxes', 7 | 'merge_aug_scores', 'merge_aug_masks', 'fast_nms' 8 | ] 9 | -------------------------------------------------------------------------------- /object_detection/mmdet/core/utils/__init__.py: -------------------------------------------------------------------------------- 1 | from .dist_utils import DistOptimizerHook, allreduce_grads, reduce_mean 2 | from .misc import mask2ndarray, multi_apply, unmap 3 | 4 | __all__ = [ 5 | 'allreduce_grads', 'DistOptimizerHook', 'reduce_mean', 'multi_apply', 6 | 'unmap', 'mask2ndarray' 7 | ] 8 | -------------------------------------------------------------------------------- /object_detection/mmdet/core/utils/dist_utils.py: -------------------------------------------------------------------------------- 1 | import warnings 2 | from collections import OrderedDict 3 | 4 | import torch.distributed as dist 5 | from mmcv.runner import OptimizerHook 6 | from torch._utils import (_flatten_dense_tensors, _take_tensors, 7 | _unflatten_dense_tensors) 8 | 9 | 10 | def _allreduce_coalesced(tensors, world_size, bucket_size_mb=-1): 11 | if bucket_size_mb > 0: 12 | bucket_size_bytes = bucket_size_mb * 1024 * 1024 13 | buckets = _take_tensors(tensors, bucket_size_bytes) 14 | else: 15 | buckets = OrderedDict() 16 | for tensor in tensors: 17 | tp = tensor.type() 18 | if tp not in buckets: 19 | buckets[tp] = [] 20 | buckets[tp].append(tensor) 21 | buckets = buckets.values() 22 | 23 | for bucket in buckets: 24 | flat_tensors = _flatten_dense_tensors(bucket) 25 | dist.all_reduce(flat_tensors) 26 | flat_tensors.div_(world_size) 27 | for tensor, synced in zip( 28 | bucket, _unflatten_dense_tensors(flat_tensors, bucket)): 29 | tensor.copy_(synced) 30 | 31 | 32 | def allreduce_grads(params, coalesce=True, bucket_size_mb=-1): 33 | """Allreduce gradients. 34 | 35 | Args: 36 | params (list[torch.Parameters]): List of parameters of a model 37 | coalesce (bool, optional): Whether allreduce parameters as a whole. 38 | Defaults to True. 39 | bucket_size_mb (int, optional): Size of bucket, the unit is MB. 40 | Defaults to -1. 41 | """ 42 | grads = [ 43 | param.grad.data for param in params 44 | if param.requires_grad and param.grad is not None 45 | ] 46 | world_size = dist.get_world_size() 47 | if coalesce: 48 | _allreduce_coalesced(grads, world_size, bucket_size_mb) 49 | else: 50 | for tensor in grads: 51 | dist.all_reduce(tensor.div_(world_size)) 52 | 53 | 54 | class DistOptimizerHook(OptimizerHook): 55 | """Deprecated optimizer hook for distributed training.""" 56 | 57 | def __init__(self, *args, **kwargs): 58 | warnings.warn('"DistOptimizerHook" is deprecated, please switch to' 59 | '"mmcv.runner.OptimizerHook".') 60 | super().__init__(*args, **kwargs) 61 | 62 | 63 | def reduce_mean(tensor): 64 | """"Obtain the mean of tensor on different GPUs.""" 65 | if not (dist.is_available() and dist.is_initialized()): 66 | return tensor 67 | tensor = tensor.clone() 68 | dist.all_reduce(tensor.div_(dist.get_world_size()), op=dist.ReduceOp.SUM) 69 | return tensor 70 | -------------------------------------------------------------------------------- /object_detection/mmdet/core/utils/misc.py: -------------------------------------------------------------------------------- 1 | from functools import partial 2 | 3 | import numpy as np 4 | import torch 5 | from six.moves import map, zip 6 | 7 | from ..mask.structures import BitmapMasks, PolygonMasks 8 | 9 | 10 | def multi_apply(func, *args, **kwargs): 11 | """Apply function to a list of arguments. 12 | 13 | Note: 14 | This function applies the ``func`` to multiple inputs and 15 | map the multiple outputs of the ``func`` into different 16 | list. Each list contains the same type of outputs corresponding 17 | to different inputs. 18 | 19 | Args: 20 | func (Function): A function that will be applied to a list of 21 | arguments 22 | 23 | Returns: 24 | tuple(list): A tuple containing multiple list, each list contains \ 25 | a kind of returned results by the function 26 | """ 27 | pfunc = partial(func, **kwargs) if kwargs else func 28 | map_results = map(pfunc, *args) 29 | return tuple(map(list, zip(*map_results))) 30 | 31 | 32 | def unmap(data, count, inds, fill=0): 33 | """Unmap a subset of item (data) back to the original set of items (of size 34 | count)""" 35 | if data.dim() == 1: 36 | ret = data.new_full((count, ), fill) 37 | ret[inds.type(torch.bool)] = data 38 | else: 39 | new_size = (count, ) + data.size()[1:] 40 | ret = data.new_full(new_size, fill) 41 | ret[inds.type(torch.bool), :] = data 42 | return ret 43 | 44 | 45 | def mask2ndarray(mask): 46 | """Convert Mask to ndarray.. 47 | 48 | Args: 49 | mask (:obj:`BitmapMasks` or :obj:`PolygonMasks` or 50 | torch.Tensor or np.ndarray): The mask to be converted. 51 | 52 | Returns: 53 | np.ndarray: Ndarray mask of shape (n, h, w) that has been converted 54 | """ 55 | if isinstance(mask, (BitmapMasks, PolygonMasks)): 56 | mask = mask.to_ndarray() 57 | elif isinstance(mask, torch.Tensor): 58 | mask = mask.detach().cpu().numpy() 59 | elif not isinstance(mask, np.ndarray): 60 | raise TypeError(f'Unsupported {type(mask)} data type') 61 | return mask 62 | -------------------------------------------------------------------------------- /object_detection/mmdet/core/visualization/__init__.py: -------------------------------------------------------------------------------- 1 | from .image import (color_val_matplotlib, imshow_det_bboxes, 2 | imshow_gt_det_bboxes) 3 | 4 | __all__ = ['imshow_det_bboxes', 'imshow_gt_det_bboxes', 'color_val_matplotlib'] 5 | -------------------------------------------------------------------------------- /object_detection/mmdet/datasets/__init__.py: -------------------------------------------------------------------------------- 1 | from .builder import DATASETS, PIPELINES, build_dataloader, build_dataset 2 | from .cityscapes import CityscapesDataset 3 | from .coco import CocoDataset 4 | from .custom import CustomDataset 5 | from .dataset_wrappers import (ClassBalancedDataset, ConcatDataset, 6 | RepeatDataset) 7 | from .deepfashion import DeepFashionDataset 8 | from .lvis import LVISDataset, LVISV1Dataset, LVISV05Dataset 9 | from .samplers import DistributedGroupSampler, DistributedSampler, GroupSampler 10 | from .utils import (NumClassCheckHook, get_loading_pipeline, 11 | replace_ImageToTensor) 12 | from .voc import VOCDataset 13 | from .wider_face import WIDERFaceDataset 14 | from .xml_style import XMLDataset 15 | 16 | __all__ = [ 17 | 'CustomDataset', 'XMLDataset', 'CocoDataset', 'DeepFashionDataset', 18 | 'VOCDataset', 'CityscapesDataset', 'LVISDataset', 'LVISV05Dataset', 19 | 'LVISV1Dataset', 'GroupSampler', 'DistributedGroupSampler', 20 | 'DistributedSampler', 'build_dataloader', 'ConcatDataset', 'RepeatDataset', 21 | 'ClassBalancedDataset', 'WIDERFaceDataset', 'DATASETS', 'PIPELINES', 22 | 'build_dataset', 'replace_ImageToTensor', 'get_loading_pipeline', 23 | 'NumClassCheckHook' 24 | ] 25 | -------------------------------------------------------------------------------- /object_detection/mmdet/datasets/deepfashion.py: -------------------------------------------------------------------------------- 1 | from .builder import DATASETS 2 | from .coco import CocoDataset 3 | 4 | 5 | @DATASETS.register_module() 6 | class DeepFashionDataset(CocoDataset): 7 | 8 | CLASSES = ('top', 'skirt', 'leggings', 'dress', 'outer', 'pants', 'bag', 9 | 'neckwear', 'headwear', 'eyeglass', 'belt', 'footwear', 'hair', 10 | 'skin', 'face') 11 | -------------------------------------------------------------------------------- /object_detection/mmdet/datasets/pipelines/__init__.py: -------------------------------------------------------------------------------- 1 | from .auto_augment import (AutoAugment, BrightnessTransform, ColorTransform, 2 | ContrastTransform, EqualizeTransform, Rotate, Shear, 3 | Translate) 4 | from .compose import Compose 5 | from .formating import (Collect, DefaultFormatBundle, ImageToTensor, 6 | ToDataContainer, ToTensor, Transpose, to_tensor) 7 | from .instaboost import InstaBoost 8 | from .loading import (LoadAnnotations, LoadImageFromFile, LoadImageFromWebcam, 9 | LoadMultiChannelImageFromFiles, LoadProposals) 10 | from .test_time_aug import MultiScaleFlipAug 11 | from .transforms import (Albu, CutOut, Expand, MinIoURandomCrop, Normalize, 12 | Pad, PhotoMetricDistortion, RandomCenterCropPad, 13 | RandomCrop, RandomFlip, Resize, SegRescale) 14 | 15 | __all__ = [ 16 | 'Compose', 'to_tensor', 'ToTensor', 'ImageToTensor', 'ToDataContainer', 17 | 'Transpose', 'Collect', 'DefaultFormatBundle', 'LoadAnnotations', 18 | 'LoadImageFromFile', 'LoadImageFromWebcam', 19 | 'LoadMultiChannelImageFromFiles', 'LoadProposals', 'MultiScaleFlipAug', 20 | 'Resize', 'RandomFlip', 'Pad', 'RandomCrop', 'Normalize', 'SegRescale', 21 | 'MinIoURandomCrop', 'Expand', 'PhotoMetricDistortion', 'Albu', 22 | 'InstaBoost', 'RandomCenterCropPad', 'AutoAugment', 'CutOut', 'Shear', 23 | 'Rotate', 'ColorTransform', 'EqualizeTransform', 'BrightnessTransform', 24 | 'ContrastTransform', 'Translate' 25 | ] 26 | -------------------------------------------------------------------------------- /object_detection/mmdet/datasets/pipelines/compose.py: -------------------------------------------------------------------------------- 1 | import collections 2 | 3 | from mmcv.utils import build_from_cfg 4 | 5 | from ..builder import PIPELINES 6 | 7 | 8 | @PIPELINES.register_module() 9 | class Compose(object): 10 | """Compose multiple transforms sequentially. 11 | 12 | Args: 13 | transforms (Sequence[dict | callable]): Sequence of transform object or 14 | config dict to be composed. 15 | """ 16 | 17 | def __init__(self, transforms): 18 | assert isinstance(transforms, collections.abc.Sequence) 19 | self.transforms = [] 20 | for transform in transforms: 21 | if isinstance(transform, dict): 22 | transform = build_from_cfg(transform, PIPELINES) 23 | self.transforms.append(transform) 24 | elif callable(transform): 25 | self.transforms.append(transform) 26 | else: 27 | raise TypeError('transform must be callable or a dict') 28 | 29 | def __call__(self, data): 30 | """Call function to apply transforms sequentially. 31 | 32 | Args: 33 | data (dict): A result dict contains the data to transform. 34 | 35 | Returns: 36 | dict: Transformed data. 37 | """ 38 | 39 | for t in self.transforms: 40 | data = t(data) 41 | if data is None: 42 | return None 43 | return data 44 | 45 | def __repr__(self): 46 | format_string = self.__class__.__name__ + '(' 47 | for t in self.transforms: 48 | format_string += '\n' 49 | format_string += f' {t}' 50 | format_string += '\n)' 51 | return format_string 52 | -------------------------------------------------------------------------------- /object_detection/mmdet/datasets/pipelines/instaboost.py: -------------------------------------------------------------------------------- 1 | import numpy as np 2 | 3 | from ..builder import PIPELINES 4 | 5 | 6 | @PIPELINES.register_module() 7 | class InstaBoost(object): 8 | r"""Data augmentation method in `InstaBoost: Boosting Instance 9 | Segmentation Via Probability Map Guided Copy-Pasting 10 | `_. 11 | 12 | Refer to https://github.com/GothicAi/Instaboost for implementation details. 13 | """ 14 | 15 | def __init__(self, 16 | action_candidate=('normal', 'horizontal', 'skip'), 17 | action_prob=(1, 0, 0), 18 | scale=(0.8, 1.2), 19 | dx=15, 20 | dy=15, 21 | theta=(-1, 1), 22 | color_prob=0.5, 23 | hflag=False, 24 | aug_ratio=0.5): 25 | try: 26 | import instaboostfast as instaboost 27 | except ImportError: 28 | raise ImportError( 29 | 'Please run "pip install instaboostfast" ' 30 | 'to install instaboostfast first for instaboost augmentation.') 31 | self.cfg = instaboost.InstaBoostConfig(action_candidate, action_prob, 32 | scale, dx, dy, theta, 33 | color_prob, hflag) 34 | self.aug_ratio = aug_ratio 35 | 36 | def _load_anns(self, results): 37 | labels = results['ann_info']['labels'] 38 | masks = results['ann_info']['masks'] 39 | bboxes = results['ann_info']['bboxes'] 40 | n = len(labels) 41 | 42 | anns = [] 43 | for i in range(n): 44 | label = labels[i] 45 | bbox = bboxes[i] 46 | mask = masks[i] 47 | x1, y1, x2, y2 = bbox 48 | # assert (x2 - x1) >= 1 and (y2 - y1) >= 1 49 | bbox = [x1, y1, x2 - x1, y2 - y1] 50 | anns.append({ 51 | 'category_id': label, 52 | 'segmentation': mask, 53 | 'bbox': bbox 54 | }) 55 | 56 | return anns 57 | 58 | def _parse_anns(self, results, anns, img): 59 | gt_bboxes = [] 60 | gt_labels = [] 61 | gt_masks_ann = [] 62 | for ann in anns: 63 | x1, y1, w, h = ann['bbox'] 64 | # TODO: more essential bug need to be fixed in instaboost 65 | if w <= 0 or h <= 0: 66 | continue 67 | bbox = [x1, y1, x1 + w, y1 + h] 68 | gt_bboxes.append(bbox) 69 | gt_labels.append(ann['category_id']) 70 | gt_masks_ann.append(ann['segmentation']) 71 | gt_bboxes = np.array(gt_bboxes, dtype=np.float32) 72 | gt_labels = np.array(gt_labels, dtype=np.int64) 73 | results['ann_info']['labels'] = gt_labels 74 | results['ann_info']['bboxes'] = gt_bboxes 75 | results['ann_info']['masks'] = gt_masks_ann 76 | results['img'] = img 77 | return results 78 | 79 | def __call__(self, results): 80 | img = results['img'] 81 | orig_type = img.dtype 82 | anns = self._load_anns(results) 83 | if np.random.choice([0, 1], p=[1 - self.aug_ratio, self.aug_ratio]): 84 | try: 85 | import instaboostfast as instaboost 86 | except ImportError: 87 | raise ImportError('Please run "pip install instaboostfast" ' 88 | 'to install instaboostfast first.') 89 | anns, img = instaboost.get_new_data( 90 | anns, img.astype(np.uint8), self.cfg, background=None) 91 | 92 | results = self._parse_anns(results, anns, img.astype(orig_type)) 93 | return results 94 | 95 | def __repr__(self): 96 | repr_str = self.__class__.__name__ 97 | repr_str += f'(cfg={self.cfg}, aug_ratio={self.aug_ratio})' 98 | return repr_str 99 | -------------------------------------------------------------------------------- /object_detection/mmdet/datasets/samplers/__init__.py: -------------------------------------------------------------------------------- 1 | from .distributed_sampler import DistributedSampler 2 | from .group_sampler import DistributedGroupSampler, GroupSampler 3 | 4 | __all__ = ['DistributedSampler', 'DistributedGroupSampler', 'GroupSampler'] 5 | -------------------------------------------------------------------------------- /object_detection/mmdet/datasets/samplers/distributed_sampler.py: -------------------------------------------------------------------------------- 1 | import math 2 | 3 | import torch 4 | from torch.utils.data import DistributedSampler as _DistributedSampler 5 | 6 | 7 | class DistributedSampler(_DistributedSampler): 8 | 9 | def __init__(self, 10 | dataset, 11 | num_replicas=None, 12 | rank=None, 13 | shuffle=True, 14 | seed=0): 15 | super().__init__( 16 | dataset, num_replicas=num_replicas, rank=rank, shuffle=shuffle) 17 | # for the compatibility from PyTorch 1.3+ 18 | self.seed = seed if seed is not None else 0 19 | 20 | def __iter__(self): 21 | # deterministically shuffle based on epoch 22 | if self.shuffle: 23 | g = torch.Generator() 24 | g.manual_seed(self.epoch + self.seed) 25 | indices = torch.randperm(len(self.dataset), generator=g).tolist() 26 | else: 27 | indices = torch.arange(len(self.dataset)).tolist() 28 | 29 | # add extra samples to make it evenly divisible 30 | # in case that indices is shorter than half of total_size 31 | indices = (indices * 32 | math.ceil(self.total_size / len(indices)))[:self.total_size] 33 | assert len(indices) == self.total_size 34 | 35 | # subsample 36 | indices = indices[self.rank:self.total_size:self.num_replicas] 37 | assert len(indices) == self.num_samples 38 | 39 | return iter(indices) 40 | -------------------------------------------------------------------------------- /object_detection/mmdet/datasets/voc.py: -------------------------------------------------------------------------------- 1 | from collections import OrderedDict 2 | 3 | from mmcv.utils import print_log 4 | 5 | from mmdet.core import eval_map, eval_recalls 6 | from .builder import DATASETS 7 | from .xml_style import XMLDataset 8 | 9 | 10 | @DATASETS.register_module() 11 | class VOCDataset(XMLDataset): 12 | 13 | CLASSES = ('aeroplane', 'bicycle', 'bird', 'boat', 'bottle', 'bus', 'car', 14 | 'cat', 'chair', 'cow', 'diningtable', 'dog', 'horse', 15 | 'motorbike', 'person', 'pottedplant', 'sheep', 'sofa', 'train', 16 | 'tvmonitor') 17 | 18 | def __init__(self, **kwargs): 19 | super(VOCDataset, self).__init__(**kwargs) 20 | if 'VOC2007' in self.img_prefix: 21 | self.year = 2007 22 | elif 'VOC2012' in self.img_prefix: 23 | self.year = 2012 24 | else: 25 | raise ValueError('Cannot infer dataset year from img_prefix') 26 | 27 | def evaluate(self, 28 | results, 29 | metric='mAP', 30 | logger=None, 31 | proposal_nums=(100, 300, 1000), 32 | iou_thr=0.5, 33 | scale_ranges=None): 34 | """Evaluate in VOC protocol. 35 | 36 | Args: 37 | results (list[list | tuple]): Testing results of the dataset. 38 | metric (str | list[str]): Metrics to be evaluated. Options are 39 | 'mAP', 'recall'. 40 | logger (logging.Logger | str, optional): Logger used for printing 41 | related information during evaluation. Default: None. 42 | proposal_nums (Sequence[int]): Proposal number used for evaluating 43 | recalls, such as recall@100, recall@1000. 44 | Default: (100, 300, 1000). 45 | iou_thr (float | list[float]): IoU threshold. Default: 0.5. 46 | scale_ranges (list[tuple], optional): Scale ranges for evaluating 47 | mAP. If not specified, all bounding boxes would be included in 48 | evaluation. Default: None. 49 | 50 | Returns: 51 | dict[str, float]: AP/recall metrics. 52 | """ 53 | 54 | if not isinstance(metric, str): 55 | assert len(metric) == 1 56 | metric = metric[0] 57 | allowed_metrics = ['mAP', 'recall'] 58 | if metric not in allowed_metrics: 59 | raise KeyError(f'metric {metric} is not supported') 60 | annotations = [self.get_ann_info(i) for i in range(len(self))] 61 | eval_results = OrderedDict() 62 | iou_thrs = [iou_thr] if isinstance(iou_thr, float) else iou_thr 63 | if metric == 'mAP': 64 | assert isinstance(iou_thrs, list) 65 | if self.year == 2007: 66 | ds_name = 'voc07' 67 | else: 68 | ds_name = self.CLASSES 69 | mean_aps = [] 70 | for iou_thr in iou_thrs: 71 | print_log(f'\n{"-" * 15}iou_thr: {iou_thr}{"-" * 15}') 72 | mean_ap, _ = eval_map( 73 | results, 74 | annotations, 75 | scale_ranges=None, 76 | iou_thr=iou_thr, 77 | dataset=ds_name, 78 | logger=logger) 79 | mean_aps.append(mean_ap) 80 | eval_results[f'AP{int(iou_thr * 100):02d}'] = round(mean_ap, 3) 81 | eval_results['mAP'] = sum(mean_aps) / len(mean_aps) 82 | elif metric == 'recall': 83 | gt_bboxes = [ann['bboxes'] for ann in annotations] 84 | recalls = eval_recalls( 85 | gt_bboxes, results, proposal_nums, iou_thr, logger=logger) 86 | for i, num in enumerate(proposal_nums): 87 | for j, iou in enumerate(iou_thr): 88 | eval_results[f'recall@{num}@{iou}'] = recalls[i, j] 89 | if recalls.shape[1] > 1: 90 | ar = recalls.mean(axis=1) 91 | for i, num in enumerate(proposal_nums): 92 | eval_results[f'AR@{num}'] = ar[i] 93 | return eval_results 94 | -------------------------------------------------------------------------------- /object_detection/mmdet/datasets/wider_face.py: -------------------------------------------------------------------------------- 1 | import os.path as osp 2 | import xml.etree.ElementTree as ET 3 | 4 | import mmcv 5 | 6 | from .builder import DATASETS 7 | from .xml_style import XMLDataset 8 | 9 | 10 | @DATASETS.register_module() 11 | class WIDERFaceDataset(XMLDataset): 12 | """Reader for the WIDER Face dataset in PASCAL VOC format. 13 | 14 | Conversion scripts can be found in 15 | https://github.com/sovrasov/wider-face-pascal-voc-annotations 16 | """ 17 | CLASSES = ('face', ) 18 | 19 | def __init__(self, **kwargs): 20 | super(WIDERFaceDataset, self).__init__(**kwargs) 21 | 22 | def load_annotations(self, ann_file): 23 | """Load annotation from WIDERFace XML style annotation file. 24 | 25 | Args: 26 | ann_file (str): Path of XML file. 27 | 28 | Returns: 29 | list[dict]: Annotation info from XML file. 30 | """ 31 | 32 | data_infos = [] 33 | img_ids = mmcv.list_from_file(ann_file) 34 | for img_id in img_ids: 35 | filename = f'{img_id}.jpg' 36 | xml_path = osp.join(self.img_prefix, 'Annotations', 37 | f'{img_id}.xml') 38 | tree = ET.parse(xml_path) 39 | root = tree.getroot() 40 | size = root.find('size') 41 | width = int(size.find('width').text) 42 | height = int(size.find('height').text) 43 | folder = root.find('folder').text 44 | data_infos.append( 45 | dict( 46 | id=img_id, 47 | filename=osp.join(folder, filename), 48 | width=width, 49 | height=height)) 50 | 51 | return data_infos 52 | -------------------------------------------------------------------------------- /object_detection/mmdet/models/__init__.py: -------------------------------------------------------------------------------- 1 | from .backbones import * # noqa: F401,F403 2 | from .builder import (BACKBONES, DETECTORS, HEADS, LOSSES, NECKS, 3 | ROI_EXTRACTORS, SHARED_HEADS, build_backbone, 4 | build_detector, build_head, build_loss, build_neck, 5 | build_roi_extractor, build_shared_head) 6 | from .dense_heads import * # noqa: F401,F403 7 | from .detectors import * # noqa: F401,F403 8 | from .losses import * # noqa: F401,F403 9 | from .necks import * # noqa: F401,F403 10 | from .roi_heads import * # noqa: F401,F403 11 | 12 | __all__ = [ 13 | 'BACKBONES', 'NECKS', 'ROI_EXTRACTORS', 'SHARED_HEADS', 'HEADS', 'LOSSES', 14 | 'DETECTORS', 'build_backbone', 'build_neck', 'build_roi_extractor', 15 | 'build_shared_head', 'build_head', 'build_loss', 'build_detector' 16 | ] 17 | -------------------------------------------------------------------------------- /object_detection/mmdet/models/backbones/__init__.py: -------------------------------------------------------------------------------- 1 | # from .darknet import Darknet 2 | # from .detectors_resnet import DetectoRS_ResNet 3 | # from .detectors_resnext import DetectoRS_ResNeXt 4 | # from .hourglass import HourglassNet 5 | # from .hrnet import HRNet 6 | # from .regnet import RegNet 7 | # from .res2net import Res2Net 8 | # from .resnest import ResNeSt 9 | # from .resnext import ResNeXt 10 | # from .ssd_vgg import SSDVGG 11 | # from .trident_resnet import TridentResNet 12 | from .resnet import ResNet, ResNetV1d 13 | from .swin_transformer import SwinTransformer 14 | from .convnext import ConvNeXt 15 | from .fcaformer import FcaFormer_SH_512 16 | 17 | # __all__ = [ 18 | # 'RegNet', 'ResNet', 'ResNetV1d', 'ResNeXt', 'SSDVGG', 'HRNet', 'Res2Net', 19 | # 'HourglassNet', 'DetectoRS_ResNet', 'DetectoRS_ResNeXt', 'Darknet', 20 | # 'ResNeSt', 'TridentResNet', 'SwinTransformer', 'ConvNeXt' 21 | # ] 22 | 23 | __all__ = [ 24 | 'ResNet', 'ResNetV1d', 'SwinTransformer', 'ConvNeXt', 'FcaFormer_SH_512' 25 | ] 26 | 27 | 28 | -------------------------------------------------------------------------------- /object_detection/mmdet/models/builder.py: -------------------------------------------------------------------------------- 1 | import warnings 2 | 3 | from mmcv.utils import Registry, build_from_cfg 4 | from torch import nn 5 | 6 | BACKBONES = Registry('backbone') 7 | NECKS = Registry('neck') 8 | ROI_EXTRACTORS = Registry('roi_extractor') 9 | SHARED_HEADS = Registry('shared_head') 10 | HEADS = Registry('head') 11 | LOSSES = Registry('loss') 12 | DETECTORS = Registry('detector') 13 | 14 | 15 | def build(cfg, registry, default_args=None): 16 | """Build a module. 17 | 18 | Args: 19 | cfg (dict, list[dict]): The config of modules, is is either a dict 20 | or a list of configs. 21 | registry (:obj:`Registry`): A registry the module belongs to. 22 | default_args (dict, optional): Default arguments to build the module. 23 | Defaults to None. 24 | 25 | Returns: 26 | nn.Module: A built nn module. 27 | """ 28 | if isinstance(cfg, list): 29 | modules = [ 30 | build_from_cfg(cfg_, registry, default_args) for cfg_ in cfg 31 | ] 32 | return nn.Sequential(*modules) 33 | else: 34 | return build_from_cfg(cfg, registry, default_args) 35 | 36 | 37 | def build_backbone(cfg): 38 | """Build backbone.""" 39 | return build(cfg, BACKBONES) 40 | 41 | 42 | def build_neck(cfg): 43 | """Build neck.""" 44 | return build(cfg, NECKS) 45 | 46 | 47 | def build_roi_extractor(cfg): 48 | """Build roi extractor.""" 49 | return build(cfg, ROI_EXTRACTORS) 50 | 51 | 52 | def build_shared_head(cfg): 53 | """Build shared head.""" 54 | return build(cfg, SHARED_HEADS) 55 | 56 | 57 | def build_head(cfg): 58 | """Build head.""" 59 | return build(cfg, HEADS) 60 | 61 | 62 | def build_loss(cfg): 63 | """Build loss.""" 64 | return build(cfg, LOSSES) 65 | 66 | 67 | def build_detector(cfg, train_cfg=None, test_cfg=None): 68 | """Build detector.""" 69 | if train_cfg is not None or test_cfg is not None: 70 | warnings.warn( 71 | 'train_cfg and test_cfg is deprecated, ' 72 | 'please specify them in model', UserWarning) 73 | assert cfg.get('train_cfg') is None or train_cfg is None, \ 74 | 'train_cfg specified in both outer field and model field ' 75 | assert cfg.get('test_cfg') is None or test_cfg is None, \ 76 | 'test_cfg specified in both outer field and model field ' 77 | return build(cfg, DETECTORS, dict(train_cfg=train_cfg, test_cfg=test_cfg)) 78 | -------------------------------------------------------------------------------- /object_detection/mmdet/models/dense_heads/__init__.py: -------------------------------------------------------------------------------- 1 | from .anchor_free_head import AnchorFreeHead 2 | from .anchor_head import AnchorHead 3 | from .atss_head import ATSSHead 4 | from .cascade_rpn_head import CascadeRPNHead, StageCascadeRPNHead 5 | from .centripetal_head import CentripetalHead 6 | from .corner_head import CornerHead 7 | from .embedding_rpn_head import EmbeddingRPNHead 8 | from .fcos_head import FCOSHead 9 | from .fovea_head import FoveaHead 10 | from .free_anchor_retina_head import FreeAnchorRetinaHead 11 | from .fsaf_head import FSAFHead 12 | from .ga_retina_head import GARetinaHead 13 | from .ga_rpn_head import GARPNHead 14 | from .gfl_head import GFLHead 15 | from .guided_anchor_head import FeatureAdaption, GuidedAnchorHead 16 | from .ld_head import LDHead 17 | from .nasfcos_head import NASFCOSHead 18 | from .paa_head import PAAHead 19 | from .pisa_retinanet_head import PISARetinaHead 20 | from .pisa_ssd_head import PISASSDHead 21 | from .reppoints_head import RepPointsHead 22 | from .retina_head import RetinaHead 23 | from .retina_sepbn_head import RetinaSepBNHead 24 | from .rpn_head import RPNHead 25 | from .sabl_retina_head import SABLRetinaHead 26 | from .ssd_head import SSDHead 27 | from .transformer_head import TransformerHead 28 | from .vfnet_head import VFNetHead 29 | from .yolact_head import YOLACTHead, YOLACTProtonet, YOLACTSegmHead 30 | from .yolo_head import YOLOV3Head 31 | 32 | __all__ = [ 33 | 'AnchorFreeHead', 'AnchorHead', 'GuidedAnchorHead', 'FeatureAdaption', 34 | 'RPNHead', 'GARPNHead', 'RetinaHead', 'RetinaSepBNHead', 'GARetinaHead', 35 | 'SSDHead', 'FCOSHead', 'RepPointsHead', 'FoveaHead', 36 | 'FreeAnchorRetinaHead', 'ATSSHead', 'FSAFHead', 'NASFCOSHead', 37 | 'PISARetinaHead', 'PISASSDHead', 'GFLHead', 'CornerHead', 'YOLACTHead', 38 | 'YOLACTSegmHead', 'YOLACTProtonet', 'YOLOV3Head', 'PAAHead', 39 | 'SABLRetinaHead', 'CentripetalHead', 'VFNetHead', 'TransformerHead', 40 | 'StageCascadeRPNHead', 'CascadeRPNHead', 'EmbeddingRPNHead', 'LDHead' 41 | ] 42 | -------------------------------------------------------------------------------- /object_detection/mmdet/models/dense_heads/base_dense_head.py: -------------------------------------------------------------------------------- 1 | from abc import ABCMeta, abstractmethod 2 | 3 | import torch.nn as nn 4 | 5 | 6 | class BaseDenseHead(nn.Module, metaclass=ABCMeta): 7 | """Base class for DenseHeads.""" 8 | 9 | def __init__(self): 10 | super(BaseDenseHead, self).__init__() 11 | 12 | @abstractmethod 13 | def loss(self, **kwargs): 14 | """Compute losses of the head.""" 15 | pass 16 | 17 | @abstractmethod 18 | def get_bboxes(self, **kwargs): 19 | """Transform network output for a batch into bbox predictions.""" 20 | pass 21 | 22 | def forward_train(self, 23 | x, 24 | img_metas, 25 | gt_bboxes, 26 | gt_labels=None, 27 | gt_bboxes_ignore=None, 28 | proposal_cfg=None, 29 | **kwargs): 30 | """ 31 | Args: 32 | x (list[Tensor]): Features from FPN. 33 | img_metas (list[dict]): Meta information of each image, e.g., 34 | image size, scaling factor, etc. 35 | gt_bboxes (Tensor): Ground truth bboxes of the image, 36 | shape (num_gts, 4). 37 | gt_labels (Tensor): Ground truth labels of each box, 38 | shape (num_gts,). 39 | gt_bboxes_ignore (Tensor): Ground truth bboxes to be 40 | ignored, shape (num_ignored_gts, 4). 41 | proposal_cfg (mmcv.Config): Test / postprocessing configuration, 42 | if None, test_cfg would be used 43 | 44 | Returns: 45 | tuple: 46 | losses: (dict[str, Tensor]): A dictionary of loss components. 47 | proposal_list (list[Tensor]): Proposals of each image. 48 | """ 49 | outs = self(x) 50 | if gt_labels is None: 51 | loss_inputs = outs + (gt_bboxes, img_metas) 52 | else: 53 | loss_inputs = outs + (gt_bboxes, gt_labels, img_metas) 54 | losses = self.loss(*loss_inputs, gt_bboxes_ignore=gt_bboxes_ignore) 55 | if proposal_cfg is None: 56 | return losses 57 | else: 58 | proposal_list = self.get_bboxes(*outs, img_metas, cfg=proposal_cfg) 59 | return losses, proposal_list 60 | -------------------------------------------------------------------------------- /object_detection/mmdet/models/dense_heads/nasfcos_head.py: -------------------------------------------------------------------------------- 1 | import copy 2 | 3 | import torch.nn as nn 4 | from mmcv.cnn import (ConvModule, Scale, bias_init_with_prob, 5 | caffe2_xavier_init, normal_init) 6 | 7 | from mmdet.models.dense_heads.fcos_head import FCOSHead 8 | from ..builder import HEADS 9 | 10 | 11 | @HEADS.register_module() 12 | class NASFCOSHead(FCOSHead): 13 | """Anchor-free head used in `NASFCOS `_. 14 | 15 | It is quite similar with FCOS head, except for the searched structure of 16 | classification branch and bbox regression branch, where a structure of 17 | "dconv3x3, conv3x3, dconv3x3, conv1x1" is utilized instead. 18 | """ 19 | 20 | def _init_layers(self): 21 | """Initialize layers of the head.""" 22 | dconv3x3_config = dict( 23 | type='DCNv2', 24 | kernel_size=3, 25 | use_bias=True, 26 | deform_groups=2, 27 | padding=1) 28 | conv3x3_config = dict(type='Conv', kernel_size=3, padding=1) 29 | conv1x1_config = dict(type='Conv', kernel_size=1) 30 | 31 | self.arch_config = [ 32 | dconv3x3_config, conv3x3_config, dconv3x3_config, conv1x1_config 33 | ] 34 | self.cls_convs = nn.ModuleList() 35 | self.reg_convs = nn.ModuleList() 36 | for i, op_ in enumerate(self.arch_config): 37 | op = copy.deepcopy(op_) 38 | chn = self.in_channels if i == 0 else self.feat_channels 39 | assert isinstance(op, dict) 40 | use_bias = op.pop('use_bias', False) 41 | padding = op.pop('padding', 0) 42 | kernel_size = op.pop('kernel_size') 43 | module = ConvModule( 44 | chn, 45 | self.feat_channels, 46 | kernel_size, 47 | stride=1, 48 | padding=padding, 49 | norm_cfg=self.norm_cfg, 50 | bias=use_bias, 51 | conv_cfg=op) 52 | 53 | self.cls_convs.append(copy.deepcopy(module)) 54 | self.reg_convs.append(copy.deepcopy(module)) 55 | 56 | self.conv_cls = nn.Conv2d( 57 | self.feat_channels, self.cls_out_channels, 3, padding=1) 58 | self.conv_reg = nn.Conv2d(self.feat_channels, 4, 3, padding=1) 59 | self.conv_centerness = nn.Conv2d(self.feat_channels, 1, 3, padding=1) 60 | 61 | self.scales = nn.ModuleList([Scale(1.0) for _ in self.strides]) 62 | 63 | def init_weights(self): 64 | """Initialize weights of the head.""" 65 | # retinanet_bias_init 66 | bias_cls = bias_init_with_prob(0.01) 67 | normal_init(self.conv_reg, std=0.01) 68 | normal_init(self.conv_centerness, std=0.01) 69 | normal_init(self.conv_cls, std=0.01, bias=bias_cls) 70 | 71 | for branch in [self.cls_convs, self.reg_convs]: 72 | for module in branch.modules(): 73 | if isinstance(module, ConvModule) \ 74 | and isinstance(module.conv, nn.Conv2d): 75 | caffe2_xavier_init(module.conv) 76 | -------------------------------------------------------------------------------- /object_detection/mmdet/models/dense_heads/rpn_test_mixin.py: -------------------------------------------------------------------------------- 1 | import sys 2 | 3 | from mmdet.core import merge_aug_proposals 4 | 5 | if sys.version_info >= (3, 7): 6 | from mmdet.utils.contextmanagers import completed 7 | 8 | 9 | class RPNTestMixin(object): 10 | """Test methods of RPN.""" 11 | 12 | if sys.version_info >= (3, 7): 13 | 14 | async def async_simple_test_rpn(self, x, img_metas): 15 | sleep_interval = self.test_cfg.pop('async_sleep_interval', 0.025) 16 | async with completed( 17 | __name__, 'rpn_head_forward', 18 | sleep_interval=sleep_interval): 19 | rpn_outs = self(x) 20 | 21 | proposal_list = self.get_bboxes(*rpn_outs, img_metas) 22 | return proposal_list 23 | 24 | def simple_test_rpn(self, x, img_metas): 25 | """Test without augmentation. 26 | 27 | Args: 28 | x (tuple[Tensor]): Features from the upstream network, each is 29 | a 4D-tensor. 30 | img_metas (list[dict]): Meta info of each image. 31 | 32 | Returns: 33 | list[Tensor]: Proposals of each image. 34 | """ 35 | rpn_outs = self(x) 36 | proposal_list = self.get_bboxes(*rpn_outs, img_metas) 37 | return proposal_list 38 | 39 | def aug_test_rpn(self, feats, img_metas): 40 | samples_per_gpu = len(img_metas[0]) 41 | aug_proposals = [[] for _ in range(samples_per_gpu)] 42 | for x, img_meta in zip(feats, img_metas): 43 | proposal_list = self.simple_test_rpn(x, img_meta) 44 | for i, proposals in enumerate(proposal_list): 45 | aug_proposals[i].append(proposals) 46 | # reorganize the order of 'img_metas' to match the dimensions 47 | # of 'aug_proposals' 48 | aug_img_metas = [] 49 | for i in range(samples_per_gpu): 50 | aug_img_meta = [] 51 | for j in range(len(img_metas)): 52 | aug_img_meta.append(img_metas[j][i]) 53 | aug_img_metas.append(aug_img_meta) 54 | # after merging, proposals will be rescaled to the original image size 55 | merged_proposals = [ 56 | merge_aug_proposals(proposals, aug_img_meta, self.test_cfg) 57 | for proposals, aug_img_meta in zip(aug_proposals, aug_img_metas) 58 | ] 59 | return merged_proposals 60 | -------------------------------------------------------------------------------- /object_detection/mmdet/models/detectors/__init__.py: -------------------------------------------------------------------------------- 1 | from .atss import ATSS 2 | from .base import BaseDetector 3 | from .cascade_rcnn import CascadeRCNN 4 | from .cornernet import CornerNet 5 | from .detr import DETR 6 | from .fast_rcnn import FastRCNN 7 | from .faster_rcnn import FasterRCNN 8 | from .fcos import FCOS 9 | from .fovea import FOVEA 10 | from .fsaf import FSAF 11 | from .gfl import GFL 12 | from .grid_rcnn import GridRCNN 13 | from .htc import HybridTaskCascade 14 | from .kd_one_stage import KnowledgeDistillationSingleStageDetector 15 | from .mask_rcnn import MaskRCNN 16 | from .mask_scoring_rcnn import MaskScoringRCNN 17 | from .nasfcos import NASFCOS 18 | from .paa import PAA 19 | from .point_rend import PointRend 20 | from .reppoints_detector import RepPointsDetector 21 | from .retinanet import RetinaNet 22 | from .rpn import RPN 23 | from .scnet import SCNet 24 | from .single_stage import SingleStageDetector 25 | from .sparse_rcnn import SparseRCNN 26 | from .trident_faster_rcnn import TridentFasterRCNN 27 | from .two_stage import TwoStageDetector 28 | from .vfnet import VFNet 29 | from .yolact import YOLACT 30 | from .yolo import YOLOV3 31 | 32 | __all__ = [ 33 | 'ATSS', 'BaseDetector', 'SingleStageDetector', 34 | 'KnowledgeDistillationSingleStageDetector', 'TwoStageDetector', 'RPN', 35 | 'FastRCNN', 'FasterRCNN', 'MaskRCNN', 'CascadeRCNN', 'HybridTaskCascade', 36 | 'RetinaNet', 'FCOS', 'GridRCNN', 'MaskScoringRCNN', 'RepPointsDetector', 37 | 'FOVEA', 'FSAF', 'NASFCOS', 'PointRend', 'GFL', 'CornerNet', 'PAA', 38 | 'YOLOV3', 'YOLACT', 'VFNet', 'DETR', 'TridentFasterRCNN', 'SparseRCNN', 39 | 'SCNet' 40 | ] 41 | -------------------------------------------------------------------------------- /object_detection/mmdet/models/detectors/atss.py: -------------------------------------------------------------------------------- 1 | from ..builder import DETECTORS 2 | from .single_stage import SingleStageDetector 3 | 4 | 5 | @DETECTORS.register_module() 6 | class ATSS(SingleStageDetector): 7 | """Implementation of `ATSS `_.""" 8 | 9 | def __init__(self, 10 | backbone, 11 | neck, 12 | bbox_head, 13 | train_cfg=None, 14 | test_cfg=None, 15 | pretrained=None): 16 | super(ATSS, self).__init__(backbone, neck, bbox_head, train_cfg, 17 | test_cfg, pretrained) 18 | -------------------------------------------------------------------------------- /object_detection/mmdet/models/detectors/cascade_rcnn.py: -------------------------------------------------------------------------------- 1 | from ..builder import DETECTORS 2 | from .two_stage import TwoStageDetector 3 | 4 | 5 | @DETECTORS.register_module() 6 | class CascadeRCNN(TwoStageDetector): 7 | r"""Implementation of `Cascade R-CNN: Delving into High Quality Object 8 | Detection `_""" 9 | 10 | def __init__(self, 11 | backbone, 12 | neck=None, 13 | rpn_head=None, 14 | roi_head=None, 15 | train_cfg=None, 16 | test_cfg=None, 17 | pretrained=None): 18 | super(CascadeRCNN, self).__init__( 19 | backbone=backbone, 20 | neck=neck, 21 | rpn_head=rpn_head, 22 | roi_head=roi_head, 23 | train_cfg=train_cfg, 24 | test_cfg=test_cfg, 25 | pretrained=pretrained) 26 | 27 | def show_result(self, data, result, **kwargs): 28 | """Show prediction results of the detector. 29 | 30 | Args: 31 | data (str or np.ndarray): Image filename or loaded image. 32 | result (Tensor or tuple): The results to draw over `img` 33 | bbox_result or (bbox_result, segm_result). 34 | 35 | Returns: 36 | np.ndarray: The image with bboxes drawn on it. 37 | """ 38 | if self.with_mask: 39 | ms_bbox_result, ms_segm_result = result 40 | if isinstance(ms_bbox_result, dict): 41 | result = (ms_bbox_result['ensemble'], 42 | ms_segm_result['ensemble']) 43 | else: 44 | if isinstance(result, dict): 45 | result = result['ensemble'] 46 | return super(CascadeRCNN, self).show_result(data, result, **kwargs) 47 | -------------------------------------------------------------------------------- /object_detection/mmdet/models/detectors/cornernet.py: -------------------------------------------------------------------------------- 1 | import torch 2 | 3 | from mmdet.core import bbox2result, bbox_mapping_back 4 | from ..builder import DETECTORS 5 | from .single_stage import SingleStageDetector 6 | 7 | 8 | @DETECTORS.register_module() 9 | class CornerNet(SingleStageDetector): 10 | """CornerNet. 11 | 12 | This detector is the implementation of the paper `CornerNet: Detecting 13 | Objects as Paired Keypoints `_ . 14 | """ 15 | 16 | def __init__(self, 17 | backbone, 18 | neck, 19 | bbox_head, 20 | train_cfg=None, 21 | test_cfg=None, 22 | pretrained=None): 23 | super(CornerNet, self).__init__(backbone, neck, bbox_head, train_cfg, 24 | test_cfg, pretrained) 25 | 26 | def merge_aug_results(self, aug_results, img_metas): 27 | """Merge augmented detection bboxes and score. 28 | 29 | Args: 30 | aug_results (list[list[Tensor]]): Det_bboxes and det_labels of each 31 | image. 32 | img_metas (list[list[dict]]): Meta information of each image, e.g., 33 | image size, scaling factor, etc. 34 | 35 | Returns: 36 | tuple: (bboxes, labels) 37 | """ 38 | recovered_bboxes, aug_labels = [], [] 39 | for bboxes_labels, img_info in zip(aug_results, img_metas): 40 | img_shape = img_info[0]['img_shape'] # using shape before padding 41 | scale_factor = img_info[0]['scale_factor'] 42 | flip = img_info[0]['flip'] 43 | bboxes, labels = bboxes_labels 44 | bboxes, scores = bboxes[:, :4], bboxes[:, -1:] 45 | bboxes = bbox_mapping_back(bboxes, img_shape, scale_factor, flip) 46 | recovered_bboxes.append(torch.cat([bboxes, scores], dim=-1)) 47 | aug_labels.append(labels) 48 | 49 | bboxes = torch.cat(recovered_bboxes, dim=0) 50 | labels = torch.cat(aug_labels) 51 | 52 | if bboxes.shape[0] > 0: 53 | out_bboxes, out_labels = self.bbox_head._bboxes_nms( 54 | bboxes, labels, self.bbox_head.test_cfg) 55 | else: 56 | out_bboxes, out_labels = bboxes, labels 57 | 58 | return out_bboxes, out_labels 59 | 60 | def aug_test(self, imgs, img_metas, rescale=False): 61 | """Augment testing of CornerNet. 62 | 63 | Args: 64 | imgs (list[Tensor]): Augmented images. 65 | img_metas (list[list[dict]]): Meta information of each image, e.g., 66 | image size, scaling factor, etc. 67 | rescale (bool): If True, return boxes in original image space. 68 | Default: False. 69 | 70 | Note: 71 | ``imgs`` must including flipped image pairs. 72 | 73 | Returns: 74 | list[list[np.ndarray]]: BBox results of each image and classes. 75 | The outer list corresponds to each image. The inner list 76 | corresponds to each class. 77 | """ 78 | img_inds = list(range(len(imgs))) 79 | 80 | assert img_metas[0][0]['flip'] + img_metas[1][0]['flip'], ( 81 | 'aug test must have flipped image pair') 82 | aug_results = [] 83 | for ind, flip_ind in zip(img_inds[0::2], img_inds[1::2]): 84 | img_pair = torch.cat([imgs[ind], imgs[flip_ind]]) 85 | x = self.extract_feat(img_pair) 86 | outs = self.bbox_head(x) 87 | bbox_list = self.bbox_head.get_bboxes( 88 | *outs, [img_metas[ind], img_metas[flip_ind]], False, False) 89 | aug_results.append(bbox_list[0]) 90 | aug_results.append(bbox_list[1]) 91 | 92 | bboxes, labels = self.merge_aug_results(aug_results, img_metas) 93 | bbox_results = bbox2result(bboxes, labels, self.bbox_head.num_classes) 94 | 95 | return [bbox_results] 96 | -------------------------------------------------------------------------------- /object_detection/mmdet/models/detectors/detr.py: -------------------------------------------------------------------------------- 1 | from mmdet.core import bbox2result 2 | from ..builder import DETECTORS 3 | from .single_stage import SingleStageDetector 4 | 5 | 6 | @DETECTORS.register_module() 7 | class DETR(SingleStageDetector): 8 | r"""Implementation of `DETR: End-to-End Object Detection with 9 | Transformers `_""" 10 | 11 | def __init__(self, 12 | backbone, 13 | bbox_head, 14 | train_cfg=None, 15 | test_cfg=None, 16 | pretrained=None): 17 | super(DETR, self).__init__(backbone, None, bbox_head, train_cfg, 18 | test_cfg, pretrained) 19 | 20 | def simple_test(self, img, img_metas, rescale=False): 21 | """Test function without test time augmentation. 22 | 23 | Args: 24 | imgs (list[torch.Tensor]): List of multiple images 25 | img_metas (list[dict]): List of image information. 26 | rescale (bool, optional): Whether to rescale the results. 27 | Defaults to False. 28 | 29 | Returns: 30 | list[list[np.ndarray]]: BBox results of each image and classes. 31 | The outer list corresponds to each image. The inner list 32 | corresponds to each class. 33 | """ 34 | batch_size = len(img_metas) 35 | assert batch_size == 1, 'Currently only batch_size 1 for inference ' \ 36 | f'mode is supported. Found batch_size {batch_size}.' 37 | x = self.extract_feat(img) 38 | outs = self.bbox_head(x, img_metas) 39 | bbox_list = self.bbox_head.get_bboxes( 40 | *outs, img_metas, rescale=rescale) 41 | 42 | bbox_results = [ 43 | bbox2result(det_bboxes, det_labels, self.bbox_head.num_classes) 44 | for det_bboxes, det_labels in bbox_list 45 | ] 46 | return bbox_results 47 | -------------------------------------------------------------------------------- /object_detection/mmdet/models/detectors/fast_rcnn.py: -------------------------------------------------------------------------------- 1 | from ..builder import DETECTORS 2 | from .two_stage import TwoStageDetector 3 | 4 | 5 | @DETECTORS.register_module() 6 | class FastRCNN(TwoStageDetector): 7 | """Implementation of `Fast R-CNN `_""" 8 | 9 | def __init__(self, 10 | backbone, 11 | roi_head, 12 | train_cfg, 13 | test_cfg, 14 | neck=None, 15 | pretrained=None): 16 | super(FastRCNN, self).__init__( 17 | backbone=backbone, 18 | neck=neck, 19 | roi_head=roi_head, 20 | train_cfg=train_cfg, 21 | test_cfg=test_cfg, 22 | pretrained=pretrained) 23 | 24 | def forward_test(self, imgs, img_metas, proposals, **kwargs): 25 | """ 26 | Args: 27 | imgs (List[Tensor]): the outer list indicates test-time 28 | augmentations and inner Tensor should have a shape NxCxHxW, 29 | which contains all images in the batch. 30 | img_metas (List[List[dict]]): the outer list indicates test-time 31 | augs (multiscale, flip, etc.) and the inner list indicates 32 | images in a batch. 33 | proposals (List[List[Tensor]]): the outer list indicates test-time 34 | augs (multiscale, flip, etc.) and the inner list indicates 35 | images in a batch. The Tensor should have a shape Px4, where 36 | P is the number of proposals. 37 | """ 38 | for var, name in [(imgs, 'imgs'), (img_metas, 'img_metas')]: 39 | if not isinstance(var, list): 40 | raise TypeError(f'{name} must be a list, but got {type(var)}') 41 | 42 | num_augs = len(imgs) 43 | if num_augs != len(img_metas): 44 | raise ValueError(f'num of augmentations ({len(imgs)}) ' 45 | f'!= num of image meta ({len(img_metas)})') 46 | 47 | if num_augs == 1: 48 | return self.simple_test(imgs[0], img_metas[0], proposals[0], 49 | **kwargs) 50 | else: 51 | # TODO: support test-time augmentation 52 | assert NotImplementedError 53 | -------------------------------------------------------------------------------- /object_detection/mmdet/models/detectors/faster_rcnn.py: -------------------------------------------------------------------------------- 1 | from ..builder import DETECTORS 2 | from .two_stage import TwoStageDetector 3 | 4 | 5 | @DETECTORS.register_module() 6 | class FasterRCNN(TwoStageDetector): 7 | """Implementation of `Faster R-CNN `_""" 8 | 9 | def __init__(self, 10 | backbone, 11 | rpn_head, 12 | roi_head, 13 | train_cfg, 14 | test_cfg, 15 | neck=None, 16 | pretrained=None): 17 | super(FasterRCNN, self).__init__( 18 | backbone=backbone, 19 | neck=neck, 20 | rpn_head=rpn_head, 21 | roi_head=roi_head, 22 | train_cfg=train_cfg, 23 | test_cfg=test_cfg, 24 | pretrained=pretrained) 25 | -------------------------------------------------------------------------------- /object_detection/mmdet/models/detectors/fcos.py: -------------------------------------------------------------------------------- 1 | from ..builder import DETECTORS 2 | from .single_stage import SingleStageDetector 3 | 4 | 5 | @DETECTORS.register_module() 6 | class FCOS(SingleStageDetector): 7 | """Implementation of `FCOS `_""" 8 | 9 | def __init__(self, 10 | backbone, 11 | neck, 12 | bbox_head, 13 | train_cfg=None, 14 | test_cfg=None, 15 | pretrained=None): 16 | super(FCOS, self).__init__(backbone, neck, bbox_head, train_cfg, 17 | test_cfg, pretrained) 18 | -------------------------------------------------------------------------------- /object_detection/mmdet/models/detectors/fovea.py: -------------------------------------------------------------------------------- 1 | from ..builder import DETECTORS 2 | from .single_stage import SingleStageDetector 3 | 4 | 5 | @DETECTORS.register_module() 6 | class FOVEA(SingleStageDetector): 7 | """Implementation of `FoveaBox `_""" 8 | 9 | def __init__(self, 10 | backbone, 11 | neck, 12 | bbox_head, 13 | train_cfg=None, 14 | test_cfg=None, 15 | pretrained=None): 16 | super(FOVEA, self).__init__(backbone, neck, bbox_head, train_cfg, 17 | test_cfg, pretrained) 18 | -------------------------------------------------------------------------------- /object_detection/mmdet/models/detectors/fsaf.py: -------------------------------------------------------------------------------- 1 | from ..builder import DETECTORS 2 | from .single_stage import SingleStageDetector 3 | 4 | 5 | @DETECTORS.register_module() 6 | class FSAF(SingleStageDetector): 7 | """Implementation of `FSAF `_""" 8 | 9 | def __init__(self, 10 | backbone, 11 | neck, 12 | bbox_head, 13 | train_cfg=None, 14 | test_cfg=None, 15 | pretrained=None): 16 | super(FSAF, self).__init__(backbone, neck, bbox_head, train_cfg, 17 | test_cfg, pretrained) 18 | -------------------------------------------------------------------------------- /object_detection/mmdet/models/detectors/gfl.py: -------------------------------------------------------------------------------- 1 | from ..builder import DETECTORS 2 | from .single_stage import SingleStageDetector 3 | 4 | 5 | @DETECTORS.register_module() 6 | class GFL(SingleStageDetector): 7 | 8 | def __init__(self, 9 | backbone, 10 | neck, 11 | bbox_head, 12 | train_cfg=None, 13 | test_cfg=None, 14 | pretrained=None): 15 | super(GFL, self).__init__(backbone, neck, bbox_head, train_cfg, 16 | test_cfg, pretrained) 17 | -------------------------------------------------------------------------------- /object_detection/mmdet/models/detectors/grid_rcnn.py: -------------------------------------------------------------------------------- 1 | from ..builder import DETECTORS 2 | from .two_stage import TwoStageDetector 3 | 4 | 5 | @DETECTORS.register_module() 6 | class GridRCNN(TwoStageDetector): 7 | """Grid R-CNN. 8 | 9 | This detector is the implementation of: 10 | - Grid R-CNN (https://arxiv.org/abs/1811.12030) 11 | - Grid R-CNN Plus: Faster and Better (https://arxiv.org/abs/1906.05688) 12 | """ 13 | 14 | def __init__(self, 15 | backbone, 16 | rpn_head, 17 | roi_head, 18 | train_cfg, 19 | test_cfg, 20 | neck=None, 21 | pretrained=None): 22 | super(GridRCNN, self).__init__( 23 | backbone=backbone, 24 | neck=neck, 25 | rpn_head=rpn_head, 26 | roi_head=roi_head, 27 | train_cfg=train_cfg, 28 | test_cfg=test_cfg, 29 | pretrained=pretrained) 30 | -------------------------------------------------------------------------------- /object_detection/mmdet/models/detectors/htc.py: -------------------------------------------------------------------------------- 1 | from ..builder import DETECTORS 2 | from .cascade_rcnn import CascadeRCNN 3 | 4 | 5 | @DETECTORS.register_module() 6 | class HybridTaskCascade(CascadeRCNN): 7 | """Implementation of `HTC `_""" 8 | 9 | def __init__(self, **kwargs): 10 | super(HybridTaskCascade, self).__init__(**kwargs) 11 | 12 | @property 13 | def with_semantic(self): 14 | """bool: whether the detector has a semantic head""" 15 | return self.roi_head.with_semantic 16 | -------------------------------------------------------------------------------- /object_detection/mmdet/models/detectors/mask_rcnn.py: -------------------------------------------------------------------------------- 1 | from ..builder import DETECTORS 2 | from .two_stage import TwoStageDetector 3 | 4 | 5 | @DETECTORS.register_module() 6 | class MaskRCNN(TwoStageDetector): 7 | """Implementation of `Mask R-CNN `_""" 8 | 9 | def __init__(self, 10 | backbone, 11 | rpn_head, 12 | roi_head, 13 | train_cfg, 14 | test_cfg, 15 | neck=None, 16 | pretrained=None): 17 | super(MaskRCNN, self).__init__( 18 | backbone=backbone, 19 | neck=neck, 20 | rpn_head=rpn_head, 21 | roi_head=roi_head, 22 | train_cfg=train_cfg, 23 | test_cfg=test_cfg, 24 | pretrained=pretrained) 25 | -------------------------------------------------------------------------------- /object_detection/mmdet/models/detectors/mask_scoring_rcnn.py: -------------------------------------------------------------------------------- 1 | from ..builder import DETECTORS 2 | from .two_stage import TwoStageDetector 3 | 4 | 5 | @DETECTORS.register_module() 6 | class MaskScoringRCNN(TwoStageDetector): 7 | """Mask Scoring RCNN. 8 | 9 | https://arxiv.org/abs/1903.00241 10 | """ 11 | 12 | def __init__(self, 13 | backbone, 14 | rpn_head, 15 | roi_head, 16 | train_cfg, 17 | test_cfg, 18 | neck=None, 19 | pretrained=None): 20 | super(MaskScoringRCNN, self).__init__( 21 | backbone=backbone, 22 | neck=neck, 23 | rpn_head=rpn_head, 24 | roi_head=roi_head, 25 | train_cfg=train_cfg, 26 | test_cfg=test_cfg, 27 | pretrained=pretrained) 28 | -------------------------------------------------------------------------------- /object_detection/mmdet/models/detectors/nasfcos.py: -------------------------------------------------------------------------------- 1 | from ..builder import DETECTORS 2 | from .single_stage import SingleStageDetector 3 | 4 | 5 | @DETECTORS.register_module() 6 | class NASFCOS(SingleStageDetector): 7 | """NAS-FCOS: Fast Neural Architecture Search for Object Detection. 8 | 9 | https://arxiv.org/abs/1906.0442 10 | """ 11 | 12 | def __init__(self, 13 | backbone, 14 | neck, 15 | bbox_head, 16 | train_cfg=None, 17 | test_cfg=None, 18 | pretrained=None): 19 | super(NASFCOS, self).__init__(backbone, neck, bbox_head, train_cfg, 20 | test_cfg, pretrained) 21 | -------------------------------------------------------------------------------- /object_detection/mmdet/models/detectors/paa.py: -------------------------------------------------------------------------------- 1 | from ..builder import DETECTORS 2 | from .single_stage import SingleStageDetector 3 | 4 | 5 | @DETECTORS.register_module() 6 | class PAA(SingleStageDetector): 7 | """Implementation of `PAA `_.""" 8 | 9 | def __init__(self, 10 | backbone, 11 | neck, 12 | bbox_head, 13 | train_cfg=None, 14 | test_cfg=None, 15 | pretrained=None): 16 | super(PAA, self).__init__(backbone, neck, bbox_head, train_cfg, 17 | test_cfg, pretrained) 18 | -------------------------------------------------------------------------------- /object_detection/mmdet/models/detectors/point_rend.py: -------------------------------------------------------------------------------- 1 | from ..builder import DETECTORS 2 | from .two_stage import TwoStageDetector 3 | 4 | 5 | @DETECTORS.register_module() 6 | class PointRend(TwoStageDetector): 7 | """PointRend: Image Segmentation as Rendering 8 | 9 | This detector is the implementation of 10 | `PointRend `_. 11 | 12 | """ 13 | 14 | def __init__(self, 15 | backbone, 16 | rpn_head, 17 | roi_head, 18 | train_cfg, 19 | test_cfg, 20 | neck=None, 21 | pretrained=None): 22 | super(PointRend, self).__init__( 23 | backbone=backbone, 24 | neck=neck, 25 | rpn_head=rpn_head, 26 | roi_head=roi_head, 27 | train_cfg=train_cfg, 28 | test_cfg=test_cfg, 29 | pretrained=pretrained) 30 | -------------------------------------------------------------------------------- /object_detection/mmdet/models/detectors/reppoints_detector.py: -------------------------------------------------------------------------------- 1 | from ..builder import DETECTORS 2 | from .single_stage import SingleStageDetector 3 | 4 | 5 | @DETECTORS.register_module() 6 | class RepPointsDetector(SingleStageDetector): 7 | """RepPoints: Point Set Representation for Object Detection. 8 | 9 | This detector is the implementation of: 10 | - RepPoints detector (https://arxiv.org/pdf/1904.11490) 11 | """ 12 | 13 | def __init__(self, 14 | backbone, 15 | neck, 16 | bbox_head, 17 | train_cfg=None, 18 | test_cfg=None, 19 | pretrained=None): 20 | super(RepPointsDetector, 21 | self).__init__(backbone, neck, bbox_head, train_cfg, test_cfg, 22 | pretrained) 23 | -------------------------------------------------------------------------------- /object_detection/mmdet/models/detectors/retinanet.py: -------------------------------------------------------------------------------- 1 | from ..builder import DETECTORS 2 | from .single_stage import SingleStageDetector 3 | 4 | 5 | @DETECTORS.register_module() 6 | class RetinaNet(SingleStageDetector): 7 | """Implementation of `RetinaNet `_""" 8 | 9 | def __init__(self, 10 | backbone, 11 | neck, 12 | bbox_head, 13 | train_cfg=None, 14 | test_cfg=None, 15 | pretrained=None): 16 | super(RetinaNet, self).__init__(backbone, neck, bbox_head, train_cfg, 17 | test_cfg, pretrained) 18 | -------------------------------------------------------------------------------- /object_detection/mmdet/models/detectors/scnet.py: -------------------------------------------------------------------------------- 1 | from ..builder import DETECTORS 2 | from .cascade_rcnn import CascadeRCNN 3 | 4 | 5 | @DETECTORS.register_module() 6 | class SCNet(CascadeRCNN): 7 | """Implementation of `SCNet `_""" 8 | 9 | def __init__(self, **kwargs): 10 | super(SCNet, self).__init__(**kwargs) 11 | -------------------------------------------------------------------------------- /object_detection/mmdet/models/detectors/trident_faster_rcnn.py: -------------------------------------------------------------------------------- 1 | from ..builder import DETECTORS 2 | from .faster_rcnn import FasterRCNN 3 | 4 | 5 | @DETECTORS.register_module() 6 | class TridentFasterRCNN(FasterRCNN): 7 | """Implementation of `TridentNet `_""" 8 | 9 | def __init__(self, 10 | backbone, 11 | rpn_head, 12 | roi_head, 13 | train_cfg, 14 | test_cfg, 15 | neck=None, 16 | pretrained=None): 17 | 18 | super(TridentFasterRCNN, self).__init__( 19 | backbone=backbone, 20 | neck=neck, 21 | rpn_head=rpn_head, 22 | roi_head=roi_head, 23 | train_cfg=train_cfg, 24 | test_cfg=test_cfg, 25 | pretrained=pretrained) 26 | assert self.backbone.num_branch == self.roi_head.num_branch 27 | assert self.backbone.test_branch_idx == self.roi_head.test_branch_idx 28 | self.num_branch = self.backbone.num_branch 29 | self.test_branch_idx = self.backbone.test_branch_idx 30 | 31 | def simple_test(self, img, img_metas, proposals=None, rescale=False): 32 | """Test without augmentation.""" 33 | assert self.with_bbox, 'Bbox head must be implemented.' 34 | x = self.extract_feat(img) 35 | if proposals is None: 36 | num_branch = (self.num_branch if self.test_branch_idx == -1 else 1) 37 | trident_img_metas = img_metas * num_branch 38 | proposal_list = self.rpn_head.simple_test_rpn(x, trident_img_metas) 39 | else: 40 | proposal_list = proposals 41 | 42 | return self.roi_head.simple_test( 43 | x, proposal_list, trident_img_metas, rescale=rescale) 44 | 45 | def aug_test(self, imgs, img_metas, rescale=False): 46 | """Test with augmentations. 47 | 48 | If rescale is False, then returned bboxes and masks will fit the scale 49 | of imgs[0]. 50 | """ 51 | x = self.extract_feats(imgs) 52 | num_branch = (self.num_branch if self.test_branch_idx == -1 else 1) 53 | trident_img_metas = [img_metas * num_branch for img_metas in img_metas] 54 | proposal_list = self.rpn_head.aug_test_rpn(x, trident_img_metas) 55 | return self.roi_head.aug_test( 56 | x, proposal_list, img_metas, rescale=rescale) 57 | 58 | def forward_train(self, img, img_metas, gt_bboxes, gt_labels, **kwargs): 59 | """make copies of img and gts to fit multi-branch.""" 60 | trident_gt_bboxes = tuple(gt_bboxes * self.num_branch) 61 | trident_gt_labels = tuple(gt_labels * self.num_branch) 62 | trident_img_metas = tuple(img_metas * self.num_branch) 63 | 64 | return super(TridentFasterRCNN, 65 | self).forward_train(img, trident_img_metas, 66 | trident_gt_bboxes, trident_gt_labels) 67 | -------------------------------------------------------------------------------- /object_detection/mmdet/models/detectors/vfnet.py: -------------------------------------------------------------------------------- 1 | from ..builder import DETECTORS 2 | from .single_stage import SingleStageDetector 3 | 4 | 5 | @DETECTORS.register_module() 6 | class VFNet(SingleStageDetector): 7 | """Implementation of `VarifocalNet 8 | (VFNet).`_""" 9 | 10 | def __init__(self, 11 | backbone, 12 | neck, 13 | bbox_head, 14 | train_cfg=None, 15 | test_cfg=None, 16 | pretrained=None): 17 | super(VFNet, self).__init__(backbone, neck, bbox_head, train_cfg, 18 | test_cfg, pretrained) 19 | -------------------------------------------------------------------------------- /object_detection/mmdet/models/detectors/yolo.py: -------------------------------------------------------------------------------- 1 | # Copyright (c) 2019 Western Digital Corporation or its affiliates. 2 | 3 | from ..builder import DETECTORS 4 | from .single_stage import SingleStageDetector 5 | 6 | 7 | @DETECTORS.register_module() 8 | class YOLOV3(SingleStageDetector): 9 | 10 | def __init__(self, 11 | backbone, 12 | neck, 13 | bbox_head, 14 | train_cfg=None, 15 | test_cfg=None, 16 | pretrained=None): 17 | super(YOLOV3, self).__init__(backbone, neck, bbox_head, train_cfg, 18 | test_cfg, pretrained) 19 | -------------------------------------------------------------------------------- /object_detection/mmdet/models/losses/__init__.py: -------------------------------------------------------------------------------- 1 | from .accuracy import Accuracy, accuracy 2 | from .ae_loss import AssociativeEmbeddingLoss 3 | from .balanced_l1_loss import BalancedL1Loss, balanced_l1_loss 4 | from .cross_entropy_loss import (CrossEntropyLoss, binary_cross_entropy, 5 | cross_entropy, mask_cross_entropy) 6 | from .focal_loss import FocalLoss, sigmoid_focal_loss 7 | from .gaussian_focal_loss import GaussianFocalLoss 8 | from .gfocal_loss import DistributionFocalLoss, QualityFocalLoss 9 | from .ghm_loss import GHMC, GHMR 10 | from .iou_loss import (BoundedIoULoss, CIoULoss, DIoULoss, GIoULoss, IoULoss, 11 | bounded_iou_loss, iou_loss) 12 | from .kd_loss import KnowledgeDistillationKLDivLoss 13 | from .mse_loss import MSELoss, mse_loss 14 | from .pisa_loss import carl_loss, isr_p 15 | from .smooth_l1_loss import L1Loss, SmoothL1Loss, l1_loss, smooth_l1_loss 16 | from .utils import reduce_loss, weight_reduce_loss, weighted_loss 17 | from .varifocal_loss import VarifocalLoss 18 | 19 | __all__ = [ 20 | 'accuracy', 'Accuracy', 'cross_entropy', 'binary_cross_entropy', 21 | 'mask_cross_entropy', 'CrossEntropyLoss', 'sigmoid_focal_loss', 22 | 'FocalLoss', 'smooth_l1_loss', 'SmoothL1Loss', 'balanced_l1_loss', 23 | 'BalancedL1Loss', 'mse_loss', 'MSELoss', 'iou_loss', 'bounded_iou_loss', 24 | 'IoULoss', 'BoundedIoULoss', 'GIoULoss', 'DIoULoss', 'CIoULoss', 'GHMC', 25 | 'GHMR', 'reduce_loss', 'weight_reduce_loss', 'weighted_loss', 'L1Loss', 26 | 'l1_loss', 'isr_p', 'carl_loss', 'AssociativeEmbeddingLoss', 27 | 'GaussianFocalLoss', 'QualityFocalLoss', 'DistributionFocalLoss', 28 | 'VarifocalLoss', 'KnowledgeDistillationKLDivLoss' 29 | ] 30 | -------------------------------------------------------------------------------- /object_detection/mmdet/models/losses/accuracy.py: -------------------------------------------------------------------------------- 1 | import mmcv 2 | import torch.nn as nn 3 | 4 | 5 | @mmcv.jit(coderize=True) 6 | def accuracy(pred, target, topk=1, thresh=None): 7 | """Calculate accuracy according to the prediction and target. 8 | 9 | Args: 10 | pred (torch.Tensor): The model prediction, shape (N, num_class) 11 | target (torch.Tensor): The target of each prediction, shape (N, ) 12 | topk (int | tuple[int], optional): If the predictions in ``topk`` 13 | matches the target, the predictions will be regarded as 14 | correct ones. Defaults to 1. 15 | thresh (float, optional): If not None, predictions with scores under 16 | this threshold are considered incorrect. Default to None. 17 | 18 | Returns: 19 | float | tuple[float]: If the input ``topk`` is a single integer, 20 | the function will return a single float as accuracy. If 21 | ``topk`` is a tuple containing multiple integers, the 22 | function will return a tuple containing accuracies of 23 | each ``topk`` number. 24 | """ 25 | assert isinstance(topk, (int, tuple)) 26 | if isinstance(topk, int): 27 | topk = (topk, ) 28 | return_single = True 29 | else: 30 | return_single = False 31 | 32 | maxk = max(topk) 33 | if pred.size(0) == 0: 34 | accu = [pred.new_tensor(0.) for i in range(len(topk))] 35 | return accu[0] if return_single else accu 36 | assert pred.ndim == 2 and target.ndim == 1 37 | assert pred.size(0) == target.size(0) 38 | assert maxk <= pred.size(1), \ 39 | f'maxk {maxk} exceeds pred dimension {pred.size(1)}' 40 | pred_value, pred_label = pred.topk(maxk, dim=1) 41 | pred_label = pred_label.t() # transpose to shape (maxk, N) 42 | correct = pred_label.eq(target.view(1, -1).expand_as(pred_label)) 43 | if thresh is not None: 44 | # Only prediction values larger than thresh are counted as correct 45 | correct = correct & (pred_value > thresh).t() 46 | res = [] 47 | for k in topk: 48 | correct_k = correct[:k].reshape(-1).float().sum(0, keepdim=True) 49 | res.append(correct_k.mul_(100.0 / pred.size(0))) 50 | return res[0] if return_single else res 51 | 52 | 53 | class Accuracy(nn.Module): 54 | 55 | def __init__(self, topk=(1, ), thresh=None): 56 | """Module to calculate the accuracy. 57 | 58 | Args: 59 | topk (tuple, optional): The criterion used to calculate the 60 | accuracy. Defaults to (1,). 61 | thresh (float, optional): If not None, predictions with scores 62 | under this threshold are considered incorrect. Default to None. 63 | """ 64 | super().__init__() 65 | self.topk = topk 66 | self.thresh = thresh 67 | 68 | def forward(self, pred, target): 69 | """Forward function to calculate accuracy. 70 | 71 | Args: 72 | pred (torch.Tensor): Prediction of models. 73 | target (torch.Tensor): Target for each prediction. 74 | 75 | Returns: 76 | tuple[float]: The accuracies under different topk criterions. 77 | """ 78 | return accuracy(pred, target, self.topk, self.thresh) 79 | -------------------------------------------------------------------------------- /object_detection/mmdet/models/losses/gaussian_focal_loss.py: -------------------------------------------------------------------------------- 1 | import mmcv 2 | import torch.nn as nn 3 | 4 | from ..builder import LOSSES 5 | from .utils import weighted_loss 6 | 7 | 8 | @mmcv.jit(derivate=True, coderize=True) 9 | @weighted_loss 10 | def gaussian_focal_loss(pred, gaussian_target, alpha=2.0, gamma=4.0): 11 | """`Focal Loss `_ for targets in gaussian 12 | distribution. 13 | 14 | Args: 15 | pred (torch.Tensor): The prediction. 16 | gaussian_target (torch.Tensor): The learning target of the prediction 17 | in gaussian distribution. 18 | alpha (float, optional): A balanced form for Focal Loss. 19 | Defaults to 2.0. 20 | gamma (float, optional): The gamma for calculating the modulating 21 | factor. Defaults to 4.0. 22 | """ 23 | eps = 1e-12 24 | pos_weights = gaussian_target.eq(1) 25 | neg_weights = (1 - gaussian_target).pow(gamma) 26 | pos_loss = -(pred + eps).log() * (1 - pred).pow(alpha) * pos_weights 27 | neg_loss = -(1 - pred + eps).log() * pred.pow(alpha) * neg_weights 28 | return pos_loss + neg_loss 29 | 30 | 31 | @LOSSES.register_module() 32 | class GaussianFocalLoss(nn.Module): 33 | """GaussianFocalLoss is a variant of focal loss. 34 | 35 | More details can be found in the `paper 36 | `_ 37 | Code is modified from `kp_utils.py 38 | `_ # noqa: E501 39 | Please notice that the target in GaussianFocalLoss is a gaussian heatmap, 40 | not 0/1 binary target. 41 | 42 | Args: 43 | alpha (float): Power of prediction. 44 | gamma (float): Power of target for negative samples. 45 | reduction (str): Options are "none", "mean" and "sum". 46 | loss_weight (float): Loss weight of current loss. 47 | """ 48 | 49 | def __init__(self, 50 | alpha=2.0, 51 | gamma=4.0, 52 | reduction='mean', 53 | loss_weight=1.0): 54 | super(GaussianFocalLoss, self).__init__() 55 | self.alpha = alpha 56 | self.gamma = gamma 57 | self.reduction = reduction 58 | self.loss_weight = loss_weight 59 | 60 | def forward(self, 61 | pred, 62 | target, 63 | weight=None, 64 | avg_factor=None, 65 | reduction_override=None): 66 | """Forward function. 67 | 68 | Args: 69 | pred (torch.Tensor): The prediction. 70 | target (torch.Tensor): The learning target of the prediction 71 | in gaussian distribution. 72 | weight (torch.Tensor, optional): The weight of loss for each 73 | prediction. Defaults to None. 74 | avg_factor (int, optional): Average factor that is used to average 75 | the loss. Defaults to None. 76 | reduction_override (str, optional): The reduction method used to 77 | override the original reduction method of the loss. 78 | Defaults to None. 79 | """ 80 | assert reduction_override in (None, 'none', 'mean', 'sum') 81 | reduction = ( 82 | reduction_override if reduction_override else self.reduction) 83 | loss_reg = self.loss_weight * gaussian_focal_loss( 84 | pred, 85 | target, 86 | weight, 87 | alpha=self.alpha, 88 | gamma=self.gamma, 89 | reduction=reduction, 90 | avg_factor=avg_factor) 91 | return loss_reg 92 | -------------------------------------------------------------------------------- /object_detection/mmdet/models/losses/kd_loss.py: -------------------------------------------------------------------------------- 1 | import mmcv 2 | import torch.nn as nn 3 | import torch.nn.functional as F 4 | 5 | from ..builder import LOSSES 6 | from .utils import weighted_loss 7 | 8 | 9 | @mmcv.jit(derivate=True, coderize=True) 10 | @weighted_loss 11 | def knowledge_distillation_kl_div_loss(pred, 12 | soft_label, 13 | T, 14 | detach_target=True): 15 | r"""Loss function for knowledge distilling using KL divergence. 16 | 17 | Args: 18 | pred (Tensor): Predicted logits with shape (N, n + 1). 19 | soft_label (Tensor): Target logits with shape (N, N + 1). 20 | T (int): Temperature for distillation. 21 | detach_target (bool): Remove soft_label from automatic differentiation 22 | 23 | Returns: 24 | torch.Tensor: Loss tensor with shape (N,). 25 | """ 26 | assert pred.size() == soft_label.size() 27 | target = F.softmax(soft_label / T, dim=1) 28 | if detach_target: 29 | target = target.detach() 30 | 31 | kd_loss = F.kl_div( 32 | F.log_softmax(pred / T, dim=1), target, reduction='none').mean(1) * ( 33 | T * T) 34 | 35 | return kd_loss 36 | 37 | 38 | @LOSSES.register_module() 39 | class KnowledgeDistillationKLDivLoss(nn.Module): 40 | """Loss function for knowledge distilling using KL divergence. 41 | 42 | Args: 43 | reduction (str): Options are `'none'`, `'mean'` and `'sum'`. 44 | loss_weight (float): Loss weight of current loss. 45 | T (int): Temperature for distillation. 46 | """ 47 | 48 | def __init__(self, reduction='mean', loss_weight=1.0, T=10): 49 | super(KnowledgeDistillationKLDivLoss, self).__init__() 50 | assert T >= 1 51 | self.reduction = reduction 52 | self.loss_weight = loss_weight 53 | self.T = T 54 | 55 | def forward(self, 56 | pred, 57 | soft_label, 58 | weight=None, 59 | avg_factor=None, 60 | reduction_override=None): 61 | """Forward function. 62 | 63 | Args: 64 | pred (Tensor): Predicted logits with shape (N, n + 1). 65 | soft_label (Tensor): Target logits with shape (N, N + 1). 66 | weight (torch.Tensor, optional): The weight of loss for each 67 | prediction. Defaults to None. 68 | avg_factor (int, optional): Average factor that is used to average 69 | the loss. Defaults to None. 70 | reduction_override (str, optional): The reduction method used to 71 | override the original reduction method of the loss. 72 | Defaults to None. 73 | """ 74 | assert reduction_override in (None, 'none', 'mean', 'sum') 75 | 76 | reduction = ( 77 | reduction_override if reduction_override else self.reduction) 78 | 79 | loss_kd = self.loss_weight * knowledge_distillation_kl_div_loss( 80 | pred, 81 | soft_label, 82 | weight, 83 | reduction=reduction, 84 | avg_factor=avg_factor, 85 | T=self.T) 86 | 87 | return loss_kd 88 | -------------------------------------------------------------------------------- /object_detection/mmdet/models/losses/mse_loss.py: -------------------------------------------------------------------------------- 1 | import torch.nn as nn 2 | import torch.nn.functional as F 3 | 4 | from ..builder import LOSSES 5 | from .utils import weighted_loss 6 | 7 | 8 | @weighted_loss 9 | def mse_loss(pred, target): 10 | """Warpper of mse loss.""" 11 | return F.mse_loss(pred, target, reduction='none') 12 | 13 | 14 | @LOSSES.register_module() 15 | class MSELoss(nn.Module): 16 | """MSELoss. 17 | 18 | Args: 19 | reduction (str, optional): The method that reduces the loss to a 20 | scalar. Options are "none", "mean" and "sum". 21 | loss_weight (float, optional): The weight of the loss. Defaults to 1.0 22 | """ 23 | 24 | def __init__(self, reduction='mean', loss_weight=1.0): 25 | super().__init__() 26 | self.reduction = reduction 27 | self.loss_weight = loss_weight 28 | 29 | def forward(self, pred, target, weight=None, avg_factor=None): 30 | """Forward function of loss. 31 | 32 | Args: 33 | pred (torch.Tensor): The prediction. 34 | target (torch.Tensor): The learning target of the prediction. 35 | weight (torch.Tensor, optional): Weight of the loss for each 36 | prediction. Defaults to None. 37 | avg_factor (int, optional): Average factor that is used to average 38 | the loss. Defaults to None. 39 | 40 | Returns: 41 | torch.Tensor: The calculated loss 42 | """ 43 | loss = self.loss_weight * mse_loss( 44 | pred, 45 | target, 46 | weight, 47 | reduction=self.reduction, 48 | avg_factor=avg_factor) 49 | return loss 50 | -------------------------------------------------------------------------------- /object_detection/mmdet/models/losses/utils.py: -------------------------------------------------------------------------------- 1 | import functools 2 | 3 | import mmcv 4 | import torch.nn.functional as F 5 | 6 | 7 | def reduce_loss(loss, reduction): 8 | """Reduce loss as specified. 9 | 10 | Args: 11 | loss (Tensor): Elementwise loss tensor. 12 | reduction (str): Options are "none", "mean" and "sum". 13 | 14 | Return: 15 | Tensor: Reduced loss tensor. 16 | """ 17 | reduction_enum = F._Reduction.get_enum(reduction) 18 | # none: 0, elementwise_mean:1, sum: 2 19 | if reduction_enum == 0: 20 | return loss 21 | elif reduction_enum == 1: 22 | return loss.mean() 23 | elif reduction_enum == 2: 24 | return loss.sum() 25 | 26 | 27 | @mmcv.jit(derivate=True, coderize=True) 28 | def weight_reduce_loss(loss, weight=None, reduction='mean', avg_factor=None): 29 | """Apply element-wise weight and reduce loss. 30 | 31 | Args: 32 | loss (Tensor): Element-wise loss. 33 | weight (Tensor): Element-wise weights. 34 | reduction (str): Same as built-in losses of PyTorch. 35 | avg_factor (float): Avarage factor when computing the mean of losses. 36 | 37 | Returns: 38 | Tensor: Processed loss values. 39 | """ 40 | # if weight is specified, apply element-wise weight 41 | if weight is not None: 42 | loss = loss * weight 43 | 44 | # if avg_factor is not specified, just reduce the loss 45 | if avg_factor is None: 46 | loss = reduce_loss(loss, reduction) 47 | else: 48 | # if reduction is mean, then average the loss by avg_factor 49 | if reduction == 'mean': 50 | loss = loss.sum() / avg_factor 51 | # if reduction is 'none', then do nothing, otherwise raise an error 52 | elif reduction != 'none': 53 | raise ValueError('avg_factor can not be used with reduction="sum"') 54 | return loss 55 | 56 | 57 | def weighted_loss(loss_func): 58 | """Create a weighted version of a given loss function. 59 | 60 | To use this decorator, the loss function must have the signature like 61 | `loss_func(pred, target, **kwargs)`. The function only needs to compute 62 | element-wise loss without any reduction. This decorator will add weight 63 | and reduction arguments to the function. The decorated function will have 64 | the signature like `loss_func(pred, target, weight=None, reduction='mean', 65 | avg_factor=None, **kwargs)`. 66 | 67 | :Example: 68 | 69 | >>> import torch 70 | >>> @weighted_loss 71 | >>> def l1_loss(pred, target): 72 | >>> return (pred - target).abs() 73 | 74 | >>> pred = torch.Tensor([0, 2, 3]) 75 | >>> target = torch.Tensor([1, 1, 1]) 76 | >>> weight = torch.Tensor([1, 0, 1]) 77 | 78 | >>> l1_loss(pred, target) 79 | tensor(1.3333) 80 | >>> l1_loss(pred, target, weight) 81 | tensor(1.) 82 | >>> l1_loss(pred, target, reduction='none') 83 | tensor([1., 1., 2.]) 84 | >>> l1_loss(pred, target, weight, avg_factor=2) 85 | tensor(1.5000) 86 | """ 87 | 88 | @functools.wraps(loss_func) 89 | def wrapper(pred, 90 | target, 91 | weight=None, 92 | reduction='mean', 93 | avg_factor=None, 94 | **kwargs): 95 | # get element-wise loss 96 | loss = loss_func(pred, target, **kwargs) 97 | loss = weight_reduce_loss(loss, weight, reduction, avg_factor) 98 | return loss 99 | 100 | return wrapper 101 | -------------------------------------------------------------------------------- /object_detection/mmdet/models/necks/__init__.py: -------------------------------------------------------------------------------- 1 | from .bfp import BFP 2 | from .channel_mapper import ChannelMapper 3 | from .fpg import FPG 4 | from .fpn import FPN 5 | from .fpn_carafe import FPN_CARAFE 6 | from .hrfpn import HRFPN 7 | from .nas_fpn import NASFPN 8 | from .nasfcos_fpn import NASFCOS_FPN 9 | from .pafpn import PAFPN 10 | from .rfp import RFP 11 | from .yolo_neck import YOLOV3Neck 12 | 13 | __all__ = [ 14 | 'FPN', 'BFP', 'ChannelMapper', 'HRFPN', 'NASFPN', 'FPN_CARAFE', 'PAFPN', 15 | 'NASFCOS_FPN', 'RFP', 'YOLOV3Neck', 'FPG' 16 | ] 17 | -------------------------------------------------------------------------------- /object_detection/mmdet/models/necks/channel_mapper.py: -------------------------------------------------------------------------------- 1 | import torch.nn as nn 2 | from mmcv.cnn import ConvModule, xavier_init 3 | 4 | from ..builder import NECKS 5 | 6 | 7 | @NECKS.register_module() 8 | class ChannelMapper(nn.Module): 9 | r"""Channel Mapper to reduce/increase channels of backbone features. 10 | 11 | This is used to reduce/increase channels of backbone features. 12 | 13 | Args: 14 | in_channels (List[int]): Number of input channels per scale. 15 | out_channels (int): Number of output channels (used at each scale). 16 | kernel_size (int, optional): kernel_size for reducing channels (used 17 | at each scale). Default: 3. 18 | conv_cfg (dict, optional): Config dict for convolution layer. 19 | Default: None. 20 | norm_cfg (dict, optional): Config dict for normalization layer. 21 | Default: None. 22 | act_cfg (dict, optional): Config dict for activation layer in 23 | ConvModule. Default: dict(type='ReLU'). 24 | 25 | Example: 26 | >>> import torch 27 | >>> in_channels = [2, 3, 5, 7] 28 | >>> scales = [340, 170, 84, 43] 29 | >>> inputs = [torch.rand(1, c, s, s) 30 | ... for c, s in zip(in_channels, scales)] 31 | >>> self = ChannelMapper(in_channels, 11, 3).eval() 32 | >>> outputs = self.forward(inputs) 33 | >>> for i in range(len(outputs)): 34 | ... print(f'outputs[{i}].shape = {outputs[i].shape}') 35 | outputs[0].shape = torch.Size([1, 11, 340, 340]) 36 | outputs[1].shape = torch.Size([1, 11, 170, 170]) 37 | outputs[2].shape = torch.Size([1, 11, 84, 84]) 38 | outputs[3].shape = torch.Size([1, 11, 43, 43]) 39 | """ 40 | 41 | def __init__(self, 42 | in_channels, 43 | out_channels, 44 | kernel_size=3, 45 | conv_cfg=None, 46 | norm_cfg=None, 47 | act_cfg=dict(type='ReLU')): 48 | super(ChannelMapper, self).__init__() 49 | assert isinstance(in_channels, list) 50 | 51 | self.convs = nn.ModuleList() 52 | for in_channel in in_channels: 53 | self.convs.append( 54 | ConvModule( 55 | in_channel, 56 | out_channels, 57 | kernel_size, 58 | padding=(kernel_size - 1) // 2, 59 | conv_cfg=conv_cfg, 60 | norm_cfg=norm_cfg, 61 | act_cfg=act_cfg)) 62 | 63 | # default init_weights for conv(msra) and norm in ConvModule 64 | def init_weights(self): 65 | """Initialize the weights of ChannelMapper module.""" 66 | for m in self.modules(): 67 | if isinstance(m, nn.Conv2d): 68 | xavier_init(m, distribution='uniform') 69 | 70 | def forward(self, inputs): 71 | """Forward function.""" 72 | assert len(inputs) == len(self.convs) 73 | outs = [self.convs[i](inputs[i]) for i in range(len(inputs))] 74 | return tuple(outs) 75 | -------------------------------------------------------------------------------- /object_detection/mmdet/models/necks/hrfpn.py: -------------------------------------------------------------------------------- 1 | import torch 2 | import torch.nn as nn 3 | import torch.nn.functional as F 4 | from mmcv.cnn import ConvModule, caffe2_xavier_init 5 | from torch.utils.checkpoint import checkpoint 6 | 7 | from ..builder import NECKS 8 | 9 | 10 | @NECKS.register_module() 11 | class HRFPN(nn.Module): 12 | """HRFPN (High Resolution Feature Pyramids) 13 | 14 | paper: `High-Resolution Representations for Labeling Pixels and Regions 15 | `_. 16 | 17 | Args: 18 | in_channels (list): number of channels for each branch. 19 | out_channels (int): output channels of feature pyramids. 20 | num_outs (int): number of output stages. 21 | pooling_type (str): pooling for generating feature pyramids 22 | from {MAX, AVG}. 23 | conv_cfg (dict): dictionary to construct and config conv layer. 24 | norm_cfg (dict): dictionary to construct and config norm layer. 25 | with_cp (bool): Use checkpoint or not. Using checkpoint will save some 26 | memory while slowing down the training speed. 27 | stride (int): stride of 3x3 convolutional layers 28 | """ 29 | 30 | def __init__(self, 31 | in_channels, 32 | out_channels, 33 | num_outs=5, 34 | pooling_type='AVG', 35 | conv_cfg=None, 36 | norm_cfg=None, 37 | with_cp=False, 38 | stride=1): 39 | super(HRFPN, self).__init__() 40 | assert isinstance(in_channels, list) 41 | self.in_channels = in_channels 42 | self.out_channels = out_channels 43 | self.num_ins = len(in_channels) 44 | self.num_outs = num_outs 45 | self.with_cp = with_cp 46 | self.conv_cfg = conv_cfg 47 | self.norm_cfg = norm_cfg 48 | 49 | self.reduction_conv = ConvModule( 50 | sum(in_channels), 51 | out_channels, 52 | kernel_size=1, 53 | conv_cfg=self.conv_cfg, 54 | act_cfg=None) 55 | 56 | self.fpn_convs = nn.ModuleList() 57 | for i in range(self.num_outs): 58 | self.fpn_convs.append( 59 | ConvModule( 60 | out_channels, 61 | out_channels, 62 | kernel_size=3, 63 | padding=1, 64 | stride=stride, 65 | conv_cfg=self.conv_cfg, 66 | act_cfg=None)) 67 | 68 | if pooling_type == 'MAX': 69 | self.pooling = F.max_pool2d 70 | else: 71 | self.pooling = F.avg_pool2d 72 | 73 | def init_weights(self): 74 | """Initialize the weights of module.""" 75 | for m in self.modules(): 76 | if isinstance(m, nn.Conv2d): 77 | caffe2_xavier_init(m) 78 | 79 | def forward(self, inputs): 80 | """Forward function.""" 81 | assert len(inputs) == self.num_ins 82 | outs = [inputs[0]] 83 | for i in range(1, self.num_ins): 84 | outs.append( 85 | F.interpolate(inputs[i], scale_factor=2**i, mode='bilinear')) 86 | out = torch.cat(outs, dim=1) 87 | if out.requires_grad and self.with_cp: 88 | out = checkpoint(self.reduction_conv, out) 89 | else: 90 | out = self.reduction_conv(out) 91 | outs = [out] 92 | for i in range(1, self.num_outs): 93 | outs.append(self.pooling(out, kernel_size=2**i, stride=2**i)) 94 | outputs = [] 95 | 96 | for i in range(self.num_outs): 97 | if outs[i].requires_grad and self.with_cp: 98 | tmp_out = checkpoint(self.fpn_convs[i], outs[i]) 99 | else: 100 | tmp_out = self.fpn_convs[i](outs[i]) 101 | outputs.append(tmp_out) 102 | return tuple(outputs) 103 | -------------------------------------------------------------------------------- /object_detection/mmdet/models/roi_heads/__init__.py: -------------------------------------------------------------------------------- 1 | from .base_roi_head import BaseRoIHead 2 | from .bbox_heads import (BBoxHead, ConvFCBBoxHead, DoubleConvFCBBoxHead, 3 | SCNetBBoxHead, Shared2FCBBoxHead, 4 | Shared4Conv1FCBBoxHead) 5 | from .cascade_roi_head import CascadeRoIHead 6 | from .double_roi_head import DoubleHeadRoIHead 7 | from .dynamic_roi_head import DynamicRoIHead 8 | from .grid_roi_head import GridRoIHead 9 | from .htc_roi_head import HybridTaskCascadeRoIHead 10 | from .mask_heads import (CoarseMaskHead, FCNMaskHead, FeatureRelayHead, 11 | FusedSemanticHead, GlobalContextHead, GridHead, 12 | HTCMaskHead, MaskIoUHead, MaskPointHead, 13 | SCNetMaskHead, SCNetSemanticHead) 14 | from .mask_scoring_roi_head import MaskScoringRoIHead 15 | from .pisa_roi_head import PISARoIHead 16 | from .point_rend_roi_head import PointRendRoIHead 17 | from .roi_extractors import SingleRoIExtractor 18 | from .scnet_roi_head import SCNetRoIHead 19 | from .shared_heads import ResLayer 20 | from .sparse_roi_head import SparseRoIHead 21 | from .standard_roi_head import StandardRoIHead 22 | from .trident_roi_head import TridentRoIHead 23 | 24 | __all__ = [ 25 | 'BaseRoIHead', 'CascadeRoIHead', 'DoubleHeadRoIHead', 'MaskScoringRoIHead', 26 | 'HybridTaskCascadeRoIHead', 'GridRoIHead', 'ResLayer', 'BBoxHead', 27 | 'ConvFCBBoxHead', 'Shared2FCBBoxHead', 'StandardRoIHead', 28 | 'Shared4Conv1FCBBoxHead', 'DoubleConvFCBBoxHead', 'FCNMaskHead', 29 | 'HTCMaskHead', 'FusedSemanticHead', 'GridHead', 'MaskIoUHead', 30 | 'SingleRoIExtractor', 'PISARoIHead', 'PointRendRoIHead', 'MaskPointHead', 31 | 'CoarseMaskHead', 'DynamicRoIHead', 'SparseRoIHead', 'TridentRoIHead', 32 | 'SCNetRoIHead', 'SCNetMaskHead', 'SCNetSemanticHead', 'SCNetBBoxHead', 33 | 'FeatureRelayHead', 'GlobalContextHead' 34 | ] 35 | -------------------------------------------------------------------------------- /object_detection/mmdet/models/roi_heads/base_roi_head.py: -------------------------------------------------------------------------------- 1 | from abc import ABCMeta, abstractmethod 2 | 3 | import torch.nn as nn 4 | 5 | from ..builder import build_shared_head 6 | 7 | 8 | class BaseRoIHead(nn.Module, metaclass=ABCMeta): 9 | """Base class for RoIHeads.""" 10 | 11 | def __init__(self, 12 | bbox_roi_extractor=None, 13 | bbox_head=None, 14 | mask_roi_extractor=None, 15 | mask_head=None, 16 | shared_head=None, 17 | train_cfg=None, 18 | test_cfg=None): 19 | super(BaseRoIHead, self).__init__() 20 | self.train_cfg = train_cfg 21 | self.test_cfg = test_cfg 22 | if shared_head is not None: 23 | self.shared_head = build_shared_head(shared_head) 24 | 25 | if bbox_head is not None: 26 | self.init_bbox_head(bbox_roi_extractor, bbox_head) 27 | 28 | if mask_head is not None: 29 | self.init_mask_head(mask_roi_extractor, mask_head) 30 | 31 | self.init_assigner_sampler() 32 | 33 | @property 34 | def with_bbox(self): 35 | """bool: whether the RoI head contains a `bbox_head`""" 36 | return hasattr(self, 'bbox_head') and self.bbox_head is not None 37 | 38 | @property 39 | def with_mask(self): 40 | """bool: whether the RoI head contains a `mask_head`""" 41 | return hasattr(self, 'mask_head') and self.mask_head is not None 42 | 43 | @property 44 | def with_shared_head(self): 45 | """bool: whether the RoI head contains a `shared_head`""" 46 | return hasattr(self, 'shared_head') and self.shared_head is not None 47 | 48 | @abstractmethod 49 | def init_weights(self, pretrained): 50 | """Initialize the weights in head. 51 | 52 | Args: 53 | pretrained (str, optional): Path to pre-trained weights. 54 | Defaults to None. 55 | """ 56 | pass 57 | 58 | @abstractmethod 59 | def init_bbox_head(self): 60 | """Initialize ``bbox_head``""" 61 | pass 62 | 63 | @abstractmethod 64 | def init_mask_head(self): 65 | """Initialize ``mask_head``""" 66 | pass 67 | 68 | @abstractmethod 69 | def init_assigner_sampler(self): 70 | """Initialize assigner and sampler.""" 71 | pass 72 | 73 | @abstractmethod 74 | def forward_train(self, 75 | x, 76 | img_meta, 77 | proposal_list, 78 | gt_bboxes, 79 | gt_labels, 80 | gt_bboxes_ignore=None, 81 | gt_masks=None, 82 | **kwargs): 83 | """Forward function during training.""" 84 | 85 | async def async_simple_test(self, x, img_meta, **kwargs): 86 | """Asynchronized test function.""" 87 | raise NotImplementedError 88 | 89 | def simple_test(self, 90 | x, 91 | proposal_list, 92 | img_meta, 93 | proposals=None, 94 | rescale=False, 95 | **kwargs): 96 | """Test without augmentation.""" 97 | 98 | def aug_test(self, x, proposal_list, img_metas, rescale=False, **kwargs): 99 | """Test with augmentations. 100 | 101 | If rescale is False, then returned bboxes and masks will fit the scale 102 | of imgs[0]. 103 | """ 104 | -------------------------------------------------------------------------------- /object_detection/mmdet/models/roi_heads/bbox_heads/__init__.py: -------------------------------------------------------------------------------- 1 | from .bbox_head import BBoxHead 2 | from .convfc_bbox_head import (ConvFCBBoxHead, Shared2FCBBoxHead, 3 | Shared4Conv1FCBBoxHead) 4 | from .dii_head import DIIHead 5 | from .double_bbox_head import DoubleConvFCBBoxHead 6 | from .sabl_head import SABLHead 7 | from .scnet_bbox_head import SCNetBBoxHead 8 | 9 | __all__ = [ 10 | 'BBoxHead', 'ConvFCBBoxHead', 'Shared2FCBBoxHead', 11 | 'Shared4Conv1FCBBoxHead', 'DoubleConvFCBBoxHead', 'SABLHead', 'DIIHead', 12 | 'SCNetBBoxHead' 13 | ] 14 | -------------------------------------------------------------------------------- /object_detection/mmdet/models/roi_heads/bbox_heads/scnet_bbox_head.py: -------------------------------------------------------------------------------- 1 | from mmdet.models.builder import HEADS 2 | from .convfc_bbox_head import ConvFCBBoxHead 3 | 4 | 5 | @HEADS.register_module() 6 | class SCNetBBoxHead(ConvFCBBoxHead): 7 | """BBox head for `SCNet `_. 8 | 9 | This inherits ``ConvFCBBoxHead`` with modified forward() function, allow us 10 | to get intermediate shared feature. 11 | """ 12 | 13 | def _forward_shared(self, x): 14 | """Forward function for shared part.""" 15 | if self.num_shared_convs > 0: 16 | for conv in self.shared_convs: 17 | x = conv(x) 18 | 19 | if self.num_shared_fcs > 0: 20 | if self.with_avg_pool: 21 | x = self.avg_pool(x) 22 | 23 | x = x.flatten(1) 24 | 25 | for fc in self.shared_fcs: 26 | x = self.relu(fc(x)) 27 | 28 | return x 29 | 30 | def _forward_cls_reg(self, x): 31 | """Forward function for classification and regression parts.""" 32 | x_cls = x 33 | x_reg = x 34 | 35 | for conv in self.cls_convs: 36 | x_cls = conv(x_cls) 37 | if x_cls.dim() > 2: 38 | if self.with_avg_pool: 39 | x_cls = self.avg_pool(x_cls) 40 | x_cls = x_cls.flatten(1) 41 | for fc in self.cls_fcs: 42 | x_cls = self.relu(fc(x_cls)) 43 | 44 | for conv in self.reg_convs: 45 | x_reg = conv(x_reg) 46 | if x_reg.dim() > 2: 47 | if self.with_avg_pool: 48 | x_reg = self.avg_pool(x_reg) 49 | x_reg = x_reg.flatten(1) 50 | for fc in self.reg_fcs: 51 | x_reg = self.relu(fc(x_reg)) 52 | 53 | cls_score = self.fc_cls(x_cls) if self.with_cls else None 54 | bbox_pred = self.fc_reg(x_reg) if self.with_reg else None 55 | 56 | return cls_score, bbox_pred 57 | 58 | def forward(self, x, return_shared_feat=False): 59 | """Forward function. 60 | 61 | Args: 62 | x (Tensor): input features 63 | return_shared_feat (bool): If True, return cls-reg-shared feature. 64 | 65 | Return: 66 | out (tuple[Tensor]): contain ``cls_score`` and ``bbox_pred``, 67 | if ``return_shared_feat`` is True, append ``x_shared`` to the 68 | returned tuple. 69 | """ 70 | x_shared = self._forward_shared(x) 71 | out = self._forward_cls_reg(x_shared) 72 | 73 | if return_shared_feat: 74 | out += (x_shared, ) 75 | 76 | return out 77 | -------------------------------------------------------------------------------- /object_detection/mmdet/models/roi_heads/double_roi_head.py: -------------------------------------------------------------------------------- 1 | from ..builder import HEADS 2 | from .standard_roi_head import StandardRoIHead 3 | 4 | 5 | @HEADS.register_module() 6 | class DoubleHeadRoIHead(StandardRoIHead): 7 | """RoI head for Double Head RCNN. 8 | 9 | https://arxiv.org/abs/1904.06493 10 | """ 11 | 12 | def __init__(self, reg_roi_scale_factor, **kwargs): 13 | super(DoubleHeadRoIHead, self).__init__(**kwargs) 14 | self.reg_roi_scale_factor = reg_roi_scale_factor 15 | 16 | def _bbox_forward(self, x, rois): 17 | """Box head forward function used in both training and testing time.""" 18 | bbox_cls_feats = self.bbox_roi_extractor( 19 | x[:self.bbox_roi_extractor.num_inputs], rois) 20 | bbox_reg_feats = self.bbox_roi_extractor( 21 | x[:self.bbox_roi_extractor.num_inputs], 22 | rois, 23 | roi_scale_factor=self.reg_roi_scale_factor) 24 | if self.with_shared_head: 25 | bbox_cls_feats = self.shared_head(bbox_cls_feats) 26 | bbox_reg_feats = self.shared_head(bbox_reg_feats) 27 | cls_score, bbox_pred = self.bbox_head(bbox_cls_feats, bbox_reg_feats) 28 | 29 | bbox_results = dict( 30 | cls_score=cls_score, 31 | bbox_pred=bbox_pred, 32 | bbox_feats=bbox_cls_feats) 33 | return bbox_results 34 | -------------------------------------------------------------------------------- /object_detection/mmdet/models/roi_heads/mask_heads/__init__.py: -------------------------------------------------------------------------------- 1 | from .coarse_mask_head import CoarseMaskHead 2 | from .fcn_mask_head import FCNMaskHead 3 | from .feature_relay_head import FeatureRelayHead 4 | from .fused_semantic_head import FusedSemanticHead 5 | from .global_context_head import GlobalContextHead 6 | from .grid_head import GridHead 7 | from .htc_mask_head import HTCMaskHead 8 | from .mask_point_head import MaskPointHead 9 | from .maskiou_head import MaskIoUHead 10 | from .scnet_mask_head import SCNetMaskHead 11 | from .scnet_semantic_head import SCNetSemanticHead 12 | 13 | __all__ = [ 14 | 'FCNMaskHead', 'HTCMaskHead', 'FusedSemanticHead', 'GridHead', 15 | 'MaskIoUHead', 'CoarseMaskHead', 'MaskPointHead', 'SCNetMaskHead', 16 | 'SCNetSemanticHead', 'GlobalContextHead', 'FeatureRelayHead' 17 | ] 18 | -------------------------------------------------------------------------------- /object_detection/mmdet/models/roi_heads/mask_heads/coarse_mask_head.py: -------------------------------------------------------------------------------- 1 | import torch.nn as nn 2 | from mmcv.cnn import ConvModule, Linear, constant_init, xavier_init 3 | from mmcv.runner import auto_fp16 4 | 5 | from mmdet.models.builder import HEADS 6 | from .fcn_mask_head import FCNMaskHead 7 | 8 | 9 | @HEADS.register_module() 10 | class CoarseMaskHead(FCNMaskHead): 11 | """Coarse mask head used in PointRend. 12 | 13 | Compared with standard ``FCNMaskHead``, ``CoarseMaskHead`` will downsample 14 | the input feature map instead of upsample it. 15 | 16 | Args: 17 | num_convs (int): Number of conv layers in the head. Default: 0. 18 | num_fcs (int): Number of fc layers in the head. Default: 2. 19 | fc_out_channels (int): Number of output channels of fc layer. 20 | Default: 1024. 21 | downsample_factor (int): The factor that feature map is downsampled by. 22 | Default: 2. 23 | """ 24 | 25 | def __init__(self, 26 | num_convs=0, 27 | num_fcs=2, 28 | fc_out_channels=1024, 29 | downsample_factor=2, 30 | *arg, 31 | **kwarg): 32 | super(CoarseMaskHead, self).__init__( 33 | *arg, num_convs=num_convs, upsample_cfg=dict(type=None), **kwarg) 34 | self.num_fcs = num_fcs 35 | assert self.num_fcs > 0 36 | self.fc_out_channels = fc_out_channels 37 | self.downsample_factor = downsample_factor 38 | assert self.downsample_factor >= 1 39 | # remove conv_logit 40 | delattr(self, 'conv_logits') 41 | 42 | if downsample_factor > 1: 43 | downsample_in_channels = ( 44 | self.conv_out_channels 45 | if self.num_convs > 0 else self.in_channels) 46 | self.downsample_conv = ConvModule( 47 | downsample_in_channels, 48 | self.conv_out_channels, 49 | kernel_size=downsample_factor, 50 | stride=downsample_factor, 51 | padding=0, 52 | conv_cfg=self.conv_cfg, 53 | norm_cfg=self.norm_cfg) 54 | else: 55 | self.downsample_conv = None 56 | 57 | self.output_size = (self.roi_feat_size[0] // downsample_factor, 58 | self.roi_feat_size[1] // downsample_factor) 59 | self.output_area = self.output_size[0] * self.output_size[1] 60 | 61 | last_layer_dim = self.conv_out_channels * self.output_area 62 | 63 | self.fcs = nn.ModuleList() 64 | for i in range(num_fcs): 65 | fc_in_channels = ( 66 | last_layer_dim if i == 0 else self.fc_out_channels) 67 | self.fcs.append(Linear(fc_in_channels, self.fc_out_channels)) 68 | last_layer_dim = self.fc_out_channels 69 | output_channels = self.num_classes * self.output_area 70 | self.fc_logits = Linear(last_layer_dim, output_channels) 71 | 72 | def init_weights(self): 73 | for m in self.fcs.modules(): 74 | if isinstance(m, nn.Linear): 75 | xavier_init(m) 76 | constant_init(self.fc_logits, 0.001) 77 | 78 | @auto_fp16() 79 | def forward(self, x): 80 | for conv in self.convs: 81 | x = conv(x) 82 | 83 | if self.downsample_conv is not None: 84 | x = self.downsample_conv(x) 85 | 86 | x = x.flatten(1) 87 | for fc in self.fcs: 88 | x = self.relu(fc(x)) 89 | mask_pred = self.fc_logits(x).view( 90 | x.size(0), self.num_classes, *self.output_size) 91 | return mask_pred 92 | -------------------------------------------------------------------------------- /object_detection/mmdet/models/roi_heads/mask_heads/feature_relay_head.py: -------------------------------------------------------------------------------- 1 | import torch.nn as nn 2 | from mmcv.cnn import kaiming_init 3 | from mmcv.runner import auto_fp16 4 | 5 | from mmdet.models.builder import HEADS 6 | 7 | 8 | @HEADS.register_module() 9 | class FeatureRelayHead(nn.Module): 10 | """Feature Relay Head used in `SCNet `_. 11 | 12 | Args: 13 | in_channels (int, optional): number of input channels. Default: 256. 14 | conv_out_channels (int, optional): number of output channels before 15 | classification layer. Default: 256. 16 | roi_feat_size (int, optional): roi feat size at box head. Default: 7. 17 | scale_factor (int, optional): scale factor to match roi feat size 18 | at mask head. Default: 2. 19 | """ 20 | 21 | def __init__(self, 22 | in_channels=1024, 23 | out_conv_channels=256, 24 | roi_feat_size=7, 25 | scale_factor=2): 26 | super(FeatureRelayHead, self).__init__() 27 | assert isinstance(roi_feat_size, int) 28 | 29 | self.in_channels = in_channels 30 | self.out_conv_channels = out_conv_channels 31 | self.roi_feat_size = roi_feat_size 32 | self.out_channels = (roi_feat_size**2) * out_conv_channels 33 | self.scale_factor = scale_factor 34 | self.fp16_enabled = False 35 | 36 | self.fc = nn.Linear(self.in_channels, self.out_channels) 37 | self.upsample = nn.Upsample( 38 | scale_factor=scale_factor, mode='bilinear', align_corners=True) 39 | 40 | def init_weights(self): 41 | """Init weights for the head.""" 42 | kaiming_init(self.fc) 43 | 44 | @auto_fp16() 45 | def forward(self, x): 46 | """Forward function.""" 47 | N, in_C = x.shape 48 | if N > 0: 49 | out_C = self.out_conv_channels 50 | out_HW = self.roi_feat_size 51 | x = self.fc(x) 52 | x = x.reshape(N, out_C, out_HW, out_HW) 53 | x = self.upsample(x) 54 | return x 55 | return None 56 | -------------------------------------------------------------------------------- /object_detection/mmdet/models/roi_heads/mask_heads/fused_semantic_head.py: -------------------------------------------------------------------------------- 1 | import torch.nn as nn 2 | import torch.nn.functional as F 3 | from mmcv.cnn import ConvModule, kaiming_init 4 | from mmcv.runner import auto_fp16, force_fp32 5 | 6 | from mmdet.models.builder import HEADS 7 | 8 | 9 | @HEADS.register_module() 10 | class FusedSemanticHead(nn.Module): 11 | r"""Multi-level fused semantic segmentation head. 12 | 13 | .. code-block:: none 14 | 15 | in_1 -> 1x1 conv --- 16 | | 17 | in_2 -> 1x1 conv -- | 18 | || 19 | in_3 -> 1x1 conv - || 20 | ||| /-> 1x1 conv (mask prediction) 21 | in_4 -> 1x1 conv -----> 3x3 convs (*4) 22 | | \-> 1x1 conv (feature) 23 | in_5 -> 1x1 conv --- 24 | """ # noqa: W605 25 | 26 | def __init__(self, 27 | num_ins, 28 | fusion_level, 29 | num_convs=4, 30 | in_channels=256, 31 | conv_out_channels=256, 32 | num_classes=183, 33 | ignore_label=255, 34 | loss_weight=0.2, 35 | conv_cfg=None, 36 | norm_cfg=None): 37 | super(FusedSemanticHead, self).__init__() 38 | self.num_ins = num_ins 39 | self.fusion_level = fusion_level 40 | self.num_convs = num_convs 41 | self.in_channels = in_channels 42 | self.conv_out_channels = conv_out_channels 43 | self.num_classes = num_classes 44 | self.ignore_label = ignore_label 45 | self.loss_weight = loss_weight 46 | self.conv_cfg = conv_cfg 47 | self.norm_cfg = norm_cfg 48 | self.fp16_enabled = False 49 | 50 | self.lateral_convs = nn.ModuleList() 51 | for i in range(self.num_ins): 52 | self.lateral_convs.append( 53 | ConvModule( 54 | self.in_channels, 55 | self.in_channels, 56 | 1, 57 | conv_cfg=self.conv_cfg, 58 | norm_cfg=self.norm_cfg, 59 | inplace=False)) 60 | 61 | self.convs = nn.ModuleList() 62 | for i in range(self.num_convs): 63 | in_channels = self.in_channels if i == 0 else conv_out_channels 64 | self.convs.append( 65 | ConvModule( 66 | in_channels, 67 | conv_out_channels, 68 | 3, 69 | padding=1, 70 | conv_cfg=self.conv_cfg, 71 | norm_cfg=self.norm_cfg)) 72 | self.conv_embedding = ConvModule( 73 | conv_out_channels, 74 | conv_out_channels, 75 | 1, 76 | conv_cfg=self.conv_cfg, 77 | norm_cfg=self.norm_cfg) 78 | self.conv_logits = nn.Conv2d(conv_out_channels, self.num_classes, 1) 79 | 80 | self.criterion = nn.CrossEntropyLoss(ignore_index=ignore_label) 81 | 82 | def init_weights(self): 83 | kaiming_init(self.conv_logits) 84 | 85 | @auto_fp16() 86 | def forward(self, feats): 87 | x = self.lateral_convs[self.fusion_level](feats[self.fusion_level]) 88 | fused_size = tuple(x.shape[-2:]) 89 | for i, feat in enumerate(feats): 90 | if i != self.fusion_level: 91 | feat = F.interpolate( 92 | feat, size=fused_size, mode='bilinear', align_corners=True) 93 | x += self.lateral_convs[i](feat) 94 | 95 | for i in range(self.num_convs): 96 | x = self.convs[i](x) 97 | 98 | mask_pred = self.conv_logits(x) 99 | x = self.conv_embedding(x) 100 | return mask_pred, x 101 | 102 | @force_fp32(apply_to=('mask_pred', )) 103 | def loss(self, mask_pred, labels): 104 | labels = labels.squeeze(1).long() 105 | loss_semantic_seg = self.criterion(mask_pred, labels) 106 | loss_semantic_seg *= self.loss_weight 107 | return loss_semantic_seg 108 | -------------------------------------------------------------------------------- /object_detection/mmdet/models/roi_heads/mask_heads/htc_mask_head.py: -------------------------------------------------------------------------------- 1 | from mmcv.cnn import ConvModule 2 | 3 | from mmdet.models.builder import HEADS 4 | from .fcn_mask_head import FCNMaskHead 5 | 6 | 7 | @HEADS.register_module() 8 | class HTCMaskHead(FCNMaskHead): 9 | 10 | def __init__(self, with_conv_res=True, *args, **kwargs): 11 | super(HTCMaskHead, self).__init__(*args, **kwargs) 12 | self.with_conv_res = with_conv_res 13 | if self.with_conv_res: 14 | self.conv_res = ConvModule( 15 | self.conv_out_channels, 16 | self.conv_out_channels, 17 | 1, 18 | conv_cfg=self.conv_cfg, 19 | norm_cfg=self.norm_cfg) 20 | 21 | def init_weights(self): 22 | super(HTCMaskHead, self).init_weights() 23 | if self.with_conv_res: 24 | self.conv_res.init_weights() 25 | 26 | def forward(self, x, res_feat=None, return_logits=True, return_feat=True): 27 | if res_feat is not None: 28 | assert self.with_conv_res 29 | res_feat = self.conv_res(res_feat) 30 | x = x + res_feat 31 | for conv in self.convs: 32 | x = conv(x) 33 | res_feat = x 34 | outs = [] 35 | if return_logits: 36 | x = self.upsample(x) 37 | if self.upsample_method == 'deconv': 38 | x = self.relu(x) 39 | mask_pred = self.conv_logits(x) 40 | outs.append(mask_pred) 41 | if return_feat: 42 | outs.append(res_feat) 43 | return outs if len(outs) > 1 else outs[0] 44 | -------------------------------------------------------------------------------- /object_detection/mmdet/models/roi_heads/mask_heads/scnet_mask_head.py: -------------------------------------------------------------------------------- 1 | from mmdet.models.builder import HEADS 2 | from mmdet.models.utils import ResLayer, SimplifiedBasicBlock 3 | from .fcn_mask_head import FCNMaskHead 4 | 5 | 6 | @HEADS.register_module() 7 | class SCNetMaskHead(FCNMaskHead): 8 | """Mask head for `SCNet `_. 9 | 10 | Args: 11 | conv_to_res (bool, optional): if True, change the conv layers to 12 | ``SimplifiedBasicBlock``. 13 | """ 14 | 15 | def __init__(self, conv_to_res=True, **kwargs): 16 | super(SCNetMaskHead, self).__init__(**kwargs) 17 | self.conv_to_res = conv_to_res 18 | if conv_to_res: 19 | assert self.conv_kernel_size == 3 20 | self.num_res_blocks = self.num_convs // 2 21 | self.convs = ResLayer( 22 | SimplifiedBasicBlock, 23 | self.in_channels, 24 | self.conv_out_channels, 25 | self.num_res_blocks, 26 | conv_cfg=self.conv_cfg, 27 | norm_cfg=self.norm_cfg) 28 | -------------------------------------------------------------------------------- /object_detection/mmdet/models/roi_heads/mask_heads/scnet_semantic_head.py: -------------------------------------------------------------------------------- 1 | from mmdet.models.builder import HEADS 2 | from mmdet.models.utils import ResLayer, SimplifiedBasicBlock 3 | from .fused_semantic_head import FusedSemanticHead 4 | 5 | 6 | @HEADS.register_module() 7 | class SCNetSemanticHead(FusedSemanticHead): 8 | """Mask head for `SCNet `_. 9 | 10 | Args: 11 | conv_to_res (bool, optional): if True, change the conv layers to 12 | ``SimplifiedBasicBlock``. 13 | """ 14 | 15 | def __init__(self, conv_to_res=True, **kwargs): 16 | super(SCNetSemanticHead, self).__init__(**kwargs) 17 | self.conv_to_res = conv_to_res 18 | if self.conv_to_res: 19 | num_res_blocks = self.num_convs // 2 20 | self.convs = ResLayer( 21 | SimplifiedBasicBlock, 22 | self.in_channels, 23 | self.conv_out_channels, 24 | num_res_blocks, 25 | conv_cfg=self.conv_cfg, 26 | norm_cfg=self.norm_cfg) 27 | self.num_convs = num_res_blocks 28 | -------------------------------------------------------------------------------- /object_detection/mmdet/models/roi_heads/roi_extractors/__init__.py: -------------------------------------------------------------------------------- 1 | from .generic_roi_extractor import GenericRoIExtractor 2 | from .single_level_roi_extractor import SingleRoIExtractor 3 | 4 | __all__ = [ 5 | 'SingleRoIExtractor', 6 | 'GenericRoIExtractor', 7 | ] 8 | -------------------------------------------------------------------------------- /object_detection/mmdet/models/roi_heads/roi_extractors/base_roi_extractor.py: -------------------------------------------------------------------------------- 1 | from abc import ABCMeta, abstractmethod 2 | 3 | import torch 4 | import torch.nn as nn 5 | from mmcv import ops 6 | 7 | 8 | class BaseRoIExtractor(nn.Module, metaclass=ABCMeta): 9 | """Base class for RoI extractor. 10 | 11 | Args: 12 | roi_layer (dict): Specify RoI layer type and arguments. 13 | out_channels (int): Output channels of RoI layers. 14 | featmap_strides (List[int]): Strides of input feature maps. 15 | """ 16 | 17 | def __init__(self, roi_layer, out_channels, featmap_strides): 18 | super(BaseRoIExtractor, self).__init__() 19 | self.roi_layers = self.build_roi_layers(roi_layer, featmap_strides) 20 | self.out_channels = out_channels 21 | self.featmap_strides = featmap_strides 22 | self.fp16_enabled = False 23 | 24 | @property 25 | def num_inputs(self): 26 | """int: Number of input feature maps.""" 27 | return len(self.featmap_strides) 28 | 29 | def init_weights(self): 30 | pass 31 | 32 | def build_roi_layers(self, layer_cfg, featmap_strides): 33 | """Build RoI operator to extract feature from each level feature map. 34 | 35 | Args: 36 | layer_cfg (dict): Dictionary to construct and config RoI layer 37 | operation. Options are modules under ``mmcv/ops`` such as 38 | ``RoIAlign``. 39 | featmap_strides (List[int]): The stride of input feature map w.r.t 40 | to the original image size, which would be used to scale RoI 41 | coordinate (original image coordinate system) to feature 42 | coordinate system. 43 | 44 | Returns: 45 | nn.ModuleList: The RoI extractor modules for each level feature 46 | map. 47 | """ 48 | 49 | cfg = layer_cfg.copy() 50 | layer_type = cfg.pop('type') 51 | assert hasattr(ops, layer_type) 52 | layer_cls = getattr(ops, layer_type) 53 | roi_layers = nn.ModuleList( 54 | [layer_cls(spatial_scale=1 / s, **cfg) for s in featmap_strides]) 55 | return roi_layers 56 | 57 | def roi_rescale(self, rois, scale_factor): 58 | """Scale RoI coordinates by scale factor. 59 | 60 | Args: 61 | rois (torch.Tensor): RoI (Region of Interest), shape (n, 5) 62 | scale_factor (float): Scale factor that RoI will be multiplied by. 63 | 64 | Returns: 65 | torch.Tensor: Scaled RoI. 66 | """ 67 | 68 | cx = (rois[:, 1] + rois[:, 3]) * 0.5 69 | cy = (rois[:, 2] + rois[:, 4]) * 0.5 70 | w = rois[:, 3] - rois[:, 1] 71 | h = rois[:, 4] - rois[:, 2] 72 | new_w = w * scale_factor 73 | new_h = h * scale_factor 74 | x1 = cx - new_w * 0.5 75 | x2 = cx + new_w * 0.5 76 | y1 = cy - new_h * 0.5 77 | y2 = cy + new_h * 0.5 78 | new_rois = torch.stack((rois[:, 0], x1, y1, x2, y2), dim=-1) 79 | return new_rois 80 | 81 | @abstractmethod 82 | def forward(self, feats, rois, roi_scale_factor=None): 83 | pass 84 | -------------------------------------------------------------------------------- /object_detection/mmdet/models/roi_heads/roi_extractors/generic_roi_extractor.py: -------------------------------------------------------------------------------- 1 | from mmcv.cnn.bricks import build_plugin_layer 2 | from mmcv.runner import force_fp32 3 | 4 | from mmdet.models.builder import ROI_EXTRACTORS 5 | from .base_roi_extractor import BaseRoIExtractor 6 | 7 | 8 | @ROI_EXTRACTORS.register_module() 9 | class GenericRoIExtractor(BaseRoIExtractor): 10 | """Extract RoI features from all level feature maps levels. 11 | 12 | This is the implementation of `A novel Region of Interest Extraction Layer 13 | for Instance Segmentation `_. 14 | 15 | Args: 16 | aggregation (str): The method to aggregate multiple feature maps. 17 | Options are 'sum', 'concat'. Default: 'sum'. 18 | pre_cfg (dict | None): Specify pre-processing modules. Default: None. 19 | post_cfg (dict | None): Specify post-processing modules. Default: None. 20 | kwargs (keyword arguments): Arguments that are the same 21 | as :class:`BaseRoIExtractor`. 22 | """ 23 | 24 | def __init__(self, 25 | aggregation='sum', 26 | pre_cfg=None, 27 | post_cfg=None, 28 | **kwargs): 29 | super(GenericRoIExtractor, self).__init__(**kwargs) 30 | 31 | assert aggregation in ['sum', 'concat'] 32 | 33 | self.aggregation = aggregation 34 | self.with_post = post_cfg is not None 35 | self.with_pre = pre_cfg is not None 36 | # build pre/post processing modules 37 | if self.with_post: 38 | self.post_module = build_plugin_layer(post_cfg, '_post_module')[1] 39 | if self.with_pre: 40 | self.pre_module = build_plugin_layer(pre_cfg, '_pre_module')[1] 41 | 42 | @force_fp32(apply_to=('feats', ), out_fp16=True) 43 | def forward(self, feats, rois, roi_scale_factor=None): 44 | """Forward function.""" 45 | if len(feats) == 1: 46 | return self.roi_layers[0](feats[0], rois) 47 | 48 | out_size = self.roi_layers[0].output_size 49 | num_levels = len(feats) 50 | roi_feats = feats[0].new_zeros( 51 | rois.size(0), self.out_channels, *out_size) 52 | 53 | # some times rois is an empty tensor 54 | if roi_feats.shape[0] == 0: 55 | return roi_feats 56 | 57 | if roi_scale_factor is not None: 58 | rois = self.roi_rescale(rois, roi_scale_factor) 59 | 60 | # mark the starting channels for concat mode 61 | start_channels = 0 62 | for i in range(num_levels): 63 | roi_feats_t = self.roi_layers[i](feats[i], rois) 64 | end_channels = start_channels + roi_feats_t.size(1) 65 | if self.with_pre: 66 | # apply pre-processing to a RoI extracted from each layer 67 | roi_feats_t = self.pre_module(roi_feats_t) 68 | if self.aggregation == 'sum': 69 | # and sum them all 70 | roi_feats += roi_feats_t 71 | else: 72 | # and concat them along channel dimension 73 | roi_feats[:, start_channels:end_channels] = roi_feats_t 74 | # update channels starting position 75 | start_channels = end_channels 76 | # check if concat channels match at the end 77 | if self.aggregation == 'concat': 78 | assert start_channels == self.out_channels 79 | 80 | if self.with_post: 81 | # apply post-processing before return the result 82 | roi_feats = self.post_module(roi_feats) 83 | return roi_feats 84 | -------------------------------------------------------------------------------- /object_detection/mmdet/models/roi_heads/shared_heads/__init__.py: -------------------------------------------------------------------------------- 1 | from .res_layer import ResLayer 2 | 3 | __all__ = ['ResLayer'] 4 | -------------------------------------------------------------------------------- /object_detection/mmdet/models/roi_heads/shared_heads/res_layer.py: -------------------------------------------------------------------------------- 1 | import torch.nn as nn 2 | from mmcv.cnn import constant_init, kaiming_init 3 | from mmcv.runner import auto_fp16, load_checkpoint 4 | 5 | from mmdet.models.backbones import ResNet 6 | from mmdet.models.builder import SHARED_HEADS 7 | from mmdet.models.utils import ResLayer as _ResLayer 8 | from mmdet.utils import get_root_logger 9 | 10 | 11 | @SHARED_HEADS.register_module() 12 | class ResLayer(nn.Module): 13 | 14 | def __init__(self, 15 | depth, 16 | stage=3, 17 | stride=2, 18 | dilation=1, 19 | style='pytorch', 20 | norm_cfg=dict(type='BN', requires_grad=True), 21 | norm_eval=True, 22 | with_cp=False, 23 | dcn=None): 24 | super(ResLayer, self).__init__() 25 | self.norm_eval = norm_eval 26 | self.norm_cfg = norm_cfg 27 | self.stage = stage 28 | self.fp16_enabled = False 29 | block, stage_blocks = ResNet.arch_settings[depth] 30 | stage_block = stage_blocks[stage] 31 | planes = 64 * 2**stage 32 | inplanes = 64 * 2**(stage - 1) * block.expansion 33 | 34 | res_layer = _ResLayer( 35 | block, 36 | inplanes, 37 | planes, 38 | stage_block, 39 | stride=stride, 40 | dilation=dilation, 41 | style=style, 42 | with_cp=with_cp, 43 | norm_cfg=self.norm_cfg, 44 | dcn=dcn) 45 | self.add_module(f'layer{stage + 1}', res_layer) 46 | 47 | def init_weights(self, pretrained=None): 48 | """Initialize the weights in the module. 49 | 50 | Args: 51 | pretrained (str, optional): Path to pre-trained weights. 52 | Defaults to None. 53 | """ 54 | if isinstance(pretrained, str): 55 | logger = get_root_logger() 56 | load_checkpoint(self, pretrained, strict=False, logger=logger) 57 | elif pretrained is None: 58 | for m in self.modules(): 59 | if isinstance(m, nn.Conv2d): 60 | kaiming_init(m) 61 | elif isinstance(m, nn.BatchNorm2d): 62 | constant_init(m, 1) 63 | else: 64 | raise TypeError('pretrained must be a str or None') 65 | 66 | @auto_fp16() 67 | def forward(self, x): 68 | res_layer = getattr(self, f'layer{self.stage + 1}') 69 | out = res_layer(x) 70 | return out 71 | 72 | def train(self, mode=True): 73 | super(ResLayer, self).train(mode) 74 | if self.norm_eval: 75 | for m in self.modules(): 76 | if isinstance(m, nn.BatchNorm2d): 77 | m.eval() 78 | -------------------------------------------------------------------------------- /object_detection/mmdet/models/utils/__init__.py: -------------------------------------------------------------------------------- 1 | from .builder import build_positional_encoding, build_transformer 2 | from .gaussian_target import gaussian_radius, gen_gaussian_target 3 | from .positional_encoding import (LearnedPositionalEncoding, 4 | SinePositionalEncoding) 5 | from .res_layer import ResLayer, SimplifiedBasicBlock 6 | from .transformer import (FFN, DynamicConv, MultiheadAttention, Transformer, 7 | TransformerDecoder, TransformerDecoderLayer, 8 | TransformerEncoder, TransformerEncoderLayer) 9 | 10 | __all__ = [ 11 | 'ResLayer', 'gaussian_radius', 'gen_gaussian_target', 'MultiheadAttention', 12 | 'FFN', 'TransformerEncoderLayer', 'TransformerEncoder', 13 | 'TransformerDecoderLayer', 'TransformerDecoder', 'Transformer', 14 | 'build_transformer', 'build_positional_encoding', 'SinePositionalEncoding', 15 | 'LearnedPositionalEncoding', 'DynamicConv', 'SimplifiedBasicBlock' 16 | ] 17 | -------------------------------------------------------------------------------- /object_detection/mmdet/models/utils/builder.py: -------------------------------------------------------------------------------- 1 | from mmcv.utils import Registry, build_from_cfg 2 | 3 | TRANSFORMER = Registry('Transformer') 4 | POSITIONAL_ENCODING = Registry('Position encoding') 5 | 6 | 7 | def build_transformer(cfg, default_args=None): 8 | """Builder for Transformer.""" 9 | return build_from_cfg(cfg, TRANSFORMER, default_args) 10 | 11 | 12 | def build_positional_encoding(cfg, default_args=None): 13 | """Builder for Position Encoding.""" 14 | return build_from_cfg(cfg, POSITIONAL_ENCODING, default_args) 15 | -------------------------------------------------------------------------------- /object_detection/mmdet/utils/__init__.py: -------------------------------------------------------------------------------- 1 | from .collect_env import collect_env 2 | from .logger import get_root_logger 3 | from .optimizer import DistOptimizerHook 4 | 5 | __all__ = ['get_root_logger', 'collect_env', 'DistOptimizerHook'] 6 | -------------------------------------------------------------------------------- /object_detection/mmdet/utils/collect_env.py: -------------------------------------------------------------------------------- 1 | from mmcv.utils import collect_env as collect_base_env 2 | from mmcv.utils import get_git_hash 3 | 4 | import mmdet 5 | 6 | 7 | def collect_env(): 8 | """Collect the information of the running environments.""" 9 | env_info = collect_base_env() 10 | env_info['MMDetection'] = mmdet.__version__ + '+' + get_git_hash()[:7] 11 | return env_info 12 | 13 | 14 | if __name__ == '__main__': 15 | for name, val in collect_env().items(): 16 | print(f'{name}: {val}') 17 | -------------------------------------------------------------------------------- /object_detection/mmdet/utils/logger.py: -------------------------------------------------------------------------------- 1 | import logging 2 | 3 | from mmcv.utils import get_logger 4 | 5 | 6 | def get_root_logger(log_file=None, log_level=logging.INFO): 7 | """Get root logger. 8 | 9 | Args: 10 | log_file (str, optional): File path of log. Defaults to None. 11 | log_level (int, optional): The level of logger. 12 | Defaults to logging.INFO. 13 | 14 | Returns: 15 | :obj:`logging.Logger`: The obtained logger 16 | """ 17 | logger = get_logger(name='mmdet', log_file=log_file, log_level=log_level) 18 | 19 | return logger 20 | -------------------------------------------------------------------------------- /object_detection/mmdet/utils/optimizer.py: -------------------------------------------------------------------------------- 1 | from mmcv.runner import OptimizerHook, HOOKS 2 | try: 3 | import apex 4 | except: 5 | print('apex is not installed') 6 | 7 | 8 | @HOOKS.register_module() 9 | class DistOptimizerHook(OptimizerHook): 10 | """Optimizer hook for distributed training.""" 11 | 12 | def __init__(self, update_interval=1, grad_clip=None, coalesce=True, bucket_size_mb=-1, use_fp16=False): 13 | self.grad_clip = grad_clip 14 | self.coalesce = coalesce 15 | self.bucket_size_mb = bucket_size_mb 16 | self.update_interval = update_interval 17 | self.use_fp16 = use_fp16 18 | 19 | def before_run(self, runner): 20 | runner.optimizer.zero_grad() 21 | 22 | def after_train_iter(self, runner): 23 | runner.outputs['loss'] /= self.update_interval 24 | if self.use_fp16: 25 | with apex.amp.scale_loss(runner.outputs['loss'], runner.optimizer) as scaled_loss: 26 | scaled_loss.backward() 27 | else: 28 | runner.outputs['loss'].backward() 29 | if self.every_n_iters(runner, self.update_interval): 30 | if self.grad_clip is not None: 31 | self.clip_grads(runner.model.parameters()) 32 | runner.optimizer.step() 33 | runner.optimizer.zero_grad() 34 | -------------------------------------------------------------------------------- /object_detection/mmdet/utils/profiling.py: -------------------------------------------------------------------------------- 1 | import contextlib 2 | import sys 3 | import time 4 | 5 | import torch 6 | 7 | if sys.version_info >= (3, 7): 8 | 9 | @contextlib.contextmanager 10 | def profile_time(trace_name, 11 | name, 12 | enabled=True, 13 | stream=None, 14 | end_stream=None): 15 | """Print time spent by CPU and GPU. 16 | 17 | Useful as a temporary context manager to find sweet spots of code 18 | suitable for async implementation. 19 | """ 20 | if (not enabled) or not torch.cuda.is_available(): 21 | yield 22 | return 23 | stream = stream if stream else torch.cuda.current_stream() 24 | end_stream = end_stream if end_stream else stream 25 | start = torch.cuda.Event(enable_timing=True) 26 | end = torch.cuda.Event(enable_timing=True) 27 | stream.record_event(start) 28 | try: 29 | cpu_start = time.monotonic() 30 | yield 31 | finally: 32 | cpu_end = time.monotonic() 33 | end_stream.record_event(end) 34 | end.synchronize() 35 | cpu_time = (cpu_end - cpu_start) * 1000 36 | gpu_time = start.elapsed_time(end) 37 | msg = f'{trace_name} {name} cpu_time {cpu_time:.2f} ms ' 38 | msg += f'gpu_time {gpu_time:.2f} ms stream {stream}' 39 | print(msg, end_stream) 40 | -------------------------------------------------------------------------------- /object_detection/mmdet/utils/util_mixins.py: -------------------------------------------------------------------------------- 1 | """This module defines the :class:`NiceRepr` mixin class, which defines a 2 | ``__repr__`` and ``__str__`` method that only depend on a custom ``__nice__`` 3 | method, which you must define. This means you only have to overload one 4 | function instead of two. Furthermore, if the object defines a ``__len__`` 5 | method, then the ``__nice__`` method defaults to something sensible, otherwise 6 | it is treated as abstract and raises ``NotImplementedError``. 7 | 8 | To use simply have your object inherit from :class:`NiceRepr` 9 | (multi-inheritance should be ok). 10 | 11 | This code was copied from the ubelt library: https://github.com/Erotemic/ubelt 12 | 13 | Example: 14 | >>> # Objects that define __nice__ have a default __str__ and __repr__ 15 | >>> class Student(NiceRepr): 16 | ... def __init__(self, name): 17 | ... self.name = name 18 | ... def __nice__(self): 19 | ... return self.name 20 | >>> s1 = Student('Alice') 21 | >>> s2 = Student('Bob') 22 | >>> print(f's1 = {s1}') 23 | >>> print(f's2 = {s2}') 24 | s1 = 25 | s2 = 26 | 27 | Example: 28 | >>> # Objects that define __len__ have a default __nice__ 29 | >>> class Group(NiceRepr): 30 | ... def __init__(self, data): 31 | ... self.data = data 32 | ... def __len__(self): 33 | ... return len(self.data) 34 | >>> g = Group([1, 2, 3]) 35 | >>> print(f'g = {g}') 36 | g = 37 | """ 38 | import warnings 39 | 40 | 41 | class NiceRepr(object): 42 | """Inherit from this class and define ``__nice__`` to "nicely" print your 43 | objects. 44 | 45 | Defines ``__str__`` and ``__repr__`` in terms of ``__nice__`` function 46 | Classes that inherit from :class:`NiceRepr` should redefine ``__nice__``. 47 | If the inheriting class has a ``__len__``, method then the default 48 | ``__nice__`` method will return its length. 49 | 50 | Example: 51 | >>> class Foo(NiceRepr): 52 | ... def __nice__(self): 53 | ... return 'info' 54 | >>> foo = Foo() 55 | >>> assert str(foo) == '' 56 | >>> assert repr(foo).startswith('>> class Bar(NiceRepr): 60 | ... pass 61 | >>> bar = Bar() 62 | >>> import pytest 63 | >>> with pytest.warns(None) as record: 64 | >>> assert 'object at' in str(bar) 65 | >>> assert 'object at' in repr(bar) 66 | 67 | Example: 68 | >>> class Baz(NiceRepr): 69 | ... def __len__(self): 70 | ... return 5 71 | >>> baz = Baz() 72 | >>> assert str(baz) == '' 73 | """ 74 | 75 | def __nice__(self): 76 | """str: a "nice" summary string describing this module""" 77 | if hasattr(self, '__len__'): 78 | # It is a common pattern for objects to use __len__ in __nice__ 79 | # As a convenience we define a default __nice__ for these objects 80 | return str(len(self)) 81 | else: 82 | # In all other cases force the subclass to overload __nice__ 83 | raise NotImplementedError( 84 | f'Define the __nice__ method for {self.__class__!r}') 85 | 86 | def __repr__(self): 87 | """str: the string of the module""" 88 | try: 89 | nice = self.__nice__() 90 | classname = self.__class__.__name__ 91 | return f'<{classname}({nice}) at {hex(id(self))}>' 92 | except NotImplementedError as ex: 93 | warnings.warn(str(ex), category=RuntimeWarning) 94 | return object.__repr__(self) 95 | 96 | def __str__(self): 97 | """str: the string of the module""" 98 | try: 99 | classname = self.__class__.__name__ 100 | nice = self.__nice__() 101 | return f'<{classname}({nice})>' 102 | except NotImplementedError as ex: 103 | warnings.warn(str(ex), category=RuntimeWarning) 104 | return object.__repr__(self) 105 | -------------------------------------------------------------------------------- /object_detection/mmdet/utils/util_random.py: -------------------------------------------------------------------------------- 1 | """Helpers for random number generators.""" 2 | import numpy as np 3 | 4 | 5 | def ensure_rng(rng=None): 6 | """Coerces input into a random number generator. 7 | 8 | If the input is None, then a global random state is returned. 9 | 10 | If the input is a numeric value, then that is used as a seed to construct a 11 | random state. Otherwise the input is returned as-is. 12 | 13 | Adapted from [1]_. 14 | 15 | Args: 16 | rng (int | numpy.random.RandomState | None): 17 | if None, then defaults to the global rng. Otherwise this can be an 18 | integer or a RandomState class 19 | Returns: 20 | (numpy.random.RandomState) : rng - 21 | a numpy random number generator 22 | 23 | References: 24 | .. [1] https://gitlab.kitware.com/computer-vision/kwarray/blob/master/kwarray/util_random.py#L270 # noqa: E501 25 | """ 26 | 27 | if rng is None: 28 | rng = np.random.mtrand._rand 29 | elif isinstance(rng, int): 30 | rng = np.random.RandomState(rng) 31 | else: 32 | rng = rng 33 | return rng 34 | -------------------------------------------------------------------------------- /object_detection/mmdet/version.py: -------------------------------------------------------------------------------- 1 | # Copyright (c) Open-MMLab. All rights reserved. 2 | 3 | __version__ = '2.11.0' 4 | short_version = __version__ 5 | 6 | 7 | def parse_version_info(version_str): 8 | version_info = [] 9 | for x in version_str.split('.'): 10 | if x.isdigit(): 11 | version_info.append(int(x)) 12 | elif x.find('rc') != -1: 13 | patch_version = x.split('rc') 14 | version_info.append(int(patch_version[0])) 15 | version_info.append(f'rc{patch_version[1]}') 16 | return tuple(version_info) 17 | 18 | 19 | version_info = parse_version_info(__version__) 20 | -------------------------------------------------------------------------------- /object_detection/scripts_det/fcaformer: -------------------------------------------------------------------------------- 1 | ## training *********************************************** 2 | # mask rcnn 3 | bash tools/dist_train.sh configs/fcaformer/mask_rcnn_fcaformer_l2_set1_480-800_adamw_3x_coco_in1k.py 8 --work-dir /home/disk/result/fcaformer/coco_det/mask_rcnn_fcaformer_l2_set1 --cfg-options model.pretrained=/home/disk/result/fcaformer/imgnet1k_cls/fcaformer_l2/checkpoint-best.pth 4 | 5 | # cascade mask rcnn 6 | bash tools/dist_train.sh configs/fcaformer/cascade_mask_rcnn_fcaformer_l2_set1_480-800_adamw_3x_coco_in1k.py 8 --work-dir /home/disk/result/fcaformer/coco_det/cascade_mask_rcnn_fcaformer_l2_set1 --cfg-options model.pretrained=/home/disk/result/fcaformer/imgnet1k_cls/fcaformer_l2/checkpoint-best.pth 7 | 8 | 9 | ## test ***************************************************** 10 | 11 | # mask rcnn 12 | bash tools/dist_test.sh configs/fcaformer/mask_rcnn_fcaformer_l2_set1_480-800_adamw_3x_coco_in1k.py /home/disk/result/fcaformer/coco_det/mask_rcnn_fcaformer_l2_set1/latest.pth 8 --eval bbox segm 13 | 14 | # cascade mask rcnn 15 | bash tools/dist_test.sh configs/fcaformer/cascade_mask_rcnn_fcaformer_l2_set1_480-800_adamw_3x_coco_in1k.py /home/disk/result/fcaformer/coco_det/cascade_mask_rcnn_fcaformer_l2_set1/latest.pth 8 --eval bbox segm 16 | 17 | -------------------------------------------------------------------------------- /object_detection/tools/dist_test.sh: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env bash 2 | 3 | CONFIG=$1 4 | CHECKPOINT=$2 5 | GPUS=$3 6 | PORT=${PORT:-29500} 7 | 8 | PYTHONPATH="$(dirname $0)/..":$PYTHONPATH \ 9 | python -m torch.distributed.launch --nproc_per_node=$GPUS --master_port=$PORT \ 10 | $(dirname "$0")/test.py $CONFIG $CHECKPOINT --launcher pytorch ${@:4} 11 | -------------------------------------------------------------------------------- /object_detection/tools/dist_train.sh: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env bash 2 | 3 | CONFIG=$1 4 | GPUS=$2 5 | PORT=${PORT:-29500} 6 | 7 | PYTHONPATH="$(dirname $0)/..":$PYTHONPATH \ 8 | python -m torch.distributed.launch --nproc_per_node=$GPUS --master_port=$PORT \ 9 | $(dirname "$0")/train.py $CONFIG --launcher pytorch ${@:3} 10 | -------------------------------------------------------------------------------- /object_detection/tools/get_flops.py: -------------------------------------------------------------------------------- 1 | import sys 2 | sys.path.insert(0, '/home/disk/code/FcaFormer/object_detection') 3 | from mmdet.models.backbones import FcaFormer_SH_512 4 | 5 | import argparse 6 | 7 | import torch 8 | from mmcv import Config, DictAction 9 | 10 | from mmdet.models import build_detector 11 | 12 | try: 13 | from mmcv.cnn import get_model_complexity_info 14 | except ImportError: 15 | raise ImportError('Please upgrade mmcv to >0.6.2') 16 | 17 | 18 | def parse_args(): 19 | parser = argparse.ArgumentParser(description='Train a detector') 20 | parser.add_argument('config', help='train config file path') 21 | parser.add_argument( 22 | '--shape', 23 | type=int, 24 | nargs='+', 25 | default=[1280, 800], 26 | help='input image size') 27 | parser.add_argument( 28 | '--cfg-options', 29 | nargs='+', 30 | action=DictAction, 31 | help='override some settings in the used config, the key-value pair ' 32 | 'in xxx=yyy format will be merged into config file. If the value to ' 33 | 'be overwritten is a list, it should be like key="[a,b]" or key=a,b ' 34 | 'It also allows nested list/tuple values, e.g. key="[(a,b),(c,d)]" ' 35 | 'Note that the quotation marks are necessary and that no white space ' 36 | 'is allowed.') 37 | args = parser.parse_args() 38 | return args 39 | 40 | 41 | def main(): 42 | 43 | args = parse_args() 44 | 45 | if len(args.shape) == 1: 46 | input_shape = (3, args.shape[0], args.shape[0]) 47 | elif len(args.shape) == 2: 48 | input_shape = (3, ) + tuple(args.shape) 49 | else: 50 | raise ValueError('invalid input shape') 51 | 52 | cfg = Config.fromfile(args.config) 53 | if args.cfg_options is not None: 54 | cfg.merge_from_dict(args.cfg_options) 55 | # import modules from string list. 56 | if cfg.get('custom_imports', None): 57 | from mmcv.utils import import_modules_from_strings 58 | import_modules_from_strings(**cfg['custom_imports']) 59 | 60 | model = build_detector( 61 | cfg.model, 62 | train_cfg=cfg.get('train_cfg'), 63 | test_cfg=cfg.get('test_cfg')) 64 | if torch.cuda.is_available(): 65 | model.cuda() 66 | model.eval() 67 | 68 | if hasattr(model, 'forward_dummy'): 69 | model.forward = model.forward_dummy 70 | else: 71 | raise NotImplementedError( 72 | 'FLOPs counter is currently not currently supported with {}'. 73 | format(model.__class__.__name__)) 74 | 75 | flops, params = get_model_complexity_info(model, input_shape) 76 | split_line = '=' * 30 77 | print(f'{split_line}\nInput shape: {input_shape}\n' 78 | f'Flops: {flops}\nParams: {params}\n{split_line}') 79 | print('!!!Please be cautious if you use the results in papers. ' 80 | 'You may need to check if all ops are supported and verify that the ' 81 | 'flops computation is correct.') 82 | 83 | 84 | if __name__ == '__main__': 85 | main() 86 | -------------------------------------------------------------------------------- /object_detection/tools/slurm_test.sh: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env bash 2 | 3 | set -x 4 | 5 | PARTITION=$1 6 | JOB_NAME=$2 7 | CONFIG=$3 8 | CHECKPOINT=$4 9 | GPUS=${GPUS:-8} 10 | GPUS_PER_NODE=${GPUS_PER_NODE:-8} 11 | CPUS_PER_TASK=${CPUS_PER_TASK:-5} 12 | PY_ARGS=${@:5} 13 | SRUN_ARGS=${SRUN_ARGS:-""} 14 | 15 | PYTHONPATH="$(dirname $0)/..":$PYTHONPATH \ 16 | srun -p ${PARTITION} \ 17 | --job-name=${JOB_NAME} \ 18 | --gres=gpu:${GPUS_PER_NODE} \ 19 | --ntasks=${GPUS} \ 20 | --ntasks-per-node=${GPUS_PER_NODE} \ 21 | --cpus-per-task=${CPUS_PER_TASK} \ 22 | --kill-on-bad-exit=1 \ 23 | ${SRUN_ARGS} \ 24 | python -u tools/test.py ${CONFIG} ${CHECKPOINT} --launcher="slurm" ${PY_ARGS} 25 | -------------------------------------------------------------------------------- /object_detection/tools/slurm_train.sh: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env bash 2 | 3 | set -x 4 | 5 | PARTITION=$1 6 | JOB_NAME=$2 7 | CONFIG=$3 8 | WORK_DIR=$4 9 | GPUS=${GPUS:-8} 10 | GPUS_PER_NODE=${GPUS_PER_NODE:-8} 11 | CPUS_PER_TASK=${CPUS_PER_TASK:-5} 12 | SRUN_ARGS=${SRUN_ARGS:-""} 13 | PY_ARGS=${@:5} 14 | 15 | PYTHONPATH="$(dirname $0)/..":$PYTHONPATH \ 16 | srun -p ${PARTITION} \ 17 | --job-name=${JOB_NAME} \ 18 | --gres=gpu:${GPUS_PER_NODE} \ 19 | --ntasks=${GPUS} \ 20 | --ntasks-per-node=${GPUS_PER_NODE} \ 21 | --cpus-per-task=${CPUS_PER_TASK} \ 22 | --kill-on-bad-exit=1 \ 23 | ${SRUN_ARGS} \ 24 | python -u tools/train.py ${CONFIG} --work-dir=${WORK_DIR} --launcher="slurm" ${PY_ARGS} 25 | -------------------------------------------------------------------------------- /semantic-segmentation/backbone/__init__.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/hkzhang-git/FcaFormer/7dcd8e0ed207a6c74708ab10553dcd6a6d4ea2bd/semantic-segmentation/backbone/__init__.py -------------------------------------------------------------------------------- /semantic-segmentation/backbone/model_test.py: -------------------------------------------------------------------------------- 1 | import torch 2 | 3 | from semantic_segmentation.backbone.cabvit_512 import CabViT_SH_512 4 | # from semantic_segmentation.backbone.cabvit_224 import CabViT_SH_224 5 | 6 | input=torch.randn(3, 3, 512, 512) 7 | model=CabViT_SH_512() 8 | output = model(input) 9 | print('done') 10 | -------------------------------------------------------------------------------- /semantic-segmentation/configs/_base_/datasets/ade20k.py: -------------------------------------------------------------------------------- 1 | # dataset settings 2 | dataset_type = 'ADE20KDataset' 3 | data_root = 'data/ade/ADEChallengeData2016' 4 | img_norm_cfg = dict( 5 | mean=[123.675, 116.28, 103.53], std=[58.395, 57.12, 57.375], to_rgb=True) 6 | crop_size = (512, 512) 7 | train_pipeline = [ 8 | dict(type='LoadImageFromFile'), 9 | dict(type='LoadAnnotations', reduce_zero_label=True), 10 | dict(type='Resize', img_scale=(2048, 512), ratio_range=(0.5, 2.0)), 11 | dict(type='RandomCrop', crop_size=crop_size, cat_max_ratio=0.75), 12 | dict(type='RandomFlip', prob=0.5), 13 | dict(type='PhotoMetricDistortion'), 14 | dict(type='Normalize', **img_norm_cfg), 15 | dict(type='Pad', size=crop_size, pad_val=0, seg_pad_val=255), 16 | dict(type='DefaultFormatBundle'), 17 | dict(type='Collect', keys=['img', 'gt_semantic_seg']), 18 | ] 19 | test_pipeline = [ 20 | dict(type='LoadImageFromFile'), 21 | dict( 22 | type='MultiScaleFlipAug', 23 | img_scale=(2048, 512), 24 | # img_ratios=[0.5, 0.75, 1.0, 1.25, 1.5, 1.75], 25 | flip=False, 26 | transforms=[ 27 | dict(type='Resize', keep_ratio=True), 28 | dict(type='RandomFlip'), 29 | dict(type='Normalize', **img_norm_cfg), 30 | dict(type='ImageToTensor', keys=['img']), 31 | dict(type='Collect', keys=['img']), 32 | ]) 33 | ] 34 | data = dict( 35 | samples_per_gpu=4, 36 | workers_per_gpu=4, 37 | train=dict( 38 | type=dataset_type, 39 | data_root=data_root, 40 | img_dir='images/training', 41 | ann_dir='annotations/training', 42 | pipeline=train_pipeline), 43 | val=dict( 44 | type=dataset_type, 45 | data_root=data_root, 46 | img_dir='images/validation', 47 | ann_dir='annotations/validation', 48 | pipeline=test_pipeline), 49 | test=dict( 50 | type=dataset_type, 51 | data_root=data_root, 52 | img_dir='images/validation', 53 | ann_dir='annotations/validation', 54 | pipeline=test_pipeline)) 55 | -------------------------------------------------------------------------------- /semantic-segmentation/configs/_base_/datasets/ade20k_640x640.py: -------------------------------------------------------------------------------- 1 | # dataset settings 2 | dataset_type = 'ADE20KDataset' 3 | data_root = 'data/ade/ADEChallengeData2016' 4 | img_norm_cfg = dict( 5 | mean=[123.675, 116.28, 103.53], std=[58.395, 57.12, 57.375], to_rgb=True) 6 | crop_size = (640, 640) 7 | train_pipeline = [ 8 | dict(type='LoadImageFromFile'), 9 | dict(type='LoadAnnotations', reduce_zero_label=True), 10 | dict(type='Resize', img_scale=(2560, 640), ratio_range=(0.5, 2.0)), 11 | dict(type='RandomCrop', crop_size=crop_size, cat_max_ratio=0.75), 12 | dict(type='RandomFlip', prob=0.5), 13 | dict(type='PhotoMetricDistortion'), 14 | dict(type='Normalize', **img_norm_cfg), 15 | dict(type='Pad', size=crop_size, pad_val=0, seg_pad_val=255), 16 | dict(type='DefaultFormatBundle'), 17 | dict(type='Collect', keys=['img', 'gt_semantic_seg']), 18 | ] 19 | test_pipeline = [ 20 | dict(type='LoadImageFromFile'), 21 | dict( 22 | type='MultiScaleFlipAug', 23 | img_scale=(2560, 640), 24 | # img_ratios=[0.5, 0.75, 1.0, 1.25, 1.5, 1.75], 25 | flip=False, 26 | transforms=[ 27 | dict(type='Resize', keep_ratio=True), 28 | dict(type='RandomFlip'), 29 | dict(type='Normalize', **img_norm_cfg), 30 | dict(type='ImageToTensor', keys=['img']), 31 | dict(type='Collect', keys=['img']), 32 | ]) 33 | ] 34 | data = dict( 35 | samples_per_gpu=4, 36 | workers_per_gpu=4, 37 | train=dict( 38 | type=dataset_type, 39 | data_root=data_root, 40 | img_dir='images/training', 41 | ann_dir='annotations/training', 42 | pipeline=train_pipeline), 43 | val=dict( 44 | type=dataset_type, 45 | data_root=data_root, 46 | img_dir='images/validation', 47 | ann_dir='annotations/validation', 48 | pipeline=test_pipeline), 49 | test=dict( 50 | type=dataset_type, 51 | data_root=data_root, 52 | img_dir='images/validation', 53 | ann_dir='annotations/validation', 54 | pipeline=test_pipeline)) 55 | -------------------------------------------------------------------------------- /semantic-segmentation/configs/_base_/datasets/ade20k_local.py: -------------------------------------------------------------------------------- 1 | # dataset settings 2 | dataset_type = 'ADE20KDataset' 3 | data_root = 'data/ade/ADEChallengeData2016_local' 4 | img_norm_cfg = dict( 5 | mean=[123.675, 116.28, 103.53], std=[58.395, 57.12, 57.375], to_rgb=True) 6 | crop_size = (512, 512) 7 | train_pipeline = [ 8 | dict(type='LoadImageFromFile'), 9 | dict(type='LoadAnnotations', reduce_zero_label=True), 10 | dict(type='Resize', img_scale=(2048, 512), ratio_range=(0.5, 2.0)), 11 | dict(type='RandomCrop', crop_size=crop_size, cat_max_ratio=0.75), 12 | dict(type='RandomFlip', prob=0.5), 13 | dict(type='PhotoMetricDistortion'), 14 | dict(type='Normalize', **img_norm_cfg), 15 | dict(type='Pad', size=crop_size, pad_val=0, seg_pad_val=255), 16 | dict(type='DefaultFormatBundle'), 17 | dict(type='Collect', keys=['img', 'gt_semantic_seg']), 18 | ] 19 | test_pipeline = [ 20 | dict(type='LoadImageFromFile'), 21 | dict( 22 | type='MultiScaleFlipAug', 23 | img_scale=(2048, 512), 24 | # img_ratios=[0.5, 0.75, 1.0, 1.25, 1.5, 1.75], 25 | flip=False, 26 | transforms=[ 27 | dict(type='Resize', keep_ratio=True), 28 | dict(type='RandomFlip'), 29 | dict(type='Normalize', **img_norm_cfg), 30 | dict(type='ImageToTensor', keys=['img']), 31 | dict(type='Collect', keys=['img']), 32 | ]) 33 | ] 34 | data = dict( 35 | samples_per_gpu=4, 36 | workers_per_gpu=4, 37 | train=dict( 38 | type=dataset_type, 39 | data_root=data_root, 40 | img_dir='images/training', 41 | ann_dir='annotations/training', 42 | pipeline=train_pipeline), 43 | val=dict( 44 | type=dataset_type, 45 | data_root=data_root, 46 | img_dir='images/validation', 47 | ann_dir='annotations/validation', 48 | pipeline=test_pipeline), 49 | test=dict( 50 | type=dataset_type, 51 | data_root=data_root, 52 | img_dir='images/validation', 53 | ann_dir='annotations/validation', 54 | pipeline=test_pipeline)) 55 | -------------------------------------------------------------------------------- /semantic-segmentation/configs/_base_/default_runtime.py: -------------------------------------------------------------------------------- 1 | # yapf:disable 2 | log_config = dict( 3 | interval=50, 4 | hooks=[ 5 | dict(type='CustomizedTextLoggerHook', by_epoch=False), 6 | # dict(type='TensorboardLoggerHook') 7 | ]) 8 | # yapf:enable 9 | dist_params = dict(backend='nccl') 10 | log_level = 'INFO' 11 | load_from = None 12 | resume_from = None 13 | workflow = [('train', 1)] 14 | cudnn_benchmark = True 15 | -------------------------------------------------------------------------------- /semantic-segmentation/configs/_base_/models/upernet_convnext.py: -------------------------------------------------------------------------------- 1 | # Copyright (c) Meta Platforms, Inc. and affiliates. 2 | 3 | # All rights reserved. 4 | 5 | # This source code is licensed under the license found in the 6 | # LICENSE file in the root directory of this source tree. 7 | 8 | 9 | norm_cfg = dict(type='SyncBN', requires_grad=True) 10 | model = dict( 11 | type='EncoderDecoder', 12 | pretrained=None, 13 | backbone=dict( 14 | type='ConvNeXt', 15 | in_chans=3, 16 | depths=[3, 3, 9, 3], 17 | dims=[96, 192, 384, 768], 18 | drop_path_rate=0.2, 19 | layer_scale_init_value=1.0, 20 | out_indices=[0, 1, 2, 3], 21 | ), 22 | decode_head=dict( 23 | type='UPerHead', 24 | in_channels=[128, 256, 512, 1024], 25 | in_index=[0, 1, 2, 3], 26 | pool_scales=(1, 2, 3, 6), 27 | channels=512, 28 | dropout_ratio=0.1, 29 | num_classes=19, 30 | norm_cfg=norm_cfg, 31 | align_corners=False, 32 | loss_decode=dict( 33 | type='CrossEntropyLoss', use_sigmoid=False, loss_weight=1.0)), 34 | auxiliary_head=dict( 35 | type='FCNHead', 36 | in_channels=384, 37 | in_index=2, 38 | channels=256, 39 | num_convs=1, 40 | concat_input=False, 41 | dropout_ratio=0.1, 42 | num_classes=19, 43 | norm_cfg=norm_cfg, 44 | align_corners=False, 45 | loss_decode=dict( 46 | type='CrossEntropyLoss', use_sigmoid=False, loss_weight=0.4)), 47 | # model training and testing settings 48 | train_cfg=dict(), 49 | test_cfg=dict(mode='whole')) 50 | -------------------------------------------------------------------------------- /semantic-segmentation/configs/_base_/schedules/schedule_160k.py: -------------------------------------------------------------------------------- 1 | # optimizer 2 | optimizer = dict(type='SGD', lr=0.01, momentum=0.9, weight_decay=0.0005) 3 | optimizer_config = dict() 4 | # learning policy 5 | lr_config = dict(policy='poly', power=0.9, min_lr=1e-4, by_epoch=False) 6 | # runtime settings 7 | runner = dict(type='IterBasedRunner', max_iters=160000) 8 | checkpoint_config = dict(by_epoch=False, interval=16000) 9 | evaluation = dict(interval=16000, metric='mIoU') 10 | -------------------------------------------------------------------------------- /semantic-segmentation/configs/_base_/schedules/schedule_320k.py: -------------------------------------------------------------------------------- 1 | # optimizer 2 | optimizer = dict(type='SGD', lr=0.01, momentum=0.9, weight_decay=0.0005) 3 | optimizer_config = dict() 4 | # learning policy 5 | lr_config = dict(policy='poly', power=0.9, min_lr=1e-4, by_epoch=False) 6 | # runtime settings 7 | runner = dict(type='IterBasedRunner', max_iters=320000) 8 | checkpoint_config = dict(by_epoch=False, interval=32000) 9 | evaluation = dict(interval=32000, metric='mIoU') 10 | -------------------------------------------------------------------------------- /semantic-segmentation/configs/fcaformer/upernet_fcaformer_l2_160k_ade20k_ms.py: -------------------------------------------------------------------------------- 1 | _base_ = [ 2 | '../_base_/models/upernet_convnext.py', '../_base_/datasets/ade20k_local.py', 3 | '../_base_/default_runtime.py', '../_base_/schedules/schedule_160k.py' 4 | ] 5 | crop_size = (512, 512) 6 | 7 | model = dict( 8 | backbone=dict( 9 | type='FcaFormer_SH_512', 10 | in_chans=3, 11 | depths=[2, 2, 7, 2], 12 | num_heads=[0, 0, 10, 15], 13 | dims=[96, 192, 320, 480], 14 | drop_path_rate=0.1, 15 | layer_scale_init_value=1.0, 16 | out_indices=[0, 1, 2, 3], 17 | seg_head_dims=[96, 192, 384, 768] 18 | ), 19 | decode_head=dict( 20 | in_channels=[96, 192, 384, 768], 21 | num_classes=150, 22 | ), 23 | auxiliary_head=dict( 24 | in_channels=384, 25 | num_classes=150 26 | ), 27 | test_cfg = dict(mode='slide', crop_size=crop_size, stride=(341, 341)), 28 | ) 29 | 30 | optimizer = dict(constructor='LearningRateDecayOptimizerConstructor', _delete_=True, type='AdamW', 31 | lr=0.0001, betas=(0.9, 0.999), weight_decay=0.01, 32 | paramwise_cfg={'decay_rate': 0.9, 33 | 'decay_type': 'stage_wise', 34 | 'num_layers': 6}) 35 | 36 | lr_config = dict(_delete_=True, policy='poly', 37 | warmup='linear', 38 | warmup_iters=1500, 39 | warmup_ratio=1e-6, 40 | power=1.0, min_lr=0.0, by_epoch=False) 41 | 42 | # By default, models are trained on 8 GPUs with 2 images per GPU 43 | data=dict(samples_per_gpu=2) 44 | 45 | runner = dict(type='IterBasedRunnerAmp') 46 | 47 | # do not use mmdet version fp16 48 | fp16 = None 49 | optimizer_config = dict( 50 | type="DistOptimizerHook", 51 | update_interval=1, 52 | grad_clip=None, 53 | coalesce=True, 54 | bucket_size_mb=-1, 55 | use_fp16=True, 56 | ) 57 | -------------------------------------------------------------------------------- /semantic-segmentation/mmcv_custom/__init__.py: -------------------------------------------------------------------------------- 1 | # Copyright (c) Meta Platforms, Inc. and affiliates. 2 | 3 | # All rights reserved. 4 | 5 | # This source code is licensed under the license found in the 6 | # LICENSE file in the root directory of this source tree. 7 | 8 | 9 | # -*- coding: utf-8 -*- 10 | 11 | from .checkpoint import load_checkpoint 12 | from .layer_decay_optimizer_constructor import LearningRateDecayOptimizerConstructor 13 | from .resize_transform import SETR_Resize 14 | from .apex_runner.optimizer import DistOptimizerHook 15 | from .train_api import train_segmentor 16 | from .customized_text import CustomizedTextLoggerHook 17 | 18 | __all__ = ['load_checkpoint', 'LearningRateDecayOptimizerConstructor', 'SETR_Resize', 'DistOptimizerHook', 'train_segmentor', 'CustomizedTextLoggerHook'] 19 | -------------------------------------------------------------------------------- /semantic-segmentation/mmcv_custom/apex_runner/__init__.py: -------------------------------------------------------------------------------- 1 | # Copyright (c) Open-MMLab. All rights reserved. 2 | from .checkpoint import save_checkpoint 3 | from .apex_iter_based_runner import IterBasedRunnerAmp 4 | 5 | 6 | __all__ = [ 7 | 'save_checkpoint', 'IterBasedRunnerAmp', 8 | ] 9 | -------------------------------------------------------------------------------- /semantic-segmentation/mmcv_custom/apex_runner/checkpoint.py: -------------------------------------------------------------------------------- 1 | # Copyright (c) Open-MMLab. All rights reserved. 2 | import os.path as osp 3 | import time 4 | from tempfile import TemporaryDirectory 5 | 6 | import torch 7 | from torch.optim import Optimizer 8 | 9 | import mmcv 10 | from mmcv.parallel import is_module_wrapper 11 | from mmcv.runner.checkpoint import weights_to_cpu, get_state_dict 12 | 13 | try: 14 | import apex 15 | except: 16 | print('apex is not installed') 17 | 18 | 19 | def save_checkpoint(model, filename, optimizer=None, meta=None): 20 | """Save checkpoint to file. 21 | 22 | The checkpoint will have 4 fields: ``meta``, ``state_dict`` and 23 | ``optimizer``, ``amp``. By default ``meta`` will contain version 24 | and time info. 25 | 26 | Args: 27 | model (Module): Module whose params are to be saved. 28 | filename (str): Checkpoint filename. 29 | optimizer (:obj:`Optimizer`, optional): Optimizer to be saved. 30 | meta (dict, optional): Metadata to be saved in checkpoint. 31 | """ 32 | if meta is None: 33 | meta = {} 34 | elif not isinstance(meta, dict): 35 | raise TypeError(f'meta must be a dict or None, but got {type(meta)}') 36 | meta.update(mmcv_version=mmcv.__version__, time=time.asctime()) 37 | 38 | if is_module_wrapper(model): 39 | model = model.module 40 | 41 | if hasattr(model, 'CLASSES') and model.CLASSES is not None: 42 | # save class name to the meta 43 | meta.update(CLASSES=model.CLASSES) 44 | 45 | checkpoint = { 46 | 'meta': meta, 47 | 'state_dict': weights_to_cpu(get_state_dict(model)) 48 | } 49 | # save optimizer state dict in the checkpoint 50 | if isinstance(optimizer, Optimizer): 51 | checkpoint['optimizer'] = optimizer.state_dict() 52 | elif isinstance(optimizer, dict): 53 | checkpoint['optimizer'] = {} 54 | for name, optim in optimizer.items(): 55 | checkpoint['optimizer'][name] = optim.state_dict() 56 | 57 | # save amp state dict in the checkpoint 58 | # checkpoint['amp'] = apex.amp.state_dict() 59 | 60 | if filename.startswith('pavi://'): 61 | try: 62 | from pavi import modelcloud 63 | from pavi.exception import NodeNotFoundError 64 | except ImportError: 65 | raise ImportError( 66 | 'Please install pavi to load checkpoint from modelcloud.') 67 | model_path = filename[7:] 68 | root = modelcloud.Folder() 69 | model_dir, model_name = osp.split(model_path) 70 | try: 71 | model = modelcloud.get(model_dir) 72 | except NodeNotFoundError: 73 | model = root.create_training_model(model_dir) 74 | with TemporaryDirectory() as tmp_dir: 75 | checkpoint_file = osp.join(tmp_dir, model_name) 76 | with open(checkpoint_file, 'wb') as f: 77 | torch.save(checkpoint, f) 78 | f.flush() 79 | model.create_file(checkpoint_file, name=model_name) 80 | else: 81 | mmcv.mkdir_or_exist(osp.dirname(filename)) 82 | # immediately flush buffer 83 | with open(filename, 'wb') as f: 84 | torch.save(checkpoint, f) 85 | f.flush() 86 | -------------------------------------------------------------------------------- /semantic-segmentation/mmcv_custom/apex_runner/optimizer.py: -------------------------------------------------------------------------------- 1 | from mmcv.runner import OptimizerHook, HOOKS 2 | try: 3 | import apex 4 | except: 5 | print('apex is not installed') 6 | 7 | 8 | @HOOKS.register_module() 9 | class DistOptimizerHook(OptimizerHook): 10 | """Optimizer hook for distributed training.""" 11 | 12 | def __init__(self, update_interval=1, grad_clip=None, coalesce=True, bucket_size_mb=-1, use_fp16=False): 13 | self.grad_clip = grad_clip 14 | self.coalesce = coalesce 15 | self.bucket_size_mb = bucket_size_mb 16 | self.update_interval = update_interval 17 | self.use_fp16 = use_fp16 18 | 19 | def before_run(self, runner): 20 | runner.optimizer.zero_grad() 21 | 22 | def after_train_iter(self, runner): 23 | runner.outputs['loss'] /= self.update_interval 24 | if self.use_fp16: 25 | with apex.amp.scale_loss(runner.outputs['loss'], runner.optimizer) as scaled_loss: 26 | scaled_loss.backward() 27 | else: 28 | runner.outputs['loss'].backward() 29 | if self.every_n_iters(runner, self.update_interval): 30 | if self.grad_clip is not None: 31 | self.clip_grads(runner.model.parameters()) 32 | runner.optimizer.step() 33 | runner.optimizer.zero_grad() 34 | -------------------------------------------------------------------------------- /semantic-segmentation/scripts_seg/fcaformer: -------------------------------------------------------------------------------- 1 | # train ****************************************************************************** 2 | PORT=29501 bash tools/dist_train.sh configs/fcaformer/upernet_fcaformer_l2_160k_ade20k_ms.py 8 --work-dir /home/disk/result/fcaformer/ADE20k_seg/fcaformer_l2 --seed 0 --deterministic --options model.pretrained='/home/disk/result/fcaformer/imgnet1k_cls/fcaformer_l2/checkpoint-best.pth' 3 | 4 | 5 | # test ********************************************************************************* 6 | PORT=295001 bash tools/dist_test.sh configs/fcaformer/upernet_fcaformer_l2_160k_ade20k_ms.py /home/disk/result/fcaformer/ADE20k_seg/fcaformer_l2/iter_160000.pth 4 --eval mIoU --aug-test 7 | -------------------------------------------------------------------------------- /semantic-segmentation/tools/dist_test.sh: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env bash 2 | 3 | CONFIG=$1 4 | CHECKPOINT=$2 5 | GPUS=$3 6 | PORT=${PORT:-29500} 7 | PYTHONPATH="$(dirname $0)/..":$PYTHONPATH \ 8 | python -m torch.distributed.launch --nproc_per_node=$GPUS --master_port=$PORT \ 9 | $(dirname "$0")/test.py $CONFIG $CHECKPOINT --launcher pytorch ${@:4} 10 | -------------------------------------------------------------------------------- /semantic-segmentation/tools/dist_train.sh: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env bash 2 | 3 | CONFIG=$1 4 | GPUS=$2 5 | PORT=${PORT:-29500} 6 | 7 | PYTHONPATH="$(dirname $0)/..":$PYTHONPATH \ 8 | python -m torch.distributed.launch --nproc_per_node=$GPUS --master_port=$PORT \ 9 | $(dirname "$0")/train.py $CONFIG --launcher pytorch ${@:3} 10 | -------------------------------------------------------------------------------- /semantic-segmentation/tools/get_flops.py: -------------------------------------------------------------------------------- 1 | import sys 2 | sys.path.append('/home/disk/code/FcaFormer/semantic_segmentation') 3 | from backbone import fcaformer 4 | import argparse 5 | 6 | from mmcv import Config 7 | from mmcv.cnn import get_model_complexity_info 8 | from mmseg.models import build_segmentor 9 | 10 | 11 | def parse_args(): 12 | parser = argparse.ArgumentParser(description='Train a segmentor') 13 | parser.add_argument('config', help='train config file path') 14 | parser.add_argument( 15 | '--shape', 16 | type=int, 17 | nargs='+', 18 | default=[2048, 512], 19 | help='input image size') 20 | args = parser.parse_args() 21 | return args 22 | 23 | 24 | def main(): 25 | 26 | args = parse_args() 27 | 28 | if len(args.shape) == 1: 29 | input_shape = (3, args.shape[0], args.shape[0]) 30 | elif len(args.shape) == 2: 31 | input_shape = (3, ) + tuple(args.shape) 32 | else: 33 | raise ValueError('invalid input shape') 34 | 35 | cfg = Config.fromfile(args.config) 36 | cfg.model.pretrained = None 37 | model = build_segmentor( 38 | cfg.model, 39 | train_cfg=cfg.get('train_cfg'), 40 | test_cfg=cfg.get('test_cfg')).cuda() 41 | model.eval() 42 | 43 | if hasattr(model, 'forward_dummy'): 44 | model.forward = model.forward_dummy 45 | else: 46 | raise NotImplementedError( 47 | 'FLOPs counter is currently not currently supported with {}'. 48 | format(model.__class__.__name__)) 49 | 50 | flops, params = get_model_complexity_info(model, input_shape) 51 | split_line = '=' * 30 52 | print('{0}\nInput shape: {1}\nFlops: {2}\nParams: {3}\n{0}'.format( 53 | split_line, input_shape, flops, params)) 54 | print('!!!Please be cautious if you use the results in papers. ' 55 | 'You may need to check if all ops are supported and verify that the ' 56 | 'flops computation is correct.') 57 | 58 | 59 | if __name__ == '__main__': 60 | main() 61 | --------------------------------------------------------------------------------