code
stringlengths
17
6.64M
@pytest.mark.parametrize('embed_dims', [False, 256]) def test_basetransformerlayer(embed_dims): attn_cfgs = (dict(type='MultiheadAttention', embed_dims=256, num_heads=8),) if embed_dims: ffn_cfgs = dict(type='FFN', embed_dims=embed_dims, feedforward_channels=1024, num_fcs=2, ffn_drop=0.0, act_cfg=dict...
def test_transformerlayersequence(): squeue = TransformerLayerSequence(num_layers=6, transformerlayers=dict(type='BaseTransformerLayer', attn_cfgs=[dict(type='MultiheadAttention', embed_dims=256, num_heads=8, dropout=0.1), dict(type='MultiheadAttention', embed_dims=256, num_heads=4)], feedforward_channels=1024, f...
def test_drop_path(): drop_path = DropPath(drop_prob=0) test_in = torch.rand(2, 3, 4, 5) assert (test_in is drop_path(test_in)) drop_path = DropPath(drop_prob=0.1) drop_path.training = False test_in = torch.rand(2, 3, 4, 5) assert (test_in is drop_path(test_in)) drop_path.training = Tr...
def test_constant_init(): conv_module = nn.Conv2d(3, 16, 3) constant_init(conv_module, 0.1) assert conv_module.weight.allclose(torch.full_like(conv_module.weight, 0.1)) assert conv_module.bias.allclose(torch.zeros_like(conv_module.bias)) conv_module_no_bias = nn.Conv2d(3, 16, 3, bias=False) co...
def test_xavier_init(): conv_module = nn.Conv2d(3, 16, 3) xavier_init(conv_module, bias=0.1) assert conv_module.bias.allclose(torch.full_like(conv_module.bias, 0.1)) xavier_init(conv_module, distribution='uniform') with pytest.raises(AssertionError): xavier_init(conv_module, distribution='...
def test_normal_init(): conv_module = nn.Conv2d(3, 16, 3) normal_init(conv_module, bias=0.1) assert conv_module.bias.allclose(torch.full_like(conv_module.bias, 0.1)) conv_module_no_bias = nn.Conv2d(3, 16, 3, bias=False) normal_init(conv_module_no_bias)
def test_trunc_normal_init(): def _random_float(a, b): return (((b - a) * random.random()) + a) def _is_trunc_normal(tensor, mean, std, a, b): z_samples = ((tensor.view((- 1)) - mean) / std) z_samples = z_samples.tolist() a0 = ((a - mean) / std) b0 = ((b - mean) / std...
def test_uniform_init(): conv_module = nn.Conv2d(3, 16, 3) uniform_init(conv_module, bias=0.1) assert conv_module.bias.allclose(torch.full_like(conv_module.bias, 0.1)) conv_module_no_bias = nn.Conv2d(3, 16, 3, bias=False) uniform_init(conv_module_no_bias)
def test_kaiming_init(): conv_module = nn.Conv2d(3, 16, 3) kaiming_init(conv_module, bias=0.1) assert conv_module.bias.allclose(torch.full_like(conv_module.bias, 0.1)) kaiming_init(conv_module, distribution='uniform') with pytest.raises(AssertionError): kaiming_init(conv_module, distributi...
def test_caffe_xavier_init(): conv_module = nn.Conv2d(3, 16, 3) caffe2_xavier_init(conv_module)
def test_bias_init_with_prob(): conv_module = nn.Conv2d(3, 16, 3) prior_prob = 0.1 normal_init(conv_module, bias=bias_init_with_prob(0.1)) bias = float((- np.log(((1 - prior_prob) / prior_prob)))) assert conv_module.bias.allclose(torch.full_like(conv_module.bias, bias))
def test_constaninit(): 'test ConstantInit class.' model = nn.Sequential(nn.Conv2d(3, 1, 3), nn.ReLU(), nn.Linear(1, 2)) func = ConstantInit(val=1, bias=2, layer='Conv2d') func(model) assert torch.equal(model[0].weight, torch.full(model[0].weight.shape, 1.0)) assert torch.equal(model[0].bias, ...
def test_xavierinit(): 'test XavierInit class.' model = nn.Sequential(nn.Conv2d(3, 1, 3), nn.ReLU(), nn.Linear(1, 2)) func = XavierInit(bias=0.1, layer='Conv2d') func(model) assert model[0].bias.allclose(torch.full_like(model[2].bias, 0.1)) assert (not model[2].bias.allclose(torch.full_like(mo...
def test_normalinit(): 'test Normalinit class.' model = nn.Sequential(nn.Conv2d(3, 1, 3), nn.ReLU(), nn.Linear(1, 2)) func = NormalInit(mean=100, std=1e-05, bias=200, layer=['Conv2d', 'Linear']) func(model) assert model[0].weight.allclose(torch.tensor(100.0)) assert model[2].weight.allclose(to...
def test_truncnormalinit(): 'test TruncNormalInit class.' model = nn.Sequential(nn.Conv2d(3, 1, 3), nn.ReLU(), nn.Linear(1, 2)) func = TruncNormalInit(mean=100, std=1e-05, bias=200, a=0, b=200, layer=['Conv2d', 'Linear']) func(model) assert model[0].weight.allclose(torch.tensor(100.0)) assert ...
def test_uniforminit(): '"test UniformInit class.' model = nn.Sequential(nn.Conv2d(3, 1, 3), nn.ReLU(), nn.Linear(1, 2)) func = UniformInit(a=1, b=1, bias=2, layer=['Conv2d', 'Linear']) func(model) assert torch.equal(model[0].weight, torch.full(model[0].weight.shape, 1.0)) assert torch.equal(m...
def test_kaiminginit(): 'test KaimingInit class.' model = nn.Sequential(nn.Conv2d(3, 1, 3), nn.ReLU(), nn.Linear(1, 2)) func = KaimingInit(bias=0.1, layer='Conv2d') func(model) assert torch.equal(model[0].bias, torch.full(model[0].bias.shape, 0.1)) assert (not torch.equal(model[2].bias, torch....
def test_caffe2xavierinit(): 'test Caffe2XavierInit.' model = nn.Sequential(nn.Conv2d(3, 1, 3), nn.ReLU(), nn.Linear(1, 2)) func = Caffe2XavierInit(bias=0.1, layer='Conv2d') func(model) assert torch.equal(model[0].bias, torch.full(model[0].bias.shape, 0.1)) assert (not torch.equal(model[2].bia...
class FooModule(nn.Module): def __init__(self): super().__init__() self.linear = nn.Linear(1, 2) self.conv2d = nn.Conv2d(3, 1, 3) self.conv2d_2 = nn.Conv2d(3, 2, 3)
def test_pretrainedinit(): 'test PretrainedInit class.' modelA = FooModule() constant_func = ConstantInit(val=1, bias=2, layer=['Conv2d', 'Linear']) modelA.apply(constant_func) modelB = FooModule() funcB = PretrainedInit(checkpoint='modelA.pth') modelC = nn.Linear(1, 2) funcC = Pretrai...
def test_initialize(): model = nn.Sequential(nn.Conv2d(3, 1, 3), nn.ReLU(), nn.Linear(1, 2)) foonet = FooModule() init_cfg = dict(type='Constant', layer=['Conv2d', 'Linear'], val=1, bias=2) initialize(model, init_cfg) assert torch.equal(model[0].weight, torch.full(model[0].weight.shape, 1.0)) ...
@patch('torch.__version__', torch_version) @pytest.mark.parametrize('in_w,in_h,in_channel,out_channel,kernel_size,stride,padding,dilation', [(10, 10, 1, 1, 3, 1, 0, 1), (20, 20, 3, 3, 5, 2, 1, 2)]) def test_conv2d(in_w, in_h, in_channel, out_channel, kernel_size, stride, padding, dilation): '\n CommandLine:\n ...
@patch('torch.__version__', torch_version) @pytest.mark.parametrize('in_w,in_h,in_t,in_channel,out_channel,kernel_size,stride,padding,dilation', [(10, 10, 10, 1, 1, 3, 1, 0, 1), (20, 20, 20, 3, 3, 5, 2, 1, 2)]) def test_conv3d(in_w, in_h, in_t, in_channel, out_channel, kernel_size, stride, padding, dilation): '\n...
@patch('torch.__version__', torch_version) @pytest.mark.parametrize('in_w,in_h,in_channel,out_channel,kernel_size,stride,padding,dilation', [(10, 10, 1, 1, 3, 1, 0, 1), (20, 20, 3, 3, 5, 2, 1, 2)]) def test_conv_transposed_2d(in_w, in_h, in_channel, out_channel, kernel_size, stride, padding, dilation): x_empty = ...
@patch('torch.__version__', torch_version) @pytest.mark.parametrize('in_w,in_h,in_t,in_channel,out_channel,kernel_size,stride,padding,dilation', [(10, 10, 10, 1, 1, 3, 1, 0, 1), (20, 20, 20, 3, 3, 5, 2, 1, 2)]) def test_conv_transposed_3d(in_w, in_h, in_t, in_channel, out_channel, kernel_size, stride, padding, dilati...
@patch('torch.__version__', torch_version) @pytest.mark.parametrize('in_w,in_h,in_channel,out_channel,kernel_size,stride,padding,dilation', [(10, 10, 1, 1, 3, 1, 0, 1), (20, 20, 3, 3, 5, 2, 1, 2)]) def test_max_pool_2d(in_w, in_h, in_channel, out_channel, kernel_size, stride, padding, dilation): x_empty = torch.r...
@patch('torch.__version__', torch_version) @pytest.mark.parametrize('in_w,in_h,in_t,in_channel,out_channel,kernel_size,stride,padding,dilation', [(10, 10, 10, 1, 1, 3, 1, 0, 1), (20, 20, 20, 3, 3, 5, 2, 1, 2)]) @pytest.mark.skipif(((torch.__version__ == 'parrots') and (not torch.cuda.is_available())), reason='parrots...
@patch('torch.__version__', torch_version) @pytest.mark.parametrize('in_w,in_h,in_feature,out_feature', [(10, 10, 1, 1), (20, 20, 3, 3)]) def test_linear(in_w, in_h, in_feature, out_feature): x_empty = torch.randn(0, in_feature, requires_grad=True) torch.manual_seed(0) wrapper = Linear(in_feature, out_fea...
@patch('mmcv.cnn.bricks.wrappers.TORCH_VERSION', (1, 10)) def test_nn_op_forward_called(): for m in ['Conv2d', 'ConvTranspose2d', 'MaxPool2d']: with patch(f'torch.nn.{m}.forward') as nn_module_forward: x_empty = torch.randn(0, 3, 10, 10) wrapper = eval(m)(3, 2, 1) wrapp...
@contextmanager def build_temporary_directory(): 'Build a temporary directory containing many files to test\n ``FileClient.list_dir_or_file``.\n\n . \n\n | -- dir1 \n\n | -- | -- text3.txt \n\n | -- dir2 \n\n | -- | -- dir3 \n\n | -- | -- | -- text4.txt \n\n | -- | -- img.jpg \n\n | -- ...
@contextmanager def delete_and_reset_method(obj, method): method_obj = deepcopy(getattr(type(obj), method)) try: delattr(type(obj), method) (yield) finally: setattr(type(obj), method, method_obj)
class MockS3Client(): def __init__(self, enable_mc=True): self.enable_mc = enable_mc def Get(self, filepath): with open(filepath, 'rb') as f: content = f.read() return content
class MockPetrelClient(): def __init__(self, enable_mc=True, enable_multi_cluster=False): self.enable_mc = enable_mc self.enable_multi_cluster = enable_multi_cluster def Get(self, filepath): with open(filepath, 'rb') as f: content = f.read() return content de...
class MockMemcachedClient(): def __init__(self, server_list_cfg, client_cfg): pass def Get(self, filepath, buffer): with open(filepath, 'rb') as f: buffer.content = f.read()
class TestFileClient(): @classmethod def setup_class(cls): cls.test_data_dir = (Path(__file__).parent / 'data') cls.img_path = (cls.test_data_dir / 'color.jpg') cls.img_shape = (300, 400, 3) cls.text_path = (cls.test_data_dir / 'filelist.txt') def test_error(self): ...
def _test_handler(file_format, test_obj, str_checker, mode='r+'): dump_str = mmcv.dump(test_obj, file_format=file_format) str_checker(dump_str) tmp_filename = osp.join(tempfile.gettempdir(), 'mmcv_test_dump') mmcv.dump(test_obj, tmp_filename, file_format=file_format) assert osp.isfile(tmp_filename...
def test_json(): def json_checker(dump_str): assert (dump_str in ['[{"a": "abc", "b": 1}, 2, "c"]', '[{"b": 1, "a": "abc"}, 2, "c"]']) _test_handler('json', obj_for_test, json_checker)
def test_yaml(): def yaml_checker(dump_str): assert (dump_str in ['- {a: abc, b: 1}\n- 2\n- c\n', '- {b: 1, a: abc}\n- 2\n- c\n', '- a: abc\n b: 1\n- 2\n- c\n', '- b: 1\n a: abc\n- 2\n- c\n']) _test_handler('yaml', obj_for_test, yaml_checker)
def test_pickle(): def pickle_checker(dump_str): import pickle assert (pickle.loads(dump_str) == obj_for_test) _test_handler('pickle', obj_for_test, pickle_checker, mode='rb+')
def test_exception(): test_obj = [{'a': 'abc', 'b': 1}, 2, 'c'] with pytest.raises(ValueError): mmcv.dump(test_obj) with pytest.raises(TypeError): mmcv.dump(test_obj, 'tmp.txt')
def test_register_handler(): @mmcv.register_handler('txt') class TxtHandler1(mmcv.BaseFileHandler): def load_from_fileobj(self, file): return file.read() def dump_to_fileobj(self, obj, file): file.write(str(obj)) def dump_to_str(self, obj, **kwargs): ...
def test_list_from_file(): filename = osp.join(osp.dirname(__file__), 'data/filelist.txt') filelist = mmcv.list_from_file(filename) assert (filelist == ['1.jpg', '2.jpg', '3.jpg', '4.jpg', '5.jpg']) filelist = mmcv.list_from_file(filename, prefix='a/') assert (filelist == ['a/1.jpg', 'a/2.jpg', 'a...
def test_dict_from_file(): filename = osp.join(osp.dirname(__file__), 'data/mapping.txt') mapping = mmcv.dict_from_file(filename) assert (mapping == {'1': 'cat', '2': ['dog', 'cow'], '3': 'panda'}) mapping = mmcv.dict_from_file(filename, key_type=int) assert (mapping == {1: 'cat', 2: ['dog', 'cow'...
@pytest.mark.skipif((torch is None), reason='requires torch library') def test_tensor2imgs(): with pytest.raises(AssertionError): tensor = np.random.rand(2, 3, 3) mmcv.tensor2imgs(tensor) with pytest.raises(AssertionError): tensor = torch.randn(2, 3, 3) mmcv.tensor2imgs(tensor)...
@patch('mmcv.__path__', [osp.join(osp.dirname(__file__), 'data/')]) def test_set_mmcv_home(): os.environ.pop(ENV_MMCV_HOME, None) mmcv_home = osp.join(osp.dirname(__file__), 'data/model_zoo/mmcv_home/') os.environ[ENV_MMCV_HOME] = mmcv_home assert (_get_mmcv_home() == mmcv_home)
@patch('mmcv.__path__', [osp.join(osp.dirname(__file__), 'data/')]) def test_default_mmcv_home(): os.environ.pop(ENV_MMCV_HOME, None) os.environ.pop(ENV_XDG_CACHE_HOME, None) assert (_get_mmcv_home() == os.path.expanduser(os.path.join(DEFAULT_CACHE_DIR, 'mmcv'))) model_urls = get_external_models() ...
@patch('mmcv.__path__', [osp.join(osp.dirname(__file__), 'data/')]) def test_get_external_models(): os.environ.pop(ENV_MMCV_HOME, None) mmcv_home = osp.join(osp.dirname(__file__), 'data/model_zoo/mmcv_home/') os.environ[ENV_MMCV_HOME] = mmcv_home ext_urls = get_external_models() assert (ext_urls =...
@patch('mmcv.__path__', [osp.join(osp.dirname(__file__), 'data/')]) def test_get_deprecated_models(): os.environ.pop(ENV_MMCV_HOME, None) mmcv_home = osp.join(osp.dirname(__file__), 'data/model_zoo/mmcv_home/') os.environ[ENV_MMCV_HOME] = mmcv_home dep_urls = get_deprecated_model_names() assert (d...
def load_from_http(url, map_location=None): return ('url:' + url)
def load_url(url, map_location=None, model_dir=None): return load_from_http(url)
def load(filepath, map_location=None): return ('local:' + filepath)
@patch('mmcv.__path__', [osp.join(osp.dirname(__file__), 'data/')]) @patch('mmcv.runner.checkpoint.load_from_http', load_from_http) @patch('mmcv.runner.checkpoint.load_url', load_url) @patch('torch.load', load) def test_load_external_url(): url = _load_checkpoint('modelzoo://resnet50') if (TORCH_VERSION < '1....
@pytest.mark.parametrize('device', ['cpu', pytest.param('cuda', marks=pytest.mark.skipif((not torch.cuda.is_available()), reason='requires CUDA support'))]) def test_active_rotated_filter(device): feature = torch.tensor(np_feature, dtype=torch.float, device=device, requires_grad=True) indices = torch.tensor(n...
@pytest.mark.skipif((not torch.cuda.is_available()), reason='requires CUDA support') def test_paconv_assign_scores(): scores = torch.tensor([[[[0.06947571, 0.6065746], [0.28462553, 0.8378516], [0.7595994, 0.97220325], [0.519155, 0.766185]], [[0.15348864, 0.6051019], [0.21510637, 0.31916398], [0.00236845, 0.584259...
@pytest.mark.skipif((not torch.cuda.is_available()), reason='requires CUDA support') def test_ball_query(): new_xyz = torch.tensor([[[(- 0.074), 1.3147, (- 1.3625)], [(- 2.2769), 2.7817, (- 0.2334)], [(- 0.4003), 2.4666, (- 0.5116)], [(- 0.074), 1.3147, (- 1.3625)], [(- 0.074), 1.3147, (- 1.3625)]], [[(- 2.0289),...
@pytest.mark.skipif((not torch.cuda.is_available()), reason='requires CUDA support') class TestBBox(object): def _test_bbox_overlaps(self, dtype=torch.float): from mmcv.ops import bbox_overlaps b1 = torch.tensor([[1.0, 1.0, 3.0, 4.0], [2.0, 2.0, 3.0, 4.0], [7.0, 7.0, 8.0, 8.0]]).cuda().type(dtype...
class TestBilinearGridSample(object): def _test_bilinear_grid_sample(self, dtype=torch.float, align_corners=False, multiplier=1, precision=0.001): from mmcv.ops.point_sample import bilinear_grid_sample input = torch.rand(1, 1, 20, 20, dtype=dtype) grid = torch.Tensor([[[1, 0, 0], [0, 1, 0...
def _test_border_align_allclose(device, dtype, pool_size): if ((not torch.cuda.is_available()) and (device == 'cuda')): pytest.skip('test requires GPU') try: from mmcv.ops import BorderAlign, border_align except ModuleNotFoundError: pytest.skip('BorderAlign op is not successfully c...
@pytest.mark.parametrize('device', ['cuda']) @pytest.mark.parametrize('dtype', [torch.float, torch.half, torch.double]) @pytest.mark.parametrize('pool_size', [1, 2]) def test_border_align(device, dtype, pool_size): _test_border_align_allclose(device, dtype, pool_size)
class TestBoxIoURotated(object): def test_box_iou_rotated_cpu(self): from mmcv.ops import box_iou_rotated np_boxes1 = np.asarray([[1.0, 1.0, 3.0, 4.0, 0.5], [2.0, 2.0, 3.0, 4.0, 0.6], [7.0, 7.0, 8.0, 8.0, 0.4]], dtype=np.float32) np_boxes2 = np.asarray([[0.0, 2.0, 2.0, 5.0, 0.3], [2.0, 1....
class TestCarafe(object): def test_carafe_naive_gradcheck(self): if (not torch.cuda.is_available()): return from mmcv.ops import CARAFENaive feat = torch.randn(2, 64, 3, 3, requires_grad=True, device='cuda').double() mask = torch.randn(2, 100, 6, 6, requires_grad=True,...
class Loss(nn.Module): def __init__(self): super().__init__() def forward(self, input, target): input = input.view((- 1)) target = target.view((- 1)) return torch.mean((input - target))
class TestCrissCrossAttention(object): def test_cc_attention(self): device = torch.device(('cuda:0' if torch.cuda.is_available() else 'cpu')) from mmcv.ops import CrissCrossAttention loss_func = Loss() input = np.fromfile('tests/data/for_ccattention/ccattention_input.bin', dtype=n...
def test_contour_expand(): from mmcv.ops import contour_expand np_internal_kernel_label = np.array([[0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 1, 1, 0, 0, 0, 0, 2, 0], [0, 0, 1, 1, 0, 0, 0, 0, 2, 0], [0, 0, 1, 1, 0, 0, 0, 0, 2, 0], [0, 0, 1, 1, 0, 0,...
@pytest.mark.skipif((not torch.cuda.is_available()), reason='requires CUDA support') def test_convex_iou(): pointsets = torch.from_numpy(np_pointsets).cuda().float() polygons = torch.from_numpy(np_polygons).cuda().float() expected_iou = torch.from_numpy(np_expected_iou).cuda().float() assert torch.all...
@pytest.mark.skipif((not torch.cuda.is_available()), reason='requires CUDA support') def test_convex_giou(): pointsets = torch.from_numpy(np_pointsets).cuda().float() polygons = torch.from_numpy(np_polygons).cuda().float() expected_giou = torch.from_numpy(np_expected_giou).cuda().float() expected_grad...
def test_corner_pool_device_and_dtypes_cpu(): '\n CommandLine:\n xdoctest -m tests/test_corner_pool.py test_corner_pool_device_and_dtypes_cpu\n ' with pytest.raises(AssertionError): pool = CornerPool('corner') lr_tensor = torch.tensor([[[[0, 0, 0, 0, 0], [2, 1, 3, 0, 2], [...
def assert_equal_tensor(tensor_a, tensor_b): assert tensor_a.eq(tensor_b).all()
class TestCorrelation(): def _test_correlation(self, dtype=torch.float): layer = Correlation(max_displacement=0) input1 = torch.tensor(_input1, dtype=dtype).cuda() input2 = torch.tensor(_input2, dtype=dtype).cuda() input1.requires_grad = True input2.requires_grad = True ...
class TestDeformconv(object): def _test_deformconv(self, dtype=torch.float, threshold=0.001, device='cuda', batch_size=10, im2col_step=2): if ((not torch.cuda.is_available()) and (device == 'cuda')): pytest.skip('test requires GPU') from mmcv.ops import DeformConv2dPack c_in =...
class TestDeformRoIPool(object): def test_deform_roi_pool_gradcheck(self): if (not torch.cuda.is_available()): return from mmcv.ops import DeformRoIPoolPack pool_h = 2 pool_w = 2 spatial_scale = 1.0 sampling_ratio = 2 for case in inputs: ...
class Testfocalloss(object): def _test_softmax(self, dtype=torch.float): if (not torch.cuda.is_available()): return from mmcv.ops import softmax_focal_loss alpha = 0.25 gamma = 2.0 for (case, output) in zip(inputs, softmax_outputs): np_x = np.array(...
@pytest.mark.skipif((not torch.cuda.is_available()), reason='requires CUDA support') def test_fps(): xyz = torch.tensor([[[(- 0.2748), 1.002, (- 1.1674)], [0.1015, 1.3952, (- 1.2681)], [(- 0.807), 2.4137, (- 0.5845)], [(- 1.0001), 2.1982, (- 0.5859)], [0.3841, 1.8983, (- 0.7431)]], [[(- 1.0696), 3.0758, (- 0.1899...
@pytest.mark.skipif((not torch.cuda.is_available()), reason='requires CUDA support') def test_fps_with_dist(): xyz = torch.tensor([[[(- 0.2748), 1.002, (- 1.1674)], [0.1015, 1.3952, (- 1.2681)], [(- 0.807), 2.4137, (- 0.5845)], [(- 1.0001), 2.1982, (- 0.5859)], [0.3841, 1.8983, (- 0.7431)]], [[(- 1.0696), 3.0758,...
class TestFusedBiasLeakyReLU(object): @classmethod def setup_class(cls): if (not torch.cuda.is_available()): return cls.input_tensor = torch.randn((2, 2, 2, 2), requires_grad=True).cuda() cls.bias = torch.zeros(2, requires_grad=True).cuda() @pytest.mark.skipif((not to...
@pytest.mark.skipif((not torch.cuda.is_available()), reason='requires CUDA support') def test_gather_points(): features = torch.tensor([[[(- 1.6095), (- 0.1029), (- 0.8876), (- 1.2447), (- 2.4031), 0.3708, (- 1.1586), (- 1.4967), (- 0.48), 0.2252], [1.9138, 3.4979, 1.6854, 1.5631, 3.6776, 3.1154, 2.1705, 2.5221, ...
@pytest.mark.skipif((not torch.cuda.is_available()), reason='requires CUDA support') def test_grouping_points(): idx = torch.tensor([[[0, 0, 0], [3, 3, 3], [8, 8, 8], [0, 0, 0], [0, 0, 0], [0, 0, 0]], [[0, 0, 0], [6, 6, 6], [9, 9, 9], [0, 0, 0], [0, 0, 0], [0, 0, 0]]]).int().cuda() festures = torch.tensor([[[...
class TestInfo(object): def test_info(self): if (not torch.cuda.is_available()): return from mmcv.ops import get_compiler_version, get_compiling_cuda_version cv = get_compiler_version() ccv = get_compiling_cuda_version() assert (cv is not None) assert (...
@pytest.mark.skipif((not torch.cuda.is_available()), reason='requires CUDA support') def test_boxes_iou_bev(): np_boxes1 = np.asarray([[1.0, 1.0, 3.0, 4.0, 0.5], [2.0, 2.0, 3.0, 4.0, 0.6], [7.0, 7.0, 8.0, 8.0, 0.4]], dtype=np.float32) np_boxes2 = np.asarray([[0.0, 2.0, 2.0, 5.0, 0.3], [2.0, 1.0, 3.0, 3.0, 0.5...
@pytest.mark.skipif((not torch.cuda.is_available()), reason='requires CUDA support') def test_nms_bev(): np_boxes = np.array([[6.0, 3.0, 8.0, 7.0, 2.0], [3.0, 6.0, 9.0, 11.0, 1.0], [3.0, 7.0, 10.0, 12.0, 1.0], [1.0, 4.0, 13.0, 7.0, 3.0]], dtype=np.float32) np_scores = np.array([0.6, 0.9, 0.7, 0.2], dtype=np.f...
@pytest.mark.skipif((not torch.cuda.is_available()), reason='requires CUDA support') def test_nms_normal_bev(): np_boxes = np.array([[6.0, 3.0, 8.0, 7.0, 2.0], [3.0, 6.0, 9.0, 11.0, 1.0], [3.0, 7.0, 10.0, 12.0, 1.0], [1.0, 4.0, 13.0, 7.0, 3.0]], dtype=np.float32) np_scores = np.array([0.6, 0.9, 0.7, 0.2], dty...
@pytest.mark.skipif((not torch.cuda.is_available()), reason='requires CUDA support') def test_knn(): new_xyz = torch.tensor([[[(- 0.074), 1.3147, (- 1.3625)], [(- 2.2769), 2.7817, (- 0.2334)], [(- 0.4003), 2.4666, (- 0.5116)], [(- 0.074), 1.3147, (- 1.3625)], [(- 0.074), 1.3147, (- 1.3625)]], [[(- 2.0289), 2.4952...
class TestMaskedConv2d(object): def test_masked_conv2d(self): if (not torch.cuda.is_available()): return from mmcv.ops import MaskedConv2d input = torch.randn(1, 3, 16, 16, requires_grad=True, device='cuda') mask = torch.randn(1, 16, 16, requires_grad=True, device='cud...
def test_sum_cell(): inputs_x = torch.randn([2, 256, 32, 32]) inputs_y = torch.randn([2, 256, 16, 16]) sum_cell = SumCell(256, 256) output = sum_cell(inputs_x, inputs_y, out_size=inputs_x.shape[(- 2):]) assert (output.size() == inputs_x.size()) output = sum_cell(inputs_x, inputs_y, out_size=in...
def test_concat_cell(): inputs_x = torch.randn([2, 256, 32, 32]) inputs_y = torch.randn([2, 256, 16, 16]) concat_cell = ConcatCell(256, 256) output = concat_cell(inputs_x, inputs_y, out_size=inputs_x.shape[(- 2):]) assert (output.size() == inputs_x.size()) output = concat_cell(inputs_x, inputs...
def test_global_pool_cell(): inputs_x = torch.randn([2, 256, 32, 32]) inputs_y = torch.randn([2, 256, 32, 32]) gp_cell = GlobalPoolingCell(with_out_conv=False) gp_cell_out = gp_cell(inputs_x, inputs_y, out_size=inputs_x.shape[(- 2):]) assert (gp_cell_out.size() == inputs_x.size()) gp_cell = Gl...
def test_resize_methods(): inputs_x = torch.randn([2, 256, 128, 128]) target_resize_sizes = [(128, 128), (256, 256)] resize_methods_list = ['nearest', 'bilinear'] for method in resize_methods_list: merge_cell = BaseMergeCell(upsample_mode=method) for target_size in target_resize_sizes:...
@pytest.mark.skipif((not torch.cuda.is_available()), reason='requires CUDA support') def test_min_area_polygons(): pointsets = torch.from_numpy(np_pointsets).cuda().float() assert np.allclose(min_area_polygons(pointsets).cpu().numpy(), expected_polygons, atol=0.0001)
class TestMdconv(object): def _test_mdconv(self, dtype=torch.float, device='cuda'): if ((not torch.cuda.is_available()) and (device == 'cuda')): pytest.skip('test requires GPU') from mmcv.ops import ModulatedDeformConv2dPack input = torch.tensor(input_t, dtype=dtype, device=de...
@pytest.mark.parametrize('device_type', ['cpu', pytest.param('cuda:0', marks=pytest.mark.skipif((not torch.cuda.is_available()), reason='requires CUDA support'))]) def test_multiscale_deformable_attention(device_type): with pytest.raises(ValueError): MultiScaleDeformableAttention(embed_dims=256, num_heads...
def test_forward_multi_scale_deformable_attn_pytorch(): (N, M, D) = (1, 2, 2) (Lq, L, P) = (2, 2, 2) shapes = torch.as_tensor([(6, 4), (3, 2)], dtype=torch.long) S = sum([(H * W).item() for (H, W) in shapes]) torch.manual_seed(3) value = (torch.rand(N, S, M, D) * 0.01) sampling_locations =...
@pytest.mark.skipif((not torch.cuda.is_available()), reason='requires CUDA support') def test_forward_equal_with_pytorch_double(): (N, M, D) = (1, 2, 2) (Lq, L, P) = (2, 2, 2) shapes = torch.as_tensor([(6, 4), (3, 2)], dtype=torch.long).cuda() level_start_index = torch.cat((shapes.new_zeros((1,)), sha...
@pytest.mark.skipif((not torch.cuda.is_available()), reason='requires CUDA support') def test_forward_equal_with_pytorch_float(): (N, M, D) = (1, 2, 2) (Lq, L, P) = (2, 2, 2) shapes = torch.as_tensor([(6, 4), (3, 2)], dtype=torch.long).cuda() level_start_index = torch.cat((shapes.new_zeros((1,)), shap...
@pytest.mark.skipif((not torch.cuda.is_available()), reason='requires CUDA support') @pytest.mark.parametrize('channels', [4, 30, 32, 64, 71, 1025]) def test_gradient_numerical(channels, grad_value=True, grad_sampling_loc=True, grad_attn_weight=True): (N, M, _) = (1, 2, 2) (Lq, L, P) = (2, 2, 2) shapes = ...
@pytest.mark.skipif((not torch.cuda.is_available()), reason='requires CUDA support') def test_points_in_polygons(): points = np.array([[300.0, 300.0], [400.0, 400.0], [100.0, 100], [300, 250], [100, 0]]) polygons = np.array([[200.0, 200.0, 400.0, 400.0, 500.0, 200.0, 400.0, 100.0], [400.0, 400.0, 500.0, 500.0...
class Loss(nn.Module): def __init__(self): super().__init__() def forward(self, input, target): input = input.view((- 1)) target = target.view((- 1)) return torch.mean((input - target))
class TestPSAMask(object): def test_psa_mask_collect(self): if (not torch.cuda.is_available()): return from mmcv.ops import PSAMask test_loss = Loss() input = np.fromfile('tests/data/for_psa_mask/psa_input.bin', dtype=np.float32) output_collect = np.fromfile('t...
@pytest.mark.skipif((not torch.cuda.is_available()), reason='requires CUDA support') def test_roialign_rotated_gradcheck(): x = torch.tensor(np_feature, dtype=torch.float, device='cuda', requires_grad=True) rois = torch.tensor(np_rois, dtype=torch.float, device='cuda') froipool = RiRoIAlignRotated((pool_h...
@pytest.mark.skipif((not torch.cuda.is_available()), reason='requires CUDA support') def test_roialign_rotated_allclose(): x = torch.tensor(np_feature, dtype=torch.float, device='cuda', requires_grad=True) rois = torch.tensor(np_rois, dtype=torch.float, device='cuda') froipool = RiRoIAlignRotated((pool_h,...
def _test_roialign_gradcheck(device, dtype): if ((not torch.cuda.is_available()) and (device == 'cuda')): pytest.skip('test requires GPU') try: from mmcv.ops import RoIAlign except ModuleNotFoundError: pytest.skip('RoIAlign op is not successfully compiled') if (dtype is torch.h...