code stringlengths 17 6.64M |
|---|
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... |
def _test_roialign_allclose(device, dtype):
if ((not torch.cuda.is_available()) and (device == 'cuda')):
pytest.skip('test requires GPU')
try:
from mmcv.ops import roi_align
except ModuleNotFoundError:
pytest.skip('test requires compilation')
pool_h = 2
pool_w = 2
spati... |
@pytest.mark.parametrize('device', ['cuda', 'cpu'])
@pytest.mark.parametrize('dtype', [torch.float, torch.double, torch.half])
def test_roialign(device, dtype):
if (dtype is torch.double):
_test_roialign_gradcheck(device=device, dtype=dtype)
_test_roialign_allclose(device=device, dtype=dtype)
|
def _test_roialign_rotated_gradcheck(device, dtype):
if ((not torch.cuda.is_available()) and (device == 'cuda')):
pytest.skip('unittest does not support GPU yet.')
try:
from mmcv.ops import RoIAlignRotated
except ModuleNotFoundError:
pytest.skip('RoIAlignRotated op is not successfu... |
def _test_roialign_rotated_allclose(device, dtype):
if ((not torch.cuda.is_available()) and (device == 'cuda')):
pytest.skip('unittest does not support GPU yet.')
try:
from mmcv.ops import RoIAlignRotated, roi_align_rotated
except ModuleNotFoundError:
pytest.skip('test requires com... |
@pytest.mark.parametrize('device', ['cuda', 'cpu'])
@pytest.mark.parametrize('dtype', [torch.float, torch.double, torch.half])
def test_roialign_rotated(device, dtype):
if (dtype is torch.double):
_test_roialign_rotated_gradcheck(device=device, dtype=dtype)
_test_roialign_rotated_allclose(device=devic... |
class TestRoiPool(object):
def test_roipool_gradcheck(self):
if (not torch.cuda.is_available()):
return
from mmcv.ops import RoIPool
pool_h = 2
pool_w = 2
spatial_scale = 1.0
for case in inputs:
np_input = np.array(case[0])
np_ro... |
@pytest.mark.skipif((not torch.cuda.is_available()), reason='requires CUDA support')
def test_RoIAwarePool3d():
roiaware_pool3d_max = RoIAwarePool3d(out_size=4, max_pts_per_voxel=128, mode='max')
roiaware_pool3d_avg = RoIAwarePool3d(out_size=4, max_pts_per_voxel=128, mode='avg')
rois = torch.tensor([[1.0,... |
@pytest.mark.skipif((not torch.cuda.is_available()), reason='requires CUDA support')
def test_points_in_boxes_part():
boxes = torch.tensor([[[1.0, 2.0, 3.0, 4.0, 5.0, 6.0, 0.3]], [[(- 10.0), 23.0, 16.0, 10, 20, 20, 0.5]]], dtype=torch.float32).cuda()
pts = torch.tensor([[[1, 2, 3.3], [1.2, 2.5, 3.0], [0.8, 2.... |
def test_points_in_boxes_cpu():
boxes = torch.tensor([[[1.0, 2.0, 3.0, 4.0, 5.0, 6.0, 0.3], [(- 10.0), 23.0, 16.0, 10, 20, 20, 0.5]]], dtype=torch.float32)
pts = torch.tensor([[[1, 2, 3.3], [1.2, 2.5, 3.0], [0.8, 2.1, 3.5], [1.6, 2.6, 3.6], [0.8, 1.2, 3.9], [(- 9.2), 21.0, 18.2], [3.8, 7.9, 6.3], [4.7, 3.5, (... |
@pytest.mark.skipif((not torch.cuda.is_available()), reason='requires CUDA support')
def test_points_in_boxes_all():
boxes = torch.tensor([[[1.0, 2.0, 3.0, 4.0, 5.0, 6.0, 0.3], [(- 10.0), 23.0, 16.0, 10, 20, 20, 0.5]]], dtype=torch.float32).cuda()
pts = torch.tensor([[[1, 2, 3.3], [1.2, 2.5, 3.0], [0.8, 2.1, ... |
@pytest.mark.skipif((not torch.cuda.is_available()), reason='requires CUDA support')
def test_gather_points():
feats = torch.tensor([[1, 2, 3.3], [1.2, 2.5, 3.0], [0.8, 2.1, 3.5], [1.6, 2.6, 3.6], [0.8, 1.2, 3.9], [(- 9.2), 21.0, 18.2], [3.8, 7.9, 6.3], [4.7, 3.5, (- 12.2)], [3.8, 7.6, (- 2)], [(- 10.6), (- 12.9)... |
@pytest.mark.skipif((not torch.cuda.is_available()), reason='requires CUDA support')
def test_rotated_feature_align():
feature = torch.tensor([[[[1.2924, (- 0.2172), (- 0.5222), 0.1172], [0.9144, 1.2248, 1.3115, (- 0.969)], [(- 0.8949), (- 1.1797), (- 0.9093), (- 0.3961)], [(- 0.4586), 0.5062, (- 0.7947), (- 0.73... |
def test_sacconv():
x = torch.rand(1, 3, 256, 256)
saconv = SAConv2d(3, 5, kernel_size=3, padding=1)
sac_out = saconv(x)
refer_conv = nn.Conv2d(3, 5, kernel_size=3, padding=1)
refer_out = refer_conv(x)
assert (sac_out.shape == refer_out.shape)
dalited_saconv = SAConv2d(3, 5, kernel_size=3,... |
def make_sparse_convmodule(in_channels, out_channels, kernel_size, indice_key, stride=1, padding=0, conv_type='SubMConv3d', norm_cfg=None, order=('conv', 'norm', 'act')):
'Make sparse convolution module.\n\n Args:\n in_channels (int): the number of input channels\n out_channels (int): the number ... |
@pytest.mark.skipif((not torch.cuda.is_available()), reason='requires CUDA support')
def test_make_sparse_convmodule():
voxel_features = torch.tensor([[6.56126, 0.9648336, (- 1.7339306), 0.315], [6.8162713, (- 2.480431), (- 1.3616394), 0.36], [11.643568, (- 4.744306), (- 1.3580885), 0.16], [23.482342, 6.5036807, ... |
class TestSyncBN(object):
def dist_init(self):
rank = int(os.environ['SLURM_PROCID'])
world_size = int(os.environ['SLURM_NTASKS'])
local_rank = int(os.environ['SLURM_LOCALID'])
node_list = str(os.environ['SLURM_NODELIST'])
node_parts = re.findall('[0-9]+', node_list)
... |
def remove_tmp_file(func):
@wraps(func)
def wrapper(*args, **kwargs):
onnx_file = 'tmp.onnx'
kwargs['onnx_file'] = onnx_file
try:
result = func(*args, **kwargs)
finally:
if os.path.exists(onnx_file):
os.remove(onnx_file)
return r... |
@remove_tmp_file
def export_nms_module_to_onnx(module, onnx_file):
torch_model = module()
torch_model.eval()
input = (torch.rand([100, 4], dtype=torch.float32), torch.rand([100], dtype=torch.float32))
torch.onnx.export(torch_model, input, onnx_file, opset_version=11, input_names=['boxes', 'scores'], o... |
def test_can_handle_nms_with_constant_maxnum():
class ModuleNMS(torch.nn.Module):
def forward(self, boxes, scores):
return nms(boxes, scores, iou_threshold=0.4, max_num=10)
onnx_model = export_nms_module_to_onnx(ModuleNMS)
preprocess_onnx_model = preprocess_onnx(onnx_model)
for n... |
def test_can_handle_nms_with_undefined_maxnum():
class ModuleNMS(torch.nn.Module):
def forward(self, boxes, scores):
return nms(boxes, scores, iou_threshold=0.4)
onnx_model = export_nms_module_to_onnx(ModuleNMS)
preprocess_onnx_model = preprocess_onnx(onnx_model)
for node in prep... |
@pytest.mark.skipif((not torch.cuda.is_available()), reason='requires CUDA support')
def test_three_interpolate():
features = torch.tensor([[[2.435, 4.7516, 4.4995, 2.435, 2.435, 2.435], [3.1236, 2.6278, 3.0447, 3.1236, 3.1236, 3.1236], [2.6732, 2.8677, 2.6436, 2.6732, 2.6732, 2.6732], [0.0124, 7.015, 7.0199, 0.0... |
@pytest.mark.skipif((not torch.cuda.is_available()), reason='requires CUDA support')
def test_three_nn():
known = torch.tensor([[[(- 1.8373), 3.5605, (- 0.7867)], [0.7615, 2.942, 0.2314], [(- 0.6503), 3.6637, (- 1.0622)], [(- 1.8373), 3.5605, (- 0.7867)], [(- 1.8373), 3.5605, (- 0.7867)]], [[(- 1.3399), 1.9991, (... |
def _test_tinshift_gradcheck(dtype):
try:
from mmcv.ops import tin_shift
except ModuleNotFoundError:
pytest.skip('TINShift op is not successfully compiled')
if (dtype == torch.half):
pytest.skip('"add_cpu/sub_cpu" not implemented for Half')
for shift in shifts:
np_input... |
def _test_tinshift_allclose(dtype):
try:
from mmcv.ops import tin_shift
except ModuleNotFoundError:
pytest.skip('TINShift op is not successfully compiled')
for (shift, output, grad) in zip(shifts, outputs, grads):
np_input = np.array(inputs)
np_shift = np.array(shift)
... |
def _test_tinshift_assert(dtype):
try:
from mmcv.ops import tin_shift
except ModuleNotFoundError:
pytest.skip('TINShift op is not successfully compiled')
inputs = [torch.rand(2, 3, 4, 2), torch.rand(2, 3, 4, 2)]
shifts = [torch.rand(2, 3), torch.rand(2, 5)]
for (x, shift) in zip(in... |
@pytest.mark.skipif((not torch.cuda.is_available()), reason='requires CUDA support')
@pytest.mark.parametrize('dtype', [torch.float, torch.double, torch.half])
def test_tinshift(dtype):
_test_tinshift_allclose(dtype=dtype)
_test_tinshift_gradcheck(dtype=dtype)
_test_tinshift_assert(dtype=dtype)
|
def mock(*args, **kwargs):
pass
|
@patch('torch.distributed._broadcast_coalesced', mock)
@patch('torch.distributed.broadcast', mock)
@patch('torch.nn.parallel.DistributedDataParallel._ddp_init_helper', mock)
def test_is_module_wrapper():
class Model(nn.Module):
def __init__(self):
super().__init__()
self.conv = n... |
def test_get_input_device():
input = torch.zeros([1, 3, 3, 3])
assert (get_input_device(input) == (- 1))
inputs = [torch.zeros([1, 3, 3, 3]), torch.zeros([1, 4, 4, 4])]
assert (get_input_device(inputs) == (- 1))
if torch.cuda.is_available():
input = torch.zeros([1, 3, 3, 3]).cuda()
... |
def test_scatter():
input = torch.zeros([1, 3, 3, 3])
output = scatter(input=input, devices=[(- 1)])
assert torch.allclose(input, output)
inputs = [torch.zeros([1, 3, 3, 3]), torch.zeros([1, 4, 4, 4])]
outputs = scatter(input=inputs, devices=[(- 1)])
for (input, output) in zip(inputs, outputs)... |
def test_Scatter():
target_gpus = [(- 1)]
input = torch.zeros([1, 3, 3, 3])
outputs = Scatter.forward(target_gpus, input)
assert isinstance(outputs, tuple)
assert torch.allclose(input, outputs[0])
target_gpus = [(- 1)]
inputs = [torch.zeros([1, 3, 3, 3]), torch.zeros([1, 4, 4, 4])]
out... |
@COMPONENTS.register_module()
class FooConv1d(BaseModule):
def __init__(self, init_cfg=None):
super().__init__(init_cfg)
self.conv1d = nn.Conv1d(4, 1, 4)
def forward(self, x):
return self.conv1d(x)
|
@COMPONENTS.register_module()
class FooConv2d(BaseModule):
def __init__(self, init_cfg=None):
super().__init__(init_cfg)
self.conv2d = nn.Conv2d(3, 1, 3)
def forward(self, x):
return self.conv2d(x)
|
@COMPONENTS.register_module()
class FooLinear(BaseModule):
def __init__(self, init_cfg=None):
super().__init__(init_cfg)
self.linear = nn.Linear(3, 4)
def forward(self, x):
return self.linear(x)
|
@COMPONENTS.register_module()
class FooLinearConv1d(BaseModule):
def __init__(self, linear=None, conv1d=None, init_cfg=None):
super().__init__(init_cfg)
if (linear is not None):
self.linear = build_from_cfg(linear, COMPONENTS)
if (conv1d is not None):
self.conv1d =... |
@FOOMODELS.register_module()
class FooModel(BaseModule):
def __init__(self, component1=None, component2=None, component3=None, component4=None, init_cfg=None) -> None:
super().__init__(init_cfg)
if (component1 is not None):
self.component1 = build_from_cfg(component1, COMPONENTS)
... |
def test_initilization_info_logger():
import os
import torch.nn as nn
from mmcv.utils.logging import get_logger
class OverloadInitConv(nn.Conv2d, BaseModule):
def init_weights(self):
for p in self.parameters():
with torch.no_grad():
p.fill_(1)
... |
def test_update_init_info():
class DummyModel(BaseModule):
def __init__(self, init_cfg=None):
super().__init__(init_cfg)
self.conv1 = nn.Conv2d(1, 1, 1, 1)
self.conv3 = nn.Conv2d(1, 1, 1, 1)
self.fc1 = nn.Linear(1, 1)
model = DummyModel()
from coll... |
def test_model_weight_init():
'\n Config\n model (FooModel, Linear: weight=1, bias=2, Conv1d: weight=3, bias=4,\n Conv2d: weight=5, bias=6)\n ├──component1 (FooConv1d)\n ├──component2 (FooConv2d)\n ├──component3 (FooLinear)\n ├──component4 (FooLinearConv1d)\n ├──linear... |
def test_nest_components_weight_init():
'\n Config\n model (FooModel, Linear: weight=1, bias=2, Conv1d: weight=3, bias=4,\n Conv2d: weight=5, bias=6)\n ├──component1 (FooConv1d, Conv1d: weight=7, bias=8)\n ├──component2 (FooConv2d, Conv2d: weight=9, bias=10)\n ├──component3 (Foo... |
def test_without_layer_weight_init():
model_cfg = dict(type='FooModel', init_cfg=[dict(type='Constant', val=1, bias=2, layer='Linear'), dict(type='Constant', val=3, bias=4, layer='Conv1d'), dict(type='Constant', val=5, bias=6, layer='Conv2d')], component1=dict(type='FooConv1d', init_cfg=dict(type='Constant', val=... |
def test_override_weight_init():
model_cfg = dict(type='FooModel', init_cfg=[dict(type='Constant', val=10, bias=20, override=dict(name='reg'))], component1=dict(type='FooConv1d'), component3=dict(type='FooLinear'))
model = build_from_cfg(model_cfg, FOOMODELS)
model.init_weights()
assert torch.equal(mo... |
def test_sequential_model_weight_init():
seq_model_cfg = [dict(type='FooConv1d', init_cfg=dict(type='Constant', layer='Conv1d', val=0.0, bias=1.0)), dict(type='FooConv2d', init_cfg=dict(type='Constant', layer='Conv2d', val=2.0, bias=3.0))]
layers = [build_from_cfg(cfg, COMPONENTS) for cfg in seq_model_cfg]
... |
def test_modulelist_weight_init():
models_cfg = [dict(type='FooConv1d', init_cfg=dict(type='Constant', layer='Conv1d', val=0.0, bias=1.0)), dict(type='FooConv2d', init_cfg=dict(type='Constant', layer='Conv2d', val=2.0, bias=3.0))]
layers = [build_from_cfg(cfg, COMPONENTS) for cfg in models_cfg]
modellist ... |
def test_moduledict_weight_init():
models_cfg = dict(foo_conv_1d=dict(type='FooConv1d', init_cfg=dict(type='Constant', layer='Conv1d', val=0.0, bias=1.0)), foo_conv_2d=dict(type='FooConv2d', init_cfg=dict(type='Constant', layer='Conv2d', val=2.0, bias=3.0)))
layers = {name: build_from_cfg(cfg, COMPONENTS) for... |
@MODULE_WRAPPERS.register_module()
class DDPWrapper(object):
def __init__(self, module):
self.module = module
|
class Block(nn.Module):
def __init__(self):
super().__init__()
self.conv = nn.Conv2d(3, 3, 1)
self.norm = nn.BatchNorm2d(3)
|
class Model(nn.Module):
def __init__(self):
super().__init__()
self.block = Block()
self.conv = nn.Conv2d(3, 3, 1)
|
class Mockpavimodel(object):
def __init__(self, name='fakename'):
self.name = name
def download(self, file):
pass
|
def assert_tensor_equal(tensor_a, tensor_b):
assert tensor_a.eq(tensor_b).all()
|
def test_get_state_dict():
if (torch.__version__ == 'parrots'):
state_dict_keys = set(['block.conv.weight', 'block.conv.bias', 'block.norm.weight', 'block.norm.bias', 'block.norm.running_mean', 'block.norm.running_var', 'conv.weight', 'conv.bias'])
else:
state_dict_keys = set(['block.conv.weig... |
def test_load_pavimodel_dist():
sys.modules['pavi'] = MagicMock()
sys.modules['pavi.modelcloud'] = MagicMock()
pavimodel = Mockpavimodel()
import pavi
pavi.modelcloud.get = MagicMock(return_value=pavimodel)
with pytest.raises(AssertionError):
_ = load_from_pavi('MyPaviFolder/checkpoint... |
def test_load_checkpoint_with_prefix():
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)
model = FooModule()
nn.init.constant_(model... |
def test_load_checkpoint():
import os
import re
import tempfile
class PrefixModel(nn.Module):
def __init__(self):
super().__init__()
self.backbone = Model()
pmodel = PrefixModel()
model = Model()
checkpoint_path = os.path.join(tempfile.gettempdir(), 'check... |
def test_load_checkpoint_metadata():
import os
import tempfile
from mmcv.runner import load_checkpoint, save_checkpoint
class ModelV1(nn.Module):
def __init__(self):
super().__init__()
self.block = Block()
self.conv1 = nn.Conv2d(3, 3, 1)
self.c... |
def test_load_classes_name():
import os
import tempfile
from mmcv.runner import load_checkpoint, save_checkpoint
checkpoint_path = os.path.join(tempfile.gettempdir(), 'checkpoint.pth')
model = Model()
save_checkpoint(model, checkpoint_path)
checkpoint = load_checkpoint(model, checkpoint_pa... |
def test_checkpoint_loader():
import os
import tempfile
from mmcv.runner import CheckpointLoader, _load_checkpoint, save_checkpoint
checkpoint_path = os.path.join(tempfile.gettempdir(), 'checkpoint.pth')
model = Model()
save_checkpoint(model, checkpoint_path)
checkpoint = _load_checkpoint(... |
def test_save_checkpoint(tmp_path):
model = Model()
optimizer = optim.SGD(model.parameters(), lr=0.1, momentum=0.9)
with pytest.raises(TypeError):
save_checkpoint(model, '/path/of/your/filename', meta='invalid type')
filename = str((tmp_path / 'checkpoint1.pth'))
save_checkpoint(model, fil... |
def test_load_from_local():
import os
home_path = os.path.expanduser('~')
checkpoint_path = os.path.join(home_path, 'dummy_checkpoint_used_to_test_load_from_local.pth')
model = Model()
save_checkpoint(model, checkpoint_path)
checkpoint = load_from_local('~/dummy_checkpoint_used_to_test_load_fr... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.