code stringlengths 17 6.64M |
|---|
class TestSRDatasets():
@classmethod
def setup_class(cls):
cls.data_prefix = (Path(__file__).parent.parent.parent / 'data')
def test_base_super_resolution_dataset(self):
class ToyDataset(BaseSRDataset):
'Toy dataset for testing SRDataset.'
def __init__(self, pip... |
def test_reds_dataset():
root_path = (Path(__file__).parent.parent.parent / 'data')
txt_content = '000/00000001.png (720, 1280, 3)\n001/00000001.png (720, 1280, 3)\n250/00000001.png (720, 1280, 3)\n'
mocked_open_function = mock_open(read_data=txt_content)
with patch('builtins.open', mocked_open_functi... |
def test_vimeo90k_dataset():
root_path = (Path(__file__).parent.parent.parent / 'data')
txt_content = '00001/0266 (256, 448, 3)\n00002/0268 (256, 448, 3)\n'
mocked_open_function = mock_open(read_data=txt_content)
lq_paths_1 = [str((((root_path / '00001') / '0266') / f'im{v}.png')) for v in range(1, 8)... |
def test_vid4_dataset():
root_path = (Path(__file__).parent.parent.parent / 'data')
txt_content = 'calendar 1 (320,480,3)\ncity 2 (320,480,3)\n'
mocked_open_function = mock_open(read_data=txt_content)
with patch('builtins.open', mocked_open_function):
vid4_dataset = SRVid4Dataset(lq_folder=(ro... |
def test_sr_reds_multiple_gt_dataset():
root_path = (Path(__file__).parent.parent.parent / 'data')
reds_dataset = SRREDSMultipleGTDataset(lq_folder=root_path, gt_folder=root_path, num_input_frames=15, pipeline=[], scale=4, val_partition='official', test_mode=False)
assert (len(reds_dataset.data_infos) == ... |
def test_sr_vimeo90k_mutiple_gt_dataset():
root_path = ((Path(__file__).parent.parent.parent / 'data') / 'vimeo90k')
txt_content = '00001/0266 (256,448,3)\n'
mocked_open_function = mock_open(read_data=txt_content)
num_input_frames = 5
lq_paths = [str((((root_path / '00001') / '0266') / f'im{v}.png... |
def test_sr_test_multiple_gt_dataset():
root_path = ((Path(__file__).parent.parent.parent / 'data') / 'test_multiple_gt')
test_dataset = SRTestMultipleGTDataset(lq_folder=root_path, gt_folder=root_path, pipeline=[], scale=4, test_mode=True)
assert (test_dataset.data_infos == [dict(lq_path=str(root_path), ... |
def test_sr_folder_multiple_gt_dataset():
root_path = ((Path(__file__).parent.parent.parent / 'data') / 'test_multiple_gt')
test_dataset = SRFolderMultipleGTDataset(lq_folder=root_path, gt_folder=root_path, pipeline=[], scale=4, test_mode=True)
assert (test_dataset.data_infos == [dict(lq_path=str(root_pat... |
def test_sr_folder_video_dataset():
root_path = ((Path(__file__).parent.parent.parent / 'data') / 'test_multiple_gt')
test_dataset = SRFolderVideoDataset(lq_folder=root_path, gt_folder=root_path, num_input_frames=5, pipeline=[], scale=4, test_mode=True)
assert (test_dataset.data_infos == [dict(lq_path=str... |
class TestVFIDataset():
pipeline = [dict(type='LoadImageFromFileList', io_backend='disk', key='inputs'), dict(type='LoadImageFromFile', io_backend='disk', key='target'), dict(type='FramesToTensor', keys=['inputs']), dict(type='ImageToTensor', keys=['target'])]
folder = 'tests/data/vimeo90k'
ann_file = 'te... |
def test_vfi_dataset():
test_ = TestVFIDataset()
test_.test_base_vfi_dataset()
test_.test_vfi_vimeo90k_dataset()
|
def check_keys_equal(result_keys, target_keys):
'Check if all elements in target_keys is in result_keys.'
return (set(target_keys) == set(result_keys))
|
def test_compose():
with pytest.raises(TypeError):
Compose('LoadAlpha')
target_keys = ['img', 'meta']
img = np.random.randn(256, 256, 3)
results = dict(img=img, abandoned_key=None, img_name='test_image.png')
test_pipeline = [dict(type='Collect', keys=['img'], meta_keys=['img_name']), dict(... |
def check_keys_contain(result_keys, target_keys):
'Check if all elements in target_keys is in result_keys.'
return set(target_keys).issubset(set(result_keys))
|
def test_to_tensor():
to_tensor = ToTensor(['str'])
with pytest.raises(TypeError):
results = dict(str='0')
to_tensor(results)
target_keys = ['tensor', 'numpy', 'sequence', 'int', 'float']
to_tensor = ToTensor(target_keys)
ori_results = dict(tensor=torch.randn(2, 3), numpy=np.random... |
def test_image_to_tensor():
ori_results = dict(img=np.random.randn(256, 256, 3))
keys = ['img']
to_float32 = False
image_to_tensor = ImageToTensor(keys)
results = image_to_tensor(ori_results)
assert (results['img'].shape == torch.Size([3, 256, 256]))
assert isinstance(results['img'], torch... |
def test_frames_to_tensor():
with pytest.raises(TypeError):
ori_results = dict(img=np.random.randn(12, 12, 3))
FramesToTensor(['img'])(ori_results)
ori_results = dict(img=[np.random.randn(12, 12, 3), np.random.randn(12, 12, 3)])
keys = ['img']
frames_to_tensor = FramesToTensor(keys, to... |
def test_masked_img():
img = np.random.rand(4, 4, 1).astype(np.float32)
mask = np.zeros((4, 4, 1), dtype=np.float32)
mask[(1, 1)] = 1
results = dict(gt_img=img, mask=mask)
get_masked_img = GetMaskedImage()
results = get_masked_img(results)
masked_img = (img * (1.0 - mask))
assert np.ar... |
def test_format_trimap():
ori_trimap = np.random.randint(3, size=(64, 64))
ori_trimap[(ori_trimap == 1)] = 128
ori_trimap[(ori_trimap == 2)] = 255
from mmcv.parallel import DataContainer
ori_result = dict(trimap=torch.from_numpy(ori_trimap.copy()), meta=DataContainer({}))
format_trimap = Forma... |
def test_collect():
inputs = dict(img=np.random.randn(256, 256, 3), label=[1], img_name='test_image.png', ori_shape=(256, 256, 3), img_shape=(256, 256, 3), pad_shape=(256, 256, 3), flip_direction='vertical', img_norm_cfg=dict(to_bgr=False))
keys = ['img', 'label']
meta_keys = ['img_shape', 'img_name', 'or... |
def test_matlab_like_resize():
results = {}
results['lq'] = np.ones((16, 16, 3))
imresize = MATLABLikeResize(keys=['lq'], scale=0.25)
results = imresize(results)
assert (results['lq'].shape == (4, 4, 3))
results['lq'] = np.ones((16, 16, 3))
imresize = MATLABLikeResize(keys=['lq'], output_s... |
def test_adjust_gamma():
'Test Gamma Correction\n\n Adpted from\n # https://github.com/scikit-image/scikit-image/blob/7e4840bd9439d1dfb6beaf549998452c99f97fdd/skimage/exposure/tests/test_exposure.py#L534 # noqa\n '
img = np.ones([1, 1])
result = adjust_gamma(img, 1.5)
assert (img.shape == re... |
def test_make_coord():
(h, w) = (20, 30)
coord = make_coord((h, w), ranges=((10, 20), ((- 5), 5)))
assert (type(coord) == torch.Tensor)
assert (coord.shape == ((h * w), 2))
coord = make_coord((h, w), flatten=False)
assert (type(coord) == torch.Tensor)
assert (coord.shape == (h, w, 2))
|
def test_random_noise():
results = {}
results['lq'] = np.ones((8, 8, 3)).astype(np.float32)
model = RandomNoise(params=dict(noise_type=['gaussian'], noise_prob=[1], gaussian_sigma=[0, 50], gaussian_gray_noise_prob=1), keys=['lq'])
results = model(results)
assert (results['lq'].shape == (8, 8, 3))
... |
def test_random_jpeg_compression():
results = {}
results['lq'] = np.ones((8, 8, 3)).astype(np.float32)
model = RandomJPEGCompression(params=dict(quality=[5, 50]), keys=['lq'])
results = model(results)
assert (results['lq'].shape == (8, 8, 3))
params = dict(quality=[5, 50], prob=0)
model = ... |
def test_random_video_compression():
results = {}
results['lq'] = ([np.ones((8, 8, 3)).astype(np.float32)] * 5)
model = RandomVideoCompression(params=dict(codec=['libx264', 'h264', 'mpeg4'], codec_prob=[(1 / 3.0), (1 / 3.0), (1 / 3.0)], bitrate=[10000.0, 100000.0]), keys=['lq'])
results = model(result... |
def test_random_resize():
results = {}
results['lq'] = np.ones((8, 8, 3)).astype(np.float32)
model = RandomResize(params=dict(resize_mode_prob=[1, 0, 0], resize_scale=[0.5, 1.5], resize_opt=['bilinear', 'area', 'bicubic'], resize_prob=[(1 / 3.0), (1 / 3.0), (1 / 3.0)]), keys=['lq'])
results = model(re... |
def test_random_blur():
results = {}
results['lq'] = np.ones((8, 8, 3)).astype(np.float32)
model = RandomBlur(params=dict(kernel_size=[41], kernel_list=['iso'], kernel_prob=[1], sigma_x=[0.2, 10], sigma_y=[0.2, 10], rotate_angle=[(- 3.1416), 3.1416]), keys=['lq'])
results = model(results)
assert (... |
def test_degradations_with_shuffle():
results = {}
results['lq'] = np.ones((8, 8, 3)).astype(np.float32)
model = DegradationsWithShuffle(degradations=[dict(type='RandomBlur', params=dict(kernel_size=[15], kernel_list=['sinc'], kernel_prob=[1], sigma_x=[0.2, 10], sigma_y=[0.2, 10], rotate_angle=[(- 3.1416)... |
def test_random_down_sampling():
img1 = np.uint8((np.random.randn(480, 640, 3) * 255))
inputs1 = dict(gt=img1)
down_sampling1 = RandomDownSampling(scale_min=1, scale_max=4, patch_size=None)
results1 = down_sampling1(inputs1)
assert (set(list(results1.keys())) == set(['gt', 'lq', 'scale']))
ass... |
def test_restoration_video_inference():
if torch.cuda.is_available():
model = init_model('./configs/restorers/basicvsr/basicvsr_reds4.py', None, device='cuda')
img_dir = './tests/data/vimeo90k/00001/0266'
window_size = 0
start_idx = 1
filename_tmpl = 'im{}.png'
outp... |
def test_video_interpolation_inference():
model = init_model('./configs/video_interpolators/cain/cain_b5_320k_vimeo-triplet.py', None, device='cpu')
model.cfg['demo_pipeline'] = [dict(type='LoadImageFromFileList', io_backend='disk', key='inputs', channel_order='rgb'), dict(type='RescaleToZeroOne', keys=['inpu... |
def test_gl_encdec():
input_x = torch.randn(1, 4, 256, 256)
template_cfg = dict(type='AOTEncoderDecoder')
aot_encdec = build_backbone(template_cfg)
aot_encdec.init_weights()
output = aot_encdec(input_x)
assert (output.shape == (1, 3, 256, 256))
cfg_ = template_cfg.copy()
cfg_['encoder'... |
def test_aot_dilation_neck():
neck = AOTBlockNeck(in_channels=256, dilation_rates=(1, 2, 4, 8), num_aotblock=8)
x = torch.rand((2, 256, 64, 64))
res = neck(x)
assert (res.shape == (2, 256, 64, 64))
if torch.cuda.is_available():
neck = AOTBlockNeck(in_channels=256, dilation_rates=(1, 2, 4, ... |
def assert_tensor_with_shape(tensor, shape):
'"Check if the shape of the tensor is equal to the target shape.'
assert isinstance(tensor, torch.Tensor)
assert (tensor.shape == shape)
|
def _demo_inputs(input_shape=(1, 4, 64, 64)):
'\n Create a superset of inputs needed to run encoder.\n\n Args:\n input_shape (tuple): input batch dimensions.\n Default: (1, 4, 64, 64).\n '
img = np.random.random(input_shape).astype(np.float32)
img = torch.from_numpy(img)
ret... |
def test_plain_decoder():
'Test PlainDecoder.'
model = PlainDecoder(512)
model.init_weights()
model.train()
encoder = VGG16(4)
img = _demo_inputs()
outputs = encoder(img)
prediction = model(outputs)
assert_tensor_with_shape(prediction, torch.Size([1, 1, 64, 64]))
if torch.cuda.... |
def test_resnet_decoder():
'Test resnet decoder.'
with pytest.raises(NotImplementedError):
ResNetDec('UnknowBlock', [2, 3, 3, 2], 512)
model = ResNetDec('BasicBlockDec', [2, 3, 3, 2], 512, kernel_size=5)
model.init_weights()
model.train()
encoder = ResNetEnc('BasicBlock', [2, 4, 4, 2],... |
def test_res_shortcut_decoder():
'Test resnet decoder with shortcut.'
with pytest.raises(NotImplementedError):
ResShortcutDec('UnknowBlock', [2, 3, 3, 2], 512)
model = ResShortcutDec('BasicBlockDec', [2, 3, 3, 2], 512)
model.init_weights()
model.train()
encoder = ResShortcutEnc('BasicB... |
def test_res_gca_decoder():
'Test resnet decoder with shortcut and guided contextual attention.'
with pytest.raises(NotImplementedError):
ResGCADecoder('UnknowBlock', [2, 3, 3, 2], 512)
model = ResGCADecoder('BasicBlockDec', [2, 3, 3, 2], 512)
model.init_weights()
model.train()
encoder... |
def test_indexed_upsample():
'Test indexed upsample module for indexnet decoder.'
indexed_upsample = IndexedUpsample(12, 12)
x = torch.rand(2, 6, 32, 32)
shortcut = torch.rand(2, 6, 32, 32)
output = indexed_upsample(x, shortcut)
assert_tensor_with_shape(output, (2, 12, 32, 32))
x = torch.r... |
def test_indexnet_decoder():
'Test Indexnet decoder.'
with pytest.raises(AssertionError):
indexnet_decoder = IndexNetDecoder(160, kernel_size=5, separable_conv=False)
x = torch.rand(2, 256, 4, 4)
shortcut = torch.rand(2, 128, 8, 8, 8)
dec_idx_feat = torch.rand(2, 128, 8, 8, 8)
... |
def test_fba_decoder():
with pytest.raises(AssertionError):
FBADecoder(pool_scales=1, in_channels=32, channels=16)
inputs = dict()
conv_out_1 = _demo_inputs((1, 11, 320, 320))
conv_out_2 = _demo_inputs((1, 64, 160, 160))
conv_out_3 = _demo_inputs((1, 256, 80, 80))
conv_out_4 = _demo_in... |
def test_deepfill_dec():
decoder = DeepFillDecoder(128, out_act_cfg=None)
assert (not decoder.with_out_activation)
decoder = DeepFillDecoder(128)
x = torch.randn((2, 128, 64, 64))
input_dict = dict(out=x)
res = decoder(input_dict)
assert (res.shape == (2, 3, 256, 256))
assert (decoder.... |
def assert_dict_keys_equal(dictionary, target_keys):
'Check if the keys of the dictionary is equal to the target key set.'
assert isinstance(dictionary, dict)
assert (set(dictionary.keys()) == set(target_keys))
|
def assert_tensor_with_shape(tensor, shape):
'"Check if the shape of the tensor is equal to the target shape.'
assert isinstance(tensor, torch.Tensor)
assert (tensor.shape == shape)
|
def test_encoder_decoder():
'Test SimpleEncoderDecoder.'
encoder = dict(type='VGG16', in_channels=4)
decoder = dict(type='PlainDecoder')
model = SimpleEncoderDecoder(encoder, decoder)
model.init_weights()
model.train()
(fg, bg, merged, alpha, trimap) = _demo_inputs_pair()
prediction = ... |
def _demo_inputs_pair(img_shape=(64, 64), batch_size=1, cuda=False):
'\n Create a superset of inputs needed to run backbone.\n\n Args:\n img_shape (tuple): shape of the input image.\n batch_size (int): batch size of the input batch.\n cuda (bool): whether transfer input into gpu.\n '... |
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 is_block(modules):
'Check if is ResNet building block.'
if isinstance(modules, (BasicBlock, Bottleneck)):
return True
return False
|
def assert_tensor_with_shape(tensor, shape):
'"Check if the shape of the tensor is equal to the target shape.'
assert isinstance(tensor, torch.Tensor)
assert (tensor.shape == shape)
|
def assert_mid_feat_shape(mid_feat, target_shape):
assert (len(mid_feat) == 5)
for i in range(5):
assert_tensor_with_shape(mid_feat[i], torch.Size(target_shape[i]))
|
def _demo_inputs(input_shape=(2, 4, 64, 64)):
'\n Create a superset of inputs needed to run encoder.\n\n Args:\n input_shape (tuple): input batch dimensions.\n Default: (1, 4, 64, 64).\n '
img = np.random.random(input_shape).astype(np.float32)
img = torch.from_numpy(img)
ret... |
def test_vgg16_encoder():
'Test VGG16 encoder.'
target_shape = [(2, 64, 32, 32), (2, 128, 16, 16), (2, 256, 8, 8), (2, 512, 4, 4), (2, 512, 2, 2)]
model = VGG16(4)
model.init_weights()
model.train()
img = _demo_inputs()
outputs = model(img)
assert_tensor_with_shape(outputs['out'], (2, ... |
def test_resnet_encoder():
'Test resnet encoder.'
with pytest.raises(NotImplementedError):
ResNetEnc('UnknownBlock', [3, 4, 4, 2], 3)
with pytest.raises(TypeError):
model = ResNetEnc('BasicBlock', [3, 4, 4, 2], 3)
model.init_weights(list())
model = ResNetEnc('BasicBlock', [3, 4... |
def test_res_shortcut_encoder():
'Test resnet encoder with shortcut.'
with pytest.raises(NotImplementedError):
ResShortcutEnc('UnknownBlock', [3, 4, 4, 2], 3)
target_shape = [(2, 32, 64, 64), (2, 32, 32, 32), (2, 64, 16, 16), (2, 128, 8, 8), (2, 256, 4, 4)]
target_late_ds_shape = [(2, 32, 64, ... |
def test_res_gca_encoder():
'Test resnet encoder with shortcut and guided contextual attention.'
with pytest.raises(NotImplementedError):
ResGCAEncoder('UnknownBlock', [3, 4, 4, 2], 3)
target_shape = [(2, 32, 64, 64), (2, 32, 32, 32), (2, 64, 16, 16), (2, 128, 8, 8), (2, 256, 4, 4)]
target_lat... |
def test_index_blocks():
'Test index blocks for indexnet encoder.'
block = HolisticIndexBlock(128, use_context=False, use_nonlinear=False)
assert (not isinstance(block.index_block, Iterable))
x = torch.rand(2, 128, 8, 8)
(enc_idx_feat, dec_idx_feat) = block(x)
assert (enc_idx_feat.shape == (2,... |
def test_indexnet_encoder():
'Test Indexnet encoder.'
with pytest.raises(ValueError):
IndexNetEncoder(4, out_stride=8)
with pytest.raises(NameError):
IndexNetEncoder(4, index_mode='unknown_mode')
indexnet_encoder = IndexNetEncoder(4, out_stride=32, width_mult=1, index_mode='m2o', aspp=... |
def test_fba_encoder():
'Test FBA encoder.'
with pytest.raises(KeyError):
FBAResnetDilated(20, in_channels=11, stem_channels=64, base_channels=64)
with pytest.raises(AssertionError):
FBAResnetDilated(50, in_channels=11, stem_channels=64, base_channels=64, num_stages=0)
with pytest.rais... |
def test_gl_encdec():
input_x = torch.randn(1, 4, 256, 256)
template_cfg = dict(type='GLEncoderDecoder')
gl_encdec = build_backbone(template_cfg)
gl_encdec.init_weights()
output = gl_encdec(input_x)
assert (output.shape == (1, 3, 256, 256))
cfg_ = template_cfg.copy()
cfg_['decoder'] = ... |
def test_gl_dilation_neck():
neck = GLDilationNeck(in_channels=8)
x = torch.rand((2, 8, 64, 64))
res = neck(x)
assert (res.shape == (2, 8, 64, 64))
if torch.cuda.is_available():
neck = GLDilationNeck(in_channels=8).cuda()
x = torch.rand((2, 8, 64, 64)).cuda()
res = neck(x)
... |
def test_gl_discs():
global_disc_cfg = dict(in_channels=3, max_channels=512, fc_in_channels=((512 * 4) * 4), fc_out_channels=1024, num_convs=6, norm_cfg=dict(type='BN'))
local_disc_cfg = dict(in_channels=3, max_channels=512, fc_in_channels=((512 * 4) * 4), fc_out_channels=1024, num_convs=5, norm_cfg=dict(type... |
def test_unet_skip_connection_block():
_cfg = dict(outer_channels=1, inner_channels=1, in_channels=None, submodule=None, is_outermost=False, is_innermost=False, norm_cfg=dict(type='BN'), use_dropout=True)
feature_shape = (1, 1, 8, 8)
feature = _demo_inputs(feature_shape)
input_shape = (1, 3, 8, 8)
... |
def test_unet_generator():
cfg = dict(type='UnetGenerator', in_channels=3, out_channels=3, num_down=8, base_channels=64, norm_cfg=dict(type='BN'), use_dropout=True, init_cfg=dict(type='normal', gain=0.02))
net = build_backbone(cfg)
net.init_weights(pretrained=None)
input_shape = (1, 3, 256, 256)
i... |
def test_residual_block_with_dropout():
_cfg = dict(channels=3, padding_mode='reflect', norm_cfg=dict(type='BN'), use_dropout=True)
feature_shape = (1, 3, 32, 32)
feature = _demo_inputs(feature_shape)
block = ResidualBlockWithDropout(**_cfg)
output = block(feature)
assert (output.shape == (1, ... |
def test_resnet_generator():
cfg = dict(type='ResnetGenerator', in_channels=3, out_channels=3, base_channels=64, norm_cfg=dict(type='IN'), use_dropout=False, num_blocks=9, padding_mode='reflect', init_cfg=dict(type='normal', gain=0.02))
net = build_backbone(cfg)
net.init_weights(pretrained=None)
input... |
def _demo_inputs(input_shape=(1, 3, 64, 64)):
'Create a superset of inputs needed to run backbone.\n\n Args:\n input_shape (tuple): input batch dimensions.\n Default: (1, 3, 64, 64).\n\n Returns:\n imgs: (Tensor): Images in FloatTensor with desired shapes.\n '
imgs = np.rando... |
def test_basicvsr_net():
'Test BasicVSR.'
basicvsr = BasicVSRNet(mid_channels=64, num_blocks=30, spynet_pretrained=None)
input_tensor = torch.rand(1, 5, 3, 64, 64)
basicvsr.init_weights(pretrained=None)
output = basicvsr(input_tensor)
assert (output.shape == (1, 5, 3, 256, 256))
if torch.c... |
def test_basicvsr_plusplus():
'Test BasicVSR++.'
model = BasicVSRPlusPlus(mid_channels=64, num_blocks=7, is_low_res_input=True, spynet_pretrained=None, cpu_cache_length=100)
input_tensor = torch.rand(1, 5, 3, 64, 64)
model.init_weights(pretrained=None)
output = model(input_tensor)
assert (outp... |
def test_feedback_block():
x1 = torch.rand(2, 16, 32, 32)
model = FeedbackBlock(16, 3, 8)
x2 = model(x1)
assert (x2.shape == x1.shape)
x3 = model(x2)
assert (x3.shape == x2.shape)
|
def test_feedback_block_custom():
x1 = torch.rand(2, 3, 32, 32)
model = FeedbackBlockCustom(3, 16, 3, 8)
x2 = model(x1)
assert (x2.shape == (2, 16, 32, 32))
|
def test_feedback_block_heatmap_attention():
x1 = torch.rand(2, 16, 32, 32)
heatmap = torch.rand(2, 5, 32, 32)
model = FeedbackBlockHeatmapAttention(16, 2, 8, 5, 2)
x2 = model(x1, heatmap)
assert (x2.shape == x1.shape)
x3 = model(x2, heatmap)
assert (x3.shape == x2.shape)
|
def test_dic_net():
model_cfg = dict(type='DICNet', in_channels=3, out_channels=3, mid_channels=48, num_blocks=6, hg_mid_channels=256, hg_num_keypoints=68, num_steps=4, upscale_factor=8, detach_attention=False)
model = build_backbone(model_cfg)
assert (model.__class__.__name__ == 'DICNet')
inputs = to... |
def test_dynamic_upsampling_filter():
'Test DynamicUpsamplingFilter.'
with pytest.raises(TypeError):
DynamicUpsamplingFilter(filter_size=3)
with pytest.raises(ValueError):
DynamicUpsamplingFilter(filter_size=(3, 3, 3))
duf = DynamicUpsamplingFilter(filter_size=(5, 5))
x = torch.ran... |
def test_pcd_alignment():
'Test PCDAlignment.'
pcd_alignment = PCDAlignment(mid_channels=4, deform_groups=2)
input_list = []
for i in range(3, 0, (- 1)):
input_list.append(torch.rand(1, 4, (2 ** i), (2 ** i)))
pcd_alignment = pcd_alignment
input_list = [v for v in input_list]
outpu... |
def test_tsa_fusion():
'Test TSAFusion.'
tsa_fusion = TSAFusion(mid_channels=4, num_frames=5, center_frame_idx=2)
input_tensor = torch.rand(1, 5, 4, 8, 8)
output = tsa_fusion(input_tensor)
assert (output.shape == (1, 4, 8, 8))
if torch.cuda.is_available():
tsa_fusion = tsa_fusion.cuda(... |
def test_edvrnet():
'Test EDVRNet.'
edvrnet = EDVRNet(3, 3, mid_channels=8, num_frames=5, deform_groups=2, num_blocks_extraction=1, num_blocks_reconstruction=1, center_frame_idx=2, with_tsa=True)
input_tensor = torch.rand(1, 5, 3, 8, 8)
edvrnet.init_weights(pretrained=None)
output = edvrnet(input_... |
class TestGLEANNet():
@classmethod
def setup_class(cls):
cls.default_cfg = dict(in_size=16, out_size=256, style_channels=512)
cls.size_cfg = dict(in_size=16, out_size=16, style_channels=512)
def test_glean_styleganv2_cpu(self):
glean = GLEANStyleGANv2(**self.default_cfg)
... |
def test_iconvsr():
'Test IconVSR.'
if torch.cuda.is_available():
iconvsr = IconVSR(mid_channels=64, num_blocks=30, keyframe_stride=5, padding=2, spynet_pretrained=None, edvr_pretrained=None).cuda()
input_tensor = torch.rand(1, 5, 3, 64, 64).cuda()
iconvsr.init_weights(pretrained=None)... |
def test_liif_edsr():
model_cfg = dict(type='LIIFEDSR', encoder=dict(type='EDSR', in_channels=3, out_channels=3, mid_channels=64, num_blocks=16), imnet=dict(type='MLPRefiner', in_dim=64, out_dim=3, hidden_list=[256, 256, 256, 256]), local_ensemble=True, feat_unfold=True, cell_decode=True, eval_bsize=30000)
mo... |
def test_liif_rdn():
model_cfg = dict(type='LIIFRDN', encoder=dict(type='RDN', in_channels=3, out_channels=3, mid_channels=64, num_blocks=16, upscale_factor=4, num_layers=8, channel_growth=64), imnet=dict(type='MLPRefiner', in_dim=64, out_dim=3, hidden_list=[256, 256, 256, 256]), local_ensemble=True, feat_unfold=... |
def test_rdn():
scale = 4
model_cfg = dict(type='RDN', in_channels=3, out_channels=3, mid_channels=64, num_blocks=16, upscale_factor=scale)
model = build_backbone(model_cfg)
assert (model.__class__.__name__ == 'RDN')
inputs = torch.rand(1, 3, 32, 16)
targets = torch.rand(1, 3, 128, 64)
los... |
def test_real_basicvsr_net():
'Test RealBasicVSR.'
real_basicvsr = RealBasicVSRNet(is_fix_cleaning=False)
real_basicvsr = RealBasicVSRNet(is_fix_cleaning=True, is_sequential_cleaning=False)
input_tensor = torch.rand(1, 5, 3, 64, 64)
real_basicvsr.init_weights(pretrained=None)
output = real_bas... |
def test_srresnet_backbone():
'Test SRResNet backbone.'
MSRResNet(in_channels=3, out_channels=3, mid_channels=8, num_blocks=2, upscale_factor=2)
net = MSRResNet(in_channels=3, out_channels=3, mid_channels=8, num_blocks=2, upscale_factor=3)
net.init_weights(pretrained=None)
input_shape = (1, 3, 12,... |
def test_edsr():
'Test EDSR.'
EDSR(in_channels=3, out_channels=3, mid_channels=8, num_blocks=2, upscale_factor=2)
net = EDSR(in_channels=3, out_channels=3, mid_channels=8, num_blocks=2, upscale_factor=3)
net.init_weights(pretrained=None)
input_shape = (1, 3, 12, 12)
img = _demo_inputs(input_sh... |
def test_discriminator():
'Test discriminator backbone.'
net = ModifiedVGG(in_channels=3, mid_channels=64)
net.init_weights(pretrained=None)
input_shape = (1, 3, 128, 128)
img = _demo_inputs(input_shape)
output = net(img)
assert (output.shape == (1, 1))
if torch.cuda.is_available():
... |
def test_rrdbnet_backbone():
'Test RRDBNet backbone.'
net = RRDBNet(in_channels=3, out_channels=3, mid_channels=8, num_blocks=2, growth_channels=4, upscale_factor=4)
net.init_weights(pretrained=None)
input_shape = (1, 3, 12, 12)
img = _demo_inputs(input_shape)
output = net(img)
assert (out... |
def test_srcnn():
net = SRCNN(channels=(3, 4, 6, 3), kernel_sizes=(9, 1, 5), upscale_factor=4)
net.init_weights(pretrained=None)
input_shape = (1, 3, 4, 4)
img = _demo_inputs(input_shape)
output = net(img)
assert (output.shape == (1, 3, 16, 16))
net = SRCNN(channels=(1, 4, 8, 1), kernel_si... |
def _demo_inputs(input_shape=(1, 3, 64, 64)):
'Create a superset of inputs needed to run backbone.\n\n Args:\n input_shape (tuple): input batch dimensions.\n Default: (1, 3, 64, 64).\n\n Returns:\n imgs: (Tensor): Images in FloatTensor with desired shapes.\n '
imgs = np.rando... |
def test_tdan_net():
'Test TDANNet.'
if torch.cuda.is_available():
tdan = TDANNet().cuda()
input_tensor = torch.rand(1, 5, 3, 64, 64).cuda()
tdan.init_weights(pretrained=None)
output = tdan(input_tensor)
assert (len(output) == 2)
assert (output[0].shape == (1, 3... |
def test_tof():
'Test TOFlow.'
tof = TOFlow(adapt_official_weights=True)
input_tensor = torch.rand(1, 7, 3, 32, 32)
tof.init_weights(pretrained=None)
output = tof(input_tensor)
assert (output.shape == (1, 3, 32, 32))
tof = TOFlow(adapt_official_weights=False)
tof.init_weights(pretraine... |
def test_tof_vfi_net():
model_cfg = dict(type='TOFlowVFINet')
model = build_backbone(model_cfg)
assert (model.__class__.__name__ == 'TOFlowVFINet')
inputs = torch.rand(1, 2, 3, 256, 248)
output = model(inputs)
assert torch.is_tensor(output)
assert (output.shape == (1, 3, 256, 248))
if ... |
class TestBaseModel(unittest.TestCase):
@patch.multiple(BaseModel, __abstractmethods__=set())
def test_parse_losses(self):
self.base_model = BaseModel()
with pytest.raises(TypeError):
losses = dict(loss=0.5)
self.base_model.parse_losses(losses)
a_loss = [torch.... |
def test_ensemble_cpu():
model = nn.Identity()
ensemble = SpatialTemporalEnsemble(is_temporal_ensemble=False)
inputs = torch.rand(1, 3, 4, 4)
outputs = ensemble(inputs, model)
np.testing.assert_almost_equal(inputs.numpy(), outputs.numpy())
ensemble = SpatialTemporalEnsemble(is_temporal_ensembl... |
def test_ensemble_cuda():
if torch.cuda.is_available():
model = nn.Identity().cuda()
ensemble = SpatialTemporalEnsemble(is_temporal_ensemble=False)
inputs = torch.rand(1, 3, 4, 4).cuda()
outputs = ensemble(inputs, model)
np.testing.assert_almost_equal(inputs.cpu().numpy(), ... |
def test_normalize_layer():
rgb_mean = (1, 2, 3)
rgb_std = (1, 0.5, 0.25)
layer = ImgNormalize(1, rgb_mean, rgb_std)
x = torch.randn((2, 3, 64, 64))
y = layer(x)
x = x.permute((1, 0, 2, 3)).reshape((3, (- 1)))
y = y.permute((1, 0, 2, 3)).reshape((3, (- 1)))
rgb_mean = torch.tensor(rgb_... |
def test_pixel_shuffle():
model = PixelShufflePack(3, 3, 2, 3)
model.init_weights()
x = torch.rand(1, 3, 16, 16)
y = model(x)
assert (y.shape == (1, 3, 32, 32))
if torch.cuda.is_available():
model = model.cuda()
x = x.cuda()
y = model(x)
assert (y.shape == (1, 3... |
def test_pixel_unshuffle():
x = torch.rand(1, 3, 20, 20)
y = pixel_unshuffle(x, scale=2)
assert (y.shape == (1, 12, 10, 10))
with pytest.raises(AssertionError):
y = pixel_unshuffle(x, scale=3)
if torch.cuda.is_available():
x = x.cuda()
y = pixel_unshuffle(x, scale=2)
... |
def test_deepfillv1_disc():
model_config = dict(global_disc_cfg=dict(type='MultiLayerDiscriminator', in_channels=3, max_channels=256, fc_in_channels=((256 * 16) * 16), fc_out_channels=1, num_convs=4, norm_cfg=None, act_cfg=dict(type='ELU'), out_act_cfg=dict(type='LeakyReLU', negative_slope=0.2)), local_disc_cfg=d... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.