repo
stringlengths
1
99
file
stringlengths
13
215
code
stringlengths
12
59.2M
file_length
int64
12
59.2M
avg_line_length
float64
3.82
1.48M
max_line_length
int64
12
2.51M
extension_type
stringclasses
1 value
GFocalV2
GFocalV2-master/tests/test_assigner.py
"""Tests the Assigner objects. CommandLine: pytest tests/test_assigner.py xdoctest tests/test_assigner.py zero """ import torch from mmdet.core.bbox.assigners import (ApproxMaxIoUAssigner, CenterRegionAssigner, MaxIoUAssigner, PointAssigner) def test_max_iou_assigner(): self = MaxIoUAssigner( pos_iou_thr=0.5, neg_iou_thr=0.5, ) bboxes = torch.FloatTensor([ [0, 0, 10, 10], [10, 10, 20, 20], [5, 5, 15, 15], [32, 32, 38, 42], ]) gt_bboxes = torch.FloatTensor([ [0, 0, 10, 9], [0, 10, 10, 19], ]) gt_labels = torch.LongTensor([2, 3]) assign_result = self.assign(bboxes, gt_bboxes, gt_labels=gt_labels) assert len(assign_result.gt_inds) == 4 assert len(assign_result.labels) == 4 expected_gt_inds = torch.LongTensor([1, 0, 2, 0]) assert torch.all(assign_result.gt_inds == expected_gt_inds) def test_max_iou_assigner_with_ignore(): self = MaxIoUAssigner( pos_iou_thr=0.5, neg_iou_thr=0.5, ignore_iof_thr=0.5, ignore_wrt_candidates=False, ) bboxes = torch.FloatTensor([ [0, 0, 10, 10], [10, 10, 20, 20], [5, 5, 15, 15], [30, 32, 40, 42], ]) gt_bboxes = torch.FloatTensor([ [0, 0, 10, 9], [0, 10, 10, 19], ]) gt_bboxes_ignore = torch.Tensor([ [30, 30, 40, 40], ]) assign_result = self.assign( bboxes, gt_bboxes, gt_bboxes_ignore=gt_bboxes_ignore) expected_gt_inds = torch.LongTensor([1, 0, 2, -1]) assert torch.all(assign_result.gt_inds == expected_gt_inds) def test_max_iou_assigner_with_empty_gt(): """Test corner case where an image might have no true detections.""" self = MaxIoUAssigner( pos_iou_thr=0.5, neg_iou_thr=0.5, ) bboxes = torch.FloatTensor([ [0, 0, 10, 10], [10, 10, 20, 20], [5, 5, 15, 15], [32, 32, 38, 42], ]) gt_bboxes = torch.empty(0, 4) assign_result = self.assign(bboxes, gt_bboxes) expected_gt_inds = torch.LongTensor([0, 0, 0, 0]) assert torch.all(assign_result.gt_inds == expected_gt_inds) def test_max_iou_assigner_with_empty_boxes(): """Test corner case where a network might predict no boxes.""" self = MaxIoUAssigner( pos_iou_thr=0.5, neg_iou_thr=0.5, ) bboxes = torch.empty((0, 4)) gt_bboxes = torch.FloatTensor([ [0, 0, 10, 9], [0, 10, 10, 19], ]) gt_labels = torch.LongTensor([2, 3]) # Test with gt_labels assign_result = self.assign(bboxes, gt_bboxes, gt_labels=gt_labels) assert len(assign_result.gt_inds) == 0 assert tuple(assign_result.labels.shape) == (0, ) # Test without gt_labels assign_result = self.assign(bboxes, gt_bboxes, gt_labels=None) assert len(assign_result.gt_inds) == 0 assert assign_result.labels is None def test_max_iou_assigner_with_empty_boxes_and_ignore(): """Test corner case where a network might predict no boxes and ignore_iof_thr is on.""" self = MaxIoUAssigner( pos_iou_thr=0.5, neg_iou_thr=0.5, ignore_iof_thr=0.5, ) bboxes = torch.empty((0, 4)) gt_bboxes = torch.FloatTensor([ [0, 0, 10, 9], [0, 10, 10, 19], ]) gt_bboxes_ignore = torch.Tensor([ [30, 30, 40, 40], ]) gt_labels = torch.LongTensor([2, 3]) # Test with gt_labels assign_result = self.assign( bboxes, gt_bboxes, gt_labels=gt_labels, gt_bboxes_ignore=gt_bboxes_ignore) assert len(assign_result.gt_inds) == 0 assert tuple(assign_result.labels.shape) == (0, ) # Test without gt_labels assign_result = self.assign( bboxes, gt_bboxes, gt_labels=None, gt_bboxes_ignore=gt_bboxes_ignore) assert len(assign_result.gt_inds) == 0 assert assign_result.labels is None def test_max_iou_assigner_with_empty_boxes_and_gt(): """Test corner case where a network might predict no boxes and no gt.""" self = MaxIoUAssigner( pos_iou_thr=0.5, neg_iou_thr=0.5, ) bboxes = torch.empty((0, 4)) gt_bboxes = torch.empty((0, 4)) assign_result = self.assign(bboxes, gt_bboxes) assert len(assign_result.gt_inds) == 0 def test_point_assigner(): self = PointAssigner() points = torch.FloatTensor([ # [x, y, stride] [0, 0, 1], [10, 10, 1], [5, 5, 1], [32, 32, 1], ]) gt_bboxes = torch.FloatTensor([ [0, 0, 10, 9], [0, 10, 10, 19], ]) assign_result = self.assign(points, gt_bboxes) expected_gt_inds = torch.LongTensor([1, 2, 1, 0]) assert torch.all(assign_result.gt_inds == expected_gt_inds) def test_point_assigner_with_empty_gt(): """Test corner case where an image might have no true detections.""" self = PointAssigner() points = torch.FloatTensor([ # [x, y, stride] [0, 0, 1], [10, 10, 1], [5, 5, 1], [32, 32, 1], ]) gt_bboxes = torch.FloatTensor([]) assign_result = self.assign(points, gt_bboxes) expected_gt_inds = torch.LongTensor([0, 0, 0, 0]) assert torch.all(assign_result.gt_inds == expected_gt_inds) def test_point_assigner_with_empty_boxes_and_gt(): """Test corner case where an image might predict no points and no gt.""" self = PointAssigner() points = torch.FloatTensor([]) gt_bboxes = torch.FloatTensor([]) assign_result = self.assign(points, gt_bboxes) assert len(assign_result.gt_inds) == 0 def test_approx_iou_assigner(): self = ApproxMaxIoUAssigner( pos_iou_thr=0.5, neg_iou_thr=0.5, ) bboxes = torch.FloatTensor([ [0, 0, 10, 10], [10, 10, 20, 20], [5, 5, 15, 15], [32, 32, 38, 42], ]) gt_bboxes = torch.FloatTensor([ [0, 0, 10, 9], [0, 10, 10, 19], ]) approxs_per_octave = 1 approxs = bboxes squares = bboxes assign_result = self.assign(approxs, squares, approxs_per_octave, gt_bboxes) expected_gt_inds = torch.LongTensor([1, 0, 2, 0]) assert torch.all(assign_result.gt_inds == expected_gt_inds) def test_approx_iou_assigner_with_empty_gt(): """Test corner case where an image might have no true detections.""" self = ApproxMaxIoUAssigner( pos_iou_thr=0.5, neg_iou_thr=0.5, ) bboxes = torch.FloatTensor([ [0, 0, 10, 10], [10, 10, 20, 20], [5, 5, 15, 15], [32, 32, 38, 42], ]) gt_bboxes = torch.FloatTensor([]) approxs_per_octave = 1 approxs = bboxes squares = bboxes assign_result = self.assign(approxs, squares, approxs_per_octave, gt_bboxes) expected_gt_inds = torch.LongTensor([0, 0, 0, 0]) assert torch.all(assign_result.gt_inds == expected_gt_inds) def test_approx_iou_assigner_with_empty_boxes(): """Test corner case where an network might predict no boxes.""" self = ApproxMaxIoUAssigner( pos_iou_thr=0.5, neg_iou_thr=0.5, ) bboxes = torch.empty((0, 4)) gt_bboxes = torch.FloatTensor([ [0, 0, 10, 9], [0, 10, 10, 19], ]) approxs_per_octave = 1 approxs = bboxes squares = bboxes assign_result = self.assign(approxs, squares, approxs_per_octave, gt_bboxes) assert len(assign_result.gt_inds) == 0 def test_approx_iou_assigner_with_empty_boxes_and_gt(): """Test corner case where an network might predict no boxes and no gt.""" self = ApproxMaxIoUAssigner( pos_iou_thr=0.5, neg_iou_thr=0.5, ) bboxes = torch.empty((0, 4)) gt_bboxes = torch.empty((0, 4)) approxs_per_octave = 1 approxs = bboxes squares = bboxes assign_result = self.assign(approxs, squares, approxs_per_octave, gt_bboxes) assert len(assign_result.gt_inds) == 0 def test_random_assign_result(): """Test random instantiation of assign result to catch corner cases.""" from mmdet.core.bbox.assigners.assign_result import AssignResult AssignResult.random() AssignResult.random(num_gts=0, num_preds=0) AssignResult.random(num_gts=0, num_preds=3) AssignResult.random(num_gts=3, num_preds=3) AssignResult.random(num_gts=0, num_preds=3) AssignResult.random(num_gts=7, num_preds=7) AssignResult.random(num_gts=7, num_preds=64) AssignResult.random(num_gts=24, num_preds=3) def test_center_region_assigner(): self = CenterRegionAssigner(pos_scale=0.3, neg_scale=1) bboxes = torch.FloatTensor([[0, 0, 10, 10], [10, 10, 20, 20], [8, 8, 9, 9]]) gt_bboxes = torch.FloatTensor([ [0, 0, 11, 11], # match bboxes[0] [10, 10, 20, 20], # match bboxes[1] [4.5, 4.5, 5.5, 5.5], # match bboxes[0] but area is too small [0, 0, 10, 10], # match bboxes[1] and has a smaller area than gt[0] ]) gt_labels = torch.LongTensor([2, 3, 4, 5]) assign_result = self.assign(bboxes, gt_bboxes, gt_labels=gt_labels) assert len(assign_result.gt_inds) == 3 assert len(assign_result.labels) == 3 expected_gt_inds = torch.LongTensor([4, 2, 0]) assert torch.all(assign_result.gt_inds == expected_gt_inds) shadowed_labels = assign_result.get_extra_property('shadowed_labels') # [8, 8, 9, 9] in the shadowed region of [0, 0, 11, 11] (label: 2) assert torch.any(shadowed_labels == torch.LongTensor([[2, 2]])) # [8, 8, 9, 9] in the shadowed region of [0, 0, 10, 10] (label: 5) assert torch.any(shadowed_labels == torch.LongTensor([[2, 5]])) # [0, 0, 10, 10] is already assigned to [4.5, 4.5, 5.5, 5.5]. # Therefore, [0, 0, 11, 11] (label: 2) is shadowed assert torch.any(shadowed_labels == torch.LongTensor([[0, 2]])) def test_center_region_assigner_with_ignore(): self = CenterRegionAssigner( pos_scale=0.5, neg_scale=1, ) bboxes = torch.FloatTensor([ [0, 0, 10, 10], [10, 10, 20, 20], ]) gt_bboxes = torch.FloatTensor([ [0, 0, 10, 10], # match bboxes[0] [10, 10, 20, 20], # match bboxes[1] ]) gt_bboxes_ignore = torch.FloatTensor([ [0, 0, 10, 10], # match bboxes[0] ]) gt_labels = torch.LongTensor([1, 2]) assign_result = self.assign( bboxes, gt_bboxes, gt_bboxes_ignore=gt_bboxes_ignore, gt_labels=gt_labels) assert len(assign_result.gt_inds) == 2 assert len(assign_result.labels) == 2 expected_gt_inds = torch.LongTensor([-1, 2]) assert torch.all(assign_result.gt_inds == expected_gt_inds) def test_center_region_assigner_with_empty_bboxes(): self = CenterRegionAssigner( pos_scale=0.5, neg_scale=1, ) bboxes = torch.empty((0, 4)).float() gt_bboxes = torch.FloatTensor([ [0, 0, 10, 10], # match bboxes[0] [10, 10, 20, 20], # match bboxes[1] ]) gt_labels = torch.LongTensor([1, 2]) assign_result = self.assign(bboxes, gt_bboxes, gt_labels=gt_labels) assert assign_result.gt_inds is None or assign_result.gt_inds.numel() == 0 assert assign_result.labels is None or assign_result.labels.numel() == 0 def test_center_region_assigner_with_empty_gts(): self = CenterRegionAssigner( pos_scale=0.5, neg_scale=1, ) bboxes = torch.FloatTensor([ [0, 0, 10, 10], [10, 10, 20, 20], ]) gt_bboxes = torch.empty((0, 4)).float() gt_labels = torch.empty((0, )).long() assign_result = self.assign(bboxes, gt_bboxes, gt_labels=gt_labels) assert len(assign_result.gt_inds) == 2 expected_gt_inds = torch.LongTensor([0, 0]) assert torch.all(assign_result.gt_inds == expected_gt_inds)
11,913
30.435356
78
py
GFocalV2
GFocalV2-master/tests/test_fp16.py
import numpy as np import pytest import torch import torch.nn as nn from mmcv.runner import auto_fp16, force_fp32 from mmcv.runner.fp16_utils import cast_tensor_type def test_cast_tensor_type(): inputs = torch.FloatTensor([5.]) src_type = torch.float32 dst_type = torch.int32 outputs = cast_tensor_type(inputs, src_type, dst_type) assert isinstance(outputs, torch.Tensor) assert outputs.dtype == dst_type inputs = 'tensor' src_type = str dst_type = str outputs = cast_tensor_type(inputs, src_type, dst_type) assert isinstance(outputs, str) inputs = np.array([5.]) src_type = np.ndarray dst_type = np.ndarray outputs = cast_tensor_type(inputs, src_type, dst_type) assert isinstance(outputs, np.ndarray) inputs = dict( tensor_a=torch.FloatTensor([1.]), tensor_b=torch.FloatTensor([2.])) src_type = torch.float32 dst_type = torch.int32 outputs = cast_tensor_type(inputs, src_type, dst_type) assert isinstance(outputs, dict) assert outputs['tensor_a'].dtype == dst_type assert outputs['tensor_b'].dtype == dst_type inputs = [torch.FloatTensor([1.]), torch.FloatTensor([2.])] src_type = torch.float32 dst_type = torch.int32 outputs = cast_tensor_type(inputs, src_type, dst_type) assert isinstance(outputs, list) assert outputs[0].dtype == dst_type assert outputs[1].dtype == dst_type inputs = 5 outputs = cast_tensor_type(inputs, None, None) assert isinstance(outputs, int) def test_auto_fp16(): with pytest.raises(TypeError): # ExampleObject is not a subclass of nn.Module class ExampleObject(object): @auto_fp16() def __call__(self, x): return x model = ExampleObject() input_x = torch.ones(1, dtype=torch.float32) model(input_x) # apply to all input args class ExampleModule(nn.Module): @auto_fp16() def forward(self, x, y): return x, y model = ExampleModule() input_x = torch.ones(1, dtype=torch.float32) input_y = torch.ones(1, dtype=torch.float32) output_x, output_y = model(input_x, input_y) assert output_x.dtype == torch.float32 assert output_y.dtype == torch.float32 model.fp16_enabled = True output_x, output_y = model(input_x, input_y) assert output_x.dtype == torch.half assert output_y.dtype == torch.half if torch.cuda.is_available(): model.cuda() output_x, output_y = model(input_x.cuda(), input_y.cuda()) assert output_x.dtype == torch.half assert output_y.dtype == torch.half # apply to specified input args class ExampleModule(nn.Module): @auto_fp16(apply_to=('x', )) def forward(self, x, y): return x, y model = ExampleModule() input_x = torch.ones(1, dtype=torch.float32) input_y = torch.ones(1, dtype=torch.float32) output_x, output_y = model(input_x, input_y) assert output_x.dtype == torch.float32 assert output_y.dtype == torch.float32 model.fp16_enabled = True output_x, output_y = model(input_x, input_y) assert output_x.dtype == torch.half assert output_y.dtype == torch.float32 if torch.cuda.is_available(): model.cuda() output_x, output_y = model(input_x.cuda(), input_y.cuda()) assert output_x.dtype == torch.half assert output_y.dtype == torch.float32 # apply to optional input args class ExampleModule(nn.Module): @auto_fp16(apply_to=('x', 'y')) def forward(self, x, y=None, z=None): return x, y, z model = ExampleModule() input_x = torch.ones(1, dtype=torch.float32) input_y = torch.ones(1, dtype=torch.float32) input_z = torch.ones(1, dtype=torch.float32) output_x, output_y, output_z = model(input_x, y=input_y, z=input_z) assert output_x.dtype == torch.float32 assert output_y.dtype == torch.float32 assert output_z.dtype == torch.float32 model.fp16_enabled = True output_x, output_y, output_z = model(input_x, y=input_y, z=input_z) assert output_x.dtype == torch.half assert output_y.dtype == torch.half assert output_z.dtype == torch.float32 if torch.cuda.is_available(): model.cuda() output_x, output_y, output_z = model( input_x.cuda(), y=input_y.cuda(), z=input_z.cuda()) assert output_x.dtype == torch.half assert output_y.dtype == torch.half assert output_z.dtype == torch.float32 # out_fp32=True class ExampleModule(nn.Module): @auto_fp16(apply_to=('x', 'y'), out_fp32=True) def forward(self, x, y=None, z=None): return x, y, z model = ExampleModule() input_x = torch.ones(1, dtype=torch.half) input_y = torch.ones(1, dtype=torch.float32) input_z = torch.ones(1, dtype=torch.float32) output_x, output_y, output_z = model(input_x, y=input_y, z=input_z) assert output_x.dtype == torch.half assert output_y.dtype == torch.float32 assert output_z.dtype == torch.float32 model.fp16_enabled = True output_x, output_y, output_z = model(input_x, y=input_y, z=input_z) assert output_x.dtype == torch.float32 assert output_y.dtype == torch.float32 assert output_z.dtype == torch.float32 if torch.cuda.is_available(): model.cuda() output_x, output_y, output_z = model( input_x.cuda(), y=input_y.cuda(), z=input_z.cuda()) assert output_x.dtype == torch.float32 assert output_y.dtype == torch.float32 assert output_z.dtype == torch.float32 def test_force_fp32(): with pytest.raises(TypeError): # ExampleObject is not a subclass of nn.Module class ExampleObject(object): @force_fp32() def __call__(self, x): return x model = ExampleObject() input_x = torch.ones(1, dtype=torch.float32) model(input_x) # apply to all input args class ExampleModule(nn.Module): @force_fp32() def forward(self, x, y): return x, y model = ExampleModule() input_x = torch.ones(1, dtype=torch.half) input_y = torch.ones(1, dtype=torch.half) output_x, output_y = model(input_x, input_y) assert output_x.dtype == torch.half assert output_y.dtype == torch.half model.fp16_enabled = True output_x, output_y = model(input_x, input_y) assert output_x.dtype == torch.float32 assert output_y.dtype == torch.float32 if torch.cuda.is_available(): model.cuda() output_x, output_y = model(input_x.cuda(), input_y.cuda()) assert output_x.dtype == torch.float32 assert output_y.dtype == torch.float32 # apply to specified input args class ExampleModule(nn.Module): @force_fp32(apply_to=('x', )) def forward(self, x, y): return x, y model = ExampleModule() input_x = torch.ones(1, dtype=torch.half) input_y = torch.ones(1, dtype=torch.half) output_x, output_y = model(input_x, input_y) assert output_x.dtype == torch.half assert output_y.dtype == torch.half model.fp16_enabled = True output_x, output_y = model(input_x, input_y) assert output_x.dtype == torch.float32 assert output_y.dtype == torch.half if torch.cuda.is_available(): model.cuda() output_x, output_y = model(input_x.cuda(), input_y.cuda()) assert output_x.dtype == torch.float32 assert output_y.dtype == torch.half # apply to optional input args class ExampleModule(nn.Module): @force_fp32(apply_to=('x', 'y')) def forward(self, x, y=None, z=None): return x, y, z model = ExampleModule() input_x = torch.ones(1, dtype=torch.half) input_y = torch.ones(1, dtype=torch.half) input_z = torch.ones(1, dtype=torch.half) output_x, output_y, output_z = model(input_x, y=input_y, z=input_z) assert output_x.dtype == torch.half assert output_y.dtype == torch.half assert output_z.dtype == torch.half model.fp16_enabled = True output_x, output_y, output_z = model(input_x, y=input_y, z=input_z) assert output_x.dtype == torch.float32 assert output_y.dtype == torch.float32 assert output_z.dtype == torch.half if torch.cuda.is_available(): model.cuda() output_x, output_y, output_z = model( input_x.cuda(), y=input_y.cuda(), z=input_z.cuda()) assert output_x.dtype == torch.float32 assert output_y.dtype == torch.float32 assert output_z.dtype == torch.half # out_fp16=True class ExampleModule(nn.Module): @force_fp32(apply_to=('x', 'y'), out_fp16=True) def forward(self, x, y=None, z=None): return x, y, z model = ExampleModule() input_x = torch.ones(1, dtype=torch.float32) input_y = torch.ones(1, dtype=torch.half) input_z = torch.ones(1, dtype=torch.half) output_x, output_y, output_z = model(input_x, y=input_y, z=input_z) assert output_x.dtype == torch.float32 assert output_y.dtype == torch.half assert output_z.dtype == torch.half model.fp16_enabled = True output_x, output_y, output_z = model(input_x, y=input_y, z=input_z) assert output_x.dtype == torch.half assert output_y.dtype == torch.half assert output_z.dtype == torch.half if torch.cuda.is_available(): model.cuda() output_x, output_y, output_z = model( input_x.cuda(), y=input_y.cuda(), z=input_z.cuda()) assert output_x.dtype == torch.half assert output_y.dtype == torch.half assert output_z.dtype == torch.half
9,714
31.275748
75
py
GFocalV2
GFocalV2-master/tests/test_models/test_roi_extractor.py
import pytest import torch from mmdet.models.roi_heads.roi_extractors import GenericRoIExtractor def test_groie(): # test with pre/post cfg = dict( roi_layer=dict(type='RoIAlign', output_size=7, sampling_ratio=2), out_channels=256, featmap_strides=[4, 8, 16, 32], pre_cfg=dict( type='ConvModule', in_channels=256, out_channels=256, kernel_size=5, padding=2, inplace=False, ), post_cfg=dict( type='ConvModule', in_channels=256, out_channels=256, kernel_size=5, padding=2, inplace=False)) groie = GenericRoIExtractor(**cfg) feats = ( torch.rand((1, 256, 200, 336)), torch.rand((1, 256, 100, 168)), torch.rand((1, 256, 50, 84)), torch.rand((1, 256, 25, 42)), ) rois = torch.tensor([[0.0000, 587.8285, 52.1405, 886.2484, 341.5644]]) res = groie(feats, rois) assert res.shape == torch.Size([1, 256, 7, 7]) # test w.o. pre/post cfg = dict( roi_layer=dict(type='RoIAlign', output_size=7, sampling_ratio=2), out_channels=256, featmap_strides=[4, 8, 16, 32]) groie = GenericRoIExtractor(**cfg) feats = ( torch.rand((1, 256, 200, 336)), torch.rand((1, 256, 100, 168)), torch.rand((1, 256, 50, 84)), torch.rand((1, 256, 25, 42)), ) rois = torch.tensor([[0.0000, 587.8285, 52.1405, 886.2484, 341.5644]]) res = groie(feats, rois) assert res.shape == torch.Size([1, 256, 7, 7]) # test w.o. pre/post concat cfg = dict( aggregation='concat', roi_layer=dict(type='RoIAlign', output_size=7, sampling_ratio=2), out_channels=256 * 4, featmap_strides=[4, 8, 16, 32]) groie = GenericRoIExtractor(**cfg) feats = ( torch.rand((1, 256, 200, 336)), torch.rand((1, 256, 100, 168)), torch.rand((1, 256, 50, 84)), torch.rand((1, 256, 25, 42)), ) rois = torch.tensor([[0.0000, 587.8285, 52.1405, 886.2484, 341.5644]]) res = groie(feats, rois) assert res.shape == torch.Size([1, 1024, 7, 7]) # test not supported aggregate method with pytest.raises(AssertionError): cfg = dict( aggregation='not support', roi_layer=dict(type='RoIAlign', output_size=7, sampling_ratio=2), out_channels=1024, featmap_strides=[4, 8, 16, 32]) _ = GenericRoIExtractor(**cfg) # test concat channels number cfg = dict( aggregation='concat', roi_layer=dict(type='RoIAlign', output_size=7, sampling_ratio=2), out_channels=256 * 5, # 256*5 != 256*4 featmap_strides=[4, 8, 16, 32]) groie = GenericRoIExtractor(**cfg) feats = ( torch.rand((1, 256, 200, 336)), torch.rand((1, 256, 100, 168)), torch.rand((1, 256, 50, 84)), torch.rand((1, 256, 25, 42)), ) rois = torch.tensor([[0.0000, 587.8285, 52.1405, 886.2484, 341.5644]]) # out_channels does not sum of feat channels with pytest.raises(AssertionError): _ = groie(feats, rois)
3,209
27.157895
77
py
GFocalV2
GFocalV2-master/tests/test_models/test_forward.py
"""pytest tests/test_forward.py.""" import copy from os.path import dirname, exists, join import numpy as np import pytest import torch def _get_config_directory(): """Find the predefined detector config directory.""" try: # Assume we are running in the source mmdetection repo repo_dpath = dirname(dirname(dirname(__file__))) except NameError: # For IPython development when this __file__ is not defined import mmdet repo_dpath = dirname(dirname(mmdet.__file__)) config_dpath = join(repo_dpath, 'configs') if not exists(config_dpath): raise Exception('Cannot find config path') return config_dpath def _get_config_module(fname): """Load a configuration as a python module.""" from mmcv import Config config_dpath = _get_config_directory() config_fpath = join(config_dpath, fname) config_mod = Config.fromfile(config_fpath) return config_mod def _get_detector_cfg(fname): """Grab configs necessary to create a detector. These are deep copied to allow for safe modification of parameters without influencing other tests. """ import mmcv config = _get_config_module(fname) model = copy.deepcopy(config.model) train_cfg = mmcv.Config(copy.deepcopy(config.train_cfg)) test_cfg = mmcv.Config(copy.deepcopy(config.test_cfg)) return model, train_cfg, test_cfg def test_rpn_forward(): model, train_cfg, test_cfg = _get_detector_cfg( 'rpn/rpn_r50_fpn_1x_coco.py') model['pretrained'] = None from mmdet.models import build_detector detector = build_detector(model, train_cfg=train_cfg, test_cfg=test_cfg) input_shape = (1, 3, 224, 224) mm_inputs = _demo_mm_inputs(input_shape) imgs = mm_inputs.pop('imgs') img_metas = mm_inputs.pop('img_metas') # Test forward train gt_bboxes = mm_inputs['gt_bboxes'] losses = detector.forward( imgs, img_metas, gt_bboxes=gt_bboxes, return_loss=True) assert isinstance(losses, dict) # Test forward test with torch.no_grad(): img_list = [g[None, :] for g in imgs] batch_results = [] for one_img, one_meta in zip(img_list, img_metas): result = detector.forward([one_img], [[one_meta]], return_loss=False) batch_results.append(result) @pytest.mark.parametrize( 'cfg_file', [ 'retinanet/retinanet_r50_fpn_1x_coco.py', 'guided_anchoring/ga_retinanet_r50_fpn_1x_coco.py', 'ghm/retinanet_ghm_r50_fpn_1x_coco.py', 'fcos/fcos_center_r50_caffe_fpn_gn-head_4x4_1x_coco.py', 'foveabox/fovea_align_r50_fpn_gn-head_4x4_2x_coco.py', # 'free_anchor/retinanet_free_anchor_r50_fpn_1x_coco.py', # 'atss/atss_r50_fpn_1x_coco.py', # not ready for topk 'reppoints/reppoints_moment_r50_fpn_1x_coco.py', 'yolo/yolov3_d53_mstrain-608_273e_coco.py' ]) def test_single_stage_forward_gpu(cfg_file): if not torch.cuda.is_available(): import pytest pytest.skip('test requires GPU and torch+cuda') model, train_cfg, test_cfg = _get_detector_cfg(cfg_file) model['pretrained'] = None from mmdet.models import build_detector detector = build_detector(model, train_cfg=train_cfg, test_cfg=test_cfg) input_shape = (2, 3, 224, 224) mm_inputs = _demo_mm_inputs(input_shape) imgs = mm_inputs.pop('imgs') img_metas = mm_inputs.pop('img_metas') detector = detector.cuda() imgs = imgs.cuda() # Test forward train gt_bboxes = [b.cuda() for b in mm_inputs['gt_bboxes']] gt_labels = [g.cuda() for g in mm_inputs['gt_labels']] losses = detector.forward( imgs, img_metas, gt_bboxes=gt_bboxes, gt_labels=gt_labels, return_loss=True) assert isinstance(losses, dict) # Test forward test with torch.no_grad(): img_list = [g[None, :] for g in imgs] batch_results = [] for one_img, one_meta in zip(img_list, img_metas): result = detector.forward([one_img], [[one_meta]], return_loss=False) batch_results.append(result) def test_faster_rcnn_ohem_forward(): model, train_cfg, test_cfg = _get_detector_cfg( 'faster_rcnn/faster_rcnn_r50_fpn_ohem_1x_coco.py') model['pretrained'] = None from mmdet.models import build_detector detector = build_detector(model, train_cfg=train_cfg, test_cfg=test_cfg) input_shape = (1, 3, 256, 256) # Test forward train with a non-empty truth batch mm_inputs = _demo_mm_inputs(input_shape, num_items=[10]) imgs = mm_inputs.pop('imgs') img_metas = mm_inputs.pop('img_metas') gt_bboxes = mm_inputs['gt_bboxes'] gt_labels = mm_inputs['gt_labels'] losses = detector.forward( imgs, img_metas, gt_bboxes=gt_bboxes, gt_labels=gt_labels, return_loss=True) assert isinstance(losses, dict) loss, _ = detector._parse_losses(losses) assert float(loss.item()) > 0 # Test forward train with an empty truth batch mm_inputs = _demo_mm_inputs(input_shape, num_items=[0]) imgs = mm_inputs.pop('imgs') img_metas = mm_inputs.pop('img_metas') gt_bboxes = mm_inputs['gt_bboxes'] gt_labels = mm_inputs['gt_labels'] losses = detector.forward( imgs, img_metas, gt_bboxes=gt_bboxes, gt_labels=gt_labels, return_loss=True) assert isinstance(losses, dict) loss, _ = detector._parse_losses(losses) assert float(loss.item()) > 0 # HTC is not ready yet @pytest.mark.parametrize('cfg_file', [ 'cascade_rcnn/cascade_mask_rcnn_r50_fpn_1x_coco.py', 'mask_rcnn/mask_rcnn_r50_fpn_1x_coco.py', 'grid_rcnn/grid_rcnn_r50_fpn_gn-head_2x_coco.py', 'ms_rcnn/ms_rcnn_r50_fpn_1x_coco.py' ]) def test_two_stage_forward(cfg_file): model, train_cfg, test_cfg = _get_detector_cfg(cfg_file) model['pretrained'] = None from mmdet.models import build_detector detector = build_detector(model, train_cfg=train_cfg, test_cfg=test_cfg) input_shape = (1, 3, 256, 256) # Test forward train with a non-empty truth batch mm_inputs = _demo_mm_inputs(input_shape, num_items=[10]) imgs = mm_inputs.pop('imgs') img_metas = mm_inputs.pop('img_metas') gt_bboxes = mm_inputs['gt_bboxes'] gt_labels = mm_inputs['gt_labels'] gt_masks = mm_inputs['gt_masks'] losses = detector.forward( imgs, img_metas, gt_bboxes=gt_bboxes, gt_labels=gt_labels, gt_masks=gt_masks, return_loss=True) assert isinstance(losses, dict) loss, _ = detector._parse_losses(losses) loss.requires_grad_(True) assert float(loss.item()) > 0 loss.backward() # Test forward train with an empty truth batch mm_inputs = _demo_mm_inputs(input_shape, num_items=[0]) imgs = mm_inputs.pop('imgs') img_metas = mm_inputs.pop('img_metas') gt_bboxes = mm_inputs['gt_bboxes'] gt_labels = mm_inputs['gt_labels'] gt_masks = mm_inputs['gt_masks'] losses = detector.forward( imgs, img_metas, gt_bboxes=gt_bboxes, gt_labels=gt_labels, gt_masks=gt_masks, return_loss=True) assert isinstance(losses, dict) loss, _ = detector._parse_losses(losses) loss.requires_grad_(True) assert float(loss.item()) > 0 loss.backward() # Test forward test with torch.no_grad(): img_list = [g[None, :] for g in imgs] batch_results = [] for one_img, one_meta in zip(img_list, img_metas): result = detector.forward([one_img], [[one_meta]], return_loss=False) batch_results.append(result) @pytest.mark.parametrize( 'cfg_file', ['ghm/retinanet_ghm_r50_fpn_1x_coco.py', 'ssd/ssd300_coco.py']) def test_single_stage_forward_cpu(cfg_file): model, train_cfg, test_cfg = _get_detector_cfg(cfg_file) model['pretrained'] = None from mmdet.models import build_detector detector = build_detector(model, train_cfg=train_cfg, test_cfg=test_cfg) input_shape = (1, 3, 300, 300) mm_inputs = _demo_mm_inputs(input_shape) imgs = mm_inputs.pop('imgs') img_metas = mm_inputs.pop('img_metas') # Test forward train gt_bboxes = mm_inputs['gt_bboxes'] gt_labels = mm_inputs['gt_labels'] losses = detector.forward( imgs, img_metas, gt_bboxes=gt_bboxes, gt_labels=gt_labels, return_loss=True) assert isinstance(losses, dict) # Test forward test with torch.no_grad(): img_list = [g[None, :] for g in imgs] batch_results = [] for one_img, one_meta in zip(img_list, img_metas): result = detector.forward([one_img], [[one_meta]], return_loss=False) batch_results.append(result) def _demo_mm_inputs(input_shape=(1, 3, 300, 300), num_items=None, num_classes=10): # yapf: disable """Create a superset of inputs needed to run test or train batches. Args: input_shape (tuple): input batch dimensions num_items (None | List[int]): specifies the number of boxes in each batch item num_classes (int): number of different labels a box might have """ from mmdet.core import BitmapMasks (N, C, H, W) = input_shape rng = np.random.RandomState(0) imgs = rng.rand(*input_shape) img_metas = [{ 'img_shape': (H, W, C), 'ori_shape': (H, W, C), 'pad_shape': (H, W, C), 'filename': '<demo>.png', 'scale_factor': 1.0, 'flip': False, } for _ in range(N)] gt_bboxes = [] gt_labels = [] gt_masks = [] for batch_idx in range(N): if num_items is None: num_boxes = rng.randint(1, 10) else: num_boxes = num_items[batch_idx] cx, cy, bw, bh = rng.rand(num_boxes, 4).T tl_x = ((cx * W) - (W * bw / 2)).clip(0, W) tl_y = ((cy * H) - (H * bh / 2)).clip(0, H) br_x = ((cx * W) + (W * bw / 2)).clip(0, W) br_y = ((cy * H) + (H * bh / 2)).clip(0, H) boxes = np.vstack([tl_x, tl_y, br_x, br_y]).T class_idxs = rng.randint(1, num_classes, size=num_boxes) gt_bboxes.append(torch.FloatTensor(boxes)) gt_labels.append(torch.LongTensor(class_idxs)) mask = np.random.randint(0, 2, (len(boxes), H, W), dtype=np.uint8) gt_masks.append(BitmapMasks(mask, H, W)) mm_inputs = { 'imgs': torch.FloatTensor(imgs).requires_grad_(True), 'img_metas': img_metas, 'gt_bboxes': gt_bboxes, 'gt_labels': gt_labels, 'gt_bboxes_ignore': None, 'gt_masks': gt_masks, } return mm_inputs def test_yolact_forward(): model, train_cfg, test_cfg = _get_detector_cfg( 'yolact/yolact_r50_1x8_coco.py') model['pretrained'] = None from mmdet.models import build_detector detector = build_detector(model, train_cfg=train_cfg, test_cfg=test_cfg) input_shape = (1, 3, 550, 550) mm_inputs = _demo_mm_inputs(input_shape) imgs = mm_inputs.pop('imgs') img_metas = mm_inputs.pop('img_metas') # Test forward train detector.train() gt_bboxes = mm_inputs['gt_bboxes'] gt_labels = mm_inputs['gt_labels'] gt_masks = mm_inputs['gt_masks'] losses = detector.forward( imgs, img_metas, gt_bboxes=gt_bboxes, gt_labels=gt_labels, gt_masks=gt_masks, return_loss=True) assert isinstance(losses, dict) # Test forward test detector.eval() with torch.no_grad(): img_list = [g[None, :] for g in imgs] batch_results = [] for one_img, one_meta in zip(img_list, img_metas): result = detector.forward([one_img], [[one_meta]], rescale=True, return_loss=False) batch_results.append(result)
12,095
30.664921
79
py
GFocalV2
GFocalV2-master/tests/test_models/test_backbones.py
import pytest import torch from mmcv.ops import DeformConv2dPack from torch.nn.modules import AvgPool2d, GroupNorm from torch.nn.modules.batchnorm import _BatchNorm from mmdet.models.backbones import RegNet, Res2Net, ResNet, ResNetV1d, ResNeXt from mmdet.models.backbones.hourglass import HourglassNet from mmdet.models.backbones.res2net import Bottle2neck from mmdet.models.backbones.resnet import BasicBlock, Bottleneck from mmdet.models.backbones.resnext import Bottleneck as BottleneckX from mmdet.models.utils import ResLayer def is_block(modules): """Check if is ResNet building block.""" if isinstance(modules, (BasicBlock, Bottleneck, BottleneckX, Bottle2neck)): return True return False def is_norm(modules): """Check if is one of the norms.""" if isinstance(modules, (GroupNorm, _BatchNorm)): return True return False def all_zeros(modules): """Check if the weight(and bias) is all zero.""" weight_zero = torch.allclose(modules.weight.data, torch.zeros_like(modules.weight.data)) if hasattr(modules, 'bias'): bias_zero = torch.allclose(modules.bias.data, torch.zeros_like(modules.bias.data)) else: bias_zero = True return weight_zero and bias_zero def check_norm_state(modules, train_state): """Check if norm layer is in correct train state.""" for mod in modules: if isinstance(mod, _BatchNorm): if mod.training != train_state: return False return True def test_resnet_basic_block(): with pytest.raises(AssertionError): # Not implemented yet. dcn = dict(type='DCN', deform_groups=1, fallback_on_stride=False) BasicBlock(64, 64, dcn=dcn) with pytest.raises(AssertionError): # Not implemented yet. plugins = [ dict( cfg=dict(type='ContextBlock', ratio=1. / 16), position='after_conv3') ] BasicBlock(64, 64, plugins=plugins) with pytest.raises(AssertionError): # Not implemented yet plugins = [ dict( cfg=dict( type='GeneralizedAttention', spatial_range=-1, num_heads=8, attention_type='0010', kv_stride=2), position='after_conv2') ] BasicBlock(64, 64, plugins=plugins) # test BasicBlock structure and forward block = BasicBlock(64, 64) assert block.conv1.in_channels == 64 assert block.conv1.out_channels == 64 assert block.conv1.kernel_size == (3, 3) assert block.conv2.in_channels == 64 assert block.conv2.out_channels == 64 assert block.conv2.kernel_size == (3, 3) x = torch.randn(1, 64, 56, 56) x_out = block(x) assert x_out.shape == torch.Size([1, 64, 56, 56]) # Test BasicBlock with checkpoint forward block = BasicBlock(64, 64, with_cp=True) assert block.with_cp x = torch.randn(1, 64, 56, 56) x_out = block(x) assert x_out.shape == torch.Size([1, 64, 56, 56]) def test_resnet_bottleneck(): with pytest.raises(AssertionError): # Style must be in ['pytorch', 'caffe'] Bottleneck(64, 64, style='tensorflow') with pytest.raises(AssertionError): # Allowed positions are 'after_conv1', 'after_conv2', 'after_conv3' plugins = [ dict( cfg=dict(type='ContextBlock', ratio=1. / 16), position='after_conv4') ] Bottleneck(64, 16, plugins=plugins) with pytest.raises(AssertionError): # Need to specify different postfix to avoid duplicate plugin name plugins = [ dict( cfg=dict(type='ContextBlock', ratio=1. / 16), position='after_conv3'), dict( cfg=dict(type='ContextBlock', ratio=1. / 16), position='after_conv3') ] Bottleneck(64, 16, plugins=plugins) with pytest.raises(KeyError): # Plugin type is not supported plugins = [dict(cfg=dict(type='WrongPlugin'), position='after_conv3')] Bottleneck(64, 16, plugins=plugins) # Test Bottleneck with checkpoint forward block = Bottleneck(64, 16, with_cp=True) assert block.with_cp x = torch.randn(1, 64, 56, 56) x_out = block(x) assert x_out.shape == torch.Size([1, 64, 56, 56]) # Test Bottleneck style block = Bottleneck(64, 64, stride=2, style='pytorch') assert block.conv1.stride == (1, 1) assert block.conv2.stride == (2, 2) block = Bottleneck(64, 64, stride=2, style='caffe') assert block.conv1.stride == (2, 2) assert block.conv2.stride == (1, 1) # Test Bottleneck DCN dcn = dict(type='DCN', deform_groups=1, fallback_on_stride=False) with pytest.raises(AssertionError): Bottleneck(64, 64, dcn=dcn, conv_cfg=dict(type='Conv')) block = Bottleneck(64, 64, dcn=dcn) assert isinstance(block.conv2, DeformConv2dPack) # Test Bottleneck forward block = Bottleneck(64, 16) x = torch.randn(1, 64, 56, 56) x_out = block(x) assert x_out.shape == torch.Size([1, 64, 56, 56]) # Test Bottleneck with 1 ContextBlock after conv3 plugins = [ dict( cfg=dict(type='ContextBlock', ratio=1. / 16), position='after_conv3') ] block = Bottleneck(64, 16, plugins=plugins) assert block.context_block.in_channels == 64 x = torch.randn(1, 64, 56, 56) x_out = block(x) assert x_out.shape == torch.Size([1, 64, 56, 56]) # Test Bottleneck with 1 GeneralizedAttention after conv2 plugins = [ dict( cfg=dict( type='GeneralizedAttention', spatial_range=-1, num_heads=8, attention_type='0010', kv_stride=2), position='after_conv2') ] block = Bottleneck(64, 16, plugins=plugins) assert block.gen_attention_block.in_channels == 16 x = torch.randn(1, 64, 56, 56) x_out = block(x) assert x_out.shape == torch.Size([1, 64, 56, 56]) # Test Bottleneck with 1 GeneralizedAttention after conv2, 1 NonLocal2D # after conv2, 1 ContextBlock after conv3 plugins = [ dict( cfg=dict( type='GeneralizedAttention', spatial_range=-1, num_heads=8, attention_type='0010', kv_stride=2), position='after_conv2'), dict(cfg=dict(type='NonLocal2d'), position='after_conv2'), dict( cfg=dict(type='ContextBlock', ratio=1. / 16), position='after_conv3') ] block = Bottleneck(64, 16, plugins=plugins) assert block.gen_attention_block.in_channels == 16 assert block.nonlocal_block.in_channels == 16 assert block.context_block.in_channels == 64 x = torch.randn(1, 64, 56, 56) x_out = block(x) assert x_out.shape == torch.Size([1, 64, 56, 56]) # Test Bottleneck with 1 ContextBlock after conv2, 2 ContextBlock after # conv3 plugins = [ dict( cfg=dict(type='ContextBlock', ratio=1. / 16, postfix=1), position='after_conv2'), dict( cfg=dict(type='ContextBlock', ratio=1. / 16, postfix=2), position='after_conv3'), dict( cfg=dict(type='ContextBlock', ratio=1. / 16, postfix=3), position='after_conv3') ] block = Bottleneck(64, 16, plugins=plugins) assert block.context_block1.in_channels == 16 assert block.context_block2.in_channels == 64 assert block.context_block3.in_channels == 64 x = torch.randn(1, 64, 56, 56) x_out = block(x) assert x_out.shape == torch.Size([1, 64, 56, 56]) def test_resnet_res_layer(): # Test ResLayer of 3 Bottleneck w\o downsample layer = ResLayer(Bottleneck, 64, 16, 3) assert len(layer) == 3 assert layer[0].conv1.in_channels == 64 assert layer[0].conv1.out_channels == 16 for i in range(1, len(layer)): assert layer[i].conv1.in_channels == 64 assert layer[i].conv1.out_channels == 16 for i in range(len(layer)): assert layer[i].downsample is None x = torch.randn(1, 64, 56, 56) x_out = layer(x) assert x_out.shape == torch.Size([1, 64, 56, 56]) # Test ResLayer of 3 Bottleneck with downsample layer = ResLayer(Bottleneck, 64, 64, 3) assert layer[0].downsample[0].out_channels == 256 for i in range(1, len(layer)): assert layer[i].downsample is None x = torch.randn(1, 64, 56, 56) x_out = layer(x) assert x_out.shape == torch.Size([1, 256, 56, 56]) # Test ResLayer of 3 Bottleneck with stride=2 layer = ResLayer(Bottleneck, 64, 64, 3, stride=2) assert layer[0].downsample[0].out_channels == 256 assert layer[0].downsample[0].stride == (2, 2) for i in range(1, len(layer)): assert layer[i].downsample is None x = torch.randn(1, 64, 56, 56) x_out = layer(x) assert x_out.shape == torch.Size([1, 256, 28, 28]) # Test ResLayer of 3 Bottleneck with stride=2 and average downsample layer = ResLayer(Bottleneck, 64, 64, 3, stride=2, avg_down=True) assert isinstance(layer[0].downsample[0], AvgPool2d) assert layer[0].downsample[1].out_channels == 256 assert layer[0].downsample[1].stride == (1, 1) for i in range(1, len(layer)): assert layer[i].downsample is None x = torch.randn(1, 64, 56, 56) x_out = layer(x) assert x_out.shape == torch.Size([1, 256, 28, 28]) # Test ResLayer of 3 BasicBlock with stride=2 and downsample_first=False layer = ResLayer(BasicBlock, 64, 64, 3, stride=2, downsample_first=False) assert layer[2].downsample[0].out_channels == 64 assert layer[2].downsample[0].stride == (2, 2) for i in range(len(layer) - 1): assert layer[i].downsample is None x = torch.randn(1, 64, 56, 56) x_out = layer(x) assert x_out.shape == torch.Size([1, 64, 28, 28]) def test_resnest_stem(): # Test default stem_channels model = ResNet(50) assert model.stem_channels == 64 assert model.conv1.out_channels == 64 assert model.norm1.num_features == 64 # Test default stem_channels, with base_channels=32 model = ResNet(50, base_channels=32) assert model.stem_channels == 32 assert model.conv1.out_channels == 32 assert model.norm1.num_features == 32 assert model.layer1[0].conv1.in_channels == 32 # Test stem_channels=64 model = ResNet(50, stem_channels=64) assert model.stem_channels == 64 assert model.conv1.out_channels == 64 assert model.norm1.num_features == 64 assert model.layer1[0].conv1.in_channels == 64 # Test stem_channels=64, with base_channels=32 model = ResNet(50, stem_channels=64, base_channels=32) assert model.stem_channels == 64 assert model.conv1.out_channels == 64 assert model.norm1.num_features == 64 assert model.layer1[0].conv1.in_channels == 64 # Test stem_channels=128 model = ResNet(depth=50, stem_channels=128) model.init_weights() model.train() assert model.conv1.out_channels == 128 assert model.layer1[0].conv1.in_channels == 128 # Test V1d stem_channels model = ResNetV1d(depth=50, stem_channels=128) model.init_weights() model.train() assert model.stem[0].out_channels == 64 assert model.stem[1].num_features == 64 assert model.stem[3].out_channels == 64 assert model.stem[4].num_features == 64 assert model.stem[6].out_channels == 128 assert model.stem[7].num_features == 128 assert model.layer1[0].conv1.in_channels == 128 def test_resnet_backbone(): """Test resnet backbone.""" with pytest.raises(KeyError): # ResNet depth should be in [18, 34, 50, 101, 152] ResNet(20) with pytest.raises(AssertionError): # In ResNet: 1 <= num_stages <= 4 ResNet(50, num_stages=0) with pytest.raises(AssertionError): # len(stage_with_dcn) == num_stages dcn = dict(type='DCN', deform_groups=1, fallback_on_stride=False) ResNet(50, dcn=dcn, stage_with_dcn=(True, )) with pytest.raises(AssertionError): # len(stage_with_plugin) == num_stages plugins = [ dict( cfg=dict(type='ContextBlock', ratio=1. / 16), stages=(False, True, True), position='after_conv3') ] ResNet(50, plugins=plugins) with pytest.raises(AssertionError): # In ResNet: 1 <= num_stages <= 4 ResNet(50, num_stages=5) with pytest.raises(AssertionError): # len(strides) == len(dilations) == num_stages ResNet(50, strides=(1, ), dilations=(1, 1), num_stages=3) with pytest.raises(TypeError): # pretrained must be a string path model = ResNet(50) model.init_weights(pretrained=0) with pytest.raises(AssertionError): # Style must be in ['pytorch', 'caffe'] ResNet(50, style='tensorflow') # Test ResNet50 norm_eval=True model = ResNet(50, norm_eval=True) model.init_weights() model.train() assert check_norm_state(model.modules(), False) # Test ResNet50 with torchvision pretrained weight model = ResNet(depth=50, norm_eval=True) model.init_weights('torchvision://resnet50') model.train() assert check_norm_state(model.modules(), False) # Test ResNet50 with first stage frozen frozen_stages = 1 model = ResNet(50, frozen_stages=frozen_stages) model.init_weights() model.train() assert model.norm1.training is False for layer in [model.conv1, model.norm1]: for param in layer.parameters(): assert param.requires_grad is False for i in range(1, frozen_stages + 1): layer = getattr(model, f'layer{i}') for mod in layer.modules(): if isinstance(mod, _BatchNorm): assert mod.training is False for param in layer.parameters(): assert param.requires_grad is False # Test ResNet50V1d with first stage frozen model = ResNetV1d(depth=50, frozen_stages=frozen_stages) assert len(model.stem) == 9 model.init_weights() model.train() check_norm_state(model.stem, False) for param in model.stem.parameters(): assert param.requires_grad is False for i in range(1, frozen_stages + 1): layer = getattr(model, f'layer{i}') for mod in layer.modules(): if isinstance(mod, _BatchNorm): assert mod.training is False for param in layer.parameters(): assert param.requires_grad is False # Test ResNet18 forward model = ResNet(18) model.init_weights() model.train() imgs = torch.randn(1, 3, 224, 224) feat = model(imgs) assert len(feat) == 4 assert feat[0].shape == torch.Size([1, 64, 56, 56]) assert feat[1].shape == torch.Size([1, 128, 28, 28]) assert feat[2].shape == torch.Size([1, 256, 14, 14]) assert feat[3].shape == torch.Size([1, 512, 7, 7]) # Test ResNet18 with checkpoint forward model = ResNet(18, with_cp=True) for m in model.modules(): if is_block(m): assert m.with_cp # Test ResNet50 with BatchNorm forward model = ResNet(50) for m in model.modules(): if is_norm(m): assert isinstance(m, _BatchNorm) model.init_weights() model.train() imgs = torch.randn(1, 3, 224, 224) feat = model(imgs) assert len(feat) == 4 assert feat[0].shape == torch.Size([1, 256, 56, 56]) assert feat[1].shape == torch.Size([1, 512, 28, 28]) assert feat[2].shape == torch.Size([1, 1024, 14, 14]) assert feat[3].shape == torch.Size([1, 2048, 7, 7]) # Test ResNet50 with layers 1, 2, 3 out forward model = ResNet(50, out_indices=(0, 1, 2)) model.init_weights() model.train() imgs = torch.randn(1, 3, 224, 224) feat = model(imgs) assert len(feat) == 3 assert feat[0].shape == torch.Size([1, 256, 56, 56]) assert feat[1].shape == torch.Size([1, 512, 28, 28]) assert feat[2].shape == torch.Size([1, 1024, 14, 14]) # Test ResNet50 with checkpoint forward model = ResNet(50, with_cp=True) for m in model.modules(): if is_block(m): assert m.with_cp model.init_weights() model.train() imgs = torch.randn(1, 3, 224, 224) feat = model(imgs) assert len(feat) == 4 assert feat[0].shape == torch.Size([1, 256, 56, 56]) assert feat[1].shape == torch.Size([1, 512, 28, 28]) assert feat[2].shape == torch.Size([1, 1024, 14, 14]) assert feat[3].shape == torch.Size([1, 2048, 7, 7]) # Test ResNet50 with GroupNorm forward model = ResNet( 50, norm_cfg=dict(type='GN', num_groups=32, requires_grad=True)) for m in model.modules(): if is_norm(m): assert isinstance(m, GroupNorm) model.init_weights() model.train() imgs = torch.randn(1, 3, 224, 224) feat = model(imgs) assert len(feat) == 4 assert feat[0].shape == torch.Size([1, 256, 56, 56]) assert feat[1].shape == torch.Size([1, 512, 28, 28]) assert feat[2].shape == torch.Size([1, 1024, 14, 14]) assert feat[3].shape == torch.Size([1, 2048, 7, 7]) # Test ResNet50 with 1 GeneralizedAttention after conv2, 1 NonLocal2D # after conv2, 1 ContextBlock after conv3 in layers 2, 3, 4 plugins = [ dict( cfg=dict( type='GeneralizedAttention', spatial_range=-1, num_heads=8, attention_type='0010', kv_stride=2), stages=(False, True, True, True), position='after_conv2'), dict(cfg=dict(type='NonLocal2d'), position='after_conv2'), dict( cfg=dict(type='ContextBlock', ratio=1. / 16), stages=(False, True, True, False), position='after_conv3') ] model = ResNet(50, plugins=plugins) for m in model.layer1.modules(): if is_block(m): assert not hasattr(m, 'context_block') assert not hasattr(m, 'gen_attention_block') assert m.nonlocal_block.in_channels == 64 for m in model.layer2.modules(): if is_block(m): assert m.nonlocal_block.in_channels == 128 assert m.gen_attention_block.in_channels == 128 assert m.context_block.in_channels == 512 for m in model.layer3.modules(): if is_block(m): assert m.nonlocal_block.in_channels == 256 assert m.gen_attention_block.in_channels == 256 assert m.context_block.in_channels == 1024 for m in model.layer4.modules(): if is_block(m): assert m.nonlocal_block.in_channels == 512 assert m.gen_attention_block.in_channels == 512 assert not hasattr(m, 'context_block') model.init_weights() model.train() imgs = torch.randn(1, 3, 224, 224) feat = model(imgs) assert len(feat) == 4 assert feat[0].shape == torch.Size([1, 256, 56, 56]) assert feat[1].shape == torch.Size([1, 512, 28, 28]) assert feat[2].shape == torch.Size([1, 1024, 14, 14]) assert feat[3].shape == torch.Size([1, 2048, 7, 7]) # Test ResNet50 with 1 ContextBlock after conv2, 1 ContextBlock after # conv3 in layers 2, 3, 4 plugins = [ dict( cfg=dict(type='ContextBlock', ratio=1. / 16, postfix=1), stages=(False, True, True, False), position='after_conv3'), dict( cfg=dict(type='ContextBlock', ratio=1. / 16, postfix=2), stages=(False, True, True, False), position='after_conv3') ] model = ResNet(50, plugins=plugins) for m in model.layer1.modules(): if is_block(m): assert not hasattr(m, 'context_block') assert not hasattr(m, 'context_block1') assert not hasattr(m, 'context_block2') for m in model.layer2.modules(): if is_block(m): assert not hasattr(m, 'context_block') assert m.context_block1.in_channels == 512 assert m.context_block2.in_channels == 512 for m in model.layer3.modules(): if is_block(m): assert not hasattr(m, 'context_block') assert m.context_block1.in_channels == 1024 assert m.context_block2.in_channels == 1024 for m in model.layer4.modules(): if is_block(m): assert not hasattr(m, 'context_block') assert not hasattr(m, 'context_block1') assert not hasattr(m, 'context_block2') model.init_weights() model.train() imgs = torch.randn(1, 3, 224, 224) feat = model(imgs) assert len(feat) == 4 assert feat[0].shape == torch.Size([1, 256, 56, 56]) assert feat[1].shape == torch.Size([1, 512, 28, 28]) assert feat[2].shape == torch.Size([1, 1024, 14, 14]) assert feat[3].shape == torch.Size([1, 2048, 7, 7]) # Test ResNet50 zero initialization of residual model = ResNet(50, zero_init_residual=True) model.init_weights() for m in model.modules(): if isinstance(m, Bottleneck): assert all_zeros(m.norm3) elif isinstance(m, BasicBlock): assert all_zeros(m.norm2) model.train() imgs = torch.randn(1, 3, 224, 224) feat = model(imgs) assert len(feat) == 4 assert feat[0].shape == torch.Size([1, 256, 56, 56]) assert feat[1].shape == torch.Size([1, 512, 28, 28]) assert feat[2].shape == torch.Size([1, 1024, 14, 14]) assert feat[3].shape == torch.Size([1, 2048, 7, 7]) # Test ResNetV1d forward model = ResNetV1d(depth=50) model.init_weights() model.train() imgs = torch.randn(1, 3, 224, 224) feat = model(imgs) assert len(feat) == 4 assert feat[0].shape == torch.Size([1, 256, 56, 56]) assert feat[1].shape == torch.Size([1, 512, 28, 28]) assert feat[2].shape == torch.Size([1, 1024, 14, 14]) assert feat[3].shape == torch.Size([1, 2048, 7, 7]) imgs = torch.randn(1, 3, 224, 224) feat = model(imgs) assert len(feat) == 4 assert feat[0].shape == torch.Size([1, 256, 56, 56]) assert feat[1].shape == torch.Size([1, 512, 28, 28]) assert feat[2].shape == torch.Size([1, 1024, 14, 14]) assert feat[3].shape == torch.Size([1, 2048, 7, 7]) imgs = torch.randn(1, 3, 224, 224) feat = model(imgs) assert len(feat) == 4 assert feat[0].shape == torch.Size([1, 256, 56, 56]) assert feat[1].shape == torch.Size([1, 512, 28, 28]) assert feat[2].shape == torch.Size([1, 1024, 14, 14]) assert feat[3].shape == torch.Size([1, 2048, 7, 7]) def test_renext_bottleneck(): with pytest.raises(AssertionError): # Style must be in ['pytorch', 'caffe'] BottleneckX(64, 64, groups=32, base_width=4, style='tensorflow') # Test ResNeXt Bottleneck structure block = BottleneckX( 64, 64, groups=32, base_width=4, stride=2, style='pytorch') assert block.conv2.stride == (2, 2) assert block.conv2.groups == 32 assert block.conv2.out_channels == 128 # Test ResNeXt Bottleneck with DCN dcn = dict(type='DCN', deform_groups=1, fallback_on_stride=False) with pytest.raises(AssertionError): # conv_cfg must be None if dcn is not None BottleneckX( 64, 64, groups=32, base_width=4, dcn=dcn, conv_cfg=dict(type='Conv')) BottleneckX(64, 64, dcn=dcn) # Test ResNeXt Bottleneck forward block = BottleneckX(64, 16, groups=32, base_width=4) x = torch.randn(1, 64, 56, 56) x_out = block(x) assert x_out.shape == torch.Size([1, 64, 56, 56]) def test_resnext_backbone(): with pytest.raises(KeyError): # ResNeXt depth should be in [50, 101, 152] ResNeXt(depth=18) # Test ResNeXt with group 32, base_width 4 model = ResNeXt(depth=50, groups=32, base_width=4) for m in model.modules(): if is_block(m): assert m.conv2.groups == 32 model.init_weights() model.train() imgs = torch.randn(1, 3, 224, 224) feat = model(imgs) assert len(feat) == 4 assert feat[0].shape == torch.Size([1, 256, 56, 56]) assert feat[1].shape == torch.Size([1, 512, 28, 28]) assert feat[2].shape == torch.Size([1, 1024, 14, 14]) assert feat[3].shape == torch.Size([1, 2048, 7, 7]) regnet_test_data = [ ('regnetx_400mf', dict(w0=24, wa=24.48, wm=2.54, group_w=16, depth=22, bot_mul=1.0), [32, 64, 160, 384]), ('regnetx_800mf', dict(w0=56, wa=35.73, wm=2.28, group_w=16, depth=16, bot_mul=1.0), [64, 128, 288, 672]), ('regnetx_1.6gf', dict(w0=80, wa=34.01, wm=2.25, group_w=24, depth=18, bot_mul=1.0), [72, 168, 408, 912]), ('regnetx_3.2gf', dict(w0=88, wa=26.31, wm=2.25, group_w=48, depth=25, bot_mul=1.0), [96, 192, 432, 1008]), ('regnetx_4.0gf', dict(w0=96, wa=38.65, wm=2.43, group_w=40, depth=23, bot_mul=1.0), [80, 240, 560, 1360]), ('regnetx_6.4gf', dict(w0=184, wa=60.83, wm=2.07, group_w=56, depth=17, bot_mul=1.0), [168, 392, 784, 1624]), ('regnetx_8.0gf', dict(w0=80, wa=49.56, wm=2.88, group_w=120, depth=23, bot_mul=1.0), [80, 240, 720, 1920]), ('regnetx_12gf', dict(w0=168, wa=73.36, wm=2.37, group_w=112, depth=19, bot_mul=1.0), [224, 448, 896, 2240]), ] @pytest.mark.parametrize('arch_name,arch,out_channels', regnet_test_data) def test_regnet_backbone(arch_name, arch, out_channels): with pytest.raises(AssertionError): # ResNeXt depth should be in [50, 101, 152] RegNet(arch_name + '233') # Test RegNet with arch_name model = RegNet(arch_name) model.init_weights() model.train() imgs = torch.randn(1, 3, 224, 224) feat = model(imgs) assert len(feat) == 4 assert feat[0].shape == torch.Size([1, out_channels[0], 56, 56]) assert feat[1].shape == torch.Size([1, out_channels[1], 28, 28]) assert feat[2].shape == torch.Size([1, out_channels[2], 14, 14]) assert feat[3].shape == torch.Size([1, out_channels[3], 7, 7]) # Test RegNet with arch model = RegNet(arch) assert feat[0].shape == torch.Size([1, out_channels[0], 56, 56]) assert feat[1].shape == torch.Size([1, out_channels[1], 28, 28]) assert feat[2].shape == torch.Size([1, out_channels[2], 14, 14]) assert feat[3].shape == torch.Size([1, out_channels[3], 7, 7]) def test_res2net_bottle2neck(): with pytest.raises(AssertionError): # Style must be in ['pytorch', 'caffe'] Bottle2neck(64, 64, base_width=26, scales=4, style='tensorflow') with pytest.raises(AssertionError): # Scale must be larger than 1 Bottle2neck(64, 64, base_width=26, scales=1, style='pytorch') # Test Res2Net Bottle2neck structure block = Bottle2neck( 64, 64, base_width=26, stride=2, scales=4, style='pytorch') assert block.scales == 4 # Test Res2Net Bottle2neck with DCN dcn = dict(type='DCN', deform_groups=1, fallback_on_stride=False) with pytest.raises(AssertionError): # conv_cfg must be None if dcn is not None Bottle2neck( 64, 64, base_width=26, scales=4, dcn=dcn, conv_cfg=dict(type='Conv')) Bottle2neck(64, 64, dcn=dcn) # Test Res2Net Bottle2neck forward block = Bottle2neck(64, 16, base_width=26, scales=4) x = torch.randn(1, 64, 56, 56) x_out = block(x) assert x_out.shape == torch.Size([1, 64, 56, 56]) def test_res2net_backbone(): with pytest.raises(KeyError): # Res2Net depth should be in [50, 101, 152] Res2Net(depth=18) # Test Res2Net with scales 4, base_width 26 model = Res2Net(depth=50, scales=4, base_width=26) for m in model.modules(): if is_block(m): assert m.scales == 4 model.init_weights() model.train() imgs = torch.randn(1, 3, 224, 224) feat = model(imgs) assert len(feat) == 4 assert feat[0].shape == torch.Size([1, 256, 56, 56]) assert feat[1].shape == torch.Size([1, 512, 28, 28]) assert feat[2].shape == torch.Size([1, 1024, 14, 14]) assert feat[3].shape == torch.Size([1, 2048, 7, 7]) def test_hourglass_backbone(): with pytest.raises(AssertionError): # HourglassNet's num_stacks should larger than 0 HourglassNet(num_stacks=0) with pytest.raises(AssertionError): # len(stage_channels) should equal len(stage_blocks) HourglassNet( stage_channels=[256, 256, 384, 384, 384], stage_blocks=[2, 2, 2, 2, 2, 4]) with pytest.raises(AssertionError): # len(stage_channels) should lagrer than downsample_times HourglassNet( downsample_times=5, stage_channels=[256, 256, 384, 384, 384], stage_blocks=[2, 2, 2, 2, 2]) # Test HourglassNet-52 model = HourglassNet(num_stacks=1) model.init_weights() model.train() imgs = torch.randn(1, 3, 511, 511) feat = model(imgs) assert len(feat) == 1 assert feat[0].shape == torch.Size([1, 256, 128, 128]) # Test HourglassNet-104 model = HourglassNet(num_stacks=2) model.init_weights() model.train() imgs = torch.randn(1, 3, 511, 511) feat = model(imgs) assert len(feat) == 2 assert feat[0].shape == torch.Size([1, 256, 128, 128]) assert feat[1].shape == torch.Size([1, 256, 128, 128])
29,683
33.637106
79
py
GFocalV2
GFocalV2-master/tests/test_models/test_necks.py
import pytest import torch from torch.nn.modules.batchnorm import _BatchNorm from mmdet.models.necks import FPN, ChannelMapper def test_fpn(): """Tests fpn.""" s = 64 in_channels = [8, 16, 32, 64] feat_sizes = [s // 2**i for i in range(4)] # [64, 32, 16, 8] out_channels = 8 # `num_outs` is not equal to len(in_channels) - start_level with pytest.raises(AssertionError): FPN(in_channels=in_channels, out_channels=out_channels, start_level=1, num_outs=2) # `end_level` is larger than len(in_channels) - 1 with pytest.raises(AssertionError): FPN(in_channels=in_channels, out_channels=out_channels, start_level=1, end_level=4, num_outs=2) # `num_outs` is not equal to end_level - start_level with pytest.raises(AssertionError): FPN(in_channels=in_channels, out_channels=out_channels, start_level=1, end_level=3, num_outs=1) # Invalid `add_extra_convs` option with pytest.raises(AssertionError): FPN(in_channels=in_channels, out_channels=out_channels, start_level=1, add_extra_convs='on_xxx', num_outs=5) fpn_model = FPN( in_channels=in_channels, out_channels=out_channels, start_level=1, add_extra_convs=True, num_outs=5) # FPN expects a multiple levels of features per image feats = [ torch.rand(1, in_channels[i], feat_sizes[i], feat_sizes[i]) for i in range(len(in_channels)) ] outs = fpn_model(feats) assert fpn_model.add_extra_convs == 'on_input' assert len(outs) == fpn_model.num_outs for i in range(fpn_model.num_outs): outs[i].shape[1] == out_channels outs[i].shape[2] == outs[i].shape[3] == s // (2**i) # Tests for fpn with no extra convs (pooling is used instead) fpn_model = FPN( in_channels=in_channels, out_channels=out_channels, start_level=1, add_extra_convs=False, num_outs=5) outs = fpn_model(feats) assert len(outs) == fpn_model.num_outs assert not fpn_model.add_extra_convs for i in range(fpn_model.num_outs): outs[i].shape[1] == out_channels outs[i].shape[2] == outs[i].shape[3] == s // (2**i) # Tests for fpn with lateral bns fpn_model = FPN( in_channels=in_channels, out_channels=out_channels, start_level=1, add_extra_convs=True, no_norm_on_lateral=False, norm_cfg=dict(type='BN', requires_grad=True), num_outs=5) outs = fpn_model(feats) assert len(outs) == fpn_model.num_outs assert fpn_model.add_extra_convs == 'on_input' for i in range(fpn_model.num_outs): outs[i].shape[1] == out_channels outs[i].shape[2] == outs[i].shape[3] == s // (2**i) bn_exist = False for m in fpn_model.modules(): if isinstance(m, _BatchNorm): bn_exist = True assert bn_exist # Bilinear upsample fpn_model = FPN( in_channels=in_channels, out_channels=out_channels, start_level=1, add_extra_convs=True, upsample_cfg=dict(mode='bilinear', align_corners=True), num_outs=5) fpn_model(feats) outs = fpn_model(feats) assert len(outs) == fpn_model.num_outs assert fpn_model.add_extra_convs == 'on_input' for i in range(fpn_model.num_outs): outs[i].shape[1] == out_channels outs[i].shape[2] == outs[i].shape[3] == s // (2**i) # Scale factor instead of fixed upsample size upsample fpn_model = FPN( in_channels=in_channels, out_channels=out_channels, start_level=1, add_extra_convs=True, upsample_cfg=dict(scale_factor=2), num_outs=5) outs = fpn_model(feats) assert len(outs) == fpn_model.num_outs for i in range(fpn_model.num_outs): outs[i].shape[1] == out_channels outs[i].shape[2] == outs[i].shape[3] == s // (2**i) # Extra convs source is 'inputs' fpn_model = FPN( in_channels=in_channels, out_channels=out_channels, add_extra_convs='on_input', start_level=1, num_outs=5) assert fpn_model.add_extra_convs == 'on_input' outs = fpn_model(feats) assert len(outs) == fpn_model.num_outs for i in range(fpn_model.num_outs): outs[i].shape[1] == out_channels outs[i].shape[2] == outs[i].shape[3] == s // (2**i) # Extra convs source is 'laterals' fpn_model = FPN( in_channels=in_channels, out_channels=out_channels, add_extra_convs='on_lateral', start_level=1, num_outs=5) assert fpn_model.add_extra_convs == 'on_lateral' outs = fpn_model(feats) assert len(outs) == fpn_model.num_outs for i in range(fpn_model.num_outs): outs[i].shape[1] == out_channels outs[i].shape[2] == outs[i].shape[3] == s // (2**i) # Extra convs source is 'outputs' fpn_model = FPN( in_channels=in_channels, out_channels=out_channels, add_extra_convs='on_output', start_level=1, num_outs=5) assert fpn_model.add_extra_convs == 'on_output' outs = fpn_model(feats) assert len(outs) == fpn_model.num_outs for i in range(fpn_model.num_outs): outs[i].shape[1] == out_channels outs[i].shape[2] == outs[i].shape[3] == s // (2**i) # extra_convs_on_inputs=False is equal to extra convs source is 'on_output' fpn_model = FPN( in_channels=in_channels, out_channels=out_channels, add_extra_convs=True, extra_convs_on_inputs=False, start_level=1, num_outs=5, ) assert fpn_model.add_extra_convs == 'on_output' outs = fpn_model(feats) assert len(outs) == fpn_model.num_outs for i in range(fpn_model.num_outs): outs[i].shape[1] == out_channels outs[i].shape[2] == outs[i].shape[3] == s // (2**i) # extra_convs_on_inputs=True is equal to extra convs source is 'on_input' fpn_model = FPN( in_channels=in_channels, out_channels=out_channels, add_extra_convs=True, extra_convs_on_inputs=True, start_level=1, num_outs=5, ) assert fpn_model.add_extra_convs == 'on_input' outs = fpn_model(feats) assert len(outs) == fpn_model.num_outs for i in range(fpn_model.num_outs): outs[i].shape[1] == out_channels outs[i].shape[2] == outs[i].shape[3] == s // (2**i) def test_channel_mapper(): """Tests ChannelMapper.""" s = 64 in_channels = [8, 16, 32, 64] feat_sizes = [s // 2**i for i in range(4)] # [64, 32, 16, 8] out_channels = 8 kernel_size = 3 feats = [ torch.rand(1, in_channels[i], feat_sizes[i], feat_sizes[i]) for i in range(len(in_channels)) ] # in_channels must be a list with pytest.raises(AssertionError): channel_mapper = ChannelMapper( in_channels=10, out_channels=out_channels, kernel_size=kernel_size) # the length of channel_mapper's inputs must be equal to the length of # in_channels with pytest.raises(AssertionError): channel_mapper = ChannelMapper( in_channels=in_channels[:-1], out_channels=out_channels, kernel_size=kernel_size) channel_mapper(feats) channel_mapper = ChannelMapper( in_channels=in_channels, out_channels=out_channels, kernel_size=kernel_size) outs = channel_mapper(feats) assert len(outs) == len(feats) for i in range(len(feats)): outs[i].shape[1] == out_channels outs[i].shape[2] == outs[i].shape[3] == s // (2**i)
7,781
31.560669
79
py
GFocalV2
GFocalV2-master/tests/test_models/test_heads.py
import mmcv import numpy as np import torch from mmdet.core import bbox2roi, build_assigner, build_sampler from mmdet.core.evaluation.bbox_overlaps import bbox_overlaps from mmdet.models.dense_heads import (AnchorHead, CornerHead, FCOSHead, FSAFHead, GuidedAnchorHead, PAAHead, SABLRetinaHead, VFNetHead, YOLACTHead, YOLACTProtonet, YOLACTSegmHead, paa_head) from mmdet.models.dense_heads.paa_head import levels_to_images from mmdet.models.roi_heads.bbox_heads import BBoxHead, SABLHead from mmdet.models.roi_heads.mask_heads import FCNMaskHead, MaskIoUHead def test_paa_head_loss(): """Tests paa head loss when truth is empty and non-empty.""" class mock_skm(object): def GaussianMixture(self, *args, **kwargs): return self def fit(self, loss): pass def predict(self, loss): components = np.zeros_like(loss, dtype=np.long) return components.reshape(-1) def score_samples(self, loss): scores = np.random.random(len(loss)) return scores paa_head.skm = mock_skm() s = 256 img_metas = [{ 'img_shape': (s, s, 3), 'scale_factor': 1, 'pad_shape': (s, s, 3) }] train_cfg = mmcv.Config( dict( assigner=dict( type='MaxIoUAssigner', pos_iou_thr=0.1, neg_iou_thr=0.1, min_pos_iou=0, ignore_iof_thr=-1), allowed_border=-1, pos_weight=-1, debug=False)) # since Focal Loss is not supported on CPU self = PAAHead( num_classes=4, in_channels=1, train_cfg=train_cfg, loss_cls=dict( type='CrossEntropyLoss', use_sigmoid=True, loss_weight=1.0), loss_bbox=dict(type='GIoULoss', loss_weight=1.3), loss_centerness=dict( type='CrossEntropyLoss', use_sigmoid=True, loss_weight=0.5)) feat = [ torch.rand(1, 1, s // feat_size, s // feat_size) for feat_size in [4, 8, 16, 32, 64] ] self.init_weights() cls_scores, bbox_preds, iou_preds = self(feat) # Test that empty ground truth encourages the network to predict background gt_bboxes = [torch.empty((0, 4))] gt_labels = [torch.LongTensor([])] gt_bboxes_ignore = None empty_gt_losses = self.loss(cls_scores, bbox_preds, iou_preds, gt_bboxes, gt_labels, img_metas, gt_bboxes_ignore) # When there is no truth, the cls loss should be nonzero but there should # be no box loss. empty_cls_loss = empty_gt_losses['loss_cls'] empty_box_loss = empty_gt_losses['loss_bbox'] empty_iou_loss = empty_gt_losses['loss_iou'] assert empty_cls_loss.item() > 0, 'cls loss should be non-zero' assert empty_box_loss.item() == 0, ( 'there should be no box loss when there are no true boxes') assert empty_iou_loss.item() == 0, ( 'there should be no box loss when there are no true boxes') # When truth is non-empty then both cls and box loss should be nonzero for # random inputs gt_bboxes = [ torch.Tensor([[23.6667, 23.8757, 238.6326, 151.8874]]), ] gt_labels = [torch.LongTensor([2])] one_gt_losses = self.loss(cls_scores, bbox_preds, iou_preds, gt_bboxes, gt_labels, img_metas, gt_bboxes_ignore) onegt_cls_loss = one_gt_losses['loss_cls'] onegt_box_loss = one_gt_losses['loss_bbox'] onegt_iou_loss = one_gt_losses['loss_iou'] assert onegt_cls_loss.item() > 0, 'cls loss should be non-zero' assert onegt_box_loss.item() > 0, 'box loss should be non-zero' assert onegt_iou_loss.item() > 0, 'box loss should be non-zero' n, c, h, w = 10, 4, 20, 20 mlvl_tensor = [torch.ones(n, c, h, w) for i in range(5)] results = levels_to_images(mlvl_tensor) assert len(results) == n assert results[0].size() == (h * w * 5, c) assert self.with_score_voting cls_scores = [torch.ones(4, 5, 5)] bbox_preds = [torch.ones(4, 5, 5)] iou_preds = [torch.ones(1, 5, 5)] mlvl_anchors = [torch.ones(5 * 5, 4)] img_shape = None scale_factor = [0.5, 0.5] cfg = mmcv.Config( dict( nms_pre=1000, min_bbox_size=0, score_thr=0.05, nms=dict(type='nms', iou_threshold=0.6), max_per_img=100)) rescale = False self._get_bboxes_single( cls_scores, bbox_preds, iou_preds, mlvl_anchors, img_shape, scale_factor, cfg, rescale=rescale) def test_fcos_head_loss(): """Tests fcos head loss when truth is empty and non-empty.""" s = 256 img_metas = [{ 'img_shape': (s, s, 3), 'scale_factor': 1, 'pad_shape': (s, s, 3) }] train_cfg = mmcv.Config( dict( assigner=dict( type='MaxIoUAssigner', pos_iou_thr=0.5, neg_iou_thr=0.4, min_pos_iou=0, ignore_iof_thr=-1), allowed_border=-1, pos_weight=-1, debug=False)) # since Focal Loss is not supported on CPU self = FCOSHead( num_classes=4, in_channels=1, train_cfg=train_cfg, loss_cls=dict( type='CrossEntropyLoss', use_sigmoid=True, loss_weight=1.0)) feat = [ torch.rand(1, 1, s // feat_size, s // feat_size) for feat_size in [4, 8, 16, 32, 64] ] cls_scores, bbox_preds, centerness = self.forward(feat) # Test that empty ground truth encourages the network to predict background gt_bboxes = [torch.empty((0, 4))] gt_labels = [torch.LongTensor([])] gt_bboxes_ignore = None empty_gt_losses = self.loss(cls_scores, bbox_preds, centerness, gt_bboxes, gt_labels, img_metas, gt_bboxes_ignore) # When there is no truth, the cls loss should be nonzero but there should # be no box loss. empty_cls_loss = empty_gt_losses['loss_cls'] empty_box_loss = empty_gt_losses['loss_bbox'] assert empty_cls_loss.item() > 0, 'cls loss should be non-zero' assert empty_box_loss.item() == 0, ( 'there should be no box loss when there are no true boxes') # When truth is non-empty then both cls and box loss should be nonzero for # random inputs gt_bboxes = [ torch.Tensor([[23.6667, 23.8757, 238.6326, 151.8874]]), ] gt_labels = [torch.LongTensor([2])] one_gt_losses = self.loss(cls_scores, bbox_preds, centerness, gt_bboxes, gt_labels, img_metas, gt_bboxes_ignore) onegt_cls_loss = one_gt_losses['loss_cls'] onegt_box_loss = one_gt_losses['loss_bbox'] assert onegt_cls_loss.item() > 0, 'cls loss should be non-zero' assert onegt_box_loss.item() > 0, 'box loss should be non-zero' def test_vfnet_head_loss(): """Tests vfnet head loss when truth is empty and non-empty.""" s = 256 img_metas = [{ 'img_shape': (s, s, 3), 'scale_factor': 1, 'pad_shape': (s, s, 3) }] train_cfg = mmcv.Config( dict( assigner=dict(type='ATSSAssigner', topk=9), allowed_border=-1, pos_weight=-1, debug=False)) # since Focal Loss is not supported on CPU self = VFNetHead( num_classes=4, in_channels=1, train_cfg=train_cfg, loss_cls=dict(type='VarifocalLoss', use_sigmoid=True, loss_weight=1.0)) if torch.cuda.is_available(): self.cuda() feat = [ torch.rand(1, 1, s // feat_size, s // feat_size).cuda() for feat_size in [4, 8, 16, 32, 64] ] cls_scores, bbox_preds, bbox_preds_refine = self.forward(feat) # Test that empty ground truth encourages the network to predict # background gt_bboxes = [torch.empty((0, 4)).cuda()] gt_labels = [torch.LongTensor([]).cuda()] gt_bboxes_ignore = None empty_gt_losses = self.loss(cls_scores, bbox_preds, bbox_preds_refine, gt_bboxes, gt_labels, img_metas, gt_bboxes_ignore) # When there is no truth, the cls loss should be nonzero but there # should be no box loss. empty_cls_loss = empty_gt_losses['loss_cls'] empty_box_loss = empty_gt_losses['loss_bbox'] assert empty_cls_loss.item() > 0, 'cls loss should be non-zero' assert empty_box_loss.item() == 0, ( 'there should be no box loss when there are no true boxes') # When truth is non-empty then both cls and box loss should be nonzero # for random inputs gt_bboxes = [ torch.Tensor([[23.6667, 23.8757, 238.6326, 151.8874]]).cuda(), ] gt_labels = [torch.LongTensor([2]).cuda()] one_gt_losses = self.loss(cls_scores, bbox_preds, bbox_preds_refine, gt_bboxes, gt_labels, img_metas, gt_bboxes_ignore) onegt_cls_loss = one_gt_losses['loss_cls'] onegt_box_loss = one_gt_losses['loss_bbox'] assert onegt_cls_loss.item() > 0, 'cls loss should be non-zero' assert onegt_box_loss.item() > 0, 'box loss should be non-zero' def test_anchor_head_loss(): """Tests anchor head loss when truth is empty and non-empty.""" s = 256 img_metas = [{ 'img_shape': (s, s, 3), 'scale_factor': 1, 'pad_shape': (s, s, 3) }] cfg = mmcv.Config( dict( assigner=dict( type='MaxIoUAssigner', pos_iou_thr=0.7, neg_iou_thr=0.3, min_pos_iou=0.3, match_low_quality=True, ignore_iof_thr=-1), sampler=dict( type='RandomSampler', num=256, pos_fraction=0.5, neg_pos_ub=-1, add_gt_as_proposals=False), allowed_border=0, pos_weight=-1, debug=False)) self = AnchorHead(num_classes=4, in_channels=1, train_cfg=cfg) # Anchor head expects a multiple levels of features per image feat = [ torch.rand(1, 1, s // (2**(i + 2)), s // (2**(i + 2))) for i in range(len(self.anchor_generator.strides)) ] cls_scores, bbox_preds = self.forward(feat) # Test that empty ground truth encourages the network to predict background gt_bboxes = [torch.empty((0, 4))] gt_labels = [torch.LongTensor([])] gt_bboxes_ignore = None empty_gt_losses = self.loss(cls_scores, bbox_preds, gt_bboxes, gt_labels, img_metas, gt_bboxes_ignore) # When there is no truth, the cls loss should be nonzero but there should # be no box loss. empty_cls_loss = sum(empty_gt_losses['loss_cls']) empty_box_loss = sum(empty_gt_losses['loss_bbox']) assert empty_cls_loss.item() > 0, 'cls loss should be non-zero' assert empty_box_loss.item() == 0, ( 'there should be no box loss when there are no true boxes') # When truth is non-empty then both cls and box loss should be nonzero for # random inputs gt_bboxes = [ torch.Tensor([[23.6667, 23.8757, 238.6326, 151.8874]]), ] gt_labels = [torch.LongTensor([2])] one_gt_losses = self.loss(cls_scores, bbox_preds, gt_bboxes, gt_labels, img_metas, gt_bboxes_ignore) onegt_cls_loss = sum(one_gt_losses['loss_cls']) onegt_box_loss = sum(one_gt_losses['loss_bbox']) assert onegt_cls_loss.item() > 0, 'cls loss should be non-zero' assert onegt_box_loss.item() > 0, 'box loss should be non-zero' def test_fsaf_head_loss(): """Tests anchor head loss when truth is empty and non-empty.""" s = 256 img_metas = [{ 'img_shape': (s, s, 3), 'scale_factor': 1, 'pad_shape': (s, s, 3) }] cfg = dict( reg_decoded_bbox=True, anchor_generator=dict( type='AnchorGenerator', octave_base_scale=1, scales_per_octave=1, ratios=[1.0], strides=[8, 16, 32, 64, 128]), bbox_coder=dict(type='TBLRBBoxCoder', normalizer=4.0), loss_cls=dict( type='FocalLoss', use_sigmoid=True, gamma=2.0, alpha=0.25, loss_weight=1.0, reduction='none'), loss_bbox=dict( type='IoULoss', eps=1e-6, loss_weight=1.0, reduction='none')) train_cfg = mmcv.Config( dict( assigner=dict( type='CenterRegionAssigner', pos_scale=0.2, neg_scale=0.2, min_pos_iof=0.01), allowed_border=-1, pos_weight=-1, debug=False)) head = FSAFHead(num_classes=4, in_channels=1, train_cfg=train_cfg, **cfg) if torch.cuda.is_available(): head.cuda() # FSAF head expects a multiple levels of features per image feat = [ torch.rand(1, 1, s // (2**(i + 2)), s // (2**(i + 2))).cuda() for i in range(len(head.anchor_generator.strides)) ] cls_scores, bbox_preds = head.forward(feat) gt_bboxes_ignore = None # When truth is non-empty then both cls and box loss should be nonzero # for random inputs gt_bboxes = [ torch.Tensor([[23.6667, 23.8757, 238.6326, 151.8874]]).cuda(), ] gt_labels = [torch.LongTensor([2]).cuda()] one_gt_losses = head.loss(cls_scores, bbox_preds, gt_bboxes, gt_labels, img_metas, gt_bboxes_ignore) onegt_cls_loss = sum(one_gt_losses['loss_cls']) onegt_box_loss = sum(one_gt_losses['loss_bbox']) assert onegt_cls_loss.item() > 0, 'cls loss should be non-zero' assert onegt_box_loss.item() > 0, 'box loss should be non-zero' # Test that empty ground truth encourages the network to predict bkg gt_bboxes = [torch.empty((0, 4)).cuda()] gt_labels = [torch.LongTensor([]).cuda()] empty_gt_losses = head.loss(cls_scores, bbox_preds, gt_bboxes, gt_labels, img_metas, gt_bboxes_ignore) # When there is no truth, the cls loss should be nonzero but there # should be no box loss. empty_cls_loss = sum(empty_gt_losses['loss_cls']) empty_box_loss = sum(empty_gt_losses['loss_bbox']) assert empty_cls_loss.item() > 0, 'cls loss should be non-zero' assert empty_box_loss.item() == 0, ( 'there should be no box loss when there are no true boxes') def test_ga_anchor_head_loss(): """Tests anchor head loss when truth is empty and non-empty.""" s = 256 img_metas = [{ 'img_shape': (s, s, 3), 'scale_factor': 1, 'pad_shape': (s, s, 3) }] cfg = mmcv.Config( dict( assigner=dict( type='MaxIoUAssigner', pos_iou_thr=0.7, neg_iou_thr=0.3, min_pos_iou=0.3, match_low_quality=True, ignore_iof_thr=-1), sampler=dict( type='RandomSampler', num=256, pos_fraction=0.5, neg_pos_ub=-1, add_gt_as_proposals=False), ga_assigner=dict( type='ApproxMaxIoUAssigner', pos_iou_thr=0.7, neg_iou_thr=0.3, min_pos_iou=0.3, ignore_iof_thr=-1), ga_sampler=dict( type='RandomSampler', num=256, pos_fraction=0.5, neg_pos_ub=-1, add_gt_as_proposals=False), allowed_border=-1, center_ratio=0.2, ignore_ratio=0.5, pos_weight=-1, debug=False)) head = GuidedAnchorHead(num_classes=4, in_channels=4, train_cfg=cfg) # Anchor head expects a multiple levels of features per image if torch.cuda.is_available(): head.cuda() feat = [ torch.rand(1, 4, s // (2**(i + 2)), s // (2**(i + 2))).cuda() for i in range(len(head.approx_anchor_generator.base_anchors)) ] cls_scores, bbox_preds, shape_preds, loc_preds = head.forward(feat) # Test that empty ground truth encourages the network to predict # background gt_bboxes = [torch.empty((0, 4)).cuda()] gt_labels = [torch.LongTensor([]).cuda()] gt_bboxes_ignore = None empty_gt_losses = head.loss(cls_scores, bbox_preds, shape_preds, loc_preds, gt_bboxes, gt_labels, img_metas, gt_bboxes_ignore) # When there is no truth, the cls loss should be nonzero but there # should be no box loss. empty_cls_loss = sum(empty_gt_losses['loss_cls']) empty_box_loss = sum(empty_gt_losses['loss_bbox']) assert empty_cls_loss.item() > 0, 'cls loss should be non-zero' assert empty_box_loss.item() == 0, ( 'there should be no box loss when there are no true boxes') # When truth is non-empty then both cls and box loss should be nonzero # for random inputs gt_bboxes = [ torch.Tensor([[23.6667, 23.8757, 238.6326, 151.8874]]).cuda(), ] gt_labels = [torch.LongTensor([2]).cuda()] one_gt_losses = head.loss(cls_scores, bbox_preds, shape_preds, loc_preds, gt_bboxes, gt_labels, img_metas, gt_bboxes_ignore) onegt_cls_loss = sum(one_gt_losses['loss_cls']) onegt_box_loss = sum(one_gt_losses['loss_bbox']) assert onegt_cls_loss.item() > 0, 'cls loss should be non-zero' assert onegt_box_loss.item() > 0, 'box loss should be non-zero' def test_bbox_head_loss(): """Tests bbox head loss when truth is empty and non-empty.""" self = BBoxHead(in_channels=8, roi_feat_size=3) # Dummy proposals proposal_list = [ torch.Tensor([[23.6667, 23.8757, 228.6326, 153.8874]]), ] target_cfg = mmcv.Config(dict(pos_weight=1)) # Test bbox loss when truth is empty gt_bboxes = [torch.empty((0, 4))] gt_labels = [torch.LongTensor([])] sampling_results = _dummy_bbox_sampling(proposal_list, gt_bboxes, gt_labels) bbox_targets = self.get_targets(sampling_results, gt_bboxes, gt_labels, target_cfg) labels, label_weights, bbox_targets, bbox_weights = bbox_targets # Create dummy features "extracted" for each sampled bbox num_sampled = sum(len(res.bboxes) for res in sampling_results) rois = bbox2roi([res.bboxes for res in sampling_results]) dummy_feats = torch.rand(num_sampled, 8 * 3 * 3) cls_scores, bbox_preds = self.forward(dummy_feats) losses = self.loss(cls_scores, bbox_preds, rois, labels, label_weights, bbox_targets, bbox_weights) assert losses.get('loss_cls', 0) > 0, 'cls-loss should be non-zero' assert losses.get('loss_bbox', 0) == 0, 'empty gt loss should be zero' # Test bbox loss when truth is non-empty gt_bboxes = [ torch.Tensor([[23.6667, 23.8757, 238.6326, 151.8874]]), ] gt_labels = [torch.LongTensor([2])] sampling_results = _dummy_bbox_sampling(proposal_list, gt_bboxes, gt_labels) rois = bbox2roi([res.bboxes for res in sampling_results]) bbox_targets = self.get_targets(sampling_results, gt_bboxes, gt_labels, target_cfg) labels, label_weights, bbox_targets, bbox_weights = bbox_targets # Create dummy features "extracted" for each sampled bbox num_sampled = sum(len(res.bboxes) for res in sampling_results) dummy_feats = torch.rand(num_sampled, 8 * 3 * 3) cls_scores, bbox_preds = self.forward(dummy_feats) losses = self.loss(cls_scores, bbox_preds, rois, labels, label_weights, bbox_targets, bbox_weights) assert losses.get('loss_cls', 0) > 0, 'cls-loss should be non-zero' assert losses.get('loss_bbox', 0) > 0, 'box-loss should be non-zero' def test_sabl_bbox_head_loss(): """Tests bbox head loss when truth is empty and non-empty.""" self = SABLHead( num_classes=4, cls_in_channels=3, reg_in_channels=3, cls_out_channels=3, reg_offset_out_channels=3, reg_cls_out_channels=3, roi_feat_size=7) # Dummy proposals proposal_list = [ torch.Tensor([[23.6667, 23.8757, 228.6326, 153.8874]]), ] target_cfg = mmcv.Config(dict(pos_weight=1)) # Test bbox loss when truth is empty gt_bboxes = [torch.empty((0, 4))] gt_labels = [torch.LongTensor([])] sampling_results = _dummy_bbox_sampling(proposal_list, gt_bboxes, gt_labels) bbox_targets = self.get_targets(sampling_results, gt_bboxes, gt_labels, target_cfg) labels, label_weights, bbox_targets, bbox_weights = bbox_targets # Create dummy features "extracted" for each sampled bbox num_sampled = sum(len(res.bboxes) for res in sampling_results) rois = bbox2roi([res.bboxes for res in sampling_results]) dummy_feats = torch.rand(num_sampled, 3, 7, 7) cls_scores, bbox_preds = self.forward(dummy_feats) losses = self.loss(cls_scores, bbox_preds, rois, labels, label_weights, bbox_targets, bbox_weights) assert losses.get('loss_cls', 0) > 0, 'cls-loss should be non-zero' assert losses.get('loss_bbox_cls', 0) == 0, 'empty gt bbox-cls-loss should be zero' assert losses.get('loss_bbox_reg', 0) == 0, 'empty gt bbox-reg-loss should be zero' # Test bbox loss when truth is non-empty gt_bboxes = [ torch.Tensor([[23.6667, 23.8757, 238.6326, 151.8874]]), ] gt_labels = [torch.LongTensor([2])] sampling_results = _dummy_bbox_sampling(proposal_list, gt_bboxes, gt_labels) rois = bbox2roi([res.bboxes for res in sampling_results]) bbox_targets = self.get_targets(sampling_results, gt_bboxes, gt_labels, target_cfg) labels, label_weights, bbox_targets, bbox_weights = bbox_targets # Create dummy features "extracted" for each sampled bbox num_sampled = sum(len(res.bboxes) for res in sampling_results) dummy_feats = torch.rand(num_sampled, 3, 7, 7) cls_scores, bbox_preds = self.forward(dummy_feats) losses = self.loss(cls_scores, bbox_preds, rois, labels, label_weights, bbox_targets, bbox_weights) assert losses.get('loss_bbox_cls', 0) > 0, 'empty gt bbox-cls-loss should be zero' assert losses.get('loss_bbox_reg', 0) > 0, 'empty gt bbox-reg-loss should be zero' def test_sabl_retina_head_loss(): """Tests anchor head loss when truth is empty and non-empty.""" s = 256 img_metas = [{ 'img_shape': (s, s, 3), 'scale_factor': 1, 'pad_shape': (s, s, 3) }] cfg = mmcv.Config( dict( assigner=dict( type='ApproxMaxIoUAssigner', pos_iou_thr=0.5, neg_iou_thr=0.4, min_pos_iou=0.0, ignore_iof_thr=-1), allowed_border=-1, pos_weight=-1, debug=False)) head = SABLRetinaHead( num_classes=4, in_channels=3, feat_channels=10, loss_cls=dict( type='CrossEntropyLoss', use_sigmoid=True, loss_weight=1.0), train_cfg=cfg) if torch.cuda.is_available(): head.cuda() # Anchor head expects a multiple levels of features per image feat = [ torch.rand(1, 3, s // (2**(i + 2)), s // (2**(i + 2))).cuda() for i in range(len(head.approx_anchor_generator.base_anchors)) ] cls_scores, bbox_preds = head.forward(feat) # Test that empty ground truth encourages the network # to predict background gt_bboxes = [torch.empty((0, 4)).cuda()] gt_labels = [torch.LongTensor([]).cuda()] gt_bboxes_ignore = None empty_gt_losses = head.loss(cls_scores, bbox_preds, gt_bboxes, gt_labels, img_metas, gt_bboxes_ignore) # When there is no truth, the cls loss should be nonzero but there # should be no box loss. empty_cls_loss = sum(empty_gt_losses['loss_cls']) empty_box_cls_loss = sum(empty_gt_losses['loss_bbox_cls']) empty_box_reg_loss = sum(empty_gt_losses['loss_bbox_reg']) assert empty_cls_loss.item() > 0, 'cls loss should be non-zero' assert empty_box_cls_loss.item() == 0, ( 'there should be no box cls loss when there are no true boxes') assert empty_box_reg_loss.item() == 0, ( 'there should be no box reg loss when there are no true boxes') # When truth is non-empty then both cls and box loss should # be nonzero for random inputs gt_bboxes = [ torch.Tensor([[23.6667, 23.8757, 238.6326, 151.8874]]).cuda(), ] gt_labels = [torch.LongTensor([2]).cuda()] one_gt_losses = head.loss(cls_scores, bbox_preds, gt_bboxes, gt_labels, img_metas, gt_bboxes_ignore) onegt_cls_loss = sum(one_gt_losses['loss_cls']) onegt_box_cls_loss = sum(one_gt_losses['loss_bbox_cls']) onegt_box_reg_loss = sum(one_gt_losses['loss_bbox_reg']) assert onegt_cls_loss.item() > 0, 'cls loss should be non-zero' assert onegt_box_cls_loss.item() > 0, 'box loss cls should be non-zero' assert onegt_box_reg_loss.item() > 0, 'box loss reg should be non-zero' def test_refine_boxes(): """Mirrors the doctest in ``mmdet.models.bbox_heads.bbox_head.BBoxHead.refine_boxes`` but checks for multiple values of n_roi / n_img.""" self = BBoxHead(reg_class_agnostic=True) test_settings = [ # Corner case: less rois than images { 'n_roi': 2, 'n_img': 4, 'rng': 34285940 }, # Corner case: no images { 'n_roi': 0, 'n_img': 0, 'rng': 52925222 }, # Corner cases: few images / rois { 'n_roi': 1, 'n_img': 1, 'rng': 1200281 }, { 'n_roi': 2, 'n_img': 1, 'rng': 1200282 }, { 'n_roi': 2, 'n_img': 2, 'rng': 1200283 }, { 'n_roi': 1, 'n_img': 2, 'rng': 1200284 }, # Corner case: no rois few images { 'n_roi': 0, 'n_img': 1, 'rng': 23955860 }, { 'n_roi': 0, 'n_img': 2, 'rng': 25830516 }, # Corner case: no rois many images { 'n_roi': 0, 'n_img': 10, 'rng': 671346 }, { 'n_roi': 0, 'n_img': 20, 'rng': 699807 }, # Corner case: cal_similarity num rois and images { 'n_roi': 20, 'n_img': 20, 'rng': 1200238 }, { 'n_roi': 10, 'n_img': 20, 'rng': 1200238 }, { 'n_roi': 5, 'n_img': 5, 'rng': 1200238 }, # ---------------------------------- # Common case: more rois than images { 'n_roi': 100, 'n_img': 1, 'rng': 337156 }, { 'n_roi': 150, 'n_img': 2, 'rng': 275898 }, { 'n_roi': 500, 'n_img': 5, 'rng': 4903221 }, ] for demokw in test_settings: try: n_roi = demokw['n_roi'] n_img = demokw['n_img'] rng = demokw['rng'] print(f'Test refine_boxes case: {demokw!r}') tup = _demodata_refine_boxes(n_roi, n_img, rng=rng) rois, labels, bbox_preds, pos_is_gts, img_metas = tup bboxes_list = self.refine_bboxes(rois, labels, bbox_preds, pos_is_gts, img_metas) assert len(bboxes_list) == n_img assert sum(map(len, bboxes_list)) <= n_roi assert all(b.shape[1] == 4 for b in bboxes_list) except Exception: print(f'Test failed with demokw={demokw!r}') raise def _demodata_refine_boxes(n_roi, n_img, rng=0): """Create random test data for the ``mmdet.models.bbox_heads.bbox_head.BBoxHead.refine_boxes`` method.""" import numpy as np from mmdet.core.bbox.demodata import random_boxes from mmdet.core.bbox.demodata import ensure_rng try: import kwarray except ImportError: import pytest pytest.skip('kwarray is required for this test') scale = 512 rng = ensure_rng(rng) img_metas = [{'img_shape': (scale, scale)} for _ in range(n_img)] # Create rois in the expected format roi_boxes = random_boxes(n_roi, scale=scale, rng=rng) if n_img == 0: assert n_roi == 0, 'cannot have any rois if there are no images' img_ids = torch.empty((0, ), dtype=torch.long) roi_boxes = torch.empty((0, 4), dtype=torch.float32) else: img_ids = rng.randint(0, n_img, (n_roi, )) img_ids = torch.from_numpy(img_ids) rois = torch.cat([img_ids[:, None].float(), roi_boxes], dim=1) # Create other args labels = rng.randint(0, 2, (n_roi, )) labels = torch.from_numpy(labels).long() bbox_preds = random_boxes(n_roi, scale=scale, rng=rng) # For each image, pretend random positive boxes are gts is_label_pos = (labels.numpy() > 0).astype(np.int) lbl_per_img = kwarray.group_items(is_label_pos, img_ids.numpy()) pos_per_img = [sum(lbl_per_img.get(gid, [])) for gid in range(n_img)] # randomly generate with numpy then sort with torch _pos_is_gts = [ rng.randint(0, 2, (npos, )).astype(np.uint8) for npos in pos_per_img ] pos_is_gts = [ torch.from_numpy(p).sort(descending=True)[0] for p in _pos_is_gts ] return rois, labels, bbox_preds, pos_is_gts, img_metas def test_mask_head_loss(): """Test mask head loss when mask target is empty.""" self = FCNMaskHead( num_convs=1, roi_feat_size=6, in_channels=8, conv_out_channels=8, num_classes=8) # Dummy proposals proposal_list = [ torch.Tensor([[23.6667, 23.8757, 228.6326, 153.8874]]), ] gt_bboxes = [ torch.Tensor([[23.6667, 23.8757, 238.6326, 151.8874]]), ] gt_labels = [torch.LongTensor([2])] sampling_results = _dummy_bbox_sampling(proposal_list, gt_bboxes, gt_labels) # create dummy mask import numpy as np from mmdet.core import BitmapMasks dummy_mask = np.random.randint(0, 2, (1, 160, 240), dtype=np.uint8) gt_masks = [BitmapMasks(dummy_mask, 160, 240)] # create dummy train_cfg train_cfg = mmcv.Config(dict(mask_size=12, mask_thr_binary=0.5)) # Create dummy features "extracted" for each sampled bbox num_sampled = sum(len(res.bboxes) for res in sampling_results) dummy_feats = torch.rand(num_sampled, 8, 6, 6) mask_pred = self.forward(dummy_feats) mask_targets = self.get_targets(sampling_results, gt_masks, train_cfg) pos_labels = torch.cat([res.pos_gt_labels for res in sampling_results]) loss_mask = self.loss(mask_pred, mask_targets, pos_labels) onegt_mask_loss = sum(loss_mask['loss_mask']) assert onegt_mask_loss.item() > 0, 'mask loss should be non-zero' # test mask_iou_head mask_iou_head = MaskIoUHead( num_convs=1, num_fcs=1, roi_feat_size=6, in_channels=8, conv_out_channels=8, fc_out_channels=8, num_classes=8) pos_mask_pred = mask_pred[range(mask_pred.size(0)), pos_labels] mask_iou_pred = mask_iou_head(dummy_feats, pos_mask_pred) pos_mask_iou_pred = mask_iou_pred[range(mask_iou_pred.size(0)), pos_labels] mask_iou_targets = mask_iou_head.get_targets(sampling_results, gt_masks, pos_mask_pred, mask_targets, train_cfg) loss_mask_iou = mask_iou_head.loss(pos_mask_iou_pred, mask_iou_targets) onegt_mask_iou_loss = loss_mask_iou['loss_mask_iou'].sum() assert onegt_mask_iou_loss.item() >= 0 def _dummy_bbox_sampling(proposal_list, gt_bboxes, gt_labels): """Create sample results that can be passed to BBoxHead.get_targets.""" num_imgs = 1 feat = torch.rand(1, 1, 3, 3) assign_config = dict( type='MaxIoUAssigner', pos_iou_thr=0.5, neg_iou_thr=0.5, min_pos_iou=0.5, ignore_iof_thr=-1) sampler_config = dict( type='RandomSampler', num=512, pos_fraction=0.25, neg_pos_ub=-1, add_gt_as_proposals=True) bbox_assigner = build_assigner(assign_config) bbox_sampler = build_sampler(sampler_config) gt_bboxes_ignore = [None for _ in range(num_imgs)] sampling_results = [] for i in range(num_imgs): assign_result = bbox_assigner.assign(proposal_list[i], gt_bboxes[i], gt_bboxes_ignore[i], gt_labels[i]) sampling_result = bbox_sampler.sample( assign_result, proposal_list[i], gt_bboxes[i], gt_labels[i], feats=feat) sampling_results.append(sampling_result) return sampling_results def test_corner_head_loss(): """Tests corner head loss when truth is empty and non-empty.""" s = 256 img_metas = [{ 'img_shape': (s, s, 3), 'scale_factor': 1, 'pad_shape': (s, s, 3) }] self = CornerHead(num_classes=4, in_channels=1) # Corner head expects a multiple levels of features per image feat = [ torch.rand(1, 1, s // 4, s // 4) for _ in range(self.num_feat_levels) ] tl_heats, br_heats, tl_embs, br_embs, tl_offs, br_offs = self.forward(feat) # Test that empty ground truth encourages the network to predict background gt_bboxes = [torch.empty((0, 4))] gt_labels = [torch.LongTensor([])] gt_bboxes_ignore = None empty_gt_losses = self.loss(tl_heats, br_heats, tl_embs, br_embs, tl_offs, br_offs, gt_bboxes, gt_labels, img_metas, gt_bboxes_ignore) empty_det_loss = sum(empty_gt_losses['det_loss']) empty_push_loss = sum(empty_gt_losses['push_loss']) empty_pull_loss = sum(empty_gt_losses['pull_loss']) empty_off_loss = sum(empty_gt_losses['off_loss']) assert empty_det_loss.item() > 0, 'det loss should be non-zero' assert empty_push_loss.item() == 0, ( 'there should be no push loss when there are no true boxes') assert empty_pull_loss.item() == 0, ( 'there should be no pull loss when there are no true boxes') assert empty_off_loss.item() == 0, ( 'there should be no box loss when there are no true boxes') # When truth is non-empty then both cls and box loss should be nonzero for # random inputs gt_bboxes = [ torch.Tensor([[23.6667, 23.8757, 238.6326, 151.8874]]), ] gt_labels = [torch.LongTensor([2])] one_gt_losses = self.loss(tl_heats, br_heats, tl_embs, br_embs, tl_offs, br_offs, gt_bboxes, gt_labels, img_metas, gt_bboxes_ignore) onegt_det_loss = sum(one_gt_losses['det_loss']) onegt_push_loss = sum(one_gt_losses['push_loss']) onegt_pull_loss = sum(one_gt_losses['pull_loss']) onegt_off_loss = sum(one_gt_losses['off_loss']) assert onegt_det_loss.item() > 0, 'det loss should be non-zero' assert onegt_push_loss.item() == 0, ( 'there should be no push loss when there are only one true box') assert onegt_pull_loss.item() > 0, 'pull loss should be non-zero' assert onegt_off_loss.item() > 0, 'off loss should be non-zero' gt_bboxes = [ torch.Tensor([[23.6667, 23.8757, 238.6326, 151.8874], [123.6667, 123.8757, 138.6326, 251.8874]]), ] gt_labels = [torch.LongTensor([2, 3])] # equalize the corners' embedding value of different objects to make the # push_loss larger than 0 gt_bboxes_ind = (gt_bboxes[0] // 4).int().tolist() for tl_emb_feat, br_emb_feat in zip(tl_embs, br_embs): tl_emb_feat[:, :, gt_bboxes_ind[0][1], gt_bboxes_ind[0][0]] = tl_emb_feat[:, :, gt_bboxes_ind[1][1], gt_bboxes_ind[1][0]] br_emb_feat[:, :, gt_bboxes_ind[0][3], gt_bboxes_ind[0][2]] = br_emb_feat[:, :, gt_bboxes_ind[1][3], gt_bboxes_ind[1][2]] two_gt_losses = self.loss(tl_heats, br_heats, tl_embs, br_embs, tl_offs, br_offs, gt_bboxes, gt_labels, img_metas, gt_bboxes_ignore) twogt_det_loss = sum(two_gt_losses['det_loss']) twogt_push_loss = sum(two_gt_losses['push_loss']) twogt_pull_loss = sum(two_gt_losses['pull_loss']) twogt_off_loss = sum(two_gt_losses['off_loss']) assert twogt_det_loss.item() > 0, 'det loss should be non-zero' assert twogt_push_loss.item() > 0, 'push loss should be non-zero' assert twogt_pull_loss.item() > 0, 'pull loss should be non-zero' assert twogt_off_loss.item() > 0, 'off loss should be non-zero' def test_corner_head_encode_and_decode_heatmap(): """Tests corner head generating and decoding the heatmap.""" s = 256 img_metas = [{ 'img_shape': (s, s, 3), 'scale_factor': 1, 'pad_shape': (s, s, 3), 'border': (0, 0, 0, 0) }] gt_bboxes = [ torch.Tensor([[10, 20, 200, 240], [40, 50, 100, 200], [10, 20, 200, 240]]) ] gt_labels = [torch.LongTensor([1, 1, 2])] self = CornerHead(num_classes=4, in_channels=1, corner_emb_channels=1) feat = [ torch.rand(1, 1, s // 4, s // 4) for _ in range(self.num_feat_levels) ] targets = self.get_targets( gt_bboxes, gt_labels, feat[0].shape, img_metas[0]['pad_shape'], with_corner_emb=self.with_corner_emb) gt_tl_heatmap = targets['topleft_heatmap'] gt_br_heatmap = targets['bottomright_heatmap'] gt_tl_offset = targets['topleft_offset'] gt_br_offset = targets['bottomright_offset'] embedding = targets['corner_embedding'] [top, left], [bottom, right] = embedding[0][0] gt_tl_embedding_heatmap = torch.zeros([1, 1, s // 4, s // 4]) gt_br_embedding_heatmap = torch.zeros([1, 1, s // 4, s // 4]) gt_tl_embedding_heatmap[0, 0, top, left] = 1 gt_br_embedding_heatmap[0, 0, bottom, right] = 1 batch_bboxes, batch_scores, batch_clses = self.decode_heatmap( tl_heat=gt_tl_heatmap, br_heat=gt_br_heatmap, tl_off=gt_tl_offset, br_off=gt_br_offset, tl_emb=gt_tl_embedding_heatmap, br_emb=gt_br_embedding_heatmap, img_meta=img_metas[0], k=100, kernel=3, distance_threshold=0.5) bboxes = batch_bboxes.view(-1, 4) scores = batch_scores.view(-1, 1) clses = batch_clses.view(-1, 1) idx = scores.argsort(dim=0, descending=True) bboxes = bboxes[idx].view(-1, 4) scores = scores[idx].view(-1) clses = clses[idx].view(-1) valid_bboxes = bboxes[torch.where(scores > 0.05)] valid_labels = clses[torch.where(scores > 0.05)] max_coordinate = valid_bboxes.max() offsets = valid_labels.to(valid_bboxes) * (max_coordinate + 1) gt_offsets = gt_labels[0].to(gt_bboxes[0]) * (max_coordinate + 1) offset_bboxes = valid_bboxes + offsets[:, None] offset_gtbboxes = gt_bboxes[0] + gt_offsets[:, None] iou_matrix = bbox_overlaps(offset_bboxes.numpy(), offset_gtbboxes.numpy()) assert (iou_matrix == 1).sum() == 3 def test_yolact_head_loss(): """Tests yolact head losses when truth is empty and non-empty.""" s = 550 img_metas = [{ 'img_shape': (s, s, 3), 'scale_factor': 1, 'pad_shape': (s, s, 3) }] train_cfg = mmcv.Config( dict( assigner=dict( type='MaxIoUAssigner', pos_iou_thr=0.5, neg_iou_thr=0.4, min_pos_iou=0., ignore_iof_thr=-1, gt_max_assign_all=False), smoothl1_beta=1., allowed_border=-1, pos_weight=-1, neg_pos_ratio=3, debug=False, min_gt_box_wh=[4.0, 4.0])) bbox_head = YOLACTHead( num_classes=80, in_channels=256, feat_channels=256, anchor_generator=dict( type='AnchorGenerator', octave_base_scale=3, scales_per_octave=1, base_sizes=[8, 16, 32, 64, 128], ratios=[0.5, 1.0, 2.0], strides=[550.0 / x for x in [69, 35, 18, 9, 5]], centers=[(550 * 0.5 / x, 550 * 0.5 / x) for x in [69, 35, 18, 9, 5]]), bbox_coder=dict( type='DeltaXYWHBBoxCoder', target_means=[.0, .0, .0, .0], target_stds=[0.1, 0.1, 0.2, 0.2]), loss_cls=dict( type='CrossEntropyLoss', use_sigmoid=False, reduction='none', loss_weight=1.0), loss_bbox=dict(type='SmoothL1Loss', beta=1.0, loss_weight=1.5), num_head_convs=1, num_protos=32, use_ohem=True, train_cfg=train_cfg) segm_head = YOLACTSegmHead( in_channels=256, num_classes=80, loss_segm=dict( type='CrossEntropyLoss', use_sigmoid=True, loss_weight=1.0)) mask_head = YOLACTProtonet( num_classes=80, in_channels=256, num_protos=32, max_masks_to_train=100, loss_mask_weight=6.125) feat = [ torch.rand(1, 256, feat_size, feat_size) for feat_size in [69, 35, 18, 9, 5] ] cls_score, bbox_pred, coeff_pred = bbox_head.forward(feat) # Test that empty ground truth encourages the network to predict background gt_bboxes = [torch.empty((0, 4))] gt_labels = [torch.LongTensor([])] gt_masks = [torch.empty((0, 550, 550))] gt_bboxes_ignore = None empty_gt_losses, sampling_results = bbox_head.loss( cls_score, bbox_pred, gt_bboxes, gt_labels, img_metas, gt_bboxes_ignore=gt_bboxes_ignore) # When there is no truth, the cls loss should be nonzero but there should # be no box loss. empty_cls_loss = sum(empty_gt_losses['loss_cls']) empty_box_loss = sum(empty_gt_losses['loss_bbox']) assert empty_cls_loss.item() > 0, 'cls loss should be non-zero' assert empty_box_loss.item() == 0, ( 'there should be no box loss when there are no true boxes') # Test segm head and mask head segm_head_outs = segm_head(feat[0]) empty_segm_loss = segm_head.loss(segm_head_outs, gt_masks, gt_labels) mask_pred = mask_head(feat[0], coeff_pred, gt_bboxes, img_metas, sampling_results) empty_mask_loss = mask_head.loss(mask_pred, gt_masks, gt_bboxes, img_metas, sampling_results) # When there is no truth, the segm and mask loss should be zero. empty_segm_loss = sum(empty_segm_loss['loss_segm']) empty_mask_loss = sum(empty_mask_loss['loss_mask']) assert empty_segm_loss.item() == 0, ( 'there should be no segm loss when there are no true boxes') assert empty_mask_loss == 0, ( 'there should be no mask loss when there are no true boxes') # When truth is non-empty then cls, box, mask, segm loss should be # nonzero for random inputs. gt_bboxes = [ torch.Tensor([[23.6667, 23.8757, 238.6326, 151.8874]]), ] gt_labels = [torch.LongTensor([2])] gt_masks = [(torch.rand((1, 550, 550)) > 0.5).float()] one_gt_losses, sampling_results = bbox_head.loss( cls_score, bbox_pred, gt_bboxes, gt_labels, img_metas, gt_bboxes_ignore=gt_bboxes_ignore) one_gt_cls_loss = sum(one_gt_losses['loss_cls']) one_gt_box_loss = sum(one_gt_losses['loss_bbox']) assert one_gt_cls_loss.item() > 0, 'cls loss should be non-zero' assert one_gt_box_loss.item() > 0, 'box loss should be non-zero' one_gt_segm_loss = segm_head.loss(segm_head_outs, gt_masks, gt_labels) mask_pred = mask_head(feat[0], coeff_pred, gt_bboxes, img_metas, sampling_results) one_gt_mask_loss = mask_head.loss(mask_pred, gt_masks, gt_bboxes, img_metas, sampling_results) one_gt_segm_loss = sum(one_gt_segm_loss['loss_segm']) one_gt_mask_loss = sum(one_gt_mask_loss['loss_mask']) assert one_gt_segm_loss.item() > 0, 'segm loss should be non-zero' assert one_gt_mask_loss.item() > 0, 'mask loss should be non-zero'
46,020
36.385053
79
py
GFocalV2
GFocalV2-master/tests/test_models/test_pisa_heads.py
import mmcv import torch from mmdet.models.dense_heads import PISARetinaHead, PISASSDHead from mmdet.models.roi_heads import PISARoIHead def test_pisa_retinanet_head_loss(): """Tests pisa retinanet head loss when truth is empty and non-empty.""" s = 256 img_metas = [{ 'img_shape': (s, s, 3), 'scale_factor': 1, 'pad_shape': (s, s, 3) }] cfg = mmcv.Config( dict( assigner=dict( type='MaxIoUAssigner', pos_iou_thr=0.7, neg_iou_thr=0.3, min_pos_iou=0.3, match_low_quality=True, ignore_iof_thr=-1), sampler=dict( type='RandomSampler', num=256, pos_fraction=0.5, neg_pos_ub=-1, add_gt_as_proposals=False), isr=dict(k=2., bias=0.), carl=dict(k=1., bias=0.2), allowed_border=0, pos_weight=-1, debug=False)) self = PISARetinaHead(num_classes=4, in_channels=1, train_cfg=cfg) # Anchor head expects a multiple levels of features per image feat = [ torch.rand(1, 1, s // (2**(i + 2)), s // (2**(i + 2))) for i in range(len(self.anchor_generator.strides)) ] cls_scores, bbox_preds = self.forward(feat) # Test that empty ground truth encourages the network to predict background gt_bboxes = [torch.empty((0, 4))] gt_labels = [torch.LongTensor([])] gt_bboxes_ignore = None empty_gt_losses = self.loss(cls_scores, bbox_preds, gt_bboxes, gt_labels, img_metas, gt_bboxes_ignore) # When there is no truth, the cls loss should be nonzero but there should # be no box loss. empty_cls_loss = empty_gt_losses['loss_cls'].sum() empty_box_loss = empty_gt_losses['loss_bbox'].sum() assert empty_cls_loss.item() > 0, 'cls loss should be non-zero' assert empty_box_loss.item() == 0, ( 'there should be no box loss when there are no true boxes') # When truth is non-empty then both cls and box loss should be nonzero for # random inputs gt_bboxes = [ torch.Tensor([[23.6667, 23.8757, 238.6326, 151.8874]]), ] gt_labels = [torch.LongTensor([2])] one_gt_losses = self.loss(cls_scores, bbox_preds, gt_bboxes, gt_labels, img_metas, gt_bboxes_ignore) onegt_cls_loss = one_gt_losses['loss_cls'].sum() onegt_box_loss = one_gt_losses['loss_bbox'].sum() assert onegt_cls_loss.item() > 0, 'cls loss should be non-zero' assert onegt_box_loss.item() > 0, 'box loss should be non-zero' def test_pisa_ssd_head_loss(): """Tests pisa ssd head loss when truth is empty and non-empty.""" s = 256 img_metas = [{ 'img_shape': (s, s, 3), 'scale_factor': 1, 'pad_shape': (s, s, 3) }] cfg = mmcv.Config( dict( assigner=dict( type='MaxIoUAssigner', pos_iou_thr=0.5, neg_iou_thr=0.5, min_pos_iou=0., ignore_iof_thr=-1, gt_max_assign_all=False), isr=dict(k=2., bias=0.), carl=dict(k=1., bias=0.2), smoothl1_beta=1., allowed_border=-1, pos_weight=-1, neg_pos_ratio=3, debug=False)) ssd_anchor_generator = dict( type='SSDAnchorGenerator', scale_major=False, input_size=300, strides=[1], ratios=([2], ), basesize_ratio_range=(0.15, 0.9)) self = PISASSDHead( num_classes=4, in_channels=(1, ), train_cfg=cfg, anchor_generator=ssd_anchor_generator) # Anchor head expects a multiple levels of features per image feat = [ torch.rand(1, 1, s // (2**(i + 2)), s // (2**(i + 2))) for i in range(len(self.anchor_generator.strides)) ] cls_scores, bbox_preds = self.forward(feat) # Test that empty ground truth encourages the network to predict background gt_bboxes = [torch.empty((0, 4))] gt_labels = [torch.LongTensor([])] gt_bboxes_ignore = None empty_gt_losses = self.loss(cls_scores, bbox_preds, gt_bboxes, gt_labels, img_metas, gt_bboxes_ignore) # When there is no truth, the cls loss should be nonzero but there should # be no box loss. empty_cls_loss = sum(empty_gt_losses['loss_cls']) empty_box_loss = sum(empty_gt_losses['loss_bbox']) # SSD is special, #pos:#neg = 1: 3, so empth gt will also lead loss cls = 0 assert empty_cls_loss.item() == 0, 'cls loss should be non-zero' assert empty_box_loss.item() == 0, ( 'there should be no box loss when there are no true boxes') # When truth is non-empty then both cls and box loss should be nonzero for # random inputs gt_bboxes = [ torch.Tensor([[23.6667, 23.8757, 238.6326, 151.8874]]), ] gt_labels = [torch.LongTensor([2])] one_gt_losses = self.loss(cls_scores, bbox_preds, gt_bboxes, gt_labels, img_metas, gt_bboxes_ignore) onegt_cls_loss = sum(one_gt_losses['loss_cls']) onegt_box_loss = sum(one_gt_losses['loss_bbox']) assert onegt_cls_loss.item() > 0, 'cls loss should be non-zero' assert onegt_box_loss.item() > 0, 'box loss should be non-zero' def test_pisa_roi_head_loss(): """Tests pisa roi head loss when truth is empty and non-empty.""" train_cfg = mmcv.Config( dict( assigner=dict( type='MaxIoUAssigner', pos_iou_thr=0.7, neg_iou_thr=0.3, min_pos_iou=0.3, match_low_quality=True, ignore_iof_thr=-1), sampler=dict( type='ScoreHLRSampler', num=4, pos_fraction=0.25, neg_pos_ub=-1, add_gt_as_proposals=True, k=0.5, bias=0.), isr=dict(k=2., bias=0.), carl=dict(k=1., bias=0.2), allowed_border=0, pos_weight=-1, debug=False)) bbox_roi_extractor = dict( type='SingleRoIExtractor', roi_layer=dict(type='RoIAlign', output_size=7, sampling_ratio=0), out_channels=1, featmap_strides=[1]) bbox_head = dict( type='Shared2FCBBoxHead', in_channels=1, fc_out_channels=2, roi_feat_size=7, num_classes=4, bbox_coder=dict( type='DeltaXYWHBBoxCoder', target_means=[0., 0., 0., 0.], target_stds=[0.1, 0.1, 0.2, 0.2]), reg_class_agnostic=False, loss_cls=dict( type='CrossEntropyLoss', use_sigmoid=False, loss_weight=1.0), loss_bbox=dict(type='L1Loss', loss_weight=1.0)) self = PISARoIHead(bbox_roi_extractor, bbox_head, train_cfg=train_cfg) s = 256 img_metas = [{ 'img_shape': (s, s, 3), 'scale_factor': 1, 'pad_shape': (s, s, 3) }] # Anchor head expects a multiple levels of features per image feat = [ torch.rand(1, 1, s // (2**(i + 2)), s // (2**(i + 2))) for i in range(1) ] proposal_list = [ torch.Tensor([[22.6667, 22.8757, 238.6326, 151.8874], [0, 3, 5, 7]]) ] # Test that empty ground truth encourages the network to predict background gt_bboxes = [torch.empty((0, 4))] gt_labels = [torch.LongTensor([])] gt_bboxes_ignore = None empty_gt_losses = self.forward_train(feat, img_metas, proposal_list, gt_bboxes, gt_labels, gt_bboxes_ignore) # When there is no truth, the cls loss should be nonzero but there should # be no box loss. empty_cls_loss = empty_gt_losses['loss_cls'].sum() empty_box_loss = empty_gt_losses['loss_bbox'].sum() assert empty_cls_loss.item() > 0, 'cls loss should be non-zero' assert empty_box_loss.item() == 0, ( 'there should be no box loss when there are no true boxes') # When truth is non-empty then both cls and box loss should be nonzero for # random inputs gt_bboxes = [ torch.Tensor([[23.6667, 23.8757, 238.6326, 151.8874]]), ] gt_labels = [torch.LongTensor([2])] one_gt_losses = self.forward_train(feat, img_metas, proposal_list, gt_bboxes, gt_labels, gt_bboxes_ignore) onegt_cls_loss = one_gt_losses['loss_cls'].sum() onegt_box_loss = one_gt_losses['loss_bbox'].sum() assert onegt_cls_loss.item() > 0, 'cls loss should be non-zero' assert onegt_box_loss.item() > 0, 'box loss should be non-zero'
8,757
34.746939
79
py
GFocalV2
GFocalV2-master/tests/test_models/test_losses.py
import pytest import torch from mmdet.models import Accuracy, build_loss def test_ce_loss(): # use_mask and use_sigmoid cannot be true at the same time with pytest.raises(AssertionError): loss_cfg = dict( type='CrossEntropyLoss', use_mask=True, use_sigmoid=True, loss_weight=1.0) build_loss(loss_cfg) # test loss with class weights loss_cls_cfg = dict( type='CrossEntropyLoss', use_sigmoid=False, class_weight=[0.8, 0.2], loss_weight=1.0) loss_cls = build_loss(loss_cls_cfg) fake_pred = torch.Tensor([[100, -100]]) fake_label = torch.Tensor([1]).long() assert torch.allclose(loss_cls(fake_pred, fake_label), torch.tensor(40.)) loss_cls_cfg = dict( type='CrossEntropyLoss', use_sigmoid=False, loss_weight=1.0) loss_cls = build_loss(loss_cls_cfg) assert torch.allclose(loss_cls(fake_pred, fake_label), torch.tensor(200.)) def test_varifocal_loss(): # only sigmoid version of VarifocalLoss is implemented with pytest.raises(AssertionError): loss_cfg = dict( type='VarifocalLoss', use_sigmoid=False, loss_weight=1.0) build_loss(loss_cfg) # test that alpha should be greater than 0 with pytest.raises(AssertionError): loss_cfg = dict( type='VarifocalLoss', alpha=-0.75, gamma=2.0, use_sigmoid=True, loss_weight=1.0) build_loss(loss_cfg) # test that pred and target should be of the same size loss_cls_cfg = dict( type='VarifocalLoss', use_sigmoid=True, alpha=0.75, gamma=2.0, iou_weighted=True, reduction='mean', loss_weight=1.0) loss_cls = build_loss(loss_cls_cfg) with pytest.raises(AssertionError): fake_pred = torch.Tensor([[100.0, -100.0]]) fake_target = torch.Tensor([[1.0]]) loss_cls(fake_pred, fake_target) # test the calculation loss_cls = build_loss(loss_cls_cfg) fake_pred = torch.Tensor([[100.0, -100.0]]) fake_target = torch.Tensor([[1.0, 0.0]]) assert torch.allclose(loss_cls(fake_pred, fake_target), torch.tensor(0.0)) # test the loss with weights loss_cls = build_loss(loss_cls_cfg) fake_pred = torch.Tensor([[0.0, 100.0]]) fake_target = torch.Tensor([[1.0, 1.0]]) fake_weight = torch.Tensor([0.0, 1.0]) assert torch.allclose( loss_cls(fake_pred, fake_target, fake_weight), torch.tensor(0.0)) def test_accuracy(): # test for empty pred pred = torch.empty(0, 4) label = torch.empty(0) accuracy = Accuracy(topk=1) acc = accuracy(pred, label) assert acc.item() == 0 pred = torch.Tensor([[0.2, 0.3, 0.6, 0.5], [0.1, 0.1, 0.2, 0.6], [0.9, 0.0, 0.0, 0.1], [0.4, 0.7, 0.1, 0.1], [0.0, 0.0, 0.99, 0]]) # test for top1 true_label = torch.Tensor([2, 3, 0, 1, 2]).long() accuracy = Accuracy(topk=1) acc = accuracy(pred, true_label) assert acc.item() == 100 # test for top1 with score thresh=0.8 true_label = torch.Tensor([2, 3, 0, 1, 2]).long() accuracy = Accuracy(topk=1, thresh=0.8) acc = accuracy(pred, true_label) assert acc.item() == 40 # test for top2 accuracy = Accuracy(topk=2) label = torch.Tensor([3, 2, 0, 0, 2]).long() acc = accuracy(pred, label) assert acc.item() == 100 # test for both top1 and top2 accuracy = Accuracy(topk=(1, 2)) true_label = torch.Tensor([2, 3, 0, 1, 2]).long() acc = accuracy(pred, true_label) for a in acc: assert a.item() == 100 # topk is larger than pred class number with pytest.raises(AssertionError): accuracy = Accuracy(topk=5) accuracy(pred, true_label) # wrong topk type with pytest.raises(AssertionError): accuracy = Accuracy(topk='wrong type') accuracy(pred, true_label) # label size is larger than required with pytest.raises(AssertionError): label = torch.Tensor([2, 3, 0, 1, 2, 0]).long() # size mismatch accuracy = Accuracy() accuracy(pred, label) # wrong pred dimension with pytest.raises(AssertionError): accuracy = Accuracy() accuracy(pred[:, :, None], true_label)
4,327
30.591241
78
py
GFocalV2
GFocalV2-master/tests/test_data/test_dataset.py
import bisect import logging import math import os.path as osp import tempfile from collections import defaultdict from unittest.mock import MagicMock, patch import mmcv import numpy as np import pytest import torch import torch.nn as nn from mmcv.runner import EpochBasedRunner from torch.utils.data import DataLoader from mmdet.core.evaluation import DistEvalHook, EvalHook from mmdet.datasets import (DATASETS, ClassBalancedDataset, CocoDataset, ConcatDataset, CustomDataset, RepeatDataset, build_dataset) def _create_dummy_coco_json(json_name): image = { 'id': 0, 'width': 640, 'height': 640, 'file_name': 'fake_name.jpg', } annotation_1 = { 'id': 1, 'image_id': 0, 'category_id': 0, 'area': 400, 'bbox': [50, 60, 20, 20], 'iscrowd': 0, } annotation_2 = { 'id': 2, 'image_id': 0, 'category_id': 0, 'area': 900, 'bbox': [100, 120, 30, 30], 'iscrowd': 0, } annotation_3 = { 'id': 3, 'image_id': 0, 'category_id': 0, 'area': 1600, 'bbox': [150, 160, 40, 40], 'iscrowd': 0, } annotation_4 = { 'id': 4, 'image_id': 0, 'category_id': 0, 'area': 10000, 'bbox': [250, 260, 100, 100], 'iscrowd': 0, } categories = [{ 'id': 0, 'name': 'car', 'supercategory': 'car', }] fake_json = { 'images': [image], 'annotations': [annotation_1, annotation_2, annotation_3, annotation_4], 'categories': categories } mmcv.dump(fake_json, json_name) def _create_dummy_custom_pkl(pkl_name): fake_pkl = [{ 'filename': 'fake_name.jpg', 'width': 640, 'height': 640, 'ann': { 'bboxes': np.array([[50, 60, 70, 80], [100, 120, 130, 150], [150, 160, 190, 200], [250, 260, 350, 360]]), 'labels': np.array([0, 0, 0, 0]) } }] mmcv.dump(fake_pkl, pkl_name) def _create_dummy_results(): boxes = [ np.array([[50, 60, 70, 80, 1.0], [100, 120, 130, 150, 0.98], [150, 160, 190, 200, 0.96], [250, 260, 350, 360, 0.95]]) ] return [boxes] def test_dataset_evaluation(): tmp_dir = tempfile.TemporaryDirectory() # create dummy data fake_json_file = osp.join(tmp_dir.name, 'fake_data.json') _create_dummy_coco_json(fake_json_file) # test single coco dataset evaluation coco_dataset = CocoDataset( ann_file=fake_json_file, classes=('car', ), pipeline=[]) fake_results = _create_dummy_results() eval_results = coco_dataset.evaluate(fake_results, classwise=True) assert eval_results['bbox_mAP'] == 1 assert eval_results['bbox_mAP_50'] == 1 assert eval_results['bbox_mAP_75'] == 1 # test concat dataset evaluation fake_concat_results = _create_dummy_results() + _create_dummy_results() # build concat dataset through two config dict coco_cfg = dict( type='CocoDataset', ann_file=fake_json_file, classes=('car', ), pipeline=[]) concat_cfgs = [coco_cfg, coco_cfg] concat_dataset = build_dataset(concat_cfgs) eval_results = concat_dataset.evaluate(fake_concat_results) assert eval_results['0_bbox_mAP'] == 1 assert eval_results['0_bbox_mAP_50'] == 1 assert eval_results['0_bbox_mAP_75'] == 1 assert eval_results['1_bbox_mAP'] == 1 assert eval_results['1_bbox_mAP_50'] == 1 assert eval_results['1_bbox_mAP_75'] == 1 # build concat dataset through concatenated ann_file coco_cfg = dict( type='CocoDataset', ann_file=[fake_json_file, fake_json_file], classes=('car', ), pipeline=[]) concat_dataset = build_dataset(coco_cfg) eval_results = concat_dataset.evaluate(fake_concat_results) assert eval_results['0_bbox_mAP'] == 1 assert eval_results['0_bbox_mAP_50'] == 1 assert eval_results['0_bbox_mAP_75'] == 1 assert eval_results['1_bbox_mAP'] == 1 assert eval_results['1_bbox_mAP_50'] == 1 assert eval_results['1_bbox_mAP_75'] == 1 # create dummy data fake_pkl_file = osp.join(tmp_dir.name, 'fake_data.pkl') _create_dummy_custom_pkl(fake_pkl_file) # test single custom dataset evaluation custom_dataset = CustomDataset( ann_file=fake_pkl_file, classes=('car', ), pipeline=[]) fake_results = _create_dummy_results() eval_results = custom_dataset.evaluate(fake_results) assert eval_results['mAP'] == 1 # test concat dataset evaluation fake_concat_results = _create_dummy_results() + _create_dummy_results() # build concat dataset through two config dict custom_cfg = dict( type='CustomDataset', ann_file=fake_pkl_file, classes=('car', ), pipeline=[]) concat_cfgs = [custom_cfg, custom_cfg] concat_dataset = build_dataset(concat_cfgs) eval_results = concat_dataset.evaluate(fake_concat_results) assert eval_results['0_mAP'] == 1 assert eval_results['1_mAP'] == 1 # build concat dataset through concatenated ann_file concat_cfg = dict( type='CustomDataset', ann_file=[fake_pkl_file, fake_pkl_file], classes=('car', ), pipeline=[]) concat_dataset = build_dataset(concat_cfg) eval_results = concat_dataset.evaluate(fake_concat_results) assert eval_results['0_mAP'] == 1 assert eval_results['1_mAP'] == 1 # build concat dataset through explict type concat_cfg = dict( type='ConcatDataset', datasets=[custom_cfg, custom_cfg], separate_eval=False) concat_dataset = build_dataset(concat_cfg) eval_results = concat_dataset.evaluate(fake_concat_results, metric='mAP') assert eval_results['mAP'] == 1 assert len(concat_dataset.datasets[0].data_infos) == \ len(concat_dataset.datasets[1].data_infos) assert len(concat_dataset.datasets[0].data_infos) == 1 tmp_dir.cleanup() @patch('mmdet.datasets.CocoDataset.load_annotations', MagicMock) @patch('mmdet.datasets.CustomDataset.load_annotations', MagicMock) @patch('mmdet.datasets.XMLDataset.load_annotations', MagicMock) @patch('mmdet.datasets.CityscapesDataset.load_annotations', MagicMock) @patch('mmdet.datasets.CocoDataset._filter_imgs', MagicMock) @patch('mmdet.datasets.CustomDataset._filter_imgs', MagicMock) @patch('mmdet.datasets.XMLDataset._filter_imgs', MagicMock) @patch('mmdet.datasets.CityscapesDataset._filter_imgs', MagicMock) @pytest.mark.parametrize('dataset', ['CocoDataset', 'VOCDataset', 'CityscapesDataset']) def test_custom_classes_override_default(dataset): dataset_class = DATASETS.get(dataset) if dataset in ['CocoDataset', 'CityscapesDataset']: dataset_class.coco = MagicMock() dataset_class.cat_ids = MagicMock() original_classes = dataset_class.CLASSES # Test setting classes as a tuple custom_dataset = dataset_class( ann_file=MagicMock(), pipeline=[], classes=('bus', 'car'), test_mode=True, img_prefix='VOC2007' if dataset == 'VOCDataset' else '') assert custom_dataset.CLASSES != original_classes assert custom_dataset.CLASSES == ('bus', 'car') # Test setting classes as a list custom_dataset = dataset_class( ann_file=MagicMock(), pipeline=[], classes=['bus', 'car'], test_mode=True, img_prefix='VOC2007' if dataset == 'VOCDataset' else '') assert custom_dataset.CLASSES != original_classes assert custom_dataset.CLASSES == ['bus', 'car'] # Test overriding not a subset custom_dataset = dataset_class( ann_file=MagicMock(), pipeline=[], classes=['foo'], test_mode=True, img_prefix='VOC2007' if dataset == 'VOCDataset' else '') assert custom_dataset.CLASSES != original_classes assert custom_dataset.CLASSES == ['foo'] # Test default behavior custom_dataset = dataset_class( ann_file=MagicMock(), pipeline=[], classes=None, test_mode=True, img_prefix='VOC2007' if dataset == 'VOCDataset' else '') assert custom_dataset.CLASSES == original_classes # Test sending file path import tempfile tmp_file = tempfile.NamedTemporaryFile() with open(tmp_file.name, 'w') as f: f.write('bus\ncar\n') custom_dataset = dataset_class( ann_file=MagicMock(), pipeline=[], classes=tmp_file.name, test_mode=True, img_prefix='VOC2007' if dataset == 'VOCDataset' else '') tmp_file.close() assert custom_dataset.CLASSES != original_classes assert custom_dataset.CLASSES == ['bus', 'car'] def test_dataset_wrapper(): CustomDataset.load_annotations = MagicMock() CustomDataset.__getitem__ = MagicMock(side_effect=lambda idx: idx) dataset_a = CustomDataset( ann_file=MagicMock(), pipeline=[], test_mode=True, img_prefix='') len_a = 10 cat_ids_list_a = [ np.random.randint(0, 80, num).tolist() for num in np.random.randint(1, 20, len_a) ] dataset_a.data_infos = MagicMock() dataset_a.data_infos.__len__.return_value = len_a dataset_a.get_cat_ids = MagicMock( side_effect=lambda idx: cat_ids_list_a[idx]) dataset_b = CustomDataset( ann_file=MagicMock(), pipeline=[], test_mode=True, img_prefix='') len_b = 20 cat_ids_list_b = [ np.random.randint(0, 80, num).tolist() for num in np.random.randint(1, 20, len_b) ] dataset_b.data_infos = MagicMock() dataset_b.data_infos.__len__.return_value = len_b dataset_b.get_cat_ids = MagicMock( side_effect=lambda idx: cat_ids_list_b[idx]) concat_dataset = ConcatDataset([dataset_a, dataset_b]) assert concat_dataset[5] == 5 assert concat_dataset[25] == 15 assert concat_dataset.get_cat_ids(5) == cat_ids_list_a[5] assert concat_dataset.get_cat_ids(25) == cat_ids_list_b[15] assert len(concat_dataset) == len(dataset_a) + len(dataset_b) repeat_dataset = RepeatDataset(dataset_a, 10) assert repeat_dataset[5] == 5 assert repeat_dataset[15] == 5 assert repeat_dataset[27] == 7 assert repeat_dataset.get_cat_ids(5) == cat_ids_list_a[5] assert repeat_dataset.get_cat_ids(15) == cat_ids_list_a[5] assert repeat_dataset.get_cat_ids(27) == cat_ids_list_a[7] assert len(repeat_dataset) == 10 * len(dataset_a) category_freq = defaultdict(int) for cat_ids in cat_ids_list_a: cat_ids = set(cat_ids) for cat_id in cat_ids: category_freq[cat_id] += 1 for k, v in category_freq.items(): category_freq[k] = v / len(cat_ids_list_a) mean_freq = np.mean(list(category_freq.values())) repeat_thr = mean_freq category_repeat = { cat_id: max(1.0, math.sqrt(repeat_thr / cat_freq)) for cat_id, cat_freq in category_freq.items() } repeat_factors = [] for cat_ids in cat_ids_list_a: cat_ids = set(cat_ids) repeat_factor = max({category_repeat[cat_id] for cat_id in cat_ids}) repeat_factors.append(math.ceil(repeat_factor)) repeat_factors_cumsum = np.cumsum(repeat_factors) repeat_factor_dataset = ClassBalancedDataset(dataset_a, repeat_thr) assert len(repeat_factor_dataset) == repeat_factors_cumsum[-1] for idx in np.random.randint(0, len(repeat_factor_dataset), 3): assert repeat_factor_dataset[idx] == bisect.bisect_right( repeat_factors_cumsum, idx) @patch('mmdet.apis.single_gpu_test', MagicMock) @patch('mmdet.apis.multi_gpu_test', MagicMock) @pytest.mark.parametrize('EvalHookParam', (EvalHook, DistEvalHook)) def test_evaluation_hook(EvalHookParam): # create dummy data dataloader = DataLoader(torch.ones((5, 2))) # 0.1. dataloader is not a DataLoader object with pytest.raises(TypeError): EvalHookParam(dataloader=MagicMock(), interval=-1) # 0.2. negative interval with pytest.raises(ValueError): EvalHookParam(dataloader, interval=-1) # 1. start=None, interval=1: perform evaluation after each epoch. runner = _build_demo_runner() evalhook = EvalHookParam(dataloader, interval=1) evalhook.evaluate = MagicMock() runner.register_hook(evalhook) runner.run([dataloader], [('train', 1)], 2) assert evalhook.evaluate.call_count == 2 # after epoch 1 & 2 # 2. start=1, interval=1: perform evaluation after each epoch. runner = _build_demo_runner() evalhook = EvalHookParam(dataloader, start=1, interval=1) evalhook.evaluate = MagicMock() runner.register_hook(evalhook) runner.run([dataloader], [('train', 1)], 2) assert evalhook.evaluate.call_count == 2 # after epoch 1 & 2 # 3. start=None, interval=2: perform evaluation after epoch 2, 4, 6, etc runner = _build_demo_runner() evalhook = EvalHookParam(dataloader, interval=2) evalhook.evaluate = MagicMock() runner.register_hook(evalhook) runner.run([dataloader], [('train', 1)], 2) assert evalhook.evaluate.call_count == 1 # after epoch 2 # 4. start=1, interval=2: perform evaluation after epoch 1, 3, 5, etc runner = _build_demo_runner() evalhook = EvalHookParam(dataloader, start=1, interval=2) evalhook.evaluate = MagicMock() runner.register_hook(evalhook) runner.run([dataloader], [('train', 1)], 3) assert evalhook.evaluate.call_count == 2 # after epoch 1 & 3 # 5. start=0/negative, interval=1: perform evaluation after each epoch and # before epoch 1. runner = _build_demo_runner() evalhook = EvalHookParam(dataloader, start=0) evalhook.evaluate = MagicMock() runner.register_hook(evalhook) runner.run([dataloader], [('train', 1)], 2) assert evalhook.evaluate.call_count == 3 # before epoch1 and after e1 & e2 runner = _build_demo_runner() with pytest.warns(UserWarning): evalhook = EvalHookParam(dataloader, start=-2) evalhook.evaluate = MagicMock() runner.register_hook(evalhook) runner.run([dataloader], [('train', 1)], 2) assert evalhook.evaluate.call_count == 3 # before epoch1 and after e1 & e2 # 6. resuming from epoch i, start = x (x<=i), interval =1: perform # evaluation after each epoch and before the first epoch. runner = _build_demo_runner() evalhook = EvalHookParam(dataloader, start=1) evalhook.evaluate = MagicMock() runner.register_hook(evalhook) runner._epoch = 2 runner.run([dataloader], [('train', 1)], 3) assert evalhook.evaluate.call_count == 2 # before & after epoch 3 # 7. resuming from epoch i, start = i+1/None, interval =1: perform # evaluation after each epoch. runner = _build_demo_runner() evalhook = EvalHookParam(dataloader, start=2) evalhook.evaluate = MagicMock() runner.register_hook(evalhook) runner._epoch = 1 runner.run([dataloader], [('train', 1)], 3) assert evalhook.evaluate.call_count == 2 # after epoch 2 & 3 def _build_demo_runner(): class Model(nn.Module): def __init__(self): super().__init__() self.linear = nn.Linear(2, 1) def forward(self, x): return self.linear(x) def train_step(self, x, optimizer, **kwargs): return dict(loss=self(x)) def val_step(self, x, optimizer, **kwargs): return dict(loss=self(x)) model = Model() tmp_dir = tempfile.mkdtemp() runner = EpochBasedRunner( model=model, work_dir=tmp_dir, logger=logging.getLogger()) return runner @pytest.mark.parametrize('classes, expected_length', [(['bus'], 2), (['car'], 1), (['bus', 'car'], 2)]) def test_allow_empty_images(classes, expected_length): dataset_class = DATASETS.get('CocoDataset') # Filter empty images filtered_dataset = dataset_class( ann_file='tests/data/coco_sample.json', img_prefix='tests/data', pipeline=[], classes=classes, filter_empty_gt=True) # Get all full_dataset = dataset_class( ann_file='tests/data/coco_sample.json', img_prefix='tests/data', pipeline=[], classes=classes, filter_empty_gt=False) assert len(filtered_dataset) == expected_length assert len(filtered_dataset.img_ids) == expected_length assert len(full_dataset) == 3 assert len(full_dataset.img_ids) == 3 assert filtered_dataset.CLASSES == classes assert full_dataset.CLASSES == classes
16,754
32.917004
79
py
GFocalV2
GFocalV2-master/tests/test_data/test_transform.py
import copy import os.path as osp import mmcv import numpy as np import pytest import torch from mmcv.utils import build_from_cfg from mmdet.core.evaluation.bbox_overlaps import bbox_overlaps from mmdet.datasets.builder import PIPELINES def test_resize(): # test assertion if img_scale is a list with pytest.raises(AssertionError): transform = dict(type='Resize', img_scale=[1333, 800], keep_ratio=True) build_from_cfg(transform, PIPELINES) # test assertion if len(img_scale) while ratio_range is not None with pytest.raises(AssertionError): transform = dict( type='Resize', img_scale=[(1333, 800), (1333, 600)], ratio_range=(0.9, 1.1), keep_ratio=True) build_from_cfg(transform, PIPELINES) # test assertion for invalid multiscale_mode with pytest.raises(AssertionError): transform = dict( type='Resize', img_scale=[(1333, 800), (1333, 600)], keep_ratio=True, multiscale_mode='2333') build_from_cfg(transform, PIPELINES) # test assertion if both scale and scale_factor are setted with pytest.raises(AssertionError): results = dict( img_prefix=osp.join(osp.dirname(__file__), '../data'), img_info=dict(filename='color.jpg')) load = dict(type='LoadImageFromFile') load = build_from_cfg(load, PIPELINES) transform = dict(type='Resize', img_scale=(1333, 800), keep_ratio=True) transform = build_from_cfg(transform, PIPELINES) results = load(results) results['scale'] = (1333, 800) results['scale_factor'] = 1.0 results = transform(results) transform = dict(type='Resize', img_scale=(1333, 800), keep_ratio=True) resize_module = build_from_cfg(transform, PIPELINES) results = dict() img = mmcv.imread( osp.join(osp.dirname(__file__), '../data/color.jpg'), 'color') results['img'] = img results['img2'] = copy.deepcopy(img) results['img_shape'] = img.shape results['ori_shape'] = img.shape # Set initial values for default meta_keys results['pad_shape'] = img.shape results['img_fields'] = ['img', 'img2'] results = resize_module(results) assert np.equal(results['img'], results['img2']).all() results.pop('scale') results.pop('scale_factor') transform = dict( type='Resize', img_scale=(1280, 800), multiscale_mode='value', keep_ratio=False) resize_module = build_from_cfg(transform, PIPELINES) results = resize_module(results) assert np.equal(results['img'], results['img2']).all() assert results['img_shape'] == (800, 1280, 3) def test_flip(): # test assertion for invalid flip_ratio with pytest.raises(AssertionError): transform = dict(type='RandomFlip', flip_ratio=1.5) build_from_cfg(transform, PIPELINES) # test assertion for 0 <= sum(flip_ratio) <= 1 with pytest.raises(AssertionError): transform = dict( type='RandomFlip', flip_ratio=[0.7, 0.8], direction=['horizontal', 'vertical']) build_from_cfg(transform, PIPELINES) # test assertion for mismatch between number of flip_ratio and direction with pytest.raises(AssertionError): transform = dict(type='RandomFlip', flip_ratio=[0.4, 0.5]) build_from_cfg(transform, PIPELINES) # test assertion for invalid direction with pytest.raises(AssertionError): transform = dict( type='RandomFlip', flip_ratio=1., direction='horizonta') build_from_cfg(transform, PIPELINES) transform = dict(type='RandomFlip', flip_ratio=1.) flip_module = build_from_cfg(transform, PIPELINES) results = dict() img = mmcv.imread( osp.join(osp.dirname(__file__), '../data/color.jpg'), 'color') original_img = copy.deepcopy(img) results['img'] = img results['img2'] = copy.deepcopy(img) results['img_shape'] = img.shape results['ori_shape'] = img.shape # Set initial values for default meta_keys results['pad_shape'] = img.shape results['scale_factor'] = 1.0 results['img_fields'] = ['img', 'img2'] results = flip_module(results) assert np.equal(results['img'], results['img2']).all() flip_module = build_from_cfg(transform, PIPELINES) results = flip_module(results) assert np.equal(results['img'], results['img2']).all() assert np.equal(original_img, results['img']).all() # test flip_ratio is float, direction is list transform = dict( type='RandomFlip', flip_ratio=0.9, direction=['horizontal', 'vertical', 'diagonal']) flip_module = build_from_cfg(transform, PIPELINES) results = dict() img = mmcv.imread( osp.join(osp.dirname(__file__), '../data/color.jpg'), 'color') original_img = copy.deepcopy(img) results['img'] = img results['img_shape'] = img.shape results['ori_shape'] = img.shape # Set initial values for default meta_keys results['pad_shape'] = img.shape results['scale_factor'] = 1.0 results['img_fields'] = ['img'] results = flip_module(results) if results['flip']: assert np.array_equal( mmcv.imflip(original_img, results['flip_direction']), results['img']) else: assert np.array_equal(original_img, results['img']) # test flip_ratio is list, direction is list transform = dict( type='RandomFlip', flip_ratio=[0.3, 0.3, 0.2], direction=['horizontal', 'vertical', 'diagonal']) flip_module = build_from_cfg(transform, PIPELINES) results = dict() img = mmcv.imread( osp.join(osp.dirname(__file__), '../data/color.jpg'), 'color') original_img = copy.deepcopy(img) results['img'] = img results['img_shape'] = img.shape results['ori_shape'] = img.shape # Set initial values for default meta_keys results['pad_shape'] = img.shape results['scale_factor'] = 1.0 results['img_fields'] = ['img'] results = flip_module(results) if results['flip']: assert np.array_equal( mmcv.imflip(original_img, results['flip_direction']), results['img']) else: assert np.array_equal(original_img, results['img']) def test_random_crop(): # test assertion for invalid random crop with pytest.raises(AssertionError): transform = dict(type='RandomCrop', crop_size=(-1, 0)) build_from_cfg(transform, PIPELINES) results = dict() img = mmcv.imread( osp.join(osp.dirname(__file__), '../data/color.jpg'), 'color') results['img'] = img results['img_shape'] = img.shape results['ori_shape'] = img.shape # TODO: add img_fields test results['bbox_fields'] = ['gt_bboxes', 'gt_bboxes_ignore'] # Set initial values for default meta_keys results['pad_shape'] = img.shape results['scale_factor'] = 1.0 def create_random_bboxes(num_bboxes, img_w, img_h): bboxes_left_top = np.random.uniform(0, 0.5, size=(num_bboxes, 2)) bboxes_right_bottom = np.random.uniform(0.5, 1, size=(num_bboxes, 2)) bboxes = np.concatenate((bboxes_left_top, bboxes_right_bottom), 1) bboxes = (bboxes * np.array([img_w, img_h, img_w, img_h])).astype( np.int) return bboxes h, w, _ = img.shape gt_bboxes = create_random_bboxes(8, w, h) gt_bboxes_ignore = create_random_bboxes(2, w, h) results['gt_bboxes'] = gt_bboxes results['gt_bboxes_ignore'] = gt_bboxes_ignore transform = dict(type='RandomCrop', crop_size=(h - 20, w - 20)) crop_module = build_from_cfg(transform, PIPELINES) results = crop_module(results) assert results['img'].shape[:2] == (h - 20, w - 20) # All bboxes should be reserved after crop assert results['img_shape'][:2] == (h - 20, w - 20) assert results['gt_bboxes'].shape[0] == 8 assert results['gt_bboxes_ignore'].shape[0] == 2 def area(bboxes): return np.prod(bboxes[:, 2:4] - bboxes[:, 0:2], axis=1) assert (area(results['gt_bboxes']) <= area(gt_bboxes)).all() assert (area(results['gt_bboxes_ignore']) <= area(gt_bboxes_ignore)).all() def test_min_iou_random_crop(): def create_random_bboxes(num_bboxes, img_w, img_h): bboxes_left_top = np.random.uniform(0, 0.5, size=(num_bboxes, 2)) bboxes_right_bottom = np.random.uniform(0.5, 1, size=(num_bboxes, 2)) bboxes = np.concatenate((bboxes_left_top, bboxes_right_bottom), 1) bboxes = (bboxes * np.array([img_w, img_h, img_w, img_h])).astype( np.int) return bboxes results = dict() img = mmcv.imread( osp.join(osp.dirname(__file__), '../data/color.jpg'), 'color') results['img'] = img results['img_shape'] = img.shape results['ori_shape'] = img.shape results['bbox_fields'] = ['gt_bboxes', 'gt_bboxes_ignore'] # Set initial values for default meta_keys results['pad_shape'] = img.shape results['scale_factor'] = 1.0 h, w, _ = img.shape gt_bboxes = create_random_bboxes(1, w, h) gt_bboxes_ignore = create_random_bboxes(1, w, h) results['gt_bboxes'] = gt_bboxes results['gt_bboxes_ignore'] = gt_bboxes_ignore transform = dict(type='MinIoURandomCrop') crop_module = build_from_cfg(transform, PIPELINES) # Test for img_fields results_test = copy.deepcopy(results) results_test['img1'] = results_test['img'] results_test['img_fields'] = ['img', 'img1'] with pytest.raises(AssertionError): crop_module(results_test) results = crop_module(results) patch = np.array([0, 0, results['img_shape'][1], results['img_shape'][0]]) ious = bbox_overlaps(patch.reshape(-1, 4), results['gt_bboxes']).reshape(-1) ious_ignore = bbox_overlaps( patch.reshape(-1, 4), results['gt_bboxes_ignore']).reshape(-1) mode = crop_module.mode if mode == 1: assert np.equal(results['gt_bboxes'], gt_bboxes).all() assert np.equal(results['gt_bboxes_ignore'], gt_bboxes_ignore).all() else: assert (ious >= mode).all() assert (ious_ignore >= mode).all() def test_pad(): # test assertion if both size_divisor and size is None with pytest.raises(AssertionError): transform = dict(type='Pad') build_from_cfg(transform, PIPELINES) transform = dict(type='Pad', size_divisor=32) transform = build_from_cfg(transform, PIPELINES) results = dict() img = mmcv.imread( osp.join(osp.dirname(__file__), '../data/color.jpg'), 'color') original_img = copy.deepcopy(img) results['img'] = img results['img2'] = copy.deepcopy(img) results['img_shape'] = img.shape results['ori_shape'] = img.shape # Set initial values for default meta_keys results['pad_shape'] = img.shape results['scale_factor'] = 1.0 results['img_fields'] = ['img', 'img2'] results = transform(results) assert np.equal(results['img'], results['img2']).all() # original img already divisible by 32 assert np.equal(results['img'], original_img).all() img_shape = results['img'].shape assert img_shape[0] % 32 == 0 assert img_shape[1] % 32 == 0 resize_transform = dict( type='Resize', img_scale=(1333, 800), keep_ratio=True) resize_module = build_from_cfg(resize_transform, PIPELINES) results = resize_module(results) results = transform(results) img_shape = results['img'].shape assert np.equal(results['img'], results['img2']).all() assert img_shape[0] % 32 == 0 assert img_shape[1] % 32 == 0 def test_normalize(): img_norm_cfg = dict( mean=[123.675, 116.28, 103.53], std=[58.395, 57.12, 57.375], to_rgb=True) transform = dict(type='Normalize', **img_norm_cfg) transform = build_from_cfg(transform, PIPELINES) results = dict() img = mmcv.imread( osp.join(osp.dirname(__file__), '../data/color.jpg'), 'color') original_img = copy.deepcopy(img) results['img'] = img results['img2'] = copy.deepcopy(img) results['img_shape'] = img.shape results['ori_shape'] = img.shape # Set initial values for default meta_keys results['pad_shape'] = img.shape results['scale_factor'] = 1.0 results['img_fields'] = ['img', 'img2'] results = transform(results) assert np.equal(results['img'], results['img2']).all() mean = np.array(img_norm_cfg['mean']) std = np.array(img_norm_cfg['std']) converted_img = (original_img[..., ::-1] - mean) / std assert np.allclose(results['img'], converted_img) def test_albu_transform(): results = dict( img_prefix=osp.join(osp.dirname(__file__), '../data'), img_info=dict(filename='color.jpg')) # Define simple pipeline load = dict(type='LoadImageFromFile') load = build_from_cfg(load, PIPELINES) albu_transform = dict( type='Albu', transforms=[dict(type='ChannelShuffle', p=1)]) albu_transform = build_from_cfg(albu_transform, PIPELINES) normalize = dict(type='Normalize', mean=[0] * 3, std=[0] * 3, to_rgb=True) normalize = build_from_cfg(normalize, PIPELINES) # Execute transforms results = load(results) results = albu_transform(results) results = normalize(results) assert results['img'].dtype == np.float32 def test_random_center_crop_pad(): # test assertion for invalid crop_size while test_mode=False with pytest.raises(AssertionError): transform = dict( type='RandomCenterCropPad', crop_size=(-1, 0), test_mode=False, test_pad_mode=None) build_from_cfg(transform, PIPELINES) # test assertion for invalid ratios while test_mode=False with pytest.raises(AssertionError): transform = dict( type='RandomCenterCropPad', crop_size=(511, 511), ratios=(1.0), test_mode=False, test_pad_mode=None) build_from_cfg(transform, PIPELINES) # test assertion for invalid mean, std and to_rgb with pytest.raises(AssertionError): transform = dict( type='RandomCenterCropPad', crop_size=(511, 511), mean=None, std=None, to_rgb=None, test_mode=False, test_pad_mode=None) build_from_cfg(transform, PIPELINES) # test assertion for invalid crop_size while test_mode=True with pytest.raises(AssertionError): transform = dict( type='RandomCenterCropPad', crop_size=(511, 511), ratios=None, border=None, mean=[123.675, 116.28, 103.53], std=[58.395, 57.12, 57.375], to_rgb=True, test_mode=True, test_pad_mode=('logical_or', 127)) build_from_cfg(transform, PIPELINES) # test assertion for invalid ratios while test_mode=True with pytest.raises(AssertionError): transform = dict( type='RandomCenterCropPad', crop_size=None, ratios=(0.9, 1.0, 1.1), border=None, mean=[123.675, 116.28, 103.53], std=[58.395, 57.12, 57.375], to_rgb=True, test_mode=True, test_pad_mode=('logical_or', 127)) build_from_cfg(transform, PIPELINES) # test assertion for invalid border while test_mode=True with pytest.raises(AssertionError): transform = dict( type='RandomCenterCropPad', crop_size=None, ratios=None, border=128, mean=[123.675, 116.28, 103.53], std=[58.395, 57.12, 57.375], to_rgb=True, test_mode=True, test_pad_mode=('logical_or', 127)) build_from_cfg(transform, PIPELINES) # test assertion for invalid test_pad_mode while test_mode=True with pytest.raises(AssertionError): transform = dict( type='RandomCenterCropPad', crop_size=None, ratios=None, border=None, mean=[123.675, 116.28, 103.53], std=[58.395, 57.12, 57.375], to_rgb=True, test_mode=True, test_pad_mode=('do_nothing', 100)) build_from_cfg(transform, PIPELINES) results = dict( img_prefix=osp.join(osp.dirname(__file__), '../data'), img_info=dict(filename='color.jpg')) load = dict(type='LoadImageFromFile', to_float32=True) load = build_from_cfg(load, PIPELINES) results = load(results) test_results = copy.deepcopy(results) def create_random_bboxes(num_bboxes, img_w, img_h): bboxes_left_top = np.random.uniform(0, 0.5, size=(num_bboxes, 2)) bboxes_right_bottom = np.random.uniform(0.5, 1, size=(num_bboxes, 2)) bboxes = np.concatenate((bboxes_left_top, bboxes_right_bottom), 1) bboxes = (bboxes * np.array([img_w, img_h, img_w, img_h])).astype( np.int) return bboxes h, w, _ = results['img_shape'] gt_bboxes = create_random_bboxes(8, w, h) gt_bboxes_ignore = create_random_bboxes(2, w, h) results['gt_bboxes'] = gt_bboxes results['gt_bboxes_ignore'] = gt_bboxes_ignore train_transform = dict( type='RandomCenterCropPad', crop_size=(h - 20, w - 20), ratios=(1.0, ), border=128, mean=[123.675, 116.28, 103.53], std=[58.395, 57.12, 57.375], to_rgb=True, test_mode=False, test_pad_mode=None) crop_module = build_from_cfg(train_transform, PIPELINES) train_results = crop_module(results) assert train_results['img'].shape[:2] == (h - 20, w - 20) # All bboxes should be reserved after crop assert train_results['pad_shape'][:2] == (h - 20, w - 20) assert train_results['gt_bboxes'].shape[0] == 8 assert train_results['gt_bboxes_ignore'].shape[0] == 2 test_transform = dict( type='RandomCenterCropPad', crop_size=None, ratios=None, border=None, mean=[123.675, 116.28, 103.53], std=[58.395, 57.12, 57.375], to_rgb=True, test_mode=True, test_pad_mode=('logical_or', 127)) crop_module = build_from_cfg(test_transform, PIPELINES) test_results = crop_module(test_results) assert test_results['img'].shape[:2] == (h | 127, w | 127) assert test_results['pad_shape'][:2] == (h | 127, w | 127) assert 'border' in test_results def test_multi_scale_flip_aug(): # test assertion if give both scale_factor and img_scale with pytest.raises(AssertionError): transform = dict( type='MultiScaleFlipAug', scale_factor=1.0, img_scale=[(1333, 800)], transforms=[dict(type='Resize')]) build_from_cfg(transform, PIPELINES) # test assertion if both scale_factor and img_scale are None with pytest.raises(AssertionError): transform = dict( type='MultiScaleFlipAug', scale_factor=None, img_scale=None, transforms=[dict(type='Resize')]) build_from_cfg(transform, PIPELINES) # test assertion if img_scale is not tuple or list of tuple with pytest.raises(AssertionError): transform = dict( type='MultiScaleFlipAug', img_scale=[1333, 800], transforms=[dict(type='Resize')]) build_from_cfg(transform, PIPELINES) # test assertion if flip_direction is not str or list of str with pytest.raises(AssertionError): transform = dict( type='MultiScaleFlipAug', img_scale=[(1333, 800)], flip_direction=1, transforms=[dict(type='Resize')]) build_from_cfg(transform, PIPELINES) scale_transform = dict( type='MultiScaleFlipAug', img_scale=[(1333, 800), (1333, 640)], transforms=[dict(type='Resize', keep_ratio=True)]) transform = build_from_cfg(scale_transform, PIPELINES) results = dict() img = mmcv.imread( osp.join(osp.dirname(__file__), '../data/color.jpg'), 'color') results['img'] = img results['img_shape'] = img.shape results['ori_shape'] = img.shape # Set initial values for default meta_keys results['pad_shape'] = img.shape results['img_fields'] = ['img'] scale_results = transform(copy.deepcopy(results)) assert len(scale_results['img']) == 2 assert scale_results['img'][0].shape == (750, 1333, 3) assert scale_results['img_shape'][0] == (750, 1333, 3) assert scale_results['img'][1].shape == (640, 1138, 3) assert scale_results['img_shape'][1] == (640, 1138, 3) scale_factor_transform = dict( type='MultiScaleFlipAug', scale_factor=[0.8, 1.0, 1.2], transforms=[dict(type='Resize', keep_ratio=False)]) transform = build_from_cfg(scale_factor_transform, PIPELINES) scale_factor_results = transform(copy.deepcopy(results)) assert len(scale_factor_results['img']) == 3 assert scale_factor_results['img'][0].shape == (230, 409, 3) assert scale_factor_results['img_shape'][0] == (230, 409, 3) assert scale_factor_results['img'][1].shape == (288, 512, 3) assert scale_factor_results['img_shape'][1] == (288, 512, 3) assert scale_factor_results['img'][2].shape == (345, 614, 3) assert scale_factor_results['img_shape'][2] == (345, 614, 3) # test pipeline of coco_detection results = dict( img_prefix=osp.join(osp.dirname(__file__), '../data'), img_info=dict(filename='color.jpg')) load_cfg, multi_scale_cfg = mmcv.Config.fromfile( 'configs/_base_/datasets/coco_detection.py').test_pipeline load = build_from_cfg(load_cfg, PIPELINES) transform = build_from_cfg(multi_scale_cfg, PIPELINES) results = transform(load(results)) assert len(results['img']) == 1 assert len(results['img_metas']) == 1 assert isinstance(results['img'][0], torch.Tensor) assert isinstance(results['img_metas'][0], mmcv.parallel.DataContainer) assert results['img_metas'][0].data['ori_shape'] == (288, 512, 3) assert results['img_metas'][0].data['img_shape'] == (750, 1333, 3) assert results['img_metas'][0].data['pad_shape'] == (768, 1344, 3) assert results['img_metas'][0].data['scale_factor'].tolist() == [ 2.603515625, 2.6041667461395264, 2.603515625, 2.6041667461395264 ] def test_cutout(): # test n_holes with pytest.raises(AssertionError): transform = dict(type='CutOut', n_holes=(5, 3), cutout_shape=(8, 8)) build_from_cfg(transform, PIPELINES) with pytest.raises(AssertionError): transform = dict(type='CutOut', n_holes=(3, 4, 5), cutout_shape=(8, 8)) build_from_cfg(transform, PIPELINES) # test cutout_shape and cutout_ratio with pytest.raises(AssertionError): transform = dict(type='CutOut', n_holes=1, cutout_shape=8) build_from_cfg(transform, PIPELINES) with pytest.raises(AssertionError): transform = dict(type='CutOut', n_holes=1, cutout_ratio=0.2) build_from_cfg(transform, PIPELINES) # either of cutout_shape and cutout_ratio should be given with pytest.raises(AssertionError): transform = dict(type='CutOut', n_holes=1) build_from_cfg(transform, PIPELINES) with pytest.raises(AssertionError): transform = dict( type='CutOut', n_holes=1, cutout_shape=(2, 2), cutout_ratio=(0.4, 0.4)) build_from_cfg(transform, PIPELINES) results = dict() img = mmcv.imread( osp.join(osp.dirname(__file__), '../data/color.jpg'), 'color') results['img'] = img results['img_shape'] = img.shape results['ori_shape'] = img.shape results['pad_shape'] = img.shape results['img_fields'] = ['img'] transform = dict(type='CutOut', n_holes=1, cutout_shape=(10, 10)) cutout_module = build_from_cfg(transform, PIPELINES) cutout_result = cutout_module(copy.deepcopy(results)) assert cutout_result['img'].sum() < img.sum() transform = dict(type='CutOut', n_holes=1, cutout_ratio=(0.8, 0.8)) cutout_module = build_from_cfg(transform, PIPELINES) cutout_result = cutout_module(copy.deepcopy(results)) assert cutout_result['img'].sum() < img.sum() transform = dict( type='CutOut', n_holes=(2, 4), cutout_shape=[(10, 10), (15, 15)], fill_in=(255, 255, 255)) cutout_module = build_from_cfg(transform, PIPELINES) cutout_result = cutout_module(copy.deepcopy(results)) assert cutout_result['img'].sum() > img.sum() transform = dict( type='CutOut', n_holes=1, cutout_ratio=(0.8, 0.8), fill_in=(255, 255, 255)) cutout_module = build_from_cfg(transform, PIPELINES) cutout_result = cutout_module(copy.deepcopy(results)) assert cutout_result['img'].sum() > img.sum()
25,008
35.886431
79
py
GFocalV2
GFocalV2-master/tests/test_data/test_sampler.py
import torch from mmdet.core.bbox.assigners import MaxIoUAssigner from mmdet.core.bbox.samplers import (OHEMSampler, RandomSampler, ScoreHLRSampler) def test_random_sampler(): assigner = MaxIoUAssigner( pos_iou_thr=0.5, neg_iou_thr=0.5, ignore_iof_thr=0.5, ignore_wrt_candidates=False, ) bboxes = torch.FloatTensor([ [0, 0, 10, 10], [10, 10, 20, 20], [5, 5, 15, 15], [32, 32, 38, 42], ]) gt_bboxes = torch.FloatTensor([ [0, 0, 10, 9], [0, 10, 10, 19], ]) gt_labels = torch.LongTensor([1, 2]) gt_bboxes_ignore = torch.Tensor([ [30, 30, 40, 40], ]) assign_result = assigner.assign( bboxes, gt_bboxes, gt_bboxes_ignore=gt_bboxes_ignore, gt_labels=gt_labels) sampler = RandomSampler( num=10, pos_fraction=0.5, neg_pos_ub=-1, add_gt_as_proposals=True) sample_result = sampler.sample(assign_result, bboxes, gt_bboxes, gt_labels) assert len(sample_result.pos_bboxes) == len(sample_result.pos_inds) assert len(sample_result.neg_bboxes) == len(sample_result.neg_inds) def test_random_sampler_empty_gt(): assigner = MaxIoUAssigner( pos_iou_thr=0.5, neg_iou_thr=0.5, ignore_iof_thr=0.5, ignore_wrt_candidates=False, ) bboxes = torch.FloatTensor([ [0, 0, 10, 10], [10, 10, 20, 20], [5, 5, 15, 15], [32, 32, 38, 42], ]) gt_bboxes = torch.empty(0, 4) gt_labels = torch.empty(0, ).long() assign_result = assigner.assign(bboxes, gt_bboxes, gt_labels=gt_labels) sampler = RandomSampler( num=10, pos_fraction=0.5, neg_pos_ub=-1, add_gt_as_proposals=True) sample_result = sampler.sample(assign_result, bboxes, gt_bboxes, gt_labels) assert len(sample_result.pos_bboxes) == len(sample_result.pos_inds) assert len(sample_result.neg_bboxes) == len(sample_result.neg_inds) def test_random_sampler_empty_pred(): assigner = MaxIoUAssigner( pos_iou_thr=0.5, neg_iou_thr=0.5, ignore_iof_thr=0.5, ignore_wrt_candidates=False, ) bboxes = torch.empty(0, 4) gt_bboxes = torch.FloatTensor([ [0, 0, 10, 9], [0, 10, 10, 19], ]) gt_labels = torch.LongTensor([1, 2]) assign_result = assigner.assign(bboxes, gt_bboxes, gt_labels=gt_labels) sampler = RandomSampler( num=10, pos_fraction=0.5, neg_pos_ub=-1, add_gt_as_proposals=True) sample_result = sampler.sample(assign_result, bboxes, gt_bboxes, gt_labels) assert len(sample_result.pos_bboxes) == len(sample_result.pos_inds) assert len(sample_result.neg_bboxes) == len(sample_result.neg_inds) def _context_for_ohem(): import sys from os.path import dirname sys.path.insert(0, dirname(dirname(dirname(__file__)))) from test_forward import _get_detector_cfg model, train_cfg, test_cfg = _get_detector_cfg( 'faster_rcnn/faster_rcnn_r50_fpn_ohem_1x_coco.py') model['pretrained'] = None from mmdet.models import build_detector context = build_detector( model, train_cfg=train_cfg, test_cfg=test_cfg).roi_head return context def test_ohem_sampler(): assigner = MaxIoUAssigner( pos_iou_thr=0.5, neg_iou_thr=0.5, ignore_iof_thr=0.5, ignore_wrt_candidates=False, ) bboxes = torch.FloatTensor([ [0, 0, 10, 10], [10, 10, 20, 20], [5, 5, 15, 15], [32, 32, 38, 42], ]) gt_bboxes = torch.FloatTensor([ [0, 0, 10, 9], [0, 10, 10, 19], ]) gt_labels = torch.LongTensor([1, 2]) gt_bboxes_ignore = torch.Tensor([ [30, 30, 40, 40], ]) assign_result = assigner.assign( bboxes, gt_bboxes, gt_bboxes_ignore=gt_bboxes_ignore, gt_labels=gt_labels) context = _context_for_ohem() sampler = OHEMSampler( num=10, pos_fraction=0.5, context=context, neg_pos_ub=-1, add_gt_as_proposals=True) feats = [torch.rand(1, 256, int(2**i), int(2**i)) for i in [6, 5, 4, 3, 2]] sample_result = sampler.sample( assign_result, bboxes, gt_bboxes, gt_labels, feats=feats) assert len(sample_result.pos_bboxes) == len(sample_result.pos_inds) assert len(sample_result.neg_bboxes) == len(sample_result.neg_inds) def test_ohem_sampler_empty_gt(): assigner = MaxIoUAssigner( pos_iou_thr=0.5, neg_iou_thr=0.5, ignore_iof_thr=0.5, ignore_wrt_candidates=False, ) bboxes = torch.FloatTensor([ [0, 0, 10, 10], [10, 10, 20, 20], [5, 5, 15, 15], [32, 32, 38, 42], ]) gt_bboxes = torch.empty(0, 4) gt_labels = torch.LongTensor([]) gt_bboxes_ignore = torch.Tensor([]) assign_result = assigner.assign( bboxes, gt_bboxes, gt_bboxes_ignore=gt_bboxes_ignore, gt_labels=gt_labels) context = _context_for_ohem() sampler = OHEMSampler( num=10, pos_fraction=0.5, context=context, neg_pos_ub=-1, add_gt_as_proposals=True) feats = [torch.rand(1, 256, int(2**i), int(2**i)) for i in [6, 5, 4, 3, 2]] sample_result = sampler.sample( assign_result, bboxes, gt_bboxes, gt_labels, feats=feats) assert len(sample_result.pos_bboxes) == len(sample_result.pos_inds) assert len(sample_result.neg_bboxes) == len(sample_result.neg_inds) def test_ohem_sampler_empty_pred(): assigner = MaxIoUAssigner( pos_iou_thr=0.5, neg_iou_thr=0.5, ignore_iof_thr=0.5, ignore_wrt_candidates=False, ) bboxes = torch.empty(0, 4) gt_bboxes = torch.FloatTensor([ [0, 0, 10, 10], [10, 10, 20, 20], [5, 5, 15, 15], [32, 32, 38, 42], ]) gt_labels = torch.LongTensor([1, 2, 2, 3]) gt_bboxes_ignore = torch.Tensor([]) assign_result = assigner.assign( bboxes, gt_bboxes, gt_bboxes_ignore=gt_bboxes_ignore, gt_labels=gt_labels) context = _context_for_ohem() sampler = OHEMSampler( num=10, pos_fraction=0.5, context=context, neg_pos_ub=-1, add_gt_as_proposals=True) feats = [torch.rand(1, 256, int(2**i), int(2**i)) for i in [6, 5, 4, 3, 2]] sample_result = sampler.sample( assign_result, bboxes, gt_bboxes, gt_labels, feats=feats) assert len(sample_result.pos_bboxes) == len(sample_result.pos_inds) assert len(sample_result.neg_bboxes) == len(sample_result.neg_inds) def test_random_sample_result(): from mmdet.core.bbox.samplers.sampling_result import SamplingResult SamplingResult.random(num_gts=0, num_preds=0) SamplingResult.random(num_gts=0, num_preds=3) SamplingResult.random(num_gts=3, num_preds=3) SamplingResult.random(num_gts=0, num_preds=3) SamplingResult.random(num_gts=7, num_preds=7) SamplingResult.random(num_gts=7, num_preds=64) SamplingResult.random(num_gts=24, num_preds=3) for i in range(3): SamplingResult.random(rng=i) def test_score_hlr_sampler_empty_pred(): assigner = MaxIoUAssigner( pos_iou_thr=0.5, neg_iou_thr=0.5, ignore_iof_thr=0.5, ignore_wrt_candidates=False, ) context = _context_for_ohem() sampler = ScoreHLRSampler( num=10, pos_fraction=0.5, context=context, neg_pos_ub=-1, add_gt_as_proposals=True) gt_bboxes_ignore = torch.Tensor([]) feats = [torch.rand(1, 256, int(2**i), int(2**i)) for i in [6, 5, 4, 3, 2]] # empty bbox bboxes = torch.empty(0, 4) gt_bboxes = torch.FloatTensor([ [0, 0, 10, 10], [10, 10, 20, 20], [5, 5, 15, 15], [32, 32, 38, 42], ]) gt_labels = torch.LongTensor([1, 2, 2, 3]) assign_result = assigner.assign( bboxes, gt_bboxes, gt_bboxes_ignore=gt_bboxes_ignore, gt_labels=gt_labels) sample_result, _ = sampler.sample( assign_result, bboxes, gt_bboxes, gt_labels, feats=feats) assert len(sample_result.neg_inds) == 0 assert len(sample_result.pos_bboxes) == len(sample_result.pos_inds) assert len(sample_result.neg_bboxes) == len(sample_result.neg_inds) # empty gt bboxes = torch.FloatTensor([ [0, 0, 10, 10], [10, 10, 20, 20], [5, 5, 15, 15], [32, 32, 38, 42], ]) gt_bboxes = torch.empty(0, 4) gt_labels = torch.LongTensor([]) assign_result = assigner.assign( bboxes, gt_bboxes, gt_bboxes_ignore=gt_bboxes_ignore, gt_labels=gt_labels) sample_result, _ = sampler.sample( assign_result, bboxes, gt_bboxes, gt_labels, feats=feats) assert len(sample_result.pos_inds) == 0 assert len(sample_result.pos_bboxes) == len(sample_result.pos_inds) assert len(sample_result.neg_bboxes) == len(sample_result.neg_inds) # non-empty input bboxes = torch.FloatTensor([ [0, 0, 10, 10], [10, 10, 20, 20], [5, 5, 15, 15], [32, 32, 38, 42], ]) gt_bboxes = torch.FloatTensor([ [0, 0, 10, 10], [10, 10, 20, 20], [5, 5, 15, 15], [32, 32, 38, 42], ]) gt_labels = torch.LongTensor([1, 2, 2, 3]) assign_result = assigner.assign( bboxes, gt_bboxes, gt_bboxes_ignore=gt_bboxes_ignore, gt_labels=gt_labels) sample_result, _ = sampler.sample( assign_result, bboxes, gt_bboxes, gt_labels, feats=feats) assert len(sample_result.pos_bboxes) == len(sample_result.pos_inds) assert len(sample_result.neg_bboxes) == len(sample_result.neg_inds)
9,745
28.533333
79
py
GFocalV2
GFocalV2-master/tests/test_data/test_models_aug_test.py
import os.path as osp import mmcv import torch from mmcv.parallel import collate from mmcv.utils import build_from_cfg from mmdet.datasets.builder import PIPELINES from mmdet.models import build_detector def model_aug_test_template(cfg_file): # get config cfg = mmcv.Config.fromfile(cfg_file) # init model cfg.model.pretrained = None model = build_detector(cfg.model, train_cfg=None, test_cfg=cfg.test_cfg) # init test pipeline and set aug test load_cfg, multi_scale_cfg = cfg.test_pipeline multi_scale_cfg['flip'] = True multi_scale_cfg['img_scale'] = [(1333, 800), (800, 600), (640, 480)] load = build_from_cfg(load_cfg, PIPELINES) transform = build_from_cfg(multi_scale_cfg, PIPELINES) results = dict( img_prefix=osp.join(osp.dirname(__file__), '../data'), img_info=dict(filename='color.jpg')) results = transform(load(results)) assert len(results['img']) == 6 assert len(results['img_metas']) == 6 results['img'] = [collate([x]) for x in results['img']] results['img_metas'] = [collate([x]).data[0] for x in results['img_metas']] # aug test the model model.eval() with torch.no_grad(): aug_result = model(return_loss=False, rescale=True, **results) return aug_result def test_aug_test_size(): results = dict( img_prefix=osp.join(osp.dirname(__file__), '../data'), img_info=dict(filename='color.jpg')) # Define simple pipeline load = dict(type='LoadImageFromFile') load = build_from_cfg(load, PIPELINES) # get config transform = dict( type='MultiScaleFlipAug', transforms=[], img_scale=[(1333, 800), (800, 600), (640, 480)], flip=True, flip_direction=['horizontal', 'vertical']) multi_aug_test_module = build_from_cfg(transform, PIPELINES) results = load(results) results = multi_aug_test_module(load(results)) # len(["original", "horizontal", "vertical"]) * # len([(1333, 800), (800, 600), (640, 480)]) assert len(results['img']) == 9 def test_cascade_rcnn_aug_test(): aug_result = model_aug_test_template( 'configs/cascade_rcnn/cascade_rcnn_r50_fpn_1x_coco.py') assert len(aug_result[0]) == 80 def test_mask_rcnn_aug_test(): aug_result = model_aug_test_template( 'configs/mask_rcnn/mask_rcnn_r50_fpn_1x_coco.py') assert len(aug_result[0]) == 2 assert len(aug_result[0][0]) == 80 assert len(aug_result[0][1]) == 80 def test_htc_aug_test(): aug_result = model_aug_test_template('configs/htc/htc_r50_fpn_1x_coco.py') assert len(aug_result[0]) == 2 assert len(aug_result[0][0]) == 80 assert len(aug_result[0][1]) == 80 def test_cornernet_aug_test(): # get config cfg = mmcv.Config.fromfile( 'configs/cornernet/cornernet_hourglass104_mstest_10x5_210e_coco.py') # init model cfg.model.pretrained = None model = build_detector(cfg.model, train_cfg=None, test_cfg=cfg.test_cfg) # init test pipeline and set aug test load_cfg, multi_scale_cfg = cfg.test_pipeline multi_scale_cfg['flip'] = True multi_scale_cfg['scale_factor'] = [0.5, 1.0, 2.0] load = build_from_cfg(load_cfg, PIPELINES) transform = build_from_cfg(multi_scale_cfg, PIPELINES) results = dict( img_prefix=osp.join(osp.dirname(__file__), '../data'), img_info=dict(filename='color.jpg')) results = transform(load(results)) assert len(results['img']) == 6 assert len(results['img_metas']) == 6 results['img'] = [collate([x]) for x in results['img']] results['img_metas'] = [collate([x]).data[0] for x in results['img_metas']] # aug test the model model.eval() with torch.no_grad(): aug_result = model(return_loss=False, rescale=True, **results) assert len(aug_result[0]) == 80
3,843
31.302521
79
py
GFocalV2
GFocalV2-master/demo/webcam_demo.py
import argparse import cv2 import torch from mmdet.apis import inference_detector, init_detector def parse_args(): parser = argparse.ArgumentParser(description='MMDetection webcam demo') parser.add_argument('config', help='test config file path') parser.add_argument('checkpoint', help='checkpoint file') parser.add_argument( '--device', type=str, default='cuda:0', help='CPU/CUDA device option') parser.add_argument( '--camera-id', type=int, default=0, help='camera device id') parser.add_argument( '--score-thr', type=float, default=0.5, help='bbox score threshold') args = parser.parse_args() return args def main(): args = parse_args() device = torch.device(args.device) model = init_detector(args.config, args.checkpoint, device=device) camera = cv2.VideoCapture(args.camera_id) print('Press "Esc", "q" or "Q" to exit.') while True: ret_val, img = camera.read() result = inference_detector(model, img) ch = cv2.waitKey(1) if ch == 27 or ch == ord('q') or ch == ord('Q'): break model.show_result( img, result, score_thr=args.score_thr, wait_time=1, show=True) if __name__ == '__main__': main()
1,260
25.829787
78
py
GFocalV2
GFocalV2-master/configs/ghm/retinanet_ghm_x101_32x4d_fpn_1x_coco.py
_base_ = './retinanet_ghm_r50_fpn_1x_coco.py' model = dict( pretrained='open-mmlab://resnext101_32x4d', backbone=dict( type='ResNeXt', depth=101, groups=32, base_width=4, num_stages=4, out_indices=(0, 1, 2, 3), frozen_stages=1, norm_cfg=dict(type='BN', requires_grad=True), style='pytorch'))
372
25.642857
53
py
GFocalV2
GFocalV2-master/configs/ghm/retinanet_ghm_r101_fpn_1x_coco.py
_base_ = './retinanet_ghm_r50_fpn_1x_coco.py' model = dict(pretrained='torchvision://resnet101', backbone=dict(depth=101))
123
40.333333
76
py
GFocalV2
GFocalV2-master/configs/ghm/retinanet_ghm_x101_64x4d_fpn_1x_coco.py
_base_ = './retinanet_ghm_r50_fpn_1x_coco.py' model = dict( pretrained='open-mmlab://resnext101_64x4d', backbone=dict( type='ResNeXt', depth=101, groups=64, base_width=4, num_stages=4, out_indices=(0, 1, 2, 3), frozen_stages=1, norm_cfg=dict(type='BN', requires_grad=True), style='pytorch'))
372
25.642857
53
py
GFocalV2
GFocalV2-master/configs/dcn/faster_rcnn_x101_32x4d_fpn_dconv_c3-c5_1x_coco.py
_base_ = '../faster_rcnn/faster_rcnn_r50_fpn_1x_coco.py' model = dict( pretrained='open-mmlab://resnext101_32x4d', backbone=dict( type='ResNeXt', depth=101, groups=32, base_width=4, num_stages=4, out_indices=(0, 1, 2, 3), frozen_stages=1, norm_cfg=dict(type='BN', requires_grad=True), style='pytorch', dcn=dict(type='DCN', deform_groups=1, fallback_on_stride=False), stage_with_dcn=(False, True, True, True)))
506
30.6875
72
py
GFocalV2
GFocalV2-master/configs/htc/htc_x101_64x4d_fpn_16x1_20e_coco.py
_base_ = './htc_r50_fpn_1x_coco.py' model = dict( pretrained='open-mmlab://resnext101_64x4d', backbone=dict( type='ResNeXt', depth=101, groups=64, base_width=4, num_stages=4, out_indices=(0, 1, 2, 3), frozen_stages=1, norm_cfg=dict(type='BN', requires_grad=True), norm_eval=True, style='pytorch')) data = dict(samples_per_gpu=1, workers_per_gpu=1) # learning policy lr_config = dict(step=[16, 19]) total_epochs = 20
504
25.578947
53
py
GFocalV2
GFocalV2-master/configs/htc/htc_without_semantic_r50_fpn_1x_coco.py
_base_ = [ '../_base_/datasets/coco_instance.py', '../_base_/schedules/schedule_1x.py', '../_base_/default_runtime.py' ] # model settings model = dict( type='HybridTaskCascade', pretrained='torchvision://resnet50', backbone=dict( type='ResNet', depth=50, num_stages=4, out_indices=(0, 1, 2, 3), frozen_stages=1, norm_cfg=dict(type='BN', requires_grad=True), norm_eval=True, style='pytorch'), neck=dict( type='FPN', in_channels=[256, 512, 1024, 2048], out_channels=256, num_outs=5), rpn_head=dict( type='RPNHead', in_channels=256, feat_channels=256, anchor_generator=dict( type='AnchorGenerator', scales=[8], ratios=[0.5, 1.0, 2.0], strides=[4, 8, 16, 32, 64]), bbox_coder=dict( type='DeltaXYWHBBoxCoder', target_means=[.0, .0, .0, .0], target_stds=[1.0, 1.0, 1.0, 1.0]), loss_cls=dict( type='CrossEntropyLoss', use_sigmoid=True, loss_weight=1.0), loss_bbox=dict(type='SmoothL1Loss', beta=1.0 / 9.0, loss_weight=1.0)), roi_head=dict( type='HybridTaskCascadeRoIHead', interleaved=True, mask_info_flow=True, num_stages=3, stage_loss_weights=[1, 0.5, 0.25], bbox_roi_extractor=dict( type='SingleRoIExtractor', roi_layer=dict(type='RoIAlign', output_size=7, sampling_ratio=0), out_channels=256, featmap_strides=[4, 8, 16, 32]), bbox_head=[ dict( type='Shared2FCBBoxHead', in_channels=256, fc_out_channels=1024, roi_feat_size=7, num_classes=80, bbox_coder=dict( type='DeltaXYWHBBoxCoder', target_means=[0., 0., 0., 0.], target_stds=[0.1, 0.1, 0.2, 0.2]), reg_class_agnostic=True, loss_cls=dict( type='CrossEntropyLoss', use_sigmoid=False, loss_weight=1.0), loss_bbox=dict(type='SmoothL1Loss', beta=1.0, loss_weight=1.0)), dict( type='Shared2FCBBoxHead', in_channels=256, fc_out_channels=1024, roi_feat_size=7, num_classes=80, bbox_coder=dict( type='DeltaXYWHBBoxCoder', target_means=[0., 0., 0., 0.], target_stds=[0.05, 0.05, 0.1, 0.1]), reg_class_agnostic=True, loss_cls=dict( type='CrossEntropyLoss', use_sigmoid=False, loss_weight=1.0), loss_bbox=dict(type='SmoothL1Loss', beta=1.0, loss_weight=1.0)), dict( type='Shared2FCBBoxHead', in_channels=256, fc_out_channels=1024, roi_feat_size=7, num_classes=80, bbox_coder=dict( type='DeltaXYWHBBoxCoder', target_means=[0., 0., 0., 0.], target_stds=[0.033, 0.033, 0.067, 0.067]), reg_class_agnostic=True, loss_cls=dict( type='CrossEntropyLoss', use_sigmoid=False, loss_weight=1.0), loss_bbox=dict(type='SmoothL1Loss', beta=1.0, loss_weight=1.0)) ], mask_roi_extractor=dict( type='SingleRoIExtractor', roi_layer=dict(type='RoIAlign', output_size=14, sampling_ratio=0), out_channels=256, featmap_strides=[4, 8, 16, 32]), mask_head=[ dict( type='HTCMaskHead', with_conv_res=False, num_convs=4, in_channels=256, conv_out_channels=256, num_classes=80, loss_mask=dict( type='CrossEntropyLoss', use_mask=True, loss_weight=1.0)), dict( type='HTCMaskHead', num_convs=4, in_channels=256, conv_out_channels=256, num_classes=80, loss_mask=dict( type='CrossEntropyLoss', use_mask=True, loss_weight=1.0)), dict( type='HTCMaskHead', num_convs=4, in_channels=256, conv_out_channels=256, num_classes=80, loss_mask=dict( type='CrossEntropyLoss', use_mask=True, loss_weight=1.0)) ])) # model training and testing settings train_cfg = dict( rpn=dict( assigner=dict( type='MaxIoUAssigner', pos_iou_thr=0.7, neg_iou_thr=0.3, min_pos_iou=0.3, ignore_iof_thr=-1), sampler=dict( type='RandomSampler', num=256, pos_fraction=0.5, neg_pos_ub=-1, add_gt_as_proposals=False), allowed_border=0, pos_weight=-1, debug=False), rpn_proposal=dict( nms_across_levels=False, nms_pre=2000, nms_post=2000, max_num=2000, nms_thr=0.7, min_bbox_size=0), rcnn=[ dict( assigner=dict( type='MaxIoUAssigner', pos_iou_thr=0.5, neg_iou_thr=0.5, min_pos_iou=0.5, ignore_iof_thr=-1), sampler=dict( type='RandomSampler', num=512, pos_fraction=0.25, neg_pos_ub=-1, add_gt_as_proposals=True), mask_size=28, pos_weight=-1, debug=False), dict( assigner=dict( type='MaxIoUAssigner', pos_iou_thr=0.6, neg_iou_thr=0.6, min_pos_iou=0.6, ignore_iof_thr=-1), sampler=dict( type='RandomSampler', num=512, pos_fraction=0.25, neg_pos_ub=-1, add_gt_as_proposals=True), mask_size=28, pos_weight=-1, debug=False), dict( assigner=dict( type='MaxIoUAssigner', pos_iou_thr=0.7, neg_iou_thr=0.7, min_pos_iou=0.7, ignore_iof_thr=-1), sampler=dict( type='RandomSampler', num=512, pos_fraction=0.25, neg_pos_ub=-1, add_gt_as_proposals=True), mask_size=28, pos_weight=-1, debug=False) ]) test_cfg = dict( rpn=dict( nms_across_levels=False, nms_pre=1000, nms_post=1000, max_num=1000, nms_thr=0.7, min_bbox_size=0), rcnn=dict( score_thr=0.001, nms=dict(type='nms', iou_threshold=0.5), max_per_img=100, mask_thr_binary=0.5)) img_norm_cfg = dict( mean=[123.675, 116.28, 103.53], std=[58.395, 57.12, 57.375], to_rgb=True) test_pipeline = [ dict(type='LoadImageFromFile'), dict( type='MultiScaleFlipAug', img_scale=(1333, 800), flip=False, transforms=[ dict(type='Resize', keep_ratio=True), dict(type='RandomFlip', flip_ratio=0.5), dict(type='Normalize', **img_norm_cfg), dict(type='Pad', size_divisor=32), dict(type='ImageToTensor', keys=['img']), dict(type='Collect', keys=['img']), ]) ] data = dict( val=dict(pipeline=test_pipeline), test=dict(pipeline=test_pipeline))
8,009
32.236515
79
py
GFocalV2
GFocalV2-master/configs/htc/htc_x101_32x4d_fpn_16x1_20e_coco.py
_base_ = './htc_r50_fpn_1x_coco.py' model = dict( pretrained='open-mmlab://resnext101_32x4d', backbone=dict( type='ResNeXt', depth=101, groups=32, base_width=4, num_stages=4, out_indices=(0, 1, 2, 3), frozen_stages=1, norm_cfg=dict(type='BN', requires_grad=True), norm_eval=True, style='pytorch')) data = dict(samples_per_gpu=1, workers_per_gpu=1) # learning policy lr_config = dict(step=[16, 19]) total_epochs = 20
504
25.578947
53
py
GFocalV2
GFocalV2-master/configs/htc/htc_x101_64x4d_fpn_dconv_c3-c5_mstrain_400_1400_16x1_20e_coco.py
_base_ = './htc_r50_fpn_1x_coco.py' model = dict( pretrained='open-mmlab://resnext101_64x4d', backbone=dict( type='ResNeXt', depth=101, groups=64, base_width=4, num_stages=4, out_indices=(0, 1, 2, 3), frozen_stages=1, norm_cfg=dict(type='BN', requires_grad=True), norm_eval=True, style='pytorch', dcn=dict(type='DCN', deform_groups=1, fallback_on_stride=False), stage_with_dcn=(False, True, True, True))) # dataset settings img_norm_cfg = dict( mean=[123.675, 116.28, 103.53], std=[58.395, 57.12, 57.375], to_rgb=True) train_pipeline = [ dict(type='LoadImageFromFile'), dict( type='LoadAnnotations', with_bbox=True, with_mask=True, with_seg=True), dict( type='Resize', img_scale=[(1600, 400), (1600, 1400)], multiscale_mode='range', keep_ratio=True), dict(type='RandomFlip', flip_ratio=0.5), dict(type='Normalize', **img_norm_cfg), dict(type='Pad', size_divisor=32), dict(type='SegRescale', scale_factor=1 / 8), dict(type='DefaultFormatBundle'), dict( type='Collect', keys=['img', 'gt_bboxes', 'gt_labels', 'gt_masks', 'gt_semantic_seg']), ] data = dict( samples_per_gpu=1, workers_per_gpu=1, train=dict(pipeline=train_pipeline)) # learning policy lr_config = dict(step=[16, 19]) total_epochs = 20
1,402
31.627907
79
py
GFocalV2
GFocalV2-master/configs/htc/htc_r101_fpn_20e_coco.py
_base_ = './htc_r50_fpn_1x_coco.py' model = dict(pretrained='torchvision://resnet101', backbone=dict(depth=101)) # learning policy lr_config = dict(step=[16, 19]) total_epochs = 20
181
29.333333
76
py
GFocalV2
GFocalV2-master/configs/reppoints/reppoints_moment_r101_fpn_dconv_c3-c5_gn-neck+head_2x_coco.py
_base_ = './reppoints_moment_r50_fpn_gn-neck+head_2x_coco.py' model = dict( pretrained='torchvision://resnet101', backbone=dict( depth=101, dcn=dict(type='DCN', deform_groups=1, fallback_on_stride=False), stage_with_dcn=(False, True, True, True)))
280
34.125
72
py
GFocalV2
GFocalV2-master/configs/reppoints/reppoints_moment_r101_fpn_gn-neck+head_2x_coco.py
_base_ = './reppoints_moment_r50_fpn_gn-neck+head_2x_coco.py' model = dict(pretrained='torchvision://resnet101', backbone=dict(depth=101))
139
45.666667
76
py
GFocalV2
GFocalV2-master/configs/reppoints/reppoints_moment_r50_fpn_1x_coco.py
_base_ = [ '../_base_/datasets/coco_detection.py', '../_base_/schedules/schedule_1x.py', '../_base_/default_runtime.py' ] model = dict( type='RepPointsDetector', pretrained='torchvision://resnet50', backbone=dict( type='ResNet', depth=50, num_stages=4, out_indices=(0, 1, 2, 3), frozen_stages=1, norm_cfg=dict(type='BN', requires_grad=True), norm_eval=True, style='pytorch'), neck=dict( type='FPN', in_channels=[256, 512, 1024, 2048], out_channels=256, start_level=1, add_extra_convs='on_input', num_outs=5), bbox_head=dict( type='RepPointsHead', num_classes=80, in_channels=256, feat_channels=256, point_feat_channels=256, stacked_convs=3, num_points=9, gradient_mul=0.1, point_strides=[8, 16, 32, 64, 128], point_base_scale=4, loss_cls=dict( type='FocalLoss', use_sigmoid=True, gamma=2.0, alpha=0.25, loss_weight=1.0), loss_bbox_init=dict(type='SmoothL1Loss', beta=0.11, loss_weight=0.5), loss_bbox_refine=dict(type='SmoothL1Loss', beta=0.11, loss_weight=1.0), transform_method='moment')) # training and testing settings train_cfg = dict( init=dict( assigner=dict(type='PointAssigner', scale=4, pos_num=1), allowed_border=-1, pos_weight=-1, debug=False), refine=dict( assigner=dict( type='MaxIoUAssigner', pos_iou_thr=0.5, neg_iou_thr=0.4, min_pos_iou=0, ignore_iof_thr=-1), allowed_border=-1, pos_weight=-1, debug=False)) test_cfg = dict( nms_pre=1000, min_bbox_size=0, score_thr=0.05, nms=dict(type='nms', iou_threshold=0.5), max_per_img=100) optimizer = dict(lr=0.01)
1,937
27.5
79
py
GFocalV2
GFocalV2-master/configs/reppoints/reppoints_moment_x101_fpn_dconv_c3-c5_gn-neck+head_2x_coco.py
_base_ = './reppoints_moment_r50_fpn_gn-neck+head_2x_coco.py' model = dict( pretrained='open-mmlab://resnext101_32x4d', backbone=dict( type='ResNeXt', depth=101, groups=32, base_width=4, num_stages=4, out_indices=(0, 1, 2, 3), frozen_stages=1, norm_cfg=dict(type='BN', requires_grad=True), style='pytorch', dcn=dict(type='DCN', deform_groups=1, fallback_on_stride=False), stage_with_dcn=(False, True, True, True)))
511
31
72
py
GFocalV2
GFocalV2-master/configs/gfl/gfl_x101_32x4d_fpn_dconv_c4-c5_mstrain_2x_coco.py
_base_ = './gfl_r50_fpn_mstrain_2x_coco.py' model = dict( type='GFL', pretrained='open-mmlab://resnext101_32x4d', backbone=dict( type='ResNeXt', depth=101, groups=32, base_width=4, num_stages=4, out_indices=(0, 1, 2, 3), frozen_stages=1, norm_cfg=dict(type='BN', requires_grad=True), dcn=dict(type='DCN', deform_groups=1, fallback_on_stride=False), stage_with_dcn=(False, False, True, True), norm_eval=True, style='pytorch'))
534
28.722222
72
py
GFocalV2
GFocalV2-master/configs/gfl/gfl_x101_32x4d_fpn_mstrain_2x_coco.py
_base_ = './gfl_r50_fpn_mstrain_2x_coco.py' model = dict( type='GFL', pretrained='open-mmlab://resnext101_32x4d', backbone=dict( type='ResNeXt', depth=101, groups=32, base_width=4, num_stages=4, out_indices=(0, 1, 2, 3), frozen_stages=1, norm_cfg=dict(type='BN', requires_grad=True), norm_eval=True, style='pytorch'))
410
24.6875
53
py
GFocalV2
GFocalV2-master/configs/gfl/gfl_r101_fpn_mstrain_2x_coco.py
_base_ = './gfl_r50_fpn_mstrain_2x_coco.py' model = dict( pretrained='torchvision://resnet101', backbone=dict( type='ResNet', depth=101, num_stages=4, out_indices=(0, 1, 2, 3), frozen_stages=1, norm_cfg=dict(type='BN', requires_grad=True), norm_eval=True, style='pytorch'))
346
25.692308
53
py
GFocalV2
GFocalV2-master/configs/gfl/gfl_r50_fpn_1x_coco.py
_base_ = [ '../_base_/datasets/coco_detection.py', '../_base_/schedules/schedule_1x.py', '../_base_/default_runtime.py' ] model = dict( type='GFL', pretrained='torchvision://resnet50', backbone=dict( type='ResNet', depth=50, num_stages=4, out_indices=(0, 1, 2, 3), frozen_stages=1, norm_cfg=dict(type='BN', requires_grad=True), norm_eval=True, style='pytorch'), neck=dict( type='FPN', in_channels=[256, 512, 1024, 2048], out_channels=256, start_level=1, add_extra_convs='on_output', num_outs=5), bbox_head=dict( type='GFLHead', num_classes=80, in_channels=256, stacked_convs=4, feat_channels=256, anchor_generator=dict( type='AnchorGenerator', ratios=[1.0], octave_base_scale=8, scales_per_octave=1, strides=[8, 16, 32, 64, 128]), loss_cls=dict( type='QualityFocalLoss', use_sigmoid=True, beta=2.0, loss_weight=1.0), loss_dfl=dict(type='DistributionFocalLoss', loss_weight=0.25), reg_max=16, loss_bbox=dict(type='GIoULoss', loss_weight=2.0))) # training and testing settings train_cfg = dict( assigner=dict(type='ATSSAssigner', topk=9), allowed_border=-1, pos_weight=-1, debug=False) test_cfg = dict( nms_pre=1000, min_bbox_size=0, score_thr=0.05, nms=dict(type='nms', iou_threshold=0.6), max_per_img=100) # optimizer optimizer = dict(type='SGD', lr=0.01, momentum=0.9, weight_decay=0.0001)
1,655
27.551724
72
py
GFocalV2
GFocalV2-master/configs/gfl/gfl_r101_fpn_dconv_c3-c5_mstrain_2x_coco.py
_base_ = './gfl_r50_fpn_mstrain_2x_coco.py' model = dict( pretrained='torchvision://resnet101', backbone=dict( type='ResNet', depth=101, num_stages=4, out_indices=(0, 1, 2, 3), frozen_stages=1, norm_cfg=dict(type='BN', requires_grad=True), dcn=dict(type='DCN', deform_groups=1, fallback_on_stride=False), stage_with_dcn=(False, True, True, True), norm_eval=True, style='pytorch'))
469
30.333333
72
py
GFocalV2
GFocalV2-master/configs/nas_fpn/retinanet_r50_fpn_crop640_50e_coco.py
_base_ = [ '../_base_/models/retinanet_r50_fpn.py', '../_base_/datasets/coco_detection.py', '../_base_/default_runtime.py' ] cudnn_benchmark = True norm_cfg = dict(type='BN', requires_grad=True) model = dict( pretrained='torchvision://resnet50', backbone=dict( type='ResNet', depth=50, num_stages=4, out_indices=(0, 1, 2, 3), frozen_stages=1, norm_cfg=norm_cfg, norm_eval=False, style='pytorch'), neck=dict( relu_before_extra_convs=True, no_norm_on_lateral=True, norm_cfg=norm_cfg), bbox_head=dict(type='RetinaSepBNHead', num_ins=5, norm_cfg=norm_cfg)) # training and testing settings train_cfg = dict(assigner=dict(neg_iou_thr=0.5)) # dataset settings img_norm_cfg = dict( mean=[123.675, 116.28, 103.53], std=[58.395, 57.12, 57.375], to_rgb=True) train_pipeline = [ dict(type='LoadImageFromFile'), dict(type='LoadAnnotations', with_bbox=True), dict( type='Resize', img_scale=(640, 640), ratio_range=(0.8, 1.2), keep_ratio=True), dict(type='RandomCrop', crop_size=(640, 640)), dict(type='RandomFlip', flip_ratio=0.5), dict(type='Normalize', **img_norm_cfg), dict(type='Pad', size=(640, 640)), dict(type='DefaultFormatBundle'), dict(type='Collect', keys=['img', 'gt_bboxes', 'gt_labels']), ] test_pipeline = [ dict(type='LoadImageFromFile'), dict( type='MultiScaleFlipAug', img_scale=(640, 640), flip=False, transforms=[ dict(type='Resize', keep_ratio=True), dict(type='RandomFlip'), dict(type='Normalize', **img_norm_cfg), dict(type='Pad', size_divisor=64), dict(type='ImageToTensor', keys=['img']), dict(type='Collect', keys=['img']), ]) ] data = dict( samples_per_gpu=8, workers_per_gpu=4, train=dict(pipeline=train_pipeline), val=dict(pipeline=test_pipeline), test=dict(pipeline=test_pipeline)) # optimizer optimizer = dict( type='SGD', lr=0.08, momentum=0.9, weight_decay=0.0001, paramwise_cfg=dict(norm_decay_mult=0, bypass_duplicate=True)) optimizer_config = dict(grad_clip=None) # learning policy lr_config = dict( policy='step', warmup='linear', warmup_iters=1000, warmup_ratio=0.1, step=[30, 40]) # runtime settings total_epochs = 50
2,407
28.728395
77
py
GFocalV2
GFocalV2-master/configs/nas_fpn/retinanet_r50_nasfpn_crop640_50e_coco.py
_base_ = [ '../_base_/models/retinanet_r50_fpn.py', '../_base_/datasets/coco_detection.py', '../_base_/default_runtime.py' ] cudnn_benchmark = True # model settings norm_cfg = dict(type='BN', requires_grad=True) model = dict( type='RetinaNet', pretrained='torchvision://resnet50', backbone=dict( type='ResNet', depth=50, num_stages=4, out_indices=(0, 1, 2, 3), frozen_stages=1, norm_cfg=norm_cfg, norm_eval=False, style='pytorch'), neck=dict(type='NASFPN', stack_times=7, norm_cfg=norm_cfg), bbox_head=dict(type='RetinaSepBNHead', num_ins=5, norm_cfg=norm_cfg)) # training and testing settings train_cfg = dict(assigner=dict(neg_iou_thr=0.5)) # dataset settings img_norm_cfg = dict( mean=[123.675, 116.28, 103.53], std=[58.395, 57.12, 57.375], to_rgb=True) train_pipeline = [ dict(type='LoadImageFromFile'), dict(type='LoadAnnotations', with_bbox=True), dict( type='Resize', img_scale=(640, 640), ratio_range=(0.8, 1.2), keep_ratio=True), dict(type='RandomCrop', crop_size=(640, 640)), dict(type='RandomFlip', flip_ratio=0.5), dict(type='Normalize', **img_norm_cfg), dict(type='Pad', size=(640, 640)), dict(type='DefaultFormatBundle'), dict(type='Collect', keys=['img', 'gt_bboxes', 'gt_labels']), ] test_pipeline = [ dict(type='LoadImageFromFile'), dict( type='MultiScaleFlipAug', img_scale=(640, 640), flip=False, transforms=[ dict(type='Resize', keep_ratio=True), dict(type='RandomFlip'), dict(type='Normalize', **img_norm_cfg), dict(type='Pad', size_divisor=128), dict(type='ImageToTensor', keys=['img']), dict(type='Collect', keys=['img']), ]) ] data = dict( samples_per_gpu=8, workers_per_gpu=4, train=dict(pipeline=train_pipeline), val=dict(pipeline=test_pipeline), test=dict(pipeline=test_pipeline)) # optimizer optimizer = dict( type='SGD', lr=0.08, momentum=0.9, weight_decay=0.0001, paramwise_cfg=dict(norm_decay_mult=0, bypass_duplicate=True)) optimizer_config = dict(grad_clip=None) # learning policy lr_config = dict( policy='step', warmup='linear', warmup_iters=1000, warmup_ratio=0.1, step=[30, 40]) # runtime settings total_epochs = 50
2,397
28.975
77
py
GFocalV2
GFocalV2-master/configs/paa/paa_r50_fpn_1x_coco.py
_base_ = [ '../_base_/datasets/coco_detection.py', '../_base_/schedules/schedule_1x.py', '../_base_/default_runtime.py' ] model = dict( type='PAA', pretrained='torchvision://resnet50', backbone=dict( type='ResNet', depth=50, num_stages=4, out_indices=(0, 1, 2, 3), frozen_stages=1, norm_cfg=dict(type='BN', requires_grad=True), norm_eval=True, style='pytorch'), neck=dict( type='FPN', in_channels=[256, 512, 1024, 2048], out_channels=256, start_level=1, add_extra_convs='on_output', num_outs=5), bbox_head=dict( type='PAAHead', reg_decoded_bbox=True, score_voting=True, topk=9, num_classes=80, in_channels=256, stacked_convs=4, feat_channels=256, anchor_generator=dict( type='AnchorGenerator', ratios=[1.0], octave_base_scale=8, scales_per_octave=1, strides=[8, 16, 32, 64, 128]), bbox_coder=dict( type='DeltaXYWHBBoxCoder', target_means=[.0, .0, .0, .0], target_stds=[0.1, 0.1, 0.2, 0.2]), loss_cls=dict( type='FocalLoss', use_sigmoid=True, gamma=2.0, alpha=0.25, loss_weight=1.0), loss_bbox=dict(type='GIoULoss', loss_weight=1.3), loss_centerness=dict( type='CrossEntropyLoss', use_sigmoid=True, loss_weight=0.5))) # training and testing settings train_cfg = dict( assigner=dict( type='MaxIoUAssigner', pos_iou_thr=0.1, neg_iou_thr=0.1, min_pos_iou=0, ignore_iof_thr=-1), allowed_border=-1, pos_weight=-1, debug=False) test_cfg = dict( nms_pre=1000, min_bbox_size=0, score_thr=0.05, nms=dict(type='nms', iou_threshold=0.6), max_per_img=100) # optimizer optimizer = dict(type='SGD', lr=0.01, momentum=0.9, weight_decay=0.0001)
2,016
27.408451
73
py
GFocalV2
GFocalV2-master/configs/paa/paa_r101_fpn_1x_coco.py
_base_ = './paa_r50_fpn_1x_coco.py' model = dict(pretrained='torchvision://resnet101', backbone=dict(depth=101)) lr_config = dict(step=[16, 22]) total_epochs = 24
163
31.8
76
py
GFocalV2
GFocalV2-master/configs/yolact/yolact_r50_1x8_coco.py
_base_ = '../_base_/default_runtime.py' # model settings img_size = 550 model = dict( type='YOLACT', pretrained='torchvision://resnet50', backbone=dict( type='ResNet', depth=50, num_stages=4, out_indices=(0, 1, 2, 3), frozen_stages=-1, # do not freeze stem norm_cfg=dict(type='BN', requires_grad=True), norm_eval=False, # update the statistics of bn zero_init_residual=False, style='pytorch'), neck=dict( type='FPN', in_channels=[256, 512, 1024, 2048], out_channels=256, start_level=1, add_extra_convs='on_input', num_outs=5, upsample_cfg=dict(mode='bilinear')), bbox_head=dict( type='YOLACTHead', num_classes=80, in_channels=256, feat_channels=256, anchor_generator=dict( type='AnchorGenerator', octave_base_scale=3, scales_per_octave=1, base_sizes=[8, 16, 32, 64, 128], ratios=[0.5, 1.0, 2.0], strides=[550.0 / x for x in [69, 35, 18, 9, 5]], centers=[(550 * 0.5 / x, 550 * 0.5 / x) for x in [69, 35, 18, 9, 5]]), bbox_coder=dict( type='DeltaXYWHBBoxCoder', target_means=[.0, .0, .0, .0], target_stds=[0.1, 0.1, 0.2, 0.2]), loss_cls=dict( type='CrossEntropyLoss', use_sigmoid=False, reduction='none', loss_weight=1.0), loss_bbox=dict(type='SmoothL1Loss', beta=1.0, loss_weight=1.5), num_head_convs=1, num_protos=32, use_ohem=True), mask_head=dict( type='YOLACTProtonet', in_channels=256, num_protos=32, num_classes=80, max_masks_to_train=100, loss_mask_weight=6.125), segm_head=dict( type='YOLACTSegmHead', num_classes=80, in_channels=256, loss_segm=dict( type='CrossEntropyLoss', use_sigmoid=True, loss_weight=1.0))) # training and testing settings train_cfg = dict( assigner=dict( type='MaxIoUAssigner', pos_iou_thr=0.5, neg_iou_thr=0.4, min_pos_iou=0., ignore_iof_thr=-1, gt_max_assign_all=False), # smoothl1_beta=1., allowed_border=-1, pos_weight=-1, neg_pos_ratio=3, debug=False) test_cfg = dict( nms_pre=1000, min_bbox_size=0, score_thr=0.05, iou_thr=0.5, top_k=200, max_per_img=100) # dataset settings dataset_type = 'CocoDataset' data_root = 'data/coco/' img_norm_cfg = dict( mean=[123.68, 116.78, 103.94], std=[58.40, 57.12, 57.38], to_rgb=True) train_pipeline = [ dict(type='LoadImageFromFile', to_float32=True), dict(type='LoadAnnotations', with_bbox=True, with_mask=True), dict(type='FilterAnnotations', min_gt_bbox_wh=(4.0, 4.0)), dict( type='PhotoMetricDistortion', brightness_delta=32, contrast_range=(0.5, 1.5), saturation_range=(0.5, 1.5), hue_delta=18), dict( type='Expand', mean=img_norm_cfg['mean'], to_rgb=img_norm_cfg['to_rgb'], ratio_range=(1, 4)), dict( type='MinIoURandomCrop', min_ious=(0.1, 0.3, 0.5, 0.7, 0.9), min_crop_size=0.3), dict(type='Resize', img_scale=(img_size, img_size), keep_ratio=False), dict(type='Normalize', **img_norm_cfg), dict(type='RandomFlip', flip_ratio=0.5), dict(type='DefaultFormatBundle'), dict(type='Collect', keys=['img', 'gt_bboxes', 'gt_labels', 'gt_masks']), ] test_pipeline = [ dict(type='LoadImageFromFile'), dict( type='MultiScaleFlipAug', img_scale=(img_size, img_size), flip=False, transforms=[ dict(type='Resize', keep_ratio=False), dict(type='Normalize', **img_norm_cfg), dict(type='ImageToTensor', keys=['img']), dict(type='Collect', keys=['img']), ]) ] data = dict( samples_per_gpu=8, workers_per_gpu=4, train=dict( type=dataset_type, ann_file=data_root + 'annotations/instances_train2017.json', img_prefix=data_root + 'train2017/', pipeline=train_pipeline), val=dict( type=dataset_type, ann_file=data_root + 'annotations/instances_val2017.json', img_prefix=data_root + 'val2017/', pipeline=test_pipeline), test=dict( type=dataset_type, ann_file=data_root + 'annotations/instances_val2017.json', img_prefix=data_root + 'val2017/', pipeline=test_pipeline)) # optimizer optimizer = dict(type='SGD', lr=1e-3, momentum=0.9, weight_decay=5e-4) optimizer_config = dict() # learning policy lr_config = dict( policy='step', warmup='linear', warmup_iters=500, warmup_ratio=0.1, step=[20, 42, 49, 52]) total_epochs = 55 cudnn_benchmark = True evaluation = dict(metric=['bbox', 'segm'])
4,947
29.732919
77
py
GFocalV2
GFocalV2-master/configs/yolact/yolact_r101_1x8_coco.py
_base_ = './yolact_r50_1x8_coco.py' model = dict(pretrained='torchvision://resnet101', backbone=dict(depth=101))
114
27.75
76
py
GFocalV2
GFocalV2-master/configs/point_rend/point_rend_r50_caffe_fpn_mstrain_1x_coco.py
_base_ = '../mask_rcnn/mask_rcnn_r50_caffe_fpn_mstrain_1x_coco.py' # model settings model = dict( type='PointRend', roi_head=dict( type='PointRendRoIHead', mask_roi_extractor=dict( type='GenericRoIExtractor', aggregation='concat', roi_layer=dict( _delete_=True, type='SimpleRoIAlign', output_size=14), out_channels=256, featmap_strides=[4]), mask_head=dict( _delete_=True, type='CoarseMaskHead', num_fcs=2, in_channels=256, conv_out_channels=256, fc_out_channels=1024, num_classes=80, loss_mask=dict( type='CrossEntropyLoss', use_mask=True, loss_weight=1.0)), point_head=dict( type='MaskPointHead', num_fcs=3, in_channels=256, fc_channels=256, num_classes=80, coarse_pred_each_layer=True, loss_point=dict( type='CrossEntropyLoss', use_mask=True, loss_weight=1.0)))) # model training and testing settings train_cfg = dict( rcnn=dict( mask_size=7, num_points=14 * 14, oversample_ratio=3, importance_sample_ratio=0.75)) test_cfg = dict( rcnn=dict( subdivision_steps=5, subdivision_num_points=28 * 28, scale_factor=2))
1,391
31.372093
77
py
GFocalV2
GFocalV2-master/configs/point_rend/point_rend_r50_caffe_fpn_mstrain_3x_coco.py
_base_ = './point_rend_r50_caffe_fpn_mstrain_1x_coco.py' # learning policy lr_config = dict(step=[28, 34]) total_epochs = 36
125
24.2
56
py
GFocalV2
GFocalV2-master/configs/detectors/detectors_cascade_rcnn_r50_1x_coco.py
_base_ = [ '../_base_/models/cascade_rcnn_r50_fpn.py', '../_base_/datasets/coco_detection.py', '../_base_/schedules/schedule_1x.py', '../_base_/default_runtime.py' ] model = dict( backbone=dict( type='DetectoRS_ResNet', conv_cfg=dict(type='ConvAWS'), sac=dict(type='SAC', use_deform=True), stage_with_sac=(False, True, True, True), output_img=True), neck=dict( type='RFP', rfp_steps=2, aspp_out_channels=64, aspp_dilations=(1, 3, 6, 1), rfp_backbone=dict( rfp_inplanes=256, type='DetectoRS_ResNet', depth=50, num_stages=4, out_indices=(0, 1, 2, 3), frozen_stages=1, norm_cfg=dict(type='BN', requires_grad=True), norm_eval=True, conv_cfg=dict(type='ConvAWS'), sac=dict(type='SAC', use_deform=True), stage_with_sac=(False, True, True, True), pretrained='torchvision://resnet50', style='pytorch')))
1,053
30.939394
72
py
GFocalV2
GFocalV2-master/configs/detectors/detectors_htc_r50_1x_coco.py
_base_ = '../htc/htc_r50_fpn_1x_coco.py' model = dict( backbone=dict( type='DetectoRS_ResNet', conv_cfg=dict(type='ConvAWS'), sac=dict(type='SAC', use_deform=True), stage_with_sac=(False, True, True, True), output_img=True), neck=dict( type='RFP', rfp_steps=2, aspp_out_channels=64, aspp_dilations=(1, 3, 6, 1), rfp_backbone=dict( rfp_inplanes=256, type='DetectoRS_ResNet', depth=50, num_stages=4, out_indices=(0, 1, 2, 3), frozen_stages=1, norm_cfg=dict(type='BN', requires_grad=True), norm_eval=True, conv_cfg=dict(type='ConvAWS'), sac=dict(type='SAC', use_deform=True), stage_with_sac=(False, True, True, True), pretrained='torchvision://resnet50', style='pytorch')))
916
30.62069
57
py
GFocalV2
GFocalV2-master/configs/detectors/cascade_rcnn_r50_rfp_1x_coco.py
_base_ = [ '../_base_/models/cascade_rcnn_r50_fpn.py', '../_base_/datasets/coco_detection.py', '../_base_/schedules/schedule_1x.py', '../_base_/default_runtime.py' ] model = dict( backbone=dict( type='DetectoRS_ResNet', conv_cfg=dict(type='ConvAWS'), output_img=True), neck=dict( type='RFP', rfp_steps=2, aspp_out_channels=64, aspp_dilations=(1, 3, 6, 1), rfp_backbone=dict( rfp_inplanes=256, type='DetectoRS_ResNet', depth=50, num_stages=4, out_indices=(0, 1, 2, 3), frozen_stages=1, norm_cfg=dict(type='BN', requires_grad=True), norm_eval=True, conv_cfg=dict(type='ConvAWS'), pretrained='torchvision://resnet50', style='pytorch')))
851
28.37931
72
py
GFocalV2
GFocalV2-master/configs/detectors/htc_r50_rfp_1x_coco.py
_base_ = '../htc/htc_r50_fpn_1x_coco.py' model = dict( backbone=dict( type='DetectoRS_ResNet', conv_cfg=dict(type='ConvAWS'), output_img=True), neck=dict( type='RFP', rfp_steps=2, aspp_out_channels=64, aspp_dilations=(1, 3, 6, 1), rfp_backbone=dict( rfp_inplanes=256, type='DetectoRS_ResNet', depth=50, num_stages=4, out_indices=(0, 1, 2, 3), frozen_stages=1, norm_cfg=dict(type='BN', requires_grad=True), norm_eval=True, conv_cfg=dict(type='ConvAWS'), pretrained='torchvision://resnet50', style='pytorch')))
714
27.6
57
py
GFocalV2
GFocalV2-master/configs/fcos/fcos_center-normbbox-centeronreg-giou_r50_caffe_fpn_gn-head_4x4_1x_coco.py
_base_ = 'fcos_r50_caffe_fpn_gn-head_4x4_1x_coco.py' model = dict( pretrained='open-mmlab://detectron2/resnet50_caffe', bbox_head=dict( norm_on_bbox=True, centerness_on_reg=True, dcn_on_last_conv=False, center_sampling=True, conv_bias=True, loss_bbox=dict(type='GIoULoss', loss_weight=1.0))) # training and testing settings test_cfg = dict(nms=dict(type='nms', iou_threshold=0.6)) # dataset settings img_norm_cfg = dict( mean=[103.530, 116.280, 123.675], std=[1.0, 1.0, 1.0], to_rgb=False) train_pipeline = [ dict(type='LoadImageFromFile'), dict(type='LoadAnnotations', with_bbox=True), dict(type='Resize', img_scale=(1333, 800), keep_ratio=True), dict(type='RandomFlip', flip_ratio=0.5), dict(type='Normalize', **img_norm_cfg), dict(type='Pad', size_divisor=32), dict(type='DefaultFormatBundle'), dict(type='Collect', keys=['img', 'gt_bboxes', 'gt_labels']), ] test_pipeline = [ dict(type='LoadImageFromFile'), dict( type='MultiScaleFlipAug', img_scale=(1333, 800), flip=False, transforms=[ dict(type='Resize', keep_ratio=True), dict(type='RandomFlip'), dict(type='Normalize', **img_norm_cfg), dict(type='Pad', size_divisor=32), dict(type='ImageToTensor', keys=['img']), dict(type='Collect', keys=['img']), ]) ] data = dict( samples_per_gpu=4, workers_per_gpu=4, train=dict(pipeline=train_pipeline), val=dict(pipeline=test_pipeline), test=dict(pipeline=test_pipeline)) optimizer_config = dict(_delete_=True, grad_clip=None) lr_config = dict(warmup='linear')
1,694
31.596154
72
py
GFocalV2
GFocalV2-master/configs/fcos/fcos_r101_caffe_fpn_gn-head_4x4_1x_coco.py
_base_ = './fcos_r50_caffe_fpn_gn-head_4x4_1x_coco.py' model = dict( pretrained='open-mmlab://detectron/resnet101_caffe', backbone=dict(depth=101))
156
30.4
56
py
GFocalV2
GFocalV2-master/configs/fcos/fcos_r101_caffe_fpn_gn-head_mstrain_640-800_4x4_2x_coco.py
_base_ = './fcos_r50_caffe_fpn_gn-head_4x4_1x_coco.py' model = dict( pretrained='open-mmlab://detectron/resnet101_caffe', backbone=dict(depth=101)) img_norm_cfg = dict( mean=[102.9801, 115.9465, 122.7717], std=[1.0, 1.0, 1.0], to_rgb=False) train_pipeline = [ dict(type='LoadImageFromFile'), dict(type='LoadAnnotations', with_bbox=True), dict( type='Resize', img_scale=[(1333, 640), (1333, 800)], multiscale_mode='value', keep_ratio=True), dict(type='RandomFlip', flip_ratio=0.5), dict(type='Normalize', **img_norm_cfg), dict(type='Pad', size_divisor=32), dict(type='DefaultFormatBundle'), dict(type='Collect', keys=['img', 'gt_bboxes', 'gt_labels']), ] test_pipeline = [ dict(type='LoadImageFromFile'), dict( type='MultiScaleFlipAug', img_scale=(1333, 800), flip=False, transforms=[ dict(type='Resize', keep_ratio=True), dict(type='RandomFlip'), dict(type='Normalize', **img_norm_cfg), dict(type='Pad', size_divisor=32), dict(type='ImageToTensor', keys=['img']), dict(type='Collect', keys=['img']), ]) ] data = dict( samples_per_gpu=4, workers_per_gpu=4, train=dict(pipeline=train_pipeline), val=dict(pipeline=test_pipeline), test=dict(pipeline=test_pipeline)) # learning policy lr_config = dict(step=[16, 22]) total_epochs = 24
1,446
31.155556
75
py
GFocalV2
GFocalV2-master/configs/fcos/fcos_x101_64x4d_fpn_gn-head_mstrain_640-800_4x2_2x_coco.py
_base_ = './fcos_r50_caffe_fpn_gn-head_4x4_1x_coco.py' model = dict( pretrained='open-mmlab://resnext101_64x4d', backbone=dict( type='ResNeXt', depth=101, groups=64, base_width=4, num_stages=4, out_indices=(0, 1, 2, 3), frozen_stages=1, norm_cfg=dict(type='BN', requires_grad=True), norm_eval=True, style='pytorch')) img_norm_cfg = dict( mean=[123.675, 116.28, 103.53], std=[58.395, 57.12, 57.375], to_rgb=True) train_pipeline = [ dict(type='LoadImageFromFile'), dict(type='LoadAnnotations', with_bbox=True), dict( type='Resize', img_scale=[(1333, 640), (1333, 800)], multiscale_mode='value', keep_ratio=True), dict(type='RandomFlip', flip_ratio=0.5), dict(type='Normalize', **img_norm_cfg), dict(type='Pad', size_divisor=32), dict(type='DefaultFormatBundle'), dict(type='Collect', keys=['img', 'gt_bboxes', 'gt_labels']), ] test_pipeline = [ dict(type='LoadImageFromFile'), dict( type='MultiScaleFlipAug', img_scale=(1333, 800), flip=False, transforms=[ dict(type='Resize', keep_ratio=True), dict(type='RandomFlip'), dict(type='Normalize', **img_norm_cfg), dict(type='Pad', size_divisor=32), dict(type='ImageToTensor', keys=['img']), dict(type='Collect', keys=['img']), ]) ] data = dict( samples_per_gpu=2, workers_per_gpu=2, train=dict(pipeline=train_pipeline), val=dict(pipeline=test_pipeline), test=dict(pipeline=test_pipeline)) # optimizer optimizer = dict( lr=0.01, paramwise_cfg=dict(bias_lr_mult=2., bias_decay_mult=0.)) optimizer_config = dict( _delete_=True, grad_clip=dict(max_norm=35, norm_type=2)) # learning policy lr_config = dict(step=[16, 22]) total_epochs = 24
1,883
30.4
77
py
GFocalV2
GFocalV2-master/configs/fcos/fcos_center_r50_caffe_fpn_gn-head_4x4_1x_coco.py
_base_ = './fcos_r50_caffe_fpn_gn-head_4x4_1x_coco.py' model = dict(bbox_head=dict(center_sampling=True, center_sample_radius=1.5))
132
43.333333
76
py
GFocalV2
GFocalV2-master/configs/fcos/fcos_r101_caffe_fpn_gn-head_4x4_2x_coco.py
_base_ = ['./fcos_r50_caffe_fpn_gn-head_4x4_2x_coco.py'] model = dict( pretrained='open-mmlab://detectron/resnet101_caffe', backbone=dict(depth=101))
158
30.8
56
py
GFocalV2
GFocalV2-master/configs/fcos/fcos_r50_caffe_fpn_gn-head_mstrain_640-800_4x4_2x_coco.py
_base_ = './fcos_r50_caffe_fpn_gn-head_4x4_1x_coco.py' img_norm_cfg = dict( mean=[102.9801, 115.9465, 122.7717], std=[1.0, 1.0, 1.0], to_rgb=False) train_pipeline = [ dict(type='LoadImageFromFile'), dict(type='LoadAnnotations', with_bbox=True), dict( type='Resize', img_scale=[(1333, 640), (1333, 800)], multiscale_mode='value', keep_ratio=True), dict(type='RandomFlip', flip_ratio=0.5), dict(type='Normalize', **img_norm_cfg), dict(type='Pad', size_divisor=32), dict(type='DefaultFormatBundle'), dict(type='Collect', keys=['img', 'gt_bboxes', 'gt_labels']), ] test_pipeline = [ dict(type='LoadImageFromFile'), dict( type='MultiScaleFlipAug', img_scale=(1333, 800), flip=False, transforms=[ dict(type='Resize', keep_ratio=True), dict(type='RandomFlip'), dict(type='Normalize', **img_norm_cfg), dict(type='Pad', size_divisor=32), dict(type='ImageToTensor', keys=['img']), dict(type='Collect', keys=['img']), ]) ] data = dict( train=dict(pipeline=train_pipeline), val=dict(pipeline=test_pipeline), test=dict(pipeline=test_pipeline)) # learning policy lr_config = dict(step=[16, 22]) total_epochs = 24
1,299
31.5
75
py
GFocalV2
GFocalV2-master/configs/fcos/fcos_center-normbbox-centeronreg-giou_r50_caffe_fpn_gn-head_dcn_4x4_1x_coco.py
_base_ = 'fcos_r50_caffe_fpn_gn-head_4x4_1x_coco.py' model = dict( pretrained='open-mmlab://detectron2/resnet50_caffe', backbone=dict( dcn=dict(type='DCNv2', deform_groups=1, fallback_on_stride=False), stage_with_dcn=(False, True, True, True)), bbox_head=dict( norm_on_bbox=True, centerness_on_reg=True, dcn_on_last_conv=True, center_sampling=True, conv_bias=True, loss_bbox=dict(type='GIoULoss', loss_weight=1.0))) # training and testing settings test_cfg = dict(nms=dict(type='nms', iou_threshold=0.6)) # dataset settings img_norm_cfg = dict( mean=[103.530, 116.280, 123.675], std=[1.0, 1.0, 1.0], to_rgb=False) train_pipeline = [ dict(type='LoadImageFromFile'), dict(type='LoadAnnotations', with_bbox=True), dict(type='Resize', img_scale=(1333, 800), keep_ratio=True), dict(type='RandomFlip', flip_ratio=0.5), dict(type='Normalize', **img_norm_cfg), dict(type='Pad', size_divisor=32), dict(type='DefaultFormatBundle'), dict(type='Collect', keys=['img', 'gt_bboxes', 'gt_labels']), ] test_pipeline = [ dict(type='LoadImageFromFile'), dict( type='MultiScaleFlipAug', img_scale=(1333, 800), flip=False, transforms=[ dict(type='Resize', keep_ratio=True), dict(type='RandomFlip'), dict(type='Normalize', **img_norm_cfg), dict(type='Pad', size_divisor=32), dict(type='ImageToTensor', keys=['img']), dict(type='Collect', keys=['img']), ]) ] data = dict( samples_per_gpu=4, workers_per_gpu=4, train=dict(pipeline=train_pipeline), val=dict(pipeline=test_pipeline), test=dict(pipeline=test_pipeline)) optimizer_config = dict(_delete_=True, grad_clip=None) lr_config = dict(warmup='linear')
1,838
32.436364
74
py
GFocalV2
GFocalV2-master/configs/fcos/fcos_r50_caffe_fpn_gn-head_4x4_1x_coco.py
_base_ = [ '../_base_/datasets/coco_detection.py', '../_base_/schedules/schedule_1x.py', '../_base_/default_runtime.py' ] # model settings model = dict( type='FCOS', pretrained='open-mmlab://detectron/resnet50_caffe', backbone=dict( type='ResNet', depth=50, num_stages=4, out_indices=(0, 1, 2, 3), frozen_stages=1, norm_cfg=dict(type='BN', requires_grad=False), norm_eval=True, style='caffe'), neck=dict( type='FPN', in_channels=[256, 512, 1024, 2048], out_channels=256, start_level=1, add_extra_convs=True, extra_convs_on_inputs=False, # use P5 num_outs=5, relu_before_extra_convs=True), bbox_head=dict( type='FCOSHead', num_classes=80, in_channels=256, stacked_convs=4, feat_channels=256, strides=[8, 16, 32, 64, 128], loss_cls=dict( type='FocalLoss', use_sigmoid=True, gamma=2.0, alpha=0.25, loss_weight=1.0), loss_bbox=dict(type='IoULoss', loss_weight=1.0), loss_centerness=dict( type='CrossEntropyLoss', use_sigmoid=True, loss_weight=1.0))) # training and testing settings train_cfg = dict( assigner=dict( type='MaxIoUAssigner', pos_iou_thr=0.5, neg_iou_thr=0.4, min_pos_iou=0, ignore_iof_thr=-1), allowed_border=-1, pos_weight=-1, debug=False) test_cfg = dict( nms_pre=1000, min_bbox_size=0, score_thr=0.05, nms=dict(type='nms', iou_threshold=0.5), max_per_img=100) img_norm_cfg = dict( mean=[102.9801, 115.9465, 122.7717], std=[1.0, 1.0, 1.0], to_rgb=False) train_pipeline = [ dict(type='LoadImageFromFile'), dict(type='LoadAnnotations', with_bbox=True), dict(type='Resize', img_scale=(1333, 800), keep_ratio=True), dict(type='RandomFlip', flip_ratio=0.5), dict(type='Normalize', **img_norm_cfg), dict(type='Pad', size_divisor=32), dict(type='DefaultFormatBundle'), dict(type='Collect', keys=['img', 'gt_bboxes', 'gt_labels']), ] test_pipeline = [ dict(type='LoadImageFromFile'), dict( type='MultiScaleFlipAug', img_scale=(1333, 800), flip=False, transforms=[ dict(type='Resize', keep_ratio=True), dict(type='RandomFlip'), dict(type='Normalize', **img_norm_cfg), dict(type='Pad', size_divisor=32), dict(type='ImageToTensor', keys=['img']), dict(type='Collect', keys=['img']), ]) ] data = dict( samples_per_gpu=4, workers_per_gpu=4, train=dict(pipeline=train_pipeline), val=dict(pipeline=test_pipeline), test=dict(pipeline=test_pipeline)) # optimizer optimizer = dict( lr=0.01, paramwise_cfg=dict(bias_lr_mult=2., bias_decay_mult=0.)) optimizer_config = dict( _delete_=True, grad_clip=dict(max_norm=35, norm_type=2)) # learning policy lr_config = dict( policy='step', warmup='constant', warmup_iters=500, warmup_ratio=1.0 / 3, step=[8, 11]) total_epochs = 12
3,146
28.688679
75
py
GFocalV2
GFocalV2-master/configs/fcos/fcos_r50_caffe_fpn_gn-head_4x4_2x_coco.py
_base_ = './fcos_r50_caffe_fpn_gn-head_4x4_1x_coco.py' # learning policy lr_config = dict(step=[16, 22]) total_epochs = 24
124
19.833333
54
py
GFocalV2
GFocalV2-master/configs/fcos/fcos_r50_caffe_fpn_4x4_1x_coco.py
_base_ = [ '../_base_/datasets/coco_detection.py', '../_base_/schedules/schedule_1x.py', '../_base_/default_runtime.py' ] # model settings model = dict( type='FCOS', pretrained='open-mmlab://detectron/resnet50_caffe', backbone=dict( type='ResNet', depth=50, num_stages=4, out_indices=(0, 1, 2, 3), frozen_stages=1, norm_cfg=dict(type='BN', requires_grad=False), norm_eval=True, style='caffe'), neck=dict( type='FPN', in_channels=[256, 512, 1024, 2048], out_channels=256, start_level=1, add_extra_convs=True, extra_convs_on_inputs=False, # use P5 num_outs=5, relu_before_extra_convs=True), bbox_head=dict( type='FCOSHead', num_classes=80, in_channels=256, stacked_convs=4, feat_channels=256, strides=[8, 16, 32, 64, 128], norm_cfg=None, loss_cls=dict( type='FocalLoss', use_sigmoid=True, gamma=2.0, alpha=0.25, loss_weight=1.0), loss_bbox=dict(type='IoULoss', loss_weight=1.0), loss_centerness=dict( type='CrossEntropyLoss', use_sigmoid=True, loss_weight=1.0))) # training and testing settings train_cfg = dict( assigner=dict( type='MaxIoUAssigner', pos_iou_thr=0.5, neg_iou_thr=0.4, min_pos_iou=0, ignore_iof_thr=-1), allowed_border=-1, pos_weight=-1, debug=False) test_cfg = dict( nms_pre=1000, min_bbox_size=0, score_thr=0.05, nms=dict(type='nms', iou_threshold=0.5), max_per_img=100) img_norm_cfg = dict( mean=[102.9801, 115.9465, 122.7717], std=[1.0, 1.0, 1.0], to_rgb=False) train_pipeline = [ dict(type='LoadImageFromFile'), dict(type='LoadAnnotations', with_bbox=True), dict(type='Resize', img_scale=(1333, 800), keep_ratio=True), dict(type='RandomFlip', flip_ratio=0.5), dict(type='Normalize', **img_norm_cfg), dict(type='Pad', size_divisor=32), dict(type='DefaultFormatBundle'), dict(type='Collect', keys=['img', 'gt_bboxes', 'gt_labels']), ] test_pipeline = [ dict(type='LoadImageFromFile'), dict( type='MultiScaleFlipAug', img_scale=(1333, 800), flip=False, transforms=[ dict(type='Resize', keep_ratio=True), dict(type='RandomFlip'), dict(type='Normalize', **img_norm_cfg), dict(type='Pad', size_divisor=32), dict(type='ImageToTensor', keys=['img']), dict(type='Collect', keys=['img']), ]) ] data = dict( samples_per_gpu=4, workers_per_gpu=4, train=dict(pipeline=train_pipeline), val=dict(pipeline=test_pipeline), test=dict(pipeline=test_pipeline)) # optimizer optimizer = dict( lr=0.01, paramwise_cfg=dict(bias_lr_mult=2., bias_decay_mult=0.)) optimizer_config = dict( _delete_=True, grad_clip=dict(max_norm=35, norm_type=2)) # learning policy lr_config = dict( policy='step', warmup='constant', warmup_iters=500, warmup_ratio=1.0 / 3, step=[8, 11]) total_epochs = 12
3,169
28.626168
75
py
GFocalV2
GFocalV2-master/configs/legacy_1.x/faster_rcnn_r50_fpn_1x_coco_v1.py
_base_ = [ '../_base_/models/faster_rcnn_r50_fpn.py', '../_base_/datasets/coco_detection.py', '../_base_/schedules/schedule_1x.py', '../_base_/default_runtime.py' ] model = dict( type='FasterRCNN', pretrained='torchvision://resnet50', rpn_head=dict( type='RPNHead', anchor_generator=dict( type='LegacyAnchorGenerator', center_offset=0.5, scales=[8], ratios=[0.5, 1.0, 2.0], strides=[4, 8, 16, 32, 64]), bbox_coder=dict(type='LegacyDeltaXYWHBBoxCoder'), loss_bbox=dict(type='SmoothL1Loss', beta=1.0 / 9.0, loss_weight=1.0)), roi_head=dict( type='StandardRoIHead', bbox_roi_extractor=dict( type='SingleRoIExtractor', roi_layer=dict( type='RoIAlign', output_size=7, sampling_ratio=2, aligned=False), out_channels=256, featmap_strides=[4, 8, 16, 32]), bbox_head=dict( bbox_coder=dict(type='LegacyDeltaXYWHBBoxCoder'), loss_bbox=dict(type='SmoothL1Loss', beta=1.0, loss_weight=1.0)))) # model training and testing settings train_cfg = dict( rpn_proposal=dict(nms_post=2000, max_num=2000), rcnn=dict(assigner=dict(match_low_quality=True)))
1,323
33.842105
78
py
GFocalV2
GFocalV2-master/configs/legacy_1.x/cascade_mask_rcnn_r50_fpn_1x_coco_v1.py
_base_ = [ '../_base_/models/cascade_mask_rcnn_r50_fpn.py', '../_base_/datasets/coco_instance.py', '../_base_/schedules/schedule_1x.py', '../_base_/default_runtime.py' ] model = dict( type='CascadeRCNN', pretrained='torchvision://resnet50', backbone=dict( type='ResNet', depth=50, num_stages=4, out_indices=(0, 1, 2, 3), frozen_stages=1, norm_cfg=dict(type='BN', requires_grad=True), norm_eval=True, style='pytorch'), neck=dict( type='FPN', in_channels=[256, 512, 1024, 2048], out_channels=256, num_outs=5), rpn_head=dict( anchor_generator=dict(type='LegacyAnchorGenerator', center_offset=0.5), bbox_coder=dict( type='LegacyDeltaXYWHBBoxCoder', target_means=[.0, .0, .0, .0], target_stds=[1.0, 1.0, 1.0, 1.0])), roi_head=dict( bbox_roi_extractor=dict( type='SingleRoIExtractor', roi_layer=dict( type='RoIAlign', output_size=7, sampling_ratio=2, aligned=False)), bbox_head=[ dict( type='Shared2FCBBoxHead', reg_class_agnostic=True, in_channels=256, fc_out_channels=1024, roi_feat_size=7, num_classes=80, bbox_coder=dict( type='LegacyDeltaXYWHBBoxCoder', target_means=[0., 0., 0., 0.], target_stds=[0.1, 0.1, 0.2, 0.2])), dict( type='Shared2FCBBoxHead', reg_class_agnostic=True, in_channels=256, fc_out_channels=1024, roi_feat_size=7, num_classes=80, bbox_coder=dict( type='LegacyDeltaXYWHBBoxCoder', target_means=[0., 0., 0., 0.], target_stds=[0.05, 0.05, 0.1, 0.1])), dict( type='Shared2FCBBoxHead', reg_class_agnostic=True, in_channels=256, fc_out_channels=1024, roi_feat_size=7, num_classes=80, bbox_coder=dict( type='LegacyDeltaXYWHBBoxCoder', target_means=[0., 0., 0., 0.], target_stds=[0.033, 0.033, 0.067, 0.067])), ], mask_roi_extractor=dict( type='SingleRoIExtractor', roi_layer=dict( type='RoIAlign', output_size=14, sampling_ratio=2, aligned=False)))) dist_params = dict(backend='nccl', port=29515)
2,753
33.425
79
py
GFocalV2
GFocalV2-master/configs/legacy_1.x/retinanet_r50_caffe_fpn_1x_coco_v1.py
_base_ = './retinanet_r50_fpn_1x_coco_v1.py' model = dict( pretrained='open-mmlab://detectron/resnet50_caffe', backbone=dict( norm_cfg=dict(requires_grad=False), norm_eval=True, style='caffe')) # use caffe img_norm img_norm_cfg = dict( mean=[102.9801, 115.9465, 122.7717], std=[1.0, 1.0, 1.0], to_rgb=False) train_pipeline = [ dict(type='LoadImageFromFile'), dict(type='LoadAnnotations', with_bbox=True), dict(type='Resize', img_scale=(1333, 800), keep_ratio=True), dict(type='RandomFlip', flip_ratio=0.5), dict(type='Normalize', **img_norm_cfg), dict(type='Pad', size_divisor=32), dict(type='DefaultFormatBundle'), dict(type='Collect', keys=['img', 'gt_bboxes', 'gt_labels']), ] test_pipeline = [ dict(type='LoadImageFromFile'), dict( type='MultiScaleFlipAug', img_scale=(1333, 800), flip=False, transforms=[ dict(type='Resize', keep_ratio=True), dict(type='RandomFlip'), dict(type='Normalize', **img_norm_cfg), dict(type='Pad', size_divisor=32), dict(type='ImageToTensor', keys=['img']), dict(type='Collect', keys=['img']), ]) ] data = dict( train=dict(pipeline=train_pipeline), val=dict(pipeline=test_pipeline), test=dict(pipeline=test_pipeline))
1,334
34.131579
75
py
GFocalV2
GFocalV2-master/configs/ms_rcnn/ms_rcnn_r50_caffe_fpn_1x_coco.py
_base_ = '../mask_rcnn/mask_rcnn_r50_caffe_fpn_1x_coco.py' model = dict( type='MaskScoringRCNN', roi_head=dict( type='MaskScoringRoIHead', mask_iou_head=dict( type='MaskIoUHead', num_convs=4, num_fcs=2, roi_feat_size=14, in_channels=256, conv_out_channels=256, fc_out_channels=1024, num_classes=80))) # model training and testing settings train_cfg = dict(rcnn=dict(mask_thr_binary=0.5))
508
28.941176
58
py
GFocalV2
GFocalV2-master/configs/ms_rcnn/ms_rcnn_x101_64x4d_fpn_1x_coco.py
_base_ = './ms_rcnn_r50_fpn_1x_coco.py' model = dict( pretrained='open-mmlab://resnext101_64x4d', backbone=dict( type='ResNeXt', depth=101, groups=64, base_width=4, num_stages=4, out_indices=(0, 1, 2, 3), frozen_stages=1, norm_cfg=dict(type='BN', requires_grad=True), style='pytorch'))
366
25.214286
53
py
GFocalV2
GFocalV2-master/configs/ms_rcnn/ms_rcnn_r50_caffe_fpn_2x_coco.py
_base_ = './ms_rcnn_r50_caffe_fpn_1x_coco.py' # learning policy lr_config = dict(step=[16, 22]) total_epochs = 24
114
22
45
py
GFocalV2
GFocalV2-master/configs/ms_rcnn/ms_rcnn_x101_32x4d_fpn_1x_coco.py
_base_ = './ms_rcnn_r50_fpn_1x_coco.py' model = dict( pretrained='open-mmlab://resnext101_32x4d', backbone=dict( type='ResNeXt', depth=101, groups=32, base_width=4, num_stages=4, out_indices=(0, 1, 2, 3), frozen_stages=1, norm_cfg=dict(type='BN', requires_grad=True), style='pytorch'))
366
25.214286
53
py
GFocalV2
GFocalV2-master/configs/ms_rcnn/ms_rcnn_r101_caffe_fpn_2x_coco.py
_base_ = './ms_rcnn_r101_caffe_fpn_1x_coco.py' # learning policy lr_config = dict(step=[16, 22]) total_epochs = 24
115
22.2
46
py
GFocalV2
GFocalV2-master/configs/ms_rcnn/ms_rcnn_r101_caffe_fpn_1x_coco.py
_base_ = './ms_rcnn_r50_caffe_fpn_1x_coco.py' model = dict( pretrained='open-mmlab://detectron2/resnet101_caffe', backbone=dict(depth=101))
148
28.8
57
py
GFocalV2
GFocalV2-master/configs/fast_rcnn/fast_rcnn_r101_fpn_2x_coco.py
_base_ = './fast_rcnn_r50_fpn_2x_coco.py' model = dict(pretrained='torchvision://resnet101', backbone=dict(depth=101))
119
39
76
py
GFocalV2
GFocalV2-master/configs/fast_rcnn/fast_rcnn_r101_fpn_1x_coco.py
_base_ = './fast_rcnn_r50_fpn_1x_coco.py' model = dict(pretrained='torchvision://resnet101', backbone=dict(depth=101))
119
39
76
py
GFocalV2
GFocalV2-master/configs/fast_rcnn/fast_rcnn_r101_caffe_fpn_1x_coco.py
_base_ = './fast_rcnn_r50_caffe_fpn_1x_coco.py' model = dict( pretrained='open-mmlab://detectron2/resnet101_caffe', backbone=dict(depth=101))
150
29.2
57
py
GFocalV2
GFocalV2-master/configs/fast_rcnn/fast_rcnn_r50_caffe_fpn_1x_coco.py
_base_ = './fast_rcnn_r50_fpn_1x_coco.py' model = dict( pretrained='open-mmlab://detectron2/resnet50_caffe', backbone=dict( norm_cfg=dict(type='BN', requires_grad=False), style='caffe')) # use caffe img_norm img_norm_cfg = dict( mean=[103.530, 116.280, 123.675], std=[1.0, 1.0, 1.0], to_rgb=False) train_pipeline = [ dict(type='LoadImageFromFile'), dict(type='LoadProposals', num_max_proposals=2000), dict(type='LoadAnnotations', with_bbox=True), dict(type='Resize', img_scale=(1333, 800), keep_ratio=True), dict(type='RandomFlip', flip_ratio=0.5), dict(type='Normalize', **img_norm_cfg), dict(type='Pad', size_divisor=32), dict(type='DefaultFormatBundle'), dict(type='Collect', keys=['img', 'proposals', 'gt_bboxes', 'gt_labels']), ] test_pipeline = [ dict(type='LoadImageFromFile'), dict(type='LoadProposals', num_max_proposals=None), dict( type='MultiScaleFlipAug', img_scale=(1333, 800), flip=False, transforms=[ dict(type='Resize', keep_ratio=True), dict(type='RandomFlip'), dict(type='Normalize', **img_norm_cfg), dict(type='Pad', size_divisor=32), dict(type='ImageToTensor', keys=['img']), dict(type='ToTensor', keys=['proposals']), dict( type='ToDataContainer', fields=[dict(key='proposals', stack=False)]), dict(type='Collect', keys=['img', 'proposals']), ]) ] data = dict( train=dict(pipeline=train_pipeline), val=dict(pipeline=test_pipeline), test=dict(pipeline=test_pipeline))
1,639
34.652174
78
py
GFocalV2
GFocalV2-master/configs/hrnet/fcos_hrnetv2p_w32_gn-head_4x4_1x_coco.py
_base_ = '../fcos/fcos_r50_caffe_fpn_gn-head_4x4_1x_coco.py' model = dict( pretrained='open-mmlab://msra/hrnetv2_w32', backbone=dict( _delete_=True, type='HRNet', extra=dict( stage1=dict( num_modules=1, num_branches=1, block='BOTTLENECK', num_blocks=(4, ), num_channels=(64, )), stage2=dict( num_modules=1, num_branches=2, block='BASIC', num_blocks=(4, 4), num_channels=(32, 64)), stage3=dict( num_modules=4, num_branches=3, block='BASIC', num_blocks=(4, 4, 4), num_channels=(32, 64, 128)), stage4=dict( num_modules=3, num_branches=4, block='BASIC', num_blocks=(4, 4, 4, 4), num_channels=(32, 64, 128, 256)))), neck=dict( _delete_=True, type='HRFPN', in_channels=[32, 64, 128, 256], out_channels=256, stride=2, num_outs=5))
1,176
29.179487
60
py
GFocalV2
GFocalV2-master/configs/vfnet/vfnet_r2_101_fpn_mstrain_2x_coco.py
_base_ = './vfnet_r50_fpn_mstrain_2x_coco.py' model = dict( pretrained='open-mmlab://res2net101_v1d_26w_4s', backbone=dict( type='Res2Net', depth=101, scales=4, base_width=26, num_stages=4, out_indices=(0, 1, 2, 3), frozen_stages=1, norm_cfg=dict(type='BN', requires_grad=True), norm_eval=True, style='pytorch'))
401
25.8
53
py
GFocalV2
GFocalV2-master/configs/vfnet/vfnet_r101_fpn_mdconv_c3-c5_mstrain_2x_coco.py
_base_ = './vfnet_r50_fpn_mdconv_c3-c5_mstrain_2x_coco.py' model = dict( pretrained='torchvision://resnet101', backbone=dict( type='ResNet', depth=101, num_stages=4, out_indices=(0, 1, 2, 3), frozen_stages=1, norm_cfg=dict(type='BN', requires_grad=True), norm_eval=True, style='pytorch', dcn=dict(type='DCNv2', deform_groups=1, fallback_on_stride=False), stage_with_dcn=(False, True, True, True)))
486
31.466667
74
py
GFocalV2
GFocalV2-master/configs/vfnet/vfnet_r50_fpn_1x_coco.py
_base_ = [ '../_base_/datasets/coco_detection.py', '../_base_/schedules/schedule_1x.py', '../_base_/default_runtime.py' ] # model settings model = dict( type='VFNet', pretrained='torchvision://resnet50', backbone=dict( type='ResNet', depth=50, num_stages=4, out_indices=(0, 1, 2, 3), frozen_stages=1, norm_cfg=dict(type='BN', requires_grad=True), norm_eval=True, style='pytorch'), neck=dict( type='FPN', in_channels=[256, 512, 1024, 2048], out_channels=256, start_level=1, add_extra_convs=True, extra_convs_on_inputs=False, # use P5 num_outs=5, relu_before_extra_convs=True), bbox_head=dict( type='VFNetHead', num_classes=80, in_channels=256, stacked_convs=3, feat_channels=256, strides=[8, 16, 32, 64, 128], center_sampling=False, dcn_on_last_conv=False, use_atss=True, use_vfl=True, loss_cls=dict( type='VarifocalLoss', use_sigmoid=True, alpha=0.75, gamma=2.0, iou_weighted=True, loss_weight=1.0), loss_bbox=dict(type='GIoULoss', loss_weight=1.5), loss_bbox_refine=dict(type='GIoULoss', loss_weight=2.0))) # training and testing settings train_cfg = dict( assigner=dict(type='ATSSAssigner', topk=9), allowed_border=-1, pos_weight=-1, debug=False) test_cfg = dict( nms_pre=1000, min_bbox_size=0, score_thr=0.05, nms=dict(type='nms', iou_threshold=0.6), max_per_img=100) # data setting dataset_type = 'CocoDataset' data_root = 'data/coco/' img_norm_cfg = dict( mean=[123.675, 116.28, 103.53], std=[58.395, 57.12, 57.375], to_rgb=True) train_pipeline = [ dict(type='LoadImageFromFile'), dict(type='LoadAnnotations', with_bbox=True), dict(type='Resize', img_scale=(1333, 800), keep_ratio=True), dict(type='RandomFlip', flip_ratio=0.5), dict(type='Normalize', **img_norm_cfg), dict(type='Pad', size_divisor=32), dict(type='DefaultFormatBundle'), dict(type='Collect', keys=['img', 'gt_bboxes', 'gt_labels']), ] test_pipeline = [ dict(type='LoadImageFromFile'), dict( type='MultiScaleFlipAug', img_scale=(1333, 800), flip=False, transforms=[ dict(type='Resize', keep_ratio=True), dict(type='RandomFlip'), dict(type='Normalize', **img_norm_cfg), dict(type='Pad', size_divisor=32), dict(type='DefaultFormatBundle'), dict(type='Collect', keys=['img']), ]) ] data = dict( samples_per_gpu=2, workers_per_gpu=2, train=dict(pipeline=train_pipeline), val=dict(pipeline=test_pipeline), test=dict(pipeline=test_pipeline)) # optimizer optimizer = dict( lr=0.01, paramwise_cfg=dict(bias_lr_mult=2., bias_decay_mult=0.)) optimizer_config = dict(grad_clip=None) # learning policy lr_config = dict( policy='step', warmup='linear', warmup_iters=500, warmup_ratio=0.1, step=[8, 11]) total_epochs = 12 # runtime load_from = None resume_from = None workflow = [('train', 1)]
3,224
27.043478
77
py
GFocalV2
GFocalV2-master/configs/vfnet/vfnet_r2_101_fpn_mdconv_c3-c5_mstrain_2x_coco.py
_base_ = './vfnet_r50_fpn_mdconv_c3-c5_mstrain_2x_coco.py' model = dict( pretrained='open-mmlab://res2net101_v1d_26w_4s', backbone=dict( type='Res2Net', depth=101, scales=4, base_width=26, num_stages=4, out_indices=(0, 1, 2, 3), frozen_stages=1, norm_cfg=dict(type='BN', requires_grad=True), norm_eval=True, style='pytorch', dcn=dict(type='DCNv2', deform_groups=1, fallback_on_stride=False), stage_with_dcn=(False, True, True, True)))
539
30.764706
74
py
GFocalV2
GFocalV2-master/configs/vfnet/vfnet_r101_fpn_mstrain_2x_coco.py
_base_ = './vfnet_r50_fpn_mstrain_2x_coco.py' model = dict(pretrained='torchvision://resnet101', backbone=dict(depth=101))
123
40.333333
76
py
GFocalV2
GFocalV2-master/configs/vfnet/vfnet_x101_32x4d_fpn_mdconv_c3-c5_mstrain_2x_coco.py
_base_ = './vfnet_r50_fpn_mdconv_c3-c5_mstrain_2x_coco.py' model = dict( pretrained='open-mmlab://resnext101_32x4d', backbone=dict( type='ResNeXt', depth=101, groups=32, base_width=4, num_stages=4, out_indices=(0, 1, 2, 3), frozen_stages=1, norm_cfg=dict(type='BN', requires_grad=True), norm_eval=True, style='pytorch', dcn=dict(type='DCNv2', deform_groups=1, fallback_on_stride=False), stage_with_dcn=(False, True, True, True)))
534
30.470588
74
py
GFocalV2
GFocalV2-master/configs/vfnet/vfnet_r101_fpn_1x_coco.py
_base_ = './vfnet_r50_fpn_1x_coco.py' model = dict(pretrained='torchvision://resnet101', backbone=dict(depth=101))
115
37.666667
76
py
GFocalV2
GFocalV2-master/configs/vfnet/vfnet_r101_fpn_2x_coco.py
_base_ = './vfnet_r50_fpn_1x_coco.py' model = dict(pretrained='torchvision://resnet101', backbone=dict(depth=101)) lr_config = dict(step=[16, 22]) total_epochs = 24
165
32.2
76
py
GFocalV2
GFocalV2-master/configs/vfnet/vfnet_x101_32x4d_fpn_mstrain_2x_coco.py
_base_ = './vfnet_r50_fpn_mstrain_2x_coco.py' model = dict( pretrained='open-mmlab://resnext101_32x4d', backbone=dict( type='ResNeXt', depth=101, groups=32, base_width=4, num_stages=4, out_indices=(0, 1, 2, 3), frozen_stages=1, norm_cfg=dict(type='BN', requires_grad=True), norm_eval=True, style='pytorch'))
396
25.466667
53
py
GFocalV2
GFocalV2-master/configs/vfnet/vfnet_x101_64x4d_fpn_mdconv_c3-c5_mstrain_2x_coco.py
_base_ = './vfnet_r50_fpn_mdconv_c3-c5_mstrain_2x_coco.py' model = dict( pretrained='open-mmlab://resnext101_64x4d', backbone=dict( type='ResNeXt', depth=101, groups=64, base_width=4, num_stages=4, out_indices=(0, 1, 2, 3), frozen_stages=1, norm_cfg=dict(type='BN', requires_grad=True), norm_eval=True, style='pytorch', dcn=dict(type='DCNv2', deform_groups=1, fallback_on_stride=False), stage_with_dcn=(False, True, True, True)))
534
30.470588
74
py
GFocalV2
GFocalV2-master/configs/vfnet/vfnet_x101_64x4d_fpn_mstrain_2x_coco.py
_base_ = './vfnet_r50_fpn_mstrain_2x_coco.py' model = dict( pretrained='open-mmlab://resnext101_64x4d', backbone=dict( type='ResNeXt', depth=101, groups=64, base_width=4, num_stages=4, out_indices=(0, 1, 2, 3), frozen_stages=1, norm_cfg=dict(type='BN', requires_grad=True), norm_eval=True, style='pytorch'))
396
25.466667
53
py
GFocalV2
GFocalV2-master/configs/foveabox/fovea_r50_fpn_4x4_1x_coco.py
_base_ = [ '../_base_/datasets/coco_detection.py', '../_base_/schedules/schedule_1x.py', '../_base_/default_runtime.py' ] # model settings model = dict( type='FOVEA', pretrained='torchvision://resnet50', backbone=dict( type='ResNet', depth=50, num_stages=4, out_indices=(0, 1, 2, 3), frozen_stages=1, norm_cfg=dict(type='BN', requires_grad=True), norm_eval=True, style='pytorch'), neck=dict( type='FPN', in_channels=[256, 512, 1024, 2048], out_channels=256, start_level=1, num_outs=5, add_extra_convs='on_input'), bbox_head=dict( type='FoveaHead', num_classes=80, in_channels=256, stacked_convs=4, feat_channels=256, strides=[8, 16, 32, 64, 128], base_edge_list=[16, 32, 64, 128, 256], scale_ranges=((1, 64), (32, 128), (64, 256), (128, 512), (256, 2048)), sigma=0.4, with_deform=False, loss_cls=dict( type='FocalLoss', use_sigmoid=True, gamma=1.50, alpha=0.4, loss_weight=1.0), loss_bbox=dict(type='SmoothL1Loss', beta=0.11, loss_weight=1.0))) # training and testing settings train_cfg = dict() test_cfg = dict( nms_pre=1000, score_thr=0.05, nms=dict(type='nms', iou_threshold=0.5), max_per_img=100) data = dict(samples_per_gpu=4, workers_per_gpu=4) # optimizer optimizer = dict(type='SGD', lr=0.01, momentum=0.9, weight_decay=0.0001)
1,548
28.226415
78
py
GFocalV2
GFocalV2-master/configs/foveabox/fovea_r101_fpn_4x4_2x_coco.py
_base_ = './fovea_r50_fpn_4x4_2x_coco.py' model = dict(pretrained='torchvision://resnet101', backbone=dict(depth=101))
119
39
76
py
GFocalV2
GFocalV2-master/configs/foveabox/fovea_align_r101_fpn_gn-head_mstrain_640-800_4x4_2x_coco.py
_base_ = './fovea_r50_fpn_4x4_1x_coco.py' model = dict( pretrained='torchvision://resnet101', backbone=dict(depth=101), bbox_head=dict( with_deform=True, norm_cfg=dict(type='GN', num_groups=32, requires_grad=True))) img_norm_cfg = dict( mean=[123.675, 116.28, 103.53], std=[58.395, 57.12, 57.375], to_rgb=True) train_pipeline = [ dict(type='LoadImageFromFile'), dict(type='LoadAnnotations', with_bbox=True), dict( type='Resize', img_scale=[(1333, 640), (1333, 800)], multiscale_mode='value', keep_ratio=True), dict(type='RandomFlip', flip_ratio=0.5), dict(type='Normalize', **img_norm_cfg), dict(type='Pad', size_divisor=32), dict(type='DefaultFormatBundle'), dict(type='Collect', keys=['img', 'gt_bboxes', 'gt_labels']), ] data = dict(train=dict(pipeline=train_pipeline)) # learning policy lr_config = dict(step=[16, 22]) total_epochs = 24
937
32.5
77
py
GFocalV2
GFocalV2-master/configs/foveabox/fovea_r101_fpn_4x4_1x_coco.py
_base_ = './fovea_r50_fpn_4x4_1x_coco.py' model = dict(pretrained='torchvision://resnet101', backbone=dict(depth=101))
119
39
76
py
GFocalV2
GFocalV2-master/configs/foveabox/fovea_align_r101_fpn_gn-head_4x4_2x_coco.py
_base_ = './fovea_r50_fpn_4x4_1x_coco.py' model = dict( pretrained='torchvision://resnet101', backbone=dict(depth=101), bbox_head=dict( with_deform=True, norm_cfg=dict(type='GN', num_groups=32, requires_grad=True))) # learning policy lr_config = dict(step=[16, 22]) total_epochs = 24
312
27.454545
69
py
GFocalV2
GFocalV2-master/configs/regnet/mask_rcnn_regnetx-8GF_fpn_1x_coco.py
_base_ = './mask_rcnn_regnetx-3.2GF_fpn_1x_coco.py' model = dict( pretrained='open-mmlab://regnetx_8.0gf', backbone=dict( type='RegNet', arch='regnetx_8.0gf', out_indices=(0, 1, 2, 3), frozen_stages=1, norm_cfg=dict(type='BN', requires_grad=True), norm_eval=True, style='pytorch'), neck=dict( type='FPN', in_channels=[80, 240, 720, 1920], out_channels=256, num_outs=5))
470
26.705882
53
py
GFocalV2
GFocalV2-master/configs/regnet/retinanet_regnetx-1.6GF_fpn_1x_coco.py
_base_ = './retinanet_regnetx-3.2GF_fpn_1x_coco.py' model = dict( pretrained='open-mmlab://regnetx_1.6gf', backbone=dict( type='RegNet', arch='regnetx_1.6gf', out_indices=(0, 1, 2, 3), frozen_stages=1, norm_cfg=dict(type='BN', requires_grad=True), norm_eval=True, style='pytorch'), neck=dict( type='FPN', in_channels=[72, 168, 408, 912], out_channels=256, num_outs=5))
469
26.647059
53
py
GFocalV2
GFocalV2-master/configs/regnet/mask_rcnn_regnetx-12GF_fpn_1x_coco.py
_base_ = './mask_rcnn_regnetx-3.2GF_fpn_1x_coco.py' model = dict( pretrained='open-mmlab://regnetx_12gf', backbone=dict( type='RegNet', arch='regnetx_12gf', out_indices=(0, 1, 2, 3), frozen_stages=1, norm_cfg=dict(type='BN', requires_grad=True), norm_eval=True, style='pytorch'), neck=dict( type='FPN', in_channels=[224, 448, 896, 2240], out_channels=256, num_outs=5))
469
26.647059
53
py
GFocalV2
GFocalV2-master/configs/regnet/retinanet_regnetx-800MF_fpn_1x_coco.py
_base_ = './retinanet_regnetx-3.2GF_fpn_1x_coco.py' model = dict( pretrained='open-mmlab://regnetx_800mf', backbone=dict( type='RegNet', arch='regnetx_800mf', out_indices=(0, 1, 2, 3), frozen_stages=1, norm_cfg=dict(type='BN', requires_grad=True), norm_eval=True, style='pytorch'), neck=dict( type='FPN', in_channels=[64, 128, 288, 672], out_channels=256, num_outs=5))
469
26.647059
53
py
GFocalV2
GFocalV2-master/configs/regnet/mask_rcnn_regnetx-4GF_fpn_1x_coco.py
_base_ = './mask_rcnn_regnetx-3.2GF_fpn_1x_coco.py' model = dict( pretrained='open-mmlab://regnetx_4.0gf', backbone=dict( type='RegNet', arch='regnetx_4.0gf', out_indices=(0, 1, 2, 3), frozen_stages=1, norm_cfg=dict(type='BN', requires_grad=True), norm_eval=True, style='pytorch'), neck=dict( type='FPN', in_channels=[80, 240, 560, 1360], out_channels=256, num_outs=5))
470
26.705882
53
py
GFocalV2
GFocalV2-master/configs/regnet/faster_rcnn_regnetx-3.2GF_fpn_mstrain_3x_coco.py
_base_ = [ '../_base_/models/faster_rcnn_r50_fpn.py', '../_base_/datasets/coco_detection.py', '../_base_/schedules/schedule_1x.py', '../_base_/default_runtime.py' ] model = dict( pretrained='open-mmlab://regnetx_3.2gf', backbone=dict( _delete_=True, type='RegNet', arch='regnetx_3.2gf', out_indices=(0, 1, 2, 3), frozen_stages=1, norm_cfg=dict(type='BN', requires_grad=True), norm_eval=True, style='pytorch'), neck=dict( type='FPN', in_channels=[96, 192, 432, 1008], out_channels=256, num_outs=5)) img_norm_cfg = dict( # The mean and std are used in PyCls when training RegNets mean=[103.53, 116.28, 123.675], std=[57.375, 57.12, 58.395], to_rgb=False) train_pipeline = [ dict(type='LoadImageFromFile'), dict(type='LoadAnnotations', with_bbox=True), dict( type='Resize', img_scale=[(1333, 640), (1333, 672), (1333, 704), (1333, 736), (1333, 768), (1333, 800)], multiscale_mode='value', keep_ratio=True), dict(type='RandomFlip', flip_ratio=0.5), dict(type='Normalize', **img_norm_cfg), dict(type='Pad', size_divisor=32), dict(type='DefaultFormatBundle'), dict(type='Collect', keys=['img', 'gt_bboxes', 'gt_labels']), ] test_pipeline = [ dict(type='LoadImageFromFile'), dict( type='MultiScaleFlipAug', img_scale=(1333, 800), flip=False, transforms=[ dict(type='Resize', keep_ratio=True), dict(type='RandomFlip'), dict(type='Normalize', **img_norm_cfg), dict(type='Pad', size_divisor=32), dict(type='ImageToTensor', keys=['img']), dict(type='Collect', keys=['img']), ]) ] data = dict( train=dict(pipeline=train_pipeline), val=dict(pipeline=test_pipeline), test=dict(pipeline=test_pipeline)) optimizer = dict(type='SGD', lr=0.02, momentum=0.9, weight_decay=0.00005) lr_config = dict(step=[28, 34]) total_epochs = 36
2,063
31.25
73
py
GFocalV2
GFocalV2-master/configs/regnet/retinanet_regnetx-3.2GF_fpn_1x_coco.py
_base_ = [ '../_base_/models/retinanet_r50_fpn.py', '../_base_/datasets/coco_detection.py', '../_base_/schedules/schedule_1x.py', '../_base_/default_runtime.py' ] model = dict( pretrained='open-mmlab://regnetx_3.2gf', backbone=dict( _delete_=True, type='RegNet', arch='regnetx_3.2gf', out_indices=(0, 1, 2, 3), frozen_stages=1, norm_cfg=dict(type='BN', requires_grad=True), norm_eval=True, style='pytorch'), neck=dict( type='FPN', in_channels=[96, 192, 432, 1008], out_channels=256, num_outs=5)) img_norm_cfg = dict( # The mean and std are used in PyCls when training RegNets mean=[103.53, 116.28, 123.675], std=[57.375, 57.12, 58.395], to_rgb=False) train_pipeline = [ dict(type='LoadImageFromFile'), dict(type='LoadAnnotations', with_bbox=True), dict(type='Resize', img_scale=(1333, 800), keep_ratio=True), dict(type='RandomFlip', flip_ratio=0.5), dict(type='Normalize', **img_norm_cfg), dict(type='Pad', size_divisor=32), dict(type='DefaultFormatBundle'), dict(type='Collect', keys=['img', 'gt_bboxes', 'gt_labels']), ] test_pipeline = [ dict(type='LoadImageFromFile'), dict( type='MultiScaleFlipAug', img_scale=(1333, 800), flip=False, transforms=[ dict(type='Resize', keep_ratio=True), dict(type='RandomFlip'), dict(type='Normalize', **img_norm_cfg), dict(type='Pad', size_divisor=32), dict(type='ImageToTensor', keys=['img']), dict(type='Collect', keys=['img']), ]) ] data = dict( train=dict(pipeline=train_pipeline), val=dict(pipeline=test_pipeline), test=dict(pipeline=test_pipeline)) optimizer = dict(type='SGD', lr=0.02, momentum=0.9, weight_decay=0.00005) optimizer_config = dict( _delete_=True, grad_clip=dict(max_norm=35, norm_type=2))
1,953
32.118644
73
py
GFocalV2
GFocalV2-master/configs/regnet/faster_rcnn_regnetx-3.2GF_fpn_1x_coco.py
_base_ = [ '../_base_/models/faster_rcnn_r50_fpn.py', '../_base_/datasets/coco_detection.py', '../_base_/schedules/schedule_1x.py', '../_base_/default_runtime.py' ] model = dict( pretrained='open-mmlab://regnetx_3.2gf', backbone=dict( _delete_=True, type='RegNet', arch='regnetx_3.2gf', out_indices=(0, 1, 2, 3), frozen_stages=1, norm_cfg=dict(type='BN', requires_grad=True), norm_eval=True, style='pytorch'), neck=dict( type='FPN', in_channels=[96, 192, 432, 1008], out_channels=256, num_outs=5)) img_norm_cfg = dict( # The mean and std are used in PyCls when training RegNets mean=[103.53, 116.28, 123.675], std=[57.375, 57.12, 58.395], to_rgb=False) train_pipeline = [ dict(type='LoadImageFromFile'), dict(type='LoadAnnotations', with_bbox=True), dict(type='Resize', img_scale=(1333, 800), keep_ratio=True), dict(type='RandomFlip', flip_ratio=0.5), dict(type='Normalize', **img_norm_cfg), dict(type='Pad', size_divisor=32), dict(type='DefaultFormatBundle'), dict(type='Collect', keys=['img', 'gt_bboxes', 'gt_labels']), ] test_pipeline = [ dict(type='LoadImageFromFile'), dict( type='MultiScaleFlipAug', img_scale=(1333, 800), flip=False, transforms=[ dict(type='Resize', keep_ratio=True), dict(type='RandomFlip'), dict(type='Normalize', **img_norm_cfg), dict(type='Pad', size_divisor=32), dict(type='ImageToTensor', keys=['img']), dict(type='Collect', keys=['img']), ]) ] data = dict( train=dict(pipeline=train_pipeline), val=dict(pipeline=test_pipeline), test=dict(pipeline=test_pipeline)) optimizer = dict(type='SGD', lr=0.02, momentum=0.9, weight_decay=0.00005)
1,869
31.807018
73
py
GFocalV2
GFocalV2-master/configs/regnet/mask_rcnn_regnetx-3.2GF_fpn_1x_coco.py
_base_ = [ '../_base_/models/mask_rcnn_r50_fpn.py', '../_base_/datasets/coco_instance.py', '../_base_/schedules/schedule_1x.py', '../_base_/default_runtime.py' ] model = dict( pretrained='open-mmlab://regnetx_3.2gf', backbone=dict( _delete_=True, type='RegNet', arch='regnetx_3.2gf', out_indices=(0, 1, 2, 3), frozen_stages=1, norm_cfg=dict(type='BN', requires_grad=True), norm_eval=True, style='pytorch'), neck=dict( type='FPN', in_channels=[96, 192, 432, 1008], out_channels=256, num_outs=5)) img_norm_cfg = dict( # The mean and std are used in PyCls when training RegNets mean=[103.53, 116.28, 123.675], std=[57.375, 57.12, 58.395], to_rgb=False) train_pipeline = [ # Images are converted to float32 directly after loading in PyCls dict(type='LoadImageFromFile'), dict(type='LoadAnnotations', with_bbox=True, with_mask=True), dict(type='Resize', img_scale=(1333, 800), keep_ratio=True), dict(type='RandomFlip', flip_ratio=0.5), dict(type='Normalize', **img_norm_cfg), dict(type='Pad', size_divisor=32), dict(type='DefaultFormatBundle'), dict(type='Collect', keys=['img', 'gt_bboxes', 'gt_labels', 'gt_masks']), ] test_pipeline = [ dict(type='LoadImageFromFile'), dict( type='MultiScaleFlipAug', img_scale=(1333, 800), flip=False, transforms=[ dict(type='Resize', keep_ratio=True), dict(type='RandomFlip'), dict(type='Normalize', **img_norm_cfg), dict(type='Pad', size_divisor=32), dict(type='ImageToTensor', keys=['img']), dict(type='Collect', keys=['img']), ]) ] data = dict( train=dict(pipeline=train_pipeline), val=dict(pipeline=test_pipeline), test=dict(pipeline=test_pipeline)) optimizer = dict(type='SGD', lr=0.02, momentum=0.9, weight_decay=0.00005)
1,964
32.87931
77
py
GFocalV2
GFocalV2-master/configs/regnet/mask_rcnn_regnetx-3.2GF_fpn_mstrain_3x_coco.py
_base_ = [ '../_base_/models/mask_rcnn_r50_fpn.py', '../_base_/datasets/coco_instance.py', '../_base_/schedules/schedule_1x.py', '../_base_/default_runtime.py' ] model = dict( pretrained='open-mmlab://regnetx_3.2gf', backbone=dict( _delete_=True, type='RegNet', arch='regnetx_3.2gf', out_indices=(0, 1, 2, 3), frozen_stages=1, norm_cfg=dict(type='BN', requires_grad=True), norm_eval=True, style='pytorch'), neck=dict( type='FPN', in_channels=[96, 192, 432, 1008], out_channels=256, num_outs=5)) img_norm_cfg = dict( # The mean and std are used in PyCls when training RegNets mean=[103.53, 116.28, 123.675], std=[57.375, 57.12, 58.395], to_rgb=False) train_pipeline = [ dict(type='LoadImageFromFile'), dict(type='LoadAnnotations', with_bbox=True, with_mask=True), dict( type='Resize', img_scale=[(1333, 640), (1333, 672), (1333, 704), (1333, 736), (1333, 768), (1333, 800)], multiscale_mode='value', keep_ratio=True), dict(type='RandomFlip', flip_ratio=0.5), dict(type='Normalize', **img_norm_cfg), dict(type='Pad', size_divisor=32), dict(type='DefaultFormatBundle'), dict(type='Collect', keys=['img', 'gt_bboxes', 'gt_labels', 'gt_masks']), ] test_pipeline = [ dict(type='LoadImageFromFile'), dict( type='MultiScaleFlipAug', img_scale=(1333, 800), flip=False, transforms=[ dict(type='Resize', keep_ratio=True), dict(type='RandomFlip'), dict(type='Normalize', **img_norm_cfg), dict(type='Pad', size_divisor=32), dict(type='ImageToTensor', keys=['img']), dict(type='Collect', keys=['img']), ]) ] data = dict( train=dict(pipeline=train_pipeline), val=dict(pipeline=test_pipeline), test=dict(pipeline=test_pipeline)) optimizer = dict(type='SGD', lr=0.02, momentum=0.9, weight_decay=0.00005) lr_config = dict(step=[28, 34]) total_epochs = 36 optimizer_config = dict( _delete_=True, grad_clip=dict(max_norm=35, norm_type=2))
2,174
31.954545
77
py
GFocalV2
GFocalV2-master/configs/regnet/mask_rcnn_regnetx-6.4GF_fpn_1x_coco.py
_base_ = './mask_rcnn_regnetx-3.2GF_fpn_1x_coco.py' model = dict( pretrained='open-mmlab://regnetx_6.4gf', backbone=dict( type='RegNet', arch='regnetx_6.4gf', out_indices=(0, 1, 2, 3), frozen_stages=1, norm_cfg=dict(type='BN', requires_grad=True), norm_eval=True, style='pytorch'), neck=dict( type='FPN', in_channels=[168, 392, 784, 1624], out_channels=256, num_outs=5))
471
26.764706
53
py
GFocalV2
GFocalV2-master/configs/gfocal/gfocal_r101_fpn_ms2x.py
_base_ = [ '../_base_/datasets/coco_detection.py', '../_base_/schedules/schedule_1x.py', '../_base_/default_runtime.py' ] model = dict( type='GFL', pretrained='torchvision://resnet101', backbone=dict( type='ResNet', depth=101, num_stages=4, out_indices=(0, 1, 2, 3), frozen_stages=1, norm_cfg=dict(type='BN', requires_grad=True), norm_eval=True, style='pytorch'), neck=dict( type='FPN', in_channels=[256, 512, 1024, 2048], out_channels=256, start_level=1, add_extra_convs='on_output', num_outs=5), bbox_head=dict( type='GFocalHead', num_classes=80, in_channels=256, stacked_convs=4, feat_channels=256, anchor_generator=dict( type='AnchorGenerator', ratios=[1.0], octave_base_scale=8, scales_per_octave=1, strides=[8, 16, 32, 64, 128]), loss_cls=dict( type='QualityFocalLoss', use_sigmoid=False, beta=2.0, loss_weight=1.0), loss_dfl=dict(type='DistributionFocalLoss', loss_weight=0.250), reg_max=16, reg_topk=4, reg_channels=64, add_mean=True, loss_bbox=dict(type='GIoULoss', loss_weight=2.0))) # training and testing settings train_cfg = dict( assigner=dict(type='ATSSAssigner', topk=9), allowed_border=-1, pos_weight=-1, debug=False) test_cfg = dict( nms_pre=1000, min_bbox_size=0, score_thr=0.05, nms=dict(type='nms', iou_threshold=0.6), max_per_img=100) # optimizer optimizer = dict(type='SGD', lr=0.01, momentum=0.9, weight_decay=0.0001) # learning policy lr_config = dict(step=[16, 22]) total_epochs = 24 # multi-scale training img_norm_cfg = dict( mean=[123.675, 116.28, 103.53], std=[58.395, 57.12, 57.375], to_rgb=True) train_pipeline = [ dict(type='LoadImageFromFile'), dict(type='LoadAnnotations', with_bbox=True), dict( type='Resize', img_scale=[(1333, 480), (1333, 960)], multiscale_mode='range', keep_ratio=True), dict(type='RandomFlip', flip_ratio=0.5), dict(type='Normalize', **img_norm_cfg), dict(type='Pad', size_divisor=32), dict(type='DefaultFormatBundle'), dict(type='Collect', keys=['img', 'gt_bboxes', 'gt_labels']), ] data = dict(train=dict(pipeline=train_pipeline)) dataset_type = 'CocoDataset' data_root = 'data/coco/' test_pipeline = [ dict(type='LoadImageFromFile'), dict( type='MultiScaleFlipAug', img_scale=(1333, 800), flip=False, transforms=[ dict(type='Resize', keep_ratio=True), dict(type='RandomFlip'), dict(type='Normalize', **img_norm_cfg), dict(type='Pad', size_divisor=32), dict(type='ImageToTensor', keys=['img']), dict(type='Collect', keys=['img']), ]) ] data = dict( samples_per_gpu=2, workers_per_gpu=2, train=dict( type=dataset_type, ann_file=data_root + 'annotations/instances_train2017.json', img_prefix=data_root + 'train2017/', pipeline=train_pipeline), val=dict( type=dataset_type, ann_file=data_root + 'annotations/instances_val2017.json', img_prefix=data_root + 'val2017/', pipeline=test_pipeline), test=dict( type=dataset_type, ann_file=data_root + 'annotations/instances_val2017.json', img_prefix=data_root + 'val2017/', pipeline=test_pipeline)) evaluation = dict(interval=1, metric='bbox')
3,639
28.836066
77
py
GFocalV2
GFocalV2-master/configs/gfocal/gfocal_r50_fpn_1x.py
_base_ = [ '../_base_/datasets/coco_detection.py', '../_base_/schedules/schedule_1x.py', '../_base_/default_runtime.py' ] model = dict( type='GFL', pretrained='torchvision://resnet50', backbone=dict( type='ResNet', depth=50, num_stages=4, out_indices=(0, 1, 2, 3), frozen_stages=1, norm_cfg=dict(type='BN', requires_grad=True), norm_eval=True, style='pytorch'), neck=dict( type='FPN', in_channels=[256, 512, 1024, 2048], out_channels=256, start_level=1, add_extra_convs='on_output', num_outs=5), bbox_head=dict( type='GFocalHead', num_classes=80, in_channels=256, stacked_convs=4, feat_channels=256, anchor_generator=dict( type='AnchorGenerator', ratios=[1.0], octave_base_scale=8, scales_per_octave=1, strides=[8, 16, 32, 64, 128]), loss_cls=dict( type='QualityFocalLoss', use_sigmoid=False, beta=2.0, loss_weight=1.0), loss_dfl=dict(type='DistributionFocalLoss', loss_weight=0.25), reg_max=16, reg_topk=4, reg_channels=64, add_mean=True, loss_bbox=dict(type='GIoULoss', loss_weight=2.0))) # training and testing settings train_cfg = dict( assigner=dict(type='ATSSAssigner', topk=9), allowed_border=-1, pos_weight=-1, debug=False) test_cfg = dict( nms_pre=1000, min_bbox_size=0, score_thr=0.05, nms=dict(type='nms', iou_threshold=0.6), max_per_img=100) # optimizer optimizer = dict(type='SGD', lr=0.01, momentum=0.9, weight_decay=0.0001) # optimizer = dict( # type='SGD', # lr=0.01, # momentum=0.9, # weight_decay=0.0001, # paramwise_cfg=dict(bias_lr_mult=2., bias_decay_mult=0.)) # learning policy lr_config = dict(step=[8, 11]) total_epochs = 12 # multi-scale training img_norm_cfg = dict( mean=[123.675, 116.28, 103.53], std=[58.395, 57.12, 57.375], to_rgb=True) train_pipeline = [ dict(type='LoadImageFromFile'), dict(type='LoadAnnotations', with_bbox=True), dict(type='Resize', img_scale=(1333, 800), keep_ratio=True), #dict( # type='Resize', # img_scale=[(1333, 480), (1333, 960)], # multiscale_mode='range', # keep_ratio=True), dict(type='RandomFlip', flip_ratio=0.5), dict(type='Normalize', **img_norm_cfg), dict(type='Pad', size_divisor=32), dict(type='DefaultFormatBundle'), dict(type='Collect', keys=['img', 'gt_bboxes', 'gt_labels']), ] data = dict(train=dict(pipeline=train_pipeline)) dataset_type = 'CocoDataset' data_root = 'data/coco/' test_pipeline = [ dict(type='LoadImageFromFile'), dict( type='MultiScaleFlipAug', img_scale=(1333, 800), flip=False, transforms=[ dict(type='Resize', keep_ratio=True), dict(type='RandomFlip'), dict(type='Normalize', **img_norm_cfg), dict(type='Pad', size_divisor=32), dict(type='ImageToTensor', keys=['img']), dict(type='Collect', keys=['img']), ]) ] data = dict( samples_per_gpu=2, workers_per_gpu=2, train=dict( type=dataset_type, ann_file=data_root + 'annotations/instances_train2017.json', img_prefix=data_root + 'train2017/', pipeline=train_pipeline), val=dict( type=dataset_type, ann_file=data_root + 'annotations/instances_val2017.json', img_prefix=data_root + 'val2017/', pipeline=test_pipeline), test=dict( type=dataset_type, ann_file=data_root + 'annotations/instances_val2017.json', img_prefix=data_root + 'val2017/', pipeline=test_pipeline)) evaluation = dict(interval=1, metric='bbox')
3,863
28.953488
77
py
GFocalV2
GFocalV2-master/configs/gfocal/gfocal_r101_dcn_fpn_ms2x.py
_base_ = [ '../_base_/datasets/coco_detection.py', '../_base_/schedules/schedule_1x.py', '../_base_/default_runtime.py' ] model = dict( type='GFL', pretrained='torchvision://resnet101', backbone=dict( type='ResNet', depth=101, num_stages=4, out_indices=(0, 1, 2, 3), frozen_stages=1, norm_cfg=dict(type='BN', requires_grad=True), dcn=dict(type='DCN', deform_groups=1, fallback_on_stride=False), stage_with_dcn=(False, True, True, True), norm_eval=True, style='pytorch'), neck=dict( type='FPN', in_channels=[256, 512, 1024, 2048], out_channels=256, start_level=1, add_extra_convs='on_output', num_outs=5), bbox_head=dict( type='GFocalHead', num_classes=80, in_channels=256, stacked_convs=4, feat_channels=256, anchor_generator=dict( type='AnchorGenerator', ratios=[1.0], octave_base_scale=8, scales_per_octave=1, strides=[8, 16, 32, 64, 128]), loss_cls=dict( type='QualityFocalLoss', use_sigmoid=False, beta=2.0, loss_weight=1.0), loss_dfl=dict(type='DistributionFocalLoss', loss_weight=0.250), reg_max=16, reg_topk=4, reg_channels=64, add_mean=True, loss_bbox=dict(type='GIoULoss', loss_weight=2.0))) # training and testing settings train_cfg = dict( assigner=dict(type='ATSSAssigner', topk=9), allowed_border=-1, pos_weight=-1, debug=False) test_cfg = dict( nms_pre=1000, min_bbox_size=0, score_thr=0.05, nms=dict(type='nms', iou_threshold=0.6), max_per_img=100) # optimizer optimizer = dict(type='SGD', lr=0.01, momentum=0.9, weight_decay=0.0001) # learning policy lr_config = dict(step=[16, 22]) total_epochs = 24 # multi-scale training img_norm_cfg = dict( mean=[123.675, 116.28, 103.53], std=[58.395, 57.12, 57.375], to_rgb=True) train_pipeline = [ dict(type='LoadImageFromFile'), dict(type='LoadAnnotations', with_bbox=True), dict( type='Resize', img_scale=[(1333, 480), (1333, 960)], multiscale_mode='range', keep_ratio=True), dict(type='RandomFlip', flip_ratio=0.5), dict(type='Normalize', **img_norm_cfg), dict(type='Pad', size_divisor=32), dict(type='DefaultFormatBundle'), dict(type='Collect', keys=['img', 'gt_bboxes', 'gt_labels']), ] data = dict(train=dict(pipeline=train_pipeline)) dataset_type = 'CocoDataset' data_root = 'data/coco/' test_pipeline = [ dict(type='LoadImageFromFile'), dict( type='MultiScaleFlipAug', img_scale=(1333, 800), flip=False, transforms=[ dict(type='Resize', keep_ratio=True), dict(type='RandomFlip'), dict(type='Normalize', **img_norm_cfg), dict(type='Pad', size_divisor=32), dict(type='ImageToTensor', keys=['img']), dict(type='Collect', keys=['img']), ]) ] data = dict( samples_per_gpu=2, workers_per_gpu=2, train=dict( type=dataset_type, ann_file=data_root + 'annotations/instances_train2017.json', img_prefix=data_root + 'train2017/', pipeline=train_pipeline), val=dict( type=dataset_type, ann_file=data_root + 'annotations/instances_val2017.json', img_prefix=data_root + 'val2017/', pipeline=test_pipeline), test=dict( type=dataset_type, ann_file=data_root + 'annotations/instances_val2017.json', img_prefix=data_root + 'val2017/', pipeline=test_pipeline)) evaluation = dict(interval=1, metric='bbox')
3,762
29.346774
77
py
GFocalV2
GFocalV2-master/configs/gfocal/gfocal_r50_fpn_ms2x.py
_base_ = [ '../_base_/datasets/coco_detection.py', '../_base_/schedules/schedule_1x.py', '../_base_/default_runtime.py' ] model = dict( type='GFL', pretrained='torchvision://resnet50', backbone=dict( type='ResNet', depth=50, num_stages=4, out_indices=(0, 1, 2, 3), frozen_stages=1, norm_cfg=dict(type='BN', requires_grad=True), norm_eval=True, style='pytorch'), neck=dict( type='FPN', in_channels=[256, 512, 1024, 2048], out_channels=256, start_level=1, add_extra_convs='on_output', num_outs=5), bbox_head=dict( type='GFocalHead', num_classes=80, in_channels=256, stacked_convs=4, feat_channels=256, anchor_generator=dict( type='AnchorGenerator', ratios=[1.0], octave_base_scale=8, scales_per_octave=1, strides=[8, 16, 32, 64, 128]), loss_cls=dict( type='QualityFocalLoss', use_sigmoid=False, beta=2.0, loss_weight=1.0), loss_dfl=dict(type='DistributionFocalLoss', loss_weight=0.25), reg_max=16, reg_topk=4, reg_channels=64, add_mean=True, loss_bbox=dict(type='GIoULoss', loss_weight=2.0))) # training and testing settings train_cfg = dict( assigner=dict(type='ATSSAssigner', topk=9), allowed_border=-1, pos_weight=-1, debug=False) test_cfg = dict( nms_pre=1000, min_bbox_size=0, score_thr=0.05, nms=dict(type='nms', iou_threshold=0.6), max_per_img=100) # optimizer optimizer = dict(type='SGD', lr=0.01, momentum=0.9, weight_decay=0.0001) # learning policy lr_config = dict(step=[16, 22]) total_epochs = 24 # multi-scale training img_norm_cfg = dict( mean=[123.675, 116.28, 103.53], std=[58.395, 57.12, 57.375], to_rgb=True) train_pipeline = [ dict(type='LoadImageFromFile'), dict(type='LoadAnnotations', with_bbox=True), dict( type='Resize', img_scale=[(1333, 480), (1333, 960)], multiscale_mode='range', keep_ratio=True), dict(type='RandomFlip', flip_ratio=0.5), dict(type='Normalize', **img_norm_cfg), dict(type='Pad', size_divisor=32), dict(type='DefaultFormatBundle'), dict(type='Collect', keys=['img', 'gt_bboxes', 'gt_labels']), ] data = dict(train=dict(pipeline=train_pipeline)) dataset_type = 'CocoDataset' data_root = 'data/coco/' test_pipeline = [ dict(type='LoadImageFromFile'), dict( type='MultiScaleFlipAug', img_scale=(1333, 800), flip=False, transforms=[ dict(type='Resize', keep_ratio=True), dict(type='RandomFlip'), dict(type='Normalize', **img_norm_cfg), dict(type='Pad', size_divisor=32), dict(type='ImageToTensor', keys=['img']), dict(type='Collect', keys=['img']), ]) ] data = dict( samples_per_gpu=2, workers_per_gpu=2, train=dict( type=dataset_type, ann_file=data_root + 'annotations/instances_train2017.json', img_prefix=data_root + 'train2017/', pipeline=train_pipeline), val=dict( type=dataset_type, ann_file=data_root + 'annotations/instances_val2017.json', img_prefix=data_root + 'val2017/', pipeline=test_pipeline), test=dict( type=dataset_type, ann_file=data_root + 'annotations/instances_val2017.json', img_prefix=data_root + 'val2017/', pipeline=test_pipeline)) evaluation = dict(interval=1, metric='bbox')
3,636
28.811475
77
py